SpyBara
Go Premium

Documentation 2026-05-02 18:14 UTC to 2026-05-04 22:58 UTC

99 files changed +47,136 −0. View all changes and history on the product overview
2026
Tue 19 06:34 Mon 18 23:59 Sun 17 01:01 Fri 15 22:58 Thu 14 17:02 Wed 13 23:01 Tue 12 22:57 Mon 11 23:00 Sun 10 23:03 Sat 9 04:57 Fri 8 22:00 Thu 7 22:59 Tue 5 23:00 Mon 4 22:58

admin-setup.md +130 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 為您的組織設定 Claude Code

6 

7> 管理員部署 Claude Code 的決策地圖,涵蓋 API 提供者、受管設定、政策執行、使用情況監控和資料處理。

8 

9Claude Code 透過受管設定來執行組織政策,這些設定優先於本地開發人員配置。您可以從 Claude 管理員控制台、行動裝置管理 (MDM) 系統或磁碟上的檔案傳遞這些設定。這些設定控制 Claude 可以存取的工具、命令、伺服器和網路目的地。

10 

11本頁按順序介紹部署決策。每一行都連結到下面的部分和該區域的參考頁面。

12 

13<Note>

14 SSO、SCIM 佈建和座位分配在 Claude 帳戶級別進行配置。有關這些步驟,請參閱 [Claude 企業管理員指南](https://claude.com/resources/tutorials/claude-enterprise-administrator-guide) 和 [座位分配](https://support.claude.com/en/articles/11845131-use-claude-code-with-your-team-or-enterprise-plan)。

15</Note>

16 

17| 決策 | 您正在選擇什麼 | 參考 |

18| :----------------------------------------------- | :---------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------ |

19| [選擇您的 API 提供者](#choose-your-api-provider) | Claude Code 驗證的位置以及如何計費 | [Authentication](/zh-TW/authentication)、[Bedrock](/zh-TW/amazon-bedrock)、[Vertex AI](/zh-TW/google-vertex-ai)、[Foundry](/zh-TW/microsoft-foundry) |

20| [決定設定如何到達裝置](#decide-how-settings-reach-devices) | 受管政策如何到達開發人員機器 | [Server-managed settings](/zh-TW/server-managed-settings)、[Settings files](/zh-TW/settings#settings-files) |

21| [決定要執行什麼](#decide-what-to-enforce) | 允許哪些工具、命令和整合 | [Permissions](/zh-TW/permissions)、[Sandboxing](/zh-TW/sandboxing) |

22| [設定使用情況可見性](#set-up-usage-visibility) | 您如何追蹤支出和採用情況 | [Analytics](/zh-TW/analytics)、[Monitoring](/zh-TW/monitoring-usage)、[Costs](/zh-TW/costs) |

23| [檢查資料處理](#review-data-handling) | 資料保留和合規狀況 | [Data usage](/zh-TW/data-usage)、[Security](/zh-TW/security) |

24 

25## 選擇您的 API 提供者

26 

27Claude Code 透過多個 API 提供者之一連接到 Claude。您的選擇會影響計費、驗證和您繼承的合規狀況。

28 

29| 提供者 | 在以下情況下選擇此選項 |

30| :---------------------------- | :----------------------------------------------------- |

31| Claude for Teams / Enterprise | 您希望 Claude Code 和 claude.ai 在一個按座位訂閱下,無需執行基礎設施。這是預設建議。 |

32| Claude Console | 您是 API 優先或希望按使用量付費計費 |

33| Amazon Bedrock | 您希望繼承現有的 AWS 合規控制和計費 |

34| Google Vertex AI | 您希望繼承現有的 GCP 合規控制和計費 |

35| Microsoft Foundry | 您希望繼承現有的 Azure 合規控制和計費 |

36 

37有關涵蓋驗證、區域和功能奇偶性的完整提供者比較,請參閱 [企業部署概述](/zh-TW/third-party-integrations)。每個提供者的驗證設定位於 [Authentication](/zh-TW/authentication)。

38 

39無論提供者如何,[網路配置](/zh-TW/network-config) 中的代理和防火牆要求都適用。如果您想要在多個提供者前面有單一端點或集中式請求日誌記錄,請參閱 [LLM gateway](/zh-TW/llm-gateway)。

40 

41## 決定設定如何到達裝置

42 

43受管設定定義優先於本地開發人員配置的政策。Claude Code 在四個位置尋找它們,並使用在給定裝置上找到的第一個。

44 

45| 機制 | 傳遞 | 優先級 | 平台 |

46| :---------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-- | :------------ |

47| Server-managed | Claude.ai 管理員控制台 | 最高 | 全部 |

48| plist / registry policy | macOS:`com.anthropic.claudecode` plist<br />Windows:`HKLM\SOFTWARE\Policies\ClaudeCode` | 高 | macOS、Windows |

49| File-based managed | macOS:`/Library/Application Support/ClaudeCode/managed-settings.json`<br />Linux 和 WSL:`/etc/claude-code/managed-settings.json`<br />Windows:`C:\Program Files\ClaudeCode\managed-settings.json` | 中 | 全部 |

50| Windows user registry | `HKCU\SOFTWARE\Policies\ClaudeCode` | 最低 | 僅 Windows |

51 

52Server-managed 設定在驗證時到達裝置,並在活動會話期間每小時刷新一次,無需端點基礎設施。它們需要 Claude for Teams 或 Enterprise 計畫,因此在其他提供者上的部署需要改用基於檔案或作業系統級別的機制之一。

53 

54如果您的組織混合使用提供者,請為 Claude.ai 使用者配置 [server-managed settings](/zh-TW/server-managed-settings) 加上 [基於檔案或 plist/registry 備用](/zh-TW/settings#settings-files),以便其他使用者仍然接收受管政策。

55 

56plist 和 HKLM 登錄位置適用於任何提供者,並且由於需要管理員權限才能寫入,因此可以抵抗篡改。Windows 使用者登錄中的 HKCU 無需提升即可寫入,因此將其視為便利預設值而不是執行通道。

57 

58無論您選擇哪種機制,受管值都優先於使用者和專案設定。陣列設定(例如 `permissions.allow` 和 `permissions.deny`)會合併來自所有來源的項目,因此開發人員可以擴展受管清單但無法從中移除。

59 

60請參閱 [Server-managed settings](/zh-TW/server-managed-settings) 和 [Settings files and precedence](/zh-TW/settings#settings-files)。

61 

62## 決定要執行什麼

63 

64受管設定可以鎖定工具、沙箱執行、限制 MCP 伺服器和外掛程式來源,以及控制哪些 hooks 執行。每一行都是一個控制表面,具有驅動它的設定鍵。

65 

66| 控制 | 它的作用 | 關鍵設定 |

67| :---------------------------------------------------------------------------------------- | :-------------------------------------------- | :--------------------------------------------------------------------------- |

68| [Permission rules](/zh-TW/permissions) | 允許、詢問或拒絕特定工具和命令 | `permissions.allow`、`permissions.deny` |

69| [Permission lockdown](/zh-TW/permissions#managed-only-settings) | 僅受管權限規則適用;禁用 `--dangerously-skip-permissions` | `allowManagedPermissionRulesOnly`、`permissions.disableBypassPermissionsMode` |

70| [Sandboxing](/zh-TW/sandboxing) | 作業系統級別的檔案系統和網路隔離,具有網域允許清單 | `sandbox.enabled`、`sandbox.network.allowedDomains` |

71| [Managed policy CLAUDE.md](/zh-TW/memory#deploy-organization-wide-claude-md) | 在每個會話中載入的組織範圍指令,無法排除 | 受管政策路徑中的檔案 |

72| [MCP server control](/zh-TW/mcp#managed-mcp-configuration) | 限制使用者可以新增或連接的 MCP 伺服器 | `allowedMcpServers`、`deniedMcpServers`、`allowManagedMcpServersOnly` |

73| [Plugin marketplace control](/zh-TW/plugin-marketplaces#managed-marketplace-restrictions) | 限制使用者可以新增和安裝的市場來源 | `strictKnownMarketplaces`、`blockedMarketplaces` |

74| [Hook restrictions](/zh-TW/settings#hook-configuration) | 僅受管 hooks 載入;限制 HTTP hook URL | `allowManagedHooksOnly`、`allowedHttpHookUrls` |

75| [Version floor](/zh-TW/settings) | 防止自動更新安裝低於組織範圍最小值的版本 | `minimumVersion` |

76 

77權限規則和沙箱涵蓋不同的層。拒絕 WebFetch 會阻止 Claude 的 fetch 工具,但如果允許 Bash,`curl` 和 `wget` 仍然可以到達任何 URL。沙箱透過在作業系統級別執行的網路網域允許清單來彌補這一差距。

78 

79有關這些控制防禦的威脅模型,請參閱 [Security](/zh-TW/security)。

80 

81## 設定使用情況可見性

82 

83根據您需要報告的內容選擇監控。

84 

85| 功能 | 您獲得什麼 | 可用性 | 從哪裡開始 |

86| :------------------ | :------------------------- | :---------- | :------------------------------------------ |

87| Usage monitoring | 會話、工具和令牌的 OpenTelemetry 匯出 | 所有提供者 | [Monitoring usage](/zh-TW/monitoring-usage) |

88| Analytics dashboard | 每個使用者的指標、貢獻追蹤、排行榜 | 僅 Anthropic | [Analytics](/zh-TW/analytics) |

89| Cost tracking | 支出限制、速率限制和使用情況歸因 | 僅 Anthropic | [Costs](/zh-TW/costs) |

90 

91雲端提供者透過 AWS Cost Explorer、GCP Billing 或 Azure Cost Management 公開支出。Claude for Teams 和 Enterprise 計畫在 [claude.ai/analytics/claude-code](https://claude.ai/analytics/claude-code) 包含使用情況儀表板。

92 

93## 檢查資料處理

94 

95在 Team、Enterprise、Claude API 和雲端提供者計畫上,Anthropic 不會在您的程式碼或提示上訓練模型。您的 API 提供者決定保留和合規狀況。

96 

97| 主題 | 需要了解的內容 | 從哪裡開始 |

98| :------------------------ | :--------------------------------------- | :------------------------------------------------ |

99| Data usage policy | Anthropic 收集什麼、保留多長時間、永遠不會用於訓練的內容 | [Data usage](/zh-TW/data-usage) |

100| Zero Data Retention (ZDR) | 請求完成後不存儲任何內容。在 Claude for Enterprise 上可用 | [Zero data retention](/zh-TW/zero-data-retention) |

101| Security architecture | 網路模型、加密、驗證、稽核追蹤 | [Security](/zh-TW/security) |

102 

103如果您需要請求級別的稽核日誌記錄或按資料敏感性路由流量,請在開發人員和您的提供者之間放置 [LLM gateway](/zh-TW/llm-gateway)。有關法規要求和認證,請參閱 [Legal and compliance](/zh-TW/legal-and-compliance)。

104 

105## 驗證和上線

106 

107配置受管設定後,讓開發人員在 Claude Code 內執行 `/status`。輸出包括以 `Enterprise managed settings` 開頭的一行,後面是括號中的來源,其中之一為 `(remote)`、`(plist)`、`(HKLM)`、`(HKCU)` 或 `(file)`。請參閱 [驗證作用中的設定](/zh-TW/settings#verify-active-settings)。

108 

109分享這些資源以幫助開發人員入門:

110 

111* [快速入門](/zh-TW/quickstart):從安裝到使用專案的首次會話逐步說明

112* [常見工作流程](/zh-TW/common-workflows):日常任務的模式,例如程式碼審查、重構和除錯

113* [Claude 101](https://anthropic.skilljar.com/claude-101) 和 [Claude Code in Action](https://anthropic.skilljar.com/claude-code-in-action):自進度 Anthropic Academy 課程

114 

115對於登入問題,請將開發人員指向 [驗證疑難排解](/zh-TW/troubleshoot-install#login-and-authentication)。最常見的修復是:

116 

117* 執行 `/logout` 然後 `/login` 以切換帳戶

118* 如果缺少企業驗證選項,執行 `claude update`

119* 更新後重新啟動終端

120 

121如果開發人員看到「您尚未被新增到您的組織」,他們的座位不包括 Claude Code 存取權限,需要在管理員控制台中更新。

122 

123## 後續步驟

124 

125選擇提供者和傳遞機制後,繼續進行詳細配置:

126 

127* [Server-managed settings](/zh-TW/server-managed-settings):從 Claude 管理員控制台傳遞受管政策

128* [Settings reference](/zh-TW/settings):每個設定鍵、檔案位置和優先級規則

129* [Amazon Bedrock](/zh-TW/amazon-bedrock)、[Google Vertex AI](/zh-TW/google-vertex-ai)、[Microsoft Foundry](/zh-TW/microsoft-foundry):提供者特定部署

130* [Claude 企業管理員指南](https://claude.com/resources/tutorials/claude-enterprise-administrator-guide):SSO、SCIM、座位管理和推出劇本

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 在 SDK 中使用 Claude Code 功能

6 

7> 將專案指令、skills、hooks 和其他 Claude Code 功能載入到您的 SDK 代理中。

8 

9Agent SDK 建立在與 Claude Code 相同的基礎上,這意味著您的 SDK 代理可以存取相同的基於檔案系統的功能:專案指令(`CLAUDE.md` 和規則)、skills、hooks 等。

10 

11當您省略 `settingSources` 時,`query()` 會讀取與 Claude Code CLI 相同的檔案系統設定:使用者、專案和本機設定、CLAUDE.md 檔案以及 `.claude/` skills、代理和命令。若要在沒有這些的情況下執行,請傳遞 `settingSources: []`,這會將代理限制為您以程式設計方式設定的內容。無論此選項如何,都會讀取受管原則設定和全域 `~/.claude.json` 設定。請參閱 [settingSources 不控制的內容](#what-settingsources-does-not-control)。

12 

13如需每項功能的概念概述及何時使用,請參閱 [擴展 Claude Code](/zh-TW/features-overview)。

14 

15## 使用 settingSources 控制檔案系統設定

16 

17設定來源選項(Python 中的 [`setting_sources`](/zh-TW/agent-sdk/python#claude-agent-options)、TypeScript 中的 [`settingSources`](/zh-TW/agent-sdk/typescript#setting-source))控制 SDK 載入哪些基於檔案系統的設定。傳遞明確清單以選擇加入特定來源,或傳遞空陣列以停用使用者、專案和本機設定。

18 

19此範例透過將 `settingSources` 設定為 `["user", "project"]` 來載入使用者層級和專案層級設定:

20 

21<CodeGroup>

22 ```python Python theme={null}

23 from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage

24 

25 async for message in query(

26 prompt="Help me refactor the auth module",

27 options=ClaudeAgentOptions(

28 # "user" loads from ~/.claude/, "project" loads from ./.claude/ in cwd.

29 # Together they give the agent access to CLAUDE.md, skills, hooks, and

30 # permissions from both locations.

31 setting_sources=["user", "project"],

32 allowed_tools=["Read", "Edit", "Bash"],

33 ),

34 ):

35 if isinstance(message, AssistantMessage):

36 for block in message.content:

37 if hasattr(block, "text"):

38 print(block.text)

39 if isinstance(message, ResultMessage) and message.subtype == "success":

40 print(f"\nResult: {message.result}")

41 ```

42 

43 ```typescript TypeScript theme={null}

44 import { query } from "@anthropic-ai/claude-agent-sdk";

45 

46 for await (const message of query({

47 prompt: "Help me refactor the auth module",

48 options: {

49 // "user" loads from ~/.claude/, "project" loads from ./.claude/ in cwd.

50 // Together they give the agent access to CLAUDE.md, skills, hooks, and

51 // permissions from both locations.

52 settingSources: ["user", "project"],

53 allowedTools: ["Read", "Edit", "Bash"]

54 }

55 })) {

56 if (message.type === "assistant") {

57 for (const block of message.message.content) {

58 if (block.type === "text") console.log(block.text);

59 }

60 }

61 if (message.type === "result" && message.subtype === "success") {

62 console.log(`\nResult: ${message.result}`);

63 }

64 }

65 ```

66</CodeGroup>

67 

68每個來源都會從特定位置載入設定,其中 `<cwd>` 是您透過 `cwd` 選項傳遞的工作目錄(如果未設定,則為程序的目前目錄)。如需完整的型別定義,請參閱 [`SettingSource`](/zh-TW/agent-sdk/typescript#setting-source)(TypeScript)或 [`SettingSource`](/zh-TW/agent-sdk/python#setting-source)(Python)。

69 

70| 來源 | 載入的內容 | 位置 |

71| :---------- | :---------------------------------------------------------------------- | :------------------------------------------------------------ |

72| `"project"` | 專案 CLAUDE.md、`.claude/rules/*.md`、專案 skills、專案 hooks、專案 `settings.json` | `<cwd>/.claude/` 以及每個父目錄直到檔案系統根目錄(當找到 `.claude/` 或沒有更多父目錄時停止) |

73| `"user"` | 使用者 CLAUDE.md、`~/.claude/rules/*.md`、使用者 skills、使用者設定 | `~/.claude/` |

74| `"local"` | CLAUDE.local.md(gitignored)、`.claude/settings.local.json` | `<cwd>/` |

75 

76省略 `settingSources` 等同於 `["user", "project", "local"]`。

77 

78`cwd` 選項決定 SDK 在何處尋找專案設定。如果 `cwd` 及其任何父目錄都不包含 `.claude/` 資料夾,則專案層級功能將不會載入。

79 

80### settingSources 不控制的內容

81 

82`settingSources` 涵蓋使用者、專案和本機設定。無論其值如何,都會讀取一些輸入:

83 

84| 輸入 | 行為 | 停用方式 |

85| :-------------------------------------------- | :--------- | :--------------------------------------------------------------------------------- |

86| 受管原則設定 | 主機上存在時始終載入 | 移除受管設定檔 |

87| `~/.claude.json` 全域設定 | 始終讀取 | 在 `env` 中使用 `CLAUDE_CONFIG_DIR` 重新定位 |

88| `~/.claude/projects/<project>/memory/` 的自動記憶體 | 預設載入到系統提示中 | 在設定中設定 `autoMemoryEnabled: false`,或在 `env` 中設定 `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` |

89 

90<Warning>

91 不要依賴預設 `query()` 選項進行多租戶隔離。因為上述輸入無論 `settingSources` 如何都會被讀取,SDK 程序可能會拾取主機層級設定和每個目錄的記憶體。對於多租戶部署,在其自己的檔案系統中執行每個租戶,並在 `env` 中設定 `settingSources: []` 加上 `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1`。請參閱 [安全部署](/zh-TW/agent-sdk/secure-deployment)。

92</Warning>

93 

94## 專案指令(CLAUDE.md 和規則)

95 

96`CLAUDE.md` 檔案和 `.claude/rules/*.md` 檔案為您的代理提供有關您的專案的持久上下文:編碼慣例、建置命令、架構決策和指令。當 `settingSources` 包含 `"project"`(如上面的範例所示)時,SDK 在工作階段開始時將這些檔案載入到上下文中。代理隨後會遵循您的專案慣例,而無需在每個提示中重複它們。

97 

98### CLAUDE.md 載入位置

99 

100| 層級 | 位置 | 何時載入 |

101| :------------- | :-------------------------------------------- | :------------------------------------------------ |

102| 專案(根目錄) | `<cwd>/CLAUDE.md` 或 `<cwd>/.claude/CLAUDE.md` | `settingSources` 包含 `"project"` |

103| 專案規則 | `<cwd>/.claude/rules/*.md` | `settingSources` 包含 `"project"` |

104| 專案(父目錄) | `cwd` 上方目錄中的 `CLAUDE.md` 檔案 | `settingSources` 包含 `"project"`,在工作階段開始時載入 |

105| 專案(子目錄) | `cwd` 子目錄中的 `CLAUDE.md` 檔案 | `settingSources` 包含 `"project"`,當代理讀取該子樹中的檔案時按需載入 |

106| 本機(gitignored) | `<cwd>/CLAUDE.local.md` | `settingSources` 包含 `"local"` |

107| 使用者 | `~/.claude/CLAUDE.md` | `settingSources` 包含 `"user"` |

108| 使用者規則 | `~/.claude/rules/*.md` | `settingSources` 包含 `"user"` |

109 

110所有層級都是累加的:如果專案和使用者 CLAUDE.md 檔案都存在,代理會看到兩者。層級之間沒有硬性優先順序規則;如果指令衝突,結果取決於 Claude 如何解釋它們。編寫不衝突的規則,或在更具體的檔案中明確說明優先順序(「這些專案指令會覆蓋任何衝突的使用者層級預設值」)。

111 

112<Tip>

113 您也可以透過 `systemPrompt` 直接注入上下文,而無需使用 CLAUDE.md 檔案。請參閱 [修改系統提示](/zh-TW/agent-sdk/modifying-system-prompts)。當您想要在互動式 Claude Code 工作階段和 SDK 代理之間共享相同上下文時,請使用 CLAUDE.md。

114</Tip>

115 

116如需如何結構化和組織 CLAUDE.md 內容的資訊,請參閱 [管理 Claude 的記憶體](/zh-TW/memory)。

117 

118## Skills

119 

120Skills 是 markdown 檔案,為您的代理提供專門知識和可呼叫的工作流程。與 `CLAUDE.md`(每個工作階段都載入)不同,skills 按需載入。代理在啟動時接收 skill 描述,並在相關時載入完整內容。

121 

122Skills 透過 `settingSources` 從檔案系統中發現。使用預設選項,使用者和專案 skills 會自動載入。當您未指定 `allowedTools` 時,`Skill` 工具預設啟用。如果您使用 `allowedTools` 允許清單,請明確包含 `"Skill"`。

123 

124<CodeGroup>

125 ```python Python theme={null}

126 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

127 

128 # Skills in .claude/skills/ are discovered automatically

129 # when settingSources includes "project"

130 async for message in query(

131 prompt="Review this PR using our code review checklist",

132 options=ClaudeAgentOptions(

133 setting_sources=["user", "project"],

134 allowed_tools=["Skill", "Read", "Grep", "Glob"],

135 ),

136 ):

137 if isinstance(message, ResultMessage) and message.subtype == "success":

138 print(message.result)

139 ```

140 

141 ```typescript TypeScript theme={null}

142 import { query } from "@anthropic-ai/claude-agent-sdk";

143 

144 // Skills in .claude/skills/ are discovered automatically

145 // when settingSources includes "project"

146 for await (const message of query({

147 prompt: "Review this PR using our code review checklist",

148 options: {

149 settingSources: ["user", "project"],

150 allowedTools: ["Skill", "Read", "Grep", "Glob"]

151 }

152 })) {

153 if (message.type === "result" && message.subtype === "success") {

154 console.log(message.result);

155 }

156 }

157 ```

158</CodeGroup>

159 

160<Note>

161 Skills 必須建立為檔案系統成品(`.claude/skills/<name>/SKILL.md`)。SDK 沒有用於註冊 skills 的程式設計 API。請參閱 [SDK 中的代理 Skills](/zh-TW/agent-sdk/skills) 以取得完整詳細資訊。

162</Note>

163 

164如需建立和使用 skills 的詳細資訊,請參閱 [SDK 中的代理 Skills](/zh-TW/agent-sdk/skills)。

165 

166## Hooks

167 

168SDK 支援兩種定義 hooks 的方式,它們並行執行:

169 

170* **檔案系統 hooks:** 在 `settings.json` 中定義的 shell 命令,當 `settingSources` 包含相關來源時載入。這些是您為 [互動式 Claude Code 工作階段](/zh-TW/hooks-guide) 設定的相同 hooks。

171* **程式設計 hooks:** 直接傳遞給 `query()` 的回呼函式。這些在您的應用程式程序中執行,可以返回結構化決策。請參閱 [使用 hooks 控制執行](/zh-TW/agent-sdk/hooks)。

172 

173兩種類型都在相同的 hook 生命週期中執行。如果您已經在專案的 `.claude/settings.json` 中有 hooks,並且您設定 `settingSources: ["project"]`,那些 hooks 會在 SDK 中自動執行,無需額外設定。

174 

175Hook 回呼接收工具輸入並返回決策字典。返回 `{}`(空字典)表示允許工具繼續。返回 `{"decision": "block", "reason": "..."}` 會阻止執行,原因會作為工具結果發送給 Claude。請參閱 [hooks 指南](/zh-TW/agent-sdk/hooks) 以取得完整的回呼簽名和返回型別。

176 

177<CodeGroup>

178 ```python Python theme={null}

179 from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, ResultMessage

180 

181 

182 # PreToolUse hook callback. Positional args:

183 # input_data: HookInput dict with tool_name, tool_input, hook_event_name

184 # tool_use_id: str | None, the ID of the tool call being intercepted

185 # context: HookContext, carries session metadata

186 async def audit_bash(input_data, tool_use_id, context):

187 command = input_data.get("tool_input", {}).get("command", "")

188 if "rm -rf" in command:

189 return {"decision": "block", "reason": "Destructive command blocked"}

190 return {} # Empty dict: allow the tool to proceed

191 

192 

193 # Filesystem hooks from .claude/settings.json run automatically

194 # when settingSources loads them. You can also add programmatic hooks:

195 async for message in query(

196 prompt="Refactor the auth module",

197 options=ClaudeAgentOptions(

198 setting_sources=["project"], # Loads hooks from .claude/settings.json

199 hooks={

200 "PreToolUse": [

201 HookMatcher(matcher="Bash", hooks=[audit_bash]),

202 ]

203 },

204 ),

205 ):

206 if isinstance(message, ResultMessage) and message.subtype == "success":

207 print(message.result)

208 ```

209 

210 ```typescript TypeScript theme={null}

211 import { query, type HookInput, type HookJSONOutput } from "@anthropic-ai/claude-agent-sdk";

212 

213 // PreToolUse hook callback. HookInput is a discriminated union on

214 // hook_event_name, so narrowing on it gives TypeScript the right

215 // tool_input shape for this event.

216 const auditBash = async (input: HookInput): Promise<HookJSONOutput> => {

217 if (input.hook_event_name !== "PreToolUse") return {};

218 const toolInput = input.tool_input as { command?: string };

219 if (toolInput.command?.includes("rm -rf")) {

220 return { decision: "block", reason: "Destructive command blocked" };

221 }

222 return {}; // Empty object: allow the tool to proceed

223 };

224 

225 // Filesystem hooks from .claude/settings.json run automatically

226 // when settingSources loads them. You can also add programmatic hooks:

227 for await (const message of query({

228 prompt: "Refactor the auth module",

229 options: {

230 settingSources: ["project"], // Loads hooks from .claude/settings.json

231 hooks: {

232 PreToolUse: [{ matcher: "Bash", hooks: [auditBash] }]

233 }

234 }

235 })) {

236 if (message.type === "result" && message.subtype === "success") {

237 console.log(message.result);

238 }

239 }

240 ```

241</CodeGroup>

242 

243### 何時使用哪種 hook 類型

244 

245| Hook 類型 | 最適合 |

246| :------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

247| **檔案系統**(`settings.json`) | 在 CLI 和 SDK 工作階段之間共享 hooks。支援 `"command"`(shell 指令碼)、`"http"`(POST 到端點)、`"mcp_tool"`(呼叫連接的 MCP 伺服器的工具)、`"prompt"`(LLM 評估提示)和 `"agent"`(生成驗證器代理)。這些在主代理和它生成的任何子代理中執行。 |

248| **程式設計**(`query()` 中的回呼) | 應用程式特定邏輯;返回結構化決策;進程內整合。限制於主工作階段。 |

249 

250<Note>

251 TypeScript SDK 支援超出 Python 的其他 hook 事件,包括 `SessionStart`、`SessionEnd`、`TeammateIdle` 和 `TaskCompleted`。請參閱 [hooks 指南](/zh-TW/agent-sdk/hooks) 以取得完整的事件相容性表。

252</Note>

253 

254如需程式設計 hooks 的完整詳細資訊,請參閱 [使用 hooks 控制執行](/zh-TW/agent-sdk/hooks)。如需檔案系統 hook 語法,請參閱 [Hooks](/zh-TW/hooks)。

255 

256## 選擇正確的功能

257 

258Agent SDK 為您提供了多種方式來擴展代理的行為。如果您不確定要使用哪一種,此表將常見目標對應到正確的方法。

259 

260| 您想要... | 使用 | SDK 表面 |

261| :-------------------------------------- | :---------------------------------------- | :------------------------------------------------------- |

262| 設定代理始終遵循的專案慣例 | [CLAUDE.md](/zh-TW/memory) | `settingSources: ["project"]` 會自動載入它 |

263| 為代理提供它在相關時載入的參考資料 | [Skills](/zh-TW/agent-sdk/skills) | `settingSources` + `allowedTools: ["Skill"]` |

264| 執行可重複使用的工作流程(部署、審查、發佈) | [使用者可呼叫的 skills](/zh-TW/agent-sdk/skills) | `settingSources` + `allowedTools: ["Skill"]` |

265| 將隔離的子任務委派給新的上下文(研究、審查) | [子代理](/zh-TW/agent-sdk/subagents) | `agents` 參數 + `allowedTools: ["Agent"]` |

266| 協調多個 Claude Code 實例,具有共享任務清單和直接的代理間訊息傳遞 | [代理團隊](/zh-TW/agent-teams) | 不直接透過 SDK 選項設定。代理團隊是一個 CLI 功能,其中一個工作階段充當團隊主管,協調獨立隊友之間的工作 |

267| 在工具呼叫上執行確定性邏輯(審計、阻止、轉換) | [Hooks](/zh-TW/agent-sdk/hooks) | `hooks` 參數與回呼,或透過 `settingSources` 載入的 shell 指令碼 |

268| 為 Claude 提供對外部服務的結構化工具存取 | [MCP](/zh-TW/agent-sdk/mcp) | `mcpServers` 參數 |

269 

270<Tip>

271 **子代理與代理團隊:** 子代理是短暫的和隔離的:新的對話、一個任務、摘要返回給父代理。代理團隊協調多個獨立的 Claude Code 實例,這些實例共享任務清單並直接相互訊息傳遞。代理團隊是一個 CLI 功能。請參閱 [子代理繼承的內容](/zh-TW/agent-sdk/subagents#what-subagents-inherit) 和 [代理團隊比較](/zh-TW/agent-teams#compare-with-subagents) 以取得詳細資訊。

272</Tip>

273 

274您啟用的每項功能都會增加代理的上下文視窗。如需每項功能的成本以及這些功能如何分層組合,請參閱 [擴展 Claude Code](/zh-TW/features-overview#understand-context-costs)。

275 

276## 相關資源

277 

278* [擴展 Claude Code](/zh-TW/features-overview):所有擴展功能的概念概述,包含比較表和上下文成本分析

279* [SDK 中的 Skills](/zh-TW/agent-sdk/skills):以程式設計方式使用 skills 的完整指南

280* [子代理](/zh-TW/agent-sdk/subagents):為隔離的子任務定義和呼叫子代理

281* [Hooks](/zh-TW/agent-sdk/hooks):在關鍵執行點攔截和控制代理行為

282* [權限](/zh-TW/agent-sdk/permissions):使用模式、規則和回呼控制工具存取

283* [系統提示](/zh-TW/agent-sdk/modifying-system-prompts):在不使用 CLAUDE.md 檔案的情況下注入上下文

agent-sdk/cost-tracking.md +263 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 追蹤成本和使用情況

6 

7> 了解如何追蹤 token 使用情況、估計成本,以及使用 Claude Agent SDK 配置 prompt caching。

8 

9Claude Agent SDK 為每次與 Claude 的互動提供詳細的 token 使用資訊。本指南說明如何正確追蹤使用情況和理解成本報告,特別是在處理平行工具使用和多步驟對話時。

10 

11如需完整的 API 文件,請參閱 [TypeScript SDK 參考](/zh-TW/agent-sdk/typescript) 和 [Python SDK 參考](/zh-TW/agent-sdk/python)。

12 

13<Warning>

14 `total_cost_usd` 和 `costUSD` 欄位是客戶端估計值,不是權威的計費資料。SDK 從在建置時捆綁的價格表本地計算它們,因此當以下情況發生時,它們可能與您實際被計費的金額不同:

15 

16 * 定價變更

17 * 已安裝的 SDK 版本無法識別某個模型

18 * 適用客戶端無法建模的計費規則

19 

20 使用這些欄位進行開發洞察和大約預算編制。如需權威計費,請使用 [Usage and Cost API](https://platform.claude.com/docs/en/build-with-claude/usage-cost-api) 或 [Claude Console](https://platform.claude.com/usage) 中的 Usage 頁面。不要向終端使用者計費或根據這些欄位觸發財務決策。

21</Warning>

22 

23## 了解 token 使用情況

24 

25TypeScript 和 Python SDK 使用不同的欄位名稱公開相同的使用資料:

26 

27* **TypeScript** 在每個助手訊息上提供每步 token 細分(`message.message.id`、`message.message.usage`),通過結果訊息上的 `modelUsage` 提供每個模型的成本,以及結果訊息上的累積總計。

28* **Python** 在每個助手訊息上提供每步 token 細分(`message.usage`、`message.message_id`),通過結果訊息上的 `model_usage` 提供每個模型的成本,以及結果訊息上的累積總計(`total_cost_usd` 和 `usage` 字典)。

29 

30兩個 SDK 使用相同的基礎成本模型並公開相同的粒度。差異在於欄位命名和每步使用情況的嵌套位置。

31 

32成本追蹤取決於理解 SDK 如何限定使用資料的範圍:

33 

34* **`query()` 呼叫:** SDK 的 `query()` 函數的一次調用。單次呼叫可能涉及多個步驟(Claude 回應、使用工具、獲取結果、再次回應)。每次呼叫在末尾產生一個 [`result`](/zh-TW/agent-sdk/typescript#sdk-result-message) 訊息。

35* **步驟:** `query()` 呼叫中的單個請求/回應週期。每個步驟產生帶有 token 使用情況的助手訊息。

36* **會話:** 由會話 ID 連結的一系列 `query()` 呼叫(使用 `resume` 選項)。會話中的每個 `query()` 呼叫獨立報告其自己的成本。

37 

38下圖顯示來自單個 `query()` 呼叫的訊息流,在每個步驟報告 token 使用情況,並在末尾顯示累積估計:

39 

40<img src="https://mintcdn.com/claude-code/Dujg43sxTkuhSELI/images/agent-sdk/message-usage-flow.svg?fit=max&auto=format&n=Dujg43sxTkuhSELI&q=85&s=c542f51ff58547ef9c0e57b16d03f33c" alt="圖表顯示一個查詢產生兩個步驟的訊息。步驟 1 有四個共享相同 ID 和使用情況的助手訊息(計數一次),步驟 2 有一個具有新 ID 的助手訊息,最終結果訊息顯示估計的 total_cost_usd。" width="760" height="520" data-path="images/agent-sdk/message-usage-flow.svg" />

41 

42<Steps>

43 <Step title="每個步驟產生助手訊息">

44 當 Claude 回應時,它發送一個或多個助手訊息。在 TypeScript 中,每個助手訊息包含一個嵌套的 `BetaMessage`(通過 `message.message` 存取),具有 `id` 和一個 [`usage`](https://platform.claude.com/docs/en/api/messages) 物件,其中包含 token 計數(`input_tokens`、`output_tokens`)。在 Python 中,`AssistantMessage` 資料類別通過 `message.usage` 和 `message.message_id` 直接公開相同的資料。當 Claude 在一個回合中使用多個工具時,該回合中的所有訊息共享相同的 ID,因此按 ID 去重以避免重複計數。

45 </Step>

46 

47 <Step title="結果訊息提供累積估計">

48 當 `query()` 呼叫完成時,SDK 發出一個結果訊息,其中包含 `total_cost_usd` 和累積 `usage`。這在 TypeScript([`SDKResultMessage`](/zh-TW/agent-sdk/typescript#sdk-result-message))和 Python([`ResultMessage`](/zh-TW/agent-sdk/python#result-message))中都可用。如果您進行多個 `query()` 呼叫(例如,在多回合會話中),每個結果只反映該個別呼叫的成本。如果您只需要估計的總計,您可以忽略每步使用情況並讀取此單一值。

49 </Step>

50</Steps>

51 

52## 取得查詢的總成本

53 

54結果訊息([TypeScript](/zh-TW/agent-sdk/typescript#sdk-result-message)、[Python](/zh-TW/agent-sdk/python#result-message))標記 `query()` 呼叫的代理迴圈的結束。它包含 `total_cost_usd`,即該呼叫中所有步驟的累積估計成本。這適用於成功和錯誤結果。如果您使用會話進行多個 `query()` 呼叫,每個結果只反映該個別呼叫的成本。

55 

56以下範例遍歷來自 `query()` 呼叫的訊息流,並在 `result` 訊息到達時列印總成本:

57 

58<CodeGroup>

59 ```typescript TypeScript theme={null}

60 import { query } from "@anthropic-ai/claude-agent-sdk";

61 

62 for await (const message of query({ prompt: "Summarize this project" })) {

63 if (message.type === "result") {

64 console.log(`Total cost: $${message.total_cost_usd}`);

65 }

66 }

67 ```

68 

69 ```python Python theme={null}

70 from claude_agent_sdk import query, ResultMessage

71 import asyncio

72 

73 

74 async def main():

75 async for message in query(prompt="Summarize this project"):

76 if isinstance(message, ResultMessage):

77 print(f"Total cost: ${message.total_cost_usd or 0}")

78 

79 

80 asyncio.run(main())

81 ```

82</CodeGroup>

83 

84## 追蹤每步和每個模型的使用情況

85 

86本節中的範例使用 TypeScript 欄位名稱。在 Python 中,等效欄位是 [`AssistantMessage.usage`](/zh-TW/agent-sdk/python#assistant-message) 和 `AssistantMessage.message_id` 用於每步使用情況,以及 [`ResultMessage.model_usage`](/zh-TW/agent-sdk/python#result-message) 用於每個模型的細分。

87 

88### 追蹤每步使用情況

89 

90每個助手訊息包含一個嵌套的 `BetaMessage`(通過 `message.message` 存取),具有 `id` 和 `usage` 物件,其中包含 token 計數。當 Claude 並行使用工具時,多個訊息共享相同的 `id` 和相同的使用資料。追蹤您已經計數的 ID,並跳過重複項以避免膨脹的總計。

91 

92<Warning>

93 平行工具呼叫產生多個助手訊息,其嵌套的 `BetaMessage` 共享相同的 `id` 和相同的使用情況。始終按 ID 去重以獲得準確的每步 token 計數。

94</Warning>

95 

96以下範例累積所有步驟中的輸入和輸出 token,每個唯一訊息 ID 只計數一次:

97 

98```typescript theme={null}

99import { query } from "@anthropic-ai/claude-agent-sdk";

100 

101const seenIds = new Set<string>();

102let totalInputTokens = 0;

103let totalOutputTokens = 0;

104 

105for await (const message of query({ prompt: "Summarize this project" })) {

106 if (message.type === "assistant") {

107 const msgId = message.message.id;

108 

109 // Parallel tool calls share the same ID, only count once

110 if (!seenIds.has(msgId)) {

111 seenIds.add(msgId);

112 totalInputTokens += message.message.usage.input_tokens;

113 totalOutputTokens += message.message.usage.output_tokens;

114 }

115 }

116}

117 

118console.log(`Steps: ${seenIds.size}`);

119console.log(`Input tokens: ${totalInputTokens}`);

120console.log(`Output tokens: ${totalOutputTokens}`);

121```

122 

123### 按模型細分使用情況

124 

125結果訊息包含 [`modelUsage`](/zh-TW/agent-sdk/typescript#model-usage),一個模型名稱到每個模型 token 計數和成本的映射。當您執行多個模型(例如,子代理使用 Haiku,主代理使用 Opus)並想查看 token 的去向時,這很有用。

126 

127以下範例執行查詢並列印每個使用的模型的成本和 token 細分:

128 

129```typescript theme={null}

130import { query } from "@anthropic-ai/claude-agent-sdk";

131 

132for await (const message of query({ prompt: "Summarize this project" })) {

133 if (message.type !== "result") continue;

134 

135 for (const [modelName, usage] of Object.entries(message.modelUsage)) {

136 console.log(`${modelName}: $${usage.costUSD.toFixed(4)}`);

137 console.log(` Input tokens: ${usage.inputTokens}`);

138 console.log(` Output tokens: ${usage.outputTokens}`);

139 console.log(` Cache read: ${usage.cacheReadInputTokens}`);

140 console.log(` Cache creation: ${usage.cacheCreationInputTokens}`);

141 }

142}

143```

144 

145## 累積多個呼叫的成本

146 

147每個 `query()` 呼叫返回其自己的 `total_cost_usd`。SDK 不提供會話級別的總計,因此如果您的應用程式進行多個 `query()` 呼叫(例如,在多回合會話中或跨不同使用者),請自行累積總計。

148 

149以下範例順序執行兩個 `query()` 呼叫,將每個呼叫的 `total_cost_usd` 加到運行總計中,並列印每個呼叫和合併的成本:

150 

151<CodeGroup>

152 ```typescript TypeScript theme={null}

153 import { query } from "@anthropic-ai/claude-agent-sdk";

154 

155 // Track cumulative cost across multiple query() calls

156 let totalSpend = 0;

157 

158 const prompts = [

159 "Read the files in src/ and summarize the architecture",

160 "List all exported functions in src/auth.ts"

161 ];

162 

163 for (const prompt of prompts) {

164 for await (const message of query({ prompt })) {

165 if (message.type === "result") {

166 totalSpend += message.total_cost_usd;

167 console.log(`This call: $${message.total_cost_usd}`);

168 }

169 }

170 }

171 

172 console.log(`Total spend: $${totalSpend.toFixed(4)}`);

173 ```

174 

175 ```python Python theme={null}

176 from claude_agent_sdk import query, ResultMessage

177 import asyncio

178 

179 

180 async def main():

181 # Track cumulative cost across multiple query() calls

182 total_spend = 0.0

183 

184 prompts = [

185 "Read the files in src/ and summarize the architecture",

186 "List all exported functions in src/auth.ts",

187 ]

188 

189 for prompt in prompts:

190 async for message in query(prompt=prompt):

191 if isinstance(message, ResultMessage):

192 cost = message.total_cost_usd or 0

193 total_spend += cost

194 print(f"This call: ${cost}")

195 

196 print(f"Total spend: ${total_spend:.4f}")

197 

198 

199 asyncio.run(main())

200 ```

201</CodeGroup>

202 

203## 處理錯誤、快取和 token 差異

204 

205為了準確的成本追蹤,請考慮失敗的對話、快取 token 定價和偶爾的報告不一致。

206 

207### 解決輸出 token 差異

208 

209在罕見情況下,您可能會觀察到具有相同 ID 的訊息的不同 `output_tokens` 值。當發生這種情況時:

210 

2111. **使用最高值:** 一組中的最終訊息通常包含準確的總計。

2122. **優先使用結果訊息:** 結果訊息中的 `total_cost_usd` 反映 SDK 在所有步驟中的累積估計,因此比自己求和每步值更可靠。它仍然是一個估計值,可能與您的實際帳單不同。

2133. **報告不一致:** 在 [Claude Code GitHub 儲存庫](https://github.com/anthropics/claude-code/issues) 提交問題。

214 

215### 追蹤失敗對話的成本

216 

217成功和錯誤結果訊息都包含 `usage` 和 `total_cost_usd`。如果對話在中途失敗,您仍然消耗了到失敗點為止的 token。無論其 `subtype` 如何,始終從結果訊息讀取成本資料。

218 

219### 追蹤快取 token

220 

221Agent SDK 自動使用 [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) 來減少重複內容的成本。您不需要自己配置快取。使用物件包含兩個額外的欄位用於快取追蹤:

222 

223* `cache_creation_input_tokens`:用於建立新快取項目的 token(按比標準輸入 token 更高的費率計費)。

224* `cache_read_input_tokens`:從現有快取項目讀取的 token(按降低的費率計費)。

225 

226將這些與 `input_tokens` 分開追蹤以了解快取節省。在 TypeScript 中,這些欄位在 [`Usage`](/zh-TW/agent-sdk/typescript#usage) 物件上輸入。在 Python 中,它們作為 [`ResultMessage.usage`](/zh-TW/agent-sdk/python#result-message) 字典中的鍵出現(例如,`message.usage.get("cache_read_input_tokens", 0)`)。

227 

228### 將 prompt 快取 TTL 延長至一小時

229 

230當您使用 API 金鑰進行身份驗證或在 Amazon Bedrock、Google Cloud Vertex AI 或 Microsoft Foundry 上執行時,SDK 寫入的快取項目預設使用 5 分鐘的 TTL。如果您的工作負載針對相同的系統提示和上下文執行許多短會話,且它們之間的間隔超過 5 分鐘,快取會在會話之間過期,每個新會話都會支付完整的輸入價格。

231 

232要請求快取寫入的 1 小時 TTL,請設定 [`ENABLE_PROMPT_CACHING_1H`](/zh-TW/env-vars) 環境變數。您可以在 shell 或容器環境中匯出它,或通過 `options.env` 傳遞它。

233 

234以下範例為在 Bedrock 上執行的代理啟用 1 小時 TTL:

235 

236<CodeGroup>

237 ```python Python theme={null}

238 options = ClaudeAgentOptions(

239 env={

240 "CLAUDE_CODE_USE_BEDROCK": "1",

241 "ENABLE_PROMPT_CACHING_1H": "1",

242 },

243 )

244 ```

245 

246 ```typescript TypeScript theme={null}

247 const options = {

248 env: {

249 ...process.env,

250 CLAUDE_CODE_USE_BEDROCK: "1",

251 ENABLE_PROMPT_CACHING_1H: "1",

252 },

253 };

254 ```

255</CodeGroup>

256 

257具有 1 小時 TTL 的快取寫入按比 5 分鐘寫入更高的費率計費,因此啟用此功能會用更高的寫入成本換取更多的快取讀取。有關詳細資訊,請參閱 [prompt caching 定價](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)。Claude 訂閱使用者已自動獲得 1 小時 TTL,不需要設定此變數。

258 

259## 相關文件

260 

261* [TypeScript SDK 參考](/zh-TW/agent-sdk/typescript) - 完整的 API 文件

262* [SDK 概述](/zh-TW/agent-sdk/overview) - SDK 入門

263* [SDK 權限](/zh-TW/agent-sdk/permissions) - 管理工具權限

agent-sdk/hooks.md +819 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 使用 hooks 攔截和控制代理行為

6 

7> 在代理執行的關鍵點使用 hooks 攔截和自訂代理行為

8 

9Hooks 是回調函數,在代理事件發生時執行您的程式碼,例如工具被呼叫、會話啟動或執行停止。使用 hooks,您可以:

10 

11* **阻止危險操作**在執行前,例如破壞性的 shell 命令或未授權的檔案存取

12* **記錄和審計**每個工具呼叫以進行合規性、除錯或分析

13* **轉換輸入和輸出**以清理資料、注入認證或重定向檔案路徑

14* **要求人工批准**敏感操作,例如資料庫寫入或 API 呼叫

15* **追蹤會話生命週期**以管理狀態、清理資源或傳送通知

16 

17本指南涵蓋 hooks 的工作原理、如何配置它們,並提供常見模式的範例,例如阻止工具、修改輸入和轉發通知。

18 

19## Hooks 如何工作

20 

21<Steps>

22 <Step title="事件觸發">

23 代理執行期間發生某事,SDK 觸發事件:工具即將被呼叫(`PreToolUse`)、工具返回結果(`PostToolUse`)、子代理啟動或停止、代理空閒或執行完成。請參閱[完整事件列表](#available-hooks)。

24 </Step>

25 

26 <Step title="SDK 收集已註冊的 hooks">

27 SDK 檢查為該事件類型註冊的 hooks。這包括您在 `options.hooks` 中傳遞的回調 hooks 和來自設定檔案的 shell 命令 hooks,當相應的 [`settingSources`](/zh-TW/agent-sdk/typescript#setting-source) 或 [`setting_sources`](/zh-TW/agent-sdk/python#setting-source) 項目啟用時(預設 `query()` 選項就是這樣)。

28 </Step>

29 

30 <Step title="匹配器篩選哪些 hooks 執行">

31 如果 hook 有 [`matcher`](#matchers) 模式(例如 `"Write|Edit"`),SDK 會針對事件的目標(例如工具名稱)測試它。沒有匹配器的 hooks 會針對該類型的每個事件執行。

32 </Step>

33 

34 <Step title="回調函數執行">

35 每個匹配的 hook 的[回調函數](#callback-functions)接收有關正在發生的事情的輸入:工具名稱、其參數、會話 ID 和其他事件特定的詳細資訊。

36 </Step>

37 

38 <Step title="您的回調返回決定">

39 執行任何操作(記錄、API 呼叫、驗證)後,您的回調返回[輸出物件](#outputs),告訴代理該做什麼:允許操作、阻止它、修改輸入或將上下文注入對話。

40 </Step>

41</Steps>

42 

43以下範例將這些步驟組合在一起。它註冊一個 `PreToolUse` hook(步驟 1),帶有 `"Write|Edit"` 匹配器(步驟 3),因此回調只針對檔案寫入工具觸發。觸發時,回調接收工具的輸入(步驟 4),檢查檔案路徑是否針對 `.env` 檔案,並返回 `permissionDecision: "deny"` 以阻止操作(步驟 5):

44 

45<CodeGroup>

46 ```python Python theme={null}

47 import asyncio

48 from claude_agent_sdk import (

49 AssistantMessage,

50 ClaudeSDKClient,

51 ClaudeAgentOptions,

52 HookMatcher,

53 ResultMessage,

54 )

55 

56 

57 # 定義一個接收工具呼叫詳細資訊的 hook 回調

58 async def protect_env_files(input_data, tool_use_id, context):

59 # 從工具的輸入參數中提取檔案路徑

60 file_path = input_data["tool_input"].get("file_path", "")

61 file_name = file_path.split("/")[-1]

62 

63 # 如果針對 .env 檔案,阻止操作

64 if file_name == ".env":

65 return {

66 "hookSpecificOutput": {

67 "hookEventName": input_data["hook_event_name"],

68 "permissionDecision": "deny",

69 "permissionDecisionReason": "Cannot modify .env files",

70 }

71 }

72 

73 # 返回空物件以允許操作

74 return {}

75 

76 

77 async def main():

78 options = ClaudeAgentOptions(

79 hooks={

80 # 為 PreToolUse 事件註冊 hook

81 # 匹配器篩選為僅 Write 和 Edit 工具呼叫

82 "PreToolUse": [HookMatcher(matcher="Write|Edit", hooks=[protect_env_files])]

83 }

84 )

85 

86 async with ClaudeSDKClient(options=options) as client:

87 await client.query("Update the database configuration")

88 async for message in client.receive_response():

89 # 篩選助手和結果訊息

90 if isinstance(message, (AssistantMessage, ResultMessage)):

91 print(message)

92 

93 

94 asyncio.run(main())

95 ```

96 

97 ```typescript TypeScript theme={null}

98 import { query, HookCallback, PreToolUseHookInput } from "@anthropic-ai/claude-agent-sdk";

99 

100 // 使用 HookCallback 類型定義 hook 回調

101 const protectEnvFiles: HookCallback = async (input, toolUseID, { signal }) => {

102 // 將輸入轉換為特定 hook 類型以確保類型安全

103 const preInput = input as PreToolUseHookInput;

104 

105 // 轉換 tool_input 以存取其屬性(在 SDK 中類型為 unknown)

106 const toolInput = preInput.tool_input as Record<string, unknown>;

107 const filePath = toolInput?.file_path as string;

108 const fileName = filePath?.split("/").pop();

109 

110 // 如果針對 .env 檔案,阻止操作

111 if (fileName === ".env") {

112 return {

113 hookSpecificOutput: {

114 hookEventName: preInput.hook_event_name,

115 permissionDecision: "deny",

116 permissionDecisionReason: "Cannot modify .env files"

117 }

118 };

119 }

120 

121 // 返回空物件以允許操作

122 return {};

123 };

124 

125 for await (const message of query({

126 prompt: "Update the database configuration",

127 options: {

128 hooks: {

129 // 為 PreToolUse 事件註冊 hook

130 // 匹配器篩選為僅 Write 和 Edit 工具呼叫

131 PreToolUse: [{ matcher: "Write|Edit", hooks: [protectEnvFiles] }]

132 }

133 }

134 })) {

135 // 篩選助手和結果訊息

136 if (message.type === "assistant" || message.type === "result") {

137 console.log(message);

138 }

139 }

140 ```

141</CodeGroup>

142 

143## 可用的 hooks

144 

145SDK 為代理執行的不同階段提供 hooks。某些 hooks 在兩個 SDK 中都可用,而其他則僅限 TypeScript。

146 

147| Hook 事件 | Python SDK | TypeScript SDK | 觸發條件 | 使用案例範例 |

148| -------------------- | ---------- | -------------- | ------------------------- | ---------------------------- |

149| `PreToolUse` | 是 | 是 | 工具呼叫請求(可以阻止或修改) | 阻止危險的 shell 命令 |

150| `PostToolUse` | 是 | 是 | 工具執行結果 | 將所有檔案變更記錄到審計追蹤 |

151| `PostToolUseFailure` | 是 | 是 | 工具執行失敗 | 處理或記錄工具錯誤 |

152| `PostToolBatch` | 否 | 是 | 一整批工具呼叫解決,每批一次,在下一個模型呼叫之前 | 為整個批次注入約定 |

153| `UserPromptSubmit` | 是 | 是 | 使用者提示提交 | 將額外上下文注入提示 |

154| `Stop` | 是 | 是 | 代理執行停止 | 在退出前保存會話狀態 |

155| `SubagentStart` | 是 | 是 | 子代理初始化 | 追蹤平行任務生成 |

156| `SubagentStop` | 是 | 是 | 子代理完成 | 聚合來自平行任務的結果 |

157| `PreCompact` | 是 | 是 | 對話壓縮請求 | 在摘要前存檔完整記錄 |

158| `PermissionRequest` | 是 | 是 | 權限對話將顯示 | 自訂權限處理 |

159| `SessionStart` | 否 | 是 | 會話初始化 | 初始化記錄和遙測 |

160| `SessionEnd` | 否 | 是 | 會話終止 | 清理臨時資源 |

161| `Notification` | 是 | 是 | 代理狀態訊息 | 將代理狀態更新傳送到 Slack 或 PagerDuty |

162| `Setup` | 否 | 是 | 會話設定/維護 | 執行初始化任務 |

163| `TeammateIdle` | 否 | 是 | 隊友變為空閒 | 重新分配工作或通知 |

164| `TaskCompleted` | 否 | 是 | 背景任務完成 | 聚合來自平行任務的結果 |

165| `ConfigChange` | 否 | 是 | 配置檔案變更 | 動態重新載入設定 |

166| `WorktreeCreate` | 否 | 是 | Git worktree 已建立 | 追蹤隔離的工作區 |

167| `WorktreeRemove` | 否 | 是 | Git worktree 已移除 | 清理工作區資源 |

168 

169## 配置 hooks

170 

171要配置 hook,請在代理選項的 `hooks` 欄位中傳遞它(Python 中的 `ClaudeAgentOptions`,TypeScript 中的 `options` 物件):

172 

173<CodeGroup>

174 ```python Python theme={null}

175 options = ClaudeAgentOptions(

176 hooks={"PreToolUse": [HookMatcher(matcher="Bash", hooks=[my_callback])]}

177 )

178 

179 async with ClaudeSDKClient(options=options) as client:

180 await client.query("Your prompt")

181 async for message in client.receive_response():

182 print(message)

183 ```

184 

185 ```typescript TypeScript theme={null}

186 for await (const message of query({

187 prompt: "Your prompt",

188 options: {

189 hooks: {

190 PreToolUse: [{ matcher: "Bash", hooks: [myCallback] }]

191 }

192 }

193 })) {

194 console.log(message);

195 }

196 ```

197</CodeGroup>

198 

199`hooks` 選項是一個字典(Python)或物件(TypeScript),其中:

200 

201* **鍵**是 [hook 事件名稱](#available-hooks)(例如 `'PreToolUse'`、`'PostToolUse'`、`'Stop'`)

202* **值**是[匹配器](#matchers)的陣列,每個都包含可選的篩選模式和您的[回調函數](#callback-functions)

203 

204### 匹配器

205 

206使用匹配器篩選您的回調何時觸發。`matcher` 欄位是一個正規表達式字串,根據 hook 事件類型匹配不同的值。例如,工具型 hooks 匹配工具名稱,而 `Notification` hooks 匹配通知類型。請參閱 [Claude Code hooks 參考](/zh-TW/hooks#matcher-patterns)以取得每個事件類型的完整匹配器值列表。

207 

208| 選項 | 類型 | 預設值 | 描述 |

209| --------- | ---------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

210| `matcher` | `string` | `undefined` | 針對事件的篩選欄位匹配的正規表達式模式。對於工具 hooks,這是工具名稱。內建工具包括 `Bash`、`Read`、`Write`、`Edit`、`Glob`、`Grep`、`WebFetch`、`Agent` 等(請參閱[工具輸入類型](/zh-TW/agent-sdk/typescript#tool-input-types)以取得完整列表)。MCP 工具使用模式 `mcp__<server>__<action>`。 |

211| `hooks` | `HookCallback[]` | - | 必需。當模式匹配時執行的回調函數陣列 |

212| `timeout` | `number` | `60` | 超時時間(秒) |

213 

214盡可能使用 `matcher` 模式來針對特定工具。帶有 `'Bash'` 的匹配器只針對 Bash 命令執行,而省略模式會針對事件的每次出現執行您的回調。請注意,對於工具型 hooks,匹配器只按**工具名稱**篩選,不按檔案路徑或其他參數篩選。要按檔案路徑篩選,請在回調內檢查 `tool_input.file_path`。

215 

216<Tip>

217 **發現工具名稱:** 請參閱[工具輸入類型](/zh-TW/agent-sdk/typescript#tool-input-types)以取得內建工具名稱的完整列表,或新增沒有匹配器的 hook 以記錄您的會話進行的所有工具呼叫。

218 

219 **MCP 工具命名:** MCP 工具始終以 `mcp__` 開頭,後跟伺服器名稱和操作:`mcp__<server>__<action>`。例如,如果您配置名為 `playwright` 的伺服器,其工具將被命名為 `mcp__playwright__browser_screenshot`、`mcp__playwright__browser_click` 等。伺服器名稱來自您在 `mcpServers` 配置中使用的鍵。

220</Tip>

221 

222### 回調函數

223 

224#### 輸入

225 

226每個 hook 回調接收三個參數:

227 

228* **輸入資料:** 一個包含事件詳細資訊的類型物件。每個 hook 類型都有自己的輸入形狀(例如,`PreToolUseHookInput` 包括 `tool_name` 和 `tool_input`,而 `NotificationHookInput` 包括 `message`)。請參閱 [TypeScript](/zh-TW/agent-sdk/typescript#hook-input) 和 [Python](/zh-TW/agent-sdk/python#hook-input) SDK 參考中的完整類型定義。

229 * 所有 hook 輸入共享 `session_id`、`cwd` 和 `hook_event_name`。

230 * 當 hook 在子代理內觸發時,`agent_id` 和 `agent_type` 會被填充。在 TypeScript 中,這些在基本 hook 輸入上,可供所有 hook 類型使用。在 Python 中,它們僅在 `PreToolUse`、`PostToolUse` 和 `PostToolUseFailure` 上。

231* **工具使用 ID**(`str | None` / `string | undefined`):關聯同一工具呼叫的 `PreToolUse` 和 `PostToolUse` 事件。

232* **上下文:** 在 TypeScript 中,包含用於取消的 `signal` 屬性(`AbortSignal`)。在 Python 中,此參數保留供將來使用。

233 

234#### 輸出

235 

236您的回調返回一個具有兩類欄位的物件:

237 

238* **頂級欄位**控制對話:`systemMessage` 將訊息注入對話中,模型可見,`continue`(Python 中的 `continue_`)決定此 hook 後代理是否繼續執行。

239* **`hookSpecificOutput`** 控制目前操作。內部的欄位取決於 hook 事件類型。對於 `PreToolUse` hooks,這是您設定 `permissionDecision`(`"allow"`、`"deny"` 或 `"ask"`)、`permissionDecisionReason` 和 `updatedInput` 的地方。在 TypeScript SDK 中,`permissionDecision` 也接受 `"defer"` 以結束查詢並[稍後繼續](/zh-TW/hooks#defer-a-tool-call-for-later);此值在 Python SDK 中不可用。對於 `PostToolUse` hooks,您可以設定 `additionalContext` 以將資訊附加到工具結果。

240 

241返回 `{}` 以允許操作而不進行變更。SDK 回調 hooks 使用與 [Claude Code shell 命令 hooks](/zh-TW/hooks#json-output) 相同的 JSON 輸出格式,其記錄每個欄位和事件特定選項。對於 SDK 類型定義,請參閱 [TypeScript](/zh-TW/agent-sdk/typescript#sync-hook-json-output) 和 [Python](/zh-TW/agent-sdk/python#sync-hook-json-output) SDK 參考。

242 

243<Note>

244 當多個 hooks 或權限規則適用時,**deny** 優先於 **defer**,**defer** 優先於 **ask**,**ask** 優先於 **allow**。如果任何 hook 返回 `deny`,操作將被阻止,無論其他 hooks 如何。

245</Note>

246 

247#### 非同步輸出

248 

249預設情況下,代理在您的 hook 返回前等待。如果您的 hook 執行副作用(記錄、傳送 webhook)並且不需要影響代理的行為,您可以改為返回非同步輸出。這告訴代理立即繼續,無需等待 hook 完成:

250 

251<CodeGroup>

252 ```python Python theme={null}

253 async def async_hook(input_data, tool_use_id, context):

254 # 啟動背景任務,然後立即返回

255 asyncio.create_task(send_to_logging_service(input_data))

256 return {"async_": True, "asyncTimeout": 30000}

257 ```

258 

259 ```typescript TypeScript theme={null}

260 const asyncHook: HookCallback = async (input, toolUseID, { signal }) => {

261 // 啟動背景任務,然後立即返回

262 sendToLoggingService(input).catch(console.error);

263 return { async: true, asyncTimeout: 30000 };

264 };

265 ```

266</CodeGroup>

267 

268| 欄位 | 類型 | 描述 |

269| -------------- | -------- | --------------------------------------------------- |

270| `async` | `true` | 表示非同步模式。代理無需等待即可繼續。在 Python 中,使用 `async_` 以避免保留關鍵字。 |

271| `asyncTimeout` | `number` | 背景操作的可選超時時間(毫秒) |

272 

273<Note>

274 非同步輸出無法阻止、修改或將上下文注入操作,因為代理已經繼續。僅將它們用於副作用,例如記錄、指標或通知。

275</Note>

276 

277## 範例

278 

279### 修改工具輸入

280 

281此範例攔截 Write 工具呼叫並重寫 `file_path` 參數以預先加上 `/sandbox`,將所有檔案寫入重定向到沙箱目錄。回調返回帶有修改路徑的 `updatedInput` 和 `permissionDecision: 'allow'` 以自動批准重寫的操作:

282 

283<CodeGroup>

284 ```python Python theme={null}

285 async def redirect_to_sandbox(input_data, tool_use_id, context):

286 if input_data["hook_event_name"] != "PreToolUse":

287 return {}

288 

289 if input_data["tool_name"] == "Write":

290 original_path = input_data["tool_input"].get("file_path", "")

291 return {

292 "hookSpecificOutput": {

293 "hookEventName": input_data["hook_event_name"],

294 "permissionDecision": "allow",

295 "updatedInput": {

296 **input_data["tool_input"],

297 "file_path": f"/sandbox{original_path}",

298 },

299 }

300 }

301 return {}

302 ```

303 

304 ```typescript TypeScript theme={null}

305 const redirectToSandbox: HookCallback = async (input, toolUseID, { signal }) => {

306 if (input.hook_event_name !== "PreToolUse") return {};

307 

308 const preInput = input as PreToolUseHookInput;

309 const toolInput = preInput.tool_input as Record<string, unknown>;

310 if (preInput.tool_name === "Write") {

311 const originalPath = toolInput.file_path as string;

312 return {

313 hookSpecificOutput: {

314 hookEventName: preInput.hook_event_name,

315 permissionDecision: "allow",

316 updatedInput: {

317 ...toolInput,

318 file_path: `/sandbox${originalPath}`

319 }

320 }

321 };

322 }

323 return {};

324 };

325 ```

326</CodeGroup>

327 

328<Note>

329 使用 `updatedInput` 時,您還必須包括 `permissionDecision: 'allow'`。始終返回新物件,而不是改變原始 `tool_input`。

330</Note>

331 

332### 新增上下文並阻止工具

333 

334此範例阻止任何嘗試寫入 `/etc` 目錄,並一起使用兩個輸出欄位:`permissionDecision: 'deny'` 停止工具呼叫,而 `systemMessage` 將提醒注入對話,以便代理接收有關操作被阻止原因的上下文並避免重試:

335 

336<CodeGroup>

337 ```python Python theme={null}

338 async def block_etc_writes(input_data, tool_use_id, context):

339 file_path = input_data["tool_input"].get("file_path", "")

340 

341 if file_path.startswith("/etc"):

342 return {

343 # 頂級欄位:將指導注入對話

344 "systemMessage": "Remember: system directories like /etc are protected.",

345 # hookSpecificOutput:阻止操作

346 "hookSpecificOutput": {

347 "hookEventName": input_data["hook_event_name"],

348 "permissionDecision": "deny",

349 "permissionDecisionReason": "Writing to /etc is not allowed",

350 },

351 }

352 return {}

353 ```

354 

355 ```typescript TypeScript theme={null}

356 const blockEtcWrites: HookCallback = async (input, toolUseID, { signal }) => {

357 const preInput = input as PreToolUseHookInput;

358 const toolInput = preInput.tool_input as Record<string, unknown>;

359 const filePath = toolInput?.file_path as string;

360 

361 if (filePath?.startsWith("/etc")) {

362 return {

363 // 頂級欄位:將指導注入對話

364 systemMessage: "Remember: system directories like /etc are protected.",

365 // hookSpecificOutput:阻止操作

366 hookSpecificOutput: {

367 hookEventName: preInput.hook_event_name,

368 permissionDecision: "deny",

369 permissionDecisionReason: "Writing to /etc is not allowed"

370 }

371 };

372 }

373 return {};

374 };

375 ```

376</CodeGroup>

377 

378### 自動批准特定工具

379 

380預設情況下,代理可能在使用某些工具前提示權限。此範例通過返回 `permissionDecision: 'allow'` 自動批准唯讀檔案系統工具(Read、Glob、Grep),讓它們無需使用者確認即可執行,同時讓所有其他工具受到正常權限檢查:

381 

382<CodeGroup>

383 ```python Python theme={null}

384 async def auto_approve_read_only(input_data, tool_use_id, context):

385 if input_data["hook_event_name"] != "PreToolUse":

386 return {}

387 

388 read_only_tools = ["Read", "Glob", "Grep"]

389 if input_data["tool_name"] in read_only_tools:

390 return {

391 "hookSpecificOutput": {

392 "hookEventName": input_data["hook_event_name"],

393 "permissionDecision": "allow",

394 "permissionDecisionReason": "Read-only tool auto-approved",

395 }

396 }

397 return {}

398 ```

399 

400 ```typescript TypeScript theme={null}

401 const autoApproveReadOnly: HookCallback = async (input, toolUseID, { signal }) => {

402 if (input.hook_event_name !== "PreToolUse") return {};

403 

404 const preInput = input as PreToolUseHookInput;

405 const readOnlyTools = ["Read", "Glob", "Grep"];

406 if (readOnlyTools.includes(preInput.tool_name)) {

407 return {

408 hookSpecificOutput: {

409 hookEventName: preInput.hook_event_name,

410 permissionDecision: "allow",

411 permissionDecisionReason: "Read-only tool auto-approved"

412 }

413 };

414 }

415 return {};

416 };

417 ```

418</CodeGroup>

419 

420### 鏈接多個 hooks

421 

422Hooks 按它們在陣列中出現的順序執行。保持每個 hook 專注於單一責任,並為複雜邏輯鏈接多個 hooks:

423 

424<CodeGroup>

425 ```python Python theme={null}

426 options = ClaudeAgentOptions(

427 hooks={

428 "PreToolUse": [

429 HookMatcher(hooks=[rate_limiter]), # 首先:檢查速率限制

430 HookMatcher(hooks=[authorization_check]), # 其次:驗證權限

431 HookMatcher(hooks=[input_sanitizer]), # 第三:清理輸入

432 HookMatcher(hooks=[audit_logger]), # 最後:記錄操作

433 ]

434 }

435 )

436 ```

437 

438 ```typescript TypeScript theme={null}

439 const options = {

440 hooks: {

441 PreToolUse: [

442 { hooks: [rateLimiter] }, // 首先:檢查速率限制

443 { hooks: [authorizationCheck] }, // 其次:驗證權限

444 { hooks: [inputSanitizer] }, // 第三:清理輸入

445 { hooks: [auditLogger] } // 最後:記錄操作

446 ]

447 }

448 };

449 ```

450</CodeGroup>

451 

452### 使用正規表達式匹配器篩選

453 

454使用正規表達式模式匹配多個工具。此範例註冊三個具有不同範圍的匹配器:第一個僅針對檔案修改工具觸發 `file_security_hook`,第二個針對任何 MCP 工具(名稱以 `mcp__` 開頭的工具)觸發 `mcp_audit_hook`,第三個針對每個工具呼叫(無論名稱如何)觸發 `global_logger`:

455 

456<CodeGroup>

457 ```python Python theme={null}

458 options = ClaudeAgentOptions(

459 hooks={

460 "PreToolUse": [

461 # 匹配檔案修改工具

462 HookMatcher(matcher="Write|Edit|Delete", hooks=[file_security_hook]),

463 # 匹配所有 MCP 工具

464 HookMatcher(matcher="^mcp__", hooks=[mcp_audit_hook]),

465 # 匹配所有內容(無匹配器)

466 HookMatcher(hooks=[global_logger]),

467 ]

468 }

469 )

470 ```

471 

472 ```typescript TypeScript theme={null}

473 const options = {

474 hooks: {

475 PreToolUse: [

476 // 匹配檔案修改工具

477 { matcher: "Write|Edit|Delete", hooks: [fileSecurityHook] },

478 

479 // 匹配所有 MCP 工具

480 { matcher: "^mcp__", hooks: [mcpAuditHook] },

481 

482 // 匹配所有內容(無匹配器)

483 { hooks: [globalLogger] }

484 ]

485 }

486 };

487 ```

488</CodeGroup>

489 

490### 追蹤子代理活動

491 

492使用 `SubagentStop` hooks 監控子代理何時完成其工作。請參閱 [TypeScript](/zh-TW/agent-sdk/typescript#hook-input) 和 [Python](/zh-TW/agent-sdk/python#hook-input) SDK 參考中的完整輸入類型。此範例在每次子代理完成時記錄摘要:

493 

494<CodeGroup>

495 ```python Python theme={null}

496 async def subagent_tracker(input_data, tool_use_id, context):

497 # 子代理完成時記錄子代理詳細資訊

498 print(f"[SUBAGENT] Completed: {input_data['agent_id']}")

499 print(f" Transcript: {input_data['agent_transcript_path']}")

500 print(f" Tool use ID: {tool_use_id}")

501 print(f" Stop hook active: {input_data.get('stop_hook_active')}")

502 return {}

503 

504 

505 options = ClaudeAgentOptions(

506 hooks={"SubagentStop": [HookMatcher(hooks=[subagent_tracker])]}

507 )

508 ```

509 

510 ```typescript TypeScript theme={null}

511 import { HookCallback, SubagentStopHookInput } from "@anthropic-ai/claude-agent-sdk";

512 

513 const subagentTracker: HookCallback = async (input, toolUseID, { signal }) => {

514 // 轉換為 SubagentStopHookInput 以存取子代理特定欄位

515 const subInput = input as SubagentStopHookInput;

516 

517 // 子代理完成時記錄子代理詳細資訊

518 console.log(`[SUBAGENT] Completed: ${subInput.agent_id}`);

519 console.log(` Transcript: ${subInput.agent_transcript_path}`);

520 console.log(` Tool use ID: ${toolUseID}`);

521 console.log(` Stop hook active: ${subInput.stop_hook_active}`);

522 return {};

523 };

524 

525 const options = {

526 hooks: {

527 SubagentStop: [{ hooks: [subagentTracker] }]

528 }

529 };

530 ```

531</CodeGroup>

532 

533### 從 hooks 發出 HTTP 請求

534 

535Hooks 可以執行非同步操作,例如 HTTP 請求。在您的 hook 內捕捉錯誤,而不是讓它們傳播,因為未處理的異常可能會中斷代理。

536 

537此範例在每個工具完成後傳送 webhook,記錄哪個工具執行以及何時執行。hook 捕捉錯誤,以便失敗的 webhook 不會中斷代理:

538 

539<CodeGroup>

540 ```python Python theme={null}

541 import asyncio

542 import json

543 import urllib.request

544 from datetime import datetime

545 

546 

547 def _send_webhook(tool_name):

548 """同步幫助程式,將工具使用資料 POST 到外部 webhook。"""

549 data = json.dumps(

550 {

551 "tool": tool_name,

552 "timestamp": datetime.now().isoformat(),

553 }

554 ).encode()

555 req = urllib.request.Request(

556 "https://api.example.com/webhook",

557 data=data,

558 headers={"Content-Type": "application/json"},

559 method="POST",

560 )

561 urllib.request.urlopen(req)

562 

563 

564 async def webhook_notifier(input_data, tool_use_id, context):

565 # 僅在工具完成後觸發(PostToolUse),而不是之前

566 if input_data["hook_event_name"] != "PostToolUse":

567 return {}

568 

569 try:

570 # 在執行緒中執行阻止 HTTP 呼叫以避免阻止事件迴圈

571 await asyncio.to_thread(_send_webhook, input_data["tool_name"])

572 except Exception as e:

573 # 記錄錯誤但不引發。失敗的 webhook 不應停止代理

574 print(f"Webhook request failed: {e}")

575 

576 return {}

577 ```

578 

579 ```typescript TypeScript theme={null}

580 import { query, HookCallback, PostToolUseHookInput } from "@anthropic-ai/claude-agent-sdk";

581 

582 const webhookNotifier: HookCallback = async (input, toolUseID, { signal }) => {

583 // 僅在工具完成後觸發(PostToolUse),而不是之前

584 if (input.hook_event_name !== "PostToolUse") return {};

585 

586 try {

587 await fetch("https://api.example.com/webhook", {

588 method: "POST",

589 headers: { "Content-Type": "application/json" },

590 body: JSON.stringify({

591 tool: (input as PostToolUseHookInput).tool_name,

592 timestamp: new Date().toISOString()

593 }),

594 // 傳遞 signal 以便在 hook 超時時取消請求

595 signal

596 });

597 } catch (error) {

598 // 分別處理取消和其他錯誤

599 if (error instanceof Error && error.name === "AbortError") {

600 console.log("Webhook request cancelled");

601 }

602 // 不重新拋出。失敗的 webhook 不應停止代理

603 }

604 

605 return {};

606 };

607 

608 // 註冊為 PostToolUse hook

609 for await (const message of query({

610 prompt: "Refactor the auth module",

611 options: {

612 hooks: {

613 PostToolUse: [{ hooks: [webhookNotifier] }]

614 }

615 }

616 })) {

617 console.log(message);

618 }

619 ```

620</CodeGroup>

621 

622### 將通知轉發到 Slack

623 

624使用 `Notification` hooks 接收來自代理的系統通知並將其轉發到外部服務。通知針對特定事件類型觸發:`permission_prompt`(Claude 需要權限)、`idle_prompt`(Claude 等待輸入)、`auth_success`(認證完成)和 `elicitation_dialog`(Claude 提示使用者)。每個通知都包括帶有人類可讀描述的 `message` 欄位,以及可選的 `title`。

625 

626此範例將每個通知轉發到 Slack 頻道。它需要 [Slack 傳入 webhook URL](https://api.slack.com/messaging/webhooks),您可以通過將應用程式新增到 Slack 工作區並啟用傳入 webhooks 來建立:

627 

628<CodeGroup>

629 ```python Python theme={null}

630 import asyncio

631 import json

632 import urllib.request

633 

634 from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, HookMatcher

635 

636 

637 def _send_slack_notification(message):

638 """同步幫助程式,通過傳入 webhook 將訊息傳送到 Slack。"""

639 data = json.dumps({"text": f"Agent status: {message}"}).encode()

640 req = urllib.request.Request(

641 "https://hooks.slack.com/services/YOUR/WEBHOOK/URL",

642 data=data,

643 headers={"Content-Type": "application/json"},

644 method="POST",

645 )

646 urllib.request.urlopen(req)

647 

648 

649 async def notification_handler(input_data, tool_use_id, context):

650 try:

651 # 在執行緒中執行阻止 HTTP 呼叫以避免阻止事件迴圈

652 await asyncio.to_thread(_send_slack_notification, input_data.get("message", ""))

653 except Exception as e:

654 print(f"Failed to send notification: {e}")

655 

656 # 返回空物件。通知 hooks 不修改代理行為

657 return {}

658 

659 

660 async def main():

661 options = ClaudeAgentOptions(

662 hooks={

663 # 為通知事件註冊 hook(不需要匹配器)

664 "Notification": [HookMatcher(hooks=[notification_handler])],

665 },

666 )

667 

668 async with ClaudeSDKClient(options=options) as client:

669 await client.query("Analyze this codebase")

670 async for message in client.receive_response():

671 print(message)

672 

673 

674 asyncio.run(main())

675 ```

676 

677 ```typescript TypeScript theme={null}

678 import { query, HookCallback, NotificationHookInput } from "@anthropic-ai/claude-agent-sdk";

679 

680 // 定義一個將通知傳送到 Slack 的 hook 回調

681 const notificationHandler: HookCallback = async (input, toolUseID, { signal }) => {

682 // 轉換為 NotificationHookInput 以存取訊息欄位

683 const notification = input as NotificationHookInput;

684 

685 try {

686 // POST 通知訊息到 Slack 傳入 webhook

687 await fetch("https://hooks.slack.com/services/YOUR/WEBHOOK/URL", {

688 method: "POST",

689 headers: { "Content-Type": "application/json" },

690 body: JSON.stringify({

691 text: `Agent status: ${notification.message}`

692 }),

693 // 傳遞 signal 以便在 hook 超時時取消請求

694 signal

695 });

696 } catch (error) {

697 if (error instanceof Error && error.name === "AbortError") {

698 console.log("Notification cancelled");

699 } else {

700 console.error("Failed to send notification:", error);

701 }

702 }

703 

704 // 返回空物件。通知 hooks 不修改代理行為

705 return {};

706 };

707 

708 // 為通知事件註冊 hook(不需要匹配器)

709 for await (const message of query({

710 prompt: "Analyze this codebase",

711 options: {

712 hooks: {

713 Notification: [{ hooks: [notificationHandler] }]

714 }

715 }

716 })) {

717 console.log(message);

718 }

719 ```

720</CodeGroup>

721 

722## 修復常見問題

723 

724### Hook 未觸發

725 

726* 驗證 hook 事件名稱正確且區分大小寫(`PreToolUse`,而不是 `preToolUse`)

727* 檢查您的匹配器模式是否與工具名稱完全匹配

728* 確保 hook 在 `options.hooks` 中的正確事件類型下

729* 對於非工具 hooks,如 `Stop` 和 `SubagentStop`,匹配器匹配不同的欄位(請參閱[匹配器模式](/zh-TW/hooks#matcher-patterns))

730* 當代理達到 [`max_turns`](/zh-TW/agent-sdk/python#claude-agent-options) 限制時,hooks 可能不會觸發,因為會話在 hooks 可以執行前結束

731 

732### 匹配器未按預期篩選

733 

734匹配器只匹配**工具名稱**,不匹配檔案路徑或其他參數。要按檔案路徑篩選,請在您的 hook 內檢查 `tool_input.file_path`:

735 

736```typescript theme={null}

737const myHook: HookCallback = async (input, toolUseID, { signal }) => {

738 const preInput = input as PreToolUseHookInput;

739 const toolInput = preInput.tool_input as Record<string, unknown>;

740 const filePath = toolInput?.file_path as string;

741 if (!filePath?.endsWith(".md")) return {}; // 跳過非 markdown 檔案

742 // 處理 markdown 檔案...

743 return {};

744};

745```

746 

747### Hook 超時

748 

749* 增加 `HookMatcher` 配置中的 `timeout` 值

750* 在 TypeScript 中使用第三個回調參數中的 `AbortSignal` 以優雅地處理取消

751 

752### 工具意外被阻止

753 

754* 檢查所有 `PreToolUse` hooks 是否返回 `permissionDecision: 'deny'`

755* 將記錄新增到您的 hooks 以查看它們返回的 `permissionDecisionReason`

756* 驗證匹配器模式不會太寬泛(空匹配器匹配所有工具)

757 

758### 修改的輸入未應用

759 

760* 確保 `updatedInput` 在 `hookSpecificOutput` 內,而不是在頂級:

761 

762 ```typescript theme={null}

763 return {

764 hookSpecificOutput: {

765 hookEventName: "PreToolUse",

766 permissionDecision: "allow",

767 updatedInput: { command: "new command" }

768 }

769 };

770 ```

771 

772* 您還必須返回 `permissionDecision: 'allow'` 以使輸入修改生效

773 

774* 在 `hookSpecificOutput` 中包括 `hookEventName` 以識別輸出適用於哪個 hook 類型

775 

776### Python 中不可用會話 hooks

777 

778`SessionStart` 和 `SessionEnd` 可以在 TypeScript 中註冊為 SDK 回調 hooks,但在 Python SDK 中不可用(`HookEvent` 省略它們)。在 Python 中,它們僅作為[shell 命令 hooks](/zh-TW/hooks#hook-events) 在設定檔案中定義(例如 `.claude/settings.json`)。要從您的 SDK 應用程式載入 shell 命令 hooks,請使用 [`setting_sources`](/zh-TW/agent-sdk/python#setting-source) 或 [`settingSources`](/zh-TW/agent-sdk/typescript#setting-source) 包括適當的設定來源:

779 

780<CodeGroup>

781 ```python Python theme={null}

782 options = ClaudeAgentOptions(

783 setting_sources=["project"], # 載入 .claude/settings.json 包括 hooks

784 )

785 ```

786 

787 ```typescript TypeScript theme={null}

788 const options = {

789 settingSources: ["project"] // 載入 .claude/settings.json 包括 hooks

790 };

791 ```

792</CodeGroup>

793 

794要改為執行初始化邏輯作為 Python SDK 回調,請使用 `client.receive_response()` 的第一條訊息作為您的觸發器。

795 

796### 子代理權限提示倍增

797 

798生成多個子代理時,每個子代理可能會分別請求權限。子代理不會自動繼承父代理權限。要避免重複提示,請使用 `PreToolUse` hooks 自動批准特定工具,或配置適用於子代理會話的權限規則。

799 

800### 子代理的遞迴 hook 迴圈

801 

802生成子代理的 `UserPromptSubmit` hook 如果這些子代理觸發相同的 hook,可能會建立無限迴圈。要防止這種情況:

803 

804* 在生成子代理前檢查 hook 輸入中的子代理指示器

805* 使用共享變數或會話狀態來追蹤您是否已在子代理內

806* 將 hooks 範圍限制為僅針對頂級代理會話執行

807 

808### systemMessage 未出現在輸出中

809 

810`systemMessage` 欄位將上下文新增到模型可見的對話中,但它可能不會出現在所有 SDK 輸出模式中。如果您需要將 hook 決定呈現給您的應用程式,請分別記錄它們或使用專用輸出頻道。

811 

812## 相關資源

813 

814* [Claude Code hooks 參考](/zh-TW/hooks):完整的 JSON 輸入/輸出架構、事件文件和匹配器模式

815* [Claude Code hooks 指南](/zh-TW/hooks-guide):shell 命令 hook 範例和逐步解說

816* [TypeScript SDK 參考](/zh-TW/agent-sdk/typescript):hook 類型、輸入/輸出定義和配置選項

817* [Python SDK 參考](/zh-TW/agent-sdk/python):hook 類型、輸入/輸出定義和配置選項

818* [權限](/zh-TW/agent-sdk/permissions):控制您的代理可以做什麼

819* [自訂工具](/zh-TW/agent-sdk/custom-tools):建立工具以擴展代理功能

agent-sdk/hosting.md +142 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 託管 Agent SDK

6 

7> 在生產環境中部署和託管 Claude Agent SDK

8 

9Claude Agent SDK 與傳統的無狀態 LLM API 不同,它維護對話狀態並在持久環境中執行命令。本指南涵蓋了在生產環境中部署基於 SDK 的代理的架構、託管考慮因素和最佳實踐。

10 

11<Info>

12 如需超越基本沙箱的安全強化(包括網路控制、認證管理和隔離選項),請參閱 [安全部署](/zh-TW/agent-sdk/secure-deployment)。

13</Info>

14 

15## 託管要求

16 

17### 基於容器的沙箱

18 

19為了安全和隔離,SDK 應在沙箱容器環境中運行。這提供了進程隔離、資源限制、網路控制和臨時文件系統。

20 

21SDK 還支持 [程序化沙箱配置](/zh-TW/agent-sdk/typescript#sandbox-settings) 用於命令執行。

22 

23### 系統要求

24 

25每個 SDK 實例需要:

26 

27* **運行時依賴項**

28 * Python 3.10+ 用於 Python SDK,或 Node.js 18+ 用於 TypeScript SDK

29 * 兩個 SDK 套件都為主機平台捆綁了本機 Claude Code 二進制文件,因此不需要為生成的 CLI 單獨安裝 Claude Code 或 Node.js

30 

31* **資源分配**

32 * 建議:1GiB RAM、5GiB 磁盤和 1 個 CPU(根據您的任務需要進行調整)

33 

34* **網路訪問**

35 * 出站 HTTPS 到 `api.anthropic.com`

36 * 可選:訪問 MCP 伺服器或外部工具

37 

38## 理解 SDK 架構

39 

40與無狀態 API 調用不同,Claude Agent SDK 作為 **長時間運行的進程** 運行,該進程:

41 

42* **在持久 shell 環境中執行命令**

43* **在工作目錄內管理文件操作**

44* **使用來自先前交互的上下文處理工具執行**

45 

46## 沙箱提供商選項

47 

48多個提供商專門提供用於 AI 代碼執行的安全容器環境:

49 

50* **[Modal Sandbox](https://modal.com/docs/guide/sandbox)** - [演示實現](https://modal.com/docs/examples/claude-slack-gif-creator)

51* **[Cloudflare Sandboxes](https://github.com/cloudflare/sandbox-sdk)**

52* **[Daytona](https://www.daytona.io/)**

53* **[E2B](https://e2b.dev/)**

54* **[Fly Machines](https://fly.io/docs/machines/)**

55* **[Vercel Sandbox](https://vercel.com/docs/functions/sandbox)**

56 

57有關自託管選項(Docker、gVisor、Firecracker)和詳細隔離配置,請參閱 [隔離技術](/zh-TW/agent-sdk/secure-deployment#isolation-technologies)。

58 

59## 生產部署模式

60 

61### 模式 1:臨時會話

62 

63為每個用戶任務創建一個新容器,然後在完成時銷毀它。

64 

65最適合一次性任務,用戶可能仍然在任務完成時與 AI 交互,但一旦完成,容器就會被銷毀。

66 

67**示例:**

68 

69* 錯誤調查和修復:使用相關上下文調試和解決特定問題

70* 發票處理:從收據/發票中提取和結構化數據用於會計系統

71* 翻譯任務:在語言之間翻譯文檔或內容批次

72* 圖像/視頻處理:對媒體文件應用轉換、優化或提取元數據

73 

74### 模式 2:長時間運行的會話

75 

76為長時間運行的任務維護持久容器實例。通常在容器內根據需求運行 **多個** Claude Agent 進程。

77 

78最適合主動代理,它們在沒有用戶輸入的情況下採取行動、提供內容的代理或處理大量消息的代理。

79 

80**示例:**

81 

82* 電子郵件代理:監控傳入電子郵件並根據內容自主進行分類、回應或採取行動

83* 網站構建器:為每個用戶託管自定義網站,具有通過容器端口提供的實時編輯功能

84* 高頻聊天機器人:處理來自 Slack 等平台的連續消息流,其中快速響應時間至關重要

85 

86### 模式 3:混合會話

87 

88臨時容器,使用歷史和狀態進行補充,可能來自數據庫或 SDK 的會話恢復功能。

89 

90最適合與用戶進行間歇性交互的容器,啟動工作並在工作完成時關閉,但可以繼續。

91 

92**示例:**

93 

94* 個人項目經理:幫助管理進行中的項目,進行間歇性檢查,維護任務、決策和進度的上下文

95* 深度研究:進行多小時的研究任務,保存發現並在用戶返回時恢復調查

96* 客戶支持代理:處理跨越多個交互的支持票證,加載票證歷史和客戶上下文

97 

98### 模式 4:單個容器

99 

100在一個全局容器中運行多個 Claude Agent SDK 進程。

101 

102最適合必須密切協作的代理。這可能是最不受歡迎的模式,因為您必須防止代理相互覆蓋。

103 

104**示例:**

105 

106* **模擬**:在模擬(如視頻遊戲)中相互交互的代理。

107 

108## 常見問題

109 

110### 我如何與我的沙箱通信?

111 

112在容器中託管時,公開端口以與您的 SDK 實例通信。您的應用程序可以為外部客戶端公開 HTTP/WebSocket 端點,而 SDK 在容器內部運行。

113 

114### 託管容器的成本是多少?

115 

116提供代理的主要成本是令牌;容器根據您配置的內容而異,但最低成本大約是每小時 5 美分。

117 

118### 我應該何時關閉空閒容器與保持它們溫暖?

119 

120這可能取決於提供商,不同的沙箱提供商將允許您為空閒超時設置不同的條件,之後沙箱可能會關閉。

121您需要根據您認為用戶響應可能的頻率來調整此超時。

122 

123### 我應該多久更新一次 Claude Code CLI?

124 

125Claude Code CLI 使用 semver 進行版本控制,因此任何破壞性更改都將被版本化。

126 

127### 我如何監控容器健康和代理性能?

128 

129由於容器只是伺服器,您用於後端的相同日誌記錄基礎設施將適用於容器。

130 

131### 代理會話在超時前可以運行多長時間?

132 

133代理會話不會超時,但考慮設置 'maxTurns' 屬性以防止 Claude 陷入循環。

134 

135## 後續步驟

136 

137* [安全部署](/zh-TW/agent-sdk/secure-deployment) - 網路控制、認證管理和隔離強化

138* [TypeScript SDK - Sandbox Settings](/zh-TW/agent-sdk/typescript#sandbox-settings) - 以程序方式配置沙箱

139* [會話指南](/zh-TW/agent-sdk/sessions) - 了解會話管理

140* [權限](/zh-TW/agent-sdk/permissions) - 配置工具權限

141* [成本追蹤](/zh-TW/agent-sdk/cost-tracking) - 監控 API 使用情況

142* [MCP 集成](/zh-TW/agent-sdk/mcp) - 使用自定義工具進行擴展

agent-sdk/overview.md +607 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Agent SDK 概述

6 

7> 使用 Claude Code 作為程式庫構建生產級 AI 代理

8 

9<Note>

10 Claude Code SDK 已重新命名為 Claude Agent SDK。如果您正在從舊 SDK 遷移,請參閱[遷移指南](/zh-TW/agent-sdk/migration-guide)。

11</Note>

12 

13構建能夠自主讀取檔案、執行命令、搜尋網路、編輯程式碼等的 AI 代理。Agent SDK 提供與 Claude Code 相同的工具、代理迴圈和上下文管理,可在 Python 和 TypeScript 中進行程式設計。

14 

15<Note>

16 Opus 4.7 (`claude-opus-4-7`) 需要 Agent SDK v0.2.111 或更高版本。如果您看到 `thinking.type.enabled` API 錯誤,請參閱[故障排除](/zh-TW/agent-sdk/quickstart#troubleshooting)。

17</Note>

18 

19<CodeGroup>

20 ```python Python theme={null}

21 import asyncio

22 from claude_agent_sdk import query, ClaudeAgentOptions

23 

24 

25 async def main():

26 async for message in query(

27 prompt="Find and fix the bug in auth.py",

28 options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),

29 ):

30 print(message) # Claude reads the file, finds the bug, edits it

31 

32 

33 asyncio.run(main())

34 ```

35 

36 ```typescript TypeScript theme={null}

37 import { query } from "@anthropic-ai/claude-agent-sdk";

38 

39 for await (const message of query({

40 prompt: "Find and fix the bug in auth.ts",

41 options: { allowedTools: ["Read", "Edit", "Bash"] }

42 })) {

43 console.log(message); // Claude reads the file, finds the bug, edits it

44 }

45 ```

46</CodeGroup>

47 

48Agent SDK 包含用於讀取檔案、執行命令和編輯程式碼的內建工具,因此您的代理可以立即開始工作,無需您實現工具執行。深入了解快速入門或探索使用 SDK 構建的真實代理:

49 

50<CardGroup cols={2}>

51 <Card title="快速入門" icon="play" href="/zh-TW/agent-sdk/quickstart">

52 在幾分鐘內構建一個除錯代理

53 </Card>

54 

55 <Card title="範例代理" icon="star" href="https://github.com/anthropics/claude-agent-sdk-demos">

56 電子郵件助手、研究代理等

57 </Card>

58</CardGroup>

59 

60## 開始使用

61 

62<Steps>

63 <Step title="安裝 SDK">

64 <Tabs>

65 <Tab title="TypeScript">

66 ```bash theme={null}

67 npm install @anthropic-ai/claude-agent-sdk

68 ```

69 </Tab>

70 

71 <Tab title="Python">

72 ```bash theme={null}

73 pip install claude-agent-sdk

74 ```

75 </Tab>

76 </Tabs>

77 

78 <Note>

79 TypeScript SDK 為您的平台捆綁了原生 Claude Code 二進位檔案作為可選依賴項,因此您無需單獨安裝 Claude Code。

80 </Note>

81 </Step>

82 

83 <Step title="設定您的 API 金鑰">

84 從[主控台](https://platform.claude.com/)取得 API 金鑰,然後將其設定為環境變數:

85 

86 ```bash theme={null}

87 export ANTHROPIC_API_KEY=your-api-key

88 ```

89 

90 SDK 也支援透過第三方 API 提供者進行身份驗證:

91 

92 * **Amazon Bedrock**:設定 `CLAUDE_CODE_USE_BEDROCK=1` 環境變數並配置 AWS 認證

93 * **Google Vertex AI**:設定 `CLAUDE_CODE_USE_VERTEX=1` 環境變數並配置 Google Cloud 認證

94 * **Microsoft Azure**:設定 `CLAUDE_CODE_USE_FOUNDRY=1` 環境變數並配置 Azure 認證

95 

96 有關詳細資訊,請參閱 [Bedrock](/zh-TW/amazon-bedrock)、[Vertex AI](/zh-TW/google-vertex-ai) 或 [Azure AI Foundry](/zh-TW/microsoft-foundry) 的設定指南。

97 

98 <Note>

99 除非事先獲得批准,否則 Anthropic 不允許第三方開發人員為其產品(包括基於 Claude Agent SDK 構建的代理)提供 claude.ai 登入或速率限制。請改用本文件中描述的 API 金鑰身份驗證方法。

100 </Note>

101 </Step>

102 

103 <Step title="執行您的第一個代理">

104 此範例建立一個使用內建工具列出目前目錄中檔案的代理。

105 

106 <CodeGroup>

107 ```python Python theme={null}

108 import asyncio

109 from claude_agent_sdk import query, ClaudeAgentOptions

110 

111 

112 async def main():

113 async for message in query(

114 prompt="What files are in this directory?",

115 options=ClaudeAgentOptions(allowed_tools=["Bash", "Glob"]),

116 ):

117 if hasattr(message, "result"):

118 print(message.result)

119 

120 

121 asyncio.run(main())

122 ```

123 

124 ```typescript TypeScript theme={null}

125 import { query } from "@anthropic-ai/claude-agent-sdk";

126 

127 for await (const message of query({

128 prompt: "What files are in this directory?",

129 options: { allowedTools: ["Bash", "Glob"] }

130 })) {

131 if ("result" in message) console.log(message.result);

132 }

133 ```

134 </CodeGroup>

135 </Step>

136</Steps>

137 

138**準備好構建了嗎?** 遵循[快速入門](/zh-TW/agent-sdk/quickstart)在幾分鐘內建立一個尋找和修復錯誤的代理。

139 

140## 功能

141 

142使 Claude Code 強大的一切都可在 SDK 中使用:

143 

144<Tabs>

145 <Tab title="內建工具">

146 您的代理可以開箱即用地讀取檔案、執行命令和搜尋程式碼庫。主要工具包括:

147 

148 | 工具 | 功能 |

149 | ------------------------------------------------------------------------------ | -------------------------------- |

150 | **Read** | 讀取工作目錄中的任何檔案 |

151 | **Write** | 建立新檔案 |

152 | **Edit** | 對現有檔案進行精確編輯 |

153 | **Bash** | 執行終端命令、指令碼、git 操作 |

154 | **Monitor** | 監視背景指令碼並對每個輸出行作為事件做出反應 |

155 | **Glob** | 按模式尋找檔案(`**/*.ts`、`src/**/*.py`) |

156 | **Grep** | 使用正規表達式搜尋檔案內容 |

157 | **WebSearch** | 搜尋網路以獲取最新資訊 |

158 | **WebFetch** | 擷取並解析網頁內容 |

159 | **[AskUserQuestion](/zh-TW/agent-sdk/user-input#handle-clarifying-questions)** | 向使用者提出具有多選選項的澄清問題 |

160 

161 此範例建立一個搜尋程式碼庫中 TODO 註解的代理:

162 

163 <CodeGroup>

164 ```python Python theme={null}

165 import asyncio

166 from claude_agent_sdk import query, ClaudeAgentOptions

167 

168 

169 async def main():

170 async for message in query(

171 prompt="Find all TODO comments and create a summary",

172 options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"]),

173 ):

174 if hasattr(message, "result"):

175 print(message.result)

176 

177 

178 asyncio.run(main())

179 ```

180 

181 ```typescript TypeScript theme={null}

182 import { query } from "@anthropic-ai/claude-agent-sdk";

183 

184 for await (const message of query({

185 prompt: "Find all TODO comments and create a summary",

186 options: { allowedTools: ["Read", "Glob", "Grep"] }

187 })) {

188 if ("result" in message) console.log(message.result);

189 }

190 ```

191 </CodeGroup>

192 </Tab>

193 

194 <Tab title="Hooks">

195 在代理生命週期的關鍵點執行自訂程式碼。SDK hooks 使用回呼函式來驗證、記錄、阻止或轉換代理行為。

196 

197 **可用 hooks:** `PreToolUse`、`PostToolUse`、`Stop`、`SessionStart`、`SessionEnd`、`UserPromptSubmit` 等。

198 

199 此範例將所有檔案變更記錄到稽核檔案:

200 

201 <CodeGroup>

202 ```python Python theme={null}

203 import asyncio

204 from datetime import datetime

205 from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher

206 

207 

208 async def log_file_change(input_data, tool_use_id, context):

209 file_path = input_data.get("tool_input", {}).get("file_path", "unknown")

210 with open("./audit.log", "a") as f:

211 f.write(f"{datetime.now()}: modified {file_path}\n")

212 return {}

213 

214 

215 async def main():

216 async for message in query(

217 prompt="Refactor utils.py to improve readability",

218 options=ClaudeAgentOptions(

219 permission_mode="acceptEdits",

220 hooks={

221 "PostToolUse": [

222 HookMatcher(matcher="Edit|Write", hooks=[log_file_change])

223 ]

224 },

225 ),

226 ):

227 if hasattr(message, "result"):

228 print(message.result)

229 

230 

231 asyncio.run(main())

232 ```

233 

234 ```typescript TypeScript theme={null}

235 import { query, HookCallback } from "@anthropic-ai/claude-agent-sdk";

236 import { appendFile } from "fs/promises";

237 

238 const logFileChange: HookCallback = async (input) => {

239 const filePath = (input as any).tool_input?.file_path ?? "unknown";

240 await appendFile("./audit.log", `${new Date().toISOString()}: modified ${filePath}\n`);

241 return {};

242 };

243 

244 for await (const message of query({

245 prompt: "Refactor utils.py to improve readability",

246 options: {

247 permissionMode: "acceptEdits",

248 hooks: {

249 PostToolUse: [{ matcher: "Edit|Write", hooks: [logFileChange] }]

250 }

251 }

252 })) {

253 if ("result" in message) console.log(message.result);

254 }

255 ```

256 </CodeGroup>

257 

258 [深入了解 hooks →](/zh-TW/agent-sdk/hooks)

259 </Tab>

260 

261 <Tab title="子代理">

262 生成專門的代理來處理集中的子任務。您的主代理委派工作,子代理報告結果。

263 

264 定義具有專門指令的自訂代理。在 `allowedTools` 中包含 `Agent`,因為子代理透過 Agent 工具呼叫:

265 

266 <CodeGroup>

267 ```python Python theme={null}

268 import asyncio

269 from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

270 

271 

272 async def main():

273 async for message in query(

274 prompt="Use the code-reviewer agent to review this codebase",

275 options=ClaudeAgentOptions(

276 allowed_tools=["Read", "Glob", "Grep", "Agent"],

277 agents={

278 "code-reviewer": AgentDefinition(

279 description="Expert code reviewer for quality and security reviews.",

280 prompt="Analyze code quality and suggest improvements.",

281 tools=["Read", "Glob", "Grep"],

282 )

283 },

284 ),

285 ):

286 if hasattr(message, "result"):

287 print(message.result)

288 

289 

290 asyncio.run(main())

291 ```

292 

293 ```typescript TypeScript theme={null}

294 import { query } from "@anthropic-ai/claude-agent-sdk";

295 

296 for await (const message of query({

297 prompt: "Use the code-reviewer agent to review this codebase",

298 options: {

299 allowedTools: ["Read", "Glob", "Grep", "Agent"],

300 agents: {

301 "code-reviewer": {

302 description: "Expert code reviewer for quality and security reviews.",

303 prompt: "Analyze code quality and suggest improvements.",

304 tools: ["Read", "Glob", "Grep"]

305 }

306 }

307 }

308 })) {

309 if ("result" in message) console.log(message.result);

310 }

311 ```

312 </CodeGroup>

313 

314 來自子代理上下文內的訊息包含 `parent_tool_use_id` 欄位,讓您追蹤哪些訊息屬於哪個子代理執行。

315 

316 [深入了解子代理 →](/zh-TW/agent-sdk/subagents)

317 </Tab>

318 

319 <Tab title="MCP">

320 透過 Model Context Protocol 連接到外部系統:資料庫、瀏覽器、API 和[數百個更多](https://github.com/modelcontextprotocol/servers)。

321 

322 此範例連接 [Playwright MCP 伺服器](https://github.com/microsoft/playwright-mcp)以為您的代理提供瀏覽器自動化功能:

323 

324 <CodeGroup>

325 ```python Python theme={null}

326 import asyncio

327 from claude_agent_sdk import query, ClaudeAgentOptions

328 

329 

330 async def main():

331 async for message in query(

332 prompt="Open example.com and describe what you see",

333 options=ClaudeAgentOptions(

334 mcp_servers={

335 "playwright": {"command": "npx", "args": ["@playwright/mcp@latest"]}

336 }

337 ),

338 ):

339 if hasattr(message, "result"):

340 print(message.result)

341 

342 

343 asyncio.run(main())

344 ```

345 

346 ```typescript TypeScript theme={null}

347 import { query } from "@anthropic-ai/claude-agent-sdk";

348 

349 for await (const message of query({

350 prompt: "Open example.com and describe what you see",

351 options: {

352 mcpServers: {

353 playwright: { command: "npx", args: ["@playwright/mcp@latest"] }

354 }

355 }

356 })) {

357 if ("result" in message) console.log(message.result);

358 }

359 ```

360 </CodeGroup>

361 

362 [深入了解 MCP →](/zh-TW/agent-sdk/mcp)

363 </Tab>

364 

365 <Tab title="權限">

366 精確控制您的代理可以使用哪些工具。允許安全操作、阻止危險操作或要求對敏感操作進行批准。

367 

368 <Note>

369 有關互動式批准提示和 `AskUserQuestion` 工具,請參閱[處理批准和使用者輸入](/zh-TW/agent-sdk/user-input)。

370 </Note>

371 

372 此範例建立一個唯讀代理,可以分析但不能修改程式碼。`allowed_tools` 預先批准 `Read`、`Glob` 和 `Grep`。

373 

374 <CodeGroup>

375 ```python Python theme={null}

376 import asyncio

377 from claude_agent_sdk import query, ClaudeAgentOptions

378 

379 

380 async def main():

381 async for message in query(

382 prompt="Review this code for best practices",

383 options=ClaudeAgentOptions(

384 allowed_tools=["Read", "Glob", "Grep"],

385 ),

386 ):

387 if hasattr(message, "result"):

388 print(message.result)

389 

390 

391 asyncio.run(main())

392 ```

393 

394 ```typescript TypeScript theme={null}

395 import { query } from "@anthropic-ai/claude-agent-sdk";

396 

397 for await (const message of query({

398 prompt: "Review this code for best practices",

399 options: {

400 allowedTools: ["Read", "Glob", "Grep"]

401 }

402 })) {

403 if ("result" in message) console.log(message.result);

404 }

405 ```

406 </CodeGroup>

407 

408 [深入了解權限 →](/zh-TW/agent-sdk/permissions)

409 </Tab>

410 

411 <Tab title="工作階段">

412 在多次交換中保持上下文。Claude 記住讀取的檔案、完成的分析和對話歷史。稍後恢復工作階段,或分叉它們以探索不同的方法。

413 

414 此範例從第一個查詢中擷取工作階段 ID,然後恢復以繼續進行完整上下文:

415 

416 <CodeGroup>

417 ```python Python theme={null}

418 import asyncio

419 from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage, ResultMessage

420 

421 

422 async def main():

423 session_id = None

424 

425 # First query: capture the session ID

426 async for message in query(

427 prompt="Read the authentication module",

428 options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"]),

429 ):

430 if isinstance(message, SystemMessage) and message.subtype == "init":

431 session_id = message.data["session_id"]

432 

433 # Resume with full context from the first query

434 async for message in query(

435 prompt="Now find all places that call it", # "it" = auth module

436 options=ClaudeAgentOptions(resume=session_id),

437 ):

438 if isinstance(message, ResultMessage):

439 print(message.result)

440 

441 

442 asyncio.run(main())

443 ```

444 

445 ```typescript TypeScript theme={null}

446 import { query } from "@anthropic-ai/claude-agent-sdk";

447 

448 let sessionId: string | undefined;

449 

450 // First query: capture the session ID

451 for await (const message of query({

452 prompt: "Read the authentication module",

453 options: { allowedTools: ["Read", "Glob"] }

454 })) {

455 if (message.type === "system" && message.subtype === "init") {

456 sessionId = message.session_id;

457 }

458 }

459 

460 // Resume with full context from the first query

461 for await (const message of query({

462 prompt: "Now find all places that call it", // "it" = auth module

463 options: { resume: sessionId }

464 })) {

465 if ("result" in message) console.log(message.result);

466 }

467 ```

468 </CodeGroup>

469 

470 [深入了解工作階段 →](/zh-TW/agent-sdk/sessions)

471 </Tab>

472</Tabs>

473 

474### Claude Code 功能

475 

476SDK 也支援 Claude Code 的基於檔案系統的配置。使用預設選項,SDK 從工作目錄中的 `.claude/` 和 `~/.claude/` 載入這些。要限制載入哪些來源,請在選項中設定 `setting_sources`(Python)或 `settingSources`(TypeScript)。

477 

478| 功能 | 描述 | 位置 |

479| --------------------------------------------------- | ---------------------- | --------------------------------- |

480| [Skills](/zh-TW/agent-sdk/skills) | 在 Markdown 中定義的專門功能 | `.claude/skills/*/SKILL.md` |

481| [Slash commands](/zh-TW/agent-sdk/slash-commands) | 用於常見任務的自訂命令 | `.claude/commands/*.md` |

482| [Memory](/zh-TW/agent-sdk/modifying-system-prompts) | 專案上下文和指令 | `CLAUDE.md` 或 `.claude/CLAUDE.md` |

483| [Plugins](/zh-TW/agent-sdk/plugins) | 使用自訂命令、代理和 MCP 伺服器進行擴展 | 透過 `plugins` 選項進行程式設計 |

484 

485## 將 Agent SDK 與其他 Claude 工具進行比較

486 

487Claude 平台提供多種方式來使用 Claude 進行構建。以下是 Agent SDK 的適用方式:

488 

489<Tabs>

490 <Tab title="Agent SDK vs Client SDK">

491 [Anthropic Client SDK](https://platform.claude.com/docs/zh-TW/api/client-sdks) 為您提供直接 API 存取:您傳送提示並自己實現工具執行。**Agent SDK** 為您提供具有內建工具執行的 Claude。

492 

493 使用 Client SDK,您實現工具迴圈。使用 Agent SDK,Claude 處理它:

494 

495 <CodeGroup>

496 ```python Python theme={null}

497 # Client SDK: You implement the tool loop

498 response = client.messages.create(...)

499 while response.stop_reason == "tool_use":

500 result = your_tool_executor(response.tool_use)

501 response = client.messages.create(tool_result=result, **params)

502 

503 # Agent SDK: Claude handles tools autonomously

504 async for message in query(prompt="Fix the bug in auth.py"):

505 print(message)

506 ```

507 

508 ```typescript TypeScript theme={null}

509 // Client SDK: You implement the tool loop

510 let response = await client.messages.create({ ...params });

511 while (response.stop_reason === "tool_use") {

512 const result = yourToolExecutor(response.tool_use);

513 response = await client.messages.create({ tool_result: result, ...params });

514 }

515 

516 // Agent SDK: Claude handles tools autonomously

517 for await (const message of query({ prompt: "Fix the bug in auth.ts" })) {

518 console.log(message);

519 }

520 ```

521 </CodeGroup>

522 </Tab>

523 

524 <Tab title="Agent SDK vs Claude Code CLI">

525 相同的功能,不同的介面:

526 

527 | 使用案例 | 最佳選擇 |

528 | -------- | ---- |

529 | 互動式開發 | CLI |

530 | CI/CD 管道 | SDK |

531 | 自訂應用程式 | SDK |

532 | 一次性任務 | CLI |

533 | 生產自動化 | SDK |

534 

535 許多團隊同時使用兩者:CLI 用於日常開發,SDK 用於生產。工作流程在它們之間直接轉換。

536 </Tab>

537 

538 <Tab title="Agent SDK vs Managed Agents">

539 [Managed Agents](https://platform.claude.com/docs/zh-TW/managed-agents/overview) 是一個託管的 REST API:Anthropic 執行代理和沙箱,您的應用程式傳送事件並串流回結果。**Agent SDK** 是一個在您自己的流程內執行代理迴圈的程式庫。

540 

541 | | Agent SDK | Managed Agents |

542 | ---------- | -------------------------- | --------------------------------- |

543 | **執行位置** | 您的流程、您的基礎設施 | Anthropic 管理的基礎設施 |

544 | **介面** | Python 或 TypeScript 程式庫 | REST API |

545 | **代理工作於** | 您基礎設施上的檔案 | 每個工作階段的託管沙箱 |

546 | **工作階段狀態** | 您檔案系統上的 JSONL | Anthropic 託管的事件日誌 |

547 | **自訂工具** | 進程內 Python 或 TypeScript 函數 | Claude 觸發工具;您執行並返回結果 |

548 | **最適合** | 本地原型設計、直接在您的檔案系統和服務上工作的代理 | 生產代理,無需操作沙箱或工作階段基礎設施、長期執行和非同步工作階段 |

549 

550 常見的路徑是先使用 Agent SDK 在本地進行原型設計,然後移至 Managed Agents 進行生產。

551 </Tab>

552</Tabs>

553 

554## 變更日誌

555 

556查看完整的變更日誌以了解 SDK 更新、錯誤修復和新功能:

557 

558* **TypeScript SDK**:[檢視 CHANGELOG.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md)

559* **Python SDK**:[檢視 CHANGELOG.md](https://github.com/anthropics/claude-agent-sdk-python/blob/main/CHANGELOG.md)

560 

561## 報告錯誤

562 

563如果您遇到 Agent SDK 的錯誤或問題:

564 

565* **TypeScript SDK**:[在 GitHub 上報告問題](https://github.com/anthropics/claude-agent-sdk-typescript/issues)

566* **Python SDK**:[在 GitHub 上報告問題](https://github.com/anthropics/claude-agent-sdk-python/issues)

567 

568## 品牌指南

569 

570對於整合 Claude Agent SDK 的合作夥伴,使用 Claude 品牌是可選的。在您的產品中引用 Claude 時:

571 

572**允許:**

573 

574* "Claude Agent"(下拉選單的首選)

575* "Claude"(當已在標記為"Agents"的選單中時)

576* "{YourAgentName} Powered by Claude"(如果您有現有的代理名稱)

577 

578**不允許:**

579 

580* "Claude Code" 或 "Claude Code Agent"

581* Claude Code 品牌的 ASCII 藝術或模仿 Claude Code 的視覺元素

582 

583您的產品應保持自己的品牌,不應顯示為 Claude Code 或任何 Anthropic 產品。有關品牌合規性的問題,請聯絡 Anthropic [銷售團隊](https://www.anthropic.com/contact-sales)。

584 

585## 許可證和條款

586 

587Claude Agent SDK 的使用受 [Anthropic 商業服務條款](https://www.anthropic.com/legal/commercial-terms)管制,包括當您使用它為您自己的客戶和最終使用者提供的產品和服務提供動力時,除非特定元件或依賴項受到該元件 LICENSE 檔案中指示的不同許可證的保護。

588 

589## 後續步驟

590 

591<CardGroup cols={2}>

592 <Card title="快速入門" icon="play" href="/zh-TW/agent-sdk/quickstart">

593 構建在幾分鐘內尋找和修復錯誤的代理

594 </Card>

595 

596 <Card title="範例代理" icon="star" href="https://github.com/anthropics/claude-agent-sdk-demos">

597 電子郵件助手、研究代理等

598 </Card>

599 

600 <Card title="TypeScript SDK" icon="code" href="/zh-TW/agent-sdk/typescript">

601 完整的 TypeScript API 參考和範例

602 </Card>

603 

604 <Card title="Python SDK" icon="code" href="/zh-TW/agent-sdk/python">

605 完整的 Python API 參考和範例

606 </Card>

607</CardGroup>

agent-sdk/plugins.md +342 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# SDK 中的 Plugins

6 

7> 通過 Agent SDK 加載自訂 plugins,以使用命令、agents、skills 和 hooks 擴展 Claude Code

8 

9Plugins 允許您使用可在專案間共享的自訂功能來擴展 Claude Code。通過 Agent SDK,您可以以程式方式從本地目錄加載 plugins,以將自訂 slash commands、agents、skills、hooks 和 MCP servers 添加到您的 agent sessions。

10 

11## 什麼是 plugins?

12 

13Plugins 是 Claude Code 擴展的套件,可以包括:

14 

15* **Skills**:Claude 自主使用的模型調用功能(也可以使用 `/skill-name` 調用)

16* **Agents**:用於特定任務的專門子 agents

17* **Hooks**:響應工具使用和其他事件的事件處理程序

18* **MCP servers**:通過 Model Context Protocol 的外部工具集成

19 

20<Note>

21 `commands/` 目錄是舊版格式。對於新 plugins,請使用 `skills/`。Claude Code 繼續支持兩種格式以實現向後相容性。

22</Note>

23 

24有關 plugin 結構和如何創建 plugins 的完整信息,請參閱 [Plugins](/zh-TW/plugins)。

25 

26## 加載 plugins

27 

28通過在選項配置中提供本地文件系統路徑來加載 plugins。`type` 字段必須是 `"local"`,這是 SDK 接受的唯一值。要使用通過 [marketplace](/zh-TW/plugin-marketplaces) 或遠程存儲庫分發的 plugin,請先下載它並提供本地目錄路徑。SDK 支持從不同位置加載多個 plugins。

29 

30<CodeGroup>

31 ```typescript TypeScript theme={null}

32 import { query } from "@anthropic-ai/claude-agent-sdk";

33 

34 for await (const message of query({

35 prompt: "Hello",

36 options: {

37 plugins: [

38 { type: "local", path: "./my-plugin" },

39 { type: "local", path: "/absolute/path/to/another-plugin" }

40 ]

41 }

42 })) {

43 // Plugin commands, agents, and other features are now available

44 }

45 ```

46 

47 ```python Python theme={null}

48 import asyncio

49 from claude_agent_sdk import query

50 

51 

52 async def main():

53 async for message in query(

54 prompt="Hello",

55 options={

56 "plugins": [

57 {"type": "local", "path": "./my-plugin"},

58 {"type": "local", "path": "/absolute/path/to/another-plugin"},

59 ]

60 },

61 ):

62 # Plugin commands, agents, and other features are now available

63 pass

64 

65 

66 asyncio.run(main())

67 ```

68</CodeGroup>

69 

70### 路徑規範

71 

72Plugin 路徑可以是:

73 

74* **相對路徑**:相對於您的當前工作目錄解析(例如,`"./plugins/my-plugin"`)

75* **絕對路徑**:完整文件系統路徑(例如,`"/home/user/plugins/my-plugin"`)

76 

77<Note>

78 路徑應指向 plugin 的根目錄(包含 `.claude-plugin/plugin.json` 的目錄)。

79</Note>

80 

81## 驗證 plugin 安裝

82 

83當 plugins 成功加載時,它們會出現在系統初始化消息中。您可以驗證您的 plugins 是否可用:

84 

85<CodeGroup>

86 ```typescript TypeScript theme={null}

87 import { query } from "@anthropic-ai/claude-agent-sdk";

88 

89 for await (const message of query({

90 prompt: "Hello",

91 options: {

92 plugins: [{ type: "local", path: "./my-plugin" }]

93 }

94 })) {

95 if (message.type === "system" && message.subtype === "init") {

96 // Check loaded plugins

97 console.log("Plugins:", message.plugins);

98 // Example: [{ name: "my-plugin", path: "./my-plugin" }]

99 

100 // Check available commands from plugins

101 console.log("Commands:", message.slash_commands);

102 // Example: ["/help", "/compact", "my-plugin:custom-command"]

103 }

104 }

105 ```

106 

107 ```python Python theme={null}

108 import asyncio

109 from claude_agent_sdk import query

110 

111 

112 async def main():

113 async for message in query(

114 prompt="Hello", options={"plugins": [{"type": "local", "path": "./my-plugin"}]}

115 ):

116 if message.type == "system" and message.subtype == "init":

117 # Check loaded plugins

118 print("Plugins:", message.data.get("plugins"))

119 # Example: [{"name": "my-plugin", "path": "./my-plugin"}]

120 

121 # Check available commands from plugins

122 print("Commands:", message.data.get("slash_commands"))

123 # Example: ["/help", "/compact", "my-plugin:custom-command"]

124 

125 

126 asyncio.run(main())

127 ```

128</CodeGroup>

129 

130## 使用 plugin skills

131 

132來自 plugins 的 skills 會自動使用 plugin 名稱進行命名空間化,以避免衝突。當作為 slash commands 調用時,格式為 `plugin-name:skill-name`。

133 

134<CodeGroup>

135 ```typescript TypeScript theme={null}

136 import { query } from "@anthropic-ai/claude-agent-sdk";

137 

138 // Load a plugin with a custom /greet skill

139 for await (const message of query({

140 prompt: "/my-plugin:greet", // Use plugin skill with namespace

141 options: {

142 plugins: [{ type: "local", path: "./my-plugin" }]

143 }

144 })) {

145 // Claude executes the custom greeting skill from the plugin

146 if (message.type === "assistant") {

147 console.log(message.message.content);

148 }

149 }

150 ```

151 

152 ```python Python theme={null}

153 import asyncio

154 from claude_agent_sdk import query, AssistantMessage, TextBlock

155 

156 

157 async def main():

158 # Load a plugin with a custom /greet skill

159 async for message in query(

160 prompt="/demo-plugin:greet", # Use plugin skill with namespace

161 options={"plugins": [{"type": "local", "path": "./plugins/demo-plugin"}]},

162 ):

163 # Claude executes the custom greeting skill from the plugin

164 if isinstance(message, AssistantMessage):

165 for block in message.content:

166 if isinstance(block, TextBlock):

167 print(f"Claude: {block.text}")

168 

169 

170 asyncio.run(main())

171 ```

172</CodeGroup>

173 

174<Note>

175 如果您通過 CLI 安裝了 plugin(例如,`/plugin install my-plugin@marketplace`),您仍然可以通過提供其安裝路徑在 SDK 中使用它。檢查 `~/.claude/plugins/` 以查找 CLI 安裝的 plugins。

176</Note>

177 

178## 完整示例

179 

180以下是演示 plugin 加載和使用的完整示例:

181 

182<CodeGroup>

183 ```typescript TypeScript theme={null}

184 import { query } from "@anthropic-ai/claude-agent-sdk";

185 import * as path from "path";

186 

187 async function runWithPlugin() {

188 const pluginPath = path.join(__dirname, "plugins", "my-plugin");

189 

190 console.log("Loading plugin from:", pluginPath);

191 

192 for await (const message of query({

193 prompt: "What custom commands do you have available?",

194 options: {

195 plugins: [{ type: "local", path: pluginPath }],

196 maxTurns: 3

197 }

198 })) {

199 if (message.type === "system" && message.subtype === "init") {

200 console.log("Loaded plugins:", message.plugins);

201 console.log("Available commands:", message.slash_commands);

202 }

203 

204 if (message.type === "assistant") {

205 console.log("Assistant:", message.message.content);

206 }

207 }

208 }

209 

210 runWithPlugin().catch(console.error);

211 ```

212 

213 ```python Python theme={null}

214 #!/usr/bin/env python3

215 """Example demonstrating how to use plugins with the Agent SDK."""

216 

217 from pathlib import Path

218 import anyio

219 from claude_agent_sdk import (

220 AssistantMessage,

221 ClaudeAgentOptions,

222 TextBlock,

223 query,

224 )

225 

226 

227 async def run_with_plugin():

228 """Example using a custom plugin."""

229 plugin_path = Path(__file__).parent / "plugins" / "demo-plugin"

230 

231 print(f"Loading plugin from: {plugin_path}")

232 

233 options = ClaudeAgentOptions(

234 plugins=[{"type": "local", "path": str(plugin_path)}],

235 max_turns=3,

236 )

237 

238 async for message in query(

239 prompt="What custom commands do you have available?", options=options

240 ):

241 if message.type == "system" and message.subtype == "init":

242 print(f"Loaded plugins: {message.data.get('plugins')}")

243 print(f"Available commands: {message.data.get('slash_commands')}")

244 

245 if isinstance(message, AssistantMessage):

246 for block in message.content:

247 if isinstance(block, TextBlock):

248 print(f"Assistant: {block.text}")

249 

250 

251 if __name__ == "__main__":

252 anyio.run(run_with_plugin)

253 ```

254</CodeGroup>

255 

256## Plugin 結構參考

257 

258Plugin 目錄必須包含 `.claude-plugin/plugin.json` 清單文件。它可以選擇性地包括:

259 

260```text theme={null}

261my-plugin/

262├── .claude-plugin/

263│ └── plugin.json # Required: plugin manifest

264├── skills/ # Agent Skills (invoked autonomously or via /skill-name)

265│ └── my-skill/

266│ └── SKILL.md

267├── commands/ # Legacy: use skills/ instead

268│ └── custom-cmd.md

269├── agents/ # Custom agents

270│ └── specialist.md

271├── hooks/ # Event handlers

272│ └── hooks.json

273└── .mcp.json # MCP server definitions

274```

275 

276有關創建 plugins 的詳細信息,請參閱:

277 

278* [Plugins](/zh-TW/plugins) - 完整的 plugin 開發指南

279* [Plugins reference](/zh-TW/plugins-reference) - 技術規範和架構

280 

281## 常見用例

282 

283### 開發和測試

284 

285在開發期間加載 plugins,無需全局安裝它們:

286 

287```typescript theme={null}

288plugins: [{ type: "local", path: "./dev-plugins/my-plugin" }];

289```

290 

291### 專案特定的擴展

292 

293在您的專案存儲庫中包含 plugins,以實現團隊範圍的一致性:

294 

295```typescript theme={null}

296plugins: [{ type: "local", path: "./project-plugins/team-workflows" }];

297```

298 

299### 多個 plugin 來源

300 

301結合來自不同位置的 plugins:

302 

303```typescript theme={null}

304plugins: [

305 { type: "local", path: "./local-plugin" },

306 { type: "local", path: "~/.claude/custom-plugins/shared-plugin" }

307];

308```

309 

310## Troubleshooting

311 

312### Plugin 未加載

313 

314如果您的 plugin 未出現在初始化消息中:

315 

3161. **檢查路徑**:確保路徑指向 plugin 根目錄(包含 `.claude-plugin/`)

3172. **驗證 plugin.json**:確保您的清單文件具有有效的 JSON 語法

3183. **檢查文件權限**:確保 plugin 目錄可讀

319 

320### Skills 未出現

321 

322如果 plugin skills 不起作用:

323 

3241. **使用命名空間**:Plugin skills 在作為 slash commands 調用時需要 `plugin-name:skill-name` 格式

3252. **檢查初始化消息**:驗證 skill 是否以正確的命名空間出現在 `slash_commands` 中

3263. **驗證 skill 文件**:確保每個 skill 在 `skills/` 下的自己的子目錄中都有 `SKILL.md` 文件(例如,`skills/my-skill/SKILL.md`)

327 

328### 路徑解析問題

329 

330如果相對路徑不起作用:

331 

3321. **檢查工作目錄**:相對路徑從您的當前工作目錄解析

3332. **使用絕對路徑**:為了可靠性,請考慮使用絕對路徑

3343. **規範化路徑**:使用路徑實用程序正確構造路徑

335 

336## 另請參閱

337 

338* [Plugins](/zh-TW/plugins) - 完整的 plugin 開發指南

339* [Plugins reference](/zh-TW/plugins-reference) - 技術規範

340* [Slash Commands](/zh-TW/agent-sdk/slash-commands) - 在 SDK 中使用 slash commands

341* [Subagents](/zh-TW/agent-sdk/subagents) - 使用專門的 agents

342* [Skills](/zh-TW/agent-sdk/skills) - 使用 Agent Skills

agent-sdk/python.md +3274 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Agent SDK 參考 - Python

6 

7> Python Agent SDK 的完整 API 參考,包括所有函數、類型和類別。

8 

9## 安裝

10 

11```bash theme={null}

12pip install claude-agent-sdk

13```

14 

15## 在 `query()` 和 `ClaudeSDKClient` 之間選擇

16 

17Python SDK 提供了兩種與 Claude Code 互動的方式:

18 

19### 快速比較

20 

21| 功能 | `query()` | `ClaudeSDKClient` |

22| :------------------ | :------------ | :---------------- |

23| **Session** | 每次建立新 session | 重複使用相同 session |

24| **Conversation** | 單一交換 | 同一上下文中的多個交換 |

25| **Connection** | 自動管理 | 手動控制 |

26| **Streaming Input** | ✅ 支援 | ✅ 支援 |

27| **Interrupts** | ❌ 不支援 | ✅ 支援 |

28| **Hooks** | ✅ 支援 | ✅ 支援 |

29| **Custom Tools** | ✅ 支援 | ✅ 支援 |

30| **Continue Chat** | ❌ 每次新 session | ✅ 維持對話 |

31| **Use Case** | 一次性任務 | 持續對話 |

32 

33### 何時使用 `query()`(每次新 session)

34 

35**最適合:**

36 

37* 一次性問題,不需要對話歷史

38* 不需要先前交換上下文的獨立任務

39* 簡單的自動化腳本

40* 當您想每次都重新開始時

41 

42### 何時使用 `ClaudeSDKClient`(持續對話)

43 

44**最適合:**

45 

46* **繼續對話** - 當您需要 Claude 記住上下文時

47* **後續問題** - 基於先前回應進行構建

48* **互動式應用程式** - 聊天介面、REPL

49* **回應驅動邏輯** - 當下一個動作取決於 Claude 的回應時

50* **Session 控制** - 明確管理對話生命週期

51 

52## 函數

53 

54### `query()`

55 

56為每次與 Claude Code 的互動建立新 session。返回一個非同步迭代器,在消息到達時產生消息。每次呼叫 `query()` 都會重新開始,不記得先前的互動。

57 

58```python theme={null}

59async def query(

60 *,

61 prompt: str | AsyncIterable[dict[str, Any]],

62 options: ClaudeAgentOptions | None = None,

63 transport: Transport | None = None

64) -> AsyncIterator[Message]

65```

66 

67#### 參數

68 

69| 參數 | 類型 | 描述 |

70| :---------- | :--------------------------- | :------------------------------------------ |

71| `prompt` | `str \| AsyncIterable[dict]` | 輸入提示,可以是字串或非同步可迭代物件(用於串流模式) |

72| `options` | `ClaudeAgentOptions \| None` | 可選配置物件(如果為 None,預設為 `ClaudeAgentOptions()`) |

73| `transport` | `Transport \| None` | 用於與 CLI 程序通訊的可選自訂傳輸 |

74 

75#### 返回

76 

77返回 `AsyncIterator[Message]`,從對話中產生消息。

78 

79#### 範例 - 使用選項

80 

81```python theme={null}

82import asyncio

83from claude_agent_sdk import query, ClaudeAgentOptions

84 

85 

86async def main():

87 options = ClaudeAgentOptions(

88 system_prompt="You are an expert Python developer",

89 permission_mode="acceptEdits",

90 cwd="/home/user/project",

91 )

92 

93 async for message in query(prompt="Create a Python web server", options=options):

94 print(message)

95 

96 

97asyncio.run(main())

98```

99 

100### `tool()`

101 

102用於定義具有類型安全的 MCP tools 的裝飾器。

103 

104```python theme={null}

105def tool(

106 name: str,

107 description: str,

108 input_schema: type | dict[str, Any],

109 annotations: ToolAnnotations | None = None

110) -> Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]

111```

112 

113#### 參數

114 

115| 參數 | 類型 | 描述 |

116| :------------- | :----------------------------------------------- | :------------------------- |

117| `name` | `str` | tool 的唯一識別碼 |

118| `description` | `str` | tool 功能的人類可讀描述 |

119| `input_schema` | `type \| dict[str, Any]` | 定義 tool 輸入參數的架構(見下文) |

120| `annotations` | [`ToolAnnotations`](#tool-annotations)` \| None` | 可選的 MCP tool 註解,為客戶端提供行為提示 |

121 

122#### 輸入架構選項

123 

1241. **簡單類型對應**(推薦):

125 

126 ```python theme={null}

127 {"text": str, "count": int, "enabled": bool}

128 ```

129 

1302. **JSON Schema 格式**(用於複雜驗證):

131 ```python theme={null}

132 {

133 "type": "object",

134 "properties": {

135 "text": {"type": "string"},

136 "count": {"type": "integer", "minimum": 0},

137 },

138 "required": ["text"],

139 }

140 ```

141 

142#### 返回

143 

144一個裝飾器函數,包裝 tool 實現並返回 `SdkMcpTool` 實例。

145 

146#### 範例

147 

148```python theme={null}

149from claude_agent_sdk import tool

150from typing import Any

151 

152 

153@tool("greet", "Greet a user", {"name": str})

154async def greet(args: dict[str, Any]) -> dict[str, Any]:

155 return {"content": [{"type": "text", "text": f"Hello, {args['name']}!"}]}

156```

157 

158#### `ToolAnnotations`

159 

160從 `mcp.types` 重新匯出(也可以從 `claude_agent_sdk` 匯入)。所有欄位都是可選提示;客戶端不應依賴它們進行安全決策。

161 

162| 欄位 | 類型 | 預設 | 描述 |

163| :---------------- | :------------- | :------ | :------------------------------------------------------------------ |

164| `title` | `str \| None` | `None` | tool 的人類可讀標題 |

165| `readOnlyHint` | `bool \| None` | `False` | 如果為 `True`,tool 不會修改其環境 |

166| `destructiveHint` | `bool \| None` | `True` | 如果為 `True`,tool 可能執行破壞性更新(僅在 `readOnlyHint` 為 `False` 時有意義) |

167| `idempotentHint` | `bool \| None` | `False` | 如果為 `True`,使用相同參數的重複呼叫沒有額外效果(僅在 `readOnlyHint` 為 `False` 時有意義) |

168| `openWorldHint` | `bool \| None` | `True` | 如果為 `True`,tool 與外部實體互動(例如網路搜尋)。如果為 `False`,tool 的域是封閉的(例如記憶體 tool) |

169 

170```python theme={null}

171from claude_agent_sdk import tool, ToolAnnotations

172from typing import Any

173 

174 

175@tool(

176 "search",

177 "Search the web",

178 {"query": str},

179 annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True),

180)

181async def search(args: dict[str, Any]) -> dict[str, Any]:

182 return {"content": [{"type": "text", "text": f"Results for: {args['query']}"}]}

183```

184 

185### `create_sdk_mcp_server()`

186 

187建立在 Python 應用程式內執行的進程內 MCP 伺服器。

188 

189```python theme={null}

190def create_sdk_mcp_server(

191 name: str,

192 version: str = "1.0.0",

193 tools: list[SdkMcpTool[Any]] | None = None

194) -> McpSdkServerConfig

195```

196 

197#### 參數

198 

199| 參數 | 類型 | 預設 | 描述 |

200| :-------- | :------------------------------ | :-------- | :-------------------------- |

201| `name` | `str` | - | 伺服器的唯一識別碼 |

202| `version` | `str` | `"1.0.0"` | 伺服器版本字串 |

203| `tools` | `list[SdkMcpTool[Any]] \| None` | `None` | 使用 `@tool` 裝飾器建立的 tool 函數清單 |

204 

205#### 返回

206 

207返回 `McpSdkServerConfig` 物件,可以傳遞給 `ClaudeAgentOptions.mcp_servers`。

208 

209#### 範例

210 

211```python theme={null}

212from claude_agent_sdk import tool, create_sdk_mcp_server

213 

214 

215@tool("add", "Add two numbers", {"a": float, "b": float})

216async def add(args):

217 return {"content": [{"type": "text", "text": f"Sum: {args['a'] + args['b']}"}]}

218 

219 

220@tool("multiply", "Multiply two numbers", {"a": float, "b": float})

221async def multiply(args):

222 return {"content": [{"type": "text", "text": f"Product: {args['a'] * args['b']}"}]}

223 

224 

225calculator = create_sdk_mcp_server(

226 name="calculator",

227 version="2.0.0",

228 tools=[add, multiply], # Pass decorated functions

229)

230 

231# Use with Claude

232options = ClaudeAgentOptions(

233 mcp_servers={"calc": calculator},

234 allowed_tools=["mcp__calc__add", "mcp__calc__multiply"],

235)

236```

237 

238### `list_sessions()`

239 

240列出過去的 sessions 及其中繼資料。按專案目錄篩選或列出所有專案中的 sessions。同步;立即返回。

241 

242```python theme={null}

243def list_sessions(

244 directory: str | None = None,

245 limit: int | None = None,

246 include_worktrees: bool = True

247) -> list[SDKSessionInfo]

248```

249 

250#### 參數

251 

252| 參數 | 類型 | 預設 | 描述 |

253| :------------------ | :------------ | :----- | :---------------------------------------------------- |

254| `directory` | `str \| None` | `None` | 列出 sessions 的目錄。省略時,返回所有專案中的 sessions |

255| `limit` | `int \| None` | `None` | 返回的最大 sessions 數 |

256| `include_worktrees` | `bool` | `True` | 當 `directory` 在 git 儲存庫內時,包括所有 worktree 路徑中的 sessions |

257 

258#### 返回類型:`SDKSessionInfo`

259 

260| 屬性 | 類型 | 描述 |

261| :-------------- | :------------ | :--------------------------------------------------- |

262| `session_id` | `str` | 唯一 session 識別碼 |

263| `summary` | `str` | 顯示標題:自訂標題、自動生成的摘要或第一個提示 |

264| `last_modified` | `int` | 上次修改時間(自紀元以來的毫秒數) |

265| `file_size` | `int \| None` | Session 檔案大小(以位元組為單位)(遠端儲存後端為 `None`) |

266| `custom_title` | `str \| None` | 使用者設定的 session 標題 |

267| `first_prompt` | `str \| None` | session 中的第一個有意義的使用者提示 |

268| `git_branch` | `str \| None` | session 結束時的 Git 分支 |

269| `cwd` | `str \| None` | session 的工作目錄 |

270| `tag` | `str \| None` | 使用者設定的 session 標籤(見 [`tag_session()`](#tag-session)) |

271| `created_at` | `int \| None` | session 建立時間(自紀元以來的毫秒數) |

272 

273#### 範例

274 

275列印專案的 10 個最近 sessions。結果按 `last_modified` 降序排序,因此第一項是最新的。省略 `directory` 以搜尋所有專案。

276 

277```python theme={null}

278from claude_agent_sdk import list_sessions

279 

280for session in list_sessions(directory="/path/to/project", limit=10):

281 print(f"{session.summary} ({session.session_id})")

282```

283 

284### `get_session_messages()`

285 

286從過去的 session 中檢索消息。同步;立即返回。

287 

288```python theme={null}

289def get_session_messages(

290 session_id: str,

291 directory: str | None = None,

292 limit: int | None = None,

293 offset: int = 0

294) -> list[SessionMessage]

295```

296 

297#### 參數

298 

299| 參數 | 類型 | 預設 | 描述 |

300| :----------- | :------------ | :----- | :------------------ |

301| `session_id` | `str` | 必需 | 要檢索消息的 session ID |

302| `directory` | `str \| None` | `None` | 要查看的專案目錄。省略時,搜尋所有專案 |

303| `limit` | `int \| None` | `None` | 返回的最大消息數 |

304| `offset` | `int` | `0` | 從開始跳過的消息數 |

305 

306#### 返回類型:`SessionMessage`

307 

308| 屬性 | 類型 | 描述 |

309| :------------------- | :----------------------------- | :---------- |

310| `type` | `Literal["user", "assistant"]` | 消息角色 |

311| `uuid` | `str` | 唯一消息識別碼 |

312| `session_id` | `str` | session 識別碼 |

313| `message` | `Any` | 原始消息內容 |

314| `parent_tool_use_id` | `None` | 保留供未來使用 |

315 

316#### 範例

317 

318```python theme={null}

319from claude_agent_sdk import list_sessions, get_session_messages

320 

321sessions = list_sessions(limit=1)

322if sessions:

323 messages = get_session_messages(sessions[0].session_id)

324 for msg in messages:

325 print(f"[{msg.type}] {msg.uuid}")

326```

327 

328### `get_session_info()`

329 

330按 ID 讀取單個 session 的中繼資料,無需掃描完整專案目錄。同步;立即返回。

331 

332```python theme={null}

333def get_session_info(

334 session_id: str,

335 directory: str | None = None,

336) -> SDKSessionInfo | None

337```

338 

339#### 參數

340 

341| 參數 | 類型 | 預設 | 描述 |

342| :----------- | :------------ | :----- | :------------------ |

343| `session_id` | `str` | 必需 | 要查詢的 session 的 UUID |

344| `directory` | `str \| None` | `None` | 專案目錄路徑。省略時,搜尋所有專案目錄 |

345 

346返回 [`SDKSessionInfo`](#return-type-sdk-session-info),如果找不到 session,則返回 `None`。

347 

348#### 範例

349 

350查詢單個 session 的中繼資料,無需掃描專案目錄。當您已經從先前的執行中獲得 session ID 時很有用。

351 

352```python theme={null}

353from claude_agent_sdk import get_session_info

354 

355info = get_session_info("550e8400-e29b-41d4-a716-446655440000")

356if info:

357 print(f"{info.summary} (branch: {info.git_branch}, tag: {info.tag})")

358```

359 

360### `rename_session()`

361 

362通過附加自訂標題項來重新命名 session。重複呼叫是安全的;最新的標題獲勝。同步。

363 

364```python theme={null}

365def rename_session(

366 session_id: str,

367 title: str,

368 directory: str | None = None,

369) -> None

370```

371 

372#### 參數

373 

374| 參數 | 類型 | 預設 | 描述 |

375| :----------- | :------------ | :----- | :-------------------- |

376| `session_id` | `str` | 必需 | 要重新命名的 session 的 UUID |

377| `title` | `str` | 必需 | 新標題。去除空格後必須非空 |

378| `directory` | `str \| None` | `None` | 專案目錄路徑。省略時,搜尋所有專案目錄 |

379 

380如果 `session_id` 不是有效的 UUID 或 `title` 為空,則引發 `ValueError`;如果找不到 session,則引發 `FileNotFoundError`。

381 

382#### 範例

383 

384重新命名最近的 session,以便稍後更容易找到。新標題在後續讀取時出現在 [`SDKSessionInfo.custom_title`](#return-type-sdk-session-info) 中。

385 

386```python theme={null}

387from claude_agent_sdk import list_sessions, rename_session

388 

389sessions = list_sessions(directory="/path/to/project", limit=1)

390if sessions:

391 rename_session(sessions[0].session_id, "Refactor auth module")

392```

393 

394### `tag_session()`

395 

396標記 session。傳遞 `None` 以清除標籤。重複呼叫是安全的;最新的標籤獲勝。同步。

397 

398```python theme={null}

399def tag_session(

400 session_id: str,

401 tag: str | None,

402 directory: str | None = None,

403) -> None

404```

405 

406#### 參數

407 

408| 參數 | 類型 | 預設 | 描述 |

409| :----------- | :------------ | :----- | :--------------------------------- |

410| `session_id` | `str` | 必需 | 要標記的 session 的 UUID |

411| `tag` | `str \| None` | 必需 | 標籤字串,或 `None` 以清除。儲存前進行 Unicode 清理 |

412| `directory` | `str \| None` | `None` | 專案目錄路徑。省略時,搜尋所有專案目錄 |

413 

414如果 `session_id` 不是有效的 UUID 或 `tag` 在清理後為空,則引發 `ValueError`;如果找不到 session,則引發 `FileNotFoundError`。

415 

416#### 範例

417 

418標記 session,然後在稍後的讀取中按該標籤篩選。傳遞 `None` 以清除現有標籤。

419 

420```python theme={null}

421from claude_agent_sdk import list_sessions, tag_session

422 

423# Tag a session

424tag_session("550e8400-e29b-41d4-a716-446655440000", "needs-review")

425 

426# Later: find all sessions with that tag

427for session in list_sessions(directory="/path/to/project"):

428 if session.tag == "needs-review":

429 print(session.summary)

430```

431 

432## 類別

433 

434### `ClaudeSDKClient`

435 

436**在多個交換中維持對話 session。** 這是 TypeScript SDK 的 `query()` 函數內部工作方式的 Python 等效物 - 它建立一個可以繼續對話的客戶端物件。

437 

438#### 主要功能

439 

440* **Session 連續性**:在多個 `query()` 呼叫中維持對話上下文

441* **相同對話**:session 保留先前的消息

442* **中斷支援**:可以在任務中途停止執行

443* **明確生命週期**:您控制 session 何時開始和結束

444* **回應驅動流程**:可以對回應做出反應並發送後續消息

445* **自訂 tools 和 hooks**:支援自訂 tools(使用 `@tool` 裝飾器建立)和 hooks

446 

447```python theme={null}

448class ClaudeSDKClient:

449 def __init__(self, options: ClaudeAgentOptions | None = None, transport: Transport | None = None)

450 async def connect(self, prompt: str | AsyncIterable[dict] | None = None) -> None

451 async def query(self, prompt: str | AsyncIterable[dict], session_id: str = "default") -> None

452 async def receive_messages(self) -> AsyncIterator[Message]

453 async def receive_response(self) -> AsyncIterator[Message]

454 async def interrupt(self) -> None

455 async def set_permission_mode(self, mode: str) -> None

456 async def set_model(self, model: str | None = None) -> None

457 async def rewind_files(self, user_message_id: str) -> None

458 async def get_mcp_status(self) -> McpStatusResponse

459 async def reconnect_mcp_server(self, server_name: str) -> None

460 async def toggle_mcp_server(self, server_name: str, enabled: bool) -> None

461 async def stop_task(self, task_id: str) -> None

462 async def get_server_info(self) -> dict[str, Any] | None

463 async def disconnect(self) -> None

464```

465 

466#### 方法

467 

468| 方法 | 描述 |

469| :---------------------------------------- | :-------------------------------------------------------------------------------------------------------------- |

470| `__init__(options)` | 使用可選配置初始化客戶端 |

471| `connect(prompt)` | 使用可選初始提示或消息流連接到 Claude |

472| `query(prompt, session_id)` | 以串流模式發送新請求 |

473| `receive_messages()` | 以非同步迭代器接收來自 Claude 的所有消息 |

474| `receive_response()` | 接收消息直到並包括 ResultMessage |

475| `interrupt()` | 發送中斷信號(僅在串流模式下工作) |

476| `set_permission_mode(mode)` | 變更目前 session 的權限模式 |

477| `set_model(model)` | 變更目前 session 的模型。傳遞 `None` 以重設為預設值 |

478| `rewind_files(user_message_id)` | 將檔案還原到指定使用者消息時的狀態。需要 `enable_file_checkpointing=True`。見 [檔案 checkpointing](/zh-TW/agent-sdk/file-checkpointing) |

479| `get_mcp_status()` | 取得所有已配置 MCP 伺服器的狀態。返回 [`McpStatusResponse`](#mcp-status-response) |

480| `reconnect_mcp_server(server_name)` | 重試連接到失敗或斷開連接的 MCP 伺服器 |

481| `toggle_mcp_server(server_name, enabled)` | 在 session 中途啟用或停用 MCP 伺服器。停用會移除其 tools |

482| `stop_task(task_id)` | 停止執行中的背景任務。[`TaskNotificationMessage`](#task-notification-message) 的狀態為 `"stopped"` 在消息流中跟隨 |

483| `get_server_info()` | 取得伺服器資訊,包括 session ID 和功能 |

484| `disconnect()` | 從 Claude 斷開連接 |

485 

486#### 上下文管理器支援

487 

488客戶端可以用作非同步上下文管理器以進行自動連接管理:

489 

490```python theme={null}

491async with ClaudeSDKClient() as client:

492 await client.query("Hello Claude")

493 async for message in client.receive_response():

494 print(message)

495```

496 

497> **重要:** 在迭代消息時,避免使用 `break` 提前退出,因為這可能導致 asyncio 清理問題。相反,讓迭代自然完成或使用標誌來追蹤何時找到所需內容。

498 

499#### 範例 - 繼續對話

500 

501```python theme={null}

502import asyncio

503from claude_agent_sdk import ClaudeSDKClient, AssistantMessage, TextBlock, ResultMessage

504 

505 

506async def main():

507 async with ClaudeSDKClient() as client:

508 # First question

509 await client.query("What's the capital of France?")

510 

511 # Process response

512 async for message in client.receive_response():

513 if isinstance(message, AssistantMessage):

514 for block in message.content:

515 if isinstance(block, TextBlock):

516 print(f"Claude: {block.text}")

517 

518 # Follow-up question - the session retains the previous context

519 await client.query("What's the population of that city?")

520 

521 async for message in client.receive_response():

522 if isinstance(message, AssistantMessage):

523 for block in message.content:

524 if isinstance(block, TextBlock):

525 print(f"Claude: {block.text}")

526 

527 # Another follow-up - still in the same conversation

528 await client.query("What are some famous landmarks there?")

529 

530 async for message in client.receive_response():

531 if isinstance(message, AssistantMessage):

532 for block in message.content:

533 if isinstance(block, TextBlock):

534 print(f"Claude: {block.text}")

535 

536 

537asyncio.run(main())

538```

539 

540#### 範例 - 使用 ClaudeSDKClient 進行串流輸入

541 

542```python theme={null}

543import asyncio

544from claude_agent_sdk import ClaudeSDKClient

545 

546 

547async def message_stream():

548 """Generate messages dynamically."""

549 yield {

550 "type": "user",

551 "message": {"role": "user", "content": "Analyze the following data:"},

552 }

553 await asyncio.sleep(0.5)

554 yield {

555 "type": "user",

556 "message": {"role": "user", "content": "Temperature: 25°C, Humidity: 60%"},

557 }

558 await asyncio.sleep(0.5)

559 yield {

560 "type": "user",

561 "message": {"role": "user", "content": "What patterns do you see?"},

562 }

563 

564 

565async def main():

566 async with ClaudeSDKClient() as client:

567 # Stream input to Claude

568 await client.query(message_stream())

569 

570 # Process response

571 async for message in client.receive_response():

572 print(message)

573 

574 # Follow-up in same session

575 await client.query("Should we be concerned about these readings?")

576 

577 async for message in client.receive_response():

578 print(message)

579 

580 

581asyncio.run(main())

582```

583 

584#### 範例 - 使用中斷

585 

586```python theme={null}

587import asyncio

588from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, ResultMessage

589 

590 

591async def interruptible_task():

592 options = ClaudeAgentOptions(allowed_tools=["Bash"], permission_mode="acceptEdits")

593 

594 async with ClaudeSDKClient(options=options) as client:

595 # Start a long-running task

596 await client.query("Count from 1 to 100 slowly, using the bash sleep command")

597 

598 # Let it run for a bit

599 await asyncio.sleep(2)

600 

601 # Interrupt the task

602 await client.interrupt()

603 print("Task interrupted!")

604 

605 # Drain the interrupted task's messages (including its ResultMessage)

606 async for message in client.receive_response():

607 if isinstance(message, ResultMessage):

608 print(f"Interrupted task finished with subtype={message.subtype!r}")

609 # subtype is "error_during_execution" for interrupted tasks

610 

611 # Send a new command

612 await client.query("Just say hello instead")

613 

614 # Now receive the new response

615 async for message in client.receive_response():

616 if isinstance(message, ResultMessage) and message.subtype == "success":

617 print(f"New result: {message.result}")

618 

619 

620asyncio.run(interruptible_task())

621```

622 

623<Note>

624 **中斷後的緩衝區行為:** `interrupt()` 發送停止信號但不清除消息緩衝區。已由中斷任務產生的消息,包括其 `ResultMessage`(帶有 `subtype="error_during_execution"`),保留在流中。您必須在讀取新查詢的回應之前使用 `receive_response()` 清空它們。如果您在 `interrupt()` 之後立即發送新查詢並僅呼叫一次 `receive_response()`,您將收到中斷任務的消息,而不是新查詢的回應。

625</Note>

626 

627#### 範例 - 進階權限控制

628 

629```python theme={null}

630from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

631from claude_agent_sdk.types import (

632 PermissionResultAllow,

633 PermissionResultDeny,

634 ToolPermissionContext,

635)

636 

637 

638async def custom_permission_handler(

639 tool_name: str, input_data: dict, context: ToolPermissionContext

640) -> PermissionResultAllow | PermissionResultDeny:

641 """Custom logic for tool permissions."""

642 

643 # Block writes to system directories

644 if tool_name == "Write" and input_data.get("file_path", "").startswith("/system/"):

645 return PermissionResultDeny(

646 message="System directory write not allowed", interrupt=True

647 )

648 

649 # Redirect sensitive file operations

650 if tool_name in ["Write", "Edit"] and "config" in input_data.get("file_path", ""):

651 safe_path = f"./sandbox/{input_data['file_path']}"

652 return PermissionResultAllow(

653 updated_input={**input_data, "file_path": safe_path}

654 )

655 

656 # Allow everything else

657 return PermissionResultAllow(updated_input=input_data)

658 

659 

660async def main():

661 options = ClaudeAgentOptions(

662 can_use_tool=custom_permission_handler, allowed_tools=["Read", "Write", "Edit"]

663 )

664 

665 async with ClaudeSDKClient(options=options) as client:

666 await client.query("Update the system config file")

667 

668 async for message in client.receive_response():

669 # Will use sandbox path instead

670 print(message)

671 

672 

673asyncio.run(main())

674```

675 

676## 類型

677 

678<Note>

679 **`@dataclass` vs `TypedDict`:** 此 SDK 使用兩種類型。用 `@dataclass` 裝飾的類別(例如 `ResultMessage`、`AgentDefinition`、`TextBlock`)在執行時是物件實例,支援屬性存取:`msg.result`。用 `TypedDict` 定義的類別(例如 `ThinkingConfigEnabled`、`McpStdioServerConfig`、`SyncHookJSONOutput`)在執行時是**純字典**,需要鍵存取:`config["budget_tokens"]`,而不是 `config.budget_tokens`。`ClassName(field=value)` 呼叫語法對兩者都有效,但只有 dataclasses 產生具有屬性的物件。

680</Note>

681 

682### `SdkMcpTool`

683 

684使用 `@tool` 裝飾器建立的 SDK MCP tool 的定義。

685 

686```python theme={null}

687@dataclass

688class SdkMcpTool(Generic[T]):

689 name: str

690 description: str

691 input_schema: type[T] | dict[str, Any]

692 handler: Callable[[T], Awaitable[dict[str, Any]]]

693 annotations: ToolAnnotations | None = None

694```

695 

696| 屬性 | 類型 | 描述 |

697| :------------- | :----------------------------------------- | :---------------------------------------------------------------------------------- |

698| `name` | `str` | tool 的唯一識別碼 |

699| `description` | `str` | 人類可讀描述 |

700| `input_schema` | `type[T] \| dict[str, Any]` | 輸入驗證的架構 |

701| `handler` | `Callable[[T], Awaitable[dict[str, Any]]]` | 處理 tool 執行的非同步函數 |

702| `annotations` | `ToolAnnotations \| None` | 可選的 MCP tool 註解(例如 `readOnlyHint`、`destructiveHint`、`openWorldHint`)。來自 `mcp.types` |

703 

704### `Transport`

705 

706自訂傳輸實現的抽象基類。使用此來透過自訂通道與 Claude 程序通訊(例如,遠端連接而不是本地子程序)。

707 

708<Warning>

709 這是一個低級內部 API。介面可能在未來版本中變更。自訂實現必須更新以符合任何介面變更。

710</Warning>

711 

712```python theme={null}

713from abc import ABC, abstractmethod

714from collections.abc import AsyncIterator

715from typing import Any

716 

717 

718class Transport(ABC):

719 @abstractmethod

720 async def connect(self) -> None: ...

721 

722 @abstractmethod

723 async def write(self, data: str) -> None: ...

724 

725 @abstractmethod

726 def read_messages(self) -> AsyncIterator[dict[str, Any]]: ...

727 

728 @abstractmethod

729 async def close(self) -> None: ...

730 

731 @abstractmethod

732 def is_ready(self) -> bool: ...

733 

734 @abstractmethod

735 async def end_input(self) -> None: ...

736```

737 

738| 方法 | 描述 |

739| :---------------- | :----------------------- |

740| `connect()` | 連接傳輸並準備通訊 |

741| `write(data)` | 將原始資料(JSON + 換行符)寫入傳輸 |

742| `read_messages()` | 非同步迭代器,產生解析的 JSON 消息 |

743| `close()` | 關閉連接並清理資源 |

744| `is_ready()` | 如果傳輸可以發送和接收,返回 `True` |

745| `end_input()` | 關閉輸入流(例如,為子程序傳輸關閉 stdin) |

746 

747匯入:`from claude_agent_sdk import Transport`

748 

749### `ClaudeAgentOptions`

750 

751Claude Code 查詢的配置 dataclass。

752 

753```python theme={null}

754@dataclass

755class ClaudeAgentOptions:

756 tools: list[str] | ToolsPreset | None = None

757 allowed_tools: list[str] = field(default_factory=list)

758 system_prompt: str | SystemPromptPreset | None = None

759 mcp_servers: dict[str, McpServerConfig] | str | Path = field(default_factory=dict)

760 permission_mode: PermissionMode | None = None

761 continue_conversation: bool = False

762 resume: str | None = None

763 max_turns: int | None = None

764 max_budget_usd: float | None = None

765 disallowed_tools: list[str] = field(default_factory=list)

766 model: str | None = None

767 fallback_model: str | None = None

768 betas: list[SdkBeta] = field(default_factory=list)

769 output_format: dict[str, Any] | None = None

770 permission_prompt_tool_name: str | None = None

771 cwd: str | Path | None = None

772 cli_path: str | Path | None = None

773 settings: str | None = None

774 add_dirs: list[str | Path] = field(default_factory=list)

775 env: dict[str, str] = field(default_factory=dict)

776 extra_args: dict[str, str | None] = field(default_factory=dict)

777 max_buffer_size: int | None = None

778 debug_stderr: Any = sys.stderr # Deprecated

779 stderr: Callable[[str], None] | None = None

780 can_use_tool: CanUseTool | None = None

781 hooks: dict[HookEvent, list[HookMatcher]] | None = None

782 user: str | None = None

783 include_partial_messages: bool = False

784 fork_session: bool = False

785 agents: dict[str, AgentDefinition] | None = None

786 setting_sources: list[SettingSource] | None = None

787 sandbox: SandboxSettings | None = None

788 plugins: list[SdkPluginConfig] = field(default_factory=list)

789 max_thinking_tokens: int | None = None # Deprecated: use thinking instead

790 thinking: ThinkingConfig | None = None

791 effort: Literal["low", "medium", "high", "max"] | None = None

792 enable_file_checkpointing: bool = False

793 session_store: SessionStore | None = None

794```

795 

796| 屬性 | 類型 | 預設 | 描述 |

797| :---------------------------- | :---------------------------------------------------------------------------------------- | :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

798| `tools` | `list[str] \| ToolsPreset \| None` | `None` | Tools 配置。使用 `{"type": "preset", "preset": "claude_code"}` 以取得 Claude Code 的預設 tools |

799| `allowed_tools` | `list[str]` | `[]` | 自動批准的 tools,無需提示。這不會限制 Claude 僅使用這些 tools;未列出的 tools 會進入 `permission_mode` 和 `can_use_tool`。使用 `disallowed_tools` 來阻止 tools。見 [權限](/zh-TW/agent-sdk/permissions#allow-and-deny-rules) |

800| `system_prompt` | `str \| SystemPromptPreset \| None` | `None` | 系統提示配置。傳遞字串以取得自訂提示,或使用 `{"type": "preset", "preset": "claude_code"}` 以取得 Claude Code 的系統提示。新增 `"append"` 以擴展預設 |

801| `mcp_servers` | `dict[str, McpServerConfig] \| str \| Path` | `{}` | MCP 伺服器配置或配置檔案路徑 |

802| `permission_mode` | `PermissionMode \| None` | `None` | tool 使用的權限模式 |

803| `continue_conversation` | `bool` | `False` | 繼續最近的對話 |

804| `resume` | `str \| None` | `None` | 要繼續的 session ID |

805| `max_turns` | `int \| None` | `None` | 最大代理轉數(tool 使用往返) |

806| `max_budget_usd` | `float \| None` | `None` | 當客戶端成本估計達到此 USD 值時停止查詢。與 `total_cost_usd` 的相同估計進行比較;見 [追蹤成本和使用情況](/zh-TW/agent-sdk/cost-tracking) 以了解準確性注意事項 |

807| `disallowed_tools` | `list[str]` | `[]` | 始終拒絕的 tools。拒絕規則首先檢查並覆蓋 `allowed_tools` 和 `permission_mode`(包括 `bypassPermissions`) |

808| `enable_file_checkpointing` | `bool` | `False` | 啟用檔案變更追蹤以進行倒帶。見 [檔案 checkpointing](/zh-TW/agent-sdk/file-checkpointing) |

809| `model` | `str \| None` | `None` | 要使用的 Claude 模型 |

810| `fallback_model` | `str \| None` | `None` | 如果主模型失敗,使用的備用模型 |

811| `betas` | `list[SdkBeta]` | `[]` | 要啟用的測試版功能。見 [`SdkBeta`](#sdk-beta) 以了解可用選項 |

812| `output_format` | `dict[str, Any] \| None` | `None` | 結構化回應的輸出格式(例如 `{"type": "json_schema", "schema": {...}}`)。見 [結構化輸出](/zh-TW/agent-sdk/structured-outputs) 以了解詳情 |

813| `permission_prompt_tool_name` | `str \| None` | `None` | 權限提示的 MCP tool 名稱 |

814| `cwd` | `str \| Path \| None` | `None` | 目前工作目錄 |

815| `cli_path` | `str \| Path \| None` | `None` | Claude Code CLI 可執行檔的自訂路徑 |

816| `settings` | `str \| None` | `None` | 設定檔案的路徑 |

817| `add_dirs` | `list[str \| Path]` | `[]` | Claude 可以存取的其他目錄 |

818| `env` | `dict[str, str]` | `{}` | 環境變數合併到繼承的程序環境之上。見 [環境變數](/zh-TW/env-vars) 以了解底層 CLI 讀取的變數 |

819| `extra_args` | `dict[str, str \| None]` | `{}` | 直接傳遞給 CLI 的其他 CLI 參數 |

820| `max_buffer_size` | `int \| None` | `None` | 緩衝 CLI stdout 時的最大位元組數 |

821| `debug_stderr` | `Any` | `sys.stderr` | *已棄用* - 用於偵錯輸出的類似檔案的物件。改用 `stderr` 回呼 |

822| `stderr` | `Callable[[str], None] \| None` | `None` | 用於 CLI stderr 輸出的回呼函數 |

823| `can_use_tool` | [`CanUseTool`](#can-use-tool) ` \| None` | `None` | tool 權限回呼函數。見 [權限類型](#can-use-tool) 以了解詳情 |

824| `hooks` | `dict[HookEvent, list[HookMatcher]] \| None` | `None` | 用於攔截事件的 hook 配置 |

825| `user` | `str \| None` | `None` | 使用者識別碼 |

826| `include_partial_messages` | `bool` | `False` | 包括部分消息串流事件。啟用時,[`StreamEvent`](#stream-event) 消息會被產生 |

827| `fork_session` | `bool` | `False` | 使用 `resume` 繼續時,分叉到新 session ID 而不是繼續原始 session |

828| `agents` | `dict[str, AgentDefinition] \| None` | `None` | 以程式設計方式定義的子代理 |

829| `plugins` | `list[SdkPluginConfig]` | `[]` | 從本地路徑載入自訂外掛程式。見 [外掛程式](/zh-TW/agent-sdk/plugins) 以了解詳情 |

830| `sandbox` | [`SandboxSettings`](#sandbox-settings) ` \| None` | `None` | 以程式設計方式配置沙箱行為。見 [沙箱設定](#sandbox-settings) 以了解詳情 |

831| `setting_sources` | `list[SettingSource] \| None` | `None`(CLI 預設值:所有來源) | 控制要載入哪些檔案系統設定。傳遞 `[]` 以停用使用者、專案和本地設定。無論如何都會載入受管原則設定。見 [使用 Claude Code 功能](/zh-TW/agent-sdk/claude-code-features#what-settingsources-does-not-control) |

832| `max_thinking_tokens` | `int \| None` | `None` | *已棄用* - 思考區塊的最大令牌數。改用 `thinking` |

833| `thinking` | [`ThinkingConfig`](#thinking-config) ` \| None` | `None` | 控制擴展思考行為。優先於 `max_thinking_tokens` |

834| `effort` | `Literal["low", "medium", "high", "max"] \| None` | `None` | 思考深度的努力級別 |

835| `session_store` | [`SessionStore`](/zh-TW/agent-sdk/session-storage#the-session-store-interface) ` \| None` | `None` | 將 session 記錄鏡像到外部後端,以便任何主機都可以繼續它們。見 [將 sessions 持久化到外部儲存](/zh-TW/agent-sdk/session-storage) |

836 

837### `OutputFormat`

838 

839結構化輸出驗證的配置。將此作為 `dict` 傳遞給 `ClaudeAgentOptions` 上的 `output_format` 欄位:

840 

841```python theme={null}

842# Expected dict shape for output_format

843{

844 "type": "json_schema",

845 "schema": {...}, # Your JSON Schema definition

846}

847```

848 

849| 欄位 | 必需 | 描述 |

850| :------- | :- | :------------------------------------- |

851| `type` | 是 | 必須是 `"json_schema"` 以進行 JSON Schema 驗證 |

852| `schema` | 是 | 用於輸出驗證的 JSON Schema 定義 |

853 

854### `SystemPromptPreset`

855 

856使用 Claude Code 的預設系統提示配置,可選新增。

857 

858```python theme={null}

859class SystemPromptPreset(TypedDict):

860 type: Literal["preset"]

861 preset: Literal["claude_code"]

862 append: NotRequired[str]

863 exclude_dynamic_sections: NotRequired[bool]

864```

865 

866| 欄位 | 必需 | 描述 |

867| :------------------------- | :- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

868| `type` | 是 | 必須是 `"preset"` 以使用預設系統提示 |

869| `preset` | 是 | 必須是 `"claude_code"` 以使用 Claude Code 的系統提示 |

870| `append` | 否 | 要附加到預設系統提示的其他指示 |

871| `exclude_dynamic_sections` | 否 | 將每個 session 上下文(例如工作目錄、git 狀態和記憶體路徑)從系統提示移到第一個使用者消息。改進跨使用者和機器的提示快取重複使用。見 [修改系統提示](/zh-TW/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines) |

872 

873### `SettingSource`

874 

875控制 SDK 從哪些檔案系統配置來源載入設定。

876 

877```python theme={null}

878SettingSource = Literal["user", "project", "local"]

879```

880 

881| 值 | 描述 | 位置 |

882| :---------- | :----------------- | :---------------------------- |

883| `"user"` | 全域使用者設定 | `~/.claude/settings.json` |

884| `"project"` | 共享專案設定(版本控制) | `.claude/settings.json` |

885| `"local"` | 本地專案設定(gitignored) | `.claude/settings.local.json` |

886 

887#### 預設行為

888 

889當 `setting_sources` 被省略或為 `None` 時,`query()` 載入與 Claude Code CLI 相同的檔案系統設定:使用者、專案和本地。無論如何都會載入受管原則設定。見 [settingSources 不控制的內容](/zh-TW/agent-sdk/claude-code-features#what-settingsources-does-not-control) 以了解無論此選項如何都會讀取的輸入,以及如何停用它們。

890 

891#### 為什麼使用 setting\_sources

892 

893**停用檔案系統設定:**

894 

895```python theme={null}

896# Do not load user, project, or local settings from disk

897from claude_agent_sdk import query, ClaudeAgentOptions

898 

899async for message in query(

900 prompt="Analyze this code",

901 options=ClaudeAgentOptions(

902 setting_sources=[]

903 ),

904):

905 print(message)

906```

907 

908<Note>

909 在 Python SDK 0.1.59 及更早版本中,空清單的處理方式與省略選項相同,因此 `setting_sources=[]` 沒有停用檔案系統設定。如果您需要空清單生效,請升級到較新版本。TypeScript SDK 不受影響。

910</Note>

911 

912**明確載入所有檔案系統設定:**

913 

914```python theme={null}

915from claude_agent_sdk import query, ClaudeAgentOptions

916 

917async for message in query(

918 prompt="Analyze this code",

919 options=ClaudeAgentOptions(

920 setting_sources=["user", "project", "local"]

921 ),

922):

923 print(message)

924```

925 

926**僅載入特定設定來源:**

927 

928```python theme={null}

929# Load only project settings, ignore user and local

930async for message in query(

931 prompt="Run CI checks",

932 options=ClaudeAgentOptions(

933 setting_sources=["project"] # Only .claude/settings.json

934 ),

935):

936 print(message)

937```

938 

939**測試和 CI 環境:**

940 

941```python theme={null}

942# Ensure consistent behavior in CI by excluding local settings

943async for message in query(

944 prompt="Run tests",

945 options=ClaudeAgentOptions(

946 setting_sources=["project"], # Only team-shared settings

947 permission_mode="bypassPermissions",

948 ),

949):

950 print(message)

951```

952 

953**僅 SDK 應用程式:**

954 

955```python theme={null}

956# Define everything programmatically.

957# Pass [] to opt out of filesystem setting sources.

958async for message in query(

959 prompt="Review this PR",

960 options=ClaudeAgentOptions(

961 setting_sources=[],

962 agents={...},

963 mcp_servers={...},

964 allowed_tools=["Read", "Grep", "Glob"],

965 ),

966):

967 print(message)

968```

969 

970**載入 CLAUDE.md 專案指示:**

971 

972```python theme={null}

973# Load project settings to include CLAUDE.md files

974async for message in query(

975 prompt="Add a new feature following project conventions",

976 options=ClaudeAgentOptions(

977 system_prompt={

978 "type": "preset",

979 "preset": "claude_code", # Use Claude Code's system prompt

980 },

981 setting_sources=["project"], # Loads CLAUDE.md from project

982 allowed_tools=["Read", "Write", "Edit"],

983 ),

984):

985 print(message)

986```

987 

988#### 設定優先順序

989 

990當載入多個來源時,設定會以此優先順序合併(最高到最低):

991 

9921. 本地設定(`.claude/settings.local.json`)

9932. 專案設定(`.claude/settings.json`)

9943. 使用者設定(`~/.claude/settings.json`)

995 

996程式設計選項(例如 `agents` 和 `allowed_tools`)會覆蓋使用者、專案和本地檔案系統設定。受管原則設定優先於程式設計選項。

997 

998### `AgentDefinition`

999 

1000以程式設計方式定義的子代理的配置。

1001 

1002```python theme={null}

1003@dataclass

1004class AgentDefinition:

1005 description: str

1006 prompt: str

1007 tools: list[str] | None = None

1008 disallowedTools: list[str] | None = None

1009 model: str | None = None

1010 skills: list[str] | None = None

1011 memory: Literal["user", "project", "local"] | None = None

1012 mcpServers: list[str | dict[str, Any]] | None = None

1013 initialPrompt: str | None = None

1014 maxTurns: int | None = None

1015 background: bool | None = None

1016 effort: Literal["low", "medium", "high", "max"] | int | None = None

1017 permissionMode: PermissionMode | None = None

1018```

1019 

1020| 欄位 | 必需 | 描述 |

1021| :---------------- | :- | :------------------------------------------------------------------------------- |

1022| `description` | 是 | 何時使用此代理的自然語言描述 |

1023| `prompt` | 是 | 代理的系統提示 |

1024| `tools` | 否 | 允許的 tool 名稱陣列。如果省略,繼承所有 tools |

1025| `disallowedTools` | 否 | 要從代理的 tool 集中移除的 tool 名稱陣列 |

1026| `model` | 否 | 此代理的模型覆蓋。接受別名,例如 `"sonnet"`、`"opus"`、`"haiku"` 或 `"inherit"`,或完整模型 ID。如果省略,使用主模型 |

1027| `skills` | 否 | 此代理可用的技能名稱清單 |

1028| `memory` | 否 | 此代理的記憶體來源:`"user"`、`"project"` 或 `"local"` |

1029| `mcpServers` | 否 | 此代理可用的 MCP 伺服器。每個項目是伺服器名稱或內聯 `{name: config}` 字典 |

1030| `initialPrompt` | 否 | 當此代理作為主執行緒代理執行時自動提交為第一個使用者轉 |

1031| `maxTurns` | 否 | 代理停止前的最大代理轉數 |

1032| `background` | 否 | 當呼叫時將此代理作為非阻塞背景任務執行 |

1033| `effort` | 否 | 此代理的推理努力級別。接受命名級別或整數 |

1034| `permissionMode` | 否 | 此代理內 tool 執行的權限模式。見 [`PermissionMode`](#permission-mode) |

1035 

1036<Note>

1037 `AgentDefinition` 欄位名稱使用 camelCase,例如 `disallowedTools`、`permissionMode` 和 `maxTurns`。這些名稱直接對應到與 TypeScript SDK 共享的線路格式。這與 `ClaudeAgentOptions` 不同,後者對等頂級欄位(例如 `disallowed_tools` 和 `permission_mode`)使用 Python snake\_case。因為 `AgentDefinition` 是 dataclass,傳遞 snake\_case 關鍵字在構造時會引發 `TypeError`。

1038</Note>

1039 

1040### `PermissionMode`

1041 

1042用於控制 tool 執行的權限模式。

1043 

1044```python theme={null}

1045PermissionMode = Literal[

1046 "default", # Standard permission behavior

1047 "acceptEdits", # Auto-accept file edits

1048 "plan", # Planning mode - no execution

1049 "dontAsk", # Deny anything not pre-approved instead of prompting

1050 "bypassPermissions", # Bypass all permission checks (use with caution)

1051]

1052```

1053 

1054### `CanUseTool`

1055 

1056tool 權限回呼函數的類型別名。

1057 

1058```python theme={null}

1059CanUseTool = Callable[

1060 [str, dict[str, Any], ToolPermissionContext], Awaitable[PermissionResult]

1061]

1062```

1063 

1064回呼接收:

1065 

1066* `tool_name`:被呼叫的 tool 名稱

1067* `input_data`:tool 的輸入參數

1068* `context`:具有其他資訊的 `ToolPermissionContext`

1069 

1070返回 `PermissionResult`(`PermissionResultAllow` 或 `PermissionResultDeny`)。

1071 

1072### `ToolPermissionContext`

1073 

1074傳遞給 tool 權限回呼的上下文資訊。

1075 

1076```python theme={null}

1077@dataclass

1078class ToolPermissionContext:

1079 signal: Any | None = None # Future: abort signal support

1080 suggestions: list[PermissionUpdate] = field(default_factory=list)

1081```

1082 

1083| 欄位 | 類型 | 描述 |

1084| :------------ | :----------------------- | :------------- |

1085| `signal` | `Any \| None` | 保留供未來中止信號支援 |

1086| `suggestions` | `list[PermissionUpdate]` | 來自 CLI 的權限更新建議 |

1087 

1088### `PermissionResult`

1089 

1090權限回呼結果的聯合類型。

1091 

1092```python theme={null}

1093PermissionResult = PermissionResultAllow | PermissionResultDeny

1094```

1095 

1096### `PermissionResultAllow`

1097 

1098指示應允許 tool 呼叫的結果。

1099 

1100```python theme={null}

1101@dataclass

1102class PermissionResultAllow:

1103 behavior: Literal["allow"] = "allow"

1104 updated_input: dict[str, Any] | None = None

1105 updated_permissions: list[PermissionUpdate] | None = None

1106```

1107 

1108| 欄位 | 類型 | 預設 | 描述 |

1109| :-------------------- | :------------------------------- | :-------- | :-------------- |

1110| `behavior` | `Literal["allow"]` | `"allow"` | 必須是 "allow" |

1111| `updated_input` | `dict[str, Any] \| None` | `None` | 要使用的修改輸入而不是原始輸入 |

1112| `updated_permissions` | `list[PermissionUpdate] \| None` | `None` | 要應用的權限更新 |

1113 

1114### `PermissionResultDeny`

1115 

1116指示應拒絕 tool 呼叫的結果。

1117 

1118```python theme={null}

1119@dataclass

1120class PermissionResultDeny:

1121 behavior: Literal["deny"] = "deny"

1122 message: str = ""

1123 interrupt: bool = False

1124```

1125 

1126| 欄位 | 類型 | 預設 | 描述 |

1127| :---------- | :---------------- | :------- | :--------------- |

1128| `behavior` | `Literal["deny"]` | `"deny"` | 必須是 "deny" |

1129| `message` | `str` | `""` | 解釋為什麼拒絕 tool 的消息 |

1130| `interrupt` | `bool` | `False` | 是否中斷目前執行 |

1131 

1132### `PermissionUpdate`

1133 

1134用於以程式設計方式更新權限的配置。

1135 

1136```python theme={null}

1137@dataclass

1138class PermissionUpdate:

1139 type: Literal[

1140 "addRules",

1141 "replaceRules",

1142 "removeRules",

1143 "setMode",

1144 "addDirectories",

1145 "removeDirectories",

1146 ]

1147 rules: list[PermissionRuleValue] | None = None

1148 behavior: Literal["allow", "deny", "ask"] | None = None

1149 mode: PermissionMode | None = None

1150 directories: list[str] | None = None

1151 destination: (

1152 Literal["userSettings", "projectSettings", "localSettings", "session"] | None

1153 ) = None

1154```

1155 

1156| 欄位 | 類型 | 描述 |

1157| :------------ | :---------------------------------------- | :-------------- |

1158| `type` | `Literal[...]` | 權限更新操作的類型 |

1159| `rules` | `list[PermissionRuleValue] \| None` | 用於新增/取代/移除操作的規則 |

1160| `behavior` | `Literal["allow", "deny", "ask"] \| None` | 基於規則的操作的行為 |

1161| `mode` | `PermissionMode \| None` | setMode 操作的模式 |

1162| `directories` | `list[str] \| None` | 用於新增/移除目錄操作的目錄 |

1163| `destination` | `Literal[...] \| None` | 應用權限更新的位置 |

1164 

1165### `PermissionRuleValue`

1166 

1167要在權限更新中新增、取代或移除的規則。

1168 

1169```python theme={null}

1170@dataclass

1171class PermissionRuleValue:

1172 tool_name: str

1173 rule_content: str | None = None

1174```

1175 

1176### `ToolsPreset`

1177 

1178使用 Claude Code 預設 tool 集的預設 tools 配置。

1179 

1180```python theme={null}

1181class ToolsPreset(TypedDict):

1182 type: Literal["preset"]

1183 preset: Literal["claude_code"]

1184```

1185 

1186### `ThinkingConfig`

1187 

1188控制擴展思考行為。三個配置的聯合:

1189 

1190```python theme={null}

1191class ThinkingConfigAdaptive(TypedDict):

1192 type: Literal["adaptive"]

1193 

1194 

1195class ThinkingConfigEnabled(TypedDict):

1196 type: Literal["enabled"]

1197 budget_tokens: int

1198 

1199 

1200class ThinkingConfigDisabled(TypedDict):

1201 type: Literal["disabled"]

1202 

1203 

1204ThinkingConfig = ThinkingConfigAdaptive | ThinkingConfigEnabled | ThinkingConfigDisabled

1205```

1206 

1207| 變體 | 欄位 | 描述 |

1208| :--------- | :---------------------- | :--------------- |

1209| `adaptive` | `type` | Claude 自適應決定何時思考 |

1210| `enabled` | `type`, `budget_tokens` | 啟用具有特定令牌預算的思考 |

1211| `disabled` | `type` | 停用思考 |

1212 

1213因為這些是 `TypedDict` 類別,它們在執行時是純字典。要麼將它們構造為字典字面量,要麼呼叫類別作為構造函數;兩者都產生 `dict`。使用 `config["budget_tokens"]` 存取欄位,而不是 `config.budget_tokens`:

1214 

1215```python theme={null}

1216from claude_agent_sdk import ClaudeAgentOptions, ThinkingConfigEnabled

1217 

1218# Option 1: dict literal (recommended, no import needed)

1219options = ClaudeAgentOptions(thinking={"type": "enabled", "budget_tokens": 20000})

1220 

1221# Option 2: constructor-style (returns a plain dict)

1222config = ThinkingConfigEnabled(type="enabled", budget_tokens=20000)

1223print(config["budget_tokens"]) # 20000

1224# config.budget_tokens would raise AttributeError

1225```

1226 

1227### `SdkBeta`

1228 

1229SDK 測試版功能的字面類型。

1230 

1231```python theme={null}

1232SdkBeta = Literal["context-1m-2025-08-07"]

1233```

1234 

1235與 `ClaudeAgentOptions` 中的 `betas` 欄位一起使用以啟用測試版功能。

1236 

1237<Warning>

1238 `context-1m-2025-08-07` 測試版自 2026 年 4 月 30 日起已停用。使用 Claude Sonnet 4.5 或 Sonnet 4 傳遞此標頭沒有效果,超過標準 200k 令牌上下文視窗的請求會返回錯誤。要使用 1M 令牌上下文視窗,請遷移到 [Claude Sonnet 4.6、Claude Opus 4.6 或 Claude Opus 4.7](https://platform.claude.com/docs/en/about-claude/models/overview),它們以標準定價包括 1M 上下文,無需測試版標頭。

1239</Warning>

1240 

1241### `McpSdkServerConfig`

1242 

1243使用 `create_sdk_mcp_server()` 建立的 SDK MCP 伺服器的配置。

1244 

1245```python theme={null}

1246class McpSdkServerConfig(TypedDict):

1247 type: Literal["sdk"]

1248 name: str

1249 instance: Any # MCP Server instance

1250```

1251 

1252### `McpServerConfig`

1253 

1254MCP 伺服器配置的聯合類型。

1255 

1256```python theme={null}

1257McpServerConfig = (

1258 McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig

1259)

1260```

1261 

1262#### `McpStdioServerConfig`

1263 

1264```python theme={null}

1265class McpStdioServerConfig(TypedDict):

1266 type: NotRequired[Literal["stdio"]] # Optional for backwards compatibility

1267 command: str

1268 args: NotRequired[list[str]]

1269 env: NotRequired[dict[str, str]]

1270```

1271 

1272#### `McpSSEServerConfig`

1273 

1274```python theme={null}

1275class McpSSEServerConfig(TypedDict):

1276 type: Literal["sse"]

1277 url: str

1278 headers: NotRequired[dict[str, str]]

1279```

1280 

1281#### `McpHttpServerConfig`

1282 

1283```python theme={null}

1284class McpHttpServerConfig(TypedDict):

1285 type: Literal["http"]

1286 url: str

1287 headers: NotRequired[dict[str, str]]

1288```

1289 

1290### `McpServerStatusConfig`

1291 

1292MCP 伺服器的配置,如 [`get_mcp_status()`](#methods) 所報告。這是所有 [`McpServerConfig`](#mcp-server-config) 傳輸變體加上用於透過 claude.ai 代理的伺服器的僅輸出 `claudeai-proxy` 變體的聯合。

1293 

1294```python theme={null}

1295McpServerStatusConfig = (

1296 McpStdioServerConfig

1297 | McpSSEServerConfig

1298 | McpHttpServerConfig

1299 | McpSdkServerConfigStatus

1300 | McpClaudeAIProxyServerConfig

1301)

1302```

1303 

1304`McpSdkServerConfigStatus` 是 [`McpSdkServerConfig`](#mcp-sdk-server-config) 的可序列化形式,僅具有 `type`(`"sdk"`)和 `name`(`str`)欄位;進程內 `instance` 被省略。`McpClaudeAIProxyServerConfig` 具有 `type`(`"claudeai-proxy"`)、`url`(`str`)和 `id`(`str`)欄位。

1305 

1306### `McpStatusResponse`

1307 

1308來自 [`ClaudeSDKClient.get_mcp_status()`](#methods) 的回應。在 `mcpServers` 鍵下包裝伺服器狀態清單。

1309 

1310```python theme={null}

1311class McpStatusResponse(TypedDict):

1312 mcpServers: list[McpServerStatus]

1313```

1314 

1315### `McpServerStatus`

1316 

1317連接的 MCP 伺服器的狀態,包含在 [`McpStatusResponse`](#mcp-status-response) 中。

1318 

1319```python theme={null}

1320class McpServerStatus(TypedDict):

1321 name: str

1322 status: McpServerConnectionStatus # "connected" | "failed" | "needs-auth" | "pending" | "disabled"

1323 serverInfo: NotRequired[McpServerInfo]

1324 error: NotRequired[str]

1325 config: NotRequired[McpServerStatusConfig]

1326 scope: NotRequired[str]

1327 tools: NotRequired[list[McpToolInfo]]

1328```

1329 

1330| 欄位 | 類型 | 描述 |

1331| :----------- | :------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------- |

1332| `name` | `str` | 伺服器名稱 |

1333| `status` | `str` | `"connected"`、`"failed"`、`"needs-auth"`、`"pending"` 或 `"disabled"` 之一 |

1334| `serverInfo` | `dict`(可選) | 伺服器名稱和版本(`{"name": str, "version": str}`) |

1335| `error` | `str`(可選) | 伺服器連接失敗時的錯誤消息 |

1336| `config` | [`McpServerStatusConfig`](#mcp-server-status-config)(可選) | 伺服器配置。與 [`McpServerConfig`](#mcp-server-config) 相同的形狀(stdio、SSE、HTTP 或 SDK),加上用於透過 claude.ai 連接的伺服器的 `claudeai-proxy` 變體 |

1337| `scope` | `str`(可選) | 配置範圍 |

1338| `tools` | `list`(可選) | 此伺服器提供的 tools,每個都具有 `name`、`description` 和 `annotations` 欄位 |

1339 

1340### `SdkPluginConfig`

1341 

1342在 SDK 中載入外掛程式的配置。

1343 

1344```python theme={null}

1345class SdkPluginConfig(TypedDict):

1346 type: Literal["local"]

1347 path: str

1348```

1349 

1350| 欄位 | 類型 | 描述 |

1351| :----- | :----------------- | :------------------------- |

1352| `type` | `Literal["local"]` | 必須是 `"local"`(目前僅支援本地外掛程式) |

1353| `path` | `str` | 外掛程式目錄的絕對或相對路徑 |

1354 

1355**範例:**

1356 

1357```python theme={null}

1358plugins = [

1359 {"type": "local", "path": "./my-plugin"},

1360 {"type": "local", "path": "/absolute/path/to/plugin"},

1361]

1362```

1363 

1364如需建立和使用外掛程式的完整資訊,見 [外掛程式](/zh-TW/agent-sdk/plugins)。

1365 

1366## 消息類型

1367 

1368### `Message`

1369 

1370所有可能消息的聯合類型。

1371 

1372```python theme={null}

1373Message = (

1374 UserMessage

1375 | AssistantMessage

1376 | SystemMessage

1377 | ResultMessage

1378 | StreamEvent

1379 | RateLimitEvent

1380)

1381```

1382 

1383### `UserMessage`

1384 

1385使用者輸入消息。

1386 

1387```python theme={null}

1388@dataclass

1389class UserMessage:

1390 content: str | list[ContentBlock]

1391 uuid: str | None = None

1392 parent_tool_use_id: str | None = None

1393 tool_use_result: dict[str, Any] | None = None

1394```

1395 

1396| 欄位 | 類型 | 描述 |

1397| :------------------- | :-------------------------- | :----------------------------- |

1398| `content` | `str \| list[ContentBlock]` | 消息內容為文字或內容區塊 |

1399| `uuid` | `str \| None` | 唯一消息識別碼 |

1400| `parent_tool_use_id` | `str \| None` | 如果此消息是 tool 結果回應,則為 tool 使用 ID |

1401| `tool_use_result` | `dict[str, Any] \| None` | tool 結果資料(如適用) |

1402 

1403### `AssistantMessage`

1404 

1405具有內容區塊的助手回應消息。

1406 

1407```python theme={null}

1408@dataclass

1409class AssistantMessage:

1410 content: list[ContentBlock]

1411 model: str

1412 parent_tool_use_id: str | None = None

1413 error: AssistantMessageError | None = None

1414 usage: dict[str, Any] | None = None

1415 message_id: str | None = None

1416```

1417 

1418| 欄位 | 類型 | 描述 |

1419| :------------------- | :------------------------------------------------------------- | :--------------------------------------------------------- |

1420| `content` | `list[ContentBlock]` | 回應中的內容區塊清單 |

1421| `model` | `str` | 產生回應的模型 |

1422| `parent_tool_use_id` | `str \| None` | 如果這是嵌套回應,則為 tool 使用 ID |

1423| `error` | [`AssistantMessageError`](#assistant-message-error) ` \| None` | 如果回應遇到錯誤,則為錯誤類型 |

1424| `usage` | `dict[str, Any] \| None` | 每消息令牌使用情況(與 [`ResultMessage.usage`](#result-message) 相同的鍵) |

1425| `message_id` | `str \| None` | API 消息 ID。來自一個轉的多個消息共享相同的 ID |

1426 

1427### `AssistantMessageError`

1428 

1429助手消息的可能錯誤類型。

1430 

1431```python theme={null}

1432AssistantMessageError = Literal[

1433 "authentication_failed",

1434 "billing_error",

1435 "rate_limit",

1436 "invalid_request",

1437 "server_error",

1438 "max_output_tokens",

1439 "unknown",

1440]

1441```

1442 

1443### `SystemMessage`

1444 

1445具有中繼資料的系統消息。

1446 

1447```python theme={null}

1448@dataclass

1449class SystemMessage:

1450 subtype: str

1451 data: dict[str, Any]

1452```

1453 

1454### `ResultMessage`

1455 

1456具有成本和使用情況資訊的最終結果消息。

1457 

1458```python theme={null}

1459@dataclass

1460class ResultMessage:

1461 subtype: str

1462 duration_ms: int

1463 duration_api_ms: int

1464 is_error: bool

1465 num_turns: int

1466 session_id: str

1467 total_cost_usd: float | None = None

1468 usage: dict[str, Any] | None = None

1469 result: str | None = None

1470 stop_reason: str | None = None

1471 structured_output: Any = None

1472 model_usage: dict[str, Any] | None = None

1473```

1474 

1475`usage` 字典在出現時包含以下鍵:

1476 

1477| 鍵 | 類型 | 描述 |

1478| ----------------------------- | ----- | ------------- |

1479| `input_tokens` | `int` | 消耗的總輸入令牌。 |

1480| `output_tokens` | `int` | 產生的總輸出令牌。 |

1481| `cache_creation_input_tokens` | `int` | 用於建立新快取項目的令牌。 |

1482| `cache_read_input_tokens` | `int` | 從現有快取項目讀取的令牌。 |

1483 

1484`model_usage` 字典將模型名稱對應到每個模型的使用情況。內部字典鍵使用 camelCase,因為該值從基礎 CLI 程序未修改地傳遞,符合 TypeScript [`ModelUsage`](/zh-TW/agent-sdk/typescript#model-usage) 類型:

1485 

1486| 鍵 | 類型 | 描述 |

1487| -------------------------- | ------- | ----------------------------------------------------------------------------------- |

1488| `inputTokens` | `int` | 此模型的輸入令牌。 |

1489| `outputTokens` | `int` | 此模型的輸出令牌。 |

1490| `cacheReadInputTokens` | `int` | 此模型的快取讀取令牌。 |

1491| `cacheCreationInputTokens` | `int` | 此模型的快取建立令牌。 |

1492| `webSearchRequests` | `int` | 此模型進行的網路搜尋請求。 |

1493| `costUSD` | `float` | 此模型的估計成本(以 USD 為單位),在客戶端計算。見 [追蹤成本和使用情況](/zh-TW/agent-sdk/cost-tracking) 以了解計費注意事項。 |

1494| `contextWindow` | `int` | 此模型的上下文視窗大小。 |

1495| `maxOutputTokens` | `int` | 此模型的最大輸出令牌限制。 |

1496 

1497### `StreamEvent`

1498 

1499用於在串流期間進行部分消息更新的串流事件。僅在 `ClaudeAgentOptions` 中 `include_partial_messages=True` 時接收。透過 `from claude_agent_sdk.types import StreamEvent` 匯入。

1500 

1501```python theme={null}

1502@dataclass

1503class StreamEvent:

1504 uuid: str

1505 session_id: str

1506 event: dict[str, Any] # The raw Claude API stream event

1507 parent_tool_use_id: str | None = None

1508```

1509 

1510| 欄位 | 類型 | 描述 |

1511| :------------------- | :--------------- | :------------------------ |

1512| `uuid` | `str` | 此事件的唯一識別碼 |

1513| `session_id` | `str` | session 識別碼 |

1514| `event` | `dict[str, Any]` | 原始 Claude API 串流事件資料 |

1515| `parent_tool_use_id` | `str \| None` | 如果此事件來自子代理,則為父 tool 使用 ID |

1516 

1517### `RateLimitEvent`

1518 

1519當速率限制狀態變更時發出(例如,從 `"allowed"` 到 `"allowed_warning"`)。使用此來在使用者達到硬限制之前警告他們,或在狀態為 `"rejected"` 時退避。

1520 

1521```python theme={null}

1522@dataclass

1523class RateLimitEvent:

1524 rate_limit_info: RateLimitInfo

1525 uuid: str

1526 session_id: str

1527```

1528 

1529| 欄位 | 類型 | 描述 |

1530| :---------------- | :---------------------------------- | :---------- |

1531| `rate_limit_info` | [`RateLimitInfo`](#rate-limit-info) | 目前速率限制狀態 |

1532| `uuid` | `str` | 唯一事件識別碼 |

1533| `session_id` | `str` | session 識別碼 |

1534 

1535### `RateLimitInfo`

1536 

1537由 [`RateLimitEvent`](#rate-limit-event) 攜帶的速率限制狀態。

1538 

1539```python theme={null}

1540RateLimitStatus = Literal["allowed", "allowed_warning", "rejected"]

1541RateLimitType = Literal[

1542 "five_hour", "seven_day", "seven_day_opus", "seven_day_sonnet", "overage"

1543]

1544 

1545 

1546@dataclass

1547class RateLimitInfo:

1548 status: RateLimitStatus

1549 resets_at: int | None = None

1550 rate_limit_type: RateLimitType | None = None

1551 utilization: float | None = None

1552 overage_status: RateLimitStatus | None = None

1553 overage_resets_at: int | None = None

1554 overage_disabled_reason: str | None = None

1555 raw: dict[str, Any] = field(default_factory=dict)

1556```

1557 

1558| 欄位 | 類型 | 描述 |

1559| :------------------------ | :------------------------ | :-------------------------------------------------- |

1560| `status` | `RateLimitStatus` | 目前狀態。`"allowed_warning"` 表示接近限制;`"rejected"` 表示達到限制 |

1561| `resets_at` | `int \| None` | 速率限制視窗重設時的 Unix 時間戳 |

1562| `rate_limit_type` | `RateLimitType \| None` | 適用的速率限制視窗 |

1563| `utilization` | `float \| None` | 消耗的速率限制分數(0.0 到 1.0) |

1564| `overage_status` | `RateLimitStatus \| None` | 按使用量付費超額使用的狀態(如適用) |

1565| `overage_resets_at` | `int \| None` | 超額視窗重設時的 Unix 時間戳 |

1566| `overage_disabled_reason` | `str \| None` | 如果狀態為 `"rejected"`,為什麼超額不可用 |

1567| `raw` | `dict[str, Any]` | 來自 CLI 的完整原始字典,包括上面未建模的欄位 |

1568 

1569### `TaskStartedMessage`

1570 

1571在背景任務啟動時發出。背景任務是在主轉之外追蹤的任何內容:背景 Bash 命令、[Monitor](#monitor) 監視、透過 Agent tool 生成的子代理或遠端代理。`task_type` 欄位告訴您是哪一個。此命名與 `Task` 到 `Agent` tool 重新命名無關。

1572 

1573```python theme={null}

1574@dataclass

1575class TaskStartedMessage(SystemMessage):

1576 task_id: str

1577 description: str

1578 uuid: str

1579 session_id: str

1580 tool_use_id: str | None = None

1581 task_type: str | None = None

1582```

1583 

1584| 欄位 | 類型 | 描述 |

1585| :------------ | :------------ | :------------------------------------------------------------------------------- |

1586| `task_id` | `str` | 任務的唯一識別碼 |

1587| `description` | `str` | 任務的描述 |

1588| `uuid` | `str` | 唯一消息識別碼 |

1589| `session_id` | `str` | session 識別碼 |

1590| `tool_use_id` | `str \| None` | 相關聯的 tool 使用 ID |

1591| `task_type` | `str \| None` | 背景任務的類型:`"local_bash"` 用於背景 Bash 和 Monitor 監視,`"local_agent"` 或 `"remote_agent"` |

1592 

1593### `TaskUsage`

1594 

1595背景任務的令牌和計時資料。

1596 

1597```python theme={null}

1598class TaskUsage(TypedDict):

1599 total_tokens: int

1600 tool_uses: int

1601 duration_ms: int

1602```

1603 

1604### `TaskProgressMessage`

1605 

1606定期為執行中的背景任務發出進度更新。

1607 

1608```python theme={null}

1609@dataclass

1610class TaskProgressMessage(SystemMessage):

1611 task_id: str

1612 description: str

1613 usage: TaskUsage

1614 uuid: str

1615 session_id: str

1616 tool_use_id: str | None = None

1617 last_tool_name: str | None = None

1618```

1619 

1620| 欄位 | 類型 | 描述 |

1621| :--------------- | :------------ | :-------------- |

1622| `task_id` | `str` | 任務的唯一識別碼 |

1623| `description` | `str` | 目前狀態描述 |

1624| `usage` | `TaskUsage` | 此任務迄今為止的令牌使用情況 |

1625| `uuid` | `str` | 唯一消息識別碼 |

1626| `session_id` | `str` | session 識別碼 |

1627| `tool_use_id` | `str \| None` | 相關聯的 tool 使用 ID |

1628| `last_tool_name` | `str \| None` | 任務最後使用的 tool 名稱 |

1629 

1630### `TaskNotificationMessage`

1631 

1632在背景任務完成、失敗或停止時發出。背景任務包括 `run_in_background` Bash 命令、Monitor 監視和背景子代理。

1633 

1634```python theme={null}

1635@dataclass

1636class TaskNotificationMessage(SystemMessage):

1637 task_id: str

1638 status: TaskNotificationStatus # "completed" | "failed" | "stopped"

1639 output_file: str

1640 summary: str

1641 uuid: str

1642 session_id: str

1643 tool_use_id: str | None = None

1644 usage: TaskUsage | None = None

1645```

1646 

1647| 欄位 | 類型 | 描述 |

1648| :------------ | :----------------------- | :---------------------------------------- |

1649| `task_id` | `str` | 任務的唯一識別碼 |

1650| `status` | `TaskNotificationStatus` | `"completed"`、`"failed"` 或 `"stopped"` 之一 |

1651| `output_file` | `str` | 任務輸出檔案的路徑 |

1652| `summary` | `str` | 任務結果的摘要 |

1653| `uuid` | `str` | 唯一消息識別碼 |

1654| `session_id` | `str` | session 識別碼 |

1655| `tool_use_id` | `str \| None` | 相關聯的 tool 使用 ID |

1656| `usage` | `TaskUsage \| None` | 任務的最終令牌使用情況 |

1657 

1658## 內容區塊類型

1659 

1660### `ContentBlock`

1661 

1662所有內容區塊的聯合類型。

1663 

1664```python theme={null}

1665ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock

1666```

1667 

1668### `TextBlock`

1669 

1670文字內容區塊。

1671 

1672```python theme={null}

1673@dataclass

1674class TextBlock:

1675 text: str

1676```

1677 

1678### `ThinkingBlock`

1679 

1680思考內容區塊(用於具有思考能力的模型)。

1681 

1682```python theme={null}

1683@dataclass

1684class ThinkingBlock:

1685 thinking: str

1686 signature: str

1687```

1688 

1689### `ToolUseBlock`

1690 

1691tool 使用請求區塊。

1692 

1693```python theme={null}

1694@dataclass

1695class ToolUseBlock:

1696 id: str

1697 name: str

1698 input: dict[str, Any]

1699```

1700 

1701### `ToolResultBlock`

1702 

1703tool 執行結果區塊。

1704 

1705```python theme={null}

1706@dataclass

1707class ToolResultBlock:

1708 tool_use_id: str

1709 content: str | list[dict[str, Any]] | None = None

1710 is_error: bool | None = None

1711```

1712 

1713## 錯誤類型

1714 

1715### `ClaudeSDKError`

1716 

1717所有 SDK 錯誤的基礎例外類別。

1718 

1719```python theme={null}

1720class ClaudeSDKError(Exception):

1721 """Base error for Claude SDK."""

1722```

1723 

1724### `CLINotFoundError`

1725 

1726當 Claude Code CLI 未安裝或找不到時引發。

1727 

1728```python theme={null}

1729class CLINotFoundError(CLIConnectionError):

1730 def __init__(

1731 self, message: str = "Claude Code not found", cli_path: str | None = None

1732 ):

1733 """

1734 Args:

1735 message: Error message (default: "Claude Code not found")

1736 cli_path: Optional path to the CLI that was not found

1737 """

1738```

1739 

1740### `CLIConnectionError`

1741 

1742當連接到 Claude Code 失敗時引發。

1743 

1744```python theme={null}

1745class CLIConnectionError(ClaudeSDKError):

1746 """Failed to connect to Claude Code."""

1747```

1748 

1749### `ProcessError`

1750 

1751當 Claude Code 程序失敗時引發。

1752 

1753```python theme={null}

1754class ProcessError(ClaudeSDKError):

1755 def __init__(

1756 self, message: str, exit_code: int | None = None, stderr: str | None = None

1757 ):

1758 self.exit_code = exit_code

1759 self.stderr = stderr

1760```

1761 

1762### `CLIJSONDecodeError`

1763 

1764當 JSON 解析失敗時引發。

1765 

1766```python theme={null}

1767class CLIJSONDecodeError(ClaudeSDKError):

1768 def __init__(self, line: str, original_error: Exception):

1769 """

1770 Args:

1771 line: The line that failed to parse

1772 original_error: The original JSON decode exception

1773 """

1774 self.line = line

1775 self.original_error = original_error

1776```

1777 

1778## Hook 類型

1779 

1780如需使用 hooks 的綜合指南,包括範例和常見模式,見 [Hooks 指南](/zh-TW/agent-sdk/hooks)。

1781 

1782### `HookEvent`

1783 

1784支援的 hook 事件類型。

1785 

1786```python theme={null}

1787HookEvent = Literal[

1788 "PreToolUse", # Called before tool execution

1789 "PostToolUse", # Called after tool execution

1790 "PostToolUseFailure", # Called when a tool execution fails

1791 "UserPromptSubmit", # Called when user submits a prompt

1792 "Stop", # Called when stopping execution

1793 "SubagentStop", # Called when a subagent stops

1794 "PreCompact", # Called before message compaction

1795 "Notification", # Called for notification events

1796 "SubagentStart", # Called when a subagent starts

1797 "PermissionRequest", # Called when a permission decision is needed

1798]

1799```

1800 

1801<Note>

1802 TypeScript SDK 支援 Python 中尚未提供的其他 hook 事件:`SessionStart`、`SessionEnd`、`Setup`、`TeammateIdle`、`TaskCompleted`、`ConfigChange`、`WorktreeCreate`、`WorktreeRemove` 和 `PostToolBatch`。

1803</Note>

1804 

1805### `HookCallback`

1806 

1807hook 回呼函數的類型定義。

1808 

1809```python theme={null}

1810HookCallback = Callable[[HookInput, str | None, HookContext], Awaitable[HookJSONOutput]]

1811```

1812 

1813參數:

1814 

1815* `input`:強類型 hook 輸入,具有基於 `hook_event_name` 的判別聯合(見 [`HookInput`](#hook-input))

1816* `tool_use_id`:可選 tool 使用識別碼(用於 tool 相關 hooks)

1817* `context`:具有其他資訊的 hook 上下文

1818 

1819返回可能包含以下內容的 [`HookJSONOutput`](#hook-json-output):

1820 

1821* `decision`:`"block"` 以阻止動作

1822* `systemMessage`:要新增到記錄的系統消息

1823* `hookSpecificOutput`:hook 特定輸出資料

1824 

1825### `HookContext`

1826 

1827傳遞給 hook 回呼的上下文資訊。

1828 

1829```python theme={null}

1830class HookContext(TypedDict):

1831 signal: Any | None # Future: abort signal support

1832```

1833 

1834### `HookMatcher`

1835 

1836用於將 hooks 符合到特定事件或 tools 的配置。

1837 

1838```python theme={null}

1839@dataclass

1840class HookMatcher:

1841 matcher: str | None = (

1842 None # Tool name or pattern to match (e.g., "Bash", "Write|Edit")

1843 )

1844 hooks: list[HookCallback] = field(

1845 default_factory=list

1846 ) # List of callbacks to execute

1847 timeout: float | None = (

1848 None # Timeout in seconds for all hooks in this matcher (default: 60)

1849 )

1850```

1851 

1852### `HookInput`

1853 

1854所有 hook 輸入類型的聯合類型。實際類型取決於 `hook_event_name` 欄位。

1855 

1856```python theme={null}

1857HookInput = (

1858 PreToolUseHookInput

1859 | PostToolUseHookInput

1860 | PostToolUseFailureHookInput

1861 | UserPromptSubmitHookInput

1862 | StopHookInput

1863 | SubagentStopHookInput

1864 | PreCompactHookInput

1865 | NotificationHookInput

1866 | SubagentStartHookInput

1867 | PermissionRequestHookInput

1868)

1869```

1870 

1871### `BaseHookInput`

1872 

1873所有 hook 輸入類型中存在的基礎欄位。

1874 

1875```python theme={null}

1876class BaseHookInput(TypedDict):

1877 session_id: str

1878 transcript_path: str

1879 cwd: str

1880 permission_mode: NotRequired[str]

1881```

1882 

1883| 欄位 | 類型 | 描述 |

1884| :---------------- | :-------- | :-------------- |

1885| `session_id` | `str` | 目前 session 識別碼 |

1886| `transcript_path` | `str` | session 記錄檔案的路徑 |

1887| `cwd` | `str` | 目前工作目錄 |

1888| `permission_mode` | `str`(可選) | 目前權限模式 |

1889 

1890### `PreToolUseHookInput`

1891 

1892`PreToolUse` hook 事件的輸入資料。

1893 

1894```python theme={null}

1895class PreToolUseHookInput(BaseHookInput):

1896 hook_event_name: Literal["PreToolUse"]

1897 tool_name: str

1898 tool_input: dict[str, Any]

1899 tool_use_id: str

1900 agent_id: NotRequired[str]

1901 agent_type: NotRequired[str]

1902```

1903 

1904| 欄位 | 類型 | 描述 |

1905| :---------------- | :---------------------- | :----------------------- |

1906| `hook_event_name` | `Literal["PreToolUse"]` | 始終為 "PreToolUse" |

1907| `tool_name` | `str` | 即將執行的 tool 名稱 |

1908| `tool_input` | `dict[str, Any]` | tool 的輸入參數 |

1909| `tool_use_id` | `str` | 此 tool 使用的唯一識別碼 |

1910| `agent_id` | `str`(可選) | 子代理識別碼,當 hook 在子代理內觸發時出現 |

1911| `agent_type` | `str`(可選) | 子代理類型,當 hook 在子代理內觸發時出現 |

1912 

1913### `PostToolUseHookInput`

1914 

1915`PostToolUse` hook 事件的輸入資料。

1916 

1917```python theme={null}

1918class PostToolUseHookInput(BaseHookInput):

1919 hook_event_name: Literal["PostToolUse"]

1920 tool_name: str

1921 tool_input: dict[str, Any]

1922 tool_response: Any

1923 tool_use_id: str

1924 agent_id: NotRequired[str]

1925 agent_type: NotRequired[str]

1926```

1927 

1928| 欄位 | 類型 | 描述 |

1929| :---------------- | :----------------------- | :----------------------- |

1930| `hook_event_name` | `Literal["PostToolUse"]` | 始終為 "PostToolUse" |

1931| `tool_name` | `str` | 已執行的 tool 名稱 |

1932| `tool_input` | `dict[str, Any]` | 使用的輸入參數 |

1933| `tool_response` | `Any` | tool 執行的回應 |

1934| `tool_use_id` | `str` | 此 tool 使用的唯一識別碼 |

1935| `agent_id` | `str`(可選) | 子代理識別碼,當 hook 在子代理內觸發時出現 |

1936| `agent_type` | `str`(可選) | 子代理類型,當 hook 在子代理內觸發時出現 |

1937 

1938### `PostToolUseFailureHookInput`

1939 

1940`PostToolUseFailure` hook 事件的輸入資料。在 tool 執行失敗時呼叫。

1941 

1942```python theme={null}

1943class PostToolUseFailureHookInput(BaseHookInput):

1944 hook_event_name: Literal["PostToolUseFailure"]

1945 tool_name: str

1946 tool_input: dict[str, Any]

1947 tool_use_id: str

1948 error: str

1949 is_interrupt: NotRequired[bool]

1950 agent_id: NotRequired[str]

1951 agent_type: NotRequired[str]

1952```

1953 

1954| 欄位 | 類型 | 描述 |

1955| :---------------- | :------------------------------ | :----------------------- |

1956| `hook_event_name` | `Literal["PostToolUseFailure"]` | 始終為 "PostToolUseFailure" |

1957| `tool_name` | `str` | 失敗的 tool 名稱 |

1958| `tool_input` | `dict[str, Any]` | 使用的輸入參數 |

1959| `tool_use_id` | `str` | 此 tool 使用的唯一識別碼 |

1960| `error` | `str` | 失敗執行的錯誤消息 |

1961| `is_interrupt` | `bool`(可選) | 失敗是否由中斷引起 |

1962| `agent_id` | `str`(可選) | 子代理識別碼,當 hook 在子代理內觸發時出現 |

1963| `agent_type` | `str`(可選) | 子代理類型,當 hook 在子代理內觸發時出現 |

1964 

1965### `UserPromptSubmitHookInput`

1966 

1967`UserPromptSubmit` hook 事件的輸入資料。

1968 

1969```python theme={null}

1970class UserPromptSubmitHookInput(BaseHookInput):

1971 hook_event_name: Literal["UserPromptSubmit"]

1972 prompt: str

1973```

1974 

1975| 欄位 | 類型 | 描述 |

1976| :---------------- | :---------------------------- | :--------------------- |

1977| `hook_event_name` | `Literal["UserPromptSubmit"]` | 始終為 "UserPromptSubmit" |

1978| `prompt` | `str` | 使用者提交的提示 |

1979 

1980### `StopHookInput`

1981 

1982`Stop` hook 事件的輸入資料。

1983 

1984```python theme={null}

1985class StopHookInput(BaseHookInput):

1986 hook_event_name: Literal["Stop"]

1987 stop_hook_active: bool

1988```

1989 

1990| 欄位 | 類型 | 描述 |

1991| :----------------- | :---------------- | :------------- |

1992| `hook_event_name` | `Literal["Stop"]` | 始終為 "Stop" |

1993| `stop_hook_active` | `bool` | stop hook 是否活躍 |

1994 

1995### `SubagentStopHookInput`

1996 

1997`SubagentStop` hook 事件的輸入資料。

1998 

1999```python theme={null}

2000class SubagentStopHookInput(BaseHookInput):

2001 hook_event_name: Literal["SubagentStop"]

2002 stop_hook_active: bool

2003 agent_id: str

2004 agent_transcript_path: str

2005 agent_type: str

2006```

2007 

2008| 欄位 | 類型 | 描述 |

2009| :---------------------- | :------------------------ | :----------------- |

2010| `hook_event_name` | `Literal["SubagentStop"]` | 始終為 "SubagentStop" |

2011| `stop_hook_active` | `bool` | stop hook 是否活躍 |

2012| `agent_id` | `str` | 子代理的唯一識別碼 |

2013| `agent_transcript_path` | `str` | 子代理記錄檔案的路徑 |

2014| `agent_type` | `str` | 子代理的類型 |

2015 

2016### `PreCompactHookInput`

2017 

2018`PreCompact` hook 事件的輸入資料。

2019 

2020```python theme={null}

2021class PreCompactHookInput(BaseHookInput):

2022 hook_event_name: Literal["PreCompact"]

2023 trigger: Literal["manual", "auto"]

2024 custom_instructions: str | None

2025```

2026 

2027| 欄位 | 類型 | 描述 |

2028| :-------------------- | :-------------------------- | :--------------- |

2029| `hook_event_name` | `Literal["PreCompact"]` | 始終為 "PreCompact" |

2030| `trigger` | `Literal["manual", "auto"]` | 觸發壓縮的原因 |

2031| `custom_instructions` | `str \| None` | 壓縮的自訂指示 |

2032 

2033### `NotificationHookInput`

2034 

2035`Notification` hook 事件的輸入資料。

2036 

2037```python theme={null}

2038class NotificationHookInput(BaseHookInput):

2039 hook_event_name: Literal["Notification"]

2040 message: str

2041 title: NotRequired[str]

2042 notification_type: str

2043```

2044 

2045| 欄位 | 類型 | 描述 |

2046| :------------------ | :------------------------ | :----------------- |

2047| `hook_event_name` | `Literal["Notification"]` | 始終為 "Notification" |

2048| `message` | `str` | 通知消息內容 |

2049| `title` | `str`(可選) | 通知標題 |

2050| `notification_type` | `str` | 通知類型 |

2051 

2052### `SubagentStartHookInput`

2053 

2054`SubagentStart` hook 事件的輸入資料。

2055 

2056```python theme={null}

2057class SubagentStartHookInput(BaseHookInput):

2058 hook_event_name: Literal["SubagentStart"]

2059 agent_id: str

2060 agent_type: str

2061```

2062 

2063| 欄位 | 類型 | 描述 |

2064| :---------------- | :------------------------- | :------------------ |

2065| `hook_event_name` | `Literal["SubagentStart"]` | 始終為 "SubagentStart" |

2066| `agent_id` | `str` | 子代理的唯一識別碼 |

2067| `agent_type` | `str` | 子代理的類型 |

2068 

2069### `PermissionRequestHookInput`

2070 

2071`PermissionRequest` hook 事件的輸入資料。允許 hooks 以程式設計方式處理權限決策。

2072 

2073```python theme={null}

2074class PermissionRequestHookInput(BaseHookInput):

2075 hook_event_name: Literal["PermissionRequest"]

2076 tool_name: str

2077 tool_input: dict[str, Any]

2078 permission_suggestions: NotRequired[list[Any]]

2079```

2080 

2081| 欄位 | 類型 | 描述 |

2082| :----------------------- | :----------------------------- | :---------------------- |

2083| `hook_event_name` | `Literal["PermissionRequest"]` | 始終為 "PermissionRequest" |

2084| `tool_name` | `str` | 請求權限的 tool 名稱 |

2085| `tool_input` | `dict[str, Any]` | tool 的輸入參數 |

2086| `permission_suggestions` | `list[Any]`(可選) | 來自 CLI 的建議權限更新 |

2087 

2088### `HookJSONOutput`

2089 

2090hook 回呼返回值的聯合類型。

2091 

2092```python theme={null}

2093HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput

2094```

2095 

2096#### `SyncHookJSONOutput`

2097 

2098具有控制和決策欄位的同步 hook 輸出。

2099 

2100```python theme={null}

2101class SyncHookJSONOutput(TypedDict):

2102 # Control fields

2103 continue_: NotRequired[bool] # Whether to proceed (default: True)

2104 suppressOutput: NotRequired[bool] # Hide stdout from transcript

2105 stopReason: NotRequired[str] # Message when continue is False

2106 

2107 # Decision fields

2108 decision: NotRequired[Literal["block"]]

2109 systemMessage: NotRequired[str] # Warning message for user

2110 reason: NotRequired[str] # Feedback for Claude

2111 

2112 # Hook-specific output

2113 hookSpecificOutput: NotRequired[HookSpecificOutput]

2114```

2115 

2116<Note>

2117 在 Python 程式碼中使用 `continue_`(帶下劃線)。發送到 CLI 時會自動轉換為 `continue`。

2118</Note>

2119 

2120#### `HookSpecificOutput`

2121 

2122包含 hook 事件名稱和事件特定欄位的 `TypedDict`。形狀取決於 `hookEventName` 值。如需每個 hook 事件的可用欄位的完整詳情,見 [使用 hooks 控制執行](/zh-TW/agent-sdk/hooks#outputs)。

2123 

2124事件特定輸出類型的判別聯合。`hookEventName` 欄位決定哪些欄位有效。

2125 

2126```python theme={null}

2127class PreToolUseHookSpecificOutput(TypedDict):

2128 hookEventName: Literal["PreToolUse"]

2129 permissionDecision: NotRequired[Literal["allow", "deny", "ask"]]

2130 permissionDecisionReason: NotRequired[str]

2131 updatedInput: NotRequired[dict[str, Any]]

2132 additionalContext: NotRequired[str]

2133 

2134 

2135class PostToolUseHookSpecificOutput(TypedDict):

2136 hookEventName: Literal["PostToolUse"]

2137 additionalContext: NotRequired[str]

2138 updatedMCPToolOutput: NotRequired[Any]

2139 

2140 

2141class PostToolUseFailureHookSpecificOutput(TypedDict):

2142 hookEventName: Literal["PostToolUseFailure"]

2143 additionalContext: NotRequired[str]

2144 

2145 

2146class UserPromptSubmitHookSpecificOutput(TypedDict):

2147 hookEventName: Literal["UserPromptSubmit"]

2148 additionalContext: NotRequired[str]

2149 

2150 

2151class NotificationHookSpecificOutput(TypedDict):

2152 hookEventName: Literal["Notification"]

2153 additionalContext: NotRequired[str]

2154 

2155 

2156class SubagentStartHookSpecificOutput(TypedDict):

2157 hookEventName: Literal["SubagentStart"]

2158 additionalContext: NotRequired[str]

2159 

2160 

2161class PermissionRequestHookSpecificOutput(TypedDict):

2162 hookEventName: Literal["PermissionRequest"]

2163 decision: dict[str, Any]

2164 

2165 

2166HookSpecificOutput = (

2167 PreToolUseHookSpecificOutput

2168 | PostToolUseHookSpecificOutput

2169 | PostToolUseFailureHookSpecificOutput

2170 | UserPromptSubmitHookSpecificOutput

2171 | NotificationHookSpecificOutput

2172 | SubagentStartHookSpecificOutput

2173 | PermissionRequestHookSpecificOutput

2174)

2175```

2176 

2177#### `AsyncHookJSONOutput`

2178 

2179延遲 hook 執行的非同步 hook 輸出。

2180 

2181```python theme={null}

2182class AsyncHookJSONOutput(TypedDict):

2183 async_: Literal[True] # Set to True to defer execution

2184 asyncTimeout: NotRequired[int] # Timeout in milliseconds

2185```

2186 

2187<Note>

2188 在 Python 程式碼中使用 `async_`(帶下劃線)。發送到 CLI 時會自動轉換為 `async`。

2189</Note>

2190 

2191### Hook 使用範例

2192 

2193此範例註冊兩個 hooks:一個阻止危險的 bash 命令(如 `rm -rf /`),另一個記錄所有 tool 使用情況以進行審計。安全 hook 僅在 Bash 命令上執行(透過 `matcher`),而記錄 hook 在所有 tools 上執行。

2194 

2195```python theme={null}

2196from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, HookContext

2197from typing import Any

2198 

2199 

2200async def validate_bash_command(

2201 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext

2202) -> dict[str, Any]:

2203 """Validate and potentially block dangerous bash commands."""

2204 if input_data["tool_name"] == "Bash":

2205 command = input_data["tool_input"].get("command", "")

2206 if "rm -rf /" in command:

2207 return {

2208 "hookSpecificOutput": {

2209 "hookEventName": "PreToolUse",

2210 "permissionDecision": "deny",

2211 "permissionDecisionReason": "Dangerous command blocked",

2212 }

2213 }

2214 return {}

2215 

2216 

2217async def log_tool_use(

2218 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext

2219) -> dict[str, Any]:

2220 """Log all tool usage for auditing."""

2221 print(f"Tool used: {input_data.get('tool_name')}")

2222 return {}

2223 

2224 

2225options = ClaudeAgentOptions(

2226 hooks={

2227 "PreToolUse": [

2228 HookMatcher(

2229 matcher="Bash", hooks=[validate_bash_command], timeout=120

2230 ), # 2 min for validation

2231 HookMatcher(

2232 hooks=[log_tool_use]

2233 ), # Applies to all tools (default 60s timeout)

2234 ],

2235 "PostToolUse": [HookMatcher(hooks=[log_tool_use])],

2236 }

2237)

2238 

2239async for message in query(prompt="Analyze this codebase", options=options):

2240 print(message)

2241```

2242 

2243## Tool 輸入/輸出類型

2244 

2245所有內建 Claude Code tools 的輸入/輸出架構文件。雖然 Python SDK 不將這些匯出為類型,但它們代表消息中 tool 輸入和輸出的結構。

2246 

2247### Agent

2248 

2249**Tool 名稱:** `Agent`(先前為 `Task`,仍接受作為別名)

2250 

2251**輸入:**

2252 

2253```python theme={null}

2254{

2255 "description": str, # A short (3-5 word) description of the task

2256 "prompt": str, # The task for the agent to perform

2257 "subagent_type": str, # The type of specialized agent to use

2258}

2259```

2260 

2261**輸出:**

2262 

2263```python theme={null}

2264{

2265 "result": str, # Final result from the subagent

2266 "usage": dict | None, # Token usage statistics

2267 "total_cost_usd": float | None, # Estimated total cost in USD

2268 "duration_ms": int | None, # Execution duration in milliseconds

2269}

2270```

2271 

2272### AskUserQuestion

2273 

2274**Tool 名稱:** `AskUserQuestion`

2275 

2276在執行期間詢問使用者澄清問題。見 [處理批准和使用者輸入](/zh-TW/agent-sdk/user-input#handle-clarifying-questions) 以了解使用詳情。

2277 

2278**輸入:**

2279 

2280```python theme={null}

2281{

2282 "questions": [ # Questions to ask the user (1-4 questions)

2283 {

2284 "question": str, # The complete question to ask the user

2285 "header": str, # Very short label displayed as a chip/tag (max 12 chars)

2286 "options": [ # The available choices (2-4 options)

2287 {

2288 "label": str, # Display text for this option (1-5 words)

2289 "description": str, # Explanation of what this option means

2290 }

2291 ],

2292 "multiSelect": bool, # Set to true to allow multiple selections

2293 }

2294 ],

2295 "answers": dict | None, # User answers populated by the permission system

2296}

2297```

2298 

2299**輸出:**

2300 

2301```python theme={null}

2302{

2303 "questions": [ # The questions that were asked

2304 {

2305 "question": str,

2306 "header": str,

2307 "options": [{"label": str, "description": str}],

2308 "multiSelect": bool,

2309 }

2310 ],

2311 "answers": dict[str, str], # Maps question text to answer string

2312 # Multi-select answers are comma-separated

2313}

2314```

2315 

2316### Bash

2317 

2318**Tool 名稱:** `Bash`

2319 

2320**輸入:**

2321 

2322```python theme={null}

2323{

2324 "command": str, # The command to execute

2325 "timeout": int | None, # Optional timeout in milliseconds (max 600000)

2326 "description": str | None, # Clear, concise description (5-10 words)

2327 "run_in_background": bool | None, # Set to true to run in background

2328}

2329```

2330 

2331**輸出:**

2332 

2333```python theme={null}

2334{

2335 "output": str, # Combined stdout and stderr output

2336 "exitCode": int, # Exit code of the command

2337 "killed": bool | None, # Whether command was killed due to timeout

2338 "shellId": str | None, # Shell ID for background processes

2339}

2340```

2341 

2342### Monitor

2343 

2344**Tool 名稱:** `Monitor`

2345 

2346執行背景腳本並將每個 stdout 行作為事件傳遞給 Claude,以便它可以做出反應而無需輪詢。Monitor 遵循與 Bash 相同的權限規則。見 [Monitor tool 參考](/zh-TW/tools-reference#monitor-tool) 以了解行為和提供者可用性。

2347 

2348**輸入:**

2349 

2350```python theme={null}

2351{

2352 "command": str, # Shell script; each stdout line is an event, exit ends the watch

2353 "description": str, # Short description shown in notifications

2354 "timeout_ms": int | None, # Kill after this deadline (default 300000, max 3600000)

2355 "persistent": bool | None, # Run for the lifetime of the session; stop with TaskStop

2356}

2357```

2358 

2359**輸出:**

2360 

2361```python theme={null}

2362{

2363 "taskId": str, # ID of the background monitor task

2364 "timeoutMs": int, # Timeout deadline in milliseconds

2365 "persistent": bool | None, # True when running until TaskStop or session end

2366}

2367```

2368 

2369### Edit

2370 

2371**Tool 名稱:** `Edit`

2372 

2373**輸入:**

2374 

2375```python theme={null}

2376{

2377 "file_path": str, # The absolute path to the file to modify

2378 "old_string": str, # The text to replace

2379 "new_string": str, # The text to replace it with

2380 "replace_all": bool | None, # Replace all occurrences (default False)

2381}

2382```

2383 

2384**輸出:**

2385 

2386```python theme={null}

2387{

2388 "message": str, # Confirmation message

2389 "replacements": int, # Number of replacements made

2390 "file_path": str, # File path that was edited

2391}

2392```

2393 

2394### Read

2395 

2396**Tool 名稱:** `Read`

2397 

2398**輸入:**

2399 

2400```python theme={null}

2401{

2402 "file_path": str, # The absolute path to the file to read

2403 "offset": int | None, # The line number to start reading from

2404 "limit": int | None, # The number of lines to read

2405}

2406```

2407 

2408**輸出(文字檔案):**

2409 

2410```python theme={null}

2411{

2412 "content": str, # File contents with line numbers

2413 "total_lines": int, # Total number of lines in file

2414 "lines_returned": int, # Lines actually returned

2415}

2416```

2417 

2418**輸出(影像):**

2419 

2420```python theme={null}

2421{

2422 "image": str, # Base64 encoded image data

2423 "mime_type": str, # Image MIME type

2424 "file_size": int, # File size in bytes

2425}

2426```

2427 

2428### Write

2429 

2430**Tool 名稱:** `Write`

2431 

2432**輸入:**

2433 

2434```python theme={null}

2435{

2436 "file_path": str, # The absolute path to the file to write

2437 "content": str, # The content to write to the file

2438}

2439```

2440 

2441**輸出:**

2442 

2443```python theme={null}

2444{

2445 "message": str, # Success message

2446 "bytes_written": int, # Number of bytes written

2447 "file_path": str, # File path that was written

2448}

2449```

2450 

2451### Glob

2452 

2453**Tool 名稱:** `Glob`

2454 

2455**輸入:**

2456 

2457```python theme={null}

2458{

2459 "pattern": str, # The glob pattern to match files against

2460 "path": str | None, # The directory to search in (defaults to cwd)

2461}

2462```

2463 

2464**輸出:**

2465 

2466```python theme={null}

2467{

2468 "matches": list[str], # Array of matching file paths

2469 "count": int, # Number of matches found

2470 "search_path": str, # Search directory used

2471}

2472```

2473 

2474### Grep

2475 

2476**Tool 名稱:** `Grep`

2477 

2478**輸入:**

2479 

2480```python theme={null}

2481{

2482 "pattern": str, # The regular expression pattern

2483 "path": str | None, # File or directory to search in

2484 "glob": str | None, # Glob pattern to filter files

2485 "type": str | None, # File type to search

2486 "output_mode": str | None, # "content", "files_with_matches", or "count"

2487 "-i": bool | None, # Case insensitive search

2488 "-n": bool | None, # Show line numbers

2489 "-B": int | None, # Lines to show before each match

2490 "-A": int | None, # Lines to show after each match

2491 "-C": int | None, # Lines to show before and after

2492 "head_limit": int | None, # Limit output to first N lines/entries

2493 "multiline": bool | None, # Enable multiline mode

2494}

2495```

2496 

2497**輸出(content 模式):**

2498 

2499```python theme={null}

2500{

2501 "matches": [

2502 {

2503 "file": str,

2504 "line_number": int | None,

2505 "line": str,

2506 "before_context": list[str] | None,

2507 "after_context": list[str] | None,

2508 }

2509 ],

2510 "total_matches": int,

2511}

2512```

2513 

2514**輸出(files\_with\_matches 模式):**

2515 

2516```python theme={null}

2517{

2518 "files": list[str], # Files containing matches

2519 "count": int, # Number of files with matches

2520}

2521```

2522 

2523### NotebookEdit

2524 

2525**Tool 名稱:** `NotebookEdit`

2526 

2527**輸入:**

2528 

2529```python theme={null}

2530{

2531 "notebook_path": str, # Absolute path to the Jupyter notebook

2532 "cell_id": str | None, # The ID of the cell to edit

2533 "new_source": str, # The new source for the cell

2534 "cell_type": "code" | "markdown" | None, # The type of the cell

2535 "edit_mode": "replace" | "insert" | "delete" | None, # Edit operation type

2536}

2537```

2538 

2539**輸出:**

2540 

2541```python theme={null}

2542{

2543 "message": str, # Success message

2544 "edit_type": "replaced" | "inserted" | "deleted", # Type of edit performed

2545 "cell_id": str | None, # Cell ID that was affected

2546 "total_cells": int, # Total cells in notebook after edit

2547}

2548```

2549 

2550### WebFetch

2551 

2552**Tool 名稱:** `WebFetch`

2553 

2554**輸入:**

2555 

2556```python theme={null}

2557{

2558 "url": str, # The URL to fetch content from

2559 "prompt": str, # The prompt to run on the fetched content

2560}

2561```

2562 

2563**輸出:**

2564 

2565```python theme={null}

2566{

2567 "response": str, # AI model's response to the prompt

2568 "url": str, # URL that was fetched

2569 "final_url": str | None, # Final URL after redirects

2570 "status_code": int | None, # HTTP status code

2571}

2572```

2573 

2574### WebSearch

2575 

2576**Tool 名稱:** `WebSearch`

2577 

2578**輸入:**

2579 

2580```python theme={null}

2581{

2582 "query": str, # The search query to use

2583 "allowed_domains": list[str] | None, # Only include results from these domains

2584 "blocked_domains": list[str] | None, # Never include results from these domains

2585}

2586```

2587 

2588**輸出:**

2589 

2590```python theme={null}

2591{

2592 "results": [{"title": str, "url": str, "snippet": str, "metadata": dict | None}],

2593 "total_results": int,

2594 "query": str,

2595}

2596```

2597 

2598### TodoWrite

2599 

2600**Tool 名稱:** `TodoWrite`

2601 

2602**輸入:**

2603 

2604```python theme={null}

2605{

2606 "todos": [

2607 {

2608 "content": str, # The task description

2609 "status": "pending" | "in_progress" | "completed", # Task status

2610 "activeForm": str, # Active form of the description

2611 }

2612 ]

2613}

2614```

2615 

2616**輸出:**

2617 

2618```python theme={null}

2619{

2620 "message": str, # Success message

2621 "stats": {"total": int, "pending": int, "in_progress": int, "completed": int},

2622}

2623```

2624 

2625### BashOutput

2626 

2627**Tool 名稱:** `BashOutput`

2628 

2629**輸入:**

2630 

2631```python theme={null}

2632{

2633 "bash_id": str, # The ID of the background shell

2634 "filter": str | None, # Optional regex to filter output lines

2635}

2636```

2637 

2638**輸出:**

2639 

2640```python theme={null}

2641{

2642 "output": str, # New output since last check

2643 "status": "running" | "completed" | "failed", # Current shell status

2644 "exitCode": int | None, # Exit code when completed

2645}

2646```

2647 

2648### KillBash

2649 

2650**Tool 名稱:** `KillBash`

2651 

2652**輸入:**

2653 

2654```python theme={null}

2655{

2656 "shell_id": str # The ID of the background shell to kill

2657}

2658```

2659 

2660**輸出:**

2661 

2662```python theme={null}

2663{

2664 "message": str, # Success message

2665 "shell_id": str, # ID of the killed shell

2666}

2667```

2668 

2669### ExitPlanMode

2670 

2671**Tool 名稱:** `ExitPlanMode`

2672 

2673**輸入:**

2674 

2675```python theme={null}

2676{

2677 "plan": str # The plan to run by the user for approval

2678}

2679```

2680 

2681**輸出:**

2682 

2683```python theme={null}

2684{

2685 "message": str, # Confirmation message

2686 "approved": bool | None, # Whether user approved the plan

2687}

2688```

2689 

2690### ListMcpResources

2691 

2692**Tool 名稱:** `ListMcpResources`

2693 

2694**輸入:**

2695 

2696```python theme={null}

2697{

2698 "server": str | None # Optional server name to filter resources by

2699}

2700```

2701 

2702**輸出:**

2703 

2704```python theme={null}

2705{

2706 "resources": [

2707 {

2708 "uri": str,

2709 "name": str,

2710 "description": str | None,

2711 "mimeType": str | None,

2712 "server": str,

2713 }

2714 ],

2715 "total": int,

2716}

2717```

2718 

2719### ReadMcpResource

2720 

2721**Tool 名稱:** `ReadMcpResource`

2722 

2723**輸入:**

2724 

2725```python theme={null}

2726{

2727 "server": str, #MCP 伺服器名稱

2728 "uri": str, # 要讀取的資源 URI

2729}

2730```

2731 

2732**輸出:**

2733 

2734```python theme={null}

2735{

2736 "contents": [

2737 {"uri": str, "mimeType": str | None, "text": str | None, "blob": str | None}

2738 ],

2739 "server": str,

2740}

2741```

2742 

2743## 使用 ClaudeSDKClient 的進階功能

2744 

2745### 建立持續對話介面

2746 

2747```python theme={null}

2748from claude_agent_sdk import (

2749 ClaudeSDKClient,

2750 ClaudeAgentOptions,

2751 AssistantMessage,

2752 TextBlock,

2753)

2754import asyncio

2755 

2756 

2757class ConversationSession:

2758 """Maintains a single conversation session with Claude."""

2759 

2760 def __init__(self, options: ClaudeAgentOptions | None = None):

2761 self.client = ClaudeSDKClient(options)

2762 self.turn_count = 0

2763 

2764 async def start(self):

2765 await self.client.connect()

2766 print("Starting conversation session. Claude will remember context.")

2767 print(

2768 "Commands: 'exit' to quit, 'interrupt' to stop current task, 'new' for new session"

2769 )

2770 

2771 while True:

2772 user_input = input(f"\n[Turn {self.turn_count + 1}] You: ")

2773 

2774 if user_input.lower() == "exit":

2775 break

2776 elif user_input.lower() == "interrupt":

2777 await self.client.interrupt()

2778 print("Task interrupted!")

2779 continue

2780 elif user_input.lower() == "new":

2781 # Disconnect and reconnect for a fresh session

2782 await self.client.disconnect()

2783 await self.client.connect()

2784 self.turn_count = 0

2785 print("Started new conversation session (previous context cleared)")

2786 continue

2787 

2788 # Send message - the session retains all previous messages

2789 await self.client.query(user_input)

2790 self.turn_count += 1

2791 

2792 # Process response

2793 print(f"[Turn {self.turn_count}] Claude: ", end="")

2794 async for message in self.client.receive_response():

2795 if isinstance(message, AssistantMessage):

2796 for block in message.content:

2797 if isinstance(block, TextBlock):

2798 print(block.text, end="")

2799 print() # New line after response

2800 

2801 await self.client.disconnect()

2802 print(f"Conversation ended after {self.turn_count} turns.")

2803 

2804 

2805async def main():

2806 options = ClaudeAgentOptions(

2807 allowed_tools=["Read", "Write", "Bash"], permission_mode="acceptEdits"

2808 )

2809 session = ConversationSession(options)

2810 await session.start()

2811 

2812 

2813# Example conversation:

2814# Turn 1 - You: "Create a file called hello.py"

2815# Turn 1 - Claude: "I'll create a hello.py file for you..."

2816# Turn 2 - You: "What's in that file?"

2817# Turn 2 - Claude: "The hello.py file I just created contains..." (remembers!)

2818# Turn 3 - You: "Add a main function to it"

2819# Turn 3 - Claude: "I'll add a main function to hello.py..." (knows which file!)

2820 

2821asyncio.run(main())

2822```

2823 

2824### 使用 Hooks 進行行為修改

2825 

2826```python theme={null}

2827from claude_agent_sdk import (

2828 ClaudeSDKClient,

2829 ClaudeAgentOptions,

2830 HookMatcher,

2831 HookContext,

2832)

2833import asyncio

2834from typing import Any

2835 

2836 

2837async def pre_tool_logger(

2838 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext

2839) -> dict[str, Any]:

2840 """Log all tool usage before execution."""

2841 tool_name = input_data.get("tool_name", "unknown")

2842 print(f"[PRE-TOOL] About to use: {tool_name}")

2843 

2844 # You can modify or block the tool execution here

2845 if tool_name == "Bash" and "rm -rf" in str(input_data.get("tool_input", {})):

2846 return {

2847 "hookSpecificOutput": {

2848 "hookEventName": "PreToolUse",

2849 "permissionDecision": "deny",

2850 "permissionDecisionReason": "Dangerous command blocked",

2851 }

2852 }

2853 return {}

2854 

2855 

2856async def post_tool_logger(

2857 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext

2858) -> dict[str, Any]:

2859 """Log results after tool execution."""

2860 tool_name = input_data.get("tool_name", "unknown")

2861 print(f"[POST-TOOL] Completed: {tool_name}")

2862 return {}

2863 

2864 

2865async def user_prompt_modifier(

2866 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext

2867) -> dict[str, Any]:

2868 """Add context to user prompts."""

2869 original_prompt = input_data.get("prompt", "")

2870 

2871 # Add a timestamp as additional context for Claude to see

2872 from datetime import datetime

2873 

2874 timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

2875 

2876 return {

2877 "hookSpecificOutput": {

2878 "hookEventName": "UserPromptSubmit",

2879 "additionalContext": f"[Submitted at {timestamp}] Original prompt: {original_prompt}",

2880 }

2881 }

2882 

2883 

2884async def main():

2885 options = ClaudeAgentOptions(

2886 hooks={

2887 "PreToolUse": [

2888 HookMatcher(hooks=[pre_tool_logger]),

2889 HookMatcher(matcher="Bash", hooks=[pre_tool_logger]),

2890 ],

2891 "PostToolUse": [HookMatcher(hooks=[post_tool_logger])],

2892 "UserPromptSubmit": [HookMatcher(hooks=[user_prompt_modifier])],

2893 },

2894 allowed_tools=["Read", "Write", "Bash"],

2895 )

2896 

2897 async with ClaudeSDKClient(options=options) as client:

2898 await client.query("List files in current directory")

2899 

2900 async for message in client.receive_response():

2901 # Hooks will automatically log tool usage

2902 pass

2903 

2904 

2905asyncio.run(main())

2906```

2907 

2908### 即時進度監控

2909 

2910```python theme={null}

2911from claude_agent_sdk import (

2912 ClaudeSDKClient,

2913 ClaudeAgentOptions,

2914 AssistantMessage,

2915 ToolUseBlock,

2916 ToolResultBlock,

2917 TextBlock,

2918)

2919import asyncio

2920 

2921 

2922async def monitor_progress():

2923 options = ClaudeAgentOptions(

2924 allowed_tools=["Write", "Bash"], permission_mode="acceptEdits"

2925 )

2926 

2927 async with ClaudeSDKClient(options=options) as client:

2928 await client.query("Create 5 Python files with different sorting algorithms")

2929 

2930 # Monitor progress in real-time

2931 async for message in client.receive_response():

2932 if isinstance(message, AssistantMessage):

2933 for block in message.content:

2934 if isinstance(block, ToolUseBlock):

2935 if block.name == "Write":

2936 file_path = block.input.get("file_path", "")

2937 print(f"Creating: {file_path}")

2938 elif isinstance(block, ToolResultBlock):

2939 print("Completed tool execution")

2940 elif isinstance(block, TextBlock):

2941 print(f"Claude says: {block.text[:100]}...")

2942 

2943 print("Task completed!")

2944 

2945 

2946asyncio.run(monitor_progress())

2947```

2948 

2949## 範例使用

2950 

2951### 基本檔案操作(使用 query)

2952 

2953```python theme={null}

2954from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ToolUseBlock

2955import asyncio

2956 

2957 

2958async def create_project():

2959 options = ClaudeAgentOptions(

2960 allowed_tools=["Read", "Write", "Bash"],

2961 permission_mode="acceptEdits",

2962 cwd="/home/user/project",

2963 )

2964 

2965 async for message in query(

2966 prompt="Create a Python project structure with setup.py", options=options

2967 ):

2968 if isinstance(message, AssistantMessage):

2969 for block in message.content:

2970 if isinstance(block, ToolUseBlock):

2971 print(f"Using tool: {block.name}")

2972 

2973 

2974asyncio.run(create_project())

2975```

2976 

2977### 錯誤處理

2978 

2979```python theme={null}

2980from claude_agent_sdk import query, CLINotFoundError, ProcessError, CLIJSONDecodeError

2981 

2982try:

2983 async for message in query(prompt="Hello"):

2984 print(message)

2985except CLINotFoundError:

2986 print(

2987 "Claude Code CLI not found. Try reinstalling: pip install --force-reinstall claude-agent-sdk"

2988 )

2989except ProcessError as e:

2990 print(f"Process failed with exit code: {e.exit_code}")

2991except CLIJSONDecodeError as e:

2992 print(f"Failed to parse response: {e}")

2993```

2994 

2995### 使用客戶端的串流模式

2996 

2997```python theme={null}

2998from claude_agent_sdk import ClaudeSDKClient

2999import asyncio

3000 

3001 

3002async def interactive_session():

3003 async with ClaudeSDKClient() as client:

3004 # Send initial message

3005 await client.query("What's the weather like?")

3006 

3007 # Process responses

3008 async for msg in client.receive_response():

3009 print(msg)

3010 

3011 # Send follow-up

3012 await client.query("Tell me more about that")

3013 

3014 # Process follow-up response

3015 async for msg in client.receive_response():

3016 print(msg)

3017 

3018 

3019asyncio.run(interactive_session())

3020```

3021 

3022### 使用 ClaudeSDKClient 的自訂 tools

3023 

3024```python theme={null}

3025from claude_agent_sdk import (

3026 ClaudeSDKClient,

3027 ClaudeAgentOptions,

3028 tool,

3029 create_sdk_mcp_server,

3030 AssistantMessage,

3031 TextBlock,

3032)

3033import asyncio

3034from typing import Any

3035 

3036 

3037# Define custom tools with @tool decorator

3038@tool("calculate", "Perform mathematical calculations", {"expression": str})

3039async def calculate(args: dict[str, Any]) -> dict[str, Any]:

3040 try:

3041 result = eval(args["expression"], {"__builtins__": {}})

3042 return {"content": [{"type": "text", "text": f"Result: {result}"}]}

3043 except Exception as e:

3044 return {

3045 "content": [{"type": "text", "text": f"Error: {str(e)}"}],

3046 "is_error": True,

3047 }

3048 

3049 

3050@tool("get_time", "Get current time", {})

3051async def get_time(args: dict[str, Any]) -> dict[str, Any]:

3052 from datetime import datetime

3053 

3054 current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

3055 return {"content": [{"type": "text", "text": f"Current time: {current_time}"}]}

3056 

3057 

3058async def main():

3059 # Create SDK MCP server with custom tools

3060 my_server = create_sdk_mcp_server(

3061 name="utilities", version="1.0.0", tools=[calculate, get_time]

3062 )

3063 

3064 # Configure options with the server

3065 options = ClaudeAgentOptions(

3066 mcp_servers={"utils": my_server},

3067 allowed_tools=["mcp__utils__calculate", "mcp__utils__get_time"],

3068 )

3069 

3070 # Use ClaudeSDKClient for interactive tool usage

3071 async with ClaudeSDKClient(options=options) as client:

3072 await client.query("What's 123 * 456?")

3073 

3074 # Process calculation response

3075 async for message in client.receive_response():

3076 if isinstance(message, AssistantMessage):

3077 for block in message.content:

3078 if isinstance(block, TextBlock):

3079 print(f"Calculation: {block.text}")

3080 

3081 # Follow up with time query

3082 await client.query("What time is it now?")

3083 

3084 async for message in client.receive_response():

3085 if isinstance(message, AssistantMessage):

3086 for block in message.content:

3087 if isinstance(block, TextBlock):

3088 print(f"Time: {block.text}")

3089 

3090 

3091asyncio.run(main())

3092```

3093 

3094## 沙箱配置

3095 

3096### `SandboxSettings`

3097 

3098沙箱行為的配置。使用此來啟用命令沙箱並以程式設計方式配置網路限制。

3099 

3100```python theme={null}

3101class SandboxSettings(TypedDict, total=False):

3102 enabled: bool

3103 autoAllowBashIfSandboxed: bool

3104 excludedCommands: list[str]

3105 allowUnsandboxedCommands: bool

3106 network: SandboxNetworkConfig

3107 ignoreViolations: SandboxIgnoreViolations

3108 enableWeakerNestedSandbox: bool

3109```

3110 

3111| 屬性 | 類型 | 預設 | 描述 |

3112| :-------------------------- | :------------------------------------------------------ | :------ | :---------------------------------------------------------------------------------------------------------------------------------- |

3113| `enabled` | `bool` | `False` | 為命令執行啟用沙箱模式 |

3114| `autoAllowBashIfSandboxed` | `bool` | `True` | 啟用沙箱時自動批准 bash 命令 |

3115| `excludedCommands` | `list[str]` | `[]` | 始終繞過沙箱限制的命令(例如 `["docker"]`)。這些自動執行沙箱外,無需模型參與 |

3116| `allowUnsandboxedCommands` | `bool` | `True` | 允許模型請求在沙箱外執行命令。當為 `True` 時,模型可以在 tool 輸入中設定 `dangerouslyDisableSandbox`,這會回退到[權限系統](#permissions-fallback-for-unsandboxed-commands) |

3117| `network` | [`SandboxNetworkConfig`](#sandbox-network-config) | `None` | 網路特定的沙箱配置 |

3118| `ignoreViolations` | [`SandboxIgnoreViolations`](#sandbox-ignore-violations) | `None` | 配置要忽略的沙箱違規 |

3119| `enableWeakerNestedSandbox` | `bool` | `False` | 啟用較弱的嵌套沙箱以相容性 |

3120 

3121#### 範例使用

3122 

3123```python theme={null}

3124from claude_agent_sdk import query, ClaudeAgentOptions, SandboxSettings

3125 

3126sandbox_settings: SandboxSettings = {

3127 "enabled": True,

3128 "autoAllowBashIfSandboxed": True,

3129 "network": {"allowLocalBinding": True},

3130}

3131 

3132async for message in query(

3133 prompt="Build and test my project",

3134 options=ClaudeAgentOptions(sandbox=sandbox_settings),

3135):

3136 print(message)

3137```

3138 

3139<Warning>

3140 **Unix socket 安全性**:`allowUnixSockets` 選項可以授予對強大系統服務的存取權限。例如,允許 `/var/run/docker.sock` 實際上透過 Docker API 授予完整主機系統存取權限,繞過沙箱隔離。僅允許嚴格必要的 Unix sockets,並了解每個的安全含義。

3141</Warning>

3142 

3143### `SandboxNetworkConfig`

3144 

3145沙箱模式的網路特定配置。

3146 

3147```python theme={null}

3148class SandboxNetworkConfig(TypedDict, total=False):

3149 allowedDomains: list[str]

3150 deniedDomains: list[str]

3151 allowManagedDomainsOnly: bool

3152 allowUnixSockets: list[str]

3153 allowAllUnixSockets: bool

3154 allowLocalBinding: bool

3155 allowMachLookup: list[str]

3156 httpProxyPort: int

3157 socksProxyPort: int

3158```

3159 

3160| 屬性 | 類型 | 預設 | 描述 |

3161| :------------------------ | :---------- | :------ | :------------------------------------------------------------ |

3162| `allowedDomains` | `list[str]` | `[]` | 沙箱化程序可以存取的網域名稱 |

3163| `deniedDomains` | `list[str]` | `[]` | 沙箱化程序無法存取的網域名稱。優先於 `allowedDomains` |

3164| `allowManagedDomainsOnly` | `bool` | `False` | 僅限受管設定:在受管設定中設定時,忽略來自非受管設定來源的 `allowedDomains`。透過 SDK 選項設定時無效 |

3165| `allowUnixSockets` | `list[str]` | `[]` | 程序可以存取的 Unix socket 路徑(例如 Docker socket) |

3166| `allowAllUnixSockets` | `bool` | `False` | 允許存取所有 Unix sockets |

3167| `allowLocalBinding` | `bool` | `False` | 允許程序繫結到本地連接埠(例如開發伺服器) |

3168| `allowMachLookup` | `list[str]` | `[]` | 僅限 macOS:允許的 XPC/Mach 服務名稱。支援尾部萬用字元 |

3169| `httpProxyPort` | `int` | `None` | 網路請求的 HTTP proxy 連接埠 |

3170| `socksProxyPort` | `int` | `None` | 網路請求的 SOCKS proxy 連接埠 |

3171 

3172<Note>

3173 內建沙箱 proxy 根據請求的主機名稱強制執行網路允許清單,不會終止或檢查 TLS 流量,因此[網域前置](https://en.wikipedia.org/wiki/Domain_fronting)等技術可能會繞過它。有關詳細資訊,請參閱[沙箱安全限制](/zh-TW/sandboxing#security-limitations),以及[安全部署](/zh-TW/agent-sdk/secure-deployment#traffic-forwarding)以配置 TLS 終止 proxy。

3174</Note>

3175 

3176### `SandboxIgnoreViolations`

3177 

3178用於忽略特定沙箱違規的配置。

3179 

3180```python theme={null}

3181class SandboxIgnoreViolations(TypedDict, total=False):

3182 file: list[str]

3183 network: list[str]

3184```

3185 

3186| 屬性 | 類型 | 預設 | 描述 |

3187| :-------- | :---------- | :--- | :----------- |

3188| `file` | `list[str]` | `[]` | 要忽略違規的檔案路徑模式 |

3189| `network` | `list[str]` | `[]` | 要忽略違規的網路模式 |

3190 

3191### 未沙箱化命令的權限回退

3192 

3193當 `allowUnsandboxedCommands` 啟用時,模型可以透過在 tool 輸入中設定 `dangerouslyDisableSandbox: True` 來請求在沙箱外執行命令。這些請求回退到現有權限系統,意味著您的 `can_use_tool` 處理程序將被呼叫,允許您實現自訂授權邏輯。

3194 

3195<Note>

3196 **`excludedCommands` vs `allowUnsandboxedCommands`:**

3197 

3198 * `excludedCommands`:始終自動繞過沙箱的靜態命令清單(例如 `["docker"]`)。模型無法控制此。

3199 * `allowUnsandboxedCommands`:讓模型在執行時透過在 tool 輸入中設定 `dangerouslyDisableSandbox: True` 來決定是否請求未沙箱化執行。

3200</Note>

3201 

3202```python theme={null}

3203from claude_agent_sdk import (

3204 query,

3205 ClaudeAgentOptions,

3206 HookMatcher,

3207 PermissionResultAllow,

3208 PermissionResultDeny,

3209 ToolPermissionContext,

3210)

3211 

3212 

3213async def can_use_tool(

3214 tool: str, input: dict, context: ToolPermissionContext

3215) -> PermissionResultAllow | PermissionResultDeny:

3216 # Check if the model is requesting to bypass the sandbox

3217 if tool == "Bash" and input.get("dangerouslyDisableSandbox"):

3218 # The model is requesting to run this command outside the sandbox

3219 print(f"Unsandboxed command requested: {input.get('command')}")

3220 

3221 if is_command_authorized(input.get("command")):

3222 return PermissionResultAllow()

3223 return PermissionResultDeny(

3224 message="Command not authorized for unsandboxed execution"

3225 )

3226 return PermissionResultAllow()

3227 

3228 

3229# Required: dummy hook keeps the stream open for can_use_tool

3230async def dummy_hook(input_data, tool_use_id, context):

3231 return {"continue_": True}

3232 

3233 

3234async def prompt_stream():

3235 yield {

3236 "type": "user",

3237 "message": {"role": "user", "content": "Deploy my application"},

3238 }

3239 

3240 

3241async def main():

3242 async for message in query(

3243 prompt=prompt_stream(),

3244 options=ClaudeAgentOptions(

3245 sandbox={

3246 "enabled": True,

3247 "allowUnsandboxedCommands": True, # Model can request unsandboxed execution

3248 },

3249 permission_mode="default",

3250 can_use_tool=can_use_tool,

3251 hooks={"PreToolUse": [HookMatcher(matcher=None, hooks=[dummy_hook])]},

3252 ),

3253 ):

3254 print(message)

3255```

3256 

3257此模式使您能夠:

3258 

3259* **審計模型請求**:記錄模型何時請求未沙箱化執行

3260* **實現允許清單**:僅允許特定命令在沙箱外執行

3261* **新增批准工作流程**:需要明確授權以進行特權操作

3262 

3263<Warning>

3264 使用 `dangerouslyDisableSandbox: True` 執行的命令具有完整系統存取權限。確保您的 `can_use_tool` 處理程序仔細驗證這些請求。

3265 

3266 如果 `permission_mode` 設定為 `bypassPermissions` 且 `allow_unsandboxed_commands` 啟用,模型可以自主執行沙箱外的命令,無需任何批准提示。此組合實際上允許模型無聲地逃脫沙箱隔離。

3267</Warning>

3268 

3269## 另見

3270 

3271* [SDK 概述](/zh-TW/agent-sdk/overview) - 一般 SDK 概念

3272* [TypeScript SDK 參考](/zh-TW/agent-sdk/typescript) - TypeScript SDK 文件

3273* [CLI 參考](/zh-TW/cli-reference) - 命令列介面

3274* [常見工作流程](/zh-TW/common-workflows) - 逐步指南

agent-sdk/quickstart.md +333 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 快速開始

6 

7> 使用 Python 或 TypeScript Agent SDK 開始構建能夠自主工作的 AI 代理

8 

9使用 Agent SDK 構建一個 AI 代理,它可以讀取您的代碼、發現錯誤並自動修復它們,無需手動干預。

10 

11**您將執行的操作:**

12 

131. 使用 Agent SDK 設置項目

142. 創建一個包含一些有缺陷代碼的文件

153. 運行一個代理,自動查找並修復錯誤

16 

17## 先決條件

18 

19* **Node.js 18+** 或 **Python 3.10+**

20* 一個 **Anthropic 帳戶**([在此註冊](https://platform.claude.com/))

21 

22## 設置

23 

24<Steps>

25 <Step title="創建項目文件夾">

26 為此快速開始創建一個新目錄:

27 

28 ```bash theme={null}

29 mkdir my-agent && cd my-agent

30 ```

31 

32 對於您自己的項目,您可以從任何文件夾運行 SDK;默認情況下,它將有權訪問該目錄及其子目錄中的文件。

33 </Step>

34 

35 <Step title="安裝 SDK">

36 為您的語言安裝 Agent SDK 包:

37 

38 <Tabs>

39 <Tab title="TypeScript">

40 ```bash theme={null}

41 npm install @anthropic-ai/claude-agent-sdk

42 ```

43 </Tab>

44 

45 <Tab title="Python (uv)">

46 [uv Python 包管理器](https://docs.astral.sh/uv/)是一個快速的 Python 包管理器,可自動處理虛擬環境:

47 

48 ```bash theme={null}

49 uv init && uv add claude-agent-sdk

50 ```

51 </Tab>

52 

53 <Tab title="Python (pip)">

54 首先創建虛擬環境,然後安裝:

55 

56 ```bash theme={null}

57 python3 -m venv .venv && source .venv/bin/activate

58 pip3 install claude-agent-sdk

59 ```

60 </Tab>

61 </Tabs>

62 

63 <Note>

64 TypeScript SDK 為您的平台捆綁了一個本機 Claude Code 二進制文件作為可選依賴項,因此您無需單獨安裝 Claude Code。

65 </Note>

66 </Step>

67 

68 <Step title="設置您的 API 密鑰">

69 從 [Claude 控制台](https://platform.claude.com/)獲取 API 密鑰,然後在您的項目目錄中創建一個 `.env` 文件:

70 

71 ```bash theme={null}

72 ANTHROPIC_API_KEY=your-api-key

73 ```

74 

75 SDK 還支持通過第三方 API 提供商進行身份驗證:

76 

77 * **Amazon Bedrock**:設置 `CLAUDE_CODE_USE_BEDROCK=1` 環境變量並配置 AWS 憑證

78 * **Google Vertex AI**:設置 `CLAUDE_CODE_USE_VERTEX=1` 環境變量並配置 Google Cloud 憑證

79 * **Microsoft Azure**:設置 `CLAUDE_CODE_USE_FOUNDRY=1` 環境變量並配置 Azure 憑證

80 

81 有關詳細信息,請參閱 [Bedrock](/zh-TW/amazon-bedrock)、[Vertex AI](/zh-TW/google-vertex-ai) 或 [Azure AI Foundry](/zh-TW/microsoft-foundry) 的設置指南。

82 

83 <Note>

84 除非事先獲得批准,否則 Anthropic 不允許第三方開發人員提供 claude.ai 登錄或對其產品的速率限制,包括基於 Claude Agent SDK 構建的代理。請改用本文檔中描述的 API 密鑰身份驗證方法。

85 </Note>

86 </Step>

87</Steps>

88 

89## 創建有缺陷的文件

90 

91此快速開始將引導您構建一個可以查找並修復代碼中的錯誤的代理。首先,您需要一個包含一些故意錯誤的文件供代理修復。在 `my-agent` 目錄中創建 `utils.py` 並粘貼以下代碼:

92 

93```python theme={null}

94def calculate_average(numbers):

95 total = 0

96 for num in numbers:

97 total += num

98 return total / len(numbers)

99 

100 

101def get_user_name(user):

102 return user["name"].upper()

103```

104 

105此代碼有兩個錯誤:

106 

1071. `calculate_average([])` 因除以零而崩潰

1082. `get_user_name(None)` 因 TypeError 而崩潰

109 

110## 構建查找並修復錯誤的代理

111 

112如果您使用 Python SDK,請創建 `agent.py`,或者如果使用 TypeScript,請創建 `agent.ts`:

113 

114<CodeGroup>

115 ```python Python theme={null}

116 import asyncio

117 from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage

118 

119 

120 async def main():

121 # Agentic loop: streams messages as Claude works

122 async for message in query(

123 prompt="Review utils.py for bugs that would cause crashes. Fix any issues you find.",

124 options=ClaudeAgentOptions(

125 allowed_tools=["Read", "Edit", "Glob"], # Tools Claude can use

126 permission_mode="acceptEdits", # Auto-approve file edits

127 ),

128 ):

129 # Print human-readable output

130 if isinstance(message, AssistantMessage):

131 for block in message.content:

132 if hasattr(block, "text"):

133 print(block.text) # Claude's reasoning

134 elif hasattr(block, "name"):

135 print(f"Tool: {block.name}") # Tool being called

136 elif isinstance(message, ResultMessage):

137 print(f"Done: {message.subtype}") # Final result

138 

139 

140 asyncio.run(main())

141 ```

142 

143 ```typescript TypeScript theme={null}

144 import { query } from "@anthropic-ai/claude-agent-sdk";

145 

146 // Agentic loop: streams messages as Claude works

147 for await (const message of query({

148 prompt: "Review utils.py for bugs that would cause crashes. Fix any issues you find.",

149 options: {

150 allowedTools: ["Read", "Edit", "Glob"], // Tools Claude can use

151 permissionMode: "acceptEdits" // Auto-approve file edits

152 }

153 })) {

154 // Print human-readable output

155 if (message.type === "assistant" && message.message?.content) {

156 for (const block of message.message.content) {

157 if ("text" in block) {

158 console.log(block.text); // Claude's reasoning

159 } else if ("name" in block) {

160 console.log(`Tool: ${block.name}`); // Tool being called

161 }

162 }

163 } else if (message.type === "result") {

164 console.log(`Done: ${message.subtype}`); // Final result

165 }

166 }

167 ```

168</CodeGroup>

169 

170此代碼有三個主要部分:

171 

1721. **`query`**:創建 agentic 循環的主要入口點。它返回一個異步迭代器,因此您使用 `async for` 在 Claude 工作時流式傳輸消息。請參閱 [Python](/zh-TW/agent-sdk/python#query) 或 [TypeScript](/zh-TW/agent-sdk/typescript#query) SDK 參考中的完整 API。

173 

1742. **`prompt`**:您希望 Claude 執行的操作。Claude 根據任務確定要使用哪些工具。

175 

1763. **`options`**:代理的配置。此示例使用 `allowedTools` 預先批准 `Read`、`Edit` 和 `Glob`,並使用 `permissionMode: "acceptEdits"` 自動批准文件更改。其他選項包括 `systemPrompt`、`mcpServers` 等。請參閱 [Python](/zh-TW/agent-sdk/python#claude-agent-options) 或 [TypeScript](/zh-TW/agent-sdk/typescript#options) 的所有選項。

177 

178`async for` 循環在 Claude 思考、調用工具、觀察結果並決定下一步操作時持續運行。每次迭代都會產生一條消息:Claude 的推理、工具調用、工具結果或最終結果。SDK 處理編排(工具執行、上下文管理、重試),因此您只需使用流。當 Claude 完成任務或遇到錯誤時,循環結束。

179 

180循環內的消息處理會過濾人類可讀的輸出。如果沒有過濾,您會看到原始消息對象,包括系統初始化和內部狀態,這對於調試很有用,但通常很冗長。

181 

182<Note>

183 此示例使用流式傳輸來實時顯示進度。如果您不需要實時輸出(例如,對於後台作業或 CI 管道),您可以一次收集所有消息。有關詳細信息,請參閱[流式傳輸與單輪模式](/zh-TW/agent-sdk/streaming-vs-single-mode)。

184</Note>

185 

186### 運行您的代理

187 

188您的代理已準備好。使用以下命令運行它:

189 

190<Tabs>

191 <Tab title="Python">

192 ```bash theme={null}

193 python3 agent.py

194 ```

195 </Tab>

196 

197 <Tab title="TypeScript">

198 ```bash theme={null}

199 npx tsx agent.ts

200 ```

201 </Tab>

202</Tabs>

203 

204運行後,檢查 `utils.py`。您將看到處理空列表和空用戶的防禦性代碼。您的代理自主地:

205 

2061. **讀取** `utils.py` 以理解代碼

2072. **分析**邏輯並識別會導致崩潰的邊界情況

2083. **編輯**文件以添加適當的錯誤處理

209 

210這就是 Agent SDK 的不同之處:Claude 直接執行工具,而不是要求您實現它們。

211 

212<Note>

213 如果您看到"API key not found",請確保您已在 `.env` 文件或 shell 環境中設置 `ANTHROPIC_API_KEY` 環境變量。有關更多幫助,請參閱[完整故障排除指南](/zh-TW/troubleshooting)。

214</Note>

215 

216### 嘗試其他提示

217 

218現在您的代理已設置好,嘗試一些不同的提示:

219 

220* `"Add docstrings to all functions in utils.py"`

221* `"Add type hints to all functions in utils.py"`

222* `"Create a README.md documenting the functions in utils.py"`

223 

224### 自定義您的代理

225 

226您可以通過更改選項來修改代理的行為。以下是一些示例:

227 

228**添加網絡搜索功能:**

229 

230<CodeGroup>

231 ```python Python theme={null}

232 options = ClaudeAgentOptions(

233 allowed_tools=["Read", "Edit", "Glob", "WebSearch"], permission_mode="acceptEdits"

234 )

235 ```

236 

237 ```typescript TypeScript hidelines={1,-1} theme={null}

238 const _ = {

239 options: {

240 allowedTools: ["Read", "Edit", "Glob", "WebSearch"],

241 permissionMode: "acceptEdits"

242 }

243 };

244 ```

245</CodeGroup>

246 

247**給 Claude 一個自定義系統提示:**

248 

249<CodeGroup>

250 ```python Python theme={null}

251 options = ClaudeAgentOptions(

252 allowed_tools=["Read", "Edit", "Glob"],

253 permission_mode="acceptEdits",

254 system_prompt="You are a senior Python developer. Always follow PEP 8 style guidelines.",

255 )

256 ```

257 

258 ```typescript TypeScript hidelines={1,-1} theme={null}

259 const _ = {

260 options: {

261 allowedTools: ["Read", "Edit", "Glob"],

262 permissionMode: "acceptEdits",

263 systemPrompt: "You are a senior Python developer. Always follow PEP 8 style guidelines."

264 }

265 };

266 ```

267</CodeGroup>

268 

269**在終端中運行命令:**

270 

271<CodeGroup>

272 ```python Python theme={null}

273 options = ClaudeAgentOptions(

274 allowed_tools=["Read", "Edit", "Glob", "Bash"], permission_mode="acceptEdits"

275 )

276 ```

277 

278 ```typescript TypeScript hidelines={1,-1} theme={null}

279 const _ = {

280 options: {

281 allowedTools: ["Read", "Edit", "Glob", "Bash"],

282 permissionMode: "acceptEdits"

283 }

284 };

285 ```

286</CodeGroup>

287 

288啟用 `Bash` 後,嘗試:`"Write unit tests for utils.py, run them, and fix any failures"`

289 

290## 關鍵概念

291 

292**工具**控制您的代理可以執行的操作:

293 

294| 工具 | 代理可以執行的操作 |

295| ---------------------------------- | --------- |

296| `Read`、`Glob`、`Grep` | 只讀分析 |

297| `Read`、`Edit`、`Glob` | 分析和修改代碼 |

298| `Read`、`Edit`、`Bash`、`Glob`、`Grep` | 完全自動化 |

299 

300**權限模式**控制您想要多少人工監督:

301 

302| 模式 | 行為 | 用例 |

303| -------------------- | -------------------------- | -------------- |

304| `acceptEdits` | 自動批准文件編輯和常見文件系統命令,詢問其他操作 | 受信任的開發工作流 |

305| `dontAsk` | 拒絕不在 `allowedTools` 中的任何內容 | 鎖定的無頭代理 |

306| `auto`(僅 TypeScript) | 模型分類器批准或拒絕每個工具調用 | 具有安全防護的自主代理 |

307| `bypassPermissions` | 運行每個工具而不提示 | 沙箱 CI、完全受信任的環境 |

308| `default` | 需要 `canUseTool` 回調來處理批准 | 自定義批准流程 |

309 

310上面的示例使用 `acceptEdits` 模式,它自動批准文件操作,以便代理可以無需交互提示地運行。如果您想提示用戶批准,請使用 `default` 模式並提供一個 [`canUseTool` 回調](/zh-TW/agent-sdk/user-input)來收集用戶輸入。如需更多控制,請參閱[權限](/zh-TW/agent-sdk/permissions)。

311 

312## 故障排除

313 

314### API 錯誤 `thinking.type.enabled` 不支持此模型

315 

316Claude Opus 4.7 將 `thinking.type.enabled` 替換為 `thinking.type.adaptive`。當您選擇 `claude-opus-4-7` 時,較舊的 Agent SDK 版本會失敗並出現以下 API 錯誤:

317 

318```text theme={null}

319API Error: 400 {"type":"invalid_request_error","message":"\"thinking.type.enabled\" is not supported for this model. Use \"thinking.type.adaptive\" and \"output_config.effort\" to control thinking behavior."}

320```

321 

322升級到 Agent SDK v0.2.111 或更高版本以使用 Opus 4.7。

323 

324## 後續步驟

325 

326現在您已創建了第一個代理,了解如何擴展其功能並根據您的用例進行定制:

327 

328* **[權限](/zh-TW/agent-sdk/permissions)**:控制您的代理可以執行的操作以及何時需要批准

329* **[Hooks](/zh-TW/agent-sdk/hooks)**:在工具調用之前或之後運行自定義代碼

330* **[會話](/zh-TW/agent-sdk/sessions)**:構建維護上下文的多輪代理

331* **[MCP 服務器](/zh-TW/agent-sdk/mcp)**:連接到數據庫、瀏覽器、API 和其他外部系統

332* **[託管](/zh-TW/agent-sdk/hosting)**:將代理部署到 Docker、雲和 CI/CD

333* **[示例代理](https://github.com/anthropics/claude-agent-sdk-demos)**:查看完整示例:電子郵件助手、研究代理等

agent-sdk/slash-commands.md +444 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# SDK 中的 Slash Commands

6 

7> 了解如何透過 SDK 使用 slash commands 來控制 Claude Code 會話

8 

9Slash commands 提供了一種方式來控制 Claude Code 會話,使用以 `/` 開頭的特殊命令。這些命令可以透過 SDK 發送,以執行諸如壓縮上下文、列出上下文使用情況或調用自訂命令等操作。只有在不需要互動式終端的情況下才能工作的命令才能透過 SDK 分派;`system/init` 訊息列出了您會話中可用的命令。

10 

11## 發現可用的 Slash Commands

12 

13Claude Agent SDK 在系統初始化訊息中提供有關可用 slash commands 的資訊。在您的會話開始時存取此資訊:

14 

15<CodeGroup>

16 ```typescript TypeScript theme={null}

17 import { query } from "@anthropic-ai/claude-agent-sdk";

18 

19 for await (const message of query({

20 prompt: "Hello Claude",

21 options: { maxTurns: 1 }

22 })) {

23 if (message.type === "system" && message.subtype === "init") {

24 console.log("Available slash commands:", message.slash_commands);

25 // Example output: ["/compact", "/context", "/usage"]

26 }

27 }

28 ```

29 

30 ```python Python theme={null}

31 import asyncio

32 from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage

33 

34 

35 async def main():

36 async for message in query(prompt="Hello Claude", options=ClaudeAgentOptions(max_turns=1)):

37 if isinstance(message, SystemMessage) and message.subtype == "init":

38 print("Available slash commands:", message.data["slash_commands"])

39 # Example output: ["/compact", "/context", "/usage"]

40 

41 

42 asyncio.run(main())

43 ```

44</CodeGroup>

45 

46## 發送 Slash Commands

47 

48透過在您的提示字串中包含 slash commands 來發送它們,就像常規文字一樣:

49 

50<CodeGroup>

51 ```typescript TypeScript theme={null}

52 import { query } from "@anthropic-ai/claude-agent-sdk";

53 

54 // Send a slash command

55 for await (const message of query({

56 prompt: "/compact",

57 options: { maxTurns: 1 }

58 })) {

59 if (message.type === "result") {

60 console.log("Command executed:", message.result);

61 }

62 }

63 ```

64 

65 ```python Python theme={null}

66 import asyncio

67 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

68 

69 

70 async def main():

71 # Send a slash command

72 async for message in query(prompt="/compact", options=ClaudeAgentOptions(max_turns=1)):

73 if isinstance(message, ResultMessage):

74 print("Command executed:", message.result)

75 

76 

77 asyncio.run(main())

78 ```

79</CodeGroup>

80 

81## 常見的 Slash Commands

82 

83### `/compact` - 壓縮對話歷史

84 

85`/compact` 命令透過總結較舊的訊息同時保留重要上下文來減少您的對話歷史的大小:

86 

87<CodeGroup>

88 ```typescript TypeScript theme={null}

89 import { query } from "@anthropic-ai/claude-agent-sdk";

90 

91 for await (const message of query({

92 prompt: "/compact",

93 options: { maxTurns: 1 }

94 })) {

95 if (message.type === "system" && message.subtype === "compact_boundary") {

96 console.log("Compaction completed");

97 console.log("Pre-compaction tokens:", message.compact_metadata.pre_tokens);

98 console.log("Trigger:", message.compact_metadata.trigger);

99 }

100 }

101 ```

102 

103 ```python Python theme={null}

104 import asyncio

105 from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage

106 

107 

108 async def main():

109 async for message in query(prompt="/compact", options=ClaudeAgentOptions(max_turns=1)):

110 if isinstance(message, SystemMessage) and message.subtype == "compact_boundary":

111 print("Compaction completed")

112 print("Pre-compaction tokens:", message.data["compact_metadata"]["pre_tokens"])

113 print("Trigger:", message.data["compact_metadata"]["trigger"])

114 

115 

116 asyncio.run(main())

117 ```

118</CodeGroup>

119 

120### 清除對話

121 

122互動式 `/clear` 命令在 SDK 中不可用。每個 `query()` 呼叫已經開始一個新的對話,所以要清除上下文,請結束目前的 `query()` 並開始一個新的。先前的對話保存在磁碟上,可以透過將其會話 ID 傳遞給 [`resume` 選項](/zh-TW/agent-sdk/sessions#resume-by-id) 來返回。

123 

124## 建立自訂 Slash Commands

125 

126除了使用內建 slash commands 外,您還可以建立自己的自訂命令,這些命令可透過 SDK 使用。自訂命令定義為特定目錄中的 markdown 檔案,類似於子代理的配置方式。

127 

128<Note>

129 `.claude/commands/` 目錄是舊版格式。建議的格式是 `.claude/skills/<name>/SKILL.md`,它支援相同的 slash command 調用(`/name`)加上 Claude 的自主調用。請參閱 [Skills](/zh-TW/agent-sdk/skills) 以了解目前的格式。CLI 繼續支援兩種格式,下面的範例對於 `.claude/commands/` 仍然準確。

130</Note>

131 

132### 檔案位置

133 

134自訂 slash commands 根據其範圍儲存在指定的目錄中:

135 

136* **專案命令**:`.claude/commands/` - 僅在目前專案中可用(舊版;建議使用 `.claude/skills/`)

137* **個人命令**:`~/.claude/commands/` - 在您的所有專案中可用(舊版;建議使用 `~/.claude/skills/`)

138 

139### 檔案格式

140 

141每個自訂命令都是一個 markdown 檔案,其中:

142 

143* 檔案名稱(不含 `.md` 副檔名)成為命令名稱

144* 檔案內容定義命令的功能

145* 可選的 YAML frontmatter 提供配置

146 

147#### 基本範例

148 

149建立 `.claude/commands/refactor.md`:

150 

151```markdown theme={null}

152Refactor the selected code to improve readability and maintainability.

153Focus on clean code principles and best practices.

154```

155 

156這會建立 `/refactor` 命令,您可以透過 SDK 使用。

157 

158#### 使用 Frontmatter

159 

160建立 `.claude/commands/security-check.md`:

161 

162```markdown theme={null}

163---

164allowed-tools: Read, Grep, Glob

165description: Run security vulnerability scan

166model: claude-opus-4-7

167---

168 

169Analyze the codebase for security vulnerabilities including:

170- SQL injection risks

171- XSS vulnerabilities

172- Exposed credentials

173- Insecure configurations

174```

175 

176### 在 SDK 中使用自訂命令

177 

178一旦在檔案系統中定義,自訂命令就會自動透過 SDK 可用:

179 

180<CodeGroup>

181 ```typescript TypeScript theme={null}

182 import { query } from "@anthropic-ai/claude-agent-sdk";

183 

184 // Use a custom command

185 for await (const message of query({

186 prompt: "/refactor src/auth/login.ts",

187 options: { maxTurns: 3 }

188 })) {

189 if (message.type === "assistant") {

190 console.log("Refactoring suggestions:", message.message);

191 }

192 }

193 

194 // Custom commands appear in the slash_commands list

195 for await (const message of query({

196 prompt: "Hello",

197 options: { maxTurns: 1 }

198 })) {

199 if (message.type === "system" && message.subtype === "init") {

200 // Will include both built-in and custom commands

201 console.log("Available commands:", message.slash_commands);

202 // Example: ["/compact", "/context", "/usage", "/refactor", "/security-check"]

203 }

204 }

205 ```

206 

207 ```python Python theme={null}

208 import asyncio

209 from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, SystemMessage

210 

211 

212 async def main():

213 # Use a custom command

214 async for message in query(

215 prompt="/refactor src/auth/login.py", options=ClaudeAgentOptions(max_turns=3)

216 ):

217 if isinstance(message, AssistantMessage):

218 for block in message.content:

219 if hasattr(block, "text"):

220 print("Refactoring suggestions:", block.text)

221 

222 # Custom commands appear in the slash_commands list

223 async for message in query(prompt="Hello", options=ClaudeAgentOptions(max_turns=1)):

224 if isinstance(message, SystemMessage) and message.subtype == "init":

225 # Will include both built-in and custom commands

226 print("Available commands:", message.data["slash_commands"])

227 # Example: ["/compact", "/context", "/usage", "/refactor", "/security-check"]

228 

229 

230 asyncio.run(main())

231 ```

232</CodeGroup>

233 

234### 進階功能

235 

236#### 引數和佔位符

237 

238自訂命令支援使用佔位符的動態引數:

239 

240建立 `.claude/commands/fix-issue.md`:

241 

242```markdown theme={null}

243---

244argument-hint: [issue-number] [priority]

245description: Fix a GitHub issue

246---

247 

248Fix issue #$1 with priority $2.

249Check the issue description and implement the necessary changes.

250```

251 

252在 SDK 中使用:

253 

254<CodeGroup>

255 ```typescript TypeScript theme={null}

256 import { query } from "@anthropic-ai/claude-agent-sdk";

257 

258 // Pass arguments to custom command

259 for await (const message of query({

260 prompt: "/fix-issue 123 high",

261 options: { maxTurns: 5 }

262 })) {

263 // Command will process with $1="123" and $2="high"

264 if (message.type === "result") {

265 console.log("Issue fixed:", message.result);

266 }

267 }

268 ```

269 

270 ```python Python theme={null}

271 import asyncio

272 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

273 

274 

275 async def main():

276 # Pass arguments to custom command

277 async for message in query(prompt="/fix-issue 123 high", options=ClaudeAgentOptions(max_turns=5)):

278 # Command will process with $1="123" and $2="high"

279 if isinstance(message, ResultMessage):

280 print("Issue fixed:", message.result)

281 

282 

283 asyncio.run(main())

284 ```

285</CodeGroup>

286 

287#### Bash 命令執行

288 

289自訂命令可以執行 bash 命令並包含其輸出:

290 

291建立 `.claude/commands/git-commit.md`:

292 

293```markdown theme={null}

294---

295allowed-tools: Bash(git add *), Bash(git status *), Bash(git commit *)

296description: Create a git commit

297---

298 

299## Context

300 

301- Current status: !`git status`

302- Current diff: !`git diff HEAD`

303 

304## Task

305 

306Create a git commit with appropriate message based on the changes.

307```

308 

309#### 檔案參考

310 

311使用 `@` 前綴包含檔案內容:

312 

313建立 `.claude/commands/review-config.md`:

314 

315```markdown theme={null}

316---

317description: Review configuration files

318---

319 

320Review the following configuration files for issues:

321- Package config: @package.json

322- TypeScript config: @tsconfig.json

323- Environment config: @.env

324 

325Check for security issues, outdated dependencies, and misconfigurations.

326```

327 

328### 使用命名空間組織

329 

330在子目錄中組織命令以獲得更好的結構:

331 

332```bash theme={null}

333.claude/commands/

334├── frontend/

335│ ├── component.md # Creates /component (project:frontend)

336│ └── style-check.md # Creates /style-check (project:frontend)

337├── backend/

338│ ├── api-test.md # Creates /api-test (project:backend)

339│ └── db-migrate.md # Creates /db-migrate (project:backend)

340└── review.md # Creates /review (project)

341```

342 

343子目錄出現在命令描述中,但不會影響命令名稱本身。

344 

345### 實用範例

346 

347#### 程式碼審查命令

348 

349建立 `.claude/commands/code-review.md`:

350 

351```markdown theme={null}

352---

353allowed-tools: Read, Grep, Glob, Bash(git diff *)

354description: Comprehensive code review

355---

356 

357## Changed Files

358!`git diff --name-only HEAD~1`

359 

360## Detailed Changes

361!`git diff HEAD~1`

362 

363## Review Checklist

364 

365Review the above changes for:

3661. Code quality and readability

3672. Security vulnerabilities

3683. Performance implications

3694. Test coverage

3705. Documentation completeness

371 

372Provide specific, actionable feedback organized by priority.

373```

374 

375#### 測試執行器命令

376 

377建立 `.claude/commands/test.md`:

378 

379```markdown theme={null}

380---

381allowed-tools: Bash, Read, Edit

382argument-hint: [test-pattern]

383description: Run tests with optional pattern

384---

385 

386Run tests matching pattern: $ARGUMENTS

387 

3881. Detect the test framework (Jest, pytest, etc.)

3892. Run tests with the provided pattern

3903. If tests fail, analyze and fix them

3914. Re-run to verify fixes

392```

393 

394透過 SDK 使用這些命令:

395 

396<CodeGroup>

397 ```typescript TypeScript theme={null}

398 import { query } from "@anthropic-ai/claude-agent-sdk";

399 

400 // Run code review

401 for await (const message of query({

402 prompt: "/code-review",

403 options: { maxTurns: 3 }

404 })) {

405 // Process review feedback

406 }

407 

408 // Run specific tests

409 for await (const message of query({

410 prompt: "/test auth",

411 options: { maxTurns: 5 }

412 })) {

413 // Handle test results

414 }

415 ```

416 

417 ```python Python theme={null}

418 import asyncio

419 from claude_agent_sdk import query, ClaudeAgentOptions

420 

421 

422 async def main():

423 # Run code review

424 async for message in query(prompt="/code-review", options=ClaudeAgentOptions(max_turns=3)):

425 # Process review feedback

426 pass

427 

428 # Run specific tests

429 async for message in query(prompt="/test auth", options=ClaudeAgentOptions(max_turns=5)):

430 # Handle test results

431 pass

432 

433 

434 asyncio.run(main())

435 ```

436</CodeGroup>

437 

438## 另請參閱

439 

440* [Slash Commands](/zh-TW/skills) - 完整的 slash command 文件

441* [SDK 中的子代理](/zh-TW/agent-sdk/subagents) - 子代理的類似檔案系統配置

442* [TypeScript SDK 參考](/zh-TW/agent-sdk/typescript) - 完整的 API 文件

443* [SDK 概述](/zh-TW/agent-sdk/overview) - 一般 SDK 概念

444* [CLI 參考](/zh-TW/cli-reference) - 命令列介面

agent-sdk/typescript.md +2975 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Agent SDK 參考 - TypeScript

6 

7> TypeScript Agent SDK 的完整 API 參考,包括所有函數、類型和介面。

8 

9<script src="/components/typescript-sdk-type-links.js" defer />

10 

11<Note>

12 **試試新的 V2 介面(預覽版):** 現在提供了一個簡化的介面,具有 `send()` 和 `stream()` 模式,使多輪對話更容易。[了解更多關於 TypeScript V2 預覽版](/zh-TW/agent-sdk/typescript-v2-preview)

13</Note>

14 

15## 安裝

16 

17```bash theme={null}

18npm install @anthropic-ai/claude-agent-sdk

19```

20 

21<Note>

22 SDK 為您的平台捆綁了一個原生 Claude Code 二進制文件作為可選依賴項,例如 `@anthropic-ai/claude-agent-sdk-darwin-arm64`。您不需要單獨安裝 Claude Code。如果您的包管理器跳過可選依賴項,SDK 會拋出 `Native CLI binary for <platform> not found`;改為將 [`pathToClaudeCodeExecutable`](#options) 設置為單獨安裝的 `claude` 二進制文件。

23</Note>

24 

25## 函數

26 

27### `query()`

28 

29與 Claude Code 互動的主要函數。創建一個異步生成器,在消息到達時流式傳輸消息。

30 

31```typescript theme={null}

32function query({

33 prompt,

34 options

35}: {

36 prompt: string | AsyncIterable<SDKUserMessage>;

37 options?: Options;

38}): Query;

39```

40 

41#### 參數

42 

43| 參數 | 類型 | 描述 |

44| :-------- | :---------------------------------------------------------------- | :------------------------ |

45| `prompt` | `string \| AsyncIterable<`[`SDKUserMessage`](#sdkuser-message)`>` | 輸入提示,可以是字符串或異步可迭代對象用於流式模式 |

46| `options` | [`Options`](#options) | 可選配置對象(見下面的 Options 類型) |

47 

48#### 返回值

49 

50返回一個 [`Query`](#query-object) 對象,它擴展了 `AsyncGenerator<`[`SDKMessage`](#sdk-message)`, void>` 並具有額外的方法。

51 

52### `startup()`

53 

54通過生成 CLI 子進程並在提示可用之前完成初始化握手來預熱 CLI 子進程。返回的 [`WarmQuery`](#warm-query) 句柄稍後接受提示並將其寫入已準備好的進程,因此第一個 `query()` 調用解析時無需支付子進程生成和初始化成本。

55 

56```typescript theme={null}

57function startup(params?: {

58 options?: Options;

59 initializeTimeoutMs?: number;

60}): Promise<WarmQuery>;

61```

62 

63#### 參數

64 

65| 參數 | 類型 | 描述 |

66| :-------------------- | :-------------------- | :---------------------------------------------------------- |

67| `options` | [`Options`](#options) | 可選配置對象。與 `query()` 的 `options` 參數相同 |

68| `initializeTimeoutMs` | `number` | 等待子進程初始化的最大時間(毫秒)。默認為 `60000`。如果初始化未在時間內完成,promise 將以超時錯誤拒絕 |

69 

70#### 返回值

71 

72返回一個 `Promise<`[`WarmQuery`](#warm-query)`>`,在子進程生成並完成其初始化握手後解析。

73 

74#### 示例

75 

76早期調用 `startup()`,例如在應用程序啟動時,然後在提示準備好後在返回的句柄上調用 `.query()`。這將子進程生成和初始化移出關鍵路徑。

77 

78```typescript theme={null}

79import { startup } from "@anthropic-ai/claude-agent-sdk";

80 

81// 提前支付啟動成本

82const warm = await startup({ options: { maxTurns: 3 } });

83 

84// 稍後,當提示準備好時,這是立即的

85for await (const message of warm.query("What files are here?")) {

86 console.log(message);

87}

88```

89 

90### `tool()`

91 

92為與 SDK MCP 服務器一起使用創建類型安全的 MCP 工具定義。

93 

94```typescript theme={null}

95function tool<Schema extends AnyZodRawShape>(

96 name: string,

97 description: string,

98 inputSchema: Schema,

99 handler: (args: InferShape<Schema>, extra: unknown) => Promise<CallToolResult>,

100 extras?: { annotations?: ToolAnnotations }

101): SdkMcpToolDefinition<Schema>;

102```

103 

104#### 參數

105 

106| 參數 | 類型 | 描述 |

107| :------------ | :------------------------------------------------------------------ | :--------------------------------- |

108| `name` | `string` | 工具的名稱 |

109| `description` | `string` | 工具功能的描述 |

110| `inputSchema` | `Schema extends AnyZodRawShape` | 定義工具輸入參數的 Zod 架構(支持 Zod 3 和 Zod 4) |

111| `handler` | `(args, extra) => Promise<`[`CallToolResult`](#call-tool-result)`>` | 執行工具邏輯的異步函數 |

112| `extras` | `{ annotations?: `[`ToolAnnotations`](#tool-annotations)` }` | 可選的 MCP 工具註釋,為客戶端提供行為提示 |

113 

114#### `ToolAnnotations`

115 

116從 `@modelcontextprotocol/sdk/types.js` 重新導出。所有字段都是可選提示;客戶端不應依賴它們進行安全決策。

117 

118| 字段 | 類型 | 默認值 | 描述 |

119| :---------------- | :-------- | :---------- | :------------------------------------------------------------- |

120| `title` | `string` | `undefined` | 工具的人類可讀標題 |

121| `readOnlyHint` | `boolean` | `false` | 如果為 `true`,工具不會修改其環境 |

122| `destructiveHint` | `boolean` | `true` | 如果為 `true`,工具可能執行破壞性更新(僅在 `readOnlyHint` 為 `false` 時有意義) |

123| `idempotentHint` | `boolean` | `false` | 如果為 `true`,使用相同參數的重複調用沒有額外效果(僅在 `readOnlyHint` 為 `false` 時有意義) |

124| `openWorldHint` | `boolean` | `true` | 如果為 `true`,工具與外部實體交互(例如,網絡搜索)。如果為 `false`,工具的域是封閉的(例如,記憶工具) |

125 

126```typescript theme={null}

127import { tool } from "@anthropic-ai/claude-agent-sdk";

128import { z } from "zod";

129 

130const searchTool = tool(

131 "search",

132 "Search the web",

133 { query: z.string() },

134 async ({ query }) => {

135 return { content: [{ type: "text", text: `Results for: ${query}` }] };

136 },

137 { annotations: { readOnlyHint: true, openWorldHint: true } }

138);

139```

140 

141### `createSdkMcpServer()`

142 

143創建在與應用程序相同的進程中運行的 MCP 服務器實例。

144 

145```typescript theme={null}

146function createSdkMcpServer(options: {

147 name: string;

148 version?: string;

149 tools?: Array<SdkMcpToolDefinition<any>>;

150}): McpSdkServerConfigWithInstance;

151```

152 

153#### 參數

154 

155| 參數 | 類型 | 描述 |

156| :---------------- | :---------------------------- | :----------------------------- |

157| `options.name` | `string` | MCP 服務器的名稱 |

158| `options.version` | `string` | 可選版本字符串 |

159| `options.tools` | `Array<SdkMcpToolDefinition>` | 使用 [`tool()`](#tool) 創建的工具定義數組 |

160 

161### `listSessions()`

162 

163發現並列出具有輕量級元數據的過去會話。按項目目錄篩選或列出所有項目中的會話。

164 

165```typescript theme={null}

166function listSessions(options?: ListSessionsOptions): Promise<SDKSessionInfo[]>;

167```

168 

169#### 參數

170 

171| 參數 | 類型 | 默認值 | 描述 |

172| :------------------------- | :-------- | :---------- | :---------------------------------------- |

173| `options.dir` | `string` | `undefined` | 列出會話的目錄。省略時,返回所有項目中的會話 |

174| `options.limit` | `number` | `undefined` | 返回的最大會話數 |

175| `options.includeWorktrees` | `boolean` | `true` | 當 `dir` 在 git 存儲庫內時,包括來自所有 worktree 路徑的會話 |

176 

177#### 返回類型:`SDKSessionInfo`

178 

179| 屬性 | 類型 | 描述 |

180| :------------- | :-------------------- | :------------------------------------------ |

181| `sessionId` | `string` | 唯一會話標識符(UUID) |

182| `summary` | `string` | 顯示標題:自定義標題、自動生成的摘要或第一個提示 |

183| `lastModified` | `number` | 上次修改時間(自紀元以來的毫秒數) |

184| `fileSize` | `number \| undefined` | 會話文件大小(字節)。僅針對本地 JSONL 存儲填充 |

185| `customTitle` | `string \| undefined` | 用戶設置的會話標題(通過 `/rename`) |

186| `firstPrompt` | `string \| undefined` | 會話中的第一個有意義的用戶提示 |

187| `gitBranch` | `string \| undefined` | 會話結束時的 Git 分支 |

188| `cwd` | `string \| undefined` | 會話的工作目錄 |

189| `tag` | `string \| undefined` | 用戶設置的會話標籤(見 [`tagSession()`](#tag-session)) |

190| `createdAt` | `number \| undefined` | 創建時間(自紀元以來的毫秒數),來自第一個條目的時間戳 |

191 

192#### 示例

193 

194打印項目的 10 個最近會話。結果按 `lastModified` 降序排序,因此第一項是最新的。省略 `dir` 以搜索所有項目。

195 

196```typescript theme={null}

197import { listSessions } from "@anthropic-ai/claude-agent-sdk";

198 

199const sessions = await listSessions({ dir: "/path/to/project", limit: 10 });

200 

201for (const session of sessions) {

202 console.log(`${session.summary} (${session.sessionId})`);

203}

204```

205 

206### `getSessionMessages()`

207 

208從過去的會話記錄中讀取用戶和助手消息。

209 

210```typescript theme={null}

211function getSessionMessages(

212 sessionId: string,

213 options?: GetSessionMessagesOptions

214): Promise<SessionMessage[]>;

215```

216 

217#### 參數

218 

219| 參數 | 類型 | 默認值 | 描述 |

220| :--------------- | :------- | :---------- | :------------------------------ |

221| `sessionId` | `string` | 必需 | 要讀取的會話 UUID(見 `listSessions()`) |

222| `options.dir` | `string` | `undefined` | 查找會話的項目目錄。省略時,搜索所有項目 |

223| `options.limit` | `number` | `undefined` | 返回的最大消息數 |

224| `options.offset` | `number` | `undefined` | 從開始跳過的消息數 |

225 

226#### 返回類型:`SessionMessage`

227 

228| 屬性 | 類型 | 描述 |

229| :------------------- | :---------------------- | :------------ |

230| `type` | `"user" \| "assistant"` | 消息角色 |

231| `uuid` | `string` | 唯一消息標識符 |

232| `session_id` | `string` | 此消息所屬的會話 |

233| `message` | `unknown` | 來自記錄的原始消息有效負載 |

234| `parent_tool_use_id` | `null` | 保留 |

235 

236#### 示例

237 

238```typescript theme={null}

239import { listSessions, getSessionMessages } from "@anthropic-ai/claude-agent-sdk";

240 

241const [latest] = await listSessions({ dir: "/path/to/project", limit: 1 });

242 

243if (latest) {

244 const messages = await getSessionMessages(latest.sessionId, {

245 dir: "/path/to/project",

246 limit: 20

247 });

248 

249 for (const msg of messages) {

250 console.log(`[${msg.type}] ${msg.uuid}`);

251 }

252}

253```

254 

255### `getSessionInfo()`

256 

257按 ID 讀取單個會話的元數據,無需掃描完整項目目錄。

258 

259```typescript theme={null}

260function getSessionInfo(

261 sessionId: string,

262 options?: GetSessionInfoOptions

263): Promise<SDKSessionInfo | undefined>;

264```

265 

266#### 參數

267 

268| 參數 | 類型 | 默認值 | 描述 |

269| :------------ | :------- | :---------- | :------------------ |

270| `sessionId` | `string` | 必需 | 要查找的會話 UUID |

271| `options.dir` | `string` | `undefined` | 項目目錄路徑。省略時,搜索所有項目目錄 |

272 

273返回 [`SDKSessionInfo`](#return-type-sdk-session-info),如果找不到會話則返回 `undefined`。

274 

275### `renameSession()`

276 

277通過附加自定義標題條目來重命名會話。重複調用是安全的;最新的標題獲勝。

278 

279```typescript theme={null}

280function renameSession(

281 sessionId: string,

282 title: string,

283 options?: SessionMutationOptions

284): Promise<void>;

285```

286 

287#### 參數

288 

289| 參數 | 類型 | 默認值 | 描述 |

290| :------------ | :------- | :---------- | :------------------ |

291| `sessionId` | `string` | 必需 | 要重命名的會話 UUID |

292| `title` | `string` | 必需 | 新標題。修剪空格後必須非空 |

293| `options.dir` | `string` | `undefined` | 項目目錄路徑。省略時,搜索所有項目目錄 |

294 

295### `tagSession()`

296 

297標記會話。傳遞 `null` 以清除標籤。重複調用是安全的;最新的標籤獲勝。

298 

299```typescript theme={null}

300function tagSession(

301 sessionId: string,

302 tag: string | null,

303 options?: SessionMutationOptions

304): Promise<void>;

305```

306 

307#### 參數

308 

309| 參數 | 類型 | 默認值 | 描述 |

310| :------------ | :--------------- | :---------- | :------------------ |

311| `sessionId` | `string` | 必需 | 要標記的會話 UUID |

312| `tag` | `string \| null` | 必需 | 標籤字符串,或 `null` 以清除 |

313| `options.dir` | `string` | `undefined` | 項目目錄路徑。省略時,搜索所有項目目錄 |

314 

315## 類型

316 

317### `Options`

318 

319`query()` 函數的配置對象。

320 

321| 屬性 | 類型 | 默認值 | 描述 |

322| :-------------------------------- | :------------------------------------------------------------------------------------------------------- | :---------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

323| `abortController` | `AbortController` | `new AbortController()` | 用於取消操作的控制器 |

324| `additionalDirectories` | `string[]` | `[]` | Claude 可以訪問的其他目錄 |

325| `agent` | `string` | `undefined` | 主線程的代理名稱。代理必須在 `agents` 選項或設置中定義 |

326| `agents` | `Record<string, [`AgentDefinition`](#agent-definition)>` | `undefined` | 以編程方式定義子代理 |

327| `allowDangerouslySkipPermissions` | `boolean` | `false` | 啟用繞過權限。使用 `permissionMode: 'bypassPermissions'` 時需要 |

328| `allowedTools` | `string[]` | `[]` | 無需提示即可自動批准的工具。這不會將 Claude 限制為僅這些工具;未列出的工具會進入 `permissionMode` 和 `canUseTool`。使用 `disallowedTools` 來阻止工具。見 [權限](/zh-TW/agent-sdk/permissions#allow-and-deny-rules) |

329| `betas` | [`SdkBeta`](#sdk-beta)`[]` | `[]` | 啟用測試功能 |

330| `canUseTool` | [`CanUseTool`](#can-use-tool) | `undefined` | 工具使用的自定義權限函數 |

331| `continue` | `boolean` | `false` | 繼續最近的對話 |

332| `cwd` | `string` | `process.cwd()` | 當前工作目錄 |

333| `debug` | `boolean` | `false` | 為 Claude Code 進程啟用調試模式 |

334| `debugFile` | `string` | `undefined` | 將調試日誌寫入特定文件路徑。隱式啟用調試模式 |

335| `disallowedTools` | `string[]` | `[]` | 始終拒絕的工具。拒絕規則首先檢查並覆蓋 `allowedTools` 和 `permissionMode`(包括 `bypassPermissions`) |

336| `effort` | `'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max'` | `'high'` | 控制 Claude 在其響應中投入多少努力。與自適應思考一起工作以指導思考深度 |

337| `enableFileCheckpointing` | `boolean` | `false` | 啟用文件更改跟蹤以進行回滾。見 [文件檢查點](/zh-TW/agent-sdk/file-checkpointing) |

338| `env` | `Record<string, string \| undefined>` | `process.env` | 環境變量。見 [環境變量](/zh-TW/env-vars) 了解底層 CLI 讀取的變量。設置 `CLAUDE_AGENT_SDK_CLIENT_APP` 以在 User-Agent 標頭中標識您的應用程序 |

339| `executable` | `'bun' \| 'deno' \| 'node'` | 自動檢測 | 要使用的 JavaScript 運行時 |

340| `executableArgs` | `string[]` | `[]` | 傳遞給可執行文件的參數 |

341| `extraArgs` | `Record<string, string \| null>` | `{}` | 其他參數 |

342| `fallbackModel` | `string` | `undefined` | 主模型失敗時使用的模型 |

343| `forkSession` | `boolean` | `false` | 使用 `resume` 恢復時,分叉到新會話 ID 而不是繼續原始會話 |

344| `hooks` | `Partial<Record<`[`HookEvent`](#hook-event)`, `[`HookCallbackMatcher`](#hook-callback-matcher)`[]>>` | `{}` | 事件的 Hook 回調 |

345| `includePartialMessages` | `boolean` | `false` | 包括部分消息事件 |

346| `maxBudgetUsd` | `number` | `undefined` | 當客戶端成本估計達到此 USD 值時停止查詢。與 `total_cost_usd` 的相同估計進行比較;見 [跟蹤成本和使用情況](/zh-TW/agent-sdk/cost-tracking) 了解準確性注意事項 |

347| `maxThinkingTokens` | `number` | `undefined` | *已棄用:* 改用 `thinking`。思考過程的最大令牌數 |

348| `maxTurns` | `number` | `undefined` | 最大代理轉數(工具使用往返) |

349| `mcpServers` | `Record<string, [`McpServerConfig`](#mcp-server-config)>` | `{}` | MCP 服務器配置 |

350| `model` | `string` | CLI 默認值 | 要使用的 Claude 模型 |

351| `outputFormat` | `{ type: 'json_schema', schema: JSONSchema }` | `undefined` | 為代理結果定義輸出格式。見 [結構化輸出](/zh-TW/agent-sdk/structured-outputs) 了解詳情 |

352| `pathToClaudeCodeExecutable` | `string` | 從捆綁的原生二進制文件自動解析 | Claude Code 可執行文件的路徑。僅在安裝期間跳過可選依賴項或您的平台不在支持的集合中時需要 |

353| `permissionMode` | [`PermissionMode`](#permission-mode) | `'default'` | 會話的權限模式 |

354| `permissionPromptToolName` | `string` | `undefined` | 權限提示的 MCP 工具名稱 |

355| `persistSession` | `boolean` | `true` | 當為 `false` 時,禁用會話持久化到磁盤。會話之後無法恢復 |

356| `plugins` | [`SdkPluginConfig`](#sdk-plugin-config)`[]` | `[]` | 從本地路徑加載自定義插件。見 [Plugins](/zh-TW/agent-sdk/plugins) 了解詳情 |

357| `promptSuggestions` | `boolean` | `false` | 啟用提示建議。在每個轉數後發出 `prompt_suggestion` 消息,帶有預測的下一個用戶提示 |

358| `resume` | `string` | `undefined` | 要恢復的會話 ID |

359| `resumeSessionAt` | `string` | `undefined` | 在特定消息 UUID 處恢復會話 |

360| `sandbox` | [`SandboxSettings`](#sandbox-settings) | `undefined` | 以編程方式配置沙箱行為。見 [沙箱設置](#sandbox-settings) 了解詳情 |

361| `sessionId` | `string` | 自動生成 | 使用特定 UUID 作為會話,而不是自動生成一個 |

362| `sessionStore` | [`SessionStore`](/zh-TW/agent-sdk/session-storage#the-session-store-interface) | `undefined` | 將會話記錄鏡像到外部後端,以便任何主機都可以恢復它們。見 [將會話持久化到外部存儲](/zh-TW/agent-sdk/session-storage) |

363| `settingSources` | [`SettingSource`](#setting-source)`[]` | CLI 默認值(所有源) | 控制加載哪些文件系統設置。傳遞 `[]` 以禁用用戶、項目和本地設置。無論如何都會加載託管策略設置。見 [使用 Claude Code 功能](/zh-TW/agent-sdk/claude-code-features#what-settingsources-does-not-control) |

364| `spawnClaudeCodeProcess` | `(options: SpawnOptions) => SpawnedProcess` | `undefined` | 用於生成 Claude Code 進程的自定義函數。用於在 VM、容器或遠程環境中運行 Claude Code |

365| `stderr` | `(data: string) => void` | `undefined` | stderr 輸出的回調 |

366| `strictMcpConfig` | `boolean` | `false` | 強制執行嚴格的 MCP 驗證 |

367| `systemPrompt` | `string \| { type: 'preset'; preset: 'claude_code'; append?: string; excludeDynamicSections?: boolean }` | `undefined`(最小提示) | 系統提示配置。傳遞字符串以獲得自定義提示,或 `{ type: 'preset', preset: 'claude_code' }` 以使用 Claude Code 的系統提示。使用預設對象形式時,添加 `append` 以使用其他指令擴展它,並設置 `excludeDynamicSections: true` 以將每個會話上下文移到第一個用戶消息中以獲得 [跨機器更好的提示緩存重用](/zh-TW/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines) |

368| `thinking` | [`ThinkingConfig`](#thinking-config) | 支持的模型為 `{ type: 'adaptive' }` | 控制 Claude 的思考/推理行為。見 [`ThinkingConfig`](#thinking-config) 了解選項 |

369| `toolConfig` | [`ToolConfig`](#tool-config) | `undefined` | 內置工具行為的配置。見 [`ToolConfig`](#tool-config) 了解詳情 |

370| `tools` | `string[] \| { type: 'preset'; preset: 'claude_code' }` | `undefined` | 工具配置。傳遞工具名稱數組或使用預設以獲得 Claude Code 的默認工具 |

371 

372### `Query` 對象

373 

374由 `query()` 函數返回的介面。

375 

376```typescript theme={null}

377interface Query extends AsyncGenerator<SDKMessage, void> {

378 interrupt(): Promise<void>;

379 rewindFiles(

380 userMessageId: string,

381 options?: { dryRun?: boolean }

382 ): Promise<RewindFilesResult>;

383 setPermissionMode(mode: PermissionMode): Promise<void>;

384 setModel(model?: string): Promise<void>;

385 setMaxThinkingTokens(maxThinkingTokens: number | null): Promise<void>;

386 initializationResult(): Promise<SDKControlInitializeResponse>;

387 supportedCommands(): Promise<SlashCommand[]>;

388 supportedModels(): Promise<ModelInfo[]>;

389 supportedAgents(): Promise<AgentInfo[]>;

390 mcpServerStatus(): Promise<McpServerStatus[]>;

391 accountInfo(): Promise<AccountInfo>;

392 reconnectMcpServer(serverName: string): Promise<void>;

393 toggleMcpServer(serverName: string, enabled: boolean): Promise<void>;

394 setMcpServers(servers: Record<string, McpServerConfig>): Promise<McpSetServersResult>;

395 streamInput(stream: AsyncIterable<SDKUserMessage>): Promise<void>;

396 stopTask(taskId: string): Promise<void>;

397 close(): void;

398}

399```

400 

401#### 方法

402 

403| 方法 | 描述 |

404| :------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------- |

405| `interrupt()` | 中斷查詢(僅在流式輸入模式下可用) |

406| `rewindFiles(userMessageId, options?)` | 將文件恢復到指定用戶消息時的狀態。傳遞 `{ dryRun: true }` 以預覽更改。需要 `enableFileCheckpointing: true`。見 [文件檢查點](/zh-TW/agent-sdk/file-checkpointing) |

407| `setPermissionMode()` | 更改權限模式(僅在流式輸入模式下可用) |

408| `setModel()` | 更改模型(僅在流式輸入模式下可用) |

409| `setMaxThinkingTokens()` | *已棄用:* 改用 `thinking` 選項。更改最大思考令牌 |

410| `initializationResult()` | 返回完整的初始化結果,包括支持的命令、模型、帳戶信息和輸出樣式配置 |

411| `supportedCommands()` | 返回可用的 slash commands |

412| `supportedModels()` | 返回具有顯示信息的可用模型 |

413| `supportedAgents()` | 返回可通過 Agent 工具調用的可用子代理,作為 [`AgentInfo`](#agent-info)`[]` |

414| `mcpServerStatus()` | 返回連接的 MCP 服務器的狀態 |

415| `accountInfo()` | 返回帳戶信息 |

416| `reconnectMcpServer(serverName)` | 按名稱重新連接 MCP 服務器 |

417| `toggleMcpServer(serverName, enabled)` | 按名稱啟用或禁用 MCP 服務器 |

418| `setMcpServers(servers)` | 動態替換此會話的 MCP 服務器集。返回有關添加、刪除的服務器和任何錯誤的信息 |

419| `streamInput(stream)` | 將輸入消息流式傳輸到查詢以進行多輪對話 |

420| `stopTask(taskId)` | 按 ID 停止運行的後台任務 |

421| `close()` | 關閉查詢並終止底層進程。強制結束查詢並清理所有資源 |

422 

423### `WarmQuery`

424 

425由 [`startup()`](#startup) 返回的句柄。子進程已生成並初始化,因此在此句柄上調用 `query()` 會直接將提示寫入準備好的進程,無需啟動延遲。

426 

427```typescript theme={null}

428interface WarmQuery extends AsyncDisposable {

429 query(prompt: string | AsyncIterable<SDKUserMessage>): Query;

430 close(): void;

431}

432```

433 

434#### 方法

435 

436| 方法 | 描述 |

437| :-------------- | :------------------------------------------------------------ |

438| `query(prompt)` | 向預熱的子進程發送提示並返回 [`Query`](#query-object)。每個 `WarmQuery` 只能調用一次 |

439| `close()` | 關閉子進程而不發送提示。使用此方法丟棄不再需要的預熱查詢 |

440 

441`WarmQuery` 實現 `AsyncDisposable`,因此可以與 `await using` 一起使用以進行自動清理。

442 

443### `SDKControlInitializeResponse`

444 

445`initializationResult()` 的返回類型。包含會話初始化數據。

446 

447```typescript theme={null}

448type SDKControlInitializeResponse = {

449 commands: SlashCommand[];

450 agents: AgentInfo[];

451 output_style: string;

452 available_output_styles: string[];

453 models: ModelInfo[];

454 account: AccountInfo;

455 fast_mode_state?: "off" | "cooldown" | "on";

456};

457```

458 

459### `AgentDefinition`

460 

461以編程方式定義的子代理的配置。

462 

463```typescript theme={null}

464type AgentDefinition = {

465 description: string;

466 tools?: string[];

467 disallowedTools?: string[];

468 prompt: string;

469 model?: string;

470 mcpServers?: AgentMcpServerSpec[];

471 skills?: string[];

472 initialPrompt?: string;

473 maxTurns?: number;

474 background?: boolean;

475 memory?: "user" | "project" | "local";

476 effort?: "low" | "medium" | "high" | "xhigh" | "max" | number;

477 permissionMode?: PermissionMode;

478 criticalSystemReminder_EXPERIMENTAL?: string;

479};

480```

481 

482| 字段 | 必需 | 描述 |

483| :------------------------------------ | :- | :---------------------------------------------------------------------------------------- |

484| `description` | 是 | 何時使用此代理的自然語言描述 |

485| `tools` | 否 | 允許的工具名稱數組。如果省略,從父代理繼承所有工具 |

486| `disallowedTools` | 否 | 要為此代理明確禁止的工具名稱數組 |

487| `prompt` | 是 | 代理的系統提示 |

488| `model` | 否 | 此代理的模型覆蓋。接受別名如 `'sonnet'`、`'opus'`、`'haiku'`、`'inherit'` 或完整模型 ID。如果省略或 `'inherit'`,使用主模型 |

489| `mcpServers` | 否 | 此代理可用的 MCP 服務器規範 |

490| `skills` | 否 | 要預加載到代理上下文中的技能名稱數組 |

491| `initialPrompt` | 否 | 當此代理作為主線程代理運行時,自動提交為第一個用戶轉數 |

492| `maxTurns` | 否 | 最大代理轉數(API 往返),然後停止 |

493| `background` | 否 | 當調用時,將此代理作為非阻塞後台任務運行 |

494| `memory` | 否 | 此代理的內存源:`'user'`、`'project'` 或 `'local'` |

495| `effort` | 否 | 此代理的推理努力級別。接受命名級別或整數 |

496| `permissionMode` | 否 | 此代理內工具執行的權限模式。見 [`PermissionMode`](#permission-mode) |

497| `criticalSystemReminder_EXPERIMENTAL` | 否 | 實驗性:添加到系統提示的關鍵提醒 |

498 

499### `AgentMcpServerSpec`

500 

501指定子代理可用的 MCP 服務器。可以是服務器名稱(字符串,引用父代理 `mcpServers` 配置中的服務器)或內聯服務器配置記錄,將服務器名稱映射到配置。

502 

503```typescript theme={null}

504type AgentMcpServerSpec = string | Record<string, McpServerConfigForProcessTransport>;

505```

506 

507其中 `McpServerConfigForProcessTransport` 是 `McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig`。

508 

509### `SettingSource`

510 

511控制 SDK 從哪些基於文件系統的配置源加載設置。

512 

513```typescript theme={null}

514type SettingSource = "user" | "project" | "local";

515```

516 

517| 值 | 描述 | 位置 |

518| :---------- | :----------------- | :---------------------------- |

519| `'user'` | 全局用戶設置 | `~/.claude/settings.json` |

520| `'project'` | 共享項目設置(版本控制) | `.claude/settings.json` |

521| `'local'` | 本地項目設置(gitignored) | `.claude/settings.local.json` |

522 

523#### 默認行為

524 

525當 `settingSources` 被省略或 `undefined` 時,`query()` 加載與 Claude Code CLI 相同的文件系統設置:用戶、項目和本地。託管策略設置在所有情況下都會加載。見 [settingSources 不控制什麼](/zh-TW/agent-sdk/claude-code-features#what-settingsources-does-not-control) 了解無論此選項如何都會讀取的輸入,以及如何禁用它們。

526 

527#### 為什麼使用 settingSources

528 

529**禁用文件系統設置:**

530 

531```typescript theme={null}

532// 不從磁盤加載用戶、項目或本地設置

533const result = query({

534 prompt: "Analyze this code",

535 options: { settingSources: [] }

536});

537```

538 

539**明確加載所有文件系統設置:**

540 

541```typescript theme={null}

542const result = query({

543 prompt: "Analyze this code",

544 options: {

545 settingSources: ["user", "project", "local"] // 加載所有設置

546 }

547});

548```

549 

550**僅加載特定設置源:**

551 

552```typescript theme={null}

553// 僅加載項目設置,忽略用戶和本地

554const result = query({

555 prompt: "Run CI checks",

556 options: {

557 settingSources: ["project"] // 僅 .claude/settings.json

558 }

559});

560```

561 

562**測試和 CI 環境:**

563 

564```typescript theme={null}

565// 通過排除本地設置確保 CI 中的一致行為

566const result = query({

567 prompt: "Run tests",

568 options: {

569 settingSources: ["project"], // 僅團隊共享設置

570 permissionMode: "bypassPermissions"

571 }

572});

573```

574 

575**僅 SDK 應用程序:**

576 

577```typescript theme={null}

578// 以編程方式定義所有內容。

579// 傳遞 [] 以選擇退出文件系統設置源。

580const result = query({

581 prompt: "Review this PR",

582 options: {

583 settingSources: [],

584 agents: {

585 /* ... */

586 },

587 mcpServers: {

588 /* ... */

589 },

590 allowedTools: ["Read", "Grep", "Glob"]

591 }

592});

593```

594 

595**加載 CLAUDE.md 項目指令:**

596 

597```typescript theme={null}

598// 加載項目設置以包括 CLAUDE.md 文件

599const result = query({

600 prompt: "Add a new feature following project conventions",

601 options: {

602 systemPrompt: {

603 type: "preset",

604 preset: "claude_code" // 使用 Claude Code 的系統提示

605 },

606 settingSources: ["project"], // 從項目目錄加載 CLAUDE.md

607 allowedTools: ["Read", "Write", "Edit"]

608 }

609});

610```

611 

612#### 設置優先級

613 

614加載多個源時,設置按此優先級(最高到最低)合併:

615 

6161. 本地設置(`.claude/settings.local.json`)

6172. 項目設置(`.claude/settings.json`)

6183. 用戶設置(`~/.claude/settings.json`)

619 

620編程選項(如 `agents` 和 `allowedTools`)覆蓋用戶、項目和本地文件系統設置。託管策略設置優先於編程選項。

621 

622### `PermissionMode`

623 

624```typescript theme={null}

625type PermissionMode =

626 | "default" // 標準權限行為

627 | "acceptEdits" // 自動接受文件編輯

628 | "bypassPermissions" // 繞過所有權限檢查

629 | "plan" // 規劃模式 - 無執行

630 | "dontAsk" // 不提示權限,如果未預批准則拒絕

631 | "auto"; // 使用模型分類器批准或拒絕每個工具調用

632```

633 

634### `CanUseTool`

635 

636用於控制工具使用的自定義權限函數類型。

637 

638```typescript theme={null}

639type CanUseTool = (

640 toolName: string,

641 input: Record<string, unknown>,

642 options: {

643 signal: AbortSignal;

644 suggestions?: PermissionUpdate[];

645 blockedPath?: string;

646 decisionReason?: string;

647 toolUseID: string;

648 agentID?: string;

649 }

650) => Promise<PermissionResult>;

651```

652 

653| 選項 | 類型 | 描述 |

654| :--------------- | :------------------------------------------- | :--------------------- |

655| `signal` | `AbortSignal` | 如果應中止操作則發出信號 |

656| `suggestions` | [`PermissionUpdate`](#permission-update)`[]` | 建議的權限更新,以便用戶不會再次被提示此工具 |

657| `blockedPath` | `string` | 觸發權限請求的文件路徑(如果適用) |

658| `decisionReason` | `string` | 解釋為什麼觸發此權限請求 |

659| `toolUseID` | `string` | 此特定工具調用在助手消息中的唯一標識符 |

660| `agentID` | `string` | 如果在子代理中運行,子代理的 ID |

661 

662### `PermissionResult`

663 

664權限檢查的結果。

665 

666```typescript theme={null}

667type PermissionResult =

668 | {

669 behavior: "allow";

670 updatedInput?: Record<string, unknown>;

671 updatedPermissions?: PermissionUpdate[];

672 toolUseID?: string;

673 }

674 | {

675 behavior: "deny";

676 message: string;

677 interrupt?: boolean;

678 toolUseID?: string;

679 };

680```

681 

682### `ToolConfig`

683 

684內置工具行為的配置。

685 

686```typescript theme={null}

687type ToolConfig = {

688 askUserQuestion?: {

689 previewFormat?: "markdown" | "html";

690 };

691};

692```

693 

694| 字段 | 類型 | 描述 |

695| :------------------------------ | :--------------------- | :---------------------------------------------------------------------------------------------------------------- |

696| `askUserQuestion.previewFormat` | `'markdown' \| 'html'` | 選擇進入 [`AskUserQuestion`](/zh-TW/agent-sdk/user-input#question-format) 選項上的 `preview` 字段並設置其內容格式。未設置時,Claude 不發出預覽 |

697 

698### `McpServerConfig`

699 

700MCP 服務器的配置。

701 

702```typescript theme={null}

703type McpServerConfig =

704 | McpStdioServerConfig

705 | McpSSEServerConfig

706 | McpHttpServerConfig

707 | McpSdkServerConfigWithInstance;

708```

709 

710#### `McpStdioServerConfig`

711 

712```typescript theme={null}

713type McpStdioServerConfig = {

714 type?: "stdio";

715 command: string;

716 args?: string[];

717 env?: Record<string, string>;

718};

719```

720 

721#### `McpSSEServerConfig`

722 

723```typescript theme={null}

724type McpSSEServerConfig = {

725 type: "sse";

726 url: string;

727 headers?: Record<string, string>;

728};

729```

730 

731#### `McpHttpServerConfig`

732 

733```typescript theme={null}

734type McpHttpServerConfig = {

735 type: "http";

736 url: string;

737 headers?: Record<string, string>;

738};

739```

740 

741#### `McpSdkServerConfigWithInstance`

742 

743```typescript theme={null}

744type McpSdkServerConfigWithInstance = {

745 type: "sdk";

746 name: string;

747 instance: McpServer;

748};

749```

750 

751#### `McpClaudeAIProxyServerConfig`

752 

753```typescript theme={null}

754type McpClaudeAIProxyServerConfig = {

755 type: "claudeai-proxy";

756 url: string;

757 id: string;

758};

759```

760 

761### `SdkPluginConfig`

762 

763SDK 中加載插件的配置。

764 

765```typescript theme={null}

766type SdkPluginConfig = {

767 type: "local";

768 path: string;

769};

770```

771 

772| 字段 | 類型 | 描述 |

773| :----- | :-------- | :----------------------- |

774| `type` | `'local'` | 必須是 `'local'`(目前僅支持本地插件) |

775| `path` | `string` | 插件目錄的絕對或相對路徑 |

776 

777**示例:**

778 

779```typescript theme={null}

780plugins: [

781 { type: "local", path: "./my-plugin" },

782 { type: "local", path: "/absolute/path/to/plugin" }

783];

784```

785 

786有關創建和使用插件的完整信息,見 [Plugins](/zh-TW/agent-sdk/plugins)。

787 

788## 消息類型

789 

790### `SDKMessage`

791 

792查詢返回的所有可能消息的聯合類型。

793 

794```typescript theme={null}

795type SDKMessage =

796 | SDKAssistantMessage

797 | SDKUserMessage

798 | SDKUserMessageReplay

799 | SDKResultMessage

800 | SDKSystemMessage

801 | SDKPartialAssistantMessage

802 | SDKCompactBoundaryMessage

803 | SDKStatusMessage

804 | SDKLocalCommandOutputMessage

805 | SDKHookStartedMessage

806 | SDKHookProgressMessage

807 | SDKHookResponseMessage

808 | SDKPluginInstallMessage

809 | SDKToolProgressMessage

810 | SDKAuthStatusMessage

811 | SDKTaskNotificationMessage

812 | SDKTaskStartedMessage

813 | SDKTaskProgressMessage

814 | SDKTaskUpdatedMessage

815 | SDKFilesPersistedEvent

816 | SDKToolUseSummaryMessage

817 | SDKRateLimitEvent

818 | SDKPromptSuggestionMessage;

819```

820 

821### `SDKAssistantMessage`

822 

823助手響應消息。

824 

825```typescript theme={null}

826type SDKAssistantMessage = {

827 type: "assistant";

828 uuid: UUID;

829 session_id: string;

830 message: BetaMessage; // 來自 Anthropic SDK

831 parent_tool_use_id: string | null;

832 error?: SDKAssistantMessageError;

833};

834```

835 

836`message` 字段是來自 Anthropic SDK 的 [`BetaMessage`](https://platform.claude.com/docs/zh-TW/api/messages/create)。它包括 `id`、`content`、`model`、`stop_reason` 和 `usage` 等字段。

837 

838`SDKAssistantMessageError` 是以下之一:`'authentication_failed'`、`'oauth_org_not_allowed'`、`'billing_error'`、`'rate_limit'`、`'invalid_request'`、`'server_error'`、`'max_output_tokens'` 或 `'unknown'`。

839 

840### `SDKUserMessage`

841 

842用戶輸入消息。

843 

844```typescript theme={null}

845type SDKUserMessage = {

846 type: "user";

847 uuid?: UUID;

848 session_id: string;

849 message: MessageParam; // 來自 Anthropic SDK

850 parent_tool_use_id: string | null;

851 isSynthetic?: boolean;

852 shouldQuery?: boolean;

853 tool_use_result?: unknown;

854 origin?: SDKMessageOrigin;

855};

856```

857 

858將 `shouldQuery` 設置為 `false` 以將消息附加到記錄而不觸發助手轉數。消息被保留並合併到下一個觸發轉數的用戶消息中。使用此方法注入上下文,例如您在帶外運行的命令的輸出,而無需在其上花費模型調用。

859 

860### `SDKUserMessageReplay`

861 

862帶有必需 UUID 的重放用戶消息。

863 

864```typescript theme={null}

865type SDKUserMessageReplay = {

866 type: "user";

867 uuid: UUID;

868 session_id: string;

869 message: MessageParam;

870 parent_tool_use_id: string | null;

871 isSynthetic?: boolean;

872 tool_use_result?: unknown;

873 origin?: SDKMessageOrigin;

874 isReplay: true;

875};

876```

877 

878### `SDKResultMessage`

879 

880最終結果消息。

881 

882```typescript theme={null}

883type SDKResultMessage =

884 | {

885 type: "result";

886 subtype: "success";

887 uuid: UUID;

888 session_id: string;

889 duration_ms: number;

890 duration_api_ms: number;

891 is_error: boolean;

892 num_turns: number;

893 result: string;

894 stop_reason: string | null;

895 total_cost_usd: number;

896 usage: NonNullableUsage;

897 modelUsage: { [modelName: string]: ModelUsage };

898 permission_denials: SDKPermissionDenial[];

899 structured_output?: unknown;

900 deferred_tool_use?: { id: string; name: string; input: Record<string, unknown> };

901 origin?: SDKMessageOrigin;

902 }

903 | {

904 type: "result";

905 subtype:

906 | "error_max_turns"

907 | "error_during_execution"

908 | "error_max_budget_usd"

909 | "error_max_structured_output_retries";

910 uuid: UUID;

911 session_id: string;

912 duration_ms: number;

913 duration_api_ms: number;

914 is_error: boolean;

915 num_turns: number;

916 stop_reason: string | null;

917 total_cost_usd: number;

918 usage: NonNullableUsage;

919 modelUsage: { [modelName: string]: ModelUsage };

920 permission_denials: SDKPermissionDenial[];

921 errors: string[];

922 origin?: SDKMessageOrigin;

923 };

924```

925 

926`origin` 字段轉發觸發此結果的用戶消息的 [`SDKMessageOrigin`](#sdkmessageorigin)。當後台任務完成且 SDK 注入合成後續轉數時,生成的 `SDKResultMessage` 攜帶 `origin: { kind: "task-notification" }`。檢查此字段以區分回答您的提示的結果與為後台任務後續發出的結果,以便您可以路由或抑制後者。對於在任何用戶轉數之前發出的結果(例如啟動錯誤),該字段不存在。

927 

928當 `PreToolUse` hook 返回 `permissionDecision: "defer"` 時,結果具有 `stop_reason: "tool_deferred"` 和 `deferred_tool_use` 攜帶待處理工具的 `id`、`name` 和 `input`。讀取此字段以在您自己的 UI 中顯示請求,然後使用相同的 `session_id` 恢復以繼續。有關完整往返,請參閱[稍後延遲工具調用](/zh-TW/hooks#defer-a-tool-call-for-later)。

929 

930### `SDKSystemMessage`

931 

932系統初始化消息。

933 

934```typescript theme={null}

935type SDKSystemMessage = {

936 type: "system";

937 subtype: "init";

938 uuid: UUID;

939 session_id: string;

940 agents?: string[];

941 apiKeySource: ApiKeySource;

942 betas?: string[];

943 claude_code_version: string;

944 cwd: string;

945 tools: string[];

946 mcp_servers: {

947 name: string;

948 status: string;

949 }[];

950 model: string;

951 permissionMode: PermissionMode;

952 slash_commands: string[];

953 output_style: string;

954 skills: string[];

955 plugins: { name: string; path: string }[];

956};

957```

958 

959### `SDKPartialAssistantMessage`

960 

961流式部分消息(僅當 `includePartialMessages` 為 true 時)。

962 

963```typescript theme={null}

964type SDKPartialAssistantMessage = {

965 type: "stream_event";

966 event: BetaRawMessageStreamEvent; // 來自 Anthropic SDK

967 parent_tool_use_id: string | null;

968 uuid: UUID;

969 session_id: string;

970};

971```

972 

973### `SDKCompactBoundaryMessage`

974 

975指示對話壓縮邊界的消息。

976 

977```typescript theme={null}

978type SDKCompactBoundaryMessage = {

979 type: "system";

980 subtype: "compact_boundary";

981 uuid: UUID;

982 session_id: string;

983 compact_metadata: {

984 trigger: "manual" | "auto";

985 pre_tokens: number;

986 };

987};

988```

989 

990### `SDKPluginInstallMessage`

991 

992插件安裝進度事件。當設置 [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](/zh-TW/env-vars) 時發出,以便您的 Agent SDK 應用程序可以在第一個轉數之前跟蹤市場插件安裝。`started` 和 `completed` 狀態括起整體安裝。`installed` 和 `failed` 狀態報告單個市場並包括 `name`。

993 

994```typescript theme={null}

995type SDKPluginInstallMessage = {

996 type: "system";

997 subtype: "plugin_install";

998 status: "started" | "installed" | "failed" | "completed";

999 name?: string;

1000 error?: string;

1001 uuid: UUID;

1002 session_id: string;

1003};

1004```

1005 

1006### `SDKPermissionDenial`

1007 

1008有關被拒絕的工具使用的信息。

1009 

1010```typescript theme={null}

1011type SDKPermissionDenial = {

1012 tool_name: string;

1013 tool_use_id: string;

1014 tool_input: Record<string, unknown>;

1015};

1016```

1017 

1018### `SDKMessageOrigin`

1019 

1020用戶角色消息的來源。這在 [`SDKUserMessage`](#sdkusermessage) 上顯示為 `origin`,並轉發到相應的 [`SDKResultMessage`](#sdkresultmessage),以便您可以判斷給定轉數的觸發因素。

1021 

1022```typescript theme={null}

1023type SDKMessageOrigin =

1024 | { kind: "human" }

1025 | { kind: "channel"; server: string }

1026 | { kind: "peer"; from: string; name?: string }

1027 | { kind: "task-notification" }

1028 | { kind: "coordinator" };

1029```

1030 

1031| `kind` | 含義 |

1032| ------------------- | ------------------------------------------------------------------------------- |

1033| `human` | 來自最終用戶的直接輸入。在用戶消息上,缺少的 `origin` 也表示人類輸入。 |

1034| `channel` | 在[頻道](/zh-TW/channels)上到達的消息。`server` 是源 MCP 伺服器名稱。 |

1035| `peer` | 來自另一個代理會話的消息,通過 `SendMessage`。`from` 是發送者地址;`name` 是發送者的顯示名稱(如果可用)。 |

1036| `task-notification` | 後台任務完成後注入的合成轉數。請參閱 [`SDKTaskNotificationMessage`](#sdktasknotificationmessage)。 |

1037| `coordinator` | 來自[代理團隊](/zh-TW/agent-teams)中的團隊協調員的消息。 |

1038 

1039## Hook 類型

1040 

1041有關使用 hooks 的綜合指南,包括示例和常見模式,見 [Hooks 指南](/zh-TW/agent-sdk/hooks)。

1042 

1043### `HookEvent`

1044 

1045可用的 hook 事件。

1046 

1047```typescript theme={null}

1048type HookEvent =

1049 | "PreToolUse"

1050 | "PostToolUse"

1051 | "PostToolUseFailure"

1052 | "PostToolBatch"

1053 | "Notification"

1054 | "UserPromptSubmit"

1055 | "SessionStart"

1056 | "SessionEnd"

1057 | "Stop"

1058 | "SubagentStart"

1059 | "SubagentStop"

1060 | "PreCompact"

1061 | "PermissionRequest"

1062 | "Setup"

1063 | "TeammateIdle"

1064 | "TaskCompleted"

1065 | "ConfigChange"

1066 | "WorktreeCreate"

1067 | "WorktreeRemove";

1068```

1069 

1070### `HookCallback`

1071 

1072Hook 回調函數類型。

1073 

1074```typescript theme={null}

1075type HookCallback = (

1076 input: HookInput, // 所有 hook 輸入類型的聯合

1077 toolUseID: string | undefined,

1078 options: { signal: AbortSignal }

1079) => Promise<HookJSONOutput>;

1080```

1081 

1082### `HookCallbackMatcher`

1083 

1084帶有可選匹配器的 Hook 配置。

1085 

1086```typescript theme={null}

1087interface HookCallbackMatcher {

1088 matcher?: string;

1089 hooks: HookCallback[];

1090 timeout?: number; // 此匹配器中所有 hooks 的超時時間(秒)

1091}

1092```

1093 

1094### `HookInput`

1095 

1096所有 hook 輸入類型的聯合類型。

1097 

1098```typescript theme={null}

1099type HookInput =

1100 | PreToolUseHookInput

1101 | PostToolUseHookInput

1102 | PostToolUseFailureHookInput

1103 | PostToolBatchHookInput

1104 | NotificationHookInput

1105 | UserPromptSubmitHookInput

1106 | SessionStartHookInput

1107 | SessionEndHookInput

1108 | StopHookInput

1109 | SubagentStartHookInput

1110 | SubagentStopHookInput

1111 | PreCompactHookInput

1112 | PermissionRequestHookInput

1113 | SetupHookInput

1114 | TeammateIdleHookInput

1115 | TaskCompletedHookInput

1116 | ConfigChangeHookInput

1117 | WorktreeCreateHookInput

1118 | WorktreeRemoveHookInput;

1119```

1120 

1121### `BaseHookInput`

1122 

1123所有 hook 輸入類型擴展的基本介面。

1124 

1125```typescript theme={null}

1126type BaseHookInput = {

1127 session_id: string;

1128 transcript_path: string;

1129 cwd: string;

1130 permission_mode?: string;

1131 agent_id?: string;

1132 agent_type?: string;

1133};

1134```

1135 

1136#### `PreToolUseHookInput`

1137 

1138```typescript theme={null}

1139type PreToolUseHookInput = BaseHookInput & {

1140 hook_event_name: "PreToolUse";

1141 tool_name: string;

1142 tool_input: unknown;

1143 tool_use_id: string;

1144};

1145```

1146 

1147#### `PostToolUseHookInput`

1148 

1149```typescript theme={null}

1150type PostToolUseHookInput = BaseHookInput & {

1151 hook_event_name: "PostToolUse";

1152 tool_name: string;

1153 tool_input: unknown;

1154 tool_response: unknown;

1155 tool_use_id: string;

1156 duration_ms?: number;

1157};

1158```

1159 

1160#### `PostToolUseFailureHookInput`

1161 

1162```typescript theme={null}

1163type PostToolUseFailureHookInput = BaseHookInput & {

1164 hook_event_name: "PostToolUseFailure";

1165 tool_name: string;

1166 tool_input: unknown;

1167 tool_use_id: string;

1168 error: string;

1169 is_interrupt?: boolean;

1170 duration_ms?: number;

1171};

1172```

1173 

1174#### `PostToolBatchHookInput`

1175 

1176在批次中的每個工具呼叫都已解決後、下一個模型請求之前觸發一次。`tool_response` 攜帶序列化的 `tool_result` 內容,模型會看到;其形狀與 `PostToolUseHookInput` 的結構化 `Output` 物件不同。

1177 

1178```typescript theme={null}

1179type PostToolBatchHookInput = BaseHookInput & {

1180 hook_event_name: "PostToolBatch";

1181 tool_calls: PostToolBatchToolCall[];

1182};

1183 

1184type PostToolBatchToolCall = {

1185 tool_name: string;

1186 tool_input: unknown;

1187 tool_use_id: string;

1188 tool_response?: unknown;

1189};

1190```

1191 

1192#### `NotificationHookInput`

1193 

1194```typescript theme={null}

1195type NotificationHookInput = BaseHookInput & {

1196 hook_event_name: "Notification";

1197 message: string;

1198 title?: string;

1199 notification_type: string;

1200};

1201```

1202 

1203#### `UserPromptSubmitHookInput`

1204 

1205```typescript theme={null}

1206type UserPromptSubmitHookInput = BaseHookInput & {

1207 hook_event_name: "UserPromptSubmit";

1208 prompt: string;

1209};

1210```

1211 

1212#### `SessionStartHookInput`

1213 

1214```typescript theme={null}

1215type SessionStartHookInput = BaseHookInput & {

1216 hook_event_name: "SessionStart";

1217 source: "startup" | "resume" | "clear" | "compact";

1218 agent_type?: string;

1219 model?: string;

1220};

1221```

1222 

1223#### `SessionEndHookInput`

1224 

1225```typescript theme={null}

1226type SessionEndHookInput = BaseHookInput & {

1227 hook_event_name: "SessionEnd";

1228 reason: ExitReason; // EXIT_REASONS 數組中的字符串

1229};

1230```

1231 

1232#### `StopHookInput`

1233 

1234```typescript theme={null}

1235type StopHookInput = BaseHookInput & {

1236 hook_event_name: "Stop";

1237 stop_hook_active: boolean;

1238 last_assistant_message?: string;

1239};

1240```

1241 

1242#### `SubagentStartHookInput`

1243 

1244```typescript theme={null}

1245type SubagentStartHookInput = BaseHookInput & {

1246 hook_event_name: "SubagentStart";

1247 agent_id: string;

1248 agent_type: string;

1249};

1250```

1251 

1252#### `SubagentStopHookInput`

1253 

1254```typescript theme={null}

1255type SubagentStopHookInput = BaseHookInput & {

1256 hook_event_name: "SubagentStop";

1257 stop_hook_active: boolean;

1258 agent_id: string;

1259 agent_transcript_path: string;

1260 agent_type: string;

1261 last_assistant_message?: string;

1262};

1263```

1264 

1265#### `PreCompactHookInput`

1266 

1267```typescript theme={null}

1268type PreCompactHookInput = BaseHookInput & {

1269 hook_event_name: "PreCompact";

1270 trigger: "manual" | "auto";

1271 custom_instructions: string | null;

1272};

1273```

1274 

1275#### `PermissionRequestHookInput`

1276 

1277```typescript theme={null}

1278type PermissionRequestHookInput = BaseHookInput & {

1279 hook_event_name: "PermissionRequest";

1280 tool_name: string;

1281 tool_input: unknown;

1282 permission_suggestions?: PermissionUpdate[];

1283};

1284```

1285 

1286#### `SetupHookInput`

1287 

1288```typescript theme={null}

1289type SetupHookInput = BaseHookInput & {

1290 hook_event_name: "Setup";

1291 trigger: "init" | "maintenance";

1292};

1293```

1294 

1295#### `TeammateIdleHookInput`

1296 

1297```typescript theme={null}

1298type TeammateIdleHookInput = BaseHookInput & {

1299 hook_event_name: "TeammateIdle";

1300 teammate_name: string;

1301 team_name: string;

1302};

1303```

1304 

1305#### `TaskCompletedHookInput`

1306 

1307```typescript theme={null}

1308type TaskCompletedHookInput = BaseHookInput & {

1309 hook_event_name: "TaskCompleted";

1310 task_id: string;

1311 task_subject: string;

1312 task_description?: string;

1313 teammate_name?: string;

1314 team_name?: string;

1315};

1316```

1317 

1318#### `ConfigChangeHookInput`

1319 

1320```typescript theme={null}

1321type ConfigChangeHookInput = BaseHookInput & {

1322 hook_event_name: "ConfigChange";

1323 source:

1324 | "user_settings"

1325 | "project_settings"

1326 | "local_settings"

1327 | "policy_settings"

1328 | "skills";

1329 file_path?: string;

1330};

1331```

1332 

1333#### `WorktreeCreateHookInput`

1334 

1335```typescript theme={null}

1336type WorktreeCreateHookInput = BaseHookInput & {

1337 hook_event_name: "WorktreeCreate";

1338 name: string;

1339};

1340```

1341 

1342#### `WorktreeRemoveHookInput`

1343 

1344```typescript theme={null}

1345type WorktreeRemoveHookInput = BaseHookInput & {

1346 hook_event_name: "WorktreeRemove";

1347 worktree_path: string;

1348};

1349```

1350 

1351### `HookJSONOutput`

1352 

1353Hook 返回值。

1354 

1355```typescript theme={null}

1356type HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput;

1357```

1358 

1359#### `AsyncHookJSONOutput`

1360 

1361```typescript theme={null}

1362type AsyncHookJSONOutput = {

1363 async: true;

1364 asyncTimeout?: number;

1365};

1366```

1367 

1368#### `SyncHookJSONOutput`

1369 

1370```typescript theme={null}

1371type SyncHookJSONOutput = {

1372 continue?: boolean;

1373 suppressOutput?: boolean;

1374 stopReason?: string;

1375 decision?: "approve" | "block";

1376 systemMessage?: string;

1377 reason?: string;

1378 hookSpecificOutput?:

1379 | {

1380 hookEventName: "PreToolUse";

1381 permissionDecision?: "allow" | "deny" | "ask" | "defer";

1382 permissionDecisionReason?: string;

1383 updatedInput?: Record<string, unknown>;

1384 additionalContext?: string;

1385 }

1386 | {

1387 hookEventName: "UserPromptSubmit";

1388 additionalContext?: string;

1389 }

1390 | {

1391 hookEventName: "SessionStart";

1392 additionalContext?: string;

1393 }

1394 | {

1395 hookEventName: "Setup";

1396 additionalContext?: string;

1397 }

1398 | {

1399 hookEventName: "SubagentStart";

1400 additionalContext?: string;

1401 }

1402 | {

1403 hookEventName: "PostToolUse";

1404 additionalContext?: string;

1405 updatedToolOutput?: unknown;

1406 /** @deprecated 使用 `updatedToolOutput`,適用於所有工具。 */

1407 updatedMCPToolOutput?: unknown;

1408 }

1409 | {

1410 hookEventName: "PostToolUseFailure";

1411 additionalContext?: string;

1412 }

1413 | {

1414 hookEventName: "PostToolBatch";

1415 additionalContext?: string;

1416 }

1417 | {

1418 hookEventName: "Notification";

1419 additionalContext?: string;

1420 }

1421 | {

1422 hookEventName: "PermissionRequest";

1423 decision:

1424 | {

1425 behavior: "allow";

1426 updatedInput?: Record<string, unknown>;

1427 updatedPermissions?: PermissionUpdate[];

1428 }

1429 | {

1430 behavior: "deny";

1431 message?: string;

1432 interrupt?: boolean;

1433 };

1434 };

1435};

1436```

1437 

1438## 工具輸入類型

1439 

1440所有內置 Claude Code 工具的輸入架構文檔。這些類型從 `@anthropic-ai/claude-agent-sdk` 導出,可用於類型安全的工具交互。

1441 

1442### `ToolInputSchemas`

1443 

1444所有工具輸入類型的聯合,從 `@anthropic-ai/claude-agent-sdk` 導出。

1445 

1446```typescript theme={null}

1447type ToolInputSchemas =

1448 | AgentInput

1449 | AskUserQuestionInput

1450 | BashInput

1451 | TaskOutputInput

1452 | EnterWorktreeInput

1453 | ExitPlanModeInput

1454 | FileEditInput

1455 | FileReadInput

1456 | FileWriteInput

1457 | GlobInput

1458 | GrepInput

1459 | ListMcpResourcesInput

1460 | McpInput

1461 | MonitorInput

1462 | NotebookEditInput

1463 | ReadMcpResourceInput

1464 | SubscribeMcpResourceInput

1465 | SubscribePollingInput

1466 | TaskStopInput

1467 | TodoWriteInput

1468 | UnsubscribeMcpResourceInput

1469 | UnsubscribePollingInput

1470 | WebFetchInput

1471 | WebSearchInput;

1472```

1473 

1474### Agent

1475 

1476**工具名稱:** `Agent`(之前是 `Task`,仍然接受作為別名)

1477 

1478```typescript theme={null}

1479type AgentInput = {

1480 description: string;

1481 prompt: string;

1482 subagent_type: string;

1483 model?: "sonnet" | "opus" | "haiku";

1484 resume?: string;

1485 run_in_background?: boolean;

1486 max_turns?: number;

1487 name?: string;

1488 team_name?: string;

1489 mode?: "acceptEdits" | "bypassPermissions" | "default" | "dontAsk" | "plan";

1490 isolation?: "worktree";

1491};

1492```

1493 

1494啟動新代理以自主處理複雜的多步驟任務。

1495 

1496### AskUserQuestion

1497 

1498**工具名稱:** `AskUserQuestion`

1499 

1500```typescript theme={null}

1501type AskUserQuestionInput = {

1502 questions: Array<{

1503 question: string;

1504 header: string;

1505 options: Array<{ label: string; description: string; preview?: string }>;

1506 multiSelect: boolean;

1507 }>;

1508};

1509```

1510 

1511在執行期間向用戶提出澄清問題。見 [處理批准和用戶輸入](/zh-TW/agent-sdk/user-input#handle-clarifying-questions) 了解使用詳情。

1512 

1513### Bash

1514 

1515**工具名稱:** `Bash`

1516 

1517```typescript theme={null}

1518type BashInput = {

1519 command: string;

1520 timeout?: number;

1521 description?: string;

1522 run_in_background?: boolean;

1523 dangerouslyDisableSandbox?: boolean;

1524};

1525```

1526 

1527在持久 shell 會話中執行 bash 命令,具有可選的超時和後台執行。

1528 

1529### Monitor

1530 

1531**工具名稱:** `Monitor`

1532 

1533```typescript theme={null}

1534type MonitorInput = {

1535 command: string;

1536 description: string;

1537 timeout_ms?: number;

1538 persistent?: boolean;

1539};

1540```

1541 

1542運行後台腳本並將每個 stdout 行作為事件傳遞給 Claude,以便它可以在不輪詢的情況下做出反應。為會話長度的監視(如日誌尾部)設置 `persistent: true`。Monitor 遵循與 Bash 相同的權限規則。見 [Monitor 工具參考](/zh-TW/tools-reference#monitor-tool) 了解行為和提供商可用性。

1543 

1544### TaskOutput

1545 

1546**工具名稱:** `TaskOutput`

1547 

1548```typescript theme={null}

1549type TaskOutputInput = {

1550 task_id: string;

1551 block: boolean;

1552 timeout: number;

1553};

1554```

1555 

1556從運行或已完成的後台任務檢索輸出。

1557 

1558### Edit

1559 

1560**工具名稱:** `Edit`

1561 

1562```typescript theme={null}

1563type FileEditInput = {

1564 file_path: string;

1565 old_string: string;

1566 new_string: string;

1567 replace_all?: boolean;

1568};

1569```

1570 

1571在文件中執行精確字符串替換。

1572 

1573### Read

1574 

1575**工具名稱:** `Read`

1576 

1577```typescript theme={null}

1578type FileReadInput = {

1579 file_path: string;

1580 offset?: number;

1581 limit?: number;

1582 pages?: string;

1583};

1584```

1585 

1586從本地文件系統讀取文件,包括文本、圖像、PDF 和 Jupyter 筆記本。對 PDF 頁面範圍使用 `pages`(例如,`"1-5"`)。

1587 

1588### Write

1589 

1590**工具名稱:** `Write`

1591 

1592```typescript theme={null}

1593type FileWriteInput = {

1594 file_path: string;

1595 content: string;

1596};

1597```

1598 

1599將文件寫入本地文件系統,如果存在則覆蓋。

1600 

1601### Glob

1602 

1603**工具名稱:** `Glob`

1604 

1605```typescript theme={null}

1606type GlobInput = {

1607 pattern: string;

1608 path?: string;

1609};

1610```

1611 

1612快速文件模式匹配,適用於任何代碼庫大小。

1613 

1614### Grep

1615 

1616**工具名稱:** `Grep`

1617 

1618```typescript theme={null}

1619type GrepInput = {

1620 pattern: string;

1621 path?: string;

1622 glob?: string;

1623 type?: string;

1624 output_mode?: "content" | "files_with_matches" | "count";

1625 "-i"?: boolean;

1626 "-n"?: boolean;

1627 "-B"?: number;

1628 "-A"?: number;

1629 "-C"?: number;

1630 context?: number;

1631 head_limit?: number;

1632 offset?: number;

1633 multiline?: boolean;

1634};

1635```

1636 

1637基於 ripgrep 的強大搜索工具,支持正則表達式。

1638 

1639### TaskStop

1640 

1641**工具名稱:** `TaskStop`

1642 

1643```typescript theme={null}

1644type TaskStopInput = {

1645 task_id?: string;

1646 shell_id?: string; // 已棄用:使用 task_id

1647};

1648```

1649 

1650按 ID 停止運行的後台任務或 shell。

1651 

1652### NotebookEdit

1653 

1654**工具名稱:** `NotebookEdit`

1655 

1656```typescript theme={null}

1657type NotebookEditInput = {

1658 notebook_path: string;

1659 cell_id?: string;

1660 new_source: string;

1661 cell_type?: "code" | "markdown";

1662 edit_mode?: "replace" | "insert" | "delete";

1663};

1664```

1665 

1666編輯 Jupyter 筆記本文件中的單元格。

1667 

1668### WebFetch

1669 

1670**工具名稱:** `WebFetch`

1671 

1672```typescript theme={null}

1673type WebFetchInput = {

1674 url: string;

1675 prompt: string;

1676};

1677```

1678 

1679從 URL 獲取內容並使用 AI 模型處理它。

1680 

1681### WebSearch

1682 

1683**工具名稱:** `WebSearch`

1684 

1685```typescript theme={null}

1686type WebSearchInput = {

1687 query: string;

1688 allowed_domains?: string[];

1689 blocked_domains?: string[];

1690};

1691```

1692 

1693搜索網絡並返回格式化結果。

1694 

1695### TodoWrite

1696 

1697**工具名稱:** `TodoWrite`

1698 

1699```typescript theme={null}

1700type TodoWriteInput = {

1701 todos: Array<{

1702 content: string;

1703 status: "pending" | "in_progress" | "completed";

1704 activeForm: string;

1705 }>;

1706};

1707```

1708 

1709創建和管理結構化任務列表以跟蹤進度。

1710 

1711### ExitPlanMode

1712 

1713**工具名稱:** `ExitPlanMode`

1714 

1715```typescript theme={null}

1716type ExitPlanModeInput = {

1717 allowedPrompts?: Array<{

1718 tool: "Bash";

1719 prompt: string;

1720 }>;

1721};

1722```

1723 

1724退出規劃模式。可選地指定實施計劃所需的基於提示的權限。

1725 

1726### ListMcpResources

1727 

1728**工具名稱:** `ListMcpResources`

1729 

1730```typescript theme={null}

1731type ListMcpResourcesInput = {

1732 server?: string;

1733};

1734```

1735 

1736列出來自連接服務器的可用 MCP 資源。

1737 

1738### ReadMcpResource

1739 

1740**工具名稱:** `ReadMcpResource`

1741 

1742```typescript theme={null}

1743type ReadMcpResourceInput = {

1744 server: string;

1745 uri: string;

1746};

1747```

1748 

1749從服務器讀取特定的 MCP 資源。

1750 

1751### EnterWorktree

1752 

1753**工具名稱:** `EnterWorktree`

1754 

1755```typescript theme={null}

1756type EnterWorktreeInput = {

1757 name?: string;

1758 path?: string;

1759};

1760```

1761 

1762創建並進入臨時 git worktree 以進行隔離工作。傳遞 `path` 以切換到當前存儲庫的現有 worktree,而不是創建新的。`name` 和 `path` 互斥。

1763 

1764## 工具輸出類型

1765 

1766所有內置 Claude Code 工具的輸出架構文檔。這些類型從 `@anthropic-ai/claude-agent-sdk` 導出,代表每個工具返回的實際響應數據。

1767 

1768### `ToolOutputSchemas`

1769 

1770所有工具輸出類型的聯合。

1771 

1772```typescript theme={null}

1773type ToolOutputSchemas =

1774 | AgentOutput

1775 | AskUserQuestionOutput

1776 | BashOutput

1777 | EnterWorktreeOutput

1778 | ExitPlanModeOutput

1779 | FileEditOutput

1780 | FileReadOutput

1781 | FileWriteOutput

1782 | GlobOutput

1783 | GrepOutput

1784 | ListMcpResourcesOutput

1785 | MonitorOutput

1786 | NotebookEditOutput

1787 | ReadMcpResourceOutput

1788 | TaskStopOutput

1789 | TodoWriteOutput

1790 | WebFetchOutput

1791 | WebSearchOutput;

1792```

1793 

1794### Agent

1795 

1796**工具名稱:** `Agent`(之前是 `Task`,仍然接受作為別名)

1797 

1798```typescript theme={null}

1799type AgentOutput =

1800 | {

1801 status: "completed";

1802 agentId: string;

1803 content: Array<{ type: "text"; text: string }>;

1804 totalToolUseCount: number;

1805 totalDurationMs: number;

1806 totalTokens: number;

1807 usage: {

1808 input_tokens: number;

1809 output_tokens: number;

1810 cache_creation_input_tokens: number | null;

1811 cache_read_input_tokens: number | null;

1812 server_tool_use: {

1813 web_search_requests: number;

1814 web_fetch_requests: number;

1815 } | null;

1816 service_tier: ("standard" | "priority" | "batch") | null;

1817 cache_creation: {

1818 ephemeral_1h_input_tokens: number;

1819 ephemeral_5m_input_tokens: number;

1820 } | null;

1821 };

1822 prompt: string;

1823 }

1824 | {

1825 status: "async_launched";

1826 agentId: string;

1827 description: string;

1828 prompt: string;

1829 outputFile: string;

1830 canReadOutputFile?: boolean;

1831 }

1832 | {

1833 status: "sub_agent_entered";

1834 description: string;

1835 message: string;

1836 };

1837```

1838 

1839返回子代理的結果。在 `status` 字段上區分:`"completed"` 用於已完成的任務,`"async_launched"` 用於後台任務,`"sub_agent_entered"` 用於交互式子代理。

1840 

1841### AskUserQuestion

1842 

1843**工具名稱:** `AskUserQuestion`

1844 

1845```typescript theme={null}

1846type AskUserQuestionOutput = {

1847 questions: Array<{

1848 question: string;

1849 header: string;

1850 options: Array<{ label: string; description: string; preview?: string }>;

1851 multiSelect: boolean;

1852 }>;

1853 answers: Record<string, string>;

1854};

1855```

1856 

1857返回提出的問題和用戶的答案。

1858 

1859### Bash

1860 

1861**工具名稱:** `Bash`

1862 

1863```typescript theme={null}

1864type BashOutput = {

1865 stdout: string;

1866 stderr: string;

1867 rawOutputPath?: string;

1868 interrupted: boolean;

1869 isImage?: boolean;

1870 backgroundTaskId?: string;

1871 backgroundedByUser?: boolean;

1872 dangerouslyDisableSandbox?: boolean;

1873 returnCodeInterpretation?: string;

1874 structuredContent?: unknown[];

1875 persistedOutputPath?: string;

1876 persistedOutputSize?: number;

1877};

1878```

1879 

1880返回命令輸出,stdout/stderr 分開。後台命令包括 `backgroundTaskId`。

1881 

1882### Monitor

1883 

1884**工具名稱:** `Monitor`

1885 

1886```typescript theme={null}

1887type MonitorOutput = {

1888 taskId: string;

1889 timeoutMs: number;

1890 persistent?: boolean;

1891};

1892```

1893 

1894返回運行監視器的後台任務 ID。使用此 ID 與 `TaskStop` 一起提前取消監視。

1895 

1896### Edit

1897 

1898**工具名稱:** `Edit`

1899 

1900```typescript theme={null}

1901type FileEditOutput = {

1902 filePath: string;

1903 oldString: string;

1904 newString: string;

1905 originalFile: string;

1906 structuredPatch: Array<{

1907 oldStart: number;

1908 oldLines: number;

1909 newStart: number;

1910 newLines: number;

1911 lines: string[];

1912 }>;

1913 userModified: boolean;

1914 replaceAll: boolean;

1915 gitDiff?: {

1916 filename: string;

1917 status: "modified" | "added";

1918 additions: number;

1919 deletions: number;

1920 changes: number;

1921 patch: string;

1922 };

1923};

1924```

1925 

1926返回編輯操作的結構化差異。

1927 

1928### Read

1929 

1930**工具名稱:** `Read`

1931 

1932```typescript theme={null}

1933type FileReadOutput =

1934 | {

1935 type: "text";

1936 file: {

1937 filePath: string;

1938 content: string;

1939 numLines: number;

1940 startLine: number;

1941 totalLines: number;

1942 };

1943 }

1944 | {

1945 type: "image";

1946 file: {

1947 base64: string;

1948 type: "image/jpeg" | "image/png" | "image/gif" | "image/webp";

1949 originalSize: number;

1950 dimensions?: {

1951 originalWidth?: number;

1952 originalHeight?: number;

1953 displayWidth?: number;

1954 displayHeight?: number;

1955 };

1956 };

1957 }

1958 | {

1959 type: "notebook";

1960 file: {

1961 filePath: string;

1962 cells: unknown[];

1963 };

1964 }

1965 | {

1966 type: "pdf";

1967 file: {

1968 filePath: string;

1969 base64: string;

1970 originalSize: number;

1971 };

1972 }

1973 | {

1974 type: "parts";

1975 file: {

1976 filePath: string;

1977 originalSize: number;

1978 count: number;

1979 outputDir: string;

1980 };

1981 };

1982```

1983 

1984返回適合文件類型的文件內容。在 `type` 字段上區分。

1985 

1986### Write

1987 

1988**工具名稱:** `Write`

1989 

1990```typescript theme={null}

1991type FileWriteOutput = {

1992 type: "create" | "update";

1993 filePath: string;

1994 content: string;

1995 structuredPatch: Array<{

1996 oldStart: number;

1997 oldLines: number;

1998 newStart: number;

1999 newLines: number;

2000 lines: string[];

2001 }>;

2002 originalFile: string | null;

2003 gitDiff?: {

2004 filename: string;

2005 status: "modified" | "added";

2006 additions: number;

2007 deletions: number;

2008 changes: number;

2009 patch: string;

2010 };

2011};

2012```

2013 

2014返回寫入結果,包含結構化差異信息。

2015 

2016### Glob

2017 

2018**工具名稱:** `Glob`

2019 

2020```typescript theme={null}

2021type GlobOutput = {

2022 durationMs: number;

2023 numFiles: number;

2024 filenames: string[];

2025 truncated: boolean;

2026};

2027```

2028 

2029返回與 glob 模式匹配的文件路徑,按修改時間排序。

2030 

2031### Grep

2032 

2033**工具名稱:** `Grep`

2034 

2035```typescript theme={null}

2036type GrepOutput = {

2037 mode?: "content" | "files_with_matches" | "count";

2038 numFiles: number;

2039 filenames: string[];

2040 content?: string;

2041 numLines?: number;

2042 numMatches?: number;

2043 appliedLimit?: number;

2044 appliedOffset?: number;

2045};

2046```

2047 

2048返回搜索結果。形狀因 `mode` 而異:文件列表、帶匹配的內容或匹配計數。

2049 

2050### TaskStop

2051 

2052**工具名稱:** `TaskStop`

2053 

2054```typescript theme={null}

2055type TaskStopOutput = {

2056 message: string;

2057 task_id: string;

2058 task_type: string;

2059 command?: string;

2060};

2061```

2062 

2063停止後台任務後返回確認。

2064 

2065### NotebookEdit

2066 

2067**工具名稱:** `NotebookEdit`

2068 

2069```typescript theme={null}

2070type NotebookEditOutput = {

2071 new_source: string;

2072 cell_id?: string;

2073 cell_type: "code" | "markdown";

2074 language: string;

2075 edit_mode: string;

2076 error?: string;

2077 notebook_path: string;

2078 original_file: string;

2079 updated_file: string;

2080};

2081```

2082 

2083返回筆記本編輯的結果,包含原始和更新的文件內容。

2084 

2085### WebFetch

2086 

2087**工具名稱:** `WebFetch`

2088 

2089```typescript theme={null}

2090type WebFetchOutput = {

2091 bytes: number;

2092 code: number;

2093 codeText: string;

2094 result: string;

2095 durationMs: number;

2096 url: string;

2097};

2098```

2099 

2100返回獲取的內容,包含 HTTP 狀態和元數據。

2101 

2102### WebSearch

2103 

2104**工具名稱:** `WebSearch`

2105 

2106```typescript theme={null}

2107type WebSearchOutput = {

2108 query: string;

2109 results: Array<

2110 | {

2111 tool_use_id: string;

2112 content: Array<{ title: string; url: string }>;

2113 }

2114 | string

2115 >;

2116 durationSeconds: number;

2117};

2118```

2119 

2120返回來自網絡的搜索結果。

2121 

2122### TodoWrite

2123 

2124**工具名稱:** `TodoWrite`

2125 

2126```typescript theme={null}

2127type TodoWriteOutput = {

2128 oldTodos: Array<{

2129 content: string;

2130 status: "pending" | "in_progress" | "completed";

2131 activeForm: string;

2132 }>;

2133 newTodos: Array<{

2134 content: string;

2135 status: "pending" | "in_progress" | "completed";

2136 activeForm: string;

2137 }>;

2138};

2139```

2140 

2141返回之前和更新的任務列表。

2142 

2143### ExitPlanMode

2144 

2145**工具名稱:** `ExitPlanMode`

2146 

2147```typescript theme={null}

2148type ExitPlanModeOutput = {

2149 plan: string | null;

2150 isAgent: boolean;

2151 filePath?: string;

2152 hasTaskTool?: boolean;

2153 awaitingLeaderApproval?: boolean;

2154 requestId?: string;

2155};

2156```

2157 

2158返回退出規劃模式後的計劃狀態。

2159 

2160### ListMcpResources

2161 

2162**工具名稱:** `ListMcpResources`

2163 

2164```typescript theme={null}

2165type ListMcpResourcesOutput = Array<{

2166 uri: string;

2167 name: string;

2168 mimeType?: string;

2169 description?: string;

2170 server: string;

2171}>;

2172```

2173 

2174返回可用 MCP 資源的數組。

2175 

2176### ReadMcpResource

2177 

2178**工具名稱:** `ReadMcpResource`

2179 

2180```typescript theme={null}

2181type ReadMcpResourceOutput = {

2182 contents: Array<{

2183 uri: string;

2184 mimeType?: string;

2185 text?: string;

2186 }>;

2187};

2188```

2189 

2190返回請求的 MCP 資源的內容。

2191 

2192### EnterWorktree

2193 

2194**工具名稱:** `EnterWorktree`

2195 

2196```typescript theme={null}

2197type EnterWorktreeOutput = {

2198 worktreePath: string;

2199 worktreeBranch?: string;

2200 message: string;

2201};

2202```

2203 

2204返回有關 git worktree 的信息。

2205 

2206## 權限類型

2207 

2208### `PermissionUpdate`

2209 

2210用於更新權限的操作。

2211 

2212```typescript theme={null}

2213type PermissionUpdate =

2214 | {

2215 type: "addRules";

2216 rules: PermissionRuleValue[];

2217 behavior: PermissionBehavior;

2218 destination: PermissionUpdateDestination;

2219 }

2220 | {

2221 type: "replaceRules";

2222 rules: PermissionRuleValue[];

2223 behavior: PermissionBehavior;

2224 destination: PermissionUpdateDestination;

2225 }

2226 | {

2227 type: "removeRules";

2228 rules: PermissionRuleValue[];

2229 behavior: PermissionBehavior;

2230 destination: PermissionUpdateDestination;

2231 }

2232 | {

2233 type: "setMode";

2234 mode: PermissionMode;

2235 destination: PermissionUpdateDestination;

2236 }

2237 | {

2238 type: "addDirectories";

2239 directories: string[];

2240 destination: PermissionUpdateDestination;

2241 }

2242 | {

2243 type: "removeDirectories";

2244 directories: string[];

2245 destination: PermissionUpdateDestination;

2246 };

2247```

2248 

2249### `PermissionBehavior`

2250 

2251```typescript theme={null}

2252type PermissionBehavior = "allow" | "deny" | "ask";

2253```

2254 

2255### `PermissionUpdateDestination`

2256 

2257```typescript theme={null}

2258type PermissionUpdateDestination =

2259 | "userSettings" // 全局用戶設置

2260 | "projectSettings" // 每個目錄的項目設置

2261 | "localSettings" // Gitignored 本地設置

2262 | "session" // 僅當前會話

2263 | "cliArg"; // CLI 參數

2264```

2265 

2266### `PermissionRuleValue`

2267 

2268```typescript theme={null}

2269type PermissionRuleValue = {

2270 toolName: string;

2271 ruleContent?: string;

2272};

2273```

2274 

2275## 其他類型

2276 

2277### `ApiKeySource`

2278 

2279```typescript theme={null}

2280type ApiKeySource = "user" | "project" | "org" | "temporary" | "oauth";

2281```

2282 

2283### `SdkBeta`

2284 

2285可通過 `betas` 選項啟用的可用測試功能。見 [Beta 標頭](https://platform.claude.com/docs/zh-TW/api/beta-headers) 了解更多信息。

2286 

2287```typescript theme={null}

2288type SdkBeta = "context-1m-2025-08-07";

2289```

2290 

2291<Warning>

2292 `context-1m-2025-08-07` beta 自 2026 年 4 月 30 日起已停用。使用 Claude Sonnet 4.5 或 Sonnet 4 傳遞此值無效,超過標準 200k 令牌上下文窗口的請求返回錯誤。要使用 1M 令牌上下文窗口,請遷移到 [Claude Sonnet 4.6、Claude Opus 4.6 或 Claude Opus 4.7](https://platform.claude.com/docs/zh-TW/about-claude/models/overview),它們以標準定價包括 1M 上下文,無需 beta 標頭。

2293</Warning>

2294 

2295### `SlashCommand`

2296 

2297有關可用 slash command 的信息。

2298 

2299```typescript theme={null}

2300type SlashCommand = {

2301 name: string;

2302 description: string;

2303 argumentHint: string;

2304 aliases?: string[];

2305};

2306```

2307 

2308### `ModelInfo`

2309 

2310有關可用模型的信息。

2311 

2312```typescript theme={null}

2313type ModelInfo = {

2314 value: string;

2315 displayName: string;

2316 description: string;

2317 supportsEffort?: boolean;

2318 supportedEffortLevels?: ("low" | "medium" | "high" | "xhigh" | "max")[];

2319 supportsAdaptiveThinking?: boolean;

2320 supportsFastMode?: boolean;

2321};

2322```

2323 

2324### `AgentInfo`

2325 

2326有關可通過 Agent 工具調用的可用子代理的信息。

2327 

2328```typescript theme={null}

2329type AgentInfo = {

2330 name: string;

2331 description: string;

2332 model?: string;

2333};

2334```

2335 

2336| 字段 | 類型 | 描述 |

2337| :------------ | :-------------------- | :------------------------------------------ |

2338| `name` | `string` | 代理類型標識符(例如,`"Explore"`、`"general-purpose"`) |

2339| `description` | `string` | 何時使用此代理的描述 |

2340| `model` | `string \| undefined` | 此代理使用的模型別名。如果省略,繼承父代理的模型 |

2341 

2342### `McpServerStatus`

2343 

2344連接的 MCP 服務器的狀態。

2345 

2346```typescript theme={null}

2347type McpServerStatus = {

2348 name: string;

2349 status: "connected" | "failed" | "needs-auth" | "pending" | "disabled";

2350 serverInfo?: {

2351 name: string;

2352 version: string;

2353 };

2354 error?: string;

2355 config?: McpServerStatusConfig;

2356 scope?: string;

2357 tools?: {

2358 name: string;

2359 description?: string;

2360 annotations?: {

2361 readOnly?: boolean;

2362 destructive?: boolean;

2363 openWorld?: boolean;

2364 };

2365 }[];

2366};

2367```

2368 

2369### `McpServerStatusConfig`

2370 

2371MCP 服務器的配置,如 `mcpServerStatus()` 報告的那樣。這是所有 MCP 服務器傳輸類型的聯合。

2372 

2373```typescript theme={null}

2374type McpServerStatusConfig =

2375 | McpStdioServerConfig

2376 | McpSSEServerConfig

2377 | McpHttpServerConfig

2378 | McpSdkServerConfig

2379 | McpClaudeAIProxyServerConfig;

2380```

2381 

2382見 [`McpServerConfig`](#mcp-server-config) 了解每種傳輸類型的詳情。

2383 

2384### `AccountInfo`

2385 

2386經過身份驗證的用戶的帳戶信息。

2387 

2388```typescript theme={null}

2389type AccountInfo = {

2390 email?: string;

2391 organization?: string;

2392 subscriptionType?: string;

2393 tokenSource?: string;

2394 apiKeySource?: string;

2395};

2396```

2397 

2398### `ModelUsage`

2399 

2400結果消息中返回的每個模型使用統計。`costUSD` 值是客戶端估計。見 [跟蹤成本和使用情況](/zh-TW/agent-sdk/cost-tracking) 了解計費注意事項。

2401 

2402```typescript theme={null}

2403type ModelUsage = {

2404 inputTokens: number;

2405 outputTokens: number;

2406 cacheReadInputTokens: number;

2407 cacheCreationInputTokens: number;

2408 webSearchRequests: number;

2409 costUSD: number;

2410 contextWindow: number;

2411 maxOutputTokens: number;

2412};

2413```

2414 

2415### `ConfigScope`

2416 

2417```typescript theme={null}

2418type ConfigScope = "local" | "user" | "project";

2419```

2420 

2421### `NonNullableUsage`

2422 

2423[`Usage`](#usage) 的版本,所有可空字段都變為非可空。

2424 

2425```typescript theme={null}

2426type NonNullableUsage = {

2427 [K in keyof Usage]: NonNullable<Usage[K]>;

2428};

2429```

2430 

2431### `Usage`

2432 

2433令牌使用統計(來自 `@anthropic-ai/sdk`)。

2434 

2435```typescript theme={null}

2436type Usage = {

2437 input_tokens: number | null;

2438 output_tokens: number | null;

2439 cache_creation_input_tokens?: number | null;

2440 cache_read_input_tokens?: number | null;

2441};

2442```

2443 

2444### `CallToolResult`

2445 

2446MCP 工具結果類型(來自 `@modelcontextprotocol/sdk/types.js`)。

2447 

2448```typescript theme={null}

2449type CallToolResult = {

2450 content: Array<{

2451 type: "text" | "image" | "resource";

2452 // 其他字段因類型而異

2453 }>;

2454 isError?: boolean;

2455};

2456```

2457 

2458### `ThinkingConfig`

2459 

2460控制 Claude 的思考/推理行為。優先於已棄用的 `maxThinkingTokens`。

2461 

2462```typescript theme={null}

2463type ThinkingConfig =

2464 | { type: "adaptive" } // 模型確定何時以及多少推理(Opus 4.6+)

2465 | { type: "enabled"; budgetTokens?: number } // 固定思考令牌預算

2466 | { type: "disabled" }; // 無擴展思考

2467```

2468 

2469### `SpawnedProcess`

2470 

2471自定義進程生成的介面(與 `spawnClaudeCodeProcess` 選項一起使用)。`ChildProcess` 已滿足此介面。

2472 

2473```typescript theme={null}

2474interface SpawnedProcess {

2475 stdin: Writable;

2476 stdout: Readable;

2477 readonly killed: boolean;

2478 readonly exitCode: number | null;

2479 kill(signal: NodeJS.Signals): boolean;

2480 on(

2481 event: "exit",

2482 listener: (code: number | null, signal: NodeJS.Signals | null) => void

2483 ): void;

2484 on(event: "error", listener: (error: Error) => void): void;

2485 once(

2486 event: "exit",

2487 listener: (code: number | null, signal: NodeJS.Signals | null) => void

2488 ): void;

2489 once(event: "error", listener: (error: Error) => void): void;

2490 off(

2491 event: "exit",

2492 listener: (code: number | null, signal: NodeJS.Signals | null) => void

2493 ): void;

2494 off(event: "error", listener: (error: Error) => void): void;

2495}

2496```

2497 

2498### `SpawnOptions`

2499 

2500傳遞給自定義生成函數的選項。

2501 

2502```typescript theme={null}

2503interface SpawnOptions {

2504 command: string;

2505 args: string[];

2506 cwd?: string;

2507 env: Record<string, string | undefined>;

2508 signal: AbortSignal;

2509}

2510```

2511 

2512### `McpSetServersResult`

2513 

2514`setMcpServers()` 操作的結果。

2515 

2516```typescript theme={null}

2517type McpSetServersResult = {

2518 added: string[];

2519 removed: string[];

2520 errors: Record<string, string>;

2521};

2522```

2523 

2524### `RewindFilesResult`

2525 

2526`rewindFiles()` 操作的結果。

2527 

2528```typescript theme={null}

2529type RewindFilesResult = {

2530 canRewind: boolean;

2531 error?: string;

2532 filesChanged?: string[];

2533 insertions?: number;

2534 deletions?: number;

2535};

2536```

2537 

2538### `SDKStatusMessage`

2539 

2540狀態更新消息(例如,壓縮)。

2541 

2542```typescript theme={null}

2543type SDKStatusMessage = {

2544 type: "system";

2545 subtype: "status";

2546 status: "compacting" | null;

2547 permissionMode?: PermissionMode;

2548 uuid: UUID;

2549 session_id: string;

2550};

2551```

2552 

2553### `SDKTaskNotificationMessage`

2554 

2555後台任務完成、失敗或停止時的通知。後台任務包括 `run_in_background` Bash 命令、[Monitor](#monitor) 監視和後台子代理。

2556 

2557```typescript theme={null}

2558type SDKTaskNotificationMessage = {

2559 type: "system";

2560 subtype: "task_notification";

2561 task_id: string;

2562 tool_use_id?: string;

2563 status: "completed" | "failed" | "stopped";

2564 output_file: string;

2565 summary: string;

2566 usage?: {

2567 total_tokens: number;

2568 tool_uses: number;

2569 duration_ms: number;

2570 };

2571 uuid: UUID;

2572 session_id: string;

2573};

2574```

2575 

2576### `SDKToolUseSummaryMessage`

2577 

2578對話中工具使用的摘要。

2579 

2580```typescript theme={null}

2581type SDKToolUseSummaryMessage = {

2582 type: "tool_use_summary";

2583 summary: string;

2584 preceding_tool_use_ids: string[];

2585 uuid: UUID;

2586 session_id: string;

2587};

2588```

2589 

2590### `SDKHookStartedMessage`

2591 

2592Hook 開始執行時發出。

2593 

2594```typescript theme={null}

2595type SDKHookStartedMessage = {

2596 type: "system";

2597 subtype: "hook_started";

2598 hook_id: string;

2599 hook_name: string;

2600 hook_event: string;

2601 uuid: UUID;

2602 session_id: string;

2603};

2604```

2605 

2606### `SDKHookProgressMessage`

2607 

2608Hook 運行時發出,帶有 stdout/stderr 輸出。

2609 

2610```typescript theme={null}

2611type SDKHookProgressMessage = {

2612 type: "system";

2613 subtype: "hook_progress";

2614 hook_id: string;

2615 hook_name: string;

2616 hook_event: string;

2617 stdout: string;

2618 stderr: string;

2619 output: string;

2620 uuid: UUID;

2621 session_id: string;

2622};

2623```

2624 

2625### `SDKHookResponseMessage`

2626 

2627Hook 完成執行時發出。

2628 

2629```typescript theme={null}

2630type SDKHookResponseMessage = {

2631 type: "system";

2632 subtype: "hook_response";

2633 hook_id: string;

2634 hook_name: string;

2635 hook_event: string;

2636 output: string;

2637 stdout: string;

2638 stderr: string;

2639 exit_code?: number;

2640 outcome: "success" | "error" | "cancelled";

2641 uuid: UUID;

2642 session_id: string;

2643};

2644```

2645 

2646### `SDKToolProgressMessage`

2647 

2648工具執行時定期發出,以指示進度。

2649 

2650```typescript theme={null}

2651type SDKToolProgressMessage = {

2652 type: "tool_progress";

2653 tool_use_id: string;

2654 tool_name: string;

2655 parent_tool_use_id: string | null;

2656 elapsed_time_seconds: number;

2657 task_id?: string;

2658 uuid: UUID;

2659 session_id: string;

2660};

2661```

2662 

2663### `SDKAuthStatusMessage`

2664 

2665在身份驗證流程中發出。

2666 

2667```typescript theme={null}

2668type SDKAuthStatusMessage = {

2669 type: "auth_status";

2670 isAuthenticating: boolean;

2671 output: string[];

2672 error?: string;

2673 uuid: UUID;

2674 session_id: string;

2675};

2676```

2677 

2678### `SDKTaskStartedMessage`

2679 

2680後台任務開始時發出。`task_type` 字段是 `"local_bash"` 用於後台 Bash 命令和 [Monitor](#monitor) 監視,`"local_agent"` 用於子代理,或 `"remote_agent"`。

2681 

2682```typescript theme={null}

2683type SDKTaskStartedMessage = {

2684 type: "system";

2685 subtype: "task_started";

2686 task_id: string;

2687 tool_use_id?: string;

2688 description: string;

2689 task_type?: string;

2690 uuid: UUID;

2691 session_id: string;

2692};

2693```

2694 

2695### `SDKTaskProgressMessage`

2696 

2697後台任務運行時定期發出。

2698 

2699```typescript theme={null}

2700type SDKTaskProgressMessage = {

2701 type: "system";

2702 subtype: "task_progress";

2703 task_id: string;

2704 tool_use_id?: string;

2705 description: string;

2706 usage: {

2707 total_tokens: number;

2708 tool_uses: number;

2709 duration_ms: number;

2710 };

2711 last_tool_name?: string;

2712 uuid: UUID;

2713 session_id: string;

2714};

2715```

2716 

2717### `SDKTaskUpdatedMessage`

2718 

2719後台任務的狀態發生變化時發出,例如當它從 `running` 轉換為 `completed` 時。將 `patch` 合併到按 `task_id` 鍵入的本地任務映射中。`end_time` 字段是 Unix 紀元時間戳(以毫秒為單位),可與 `Date.now()` 比較。

2720 

2721```typescript theme={null}

2722type SDKTaskUpdatedMessage = {

2723 type: "system";

2724 subtype: "task_updated";

2725 task_id: string;

2726 patch: {

2727 status?: "pending" | "running" | "completed" | "failed" | "killed";

2728 description?: string;

2729 end_time?: number;

2730 total_paused_ms?: number;

2731 error?: string;

2732 is_backgrounded?: boolean;

2733 };

2734 uuid: UUID;

2735 session_id: string;

2736};

2737```

2738 

2739### `SDKFilesPersistedEvent`

2740 

2741文件檢查點持久化到磁盤時發出。

2742 

2743```typescript theme={null}

2744type SDKFilesPersistedEvent = {

2745 type: "system";

2746 subtype: "files_persisted";

2747 files: { filename: string; file_id: string }[];

2748 failed: { filename: string; error: string }[];

2749 processed_at: string;

2750 uuid: UUID;

2751 session_id: string;

2752};

2753```

2754 

2755### `SDKRateLimitEvent`

2756 

2757會話遇到速率限制時發出。

2758 

2759```typescript theme={null}

2760type SDKRateLimitEvent = {

2761 type: "rate_limit_event";

2762 rate_limit_info: {

2763 status: "allowed" | "allowed_warning" | "rejected";

2764 resetsAt?: number;

2765 utilization?: number;

2766 };

2767 uuid: UUID;

2768 session_id: string;

2769};

2770```

2771 

2772### `SDKLocalCommandOutputMessage`

2773 

2774本地 slash command 的輸出(例如,`/voice` 或 `/usage`)。在記錄中顯示為助手風格的文本。

2775 

2776```typescript theme={null}

2777type SDKLocalCommandOutputMessage = {

2778 type: "system";

2779 subtype: "local_command_output";

2780 content: string;

2781 uuid: UUID;

2782 session_id: string;

2783};

2784```

2785 

2786### `SDKPromptSuggestionMessage`

2787 

2788啟用 `promptSuggestions` 時在每個轉數後發出。包含預測的下一個用戶提示。

2789 

2790```typescript theme={null}

2791type SDKPromptSuggestionMessage = {

2792 type: "prompt_suggestion";

2793 suggestion: string;

2794 uuid: UUID;

2795 session_id: string;

2796};

2797```

2798 

2799### `AbortError`

2800 

2801中止操作的自定義錯誤類。

2802 

2803```typescript theme={null}

2804class AbortError extends Error {}

2805```

2806 

2807## 沙箱配置

2808 

2809### `SandboxSettings`

2810 

2811沙箱行為的配置。使用此選項以編程方式啟用命令沙箱和配置網絡限制。

2812 

2813```typescript theme={null}

2814type SandboxSettings = {

2815 enabled?: boolean;

2816 autoAllowBashIfSandboxed?: boolean;

2817 excludedCommands?: string[];

2818 allowUnsandboxedCommands?: boolean;

2819 network?: SandboxNetworkConfig;

2820 filesystem?: SandboxFilesystemConfig;

2821 ignoreViolations?: Record<string, string[]>;

2822 enableWeakerNestedSandbox?: boolean;

2823 ripgrep?: { command: string; args?: string[] };

2824};

2825```

2826 

2827| 屬性 | 類型 | 默認值 | 描述 |

2828| :-------------------------- | :------------------------------------------------------ | :---------- | :------------------------------------------------------------------------------------------------------------------------------- |

2829| `enabled` | `boolean` | `false` | 為命令執行啟用沙箱模式 |

2830| `autoAllowBashIfSandboxed` | `boolean` | `true` | 啟用沙箱時自動批准 bash 命令 |

2831| `excludedCommands` | `string[]` | `[]` | 始終繞過沙箱限制的命令(例如,`['docker']`)。這些自動運行在沙箱外,無需模型參與 |

2832| `allowUnsandboxedCommands` | `boolean` | `true` | 允許模型請求在沙箱外運行命令。當為 `true` 時,模型可以在工具輸入中設置 `dangerouslyDisableSandbox`,這會回退到 [權限系統](#permissions-fallback-for-unsandboxed-commands) |

2833| `network` | [`SandboxNetworkConfig`](#sandbox-network-config) | `undefined` | 網絡特定的沙箱配置 |

2834| `filesystem` | [`SandboxFilesystemConfig`](#sandbox-filesystem-config) | `undefined` | 文件系統特定的沙箱配置,用於讀/寫限制 |

2835| `ignoreViolations` | `Record<string, string[]>` | `undefined` | 違規類別到要忽略的模式的映射(例如,`{ file: ['/tmp/*'], network: ['localhost'] }`) |

2836| `enableWeakerNestedSandbox` | `boolean` | `false` | 為兼容性啟用較弱的嵌套沙箱 |

2837| `ripgrep` | `{ command: string; args?: string[] }` | `undefined` | 沙箱環境中的自定義 ripgrep 二進制配置 |

2838 

2839#### 示例用法

2840 

2841```typescript theme={null}

2842import { query } from "@anthropic-ai/claude-agent-sdk";

2843 

2844for await (const message of query({

2845 prompt: "Build and test my project",

2846 options: {

2847 sandbox: {

2848 enabled: true,

2849 autoAllowBashIfSandboxed: true,

2850 network: {

2851 allowLocalBinding: true

2852 }

2853 }

2854 }

2855})) {

2856 if ("result" in message) console.log(message.result);

2857}

2858```

2859 

2860<Warning>

2861 **Unix socket 安全性:** `allowUnixSockets` 選項可以授予對強大系統服務的訪問權限。例如,允許 `/var/run/docker.sock` 實際上通過 Docker API 授予對主機系統的完全訪問權限,繞過沙箱隔離。僅允許絕對必要的 Unix sockets 並了解每個的安全含義。

2862</Warning>

2863 

2864### `SandboxNetworkConfig`

2865 

2866沙箱模式的網絡特定配置。

2867 

2868```typescript theme={null}

2869type SandboxNetworkConfig = {

2870 allowedDomains?: string[];

2871 deniedDomains?: string[];

2872 allowManagedDomainsOnly?: boolean;

2873 allowLocalBinding?: boolean;

2874 allowUnixSockets?: string[];

2875 allowAllUnixSockets?: boolean;

2876 httpProxyPort?: number;

2877 socksProxyPort?: number;

2878};

2879```

2880 

2881| 屬性 | 類型 | 默認值 | 描述 |

2882| :------------------------ | :--------- | :---------- | :--------------------------------------- |

2883| `allowedDomains` | `string[]` | `[]` | 沙箱進程可以訪問的域名 |

2884| `deniedDomains` | `string[]` | `[]` | 沙箱進程無法訪問的域名。優先於 `allowedDomains` |

2885| `allowManagedDomainsOnly` | `boolean` | `false` | 將網絡訪問限制為僅 `allowedDomains` 中的域 |

2886| `allowLocalBinding` | `boolean` | `false` | 允許進程綁定到本地端口(例如,用於開發服務器) |

2887| `allowUnixSockets` | `string[]` | `[]` | 進程可以訪問的 Unix socket 路徑(例如,Docker socket) |

2888| `allowAllUnixSockets` | `boolean` | `false` | 允許訪問所有 Unix sockets |

2889| `httpProxyPort` | `number` | `undefined` | 網絡請求的 HTTP 代理端口 |

2890| `socksProxyPort` | `number` | `undefined` | 網絡請求的 SOCKS 代理端口 |

2891 

2892<Note>

2893 內置沙箱代理根據請求的主機名強制執行 `allowedDomains`,並且不終止或檢查 TLS 流量,因此 [域前置](https://en.wikipedia.org/wiki/Domain_fronting) 等技術可能會繞過它。有關詳細信息,請參閱 [沙箱安全限制](/zh-TW/sandboxing#security-limitations),以及 [安全部署](/zh-TW/agent-sdk/secure-deployment#traffic-forwarding) 以配置 TLS 終止代理。

2894</Note>

2895 

2896### `SandboxFilesystemConfig`

2897 

2898沙箱模式的文件系統特定配置。

2899 

2900```typescript theme={null}

2901type SandboxFilesystemConfig = {

2902 allowWrite?: string[];

2903 denyWrite?: string[];

2904 denyRead?: string[];

2905};

2906```

2907 

2908| 屬性 | 類型 | 默認值 | 描述 |

2909| :----------- | :--------- | :--- | :------------ |

2910| `allowWrite` | `string[]` | `[]` | 允許寫入訪問的文件路徑模式 |

2911| `denyWrite` | `string[]` | `[]` | 拒絕寫入訪問的文件路徑模式 |

2912| `denyRead` | `string[]` | `[]` | 拒絕讀取訪問的文件路徑模式 |

2913 

2914### 無沙箱命令的權限回退

2915 

2916啟用 `allowUnsandboxedCommands` 時,模型可以通過在工具輸入中設置 `dangerouslyDisableSandbox: true` 來請求在沙箱外運行命令。這些請求回退到現有的權限系統,意味著您的 `canUseTool` 處理程序被調用,允許您實現自定義授權邏輯。

2917 

2918<Note>

2919 **`excludedCommands` vs `allowUnsandboxedCommands`:**

2920 

2921 * `excludedCommands`:始終自動繞過沙箱的命令的靜態列表(例如,`['docker']`)。模型對此無控制。

2922 * `allowUnsandboxedCommands`:讓模型在運行時通過在工具輸入中設置 `dangerouslyDisableSandbox: true` 來決定是否請求無沙箱執行。

2923</Note>

2924 

2925```typescript theme={null}

2926import { query } from "@anthropic-ai/claude-agent-sdk";

2927 

2928for await (const message of query({

2929 prompt: "Deploy my application",

2930 options: {

2931 sandbox: {

2932 enabled: true,

2933 allowUnsandboxedCommands: true // 模型可以請求無沙箱執行

2934 },

2935 permissionMode: "default",

2936 canUseTool: async (tool, input) => {

2937 // 檢查模型是否請求繞過沙箱

2938 if (tool === "Bash" && input.dangerouslyDisableSandbox) {

2939 // 模型請求在沙箱外運行此命令

2940 console.log(`Unsandboxed command requested: ${input.command}`);

2941 

2942 if (isCommandAuthorized(input.command)) {

2943 return { behavior: "allow" as const, updatedInput: input };

2944 }

2945 return {

2946 behavior: "deny" as const,

2947 message: "Command not authorized for unsandboxed execution"

2948 };

2949 }

2950 return { behavior: "allow" as const, updatedInput: input };

2951 }

2952 }

2953})) {

2954 if ("result" in message) console.log(message.result);

2955}

2956```

2957 

2958此模式使您能夠:

2959 

2960* **審計模型請求:** 記錄模型何時請求無沙箱執行

2961* **實現允許列表:** 僅允許特定命令在沙箱外運行

2962* **添加批准工作流:** 需要對特權操作進行明確授權

2963 

2964<Warning>

2965 使用 `dangerouslyDisableSandbox: true` 運行的命令具有完整的系統訪問權限。確保您的 `canUseTool` 處理程序仔細驗證這些請求。

2966 

2967 如果 `permissionMode` 設置為 `bypassPermissions` 且 `allowUnsandboxedCommands` 啟用,模型可以自主執行沙箱外的命令,無需任何批准提示。此組合實際上允許模型無聲地逃離沙箱隔離。

2968</Warning>

2969 

2970## 另見

2971 

2972* [SDK 概述](/zh-TW/agent-sdk/overview) - 常規 SDK 概念

2973* [Python SDK 參考](/zh-TW/agent-sdk/python) - Python SDK 文檔

2974* [CLI 參考](/zh-TW/cli-reference) - 命令行介面

2975* [常見工作流](/zh-TW/common-workflows) - 分步指南

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# TypeScript SDK V2 介面(預覽)

6 

7> 簡化的 V2 TypeScript Agent SDK 預覽,具有用於多輪對話的基於會話的 send/stream 模式。

8 

9<Warning>

10 V2 介面是一個**不穩定的預覽版本**。API 可能會根據反饋進行更改,然後才能變成穩定版本。某些功能(如會話分叉)僅在 [V1 SDK](/zh-TW/agent-sdk/typescript) 中可用。

11</Warning>

12 

13V2 Claude Agent TypeScript SDK 消除了對非同步生成器和 yield 協調的需求。這使多輪對話變得更簡單,而不是在各輪之間管理生成器狀態,每一輪都是一個單獨的 `send()`/`stream()` 週期。API 表面縮減為三個概念:

14 

15* `createSession()` / `resumeSession()`:開始或繼續對話

16* `session.send()`:發送訊息

17* `session.stream()`:取得回應

18 

19## 安裝

20 

21V2 介面包含在現有的 SDK 套件中:

22 

23```bash theme={null}

24npm install @anthropic-ai/claude-agent-sdk

25```

26 

27<Note>

28 SDK 為您的平台捆綁了一個原生 Claude Code 二進位檔案作為可選依賴項,因此您無需單獨安裝 Claude Code。

29</Note>

30 

31## 快速開始

32 

33### 單次提示

34 

35對於不需要維護會話的簡單單輪查詢,請使用 `unstable_v2_prompt()`。此範例發送一個數學問題並記錄答案:

36 

37```typescript theme={null}

38import { unstable_v2_prompt } from "@anthropic-ai/claude-agent-sdk";

39 

40const result = await unstable_v2_prompt("What is 2 + 2?", {

41 model: "claude-opus-4-7"

42});

43if (result.subtype === "success") {

44 console.log(result.result);

45}

46```

47 

48<details>

49 <summary>查看 V1 中的相同操作</summary>

50 

51 ```typescript theme={null}

52 import { query } from "@anthropic-ai/claude-agent-sdk";

53 

54 const q = query({

55 prompt: "What is 2 + 2?",

56 options: { model: "claude-opus-4-7" }

57 });

58 

59 for await (const msg of q) {

60 if (msg.type === "result" && msg.subtype === "success") {

61 console.log(msg.result);

62 }

63 }

64 ```

65</details>

66 

67### 基本會話

68 

69對於超出單個提示的互動,請建立一個會話。V2 將發送和串流分為不同的步驟:

70 

71* `send()` 分派您的訊息

72* `stream()` 串流回應

73 

74這種明確的分離使得在輪次之間添加邏輯變得更容易(例如在發送後續訊息之前處理回應)。

75 

76下面的範例建立一個會話,向 Claude 發送「Hello!」,並列印文字回應。它使用 [`await using`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management)(TypeScript 5.2+)在區塊退出時自動關閉會話。您也可以手動呼叫 `session.close()`。

77 

78```typescript theme={null}

79import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";

80 

81await using session = unstable_v2_createSession({

82 model: "claude-opus-4-7"

83});

84 

85await session.send("Hello!");

86for await (const msg of session.stream()) {

87 // Filter for assistant messages to get human-readable output

88 if (msg.type === "assistant") {

89 const text = msg.message.content

90 .filter((block) => block.type === "text")

91 .map((block) => block.text)

92 .join("");

93 console.log(text);

94 }

95}

96```

97 

98<details>

99 <summary>查看 V1 中的相同操作</summary>

100 

101 在 V1 中,輸入和輸出都通過單個非同步生成器流動。對於基本提示,這看起來很相似,但添加多輪邏輯需要重新構造以使用輸入生成器。

102 

103 ```typescript theme={null}

104 import { query } from "@anthropic-ai/claude-agent-sdk";

105 

106 const q = query({

107 prompt: "Hello!",

108 options: { model: "claude-opus-4-7" }

109 });

110 

111 for await (const msg of q) {

112 if (msg.type === "assistant") {

113 const text = msg.message.content

114 .filter((block) => block.type === "text")

115 .map((block) => block.text)

116 .join("");

117 console.log(text);

118 }

119 }

120 ```

121</details>

122 

123### 多輪對話

124 

125會話在多次交換中保持上下文。要繼續對話,請在同一會話上再次呼叫 `send()`。Claude 會記住之前的輪次。

126 

127此範例詢問一個數學問題,然後詢問一個引用先前答案的後續問題:

128 

129```typescript theme={null}

130import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";

131 

132await using session = unstable_v2_createSession({

133 model: "claude-opus-4-7"

134});

135 

136// Turn 1

137await session.send("What is 5 + 3?");

138for await (const msg of session.stream()) {

139 // Filter for assistant messages to get human-readable output

140 if (msg.type === "assistant") {

141 const text = msg.message.content

142 .filter((block) => block.type === "text")

143 .map((block) => block.text)

144 .join("");

145 console.log(text);

146 }

147}

148 

149// Turn 2

150await session.send("Multiply that by 2");

151for await (const msg of session.stream()) {

152 if (msg.type === "assistant") {

153 const text = msg.message.content

154 .filter((block) => block.type === "text")

155 .map((block) => block.text)

156 .join("");

157 console.log(text);

158 }

159}

160```

161 

162<details>

163 <summary>查看 V1 中的相同操作</summary>

164 

165 ```typescript theme={null}

166 import { query } from "@anthropic-ai/claude-agent-sdk";

167 

168 // Must create an async iterable to feed messages

169 async function* createInputStream() {

170 yield {

171 type: "user",

172 session_id: "",

173 message: { role: "user", content: [{ type: "text", text: "What is 5 + 3?" }] },

174 parent_tool_use_id: null

175 };

176 // Must coordinate when to yield next message

177 yield {

178 type: "user",

179 session_id: "",

180 message: { role: "user", content: [{ type: "text", text: "Multiply by 2" }] },

181 parent_tool_use_id: null

182 };

183 }

184 

185 const q = query({

186 prompt: createInputStream(),

187 options: { model: "claude-opus-4-7" }

188 });

189 

190 for await (const msg of q) {

191 if (msg.type === "assistant") {

192 const text = msg.message.content

193 .filter((block) => block.type === "text")

194 .map((block) => block.text)

195 .join("");

196 console.log(text);

197 }

198 }

199 ```

200</details>

201 

202### 會話恢復

203 

204如果您有來自先前互動的會話 ID,您可以稍後恢復它。這對於長時間運行的工作流程或當您需要在應用程式重新啟動時保持對話時很有用。

205 

206此範例建立一個會話,儲存其 ID,關閉它,然後恢復對話:

207 

208```typescript theme={null}

209import {

210 unstable_v2_createSession,

211 unstable_v2_resumeSession,

212 type SDKMessage

213} from "@anthropic-ai/claude-agent-sdk";

214 

215// Helper to extract text from assistant messages

216function getAssistantText(msg: SDKMessage): string | null {

217 if (msg.type !== "assistant") return null;

218 return msg.message.content

219 .filter((block) => block.type === "text")

220 .map((block) => block.text)

221 .join("");

222}

223 

224// Create initial session and have a conversation

225const session = unstable_v2_createSession({

226 model: "claude-opus-4-7"

227});

228 

229await session.send("Remember this number: 42");

230 

231// Get the session ID from any received message

232let sessionId: string | undefined;

233for await (const msg of session.stream()) {

234 sessionId = msg.session_id;

235 const text = getAssistantText(msg);

236 if (text) console.log("Initial response:", text);

237}

238 

239console.log("Session ID:", sessionId);

240session.close();

241 

242// Later: resume the session using the stored ID

243await using resumedSession = unstable_v2_resumeSession(sessionId!, {

244 model: "claude-opus-4-7"

245});

246 

247await resumedSession.send("What number did I ask you to remember?");

248for await (const msg of resumedSession.stream()) {

249 const text = getAssistantText(msg);

250 if (text) console.log("Resumed response:", text);

251}

252```

253 

254<details>

255 <summary>查看 V1 中的相同操作</summary>

256 

257 ```typescript theme={null}

258 import { query } from "@anthropic-ai/claude-agent-sdk";

259 

260 // Create initial session

261 const initialQuery = query({

262 prompt: "Remember this number: 42",

263 options: { model: "claude-opus-4-7" }

264 });

265 

266 // Get session ID from any message

267 let sessionId: string | undefined;

268 for await (const msg of initialQuery) {

269 sessionId = msg.session_id;

270 if (msg.type === "assistant") {

271 const text = msg.message.content

272 .filter((block) => block.type === "text")

273 .map((block) => block.text)

274 .join("");

275 console.log("Initial response:", text);

276 }

277 }

278 

279 console.log("Session ID:", sessionId);

280 

281 // Later: resume the session

282 const resumedQuery = query({

283 prompt: "What number did I ask you to remember?",

284 options: {

285 model: "claude-opus-4-7",

286 resume: sessionId

287 }

288 });

289 

290 for await (const msg of resumedQuery) {

291 if (msg.type === "assistant") {

292 const text = msg.message.content

293 .filter((block) => block.type === "text")

294 .map((block) => block.text)

295 .join("");

296 console.log("Resumed response:", text);

297 }

298 }

299 ```

300</details>

301 

302### 清理

303 

304會話可以手動關閉或使用 [`await using`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management)(TypeScript 5.2+ 功能用於自動資源清理)自動關閉。如果您使用的是較舊的 TypeScript 版本或遇到相容性問題,請改用手動清理。

305 

306**自動清理(TypeScript 5.2+):**

307 

308```typescript theme={null}

309import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";

310 

311await using session = unstable_v2_createSession({

312 model: "claude-opus-4-7"

313});

314// Session closes automatically when the block exits

315```

316 

317**手動清理:**

318 

319```typescript theme={null}

320import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";

321 

322const session = unstable_v2_createSession({

323 model: "claude-opus-4-7"

324});

325// ... use the session ...

326session.close();

327```

328 

329## API 參考

330 

331### `unstable_v2_createSession()`

332 

333為多輪對話建立新會話。

334 

335```typescript theme={null}

336function unstable_v2_createSession(options: {

337 model: string;

338 // Additional options supported

339}): SDKSession;

340```

341 

342### `unstable_v2_resumeSession()`

343 

344按 ID 恢復現有會話。

345 

346```typescript theme={null}

347function unstable_v2_resumeSession(

348 sessionId: string,

349 options: {

350 model: string;

351 // Additional options supported

352 }

353): SDKSession;

354```

355 

356### `unstable_v2_prompt()`

357 

358用於單輪查詢的單次便利函數。

359 

360```typescript theme={null}

361function unstable_v2_prompt(

362 prompt: string,

363 options: {

364 model: string;

365 // Additional options supported

366 }

367): Promise<SDKResultMessage>;

368```

369 

370### SDKSession 介面

371 

372```typescript theme={null}

373interface SDKSession {

374 readonly sessionId: string;

375 send(message: string | SDKUserMessage): Promise<void>;

376 stream(): AsyncGenerator<SDKMessage, void>;

377 close(): void;

378}

379```

380 

381## 功能可用性

382 

383並非所有 V1 功能在 V2 中都可用。以下功能需要使用 [V1 SDK](/zh-TW/agent-sdk/typescript):

384 

385* 會話分叉(`forkSession` 選項)

386* 某些進階串流輸入模式

387 

388## 反饋

389 

390在 V2 介面變成穩定版本之前分享您的反饋。通過 [GitHub Issues](https://github.com/anthropics/claude-code/issues) 報告問題和建議。

391 

392## 另請參閱

393 

394* [TypeScript SDK 參考(V1)](/zh-TW/agent-sdk/typescript) - 完整的 V1 SDK 文件

395* [SDK 概述](/zh-TW/agent-sdk/overview) - 一般 SDK 概念

396* [GitHub 上的 V2 範例](https://github.com/anthropics/claude-agent-sdk-demos/tree/main/hello-world-v2) - 工作程式碼範例

agent-teams.md +424 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 協調 Claude Code 工作階段團隊

6 

7> 協調多個 Claude Code 實例作為團隊一起工作,具有共享任務、代理間訊息傳遞和集中管理。

8 

9<Warning>

10 Agent teams 是實驗性功能,預設為停用。透過在 [settings.json](/zh-TW/settings) 或環境中新增 `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` 來啟用。Agent teams 在工作階段恢復、任務協調和關閉行為方面有[已知限制](#limitations)。

11</Warning>

12 

13Agent teams 讓您協調多個 Claude Code 實例一起工作。一個工作階段充當團隊主管,協調工作、分配任務並綜合結果。隊友獨立工作,各自在自己的 context window 中,並直接相互溝通。

14 

15與 [subagents](/zh-TW/sub-agents) 不同,subagents 在單個工作階段內運行,只能向主代理報告,您也可以直接與個別隊友互動,無需透過主管。

16 

17<Note>

18 Agent teams 需要 Claude Code v2.1.32 或更新版本。使用 `claude --version` 檢查您的版本。

19</Note>

20 

21本頁涵蓋:

22 

23* [何時使用 agent teams](#when-to-use-agent-teams),包括最佳使用案例以及與 subagents 的比較

24* [啟動您的第一個 agent team](#start-your-first-agent-team)

25* [控制您的 agent team](#control-your-agent-team),包括顯示模式、任務分配和委派

26* [並行工作的最佳實踐](#best-practices)

27 

28## 何時使用 agent teams

29 

30Agent teams 最適合用於並行探索能增加真實價值的任務。請參閱[使用案例範例](#use-case-examples)以了解完整情景。最強的使用案例是:

31 

32* **研究和審查**:多個隊友可以同時調查問題的不同方面,然後分享並質疑彼此的發現

33* **新模組或功能**:隊友可以各自擁有一個獨立部分,不會相互干擾

34* **使用競爭假設進行除錯**:隊友並行測試不同的理論,更快地收斂到答案

35* **跨層協調**:跨越前端、後端和測試的變更,各由不同的隊友負責

36 

37Agent teams 增加了協調開銷,並使用的 tokens 遠多於單個工作階段。當隊友可以獨立運作時,它們效果最佳。對於順序任務、相同檔案編輯或具有許多依賴關係的工作,單個工作階段或 [subagents](/zh-TW/sub-agents) 更有效。

38 

39### 與 subagents 比較

40 

41Agent teams 和 [subagents](/zh-TW/sub-agents) 都讓您並行化工作,但它們的運作方式不同。根據您的工作人員是否需要相互溝通來選擇:

42 

43<Frame caption="Subagents 只向主代理報告結果,彼此不交談。在 agent teams 中,隊友共享任務列表、認領工作並直接相互溝通。">

44 <img src="https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-light.png?fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=2f8db9b4f3705dd3ab931fbe2d96e42a" className="dark:hidden" alt="比較 subagent 和 agent team 架構的圖表。Subagents 由主代理生成、執行工作並報告結果。Agent teams 透過共享任務列表進行協調,隊友彼此直接溝通。" width="4245" height="1615" data-path="images/subagents-vs-agent-teams-light.png" />

45 

46 <img src="https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-dark.png?fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=d573a037540f2ada6a9ae7d8285b46fd" className="hidden dark:block" alt="比較 subagent 和 agent team 架構的圖表。Subagents 由主代理生成、執行工作並報告結果。Agent teams 透過共享任務列表進行協調,隊友彼此直接溝通。" width="4245" height="1615" data-path="images/subagents-vs-agent-teams-dark.png" />

47</Frame>

48 

49| | Subagents | Agent teams |

50| :----------- | :-------------------------- | :---------------------- |

51| **Context** | 自己的 context window;結果返回給呼叫者 | 自己的 context window;完全獨立 |

52| **溝通** | 只向主代理報告結果 | 隊友直接相互訊息傳遞 |

53| **協調** | 主代理管理所有工作 | 具有自我協調的共享任務列表 |

54| **最適合** | 只有結果重要的專注任務 | 需要討論和協作的複雜工作 |

55| **Token 成本** | 較低:結果摘要返回到主 context | 較高:每個隊友是一個獨立的 Claude 實例 |

56 

57當您需要快速、專注的工作人員報告結果時,使用 subagents。當隊友需要分享發現、相互質疑並自行協調時,使用 agent teams。

58 

59## 啟用 agent teams

60 

61Agent teams 預設為停用。透過將 `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` 環境變數設定為 `1`,在您的 shell 環境或透過 [settings.json](/zh-TW/settings) 來啟用:

62 

63```json settings.json theme={null}

64{

65 "env": {

66 "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"

67 }

68}

69```

70 

71## 啟動您的第一個 agent team

72 

73啟用 agent teams 後,告訴 Claude 建立一個 agent team 並用自然語言描述您想要的任務和團隊結構。Claude 建立團隊、生成隊友並根據您的提示協調工作。

74 

75此範例效果很好,因為三個角色是獨立的,可以在不相互等待的情況下探索問題:

76 

77```text theme={null}

78I'm designing a CLI tool that helps developers track TODO comments across

79their codebase. Create an agent team to explore this from different angles: one

80teammate on UX, one on technical architecture, one playing devil's advocate.

81```

82 

83從那裡,Claude 建立一個具有[共享任務列表](/zh-TW/interactive-mode#task-list)的團隊,為每個觀點生成隊友,讓他們探索問題,綜合發現,並嘗試在完成時[清理團隊](#clean-up-the-team)。

84 

85主管的終端列出所有隊友及其正在進行的工作。使用 Shift+Down 循環瀏覽隊友並直接向他們傳送訊息。在最後一個隊友之後,Shift+Down 會回到主管。

86 

87如果您希望每個隊友都在自己的分割窗格中,請參閱[選擇顯示模式](#choose-a-display-mode)。

88 

89## 控制您的 agent team

90 

91用自然語言告訴主管您想要什麼。它根據您的指示處理團隊協調、任務分配和委派。

92 

93### 選擇顯示模式

94 

95Agent teams 支援兩種顯示模式:

96 

97* **In-process**:所有隊友在您的主終端內運行。使用 Shift+Down 循環瀏覽隊友並輸入以直接向他們傳送訊息。在任何終端中工作,無需額外設定。

98* **Split panes**:每個隊友都有自己的窗格。您可以同時看到所有人的輸出並點擊窗格直接互動。需要 tmux 或 iTerm2。

99 

100<Note>

101 `tmux` 在某些作業系統上有已知限制,傳統上在 macOS 上效果最佳。在 iTerm2 中使用 `tmux -CC` 是進入 `tmux` 的建議入口點。

102</Note>

103 

104預設值是 `"auto"`,如果您已在 tmux 工作階段內運行,則使用分割窗格,否則使用 in-process。`"tmux"` 設定啟用分割窗格模式,並根據您的終端自動偵測是否使用 tmux 或 iTerm2。若要覆蓋,請在 `~/.claude/settings.json` 中設定 [`teammateMode`](/zh-TW/settings#available-settings):

105 

106```json theme={null}

107{

108 "teammateMode": "in-process"

109}

110```

111 

112若要為單個工作階段強制 in-process 模式,請將其作為旗標傳遞:

113 

114```bash theme={null}

115claude --teammate-mode in-process

116```

117 

118分割窗格模式需要 [tmux](https://github.com/tmux/tmux/wiki) 或 iTerm2 搭配 [`it2` CLI](https://github.com/mkusaka/it2)。若要手動安裝:

119 

120* **tmux**:透過您系統的套件管理器安裝。請參閱 [tmux wiki](https://github.com/tmux/tmux/wiki/Installing) 以了解平台特定的指示。

121* **iTerm2**:安裝 [`it2` CLI](https://github.com/mkusaka/it2),然後在 **iTerm2 → Settings → General → Magic → Enable Python API** 中啟用 Python API。

122 

123### 指定隊友和模型

124 

125Claude 根據您的任務決定要生成的隊友數量,或者您可以指定您想要的確切內容:

126 

127```text theme={null}

128Create a team with 4 teammates to refactor these modules in parallel.

129Use Sonnet for each teammate.

130```

131 

132### 要求隊友的計畫批准

133 

134對於複雜或有風險的任務,您可以要求隊友在實施前進行計畫。隊友在唯讀計畫模式下工作,直到主管批准其方法:

135 

136```text theme={null}

137Spawn an architect teammate to refactor the authentication module.

138Require plan approval before they make any changes.

139```

140 

141當隊友完成計畫時,它會向主管發送計畫批准請求。主管審查計畫並批准或拒絕並提供反饋。如果被拒絕,隊友保持在計畫模式,根據反饋進行修訂並重新提交。一旦批准,隊友退出計畫模式並開始實施。

142 

143主管自主做出批准決定。若要影響主管的判斷,在您的提示中提供標準,例如「只批准包含測試覆蓋的計畫」或「拒絕修改資料庫架構的計畫」。

144 

145### 直接與隊友交談

146 

147每個隊友都是一個完整、獨立的 Claude Code 工作階段。您可以直接向任何隊友傳送訊息,以提供額外指示、提出後續問題或重新定向其方法。

148 

149* **In-process 模式**:使用 Shift+Down 循環瀏覽隊友,然後輸入以向他們傳送訊息。按 Enter 查看隊友的工作階段,然後按 Escape 中斷其目前回合。按 Ctrl+T 切換任務列表。

150* **Split-pane 模式**:點擊隊友的窗格以直接與其工作階段互動。每個隊友都有自己終端的完整檢視。

151 

152### 分配和認領任務

153 

154共享任務列表協調整個團隊的工作。主管建立任務,隊友完成它們。任務有三種狀態:待處理、進行中和已完成。任務也可以依賴其他任務:具有未解決依賴關係的待處理任務在這些依賴關係完成之前無法被認領。

155 

156主管可以明確分配任務,或隊友可以自行認領:

157 

158* **主管分配**:告訴主管將哪個任務分配給哪個隊友

159* **自行認領**:完成任務後,隊友自行選擇下一個未分配、未阻止的任務

160 

161任務認領使用檔案鎖定來防止多個隊友同時嘗試認領同一任務時的競爭條件。

162 

163### 關閉隊友

164 

165若要優雅地結束隊友的工作階段:

166 

167```text theme={null}

168Ask the researcher teammate to shut down

169```

170 

171主管發送關閉請求。隊友可以批准並優雅地退出,或拒絕並提供解釋。

172 

173### 清理團隊

174 

175完成後,要求主管清理:

176 

177```text theme={null}

178Clean up the team

179```

180 

181這會移除共享的團隊資源。當主管運行清理時,它會檢查活躍的隊友,如果仍有任何隊友在運行,則失敗,因此請先關閉他們。

182 

183<Warning>

184 始終使用主管進行清理。隊友不應運行清理,因為他們的團隊 context 可能無法正確解析,可能會使資源處於不一致的狀態。

185</Warning>

186 

187### 使用 hooks 強制執行品質閘門

188 

189使用 [hooks](/zh-TW/hooks) 在隊友完成工作或任務建立或完成時強制執行規則:

190 

191* [`TeammateIdle`](/zh-TW/hooks#teammateidle):當隊友即將閒置時運行。以代碼 2 退出以發送反饋並保持隊友工作。

192* [`TaskCreated`](/zh-TW/hooks#taskcreated):當任務正在建立時運行。以代碼 2 退出以防止建立並發送反饋。

193* [`TaskCompleted`](/zh-TW/hooks#taskcompleted):當任務被標記為完成時運行。以代碼 2 退出以防止完成並發送反饋。

194 

195## Agent teams 如何工作

196 

197本節涵蓋 agent teams 背後的架構和機制。如果您想開始使用它們,請參閱上面的[控制您的 agent team](#control-your-agent-team)。

198 

199### Claude 如何啟動 agent teams

200 

201Agent teams 有兩種啟動方式:

202 

203* **您請求一個團隊**:給 Claude 一個受益於並行工作的任務,並明確要求一個 agent team。Claude 根據您的指示建立一個。

204* **Claude 提議一個團隊**:如果 Claude 確定您的任務將受益於並行工作,它可能會建議建立一個團隊。您在它繼續之前確認。

205 

206在這兩種情況下,您都保持控制。Claude 不會在沒有您批准的情況下建立團隊。

207 

208### 架構

209 

210Agent team 由以下部分組成:

211 

212| 元件 | 角色 |

213| :------------ | :--------------------------------- |

214| **Team lead** | 建立團隊、生成隊友並協調工作的主要 Claude Code 工作階段 |

215| **Teammates** | 各自處理分配任務的獨立 Claude Code 實例 |

216| **Task list** | 隊友認領和完成的共享工作項目列表 |

217| **Mailbox** | 代理之間通訊的訊息系統 |

218 

219請參閱[選擇顯示模式](#choose-a-display-mode)以了解顯示配置選項。隊友訊息自動到達主管。

220 

221系統自動管理任務依賴關係。當隊友完成其他任務依賴的任務時,被阻止的任務會自動解除阻止。

222 

223團隊和任務存儲在本地:

224 

225* **Team config**:`~/.claude/teams/{team-name}/config.json`

226* **Task list**:`~/.claude/tasks/{team-name}/`

227 

228Claude Code 在您建立團隊時自動生成這兩者,並在隊友加入、閒置或離開時更新它們。團隊配置保存運行時狀態,例如工作階段 ID 和 tmux 窗格 ID,因此不要手動編輯或預先編寫它:您的變更會在下次狀態更新時被覆蓋。

229 

230若要定義可重複使用的隊友角色,請改用 [subagent 定義](#use-subagent-definitions-for-teammates)。

231 

232團隊配置包含一個 `members` 陣列,其中包含每個隊友的名稱、代理 ID 和代理類型。隊友可以讀取此檔案以發現其他團隊成員。

233 

234沒有專案級別的團隊配置等效項。您專案目錄中的 `.claude/teams/teams.json` 之類的檔案不被識別為配置;Claude 將其視為普通檔案。

235 

236### 為隊友使用 subagent 定義

237 

238生成隊友時,您可以參考來自任何 [subagent 範圍](/zh-TW/sub-agents#choose-the-subagent-scope)的 [subagent](/zh-TW/sub-agents) 類型:專案、使用者、plugin 或 CLI 定義。這讓您定義一個角色一次,例如安全審查者或測試執行者,並將其同時重複使用為委派的 subagent 和 agent team 隊友。

239 

240若要使用 subagent 定義,在要求 Claude 生成隊友時按名稱提及它:

241 

242```text theme={null}

243Spawn a teammate using the security-reviewer agent type to audit the auth module.

244```

245 

246隊友遵守該定義的 `tools` 允許清單和 `model`,並且定義的主體會附加到隊友的系統提示中作為額外指示,而不是替換它。Team coordination tools 例如 `SendMessage` 和任務管理工具始終對隊友可用,即使 `tools` 限制其他工具。

247 

248<Note>

249 Subagent 定義中的 `skills` 和 `mcpServers` frontmatter 欄位在該定義作為隊友運行時不適用。隊友從您的專案和使用者設定中載入 skills 和 MCP servers,與常規工作階段相同。

250</Note>

251 

252### 權限

253 

254隊友開始時具有主管的權限設定。如果主管使用 `--dangerously-skip-permissions` 運行,所有隊友也會這樣做。生成後,您可以更改個別隊友模式,但在生成時無法設定每個隊友的模式。

255 

256### Context 和通訊

257 

258每個隊友都有自己的 context window。生成時,隊友載入與常規工作階段相同的專案 context:CLAUDE.md、MCP servers 和 skills。它還接收來自主管的生成提示。主管的對話歷史不會延續。

259 

260**隊友如何分享資訊:**

261 

262* **自動訊息傳遞**:當隊友發送訊息時,它們會自動傳遞給收件人。主管不需要輪詢更新。

263* **閒置通知**:當隊友完成並停止時,他們會自動通知主管。

264* **共享任務列表**:所有代理都可以看到任務狀態並認領可用工作。

265* **隊友訊息傳遞**:按名稱向一個特定隊友發送訊息。若要聯繫所有人,請為每個收件人發送一條訊息。

266 

267主管在生成隊友時為其分配名稱,任何隊友都可以按該名稱向任何其他隊友傳送訊息。若要獲得可在稍後提示中參考的可預測名稱,請在您的生成指示中告訴主管如何稱呼每個隊友。

268 

269### Token 使用

270 

271Agent teams 使用的 tokens 遠多於單個工作階段。每個隊友都有自己的 context window,token 使用量隨活躍隊友數量而增加。對於研究、審查和新功能工作,額外的 tokens 通常是值得的。對於日常任務,單個工作階段更具成本效益。請參閱 [agent team token 成本](/zh-TW/costs#agent-team-token-costs)以了解使用指南。

272 

273## 使用案例範例

274 

275這些範例展示了 agent teams 如何處理並行探索增加價值的任務。

276 

277### 運行並行程式碼審查

278 

279單個審查者傾向於一次專注於一種類型的問題。將審查標準分成獨立領域意味著安全性、效能和測試覆蓋都同時獲得徹底的關注。提示為每個隊友分配一個不同的視角,以便他們不重疊:

280 

281```text theme={null}

282Create an agent team to review PR #142. Spawn three reviewers:

283- One focused on security implications

284- One checking performance impact

285- One validating test coverage

286Have them each review and report findings.

287```

288 

289每個審查者從相同的 PR 工作,但應用不同的篩選器。主管在他們完成後綜合所有三個的發現。

290 

291### 使用競爭假設進行調查

292 

293當根本原因不清楚時,單個代理傾向於找到一個看似合理的解釋並停止尋找。提示透過使隊友明確對抗來對抗這一點:每個隊友的工作不僅是調查自己的理論,還要質疑其他隊友的理論。

294 

295```text theme={null}

296Users report the app exits after one message instead of staying connected.

297Spawn 5 agent teammates to investigate different hypotheses. Have them talk to

298each other to try to disprove each other's theories, like a scientific

299debate. Update the findings doc with whatever consensus emerges.

300```

301 

302辯論結構是這裡的關鍵機制。順序調查受到錨定的影響:一旦探索了一個理論,後續調查就會偏向於它。

303 

304有多個獨立調查人員積極嘗試相互反駁,倖存的理論更有可能是實際的根本原因。

305 

306## 最佳實踐

307 

308### 給隊友足夠的 context

309 

310隊友自動載入專案 context,包括 CLAUDE.md、MCP servers 和 skills,但他們不繼承主管的對話歷史。請參閱[Context 和通訊](#context-and-communication)以了解詳情。在生成提示中包含任務特定的詳情:

311 

312```text theme={null}

313Spawn a security reviewer teammate with the prompt: "Review the authentication module

314at src/auth/ for security vulnerabilities. Focus on token handling, session

315management, and input validation. The app uses JWT tokens stored in

316httpOnly cookies. Report any issues with severity ratings."

317```

318 

319### 選擇適當的團隊規模

320 

321隊友數量沒有硬性限制,但實際限制適用:

322 

323* **Token 成本線性增加**:每個隊友都有自己的 context window 並獨立消耗 tokens。請參閱 [agent team token 成本](/zh-TW/costs#agent-team-token-costs)以了解詳情。

324* **協調開銷增加**:更多隊友意味著更多通訊、任務協調和潛在衝突

325* **收益遞減**:超過一定點後,額外的隊友不會按比例加快工作

326 

327對於大多數工作流程,從 3-5 個隊友開始。這平衡了並行工作與可管理的協調。本指南中的範例使用 3-5 個隊友,因為該範圍在不同任務類型中效果很好。

328 

329每個隊友有 5-6 個[任務](/zh-TW/agent-teams#architecture)可以保持每個人的生產力,而不會過度的上下文切換。如果您有 15 個獨立任務,3 個隊友是一個很好的起點。

330 

331只有當工作真正受益於隊友同時工作時才擴展。三個專注的隊友通常優於五個分散的隊友。

332 

333### 適當調整任務大小

334 

335* **太小**:協調開銷超過收益

336* **太大**:隊友工作時間過長而沒有檢查點,增加浪費努力的風險

337* **恰到好處**:自包含的單位,產生清晰的可交付成果,例如函數、測試檔案或審查

338 

339<Tip>

340 主管將工作分解為任務並自動分配給隊友。如果它沒有建立足夠的任務,要求它將工作分成更小的部分。每個隊友有 5-6 個任務可以保持每個人的生產力,並讓主管在有人卡住時重新分配工作。

341</Tip>

342 

343### 等待隊友完成

344 

345有時主管開始自己實施任務,而不是等待隊友。如果您注意到這一點:

346 

347```text theme={null}

348Wait for your teammates to complete their tasks before proceeding

349```

350 

351### 從研究和審查開始

352 

353如果您是 agent teams 的新手,請從具有清晰邊界且不需要編寫程式碼的任務開始:審查 PR、研究庫或調查錯誤。這些任務展示了並行探索的價值,而不會帶來並行實施所帶來的協調挑戰。

354 

355### 避免檔案衝突

356 

357兩個隊友編輯同一檔案會導致覆蓋。分解工作,使每個隊友擁有不同的檔案集。

358 

359### 監控和引導

360 

361檢查隊友的進度,重新定向不起作用的方法,並在發現時綜合發現。讓團隊無人值守運行太長時間會增加浪費努力的風險。

362 

363## 故障排除

364 

365### 隊友未出現

366 

367如果在您要求 Claude 建立團隊後隊友未出現:

368 

369* 在 in-process 模式中,隊友可能已在運行但不可見。按 Shift+Down 循環瀏覽活躍隊友。

370* 檢查您給 Claude 的任務是否足夠複雜以保證團隊。Claude 根據任務決定是否生成隊友。

371* 如果您明確要求分割窗格,請確保 tmux 已安裝並在您的 PATH 中可用:

372 ```bash theme={null}

373 which tmux

374 ```

375* 對於 iTerm2,驗證 `it2` CLI 已安裝且 Python API 在 iTerm2 偏好設定中啟用。

376 

377### 過多權限提示

378 

379隊友權限請求冒泡到主管,這可能會造成摩擦。在生成隊友之前在 [permission settings](/zh-TW/permissions) 中預批准常見操作以減少中斷。

380 

381### 隊友在錯誤時停止

382 

383隊友可能在遇到錯誤後停止,而不是恢復。使用 in-process 模式中的 Shift+Down 或分割模式中的點擊窗格檢查其輸出,然後:

384 

385* 直接給他們額外的指示

386* 生成替換隊友以繼續工作

387 

388### 主管在工作完成前關閉

389 

390主管可能在所有任務實際完成之前決定團隊已完成。如果發生這種情況,告訴它繼續。您也可以告訴主管在繼續之前等待隊友完成,如果它開始做工作而不是委派。

391 

392### 孤立的 tmux 工作階段

393 

394如果 tmux 工作階段在團隊結束後仍然存在,它可能未被完全清理。列出工作階段並殺死由團隊建立的工作階段:

395 

396```bash theme={null}

397tmux ls

398tmux kill-session -t <session-name>

399```

400 

401## 限制

402 

403Agent teams 是實驗性的。要注意的目前限制:

404 

405* **In-process 隊友沒有工作階段恢復**:`/resume` 和 `/rewind` 不會恢復 in-process 隊友。恢復工作階段後,主管可能會嘗試向不再存在的隊友傳送訊息。如果發生這種情況,告訴主管生成新隊友。

406* **任務狀態可能滯後**:隊友有時無法將任務標記為已完成,這會阻止依賴任務。如果任務似乎卡住,請檢查工作是否實際完成並手動更新任務狀態或告訴主管推動隊友。

407* **關閉可能很慢**:隊友在關閉前完成其目前請求或工具呼叫,這可能需要時間。

408* **每個工作階段一個團隊**:主管一次只能管理一個團隊。在啟動新團隊之前清理目前團隊。

409* **沒有嵌套團隊**:隊友無法生成自己的團隊或隊友。只有主管可以管理團隊。

410* **主管是固定的**:建立團隊的工作階段在其生命週期內是主管。您無法將隊友提升為主管或轉移領導權。

411* **權限在生成時設定**:所有隊友開始時具有主管的權限模式。您可以在生成後更改個別隊友模式,但在生成時無法設定每個隊友的模式。

412* **分割窗格需要 tmux 或 iTerm2**:預設 in-process 模式在任何終端中工作。VS Code 的整合終端、Windows Terminal 或 Ghostty 不支援分割窗格模式。

413 

414<Tip>

415 **`CLAUDE.md` 正常工作**:隊友從其工作目錄讀取 `CLAUDE.md` 檔案。使用此為所有隊友提供專案特定的指導。

416</Tip>

417 

418## 後續步驟

419 

420探索並行工作和委派的相關方法:

421 

422* **輕量級委派**:[subagents](/zh-TW/sub-agents) 在您的工作階段內為研究或驗證生成幫助代理,更適合不需要代理間協調的任務

423* **手動並行工作階段**:[Git worktrees](/zh-TW/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees) 讓您自己運行多個 Claude Code 工作階段,無需自動化團隊協調

424* **比較方法**:請參閱 [subagent vs agent team](/zh-TW/features-overview#compare-similar-features) 比較以了解並排細分

amazon-bedrock.md +589 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Amazon Bedrock 上的 Claude Code

6 

7> 了解如何透過 Amazon Bedrock 設定 Claude Code,包括設定、IAM 設定和故障排除。

8 

9export const ContactSalesCard = ({surface}) => {

10 const utm = content => `utm_source=claude_code&utm_medium=docs&utm_content=${surface}_${content}`;

11 const iconArrowRight = (size = 13) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

12 <line x1="5" y1="12" x2="19" y2="12" />

13 <polyline points="12 5 19 12 12 19" />

14 </svg>;

15 const STYLES = `

16.cc-cs {

17 --cs-slate: #141413;

18 --cs-clay: #d97757;

19 --cs-clay-deep: #c6613f;

20 --cs-gray-000: #ffffff;

21 --cs-gray-700: #3d3d3a;

22 --cs-border-default: rgba(31, 30, 29, 0.15);

23 font-family: inherit;

24}

25.dark .cc-cs {

26 --cs-slate: #f0eee6;

27 --cs-gray-000: #262624;

28 --cs-gray-700: #bfbdb4;

29 --cs-border-default: rgba(240, 238, 230, 0.14);

30}

31.cc-cs-card {

32 display: flex; align-items: center; justify-content: space-between;

33 gap: 16px; padding: 14px 16px; margin: 0;

34 background: var(--cs-gray-000); border: 0.5px solid var(--cs-border-default);

35 border-radius: 8px; flex-wrap: wrap;

36}

37.cc-cs-text { font-size: 13px; color: var(--cs-gray-700); line-height: 1.5; flex: 1; min-width: 240px; }

38.cc-cs-text strong { font-weight: 550; color: var(--cs-slate); }

39.cc-cs-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }

40.cc-cs-btn-clay {

41 display: inline-flex; align-items: center; gap: 8px;

42 background: var(--cs-clay-deep); color: #fff; border: none;

43 border-radius: 8px; padding: 8px 14px;

44 font-size: 13px; font-weight: 500;

45 transition: background-color 0.15s; white-space: nowrap;

46}

47.cc-cs-btn-clay:hover { background: var(--cs-clay); }

48.cc-cs-btn-ghost {

49 display: inline-flex; align-items: center; gap: 8px;

50 background: transparent; color: var(--cs-gray-700);

51 border: 0.5px solid var(--cs-border-default);

52 border-radius: 8px; padding: 8px 14px;

53 font-size: 13px; font-weight: 500;

54}

55.cc-cs-btn-ghost:hover { background: rgba(0, 0, 0, 0.04); }

56.dark .cc-cs-btn-ghost:hover { background: rgba(255, 255, 255, 0.04); }

57@media (max-width: 720px) {

58 .cc-cs-actions { width: 100%; }

59}

60`;

61 return <div className="cc-cs not-prose">

62 <style>{STYLES}</style>

63 <div className="cc-cs-card">

64 <div className="cc-cs-text">

65 <strong>Deploying Claude Code across your organization?</strong> Talk to sales about enterprise plans, SSO, and centralized billing.

66 </div>

67 <div className="cc-cs-actions">

68 <a href={`https://claude.com/pricing?${utm('view_plans')}#plans-business`} className="cc-cs-btn-ghost">

69 View plans

70 </a>

71 <a href={`https://claude.com/contact-sales?${utm('contact_sales')}`} className="cc-cs-btn-clay">

72 Contact sales {iconArrowRight()}

73 </a>

74 </div>

75 </div>

76 </div>;

77};

78 

79export const Experiment = ({flag, treatment, children}) => {

80 const VID_KEY = 'exp_vid';

81 const CONSENT_COUNTRIES = new Set(['AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'RE', 'GP', 'MQ', 'GF', 'YT', 'BL', 'MF', 'PM', 'WF', 'PF', 'NC', 'AW', 'CW', 'SX', 'FO', 'GL', 'AX', 'GB', 'UK', 'AI', 'BM', 'IO', 'VG', 'KY', 'FK', 'GI', 'MS', 'PN', 'SH', 'TC', 'GG', 'JE', 'IM', 'CA', 'BR', 'IN']);

82 const fnv1a = s => {

83 let h = 0x811c9dc5;

84 for (let i = 0; i < s.length; i++) {

85 h ^= s.charCodeAt(i);

86 h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);

87 }

88 return h >>> 0;

89 };

90 const bucket = (seed, vid) => fnv1a(fnv1a(seed + vid) + '') % 10000 < 5000 ? 'control' : 'treatment';

91 const [decision] = useState(() => {

92 const params = new URLSearchParams(location.search);

93 const preBucketed = document.documentElement.dataset['gb_' + flag.replace(/-/g, '_')];

94 const force = params.get('gb-force');

95 if (force) {

96 for (const p of force.split(',')) {

97 const [k, v] = p.split(':');

98 if (k === flag) return {

99 variant: v || 'treatment',

100 track: false

101 };

102 }

103 }

104 if (navigator.globalPrivacyControl) {

105 return {

106 variant: 'control',

107 track: false

108 };

109 }

110 const prefsMatch = document.cookie.match(/(?:^|; )anthropic-consent-preferences=([^;]+)/);

111 if (prefsMatch) {

112 try {

113 if (JSON.parse(decodeURIComponent(prefsMatch[1])).analytics !== true) {

114 return {

115 variant: 'control',

116 track: false

117 };

118 }

119 } catch {

120 return {

121 variant: 'control',

122 track: false

123 };

124 }

125 } else {

126 const country = params.get('country')?.toUpperCase() || (document.cookie.match(/(?:^|; )cf_geo=([A-Z]{2})/) || [])[1];

127 if (!country || CONSENT_COUNTRIES.has(country)) {

128 return {

129 variant: 'control',

130 track: false

131 };

132 }

133 }

134 let vid;

135 try {

136 const ajsMatch = document.cookie.match(/(?:^|; )ajs_anonymous_id=([^;]+)/);

137 if (ajsMatch) {

138 vid = decodeURIComponent(ajsMatch[1]).replace(/^"|"$/g, '');

139 } else {

140 vid = localStorage.getItem(VID_KEY);

141 if (!vid) {

142 vid = crypto.randomUUID();

143 }

144 document.cookie = `ajs_anonymous_id=${vid}; domain=.claude.com; path=/; Secure; SameSite=Lax; max-age=31536000`;

145 }

146 try {

147 localStorage.setItem(VID_KEY, vid);

148 } catch {}

149 } catch {

150 return {

151 variant: 'control',

152 track: false

153 };

154 }

155 const variant = preBucketed === '1' ? 'treatment' : preBucketed === '0' ? 'control' : bucket(flag, vid);

156 return {

157 variant,

158 track: true,

159 vid

160 };

161 });

162 useEffect(() => {

163 if (!decision.track) return;

164 fetch('https://api.anthropic.com/api/event_logging/v2/batch', {

165 method: 'POST',

166 headers: {

167 'Content-Type': 'application/json',

168 'x-service-name': 'claude_code_docs'

169 },

170 body: JSON.stringify({

171 events: [{

172 event_type: 'GrowthbookExperimentEvent',

173 event_data: {

174 device_id: decision.vid,

175 anonymous_id: decision.vid,

176 timestamp: new Date().toISOString(),

177 experiment_id: flag,

178 variation_id: decision.variant === 'treatment' ? 1 : 0,

179 environment: 'production'

180 }

181 }]

182 }),

183 keepalive: true

184 }).catch(() => {});

185 }, []);

186 return decision.variant === 'treatment' ? treatment : children;

187};

188 

189<Experiment flag="docs-contact-sales-cta" treatment={<ContactSalesCard surface="bedrock" />} />

190 

191## 先決條件

192 

193在使用 Bedrock 設定 Claude Code 之前,請確保您具有:

194 

195* 已啟用 Bedrock 存取的 AWS 帳戶

196* 在 Bedrock 中存取所需的 Claude 模型(例如 Claude Sonnet 4.6)

197* 已安裝並設定 AWS CLI(選用 - 僅在您沒有其他取得認證機制時才需要)

198* 適當的 IAM 權限

199 

200若要使用您自己的 Bedrock 認證登入,請遵循下面的[使用 Bedrock 登入](#sign-in-with-bedrock)。若要在整個團隊中部署 Claude Code,請使用[手動設定](#set-up-manually)步驟並在推出前[固定您的模型版本](#4-pin-model-versions)。

201 

202## 使用 Bedrock 登入

203 

204如果您有 AWS 認證並想開始透過 Bedrock 使用 Claude Code,登入精靈會引導您完成整個過程。您每個帳戶完成一次 AWS 端的先決條件;精靈會處理 Claude Code 端。

205 

206<Steps>

207 <Step title="在您的 AWS 帳戶中啟用 Anthropic 模型">

208 在 [Amazon Bedrock 主控台](https://console.aws.amazon.com/bedrock/)中,開啟模型目錄,選取 Anthropic 模型,然後提交使用案例表單。提交後立即授予存取權限。請參閱[提交使用案例詳細資訊](#1-submit-use-case-details)以了解 AWS Organizations,以及[IAM 設定](#iam-configuration)以了解您的角色所需的權限。

209 </Step>

210 

211 <Step title="啟動 Claude Code 並選擇 Bedrock">

212 執行 `claude`。在登入提示處,選取**第三方平台**,然後選取 **Amazon Bedrock**。

213 </Step>

214 

215 <Step title="遵循精靈提示">

216 選擇您如何向 AWS 進行驗證:從您的 `~/.aws` 目錄偵測到的 AWS 設定檔、Bedrock API 金鑰、存取金鑰和密碼,或已在您的環境中的認證。精靈會選取您的區域,驗證您的帳戶可以叫用哪些 Claude 模型,並讓您固定它們。它會將結果儲存到您的[使用者設定檔](/zh-TW/settings)的 `env` 區塊,因此您不需要自己匯出環境變數。

217 </Step>

218</Steps>

219 

220登入後,隨時執行 `/setup-bedrock` 以重新開啟精靈並變更您的認證、區域或模型固定。

221 

222## 手動設定

223 

224若要透過環境變數而不是精靈來設定 Bedrock,例如在 CI 或指令碼化企業推出中,請遵循下面的步驟。

225 

226### 1. 提交使用案例詳細資訊

227 

228Anthropic 模型的首次使用者必須在叫用模型之前提交使用案例詳細資訊。這是每個 AWS 帳戶執行一次的操作。

229 

2301. 確保您具有下面所述的正確 IAM 權限

2312. 導覽至 [Amazon Bedrock 主控台](https://console.aws.amazon.com/bedrock/)

2323. 從**模型目錄**選取 Anthropic 模型

2334. 完成使用案例表單。提交後立即授予存取權限。

234 

235如果您使用 AWS Organizations,您可以使用 [`PutUseCaseForModelAccess` API](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_PutUseCaseForModelAccess.html) 從管理帳戶提交一次表單。此呼叫需要 `bedrock:PutUseCaseForModelAccess` IAM 權限。核准會自動延伸到子帳戶。

236 

237### 2. 設定 AWS 認證

238 

239Claude Code 使用預設的 AWS SDK 認證鏈。使用以下其中一種方法設定您的認證:

240 

241**選項 A:AWS CLI 設定**

242 

243```bash theme={null}

244aws configure

245```

246 

247**選項 B:環境變數(存取金鑰)**

248 

249```bash theme={null}

250export AWS_ACCESS_KEY_ID=your-access-key-id

251export AWS_SECRET_ACCESS_KEY=your-secret-access-key

252export AWS_SESSION_TOKEN=your-session-token

253```

254 

255**選項 C:環境變數(SSO 設定檔)**

256 

257```bash theme={null}

258aws sso login --profile=<your-profile-name>

259 

260export AWS_PROFILE=your-profile-name

261```

262 

263**選項 D:AWS 管理主控台認證**

264 

265```bash theme={null}

266aws login

267```

268 

269[深入了解](https://docs.aws.amazon.com/signin/latest/userguide/command-line-sign-in.html) `aws login`。

270 

271**選項 E:Bedrock API 金鑰**

272 

273```bash theme={null}

274export AWS_BEARER_TOKEN_BEDROCK=your-bedrock-api-key

275```

276 

277Bedrock API 金鑰提供了一種更簡單的驗證方法,無需完整的 AWS 認證。[深入了解 Bedrock API 金鑰](https://aws.amazon.com/blogs/machine-learning/accelerate-ai-development-with-amazon-bedrock-api-keys/)。

278 

279#### 進階認證設定

280 

281Claude Code 支援 AWS SSO 和公司身分提供者的自動認證重新整理。將這些設定新增至您的 Claude Code 設定檔(請參閱[設定](/zh-TW/settings)以了解檔案位置)。

282 

283當 Claude Code 偵測到您的 AWS 認證已過期(基於本機時間戳記或當 Bedrock 傳回認證錯誤時),它將自動執行您設定的 `awsAuthRefresh` 和/或 `awsCredentialExport` 命令以取得新認證,然後重試請求。

284 

285##### 範例設定

286 

287```json theme={null}

288{

289 "awsAuthRefresh": "aws sso login --profile myprofile",

290 "env": {

291 "AWS_PROFILE": "myprofile"

292 }

293}

294```

295 

296##### 設定說明

297 

298**`awsAuthRefresh`**:用於修改 `.aws` 目錄的命令,例如更新認證、SSO 快取或設定檔。命令的輸出會顯示給使用者,但不支援互動式輸入。這適用於瀏覽器型 SSO 流程,其中 CLI 顯示 URL 或代碼,您在瀏覽器中完成驗證。

299 

300**`awsCredentialExport`**:僅在您無法修改 `.aws` 且必須直接傳回認證時使用。輸出會被無聲地擷取,不會顯示給使用者。命令必須以此格式輸出 JSON:

301 

302```json theme={null}

303{

304 "Credentials": {

305 "AccessKeyId": "value",

306 "SecretAccessKey": "value",

307 "SessionToken": "value"

308 }

309}

310```

311 

312### 3. 設定 Claude Code

313 

314設定下列環境變數以啟用 Bedrock:

315 

316```bash theme={null}

317# 啟用 Bedrock 整合

318export CLAUDE_CODE_USE_BEDROCK=1

319export AWS_REGION=us-east-1 # 或您偏好的區域

320 

321# 選用:覆寫小型/快速模型 (Haiku) 的區域。

322# 也適用於 Bedrock Mantle。

323export ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION=us-west-2

324 

325# 選用:覆寫 Bedrock 端點 URL 以用於自訂端點或閘道

326# export ANTHROPIC_BEDROCK_BASE_URL=https://bedrock-runtime.us-east-1.amazonaws.com

327```

328 

329為 Claude Code 啟用 Bedrock 時,請記住以下事項:

330 

331* `AWS_REGION` 是必需的環境變數。Claude Code 不會從 `.aws` 設定檔讀取此設定。

332* 使用 Bedrock 時,`/login` 和 `/logout` 命令會被停用,因為驗證是透過 AWS 認證處理的。

333* 您可以使用設定檔來設定環境變數,例如 `AWS_PROFILE`,您不想將其洩露給其他程序。請參閱[設定](/zh-TW/settings)以取得更多資訊。

334 

335### 4. 固定模型版本

336 

337<Warning>

338 在部署給多個使用者時固定特定的模型版本。如果不固定,模型別名(例如 `sonnet` 和 `opus`)會解析為最新版本,當 Anthropic 發佈更新時,該版本可能在您的 Bedrock 帳戶中尚不可用。Claude Code 在啟動時會在最新版本不可用時[回退](#startup-model-checks)到先前版本,但固定可讓您控制使用者何時移至新模型。

339</Warning>

340 

341將這些環境變數設定為特定的 Bedrock 模型 ID。

342 

343如果沒有 `ANTHROPIC_DEFAULT_OPUS_MODEL`,Bedrock 上的 `opus` 別名會解析為 Opus 4.6。將其設定為 Opus 4.7 ID 以使用最新模型:

344 

345```bash theme={null}

346export ANTHROPIC_DEFAULT_OPUS_MODEL='us.anthropic.claude-opus-4-7'

347export ANTHROPIC_DEFAULT_SONNET_MODEL='us.anthropic.claude-sonnet-4-6'

348export ANTHROPIC_DEFAULT_HAIKU_MODEL='us.anthropic.claude-haiku-4-5-20251001-v1:0'

349```

350 

351這些變數使用跨區域推論設定檔 ID(帶有 `us.` 前綴)。如果您使用不同的區域前綴或應用程式推論設定檔,請相應調整。如需目前和舊版模型 ID,請參閱[模型概觀](https://platform.claude.com/docs/en/about-claude/models/overview)。請參閱[模型設定](/zh-TW/model-config#pin-models-for-third-party-deployments)以取得完整的環境變數清單。

352 

353未設定固定變數時,Claude Code 使用這些預設模型:

354 

355| 模型類型 | 預設值 |

356| :------ | :--------------------------------------------- |

357| 主要模型 | `us.anthropic.claude-sonnet-4-5-20250929-v1:0` |

358| 小型/快速模型 | `us.anthropic.claude-haiku-4-5-20251001-v1:0` |

359 

360若要進一步自訂模型,請使用以下其中一種方法:

361 

362```bash theme={null}

363# 使用推論設定檔 ID

364export ANTHROPIC_MODEL='global.anthropic.claude-sonnet-4-6'

365export ANTHROPIC_DEFAULT_HAIKU_MODEL='us.anthropic.claude-haiku-4-5-20251001-v1:0'

366 

367# 使用應用程式推論設定檔 ARN

368export ANTHROPIC_MODEL='arn:aws:bedrock:us-east-2:your-account-id:application-inference-profile/your-model-id'

369 

370# 選用:如果需要,停用 prompt caching

371export DISABLE_PROMPT_CACHING=1

372 

373# 選用:要求 1 小時 prompt cache TTL 而不是 5 分鐘預設值

374export ENABLE_PROMPT_CACHING_1H=1

375```

376 

377<Note>[Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) 可能不適用於所有區域。使用 1 小時 TTL 的快取寫入按比 5 分鐘寫入更高的費率計費。</Note>

378 

379#### 將每個模型版本對應至推論設定檔

380 

381`ANTHROPIC_DEFAULT_*_MODEL` 環境變數為每個模型系列設定一個推論設定檔。如果您的組織需要在 `/model` 選擇器中公開同一系列的多個版本,每個版本都路由到其自己的應用程式推論設定檔 ARN,請改用[設定檔](/zh-TW/settings#settings-files)中的 `modelOverrides` 設定。

382 

383此範例將四個 Opus 版本對應至不同的 ARN,以便使用者可以在它們之間切換,而無需繞過您組織的推論設定檔:

384 

385```json theme={null}

386{

387 "modelOverrides": {

388 "claude-opus-4-7": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-47-prod",

389 "claude-opus-4-6": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-46-prod",

390 "claude-opus-4-5-20251101": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-45-prod",

391 "claude-opus-4-1-20250805": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-41-prod"

392 }

393}

394```

395 

396當使用者在 `/model` 中選取其中一個版本時,Claude Code 會使用對應的 ARN 呼叫 Bedrock。沒有覆寫的版本會回退到內建的 Bedrock 模型 ID 或在啟動時發現的任何相符推論設定檔。請參閱[覆寫每個版本的模型 ID](/zh-TW/model-config#override-model-ids-per-version),以了解覆寫如何與 `availableModels` 和其他模型設定互動的詳細資訊。

397 

398## 啟動模型檢查

399 

400當 Claude Code 以 Bedrock 設定啟動時,它會驗證它打算使用的模型在您的帳戶中是否可存取。此檢查需要 Claude Code v2.1.94 或更新版本。

401 

402如果您已固定的模型版本比目前 Claude Code 預設值更舊,且您的帳戶可以叫用較新版本,Claude Code 會提示您更新固定。接受會將新模型 ID 寫入您的[使用者設定檔](/zh-TW/settings)並重新啟動 Claude Code。拒絕會被記住,直到下一次預設版本變更。指向[應用程式推論設定檔 ARN](#map-each-model-version-to-an-inference-profile) 的固定會被跳過,因為這些由您的管理員管理。

403 

404如果您尚未固定模型且目前預設值在您的帳戶中不可用,Claude Code 會在目前工作階段中回退到先前版本並顯示通知。回退不會被保留。在您的 Bedrock 帳戶中啟用較新模型或[固定版本](#4-pin-model-versions)以使選擇永久化。

405 

406## IAM 設定

407 

408建立具有 Claude Code 所需權限的 IAM 政策:

409 

410```json theme={null}

411{

412 "Version": "2012-10-17",

413 "Statement": [

414 {

415 "Sid": "AllowModelAndInferenceProfileAccess",

416 "Effect": "Allow",

417 "Action": [

418 "bedrock:InvokeModel",

419 "bedrock:InvokeModelWithResponseStream",

420 "bedrock:ListInferenceProfiles",

421 "bedrock:GetInferenceProfile"

422 ],

423 "Resource": [

424 "arn:aws:bedrock:*:*:inference-profile/*",

425 "arn:aws:bedrock:*:*:application-inference-profile/*",

426 "arn:aws:bedrock:*:*:foundation-model/*"

427 ]

428 },

429 {

430 "Sid": "AllowMarketplaceSubscription",

431 "Effect": "Allow",

432 "Action": [

433 "aws-marketplace:ViewSubscriptions",

434 "aws-marketplace:Subscribe"

435 ],

436 "Resource": "*",

437 "Condition": {

438 "StringEquals": {

439 "aws:CalledViaLast": "bedrock.amazonaws.com"

440 }

441 }

442 }

443 ]

444}

445```

446 

447如需更嚴格的權限,您可以將資源限制為特定的推論設定檔 ARN。

448 

449`bedrock:GetInferenceProfile` 讓 Claude Code 將[應用程式推論設定檔 ARN](#map-each-model-version-to-an-inference-profile) 解析為其支援的基礎模型,用於為該模型選擇正確的請求形狀。

450 

451如果權杖缺少此權限,Claude Code 會透過使用替代形狀重試一次來自動復原,因此請求仍會成功,但每個新模型都會增加額外的往返。授予權限可避免重試。這最常適用於 `AWS_BEARER_TOKEN_BEDROCK` 部署,其中權杖的政策通常比完整 IAM 角色更狹隘。

452 

453如需詳細資訊,請參閱 [Bedrock IAM 文件](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html)。

454 

455<Note>

456 為 Claude Code 建立專用的 AWS 帳戶,以簡化成本追蹤和存取控制。

457</Note>

458 

459## 1M 權杖內容視窗

460 

461Claude Opus 4.7、Opus 4.6 和 Sonnet 4.6 在 Amazon Bedrock 上支援 [1M 權杖內容視窗](https://platform.claude.com/docs/en/build-with-claude/context-windows#1m-token-context-window)。當您選取 1M 模型變體時,Claude Code 會自動啟用擴展內容視窗。

462 

463[設定精靈](#sign-in-with-bedrock)在固定模型時提供 1M 內容選項。若要為手動固定的模型啟用它,請在模型 ID 後附加 `[1m]`。請參閱[為第三方部署固定模型](/zh-TW/model-config#pin-models-for-third-party-deployments)以取得詳細資訊。

464 

465## AWS Guardrails

466 

467[Amazon Bedrock Guardrails](https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails.html) 可讓您為 Claude Code 實施內容篩選。在 [Amazon Bedrock 主控台](https://console.aws.amazon.com/bedrock/)中建立 Guardrail,發佈版本,然後將 Guardrail 標頭新增至您的[設定檔](/zh-TW/settings)。如果您使用跨區域推論設定檔,請在 Guardrail 上啟用跨區域推論。

468 

469範例設定:

470 

471```json theme={null}

472{

473 "env": {

474 "ANTHROPIC_CUSTOM_HEADERS": "X-Amzn-Bedrock-GuardrailIdentifier: your-guardrail-id\nX-Amzn-Bedrock-GuardrailVersion: 1"

475 }

476}

477```

478 

479## 使用 Mantle 端點

480 

481Mantle 是一個 Amazon Bedrock 端點,透過原生 Anthropic API 形狀而不是 Bedrock Invoke API 提供 Claude 模型。它使用相同的 AWS 認證、IAM 權限和本頁面前面所述的 `awsAuthRefresh` 設定。

482 

483<Note>

484 Mantle 需要 Claude Code v2.1.94 或更新版本。執行 `claude --version` 以檢查。

485</Note>

486 

487### 啟用 Mantle

488 

489已設定 AWS 認證後,設定 `CLAUDE_CODE_USE_MANTLE` 以將請求路由到 Mantle 端點:

490 

491```bash theme={null}

492export CLAUDE_CODE_USE_MANTLE=1

493export AWS_REGION=us-east-1

494```

495 

496Claude Code 從 `AWS_REGION` 構造端點 URL。若要為自訂端點或閘道覆寫它,請設定 `ANTHROPIC_BEDROCK_MANTLE_BASE_URL`。

497 

498在 Claude Code 內執行 `/status` 以確認。當 Mantle 處於作用中時,提供者行會顯示 `Amazon Bedrock (Mantle)`。

499 

500### 選取 Mantle 模型

501 

502Mantle 使用以 `anthropic.` 為前綴且沒有版本尾碼的模型 ID,例如 `anthropic.claude-haiku-4-5`。您的帳戶可用的模型取決於您的組織已被授予的內容;其他模型 ID 列在來自 AWS 的您的上線材料中。請聯絡您的 AWS 帳戶團隊以要求存取允許清單模型。

503 

504使用 `--model` 旗標或 Claude Code 內的 `/model` 設定模型:

505 

506```bash theme={null}

507claude --model anthropic.claude-haiku-4-5

508```

509 

510### 與 Invoke API 並行執行 Mantle

511 

512您在 Mantle 上可用的模型可能不包括您今天使用的每個模型。設定 `CLAUDE_CODE_USE_BEDROCK` 和 `CLAUDE_CODE_USE_MANTLE` 可讓 Claude Code 從同一工作階段呼叫兩個端點。符合 Mantle 格式的模型 ID 會路由到 Mantle,所有其他模型 ID 會進入 Bedrock Invoke API。

513 

514```bash theme={null}

515export CLAUDE_CODE_USE_BEDROCK=1

516export CLAUDE_CODE_USE_MANTLE=1

517```

518 

519若要在 `/model` 選擇器中顯示 Mantle 模型,請在[設定檔](/zh-TW/settings)中的 `availableModels` 中列出其 ID。此設定也會將選擇器限制為列出的項目,因此請包括您想保持可用的每個別名:

520 

521```json theme={null}

522{

523 "availableModels": ["opus", "sonnet", "haiku", "anthropic.claude-haiku-4-5"]

524}

525```

526 

527帶有 `anthropic.` 前綴的項目會新增為自訂選擇器選項並路由到 Mantle。將 `anthropic.claude-haiku-4-5` 替換為您的帳戶已被授予的模型 ID。請參閱[限制模型選擇](/zh-TW/model-config#restrict-model-selection)以了解 `availableModels` 如何與其他模型設定互動。

528 

529當兩個提供者都處於作用中時,`/status` 會顯示 `Amazon Bedrock + Amazon Bedrock (Mantle)`。

530 

531### 透過閘道路由 Mantle

532 

533如果您的組織透過集中式 [LLM 閘道](/zh-TW/llm-gateway)路由模型流量,該閘道在伺服器端注入 AWS 認證,請停用用戶端驗證,以便 Claude Code 傳送沒有 SigV4 簽名或 `x-api-key` 標頭的請求:

534 

535```bash theme={null}

536export CLAUDE_CODE_USE_MANTLE=1

537export CLAUDE_CODE_SKIP_MANTLE_AUTH=1

538export ANTHROPIC_BEDROCK_MANTLE_BASE_URL=https://your-gateway.example.com

539```

540 

541### Mantle 環境變數

542 

543這些變數特定於 Mantle 端點。請參閱[環境變數](/zh-TW/env-vars)以取得完整清單。

544 

545| 變數 | 目的 |

546| :-------------------------------------- | :--------------------------------- |

547| `CLAUDE_CODE_USE_MANTLE` | 啟用 Mantle 端點。設定為 `1` 或 `true`。 |

548| `ANTHROPIC_BEDROCK_MANTLE_BASE_URL` | 覆寫預設 Mantle 端點 URL |

549| `CLAUDE_CODE_SKIP_MANTLE_AUTH` | 跳過用戶端驗證以進行代理設定 |

550| `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | 覆寫 Haiku 級模型的 AWS 區域(與 Bedrock 共用) |

551 

552## 故障排除

553 

554### 使用 SSO 和公司代理的驗證迴圈

555 

556如果在使用 AWS SSO 時瀏覽器標籤頻繁開啟,請從您的[設定檔](/zh-TW/settings)中移除 `awsAuthRefresh` 設定。這可能發生在公司 VPN 或 TLS 檢查代理中斷 SSO 瀏覽器流程時。Claude Code 將中斷的連線視為驗證失敗,重新執行 `awsAuthRefresh`,並無限迴圈。

557 

558如果您的網路環境干擾自動瀏覽器型 SSO 流程,請在啟動 Claude Code 之前手動使用 `aws sso login`,而不是依賴 `awsAuthRefresh`。

559 

560### 區域問題

561 

562如果您遇到區域問題:

563 

564* 檢查模型可用性:`aws bedrock list-inference-profiles --region your-region`

565* 切換至支援的區域:`export AWS_REGION=us-east-1`

566* 考慮使用推論設定檔進行跨區域存取

567 

568如果您收到「不支援隨需輸送量」的錯誤:

569 

570* 將模型指定為[推論設定檔](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html) ID

571 

572Claude Code 使用 Bedrock [Invoke API](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html),不支援 Converse API。

573 

574### Mantle 端點錯誤

575 

576如果在設定 `CLAUDE_CODE_USE_MANTLE` 後 `/status` 未顯示 `Amazon Bedrock (Mantle)`,則該變數未到達程序。確認它已在您啟動 `claude` 的 shell 中匯出,或在[設定檔](/zh-TW/settings)的 `env` 區塊中設定它。

577 

578來自 Mantle 端點的 `403`(具有有效認證)表示您的 AWS 帳戶尚未被授予存取您要求的模型的權限。請聯絡您的 AWS 帳戶團隊以要求存取。

579 

580命名模型 ID 的 `400` 表示該模型未在 Mantle 上提供。Mantle 有其自己的模型陣容,與標準 Bedrock 目錄分開,因此推論設定檔 ID(例如 `us.anthropic.claude-sonnet-4-6`)將無法運作。使用 Mantle 格式的 ID,或啟用[兩個端點](#run-mantle-alongside-the-invoke-api),以便 Claude Code 將每個請求路由到模型可用的端點。

581 

582## 其他資源

583 

584* [Bedrock 文件](https://docs.aws.amazon.com/bedrock/)

585* [Bedrock 定價](https://aws.amazon.com/bedrock/pricing/)

586* [Bedrock 推論設定檔](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html)

587* [Bedrock 權杖燃盡和配額](https://docs.aws.amazon.com/bedrock/latest/userguide/quotas-token-burndown.html)

588* [Amazon Bedrock 上的 Claude Code:快速設定指南](https://community.aws/content/2tXkZKrZzlrlu0KfH8gST5Dkppq/claude-code-on-amazon-bedrock-quick-setup-guide)

589* [Claude Code 監控實施 (Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md)

analytics.md +224 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 使用分析追蹤團隊使用情況

6 

7> 在分析儀表板中查看 Claude Code 使用指標、追蹤採用情況並衡量工程速度。

8 

9Claude Code 提供分析儀表板,幫助組織了解開發人員使用模式、追蹤貢獻指標,並衡量 Claude Code 對工程速度的影響。根據您的計劃訪問儀表板:

10 

11| 計劃 | 儀表板 URL | 包含內容 | 了解更多 |

12| ----------------------------- | -------------------------------------------------------------------------- | ------------------------------ | ------------------------------------------------ |

13| Claude for Teams / Enterprise | [claude.ai/analytics/claude-code](https://claude.ai/analytics/claude-code) | 使用指標、與 GitHub 整合的貢獻指標、排行榜、數據匯出 | [詳情](#access-analytics-for-teams-and-enterprise) |

14| API (Claude Console) | [platform.claude.com/claude-code](https://platform.claude.com/claude-code) | 使用指標、支出追蹤、團隊洞察 | [詳情](#access-analytics-for-api-customers) |

15 

16## 訪問 Teams 和 Enterprise 的分析

17 

18導航至 [claude.ai/analytics/claude-code](https://claude.ai/analytics/claude-code)。管理員和所有者可以查看儀表板。

19 

20Teams 和 Enterprise 儀表板包括:

21 

22* **使用指標**:已接受的代碼行數、建議接受率、每日活躍用戶和會話

23* **貢獻指標**:使用 Claude Code 協助發布的 PR 和代碼行數,具有 [GitHub 整合](#enable-contribution-metrics)

24* **排行榜**:按 Claude Code 使用情況排名的頂級貢獻者

25* **數據匯出**:將貢獻數據下載為 CSV 格式以進行自訂報告

26 

27### 啟用貢獻指標

28 

29<Note>

30 貢獻指標處於公開測試版,可在 Claude for Teams 和 Claude for Enterprise 計劃上使用。這些指標僅涵蓋您 claude.ai 組織內的用戶。通過 Claude Console API 或第三方整合的使用不包括在內。

31</Note>

32 

33使用和採用數據適用於所有 Claude for Teams 和 Claude for Enterprise 帳戶。貢獻指標需要額外設置以連接您的 GitHub 組織。

34 

35您需要所有者角色來配置分析設置。GitHub 管理員必須安裝 GitHub 應用程序。

36 

37<Warning>

38 啟用了 [Zero Data Retention](/zh-TW/zero-data-retention) 的組織無法使用貢獻指標。分析儀表板將僅顯示使用指標。

39</Warning>

40 

41<Steps>

42 <Step title="安裝 GitHub 應用程序">

43 GitHub 管理員在您組織的 GitHub 帳戶上安裝 Claude GitHub 應用程序,位址為 [github.com/apps/claude](https://github.com/apps/claude)。

44 </Step>

45 

46 <Step title="啟用 Claude Code 分析">

47 Claude 所有者導航至 [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) 並啟用 Claude Code 分析功能。

48 </Step>

49 

50 <Step title="啟用 GitHub 分析">

51 在同一頁面上,啟用'GitHub 分析'切換。

52 </Step>

53 

54 <Step title="使用 GitHub 進行身份驗證">

55 完成 GitHub 身份驗證流程並選擇要包含在分析中的 GitHub 組織。

56 </Step>

57</Steps>

58 

59啟用後,數據通常在 24 小時內出現,並進行每日更新。如果沒有數據出現,您可能會看到以下消息之一:

60 

61* **「需要 GitHub 應用程序」**:安裝 GitHub 應用程序以查看貢獻指標

62* **「數據處理進行中」**:幾天後重新檢查,如果數據未出現,請確認 GitHub 應用程序已安裝

63 

64貢獻指標支持 GitHub Cloud 和 GitHub Enterprise Server。

65 

66### 查看摘要指標

67 

68<Note>

69 這些指標故意保守,代表對 Claude Code 實際影響的低估。只有高度確信 Claude Code 參與的代碼行和 PR 才會被計算。

70</Note>

71 

72儀表板在頂部顯示這些摘要指標:

73 

74* **帶有 CC 的 PR**:包含至少一行使用 Claude Code 編寫的代碼的已合併拉取請求的總計數

75* **帶有 CC 的代碼行**:所有已合併 PR 中使用 Claude Code 協助編寫的代碼行總數。僅計算「有效行」:規範化後超過 3 個字符的行,不包括空行和僅包含括號或瑣碎標點符號的行。

76* **帶有 Claude Code 的 PR (%)**:包含 Claude Code 協助代碼的所有已合併 PR 的百分比

77* **建議接受率**:用戶接受 Claude Code 代碼編輯建議的次數百分比,包括 Edit、Write 和 NotebookEdit 工具使用

78* **已接受的代碼行**:Claude Code 編寫且用戶在其會話中已接受的代碼行總數。這不包括被拒絕的建議,也不追蹤後續刪除。

79 

80### 探索圖表

81 

82儀表板包括多個圖表以可視化一段時間內的趨勢。

83 

84#### 追蹤採用

85 

86採用圖表顯示每日使用趨勢:

87 

88* **用戶**:每日活躍用戶

89* **會話**:每天活躍 Claude Code 會話的數量

90 

91#### 衡量每個用戶的 PR

92 

93此圖表顯示一段時間內的個人開發人員活動:

94 

95* **每個用戶的 PR**:每天合併的 PR 總數除以每日活躍用戶

96* **用戶**:每日活躍用戶

97 

98使用此功能了解隨著 Claude Code 採用增加,個人生產力如何變化。

99 

100#### 查看拉取請求細分

101 

102拉取請求圖表顯示已合併 PR 的每日細分:

103 

104* **帶有 CC 的 PR**:包含 Claude Code 協助代碼的拉取請求

105* **不帶 CC 的 PR**:不包含 Claude Code 協助代碼的拉取請求

106 

107切換至**代碼行**視圖以按代碼行而不是 PR 計數查看相同的細分。

108 

109#### 查找頂級貢獻者

110 

111排行榜顯示按貢獻量排名的前 10 名用戶。在以下之間切換:

112 

113* **拉取請求**:顯示每個用戶的帶有 Claude Code 的 PR 與所有 PR

114* **代碼行**:顯示每個用戶的帶有 Claude Code 的行與所有行

115 

116點擊**匯出所有用戶**以將所有用戶的完整貢獻數據下載為 CSV 文件。匯出包括所有用戶,而不僅僅是顯示的前 10 名。

117 

118### PR 歸因

119 

120啟用貢獻指標後,Claude Code 會分析已合併的拉取請求,以確定哪些代碼是使用 Claude Code 協助編寫的。這是通過將 Claude Code 會話活動與每個 PR 中的代碼進行匹配來完成的。

121 

122#### 標記標準

123 

124如果 PR 包含在 Claude Code 會話期間編寫的至少一行代碼,則將其標記為「帶有 Claude Code」。系統使用保守匹配:只有高度確信 Claude Code 參與的代碼才被計為協助。

125 

126#### 歸因過程

127 

128當拉取請求被合併時:

129 

1301. 從 PR diff 中提取添加的行

1312. 識別在時間窗口內編輯匹配文件的 Claude Code 會話

1323. 使用多種策略將 PR 行與 Claude Code 輸出進行匹配

1334. 計算 AI 協助行和總行的指標

134 

135在比較之前,行被規範化:空格被修剪、多個空格被折疊、引號被標準化、文本被轉換為小寫。

136 

137包含 Claude Code 協助行的已合併拉取請求在 GitHub 中被標記為 `claude-code-assisted`。

138 

139#### 時間窗口

140 

141PR 合併日期前 21 天至後 2 天的會話被考慮用於歸因匹配。

142 

143#### 排除的文件

144 

145某些文件會自動從分析中排除,因為它們是自動生成的:

146 

147* 鎖定文件:package-lock.json、yarn.lock、Cargo.lock 及類似文件

148* 生成的代碼:Protobuf 輸出、構建工件、縮小的文件

149* 構建目錄:dist/、build/、node\_modules/、target/

150* 測試夾具:快照、盒帶、模擬數據

151* 超過 1,000 個字符的行,可能是縮小或生成的

152 

153#### 歸因說明

154 

155在解釋歸因數據時,請記住這些額外詳情:

156 

157* 由開發人員大幅重寫的代碼,差異超過 20%,不歸因於 Claude Code

158* 21 天窗口外的會話不被考慮

159* 該算法在執行歸因時不考慮 PR 源或目標分支

160 

161### 從分析中獲得最大收益

162 

163使用貢獻指標來展示 ROI、識別採用模式並找到可以幫助他人入門的團隊成員。

164 

165#### 監控採用

166 

167追蹤採用圖表和用戶計數以識別:

168 

169* 可以分享最佳實踐的活躍用戶

170* 整個組織的整體採用趨勢

171* 可能表示摩擦或問題的使用下降

172 

173#### 衡量 ROI

174 

175貢獻指標幫助回答「這個工具值得投資嗎?」,使用來自您自己代碼庫的數據:

176 

177* 隨著採用增加,追蹤一段時間內每個用戶的 PR 變化

178* 比較使用和不使用 Claude Code 發布的 PR 和代碼行

179* 與 [DORA 指標](https://dora.dev/)、衝刺速度或其他工程 KPI 一起使用,以了解採用 Claude Code 帶來的變化

180 

181#### 識別超級用戶

182 

183排行榜幫助您找到具有高 Claude Code 採用率的團隊成員,他們可以:

184 

185* 與團隊分享提示技術和工作流程

186* 提供有關什麼運作良好的反饋

187* 幫助新用戶入門

188 

189#### 以編程方式訪問數據

190 

191要通過 GitHub 查詢此數據,請搜索標記為 `claude-code-assisted` 的 PR。

192 

193## 訪問 API 客戶的分析

194 

195使用 Claude Console 的 API 客戶可以在 [platform.claude.com/claude-code](https://platform.claude.com/claude-code) 訪問分析。您需要 UsageView 權限才能訪問儀表板,該權限授予開發人員、計費、管理員、所有者和主要所有者角色。

196 

197<Note>

198 GitHub 整合的貢獻指標目前不適用於 API 客戶。Console 儀表板僅顯示使用和支出指標。

199</Note>

200 

201Console 儀表板顯示:

202 

203* **已接受的代碼行**:Claude Code 編寫且用戶在其會話中已接受的代碼行總數。這不包括被拒絕的建議,也不追蹤後續刪除。

204* **建議接受率**:用戶接受代碼編輯工具使用的次數百分比,包括 Edit、Write 和 NotebookEdit 工具。

205* **活動**:圖表上顯示的每日活躍用戶和會話。

206* **支出**:每日 API 成本(以美元計)以及用戶計數。

207 

208### 查看團隊洞察

209 

210團隊洞察表顯示每個用戶的指標:

211 

212* **成員**:所有已向 Claude Code 進行身份驗證的用戶。API 密鑰用戶按密鑰標識符顯示,OAuth 用戶按電子郵件地址顯示。

213* **本月支出**:每個用戶當前月份的每用戶 API 成本總計。

214* **本月代碼行**:每個用戶當前月份已接受代碼行的每用戶總計。

215 

216<Note>

217 Console 儀表板中的支出數字是用於分析目的的估計值。有關實際成本,請參閱您的計費頁面。

218</Note>

219 

220## 相關資源

221 

222* [使用 OpenTelemetry 進行監控](/zh-TW/monitoring-usage):將實時指標和事件匯出到您的可觀測性堆棧

223* [有效管理成本](/zh-TW/costs):設置支出限制並優化令牌使用

224* [權限](/zh-TW/permissions):配置角色和權限

authentication.md +155 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 驗證

6 

7> 登入 Claude Code 並為個人、團隊和組織配置驗證。

8 

9Claude Code 支援多種驗證方法,具體取決於您的設定。個人使用者可以使用 Claude.ai 帳戶登入,而團隊可以使用 Claude for Teams 或 Enterprise、Claude Console 或雲端提供商(如 Amazon Bedrock、Google Vertex AI 或 Microsoft Foundry)。

10 

11## 登入 Claude Code

12 

13[安裝 Claude Code](/zh-TW/setup#install-claude-code) 後,在您的終端機中執行 `claude`。首次啟動時,Claude Code 會為您開啟瀏覽器視窗以供登入。

14 

15如果瀏覽器未自動開啟,請按 `c` 將登入 URL 複製到您的剪貼簿,然後將其貼到您的瀏覽器中。

16 

17如果您的瀏覽器在您登入後顯示登入代碼而不是重新導向回來,請將其貼到終端機的 `Paste code here if prompted` 提示符處。這在瀏覽器無法連接到 Claude Code 的本機回呼伺服器時發生,這在 WSL2、SSH 工作階段和容器中很常見。

18 

19您可以使用以下任何帳戶類型進行驗證:

20 

21* **Claude Pro 或 Max 訂閱**:使用您的 Claude.ai 帳戶登入。在 [claude.com/pricing](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=authentication_pro_max) 訂閱。

22* **Claude for Teams 或 Enterprise**:使用您的團隊管理員邀請您的 Claude.ai 帳戶登入。

23* **Claude Console**:使用您的 Console 認證登入。您的管理員必須先 [邀請您](#claude-console-authentication)。

24* **雲端提供商**:如果您的組織使用 [Amazon Bedrock](/zh-TW/amazon-bedrock)、[Google Vertex AI](/zh-TW/google-vertex-ai) 或 [Microsoft Foundry](/zh-TW/microsoft-foundry),請在執行 `claude` 之前設定所需的環境變數。不需要瀏覽器登入。

25 

26若要登出並重新驗證,請在 Claude Code 提示符處輸入 `/logout`。

27 

28如果您在登入時遇到問題,請參閱 [驗證疑難排解](/zh-TW/troubleshoot-install#login-and-authentication)。

29 

30## 設定團隊驗證

31 

32對於團隊和組織,您可以透過以下方式之一配置 Claude Code 存取:

33 

34* [Claude for Teams 或 Enterprise](#claude-for-teams-or-enterprise),建議用於大多數團隊

35* [Claude Console](#claude-console-authentication)

36* [Amazon Bedrock](/zh-TW/amazon-bedrock)

37* [Google Vertex AI](/zh-TW/google-vertex-ai)

38* [Microsoft Foundry](/zh-TW/microsoft-foundry)

39 

40### Claude for Teams 或 Enterprise

41 

42[Claude for Teams](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=authentication_teams#team-&-enterprise) 和 [Claude for Enterprise](https://anthropic.com/contact-sales?utm_source=claude_code\&utm_medium=docs\&utm_content=authentication_enterprise) 為使用 Claude Code 的組織提供最佳體驗。團隊成員可以存取 Claude Code 和網頁版 Claude,並具有集中式帳單和團隊管理。

43 

44* **Claude for Teams**:自助服務方案,具有協作功能、管理工具和帳單管理。最適合較小的團隊。

45* **Claude for Enterprise**:新增 SSO、網域擷取、角色型權限、合規性 API 和受管原則設定,用於組織範圍的 Claude Code 配置。最適合具有安全性和合規性要求的大型組織。

46 

47<Steps>

48 <Step title="訂閱">

49 訂閱 [Claude for Teams](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=authentication_teams_step#team-&-enterprise) 或聯絡銷售部門以取得 [Claude for Enterprise](https://anthropic.com/contact-sales?utm_source=claude_code\&utm_medium=docs\&utm_content=authentication_enterprise_step)。

50 </Step>

51 

52 <Step title="邀請團隊成員">

53 從管理儀表板邀請團隊成員。

54 </Step>

55 

56 <Step title="安裝並登入">

57 團隊成員安裝 Claude Code 並使用其 Claude.ai 帳戶登入。

58 </Step>

59</Steps>

60 

61### Claude Console 驗證

62 

63對於偏好基於 API 的帳單的組織,您可以透過 Claude Console 設定存取。

64 

65<Steps>

66 <Step title="建立或使用 Console 帳戶">

67 使用您現有的 Claude Console 帳戶或建立新帳戶。

68 </Step>

69 

70 <Step title="新增使用者">

71 您可以透過以下任一方法新增使用者:

72 

73 * 從 Console 內大量邀請使用者:Settings -> Members -> Invite

74 * [設定 SSO](https://support.claude.com/en/articles/13132885-setting-up-single-sign-on-sso)

75 </Step>

76 

77 <Step title="指派角色">

78 邀請使用者時,指派以下其中一個角色:

79 

80 * **Claude Code** 角色:使用者只能建立 Claude Code API 金鑰

81 * **Developer** 角色:使用者可以建立任何類型的 API 金鑰

82 </Step>

83 

84 <Step title="使用者完成設定">

85 每個受邀使用者需要:

86 

87 * 接受 Console 邀請

88 * [檢查系統要求](/zh-TW/setup#system-requirements)

89 * [安裝 Claude Code](/zh-TW/setup#install-claude-code)

90 * 使用 Console 帳戶認證登入

91 </Step>

92</Steps>

93 

94### 雲端提供商驗證

95 

96對於使用 Amazon Bedrock、Google Vertex AI 或 Microsoft Foundry 的團隊:

97 

98<Steps>

99 <Step title="遵循提供商設定">

100 遵循 [Bedrock 文件](/zh-TW/amazon-bedrock)、[Vertex 文件](/zh-TW/google-vertex-ai) 或 [Microsoft Foundry 文件](/zh-TW/microsoft-foundry)。

101 </Step>

102 

103 <Step title="分發配置">

104 將環境變數和產生雲端認證的說明分發給您的使用者。深入瞭解如何 [在此管理配置](/zh-TW/settings)。

105 </Step>

106 

107 <Step title="安裝 Claude Code">

108 使用者可以 [安裝 Claude Code](/zh-TW/setup#install-claude-code)。

109 </Step>

110</Steps>

111 

112## 認證管理

113 

114Claude Code 安全地管理您的驗證認證:

115 

116* **儲存位置**:在 macOS 上,認證儲存在加密的 macOS Keychain 中。在 Linux 和 Windows 上,認證儲存在 `~/.claude/.credentials.json` 中,或在設定了 `$CLAUDE_CONFIG_DIR` 變數時儲存在該位置下。在 Linux 上,檔案以模式 `0600` 寫入;在 Windows 上,它繼承您的使用者設定檔目錄的存取控制。

117* **支援的驗證類型**:Claude.ai 認證、Claude API 認證、Azure Auth、Bedrock Auth 和 Vertex Auth。

118* **自訂認證指令碼**:[`apiKeyHelper`](/zh-TW/settings#available-settings) 設定可以配置為執行傳回 API 金鑰的 shell 指令碼。

119* **重新整理間隔**:根據預設,`apiKeyHelper` 在 5 分鐘後或在 HTTP 401 回應時呼叫。設定 `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` 環境變數以自訂重新整理間隔。

120* **緩慢協助程式通知**:如果 `apiKeyHelper` 花費超過 10 秒的時間傳回金鑰,Claude Code 會在提示符列中顯示警告通知,顯示經過的時間。如果您經常看到此通知,請檢查您的認證指令碼是否可以最佳化。

121 

122`apiKeyHelper`、`ANTHROPIC_API_KEY` 和 `ANTHROPIC_AUTH_TOKEN` 僅適用於終端機 CLI 工作階段。Claude Desktop 和遠端工作階段僅使用 OAuth,不會呼叫 `apiKeyHelper` 或讀取 API 金鑰環境變數。

123 

124### 驗證優先順序

125 

126當存在多個認證時,Claude Code 按此順序選擇一個:

127 

1281. 雲端提供商認證,當設定了 `CLAUDE_CODE_USE_BEDROCK`、`CLAUDE_CODE_USE_VERTEX` 或 `CLAUDE_CODE_USE_FOUNDRY` 時。請參閱 [第三方整合](/zh-TW/third-party-integrations) 以取得設定。

1292. `ANTHROPIC_AUTH_TOKEN` 環境變數。作為 `Authorization: Bearer` 標頭傳送。當透過 [LLM 閘道或代理](/zh-TW/llm-gateway) 路由時使用此選項,該閘道或代理使用持有人令牌而不是 Anthropic API 金鑰進行驗證。

1303. `ANTHROPIC_API_KEY` 環境變數。作為 `X-Api-Key` 標頭傳送。用於直接 Anthropic API 存取,使用來自 [Claude Console](https://platform.claude.com) 的金鑰。在互動模式下,系統會提示您一次以核准或拒絕金鑰,您的選擇會被記住。若要稍後變更,請使用 `/config` 中的「使用自訂 API 金鑰」切換。在非互動模式 (`-p`) 中,當金鑰存在時始終使用該金鑰。

1314. [`apiKeyHelper`](/zh-TW/settings#available-settings) 指令碼輸出。用於動態或輪換認證,例如從保管庫擷取的短期令牌。

1325. `CLAUDE_CODE_OAUTH_TOKEN` 環境變數。由 [`claude setup-token`](#generate-a-long-lived-token) 產生的長期 OAuth 令牌。用於 CI 管道和指令碼,其中瀏覽器登入不可用。

1336. 來自 `/login` 的訂閱 OAuth 認證。這是 Claude Pro、Max、Team 和 Enterprise 使用者的預設值。

134 

135如果您有有效的 Claude 訂閱,但您的環境中也設定了 `ANTHROPIC_API_KEY`,則 API 金鑰在核准後優先。如果金鑰屬於已停用或過期的組織,這可能會導致驗證失敗。執行 `unset ANTHROPIC_API_KEY` 以回退到您的訂閱,並檢查 `/status` 以確認哪種方法處於活動狀態。

136 

137[網頁版 Claude Code](/zh-TW/claude-code-on-the-web) 始終使用您的訂閱認證。沙箱環境中的 `ANTHROPIC_API_KEY` 和 `ANTHROPIC_AUTH_TOKEN` 不會覆蓋它們。

138 

139### 產生長期令牌

140 

141對於 CI 管道、指令碼或其他互動式瀏覽器登入不可用的環境,使用 `claude setup-token` 產生一年期 OAuth 令牌:

142 

143```bash theme={null}

144claude setup-token

145```

146 

147該命令會引導您完成 OAuth 授權並將令牌列印到終端機。它不會將令牌儲存在任何地方;複製它並將其設定為您想要驗證的任何地方的 `CLAUDE_CODE_OAUTH_TOKEN` 環境變數:

148 

149```bash theme={null}

150export CLAUDE_CODE_OAUTH_TOKEN=your-token

151```

152 

153此令牌使用您的 Claude 訂閱進行驗證,需要 Pro、Max、Team 或 Enterprise 方案。它的範圍僅限於推論,無法建立 [Remote Control](/zh-TW/remote-control) 工作階段。

154 

155[Bare mode](/zh-TW/headless#start-faster-with-bare-mode) 不讀取 `CLAUDE_CODE_OAUTH_TOKEN`。如果您的指令碼傳遞 `--bare`,請改用 `ANTHROPIC_API_KEY` 或 `apiKeyHelper` 進行驗證。

auto-mode-config.md +178 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 設定自動模式

6 

7> 告訴自動模式分類器您的組織信任哪些儲存庫、儲存桶和網域。設定環境上下文、覆蓋預設的阻止和允許規則,並使用自動模式 CLI 子命令檢查您的有效設定。

8 

9[自動模式](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode)讓 Claude Code 無需權限提示即可執行,方法是透過分類器路由每個工具呼叫,該分類器會阻止任何不可逆、破壞性或針對您環境外部的操作。使用 `autoMode` 設定區塊告訴該分類器您的組織信任哪些儲存庫、儲存桶和網域,以便它停止阻止常規內部操作。

10 

11<Note>

12 自動模式可在 Max、Team、Enterprise 和 API 方案上透過 Anthropic API 使用。它在 Pro 上或在 Bedrock、Vertex 或 Foundry 上不可用。如果 Claude Code 報告您的帳戶無法使用自動模式,請檢查[完整要求](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode),其中也涵蓋支援的模型和 Team 與 Enterprise 方案上的管理員啟用。

13</Note>

14 

15開箱即用,分類器只信任工作目錄和目前儲存庫的已設定遠端。推送到您公司的原始碼控制組織或寫入團隊雲端儲存桶等操作會被阻止,直到您將它們新增到 `autoMode.environment`。

16 

17有關如何啟用自動模式以及它預設阻止的內容,請參閱[權限模式](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode)。本頁是設定參考。

18 

19本頁涵蓋如何:

20 

21* [選擇在何處設定規則](#where-the-classifier-reads-configuration)跨 CLAUDE.md、使用者設定和受管設定

22* [定義受信任的基礎設施](#define-trusted-infrastructure)使用 `autoMode.environment`

23* [覆蓋阻止和允許規則](#override-the-block-and-allow-rules)當預設值不符合您的管道時

24* [檢查您的有效設定](#inspect-the-defaults-and-your-effective-config)使用 `claude auto-mode` 子命令

25* [檢查拒絕](#review-denials)以便您知道接下來要新增什麼

26 

27## 分類器讀取設定的位置

28 

29分類器讀取與 Claude 本身載入的相同 [CLAUDE.md](/zh-TW/memory) 內容,因此您專案的 CLAUDE.md 中的「永遠不要強制推送」之類的指令同時引導 Claude 和分類器。從那裡開始了解專案慣例和行為規則。

30 

31對於跨專案應用的規則,例如受信任的基礎設施或組織範圍的拒絕規則,請使用 `autoMode` 設定區塊。分類器從以下範圍讀取 `autoMode`:

32 

33| 範圍 | 檔案 | 用途 |

34| :------------------------- | :------------------------------------- | :------------------------ |

35| 一個開發人員 | `~/.claude/settings.json` | 個人受信任的基礎設施 |

36| 一個專案,一個開發人員 | `.claude/settings.local.json` | 每個專案的受信任儲存桶或服務,gitignored |

37| 組織範圍 | [受管設定](/zh-TW/server-managed-settings) | 分散到所有開發人員的受信任基礎設施 |

38| `--settings` 旗標或 Agent SDK | 內聯 JSON | 自動化的每次呼叫覆蓋 |

39 

40分類器不從 `.claude/settings.json` 中的共用專案設定讀取 `autoMode`,因此簽入的儲存庫無法注入其自己的允許規則。

41 

42來自每個範圍的項目會被合併。開發人員可以使用個人項目擴展 `environment`、`allow` 和 `soft_deny`,但無法移除受管設定提供的項目。因為允許規則在分類器內充當阻止規則的例外,開發人員新增的 `allow` 項目可以覆蓋組織 `soft_deny` 項目:組合是加法的,而不是硬策略邊界。

43 

44<Note>

45 分類器是在[權限系統](/zh-TW/permissions)之後執行的第二道門。對於無論使用者意圖或分類器設定如何都必須永遠不執行的操作,請在受管設定中使用 `permissions.deny`,它在諮詢分類器之前阻止操作,無法被覆蓋。

46</Note>

47 

48## 定義受信任的基礎設施

49 

50對於大多數組織,`autoMode.environment` 是您唯一需要設定的欄位。它告訴分類器哪些儲存庫、儲存桶和網域是受信任的:分類器使用它來決定「外部」的含義,因此任何未列出的目的地都是潛在的資料外洩目標。

51 

52預設環境清單信任工作儲存庫及其設定的遠端。若要在該預設值旁邊新增您自己的項目,請在陣列中包含字面字串 `"$defaults"`。預設項目會在該位置被插入,因此您的自訂項目可以在它們之前或之後。

53 

54```json theme={null}

55{

56 "autoMode": {

57 "environment": [

58 "$defaults",

59 "Source control: github.example.com/acme-corp and all repos under it",

60 "Trusted cloud buckets: s3://acme-build-artifacts, gs://acme-ml-datasets",

61 "Trusted internal domains: *.corp.example.com, api.internal.example.com",

62 "Key internal services: Jenkins at ci.example.com, Artifactory at artifacts.example.com"

63 ]

64 }

65}

66```

67 

68項目是散文,不是正規表達式或工具模式。分類器將它們讀取為自然語言規則。按照您向新工程師描述基礎設施的方式編寫它們。徹底的環境部分涵蓋:

69 

70* **組織**:您的公司名稱以及 Claude Code 的主要用途,例如軟體開發、基礎設施自動化或資料工程

71* **原始碼控制**:您的開發人員推送到的每個 GitHub、GitLab 或 Bitbucket 組織

72* **雲端提供者和受信任的儲存桶**:Claude 應該能夠讀取和寫入的儲存桶名稱或前綴

73* **受信任的內部網域**:您網路內的 API、儀表板和服務的主機名稱,例如 `*.internal.example.com`

74* **關鍵內部服務**:CI、工件登錄、內部套件索引、事件工具

75* **其他上下文**:受管制行業的限制、多租戶基礎設施或影響分類器應將什麼視為風險的合規要求

76 

77一個有用的起始範本:填入括號中的欄位並移除任何不適用的行。

78 

79```json theme={null}

80{

81 "autoMode": {

82 "environment": [

83 "$defaults",

84 "Organization: {COMPANY_NAME}. Primary use: {PRIMARY_USE_CASE, e.g. software development, infrastructure automation}",

85 "Source control: {SOURCE_CONTROL, e.g. GitHub org github.example.com/acme-corp}",

86 "Cloud provider(s): {CLOUD_PROVIDERS, e.g. AWS, GCP, Azure}",

87 "Trusted cloud buckets: {TRUSTED_BUCKETS, e.g. s3://acme-builds, gs://acme-datasets}",

88 "Trusted internal domains: {TRUSTED_DOMAINS, e.g. *.internal.example.com, api.example.com}",

89 "Key internal services: {SERVICES, e.g. Jenkins at ci.example.com, Artifactory at artifacts.example.com}",

90 "Additional context: {EXTRA, e.g. regulated industry, multi-tenant infrastructure, compliance requirements}"

91 ]

92 }

93}

94```

95 

96您提供的上下文越具體,分類器就越能區分常規內部操作和資料外洩嘗試。

97 

98您不需要一次性填入所有內容。合理的推出:從預設值開始,新增您的原始碼控制組織和關鍵內部服務,這解決了最常見的誤報,例如推送到您自己的儲存庫。接下來新增受信任的網域和雲端儲存桶。隨著阻止出現,填入其餘部分。

99 

100## 覆蓋阻止和允許規則

101 

102兩個額外的欄位讓您取代分類器的內建規則清單:`autoMode.soft_deny` 控制被阻止的內容,`autoMode.allow` 控制應用哪些例外。每個都是散文描述的陣列,讀取為自然語言規則。沒有 `autoMode.deny` 欄位;要硬阻止操作而不管意圖,請使用 [`permissions.deny`](/zh-TW/permissions),它在分類器之前執行。

103 

104在分類器內,優先順序分為三個層級:

105 

106* `soft_deny` 規則首先阻止

107* `allow` 規則然後覆蓋匹配的阻止作為例外

108* 明確的使用者意圖覆蓋兩者:如果使用者的訊息直接且具體地描述 Claude 即將採取的確切操作,分類器允許它,即使 `soft_deny` 規則匹配

109 

110一般請求不算作明確意圖。要求 Claude「清理儲存庫」不授權強制推送,但要求 Claude「強制推送此分支」則授權。

111 

112要放寬,當分類器重複標記預設例外不涵蓋的常規模式時,新增到 `allow`。要加強,對於預設值遺漏的特定於您環境的風險,新增到 `soft_deny`。要保留內建規則同時新增您自己的規則,請在陣列中包含字面字串 `"$defaults"`。預設規則會在該位置拼接,因此您的自訂規則可以在它們之前或之後,並且當內建清單在版本發佈中變更時,您繼續繼承更新。

113 

114```json theme={null}

115{

116 "autoMode": {

117 "environment": [

118 "$defaults",

119 "Source control: github.example.com/acme-corp and all repos under it"

120 ],

121 "allow": [

122 "$defaults",

123 "Deploying to the staging namespace is allowed: staging is isolated from production and resets nightly",

124 "Writing to s3://acme-scratch/ is allowed: ephemeral bucket with a 7-day lifecycle policy"

125 ],

126 "soft_deny": [

127 "$defaults",

128 "Never run database migrations outside the migrations CLI, even against dev databases",

129 "Never modify files under infra/terraform/prod/: production infrastructure changes go through the review workflow"

130 ]

131 }

132}

133```

134 

135<Danger>

136 設定 `environment`、`allow` 或 `soft_deny` 中的任何一個而不包含 `"$defaults"` 會取代該部分的整個預設清單。如果您設定 `soft_deny` 為單一項目並省略 `"$defaults"`,每個內建阻止規則都會被丟棄:強制推送、資料外洩、`curl | bash`、生產部署以及所有其他預設阻止規則都變成允許。只在您打算完全掌控清單時才省略 `"$defaults"`。在該情況下,執行 `claude auto-mode defaults` 列印內建規則,將它們複製到您的設定檔案中,然後根據您自己的管道和風險容限檢查每個規則。

137</Danger>

138 

139每個部分獨立評估,因此單獨設定 `environment` 會保持預設 `allow` 和 `soft_deny` 清單完整。

140 

141## 檢查預設值和您的有效設定

142 

143三個 CLI 子命令幫助您檢查和驗證您的設定。

144 

145將內建 `environment`、`allow` 和 `soft_deny` 規則列印為 JSON:

146 

147```bash theme={null}

148claude auto-mode defaults

149```

150 

151列印分類器實際使用的內容為 JSON,在設定的地方應用您的設定,否則使用預設值:

152 

153```bash theme={null}

154claude auto-mode config

155```

156 

157獲得關於您的自訂 `allow` 和 `soft_deny` 規則的 AI 反饋:

158 

159```bash theme={null}

160claude auto-mode critique

161```

162 

163在儲存設定後執行 `claude auto-mode config` 以確認有效規則是您期望的,並且 `"$defaults"` 已展開到位。如果您已編寫自訂規則,`claude auto-mode critique` 會檢查它們並標記模糊、冗餘或可能導致誤報的項目。如果您需要移除或重寫內建規則而不是在其旁邊新增,請將 `claude auto-mode defaults` 的輸出儲存到檔案,編輯清單,並將結果貼到您的設定檔案中以取代 `"$defaults"`。

164 

165## 檢查拒絕

166 

167當自動模式拒絕工具呼叫時,拒絕會記錄在 `/permissions` 下的「最近拒絕」標籤中。在拒絕的操作上按 `r` 將其標記為重試:當您退出對話框時,Claude Code 會傳送一條訊息告訴模型它可能重試該工具呼叫並繼續對話。

168 

169對同一目的地的重複拒絕通常意味著分類器缺少上下文。將該目的地新增到 `autoMode.environment`,然後執行 `claude auto-mode config` 確認它生效。

170 

171要以程式設計方式對拒絕做出反應,請使用 [`PermissionDenied` hook](/zh-TW/hooks#permissiondenied)。

172 

173## 另請參閱

174 

175* [權限模式](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode):自動模式是什麼、它預設阻止什麼以及如何啟用它

176* [受管設定](/zh-TW/server-managed-settings):在您的組織中部署 `autoMode` 設定

177* [權限](/zh-TW/permissions):在分類器執行之前應用的允許、詢問和拒絕規則

178* [設定](/zh-TW/settings):完整的設定參考,包括 `autoMode` 鍵

best-practices.md +583 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Claude Code 最佳實踐

6 

7> 從配置環境到跨平行會話擴展,充分利用 Claude Code 的提示和模式。

8 

9Claude Code 是一個代理式編碼環境。與等待回答問題的聊天機器人不同,Claude Code 可以讀取您的文件、運行命令、進行更改,並在您觀看、重定向或完全離開時自主解決問題。

10 

11這改變了您的工作方式。與其自己編寫代碼並要求 Claude 審查,不如描述您想要的內容,讓 Claude 找出如何構建它。Claude 會探索、規劃和實施。

12 

13但這種自主性仍然伴隨著學習曲線。Claude 在您需要理解的某些約束條件下工作。

14 

15本指南涵蓋了在 Anthropic 內部團隊和在各種代碼庫、語言和環境中使用 Claude Code 的工程師中已被證明有效的模式。有關代理循環如何在幕後工作的信息,請參閱 [Claude Code 如何工作](/zh-TW/how-claude-code-works)。

16 

17***

18 

19大多數最佳實踐都基於一個約束:Claude 的 context window 填滿得很快,隨著填滿,性能會下降。

20 

21Claude 的 context window 保存您的整個對話,包括每條消息、Claude 讀取的每個文件和每個命令輸出。但是,這可能會很快填滿。單個調試會話或代碼庫探索可能會生成並消耗數萬個令牌。

22 

23這很重要,因為隨著 context 填滿,LLM 性能會下降。當 context window 即將滿時,Claude 可能會開始「遺忘」早期的指令或犯更多錯誤。context window 是最重要的資源來管理。要查看會話在實踐中如何填滿,請 [觀看互動式演練](/zh-TW/context-window),了解啟動時加載的內容以及每次文件讀取的成本。使用 [自定義狀態行](/zh-TW/statusline) 持續跟蹤 context 使用情況,並查看 [減少令牌使用](/zh-TW/costs#reduce-token-usage) 以了解減少令牌使用的策略。

24 

25***

26 

27## 給 Claude 一種驗證其工作的方式

28 

29<Tip>

30 包括測試、截圖或預期輸出,以便 Claude 可以檢查自己。這是您可以做的最高槓桿的事情。

31</Tip>

32 

33當 Claude 能夠驗證自己的工作時,例如運行測試、比較截圖和驗證輸出,Claude 的表現會大幅提高。

34 

35沒有明確的成功標準,它可能會產生看起來正確但實際上不起作用的東西。您成為唯一的反饋循環,每個錯誤都需要您的關注。

36 

37| 策略 | 之前 | 之後 |

38| ----------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |

39| **提供驗證標準** | *「實現一個驗證電子郵件地址的函數」* | *「編寫一個 validateEmail 函數。示例測試用例:[user@example.com](mailto:user@example.com) 為真,invalid 為假,[user@.com](mailto:user@.com) 為假。實施後運行測試」* |

40| **以視覺方式驗證 UI 更改** | *「使儀表板看起來更好」* | *「\[粘貼截圖] 實施此設計。對結果進行截圖並與原始設計進行比較。列出差異並修復它們」* |

41| **解決根本原因,而不是症狀** | *「構建失敗」* | *「構建失敗,出現此錯誤:\[粘貼錯誤]。修復它並驗證構建成功。解決根本原因,不要抑制錯誤」* |

42 

43UI 更改可以使用 [Claude Chrome 擴展](/zh-TW/chrome) 進行驗證。它在您的瀏覽器中打開新標籤頁,測試 UI,並迭代直到代碼工作。

44 

45您的驗證也可以是測試套件、linter 或檢查輸出的 Bash 命令。投資使您的驗證堅如磐石。

46 

47***

48 

49## 先探索,然後規劃,然後編碼

50 

51<Tip>

52 將研究和規劃與實施分開,以避免解決錯誤的問題。

53</Tip>

54 

55讓 Claude 直接跳到編碼可能會產生解決錯誤問題的代碼。使用 [Plan Mode](/zh-TW/common-workflows#use-plan-mode-for-safe-code-analysis) 將探索與執行分開。

56 

57推薦的工作流程有四個階段:

58 

59<Steps>

60 <Step title="探索">

61 進入 Plan Mode。Claude 讀取文件並回答問題,不進行任何更改。

62 

63 ```txt claude (Plan Mode) theme={null}

64 read /src/auth and understand how we handle sessions and login.

65 also look at how we manage environment variables for secrets.

66 ```

67 </Step>

68 

69 <Step title="規劃">

70 要求 Claude 創建詳細的實施計劃。

71 

72 ```txt claude (Plan Mode) theme={null}

73 I want to add Google OAuth. What files need to change?

74 What's the session flow? Create a plan.

75 ```

76 

77 按 `Ctrl+G` 在文本編輯器中打開計劃進行直接編輯,然後 Claude 再繼續。

78 </Step>

79 

80 <Step title="實施">

81 切換回正常模式,讓 Claude 編碼,根據其計劃進行驗證。

82 

83 ```txt claude (Normal Mode) theme={null}

84 implement the OAuth flow from your plan. write tests for the

85 callback handler, run the test suite and fix any failures.

86 ```

87 </Step>

88 

89 <Step title="提交">

90 要求 Claude 使用描述性消息進行提交並創建 PR。

91 

92 ```txt claude (Normal Mode) theme={null}

93 commit with a descriptive message and open a PR

94 ```

95 </Step>

96</Steps>

97 

98<Callout>

99 Plan Mode 很有用,但也增加了開銷。

100 

101 對於範圍明確且修復很小的任務(如修復拼寫錯誤、添加日誌行或重命名變量),直接要求 Claude 執行。

102 

103 當您對方法不確定、更改修改多個文件或您不熟悉被修改的代碼時,規劃最有用。如果您可以用一句話描述 diff,請跳過計劃。

104</Callout>

105 

106***

107 

108## 在提示中提供具體的上下文

109 

110<Tip>

111 您的指令越精確,您需要的更正就越少。

112</Tip>

113 

114Claude 可以推斷意圖,但無法讀心術。參考特定文件、提及約束條件並指出示例模式。

115 

116| 策略 | 之前 | 之後 |

117| ------------------------------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------- |

118| **限定任務範圍。** 指定哪個文件、什麼場景和測試偏好。 | *「為 foo.py 添加測試」* | *「為 foo.py 編寫測試,涵蓋用戶已登出的邊界情況。避免使用 mocks。」* |

119| **指向來源。** 指導 Claude 到可以回答問題的來源。 | *「為什麼 ExecutionFactory 有這樣奇怪的 api?」* | *「查看 ExecutionFactory 的 git 歷史記錄並總結其 api 是如何形成的」* |

120| **參考現有模式。** 指向代碼庫中的模式。 | *「添加日曆小部件」* | *「查看主頁上現有小部件的實施方式以了解模式。HotDogWidget.php 是一個很好的例子。按照模式實施一個新的日曆小部件,讓用戶選擇月份並向前/向後分頁以選擇年份。從頭開始構建,除了代碼庫中已使用的庫外,不使用其他庫。」* |

121| **描述症狀。** 提供症狀、可能的位置以及「修復」的樣子。 | *「修復登錄錯誤」* | *「用戶報告會話超時後登錄失敗。檢查 src/auth/ 中的身份驗證流程,特別是令牌刷新。編寫一個失敗的測試來重現問題,然後修復它」* |

122 

123當您在探索並可以承受改正時,模糊的提示可能很有用。像 `「您會改進此文件中的什麼?」` 這樣的提示可以表面您沒有想到要詢問的內容。

124 

125### 提供豐富的內容

126 

127<Tip>

128 使用 `@` 參考文件、粘貼截圖/圖像或直接管道數據。

129</Tip>

130 

131您可以通過多種方式向 Claude 提供豐富的數據:

132 

133* **使用 `@` 參考文件**,而不是描述代碼的位置。Claude 在回應前讀取文件。

134* **直接粘貼圖像**。複製/粘貼或將圖像拖放到提示中。

135* **提供 URL** 用於文檔和 API 參考。使用 `/permissions` 將常用域名列入白名單。

136* **通過運行 `cat error.log | claude` 管道數據**,直接發送文件內容。

137* **讓 Claude 獲取它需要的內容**。告訴 Claude 使用 Bash 命令、MCP 工具或通過讀取文件自己拉取上下文。

138 

139***

140 

141## 配置您的環境

142 

143一些設置步驟使 Claude Code 在所有會話中的效果顯著提高。有關擴展功能的完整概述和何時使用每個功能,請參閱 [擴展 Claude Code](/zh-TW/features-overview)。

144 

145### 編寫有效的 CLAUDE.md

146 

147<Tip>

148 運行 `/init` 根據您當前的項目結構生成一個啟動 CLAUDE.md 文件,然後隨著時間推移進行改進。

149</Tip>

150 

151CLAUDE.md 是一個特殊文件,Claude 在每次對話開始時都會讀取。包括 Bash 命令、代碼風格和工作流規則。這給 Claude 提供了它無法從代碼中推斷出的持久上下文。

152 

153`/init` 命令分析您的代碼庫以檢測構建系統、測試框架和代碼模式,為您提供堅實的基礎進行改進。

154 

155CLAUDE.md 文件沒有必需的格式,但要保持簡短和易於閱讀。例如:

156 

157```markdown CLAUDE.md theme={null}

158# Code style

159- Use ES modules (import/export) syntax, not CommonJS (require)

160- Destructure imports when possible (eg. import { foo } from 'bar')

161 

162# Workflow

163- Be sure to typecheck when you're done making a series of code changes

164- Prefer running single tests, and not the whole test suite, for performance

165```

166 

167CLAUDE.md 在每個會話中加載,因此只包括廣泛適用的內容。對於僅在某些時候相關的域知識或工作流,請改用 [skills](/zh-TW/skills)。Claude 按需加載它們,不會使每次對話都變得臃腫。

168 

169保持簡潔。對於每一行,問自己:*「刪除這一行會導致 Claude 犯錯誤嗎?」* 如果不會,刪除它。臃腫的 CLAUDE.md 文件會導致 Claude 忽略您的實際指令!

170 

171| ✅ 包括 | ❌ 排除 |

172| -------------------- | ---------------------- |

173| Claude 無法猜測的 Bash 命令 | Claude 可以通過讀取代碼找出的任何內容 |

174| 與默認值不同的代碼風格規則 | Claude 已經知道的標準語言約定 |

175| 測試指令和首選測試運行器 | 詳細的 API 文檔(改為鏈接到文檔) |

176| 存儲庫禮儀(分支命名、PR 約定) | 經常變化的信息 |

177| 特定於您項目的架構決策 | 長篇解釋或教程 |

178| 開發人員環境怪癖(必需的環境變量) | 文件逐個描述代碼庫 |

179| 常見陷阱或非顯而易見的行為 | 自明的實踐,如「編寫乾淨代碼」 |

180 

181如果 Claude 儘管有反對規則仍然不斷做您不想要的事情,該文件可能太長,規則被遺漏了。如果 Claude 詢問您在 CLAUDE.md 中回答的問題,措辭可能不明確。像對待代碼一樣對待 CLAUDE.md:當事情出錯時進行審查,定期修剪,並通過觀察 Claude 的行為是否實際改變來測試更改。

182 

183您可以通過添加強調(例如「IMPORTANT」或「YOU MUST」)來調整指令以改進遵守。將文件簽入 git,以便您的團隊可以貢獻。該文件的價值隨著時間的推移而複合。

184 

185CLAUDE.md 文件可以使用 `@path/to/import` 語法導入其他文件:

186 

187```markdown CLAUDE.md theme={null}

188See @README.md for project overview and @package.json for available npm commands.

189 

190# Additional Instructions

191- Git workflow: @docs/git-instructions.md

192- Personal overrides: @~/.claude/my-project-instructions.md

193```

194 

195您可以將 CLAUDE.md 文件放在多個位置:

196 

197* **主文件夾(`~/.claude/CLAUDE.md`)**:適用於所有 Claude 會話

198* **項目根目錄(`./CLAUDE.md`)**:簽入 git 以與您的團隊共享

199* **項目根目錄(`./CLAUDE.local.md`)**:個人項目特定的筆記;將此文件添加到您的 `.gitignore`,以便不與您的團隊共享

200* **父目錄**:對於 monorepos 很有用,其中 `root/CLAUDE.md` 和 `root/foo/CLAUDE.md` 都會自動拉入

201* **子目錄**:當在這些目錄中的文件上工作時,Claude 按需拉入子 CLAUDE.md 文件

202 

203### 配置權限

204 

205<Tip>

206 使用 [auto mode](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode) 讓分類器處理批准,使用 `/permissions` 將特定命令列入白名單,或使用 `/sandbox` 進行操作系統級隔離。每種方式都減少了中斷,同時讓您保持控制。

207</Tip>

208 

209默認情況下,Claude Code 請求可能修改您的系統的操作的權限:文件寫入、Bash 命令、MCP 工具等。這是安全的但很繁瑣。在第十次批准後,您實際上不是在審查,而是在點擊。有三種方法可以減少這些中斷:

210 

211* **Auto mode**:一個單獨的分類器模型審查命令並僅阻止看起來有風險的內容:範圍升級、未知基礎設施或由敵對內容驅動的操作。最適合當您信任任務的總體方向但不想點擊每一步時

212* **權限白名單**:允許您知道安全的特定工具,如 `npm run lint` 或 `git commit`

213* **沙箱**:啟用操作系統級隔離,限制文件系統和網絡訪問,允許 Claude 在定義的邊界內更自由地工作

214 

215閱讀更多關於 [permission modes](/zh-TW/permission-modes)、[permission rules](/zh-TW/permissions) 和 [sandboxing](/zh-TW/sandboxing)。

216 

217### 使用 CLI 工具

218 

219<Tip>

220 告訴 Claude Code 在與外部服務交互時使用 CLI 工具,如 `gh`、`aws`、`gcloud` 和 `sentry-cli`。

221</Tip>

222 

223CLI 工具是與外部服務交互的最 context 高效的方式。如果您使用 GitHub,請安裝 `gh` CLI。Claude 知道如何使用它來創建問題、打開拉取請求和讀取評論。沒有 `gh`,Claude 仍然可以使用 GitHub API,但未經身份驗證的請求經常會達到速率限制。

224 

225Claude 也很擅長學習它不知道的 CLI 工具。嘗試像 `Use 'foo-cli-tool --help' to learn about foo tool, then use it to solve A, B, C.` 這樣的提示。

226 

227### 連接 MCP servers

228 

229<Tip>

230 運行 `claude mcp add` 以連接外部工具,如 Notion、Figma 或您的數據庫。

231</Tip>

232 

233使用 [MCP servers](/zh-TW/mcp),您可以要求 Claude 從問題跟蹤器實施功能、查詢數據庫、分析監控數據、集成來自 Figma 的設計並自動化工作流。

234 

235### 設置 hooks

236 

237<Tip>

238 使用 hooks 進行必須每次發生且沒有例外的操作。

239</Tip>

240 

241[Hooks](/zh-TW/hooks-guide) 在 Claude 工作流中的特定點自動運行腳本。與建議性的 CLAUDE.md 指令不同,hooks 是確定性的,保證操作發生。

242 

243Claude 可以為您編寫 hooks。嘗試像 *「編寫一個在每次文件編輯後運行 eslint 的 hook」* 或 *「編寫一個阻止寫入遷移文件夾的 hook。」* 這樣的提示。編輯 `.claude/settings.json` 直接配置 hooks,並運行 `/hooks` 瀏覽已配置的內容。

244 

245### 創建 skills

246 

247<Tip>

248 在 `.claude/skills/` 中創建 `SKILL.md` 文件,為 Claude 提供域知識和可重用工作流。

249</Tip>

250 

251[Skills](/zh-TW/skills) 使用特定於您的項目、團隊或域的信息擴展 Claude 的知識。Claude 在相關時自動應用它們,或者您可以使用 `/skill-name` 直接調用它們。

252 

253通過將目錄與 `SKILL.md` 添加到 `.claude/skills/` 來創建 skill:

254 

255```markdown .claude/skills/api-conventions/SKILL.md theme={null}

256---

257name: api-conventions

258description: REST API design conventions for our services

259---

260# API Conventions

261- Use kebab-case for URL paths

262- Use camelCase for JSON properties

263- Always include pagination for list endpoints

264- Version APIs in the URL path (/v1/, /v2/)

265```

266 

267Skills 也可以定義您直接調用的可重複工作流:

268 

269```markdown .claude/skills/fix-issue/SKILL.md theme={null}

270---

271name: fix-issue

272description: Fix a GitHub issue

273disable-model-invocation: true

274---

275Analyze and fix the GitHub issue: $ARGUMENTS.

276 

2771. Use `gh issue view` to get the issue details

2782. Understand the problem described in the issue

2793. Search the codebase for relevant files

2804. Implement the necessary changes to fix the issue

2815. Write and run tests to verify the fix

2826. Ensure code passes linting and type checking

2837. Create a descriptive commit message

2848. Push and create a PR

285```

286 

287運行 `/fix-issue 1234` 來調用它。對於具有您想手動觸發的副作用的工作流,使用 `disable-model-invocation: true`。

288 

289### 創建自定義 subagents

290 

291<Tip>

292 在 `.claude/agents/` 中定義專門的助手,Claude 可以委派給它們進行隔離的任務。

293</Tip>

294 

295[Subagents](/zh-TW/sub-agents) 在自己的 context 中運行,具有自己的一組允許的工具。它們對於讀取許多文件或需要專門關注而不會使主對話變得混亂的任務很有用。

296 

297```markdown .claude/agents/security-reviewer.md theme={null}

298---

299name: security-reviewer

300description: Reviews code for security vulnerabilities

301tools: Read, Grep, Glob, Bash

302model: opus

303---

304You are a senior security engineer. Review code for:

305- Injection vulnerabilities (SQL, XSS, command injection)

306- Authentication and authorization flaws

307- Secrets or credentials in code

308- Insecure data handling

309 

310Provide specific line references and suggested fixes.

311```

312 

313明確告訴 Claude 使用 subagents:*「使用 subagent 審查此代碼以查找安全問題。」*

314 

315### 安裝 plugins

316 

317<Tip>

318 運行 `/plugin` 瀏覽市場。Plugins 無需配置即可添加 skills、工具和集成。

319</Tip>

320 

321[Plugins](/zh-TW/plugins) 將 skills、hooks、subagents 和 MCP servers 捆綁到來自社區和 Anthropic 的單個可安裝單元中。如果您使用類型化語言,請安裝 [代碼智能 plugin](/zh-TW/discover-plugins#code-intelligence) 以為 Claude 提供精確的符號導航和編輯後的自動錯誤檢測。

322 

323有關在 skills、subagents、hooks 和 MCP 之間選擇的指導,請參閱 [擴展 Claude Code](/zh-TW/features-overview#match-features-to-your-goal)。

324 

325***

326 

327## 有效溝通

328 

329您與 Claude Code 溝通的方式會顯著影響結果的質量。

330 

331### 詢問代碼庫問題

332 

333<Tip>

334 詢問 Claude 您會問資深工程師的問題。

335</Tip>

336 

337當加入新代碼庫時,使用 Claude Code 進行學習和探索。您可以詢問 Claude 與詢問另一位工程師相同類型的問題:

338 

339* 日誌記錄如何工作?

340* 我如何創建新的 API 端點?

341* `foo.rs` 第 134 行的 `async move { ... }` 做什麼?

342* `CustomerOnboardingFlowImpl` 處理哪些邊界情況?

343* 為什麼此代碼在第 333 行調用 `foo()` 而不是 `bar()`?

344 

345以這種方式使用 Claude Code 是一個有效的入職工作流程,改進了入職時間並減少了對其他工程師的負擔。無需特殊提示:直接提出問題。

346 

347### 讓 Claude 採訪您

348 

349<Tip>

350 對於較大的功能,讓 Claude 先採訪您。從最小的提示開始,並要求 Claude 使用 `AskUserQuestion` 工具採訪您。

351</Tip>

352 

353Claude 會詢問您可能還沒有考慮的事情,包括技術實施、UI/UX、邊界情況和權衡。

354 

355```text theme={null}

356I want to build [brief description]. Interview me in detail using the AskUserQuestion tool.

357 

358Ask about technical implementation, UI/UX, edge cases, concerns, and tradeoffs. Don't ask obvious questions, dig into the hard parts I might not have considered.

359 

360Keep interviewing until we've covered everything, then write a complete spec to SPEC.md.

361```

362 

363規格完成後,開始新會話以執行它。新會話具有完全專注於實施的乾淨 context,您有一個書面規格可供參考。

364 

365***

366 

367## 管理您的會話

368 

369對話是持久的和可逆的。利用這一點!

370 

371### 及早且經常改正方向

372 

373<Tip>

374 一旦您注意到 Claude 偏離軌道,立即改正。

375</Tip>

376 

377最好的結果來自緊密的反饋循環。儘管 Claude 有時會在第一次嘗試時完美地解決問題,但快速改正通常會更快地產生更好的解決方案。

378 

379* **`Esc`**:使用 `Esc` 鍵在中途停止 Claude。Context 被保留,所以您可以重定向。

380* **`Esc + Esc` 或 `/rewind`**:按 `Esc` 兩次或運行 `/rewind` 打開倒帶菜單並恢復之前的對話和代碼狀態,或從選定的消息進行總結。

381* **`「撤銷那個」`**:讓 Claude 恢復其更改。

382* **`/clear`**:在不相關的任務之間重置 context。具有不相關 context 的長會話可能會降低性能。

383 

384如果您在一個會話中對同一問題改正了 Claude 超過兩次,context 就會被失敗的方法所污染。運行 `/clear` 並使用更具體的提示重新開始,該提示包含您學到的內容。具有更好提示的乾淨會話幾乎總是優於具有累積改正的長會話。

385 

386### 積極管理 context

387 

388<Tip>

389 在不相關的任務之間運行 `/clear` 以重置 context。

390</Tip>

391 

392當您接近 context 限制時,Claude Code 會自動壓縮對話歷史記錄,這保留了重要的代碼和決策,同時釋放空間。

393 

394在長會話期間,Claude 的 context window 可能會充滿不相關的對話、文件內容和命令。這可能會降低性能,有時會分散 Claude 的注意力。

395 

396* 在任務之間頻繁使用 `/clear` 以完全重置 context window

397* 當自動壓縮觸發時,Claude 總結最重要的內容,包括代碼模式、文件狀態和關鍵決策

398* 為了更好地控制,運行 `/compact <instructions>`,如 `/compact Focus on the API changes`

399* 要僅壓縮對話的一部分,使用 `Esc + Esc` 或 `/rewind`,選擇消息檢查點,然後選擇 **從此處進行總結**。這會壓縮該點之後的消息,同時保持早期 context 完整。

400* 在 CLAUDE.md 中使用像 `「壓縮時,始終保留完整的修改文件列表和任何測試命令」` 這樣的指令自定義壓縮行為,以確保關鍵 context 在總結中存活。

401* 對於不需要留在 context 中的快速問題,使用 [`/btw`](/zh-TW/interactive-mode#side-questions-with-btw)。答案出現在可關閉的覆蓋層中,永遠不會進入對話歷史記錄,所以您可以檢查詳細信息而不會增加 context。

402 

403### 使用 subagents 進行調查

404 

405<Tip>

406 使用 `「使用 subagents 調查 X」` 委派研究。他們在單獨的 context 中探索,為實施保持您的主對話乾淨。

407</Tip>

408 

409由於 context 是您的基本約束,subagents 是可用的最強大的工具之一。當 Claude 研究代碼庫時,它讀取許多文件,所有這些都會消耗您的 context。Subagents 在單獨的 context windows 中運行並報告回摘要:

410 

411```text theme={null}

412Use subagents to investigate how our authentication system handles token

413refresh, and whether we have any existing OAuth utilities I should reuse.

414```

415 

416subagent 探索代碼庫、讀取相關文件並報告發現,所有這些都不會使您的主對話變得混亂。

417 

418您也可以在 Claude 實施某些內容後使用 subagents 進行驗證:

419 

420```text theme={null}

421use a subagent to review this code for edge cases

422```

423 

424### 使用檢查點倒帶

425 

426<Tip>

427 Claude 進行的每個操作都會創建一個檢查點。您可以將對話、代碼或兩者恢復到任何之前的檢查點。

428</Tip>

429 

430Claude 在更改前自動檢查點。雙擊 `Escape` 或運行 `/rewind` 打開倒帶菜單。您可以僅恢復對話、僅恢復代碼、恢復兩者或從選定的消息進行總結。有關詳細信息,請參閱 [Checkpointing](/zh-TW/checkpointing)。

431 

432與其仔細規劃每一步,不如告訴 Claude 嘗試一些冒險的事情。如果不起作用,倒帶並嘗試不同的方法。檢查點在會話之間持續,所以您可以關閉終端並稍後仍然倒帶。

433 

434<Warning>

435 檢查點僅跟蹤 Claude 進行的更改,不跟蹤外部進程。這不是 git 的替代品。

436</Warning>

437 

438### 恢復對話

439 

440<Tip>

441 運行 `claude --continue` 以從中斷的地方繼續,或 `--resume` 以從最近的會話中選擇。

442</Tip>

443 

444Claude Code 在本地保存對話。當任務跨越多個會話時,您不必重新解釋 context:

445 

446```bash theme={null}

447claude --continue # Resume the most recent conversation

448claude --resume # Select from recent conversations

449```

450 

451使用 `/rename` 給會話起描述性名稱,如 `「oauth-migration」` 或 `「debugging-memory-leak」`,以便您稍後可以找到它們。像對待分支一樣對待會話:不同的工作流可以有單獨的、持久的 contexts。

452 

453***

454 

455## 自動化和擴展

456 

457一旦您對一個 Claude 有效,通過平行會話、非交互模式和扇出模式將您的輸出乘以倍數。

458 

459到目前為止,一切都假設一個人、一個 Claude 和一個對話。但 Claude Code 水平擴展。本節中的技術展示了您如何完成更多工作。

460 

461### 運行非交互模式

462 

463<Tip>

464 在 CI、pre-commit hooks 或腳本中使用 `claude -p "prompt"`。添加 `--output-format stream-json` 以獲得流式 JSON 輸出。

465</Tip>

466 

467使用 `claude -p "your prompt"`,您可以非交互地運行 Claude,不需要會話。非交互模式是您將 Claude 集成到 CI 管道、pre-commit hooks 或任何自動化工作流中的方式。輸出格式讓您以編程方式解析結果:純文本、JSON 或流式 JSON。

468 

469```bash theme={null}

470# One-off queries

471claude -p "Explain what this project does"

472 

473# Structured output for scripts

474claude -p "List all API endpoints" --output-format json

475 

476# Streaming for real-time processing

477claude -p "Analyze this log file" --output-format stream-json

478```

479 

480### 運行多個 Claude 會話

481 

482<Tip>

483 並行運行多個 Claude 會話以加快開發、運行隔離的實驗或啟動複雜的工作流。

484</Tip>

485 

486有三種主要方式來運行平行會話:

487 

488* [Claude Code 桌面應用](/zh-TW/desktop#work-in-parallel-with-sessions):以視覺方式管理多個本地會話。每個會話都有自己的隔離 worktree。

489* [Claude Code 在網絡上](/zh-TW/claude-code-on-the-web):在 Anthropic 的安全雲基礎設施上在隔離的 VM 中運行。

490* [Agent teams](/zh-TW/agent-teams):多個會話的自動協調,具有共享任務、消息和團隊領導。

491 

492除了並行化工作外,多個會話還支持質量聚焦的工作流。新鮮的 context 改進代碼審查,因為 Claude 不會偏向於它剛剛編寫的代碼。

493 

494例如,使用 Writer/Reviewer 模式:

495 

496| 會話 A(Writer) | 會話 B(Reviewer) |

497| -------------------------- | ------------------------------------------------------------------------- |

498| `實施我們 API 端點的速率限制器` | |

499| | `審查 @src/middleware/rateLimiter.ts 中的速率限制器實施。查找邊界情況、競態條件和與我們現有中間件模式的一致性。` |

500| `這是審查反饋:[會話 B 輸出]。解決這些問題。` | |

501 

502您可以對測試做類似的事情:讓一個 Claude 編寫測試,然後另一個編寫代碼來通過它們。

503 

504### 跨文件扇出

505 

506<Tip>

507 循環遍歷任務,為每個任務調用 `claude -p`。使用 `--allowedTools` 為批量操作限定權限。

508</Tip>

509 

510對於大型遷移或分析,您可以在許多平行 Claude 調用中分配工作:

511 

512<Steps>

513 <Step title="生成任務列表">

514 讓 Claude 列出所有需要遷移的文件(例如,`列出所有 2,000 個需要遷移的 Python 文件`)

515 </Step>

516 

517 <Step title="編寫腳本以循環遍歷列表">

518 ```bash theme={null}

519 for file in $(cat files.txt); do

520 claude -p "Migrate $file from React to Vue. Return OK or FAIL." \

521 --allowedTools "Edit,Bash(git commit *)"

522 done

523 ```

524 </Step>

525 

526 <Step title="在幾個文件上測試,然後大規模運行">

527 根據前 2-3 個文件出現的問題改進您的提示,然後在完整集合上運行。`--allowedTools` 標誌限制 Claude 可以做什麼,這在您無人值守運行時很重要。

528 </Step>

529</Steps>

530 

531您也可以將 Claude 集成到現有的數據/處理管道中:

532 

533```bash theme={null}

534claude -p "<your prompt>" --output-format json | your_command

535```

536 

537在開發期間使用 `--verbose` 進行調試,在生產中關閉它。

538 

539### 使用 auto mode 自主運行

540 

541對於不間斷的執行和背景安全檢查,使用 [auto mode](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode)。分類器模型在命令運行前審查它們,阻止範圍升級、未知基礎設施和由敵對內容驅動的操作,同時讓常規工作無提示進行。

542 

543```bash theme={null}

544claude --permission-mode auto -p "fix all lint errors"

545```

546 

547對於使用 `-p` 標誌的非交互運行,如果分類器重複阻止操作,auto mode 會中止,因為沒有用戶可以回退到。請參閱 [auto mode 何時回退](/zh-TW/permission-modes#when-auto-mode-falls-back) 以了解閾值。

548 

549***

550 

551## 避免常見的失敗模式

552 

553這些是常見的錯誤。及早識別它們可以節省時間:

554 

555* **廚房水槽會話。** 您從一個任務開始,然後詢問 Claude 不相關的事情,然後回到第一個任務。Context 充滿了不相關的信息。

556 > **修復**:在不相關的任務之間使用 `/clear`。

557* **一次又一次地改正。** Claude 做錯了什麼,您改正它,它仍然是錯的,您再次改正。Context 被失敗的方法所污染。

558 > **修復**:在兩次失敗的改正後,`/clear` 並編寫一個更好的初始提示,包含您學到的內容。

559* **過度指定的 CLAUDE.md。** 如果您的 CLAUDE.md 太長,Claude 會忽略其中的一半,因為重要的規則在噪音中丟失了。

560 > **修復**:無情地修剪。如果 Claude 已經在沒有指令的情況下正確地做某事,刪除它或將其轉換為 hook。

561* **信任然後驗證的差距。** Claude 產生看起來合理的實施,但不處理邊界情況。

562 > **修復**:始終提供驗證(測試、腳本、截圖)。如果您無法驗證它,不要發布它。

563* **無限探索。** 您要求 Claude「調查」某些內容而不限定範圍。Claude 讀取數百個文件,填滿 context。

564 > **修復**:狹隘地限定調查範圍或使用 subagents,以便探索不會消耗您的主 context。

565 

566***

567 

568## 培養您的直覺

569 

570本指南中的模式不是一成不變的。它們是通常效果很好的起點,但可能不是每種情況的最優選擇。

571 

572有時您\_應該\_讓 context 累積,因為您深入一個複雜的問題,歷史很有價值。有時您應該跳過規劃,讓 Claude 找出答案,因為任務是探索性的。有時模糊的提示正是您想要的,因為您想在限制它之前看到 Claude 如何解釋問題。

573 

574注意什麼有效。當 Claude 產生出色的輸出時,注意您做了什麼:提示結構、您提供的 context、您所在的模式。當 Claude 遇到困難時,問為什麼。Context 太嘈雜了嗎?提示太模糊了嗎?任務對於一次通過來說太大了嗎?

575 

576隨著時間的推移,您將培養沒有指南可以捕捉的直覺。您將知道何時具體以及何時開放,何時規劃以及何時探索,何時清除 context 以及何時讓它累積。

577 

578## 相關資源

579 

580* [Claude Code 如何工作](/zh-TW/how-claude-code-works):代理循環、工具和 context 管理

581* [擴展 Claude Code](/zh-TW/features-overview):skills、hooks、MCP、subagents 和 plugins

582* [常見工作流](/zh-TW/common-workflows):調試、測試、PR 等的分步配方

583* [CLAUDE.md](/zh-TW/memory):存儲項目約定和持久 context

champion-kit.md +191 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Champion kit

6 

7> 工程師在內部倡導 Claude Code 的行動手冊:分享什麼、如何回答問題,以及如何在團隊中推動採用。

8 

9本頁面適用於已經在使用 Claude Code 並想幫助團隊採用它的個別工程師。它涵蓋了要分享什麼、如何回答你將收到的問題、三十天行動手冊,以及對常見疑慮的回應。

10 

11開發者工具的採用很少是因為推出公告而發生的。它發生在團隊中有人開始很好地使用該工具、公開談論它,並使其他人容易跟進的時候。你作為倡導者所做的工作對團隊有不成比例的影響:你分享的每個例子都會縮短後來工程師的學習曲線,你在公開場合回答的每個問題都會將一個人的經驗轉變為整個團隊可以建立的東西。你是在充當團隊的乘數,而不是幫助台,本指南的結構是為了讓這個角色在這些條件下保持可持續性。

12 

13## 倡導者角色

14 

15該角色由三種相互強化的行為組成。

16 

17| 行為 | 實踐中的樣子 | 為什麼重要 |

18| --------- | ---------------------------------------------- | ------------------------------------------------------ |

19| 分享你的發現 | 在你的團隊已經閱讀的地方發佈提示、截圖和小勝利,例如工程頻道、站會線程或拉取請求描述。 | 來自你自己代碼庫的例子比任何外部文檔都更有說服力,因為同事可以看到該工具如何確切地應用於他們與你共享的問題。 |

20| 成為人們提問的對象 | 當同事問你如何完成某事時,用你實際使用的提示進行回應,以便他們可以直接將其應用於自己的任務。 | 一個具體、可運行的例子消除了好奇心和第一次成功使用之間的差距,這是大多數採用工作停滯的地方。 |

21| 擴大圈子 | 建立少量輕量級、定期的習慣,例如專用頻道或每週線程,以便即使你的注意力在別處,動力也能繼續。 | 依賴單一人員的採用是脆弱的。由共享習慣承載的採用會繼續自行複合。 |

22 

23大多數這些自然適應你已經在做的工作。區別在於對你的發現發佈位置和你的答案如何傳播的少量額外意圖。

24 

25### 這應該花費你多少

26 

27與自己和你的主管設定期望。下面的活動旨在適應正常的工作週,該角色應該保持為現有工作的乘數,而不是額外的支持責任。

28 

29| 活動 | 每週時間 | 指導 |

30| ----------- | --------- | ------------------------------------------------------------ |

31| 發佈勝利和提示 | 約 15 分鐘 | 用截圖和一兩句話在當時捕捉這些;避免將它們變成正式的寫作。 |

32| 在共享頻道中回答問題 | 約 20 分鐘 | 公開回答一次,然後當問題再次出現時連結回該答案。 |

33| 主持每週展示和講述線程 | 約 5 分鐘 | 你發佈開場提示;團隊提供內容。 |

34| 可選配對或演練 | 0 到 30 分鐘 | 為真正被卡住的同事保留此項,並在安排時間之前提供 [Quickstart](/zh-TW/quickstart) 連結。 |

35 

36## 分享你的發現

37 

38你自己的經驗是你的同事將遇到的最有說服力的材料,因為它特定於代碼庫、工作流程和你們都共享的問題。文檔告訴人們什麼是可能的;你的帖子向他們展示在你的環境中實際上什麼是有效的。

39 

40### 什麼值得分享

41 

42最有用的帖子描述了同事明天可以重複使用的技術,而不是已經完成的結果。技術在團隊中傳播時會複合;狀態更新則不會。

43 

44可重複使用技術的例子:

45 

46* "我發現 @-提及目錄有效。將其指向 `@src/components/` 並詢問哪些缺少測試,發現了我忽略的兩個。"

47* "Plan mode(`Shift+Tab`)在進行任何編輯之前顯示確切將觸及哪些文件,這就是為什麼我對在共享代碼上使用它感到放心。"

48* "我配置了一個 Stop hook,以便在長任務完成時收到桌面通知。配置在線程中。"

49* "運行 `/init` 從存儲庫生成 `CLAUDE.md`,以便助手停止重新詢問我們的約定。"

50 

51### 在哪裡分享

52 

53在你的團隊已經閱讀的地方發佈。目標是將例子放在正常工作的路徑中,而不是創建一個目的地。

54 

55| 位置 | 最適合 | 推薦格式 |

56| ---------------------- | --------------------------- | -------------------------------- |

57| `#claude-code` 或一般工程頻道 | 發現、提示和"今天我學到"的時刻 | 一個截圖伴隨一兩句上下文 |

58| 拉取請求描述 | 在審查者已經閱讀的真實代碼上演示該方法 | 一行,例如"Claude 和我做了這個重構;很樂意講解該方法。" |

59| 站會或每週書面更新 | 使用正常化與主管和跳級經理 | 一句話描述一個具體結果 |

60| 團隊 wiki 或內部文檔 | 持久的模式、自定義技能和 `CLAUDE.md` 例子 | 一個短頁面,從頻道主題連結,以便它保持可發現性 |

61 

62### 有效的格式

63 

64一個截圖伴隨一行上下文,或簡短的前後描述,通常是正確的細節級別。保持每個帖子足夠短,以便滾動經過的人仍然吸收要點。長寫作往往被保存以供稍後使用並被遺忘,而帶有截圖的短帖子往往被複製和嘗試。

65 

66下面的例子帖子說明了語氣和長度;適應它們而不是逐字複製。

67 

68```text theme={null}

69今天學到 @-提及目錄有效。我將其指向 @src/components/ 並詢問哪些

70組件缺少測試,它發現了我忘記的兩個。

71```

72 

73```text theme={null}

74我配置了一個 Stop hook,以便在長任務完成時收到桌面通知。我開始

75了一個重構,走開了,並在完成時收到通知。配置在線程中。

76```

77 

78```text theme={null}

79Plan mode 是我對在重要代碼上使用它感到放心的原因。按 Shift+Tab

80直到你看到"plan";它在更改任何內容之前精確列出它打算觸及的文件。

81```

82 

83## 成為人們提問的對象

84 

85一旦你分享了幾個例子,問題就會隨之而來。這是倡導者角色具有最大槓桿作用的地方,因為對一個人的好答案經常會解除其他幾個正在觀看同一頻道的人的困境。

86 

87### 用提示而不是解釋來回答

88 

89當同事問你如何完成某事時,最有用的回應是你實際使用的提示。他們將通過針對自己的問題運行該提示學到更多,而不是從你可以寫的任何描述,並且它給了他們可以立即採取行動的東西。

90 

91```text theme={null}

92同事:你是如何發現那個競態條件的?

93 

94倡導者:我問,"@tests/scheduler.test.ts 中的測試不穩定,找出原因,"

95它追蹤了調度程序中的兩個未加入的承諾。在你的測試上嘗試相同的措辭。

96```

97 

98### 指向功能而不是文檔

99 

100"嘗試 plan mode,按 `Shift+Tab` 直到你看到它"這樣的回應在當時比文檔連結更有用。如果該人稍後需要更多深度,他們會自己找到;現在他們需要解除困境的單一事物。

101 

102### 你可能會聽到的問題

103 

104| 問題 | 建議回應 | 後續資源 |

105| --------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------- |

106| "我應該首先在什麼上嘗試它?" | 推薦一個真實但有限的任務,理想情況下是一個你一直推遲的錯誤或雜務,因為它很繁瑣而不是困難。 | [Common workflows](/zh-TW/common-workflows) |

107| "我如何相信它處理我的代碼?" | 介紹 plan mode:按 `Shift+Tab` 循環進入它,Claude 精確提議它打算更改什麼,在用戶批准之前不修改任何內容。 | [Permissions](/zh-TW/permissions) |

108| "設置值得付出努力嗎?" | 安裝大約需要兩分鐘,在終端中運行,不需要 IDE 擴展。運行一次 `/init` 足以開始工作。 | [Quickstart](/zh-TW/quickstart) |

109| "它產生了不正確的結果。" | 鼓勵他們將失敗提供回 Claude。粘貼錯誤消息或失敗的測試遠比重新表述原始請求更有效。 | [Common workflows](/zh-TW/common-workflows) |

110| "它不理解我們的代碼庫約定。" | 建議運行 `/init` 生成 `CLAUDE.md` 文件,然後添加團隊的約定、測試命令和任何應避免的目錄。 | [Memory](/zh-TW/memory) |

111| "這只是自動完成嗎?" | 提供一個簡短的演示,其中 Claude 解釋一個不熟悉的文件、跨服務追蹤錯誤或起草遷移計劃。這些任務需要在存儲庫中進行推理,而不是完成單一行。 | 一個兩分鐘的現場演示 |

112| "安全和數據處理呢?" | 將此問題轉介給你的管理員。你的組織的部署和數據處理政策已經配置,倡導者不應該即興回答此問題。 | [Security](/zh-TW/security) · [Data usage](/zh-TW/data-usage) |

113 

114## 擴大圈子

115 

116目標不是建立一個程序或擁有推出。它是建立少量輕量級習慣,以便即使你停止主動推動它,動力也能繼續。當頻道中的問題被除你之外的人回答時,該角色已經完成了它的工作。

117 

118### 傾向於有效的模式

119 

120| 模式 | 如何運行它 | 所需努力 |

121| ------------- | ------------------------------------------------------------------------------------------------------------- | ------------ |

122| 專用頻道 | 創建一個 `#claude-code` 頻道(或現有頻道中的定期線程),固定 [Quickstart](/zh-TW/quickstart) 連結和一個強大的例子,並公開回答問題,以便每個答案都使觀看的每個人受益。 | 大約五分鐘設置,然後環境 |

123| 每週展示和講述線程 | 每個星期五,發佈"Claude 本週幫助你做了什麼?"不需要準備、幻燈片或會議;截圖和簡短描述就足夠了。 | 每週約兩分鐘 |

124| 分享自定義技能 | 發佈你最有用的 `.claude/skills/<name>/SKILL.md` 文件,例如一個 `/ship` 技能,在提交前運行測試和 lint,帶有一行描述。因為技能是純 Markdown,同事可以立即採用它們。 | 每個技能約五分鐘 |

125| 從你自己的使用生成設置指南 | 在你花費真實時間的項目中運行 `/team-onboarding`。Claude 掃描你最近的會話、命令和 MCP 服務器,然後生成一個新隊友可以粘貼為他們的第一條消息以重放你的設置的指南。在頻道中固定它。 | 約兩分鐘 |

126| 配對第一個任務 | 為任何開始的人提供一個十五分鐘的配對會話。他們自己代碼上的一個成功結果比任何演示都更有說服力。 | 每人約十五分鐘 |

127| 識別下一個倡導者 | 問你最多問題的同事通常已經準備好承擔這個角色。轉發他們這個頁面並在你之間分配頻道責任。 | 可忽略不計 |

128 

129### 三十天行動手冊

130 

131如果一個寬鬆的計劃有幫助,下面的序列反映了在大多數團隊中傾向於有效的東西。自由調整以適應你的背景。

132 

133<Steps>

134 <Step title="第 1 週:播種頻道">

135 創建頻道,固定 [Quickstart](/zh-TW/quickstart),並發佈兩三個你自己的例子,包括提示。

136 

137 **表明它有效的信號:** 幾個同事做出反應或回覆,至少在頻道中提出一個問題。

138 </Step>

139 

140 <Step title="第 2 週:開始節奏">

141 開始每週展示和講述線程,公開回答每個問題,並分享一個自定義技能或 `CLAUDE.md` 片段。

142 

143 **表明它有效的信號:** 除你之外的人發佈他們自己的例子。

144 </Step>

145 

146 <Step title="第 3 週:配對和整合">

147 提供兩三個短配對會話,並將最常見的問題和答案整合到一個固定的常見問題消息中。

148 

149 **表明它有效的信號:** 你看到重複使用,同樣的同事返回而不是嘗試一次然後停止。

150 </Step>

151 

152 <Step title="第 4 週:交接">

153 識別第二個倡導者,並與你的主管或管理員分享什麼有效和什麼無效的簡要總結。

154 

155 **表明它有效的信號:** 頻道中的問題由除你之外的人回答。

156 </Step>

157</Steps>

158 

159### 當有人想深入時

160 

161你是溫暖的介紹而不是入職計劃。當同事從"我應該嘗試這個嗎"進入"我如何有效地使用它"時,指向他們 [Quickstart](/zh-TW/quickstart) 和 [Common workflows](/zh-TW/common-workflows) 頁面。它們包含涵蓋真正有用但難以自己發現的功能的簡短部分。

162 

163## 回應常見疑慮

164 

165健康的懷疑是預期的;工程師應該對觸及他們代碼的工具保持謹慎。最有效的回應很少是論證一般情況。相反,承認疑慮,提供簡短的重新框架,並在該人自己的代碼上提議一個具體的演示。大多數疑慮通過單一成功的經驗得到解決。

166 

167| 疑慮 | 建議回應 | 提供的證據 |

168| ----------------- | ------------------------------------------------------------------------ | ------------------------ |

169| "我沒有它更快。" | 這對該人日常編寫的代碼可能是真的。建議在他們傾向於避免的工作上嘗試它:遺留文件、不熟悉的服務或測試腳手架,其中槓桿最高。 | 計時一個繁瑣的任務兩種方式並比較。 |

170| "我不相信 AI 觸及生產代碼。" | 同意沒有更改應該在未閱讀的情況下登陸。Plan mode 結合正常的 diff 審查意味著沒有應用工程師未檢查的內容,與任何拉取請求相同的標準。 | 在真實文件上演示 plan mode。 |

171| "它會使初級工程師變弱。" | 使用得當,它是一個有效的解釋者。鼓勵初級工程師在要求它更改任何內容之前要求 Claude 解釋一個文件及其調用站點。 | 一起運行"解釋 @file 及其被調用的位置"。 |

172| "我嘗試過一次,它產生了幻覺。" | 這通常是上下文問題而不是模型問題。@-提及相關文件、運行 `/init` 和提供實際錯誤輸出通常會解決它。 | 用適當的 `@` 上下文重新運行他們的原始提示。 |

173| "我們沒有時間學習另一個工具。" | Claude Code 是一個終端命令而不是平台。如果它在第一個會話中不返回價值,設置它是合理的。 | 兩分鐘安裝後跟一個真實錯誤。 |

174 

175## 快速參考表

176 

177下面的技術是最可靠地將某人從第一次試驗轉移到日常使用的技術。在頻道中固定此表或單獨分享它。

178 

179| 技術 | 如何應用它 |

180| ---------- | ---------------------------------------------------------------------------------------------- |

181| 提供正確的上下文 | 使用 `@file` 或 `@directory/` 參考,或直接粘貼錯誤或日誌輸出。提供相關上下文比精心製作的提示更有效。 |

182| 在編輯前審查計劃 | 按 `Shift+Tab` 進入 plan mode。Claude 將在執行之前描述預期的更改以供你批准。 |

183| 教它你的存儲庫 | 運行 `/init` 生成 `CLAUDE.md` 文件,然後添加你的約定、測試命令和任何不應修改的目錄。見 [Memory](/zh-TW/memory)。 |

184| 重複使用工作流程 | 在 `.claude/skills/<name>/` 中保存 `SKILL.md` 文件以創建整個團隊可以使用的 `/name` 技能。見 [Skills](/zh-TW/skills)。 |

185| 在長任務期間保持知情 | 配置一個 Stop hook 以在長時間運行的任務完成時收到桌面通知。見 [Hooks](/zh-TW/hooks-guide)。 |

186| 從不正確的結果恢復 | 與其重新表述請求,不如將失敗的測試或堆棧跟蹤粘貼回 Claude,並要求它解決該特定失敗。 |

187| 保持編輯精確 | 要求一個 diff,或指定"只更改 X。"Claude 在陳述範圍時尊重範圍。 |

188 

189<Tip>

190 Claude Code 經常更新。在內部分發此材料之前,根據 [documentation home page](/zh-TW/overview) 驗證版本特定的詳細信息。

191</Tip>

channels.md +357 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 使用 channels 將事件推送到執行中的工作階段

6 

7> 使用 channels 從 MCP 伺服器將訊息、警報和 webhooks 推送到您的 Claude Code 工作階段。轉發 CI 結果、聊天訊息和監控事件,讓 Claude 在您不在時做出反應。

8 

9<Note>

10 Channels 處於[研究預覽](#research-preview)階段,需要 Claude Code v2.1.80 或更新版本。它們需要 claude.ai 登入。不支援 Console 和 API 金鑰驗證。Team 和 Enterprise 組織必須[明確啟用它們](#enterprise-controls)。

11</Note>

12 

13Channel 是一個 MCP 伺服器,可將事件推送到您執行中的 Claude Code 工作階段,讓 Claude 能對您不在終端時發生的事情做出反應。Channels 可以是雙向的:Claude 讀取事件並通過同一 channel 回覆,就像聊天橋接一樣。事件只在工作階段開啟時到達,因此對於始終開啟的設定,您可以在背景程序或持久終端中執行 Claude。

14 

15與產生新鮮雲端工作階段或等待輪詢的整合不同,事件到達您已開啟的工作階段:請參閱 [channels 如何比較](#how-channels-compare)。

16 

17您將 channel 安裝為外掛程式,並使用您自己的認證進行設定。Telegram、Discord 和 iMessage 包含在研究預覽中。

18 

19當 Claude 通過 channel 回覆時,您會在終端中看到入站訊息,但看不到回覆文字。終端顯示工具呼叫和確認(如「已傳送」),實際回覆會出現在另一個平台上。

20 

21本頁涵蓋:

22 

23* [支援的 channels](#supported-channels):Telegram、Discord 和 iMessage 設定

24* [安裝並執行 channel](#quickstart),使用 fakechat(本地主機演示)

25* [誰可以推送訊息](#security):寄件者允許清單以及您如何配對

26* [為您的組織啟用 channels](#enterprise-controls)(Team 和 Enterprise)

27* [Channels 如何比較](#how-channels-compare)網路工作階段、Slack、MCP 和遠端控制

28 

29若要建立您自己的 channel,請參閱 [Channels 參考](/zh-TW/channels-reference)。

30 

31## 支援的 channels

32 

33每個支援的 channel 都是需要 [Bun](https://bun.sh) 的外掛程式。如需在連接真實平台之前親身體驗外掛程式流程的演示,請嘗試 [fakechat 快速入門](#quickstart)。

34 

35<Tabs>

36 <Tab title="Telegram">

37 檢視完整的 [Telegram 外掛程式原始碼](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/telegram)。

38 

39 <Steps>

40 <Step title="建立 Telegram 機器人">

41 在 Telegram 中開啟 [BotFather](https://t.me/BotFather) 並傳送 `/newbot`。給它一個顯示名稱和一個以 `bot` 結尾的唯一使用者名稱。複製 BotFather 返回的權杖。

42 </Step>

43 

44 <Step title="安裝外掛程式">

45 在 Claude Code 中,執行:

46 

47 ```

48 /plugin install telegram@claude-plugins-official

49 ```

50 

51 如果 Claude Code 報告在任何市場中找不到該外掛程式,您的市場可能遺失或已過期。執行 `/plugin marketplace update claude-plugins-official` 以重新整理它,或如果您之前未新增過,執行 `/plugin marketplace add anthropics/claude-plugins-official`。然後重試安裝。

52 

53 安裝後,執行 `/reload-plugins` 以啟用外掛程式的設定命令。

54 </Step>

55 

56 <Step title="設定您的權杖">

57 使用來自 BotFather 的權杖執行設定命令:

58 

59 ```

60 /telegram:configure <token>

61 ```

62 

63 這會將其儲存到 `~/.claude/channels/telegram/.env`。您也可以在啟動 Claude Code 之前在 shell 環境中設定 `TELEGRAM_BOT_TOKEN`。

64 </Step>

65 

66 <Step title="在啟用 channels 的情況下重新啟動">

67 退出 Claude Code 並使用 channel 旗標重新啟動。這會啟動 Telegram 外掛程式,開始輪詢來自您機器人的訊息:

68 

69 ```bash theme={null}

70 claude --channels plugin:telegram@claude-plugins-official

71 ```

72 </Step>

73 

74 <Step title="配對您的帳戶">

75 開啟 Telegram 並向您的機器人傳送任何訊息。機器人會回覆配對代碼。

76 

77 <Note>如果您的機器人沒有回應,請確保 Claude Code 使用上一步的 `--channels` 執行。機器人只能在 channel 處於活動狀態時回覆。</Note>

78 

79 回到 Claude Code,執行:

80 

81 ```

82 /telegram:access pair <code>

83 ```

84 

85 然後鎖定存取權,使只有您的帳戶可以傳送訊息:

86 

87 ```

88 /telegram:access policy allowlist

89 ```

90 </Step>

91 </Steps>

92 </Tab>

93 

94 <Tab title="Discord">

95 檢視完整的 [Discord 外掛程式原始碼](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/discord)。

96 

97 <Steps>

98 <Step title="建立 Discord 機器人">

99 前往 [Discord 開發者入口網站](https://discord.com/developers/applications),按一下**新應用程式**,並為其命名。在**機器人**部分中,建立使用者名稱,然後按一下**重設權杖**並複製權杖。

100 </Step>

101 

102 <Step title="啟用訊息內容意圖">

103 在您的機器人設定中,向下捲動至**特權閘道意圖**並啟用**訊息內容意圖**。

104 </Step>

105 

106 <Step title="邀請機器人加入您的伺服器">

107 前往 **OAuth2 > URL 產生器**。選擇 `bot` 範圍並啟用這些權限:

108 

109 * 檢視頻道

110 * 傳送訊息

111 * 在執行緒中傳送訊息

112 * 讀取訊息歷史記錄

113 * 附加檔案

114 * 新增反應

115 

116 開啟產生的 URL 以將機器人新增到您的伺服器。

117 </Step>

118 

119 <Step title="安裝外掛程式">

120 在 Claude Code 中,執行:

121 

122 ```

123 /plugin install discord@claude-plugins-official

124 ```

125 

126 如果 Claude Code 報告在任何市場中找不到該外掛程式,您的市場可能遺失或已過期。執行 `/plugin marketplace update claude-plugins-official` 以重新整理它,或如果您之前未新增過,執行 `/plugin marketplace add anthropics/claude-plugins-official`。然後重試安裝。

127 

128 安裝後,執行 `/reload-plugins` 以啟用外掛程式的設定命令。

129 </Step>

130 

131 <Step title="設定您的權杖">

132 使用您複製的機器人權杖執行設定命令:

133 

134 ```

135 /discord:configure <token>

136 ```

137 

138 這會將其儲存到 `~/.claude/channels/discord/.env`。您也可以在啟動 Claude Code 之前在 shell 環境中設定 `DISCORD_BOT_TOKEN`。

139 </Step>

140 

141 <Step title="在啟用 channels 的情況下重新啟動">

142 退出 Claude Code 並使用 channel 旗標重新啟動。這會連接 Discord 外掛程式,讓您的機器人可以接收和回應訊息:

143 

144 ```bash theme={null}

145 claude --channels plugin:discord@claude-plugins-official

146 ```

147 </Step>

148 

149 <Step title="配對您的帳戶">

150 在 Discord 上直接訊息您的機器人。機器人會回覆配對代碼。

151 

152 <Note>如果您的機器人沒有回應,請確保 Claude Code 使用上一步的 `--channels` 執行。機器人只能在 channel 處於活動狀態時回覆。</Note>

153 

154 回到 Claude Code,執行:

155 

156 ```

157 /discord:access pair <code>

158 ```

159 

160 然後鎖定存取權,使只有您的帳戶可以傳送訊息:

161 

162 ```

163 /discord:access policy allowlist

164 ```

165 </Step>

166 </Steps>

167 </Tab>

168 

169 <Tab title="iMessage">

170 檢視完整的 [iMessage 外掛程式原始碼](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/imessage)。

171 

172 iMessage channel 直接讀取您的訊息資料庫,並通過 AppleScript 傳送回覆。它需要 macOS,不需要機器人權杖或外部服務。

173 

174 <Steps>

175 <Step title="授予完整磁碟存取權">

176 位於 `~/Library/Messages/chat.db` 的訊息資料庫受 macOS 保護。伺服器第一次讀取它時,macOS 會提示存取:按一下**允許**。提示會命名啟動 Bun 的任何應用程式,例如終端、iTerm 或您的 IDE。

177 

178 如果提示未出現或您按一下「不允許」,請在**系統設定 > 隱私與安全 > 完整磁碟存取**下手動授予存取權,並新增您的終端。沒有這個,伺服器會立即退出,並顯示 `authorization denied`。

179 </Step>

180 

181 <Step title="安裝外掛程式">

182 在 Claude Code 中,執行:

183 

184 ```

185 /plugin install imessage@claude-plugins-official

186 ```

187 

188 如果 Claude Code 報告在任何市場中找不到該外掛程式,您的市場可能遺失或已過期。執行 `/plugin marketplace update claude-plugins-official` 以重新整理它,或如果您之前未新增過,執行 `/plugin marketplace add anthropics/claude-plugins-official`。然後重試安裝。

189 </Step>

190 

191 <Step title="在啟用 channels 的情況下重新啟動">

192 退出 Claude Code 並使用 channel 旗標重新啟動:

193 

194 ```bash theme={null}

195 claude --channels plugin:imessage@claude-plugins-official

196 ```

197 </Step>

198 

199 <Step title="傳送訊息給自己">

200 在任何登入您 Apple ID 的裝置上開啟訊息,並向自己傳送訊息。它立即到達 Claude:自聊天繞過存取控制,無需設定。

201 

202 <Note>Claude 傳送的第一個回覆會觸發 macOS 自動化提示,詢問您的終端是否可以控制訊息。按一下 **OK**。</Note>

203 </Step>

204 

205 <Step title="允許其他寄件者">

206 預設情況下,只有您自己的訊息通過。若要讓另一個聯絡人到達 Claude,請新增其控制代碼:

207 

208 ```

209 /imessage:access allow +15551234567

210 ```

211 

212 控制代碼是 `+country` 格式的電話號碼或 Apple ID 電子郵件,例如 `user@example.com`。

213 </Step>

214 </Steps>

215 </Tab>

216</Tabs>

217 

218您也可以[建立您自己的 channel](/zh-TW/channels-reference),用於尚未有外掛程式的系統。

219 

220## 快速入門

221 

222Fakechat 是一個官方支援的演示 channel,在 localhost 上執行聊天 UI,無需驗證,也無需設定外部服務。

223 

224安裝並啟用 fakechat 後,您可以在瀏覽器中輸入,訊息會到達您的 Claude Code 工作階段。Claude 回覆,回覆會顯示在瀏覽器中。測試 fakechat 介面後,嘗試 [Telegram](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/telegram)、[Discord](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/discord) 或 [iMessage](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/imessage)。

225 

226若要嘗試 fakechat 演示,您需要:

227 

228* Claude Code [已安裝並使用 claude.ai 帳戶進行驗證](/zh-TW/quickstart#step-1-install-claude-code)

229* [Bun](https://bun.sh) 已安裝。預先建立的 channel 外掛程式是 Bun 指令碼。使用 `bun --version` 檢查;如果失敗,[安裝 Bun](https://bun.sh/docs/installation)。

230* **Team/Enterprise 使用者**:您的組織管理員必須在受管設定中[啟用 channels](#enterprise-controls)

231 

232<Steps>

233 <Step title="安裝 fakechat channel 外掛程式">

234 啟動 Claude Code 工作階段並執行安裝命令:

235 

236 ```text theme={null}

237 /plugin install fakechat@claude-plugins-official

238 ```

239 

240 如果 Claude Code 報告在任何市場中找不到該外掛程式,您的市場可能遺失或已過期。執行 `/plugin marketplace update claude-plugins-official` 以重新整理它,或如果您之前未新增過,執行 `/plugin marketplace add anthropics/claude-plugins-official`。然後重試安裝。

241 </Step>

242 

243 <Step title="在啟用 channel 的情況下重新啟動">

244 退出 Claude Code,然後使用 `--channels` 重新啟動並傳遞您安裝的 fakechat 外掛程式:

245 

246 ```bash theme={null}

247 claude --channels plugin:fakechat@claude-plugins-official

248 ```

249 

250 fakechat 伺服器會自動啟動。

251 

252 <Tip>

253 您可以將多個外掛程式傳遞到 `--channels`,以空格分隔。

254 </Tip>

255 </Step>

256 

257 <Step title="推送訊息進去">

258 在 [http://localhost:8787](http://localhost:8787) 開啟 fakechat UI 並輸入訊息:

259 

260 ```text theme={null}

261 hey, what's in my working directory?

262 ```

263 

264 訊息作為 `<channel source="fakechat">` 事件到達您的 Claude Code 工作階段。Claude 讀取它,完成工作,並呼叫 fakechat 的 `reply` 工具。答案會顯示在聊天 UI 中。

265 </Step>

266</Steps>

267 

268如果 Claude 在您不在終端時遇到權限提示,工作階段會暫停,直到您回應。宣告[權限中繼功能](/zh-TW/channels-reference#relay-permission-prompts)的 Channel 伺服器可以將這些提示轉發給您,以便您可以遠端批准或拒絕。對於無人值守使用,[`--dangerously-skip-permissions`](/zh-TW/permission-modes#skip-all-checks-with-bypasspermissions-mode) 完全繞過提示,但僅在您信任的環境中使用。

269 

270## 安全性

271 

272每個已批准的 channel 外掛程式都維護寄件者允許清單:只有您新增的 ID 可以推送訊息,其他所有人都會被無聲地丟棄。

273 

274Telegram 和 Discord 通過配對啟動清單:

275 

2761. 在 Telegram 或 Discord 中找到您的機器人並向其傳送任何訊息

2772. 機器人回覆配對代碼

2783. 在您的 Claude Code 工作階段中,在提示時批准代碼

2794. 您的寄件者 ID 會新增到允許清單

280 

281iMessage 的工作方式不同:向自己傳送訊息會自動繞過閘道,您可以使用 `/imessage:access allow` 按控制代碼新增其他聯絡人。

282 

283除此之外,您可以使用 `--channels` 控制每個工作階段啟用哪些伺服器,在 Team 和 Enterprise 計畫上,您的組織可以使用 [`channelsEnabled`](#enterprise-controls) 控制可用性。

284 

285在 `.mcp.json` 中還不足以推送訊息:伺服器也必須在 `--channels` 中命名。

286 

287允許清單也會閘道[權限中繼](/zh-TW/channels-reference#relay-permission-prompts)(如果 channel 宣告它)。任何可以通過 channel 回覆的人都可以批准或拒絕您工作階段中的工具使用,因此只允許清單您信任具有該權限的寄件者。

288 

289## Enterprise 控制

290 

291在 Team 和 Enterprise 計畫上,channels 預設為關閉。管理員通過兩個[受管設定](/zh-TW/settings)控制可用性,使用者無法覆蓋:

292 

293| 設定 | 目的 | 未設定時 |

294| :---------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- | :---------------- |

295| `channelsEnabled` | 主開關。必須為 `true` 才能讓任何 channel 傳遞訊息。通過 [claude.ai 管理員主控台](https://claude.ai/admin-settings/claude-code)切換或直接在受管設定中設定。關閉時會阻止所有 channels,包括開發旗標。 | Channels 被阻止 |

296| `allowedChannelPlugins` | 啟用 channels 後可以註冊哪些外掛程式。設定時替換 Anthropic 維護的清單。僅在 `channelsEnabled` 為 `true` 時適用。 | 應用 Anthropic 預設清單 |

297 

298沒有組織的 Pro 和 Max 使用者完全跳過這些檢查:channels 可用,使用者按工作階段選擇加入 `--channels`。

299 

300### 為您的組織啟用 channels

301 

302管理員可以從 [**claude.ai → 管理員設定 → Claude Code → Channels**](https://claude.ai/admin-settings/claude-code) 啟用 channels,或通過在受管設定中將 `channelsEnabled` 設定為 `true`。

303 

304啟用後,您組織中的使用者可以使用 `--channels` 將 channel 伺服器選擇加入個別工作階段。如果設定已停用或未設定,MCP 伺服器仍會連接,其工具可以工作,但 channel 訊息不會到達。啟動警告會告訴使用者讓管理員啟用該設定。

305 

306### 限制可以執行哪些 channel 外掛程式

307 

308預設情況下,Anthropic 維護的允許清單上的任何外掛程式都可以註冊為 channel。Team 和 Enterprise 計畫上的管理員可以通過在受管設定中設定 `allowedChannelPlugins` 來用自己的清單替換該允許清單。使用此功能來限制允許哪些官方外掛程式、批准來自您自己的內部市場的 channels,或兩者。每個條目命名一個外掛程式及其來自的市場:

309 

310```json theme={null}

311{

312 "channelsEnabled": true,

313 "allowedChannelPlugins": [

314 { "marketplace": "claude-plugins-official", "plugin": "telegram" },

315 { "marketplace": "claude-plugins-official", "plugin": "discord" },

316 { "marketplace": "acme-corp-plugins", "plugin": "internal-alerts" }

317 ]

318}

319```

320 

321設定 `allowedChannelPlugins` 時,它完全替換 Anthropic 允許清單:只有列出的外掛程式可以註冊。保持未設定以回退到預設 Anthropic 允許清單。空陣列會阻止允許清單中的所有 channel 外掛程式,但 `--dangerously-load-development-channels` 仍可以為本地測試繞過它。若要完全阻止 channels,包括開發旗標,請改為保持 `channelsEnabled` 未設定。

322 

323此設定需要 `channelsEnabled: true`。如果使用者傳遞一個不在您清單上的外掛程式到 `--channels`,Claude Code 會正常啟動,但 channel 不會註冊,啟動通知會解釋該外掛程式不在組織的已批准清單上。

324 

325## 研究預覽

326 

327Channels 是研究預覽功能。可用性正在逐步推出,`--channels` 旗標語法和協議合約可能會根據回饋而改變。

328 

329在預覽期間,`--channels` 只接受來自 Anthropic 維護的允許清單的外掛程式,或來自您組織的允許清單(如果管理員已設定 [`allowedChannelPlugins`](#restrict-which-channel-plugins-can-run))。[claude-plugins-official](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins) 中的 channel 外掛程式是預設已批准的集合。如果您傳遞不在有效允許清單上的東西,Claude Code 會正常啟動,但 channel 不會註冊,啟動通知會告訴您原因。

330 

331若要測試您正在建立的 channel,請使用 `--dangerously-load-development-channels`。請參閱[在研究預覽期間測試](/zh-TW/channels-reference#test-during-the-research-preview),以取得有關測試您建立的自訂 channels 的資訊。

332 

333在 [Claude Code GitHub 儲存庫](https://github.com/anthropics/claude-code/issues)上報告問題或回饋。

334 

335## Channels 如何比較

336 

337Claude Code 的多個功能連接到終端外的系統,每個都適合不同類型的工作:

338 

339| 功能 | 它的作用 | 適合 |

340| ------------------------------------------------- | -------------------------------------- | -------------------- |

341| [網路上的 Claude Code](/zh-TW/claude-code-on-the-web) | 在新鮮雲端沙箱中執行任務,從 GitHub 複製 | 委派您稍後檢查的自包含非同步工作 |

342| [Slack 中的 Claude](/zh-TW/slack) | 從頻道或執行緒中的 `@Claude` 提及產生網路工作階段 | 直接從團隊對話內容啟動任務 |

343| 標準 [MCP 伺服器](/zh-TW/mcp) | Claude 在任務期間查詢它;沒有任何東西被推送到工作階段 | 讓 Claude 按需存取讀取或查詢系統 |

344| [遠端控制](/zh-TW/remote-control) | 您從 claude.ai 或 Claude 行動應用程式驅動您的本地工作階段 | 在遠離您的桌子時引導進行中的工作階段 |

345 

346Channels 通過將來自非 Claude 來源的事件推送到您已執行的本地工作階段,填補該清單中的空白。

347 

348* **聊天橋接**:通過 Telegram、Discord 或 iMessage 從您的手機詢問 Claude 一些事情,答案會在同一聊天中返回,而工作在您的機器上針對您的真實檔案執行。

349* **[Webhook 接收器](/zh-TW/channels-reference#example-build-a-webhook-receiver)**:來自 CI、您的錯誤追蹤器、部署管道或其他外部服務的 webhook 到達 Claude 已開啟您的檔案並記得您正在調試的地方。

350 

351## 後續步驟

352 

353一旦您有 channel 執行,請探索這些相關功能:

354 

355* [建立您自己的 channel](/zh-TW/channels-reference),用於尚未有外掛程式的系統

356* [遠端控制](/zh-TW/remote-control),從您的手機驅動本地工作階段,而不是將事件轉發到其中

357* [排程任務](/zh-TW/scheduled-tasks),按計時器輪詢,而不是對推送事件做出反應

channels-reference.md +749 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Channels 參考

6 

7> 建立一個 MCP 伺服器,將 webhooks、警報和聊天訊息推送到 Claude Code 工作階段。頻道合約的參考:功能聲明、通知事件、回覆工具、寄件者閘道和權限中繼。

8 

9<Note>

10 Channels 處於[研究預覽](/zh-TW/channels#research-preview)階段,需要 Claude Code v2.1.80 或更新版本。它們需要 claude.ai 登入。不支援 Console 和 API 金鑰驗證。Team 和 Enterprise 組織必須[明確啟用它們](/zh-TW/channels#enterprise-controls)。

11</Note>

12 

13Channel 是一個 MCP 伺服器,將事件推送到 Claude Code 工作階段,以便 Claude 可以對終端機外發生的事情做出反應。

14 

15您可以建立單向或雙向 channel。單向 channel 轉發警報、webhooks 或監控事件供 Claude 處理。雙向 channel(如聊天橋接)也會[公開回覆工具](#expose-a-reply-tool),以便 Claude 可以傳送訊息回去。具有受信任寄件者路徑的 channel 也可以選擇加入[中繼權限提示](#relay-permission-prompts),以便您可以遠端批准或拒絕工具使用。

16 

17本頁涵蓋:

18 

19* [概述](#overview):channels 如何運作

20* [您需要什麼](#what-you-need):要求和一般步驟

21* [範例:建立 webhook 接收器](#example-build-a-webhook-receiver):最小單向逐步解說

22* [伺服器選項](#server-options):建構函式欄位

23* [通知格式](#notification-format):事件承載

24* [公開回覆工具](#expose-a-reply-tool):讓 Claude 傳送訊息回去

25* [閘道入站訊息](#gate-inbound-messages):寄件者檢查以防止提示注入

26* [中繼權限提示](#relay-permission-prompts):將工具批准提示轉發到遠端 channels

27 

28若要使用現有 channel 而不是建立一個,請參閱 [Channels](/zh-TW/channels)。Telegram、Discord、iMessage 和 fakechat 包含在研究預覽中。

29 

30## 概述

31 

32Channel 是在與 Claude Code 相同的機器上執行的 [MCP](https://modelcontextprotocol.io) 伺服器。Claude Code 將其作為子程序生成並透過 stdio 進行通訊。您的 channel 伺服器是外部系統和 Claude Code 工作階段之間的橋接:

33 

34* **聊天平台**(Telegram、Discord):您的外掛程式在本機執行並輪詢平台的 API 以取得新訊息。當有人傳送 DM 給您的機器人時,外掛程式會接收訊息並將其轉發給 Claude。無需公開 URL。

35* **Webhooks**(CI、監控):您的伺服器在本機 HTTP 連接埠上監聽。外部系統 POST 到該連接埠,您的伺服器將承載推送給 Claude。

36 

37<img src="https://mintlify.s3.us-west-1.amazonaws.com/claude-code/zh-TW/images/channel-architecture.svg" alt="架構圖,顯示外部系統連接到您的本機 channel 伺服器,該伺服器透過 stdio 與 Claude Code 通訊" />

38 

39## 您需要什麼

40 

41唯一的硬性要求是 [`@modelcontextprotocol/sdk`](https://www.npmjs.com/package/@modelcontextprotocol/sdk) 套件和 Node.js 相容的執行時。[Bun](https://bun.sh)、[Node](https://nodejs.org) 和 [Deno](https://deno.com) 都可以運作。研究預覽中的預先建立外掛程式使用 Bun,但您的 channel 不一定要。

42 

43您的伺服器需要:

44 

451. 聲明 `claude/channel` 功能,以便 Claude Code 註冊通知監聽器

462. 當發生某事時發出 `notifications/claude/channel` 事件

473. 透過 [stdio transport](https://modelcontextprotocol.io/docs/concepts/transports#standard-io) 連接(Claude Code 將您的伺服器作為子程序生成)

48 

49[伺服器選項](#server-options)和[通知格式](#notification-format)部分詳細涵蓋每一項。請參閱[範例:建立 webhook 接收器](#example-build-a-webhook-receiver)以取得完整逐步解說。

50 

51在研究預覽期間,自訂 channels 不在[核准允許清單](/zh-TW/channels#supported-channels)上。使用 `--dangerously-load-development-channels` 在本機測試。請參閱[在研究預覽期間測試](#test-during-the-research-preview)以取得詳細資訊。

52 

53## 範例:建立 webhook 接收器

54 

55本逐步解說建立一個單一檔案伺服器,該伺服器監聽 HTTP 要求並將其轉發到您的 Claude Code 工作階段。最後,任何可以傳送 HTTP POST 的東西(如 CI 管道、監控警報或 `curl` 命令)都可以將事件推送給 Claude。

56 

57此範例使用 [Bun](https://bun.sh) 作為執行時,用於其內建 HTTP 伺服器和 TypeScript 支援。您可以改用 [Node](https://nodejs.org) 或 [Deno](https://deno.com);唯一的要求是 [MCP SDK](https://www.npmjs.com/package/@modelcontextprotocol/sdk)。

58 

59<Steps>

60 <Step title="建立專案">

61 建立新目錄並安裝 MCP SDK:

62 

63 ```bash theme={null}

64 mkdir webhook-channel && cd webhook-channel

65 bun add @modelcontextprotocol/sdk

66 ```

67 </Step>

68 

69 <Step title="編寫 channel 伺服器">

70 建立名為 `webhook.ts` 的檔案。這是您的整個 channel 伺服器:它透過 stdio 連接到 Claude Code,並在連接埠 8788 上監聽 HTTP POST。當要求到達時,它將主體作為 channel 事件推送給 Claude。

71 

72 ```ts title="webhook.ts" theme={null}

73 #!/usr/bin/env bun

74 import { Server } from '@modelcontextprotocol/sdk/server/index.js'

75 import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'

76 

77 // 建立 MCP 伺服器並將其聲明為 channel

78 const mcp = new Server(

79 { name: 'webhook', version: '0.0.1' },

80 {

81 // 這個金鑰是使其成為 channel 的原因 — Claude Code 為其註冊監聽器

82 capabilities: { experimental: { 'claude/channel': {} } },

83 // 新增到 Claude 的系統提示,以便它知道如何處理這些事件

84 instructions: 'Events from the webhook channel arrive as <channel source="webhook" ...>. They are one-way: read them and act, no reply expected.',

85 },

86 )

87 

88 // 透過 stdio 連接到 Claude Code(Claude Code 生成此程序)

89 await mcp.connect(new StdioServerTransport())

90 

91 // 啟動 HTTP 伺服器,將每個 POST 轉發給 Claude

92 Bun.serve({

93 port: 8788, // 任何開放連接埠都可以

94 // 僅限 localhost:此機器外的任何東西都無法 POST

95 hostname: '127.0.0.1',

96 async fetch(req) {

97 const body = await req.text()

98 await mcp.notification({

99 method: 'notifications/claude/channel',

100 params: {

101 content: body, // 成為 <channel> 標籤的主體

102 // 每個金鑰都成為標籤屬性,例如 <channel path="/" method="POST">

103 meta: { path: new URL(req.url).pathname, method: req.method },

104 },

105 })

106 return new Response('ok')

107 },

108 })

109 ```

110 

111 該檔案按順序執行三項操作:

112 

113 * **伺服器配置**:使用 `claude/channel` 在其功能中建立 MCP 伺服器,這是告訴 Claude Code 這是 channel 的原因。[`instructions`](#server-options) 字串進入 Claude 的系統提示:告訴 Claude 期望什麼事件、是否回覆,以及如果應該回覆,使用哪個工具和傳遞回哪個屬性(如 `chat_id`)。

114 * **Stdio 連接**:透過 stdin/stdout 連接到 Claude Code。這對任何 [MCP 伺服器](https://modelcontextprotocol.io/docs/concepts/transports#standard-io) 都是標準的:Claude Code 將其作為子程序生成。

115 * **HTTP 監聽器**:在連接埠 8788 上啟動本機網頁伺服器。每個 POST 主體都透過 `mcp.notification()` 作為 channel 事件轉發給 Claude。`content` 成為事件主體,每個 `meta` 項目成為 `<channel>` 標籤上的屬性。監聽器需要存取 `mcp` 實例,因此它在同一程序中執行。對於較大的專案,您可以將其分割成單獨的模組。

116 </Step>

117 

118 <Step title="向 Claude Code 註冊您的伺服器">

119 將伺服器新增到您的 MCP 配置,以便 Claude Code 知道如何啟動它。對於同一目錄中的專案層級 `.mcp.json`,使用相對路徑。對於 `~/.claude.json` 中的使用者層級配置,使用完整絕對路徑,以便可以從任何專案找到伺服器:

120 

121 ```json title=".mcp.json" theme={null}

122 {

123 "mcpServers": {

124 "webhook": { "command": "bun", "args": ["./webhook.ts"] }

125 }

126 }

127 ```

128 

129 Claude Code 在啟動時讀取您的 MCP 配置並將每個伺服器作為子程序生成。

130 </Step>

131 

132 <Step title="測試它">

133 在研究預覽期間,自訂 channels 不在允許清單上,因此使用開發旗標啟動 Claude Code:

134 

135 ```bash theme={null}

136 claude --dangerously-load-development-channels server:webhook

137 ```

138 

139 當 Claude Code 啟動時,它讀取您的 MCP 配置,將您的 `webhook.ts` 作為子程序生成,HTTP 監聽器自動在您配置的連接埠上啟動(此範例中為 8788)。您不需要自己執行伺服器。

140 

141 如果您看到'被組織政策阻止',您的 Team 或 Enterprise 管理員需要先[啟用 channels](/zh-TW/channels#enterprise-controls)。

142 

143 在單獨的終端機中,透過傳送帶有訊息的 HTTP POST 來模擬 webhook 到您的伺服器。此範例將 CI 失敗警報傳送到連接埠 8788(或您配置的任何連接埠):

144 

145 ```bash theme={null}

146 curl -X POST localhost:8788 -d "build failed on main: https://ci.example.com/run/1234"

147 ```

148 

149 承載作為 `<channel>` 標籤到達您的 Claude Code 工作階段:

150 

151 ```text theme={null}

152 <channel source="webhook" path="/" method="POST">build failed on main: https://ci.example.com/run/1234</channel>

153 ```

154 

155 在您的 Claude Code 終端機中,您會看到 Claude 接收訊息並開始回應:讀取檔案、執行命令或訊息要求的任何內容。這是一個單向 channel,因此 Claude 在您的工作階段中採取行動,但不會透過 webhook 傳送任何內容回去。若要新增回覆,請參閱[公開回覆工具](#expose-a-reply-tool)。

156 

157 如果事件未到達,診斷取決於 `curl` 返回的內容:

158 

159 * **`curl` 成功但沒有任何內容到達 Claude**:在您的工作階段中執行 `/mcp` 以檢查伺服器的狀態。「無法連接」通常表示伺服器檔案中的相依性或匯入錯誤;檢查 `~/.claude/debug/<session-id>.txt` 的偵錯日誌以取得 stderr 追蹤。

160 * **`curl` 失敗,出現「連接被拒絕」**:連接埠要麼尚未繫結,要麼來自較早執行的過時程序正在佔用它。`lsof -i :<port>` 顯示正在監聽的內容;在重新啟動工作階段之前 `kill` 過時程序。

161 </Step>

162</Steps>

163 

164[fakechat 伺服器](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/fakechat)使用網頁 UI、檔案附件和用於雙向聊天的回覆工具擴展此模式。

165 

166## 在研究預覽期間測試

167 

168在研究預覽期間,每個 channel 都必須在[核准允許清單](/zh-TW/channels#research-preview)上才能註冊。開發旗標在確認提示後繞過特定項目的允許清單。此範例顯示兩種項目類型:

169 

170```bash theme={null}

171# 測試您正在開發的外掛程式

172claude --dangerously-load-development-channels plugin:yourplugin@yourmarketplace

173 

174# 測試裸 .mcp.json 伺服器(尚無外掛程式包裝)

175claude --dangerously-load-development-channels server:webhook

176```

177 

178繞過是按項目進行的。將此旗標與 `--channels` 結合不會將繞過擴展到 `--channels` 項目。在研究預覽期間,核准允許清單由 Anthropic 策劃,因此您的 channel 在您建立和測試時保持在開發旗標上。

179 

180<Note>

181 此旗標僅跳過允許清單。`channelsEnabled` 組織政策仍然適用。不要使用它來執行來自不受信任來源的 channels。

182</Note>

183 

184## 伺服器選項

185 

186Channel 在 [`Server`](https://modelcontextprotocol.io/docs/concepts/servers) 建構函式中設定這些選項。`instructions` 和 `capabilities.tools` 欄位是[標準 MCP](https://modelcontextprotocol.io/docs/concepts/servers);`capabilities.experimental['claude/channel']` 和 `capabilities.experimental['claude/channel/permission']` 是 channel 特定的新增項目:

187 

188| 欄位 | 類型 | 描述 |

189| :------------------------------------------------------- | :------- | :------------------------------------------------------------------------------------------------------------------------------ |

190| `capabilities.experimental['claude/channel']` | `object` | 必需。始終為 `{}`。存在會註冊通知監聽器。 |

191| `capabilities.experimental['claude/channel/permission']` | `object` | 選用。始終為 `{}`。聲明此 channel 可以接收權限中繼要求。聲明時,Claude Code 會將工具批准提示轉發到您的 channel,以便您可以遠端批准或拒絕它們。請參閱[中繼權限提示](#relay-permission-prompts)。 |

192| `capabilities.tools` | `object` | 僅限雙向。始終為 `{}`。標準 MCP 工具功能。請參閱[公開回覆工具](#expose-a-reply-tool)。 |

193| `instructions` | `string` | 建議。新增到 Claude 的系統提示。告訴 Claude 期望什麼事件、`<channel>` 標籤屬性的含義、是否回覆,如果是,使用哪個工具以及傳遞回哪個屬性(如 `chat_id`)。 |

194 

195若要建立單向 channel,請省略 `capabilities.tools`。此範例顯示設定了 channel 功能、工具和指示的雙向設定:

196 

197```ts theme={null}

198import { Server } from '@modelcontextprotocol/sdk/server/index.js'

199 

200const mcp = new Server(

201 { name: 'your-channel', version: '0.0.1' },

202 {

203 capabilities: {

204 experimental: { 'claude/channel': {} }, // 註冊 channel 監聽器

205 tools: {}, // 對於單向 channels 省略

206 },

207 // 新增到 Claude 的系統提示,以便它知道如何處理您的事件

208 instructions: 'Messages arrive as <channel source="your-channel" ...>. Reply with the reply tool.',

209 },

210)

211```

212 

213若要推送事件,請使用方法 `notifications/claude/channel` 呼叫 `mcp.notification()`。參數在下一部分中。

214 

215## 通知格式

216 

217您的伺服器發出 `notifications/claude/channel` 和兩個參數:

218 

219| 欄位 | 類型 | 描述 |

220| :-------- | :----------------------- | :------------------------------------------------------------------------------------------------ |

221| `content` | `string` | 事件主體。作為 `<channel>` 標籤的主體傳遞。 |

222| `meta` | `Record<string, string>` | 選用。每個項目成為 `<channel>` 標籤上的屬性,用於路由上下文,如聊天 ID、寄件者名稱或警報嚴重性。金鑰必須是識別碼:僅限字母、數字和底線。包含連字號或其他字元的金鑰會被無聲地捨棄。 |

223 

224您的伺服器透過在 `Server` 實例上呼叫 `mcp.notification()` 來推送事件。此範例推送帶有兩個中繼金鑰的 CI 失敗警報:

225 

226```ts theme={null}

227await mcp.notification({

228 method: 'notifications/claude/channel',

229 params: {

230 content: 'build failed on main: https://ci.example.com/run/1234',

231 meta: { severity: 'high', run_id: '1234' },

232 },

233})

234```

235 

236事件在 Claude 的上下文中到達,包裝在 `<channel>` 標籤中。`source` 屬性從您的伺服器配置的名稱自動設定:

237 

238```text theme={null}

239<channel source="your-channel" severity="high" run_id="1234">

240build failed on main: https://ci.example.com/run/1234

241</channel>

242```

243 

244## 公開回覆工具

245 

246如果您的 channel 是雙向的(如聊天橋接而不是警報轉發器),請公開標準 [MCP 工具](https://modelcontextprotocol.io/docs/concepts/tools),Claude 可以呼叫該工具來傳送訊息回去。工具註冊沒有任何 channel 特定的內容。回覆工具有三個元件:

247 

2481. 您的 `Server` 建構函式功能中的 `tools: {}` 項目,以便 Claude Code 發現工具

2492. 定義工具架構並實現傳送邏輯的工具處理程式

2503. 您的 `Server` 建構函式中的 `instructions` 字串,告訴 Claude 何時以及如何呼叫工具

251 

252若要將這些新增到上面的 [webhook 接收器](#example-build-a-webhook-receiver):

253 

254<Steps>

255 <Step title="啟用工具發現">

256 在 `webhook.ts` 中的 `Server` 建構函式中,將 `tools: {}` 新增到功能,以便 Claude Code 知道您的伺服器提供工具:

257 

258 ```ts theme={null}

259 capabilities: {

260 experimental: { 'claude/channel': {} },

261 tools: {}, // 啟用工具發現

262 },

263 ```

264 </Step>

265 

266 <Step title="註冊回覆工具">

267 將以下內容新增到 `webhook.ts`。`import` 位於檔案頂部,與您的其他匯入一起;兩個處理程式位於 `Server` 建構函式和 `mcp.connect()` 之間。這會註冊一個 `reply` 工具,Claude 可以使用 `chat_id` 和 `text` 呼叫:

268 

269 ```ts theme={null}

270 // 在 webhook.ts 頂部新增此匯入

271 import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'

272 

273 // Claude 在啟動時查詢此項以發現您的伺服器提供什麼工具

274 mcp.setRequestHandler(ListToolsRequestSchema, async () => ({

275 tools: [{

276 name: 'reply',

277 description: 'Send a message back over this channel',

278 // inputSchema 告訴 Claude 要傳遞什麼引數

279 inputSchema: {

280 type: 'object',

281 properties: {

282 chat_id: { type: 'string', description: 'The conversation to reply in' },

283 text: { type: 'string', description: 'The message to send' },

284 },

285 required: ['chat_id', 'text'],

286 },

287 }],

288 }))

289 

290 // Claude 想要叫用工具時呼叫此項

291 mcp.setRequestHandler(CallToolRequestSchema, async req => {

292 if (req.params.name === 'reply') {

293 const { chat_id, text } = req.params.arguments as { chat_id: string; text: string }

294 // send() 是您的出站:POST 到您的聊天平台,或用於本機

295 // 測試下面完整範例中顯示的 SSE 廣播。

296 send(`Reply to ${chat_id}: ${text}`)

297 return { content: [{ type: 'text', text: 'sent' }] }

298 }

299 throw new Error(`unknown tool: ${req.params.name}`)

300 })

301 ```

302 </Step>

303 

304 <Step title="更新指示">

305 更新 `Server` 建構函式中的 `instructions` 字串,以便 Claude 知道透過工具將回覆路由回去。此範例告訴 Claude 從入站標籤傳遞 `chat_id`:

306 

307 ```ts theme={null}

308 instructions: 'Messages arrive as <channel source="webhook" chat_id="...">. Reply with the reply tool, passing the chat_id from the tag.'

309 ```

310 </Step>

311</Steps>

312 

313以下是具有雙向支援的完整 `webhook.ts`。出站回覆透過 `GET /events` 使用 [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) (SSE) 串流,因此 `curl -N localhost:8788/events` 可以即時觀看它們;入站聊天到達 `POST /`:

314 

315```ts title="Full webhook.ts with reply tool' expandable theme={null}

316#!/usr/bin/env bun

317import { Server } from '@modelcontextprotocol/sdk/server/index.js'

318import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'

319import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'

320 

321// --- 出站:寫入 /events 上任何 curl -N 監聽器 ---

322// 真實橋接會改為 POST 到您的聊天平台。

323const listeners = new Set<(chunk: string) => void>()

324function send(text: string) {

325 const chunk = text.split('\n').map(l => `data: ${l}\n`).join('') + '\n'

326 for (const emit of listeners) emit(chunk)

327}

328 

329const mcp = new Server(

330 { name: 'webhook', version: '0.0.1' },

331 {

332 capabilities: {

333 experimental: { 'claude/channel': {} },

334 tools: {},

335 },

336 instructions: 'Messages arrive as <channel source="webhook" chat_id="...">. Reply with the reply tool, passing the chat_id from the tag.',

337 },

338)

339 

340mcp.setRequestHandler(ListToolsRequestSchema, async () => ({

341 tools: [{

342 name: 'reply',

343 description: 'Send a message back over this channel',

344 inputSchema: {

345 type: 'object',

346 properties: {

347 chat_id: { type: 'string', description: 'The conversation to reply in' },

348 text: { type: 'string', description: 'The message to send' },

349 },

350 required: ['chat_id', 'text'],

351 },

352 }],

353}))

354 

355mcp.setRequestHandler(CallToolRequestSchema, async req => {

356 if (req.params.name === 'reply') {

357 const { chat_id, text } = req.params.arguments as { chat_id: string; text: string }

358 send(`Reply to ${chat_id}: ${text}`)

359 return { content: [{ type: 'text', text: 'sent' }] }

360 }

361 throw new Error(`unknown tool: ${req.params.name}`)

362})

363 

364await mcp.connect(new StdioServerTransport())

365 

366let nextId = 1

367Bun.serve({

368 port: 8788,

369 hostname: '127.0.0.1',

370 idleTimeout: 0, // 不要關閉閒置 SSE 串流

371 async fetch(req) {

372 const url = new URL(req.url)

373 

374 // GET /events:SSE 串流,所以 curl -N 可以即時觀看 Claude 的回覆

375 if (req.method === 'GET' && url.pathname === '/events') {

376 const stream = new ReadableStream({

377 start(ctrl) {

378 ctrl.enqueue(': connected\n\n') // 所以 curl 立即顯示某些內容

379 const emit = (chunk: string) => ctrl.enqueue(chunk)

380 listeners.add(emit)

381 req.signal.addEventListener('abort', () => listeners.delete(emit))

382 },

383 })

384 return new Response(stream, {

385 headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' },

386 })

387 }

388 

389 // POST:作為 channel 事件轉發給 Claude

390 const body = await req.text()

391 const chat_id = String(nextId++)

392 await mcp.notification({

393 method: 'notifications/claude/channel',

394 params: {

395 content: body,

396 meta: { chat_id, path: url.pathname, method: req.method },

397 },

398 })

399 return new Response('ok')

400 },

401})

402```

403 

404[fakechat 伺服器](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/fakechat)顯示了一個更完整的範例,具有檔案附件和訊息編輯。

405 

406## 閘道入站訊息

407 

408未閘道的 channel 是提示注入向量。任何可以到達您的端點的人都可以在 Claude 前面放置文字。監聽聊天平台或公開端點的 channel 在發出任何內容之前需要真正的寄件者檢查。

409 

410在呼叫 `mcp.notification()` 之前,根據允許清單檢查寄件者。此範例捨棄來自不在集合中的寄件者的任何訊息:

411 

412```ts theme={null}

413const allowed = new Set(loadAllowlist()) // 從您的 access.json 或等效項

414 

415// 在您的訊息處理程式中,在發出之前:

416if (!allowed.has(message.from.id)) { // 寄件者,不是房間

417 return // 無聲地捨棄

418}

419await mcp.notification({ ... })

420```

421 

422根據寄件者的身份而不是聊天或房間身份進行閘道:範例中的 `message.from.id`,而不是 `message.chat.id`。在群組聊天中,這些不同,根據房間進行閘道會讓允許清單群組中的任何人將訊息注入到工作階段中。

423 

424[Telegram](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/telegram) 和 [Discord](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/discord) channels 以相同方式根據寄件者允許清單進行閘道。它們透過配對啟動清單:使用者傳送 DM 給機器人,機器人回覆配對代碼,使用者在其 Claude Code 工作階段中批准它,其平台 ID 被新增。請參閱任一實現以取得完整配對流程。[iMessage](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/imessage) channel 採用不同的方法:它在啟動時從 Messages 資料庫偵測使用者自己的位址並自動讓它們通過,其他寄件者按控制代碼新增。

425 

426## 中繼權限提示

427 

428<Note>

429 權限中繼需要 Claude Code v2.1.81 或更新版本。較早版本會忽略 `claude/channel/permission` 功能。

430</Note>

431 

432當 Claude 呼叫需要批准的工具時,本機終端機對話框開啟,工作階段等待。雙向 channel 可以選擇加入以在平行接收相同提示,並將其中繼到您在另一台裝置上。兩者都保持活躍:您可以在終端機或手機上回答,Claude Code 應用先到達的答案並關閉另一個。

433 

434中繼涵蓋工具使用批准,如 Bash、Write 和 Edit。專案信任和 MCP 伺服器同意對話框不中繼;這些僅在本機終端機中出現。

435 

436### 中繼如何運作

437 

438當權限提示開啟時,中繼迴圈有四個步驟:

439 

4401. Claude Code 生成短要求 ID 並通知您的伺服器

4412. 您的伺服器將提示和 ID 轉發到您的聊天應用

4423. 遠端使用者回覆是或否以及該 ID

4434. 您的入站處理程式將回覆解析為判決,Claude Code 僅在 ID 符合開啟要求時應用它

444 

445本機終端機對話框在所有這一切中保持開啟。如果終端機上的某人在遠端判決到達之前回答,該答案會改為應用,待處理的遠端要求會被捨棄。

446 

447<img src="https://mintlify.s3.us-west-1.amazonaws.com/claude-code/zh-TW/images/channel-permission-relay.svg" alt="序列圖:Claude Code 傳送 permission_request 通知到 channel 伺服器,伺服器格式化並傳送提示到聊天應用,人類回覆判決,伺服器將該回覆解析為權限通知回到 Claude Code" />

448 

449### 權限要求欄位

450 

451來自 Claude Code 的出站通知是 `notifications/claude/channel/permission_request`。像[頻道通知](#notification-format)一樣,傳輸是標準 MCP,但方法和架構是 Claude Code 擴展。`params` 物件有四個字串欄位,您的伺服器將其格式化為出站提示:

452 

453| 欄位 | 描述 |

454| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |

455| `request_id` | 五個小寫字母,從 `a`-`z` 中抽取,不包括 `l`,因此在手機上輸入時永遠不會讀作 `1` 或 `I`。將其包含在您的出站提示中,以便可以在回覆中回顯。Claude Code 僅接受帶有其發出的 ID 的判決。本機終端機對話框不顯示此 ID,因此您的出站處理程式是了解它的唯一方式。 |

456| `tool_name` | Claude 想要使用的工具的名稱,例如 `Bash` 或 `Write`。 |

457| `description` | 此特定工具呼叫執行的操作的人類可讀摘要,與本機終端機對話框顯示的文字相同。對於 Bash 呼叫,這是 Claude 對命令的描述,或如果未給出,則是命令本身。 |

458| `input_preview` | 工具的引數作為 JSON 字串,截斷為 200 個字元。對於 Bash,這是命令;對於 Write,它是檔案路徑和內容的前綴。如果您只有一行訊息的空間,請從您的提示中省略它。您的伺服器決定要顯示什麼。 |

459 

460您的伺服器傳送回的判決是 `notifications/claude/channel/permission`,有兩個欄位:`request_id` 回顯上面的 ID,`behavior` 設定為 `'allow'` 或 `'deny'`。允許讓工具呼叫繼續;拒絕會拒絕它,與在本機對話框中回答'否'相同。兩個判決都不影響未來的呼叫。

461 

462### 將中繼新增到聊天橋接

463 

464將權限中繼新增到雙向 channel 需要三個元件:

465 

4661. 您的 `Server` 建構函式中 `experimental` 功能下的 `claude/channel/permission: {}` 項目,以便 Claude Code 知道轉發提示

4672. `notifications/claude/channel/permission_request` 的通知處理程式,格式化提示並透過您的平台 API 傳送出去

4683. 您的入站訊息處理程式中的檢查,識別 `yes <id>` 或 `no <id>` 並發出 `notifications/claude/channel/permission` 判決通知,而不是將文字轉發給 Claude

469 

470僅在您的 channel [驗證寄件者](#gate-inbound-messages)時聲明功能,因為任何可以透過您的 channel 回覆的人都可以批准或拒絕您工作階段中的工具使用。

471 

472若要將這些新增到[公開回覆工具](#expose-a-reply-tool)中組裝的雙向聊天橋接:

473 

474<Steps>

475 <Step title="聲明權限功能">

476 在您的 `Server` 建構函式中,在 `experimental` 下的 `claude/channel` 旁邊新增 `claude/channel/permission: {}`:

477 

478 ```ts theme={null}

479 capabilities: {

480 experimental: {

481 'claude/channel': {},

482 'claude/channel/permission': {}, // 選擇加入權限中繼

483 },

484 tools: {},

485 },

486 ```

487 </Step>

488 

489 <Step title="處理傳入要求">

490 在您的 `Server` 建構函式和 `mcp.connect()` 之間註冊通知處理程式。當權限對話框開啟時,Claude Code 使用[四個要求欄位](#permission-request-fields)呼叫它。您的處理程式為您的平台格式化提示,並包含使用 ID 回覆的指示:

491 

492 ```ts theme={null}

493 import { z } from 'zod'

494 

495 // setNotificationHandler 透過方法欄位上的 z.literal 進行路由,

496 // 所以此架構既是驗證器又是分派金鑰

497 const PermissionRequestSchema = z.object({

498 method: z.literal('notifications/claude/channel/permission_request'),

499 params: z.object({

500 request_id: z.string(), // 五個小寫字母,在您的提示中逐字包含

501 tool_name: z.string(), // 例如 "Bash"、"Write"

502 description: z.string(), // 此呼叫的人類可讀摘要

503 input_preview: z.string(), // 工具引數作為 JSON,截斷至 ~200 個字元

504 }),

505 })

506 

507 mcp.setNotificationHandler(PermissionRequestSchema, async ({ params }) => {

508 // send() 是您的出站:POST 到您的聊天平台,或用於本機

509 // 測試下面完整範例中顯示的 SSE 廣播。

510 send(

511 `Claude wants to run ${params.tool_name}: ${params.description}\n\n` +

512 // 指示中的 ID 是您的入站處理程式在步驟 3 中解析的內容

513 `Reply "yes ${params.request_id}" or "no ${params.request_id}"`,

514 )

515 })

516 ```

517 </Step>

518 

519 <Step title="在您的入站處理程式中攔截判決">

520 您的入站處理程式是接收來自您的平台的訊息的迴圈或回呼:與您[根據寄件者進行閘道](#gate-inbound-messages)和發出 `notifications/claude/channel` 以將聊天轉發給 Claude 的地方相同。在聊天轉發呼叫之前新增檢查,識別判決格式並改為發出權限通知。

521 

522 正規表達式符合 Claude Code 生成的 ID 格式:五個字母,永遠不是 `l`。`/i` 旗標容許手機自動更正將回覆大寫;在傳送回之前將擷取的 ID 小寫。

523 

524 ```ts theme={null}

525 // 符合 "y abcde"、"yes abcde"、"n abcde"、"no abcde"

526 // [a-km-z] 是 Claude Code 使用的 ID 字母表(小寫,跳過 'l')

527 // /i 容許手機自動更正;在傳送前小寫擷取

528 const PERMISSION_REPLY_RE = /^\s*(y|yes|n|no)\s+([a-km-z]{5})\s*$/i

529 

530 async function onInbound(message: PlatformMessage) {

531 if (!allowed.has(message.from.id)) return // 首先根據寄件者進行閘道

532 

533 const m = PERMISSION_REPLY_RE.exec(message.text)

534 if (m) {

535 // m[1] 是判決詞,m[2] 是要求 ID

536 // 改為將判決通知發出回 Claude Code,而不是聊天

537 await mcp.notification({

538 method: 'notifications/claude/channel/permission',

539 params: {

540 request_id: m[2].toLowerCase(), // 在自動更正大寫的情況下正規化

541 behavior: m[1].toLowerCase().startsWith('y') ? 'allow' : 'deny',

542 },

543 })

544 return // 作為判決處理,不要也轉發為聊天

545 }

546 

547 // 不符合判決格式:落入正常聊天路徑

548 await mcp.notification({

549 method: 'notifications/claude/channel',

550 params: { content: message.text, meta: { chat_id: String(message.chat.id) } },

551 })

552 }

553 ```

554 </Step>

555</Steps>

556 

557Claude Code 也保持本機終端機對話框開啟,因此您可以在任一位置回答,先到達的答案會被應用。不完全符合預期格式的遠端回覆以兩種方式之一失敗,在兩種情況下對話框都保持開啟:

558 

559* **不同格式**:您的入站處理程式的正規表達式無法符合,因此 `approve it` 或 `yes` 之類的文字(沒有 ID)會作為正常訊息落入 Claude。

560* **正確格式,錯誤 ID**:您的伺服器發出判決,但 Claude Code 找不到具有該 ID 的開啟要求並無聲地捨棄它。

561 

562### 完整範例

563 

564下面組裝的 `webhook.ts` 結合了本頁的所有三個擴展:回覆工具、寄件者閘道和權限中繼。如果您從這裡開始,您還需要初始逐步解說中的[專案設定和 `.mcp.json` 項目](#example-build-a-webhook-receiver)。

565 

566為了使兩個方向都可以從 curl 測試,HTTP 監聽器提供兩個路徑:

567 

568* **`GET /events`**:保持 SSE 串流開啟並將每個出站訊息推送為 `data:` 行,因此 `curl -N` 可以即時觀看 Claude 的回覆和權限提示到達。

569* **`POST /`**:入站側,與之前相同的處理程式,現在在聊天轉發分支之前插入了判決格式檢查。

570 

571```ts title="Full webhook.ts with permission relay' expandable theme={null}

572#!/usr/bin/env bun

573import { Server } from '@modelcontextprotocol/sdk/server/index.js'

574import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'

575import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'

576import { z } from 'zod'

577 

578// --- 出站:寫入 /events 上任何 curl -N 監聽器 ---

579// 真實橋接會改為 POST 到您的聊天平台。

580const listeners = new Set<(chunk: string) => void>()

581function send(text: string) {

582 const chunk = text.split('\n').map(l => `data: ${l}\n`).join('') + '\n'

583 for (const emit of listeners) emit(chunk)

584}

585 

586// 寄件者允許清單。對於本機逐步解說,我們信任單一 X-Sender

587// 標頭值 "dev";真實橋接會檢查平台的使用者 ID。

588const allowed = new Set(['dev'])

589 

590const mcp = new Server(

591 { name: 'webhook', version: '0.0.1' },

592 {

593 capabilities: {

594 experimental: {

595 'claude/channel': {},

596 'claude/channel/permission': {}, // 選擇加入權限中繼

597 },

598 tools: {},

599 },

600 instructions:

601 'Messages arrive as <channel source="webhook" chat_id="...">. ' +

602 'Reply with the reply tool, passing the chat_id from the tag.',

603 },

604)

605 

606// --- 回覆工具:Claude 呼叫此項以傳送訊息回去 ---

607mcp.setRequestHandler(ListToolsRequestSchema, async () => ({

608 tools: [{

609 name: 'reply',

610 description: 'Send a message back over this channel',

611 inputSchema: {

612 type: 'object',

613 properties: {

614 chat_id: { type: 'string', description: 'The conversation to reply in' },

615 text: { type: 'string', description: 'The message to send' },

616 },

617 required: ['chat_id', 'text'],

618 },

619 }],

620}))

621 

622mcp.setRequestHandler(CallToolRequestSchema, async req => {

623 if (req.params.name === 'reply') {

624 const { chat_id, text } = req.params.arguments as { chat_id: string; text: string }

625 send(`Reply to ${chat_id}: ${text}`)

626 return { content: [{ type: 'text', text: 'sent' }] }

627 }

628 throw new Error(`unknown tool: ${req.params.name}`)

629})

630 

631// --- 權限中繼:Claude Code(不是 Claude)在對話框開啟時呼叫此項

632const PermissionRequestSchema = z.object({

633 method: z.literal('notifications/claude/channel/permission_request'),

634 params: z.object({

635 request_id: z.string(),

636 tool_name: z.string(),

637 description: z.string(),

638 input_preview: z.string(),

639 }),

640})

641 

642mcp.setNotificationHandler(PermissionRequestSchema, async ({ params }) => {

643 send(

644 `Claude wants to run ${params.tool_name}: ${params.description}\n\n` +

645 `Reply "yes ${params.request_id}" or "no ${params.request_id}"`,

646 )

647})

648 

649await mcp.connect(new StdioServerTransport())

650 

651// --- HTTP on :8788:GET /events 串流出站,POST 路由入站 ---

652const PERMISSION_REPLY_RE = /^\s*(y|yes|n|no)\s+([a-km-z]{5})\s*$/i

653let nextId = 1

654 

655Bun.serve({

656 port: 8788,

657 hostname: '127.0.0.1',

658 idleTimeout: 0, // 不要關閉閒置 SSE 串流

659 async fetch(req) {

660 const url = new URL(req.url)

661 

662 // GET /events:SSE 串流,所以 curl -N 可以即時觀看回覆和提示

663 if (req.method === 'GET' && url.pathname === '/events') {

664 const stream = new ReadableStream({

665 start(ctrl) {

666 ctrl.enqueue(': connected\n\n') // 所以 curl 立即顯示某些內容

667 const emit = (chunk: string) => ctrl.enqueue(chunk)

668 listeners.add(emit)

669 req.signal.addEventListener('abort', () => listeners.delete(emit))

670 },

671 })

672 return new Response(stream, {

673 headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' },

674 })

675 }

676 

677 // 其他所有內容都是入站:首先根據寄件者進行閘道

678 const body = await req.text()

679 const sender = req.headers.get('X-Sender') ?? ''

680 if (!allowed.has(sender)) return new Response('forbidden', { status: 403 })

681 

682 // 在將其視為聊天之前檢查判決格式

683 const m = PERMISSION_REPLY_RE.exec(body)

684 if (m) {

685 await mcp.notification({

686 method: 'notifications/claude/channel/permission',

687 params: {

688 request_id: m[2].toLowerCase(),

689 behavior: m[1].toLowerCase().startsWith('y') ? 'allow' : 'deny',

690 },

691 })

692 return new Response('verdict recorded')

693 }

694 

695 // 正常聊天:作為 channel 事件轉發給 Claude

696 const chat_id = String(nextId++)

697 await mcp.notification({

698 method: 'notifications/claude/channel',

699 params: { content: body, meta: { chat_id, path: url.pathname } },

700 })

701 return new Response('ok')

702 },

703})

704```

705 

706在三個終端機中測試判決路徑。第一個是您的 Claude Code 工作階段,使用[開發旗標](#test-during-the-research-preview)啟動,以便它生成 `webhook.ts`:

707 

708```bash theme={null}

709claude --dangerously-load-development-channels server:webhook

710```

711 

712在第二個中,串流出站側,以便您可以看到 Claude 的回覆和任何權限提示在它們觸發時到達:

713 

714```bash theme={null}

715curl -N localhost:8788/events

716```

717 

718在第三個中,傳送一條訊息,使 Claude 嘗試執行命令:

719 

720```bash theme={null}

721curl -d "list the files in this directory" -H "X-Sender: dev" localhost:8788

722```

723 

724本機權限對話框在您的 Claude Code 終端機中開啟。片刻後,提示出現在 `/events` 串流中,包括五字母 ID。從遠端側批准它:

725 

726```bash theme={null}

727curl -d "yes <id>" -H "X-Sender: dev" localhost:8788

728```

729 

730本機對話框關閉,工具執行。Claude 的回覆透過 `reply` 工具回來並也落入串流中。

731 

732此檔案中的三個 channel 特定部分:

733 

734* **`Server` 建構函式中的功能**:`claude/channel` 註冊通知監聽器,`claude/channel/permission` 選擇加入權限中繼,`tools` 讓 Claude 發現回覆工具。

735* **出站路徑**:`reply` 工具處理程式是 Claude 為對話回應呼叫的;`PermissionRequestSchema` 通知處理程式是 Claude Code 在權限對話框開啟時呼叫的。兩者都呼叫 `send()` 透過 `/events` 廣播,但它們由系統的不同部分觸發。

736* **HTTP 處理程式**:`GET /events` 保持 SSE 串流開啟,以便 curl 可以即時觀看出站;`POST` 是入站,根據 `X-Sender` 標頭進行閘道。`yes <id>` 或 `no <id>` 主體作為判決通知進入 Claude Code,永遠不會到達 Claude;其他任何內容都作為 channel 事件轉發給 Claude。

737 

738## 打包為外掛程式

739 

740若要使您的 channel 可安裝和可共享,請將其包裝在[外掛程式](/zh-TW/plugins)中並將其發佈到[市場](/zh-TW/plugin-marketplaces)。使用者使用 `/plugin install` 安裝它,然後使用 `--channels plugin:<name>@<marketplace>` 按工作階段啟用它。

741 

742發佈到您自己的市場的 channel 仍然需要 `--dangerously-load-development-channels` 才能執行,因為它不在[核准允許清單](/zh-TW/channels#supported-channels)上。若要將其新增,請[將其提交到官方市場](/zh-TW/plugins#submit-your-plugin-to-the-official-marketplace)。Channel 外掛程式在被批准之前會進行安全審查。在 Team 和 Enterprise 計劃上,管理員可以改為將您的外掛程式包含在組織自己的 [`allowedChannelPlugins`](/zh-TW/channels#restrict-which-channel-plugins-can-run) 清單中,該清單取代預設 Anthropic 允許清單。

743 

744## 另請參閱

745 

746* [Channels](/zh-TW/channels) 安裝並使用 Telegram、Discord、iMessage 或 fakechat 演示,以及為 Team 或 Enterprise 組織啟用 channels

747* [工作 channel 實現](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins)以取得具有配對流程、回覆工具和檔案附件的完整伺服器程式碼

748* [MCP](/zh-TW/mcp) 用於 channel 伺服器實現的基礎協議

749* [外掛程式](/zh-TW/plugins) 打包您的 channel,以便使用者可以使用 `/plugin install` 安裝它

checkpointing.md +89 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Checkpointing

6 

7> 追蹤、回溯和總結 Claude 的編輯和對話以管理會話狀態。

8 

9Claude Code 會自動追蹤 Claude 在您工作時所做的檔案編輯,讓您可以快速撤銷變更並回溯到先前的狀態,以防任何事情出現偏差。

10 

11## Checkpointing 的運作方式

12 

13當您與 Claude 合作時,checkpointing 會自動捕捉每次編輯前的程式碼狀態。這個安全網讓您可以進行雄心勃勃的大規模任務,同時知道您可以隨時回到先前的程式碼狀態。

14 

15### 自動追蹤

16 

17Claude Code 追蹤由其檔案編輯工具所做的所有變更:

18 

19* 每個使用者提示都會建立一個新的 checkpoint

20* Checkpoints 在會話之間持續存在,因此您可以在恢復的對話中存取它們

21* 自動清理,與會話一起在 30 天後刪除(可配置)

22 

23### 回溯和總結

24 

25按兩次 `Esc`(`Esc` + `Esc`)或使用 `/rewind` 命令來開啟回溯選單。可滾動的清單顯示會話中的每個提示。選擇您想要操作的點,然後選擇一個動作:

26 

27* **恢復程式碼和對話**:將程式碼和對話都回復到該點

28* **恢復對話**:回溯到該訊息,同時保持目前程式碼

29* **恢復程式碼**:回復檔案變更,同時保持對話

30* **從此處總結**:將此點之後的對話壓縮為摘要,釋放 context window 空間

31* **算了**:返回訊息清單而不進行任何變更

32 

33恢復對話或總結後,所選訊息的原始提示會恢復到輸入欄位中,以便您可以重新傳送或編輯它。

34 

35#### 恢復與總結

36 

37三個恢復選項會回復狀態:它們撤銷程式碼變更、對話歷史或兩者。「從此處總結」的運作方式不同:

38 

39* 所選訊息之前的訊息保持完整

40* 所選訊息及其後的所有訊息都被替換為緊湊的 AI 生成摘要

41* 磁碟上的檔案不會改變

42* 原始訊息保存在會話記錄中,因此 Claude 可以在需要時參考詳細資訊

43 

44這類似於 `/compact`,但更有針對性:您不是總結整個對話,而是保持早期上下文的完整詳細資訊,只壓縮佔用空間的部分。您可以輸入可選指示來引導摘要的重點。

45 

46<Note>

47 總結讓您保持在同一會話中並壓縮上下文。如果您想嘗試不同的方法,同時保持原始會話完整,請改用 [fork](/zh-TW/how-claude-code-works#resume-or-fork-sessions)(`claude --continue --fork-session`)。

48</Note>

49 

50## 常見使用案例

51 

52Checkpoints 在以下情況下特別有用:

53 

54* **探索替代方案**:嘗試不同的實現方法,而不會失去起點

55* **從錯誤中恢復**:快速撤銷引入錯誤或破壞功能的變更

56* **迭代功能**:進行變化實驗,同時知道您可以回復到工作狀態

57* **釋放上下文空間**:從中點開始總結冗長的除錯會話,保持初始指示完整

58 

59## 限制

60 

61### Bash 命令變更未追蹤

62 

63Checkpointing 不追蹤由 bash 命令修改的檔案。例如,如果 Claude Code 執行:

64 

65```bash theme={null}

66rm file.txt

67mv old.txt new.txt

68cp source.txt dest.txt

69```

70 

71這些檔案修改無法透過回溯撤銷。只有透過 Claude 的檔案編輯工具進行的直接檔案編輯才會被追蹤。

72 

73### 外部變更未追蹤

74 

75Checkpointing 只追蹤在目前會話中已編輯的檔案。您在 Claude Code 外部對檔案所做的手動變更以及來自其他並行會話的編輯通常不會被捕捉,除非它們碰巧修改與目前會話相同的檔案。

76 

77### 不是版本控制的替代品

78 

79Checkpoints 設計用於快速的會話級恢復。對於永久版本歷史和協作:

80 

81* 繼續使用版本控制(例如 Git)進行提交、分支和長期歷史

82* Checkpoints 補充但不替代適當的版本控制

83* 將 checkpoints 視為「本地撤銷」,Git 視為「永久歷史」

84 

85## 另請參閱

86 

87* [Interactive mode](/zh-TW/interactive-mode) - 快捷鍵和會話控制

88* [Built-in commands](/zh-TW/commands) - 使用 `/rewind` 存取 checkpoints

89* [CLI reference](/zh-TW/cli-reference) - 命令列選項

chrome.md +232 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 在 Chrome 中使用 Claude Code(測試版)

6 

7> 將 Claude Code 連接到您的 Chrome 瀏覽器,以測試網頁應用程式、使用控制台日誌進行除錯、自動填充表單,以及從網頁中提取資料。

8 

9Claude Code 與 [Claude in Chrome 瀏覽器擴充功能](https://chromewebstore.google.com/detail/claude/fcoeoabgfenejglbffodgkkbkcdhcgfn)整合,為您提供從 CLI 或 [VS Code 擴充功能](/zh-TW/vs-code#automate-browser-tasks-with-chrome) 進行瀏覽器自動化的功能。建立您的程式碼,然後在瀏覽器中測試和除錯,無需切換上下文。

10 

11Claude 為瀏覽器任務開啟新標籤頁,並共享您瀏覽器的登入狀態,因此它可以存取您已登入的任何網站。瀏覽器操作在可見的 Chrome 視窗中即時執行。當 Claude 遇到登入頁面或 CAPTCHA 時,它會暫停並要求您手動處理。

12 

13<Note>

14 Chrome 整合處於測試版,目前適用於 Google Chrome 和 Microsoft Edge。尚不支援 Brave、Arc 或其他基於 Chromium 的瀏覽器。也不支援 WSL(Windows Subsystem for Linux)。

15</Note>

16 

17## 功能

18 

19連接 Chrome 後,您可以在單一工作流程中鏈接瀏覽器操作與編碼任務:

20 

21* **即時除錯**:直接讀取控制台錯誤和 DOM 狀態,然後修復導致它們的程式碼

22* **設計驗證**:從 Figma 模型建立 UI,然後在瀏覽器中開啟以驗證它是否相符

23* **網頁應用程式測試**:測試表單驗證、檢查視覺回歸或驗證使用者流程

24* **已驗證的網頁應用程式**:與 Google Docs、Gmail、Notion 或您已登入的任何應用程式互動,無需 API 連接器

25* **資料提取**:從網頁中提取結構化資訊並將其儲存在本地

26* **任務自動化**:自動化重複的瀏覽器任務,如資料輸入、表單填充或多網站工作流程

27* **工作階段錄製**:將瀏覽器互動錄製為 GIF,以記錄或分享發生的情況

28 

29## 先決條件

30 

31在使用 Claude Code 與 Chrome 之前,您需要:

32 

33* [Google Chrome](https://www.google.com/chrome/) 或 [Microsoft Edge](https://www.microsoft.com/edge) 瀏覽器

34* [Claude in Chrome 擴充功能](https://chromewebstore.google.com/detail/claude/fcoeoabgfenejglbffodgkkbkcdhcgfn) 版本 1.0.36 或更高版本,可在 Chrome Web Store 中為兩個瀏覽器取得

35* [Claude Code](/zh-TW/quickstart#step-1-install-claude-code) 版本 2.0.73 或更高版本

36* 直接 Anthropic 計畫(Pro、Max、Team 或 Enterprise)

37 

38<Note>

39 Chrome 整合不適用於 Amazon Bedrock、Google Cloud Vertex AI 或 Microsoft Foundry 等第三方提供商。如果您只透過第三方提供商存取 Claude,則需要單獨的 claude.ai 帳戶才能使用此功能。

40</Note>

41 

42## 在 CLI 中開始

43 

44<Steps>

45 <Step title="使用 Chrome 啟動 Claude Code">

46 使用 `--chrome` 標誌啟動 Claude Code:

47 

48 ```bash theme={null}

49 claude --chrome

50 ```

51 

52 您也可以透過執行 `/chrome` 在現有工作階段中啟用 Chrome。

53 </Step>

54 

55 <Step title="要求 Claude 使用瀏覽器">

56 此範例導航到頁面、與其互動並報告其發現,全部來自您的終端或編輯器:

57 

58 ```text theme={null}

59 Go to code.claude.com/docs, click on the search box,

60 type "hooks", and tell me what results appear

61 ```

62 </Step>

63</Steps>

64 

65隨時執行 `/chrome` 以檢查連接狀態、管理權限或重新連接擴充功能。

66 

67對於 VS Code,請參閱 [VS Code 中的瀏覽器自動化](/zh-TW/vs-code#automate-browser-tasks-with-chrome)。

68 

69### 預設啟用 Chrome

70 

71為了避免每個工作階段都傳遞 `--chrome`,執行 `/chrome` 並選擇「預設啟用」。

72 

73在 [VS Code 擴充功能](/zh-TW/vs-code#automate-browser-tasks-with-chrome) 中,只要安裝了 Chrome 擴充功能,Chrome 就可用。無需額外標誌。

74 

75<Note>

76 在 CLI 中預設啟用 Chrome 會增加上下文使用量,因為瀏覽器工具始終被載入。如果您注意到上下文消耗增加,請停用此設定,並僅在需要時使用 `--chrome`。

77</Note>

78 

79### 管理網站權限

80 

81網站級權限繼承自 Chrome 擴充功能。在 Chrome 擴充功能設定中管理權限,以控制 Claude 可以瀏覽、點擊和輸入的網站。

82 

83## 範例工作流程

84 

85這些範例展示了將瀏覽器操作與編碼任務結合的常見方式。執行 `/mcp` 並選擇 `claude-in-chrome` 以查看可用瀏覽器工具的完整清單。

86 

87### 測試本地網頁應用程式

88 

89開發網頁應用程式時,要求 Claude 驗證您的變更是否正確運作:

90 

91```text theme={null}

92I just updated the login form validation. Can you open localhost:3000,

93try submitting the form with invalid data, and check if the error

94messages appear correctly?

95```

96 

97Claude 導航到您的本地伺服器、與表單互動並報告其觀察結果。

98 

99### 使用控制台日誌進行除錯

100 

101Claude 可以讀取控制台輸出以幫助診斷問題。告訴 Claude 要尋找的模式,而不是要求所有控制台輸出,因為日誌可能很冗長:

102 

103```text theme={null}

104Open the dashboard page and check the console for any errors when

105the page loads.

106```

107 

108Claude 讀取控制台訊息,可以篩選特定模式或錯誤類型。

109 

110### 自動填充表單

111 

112加快重複資料輸入任務的速度:

113 

114```text theme={null}

115I have a spreadsheet of customer contacts in contacts.csv. For each row,

116go to the CRM at crm.example.com, click "Add Contact", and fill in the

117name, email, and phone fields.

118```

119 

120Claude 讀取您的本地檔案、導航網頁介面並為每筆記錄輸入資料。

121 

122### 在 Google Docs 中起草內容

123 

124使用 Claude 直接在您的文件中寫入,無需 API 設定:

125 

126```text theme={null}

127Draft a project update based on the recent commits and add it to my

128Google Doc at docs.google.com/document/d/abc123

129```

130 

131Claude 開啟文件、點擊編輯器並輸入內容。這適用於您已登入的任何網頁應用程式:Gmail、Notion、Sheets 等。

132 

133### 從網頁中提取資料

134 

135從網站中提取結構化資訊:

136 

137```text theme={null}

138Go to the product listings page and extract the name, price, and

139availability for each item. Save the results as a CSV file.

140```

141 

142Claude 導航到頁面、讀取內容並將資料編譯成結構化格式。

143 

144### 執行多網站工作流程

145 

146協調多個網站之間的任務:

147 

148```text theme={null}

149Check my calendar for meetings tomorrow, then for each meeting with

150an external attendee, look up their company website and add a note

151about what they do.

152```

153 

154Claude 跨標籤頁工作以收集資訊並完成工作流程。

155 

156### 錄製演示 GIF

157 

158建立瀏覽器互動的可共享錄製:

159 

160```text theme={null}

161Record a GIF showing how to complete the checkout flow, from adding

162an item to the cart through to the confirmation page.

163```

164 

165Claude 錄製互動序列並將其儲存為 GIF 檔案。

166 

167## 故障排除

168 

169### 未偵測到擴充功能

170 

171如果 Claude Code 顯示「未偵測到 Chrome 擴充功能」:

172 

1731. 驗證 Chrome 擴充功能已安裝並在 `chrome://extensions` 中啟用

1742. 透過執行 `claude --version` 驗證 Claude Code 是否為最新版本

1753. 檢查 Chrome 是否正在執行

1764. 執行 `/chrome` 並選擇「重新連接擴充功能」以重新建立連接

1775. 如果問題仍然存在,請重新啟動 Claude Code 和 Chrome

178 

179第一次啟用 Chrome 整合時,Claude Code 會安裝原生訊息主機設定檔。Chrome 在啟動時讀取此檔案,因此如果擴充功能在您的第一次嘗試中未被偵測到,請重新啟動 Chrome 以取得新設定。

180 

181如果連接仍然失敗,請驗證主機設定檔是否存在於:

182 

183對於 Chrome:

184 

185* **macOS**:`~/Library/Application Support/Google/Chrome/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json`

186* **Linux**:`~/.config/google-chrome/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json`

187* **Windows**:在 Windows 登錄中檢查 `HKCU\Software\Google\Chrome\NativeMessagingHosts\`

188 

189對於 Edge:

190 

191* **macOS**:`~/Library/Application Support/Microsoft Edge/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json`

192* **Linux**:`~/.config/microsoft-edge/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json`

193* **Windows**:在 Windows 登錄中檢查 `HKCU\Software\Microsoft\Edge\NativeMessagingHosts\`

194 

195### 瀏覽器無回應

196 

197如果 Claude 的瀏覽器命令停止工作:

198 

1991. 檢查是否有模態對話框(警告、確認、提示)阻止頁面。JavaScript 對話框會阻止瀏覽器事件並防止 Claude 接收命令。手動關閉對話框,然後告訴 Claude 繼續。

2002. 要求 Claude 建立新標籤頁並重試

2013. 透過在 `chrome://extensions` 中停用並重新啟用 Chrome 擴充功能來重新啟動它

202 

203### 長工作階段期間連接中斷

204 

205Chrome 擴充功能的服務工作者可能在延長的工作階段期間進入閒置狀態,這會中斷連接。如果瀏覽器工具在一段時間不活動後停止工作,請執行 `/chrome` 並選擇「重新連接擴充功能」。

206 

207### Windows 特定問題

208 

209在 Windows 上,您可能會遇到:

210 

211* **命名管道衝突 (EADDRINUSE)**:如果另一個程序正在使用相同的命名管道,請重新啟動 Claude Code。關閉任何可能使用 Chrome 的其他 Claude Code 工作階段。

212* **原生訊息主機錯誤**:如果原生訊息主機在啟動時崩潰,請嘗試重新安裝 Claude Code 以重新產生主機設定。

213 

214### 常見錯誤訊息

215 

216以下是最常遇到的錯誤及其解決方法:

217 

218| 錯誤 | 原因 | 修復 |

219| ------------ | -------------------- | ---------------------------------------------- |

220| 「瀏覽器擴充功能未連接」 | 原生訊息主機無法到達擴充功能 | 重新啟動 Chrome 和 Claude Code,然後執行 `/chrome` 以重新連接 |

221| 「未偵測到擴充功能」 | Chrome 擴充功能未安裝或已停用 | 在 `chrome://extensions` 中安裝或啟用擴充功能 |

222| 「沒有可用的標籤頁」 | Claude 在標籤頁準備好之前嘗試操作 | 要求 Claude 建立新標籤頁並重試 |

223| 「接收端不存在」 | 擴充功能服務工作者進入閒置狀態 | 執行 `/chrome` 並選擇「重新連接擴充功能」 |

224 

225## 另請參閱

226 

227* [電腦使用](/zh-TW/computer-use):當任務無法在瀏覽器中完成時控制原生 macOS 應用程式

228* [在 VS Code 中使用 Claude Code](/zh-TW/vs-code#automate-browser-tasks-with-chrome):VS Code 擴充功能中的瀏覽器自動化

229* [CLI 參考](/zh-TW/cli-reference):命令列標誌,包括 `--chrome`

230* [常見工作流程](/zh-TW/common-workflows):更多使用 Claude Code 的方式

231* [資料和隱私](/zh-TW/data-usage):Claude Code 如何處理您的資料

232* [Claude in Chrome 入門](https://support.claude.com/en/articles/12012173-getting-started-with-claude-in-chrome):Chrome 擴充功能的完整文件,包括快捷鍵、排程和權限

claude-code-on-the-web.md +773 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 在網頁上使用 Claude Code

6 

7> 配置雲端環境、設定指令碼、網路存取和 Docker 在 Anthropic 的沙箱中。使用 `--remote` 和 `--teleport` 在網頁和終端之間移動工作階段。

8 

9<Note>

10 Claude Code 網頁版目前處於研究預覽階段,適用於 Pro、Max 和 Team 使用者,以及具有高級席位或 Chat + Claude Code 席位的 Enterprise 使用者。

11</Note>

12 

13Claude Code 網頁版在 [claude.ai/code](https://claude.ai/code) 上的 Anthropic 管理的雲端基礎設施上執行任務。工作階段即使在您關閉瀏覽器後仍會保留,您可以從 Claude 行動應用程式監控它們。

14 

15<Tip>

16 初次使用 Claude Code 網頁版?從[開始使用](/zh-TW/web-quickstart)開始,連接您的 GitHub 帳戶並提交您的第一個任務。

17</Tip>

18 

19本頁涵蓋:

20 

21* [GitHub 驗證選項](#github-authentication-options):連接 GitHub 的兩種方式

22* [雲端環境](#the-cloud-environment):哪些配置會保留、安裝了哪些工具以及如何配置環境

23* [設定指令碼](#setup-scripts)和依賴管理

24* [網路存取](#network-access):級別、代理和預設允許清單

25* [在網頁和終端之間移動任務](#move-tasks-between-web-and-terminal),使用 `--remote` 和 `--teleport`

26* [使用工作階段](#work-with-sessions):檢查、共享、封存、刪除

27* [自動修復拉取請求](#auto-fix-pull-requests):自動回應 CI 失敗和審查評論

28* [安全性和隔離](#security-and-isolation):工作階段如何隔離

29* [限制](#limitations):速率限制和平台限制

30 

31## GitHub 驗證選項

32 

33雲端工作階段需要存取您的 GitHub 儲存庫以複製程式碼和推送分支。您可以通過兩種方式授予存取權限:

34 

35| 方法 | 運作方式 | 最適合 |

36| :--------------- | :------------------------------------------------------------------------------ | :--------------- |

37| **GitHub App** | 在[網頁上線](/zh-TW/web-quickstart)期間在特定儲存庫上安裝 Claude GitHub App。存取按儲存庫範圍。 | 想要明確的按儲存庫授權的團隊 |

38| **`/web-setup`** | 在您的終端中執行 `/web-setup` 以將您的本機 `gh` CLI 令牌同步到您的 Claude 帳戶。存取與您的 `gh` 令牌可以看到的內容相符。 | 已經使用 `gh` 的個人開發者 |

39 

40任一方法都可以。[`/schedule`](/zh-TW/routines)檢查任一形式的存取,如果都未配置,會提示您執行 `/web-setup`。有關 `/web-setup` 的逐步說明,請參閱[從您的終端連接](/zh-TW/web-quickstart#connect-from-your-terminal)。

41 

42[自動修復](#auto-fix-pull-requests)需要 GitHub App,它使用該應用程式接收 PR webhooks。如果您使用 `/web-setup` 連接,稍後想要自動修復,請在這些儲存庫上安裝該應用程式。

43 

44Team 和 Enterprise 管理員可以在 [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) 使用快速網頁設定切換來禁用 `/web-setup`。

45 

46<Note>

47 啟用[零資料保留](/zh-TW/zero-data-retention)的組織無法使用 `/web-setup` 或其他雲端工作階段功能。

48</Note>

49 

50## 雲端環境

51 

52每個工作階段在一個新的 Anthropic 管理的 VM 中執行,其中您的儲存庫已複製。本節涵蓋工作階段啟動時可用的內容以及如何自訂它。

53 

54### 雲端工作階段中可用的內容

55 

56雲端工作階段從您的儲存庫的新複製開始。任何提交到儲存庫的內容都可用。您只在自己的機器上安裝或配置的任何內容都不可用。

57 

58| | 在雲端工作階段中可用 | 原因 |

59| :------------------------------------------------------------- | :--------- | :----------------------------------------------------------------------------------------- |

60| 您的儲存庫的 `CLAUDE.md` | 是 | 複製的一部分 |

61| 您的儲存庫的 `.claude/settings.json` hooks | 是 | 複製的一部分 |

62| 您的儲存庫的 `.mcp.json` MCP 伺服器 | 是 | 複製的一部分 |

63| 您的儲存庫的 `.claude/rules/` | 是 | 複製的一部分 |

64| 您的儲存庫的 `.claude/skills/`、`.claude/agents/`、`.claude/commands/` | 是 | 複製的一部分 |

65| 在 `.claude/settings.json` 中聲明的 Plugins | 是 | 在工作階段啟動時從您聲明的[市場](/zh-TW/plugin-marketplaces)安裝。需要網路存取才能到達市場來源 |

66| 您的使用者 `~/.claude/CLAUDE.md` | 否 | 位於您的機器上,不在儲存庫中 |

67| 僅在您的使用者設定中啟用的 Plugins | 否 | 使用者範圍的 `enabledPlugins` 位於 `~/.claude/settings.json`。改為在儲存庫的 `.claude/settings.json` 中聲明它們 |

68| 您使用 `claude mcp add` 新增的 MCP 伺服器 | 否 | 這些寫入您的本機使用者配置,不是儲存庫。改為在[`.mcp.json`](/zh-TW/mcp#project-scope)中聲明伺服器 |

69| 靜態 API 令牌和認證 | 否 | 尚不存在專用的秘密存儲。請參閱下文 |

70| 互動式驗證,如 AWS SSO | 否 | 不支援。SSO 需要無法在雲端工作階段中執行的基於瀏覽器的登入 |

71 

72若要在雲端工作階段中提供配置,請將其提交到儲存庫。尚不可用專用的秘密存儲。環境變數和設定指令碼都存儲在環境配置中,對任何可以編輯該環境的人可見。如果您需要雲端工作階段中的秘密,請將它們新增為環境變數,並考慮該可見性。

73 

74### 已安裝的工具

75 

76雲端工作階段預先安裝了常見的語言執行時、建置工具和資料庫。下表按類別總結了包含的內容。

77 

78| 類別 | 包含 |

79| :------------ | :-------------------------------------------------------------------- |

80| **Python** | Python 3.x,包含 pip、poetry、uv、black、mypy、pytest、ruff |

81| **Node.js** | 20、21 和 22(通過 nvm),包含 npm、yarn、pnpm、bun¹、eslint、prettier、chromedriver |

82| **Ruby** | 3.1、3.2、3.3,包含 gem、bundler、rbenv |

83| **PHP** | 8.4,包含 Composer |

84| **Java** | OpenJDK 21,包含 Maven 和 Gradle |

85| **Go** | 最新穩定版本,包含模組支援 |

86| **Rust** | rustc 和 cargo |

87| **C/C++** | GCC、Clang、cmake、ninja、conan |

88| **Docker** | docker、dockerd、docker compose |

89| **Databases** | PostgreSQL 16、Redis 7.0 |

90| **Utilities** | git、jq、yq、ripgrep、tmux、vim、nano |

91 

92¹ Bun 已安裝,但在套件取得時有已知的[代理相容性問題](#install-dependencies-with-a-sessionstart-hook)。

93 

94如需確切版本,請要求 Claude 在雲端工作階段中執行 `check-tools`。此命令僅存在於雲端工作階段中。

95 

96### 使用 GitHub 問題和拉取請求

97 

98雲端工作階段包含內建的 GitHub 工具,讓 Claude 可以讀取問題、列出拉取請求、取得差異和發佈評論,無需任何設定。這些工具通過[GitHub 代理](#github-proxy)進行驗證,使用您在 [GitHub 驗證選項](#github-authentication-options)下配置的任何方法,因此您的令牌永遠不會進入容器。

99 

100`gh` CLI 未預先安裝。如果您需要內建工具不涵蓋的 `gh` 命令,例如 `gh release` 或 `gh workflow run`,請自行安裝和驗證:

101 

102<Steps>

103 <Step title="在您的設定指令碼中安裝 gh">

104 將 `apt update && apt install -y gh` 新增到您的[設定指令碼](#setup-scripts)。

105 </Step>

106 

107 <Step title="提供令牌">

108 將 `GH_TOKEN` 環境變數新增到您的[環境設定](#configure-your-environment),其中包含 GitHub 個人存取令牌。`gh` 會自動讀取 `GH_TOKEN`,因此不需要 `gh auth login` 步驟。

109 </Step>

110</Steps>

111 

112### 將工件連結回工作階段

113 

114每個雲端工作階段在 claude.ai 上都有一個成績單 URL,工作階段可以從 `CLAUDE_CODE_REMOTE_SESSION_ID` 環境變數讀取自己的 ID。使用此在 PR 正文、提交訊息、Slack 貼文或生成的報告中放置可追蹤的連結,以便審查者可以開啟產生它們的執行。

115 

116要求 Claude 從環境變數構造連結。以下命令列印 URL:

117 

118```bash theme={null}

119echo "https://claude.ai/code/${CLAUDE_CODE_REMOTE_SESSION_ID}"

120```

121 

122### 執行測試、啟動服務和新增套件

123 

124Claude 執行測試作為處理任務的一部分。在您的提示中要求它,例如「修復 `tests/` 中的失敗測試」或「在每次變更後執行 pytest」。測試執行器(如 pytest、jest 和 cargo test)開箱即用,因為它們已預先安裝。

125 

126PostgreSQL 和 Redis 已預先安裝,但預設不執行。在工作階段期間要求 Claude 啟動每一個:

127 

128```bash theme={null}

129service postgresql start

130```

131 

132```bash theme={null}

133service redis-server start

134```

135 

136Docker 可用於執行容器化服務。要求 Claude 執行 `docker compose up` 以啟動您的專案服務。拉取映像的網路存取遵循您的環境的[存取級別](#access-levels),[信任預設值](#default-allowed-domains)包括 Docker Hub 和其他常見登錄。

137 

138如果您的映像很大或拉取速度很慢,請將 `docker compose pull` 或 `docker compose build` 新增到您的[設定指令碼](#setup-scripts)。拉取的映像會保存在[快取環境](#environment-caching)中,因此每個新工作階段都已在磁碟上有它們。快取僅存儲檔案,不存儲執行中的程序,因此 Claude 仍然在每個工作階段啟動容器。

139 

140若要新增未預先安裝的套件,請使用[設定指令碼](#setup-scripts)。指令碼的輸出會被[快取](#environment-caching),因此您在那裡安裝的套件在每個工作階段開始時都可用,無需每次重新安裝。您也可以要求 Claude 在工作階段期間安裝套件,但這些安裝不會在工作階段之間保留。

141 

142### 資源限制

143 

144雲端工作階段執行時具有可能隨時間變化的近似資源上限:

145 

146* 4 vCPU

147* 16 GB RAM

148* 30 GB 磁碟

149 

150需要明顯更多記憶體的任務,例如大型建置工作或記憶體密集型測試,可能會失敗或被終止。對於超出這些限制的工作負載,請使用[遠端控制](/zh-TW/remote-control)在您自己的硬體上執行 Claude Code。

151 

152### 配置您的環境

153 

154環境控制[網路存取](#network-access)、環境變數和在工作階段啟動前執行的[設定指令碼](#setup-scripts)。有關不需要任何配置即可使用的內容,請參閱[已安裝的工具](#installed-tools)。您可以從網頁介面或終端管理環境:

155 

156| 操作 | 方式 |

157| :----------------- | :-------------------------------------------------------------------------------- |

158| 新增環境 | 選擇目前環境以開啟選擇器,然後選擇**新增環境**。對話框包括名稱、網路存取級別、環境變數和設定指令碼。 |

159| 編輯環境 | 選擇環境名稱右側的設定圖示。 |

160| 封存環境 | 開啟環境進行編輯並選擇**封存**。封存的環境隱藏在選擇器中,但現有工作階段繼續執行。 |

161| 為 `--remote` 設定預設值 | 在您的終端中執行 `/remote-env`。如果您有單一環境,此命令顯示您目前的配置。`/remote-env` 僅選擇預設值;從網頁介面新增、編輯和封存環境。 |

162 

163環境變數使用 `.env` 格式,每行一個 `KEY=value` 對。不要用引號包裝值,因為引號會存儲為值的一部分。

164 

165```text theme={null}

166NODE_ENV=development

167LOG_LEVEL=debug

168DATABASE_URL=postgres://localhost:5432/myapp

169```

170 

171## 設定指令碼

172 

173設定指令碼是一個 Bash 指令碼,在新的雲端工作階段啟動時執行,在 Claude Code 啟動之前。使用設定指令碼來安裝依賴項、配置工具或取得工作階段需要但未預先安裝的任何內容。

174 

175指令碼在 Ubuntu 24.04 上以 root 身份執行,因此 `apt install` 和大多數語言套件管理器都可以工作。

176 

177若要新增設定指令碼,請開啟環境設定對話框並在**設定指令碼**欄位中輸入您的指令碼。

178 

179此範例安裝 `gh` CLI,它未預先安裝:

180 

181```bash theme={null}

182#!/bin/bash

183apt update && apt install -y gh

184```

185 

186如果指令碼以非零值退出,工作階段將無法啟動。將 `|| true` 附加到非關鍵命令以避免在不穩定的安裝失敗時阻止工作階段。

187 

188<Note>

189 安裝套件的設定指令碼需要網路存取才能到達登錄。預設**信任**網路存取允許連接到[常見套件登錄](#default-allowed-domains),包括 npm、PyPI、RubyGems 和 crates.io。如果您的環境使用**無**網路存取,指令碼將無法安裝套件。

190</Note>

191 

192### 環境快取

193 

194設定指令碼在您第一次在環境中啟動工作階段時執行。完成後,Anthropic 會快照檔案系統並將該快照重新用作後續工作階段的起點。新工作階段以您的依賴項、工具和 Docker 映像已在磁碟上開始,設定指令碼步驟被跳過。這即使在指令碼安裝大型工具鏈或拉取容器映像時也能保持啟動速度快。

195 

196快取捕獲檔案,不捕獲執行中的程序。設定指令碼寫入磁碟的任何內容都會保留。它啟動的服務或容器不會,因此通過要求 Claude 或使用 [SessionStart hook](#setup-scripts-vs-sessionstart-hooks) 按工作階段啟動這些。

197 

198當您更改環境的設定指令碼或允許的網路主機時,以及當快取在大約七天後達到其過期時間時,設定指令碼會再次執行以重建快取。恢復現有工作階段永遠不會重新執行設定指令碼。

199 

200您不需要自行啟用快取或管理快照。

201 

202### 設定指令碼與 SessionStart hooks

203 

204使用設定指令碼來安裝雲端需要但您的筆記型電腦已有的東西,例如語言執行時或 CLI 工具。使用 [SessionStart hook](/zh-TW/hooks#sessionstart) 進行應在任何地方執行的專案設定,雲端和本機,例如 `npm install`。

205 

206兩者都在工作階段開始時執行,但它們屬於不同的位置:

207 

208| | 設定指令碼 | SessionStart hooks |

209| --- | --------------------------------------------------- | ---------------------------------- |

210| 附加到 | 雲端環境 | 您的儲存庫 |

211| 配置在 | 雲端環境 UI | 您的儲存庫中的 `.claude/settings.json` |

212| 執行 | 在 Claude Code 啟動之前,當沒有[快取環境](#environment-caching)時 | 在 Claude Code 啟動之後,在每個工作階段上,包括已恢復的 |

213| 範圍 | 僅雲端環境 | 本機和雲端 |

214 

215SessionStart hooks 也可以在本機使用者級別 `~/.claude/settings.json` 中定義,但使用者級別設定不會轉移到雲端工作階段。在雲端中,只有提交到儲存庫的 hooks 執行。

216 

217### 使用 SessionStart hook 安裝依賴項

218 

219若要僅在雲端工作階段中安裝依賴項,請將 SessionStart hook 新增到您的儲存庫的 `.claude/settings.json`:

220 

221```json theme={null}

222{

223 "hooks": {

224 "SessionStart": [

225 {

226 "matcher": "startup|resume",

227 "hooks": [

228 {

229 "type": "command",

230 "command": "\"$CLAUDE_PROJECT_DIR\"/scripts/install_pkgs.sh"

231 }

232 ]

233 }

234 ]

235 }

236}

237```

238 

239在 `scripts/install_pkgs.sh` 建立指令碼並使用 `chmod +x` 使其可執行。`CLAUDE_CODE_REMOTE` 環境變數在雲端工作階段中設定為 `true`,因此您可以使用它來跳過本機執行:

240 

241```bash theme={null}

242#!/bin/bash

243 

244if [ "$CLAUDE_CODE_REMOTE" != "true" ]; then

245 exit 0

246fi

247 

248npm install

249pip install -r requirements.txt

250exit 0

251```

252 

253SessionStart hooks 在雲端工作階段中有一些限制:

254 

255* **無雲端專用範圍**:hooks 在本機和雲端工作階段中執行。若要跳過本機執行,請檢查上面所示的 `CLAUDE_CODE_REMOTE` 環境變數。

256* **需要網路存取**:安裝命令需要到達套件登錄。如果您的環境使用**無**網路存取,這些 hooks 會失敗。[**信任**下的預設允許清單](#default-allowed-domains)涵蓋 npm、PyPI、RubyGems 和 crates.io。

257* **代理相容性**:所有出站流量都通過[安全代理](#security-proxy)。某些套件管理器無法與此代理正確配合使用。Bun 是一個已知的例子。

258* **新增啟動延遲**:hooks 在每次工作階段啟動或恢復時執行,不像設定指令碼受益於[環境快取](#environment-caching)。通過在重新安裝之前檢查依賴項是否已存在來保持安裝指令碼快速。

259 

260若要為後續 Bash 命令保留環境變數,請寫入 `$CLAUDE_ENV_FILE` 處的檔案。有關詳細資訊,請參閱 [SessionStart hooks](/zh-TW/hooks#sessionstart)。

261 

262尚不支援使用您自己的 Docker 映像替換基礎映像。使用設定指令碼在[提供的映像](#installed-tools)上安裝您需要的內容,或使用 `docker compose` 將您的映像作為容器與 Claude 一起執行。

263 

264## 網路存取

265 

266網路存取控制來自雲端環境的出站連接。每個環境指定一個存取級別,您可以使用自訂允許的域擴展它。預設值為**信任**,允許套件登錄和其他[允許清單域](#default-allowed-domains)。

267 

268### 存取級別

269 

270在建立或編輯環境時選擇存取級別:

271 

272| 級別 | 出站連接 |

273| :----- | :---------------------------------------------------- |

274| **無** | 無出站網路存取 |

275| **信任** | [允許清單域](#default-allowed-domains)僅:套件登錄、GitHub、雲端 SDK |

276| **完全** | 任何域 |

277| **自訂** | 您自己的允許清單,可選地包括預設值 |

278 

279GitHub 操作使用[單獨的代理](#github-proxy),獨立於此設定。

280 

281### 允許特定域

282 

283若要允許不在信任清單中的域,請在環境的網路存取設定中選擇**自訂**。出現**允許的域**欄位。每行輸入一個域:

284 

285```text theme={null}

286api.example.com

287*.internal.example.com

288registry.example.com

289```

290 

291使用 `*.` 進行萬用字元子域匹配。檢查**也包括常見套件管理器的預設清單**以將[信任域](#default-allowed-domains)與您的自訂項目一起保留,或將其取消選中以僅允許您列出的內容。

292 

293### GitHub 代理

294 

295為了安全起見,所有 GitHub 操作都通過專用代理服務進行,該服務透明地處理所有 git 互動。在沙箱內,git 用戶端使用自訂建置的限定認證進行驗證。此代理:

296 

297* 安全地管理 GitHub 驗證:git 用戶端在沙箱內使用限定認證,代理驗證並將其轉換為您的實際 GitHub 驗證令牌

298* 限制 git push 操作到目前工作分支以確保安全

299* 啟用複製、取得和 PR 操作,同時維護安全邊界

300 

301### 安全代理

302 

303環境在 HTTP/HTTPS 網路代理後面執行,用於安全和濫用防止目的。所有出站網際網路流量都通過此代理,該代理提供:

304 

305* 防止惡意請求

306* 速率限制和濫用防止

307* 增強安全性的內容篩選

308 

309### 預設允許的域

310 

311使用**信任**網路存取時,預設允許以下域。標記為 `*` 的域表示萬用字元子域匹配,因此 `*.gcr.io` 允許 `gcr.io` 的任何子域。

312 

313<AccordionGroup>

314 <Accordion title="Anthropic 服務">

315 * api.anthropic.com

316 * statsig.anthropic.com

317 * docs.claude.com

318 * platform.claude.com

319 * code.claude.com

320 * claude.ai

321 </Accordion>

322 

323 <Accordion title="版本控制">

324 * github.com

325 * [www.github.com](http://www.github.com)

326 * api.github.com

327 * npm.pkg.github.com

328 * raw\.githubusercontent.com

329 * pkg-npm.githubusercontent.com

330 * objects.githubusercontent.com

331 * release-assets.githubusercontent.com

332 * codeload.github.com

333 * avatars.githubusercontent.com

334 * camo.githubusercontent.com

335 * gist.github.com

336 * gitlab.com

337 * [www.gitlab.com](http://www.gitlab.com)

338 * registry.gitlab.com

339 * bitbucket.org

340 * [www.bitbucket.org](http://www.bitbucket.org)

341 * api.bitbucket.org

342 </Accordion>

343 

344 <Accordion title="容器登錄">

345 * registry-1.docker.io

346 * auth.docker.io

347 * index.docker.io

348 * hub.docker.com

349 * [www.docker.com](http://www.docker.com)

350 * production.cloudflare.docker.com

351 * download.docker.com

352 * gcr.io

353 * \*.gcr.io

354 * ghcr.io

355 * mcr.microsoft.com

356 * \*.data.mcr.microsoft.com

357 * public.ecr.aws

358 </Accordion>

359 

360 <Accordion title="雲端平台">

361 * cloud.google.com

362 * accounts.google.com

363 * gcloud.google.com

364 * \*.googleapis.com

365 * storage.googleapis.com

366 * compute.googleapis.com

367 * container.googleapis.com

368 * azure.com

369 * portal.azure.com

370 * microsoft.com

371 * [www.microsoft.com](http://www.microsoft.com)

372 * \*.microsoftonline.com

373 * packages.microsoft.com

374 * dotnet.microsoft.com

375 * dot.net

376 * visualstudio.com

377 * dev.azure.com

378 * \*.amazonaws.com

379 * \*.api.aws

380 * oracle.com

381 * [www.oracle.com](http://www.oracle.com)

382 * java.com

383 * [www.java.com](http://www.java.com)

384 * java.net

385 * [www.java.net](http://www.java.net)

386 * download.oracle.com

387 * yum.oracle.com

388 </Accordion>

389 

390 <Accordion title="JavaScript 和 Node 套件管理器">

391 * registry.npmjs.org

392 * [www.npmjs.com](http://www.npmjs.com)

393 * [www.npmjs.org](http://www.npmjs.org)

394 * npmjs.com

395 * npmjs.org

396 * yarnpkg.com

397 * registry.yarnpkg.com

398 </Accordion>

399 

400 <Accordion title="Python 套件管理器">

401 * pypi.org

402 * [www.pypi.org](http://www.pypi.org)

403 * files.pythonhosted.org

404 * pythonhosted.org

405 * test.pypi.org

406 * pypi.python.org

407 * pypa.io

408 * [www.pypa.io](http://www.pypa.io)

409 </Accordion>

410 

411 <Accordion title="Ruby 套件管理器">

412 * rubygems.org

413 * [www.rubygems.org](http://www.rubygems.org)

414 * api.rubygems.org

415 * index.rubygems.org

416 * ruby-lang.org

417 * [www.ruby-lang.org](http://www.ruby-lang.org)

418 * rubyforge.org

419 * [www.rubyforge.org](http://www.rubyforge.org)

420 * rubyonrails.org

421 * [www.rubyonrails.org](http://www.rubyonrails.org)

422 * rvm.io

423 * get.rvm.io

424 </Accordion>

425 

426 <Accordion title="Rust 套件管理器">

427 * crates.io

428 * [www.crates.io](http://www.crates.io)

429 * index.crates.io

430 * static.crates.io

431 * rustup.rs

432 * static.rust-lang.org

433 * [www.rust-lang.org](http://www.rust-lang.org)

434 </Accordion>

435 

436 <Accordion title="Go 套件管理器">

437 * proxy.golang.org

438 * sum.golang.org

439 * index.golang.org

440 * golang.org

441 * [www.golang.org](http://www.golang.org)

442 * goproxy.io

443 * pkg.go.dev

444 </Accordion>

445 

446 <Accordion title="JVM 套件管理器">

447 * maven.org

448 * repo.maven.org

449 * central.maven.org

450 * repo1.maven.org

451 * repo.maven.apache.org

452 * jcenter.bintray.com

453 * gradle.org

454 * [www.gradle.org](http://www.gradle.org)

455 * services.gradle.org

456 * plugins.gradle.org

457 * kotlinlang.org

458 * [www.kotlinlang.org](http://www.kotlinlang.org)

459 * spring.io

460 * repo.spring.io

461 </Accordion>

462 

463 <Accordion title="其他套件管理器">

464 * packagist.org (PHP Composer)

465 * [www.packagist.org](http://www.packagist.org)

466 * repo.packagist.org

467 * nuget.org (.NET NuGet)

468 * [www.nuget.org](http://www.nuget.org)

469 * api.nuget.org

470 * pub.dev (Dart/Flutter)

471 * api.pub.dev

472 * hex.pm (Elixir/Erlang)

473 * [www.hex.pm](http://www.hex.pm)

474 * cpan.org (Perl CPAN)

475 * [www.cpan.org](http://www.cpan.org)

476 * metacpan.org

477 * [www.metacpan.org](http://www.metacpan.org)

478 * api.metacpan.org

479 * cocoapods.org (iOS/macOS)

480 * [www.cocoapods.org](http://www.cocoapods.org)

481 * cdn.cocoapods.org

482 * haskell.org

483 * [www.haskell.org](http://www.haskell.org)

484 * hackage.haskell.org

485 * swift.org

486 * [www.swift.org](http://www.swift.org)

487 </Accordion>

488 

489 <Accordion title="Linux 發行版">

490 * archive.ubuntu.com

491 * security.ubuntu.com

492 * ubuntu.com

493 * [www.ubuntu.com](http://www.ubuntu.com)

494 * \*.ubuntu.com

495 * ppa.launchpad.net

496 * launchpad.net

497 * [www.launchpad.net](http://www.launchpad.net)

498 * \*.nixos.org

499 </Accordion>

500 

501 <Accordion title="開發工具和平台">

502 * dl.k8s.io (Kubernetes)

503 * pkgs.k8s.io

504 * k8s.io

505 * [www.k8s.io](http://www.k8s.io)

506 * releases.hashicorp.com (HashiCorp)

507 * apt.releases.hashicorp.com

508 * rpm.releases.hashicorp.com

509 * archive.releases.hashicorp.com

510 * hashicorp.com

511 * [www.hashicorp.com](http://www.hashicorp.com)

512 * repo.anaconda.com (Anaconda/Conda)

513 * conda.anaconda.org

514 * anaconda.org

515 * [www.anaconda.com](http://www.anaconda.com)

516 * anaconda.com

517 * continuum.io

518 * apache.org (Apache)

519 * [www.apache.org](http://www.apache.org)

520 * archive.apache.org

521 * downloads.apache.org

522 * eclipse.org (Eclipse)

523 * [www.eclipse.org](http://www.eclipse.org)

524 * download.eclipse.org

525 * nodejs.org (Node.js)

526 * [www.nodejs.org](http://www.nodejs.org)

527 * developer.apple.com

528 * developer.android.com

529 * pkg.stainless.com

530 * binaries.prisma.sh

531 </Accordion>

532 

533 <Accordion title="雲端服務和監控">

534 * statsig.com

535 * [www.statsig.com](http://www.statsig.com)

536 * api.statsig.com

537 * sentry.io

538 * \*.sentry.io

539 * downloads.sentry-cdn.com

540 * http-intake.logs.datadoghq.com

541 * \*.datadoghq.com

542 * \*.datadoghq.eu

543 * api.honeycomb.io

544 </Accordion>

545 

546 <Accordion title="內容傳遞和鏡像">

547 * sourceforge.net

548 * \*.sourceforge.net

549 * packagecloud.io

550 * \*.packagecloud.io

551 * fonts.googleapis.com

552 * fonts.gstatic.com

553 </Accordion>

554 

555 <Accordion title="架構和配置">

556 * json-schema.org

557 * [www.json-schema.org](http://www.json-schema.org)

558 * json.schemastore.org

559 * [www.schemastore.org](http://www.schemastore.org)

560 </Accordion>

561 

562 <Accordion title="Model Context Protocol">

563 * \*.modelcontextprotocol.io

564 </Accordion>

565</AccordionGroup>

566 

567## 在網頁和終端之間移動任務

568 

569這些工作流程需要[Claude Code CLI](/zh-TW/quickstart)登入到相同的 claude.ai 帳戶。您可以從終端啟動新的雲端工作階段,或將雲端工作階段拉入終端以在本機繼續。雲端工作階段即使在您關閉筆記型電腦後仍會保留,您可以從任何地方(包括 Claude 行動應用程式)監控它們。

570 

571<Note>

572 從 CLI,工作階段交接是單向的:您可以使用 `--teleport` 將雲端工作階段拉入終端,但無法將現有終端工作階段推送到網頁。`--remote` 旗標為您目前的儲存庫建立新的雲端工作階段。[Desktop 應用程式](/zh-TW/desktop#continue-in-another-surface)提供可將本機工作階段發送到網頁的'在另一個表面繼續'功能表。

573</Note>

574 

575### 從終端到網頁

576 

577使用 `--remote` 旗標從命令列啟動雲端工作階段:

578 

579```bash theme={null}

580claude --remote "Fix the authentication bug in src/auth/login.ts"

581```

582 

583這會在 claude.ai 上建立新的雲端工作階段。工作階段複製您目前目錄的 GitHub 遠端,位於您目前的分支,因此如果您有本機提交,請先推送,因為 VM 從 GitHub 而不是您的機器複製。`--remote` 一次適用於單一儲存庫。任務在雲端執行,而您繼續在本機工作。

584 

585<Note>

586 `--remote` 建立雲端工作階段。`--remote-control` 無關:它公開本機 CLI 工作階段以從網頁進行監控。請參閱[遠端控制](/zh-TW/remote-control)。

587</Note>

588 

589在 Claude Code CLI 中使用 `/tasks` 檢查進度,或在 claude.ai 或 Claude 行動應用程式上開啟工作階段以直接互動。從那裡,您可以引導 Claude、提供反饋或回答問題,就像任何其他對話一樣。

590 

591#### 雲端任務的提示

592 

593**在本機規劃,在遠端執行**:對於複雜任務,在規劃模式下啟動 Claude 以協作制定方法,然後將工作發送到雲端:

594 

595```bash theme={null}

596claude --permission-mode plan

597```

598 

599在規劃模式下,Claude 讀取檔案、執行命令以探索並提出計畫,而不編輯原始程式碼。一旦您對計畫感到滿意,將計畫保存到儲存庫、提交和推送,以便雲端 VM 可以複製它。然後為自主執行啟動雲端工作階段:

600 

601```bash theme={null}

602claude --remote "Execute the migration plan in docs/migration-plan.md"

603```

604 

605此模式讓您可以控制策略,同時讓 Claude 在雲端自主執行。

606 

607**使用 ultraplan 在雲端規劃**:若要在網頁工作階段中起草和檢查計畫本身,請使用 [ultraplan](/zh-TW/ultraplan)。Claude 在 Claude Code 網頁版上生成計畫,同時您繼續工作,然後您在瀏覽器中對部分進行評論並選擇遠端執行或將計畫發送回終端。

608 

609**並行執行任務**:每個 `--remote` 命令建立自己的雲端工作階段,獨立執行。您可以啟動多個任務,它們都會在單獨的工作階段中同時執行:

610 

611```bash theme={null}

612claude --remote "Fix the flaky test in auth.spec.ts"

613claude --remote "Update the API documentation"

614claude --remote "Refactor the logger to use structured output"

615```

616 

617使用 Claude Code CLI 中的 `/tasks` 監控所有工作階段。當工作階段完成時,您可以從網頁介面建立 PR,或[傳送](#from-web-to-terminal)工作階段到終端以繼續工作。

618 

619#### 發送沒有 GitHub 的本機儲存庫

620 

621當您從未連接到 GitHub 的儲存庫執行 `claude --remote` 時,Claude Code 會捆綁您的本機儲存庫並直接上傳到雲端工作階段。捆綁包括您的完整儲存庫歷史記錄,跨所有分支,加上任何未提交的對追蹤檔案的變更。

622 

623當 GitHub 存取不可用時,此回退會自動啟動。若要即使在 GitHub 已連接時也強制它,請設定 `CCR_FORCE_BUNDLE=1`:

624 

625```bash theme={null}

626CCR_FORCE_BUNDLE=1 claude --remote "Run the test suite and fix any failures"

627```

628 

629捆綁的儲存庫必須符合這些限制:

630 

631* 目錄必須是至少有一個提交的 git 儲存庫

632* 捆綁的儲存庫必須在 100 MB 以下。較大的儲存庫回退到僅捆綁目前分支,然後回退到工作樹的單一壓縮快照,並且僅在快照仍然太大時失敗

633* 未追蹤的檔案不包括;在您希望雲端工作階段看到的檔案上執行 `git add`

634* 從捆綁建立的工作階段無法推送回遠端,除非您也配置了 [GitHub 驗證](#github-authentication-options)

635 

636### 從網頁到終端

637 

638使用以下任何方式將雲端工作階段拉入終端:

639 

640* **使用 `--teleport`**:從命令列,執行 `claude --teleport` 以進行互動式工作階段選擇器,或執行 `claude --teleport <session-id>` 以直接恢復特定工作階段。如果您有未提交的變更,系統會提示您先隱藏它們。

641* **使用 `/teleport`**:在現有 CLI 工作階段內,執行 `/teleport`(或 `/tp`)以開啟相同的工作階段選擇器,而無需重新啟動 Claude Code。

642* **從 `/tasks`**:執行 `/tasks` 以查看您的背景工作階段,然後按 `t` 傳送到其中一個

643* **從網頁介面**:選擇**在 CLI 中開啟**以複製可貼到終端的命令

644 

645當您傳送工作階段時,Claude 驗證您在正確的儲存庫中,從雲端工作階段取得並簽出分支,並將完整的對話歷史記錄載入到終端。

646 

647`--teleport` 與 `--resume` 不同。`--resume` 從此機器的本機歷史記錄重新開啟對話,不列出雲端工作階段;`--teleport` 拉取雲端工作階段及其分支。

648 

649#### 傳送要求

650 

651傳送在恢復工作階段之前檢查這些要求。如果任何要求未滿足,您會看到錯誤或被提示解決問題。

652 

653| 要求 | 詳細資訊 |

654| ---------- | ---------------------------------- |

655| 乾淨的 git 狀態 | 您的工作目錄必須沒有未提交的變更。如果需要,傳送會提示您隱藏變更。 |

656| 正確的儲存庫 | 您必須從同一儲存庫的簽出執行 `--teleport`,而不是分支。 |

657| 分支可用 | 雲端工作階段中的分支必須已推送到遠端。傳送會自動取得並簽出它。 |

658| 相同帳戶 | 您必須驗證到雲端工作階段中使用的相同 claude.ai 帳戶。 |

659 

660#### `--teleport` 不可用

661 

662傳送需要 claude.ai 訂閱驗證。如果您通過 API 金鑰、Bedrock、Vertex AI 或 Microsoft Foundry 進行驗證,請執行 `/login` 以改為使用您的 claude.ai 帳戶登入。如果您已通過 claude.ai 登入,`--teleport` 仍不可用,您的組織可能已禁用雲端工作階段。

663 

664## 使用工作階段

665 

666工作階段出現在 claude.ai/code 的側邊欄中。從那裡,您可以檢查變更、與隊友共享、封存完成的工作或永久刪除工作階段。

667 

668### 管理上下文

669 

670雲端工作階段支援產生文字輸出的[內建命令](/zh-TW/commands)。開啟互動式終端選擇器的命令(如 `/model` 或 `/config`)不可用。

671 

672對於上下文管理特別:

673 

674| 命令 | 在雲端工作階段中有效 | 備註 |

675| :--------- | :--------- | :----------------------------------------------------- |

676| `/compact` | 是 | 總結對話以釋放上下文。接受可選的焦點指示,如 `/compact keep the test output` |

677| `/context` | 是 | 顯示目前在上下文視窗中的內容 |

678| `/clear` | 否 | 改為從側邊欄啟動新工作階段 |

679 

680自動壓縮在上下文視窗接近容量時自動執行,與 CLI 中相同。若要更早觸發它,請在您的[環境變數](#configure-your-environment)中設定 [`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`](/zh-TW/env-vars)。例如,`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=70` 在 70% 容量而不是預設 \~95% 時壓縮。若要更改壓縮計算的有效視窗大小,請使用 [`CLAUDE_CODE_AUTO_COMPACT_WINDOW`](/zh-TW/env-vars)。

681 

682[Subagents](/zh-TW/sub-agents) 的運作方式與本機相同。Claude 可以使用 Task 工具生成它們,以將研究或並行工作卸載到單獨的上下文視窗中,保持主對話更輕。在您的儲存庫的 `.claude/agents/` 中定義的 Subagents 會自動選擇。[Agent teams](/zh-TW/agent-teams) 預設關閉,但可以通過將 `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` 新增到您的[環境變數](#configure-your-environment)來啟用。

683 

684### 檢查變更

685 

686每個工作階段顯示一個差異指示器,其中包含新增和移除的行數,例如 `+42 -18`。選擇它以開啟差異檢視,在特定行上留下內聯評論,並使用您的下一條訊息將它們發送給 Claude。有關完整逐步說明(包括 PR 建立),請參閱[檢查和迭代](/zh-TW/web-quickstart#review-and-iterate)。若要讓 Claude 自動監控 PR 以查找 CI 失敗和審查評論,請參閱[自動修復拉取請求](#auto-fix-pull-requests)。

687 

688### 共享工作階段

689 

690若要共享工作階段,請根據下面的帳戶類型切換其可見性。之後,按原樣共享工作階段連結。收件者在開啟連結時看到最新狀態,但他們的檢視不會即時更新。

691 

692#### 從 Enterprise 或 Team 帳戶共享

693 

694對於 Enterprise 和 Team 帳戶,兩個可見性選項是**私人**和**Team**。Team 可見性使工作階段對您的 claude.ai 組織的其他成員可見。儲存庫存取驗證預設啟用,基於連接到收件者帳戶的 GitHub 帳戶。您帳戶的顯示名稱對所有有存取權限的收件者可見。[Slack 中的 Claude](/zh-TW/slack)工作階段會自動以 Team 可見性共享。

695 

696#### 從 Max 或 Pro 帳戶共享

697 

698對於 Max 和 Pro 帳戶,兩個可見性選項是**私人**和**公開**。公開可見性使工作階段對任何登入 claude.ai 的使用者可見。

699 

700在共享之前檢查您的工作階段是否包含敏感內容。工作階段可能包含來自私人 GitHub 儲存庫的程式碼和認證。儲存庫存取驗證預設未啟用。

701 

702若要要求收件者具有儲存庫存取權限,或從共享工作階段中隱藏您的名稱,請前往「設定」>「Claude Code」>「共享設定」。

703 

704### 封存工作階段

705 

706您可以封存工作階段以保持工作階段清單的組織。封存的工作階段隱藏在預設工作階段清單中,但可以通過篩選封存的工作階段來檢視。

707 

708若要封存工作階段,請在側邊欄中將滑鼠懸停在工作階段上,然後選擇封存圖示。

709 

710### 刪除工作階段

711 

712刪除工作階段會永久移除工作階段及其資料。此操作無法撤銷。您可以通過兩種方式刪除工作階段:

713 

714* **從側邊欄**:篩選封存的工作階段,然後將滑鼠懸停在您要刪除的工作階段上,並選擇刪除圖示

715* **從工作階段功能表**:開啟工作階段,選擇工作階段標題旁的下拉式功能表,然後選擇**刪除**

716 

717在刪除工作階段之前,系統會要求您確認。

718 

719## 自動修復拉取請求

720 

721Claude 可以監視拉取請求並自動回應 CI 失敗和審查評論。Claude 訂閱 PR 上的 GitHub 活動,當檢查失敗或審查者留下評論時,Claude 會調查並推送修復(如果有明確的修復)。

722 

723<Note>

724 自動修復需要在您的儲存庫上安裝 Claude GitHub App。如果您還沒有,請從 [GitHub App 頁面](https://github.com/apps/claude)安裝它,或在[設定](/zh-TW/web-quickstart#connect-github-and-create-an-environment)期間出現提示時安裝。

725</Note>

726 

727根據 PR 來自何處以及您使用的設備,有幾種方式可以開啟自動修復:

728 

729* **在 Claude Code 網頁版中建立的 PR**:開啟 CI 狀態欄並選擇**自動修復**

730* **從您的終端**:在 PR 的分支上執行 [`/autofix-pr`](/zh-TW/commands)。Claude Code 使用 `gh` 偵測開啟的 PR,生成網頁工作階段,並在一個步驟中開啟自動修復

731* **從行動應用程式**:告訴 Claude 自動修復 PR,例如「監視此 PR 並修復任何 CI 失敗或審查評論」

732* **任何現有 PR**:將 PR URL 貼到工作階段中並告訴 Claude 自動修復它

733 

734### Claude 如何回應 PR 活動

735 

736當自動修復處於活動狀態時,Claude 會收到 PR 的 GitHub 事件,包括新的審查評論和 CI 檢查失敗。對於每個事件,Claude 會調查並決定如何進行:

737 

738* **明確的修復**:如果 Claude 對修復有信心且不與早期指示衝突,Claude 會進行變更、推送它,並在工作階段中解釋所做的工作

739* **模糊的請求**:如果審查者的評論可以以多種方式解釋或涉及架構上重要的內容,Claude 會在採取行動前詢問您

740* **重複或無操作事件**:如果事件是重複的或不需要變更,Claude 會在工作階段中記錄它並繼續

741 

742Claude 可能會在 GitHub 上回覆審查評論執行緒作為解決它們的一部分。這些回覆使用您的 GitHub 帳戶發佈,因此它們會出現在您的使用者名稱下,但每個回覆都標記為來自 Claude Code,以便審查者知道它是由代理編寫的,而不是由您直接編寫的。

743 

744<Warning>

745 如果您的儲存庫使用評論觸發的自動化,例如 Atlantis、Terraform Cloud 或在 `issue_comment` 事件上執行的自訂 GitHub Actions,請注意 Claude 可以代表您回覆,這可能會觸發這些工作流程。在啟用自動修復之前檢查您的儲存庫自動化,並考慮為 PR 評論可以部署基礎設施或執行特權操作的儲存庫禁用自動修復。

746</Warning>

747 

748## 安全性和隔離

749 

750每個雲端工作階段通過多個層與您的機器和其他工作階段分離:

751 

752* **隔離的虛擬機器**:每個工作階段在隔離的 Anthropic 管理的 VM 中執行

753* **網路存取控制**:網路存取預設受限,可以禁用。在禁用網路存取的情況下執行時,Claude Code 仍然可以與 Anthropic API 通訊,這可能允許資料離開 VM。

754* **認證保護**:敏感認證(如 git 認證或簽署金鑰)永遠不在沙箱內與 Claude Code 一起。驗證通過使用限定認證的安全代理進行處理。

755* **安全分析**:程式碼在隔離的 VM 內進行分析和修改,然後建立 PR

756 

757## 限制

758 

759在依賴雲端工作階段進行工作流程之前,請考慮這些限制:

760 

761* **速率限制**:Claude Code 網頁版與您帳戶內所有其他 Claude 和 Claude Code 使用共享速率限制。並行執行多個任務會按比例消耗更多速率限制。雲端 VM 沒有單獨的計算費用。

762* **儲存庫驗證**:您只能在驗證到相同帳戶時將工作階段從網頁移動到本機

763* **平台限制**:儲存庫複製和拉取請求建立需要 GitHub。自託管[GitHub Enterprise Server](/zh-TW/github-enterprise-server) 執行個體支援 Team 和 Enterprise 計畫。GitLab、Bitbucket 和其他非 GitHub 儲存庫可以作為[本機捆綁](#send-local-repositories-without-github)發送到雲端工作階段,但工作階段無法將結果推送回遠端

764 

765## 相關資源

766 

767* [Ultraplan](/zh-TW/ultraplan):在雲端工作階段中起草計畫並在瀏覽器中檢查它

768* [Ultrareview](/zh-TW/ultrareview):在雲端沙箱中執行深度多代理程式碼審查

769* [Routines](/zh-TW/routines):自動化按排程、通過 API 呼叫或回應 GitHub 事件的工作

770* [Hooks 配置](/zh-TW/hooks):在工作階段生命週期事件執行指令碼

771* [設定參考](/zh-TW/settings):所有配置選項

772* [安全性](/zh-TW/security):隔離保證和資料處理

773* [資料使用](/zh-TW/data-usage):Anthropic 從雲端工作階段保留的內容

claude-directory.md +1596 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 探索 .claude 目錄

6 

7> Claude Code 讀取 CLAUDE.md、settings.json、hooks、skills、commands、subagents、rules 和自動記憶的位置。探索您專案中的 .claude 目錄和主目錄中的 ~/.claude。

8 

9export const ClaudeExplorer = () => {

10 const A = useMemo(() => ({href, children}) => <a href={href} style={{

11 color: 'var(--ce-accent)',

12 textDecoration: 'none',

13 borderBottom: '1px dotted var(--ce-accent)'

14 }}>{children}</a>, []);

15 const C = useMemo(() => ({children}) => <code style={{

16 fontFamily: 'var(--ce-mono)',

17 fontSize: '0.92em',

18 padding: '1px 4px',

19 borderRadius: '3px',

20 background: 'var(--ce-surface)',

21 border: '0.5px solid var(--ce-border-subtle)'

22 }}>{children}</code>, []);

23 const commandsNote = useMemo(() => <>Commands and skills are now the same mechanism. For new workflows, use <A href="/en/skills">skills/</A> instead: same <C>/name</C> invocation, plus you can bundle supporting files.</>, []);

24 const FILE_TREE = useMemo(() => ({

25 project: {

26 label: 'your-project/',

27 children: [{

28 id: 'claude-md',

29 label: 'CLAUDE.md',

30 type: 'file',

31 icon: 'md',

32 color: '#6A9BCC',

33 badge: 'committed',

34 oneLiner: 'Project instructions Claude reads every session',

35 when: 'Loaded into context at the start of every session',

36 description: 'Project-specific instructions that shape how Claude works in this repository. Put your conventions, common commands, and architectural context here so Claude operates with the same assumptions your team does.',

37 tips: ['Target under 200 lines. Longer files still load in full but may reduce adherence', <>CLAUDE.md loads into every session. If something only matters for specific tasks, move it to a <A href="/en/skills">skill</A> or a path-scoped <A href="/en/memory#organize-rules-with-claude/rules/">rule</A> so it loads only when needed</>, 'List the commands you run most, like build, test, and format, so Claude knows them without you spelling them out each time', <>Run <C>/memory</C> to open and edit CLAUDE.md from within a session</>, <>Also works at <C>.claude/CLAUDE.md</C> if you prefer to keep the project root clean</>],

38 exampleIntro: 'This example is for a TypeScript and React project. It lists the build and test commands, the framework conventions Claude should follow, and project-specific rules like export style and file layout.',

39 example: `# Project conventions

40 

41## Commands

42- Build: \`npm run build\`

43- Test: \`npm test\`

44- Lint: \`npm run lint\`

45 

46## Stack

47- TypeScript with strict mode

48- React 19, functional components only

49 

50## Rules

51- Named exports, never default exports

52- Tests live next to source: \`foo.ts\` -> \`foo.test.ts\`

53- All API routes return \`{ data, error }\` shape`,

54 docsLink: '/en/memory'

55 }, {

56 id: 'mcp-json',

57 label: '.mcp.json',

58 type: 'file',

59 icon: 'json',

60 color: '#9B7BC4',

61 badge: 'committed',

62 oneLiner: 'Project-scoped MCP servers, shared with your team',

63 when: <>Servers connect when the session begins. Tool schemas are deferred by default and load on demand via <A href="/en/mcp#scale-with-mcp-tool-search">tool search</A></>,

64 description: <>Configures Model Context Protocol (MCP) servers that give Claude access to external tools: databases, APIs, browsers, and more. This file holds the project-scoped servers your whole team uses. Personal servers you want to keep to yourself go in <C>~/.claude.json</C> instead.</>,

65 tips: [<>Use environment variable references for secrets: <C>{'${GITHUB_TOKEN}'}</C></>, <>Lives at the project root, not inside <C>.claude/</C></>, <>For servers only you need, run <C>claude mcp add --scope user</C>. This writes to <C>~/.claude.json</C> instead of <C>.mcp.json</C></>],

66 exampleIntro: <>This example configures the GitHub MCP server so Claude can read issues and open pull requests. The <C>{'${GITHUB_TOKEN}'}</C> reference is read from your shell environment when Claude Code starts the server, so the token never lands in the file.</>,

67 example: `{

68 "mcpServers": {

69 "github": {

70 "command": "npx",

71 "args": ["-y", "@modelcontextprotocol/server-github"],

72 "env": {

73 "GITHUB_TOKEN": "\${GITHUB_TOKEN}"

74 }

75 }

76 }

77}`,

78 docsLink: '/en/mcp'

79 }, {

80 id: 'worktreeinclude',

81 label: '.worktreeinclude',

82 type: 'file',

83 icon: 'md',

84 color: '#8FA876',

85 badge: 'committed',

86 oneLiner: 'Gitignored files to copy into new worktrees',

87 when: <>Read when Claude creates a git worktree via <C>--worktree</C>, the <C>EnterWorktree</C> tool, or subagent <C>isolation: worktree</C></>,

88 description: <>Lists gitignored files to copy from your main repository into each new worktree. Worktrees are fresh checkouts, so untracked files like <C>.env</C> are missing by default. Patterns here use <C>.gitignore</C> syntax. Only files that match a pattern and are also gitignored get copied, so tracked files are never duplicated.</>,

89 tips: [<>Lives at the project root, not inside <C>.claude/</C></>, <>Git-only: if you configure a <A href="/en/hooks#worktreecreate">WorktreeCreate hook</A> for a different VCS, this file is not read. Copy files inside your hook script instead</>, <>Also applies to parallel sessions in the <A href="/en/desktop#work-in-parallel-with-sessions">desktop app</A></>],

90 exampleIntro: 'This example copies your local environment files and a secrets config into every worktree Claude creates. Comments start with # and blank lines are ignored, same as .gitignore.',

91 example: `# Local environment

92.env

93.env.local

94 

95# API credentials

96config/secrets.json`,

97 docsLink: '/en/worktrees#copy-gitignored-files-into-worktrees'

98 }, {

99 id: 'dot-claude',

100 label: '.claude/',

101 type: 'folder',

102 icon: 'folder',

103 color: 'var(--ce-accent)',

104 oneLiner: 'Project-level configuration, rules, and extensions',

105 description: 'Everything Claude Code reads that is specific to this project. If you use git, commit most files here so your team shares them; a few, like settings.local.json, are automatically gitignored. Each file badge shows which.',

106 children: [{

107 id: 'settings-json',

108 label: 'settings.json',

109 type: 'file',

110 icon: 'json',

111 color: 'var(--ce-text-3)',

112 badge: 'committed',

113 oneLiner: 'Permissions, hooks, and configuration',

114 when: <>Overrides global <C>~/.claude/settings.json</C>. Local settings, CLI flags, and managed settings override this</>,

115 description: 'Settings that Claude Code applies directly. Permissions control which commands and tools Claude can use; hooks run your scripts at specific points in a session. Unlike CLAUDE.md, which Claude reads as guidance, these are enforced whether Claude follows them or not.',

116 contains: [<><A href="/en/permissions">permissions</A>: allow, deny, or prompt before Claude uses specific tools or commands</>, <><A href="/en/hooks">hooks</A>: run your own scripts on events like before a tool call or after a file edit</>, <><A href="/en/statusline">statusLine</A>: customize the line shown at the bottom while Claude works</>, <><A href="/en/settings#available-settings">model</A>: pick a default model for this project</>, <><A href="/en/settings#environment-variables">env</A>: environment variables set in every session</>, <><A href="/en/output-styles">outputStyle</A>: select a custom system-prompt style from output-styles/</>],

117 tips: [<>Bash permission patterns support wildcards: <C>Bash(npm test *)</C> matches any command starting with <C>npm test</C></>, <>Array settings like <C>permissions.allow</C> combine across all scopes; scalar settings like <C>model</C> use the most specific value</>],

118 exampleIntro: <>This example allows <C>npm test</C> and <C>npm run</C> commands without prompting, blocks <C>rm -rf</C>, and runs Prettier on files after Claude edits or writes them.</>,

119 example: `{

120 "permissions": {

121 "allow": [

122 "Bash(npm test *)",

123 "Bash(npm run *)"

124 ],

125 "deny": [

126 "Bash(rm -rf *)"

127 ]

128 },

129 "hooks": {

130 "PostToolUse": [{

131 "matcher": "Edit|Write",

132 "hooks": [{

133 "type": "command",

134 "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"

135 }]

136 }]

137 }

138}`,

139 docsLink: '/en/settings'

140 }, {

141 id: 'settings-local-json',

142 label: 'settings.local.json',

143 type: 'file',

144 icon: 'json',

145 color: 'var(--ce-text-3)',

146 badge: 'gitignored',

147 oneLiner: 'Your personal settings overrides for this project',

148 when: 'Highest of the user-editable settings files; CLI flags and managed settings still take precedence',

149 description: 'Personal settings that take precedence over the project defaults. Same JSON format as settings.json, but not committed. Use this when you need different permissions or defaults than the team config.',

150 tips: [<>Same schema as settings.json. Array settings like <C>permissions.allow</C> combine across scopes; scalar settings like <C>model</C> use the local value</>, <>Claude Code adds this file to <C>~/.config/git/ignore</C> the first time it writes one. If you use a custom <C>core.excludesFile</C>, add the pattern there too. To share the ignore rule with your team, also add it to the project <C>.gitignore</C></>],

151 exampleIntro: 'This example adds Docker permissions on top of whatever the team settings.json allows.',

152 example: `{

153 "permissions": {

154 "allow": [

155 "Bash(docker *)"

156 ]

157 }

158}`,

159 docsLink: '/en/settings'

160 }, {

161 id: 'rules',

162 label: 'rules/',

163 type: 'folder',

164 icon: 'folder',

165 color: '#9B7BC4',

166 oneLiner: 'Topic-scoped instructions, optionally gated by file paths',

167 when: <>Rules without <C>paths:</C> load at session start. Rules with <C>paths:</C> load when a matching file enters context</>,

168 description: [<>Project instructions split into topic files that can load conditionally based on file paths. A rule without <C>paths:</C> frontmatter loads at session start like CLAUDE.md; a rule with <C>paths:</C> loads only when Claude reads a matching file.</>, <>Like CLAUDE.md, rules are guidance Claude reads, not configuration Claude Code enforces. For guaranteed behavior use <A href="/en/hooks">hooks</A> or <A href="/en/permissions">permissions</A>.</>],

169 tips: [<>Use <C>paths:</C> frontmatter with globs to scope rules to directories or file types</>, <>Subdirectories work: <C>.claude/rules/frontend/react.md</C> is discovered automatically</>, 'When CLAUDE.md approaches 200 lines, start splitting into rules'],

170 docsLink: '/en/memory#organize-rules-with-claude/rules/',

171 children: [{

172 id: 'rule-testing',

173 label: 'testing.md',

174 type: 'file',

175 icon: 'md',

176 color: '#9B7BC4',

177 badge: 'committed',

178 oneLiner: 'Test conventions scoped to test files',

179 when: <>Loaded when Claude reads a file matching the <C>paths:</C> globs below</>,

180 description: <>An example rule that only loads when Claude is working on test files. The <C>paths:</C> globs in the frontmatter define which files trigger it; here, anything ending in .test.ts or .test.tsx. For other files, this rule is not loaded into context.</>,

181 example: `---

182paths:

183 - "**/*.test.ts"

184 - "**/*.test.tsx"

185---

186 

187# Testing Rules

188 

189- Use descriptive test names: "should [expected] when [condition]"

190- Mock external dependencies, not internal modules

191- Clean up side effects in afterEach`

192 }, {

193 id: 'rule-api',

194 label: 'api-design.md',

195 type: 'file',

196 icon: 'md',

197 color: '#9B7BC4',

198 badge: 'committed',

199 oneLiner: 'API conventions scoped to backend code',

200 when: <>Loaded when Claude reads a file matching the <C>paths:</C> glob below</>,

201 description: <>A second example showing a rule scoped to backend code. The <C>paths:</C> glob matches files under src/api/, so these conventions load only when Claude is editing API routes.</>,

202 example: `---

203paths:

204 - "src/api/**/*.ts"

205---

206 

207# API Design Rules

208 

209- All endpoints must validate input with Zod schemas

210- Return shape: { data: T } | { error: string }

211- Rate limit all public endpoints`

212 }]

213 }, {

214 id: 'skills',

215 label: 'skills/',

216 type: 'folder',

217 icon: 'folder',

218 color: '#D4A843',

219 oneLiner: 'Reusable prompts you or Claude invoke by name',

220 when: <>Invoked with <C>/skill-name</C> or when Claude matches the task to a skill</>,

221 description: <>Each skill is a folder with a SKILL.md file plus any supporting files it needs. By default, both you and Claude can invoke a skill. Use frontmatter to control that: <C>disable-model-invocation: true</C> for user-only workflows like <C>/deploy</C>, or <C>user-invocable: false</C> to hide from the <C>/</C> menu while Claude can still invoke it.</>,

222 tips: [<>Skills accept arguments: <C>/deploy staging</C> passes "staging" as <C>$ARGUMENTS</C>. Use <C>$0</C>, <C>$1</C>, and so on for positional access</>, <>The <C>description</C> frontmatter determines when Claude auto-invokes the skill</>, 'Bundle reference docs alongside SKILL.md. Claude knows the skill directory path and can read supporting files when you mention them'],

223 docsLink: '/en/skills',

224 children: [{

225 id: 'skill-review',

226 label: 'security-review/',

227 type: 'folder',

228 icon: 'folder',

229 color: '#D4A843',

230 oneLiner: 'A skill bundling SKILL.md with supporting files',

231 children: [{

232 id: 'skill-review-md',

233 label: 'SKILL.md',

234 type: 'file',

235 icon: 'md',

236 color: '#D4A843',

237 badge: 'committed',

238 oneLiner: 'Entrypoint: trigger, invocability, instructions',

239 when: <>User types <C>/security-review &lt;target&gt;</C>; Claude cannot auto-invoke this skill</>,

240 description: [<>This skill uses <C>disable-model-invocation: true</C> so only you can trigger it; Claude never invokes it on its own.</>, <>The <C>!`...`</C> line runs a shell command and injects its output into the prompt. <C>$ARGUMENTS</C> substitutes whatever you typed after the skill name. Claude sees the skill directory path, so mentioning a bundled file like checklist.md lets Claude read it.</>],

241 example: `---

242description: Reviews code changes for security vulnerabilities, authentication gaps, and injection risks

243disable-model-invocation: true

244argument-hint: <branch-or-path>

245---

246 

247## Diff to review

248 

249!\`git diff $ARGUMENTS\`

250 

251Audit the changes above for:

252 

2531. Injection vulnerabilities (SQL, XSS, command)

2542. Authentication and authorization gaps

2553. Hardcoded secrets or credentials

256 

257Use checklist.md in this skill directory for the full review checklist.

258 

259Report findings with severity ratings and remediation steps.`

260 }, {

261 id: 'skill-checklist',

262 label: 'checklist.md',

263 type: 'file',

264 icon: 'md',

265 color: '#D4A843',

266 badge: 'committed',

267 oneLiner: 'Supporting file bundled with the skill',

268 when: 'Claude reads it on demand while running the skill',

269 description: <>Skills can bundle any supporting files: reference docs, templates, scripts. The skill directory path is prepended to SKILL.md, so Claude can read bundled files by name. For scripts in bash injection commands, use the <C>{'${CLAUDE_SKILL_DIR}'}</C> placeholder.</>,

270 example: `# Security Review Checklist

271 

272## Input Validation

273- [ ] All user input sanitized before DB queries

274- [ ] File upload MIME types validated

275- [ ] Path traversal prevented on file operations

276 

277## Authentication

278- [ ] JWT tokens expire after 24 hours

279- [ ] API keys stored in environment variables

280- [ ] Passwords hashed with bcrypt or argon2`

281 }]

282 }]

283 }, {

284 id: 'commands',

285 label: 'commands/',

286 type: 'folder',

287 icon: 'folder',

288 color: '#788C5D',

289 oneLiner: <>Single-file prompts invoked with <C>/name</C></>,

290 note: commandsNote,

291 when: <>User types <C>/command-name</C></>,

292 description: <>A file at <C>commands/deploy.md</C> creates <C>/deploy</C> the same way a skill at <C>skills/deploy/SKILL.md</C> does, and both can be auto-invoked by Claude. Skills use a directory with SKILL.md, letting you bundle reference docs, templates, or scripts alongside the prompt.</>,

293 tips: [<>Use <C>$ARGUMENTS</C> in the file to accept parameters: <C>/fix-issue 123</C></>, 'If a skill and command share a name, the skill takes precedence', 'New commands should usually be skills instead; commands remain supported'],

294 docsLink: '/en/skills',

295 children: [{

296 id: 'cmd-example',

297 label: 'fix-issue.md',

298 type: 'file',

299 icon: 'md',

300 color: '#788C5D',

301 badge: 'committed',

302 oneLiner: <>Invoked as <C>/fix-issue &lt;number&gt;</C></>,

303 note: commandsNote,

304 description: [<>An example command for fixing a GitHub issue. Type <C>/fix-issue 123</C> and the <C>!`...`</C> line runs <C>gh issue view 123</C> in your shell, injecting the output into the prompt before Claude sees it.</>, <><C>$ARGUMENTS</C> substitutes whatever you typed after the command name. For positional access, use <C>$0</C> <C>$1</C> and so on.</>],

305 example: `---

306argument-hint: <issue-number>

307---

308 

309!\`gh issue view $ARGUMENTS\`

310 

311Investigate and fix the issue above.

312 

3131. Trace the bug to its root cause

3142. Implement the fix

3153. Write or update tests

3164. Summarize what you changed and why`

317 }]

318 }, {

319 id: 'output-styles',

320 label: 'output-styles/',

321 type: 'folder',

322 icon: 'folder',

323 color: '#5AA7A7',

324 oneLiner: 'Project-scoped output styles, if your team shares any',

325 when: 'Applied at session start when selected via the outputStyle setting',

326 description: <>Output styles are usually personal, so most live in <C>~/.claude/output-styles/</C>. Put one here if your team shares a style, like a review mode everyone uses. See <A href="#ce-global-output-styles">the Global tab</A> for the full explanation and example.</>,

327 docsLink: '/en/output-styles',

328 children: []

329 }, {

330 id: 'agents',

331 label: 'agents/',

332 type: 'folder',

333 icon: 'folder',

334 color: '#C46686',

335 oneLiner: 'Specialized subagents with their own context window',

336 when: 'Runs in its own context window when you or Claude invoke it',

337 description: 'Each markdown file defines a subagent with its own system prompt, tool access, and optionally its own model. Subagents run in a fresh context window, keeping the main conversation clean. Useful for parallel work or isolated tasks.',

338 tips: ['Each agent gets a fresh context window, separate from your main session', <>Restrict tool access per agent with the <C>tools:</C> frontmatter field</>, 'Type @ and pick an agent from the autocomplete to delegate directly'],

339 docsLink: '/en/sub-agents',

340 children: [{

341 id: 'agent-reviewer',

342 label: 'code-reviewer.md',

343 type: 'file',

344 icon: 'md',

345 color: '#C46686',

346 badge: 'committed',

347 oneLiner: 'Subagent for isolated code review',

348 when: 'Claude spawns it for review tasks, or you @-mention it from the autocomplete',

349 description: <>An example subagent restricted to read-only tools. The <C>description</C> frontmatter tells Claude when to delegate to it automatically; <C>tools:</C> limits it to Read, Grep, and Glob so it can inspect code but never edit. The body becomes the subagent's system prompt.</>,

350 example: `---

351name: code-reviewer

352description: Reviews code for correctness, security, and maintainability

353tools: Read, Grep, Glob

354---

355 

356You are a senior code reviewer. Review for:

357 

3581. Correctness: logic errors, edge cases, null handling

3592. Security: injection, auth bypass, data exposure

3603. Maintainability: naming, complexity, duplication

361 

362Every finding must include a concrete fix.`

363 }]

364 }, {

365 id: 'agent-memory',

366 label: 'agent-memory/',

367 type: 'folder',

368 icon: 'folder',

369 color: '#C46686',

370 badge: 'committed',

371 autogen: true,

372 oneLiner: 'Subagent persistent memory, separate from your main session auto memory',

373 when: 'First 200 lines (capped at 25KB) of MEMORY.md loaded into the subagent system prompt when it runs',

374 description: <>Subagents with <C>memory: project</C> in their frontmatter get a dedicated memory directory here. This is distinct from your <A href="/en/memory#auto-memory">main session auto memory</A> at <C>~/.claude/projects/</C>: each subagent reads and writes its own MEMORY.md, not yours.</>,

375 tips: [<>Only created for subagents that set the <C>memory:</C> frontmatter field</>, <>This directory holds project-scoped subagent memory, meant to be shared with your team. To keep memory out of version control use <C>memory: local</C>, which writes to <C>.claude/agent-memory-local/</C> instead. For cross-project memory use <C>memory: user</C>, which writes to <C>~/.claude/agent-memory/</C></>, <>The main session auto memory is a different feature; see <C>~/.claude/projects/</C> in the Global tab</>],

376 docsLink: '/en/sub-agents#enable-persistent-memory',

377 children: [{

378 id: 'agent-memory-sub',

379 label: '<agent-name>/',

380 type: 'folder',

381 icon: 'folder',

382 color: '#C46686',

383 autogen: true,

384 children: [{

385 id: 'agent-memory-md',

386 label: 'MEMORY.md',

387 type: 'file',

388 icon: 'md',

389 color: '#C46686',

390 badge: 'committed',

391 autogen: true,

392 oneLiner: 'The subagent writes and maintains this file automatically',

393 when: 'Loaded into the subagent system prompt when the subagent starts',

394 description: <>Works the same as your <A href="/en/memory#auto-memory">main auto memory</A>: the subagent creates and updates this file itself. You do not write it. The subagent reads it at the start of each task and writes back what it learns.</>,

395 example: `# code-reviewer memory

396 

397## Patterns seen

398- Project uses custom Result<T, E> type, not exceptions

399- Auth middleware expects Bearer token in Authorization header

400- Tests use factory functions in test/factories/

401 

402## Recurring issues

403- Missing null checks on API responses (src/api/*)

404- Unhandled promise rejections in background jobs`

405 }]

406 }]

407 }]

408 }]

409 },

410 global: {

411 label: '~/',

412 children: [{

413 id: 'claude-json',

414 label: '.claude.json',

415 type: 'file',

416 icon: 'json',

417 color: 'var(--ce-text-3)',

418 badge: 'local',

419 oneLiner: 'App state and UI preferences',

420 when: <>Read at session start for your preferences and MCP servers. Claude Code writes back to it when you change settings in <C>/config</C> or approve trust prompts</>,

421 description: <>Holds state that does not belong in settings.json: theme, OAuth session, per-project trust decisions, your personal MCP servers, and UI toggles. Mostly managed through <C>/config</C> rather than editing directly.</>,

422 tips: [<>IDE toggles like <C>autoConnectIde</C> and <C>externalEditorContext</C> live here, not in settings.json</>, <>The <C>projects</C> key tracks per-project state like trust-dialog acceptance and last-session metrics. Permission rules you approve in-session go to <C>.claude/settings.local.json</C> instead</>, <>MCP servers here are yours only: user scope applies across all projects, local scope is per-project but not committed. Team-shared servers go in <C>.mcp.json</C> at the project root instead</>],

423 example: `{

424 "autoConnectIde": true,

425 "externalEditorContext": true,

426 "mcpServers": {

427 "my-tools": {

428 "command": "npx",

429 "args": ["-y", "@example/mcp-server"]

430 }

431 }

432}`,

433 docsLink: '/en/settings#global-config-settings'

434 }, {

435 id: 'global-dot-claude',

436 label: '.claude/',

437 type: 'folder',

438 icon: 'folder',

439 color: 'var(--ce-accent)',

440 oneLiner: 'Your personal configuration across all projects',

441 description: 'The global counterpart to your project .claude/ directory. Files here apply to every project you work in and are never committed to any repository.',

442 children: [{

443 id: 'global-claude-md',

444 label: 'CLAUDE.md',

445 type: 'file',

446 icon: 'md',

447 color: '#6A9BCC',

448 badge: 'local',

449 oneLiner: 'Personal preferences across every project',

450 when: 'Loaded at the start of every session, in every project',

451 description: 'Your global instruction file. Loaded alongside the project CLAUDE.md at session start, so both are in context together. When instructions conflict, project-level instructions take priority. Keep this to preferences that apply everywhere: response style, commit format, personal conventions.',

452 tips: ['Keep it short since it loads into context for every project, alongside that project\'s own CLAUDE.md', 'Good for response style, commit format, and personal conventions'],

453 example: `# Global preferences

454 

455- Keep explanations concise

456- Use conventional commit format

457- Show the terminal command to verify changes

458- Prefer composition over inheritance`,

459 docsLink: '/en/memory'

460 }, {

461 id: 'global-settings',

462 label: 'settings.json',

463 type: 'file',

464 icon: 'json',

465 color: 'var(--ce-text-3)',

466 badge: 'local',

467 oneLiner: 'Default settings for all projects',

468 when: 'Your defaults. Project and local settings.json override any keys you also set there',

469 description: [<>Same keys as project <C>settings.json</C>: permissions, hooks, model, environment variables, and the rest. Put settings here that you want in every project, like permissions you always allow, a preferred model, or a notification hook that runs regardless of which project you're in.</>, <>Settings follow a precedence order: project <C>settings.json</C> overrides any matching keys you set here. This is different from CLAUDE.md, where global and project files are both loaded into context rather than merged key by key.</>],

470 example: `{

471 "permissions": {

472 "allow": [

473 "Bash(git log *)",

474 "Bash(git diff *)"

475 ]

476 }

477}`,

478 docsLink: '/en/settings'

479 }, {

480 id: 'keybindings',

481 label: 'keybindings.json',

482 type: 'file',

483 icon: 'json',

484 color: 'var(--ce-text-3)',

485 badge: 'local',

486 oneLiner: 'Custom keyboard shortcuts',

487 when: 'Read at session start and hot-reloaded when you edit the file',

488 description: <>Rebind keyboard shortcuts in the interactive CLI. Run <C>/keybindings</C> to create or open this file with a schema reference. Ctrl+C, Ctrl+D, Ctrl+M, and Caps Lock are reserved and cannot be rebound.</>,

489 exampleIntro: <>This example binds <C>Ctrl+E</C> to open your external editor and unbinds <C>Ctrl+U</C> by setting it to <C>null</C>. The <C>context</C> field scopes bindings to a specific part of the CLI, here the main chat input.</>,

490 example: `{

491 "$schema": "https://www.schemastore.org/claude-code-keybindings.json",

492 "$docs": "https://code.claude.com/docs/en/keybindings",

493 "bindings": [

494 {

495 "context": "Chat",

496 "bindings": {

497 "ctrl+e": "chat:externalEditor",

498 "ctrl+u": null

499 }

500 }

501 ]

502}`,

503 docsLink: '/en/keybindings'

504 }, {

505 id: 'themes',

506 label: 'themes/',

507 type: 'folder',

508 icon: 'folder',

509 color: '#5AA7A7',

510 oneLiner: 'Custom color themes',

511 when: <>Read at session start and hot-reloaded when files change. Listed in <C>/theme</C></>,

512 description: <>Each <C>.json</C> file defines a custom color theme: a built-in <C>base</C> preset plus an <C>overrides</C> map of color tokens. Create one interactively with <C>/theme</C> or write the JSON by hand. Selecting a custom theme stores <C>custom:&lt;slug&gt;</C> as your theme preference.</>,

513 example: `{

514 "name": "Dracula",

515 "base": "dark",

516 "overrides": {

517 "claude": "#bd93f9",

518 "error": "#ff5555",

519 "success": "#50fa7b"

520 }

521}`,

522 docsLink: '/en/terminal-config#create-a-custom-theme',

523 children: []

524 }, {

525 id: 'global-projects',

526 label: 'projects/',

527 type: 'folder',

528 icon: 'folder',

529 color: '#E8A45C',

530 autogen: true,

531 oneLiner: "Auto memory: Claude's notes to itself, per project",

532 when: 'MEMORY.md loaded at session start; topic files read on demand',

533 description: 'Auto memory lets Claude accumulate knowledge across sessions without you writing anything. Claude saves notes as it works: build commands, debugging insights, architecture notes. Each project gets its own memory directory keyed by the repository path.',

534 tips: [<>On by default. Toggle with <C>/memory</C> or <C>autoMemoryEnabled</C> in settings</>, 'MEMORY.md is the index loaded each session. The first 200 lines, or 25KB, whichever comes first, are read', 'Topic files like debugging.md are read on demand, not at startup', 'These are plain markdown. Edit or delete them anytime'],

535 docsLink: '/en/memory#auto-memory',

536 children: [{

537 id: 'memory-dir',

538 label: '<project>/memory/',

539 type: 'folder',

540 icon: 'folder',

541 color: '#E8A45C',

542 autogen: true,

543 oneLiner: "Claude's accumulated knowledge for one project",

544 children: [{

545 id: 'memory-md',

546 label: 'MEMORY.md',

547 type: 'file',

548 icon: 'md',

549 color: '#E8A45C',

550 badge: 'local',

551 autogen: true,

552 oneLiner: 'Claude writes and maintains this file automatically',

553 when: 'First 200 lines (capped at 25KB) loaded at session start',

554 description: 'Claude creates and updates this file as it works; you do not write it yourself. It acts as an index that Claude reads at the start of every session, pointing to topic files for detail. You can edit or delete it, but Claude will keep updating it.',

555 example: `# Memory Index

556 

557## Project

558- [build-and-test.md](build-and-test.md): npm run build (~45s), Vitest, dev server on 3001

559- [architecture.md](architecture.md): API client singleton, refresh-token auth

560 

561## Reference

562- [debugging.md](debugging.md): auth token rotation and DB connection troubleshooting`,

563 docsLink: '/en/memory'

564 }, {

565 id: 'memory-topic',

566 label: 'debugging.md',

567 type: 'file',

568 icon: 'md',

569 color: '#E8A45C',

570 badge: 'local',

571 autogen: true,

572 oneLiner: 'Topic notes Claude writes when MEMORY.md gets long',

573 when: 'Claude reads this when a related task comes up',

574 description: 'An example of a topic file Claude creates when MEMORY.md grows too long. Claude picks the filename based on what it splits out: debugging.md, architecture.md, build-commands.md, or similar. You never create these yourself. Claude reads a topic file back only when the current task relates to it.',

575 example: `---

576name: Debugging patterns

577description: Auth token rotation and database connection troubleshooting for this project

578type: reference

579---

580 

581## Auth Token Issues

582- Refresh token rotation: old token invalidated immediately

583- If 401 after refresh: check clock skew between client and server

584 

585## Database Connection Drops

586- Connection pool: max 10 in dev, 50 in prod

587- Always check \`docker compose ps\` first`

588 }]

589 }]

590 }, {

591 id: 'global-rules',

592 label: 'rules/',

593 type: 'folder',

594 icon: 'folder',

595 color: '#9B7BC4',

596 oneLiner: 'User-level rules that apply to every project',

597 when: <>Rules without <C>paths:</C> load at session start. Rules with <C>paths:</C> load when a matching file enters context</>,

598 description: 'Same as project .claude/rules/ but applies everywhere. Use this for conventions you want across all your work, like personal code style or commit message format.',

599 docsLink: '/en/memory#organize-rules-with-claude/rules/',

600 children: []

601 }, {

602 id: 'global-skills',

603 label: 'skills/',

604 type: 'folder',

605 icon: 'folder',

606 color: '#D4A843',

607 oneLiner: 'Personal skills available in every project',

608 when: <>Invoked with <C>/skill-name</C> in any project</>,

609 description: 'Skills you built for yourself that work everywhere. Same structure as project skills: each is a folder with SKILL.md, scoped to your user account instead of a single project.',

610 docsLink: '/en/skills',

611 children: []

612 }, {

613 id: 'global-commands',

614 label: 'commands/',

615 type: 'folder',

616 icon: 'folder',

617 color: '#788C5D',

618 oneLiner: 'Personal single-file commands available in every project',

619 note: commandsNote,

620 when: <>User types <C>/command-name</C> in any project</>,

621 description: 'Same as project commands/ but scoped to your user account. Each markdown file becomes a command available everywhere.',

622 docsLink: '/en/skills',

623 children: []

624 }, {

625 id: 'global-output-styles',

626 label: 'output-styles/',

627 type: 'folder',

628 icon: 'folder',

629 color: '#5AA7A7',

630 oneLiner: 'Custom system-prompt sections that adjust how Claude works',

631 when: 'Applied at session start when selected via the outputStyle setting',

632 description: [<>Each markdown file defines an output style: a section appended to the system prompt that, by default, also drops the built-in software-engineering task instructions. Use this to adapt Claude Code for uses beyond coding, or to add teaching or review modes.</>, <>Select a built-in or custom style with <C>/config</C> or the <C>outputStyle</C> key in settings. Styles here are available in every project; project-level styles with the same name take precedence.</>],

633 tips: ['Built-in styles Explanatory and Learning are included with Claude Code; custom styles go here', <>Set <C>keep-coding-instructions: true</C> in frontmatter to keep the default task instructions alongside your additions</>, 'Changes take effect on the next session since the system prompt is fixed at startup for caching'],

634 docsLink: '/en/output-styles',

635 children: [{

636 id: 'output-style-example',

637 label: 'teaching.md',

638 type: 'file',

639 icon: 'md',

640 color: '#5AA7A7',

641 badge: 'local',

642 oneLiner: 'Example style that adds explanations and leaves small changes for you',

643 when: <>Active when <C>outputStyle</C> in settings is set to <C>teaching</C></>,

644 description: <>This style appends instructions to the system prompt: Claude adds a "Why this approach" note after each task and leaves TODO(human) markers for changes under 10 lines instead of writing them itself. Select it by setting <C>outputStyle</C> to the filename without .md, or to the <C>name</C> field if you set one in frontmatter.</>,

645 example: `---

646description: Explains reasoning and asks you to implement small pieces

647keep-coding-instructions: true

648---

649 

650After completing each task, add a brief "Why this approach" note

651explaining the key design decision.

652 

653When a change is under 10 lines, ask the user to implement it

654themselves by leaving a TODO(human) marker instead of writing it.`

655 }]

656 }, {

657 id: 'global-agents',

658 label: 'agents/',

659 type: 'folder',

660 icon: 'folder',

661 color: '#C46686',

662 oneLiner: 'Personal subagents available in every project',

663 when: 'Claude delegates or you @-mention in any project',

664 description: 'Subagents defined here are available across all your projects. Same format as project agents.',

665 docsLink: '/en/sub-agents',

666 children: []

667 }, {

668 id: 'global-agent-memory',

669 label: 'agent-memory/',

670 type: 'folder',

671 icon: 'folder',

672 color: '#C46686',

673 autogen: true,

674 oneLiner: <>Persistent memory for subagents with <C>memory: user</C></>,

675 when: 'Loaded into the subagent system prompt when the subagent starts',

676 description: <>Subagents with <C>memory: user</C> in their frontmatter store knowledge here that persists across all projects. For project-scoped subagent memory, see <C>.claude/agent-memory/</C> instead.</>,

677 docsLink: '/en/sub-agents#enable-persistent-memory',

678 children: []

679 }]

680 }]

681 }

682 }), []);

683 const BADGE_STYLES = useMemo(() => ({

684 committed: {

685 bg: 'rgba(85,138,66,0.08)',

686 color: 'var(--ce-badge-committed)',

687 border: 'rgba(85,138,66,0.15)',

688 label: 'committed'

689 },

690 gitignored: {

691 bg: 'rgba(217,119,87,0.06)',

692 color: 'var(--ce-badge-gitignored)',

693 border: 'rgba(217,119,87,0.15)',

694 label: 'gitignored'

695 },

696 local: {

697 bg: 'rgba(115,114,108,0.06)',

698 color: 'var(--ce-badge-local)',

699 border: 'rgba(115,114,108,0.12)',

700 label: 'local only'

701 },

702 autogen: {

703 bg: 'rgba(232,164,92,0.1)',

704 color: 'var(--ce-badge-autogen)',

705 border: 'rgba(232,164,92,0.2)',

706 label: 'Claude writes'

707 }

708 }), []);

709 const allNodes = useMemo(() => {

710 const flatten = (nodes, acc, path, parentId) => {

711 for (const node of nodes) {

712 const nextPath = [...path, node.label];

713 acc[node.id] = {

714 ...node,

715 path: nextPath,

716 parentId

717 };

718 if (node.children) flatten(node.children, acc, nextPath, node.id);

719 }

720 return acc;

721 };

722 const project = flatten(FILE_TREE.project.children, {}, [FILE_TREE.project.label]);

723 const global = flatten(FILE_TREE.global.children, {}, [FILE_TREE.global.label]);

724 for (const id in project) project[id].root = 'project';

725 for (const id in global) global[id].root = 'global';

726 return {

727 ...project,

728 ...global

729 };

730 }, [FILE_TREE]);

731 const allFolderIds = useMemo(() => Object.keys(allNodes).filter(id => allNodes[id].type === 'folder'), [allNodes]);

732 const DEFAULT_EXPANDED = ['dot-claude', 'rules', 'skills', 'skill-review', 'commands', 'agents', 'agent-memory', 'agent-memory-sub', 'global-dot-claude', 'global-output-styles', 'global-projects', 'memory-dir'];

733 const [mounted, setMounted] = useState(false);

734 const [activeRoot, setActiveRoot] = useState('project');

735 const [selectedId, setSelectedId] = useState('claude-md');

736 const [expandedFolders, setExpandedFolders] = useState(() => new Set(DEFAULT_EXPANDED));

737 const [forceMobile, setForceMobile] = useState(false);

738 const [copiedId, setCopiedId] = useState(null);

739 const [isFullscreen, setIsFullscreen] = useState(false);

740 const copyTimeoutRef = useRef(null);

741 const rootRef = useRef(null);

742 useEffect(() => {

743 setMounted(true);

744 const applyHash = scroll => {

745 const hash = window.location.hash.slice(1);

746 if (!hash.startsWith('ce-')) return;

747 const id = hash.slice(3);

748 const node = allNodes[id];

749 if (!node) return;

750 setActiveRoot(node.root);

751 setSelectedId(id);

752 setExpandedFolders(new Set(allFolderIds));

753 if (scroll && rootRef.current) rootRef.current.scrollIntoView({

754 behavior: 'smooth',

755 block: 'start'

756 });

757 };

758 applyHash(false);

759 const onHashChange = () => applyHash(true);

760 const onFsChange = () => setIsFullscreen(!!document.fullscreenElement);

761 window.addEventListener('hashchange', onHashChange);

762 document.addEventListener('fullscreenchange', onFsChange);

763 return () => {

764 if (copyTimeoutRef.current) clearTimeout(copyTimeoutRef.current);

765 window.removeEventListener('hashchange', onHashChange);

766 document.removeEventListener('fullscreenchange', onFsChange);

767 };

768 }, []);

769 useEffect(() => {

770 if (!mounted || !rootRef.current) return;

771 const hash = window.location.hash.slice(1);

772 if (hash.startsWith('ce-') && allNodes[hash.slice(3)]) {

773 rootRef.current.scrollIntoView({

774 behavior: 'smooth',

775 block: 'start'

776 });

777 }

778 }, [mounted]);

779 if (!mounted) return null;

780 const selected = allNodes[selectedId];

781 const tree = FILE_TREE[activeRoot];

782 const isCopied = copiedId === selected.id;

783 const toggleFolder = id => {

784 const next = new Set(expandedFolders);

785 next.has(id) ? next.delete(id) : next.add(id);

786 setExpandedFolders(next);

787 };

788 const switchRoot = root => {

789 if (root === activeRoot) return;

790 setActiveRoot(root);

791 const firstId = FILE_TREE[root].children[0].id;

792 setSelectedId(firstId);

793 try {

794 history.replaceState(null, '', '#ce-' + firstId);

795 } catch (e) {}

796 };

797 const toggleFullscreen = () => {

798 if (!rootRef.current) return;

799 if (document.fullscreenElement) document.exitFullscreen(); else rootRef.current.requestFullscreen().catch(() => {});

800 };

801 const selectNode = n => {

802 setSelectedId(n.id);

803 if (n.type === 'folder' && !expandedFolders.has(n.id)) toggleFolder(n.id);

804 try {

805 history.replaceState(null, '', '#ce-' + n.id);

806 } catch (e) {}

807 };

808 const iconBtn = {

809 width: 28,

810 flexShrink: 0,

811 borderRadius: '6px',

812 border: 'none',

813 cursor: 'pointer',

814 background: 'transparent',

815 color: 'var(--ce-text-4)',

816 display: 'flex',

817 alignItems: 'center',

818 justifyContent: 'center'

819 };

820 const visibleFolderIds = allFolderIds.filter(id => allNodes[id].root === activeRoot);

821 const allExpanded = visibleFolderIds.every(id => expandedFolders.has(id));

822 const toggleAllFolders = () => {

823 const next = new Set(expandedFolders);

824 visibleFolderIds.forEach(id => allExpanded ? next.delete(id) : next.add(id));

825 setExpandedFolders(next);

826 };

827 const onTreeKeyDown = e => {

828 if (!['ArrowDown', 'ArrowUp', 'ArrowRight', 'ArrowLeft'].includes(e.key)) return;

829 const visible = [];

830 const walk = nodes => {

831 for (const n of nodes) {

832 visible.push(n.id);

833 if (n.children && expandedFolders.has(n.id)) walk(n.children);

834 }

835 };

836 walk(tree.children);

837 const i = visible.indexOf(selectedId);

838 if (i === -1) return;

839 e.preventDefault();

840 if (e.key === 'ArrowDown' && i < visible.length - 1) selectNode(allNodes[visible[i + 1]]); else if (e.key === 'ArrowUp' && i > 0) selectNode(allNodes[visible[i - 1]]); else if (e.key === 'ArrowRight' && selected.type === 'folder') {

841 if (!expandedFolders.has(selectedId)) toggleFolder(selectedId); else if (selected.children && selected.children.length) selectNode(allNodes[selected.children[0].id]);

842 } else if (e.key === 'ArrowLeft') {

843 if (selected.type === 'folder' && expandedFolders.has(selectedId)) toggleFolder(selectedId); else if (selected.parentId) selectNode(allNodes[selected.parentId]);

844 }

845 };

846 const copyExample = (id, text) => {

847 const done = () => {

848 setCopiedId(id);

849 if (copyTimeoutRef.current) clearTimeout(copyTimeoutRef.current);

850 copyTimeoutRef.current = setTimeout(() => setCopiedId(null), 2000);

851 };

852 const fallback = () => {

853 const ta = document.createElement('textarea');

854 ta.value = text;

855 ta.style.position = 'fixed';

856 ta.style.opacity = '0';

857 document.body.appendChild(ta);

858 ta.select();

859 try {

860 if (document.execCommand('copy')) done();

861 } catch (e) {}

862 document.body.removeChild(ta);

863 };

864 if (navigator.clipboard) {

865 navigator.clipboard.writeText(text).then(done, fallback);

866 } else {

867 fallback();

868 }

869 };

870 const renderIcon = (icon, color, size) => {

871 const sz = size || 14;

872 if (icon === 'folder') {

873 return <svg width={sz} height={sz} viewBox="0 0 14 14" fill="none">

874 <path d="M1.5 3.5a1 1 0 0 1 1-1h2.6l1 1.2h5.4a1 1 0 0 1 1 1v5.8a1 1 0 0 1-1 1h-9a1 1 0 0 1-1-1V3.5z" fill={color} fillOpacity="0.15" stroke={color} strokeWidth="1" />

875 </svg>;

876 }

877 if (icon === 'json') {

878 return <svg width={sz} height={sz} viewBox="0 0 14 14" fill="none">

879 <rect x="2" y="1.5" width="10" height="11" rx="1.5" fill={color} fillOpacity="0.15" stroke={color} strokeWidth="1" />

880 <text x="7" y="9" fontSize="6" fontFamily="monospace" fill={color} textAnchor="middle" fontWeight="700">{'{}'}</text>

881 </svg>;

882 }

883 return <svg width={sz} height={sz} viewBox="0 0 14 14" fill="none">

884 <rect x="2" y="1.5" width="10" height="11" rx="1.5" fill={color} fillOpacity="0.15" stroke={color} strokeWidth="1" />

885 <line x1="4.5" y1="5" x2="9.5" y2="5" stroke={color} strokeWidth="1" />

886 <line x1="4.5" y1="7" x2="9.5" y2="7" stroke={color} strokeWidth="1" />

887 <line x1="4.5" y1="9" x2="8" y2="9" stroke={color} strokeWidth="1" />

888 </svg>;

889 };

890 const renderNode = (node, depth) => {

891 const isFolder = node.type === 'folder';

892 const isExpanded = expandedFolders.has(node.id);

893 const isSelected = selectedId === node.id;

894 return <div key={node.id}>

895 <button role="treeitem" tabIndex={-1} onClick={() => selectNode(node)} aria-selected={isSelected} aria-expanded={isFolder ? isExpanded : undefined} style={{

896 display: 'flex',

897 alignItems: 'center',

898 gap: '5px',

899 width: '100%',

900 padding: `4px 8px 4px ${8 + depth * 16}px`,

901 background: isSelected ? 'var(--ce-accent-bg)' : 'transparent',

902 borderTop: 'none',

903 borderRight: 'none',

904 borderBottom: 'none',

905 borderLeft: isSelected ? '2px solid var(--ce-accent)' : '2px solid transparent',

906 outline: 'none',

907 cursor: 'pointer',

908 textAlign: 'left',

909 fontFamily: 'var(--ce-mono)',

910 fontSize: '13.5px',

911 color: isSelected ? 'var(--ce-accent)' : 'var(--ce-text-2)',

912 fontWeight: isSelected ? 550 : 400,

913 transition: 'all 0.1s'

914 }}>

915 {isFolder ? <span onClick={e => {

916 e.stopPropagation();

917 toggleFolder(node.id);

918 }} style={{

919 fontSize: '14px',

920 color: 'var(--ce-text-4)',

921 width: '20px',

922 height: '20px',

923 display: 'inline-flex',

924 alignItems: 'center',

925 justifyContent: 'center',

926 cursor: 'pointer',

927 borderRadius: '4px',

928 marginLeft: '-6px',

929 flexShrink: 0

930 }} onMouseEnter={e => {

931 e.currentTarget.style.background = 'var(--ce-arrow-hover)';

932 e.currentTarget.style.color = 'var(--ce-text-2)';

933 }} onMouseLeave={e => {

934 e.currentTarget.style.background = 'transparent';

935 e.currentTarget.style.color = 'var(--ce-text-4)';

936 }}>{isExpanded ? '▾' : '▸'}</span> : <span style={{

937 width: '14px',

938 flexShrink: 0

939 }} />}

940 {renderIcon(node.icon, node.color)}

941 <span style={{

942 flex: 1,

943 overflow: 'hidden',

944 textOverflow: 'ellipsis',

945 whiteSpace: 'nowrap'

946 }}>{node.label}</span>

947 {node.badge && BADGE_STYLES[node.badge] && <span title={BADGE_STYLES[node.badge].label} style={{

948 width: 6,

949 height: 6,

950 borderRadius: '50%',

951 background: BADGE_STYLES[node.badge].color,

952 flexShrink: 0,

953 opacity: 0.7

954 }} />}

955 </button>

956 {isFolder && isExpanded && node.children && <div role="group">{node.children.map(child => renderNode(child, depth + 1))}</div>}

957 </div>;

958 };

959 return <>

960 <style>{`

961 .ce-root {

962 --ce-mono: var(--font-mono, ui-monospace, monospace);

963 --ce-accent: #D97757;

964 --ce-accent-bg: rgba(217,119,87,0.06);

965 --ce-accent-border: rgba(217,119,87,0.12);

966 --ce-bg: #fff;

967 --ce-surface: #FAFAF7;

968 --ce-surface-hover: #F0EEE6;

969 --ce-border: #E8E6DC;

970 --ce-border-subtle: #F0EEE6;

971 --ce-text: #141413;

972 --ce-text-2: #5E5D59;

973 --ce-text-3: #73726C;

974 --ce-text-4: #9C9A92;

975 --ce-text-5: #B8B6AE;

976 --ce-sep: #D1CFC5;

977 --ce-code-header: #F5F4ED;

978 --ce-code-bg: #1A1918;

979 --ce-arrow-hover: rgba(0,0,0,0.08);

980 --ce-badge-committed: #3d6b2e;

981 --ce-badge-gitignored: #b85c3a;

982 --ce-badge-local: #5e5d59;

983 --ce-badge-autogen: #b07520;

984 --ce-when-text: #4a7fb5;

985 }

986 .dark .ce-root {

987 --ce-bg: #1a1918;

988 --ce-surface: #232221;

989 --ce-surface-hover: #2e2d2b;

990 --ce-border: #3a3936;

991 --ce-border-subtle: #2e2d2b;

992 --ce-text: #e8e6dc;

993 --ce-text-2: #c4c2b8;

994 --ce-text-3: #9c9a92;

995 --ce-text-4: #73726c;

996 --ce-text-5: #5e5d59;

997 --ce-sep: #4a4946;

998 --ce-code-header: #2e2d2b;

999 --ce-code-bg: #0d0d0c;

1000 --ce-arrow-hover: rgba(255,255,255,0.08);

1001 --ce-badge-committed: #6fa85c;

1002 --ce-badge-gitignored: #e08a60;

1003 --ce-badge-local: #9c9a92;

1004 --ce-badge-autogen: #e8a45c;

1005 --ce-when-text: #8bb4e0;

1006 }

1007 .ce-mobile-fallback { display: none; border: 1px solid rgba(0,0,0,0.1); background: rgba(0,0,0,0.03); }

1008 .dark .ce-mobile-fallback { border-color: rgba(255,255,255,0.15); background: rgba(255,255,255,0.04); }

1009 @media (max-width: 700px) {

1010 .ce-root:not(.ce-force) { display: none !important; }

1011 .ce-mobile-fallback { display: block; }

1012 }

1013 `}</style>

1014 {!forceMobile && <div className="ce-mobile-fallback" style={{

1015 padding: '14px 16px',

1016 borderRadius: '8px',

1017 fontSize: '14px'

1018 }}>

1019 The interactive explorer works best on a larger screen. See the <a href="#file-reference" style={{

1020 color: '#D97757'

1021 }}>file reference table</a> below, or <button onClick={() => setForceMobile(true)} style={{

1022 border: 'none',

1023 background: 'none',

1024 padding: 0,

1025 color: '#D97757',

1026 textDecoration: 'underline',

1027 cursor: 'pointer',

1028 font: 'inherit'

1029 }}>show the explorer anyway</button>.

1030 </div>}

1031 <div ref={rootRef} className={forceMobile ? 'ce-root ce-force' : 'ce-root'} style={{

1032 borderRadius: isFullscreen ? 0 : '12px',

1033 border: '1px solid var(--ce-border)',

1034 background: 'var(--ce-bg)',

1035 display: 'flex',

1036 alignItems: 'stretch',

1037 overflow: 'hidden',

1038 fontFamily: 'var(--font-sans, -apple-system, sans-serif)',

1039 ...isFullscreen && ({

1040 height: '100vh'

1041 })

1042 }}>

1043 {}

1044 <div style={{

1045 width: 'min(240px, 35%)',

1046 minWidth: '180px',

1047 flexShrink: 0,

1048 borderRight: '1px solid var(--ce-border-subtle)',

1049 background: 'var(--ce-surface)',

1050 display: 'flex',

1051 flexDirection: 'column'

1052 }}>

1053 <div style={{

1054 padding: '8px 8px 4px',

1055 borderBottom: '1px solid var(--ce-border-subtle)',

1056 display: 'flex',

1057 gap: '4px'

1058 }}>

1059 {['project', 'global'].map(root => <button key={root} onClick={() => switchRoot(root)} style={{

1060 flex: 1,

1061 padding: '6px 0',

1062 borderRadius: '6px',

1063 border: 'none',

1064 cursor: 'pointer',

1065 fontFamily: 'var(--ce-mono)',

1066 fontSize: '11.5px',

1067 background: activeRoot === root ? 'var(--ce-accent-bg)' : 'transparent',

1068 color: activeRoot === root ? 'var(--ce-accent)' : 'var(--ce-text-4)',

1069 fontWeight: activeRoot === root ? 600 : 430

1070 }}>

1071 {root === 'project' ? 'Project' : 'Global (~/)'}

1072 </button>)}

1073 <button onClick={toggleAllFolders} title={allExpanded ? 'Collapse all' : 'Expand all'} style={{

1074 ...iconBtn,

1075 fontSize: 11

1076 }}>

1077 {allExpanded ? '⊟' : '⊞'}

1078 </button>

1079 <button onClick={toggleFullscreen} title={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'} style={{

1080 ...iconBtn,

1081 fontSize: 13

1082 }}>

1083 {isFullscreen ? '⤡' : '⛶'}

1084 </button>

1085 </div>

1086 <div role="tree" aria-label="Configuration files" tabIndex={0} onKeyDown={onTreeKeyDown} style={{

1087 padding: '6px 0',

1088 overflowY: 'auto',

1089 flex: 1,

1090 outline: 'none'

1091 }}>

1092 {tree.children.map(node => renderNode(node, 0))}

1093 </div>

1094 </div>

1095 

1096 {}

1097 <div style={{

1098 flex: 1,

1099 minWidth: 0,

1100 padding: '20px 24px',

1101 minHeight: '400px',

1102 overflowY: 'auto'

1103 }}>

1104 <span aria-live="polite" style={{

1105 position: 'absolute',

1106 width: 1,

1107 height: 1,

1108 overflow: 'hidden',

1109 clip: 'rect(0 0 0 0)'

1110 }}>{selected.label} selected</span>

1111 {}

1112 <div style={{

1113 fontFamily: 'var(--ce-mono)',

1114 fontSize: '11px',

1115 color: 'var(--ce-text-4)',

1116 marginBottom: '10px',

1117 cursor: 'default'

1118 }}>

1119 {selected.path.map((seg, i) => <span key={i}>

1120 <span style={{

1121 color: i === selected.path.length - 1 ? 'var(--ce-accent)' : 'var(--ce-text-4)'

1122 }}>{seg.replace(/\/$/, '')}</span>

1123 {i < selected.path.length - 1 && <span style={{

1124 color: 'var(--ce-sep)'

1125 }}> / </span>}

1126 </span>)}

1127 </div>

1128 

1129 {}

1130 <div style={{

1131 display: 'flex',

1132 alignItems: 'flex-start',

1133 gap: '10px',

1134 marginBottom: '10px'

1135 }}>

1136 <span style={{

1137 flexShrink: 0,

1138 display: 'flex'

1139 }}>{renderIcon(selected.icon, selected.color, 24)}</span>

1140 <div style={{

1141 flex: 1,

1142 minWidth: 0

1143 }}>

1144 <div style={{

1145 fontSize: '22px',

1146 fontWeight: 600,

1147 color: 'var(--ce-text)',

1148 letterSpacing: '-0.3px',

1149 lineHeight: '26px'

1150 }}>{selected.label}</div>

1151 {selected.oneLiner && <div style={{

1152 fontSize: '15px',

1153 color: 'var(--ce-text-3)',

1154 marginTop: '3px'

1155 }}>{selected.oneLiner}</div>}

1156 </div>

1157 <div style={{

1158 display: 'flex',

1159 gap: '4px',

1160 flexShrink: 0

1161 }}>

1162 {[selected.autogen && 'autogen', selected.badge].filter(Boolean).map(k => {

1163 const s = BADGE_STYLES[k];

1164 if (!s) return null;

1165 return <span key={k} style={{

1166 fontFamily: 'var(--ce-mono)',

1167 fontSize: '10px',

1168 fontWeight: 600,

1169 textTransform: 'uppercase',

1170 letterSpacing: '0.3px',

1171 padding: '2px 6px',

1172 borderRadius: '4px',

1173 background: s.bg,

1174 color: s.color,

1175 border: `0.5px solid ${s.border}`

1176 }}>{s.label}</span>;

1177 })}

1178 </div>

1179 </div>

1180 

1181 {}

1182 {selected.note && <div style={{

1183 padding: '10px 12px',

1184 borderRadius: '8px',

1185 marginBottom: '14px',

1186 background: 'rgba(217,119,87,0.06)',

1187 border: '1px solid rgba(217,119,87,0.2)',

1188 borderLeft: '3px solid var(--ce-accent)',

1189 fontSize: '15px',

1190 color: 'var(--ce-text-2)',

1191 lineHeight: 1.6

1192 }}>

1193 {selected.note}

1194 </div>}

1195 

1196 {}

1197 {selected.when && <div style={{

1198 padding: '8px 12px',

1199 borderRadius: '6px',

1200 background: 'rgba(106,155,204,0.06)',

1201 border: '0.5px solid rgba(106,155,204,0.12)',

1202 fontSize: '15px',

1203 color: 'var(--ce-when-text)',

1204 marginBottom: '16px'

1205 }}>

1206 <div style={{

1207 fontSize: '10px',

1208 fontWeight: 700,

1209 textTransform: 'uppercase',

1210 letterSpacing: '0.4px',

1211 opacity: 0.65,

1212 marginBottom: '3px'

1213 }}>When it loads</div>

1214 <div style={{

1215 fontWeight: 500

1216 }}>{selected.when}</div>

1217 </div>}

1218 

1219 {}

1220 {selected.description && <div style={{

1221 fontSize: '16px',

1222 color: 'var(--ce-text-2)',

1223 lineHeight: 1.65,

1224 marginBottom: '16px'

1225 }}>

1226 {Array.isArray(selected.description) ? selected.description.map((para, i) => <div key={i} style={{

1227 marginBottom: i < selected.description.length - 1 ? '12px' : 0

1228 }}>{para}</div>) : selected.description}

1229 </div>}

1230 

1231 {}

1232 {selected.contains && selected.contains.length > 0 && <div style={{

1233 marginBottom: '16px'

1234 }}>

1235 <div style={{

1236 fontSize: '11px',

1237 fontWeight: 700,

1238 color: 'var(--ce-text-4)',

1239 textTransform: 'uppercase',

1240 letterSpacing: '0.4px',

1241 marginBottom: '8px'

1242 }}>Common keys</div>

1243 {selected.contains.map((item, i) => <div key={i} style={{

1244 display: 'flex',

1245 gap: '7px',

1246 fontSize: '15px',

1247 color: 'var(--ce-text-2)',

1248 lineHeight: 1.5,

1249 marginBottom: '5px'

1250 }}>

1251 <span style={{

1252 fontSize: '7px',

1253 color: 'var(--ce-text-4)',

1254 marginTop: '6px'

1255 }}>●</span>

1256 <span>{item}</span>

1257 </div>)}

1258 </div>}

1259 

1260 {}

1261 {selected.tips && selected.tips.length > 0 && <div style={{

1262 padding: '12px 14px',

1263 borderRadius: '8px',

1264 background: 'var(--ce-surface)',

1265 border: '1px solid var(--ce-border-subtle)',

1266 marginBottom: '16px'

1267 }}>

1268 <div style={{

1269 fontSize: '11px',

1270 fontWeight: 700,

1271 color: 'var(--ce-accent)',

1272 textTransform: 'uppercase',

1273 letterSpacing: '0.4px',

1274 marginBottom: '6px'

1275 }}>Tips</div>

1276 {selected.tips.map((tip, i) => <div key={i} style={{

1277 display: 'flex',

1278 gap: '7px',

1279 fontSize: '14.5px',

1280 color: 'var(--ce-text-2)',

1281 marginBottom: i < selected.tips.length - 1 ? '5px' : 0

1282 }}>

1283 <span style={{

1284 fontSize: '7px',

1285 color: 'var(--ce-accent)',

1286 marginTop: '6px'

1287 }}>●</span>

1288 <span>{tip}</span>

1289 </div>)}

1290 </div>}

1291 

1292 {}

1293 {selected.example && <div style={{

1294 marginBottom: '16px'

1295 }}>

1296 {selected.exampleIntro && <div style={{

1297 fontSize: '15px',

1298 color: 'var(--ce-text-2)',

1299 lineHeight: 1.6,

1300 marginBottom: '10px'

1301 }}>

1302 {selected.exampleIntro}

1303 </div>}

1304 <div style={{

1305 display: 'flex',

1306 justifyContent: 'space-between',

1307 alignItems: 'center',

1308 padding: '6px 10px',

1309 background: 'var(--ce-code-header)',

1310 border: '1px solid var(--ce-border)',

1311 borderRadius: '8px 8px 0 0'

1312 }}>

1313 <span style={{

1314 fontFamily: 'var(--ce-mono)',

1315 fontSize: '11px',

1316 fontWeight: 600,

1317 color: 'var(--ce-text-3)'

1318 }}>{selected.label}</span>

1319 <button onClick={() => copyExample(selected.id, selected.example)} style={{

1320 padding: '3px 8px',

1321 borderRadius: '4px',

1322 fontSize: '11px',

1323 fontWeight: 600,

1324 cursor: 'pointer',

1325 transition: 'all 0.15s',

1326 background: isCopied ? 'rgba(85,138,66,0.08)' : 'var(--ce-code-header)',

1327 border: isCopied ? '0.5px solid rgba(85,138,66,0.2)' : '0.5px solid var(--ce-border)',

1328 color: isCopied ? '#558A42' : 'var(--ce-text-3)'

1329 }}>

1330 {isCopied ? '✓ Copied' : 'Copy'}

1331 </button>

1332 </div>

1333 <pre style={{

1334 margin: 0,

1335 padding: '12px 14px',

1336 background: 'var(--ce-code-bg)',

1337 color: '#E8E6DC',

1338 fontFamily: 'var(--ce-mono)',

1339 fontSize: '13px',

1340 lineHeight: 1.65,

1341 borderRadius: '0 0 8px 8px',

1342 overflowX: 'auto',

1343 whiteSpace: 'pre'

1344 }}>{selected.example}</pre>

1345 </div>}

1346 

1347 {}

1348 {selected.docsLink && <a href={selected.docsLink} style={{

1349 display: 'inline-flex',

1350 padding: '5px 12px',

1351 borderRadius: '6px',

1352 background: 'var(--ce-accent-bg)',

1353 border: '1px solid var(--ce-accent-border)',

1354 color: 'var(--ce-accent)',

1355 fontSize: '12px',

1356 fontWeight: 600,

1357 textDecoration: 'none'

1358 }}>Full docs →</a>}

1359 

1360 {}

1361 {selected.children && selected.children.length > 0 && <div style={{

1362 marginTop: '20px'

1363 }}>

1364 <div style={{

1365 fontSize: '11px',

1366 fontWeight: 700,

1367 color: 'var(--ce-text-4)',

1368 textTransform: 'uppercase',

1369 letterSpacing: '0.4px',

1370 marginBottom: '8px'

1371 }}>Contents</div>

1372 <div style={{

1373 display: 'flex',

1374 flexDirection: 'column',

1375 gap: '4px'

1376 }}>

1377 {selected.children.map(child => <button key={child.id} onClick={() => selectNode(child)} style={{

1378 display: 'flex',

1379 alignItems: 'center',

1380 gap: '8px',

1381 padding: '6px 8px',

1382 width: '100%',

1383 background: 'var(--ce-surface)',

1384 borderRadius: '6px',

1385 border: 'none',

1386 cursor: 'pointer',

1387 textAlign: 'left',

1388 transition: 'background 0.1s'

1389 }} onMouseEnter={e => e.currentTarget.style.background = 'var(--ce-surface-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'var(--ce-surface)'}>

1390 {renderIcon(child.icon, child.color, 13)}

1391 <span style={{

1392 fontFamily: 'var(--ce-mono)',

1393 fontSize: '12px',

1394 color: 'var(--ce-text-2)'

1395 }}>{child.label}</span>

1396 {child.oneLiner && <span style={{

1397 fontSize: '11px',

1398 color: 'var(--ce-text-4)',

1399 overflow: 'hidden',

1400 textOverflow: 'ellipsis',

1401 whiteSpace: 'nowrap'

1402 }}>{child.oneLiner}</span>}

1403 </button>)}

1404 </div>

1405 </div>}

1406 </div>

1407 </div>

1408 </>;

1409};

1410 

1411Claude Code 從您的專案目錄和主目錄中的 `~/.claude` 讀取指令、設定、skills、subagents 和記憶。將專案檔案提交到 git 以與您的團隊共享;`~/.claude` 中的檔案是個人設定,適用於您的所有專案。

1412 

1413在 Windows 上,`~/.claude` 解析為 `%USERPROFILE%\.claude`。如果您設定了 [`CLAUDE_CONFIG_DIR`](/zh-TW/env-vars),此頁面上的每個 `~/.claude` 路徑都會改為位於該目錄下。

1414 

1415大多數使用者只編輯 `CLAUDE.md` 和 `settings.json`。目錄的其餘部分是可選的:根據需要新增 skills、rules 或 subagents。

1416 

1417## 探索目錄

1418 

1419點擊樹中的檔案以查看每個檔案的功能、何時載入以及範例。

1420 

1421<ClaudeExplorer />

1422 

1423## 未顯示的內容

1424 

1425探索器涵蓋您編寫和編輯的檔案。一些相關檔案位於其他位置:

1426 

1427| 檔案 | 位置 | 用途 |

1428| ----------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

1429| `managed-settings.json` | 系統級別,因作業系統而異 | 企業強制執行的設定,您無法覆蓋。請參閱[伺服器管理的設定](/zh-TW/server-managed-settings)。 |

1430| `CLAUDE.local.md` | 專案根目錄 | 您對此專案的私人偏好設定,與 CLAUDE.md 一起載入。手動建立並將其新增到 `.gitignore`。 |

1431| 已安裝的 plugins | `~/.claude/plugins` | 複製的市場、已安裝的 plugin 版本和每個 plugin 的資料,由 `claude plugin` 命令管理。孤立版本在 plugin 更新或解除安裝後 7 天內被刪除。請參閱 [plugin 快取](/zh-TW/plugins-reference#plugin-caching-and-file-resolution)。 |

1432 

1433`~/.claude` 還保存 Claude Code 在您工作時寫入的資料:文字記錄、提示歷史記錄、檔案快照、快取和日誌。請參閱下方的[應用程式資料](#application-data)。

1434 

1435## 選擇正確的檔案

1436 

1437不同類型的自訂設定位於不同的檔案中。使用此表格找到變更應該位於何處。

1438 

1439| 您想要 | 編輯 | 範圍 | 參考 |

1440| :--------------------- | :-------------------------------------- | :---- | :------------------------------------------------------ |

1441| 為 Claude 提供專案上下文和慣例 | `CLAUDE.md` | 專案或全域 | [Memory](/zh-TW/memory) |

1442| 允許或阻止特定工具呼叫 | `settings.json` `permissions` 或 `hooks` | 專案或全域 | [Permissions](/zh-TW/permissions)、[Hooks](/zh-TW/hooks) |

1443| 在工具呼叫之前或之後執行指令碼 | `settings.json` `hooks` | 專案或全域 | [Hooks](/zh-TW/hooks) |

1444| 為工作階段設定環境變數 | `settings.json` `env` | 專案或全域 | [Settings](/zh-TW/settings#available-settings) |

1445| 將個人覆蓋保留在 git 之外 | `settings.local.json` | 僅專案 | [Settings scopes](/zh-TW/settings#settings-files) |

1446| 新增您使用 `/name` 叫用的提示或功能 | `skills/<name>/SKILL.md` | 專案或全域 | [Skills](/zh-TW/skills) |

1447| 定義具有自己工具的專門 subagent | `agents/*.md` | 專案或全域 | [Subagents](/zh-TW/sub-agents) |

1448| 透過 MCP 連接外部工具 | `.mcp.json` | 僅專案 | [MCP](/zh-TW/mcp) |

1449| 變更 Claude 格式化回應的方式 | `output-styles/*.md` | 專案或全域 | [Output styles](/zh-TW/output-styles) |

1450 

1451## 檔案參考

1452 

1453此表列出探索器涵蓋的每個檔案。專案範圍的檔案位於您的儲存庫中的 `.claude/` 下(或 `CLAUDE.md`、`.mcp.json` 和 `.worktreeinclude` 的根目錄)。全域範圍的檔案位於 `~/.claude/` 中,適用於所有專案。

1454 

1455<Note>

1456 有幾件事可以覆蓋您在這些檔案中放入的內容:

1457 

1458 * 您的組織部署的[受管設定](/zh-TW/server-managed-settings)優先於所有內容

1459 * CLI 旗標(如 `--permission-mode` 或 `--settings`)會覆蓋該工作階段的 `settings.json`

1460 * 某些環境變數優先於其等效設定,但這會有所不同:檢查[環境變數參考](/zh-TW/env-vars)以了解每個變數

1461 

1462 請參閱[設定優先順序](/zh-TW/settings#settings-precedence)以了解完整順序。

1463</Note>

1464 

1465點擊檔案名稱以在上方的探索器中開啟該節點。

1466 

1467| 檔案 | 範圍 | 提交 | 功能 | 參考 |

1468| --------------------------------------------------- | ----- | -- | ----------------------------- | ----------------------------------------------------------------------- |

1469| [`CLAUDE.md`](#ce-claude-md) | 專案和全域 | ✓ | 每個工作階段載入的指令 | [Memory](/zh-TW/memory) |

1470| [`rules/*.md`](#ce-rules) | 專案和全域 | ✓ | 主題範圍的指令,可選擇路徑限制 | [Rules](/zh-TW/memory#organize-rules-with-claude/rules/) |

1471| [`settings.json`](#ce-settings-json) | 專案和全域 | ✓ | 權限、hooks、環境變數、模型預設值 | [Settings](/zh-TW/settings) |

1472| [`settings.local.json`](#ce-settings-local-json) | 僅專案 | | 您的個人覆蓋,自動 gitignored | [Settings scopes](/zh-TW/settings#settings-files) |

1473| [`.mcp.json`](#ce-mcp-json) | 僅專案 | ✓ | 團隊共享的 MCP 伺服器 | [MCP scopes](/zh-TW/mcp#mcp-installation-scopes) |

1474| [`.worktreeinclude`](#ce-worktreeinclude) | 僅專案 | ✓ | Gitignored 檔案以複製到新的 worktrees | [Worktrees](/zh-TW/common-workflows#copy-gitignored-files-to-worktrees) |

1475| [`skills/<name>/SKILL.md`](#ce-skills) | 專案和全域 | ✓ | 可重複使用的提示,使用 `/name` 叫用或自動叫用 | [Skills](/zh-TW/skills) |

1476| [`commands/*.md`](#ce-commands) | 專案和全域 | ✓ | 單檔案提示;與 skills 相同的機制 | [Skills](/zh-TW/skills) |

1477| [`output-styles/*.md`](#ce-output-styles) | 專案和全域 | ✓ | 自訂系統提示部分 | [Output styles](/zh-TW/output-styles) |

1478| [`agents/*.md`](#ce-agents) | 專案和全域 | ✓ | Subagent 定義及其自己的提示和工具 | [Subagents](/zh-TW/sub-agents) |

1479| [`agent-memory/<name>/`](#ce-agent-memory) | 專案和全域 | ✓ | Subagents 的持久記憶 | [Persistent memory](/zh-TW/sub-agents#enable-persistent-memory) |

1480| [`~/.claude.json`](#ce-claude-json) | 僅全域 | | 應用程式狀態、OAuth、UI 切換、個人 MCP 伺服器 | [Global config](/zh-TW/settings#global-config-settings) |

1481| [`projects/<project>/memory/`](#ce-global-projects) | 僅全域 | | 自動記憶:Claude 在工作階段間對自己的筆記 | [Auto memory](/zh-TW/memory#auto-memory) |

1482| [`keybindings.json`](#ce-keybindings) | 僅全域 | | 自訂快捷鍵 | [Keybindings](/zh-TW/keybindings) |

1483| [`themes/*.json`](#ce-themes) | 僅全域 | | 自訂色彩主題 | [Custom themes](/zh-TW/terminal-config#create-a-custom-theme) |

1484 

1485## 檢查已載入的內容

1486 

1487探索器顯示可以存在的檔案。若要查看在您目前工作階段中實際載入的內容,請使用這些命令:

1488 

1489| 命令 | 顯示 |

1490| -------------- | ------------------------------------- |

1491| `/context` | 按類別的權杖使用情況:系統提示、記憶檔案、skills、MCP 工具和訊息 |

1492| `/memory` | 載入了哪些 CLAUDE.md 和 rules 檔案,加上自動記憶項目 |

1493| `/agents` | 已設定的 subagents 及其設定 |

1494| `/hooks` | 作用中的 hook 設定 |

1495| `/mcp` | 已連接的 MCP 伺服器及其狀態 |

1496| `/skills` | 來自專案、使用者和 plugin 來源的可用 skills |

1497| `/permissions` | 目前的允許和拒絕規則 |

1498| `/doctor` | 安裝和設定診斷 |

1499 

1500首先執行 `/context` 以取得概觀,然後執行特定命令以調查您想要的區域。

1501 

1502## 應用程式資料

1503 

1504除了您編寫的設定外,`~/.claude` 還保存 Claude Code 在工作階段期間寫入的資料。這些檔案是純文字。任何通過工具的內容都會在磁碟上的文字記錄中結束:檔案內容、命令輸出、貼上的文字。

1505 

1506### 自動清理

1507 

1508下列路徑中的檔案在啟動時被刪除,一旦它們的年齡超過 [`cleanupPeriodDays`](/zh-TW/settings#available-settings)。預設值為 30 天。

1509 

1510| `~/.claude/` 下的路徑 | 內容 |

1511| -------------------------------------------- | --------------------------------------------------------------------------------------- |

1512| `projects/<project>/<session>.jsonl` | 完整對話文字記錄:每條訊息、工具呼叫和工具結果 |

1513| `projects/<project>/<session>/tool-results/` | 溢出到單獨檔案的大型工具輸出 |

1514| `file-history/<session>/` | Claude 變更的檔案的編輯前快照,用於[檢查點還原](/zh-TW/checkpointing) |

1515| `plans/` | 在 [Plan Mode](/zh-TW/permission-modes#analyze-before-you-edit-with-plan-mode) 期間寫入的計畫檔案 |

1516| `debug/` | 每個工作階段的偵錯日誌,僅在您使用 `--debug` 啟動或執行 `/debug` 時寫入 |

1517| `paste-cache/`、`image-cache/` | 大型貼上和附加影像的內容 |

1518| `session-env/` | 每個工作階段的環境中繼資料 |

1519| `tasks/` | 由 task tools 寫入的每個工作階段任務清單 |

1520| `shell-snapshots/` | Bash tool 使用的擷取 shell 環境。在正常退出時移除。掃描會清除任何在當機後遺留的檔案。 |

1521| `backups/` | 在設定遷移前取得的 `~/.claude.json` 的時間戳記副本 |

1522 

1523### 保留直到您刪除它們

1524 

1525以下路徑不受自動清理覆蓋,並無限期保留。

1526 

1527| `~/.claude/` 下的路徑 | 內容 |

1528| ------------------ | ------------------------------ |

1529| `history.jsonl` | 您輸入的每個提示,帶有時間戳記和專案路徑。用於向上箭頭回憶。 |

1530| `stats-cache.json` | 由 `/usage` 顯示的彙總權杖和成本計數 |

1531| `todos/` | 舊版每個工作階段的任務清單。不再由目前版本寫入;可安全刪除。 |

1532 

1533其他小型快取和鎖定檔案會根據您使用的功能而出現,可安全刪除。

1534 

1535### 純文字儲存

1536 

1537文字記錄和歷史記錄在靜止時未加密。作業系統檔案權限是唯一的保護。如果工具讀取 `.env` 檔案或命令列印認證,該值會寫入 `projects/<project>/<session>.jsonl`。若要減少暴露:

1538 

1539* 降低 `cleanupPeriodDays` 以縮短文字記錄的保留時間

1540* 設定 [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](/zh-TW/env-vars) 環境變數以跳過在任何模式中寫入文字記錄和提示歷史記錄。在非互動模式中,您可以改為在 `-p` 旁邊傳遞 `--no-session-persistence`,或在 Agent SDK 中設定 `persistSession: false`。

1541* 使用[權限規則](/zh-TW/permissions)拒絕讀取認證檔案

1542 

1543### 清除本機資料

1544 

1545執行 `claude project purge` 以刪除 Claude Code 為一個專案保存的狀態:

1546 

1547* `projects/` 下的文字記錄和自動記憶

1548* 每個工作階段的 `tasks/`、`debug/` 和 `file-history/` 項目

1549* `history.jsonl` 中的匹配提示行

1550* 專案在 `~/.claude.json` 中的項目

1551 

1552該命令會列印完整的刪除計畫,並在移除任何內容之前要求確認。

1553 

1554預覽計畫而不刪除任何內容:

1555 

1556```bash theme={null}

1557claude project purge ~/work/my-repo --dry-run

1558```

1559 

1560透過單一確認提示刪除:

1561 

1562```bash theme={null}

1563claude project purge ~/work/my-repo

1564```

1565 

1566省略路徑以從互動式清單中選擇專案。

1567 

1568跳過確認提示以在指令碼中使用:

1569 

1570```bash theme={null}

1571claude project purge ~/work/my-repo --yes

1572```

1573 

1574傳遞 `--all` 而不是路徑以一次清除所有專案的狀態,這會直接刪除 `history.jsonl` 而不是篩選它。傳遞 `-i` 以逐項逐步執行刪除計畫。

1575 

1576該命令會單獨保留 `shell-snapshots/` 和 `backups/`,因為這些不是專案範圍的,並在計畫輸出中警告它們。如果沒有狀態與給定路徑相符,它會以狀態 1 退出。

1577 

1578您也可以手動刪除上述任何應用程式資料路徑。新工作階段不受影響。下表顯示您對過去工作階段失去的內容。

1579 

1580| 刪除 | 您失去 |

1581| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |

1582| `~/.claude/projects/` | 過去工作階段的繼續、繼續和倒帶 |

1583| `~/.claude/history.jsonl` | 向上箭頭提示回憶 |

1584| `~/.claude/file-history/` | 過去工作階段的檢查點還原 |

1585| `~/.claude/stats-cache.json` | 由 `/usage` 顯示的歷史總計 |

1586| `~/.claude/debug/`、`~/.claude/plans/`、`~/.claude/paste-cache/`、`~/.claude/image-cache/`、`~/.claude/session-env/`、`~/.claude/tasks/`、`~/.claude/shell-snapshots/`、`~/.claude/backups/` | 沒有面向使用者的內容 |

1587| `~/.claude/todos/` | 無。舊版目錄不由目前版本寫入。 |

1588 

1589不要刪除 `~/.claude.json`、`~/.claude/settings.json` 或 `~/.claude/plugins/`:這些保存您的驗證、偏好設定和已安裝的 plugins。

1590 

1591## 相關資源

1592 

1593* [管理 Claude 的記憶](/zh-TW/memory):寫入和組織 CLAUDE.md、rules 和自動記憶

1594* [設定設定](/zh-TW/settings):設定權限、hooks、環境變數和模型預設值

1595* [建立 skills](/zh-TW/skills):建立可重複使用的提示和工作流程

1596* [設定 subagents](/zh-TW/sub-agents):定義具有自己上下文的專門代理

cli-reference.md +129 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# CLI 參考

6 

7> Claude Code 命令列介面的完整參考,包括命令和旗標。

8 

9## CLI 命令

10 

11您可以使用這些命令來啟動工作階段、管道內容、繼續對話和管理更新:

12 

13| 命令 | 描述 | 範例 |

14| :------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------- |

15| `claude` | 啟動互動式工作階段 | `claude` |

16| `claude "query"` | 使用初始提示啟動互動式工作階段 | `claude "explain this project"` |

17| `claude -p "query"` | 透過 SDK 查詢,然後退出 | `claude -p "explain this function"` |

18| `cat file \| claude -p "query"` | 處理管道內容 | `cat logs.txt \| claude -p "explain"` |

19| `claude -c` | 在目前目錄中繼續最近的對話 | `claude -c` |

20| `claude -c -p "query"` | 透過 SDK 繼續 | `claude -c -p "Check for type errors"` |

21| `claude -r "<session>" "query"` | 按 ID 或名稱繼續工作階段 | `claude -r "auth-refactor" "Finish this PR"` |

22| `claude update` | 更新至最新版本 | `claude update` |

23| `claude install [version]` | 安裝或重新安裝原生二進位檔。接受版本如 `2.1.118`、`stable` 或 `latest`。請參閱 [安裝特定版本](/zh-TW/setup#install-a-specific-version) | `claude install stable` |

24| `claude auth login` | 登入您的 Anthropic 帳戶。使用 `--email` 預先填入您的電子郵件地址,使用 `--sso` 強制進行 SSO 驗證,使用 `--console` 以 Anthropic Console 登入以進行 API 使用計費,而不是 Claude 訂閱 | `claude auth login --console` |

25| `claude auth logout` | 從您的 Anthropic 帳戶登出 | `claude auth logout` |

26| `claude auth status` | 以 JSON 格式顯示驗證狀態。使用 `--text` 以人類可讀的格式輸出。如果已登入則以代碼 0 退出,如果未登入則以代碼 1 退出 | `claude auth status` |

27| `claude agents` | 列出所有已設定的 [subagents](/zh-TW/sub-agents),按來源分組 | `claude agents` |

28| `claude auto-mode defaults` | 以 JSON 格式列印內建的 [auto mode](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode) 分類器規則。使用 `claude auto-mode config` 查看您的有效設定及套用的設定 | `claude auto-mode defaults > rules.json` |

29| `claude mcp` | 設定 Model Context Protocol (MCP) 伺服器 | 請參閱 [Claude Code MCP 文件](/zh-TW/mcp)。 |

30| `claude plugin` | 管理 Claude Code [plugins](/zh-TW/plugins)。別名:`claude plugins`。請參閱 [plugin 參考](/zh-TW/plugins-reference#cli-commands-reference) 以了解子命令 | `claude plugin install code-review@claude-plugins-official` |

31| `claude project purge [path]` | 刪除專案的所有本機 Claude Code 狀態:文字記錄、工作清單、偵錯日誌、檔案編輯歷史記錄、提示歷史記錄行和專案在 `~/.claude.json` 中的項目。省略 `[path]` 以從互動式清單中選擇。旗標:`--dry-run` 以預覽,`-y`/`--yes` 以跳過確認,`-i`/`--interactive` 以確認每個項目,`--all` 用於每個專案。請參閱 [清除本機資料](/zh-TW/claude-directory#clear-local-data) | `claude project purge ~/work/repo --dry-run` |

32| `claude remote-control` | 啟動 [Remote Control](/zh-TW/remote-control) 伺服器以從 Claude.ai 或 Claude 應用程式控制 Claude Code。在伺服器模式下執行(無本機互動式工作階段)。請參閱 [伺服器模式旗標](/zh-TW/remote-control#start-a-remote-control-session) | `claude remote-control --name "My Project"` |

33| `claude setup-token` | 為 CI 和指令碼產生長期 OAuth 權杖。將權杖列印到終端而不儲存它。需要 Claude 訂閱。請參閱 [產生長期權杖](/zh-TW/authentication#generate-a-long-lived-token) | `claude setup-token` |

34| `claude ultrareview [target]` | 非互動式執行 [ultrareview](/zh-TW/ultrareview#run-ultrareview-non-interactively)。將發現列印到標準輸出,成功時以代碼 0 退出,失敗時以代碼 1 退出。使用 `--json` 取得原始承載,使用 `--timeout <minutes>` 覆蓋 30 分鐘的預設值 | `claude ultrareview 1234 --json` |

35 

36如果您輸入錯誤的子命令,Claude Code 會建議最接近的匹配項並退出而不啟動工作階段。例如,`claude udpate` 會列印 `Did you mean claude update?`。

37 

38## CLI 旗標

39 

40使用這些命令列旗標自訂 Claude Code 的行為。`claude --help` 不會列出每個旗標,因此旗標在 `--help` 中的缺失並不表示它無法使用。

41 

42| 旗標 | 描述 | 範例 |

43| :---------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------- |

44| `--add-dir` | 新增額外的工作目錄供 Claude 讀取和編輯檔案。授予檔案存取權;大多數 `.claude/` 設定 [未從這些目錄探索](/zh-TW/permissions#additional-directories-grant-file-access-not-configuration)。驗證每個路徑是否存在為目錄 | `claude --add-dir ../apps ../lib` |

45| `--agent` | 為目前工作階段指定代理程式(覆蓋 `agent` 設定) | `claude --agent my-custom-agent` |

46| `--agents` | 透過 JSON 動態定義自訂 subagents。使用與 subagent [frontmatter](/zh-TW/sub-agents#supported-frontmatter-fields) 相同的欄位名稱,加上代理程式指示的 `prompt` 欄位 | `claude --agents '{"reviewer":{"description":"Reviews code","prompt":"You are a code reviewer"}}'` |

47| `--allow-dangerously-skip-permissions` | 新增 `bypassPermissions` 到 `Shift+Tab` 模式循環而不立即啟動它。允許您以不同的模式(如 `plan`)開始,稍後切換到 `bypassPermissions`。請參閱 [permission modes](/zh-TW/permission-modes#skip-all-checks-with-bypasspermissions-mode) | `claude --permission-mode plan --allow-dangerously-skip-permissions` |

48| `--allowedTools` | 無需提示權限即可執行的工具。請參閱 [permission rule syntax](/zh-TW/settings#permission-rule-syntax) 以了解模式匹配。若要限制可用的工具,請改用 `--tools` | `"Bash(git log *)" "Bash(git diff *)" "Read"` |

49| `--append-system-prompt` | 將自訂文字附加到預設系統提示的末尾 | `claude --append-system-prompt "Always use TypeScript"` |

50| `--append-system-prompt-file` | 從檔案載入額外的系統提示文字並附加到預設提示 | `claude --append-system-prompt-file ./extra-rules.txt` |

51| `--bare` | 最小模式:跳過 hooks、skills、plugins、MCP 伺服器、自動記憶體和 CLAUDE.md 的自動探索,以便指令碼呼叫啟動更快。Claude 可以存取 Bash、檔案讀取和檔案編輯工具。設定 [`CLAUDE_CODE_SIMPLE`](/zh-TW/env-vars)。請參閱 [bare mode](/zh-TW/headless#start-faster-with-bare-mode) | `claude --bare -p "query"` |

52| `--betas` | 要包含在 API 請求中的 Beta 標頭(僅限 API 金鑰使用者) | `claude --betas interleaved-thinking` |

53| `--channels` | (研究預覽)MCP 伺服器,其 [channel](/zh-TW/channels) 通知 Claude 應在此工作階段中監聽。以空格分隔的 `plugin:<name>@<marketplace>` 項目清單。需要 Claude.ai 驗證 | `claude --channels plugin:my-notifier@my-marketplace` |

54| `--chrome` | 啟用 [Chrome 瀏覽器整合](/zh-TW/chrome) 以進行網頁自動化和測試 | `claude --chrome` |

55| `--continue`, `-c` | 載入目前目錄中最近的對話。包括使用 `/add-dir` 新增此目錄的工作階段 | `claude --continue` |

56| `--dangerously-load-development-channels` | 啟用不在核准允許清單上的 [channels](/zh-TW/channels-reference#test-during-the-research-preview),用於本機開發。接受 `plugin:<name>@<marketplace>` 和 `server:<name>` 項目。提示確認 | `claude --dangerously-load-development-channels server:webhook` |

57| `--dangerously-skip-permissions` | 略過權限提示。等同於 `--permission-mode bypassPermissions`。請參閱 [permission modes](/zh-TW/permission-modes#skip-all-checks-with-bypasspermissions-mode) 以了解此操作會和不會略過的內容 | `claude --dangerously-skip-permissions` |

58| `--debug` | 啟用偵錯模式,可選類別篩選(例如,`"api,hooks"` 或 `"!statsig,!file"`) | `claude --debug "api,mcp"` |

59| `--debug-file <path>` | 將偵錯日誌寫入特定檔案路徑。隱含啟用偵錯模式。優先於 `CLAUDE_CODE_DEBUG_LOGS_DIR` | `claude --debug-file /tmp/claude-debug.log` |

60| `--disable-slash-commands` | 為此工作階段停用所有 skills 和命令 | `claude --disable-slash-commands` |

61| `--disallowedTools` | 從模型的內容中移除且無法使用的工具 | `"Bash(git log *)" "Bash(git diff *)" "Edit"` |

62| `--effort` | 為目前工作階段設定 [effort level](/zh-TW/model-config#adjust-effort-level)。選項:`low`、`medium`、`high`、`xhigh`、`max`;可用的層級取決於模型。工作階段範圍且不會持久化到設定 | `claude --effort high` |

63| `--enable-auto-mode` | {/* max-version: 2.1.110 */}在 v2.1.111 中移除。Auto mode 現在預設在 `Shift+Tab` 循環中;使用 `--permission-mode auto` 以它開始 | `claude --permission-mode auto` |

64| `--exclude-dynamic-system-prompt-sections` | 將每台機器的系統提示部分(工作目錄、環境資訊、記憶體路徑、git 狀態)移至第一個使用者訊息。改善在執行相同工作的不同使用者和機器之間的提示快取重複使用。僅適用於預設系統提示;設定 `--system-prompt` 或 `--system-prompt-file` 時忽略。與 `-p` 搭配使用以進行指令碼化、多使用者工作負載 | `claude -p --exclude-dynamic-system-prompt-sections "query"` |

65| `--fallback-model` | 當預設模型過載時啟用自動回退到指定的模型(僅列印模式) | `claude -p --fallback-model sonnet "query"` |

66| `--fork-session` | 繼續時,建立新的工作階段 ID 而不是重複使用原始 ID(與 `--resume` 或 `--continue` 搭配使用) | `claude --resume abc123 --fork-session` |

67| `--from-pr` | 繼續連結到特定提取請求的工作階段。接受 PR 編號、GitHub 或 GitHub Enterprise PR URL、GitLab 合併請求 URL 或 Bitbucket 提取請求 URL。當 Claude 建立提取請求時,工作階段會自動連結 | `claude --from-pr 123` |

68| `--ide` | 如果恰好有一個有效的 IDE 可用,在啟動時自動連線到 IDE | `claude --ide` |

69| `--init` | 在工作階段前執行 [Setup hooks](/zh-TW/hooks#setup),使用 `init` 匹配器(僅列印模式) | `claude -p --init "query"` |

70| `--init-only` | 執行 [Setup](/zh-TW/hooks#setup) 和 `SessionStart` hooks,然後退出而不啟動對話 | `claude --init-only` |

71| `--include-hook-events` | 在輸出串流中包含所有 hook 生命週期事件。需要 `--output-format stream-json` | `claude -p --output-format stream-json --include-hook-events "query"` |

72| `--include-partial-messages` | 在輸出中包含部分串流事件。需要 `--print` 和 `--output-format stream-json` | `claude -p --output-format stream-json --include-partial-messages "query"` |

73| `--input-format` | 為列印模式指定輸入格式(選項:`text`、`stream-json`) | `claude -p --output-format json --input-format stream-json` |

74| `--json-schema` | 在代理程式完成其工作流程後取得符合 JSON Schema 的驗證 JSON 輸出(僅列印模式,請參閱 [structured outputs](/zh-TW/agent-sdk/structured-outputs)) | `claude -p --json-schema '{"type":"object","properties":{...}}' "query"` |

75| `--maintenance` | 在工作階段前執行 [Setup hooks](/zh-TW/hooks#setup),使用 `maintenance` 匹配器(僅列印模式) | `claude -p --maintenance "query"` |

76| `--max-budget-usd` | 在停止前在 API 呼叫上花費的最大美元金額(僅列印模式) | `claude -p --max-budget-usd 5.00 "query"` |

77| `--max-turns` | 限制代理程式轉數(僅列印模式)。達到限制時以錯誤退出。預設無限制 | `claude -p --max-turns 3 "query"` |

78| `--mcp-config` | 從 JSON 檔案或字串載入 MCP 伺服器(以空格分隔) | `claude --mcp-config ./mcp.json` |

79| `--model` | 使用最新模型的別名(`sonnet` 或 `opus`)或模型的完整名稱為目前工作階段設定模型 | `claude --model claude-sonnet-4-6` |

80| `--name`, `-n` | 為工作階段設定顯示名稱,顯示在 `/resume` 和終端標題中。您可以使用 `claude --resume <name>` 繼續已命名的工作階段。<br /><br />[`/rename`](/zh-TW/commands) 在工作階段中途變更名稱,也會在提示列中顯示 | `claude -n "my-feature-work"` |

81| `--no-chrome` | 為此工作階段停用 [Chrome 瀏覽器整合](/zh-TW/chrome) | `claude --no-chrome` |

82| `--no-session-persistence` | 停用工作階段持久性,使工作階段不會儲存到磁碟且無法繼續(僅列印模式) | `claude -p --no-session-persistence "query"` |

83| `--output-format` | 為列印模式指定輸出格式(選項:`text`、`json`、`stream-json`) | `claude -p "query" --output-format json` |

84| `--permission-mode` | 以指定的 [permission mode](/zh-TW/permission-modes) 開始。接受 `default`、`acceptEdits`、`plan`、`auto`、`dontAsk` 或 `bypassPermissions`。覆蓋設定檔案中的 `defaultMode` | `claude --permission-mode plan` |

85| `--permission-prompt-tool` | 指定 MCP 工具以在非互動模式下處理權限提示 | `claude -p --permission-prompt-tool mcp_auth_tool "query"` |

86| `--plugin-dir` | 為此工作階段僅從目錄載入 plugins。每個旗標採用一個路徑。重複旗標以使用多個目錄:`--plugin-dir A --plugin-dir B` | `claude --plugin-dir ./my-plugins` |

87| `--print`, `-p` | 列印回應而不進入互動模式(請參閱 [Agent SDK 文件](/zh-TW/agent-sdk/overview) 以了解程式化使用詳細資訊) | `claude -p "query"` |

88| `--remote` | 在 claude.ai 上建立新的 [web session](/zh-TW/claude-code-on-the-web),並提供工作描述 | `claude --remote "Fix the login bug"` |

89| `--remote-control`, `--rc` | 啟動互動式工作階段,並啟用 [Remote Control](/zh-TW/remote-control#start-a-remote-control-session),以便您也可以從 claude.ai 或 Claude 應用程式控制它。可選擇傳遞工作階段的名稱 | `claude --remote-control "My Project"` |

90| `--remote-control-session-name-prefix <prefix>` | [Remote Control](/zh-TW/remote-control) 工作階段名稱的前綴,當未設定明確名稱時自動產生。預設為您的機器主機名稱,產生如 `myhost-graceful-unicorn` 的名稱。設定 `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` 以獲得相同效果 | `claude remote-control --remote-control-session-name-prefix dev-box` |

91| `--replay-user-messages` | 從 stdin 重新發出使用者訊息回到 stdout 以進行確認。需要 `--input-format stream-json` 和 `--output-format stream-json` | `claude -p --input-format stream-json --output-format stream-json --replay-user-messages` |

92| `--resume`, `-r` | 按 ID 或名稱繼續特定工作階段,或顯示互動式選擇器以選擇工作階段。包括使用 `/add-dir` 新增此目錄的工作階段 | `claude --resume auth-refactor` |

93| `--session-id` | 為對話使用特定的工作階段 ID(必須是有效的 UUID) | `claude --session-id "550e8400-e29b-41d4-a716-446655440000"` |

94| `--setting-sources` | 要載入的設定來源的逗號分隔清單(`user`、`project`、`local`) | `claude --setting-sources user,project` |

95| `--settings` | 設定 JSON 檔案的路徑或要載入其他設定的 JSON 字串 | `claude --settings ./settings.json` |

96| `--strict-mcp-config` | 僅使用 `--mcp-config` 中的 MCP 伺服器,忽略所有其他 MCP 設定 | `claude --strict-mcp-config --mcp-config ./mcp.json` |

97| `--system-prompt` | 用自訂文字取代整個系統提示 | `claude --system-prompt "You are a Python expert"` |

98| `--system-prompt-file` | 從檔案載入系統提示,取代預設提示 | `claude --system-prompt-file ./custom-prompt.txt` |

99| `--teleport` | 在本機終端中繼續 [web session](/zh-TW/claude-code-on-the-web) | `claude --teleport` |

100| `--teammate-mode` | 設定 [agent team](/zh-TW/agent-teams) 隊友的顯示方式:`auto`(預設)、`in-process` 或 `tmux`。請參閱 [選擇顯示模式](/zh-TW/agent-teams#choose-a-display-mode) | `claude --teammate-mode in-process` |

101| `--tmux` | 為 worktree 建立 tmux 工作階段。需要 `--worktree`。在可用時使用 iTerm2 原生窗格;傳遞 `--tmux=classic` 以使用傳統 tmux | `claude -w feature-auth --tmux` |

102| `--tools` | 限制 Claude 可以使用的內建工具。使用 `""` 停用全部,`"default"` 為全部,或工具名稱如 `"Bash,Edit,Read"` | `claude --tools "Bash,Edit,Read"` |

103| `--verbose` | 啟用詳細記錄,顯示完整的逐轉輸出 | `claude --verbose` |

104| `--version`, `-v` | 輸出版本號 | `claude -v` |

105| `--worktree`, `-w` | 在隔離的 [git worktree](/zh-TW/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees) 中啟動 Claude,位於 `<repo>/.claude/worktrees/<name>`。如果未提供名稱,則會自動產生一個 | `claude -w feature-auth` |

106 

107### 系統提示旗標

108 

109Claude Code 提供四個旗標用於自訂系統提示。所有四個都在互動和非互動模式中運作。

110 

111| 旗標 | 行為 | 範例 |

112| :---------------------------- | :----------- | :------------------------------------------------------ |

113| `--system-prompt` | 取代整個預設提示 | `claude --system-prompt "You are a Python expert"` |

114| `--system-prompt-file` | 用檔案內容取代 | `claude --system-prompt-file ./prompts/review.txt` |

115| `--append-system-prompt` | 附加到預設提示 | `claude --append-system-prompt "Always use TypeScript"` |

116| `--append-system-prompt-file` | 將檔案內容附加到預設提示 | `claude --append-system-prompt-file ./style-rules.txt` |

117 

118`--system-prompt` 和 `--system-prompt-file` 互斥。附加旗標可以與任一取代旗標組合。

119 

120對於大多數使用案例,請使用附加旗標。附加會保留 Claude Code 的內建功能,同時新增您的需求。僅當您需要對系統提示進行完全控制時,才使用取代旗標。

121 

122## 另請參閱

123 

124* [Chrome 擴充功能](/zh-TW/chrome) - 瀏覽器自動化和網頁測試

125* [互動模式](/zh-TW/interactive-mode) - 快捷鍵、輸入模式和互動功能

126* [快速入門指南](/zh-TW/quickstart) - Claude Code 入門

127* [常見工作流程](/zh-TW/common-workflows) - 進階工作流程和模式

128* [設定](/zh-TW/settings) - 設定選項

129* [Agent SDK 文件](/zh-TW/agent-sdk/overview) - 程式化使用和整合

code-review.md +274 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Code Review

6 

7> 設定自動化 PR 審查,使用多代理分析您的完整程式碼庫來捕捉邏輯錯誤、安全漏洞和迴歸

8 

9<Note>

10 Code Review 處於研究預覽階段,適用於 [Team 和 Enterprise](https://claude.ai/admin-settings/claude-code) 訂閱。對於啟用了 [Zero Data Retention](/zh-TW/zero-data-retention) 的組織,此功能不可用。

11</Note>

12 

13Code Review 分析您的 GitHub pull request,並在發現問題的程式碼行上發佈內聯評論。一群專門的代理在您完整程式碼庫的背景下檢查程式碼變更,尋找邏輯錯誤、安全漏洞、破損的邊界情況和細微的迴歸。

14 

15發現結果按嚴重程度標記,不會批准或阻止您的 PR,因此現有的審查工作流程保持不變。您可以通過在存儲庫中添加 `CLAUDE.md` 或 `REVIEW.md` 文件來調整 Claude 標記的內容。

16 

17要在您自己的 CI 基礎設施中運行 Claude 而不是此託管服務,請參閱 [GitHub Actions](/zh-TW/github-actions) 或 [GitLab CI/CD](/zh-TW/gitlab-ci-cd)。對於自託管 GitHub 實例上的存儲庫,請參閱 [GitHub Enterprise Server](/zh-TW/github-enterprise-server)。

18 

19本頁涵蓋:

20 

21* [審查如何運作](#how-reviews-work)

22* [設定](#set-up-code-review)

23* [手動觸發審查](#manually-trigger-reviews),使用 `@claude review` 和 `@claude review once`

24* [自訂審查](#customize-reviews),使用 `CLAUDE.md` 和 `REVIEW.md`

25* [定價](#pricing)

26* [故障排除](#troubleshooting)失敗的運行和缺失的評論

27 

28## 審查如何運作

29 

30一旦管理員為您的組織[啟用 Code Review](#set-up-code-review),審查將在 PR 開啟時、每次推送時或手動請求時觸發,具體取決於存儲庫的配置行為。在任何模式下,評論 `@claude review` [在 PR 上啟動審查](#manually-trigger-reviews)。

31 

32當審查運行時,多個代理在 Anthropic 基礎設施上並行分析差異和周圍程式碼。每個代理尋找不同類別的問題,然後驗證步驟檢查候選項目是否符合實際程式碼行為,以過濾掉誤報。結果被去重、按嚴重程度排名,並作為內聯評論發佈在發現問題的特定行上,並在審查正文中提供摘要。如果未發現問題,Claude 會在 PR 上發佈簡短的確認評論。

33 

34審查成本隨著 PR 大小和複雜性而擴展,平均在 20 分鐘內完成。管理員可以通過 [分析儀表板](#view-usage) 監控審查活動和支出。

35 

36### 嚴重程度級別

37 

38每個發現都標記有嚴重程度級別:

39 

40| 標記 | 嚴重程度 | 含義 |

41| :- | :--- | :------------------- |

42| 🔴 | 重要 | 應在合併前修復的錯誤 |

43| 🟡 | 細節 | 輕微問題,值得修復但不阻止 |

44| 🟣 | 預先存在 | 程式碼庫中存在但未由此 PR 引入的錯誤 |

45 

46發現包括可折疊的擴展推理部分,您可以展開以了解 Claude 為什麼標記該問題以及它如何驗證問題。

47 

48### 對發現進行評分和回覆

49 

50每個來自 Claude 的審查評論都已附加 👍 和 👎,因此兩個按鈕都會在 GitHub UI 中出現,以便一鍵評分。如果發現有用,請點擊 👍;如果發現錯誤或嘈雜,請點擊 👎。Anthropic 在 PR 合併後收集反應計數,並使用它們來調整審查者。反應不會觸發重新審查或更改 PR 上的任何內容。

51 

52回覆內聯評論不會提示 Claude 回應或更新 PR。要對發現採取行動,請修復程式碼並推送。如果 PR 訂閱了推送觸發的審查,下一次運行將在問題修復時解決線程。要在不推送的情況下請求新審查,請作為 [頂級 PR 評論](#manually-trigger-reviews) 評論 `@claude review once`。

53 

54### 檢查運行輸出

55 

56除了內聯審查評論外,每次審查都會填充 **Claude Code Review** 檢查運行,該運行與您的 CI 檢查一起出現。展開其 **Details** 連結以在一個地方查看每個發現的摘要,按嚴重程度排序:

57 

58| 嚴重程度 | 文件:行 | 問題 |

59| ----- | ------------------------- | ------------------------------ |

60| 🔴 重要 | `src/auth/session.ts:142` | 令牌刷新與登出競爭,留下過時的會話活躍 |

61| 🟡 細節 | `src/auth/session.ts:88` | `parseExpiry` 在格式錯誤的輸入上無聲地返回 0 |

62 

63每個發現也作為 **Files changed** 標籤中的註釋出現,直接標記在相關的差異行上。重要發現用紅色標記呈現,細節用黃色警告,預先存在的錯誤用灰色通知。註釋和嚴重程度表獨立於內聯審查評論寫入檢查運行,因此即使 GitHub 拒絕在移動的行上的內聯評論,它們仍然可用。

64 

65檢查運行始終以中立結論完成,因此它永遠不會通過分支保護規則阻止合併。如果您想根據 Code Review 發現來限制合併,請在您自己的 CI 中讀取檢查運行輸出中的嚴重程度細分。Details 文本的最後一行是機器可讀的評論,您的工作流可以使用 `gh` 和 jq 解析:

66 

67```bash theme={null}

68gh api repos/OWNER/REPO/check-runs/CHECK_RUN_ID \

69 --jq '.output.text | split("bughunter-severity: ")[1] | split(" -->")[0] | fromjson'

70```

71 

72這返回一個 JSON 對象,其中包含每個嚴重程度的計數,例如 `{"normal": 2, "nit": 1, "pre_existing": 0}`。`normal` 鍵保存重要發現的計數;非零值意味著 Claude 發現至少一個值得在合併前修復的錯誤。

73 

74### Code Review 檢查的內容

75 

76默認情況下,Code Review 專注於正確性:會破壞生產的錯誤,而不是格式設置偏好或缺失的測試覆蓋。您可以通過 [添加指導文件](#customize-reviews) 到您的存儲庫來擴展它檢查的內容。

77 

78## 設定 Code Review

79 

80管理員為組織啟用 Code Review 一次,並選擇要包含的存儲庫。

81 

82<Steps>

83 <Step title="開啟 Claude Code 管理員設定">

84 前往 [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) 並找到 Code Review 部分。您需要對 Claude 組織的管理員存取權限以及在 GitHub 組織中安裝 GitHub Apps 的權限。

85 </Step>

86 

87 <Step title="開始設定">

88 點擊 **Setup**。這開始 GitHub App 安裝流程。

89 </Step>

90 

91 <Step title="安裝 Claude GitHub App">

92 按照提示將 Claude GitHub App 安裝到您的 GitHub 組織。該應用請求這些存儲庫權限:

93 

94 * **Contents**:讀取和寫入

95 * **Issues**:讀取和寫入

96 * **Pull requests**:讀取和寫入

97 

98 Code Review 使用對內容的讀取存取權限和對 pull request 的寫入存取權限。更廣泛的權限集也支持 [GitHub Actions](/zh-TW/github-actions),如果您稍後啟用它。

99 </Step>

100 

101 <Step title="選擇存儲庫">

102 選擇要為 Code Review 啟用的存儲庫。如果您看不到存儲庫,請確保您在安裝期間給予 Claude GitHub App 存取權限。您可以稍後添加更多存儲庫。

103 </Step>

104 

105 <Step title="設定每個存儲庫的審查觸發器">

106 設定完成後,Code Review 部分在表格中顯示您的存儲庫。對於每個存儲庫,使用 **Review Behavior** 下拉菜單選擇何時運行審查:

107 

108 * **Once after PR creation**:當 PR 開啟或標記為準備審查時,審查運行一次

109 * **After every push**:在每次推送到 PR 分支時運行審查,在 PR 演變時捕捉新問題,並在您修復標記的問題時自動解決線程

110 * **Manual**:審查僅在有人 [在 PR 上評論 `@claude review` 或 `@claude review once`](#manually-trigger-reviews) 時開始;`@claude review` 也會訂閱 PR 以進行後續推送的審查

111 

112 每次推送時審查運行最多的審查並花費最多。手動模式對於高流量存儲庫很有用,您想選擇特定 PR 進行審查,或者只在 PR 準備好時才開始審查您的 PR。

113 </Step>

114</Steps>

115 

116存儲庫表還顯示每個存儲庫基於最近活動的平均審查成本。使用行操作菜單按存儲庫打開或關閉 Code Review,或完全移除存儲庫。

117 

118要驗證設定,請開啟測試 PR。如果您選擇了自動觸發器,名為 **Claude Code Review** 的檢查運行會在幾分鐘內出現。如果您選擇了手動,在 PR 上評論 `@claude review` 以開始第一次審查。如果沒有檢查運行出現,請確認存儲庫列在您的管理員設定中,並且 Claude GitHub App 有權存取它。

119 

120## 手動觸發審查

121 

122兩個評論命令按需啟動審查。無論存儲庫的配置觸發器如何,兩者都有效,因此您可以使用它們在手動模式下選擇特定 PR 進行審查,或在其他模式下獲得立即重新審查。

123 

124| 命令 | 它做什麼 |

125| :-------------------- | :---------------------- |

126| `@claude review` | 啟動審查並訂閱 PR 以進行今後的推送觸發審查 |

127| `@claude review once` | 啟動單次審查,不訂閱未來推送 |

128 

129當您想要對 PR 的當前狀態獲得反饋但不想每次後續推送都產生審查時,使用 `@claude review once`。這對於具有頻繁推送的長期運行 PR 很有用,或者當您想要一次性第二意見而不改變 PR 的審查行為時。

130 

131對於任一命令觸發審查:

132 

133* 將其發佈為頂級 PR 評論,而不是差異行上的內聯評論

134* 在評論開始時放置命令,如果您使用一次性形式,將 `once` 放在同一行

135* 您必須對存儲庫具有所有者、成員或協作者存取權限

136* PR 必須開啟

137 

138與自動觸發不同,手動觸發在草稿 PR 上運行,因為明確的請求表示您想要現在的審查,無論草稿狀態如何。

139 

140如果該 PR 上已有審查正在運行,請求將排隊直到進行中的審查完成。您可以通過 PR 上的檢查運行監控進度。

141 

142## 自訂審查

143 

144Code Review 從您的存儲庫讀取兩個文件來指導它標記的內容。它們在強度上有所不同:

145 

146* **`CLAUDE.md`**:Claude Code 用於所有任務的共享項目指令,不僅僅是審查。Code Review 將其讀取為項目背景,並將新引入的違規標記為細節。

147* **`REVIEW.md`**:僅審查指導,直接注入到審查管道中每個代理的系統提示中作為最高優先級。使用它來改變標記的內容、嚴重程度以及發現的報告方式。

148 

149### CLAUDE.md

150 

151Code Review 讀取您存儲庫的 `CLAUDE.md` 文件,並將新引入的違規視為 [細節級別](#severity-levels) 的發現。這是雙向工作的:如果您的 PR 以使 `CLAUDE.md` 陳述過時的方式更改程式碼,Claude 會標記文件需要更新。

152 

153Claude 在目錄層次結構的每個級別讀取 `CLAUDE.md` 文件,因此子目錄的 `CLAUDE.md` 中的規則僅適用於該路徑下的文件。有關 `CLAUDE.md` 如何運作的更多信息,請參閱 [memory 文檔](/zh-TW/memory)。

154 

155對於您不想應用於一般 Claude Code 會話的審查特定指導,請改用 [`REVIEW.md`](#review-md)。

156 

157### REVIEW\.md

158 

159`REVIEW.md` 是位於您存儲庫根目錄的文件,它覆蓋 Code Review 在您的存儲庫上的行為方式。其內容被注入到審查管道中每個代理的系統提示中作為最高優先級指令塊,優先於默認審查指導。

160 

161因為它是逐字粘貼的,`REVIEW.md` 是純指令:[`@` 導入語法](/zh-TW/memory#import-additional-files) 不會展開,引用的文件不會讀入提示中。將您想要強制執行的規則直接放在文件中。

162 

163#### 您可以調整什麼

164 

165`REVIEW.md` 是自由格式的 markdown,因此任何您可以表達為審查指令的內容都在範圍內。下面的模式在實踐中影響最大。

166 

167**嚴重程度**:重新定義 🔴 重要對您的存儲庫意味著什麼。默認校準針對生產程式碼;文檔存儲庫、配置存儲庫或原型可能想要更窄的定義。明確說明哪些類別的發現是重要的,哪些最多是細節。您也可以向另一個方向升級,例如將任何 `CLAUDE.md` 違規視為重要而不是默認細節。

168 

169**細節量**:限制單次審查發佈的 🟡 細節評論數量。散文和配置文件可以永遠被打磨。像「最多報告五個細節,在摘要中提及其餘的計數」這樣的上限使審查可操作。

170 

171**跳過規則**:列出 Claude 應該不發佈任何發現的路徑、分支模式和發現類別。常見候選是生成的程式碼、lockfiles、供應商依賴和機器編寫的分支,以及您的 CI 已經強制執行的任何內容,如 linting 或拼寫檢查。對於值得進行某些審查但不完全審查的路徑,設定更高的標準而不是完全跳過:「在 `scripts/` 中,僅在接近確定且嚴重時報告。」

172 

173**存儲庫特定檢查**:添加您想在每個 PR 上標記的規則,例如「新 API 路由必須有集成測試。」因為 `REVIEW.md` 被注入為最高優先級,這些比長 `CLAUDE.md` 中的相同規則更可靠地著陸。

174 

175**驗證標準**:在發佈發現類別之前需要證據。例如,「行為聲明需要源中的 `file:line` 引用,而不是從命名推斷」減少了否則會花費作者往返的誤報。

176 

177**重新審查收斂**:告訴 Claude 當 PR 已經被審查時如何表現。像「在第一次審查後,抑制新細節並僅發佈重要發現」這樣的規則阻止一行修復從僅風格達到第七輪。

178 

179**摘要形狀**:要求審查正文以一行計數開頭,例如 `2 factual, 4 style`,並在這種情況下以「沒有事實問題」開頭。作者想在詳細信息之前知道工作的形狀。

180 

181#### 示例

182 

183此 `REVIEW.md` 為後端服務重新校準嚴重程度,限制細節,跳過生成的文件,並添加存儲庫特定檢查。

184 

185```markdown theme={null}

186# 審查指令

187 

188## 重要在這裡意味著什麼

189 

190保留重要用於會破壞行為、洩露數據或阻止回滾的發現:不正確的邏輯、無範圍的數據庫查詢、日誌或錯誤消息中的 PII,以及不向後兼容的遷移。風格、命名和重構建議最多是細節。

191 

192## 限制細節

193 

194每次審查最多報告五個細節。如果您發現更多,請在摘要中說「加上 N 個類似項目」而不是內聯發佈它們。如果您發現的一切都是細節,請以「沒有阻止問題」開頭摘要。

195 

196## 不要報告

197 

198- CI 已經強制執行的任何內容:lint、格式化、類型錯誤

199- `src/gen/` 下的生成文件和任何 `*.lock` 文件

200- 故意違反生產規則的僅測試程式碼

201 

202## 始終檢查

203 

204- 新 API 路由有集成測試

205- 日誌行不包括電子郵件地址、用戶 ID 或請求正文

206- 數據庫查詢的範圍限於調用者的租戶

207```

208 

209#### 保持專注

210 

211長度有成本:長 `REVIEW.md` 會稀釋最重要的規則。將其保留為改變審查行為的指令,並將一般項目背景留在 `CLAUDE.md` 中。

212 

213## 查看使用情況

214 

215前往 [claude.ai/analytics/code-review](https://claude.ai/analytics/code-review) 查看整個組織的 Code Review 活動。儀表板顯示:

216 

217| 部分 | 它顯示什麼 |

218| :------------------- | :----------------------------- |

219| PRs reviewed | 在選定時間範圍內審查的 pull request 的每日計數 |

220| Cost weekly | Code Review 的每週支出 |

221| Feedback | 因開發人員解決問題而自動解決的審查評論計數 |

222| Repository breakdown | 每個存儲庫審查的 PR 計數和解決的評論 |

223 

224管理員設定中的存儲庫表也顯示每個存儲庫的平均審查成本。儀表板成本數字是用於監控活動的估計;對於發票準確的支出,請參閱您的 Anthropic 帳單。

225 

226## 定價

227 

228Code Review 根據令牌使用情況計費。每次審查平均花費 \$15-25,隨著 PR 大小、程式碼庫複雜性和需要驗證的問題數量而擴展。Code Review 使用通過 [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) 單獨計費,不計入您計劃的包含使用情況。

229 

230您選擇的審查觸發器影響總成本:

231 

232* **Once after PR creation**:每個 PR 運行一次

233* **After every push**:在每次推送時運行,將成本乘以推送次數

234* **Manual**:在有人在 PR 上評論 `@claude review` 之前沒有審查

235 

236在任何模式下,評論 `@claude review` [選擇 PR 進入推送觸發的審查](#manually-trigger-reviews),因此在該評論之後每次推送都會產生額外成本。要運行單次審查而不訂閱未來推送,請改為評論 `@claude review once`。

237 

238成本出現在您的 Anthropic 帳單上,無論您的組織是否為其他 Claude Code 功能使用 Amazon Bedrock 或 Google Vertex AI。要為 Code Review 設定月度支出上限,請前往 [claude.ai/admin-settings/usage](https://claude.ai/admin-settings/usage) 並為 Claude Code Review 服務配置限制。

239 

240通過 [analytics](#view-usage) 中的每週成本圖表或管理員設定中的每個存儲庫平均成本列監控支出。

241 

242## 故障排除

243 

244審查運行是盡力而為的。失敗的運行永遠不會阻止您的 PR,但它也不會自動重試。本部分涵蓋如何從失敗的運行中恢復,以及在檢查運行報告您找不到的問題時在哪裡查看。

245 

246### 重新觸發失敗或超時的審查

247 

248當審查基礎設施遇到內部錯誤或超過其時間限制時,檢查運行完成,標題為 **Code review encountered an error** 或 **Code review timed out**。結論仍然是中立的,因此沒有任何東西阻止您的合併,但沒有發現被發佈。

249 

250要再次運行審查,在 PR 上評論 `@claude review once`。這啟動一個新的審查,不訂閱 PR 以進行未來推送。如果 PR 已訂閱推送觸發的審查,推送新提交也會啟動新審查。

251 

252GitHub 的 Checks 標籤中的 **Re-run** 按鈕不會重新觸發 Code Review。改用評論命令或新推送。

253 

254### 審查未運行,PR 顯示支出上限消息

255 

256當您的組織的月度支出上限達到時,Code Review 在 PR 上發佈單個評論,解釋審查被跳過。審查在下一個計費期開始時自動恢復,或當管理員在 [claude.ai/admin-settings/usage](https://claude.ai/admin-settings/usage) 提高上限時立即恢復。

257 

258### 查找未顯示為內聯評論的問題

259 

260如果檢查運行標題說發現了問題,但您在差異上看不到內聯審查評論,請在這些其他位置查看發現的位置:

261 

262* **Check run Details**:在 Checks 標籤中的 Claude Code Review 檢查旁邊點擊 **Details**。嚴重程度表列出每個發現及其文件、行和摘要,無論內聯評論是否被接受。

263* **Files changed annotations**:在 PR 上打開 **Files changed** 標籤。發現呈現為直接附加到差異行的註釋,與審查評論分開。

264* **Review body**:如果您在審查運行時推送到 PR,某些發現可能引用當前差異中不再存在的行。這些出現在審查正文文本中的 **Additional findings** 標題下,而不是作為內聯評論。

265 

266## 相關資源

267 

268Code Review 設計用於與 Claude Code 的其餘部分一起工作。如果您想在開啟 PR 之前在本地運行審查、需要自託管設定,或想深入了解 `CLAUDE.md` 如何在工具中塑造 Claude 的行為,這些頁面是很好的下一步:

269 

270* [Plugins](/zh-TW/discover-plugins):瀏覽插件市場,包括用於在推送前本地運行按需審查的 `code-review` 插件

271* [GitHub Actions](/zh-TW/github-actions):在您自己的 GitHub Actions 工作流中運行 Claude,以實現超越程式碼審查的自訂自動化

272* [GitLab CI/CD](/zh-TW/gitlab-ci-cd):GitLab 管道的自託管 Claude 集成

273* [Memory](/zh-TW/memory):`CLAUDE.md` 文件如何在 Claude Code 中工作

274* [Analytics](/zh-TW/analytics):追蹤超越程式碼審查的 Claude Code 使用情況

commands.md +113 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 命令

6 

7> Claude Code 中可用命令的完整參考,包括內建命令和捆綁的 skills。

8 

9命令在工作階段內控制 Claude Code。它們提供了一種快速方式來切換模型、管理權限、清除上下文、執行工作流程等。

10 

11輸入 `/` 以查看所有可用命令,或輸入 `/` 後跟字母以篩選。

12 

13下表列出了 Claude Code 中包含的所有命令。標記為 **[Skill](/zh-TW/skills#bundled-skills)** 的項目是捆綁的 skills。它們使用與您自己編寫的 skills 相同的機制:提示交給 Claude,Claude 也可以在相關時自動調用。其他所有項目都是內建命令,其行為被編碼到 CLI 中。若要添加您自己的命令,請參閱 [skills](/zh-TW/skills)。

14 

15並非每個命令都對每個使用者顯示。可用性取決於您的平台、方案和環境。例如,`/desktop` 僅在 macOS 和 Windows 上顯示,`/upgrade` 僅在 Pro 和 Max 方案上顯示。

16 

17在下表中,`<arg>` 表示必需的引數,`[arg]` 表示可選的引數。

18 

19| 命令 | 用途 |

20| :---------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

21| `/add-dir <path>` | 為目前工作階段期間的檔案存取添加工作目錄。大多數 `.claude/` 配置[未從添加的目錄發現](/zh-TW/permissions#additional-directories-grant-file-access-not-configuration)。您可以稍後使用 `--continue` 或 `--resume` 從添加的目錄繼續工作階段 |

22| `/agents` | 管理 [agent](/zh-TW/sub-agents) 配置 |

23| `/autofix-pr [prompt]` | 生成一個[網頁上的 Claude Code](/zh-TW/claude-code-on-the-web#auto-fix-pull-requests) 工作階段,監視目前分支的 PR 並在 CI 失敗或審閱者留下評論時推送修復。使用 `gh pr view` 檢測已簽出分支的開放 PR;若要監視不同的 PR,請先簽出其分支。預設情況下,遠端工作階段被告知修復每個 CI 失敗和審閱評論;傳遞提示以給予它不同的指示,例如 `/autofix-pr only fix lint and type errors`。需要 `gh` CLI 和訪問[網頁上的 Claude Code](/zh-TW/claude-code-on-the-web#who-can-use-claude-code-on-the-web) |

24| `/batch <instruction>` | **[Skill](/zh-TW/skills#bundled-skills).** 在整個程式碼庫中並行協調大規模變更。研究程式碼庫,將工作分解為 5 到 30 個獨立單位,並呈現計劃。獲得批准後,在隔離的 [git worktree](/zh-TW/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees) 中為每個單位生成一個背景 agent。每個 agent 實現其單位、運行測試並開啟 pull request。需要 git 存放庫。示例:`/batch migrate src/ from Solid to React` |

25| `/branch [name]` | 在此時刻建立目前對話的分支。切換到分支並保留原始分支,您可以使用 `/resume` 返回。別名:`/fork`。當設定 [`CLAUDE_CODE_FORK_SUBAGENT`](/zh-TW/env-vars) 時,`/fork` 改為生成[分叉的 subagent](/zh-TW/sub-agents#fork-the-current-conversation),不再是此命令的別名 |

26| `/btw <question>` | 提出快速[側邊問題](/zh-TW/interactive-mode#side-questions-with-%2Fbtw),無需添加到對話中 |

27| `/chrome` | 配置 [Chrome 中的 Claude](/zh-TW/chrome) 設定 |

28| `/claude-api [migrate\|managed-agents-onboard]` | **[Skill](/zh-TW/skills#bundled-skills).** 為您的專案語言(Python、TypeScript、Java、Go、Ruby、C#、PHP 或 cURL)和 Managed Agents 參考加載 Claude API 參考資料。涵蓋工具使用、串流、批次、結構化輸出和常見陷阱。當您的程式碼導入 `anthropic` 或 `@anthropic-ai/sdk` 時也會自動激活。執行 `/claude-api migrate` 以將現有 Claude API 程式碼升級到較新的模型:Claude 詢問要掃描哪些檔案以及要針對哪個模型,然後更新在版本之間變更的模型 ID、thinking 配置和其他參數。執行 `/claude-api managed-agents-onboard` 以進行互動式逐步解說,從頭開始建立新的 Managed Agent |

29| `/clear` | 使用空上下文開始新對話。上一個對話在 `/resume` 中保持可用。若要在繼續同一對話時釋放上下文,請改用 `/compact`。別名:`/reset`、`/new` |

30| `/color [color\|default]` | 設定目前工作階段的提示列顏色。可用顏色:`red`、`blue`、`green`、`yellow`、`purple`、`orange`、`pink`、`cyan`。使用 `default` 重設。當[遠端控制](/zh-TW/remote-control)已連接時,顏色會同步到 claude.ai/code |

31| `/compact [instructions]` | 通過總結到目前為止的對話來釋放上下文。可選擇性地傳遞焦點指示以進行摘要。請參閱[壓縮如何處理規則、skills 和記憶體檔案](/zh-TW/context-window#what-survives-compaction) |

32| `/config` | 開啟[設定](/zh-TW/settings)介面以調整主題、模型、[輸出樣式](/zh-TW/output-styles)和其他偏好設定。別名:`/settings` |

33| `/context` | 將目前的上下文使用情況視覺化為彩色網格。顯示上下文繁重工具、記憶體膨脹和容量警告的最佳化建議 |

34| `/copy [N]` | 將最後一個助手回應複製到剪貼簿。傳遞數字 `N` 以複製第 N 個最新回應:`/copy 2` 複製倒數第二個。當存在程式碼區塊時,顯示互動式選擇器以選擇個別區塊或完整回應。在選擇器中按 `w` 以將選擇寫入檔案而不是剪貼簿,這在 SSH 上很有用 |

35| `/cost` | `/usage` 的別名 |

36| `/debug [description]` | **[Skill](/zh-TW/skills#bundled-skills).** 為目前工作階段啟用偵錯日誌記錄並通過讀取工作階段偵錯日誌來排除故障。除非您使用 `claude --debug` 啟動,否則偵錯日誌記錄預設為關閉,因此在工作階段中期運行 `/debug` 會從該時刻開始捕獲日誌。可選擇性地描述問題以集中分析 |

37| `/desktop` | 在 Claude Code Desktop 應用程式中繼續目前的工作階段。僅限 macOS 和 Windows。別名:`/app` |

38| `/diff` | 開啟互動式差異檢視器,顯示未提交的變更和每個回合的差異。使用左/右箭頭在目前的 git 差異和個別 Claude 回合之間切換,使用上/下箭頭瀏覽檔案 |

39| `/doctor` | 診斷並驗證您的 Claude Code 安裝和設定。結果顯示狀態圖示。按 `f` 讓 Claude 修復任何報告的問題 |

40| `/effort [level\|auto]` | 設定模型[努力程度](/zh-TW/model-config#adjust-effort-level)。接受 `low`、`medium`、`high`、`xhigh` 或 `max`;可用的程度取決於模型,`max` 僅限工作階段。`auto` 重設為模型預設值。不帶引數時,開啟互動式滑塊;使用左右箭頭選擇程度,按 `Enter` 應用。立即生效,無需等待目前回應完成 |

41| `/exit` | 結束 CLI。別名:`/quit` |

42| `/export [filename]` | 將目前的對話匯出為純文字。使用檔案名稱時,直接寫入該檔案。不使用檔案名稱時,開啟對話框以複製到剪貼簿或儲存到檔案 |

43| `/extra-usage` | 配置額外使用量以在達到速率限制時繼續工作 |

44| `/fast [on\|off]` | 切換[快速模式](/zh-TW/fast-mode)開啟或關閉 |

45| `/feedback [report]` | 提交有關 Claude Code 的意見反應。別名:`/bug` |

46| `/fewer-permission-prompts` | **[Skill](/zh-TW/skills#bundled-skills).** 掃描您的記錄以查找常見的唯讀 Bash 和 MCP 工具呼叫,然後將優先允許清單添加到專案 `.claude/settings.json` 以減少權限提示 |

47| `/focus` | 切換焦點檢視,僅顯示您的最後一個提示、帶有編輯 diffstats 的單行工具呼叫摘要和最終回應。選擇在工作階段之間保持。僅在[全螢幕渲染](/zh-TW/fullscreen)中可用 |

48| `/heapdump` | 將 JavaScript 堆快照和記憶體分解寫入 `~/Desktop`,或在沒有 Desktop 資料夾的 Linux 上寫入您的主目錄,以診斷高記憶體使用情況。請參閱[故障排除](/zh-TW/troubleshooting#high-cpu-or-memory-usage) |

49| `/help` | 顯示說明和可用命令 |

50| `/hooks` | 檢視工具事件的 [hook](/zh-TW/hooks) 配置 |

51| `/ide` | 管理 IDE 整合並顯示狀態 |

52| `/init` | 使用 `CLAUDE.md` 指南初始化專案。設定 `CLAUDE_CODE_NEW_INIT=1` 以進行互動式流程,該流程也會逐步引導您完成 skills、hooks 和個人記憶體檔案 |

53| `/insights` | 產生報告,分析您的 Claude Code 工作階段,包括專案領域、互動模式和摩擦點 |

54| `/install-github-app` | 為存放庫設定 [Claude GitHub Actions](/zh-TW/github-actions) 應用程式。引導您選擇存放庫並配置整合 |

55| `/install-slack-app` | 安裝 Claude Slack 應用程式。開啟瀏覽器以完成 OAuth 流程 |

56| `/keybindings` | 開啟或建立您的快捷鍵配置檔案 |

57| `/login` | 登入您的 Anthropic 帳戶 |

58| `/logout` | 登出您的 Anthropic 帳戶 |

59| `/loop [interval] [prompt]` | **[Skill](/zh-TW/skills#bundled-skills).** 在工作階段保持開啟時重複執行提示。省略間隔,Claude 會在迭代之間自動調整步調。省略提示,Claude 運行自主維護檢查,或 `.claude/loop.md` 中的提示(如果存在)。示例:`/loop 5m check if the deploy finished`。請參閱[按計劃運行提示](/zh-TW/scheduled-tasks)。別名:`/proactive` |

60| `/mcp` | 管理 MCP 伺服器連線和 OAuth 驗證 |

61| `/memory` | 編輯 `CLAUDE.md` 記憶體檔案、啟用或停用[自動記憶體](/zh-TW/memory#auto-memory),以及檢視自動記憶體項目 |

62| `/mobile` | 顯示 QR 碼以下載 Claude 行動應用程式。別名:`/ios`、`/android` |

63| `/model [model]` | 選擇或變更 AI 模型。對於支援此功能的模型,使用左/右箭頭以[調整努力程度](/zh-TW/model-config#adjust-effort-level)。不帶引數時,開啟選擇器,當對話有先前輸出時要求確認,因為下一個回應會重新讀取完整歷史記錄而不使用快取上下文。確認後,變更立即應用,無需等待目前回應完成 |

64| `/passes` | 與朋友分享免費一週的 Claude Code。僅在您的帳戶符合資格時可見 |

65| `/permissions` | 管理工具權限的允許、詢問和拒絕規則。開啟互動式對話框,您可以按範圍檢視規則、添加或移除規則、管理工作目錄,以及檢視[最近的自動模式拒絕](/zh-TW/auto-mode-config#review-denials)。別名:`/allowed-tools` |

66| `/plan [description]` | 直接從提示進入 Plan Mode。傳遞可選的描述以進入 Plan Mode 並立即開始該工作,例如 `/plan fix the auth bug` |

67| `/plugin` | 管理 Claude Code [plugins](/zh-TW/plugins) |

68| `/powerup` | 通過具有動畫演示的快速互動式課程探索 Claude Code 功能 |

69| `/pr-comments [PR]` | {/* max-version: 2.1.90 */}在 v2.1.91 中移除。直接詢問 Claude 以查看 pull request 評論。在較早的版本上,從 GitHub pull request 擷取並顯示評論;自動偵測目前分支的 PR,或傳遞 PR URL 或編號。需要 `gh` CLI |

70| `/privacy-settings` | 檢視和更新您的隱私設定。僅適用於 Pro 和 Max 方案訂閱者 |

71| `/recap` | 按需生成目前工作階段的單行摘要。請參閱[工作階段摘要](/zh-TW/interactive-mode#session-recap)以了解您離開後出現的自動摘要 |

72| `/release-notes` | 在互動式版本選擇器中檢視變更日誌。選擇特定版本以查看其發行說明,或選擇顯示所有版本 |

73| `/reload-plugins` | 重新載入所有作用中的 [plugins](/zh-TW/plugins) 以套用待處理的變更,無需重新啟動。報告每個已重新載入的元件的計數,並標記任何載入錯誤 |

74| `/remote-control` | 使此工作階段可從 claude.ai 進行[遠端控制](/zh-TW/remote-control)。別名:`/rc` |

75| `/remote-env` | 為[使用 `--remote` 啟動的網頁工作階段](/zh-TW/claude-code-on-the-web#configure-your-environment)配置預設遠端環境 |

76| `/rename [name]` | 重新命名目前的工作階段並在提示列上顯示名稱。不使用名稱時,從對話歷史記錄自動產生名稱 |

77| `/resume [session]` | 按 ID 或名稱繼續對話,或開啟工作階段選擇器。別名:`/continue` |

78| `/review [PR]` | 在您目前的工作階段中本地審閱 pull request。如需更深入的雲端審閱,請參閱 [`/ultrareview`](/zh-TW/ultrareview) |

79| `/rewind` | 將對話和/或程式碼倒帶到上一個時刻,或從選定的訊息進行摘要。請參閱 [checkpointing](/zh-TW/checkpointing)。別名:`/checkpoint`、`/undo` |

80| `/sandbox` | 切換 [sandbox 模式](/zh-TW/sandboxing)。僅在支援的平台上可用 |

81| `/schedule [description]` | 建立、更新、列出或執行[例行工作](/zh-TW/routines)。Claude 會以對話方式引導您完成設定。別名:`/routines` |

82| `/security-review` | 分析目前分支上的待處理變更以查找安全漏洞。檢查 git 差異並識別注入、驗證問題和資料洩露等風險 |

83| `/setup-bedrock` | 通過互動式精靈配置 [Amazon Bedrock](/zh-TW/amazon-bedrock) 驗證、區域和模型釘選。僅在設定 `CLAUDE_CODE_USE_BEDROCK=1` 時可見。首次 Bedrock 使用者也可以從登入螢幕訪問此精靈 |

84| `/setup-vertex` | 通過互動式精靈配置 [Google Vertex AI](/zh-TW/google-vertex-ai) 驗證、專案、區域和模型釘選。僅在設定 `CLAUDE_CODE_USE_VERTEX=1` 時可見。首次 Vertex AI 使用者也可以從登入螢幕訪問此精靈 |

85| `/simplify [focus]` | **[Skill](/zh-TW/skills#bundled-skills).** 審閱您最近變更的檔案以查找程式碼重用、品質和效率問題,然後修復它們。並行生成三個審閱 agent,聚合其發現並應用修復。傳遞文字以集中於特定關注點:`/simplify focus on memory efficiency` |

86| `/skills` | 列出可用的 [skills](/zh-TW/skills)。按 `t` 按 token 計數排序 |

87| `/stats` | `/usage` 的別名。在 Stats 標籤上開啟 |

88| `/status` | 開啟設定介面(狀態標籤),顯示版本、模型、帳戶和連線狀態。在 Claude 回應時運作,無需等待目前回應完成 |

89| `/statusline` | 配置 Claude Code 的[狀態列](/zh-TW/statusline)。描述您想要的內容,或不帶引數執行以從您的 shell 提示自動配置 |

90| `/stickers` | 訂購 Claude Code 貼紙 |

91| `/tasks` | 列出並管理背景工作。也可用作 `/bashes` |

92| `/team-onboarding` | 從您的 Claude Code 使用歷史記錄產生團隊入職指南。Claude 分析您過去 30 天的工作階段、命令和 MCP 伺服器使用情況,並產生一份 markdown 指南,團隊成員可以貼上作為第一條訊息以快速設定 |

93| `/teleport` | 將[網頁上的 Claude Code](/zh-TW/claude-code-on-the-web#from-web-to-terminal) 工作階段拉入此終端機:開啟選擇器,然後擷取分支和對話。也可用作 `/tp`。需要 claude.ai 訂閱 |

94| `/terminal-setup` | 為 Shift+Enter 和其他快捷鍵配置終端機快捷鍵。僅在需要它的終端機中可見,例如 VS Code、Cursor、Windsurf、Alacritty 或 Zed |

95| `/theme` | 變更色彩主題。包括跟隨您終端機深色或淺色背景的 `auto` 選項、淺色和深色變體、色盲無障礙(daltonized)主題、ANSI 主題(使用您終端機的色彩調色盤),以及來自 `~/.claude/themes/` 或 plugins 的任何[自訂主題](/zh-TW/terminal-config#create-a-custom-theme) |

96| `/tui [default\|fullscreen]` | 設定終端機 UI 渲染器並使用您的對話完整重新啟動到它。`fullscreen` 啟用[無閃爍 alt-screen 渲染器](/zh-TW/fullscreen)。不帶引數時,列印作用中的渲染器 |

97| `/ultraplan <prompt>` | 在 [ultraplan](/zh-TW/ultraplan) 工作階段中草擬計劃,在您的瀏覽器中檢視它,然後遠端執行或將其發送回您的終端機 |

98| `/ultrareview [PR]` | 在雲端沙箱中使用 [ultrareview](/zh-TW/ultrareview) 運行深度、多 agent 程式碼審閱。Pro 和 Max 上包括 3 次免費執行,至 2026 年 5 月 5 日,然後需要[額外使用](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) |

99| `/upgrade` | 開啟升級頁面以切換到更高的方案層級 |

100| `/usage` | 顯示工作階段成本、方案使用限制和活動統計資訊。請參閱[成本追蹤指南](/zh-TW/costs#using-the-%2Fusage-command)以了解訂閱特定的詳細資訊。`/cost` 和 `/stats` 是別名 |

101| `/vim` | {/* max-version: 2.1.91 */}在 v2.1.92 中移除。若要在 Vim 和一般編輯模式之間切換,請使用 `/config` → Editor mode |

102| `/voice [hold\|tap\|off]` | 切換[語音聽寫](/zh-TW/voice-dictation),或在特定模式下啟用它。需要 Claude.ai 帳戶 |

103| `/web-setup` | 使用您的本地 `gh` CLI 認證將您的 GitHub 帳戶連接到[網頁上的 Claude Code](/zh-TW/web-quickstart#connect-from-your-terminal)。如果 GitHub 未連接,`/schedule` 會自動提示此操作 |

104 

105## MCP prompts

106 

107MCP 伺服器可以公開顯示為命令的提示。這些使用 `/mcp__<server>__<prompt>` 格式,並從連接的伺服器動態發現。請參閱 [MCP prompts](/zh-TW/mcp#use-mcp-prompts-as-commands) 以了解詳細資訊。

108 

109## 另請參閱

110 

111* [Skills](/zh-TW/skills):建立您自己的命令

112* [Interactive mode](/zh-TW/interactive-mode):鍵盤快捷鍵、Vim 模式和命令歷史記錄

113* [CLI reference](/zh-TW/cli-reference):啟動時間旗標

common-workflows.md +1030 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 常見工作流程

6 

7> 使用 Claude Code 探索程式碼庫、修復錯誤、重構、測試和其他日常任務的逐步指南。

8 

9本頁涵蓋日常開發的實用工作流程:探索陌生程式碼、除錯、重構、編寫測試、建立 PR 和管理會話。每個部分都包含您可以根據自己的專案調整的範例提示。如需更高層級的模式和提示,請參閱[最佳實踐](/zh-TW/best-practices)。

10 

11## 了解新的程式碼庫

12 

13### 快速取得程式碼庫概覽

14 

15假設您剛加入一個新專案,需要快速了解其結構。

16 

17<Steps>

18 <Step title="導航到專案根目錄">

19 ```bash theme={null}

20 cd /path/to/project

21 ```

22 </Step>

23 

24 <Step title="啟動 Claude Code">

25 ```bash theme={null}

26 claude

27 ```

28 </Step>

29 

30 <Step title="要求高層級概覽">

31 ```text theme={null}

32 give me an overview of this codebase

33 ```

34 </Step>

35 

36 <Step title="深入探討特定元件">

37 ```text theme={null}

38 explain the main architecture patterns used here

39 ```

40 

41 ```text theme={null}

42 what are the key data models?

43 ```

44 

45 ```text theme={null}

46 how is authentication handled?

47 ```

48 </Step>

49</Steps>

50 

51<Tip>

52 提示:

53 

54 * 從廣泛的問題開始,然後縮小到特定領域

55 * 詢問專案中使用的編碼慣例和模式

56 * 要求提供專案特定術語的詞彙表

57</Tip>

58 

59### 尋找相關程式碼

60 

61假設您需要找到與特定功能相關的程式碼。

62 

63<Steps>

64 <Step title="要求 Claude 尋找相關檔案">

65 ```text theme={null}

66 find the files that handle user authentication

67 ```

68 </Step>

69 

70 <Step title="取得元件如何互動的背景資訊">

71 ```text theme={null}

72 how do these authentication files work together?

73 ```

74 </Step>

75 

76 <Step title="了解執行流程">

77 ```text theme={null}

78 trace the login process from front-end to database

79 ```

80 </Step>

81</Steps>

82 

83<Tip>

84 提示:

85 

86 * 明確說明您要尋找的內容

87 * 使用專案中的領域語言

88 * 為您的語言安裝[程式碼智能外掛](/zh-TW/discover-plugins#code-intelligence),以便 Claude 進行精確的'前往定義'和'尋找參考'導航

89</Tip>

90 

91***

92 

93## 有效地修復錯誤

94 

95假設您遇到了錯誤訊息,需要找到並修復其來源。

96 

97<Steps>

98 <Step title="與 Claude 分享錯誤">

99 ```text theme={null}

100 I'm seeing an error when I run npm test

101 ```

102 </Step>

103 

104 <Step title="要求修復建議">

105 ```text theme={null}

106 suggest a few ways to fix the @ts-ignore in user.ts

107 ```

108 </Step>

109 

110 <Step title="應用修復">

111 ```text theme={null}

112 update user.ts to add the null check you suggested

113 ```

114 </Step>

115</Steps>

116 

117<Tip>

118 提示:

119 

120 * 告訴 Claude 重現問題的命令並取得堆疊追蹤

121 * 提及重現錯誤的任何步驟

122 * 讓 Claude 知道錯誤是間歇性的還是持續的

123</Tip>

124 

125***

126 

127## 重構程式碼

128 

129假設您需要更新舊程式碼以使用現代模式和實踐。

130 

131<Steps>

132 <Step title="識別用於重構的舊版程式碼">

133 ```text theme={null}

134 find deprecated API usage in our codebase

135 ```

136 </Step>

137 

138 <Step title="取得重構建議">

139 ```text theme={null}

140 suggest how to refactor utils.js to use modern JavaScript features

141 ```

142 </Step>

143 

144 <Step title="安全地應用變更">

145 ```text theme={null}

146 refactor utils.js to use ES2024 features while maintaining the same behavior

147 ```

148 </Step>

149 

150 <Step title="驗證重構">

151 ```text theme={null}

152 run tests for the refactored code

153 ```

154 </Step>

155</Steps>

156 

157<Tip>

158 提示:

159 

160 * 要求 Claude 解釋現代方法的優點

161 * 在需要時要求變更保持向後相容性

162 * 以小的、可測試的增量進行重構

163</Tip>

164 

165***

166 

167## 使用專門的 subagents

168 

169假設您想使用專門的 AI subagents 來更有效地處理特定任務。

170 

171<Steps>

172 <Step title="檢視可用的 subagents">

173 ```text theme={null}

174 /agents

175 ```

176 

177 這會顯示所有可用的 subagents 並讓您建立新的。

178 </Step>

179 

180 <Step title="自動使用 subagents">

181 Claude Code 會自動將適當的任務委派給專門的 subagents:

182 

183 ```text theme={null}

184 review my recent code changes for security issues

185 ```

186 

187 ```text theme={null}

188 run all tests and fix any failures

189 ```

190 </Step>

191 

192 <Step title="明確要求特定的 subagents">

193 ```text theme={null}

194 use the code-reviewer subagent to check the auth module

195 ```

196 

197 ```text theme={null}

198 have the debugger subagent investigate why users can't log in

199 ```

200 </Step>

201 

202 <Step title="為您的工作流程建立自訂 subagents">

203 ```text theme={null}

204 /agents

205 ```

206 

207 然後選擇「建立新 subagent」並按照提示定義:

208 

209 * 描述 subagent 目的的唯一識別碼(例如 `code-reviewer`、`api-designer`)。

210 * Claude 何時應使用此代理

211 * 它可以存取哪些工具

212 * 描述代理角色和行為的系統提示

213 </Step>

214</Steps>

215 

216<Tip>

217 提示:

218 

219 * 在 `.claude/agents/` 中建立專案特定的 subagents 以供團隊共享

220 * 使用描述性的 `description` 欄位來啟用自動委派

221 * 限制工具存取權限為每個 subagent 實際需要的內容

222 * 查看[subagents 文件](/zh-TW/sub-agents)以取得詳細範例

223</Tip>

224 

225***

226 

227## 使用 Plan Mode 進行安全的程式碼分析

228 

229Plan Mode 指示 Claude 通過使用唯讀操作分析程式碼庫來建立計畫,非常適合探索程式碼庫、規劃複雜變更或安全地檢查程式碼。在 Plan Mode 中,Claude 使用 [`AskUserQuestion`](/zh-TW/tools-reference) 在提出計畫之前收集需求並澄清您的目標。

230 

231### 何時使用 Plan Mode

232 

233* **多步驟實現**:當您的功能需要編輯許多檔案時

234* **程式碼探索**:當您想在進行任何變更之前徹底研究程式碼庫時

235* **互動式開發**:當您想與 Claude 迭代方向時

236 

237### 如何使用 Plan Mode

238 

239**在會話期間開啟 Plan Mode**

240 

241您可以在會話期間使用 **Shift+Tab** 循環切換權限模式。

242 

243如果您處於 Normal Mode,**Shift+Tab** 首先切換到 Auto-Accept Mode,在終端底部顯示 `⏵⏵ accept edits on`。隨後的 **Shift+Tab** 將切換到 Plan Mode,顯示 `⏸ plan mode on`。

244 

245**在 Plan Mode 中啟動新會話**

246 

247要在 Plan Mode 中啟動新會話,請使用 `--permission-mode plan` 標誌:

248 

249```bash theme={null}

250claude --permission-mode plan

251```

252 

253**在 Plan Mode 中執行「無頭」查詢**

254 

255您也可以使用 `-p` 直接在 Plan Mode 中執行查詢(即在[「無頭模式」](/zh-TW/headless)中):

256 

257```bash theme={null}

258claude --permission-mode plan -p "Analyze the authentication system and suggest improvements"

259```

260 

261### 範例:規劃複雜的重構

262 

263```bash theme={null}

264claude --permission-mode plan

265```

266 

267```text theme={null}

268I need to refactor our authentication system to use OAuth2. Create a detailed migration plan.

269```

270 

271Claude 分析當前實現並建立全面的計畫。使用後續問題進行細化:

272 

273```text theme={null}

274What about backward compatibility?

275```

276 

277```text theme={null}

278How should we handle database migration?

279```

280 

281<Tip>按 `Ctrl+G` 在預設文字編輯器中開啟計畫,您可以在 Claude 繼續之前直接編輯它。</Tip>

282 

283當您接受計畫時,Claude 會自動從計畫內容命名會話。名稱會出現在提示欄和會話選擇器中。如果您已經使用 `--name` 或 `/rename` 設定了名稱,接受計畫不會覆蓋它。

284 

285### 將 Plan Mode 設定為預設值

286 

287```json theme={null}

288// .claude/settings.json

289{

290 "permissions": {

291 "defaultMode": "plan"

292 }

293}

294```

295 

296有關更多配置選項,請參閱[設定文件](/zh-TW/settings#available-settings)。

297 

298***

299 

300## 使用測試

301 

302假設您需要為未涵蓋的程式碼新增測試。

303 

304<Steps>

305 <Step title="識別未測試的程式碼">

306 ```text theme={null}

307 find functions in NotificationsService.swift that are not covered by tests

308 ```

309 </Step>

310 

311 <Step title="產生測試框架">

312 ```text theme={null}

313 add tests for the notification service

314 ```

315 </Step>

316 

317 <Step title="新增有意義的測試案例">

318 ```text theme={null}

319 add test cases for edge conditions in the notification service

320 ```

321 </Step>

322 

323 <Step title="執行並驗證測試">

324 ```text theme={null}

325 run the new tests and fix any failures

326 ```

327 </Step>

328</Steps>

329 

330Claude 可以產生遵循您專案現有模式和慣例的測試。要求測試時,請明確說明您想驗證的行為。Claude 會檢查您現有的測試檔案,以符合已在使用的風格、框架和斷言模式。

331 

332為了獲得全面的涵蓋範圍,要求 Claude 識別您可能遺漏的邊界情況。Claude 可以分析您的程式碼路徑,並建議測試錯誤條件、邊界值和容易忽視的意外輸入。

333 

334***

335 

336## 建立提取請求

337 

338您可以直接要求 Claude 建立提取請求(「為我的變更建立 pr」),或逐步引導 Claude 完成:

339 

340<Steps>

341 <Step title="總結您的變更">

342 ```text theme={null}

343 summarize the changes I've made to the authentication module

344 ```

345 </Step>

346 

347 <Step title="產生提取請求">

348 ```text theme={null}

349 create a pr

350 ```

351 </Step>

352 

353 <Step title="檢查並細化">

354 ```text theme={null}

355 enhance the PR description with more context about the security improvements

356 ```

357 </Step>

358</Steps>

359 

360當您使用 `gh pr create` 建立 PR 時,會話會自動連結到該 PR。您稍後可以使用 `claude --from-pr <number>` 繼續。

361 

362<Tip>

363 在提交前檢查 Claude 產生的 PR,並要求 Claude 突出顯示潛在的風險或考慮事項。

364</Tip>

365 

366## 處理文件

367 

368假設您需要為程式碼新增或更新文件。

369 

370<Steps>

371 <Step title="識別未記錄的程式碼">

372 ```text theme={null}

373 find functions without proper JSDoc comments in the auth module

374 ```

375 </Step>

376 

377 <Step title="產生文件">

378 ```text theme={null}

379 add JSDoc comments to the undocumented functions in auth.js

380 ```

381 </Step>

382 

383 <Step title="檢查並增強">

384 ```text theme={null}

385 improve the generated documentation with more context and examples

386 ```

387 </Step>

388 

389 <Step title="驗證文件">

390 ```text theme={null}

391 check if the documentation follows our project standards

392 ```

393 </Step>

394</Steps>

395 

396<Tip>

397 提示:

398 

399 * 指定您想要的文件風格(JSDoc、docstrings 等)

400 * 要求文件中的範例

401 * 要求公開 API、介面和複雜邏輯的文件

402</Tip>

403 

404***

405 

406## 在筆記和非程式碼資料夾中工作

407 

408Claude Code 可在任何目錄中工作。在筆記保管庫、文件資料夾或任何 markdown 檔案集合中執行它,以搜尋、編輯和重新組織內容,就像您處理程式碼一樣。

409 

410`.claude/` 目錄和 `CLAUDE.md` 與其他工具的配置目錄並存,不會產生衝突。Claude 在每次工具呼叫時都會重新讀取檔案,所以它會在下次讀取該檔案時看到您在另一個應用程式中所做的編輯。

411 

412***

413 

414## 使用影像

415 

416假設您需要在程式碼庫中使用影像,並希望 Claude 幫助分析影像內容。

417 

418<Steps>

419 <Step title="將影像新增到對話中">

420 您可以使用以下任何方法:

421 

422 1. 將影像拖放到 Claude Code 視窗中

423 2. 複製影像並使用 ctrl+v 將其貼到 CLI 中(不要使用 cmd+v)

424 3. 向 Claude 提供影像路徑。例如,「分析此影像:/path/to/your/image.png」

425 </Step>

426 

427 <Step title="要求 Claude 分析影像">

428 ```text theme={null}

429 What does this image show?

430 ```

431 

432 ```text theme={null}

433 Describe the UI elements in this screenshot

434 ```

435 

436 ```text theme={null}

437 Are there any problematic elements in this diagram?

438 ```

439 </Step>

440 

441 <Step title="使用影像作為背景資訊">

442 ```text theme={null}

443 Here's a screenshot of the error. What's causing it?

444 ```

445 

446 ```text theme={null}

447 This is our current database schema. How should we modify it for the new feature?

448 ```

449 </Step>

450 

451 <Step title="從視覺內容取得程式碼建議">

452 ```text theme={null}

453 Generate CSS to match this design mockup

454 ```

455 

456 ```text theme={null}

457 What HTML structure would recreate this component?

458 ```

459 </Step>

460</Steps>

461 

462<Tip>

463 提示:

464 

465 * 當文字描述不清楚或繁瑣時,使用影像

466 * 包含錯誤、UI 設計或圖表的螢幕截圖以獲得更好的背景資訊

467 * 您可以在對話中使用多個影像

468 * 影像分析適用於圖表、螢幕截圖、模型等

469 * 當 Claude 參考影像時(例如 `[Image #1]`),`Cmd+Click`(Mac)或 `Ctrl+Click`(Windows/Linux)連結以在預設檢視器中開啟影像

470</Tip>

471 

472***

473 

474## 參考檔案和目錄

475 

476使用 @ 快速包含檔案或目錄,無需等待 Claude 讀取它們。

477 

478<Steps>

479 <Step title="參考單個檔案">

480 ```text theme={null}

481 Explain the logic in @src/utils/auth.js

482 ```

483 

484 這會在對話中包含檔案的完整內容。

485 </Step>

486 

487 <Step title="參考目錄">

488 ```text theme={null}

489 What's the structure of @src/components?

490 ```

491 

492 這提供了帶有檔案資訊的目錄清單。

493 </Step>

494 

495 <Step title="參考 MCP 資源">

496 ```text theme={null}

497 Show me the data from @github:repos/owner/repo/issues

498 ```

499 

500 這使用 @server:resource 格式從連接的 MCP 伺服器取得資料。有關詳細資訊,請參閱 [MCP 資源](/zh-TW/mcp#use-mcp-resources)。

501 </Step>

502</Steps>

503 

504<Tip>

505 提示:

506 

507 * 檔案路徑可以是相對的或絕對的

508 * @ 檔案參考會在檔案的目錄和父目錄中新增 `CLAUDE.md` 到背景資訊

509 * 目錄參考顯示檔案清單,而不是內容

510 * 您可以在單個訊息中參考多個檔案(例如「@file1.js and @file2.js」)

511</Tip>

512 

513***

514 

515## 使用擴展思考(Thinking Mode)

516 

517[擴展思考](https://platform.claude.com/docs/zh-TW/build-with-claude/extended-thinking)預設啟用,為 Claude 提供空間在回應前逐步推理複雜問題。此推理在詳細模式中可見,您可以使用 `Ctrl+O` 切換。在擴展思考期間,進度提示會出現在指示器下方,例如「still thinking」和「almost done thinking」,以指示 Claude 正在積極工作。

518 

519此外,[支援努力級別的模型](/zh-TW/model-config#adjust-effort-level)使用自適應推理:不是固定的思考令牌預算,而是模型根據您的努力級別設定和手邊的任務動態決定是否以及如何思考。自適應推理讓 Claude 對日常提示回應更快,並為受益於深度思考的步驟保留更深層的思考。

520 

521擴展思考對於複雜的架構決策、具有挑戰性的錯誤、多步驟實現規劃和評估不同方法之間的權衡特別有價值。

522 

523<Note>

524 「think」、「think hard」和「think more」等短語被解釋為常規提示指令,不分配思考令牌。

525</Note>

526 

527### 配置 Thinking Mode

528 

529思考預設啟用,但您可以調整或禁用它。

530 

531| 範圍 | 如何配置 | 詳細資訊 |

532| -------------------- | ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |

533| **努力級別** | 執行 `/effort`、在 `/model` 中調整,或設定 [`CLAUDE_CODE_EFFORT_LEVEL`](/zh-TW/env-vars) | 控制[支援的模型](/zh-TW/model-config#adjust-effort-level)上的思考深度 |

534| **`ultrathink` 關鍵字** | 在提示中的任何地方包含「ultrathink」 | 在該輪添加上下文指令,告訴模型進行更多推理。不會改變努力級別本身;請參閱[調整努力級別](/zh-TW/model-config#adjust-effort-level)以了解相關資訊 |

535| **切換快捷鍵** | 按 `Option+T`(macOS)或 `Alt+T`(Windows/Linux) | 切換當前會話的思考開/關(所有模型)。可能需要[終端配置](/zh-TW/terminal-config)來啟用 Option 鍵快捷鍵 |

536| **全域預設值** | 使用 `/config` 切換 Thinking Mode | 在所有專案中設定預設值(所有模型)。<br />儲存為 `~/.claude/settings.json` 中的 `alwaysThinkingEnabled` |

537| **限制令牌預算** | 設定 [`MAX_THINKING_TOKENS`](/zh-TW/env-vars) 環境變數 | 將思考預算限制為特定數量的令牌。在支援自適應推理的模型上,只有設定為 `0` 時才適用,除非禁用自適應推理。範例:`export MAX_THINKING_TOKENS=10000` |

538 

539要檢視 Claude 的思考過程,按 `Ctrl+O` 切換詳細模式,並查看顯示為灰色斜體文字的內部推理。

540 

541### 擴展思考如何運作

542 

543擴展思考控制 Claude 在回應前執行多少內部推理。更多思考提供更多空間來探索解決方案、分析邊界情況和自我糾正錯誤。

544 

545在[支援努力級別的模型](/zh-TW/model-config#adjust-effort-level)上,思考使用自適應推理:模型根據您選擇的努力級別動態分配思考令牌。這是調整速度和推理深度之間權衡的推薦方式。如果您想讓 Claude 比您的努力級別會產生的更多或更少地思考,您也可以直接在提示中或在 `CLAUDE.md` 中說明。

546 

547使用較舊的模型,思考使用固定令牌預算,從您的輸出分配中提取。預算因模型而異;有關詳細資訊,請參閱 [`MAX_THINKING_TOKENS`](/zh-TW/env-vars)。您可以使用該環境變數限制預算,或通過 `/config` 或 `Option+T`/`Alt+T` 切換完全禁用思考。

548 

549在支援自適應推理的模型上,`MAX_THINKING_TOKENS` 只在設定為 `0` 以禁用思考時適用,或當 `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1` 將模型恢復為固定預算時適用。`CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` 僅適用於 Opus 4.6 和 Sonnet 4.6。Opus 4.7 始終使用自適應推理,不支援固定思考預算。請參閱[環境變數](/zh-TW/env-vars)。

550 

551<Warning>

552 您需要為所有使用的思考令牌付費,即使思考摘要被編輯。在互動模式中,思考預設顯示為摺疊的存根。在 `settings.json` 中設定 `showThinkingSummaries: true` 以顯示完整摘要。

553</Warning>

554 

555***

556 

557## 繼續之前的對話

558 

559啟動 Claude Code 時,您可以繼續之前的會話:

560 

561* `claude --continue` 繼續當前目錄中最近的對話

562* `claude --resume` 開啟對話選擇器或按名稱繼續

563* `claude --from-pr 123` 繼續連結到特定提取請求的會話

564 

565從活躍會話內,使用 `/resume` 切換到不同的對話。

566 

567當選定的會話足夠舊且足夠大,以至於重新閱讀它會消耗您使用限額的大部分時,`--resume`、`--continue` 和 `/resume` 會提供從摘要繼續而不是載入完整記錄的選項。此提示在 Amazon Bedrock、Google Cloud Vertex AI 或 Microsoft Foundry 上不可用。

568 

569會話按專案目錄儲存。預設情況下,`/resume` 選擇器顯示來自當前 worktree 的互動式會話,帶有快捷鍵以擴展清單到其他 worktrees 或專案、搜尋、預覽和重新命名。有關完整的快捷鍵參考,請參閱下面的[使用會話選擇器](#use-the-session-picker)。

570 

571當您從同一儲存庫的另一個 worktree 選擇會話時,Claude Code 會直接繼續它,無需您先切換目錄。從不相關的專案選擇會話會將 `cd` 和繼續命令複製到您的剪貼簿。

572 

573按名稱繼續會在當前儲存庫及其 worktrees 中解析。`claude --resume <name>` 和 `/resume <name>` 都會尋找精確匹配並直接繼續它,即使會話位於不同的 worktree 中。

574 

575當名稱不明確時,`claude --resume <name>` 會開啟選擇器,並將名稱預先填充為搜尋詞。`/resume <name>` 從會話內報告錯誤,所以執行 `/resume` 不帶引數以開啟選擇器並選擇。

576 

577由 `claude -p` 或 SDK 調用建立的會話不會出現在選擇器中,但您仍然可以通過將其會話 ID 直接傳遞給 `claude --resume <session-id>` 來繼續。

578 

579### 命名您的會話

580 

581給會話起描述性名稱以便稍後找到它們。這是在處理多個任務或功能時的最佳實踐。

582 

583<Steps>

584 <Step title="命名會話">

585 在啟動時使用 `-n` 命名會話:

586 

587 ```bash theme={null}

588 claude -n auth-refactor

589 ```

590 

591 或在會話期間使用 `/rename`,這也會在提示欄上顯示名稱:

592 

593 ```text theme={null}

594 /rename auth-refactor

595 ```

596 

597 您也可以從選擇器重新命名任何會話:執行 `/resume`,導航到會話,然後按 `Ctrl+R`。

598 </Step>

599 

600 <Step title="稍後按名稱繼續">

601 從命令列:

602 

603 ```bash theme={null}

604 claude --resume auth-refactor

605 ```

606 

607 或從活躍會話內:

608 

609 ```text theme={null}

610 /resume auth-refactor

611 ```

612 </Step>

613</Steps>

614 

615### 使用會話選擇器

616 

617`/resume` 命令(或 `claude --resume` 不帶引數)開啟具有以下功能的互動式會話選擇器:

618 

619**選擇器中的快捷鍵:**

620 

621| 快捷鍵 | 動作 |

622| :----------------------- | :------------------------------------------------------------- |

623| `↑` / `↓` | 在會話之間導航 |

624| `→` / `←` | 展開或摺疊分組的會話 |

625| `Enter` | 選擇並繼續突出顯示的會話 |

626| `Space` | 預覽會話內容。`Ctrl+V` 在不將其捕獲為貼上的終端上也有效 |

627| `Ctrl+R` | 重新命名突出顯示的會話 |

628| `/` 或除 `Space` 外的任何可列印字元 | 進入搜尋模式並篩選會話 |

629| `Ctrl+A` | 顯示此機器上所有專案的會話。再次按下以恢復當前儲存庫 |

630| `Ctrl+W` | 顯示當前儲存庫所有 worktrees 的會話。再次按下以恢復當前 worktree。僅在多 worktree 儲存庫中顯示 |

631| `Ctrl+B` | 篩選為來自您當前 git 分支的會話。再次按下以顯示所有分支的會話 |

632| `Esc` | 退出選擇器或搜尋模式 |

633 

634**會話組織:**

635 

636選擇器顯示帶有有用中繼資料的會話:

637 

638* 會話名稱(如果設定),否則對話摘要或第一個使用者提示

639* 自上次活動以來經過的時間

640* 訊息計數

641* Git 分支(如果適用)

642* 專案路徑,在使用 `Ctrl+A` 擴展到所有專案後顯示

643 

644分叉的會話(使用 `/branch`、`/rewind` 或 `--fork-session` 建立)在其根會話下分組,使找到相關對話更容易。

645 

646<Tip>

647 提示:

648 

649 * **盡早命名會話**:在開始處理不同任務時使用 `/rename`——稍後找到「payment-integration」比「explain this function」容易得多

650 * 使用 `--continue` 快速存取當前目錄中最近的對話

651 * 當您知道需要哪個會話時,使用 `--resume session-name`

652 * 當您需要瀏覽和選擇時,使用 `--resume`(不帶名稱)

653 * 對於指令碼,使用 `claude --continue --print "prompt"` 以非互動模式繼續

654 * 在選擇器中按 `Space` 在繼續前預覽會話

655 * 繼續的對話以與原始對話相同的模型和配置開始

656 

657 它如何運作:

658 

659 1. **對話儲存**:所有對話都自動在本地儲存,包含完整的訊息歷史記錄

660 2. **訊息反序列化**:繼續時,整個訊息歷史記錄被恢復以保持背景資訊

661 3. **工具狀態**:來自之前對話的工具使用和結果被保留

662 4. **背景資訊恢復**:對話以所有先前背景資訊完整繼續

663</Tip>

664 

665***

666 

667## 使用 Git worktrees 執行平行 Claude Code 會話

668 

669同時處理多個任務時,您需要每個 Claude 會話都有自己的程式碼庫副本,以便變更不會衝突。Git worktrees 通過建立單獨的工作目錄來解決此問題,每個目錄都有自己的檔案和分支,同時共享相同的儲存庫歷史記錄和遠端連接。這意味著您可以讓 Claude 在一個 worktree 中處理功能,同時在另一個 worktree 中修復錯誤,而不會相互干擾。

670 

671使用 `--worktree`(`-w`)標誌建立隔離的 worktree 並在其中啟動 Claude。您傳遞的值成為 worktree 目錄名稱和分支名稱:

672 

673```bash theme={null}

674# 在名為「feature-auth」的 worktree 中啟動 Claude

675# 建立 .claude/worktrees/feature-auth/ 和新分支

676claude --worktree feature-auth

677 

678# 在單獨的 worktree 中啟動另一個會話

679claude --worktree bugfix-123

680```

681 

682如果您省略名稱,Claude 會自動產生一個隨機名稱:

683 

684```bash theme={null}

685# 自動產生名稱如「bright-running-fox」

686claude --worktree

687```

688 

689Worktrees 建立在 `<repo>/.claude/worktrees/<name>` 並從預設遠端分支分支。worktree 分支命名為 `worktree-<name>`。

690 

691預設遠端分支不可通過 Claude Code 標誌或設定配置。`origin/HEAD` 是儲存在您本地 `.git` 目錄中的參考,Git 在您複製時設定一次。如果儲存庫的預設分支稍後在 GitHub 或 GitLab 上變更,您的本地 `origin/HEAD` 會繼續指向舊的,worktrees 將從那裡分支。要重新同步您的本地參考與遠端目前認為的預設值:

692 

693```bash theme={null}

694git remote set-head origin -a

695```

696 

697這是一個標準 Git 命令,只更新您的本地 `.git` 目錄。遠端伺服器上沒有任何變更。如果您想 worktrees 基於特定分支而不是遠端的預設值,請使用 `git remote set-head origin your-branch-name` 明確設定它。

698 

699為了完全控制 worktrees 的建立方式,包括為每次調用選擇不同的基礎,配置 [WorktreeCreate hook](/zh-TW/hooks#worktreecreate)。該 hook 完全取代 Claude Code 的預設 `git worktree` 邏輯,所以您可以從任何您需要的 ref 中取得和分支。

700 

701您也可以在會話期間要求 Claude「在 worktree 中工作」或「啟動 worktree」,它會自動建立一個。

702 

703### Subagent worktrees

704 

705Subagents 也可以使用 worktree 隔離來並行工作而不會衝突。要求 Claude「為您的代理使用 worktrees」或在[自訂 subagent](/zh-TW/sub-agents#supported-frontmatter-fields) 中配置它,方法是在代理的 frontmatter 中新增 `isolation: worktree`。每個 subagent 都獲得自己的 worktree,在 subagent 完成而沒有變更時自動清理。

706 

707### Worktree 清理

708 

709當您退出 worktree 會話時,Claude 根據您是否進行了變更來處理清理:

710 

711* **無變更**:worktree 及其分支會自動移除

712* **存在變更或提交**:Claude 提示您保留或移除 worktree。保留會保留目錄和分支,以便您稍後返回。移除會刪除 worktree 目錄及其分支,丟棄所有未提交的變更和提交

713 

714Subagent worktrees 由於崩潰或中斷的平行執行而孤立的,一旦它們超過您的 [`cleanupPeriodDays`](/zh-TW/settings#available-settings) 設定,就會在啟動時自動移除,前提是它們沒有未提交的變更、沒有未追蹤的檔案且沒有未推送的提交。使用 `--worktree` 建立的 Worktrees 永遠不會被此掃描移除。

715 

716要在 Claude 會話外清理 worktrees,請使用[手動 worktree 管理](#manage-worktrees-manually)。

717 

718<Tip>

719 將 `.claude/worktrees/` 新增到您的 `.gitignore` 以防止 worktree 內容在主儲存庫中顯示為未追蹤的檔案。

720</Tip>

721 

722### 複製 gitignored 檔案到 worktrees

723 

724Git worktrees 是新鮮的簽出,所以它們不包含來自主儲存庫的未追蹤檔案,如 `.env` 或 `.env.local`。要在 Claude 建立 worktree 時自動複製這些檔案,請在專案根目錄新增 `.worktreeinclude` 檔案。

725 

726該檔案使用 `.gitignore` 語法列出要複製的檔案。只有符合模式且也被 gitignored 的檔案才會被複製,所以追蹤的檔案永遠不會被複製。

727 

728```text .worktreeinclude theme={null}

729.env

730.env.local

731config/secrets.json

732```

733 

734這適用於使用 `--worktree` 建立的 worktrees、subagent worktrees 和[桌面應用](/zh-TW/desktop#work-in-parallel-with-sessions)中的平行會話。

735 

736### 手動管理 worktrees

737 

738為了更好地控制 worktree 位置和分支配置,直接使用 Git 建立 worktrees。當您需要簽出特定現有分支或將 worktree 放在儲存庫外時,這很有用。

739 

740```bash theme={null}

741# 使用新分支建立 worktree

742git worktree add ../project-feature-a -b feature-a

743 

744# 使用現有分支建立 worktree

745git worktree add ../project-bugfix bugfix-123

746 

747# 在 worktree 中啟動 Claude

748cd ../project-feature-a && claude

749 

750# 完成時清理

751git worktree list

752git worktree remove ../project-feature-a

753```

754 

755在[官方 Git worktree 文件](https://git-scm.com/docs/git-worktree)中了解更多。

756 

757<Tip>

758 記住根據您的專案設定在每個新 worktree 中初始化您的開發環境。根據您的堆疊,這可能包括執行依賴項安裝(`npm install`、`yarn`)、設定虛擬環境或遵循您的專案標準設定過程。

759</Tip>

760 

761### 非 git 版本控制

762 

763Worktree 隔離預設使用 git。對於其他版本控制系統(如 SVN、Perforce 或 Mercurial),配置 [WorktreeCreate 和 WorktreeRemove hooks](/zh-TW/hooks#worktreecreate) 以提供自訂 worktree 建立和清理邏輯。配置後,當您使用 `--worktree` 時,這些 hooks 會取代預設 git 行為,所以[`.worktreeinclude`](#copy-gitignored-files-to-worktrees) 不會被處理。改為在您的 hook 指令碼中複製任何本地配置檔案。

764 

765對於具有共享任務和訊息的平行會話的自動協調,請參閱[代理團隊](/zh-TW/agent-teams)。

766 

767***

768 

769## 在 Claude 需要您注意時獲得通知

770 

771當您啟動長時間執行的任務並切換到另一個視窗時,您可以設定桌面通知,以便在 Claude 完成或需要您的輸入時知道。這使用 `Notification` [hook 事件](/zh-TW/hooks-guide#get-notified-when-claude-needs-input),每當 Claude 等待權限、閒置並準備好新提示或完成身份驗證時觸發。

772 

773<Steps>

774 <Step title="將 hook 新增到您的設定">

775 開啟 `~/.claude/settings.json` 並新增一個 `Notification` hook,該 hook 呼叫您平台的原生通知命令:

776 

777 <Tabs>

778 <Tab title="macOS">

779 ```json theme={null}

780 {

781 "hooks": {

782 "Notification": [

783 {

784 "matcher": "",

785 "hooks": [

786 {

787 "type": "command",

788 "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"

789 }

790 ]

791 }

792 ]

793 }

794 }

795 ```

796 </Tab>

797 

798 <Tab title="Linux">

799 ```json theme={null}

800 {

801 "hooks": {

802 "Notification": [

803 {

804 "matcher": "",

805 "hooks": [

806 {

807 "type": "command",

808 "command": "notify-send 'Claude Code' 'Claude Code needs your attention'"

809 }

810 ]

811 }

812 ]

813 }

814 }

815 ```

816 </Tab>

817 

818 <Tab title="Windows">

819 ```json theme={null}

820 {

821 "hooks": {

822 "Notification": [

823 {

824 "matcher": "",

825 "hooks": [

826 {

827 "type": "command",

828 "command": "powershell.exe -Command \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')\""

829 }

830 ]

831 }

832 ]

833 }

834 }

835 ```

836 </Tab>

837 </Tabs>

838 

839 如果您的設定檔已有 `hooks` 鍵,請將 `Notification` 項目合併到其中,而不是覆蓋。您也可以通過在 CLI 中描述您想要的內容來要求 Claude 為您編寫 hook。

840 </Step>

841 

842 <Step title="可選地縮小匹配器範圍">

843 預設情況下,hook 在所有通知類型上觸發。要僅針對特定事件觸發,請將 `matcher` 欄位設定為以下值之一:

844 

845 | 匹配器 | 觸發時機 |

846 | :--------------------- | :------------------ |

847 | `permission_prompt` | Claude 需要您批准工具使用 |

848 | `idle_prompt` | Claude 完成並等待您的下一個提示 |

849 | `auth_success` | 身份驗證完成 |

850 | `elicitation_dialog` | MCP 伺服器開啟引發表單 |

851 | `elicitation_complete` | MCP 引發表單已提交或關閉 |

852 | `elicitation_response` | MCP 引發回應已傳送回伺服器 |

853 </Step>

854 

855 <Step title="驗證 hook">

856 輸入 `/hooks` 並選擇 `Notification` 以確認 hook 出現。選擇它會顯示將執行的命令。要端到端測試它,要求 Claude 執行需要權限的命令並切換離開終端,或要求 Claude 直接觸發通知。

857 </Step>

858</Steps>

859 

860如需完整的事件架構和通知類型,請參閱[通知參考](/zh-TW/hooks#notification)。

861 

862***

863 

864## 將 Claude 用作 unix 風格的實用程式

865 

866### 將 Claude 新增到您的驗證過程

867 

868假設您想將 Claude Code 用作 linter 或程式碼審查者。

869 

870**將 Claude 新增到您的建置指令碼:**

871 

872```json theme={null}

873// package.json

874{

875 ...

876 "scripts": {

877 ...

878 "lint:claude": "claude -p 'you are a linter. please look at the changes vs. main and report any issues related to typos. report the filename and line number on one line, and a description of the issue on the second line. do not return any other text.'"

879 }

880}

881```

882 

883<Tip>

884 提示:

885 

886 * 在您的 CI/CD 管道中使用 Claude 進行自動程式碼審查

887 * 自訂提示以檢查與您的專案相關的特定問題

888 * 考慮為不同類型的驗證建立多個指令碼

889</Tip>

890 

891### 管道進入、管道輸出

892 

893假設您想將資料管道輸入 Claude,並以結構化格式取回資料。

894 

895**通過 Claude 管道資料:**

896 

897```bash theme={null}

898cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt

899```

900 

901<Tip>

902 提示:

903 

904 * 使用管道將 Claude 整合到現有 shell 指令碼中

905 * 與其他 Unix 工具結合以實現強大的工作流程

906 * 考慮使用 `--output-format` 以獲得結構化輸出

907</Tip>

908 

909### 控制輸出格式

910 

911假設您需要 Claude 的輸出採用特定格式,特別是在將 Claude Code 整合到指令碼或其他工具時。

912 

913<Steps>

914 <Step title="使用文字格式(預設)">

915 ```bash theme={null}

916 cat data.txt | claude -p 'summarize this data' --output-format text > summary.txt

917 ```

918 

919 這只輸出 Claude 的純文字回應(預設行為)。

920 </Step>

921 

922 <Step title="使用 JSON 格式">

923 ```bash theme={null}

924 cat code.py | claude -p 'analyze this code for bugs' --output-format json > analysis.json

925 ```

926 

927 這輸出包含中繼資料(包括成本和持續時間)的訊息的 JSON 陣列。

928 </Step>

929 

930 <Step title="使用串流 JSON 格式">

931 ```bash theme={null}

932 cat log.txt | claude -p 'parse this log file for errors' --output-format stream-json

933 ```

934 

935 這在 Claude 處理請求時實時輸出一系列 JSON 物件。每個訊息都是有效的 JSON 物件,但如果連接,整個輸出不是有效的 JSON。

936 </Step>

937</Steps>

938 

939<Tip>

940 提示:

941 

942 * 對於簡單整合(您只需要 Claude 的回應),使用 `--output-format text`

943 * 當您需要完整的對話日誌時,使用 `--output-format json`

944 * 對於每個對話輪次的實時輸出,使用 `--output-format stream-json`

945</Tip>

946 

947***

948 

949## 在排程上執行 Claude

950 

951假設您想讓 Claude 自動定期處理任務,例如每天早上檢查開放 PR、每週審計依賴項或在夜間檢查 CI 失敗。

952 

953根據您想讓任務執行的位置選擇排程選項:

954 

955| 選項 | 執行位置 | 最適合 |

956| :--------------------------------------- | :---------------- | :------------------------------------------------------------------------------------------------------------- |

957| [Routines](/zh-TW/routines) | Anthropic 管理的基礎設施 | 應該在您的電腦關閉時執行的任務。也可以由 API 呼叫或 GitHub 事件觸發,除了排程。在 [claude.ai/code/routines](https://claude.ai/code/routines) 配置。 |

958| [桌面排程任務](/zh-TW/desktop-scheduled-tasks) | 您的機器,通過桌面應用 | 需要直接存取本地檔案、工具或未提交變更的任務。 |

959| [GitHub Actions](/zh-TW/github-actions) | 您的 CI 管道 | 與儲存庫事件(如開啟的 PR)相關的任務,或應與工作流程配置一起存在的 cron 排程。 |

960| [`/loop`](/zh-TW/scheduled-tasks) | 當前 CLI 會話 | 會話開啟時的快速輪詢。任務在您開始新對話時停止;`--resume` 和 `--continue` 恢復未過期的任務。 |

961 

962<Tip>

963 為排程任務編寫提示時,明確說明成功是什麼樣子以及如何處理結果。任務自主執行,所以它無法提出澄清問題。例如:'檢查標記為 `needs-review` 的開放 PR,對任何問題留下內聯評論,並在 `#eng-reviews` Slack 頻道中發佈摘要。'

964</Tip>

965 

966***

967 

968## 詢問 Claude 其功能

969 

970Claude 內建存取其文件,可以回答有關其自身功能和限制的問題。

971 

972### 範例問題

973 

974```text theme={null}

975can Claude Code create pull requests?

976```

977 

978```text theme={null}

979how does Claude Code handle permissions?

980```

981 

982```text theme={null}

983what skills are available?

984```

985 

986```text theme={null}

987how do I use MCP with Claude Code?

988```

989 

990```text theme={null}

991how do I configure Claude Code for Amazon Bedrock?

992```

993 

994```text theme={null}

995what are the limitations of Claude Code?

996```

997 

998<Note>

999 Claude 根據文件提供對這些問題的答案。如需可執行的範例和實踐演示,請執行 `/powerup` 以取得具有動畫演示的互動式課程,或參閱上面的特定工作流程部分。

1000</Note>

1001 

1002<Tip>

1003 提示:

1004 

1005 * Claude 始終可以存取最新的 Claude Code 文件,無論您使用的版本如何

1006 * 提出具體問題以獲得詳細答案

1007 * Claude 可以解釋複雜的功能,如 MCP 整合、企業配置和進階工作流程

1008</Tip>

1009 

1010***

1011 

1012## 後續步驟

1013 

1014<CardGroup cols={2}>

1015 <Card title="最佳實踐" icon="lightbulb" href="/zh-TW/best-practices">

1016 從 Claude Code 中獲得最大收益的模式

1017 </Card>

1018 

1019 <Card title="Claude Code 如何運作" icon="gear" href="/zh-TW/how-claude-code-works">

1020 了解代理迴圈和背景資訊管理

1021 </Card>

1022 

1023 <Card title="擴展 Claude Code" icon="puzzle-piece" href="/zh-TW/features-overview">

1024 新增 skills、hooks、MCP、subagents 和外掛

1025 </Card>

1026 

1027 <Card title="參考實現" icon="code" href="https://github.com/anthropics/claude-code/tree/main/.devcontainer">

1028 複製開發容器參考實現

1029 </Card>

1030</CardGroup>

communications-kit.md +443 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 通訊工具包

6 

7> 推出公告、滴灌式行銷訊息和常見問題解答,用於在您的工程組織中推出 Claude Code。

8 

9本頁面適用於在團隊中推出 Claude Code 的管理員和工程主管。它提供了可直接使用的推出公告、提示和技巧滴灌式行銷活動,以及針對您最常被問到的問題的單行常見問題解答。

10 

11<Note>

12 將此處的所有內容視為草稿副本,而非最終副本。用您組織的語氣重寫每條訊息,用您自己程式碼庫中的實際錯誤和模組替換示例任務,並在發送前替換 `[括號中的佔位符]`。推動採用的公告是那些看起來像您公司某人寫的公告。

13</Note>

14 

15## 推出通訊

16 

17一份公告分為兩種格式,加上兩個可選變體。選擇最適合您推出的格式,然後從那裡開始重寫。

18 

19### 發送前

20 

21在公告發出前,請完成此檢查清單。每一項都會關閉一個差距,否則會變成推出當天的支援討論串。

22 

23| 項目 | 為什麼重要 |

24| ------------------------------------------------- | -------------------------------------- |

25| `#claude-code` 頻道已建立並在訊息中連結 | 讓問題有一個集中的地方 |

26| 在您環境中至少一台機器上測試過安裝命令 | 在所有人同時遇到代理或防火牆問題之前捕捉它們 |

27| 安全和資料處理連結已準備好([資料使用](/zh-TW/data-usage) 或您的內部等效項) | "我的程式碼去哪裡了?" 將是第一個回覆 |

28| 已選擇一個具體的首個任務,您程式碼庫中的實際錯誤或檔案 | 通用示例不會轉換;"修復 `auth_test.go` 中的不穩定測試" 會 |

29| 為前 48 小時指定的頻道擁有者 | 未回答的推出當天問題會扼殺動力 |

30| 已安排一位 C 級主管贊助者發送或共同簽署公告 | 由高管發送的推出在第一週採用率上始終比由管理員或工具團隊發送的要高 |

31 

32### 公告

33 

34將此用作您的標準組織範圍推出訊息。它涵蓋了 Claude Code 是什麼,提供了兩分鐘的安裝路徑,為讀者提供了一個具體的任務來嘗試,並在任何人必須提出問題之前回答了 "我的程式碼去哪裡了?"。

35 

36<Tabs>

37 <Tab title="電子郵件">

38 ```text theme={null}

39 主旨:Claude Code 現已為 [工程部門 / 您的團隊] 推出

40 

41 團隊,

42 

43 從今天開始,您可以存取 Claude Code,這是一個在您的終端中執行、讀取您的實際程式碼庫並端到端完成實際任務的 AI 編碼代理:除錯、重構、測試、PR。它不是自動完成,也不是聊天視窗。它編輯檔案、執行您的命令,並在任何風險操作前請求許可。

44 

45 在兩分鐘內開始執行:

46 

47 curl -fsSL https://claude.ai/install.sh | bash

48 cd <your-repo>

49 claude

50 

51 然後執行一次 /init。Claude 讀取您的專案並寫入一個 CLAUDE.md,其中包含您的建置命令和約定,因此您不再需要重新解釋基礎知識。

52 

53 然後在您已經在的儲存庫上嘗試以下其中之一:

54 

55 - "檔案 [file] 中的測試不穩定。找出原因並修復它"

56 - "向我介紹 [module] 如何處理 [X]"

57 - "查看我的工作差異並告訴我在我推送前什麼是風險的"

58 

59 您的程式碼去哪裡了:Claude Code 在您的終端中執行,並直接與 Anthropic 的 API 通訊,迴路中沒有第三方伺服器。它在編輯檔案或執行命令前請求許可。根據我們的企業協議,Anthropic 不使用您的程式碼或提示來訓練其模型。

60 詳情:https://code.claude.com/docs/en/data-usage

61 https://code.claude.com/docs/en/security

62 

63 有問題去哪裡:#claude-code。[擁有者名稱] 本週正在監視它。

64 

65 - [名稱]

66 

67 P.S. 更喜歡您的編輯器?有一個 VS Code 擴充功能和一個 JetBrains 外掛。相同的代理,不需要終端。

68 ```

69 </Tab>

70 

71 <Tab title="Slack 或 Teams">

72 ```markdown theme={null}

73 🚀 *Claude Code 現已為 [團隊] 推出*

74 

75 AI 編碼代理,在您的終端中執行,讀取您的儲存庫,完成實際工作:

76 錯誤、重構、測試、PR。在觸及任何東西前請求許可。

77 

78 `curl -fsSL https://claude.ai/install.sh | bash` → `cd your-repo` → `claude`

79 

80 *首先要嘗試的* → 執行 `/init`,然後:"檔案 [file] 中的測試不穩定,

81 找出原因並修復它。"

82 

83 🔒 在您的終端中執行,僅與 Anthropic 的 API 通訊。根據我們的

84 企業計畫,您的程式碼和提示不用於訓練模型。

85 資料使用 → https://code.claude.com/docs/en/data-usage

86 

87 📚 快速入門 · VS Code · 免費 1 小時課程

88 https://code.claude.com/docs/en/quickstart

89 https://code.claude.com/docs/en/vs-code

90 https://anthropic.skilljar.com/claude-code-in-action

91 

92 問題 → 此討論串。[擁有者] 正在負責。

93 ```

94 </Tab>

95</Tabs>

96 

97### 執行贊助商變體

98 

99從您的贊助執行官(如 CTO、CIO 或 SVP 工程)發送此訊息,使用他們的名字和帳戶。由高管名義發出的推出在開啟率和第一週啟用速度上始終比來自管理員或工具團隊的相同訊息要高。它表示公司優先事項,而不是可選實驗。

100 

101此版本故意精簡為一個要求:安裝它並在一個實際任務上執行它。高管的工作是讓要求落實;標準公告和 `#claude-code` 處理方式。

102 

103<Tabs>

104 <Tab title="電子郵件">

105 ```text theme={null}

106 主旨:我希望每位工程師本週嘗試的一件事

107 

108 團隊,

109 

110 我們已為所有工程部門開啟了 Claude Code。它是一個直接在您的終端中、在您的實際程式碼庫上工作的 AI 代理,已經使用它的團隊的早期結果足夠強勁,我希望本週每個人都使用它。

111 

112 我要求十分鐘:

113 

114 curl -fsSL https://claude.ai/install.sh | bash

115 cd <your-repo>

116 claude

117 

118 然後給它一個實際任務:您一直在推遲的錯誤,或 "向我介紹 [module] 如何工作"。

119 

120 這就是全部要求。[擁有者名稱] 和團隊在 #claude-code 中處理您遇到的任何問題。

121 

122 - [執行官名稱]

123 [職位]

124 ```

125 </Tab>

126 

127 <Tab title="Slack 或 Teams">

128 ```markdown theme={null}

129 📣 *來自 [執行官名稱]:本週要嘗試的一件事*

130 

131 我們已為所有工程部門開啟了 *Claude Code*。早期結果足夠強勁,我要求每個人本週在實際工作上給它十分鐘。

132 

133 `curl -fsSL https://claude.ai/install.sh | bash` → `cd your-repo` →

134 `claude` → 給它一個實際任務。

135 

136 就這樣。問題 → #claude-code。

137 ```

138 </Tab>

139</Tabs>

140 

141### 試點小組變體

142 

143用於分階段推出。僅發送給試點隊列。

144 

145```text theme={null}

146主旨:您在 Claude Code 試點中

147 

148[名稱 / 團隊],

149 

150您是 [公司] Claude Code 的第一波。我們選擇了這個小組,因為您會在實際問題上使用它,並告訴我們關於它的真實情況。

151 

152要求:本週至少在一個實際任務上使用它,然後在 #claude-code-pilot 中留下一條筆記,涵蓋什麼有效、什麼令人煩惱以及什麼讓您驚訝。該反饋決定了我們如何向其他人推出。

153 

154[繼續標準公告中的 "在兩分鐘內開始執行"]

155 

156試點的一個額外事項:在您的第一個多檔案變更時,按 Shift+Tab

157直到您看到 "plan"。Claude 將在觸及任何檔案前準確說明它打算做什麼。這是校準您應該信任多少的最快方式。

158```

159 

160### 冠軍招募直訊

161 

162推出後,直訊在 `#claude-code` 中最活躍的兩三個人。

163 

164```text theme={null}

165嘿 [名稱],您的 #claude-code 貼文對採用的推動比我的公告做得更多。幾個人告訴我您的 [討論串 / 螢幕截圖]

166是他們實際嘗試它的原因。

167 

168想讓這成為半官方的嗎?低投入:主要是繼續發佈您正在發佈的內容,加上新功能的首先嘗試和與 Anthropic 團隊的直接聯繫。如果您有興趣,我可以分享一個簡短的遊戲手冊。

169```

170 

171## 提示和技巧行銷活動

172 

173設計用於在推出後推動功能啟用的現成 Slack 或 Teams 訊息。每個都遵循相同的模式:一個鉤子、收益、一個 "現在嘗試" 提示和一個文件連結。在 `#claude-code` 中每週滴灌一兩個,或選擇與您團隊差距相符的少數幾個。它們獨立存在,沒有必需的順序。

174 

175直接從每個區塊複製訊息正文到 Slack 或 Teams。在發送前替換 `[括號中的佔位符]`。

176 

177### 開始使用

178 

179**選擇正確的模型**

180 

181```markdown theme={null}

182🎯 *提示:將模型與時刻相匹配*

183 

184使用 Opus 修復打字錯誤會浪費計算。使用 Haiku 進行 12 檔案重構

185是要求重做。

186 

187Claude Code 在與 Claude 應用相同的模型上執行,您可以在會話中間切換。*Sonnet* 是日常功能工作、錯誤、測試和審查的預設主力。在大型重構、複雜除錯或任何高風險的事情上使用 *Opus*。對於快速問題、格式化和速度獲勝的機械編輯,降低到 *Haiku*。

188 

189*現在嘗試:* 輸入 `/model` 並選擇 Sonnet(如果您還沒有的話)。它是大多數任務的正確預設。

190 

191📖 模型配置 → https://code.claude.com/docs/en/model-config

192```

193 

194| 模型 | 最適合 |

195| ------ | ----------------------------- |

196| Opus | 大規模重構、複雜除錯、架構決策、高風險變更 |

197| Sonnet | 日常功能工作、錯誤修復、測試、文件、程式碼審查。建議預設。 |

198| Haiku | 快速問題、格式化、機械編輯、快速迭代 |

199 

200**首先嘗試的快速勝利**

201 

202```markdown theme={null}

203🚀 *提示:在您的前 10 分鐘內嘗試的三件事*

204 

205已安裝 Claude Code 但不確定實際要求什麼?從一直困擾您整週的東西開始。

206 

207 - 修復令人煩惱的東西:"檔案 [file] 中的測試不穩定,找出原因"

208 - 在您沒有寫的程式碼中定位:"向我介紹 [module] 如何工作"

209 - 在您推送前進行理智檢查:"查看我的工作差異並告訴我什麼看起來風險"

210 

211這些都不需要設定。只需 `cd` 進入您的儲存庫並執行 `claude`。

212 

213*現在嘗試:* 選擇您一直在迴避的錯誤並貼上錯誤訊息。

214 

215📖 快速入門 → https://code.claude.com/docs/en/quickstart

216```

217 

218### 專案記憶

219 

220**`/init` 和 CLAUDE.md**

221 

222```markdown theme={null}

223📁 *提示:停止每個會話重新解釋您的儲存庫*

224 

225第五次告訴 Claude "我們使用 pnpm,而不是 npm"?有一個一次性修復。

226 

227每個儲存庫執行一次 `/init`。Claude 讀取您的專案結構並寫入一個 CLAUDE.md 檔案,其中包含您的建置命令、架構和約定。該儲存庫中的每個未來會話都會自動從此檔案開始。將其保持在兩個螢幕以下。它是一個速查表,而不是文件。

228 

229*現在嘗試:* 開啟您的主儲存庫,執行 `claude`,輸入 `/init`。三十秒,在之後的每個會話中都有回報。

230 

231📖 CLAUDE.md 和專案記憶 → https://code.claude.com/docs/en/memory

232```

233 

234**@-參考**

235 

236```markdown theme={null}

237📎 *提示:停止將檔案內容貼到聊天中*

238 

239複製一個元件的 200 行到您的提示中,以便 Claude 可以 "看到" 它?您不必這樣做。

240 

241輸入 `@` 然後是檔案路徑。Claude 直接將檔案拉入上下文。也適用於整個目錄。

242 

243> @src/components/Button.tsx 中的樣式看起來不對,根據 @docs/design-system.md 檢查

244 

245*現在嘗試:* 輸入 `@` 然後 Tab。自動完成顯示您可以到達的每個檔案。

246 

247📖 參考檔案 → https://code.claude.com/docs/en/common-workflows

248```

249 

250### 控制和安全

251 

252**許可模式**

253 

254```markdown theme={null}

255🛡️ *提示:一個按鍵在 "查看但不觸及" 和 "就做吧" 之間*

256 

257有時您希望 Claude 在每次編輯前請求許可。有時您只是希望它發貨。您不應該永遠選擇一個。

258 

259*Shift+Tab* 循環通過 Claude 獲得多少自由度:*default* 在風險操作前請求,*acceptEdits* 讓檔案編輯和常見檔案系統命令流通,同時仍在其他 shell 命令前檢查,*plan* 在觸及任何東西前為您的批准提議變更。Plan 模式是信任建立者,因此對於觸及多個檔案的任何事情,從那裡開始。

260 

261*現在嘗試:* 在您的下一個重構上,按 Shift+Tab 直到您看到 "plan",

262然後描述變更。您將在單個檔案移動前獲得完整提案。

263 

264📖 許可模式 → https://code.claude.com/docs/en/permissions

265```

266 

267**檢查點和 `/rewind`**

268 

269```markdown theme={null}

270⏪ *提示:整個對話有一個撤銷按鈕*

271 

272Claude 三個回合前走錯了路,現在您正在解開它?您不必向前修復。

273 

274`/rewind` 回滾到對話中的較早點,包括 Claude 沿途所做的檔案變更。檢查點是自動的;您不需要設定任何東西。

275 

276*現在嘗試:* 按 *Esc* 兩次以開啟倒帶菜單,或輸入 `/rewind`。

277選擇事情變得不對勁之前的點。

278 

279📖 檢查點 → https://code.claude.com/docs/en/checkpointing

280```

281 

282### 連接您的工具

283 

284**MCP 連接器**

285 

286```markdown theme={null}

287🔌 *提示:讓 Claude 讀取您的問題追蹤器,這樣您就不必貼票證*

288 

289將 Jira 票證複製貼到終端感覺像是向後退一步。確實如此。

290 

291一個配置檔案(您的專案根目錄中的 `.mcp.json`)將 Claude 連接到 GitHub、Jira、Linear 或您使用的任何追蹤器。然後 "什麼是分配給我的最高優先級問題?" 和 "繼續修復它" 在同一對話中發生。

292 

293*現在嘗試:* 要求 Claude "在此儲存庫中為 [GitHub/Jira/Linear] 設定 MCP 連接器"。它將為您寫入配置。

294 

295📖 MCP 連接器 → https://code.claude.com/docs/en/mcp

296```

297 

298### 自動化您的工作流程

299 

300**Skills**

301 

302```markdown theme={null}

303⚡ *提示:將您一直重新輸入的提示變成命令*

304 

305本週三次輸入 "從 git log 總結我今天所做的工作,為站立會議格式化"?那是一個等待發生的斜杠命令。

306 

307`.claude/skills/<name>/` 中的 SKILL.md 檔案變成可重用提示;輸入 `/name` 來執行它。在您輸入您之前輸入過的多步驟提示的第二次時製作一個。最簡單的路徑:要求 Claude 為您製作它。

308 

309*現在嘗試:* 輸入 "為我製作一個 /standup skill,從 git log 總結我今天所做的工作",然後明天早上執行 `/standup`。

310 

311📖 Skills → https://code.claude.com/docs/en/skills

312```

313 

314**Hooks**

315 

316```markdown theme={null}

317🔔 *提示:當您的重構完成時收到通知*

318 

319坐在您的辦公桌前看著 Claude 完成一個長任務?您有更好的事情要做那八分鐘。

320 

321Hooks 是在 Claude Code 事件上觸發的 shell 命令。一個發送桌面通知的 Stop hook 意味著您可以啟動一個長重構、走開,並在完成時立即收到通知。

322 

323*現在嘗試:* 要求 Claude "新增一個 Stop hook,當您完成時發送桌面通知"。它將寫入指令碼並連接它。

324 

325📖 Hooks 指南 → https://code.claude.com/docs/en/hooks-guide

326```

327 

328### 日常開發

329 

330**螢幕截圖和圖像**

331 

332```markdown theme={null}

333📸 *提示:停止描述錯誤對話框。只需顯示它。*

334 

335輸出 "有一個紅色框說一些關於空參考的東西,它指向第 47 行左右"?螢幕截圖它。

336 

337直接將螢幕截圖拖到終端中,Claude 看到它:錯誤對話框、UI 模型、白板照片、Figma 匯出。*Ctrl+V* 從剪貼板貼上(在 macOS 上也使用 Ctrl+V,而不是 Cmd+V)。

338 

339*現在嘗試:* 下次視覺上出現問題時,螢幕截圖它並直接貼到提示中。然後只需輸入 "這裡出了什麼問題?"

340 

341📖 使用圖像 → https://code.claude.com/docs/en/common-workflows

342```

343 

344**Git 工作流程**

345 

346```markdown theme={null}

347🌿 *提示:交接整個 git 儀式*

348 

349修復花了 5 分鐘。提交訊息、分支和 PR 描述花了 15 分鐘。該比率是錯誤的。

350 

351Claude 處理完整的 git 流程:具有常規訊息的提交、分支、具有適當摘要的 PR。一個要求:"修復偏差一,使用常規提交訊息提交,並開啟 PR。" 審查別人的工作?貼上 PR URL 並要求 Claude 向您介紹差異。

352 

353*現在嘗試:* 在您的下一個修復後,而不是切換到您的 git 客戶端,

354只需輸入 "用好訊息提交此內容並開啟 PR"。

355 

356📖 建立拉取請求 → https://code.claude.com/docs/en/common-workflows

357```

358 

359### 分享和擴展

360 

361**Plugins**

362 

363```markdown theme={null}

364📦 *提示:有人可能已經建立了該 skill*

365 

366即將花一小時建立 `/deploy` 命令?檢查它是否已經存在。

367 

368Skills 被捆綁並作為外掛共享。`/plugin` 瀏覽可用的內容並在一個步驟中安裝。五分鐘的瀏覽可以節省一小時的建立。

369 

370*現在嘗試:* 輸入 `/plugin` 並滾動瀏覽。您會找到至少一件您不知道自己想要的東西。

371 

372📖 Plugins → https://code.claude.com/docs/en/plugins

373```

374 

375### 安全和管理

376 

377**安全架構**

378 

379```markdown theme={null}

380🔐 *提示:下次被問到時 "這安全嗎?" 的答案*

381 

382您團隊中的某個人會問 "等等,我的程式碼去哪裡了?"

383這是您可以貼上的簡短版本。

384 

385許可優先設計。每個檔案編輯、shell 命令和外部呼叫都由您的批准控制。CLI 在您的終端中執行,直接與 Anthropic 的 API 通訊,沒有第三方伺服器,並支援 shell 命令的可選作業系統級沙箱。根據我們的企業計畫,Anthropic 不使用您的程式碼或提示來訓練其模型。

386 

387*現在嘗試:* 保存這兩個連結,以備下次問題出現時使用。

388它們回答了大多數安全審查問題。

389 

390📖 https://code.claude.com/docs/en/security

391📖 https://code.claude.com/docs/en/data-usage

392```

393 

394**最佳實踐**

395 

396```markdown theme={null}

397✅ *提示:將 "嘗試過一次" 與 "每天使用" 分開的 4 個習慣*

398 

399大多數從 Claude Code 反彈的人跳過了其中之一。大多數堅持的人在第一週完成了全部四個。

400 

401 - 對於觸及多個檔案的任何事情,在 plan 模式中開始

402 - 早期執行 /init;上下文複合

403 - 在提交前審查差異;Claude 可以自信地出錯

404 - 驗證觸及關鍵路徑的變更;將其視為銳利的初級,而不是預言家

405 

406*現在嘗試:* 如果您只做了其中一兩個,選擇您缺少的那個並在您的下一個任務上執行它。在 #claude-code 中發佈發生了什麼變化。

407 

408📖 最佳實踐 → https://code.claude.com/docs/en/best-practices

409```

410 

411## 快速參考

412 

413### 常見問題解答回應

414 

415針對您最常被問到的問題的單行回覆。

416 

417| 問題 | 回應 |

418| ------------------- | -------------------------------------------------------------------------------------------------------- |

419| "它在 VS Code 中工作嗎?" | 是的。有一個 VS Code 擴充功能和一個 JetBrains 外掛,具有相同的功能,嵌入在您的編輯器中。[VS Code →](/zh-TW/vs-code) |

420| "我必須先配置什麼嗎?" | 不。安裝,然後在任何儲存庫中執行 `claude`。執行一次 `/init`,您就設定好了。[快速入門 →](/zh-TW/quickstart) |

421| "我的程式碼去哪裡了?" | CLI 在您的終端中執行,並將上下文發送到 Anthropic 的 API 進行推理,沒有第三方伺服器。根據您的企業計畫,您的程式碼和提示不用於訓練模型。[資料使用 →](/zh-TW/data-usage) |

422| "它能看到我的整個儲存庫嗎?" | 它讀取您給它存取權限的內容。您工作目錄內的檔案讀取不提示;許可提示控制編輯、shell 命令和該目錄外的任何東西。[許可 →](/zh-TW/permissions) |

423| "這與 Copilot 有什麼不同?" | Copilot 自動完成行。Claude Code 是一個讀取檔案、執行命令和進行多檔案編輯的代理。[概述 →](/zh-TW/overview) |

424| "我應該首先嘗試什麼?" | 您一直在推遲的錯誤,因為它很乏味。"檔案 \[file] 中的測試不穩定,找出原因。" [快速入門 →](/zh-TW/quickstart) |

425 

426### 提示範本

427 

428與已安裝但不確定要求什麼的工程師分享這些入門提示。每一個都以它在實際會話中輸入的方式措辭;用您自己儲存庫中的檔案替換括號中的部分。

429 

430| 任務 | 提示 |

431| -------- | -------------------------------------------- |

432| 修復錯誤 | "檔案 \[file] 中的測試失敗,找出原因並修復它" |

433| 理解程式碼 | "向我介紹 \[module] 如何工作,然後告訴我進入點在哪裡" |

434| 安全重構 | "重構 \[module] 到 \[goal],使用 plan 模式,以便我可以先審查" |

435| 寫測試 | "為 \[file] 寫測試,涵蓋 \[scenario] 周圍的邊界情況" |

436| 提交前審查 | "查看我的工作差異並告訴我什麼看起來風險" |

437| 開啟 PR | "修復 \[issue],寫一個常規提交,並用摘要開啟 PR" |

438| 製作 skill | "為我製作一個 /ship skill,在提交前執行測試和 lint" |

439| 除錯堆棧追蹤 | "這是堆棧追蹤,找到根本原因,不要只是掩蓋它" |

440 

441<Tip>

442 Claude Code 頻繁發貨。在內部分發前,根據 [文件首頁](/zh-TW/overview) 驗證版本特定詳情。

443</Tip>

computer-use.md +206 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 讓 Claude 從 CLI 使用您的電腦

6 

7> 在 Claude Code CLI 中啟用 computer use,讓 Claude 可以在 macOS 上開啟應用程式、點擊、輸入和查看您的螢幕。測試原生應用程式、除錯視覺問題,以及自動化僅限 GUI 的工具,無需離開您的終端機。

8 

9<Note>

10 {/* plan-availability: feature=computer-use plans=pro,max */}

11 

12 Computer use 是 macOS 上的研究預覽版本,需要 Pro 或 Max 方案。Team 或 Enterprise 方案不提供此功能。它需要 Claude Code v2.1.85 或更新版本以及互動式工作階段,因此在使用 `-p` 旗標的非互動式模式中不可用。

13</Note>

14 

15Computer use 讓 Claude 可以開啟應用程式、控制您的螢幕,並以您的方式在您的機器上工作。從 CLI,Claude 可以編譯 Swift 應用程式、啟動它、點擊每個按鈕,並擷取結果的螢幕截圖,所有這些都在編寫程式碼的同一個對話中進行。

16 

17本頁涵蓋 computer use 在 CLI 中的運作方式。如需 Desktop 應用程式,請參閱 [Desktop 中的 computer use](/zh-TW/desktop#let-claude-use-your-computer)。

18 

19## 您可以使用 computer use 做什麼

20 

21Computer use 處理需要 GUI 的任務:任何您通常必須離開終端機並手動執行的操作。

22 

23* **建置和驗證原生應用程式**:要求 Claude 建置 macOS 選單列應用程式。Claude 編寫 Swift、編譯它、啟動它,並點擊每個控制項以驗證它在您開啟之前是否有效。

24* **端對端 UI 測試**:將 Claude 指向本機 Electron 應用程式並說「測試上線流程」。Claude 開啟應用程式、點擊註冊,並擷取每個步驟的螢幕截圖。無需 Playwright 設定、無需測試工具。

25* **除錯視覺和版面配置問題**:告訴 Claude「模態視窗在小視窗上被裁剪」。Claude 調整視窗大小、重現錯誤、擷取螢幕截圖、修補 CSS,並驗證修復。Claude 看到您看到的內容。

26* **驅動僅限 GUI 的工具**:與設計工具、硬體控制面板、iOS 模擬器或沒有 CLI 或 API 的專有應用程式互動。

27 

28## Computer use 何時適用

29 

30Claude 有多種方式與應用程式或服務互動。Computer use 是最廣泛和最慢的,因此 Claude 首先嘗試最精確的工具:

31 

32* 如果您有該服務的 [MCP server](/zh-TW/mcp),Claude 會使用它。

33* 如果任務是 shell 命令,Claude 會使用 Bash。

34* 如果任務是瀏覽器工作且您已設定 [Claude in Chrome](/zh-TW/chrome),Claude 會使用它。

35* 如果以上都不適用,Claude 會使用 computer use。

36 

37螢幕控制保留用於其他工具無法到達的事物:原生應用程式、模擬器和沒有 API 的工具。

38 

39## 啟用 computer use

40 

41Computer use 可作為稱為 `computer-use` 的內建 MCP server 使用。預設情況下它是關閉的,直到您啟用它。

42 

43<Steps>

44 <Step title="開啟 MCP 選單">

45 在互動式 Claude Code 工作階段中,執行:

46 

47 ```text theme={null}

48 /mcp

49 ```

50 

51 在伺服器清單中找到 `computer-use`。它顯示為已停用。

52 </Step>

53 

54 <Step title="啟用伺服器">

55 選擇 `computer-use` 並選擇**啟用**。該設定按專案保留,因此您只需為每個想要 computer use 的專案執行一次。

56 </Step>

57 

58 <Step title="授予 macOS 權限">

59 Claude 第一次嘗試使用您的電腦時,您會看到授予兩個 macOS 權限的提示:

60 

61 * **Accessibility**:讓 Claude 點擊、輸入和捲動

62 * **Screen Recording**:讓 Claude 看到您螢幕上的內容

63 

64 提示包含開啟相關系統設定窗格的連結。授予兩者,然後在提示中選擇**重試**。授予螢幕錄製權限後,macOS 可能需要您重新啟動 Claude Code。

65 </Step>

66</Steps>

67 

68設定後,要求 Claude 執行需要 GUI 的操作:

69 

70```text theme={null}

71建置應用程式目標、啟動它,並點擊每個標籤以確保

72沒有任何內容崩潰。擷取您找到的任何錯誤狀態的螢幕截圖。

73```

74 

75## 按工作階段核准應用程式

76 

77啟用 `computer-use` 伺服器不會授予 Claude 存取您機器上每個應用程式的權限。Claude 在工作階段中第一次需要特定應用程式時,您的終端機中會出現提示,顯示:

78 

79* Claude 想要控制哪些應用程式

80* 任何額外的權限請求,例如剪貼簿存取

81* Claude 工作時將隱藏多少其他應用程式

82 

83選擇**允許此工作階段**或**拒絕**。核准持續到目前工作階段。當 Claude 同時請求多個應用程式時,您可以一次核准多個應用程式。

84 

85具有廣泛影響的應用程式在提示中顯示額外警告,讓您知道核准它們會授予什麼:

86 

87| 警告 | 適用於 |

88| :----------- | :-------------------------------------- |

89| 等同於 shell 存取 | Terminal、iTerm、VS Code、Warp 和其他終端機和 IDE |

90| 可以讀取或寫入任何檔案 | Finder |

91| 可以變更系統設定 | System Settings |

92 

93這些應用程式不會被封鎖。警告讓您決定任務是否值得該級別的存取。

94 

95Claude 的控制級別也因應用程式類別而異:瀏覽器和交易平台是僅檢視,終端機和 IDE 是僅點擊,其他所有內容都獲得完全控制。請參閱 [Desktop 中的應用程式權限](/zh-TW/desktop#app-permissions)以取得完整的層級細目。

96 

97## Claude 如何在您的螢幕上工作

98 

99了解流程有助於您預期 Claude 將執行的操作以及如何進行干預。

100 

101### 一次一個工作階段

102 

103Computer use 在活動時持有機器範圍的鎖定。如果另一個 Claude Code 工作階段已在使用您的電腦,新的嘗試會失敗,並顯示一條訊息,告訴您哪個工作階段持有鎖定。先完成或退出該工作階段。

104 

105### Claude 工作時應用程式被隱藏

106 

107當 Claude 開始控制您的螢幕時,其他可見的應用程式會被隱藏,以便 Claude 只與已核准的應用程式互動。您的終端機視窗保持可見並從螢幕截圖中排除,因此您可以觀看工作階段,Claude 永遠看不到自己的輸出。

108 

109當 Claude 完成該輪次時,隱藏的應用程式會自動恢復。

110 

111### 隨時停止

112 

113當 Claude 獲得鎖定時,會出現 macOS 通知:「Claude 正在使用您的電腦 · 按 Esc 停止」。在任何地方按 `Esc` 立即中止目前操作,或在終端機中按 `Ctrl+C`。無論哪種方式,Claude 都會釋放鎖定、取消隱藏您的應用程式,並將控制權返回給您。

114 

115Claude 完成時會出現第二個通知。

116 

117## 安全性和信任邊界

118 

119<Warning>

120 與 [沙箱化 Bash 工具](/zh-TW/sandboxing)不同,computer use 在您的實際桌面上執行,可以存取您核准的應用程式。Claude 檢查每個操作並標記來自螢幕上內容的潛在提示注入,但信任邊界是不同的。請參閱 [computer use 安全指南](https://support.claude.com/en/articles/14128542)以了解最佳實踐。

121</Warning>

122 

123內建護欄在不需要設定的情況下降低風險:

124 

125* **按應用程式核准**:Claude 只能控制您在目前工作階段中已核准的應用程式。

126* **哨兵警告**:授予 shell、檔案系統或系統設定存取的應用程式在您核准之前會被標記。

127* **終端機從螢幕截圖中排除**:Claude 永遠看不到您的終端機視窗,因此您工作階段中的螢幕上提示無法反饋到模型中。

128* **全域逃脫**:`Esc` 鍵可以從任何地方中止 computer use,並且按鍵被消耗,因此提示注入無法使用它來關閉對話框。

129* **鎖定檔案**:一次只有一個工作階段可以控制您的機器。

130 

131## 範例工作流程

132 

133這些範例顯示將 computer use 與編碼任務結合的常見方式。

134 

135### 驗證原生建置

136 

137對 macOS 或 iOS 應用程式進行變更後,讓 Claude 在一次通過中編譯和驗證:

138 

139```text theme={null}

140建置 MenuBarStats 目標、啟動它、開啟偏好設定視窗,

141並驗證間隔滑塊更新標籤。完成後擷取偏好設定視窗的螢幕截圖。

142```

143 

144Claude 執行 `xcodebuild`、啟動應用程式、與 UI 互動,並報告它發現的內容。

145 

146### 重現版面配置錯誤

147 

148當視覺錯誤僅在特定視窗大小出現時,讓 Claude 找到它:

149 

150```text theme={null}

151設定模態視窗在狹窄視窗上裁剪其頁尾。調整應用程式

152視窗大小直到您可以重現它、擷取裁剪狀態的螢幕截圖,

153然後檢查模態容器的 CSS。

154```

155 

156Claude 調整視窗大小、擷取損壞的狀態,並讀取相關的樣式表。

157 

158### 測試模擬器流程

159 

160無需編寫 XCTest 即可驅動 iOS 模擬器:

161 

162```text theme={null}

163開啟 iOS 模擬器、啟動應用程式、點擊上線螢幕,

164並告訴我是否有任何螢幕花費超過一秒鐘的時間來載入。

165```

166 

167Claude 以您使用滑鼠的方式控制模擬器。

168 

169## 與 Desktop 應用程式的差異

170 

171CLI 和 Desktop 表面共享相同的 computer use 引擎。一些 Desktop 特定的控制項在 CLI 中還不可用:

172 

173| 功能 | Desktop | CLI |

174| :---------- | :----------------------------------- | :-------------------------- |

175| 啟用 | **設定 > 一般**中的切換(在 **Desktop 應用程式**下) | 在 `/mcp` 中啟用 `computer-use` |

176| 拒絕的應用程式清單 | 可在設定中設定 | 尚不可用 |

177| 自動取消隱藏切換 | 可選 | 始終開啟 |

178| Dispatch 整合 | Dispatch 生成的工作階段可以使用 computer use | 不適用 |

179 

180## 疑難排解

181 

182### 「Computer use 正在被另一個 Claude 工作階段使用」

183 

184另一個 Claude Code 工作階段持有鎖定。完成該工作階段中的任務或退出它。如果另一個工作階段崩潰,當 Claude 偵測到該程序不再執行時,鎖定會自動釋放。

185 

186### macOS 權限提示不斷重新出現

187 

188授予螢幕錄製權限後,macOS 有時需要重新啟動請求程序。完全退出 Claude Code 並啟動新工作階段。如果提示仍然存在,開啟**系統設定 > 隱私與安全 > 螢幕錄製**並確認您的終端機應用程式已列出並啟用。

189 

190### `computer-use` 未出現在 `/mcp` 中

191 

192伺服器僅在符合條件的設定上出現。檢查:

193 

194* 您在 macOS 上。Computer use 在 Linux 或 Windows 上不可用。

195* 您執行的是 Claude Code v2.1.85 或更新版本。執行 `claude --version` 以檢查。

196* 您在 Pro 或 Max 方案上。執行 `/status` 以確認您的訂閱。

197* 您透過 claude.ai 進行身份驗證。Computer use 不適用於 Amazon Bedrock、Google Cloud Vertex AI 或 Microsoft Foundry 等第三方提供者。如果您完全透過第三方提供者存取 Claude,您需要單獨的 claude.ai 帳戶才能使用此功能。

198* 您在互動式工作階段中。Computer use 在使用 `-p` 旗標的非互動式模式中不可用。

199 

200## 另請參閱

201 

202* [Desktop 中的 Computer use](/zh-TW/desktop#let-claude-use-your-computer):具有圖形設定頁面的相同功能

203* [Claude in Chrome](/zh-TW/chrome):用於基於網路的任務的瀏覽器自動化

204* [MCP](/zh-TW/mcp):將 Claude 連接到結構化工具和 API

205* [Sandboxing](/zh-TW/sandboxing):Claude 的 Bash 工具如何隔離檔案系統和網路存取

206* [Computer use 安全指南](https://support.claude.com/en/articles/14128542):安全 computer use 的最佳實踐

costs.md +203 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 有效管理成本

6 

7> 追蹤 token 使用情況、設定團隊支出限制,並透過上下文管理、模型選擇、延伸思考設定和預處理 hooks 來降低 Claude Code 成本。

8 

9Claude Code 按 API token 消耗量計費。如需訂閱計畫定價(Pro、Max、Team、Enterprise),請參閱 [claude.com/pricing](https://claude.com/pricing)。每位開發人員的成本差異很大,取決於模型選擇、程式碼庫大小和使用模式,例如執行多個執行個體或自動化。

10 

11在企業部署中,平均成本約為每位開發人員每個活躍日 $13,每位開發人員每月 $150-250,90% 的使用者成本保持在每個活躍日 \$30 以下。若要估計您自己團隊的支出,請從小型試點群組開始,並使用下面的追蹤工具建立基準,然後再進行更廣泛的推出。

12 

13本頁涵蓋如何[追蹤您的成本](#track-your-costs)、[管理團隊成本](#managing-costs-for-teams)和[減少 token 使用](#reduce-token-usage)。

14 

15## 追蹤您的成本

16 

17### 使用 `/usage` 命令

18 

19<Note>

20 `/usage` 中的 Session 區塊顯示 API token 使用情況,適用於 API 使用者。Claude Max 和 Pro 訂閱者的使用情況已包含在其訂閱中,因此工作階段成本數字與計費無關。訂閱者會在同一畫面上看到計畫使用情況列和活動統計資訊。

21</Note>

22 

23`/usage` 命令為您目前的工作階段提供詳細的 token 使用統計資訊。美元數字是根據 token 計數在本地計算的估計值,可能與您的實際帳單不同。如需權威計費資訊,請參閱 [Claude Console](https://platform.claude.com/usage) 中的「使用情況」頁面。

24 

25```text theme={null}

26Total cost: $0.55

27Total duration (API): 6m 19.7s

28Total duration (wall): 6h 33m 10.2s

29Total code changes: 0 lines added, 0 lines removed

30```

31 

32## 管理團隊成本

33 

34使用 Claude API 時,您可以在 Claude Code 工作區支出上[設定工作區支出限制](https://platform.claude.com/docs/zh-TW/build-with-claude/workspaces#workspace-limits)。管理員可以在 Console 中[檢視成本和使用情況報告](https://platform.claude.com/docs/zh-TW/build-with-claude/workspaces#usage-and-cost-tracking)。

35 

36<Note>

37 當您首次使用 Claude Console 帳戶驗證 Claude Code 時,系統會自動為您建立一個名為「Claude Code」的工作區。此工作區為您的組織中所有 Claude Code 使用情況提供集中式成本追蹤和管理。您無法為此工作區建立 API 金鑰;它專門用於 Claude Code 驗證和使用。

38 

39 對於具有自訂速率限制的組織,此工作區中的 Claude Code 流量計入您的組織整體 API 速率限制。您可以在 Claude Console 的此工作區的「限制」頁面上設定[工作區速率限制](https://platform.claude.com/docs/zh-TW/api/rate-limits#setting-lower-limits-for-workspaces),以限制 Claude Code 的份額並保護其他生產工作負載。

40</Note>

41 

42在 Bedrock、Vertex 和 Foundry 上,Claude Code 不會從您的雲端傳送指標。若要取得成本指標,多家大型企業報告使用[LiteLLM](/zh-TW/llm-gateway#litellm-configuration),這是一個開源工具,可幫助公司[按金鑰追蹤支出](https://docs.litellm.ai/docs/proxy/virtual_keys#tracking-spend)。此專案與 Anthropic 無關,且尚未進行安全審計。

43 

44### 速率限制建議

45 

46為團隊設定 Claude Code 時,請根據您的組織規模考慮這些每位使用者的 Token Per Minute (TPM) 和 Request Per Minute (RPM) 建議:

47 

48| 團隊規模 | 每位使用者 TPM | 每位使用者 RPM |

49| ------------ | --------- | --------- |

50| 1-5 位使用者 | 200k-300k | 5-7 |

51| 5-20 位使用者 | 100k-150k | 2.5-3.5 |

52| 20-50 位使用者 | 50k-75k | 1.25-1.75 |

53| 50-100 位使用者 | 25k-35k | 0.62-0.87 |

54| 100-500 位使用者 | 15k-20k | 0.37-0.47 |

55| 500+ 位使用者 | 10k-15k | 0.25-0.35 |

56 

57例如,如果您有 200 位使用者,您可能會為每位使用者請求 20k TPM,或總共 400 萬 TPM (200\*20,000 = 400 萬)。

58 

59隨著團隊規模增長,每位使用者的 TPM 會減少,因為在較大的組織中,傾向於較少的使用者同時使用 Claude Code。這些速率限制適用於組織層級,而不是每個個別使用者,這意味著當其他人未主動使用該服務時,個別使用者可以暫時消耗超過其計算份額的資源。

60 

61<Note>

62 如果您預期會出現異常高的並行使用情況(例如與大型群組進行的即時培訓課程),您可能需要更高的每位使用者 TPM 配置。

63</Note>

64 

65### Agent 團隊 token 成本

66 

67[Agent 團隊](/zh-TW/agent-teams)會產生多個 Claude Code 執行個體,每個都有自己的上下文視窗。Token 使用量會隨著活躍隊友數量和每個隊友執行時間的長短而擴展。

68 

69為了保持 agent 團隊成本可控:

70 

71* 為隊友使用 Sonnet。它為協調任務平衡了功能和成本。

72* 保持團隊規模小。每位隊友執行自己的上下文視窗,因此 token 使用量大致與團隊規模成正比。

73* 保持產生提示的焦點。隊友會自動載入 CLAUDE.md、MCP 伺服器和 skills,但產生提示中的所有內容都會從一開始就新增到其上下文中。

74* 工作完成時清理團隊。活躍的隊友即使閒置也會繼續消耗 token。

75* Agent 團隊預設為停用。在您的[settings.json](/zh-TW/settings)或環境中設定 `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` 以啟用它們。請參閱[啟用 agent 團隊](/zh-TW/agent-teams#enable-agent-teams)。

76 

77## 減少 token 使用

78 

79Token 成本隨上下文大小而擴展:Claude 處理的上下文越多,您使用的 token 就越多。Claude Code 透過 prompt caching(減少重複內容(如系統提示)的成本)和 auto-compact(在接近上下文限制時總結對話歷史記錄)自動優化成本。

80 

81以下策略可幫助您保持上下文較小並降低每條訊息的成本。

82 

83### 主動管理上下文

84 

85使用 `/usage` 檢查您目前的 token 使用情況,或[設定您的狀態行](/zh-TW/statusline#context-window-usage)以持續顯示它。

86 

87* **在任務之間清除**:切換到不相關的工作時,使用 `/clear` 重新開始。過時的上下文會在後續的每條訊息上浪費 token。在清除之前使用 `/rename` 以便稍後輕鬆找到工作階段,然後使用 `/resume` 返回到它。

88* **新增自訂壓縮指示**:`/compact Focus on code samples and API usage` 告訴 Claude 在總結期間要保留什麼。

89 

90您也可以在 CLAUDE.md 中自訂壓縮行為:

91 

92```markdown theme={null}

93# Compact instructions

94 

95When you are using compact, please focus on test output and code changes

96```

97 

98### 選擇正確的模型

99 

100Sonnet 能很好地處理大多數編碼任務,成本低於 Opus。為複雜的架構決策或多步驟推理保留 Opus。使用 `/model` 在工作階段中途切換模型,或在 `/config` 中設定預設值。對於簡單的 subagent 任務,在您的[subagent 設定](/zh-TW/sub-agents#choose-a-model)中指定 `model: haiku`。

101 

102### 減少 MCP 伺服器開銷

103 

104MCP 工具定義[預設為延遲](/zh-TW/mcp#scale-with-mcp-tool-search),因此只有工具名稱進入上下文,直到 Claude 使用特定工具。執行 `/context` 以查看消耗空間的內容。

105 

106* **在可用時偏好 CLI 工具**:`gh`、`aws`、`gcloud` 和 `sentry-cli` 等工具比 MCP 伺服器更具上下文效率,因為它們不會新增任何每個工具的列表。Claude 可以直接執行 CLI 命令。

107* **停用未使用的伺服器**:執行 `/mcp` 以查看已設定的伺服器,並停用任何您未主動使用的伺服器。

108 

109### 為型別化語言安裝程式碼智慧外掛

110 

111[程式碼智慧外掛](/zh-TW/discover-plugins#code-intelligence)為 Claude 提供精確的符號導航,而不是基於文字的搜尋,在探索不熟悉的程式碼時減少不必要的檔案讀取。單一「前往定義」呼叫取代了可能需要的 grep 後跟讀取多個候選檔案。已安裝的語言伺服器也會在編輯後自動報告型別錯誤,因此 Claude 無需執行編譯器即可捕捉錯誤。

112 

113### 將處理卸載到 hooks 和 skills

114 

115自訂[hooks](/zh-TW/hooks)可以在 Claude 看到資料之前對其進行預處理。Claude 不是讀取 10,000 行日誌檔案來尋找錯誤,hook 可以 grep `ERROR` 並僅返回匹配的行,將上下文從數萬個 token 減少到數百個。

116 

117[skill](/zh-TW/skills)可以為 Claude 提供領域知識,因此它不必進行探索。例如,「codebase-overview」skill 可以描述您的專案架構、關鍵目錄和命名慣例。當 Claude 呼叫該 skill 時,它會立即獲得此上下文,而不是花費 token 讀取多個檔案來理解結構。

118 

119例如,此 PreToolUse hook 篩選測試輸出以僅顯示失敗:

120 

121<Tabs>

122 <Tab title="settings.json">

123 將此新增到您的[settings.json](/zh-TW/settings#settings-files)以在每個 Bash 命令之前執行 hook:

124 

125 ```json theme={null}

126 {

127 "hooks": {

128 "PreToolUse": [

129 {

130 "matcher": "Bash",

131 "hooks": [

132 {

133 "type": "command",

134 "command": "~/.claude/hooks/filter-test-output.sh"

135 }

136 ]

137 }

138 ]

139 }

140 }

141 ```

142 </Tab>

143 

144 <Tab title="filter-test-output.sh">

145 hook 呼叫此指令碼,該指令碼檢查命令是否為測試執行器並修改它以僅顯示失敗:

146 

147 ```bash theme={null}

148 #!/bin/bash

149 input=$(cat)

150 cmd=$(echo "$input" | jq -r '.tool_input.command')

151 

152 # If running tests, filter to show only failures

153 if [[ "$cmd" =~ ^(npm test|pytest|go test) ]]; then

154 filtered_cmd="$cmd 2>&1 | grep -A 5 -E '(FAIL|ERROR|error:)' | head -100"

155 echo "{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"allow\",\"updatedInput\":{\"command\":\"$filtered_cmd\"}}}"

156 else

157 echo "{}"

158 fi

159 ```

160 </Tab>

161</Tabs>

162 

163### 將指示從 CLAUDE.md 移至 skills

164 

165您的[CLAUDE.md](/zh-TW/memory)檔案在工作階段開始時載入到上下文中。如果它包含特定工作流程的詳細指示(例如 PR 審查或資料庫遷移),即使您在進行不相關的工作時,這些 token 也會存在。[Skills](/zh-TW/skills)僅在呼叫時按需載入,因此將專門指示移至 skills 可以保持您的基本上下文較小。目標是透過僅包含必要內容來將 CLAUDE.md 保持在 200 行以下。

166 

167### 調整延伸思考

168 

169延伸思考預設為啟用,因為它可以顯著改善複雜規劃和推理任務的效能。思考 token 會作為輸出 token 計費,預設預算可能是每個請求數萬個 token,取決於模型。對於不需要深度推理的較簡單任務,您可以透過在 `/effort` 中降低[努力等級](/zh-TW/model-config#adjust-effort-level)或在 `/model` 中降低、在 `/config` 中停用思考或降低預算(例如,`MAX_THINKING_TOKENS=8000`)來降低成本。

170 

171### 將詳細操作委派給 subagents

172 

173執行測試、擷取文件或處理日誌檔案可能會消耗大量上下文。將這些委派給[subagents](/zh-TW/sub-agents#isolate-high-volume-operations),以便詳細輸出保留在 subagent 的上下文中,而只有摘要返回到您的主要對話。

174 

175### 管理 agent 團隊成本

176 

177當隊友在 plan mode 中執行時,Agent 團隊使用的 token 大約是標準工作階段的 7 倍,因為每位隊友維護自己的上下文視窗並作為單獨的 Claude 執行個體執行。保持團隊任務小且自成一體,以限制每位隊友的 token 使用。有關詳細資訊,請參閱[agent 團隊](/zh-TW/agent-teams)。

178 

179### 撰寫具體提示

180 

181模糊的請求(例如「改進此程式碼庫」)會觸發廣泛掃描。具體的請求(例如「在 auth.ts 中的登入函式中新增輸入驗證」)讓 Claude 能夠以最少的檔案讀取高效地工作。

182 

183### 有效處理複雜任務

184 

185對於較長或更複雜的工作,這些習慣有助於避免因走錯方向而浪費的 token:

186 

187* **對複雜任務使用 plan mode**:按 Shift+Tab 進入[plan mode](/zh-TW/common-workflows#use-plan-mode-for-safe-code-analysis),然後再進行實施。Claude 探索程式碼庫並提出一個方法供您批准,防止當初始方向錯誤時進行昂貴的返工。

188* **及早糾正方向**:如果 Claude 開始朝著錯誤的方向前進,按 Escape 立即停止。使用 `/rewind` 或雙擊 Escape 將對話和程式碼恢復到先前的 checkpoint。

189* **提供驗證目標**:在您的提示中包含測試案例、貼上螢幕截圖或定義預期輸出。當 Claude 可以驗證自己的工作時,它會在您需要請求修復之前捕捉問題。

190* **增量測試**:寫一個檔案、測試它,然後繼續。這會在問題便宜時及早捕捉問題。

191 

192## 背景 token 使用

193 

194Claude Code 即使在閒置時也會為某些背景功能使用 token:

195 

196* **對話總結**:為 `claude --resume` 功能總結先前對話的背景工作

197* **命令處理**:某些命令(例如 `/usage`)可能會產生檢查狀態的請求

198 

199這些背景程序即使沒有主動互動也會消耗少量 token(通常每個工作階段不到 \$0.04)。

200 

201## 瞭解 Claude Code 行為的變化

202 

203Claude Code 定期接收可能改變功能工作方式的更新,包括成本報告。執行 `claude --version` 以檢查您目前的版本。如有具體計費問題,請透過您的[Console 帳戶](https://platform.claude.com/login)聯絡 Anthropic 支援。

data-usage.md +124 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 資料使用

6 

7> 了解 Anthropic 對 Claude 資料使用政策

8 

9## 資料政策

10 

11### 資料訓練政策

12 

13**消費者使用者(免費、Pro 和 Max 方案)**:

14我們讓您可以選擇是否允許您的資料用於改進未來的 Claude 模型。當此設定開啟時,我們將使用來自免費、Pro 和 Max 帳戶的資料來訓練新模型(包括當您從這些帳戶使用 Claude Code 時)。

15 

16**商業使用者**:(Team 和 Enterprise 方案、API、第三方平台和 Claude Gov)維持現有政策:除非客戶選擇向我們提供資料以改進模型(例如,[開發者合作夥伴計畫](https://support.claude.com/en/articles/11174108-about-the-development-partner-program)),否則 Anthropic 不會在商業條款下使用發送至 Claude Code 的程式碼或提示來訓練生成模型。

17 

18### 開發者合作夥伴計畫

19 

20如果您明確選擇加入向我們提供訓練材料的方法,例如透過[開發者合作夥伴計畫](https://support.claude.com/en/articles/11174108-about-the-development-partner-program),我們可能會使用所提供的材料來訓練我們的模型。組織管理員可以明確選擇為其組織加入開發者合作夥伴計畫。請注意,此計畫僅適用於 Anthropic 第一方 API,不適用於 Bedrock 或 Vertex 使用者。

21 

22### 使用 `/feedback` 命令的回饋

23 

24如果您選擇使用 `/feedback` 命令向我們發送有關 Claude Code 的回饋,我們可能會使用您的回饋來改進我們的產品和服務。透過 `/feedback` 共享的文字記錄會保留 5 年。

25 

26### 工作階段品質調查

27 

28當您在 Claude Code 中看到「Claude 在此工作階段中表現如何?」提示時,回應此調查(包括選擇「關閉」),只會記錄您的評分。我們不會作為此評分提示本身的一部分收集或儲存任何對話文字記錄、輸入、輸出或其他工作階段資料。與豎起大拇指/向下大拇指回饋或 `/feedback` 報告不同,此工作階段品質調查是一個簡單的產品滿意度指標。

29 

30在評分提示之後,您可能會看到一個單獨的後續提問「Anthropic 可以查看您的工作階段文字記錄以幫助我們改進 Claude Code 嗎?」。這是一個與評分不同的可選第二步:

31 

32* **是**:將您的對話文字記錄、任何子代理文字記錄和磁碟中的原始工作階段日誌檔案上傳至 Anthropic。已知的 API 金鑰和權杖模式在上傳前會被編輯。原始程式碼、檔案內容和其他對話內容會按原樣上傳。共享的文字記錄會保留最多 6 個月。

33* **否**:拒絕而不發送任何內容

34* **不再詢問**:拒絕並停止此後續提問在未來工作階段中出現

35 

36除非您明確選擇**是**,否則不會上傳任何內容。具有[零資料保留](/zh-TW/zero-data-retention)的組織,或組織政策停用產品回饋的組織,永遠不會看到此後續提問。您對此調查的回應(包括評分提示後提交的工作階段文字記錄)不會影響您的資料訓練偏好設定,也不能用於訓練我們的 AI 模型。

37 

38若要停用這些調查,請設定 `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1`。當設定 `DISABLE_TELEMETRY` 或 `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` 時,調查也會停用。若要控制頻率而不是停用,請在您的設定檔中設定 [`feedbackSurveyRate`](/zh-TW/settings#available-settings) 為 `0` 到 `1` 之間的機率。

39 

40### 資料保留

41 

42Anthropic 根據您的帳戶類型和偏好設定保留 Claude Code 資料。

43 

44**消費者使用者(免費、Pro 和 Max 方案)**:

45 

46* 允許資料用於模型改進的使用者:5 年保留期,以支持模型開發和安全改進

47* 不允許資料用於模型改進的使用者:30 天保留期

48* 隱私設定可以隨時在 [claude.ai/settings/data-privacy-controls](https://claude.ai/settings/data-privacy-controls) 變更。

49 

50**商業使用者(Team、Enterprise 和 API)**:

51 

52* 標準:30 天保留期

53* [零資料保留](/zh-TW/zero-data-retention):適用於 Claude for Enterprise 上的 Claude Code。ZDR 按組織啟用;每個新組織必須由您的帳戶團隊單獨啟用 ZDR

54* 本機快取:Claude Code 用戶端在 `~/.claude/projects/` 下以純文字形式本機儲存工作階段文字記錄,預設為 30 天,以啟用工作階段繼續。使用 `cleanupPeriodDays` 調整期間。請參閱[應用程式資料](/zh-TW/claude-directory#application-data)以了解儲存的內容以及如何清除。

55 

56您可以隨時刪除網路上的個別 Claude Code 工作階段。刪除工作階段會永久移除工作階段的事件資料。如需有關如何刪除工作階段的說明,請參閱[刪除工作階段](/zh-TW/claude-code-on-the-web#delete-sessions)。

57 

58在我們的[隱私中心](https://privacy.anthropic.com/)了解更多有關資料保留實踐的資訊。

59 

60如需完整詳細資訊,請查閱我們的[商業服務條款](https://www.anthropic.com/legal/commercial-terms)(適用於 Team、Enterprise 和 API 使用者)或[消費者條款](https://www.anthropic.com/legal/consumer-terms)(適用於免費、Pro 和 Max 使用者)和[隱私政策](https://www.anthropic.com/legal/privacy)。

61 

62## 資料存取

63 

64對於所有第一方使用者,您可以了解更多有關為[本機 Claude Code](#local-claude-code-data-flow-and-dependencies) 和[遠端 Claude Code](#cloud-execution-data-flow-and-dependencies) 記錄的資料。[遠端控制](/zh-TW/remote-control)工作階段遵循本機資料流,因為所有執行都在您的機器上進行。請注意,對於遠端 Claude Code,Claude 會存取您啟動 Claude Code 工作階段的儲存庫。Claude 不會存取您已連接但尚未在其中啟動工作階段的儲存庫。

65 

66## 本機 Claude Code:資料流和相依性

67 

68下圖顯示 Claude Code 在安裝和正常操作期間如何連接到外部服務。實線表示必需的連接,而虛線表示可選或使用者啟動的資料流。

69 

70<img src="https://mintcdn.com/claude-code/YcBW2H7CArGcduPb/images/claude-code-data-flow.svg?fit=max&auto=format&n=YcBW2H7CArGcduPb&q=85&s=b600a89f84fc86f9ff7be00a466c0635" alt="顯示 Claude Code 外部連接的圖表:安裝/更新連接到發佈伺服器,使用者請求連接到 Anthropic 服務,包括 Console 驗證、public-api,以及可選的 Statsig、Sentry 和錯誤報告" width="720" height="520" data-path="images/claude-code-data-flow.svg" />

71 

72Claude Code 在本機執行。為了與 LLM 互動,Claude Code 透過網路發送資料。此資料包括所有使用者提示和模型輸出,在傳輸中透過 TLS 1.2+ 加密。Claude Code 與大多數流行的 VPN 和 LLM 代理相容。

73 

74靜止時的加密取決於您的模型提供者:

75 

76| 提供者 | 靜止時加密 |

77| ---------------------- | --------------------------------------------------------------------- |

78| Anthropic API | 基礎設施層級磁碟加密 (AES-256)。啟用[零資料保留](/zh-TW/zero-data-retention)以避免伺服器端持久化。 |

79| Amazon Bedrock | AES-256 搭配 AWS 管理的金鑰。客戶管理的金鑰可透過 AWS KMS 取得。 |

80| Google Cloud Vertex AI | Google 管理的加密金鑰。CMEK 可用。 |

81| Microsoft Foundry | 請求路由到 Anthropic 基礎設施,具有 AES-256 磁碟加密。 |

82 

83Claude Code 建立在 Anthropic 的 API 上。有關 API 安全控制的詳細資訊,包括 API 記錄程序,請參閱 [Anthropic 信任中心](https://trust.anthropic.com)中的合規性文件。

84 

85### 雲端執行:資料流和相依性

86 

87使用[網路上的 Claude Code](/zh-TW/claude-code-on-the-web)時,工作階段在 Anthropic 管理的虛擬機器中執行,而不是在本機執行。在雲端環境中:

88 

89* \*\*程式碼和資料儲存:\*\*您的儲存庫被複製到隔離的 VM。程式碼和工作階段資料受您帳戶類型的保留和使用政策約束(請參閱上面的資料保留部分)

90* \*\*認證:\*\*GitHub 驗證透過安全代理進行;您的 GitHub 認證永遠不會進入沙箱

91* \*\*網路流量:\*\*所有出站流量都透過安全代理進行,用於稽核記錄和濫用防止

92* \*\*工作階段資料:\*\*提示、程式碼變更和輸出遵循與本機 Claude Code 使用相同的資料政策

93 

94有關雲端執行的安全詳細資訊,請參閱[安全性](/zh-TW/security#cloud-execution-security)。

95 

96## 遙測服務

97 

98Claude Code 從使用者的機器連接到 Statsig 服務,以記錄延遲、可靠性和使用模式等操作指標。此記錄不包括任何程式碼或檔案路徑。資料在傳輸中使用 TLS 加密,在靜止時使用 256 位 AES 加密。在 [Statsig 安全文件](https://www.statsig.com/trust/security)中閱讀更多資訊。若要選擇退出 Statsig 遙測,請設定 `DISABLE_TELEMETRY` 環境變數。

99 

100Claude Code 從使用者的機器連接到 Sentry 進行操作錯誤記錄。資料在傳輸中使用 TLS 加密,在靜止時使用 256 位 AES 加密。在 [Sentry 安全文件](https://sentry.io/security/)中閱讀更多資訊。若要選擇退出錯誤記錄,請設定 `DISABLE_ERROR_REPORTING` 環境變數。

101 

102當使用者執行 `/feedback` 命令時,他們的完整對話歷史記錄(包括程式碼)的副本會發送到 Anthropic。資料在傳輸中使用 TLS 加密。可選地,在公開儲存庫中建立 GitHub 問題。若要選擇退出,請設定 `DISABLE_FEEDBACK_COMMAND` 環境變數為 `1`。

103 

104## 按 API 提供者的預設行為

105 

106根據預設,當使用 Bedrock、Vertex 或 Foundry 時,錯誤報告、遙測和錯誤報告會停用。工作階段品質調查和 WebFetch 網域安全檢查是例外,無論提供者為何都會執行。您可以透過設定 `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` 一次選擇退出所有非必要流量,包括調查。此變數不會影響 WebFetch 檢查,該檢查有其自己的選擇退出。以下是完整的預設行為:

107 

108| 服務 | Claude API | Vertex API | Bedrock API | Foundry API |

109| ------------------------------ | --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- |

110| **Statsig(指標)** | 預設開啟。<br />`DISABLE_TELEMETRY=1` 以停用。 | 預設關閉。<br />`CLAUDE_CODE_USE_VERTEX` 必須為 1。 | 預設關閉。<br />`CLAUDE_CODE_USE_BEDROCK` 必須為 1。 | 預設關閉。<br />`CLAUDE_CODE_USE_FOUNDRY` 必須為 1。 |

111| **Sentry(錯誤)** | 預設開啟。<br />`DISABLE_ERROR_REPORTING=1` 以停用。 | 預設關閉。<br />`CLAUDE_CODE_USE_VERTEX` 必須為 1。 | 預設關閉。<br />`CLAUDE_CODE_USE_BEDROCK` 必須為 1。 | 預設關閉。<br />`CLAUDE_CODE_USE_FOUNDRY` 必須為 1。 |

112| **Claude API(`/feedback` 報告)** | 預設開啟。<br />`DISABLE_FEEDBACK_COMMAND=1` 以停用。 | 預設關閉。<br />`CLAUDE_CODE_USE_VERTEX` 必須為 1。 | 預設關閉。<br />`CLAUDE_CODE_USE_BEDROCK` 必須為 1。 | 預設關閉。<br />`CLAUDE_CODE_USE_FOUNDRY` 必須為 1。 |

113| **工作階段品質調查** | 預設開啟。<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` 以停用。 | 預設開啟。<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` 以停用。 | 預設開啟。<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` 以停用。 | 預設開啟。<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` 以停用。 |

114| **WebFetch 網域安全檢查** | 預設開啟。<br />[設定](/zh-TW/settings)中的 `skipWebFetchPreflight: true` 以停用。 | 預設開啟。<br />[設定](/zh-TW/settings)中的 `skipWebFetchPreflight: true` 以停用。 | 預設開啟。<br />[設定](/zh-TW/settings)中的 `skipWebFetchPreflight: true` 以停用。 | 預設開啟。<br />[設定](/zh-TW/settings)中的 `skipWebFetchPreflight: true` 以停用。 |

115 

116所有環境變數都可以簽入 `settings.json`(請參閱[設定參考](/zh-TW/settings))。

117 

118自 v2.1.126 起,當主機平台設定 `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST` 時,Statsig 指標在 Vertex、Bedrock 和 Foundry 上預設為開啟,並遵循標準 `DISABLE_TELEMETRY` 選擇退出。Sentry 錯誤報告和 `/feedback` 報告在這些提供者上仍預設為關閉。

119 

120### WebFetch 網域安全檢查

121 

122在擷取 URL 之前,WebFetch 工具會將請求的主機名稱發送到 `api.anthropic.com`,以根據 Anthropic 維護的安全封鎖清單進行檢查。只會發送主機名稱,不會發送完整 URL、路徑或頁面內容。結果按主機名稱快取五分鐘。

123 

124無論您使用哪個模型提供者,此檢查都會執行,並且不受 `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` 影響。如果您的網路封鎖 `api.anthropic.com`,WebFetch 請求會失敗,直到您允許清單該網域或在[設定](/zh-TW/settings)中設定 `skipWebFetchPreflight: true`。停用檢查意味著 WebFetch 會嘗試擷取任何 URL,而不查詢封鎖清單,因此如果您需要限制 Claude 可以存取的網域,請將其與 [`WebFetch` 權限規則](/zh-TW/permissions#webfetch)結合。

debug-your-config.md +97 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 偵錯您的設定

6 

7> 診斷為什麼 CLAUDE.md、settings、hooks、MCP servers 或 skills 沒有生效。使用 /context、/doctor、/hooks 和 /mcp 查看實際載入的內容。

8 

9當 Claude 忽略您的指令或您設定的功能沒有出現時,通常是因為檔案沒有載入、從您預期以外的位置載入,或被另一個檔案覆蓋。本指南展示如何檢查 Claude Code 實際載入的內容,以便您縮小範圍。

10 

11如需安裝、驗證和連線問題的協助,請改為參閱 [Troubleshooting](/zh-TW/troubleshoot-install)。

12 

13## 查看載入到 context 的內容

14 

15`/context` 命令顯示佔用目前工作階段 context 視窗的所有內容,按類別細分:系統提示、記憶檔案、skills、MCP tools 和對話訊息。首先執行它以確認您的 `CLAUDE.md`、規則或 skill 描述是否存在。

16 

17如需特定類別的詳細資訊,請使用專用命令進行後續操作:

18 

19| 命令 | 顯示 |

20| :------------- | :------------------------------- |

21| `/memory` | 載入了哪些 `CLAUDE.md` 和規則檔案,加上自動記憶項目 |

22| `/skills` | 來自專案、使用者和外掛程式來源的可用 skills |

23| `/agents` | 已設定的子代理及其設定 |

24| `/hooks` | 作用中的 hook 設定 |

25| `/mcp` | 已連線的 MCP servers 及其狀態 |

26| `/permissions` | 目前生效的已解析允許和拒絕規則 |

27| `/doctor` | 設定診斷:無效的鍵、schema 錯誤、安裝健康狀況 |

28| `/status` | 作用中的設定來源,包括是否啟用了受管設定 |

29 

30如果記憶檔案在 `/memory` 中遺失,請根據 [CLAUDE.md 檔案如何載入](/zh-TW/memory#how-claude-md-files-load) 檢查其位置。子目錄 `CLAUDE.md` 檔案在 Claude 使用 Read 工具讀取該目錄中的檔案時按需載入,而不是在工作階段開始時載入。

31 

32如果 `/memory` 確認檔案已載入但 Claude 仍未遵循特定指令,問題可能在於指令的編寫方式,而不是是否載入。CLAUDE.md 適用於您會給新隊友的指導類型,例如專案慣例、建置命令和檔案所在位置。

33 

34當指令模糊到可以多種方式解釋時、當兩個檔案給出衝突的方向時,或當檔案變得足夠長以至於個別規則獲得較少關注時,遵循度會下降。[編寫有效的指令](/zh-TW/memory#write-effective-instructions) 涵蓋保持遵循度高的特異性、大小和結構模式。

35 

36<Note>

37 CLAUDE.md 和 permissions 解決不同的問題。CLAUDE.md 告訴 Claude 您的專案如何運作,以便它做出良好決策。[Permissions](/zh-TW/permissions) 和 [hooks](/zh-TW/hooks) 無論 Claude 決定什麼,都會強制執行限制。使用 CLAUDE.md 表示「我們在這裡這樣做」。使用 permissions 或 hooks 表示安全邊界和任何必須永遠不會發生的事情,其中您需要保證而不是指導。

38</Note>

39 

40## 檢查已解析的設定

41 

42設定在受管、使用者、專案和本機範圍之間合併。受管設定在存在時始終優先。在其餘的設定中,較近的範圍會按本機、專案、使用者的順序覆蓋較廣的範圍。某些設定也可以由命令列旗標或 [環境變數](/zh-TW/env-vars) 設定,這些變數充當另一個覆蓋層。當設定似乎不適用時,您設定的值通常被另一個範圍或環境變數覆蓋。

43 

44執行 `/doctor` 以驗證您的設定檔案並顯示無效的鍵或 schema 錯誤。執行 `/status` 以查看哪些設定來源處於作用中,包括是否啟用了受管設定。若要瞭解給定鍵的哪個範圍優先,請參閱 [範圍如何互動](/zh-TW/settings#how-scopes-interact)。

45 

46## 檢查 MCP servers

47 

48執行 `/mcp` 以查看每個已設定的 server、其連線狀態,以及您是否已為目前專案核准它。server 可以定義正確但仍然不提供 tools,原因有幾個常見的:

49 

50* `.mcp.json` 中的專案範圍 servers 需要一次性核准。如果提示被關閉,server 將保持停用狀態,直到您從 `/mcp` 核准它。

51* 啟動失敗的 server 在 `/mcp` 中顯示為失敗。`command` 或 `args` 中的相對檔案路徑是常見原因,因為它們相對於您啟動 Claude Code 的目錄而不是 `.mcp.json` 的位置進行解析。

52* 顯示為已連線但列出零個 tools 的 server 已成功啟動但未返回 tool 清單。從 `/mcp` 選擇 **Reconnect**。如果計數保持為零,執行 `claude --debug mcp` 以查看 server 的 stderr 輸出。

53 

54如需設定位置和範圍規則,請參閱 [MCP](/zh-TW/mcp)。

55 

56## 檢查 hooks

57 

58執行 `/hooks` 以列出為目前工作階段註冊的每個 hook,按事件分組。如果您定義的 hook 沒有出現,則它未被讀取:hooks 位於設定檔案中的 `"hooks"` 鍵下,而不是在獨立檔案中。

59 

60如果 hook 出現但不觸發,通常是 matcher 的問題。`matcher` 欄位是一個使用 `|` 匹配多個 tool 名稱的單一字串,例如 `"Edit|Write"`。拼寫錯誤的 tool 名稱會無聲地失敗,因為 matcher 永遠不會匹配。陣列值是 schema 錯誤:Claude Code 顯示設定錯誤通知,`/doctor` 報告驗證失敗,hook 項目被刪除,因此不會出現在 `/hooks` 中。

61 

62對 `settings.json` 的編輯在短暫的檔案穩定延遲後在執行中的工作階段中生效。您不需要重新啟動。如果在保存後幾秒鐘 `/hooks` 仍顯示舊定義,請再次執行 `/hooks` 以重新整理檢視。

63 

64如果 `/hooks` 顯示 hook 但它仍然不觸發,下一步是即時監視 hook 評估。使用 `claude --debug hooks` 啟動工作階段並觸發 tool 呼叫。偵錯日誌記錄每個事件、檢查了哪些 matchers 以及 hook 的結束代碼和輸出。如需日誌格式,請參閱 [Debug hooks](/zh-TW/hooks#debug-hooks),如需常見失敗模式,請參閱 [hooks 疑難排解](/zh-TW/hooks-guide#limitations-and-troubleshooting)。

65 

66## 常見原因

67 

68大多數設定意外可以追溯到一小組位置和語法規則。在假設有 bug 之前檢查這些:

69 

70| 症狀 | 原因 | 修正 |

71| :---------------------------------------------- | :----------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------- |

72| Hook 永遠不觸發 | `matcher` 是 JSON 陣列而不是字串 | 使用單一字串搭配 `\|` 來匹配多個 tools,例如 `"Edit\|Write"`。請參閱 [matcher 模式](/zh-TW/hooks#matcher-patterns)。 |

73| Hook 永遠不觸發 | `matcher` 值是小寫,例如 `"bash"` | 匹配區分大小寫。Tool 名稱是大寫的:`Bash`、`Edit`、`Write`、`Read`。 |

74| Hook 永遠不觸發 | Hooks 在獨立的 `.claude/hooks.json` 檔案中 | 沒有獨立的 hooks 檔案。在 `settings.json` 中的 `"hooks"` 鍵下定義 hooks。請參閱 [hook 設定](/zh-TW/hooks)。 |

75| 全域設定的 Permissions、hooks 或 env 被忽略 | 設定已新增到 `~/.claude.json` | `~/.claude.json` 保存應用程式狀態和 UI 切換。`permissions`、`hooks` 和 `env` 屬於 `~/.claude/settings.json`。這是兩個不同的檔案。 |

76| `settings.json` 值似乎被忽略 | 相同的鍵在 `settings.local.json` 中設定 | `settings.local.json` 覆蓋 `settings.json`,兩者都覆蓋 `~/.claude/settings.json`。請參閱 [settings 優先順序](/zh-TW/settings#how-scopes-interact)。 |

77| Skill 不出現在 `/skills` 中 | Skill 檔案位於 `.claude/skills/name.md` 而不是在資料夾中 | 使用包含 `SKILL.md` 的資料夾:`.claude/skills/name/SKILL.md`。 |

78| Skill 出現在 `/skills` 中但 Claude 永遠不呼叫它 | Skill 在其 frontmatter 中有 `disable-model-invocation: true`,或其描述與您表述請求的方式不符 | 檢查 `/skills` 中的徽章:「user-only」標籤表示 Claude 不會自動觸發它。請參閱 [skill 呼叫](/zh-TW/skills)。 |

79| 子目錄 `CLAUDE.md` 指令似乎被忽略 | 子目錄檔案按需載入,而不是在工作階段開始時載入 | 它們在 Claude 使用 Read 工具讀取該目錄中的檔案時載入,而不是在啟動時,也不是在寫入或建立檔案時。請參閱 [CLAUDE.md 檔案如何載入](/zh-TW/memory#how-claude-md-files-load)。 |

80| 子代理忽略 `CLAUDE.md` 指令 | 子代理不總是繼承專案記憶 | 將關鍵規則放在代理檔案主體中,該主體成為子代理的系統提示。請參閱 [子代理設定](/zh-TW/sub-agents)。 |

81| 清理邏輯在工作階段結束時永遠不執行 | 未設定 `SessionEnd` hook | 在 `settings.json` 中新增 `SessionEnd` hook。請參閱 [hook 事件清單](/zh-TW/hooks#hook-events)。 |

82| `.mcp.json` 中的 MCP servers 永遠不載入 | 檔案位於 `.claude/` 下或使用 Claude Desktop 的設定格式 | 專案 MCP 設定位於儲存庫根目錄為 `.mcp.json`,而不是在 `.claude/` 內。請參閱 [MCP 設定](/zh-TW/mcp)。 |

83| 新增的專案 MCP server 但不出現 | 一次性核准提示被關閉 | 專案範圍 servers 需要核准。執行 `/mcp` 以查看狀態並核准。 |

84| MCP server 從某些目錄啟動失敗 | `command` 或 `args` 使用相對檔案路徑 | 對本機指令碼使用絕對路徑。您 `PATH` 上的可執行檔(如 `npx` 或 `uvx`)可以按原樣使用。 |

85| MCP server 啟動時沒有預期的環境變數 | 變數在 `settings.json` `env` 中,不會傳播到 MCP 子程序 | 改為在 `.mcp.json` 內設定每個 server 的 `env`。 |

86| `Bash(rm *)` 拒絕規則不阻止 `/bin/rm` 或 `find -delete` | 前綴規則匹配字面命令字串,而不是基礎可執行檔 | 為每個變體新增明確模式,或使用 [PreToolUse hook](/zh-TW/hooks-guide) 或 [sandbox](/zh-TW/sandboxing) 以獲得硬保證。 |

87 

88## 相關資源

89 

90如需每個設定表面的完整參考,請參閱專用頁面:

91 

92* **[`.claude` 目錄參考](/zh-TW/claude-directory)**:每個設定檔案位置及其讀取方式

93* **[Settings](/zh-TW/settings)**:優先順序和完整鍵清單

94* **[Hooks 參考](/zh-TW/hooks)**:事件名稱、承載和 `--debug hooks` 輸出格式

95* **[MCP](/zh-TW/mcp)**:server 設定、核准和 `/mcp` 輸出

96* **[Troubleshoot installation and login](/zh-TW/troubleshoot-install)**:`command not found`、PATH 和身份驗證問題

97* **[Troubleshooting](/zh-TW/troubleshooting)**:效能、掛起和搜尋問題

desktop.md +761 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 使用 Claude Code Desktop

6 

7> 充分利用 Claude Code Desktop:具有 Git 隔離的並行會話、拖放窗格佈局、整合終端機和檔案編輯器、側邊聊天、電腦使用、從您的手機 Dispatch 會話、視覺化差異檢查、應用程式預覽、PR 監控、連接器和企業配置。

8 

9Claude Desktop 應用程式有三個標籤:**Chat** 用於對話、**Cowork** 用於 [Dispatch 和更長的代理工作](https://claude.com/product/cowork),以及 **Code** 用於軟體開發。本頁面是 Code 標籤的參考。

10 

11<CardGroup cols={2}>

12 <Card title="Download for macOS" icon="apple" href="https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code&utm_medium=docs">

13 Universal build for Intel and Apple Silicon

14 </Card>

15 

16 <Card title="Download for Windows" icon="windows" href="https://claude.ai/api/desktop/win32/x64/setup/latest/redirect?utm_source=claude_code&utm_medium=docs">

17 For x64 processors

18 </Card>

19</CardGroup>

20 

21For Windows ARM64, download the [ARM64 installer](https://claude.ai/api/desktop/win32/arm64/setup/latest/redirect?utm_source=claude_code\&utm_medium=docs). The desktop app is not available on Linux; use the [CLI](/en/quickstart) instead.

22 

23安裝後,啟動 Claude,登入,然後點擊 **Code** 標籤。第一次在 Windows 上開啟時,您需要安裝 [Git for Windows](https://git-scm.com/downloads/win);安裝後請重新啟動應用程式。如需您第一個會話的逐步說明,請參閱[快速入門指南](/zh-TW/desktop-quickstart)。

24 

25在 Code 標籤中,每個對話都是一個**會話**:它有自己的聊天歷史記錄、專案資料夾和程式碼變更,獨立於任何其他會話。側邊欄列出您的會話,並讓您並行執行多個會話。在會話中,您可以:

26 

27* [使用差異檢查檢查和評論變更](#review-changes-with-diff-view),然後[透過 CI 監控產生的 PR](#monitor-pull-request-status)

28* [在嵌入式瀏覽器中預覽您執行的應用程式](#preview-your-app),同時 Claude 驗證其自己的變更

29* [排列窗格](#arrange-your-workspace),將聊天、差異、預覽、終端機和檔案編輯器並排放置

30* 提出[側邊問題](#ask-a-side-question-without-derailing-the-session),使用會話的內容而不會偏離主題

31* [連接外部工具](#connect-external-tools),例如 GitHub、Slack 和 Linear

32* 讓 Claude [開啟應用程式並控制您的螢幕](#let-claude-use-your-computer)

33* 在您的機器上、[雲端](#run-long-running-tasks-remotely)或 [SSH](#ssh-sessions) 上執行

34 

35如需[排程定期工作](/zh-TW/desktop-scheduled-tasks)、[快捷鍵](#keyboard-shortcuts)或[從您的手機傳送任務](#sessions-from-dispatch),請參閱連結的頁面和章節。如果您已經使用基於終端機的 CLI,請參閱 [CLI 比較](#coming-from-the-cli)以了解哪些內容可以轉移。

36 

37## 開始會話

38 

39在發送第一條訊息之前,在提示區域中配置四項內容:

40 

41* **環境**:選擇 Claude 執行的位置。選擇 **Local** 用於您的機器、**Remote** 用於 Anthropic 託管的雲端會話,或用於您管理的遠端機器的 [**SSH 連線**](#ssh-sessions)。請參閱[環境配置](#environment-configuration)。

42* **專案資料夾**:選擇 Claude 工作的資料夾或儲存庫。對於遠端會話,您可以新增[多個儲存庫](#run-long-running-tasks-remotely)。

43* **模型**:從傳送按鈕旁的下拉式選單中選擇[模型](/zh-TW/model-config#available-models)。您可以在會話期間變更此設定。

44* **權限模式**:從[模式選擇器](#choose-a-permission-mode)中選擇 Claude 擁有多少自主權。您可以在會話期間變更此設定。

45 

46輸入您的任務並按 **Enter** 開始。每個會話都會追蹤自己的上下文並獨立進行變更。

47 

48## 使用程式碼

49 

50為 Claude 提供正確的上下文,控制它自主執行的程度,並檢查它所做的變更。

51 

52### 使用提示框

53 

54輸入您想讓 Claude 執行的操作,然後按 **Enter** 傳送。Claude 會讀取您的專案檔案、進行變更,並根據您的[權限模式](#choose-a-permission-mode)執行命令。您可以隨時中斷 Claude:點擊停止按鈕或輸入您的更正並按 **Enter**。Claude 會停止正在執行的操作並根據您的輸入進行調整。

55 

56提示框旁的 **+** 按鈕可讓您存取檔案附件、[skills](#use-skills)、[連接器](#connect-external-tools)和[plugins](#install-plugins)。

57 

58### 將檔案和上下文新增到提示

59 

60提示框支援兩種方式來引入外部上下文:

61 

62* **@mention 檔案**:輸入 `@` 後跟檔案名稱,將檔案新增到對話上下文。Claude 隨後可以讀取和參考該檔案。@mention 在遠端會話中不可用。

63* **附加檔案**:使用附件按鈕將影像、PDF 和其他檔案附加到您的提示,或直接將檔案拖放到提示中。這對於分享錯誤的螢幕截圖、設計模型或參考文件很有用。

64 

65### 選擇權限模式

66 

67權限模式控制 Claude 在會話期間擁有多少自主權:它是否在編輯檔案、執行命令或兩者之前詢問。您可以隨時使用傳送按鈕旁的模式選擇器切換模式。從「詢問權限」開始,以查看 Claude 確切執行的操作,然後隨著您變得更加熟悉,移至「自動接受編輯」或 Plan Mode。

68 

69| 模式 | 設定金鑰 | 行為 |

70| ------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------- |

71| **詢問權限** | `default` | Claude 在編輯檔案或執行命令之前詢問。您會看到差異,並可以接受或拒絕每項變更。建議新使用者使用。 |

72| **自動接受編輯** | `acceptEdits` | Claude 自動接受檔案編輯和常見的檔案系統命令,如 `mkdir`、`touch` 和 `mv`,但在執行其他終端機命令之前仍會詢問。當您信任檔案變更並想要更快速的迭代時,請使用此選項。 |

73| **Plan Mode** | `plan` | Claude 讀取檔案並執行命令以探索,然後提出計畫而不編輯您的原始程式碼。適合您想要先檢查方法的複雜任務。 |

74| **Auto** | `auto` | Claude 執行所有操作,並進行背景安全檢查以驗證與您的請求的一致性。減少權限提示,同時保持監督。在您的「設定」→「Claude Code」中啟用。請參閱下方的[可用性要求](#auto-mode-availability)。 |

75| **略過權限** | `bypassPermissions` | Claude 執行時不會有任何權限提示,相當於 CLI 中的 `--dangerously-skip-permissions`。在「設定」→「Claude Code」下的「允許略過權限模式」中啟用。僅在沙箱容器或虛擬機器中使用。企業管理員可以停用此選項。 |

76 

77`dontAsk` 權限模式僅在 [CLI](/zh-TW/permission-modes#allow-only-pre-approved-tools-with-dontask-mode) 中可用。

78 

79<span id="auto-mode-availability" />

80 

81Auto Mode 是在 Max、Team、Enterprise 和 API 計畫上提供的研究預覽版。在 Pro 計畫或第三方提供者上不可用。在 Team、Enterprise 和 API 計畫上,它需要 Claude Sonnet 4.6、Opus 4.6 或 Opus 4.7。在 Max 計畫上,它需要 Claude Opus 4.7。

82 

83<Tip title="最佳實踐">

84 在 Plan Mode 中開始複雜任務,以便 Claude 在進行變更之前規劃方法。一旦您批准計畫,切換到'自動接受編輯'或'詢問權限'以執行它。有關此工作流程的更多資訊,請參閱[先探索,然後計畫,然後編碼](/zh-TW/best-practices#explore-first-then-plan-then-code)。

85</Tip>

86 

87遠端會話支援'自動接受編輯'和 Plan Mode。'詢問權限'不可用,因為遠端會話預設會自動接受檔案編輯,'略過權限'不可用,因為遠端環境已經是沙箱化的。

88 

89企業管理員可以限制哪些權限模式可用。有關詳細資訊,請參閱[企業配置](#enterprise-configuration)。

90 

91### 預覽您的應用程式

92 

93Claude 可以啟動開發伺服器並開啟嵌入式瀏覽器來驗證其變更。這適用於前端網路應用程式以及後端伺服器:Claude 可以測試 API 端點、檢視伺服器日誌,並對其發現的問題進行迭代。在大多數情況下,Claude 在編輯專案檔案後會自動啟動伺服器。您也可以隨時要求 Claude 進行預覽。預設情況下,Claude [自動驗證](#auto-verify-changes)每次編輯後的變更。

94 

95預覽窗格也可以開啟您專案中的靜態 HTML 檔案、PDF、影像和影片。點擊聊天中的 HTML、PDF、影像或影片路徑以在預覽中開啟它。

96 

97從預覽窗格,您可以:

98 

99* 直接在嵌入式瀏覽器中與執行中的應用程式互動

100* 觀看 Claude 自動驗證自己的變更:它會擷取螢幕截圖、檢查 DOM、點擊元素、填寫表單,並修復它發現的問題

101* 從會話工具列中的 **Preview** 下拉式選單啟動或停止伺服器

102* 透過在下拉式選單中選擇 **Persist sessions**,在伺服器重新啟動時保留 Cookie 和本機儲存,這樣您就不必在開發期間重新登入

103* 編輯伺服器配置或一次停止所有伺服器

104 

105Claude 根據您的專案建立初始伺服器配置。如果您的應用程式使用自訂開發命令,請編輯 `.claude/launch.json` 以符合您的設定。有關完整參考,請參閱[配置預覽伺服器](#configure-preview-servers)。

106 

107若要清除已儲存的會話資料,請在'設定'→'Claude Code'中切換 **Persist preview sessions** 關閉。若要完全停用預覽,請在'設定'→'Claude Code'中切換 **Preview** 關閉。

108 

109### 使用差異檢查檢查變更

110 

111Claude 對您的程式碼進行變更後,差異檢查可讓您在建立提取請求之前逐個檔案檢查修改。

112 

113當 Claude 變更檔案時,會出現一個差異統計指示器,顯示新增和移除的行數,例如 `+12 -1`。點擊此指示器以開啟差異檢視器,它在左側顯示檔案清單,在右側顯示每個檔案的變更。

114 

115若要對特定行進行註解,請點擊差異中的任何行以開啟註解框。輸入您的回饋並按 **Enter** 新增註解。在多行新增註解後,一次提交所有註解:

116 

117* **macOS**:按 **Cmd+Enter**

118* **Windows**:按 **Ctrl+Enter**

119 

120Claude 會讀取您的註解並進行要求的變更,這些變更會顯示為您可以檢查的新差異。

121 

122### 檢查您的程式碼

123 

124在差異檢查中,點擊右上角工具列中的 **Review code**,要求 Claude 在您提交之前評估變更。Claude 會檢查目前的差異,並直接在差異檢查中留下註解。您可以回應任何註解或要求 Claude 進行修訂。

125 

126檢查著重於高信號問題:編譯錯誤、明確的邏輯錯誤、安全漏洞和明顯的錯誤。它不會標記樣式、格式、預先存在的問題或任何 linter 會捕捉的內容。

127 

128### 監控提取請求狀態

129 

130開啟提取請求後,CI 狀態列會出現在會話中。Claude Code 使用 GitHub CLI 來輪詢檢查結果並顯示失敗。

131 

132* **自動修復**:啟用後,Claude 會透過讀取失敗輸出並進行迭代,自動嘗試修復失敗的 CI 檢查。

133* **自動合併**:啟用後,Claude 會在所有檢查通過後合併 PR。合併方法是壓縮。自動合併必須在您的 GitHub 儲存庫設定中[啟用](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-auto-merge-for-pull-requests-in-your-repository)才能運作。

134 

135使用 CI 狀態列中的 **Auto-fix** 和 **Auto-merge** 切換來啟用任一選項。Claude Code 也會在 CI 完成時傳送桌面通知。若要在 PR 合併或關閉後自動存檔會話,請在'設定'→'Claude Code'中開啟[自動存檔](#work-in-parallel-with-sessions)。

136 

137<Note>

138 PR 監控需要在您的機器上安裝並驗證 [GitHub CLI (`gh`)](https://cli.github.com/)。如果未安裝 `gh`,Desktop 會在您第一次嘗試建立 PR 時提示您安裝它。

139</Note>

140 

141## 安排您的工作區

142 

143Code 標籤是圍繞您可以以任何佈局排列的窗格構建的:聊天、差異、預覽、終端機、檔案、plan、tasks 和 subagent。透過其標題拖動窗格以重新定位它,或拖動窗格邊緣以調整其大小。在 macOS 上按 **Cmd+\\** 或在 Windows 上按 **Ctrl+\\** 以關閉焦點窗格。從會話工具列中的 **Views** 選單開啟其他窗格。

144 

145<Note>

146 本節中的窗格佈局、終端機、檔案編輯器和檢視模式需要 Claude Desktop v1.2581.0 或更新版本。在 macOS 上開啟 **Claude → Check for Updates** 或在 Windows 上開啟 **Help → Check for Updates** 以更新。

147</Note>

148 

149### 在終端機中執行命令

150 

151整合終端機讓您在會話旁執行命令,而無需切換到另一個應用程式。從 **Views** 選單開啟它,或在 macOS 或 Windows 上按 **Ctrl+\`**。終端機在您會話的工作目錄中開啟,並與 Claude 共用相同的環境,因此 `npm test` 或 `git status` 等命令會看到 Claude 正在編輯的相同檔案。終端機僅在本機會話中可用。

152 

153### 開啟和編輯檔案

154 

155點擊聊天或差異檢視器中的檔案路徑以在檔案窗格中開啟它。HTML、PDF、影像和影片路徑改為在[預覽窗格](#preview-your-app)中開啟。進行現場編輯並點擊 **Save** 以寫回。如果自您開啟檔案以來檔案在磁碟上已變更,窗格會警告您並讓您覆蓋或放棄。點擊 **Discard** 以還原您的編輯,或點擊窗格標題中的路徑以複製絕對路徑。

156 

157檔案窗格在本機和 SSH 會話中可用。對於遠端會話,要求 Claude 進行變更。

158 

159### 在其他應用程式中開啟檔案

160 

161右鍵點擊聊天、差異檢視器或檔案窗格中的任何檔案路徑以開啟上下文選單:

162 

163* **Attach as context**:將檔案新增到您的下一個提示

164* **Open in**:在已安裝的編輯器(如 VS Code、Cursor 或 Zed)中開啟檔案

165* **Show in Finder**(在 macOS 上),**Show in Explorer**(在 Windows 上):開啟包含資料夾

166* **Copy path**:將絕對路徑複製到您的剪貼簿

167 

168### 切換檢視模式

169 

170檢視模式控制聊天記錄中顯示多少詳細資訊。從傳送按鈕旁的 **Transcript view** 下拉式選單切換模式,或在 macOS 或 Windows 上按 **Ctrl+O** 以循環瀏覽它們。

171 

172| 模式 | 它顯示什麼 |

173| ----------- | -------------------------- |

174| **Normal** | 工具呼叫摺疊成摘要,具有完整文字回應 |

175| **Verbose** | Claude 採取的每個工具呼叫、檔案讀取和中間步驟 |

176| **Summary** | 僅 Claude 的最終回應和它所做的變更 |

177 

178在調試 Claude 為什麼採取特定操作時使用 Verbose。當您執行多個會話並想要快速掃描結果時,使用 Summary。

179 

180### 快捷鍵

181 

182在 macOS 上按 **Cmd+/** 或在 Windows 上按 **Ctrl+/** 以查看 Code 標籤中可用的所有快捷鍵。在 Windows 上,對下面的快捷鍵使用 **Ctrl** 代替 **Cmd**。會話循環、終端機切換和檢視模式切換在每個平台上都使用 **Ctrl**。

183 

184| 快捷鍵 | 操作 |

185| ------------------------------------- | ------------- |

186| `Cmd` `/` | 顯示快捷鍵 |

187| `Cmd` `N` | 新會話 |

188| `Cmd` `W` | 關閉會話 |

189| `Ctrl` `Tab` / `Ctrl` `Shift` `Tab` | 下一個或上一個會話 |

190| `Cmd` `Shift` `]` / `Cmd` `Shift` `[` | 下一個或上一個會話 |

191| `Esc` | 停止 Claude 的回應 |

192| `Cmd` `Shift` `D` | 切換差異窗格 |

193| `Cmd` `Shift` `P` | 切換預覽窗格 |

194| `Cmd` `Shift` `S` | 在預覽中選擇元素 |

195| `Ctrl` `` ` `` | 切換終端機窗格 |

196| `Cmd` `\` | 關閉焦點窗格 |

197| `Cmd` `;` | 開啟側邊聊天 |

198| `Ctrl` `O` | 循環檢視模式 |

199| `Cmd` `Shift` `M` | 開啟權限模式選單 |

200| `Cmd` `Shift` `I` | 開啟模型選單 |

201| `Cmd` `Shift` `E` | 開啟工作量選單 |

202| `1`–`9` | 在開啟的選單中選擇項目 |

203 

204這些快捷鍵僅適用於 Code 標籤。終端機型 [interactive mode 快捷鍵](/zh-TW/interactive-mode#keyboard-shortcuts)(如 `Shift+Tab` 以循環模式)不適用於 Desktop。

205 

206### 檢查使用情況

207 

208點擊模型選擇器旁的使用情況環以查看您目前的上下文視窗使用情況和您計畫在該期間的使用情況。上下文使用情況是按會話的;計畫使用情況在您所有 Claude Code 介面中共用。

209 

210## 讓 Claude 使用您的電腦

211 

212電腦使用讓 Claude 開啟您的應用程式、控制您的螢幕,並以您的方式直接在您的機器上工作。要求 Claude 在行動模擬器中測試原生應用程式、與沒有 CLI 的桌面工具互動,或自動化只能透過 GUI 運作的內容。

213 

214<Note>

215 電腦使用是 macOS 和 Windows 上的研究預覽版,需要 Pro 或 Max 計畫。它在 Team 或 Enterprise 計畫上不可用。Claude Desktop 應用程式必須執行。

216</Note>

217 

218電腦使用預設為關閉。[在'設定'中啟用它](#enable-computer-use),然後 Claude 才能控制您的螢幕。在 macOS 上,您還需要授予'協助工具'和'螢幕錄製'權限。

219 

220<Warning>

221 與[沙箱化 Bash 工具](/zh-TW/sandboxing)不同,電腦使用在您的實際桌面上執行,可以存取您批准的任何內容。Claude 會檢查每個操作並標記螢幕上內容的潛在提示注入,但信任邊界不同。有關最佳實踐,請參閱[電腦使用安全指南](https://support.claude.com/en/articles/14128542)。

222</Warning>

223 

224### 何時應用電腦使用

225 

226Claude 有多種方式與應用程式或服務互動,電腦使用是最廣泛和最慢的。它首先嘗試最精確的工具:

227 

228* 如果您有服務的[連接器](#connect-external-tools),Claude 會使用連接器。

229* 如果任務是 shell 命令,Claude 會使用 Bash。

230* 如果任務是瀏覽器工作且您已設定[Chrome 中的 Claude](/zh-TW/chrome),Claude 會使用它。

231* 如果以上都不適用,Claude 會使用電腦使用。

232 

233[每個應用程式的存取層級](#app-permissions)強化了這一點:瀏覽器限制為僅檢視,終端機和 IDE 限制為僅點擊,引導 Claude 使用專用工具,即使電腦使用處於活動狀態。螢幕控制保留給其他工具無法到達的內容,例如原生應用程式、硬體控制面板、行動模擬器或沒有 API 的專有工具。

234 

235### 啟用電腦使用

236 

237電腦使用預設為關閉。如果您要求 Claude 執行需要它的操作而它處於關閉狀態,Claude 會告訴您如果在'設定'中啟用電腦使用,它可以執行該任務。

238 

239<Steps>

240 <Step title="更新桌面應用程式">

241 確保您有最新版本的 Claude Desktop。在 [claude.com/download](https://claude.com/download) 下載或更新,然後重新啟動應用程式。

242 </Step>

243 

244 <Step title="開啟切換">

245 在桌面應用程式中,前往 **Settings > General**(在 **Desktop app** 下)。找到 **Computer use** 切換並開啟它。在 Windows 上,切換立即生效,設定完成。在 macOS 上,繼續下一步。

246 

247 如果您看不到切換,請確認您在 macOS 或 Windows 上使用 Pro 或 Max 計畫,然後更新並重新啟動應用程式。

248 </Step>

249 

250 <Step title="授予 macOS 權限">

251 在 macOS 上,在切換生效之前授予兩個系統權限:

252 

253 * **Accessibility**:讓 Claude 點擊、輸入和滾動

254 * **Screen Recording**:讓 Claude 看到您螢幕上的內容

255 

256 「設定」頁面顯示每個權限的目前狀態。如果任一被拒絕,點擊徽章以開啟相關的「系統設定」窗格。

257 </Step>

258</Steps>

259 

260### 應用程式權限

261 

262Claude 第一次需要使用應用程式時,會在您的會話中出現提示。點擊 **Allow for this session** 或 **Deny**。批准在目前會話中持續,或在 [Dispatch 產生的會話](#sessions-from-dispatch)中持續 30 分鐘。

263 

264提示也顯示 Claude 對該應用程式獲得的控制級別。這些層級由應用程式類別固定,無法變更:

265 

266| 層級 | Claude 可以執行的操作 | 適用於 |

267| :--- | :---------------- | :------- |

268| 僅檢視 | 在螢幕截圖中查看應用程式 | 瀏覽器、交易平台 |

269| 僅點擊 | 點擊和滾動,但不能輸入或使用快捷鍵 | 終端機、IDE |

270| 完全控制 | 點擊、輸入、拖動和使用快捷鍵 | 其他所有內容 |

271 

272具有廣泛影響力的應用程式(如終端機、Finder 或檔案總管,以及「系統設定」或「設定」)在提示中顯示額外警告,以便您知道批准它們會授予什麼。

273 

274您可以在 **Settings > General**(在 **Desktop app** 下)中配置兩個設定:

275 

276* **Denied apps**:在此處新增應用程式以拒絕它們而不提示。Claude 可能仍會透過允許應用程式中的操作間接影響被拒絕的應用程式,但它無法直接與被拒絕的應用程式互動。

277* **Unhide apps when Claude finishes**:當 Claude 工作時,您的其他視窗會被隱藏,以便它僅與批准的應用程式互動。當 Claude 完成時,隱藏的視窗會被恢復,除非您關閉此設定。

278 

279## 管理會話

280 

281每個會話都是一個獨立的對話,具有自己的上下文和變更。您可以並行執行多個會話、分支出側邊聊天、將工作傳送到雲端,或讓 Dispatch 從您的手機為您啟動會話。

282 

283### 使用會話並行工作

284 

285點擊側邊欄中的 **+ New session**,或在 macOS 上按 **Cmd+N** 或在 Windows 上按 **Ctrl+N**,以並行處理多個任務。按 **Ctrl+Tab** 和 **Ctrl+Shift+Tab** 以循環瀏覽側邊欄中的會話。對於 Git 儲存庫,每個會話都會使用 [Git worktrees](/zh-TW/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees) 獲得自己的隔離專案副本,因此一個會話中的變更不會影響其他會話,直到您提交它們。

286 

287Worktrees 預設儲存在 `<project-root>/.claude/worktrees/` 中。您可以在「設定」→「Claude Code」下的「Worktree location」中將其變更為自訂目錄。您也可以設定一個分支前綴,該前綴會被加在每個 worktree 分支名稱前面,這對於保持 Claude 建立的分支井然有序很有用。若要在完成後移除 worktree,請將滑鼠懸停在側邊欄中的會話上,然後點擊存檔圖示。若要在 PR 合併或關閉後自動存檔會話,請在「設定」→「Claude Code」中開啟 **Auto-archive after PR merge or close**。自動存檔僅適用於已完成執行的本機會話。

288 

289若要在新 worktrees 中包含 gitignored 檔案(如 `.env`),請在您的專案根目錄中建立 [`.worktreeinclude` 檔案](/zh-TW/common-workflows#copy-gitignored-files-to-worktrees)。

290 

291<Note>

292 會話隔離需要 [Git](https://git-scm.com/downloads)。大多數 Mac 預設包含 Git。在終端機中執行 `git --version` 進行檢查。在 Windows 上,Code 標籤需要 Git 才能運作:[下載 Git for Windows](https://git-scm.com/downloads/win)、安裝它,然後重新啟動應用程式。如果您遇到 Git 錯誤,請在 [Cowork 標籤](https://claude.com/product/cowork) 中詢問 Claude 以幫助排除您的設定問題。

293</Note>

294 

295使用側邊欄頂部的控制項按狀態、專案或環境篩選會話,並按專案分組會話。若要重新命名會話,請點擊活動會話頂部工具列中的會話標題。若要檢查上下文使用情況,請參閱[檢查使用情況](#check-usage)。當上下文填滿時,Claude 會自動總結對話並繼續工作。您也可以輸入 `/compact` 來更早觸發總結並釋放上下文空間。有關壓縮如何運作的詳細資訊,請參閱[上下文視窗](/zh-TW/how-claude-code-works#the-context-window)。

296 

297### 在不偏離會話的情況下詢問側邊問題

298 

299側邊聊天讓您詢問 Claude 一個使用您會話上下文的問題,但不會將任何內容新增回主對話。當您想要理解一段程式碼、檢查假設或探索想法而不引導會話偏離時,請使用它。

300 

301在 macOS 上按 **Cmd+;** 或在 Windows 上按 **Ctrl+;** 以開啟側邊聊天,或在提示框中輸入 `/btw`。側邊聊天可以讀取主執行緒中到該點為止的所有內容。完成後,關閉側邊聊天並在您離開的地方繼續主會話。側邊聊天在本機和 SSH 會話中可用。

302 

303### 觀看背景任務

304 

305任務窗格顯示在目前會話內執行的背景工作:子代理、背景 shell 命令和工作流程。從 **Views** 選單開啟它或將其拖入您的佈局。

306 

307點擊任何項目以在子代理窗格中查看其輸出或停止它。若要查看其他會話正在執行的操作,請使用[側邊欄](#work-in-parallel-with-sessions)。

308 

309### 遠端執行長時間執行的任務

310 

311對於大型重構、測試套件、遷移或其他長時間執行的任務,在開始會話時選擇 **Remote** 而不是 **Local**。遠端會話在 Anthropic 的雲端基礎設施上執行,即使您關閉應用程式或關閉電腦,也會繼續執行。隨時檢查以查看進度或引導 Claude 朝不同方向發展。您也可以從 [claude.ai/code](https://claude.ai/code) 或 Claude iOS 應用程式監控遠端會話。

312 

313遠端會話也支援多個儲存庫。選擇雲端環境後,點擊儲存庫藥丸旁的 **+** 按鈕,將其他儲存庫新增到會話。每個儲存庫都有自己的分支選擇器。這對於跨越多個程式碼庫的任務很有用,例如更新共用程式庫及其使用者。

314 

315有關遠端會話如何運作的更多資訊,請參閱[網路上的 Claude Code](/zh-TW/claude-code-on-the-web)。

316 

317### 在另一個介面中繼續

318 

319**Continue in** 選單可從會話工具列右下角的 VS Code 圖示存取,可讓您將會話移至另一個介面:

320 

321* **Claude Code on the Web**:將您的本機會話傳送到遠端繼續執行。Desktop 推送您的分支、產生對話摘要,並使用完整上下文建立新的遠端會話。然後您可以選擇存檔本機會話或保留它。這需要乾淨的工作樹,不適用於 SSH 會話。

322* **Your IDE**:在目前工作目錄的支援 IDE 中開啟您的專案。

323 

324### 來自 Dispatch 的會話

325 

326[Dispatch](https://support.claude.com/en/articles/13947068) 是與 Claude 的持久對話,存在於 [Cowork](https://claude.com/product/cowork#dispatch-and-computer-use) 標籤中。您向 Dispatch 傳送任務,它決定如何處理它。

327 

328任務可以透過兩種方式成為 Code 會話:您直接要求一個,例如「開啟 Claude Code 會話並修復登入錯誤」,或 Dispatch 決定任務是開發工作並自行產生一個。通常路由到 Code 的任務包括修復錯誤、更新相依性、執行測試或開啟提取請求。研究、文件編輯和試算表工作保留在 Cowork 中。

329 

330無論哪種方式,Code 會話都會在 Code 標籤的側邊欄中出現,帶有 **Dispatch** 徽章。當它完成或需要您的批准時,您會在手機上收到推送通知。

331 

332如果您已[啟用電腦使用](#let-claude-use-your-computer),Dispatch 產生的 Code 會話也可以使用它。這些會話中的應用程式批准在 30 分鐘後過期並重新提示,而不是像常規 Code 會話那樣持續整個會話。

333 

334有關設定、配對和 Dispatch 設定,請參閱 [Dispatch 幫助文章](https://support.claude.com/en/articles/13947068)。Dispatch 需要 Pro 或 Max 計畫,在 Team 或 Enterprise 計畫上不可用。

335 

336Dispatch 是當您遠離終端機時與 Claude 合作的多種方式之一。請參閱[平台和整合](/zh-TW/platforms#work-when-you-are-away-from-your-terminal)以將其與遠端控制、頻道、Slack 和排程任務進行比較。

337 

338## 擴展 Claude Code

339 

340連接外部服務、新增可重複使用的工作流程、自訂 Claude 的行為,並配置預覽伺服器。若要在一個地方管理連接器、skills 和 plugins,請點擊側邊欄中的 **Customize**。

341 

342### 連接外部工具

343 

344對於本機和 [SSH](#ssh-sessions) 會話,點擊提示框旁的 **+** 按鈕,然後選擇 **Connectors** 以新增 Google Calendar、Slack、GitHub、Linear、Notion 等整合。您可以在會話之前或期間新增連接器。**+** 按鈕在遠端會話中不可用,但 [routines](/zh-TW/routines) 在 routine 建立時配置連接器。

345 

346若要管理或斷開連接器,請在桌面應用程式中前往「設定」→「Connectors」,或從提示框中的「Connectors」選單中選擇 **Manage connectors**。

347 

348連接後,Claude 可以讀取您的日曆、傳送訊息、建立問題,並直接與您的工具互動。您可以詢問 Claude 在您的會話中配置了哪些連接器。

349 

350連接器是 [MCP servers](/zh-TW/mcp),具有圖形設定流程。使用它們可以快速與支援的服務整合。對於「Connectors」中未列出的整合,透過 [settings files](/zh-TW/mcp#installing-mcp-servers) 手動新增 MCP servers。您也可以 [create custom connectors](https://support.claude.com/en/articles/11175166-getting-started-with-custom-connectors-using-remote-mcp)。

351 

352### 使用 skills

353 

354[Skills](/zh-TW/skills) 擴展 Claude 可以執行的操作。Claude 在相關時自動載入它們,或者您可以直接呼叫一個:在提示框中輸入 `/` 或點擊 **+** 按鈕並選擇 **Slash commands** 以瀏覽可用的內容。這包括 [built-in commands](/zh-TW/commands)、您的 [custom skills](/zh-TW/skills#create-your-first-skill)、來自您程式碼庫的專案 skills,以及來自任何 [installed plugins](/zh-TW/plugins) 的 skills。選擇一個,它會在輸入欄位中突出顯示。在其後輸入您的任務並照常傳送。

355 

356### 安裝 plugins

357 

358[Plugins](/zh-TW/plugins) 是可重複使用的套件,可將 skills、agents、hooks、MCP servers 和 LSP 配置新增到 Claude Code。您可以從桌面應用程式安裝 plugins,而無需使用終端機。

359 

360對於本機和 [SSH](#ssh-sessions) 會話,點擊提示框旁的 **+** 按鈕,然後選擇 **Plugins** 以查看您已安裝的 plugins 及其 skills。若要新增 plugin,從子選單中選擇 **Add plugin** 以開啟 plugin 瀏覽器,它顯示來自您配置的 [marketplaces](/zh-TW/plugin-marketplaces)(包括官方 Anthropic 市場)的可用 plugins。選擇 **Manage plugins** 以啟用、停用或解除安裝 plugins。

361 

362Plugins 可以限定於您的使用者帳戶、特定專案或僅本機。如果您的組織集中管理 plugins,這些 plugins 在桌面會話中的可用方式與在 CLI 中相同。遠端會話不提供 Plugins。有關完整的 plugin 參考(包括建立您自己的 plugins),請參閱 [plugins](/zh-TW/plugins)。

363 

364### 配置預覽伺服器

365 

366Claude 會自動偵測您的開發伺服器設定,並將配置儲存在您開始會話時選擇的資料夾根目錄中的 `.claude/launch.json`。Preview 使用此資料夾作為其工作目錄,因此如果您選擇了父資料夾,具有自己開發伺服器的子資料夾將不會自動偵測。若要使用子資料夾的伺服器,請直接在該資料夾中開始會話,或手動新增配置。

367 

368若要自訂伺服器的啟動方式,例如使用 `yarn dev` 而不是 `npm run dev` 或變更連接埠,請手動編輯檔案或點擊 Preview 下拉式選單中的 **Edit configuration** 以在您的程式碼編輯器中開啟它。該檔案支援帶註解的 JSON。

369 

370```json theme={null}

371{

372 "version": "0.0.1",

373 "configurations": [

374 {

375 "name": "my-app",

376 "runtimeExecutable": "npm",

377 "runtimeArgs": ["run", "dev"],

378 "port": 3000

379 }

380 ]

381}

382```

383 

384您可以定義多個配置以從同一專案執行不同的伺服器,例如前端和 API。請參閱下面的 [examples](#examples)。

385 

386#### 自動驗證變更

387 

388啟用 `autoVerify` 時,Claude 會在編輯檔案後自動驗證程式碼變更。它會擷取螢幕截圖、檢查錯誤,並在完成回應之前確認變更有效。

389 

390自動驗證預設為開啟。透過將 `"autoVerify": false` 新增到 `.claude/launch.json`,或從 **Preview** 下拉式選單切換它,按專案停用它。

391 

392```json theme={null}

393{

394 "version": "0.0.1",

395 "autoVerify": false,

396 "configurations": [...]

397}

398```

399 

400停用後,預覽工具仍然可用,您可以隨時要求 Claude 進行驗證。自動驗證使其在每次編輯後自動進行。

401 

402#### 配置欄位

403 

404`configurations` 陣列中的每個項目接受以下欄位:

405 

406| 欄位 | 類型 | 描述 |

407| ------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------- |

408| `name` | string | 此伺服器的唯一識別碼 |

409| `runtimeExecutable` | string | 要執行的命令,例如 `npm`、`yarn` 或 `node` |

410| `runtimeArgs` | string\[] | 傳遞給 `runtimeExecutable` 的引數,例如 `["run", "dev"]` |

411| `port` | number | 您的伺服器監聽的連接埠。預設為 3000 |

412| `cwd` | string | 相對於您的專案根目錄的工作目錄。預設為專案根目錄。使用 `${workspaceFolder}` 明確參考專案根目錄 |

413| `env` | object | 其他環境變數作為鍵值對,例如 `{ "NODE_ENV": "development" }`。不要在此處放置機密,因為此檔案會提交到您的儲存庫。若要將機密傳遞到您的開發伺服器,請在 [local environment editor](#local-sessions) 中設定它們。 |

414| `autoPort` | boolean | 如何處理連接埠衝突。請參閱下面 |

415| `program` | string | 使用 `node` 執行的指令碼。請參閱 [when to use `program` vs `runtimeExecutable`](#when-to-use-program-vs-runtimeexecutable) |

416| `args` | string\[] | 傳遞給 `program` 的引數。僅在設定 `program` 時使用 |

417 

418##### 何時使用 `program` 與 `runtimeExecutable`

419 

420使用 `runtimeExecutable` 搭配 `runtimeArgs` 透過套件管理器啟動開發伺服器。例如,`"runtimeExecutable": "npm"` 搭配 `"runtimeArgs": ["run", "dev"]` 執行 `npm run dev`。

421 

422當您有想要直接使用 `node` 執行的獨立指令碼時,使用 `program`。例如,`"program": "server.js"` 執行 `node server.js`。使用 `args` 傳遞其他標誌。

423 

424#### 連接埠衝突

425 

426`autoPort` 欄位控制當您偏好的連接埠已在使用時會發生什麼:

427 

428* **`true`**:Claude 自動尋找並使用空閒連接埠。適合大多數開發伺服器。

429* **`false`**:Claude 失敗並出現錯誤。當您的伺服器必須使用特定連接埠時使用此選項,例如 OAuth 回呼或 CORS 允許清單。

430* **未設定(預設)**:Claude 詢問伺服器是否需要該確切連接埠,然後儲存您的答案。

431 

432當 Claude 選擇不同的連接埠時,它會透過 `PORT` 環境變數將指派的連接埠傳遞給您的伺服器。

433 

434#### 範例

435 

436這些配置顯示不同專案類型的常見設定:

437 

438<Tabs>

439 <Tab title="Next.js">

440 此配置使用 Yarn 在連接埠 3000 上執行 Next.js 應用程式:

441 

442 ```json theme={null}

443 {

444 "version": "0.0.1",

445 "configurations": [

446 {

447 "name": "web",

448 "runtimeExecutable": "yarn",

449 "runtimeArgs": ["dev"],

450 "port": 3000

451 }

452 ]

453 }

454 ```

455 </Tab>

456 

457 <Tab title="Multiple servers">

458 對於具有前端和 API 伺服器的 monorepo,定義多個配置。前端使用 `autoPort: true`,因此如果 3000 被佔用,它會選擇空閒連接埠,而 API 伺服器需要確切的連接埠 8080:

459 

460 ```json theme={null}

461 {

462 "version": "0.0.1",

463 "configurations": [

464 {

465 "name": "frontend",

466 "runtimeExecutable": "npm",

467 "runtimeArgs": ["run", "dev"],

468 "cwd": "apps/web",

469 "port": 3000,

470 "autoPort": true

471 },

472 {

473 "name": "api",

474 "runtimeExecutable": "npm",

475 "runtimeArgs": ["run", "start"],

476 "cwd": "server",

477 "port": 8080,

478 "env": { "NODE_ENV": "development" },

479 "autoPort": false

480 }

481 ]

482 }

483 ```

484 </Tab>

485 

486 <Tab title="Node.js script">

487 若要直接執行 Node.js 指令碼而不是使用套件管理器命令,請使用 `program` 欄位:

488 

489 ```json theme={null}

490 {

491 "version": "0.0.1",

492 "configurations": [

493 {

494 "name": "server",

495 "program": "server.js",

496 "args": ["--verbose"],

497 "port": 4000

498 }

499 ]

500 }

501 ```

502 </Tab>

503</Tabs>

504 

505## 環境配置

506 

507您在[開始會話](#start-a-session)時選擇的環境決定了 Claude 執行的位置以及您如何連接:

508 

509* **Local**:在您的機器上執行,直接存取您的檔案

510* **Remote**:在 Anthropic 的雲端基礎設施上執行。即使您關閉應用程式,會話也會繼續。

511* **SSH**:在您透過 SSH 連接的遠端機器上執行,例如您自己的伺服器、雲端虛擬機器或開發容器

512 

513### 本機會話

514 

515桌面應用程式並不總是繼承您的完整 shell 環境。在 macOS 上,當您從 Dock 或 Finder 啟動應用程式時,它會讀取您的 shell 設定檔(如 `~/.zshrc` 或 `~/.bashrc`)以提取 `PATH` 和一組固定的 Claude Code 變數,但您在那裡匯出的其他變數不會被拾取。在 Windows 上,應用程式繼承使用者和系統環境變數,但不讀取 PowerShell 設定檔。

516 

517若要在任何平台上為本機會話和開發伺服器設定環境變數,請在提示框中開啟環境下拉式選單,將滑鼠懸停在 **Local** 上,然後點擊齒輪圖示以開啟本機環境編輯器。您在此處儲存的變數會在您的機器上加密儲存,並適用於您啟動的每個本機會話和預覽伺服器。您也可以將變數新增到 `~/.claude/settings.json` 檔案中的 `env` 金鑰,儘管這些僅到達 Claude 會話而不是開發伺服器。有關支援的變數的完整清單,請參閱[環境變數](/zh-TW/env-vars)。

518 

519[擴展思考](/zh-TW/common-workflows#use-extended-thinking-thinking-mode)預設啟用,這改進了複雜推理任務的效能,但使用額外的 tokens。若要完全停用思考,請在本機環境編輯器中將 `MAX_THINKING_TOKENS` 設定為 `0`。在具有[自適應推理](/zh-TW/model-config#adjust-effort-level)的模型上,任何其他 `MAX_THINKING_TOKENS` 值都會被忽略,因為自適應推理控制思考深度。在 Opus 4.6 和 Sonnet 4.6 上,將 `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` 設定為 `1` 以使用固定思考預算;Opus 4.7 始終使用自適應推理,沒有固定預算模式。

520 

521### 遠端會話

522 

523遠端會話即使您關閉應用程式也會在背景繼續。使用情況計入您的[訂閱計畫限制](/zh-TW/costs),沒有單獨的計算費用。

524 

525您可以建立具有不同網路存取級別和環境變數的自訂雲端環境。在開始遠端會話時選擇環境下拉式選單,然後選擇 **Add environment**。有關配置網路存取和環境變數的詳細資訊,請參閱[雲端環境](/zh-TW/claude-code-on-the-web#the-cloud-environment)。

526 

527### SSH 會話

528 

529SSH 會話可讓您在遠端機器上執行 Claude Code,同時使用桌面應用程式作為您的介面。這對於使用存在於雲端虛擬機器、開發容器或具有特定硬體或相依性的伺服器上的程式碼庫很有用。

530 

531若要新增 SSH 連線,請在開始會話前點擊環境下拉式選單,然後選擇 **+ Add SSH connection**。對話框要求:

532 

533* **Name**:此連線的友善標籤

534* **SSH Host**:`user@hostname` 或在 `~/.ssh/config` 中定義的主機

535* **SSH Port**:如果留空則預設為 22,或使用您的 SSH 配置中的連接埠

536* **Identity File**:您的私鑰的路徑,例如 `~/.ssh/id_rsa`。留空以使用預設金鑰或您的 SSH 配置。

537 

538新增後,連線會出現在環境下拉式選單中。選擇它以在該機器上啟動會話。Claude 在遠端機器上執行,可存取其檔案和工具。

539 

540遠端機器必須執行 Linux 或 macOS。桌面應用程式會在您第一次連接時自動在遠端機器上安裝 Claude Code。連接後,SSH 會話支援權限模式、連接器、plugins 和 MCP servers。

541 

542#### 為您的團隊預先配置 SSH 連線

543 

544管理員可以透過將 `sshConfigs` 新增到[受管設定](/zh-TW/settings#settings-precedence)檔案來將 SSH 連線分發給團隊成員。以這種方式定義的連線會自動出現在每個使用者的環境下拉式選單中,並顯示為受管,因此使用者可以選擇它們,但無法在應用程式中編輯或刪除它們。

545 

546以下範例預先配置了一個在遠端主機上的 `~/projects` 中開啟的單一連線:

547 

548```json theme={null}

549{

550 "sshConfigs": [

551 {

552 "id": "shared-dev-vm",

553 "name": "Shared Dev VM",

554 "sshHost": "user@dev.example.com",

555 "sshPort": 22,

556 "sshIdentityFile": "~/.ssh/id_ed25519",

557 "startDirectory": "~/projects"

558 }

559 ]

560}

561```

562 

563每個項目都需要 `id`、`name` 和 `sshHost`。`sshPort`、`sshIdentityFile` 和 `startDirectory` 欄位是選用的。使用者也可以將 `sshConfigs` 新增到他們自己的 `~/.claude/settings.json`,這是透過對話框新增的連線的儲存位置。

564 

565## 企業配置

566 

567Teams 或 Enterprise 計畫上的組織可以透過管理員主控台控制、受管設定檔案和裝置管理原則來管理桌面應用程式行為。

568 

569### 管理員主控台控制

570 

571這些設定透過[管理員設定主控台](https://claude.ai/admin-settings/claude-code)配置:

572 

573* **Desktop 中的 Code**:控制您組織中的使用者是否可以在桌面應用程式中存取 Claude Code

574* **網路上的 Code**:為您的組織啟用或停用[網路會話](/zh-TW/claude-code-on-the-web)

575* **遠端控制**:為您的組織啟用或停用[遠端控制](/zh-TW/remote-control)

576* **停用略過權限模式**:防止您組織中的使用者啟用略過權限模式

577 

578### 受管設定

579 

580受管設定會覆蓋專案和使用者設定,並在 Desktop 產生 CLI 會話時套用。您可以在您組織的[受管設定](/zh-TW/settings#settings-precedence)檔案中設定這些金鑰,或透過管理員主控台遠端推送它們。

581 

582| 金鑰 | 描述 |

583| ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |

584| `permissions.disableBypassPermissionsMode` | 設定為 `"disable"` 以防止使用者啟用略過權限模式。 |

585| `disableAutoMode` | 設定為 `"disable"` 以防止使用者啟用 [Auto](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode) 模式。從模式選擇器中移除 Auto。也在 `permissions` 下接受。 |

586| `autoMode` | 自訂 auto 模式分類器在您的組織中信任和阻止的內容。請參閱[配置 auto 模式](/zh-TW/auto-mode-config)。 |

587| `sshConfigs` | 預先配置[SSH 連線](#pre-configure-ssh-connections-for-your-team),在環境下拉式選單中顯示。使用者無法編輯或刪除受管連線。 |

588 

589部署到每台機器上磁碟的受管設定檔案適用於 Desktop 會話。透過管理員主控台推送的遠端受管設定目前僅適用於 CLI 和 IDE 會話,因此對於 Desktop 部署,請透過 MDM 分發檔案或使用上面的[管理員主控台控制](#admin-console-controls)。

590 

591`permissions.disableBypassPermissionsMode` 和 `disableAutoMode` 也在使用者和專案設定中運作,但將它們放在受管設定中可防止使用者覆蓋它們。`autoMode` 從使用者設定、`.claude/settings.local.json` 和受管設定讀取,但不從簽入的 `.claude/settings.json` 讀取:複製的儲存庫無法注入自己的分類器規則。有關受管專用設定(包括 `allowManagedPermissionRulesOnly` 和 `allowManagedHooksOnly`)的完整清單,請參閱[受管專用設定](/zh-TW/permissions#managed-only-settings)。

592 

593### 裝置管理原則

594 

595IT 團隊可以透過 macOS 上的 MDM 或 Windows 上的群組原則來管理桌面應用程式。可用的原則包括啟用或停用 Claude Code 功能、控制自動更新和設定自訂部署 URL。

596 

597* **macOS**:使用 Jamf 或 Kandji 等工具透過 `com.anthropic.Claude` 偏好設定網域配置

598* **Windows**:透過 `SOFTWARE\Policies\Claude` 的登錄配置

599 

600### 驗證和 SSO

601 

602企業組織可以要求所有使用者進行 SSO。有關計畫級別的詳細資訊,請參閱[驗證](/zh-TW/authentication),有關 SAML 和 OIDC 配置,請參閱[設定 SSO](https://support.claude.com/en/articles/13132885-setting-up-single-sign-on-sso)。

603 

604### 資料處理

605 

606Claude Code 在本機會話中本機處理您的程式碼,或在遠端會話中在 Anthropic 的雲端基礎設施上處理。對話和程式碼上下文會傳送到 Anthropic 的 API 進行處理。有關資料保留、隱私和合規性的詳細資訊,請參閱[資料處理](/zh-TW/data-usage)。

607 

608### 部署

609 

610Desktop 可以透過企業部署工具分發:

611 

612* **macOS**:透過 MDM(例如 Jamf 或 Kandji)使用 `.dmg` 安裝程式分發

613* **Windows**:透過 MSIX 套件或 `.exe` 安裝程式部署。有關企業部署選項(包括無聲安裝),請參閱[為 Windows 部署 Claude Desktop](https://support.claude.com/en/articles/12622703-deploy-claude-desktop-for-windows)

614 

615有關網路配置(例如代理設定、防火牆允許清單和 LLM 閘道),請參閱[網路配置](/zh-TW/network-config)。

616 

617有關完整的企業配置參考,請參閱[企業配置指南](https://support.claude.com/en/articles/12622667-enterprise-configuration)。

618 

619## 來自 CLI?

620 

621如果您已經使用 Claude Code CLI,Desktop 執行相同的基礎引擎,具有圖形介面。您可以在同一機器上同時執行兩者,甚至在同一專案上執行。每個都維護單獨的會話歷史記錄,但它們透過 CLAUDE.md 檔案共用配置和專案記憶。

622 

623若要將 CLI 會話移至 Desktop,請在終端機中執行 `/desktop`。Claude 儲存您的會話並在桌面應用程式中開啟它,然後退出 CLI。此命令僅在 macOS 和 Windows 上可用。

624 

625<Tip>

626 何時使用 Desktop 與 CLI:當您想要在一個視窗中管理並行會話、並排排列窗格或視覺化檢查變更時,使用 Desktop。當您需要指令碼、自動化或偏好終端機工作流程時,使用 CLI。

627</Tip>

628 

629### CLI 標誌等效項

630 

631此表顯示常見 CLI 標誌的桌面應用程式等效項。未列出的標誌沒有桌面等效項,因為它們是為指令碼或自動化設計的。

632 

633| CLI | Desktop 等效項 |

634| ------------------------------------- | ---------------------------------------------------------- |

635| `--model sonnet` | 傳送按鈕旁的模型下拉式選單 |

636| `--resume`, `--continue` | 點擊側邊欄中的會話 |

637| `--permission-mode` | 傳送按鈕旁的模式選擇器 |

638| `--dangerously-skip-permissions` | 略過權限模式。在「設定」→「Claude Code」→「允許略過權限模式」中啟用。企業管理員可以停用此設定。 |

639| `--add-dir` | 在遠端會話中使用 **+** 按鈕新增多個儲存庫 |

640| `--allowedTools`, `--disallowedTools` | 沒有各別會話等效項。[設定檔案](/zh-TW/settings)中的權限規則仍然適用。 |

641| `--verbose` | [Verbose 檢視模式](#switch-view-modes)在「Transcript view」下拉式選單中 |

642| `--print`, `--output-format` | 不可用。Desktop 僅限互動。 |

643| `ANTHROPIC_MODEL` 環境變數 | 傳送按鈕旁的模型下拉式選單 |

644| `MAX_THINKING_TOKENS` 環境變數 | 在本機環境編輯器中設定。請參閱[環境配置](#environment-configuration)。 |

645 

646### 共用配置

647 

648Desktop 和 CLI 讀取相同的配置檔案,因此您的設定會轉移:

649 

650* **[CLAUDE.md](/zh-TW/memory)** 和 `CLAUDE.local.md` 檔案在您的專案中由兩者使用

651* **[MCP servers](/zh-TW/mcp)** 在 `~/.claude.json` 或 `.mcp.json` 中配置的在兩者中都有效

652* **[Hooks](/zh-TW/hooks)** 和 **[skills](/zh-TW/skills)** 在設定中定義的適用於兩者

653* **[Settings](/zh-TW/settings)** 在 `~/.claude.json` 和 `~/.claude/settings.json` 中是共用的。`settings.json` 中的權限規則、允許的工具和其他設定適用於 Desktop 會話。

654* **Models**:Sonnet、Opus 和 Haiku 在兩者中都可用。在 Desktop 中,從傳送按鈕旁的下拉式選單中選擇模型。您可以在會話期間從相同的下拉式選單變更模型。

655 

656<Note>

657 **MCP servers:桌面聊天應用程式與 Claude Code**:在 `claude_desktop_config.json` 中為 Claude Desktop 聊天應用程式配置的 MCP servers 與 Claude Code 分開,不會出現在 Code 標籤中。若要在 Claude Code 中使用 MCP servers,請在 `~/.claude.json` 或您的專案的 `.mcp.json` 檔案中配置它們。有關詳細資訊,請參閱 [MCP 配置](/zh-TW/mcp#installing-mcp-servers)。

658</Note>

659 

660### 功能比較

661 

662此表比較 CLI 和 Desktop 之間的核心功能。有關 CLI 標誌的完整清單,請參閱 [CLI 參考](/zh-TW/cli-reference)。

663 

664| 功能 | CLI | Desktop |

665| ----------------------------------------- | -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |

666| 權限模式 | 所有模式,包括 `dontAsk` | 詢問權限、自動接受編輯、Plan Mode、Auto 和透過「設定」略過權限 |

667| `--dangerously-skip-permissions` | CLI 標誌 | 略過權限模式。在「設定」→「Claude Code」→「允許略過權限模式」中啟用 |

668| [第三方提供者](/zh-TW/third-party-integrations) | Bedrock、Vertex、Foundry | Anthropic 的 API 預設。企業部署可以配置 Vertex AI 和閘道提供者。請參閱[企業配置指南](https://support.claude.com/en/articles/12622667-enterprise-configuration)。 |

669| [MCP servers](/zh-TW/mcp) | 在設定檔案中配置 | 本機和 SSH 會話的連接器 UI,或設定檔案 |

670| [Plugins](/zh-TW/plugins) | `/plugin` 命令 | plugin 管理器 UI |

671| @mention 檔案 | 文字型 | 具有自動完成;本機和 SSH 會話僅 |

672| 檔案附件 | 不可用 | 影像、PDF |

673| 會話隔離 | [`--worktree`](/zh-TW/cli-reference) 標誌 | 自動 worktrees |

674| 多個會話 | 單獨的終端機 | 側邊欄標籤 |

675| 定期任務 | Cron 工作、CI 管道 | [排程任務](/zh-TW/desktop-scheduled-tasks) |

676| 電腦使用 | [透過 `/mcp` 在 macOS 上啟用](/zh-TW/computer-use) | [應用程式和螢幕控制](#let-claude-use-your-computer)在 macOS 和 Windows 上 |

677| Dispatch 整合 | 不可用 | [Dispatch 會話](#sessions-from-dispatch)在側邊欄中 |

678| 指令碼和自動化 | [`--print`](/zh-TW/cli-reference)、[Agent SDK](/zh-TW/headless) | 不可用 |

679 

680### Desktop 中不可用的內容

681 

682以下功能僅在 CLI 或 VS Code 擴充功能中可用:

683 

684* **第三方提供者**:Desktop 預設連接到 Anthropic 的 API。企業部署可以配置 Vertex AI 和閘道提供者,透過[受管設定](https://support.claude.com/en/articles/12622667-enterprise-configuration)。對於 Bedrock 或 Foundry,請使用 [CLI](/zh-TW/quickstart)。

685* **Linux**:桌面應用程式僅在 macOS 和 Windows 上可用。在 Linux 上,請使用 [CLI](/zh-TW/quickstart)。

686* **內嵌程式碼建議**:Desktop 不提供自動完成樣式的建議。它透過對話提示和明確的程式碼變更進行工作。

687* **Agent teams**:多代理協調可透過 [CLI](/zh-TW/agent-teams) 和 [Agent SDK](/zh-TW/headless) 使用,不在 Desktop 中。

688 

689## 疑難排解

690 

691下面的部分涵蓋桌面應用程式特定的問題。對於出現在聊天中的執行時 API 錯誤,例如 `API Error: 500`、`529 Overloaded`、`429` 或 `Prompt is too long`,請參閱[錯誤參考](/zh-TW/errors)。這些錯誤及其修復在 CLI、Desktop 和網路中是相同的。

692 

693### 檢查您的版本

694 

695若要查看您執行的桌面應用程式版本:

696 

697* **macOS**:點擊選單列中的 **Claude**,然後點擊 **About Claude**

698* **Windows**:點擊 **Help**,然後點擊 **About**

699 

700點擊版本號以將其複製到您的剪貼簿。

701 

702### Code 標籤中的 403 或驗證錯誤

703 

704如果在使用 Code 標籤時看到 `Error 403: Forbidden` 或其他驗證失敗:

705 

7061. 從應用程式選單登出並重新登入。這是最常見的修復。

7072. 驗證您有有效的付費訂閱:Pro、Max、Team 或 Enterprise。

7083. 如果 CLI 有效但 Desktop 無效,完全退出桌面應用程式(不只是關閉視窗),然後重新開啟並登入。

7094. 檢查您的網際網路連線和代理設定。

710 

711### 啟動時螢幕空白或卡住

712 

713如果應用程式開啟但顯示空白或無反應的螢幕:

714 

7151. 重新啟動應用程式。

7162. 檢查待處理的更新。應用程式在啟動時自動更新。

7173. 在 Windows 上,檢查「事件檢視器」中的 **Windows 日誌 → 應用程式** 下的當機日誌。

718 

719### 「無法載入會話」

720 

721如果您看到 `Failed to load session`,選定的資料夾可能不再存在、Git 儲存庫可能需要未安裝的 Git LFS,或檔案權限可能阻止存取。嘗試選擇不同的資料夾或重新啟動應用程式。

722 

723### 會話找不到已安裝的工具

724 

725如果 Claude 找不到 `npm`、`node` 或其他 CLI 命令等工具,請驗證工具在您的常規終端機中有效、檢查您的 shell 設定檔是否正確設定 PATH,並重新啟動桌面應用程式以重新載入環境變數。

726 

727### Git 和 Git LFS 錯誤

728 

729在 Windows 上,Git 是啟動本機會話的 Code 標籤所需的。如果您看到「Git is required」,請安裝 [Git for Windows](https://git-scm.com/downloads/win) 並重新啟動應用程式。

730 

731如果您看到「Git LFS is required by this repository but is not installed」,請從 [git-lfs.com](https://git-lfs.com/) 安裝 Git LFS,執行 `git lfs install`,然後重新啟動應用程式。

732 

733### Windows 上的 MCP servers 無法運作

734 

735如果 MCP server 切換沒有回應或伺服器在 Windows 上無法連接,請檢查伺服器是否在您的設定中正確配置、重新啟動應用程式、驗證伺服器程序在工作管理員中執行,並檢查伺服器日誌以查看連線錯誤。

736 

737### 應用程式無法退出

738 

739* **macOS**:按 Cmd+Q。如果應用程式沒有回應,使用 Cmd+Option+Esc 強制退出,選擇 Claude,然後點擊「強制退出」。

740* **Windows**:使用 Ctrl+Shift+Esc 的工作管理員來結束 Claude 程序。

741 

742### Windows 特定問題

743 

744* **安裝後 PATH 未更新**:開啟新的終端機視窗。PATH 更新僅適用於新的終端機會話。

745* **並行安裝錯誤**:如果您看到有關另一個安裝進行中的錯誤,但實際上沒有,請嘗試以管理員身份執行安裝程式。

746 

747### 在 CLI 中開啟時「分支尚不存在」

748 

749遠端會話可以建立在您的本機機器上不存在的分支。點擊會話工具列中的分支名稱以複製它,然後在本機提取它:

750 

751```bash theme={null}

752git fetch origin <branch-name>

753git checkout <branch-name>

754```

755 

756### 仍然卡住?

757 

758* 在 [GitHub Issues](https://github.com/anthropics/claude-code/issues) 上搜尋或提交錯誤

759* 造訪 [Claude 支援中心](https://support.claude.com/)

760 

761提交錯誤時,包括您的桌面應用程式版本、您的作業系統、確切的錯誤訊息和相關日誌。在 macOS 上,檢查 Console.app。在 Windows 上,檢查「事件檢視器」→「Windows 日誌」→「應用程式」。

desktop-quickstart.md +129 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 開始使用桌面應用程式

6 

7> 在桌面上安裝 Claude Code 並開始您的第一個編碼會話

8 

9桌面應用程式為您提供具有圖形介面的 Claude Code,專為並行執行多個會話而設計:用於管理並行工作的側邊欄、具有整合終端機和檔案編輯器的拖放式佈局、視覺化差異檢查、即時應用程式預覽、GitHub PR 監控與自動合併,以及排程任務。無需終端機。

10 

11<CardGroup cols={2}>

12 <Card title="Download for macOS" icon="apple" href="https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code&utm_medium=docs">

13 Universal build for Intel and Apple Silicon

14 </Card>

15 

16 <Card title="Download for Windows" icon="windows" href="https://claude.ai/api/desktop/win32/x64/setup/latest/redirect?utm_source=claude_code&utm_medium=docs">

17 For x64 processors

18 </Card>

19</CardGroup>

20 

21For Windows ARM64, download the [ARM64 installer](https://claude.ai/api/desktop/win32/arm64/setup/latest/redirect?utm_source=claude_code\&utm_medium=docs). The desktop app is not available on Linux; use the [CLI](/en/quickstart) instead.

22 

23<Note>

24 Claude Code 需要 [Pro、Max、Team 或 Enterprise 訂閱](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=desktop_quickstart_pricing)。

25</Note>

26 

27本頁面將引導您安裝應用程式並開始您的第一個會話。如果您已經設定完成,請參閱 [使用 Claude Code Desktop](/zh-TW/desktop) 以取得完整參考。

28 

29桌面應用程式有三個標籤:

30 

31* **Chat**:無檔案存取的一般對話,類似於 claude.ai。

32* **Cowork**:一個自主背景代理,在雲端 VM 中處理任務,具有自己的環境。它可以獨立執行,同時您進行其他工作。

33* **Code**:具有直接存取本機檔案的互動式編碼助手。您可以即時檢查並批准每項變更。

34 

35Chat 和 Cowork 涵蓋在 [Claude Desktop 支援文章](https://support.claude.com/en/collections/16163169-claude-desktop) 中。本頁面重點關注 **Code** 標籤。

36 

37## 安裝

38 

39<Steps>

40 <Step title="安裝並登入">

41 從上方連結下載您平台的安裝程式並執行它。從 macOS 上的應用程式資料夾或 Windows 上的開始功能表啟動 Claude,然後使用您的 Anthropic 帳戶登入。

42 </Step>

43 

44 <Step title="開啟 Code 標籤">

45 點擊頂部中央的 **Code** 標籤。如果點擊 Code 提示您升級,您需要先 [訂閱付費方案](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=desktop_quickstart_upgrade)。如果它提示您線上登入,請完成登入並重新啟動應用程式。如果您看到 403 錯誤,請參閱 [驗證疑難排解](/zh-TW/desktop#403-or-authentication-errors-in-the-code-tab)。

46 </Step>

47</Steps>

48 

49桌面應用程式包含 Claude Code。您無需單獨安裝 Node.js 或 CLI。若要從終端機使用 `claude`,請單獨安裝 CLI。請參閱 [開始使用 CLI](/zh-TW/quickstart)。

50 

51## 開始您的第一個會話

52 

53開啟 Code 標籤後,選擇一個專案並給 Claude 一些工作。

54 

55<Steps>

56 <Step title="選擇環境和資料夾">

57 選擇 **Local** 以在您的機器上執行 Claude,直接使用您的檔案。點擊 **Select folder** 並選擇您的專案目錄。

58 

59 <Tip>

60 從您熟悉的小型專案開始。這是查看 Claude Code 能做什麼的最快方式。在 Windows 上,必須安裝 [Git](https://git-scm.com/downloads/win) 才能使本機會話正常運作。大多數 Mac 預設包含 Git。

61 </Tip>

62 

63 您也可以選擇:

64 

65 * **Remote**:在 Anthropic 的雲端基礎設施上執行會話,即使您關閉應用程式也會繼續。遠端會話使用與 [Claude Code on the web](/zh-TW/claude-code-on-the-web) 相同的基礎設施。

66 * **SSH**:透過 SSH 連接到遠端機器(您自己的伺服器、雲端 VM 或開發容器)。Claude Code 必須安裝在遠端機器上。

67 </Step>

68 

69 <Step title="選擇模型">

70 從傳送按鈕旁的下拉式選單中選擇模型。請參閱 [models](/zh-TW/model-config#available-models) 以比較 Opus、Sonnet 和 Haiku。您可以稍後從相同的下拉式選單變更模型。

71 </Step>

72 

73 <Step title="告訴 Claude 要做什麼">

74 輸入您想要 Claude 做的事情:

75 

76 * `Find a TODO comment and fix it`

77 * `Add tests for the main function`

78 * `Create a CLAUDE.md with instructions for this codebase`

79 

80 [會話](/zh-TW/desktop#work-in-parallel-with-sessions) 是與 Claude 關於您的程式碼的對話。每個會話追蹤自己的上下文和變更,因此您可以處理多個任務而不會相互干擾。

81 </Step>

82 

83 <Step title="檢查並接受變更">

84 預設情況下,Code 標籤以 [詢問權限模式](/zh-TW/desktop#choose-a-permission-mode) 啟動,其中 Claude 提出變更並等待您的批准才能應用它們。您將看到:

85 

86 1. [差異檢視](/zh-TW/desktop#review-changes-with-diff-view) 顯示每個檔案中將發生的確切變更

87 2. 接受/拒絕按鈕以批准或拒絕每項變更

88 3. Claude 處理您的請求時的即時更新

89 

90 如果您拒絕變更,Claude 將詢問您希望如何以不同方式進行。在您接受之前,您的檔案不會被修改。

91 </Step>

92</Steps>

93 

94## 接下來呢?

95 

96您已進行了第一次編輯。如需 Desktop 可執行的所有操作的完整參考,請參閱 [使用 Claude Code Desktop](/zh-TW/desktop)。以下是一些接下來要嘗試的事項。

97 

98**中斷並引導。** 您可以隨時中斷 Claude。如果它走錯了方向,點擊停止按鈕或輸入您的更正並按 **Enter**。Claude 停止正在進行的操作並根據您的輸入進行調整。您無需等待它完成或重新開始。

99 

100**給 Claude 更多上下文。** 在提示框中輸入 `@filename` 以將特定檔案拉入對話,使用附件按鈕附加影像和 PDF,或直接將檔案拖放到提示中。Claude 擁有的上下文越多,結果越好。請參閱 [新增檔案和上下文](/zh-TW/desktop#add-files-and-context-to-prompts)。

101 

102**使用 skills 執行可重複的任務。** 輸入 `/` 或點擊 **+** → **Slash commands** 以瀏覽 [內建命令](/zh-TW/commands)、[自訂 skills](/zh-TW/skills) 和外掛程式 skills。Skills 是可重複使用的提示,您可以在需要時調用,例如程式碼檢查清單或部署步驟。

103 

104**在提交前檢查變更。** Claude 編輯檔案後,會出現 `+12 -1` 指示器。點擊它以開啟 [差異檢視](/zh-TW/desktop#review-changes-with-diff-view),逐個檔案檢查修改,並在特定行上評論。Claude 讀取您的評論並進行修訂。點擊 **Review code** 讓 Claude 自己評估差異並留下內聯建議。

105 

106**調整您擁有的控制量。** 您的 [權限模式](/zh-TW/desktop#choose-a-permission-mode) 控制平衡。詢問權限(預設)在每次編輯前需要批准。自動接受編輯會自動接受檔案編輯以加快迭代。Plan Mode 讓 Claude 在不觸及任何檔案的情況下規劃方法,這在大型重構前很有用。

107 

108**新增外掛程式以獲得更多功能。** 點擊提示框旁的 **+** 按鈕並選擇 **Plugins** 以瀏覽並安裝 [外掛程式](/zh-TW/desktop#install-plugins),這些外掛程式新增 skills、代理、MCP servers 等。

109 

110**排列您的工作區。** 將聊天、差異、終端機、檔案和預覽窗格拖放到您想要的任何佈局中。使用 **Ctrl+\`** 開啟終端機以在您的會話旁執行命令,或點擊檔案路徑以在檔案窗格中開啟它。請參閱 [排列您的工作區](/zh-TW/desktop#arrange-your-workspace)。

111 

112**預覽您的應用程式。** 點擊 **Preview** 下拉式選單以直接在桌面中執行您的開發伺服器。Claude 可以檢視執行中的應用程式、測試端點、檢查日誌並對其看到的內容進行迭代。請參閱 [預覽您的應用程式](/zh-TW/desktop#preview-your-app)。

113 

114**追蹤您的提取請求。** 開啟 PR 後,Claude Code 監控 CI 檢查結果,並可以自動修復失敗或在所有檢查通過後合併 PR。請參閱 [監控提取請求狀態](/zh-TW/desktop#monitor-pull-request-status)。

115 

116**將 Claude 放在排程上。** 設定 [排程任務](/zh-TW/desktop-scheduled-tasks) 以定期自動執行 Claude:每天早上進行程式碼檢查、每週進行依賴項審計,或從您連接的工具中提取的簡報。

117 

118**準備好時擴展。** 從側邊欄開啟 [並行會話](/zh-TW/desktop#work-in-parallel-with-sessions) 以同時處理多個任務,每個任務都在自己的 Git worktree 中,並開啟 [任務窗格](/zh-TW/desktop#watch-background-tasks) 以監看會話正在執行的子代理和背景命令。開啟 [側邊聊天](/zh-TW/desktop#ask-a-side-question-without-derailing-the-session) 以提出問題而不會偏離主線。將 [長期執行的工作發送到雲端](/zh-TW/desktop#run-long-running-tasks-remotely),以便即使您關閉應用程式也會繼續,或 [在網路或 IDE 中繼續會話](/zh-TW/desktop#continue-in-another-surface)(如果任務花費的時間比預期長)。[連接外部工具](/zh-TW/desktop#extend-claude-code),例如 GitHub、Slack 和 Linear,以整合您的工作流程。

119 

120## 來自 CLI?

121 

122Desktop 使用與 CLI 相同的引擎,但具有圖形介面。您可以在同一專案上同時執行兩者,它們共享配置(CLAUDE.md 檔案、MCP servers、hooks、skills 和設定)。如需功能、標誌等效項和 Desktop 中不可用的內容的完整比較,請參閱 [CLI 比較](/zh-TW/desktop#coming-from-the-cli)。

123 

124## 接下來

125 

126* [使用 Claude Code Desktop](/zh-TW/desktop):權限模式、並行會話、差異檢視、連接器和企業配置

127* [疑難排解](/zh-TW/desktop#troubleshooting):常見錯誤和設定問題的解決方案

128* [最佳實踐](/zh-TW/best-practices):撰寫有效提示和充分利用 Claude Code 的提示

129* [常見工作流程](/zh-TW/common-workflows):除錯、重構、測試等的教學課程

devcontainer.md +194 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 開發容器

6 

7> 在開發容器中執行 Claude Code,為您的團隊提供一致、隔離的環境。

8 

9[開發容器](https://containers.dev/)(或 dev container)讓您定義一個相同的隔離環境,您的團隊中的每位工程師都可以執行。安裝 Claude Code 在該容器中後,Claude 執行的命令會在容器內執行,而不是在主機上執行,同時對您的專案檔案的編輯會在您工作時出現在本地儲存庫中。

10 

11本頁涵蓋[在開發容器中安裝 Claude Code](#add-claude-code-to-your-dev-container) 以及隨後的配置主題。每個主題都是獨立的,因此請跳轉到與您需要設定的內容相符的主題:

12 

13* [在重新構建時保持身份驗證和設定](#persist-authentication-and-settings-across-rebuilds)

14* [強制執行組織政策](#enforce-organization-policy)

15* [限制網路出站流量](#restrict-network-egress)

16* [無需權限提示即可執行](#run-without-permission-prompts)

17 

18<Warning>

19 雖然開發容器提供了大量保護,但沒有任何系統完全免疫所有攻擊。

20 當使用 `--dangerously-skip-permissions` 執行時,開發容器不會阻止惡意專案從容器內可存取的任何內容(包括儲存在 [`~/.claude`](/zh-TW/claude-directory) 中的 Claude Code 認證)進行資料外洩。

21 僅在使用受信任的儲存庫進行開發時使用開發容器,並監控 Claude 的活動。

22 避免將主機祕密(例如 `~/.ssh` 或雲端認證檔案)掛載到容器中;優先使用儲存庫範圍或短期有效的令牌。

23</Warning>

24 

25<Accordion title="開發容器如何與您的編輯器配合使用">

26 <img src="https://mintcdn.com/claude-code/YvJyjZfd9yMihr0i/images/devcontainer-architecture.svg?fit=max&auto=format&n=YvJyjZfd9yMihr0i&q=85&s=9017b1d16a446c6cc37ba562f35b9aae" className="dark:hidden" alt="顯示主機上的編輯器連接到 Docker 開發容器的圖表。Claude Code、終端和構建工具在容器內執行。主機儲存庫被綁定掛載到容器中作為工作區。" width="640" height="300" data-path="images/devcontainer-architecture.svg" />

27 

28 <img src="https://mintcdn.com/claude-code/YvJyjZfd9yMihr0i/images/devcontainer-architecture-dark.svg?fit=max&auto=format&n=YvJyjZfd9yMihr0i&q=85&s=ef00c8e25b1ea7a3a152895f1488831b" className="hidden dark:block" alt="顯示主機上的編輯器連接到 Docker 開發容器的圖表。Claude Code、終端和構建工具在容器內執行。主機儲存庫被綁定掛載到容器中作為工作區。" width="640" height="300" data-path="images/devcontainer-architecture-dark.svg" />

29 

30 開發容器作為 Docker 容器執行,可以在您的機器上或雲端主機(例如 GitHub Codespaces)上執行。支援 Dev Containers 規範的編輯器(例如 VS Code、GitHub Codespaces、JetBrains IDE 或 Cursor)連接到該容器:您在編輯器中照常瀏覽和編輯檔案,但整合終端、語言伺服器和構建工具都在容器內執行,而不是在您的主機上。不支援開發容器的編輯器(例如純 Vim)不是此工作流程的一部分。

31 

32 Claude Code 在容器內執行,因此它看到與您的專案工具鏈其餘部分相同的檔案、依賴項和工具。在 VS Code 中,您可以使用 [Claude Code 擴充功能面板](/zh-TW/vs-code) 或在整合終端中執行 `claude`;兩者都在容器內執行並共享相同的 `~/.claude` 配置。

33</Accordion>

34 

35## 在開發容器中新增 Claude Code

36 

37Claude Code 透過 [Claude Code Dev Container Feature](https://github.com/anthropics/devcontainer-features/tree/main/src/claude-code) 安裝到任何開發容器中。

38 

39這些設定適用於任何支援 Dev Containers 規範的工具,例如 VS Code、GitHub Codespaces 或 JetBrains IDE。下面的步驟以 VS Code 為例。

40 

41當您在 VS Code 或 Codespaces 中開啟容器時,該功能還會新增 Claude Code VS Code 擴充功能;其他編輯器會忽略該部分。

42 

43<Tip>

44 初次接觸開發容器?[VS Code Dev Containers 教程](https://code.visualstudio.com/docs/devcontainers/tutorial)會逐步介紹安裝 Docker、擴充功能和開啟您的第一個容器。如需更完整的強化示例(包含防火牆和持久磁碟區),請參閱[試用參考容器](#try-the-reference-container)。

45</Tip>

46 

47<Steps>

48 <Step title="建立或更新 devcontainer.json">

49 將以下內容儲存為儲存庫中的 `.devcontainer/devcontainer.json`,或將 `features` 區塊新增到您現有的檔案中。

50 

51 末尾的版本標籤(例如 `:1.0`)會固定功能的安裝指令碼,而不是 Claude Code 版本。該功能會安裝最新的 Claude Code,Claude Code 預設會在容器內自動更新。

52 

53 若要固定 CLI 版本或停用自動更新,請參閱[強制執行組織政策](#enforce-organization-policy)。

54 

55 ```json .devcontainer/devcontainer.json theme={null}

56 {

57 "image": "mcr.microsoft.com/devcontainers/base:ubuntu",

58 "features": {

59 "ghcr.io/anthropics/devcontainer-features/claude-code:1.0": {}

60 }

61 }

62 ```

63 

64 將 `image` 行替換為您的專案的基礎映像,或如果您現有的檔案使用 Dockerfile,則將其移除。

65 </Step>

66 

67 <Step title="重新構建容器">

68 在 Mac 上使用 `Cmd+Shift+P` 或在 Windows 和 Linux 上使用 `Ctrl+Shift+P` 開啟 VS Code 命令面板,並執行 **Dev Containers: Rebuild Container**。

69 

70 對於其他工具,請遵循該工具的重新構建操作:請參閱 [GitHub Codespaces 中的重新構建](https://docs.github.com/en/codespaces/developing-in-a-codespace/rebuilding-the-container-in-a-codespace)、[Dev Containers CLI](https://github.com/devcontainers/cli) 或您的 IDE 的開發容器文件。

71 </Step>

72 

73 <Step title="登入 Claude Code">

74 在重新構建的容器中開啟終端並執行 `claude`,然後按照身份驗證提示進行操作。

75 </Step>

76</Steps>

77 

78您在身份驗證提示中看到的內容取決於您的提供者:

79 

80* **Anthropic**:透過瀏覽器使用您的 Claude 或 Anthropic Console 帳戶登入

81* **[Amazon Bedrock、Google Vertex AI 或 Microsoft Foundry](/zh-TW/third-party-integrations)**:Claude Code 使用您的雲端提供者認證,無需瀏覽器提示

82 

83對於雲端提供者,透過 `containerEnv`、Codespaces 祕密或您的雲端的工作負載身份(而不是從主機掛載認證檔案)將認證傳遞到容器中。請參閱 [Amazon Bedrock](/zh-TW/amazon-bedrock)、[Google Vertex AI](/zh-TW/google-vertex-ai) 或 [Microsoft Foundry](/zh-TW/microsoft-foundry) 以了解 Claude Code 讀取的認證鏈。

84 

85請參閱[選擇您的 API 提供者](/zh-TW/admin-setup#choose-your-api-provider)以決定哪條路徑適合您的組織。

86 

87<Note>

88 如果瀏覽器登入完成但回調從未到達容器,請複製瀏覽器中顯示的代碼,並將其貼上到終端中的 `Paste code here if prompted` 提示處。當編輯器的連接埠轉發不會路由 localhost 回調時,可能會發生這種情況。

89</Note>

90 

91## 在重新構建時保持身份驗證和設定

92 

93預設情況下,容器的主目錄在重新構建時會被丟棄,因此工程師必須每次都重新登入。Claude Code 將其身份驗證令牌、使用者設定和工作階段歷史記錄儲存在 [`~/.claude`](/zh-TW/claude-directory) 下。在該路徑掛載一個命名磁碟區以在重新構建時保持此狀態。

94 

95以下示例在 `node` 使用者的主目錄掛載一個磁碟區:

96 

97```json devcontainer.json theme={null}

98"mounts": [

99 "source=claude-code-config,target=/home/node/.claude,type=volume"

100]

101```

102 

103將 `/home/node` 替換為您的容器的 `remoteUser` 的主目錄。如果您在 `~/.claude` 以外的位置掛載磁碟區,請設定 [`CLAUDE_CONFIG_DIR`](/zh-TW/env-vars) 為掛載路徑,以便 Claude Code 在那裡讀取和寫入。

104 

105若要隔離每個專案的狀態,而不是在所有儲存庫中共享一個磁碟區,請在來源名稱中包含 `${devcontainerId}` 變數。[參考配置](https://github.com/anthropics/claude-code/blob/main/.devcontainer/devcontainer.json)為此目的使用 `source=claude-code-config-${devcontainerId}`。

106 

107在 GitHub Codespaces 中,`~/.claude` 在停止和啟動 codespace 時會保持,但在重新構建容器時仍會被清除,因此上面的磁碟區掛載也適用於此。若要在 codespace 之間進行身份驗證,請將 `ANTHROPIC_API_KEY` 或來自 [`claude setup-token`](/zh-TW/authentication#generate-a-long-lived-token) 的 `CLAUDE_CODE_OAUTH_TOKEN` 儲存為 [Codespaces 祕密](https://docs.github.com/en/codespaces/managing-your-codespaces/managing-your-account-specific-secrets-for-github-codespaces);Codespaces 會自動將祕密作為環境變數提供給容器內。

108 

109## 強制執行組織政策

110 

111開發容器是應用組織政策的便利場所,因為相同的映像和配置在每位工程師的機器上執行。

112 

113Claude Code 在 Linux 上讀取 `/etc/claude-code/managed-settings.json` 並在[設定層級結構](/zh-TW/settings#how-scopes-interact)中以最高優先級應用它,因此那裡的值會覆蓋工程師在 `~/.claude` 或專案的 `.claude/` 目錄中設定的任何內容。從您的 Dockerfile 複製檔案到位置:

114 

115```dockerfile Dockerfile theme={null}

116RUN mkdir -p /etc/claude-code

117COPY managed-settings.json /etc/claude-code/managed-settings.json

118```

119 

120因為 Dockerfile 存在於儲存庫中,任何具有寫入存取權限的人都可以更改或移除此步驟。對於工程師無法透過編輯儲存庫檔案來繞過的政策,請透過[伺服器管理的設定](/zh-TW/server-managed-settings)或您的 MDM 提供託管設定。請參閱[託管設定檔案](/zh-TW/settings#settings-files)以了解可用的鍵和其他傳遞路徑。

121 

122若要設定適用於容器中每個 Claude Code 工作階段的[環境變數](/zh-TW/env-vars),請將它們新增到您的 `devcontainer.json` 中的 `containerEnv`。以下示例選擇退出遙測和錯誤報告,並防止 Claude Code 在安裝後自動更新:

123 

124```json devcontainer.json theme={null}

125"containerEnv": {

126 "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",

127 "DISABLE_AUTOUPDATER": "1"

128}

129```

130 

131Dev Container Feature 始終安裝最新的 Claude Code 版本。若要為可重現的構建固定特定的 Claude Code 版本,請從您的 Dockerfile 使用 `npm install -g @anthropic-ai/claude-code@X.Y.Z` 安裝它,而不是使用該功能,並設定 `DISABLE_AUTOUPDATER`,如上所示。

132 

133如需完整的政策控制清單(包括權限規則、工具限制和 MCP 伺服器允許清單),請參閱[為您的組織設定 Claude Code](/zh-TW/admin-setup)。

134 

135若要在容器內提供 [MCP 伺服器](/zh-TW/mcp),請在儲存庫根目錄的 `.mcp.json` 檔案中以[專案範圍](/zh-TW/mcp#mcp-installation-scopes)定義它們,以便它們與您的開發容器配置一起簽入。在您的 Dockerfile 中安裝本地 stdio 伺服器所依賴的任何二進位檔案,並將遠端伺服器網域新增到您的網路允許清單。

136 

137## 限制網路出站流量

138 

139您可以將容器的出站流量限制為僅 Claude Code 需要的網域。請參閱[網路存取要求](/zh-TW/network-config#network-access-requirements)以了解推理和身份驗證網域,以及[遙測服務](/zh-TW/data-usage#telemetry-services)以了解可選的遙測和錯誤報告連接以及如何停用它們。

140 

141參考容器包含一個 [`init-firewall.sh`](https://github.com/anthropics/claude-code/blob/main/.devcontainer/init-firewall.sh) 指令碼,該指令碼會阻止除 Claude Code 和您的開發工具需要的網域之外的所有出站流量。在容器內執行防火牆需要額外的權限,因此參考透過 `runArgs` 新增 `NET_ADMIN` 和 `NET_RAW` 功能。防火牆指令碼和這些功能對 Claude Code 本身不是必需的:您可以將它們省略並改為依賴您自己的網路控制。

142 

143## 無需權限提示即可執行

144 

145因為容器以非 root 使用者身份執行 Claude Code 並將命令執行限制在容器內,您可以傳遞 `--dangerously-skip-permissions` 以進行無人值守操作。當以 root 身份啟動時,CLI 會拒絕此標誌,因此請確認 `remoteUser` 設定為非 root 帳戶。

146 

147跳過權限提示會移除您在工具呼叫執行前進行審查的機會。Claude 仍然可以修改綁定掛載工作區中的任何檔案(該檔案直接出現在您的主機上),並到達容器的網路政策允許的任何內容。將此標誌與上面的[網路出站流量限制](#restrict-network-egress)配對,以限制繞過的工作階段可以到達的內容。

148 

149如果您想要更少的提示而不停用安全檢查,請考慮改為[自動模式](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode),該模式具有在執行前審查操作的分類器。若要完全防止工程師使用 `--dangerously-skip-permissions`,請在[託管設定](/zh-TW/settings#permission-settings)中將 `permissions.disableBypassPermissionsMode` 設定為 `"disable"`。

150 

151## 試用參考容器

152 

153[`anthropics/claude-code`](https://github.com/anthropics/claude-code/tree/main/.devcontainer) 儲存庫包含一個示例開發容器,該容器結合了 CLI、出站防火牆、持久磁碟區和基於 Zsh 的 shell。它作為工作示例而不是維護的基礎映像提供;在將它們應用到您自己的配置之前,使用它來查看這些部分如何組合在一起。

154 

155<Steps>

156 <Step title="安裝先決條件">

157 安裝 VS Code 和 [Dev Containers 擴充功能](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers)。

158 </Step>

159 

160 <Step title="複製參考">

161 複製 [Claude Code 儲存庫](https://github.com/anthropics/claude-code)並在 VS Code 中開啟它。

162 </Step>

163 

164 <Step title="在容器中重新開啟">

165 出現提示時,點擊 **Reopen in Container**,或從命令面板執行 **Dev Containers: Reopen in Container**。

166 </Step>

167 

168 <Step title="啟動 Claude Code">

169 容器完成構建後,使用 `` Ctrl+` `` 開啟終端並執行 `claude` 以登入並啟動您的第一個工作階段。

170 </Step>

171</Steps>

172 

173若要將此配置用於您自己的專案,請將 `.devcontainer/` 目錄複製到您的儲存庫中並根據您的工具鏈調整 Dockerfile,或返回[在開發容器中新增 Claude Code](#add-claude-code-to-your-dev-container) 以僅將功能新增到您已有的設定中。

174 

175參考配置由三個檔案組成。當您透過功能將 Claude Code 新增到您自己的開發容器時,這些都不是必需的,但它們展示了一種組合這些部分的方式。

176 

177| 檔案 | 目的 |

178| ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |

179| [`devcontainer.json`](https://github.com/anthropics/claude-code/blob/main/.devcontainer/devcontainer.json) | 磁碟區掛載、`runArgs` 功能、VS Code 擴充功能和 `containerEnv` |

180| [`Dockerfile`](https://github.com/anthropics/claude-code/blob/main/.devcontainer/Dockerfile) | 基礎映像、開發工具和 Claude Code 安裝 |

181| [`init-firewall.sh`](https://github.com/anthropics/claude-code/blob/main/.devcontainer/init-firewall.sh) | 阻止除允許的網域外的所有出站網路流量 |

182 

183## 後續步驟

184 

185Claude Code 在您的開發容器中執行後,下面的頁面涵蓋組織推出的其餘部分:選擇身份驗證路徑、在儲存庫外提供託管政策、監控使用情況以及了解 Claude Code 儲存和傳送的內容。

186 

187* [為您的組織設定 Claude Code](/zh-TW/admin-setup):選擇身份驗證提供者、決定政策如何到達裝置以及規劃推出

188* [伺服器管理的設定](/zh-TW/server-managed-settings):從 Claude.ai 管理員控制台提供託管政策,以便工程師無法透過編輯儲存庫檔案來繞過它

189* [監控使用情況和審計活動](/zh-TW/monitoring-usage):匯出 OpenTelemetry 指標並審查您的團隊正在執行的內容

190* [網路存取要求](/zh-TW/network-config#network-access-requirements):代理和防火牆的完整網域允許清單

191* [遙測服務和選擇退出](/zh-TW/data-usage#telemetry-services):Claude Code 預設傳送的內容以及停用它的環境變數

192* [探索 `.claude` 目錄](/zh-TW/claude-directory):磁碟區掛載包含的內容,包括認證、設定和工作階段歷史記錄

193* [安全模型](/zh-TW/security):Claude Code 的權限系統、沙箱和提示注入保護如何組合在一起

194* [權限模式](/zh-TW/permission-modes):從計劃模式到自動模式到繞過的完整範圍,以及何時使用每種模式

discover-plugins.md +427 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 透過市場探索和安裝預建外掛程式

6 

7> 從市場探索和安裝外掛程式,以使用新命令、代理和功能擴展 Claude Code。

8 

9外掛程式透過技能、代理、hooks 和 MCP servers 擴展 Claude Code。外掛程式市場是幫助您探索和安裝這些擴展的目錄,無需自己構建它們。

10 

11想要建立和分發您自己的市場?請參閱[建立和分發外掛程式市場](/zh-TW/plugin-marketplaces)。

12 

13## 市場如何運作

14 

15市場是他人建立和共享的外掛程式目錄。使用市場是一個兩步流程:

16 

17<Steps>

18 <Step title="新增市場">

19 這會向 Claude Code 註冊目錄,以便您可以瀏覽可用內容。尚未安裝任何外掛程式。

20 </Step>

21 

22 <Step title="安裝個別外掛程式">

23 瀏覽目錄並安裝您想要的外掛程式。

24 </Step>

25</Steps>

26 

27將其視為新增應用程式商店:新增商店可讓您存取瀏覽其集合,但您仍然可以選擇個別下載哪些應用程式。

28 

29## 官方 Anthropic 市場

30 

31官方 Anthropic 市場 (`claude-plugins-official`) 在您啟動 Claude Code 時自動可用。執行 `/plugin` 並前往 **Discover** 標籤以瀏覽可用內容,或在 [claude.com/plugins](https://claude.com/plugins) 查看目錄。

32 

33若要從官方市場安裝外掛程式,請使用 `/plugin install <name>@claude-plugins-official`。例如,若要安裝 GitHub 整合:

34 

35```shell theme={null}

36/plugin install github@claude-plugins-official

37```

38 

39<Note>

40 官方市場由 Anthropic 維護。若要將外掛程式提交到官方市場,請使用其中一個應用內提交表單:

41 

42 * **Claude.ai**: [claude.ai/settings/plugins/submit](https://claude.ai/settings/plugins/submit)

43 * **Console**: [platform.claude.com/plugins/submit](https://platform.claude.com/plugins/submit)

44 

45 若要獨立分發外掛程式,請[建立您自己的市場](/zh-TW/plugin-marketplaces)並與使用者共享。

46</Note>

47 

48官方市場包括多個外掛程式類別:

49 

50### 程式碼智能

51 

52程式碼智能外掛程式啟用 Claude Code 的內建 LSP 工具,使 Claude 能夠跳轉到定義、尋找參考資料,並在編輯後立即查看類型錯誤。這些外掛程式配置[語言伺服器協議](https://microsoft.github.io/language-server-protocol/)連接,這是為 VS Code 程式碼智能提供動力的相同技術。

53 

54這些外掛程式需要在您的系統上安裝語言伺服器二進位檔。如果您已經安裝了語言伺服器,當您開啟專案時,Claude 可能會提示您安裝相應的外掛程式。

55 

56| 語言 | 外掛程式 | 所需的二進位檔 |

57| :--------- | :------------------ | :--------------------------- |

58| C/C++ | `clangd-lsp` | `clangd` |

59| C# | `csharp-lsp` | `csharp-ls` |

60| Go | `gopls-lsp` | `gopls` |

61| Java | `jdtls-lsp` | `jdtls` |

62| Kotlin | `kotlin-lsp` | `kotlin-language-server` |

63| Lua | `lua-lsp` | `lua-language-server` |

64| PHP | `php-lsp` | `intelephense` |

65| Python | `pyright-lsp` | `pyright-langserver` |

66| Rust | `rust-analyzer-lsp` | `rust-analyzer` |

67| Swift | `swift-lsp` | `sourcekit-lsp` |

68| TypeScript | `typescript-lsp` | `typescript-language-server` |

69 

70您也可以[為其他語言建立您自己的 LSP 外掛程式](/zh-TW/plugins-reference#lsp-servers)。

71 

72<Note>

73 如果在安裝外掛程式後在 `/plugin` Errors 標籤中看到 `Executable not found in $PATH`,請從上表安裝所需的二進位檔。

74</Note>

75 

76#### Claude 從程式碼智能外掛程式獲得的功能

77 

78安裝程式碼智能外掛程式並且其語言伺服器二進位檔可用後,Claude 獲得兩項功能:

79 

80* **自動診斷**:在 Claude 進行每次檔案編輯後,語言伺服器分析變更並自動報告錯誤和警告。Claude 看到類型錯誤、遺漏的匯入和語法問題,無需執行編譯器或 linter。如果 Claude 引入錯誤,它會注意到並在同一輪中修復問題。這不需要超出安裝外掛程式的任何配置。當「找到診斷」指示器出現時,您可以按 **Ctrl+O** 來內聯查看診斷。

81* **程式碼導航**:Claude 可以使用語言伺服器跳轉到定義、尋找參考資料、懸停時取得類型資訊、列出符號、尋找實現和追蹤呼叫層次結構。這些操作為 Claude 提供比基於 grep 的搜尋更精確的導航,儘管可用性可能因語言和環境而異。

82 

83如果您遇到問題,請參閱[程式碼智能故障排除](#code-intelligence-issues)。

84 

85### 外部整合

86 

87這些外掛程式捆綁預先配置的 [MCP servers](/zh-TW/mcp),以便您可以連接 Claude 到外部服務,無需手動設定:

88 

89* **原始碼控制**:`github`、`gitlab`

90* **專案管理**:`atlassian`(Jira/Confluence)、`asana`、`linear`、`notion`

91* **設計**:`figma`

92* **基礎設施**:`vercel`、`firebase`、`supabase`

93* **通訊**:`slack`

94* **監控**:`sentry`

95 

96### 開發工作流程

97 

98為常見開發任務新增命令和代理的外掛程式:

99 

100* **commit-commands**:Git 提交工作流程,包括提交、推送和 PR 建立

101* **pr-review-toolkit**:用於審查拉取請求的專門代理

102* **agent-sdk-dev**:使用 Claude Agent SDK 構建的工具

103* **plugin-dev**:建立您自己的外掛程式的工具組

104 

105### 輸出樣式

106 

107自訂 Claude 的回應方式:

108 

109* **explanatory-output-style**:關於實現選擇的教育見解

110* **learning-output-style**:用於技能建立的互動式學習模式

111 

112## 試試看:新增演示市場

113 

114Anthropic 也維護一個[演示外掛程式市場](https://github.com/anthropics/claude-code/tree/main/plugins)(`claude-code-plugins`),其中包含展示外掛程式系統可能性的範例外掛程式。與官方市場不同,您需要手動新增此市場。

115 

116<Steps>

117 <Step title="新增市場">

118 在 Claude Code 中,為 `anthropics/claude-code` 市場執行 `plugin marketplace add` 命令:

119 

120 ```shell theme={null}

121 /plugin marketplace add anthropics/claude-code

122 ```

123 

124 這會下載市場目錄並使其外掛程式可供您使用。

125 </Step>

126 

127 <Step title="瀏覽可用外掛程式">

128 執行 `/plugin` 以開啟外掛程式管理器。這會開啟一個標籤式介面,其中有四個標籤,您可以使用 **Tab** 鍵(或 **Shift+Tab** 向後)循環瀏覽:

129 

130 * **Discover**:從所有市場瀏覽可用外掛程式

131 * **Installed**:檢視和管理已安裝的外掛程式

132 * **Marketplaces**:新增、移除或更新已新增的市場

133 * **Errors**:檢視任何外掛程式載入錯誤

134 

135 前往 **Discover** 標籤以查看您剛新增的市場中的外掛程式。

136 </Step>

137 

138 <Step title="安裝外掛程式">

139 選擇外掛程式以檢視其詳細資訊,然後選擇安裝範圍:

140 

141 * **User scope**:在所有專案中為自己安裝

142 * **Project scope**:為此儲存庫上的所有協作者安裝

143 * **Local scope**:僅在此儲存庫中為自己安裝

144 

145 例如,選擇 **commit-commands**(新增 git 工作流程命令的外掛程式)並將其安裝到您的使用者範圍。

146 

147 您也可以直接從命令列安裝:

148 

149 ```shell theme={null}

150 /plugin install commit-commands@anthropics-claude-code

151 ```

152 

153 請參閱[配置範圍](/zh-TW/settings#configuration-scopes)以深入瞭解範圍。

154 </Step>

155 

156 <Step title="使用您的新外掛程式">

157 安裝後,執行 `/reload-plugins` 以啟動外掛程式。外掛程式命令由外掛程式名稱命名空間,因此 **commit-commands** 提供 `/commit-commands:commit` 之類的命令。

158 

159 透過對檔案進行變更並執行以下命令來試試看:

160 

161 ```shell theme={null}

162 /commit-commands:commit

163 ```

164 

165 這會暫存您的變更、產生提交訊息並建立提交。

166 

167 每個外掛程式的工作方式不同。檢查 **Discover** 標籤中的外掛程式描述或其首頁,以瞭解它提供的命令和功能。

168 </Step>

169</Steps>

170 

171本指南的其餘部分涵蓋了您可以新增市場、安裝外掛程式和管理配置的所有方式。

172 

173## 新增市場

174 

175使用 `/plugin marketplace add` 命令從不同來源新增市場。

176 

177<Tip>

178 **快捷方式**:您可以使用 `/plugin market` 代替 `/plugin marketplace`,以及 `rm` 代替 `remove`。

179</Tip>

180 

181* **GitHub 儲存庫**:`owner/repo` 格式(例如,`anthropics/claude-code`)

182* **Git URL**:任何 git 儲存庫 URL(GitLab、Bitbucket、自託管)

183* **本機路徑**:目錄或 `marketplace.json` 檔案的直接路徑

184* **遠端 URL**:託管 `marketplace.json` 檔案的直接 URL

185 

186### 從 GitHub 新增

187 

188使用 `owner/repo` 格式新增包含 `.claude-plugin/marketplace.json` 檔案的 GitHub 儲存庫,其中 `owner` 是 GitHub 使用者名稱或組織,`repo` 是儲存庫名稱。

189 

190例如,`anthropics/claude-code` 指的是由 `anthropics` 擁有的 `claude-code` 儲存庫:

191 

192```shell theme={null}

193/plugin marketplace add anthropics/claude-code

194```

195 

196### 從其他 Git 主機新增

197 

198透過提供完整 URL 新增任何 git 儲存庫。這適用於任何 Git 主機,包括 GitLab、Bitbucket 和自託管伺服器:

199 

200使用 HTTPS:

201 

202```shell theme={null}

203/plugin marketplace add https://gitlab.com/company/plugins.git

204```

205 

206使用 SSH:

207 

208```shell theme={null}

209/plugin marketplace add git@gitlab.com:company/plugins.git

210```

211 

212若要新增特定分支或標籤,請在 `#` 後面附加 ref:

213 

214```shell theme={null}

215/plugin marketplace add https://gitlab.com/company/plugins.git#v1.0.0

216```

217 

218### 從本機路徑新增

219 

220新增包含 `.claude-plugin/marketplace.json` 檔案的本機目錄:

221 

222```shell theme={null}

223/plugin marketplace add ./my-marketplace

224```

225 

226您也可以新增 `marketplace.json` 檔案的直接路徑:

227 

228```shell theme={null}

229/plugin marketplace add ./path/to/marketplace.json

230```

231 

232### 從遠端 URL 新增

233 

234透過 URL 新增遠端 `marketplace.json` 檔案:

235 

236```shell theme={null}

237/plugin marketplace add https://example.com/marketplace.json

238```

239 

240<Note>

241 與基於 Git 的市場相比,基於 URL 的市場有一些限制。如果在安裝外掛程式時遇到「找不到路徑」錯誤,請參閱[故障排除](/zh-TW/plugin-marketplaces#plugins-with-relative-paths-fail-in-url-based-marketplaces)。

242</Note>

243 

244## 安裝外掛程式

245 

246新增市場後,您可以直接安裝外掛程式(預設安裝到使用者範圍):

247 

248```shell theme={null}

249/plugin install plugin-name@marketplace-name

250```

251 

252若要選擇不同的[安裝範圍](/zh-TW/settings#configuration-scopes),請使用互動式 UI:執行 `/plugin`,前往 **Discover** 標籤,然後在外掛程式上按 **Enter**。您將看到以下選項:

253 

254* **User scope**(預設):在所有專案中為自己安裝

255* **Project scope**:為此儲存庫上的所有協作者安裝(新增到 `.claude/settings.json`)

256* **Local scope**:僅在此儲存庫中為自己安裝(不與協作者共享)

257 

258您也可能看到具有 **managed** 範圍的外掛程式,這些是由管理員透過[受管設定](/zh-TW/settings#settings-files)安裝的,無法修改。

259 

260執行 `/plugin` 並前往 **Installed** 標籤以查看按範圍分組的外掛程式。

261 

262<Warning>

263 在安裝外掛程式之前,請確保您信任它。Anthropic 不控制外掛程式中包含的 MCP servers、檔案或其他軟體,也無法驗證它們是否按預期工作。檢查每個外掛程式的首頁以獲取更多資訊。

264</Warning>

265 

266## 管理已安裝的外掛程式

267 

268執行 `/plugin` 並前往 **Installed** 標籤以檢視、啟用、停用或解除安裝外掛程式。輸入以按外掛程式名稱或描述篩選清單。

269 

270您也可以使用直接命令管理外掛程式。

271 

272停用外掛程式而不解除安裝:

273 

274```shell theme={null}

275/plugin disable plugin-name@marketplace-name

276```

277 

278重新啟用已停用的外掛程式:

279 

280```shell theme={null}

281/plugin enable plugin-name@marketplace-name

282```

283 

284完全移除外掛程式:

285 

286```shell theme={null}

287/plugin uninstall plugin-name@marketplace-name

288```

289 

290`--scope` 選項可讓您使用 CLI 命令針對特定範圍:

291 

292```shell theme={null}

293claude plugin install formatter@your-org --scope project

294claude plugin uninstall formatter@your-org --scope project

295```

296 

297### 在不重新啟動的情況下套用外掛程式變更

298 

299當您在工作階段期間安裝、啟用或停用外掛程式時,執行 `/reload-plugins` 以在不重新啟動的情況下啟動所有變更:

300 

301```shell theme={null}

302/reload-plugins

303```

304 

305Claude Code 重新載入所有活動外掛程式,並顯示外掛程式、技能、代理、hooks、外掛程式 MCP servers 和外掛程式 LSP servers 的計數。

306 

307## 管理市場

308 

309您可以透過互動式 `/plugin` 介面或使用 CLI 命令管理市場。

310 

311### 使用互動式介面

312 

313執行 `/plugin` 並前往 **Marketplaces** 標籤以:

314 

315* 檢視所有已新增的市場及其來源和狀態

316* 新增新市場

317* 更新市場清單以取得最新外掛程式

318* 移除您不再需要的市場

319 

320### 使用 CLI 命令

321 

322您也可以使用直接命令管理市場。

323 

324列出所有已配置的市場:

325 

326```shell theme={null}

327/plugin marketplace list

328```

329 

330從市場重新整理外掛程式清單:

331 

332```shell theme={null}

333/plugin marketplace update marketplace-name

334```

335 

336移除市場:

337 

338```shell theme={null}

339/plugin marketplace remove marketplace-name

340```

341 

342<Warning>

343 移除市場將解除安裝您從中安裝的任何外掛程式。

344</Warning>

345 

346### 配置自動更新

347 

348Claude Code 可以在啟動時自動更新市場及其已安裝的外掛程式。為市場啟用自動更新後,Claude Code 會重新整理市場資料並將已安裝的外掛程式更新到其最新版本。如果任何外掛程式已更新,您將看到提示您執行 `/reload-plugins` 的通知。

349 

350透過 UI 為個別市場切換自動更新:

351 

3521. 執行 `/plugin` 以開啟外掛程式管理器

3532. 選擇 **Marketplaces**

3543. 從清單中選擇市場

3554. 選擇 **Enable auto-update** 或 **Disable auto-update**

356 

357官方 Anthropic 市場預設啟用自動更新。第三方和本機開發市場預設停用自動更新。

358 

359若要完全停用 Claude Code 和所有外掛程式的所有自動更新,請設定 `DISABLE_AUTOUPDATER` 環境變數。有關詳細資訊,請參閱[自動更新](/zh-TW/setup#auto-updates)。

360 

361若要在停用 Claude Code 自動更新的同時保持外掛程式自動更新啟用,請設定 `FORCE_AUTOUPDATE_PLUGINS=1` 以及 `DISABLE_AUTOUPDATER`:

362 

363```bash theme={null}

364export DISABLE_AUTOUPDATER=1

365export FORCE_AUTOUPDATE_PLUGINS=1

366```

367 

368當您想要手動管理 Claude Code 更新但仍然接收自動外掛程式更新時,這很有用。

369 

370## 配置團隊市場

371 

372團隊管理員可以透過將市場配置新增到 `.claude/settings.json` 來為專案設定自動市場安裝。當團隊成員信任儲存庫資料夾時,Claude Code 會提示他們安裝這些市場和外掛程式。

373 

374將 `extraKnownMarketplaces` 新增到您的專案的 `.claude/settings.json`:

375 

376```json theme={null}

377{

378 "extraKnownMarketplaces": {

379 "my-team-tools": {

380 "source": {

381 "source": "github",

382 "repo": "your-org/claude-plugins"

383 }

384 }

385 }

386}

387```

388 

389如需完整配置選項(包括 `extraKnownMarketplaces` 和 `enabledPlugins`),請參閱[外掛程式設定](/zh-TW/settings#plugin-settings)。

390 

391## 安全性

392 

393外掛程式和市場是高度受信任的元件,可以使用您的使用者權限在您的機器上執行任意程式碼。僅從您信任的來源安裝外掛程式和新增市場。組織可以使用[受管市場限制](/zh-TW/plugin-marketplaces#managed-marketplace-restrictions)限制使用者可以新增的市場。

394 

395## 故障排除

396 

397### /plugin 命令無法識別

398 

399如果您看到「未知命令」或 `/plugin` 命令未出現:

400 

4011. **檢查您的版本**:執行 `claude --version` 以查看已安裝的內容。

4022. **更新 Claude Code**:

403 * **Homebrew**:`brew upgrade claude-code`

404 * **npm**:`npm update -g @anthropic-ai/claude-code`

405 * **原生安裝程式**:從[設定](/zh-TW/setup)重新執行安裝命令

4063. **重新啟動 Claude Code**:更新後,重新啟動您的終端機並再次執行 `claude`。

407 

408### 常見問題

409 

410* **市場未載入**:驗證 URL 是否可存取以及 `.claude-plugin/marketplace.json` 是否存在於路徑中

411* **外掛程式安裝失敗**:檢查外掛程式來源 URL 是否可存取以及儲存庫是否為公開(或您有存取權)

412* **安裝後找不到檔案**:外掛程式被複製到快取中,因此參考外掛程式目錄外檔案的路徑將無法運作

413* **外掛程式技能未出現**:使用 `rm -rf ~/.claude/plugins/cache` 清除快取,重新啟動 Claude Code,然後重新安裝外掛程式。

414 

415如需詳細的故障排除和解決方案,請參閱市場指南中的[故障排除](/zh-TW/plugin-marketplaces#troubleshooting)。如需偵錯工具,請參閱[偵錯和開發工具](/zh-TW/plugins-reference#debugging-and-development-tools)。

416 

417### 程式碼智能問題

418 

419* **語言伺服器未啟動**:驗證二進位檔已安裝且在您的 `$PATH` 中可用。檢查 `/plugin` Errors 標籤以獲取詳細資訊。

420* **高記憶體使用量**:`rust-analyzer` 和 `pyright` 等語言伺服器在大型專案上可能會消耗大量記憶體。如果您遇到記憶體問題,請使用 `/plugin disable <plugin-name>` 停用外掛程式,並改為依賴 Claude 的內建搜尋工具。

421* **monorepos 中的誤報診斷**:如果工作區配置不正確,語言伺服器可能會報告內部套件的未解決匯入錯誤。這些不會影響 Claude 編輯程式碼的能力。

422 

423## 後續步驟

424 

425* **構建您自己的外掛程式**:請參閱[外掛程式](/zh-TW/plugins)以建立技能、代理和 hooks

426* **建立市場**:請參閱[建立外掛程式市場](/zh-TW/plugin-marketplaces)以將外掛程式分發給您的團隊或社群

427* **技術參考**:請參閱[外掛程式參考](/zh-TW/plugins-reference)以取得完整規格

env-vars.md +238 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 環境變數

6 

7> 控制 Claude Code 行為的環境變數完整參考。

8 

9Claude Code 支援以下環境變數來控制其行為。在啟動 `claude` 之前在您的 shell 中設定它們,或在 [`settings.json`](/zh-TW/settings#available-settings) 中的 `env` 鍵下配置它們,以將其應用於每個工作階段或在您的團隊中推出。

10 

11| 變數 | 用途 |

12| :------------------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

13| `ANTHROPIC_API_KEY` | API 金鑰作為 `X-Api-Key` 標頭發送。設定時,即使您已登入,此金鑰也會用於代替您的 Claude Pro、Max、Team 或 Enterprise 訂閱。在非互動式模式(`-p`)中,金鑰存在時始終使用。在互動式模式中,系統會提示您在金鑰覆蓋您的訂閱之前批准一次。若要改用您的訂閱,請執行 `unset ANTHROPIC_API_KEY` |

14| `ANTHROPIC_AUTH_TOKEN` | `Authorization` 標頭的自訂值(您在此設定的值將以 `Bearer ` 為前綴) |

15| `ANTHROPIC_BASE_URL` | 覆蓋 API 端點以透過代理或閘道路由請求。設定為非第一方主機時,[MCP tool search](/zh-TW/mcp#scale-with-mcp-tool-search) 預設停用。如果您的代理轉發 `tool_reference` 區塊,請設定 `ENABLE_TOOL_SEARCH=true` |

16| `ANTHROPIC_BEDROCK_BASE_URL` | 覆蓋 Bedrock 端點 URL。用於自訂 Bedrock 端點或透過 [LLM gateway](/zh-TW/llm-gateway) 路由。請參閱 [Amazon Bedrock](/zh-TW/amazon-bedrock) |

17| `ANTHROPIC_BEDROCK_MANTLE_BASE_URL` | 覆蓋 Bedrock Mantle 端點 URL。請參閱 [Mantle endpoint](/zh-TW/amazon-bedrock#use-the-mantle-endpoint) |

18| `ANTHROPIC_BEDROCK_SERVICE_TIER` | Bedrock [service tier](https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html)(`default`、`flex` 或 `priority`)。作為 `X-Amzn-Bedrock-Service-Tier` 標頭發送。請參閱 [Amazon Bedrock](/zh-TW/amazon-bedrock#service-tiers) |

19| `ANTHROPIC_BETAS` | 逗號分隔的其他 `anthropic-beta` 標頭值清單,以包含在 API 請求中。Claude Code 已發送其需要的 beta 標頭;使用此選項可在 Claude Code 新增原生支援之前選擇加入 [Anthropic API beta](https://platform.claude.com/docs/en/api/beta-headers)。與 [`--betas` 旗標](/zh-TW/cli-reference#cli-flags)(需要 API 金鑰驗證)不同,此變數適用於所有驗證方法,包括 Claude.ai 訂閱 |

20| `ANTHROPIC_CUSTOM_HEADERS` | 要新增至請求的自訂標頭(`Name: Value` 格式,多個標頭以換行符分隔) |

21| `ANTHROPIC_CUSTOM_MODEL_OPTION` | 要在 `/model` 選擇器中新增為自訂項目的模型 ID。使用此選項可使非標準或閘道特定的模型可選擇,而無需替換內建別名。請參閱 [Model configuration](/zh-TW/model-config#add-a-custom-model-option) |

22| `ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION` | `/model` 選擇器中自訂模型項目的顯示描述。未設定時預設為 `Custom model (<model-id>)` |

23| `ANTHROPIC_CUSTOM_MODEL_OPTION_NAME` | `/model` 選擇器中自訂模型項目的顯示名稱。未設定時預設為模型 ID |

24| `ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES` | 請參閱 [Model configuration](/zh-TW/model-config#customize-pinned-model-display-and-capabilities) |

25| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | 請參閱 [Model configuration](/zh-TW/model-config#environment-variables) |

26| `ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION` | 請參閱 [Model configuration](/zh-TW/model-config#customize-pinned-model-display-and-capabilities) |

27| `ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME` | 請參閱 [Model configuration](/zh-TW/model-config#customize-pinned-model-display-and-capabilities) |

28| `ANTHROPIC_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES` | 請參閱 [Model configuration](/zh-TW/model-config#customize-pinned-model-display-and-capabilities) |

29| `ANTHROPIC_DEFAULT_OPUS_MODEL` | 請參閱 [Model configuration](/zh-TW/model-config#environment-variables) |

30| `ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION` | 請參閱 [Model configuration](/zh-TW/model-config#customize-pinned-model-display-and-capabilities) |

31| `ANTHROPIC_DEFAULT_OPUS_MODEL_NAME` | 請參閱 [Model configuration](/zh-TW/model-config#customize-pinned-model-display-and-capabilities) |

32| `ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES` | 請參閱 [Model configuration](/zh-TW/model-config#customize-pinned-model-display-and-capabilities) |

33| `ANTHROPIC_DEFAULT_SONNET_MODEL` | 請參閱 [Model configuration](/zh-TW/model-config#environment-variables) |

34| `ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION` | 請參閱 [Model configuration](/zh-TW/model-config#customize-pinned-model-display-and-capabilities) |

35| `ANTHROPIC_DEFAULT_SONNET_MODEL_NAME` | 請參閱 [Model configuration](/zh-TW/model-config#customize-pinned-model-display-and-capabilities) |

36| `ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES` | 請參閱 [Model configuration](/zh-TW/model-config#customize-pinned-model-display-and-capabilities) |

37| `ANTHROPIC_FOUNDRY_API_KEY` | Microsoft Foundry 驗證的 API 金鑰(請參閱 [Microsoft Foundry](/zh-TW/microsoft-foundry)) |

38| `ANTHROPIC_FOUNDRY_BASE_URL` | Foundry 資源的完整基礎 URL(例如,`https://my-resource.services.ai.azure.com/anthropic`)。`ANTHROPIC_FOUNDRY_RESOURCE` 的替代方案(請參閱 [Microsoft Foundry](/zh-TW/microsoft-foundry)) |

39| `ANTHROPIC_FOUNDRY_RESOURCE` | Foundry 資源名稱(例如,`my-resource`)。如果未設定 `ANTHROPIC_FOUNDRY_BASE_URL`,則為必需(請參閱 [Microsoft Foundry](/zh-TW/microsoft-foundry)) |

40| `ANTHROPIC_MODEL` | 要使用的模型設定名稱(請參閱 [Model Configuration](/zh-TW/model-config#environment-variables)) |

41| `ANTHROPIC_SMALL_FAST_MODEL` | \[已棄用] [Haiku 級別模型用於背景任務](/zh-TW/costs)的名稱 |

42| `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | 使用 Bedrock 或 Bedrock Mantle 時覆蓋 Haiku 級別模型的 AWS 區域 |

43| `ANTHROPIC_VERTEX_BASE_URL` | 覆蓋 Vertex AI 端點 URL。用於自訂 Vertex 端點或透過 [LLM gateway](/zh-TW/llm-gateway) 路由。請參閱 [Google Vertex AI](/zh-TW/google-vertex-ai) |

44| `ANTHROPIC_VERTEX_PROJECT_ID` | Vertex AI 的 GCP 專案 ID。使用 [Google Vertex AI](/zh-TW/google-vertex-ai) 時為必需 |

45| `API_TIMEOUT_MS` | API 請求的逾時(以毫秒為單位)(預設值:600000,或 10 分鐘;最大值:2147483647)。在緩慢網路上請求逾時或透過代理路由時增加此值。超過最大值的值會導致基礎計時器溢位,並導致請求立即失敗 |

46| `AWS_BEARER_TOKEN_BEDROCK` | Bedrock API 金鑰用於驗證(請參閱 [Bedrock API keys](https://aws.amazon.com/blogs/machine-learning/accelerate-ai-development-with-amazon-bedrock-api-keys/)) |

47| `BASH_DEFAULT_TIMEOUT_MS` | 長時間執行的 bash 命令的預設逾時(預設值:120000,或 2 分鐘) |

48| `BASH_MAX_OUTPUT_LENGTH` | bash 輸出中的最大字元數,超過此數量後將進行中間截斷 |

49| `BASH_MAX_TIMEOUT_MS` | 模型可以為長時間執行的 bash 命令設定的最大逾時(預設值:600000,或 10 分鐘) |

50| `CCR_FORCE_BUNDLE` | 設定為 `1` 以強制 [`claude --remote`](/zh-TW/claude-code-on-the-web#send-local-repositories-without-github) 在 GitHub 存取可用時也要捆綁並上傳您的本機儲存庫 |

51| `CLAUDECODE` | 在 Claude Code 生成的 shell 環境中設定為 `1`(Bash 工具、tmux 工作階段)。未在 [hooks](/zh-TW/hooks) 或 [status line](/zh-TW/statusline) 命令中設定。用於偵測指令碼何時在 Claude Code 生成的 shell 內執行 |

52| `CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS` | 設定為 `1` 以停用所有內建 [subagent](/zh-TW/sub-agents) 類型,例如 Explore 和 Plan。僅適用於非互動式模式(`-p` 旗標)。對於想要空白狀態的 SDK 使用者很有用 |

53| `CLAUDE_AGENT_SDK_MCP_NO_PREFIX` | 設定為 `1` 以跳過來自 SDK 建立的 MCP 伺服器的工具名稱上的 `mcp__<server>__` 前綴。工具使用其原始名稱。僅限 SDK 使用 |

54| `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` | 設定自動壓縮觸發的上下文容量百分比 (1-100)。預設情況下,自動壓縮在約 95% 容量時觸發。使用較低的值(如 `50`)以更早進行壓縮。高於預設閾值的值無效。適用於主要對話和 subagents。此百分比與 [status line](/zh-TW/statusline) 中可用的 `context_window.used_percentage` 欄位一致 |

55| `CLAUDE_AUTO_BACKGROUND_TASKS` | 設定為 `1` 以強制啟用長時間執行的代理任務的自動背景執行。啟用時,subagents 在執行約兩分鐘後會移至背景 |

56| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | 在主工作階段中每個 Bash 或 PowerShell 命令後返回原始工作目錄 |

57| `CLAUDE_CODE_ACCESSIBILITY` | 設定為 `1` 以保持原生終端游標可見並停用反轉文字游標指示器。允許 macOS Zoom 等螢幕放大鏡追蹤游標位置 |

58| `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` | 設定為 `1` 以從使用 `--add-dir` 指定的目錄載入記憶體檔案。載入 `CLAUDE.md`、`.claude/CLAUDE.md`、`.claude/rules/*.md` 和 `CLAUDE.local.md`。預設情況下,其他目錄不載入記憶體檔案 |

59| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | 應刷新認證的間隔(以毫秒為單位)(使用 [`apiKeyHelper`](/zh-TW/settings#available-settings) 時) |

60| `CLAUDE_CODE_ATTRIBUTION_HEADER` | 設定為 `0` 以省略系統提示開始處的歸屬區塊(用戶端版本和提示指紋)。停用它會改善透過 [LLM gateway](/zh-TW/llm-gateway) 路由時的提示快取命中率。Anthropic API 快取不受影響 |

61| `CLAUDE_CODE_AUTO_COMPACT_WINDOW` | 設定用於自動壓縮計算的上下文容量(以 token 為單位)。預設為模型的上下文視窗:標準模型為 200K 或 [extended context](/zh-TW/model-config#extended-context) 模型為 1M。在 1M 模型上使用較低的值(如 `500000`)以將視窗視為 500K 用於壓縮目的。該值上限為模型的實際上下文視窗。`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` 作為此值的百分比應用。設定此變數會將壓縮閾值與狀態行的 `used_percentage` 解耦,後者始終使用模型的完整上下文視窗 |

62| `CLAUDE_CODE_AUTO_CONNECT_IDE` | 覆蓋自動 [IDE connection](/zh-TW/vs-code)。預設情況下,在支援的 IDE 的整合終端內啟動時,Claude Code 會自動連線。設定為 `false` 以防止此情況。設定為 `true` 以在自動偵測失敗時強制連線嘗試,例如當 tmux 遮蔽父終端時 |

63| `CLAUDE_CODE_CERT_STORE` | TLS 連線的 CA 憑證來源逗號分隔清單。`bundled` 是隨 Claude Code 提供的 Mozilla CA 集。`system` 是作業系統信任存放區。預設為 `bundled,system`。系統存放區整合需要原生二進位分佈。在 Node.js 執行時,無論此值如何,只使用捆綁集 |

64| `CLAUDE_CODE_CLIENT_CERT` | 用於 mTLS 驗證的用戶端憑證檔案的路徑 |

65| `CLAUDE_CODE_CLIENT_KEY` | 用於 mTLS 驗證的用戶端私密金鑰檔案的路徑 |

66| `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | 加密 CLAUDE\_CODE\_CLIENT\_KEY 的密碼(可選) |

67| `CLAUDE_CODE_DEBUG_LOGS_DIR` | 覆蓋偵錯日誌檔案路徑。儘管名稱如此,這是檔案路徑,而不是目錄。需要透過 `--debug` 或 `/debug` 單獨啟用偵錯模式:僅設定此變數不會啟用日誌記錄。[`--debug-file`](/zh-TW/cli-reference#cli-flags) 旗標同時執行兩者。預設為 `~/.claude/debug/<session-id>.txt` |

68| `CLAUDE_CODE_DEBUG_LOG_LEVEL` | 寫入偵錯日誌檔案的最小日誌級別。值:`verbose`、`debug`(預設)、`info`、`warn`、`error`。設定為 `verbose` 以包含高容量診斷,例如完整狀態行命令輸出,或提高到 `error` 以減少雜訊 |

69| `CLAUDE_CODE_DISABLE_1M_CONTEXT` | 設定為 `1` 以停用 [1M context window](/zh-TW/model-config#extended-context) 支援。設定時,1M 模型變體在模型選擇器中不可用。對於具有合規性要求的企業環境很有用 |

70| `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` | 設定為 `1` 以停用 Opus 4.6 和 Sonnet 4.6 的 [adaptive reasoning](/zh-TW/model-config#adjust-effort-level),並回退到由 `MAX_THINKING_TOKENS` 控制的固定思考預算。{/* min-version: 2.1.111 */}對 Opus 4.7 無效,其始終使用自適應推理 |

71| `CLAUDE_CODE_DISABLE_ATTACHMENTS` | 設定為 `1` 以停用附件處理。使用 `@` 語法的檔案提及會作為純文字發送,而不是擴展為檔案內容 |

72| `CLAUDE_CODE_DISABLE_AUTO_MEMORY` | 設定為 `1` 以停用 [auto memory](/zh-TW/memory#auto-memory)。設定為 `0` 以在逐步推出期間強制啟用自動記憶體。停用時,Claude 不會建立或載入自動記憶體檔案 |

73| `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` | 設定為 `1` 以停用所有背景任務功能,包括 Bash 和 subagent 工具上的 `run_in_background` 參數、自動背景執行和 Ctrl+B 快捷鍵 |

74| `CLAUDE_CODE_DISABLE_CLAUDE_MDS` | 設定為 `1` 以防止將任何 CLAUDE.md 記憶體檔案載入上下文,包括使用者、專案和自動記憶體檔案 |

75| `CLAUDE_CODE_DISABLE_CRON` | 設定為 `1` 以停用 [scheduled tasks](/zh-TW/scheduled-tasks)。`/loop` skill 和 cron 工具變為不可用,任何已排程的任務停止觸發,包括已在工作階段中執行的任務 |

76| `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | 設定為 `1` 以從 API 請求中移除 Anthropic 特定的 `anthropic-beta` 請求標頭和 beta 工具架構欄位(例如 `defer_loading` 和 `eager_input_streaming`)。當代理閘道拒絕請求並出現「Unexpected value(s) for the `anthropic-beta` header」或「Extra inputs are not permitted」之類的錯誤時,請使用此選項。標準欄位(`name`、`description`、`input_schema`、`cache_control`)會保留。 |

77| `CLAUDE_CODE_DISABLE_FAST_MODE` | 設定為 `1` 以停用 [fast mode](/zh-TW/fast-mode) |

78| `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY` | 設定為 `1` 以停用「Claude 表現如何?」工作階段品質調查。在設定 `DISABLE_TELEMETRY` 或 `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` 時也會停用調查。請參閱 [Session quality surveys](/zh-TW/data-usage#session-quality-surveys) |

79| `CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING` | 設定為 `1` 以停用檔案 [checkpointing](/zh-TW/checkpointing)。`/rewind` 命令將無法還原程式碼變更 |

80| `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` | 設定為 `1` 以從 Claude 的系統提示中移除內建的提交和 PR 工作流程指令以及 git 狀態快照。在使用您自己的 git 工作流程 skills 時很有用。設定時優先於 [`includeGitInstructions`](/zh-TW/settings#available-settings) 設定 |

81| `CLAUDE_CODE_DISABLE_LEGACY_MODEL_REMAP` | 設定為 `1` 以防止在 Anthropic API 上自動重新對應 Opus 4.0 和 4.1 至目前的 Opus 版本。在您想要刻意固定較舊模型時使用。重新對應不在 Bedrock、Vertex 或 Foundry 上執行 |

82| `CLAUDE_CODE_DISABLE_MOUSE` | 設定為 `1` 以停用 [fullscreen rendering](/zh-TW/fullscreen) 中的滑鼠追蹤。使用 `PgUp` 和 `PgDn` 的鍵盤捲動仍然有效。使用此選項可保留您終端的原生選擇複製行為 |

83| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | 相當於設定 `DISABLE_AUTOUPDATER`、`DISABLE_FEEDBACK_COMMAND`、`DISABLE_ERROR_REPORTING` 和 `DISABLE_TELEMETRY` |

84| `CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK` | 設定為 `1` 以停用串流請求在中途失敗時的非串流回退。串流錯誤會傳播到重試層。當代理或閘道導致回退產生重複的工具執行時很有用 |

85| `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` | 設定為 `1` 以跳過首次執行時官方外掛程式市場的自動新增 |

86| `CLAUDE_CODE_DISABLE_POLICY_SKILLS` | 設定為 `1` 以跳過從系統範圍的受管 skills 目錄載入 skills。對於不應載入操作員佈建的 skills 的容器或 CI 工作階段很有用 |

87| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | 設定為 `1` 以停用基於對話上下文的自動終端標題更新 |

88| `CLAUDE_CODE_DISABLE_THINKING` | 設定為 `1` 以強制停用 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking),無論模型支援或其他設定如何。比 `MAX_THINKING_TOKENS=0` 更直接 |

89| `CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL` | 設定為 `1` 以停用 [fullscreen rendering](/zh-TW/fullscreen) 中的虛擬捲動,並呈現文字記錄中的每條訊息。如果全螢幕模式中的捲動顯示應該出現訊息的空白區域,請使用此選項 |

90| `CLAUDE_CODE_EFFORT_LEVEL` | 為支援的模型設定努力級別。值:`low`、`medium`、`high`、`xhigh`、`max` 或 `auto` 以使用模型預設值。可用級別取決於模型。優先於 `/effort` 和 `effortLevel` 設定。請參閱 [Adjust effort level](/zh-TW/model-config#adjust-effort-level) |

91| `CLAUDE_CODE_ENABLE_AWAY_SUMMARY` | 覆蓋 [session recap](/zh-TW/interactive-mode#session-recap) 可用性。設定為 `0` 以強制關閉摘要,無論 `/config` 切換如何。設定為 `1` 以在 [`awaySummaryEnabled`](/zh-TW/settings#available-settings) 為 `false` 時強制啟用摘要。優先於設定和 `/config` 切換 |

92| `CLAUDE_CODE_ENABLE_BACKGROUND_PLUGIN_REFRESH` | 設定為 `1` 以在 [non-interactive mode](/zh-TW/headless) 中背景安裝完成後在回合邊界處刷新外掛程式狀態。預設關閉,因為刷新會在工作階段中途更改系統提示,這會使該回合的 [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) 失效 |

93| `CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING` | 設定為 `1` 以強制啟用細粒度工具輸入串流。沒有此選項,API 會在發送 delta 事件之前完全緩衝工具輸入參數,這可能會延遲大型工具輸入的顯示。僅限 Anthropic API:對 Bedrock、Vertex 或 Foundry 無效 |

94| `CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION` | 設定為 `false` 以停用提示建議(`/config` 中的「提示建議」切換)。這些是在 Claude 回應後出現在您的提示輸入中的灰顯預測。請參閱 [Prompt suggestions](/zh-TW/interactive-mode#prompt-suggestions) |

95| `CLAUDE_CODE_ENABLE_TASKS` | 設定為 `1` 以在非互動式模式(`-p` 旗標)中啟用任務追蹤系統。任務在互動式模式中預設為開啟。請參閱 [Task list](/zh-TW/interactive-mode#task-list) |

96| `CLAUDE_CODE_ENABLE_TELEMETRY` | 設定為 `1` 以啟用 OpenTelemetry 資料收集以進行指標和日誌記錄。在配置 OTel 匯出器之前需要。請參閱 [Monitoring](/zh-TW/monitoring-usage) |

97| `CLAUDE_CODE_EXIT_AFTER_STOP_DELAY` | 查詢迴圈變為閒置後自動退出前等待的時間(以毫秒為單位)。對於使用 SDK 模式的自動化工作流程和指令碼很有用 |

98| `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` | 設定為 `1` 以啟用 [agent teams](/zh-TW/agent-teams)。Agent teams 是實驗性的,預設停用 |

99| `CLAUDE_CODE_EXTRA_BODY` | JSON 物件以合併到每個 API 請求主體的頂層。對於傳遞 Claude Code 不直接公開的提供者特定參數很有用 |

100| `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS` | 覆蓋檔案讀取的預設 token 限制。當您需要完整讀取較大的檔案時很有用 |

101| `CLAUDE_CODE_FORK_SUBAGENT` | 設定為 `1` 以啟用 [forked subagents](/zh-TW/sub-agents#fork-the-current-conversation)。分叉的 subagent 從主工作階段繼承完整的對話上下文,而不是從頭開始。啟用時,`/fork` 會生成分叉的 subagent,而不是充當 [`/branch`](/zh-TW/commands) 的別名,所有 subagent 生成都在背景中執行。在互動式模式和透過 SDK 或 `claude -p` 中工作 |

102| `CLAUDE_CODE_GIT_BASH_PATH` | 僅限 Windows:Git Bash 可執行檔(`bash.exe`)的路徑。在 Git Bash 已安裝但不在您的 PATH 中時使用。請參閱 [Windows setup](/zh-TW/setup#set-up-on-windows) |

103| `CLAUDE_CODE_GLOB_HIDDEN` | 設定為 `false` 以在 Claude 呼叫 [Glob tool](/zh-TW/tools-reference) 時從結果中排除隱藏檔案。預設包含。不影響 `@` 檔案自動完成、`ls`、Grep 或 Read |

104| `CLAUDE_CODE_GLOB_NO_IGNORE` | 設定為 `false` 以使 [Glob tool](/zh-TW/tools-reference) 尊重 `.gitignore` 模式。預設情況下,Glob 返回所有符合的檔案,包括 gitignored 的檔案。不影響 `@` 檔案自動完成,其具有自己的 [`respectGitignore` 設定](/zh-TW/settings#available-settings) |

105| `CLAUDE_CODE_GLOB_TIMEOUT_SECONDS` | Glob 工具檔案探索的逾時(以秒為單位)。在大多數平台上預設為 20 秒,在 WSL 上預設為 60 秒 |

106| `CLAUDE_CODE_HIDE_CWD` | 設定為 `1` 以在啟動標誌中隱藏工作目錄。對於螢幕共享或錄製很有用,其中路徑會暴露您的作業系統使用者名稱 |

107| `CLAUDE_CODE_IDE_HOST_OVERRIDE` | 覆蓋用於連線至 IDE 擴充功能的主機位址。預設情況下,Claude Code 會自動偵測正確的位址,包括 WSL 到 Windows 路由 |

108| `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL` | 跳過 IDE 擴充功能的自動安裝。相當於將 [`autoInstallIdeExtension`](/zh-TW/settings#global-config-settings) 設定為 `false` |

109| `CLAUDE_CODE_IDE_SKIP_VALID_CHECK` | 設定為 `1` 以跳過連線期間 IDE 鎖定檔案項目的驗證。當自動連線無法找到您的 IDE(儘管它正在執行)時使用 |

110| `CLAUDE_CODE_MAX_CONTEXT_TOKENS` | 覆蓋 Claude Code 假設用於作用中模型的上下文視窗大小。僅在同時設定 `DISABLE_COMPACT` 時生效。當透過 `ANTHROPIC_BASE_URL` 路由到模型時使用,其上下文視窗與其名稱的內建大小不符 |

111| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | 設定大多數請求的最大輸出 token 數。預設值和上限因模型而異;請參閱 [max output tokens](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison)。增加此值會減少在 [auto-compaction](/zh-TW/costs#reduce-token-usage) 觸發之前可用的有效上下文視窗。 |

112| `CLAUDE_CODE_MAX_RETRIES` | 覆蓋重試失敗 API 請求的次數(預設值:10) |

113| `CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY` | 可以並行執行的唯讀工具和 subagents 的最大數量(預設值:10)。較高的值會增加並行性,但消耗更多資源 |

114| `CLAUDE_CODE_MCP_ALLOWLIST_ENV` | 設定為 `1` 以使用僅安全基線環境加上伺服器配置的 `env` 而不是繼承您的 shell 環境來生成 stdio MCP 伺服器 |

115| `CLAUDE_CODE_NEW_INIT` | 設定為 `1` 以使 `/init` 執行互動式設定流程。流程會詢問要產生哪些檔案,包括 CLAUDE.md、skills 和 hooks,然後再探索程式碼庫並寫入它們。沒有此變數,`/init` 會自動產生 CLAUDE.md 而不提示。 |

116| `CLAUDE_CODE_NO_FLICKER` | 設定為 `1` 以啟用 [fullscreen rendering](/zh-TW/fullscreen),一項研究預覽,可減少閃爍並在長對話中保持記憶體平坦。相當於 [`tui`](/zh-TW/settings#available-settings) 設定;您也可以使用 `/tui fullscreen` 切換 |

117| `CLAUDE_CODE_OAUTH_REFRESH_TOKEN` | Claude.ai 驗證的 OAuth 重新整理權杖。設定時,`claude auth login` 會直接交換此權杖,而不是開啟瀏覽器。需要 `CLAUDE_CODE_OAUTH_SCOPES`。對於在自動化環境中佈建驗證很有用 |

118| `CLAUDE_CODE_OAUTH_SCOPES` | 重新整理權杖發出時所使用的空格分隔 OAuth 範圍,例如 `"user:profile user:inference user:sessions:claude_code"`。設定 `CLAUDE_CODE_OAUTH_REFRESH_TOKEN` 時為必需 |

119| `CLAUDE_CODE_OAUTH_TOKEN` | Claude.ai 驗證的 OAuth 存取權杖。`/login` 對於 SDK 和自動化環境的替代方案。優先於鑰匙圈儲存的認證。使用 [`claude setup-token`](/zh-TW/authentication#generate-a-long-lived-token) 產生一個 |

120| `CLAUDE_CODE_OTEL_FLUSH_TIMEOUT_MS` | 刷新待處理 OpenTelemetry spans 的逾時(以毫秒為單位)(預設值:5000)。請參閱 [Monitoring](/zh-TW/monitoring-usage) |

121| `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | 刷新動態 OpenTelemetry 標頭的間隔(以毫秒為單位)(預設值:1740000 / 29 分鐘)。請參閱 [Dynamic headers](/zh-TW/monitoring-usage#dynamic-headers) |

122| `CLAUDE_CODE_OTEL_SHUTDOWN_TIMEOUT_MS` | OpenTelemetry 匯出器在關閉時完成的逾時(以毫秒為單位)(預設值:2000)。如果指標在退出時被丟棄,請增加此值。請參閱 [Monitoring](/zh-TW/monitoring-usage) |

123| `CLAUDE_CODE_PERFORCE_MODE` | 設定為 `1` 以啟用 Perforce 感知寫入保護。設定時,如果目標檔案缺少擁有者寫入位元(Perforce 在同步的檔案上清除,直到 `p4 edit` 開啟它們),Edit、Write 和 NotebookEdit 會失敗並提示 `p4 edit <file>`。這可防止 Claude Code 繞過 Perforce 變更追蹤 |

124| `CLAUDE_CODE_PLUGIN_CACHE_DIR` | 覆蓋外掛程式根目錄。儘管名稱如此,這會設定父目錄,而不是快取本身:市場和外掛程式快取位於此路徑下的子目錄中。預設為 `~/.claude/plugins` |

125| `CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS` | 安裝或更新外掛程式時 git 操作的逾時(以毫秒為單位)(預設值:120000)。對於大型儲存庫或網路連線緩慢,請增加此值。請參閱 [Git operations time out](/zh-TW/plugin-marketplaces#git-operations-time-out) |

126| `CLAUDE_CODE_PLUGIN_KEEP_MARKETPLACE_ON_FAILURE` | 設定為 `1` 以在 `git pull` 失敗時保留現有的市場快取,而不是擦除並重新複製。在離線或隔離環境中很有用,其中重新複製會以相同方式失敗。請參閱 [Marketplace updates fail in offline environments](/zh-TW/plugin-marketplaces#marketplace-updates-fail-in-offline-environments) |

127| `CLAUDE_CODE_PLUGIN_SEED_DIR` | 一個或多個唯讀外掛程式種子目錄的路徑,在 Unix 上以 `:` 分隔,在 Windows 上以 `;` 分隔。使用此選項可將預先填充的外掛程式目錄捆綁到容器映像中。Claude Code 在啟動時從這些目錄註冊市場,並使用預先快取的外掛程式而無需重新複製。請參閱 [Pre-populate plugins for containers](/zh-TW/plugin-marketplaces#pre-populate-plugins-for-containers) |

128| `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST` | 由嵌入 Claude Code 並代表其管理模型提供者路由的主機平台設定。設定時,提供者選擇、端點和驗證變數(例如 `CLAUDE_CODE_USE_BEDROCK`、`ANTHROPIC_BASE_URL` 和 `ANTHROPIC_API_KEY`)在設定檔案中被忽略,以便使用者設定無法覆蓋主機的路由。Bedrock、Vertex 和 Foundry 的自動遙測選擇退出也會被跳過,因此遙測遵循標準 `DISABLE_TELEMETRY` 選擇退出。請參閱 [Default behaviors by API provider](/zh-TW/data-usage#default-behaviors-by-api-provider) |

129| `CLAUDE_CODE_PROXY_RESOLVES_HOSTS` | 設定為 `1` 以允許代理執行 DNS 解析而不是呼叫者。對於代理應處理主機名稱解析的環境選擇加入 |

130| `CLAUDE_CODE_REMOTE` | 當 Claude Code 作為 [cloud session](/zh-TW/claude-code-on-the-web) 執行時自動設定為 `true`。從 hook 或設定指令碼讀取此項以偵測您是否在雲端環境中 |

131| `CLAUDE_CODE_REMOTE_SESSION_ID` | 在 [cloud sessions](/zh-TW/claude-code-on-the-web) 中自動設定為目前工作階段的 ID。讀取此項以構造回到工作階段文字記錄的連結。請參閱 [Link artifacts back to the session](/zh-TW/claude-code-on-the-web#link-artifacts-back-to-the-session) |

132| `CLAUDE_CODE_RESUME_INTERRUPTED_TURN` | 設定為 `1` 以在上一個工作階段在中途結束時自動繼續。在 SDK 模式中使用,以便模型繼續而無需 SDK 重新發送提示 |

133| `CLAUDE_CODE_SCRIPT_CAPS` | JSON 物件,當設定 `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` 時限制特定指令碼在每個工作階段中可被呼叫的次數。鍵是針對命令文字進行比對的子字串;值是整數呼叫限制。例如,`{"deploy.sh": 2}` 允許 `deploy.sh` 最多被呼叫兩次。比對是基於子字串的,因此 shell 擴展技巧(如 `./scripts/deploy.sh $(evil)`)仍然計入上限。透過 `xargs` 或 `find -exec` 的執行時扇出未被偵測;這是深度防禦控制 |

134| `CLAUDE_CODE_SCROLL_SPEED` | 在 [fullscreen rendering](/zh-TW/fullscreen#mouse-wheel-scrolling) 中設定滑鼠滾輪捲動乘數。接受 1 到 20 的值。設定為 `3` 以符合 `vim`(如果您的終端在沒有放大的情況下每個刻度發送一個滾輪事件) |

135| `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` | 覆蓋 [SessionEnd](/zh-TW/hooks#sessionend) hooks 的時間預算(以毫秒為單位)。適用於工作階段退出、`/clear` 和透過互動式 `/resume` 切換工作階段。預設情況下,預算為 1.5 秒,自動提高到設定檔案中配置的最高每個 hook `timeout`,最高 60 秒。外掛程式提供的 hooks 上的逾時不會提高預算 |

136| `CLAUDE_CODE_SHELL` | 覆蓋自動 shell 偵測。當您的登入 shell 與您偏好的工作 shell 不同時很有用(例如,`bash` 與 `zsh`) |

137| `CLAUDE_CODE_SHELL_PREFIX` | 命令前綴以包裝 Claude Code 生成的 shell 命令:Bash 工具呼叫、[hook](/zh-TW/hooks) 命令和 stdio [MCP server](/zh-TW/mcp) 啟動命令。對於日誌記錄或稽核很有用。範例:設定 `/path/to/logger.sh` 會將每個命令執行為 `/path/to/logger.sh <command>` |

138| `CLAUDE_CODE_SIMPLE` | 設定為 `1` 以使用最小系統提示和僅 Bash、檔案讀取和檔案編輯工具執行。來自 `--mcp-config` 的 MCP 工具仍然可用。停用 hooks、skills、plugins、MCP 伺服器、自動記憶體和 CLAUDE.md 的自動探索。[`--bare`](/zh-TW/headless#start-faster-with-bare-mode) CLI 旗標設定此項 |

139| `CLAUDE_CODE_SIMPLE_SYSTEM_PROMPT` | 設定為 `1` 以在 Opus 4.7 上使用較短的系統提示和縮寫工具描述。對其他模型無效。完整工具集、hooks、MCP 伺服器和 CLAUDE.md 探索保持啟用 |

140| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | 跳過 Bedrock 的 AWS 驗證(例如,使用 LLM 閘道時) |

141| `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` | 跳過 Microsoft Foundry 的 Azure 驗證(例如,使用 LLM 閘道時) |

142| `CLAUDE_CODE_SKIP_MANTLE_AUTH` | 跳過 Bedrock Mantle 的 AWS 驗證(例如,使用 LLM 閘道時) |

143| `CLAUDE_CODE_SKIP_PROMPT_HISTORY` | 設定為 `1` 以跳過將提示歷史記錄和工作階段文字記錄寫入磁碟。使用此變數啟動的工作階段不會出現在 `--resume`、`--continue` 或向上箭頭歷史記錄中。對於臨時指令碼化工作階段很有用 |

144| `CLAUDE_CODE_SKIP_VERTEX_AUTH` | 跳過 Vertex 的 Google 驗證(例如,使用 LLM 閘道時) |

145| `CLAUDE_CODE_SUBAGENT_MODEL` | 請參閱 [Model configuration](/zh-TW/model-config) |

146| `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` | 設定為 `1` 以從子程序環境中移除 Anthropic 和雲端提供者認證(Bash 工具、hooks、MCP stdio 伺服器)。父 Claude 程序保留這些認證以進行 API 呼叫,但子程序無法讀取它們,減少了嘗試透過 shell 擴展來竊取機密的提示注入攻擊的暴露。在 Linux 上,這也會在隔離的 PID 命名空間中執行 Bash 子程序,以便它們無法透過 `/proc` 讀取主機程序環境;作為副作用,`ps`、`pgrep` 和 `kill` 無法看到或發信號給主機程序。配置 `allowed_non_write_users` 時,`claude-code-action` 會自動設定此項 |

147| `CLAUDE_CODE_SYNC_PLUGIN_INSTALL` | 在非互動式模式(`-p` 旗標)中設定為 `1` 以等待外掛程式安裝完成,然後再進行第一個查詢。沒有此選項,外掛程式會在背景中安裝,可能在第一個回合時不可用。與 `CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS` 結合以限制等待時間 |

148| `CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS` | 同步外掛程式安裝的逾時(以毫秒為單位)。超過時,Claude Code 會在沒有外掛程式的情況下繼續並記錄錯誤。無預設值:沒有此變數,同步安裝會等待直到完成 |

149| `CLAUDE_CODE_SYNTAX_HIGHLIGHT` | 設定為 `false` 以停用 diff 輸出中的語法醒目提示。當顏色干擾您的終端設定時很有用 |

150| `CLAUDE_CODE_TASK_LIST_ID` | 跨工作階段共享任務清單。在多個 Claude Code 實例中設定相同的 ID 以協調共享任務清單。請參閱 [Task list](/zh-TW/interactive-mode#task-list) |

151| `CLAUDE_CODE_TEAM_NAME` | 此隊友所屬的 agent team 名稱。在 [agent team](/zh-TW/agent-teams) 成員上自動設定 |

152| `CLAUDE_CODE_TMPDIR` | 覆蓋用於內部臨時檔案的臨時目錄。Claude Code 將 `/claude-{uid}/`(Unix)或 `/claude/`(Windows)附加到此路徑。預設值:macOS 上的 `/tmp`、Linux/Windows 上的 `os.tmpdir()` |

153| `CLAUDE_CODE_TMUX_TRUECOLOR` | 設定為 `1` 以允許 tmux 內的 24 位真彩色輸出。預設情況下,當設定 `$TMUX` 時,Claude Code 會限制為 256 色,因為 tmux 不會通過真彩色逃逸序列,除非配置為這樣做。在將 `set -ga terminal-overrides ',*:Tc'` 新增到您的 `~/.tmux.conf` 後設定此項。請參閱 [Terminal configuration](/zh-TW/terminal-config) 以取得其他 tmux 設定 |

154| `CLAUDE_CODE_USE_BEDROCK` | 使用 [Bedrock](/zh-TW/amazon-bedrock) |

155| `CLAUDE_CODE_USE_FOUNDRY` | 使用 [Microsoft Foundry](/zh-TW/microsoft-foundry) |

156| `CLAUDE_CODE_USE_MANTLE` | 使用 Bedrock [Mantle endpoint](/zh-TW/amazon-bedrock#use-the-mantle-endpoint) |

157| `CLAUDE_CODE_USE_NATIVE_FILE_SEARCH` | 設定為 `1` 以使用 Node.js 檔案 API 而不是 ripgrep 來探索自訂命令、subagents 和輸出樣式。如果捆綁的 ripgrep 二進位檔案在您的環境中不可用或被阻止,請設定此項。不影響 Grep 或檔案搜尋工具 |

158| `CLAUDE_CODE_USE_POWERSHELL_TOOL` | 控制 PowerShell 工具。在沒有 Git Bash 的 Windows 上,工具會自動啟用;設定為 `0` 以停用它。在安裝了 Git Bash 的 Windows 上,工具正在逐步推出:設定為 `1` 以選擇加入或 `0` 以選擇退出。在 Linux、macOS 和 WSL 上,設定為 `1` 以啟用它,這需要您的 `PATH` 上有 `pwsh`。在 Windows 上啟用時,Claude 可以原生執行 PowerShell 命令,而不是透過 Git Bash 路由。請參閱 [PowerShell tool](/zh-TW/tools-reference#powershell-tool) |

159| `CLAUDE_CODE_USE_VERTEX` | 使用 [Vertex](/zh-TW/google-vertex-ai) |

160| `CLAUDE_CONFIG_DIR` | 覆蓋配置目錄(預設值:`~/.claude`)。所有設定、認證、工作階段歷史記錄和外掛程式都儲存在此路徑下。對於並排執行多個帳戶很有用:例如,`alias claude-work='CLAUDE_CONFIG_DIR=~/.claude-work claude'` |

161| `CLAUDE_ENABLE_BYTE_WATCHDOG` | 設定為 `1` 以強制啟用位元級串流閒置監視程式,或設定為 `0` 以強制停用它。未設定時,監視程式預設對 Anthropic API 連線啟用。位元監視程式會在 `CLAUDE_STREAM_IDLE_TIMEOUT_MS` 設定的持續時間內沒有位元到達線路時中止連線,最少 5 分鐘,獨立於事件級監視程式 |

162| `CLAUDE_ENABLE_STREAM_WATCHDOG` | 設定為 `1` 以啟用事件級串流閒置監視程式。預設關閉。對於 Bedrock、Vertex 和 Foundry,這是唯一可用的閒置監視程式。使用 `CLAUDE_STREAM_IDLE_TIMEOUT_MS` 配置逾時 |

163| `CLAUDE_ENV_FILE` | Claude Code 在每個 Bash 命令之前在同一 shell 程序中執行的 shell 指令碼的路徑,因此檔案中的匯出對命令可見。用於在命令之間保持 virtualenv 或 conda 啟用。也由 [SessionStart](/zh-TW/hooks#persist-environment-variables)、[Setup](/zh-TW/hooks#setup)、[CwdChanged](/zh-TW/hooks#cwdchanged) 和 [FileChanged](/zh-TW/hooks#filechanged) hooks 動態填充 |

164| `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` | 當未提供明確名稱時,自動產生的 [Remote Control](/zh-TW/remote-control) 工作階段名稱的前綴。預設為您的機器主機名稱,產生名稱如 `myhost-graceful-unicorn`。`--remote-control-session-name-prefix` CLI 旗標為單一呼叫設定相同的值 |

165| `CLAUDE_STREAM_IDLE_TIMEOUT_MS` | 串流閒置監視程式在關閉停滯連線之前的逾時(以毫秒為單位)。預設和最小 `300000`(5 分鐘)用於位元級和事件級監視程式;較低的值會無聲地限制以吸收延伸思考暫停和代理緩衝。對於第三方提供者,需要 `CLAUDE_ENABLE_STREAM_WATCHDOG=1` |

166| `DISABLE_AUTOUPDATER` | 設定為 `1` 以停用自動背景更新。手動 `claude update` 仍然有效。使用 `DISABLE_UPDATES` 以阻止兩者 |

167| `DISABLE_AUTO_COMPACT` | 設定為 `1` 以停用接近上下文限制時的自動壓縮。手動 `/compact` 命令仍然可用。在您想要明確控制何時進行壓縮時使用 |

168| `DISABLE_COMPACT` | 設定為 `1` 以停用所有壓縮:自動壓縮和手動 `/compact` 命令 |

169| `DISABLE_COST_WARNINGS` | 設定為 `1` 以停用成本警告訊息 |

170| `DISABLE_DOCTOR_COMMAND` | 設定為 `1` 以隱藏 `/doctor` 命令。對於使用者不應執行安裝診斷的受管部署很有用 |

171| `DISABLE_ERROR_REPORTING` | 設定為 `1` 以選擇退出 Sentry 錯誤報告 |

172| `DISABLE_EXTRA_USAGE_COMMAND` | 設定為 `1` 以隱藏 `/extra-usage` 命令,讓使用者購買超過速率限制的額外使用量 |

173| `DISABLE_FEEDBACK_COMMAND` | 設定為 `1` 以停用 `/feedback` 命令。較舊的名稱 `DISABLE_BUG_COMMAND` 也被接受 |

174| `DISABLE_GROWTHBOOK` | 設定為 `1` 以停用 GrowthBook 功能旗標擷取並為每個旗標使用程式碼預設值。遙測事件日誌記錄保持開啟,除非也設定 `DISABLE_TELEMETRY` |

175| `DISABLE_INSTALLATION_CHECKS` | 設定為 `1` 以停用安裝警告。僅在手動管理安裝位置時使用,因為這可能會掩蓋標準安裝的問題 |

176| `DISABLE_INSTALL_GITHUB_APP_COMMAND` | 設定為 `1` 以隱藏 `/install-github-app` 命令。使用第三方提供者(Bedrock、Vertex 或 Foundry)時已隱藏 |

177| `DISABLE_INTERLEAVED_THINKING` | 設定為 `1` 以防止發送交錯思考 beta 標頭。當您的 LLM 閘道或提供者不支援 [interleaved thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#interleaved-thinking) 時很有用 |

178| `DISABLE_LOGIN_COMMAND` | 設定為 `1` 以隱藏 `/login` 命令。當驗證透過 API 金鑰或 `apiKeyHelper` 外部處理時很有用 |

179| `DISABLE_LOGOUT_COMMAND` | 設定為 `1` 以隱藏 `/logout` 命令 |

180| `DISABLE_PROMPT_CACHING` | 設定為 `1` 以停用所有模型的提示快取(優先於每個模型的設定) |

181| `DISABLE_PROMPT_CACHING_HAIKU` | 設定為 `1` 以停用 Haiku 模型的提示快取 |

182| `DISABLE_PROMPT_CACHING_OPUS` | 設定為 `1` 以停用 Opus 模型的提示快取 |

183| `DISABLE_PROMPT_CACHING_SONNET` | 設定為 `1` 以停用 Sonnet 模型的提示快取 |

184| `DISABLE_TELEMETRY` | 設定為 `1` 以選擇退出 Statsig 遙測(請注意,Statsig 事件不包括使用者資料,如程式碼、檔案路徑或 bash 命令) |

185| `DISABLE_UPDATES` | 設定為 `1` 以阻止所有更新,包括手動 `claude update` 和 `claude install`。比 `DISABLE_AUTOUPDATER` 更嚴格。在透過您自己的管道分發 Claude Code 且使用者不應自行更新時使用 |

186| `DISABLE_UPGRADE_COMMAND` | 設定為 `1` 以隱藏 `/upgrade` 命令 |

187| `ENABLE_CLAUDEAI_MCP_SERVERS` | 設定為 `false` 以停用 Claude Code 中的 [claude.ai MCP servers](/zh-TW/mcp#use-mcp-servers-from-claude-ai)。對於已登入的使用者預設啟用 |

188| `ENABLE_PROMPT_CACHING_1H` | 設定為 `1` 以要求 1 小時的提示快取 TTL,而不是預設的 5 分鐘。適用於 API 金鑰、[Bedrock](/zh-TW/amazon-bedrock)、[Vertex](/zh-TW/google-vertex-ai) 和 [Foundry](/zh-TW/microsoft-foundry) 使用者。訂閱使用者自動接收 1 小時 TTL。1 小時快取寫入以更高的速率計費 |

189| `ENABLE_PROMPT_CACHING_1H_BEDROCK` | 已棄用。改用 `ENABLE_PROMPT_CACHING_1H` |

190| `ENABLE_TOOL_SEARCH` | 控制 [MCP tool search](/zh-TW/mcp#scale-with-mcp-tool-search)。未設定:預設所有 MCP 工具延遲,但在 Vertex AI 上或當 `ANTHROPIC_BASE_URL` 指向非第一方主機時提前載入。值:`true`(始終延遲,包括代理和 Vertex AI)、`auto`(閾值模式:如果工具符合上下文的 10% 內則提前載入)、`auto:N`(自訂閾值,例如 `auto:5` 表示 5%)、`false`(提前載入全部) |

191| `FALLBACK_FOR_ALL_PRIMARY_MODELS` | 設定為任何非空值以在任何主要模型上重複過載錯誤後觸發回退至 [`--fallback-model`](/zh-TW/cli-reference#cli-flags)。預設情況下,僅 Opus 模型觸發回退 |

192| `FORCE_AUTOUPDATE_PLUGINS` | 設定為 `1` 以強制外掛程式自動更新,即使主自動更新器通過 `DISABLE_AUTOUPDATER` 停用 |

193| `FORCE_PROMPT_CACHING_5M` | 設定為 `1` 以強制 5 分鐘的提示快取 TTL,即使 1 小時 TTL 會以其他方式適用。覆蓋 `ENABLE_PROMPT_CACHING_1H` |

194| `HTTP_PROXY` | 為網路連線指定 HTTP 代理伺服器 |

195| `HTTPS_PROXY` | 為網路連線指定 HTTPS 代理伺服器 |

196| `IS_DEMO` | 設定為 `1` 以啟用演示模式:隱藏標頭和 `/status` 輸出中的電子郵件和組織名稱,並跳過上線。對於串流或錄製工作階段很有用 |

197| `MAX_MCP_OUTPUT_TOKENS` | MCP 工具回應中允許的最大 token 數。當輸出超過 10,000 token 時,Claude Code 會顯示警告。宣告 [`anthropic/maxResultSizeChars`](/zh-TW/mcp#raise-the-limit-for-a-specific-tool) 的工具對文字內容使用該字元限制,但來自這些工具的影像內容仍受此變數限制(預設值:25000) |

198| `MAX_STRUCTURED_OUTPUT_RETRIES` | 當模型的回應無法驗證非互動式模式(`-p` 旗標)中的 [`--json-schema`](/zh-TW/cli-reference#cli-flags) 時重試的次數。預設為 5 |

199| `MAX_THINKING_TOKENS` | 覆蓋 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) token 預算。上限是模型的 [max output tokens](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison) 減一。設定為 `0` 以完全停用思考。在具有 [adaptive reasoning](/zh-TW/model-config#adjust-effort-level) 的模型上,預算會被忽略,除非透過 `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` 停用自適應推理 |

200| `MCP_CLIENT_SECRET` | 需要 [pre-configured credentials](/zh-TW/mcp#use-pre-configured-oauth-credentials) 的 MCP 伺服器的 OAuth 用戶端密碼。在使用 `--client-secret` 新增伺服器時避免互動式提示 |

201| `MCP_CONNECTION_NONBLOCKING` | 在非互動式模式(`-p`)中設定為 `true` 以完全跳過 MCP 連線等待。對於不需要 MCP 工具的指令碼化管道很有用。沒有此變數,第一個查詢會等待最多 5 秒以進行 `--mcp-config` 伺服器連線 |

202| `MCP_OAUTH_CALLBACK_PORT` | OAuth 重新導向回呼的固定連接埠,作為在使用 [pre-configured credentials](/zh-TW/mcp#use-pre-configured-oauth-credentials) 新增 MCP 伺服器時 `--callback-port` 的替代方案 |

203| `MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE` | 啟動期間並行連線的遠端 MCP 伺服器(HTTP/SSE)的最大數量(預設值:20) |

204| `MCP_SERVER_CONNECTION_BATCH_SIZE` | 啟動期間並行連線的本機 MCP 伺服器(stdio)的最大數量(預設值:3) |

205| `MCP_TIMEOUT` | MCP 伺服器啟動的逾時(以毫秒為單位)(預設值:30000,或 30 秒) |

206| `MCP_TOOL_TIMEOUT` | MCP 工具執行的逾時(以毫秒為單位)(預設值:100000000,約 28 小時) |

207| `NO_PROXY` | 要直接發出請求的網域和 IP 清單,繞過代理 |

208| `OTEL_LOG_RAW_API_BODIES` | 設定為 `1` 以將完整的 Anthropic Messages API 請求和回應 JSON 作為 `api_request_body` / `api_response_body` 日誌事件發出,或 `file:<dir>` 以將未截斷的主體寫入磁碟並發出 `body_ref` 路徑。預設停用;主體包括整個對話歷史記錄。請參閱 [Monitoring](/zh-TW/monitoring-usage#api-request-body-event) |

209| `OTEL_LOG_TOOL_CONTENT` | 設定為 `1` 以在 OpenTelemetry span 事件中包含工具輸入和輸出內容。預設停用以保護敏感資料。請參閱 [Monitoring](/zh-TW/monitoring-usage) |

210| `OTEL_LOG_TOOL_DETAILS` | 設定為 `1` 以在 OpenTelemetry 追蹤和日誌中包含工具輸入引數、MCP 伺服器名稱、工具失敗時的原始錯誤字串和其他工具詳細資訊。預設停用以保護個人識別資訊。請參閱 [Monitoring](/zh-TW/monitoring-usage) |

211| `OTEL_LOG_USER_PROMPTS` | 設定為 `1` 以在 OpenTelemetry 追蹤和日誌中包含使用者提示文字。預設停用(提示被編輯)。請參閱 [Monitoring](/zh-TW/monitoring-usage) |

212| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` | 設定為 `false` 以從指標屬性中排除帳戶 UUID(預設值:包含)。請參閱 [Monitoring](/zh-TW/monitoring-usage) |

213| `OTEL_METRICS_INCLUDE_SESSION_ID` | 設定為 `false` 以從指標屬性中排除工作階段 ID(預設值:包含)。請參閱 [Monitoring](/zh-TW/monitoring-usage) |

214| `OTEL_METRICS_INCLUDE_VERSION` | 設定為 `true` 以在指標屬性中包含 Claude Code 版本(預設值:排除)。請參閱 [Monitoring](/zh-TW/monitoring-usage) |

215| `SLASH_COMMAND_TOOL_CHAR_BUDGET` | 覆蓋顯示給 [Skill tool](/zh-TW/skills#control-who-invokes-a-skill) 的 skill 中繼資料的字元預算。預算在上下文視窗的 1% 處動態縮放,回退為 8,000 個字元。為了向後相容性保留舊名稱 |

216| `TASK_MAX_OUTPUT_LENGTH` | [subagent](/zh-TW/sub-agents) 輸出在截斷前的最大字元數(預設值:32000,最大值:160000)。截斷時,完整輸出會儲存到磁碟,路徑會包含在截斷的回應中 |

217| `USE_BUILTIN_RIPGREP` | 設定為 `0` 以使用系統安裝的 `rg` 而不是 Claude Code 隨附的 `rg` |

218| `VERTEX_REGION_CLAUDE_3_5_HAIKU` | 使用 Vertex AI 時覆蓋 Claude 3.5 Haiku 的區域 |

219| `VERTEX_REGION_CLAUDE_3_5_SONNET` | 使用 Vertex AI 時覆蓋 Claude 3.5 Sonnet 的區域 |

220| `VERTEX_REGION_CLAUDE_3_7_SONNET` | 使用 Vertex AI 時覆蓋 Claude 3.7 Sonnet 的區域 |

221| `VERTEX_REGION_CLAUDE_4_0_OPUS` | 使用 Vertex AI 時覆蓋 Claude 4.0 Opus 的區域 |

222| `VERTEX_REGION_CLAUDE_4_0_SONNET` | 使用 Vertex AI 時覆蓋 Claude 4.0 Sonnet 的區域 |

223| `VERTEX_REGION_CLAUDE_4_1_OPUS` | 使用 Vertex AI 時覆蓋 Claude 4.1 Opus 的區域 |

224| `VERTEX_REGION_CLAUDE_4_5_OPUS` | 使用 Vertex AI 時覆蓋 Claude Opus 4.5 的區域 |

225| `VERTEX_REGION_CLAUDE_4_5_SONNET` | 使用 Vertex AI 時覆蓋 Claude Sonnet 4.5 的區域 |

226| `VERTEX_REGION_CLAUDE_4_6_OPUS` | 使用 Vertex AI 時覆蓋 Claude Opus 4.6 的區域 |

227| `VERTEX_REGION_CLAUDE_4_6_SONNET` | 使用 Vertex AI 時覆蓋 Claude Sonnet 4.6 的區域 |

228| `VERTEX_REGION_CLAUDE_4_7_OPUS` | {/* min-version: 2.1.111 */}使用 Vertex AI 時覆蓋 Claude Opus 4.7 的區域 |

229| `VERTEX_REGION_CLAUDE_HAIKU_4_5` | 使用 Vertex AI 時覆蓋 Claude Haiku 4.5 的區域 |

230 

231標準 OpenTelemetry 匯出器變數(`OTEL_METRICS_EXPORTER`、`OTEL_LOGS_EXPORTER`、`OTEL_EXPORTER_OTLP_ENDPOINT`、`OTEL_EXPORTER_OTLP_PROTOCOL`、`OTEL_EXPORTER_OTLP_HEADERS`、`OTEL_METRIC_EXPORT_INTERVAL`、`OTEL_RESOURCE_ATTRIBUTES` 和信號特定變體)也受支援。請參閱 [Monitoring](/zh-TW/monitoring-usage) 以取得配置詳細資訊。

232 

233## 另請參閱

234 

235* [Settings](/zh-TW/settings):在 `settings.json` 中配置環境變數,使其適用於每個工作階段

236* [CLI reference](/zh-TW/cli-reference):啟動時旗標

237* [Network configuration](/zh-TW/network-config):代理和 TLS 設定

238* [Monitoring](/zh-TW/monitoring-usage):OpenTelemetry 配置

errors.md +536 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 錯誤參考

6 

7> 查詢 Claude Code 執行時錯誤訊息,了解每個錯誤的含義及修復方法。

8 

9本頁列出 Claude Code 顯示的執行時錯誤及如何從每個錯誤中恢復,以及當回應似乎有問題但沒有錯誤時要檢查的內容。如需安裝錯誤(例如 `command not found` 或設定期間的 TLS 失敗),請參閱 [Troubleshoot installation and login](/zh-TW/troubleshoot-install)。

10 

11這些錯誤和恢復命令適用於 CLI、[Desktop app](/zh-TW/desktop) 和 [Claude Code on the web](/zh-TW/claude-code-on-the-web),因為這三者都包裝相同的 Claude Code CLI。如需特定表面的問題,請參閱該表面頁面上的疑難排解部分。

12 

13<Note>

14 Claude Code 呼叫 Claude API 以取得模型回應,因此大多數執行時錯誤對應到基礎 API 錯誤代碼。本頁涵蓋每個錯誤在 Claude Code 中的含義及如何恢復。如需原始 HTTP 狀態代碼定義,請參閱 [Claude Platform error reference](https://platform.claude.com/docs/en/api/errors)。

15</Note>

16 

17## 尋找您的錯誤

18 

19將您在終端中看到的訊息與下方的部分相符。

20 

21| 訊息 | 部分 |

22| :----------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------ |

23| `API Error: 500 ... Internal server error` | [Server errors](#api-error-500-internal-server-error) |

24| `API Error: Repeated 529 Overloaded errors` | [Server errors](#api-error-repeated-529-overloaded-errors) |

25| `Request timed out` | [Server errors](#request-timed-out),或如果訊息提及您的網際網路連線,則為 [Network](#unable-to-connect-to-api) |

26| `<model> is temporarily unavailable, so auto mode cannot determine the safety of...` | [Server errors](#auto-mode-cannot-determine-the-safety-of-an-action) |

27| `You've hit your session limit` / `You've hit your weekly limit` | [Usage limits](#youve-hit-your-session-limit) |

28| `Server is temporarily limiting requests` | [Usage limits](#server-is-temporarily-limiting-requests) |

29| `Request rejected (429)` | [Usage limits](#request-rejected-429) |

30| `Credit balance is too low` | [Usage limits](#credit-balance-is-too-low) |

31| `Not logged in · Please run /login` | [Authentication](#not-logged-in) |

32| `Invalid API key` | [Authentication](#invalid-api-key) |

33| `This organization has been disabled` | [Authentication](#this-organization-has-been-disabled) |

34| `OAuth token revoked` / `OAuth token has expired` | [Authentication](#oauth-token-revoked-or-expired) |

35| `does not meet scope requirement user:profile` | [Authentication](#oauth-scope-requirement) |

36| `Unable to connect to API` | [Network](#unable-to-connect-to-api) |

37| `SSL certificate verification failed` | [Network](#ssl-certificate-errors) |

38| `Prompt is too long` | [Request errors](#prompt-is-too-long) |

39| `Error during compaction: Conversation too long` | [Request errors](#error-during-compaction-conversation-too-long) |

40| `Request too large` | [Request errors](#request-too-large) |

41| `Image was too large` | [Request errors](#image-was-too-large) |

42| `PDF too large` / `PDF is password protected` | [Request errors](#pdf-errors) |

43| `Extra inputs are not permitted` | [Request errors](#extra-inputs-are-not-permitted) |

44| `There's an issue with the selected model` | [Request errors](#theres-an-issue-with-the-selected-model) |

45| `Claude Opus is not available with the Claude Pro plan` | [Request errors](#claude-opus-is-not-available-with-the-claude-pro-plan) |

46| `thinking.type.enabled is not supported for this model` | [Request errors](#thinking-type-enabled-is-not-supported-for-this-model) |

47| `max_tokens must be greater than thinking.budget_tokens` | [Request errors](#thinking-budget-exceeds-output-limit) |

48| `API Error: 400 due to tool use concurrency issues` | [Request errors](#tool-use-or-thinking-block-mismatch) |

49| 回應品質似乎低於平常 | [Response quality](#responses-seem-lower-quality-than-usual) |

50 

51## 自動重試

52 

53Claude Code 在向您顯示錯誤之前會重試暫時性失敗。伺服器錯誤、過載回應、請求逾時、臨時 429 節流和中斷的連線都會以指數退避方式重試最多 10 次。重試時,微調器會顯示 `Retrying in Ns · attempt x/y` 倒數計時。

54 

55當您看到本頁上的其中一個錯誤時,這些重試已經用盡。您可以使用兩個環境變數調整行為:

56 

57| 變數 | 預設值 | 效果 |

58| :------------------------------------------- | :----- | :--------------------------------- |

59| [`CLAUDE_CODE_MAX_RETRIES`](/zh-TW/env-vars) | 10 | 重試次數。降低它以在指令碼中更快地顯示失敗;提高它以等待更長的事件。 |

60| [`API_TIMEOUT_MS`](/zh-TW/env-vars) | 600000 | 每個請求的逾時(毫秒)。為慢速網路或代理提高它。 |

61 

62## 伺服器錯誤

63 

64這些錯誤來自 Anthropic 基礎設施,而不是您的帳戶或請求。

65 

66### API Error: 500 Internal server error

67 

68Claude Code 為任何 5xx 狀態顯示原始 API 回應主體。下面的範例顯示 500 回應:

69 

70```text theme={null}

71API Error: 500 {"type":"error","error":{"type":"api_error","message":"Internal server error"}} · check status.claude.com

72```

73 

74這表示 API 內部發生意外失敗。它不是由您的提示、設定或帳戶引起的。

75 

76**要做什麼:**

77 

78* 檢查 [status.claude.com](https://status.claude.com) 以了解活躍的事件

79* 等待一分鐘,然後再次傳送您的訊息。您的原始訊息仍在對話中,因此對於長提示,您可以輸入 `try again` 而不是貼上整個內容。

80* 如果錯誤持續存在且沒有發佈的事件,請執行 `/feedback` 以便 Anthropic 可以使用您的請求詳細資訊進行調查。如果您的提供者上 `/feedback` 不可用,請參閱 [Report an error](#report-an-error)。

81 

82### API Error: Repeated 529 Overloaded errors

83 

84API 在所有使用者中暫時達到容量。Claude Code 在顯示此訊息之前已經重試了多次:

85 

86```text theme={null}

87API Error: Repeated 529 Overloaded errors · check status.claude.com

88```

89 

90529 不是您的使用限制,也不會計入您的配額。

91 

92**要做什麼:**

93 

94* 檢查 [status.claude.com](https://status.claude.com) 以了解容量通知

95* 幾分鐘後再試一次

96* 執行 `/model` 並切換到不同的模型以繼續工作,因為容量是按模型追蹤的。當一個模型負載特別高時,Claude Code 會提示您執行此操作,例如 `Opus is experiencing high load, please use /model to switch to Sonnet`。

97 

98### Request timed out

99 

100API 在連線截止時間之前沒有回應。

101 

102```text theme={null}

103Request timed out

104```

105 

106這可能在高負載期間或生成非常大的回應時發生。預設請求逾時為 10 分鐘。

107 

108**要做什麼:**

109 

110* 重試請求

111* 對於長時間執行的任務,將工作分解為較小的提示

112* 如果原因是慢速網路或代理,請按照 [Automatic retries](#automatic-retries) 中的說明提高 `API_TIMEOUT_MS`

113* 如果逾時頻繁且您的網路在其他方面是健康的,請參閱下面的 [Network and connection errors](#network-and-connection-errors)

114 

115### Auto mode cannot determine the safety of an action

116 

117[auto mode](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode) 用來分類動作的模型已過載,因此 auto mode 阻止了該動作而不是未經檢查地批准它。

118 

119```text theme={null}

120<model> is temporarily unavailable, so auto mode cannot determine the safety of <tool> right now. Wait briefly and then try this action again.

121```

122 

123在您的工作目錄內的讀取、搜尋和編輯會跳過分類器,因此它們在中斷期間繼續工作。

124 

125**要做什麼:**

126 

127* 幾秒鐘後重試;Claude 看到相同的訊息,通常會自動重試

128* 如果重試持續失敗,繼續進行唯讀任務,稍後再回到被阻止的動作

129* 這是暫時的,與 [auto mode eligibility](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode) 無關;您不需要更改設定

130 

131## 使用限制

132 

133這些錯誤表示與您的帳戶或計畫相關的配額已達到。它們與影響所有人的 [server errors](#server-errors) 不同。

134 

135### You've hit your session limit

136 

137訂閱計畫包括滾動使用額度。當它用完時,您會看到以下訊息之一:

138 

139```text theme={null}

140You've hit your session limit · resets 3:45pm

141You've hit your weekly limit · resets Mon 12:00am

142You've hit your Opus limit · resets 3:45pm

143```

144 

145Claude Code 會阻止進一步的請求,直到訊息中顯示的重設時間。

146 

147**要做什麼:**

148 

149* 等待錯誤中顯示的重設時間

150* 執行 `/usage` 以查看您的計畫限制及其重設時間

151* 執行 `/extra-usage` 以在 Pro 和 Max 上購買額外使用,或在 Team 和 Enterprise 上向您的管理員請求。請參閱 [Extra usage for paid plans](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) 以了解如何計費。

152* 若要升級您的計畫以獲得更高的基本限制,請參閱 [claude.com/pricing](https://claude.com/pricing)

153 

154若要在達到限制之前監視您的剩餘額度,請將 `rate_limits` 欄位新增到 [custom status line](/zh-TW/statusline#rate-limit-usage),或在 Desktop app 中按一下模型選擇器旁邊的 [usage ring](/zh-TW/desktop#check-usage)。

155 

156### Server is temporarily limiting requests

157 

158API 應用了與您的計畫配額無關的短期節流。

159 

160```text theme={null}

161API Error: Server is temporarily limiting requests (not your usage limit)

162```

163 

164這在顯示之前會 [retried automatically](#automatic-retries)。

165 

166**要做什麼:**

167 

168* 稍等片刻,然後再試一次

169* 如果持續存在,請檢查 [status.claude.com](https://status.claude.com)

170 

171### Request rejected (429)

172 

173您已達到為您的 API 金鑰、Amazon Bedrock 專案或 Google Vertex AI 專案配置的速率限制。

174 

175```text theme={null}

176API Error: Request rejected (429) · this may be a temporary capacity issue

177```

178 

179**要做什麼:**

180 

181* 執行 `/status` 並確認活躍的認證是您期望的。環境中的流浪 `ANTHROPIC_API_KEY` 可能會透過低階金鑰而不是您的訂閱路由請求。

182* 檢查您的提供者主控台以了解活躍的限制,並在需要時請求更高的層級

183* 對於 Anthropic API 金鑰,請參閱 [rate limits reference](https://platform.claude.com/docs/en/api/rate-limits) 以了解層級如何運作以及如何設定每個工作區的上限

184* 降低並行性:降低 [`CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY`](/zh-TW/env-vars)、避免執行許多平行子代理,或使用 `/model` 切換到較小的模型以進行高容量指令碼執行

185 

186### Credit balance is too low

187 

188您的 Console 組織已用完預付額度。

189 

190```text theme={null}

191Credit balance is too low

192```

193 

194**要做什麼:**

195 

196* 在 [platform.claude.com/settings/billing](https://platform.claude.com/settings/billing) 新增額度,並考慮在那裡啟用自動重新載入,以便在達到零之前重新填充餘額

197* 如果您有 Pro、Max、Team 或 Enterprise 計畫,請使用 `/login` 切換到訂閱認證

198* 在 Console 中設定每個工作區的支出上限,以防止單個專案耗盡組織餘額。請參閱 [Manage costs effectively](/zh-TW/costs)。

199 

200## 認證錯誤

201 

202這些錯誤表示 Claude Code 無法向 API 證明您的身份。隨時執行 `/status` 以查看目前活躍的認證。

203 

204### Not logged in

205 

206此工作階段沒有有效的認證可用。

207 

208```text theme={null}

209Not logged in · Please run /login

210```

211 

212**要做什麼:**

213 

214* 執行 `/login` 以使用您的 Claude 訂閱或 Console 帳戶進行認證

215* 如果您期望環境變數對您進行認證,請確認 `ANTHROPIC_API_KEY` 已在您啟動 `claude` 的 shell 中設定並匯出

216* 對於無法進行互動式登入的 CI 或自動化,請配置一個 [`apiKeyHelper`](/zh-TW/settings#available-settings) 指令碼,在啟動時擷取金鑰

217* 請參閱 [Authentication precedence](/zh-TW/authentication#authentication-precedence) 以了解當存在多個認證時哪個會獲勝

218 

219如果系統提示您重複登入,請參閱 [Not logged in or token expired](/zh-TW/troubleshoot-install#not-logged-in-or-token-expired) 以了解系統時鐘和 macOS Keychain 修復。

220 

221### Invalid API key

222 

223`ANTHROPIC_API_KEY` 環境變數或 `apiKeyHelper` 指令碼傳回的金鑰被 API 拒絕。

224 

225```text theme={null}

226Invalid API key · Fix external API key

227```

228 

229**要做什麼:**

230 

231* 檢查拼寫錯誤,並確認金鑰未在 [Console](https://platform.claude.com/settings/keys) 中被撤銷

232* 在同一個 shell 中執行 `env | grep ANTHROPIC`。direnv、dotenv shell 外掛程式和 IDE 終端等工具可以從您的專案中的 `.env` 檔案載入過時的金鑰,而無需您明確設定它。

233* 取消設定 `ANTHROPIC_API_KEY` 並執行 `/login` 以改用訂閱認證

234* 如果金鑰來自 [`apiKeyHelper`](/zh-TW/settings#available-settings) 指令碼,請直接執行指令碼以確認它在 stdout 上列印有效的金鑰

235* 執行 `/status` 以確認 Claude Code 實際使用的認證來源

236 

237### This organization has been disabled

238 

239來自已停用 Console 組織的過時 `ANTHROPIC_API_KEY` 正在覆蓋您的訂閱登入。

240 

241```text theme={null}

242Your ANTHROPIC_API_KEY belongs to a disabled organization · Unset the environment variable to use your other credentials

243API Error: 400 ... This organization has been disabled.

244```

245 

246環境變數優先於 `/login`,因此在您的 shell 設定檔中匯出或從 `.env` 檔案載入的金鑰即使您有有效的 Pro 或 Max 訂閱也會被使用。在非互動式模式 (`-p`) 中,當存在金鑰時總是使用該金鑰。

247 

248**要做什麼:**

249 

250* 在目前的 shell 中取消設定 `ANTHROPIC_API_KEY` 並從您的 shell 設定檔中移除它,然後重新啟動 `claude`

251* 之後執行 `/status` 以確認活躍的認證是您的訂閱

252* 如果未設定環境變數且錯誤持續存在,則已停用的組織是與您的 `/login` 相關聯的組織。聯絡支援或使用不同的帳戶登入。

253 

254### OAuth token revoked or expired

255 

256您的已儲存登入不再有效。撤銷的令牌表示您在任何地方登出或管理員移除了存取權;過期的令牌表示自動重新整理在工作階段中途失敗。

257 

258```text theme={null}

259OAuth token revoked · Please run /login

260OAuth token has expired · Please run /login

261API Error: 401 ... authentication_error

262```

263 

264**要做什麼:**

265 

266* 執行 `/login` 以再次登入

267* 如果在同一工作階段中重新認證後錯誤返回,請先執行 `/logout` 以完全清除儲存的令牌,然後執行 `/login`

268* 對於跨啟動的重複登入提示,請參閱 [Troubleshooting](/zh-TW/troubleshoot-install#not-logged-in-or-token-expired) 中的系統時鐘和 macOS Keychain 檢查

269* 對於其他失敗(包括 `403 Forbidden` 和 OAuth 瀏覽器問題),請參閱 [Login and authentication](/zh-TW/troubleshoot-install#login-and-authentication)

270 

271### OAuth scope requirement

272 

273儲存的令牌早於較新功能所需的權限範圍。您最常從 `/usage` 和狀態行使用指標看到這一點:

274 

275```text theme={null}

276OAuth token does not meet scope requirement: user:profile

277```

278 

279**要做什麼:**

280 

281* 執行 `/login` 以使用目前的範圍鑄造新令牌。您不需要先登出。

282 

283## 網路和連線錯誤

284 

285這些錯誤表示 Claude Code 根本無法到達 API。它們幾乎總是源於您的本地網路、代理或防火牆,而不是 Anthropic 基礎設施。

286 

287### Unable to connect to API

288 

289到 API 的 TCP 連線失敗或從未完成。

290 

291```text theme={null}

292Unable to connect to API. Check your internet connection

293Unable to connect to API (ECONNREFUSED)

294Unable to connect to API (ECONNRESET)

295Unable to connect to API (ETIMEDOUT)

296fetch failed

297Request timed out. Check your internet connection and proxy settings

298```

299 

300常見原因包括沒有網際網路存取、阻止 `api.anthropic.com` 的 VPN 或未配置的必需公司代理。

301 

302**要做什麼:**

303 

304* 透過從同一個 shell 執行 `curl -I https://api.anthropic.com` 來確認您可以到達 API 主機。在 Windows PowerShell 上使用 `curl.exe -I https://api.anthropic.com` 以便不使用內建的 `Invoke-WebRequest` 別名。

305* 如果您在公司代理後面,請在啟動 Claude Code 之前設定 `HTTPS_PROXY` 並參閱 [Network configuration](/zh-TW/network-config)

306* 如果您透過 LLM 閘道或中繼路由,請將 [`ANTHROPIC_BASE_URL`](/zh-TW/env-vars) 設定為其位址。請參閱 [LLM gateway configuration](/zh-TW/llm-gateway) 以了解設定。

307* 確保您的防火牆允許 [Network access requirements](/zh-TW/network-config#network-access-requirements) 中列出的主機

308* 間歇性失敗會 [retried automatically](#automatic-retries);持續失敗指向本地網路問題

309 

310如果 `curl` 成功但 Claude Code 仍然失敗,原因通常是 Node.js 和網路之間的某些東西,而不是網路本身:

311 

312* 在 Linux 和 WSL 上,檢查 `/etc/resolv.conf` 是否有無法到達的名稱伺服器。WSL 特別可以從主機繼承損壞的解析器。

313* 在 macOS 上,已斷開連線或卸載的 VPN 用戶端可能會留下隧道介面或路由規則。檢查 `ifconfig` 以了解過時的 `utun` 介面,並在系統設定中移除 VPN 的網路擴充功能。

314* Docker Desktop 和類似的容器執行時可以攔截出站流量。退出它們並重試以排除這一點。

315 

316### SSL certificate errors

317 

318您網路上的代理或安全設備正在使用其自己的憑證攔截 TLS 流量,而 Node.js 不信任它。

319 

320```text theme={null}

321Unable to connect to API: SSL certificate verification failed. Check your proxy or corporate SSL certificates

322Unable to connect to API: Self-signed certificate detected

323```

324 

325**要做什麼:**

326 

327* 匯出您組織的 CA 套件,並使用 `NODE_EXTRA_CA_CERTS=/path/to/ca-bundle.pem` 指向 Node

328* 請參閱 [Network configuration](/zh-TW/network-config#custom-ca-certificates) 以了解完整的設定說明

329* 不要設定 `NODE_TLS_REJECT_UNAUTHORIZED=0`,這會完全停用憑證驗證

330 

331## 請求錯誤

332 

333這些錯誤表示 API 收到了您的請求但拒絕了其內容。

334 

335### Prompt is too long

336 

337對話加上附加檔案超過了模型的上下文視窗。

338 

339```text theme={null}

340Prompt is too long

341```

342 

343**要做什麼:**

344 

345* 執行 `/compact` 以總結較早的轉向並釋放空間,或執行 `/clear` 以重新開始

346* 執行 `/context` 以查看消耗視窗的內容的細目:系統提示、工具、記憶檔案和訊息

347* 使用 `/mcp disable <name>` 停用您未使用的 MCP 伺服器,以從上下文中移除其工具定義

348* 修剪大型 `CLAUDE.md` 記憶檔案,或將說明移至 [path-scoped rules](/zh-TW/memory#path-specific-rules),這些規則僅在相關時載入

349* 子代理從父工作階段繼承每個 MCP 工具定義,這可能會在第一個轉向之前填滿其上下文視窗。在生成子代理之前停用您未使用的 MCP 伺服器。

350* 自動壓縮預設為開啟,通常可防止此錯誤。如果您已設定 [`DISABLE_AUTO_COMPACT`](/zh-TW/env-vars),請重新啟用它或在視窗填滿之前手動執行 `/compact`。

351 

352請參閱 [Explore the context window](/zh-TW/context-window) 以取得上下文如何填滿的互動式檢視。

353 

354### Error during compaction: Conversation too long

355 

356`/compact` 本身失敗,因為沒有足夠的可用上下文來保存它產生的摘要。

357 

358```text theme={null}

359Error during compaction: Conversation too long. Press esc twice to go up a few messages and try again.

360```

361 

362當視窗在自動壓縮觸發時已經滿了,或當您在看到 `Prompt is too long` 後執行 `/compact` 時,可能會發生這種情況。

363 

364**要做什麼:**

365 

366* 按 Esc 兩次以開啟訊息清單並回退幾個轉向。這會從上下文中刪除最近的訊息。然後再次執行 `/compact`。

367* 如果回退沒有釋放足夠的空間,請執行 `/clear` 以啟動新的工作階段。您之前的對話已保留,可以使用 `/resume` 重新開啟。

368 

369### Request too large

370 

371原始請求主體在標記化之前超過了 API 的位元組限制,通常是因為貼上的大型檔案或附件。

372 

373```text theme={null}

374Request too large (max 30 MB). Double press esc to go back and remove or shrink the attached content.

375```

376 

377這是 HTTP 請求的大小限制,與 [context window limit](#prompt-is-too-long) 分開。

378 

379**要做什麼:**

380 

381* 按 Esc 兩次並回退到新增超大內容的轉向之前

382* 按路徑參考大型檔案而不是貼上其內容,以便 Claude 可以分塊讀取它們

383* 對於影像,請參閱下面的 [Image was too large](#image-was-too-large)

384 

385### Image was too large

386 

387貼上或附加的影像超過了 API 的大小或尺寸限制。

388 

389```text theme={null}

390Image was too large. Double press esc to go back and try again with a smaller image.

391API Error: 400 ... image dimensions exceed max allowed size

392```

393 

394影像在錯誤後保留在對話歷史記錄中,因此每個後續訊息都會失敗,出現相同的錯誤,直到您移除它。

395 

396**要做什麼:**

397 

398* 按 Esc 兩次並回退到新增影像的轉向之前

399* 在貼上之前調整影像大小。API 接受單個影像最長邊最多 8000 像素的影像,或當許多影像在上下文中時為 2000 像素。

400* 拍攝相關區域的更緊密螢幕截圖,而不是整個螢幕

401 

402### PDF errors

403 

404您附加的 PDF 無法處理。

405 

406```text theme={null}

407PDF too large (max 100 pages, 32 MB). Try splitting it or extracting text first.

408PDF is password protected. Try removing protection or extracting text first.

409The PDF file was not valid. Try converting to a different format first.

410```

411 

412**要做什麼:**

413 

414* 對於超大 PDF,請要求 Claude 使用 Read 工具讀取頁面範圍,而不是附加整個檔案,或使用 `pdftotext` 等工具提取文字並按路徑參考輸出檔案

415* 對於受保護或無效的 PDF,移除密碼或從其來源應用程式重新匯出檔案,然後再試一次

416 

417### Extra inputs are not permitted

418 

419Claude Code 和 API 之間的代理或 LLM 閘道剝離了 `anthropic-beta` 請求標頭,因此 API 拒絕了依賴它的欄位。

420 

421```text theme={null}

422API Error: 400 ... Extra inputs are not permitted ... context_management

423API Error: 400 ... Extra inputs are not permitted ... tools.0.custom.input_examples

424API Error: 400 ... Unexpected value(s) for the `anthropic-beta` header

425```

426 

427Claude Code 傳送僅限測試版的欄位(例如 `context_management`、`effort` 和工具 `input_examples`)以及啟用它們的 `anthropic-beta` 標頭。當閘道轉發主體但刪除標頭時,API 會看到它不識別的欄位。

428 

429**要做什麼:**

430 

431* 配置您的閘道以轉發 `anthropic-beta` 標頭。請參閱 [LLM gateway configuration](/zh-TW/llm-gateway)。

432* 作為後備,在啟動之前設定 [`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`](/zh-TW/env-vars)。這會停用需要測試版標頭的功能,以便請求透過無法轉發它的閘道成功。

433 

434### There's an issue with the selected model

435 

436配置的模型名稱未被識別,或您的帳戶缺乏對其的存取權。

437 

438```text theme={null}

439There's an issue with the selected model (claude-...). It may not exist or you may not have access to it. Run /model to select a different one.

440```

441 

442**要做什麼:**

443 

444* 執行 `/model` 以從您帳戶可用的模型中選擇

445* 使用別名(例如 `sonnet` 或 `opus`)而不是完整的版本化 ID。別名追蹤最新版本,因此它們不會過時。請參閱 [Model configuration](/zh-TW/model-config)。

446* 如果錯誤的模型一直出現,則某處設定了過時的 ID。按 [優先順序](/zh-TW/model-config#setting-your-model) 檢查:`--model` 旗標、`ANTHROPIC_MODEL` 環境變數,然後是 `.claude/settings.local.json` 中的 `model` 欄位、您專案的 `.claude/settings.json` 和 `~/.claude/settings.json`。移除過時的值,Claude Code 會回退到您的帳戶預設值。

447* 對於 Vertex AI 部署,請參閱 [Vertex AI troubleshooting](/zh-TW/google-vertex-ai#troubleshooting)。

448 

449### Claude Opus is not available with the Claude Pro plan

450 

451您的活躍訂閱計畫不包括您選擇的模型。

452 

453```text theme={null}

454Claude Opus is not available with the Claude Pro plan · Select a different model in /model

455```

456 

457**要做什麼:**

458 

459* 執行 `/model` 並選擇您的計畫包括的模型

460* 如果您最近升級了計畫但仍然看到這個,請執行 `/logout` 然後 `/login`。儲存的令牌反映您登入時的計畫,因此在現有工作階段中升級網路不會生效,直到您重新認證。

461* 請參閱 [claude.com/pricing](https://claude.com/pricing) 以了解每個計畫包括哪些模型

462 

463### thinking.type.enabled is not supported for this model

464 

465您的 Claude Code 版本早於 Opus 4.7 的最低版本。CLI 傳送了模型不再接受的思考配置。

466 

467```text theme={null}

468API Error: 400 ... "thinking.type.enabled" is not supported for this model. Use "thinking.type.adaptive" and "output_config.effort" to control thinking behavior.

469```

470 

471**要做什麼:**

472 

473* 執行 `claude update` 以升級到 v2.1.111 或更新版本,然後重新啟動 Claude Code

474* 如果您無法升級,請執行 `/model` 並選擇 Opus 4.6 或 Sonnet

475* 如果您在 Agent SDK 中遇到這個,請參閱 [SDK troubleshooting](/zh-TW/agent-sdk/quickstart#troubleshooting)

476 

477### Thinking budget exceeds output limit

478 

479配置的擴展思考預算超過最大回應長度,因此實際答案沒有剩餘空間。

480 

481```text theme={null}

482API Error: 400 ... max_tokens must be greater than thinking.budget_tokens

483```

484 

485Claude Code 在 Anthropic API 上自動調整這些值。當 [`MAX_THINKING_TOKENS`](/zh-TW/env-vars) 設定高於提供者的輸出限制時,或當計畫模式提高思考預算時,您通常會在 Amazon Bedrock 或 Google Vertex AI 上看到此錯誤。

486 

487**要做什麼:**

488 

489* 降低 `MAX_THINKING_TOKENS`,或將 [`CLAUDE_CODE_MAX_OUTPUT_TOKENS`](/zh-TW/env-vars) 提高到思考預算之上

490* 請參閱 [Extended thinking](/zh-TW/common-workflows#use-extended-thinking-thinking-mode) 以了解預算如何與輸出長度互動

491 

492### Tool use or thinking block mismatch

493 

494對話歷史記錄以不一致的狀態到達 API,通常是在工具呼叫被中斷或轉向在流中途被編輯後。

495 

496```text theme={null}

497API Error: 400 due to tool use concurrency issues. Run /rewind to recover the conversation.

498API Error: 400 ... unexpected `tool_use_id` found in `tool_result` blocks

499API Error: 400 ... thinking blocks ... cannot be modified

500```

501 

502所有三個變體都表示相同的事情:歷史記錄中 `tool_use`、`tool_result` 和 `thinking` 區塊的序列不再與 API 期望的相符。

503 

504**要做什麼:**

505 

506* 執行 `/rewind`,或按 Esc 兩次,以回退到損壞轉向之前的檢查點並從那裡繼續。請參閱 [Checkpointing](/zh-TW/checkpointing) 以了解如何建立和恢復檢查點。

507 

508## 回應品質似乎低於平常

509 

510如果 Claude 的答案似乎不如您預期的那樣有能力,但沒有顯示錯誤,原因通常是對話狀態而不是模型本身。Claude Code 不會無聲地更改模型版本。它可以在特定情況下切換到後備模型,例如達到 Opus 配額或 Bedrock 或 Vertex AI 區域缺乏您的模型;下面的模型選擇檢查會捕獲兩者,[Model configuration](/zh-TW/model-config) 解釋何時應用後備。

511 

512首先檢查這些:

513 

514* **模型選擇**:執行 `/model` 以確認您在您期望的模型上。之前的 `/model` 選擇或 `ANTHROPIC_MODEL` 環境變數可能會讓您使用比您想要的更小的模型。

515* **努力級別**:執行 `/effort` 以檢查目前的推理級別,並為困難的除錯或設計工作提高它。預設值因模型而異,因此在假設您低於最大值之前請檢查。請參閱 [Adjust effort level](/zh-TW/model-config#adjust-effort-level) 以了解每個模型的預設值和 `ultrathink` 快捷方式。

516* **上下文壓力**:執行 `/context` 以查看視窗的滿度。如果接近容量,請在自然斷點執行 `/compact` 或執行 `/clear` 以重新開始。請參閱 [Explore the context window](/zh-TW/context-window) 以了解自動壓縮如何影響較早的轉向。

517* **過時的說明**:大型或過時的 `CLAUDE.md` 檔案和 MCP 工具定義消耗上下文,可能會引導回應。`/doctor` 標記超大記憶檔案和子代理定義;`/context` 顯示 MCP 工具令牌使用。

518 

519當回應出錯時,回退通常比用更正回覆效果更好。按 Esc 兩次或執行 `/rewind` 以回退到不良轉向之前,然後用更多細節重新表述提示。在執行緒中更正會將錯誤的嘗試保留在上下文中,這可能會將後來的答案錨定到它。請參閱 [Checkpointing](/zh-TW/checkpointing)。

520 

521如果在檢查上述內容後品質仍然似乎有問題,請執行 `/feedback` 並描述您期望的內容與您得到的內容。以這種方式提交的反饋包括對話記錄,這是 Anthropic 診斷真實回歸的最快方式。如果您的提供者上 `/feedback` 不可用,請參閱 [Report an error](#report-an-error)。

522 

523## 報告錯誤

524 

525本頁涵蓋來自 Claude API 的錯誤。對於來自其他 Claude Code 元件的錯誤,請參閱相關指南:

526 

527* MCP 伺服器無法連線或認證:[MCP](/zh-TW/mcp)

528* Hook 指令碼失敗或阻止工具:[Debug hooks](/zh-TW/hooks#debug-hooks)

529* 安裝期間權限被拒絕或檔案系統錯誤:[Troubleshoot installation and login](/zh-TW/troubleshoot-install)

530 

531如果此處未列出錯誤或建議的修復無法幫助:

532 

533* 在 Claude Code 內執行 `/feedback` 以將記錄和描述傳送給 Anthropic。該命令還提供開啟預填充 GitHub 問題的選項。Bedrock、Vertex AI 和 Foundry 部署上不提供反饋。

534* 執行 `/doctor` 以檢查本地配置問題

535* 檢查 [status.claude.com](https://status.claude.com) 以了解活躍的事件

536* 在 GitHub 上搜尋 [existing issues](https://github.com/anthropics/claude-code/issues)

fast-mode.md +151 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 使用快速模式加快回應速度

6 

7> 在 Claude Code 中切換快速模式,以獲得更快的 Opus 4.6 回應。

8 

9<Note>

10 快速模式處於[研究預覽](#research-preview)階段。該功能、定價和可用性可能會根據反饋而改變。

11</Note>

12 

13快速模式是 Claude Opus 4.6 的高速配置,使模型速度提升 2.5 倍,但每個 token 的成本更高。當您需要速度進行互動式工作(如快速迭代或實時調試)時,使用 `/fast` 切換開啟,當成本比延遲更重要時,切換關閉。

14 

15快速模式不是不同的模型。它使用相同的 Opus 4.6,但採用不同的 API 配置,優先考慮速度而非成本效率。您獲得相同的品質和功能,只是回應速度更快。

16 

17<Note>

18 快速模式需要 Claude Code v2.1.36 或更新版本。使用 `claude --version` 檢查您的版本。

19</Note>

20 

21需要了解的事項:

22 

23* 使用 `/fast` 在 Claude Code CLI 中切換快速模式。也可在 Claude Code VS Code 擴充功能中透過 `/fast` 使用。

24* Opus 4.6 快速模式定價起價為 \$30/150 MTok。快速模式在 2 月 16 日太平洋時間 11:59pm 之前以 50% 折扣提供給所有方案。

25* 適用於訂閱方案(Pro/Max/Team/Enterprise)上的所有 Claude Code 使用者和 Claude Console。

26* 對於訂閱方案(Pro/Max/Team/Enterprise)上的 Claude Code 使用者,快速模式僅透過額外使用提供,不包含在訂閱速率限制中。

27 

28本頁涵蓋如何[切換快速模式](#toggle-fast-mode)、其[成本權衡](#understand-the-cost-tradeoff)、[何時使用](#decide-when-to-use-fast-mode)、[要求](#requirements)、[每個工作階段選擇加入](#require-per-session-opt-in)和[速率限制行為](#handle-rate-limits)。

29 

30## 切換快速模式

31 

32透過以下任一方式切換快速模式:

33 

34* 輸入 `/fast` 並按 Tab 鍵切換開啟或關閉

35* 在您的[使用者設定檔案](/zh-TW/settings)中設定 `"fastMode": true`

36 

37預設情況下,快速模式在工作階段之間保持。管理員可以配置快速模式在每個工作階段重設。詳見[要求每個工作階段選擇加入](#require-per-session-opt-in)。

38 

39為了獲得最佳成本效率,在工作階段開始時啟用快速模式,而不是在對話中途切換。詳見[了解成本權衡](#understand-the-cost-tradeoff)。

40 

41當您啟用快速模式時:

42 

43* 如果您使用不同的模型,Claude Code 會自動切換到 Opus 4.6

44* 您會看到確認訊息:"Fast mode ON"

45* 快速模式啟用時,提示旁會出現一個小的 `↯` 圖示

46* 隨時再次執行 `/fast` 以檢查快速模式是否開啟或關閉

47 

48當您再次使用 `/fast` 關閉快速模式時,您仍保持在 Opus 4.6 上。模型不會還原到您之前的模型。要切換到不同的模型,請使用 `/model`。

49 

50## 了解成本權衡

51 

52快速模式的每個 token 定價高於標準 Opus 4.6:

53 

54| 模式 | 輸入 (MTok) | 輸出 (MTok) |

55| ------------------------ | --------- | --------- |

56| Opus 4.6 上的快速模式 (\<200K) | \$30 | \$150 |

57| Opus 4.6 上的快速模式 (>200K) | \$60 | \$225 |

58 

59快速模式與 1M token 擴展上下文視窗相容。

60 

61當您在對話中途切換到快速模式時,您需要為整個對話上下文支付完整的快速模式未快取輸入 token 價格。這比從一開始就啟用快速模式的成本更高。

62 

63## 決定何時使用快速模式

64 

65快速模式最適合用於回應延遲比成本更重要的互動式工作:

66 

67* 快速迭代程式碼變更

68* 實時調試工作階段

69* 時間敏感的工作,有緊迫的截止日期

70 

71標準模式更適合:

72 

73* 速度不那麼重要的長期自主任務

74* 批次處理或 CI/CD 管道

75* 成本敏感的工作負載

76 

77### 快速模式與努力等級

78 

79快速模式和努力等級都會影響回應速度,但方式不同:

80 

81| 設定 | 效果 |

82| ----------- | ------------------------- |

83| **快速模式** | 相同的模型品質、更低的延遲、更高的成本 |

84| **較低的努力等級** | 較少的思考時間、更快的回應、複雜任務上可能品質較低 |

85 

86您可以結合兩者:在直接任務上使用快速模式搭配較低的[努力等級](/zh-TW/model-config#adjust-effort-level)以獲得最大速度。

87 

88## 要求

89 

90快速模式需要以下所有條件:

91 

92* **第三方雲端提供商上不可用**:快速模式在 Amazon Bedrock、Google Vertex AI 或 Microsoft Azure Foundry 上不可用。快速模式可透過 Anthropic Console API 和使用額外使用的 Claude 訂閱方案取得。

93* **啟用額外使用**:您的帳戶必須啟用額外使用,這允許超出您方案包含使用量的計費。對於個人帳戶,在您的 [Console 計費設定](https://platform.claude.com/settings/organization/billing)中啟用此功能。對於 Teams 和 Enterprise,管理員必須為組織啟用額外使用。

94 

95<Note>

96 快速模式使用直接計費到額外使用,即使您的方案上還有剩餘使用量。這意味著快速模式 token 不計入您方案的包含使用量,並從第一個 token 開始按快速模式費率計費。

97</Note>

98 

99* **Teams 和 Enterprise 的管理員啟用**:快速模式預設對 Teams 和 Enterprise 組織禁用。管理員必須明確[啟用快速模式](#enable-fast-mode-for-your-organization),使用者才能存取它。

100 

101<Note>

102 如果您的管理員尚未為您的組織啟用快速模式,`/fast` 命令將顯示「Fast mode has been disabled by your organization.」

103</Note>

104 

105### 為您的組織啟用快速模式

106 

107管理員可以在以下位置啟用快速模式:

108 

109* **Console**(API 客戶):[Claude Code 偏好設定](https://platform.claude.com/claude-code/preferences)

110* **Claude AI**(Teams 和 Enterprise):[管理員設定 > Claude Code](https://claude.ai/admin-settings/claude-code)

111 

112另一個完全禁用快速模式的選項是設定 `CLAUDE_CODE_DISABLE_FAST_MODE=1`。詳見[環境變數](/zh-TW/env-vars)。

113 

114### 要求每個工作階段選擇加入

115 

116預設情況下,快速模式在工作階段之間保持:如果使用者啟用快速模式,它在未來工作階段中保持開啟。[Teams](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=fast_mode_teams#team-&-enterprise) 或 [Enterprise](https://anthropic.com/contact-sales?utm_source=claude_code\&utm_medium=docs\&utm_content=fast_mode_enterprise) 方案上的管理員可以透過在[受管設定](/zh-TW/settings#settings-files)或[伺服器受管設定](/zh-TW/server-managed-settings)中將 `fastModePerSessionOptIn` 設定為 `true` 來防止這種情況。這會導致每個工作階段以快速模式關閉開始,要求使用者使用 `/fast` 明確啟用它。

117 

118```json theme={null}

119{

120 "fastModePerSessionOptIn": true

121}

122```

123 

124這對於控制執行多個並行工作階段的使用者的組織成本很有用。使用者在需要速度時仍可以使用 `/fast` 啟用快速模式,但它在每個新工作階段開始時重設。使用者的快速模式偏好設定仍會保存,因此移除此設定會還原預設的持久行為。

125 

126## 處理速率限制

127 

128快速模式與標準 Opus 4.6 有不同的速率限制。當您達到快速模式速率限制或用完額外使用額度時:

129 

1301. 快速模式自動回退到標準 Opus 4.6

1312. `↯` 圖示變灰以指示冷卻

1323. 您以標準速度和定價繼續工作

1334. 冷卻期過期時,快速模式自動重新啟用

134 

135要手動禁用快速模式而不是等待冷卻,請再次執行 `/fast`。

136 

137## 研究預覽

138 

139快速模式是研究預覽功能。這意味著:

140 

141* 該功能可能會根據反饋而改變

142* 可用性和定價可能會改變

143* 底層 API 配置可能會演變

144 

145透過您通常的 Anthropic 支援管道報告問題或反饋。

146 

147## 另請參閱

148 

149* [模型配置](/zh-TW/model-config):切換模型和調整努力等級

150* [有效管理成本](/zh-TW/costs):追蹤 token 使用量並降低成本

151* [狀態行配置](/zh-TW/statusline):顯示模型和上下文資訊

features-overview.md +294 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 擴展 Claude Code

6 

7> 了解何時使用 CLAUDE.md、Skills、subagents、hooks、MCP 和 plugins。

8 

9Claude Code 結合了一個能夠推理您程式碼的模型與[內建工具](/zh-TW/how-claude-code-works#tools),用於檔案操作、搜尋、執行和網路存取。內建工具涵蓋了大多數編碼任務。本指南涵蓋擴展層:您添加的功能,用於自訂 Claude 的知識、將其連接到外部服務,以及自動化工作流程。

10 

11<Note>

12 有關核心代理迴圈如何運作的資訊,請參閱[Claude Code 如何運作](/zh-TW/how-claude-code-works)。

13</Note>

14 

15**初次使用 Claude Code?** 從[CLAUDE.md](/zh-TW/memory)開始了解專案約定。根據需要添加其他擴展。

16 

17## 概述

18 

19擴展插入代理迴圈的不同部分:

20 

21* **[CLAUDE.md](/zh-TW/memory)** 添加 Claude 在每個會話中看到的持久上下文

22* **[Skills](/zh-TW/skills)** 添加可重複使用的知識和可調用的工作流程

23* **[MCP](/zh-TW/mcp)** 將 Claude 連接到外部服務和工具

24* **[Subagents](/zh-TW/sub-agents)** 在隔離的上下文中運行自己的迴圈,返回摘要

25* **[Agent teams](/zh-TW/agent-teams)** 協調多個獨立會話,具有共享任務和點對點訊息傳遞

26* **[Hooks](/zh-TW/hooks)** 完全在迴圈外運行作為確定性指令碼

27* **[Plugins](/zh-TW/plugins)** 和 **[marketplaces](/zh-TW/plugin-marketplaces)** 打包和分發這些功能

28 

29[Skills](/zh-TW/skills)是最靈活的擴展。Skill 是一個包含知識、工作流程或指令的 markdown 檔案。您可以使用像 `/deploy` 這樣的命令調用 skills,或者 Claude 可以在相關時自動載入它們。Skills 可以在您目前的對話中運行,或通過 subagents 在隔離的上下文中運行。

30 

31## 將功能與您的目標相匹配

32 

33功能範圍從 Claude 在每個會話中看到的始終開啟的上下文,到您或 Claude 可以調用的按需功能,再到在特定事件上運行的背景自動化。下表顯示了可用的功能以及何時使用每一個。

34 

35| 功能 | 它的作用 | 何時使用 | 範例 |

36| ------------------------------------- | ---------------------- | --------------------- | ----------------------------------------- |

37| **CLAUDE.md** | 每次對話載入的持久上下文 | 專案約定、「始終執行 X」規則 | 「使用 pnpm,而不是 npm。在提交前運行測試。」 |

38| **Skill** | Claude 可以使用的指令、知識和工作流程 | 可重複使用的內容、參考文件、可重複的任務 | `/deploy` 運行您的部署檢查清單;包含端點模式的 API 文件 skill |

39| **Subagent** | 返回摘要結果的隔離執行上下文 | 上下文隔離、並行任務、專門的工作者 | 讀取許多檔案但僅返回關鍵發現的研究任務 |

40| **[Agent teams](/zh-TW/agent-teams)** | 協調多個獨立的 Claude Code 會話 | 並行研究、新功能開發、使用競爭假設進行除錯 | 生成審查者以同時檢查安全性、效能和測試 |

41| **MCP** | 連接到外部服務 | 外部資料或操作 | 查詢您的資料庫、發佈到 Slack、控制瀏覽器 |

42| **Hook** | 在事件上運行的確定性指令碼 | 可預測的自動化,不涉及 LLM | 在每次檔案編輯後運行 ESLint |

43 

44**[Plugins](/zh-TW/plugins)** 是打包層。Plugin 將 skills、hooks、subagents 和 MCP servers 捆綁到單個可安裝單元中。Plugin skills 是命名空間的(如 `/my-plugin:review`),因此多個 plugins 可以共存。當您想在多個儲存庫中重複使用相同的設置或通過 **[marketplace](/zh-TW/plugin-marketplaces)** 分發給他人時,使用 plugins。

45 

46### 比較相似的功能

47 

48某些功能可能看起來相似。以下是如何區分它們。

49 

50<Tabs>

51 <Tab title="Skill vs Subagent">

52 Skills 和 subagents 解決不同的問題:

53 

54 * **Skills** 是可重複使用的內容,您可以將其載入任何上下文

55 * **Subagents** 是與您的主要對話分開運行的隔離工作者

56 

57 | 方面 | Skill | Subagent |

58 | -------- | ---------------- | --------------------- |

59 | **它是什麼** | 可重複使用的指令、知識或工作流程 | 具有自己上下文的隔離工作者 |

60 | **主要優勢** | 在上下文之間共享內容 | 上下文隔離。工作單獨進行,僅返回摘要 |

61 | **最適合** | 參考資料、可調用的工作流程 | 讀取許多檔案的任務、並行工作、專門的工作者 |

62 

63 **Skills 可以是參考或操作。** 參考 skills 提供 Claude 在整個會話中使用的知識(如您的 API 風格指南)。操作 skills 告訴 Claude 執行特定操作(如運行您的部署工作流程的 `/deploy`)。

64 

65 **當您需要上下文隔離或您的上下文視窗變滿時,使用 subagent**。Subagent 可能讀取數十個檔案或運行廣泛的搜尋,但您的主要對話僅接收摘要。由於 subagent 工作不消耗您的主要上下文,當您不需要中間工作保持可見時,這也很有用。自訂 subagents 可以有自己的指令,並可以預載 skills。

66 

67 **它們可以結合。** Subagent 可以預載特定 skills(`skills:` 欄位)。Skill 可以使用 `context: fork` 在隔離的上下文中運行。有關詳細資訊,請參閱 [Skills](/zh-TW/skills)。

68 </Tab>

69 

70 <Tab title="CLAUDE.md vs Skill">

71 兩者都存儲指令,但它們的載入方式和用途不同。

72 

73 | 方面 | CLAUDE.md | Skill |

74 | ------------ | --------------- | --------------- |

75 | **載入** | 每個會話,自動 | 按需 |

76 | **可以包含檔案** | 是,使用 `@path` 匯入 | 是,使用 `@path` 匯入 |

77 | **可以觸發工作流程** | 否 | 是,使用 `/<name>` |

78 | **最適合** | 「始終執行 X」規則 | 參考資料、可調用的工作流程 |

79 

80 **如果 Claude 應該始終知道它,請將其放在 CLAUDE.md 中**:編碼約定、構建命令、專案結構、「永遠不要執行 X」規則。

81 

82 **如果它是 Claude 有時需要的參考資料(API 文件、風格指南)或您使用 `/<name>` 觸發的工作流程(部署、審查、發佈),請將其放在 skill 中**。

83 

84 **經驗法則:** 保持 CLAUDE.md 在 200 行以下。如果它在增長,將參考內容移動到 skills 或拆分為 [`.claude/rules/`](/zh-TW/memory#organize-rules-with-clauderules) 檔案。

85 </Tab>

86 

87 <Tab title="CLAUDE.md vs Rules vs Skills">

88 所有三者都存儲指令,但它們的載入方式不同:

89 

90 | 方面 | CLAUDE.md | `.claude/rules/` | Skill |

91 | ------- | --------- | ---------------- | ------------- |

92 | **載入** | 每個會話 | 每個會話,或在打開匹配檔案時 | 按需,在調用或相關時 |

93 | **範圍** | 整個專案 | 可以限定到檔案路徑 | 特定於任務 |

94 | **最適合** | 核心約定和構建命令 | 特定於語言或目錄的指南 | 參考資料、可重複的工作流程 |

95 

96 **使用 CLAUDE.md** 用於每個會話需要的指令:構建命令、測試約定、專案架構。

97 

98 **使用 rules** 保持 CLAUDE.md 專注。具有 [`paths` frontmatter](/zh-TW/memory#path-specific-rules) 的 rules 僅在 Claude 使用匹配檔案時載入,節省上下文。

99 

100 **使用 skills** 用於 Claude 有時只需要的內容,如 API 文件或您使用 `/<name>` 觸發的部署檢查清單。

101 </Tab>

102 

103 <Tab title="Subagent vs Agent team">

104 兩者都並行化工作,但它們在架構上不同:

105 

106 * **Subagents** 在您的會話內運行並將結果報告回您的主要上下文

107 * **Agent teams** 是相互通訊的獨立 Claude Code 會話

108 

109 | 方面 | Subagent | Agent team |

110 | -------- | ----------------- | --------------------- |

111 | **上下文** | 自己的上下文視窗;結果返回給呼叫者 | 自己的上下文視窗;完全獨立 |

112 | **通訊** | 僅向主代理報告結果 | 隊友直接相互訊息傳遞 |

113 | **協調** | 主代理管理所有工作 | 具有自我協調的共享任務清單 |

114 | **最適合** | 只有結果重要的專注任務 | 需要討論和協作的複雜工作 |

115 | **令牌成本** | 較低:結果摘要回主上下文 | 較高:每個隊友是單獨的 Claude 實例 |

116 

117 **當您需要快速、專注的工作者時,使用 subagent**:研究問題、驗證聲明、審查檔案。Subagent 執行工作並返回摘要。您的主要對話保持乾淨。

118 

119 **當隊友需要共享發現、相互質疑和獨立協調時,使用 agent team**。Agent teams 最適合具有競爭假設的研究、並行程式碼審查,以及每個隊友擁有單獨部分的新功能開發。

120 

121 **轉換點:** 如果您運行並行 subagents 但遇到上下文限制,或者您的 subagents 需要相互通訊,agent teams 是自然的下一步。

122 

123 <Note>

124 Agent teams 是實驗性的,預設情況下被禁用。有關設置和目前限制,請參閱 [agent teams](/zh-TW/agent-teams)。

125 </Note>

126 </Tab>

127 

128 <Tab title="MCP vs Skill">

129 MCP 將 Claude 連接到外部服務。Skills 擴展 Claude 的知識,包括如何有效地使用這些服務。

130 

131 | 方面 | MCP | Skill |

132 | -------- | -------------------- | ------------------------- |

133 | **它是什麼** | 連接到外部服務的協議 | 知識、工作流程和參考資料 |

134 | **提供** | 工具和資料存取 | 知識、工作流程、參考資料 |

135 | **範例** | Slack 整合、資料庫查詢、瀏覽器控制 | 程式碼審查檢查清單、部署工作流程、API 風格指南 |

136 

137 這些解決不同的問題,並且可以很好地協同工作:

138 

139 **MCP** 給予 Claude 與外部系統互動的能力。沒有 MCP,Claude 無法查詢您的資料庫或發佈到 Slack。

140 

141 **Skills** 給予 Claude 關於如何有效使用這些工具的知識,以及您可以使用 `/<name>` 觸發的工作流程。Skill 可能包括您的團隊資料庫架構和查詢模式,或具有您的團隊訊息格式規則的 `/post-to-slack` 工作流程。

142 

143 範例:MCP 伺服器將 Claude 連接到您的資料庫。Skill 教導 Claude 您的資料模型、常見查詢模式,以及用於不同任務的表格。

144 </Tab>

145</Tabs>

146 

147### 了解功能如何分層

148 

149功能可以在多個級別定義:使用者範圍、每個專案、通過 plugins,或通過受管理的策略。您也可以在子目錄中嵌套 CLAUDE.md 檔案,或在 monorepo 的特定套件中放置 skills。當相同的功能存在於多個級別時,以下是它們的分層方式:

150 

151* **CLAUDE.md 檔案** 是累加的:所有級別同時對 Claude 的上下文貢獻內容。來自您的工作目錄及以上的檔案在啟動時載入;子目錄在您在其中工作時載入。當指令衝突時,Claude 使用判斷來協調它們,更具體的指令通常優先。請參閱 [CLAUDE.md 檔案如何載入](/zh-TW/memory#how-claudemd-files-load)。

152* **Skills 和 subagents** 按名稱覆蓋:當相同名稱存在於多個級別時,一個定義根據優先級獲勝(skills 為受管理 > 使用者 > 專案;subagents 為受管理 > CLI 標誌 > 專案 > 使用者 > plugin)。Plugin skills 是[命名空間](/zh-TW/plugins#add-skills-to-your-plugin)的,以避免衝突。請參閱 [skill 發現](/zh-TW/skills#where-skills-live) 和 [subagent 範圍](/zh-TW/sub-agents#choose-the-subagent-scope)。

153* **MCP 伺服器** 按名稱覆蓋:本地 > 專案 > 使用者。請參閱 [MCP 範圍](/zh-TW/mcp#scope-hierarchy-and-precedence)。

154* **Hooks** 合併:所有註冊的 hooks 為其匹配事件觸發,無論來源如何。請參閱 [hooks](/zh-TW/hooks)。

155 

156### 結合功能

157 

158每個擴展解決不同的問題:CLAUDE.md 處理始終開啟的上下文,skills 處理按需知識和工作流程,MCP 處理外部連接,subagents 處理隔離,hooks 處理自動化。真實的設置根據您的工作流程結合它們。

159 

160例如,您可能使用 CLAUDE.md 用於專案約定、skill 用於您的部署工作流程、MCP 用於連接到您的資料庫,以及 hook 用於在每次編輯後運行 linting。每個功能處理它最擅長的事情。

161 

162| 模式 | 它如何運作 | 範例 |

163| ---------------------- | -------------------------------------- | ---------------------------------------------- |

164| **Skill + MCP** | MCP 提供連接;skill 教導 Claude 如何很好地使用它 | MCP 連接到您的資料庫,skill 記錄您的架構和查詢模式 |

165| **Skill + Subagent** | Skill 生成 subagents 進行並行工作 | `/audit` skill 啟動在隔離上下文中工作的安全性、效能和風格 subagents |

166| **CLAUDE.md + Skills** | CLAUDE.md 保持始終開啟的規則;skills 保持按需載入的參考資料 | CLAUDE.md 說'遵循我們的 API 約定',skill 包含完整的 API 風格指南 |

167| **Hook + MCP** | Hook 通過 MCP 觸發外部操作 | 編輯後 hook 在 Claude 修改關鍵檔案時發送 Slack 通知 |

168 

169## 了解上下文成本

170 

171您添加的每個功能都消耗 Claude 的一些上下文。太多可能會填滿您的上下文視窗,但它也可能添加噪聲,使 Claude 效率降低;skills 可能無法正確觸發,或 Claude 可能會失去對您的約定的追蹤。了解這些權衡有助於您構建有效的設置。

172 

173### 按功能的上下文成本

174 

175每個功能都有不同的載入策略和上下文成本:

176 

177| 功能 | 何時載入 | 什麼載入 | 上下文成本 |

178| ------------- | ---------- | ------------------ | ----------------- |

179| **CLAUDE.md** | 會話開始 | 完整內容 | 每個請求 |

180| **Skills** | 會話開始 + 使用時 | 啟動時的描述,使用時的完整內容 | 低(每個請求的描述)\* |

181| **MCP 伺服器** | 會話開始 | 所有工具定義和架構 | 每個請求 |

182| **Subagents** | 生成時 | 具有指定 skills 的新鮮上下文 | 與主會話隔離 |

183| **Hooks** | 觸發時 | 無(外部運行) | 零,除非 hook 返回額外上下文 |

184 

185\*預設情況下,skill 描述在會話開始時載入,以便 Claude 決定何時使用它們。在 skill 的 frontmatter 中設置 `disable-model-invocation: true` 以將其完全隱藏在 Claude 中,直到您手動調用它。這將 skills 的上下文成本降低到零,您只需自己觸發這些 skills。

186 

187### 了解功能如何載入

188 

189每個功能在您的會話中的不同點載入。下面的選項卡說明每個功能何時載入以及什麼進入上下文。

190 

191<img src="https://mintcdn.com/claude-code/6yTCYq1p37ZB8-CQ/images/context-loading.svg?fit=max&auto=format&n=6yTCYq1p37ZB8-CQ&q=85&s=5a58ce953a35a2412892015e2ad6cb67" alt="上下文載入:CLAUDE.md 和 MCP 在會話開始時載入並保留在每個請求中。Skills 在啟動時載入描述,在調用時載入完整內容。Subagents 獲得隔離的上下文。Hooks 外部運行。" width="720" height="410" data-path="images/context-loading.svg" />

192 

193<Tabs>

194 <Tab title="CLAUDE.md">

195 **何時:** 會話開始

196 

197 **什麼載入:** 所有 CLAUDE.md 檔案的完整內容(受管理、使用者和專案級別)。

198 

199 **繼承:** Claude 從您的工作目錄讀取 CLAUDE.md 檔案直到根目錄,並在訪問這些檔案時在子目錄中發現嵌套的檔案。有關詳細資訊,請參閱 [CLAUDE.md 檔案如何載入](/zh-TW/memory#how-claudemd-files-load)。

200 

201 <Tip>保持 CLAUDE.md 在 200 行以下。將參考資料移動到 skills,它們按需載入。</Tip>

202 </Tab>

203 

204 <Tab title="Skills">

205 Skills 是 Claude 工具包中的額外功能。它們可以是參考資料(如 API 風格指南)或可調用的工作流程,您可以使用 `/<name>` 觸發(如 `/deploy`)。Claude Code 附帶[捆綁的 skills](/zh-TW/skills#bundled-skills),如 `/simplify`、`/batch` 和 `/debug`,開箱即用。您也可以創建自己的。Claude 在適當時使用 skills,或者您可以直接調用一個。

206 

207 **何時:** 取決於 skill 的配置。預設情況下,描述在會話開始時載入,完整內容在使用時載入。對於僅使用者 skills(`disable-model-invocation: true`),在您調用它們之前不會載入任何內容。

208 

209 **什麼載入:** 對於模型可調用的 skills,Claude 在每個請求中看到名稱和描述。當您使用 `/<name>` 調用 skill 或 Claude 自動載入它時,完整內容載入到您的對話中。

210 

211 **Claude 如何選擇 skills:** Claude 將您的任務與 skill 描述相匹配,以決定哪些相關。如果描述模糊或重疊,Claude 可能載入錯誤的 skill 或錯過會有幫助的。要告訴 Claude 使用特定 skill,請使用 `/<name>` 調用它。具有 `disable-model-invocation: true` 的 Skills 對 Claude 不可見,直到您調用它們。

212 

213 **上下文成本:** 低,直到使用。僅使用者 skills 在調用前成本為零。

214 

215 **在 subagents 中:** Skills 在 subagents 中的工作方式不同。不是按需載入,傳遞給 subagent 的 skills 在啟動時完全預載入其上下文。Subagents 不從主會話繼承 skills;您必須明確指定它們。

216 

217 <Tip>對具有副作用的 skills 使用 `disable-model-invocation: true`。這節省上下文並確保只有您觸發它們。</Tip>

218 </Tab>

219 

220 <Tab title="MCP 伺服器">

221 **何時:** 會話開始。

222 

223 **什麼載入:** 來自連接伺服器的所有工具定義和 JSON 架構。

224 

225 **上下文成本:** [工具搜尋](/zh-TW/mcp#scale-with-mcp-tool-search)(預設啟用)將 MCP 工具載入到上下文的 10%,並延遲其餘部分直到需要。

226 

227 **可靠性注意:** MCP 連接可能在會話中途無聲地失敗。如果伺服器斷開連接,其工具會無警告地消失。Claude 可能嘗試使用不再存在的工具。如果您注意到 Claude 無法使用它之前可以存取的 MCP 工具,請使用 `/mcp` 檢查連接。

228 

229 <Tip>運行 `/mcp` 以查看每個伺服器的令牌成本。斷開您未主動使用的伺服器。</Tip>

230 </Tab>

231 

232 <Tab title="Subagents">

233 **何時:** 按需,當您或 Claude 為任務生成一個時。

234 

235 **什麼載入:** 新鮮、隔離的上下文,包含:

236 

237 * 系統提示(與父級共享以提高快取效率)

238 * 代理 `skills:` 欄位中列出的 skills 的完整內容

239 * CLAUDE.md 和 git 狀態(從父級繼承)

240 * 主代理在提示中傳遞的任何上下文

241 

242 **上下文成本:** 與主會話隔離。Subagents 不繼承您的對話歷史或調用的 skills。

243 

244 <Tip>對不需要您完整對話上下文的工作使用 subagents。它們的隔離防止膨脹您的主會話。</Tip>

245 </Tab>

246 

247 <Tab title="Hooks">

248 **何時:** 觸發時。Hooks 在特定生命週期事件(如工具執行、會話邊界、提示提交、權限請求和壓縮)時觸發。有關完整清單,請參閱 [Hooks](/zh-TW/hooks)。

249 

250 **什麼載入:** 預設情況下無。Hooks 作為外部指令碼運行。

251 

252 **上下文成本:** 零,除非 hook 返回添加為訊息到您的對話的輸出。

253 

254 <Tip>Hooks 非常適合不需要影響 Claude 上下文的副作用(linting、logging)。</Tip>

255 </Tab>

256</Tabs>

257 

258## 了解更多

259 

260每個功能都有自己的指南,包含設置指令、範例和配置選項。

261 

262<CardGroup cols={2}>

263 <Card title="CLAUDE.md" icon="file-lines" href="/zh-TW/memory">

264 存儲專案上下文、約定和指令

265 </Card>

266 

267 <Card title="Skills" icon="brain" href="/zh-TW/skills">

268 給予 Claude 領域專業知識和可重複使用的工作流程

269 </Card>

270 

271 <Card title="Subagents" icon="users" href="/zh-TW/sub-agents">

272 將工作卸載到隔離的上下文

273 </Card>

274 

275 <Card title="Agent teams" icon="network" href="/zh-TW/agent-teams">

276 協調多個並行工作的會話

277 </Card>

278 

279 <Card title="MCP" icon="plug" href="/zh-TW/mcp">

280 將 Claude 連接到外部服務

281 </Card>

282 

283 <Card title="Hooks" icon="bolt" href="/zh-TW/hooks-guide">

284 使用 hooks 自動化工作流程

285 </Card>

286 

287 <Card title="Plugins" icon="puzzle-piece" href="/zh-TW/plugins">

288 捆綁和共享功能集

289 </Card>

290 

291 <Card title="Marketplaces" icon="store" href="/zh-TW/plugin-marketplaces">

292 託管和分發 plugin 集合

293 </Card>

294</CardGroup>

fullscreen.md +159 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 全螢幕渲染

6 

7> 啟用更平順、無閃爍的渲染模式,具有滑鼠支援和穩定的記憶體使用,適用於長對話。

8 

9<Note>

10 全螢幕渲染是一個選擇加入的[研究預覽](#research-preview),需要 Claude Code v2.1.89 或更新版本。在您目前的對話中執行 `/tui fullscreen` 以切換,或在 v2.1.110 之前的版本上設定 `CLAUDE_CODE_NO_FLICKER=1`。行為可能會根據回饋而改變。

11</Note>

12 

13全螢幕渲染是 Claude Code CLI 的替代渲染路徑,可消除閃爍、在長對話中保持記憶體使用平穩,並新增滑鼠支援。它在終端的替代螢幕緩衝區上繪製介面,就像 `vim` 或 `htop` 一樣,並且只渲染目前可見的訊息。這減少了每次更新時傳送到終端的資料量。

14 

15在渲染吞吐量是瓶頸的終端模擬器中,差異最為明顯,例如 VS Code 整合終端、tmux 和 iTerm2。如果您的終端捲動位置在 Claude 工作時跳到頂部,或者工具輸出串流進來時螢幕閃爍,此模式可以解決這些問題。

16 

17<Note>

18 全螢幕一詞描述的是 Claude Code 如何接管終端的繪製表面,就像 `vim` 一樣。它與最大化終端視窗無關,並且在任何視窗大小下都能運作。

19</Note>

20 

21## 啟用全螢幕渲染

22 

23在任何 Claude Code 對話中執行 `/tui fullscreen`。CLI 會儲存 [`tui` 設定](/zh-TW/settings#available-settings)並重新啟動進入全螢幕模式,您的對話保持完整,因此您可以在工作階段中途切換而不會失去上下文。執行 `/tui` 不帶任何引數以列印哪個渲染器處於活動狀態。

24 

25您也可以在啟動 Claude Code 之前設定 `CLAUDE_CODE_NO_FLICKER` 環境變數:

26 

27```bash theme={null}

28CLAUDE_CODE_NO_FLICKER=1 claude

29```

30 

31`tui` 設定和環境變數是等效的。`/tui` 命令會從重新啟動的程序中清除 `CLAUDE_CODE_NO_FLICKER`,以便它寫入的設定生效。

32 

33## 變更內容

34 

35全螢幕渲染改變了 CLI 如何繪製到您的終端。輸入框保持固定在螢幕底部,而不是在輸出串流進來時移動。如果輸入在 Claude 工作時保持不動,則全螢幕渲染處於活動狀態。只有可見的訊息保留在渲染樹中,因此無論對話長度如何,記憶體都保持恆定。

36 

37因為對話存在於替代螢幕緩衝區而不是終端的捲動回溯,所以有幾件事的運作方式不同:

38 

39| 之前 | 現在 | 詳細資訊 |

40| :--------------------- | :-------------------------------------- | :--------------------------------------------- |

41| `Cmd+f` 或 tmux 搜尋來尋找文字 | `Ctrl+o` 進入文字記錄模式,然後 `/` 搜尋或 `[` 寫入捲動回溯 | [搜尋和檢閱對話](#search-and-review-the-conversation) |

42| 終端的原生點擊並拖曳來選擇和複製 | 應用程式內選擇,在滑鼠釋放時自動複製 | [使用滑鼠](#use-the-mouse) |

43| `Cmd` 點擊來開啟 URL | 點擊 URL | [使用滑鼠](#use-the-mouse) |

44 

45如果滑鼠捕捉干擾您的工作流程,您可以[關閉它](#keep-native-text-selection),同時保持無閃爍渲染。

46 

47## 使用滑鼠

48 

49全螢幕渲染捕捉滑鼠事件並在 Claude Code 內處理它們:

50 

51* **在提示輸入中點擊**以在您輸入的文字中的任何位置定位游標。

52* **點擊摺疊的工具結果**以展開它並查看完整輸出。再次點擊以摺疊。工具呼叫及其結果一起展開。只有有更多內容要顯示的訊息才可點擊。

53* **點擊 URL 或檔案路徑**以開啟它。工具輸出中的檔案路徑(例如在 Edit 或 Write 後列印的路徑)在您的預設應用程式中開啟。純 `http://` 和 `https://` URL 在您的瀏覽器中開啟。在大多數終端中,這會取代原生 `Cmd` 點擊或 `Ctrl` 點擊,滑鼠捕捉會攔截這些。在 VS Code 整合終端和類似的基於 xterm.js 的終端中,繼續使用 `Cmd` 點擊。Claude Code 在那裡遵從終端自己的連結處理程式,以避免連結開啟兩次。

54* **點擊並拖曳**以在對話中的任何位置選擇文字。雙擊選擇一個單詞,符合 iTerm2 的單詞邊界,因此檔案路徑選擇為一個單位。三擊選擇該行。

55* **使用滑鼠滾輪捲動**以在對話中移動。

56 

57選定的文字在滑鼠釋放時自動複製到您的剪貼簿。若要關閉此功能,請在 `/config` 中切換「選擇時複製」。關閉後,按 `Ctrl+Shift+c` 手動複製。在支援 kitty 鍵盤協議的終端上,例如 kitty、WezTerm、Ghostty 和 iTerm2,`Cmd+c` 也可以運作。如果您有活動選擇,`Ctrl+c` 複製而不是取消。

58 

59有活動選擇時,按住 `Shift` 並按方向鍵以從鍵盤延伸它。`Shift+↑` 和 `Shift+↓` 在選擇到達頂部或底部邊緣時捲動檢視區。`Shift+Home` 和 `Shift+End` 延伸到目前行的開始或結束。

60 

61## 捲動對話

62 

63全螢幕渲染在應用程式內處理捲動。使用這些快捷鍵來導航:

64 

65| 快捷鍵 | 動作 |

66| :-------------- | :-------------- |

67| `PgUp` / `PgDn` | 向上或向下捲動半個螢幕 |

68| `Ctrl+Home` | 跳到對話的開始 |

69| `Ctrl+End` | 跳到最新訊息並重新啟用自動跟隨 |

70| 滑鼠滾輪 | 一次捲動幾行 |

71 

72在沒有專用 `PgUp`、`PgDn`、`Home` 或 `End` 鍵的鍵盤上,例如 MacBook 鍵盤,按住 `Fn` 並使用方向鍵:`Fn+↑` 傳送 `PgUp`、`Fn+↓` 傳送 `PgDn`、`Fn+←` 傳送 `Home`、`Fn+→` 傳送 `End`。這使 `Ctrl+Fn+→` 成為跳到底部的快捷鍵。如果感覺很尷尬,請使用滑鼠滾輪捲動到底部以恢復跟隨,或將 `scroll:bottom` 重新繫結到可達到的東西。

73 

74這些動作是可重新繫結的。請參閱[捲動動作](/zh-TW/keybindings#scroll-actions)以取得完整的動作名稱清單,包括沒有預設繫結的半頁和整頁變體。

75 

76### 自動跟隨

77 

78向上捲動會暫停自動跟隨,以便新輸出不會將您拉回底部。按 `Ctrl+End` 或捲動到底部以恢復跟隨。

79 

80若要完全關閉自動跟隨,使檢視保持在您留下的位置,請開啟 `/config` 並將「自動捲動」設定為關閉。禁用自動捲動後,檢視永遠不會自動跳到底部。需要回應的權限提示和其他對話框無論此設定如何都仍會捲動到檢視中。

81 

82### 滑鼠滾輪捲動

83 

84滑鼠滾輪捲動需要您的終端將滑鼠事件轉發給 Claude Code。大多數終端在應用程式要求時都會執行此操作。iTerm2 將其設為每個設定檔的設定:如果滾輪無法執行任何操作,但 `PgUp` 和 `PgDn` 運作,請開啟「設定」→「設定檔」→「終端」並開啟「啟用滑鼠報告」。點擊展開和文字選擇也需要相同的設定。

85 

86如果滑鼠滾輪捲動感覺很慢,您的終端可能每個物理凹口傳送一個捲動事件,沒有乘數。某些終端(例如 Ghostty 和啟用更快捲動的 iTerm2)已經放大了滾輪事件。其他終端(包括 VS Code 整合終端)每個凹口傳送恰好一個事件。Claude Code 無法偵測哪個。

87 

88設定 `CLAUDE_CODE_SCROLL_SPEED` 以乘以基本捲動距離:

89 

90```bash theme={null}

91export CLAUDE_CODE_SCROLL_SPEED=3

92```

93 

94值 `3` 符合 `vim` 和類似應用程式中的預設值。該設定接受 1 到 20 的值。

95 

96## 搜尋和檢閱對話

97 

98`Ctrl+o` 在正常提示和文字記錄模式之間切換。若要取得更安靜的檢視,只顯示您的最後一個提示、工具呼叫的單行摘要(含編輯 diffstats)和最終回應,請執行 `/focus`。該設定在工作階段之間保持。再次執行 `/focus` 以關閉它。

99 

100文字記錄模式獲得 `less` 風格的導航和搜尋:

101 

102| 鍵 | 動作 |

103| :---------------------------------- | :----------------------------------------- |

104| `/` | 開啟搜尋。輸入以尋找符合項,`Enter` 接受,`Esc` 取消並恢復您的捲動位置 |

105| `n` / `N` | 跳到下一個或上一個符合項。在您關閉搜尋列後運作 |

106| `j` / `k` 或 `↑` / `↓` | 捲動一行 |

107| `g` / `G` 或 `Home` / `End` | 跳到頂部或底部 |

108| `Ctrl+u` / `Ctrl+d` | 捲動半頁 |

109| `Ctrl+b` / `Ctrl+f` 或 `Space` / `b` | 捲動整頁 |

110| `Ctrl+o`、`Esc` 或 `q` | 退出文字記錄模式並返回提示 |

111 

112您的終端的 `Cmd+f` 和 tmux 搜尋看不到對話,因為它存在於替代螢幕緩衝區,而不是原生捲動回溯。若要將內容交還給您的終端,請先按 `Ctrl+o` 進入文字記錄模式,然後:

113 

114* **`[`**:將完整對話寫入您的終端的原生捲動回溯緩衝區,所有工具輸出都已展開。對話現在是終端中的普通文字,因此 `Cmd+f`、tmux 複製模式和任何其他原生工具都可以搜尋或選擇它。長工作階段在發生此情況時可能會暫停片刻。這會持續到您使用 `Esc` 或 `q` 退出文字記錄模式,這會讓您回到全螢幕渲染。下一個 `Ctrl+o` 重新開始。

115* **`v`**:將對話寫入臨時檔案並在 `$VISUAL` 或 `$EDITOR` 中開啟它。

116 

117按 `Esc` 或 `q` 返回提示。

118 

119## 清除對話

120 

121在兩秒內按 `Ctrl+L` 兩次以執行 `/clear` 並開始新對話。第一次按下會重新繪製螢幕並顯示提示;第二次按下會清除對話。在 macOS 上,雙擊 `Cmd+K` 也會執行 `/clear`。

122 

123## 與 tmux 搭配使用

124 

125全螢幕渲染在 tmux 內運作,有兩個注意事項。

126 

127滑鼠滾輪捲動需要 tmux 的滑鼠模式。如果您的 `~/.tmux.conf` 尚未啟用它,請新增此行並重新載入您的設定:

128 

129```bash theme={null}

130set -g mouse on

131```

132 

133沒有滑鼠模式,滾輪事件會進入 tmux 而不是 Claude Code。使用 `PgUp` 和 `PgDn` 的鍵盤捲動無論如何都能運作。如果 Claude Code 偵測到 tmux 且滑鼠模式關閉,它會在啟動時列印一次性提示。

134 

135全螢幕渲染與 iTerm2 的 tmux 整合模式不相容,這是您使用 `tmux -CC` 進入的模式。在整合模式中,iTerm2 將每個 tmux 窗格渲染為原生分割,而不是讓 tmux 繪製到終端。替代螢幕緩衝區和滑鼠追蹤在那裡無法正確運作:滑鼠滾輪無法執行任何操作,雙擊可能會損壞終端狀態。不要在 `tmux -CC` 工作階段中啟用全螢幕渲染。在 iTerm2 內的常規 tmux(沒有 `-CC`)運作良好。

136 

137## 保持原生文字選擇

138 

139滑鼠捕捉是最常見的摩擦點,特別是在 SSH 上或 tmux 內。當 Claude Code 捕捉滑鼠事件時,您的終端的原生選擇時複製停止運作。您使用點擊並拖曳進行的選擇存在於 Claude Code 內,而不是在您的終端的選擇緩衝區中,因此 tmux 複製模式、Kitty 提示和類似工具看不到它。

140 

141Claude Code 嘗試將選擇寫入您的剪貼簿,但它使用的路徑取決於您的設定。在 tmux 內,它寫入 tmux 貼上緩衝區。在 SSH 上,它回退到 OSC 52 逃逸序列,某些終端預設會阻止這些序列。iTerm2 會阻止它們,直到您開啟 Settings → General → Selection → Applications in terminal may access clipboard。在 iTerm2 中執行 [`/terminal-setup`](/zh-TW/terminal-config) 會為您啟用此功能。Claude Code 在每次複製後列印一個快顯通知,告訴您它使用了哪個路徑。

142 

143如果您想進行一次性的原生選擇,請在點擊並拖曳時按住您的終端的略過修飾鍵:iTerm2 中的 `Option`,或大多數 Linux 和 Windows 終端中的 `Shift`。修飾鍵告訴您的終端自己處理選擇,而不是將滑鼠事件轉發給 Claude Code,因此 `Cmd+C` 和您的終端的其他複製快捷鍵可以在其上運作。

144 

145如果您一直依賴原生選擇,請設定 `CLAUDE_CODE_DISABLE_MOUSE=1` 以選擇退出滑鼠捕捉,同時保持無閃爍渲染和平穩記憶體:

146 

147```bash theme={null}

148CLAUDE_CODE_NO_FLICKER=1 CLAUDE_CODE_DISABLE_MOUSE=1 claude

149```

150 

151禁用滑鼠捕捉後,使用 `PgUp`、`PgDn`、`Ctrl+Home` 和 `Ctrl+End` 的鍵盤捲動仍然運作,您的終端原生處理選擇。您會失去點擊定位游標、點擊展開工具輸出、URL 點擊和 Claude Code 內的滾輪捲動。

152 

153## 研究預覽

154 

155全螢幕渲染是一個研究預覽功能。它已在常見終端模擬器上進行測試,但您可能會在不太常見的終端或不尋常的設定上遇到渲染問題。

156 

157如果您遇到問題,請在 Claude Code 內執行 `/feedback` 以報告它,或在 [claude-code GitHub 儲存庫](https://github.com/anthropics/claude-code/issues)上開啟問題。包括您的終端模擬器名稱和版本。

158 

159若要關閉全螢幕渲染,請執行 `/tui default`,或如果您以該方式啟用它,請取消設定環境變數。

github-actions.md +670 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Claude Code GitHub Actions

6 

7> 了解如何將 Claude Code 整合到您的開發工作流程中,使用 Claude Code GitHub Actions

8 

9Claude Code GitHub Actions 為您的 GitHub 工作流程帶來 AI 驅動的自動化。只需在任何 PR 或議題中提及 `@claude`,Claude 就可以分析您的程式碼、建立 pull request、實現功能和修復錯誤 - 同時遵循您專案的標準。如需在每個 PR 上自動發佈評論而無需觸發,請參閱 [GitHub Code Review](/zh-TW/code-review)。

10 

11<Note>

12 Claude Code GitHub Actions 建立在 [Claude Agent SDK](/zh-TW/agent-sdk/overview) 之上,該 SDK 可實現 Claude Code 與您的應用程式的程式化整合。您可以使用 SDK 來建立超越 GitHub Actions 的自訂自動化工作流程。

13</Note>

14 

15<Info>

16 **Claude Opus 4.7 現已推出。** Claude Code GitHub Actions 預設使用 Sonnet。若要使用 Opus 4.7,請設定 [model 參數](#breaking-changes-reference)以使用 `claude-opus-4-7`。

17</Info>

18 

19## 為什麼使用 Claude Code GitHub Actions?

20 

21* **即時 PR 建立**:描述您需要的內容,Claude 會建立包含所有必要變更的完整 PR

22* **自動化程式碼實現**:使用單一命令將議題轉換為可運作的程式碼

23* **遵循您的標準**:Claude 尊重您的 `CLAUDE.md` 指南和現有程式碼模式

24* **簡單設定**:使用我們的安裝程式和 API 金鑰在幾分鐘內開始使用

25* **預設安全**:您的程式碼保留在 Github 的執行器上

26 

27## Claude 可以做什麼?

28 

29Claude Code 提供了一個強大的 GitHub Action,改變了您使用程式碼的方式:

30 

31### Claude Code Action

32 

33此 GitHub Action 允許您在 GitHub Actions 工作流程中執行 Claude Code。您可以使用此功能在 Claude Code 之上建立任何自訂工作流程。

34 

35[檢視儲存庫 →](https://github.com/anthropics/claude-code-action)

36 

37## 設定

38 

39## 快速設定

40 

41設定此 action 的最簡單方法是透過終端機中的 Claude Code。只需開啟 claude 並執行 `/install-github-app`。

42 

43此命令將引導您完成 GitHub app 和所需密鑰的設定。

44 

45<Note>

46 * 您必須是儲存庫管理員才能安裝 GitHub app 並新增密鑰

47 * GitHub app 將要求對內容、議題和 Pull request 的讀取和寫入權限

48 * 此快速入門方法僅適用於直接 Claude API 使用者。如果您使用 Amazon Bedrock 或 Google Vertex AI,請參閱 [使用 Amazon Bedrock 和 Google Vertex AI](#using-with-amazon-bedrock-%26-google-vertex-ai) 部分。

49</Note>

50 

51## 手動設定

52 

53如果 `/install-github-app` 命令失敗或您偏好手動設定,請遵循以下手動設定說明:

54 

551. **安裝 Claude GitHub app** 到您的儲存庫:[https://github.com/apps/claude](https://github.com/apps/claude)

56 

57 Claude GitHub app 需要以下儲存庫權限:

58 

59 * **Contents**:讀取和寫入(修改儲存庫檔案)

60 * **Issues**:讀取和寫入(回應議題)

61 * **Pull requests**:讀取和寫入(建立 PR 和推送變更)

62 

63 如需有關安全性和權限的更多詳細資訊,請參閱 [安全性文件](https://github.com/anthropics/claude-code-action/blob/main/docs/security.md)。

642. **新增 ANTHROPIC\_API\_KEY** 到您的儲存庫密鑰([了解如何在 GitHub Actions 中使用密鑰](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions))

653. **複製工作流程檔案** 從 [examples/claude.yml](https://github.com/anthropics/claude-code-action/blob/main/examples/claude.yml) 到您的儲存庫的 `.github/workflows/`

66 

67<Tip>

68 完成快速入門或手動設定後,透過在議題或 PR 評論中標記 `@claude` 來測試 action。

69</Tip>

70 

71## 從 Beta 升級

72 

73<Warning>

74 Claude Code GitHub Actions v1.0 引入了重大變更,需要更新您的工作流程檔案才能從 beta 版本升級到 v1.0。

75</Warning>

76 

77如果您目前使用 Claude Code GitHub Actions 的 beta 版本,我們建議您更新工作流程以使用 GA 版本。新版本簡化了設定,同時新增了強大的新功能,如自動模式偵測。

78 

79### 基本變更

80 

81所有 beta 使用者必須對其工作流程檔案進行這些變更才能升級:

82 

831. **更新 action 版本**:將 `@beta` 變更為 `@v1`

842. **移除模式設定**:刪除 `mode: "tag"` 或 `mode: "agent"`(現在自動偵測)

853. **更新提示輸入**:將 `direct_prompt` 替換為 `prompt`

864. **移動 CLI 選項**:將 `max_turns`、`model`、`custom_instructions` 等轉換為 `claude_args`

87 

88### 重大變更參考

89 

90| 舊 Beta 輸入 | 新 v1.0 輸入 |

91| --------------------- | ------------------------------------- |

92| `mode` | *(已移除 - 自動偵測)* |

93| `direct_prompt` | `prompt` |

94| `override_prompt` | `prompt` 搭配 GitHub 變數 |

95| `custom_instructions` | `claude_args: --append-system-prompt` |

96| `max_turns` | `claude_args: --max-turns` |

97| `model` | `claude_args: --model` |

98| `allowed_tools` | `claude_args: --allowedTools` |

99| `disallowed_tools` | `claude_args: --disallowedTools` |

100| `claude_env` | `settings` JSON 格式 |

101 

102### 前後範例

103 

104**Beta 版本:**

105 

106```yaml theme={null}

107- uses: anthropics/claude-code-action@beta

108 with:

109 mode: "tag"

110 direct_prompt: "Review this PR for security issues"

111 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

112 custom_instructions: "Follow our coding standards"

113 max_turns: "10"

114 model: "claude-sonnet-4-6"

115```

116 

117**GA 版本 (v1.0):**

118 

119```yaml theme={null}

120- uses: anthropics/claude-code-action@v1

121 with:

122 prompt: "Review this PR for security issues"

123 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

124 claude_args: |

125 --append-system-prompt "Follow our coding standards"

126 --max-turns 10

127 --model claude-sonnet-4-6

128```

129 

130<Tip>

131 該 action 現在會根據您的設定自動偵測是否在互動模式(回應 `@claude` 提及)或自動化模式(立即使用提示執行)中執行。

132</Tip>

133 

134## 範例使用案例

135 

136Claude Code GitHub Actions 可以幫助您完成各種任務。[examples 目錄](https://github.com/anthropics/claude-code-action/tree/main/examples)包含適用於不同情境的現成工作流程。

137 

138### 基本工作流程

139 

140```yaml theme={null}

141name: Claude Code

142on:

143 issue_comment:

144 types: [created]

145 pull_request_review_comment:

146 types: [created]

147jobs:

148 claude:

149 runs-on: ubuntu-latest

150 steps:

151 - uses: anthropics/claude-code-action@v1

152 with:

153 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

154 # Responds to @claude mentions in comments

155```

156 

157### 使用 skills

158 

159```yaml theme={null}

160name: Code Review

161on:

162 pull_request:

163 types: [opened, synchronize]

164jobs:

165 review:

166 runs-on: ubuntu-latest

167 steps:

168 - uses: anthropics/claude-code-action@v1

169 with:

170 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

171 prompt: "Review this pull request for code quality, correctness, and security. Analyze the diff, then post your findings as review comments."

172 claude_args: "--max-turns 5"

173```

174 

175### 使用提示的自訂自動化

176 

177```yaml theme={null}

178name: Daily Report

179on:

180 schedule:

181 - cron: "0 9 * * *"

182jobs:

183 report:

184 runs-on: ubuntu-latest

185 steps:

186 - uses: anthropics/claude-code-action@v1

187 with:

188 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

189 prompt: "Generate a summary of yesterday's commits and open issues"

190 claude_args: "--model opus"

191```

192 

193### 常見使用案例

194 

195在議題或 PR 評論中:

196 

197```text theme={null}

198@claude implement this feature based on the issue description

199@claude how should I implement user authentication for this endpoint?

200@claude fix the TypeError in the user dashboard component

201```

202 

203Claude 將自動分析上下文並做出適當的回應。

204 

205## 最佳實踐

206 

207### CLAUDE.md 設定

208 

209在您的儲存庫根目錄建立 `CLAUDE.md` 檔案,以定義程式碼風格指南、審查標準、專案特定規則和偏好的模式。此檔案指導 Claude 對您的專案標準的理解。

210 

211### 安全考量

212 

213<Warning>永遠不要直接將 API 金鑰提交到您的儲存庫。</Warning>

214 

215如需包括權限、身份驗證和最佳實踐的全面安全指導,請參閱 [Claude Code Action 安全性文件](https://github.com/anthropics/claude-code-action/blob/main/docs/security.md)。

216 

217始終使用 GitHub Secrets 來存放 API 金鑰:

218 

219* 將您的 API 金鑰新增為名為 `ANTHROPIC_API_KEY` 的儲存庫密鑰

220* 在工作流程中參考它:`anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}`

221* 將 action 權限限制為僅必要的權限

222* 在合併前審查 Claude 的建議

223 

224始終使用 GitHub Secrets(例如 `${{ secrets.ANTHROPIC_API_KEY }}`)而不是直接在工作流程檔案中硬編碼 API 金鑰。

225 

226### 最佳化效能

227 

228使用議題範本提供上下文,保持您的 `CLAUDE.md` 簡潔且專注,並為您的工作流程設定適當的逾時。

229 

230### CI 成本

231 

232使用 Claude Code GitHub Actions 時,請注意相關成本:

233 

234**GitHub Actions 成本:**

235 

236* Claude Code 在 GitHub 託管的執行器上執行,這會消耗您的 GitHub Actions 分鐘數

237* 請參閱 [GitHub 的計費文件](https://docs.github.com/en/billing/managing-billing-for-your-products/managing-billing-for-github-actions/about-billing-for-github-actions)以了解詳細的定價和分鐘限制

238 

239**API 成本:**

240 

241* 每次 Claude 互動都會根據提示和回應的長度消耗 API 令牌

242* 令牌使用量因任務複雜性和程式碼庫大小而異

243* 請參閱 [Claude 的定價頁面](https://claude.com/platform/api)以了解目前的令牌費率

244 

245**成本最佳化提示:**

246 

247* 使用特定的 `@claude` 命令來減少不必要的 API 呼叫

248* 在 `claude_args` 中設定適當的 `--max-turns` 以防止過度迭代

249* 設定工作流程級別的逾時以避免失控的工作

250* 考慮使用 GitHub 的並行控制來限制平行執行

251 

252## 設定範例

253 

254Claude Code Action v1 使用統一參數簡化了設定:

255 

256```yaml theme={null}

257- uses: anthropics/claude-code-action@v1

258 with:

259 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

260 prompt: "Your instructions here" # Optional

261 claude_args: "--max-turns 5" # Optional CLI arguments

262```

263 

264主要功能:

265 

266* **統一提示介面** - 對所有指令使用 `prompt`

267* **Skills** - 直接從提示中呼叫已安裝的 [skills](/zh-TW/skills)

268* **CLI 傳遞** - 透過 `claude_args` 的任何 Claude Code CLI 引數

269* **靈活的觸發器** - 適用於任何 GitHub 事件

270 

271訪問 [examples 目錄](https://github.com/anthropics/claude-code-action/tree/main/examples)以取得完整的工作流程檔案。

272 

273<Tip>

274 當回應議題或 PR 評論時,Claude 會自動回應 @claude 提及。對於其他事件,使用 `prompt` 參數來提供指令。

275</Tip>

276 

277## 使用 Amazon Bedrock 和 Google Vertex AI

278 

279對於企業環境,您可以使用 Claude Code GitHub Actions 搭配您自己的雲端基礎設施。此方法讓您可以控制資料駐留和計費,同時保持相同的功能。

280 

281### 先決條件

282 

283在使用雲端提供者設定 Claude Code GitHub Actions 之前,您需要:

284 

285#### 對於 Google Cloud Vertex AI:

286 

2871. 啟用了 Vertex AI 的 Google Cloud 專案

2882. 為 GitHub Actions 設定的工作負載身份聯盟

2893. 具有所需權限的服務帳戶

2904. GitHub App(建議)或使用預設 GITHUB\_TOKEN

291 

292#### 對於 Amazon Bedrock:

293 

2941. 啟用了 Amazon Bedrock 的 AWS 帳戶

2952. 在 AWS 中設定的 GitHub OIDC 身份提供者

2963. 具有 Bedrock 權限的 IAM 角色

2974. GitHub App(建議)或使用預設 GITHUB\_TOKEN

298 

299<Steps>

300 <Step title="建立自訂 GitHub App(建議用於第三方提供者)">

301 為了在使用 Vertex AI 或 Bedrock 等第三方提供者時獲得最佳控制和安全性,我們建議建立您自己的 GitHub App:

302 

303 1. 前往 [https://github.com/settings/apps/new](https://github.com/settings/apps/new)

304 2. 填寫基本資訊:

305 * **GitHub App 名稱**:選擇唯一的名稱(例如'YourOrg Claude Assistant')

306 * **首頁 URL**:您的組織網站或儲存庫 URL

307 3. 設定 app 設定:

308 * **Webhooks**:取消勾選'Active'(此整合不需要)

309 4. 設定所需的權限:

310 * **儲存庫權限**:

311 * Contents:讀取和寫入

312 * Issues:讀取和寫入

313 * Pull requests:讀取和寫入

314 5. 點擊'Create GitHub App'

315 6. 建立後,點擊'Generate a private key'並儲存下載的 `.pem` 檔案

316 7. 從 app 設定頁面記下您的 App ID

317 8. 將 app 安裝到您的儲存庫:

318 * 從您的 app 設定頁面,點擊左側邊欄中的'Install App'

319 * 選擇您的帳戶或組織

320 * 選擇'Only select repositories'並選擇特定儲存庫

321 * 點擊'Install'

322 9. 將私鑰新增為儲存庫密鑰:

323 * 前往您的儲存庫的 Settings → Secrets and variables → Actions

324 * 建立名為 `APP_PRIVATE_KEY` 的新密鑰,內容為 `.pem` 檔案的內容

325 10. 將 App ID 新增為密鑰:

326 

327 * 建立名為 `APP_ID` 的新密鑰,內容為您的 GitHub App 的 ID

328 

329 <Note>

330 此 app 將與 [actions/create-github-app-token](https://github.com/actions/create-github-app-token) action 一起使用,以在您的工作流程中產生身份驗證令牌。

331 </Note>

332 

333 **Claude API 的替代方案或如果您不想設定自己的 Github app**:使用官方 Anthropic app:

334 

335 1. 從以下位置安裝:[https://github.com/apps/claude](https://github.com/apps/claude)

336 2. 無需額外的身份驗證設定

337 </Step>

338 

339 <Step title="設定雲端提供者身份驗證">

340 選擇您的雲端提供者並設定安全的身份驗證:

341 

342 <AccordionGroup>

343 <Accordion title="Amazon Bedrock">

344 **設定 AWS 以允許 GitHub Actions 安全地進行身份驗證,而無需儲存認證。**

345 

346 > **安全性注意**:使用儲存庫特定的設定並僅授予最少所需的權限。

347 

348 **必需的設定**:

349 

350 1. **啟用 Amazon Bedrock**:

351 * 請求在 Amazon Bedrock 中存取 Claude 模型

352 * 對於跨區域模型,請在所有必需的區域中請求存取

353 

354 2. **設定 GitHub OIDC 身份提供者**:

355 * 提供者 URL:`https://token.actions.githubusercontent.com`

356 * 受眾:`sts.amazonaws.com`

357 

358 3. **為 GitHub Actions 建立 IAM 角色**:

359 * 受信任的實體類型:Web 身份

360 * 身份提供者:`token.actions.githubusercontent.com`

361 * 權限:`AmazonBedrockFullAccess` 政策

362 * 為您的特定儲存庫設定信任政策

363 

364 **必需的值**:

365 

366 設定後,您將需要:

367 

368 * **AWS\_ROLE\_TO\_ASSUME**:您建立的 IAM 角色的 ARN

369 

370 <Tip>

371 OIDC 比使用靜態 AWS 存取金鑰更安全,因為認證是臨時的並自動輪換。

372 </Tip>

373 

374 請參閱 [AWS 文件](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html)以取得詳細的 OIDC 設定說明。

375 </Accordion>

376 

377 <Accordion title="Google Vertex AI">

378 **設定 Google Cloud 以允許 GitHub Actions 安全地進行身份驗證,而無需儲存認證。**

379 

380 > **安全性注意**:使用儲存庫特定的設定並僅授予最少所需的權限。

381 

382 **必需的設定**:

383 

384 1. **在您的 Google Cloud 專案中啟用 API**:

385 * IAM Credentials API

386 * Security Token Service (STS) API

387 * Vertex AI API

388 

389 2. **建立工作負載身份聯盟資源**:

390 * 建立工作負載身份池

391 * 新增 GitHub OIDC 提供者,具有:

392 * 簽發者:`https://token.actions.githubusercontent.com`

393 * 儲存庫和擁有者的屬性對應

394 * **安全性建議**:使用儲存庫特定的屬性條件

395 

396 3. **建立服務帳戶**:

397 * 僅授予 `Vertex AI User` 角色

398 * **安全性建議**:為每個儲存庫建立專用服務帳戶

399 

400 4. **設定 IAM 繫結**:

401 * 允許工作負載身份池模擬服務帳戶

402 * **安全性建議**:使用儲存庫特定的主體集

403 

404 **必需的值**:

405 

406 設定後,您將需要:

407 

408 * **GCP\_WORKLOAD\_IDENTITY\_PROVIDER**:完整的提供者資源名稱

409 * **GCP\_SERVICE\_ACCOUNT**:服務帳戶電子郵件地址

410 

411 <Tip>

412 工作負載身份聯盟消除了對可下載服務帳戶金鑰的需求,提高了安全性。

413 </Tip>

414 

415 如需詳細的設定說明,請參閱 [Google Cloud 工作負載身份聯盟文件](https://cloud.google.com/iam/docs/workload-identity-federation)。

416 </Accordion>

417 </AccordionGroup>

418 </Step>

419 

420 <Step title="新增必需的密鑰">

421 將以下密鑰新增到您的儲存庫(Settings → Secrets and variables → Actions):

422 

423 #### 對於 Claude API(直接):

424 

425 1. **對於 API 身份驗證**:

426 * `ANTHROPIC_API_KEY`:您的 Claude API 金鑰,來自 [console.anthropic.com](https://console.anthropic.com)

427 

428 2. **對於 GitHub App(如果使用您自己的 app)**:

429 * `APP_ID`:您的 GitHub App 的 ID

430 * `APP_PRIVATE_KEY`:私鑰 (.pem) 內容

431 

432 #### 對於 Google Cloud Vertex AI

433 

434 1. **對於 GCP 身份驗證**:

435 * `GCP_WORKLOAD_IDENTITY_PROVIDER`

436 * `GCP_SERVICE_ACCOUNT`

437 

438 2. **對於 GitHub App(如果使用您自己的 app)**:

439 * `APP_ID`:您的 GitHub App 的 ID

440 * `APP_PRIVATE_KEY`:私鑰 (.pem) 內容

441 

442 #### 對於 Amazon Bedrock

443 

444 1. **對於 AWS 身份驗證**:

445 * `AWS_ROLE_TO_ASSUME`

446 

447 2. **對於 GitHub App(如果使用您自己的 app)**:

448 * `APP_ID`:您的 GitHub App 的 ID

449 * `APP_PRIVATE_KEY`:私鑰 (.pem) 內容

450 </Step>

451 

452 <Step title="建立工作流程檔案">

453 建立與您的雲端提供者整合的 GitHub Actions 工作流程檔案。以下範例顯示了 Amazon Bedrock 和 Google Vertex AI 的完整設定:

454 

455 <AccordionGroup>

456 <Accordion title="Amazon Bedrock 工作流程">

457 **先決條件:**

458 

459 * 啟用了 Amazon Bedrock 存取且具有 Claude 模型權限

460 * GitHub 在 AWS 中設定為 OIDC 身份提供者

461 * 具有 Bedrock 權限且信任 GitHub Actions 的 IAM 角色

462 

463 **必需的 GitHub 密鑰:**

464 

465 | 密鑰名稱 | 描述 |

466 | -------------------- | --------------------------- |

467 | `AWS_ROLE_TO_ASSUME` | Bedrock 存取的 IAM 角色的 ARN |

468 | `APP_ID` | 您的 GitHub App ID(來自 app 設定) |

469 | `APP_PRIVATE_KEY` | 您為 GitHub App 產生的私鑰 |

470 

471 ```yaml theme={null}

472 name: Claude PR Action

473 

474 permissions:

475 contents: write

476 pull-requests: write

477 issues: write

478 id-token: write

479 

480 on:

481 issue_comment:

482 types: [created]

483 pull_request_review_comment:

484 types: [created]

485 issues:

486 types: [opened, assigned]

487 

488 jobs:

489 claude-pr:

490 if: |

491 (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||

492 (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||

493 (github.event_name == 'issues' && contains(github.event.issue.body, '@claude'))

494 runs-on: ubuntu-latest

495 env:

496 AWS_REGION: us-west-2

497 steps:

498 - name: Checkout repository

499 uses: actions/checkout@v4

500 

501 - name: Generate GitHub App token

502 id: app-token

503 uses: actions/create-github-app-token@v2

504 with:

505 app-id: ${{ secrets.APP_ID }}

506 private-key: ${{ secrets.APP_PRIVATE_KEY }}

507 

508 - name: Configure AWS Credentials (OIDC)

509 uses: aws-actions/configure-aws-credentials@v4

510 with:

511 role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }}

512 aws-region: us-west-2

513 

514 - uses: anthropics/claude-code-action@v1

515 with:

516 github_token: ${{ steps.app-token.outputs.token }}

517 use_bedrock: "true"

518 claude_args: '--model us.anthropic.claude-sonnet-4-6 --max-turns 10'

519 ```

520 

521 <Tip>

522 Bedrock 的模型 ID 格式包括區域前綴(例如 `us.anthropic.claude-sonnet-4-6`)。

523 </Tip>

524 </Accordion>

525 

526 <Accordion title="Google Vertex AI 工作流程">

527 **先決條件:**

528 

529 * 在您的 GCP 專案中啟用了 Vertex AI API

530 * 為 GitHub 設定的工作負載身份聯盟

531 * 具有 Vertex AI 權限的服務帳戶

532 

533 **必需的 GitHub 密鑰:**

534 

535 | 密鑰名稱 | 描述 |

536 | -------------------------------- | --------------------------- |

537 | `GCP_WORKLOAD_IDENTITY_PROVIDER` | 工作負載身份提供者資源名稱 |

538 | `GCP_SERVICE_ACCOUNT` | 具有 Vertex AI 存取權限的服務帳戶電子郵件 |

539 | `APP_ID` | 您的 GitHub App ID(來自 app 設定) |

540 | `APP_PRIVATE_KEY` | 您為 GitHub App 產生的私鑰 |

541 

542 ```yaml theme={null}

543 name: Claude PR Action

544 

545 permissions:

546 contents: write

547 pull-requests: write

548 issues: write

549 id-token: write

550 

551 on:

552 issue_comment:

553 types: [created]

554 pull_request_review_comment:

555 types: [created]

556 issues:

557 types: [opened, assigned]

558 

559 jobs:

560 claude-pr:

561 if: |

562 (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||

563 (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||

564 (github.event_name == 'issues' && contains(github.event.issue.body, '@claude'))

565 runs-on: ubuntu-latest

566 steps:

567 - name: Checkout repository

568 uses: actions/checkout@v4

569 

570 - name: Generate GitHub App token

571 id: app-token

572 uses: actions/create-github-app-token@v2

573 with:

574 app-id: ${{ secrets.APP_ID }}

575 private-key: ${{ secrets.APP_PRIVATE_KEY }}

576 

577 - name: Authenticate to Google Cloud

578 id: auth

579 uses: google-github-actions/auth@v2

580 with:

581 workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}

582 service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}

583 

584 - uses: anthropics/claude-code-action@v1

585 with:

586 github_token: ${{ steps.app-token.outputs.token }}

587 trigger_phrase: "@claude"

588 use_vertex: "true"

589 claude_args: '--model claude-sonnet-4-5@20250929 --max-turns 10'

590 env:

591 ANTHROPIC_VERTEX_PROJECT_ID: ${{ steps.auth.outputs.project_id }}

592 CLOUD_ML_REGION: us-east5

593 VERTEX_REGION_CLAUDE_4_5_SONNET: us-east5

594 ```

595 

596 <Tip>

597 專案 ID 會自動從 Google Cloud 身份驗證步驟中擷取,因此您無需硬編碼它。

598 </Tip>

599 </Accordion>

600 </AccordionGroup>

601 </Step>

602</Steps>

603 

604## 故障排除

605 

606### Claude 不回應 @claude 命令

607 

608驗證 GitHub App 是否正確安裝,檢查工作流程是否已啟用,確保 API 金鑰已在儲存庫密鑰中設定,並確認評論包含 `@claude`(不是 `/claude`)。

609 

610### CI 不在 Claude 的提交上執行

611 

612確保您使用的是 GitHub App 或自訂 app(不是 Actions 使用者),檢查工作流程觸發器是否包括必要的事件,並驗證 app 權限是否包括 CI 觸發器。

613 

614### 身份驗證錯誤

615 

616確認 API 金鑰有效且具有足夠的權限。對於 Bedrock/Vertex,檢查認證設定並確保密鑰在工作流程中命名正確。

617 

618## 進階設定

619 

620### Action 參數

621 

622Claude Code Action v1 使用簡化的設定:

623 

624| 參數 | 描述 | 必需 |

625| ------------------- | ------------------------------------------ | ----- |

626| `prompt` | Claude 的指令(純文字或 [skill](/zh-TW/skills) 名稱) | 否\* |

627| `claude_args` | 傳遞給 Claude Code 的 CLI 引數 | 否 |

628| `anthropic_api_key` | Claude API 金鑰 | 是\*\* |

629| `github_token` | 用於 API 存取的 GitHub 令牌 | 否 |

630| `trigger_phrase` | 自訂觸發短語(預設:「@claude」) | 否 |

631| `use_bedrock` | 使用 Amazon Bedrock 而不是 Claude API | 否 |

632| `use_vertex` | 使用 Google Vertex AI 而不是 Claude API | 否 |

633 

634\*提示是可選的 - 當在議題/PR 評論中省略時,Claude 回應觸發短語\

635\*\*對於直接 Claude API 是必需的,對於 Bedrock/Vertex 不是必需的

636 

637#### 傳遞 CLI 引數

638 

639`claude_args` 參數接受任何 Claude Code CLI 引數:

640 

641```yaml theme={null}

642claude_args: "--max-turns 5 --model claude-sonnet-4-6 --mcp-config /path/to/config.json"

643```

644 

645常見引數:

646 

647* `--max-turns`:最大對話輪數(預設:10)

648* `--model`:要使用的模型(例如 `claude-sonnet-4-6`)

649* `--mcp-config`:MCP 設定的路徑

650* `--allowedTools`:允許的工具的逗號分隔清單。`--allowed-tools` 別名也可以使用。

651* `--debug`:啟用偵錯輸出

652 

653### 替代整合方法

654 

655雖然 `/install-github-app` 命令是推薦的方法,但您也可以:

656 

657* **自訂 GitHub App**:對於需要品牌使用者名稱或自訂身份驗證流程的組織。建立您自己的 GitHub App,具有所需的權限(contents、issues、pull requests),並使用 actions/create-github-app-token action 在您的工作流程中產生令牌。

658* **手動 GitHub Actions**:直接工作流程設定以獲得最大靈活性

659* **MCP 設定**:Model Context Protocol 伺服器的動態載入

660 

661請參閱 [Claude Code Action 文件](https://github.com/anthropics/claude-code-action/blob/main/docs)以取得有關身份驗證、安全性和進階設定的詳細指南。

662 

663### 自訂 Claude 的行為

664 

665您可以透過兩種方式自訂 Claude 的行為:

666 

6671. **CLAUDE.md**:在您的儲存庫根目錄中的 `CLAUDE.md` 檔案中定義編碼標準、審查標準和專案特定規則。Claude 在建立 PR 和回應請求時將遵循這些指南。請查看我們的 [Memory 文件](/zh-TW/memory)以取得更多詳細資訊。

6682. **自訂提示**:在工作流程檔案中使用 `prompt` 參數來提供工作流程特定的指令。這允許您為不同的工作流程或任務自訂 Claude 的行為。

669 

670Claude 在建立 PR 和回應請求時將遵循這些指南。

gitlab-ci-cd.md +466 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Claude Code GitLab CI/CD

6 

7> 了解如何將 Claude Code 整合到您的開發工作流程中,使用 GitLab CI/CD

8 

9<Info>

10 Claude Code for GitLab CI/CD 目前處於測試版。隨著我們改進體驗,功能和功能可能會演變。

11 

12 此整合由 GitLab 維護。如需支援,請參閱以下 [GitLab issue](https://gitlab.com/gitlab-org/gitlab/-/issues/573776)。

13</Info>

14 

15<Note>

16 此整合建立在 [Claude Code CLI and Agent SDK](/zh-TW/agent-sdk/overview) 之上,可在您的 CI/CD 工作和自訂自動化工作流程中以程式設計方式使用 Claude。

17</Note>

18 

19## 為什麼要在 GitLab 中使用 Claude Code?

20 

21* **即時 MR 建立**:描述您需要的內容,Claude 會提出完整的 MR,包括變更和說明

22* **自動化實現**:使用單一命令或提及將問題轉變為可運作的程式碼

23* **專案感知**:Claude 遵循您的 `CLAUDE.md` 指南和現有程式碼模式

24* **簡單設定**:在 `.gitlab-ci.yml` 中新增一個工作和一個遮罩 CI/CD 變數

25* **企業就緒**:選擇 Claude API、Amazon Bedrock 或 Google Vertex AI 以滿足資料駐留和採購需求

26* **預設安全**:在您的 GitLab runners 中執行,具有您的分支保護和核准

27 

28## 運作方式

29 

30Claude Code 使用 GitLab CI/CD 在隔離的工作中執行 AI 任務,並透過 MR 將結果提交回去:

31 

321. **事件驅動的編排**:GitLab 監聽您選擇的觸發器(例如,在問題、MR 或審查執行緒中提及 `@claude` 的評論)。該工作從執行緒和儲存庫收集上下文,從該輸入建立提示,並執行 Claude Code。

33 

342. **提供者抽象化**:使用適合您環境的提供者:

35 * Claude API (SaaS)

36 * Amazon Bedrock (基於 IAM 的存取、跨區域選項)

37 * Google Vertex AI (GCP 原生、Workload Identity Federation)

38 

393. **沙箱執行**:每次互動都在具有嚴格網路和檔案系統規則的容器中執行。Claude Code 強制執行工作區範圍的權限以限制寫入。每項變更都透過 MR 流動,以便審查者看到差異並且核准仍然適用。

40 

41選擇區域端點以減少延遲並滿足資料主權要求,同時使用現有的雲端協議。

42 

43## Claude 可以做什麼?

44 

45Claude Code 啟用強大的 CI/CD 工作流程,改變您與程式碼的互動方式:

46 

47* 從問題描述或評論建立和更新 MR

48* 分析效能回歸並提出最佳化建議

49* 直接在分支中實現功能,然後開啟 MR

50* 修復由測試或評論識別的錯誤和回歸

51* 回應後續評論以反覆進行請求的變更

52 

53## 設定

54 

55### 快速設定

56 

57最快的入門方式是在您的 `.gitlab-ci.yml` 中新增最小工作,並將您的 API 金鑰設定為遮罩變數。

58 

591. **新增遮罩 CI/CD 變數**

60 * 前往 **Settings** → **CI/CD** → **Variables**

61 * 新增 `ANTHROPIC_API_KEY`(遮罩,根據需要保護)

62 

632. **在 `.gitlab-ci.yml` 中新增 Claude 工作**

64 

65```yaml theme={null}

66stages:

67 - ai

68 

69claude:

70 stage: ai

71 image: node:24-alpine3.21

72 # 調整規則以符合您想要觸發工作的方式:

73 # - 手動執行

74 # - 合併請求事件

75 # - 當評論包含 '@claude' 時的 web/API 觸發

76 rules:

77 - if: '$CI_PIPELINE_SOURCE == "web"'

78 - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'

79 variables:

80 GIT_STRATEGY: fetch

81 before_script:

82 - apk update

83 - apk add --no-cache git curl bash

84 - curl -fsSL https://claude.ai/install.sh | bash

85 script:

86 # 選用:如果您的設定提供,啟動 GitLab MCP server

87 - /bin/gitlab-mcp-server || true

88 # 透過 web/API 觸發器使用 AI_FLOW_* 變數時,使用上下文負載

89 - echo "$AI_FLOW_INPUT for $AI_FLOW_CONTEXT on $AI_FLOW_EVENT"

90 - >

91 claude

92 -p "${AI_FLOW_INPUT:-'Review this MR and implement the requested changes'}"

93 --permission-mode acceptEdits

94 --allowedTools "Bash Read Edit Write mcp__gitlab"

95 --debug

96```

97 

98新增工作和您的 `ANTHROPIC_API_KEY` 變數後,透過 **CI/CD** → **Pipelines** 手動執行工作進行測試,或從 MR 觸發它,讓 Claude 在分支中提出更新並在需要時開啟 MR。

99 

100<Note>

101 若要改為在 Amazon Bedrock 或 Google Vertex AI 上執行而不是 Claude API,請參閱下方的 [Using with Amazon Bedrock & Google Vertex AI](#using-with-amazon-bedrock--google-vertex-ai) 部分,了解驗證和環境設定。

102</Note>

103 

104### 手動設定(建議用於生產)

105 

106如果您偏好更受控的設定或需要企業提供者:

107 

1081. **設定提供者存取**:

109 * **Claude API**:建立並將 `ANTHROPIC_API_KEY` 儲存為遮罩 CI/CD 變數

110 * **Amazon Bedrock**:**Configure GitLab** → **AWS OIDC** 並為 Bedrock 建立 IAM 角色

111 * **Google Vertex AI**:**Configure Workload Identity Federation for GitLab** → **GCP**

112 

1132. **為 GitLab API 操作新增專案認證**:

114 * 預設使用 `CI_JOB_TOKEN`,或建立具有 `api` 範圍的專案存取令牌

115 * 如果使用 PAT,將其儲存為 `GITLAB_ACCESS_TOKEN`(遮罩)

116 

1173. **在 `.gitlab-ci.yml` 中新增 Claude 工作**(請參閱下方的範例)

118 

1194. **(選用)啟用提及驅動的觸發器**:

120 * 為「Comments (notes)」新增專案 webhook 到您的事件監聽器(如果您使用的話)

121 * 當評論包含 `@claude` 時,讓監聽器使用 `AI_FLOW_INPUT` 和 `AI_FLOW_CONTEXT` 等變數呼叫管道觸發 API

122 

123## 範例使用案例

124 

125### 將問題轉變為 MR

126 

127在問題評論中:

128 

129```text theme={null}

130@claude implement this feature based on the issue description

131```

132 

133Claude 分析問題和程式碼庫,在分支中寫入變更,並開啟 MR 供審查。

134 

135### 獲得實現幫助

136 

137在 MR 討論中:

138 

139```text theme={null}

140@claude suggest a concrete approach to cache the results of this API call

141```

142 

143Claude 提出變更,新增具有適當快取的程式碼,並更新 MR。

144 

145### 快速修復錯誤

146 

147在問題或 MR 評論中:

148 

149```text theme={null}

150@claude fix the TypeError in the user dashboard component

151```

152 

153Claude 定位錯誤,實現修復,並更新分支或開啟新的 MR。

154 

155## 使用 Amazon Bedrock 和 Google Vertex AI

156 

157對於企業環境,您可以在您的雲端基礎設施上完全執行 Claude Code,具有相同的開發人員體驗。

158 

159<Tabs>

160 <Tab title="Amazon Bedrock">

161 ### 先決條件

162 

163 在使用 Amazon Bedrock 設定 Claude Code 之前,您需要:

164 

165 1. 具有 Amazon Bedrock 存取權限的 AWS 帳戶,可存取所需的 Claude 模型

166 2. 在 AWS IAM 中設定為 OIDC 身份提供者的 GitLab

167 3. 具有 Bedrock 權限和信任政策的 IAM 角色,限制於您的 GitLab 專案/refs

168 4. 用於角色假設的 GitLab CI/CD 變數:

169 * `AWS_ROLE_TO_ASSUME`(角色 ARN)

170 * `AWS_REGION`(Bedrock 區域)

171 

172 ### 設定說明

173 

174 設定 AWS 以允許 GitLab CI 工作透過 OIDC 假設 IAM 角色(無靜態金鑰)。

175 

176 **必需的設定:**

177 

178 1. 啟用 Amazon Bedrock 並請求存取您的目標 Claude 模型

179 2. 為 GitLab 建立 IAM OIDC 提供者(如果尚未存在)

180 3. 建立由 GitLab OIDC 提供者信任的 IAM 角色,限制於您的專案和受保護的 refs

181 4. 為 Bedrock invoke API 附加最小權限

182 

183 **要儲存在 CI/CD 變數中的必需值:**

184 

185 * `AWS_ROLE_TO_ASSUME`

186 * `AWS_REGION`

187 

188 在 Settings → CI/CD → Variables 中新增變數:

189 

190 ```yaml theme={null}

191 # 對於 Amazon Bedrock:

192 - AWS_ROLE_TO_ASSUME

193 - AWS_REGION

194 ```

195 

196 使用上面的 Amazon Bedrock 工作範例在執行時交換 GitLab 工作令牌以取得臨時 AWS 認證。

197 </Tab>

198 

199 <Tab title="Google Vertex AI">

200 ### 先決條件

201 

202 在使用 Google Vertex AI 設定 Claude Code 之前,您需要:

203 

204 1. 具有以下內容的 Google Cloud 專案:

205 * 啟用 Vertex AI API

206 * 設定 Workload Identity Federation 以信任 GitLab OIDC

207 2. 僅具有所需 Vertex AI 角色的專用服務帳戶

208 3. 用於 WIF 的 GitLab CI/CD 變數:

209 * `GCP_WORKLOAD_IDENTITY_PROVIDER`(完整資源名稱)

210 * `GCP_SERVICE_ACCOUNT`(服務帳戶電子郵件)

211 

212 ### 設定說明

213 

214 設定 Google Cloud 以允許 GitLab CI 工作透過 Workload Identity Federation 模擬服務帳戶。

215 

216 **必需的設定:**

217 

218 1. 啟用 IAM Credentials API、STS API 和 Vertex AI API

219 2. 為 GitLab OIDC 建立 Workload Identity Pool 和提供者

220 3. 建立具有 Vertex AI 角色的專用服務帳戶

221 4. 授予 WIF 主體權限以模擬服務帳戶

222 

223 **要儲存在 CI/CD 變數中的必需值:**

224 

225 * `GCP_WORKLOAD_IDENTITY_PROVIDER`

226 * `GCP_SERVICE_ACCOUNT`

227 

228 在 Settings → CI/CD → Variables 中新增變數:

229 

230 ```yaml theme={null}

231 # 對於 Google Vertex AI:

232 - GCP_WORKLOAD_IDENTITY_PROVIDER

233 - GCP_SERVICE_ACCOUNT

234 - CLOUD_ML_REGION (例如,us-east5)

235 ```

236 

237 使用上面的 Google Vertex AI 工作範例在不儲存金鑰的情況下進行驗證。

238 </Tab>

239</Tabs>

240 

241## 設定範例

242 

243以下是您可以調整到您的管道的現成程式碼片段。

244 

245### 基本 .gitlab-ci.yml (Claude API)

246 

247```yaml theme={null}

248stages:

249 - ai

250 

251claude:

252 stage: ai

253 image: node:24-alpine3.21

254 rules:

255 - if: '$CI_PIPELINE_SOURCE == "web"'

256 - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'

257 variables:

258 GIT_STRATEGY: fetch

259 before_script:

260 - apk update

261 - apk add --no-cache git curl bash

262 - curl -fsSL https://claude.ai/install.sh | bash

263 script:

264 - /bin/gitlab-mcp-server || true

265 - >

266 claude

267 -p "${AI_FLOW_INPUT:-'Summarize recent changes and suggest improvements'}"

268 --permission-mode acceptEdits

269 --allowedTools "Bash Read Edit Write mcp__gitlab"

270 --debug

271 # Claude Code 將使用 CI/CD 變數中的 ANTHROPIC_API_KEY

272```

273 

274### Amazon Bedrock 工作範例 (OIDC)

275 

276**先決條件:**

277 

278* 啟用 Amazon Bedrock 並存取您選擇的 Claude 模型

279* 在 AWS 中設定 GitLab OIDC,具有信任您的 GitLab 專案和 refs 的角色

280* 具有 Bedrock 權限的 IAM 角色(建議最小權限)

281 

282**必需的 CI/CD 變數:**

283 

284* `AWS_ROLE_TO_ASSUME`:Bedrock 存取的 IAM 角色的 ARN

285* `AWS_REGION`:Bedrock 區域(例如,`us-west-2`)

286 

287```yaml theme={null}

288claude-bedrock:

289 stage: ai

290 image: node:24-alpine3.21

291 rules:

292 - if: '$CI_PIPELINE_SOURCE == "web"'

293 before_script:

294 - apk add --no-cache bash curl jq git python3 py3-pip

295 - pip install --no-cache-dir awscli

296 - curl -fsSL https://claude.ai/install.sh | bash

297 # 交換 GitLab OIDC 令牌以取得 AWS 認證

298 - export AWS_WEB_IDENTITY_TOKEN_FILE="${CI_JOB_JWT_FILE:-/tmp/oidc_token}"

299 - if [ -n "${CI_JOB_JWT_V2}" ]; then printf "%s" "$CI_JOB_JWT_V2" > "$AWS_WEB_IDENTITY_TOKEN_FILE"; fi

300 - >

301 aws sts assume-role-with-web-identity

302 --role-arn "$AWS_ROLE_TO_ASSUME"

303 --role-session-name "gitlab-claude-$(date +%s)"

304 --web-identity-token "file://$AWS_WEB_IDENTITY_TOKEN_FILE"

305 --duration-seconds 3600 > /tmp/aws_creds.json

306 - export AWS_ACCESS_KEY_ID="$(jq -r .Credentials.AccessKeyId /tmp/aws_creds.json)"

307 - export AWS_SECRET_ACCESS_KEY="$(jq -r .Credentials.SecretAccessKey /tmp/aws_creds.json)"

308 - export AWS_SESSION_TOKEN="$(jq -r .Credentials.SessionToken /tmp/aws_creds.json)"

309 script:

310 - /bin/gitlab-mcp-server || true

311 - >

312 claude

313 -p "${AI_FLOW_INPUT:-'Implement the requested changes and open an MR'}"

314 --permission-mode acceptEdits

315 --allowedTools "Bash Read Edit Write mcp__gitlab"

316 --debug

317 variables:

318 AWS_REGION: "us-west-2"

319```

320 

321<Note>

322 Bedrock 的模型 ID 包括區域特定的前綴(例如,`us.anthropic.claude-sonnet-4-6`)。如果您的工作流程支援,透過您的工作設定或提示傳遞所需的模型。

323</Note>

324 

325### Google Vertex AI 工作範例 (Workload Identity Federation)

326 

327**先決條件:**

328 

329* 在您的 GCP 專案中啟用 Vertex AI API

330* 設定 Workload Identity Federation 以信任 GitLab OIDC

331* 具有 Vertex AI 權限的服務帳戶

332 

333**必需的 CI/CD 變數:**

334 

335* `GCP_WORKLOAD_IDENTITY_PROVIDER`:完整提供者資源名稱

336* `GCP_SERVICE_ACCOUNT`:服務帳戶電子郵件

337* `CLOUD_ML_REGION`:Vertex 區域(例如,`us-east5`)

338 

339```yaml theme={null}

340claude-vertex:

341 stage: ai

342 image: gcr.io/google.com/cloudsdktool/google-cloud-cli:slim

343 rules:

344 - if: '$CI_PIPELINE_SOURCE == "web"'

345 before_script:

346 - apt-get update && apt-get install -y git && apt-get clean

347 - curl -fsSL https://claude.ai/install.sh | bash

348 # 透過 WIF 驗證到 Google Cloud(無下載的金鑰)

349 - >

350 gcloud auth login --cred-file=<(cat <<EOF

351 {

352 "type": "external_account",

353 "audience": "${GCP_WORKLOAD_IDENTITY_PROVIDER}",

354 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",

355 "service_account_impersonation_url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${GCP_SERVICE_ACCOUNT}:generateAccessToken",

356 "token_url": "https://sts.googleapis.com/v1/token"

357 }

358 EOF

359 )

360 - gcloud config set project "$(gcloud projects list --format='value(projectId)' --filter="name:${CI_PROJECT_NAMESPACE}" | head -n1)" || true

361 script:

362 - /bin/gitlab-mcp-server || true

363 - >

364 CLOUD_ML_REGION="${CLOUD_ML_REGION:-us-east5}"

365 claude

366 -p "${AI_FLOW_INPUT:-'Review and update code as requested'}"

367 --permission-mode acceptEdits

368 --allowedTools "Bash Read Edit Write mcp__gitlab"

369 --debug

370 variables:

371 CLOUD_ML_REGION: "us-east5"

372```

373 

374<Note>

375 使用 Workload Identity Federation,您不需要儲存服務帳戶金鑰。使用儲存庫特定的信任條件和最小權限服務帳戶。

376</Note>

377 

378## 最佳實踐

379 

380### CLAUDE.md 設定

381 

382在儲存庫根目錄建立 `CLAUDE.md` 檔案以定義編碼標準、審查標準和專案特定規則。Claude 在執行期間讀取此檔案並在提出變更時遵循您的慣例。

383 

384### 安全考量

385 

386**永遠不要將 API 金鑰或雲端認證提交到您的儲存庫**。始終使用 GitLab CI/CD 變數:

387 

388* 將 `ANTHROPIC_API_KEY` 新增為遮罩變數(並根據需要保護它)

389* 盡可能使用提供者特定的 OIDC(無長期金鑰)

390* 限制工作權限和網路出口

391* 像審查任何其他貢獻者一樣審查 Claude 的 MR

392 

393### 最佳化效能

394 

395* 保持 `CLAUDE.md` 專注和簡潔

396* 提供清晰的問題/MR 描述以減少反覆

397* 設定合理的工作逾時以避免失控執行

398* 在可能的情況下在 runners 中快取 npm 和套件安裝

399 

400### CI 成本

401 

402使用 Claude Code 與 GitLab CI/CD 時,請注意相關成本:

403 

404* **GitLab Runner 時間**:

405 * Claude 在您的 GitLab runners 上執行並消耗計算分鐘數

406 * 有關詳細資訊,請參閱您的 GitLab 計畫的 runner 計費

407 

408* **API 成本**:

409 * 每次 Claude 互動根據提示和回應大小消耗令牌

410 * 令牌使用量因任務複雜性和程式碼庫大小而異

411 * 有關詳細資訊,請參閱 [Anthropic 定價](https://platform.claude.com/docs/zh-TW/about-claude/pricing)

412 

413* **成本最佳化提示**:

414 * 使用特定的 `@claude` 命令以減少不必要的轉換

415 * 設定適當的 `max_turns` 和工作逾時值

416 * 限制並行以控制平行執行

417 

418## 安全和治理

419 

420* 每個工作都在具有受限網路存取的隔離容器中執行

421* Claude 的變更透過 MR 流動,以便審查者看到每個差異

422* 分支保護和核准規則適用於 AI 生成的程式碼

423* Claude Code 使用工作區範圍的權限以限制寫入

424* 成本保持在您的控制下,因為您帶來自己的提供者認證

425 

426## 疑難排解

427 

428### Claude 不回應 @claude 命令

429 

430* 驗證您的管道正在被觸發(手動、MR 事件或透過 note 事件監聽器/webhook)

431* 確保 CI/CD 變數(`ANTHROPIC_API_KEY` 或雲端提供者設定)存在且未遮罩

432* 檢查評論是否包含 `@claude`(不是 `/claude`)以及您的提及觸發器是否已設定

433 

434### 工作無法寫入評論或開啟 MR

435 

436* 確保 `CI_JOB_TOKEN` 對專案具有足夠的權限,或使用具有 `api` 範圍的專案存取令牌

437* 檢查 `mcp__gitlab` 工具是否在 `--allowedTools` 中啟用

438* 確認工作在 MR 的上下文中執行或透過 `AI_FLOW_*` 變數有足夠的上下文

439 

440### 驗證錯誤

441 

442* **對於 Claude API**:確認 `ANTHROPIC_API_KEY` 有效且未過期

443* **對於 Bedrock/Vertex**:驗證 OIDC/WIF 設定、角色模擬和祕密名稱;確認區域和模型可用性

444 

445## 進階設定

446 

447### 常見參數和變數

448 

449Claude Code 支援這些常用輸入:

450 

451* `prompt` / `prompt_file`:內聯提供說明(`-p`)或透過檔案

452* `max_turns`:限制來回反覆的次數

453* `timeout_minutes`:限制總執行時間

454* `ANTHROPIC_API_KEY`:Claude API 所需(不用於 Bedrock/Vertex)

455* 提供者特定環境:`AWS_REGION`、Vertex 的專案/區域變數

456 

457<Note>

458 確切的旗標和參數可能因 `@anthropic-ai/claude-code` 的版本而異。在您的工作中執行 `claude --help` 以查看支援的選項。

459</Note>

460 

461### 自訂 Claude 的行為

462 

463您可以透過兩種主要方式指導 Claude:

464 

4651. **CLAUDE.md**:定義編碼標準、安全要求和專案慣例。Claude 在執行期間讀取此檔案並遵循您的規則。

4662. **自訂提示**:透過工作中的 `prompt`/`prompt_file` 傳遞任務特定的說明。為不同的工作使用不同的提示(例如,審查、實現、重構)。

glossary.md +307 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 詞彙表

6 

7> Claude Code 術語定義。了解 agentic loop、compaction、CLAUDE.md、hooks、subagents、MCP 和其他核心概念的含義。

8 

9本詞彙表定義 Claude Code 術語。每個條目都連結到深入涵蓋該概念的頁面。對於 tokens、temperature 和 RAG 等模型級概念,請參閱[平台詞彙表](https://platform.claude.com/docs/en/about-claude/glossary)。

10 

11## A

12 

13### Agent teams

14 

15由團隊主導協調的多個獨立 Claude Code 會話,具有共享的任務列表和點對點訊息傳遞。與在單個會話內運行且僅向父級報告的 [subagents](#subagent) 不同,隊友各自擁有自己的上下文視窗,您可以直接與任何隊友互動。Agent teams 是實驗性的,必須通過設定 `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` 來啟用。

16 

17了解更多:[Run agent teams](/zh-TW/agent-teams)

18 

19### Agentic coding

20 

21一種工作流程,其中 AI 可以自主地讀取檔案、執行命令和進行更改,而您可以觀看、重定向或離開,與只能用文字回應的聊天助手相反,您必須自己應用這些文字。Claude Code 是 agentic 的,因為它具有讓它採取行動的 [tools](#tool),而不僅僅是提供建議。

22 

23了解更多:[How Claude Code works](/zh-TW/how-claude-code-works)

24 

25### Agentic harness

26 

27將語言模型轉變為能力強大的編碼代理的工具、上下文管理和執行環境。Claude Code 是 harness;Claude 是其中的模型。Harness 提供檔案存取、shell 執行、權限控制、記憶體載入以及將動作鏈接在一起的迴圈。

28 

29了解更多:[How Claude Code works](/zh-TW/how-claude-code-works)

30 

31### Agentic loop

32 

33Claude 為每項任務執行的循環:收集上下文、採取行動、驗證結果並重複直到完成。每個工具使用都會返回資訊,為下一步提供資訊。您可以隨時中斷迴圈進行重定向。大多數擴展點,包括 [hooks](#hook)、[skills](#skill) 和 [MCP](#mcp-model-context-protocol),都插入到此迴圈的特定階段。

34 

35了解更多:[How Claude Code works](/zh-TW/how-claude-code-works#the-agentic-loop)

36 

37### Auto memory

38 

39Claude 根據您的更正和偏好為自己編寫的筆記,按 git 儲存庫存儲在 `~/.claude/projects/` 下。同一儲存庫的所有 worktrees 共享一個 auto memory 目錄。`MEMORY.md` 索引的前 200 行或 25 KB 在每個會話開始時載入。Auto memory 是 Claude 編寫的對應物,與您編寫的 [CLAUDE.md](#claude-md) 相對。

40 

41了解更多:[Auto memory](/zh-TW/memory#auto-memory)

42 

43### Auto mode

44 

45一種 [permission mode](#permission-mode),其中單獨的分類器模型在後台審查每個動作,而不是向您顯示批准提示。分類器會阻止範圍升級、不受信任的基礎設施和 [prompt injection](#prompt-injection)。它永遠看不到工具結果,因此注入的指令無法影響其決定。Auto mode 是在 Max、Team、Enterprise 和 API 計畫上提供的研究預覽。

46 

47了解更多:[Eliminate prompts with auto mode](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode)

48 

49## B

50 

51### Bare mode

52 

53一個啟動標誌 `--bare`,它跳過 hooks、skills、plugins、MCP servers、auto memory 和 CLAUDE.md 的自動發現。只有您明確傳遞的標誌才會生效。建議用於 CI 和指令碼呼叫,其中您需要在不同機器上的相同行為,無論本地配置如何。

54 

55了解更多:[Start faster with bare mode](/zh-TW/headless#start-faster-with-bare-mode)

56 

57### Bundled skills

58 

59Claude Code 附帶的基於提示的劇本,例如 `/batch`、`/simplify`、`/debug` 和 `/loop`。與執行固定邏輯的內建命令不同,bundled skills 為 Claude 提供詳細的提示並讓它協調工作,因此它們可以生成代理、讀取檔案並適應您的程式碼庫。

60 

61了解更多:[Bundled skills](/zh-TW/skills#bundled-skills)

62 

63## C

64 

65### Channel

66 

67一個 [MCP server](#mcp-model-context-protocol),它將事件推送到您正在運行的會話中,以便 Claude 可以對您離開終端時發生的事情做出反應。Channels 可以是雙向的:Claude 讀取入站事件並通過同一 channel 回覆。Telegram、Discord 和 iMessage 包含在研究預覽中。

68 

69了解更多:[Channels](/zh-TW/channels)

70 

71### Checkpoint

72 

73在 Claude 進行每次編輯之前捕獲的程式碼自動快照。按 `Esc` 兩次或執行 `/rewind` 以將程式碼、對話或兩者恢復到較早的時間點。Checkpoints 是會話本地的,與 git 分開,不追蹤通過 Bash 工具進行的更改。

74 

75了解更多:[Checkpointing](/zh-TW/checkpointing)

76 

77### `.claude` directory

78 

79Claude Code 讀取專案範圍配置的目錄:設定、hooks、skills、subagents、rules 和 auto memory。專案在其根目錄有 `.claude/`;您的使用者級預設值在 `~/.claude/`。

80 

81了解更多:[The `.claude` directory](/zh-TW/claude-directory)

82 

83### CLAUDE.md

84 

85您為 Claude 編寫的持久指令的 markdown 檔案,在每個會話開始時作為系統提示後的使用者訊息載入。將專案約定、架構筆記和「始終執行 X」規則放在這裡。CLAUDE.md 在 [compaction](#compaction) 期間倖存,之後會從磁碟重新讀取。

86 

87您可以在專案範圍內的 `./CLAUDE.md` 或 `./.claude/CLAUDE.md`、使用者範圍內的 `~/.claude/CLAUDE.md` 或作為組織的 [managed policy](#managed-settings) 放置 CLAUDE.md。更具體的位置優先。

88 

89了解更多:[CLAUDE.md files](/zh-TW/memory#claude-md-files)

90 

91### Command

92 

93一個可重複使用的指令,您可以通過在提示中輸入 `/name` 來調用。內建命令(如 `/clear`、`/model` 和 `/compact`)控制會話。您可以在 `.claude/commands/` 中將自己的命令定義為檔案,或從 [plugin](#plugin) 安裝它們。[Skills](#skill) 是打包多步驟命令的推薦方式。

94 

95了解更多:[Commands](/zh-TW/commands) · [Skills](/zh-TW/skills)

96 

97### Compaction

98 

99當 [context window](#context-window) 接近其限制時,自動摘要您的對話。首先清除較舊的工具輸出,然後摘要對話。專案根目錄 CLAUDE.md 和 auto memory 在 compaction 期間倖存並從磁碟重新載入;僅在對話中給出的指令可能會丟失。執行 `/compact` 手動觸發,可選擇使用焦點,如 `/compact focus on the API changes`。

100 

101了解更多:[What survives compaction](/zh-TW/context-window#what-survives-compaction) · [When context fills up](/zh-TW/how-claude-code-works#when-context-fills-up)

102 

103### Context window

104 

105會話的工作記憶,保存對話歷史、檔案內容、命令輸出、CLAUDE.md、auto memory、載入的 skills 和系統指令。當您工作時,上下文會填滿直到 [compaction](#compaction) 摘要它。執行 `/context` 查看什麼在使用空間。對於基礎模型概念,請參閱[平台詞彙表](https://platform.claude.com/docs/en/about-claude/glossary#context-window)。

106 

107了解更多:[Explore the context window](/zh-TW/context-window)

108 

109## D

110 

111### Dispatch

112 

113一個電話啟動的任務路由器,當您從 Claude 行動應用程式發送編碼任務時,它會在 Desktop 應用程式中生成 Claude Code 會話。您的提示會自動路由到正確的工具。在 Pro 和 Max 計畫上可用。

114 

115了解更多:[Sessions from Dispatch](/zh-TW/desktop#sessions-from-dispatch)

116 

117## E

118 

119### Effort level

120 

121一個設定,控制 Claude 在每個回合上使用多少自適應推理思考預算。更高的努力意味著更多的思考 tokens 和更深入的推理;更低的努力更快且更便宜。Effort 在 Opus 4.7、Opus 4.6 和 Sonnet 4.6 上受支援。

122 

123了解更多:[Adjust effort level](/zh-TW/model-config#adjust-effort-level)

124 

125### Extended thinking

126 

127模型在回應前執行的可見逐步推理。您可以使用 `MAX_THINKING_TOKENS` 限制思考 tokens 或調整 [effort level](#effort-level)。思考在終端中以灰色斜體文字顯示。

128 

129了解更多:[Use extended thinking](/zh-TW/common-workflows#use-extended-thinking-thinking-mode)

130 

131## H

132 

133### Hook

134 

135一個使用者定義的處理程式,在 Claude Code 生命週期中的特定點自動執行,例如在工具執行前、檔案編輯後或會話開始時。處理程式可以是 shell 命令、HTTP 端點、MCP 工具、LLM 提示或 subagent。Hooks 是確定性的:它們在固定的生命週期點觸發,而不是由模型自行決定。

136 

137Hook 配置有三個級別:

138 

139* **Hook event**:生命週期點

140* **Matcher**:篩選哪些事件觸發它

141* **Hook handler**:執行什麼

142 

143了解更多:[Get started with hooks](/zh-TW/hooks-guide) · [Hooks reference](/zh-TW/hooks)

144 

145## M

146 

147### Managed settings

148 

149由 IT 或 DevOps 在組織範圍內強制執行的設定檔案,放置在 `~/.claude` 外的 OS 級路徑。使用者無法覆蓋或排除受管設定。使用此功能可實現安全策略、合規要求或整個機隊的標準化工具。

150 

151了解更多:[Server-managed settings](/zh-TW/server-managed-settings)

152 

153### MCP (Model Context Protocol)

154 

155一個開放標準,用於將 AI 工具連接到外部資料來源和服務。MCP servers 為 Claude 提供 Slack、Jira、資料庫、瀏覽器和數百個其他整合的新工具。您可以通過 `/mcp` 連接 servers 或將它們添加到 `.mcp.json`。有關協議本身,請參閱[平台詞彙表](https://platform.claude.com/docs/en/about-claude/glossary#mcp-model-context-protocol)。

156 

157了解更多:[Model Context Protocol](/zh-TW/mcp)

158 

159### MCP Tool Search

160 

161一個上下文節省機制,它延遲 MCP 工具架構直到需要時。只有工具名稱在啟動時載入;Claude 在決定使用特定工具時按需獲取完整架構。這可以防止閒置的 MCP servers 消耗太多上下文。

162 

163了解更多:[Scale with MCP Tool Search](/zh-TW/mcp#scale-with-mcp-tool-search)

164 

165## N

166 

167### Non-interactive mode

168 

169一種執行單個提示並退出而不進行對話會話的模式,使用 `-p` 或 `--print` 調用。用於 CI、指令碼和管道。[Agent SDK](/zh-TW/agent-sdk/overview) 是 Python 和 TypeScript 的等效項。以前稱為 headless mode。

170 

171了解更多:[Run Claude Code programmatically](/zh-TW/headless)

172 

173## O

174 

175### Output style

176 

177一個配置,修改 Claude 的系統提示以改變回應行為、語氣或格式。Output styles 關閉預設系統提示的軟體工程特定部分,與 [CLAUDE.md](#claude-md) 不同,後者作為系統提示後的使用者訊息傳遞。內建樣式包括 Default、Explanatory 和 Learning。

178 

179了解更多:[Output styles](/zh-TW/output-styles)

180 

181## P

182 

183### Permission mode

184 

185會話的基線批准行為。在 CLI 中使用 `Shift+Tab` 循環或在 VS Code、Desktop 和 claude.ai 中使用模式選擇器。可用的模式是 `default`、`acceptEdits`、`plan`、`auto`、`dontAsk` 和 `bypassPermissions`。

186 

187了解更多:[Choose a permission mode](/zh-TW/permission-modes)

188 

189### Permission rule

190 

191一個設定條目,根據工具名稱和引數模式允許、詢問或拒絕工具調用。規則按 deny→ask→allow 順序評估,首先匹配獲勝。Permission rules 是分層在更廣泛的 [permission mode](#permission-mode) 之上的細粒度控制。

192 

193了解更多:[Configure permissions](/zh-TW/permissions)

194 

195### Plan mode

196 

197一種 [permission mode](#permission-mode),其中 Claude 研究並提議更改而不編輯您的原始檔案。它可以讀取、搜索和執行探索命令,然後在觸及任何內容之前提出批准計畫。使用 `/plan` 或按 `Shift+Tab` 進入 plan mode。

198 

199了解更多:[Analyze before you edit with plan mode](/zh-TW/permission-modes#analyze-before-you-edit-with-plan-mode)

200 

201### Plugin

202 

203一個 skills、hooks、subagents 和 MCP servers 的捆綁包,打包為單個可安裝單元。Plugin skills 命名為 `plugin-name:skill-name`,以便多個 plugins 共存。通過 [marketplace](/zh-TW/plugin-marketplaces) 在團隊間分發 plugins。

204 

205了解更多:[Plugins](/zh-TW/plugins)

206 

207### Project trust

208 

209一個一次性對話框,在 Claude Code 載入其配置之前接受目錄。Trust 控制 marketplace plugins 的自動安裝和專案定義的 hooks 的執行。信任目錄意味著其 `.claude/settings.json`、`.mcp.json` 和其他配置檔案生效。

210 

211了解更多:[The `.claude` directory](/zh-TW/claude-directory)

212 

213### Prompt injection

214 

215嵌入在檔案、網頁或工具結果中的敵對指令,試圖將 Claude 重定向到您從未要求的動作。Claude Code 的防禦包括權限系統、命令黑名單和信任驗證。[Auto mode](#auto-mode) 添加了一個伺服器端探針,掃描工具結果中的可疑內容,以及一個永遠看不到工具結果的分類器,因此注入的文字無法影響其批准決定。

216 

217了解更多:[Protect against prompt injection](/zh-TW/security#protect-against-prompt-injection)

218 

219## R

220 

221### Remote Control

222 

223一種通過 claude.ai 從您的電話或瀏覽器繼續本地 Claude Code 會話的方式。您的程式碼保留在您的機器上;只有 UI 是遠端的。與在 web 上運行的 Claude Code 不同,後者在雲沙箱中運行。

224 

225了解更多:[Remote Control](/zh-TW/remote-control)

226 

227### Rules

228 

229`.claude/rules/` 中的模組化指令檔案,與 CLAUDE.md 一起載入。規則可以使用 YAML `paths:` frontmatter 進行路徑範圍設定,因此它只在 Claude 讀取匹配檔案時載入,保持上下文精簡直到相關。

230 

231了解更多:[Organize rules with `.claude/rules/`](/zh-TW/memory#organize-rules-with-claude/rules/)

232 

233## S

234 

235### Sandboxing

236 

237Bash 工具的 OS 級檔案系統和網路隔離。命令在您預先定義的邊界內執行,因此 Claude 可以在其中自由工作,無需每個命令的批准提示。Sandboxing 是與 [permission rules](#permission-rule) 分開的一層。

238 

239了解更多:[Sandboxing](/zh-TW/sandboxing)

240 

241### Session

242 

243與您當前目錄相關的對話,具有自己的獨立 [context window](#context-window)。會話可以使用 `claude -c` 恢復、使用 `--fork-session` 分叉以在新會話 ID 下保留歷史記錄,或在終端間並行執行。執行 `/clear` 啟動新會話;前一個會話保持存儲並可通過 `/resume` 獲得。每個會話的記錄存儲在 `~/.claude/projects/` 下。

244 

245了解更多:[Work with sessions](/zh-TW/how-claude-code-works#work-with-sessions)

246 

247### Settings layers

248 

249Claude Code 讀取配置的層級結構,按優先順序從最高到最低:[managed policy](#managed-settings)、命令行引數、`.claude/settings.local.json` 的本地設定、`.claude/settings.json` 的專案設定,然後是 `~/.claude/settings.json` 的使用者設定。陣列跨層級合併;較高層級的標量覆蓋較低層級的。

250 

251了解更多:[Settings files](/zh-TW/settings#settings-files)

252 

253### Skill

254 

255一個 `SKILL.md` 檔案,包含 Claude 添加到其工具包中的指令、知識或工作流程。Claude 在相關時自動載入 skill,或您可以使用 `/skill-name` 直接調用它。Skills 遵循 Agent Skills 開放標準;Claude Code 使用調用控制和 subagent 執行擴展它。

256 

257Skills 是自訂命令的推薦後繼者。`.claude/commands/deploy.md` 的檔案和 `.claude/skills/deploy/SKILL.md` 的檔案都會建立 `/deploy` 並以相同方式工作;現有命令檔案繼續工作。

258 

259了解更多:[Extend Claude with skills](/zh-TW/skills)

260 

261### Subagent

262 

263一個專門的 AI 助手,在自己的上下文視窗中運行,具有自訂系統提示、特定工具存取和獨立權限。它處理委派的任務並向主對話返回摘要。使用 subagents 將大型探索保留在主上下文之外或執行並行研究。與 [agent teams](#agent-teams) 不同,其中每個代理都是您可以直接交談的完整獨立會話。

264 

265內建 subagents 包括 Explore、Plan 和通用目的。

266 

267了解更多:[Create custom subagents](/zh-TW/sub-agents)

268 

269### Surface

270 

271您存取 Claude Code 的任何地方:CLI、VS Code、JetBrains、Desktop 或 claude.ai。所有 surfaces 共享相同的引擎,因此您的 CLAUDE.md、設定和 skills 在它們之間以相同方式工作。Slack 和 Chrome 擴展是連接到 surface 的整合,而不是 surfaces 本身。

272 

273了解更多:[Platforms and integrations](/zh-TW/platforms)

274 

275## T

276 

277### Teleport

278 

279一個命令 `/teleport`,它將雲 Claude Code 會話拉入您的本地終端。Claude 獲取分支、載入對話歷史並從 web 會話的最後狀態恢復。反向方向是 `--remote`,它將本地任務發送到 web 上執行。

280 

281了解更多:[From web to terminal](/zh-TW/claude-code-on-the-web#from-web-to-terminal)

282 

283### Tool

284 

285Claude 可以採取的動作:讀取檔案、編輯程式碼、執行 shell 命令、搜索 web、生成 subagent。Tools 是使 Claude Code 成為 agentic 的原因。沒有它們,Claude 只能用文字回應。每個工具使用都會返回一個結果,為 [agentic loop](#agentic-loop) 中 Claude 的下一個決定提供資訊。

286 

287了解更多:[Tools available to Claude](/zh-TW/tools-reference)

288 

289## W

290 

291### Worktree isolation

292 

293一個隔離模式,在 `.claude/worktrees/` 下的單獨 git worktree 中執行 Claude,使用 `-w` 標誌或 subagent 配置中的 `isolation: worktree` 啟用。更改保留在單獨分支的單獨目錄中,因此並行代理不會覆蓋彼此的檔案。

294 

295了解更多:[Run parallel sessions with git worktrees](/zh-TW/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees)

296 

297***

298 

299## 已棄用和重新命名的術語

300 

301這些術語出現在較舊的文件、部落格文章和社群內容中。搜索本網站時使用當前名稱。

302 

303| 舊術語 | 現在稱為 | 備註 |

304| --------------- | --------------------------------------------- | -------------------------- |

305| Headless mode | [Non-interactive mode](#non-interactive-mode) | 相同的 `-p` 標誌,相同的行為 |

306| Custom commands | [Skills](#skill) | `.claude/commands/` 檔案仍然有效 |

307| Slash commands | Commands | 從產品副本中刪除了「Slash」 |

google-vertex-ai.md +387 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Google Vertex AI 上的 Claude Code

6 

7> 了解如何透過 Google Vertex AI 設定 Claude Code,包括設定、IAM 設定和故障排除。

8 

9export const ContactSalesCard = ({surface}) => {

10 const utm = content => `utm_source=claude_code&utm_medium=docs&utm_content=${surface}_${content}`;

11 const iconArrowRight = (size = 13) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

12 <line x1="5" y1="12" x2="19" y2="12" />

13 <polyline points="12 5 19 12 12 19" />

14 </svg>;

15 const STYLES = `

16.cc-cs {

17 --cs-slate: #141413;

18 --cs-clay: #d97757;

19 --cs-clay-deep: #c6613f;

20 --cs-gray-000: #ffffff;

21 --cs-gray-700: #3d3d3a;

22 --cs-border-default: rgba(31, 30, 29, 0.15);

23 font-family: inherit;

24}

25.dark .cc-cs {

26 --cs-slate: #f0eee6;

27 --cs-gray-000: #262624;

28 --cs-gray-700: #bfbdb4;

29 --cs-border-default: rgba(240, 238, 230, 0.14);

30}

31.cc-cs-card {

32 display: flex; align-items: center; justify-content: space-between;

33 gap: 16px; padding: 14px 16px; margin: 0;

34 background: var(--cs-gray-000); border: 0.5px solid var(--cs-border-default);

35 border-radius: 8px; flex-wrap: wrap;

36}

37.cc-cs-text { font-size: 13px; color: var(--cs-gray-700); line-height: 1.5; flex: 1; min-width: 240px; }

38.cc-cs-text strong { font-weight: 550; color: var(--cs-slate); }

39.cc-cs-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }

40.cc-cs-btn-clay {

41 display: inline-flex; align-items: center; gap: 8px;

42 background: var(--cs-clay-deep); color: #fff; border: none;

43 border-radius: 8px; padding: 8px 14px;

44 font-size: 13px; font-weight: 500;

45 transition: background-color 0.15s; white-space: nowrap;

46}

47.cc-cs-btn-clay:hover { background: var(--cs-clay); }

48.cc-cs-btn-ghost {

49 display: inline-flex; align-items: center; gap: 8px;

50 background: transparent; color: var(--cs-gray-700);

51 border: 0.5px solid var(--cs-border-default);

52 border-radius: 8px; padding: 8px 14px;

53 font-size: 13px; font-weight: 500;

54}

55.cc-cs-btn-ghost:hover { background: rgba(0, 0, 0, 0.04); }

56.dark .cc-cs-btn-ghost:hover { background: rgba(255, 255, 255, 0.04); }

57@media (max-width: 720px) {

58 .cc-cs-actions { width: 100%; }

59}

60`;

61 return <div className="cc-cs not-prose">

62 <style>{STYLES}</style>

63 <div className="cc-cs-card">

64 <div className="cc-cs-text">

65 <strong>Deploying Claude Code across your organization?</strong> Talk to sales about enterprise plans, SSO, and centralized billing.

66 </div>

67 <div className="cc-cs-actions">

68 <a href={`https://claude.com/pricing?${utm('view_plans')}#plans-business`} className="cc-cs-btn-ghost">

69 View plans

70 </a>

71 <a href={`https://claude.com/contact-sales?${utm('contact_sales')}`} className="cc-cs-btn-clay">

72 Contact sales {iconArrowRight()}

73 </a>

74 </div>

75 </div>

76 </div>;

77};

78 

79export const Experiment = ({flag, treatment, children}) => {

80 const VID_KEY = 'exp_vid';

81 const CONSENT_COUNTRIES = new Set(['AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'RE', 'GP', 'MQ', 'GF', 'YT', 'BL', 'MF', 'PM', 'WF', 'PF', 'NC', 'AW', 'CW', 'SX', 'FO', 'GL', 'AX', 'GB', 'UK', 'AI', 'BM', 'IO', 'VG', 'KY', 'FK', 'GI', 'MS', 'PN', 'SH', 'TC', 'GG', 'JE', 'IM', 'CA', 'BR', 'IN']);

82 const fnv1a = s => {

83 let h = 0x811c9dc5;

84 for (let i = 0; i < s.length; i++) {

85 h ^= s.charCodeAt(i);

86 h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);

87 }

88 return h >>> 0;

89 };

90 const bucket = (seed, vid) => fnv1a(fnv1a(seed + vid) + '') % 10000 < 5000 ? 'control' : 'treatment';

91 const [decision] = useState(() => {

92 const params = new URLSearchParams(location.search);

93 const preBucketed = document.documentElement.dataset['gb_' + flag.replace(/-/g, '_')];

94 const force = params.get('gb-force');

95 if (force) {

96 for (const p of force.split(',')) {

97 const [k, v] = p.split(':');

98 if (k === flag) return {

99 variant: v || 'treatment',

100 track: false

101 };

102 }

103 }

104 if (navigator.globalPrivacyControl) {

105 return {

106 variant: 'control',

107 track: false

108 };

109 }

110 const prefsMatch = document.cookie.match(/(?:^|; )anthropic-consent-preferences=([^;]+)/);

111 if (prefsMatch) {

112 try {

113 if (JSON.parse(decodeURIComponent(prefsMatch[1])).analytics !== true) {

114 return {

115 variant: 'control',

116 track: false

117 };

118 }

119 } catch {

120 return {

121 variant: 'control',

122 track: false

123 };

124 }

125 } else {

126 const country = params.get('country')?.toUpperCase() || (document.cookie.match(/(?:^|; )cf_geo=([A-Z]{2})/) || [])[1];

127 if (!country || CONSENT_COUNTRIES.has(country)) {

128 return {

129 variant: 'control',

130 track: false

131 };

132 }

133 }

134 let vid;

135 try {

136 const ajsMatch = document.cookie.match(/(?:^|; )ajs_anonymous_id=([^;]+)/);

137 if (ajsMatch) {

138 vid = decodeURIComponent(ajsMatch[1]).replace(/^"|"$/g, '');

139 } else {

140 vid = localStorage.getItem(VID_KEY);

141 if (!vid) {

142 vid = crypto.randomUUID();

143 }

144 document.cookie = `ajs_anonymous_id=${vid}; domain=.claude.com; path=/; Secure; SameSite=Lax; max-age=31536000`;

145 }

146 try {

147 localStorage.setItem(VID_KEY, vid);

148 } catch {}

149 } catch {

150 return {

151 variant: 'control',

152 track: false

153 };

154 }

155 const variant = preBucketed === '1' ? 'treatment' : preBucketed === '0' ? 'control' : bucket(flag, vid);

156 return {

157 variant,

158 track: true,

159 vid

160 };

161 });

162 useEffect(() => {

163 if (!decision.track) return;

164 fetch('https://api.anthropic.com/api/event_logging/v2/batch', {

165 method: 'POST',

166 headers: {

167 'Content-Type': 'application/json',

168 'x-service-name': 'claude_code_docs'

169 },

170 body: JSON.stringify({

171 events: [{

172 event_type: 'GrowthbookExperimentEvent',

173 event_data: {

174 device_id: decision.vid,

175 anonymous_id: decision.vid,

176 timestamp: new Date().toISOString(),

177 experiment_id: flag,

178 variation_id: decision.variant === 'treatment' ? 1 : 0,

179 environment: 'production'

180 }

181 }]

182 }),

183 keepalive: true

184 }).catch(() => {});

185 }, []);

186 return decision.variant === 'treatment' ? treatment : children;

187};

188 

189<Experiment flag="docs-contact-sales-cta" treatment={<ContactSalesCard surface="vertex" />} />

190 

191## 先決條件

192 

193在使用 Vertex AI 設定 Claude Code 之前,請確保您具有:

194 

195* 已啟用計費的 Google Cloud Platform (GCP) 帳戶

196* 已啟用 Vertex AI API 的 GCP 專案

197* 存取所需的 Claude 模型(例如 Claude Sonnet 4.6)

198* 已安裝並設定 Google Cloud SDK (`gcloud`)

199* 在所需的 GCP 區域中分配的配額

200 

201若要使用您自己的 Vertex AI 認證登入,請遵循下方的[使用 Vertex AI 登入](#sign-in-with-vertex-ai)。若要在整個團隊中部署 Claude Code,請使用[手動設定](#set-up-manually)步驟並在推出前[固定您的模型版本](#5-pin-model-versions)。

202 

203## 使用 Vertex AI 登入

204 

205如果您有 Google Cloud 認證並想開始透過 Vertex AI 使用 Claude Code,登入精靈會引導您完成整個過程。您只需在每個專案中完成一次 GCP 端的先決條件;精靈會處理 Claude Code 端的設定。

206 

207<Note>

208 Vertex AI 設定精靈需要 Claude Code v2.1.98 或更新版本。執行 `claude --version` 以檢查。

209</Note>

210 

211<Steps>

212 <Step title="在您的 GCP 專案中啟用 Claude 模型">

213 為您的專案[啟用 Vertex AI API](#1-enable-vertex-ai-api),然後在 [Vertex AI Model Garden](https://console.cloud.google.com/vertex-ai/model-garden) 中要求存取您想要的 Claude 模型。請參閱 [IAM 設定](#iam-configuration)以了解您的帳戶需要的權限。

214 </Step>

215 

216 <Step title="啟動 Claude Code 並選擇 Vertex AI">

217 執行 `claude`。在登入提示處,選擇**第三方平台**,然後選擇 **Google Vertex AI**。

218 </Step>

219 

220 <Step title="遵循精靈提示">

221 選擇您如何向 Google Cloud 進行驗證:來自 `gcloud` 的應用程式預設認證、服務帳戶金鑰檔案,或已在您的環境中的認證。精靈會偵測您的專案和區域,驗證您的專案可以呼叫哪些 Claude 模型,並讓您固定它們。它會將結果儲存到您的[使用者設定檔](/zh-TW/settings)的 `env` 區塊,因此您不需要自己匯出環境變數。

222 </Step>

223</Steps>

224 

225登入後,您可以隨時執行 `/setup-vertex` 以重新開啟精靈並變更您的認證、專案、區域或模型固定。

226 

227## 區域設定

228 

229Claude Code 支援 Vertex AI [全球](https://cloud.google.com/blog/products/ai-machine-learning/global-endpoint-for-claude-models-generally-available-on-vertex-ai)、多區域和區域端點。將 `CLOUD_ML_REGION` 設定為 `global`、多區域位置(例如 `eu` 或 `us`)或特定區域(例如 `us-east5`)。Claude Code 為每種形式選擇正確的 Vertex AI 主機名稱,包括多區域位置的 `aiplatform.eu.rep.googleapis.com` 和 `aiplatform.us.rep.googleapis.com` 主機。

230 

231<Note>

232 Vertex AI 可能不支援每個端點類型上的 Claude Code 預設模型。模型可用性在[特定區域](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#genai-partner-models)、多區域位置和[全球端點](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#supported_models)之間有所不同。您可能需要切換到支援的位置或指定支援的模型。

233</Note>

234 

235## 手動設定

236 

237若要透過環境變數而不是精靈來設定 Vertex AI,例如在 CI 或指令碼化企業推出中,請遵循下列步驟。

238 

239### 1. 啟用 Vertex AI API

240 

241在您的 GCP 專案中啟用 Vertex AI API:

242 

243```bash theme={null}

244# 設定您的專案 ID

245gcloud config set project YOUR-PROJECT-ID

246 

247# 啟用 Vertex AI API

248gcloud services enable aiplatform.googleapis.com

249```

250 

251### 2. 要求模型存取

252 

253在 Vertex AI 中要求存取 Claude 模型:

254 

2551. 導覽至 [Vertex AI Model Garden](https://console.cloud.google.com/vertex-ai/model-garden)

2562. 搜尋「Claude」模型

2573. 要求存取所需的 Claude 模型(例如 Claude Sonnet 4.6)

2584. 等待核准(可能需要 24-48 小時)

259 

260### 3. 設定 GCP 認證

261 

262Claude Code 使用標準的 Google Cloud 驗證。

263 

264如需詳細資訊,請參閱 [Google Cloud 驗證文件](https://cloud.google.com/docs/authentication)。

265 

266Claude Code v2.1.121 或更新版本透過相同的 Application Default Credentials 鏈支援 [X.509 憑證型 Workload Identity Federation](https://cloud.google.com/iam/docs/workload-identity-federation-with-x509-certificates)。將 `GOOGLE_APPLICATION_CREDENTIALS` 設定為您的認證設定檔案路徑。

267 

268<Note>

269 進行驗證時,Claude Code 將自動使用 `ANTHROPIC_VERTEX_PROJECT_ID` 環境變數中的專案 ID。若要覆寫此設定,請設定下列其中一個環境變數:`GCLOUD_PROJECT`、`GOOGLE_CLOUD_PROJECT` 或 `GOOGLE_APPLICATION_CREDENTIALS`。

270</Note>

271 

272### 4. 設定 Claude Code

273 

274設定下列環境變數:

275 

276```bash theme={null}

277# 啟用 Vertex AI 整合

278export CLAUDE_CODE_USE_VERTEX=1

279export CLOUD_ML_REGION=global

280export ANTHROPIC_VERTEX_PROJECT_ID=YOUR-PROJECT-ID

281 

282# 選用:覆寫 Vertex 端點 URL 以用於自訂端點或閘道

283# export ANTHROPIC_VERTEX_BASE_URL=https://aiplatform.googleapis.com

284 

285# 選用:如需要,停用 prompt caching

286export DISABLE_PROMPT_CACHING=1

287 

288# 選用:要求 1 小時 prompt cache TTL 而不是 5 分鐘預設值

289export ENABLE_PROMPT_CACHING_1H=1

290 

291# 當 CLOUD_ML_REGION=global 時,覆寫不支援全球端點的模型的區域

292export VERTEX_REGION_CLAUDE_HAIKU_4_5=us-east5

293export VERTEX_REGION_CLAUDE_4_6_SONNET=europe-west1

294```

295 

296大多數模型版本都有對應的 `VERTEX_REGION_CLAUDE_*` 變數。如需完整清單,請參閱[環境變數參考](/zh-TW/env-vars)。檢查 [Vertex Model Garden](https://console.cloud.google.com/vertex-ai/model-garden) 以確定哪些模型支援全球端點與僅限區域端點。

297 

298[Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) 會自動啟用。若要停用它,請設定 `DISABLE_PROMPT_CACHING=1`。若要要求 1 小時 cache TTL 而不是 5 分鐘預設值,請設定 `ENABLE_PROMPT_CACHING_1H=1`;具有 1 小時 TTL 的 cache 寫入會以更高費率計費。如需提高速率限制,請聯絡 Google Cloud 支援。使用 Vertex AI 時,`/login` 和 `/logout` 命令會被停用,因為驗證是透過 Google Cloud 認證處理的。

299 

300[MCP tool search](/zh-TW/mcp#scale-with-mcp-tool-search) 在 Vertex AI 上預設為停用,因為端點不接受所需的 beta 標頭。所有 MCP 工具定義會改為預先載入。若要選擇加入,請設定 `ENABLE_TOOL_SEARCH=true`。

301 

302### 5. 固定模型版本

303 

304<Warning>

305 在部署到多個使用者時固定特定模型版本。如果不固定,模型別名(例如 `sonnet` 和 `opus`)會解析為最新版本,當 Anthropic 發佈更新時,該版本可能尚未在您的 Vertex AI 專案中啟用。Claude Code 在啟動時會在最新版本無法使用時[回退](#startup-model-checks)到先前版本,但固定可讓您控制使用者何時移至新模型。

306</Warning>

307 

308將這些環境變數設定為特定的 Vertex AI 模型 ID。

309 

310如果沒有 `ANTHROPIC_DEFAULT_OPUS_MODEL`,Vertex 上的 `opus` 別名會解析為 Opus 4.6。將其設定為 Opus 4.7 ID 以使用最新模型:

311 

312```bash theme={null}

313export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-7'

314export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-6'

315export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5@20251001'

316```

317 

318如需目前和舊版模型 ID,請參閱[模型概覽](https://platform.claude.com/docs/en/about-claude/models/overview)。如需完整的環境變數清單,請參閱[模型設定](/zh-TW/model-config#pin-models-for-third-party-deployments)。

319 

320未設定固定變數時,Claude Code 使用這些預設模型:

321 

322| 模型類型 | 預設值 |

323| :------ | :--------------------------- |

324| 主要模型 | `claude-sonnet-4-5@20250929` |

325| 小型/快速模型 | `claude-haiku-4-5@20251001` |

326 

327若要進一步自訂模型:

328 

329```bash theme={null}

330export ANTHROPIC_MODEL='claude-opus-4-7'

331export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5@20251001'

332```

333 

334## 啟動模型檢查

335 

336當 Claude Code 以設定的 Vertex AI 啟動時,它會驗證它打算使用的模型在您的專案中是否可存取。此檢查需要 Claude Code v2.1.98 或更新版本。

337 

338如果您已固定的模型版本比目前 Claude Code 預設值更舊,且您的專案可以呼叫較新版本,Claude Code 會提示您更新固定。接受會將新模型 ID 寫入您的[使用者設定檔](/zh-TW/settings)並重新啟動 Claude Code。拒絕會被記住,直到下一次預設版本變更。

339 

340如果您尚未固定模型,且目前預設值在您的專案中無法使用,Claude Code 會在目前工作階段中回退到先前版本並顯示通知。回退不會被保留。在 [Model Garden](https://console.cloud.google.com/vertex-ai/model-garden) 中啟用較新模型或[固定版本](#5-pin-model-versions)以使選擇永久化。

341 

342## IAM 設定

343 

344指派所需的 IAM 權限:

345 

346`roles/aiplatform.user` 角色包含所需的權限:

347 

348* `aiplatform.endpoints.predict` - 模型呼叫和權杖計數所需

349 

350如需更嚴格的權限,請建立只包含上述權限的自訂角色。

351 

352如需詳細資訊,請參閱 [Vertex IAM 文件](https://cloud.google.com/vertex-ai/docs/general/access-control)。

353 

354<Note>

355 為 Claude Code 建立專用的 GCP 專案,以簡化成本追蹤和存取控制。

356</Note>

357 

358## 1M token context window

359 

360Claude Opus 4.7、Opus 4.6 和 Sonnet 4.6 在 Vertex AI 上支援 [1M token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows#1m-token-context-window)。當您選擇 1M 模型變體時,Claude Code 會自動啟用擴展 context window。

361 

362[設定精靈](#sign-in-with-vertex-ai)在固定模型時提供 1M context 選項。若要為手動固定的模型啟用它,請在模型 ID 後附加 `[1m]`。如需詳細資訊,請參閱[為第三方部署固定模型](/zh-TW/model-config#pin-models-for-third-party-deployments)。

363 

364## 故障排除

365 

366如果您遇到配額問題:

367 

368* 透過 [Cloud Console](https://cloud.google.com/docs/quotas/view-manage) 檢查目前配額或要求增加配額

369 

370如果您遇到「找不到模型」404 錯誤:

371 

372* 確認模型在 [Model Garden](https://console.cloud.google.com/vertex-ai/model-garden) 中已啟用

373* 驗證模型在您指定的位置中可用。某些模型僅在 `global` 或多區域位置(例如 `eu` 和 `us`)上提供,不在特定區域中

374* 如果使用 `CLOUD_ML_REGION=global`,請檢查您的模型是否在 [Model Garden](https://console.cloud.google.com/vertex-ai/model-garden) 中的「支援的功能」下支援全球端點。對於不支援全球端點的模型,請執行下列其中一項:

375 * 透過 `ANTHROPIC_MODEL` 或 `ANTHROPIC_DEFAULT_HAIKU_MODEL` 指定支援的模型,或

376 * 使用 `VERTEX_REGION_<MODEL_NAME>` 環境變數設定區域或多區域位置

377 

378如果您遇到 429 錯誤:

379 

380* 對於區域端點,請確保主要模型和小型/快速模型在您選擇的區域中受支援

381* 考慮切換到 `CLOUD_ML_REGION=global` 以獲得更好的可用性

382 

383## 其他資源

384 

385* [Vertex AI 文件](https://cloud.google.com/vertex-ai/docs)

386* [Vertex AI 定價](https://cloud.google.com/vertex-ai/pricing)

387* [Vertex AI 配額和限制](https://cloud.google.com/vertex-ai/docs/quotas)

headless.md +225 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 以程式方式執行 Claude Code

6 

7> 使用 Agent SDK 從 CLI、Python 或 TypeScript 以程式方式執行 Claude Code。

8 

9[Agent SDK](/zh-TW/agent-sdk/overview) 提供與 Claude Code 相同的工具、agent 迴圈和上下文管理。它可作為 CLI 用於指令碼和 CI/CD,或作為 [Python](/zh-TW/agent-sdk/python) 和 [TypeScript](/zh-TW/agent-sdk/typescript) 套件供完整的程式控制。

10 

11<Note>

12 CLI 之前稱為「無頭模式」。`-p` 旗標和所有 CLI 選項的工作方式相同。

13</Note>

14 

15若要從 CLI 以程式方式執行 Claude Code,請傳遞 `-p` 和您的提示以及任何 [CLI 選項](/zh-TW/cli-reference):

16 

17```bash theme={null}

18claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"

19```

20 

21本頁涵蓋透過 CLI (`claude -p`) 使用 Agent SDK。如需具有結構化輸出、工具核准回呼和原生訊息物件的 Python 和 TypeScript SDK 套件,請參閱 [完整 Agent SDK 文件](/zh-TW/agent-sdk/overview)。

22 

23## 基本用法

24 

25將 `-p`(或 `--print`)旗標新增至任何 `claude` 命令以非互動方式執行它。所有 [CLI 選項](/zh-TW/cli-reference) 都適用於 `-p`,包括:

26 

27* `--continue` 用於 [繼續對話](#continue-conversations)

28* `--allowedTools` 用於 [自動核准工具](#auto-approve-tools)

29* `--output-format` 用於 [結構化輸出](#get-structured-output)

30 

31此範例詢問 Claude 關於您的程式碼庫的問題並列印回應:

32 

33```bash theme={null}

34claude -p "What does the auth module do?"

35```

36 

37### 使用裸機模式加快速度

38 

39新增 `--bare` 以跳過 hooks、skills、plugins、MCP 伺服器、自動記憶體和 CLAUDE.md 的自動探索來減少啟動時間。沒有它,`claude -p` 會載入互動式工作階段會載入的相同 [上下文](/zh-TW/how-claude-code-works#the-context-window),包括在工作目錄或 `~/.claude` 中設定的任何內容。

40 

41裸機模式對於 CI 和指令碼很有用,您需要在每台機器上獲得相同的結果。隊友 `~/.claude` 中的 hook 或專案的 `.mcp.json` 中的 MCP 伺服器不會執行,因為裸機模式永遠不會讀取它們。只有您明確傳遞的旗標才會生效。

42 

43此範例在裸機模式下執行一次性摘要任務,並預先核准 Read 工具,以便呼叫完成而無需許可提示:

44 

45```bash theme={null}

46claude --bare -p "Summarize this file" --allowedTools "Read"

47```

48 

49在裸機模式下,Claude 可以存取 Bash、檔案讀取和檔案編輯工具。使用旗標傳遞您需要的任何上下文:

50 

51| 要載入 | 使用 |

52| --------- | ------------------------------------------------------- |

53| 系統提示新增 | `--append-system-prompt`, `--append-system-prompt-file` |

54| 設定 | `--settings <file-or-json>` |

55| MCP 伺服器 | `--mcp-config <file-or-json>` |

56| 自訂 agents | `--agents <json>` |

57| 外掛程式目錄 | `--plugin-dir <path>` |

58 

59裸機模式跳過 OAuth 和鑰匙圈讀取。Anthropic 驗證必須來自 `ANTHROPIC_API_KEY` 或傳遞給 `--settings` 的 JSON 中的 `apiKeyHelper`。Bedrock、Vertex 和 Foundry 使用其通常的提供者認證。

60 

61<Note>

62 `--bare` 是指令碼和 SDK 呼叫的建議模式,將在未來版本中成為 `-p` 的預設值。

63</Note>

64 

65## 範例

66 

67這些範例突出顯示常見的 CLI 模式。對於 CI 和其他指令碼呼叫,新增 [`--bare`](#start-faster-with-bare-mode) 以便它們不會選擇本地設定的任何內容。

68 

69### 取得結構化輸出

70 

71使用 `--output-format` 控制回應的傳回方式:

72 

73* `text`(預設):純文字輸出

74* `json`:包含結果、工作階段 ID 和中繼資料的結構化 JSON

75* `stream-json`:用於即時串流的換行分隔 JSON

76 

77此範例以 JSON 格式傳回專案摘要及工作階段中繼資料,文字結果在 `result` 欄位中:

78 

79```bash theme={null}

80claude -p "Summarize this project" --output-format json

81```

82 

83若要取得符合特定結構描述的輸出,請使用 `--output-format json` 搭配 `--json-schema` 和 [JSON Schema](https://json-schema.org/) 定義。回應包含關於請求的中繼資料(工作階段 ID、使用情況等),結構化輸出在 `structured_output` 欄位中。

84 

85此範例從 auth.py 提取函式名稱並將其作為字串陣列傳回:

86 

87```bash theme={null}

88claude -p "Extract the main function names from auth.py" \

89 --output-format json \

90 --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'

91```

92 

93<Tip>

94 使用 [jq](https://jqlang.github.io/jq/) 之類的工具來解析回應並提取特定欄位:

95 

96 ```bash theme={null}

97 # Extract the text result

98 claude -p "Summarize this project" --output-format json | jq -r '.result'

99 

100 # Extract structured output

101 claude -p "Extract function names from auth.py" \

102 --output-format json \

103 --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \

104 | jq '.structured_output'

105 ```

106</Tip>

107 

108### 串流回應

109 

110使用 `--output-format stream-json` 搭配 `--verbose` 和 `--include-partial-messages` 以在產生令牌時接收它們。每一行都是代表事件的 JSON 物件:

111 

112```bash theme={null}

113claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages

114```

115 

116下列範例使用 [jq](https://jqlang.github.io/jq/) 篩選文字差異並僅顯示串流文字。`-r` 旗標輸出原始字串(無引號),`-j` 不帶換行符號的聯結,因此令牌會連續串流:

117 

118```bash theme={null}

119claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \

120 jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'

121```

122 

123當 API 請求因可重試錯誤而失敗時,Claude Code 會在重試前發出 `system/api_retry` 事件。您可以使用此來顯示重試進度或實施自訂退避邏輯。

124 

125| 欄位 | 類型 | 描述 |

126| ---------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |

127| `type` | `"system"` | 訊息類型 |

128| `subtype` | `"api_retry"` | 將此識別為重試事件 |

129| `attempt` | 整數 | 目前嘗試次數,從 1 開始 |

130| `max_retries` | 整數 | 允許的總重試次數 |

131| `retry_delay_ms` | 整數 | 毫秒直到下一次嘗試 |

132| `error_status` | 整數或 null | HTTP 狀態碼,或 `null` 表示沒有 HTTP 回應的連線錯誤 |

133| `error` | 字串 | 錯誤類別:`authentication_failed`、`oauth_org_not_allowed`、`billing_error`、`rate_limit`、`invalid_request`、`server_error`、`max_output_tokens` 或 `unknown` |

134| `uuid` | 字串 | 唯一事件識別碼 |

135| `session_id` | 字串 | 事件所屬的工作階段 |

136 

137`system/init` 事件報告工作階段中繼資料,包括模型、工具、MCP 伺服器和載入的外掛程式。除非設定了 [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](/zh-TW/env-vars),否則它是串流中的第一個事件,在這種情況下 `plugin_install` 事件在其之前。使用外掛程式欄位在外掛程式未載入時使 CI 失敗:

138 

139| 欄位 | 類型 | 描述 |

140| --------------- | -- | ------------------------------------------------------------------------------------------------ |

141| `plugins` | 陣列 | 成功載入的外掛程式,每個都有 `name` 和 `path` |

142| `plugin_errors` | 陣列 | 外掛程式載入時間錯誤,例如不滿足的相依性版本,每個都有 `plugin`、`type` 和 `message`。受影響的外掛程式被降級並從 `plugins` 中缺失。當沒有錯誤時,金鑰被省略 |

143 

144當設定了 [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](/zh-TW/env-vars) 時,Claude Code 在第一次轉換前發出 `system/plugin_install` 事件,同時市場外掛程式安裝。使用這些在您自己的 UI 中顯示安裝進度。

145 

146| 欄位 | 類型 | 描述 |

147| ------------ | ---------------------------------------------------- | ------------------------------------------------------------ |

148| `type` | `"system"` | 訊息類型 |

149| `subtype` | `"plugin_install"` | 將此識別為外掛程式安裝事件 |

150| `status` | `"started"`、`"installed"`、`"failed"` 或 `"completed"` | `started` 和 `completed` 括住整體安裝;`installed` 和 `failed` 報告個別市場 |

151| `name` | 字串,選用 | 市場名稱,在 `installed` 和 `failed` 上出現 |

152| `error` | 字串,選用 | 失敗訊息,在 `failed` 上出現 |

153| `uuid` | 字串 | 唯一事件識別碼 |

154| `session_id` | 字串 | 事件所屬的工作階段 |

155 

156如需具有回呼和訊息物件的程式化串流,請參閱 Agent SDK 文件中的 [即時串流回應](/zh-TW/agent-sdk/streaming-output)。

157 

158### 自動核准工具

159 

160使用 `--allowedTools` 讓 Claude 使用某些工具而無需提示。此範例執行測試套件並修復失敗,允許 Claude 執行 Bash 命令和讀取/編輯檔案而無需請求許可:

161 

162```bash theme={null}

163claude -p "Run the test suite and fix any failures" \

164 --allowedTools "Bash,Read,Edit"

165```

166 

167若要為整個工作階段設定基準而不是列出個別工具,請傳遞 [權限模式](/zh-TW/permission-modes)。`dontAsk` 拒絕 `permissions.allow` 規則或 [唯讀命令集](/zh-TW/permissions#read-only-commands) 中未包含的任何內容,這對於鎖定的 CI 執行很有用。`acceptEdits` 讓 Claude 寫入檔案而無需提示,也自動核准常見的檔案系統命令,例如 `mkdir`、`touch`、`mv` 和 `cp`。其他 shell 命令和網路請求仍然需要 `--allowedTools` 項目或 `permissions.allow` 規則,否則當嘗試執行時執行會中止:

168 

169```bash theme={null}

170claude -p "Apply the lint fixes" --permission-mode acceptEdits

171```

172 

173### 建立提交

174 

175此範例檢查暫存的變更並建立具有適當訊息的提交:

176 

177```bash theme={null}

178claude -p "Look at my staged changes and create an appropriate commit" \

179 --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"

180```

181 

182`--allowedTools` 旗標使用 [權限規則語法](/zh-TW/settings#permission-rule-syntax)。尾部的 ` *` 啟用前綴匹配,因此 `Bash(git diff *)` 允許任何以 `git diff` 開頭的命令。空格在 `*` 之前很重要:沒有它,`Bash(git diff*)` 也會符合 `git diff-index`。

183 

184<Note>

185 使用者叫用的 [skills](/zh-TW/skills) 如 `/commit` 和 [內建命令](/zh-TW/commands) 僅在互動模式中可用。在 `-p` 模式中,改為描述您想要完成的任務。

186</Note>

187 

188### 自訂系統提示

189 

190使用 `--append-system-prompt` 新增指示同時保持 Claude Code 的預設行為。此範例將 PR 差異管道傳送至 Claude 並指示它檢查安全漏洞:

191 

192```bash theme={null}

193gh pr diff "$1" | claude -p \

194 --append-system-prompt "You are a security engineer. Review for vulnerabilities." \

195 --output-format json

196```

197 

198請參閱 [系統提示旗標](/zh-TW/cli-reference#system-prompt-flags) 以取得更多選項,包括 `--system-prompt` 以完全取代預設提示。

199 

200### 繼續對話

201 

202使用 `--continue` 繼續最近的對話,或使用 `--resume` 搭配工作階段 ID 以繼續特定對話。此範例執行檢查,然後傳送後續提示:

203 

204```bash theme={null}

205# First request

206claude -p "Review this codebase for performance issues"

207 

208# Continue the most recent conversation

209claude -p "Now focus on the database queries" --continue

210claude -p "Generate a summary of all issues found" --continue

211```

212 

213如果您執行多個對話,請擷取工作階段 ID 以繼續特定對話:

214 

215```bash theme={null}

216session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')

217claude -p "Continue that review" --resume "$session_id"

218```

219 

220## 後續步驟

221 

222* [Agent SDK 快速入門](/zh-TW/agent-sdk/quickstart):使用 Python 或 TypeScript 建立您的第一個 agent

223* [CLI 參考](/zh-TW/cli-reference):所有 CLI 旗標和選項

224* [GitHub Actions](/zh-TW/github-actions):在 GitHub 工作流程中使用 Agent SDK

225* [GitLab CI/CD](/zh-TW/gitlab-ci-cd):在 GitLab 管道中使用 Agent SDK

hooks.md +2658 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Hooks 參考

6 

7> Claude Code hook 事件、配置架構、JSON 輸入/輸出格式、退出代碼、非同步 hooks、HTTP hooks、提示 hooks 和 MCP 工具 hooks 的參考。

8 

9<Tip>

10 如需快速入門指南和範例,請參閱 [使用 hooks 自動化工作流程](/zh-TW/hooks-guide)。

11</Tip>

12 

13Hooks 是使用者定義的 shell 命令、HTTP 端點或 LLM 提示,在 Claude Code 生命週期的特定時間點自動執行。使用此參考來查詢事件架構、配置選項、JSON 輸入/輸出格式,以及非同步 hooks、HTTP hooks 和 MCP 工具 hooks 等進階功能。如果您是第一次設定 hooks,請改為從 [指南](/zh-TW/hooks-guide) 開始。

14 

15## Hook 生命週期

16 

17Hooks 在 Claude Code 工作階段期間的特定時間點觸發。當事件觸發且匹配器匹配時,Claude Code 會將有關該事件的 JSON 上下文傳遞給您的 hook 處理程式。對於命令 hooks,輸入會到達 stdin。對於 HTTP hooks,它會作為 POST 請求正文到達。您的處理程式可以檢查輸入、採取行動,並可選擇性地返回決定。事件分為三種節奏:每個工作階段一次(`SessionStart`、`SessionEnd`)、每個轉向一次(`UserPromptSubmit`、`Stop`、`StopFailure`),以及代理迴圈內每個工具呼叫(`PreToolUse`、`PostToolUse`):

18 

19<div style={{maxWidth: "500px", margin: "0 auto"}}>

20 <Frame>

21 <img src="https://mintcdn.com/claude-code/ZIW26Z9pnpsXLhbS/images/hooks-lifecycle.svg?fit=max&auto=format&n=ZIW26Z9pnpsXLhbS&q=85&s=ee23691324deb6501df09bfdae560b64" alt="Hook 生命週期圖表,顯示可選的 Setup 進入 SessionStart,然後是每個轉向的迴圈,包含 UserPromptSubmit、用於 slash commands 的 UserPromptExpansion、嵌套的代理迴圈(PreToolUse、PermissionRequest、PostToolUse、PostToolUseFailure、PostToolBatch、SubagentStart/Stop、TaskCreated、TaskCompleted)和 Stop 或 StopFailure,接著是 TeammateIdle、PreCompact、PostCompact 和 SessionEnd,Elicitation 和 ElicitationResult 嵌套在 MCP 工具執行內,PermissionDenied 作為 PermissionRequest 的側分支用於自動模式拒絕,WorktreeCreate、WorktreeRemove、Notification、ConfigChange、InstructionsLoaded、CwdChanged 和 FileChanged 作為獨立非同步事件" width="520" height="1228" data-path="images/hooks-lifecycle.svg" />

22 </Frame>

23</div>

24 

25下表總結了每個事件何時觸發。[Hook 事件](#hook-events) 部分記錄了每個事件的完整輸入架構和決定控制選項。

26 

27| Event | When it fires |

28| :-------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |

29| `SessionStart` | When a session begins or resumes |

30| `Setup` | When you start Claude Code with `--init-only`, or with `--init` or `--maintenance` in `-p` mode. For one-time preparation in CI or scripts |

31| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |

32| `UserPromptExpansion` | When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion |

33| `PreToolUse` | Before a tool call executes. Can block it |

34| `PermissionRequest` | When a permission dialog appears |

35| `PermissionDenied` | When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call |

36| `PostToolUse` | After a tool call succeeds |

37| `PostToolUseFailure` | After a tool call fails |

38| `PostToolBatch` | After a full batch of parallel tool calls resolves, before the next model call |

39| `Notification` | When Claude Code sends a notification |

40| `SubagentStart` | When a subagent is spawned |

41| `SubagentStop` | When a subagent finishes |

42| `TaskCreated` | When a task is being created via `TaskCreate` |

43| `TaskCompleted` | When a task is being marked as completed |

44| `Stop` | When Claude finishes responding |

45| `StopFailure` | When the turn ends due to an API error. Output and exit code are ignored |

46| `TeammateIdle` | When an [agent team](/en/agent-teams) teammate is about to go idle |

47| `InstructionsLoaded` | When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session |

48| `ConfigChange` | When a configuration file changes during a session |

49| `CwdChanged` | When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv |

50| `FileChanged` | When a watched file changes on disk. The `matcher` field specifies which filenames to watch |

51| `WorktreeCreate` | When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior |

52| `WorktreeRemove` | When a worktree is being removed, either at session exit or when a subagent finishes |

53| `PreCompact` | Before context compaction |

54| `PostCompact` | After context compaction completes |

55| `Elicitation` | When an MCP server requests user input during a tool call |

56| `ElicitationResult` | After a user responds to an MCP elicitation, before the response is sent back to the server |

57| `SessionEnd` | When a session terminates |

58 

59### Hook 如何解析

60 

61為了了解這些部分如何組合在一起,請考慮此 `PreToolUse` hook,它會阻止破壞性 shell 命令。`matcher` 縮小到 Bash 工具呼叫,`if` 條件進一步縮小到符合 `rm *` 的 Bash 子命令,因此 `block-rm.sh` 僅在兩個篩選器都匹配時才生成:

62 

63```json theme={null}

64{

65 "hooks": {

66 "PreToolUse": [

67 {

68 "matcher": "Bash",

69 "hooks": [

70 {

71 "type": "command",

72 "if": "Bash(rm *)",

73 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-rm.sh"

74 }

75 ]

76 }

77 ]

78 }

79}

80```

81 

82該指令碼從 stdin 讀取 JSON 輸入,提取命令,如果包含 `rm -rf`,則返回 `permissionDecision` 為 `"deny"`:

83 

84```bash theme={null}

85#!/bin/bash

86# .claude/hooks/block-rm.sh

87COMMAND=$(jq -r '.tool_input.command')

88 

89if echo "$COMMAND" | grep -q 'rm -rf'; then

90 jq -n '{

91 hookSpecificOutput: {

92 hookEventName: "PreToolUse",

93 permissionDecision: "deny",

94 permissionDecisionReason: "Destructive command blocked by hook"

95 }

96 }'

97else

98 exit 0 # allow the command

99fi

100```

101 

102現在假設 Claude Code 決定執行 `Bash "rm -rf /tmp/build"`。以下是發生的情況:

103 

104<Frame>

105 <img src="https://mintcdn.com/claude-code/-tYw1BD_DEqfyyOZ/images/hook-resolution.svg?fit=max&auto=format&n=-tYw1BD_DEqfyyOZ&q=85&s=c73ebc1eeda2037570427d7af1e0a891" alt="Hook 解析流程:PreToolUse 事件觸發,匹配器檢查 Bash 匹配,if 條件檢查 Bash(rm *) 匹配,hook 處理程式執行,結果返回到 Claude Code" width="930" height="290" data-path="images/hook-resolution.svg" />

106</Frame>

107 

108<Steps>

109 <Step title="事件觸發">

110 `PreToolUse` 事件觸發。Claude Code 將工具輸入作為 JSON 在 stdin 上發送到 hook:

111 

112 ```json theme={null}

113 { "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" }, ... }

114 ```

115 </Step>

116 

117 <Step title="匹配器檢查">

118 匹配器 `"Bash"` 與工具名稱匹配,因此此 hook 群組啟動。如果您省略匹配器或使用 `"*"`,群組在事件的每次出現時啟動。

119 </Step>

120 

121 <Step title="If 條件檢查">

122 `if` 條件 `"Bash(rm *)"` 匹配,因為 `rm -rf /tmp/build` 是符合 `rm *` 的子命令,因此此處理程式生成。如果命令是 `npm test`,`if` 檢查會失敗,`block-rm.sh` 永遠不會執行,避免程序生成開銷。`if` 欄位是可選的;沒有它,匹配群組中的每個處理程式都執行。

123 </Step>

124 

125 <Step title="Hook 處理程式執行">

126 該指令碼檢查完整命令並找到 `rm -rf`,因此它將決定列印到 stdout:

127 

128 ```json theme={null}

129 {

130 "hookSpecificOutput": {

131 "hookEventName": "PreToolUse",

132 "permissionDecision": "deny",

133 "permissionDecisionReason": "Destructive command blocked by hook"

134 }

135 }

136 ```

137 

138 如果命令是更安全的 `rm` 變體,如 `rm file.txt`,指令碼會改為執行 `exit 0`,這告訴 Claude Code 允許工具呼叫而無需進一步操作。

139 </Step>

140 

141 <Step title="Claude Code 根據結果採取行動">

142 Claude Code 讀取 JSON 決定,阻止工具呼叫,並向 Claude 顯示原因。

143 </Step>

144</Steps>

145 

146下面的 [配置](#configuration) 部分記錄了完整架構,每個 [hook 事件](#hook-events) 部分記錄了您的命令接收的輸入以及它可以返回的輸出。

147 

148## 配置

149 

150Hooks 在 JSON 設定檔中定義。配置有三個嵌套層級:

151 

1521. 選擇要回應的 [hook 事件](#hook-events),例如 `PreToolUse` 或 `Stop`

1532. 新增 [匹配器群組](#matcher-patterns) 以篩選何時觸發,例如'僅針對 Bash 工具'

1543. 定義一個或多個 [hook 處理程式](#hook-handler-fields) 以在匹配時執行

155 

156有關完整的逐步說明和註解範例,請參閱上面的 [Hook 如何解析](#how-a-hook-resolves)。

157 

158<Note>

159 此頁面為每個層級使用特定術語:**hook 事件**表示生命週期點,**匹配器群組**表示篩選器,**hook 處理程式**表示執行的 shell 命令、HTTP 端點、MCP 工具、提示或代理。'Hook'本身指的是一般功能。

160</Note>

161 

162### Hook 位置

163 

164您定義 hook 的位置決定了其範圍:

165 

166| 位置 | 範圍 | 可共享 |

167| :-------------------------------------------------------------- | :-------- | :----------- |

168| `~/.claude/settings.json` | 您的所有專案 | 否,本機限定 |

169| `.claude/settings.json` | 單一專案 | 是,可提交到儲存庫 |

170| `.claude/settings.local.json` | 單一專案 | 否,gitignored |

171| 受管理的原則設定 | 組織範圍 | 是,由管理員控制 |

172| [Plugin](/zh-TW/plugins) `hooks/hooks.json` | 啟用外掛程式時 | 是,與外掛程式一起打包 |

173| [Skill](/zh-TW/skills) 或 [agent](/zh-TW/sub-agents) frontmatter | 元件處於活動狀態時 | 是,在元件檔案中定義 |

174 

175有關設定檔解析的詳細資訊,請參閱 [settings](/zh-TW/settings)。企業管理員可以使用 `allowManagedHooksOnly` 來阻止使用者、專案和外掛程式 hooks。在受管理的設定 `enabledPlugins` 中強制啟用的外掛程式的 Hooks 是例外,因此管理員可以通過組織市場分發經過驗證的 hooks。請參閱 [Hook 配置](/zh-TW/settings#hook-configuration)。

176 

177### 匹配器模式

178 

179`matcher` 欄位篩選 hooks 何時觸發。匹配器的評估方式取決於它包含的字元:

180 

181| 匹配器值 | 評估為 | 範例 |

182| :---------------- | :------------------- | :------------------------------------------------------------------------ |

183| `"*"`、`""` 或省略 | 匹配所有 | 在事件的每次出現時觸發 |

184| 僅字母、數字、`_` 和 `\|` | 精確字串或 `\|` 分隔的精確字串清單 | `Bash` 僅匹配 Bash 工具;`Edit\|Write` 精確匹配任一工具 |

185| 包含任何其他字元 | JavaScript 正規表達式 | `^Notebook` 匹配任何以 Notebook 開頭的工具;`mcp__memory__.*` 匹配來自 `memory` 伺服器的每個工具 |

186 

187`FileChanged` 事件在建立其監視清單時不遵循這些規則。請參閱 [FileChanged](#filechanged)。

188 

189每個事件類型在不同的欄位上匹配:

190 

191| 事件 | 匹配器篩選的內容 | 範例匹配器值 |

192| :----------------------------------------------------------------------------------------------------------------------- | :---------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ |

193| `PreToolUse`、`PostToolUse`、`PostToolUseFailure`、`PermissionRequest`、`PermissionDenied` | 工具名稱 | `Bash`、`Edit\|Write`、`mcp__.*` |

194| `SessionStart` | 工作階段如何開始 | `startup`、`resume`、`clear`、`compact` |

195| `Setup` | 哪個 CLI 旗標觸發設定 | `init`、`maintenance` |

196| `SessionEnd` | 工作階段為何結束 | `clear`、`resume`、`logout`、`prompt_input_exit`、`bypass_permissions_disabled`、`other` |

197| `Notification` | 通知類型 | `permission_prompt`、`idle_prompt`、`auth_success`、`elicitation_dialog`、`elicitation_complete`、`elicitation_response` |

198| `SubagentStart` | 代理類型 | `general-purpose`、`Explore`、`Plan` 或自訂代理名稱 |

199| `PreCompact`、`PostCompact` | 觸發壓縮的原因 | `manual`、`auto` |

200| `SubagentStop` | 代理類型 | 與 `SubagentStart` 相同的值 |

201| `ConfigChange` | 配置來源 | `user_settings`、`project_settings`、`local_settings`、`policy_settings`、`skills` |

202| `CwdChanged` | 不支援匹配器 | 總是在每次目錄變更時觸發 |

203| `FileChanged` | 要監視的檔案名稱(請參閱 [FileChanged](#filechanged)) | `.envrc\|.env` |

204| `StopFailure` | 錯誤類型 | `rate_limit`、`authentication_failed`、`oauth_org_not_allowed`、`billing_error`、`invalid_request`、`server_error`、`max_output_tokens`、`unknown` |

205| `InstructionsLoaded` | 載入原因 | `session_start`、`nested_traversal`、`path_glob_match`、`include`、`compact` |

206| `UserPromptExpansion` | 命令名稱 | 您的 skill 或命令名稱 |

207| `Elicitation` | MCP 伺服器名稱 | 您配置的 MCP 伺服器名稱 |

208| `ElicitationResult` | MCP 伺服器名稱 | 與 `Elicitation` 相同的值 |

209| `UserPromptSubmit`、`PostToolBatch`、`Stop`、`TeammateIdle`、`TaskCreated`、`TaskCompleted`、`WorktreeCreate`、`WorktreeRemove` | 不支援匹配器 | 總是在每次出現時觸發 |

210 

211匹配器針對 Claude Code 在 stdin 上發送給您的 hook 的 [JSON 輸入](#hook-input-and-output) 中的欄位執行。對於工具事件,該欄位是 `tool_name`。每個 [hook 事件](#hook-events) 部分列出了該事件的完整匹配器值集和輸入架構。

212 

213此範例僅在 Claude 寫入或編輯檔案時執行 linting 指令碼:

214 

215```json theme={null}

216{

217 "hooks": {

218 "PostToolUse": [

219 {

220 "matcher": "Edit|Write",

221 "hooks": [

222 {

223 "type": "command",

224 "command": "/path/to/lint-check.sh"

225 }

226 ]

227 }

228 ]

229 }

230}

231```

232 

233`UserPromptSubmit`、`PostToolBatch`、`Stop`、`TeammateIdle`、`TaskCreated`、`TaskCompleted`、`WorktreeCreate`、`WorktreeRemove` 和 `CwdChanged` 不支援匹配器,總是在每次出現時觸發。如果您將 `matcher` 欄位新增到這些事件,它會被無聲地忽略。

234 

235對於工具事件,您可以通過在個別 hook 處理程式上設定 [`if` 欄位](#common-fields) 來更狹隘地篩選。`if` 使用 [權限規則語法](/zh-TW/permissions) 來匹配工具名稱和參數,因此 `"Bash(git *)"` 僅在任何 Bash 輸入的子命令匹配 `git *` 時執行,`"Edit(*.ts)"` 僅針對 TypeScript 檔案執行。

236 

237#### 匹配 MCP 工具

238 

239[MCP](/zh-TW/mcp) 伺服器工具在工具事件中顯示為常規工具(`PreToolUse`、`PostToolUse`、`PostToolUseFailure`、`PermissionRequest`、`PermissionDenied`),因此您可以像匹配任何其他工具名稱一樣匹配它們。

240 

241MCP 工具遵循命名模式 `mcp__<server>__<tool>`,例如:

242 

243* `mcp__memory__create_entities`:Memory 伺服器的建立實體工具

244* `mcp__filesystem__read_file`:Filesystem 伺服器的讀取檔案工具

245* `mcp__github__search_repositories`:GitHub 伺服器的搜尋工具

246 

247要匹配來自伺服器的每個工具,請在伺服器前綴後附加 `.*`。`.*` 是必需的:像 `mcp__memory` 這樣的匹配器僅包含字母和底線,因此它被比較為精確字串,不匹配任何工具。

248 

249* `mcp__memory__.*` 匹配來自 `memory` 伺服器的所有工具

250* `mcp__.*__write.*` 匹配來自任何伺服器的任何名稱以 `write` 開頭的工具

251 

252此範例記錄所有 memory 伺服器操作並驗證來自任何 MCP 伺服器的寫入操作:

253 

254```json theme={null}

255{

256 "hooks": {

257 "PreToolUse": [

258 {

259 "matcher": "mcp__memory__.*",

260 "hooks": [

261 {

262 "type": "command",

263 "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"

264 }

265 ]

266 },

267 {

268 "matcher": "mcp__.*__write.*",

269 "hooks": [

270 {

271 "type": "command",

272 "command": "/home/user/scripts/validate-mcp-write.py"

273 }

274 ]

275 }

276 ]

277 }

278}

279```

280 

281### Hook 處理程式欄位

282 

283內部 `hooks` 陣列中的每個物件都是一個 hook 處理程式:當匹配器匹配時執行的 shell 命令、HTTP 端點、MCP 工具、LLM 提示或代理。有五種類型:

284 

285* **[命令 hooks](#command-hook-fields)**(`type: "command"`):執行 shell 命令。您的指令碼在 stdin 上接收事件的 [JSON 輸入](#hook-input-and-output),並通過退出代碼和 stdout 傳回結果。

286* **[HTTP hooks](#http-hook-fields)**(`type: "http"`):將事件的 JSON 輸入作為 HTTP POST 請求發送到 URL。端點通過使用與命令 hooks 相同的 [JSON 輸出格式](#json-output) 的回應正文傳回結果。

287* **[MCP 工具 hooks](#mcp-tool-hook-fields)**(`type: "mcp_tool"`):在已連接的 [MCP 伺服器](/zh-TW/mcp) 上呼叫工具。工具的文字輸出被視為類似命令 hook stdout。

288* **[提示 hooks](#prompt-and-agent-hook-fields)**(`type: "prompt"`):將提示發送到 Claude 模型進行單輪評估。模型以 JSON 形式返回是/否決定。請參閱 [基於提示的 hooks](#prompt-based-hooks)。

289* **[代理 hooks](#prompt-and-agent-hook-fields)**(`type: "agent"`):生成一個可以使用 Read、Grep 和 Glob 等工具來驗證條件的 subagent,然後返回決定。代理 hooks 是實驗性的,可能會變更。請參閱 [基於代理的 hooks](#agent-based-hooks)。

290 

291#### 通用欄位

292 

293這些欄位適用於所有 hook 類型:

294 

295| 欄位 | 必需 | 描述 |

296| :-------------- | :- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

297| `type` | 是 | `"command"`、`"http"`、`"mcp_tool"`、`"prompt"` 或 `"agent"` |

298| `if` | 否 | 權限規則語法以篩選此 hook 何時執行,例如 `"Bash(git *)"` 或 `"Edit(*.ts)"`。Hook 僅在工具呼叫匹配模式時生成,或當 Bash 命令太複雜而無法解析時。僅在工具事件上評估:`PreToolUse`、`PostToolUse`、`PostToolUseFailure`、`PermissionRequest` 和 `PermissionDenied`。在其他事件上,設定 `if` 的 hook 永遠不會執行。使用與 [權限規則](/zh-TW/permissions) 相同的語法 |

299| `timeout` | 否 | 取消前的秒數。預設值:命令 600、提示 30、代理 60 |

300| `statusMessage` | 否 | hook 執行時顯示的自訂微調訊息 |

301| `once` | 否 | 如果為 `true`,每個工作階段只執行一次,然後被移除。僅在 [skill frontmatter](#hooks-in-skills-and-agents) 中受尊重;在設定檔和代理 frontmatter 中被忽略 |

302 

303`if` 欄位恰好包含一個權限規則。沒有 `&&`、`||` 或清單語法來組合規則;要應用多個條件,請為每個條件定義一個單獨的 hook 處理程式。對於 Bash,規則會針對工具輸入的每個子命令進行匹配,在去除前導 `VAR=value` 指派後,因此 `if: "Bash(git push *)"` 同時匹配 `FOO=bar git push` 和 `npm test && git push`。如果任何子命令匹配,hook 會執行,並且當命令太複雜而無法解析時總是執行。

304 

305#### 命令 hook 欄位

306 

307除了 [通用欄位](#common-fields) 外,命令 hooks 還接受這些欄位:

308 

309| 欄位 | 必需 | 描述 |

310| :------------ | :- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------- |

311| `command` | 是 | 要執行的 shell 命令 |

312| `async` | 否 | 如果為 `true`,在背景執行而不阻止。請參閱 [在背景執行 hooks](#run-hooks-in-the-background) |

313| `asyncRewake` | 否 | 如果為 `true`,在背景執行並在退出代碼 2 時喚醒 Claude。暗示 `async`。Hook 的 stderr,或如果 stderr 為空則為 stdout,作為系統提醒顯示給 Claude,以便它可以對長時間執行的背景失敗做出反應 |

314| `shell` | 否 | 用於此 hook 的 shell。接受 `"bash"`(預設)或 `"powershell"`。設定 `"powershell"` 在 Windows 上通過 PowerShell 執行命令。不需要 `CLAUDE_CODE_USE_POWERSHELL_TOOL`,因為 hooks 直接生成 PowerShell |

315 

316#### HTTP hook 欄位

317 

318除了 [通用欄位](#common-fields) 外,HTTP hooks 還接受這些欄位:

319 

320| 欄位 | 必需 | 描述 |

321| :--------------- | :- | :------------------------------------------------------------------------------------------ |

322| `url` | 是 | 要發送 POST 請求的 URL |

323| `headers` | 否 | 其他 HTTP 標頭作為鍵值對。值支援使用 `$VAR_NAME` 或 `${VAR_NAME}` 語法的環境變數插值。只有列在 `allowedEnvVars` 中的變數才會被解析 |

324| `allowedEnvVars` | 否 | 可能被插值到標頭值中的環境變數名稱清單。對未列出的變數的參考會被替換為空字串。任何環境變數插值都需要此項 |

325 

326Claude Code 將 hook 的 [JSON 輸入](#hook-input-and-output) 作為 POST 請求正文發送,`Content-Type: application/json`。回應正文使用與命令 hooks 相同的 [JSON 輸出格式](#json-output)。

327 

328錯誤處理與命令 hooks 不同:非 2xx 回應、連線失敗和逾時都會產生非阻止性錯誤,允許執行繼續。要阻止工具呼叫或拒絕權限,請返回 2xx 回應,其 JSON 正文包含 `decision: "block"` 或 `hookSpecificOutput` 與 `permissionDecision: "deny"`。

329 

330此範例將 `PreToolUse` 事件發送到本機驗證服務,使用來自 `MY_TOKEN` 環境變數的令牌進行驗證:

331 

332```json theme={null}

333{

334 "hooks": {

335 "PreToolUse": [

336 {

337 "matcher": "Bash",

338 "hooks": [

339 {

340 "type": "http",

341 "url": "http://localhost:8080/hooks/pre-tool-use",

342 "timeout": 30,

343 "headers": {

344 "Authorization": "Bearer $MY_TOKEN"

345 },

346 "allowedEnvVars": ["MY_TOKEN"]

347 }

348 ]

349 }

350 ]

351 }

352}

353```

354 

355#### MCP 工具 hook 欄位

356 

357除了 [通用欄位](#common-fields) 外,MCP 工具 hooks 還接受這些欄位:

358 

359| 欄位 | 必需 | 描述 |

360| :------- | :- | :------------------------------------------------------------------------------------------------------ |

361| `server` | 是 | 已配置的 MCP 伺服器的名稱。伺服器必須已連接;hook 永遠不會觸發 OAuth 或連接流程 |

362| `tool` | 是 | 該伺服器上要呼叫的工具名稱 |

363| `input` | 否 | 傳遞給工具的參數。字串值支援來自 hook 的 [JSON 輸入](#hook-input-and-output) 的 `${path}` 替換,例如 `"${tool_input.file_path}"` |

364 

365工具的文字內容被視為類似命令 hook stdout:如果它解析為有效的 [JSON 輸出](#json-output),它會被處理為決定,否則它會顯示為純文字。如果命名的伺服器未連接,或工具返回 `isError: true`,hook 會產生非阻止性錯誤,執行繼續。

366 

367MCP 工具 hooks 在 Claude Code 連接到您的 MCP 伺服器後在每個 hook 事件上都可用。`SessionStart` 和 `Setup` 通常在伺服器完成連接之前觸發,因此這些事件上的 hooks 應該預期首次執行時出現「未連接」錯誤。

368 

369此範例在每個 `Write` 或 `Edit` 後在 `my_server` MCP 伺服器上呼叫 `security_scan` 工具,傳遞編輯檔案的路徑:

370 

371```json theme={null}

372{

373 "hooks": {

374 "PostToolUse": [

375 {

376 "matcher": "Write|Edit",

377 "hooks": [

378 {

379 "type": "mcp_tool",

380 "server": "my_server",

381 "tool": "security_scan",

382 "input": { "file_path": "${tool_input.file_path}" }

383 }

384 ]

385 }

386 ]

387 }

388}

389```

390 

391#### 提示和代理 hook 欄位

392 

393除了 [通用欄位](#common-fields) 外,提示和代理 hooks 還接受這些欄位:

394 

395| 欄位 | 必需 | 描述 |

396| :------- | :- | :----------------------------------------------- |

397| `prompt` | 是 | 要發送到模型的提示文字。使用 `$ARGUMENTS` 作為 hook 輸入 JSON 的佔位符 |

398| `model` | 否 | 用於評估的模型。預設為快速模型 |

399 

400所有匹配的 hooks 並行執行,相同的處理程式會自動去重。命令 hooks 按命令字串去重,HTTP hooks 按 URL 去重。處理程式在目前目錄中執行,使用 Claude Code 的環境。在遠端網路環境中,`$CLAUDE_CODE_REMOTE` 環境變數設定為 `"true"`,在本機 CLI 中未設定。

401 

402### 按路徑參考指令碼

403 

404使用環境變數按相對於專案或外掛程式根目錄的路徑參考 hook 指令碼,無論 hook 執行時的工作目錄如何:

405 

406* `$CLAUDE_PROJECT_DIR`:專案根目錄。用引號括起來以處理包含空格的路徑。

407* `${CLAUDE_PLUGIN_ROOT}`:外掛程式的安裝目錄,用於與 [plugin](/zh-TW/plugins) 一起打包的指令碼。在每次外掛程式更新時變更。

408* `${CLAUDE_PLUGIN_DATA}`:外掛程式的 [持久資料目錄](/zh-TW/plugins-reference#persistent-data-directory),用於應該在外掛程式更新後保留的依賴項和狀態。

409 

410<Tabs>

411 <Tab title="專案指令碼">

412 此範例使用 `$CLAUDE_PROJECT_DIR` 在任何 `Write` 或 `Edit` 工具呼叫後從專案的 `.claude/hooks/` 目錄執行樣式檢查器:

413 

414 ```json theme={null}

415 {

416 "hooks": {

417 "PostToolUse": [

418 {

419 "matcher": "Write|Edit",

420 "hooks": [

421 {

422 "type": "command",

423 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"

424 }

425 ]

426 }

427 ]

428 }

429 }

430 ```

431 </Tab>

432 

433 <Tab title="外掛程式指令碼">

434 在 `hooks/hooks.json` 中定義外掛程式 hooks,使用可選的頂層 `description` 欄位。啟用外掛程式時,其 hooks 會與您的使用者和專案 hooks 合併。

435 

436 此範例執行與外掛程式一起打包的格式化指令碼:

437 

438 ```json theme={null}

439 {

440 "description": "Automatic code formatting",

441 "hooks": {

442 "PostToolUse": [

443 {

444 "matcher": "Write|Edit",

445 "hooks": [

446 {

447 "type": "command",

448 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",

449 "timeout": 30

450 }

451 ]

452 }

453 ]

454 }

455 }

456 ```

457 

458 有關建立外掛程式 hooks 的詳細資訊,請參閱 [外掛程式元件參考](/zh-TW/plugins-reference#hooks)。

459 </Tab>

460</Tabs>

461 

462### Skills 和代理中的 Hooks

463 

464除了設定檔和外掛程式外,hooks 還可以使用 frontmatter 直接在 [skills](/zh-TW/skills) 和 [subagents](/zh-TW/sub-agents) 中定義。這些 hooks 的範圍限於元件的生命週期,只有在該元件處於活動狀態時才執行。

465 

466支援所有 hook 事件。對於 subagents,`Stop` hooks 會自動轉換為 `SubagentStop`,因為這是 subagent 完成時觸發的事件。

467 

468Hooks 使用與基於設定的 hooks 相同的配置格式,但範圍限於元件的生命週期,並在完成時清理。

469 

470此 skill 定義了一個 `PreToolUse` hook,在每個 `Bash` 命令之前執行安全驗證指令碼:

471 

472```yaml theme={null}

473---

474name: secure-operations

475description: Perform operations with security checks

476hooks:

477 PreToolUse:

478 - matcher: "Bash"

479 hooks:

480 - type: command

481 command: "./scripts/security-check.sh"

482---

483```

484 

485代理在其 YAML frontmatter 中使用相同的格式。

486 

487### `/hooks` 選單

488 

489在 Claude Code 中輸入 `/hooks` 以開啟唯讀瀏覽器來查看您配置的 hooks。選單顯示每個 hook 事件及其配置的 hooks 計數,讓您深入查看匹配器,並顯示每個 hook 處理程式的完整詳細資訊。使用它來驗證配置、檢查 hook 來自哪個設定檔,或檢查 hook 的命令、提示或 URL。

490 

491選單顯示所有五種 hook 類型:`command`、`prompt`、`agent`、`http` 和 `mcp_tool`。每個 hook 都標有 `[type]` 前綴和指示其定義位置的來源:

492 

493* `User`:來自 `~/.claude/settings.json`

494* `Project`:來自 `.claude/settings.json`

495* `Local`:來自 `.claude/settings.local.json`

496* `Plugin`:來自外掛程式的 `hooks/hooks.json`

497* `Session`:在目前工作階段中記錄在記憶體中

498* `Built-in`:由 Claude Code 內部註冊

499 

500選擇 hook 會開啟詳細檢視,顯示其事件、匹配器、類型、來源檔案和完整命令、提示或 URL。選單是唯讀的:要新增、修改或移除 hooks,請直接編輯設定 JSON 或要求 Claude 進行變更。

501 

502### 停用或移除 hooks

503 

504要移除 hook,請從設定 JSON 檔案中刪除其項目。

505 

506要暫時停用所有 hooks 而不移除它們,請在設定檔中設定 `"disableAllHooks": true`。沒有辦法在保留 hook 在配置中的同時停用單個 hook。

507 

508`disableAllHooks` 設定遵循受管理的設定階層。如果管理員已通過受管理的原則設定配置了 hooks,則在使用者、專案或本機設定中設定的 `disableAllHooks` 無法停用這些受管理的 hooks。只有在受管理的設定層級設定的 `disableAllHooks` 才能停用受管理的 hooks。

509 

510對設定檔中 hooks 的直接編輯通常由檔案監視程式自動拾取。

511 

512## Hook 輸入和輸出

513 

514命令 hooks 通過 stdin 接收 JSON 資料,並通過退出代碼、stdout 和 stderr 傳回結果。HTTP hooks 接收相同的 JSON 作為 POST 請求正文,並通過 HTTP 回應正文傳回結果。本部分涵蓋所有事件通用的欄位和行為。每個事件在 [Hook 事件](#hook-events) 下的部分包括其特定的輸入架構和決定控制選項。

515 

516### 通用輸入欄位

517 

518除了每個 [hook 事件](#hook-events) 部分中記錄的事件特定欄位外,所有 hook 事件都接收這些欄位作為 JSON。對於命令 hooks,此 JSON 通過 stdin 到達。對於 HTTP hooks,它作為 POST 請求正文到達。

519 

520| 欄位 | 描述 |

521| :---------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

522| `session_id` | 目前工作階段識別碼 |

523| `transcript_path` | 對話 JSON 的路徑 |

524| `cwd` | 叫用 hook 時的目前工作目錄 |

525| `permission_mode` | 目前 [權限模式](/zh-TW/permissions#permission-modes):`"default"`、`"plan"`、`"acceptEdits"`、`"auto"`、`"dontAsk"` 或 `"bypassPermissions"`。並非所有事件都接收此欄位:請參閱下面每個事件的 JSON 範例以檢查 |

526| `hook_event_name` | 觸發的事件名稱 |

527 

528使用 `--agent` 執行或在 subagent 內執行時,包括兩個額外欄位:

529 

530| 欄位 | 描述 |

531| :----------- | :------------------------------------------------------------------------------------------------------------------------------------- |

532| `agent_id` | Subagent 的唯一識別碼。僅當 hook 在 subagent 呼叫內觸發時出現。使用此項來區分 subagent hook 呼叫與主執行緒呼叫。 |

533| `agent_type` | 代理名稱(例如 `"Explore"` 或 `"security-reviewer"`)。當工作階段使用 `--agent` 或 hook 在 subagent 內觸發時出現。對於 subagents,subagent 的類型優先於工作階段的 `--agent` 值。 |

534 

535例如,Bash 命令的 `PreToolUse` hook 在 stdin 上接收此內容:

536 

537```json theme={null}

538{

539 "session_id": "abc123",

540 "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",

541 "cwd": "/home/user/my-project",

542 "permission_mode": "default",

543 "hook_event_name": "PreToolUse",

544 "tool_name": "Bash",

545 "tool_input": {

546 "command": "npm test"

547 }

548}

549```

550 

551`tool_name` 和 `tool_input` 欄位是事件特定的。每個 [hook 事件](#hook-events) 部分記錄了該事件的額外欄位。

552 

553### 退出代碼輸出

554 

555來自您的 hook 命令的退出代碼告訴 Claude Code 該操作是應該進行、被阻止還是被忽略。

556 

557**退出 0** 表示成功。Claude Code 解析 stdout 以查找 [JSON 輸出欄位](#json-output)。JSON 輸出僅在退出 0 時處理。對於大多數事件,stdout 被寫入詳細日誌,但不在成績單中顯示。例外是 `UserPromptSubmit`、`UserPromptExpansion` 和 `SessionStart`,其中 stdout 被新增為 Claude 可以看到和作用的上下文。

558 

559**退出 2** 表示阻止性錯誤。Claude Code 忽略 stdout 和其中的任何 JSON。相反,stderr 文字被反饋給 Claude 作為錯誤訊息。效果取決於事件:`PreToolUse` 阻止工具呼叫,`UserPromptSubmit` 拒絕提示,等等。有關完整清單,請參閱 [退出代碼 2 行為](#exit-code-2-behavior-per-event)。

560 

561**任何其他退出代碼** 是大多數 hook 事件的非阻止性錯誤。成績單顯示 `<hook name> hook error` 通知,後跟 stderr 的第一行,因此您可以識別原因而無需 `--debug`。執行繼續,完整的 stderr 被寫入詳細日誌。

562 

563例如,一個 hook 命令指令碼,阻止危險的 Bash 命令:

564 

565```bash theme={null}

566#!/bin/bash

567# 從 stdin 讀取 JSON 輸入,檢查命令

568command=$(jq -r '.tool_input.command' < /dev/stdin)

569 

570if [[ "$command" == rm* ]]; then

571 echo "Blocked: rm commands are not allowed" >&2

572 exit 2 # 阻止性錯誤:工具呼叫被阻止

573fi

574 

575exit 0 # 成功:工具呼叫進行

576```

577 

578<Warning>

579 對於大多數 hook 事件,只有退出代碼 2 會阻止操作。Claude Code 將退出代碼 1 視為非阻止性錯誤並繼續操作,儘管 1 是傳統的 Unix 失敗代碼。如果您的 hook 旨在強制執行原則,請使用 `exit 2`。例外是 `WorktreeCreate`,其中任何非零退出代碼都會中止 worktree 建立。

580</Warning>

581 

582#### 每個事件的退出代碼 2 行為

583 

584退出代碼 2 是 hook 發出「停止,不要這樣做」的方式。效果取決於事件,因為某些事件代表可以被阻止的操作(例如尚未發生的工具呼叫),而其他事件代表已經發生或無法防止的事情。

585 

586| Hook 事件 | 可以阻止? | 退出 2 時發生的情況 |

587| :-------------------- | :---- | :------------------------------------------------------------------------- |

588| `PreToolUse` | 是 | 阻止工具呼叫 |

589| `PermissionRequest` | 是 | 拒絕權限 |

590| `UserPromptSubmit` | 是 | 阻止提示處理並清除提示 |

591| `UserPromptExpansion` | 是 | 阻止擴展 |

592| `Stop` | 是 | 防止 Claude 停止,繼續對話 |

593| `SubagentStop` | 是 | 防止 subagent 停止 |

594| `TeammateIdle` | 是 | 防止隊友閒置(隊友繼續工作) |

595| `TaskCreated` | 是 | 回滾任務建立 |

596| `TaskCompleted` | 是 | 防止任務被標記為已完成 |

597| `ConfigChange` | 是 | 阻止配置變更生效(除了 `policy_settings`) |

598| `StopFailure` | 否 | 輸出和退出代碼被忽略 |

599| `PostToolUse` | 否 | 向 Claude 顯示 stderr(工具已執行) |

600| `PostToolUseFailure` | 否 | 向 Claude 顯示 stderr(工具已失敗) |

601| `PostToolBatch` | 是 | 在下一個模型呼叫之前停止代理迴圈 |

602| `PermissionDenied` | 否 | 退出代碼和 stderr 被忽略(拒絕已發生)。使用 JSON `hookSpecificOutput.retry: true` 告訴模型它可能重試 |

603| `Notification` | 否 | 僅向使用者顯示 stderr |

604| `SubagentStart` | 否 | 僅向使用者顯示 stderr |

605| `SessionStart` | 否 | 僅向使用者顯示 stderr |

606| `Setup` | 否 | 僅向使用者顯示 stderr |

607| `SessionEnd` | 否 | 僅向使用者顯示 stderr |

608| `CwdChanged` | 否 | 僅向使用者顯示 stderr |

609| `FileChanged` | 否 | 僅向使用者顯示 stderr |

610| `PreCompact` | 是 | 阻止壓縮 |

611| `PostCompact` | 否 | 僅向使用者顯示 stderr |

612| `Elicitation` | 是 | 拒絕徵詢 |

613| `ElicitationResult` | 是 | 阻止回應(操作變為拒絕) |

614| `WorktreeCreate` | 是 | 任何非零退出代碼都會導致 worktree 建立失敗 |

615| `WorktreeRemove` | 否 | 失敗僅在偵錯模式中記錄 |

616| `InstructionsLoaded` | 否 | 退出代碼被忽略 |

617 

618### HTTP 回應處理

619 

620HTTP hooks 使用 HTTP 狀態代碼和回應正文,而不是退出代碼和 stdout:

621 

622* **2xx 且正文為空**:成功,等同於退出代碼 0 且無輸出

623* **2xx 且正文為純文字**:成功,文字被新增為上下文

624* **2xx 且正文為 JSON**:成功,使用與命令 hooks 相同的 [JSON 輸出](#json-output) 架構進行解析

625* **非 2xx 狀態**:非阻止性錯誤,執行繼續

626* **連線失敗或逾時**:非阻止性錯誤,執行繼續

627 

628與命令 hooks 不同,HTTP hooks 無法僅通過狀態代碼發出阻止性錯誤信號。要阻止工具呼叫或拒絕權限,請返回 2xx 回應,其 JSON 正文包含適當的決定欄位。

629 

630### JSON 輸出

631 

632退出代碼讓您允許或阻止,但 JSON 輸出提供更細粒度的控制。與其以代碼 2 退出來阻止,不如以 0 退出並將 JSON 物件列印到 stdout。Claude Code 從該 JSON 讀取特定欄位以控制行為,包括 [決定控制](#decision-control) 以阻止、允許或升級給使用者。

633 

634<Note>

635 您必須為每個 hook 選擇一種方法,而不是兩種:要麼單獨使用退出代碼進行信號傳遞,要麼以 0 退出並列印 JSON 以進行結構化控制。Claude Code 僅在退出 0 時處理 JSON。如果您退出 2,任何 JSON 都會被忽略。

636</Note>

637 

638您的 hook 的 stdout 必須僅包含 JSON 物件。如果您的 shell 設定檔在啟動時列印文字,它可能會干擾 JSON 解析。請參閱故障排除指南中的 [JSON 驗證失敗](/zh-TW/hooks-guide#json-validation-failed)。

639 

640注入到上下文中的 hook 輸出(`additionalContext`、`systemMessage` 或純 stdout)的上限為 10,000 個字元。超過此限制的輸出會儲存到檔案並替換為預覽和檔案路徑,與大型工具結果的處理方式相同。

641 

642JSON 物件支援三種欄位:

643 

644* **通用欄位**,如 `continue`,在所有事件中工作。這些列在下表中。

645* **頂層 `decision` 和 `reason`** 由某些事件用來阻止或提供反饋。

646* **`hookSpecificOutput`** 是一個嵌套物件,用於需要更豐富控制的事件。它需要一個設定為事件名稱的 `hookEventName` 欄位。

647 

648| 欄位 | 預設 | 描述 |

649| :--------------- | :------ | :------------------------------------------------- |

650| `continue` | `true` | 如果為 `false`,Claude 在 hook 執行後完全停止處理。優先於任何事件特定的決定欄位 |

651| `stopReason` | 無 | 當 `continue` 為 `false` 時向使用者顯示的訊息。不向 Claude 顯示 |

652| `suppressOutput` | `false` | 如果為 `true`,隱藏詳細日誌中的 stdout |

653| `systemMessage` | 無 | 向使用者顯示的警告訊息 |

654 

655要無論事件類型如何都完全停止 Claude:

656 

657```json theme={null}

658{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }

659```

660 

661#### 新增 Claude 的上下文

662 

663`additionalContext` 欄位將字串從您的 hook 傳遞到 Claude 的上下文視窗。Claude Code 將字串包裝在系統提醒中,並將其插入到 hook 觸發的對話點。Claude 在下一個模型請求時讀取提醒,但它不會在介面中顯示為聊天訊息。

664 

665在 `hookSpecificOutput` 中返回 `additionalContext` 以及事件名稱:

666 

667```json theme={null}

668{

669 "hookSpecificOutput": {

670 "hookEventName": "PostToolUse",

671 "additionalContext": "This file is generated. Edit src/schema.ts and run `bun generate` instead."

672 }

673}

674```

675 

676提醒出現的位置取決於事件:

677 

678* [SessionStart](#sessionstart)、[Setup](#setup) 和 [SubagentStart](#subagentstart):在對話開始,在第一個提示之前

679* [UserPromptSubmit](#userpromptsubmit) 和 [UserPromptExpansion](#userpromptexpansion):與提交的提示一起

680* [PreToolUse](#pretooluse)、[PostToolUse](#posttooluse)、[PostToolUseFailure](#posttoolusefailure) 和 [PostToolBatch](#posttoolbatch):在工具結果旁邊

681 

682當多個 hooks 為同一事件返回 `additionalContext` 時,Claude 接收所有值。如果值超過 10,000 個字元,Claude Code 會將完整文字寫入工作階段目錄中的檔案,並將檔案路徑與簡短預覽傳遞給 Claude。

683 

684使用 `additionalContext` 來提供 Claude 應該知道的有關您環境目前狀態或剛剛執行的操作的資訊:

685 

686* **環境狀態**:目前分支、部署目標或活躍的功能旗標

687* **條件專案規則**:哪個測試命令適用於剛編輯的檔案,此 worktree 中哪些目錄是唯讀的

688* **外部資料**:分配給您的開放問題、最近的 CI 結果、從內部服務擷取的內容

689 

690對於永遠不會改變的指示,優先使用 [CLAUDE.md](/zh-TW/memory)。它無需執行指令碼即可載入,是靜態專案約定的標準位置。

691 

692將文字寫成事實陳述,而不是命令式系統指示。「部署目標是生產」或「此儲存庫使用 `bun test`」之類的措辭讀起來像專案資訊。框架為帶外系統命令的文字可能會觸發 Claude 的提示注入防禦,這會導致 Claude 將文字呈現給您,而不是將其視為上下文。

693 

694注入後,文字會儲存在工作階段成績單中。對於 `PostToolUse` 或 `UserPromptSubmit` 等中期事件,使用 `--continue` 或 `--resume` 繼續會重播儲存的文字,而不是為過去的回合重新執行 hook,因此時間戳或提交 SHA 等值在繼續時變得陳舊。`SessionStart` hooks 在使用 `source` 設定為 `"resume"` 的 `--resume` 時再次執行,因此它們可以刷新其上下文。

695 

696#### 決定控制

697 

698並非每個事件都支援阻止或通過 JSON 控制行為。支援的事件各自使用不同的欄位集來表達該決定。在編寫 hook 之前,使用此表作為快速參考:

699 

700| 事件 | 決定模式 | 關鍵欄位 |

701| :-------------------------------------------------------------------------------------------------------------------------- | :---------------------- | :------------------------------------------------------------------------------------------------- |

702| UserPromptSubmit、UserPromptExpansion、PostToolUse、PostToolUseFailure、PostToolBatch、Stop、SubagentStop、ConfigChange、PreCompact | 頂層 `decision` | `decision: "block"`、`reason` |

703| TeammateIdle、TaskCreated、TaskCompleted | 退出代碼或 `continue: false` | 退出代碼 2 使用 stderr 反饋阻止操作。JSON `{"continue": false, "stopReason": "..."}` 也會完全停止隊友,匹配 `Stop` hook 行為 |

704| PreToolUse | `hookSpecificOutput` | `permissionDecision`(allow/deny/ask/defer)、`permissionDecisionReason` |

705| PermissionRequest | `hookSpecificOutput` | `decision.behavior`(allow/deny) |

706| PermissionDenied | `hookSpecificOutput` | `retry: true` 告訴模型它可能重試被拒絕的工具呼叫 |

707| WorktreeCreate | 路徑返回 | 命令 hook 在 stdout 上列印路徑;HTTP hook 通過 `hookSpecificOutput.worktreePath` 返回。Hook 失敗或缺少路徑會導致建立失敗 |

708| Elicitation | `hookSpecificOutput` | `action`(accept/decline/cancel)、`content`(accept 的表單欄位值) |

709| ElicitationResult | `hookSpecificOutput` | `action`(accept/decline/cancel)、`content`(覆蓋表單欄位值) |

710| WorktreeRemove、Notification、SessionEnd、PostCompact、InstructionsLoaded、StopFailure、CwdChanged、FileChanged | 無 | 無決定控制。用於副作用,如記錄或清理 |

711 

712以下是每種模式的實際範例:

713 

714<Tabs>

715 <Tab title="頂層決定">

716 由 `UserPromptSubmit`、`UserPromptExpansion`、`PostToolUse`、`PostToolUseFailure`、`PostToolBatch`、`Stop`、`SubagentStop`、`ConfigChange` 和 `PreCompact` 使用。唯一的值是 `"block"`。要允許操作進行,請從 JSON 中省略 `decision`,或以 0 退出而不帶任何 JSON:

717 

718 ```json theme={null}

719 {

720 "decision": "block",

721 "reason": "Test suite must pass before proceeding"

722 }

723 ```

724 </Tab>

725 

726 <Tab title="PreToolUse">

727 使用 `hookSpecificOutput` 進行更豐富的控制:允許、拒絕或升級給使用者。您還可以在執行前修改工具輸入或為 Claude 注入額外上下文。有關完整的選項集,請參閱 [PreToolUse 決定控制](#pretooluse-decision-control)。

728 

729 ```json theme={null}

730 {

731 "hookSpecificOutput": {

732 "hookEventName": "PreToolUse",

733 "permissionDecision": "deny",

734 "permissionDecisionReason": "Database writes are not allowed"

735 }

736 }

737 ```

738 </Tab>

739 

740 <Tab title="PermissionRequest">

741 使用 `hookSpecificOutput` 代表使用者允許或拒絕權限請求。允許時,您還可以修改工具的輸入或應用權限規則,以便使用者不會再次被提示。有關完整的選項集,請參閱 [PermissionRequest 決定控制](#permissionrequest-decision-control)。

742 

743 ```json theme={null}

744 {

745 "hookSpecificOutput": {

746 "hookEventName": "PermissionRequest",

747 "decision": {

748 "behavior": "allow",

749 "updatedInput": {

750 "command": "npm run lint"

751 }

752 }

753 }

754 }

755 ```

756 </Tab>

757</Tabs>

758 

759有關擴展範例,包括 Bash 命令驗證、提示篩選和自動批准指令碼,請參閱指南中的 [您可以自動化的內容](/zh-TW/hooks-guide#what-you-can-automate) 和 [Bash 命令驗證器參考實現](https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py)。

760 

761## Hook 事件

762 

763每個事件對應於 Claude Code 生命週期中 hooks 可以執行的一個點。下面的部分按順序排列以匹配生命週期:從工作階段設定通過代理迴圈到工作階段結束。每個部分描述事件何時觸發、它支援什麼匹配器、它接收的 JSON 輸入,以及如何通過輸出控制行為。

764 

765### SessionStart

766 

767在 Claude Code 啟動新工作階段或恢復現有工作階段時執行。適用於載入開發上下文,例如現有問題或程式碼庫的最近變更,或設定環境變數。對於不需要指令碼的靜態上下文,請改用 [CLAUDE.md](/zh-TW/memory)。

768 

769SessionStart 在每個工作階段執行,因此請保持這些 hooks 快速。僅支援 `type: "command"` 和 `type: "mcp_tool"` hooks。

770 

771匹配器值對應於工作階段的啟動方式:

772 

773| 匹配器 | 何時觸發 |

774| :-------- | :---------------------------------- |

775| `startup` | 新工作階段 |

776| `resume` | `--resume`、`--continue` 或 `/resume` |

777| `clear` | `/clear` |

778| `compact` | 自動或手動壓縮 |

779 

780#### SessionStart 輸入

781 

782除了 [通用輸入欄位](#common-input-fields) 外,SessionStart hooks 還接收 `source`、`model` 和可選的 `agent_type`。`source` 欄位指示工作階段如何啟動:新工作階段為 `"startup"`,恢復的工作階段為 `"resume"`,`/clear` 後為 `"clear"`,或壓縮後為 `"compact"`。`model` 欄位包含模型識別碼。如果您使用 `claude --agent <name>` 啟動 Claude Code,`agent_type` 欄位包含代理名稱。

783 

784```json theme={null}

785{

786 "session_id": "abc123",

787 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

788 "cwd": "/Users/...",

789 "hook_event_name": "SessionStart",

790 "source": "startup",

791 "model": "claude-sonnet-4-6"

792}

793```

794 

795#### SessionStart 決定控制

796 

797您的 hook 指令碼列印到 stdout 的任何文字都被新增為 Claude 的上下文。除了所有 hooks 可用的 [JSON 輸出欄位](#json-output) 外,您還可以返回這些事件特定欄位:

798 

799| 欄位 | 描述 |

800| :------------------ | :---------------------------------------------------------------------------------------------- |

801| `additionalContext` | 新增到 Claude 上下文開始處的字串,在第一個提示之前。請參閱 [為 Claude 新增上下文](#add-context-for-claude) 以了解文字如何傳遞以及要放入其中的內容 |

802 

803```json theme={null}

804{

805 "hookSpecificOutput": {

806 "hookEventName": "SessionStart",

807 "additionalContext": "Current branch: feat/auth-refactor\nUncommitted changes: src/auth.ts, src/login.tsx\nActive issue: #4211 Migrate to OAuth2"

808 }

809}

810```

811 

812由於純 stdout 已經到達 Claude 用於此事件,只載入上下文的 hook 可以直接列印到 stdout 而無需建立 JSON。當您需要將上下文與其他欄位(例如 `suppressOutput`)結合時,請使用 JSON 形式。

813 

814#### 持久化環境變數

815 

816SessionStart hooks 可以存取 `CLAUDE_ENV_FILE` 環境變數,該變數提供一個檔案路徑,您可以在其中為後續 Bash 命令持久化環境變數。

817 

818要設定個別環境變數,請將 `export` 陳述式寫入 `CLAUDE_ENV_FILE`。使用追加(`>>`)來保留由其他 hooks 設定的變數:

819 

820```bash theme={null}

821#!/bin/bash

822 

823if [ -n "$CLAUDE_ENV_FILE" ]; then

824 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"

825 echo 'export DEBUG_LOG=true' >> "$CLAUDE_ENV_FILE"

826 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"

827fi

828 

829exit 0

830```

831 

832要捕獲設定命令中的所有環境變更,請比較之前和之後的匯出變數:

833 

834```bash theme={null}

835#!/bin/bash

836 

837ENV_BEFORE=$(export -p | sort)

838 

839# 執行修改環境的設定命令

840source ~/.nvm/nvm.sh

841nvm use 20

842 

843if [ -n "$CLAUDE_ENV_FILE" ]; then

844 ENV_AFTER=$(export -p | sort)

845 comm -13 <(echo "$ENV_BEFORE") <(echo "$ENV_AFTER") >> "$CLAUDE_ENV_FILE"

846fi

847 

848exit 0

849```

850 

851寫入此檔案的任何變數都將在工作階段期間 Claude Code 執行的所有後續 Bash 命令中可用。

852 

853<Note>

854 `CLAUDE_ENV_FILE` 可用於 SessionStart、[Setup](#setup)、[CwdChanged](#cwdchanged) 和 [FileChanged](#filechanged) hooks。其他 hook 類型無法存取此變數。

855</Note>

856 

857### Setup

858 

859僅當您使用 `--init-only` 啟動 Claude Code,或在列印模式(`-p`)中使用 `--init` 或 `--maintenance` 時觸發。它在正常啟動時不觸發。使用它進行一次性依賴項安裝或您從 CI 或指令碼明確觸發的計劃清理,與正常工作階段啟動分開。對於每個工作階段的初始化,請改用 [SessionStart](#sessionstart)。

860 

861匹配器值對應於觸發 hook 的 CLI 標誌:

862 

863| 匹配器 | 何時觸發 |

864| :------------ | :---------------------------------------- |

865| `init` | `claude --init-only` 或 `claude -p --init` |

866| `maintenance` | `claude -p --maintenance` |

867 

868`--init-only` 執行 Setup hooks 和 SessionStart hooks(帶有 `startup` 匹配器),然後退出而不啟動對話。`--init` 和 `--maintenance` 僅在與 `-p`(列印模式)結合時觸發 Setup hooks;在互動式工作階段中,這兩個標誌目前不觸發 Setup hooks。

869 

870因為 Setup 不在每次啟動時觸發,需要安裝依賴項的外掛程式無法僅依賴 Setup。實際的模式是在首次使用時檢查依賴項,如果缺失則安裝,例如測試 `${CLAUDE_PLUGIN_DATA}/node_modules` 的 hook 或 skill,如果不存在則執行 `npm install`。請參閱 [持久資料目錄](/zh-TW/plugins-reference#persistent-data-directory) 以了解在何處儲存已安裝的依賴項。

871 

872#### Setup 輸入

873 

874除了 [通用輸入欄位](#common-input-fields) 外,Setup hooks 還接收設定為 `"init"` 或 `"maintenance"` 的 `trigger` 欄位:

875 

876```json theme={null}

877{

878 "session_id": "abc123",

879 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

880 "cwd": "/Users/...",

881 "hook_event_name": "Setup",

882 "trigger": "init"

883}

884```

885 

886#### Setup 決定控制

887 

888Setup hooks 無法阻止。在退出代碼 2 時,stderr 向使用者顯示;在任何其他非零退出代碼時,stderr 僅在您使用 `--verbose` 啟動時出現。在兩種情況下,執行都會繼續。要將資訊傳遞到 Claude 的上下文中,請在 JSON 輸出中返回 `additionalContext`;純 stdout 僅寫入偵錯日誌。除了所有 hooks 可用的 [JSON 輸出欄位](#json-output) 外,您還可以返回這些事件特定欄位:

889 

890| 欄位 | 描述 |

891| :------------------ | :------------------------------- |

892| `additionalContext` | 新增到 Claude 上下文的字串。多個 hooks 的值被連接 |

893 

894```json theme={null}

895{

896 "hookSpecificOutput": {

897 "hookEventName": "Setup",

898 "additionalContext": "Dependencies installed: node_modules, .venv"

899 }

900}

901```

902 

903Setup hooks 可以存取 `CLAUDE_ENV_FILE`。寫入該檔案的變數會持久化到工作階段的後續 Bash 命令中,就像在 [SessionStart hooks](#persist-environment-variables) 中一樣。僅支援 `type: "command"` 和 `type: "mcp_tool"` hooks。

904 

905### InstructionsLoaded

906 

907當 `CLAUDE.md` 或 `.claude/rules/*.md` 檔案被載入到上下文中時觸發。此事件在工作階段開始時針對急切載入的檔案觸發,稍後當檔案被延遲載入時再次觸發,例如當 Claude 存取包含嵌套 `CLAUDE.md` 的子目錄時,或當具有 `paths:` frontmatter 的條件規則匹配時。該 hook 不支援阻止或決定控制。它以非同步方式執行以用於可觀測性目的。

908 

909匹配器針對 `load_reason` 執行。例如,使用 `"matcher": "session_start"` 僅針對在工作階段開始時載入的檔案觸發,或使用 `"matcher": "path_glob_match|nested_traversal"` 僅針對延遲載入觸發。

910 

911#### InstructionsLoaded 輸入

912 

913除了 [通用輸入欄位](#common-input-fields) 外,InstructionsLoaded hooks 還接收這些欄位:

914 

915| 欄位 | 描述 |

916| :------------------ | :--------------------------------------------------------------------------------------------------------------------------- |

917| `file_path` | 被載入的指令檔案的絕對路徑 |

918| `memory_type` | 檔案的範圍:`"User"`、`"Project"`、`"Local"` 或 `"Managed"` |

919| `load_reason` | 檔案被載入的原因:`"session_start"`、`"nested_traversal"`、`"path_glob_match"`、`"include"` 或 `"compact"`。`"compact"` 值在壓縮事件後重新載入指令檔案時觸發 |

920| `globs` | 檔案 `paths:` frontmatter 中的路徑 glob 模式(如果有)。僅針對 `path_glob_match` 載入出現 |

921| `trigger_file_path` | 觸發此載入的檔案的路徑,用於延遲載入 |

922| `parent_file_path` | 包含此檔案的父指令檔案的路徑,用於 `include` 載入 |

923 

924```json theme={null}

925{

926 "session_id": "abc123",

927 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",

928 "cwd": "/Users/my-project",

929 "hook_event_name": "InstructionsLoaded",

930 "file_path": "/Users/my-project/CLAUDE.md",

931 "memory_type": "Project",

932 "load_reason": "session_start"

933}

934```

935 

936#### InstructionsLoaded 決定控制

937 

938InstructionsLoaded hooks 沒有決定控制。它們無法阻止或修改指令載入。使用此事件進行稽核記錄、合規性追蹤或可觀測性。

939 

940### UserPromptSubmit

941 

942在使用者提交提示時執行,在 Claude 處理之前。這允許您根據提示/對話新增額外上下文、驗證提示或阻止某些類型的提示。

943 

944#### UserPromptSubmit 輸入

945 

946除了 [通用輸入欄位](#common-input-fields) 外,UserPromptSubmit hooks 還接收包含使用者提交的文字的 `prompt` 欄位。

947 

948```json theme={null}

949{

950 "session_id": "abc123",

951 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

952 "cwd": "/Users/...",

953 "permission_mode": "default",

954 "hook_event_name": "UserPromptSubmit",

955 "prompt": "Write a function to calculate the factorial of a number"

956}

957```

958 

959#### UserPromptSubmit 決定控制

960 

961`UserPromptSubmit` hooks 可以控制使用者提示是否被處理並新增上下文。所有 [JSON 輸出欄位](#json-output) 都可用。

962 

963有兩種方式在退出代碼 0 時向對話新增上下文:

964 

965* **純文字 stdout**:寫入 stdout 的任何非 JSON 文字都被新增為上下文

966* **帶有 `additionalContext` 的 JSON**:使用下面的 JSON 格式以獲得更多控制。`additionalContext` 欄位被新增為上下文

967 

968純 stdout 在成績單中顯示為 hook 輸出。`additionalContext` 欄位被更謹慎地新增。

969 

970要阻止提示,請返回一個 JSON 物件,其中 `decision` 設定為 `"block"`:

971 

972| 欄位 | 描述 |

973| :------------------ | :----------------------------------------------------------------------- |

974| `decision` | `"block"` 防止提示被處理並從上下文中清除它。省略以允許提示進行 |

975| `reason` | 當 `decision` 為 `"block"` 時向使用者顯示。不新增到上下文 |

976| `additionalContext` | 新增到 Claude 上下文的字串,與提交的提示一起。請參閱 [為 Claude 新增上下文](#add-context-for-claude) |

977| `sessionTitle` | 設定工作階段標題,與 `/rename` 相同的效果。使用此項根據提示內容自動命名工作階段 |

978 

979```json theme={null}

980{

981 "decision": "block",

982 "reason": "Explanation for decision",

983 "hookSpecificOutput": {

984 "hookEventName": "UserPromptSubmit",

985 "additionalContext": "My additional context here",

986 "sessionTitle": "My session title"

987 }

988}

989```

990 

991<Note>

992 JSON 格式對於簡單用例不是必需的。要新增上下文,您可以使用退出代碼 0 將純文字列印到 stdout。當您需要阻止提示或想要更結構化的控制時,請使用 JSON。

993</Note>

994 

995### UserPromptExpansion

996 

997當使用者輸入的斜杠命令在到達 Claude 之前展開為提示時執行。使用此項來阻止特定命令的直接呼叫、為特定 skill 注入上下文,或記錄使用者呼叫哪些命令。例如,匹配 `deploy` 的 hook 可以在不存在批准檔案時阻止 `/deploy`,或匹配審查 skill 的 hook 可以將團隊的審查檢查清單附加為 `additionalContext`。

998 

999此事件涵蓋 `PreToolUse` 不涵蓋的路徑:匹配 `Skill` 工具的 `PreToolUse` hook 僅在 Claude 呼叫工具時觸發,但直接輸入 `/skillname` 會繞過 `PreToolUse`。`UserPromptExpansion` 在該直接路徑上觸發。

1000 

1001匹配 `command_name`。留空匹配器以針對每個提示類型斜杠命令觸發。

1002 

1003#### UserPromptExpansion 輸入

1004 

1005除了 [通用輸入欄位](#common-input-fields) 外,UserPromptExpansion hooks 還接收 `expansion_type`、`command_name`、`command_args`、`command_source` 和原始 `prompt` 字串。`expansion_type` 欄位對於 skill 和自訂命令為 `slash_command`,或對於 MCP 伺服器提示為 `mcp_prompt`。

1006 

1007```json theme={null}

1008{

1009 "session_id": "abc123",

1010 "transcript_path": "/Users/.../00893aaf.jsonl",

1011 "cwd": "/Users/...",

1012 "permission_mode": "default",

1013 "hook_event_name": "UserPromptExpansion",

1014 "expansion_type": "slash_command",

1015 "command_name": "example-skill",

1016 "command_args": "arg1 arg2",

1017 "command_source": "plugin",

1018 "prompt": "/example-skill arg1 arg2"

1019}

1020```

1021 

1022#### UserPromptExpansion 決定控制

1023 

1024`UserPromptExpansion` hooks 可以阻止展開或新增上下文。所有 [JSON 輸出欄位](#json-output) 都可用。

1025 

1026| 欄位 | 描述 |

1027| :------------------ | :----------------------------------------------------------------------- |

1028| `decision` | `"block"` 防止斜杠命令展開。省略以允許它進行 |

1029| `reason` | 當 `decision` 為 `"block"` 時向使用者顯示 |

1030| `additionalContext` | 新增到 Claude 上下文的字串,與展開的提示一起。請參閱 [為 Claude 新增上下文](#add-context-for-claude) |

1031 

1032```json theme={null}

1033{

1034 "decision": "block",

1035 "reason": "This slash command is not available",

1036 "hookSpecificOutput": {

1037 "hookEventName": "UserPromptExpansion",

1038 "additionalContext": "Additional context for this expansion"

1039 }

1040}

1041```

1042 

1043### PreToolUse

1044 

1045在 Claude 建立工具參數後和處理工具呼叫之前執行。匹配工具名稱:`Bash`、`Edit`、`Write`、`Read`、`Glob`、`Grep`、`Agent`、`WebFetch`、`WebSearch`、`AskUserQuestion`、`ExitPlanMode` 和任何 [MCP 工具名稱](#match-mcp-tools)。

1046 

1047使用 [PreToolUse 決定控制](#pretooluse-decision-control) 來允許、拒絕、詢問或延遲工具呼叫。

1048 

1049#### PreToolUse 輸入

1050 

1051除了 [通用輸入欄位](#common-input-fields) 外,PreToolUse hooks 還接收 `tool_name`、`tool_input` 和 `tool_use_id`。`tool_input` 欄位取決於工具:

1052 

1053##### Bash

1054 

1055執行 shell 命令。

1056 

1057| 欄位 | 類型 | 範例 | 描述 |

1058| :------------------ | :-- | :----------------- | :------------ |

1059| `command` | 字串 | `"npm test"` | 要執行的 shell 命令 |

1060| `description` | 字串 | `"Run test suite"` | 命令執行內容的可選描述 |

1061| `timeout` | 數字 | `120000` | 可選逾時(毫秒) |

1062| `run_in_background` | 布林值 | `false` | 是否在背景執行命令 |

1063 

1064##### Write

1065 

1066建立或覆寫檔案。

1067 

1068| 欄位 | 類型 | 範例 | 描述 |

1069| :---------- | :- | :-------------------- | :---------- |

1070| `file_path` | 字串 | `"/path/to/file.txt"` | 要寫入的檔案的絕對路徑 |

1071| `content` | 字串 | `"file content"` | 要寫入檔案的內容 |

1072 

1073##### Edit

1074 

1075替換現有檔案中的字串。

1076 

1077| 欄位 | 類型 | 範例 | 描述 |

1078| :------------ | :-- | :-------------------- | :---------- |

1079| `file_path` | 字串 | `"/path/to/file.txt"` | 要編輯的檔案的絕對路徑 |

1080| `old_string` | 字串 | `"original text"` | 要查詢和替換的文字 |

1081| `new_string` | 字串 | `"replacement text"` | 替換文字 |

1082| `replace_all` | 布林值 | `false` | 是否替換所有出現次數 |

1083 

1084##### Read

1085 

1086讀取檔案內容。

1087 

1088| 欄位 | 類型 | 範例 | 描述 |

1089| :---------- | :- | :-------------------- | :---------- |

1090| `file_path` | 字串 | `"/path/to/file.txt"` | 要讀取的檔案的絕對路徑 |

1091| `offset` | 數字 | `10` | 可選的開始讀取的行號 |

1092| `limit` | 數字 | `50` | 可選的要讀取的行數 |

1093 

1094##### Glob

1095 

1096尋找與 glob 模式匹配的檔案。

1097 

1098| 欄位 | 類型 | 範例 | 描述 |

1099| :-------- | :- | :--------------- | :---------------- |

1100| `pattern` | 字串 | `"**/*.ts"` | 要匹配檔案的 glob 模式 |

1101| `path` | 字串 | `"/path/to/dir"` | 可選的搜尋目錄。預設為目前工作目錄 |

1102 

1103##### Grep

1104 

1105使用正規表達式搜尋檔案內容。

1106 

1107| 欄位 | 類型 | 範例 | 描述 |

1108| :------------ | :-- | :--------------- | :------------------------------------------------------------------------ |

1109| `pattern` | 字串 | `"TODO.*fix"` | 要搜尋的正規表達式模式 |

1110| `path` | 字串 | `"/path/to/dir"` | 可選的要搜尋的檔案或目錄 |

1111| `glob` | 字串 | `"*.ts"` | 可選的 glob 模式以篩選檔案 |

1112| `output_mode` | 字串 | `"content"` | `"content"`、`"files_with_matches"` 或 `"count"`。預設為 `"files_with_matches"` |

1113| `-i` | 布林值 | `true` | 不區分大小寫的搜尋 |

1114| `multiline` | 布林值 | `false` | 啟用多行匹配 |

1115 

1116##### WebFetch

1117 

1118擷取和處理網路內容。

1119 

1120| 欄位 | 類型 | 範例 | 描述 |

1121| :------- | :- | :---------------------------- | :----------- |

1122| `url` | 字串 | `"https://example.com/api"` | 要擷取內容的 URL |

1123| `prompt` | 字串 | `"Extract the API endpoints"` | 在擷取的內容上執行的提示 |

1124 

1125##### WebSearch

1126 

1127搜尋網路。

1128 

1129| 欄位 | 類型 | 範例 | 描述 |

1130| :---------------- | :- | :----------------------------- | :-------------- |

1131| `query` | 字串 | `"react hooks best practices"` | 搜尋查詢 |

1132| `allowed_domains` | 陣列 | `["docs.example.com"]` | 可選:僅包含來自這些網域的結果 |

1133| `blocked_domains` | 陣列 | `["spam.example.com"]` | 可選:排除來自這些網域的結果 |

1134 

1135##### Agent

1136 

1137生成一個 [subagent](/zh-TW/sub-agents)。

1138 

1139| 欄位 | 類型 | 範例 | 描述 |

1140| :-------------- | :- | :------------------------- | :------------ |

1141| `prompt` | 字串 | `"Find all API endpoints"` | 代理要執行的任務 |

1142| `description` | 字串 | `"Find API endpoints"` | 任務的簡短描述 |

1143| `subagent_type` | 字串 | `"Explore"` | 要使用的專門代理類型 |

1144| `model` | 字串 | `"sonnet"` | 可選的模型別名以覆蓋預設值 |

1145 

1146##### AskUserQuestion

1147 

1148詢問使用者一到四個多選題。

1149 

1150| 欄位 | 類型 | 範例 | 描述 |

1151| :---------- | :- | :----------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------- |

1152| `questions` | 陣列 | `[{"question": "Which framework?", "header": "Framework", "options": [{"label": "React"}], "multiSelect": false}]` | 要呈現的問題,每個都有 `question` 字串、簡短 `header`、`options` 陣列和可選的 `multiSelect` 標誌 |

1153| `answers` | 物件 | `{"Which framework?": "React"}` | 可選。將問題文字對應到選定的選項標籤。多選答案用逗號連接標籤。Claude 不設定此欄位;通過 `updatedInput` 提供它以以程式方式回答 |

1154 

1155#### PreToolUse 決定控制

1156 

1157`PreToolUse` hooks 可以控制工具呼叫是否進行。與使用頂層 `decision` 欄位的其他 hooks 不同,PreToolUse 在 `hookSpecificOutput` 物件內返回其決定。這提供了更豐富的控制:四個結果(允許、拒絕、詢問或延遲)加上在執行前修改工具輸入的能力。

1158 

1159| 欄位 | 描述 |

1160| :------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |

1161| `permissionDecision` | `"allow"` 跳過權限提示。`"deny"` 防止工具呼叫。`"ask"` 提示使用者確認。`"defer"` 優雅地退出,以便稍後可以恢復工具。[拒絕和詢問規則](/zh-TW/permissions#manage-permissions) 在 hook 返回 `"allow"` 時仍然適用 |

1162| `permissionDecisionReason` | 對於 `"allow"` 和 `"ask"`,向使用者顯示但不向 Claude 顯示。對於 `"deny"`,向 Claude 顯示。對於 `"defer"`,被忽略 |

1163| `updatedInput` | 在執行前修改工具的輸入參數。替換整個輸入物件,因此包括未修改的欄位以及修改後的欄位。與 `"allow"` 結合以自動批准,或與 `"ask"` 結合以向使用者顯示修改後的輸入。對於 `"defer"`,被忽略 |

1164| `additionalContext` | 在工具執行前新增到 Claude 上下文的字串。對於 `"defer"`,被忽略。請參閱 [為 Claude 新增上下文](#add-context-for-claude) |

1165 

1166當多個 PreToolUse hooks 返回不同的決定時,優先順序是 `deny` > `defer` > `ask` > `allow`。

1167 

1168當 hook 返回 `"ask"` 時,向使用者顯示的權限提示包括一個標籤,識別 hook 來自何處:例如 `[User]`、`[Project]`、`[Plugin]` 或 `[Local]`。這幫助使用者了解哪個配置來源正在請求確認。

1169 

1170```json theme={null}

1171{

1172 "hookSpecificOutput": {

1173 "hookEventName": "PreToolUse",

1174 "permissionDecision": "allow",

1175 "permissionDecisionReason": "My reason here",

1176 "updatedInput": {

1177 "field_to_modify": "new value"

1178 },

1179 "additionalContext": "Current environment: production. Proceed with caution."

1180 }

1181}

1182```

1183 

1184`AskUserQuestion` 和 `ExitPlanMode` 需要使用者互動,通常在 [非互動模式](/zh-TW/headless) 中使用 `-p` 標誌時阻止。返回 `permissionDecision: "allow"` 以及 `updatedInput` 滿足該要求:hook 從 stdin 讀取工具的輸入,通過您自己的 UI 收集答案,並在 `updatedInput` 中返回它,以便工具執行而不提示。僅返回 `"allow"` 對這些工具不夠。對於 `AskUserQuestion`,回顯原始 `questions` 陣列並新增一個 [`answers`](#askuserquestion) 物件,將每個問題的文字對應到選定的答案。

1185 

1186<Note>

1187 PreToolUse 之前使用頂層 `decision` 和 `reason` 欄位,但這些對此事件已棄用。改用 `hookSpecificOutput.permissionDecision` 和 `hookSpecificOutput.permissionDecisionReason`。棄用的值 `"approve"` 和 `"block"` 對應於 `"allow"` 和 `"deny"`。PostToolUse 和 Stop 等其他事件繼續使用頂層 `decision` 和 `reason` 作為其目前格式。

1188</Note>

1189 

1190#### 延遲工具呼叫以供稍後使用

1191 

1192`"defer"` 用於執行 `claude -p` 作為子程序並讀取其 JSON 輸出的整合,例如 Agent SDK 應用程式或建立在 Claude Code 之上的自訂 UI。它讓該呼叫程序在工具呼叫處暫停 Claude,通過其自己的介面收集輸入,並從中斷處恢復。Claude Code 僅在 [非互動模式](/zh-TW/headless) 中使用 `-p` 標誌時遵守此值。在互動式工作階段中,它記錄警告並忽略 hook 結果。

1193 

1194<Note>

1195 `defer` 值需要 Claude Code v2.1.89 或更高版本。較早的版本無法識別它,工具通過正常權限流程進行。

1196</Note>

1197 

1198`AskUserQuestion` 工具是典型情況:Claude 想要詢問使用者某些事情,但沒有終端來回答。往返工作如下:

1199 

12001. Claude 呼叫 `AskUserQuestion`。`PreToolUse` hook 觸發。

12012. Hook 返回 `permissionDecision: "defer"`。工具不執行。程序以 `stop_reason: "tool_deferred"` 退出,待處理的工具呼叫保留在成績單中。

12023. 呼叫程序從 SDK 結果讀取 `deferred_tool_use`,在其自己的 UI 中呈現問題,並等待答案。

12034. 呼叫程序執行 `claude -p --resume <session-id>`。相同的工具呼叫再次觸發 `PreToolUse`。

12045. Hook 返回 `permissionDecision: "allow"`,答案在 `updatedInput` 中。工具執行,Claude 繼續。

1205 

1206`deferred_tool_use` 欄位攜帶工具的 `id`、`name` 和 `input`。`input` 是 Claude 為工具呼叫生成的參數,在執行前捕獲:

1207 

1208```json theme={null}

1209{

1210 "type": "result",

1211 "subtype": "success",

1212 "stop_reason": "tool_deferred",

1213 "session_id": "abc123",

1214 "deferred_tool_use": {

1215 "id": "toolu_01abc",

1216 "name": "AskUserQuestion",

1217 "input": { "questions": [{ "question": "Which framework?", "header": "Framework", "options": [{"label": "React"}, {"label": "Vue"}], "multiSelect": false }] }

1218 }

1219}

1220```

1221 

1222沒有逾時或重試限制。工作階段保留在磁碟上,直到您恢復它,受到 [`cleanupPeriodDays`](/zh-TW/settings#available-settings) 保留掃描的約束,該掃描在預設 30 天後刪除工作階段檔案。如果恢復時答案還沒有準備好,hook 可以再次返回 `"defer"`,程序以相同的方式退出。呼叫程序控制何時通過最終返回 `"allow"` 或 `"deny"` 從 hook 中斷迴圈。

1223 

1224`"defer"` 僅在 Claude 在轉向中進行單一工具呼叫時有效。如果 Claude 一次進行多個工具呼叫,`"defer"` 會被忽略並顯示警告,工具通過正常權限流程進行。該限制存在是因為恢復只能重新執行一個工具:沒有辦法延遲一個呼叫而不留下其他呼叫未解決。

1225 

1226如果恢復時延遲的工具不再可用,程序以 `stop_reason: "tool_deferred_unavailable"` 和 `is_error: true` 退出,在 hook 觸發之前。這發生在提供工具的 MCP 伺服器對於恢復的工作階段未連接時。`deferred_tool_use` 有效負載仍然包括在內,以便您可以識別哪個工具遺失。

1227 

1228<Warning>

1229 `--resume` 不會從先前的工作階段恢復權限模式。在恢復時傳遞與工具被延遲時活動的相同 `--permission-mode` 標誌。Claude Code 在模式不同時記錄警告。

1230</Warning>

1231 

1232### PermissionRequest

1233 

1234在向使用者顯示權限對話框時執行。使用 [PermissionRequest 決定控制](#permissionrequest-decision-control) 代表使用者允許或拒絕。

1235 

1236匹配工具名稱,與 PreToolUse 相同的值。

1237 

1238#### PermissionRequest 輸入

1239 

1240PermissionRequest hooks 接收 `tool_name` 和 `tool_input` 欄位,如 PreToolUse hooks,但沒有 `tool_use_id`。可選的 `permission_suggestions` 陣列包含使用者通常在權限對話框中看到的「總是允許」選項。區別在於 hook 何時觸發:PermissionRequest hooks 在權限對話框即將向使用者顯示時執行,而 PreToolUse hooks 在工具執行前執行,無論權限狀態如何。

1241 

1242```json theme={null}

1243{

1244 "session_id": "abc123",

1245 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1246 "cwd": "/Users/...",

1247 "permission_mode": "default",

1248 "hook_event_name": "PermissionRequest",

1249 "tool_name": "Bash",

1250 "tool_input": {

1251 "command": "rm -rf node_modules",

1252 "description": "Remove node_modules directory"

1253 },

1254 "permission_suggestions": [

1255 {

1256 "type": "addRules",

1257 "rules": [{ "toolName": "Bash", "ruleContent": "rm -rf node_modules" }],

1258 "behavior": "allow",

1259 "destination": "localSettings"

1260 }

1261 ]

1262}

1263```

1264 

1265#### PermissionRequest 決定控制

1266 

1267`PermissionRequest` hooks 可以允許或拒絕權限請求。除了所有 hooks 可用的 [JSON 輸出欄位](#json-output) 外,您的 hook 指令碼可以返回一個 `decision` 物件,其中包含這些事件特定欄位:

1268 

1269| 欄位 | 描述 |

1270| :------------------- | :------------------------------------------------------------------------------------------------------------------ |

1271| `behavior` | `"allow"` 授予權限,`"deny"` 拒絕它。[拒絕和詢問規則](/zh-TW/permissions#manage-permissions) 仍然適用,所以返回 `"allow"` 的 hook 不會覆蓋匹配的拒絕規則 |

1272| `updatedInput` | 僅適用於 `"allow"`:在執行前修改工具的輸入參數。替換整個輸入物件,因此包括未修改的欄位以及修改後的欄位。修改後的輸入會重新評估拒絕和詢問規則 |

1273| `updatedPermissions` | 僅適用於 `"allow"`:應用的 [權限更新項目](#permission-update-entries) 陣列,例如新增允許規則或變更工作階段權限模式 |

1274| `message` | 僅適用於 `"deny"`:告訴 Claude 為什麼權限被拒絕 |

1275| `interrupt` | 僅適用於 `"deny"`:如果為 `true`,停止 Claude |

1276 

1277```json theme={null}

1278{

1279 "hookSpecificOutput": {

1280 "hookEventName": "PermissionRequest",

1281 "decision": {

1282 "behavior": "allow",

1283 "updatedInput": {

1284 "command": "npm run lint"

1285 }

1286 }

1287 }

1288}

1289```

1290 

1291#### 權限更新項目

1292 

1293`updatedPermissions` 輸出欄位和 [`permission_suggestions` 輸入欄位](#permissionrequest-input) 都使用相同的項目物件陣列。每個項目都有一個 `type` 決定其他欄位,以及一個 `destination` 控制變更寫入位置。

1294 

1295| `type` | 欄位 | 效果 |

1296| :------------------ | :------------------------------- | :------------------------------------------------------------------------------------------------------------------- |

1297| `addRules` | `rules`、`behavior`、`destination` | 新增權限規則。`rules` 是 `{toolName, ruleContent?}` 物件的陣列。省略 `ruleContent` 以匹配整個工具。`behavior` 是 `"allow"`、`"deny"` 或 `"ask"` |

1298| `replaceRules` | `rules`、`behavior`、`destination` | 用提供的 `rules` 替換 `destination` 處給定 `behavior` 的所有規則 |

1299| `removeRules` | `rules`、`behavior`、`destination` | 移除匹配的給定 `behavior` 的規則 |

1300| `setMode` | `mode`、`destination` | 變更權限模式。有效模式為 `default`、`acceptEdits`、`dontAsk`、`bypassPermissions` 和 `plan` |

1301| `addDirectories` | `directories`、`destination` | 新增工作目錄。`directories` 是路徑字串的陣列 |

1302| `removeDirectories` | `directories`、`destination` | 移除工作目錄 |

1303 

1304<Note>

1305 `setMode` 與 `bypassPermissions` 僅在工作階段已經啟用繞過模式時生效:`--dangerously-skip-permissions`、`--permission-mode bypassPermissions`、`--allow-dangerously-skip-permissions` 或 `permissions.defaultMode: "bypassPermissions"` 在設定中,且模式未被 [`permissions.disableBypassPermissionsMode`](/zh-TW/permissions#managed-settings) 停用。否則更新是無操作。`bypassPermissions` 無論 `destination` 如何都永遠不會被持久化為 `defaultMode`。

1306</Note>

1307 

1308每個項目上的 `destination` 欄位決定變更是保留在記憶體中還是持久化到設定檔。

1309 

1310| `destination` | 寫入 |

1311| :---------------- | :---------------------------- |

1312| `session` | 僅在記憶體中,工作階段結束時丟棄 |

1313| `localSettings` | `.claude/settings.local.json` |

1314| `projectSettings` | `.claude/settings.json` |

1315| `userSettings` | `~/.claude/settings.json` |

1316 

1317Hook 可以回顯它接收的 `permission_suggestions` 之一作為其自己的 `updatedPermissions` 輸出,這等同於使用者在對話框中選擇該「總是允許」選項。

1318 

1319### PostToolUse

1320 

1321在工具成功完成後立即執行。

1322 

1323匹配工具名稱,與 PreToolUse 相同的值。

1324 

1325#### PostToolUse 輸入

1326 

1327`PostToolUse` hooks 在工具已經成功執行後觸發。輸入包括 `tool_input`(發送給工具的參數)和 `tool_response`(它返回的結果)。兩者的確切架構取決於工具。

1328 

1329```json theme={null}

1330{

1331 "session_id": "abc123",

1332 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1333 "cwd": "/Users/...",

1334 "permission_mode": "default",

1335 "hook_event_name": "PostToolUse",

1336 "tool_name": "Write",

1337 "tool_input": {

1338 "file_path": "/path/to/file.txt",

1339 "content": "file content"

1340 },

1341 "tool_response": {

1342 "filePath": "/path/to/file.txt",

1343 "success": true

1344 },

1345 "tool_use_id": "toolu_01ABC123...",

1346 "duration_ms": 12

1347}

1348```

1349 

1350| 欄位 | 描述 |

1351| :------------ | :--------------------------------------------- |

1352| `duration_ms` | 可選。工具執行時間(毫秒)。不包括權限提示和 PreToolUse hooks 中花費的時間 |

1353 

1354#### PostToolUse 決定控制

1355 

1356`PostToolUse` hooks 可以在工具執行後向 Claude 提供反饋。除了所有 hooks 可用的 [JSON 輸出欄位](#json-output) 外,您的 hook 指令碼可以返回這些事件特定欄位:

1357 

1358| 欄位 | 描述 |

1359| :--------------------- | :----------------------------------------------------------------------------- |

1360| `decision` | `"block"` 提示 Claude 使用 `reason`。省略以允許操作進行 |

1361| `reason` | 當 `decision` 為 `"block"` 時向 Claude 顯示的解釋 |

1362| `additionalContext` | 新增到 Claude 上下文的字串,與工具結果一起。請參閱 [為 Claude 新增上下文](#add-context-for-claude) |

1363| `updatedToolOutput` | 在將工具的輸出發送給 Claude 之前,用提供的值替換它。該值必須符合工具的輸出形狀 |

1364| `updatedMCPToolOutput` | 僅適用於 [MCP 工具](#match-mcp-tools):用提供的值替換工具的輸出。優先使用 `updatedToolOutput`,它適用於所有工具 |

1365 

1366下面的範例替換 `Bash` 呼叫的輸出。替換值符合 `Bash` 工具的輸出形狀:

1367 

1368```json theme={null}

1369{

1370 "hookSpecificOutput": {

1371 "hookEventName": "PostToolUse",

1372 "additionalContext": "Additional information for Claude",

1373 "updatedToolOutput": {

1374 "stdout": "[redacted]",

1375 "stderr": "",

1376 "interrupted": false,

1377 "isImage": false

1378 }

1379 }

1380}

1381```

1382 

1383<Warning>

1384 `updatedToolOutput` 僅改變 Claude 看到的內容。工具已經在 hook 觸發時執行,因此任何寫入的檔案、執行的命令或發送的網路請求都已生效。遙測(如 OpenTelemetry 工具跨度和分析事件)也會在 hook 執行前捕獲原始輸出。要在執行前防止或修改工具呼叫,請改用 [PreToolUse](#pretooluse) hook。

1385 

1386 替換值必須符合工具的輸出形狀。內建工具返回結構化物件而不是純字串。例如,`Bash` 返回一個具有 `stdout`、`stderr`、`interrupted` 和 `isImage` 欄位的物件。對於內建工具,不符合工具輸出架構的值會被忽略,並使用原始輸出。MCP 工具輸出通過而不進行架構驗證。去除 Claude 需要的錯誤詳細資訊可能會導致它在錯誤的假設下進行。

1387</Warning>

1388 

1389### PostToolUseFailure

1390 

1391當工具執行失敗時執行。此事件針對拋出錯誤或返回失敗結果的工具呼叫觸發。使用此項來記錄失敗、發送警報或向 Claude 提供更正反饋。

1392 

1393匹配工具名稱,與 PreToolUse 相同的值。

1394 

1395#### PostToolUseFailure 輸入

1396 

1397PostToolUseFailure hooks 接收與 PostToolUse 相同的 `tool_name` 和 `tool_input` 欄位,以及作為頂層欄位的錯誤資訊:

1398 

1399```json theme={null}

1400{

1401 "session_id": "abc123",

1402 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1403 "cwd": "/Users/...",

1404 "permission_mode": "default",

1405 "hook_event_name": "PostToolUseFailure",

1406 "tool_name": "Bash",

1407 "tool_input": {

1408 "command": "npm test",

1409 "description": "Run test suite"

1410 },

1411 "tool_use_id": "toolu_01ABC123...",

1412 "error": "Command exited with non-zero status code 1",

1413 "is_interrupt": false,

1414 "duration_ms": 4187

1415}

1416```

1417 

1418| 欄位 | 描述 |

1419| :------------- | :--------------------------------------------- |

1420| `error` | 描述出錯的字串 |

1421| `is_interrupt` | 可選的布林值,指示失敗是否由使用者中斷引起 |

1422| `duration_ms` | 可選。工具執行時間(毫秒)。不包括權限提示和 PreToolUse hooks 中花費的時間 |

1423 

1424#### PostToolUseFailure 決定控制

1425 

1426`PostToolUseFailure` hooks 可以在工具失敗後向 Claude 提供上下文。除了所有 hooks 可用的 [JSON 輸出欄位](#json-output) 外,您的 hook 指令碼可以返回這些事件特定欄位:

1427 

1428| 欄位 | 描述 |

1429| :------------------ | :-------------------------------------------------------------------- |

1430| `additionalContext` | 新增到 Claude 上下文的字串,與錯誤一起。請參閱 [為 Claude 新增上下文](#add-context-for-claude) |

1431 

1432```json theme={null}

1433{

1434 "hookSpecificOutput": {

1435 "hookEventName": "PostToolUseFailure",

1436 "additionalContext": "Additional information about the failure for Claude"

1437 }

1438}

1439```

1440 

1441### PostToolBatch

1442 

1443在批次中的每個工具呼叫都已解決後執行一次,在 Claude Code 向模型發送下一個請求之前。`PostToolUse` 每個工具執行一次,這意味著當 Claude 進行平行工具呼叫時它並發執行。`PostToolBatch` 恰好執行一次,包含完整批次,因此它是注入取決於執行的工具集而不是任何單一工具的上下文的正確位置。此事件沒有匹配器。

1444 

1445#### PostToolBatch 輸入

1446 

1447除了 [通用輸入欄位](#common-input-fields) 外,PostToolBatch hooks 還接收 `tool_calls`,一個描述批次中每個工具呼叫的陣列:

1448 

1449```json theme={null}

1450{

1451 "session_id": "abc123",

1452 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1453 "cwd": "/Users/...",

1454 "permission_mode": "default",

1455 "hook_event_name": "PostToolBatch",

1456 "tool_calls": [

1457 {

1458 "tool_name": "Read",

1459 "tool_input": {"file_path": "/.../ledger/accounts.py"},

1460 "tool_use_id": "toolu_01...",

1461 "tool_response": " 1\tfrom __future__ import annotations\n 2\t..."

1462 },

1463 {

1464 "tool_name": "Read",

1465 "tool_input": {"file_path": "/.../ledger/transactions.py"},

1466 "tool_use_id": "toolu_02...",

1467 "tool_response": " 1\tfrom __future__ import annotations\n 2\t..."

1468 }

1469 ]

1470}

1471```

1472 

1473`tool_response` 包含與模型在相應 `tool_result` 塊中接收的內容相同的內容。該值是序列化的字串或內容塊陣列,完全如工具發出的那樣。對於 `Read`,這意味著行號前綴的文字而不是原始檔案內容。回應可能很大,因此僅解析您需要的欄位。

1474 

1475<Note>

1476 `tool_response` 形狀與 `PostToolUse` 的不同。`PostToolUse` 傳遞工具的結構化 `Output` 物件,例如 `Write` 的 `{filePath: "...", success: true}`;`PostToolBatch` 傳遞序列化的 `tool_result` 內容模型看到的。

1477</Note>

1478 

1479#### PostToolBatch 決定控制

1480 

1481`PostToolBatch` hooks 可以為 Claude 注入上下文。除了所有 hooks 可用的 [JSON 輸出欄位](#json-output) 外,您的 hook 指令碼可以返回這些事件特定欄位:

1482 

1483| 欄位 | 描述 |

1484| :------------------ | :------------------------------------------------------------------------------------------------------ |

1485| `additionalContext` | 在下一個模型呼叫之前注入一次的上下文字串。請參閱 [為 Claude 新增上下文](#add-context-for-claude) 以了解傳遞詳細資訊、要放入其中的內容,以及恢復的工作階段如何處理過去的值 |

1486 

1487```json theme={null}

1488{

1489 "hookSpecificOutput": {

1490 "hookEventName": "PostToolBatch",

1491 "additionalContext": "These files are part of the ledger module. Run pytest before marking the task complete."

1492 }

1493}

1494```

1495 

1496<Note>

1497 注入的 `additionalContext` 被持久化到工作階段成績單。在 `--continue` 或 `--resume` 時,保存的文字從磁碟重新播放,hook 不會針對過去的轉向重新執行。優先選擇靜態上下文,例如慣例或檔案類型指導,而不是動態值,例如時間戳或目前提交 SHA,因為這些在恢復時變得陳舊。

1498 

1499 將上下文框架為事實資訊而不是命令式系統指令。寫成帶外系統命令的文字可以觸發 Claude 的提示注入防禦,這會將注入呈現給使用者而不是對其採取行動。

1500</Note>

1501 

1502返回 `decision: "block"` 或 `continue: false` 在下一個模型呼叫之前停止代理迴圈。

1503 

1504### PermissionDenied

1505 

1506當 [自動模式](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode) 分類器拒絕工具呼叫時執行。此 hook 僅在自動模式中觸發:當您手動拒絕權限對話框、當 `PreToolUse` hook 阻止呼叫或當 `deny` 規則匹配時,它不執行。使用它來記錄分類器拒絕、調整配置或告訴模型它可能重試工具呼叫。

1507 

1508匹配工具名稱,與 PreToolUse 相同的值。

1509 

1510#### PermissionDenied 輸入

1511 

1512除了 [通用輸入欄位](#common-input-fields) 外,PermissionDenied hooks 還接收 `tool_name`、`tool_input`、`tool_use_id` 和 `reason`。

1513 

1514```json theme={null}

1515{

1516 "session_id": "abc123",

1517 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1518 "cwd": "/Users/...",

1519 "permission_mode": "auto",

1520 "hook_event_name": "PermissionDenied",

1521 "tool_name": "Bash",

1522 "tool_input": {

1523 "command": "rm -rf /tmp/build",

1524 "description": "Clean build directory"

1525 },

1526 "tool_use_id": "toolu_01ABC123...",

1527 "reason": "Auto mode denied: command targets a path outside the project"

1528}

1529```

1530 

1531| 欄位 | 描述 |

1532| :------- | :-------------- |

1533| `reason` | 分類器拒絕工具呼叫的原因的解釋 |

1534 

1535#### PermissionDenied 決定控制

1536 

1537PermissionDenied hooks 可以告訴模型它可能重試被拒絕的工具呼叫。返回一個 JSON 物件,其中 `hookSpecificOutput.retry` 設定為 `true`:

1538 

1539```json theme={null}

1540{

1541 "hookSpecificOutput": {

1542 "hookEventName": "PermissionDenied",

1543 "retry": true

1544 }

1545}

1546```

1547 

1548當 `retry` 為 `true` 時,Claude Code 向對話新增一條訊息,告訴模型它可能重試工具呼叫。拒絕本身不被反轉。如果您的 hook 不返回 JSON,或返回 `retry: false`,拒絕成立,模型接收原始拒絕訊息。

1549 

1550### Notification

1551 

1552當 Claude Code 發送通知時執行。匹配通知類型:`permission_prompt`、`idle_prompt`、`auth_success`、`elicitation_dialog`、`elicitation_complete`、`elicitation_response`。省略匹配器以針對所有通知類型執行 hooks。

1553 

1554使用單獨的匹配器根據通知類型執行不同的處理程式。此配置在 Claude 需要權限批准時觸發權限特定的警報指令碼,在 Claude 閒置時觸發不同的通知:

1555 

1556```json theme={null}

1557{

1558 "hooks": {

1559 "Notification": [

1560 {

1561 "matcher": "permission_prompt",

1562 "hooks": [

1563 {

1564 "type": "command",

1565 "command": "/path/to/permission-alert.sh"

1566 }

1567 ]

1568 },

1569 {

1570 "matcher": "idle_prompt",

1571 "hooks": [

1572 {

1573 "type": "command",

1574 "command": "/path/to/idle-notification.sh"

1575 }

1576 ]

1577 }

1578 ]

1579 }

1580}

1581```

1582 

1583#### Notification 輸入

1584 

1585除了 [通用輸入欄位](#common-input-fields) 外,Notification hooks 還接收包含通知文字的 `message`、可選的 `title` 和指示哪個類型觸發的 `notification_type`。

1586 

1587```json theme={null}

1588{

1589 "session_id": "abc123",

1590 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1591 "cwd": "/Users/...",

1592 "hook_event_name": "Notification",

1593 "message": "Claude needs your permission to use Bash",

1594 "title": "Permission needed",

1595 "notification_type": "permission_prompt"

1596}

1597```

1598 

1599Notification hooks 無法阻止或修改通知。它們用於副作用,例如將通知轉發到外部服務。[通用 JSON 輸出欄位](#json-output)(例如 `systemMessage`)適用。

1600 

1601### SubagentStart

1602 

1603當通過 Agent 工具生成 Claude Code subagent 時執行。支援匹配器以按代理類型名稱篩選(內建代理,如 `general-purpose`、`Explore`、`Plan` 或來自 `.claude/agents/` 的自訂代理名稱)。

1604 

1605#### SubagentStart 輸入

1606 

1607除了 [通用輸入欄位](#common-input-fields) 外,SubagentStart hooks 還接收 `agent_id`(subagent 的唯一識別碼)和 `agent_type`(代理名稱,內建代理,如 `"general-purpose"`、`"Explore"`、`"Plan"` 或自訂代理名稱)。

1608 

1609```json theme={null}

1610{

1611 "session_id": "abc123",

1612 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1613 "cwd": "/Users/...",

1614 "hook_event_name": "SubagentStart",

1615 "agent_id": "agent-abc123",

1616 "agent_type": "Explore"

1617}

1618```

1619 

1620SubagentStart hooks 無法阻止 subagent 建立,但它們可以將上下文注入到 subagent 中。除了所有 hooks 可用的 [JSON 輸出欄位](#json-output) 外,您可以返回:

1621 

1622| 欄位 | 描述 |

1623| :------------------ | :----------------------------------------------------------------------------- |

1624| `additionalContext` | 新增到 subagent 上下文開始處的字串,在其第一個提示之前。請參閱 [為 Claude 新增上下文](#add-context-for-claude) |

1625 

1626```json theme={null}

1627{

1628 "hookSpecificOutput": {

1629 "hookEventName": "SubagentStart",

1630 "additionalContext": "Follow security guidelines for this task"

1631 }

1632}

1633```

1634 

1635### SubagentStop

1636 

1637當 Claude Code subagent 完成回應時執行。匹配代理類型,與 SubagentStart 相同的值。

1638 

1639#### SubagentStop 輸入

1640 

1641除了 [通用輸入欄位](#common-input-fields) 外,SubagentStop hooks 還接收 `stop_hook_active`、`agent_id`、`agent_type`、`agent_transcript_path` 和 `last_assistant_message`。`agent_type` 欄位是用於匹配器篩選的值。`transcript_path` 是主工作階段的成績單,而 `agent_transcript_path` 是 subagent 自己的成績單,存儲在嵌套的 `subagents/` 資料夾中。`last_assistant_message` 欄位包含 subagent 最終回應的文字內容,因此 hooks 可以存取它而無需解析成績單檔案。

1642 

1643```json theme={null}

1644{

1645 "session_id": "abc123",

1646 "transcript_path": "~/.claude/projects/.../abc123.jsonl",

1647 "cwd": "/Users/...",

1648 "permission_mode": "default",

1649 "hook_event_name": "SubagentStop",

1650 "stop_hook_active": false,

1651 "agent_id": "def456",

1652 "agent_type": "Explore",

1653 "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl",

1654 "last_assistant_message": "Analysis complete. Found 3 potential issues..."

1655}

1656```

1657 

1658SubagentStop hooks 使用與 [Stop hooks](#stop-decision-control) 相同的決定控制格式。

1659 

1660### TaskCreated

1661 

1662當任務通過 `TaskCreate` 工具被建立時執行。使用此項來強制執行命名慣例、要求任務描述或防止某些任務被建立。

1663 

1664當 `TaskCreated` hook 以代碼 2 退出時,任務不被建立,stderr 訊息被反饋給模型作為反饋。要完全停止隊友而不是重新執行它,請返回 JSON,其中 `{"continue": false, "stopReason": "..."}`。TaskCreated hooks 不支援匹配器,在每次出現時觸發。

1665 

1666#### TaskCreated 輸入

1667 

1668除了 [通用輸入欄位](#common-input-fields) 外,TaskCreated hooks 還接收 `task_id`、`task_subject` 和可選的 `task_description`、`teammate_name` 和 `team_name`。

1669 

1670```json theme={null}

1671{

1672 "session_id": "abc123",

1673 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1674 "cwd": "/Users/...",

1675 "permission_mode": "default",

1676 "hook_event_name": "TaskCreated",

1677 "task_id": "task-001",

1678 "task_subject": "Implement user authentication",

1679 "task_description": "Add login and signup endpoints",

1680 "teammate_name": "implementer",

1681 "team_name": "my-project"

1682}

1683```

1684 

1685| 欄位 | 描述 |

1686| :----------------- | :--------------- |

1687| `task_id` | 被建立的任務的識別碼 |

1688| `task_subject` | 任務的標題 |

1689| `task_description` | 任務的詳細描述。可能不存在 |

1690| `teammate_name` | 建立任務的隊友的名稱。可能不存在 |

1691| `team_name` | 團隊的名稱。可能不存在 |

1692 

1693#### TaskCreated 決定控制

1694 

1695TaskCreated hooks 支援兩種方式來控制任務建立:

1696 

1697* **退出代碼 2**:任務不被建立,stderr 訊息被反饋給模型作為反饋。

1698* **JSON `{"continue": false, "stopReason": "..."}`**:完全停止隊友,匹配 `Stop` hook 行為。`stopReason` 向使用者顯示。

1699 

1700此範例阻止主題不遵循所需格式的任務:

1701 

1702```bash theme={null}

1703#!/bin/bash

1704INPUT=$(cat)

1705TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')

1706 

1707if [[ ! "$TASK_SUBJECT" =~ ^\[TICKET-[0-9]+\] ]]; then

1708 echo "Task subject must start with a ticket number, e.g. '[TICKET-123] Add feature'" >&2

1709 exit 2

1710fi

1711 

1712exit 0

1713```

1714 

1715### TaskCompleted

1716 

1717當任務被標記為已完成時執行。這在兩種情況下觸發:當任何代理通過 TaskUpdate 工具明確標記任務為已完成時,或當 [agent team](/zh-TW/agent-teams) 隊友完成其輪次並有進行中的任務時。使用此項來強制執行完成條件,例如通過測試或 lint 檢查,然後任務才能關閉。

1718 

1719當 `TaskCompleted` hook 以代碼 2 退出時,任務不被標記為已完成,stderr 訊息被反饋給模型作為反饋。要完全停止隊友而不是重新執行它,請返回 JSON,其中 `{"continue": false, "stopReason": "..."}`。TaskCompleted hooks 不支援匹配器,在每次出現時觸發。

1720 

1721#### TaskCompleted 輸入

1722 

1723除了 [通用輸入欄位](#common-input-fields) 外,TaskCompleted hooks 還接收 `task_id`、`task_subject` 和可選的 `task_description`、`teammate_name` 和 `team_name`。

1724 

1725```json theme={null}

1726{

1727 "session_id": "abc123",

1728 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1729 "cwd": "/Users/...",

1730 "permission_mode": "default",

1731 "hook_event_name": "TaskCompleted",

1732 "task_id": "task-001",

1733 "task_subject": "Implement user authentication",

1734 "task_description": "Add login and signup endpoints",

1735 "teammate_name": "implementer",

1736 "team_name": "my-project"

1737}

1738```

1739 

1740| 欄位 | 描述 |

1741| :----------------- | :--------------- |

1742| `task_id` | 被完成的任務的識別碼 |

1743| `task_subject` | 任務的標題 |

1744| `task_description` | 任務的詳細描述。可能不存在 |

1745| `teammate_name` | 完成任務的隊友的名稱。可能不存在 |

1746| `team_name` | 團隊的名稱。可能不存在 |

1747 

1748#### TaskCompleted 決定控制

1749 

1750TaskCompleted hooks 支援兩種方式來控制任務完成:

1751 

1752* **退出代碼 2**:任務不被標記為已完成,stderr 訊息被反饋給模型作為反饋。

1753* **JSON `{"continue": false, "stopReason": "..."}`**:完全停止隊友,匹配 `Stop` hook 行為。`stopReason` 向使用者顯示。

1754 

1755此範例執行測試並在失敗時阻止任務完成:

1756 

1757```bash theme={null}

1758#!/bin/bash

1759INPUT=$(cat)

1760TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')

1761 

1762# 執行測試套件

1763if ! npm test 2>&1; then

1764 echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2

1765 exit 2

1766fi

1767 

1768exit 0

1769```

1770 

1771### Stop

1772 

1773當主 Claude Code 代理完成回應時執行。如果停止是由於使用者中斷,則不執行。API 錯誤會觸發 [StopFailure](#stopfailure)。

1774 

1775#### Stop 輸入

1776 

1777除了 [通用輸入欄位](#common-input-fields) 外,Stop hooks 還接收 `stop_hook_active` 和 `last_assistant_message`。`stop_hook_active` 欄位在 Claude Code 已經作為 stop hook 的結果繼續時為 `true`。檢查此值或處理成績單以防止 Claude Code 無限執行。`last_assistant_message` 欄位包含 Claude 最終回應的文字內容,因此 hooks 可以存取它而無需解析成績單檔案。

1778 

1779```json theme={null}

1780{

1781 "session_id": "abc123",

1782 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1783 "cwd": "/Users/...",

1784 "permission_mode": "default",

1785 "hook_event_name": "Stop",

1786 "stop_hook_active": true,

1787 "last_assistant_message": "I've completed the refactoring. Here's a summary..."

1788}

1789```

1790 

1791#### Stop 決定控制

1792 

1793`Stop` 和 `SubagentStop` hooks 可以控制 Claude 是否繼續。除了所有 hooks 可用的 [JSON 輸出欄位](#json-output) 外,您的 hook 指令碼可以返回這些事件特定欄位:

1794 

1795| 欄位 | 描述 |

1796| :--------- | :---------------------------------------------- |

1797| `decision` | `"block"` 防止 Claude 停止。省略以允許 Claude 停止 |

1798| `reason` | 當 `decision` 為 `"block"` 時必需。告訴 Claude 為什麼它應該繼續 |

1799 

1800```json theme={null}

1801{

1802 "decision": "block",

1803 "reason": "Must be provided when Claude is blocked from stopping"

1804}

1805```

1806 

1807### StopFailure

1808 

1809當轉向因 API 錯誤而結束時執行,而不是 [Stop](#stop)。輸出和退出代碼被忽略。使用此項來記錄失敗、發送警報或在 Claude 因速率限制、驗證問題或其他 API 錯誤而無法完成回應時採取恢復操作。

1810 

1811#### StopFailure 輸入

1812 

1813除了 [通用輸入欄位](#common-input-fields) 外,StopFailure hooks 還接收 `error`、可選的 `error_details` 和可選的 `last_assistant_message`。`error` 欄位識別錯誤類型,用於匹配器篩選。

1814 

1815| 欄位 | 描述 |

1816| :----------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------- |

1817| `error` | 錯誤類型:`rate_limit`、`authentication_failed`、`oauth_org_not_allowed`、`billing_error`、`invalid_request`、`server_error`、`max_output_tokens` 或 `unknown` |

1818| `error_details` | 有關錯誤的其他詳細資訊(如果可用) |

1819| `last_assistant_message` | 在對話中顯示的呈現錯誤文字。與 `Stop` 和 `SubagentStop` 不同,其中此欄位包含 Claude 的對話輸出,對於 `StopFailure`,它包含 API 錯誤字串本身,例如 `"API Error: Rate limit reached"` |

1820 

1821```json theme={null}

1822{

1823 "session_id": "abc123",

1824 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1825 "cwd": "/Users/...",

1826 "hook_event_name": "StopFailure",

1827 "error": "rate_limit",

1828 "error_details": "429 Too Many Requests",

1829 "last_assistant_message": "API Error: Rate limit reached"

1830}

1831```

1832 

1833StopFailure hooks 沒有決定控制。它們僅用於通知和記錄目的執行。

1834 

1835### TeammateIdle

1836 

1837當 [agent team](/zh-TW/agent-teams) 隊友在完成其輪次後即將閒置時執行。使用此項來在隊友停止工作之前強制執行品質閘道,例如要求通過 lint 檢查或驗證輸出檔案存在。

1838 

1839當 `TeammateIdle` hook 以代碼 2 退出時,隊友會收到 stderr 訊息作為反饋,並繼續工作而不是閒置。要完全停止隊友而不是重新執行它,請返回 JSON,其中 `{"continue": false, "stopReason": "..."}`。TeammateIdle hooks 不支援匹配器,在每次出現時觸發。

1840 

1841#### TeammateIdle 輸入

1842 

1843除了 [通用輸入欄位](#common-input-fields) 外,TeammateIdle hooks 還接收 `teammate_name` 和 `team_name`。

1844 

1845```json theme={null}

1846{

1847 "session_id": "abc123",

1848 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1849 "cwd": "/Users/...",

1850 "permission_mode": "default",

1851 "hook_event_name": "TeammateIdle",

1852 "teammate_name": "researcher",

1853 "team_name": "my-project"

1854}

1855```

1856 

1857| 欄位 | 描述 |

1858| :-------------- | :--------- |

1859| `teammate_name` | 即將閒置的隊友的名稱 |

1860| `team_name` | 團隊的名稱 |

1861 

1862#### TeammateIdle 決定控制

1863 

1864TeammateIdle hooks 支援兩種方式來控制隊友行為:

1865 

1866* **退出代碼 2**:隊友會收到 stderr 訊息作為反饋,並繼續工作而不是閒置。

1867* **JSON `{"continue": false, "stopReason": "..."}`**:完全停止隊友,匹配 `Stop` hook 行為。`stopReason` 向使用者顯示。

1868 

1869此範例在允許隊友閒置之前檢查建置成品是否存在:

1870 

1871```bash theme={null}

1872#!/bin/bash

1873 

1874if [ ! -f "./dist/output.js" ]; then

1875 echo "Build artifact missing. Run the build before stopping." >&2

1876 exit 2

1877fi

1878 

1879exit 0

1880```

1881 

1882### ConfigChange

1883 

1884當配置檔案在工作階段期間變更時執行。使用此項來稽核設定變更、強制執行安全原則或阻止對配置檔案的未授權修改。

1885 

1886ConfigChange hooks 針對設定檔、受管理的原則設定和 skill 檔案的變更觸發。輸入中的 `source` 欄位告訴您哪種類型的配置變更,可選的 `file_path` 欄位提供變更檔案的路徑。

1887 

1888匹配器篩選配置來源:

1889 

1890| 匹配器 | 何時觸發 |

1891| :----------------- | :------------------------------- |

1892| `user_settings` | `~/.claude/settings.json` 變更 |

1893| `project_settings` | `.claude/settings.json` 變更 |

1894| `local_settings` | `.claude/settings.local.json` 變更 |

1895| `policy_settings` | 受管理的原則設定變更 |

1896| `skills` | `.claude/skills/` 中的 skill 檔案變更 |

1897 

1898此範例記錄所有配置變更以進行安全稽核:

1899 

1900```json theme={null}

1901{

1902 "hooks": {

1903 "ConfigChange": [

1904 {

1905 "hooks": [

1906 {

1907 "type": "command",

1908 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/audit-config-change.sh"

1909 }

1910 ]

1911 }

1912 ]

1913 }

1914}

1915```

1916 

1917#### ConfigChange 輸入

1918 

1919除了 [通用輸入欄位](#common-input-fields) 外,ConfigChange hooks 還接收 `source` 和可選的 `file_path`。`source` 欄位指示哪種配置類型變更,`file_path` 提供被修改的特定檔案的路徑。

1920 

1921```json theme={null}

1922{

1923 "session_id": "abc123",

1924 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1925 "cwd": "/Users/...",

1926 "hook_event_name": "ConfigChange",

1927 "source": "project_settings",

1928 "file_path": "/Users/.../my-project/.claude/settings.json"

1929}

1930```

1931 

1932#### ConfigChange 決定控制

1933 

1934ConfigChange hooks 可以阻止配置變更生效。使用退出代碼 2 或 JSON `decision` 來防止變更。被阻止時,新設定不會應用於執行中的工作階段。

1935 

1936| 欄位 | 描述 |

1937| :--------- | :---------------------------------- |

1938| `decision` | `"block"` 防止配置變更被應用。省略以允許變更 |

1939| `reason` | 當 `decision` 為 `"block"` 時向使用者顯示的解釋 |

1940 

1941```json theme={null}

1942{

1943 "decision": "block",

1944 "reason": "Configuration changes to project settings require admin approval"

1945}

1946```

1947 

1948`policy_settings` 變更無法被阻止。Hooks 仍然針對 `policy_settings` 來源觸發,因此您可以使用它們進行稽核記錄,但任何阻止決定都會被忽略。這確保企業管理的設定始終生效。

1949 

1950### CwdChanged

1951 

1952當工作目錄在工作階段期間變更時執行,例如當 Claude 執行 `cd` 命令時。使用此項來對目錄變更做出反應:重新載入環境變數、啟動專案特定的工具鏈或自動執行設定指令碼。與 [FileChanged](#filechanged) 配對,用於 [direnv](https://direnv.net/) 等管理每個目錄環境的工具。

1953 

1954CwdChanged hooks 可以存取 `CLAUDE_ENV_FILE`。寫入該檔案的變數會持久化到工作階段的後續 Bash 命令中,就像在 [SessionStart hooks](#persist-environment-variables) 中一樣。

1955 

1956CwdChanged 不支援匹配器,在每次目錄變更時觸發。

1957 

1958#### CwdChanged 輸入

1959 

1960除了 [通用輸入欄位](#common-input-fields) 外,CwdChanged hooks 還接收 `old_cwd` 和 `new_cwd`。

1961 

1962```json theme={null}

1963{

1964 "session_id": "abc123",

1965 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",

1966 "cwd": "/Users/my-project/src",

1967 "hook_event_name": "CwdChanged",

1968 "old_cwd": "/Users/my-project",

1969 "new_cwd": "/Users/my-project/src"

1970}

1971```

1972 

1973#### CwdChanged 輸出

1974 

1975除了所有 hooks 可用的 [JSON 輸出欄位](#json-output) 外,CwdChanged hooks 還可以返回 `watchPaths` 來動態設定 [FileChanged](#filechanged) 監視的檔案路徑:

1976 

1977| 欄位 | 描述 |

1978| :----------- | :--------------------------------------------------------------------- |

1979| `watchPaths` | 絕對路徑的陣列。替換目前的動態監視清單(來自您 `matcher` 配置的路徑始終被監視)。返回空陣列會清除動態清單,這在進入新目錄時很典型 |

1980 

1981CwdChanged hooks 沒有決定控制。它們無法阻止目錄變更。

1982 

1983### FileChanged

1984 

1985當監視的檔案在磁碟上變更時執行。適用於在專案配置檔案被修改時重新載入環境變數。

1986 

1987`matcher` 對於此事件有兩個角色:

1988 

1989* **建立監視清單**:值在 `|` 上分割,每個段被註冊為工作目錄中的檔案名稱,因此 `".envrc|.env"` 監視恰好這兩個檔案。正規表達式模式在這裡沒有用:像 `^\.env` 這樣的值會監視一個字面上名為 `^\.env` 的檔案。

1990* **篩選哪些 hooks 執行**:當監視的檔案變更時,相同的值使用標準 [匹配器規則](#matcher-patterns) 針對變更檔案的基本名稱篩選哪些 hook 群組執行。

1991 

1992FileChanged hooks 可以存取 `CLAUDE_ENV_FILE`。寫入該檔案的變數會持久化到工作階段的後續 Bash 命令中,就像在 [SessionStart hooks](#persist-environment-variables) 中一樣。

1993 

1994#### FileChanged 輸入

1995 

1996除了 [通用輸入欄位](#common-input-fields) 外,FileChanged hooks 還接收 `file_path` 和 `event`。

1997 

1998| 欄位 | 描述 |

1999| :---------- | :-------------------------------------------------------- |

2000| `file_path` | 變更檔案的絕對路徑 |

2001| `event` | 發生的情況:`"change"`(檔案被修改)、`"add"`(檔案被建立)或 `"unlink"`(檔案被刪除) |

2002 

2003```json theme={null}

2004{

2005 "session_id": "abc123",

2006 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",

2007 "cwd": "/Users/my-project",

2008 "hook_event_name": "FileChanged",

2009 "file_path": "/Users/my-project/.envrc",

2010 "event": "change"

2011}

2012```

2013 

2014#### FileChanged 輸出

2015 

2016除了所有 hooks 可用的 [JSON 輸出欄位](#json-output) 外,FileChanged hooks 還可以返回 `watchPaths` 來動態更新監視的檔案路徑:

2017 

2018| 欄位 | 描述 |

2019| :----------- | :-------------------------------------------------------------------------------- |

2020| `watchPaths` | 絕對路徑的陣列。替換目前的動態監視清單(來自您 `matcher` 配置的路徑始終被監視)。當您的 hook 指令碼根據變更的檔案發現要監視的其他檔案時,使用此項 |

2021 

2022FileChanged hooks 沒有決定控制。它們無法阻止檔案變更的發生。

2023 

2024### WorktreeCreate

2025 

2026當您執行 `claude --worktree` 或 [subagent 使用 `isolation: "worktree"`](/zh-TW/sub-agents#choose-the-subagent-scope) 時,Claude Code 使用 `git worktree` 建立隔離的工作副本。如果您配置 WorktreeCreate hook,它會替換預設的 git 行為,讓您使用不同的版本控制系統,如 SVN、Perforce 或 Mercurial。

2027 

2028因為 hook 完全替換預設行為,[`.worktreeinclude`](/zh-TW/worktrees#copy-gitignored-files-into-worktrees) 不被處理。如果您需要將本機配置檔案(如 `.env`)複製到新 worktree,請在您的 hook 指令碼內執行。

2029 

2030Hook 必須返回建立的 worktree 目錄的絕對路徑。Claude Code 使用此路徑作為隔離工作階段的工作目錄。命令 hooks 在 stdout 上列印它;HTTP hooks 通過 `hookSpecificOutput.worktreePath` 返回它。

2031 

2032此範例建立 SVN 工作副本並列印路徑供 Claude Code 使用。將儲存庫 URL 替換為您自己的:

2033 

2034```json theme={null}

2035{

2036 "hooks": {

2037 "WorktreeCreate": [

2038 {

2039 "hooks": [

2040 {

2041 "type": "command",

2042 "command": "bash -c 'NAME=$(jq -r .name); DIR=\"$HOME/.claude/worktrees/$NAME\"; svn checkout https://svn.example.com/repo/trunk \"$DIR\" >&2 && echo \"$DIR\"'"

2043 }

2044 ]

2045 }

2046 ]

2047 }

2048}

2049```

2050 

2051Hook 從 stdin 上的 JSON 輸入讀取 worktree `name`,將新副本簽出到新目錄,並列印目錄路徑。最後一行的 `echo` 是 Claude Code 讀取的 worktree 路徑。將任何其他輸出重定向到 stderr,以免干擾路徑。

2052 

2053#### WorktreeCreate 輸入

2054 

2055除了 [通用輸入欄位](#common-input-fields) 外,WorktreeCreate hooks 還接收 `name` 欄位。這是新 worktree 的 slug 識別碼,由使用者指定或自動生成(例如 `bold-oak-a3f2`)。

2056 

2057```json theme={null}

2058{

2059 "session_id": "abc123",

2060 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

2061 "cwd": "/Users/...",

2062 "hook_event_name": "WorktreeCreate",

2063 "name": "feature-auth"

2064}

2065```

2066 

2067#### WorktreeCreate 輸出

2068 

2069WorktreeCreate hooks 不使用標準的允許/阻止決定模型。相反,hook 的成功或失敗決定結果。Hook 必須返回建立的 worktree 目錄的絕對路徑:

2070 

2071* **命令 hooks**(`type: "command"`):在 stdout 上列印路徑。

2072* **HTTP hooks**(`type: "http"`):在回應正文中返回 `{ "hookSpecificOutput": { "hookEventName": "WorktreeCreate", "worktreePath": "/absolute/path" } }`。

2073 

2074如果 hook 失敗或不產生路徑,worktree 建立失敗並出現錯誤。

2075 

2076### WorktreeRemove

2077 

2078[WorktreeCreate](#worktreecreate) 的清理對應項。此 hook 在 worktree 被移除時觸發,要麼當您退出 `--worktree` 工作階段並選擇移除它時,要麼當具有 `isolation: "worktree"` 的 subagent 完成時。對於基於 git 的 worktrees,Claude 使用 `git worktree remove` 自動處理清理。如果您為非 git 版本控制系統配置了 WorktreeCreate hook,請將其與 WorktreeRemove hook 配對以處理清理。沒有它,worktree 目錄會留在磁碟上。

2079 

2080Claude Code 將 WorktreeCreate 返回的路徑作為 `worktree_path` 在 hook 輸入中傳遞。此範例讀取該路徑並移除目錄:

2081 

2082```json theme={null}

2083{

2084 "hooks": {

2085 "WorktreeRemove": [

2086 {

2087 "hooks": [

2088 {

2089 "type": "command",

2090 "command": "bash -c 'jq -r .worktree_path | xargs rm -rf'"

2091 }

2092 ]

2093 }

2094 ]

2095 }

2096}

2097```

2098 

2099#### WorktreeRemove 輸入

2100 

2101除了 [通用輸入欄位](#common-input-fields) 外,WorktreeRemove hooks 還接收 `worktree_path` 欄位,這是被移除的 worktree 的絕對路徑。

2102 

2103```json theme={null}

2104{

2105 "session_id": "abc123",

2106 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

2107 "cwd": "/Users/...",

2108 "hook_event_name": "WorktreeRemove",

2109 "worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth"

2110}

2111```

2112 

2113WorktreeRemove hooks 沒有決定控制。它們無法阻止 worktree 移除,但可以執行清理任務,如移除版本控制狀態或存檔變更。Hook 失敗僅在偵錯模式中記錄。

2114 

2115### PreCompact

2116 

2117在 Claude Code 即將執行壓縮操作之前執行。

2118 

2119匹配器值指示壓縮是手動觸發還是自動觸發:

2120 

2121| 匹配器 | 何時觸發 |

2122| :------- | :----------- |

2123| `manual` | `/compact` |

2124| `auto` | 當上下文視窗滿時自動壓縮 |

2125 

2126退出代碼 2 以阻止壓縮。對於手動 `/compact`,stderr 訊息向使用者顯示。您也可以通過返回帶有 `"decision": "block"` 的 JSON 來阻止。

2127 

2128阻止自動壓縮有不同的效果,取決於何時觸發。如果壓縮在上下文限制之前主動觸發,Claude Code 會跳過它,對話繼續未壓縮。如果壓縮被觸發以從已由 API 返回的上下文限制錯誤恢復,基礎錯誤會浮出並且目前請求失敗。

2129 

2130#### PreCompact 輸入

2131 

2132除了 [通用輸入欄位](#common-input-fields) 外,PreCompact hooks 還接收 `trigger` 和 `custom_instructions`。對於 `manual`,`custom_instructions` 包含使用者傳遞到 `/compact` 的內容。對於 `auto`,`custom_instructions` 為空。

2133 

2134```json theme={null}

2135{

2136 "session_id": "abc123",

2137 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

2138 "cwd": "/Users/...",

2139 "hook_event_name": "PreCompact",

2140 "trigger": "manual",

2141 "custom_instructions": ""

2142}

2143```

2144 

2145### PostCompact

2146 

2147在 Claude Code 完成壓縮操作後執行。使用此事件來對新的壓縮狀態做出反應,例如記錄生成的摘要或更新外部狀態。

2148 

2149與 `PreCompact` 相同的匹配器值適用:

2150 

2151| 匹配器 | 何時觸發 |

2152| :------- | :------------- |

2153| `manual` | 在 `/compact` 後 |

2154| `auto` | 在上下文視窗滿時自動壓縮後 |

2155 

2156#### PostCompact 輸入

2157 

2158除了 [通用輸入欄位](#common-input-fields) 外,PostCompact hooks 還接收 `trigger` 和 `compact_summary`。`compact_summary` 欄位包含壓縮操作生成的對話摘要。

2159 

2160```json theme={null}

2161{

2162 "session_id": "abc123",

2163 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

2164 "cwd": "/Users/...",

2165 "hook_event_name": "PostCompact",

2166 "trigger": "manual",

2167 "compact_summary": "Summary of the compacted conversation..."

2168}

2169```

2170 

2171PostCompact hooks 沒有決定控制。它們無法影響壓縮結果,但可以執行後續任務。

2172 

2173### SessionEnd

2174 

2175當 Claude Code 工作階段結束時執行。適用於清理任務、記錄工作階段統計資訊或儲存工作階段狀態。支援匹配器以按退出原因篩選。

2176 

2177輸入中的 `reason` 欄位指示工作階段為何結束:

2178 

2179| 原因 | 描述 |

2180| :---------------------------- | :--------------------- |

2181| `clear` | 使用 `/clear` 命令清除工作階段 |

2182| `resume` | 通過互動式 `/resume` 切換工作階段 |

2183| `logout` | 使用者登出 |

2184| `prompt_input_exit` | 使用者在提示輸入可見時退出 |

2185| `bypass_permissions_disabled` | 繞過權限模式被停用 |

2186| `other` | 其他退出原因 |

2187 

2188#### SessionEnd 輸入

2189 

2190除了 [通用輸入欄位](#common-input-fields) 外,SessionEnd hooks 還接收指示工作階段為何結束的 `reason` 欄位。有關所有值,請參閱上面的 [原因表](#sessionend)。

2191 

2192```json theme={null}

2193{

2194 "session_id": "abc123",

2195 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

2196 "cwd": "/Users/...",

2197 "hook_event_name": "SessionEnd",

2198 "reason": "other"

2199}

2200```

2201 

2202SessionEnd hooks 沒有決定控制。它們無法阻止工作階段終止,但可以執行清理任務。

2203 

2204SessionEnd hooks 的預設逾時為 1.5 秒。這適用於工作階段退出、`/clear` 和通過互動式 `/resume` 切換工作階段。如果 hook 需要更多時間,請在 hook 配置中設定每個 hook 的 `timeout`。整體預算會自動提高到設定檔中配置的最高每個 hook 逾時,最高 60 秒。在外掛程式提供的 hooks 上設定的逾時不會提高預算。要明確覆蓋預算,請在毫秒中設定 `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` 環境變數。

2205 

2206```bash theme={null}

2207CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude

2208```

2209 

2210### Elicitation

2211 

2212當 MCP 伺服器在任務中途請求使用者輸入時執行。預設情況下,Claude Code 顯示互動式對話框供使用者回應。Hooks 可以攔截此請求並以程式方式回應,完全跳過對話框。

2213 

2214匹配器欄位與 MCP 伺服器名稱匹配。

2215 

2216#### Elicitation 輸入

2217 

2218除了 [通用輸入欄位](#common-input-fields) 外,Elicitation hooks 還接收 `mcp_server_name`、`message` 和可選的 `mode`、`url`、`elicitation_id` 和 `requested_schema` 欄位。

2219 

2220對於表單模式徵詢(最常見的情況):

2221 

2222```json theme={null}

2223{

2224 "session_id": "abc123",

2225 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

2226 "cwd": "/Users/...",

2227 "permission_mode": "default",

2228 "hook_event_name": "Elicitation",

2229 "mcp_server_name": "my-mcp-server",

2230 "message": "Please provide your credentials",

2231 "mode": "form",

2232 "requested_schema": {

2233 "type": "object",

2234 "properties": {

2235 "username": { "type": "string", "title": "Username" }

2236 }

2237 }

2238}

2239```

2240 

2241對於 URL 模式徵詢(基於瀏覽器的驗證):

2242 

2243```json theme={null}

2244{

2245 "session_id": "abc123",

2246 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

2247 "cwd": "/Users/...",

2248 "permission_mode": "default",

2249 "hook_event_name": "Elicitation",

2250 "mcp_server_name": "my-mcp-server",

2251 "message": "Please authenticate",

2252 "mode": "url",

2253 "url": "https://auth.example.com/login"

2254}

2255```

2256 

2257#### Elicitation 輸出

2258 

2259要以程式方式回應而不顯示對話框,請返回帶有 `hookSpecificOutput` 的 JSON 物件:

2260 

2261```json theme={null}

2262{

2263 "hookSpecificOutput": {

2264 "hookEventName": "Elicitation",

2265 "action": "accept",

2266 "content": {

2267 "username": "alice"

2268 }

2269 }

2270}

2271```

2272 

2273| 欄位 | 值 | 描述 |

2274| :-------- | :-------------------------- | :----------------------------------- |

2275| `action` | `accept`、`decline`、`cancel` | 是否接受、拒絕或取消請求 |

2276| `content` | 物件 | 要提交的表單欄位值。僅在 `action` 為 `accept` 時使用 |

2277 

2278退出代碼 2 拒絕徵詢並向使用者顯示 stderr。

2279 

2280### ElicitationResult

2281 

2282在使用者回應 MCP 徵詢後執行。Hooks 可以觀察、修改或阻止回應,然後將其發送回 MCP 伺服器。

2283 

2284匹配器欄位與 MCP 伺服器名稱匹配。

2285 

2286#### ElicitationResult 輸入

2287 

2288除了 [通用輸入欄位](#common-input-fields) 外,ElicitationResult hooks 還接收 `mcp_server_name`、`action` 和可選的 `mode`、`elicitation_id` 和 `content` 欄位。

2289 

2290```json theme={null}

2291{

2292 "session_id": "abc123",

2293 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

2294 "cwd": "/Users/...",

2295 "permission_mode": "default",

2296 "hook_event_name": "ElicitationResult",

2297 "mcp_server_name": "my-mcp-server",

2298 "action": "accept",

2299 "content": { "username": "alice" },

2300 "mode": "form",

2301 "elicitation_id": "elicit-123"

2302}

2303```

2304 

2305#### ElicitationResult 輸出

2306 

2307要覆蓋使用者的回應,請返回帶有 `hookSpecificOutput` 的 JSON 物件:

2308 

2309```json theme={null}

2310{

2311 "hookSpecificOutput": {

2312 "hookEventName": "ElicitationResult",

2313 "action": "decline",

2314 "content": {}

2315 }

2316}

2317```

2318 

2319| 欄位 | 值 | 描述 |

2320| :-------- | :-------------------------- | :---------------------------------- |

2321| `action` | `accept`、`decline`、`cancel` | 覆蓋使用者的操作 |

2322| `content` | 物件 | 覆蓋表單欄位值。僅在 `action` 為 `accept` 時有意義 |

2323 

2324退出代碼 2 阻止回應,將有效操作變更為 `decline`。

2325 

2326## 基於提示的 hooks

2327 

2328除了命令、HTTP 和 MCP tool hooks 外,Claude Code 還支援基於提示的 hooks(`type: "prompt"`),使用 LLM 評估是否允許或阻止操作,以及代理 hooks(`type: "agent"`),生成具有工具存取權限的代理驗證器。並非所有事件都支援每種 hook 類型。

2329 

2330支援所有五種 hook 類型(`command`、`http`、`mcp_tool`、`prompt` 和 `agent`)的事件:

2331 

2332* `PermissionRequest`

2333* `PostToolBatch`

2334* `PostToolUse`

2335* `PostToolUseFailure`

2336* `PreToolUse`

2337* `Stop`

2338* `SubagentStop`

2339* `TaskCompleted`

2340* `TaskCreated`

2341* `UserPromptExpansion`

2342* `UserPromptSubmit`

2343 

2344支援 `command`、`http` 和 `mcp_tool` hooks 但不支援 `prompt` 或 `agent` 的事件:

2345 

2346* `ConfigChange`

2347* `CwdChanged`

2348* `Elicitation`

2349* `ElicitationResult`

2350* `FileChanged`

2351* `InstructionsLoaded`

2352* `Notification`

2353* `PermissionDenied`

2354* `PostCompact`

2355* `PreCompact`

2356* `SessionEnd`

2357* `StopFailure`

2358* `SubagentStart`

2359* `TeammateIdle`

2360* `WorktreeCreate`

2361* `WorktreeRemove`

2362 

2363`SessionStart` 和 `Setup` 支援 `command` 和 `mcp_tool` hooks。它們不支援 `http`、`prompt` 或 `agent` hooks。

2364 

2365### 基於提示的 hooks 如何工作

2366 

2367基於提示的 hooks 不執行 Bash 命令,而是:

2368 

23691. 將 hook 輸入和您的提示發送到 Claude 模型,預設為 Haiku

23702. LLM 以包含決定的結構化 JSON 回應

23713. Claude Code 自動處理決定

2372 

2373### 提示 hook 配置

2374 

2375將 `type` 設定為 `"prompt"` 並提供 `prompt` 字串而不是 `command`。使用 `$ARGUMENTS` 佔位符將 hook 的 JSON 輸入資料注入到您的提示文字中。Claude Code 將組合的提示和輸入發送到快速 Claude 模型,該模型返回 JSON 決定。

2376 

2377此 `Stop` hook 詢問 LLM 在允許 Claude 完成之前是否應該停止:

2378 

2379```json theme={null}

2380{

2381 "hooks": {

2382 "Stop": [

2383 {

2384 "hooks": [

2385 {

2386 "type": "prompt",

2387 "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."

2388 }

2389 ]

2390 }

2391 ]

2392 }

2393}

2394```

2395 

2396| 欄位 | 必需 | 描述 |

2397| :-------- | :- | :------------------------------------------------------------------------------------- |

2398| `type` | 是 | 必須為 `"prompt"` |

2399| `prompt` | 是 | 要發送到 LLM 的提示文字。使用 `$ARGUMENTS` 作為 hook 輸入 JSON 的佔位符。如果 `$ARGUMENTS` 不存在,輸入 JSON 會附加到提示 |

2400| `model` | 否 | 用於評估的模型。預設為快速模型 |

2401| `timeout` | 否 | 逾時(秒)。預設值:30 |

2402 

2403### 回應架構

2404 

2405LLM 必須以包含以下內容的 JSON 回應:

2406 

2407```json theme={null}

2408{

2409 "ok": true | false,

2410 "reason": "Explanation for the decision"

2411}

2412```

2413 

2414| 欄位 | 描述 |

2415| :------- | :------------------------- |

2416| `ok` | `true` 允許操作,`false` 防止它 |

2417| `reason` | 當 `ok` 為 `false` 時必需。阻止的解釋 |

2418 

2419`ok: false` 時發生的情況取決於事件:

2420 

2421* `Stop` 和 `SubagentStop`:原因被反饋給 Claude 作為其下一個指令,轉換繼續

2422* `PreToolUse`:工具呼叫被拒絕,原因作為工具錯誤返回給 Claude,相當於命令 hook 的 `permissionDecision: "deny"`

2423* `PostToolUse`、`PostToolBatch`、`UserPromptSubmit` 和 `UserPromptExpansion`:轉換結束,原因在聊天中顯示為警告行,相當於從命令 hook 返回 `"continue": false`

2424* `PostToolUseFailure`、`TaskCreated` 和 `TaskCompleted`:原因作為工具錯誤返回給 Claude,類似於 `PreToolUse`

2425* `PermissionRequest`:`ok: false` 沒有效果。要從 hook 拒絕批准,請使用[命令 hook](#command-hook-fields)返回 `hookSpecificOutput.decision.behavior: "deny"`

2426 

2427如果您需要對任何事件進行更精細的控制,請使用[命令 hook](#command-hook-fields),其中包含[決定控制](#decision-control)中描述的每個事件欄位。

2428 

2429### 範例:多條件 Stop hook

2430 

2431此 `Stop` hook 使用詳細提示在允許 Claude 停止之前檢查三個條件。如果 `"ok"` 為 `false`,Claude 繼續工作,提供的原因作為其下一個指令。`SubagentStop` hooks 使用相同的格式來評估 [subagent](/zh-TW/sub-agents) 是否應該停止:

2432 

2433```json theme={null}

2434{

2435 "hooks": {

2436 "Stop": [

2437 {

2438 "hooks": [

2439 {

2440 "type": "prompt",

2441 "prompt": "You are evaluating whether Claude should stop working. Context: $ARGUMENTS\n\nAnalyze the conversation and determine if:\n1. All user-requested tasks are complete\n2. Any errors need to be addressed\n3. Follow-up work is needed\n\nRespond with JSON: {\"ok\": true} to allow stopping, or {\"ok\": false, \"reason\": \"your explanation\"} to continue working.",

2442 "timeout": 30

2443 }

2444 ]

2445 }

2446 ]

2447 }

2448}

2449```

2450 

2451## 基於代理的 hooks

2452 

2453<Warning>

2454 代理 hooks 是實驗性的。行為和配置可能在未來版本中變更。對於生產工作流程,建議使用[命令 hooks](#command-hook-fields)。

2455</Warning>

2456 

2457基於代理的 hooks(`type: "agent"`)類似於基於提示的 hooks,但具有多輪工具存取。代理 hook 不是單一 LLM 呼叫,而是生成一個可以讀取檔案、搜尋程式碼和檢查程式碼庫以驗證條件的 subagent。代理 hooks 支援與基於提示的 hooks 相同的事件。

2458 

2459### 代理 hooks 如何工作

2460 

2461當代理 hook 觸發時:

2462 

24631. Claude Code 生成一個 subagent,使用您的提示和 hook 的 JSON 輸入

24642. Subagent 可以使用 Read、Grep 和 Glob 等工具進行調查

24653. 在最多 50 輪後,subagent 返回結構化的 `{ "ok": true/false }` 決定

24664. Claude Code 以與提示 hook 相同的方式處理決定

2467 

2468代理 hooks 在驗證需要檢查實際檔案或測試輸出時很有用,而不僅僅是評估 hook 輸入資料。

2469 

2470### 代理 hook 配置

2471 

2472將 `type` 設定為 `"agent"` 並提供 `prompt` 字串。配置欄位與[提示 hooks](#prompt-hook-configuration) 相同,但逾時更長:

2473 

2474| 欄位 | 必需 | 描述 |

2475| :-------- | :- | :----------------------------------------------- |

2476| `type` | 是 | 必須為 `"agent"` |

2477| `prompt` | 是 | 描述要驗證的內容的提示。使用 `$ARGUMENTS` 作為 hook 輸入 JSON 的佔位符 |

2478| `model` | 否 | 要使用的模型。預設為快速模型 |

2479| `timeout` | 否 | 逾時(秒)。預設值:60 |

2480 

2481回應架構與提示 hooks 相同:`{ "ok": true }` 允許或 `{ "ok": false, "reason": "..." }` 阻止。

2482 

2483此 `Stop` hook 驗證所有單元測試通過,然後允許 Claude 完成:

2484 

2485```json theme={null}

2486{

2487 "hooks": {

2488 "Stop": [

2489 {

2490 "hooks": [

2491 {

2492 "type": "agent",

2493 "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",

2494 "timeout": 120

2495 }

2496 ]

2497 }

2498 ]

2499 }

2500}

2501```

2502 

2503## 在背景執行 hooks

2504 

2505預設情況下,hooks 會阻止 Claude 的執行,直到它們完成。對於長時間執行的任務,如部署、測試套件或外部 API 呼叫,設定 `"async": true` 以在背景執行 hook,同時 Claude 繼續工作。非同步 hooks 無法阻止或控制 Claude 的行為:回應欄位,如 `decision`、`permissionDecision` 和 `continue` 沒有效果,因為它們會控制的操作已經完成。

2506 

2507### 配置非同步 hook

2508 

2509將 `"async": true` 新增到命令 hook 的配置以在背景執行它而不阻止 Claude。此欄位僅在 `type: "command"` hooks 上可用。

2510 

2511此 hook 在每個 `Write` 工具呼叫後執行測試指令碼。Claude 立即繼續工作,同時 `run-tests.sh` 執行最多 120 秒。當指令碼完成時,其輸出在下一個對話輪次上傳遞:

2512 

2513```json theme={null}

2514{

2515 "hooks": {

2516 "PostToolUse": [

2517 {

2518 "matcher": "Write",

2519 "hooks": [

2520 {

2521 "type": "command",

2522 "command": "/path/to/run-tests.sh",

2523 "async": true,

2524 "timeout": 120

2525 }

2526 ]

2527 }

2528 ]

2529 }

2530}

2531```

2532 

2533`timeout` 欄位設定背景程序的最大時間(秒)。如果未指定,非同步 hooks 使用與同步 hooks 相同的 10 分鐘預設值。

2534 

2535### 非同步 hooks 如何執行

2536 

2537當非同步 hook 觸發時,Claude Code 啟動 hook 程序並立即繼續,而不等待它完成。Hook 在 stdin 上接收與同步 hook 相同的 JSON 輸入。

2538 

2539背景程序退出後,如果 hook 產生了帶有 `systemMessage` 或 `additionalContext` 欄位的 JSON 回應,該內容會在下一個對話輪次上作為上下文傳遞給 Claude。

2540 

2541非同步 hook 完成通知預設被抑制。要查看它們,請使用 `Ctrl+O` 啟用詳細模式或使用 `--verbose` 啟動 Claude Code。

2542 

2543### 範例:檔案變更後執行測試

2544 

2545此 hook 在 Claude 寫入檔案時在背景啟動測試套件,然後在測試完成時將結果報告回 Claude。將此指令碼儲存到專案中的 `.claude/hooks/run-tests-async.sh` 並使用 `chmod +x` 使其可執行:

2546 

2547```bash theme={null}

2548#!/bin/bash

2549# run-tests-async.sh

2550 

2551# 從 stdin 讀取 hook 輸入

2552INPUT=$(cat)

2553FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

2554 

2555# 僅針對原始檔案執行測試

2556if [[ "$FILE_PATH" != *.ts && "$FILE_PATH" != *.js ]]; then

2557 exit 0

2558fi

2559 

2560# 執行測試並通過 systemMessage 報告結果

2561RESULT=$(npm test 2>&1)

2562EXIT_CODE=$?

2563 

2564if [ $EXIT_CODE -eq 0 ]; then

2565 echo "{\"systemMessage\": \"Tests passed after editing $FILE_PATH\"}"

2566else

2567 echo "{\"systemMessage\": \"Tests failed after editing $FILE_PATH: $RESULT\"}"

2568fi

2569```

2570 

2571然後將此配置新增到專案根目錄中的 `.claude/settings.json`。`async: true` 標誌讓 Claude 在測試執行時繼續工作:

2572 

2573```json theme={null}

2574{

2575 "hooks": {

2576 "PostToolUse": [

2577 {

2578 "matcher": "Write|Edit",

2579 "hooks": [

2580 {

2581 "type": "command",

2582 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/run-tests-async.sh",

2583 "async": true,

2584 "timeout": 300

2585 }

2586 ]

2587 }

2588 ]

2589 }

2590}

2591```

2592 

2593### 限制

2594 

2595非同步 hooks 與同步 hooks 相比有幾個限制:

2596 

2597* 僅 `type: "command"` hooks 支援 `async`。基於提示的 hooks 無法非同步執行。

2598* 非同步 hooks 無法阻止工具呼叫或返回決定。到 hook 完成時,觸發操作已經進行。

2599* Hook 輸出在下一個對話輪次上傳遞。如果工作階段閒置,回應會等待直到下一個使用者互動。例外:`asyncRewake` hook 在退出代碼 2 時喚醒 Claude,即使工作階段閒置。

2600* 每次執行都會建立一個單獨的背景程序。同一非同步 hook 的多次觸發之間沒有去重。

2601 

2602## 安全考慮

2603 

2604### 免責聲明

2605 

2606命令 hooks 以您的系統使用者的完整權限執行。

2607 

2608<Warning>

2609 命令 hooks 以您的完整使用者權限執行 shell 命令。它們可以修改、刪除或存取您的使用者帳戶可以存取的任何檔案。在將任何 hook 命令新增到您的配置之前,請審查並測試它們。

2610</Warning>

2611 

2612### 安全最佳實踐

2613 

2614編寫 hooks 時,請記住這些實踐:

2615 

2616* **驗證和清理輸入**:永遠不要盲目信任輸入資料

2617* **始終引用 shell 變數**:使用 `"$VAR"` 而不是 `$VAR`

2618* **阻止路徑遍歷**:檢查檔案路徑中的 `..`

2619* **使用絕對路徑**:為指令碼指定完整路徑,使用 `"$CLAUDE_PROJECT_DIR"` 作為專案根目錄

2620* **跳過敏感檔案**:避免 `.env`、`.git/`、金鑰等

2621 

2622## Windows PowerShell 工具

2623 

2624在 Windows 上,您可以通過在命令 hook 上設定 `"shell": "powershell"` 在 PowerShell 中執行個別 hooks。Hooks 直接生成 PowerShell,因此無論是否設定 `CLAUDE_CODE_USE_POWERSHELL_TOOL` 都有效。Claude Code 自動偵測 `pwsh.exe`(PowerShell 7+),回退到 `powershell.exe`(5.1)。

2625 

2626```json theme={null}

2627{

2628 "hooks": {

2629 "PostToolUse": [

2630 {

2631 "matcher": "Write",

2632 "hooks": [

2633 {

2634 "type": "command",

2635 "shell": "powershell",

2636 "command": "Write-Host 'File written'"

2637 }

2638 ]

2639 }

2640 ]

2641 }

2642}

2643```

2644 

2645## 偵錯 hooks

2646 

2647Hook 執行詳細資訊,包括哪些 hooks 匹配、它們的退出代碼和完整 stdout 和 stderr,被寫入詳細日誌檔案。使用 `claude --debug-file <path>` 啟動 Claude Code 以將日誌寫入已知位置,或執行 `claude --debug` 並在 `~/.claude/debug/<session-id>.txt` 讀取日誌。`--debug` 標誌不列印到終端。

2648 

2649```text theme={null}

2650[DEBUG] Executing hooks for PostToolUse:Write

2651[DEBUG] Found 1 hook commands to execute

2652[DEBUG] Executing hook command: <Your command> with timeout 600000ms

2653[DEBUG] Hook command completed with status 0: <Your stdout>

2654```

2655 

2656有關更細粒度的 hook 匹配詳細資訊,設定 `CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose` 以查看額外的日誌行,例如 hook 匹配器計數和查詢匹配。

2657 

2658有關故障排除常見問題,如 hooks 不觸發、無限 Stop hook 迴圈或配置錯誤,請參閱指南中的 [限制和故障排除](/zh-TW/hooks-guide#limitations-and-troubleshooting)。有關涵蓋 `/context`、`/doctor` 和設定優先順序的更廣泛診斷逐步解說,請參閱 [偵錯您的配置](/zh-TW/debug-your-config)。

hooks-guide.md +927 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 使用 hooks 自動化工作流程

6 

7> 當 Claude Code 編輯檔案、完成任務或需要輸入時,自動執行 shell 命令。格式化程式碼、發送通知、驗證命令並強制執行專案規則。

8 

9Hooks 是使用者定義的 shell 命令,在 Claude Code 生命週期的特定時間點執行。它們提供對 Claude Code 行為的確定性控制,確保某些操作始終發生,而不是依賴 LLM 選擇執行它們。使用 hooks 來強制執行專案規則、自動化重複性任務,並將 Claude Code 與您現有的工具整合。

10 

11對於需要判斷而不是確定性規則的決策,您也可以使用[基於提示的 hooks](#prompt-based-hooks) 或[基於代理的 hooks](#agent-based-hooks),它們使用 Claude 模型來評估條件。

12 

13有關擴展 Claude Code 的其他方式,請參閱[skills](/zh-TW/skills)以提供 Claude 額外的指令和可執行命令、[subagents](/zh-TW/sub-agents)以在隔離的上下文中執行任務,以及[plugins](/zh-TW/plugins)以打包要在專案間共享的擴展。

14 

15<Tip>

16 本指南涵蓋常見用例和入門方式。有關完整的事件架構、JSON 輸入/輸出格式和非同步 hooks 和 MCP 工具 hooks 等進階功能,請參閱 [Hooks 參考](/zh-TW/hooks)。

17</Tip>

18 

19## 設定您的第一個 hook

20 

21若要建立 hook,請將 `hooks` 區塊新增到[設定檔](#configure-hook-location)。本逐步解說建立一個桌面通知 hook,因此每當 Claude 等待您的輸入而不是監視終端時,您都會收到警報。

22 

23<Steps>

24 <Step title="將 hook 新增到您的設定">

25 開啟 `~/.claude/settings.json` 並新增 `Notification` hook。下面的範例使用 `osascript` 進行 macOS;有關 Linux 和 Windows 命令,請參閱[當 Claude 需要輸入時收到通知](#get-notified-when-claude-needs-input)。

26 

27 ```json theme={null}

28 {

29 "hooks": {

30 "Notification": [

31 {

32 "matcher": "",

33 "hooks": [

34 {

35 "type": "command",

36 "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"

37 }

38 ]

39 }

40 ]

41 }

42 }

43 ```

44 

45 如果您的設定檔已經有 `hooks` 鍵,請將 `Notification` 作為現有事件鍵的同級項目新增,而不是替換整個物件。每個事件名稱是單個 `hooks` 物件內的鍵:

46 

47 ```json theme={null}

48 {

49 "hooks": {

50 "PostToolUse": [

51 {

52 "matcher": "Edit|Write",

53 "hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write" }]

54 }

55 ],

56 "Notification": [

57 {

58 "matcher": "",

59 "hooks": [{ "type": "command", "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'" }]

60 }

61 ]

62 }

63 }

64 ```

65 

66 您也可以透過在 CLI 中描述您想要的內容,要求 Claude 為您編寫 hook。

67 </Step>

68 

69 <Step title="驗證配置">

70 輸入 `/hooks` 以開啟 hooks 瀏覽器。您將看到所有可用 hook 事件的列表,每個配置了 hooks 的事件旁邊都有一個計數。選擇 `Notification` 以確認您的新 hook 出現在列表中。選擇 hook 會顯示其詳細資訊:事件、匹配器、類型、來源檔案和命令。

71 </Step>

72 

73 <Step title="測試 hook">

74 按 `Esc` 返回 CLI。要求 Claude 執行需要權限的操作,然後切換離開終端。您應該會收到桌面通知。

75 </Step>

76</Steps>

77 

78<Tip>

79 `/hooks` 選單是唯讀的。若要新增、修改或移除 hooks,請直接編輯您的設定 JSON 或要求 Claude 進行變更。

80</Tip>

81 

82## 您可以自動化的內容

83 

84Hooks 讓您在 Claude Code 生命週期的關鍵點執行程式碼:編輯後格式化檔案、在執行前阻止命令、當 Claude 需要輸入時發送通知、在工作階段開始時注入上下文等。有關 hook 事件的完整列表,請參閱 [Hooks 參考](/zh-TW/hooks#hook-lifecycle)。

85 

86每個範例都包含一個現成可用的配置區塊,您可以將其新增到[設定檔](#configure-hook-location)。最常見的模式:

87 

88* [當 Claude 需要輸入時收到通知](#get-notified-when-claude-needs-input)

89* [編輯後自動格式化程式碼](#auto-format-code-after-edits)

90* [阻止編輯受保護的檔案](#block-edits-to-protected-files)

91* [壓縮後重新注入上下文](#re-inject-context-after-compaction)

92* [審計配置變更](#audit-configuration-changes)

93* [當目錄或檔案變更時重新載入環境](#reload-environment-when-directory-or-files-change)

94* [自動批准特定權限提示](#auto-approve-specific-permission-prompts)

95 

96### 當 Claude 需要輸入時收到通知

97 

98每當 Claude 完成工作並需要您的輸入時收到桌面通知,這樣您可以切換到其他任務而無需檢查終端。

99 

100此 hook 使用 `Notification` 事件,當 Claude 等待輸入或權限時觸發。下面的每個標籤使用平台的原生通知命令。將此新增到 `~/.claude/settings.json`:

101 

102<Tabs>

103 <Tab title="macOS">

104 ```json theme={null}

105 {

106 "hooks": {

107 "Notification": [

108 {

109 "matcher": "",

110 "hooks": [

111 {

112 "type": "command",

113 "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"

114 }

115 ]

116 }

117 ]

118 }

119 }

120 ```

121 

122 <Accordion title="如果沒有出現通知">

123 `osascript` 透過內建的 Script Editor 應用程式路由通知。如果 Script Editor 沒有通知權限,命令會無聲地失敗,macOS 不會提示您授予它。在終端中執行一次以使 Script Editor 出現在您的通知設定中:

124 

125 ```bash theme={null}

126 osascript -e 'display notification "test"'

127 ```

128 

129 目前不會出現任何內容。開啟**系統設定 > 通知**,在列表中找到 **Script Editor**,並開啟**允許通知**。再次執行命令以確認測試通知出現。

130 </Accordion>

131 </Tab>

132 

133 <Tab title="Linux">

134 ```json theme={null}

135 {

136 "hooks": {

137 "Notification": [

138 {

139 "matcher": "",

140 "hooks": [

141 {

142 "type": "command",

143 "command": "notify-send 'Claude Code' 'Claude Code needs your attention'"

144 }

145 ]

146 }

147 ]

148 }

149 }

150 ```

151 </Tab>

152 

153 <Tab title="Windows (PowerShell)">

154 ```json theme={null}

155 {

156 "hooks": {

157 "Notification": [

158 {

159 "matcher": "",

160 "hooks": [

161 {

162 "type": "command",

163 "command": "powershell.exe -Command \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')\""

164 }

165 ]

166 }

167 ]

168 }

169 }

170 ```

171 </Tab>

172</Tabs>

173 

174空的 `matcher` 會在所有通知類型上觸發。若要僅在特定事件上觸發,請將其設定為以下其中一個值:

175 

176| Matcher | 觸發時機 |

177| :--------------------- | :------------------ |

178| `permission_prompt` | Claude 需要您批准工具使用 |

179| `idle_prompt` | Claude 完成並等待您的下一個提示 |

180| `auth_success` | 驗證完成 |

181| `elicitation_dialog` | MCP 伺服器開啟引導表單 |

182| `elicitation_complete` | MCP 引導表單被提交或關閉 |

183| `elicitation_response` | MCP 引導回應被發送回伺服器 |

184 

185輸入 `/hooks` 並選擇 `Notification` 以確認 hook 已註冊。有關完整的事件架構,請參閱 [Notification 參考](/zh-TW/hooks#notification)。

186 

187### 編輯後自動格式化程式碼

188 

189在 Claude 編輯的每個檔案上自動執行 [Prettier](https://prettier.io/),以便格式保持一致而無需手動干預。

190 

191此 hook 使用 `PostToolUse` 事件搭配 `Edit|Write` 匹配器,因此它只在檔案編輯工具之後執行。該命令使用 [`jq`](https://jqlang.github.io/jq/) 提取編輯的檔案路徑並將其傳遞給 Prettier。將此新增到您的專案根目錄中的 `.claude/settings.json`:

192 

193```json theme={null}

194{

195 "hooks": {

196 "PostToolUse": [

197 {

198 "matcher": "Edit|Write",

199 "hooks": [

200 {

201 "type": "command",

202 "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"

203 }

204 ]

205 }

206 ]

207 }

208}

209```

210 

211<Note>

212 本頁上的 Bash 範例使用 `jq` 進行 JSON 解析。使用 `brew install jq`(macOS)、`apt-get install jq`(Debian/Ubuntu)安裝它,或參閱 [`jq` 下載](https://jqlang.github.io/jq/download/)。

213</Note>

214 

215### 阻止編輯受保護的檔案

216 

217防止 Claude 修改敏感檔案,如 `.env`、`package-lock.json` 或 `.git/` 中的任何內容。Claude 會收到解釋編輯被阻止原因的回饋,因此它可以調整其方法。

218 

219此範例使用 hook 呼叫的單獨指令檔。該指令檢查目標檔案路徑是否與受保護的模式列表相符,並以代碼 2 退出以阻止編輯。

220 

221<Steps>

222 <Step title="建立 hook 指令">

223 將此儲存到 `.claude/hooks/protect-files.sh`:

224 

225 ```bash theme={null}

226 #!/bin/bash

227 # protect-files.sh

228 

229 INPUT=$(cat)

230 FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

231 

232 PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/")

233 

234 for pattern in "${PROTECTED_PATTERNS[@]}"; do

235 if [[ "$FILE_PATH" == *"$pattern"* ]]; then

236 echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2

237 exit 2

238 fi

239 done

240 

241 exit 0

242 ```

243 </Step>

244 

245 <Step title="使指令可執行(macOS/Linux)">

246 Hook 指令必須可執行,Claude Code 才能執行它們:

247 

248 ```bash theme={null}

249 chmod +x .claude/hooks/protect-files.sh

250 ```

251 </Step>

252 

253 <Step title="註冊 hook">

254 將 `PreToolUse` hook 新增到 `.claude/settings.json`,在任何 `Edit` 或 `Write` 工具呼叫之前執行指令:

255 

256 ```json theme={null}

257 {

258 "hooks": {

259 "PreToolUse": [

260 {

261 "matcher": "Edit|Write",

262 "hooks": [

263 {

264 "type": "command",

265 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"

266 }

267 ]

268 }

269 ]

270 }

271 }

272 ```

273 </Step>

274</Steps>

275 

276### 壓縮後重新注入上下文

277 

278當 Claude 的上下文視窗填滿時,壓縮會總結對話以釋放空間。這可能會遺失重要細節。使用帶有 `compact` 匹配器的 `SessionStart` hook 在每次壓縮後重新注入關鍵上下文。

279 

280您的命令寫入 stdout 的任何文字都會新增到 Claude 的上下文中。此範例提醒 Claude 專案慣例和最近的工作。將此新增到您的專案根目錄中的 `.claude/settings.json`:

281 

282```json theme={null}

283{

284 "hooks": {

285 "SessionStart": [

286 {

287 "matcher": "compact",

288 "hooks": [

289 {

290 "type": "command",

291 "command": "echo 'Reminder: use Bun, not npm. Run bun test before committing. Current sprint: auth refactor.'"

292 }

293 ]

294 }

295 ]

296 }

297}

298```

299 

300您可以將 `echo` 替換為任何產生動態輸出的命令,如 `git log --oneline -5` 以顯示最近的提交。有關在每個工作階段開始時注入上下文,請考慮改用 [CLAUDE.md](/zh-TW/memory)。有關環境變數,請參閱參考中的 [`CLAUDE_ENV_FILE`](/zh-TW/hooks#persist-environment-variables)。

301 

302### 審計配置變更

303 

304追蹤工作階段期間設定或 skills 檔案何時變更。`ConfigChange` 事件在外部程序或編輯器修改配置檔案時觸發,因此您可以記錄變更以進行合規性檢查或阻止未授權的修改。

305 

306此範例將每個變更附加到審計日誌。將此新增到 `~/.claude/settings.json`:

307 

308```json theme={null}

309{

310 "hooks": {

311 "ConfigChange": [

312 {

313 "matcher": "",

314 "hooks": [

315 {

316 "type": "command",

317 "command": "jq -c '{timestamp: now | todate, source: .source, file: .file_path}' >> ~/claude-config-audit.log"

318 }

319 ]

320 }

321 ]

322 }

323}

324```

325 

326匹配器按配置類型篩選:`user_settings`、`project_settings`、`local_settings`、`policy_settings` 或 `skills`。要阻止變更生效,以代碼 2 退出或傳回 `{"decision": "block"}`。有關完整的輸入架構,請參閱 [ConfigChange 參考](/zh-TW/hooks#configchange)。

327 

328### 當目錄或檔案變更時重新載入環境

329 

330某些專案根據您所在的目錄設定不同的環境變數。[direnv](https://direnv.net/) 之類的工具在您的 shell 中自動執行此操作,但 Claude 的 Bash 工具不會自行選取這些變更。

331 

332配對 `SessionStart` hook 與 `CwdChanged` hook 可以修復此問題。`SessionStart` 載入您啟動時所在目錄的變數,`CwdChanged` 在 Claude 每次變更目錄時重新載入它們。兩者都寫入 `CLAUDE_ENV_FILE`,Claude Code 在每個 Bash 命令之前執行為指令碼前置。將此新增到 `~/.claude/settings.json`:

333 

334```json theme={null}

335{

336 "hooks": {

337 "SessionStart": [

338 {

339 "hooks": [

340 {

341 "type": "command",

342 "command": "direnv export bash > \"$CLAUDE_ENV_FILE\""

343 }

344 ]

345 }

346 ],

347 "CwdChanged": [

348 {

349 "hooks": [

350 {

351 "type": "command",

352 "command": "direnv export bash > \"$CLAUDE_ENV_FILE\""

353 }

354 ]

355 }

356 ]

357 }

358}

359```

360 

361在每個具有 `.envrc` 的目錄中執行一次 `direnv allow`,以便允許 direnv 載入它。如果您使用 devbox 或 nix 而不是 direnv,相同的模式適用於 `devbox shellenv` 或 `devbox global shellenv` 代替 `direnv export bash`。

362 

363若要對特定檔案而不是每次目錄變更做出反應,請使用 `FileChanged` 搭配 `matcher` 列出要監視的檔案名稱(以 `|` 分隔)。若要建立監視清單,此值會分割為字面檔案名稱,而不是作為正規表達式進行評估。有關輸入架構、`watchPaths` 輸出和 `CLAUDE_ENV_FILE` 詳細資訊,請參閱 [FileChanged](/zh-TW/hooks#filechanged)。此範例監視工作目錄中 `.envrc` 和 `.env` 的變更:

364 

365```json theme={null}

366{

367 "hooks": {

368 "FileChanged": [

369 {

370 "matcher": ".envrc|.env",

371 "hooks": [

372 {

373 "type": "command",

374 "command": "direnv export bash > \"$CLAUDE_ENV_FILE\""

375 }

376 ]

377 }

378 ]

379 }

380}

381```

382 

383有關輸入架構、`watchPaths` 輸出和 `CLAUDE_ENV_FILE` 詳細資訊,請參閱 [CwdChanged](/zh-TW/hooks#cwdchanged) 和 [FileChanged](/zh-TW/hooks#filechanged) 參考項目。

384 

385### 自動批准特定權限提示

386 

387跳過您始終允許的工具呼叫的批准對話。此範例自動批准 `ExitPlanMode`,這是 Claude 在完成呈現計畫並要求繼續時呼叫的工具,因此您不會在每次計畫準備好時被提示。

388 

389與上面的退出代碼範例不同,自動批准要求您的 hook 將 JSON 決策寫入 stdout。`PermissionRequest` hook 在 Claude Code 即將顯示權限對話時觸發,傳回 `"behavior": "allow"` 會代表您回答它。

390 

391匹配器將 hook 的範圍限制為僅 `ExitPlanMode`,因此不會影響其他提示。將此新增到 `~/.claude/settings.json`:

392 

393```json theme={null}

394{

395 "hooks": {

396 "PermissionRequest": [

397 {

398 "matcher": "ExitPlanMode",

399 "hooks": [

400 {

401 "type": "command",

402 "command": "echo '{\"hookSpecificOutput\": {\"hookEventName\": \"PermissionRequest\", \"decision\": {\"behavior\": \"allow\"}}}'"

403 }

404 ]

405 }

406 ]

407 }

408}

409```

410 

411當 hook 批准時,Claude Code 退出計畫模式並恢復進入計畫模式之前處於活動狀態的任何權限模式。文字記錄顯示「由 PermissionRequest hook 允許」,其中對話會出現。hook 路徑始終保持當前對話:它無法清除上下文並以對話可以執行的方式啟動新的實現工作階段。

412 

413若要改為設定特定的權限模式,您的 hook 的輸出可以包含帶有 `setMode` 項目的 `updatedPermissions` 陣列。`mode` 值是任何權限模式,如 `default`、`acceptEdits` 或 `bypassPermissions`,`destination: "session"` 僅將其應用於當前工作階段。

414 

415<Note>

416 `bypassPermissions` 只有在工作階段已經啟用了繞過模式時才適用:`--dangerously-skip-permissions`、`--permission-mode bypassPermissions`、`--allow-dangerously-skip-permissions` 或設定中的 `permissions.defaultMode: "bypassPermissions"`,且未被 [`permissions.disableBypassPermissionsMode`](/zh-TW/permissions#managed-settings) 禁用。它永遠不會被持久化為 `defaultMode`。

417</Note>

418 

419若要將工作階段切換到 `acceptEdits`,您的 hook 會將此 JSON 寫入 stdout:

420 

421```json theme={null}

422{

423 "hookSpecificOutput": {

424 "hookEventName": "PermissionRequest",

425 "decision": {

426 "behavior": "allow",

427 "updatedPermissions": [

428 { "type": "setMode", "mode": "acceptEdits", "destination": "session" }

429 ]

430 }

431 }

432}

433```

434 

435保持匹配器盡可能狹窄。在 `.*` 上進行匹配或留空匹配器會自動批准每個權限提示,包括檔案寫入和 shell 命令。有關決策欄位的完整集合,請參閱 [PermissionRequest 參考](/zh-TW/hooks#permissionrequest-decision-control)。

436 

437## Hooks 如何工作

438 

439Hook 事件在 Claude Code 的特定生命週期點觸發。當事件觸發時,所有匹配的 hooks 並行執行,相同的 hook 命令會自動去重。下表顯示每個事件及其觸發時間:

440 

441| Event | When it fires |

442| :-------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |

443| `SessionStart` | When a session begins or resumes |

444| `Setup` | When you start Claude Code with `--init-only`, or with `--init` or `--maintenance` in `-p` mode. For one-time preparation in CI or scripts |

445| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |

446| `UserPromptExpansion` | When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion |

447| `PreToolUse` | Before a tool call executes. Can block it |

448| `PermissionRequest` | When a permission dialog appears |

449| `PermissionDenied` | When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call |

450| `PostToolUse` | After a tool call succeeds |

451| `PostToolUseFailure` | After a tool call fails |

452| `PostToolBatch` | After a full batch of parallel tool calls resolves, before the next model call |

453| `Notification` | When Claude Code sends a notification |

454| `SubagentStart` | When a subagent is spawned |

455| `SubagentStop` | When a subagent finishes |

456| `TaskCreated` | When a task is being created via `TaskCreate` |

457| `TaskCompleted` | When a task is being marked as completed |

458| `Stop` | When Claude finishes responding |

459| `StopFailure` | When the turn ends due to an API error. Output and exit code are ignored |

460| `TeammateIdle` | When an [agent team](/en/agent-teams) teammate is about to go idle |

461| `InstructionsLoaded` | When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session |

462| `ConfigChange` | When a configuration file changes during a session |

463| `CwdChanged` | When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv |

464| `FileChanged` | When a watched file changes on disk. The `matcher` field specifies which filenames to watch |

465| `WorktreeCreate` | When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior |

466| `WorktreeRemove` | When a worktree is being removed, either at session exit or when a subagent finishes |

467| `PreCompact` | Before context compaction |

468| `PostCompact` | After context compaction completes |

469| `Elicitation` | When an MCP server requests user input during a tool call |

470| `ElicitationResult` | After a user responds to an MCP elicitation, before the response is sent back to the server |

471| `SessionEnd` | When a session terminates |

472 

473當多個 hooks 相符時,每個都傳回自己的結果。對於決策,Claude Code 選擇最具限制性的答案。傳回 `deny` 的 `PreToolUse` hook 會取消工具呼叫,無論其他的傳回什麼。一個 hook 傳回 `ask` 會強制權限提示,即使其餘的傳回 `allow`。來自 `additionalContext` 的文字會從每個 hook 保留並一起傳遞給 Claude。

474 

475每個 hook 都有一個 `type` 來決定它如何執行。大多數 hooks 使用 `"type": "command"`,它執行 shell 命令。還有四種其他類型可用:

476 

477* `"type": "http"`:POST 事件資料到 URL。請參閱 [HTTP hooks](#http-hooks)。

478* `"type": "mcp_tool"`:在已連接的 MCP 伺服器上呼叫工具。請參閱 [MCP tool hooks](/zh-TW/hooks#mcp-tool-hook-fields)。

479* `"type": "prompt"`:單輪 LLM 評估。請參閱[基於提示的 hooks](#prompt-based-hooks)。

480* `"type": "agent"`:具有工具存取的多輪驗證。Agent hooks 是實驗性的,可能會改變。請參閱[基於 Agent 的 hooks](#agent-based-hooks)。

481 

482### 讀取輸入並傳回輸出

483 

484Hooks 透過 stdin、stdout、stderr 和退出代碼與 Claude Code 通訊。當事件觸發時,Claude Code 將事件特定的資料作為 JSON 傳遞到您的指令的 stdin。您的指令讀取該資料、執行其工作,並透過退出代碼告訴 Claude Code 接下來要做什麼。

485 

486#### Hook 輸入

487 

488每個事件都包含常見欄位,如 `session_id` 和 `cwd`,但每個事件類型都新增不同的資料。例如,當 Claude 執行 Bash 命令時,`PreToolUse` hook 在 stdin 上接收類似以下內容:

489 

490```json theme={null}

491{

492 "session_id": "abc123", // 此工作階段的唯一 ID

493 "cwd": "/Users/sarah/myproject", // 事件觸發時的工作目錄

494 "hook_event_name": "PreToolUse", // 哪個事件觸發了此 hook

495 "tool_name": "Bash", // Claude 即將使用的工具

496 "tool_input": { // Claude 傳遞給工具的引數

497 "command": "npm test" // 對於 Bash,這是 shell 命令

498 }

499}

500```

501 

502您的指令可以解析該 JSON 並對任何這些欄位採取行動。`UserPromptSubmit` hooks 改為取得 `prompt` 文字,`SessionStart` hooks 取得 `source`(startup、resume、clear、compact),等等。有關共享欄位,請參閱參考中的[常見輸入欄位](/zh-TW/hooks#common-input-fields),以及每個事件的部分以了解事件特定的架構。

503 

504#### Hook 輸出

505 

506您的指令透過寫入 stdout 或 stderr 並以特定代碼退出來告訴 Claude Code 接下來要做什麼。例如,想要阻止命令的 `PreToolUse` hook:

507 

508```bash theme={null}

509#!/bin/bash

510INPUT=$(cat)

511COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command')

512 

513if echo "$COMMAND" | grep -q "drop table"; then

514 echo "Blocked: dropping tables is not allowed" >&2 # stderr 變成 Claude 的回饋

515 exit 2 # exit 2 = 阻止操作

516fi

517 

518exit 0 # exit 0 = 讓它繼續

519```

520 

521退出代碼決定接下來會發生什麼:

522 

523* **Exit 0**:操作繼續。對於 `UserPromptSubmit`、`UserPromptExpansion` 和 `SessionStart` hooks,您寫入 stdout 的任何內容都會新增到 Claude 的上下文中。

524* **Exit 2**:操作被阻止。寫入原因到 stderr,Claude 會收到它作為回饋,以便它可以調整。某些事件無法被阻止:對於 `SessionStart`、`Setup`、`Notification` 和其他事件,exit 2 會向使用者顯示 stderr,執行繼續。有關完整清單,請參閱[每個事件的 exit code 2 行為](/zh-TW/hooks#exit-code-2-behavior-per-event)。

525* **任何其他退出代碼**:操作繼續。文字記錄顯示 `<hook name> hook error` 通知,後面跟著 stderr 的第一行;完整的 stderr 進入[除錯日誌](/zh-TW/hooks#debug-hooks)。

526 

527#### 結構化 JSON 輸出

528 

529退出代碼給您兩個選項:允許或阻止。為了獲得更多控制,退出 0 並改為將 JSON 物件列印到 stdout。

530 

531<Note>

532 使用 exit 2 以 stderr 訊息阻止,或使用 exit 0 和 JSON 進行結構化控制。不要混合它們:Claude Code 在您退出 2 時忽略 JSON。

533</Note>

534 

535例如,`PreToolUse` hook 可以拒絕工具呼叫並告訴 Claude 為什麼,或將其升級給使用者以獲得批准:

536 

537```json theme={null}

538{

539 "hookSpecificOutput": {

540 "hookEventName": "PreToolUse",

541 "permissionDecision": "deny",

542 "permissionDecisionReason": "Use rg instead of grep for better performance"

543 }

544}

545```

546 

547使用 `"deny"`,Claude Code 會取消工具呼叫並將 `permissionDecisionReason` 回饋給 Claude。這些 `permissionDecision` 值特定於 `PreToolUse`:

548 

549* `"allow"`:跳過互動式權限提示。拒絕和詢問規則,包括企業受管拒絕清單,仍然適用

550* `"deny"`:取消工具呼叫並將原因傳送給 Claude

551* `"ask"`:照常向使用者顯示權限提示

552 

553第四個值 `"defer"` 在[非互動模式](/zh-TW/headless)中使用 `-p` 旗標時可用。它以保留的工具呼叫退出程序,以便 Agent SDK 包裝器可以收集輸入並繼續。有關詳細資訊,請參閱參考中的[延遲工具呼叫以供稍後使用](/zh-TW/hooks#defer-a-tool-call-for-later)。

554 

555傳回 `"allow"` 會跳過互動式提示,但不會覆蓋[權限規則](/zh-TW/permissions#manage-permissions)。如果拒絕規則與工具呼叫相符,即使您的 hook 傳回 `"allow"`,呼叫也會被阻止。如果詢問規則相符,使用者仍會被提示。這意味著來自任何設定範圍(包括[受管理的設定](/zh-TW/settings#settings-files))的拒絕規則始終優先於 hook 批准。

556 

557其他事件使用不同的決策模式。例如,`PostToolUse` 和 `Stop` hooks 使用頂級 `decision: "block"` 欄位,而 `PermissionRequest` 使用 `hookSpecificOutput.decision.behavior`。有關按事件的完整分解,請參閱參考中的[摘要表](/zh-TW/hooks#decision-control)。

558 

559對於 `UserPromptSubmit` hooks,改用 `additionalContext` 將文字注入到 Claude 的上下文中。基於提示的 hooks(`type: "prompt"`)以不同方式處理輸出:請參閱[基於提示的 hooks](#prompt-based-hooks)。

560 

561### 使用匹配器篩選 hooks

562 

563沒有匹配器,hook 會在其事件的每次出現時觸發。匹配器讓您縮小範圍。例如,如果您只想在檔案編輯後執行格式化程式(而不是在每次工具呼叫後),請將匹配器新增到您的 `PostToolUse` hook:

564 

565```json theme={null}

566{

567 "hooks": {

568 "PostToolUse": [

569 {

570 "matcher": "Edit|Write",

571 "hooks": [

572 { "type": "command", "command": "prettier --write ..." }

573 ]

574 }

575 ]

576 }

577}

578```

579 

580`"Edit|Write"` 匹配器只在 Claude 使用 `Edit` 或 `Write` 工具時觸發,而不是在它使用 `Bash`、`Read` 或任何其他工具時。請參閱[匹配器模式](/zh-TW/hooks#matcher-patterns)以了解純名稱和正規表達式如何被評估。

581 

582<Note>

583 Claude 也可以透過 `Bash` 工具執行 shell 命令來建立或修改檔案。如果您的 hook 必須看到每個檔案變更,例如用於合規掃描或稽核日誌,請新增一個[`Stop`](/zh-TW/hooks#stop) hook,它每輪掃描一次工作樹。為了獲得每次呼叫的覆蓋範圍,也請匹配 `Bash` 並讓您的指令使用 `git status --porcelain` 列出修改和未追蹤的檔案。

584</Note>

585 

586每個事件類型都在特定欄位上進行匹配:

587 

588| 事件 | 匹配器篩選的內容 | 範例匹配器值 |

589| :------------------------------------------------------------------------------------------------------------------------------------ | :----------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ |

590| `PreToolUse`、`PostToolUse`、`PostToolUseFailure`、`PermissionRequest`、`PermissionDenied` | 工具名稱 | `Bash`、`Edit\|Write`、`mcp__.*` |

591| `SessionStart` | 工作階段如何開始 | `startup`、`resume`、`clear`、`compact` |

592| `Setup` | 哪個 CLI 旗標觸發了設定 | `init`、`maintenance` |

593| `SessionEnd` | 工作階段為什麼結束 | `clear`、`resume`、`logout`、`prompt_input_exit`、`bypass_permissions_disabled`、`other` |

594| `Notification` | 通知類型 | `permission_prompt`、`idle_prompt`、`auth_success`、`elicitation_dialog`、`elicitation_complete`、`elicitation_response` |

595| `SubagentStart` | Agent 類型 | `general-purpose`、`Explore`、`Plan` 或自訂 Agent 名稱 |

596| `PreCompact`、`PostCompact` | 什麼觸發了壓縮 | `manual`、`auto` |

597| `SubagentStop` | Agent 類型 | 與 `SubagentStart` 相同的值 |

598| `ConfigChange` | 配置來源 | `user_settings`、`project_settings`、`local_settings`、`policy_settings`、`skills` |

599| `StopFailure` | 錯誤類型 | `rate_limit`、`authentication_failed`、`oauth_org_not_allowed`、`billing_error`、`invalid_request`、`server_error`、`max_output_tokens`、`unknown` |

600| `InstructionsLoaded` | 載入原因 | `session_start`、`nested_traversal`、`path_glob_match`、`include`、`compact` |

601| `Elicitation` | MCP 伺服器名稱 | 您配置的 MCP 伺服器名稱 |

602| `ElicitationResult` | MCP 伺服器名稱 | 與 `Elicitation` 相同的值 |

603| `FileChanged` | 字面檔案名稱以監視(請參閱 [FileChanged](/zh-TW/hooks#filechanged)) | `.envrc\|.env` |

604| `UserPromptExpansion` | 命令名稱 | 您的 skill 或命令名稱 |

605| `UserPromptSubmit`、`PostToolBatch`、`Stop`、`TeammateIdle`、`TaskCreated`、`TaskCompleted`、`WorktreeCreate`、`WorktreeRemove`、`CwdChanged` | 不支援匹配器 | 始終在每次出現時觸發 |

606 

607顯示不同事件類型上匹配器的更多範例:

608 

609<Tabs>

610 <Tab title="記錄每個 Bash 命令">

611 只匹配 `Bash` 工具呼叫並將每個命令記錄到檔案。`PostToolUse` 事件在命令完成後觸發,因此 `tool_input.command` 包含執行的內容。hook 在 stdin 上接收事件資料作為 JSON,`jq -r '.tool_input.command'` 只提取命令字串,`>>` 將其附加到日誌檔案:

612 

613 ```json theme={null}

614 {

615 "hooks": {

616 "PostToolUse": [

617 {

618 "matcher": "Bash",

619 "hooks": [

620 {

621 "type": "command",

622 "command": "jq -r '.tool_input.command' >> ~/.claude/command-log.txt"

623 }

624 ]

625 }

626 ]

627 }

628 }

629 ```

630 </Tab>

631 

632 <Tab title="匹配 MCP 工具">

633 MCP 工具使用與內建工具不同的命名慣例:`mcp__<server>__<tool>`,其中 `<server>` 是 MCP 伺服器名稱,`<tool>` 是它提供的工具。例如,`mcp__github__search_repositories` 或 `mcp__filesystem__read_file`。使用正規表達式匹配器來針對來自特定伺服器的所有工具,或使用 `mcp__.*__write.*` 之類的模式跨伺服器進行匹配。有關完整的範例列表,請參閱參考中的[匹配 MCP 工具](/zh-TW/hooks#match-mcp-tools)。

634 

635 下面的命令使用 `jq` 從 hook 的 JSON 輸入中提取工具名稱,並將其寫入 stderr。寫入 stderr 會保持 stdout 乾淨以用於 JSON 輸出,並將訊息發送到[除錯日誌](/zh-TW/hooks#debug-hooks):

636 

637 ```json theme={null}

638 {

639 "hooks": {

640 "PreToolUse": [

641 {

642 "matcher": "mcp__github__.*",

643 "hooks": [

644 {

645 "type": "command",

646 "command": "echo \"GitHub tool called: $(jq -r '.tool_name')\" >&2"

647 }

648 ]

649 }

650 ]

651 }

652 }

653 ```

654 </Tab>

655 

656 <Tab title="在工作階段結束時清理">

657 `SessionEnd` 事件支援工作階段結束原因的匹配器。此 hook 只在 `clear` 時觸發(當您執行 `/clear` 時),而不是在正常退出時:

658 

659 ```json theme={null}

660 {

661 "hooks": {

662 "SessionEnd": [

663 {

664 "matcher": "clear",

665 "hooks": [

666 {

667 "type": "command",

668 "command": "rm -f /tmp/claude-scratch-*.txt"

669 }

670 ]

671 }

672 ]

673 }

674 }

675 ```

676 </Tab>

677</Tabs>

678 

679有關完整的匹配器語法,請參閱 [Hooks 參考](/zh-TW/hooks#configuration)。

680 

681#### 使用 `if` 欄位按工具名稱和引數篩選

682 

683<Note>

684 `if` 欄位需要 Claude Code v2.1.85 或更新版本。較早的版本會忽略它並在每次匹配的呼叫上執行 hook。

685</Note>

686 

687`if` 欄位使用[權限規則語法](/zh-TW/permissions)按工具名稱和引數一起篩選 hooks,因此 hook 程序只在工具呼叫相符時生成,或當 Bash 命令太複雜而無法解析時。這超越了 `matcher`,它只在工具名稱級別篩選。

688 

689例如,若要只在 Claude 使用 `git` 命令而不是所有 Bash 命令時執行 hook:

690 

691```json theme={null}

692{

693 "hooks": {

694 "PreToolUse": [

695 {

696 "matcher": "Bash",

697 "hooks": [

698 {

699 "type": "command",

700 "if": "Bash(git *)",

701 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-git-policy.sh"

702 }

703 ]

704 }

705 ]

706 }

707}

708```

709 

710hook 程序只在 Bash 命令的子命令與 `git *` 相符時生成,或當命令太複雜而無法解析為子命令時。對於複合命令(如 `npm test && git push`),Claude Code 評估每個子命令並觸發 hook,因為 `git push` 相符。`if` 欄位接受與權限規則相同的模式:`"Bash(git *)"`、`"Edit(*.ts)"` 等。若要匹配多個工具名稱,請使用每個都有自己的 `if` 值的單獨處理程式,或在 `matcher` 級別進行匹配,其中支援管道交替。

711 

712`if` 只適用於工具事件:`PreToolUse`、`PostToolUse`、`PostToolUseFailure`、`PermissionRequest` 和 `PermissionDenied`。將其新增到任何其他事件會防止 hook 執行。

713 

714### 配置 hook 位置

715 

716您新增 hook 的位置決定了其範圍:

717 

718| 位置 | 範圍 | 可共享 |

719| :------------------------------------------------------------- | :---------------------- | :----------- |

720| `~/.claude/settings.json` | 您的所有專案 | 否,本機到您的機器 |

721| `.claude/settings.json` | 單個專案 | 是,可以提交到儲存庫 |

722| `.claude/settings.local.json` | 單個專案 | 否,gitignored |

723| 受管理的原則設定 | 組織範圍 | 是,由管理員控制 |

724| [Plugin](/zh-TW/plugins) `hooks/hooks.json` | 啟用外掛時 | 是,與外掛捆綁 |

725| [Skill](/zh-TW/skills) 或[Agent](/zh-TW/sub-agents) frontmatter | 當 skill 或 Agent 處於活動狀態時 | 是,在元件檔案中定義 |

726 

727在 Claude Code 中執行 [`/hooks`](/zh-TW/hooks#the-hooks-menu) 以瀏覽按事件分組的所有配置的 hooks。若要一次禁用所有 hooks,請在設定檔中設定 `"disableAllHooks": true`。

728 

729如果您在 Claude Code 執行時直接編輯設定檔,檔案監視程式通常會自動選取 hook 變更。

730 

731## 基於提示的 hooks

732 

733對於需要判斷而不是確定性規則的決策,使用 `type: "prompt"` hooks。Claude Code 不執行 shell 命令,而是將您的提示和 hook 的輸入資料傳送到 Claude 模型(預設為 Haiku)以做出決策。如果您需要更多功能,可以使用 `model` 欄位指定不同的模型。

734 

735模型的唯一工作是傳回 yes/no 決策作為 JSON:

736 

737* `"ok": true`:操作繼續

738* `"ok": false`:發生的情況取決於事件:

739 * `Stop` 和 `SubagentStop`:`reason` 被回饋給 Claude,以便它繼續工作

740 * `PreToolUse`:工具呼叫被拒絕,`reason` 作為工具錯誤傳回給 Claude,以便它可以調整並繼續

741 * `PostToolUse`、`PostToolBatch`、`UserPromptSubmit` 和 `UserPromptExpansion`:回合結束,`reason` 在聊天中顯示為警告行

742 

743此範例使用 `Stop` hook 詢問模型是否所有請求的任務都已完成。如果模型傳回 `"ok": false`,Claude 會繼續工作並使用 `reason` 作為其下一個指令:

744 

745```json theme={null}

746{

747 "hooks": {

748 "Stop": [

749 {

750 "hooks": [

751 {

752 "type": "prompt",

753 "prompt": "Check if all tasks are complete. If not, respond with {\"ok\": false, \"reason\": \"what remains to be done\"}."

754 }

755 ]

756 }

757 ]

758 }

759}

760```

761 

762有關完整的配置選項,請參閱參考中的[基於提示的 hooks](/zh-TW/hooks#prompt-based-hooks)。

763 

764## 基於代理的 hooks

765 

766<Warning>

767 Agent hooks 是實驗性的。行為和配置可能在未來版本中改變。對於生產工作流程,優先使用[命令 hooks](/zh-TW/hooks#command-hook-fields)。

768</Warning>

769 

770當驗證需要檢查檔案或執行命令時,使用 `type: "agent"` hooks。與只進行單個 LLM 呼叫的提示 hooks 不同,代理 hooks 生成一個 subagent,可以讀取檔案、搜尋程式碼和使用其他工具在傳回決策之前驗證條件。

771 

772代理 hooks 使用與提示 hooks 相同的 `"ok"` / `"reason"` 回應格式,但預設超時時間更長(60 秒)且最多 50 個工具使用輪次。

773 

774此範例驗證在允許 Claude 停止之前測試通過:

775 

776```json theme={null}

777{

778 "hooks": {

779 "Stop": [

780 {

781 "hooks": [

782 {

783 "type": "agent",

784 "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",

785 "timeout": 120

786 }

787 ]

788 }

789 ]

790 }

791}

792```

793 

794當 hook 輸入資料本身足以做出決策時,使用提示 hooks。當您需要根據程式碼庫的實際狀態驗證某些內容時,使用代理 hooks。

795 

796有關完整的配置選項,請參閱參考中的[基於代理的 hooks](/zh-TW/hooks#agent-based-hooks)。

797 

798## HTTP hooks

799 

800使用 `type: "http"` hooks 將事件資料 POST 到 HTTP 端點,而不是執行 shell 命令。端點接收命令 hook 在 stdin 上接收的相同 JSON,並使用相同的 JSON 格式透過 HTTP 回應主體傳回結果。

801 

802HTTP hooks 在您希望 Web 伺服器、雲端函數或外部服務處理 hook 邏輯時很有用:例如,一個共享的審計服務,在整個團隊中記錄工具使用事件。

803 

804此範例將每個工具使用 POST 到本機記錄服務:

805 

806```json theme={null}

807{

808 "hooks": {

809 "PostToolUse": [

810 {

811 "hooks": [

812 {

813 "type": "http",

814 "url": "http://localhost:8080/hooks/tool-use",

815 "headers": {

816 "Authorization": "Bearer $MY_TOKEN"

817 },

818 "allowedEnvVars": ["MY_TOKEN"]

819 }

820 ]

821 }

822 ]

823 }

824}

825```

826 

827端點應使用與命令 hooks 相同的[輸出格式](/zh-TW/hooks#json-output)傳回 JSON 回應主體。要阻止工具呼叫,傳回 2xx 回應並包含適當的 `hookSpecificOutput` 欄位。HTTP 狀態代碼本身無法阻止操作。

828 

829標頭值支援使用 `$VAR_NAME` 或 `${VAR_NAME}` 語法的環境變數插值。只有在 `allowedEnvVars` 陣列中列出的變數才會被解析;所有其他 `$VAR` 參考保持為空。

830 

831有關完整的配置選項和回應處理,請參閱參考中的 [HTTP hooks](/zh-TW/hooks#http-hook-fields)。

832 

833## 限制和故障排除

834 

835### 限制

836 

837* 命令 hooks 只透過 stdout、stderr 和退出代碼通訊。它們無法觸發 `/` 命令或工具呼叫。透過 `additionalContext` 傳回的文字會作為系統提醒注入,Claude 將其讀取為純文字。HTTP hooks 改為透過回應主體通訊。

838* Hook 超時預設為 10 分鐘,可透過 `timeout` 欄位(以秒為單位)按 hook 配置。

839* `PostToolUse` hooks 無法撤銷操作,因為工具已經執行。

840* `PermissionRequest` hooks 在[非互動模式](/zh-TW/headless)(`-p`)中不觸發。對於自動化權限決策,使用 `PreToolUse` hooks。

841* `Stop` hooks 在 Claude 完成回應時觸發,而不僅在任務完成時。它們在使用者中斷時不觸發。API 錯誤觸發 [StopFailure](/zh-TW/hooks#stopfailure) 代替。

842* 當多個 PreToolUse hooks 傳回 [`updatedInput`](/zh-TW/hooks#pretooluse) 以重寫工具的引數時,最後完成的會獲勝。由於 hooks 並行執行,順序是非確定性的。避免有多個 hook 修改同一工具的輸入。

843 

844### Hooks 和權限模式

845 

846PreToolUse hooks 在任何權限模式檢查之前觸發。傳回 `permissionDecision: "deny"` 的 hook 會阻止工具,即使在 `bypassPermissions` 模式或使用 `--dangerously-skip-permissions`。這讓您強制執行使用者無法透過變更其權限模式來繞過的原則。

847 

848反面不成立:傳回 `"allow"` 的 hook 不會繞過來自設定的拒絕規則。Hooks 可以加強限制,但不能放寬超過權限規則允許的限制。

849 

850### Hook 未觸發

851 

852Hook 已配置但從不執行。

853 

854* 執行 `/hooks` 並確認 hook 出現在正確的事件下

855* 檢查匹配器模式是否與工具名稱完全相符(匹配器區分大小寫)

856* 驗證您觸發的是正確的事件類型(例如,`PreToolUse` 在工具執行前觸發,`PostToolUse` 在之後觸發)

857* 如果在非互動模式(`-p`)中使用 `PermissionRequest` hooks,改用 `PreToolUse`

858 

859### Hook 輸出中的錯誤

860 

861您在文字記錄中看到類似「PreToolUse hook error: ...」的訊息。

862 

863* 您的指令意外以非零代碼退出。透過管道傳輸範例 JSON 來手動測試它:

864 ```bash theme={null}

865 echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | ./my-hook.sh

866 echo $? # 檢查退出代碼

867 ```

868* 如果您看到「command not found」,使用絕對路徑或 `$CLAUDE_PROJECT_DIR` 來參考指令

869* 如果您看到「jq: command not found」,安裝 `jq` 或使用 Python/Node.js 進行 JSON 解析

870* 如果指令根本沒有執行,使其可執行:`chmod +x ./my-hook.sh`

871 

872### `/hooks` 顯示未配置任何 hooks

873 

874您編輯了設定檔但 hooks 未出現在選單中。

875 

876* 檔案編輯通常會自動選取。如果在幾秒鐘後仍未出現,檔案監視程式可能已錯過變更:重新啟動您的工作階段以強制重新載入。

877* 驗證您的 JSON 有效(不允許尾隨逗號和註解)

878* 確認設定檔在正確的位置:`.claude/settings.json` 用於專案 hooks,`~/.claude/settings.json` 用於全域 hooks

879 

880### Stop hook 永遠執行

881 

882Claude 在無限迴圈中繼續工作而不是停止。

883 

884您的 Stop hook 指令需要檢查它是否已經觸發了延續。從 JSON 輸入解析 `stop_hook_active` 欄位,如果為 `true` 則提前退出:

885 

886```bash theme={null}

887#!/bin/bash

888INPUT=$(cat)

889if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then

890 exit 0 # 允許 Claude 停止

891fi

892# ... 您的 hook 邏輯的其餘部分

893```

894 

895### JSON 驗證失敗

896 

897Claude Code 顯示 JSON 解析錯誤,即使您的 hook 指令輸出有效的 JSON。

898 

899當 Claude Code 執行 hook 時,它生成一個 shell,該 shell 來源您的設定檔(`~/.zshrc` 或 `~/.bashrc`)。如果您的設定檔包含無條件的 `echo` 陳述式,該輸出會被前置到您的 hook 的 JSON:

900 

901```text theme={null}

902Shell ready on arm64

903{"decision": "block", "reason": "Not allowed"}

904```

905 

906Claude Code 嘗試將其解析為 JSON 並失敗。要修復此問題,在您的 shell 設定檔中包裝 echo 陳述式,使其只在互動式 shell 中執行:

907 

908```bash theme={null}

909# 在 ~/.zshrc 或 ~/.bashrc 中

910if [[ $- == *i* ]]; then

911 echo "Shell ready"

912fi

913```

914 

915`$-` 變數包含 shell 旗標,`i` 表示互動式。Hooks 在非互動式 shell 中執行,因此 echo 被跳過。

916 

917### 除錯技術

918 

919文字記錄檢視(使用 `Ctrl+O` 切換)為每個觸發的 hook 顯示一行摘要:成功是無聲的,阻止錯誤顯示 stderr,非阻止錯誤顯示 `<hook name> hook error` 通知,後面跟著 stderr 的第一行。

920 

921有關完整的執行詳細資訊,包括哪些 hooks 相符、它們的退出代碼、stdout 和 stderr,請閱讀除錯日誌。使用 `claude --debug-file /tmp/claude.log` 啟動 Claude Code 以寫入已知路徑,然後在另一個終端中執行 `tail -f /tmp/claude.log`。如果您啟動時沒有該旗標,在工作階段中執行 `/debug` 以啟用記錄並找到日誌路徑。

922 

923## 深入瞭解

924 

925* [Hooks 參考](/zh-TW/hooks):完整的事件架構、JSON 輸出格式、非同步 hooks 和 MCP 工具 hooks

926* [安全考量](/zh-TW/hooks#security-considerations):在共享或生產環境中部署 hooks 之前進行檢查

927* [Bash 命令驗證器範例](https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py):完整的參考實現

how-claude-code-works.md +263 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Claude Code 如何運作

6 

7> 了解代理迴圈、內建工具,以及 Claude Code 如何與您的專案互動。

8 

9Claude Code 是在您的終端機中執行的代理助手。雖然它在編碼方面表現出色,但它可以幫助您從命令列執行的任何操作:撰寫文件、執行建置、搜尋檔案、研究主題等。

10 

11本指南涵蓋核心架構、內建功能,以及[有效使用 Claude Code 的提示](#work-effectively-with-claude-code)。如需逐步說明,請參閱[常見工作流程](/zh-TW/common-workflows)。如需擴展功能(如 skills、MCP 和 hooks),請參閱[擴展 Claude Code](/zh-TW/features-overview)。

12 

13## 代理迴圈

14 

15當您給 Claude 一項任務時,它會經歷三個階段:**收集上下文**、**採取行動**和**驗證結果**。這些階段相互融合。Claude 始終使用工具,無論是搜尋檔案以了解您的程式碼、編輯以進行變更,還是執行測試以檢查其工作。

16 

17<img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/agentic-loop.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=5f1827dec8539f38adee90ead3a85a38" alt="代理迴圈:您的提示導致 Claude 收集上下文、採取行動、驗證結果,並重複直到任務完成。您可以在任何時刻中斷。" width="720" height="280" data-path="images/agentic-loop.svg" />

18 

19迴圈會根據您的要求進行調整。關於您程式碼庫的問題可能只需要收集上下文。錯誤修復會反覆循環所有三個階段。重構可能涉及廣泛的驗證。Claude 根據從上一步學到的內容決定每一步需要什麼,將數十個操作鏈接在一起,並沿途進行課程修正。

20 

21您也是這個迴圈的一部分。您可以在任何時刻中斷以引導 Claude 朝不同方向發展、提供額外上下文,或要求它嘗試不同的方法。Claude 自主工作,但對您的輸入保持回應。

22 

23代理迴圈由兩個元件提供動力:[模型](#models)進行推理,[工具](#tools)採取行動。Claude Code 充當 Claude 周圍的**代理工具**:它提供工具、上下文管理和執行環境,將語言模型轉變為能力強大的編碼代理。

24 

25### 模型

26 

27Claude Code 使用 Claude 模型來理解您的程式碼並推理任務。Claude 可以讀取任何語言的程式碼、理解元件如何連接,以及找出需要改變什麼來完成您的目標。對於複雜任務,它將工作分解為步驟、執行它們,並根據學到的內容進行調整。

28 

29[多個模型](/zh-TW/model-config)可用,具有不同的權衡。Sonnet 可以很好地處理大多數編碼任務。Opus 為複雜的架構決策提供更強的推理能力。在會話期間使用 `/model` 切換,或使用 `claude --model <name>` 開始。

30 

31當本指南說「Claude 選擇」或「Claude 決定」時,是模型在進行推理。

32 

33### 工具

34 

35工具是使 Claude Code 成為代理的原因。沒有工具,Claude 只能用文字回應。有了工具,Claude 可以採取行動:讀取您的程式碼、編輯檔案、執行命令、搜尋網路,以及與外部服務互動。每個工具使用都會返回資訊,反饋到迴圈中,告知 Claude 的下一個決定。

36 

37內建工具通常分為五個類別,每個類別代表不同類型的代理能力。

38 

39| 類別 | Claude 可以做什麼 |

40| --------- | --------------------------------------------------------------------------------- |

41| **檔案操作** | 讀取檔案、編輯程式碼、建立新檔案、重新命名和重新組織 |

42| **搜尋** | 按模式查找檔案、使用正規表達式搜尋內容、探索程式碼庫 |

43| **執行** | 執行 shell 命令、啟動伺服器、執行測試、使用 git |

44| **網路** | 搜尋網路、擷取文件、查詢錯誤訊息 |

45| **程式碼智能** | 編輯後查看類型錯誤和警告、跳轉到定義、查找參考(需要[程式碼智能外掛程式](/zh-TW/discover-plugins#code-intelligence)) |

46 

47這些是主要功能。Claude 還具有用於生成 subagents、詢問您問題和其他編排任務的工具。請參閱[Claude 可用的工具](/zh-TW/tools-reference)以取得完整清單。

48 

49Claude 根據您的提示和沿途學到的內容選擇使用哪些工具。當您說「修復失敗的測試」時,Claude 可能會:

50 

511. 執行測試套件以查看失敗的內容

522. 讀取錯誤輸出

533. 搜尋相關的原始檔案

544. 讀取這些檔案以理解程式碼

555. 編輯檔案以修復問題

566. 再次執行測試以驗證

57 

58每個工具使用都會給 Claude 新資訊,告知下一步。這就是代理迴圈的實際運作。

59 

60**擴展基本功能:** 內建工具是基礎。您可以使用 [skills](/zh-TW/skills) 擴展 Claude 知道的內容、使用 [MCP](/zh-TW/mcp) 連接到外部服務、使用 [hooks](/zh-TW/hooks) 自動化工作流程,以及將任務卸載給 [subagents](/zh-TW/sub-agents)。這些擴展形成了核心代理迴圈之上的一層。請參閱[擴展 Claude Code](/zh-TW/features-overview) 以獲得有關為您的需求選擇正確擴展的指導。

61 

62## Claude 可以存取什麼

63 

64本指南重點介紹終端機。Claude Code 也在 [VS Code](/zh-TW/vs-code)、[JetBrains IDE](/zh-TW/jetbrains) 和其他環境中執行。

65 

66當您在目錄中執行 `claude` 時,Claude Code 可以存取:

67 

68* **您的專案。** 您目錄和子目錄中的檔案,以及其他地方經您許可的檔案。

69* **您的終端機。** 您可以執行的任何命令:建置工具、git、套件管理器、系統公用程式、指令碼。如果您可以從命令列執行,Claude 也可以。

70* **您的 git 狀態。** 目前分支、未提交的變更和最近的提交歷史。

71* **您的 [CLAUDE.md](/zh-TW/memory)。** 一個 markdown 檔案,您可以在其中儲存專案特定的指示、慣例和 Claude 應該在每個會話中知道的上下文。

72* **[自動記憶](/zh-TW/memory#auto-memory)。** Claude 在您工作時自動儲存的學習內容,例如專案模式和您的偏好。MEMORY.md 的前 200 行或 25KB(以先到者為準)在每個會話開始時載入。

73* **您設定的擴展。** 用於外部服務的 [MCP servers](/zh-TW/mcp)、用於工作流程的 [skills](/zh-TW/skills)、用於委派工作的 [subagents](/zh-TW/sub-agents),以及用於瀏覽器互動的 [Claude in Chrome](/zh-TW/chrome)。

74 

75因為 Claude 看到您的整個專案,它可以跨越它工作。當您要求 Claude「修復身份驗證錯誤」時,它會搜尋相關檔案、讀取多個檔案以理解上下文、跨它們進行協調編輯、執行測試以驗證修復,以及在您要求時提交變更。這與只看到目前檔案的內聯程式碼助手不同。

76 

77## 環境和介面

78 

79上述代理迴圈、工具和功能在您使用 Claude Code 的任何地方都是相同的。改變的是程式碼執行的位置以及您與它互動的方式。

80 

81### 執行環境

82 

83Claude Code 在三個環境中執行,每個環境對程式碼執行位置有不同的權衡。

84 

85| 環境 | 程式碼執行位置 | 使用案例 |

86| -------- | ---------------- | ----------------- |

87| **本機** | 您的機器 | 預設。完全存取您的檔案、工具和環境 |

88| **雲端** | Anthropic 管理的 VM | 卸載任務、處理您本機沒有的儲存庫 |

89| **遠端控制** | 您的機器,從瀏覽器控制 | 使用網路 UI,同時保持一切本機 |

90 

91### 介面

92 

93您可以透過終端機、[桌面應用程式](/zh-TW/desktop)、[IDE 擴展](/zh-TW/vs-code)、[claude.ai/code](https://claude.ai/code)、[遠端控制](/zh-TW/remote-control)、[Slack](/zh-TW/slack) 和 [CI/CD 管道](/zh-TW/github-actions)存取 Claude Code。介面決定了您如何看到和與 Claude 互動,但底層代理迴圈是相同的。請參閱[在任何地方使用 Claude Code](/zh-TW/overview#use-claude-code-everywhere) 以取得完整清單。

94 

95## 使用會話

96 

97Claude Code 在您工作時將您的對話儲存在本機。每條訊息、工具使用和結果都被儲存,這使得[重新開始](#undo-changes-with-checkpoints)、[恢復和分叉](#resume-or-fork-sessions)會話成為可能。在 Claude 進行程式碼變更之前,它還會快照受影響的檔案,以便您在需要時可以還原。

98 

99**會話是獨立的。** 每個新會話都以新的上下文視窗開始,沒有來自先前會話的對話歷史。Claude 可以使用[自動記憶](/zh-TW/memory#auto-memory)跨會話保留學習內容,您可以在 [CLAUDE.md](/zh-TW/memory) 中新增自己的持久指示。

100 

101### 跨分支工作

102 

103每個 Claude Code 對話都是綁定到您目前目錄的會話。當您恢復時,您只會看到該目錄中的會話。

104 

105Claude 看到您目前分支的檔案。當您切換分支時,Claude 看到新分支的檔案,但您的對話歷史保持不變。Claude 記得您討論過的內容,即使在切換後也是如此。

106 

107由於會話綁定到目錄,您可以使用 [git worktrees](/zh-TW/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees) 執行平行 Claude 會話,這會為個別分支建立單獨的目錄。

108 

109### 恢復或分叉會話

110 

111當您使用 `claude --continue` 或 `claude --resume` 恢復會話時,您使用相同的會話 ID 從中斷的地方繼續。新訊息附加到現有對話。您的完整對話歷史被還原,但會話範圍的許可不被還原。您需要重新批准這些。

112 

113<img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/session-continuity.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=fa41d12bfb57579cabfeece907151d30" alt="會話連續性:恢復繼續相同的會話,分叉使用新 ID 建立新分支。" width="560" height="280" data-path="images/session-continuity.svg" />

114 

115要分叉並嘗試不同的方法而不影響原始會話,請使用 `--fork-session` 旗標:

116 

117```bash theme={null}

118claude --continue --fork-session

119```

120 

121這會建立新的會話 ID,同時保留該點之前的對話歷史。原始會話保持不變。與恢復一樣,分叉的會話不會繼承會話範圍的許可。

122 

123**在多個終端機中的相同會話**:如果您在多個終端機中恢復相同的會話,兩個終端機都會寫入相同的會話檔案。來自兩者的訊息會交錯,就像兩個人在同一個筆記本中寫字。沒有任何內容損壞,但對話變得混亂。每個終端機在會話期間只看到自己的訊息,但如果您稍後恢復該會話,您會看到所有內容交錯。對於從相同起點進行的平行工作,使用 `--fork-session` 為每個終端機提供自己的乾淨會話。

124 

125### 上下文視窗

126 

127Claude 的上下文視窗保存您的對話歷史、檔案內容、命令輸出、[CLAUDE.md](/zh-TW/memory)、[自動記憶](/zh-TW/memory#auto-memory)、載入的 skills 和系統指示。當您工作時,上下文會填滿。Claude 會自動壓縮,但對話早期的指示可能會丟失。將持久規則放在 CLAUDE.md 中,並執行 `/context` 以查看什麼在使用空間。

128 

129如需互動式逐步說明,請參閱[探索上下文視窗](/zh-TW/context-window)。

130 

131#### 當上下文填滿時

132 

133Claude Code 在您接近限制時自動管理上下文。它首先清除較舊的工具輸出,然後在需要時總結對話。您的請求和關鍵程式碼片段被保留;對話早期的詳細指示可能會丟失。將持久規則放在 CLAUDE.md 中,而不是依賴對話歷史。

134 

135要控制在壓縮期間保留的內容,請在 CLAUDE.md 中新增「Compact Instructions」部分或使用焦點執行 `/compact`(如 `/compact focus on the API changes`)。

136 

137執行 `/context` 以查看什麼在使用空間。MCP 工具定義預設會延遲,並透過[工具搜尋](/zh-TW/mcp#scale-with-mcp-tool-search)按需載入,因此只有工具名稱會消耗上下文,直到 Claude 使用特定工具。執行 `/mcp` 以檢查每個伺服器的成本。

138 

139#### 使用 skills 和 subagents 管理上下文

140 

141除了壓縮,您可以使用其他功能來控制什麼載入到上下文中。

142 

143[Skills](/zh-TW/skills) 按需載入。Claude 在會話開始時看到 skill 描述,但完整內容只在使用 skill 時載入。對於您手動呼叫的 skills,設定 `disable-model-invocation: true` 以將描述保留在上下文之外,直到您需要它們。

144 

145[Subagents](/zh-TW/sub-agents) 獲得自己的新上下文,完全與您的主要對話分開。他們的工作不會使您的上下文膨脹。完成後,他們返回摘要。這種隔離是 subagents 在長會話中有幫助的原因。

146 

147請參閱[上下文成本](/zh-TW/features-overview#understand-context-costs)以了解每個功能的成本,以及[減少令牌使用](/zh-TW/costs#reduce-token-usage)以獲得管理上下文的提示。

148 

149## 使用檢查點和許可保持安全

150 

151Claude 有兩個安全機制:檢查點讓您撤銷檔案變更,許可控制 Claude 可以在不詢問的情況下執行的操作。

152 

153### 使用檢查點撤銷變更

154 

155**每個檔案編輯都是可逆的。** 在 Claude 編輯任何檔案之前,它會快照目前內容。如果出現問題,按 `Esc` 兩次以重新開始到先前狀態,或要求 Claude 撤銷。

156 

157檢查點是會話本機的,與 git 分開。它們只涵蓋檔案變更。影響遠端系統的操作(資料庫、API、部署)無法檢查點,這就是為什麼 Claude 在執行具有外部副作用的命令之前詢問。

158 

159### 控制 Claude 可以做什麼

160 

161按 `Shift+Tab` 循環通過許可模式:

162 

163* **預設**:Claude 在檔案編輯和 shell 命令之前詢問

164* **自動接受編輯**:Claude 編輯檔案而不詢問,仍然詢問命令

165* **Plan Mode**:Claude 僅使用唯讀工具,建立您可以在執行前批准的計畫

166* **Auto mode**:Claude 使用背景安全檢查評估所有操作。目前是研究預覽

167 

168您也可以在 `.claude/settings.json` 中允許特定命令,以便 Claude 不會每次都詢問。這對於受信任的命令(如 `npm test` 或 `git status`)很有用。設定可以從組織範圍的政策範圍到個人偏好。請參閱[許可](/zh-TW/permissions)以取得詳細資訊。

169 

170***

171 

172## 有效使用 Claude Code

173 

174這些提示可幫助您從 Claude Code 獲得更好的結果。

175 

176### 向 Claude Code 尋求幫助

177 

178Claude Code 可以教您如何使用它。提出問題,例如「我如何設定 hooks?」或「構建我的 CLAUDE.md 的最佳方式是什麼?」,Claude 會解釋。

179 

180內建命令也會引導您完成設定:

181 

182* `/init` 引導您為您的專案建立 CLAUDE.md

183* `/agents` 幫助您設定自訂 subagents

184* `/doctor` 診斷您的安裝的常見問題

185 

186### 這是一個對話

187 

188Claude Code 是對話式的。您不需要完美的提示。從您想要的開始,然後細化:

189 

190```text theme={null}

191修復登入錯誤

192```

193 

194\[Claude 調查,嘗試一些東西]

195 

196```text theme={null}

197這不太對。問題在於會話處理。

198```

199 

200\[Claude 調整方法]

201 

202當第一次嘗試不正確時,您不會重新開始。您進行迭代。

203 

204#### 中斷和引導

205 

206您可以在任何時刻中斷 Claude。如果它走錯了路,只需輸入您的更正並按 Enter。Claude 將停止正在執行的操作,並根據您的輸入調整其方法。您不必等待它完成或重新開始。

207 

208### 預先具體

209 

210您的初始提示越精確,您需要的更正就越少。參考特定檔案、提及約束,並指出範例模式。

211 

212```text theme={null}

213結帳流程對於具有過期卡的使用者已損壞。

214檢查 src/payments/ 以查找問題,特別是令牌刷新。

215先寫一個失敗的測試,然後修復它。

216```

217 

218模糊的提示有效,但您會花更多時間引導。像上面這樣的具體提示通常在第一次嘗試時成功。

219 

220### 給 Claude 一些東西來驗證

221 

222Claude 在能夠檢查自己的工作時表現更好。包括測試案例、貼上預期 UI 的螢幕截圖,或定義您想要的輸出。

223 

224```text theme={null}

225實現 validateEmail。測試案例:'user@example.com' → true,

226'invalid' → false,'user@.com' → false。之後執行測試。

227```

228 

229對於視覺工作,貼上設計的螢幕截圖,並要求 Claude 將其實現與其進行比較。

230 

231### 在實現之前探索

232 

233對於複雜的問題,將研究與編碼分開。使用計畫模式(按 `Shift+Tab` 兩次)首先分析程式碼庫:

234 

235```text theme={null}

236讀取 src/auth/ 並理解我們如何處理會話。

237然後為新增 OAuth 支援建立計畫。

238```

239 

240檢查計畫,透過對話細化它,然後讓 Claude 實現。這種兩階段方法比直接跳到程式碼產生更好的結果。

241 

242### 委派,不要指示

243 

244想像委派給一位能力強大的同事。提供上下文和方向,然後相信 Claude 會找出詳細資訊:

245 

246```text theme={null}

247結帳流程對於具有過期卡的使用者已損壞。

248相關程式碼在 src/payments/ 中。您可以調查並修復它嗎?

249```

250 

251您不需要指定要讀取哪些檔案或執行哪些命令。Claude 會找出來。

252 

253## 接下來

254 

255<CardGroup cols={2}>

256 <Card title="使用功能擴展" icon="puzzle-piece" href="/zh-TW/features-overview">

257 新增 Skills、MCP 連接和自訂命令

258 </Card>

259 

260 <Card title="常見工作流程" icon="graduation-cap" href="/zh-TW/common-workflows">

261 典型任務的逐步指南

262 </Card>

263</CardGroup>

interactive-mode.md +362 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 互動模式

6 

7> Claude Code 會話中鍵盤快捷鍵、輸入模式和互動功能的完整參考。

8 

9## 鍵盤快捷鍵

10 

11<Note>

12 鍵盤快捷鍵可能因平台和終端而異。按 `?` 查看您環境中可用的快捷鍵。

13 

14 **macOS 使用者**:Option/Alt 鍵快捷鍵(`Alt+B`、`Alt+F`、`Alt+Y`、`Alt+M`、`Alt+P`、`Alt+T`)需要在終端中將 Option 配置為 Meta:

15 

16 * **iTerm2**:設定 → Profiles → Keys → General → 將 Left/Right Option 鍵設定為「Esc+」

17 * **Apple Terminal**:設定 → Profiles → Keyboard → 勾選「Use Option as Meta Key」

18 * **VS Code**:在 VS Code 設定中設定 `"terminal.integrated.macOptionIsMeta": true`

19 

20 詳見[終端配置](/zh-TW/terminal-config)。

21</Note>

22 

23### 一般控制

24 

25| 快捷鍵 | 說明 | 上下文 |

26| :------------------------------------------- | :-------------------- | :---------------------------------------------------------------------------------------------------------------------------------------- |

27| `Ctrl+C` | 取消目前輸入或生成 | 標準中斷 |

28| `Ctrl+X Ctrl+K` | 終止所有背景代理。在 3 秒內按兩次以確認 | 背景代理控制 |

29| `Ctrl+D` | 退出 Claude Code 會話 | EOF 信號 |

30| `Ctrl+G` 或 `Ctrl+X Ctrl+E` | 在預設文字編輯器中開啟 | 在預設文字編輯器中編輯您的提示或自訂回應。`Ctrl+X Ctrl+E` 是 readline 原生繫結。在 `/config` 中開啟「在外部編輯器中顯示最後回應」,以在您的提示上方將 Claude 的先前回覆作為 `#` 註解上下文預先加入;當您儲存時,註解區塊會被移除 |

31| `Ctrl+L` | 重繪螢幕 | 強制完整終端重繪。輸入和對話歷史會保留。如果顯示變得混亂或部分空白,請使用此選項恢復 |

32| `Ctrl+O` | 切換文字記錄檢視器 | 顯示詳細的工具使用和執行情況。也會展開 MCP 呼叫,預設情況下會摺疊為單行,例如「Called slack 3 times」 |

33| `Ctrl+R` | 反向搜尋命令歷史 | 以互動方式搜尋先前的命令 |

34| `Ctrl+V` 或 `Cmd+V`(iTerm2)或 `Alt+V`(Windows) | 從剪貼簿貼上影像 | 在游標處插入 `[Image #N]` 晶片,以便您可以在提示中按位置參考它 |

35| `Ctrl+B` | 背景執行工作 | 將 bash 命令和代理放在背景執行。Tmux 使用者按兩次 |

36| `Ctrl+T` | 切換工作清單 | 在終端狀態區域中顯示或隱藏[工作清單](#task-list) |

37| `Left/Right arrows` | 在對話框標籤之間循環 | 在權限對話框和選單中的標籤之間導航 |

38| `Up/Down arrows` 或 `Ctrl+P`/`Ctrl+N` | 移動游標或導航命令歷史 | 在多行輸入中,首先在提示內移動游標。一旦游標已在頂部或底部邊緣,再次按下會導航命令歷史 |

39| `Esc` + `Esc` | 回溯或摘要 | 將程式碼和/或對話恢復到先前的點,或從選定的訊息進行摘要 |

40| `Shift+Tab` 或 `Alt+M`(某些配置) | 循環權限模式 | 在 `default`、`acceptEdits`、`plan` 和您啟用的任何模式(例如 `auto` 或 `bypassPermissions`)之間循環。詳見[權限模式](/zh-TW/permission-modes)。 |

41| `Option+P`(macOS)或 `Alt+P`(Windows/Linux) | 切換模型 | 在不清除提示的情況下切換模型 |

42| `Option+T`(macOS)或 `Alt+T`(Windows/Linux) | 切換擴展思考 | 啟用或停用擴展思考模式。在 macOS 上,配置您的終端以傳送 Option 作為 Meta,此快捷鍵才能運作 |

43| `Option+O`(macOS)或 `Alt+O`(Windows/Linux) | 切換快速模式 | 啟用或停用[快速模式](/zh-TW/fast-mode) |

44 

45### 文字編輯

46 

47| 快捷鍵 | 說明 | 上下文 |

48| :--------------------- | :---------- | :------------------------------------------------------------------------------------------- |

49| `Ctrl+A` | 將游標移至目前行的開始 | 在多行輸入中,移至目前邏輯行的開始 |

50| `Ctrl+E` | 將游標移至目前行的結尾 | 在多行輸入中,移至目前邏輯行的結尾 |

51| `Ctrl+K` | 刪除到行尾 | 儲存已刪除的文字以供貼上 |

52| `Ctrl+U` | 從游標刪除到行首 | 儲存已刪除的文字以供貼上。重複以清除多行輸入中的行。在 macOS 上,終端模擬器(包括 iTerm2 和 Terminal.app)將 `Cmd+Backspace` 對應到此快捷鍵 |

53| `Ctrl+W` | 刪除上一個單字 | 儲存已刪除的文字以供貼上。在 Windows 上,`Ctrl+Backspace` 也會刪除上一個單字 |

54| `Ctrl+Y` | 貼上已刪除的文字 | 貼上使用 `Ctrl+K`、`Ctrl+U` 或 `Ctrl+W` 刪除的文字 |

55| `Alt+Y`(在 `Ctrl+Y` 之後) | 循環貼上歷史 | 貼上後,循環瀏覽先前刪除的文字。在 macOS 上需要[將 Option 設定為 Meta](#keyboard-shortcuts) |

56| `Alt+B` | 將游標向後移動一個單字 | 單字導航。在 macOS 上需要[將 Option 設定為 Meta](#keyboard-shortcuts) |

57| `Alt+F` | 將游標向前移動一個單字 | 單字導航。在 macOS 上需要[將 Option 設定為 Meta](#keyboard-shortcuts) |

58 

59### 主題和顯示

60 

61| 快捷鍵 | 說明 | 上下文 |

62| :------- | :------------- | :--------------------------------------------- |

63| `Ctrl+T` | 切換程式碼區塊的語法醒目提示 | 僅在 `/theme` 選擇器選單內有效。控制 Claude 回應中的程式碼是否使用語法著色 |

64 

65### 多行輸入

66 

67| 方法 | 快捷鍵 | 上下文 |

68| :---------- | :------------- | :------------------------------------------------------------------------------------------- |

69| 快速逃脫 | `\` + `Enter` | 適用於所有終端 |

70| Option 鍵 | `Option+Enter` | 在 macOS 上啟用[將 Option 設定為 Meta](/zh-TW/terminal-config#enable-option-key-shortcuts-on-macos)後 |

71| Shift+Enter | `Shift+Enter` | 在 iTerm2、WezTerm、Ghostty、Kitty、Warp、Apple Terminal 中開箱即用 |

72| 控制序列 | `Ctrl+J` | 在任何終端中無需配置即可使用 |

73| 貼上模式 | 直接貼上 | 適用於程式碼區塊、日誌 |

74 

75<Tip>

76 Shift+Enter 在 iTerm2、WezTerm、Ghostty、Kitty、Warp 和 Apple Terminal 中無需配置即可使用。對於 VS Code、Cursor、Windsurf、Alacritty 和 Zed,執行 `/terminal-setup` 以安裝繫結。

77</Tip>

78 

79### 快速命令

80 

81| 快捷鍵 | 說明 | 備註 |

82| :------ | :-------- | :----------------------------------------- |

83| `/` 在開始 | 命令或 skill | 詳見[命令](#commands)和 [skills](/zh-TW/skills) |

84| `!` 在開始 | Bash 模式 | 直接執行命令並將執行輸出新增到會話 |

85| `@` | 檔案路徑提及 | 觸發檔案路徑自動完成 |

86 

87### 文字記錄檢視器

88 

89當文字記錄檢視器開啟時(使用 `Ctrl+O` 切換),這些快捷鍵可用。`Ctrl+E` 可以透過 [`transcript:toggleShowAll`](/zh-TW/keybindings) 重新繫結。

90 

91| 快捷鍵 | 說明 |

92| :----------------- | :---------------------------------------------------------------------------------------------------------------- |

93| `Ctrl+E` | 切換顯示所有內容 |

94| `[` | 將完整對話寫入終端的原生滾動回溯,以便 `Cmd+F`、tmux 複製模式和其他原生工具可以搜尋它。需要[全螢幕渲染](/zh-TW/fullscreen#search-and-review-the-conversation) |

95| `v` | 將對話寫入臨時檔案並在 `$VISUAL` 或 `$EDITOR` 中開啟它。需要[全螢幕渲染](/zh-TW/fullscreen) |

96| `q`、`Ctrl+C`、`Esc` | 退出文字記錄檢視。所有三個都可以透過 [`transcript:exit`](/zh-TW/keybindings) 重新繫結 |

97 

98### 語音輸入

99 

100| 快捷鍵 | 說明 | 備註 |

101| :------------ | :--- | :------------------------------------------------------------------------------------------------------------------------- |

102| 按住或點擊 `Space` | 語音聽寫 | 需要啟用[語音聽寫](/zh-TW/voice-dictation)。按住以錄製,或執行 `/voice tap` 以進行點擊切換。[可重新繫結](/zh-TW/voice-dictation#rebind-the-dictation-key) |

103 

104## 命令

105 

106在 Claude Code 中輸入 `/` 以查看所有可用命令,或輸入 `/` 後跟任何字母以篩選。`/` 選單顯示您可以呼叫的所有內容:內建命令、捆綁和使用者撰寫的 [skills](/zh-TW/skills),以及由 [plugins](/zh-TW/plugins) 和 [MCP servers](/zh-TW/mcp#use-mcp-prompts-as-commands) 貢獻的命令。並非所有內建命令對每個使用者都可見,因為某些命令取決於您的平台或計畫。

107 

108詳見[命令參考](/zh-TW/commands)以取得 Claude Code 中包含的命令的完整清單。

109 

110## Vim 編輯器模式

111 

112透過 `/config` → Editor mode 啟用 vim 風格編輯。

113 

114### 模式切換

115 

116| 命令 | 動作 | 來自模式 |

117| :---- | :----------- | :------------ |

118| `Esc` | 進入 NORMAL 模式 | INSERT、VISUAL |

119| `i` | 在游標前插入 | NORMAL |

120| `I` | 在行首插入 | NORMAL |

121| `a` | 在游標後插入 | NORMAL |

122| `A` | 在行尾插入 | NORMAL |

123| `o` | 在下方開啟行 | NORMAL |

124| `O` | 在上方開啟行 | NORMAL |

125| `v` | 開始字元式視覺選擇 | NORMAL |

126| `V` | 開始行式視覺選擇 | NORMAL |

127 

128### 導航(NORMAL 模式)

129 

130| 命令 | 動作 |

131| :-------------- | :----------------- |

132| `h`/`j`/`k`/`l` | 向左/向下/向上/向右移動 |

133| `w` | 下一個單字 |

134| `e` | 單字結尾 |

135| `b` | 上一個單字 |

136| `0` | 行首 |

137| `$` | 行尾 |

138| `^` | 第一個非空白字元 |

139| `gg` | 輸入開始 |

140| `G` | 輸入結尾 |

141| `f{char}` | 跳到下一個字元出現位置 |

142| `F{char}` | 跳到上一個字元出現位置 |

143| `t{char}` | 跳到下一個字元出現位置之前 |

144| `T{char}` | 跳到上一個字元出現位置之後 |

145| `;` | 重複上一個 f/F/t/T 動作 |

146| `,` | 反向重複上一個 f/F/t/T 動作 |

147 

148<Note>

149 在 vim 正常模式中,如果游標位於輸入的開始或結尾且無法進一步移動,`j`/`k` 和箭頭鍵將導航命令歷史。

150</Note>

151 

152### 編輯(NORMAL 模式)

153 

154| 命令 | 動作 |

155| :------------- | :---------- |

156| `x` | 刪除字元 |

157| `dd` | 刪除行 |

158| `D` | 刪除到行尾 |

159| `dw`/`de`/`db` | 刪除單字/到結尾/向後 |

160| `cc` | 變更行 |

161| `C` | 變更到行尾 |

162| `cw`/`ce`/`cb` | 變更單字/到結尾/向後 |

163| `yy`/`Y` | 複製行 |

164| `yw`/`ye`/`yb` | 複製單字/到結尾/向後 |

165| `p` | 在游標後貼上 |

166| `P` | 在游標前貼上 |

167| `>>` | 縮排行 |

168| `<<` | 取消縮排行 |

169| `J` | 合併行 |

170| `u` | 復原 |

171| `.` | 重複上一個變更 |

172 

173### 文字物件(NORMAL 模式)

174 

175文字物件與運算子(如 `d`、`c` 和 `y`)搭配使用:

176 

177| 命令 | 動作 |

178| :-------- | :---------------- |

179| `iw`/`aw` | 內部/周圍單字 |

180| `iW`/`aW` | 內部/周圍 WORD(以空白分隔) |

181| `i"`/`a"` | 內部/周圍雙引號 |

182| `i'`/`a'` | 內部/周圍單引號 |

183| `i(`/`a(` | 內部/周圍括號 |

184| `i[`/`a[` | 內部/周圍方括號 |

185| `i{`/`a{` | 內部/周圍大括號 |

186 

187### 視覺模式

188 

189按 `v` 進行字元式選擇或按 `V` 進行行式選擇。動作會擴展選擇,運算子直接作用於選擇。

190 

191| 命令 | 動作 |

192| :--------------- | :------------------- |

193| `d`/`x` | 刪除選擇 |

194| `y` | 複製選擇 |

195| `c`/`s` | 變更選擇 |

196| `p` | 用暫存器內容取代選擇 |

197| `r{char}` | 將每個選定的字元取代為 `{char}` |

198| `~`/`u`/`U` | 切換、小寫或大寫選擇 |

199| `>`/`<` | 縮排或取消縮排選定的行 |

200| `J` | 合併選定的行 |

201| `o` | 交換游標和錨點 |

202| `iw`/`aw`/`i"`/… | 選擇文字物件 |

203| `v`/`V` | 在字元式和行式之間切換,或退出 |

204 

205不支援使用 `Ctrl+V` 的區塊式視覺模式。

206 

207## 命令歷史

208 

209Claude Code 維護目前會話的命令歷史:

210 

211* 輸入歷史按工作目錄儲存

212* 當您執行 `/clear` 以開始新會話時,輸入歷史會重設。先前會話的對話會被保留,可以繼續進行。

213* 使用向上/向下箭頭導航(請參閱上面的快捷鍵)

214* **注意**:歷史擴展(`!`)預設停用

215 

216### 使用 Ctrl+R 進行反向搜尋

217 

218按 `Ctrl+R` 以互動方式搜尋您的命令歷史:

219 

2201. **開始搜尋**:按 `Ctrl+R` 啟動反向歷史搜尋

2212. **輸入查詢**:輸入文字以在先前的命令中搜尋。搜尋詞在匹配結果中醒目提示

2223. **導航匹配項**:再次按 `Ctrl+R` 以循環瀏覽較舊的匹配項

2234. **變更範圍**:按 `Ctrl+S` 以在此會話、此專案和所有專案之間循環

2245. **接受匹配項**:

225 * 按 `Tab` 或 `Esc` 以接受目前匹配項並繼續編輯

226 * 按 `Enter` 以接受並立即執行命令

2276. **取消搜尋**:

228 * 按 `Ctrl+C` 以取消並恢復您的原始輸入

229 * 在空搜尋上按 `Backspace` 以取消

230 

231搜尋顯示匹配的命令,搜尋詞醒目提示,因此您可以找到並重複使用先前的輸入。

232 

233## 背景 bash 命令

234 

235Claude Code 支援在背景執行 bash 命令,允許您在長時間執行的程序執行時繼續工作。

236 

237### 背景執行的工作原理

238 

239當 Claude Code 在背景執行命令時,它會非同步執行命令並立即傳回背景工作 ID。Claude Code 可以在命令在背景繼續執行時回應新提示。

240 

241若要在背景執行命令,您可以:

242 

243* 提示 Claude Code 在背景執行命令

244* 按 Ctrl+B 將常規 Bash 工具呼叫移到背景。(Tmux 使用者必須按 Ctrl+B 兩次,因為 tmux 的前綴鍵。)

245 

246**主要功能:**

247 

248* 輸出被寫入檔案,Claude 可以使用 Read 工具檢索它

249* 背景工作有唯一的 ID 用於追蹤和輸出檢索

250* 背景工作在 Claude Code 退出時會自動清理

251* 如果輸出超過 5GB,背景工作會自動終止,stderr 中會有說明原因的備註

252 

253若要停用所有背景工作功能,請將 `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` 環境變數設定為 `1`。詳見[環境變數](/zh-TW/env-vars)。

254 

255**常見的背景執行命令:**

256 

257* 建置工具(webpack、vite、make)

258* 套件管理器(npm、yarn、pnpm)

259* 測試執行器(jest、pytest)

260* 開發伺服器

261* 長時間執行的程序(docker、terraform)

262 

263### 使用 `!` 前綴的 Bash 模式

264 

265透過在輸入前加上 `!` 直接執行 bash 命令,無需透過 Claude:

266 

267```bash theme={null}

268! npm test

269! git status

270! ls -la

271```

272 

273Bash 模式:

274 

275* 將命令及其輸出新增到對話上下文

276* 顯示即時進度和輸出

277* 支援相同的 `Ctrl+B` 背景執行,用於長時間執行的命令

278* 不需要 Claude 解釋或批准命令

279* 支援基於歷史的自動完成:輸入部分命令並按 **Tab** 以從目前專案中的先前 `!` 命令完成

280* 使用 `Escape`、`Backspace` 或在空提示上使用 `Ctrl+U` 退出

281* 將以 `!` 開頭的貼上文字貼到空提示中會自動進入 bash 模式,符合輸入的 `!` 行為

282 

283這對於快速 shell 操作同時維護對話上下文很有用。

284 

285## 提示建議

286 

287當您首次開啟會話時,提示輸入中會出現灰色的範例命令以幫助您開始。Claude Code 從您的專案的 git 歷史中選擇此項,因此它反映您最近一直在處理的檔案。

288 

289Claude 回應後,建議會根據您的對話歷史繼續出現,例如多部分請求的後續步驟或工作流程的自然延續。

290 

291* 按 **Tab** 或 **Right arrow** 以接受建議,或按 **Enter** 以接受並提交

292* 開始輸入以關閉它

293 

294建議作為背景請求執行,該請求重複使用父對話的提示快取,因此額外成本最少。當快取冷時,Claude Code 會跳過建議生成以避免不必要的成本。

295 

296在對話的第一輪之後、在非互動模式中以及在 Plan Mode 中,建議會自動跳過。

297 

298若要完全停用提示建議,請設定環境變數或在 `/config` 中切換設定:

299 

300```bash theme={null}

301export CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false

302```

303 

304## 使用 /btw 的側面問題

305 

306使用 `/btw` 詢問有關您目前工作的快速問題,而不將其新增到對話歷史。當您想要快速答案但不想雜亂主要上下文或使 Claude 偏離長時間執行的工作時,這很有用。

307 

308```

309/btw what was the name of that config file again?

310```

311 

312側面問題可以完全看到目前對話,因此您可以詢問 Claude 已經讀過的程式碼、它之前做出的決定或會話中的任何其他內容。問題和答案是短暫的:它們出現在可關閉的覆蓋層中,永遠不會進入對話歷史。

313 

314* **Claude 工作時可用**:即使 Claude 正在處理回應時,您也可以執行 `/btw`。側面問題獨立執行,不會中斷主要輪次。

315* **無工具存取**:側面問題僅從已在上下文中的內容回答。Claude 在回答側面問題時無法讀取檔案、執行命令或搜尋。

316* **單一回應**:沒有後續輪次。如果您需要來回往返,請改用正常提示。

317* **低成本**:側面問題重複使用父對話的提示快取,因此額外成本最少。

318 

319按 **Space**、**Enter** 或 **Escape** 以關閉答案並返回提示。

320 

321`/btw` 是 [subagent](/zh-TW/sub-agents) 的反面:它看到您的完整對話但沒有工具,而 subagent 有完整工具但以空上下文開始。使用 `/btw` 詢問 Claude 從此會話已知的內容;使用 subagent 去發現新的東西。

322 

323## 工作清單

324 

325在處理複雜的多步驟工作時,Claude 會建立工作清單以追蹤進度。工作出現在終端的狀態區域中,指示器顯示待處理、進行中或完成的內容。

326 

327* 按 `Ctrl+T` 以切換工作清單檢視。顯示一次最多 5 個工作

328* 若要查看所有工作或清除它們,直接詢問 Claude:「show me all tasks」或「clear all tasks」

329* 工作在上下文壓縮中持續存在,幫助 Claude 在較大的專案上保持組織

330* 若要在會話之間共享工作清單,請設定 `CLAUDE_CODE_TASK_LIST_ID` 以使用 `~/.claude/tasks/` 中的命名目錄:`CLAUDE_CODE_TASK_LIST_ID=my-project claude`

331 

332## 會話摘要

333 

334當您在離開終端後返回時,Claude Code 會顯示到目前為止會話中發生的情況的單行摘要。摘要在背景中生成,一旦自上次完成的輪次以來至少已過三分鐘且終端未聚焦,就會準備好。摘要僅在會話至少有三個輪次後出現,且永遠不會連續出現兩次。

335 

336執行 `/recap` 以按需生成摘要。若要關閉自動摘要,請開啟 `/config` 並停用**會話摘要**。

337 

338會話摘要在每個計畫和提供者上預設開啟。摘要在非互動模式中始終被跳過。

339 

340## PR 審查狀態

341 

342在處理具有開啟拉取請求的分支時,Claude Code 在頁尾顯示可點擊的 PR 連結(例如「PR #446」)。連結有一個彩色底線,指示審查狀態:

343 

344* 綠色:已批准

345* 黃色:待審查

346* 紅色:要求變更

347* 灰色:草稿

348* 紫色:已合併

349 

350`Cmd+click`(Mac)或 `Ctrl+click`(Windows/Linux)連結以在瀏覽器中開啟拉取請求。狀態每 60 秒自動更新。

351 

352<Note>

353 PR 狀態需要安裝並驗證 `gh` CLI(`gh auth login`)。

354</Note>

355 

356## 另請參閱

357 

358* [Skills](/zh-TW/skills) - 自訂提示和工作流程

359* [Checkpointing](/zh-TW/checkpointing) - 回溯 Claude 的編輯並恢復先前的狀態

360* [CLI 參考](/zh-TW/cli-reference) - 命令列旗標和選項

361* [設定](/zh-TW/settings) - 配置選項

362* [記憶體管理](/zh-TW/memory) - 管理 CLAUDE.md 檔案

jetbrains.md +192 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# JetBrains IDEs

6 

7> 使用 Claude Code 與 JetBrains IDEs(包括 IntelliJ、PyCharm、WebStorm 等)整合

8 

9Claude Code 透過專用外掛程式與 JetBrains IDEs 整合,提供互動式差異檢視、選擇內容共享等功能。

10 

11## 支援的 IDEs

12 

13Claude Code 外掛程式適用於大多數 JetBrains IDEs,包括:

14 

15* IntelliJ IDEA

16* PyCharm

17* Android Studio

18* WebStorm

19* PhpStorm

20* GoLand

21 

22## 功能

23 

24* **快速啟動**:使用 `Cmd+Esc`(Mac)或 `Ctrl+Esc`(Windows/Linux)直接從編輯器開啟 Claude Code,或點擊 UI 中的 Claude Code 按鈕

25* **差異檢視**:程式碼變更可直接在 IDE 差異檢視器中顯示,而不是在終端機中

26* **選擇內容共享**:IDE 中的目前選擇或分頁會自動與 Claude Code 共享

27* **檔案參考快捷方式**:使用 `Cmd+Option+K`(Mac)或 `Alt+Ctrl+K`(Linux/Windows)插入檔案參考,例如 `@src/auth.ts#L1-99`

28* **診斷共享**:IDE 中的診斷錯誤(例如 lint 和語法錯誤)會在您工作時自動與 Claude 共享

29 

30## 安裝

31 

32### Marketplace 安裝

33 

34從 JetBrains marketplace 尋找並安裝 [Claude Code 外掛程式](https://plugins.jetbrains.com/plugin/27310-claude-code-beta-),然後重新啟動您的 IDE。

35 

36如果您還未安裝 Claude Code,請參閱[快速入門指南](/zh-TW/quickstart)以取得安裝說明。

37 

38<Note>

39 安裝外掛程式後,您可能需要完全重新啟動 IDE 才能使其生效。

40</Note>

41 

42## 使用方式

43 

44### 從您的 IDE

45 

46從 IDE 的整合終端機執行 `claude`,所有整合功能將處於活躍狀態。

47 

48### 從外部終端機

49 

50在任何外部終端機中使用 `/ide` 命令,將 Claude Code 連接到您的 JetBrains IDE 並啟動所有功能:

51 

52```bash theme={null}

53claude

54```

55 

56```text theme={null}

57/ide

58```

59 

60如果您希望 Claude 能夠存取與 IDE 相同的檔案,請從與 IDE 專案根目錄相同的目錄啟動 Claude Code。

61 

62## 設定

63 

64### Claude Code 設定

65 

66透過 Claude Code 的設定來設定 IDE 整合:

67 

681. 執行 `claude`

692. 輸入 `/config` 命令

703. 將差異工具設定為 `auto` 以在 IDE 中顯示差異,或設定為 `terminal` 以在終端機中保留差異

71 

72### 外掛程式設定

73 

74透過前往 **Settings → Tools → Claude Code \[Beta]** 來設定 Claude Code 外掛程式:

75 

76#### 一般設定

77 

78* **Claude 命令**:指定自訂命令以執行 Claude,例如 `claude`、`/usr/local/bin/claude` 或 `npx @anthropic-ai/claude-code`

79* **抑制找不到 Claude 命令的通知**:略過有關找不到 Claude 命令的通知

80* **啟用使用 Option+Enter 進行多行提示**:僅限 macOS。啟用時,Option+Enter 會在 Claude Code 提示中插入新行。如果遇到 Option 鍵被意外捕獲的問題,請停用此選項。需要終端機重新啟動。

81* **啟用自動更新**:自動檢查並安裝外掛程式更新,在重新啟動時套用

82 

83<Tip>

84 對於 WSL 使用者:將 `wsl -d Ubuntu -- bash -lic "claude"` 設定為您的 Claude 命令(將 `Ubuntu` 替換為您的 WSL 發行版名稱)

85</Tip>

86 

87#### ESC 鍵設定

88 

89如果 ESC 鍵無法在 JetBrains 終端機中中斷 Claude Code 操作:

90 

911. 前往 **Settings → Tools → Terminal**

922. 執行下列其中一項:

93 * 取消勾選「使用 Escape 將焦點移至編輯器」,或

94 * 點擊「設定終端機快捷鍵」並刪除「切換焦點至編輯器」快捷方式

953. 套用變更

96 

97這將允許 ESC 鍵正確中斷 Claude Code 操作。

98 

99## 特殊設定

100 

101### 遠端開發

102 

103<Warning>

104 使用 JetBrains 遠端開發時,您必須透過 **Settings → Plugin (Host)** 在遠端主機上安裝外掛程式。

105</Warning>

106 

107外掛程式必須安裝在遠端主機上,而不是在您的本機用戶端機器上。

108 

109### WSL 設定

110 

111如果您在 WSL2 上使用 Claude Code 搭配 JetBrains IDE,並看到「未偵測到可用的 IDEs」,原因通常是 WSL2 的 NAT 網路或 Windows 防火牆阻止了 WSL2 與在 Windows 主機上執行的 IDE 之間的連線。WSL1 直接使用主機的網路,不受影響。

112 

113#### 允許 WSL2 流量通過 Windows 防火牆

114 

115這是建議的修復方式,因為它保持您現有的 WSL2 網路模式。

116 

117<Steps>

118 <Step title="尋找您的 WSL2 IP 位址">

119 從您的 WSL shell 內執行:

120 

121 ```bash theme={null}

122 hostname -I

123 ```

124 

125 記下子網路,例如 `172.21.123.45` 在 `172.21.0.0/16` 中。

126 </Step>

127 

128 <Step title="建立防火牆規則">

129 以系統管理員身份開啟 PowerShell 並執行以下命令,調整 IP 範圍以符合您的子網路:

130 

131 ```powershell theme={null}

132 New-NetFirewallRule -DisplayName "Allow WSL2 Internal Traffic" -Direction Inbound -Protocol TCP -Action Allow -RemoteAddress 172.21.0.0/16 -LocalAddress 172.21.0.0/16

133 ```

134 </Step>

135 

136 <Step title="重新啟動您的 IDE 和 Claude Code">

137 關閉並重新開啟兩者,以使新規則生效。

138 </Step>

139</Steps>

140 

141#### 將 WSL2 切換為鏡像網路

142 

143鏡像網路需要 Windows 11 22H2 或更新版本。如果您使用 Windows 10,請改用上述防火牆規則。

144 

145將以下內容新增到您 Windows 使用者目錄中的 `.wslconfig`:

146 

147```ini theme={null}

148[wsl2]

149networkingMode=mirrored

150```

151 

152然後從 PowerShell 使用 `wsl --shutdown` 重新啟動 WSL。

153 

154## 疑難排解

155 

156### 外掛程式無法運作

157 

158如果外掛程式已安裝但 Claude Code 功能未出現在您的 IDE 中:

159 

160* 確保您從專案根目錄執行 Claude Code

161* 檢查 JetBrains 外掛程式在 IDE 設定中是否已啟用

162* 完全重新啟動 IDE(您可能需要執行多次)

163* 對於遠端開發,確保外掛程式已安裝在遠端主機上

164 

165### IDE 未被偵測

166 

167如果執行 `claude` 顯示「未偵測到可用的 IDEs」:

168 

169* 驗證外掛程式已安裝並啟用

170* 完全重新啟動 IDE

171* 檢查您是否從整合終端機執行 Claude Code

172* 對於 WSL 使用者,請參閱上方的 [WSL 設定](#wsl-設定)

173 

174### 找不到命令

175 

176如果點擊 Claude 圖示顯示「找不到命令」:

177 

1781. 透過在終端機中執行 `claude --version` 驗證 Claude Code 已安裝

1792. 在外掛程式設定中設定 Claude 命令路徑

1803. 對於 WSL 使用者,使用設定部分中提到的 WSL 命令格式

181 

182## 安全考量

183 

184當 Claude Code 在啟用自動編輯權限的 JetBrains IDE 中執行時,它可能能夠修改可由您的 IDE 自動執行的 IDE 設定檔。這可能會增加在自動編輯模式下執行 Claude Code 的風險,並允許繞過 Claude Code 對 bash 執行的權限提示。

185 

186在 JetBrains IDEs 中執行時,請考慮:

187 

188* 對編輯使用手動核准模式

189* 特別注意確保 Claude 僅與受信任的提示一起使用

190* 注意 Claude Code 有權限修改的檔案

191 

192如需 IDE 外的 Claude Code 安裝或登入問題,請參閱[疑難排解安裝和登入](/zh-TW/troubleshoot-install)。

keybindings.md +463 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 自訂鍵盤快捷鍵

6 

7> 使用快捷鍵配置檔案在 Claude Code 中自訂鍵盤快捷鍵。

8 

9<Note>

10 可自訂的鍵盤快捷鍵需要 Claude Code v2.1.18 或更新版本。使用 `claude --version` 檢查您的版本。

11</Note>

12 

13Claude Code 支援可自訂的鍵盤快捷鍵。執行 `/keybindings` 以在 `~/.claude/keybindings.json` 建立或開啟您的配置檔案。

14 

15## 配置檔案

16 

17快捷鍵配置檔案是一個包含 `bindings` 陣列的物件。每個區塊指定一個上下文和一個按鍵組合到動作的對應。

18 

19<Note>快捷鍵檔案的變更會自動偵測並套用,無需重新啟動 Claude Code。</Note>

20 

21| 欄位 | 說明 |

22| :--------- | :---------------------------- |

23| `$schema` | 選用的 JSON Schema URL,用於編輯器自動完成 |

24| `$docs` | 選用的文件 URL |

25| `bindings` | 按上下文分組的繫結區塊陣列 |

26 

27此範例在聊天上下文中將 `Ctrl+E` 繫結到開啟外部編輯器,並取消繫結 `Ctrl+U`:

28 

29```json theme={null}

30{

31 "$schema": "https://www.schemastore.org/claude-code-keybindings.json",

32 "$docs": "https://code.claude.com/docs/zh-TW/keybindings",

33 "bindings": [

34 {

35 "context": "Chat",

36 "bindings": {

37 "ctrl+e": "chat:externalEditor",

38 "ctrl+u": null

39 }

40 }

41 ]

42}

43```

44 

45## 上下文

46 

47每個繫結區塊指定一個**上下文**,其中快捷鍵適用:

48 

49| 上下文 | 說明 |

50| :---------------- | :------------------- |

51| `Global` | 在應用程式的任何地方適用 |

52| `Chat` | 主聊天輸入區域 |

53| `Autocomplete` | 自動完成選單已開啟 |

54| `Settings` | 設定選單 |

55| `Confirmation` | 權限和確認對話框 |

56| `Tabs` | 標籤導覽元件 |

57| `Help` | 說明選單可見 |

58| `Transcript` | 文字記錄檢視器 |

59| `HistorySearch` | 歷史記錄搜尋模式 (Ctrl+R) |

60| `Task` | 背景工作正在執行 |

61| `ThemePicker` | 主題選擇器對話框 |

62| `Attachments` | 影像附件導覽在選擇對話框中 |

63| `Footer` | 頁尾指示器導覽(工作、團隊、差異) |

64| `MessageSelector` | 回溯和摘要對話框訊息選擇 |

65| `DiffDialog` | 差異檢視器導覽 |

66| `ModelPicker` | 模型選擇器努力程度 |

67| `Select` | 通用選擇/清單元件 |

68| `Plugin` | Plugin 對話框(瀏覽、探索、管理) |

69| `Scroll` | 對話滾動和全螢幕模式中的文字選擇 |

70| `Doctor` | `/doctor` 診斷螢幕 |

71 

72## 可用動作

73 

74動作遵循 `namespace:action` 格式,例如 `chat:submit` 用於傳送訊息,或 `app:toggleTodos` 用於顯示工作清單。每個上下文都有特定的可用動作。

75 

76### 應用程式動作

77 

78在 `Global` 上下文中可用的動作:

79 

80| 動作 | 預設值 | 說明 |

81| :--------------------- | :----- | :------------- |

82| `app:interrupt` | Ctrl+C | 取消目前操作 |

83| `app:exit` | Ctrl+D | 結束 Claude Code |

84| `app:redraw` | (未繫結) | 強制終端機重新繪製 |

85| `app:toggleTodos` | Ctrl+T | 切換工作清單可見性 |

86| `app:toggleTranscript` | Ctrl+O | 切換詳細文字記錄 |

87 

88### 歷史記錄動作

89 

90用於導覽命令歷史記錄的動作:

91 

92| 動作 | 預設值 | 說明 |

93| :----------------- | :----- | :-------- |

94| `history:search` | Ctrl+R | 開啟歷史記錄搜尋 |

95| `history:previous` | Up | 上一個歷史記錄項目 |

96| `history:next` | Down | 下一個歷史記錄項目 |

97 

98### 聊天動作

99 

100在 `Chat` 上下文中可用的動作:

101 

102| 動作 | 預設值 | 說明 |

103| :-------------------- | :------------------------ | :---------------------------------------------------------------------------------------- |

104| `chat:cancel` | Escape | 取消目前輸入 |

105| `chat:clearInput` | Ctrl+L | 強制進行完整螢幕重新繪製,保留輸入。在[全螢幕渲染](/zh-TW/fullscreen#clear-the-conversation)中,在兩秒內按兩次以執行 `/clear` |

106| `chat:clearScreen` | Cmd+K | 在[全螢幕渲染](/zh-TW/fullscreen#clear-the-conversation)中,在兩秒內按兩次以執行 `/clear` |

107| `chat:killAgents` | Ctrl+X Ctrl+K | 終止所有背景代理 |

108| `chat:cycleMode` | Shift+Tab\* | 循環權限模式 |

109| `chat:modelPicker` | Meta+P | 開啟模型選擇器 |

110| `chat:fastMode` | Meta+O | 切換快速模式 |

111| `chat:thinkingToggle` | Meta+T | 切換延伸思考 |

112| `chat:submit` | Enter | 提交訊息 |

113| `chat:newline` | Ctrl+J | 插入換行符而不提交 |

114| `chat:undo` | Ctrl+\_, Ctrl+Shift+- | 復原上一個動作 |

115| `chat:externalEditor` | Ctrl+G, Ctrl+X Ctrl+E | 在外部編輯器中開啟 |

116| `chat:stash` | Ctrl+S | 暫存目前提示 |

117| `chat:imagePaste` | Ctrl+V (Windows 上為 Alt+V) | 貼上影像 |

118 

119\*在沒有 VT 模式的 Windows 上(Node \<24.2.0/\<22.17.0、Bun \<1.2.23),預設為 Meta+M。

120 

121### 自動完成動作

122 

123在 `Autocomplete` 上下文中可用的動作:

124 

125| 動作 | 預設值 | 說明 |

126| :---------------------- | :----- | :---- |

127| `autocomplete:accept` | Tab | 接受建議 |

128| `autocomplete:dismiss` | Escape | 關閉選單 |

129| `autocomplete:previous` | Up | 上一個建議 |

130| `autocomplete:next` | Down | 下一個建議 |

131 

132### 確認動作

133 

134在 `Confirmation` 上下文中可用的動作:

135 

136| 動作 | 預設值 | 說明 |

137| :-------------------------- | :-------- | :----- |

138| `confirm:yes` | Y, Enter | 確認動作 |

139| `confirm:no` | N, Escape | 拒絕動作 |

140| `confirm:previous` | Up | 上一個選項 |

141| `confirm:next` | Down | 下一個選項 |

142| `confirm:nextField` | Tab | 下一個欄位 |

143| `confirm:previousField` | (未繫結) | 上一個欄位 |

144| `confirm:toggle` | Space | 切換選擇 |

145| `confirm:cycleMode` | Shift+Tab | 循環權限模式 |

146| `confirm:toggleExplanation` | Ctrl+E | 切換權限說明 |

147 

148### 權限動作

149 

150在 `Confirmation` 上下文中可用於權限對話框的動作:

151 

152| 動作 | 預設值 | 說明 |

153| :----------------------- | :----- | :------- |

154| `permission:toggleDebug` | Ctrl+D | 切換權限偵錯資訊 |

155 

156### 文字記錄動作

157 

158在 `Transcript` 上下文中可用的動作:

159 

160| 動作 | 預設值 | 說明 |

161| :------------------------- | :---------------- | :------- |

162| `transcript:toggleShowAll` | Ctrl+E | 切換顯示所有內容 |

163| `transcript:exit` | q, Ctrl+C, Escape | 結束文字記錄檢視 |

164 

165### 歷史記錄搜尋動作

166 

167在 `HistorySearch` 上下文中可用的動作:

168 

169| 動作 | 預設值 | 說明 |

170| :------------------------- | :---------- | :---------------- |

171| `historySearch:next` | Ctrl+R | 下一個符合項目 |

172| `historySearch:accept` | Escape, Tab | 接受選擇 |

173| `historySearch:cancel` | Ctrl+C | 取消搜尋 |

174| `historySearch:execute` | Enter | 執行選定的命令 |

175| `historySearch:cycleScope` | Ctrl+S | 循環範圍:工作階段、專案、任何地方 |

176 

177### 工作動作

178 

179在 `Task` 上下文中可用的動作:

180 

181| 動作 | 預設值 | 說明 |

182| :---------------- | :----- | :------- |

183| `task:background` | Ctrl+B | 背景執行目前工作 |

184 

185### 主題動作

186 

187在 `ThemePicker` 上下文中可用的動作:

188 

189| 動作 | 預設值 | 說明 |

190| :------------------------------- | :----- | :------- |

191| `theme:toggleSyntaxHighlighting` | Ctrl+T | 切換語法醒目提示 |

192 

193### 說明動作

194 

195在 `Help` 上下文中可用的動作:

196 

197| 動作 | 預設值 | 說明 |

198| :------------- | :----- | :----- |

199| `help:dismiss` | Escape | 關閉說明選單 |

200 

201### Tabs 動作

202 

203在 `Tabs` 上下文中可用的動作:

204 

205| 動作 | 預設值 | 說明 |

206| :-------------- | :-------------- | :---- |

207| `tabs:next` | Tab, Right | 下一個標籤 |

208| `tabs:previous` | Shift+Tab, Left | 上一個標籤 |

209 

210### 附件動作

211 

212在 `Attachments` 上下文中可用的動作:

213 

214| 動作 | 預設值 | 說明 |

215| :--------------------- | :---------------- | :------ |

216| `attachments:next` | Right | 下一個附件 |

217| `attachments:previous` | Left | 上一個附件 |

218| `attachments:remove` | Backspace, Delete | 移除選定的附件 |

219| `attachments:exit` | Down, Escape | 結束附件導覽 |

220 

221### 頁尾動作

222 

223在 `Footer` 上下文中可用的動作:

224 

225| 動作 | 預設值 | 說明 |

226| :---------------------- | :----- | :---------------- |

227| `footer:next` | Right | 下一個頁尾項目 |

228| `footer:previous` | Left | 上一個頁尾項目 |

229| `footer:up` | Up | 在頁尾中向上導覽(在頂部取消選擇) |

230| `footer:down` | Down | 在頁尾中向下導覽 |

231| `footer:openSelected` | Enter | 開啟選定的頁尾項目 |

232| `footer:clearSelection` | Escape | 清除頁尾選擇 |

233 

234### 訊息選擇器動作

235 

236在 `MessageSelector` 上下文中可用的動作:

237 

238| 動作 | 預設值 | 說明 |

239| :----------------------- | :---------------------------------------- | :------- |

240| `messageSelector:up` | Up, K, Ctrl+P | 在清單中向上移動 |

241| `messageSelector:down` | Down, J, Ctrl+N | 在清單中向下移動 |

242| `messageSelector:top` | Ctrl+Up, Shift+Up, Meta+Up, Shift+K | 跳至頂部 |

243| `messageSelector:bottom` | Ctrl+Down, Shift+Down, Meta+Down, Shift+J | 跳至底部 |

244| `messageSelector:select` | Enter | 選擇訊息 |

245 

246### Diff 動作

247 

248在 `DiffDialog` 上下文中可用的動作:

249 

250| 動作 | 預設值 | 說明 |

251| :-------------------- | :------- | :-------- |

252| `diff:dismiss` | Escape | 關閉差異檢視器 |

253| `diff:previousSource` | Left | 上一個差異來源 |

254| `diff:nextSource` | Right | 下一個差異來源 |

255| `diff:previousFile` | Up | 差異中的上一個檔案 |

256| `diff:nextFile` | Down | 差異中的下一個檔案 |

257| `diff:viewDetails` | Enter | 檢視差異詳細資訊 |

258| `diff:back` | (特定於上下文) | 在差異檢視器中返回 |

259 

260### 模型選擇器動作

261 

262在 `ModelPicker` 上下文中可用的動作:

263 

264| 動作 | 預設值 | 說明 |

265| :--------------------------- | :---- | :----- |

266| `modelPicker:decreaseEffort` | Left | 降低努力程度 |

267| `modelPicker:increaseEffort` | Right | 提高努力程度 |

268 

269### 選擇動作

270 

271在 `Select` 上下文中可用的動作:

272 

273| 動作 | 預設值 | 說明 |

274| :---------------- | :-------------- | :---- |

275| `select:next` | Down, J, Ctrl+N | 下一個選項 |

276| `select:previous` | Up, K, Ctrl+P | 上一個選項 |

277| `select:accept` | Enter | 接受選擇 |

278| `select:cancel` | Escape | 取消選擇 |

279 

280### Plugin 動作

281 

282在 `Plugin` 上下文中可用的動作:

283 

284| 動作 | 預設值 | 說明 |

285| :---------------- | :---- | :--------------------------------- |

286| `plugin:toggle` | Space | 切換 plugin 選擇 |

287| `plugin:install` | I | 安裝選定的 plugins |

288| `plugin:favorite` | F | 將選定的 plugin 標記為最愛,使其在「已安裝」標籤頂部附近排序 |

289 

290### 設定動作

291 

292在 `Settings` 上下文中可用的動作:

293 

294| 動作 | 預設值 | 說明 |

295| :---------------- | :---- | :-------------------------- |

296| `settings:search` | / | 進入搜尋模式 |

297| `settings:retry` | R | 重試載入使用量資料(發生錯誤時) |

298| `settings:close` | Enter | 儲存變更並關閉配置面板。Escape 會捨棄變更並關閉 |

299 

300### Doctor 動作

301 

302在 `Doctor` 上下文中可用的動作:

303 

304| 動作 | 預設值 | 說明 |

305| :----------- | :-- | :--------------------------------- |

306| `doctor:fix` | F | 將診斷報告傳送給 Claude 以修復報告的問題。僅在發現問題時有效 |

307 

308### 語音動作

309 

310在啟用[語音聽寫](/zh-TW/voice-dictation)時,在 `Chat` 上下文中可用的動作:

311 

312| 動作 | 預設值 | 說明 |

313| :----------------- | :---- | :----------------------- |

314| `voice:pushToTalk` | Space | 聽寫提示。根據 `/voice` 模式按住或點選 |

315 

316### 滾動動作

317 

318在啟用[全螢幕渲染](/zh-TW/fullscreen)時,在 `Scroll` 上下文中可用的動作:

319 

320| 動作 | 預設值 | 說明 |

321| :-------------------------- | :------------------- | :--------------------------------------------------- |

322| `scroll:lineUp` | (未繫結) | 向上滾動一行。滑鼠滾輪滾動會觸發此動作 |

323| `scroll:lineDown` | (未繫結) | 向下滾動一行。滑鼠滾輪滾動會觸發此動作 |

324| `scroll:pageUp` | PageUp | 向上滾動視窗高度的一半 |

325| `scroll:pageDown` | PageDown | 向下滾動視窗高度的一半 |

326| `scroll:top` | Ctrl+Home | 跳至對話的開始 |

327| `scroll:bottom` | Ctrl+End | 跳至最新訊息並重新啟用自動跟隨 |

328| `scroll:halfPageUp` | (未繫結) | 向上滾動視窗高度的一半。與 `scroll:pageUp` 相同的行為,為 vi 風格的重新繫結提供 |

329| `scroll:halfPageDown` | (未繫結) | 向下滾動視窗高度的一半。與 `scroll:pageDown` 相同的行為,為 vi 風格的重新繫結提供 |

330| `scroll:fullPageUp` | (未繫結) | 向上滾動完整視窗高度 |

331| `scroll:fullPageDown` | (未繫結) | 向下滾動完整視窗高度 |

332| `selection:copy` | Ctrl+Shift+C / Cmd+C | 將選定的文字複製到剪貼簿 |

333| `selection:clear` | (未繫結) | 清除有效的文字選擇 |

334| `selection:extendLeft` | Shift+Left | 將有效選擇向左延伸一欄 |

335| `selection:extendRight` | Shift+Right | 將有效選擇向右延伸一欄 |

336| `selection:extendUp` | Shift+Up | 將有效選擇向上延伸一列。當選擇到達頂部邊緣時滾動視窗 |

337| `selection:extendDown` | Shift+Down | 將有效選擇向下延伸一列。當選擇到達底部邊緣時滾動視窗 |

338| `selection:extendLineStart` | Shift+Home | 將有效選擇延伸到行的開始 |

339| `selection:extendLineEnd` | Shift+End | 將有效選擇延伸到行的結尾 |

340 

341## 按鍵組合語法

342 

343### 修飾鍵

344 

345使用 `+` 分隔符搭配修飾鍵:

346 

347* `ctrl` 或 `control` - Control 鍵

348* `shift` - Shift 鍵

349* `alt`、`opt`、`option` 或 `meta` - Windows 和 Linux 上的 Alt 鍵,macOS 上的 Option 鍵

350* `cmd`、`command`、`super` 或 `win` - macOS 上的 Command 鍵,Windows 上的 Windows 鍵,Linux 上的 Super 鍵

351 

352`cmd` 群組只在報告 Super 修飾鍵的終端機中被偵測,例如支援 Kitty 鍵盤協議或 xterm 的 `modifyOtherKeys` 模式的終端機。大多數終端機不會發送它,因此對於您想在任何地方都能運作的繫結,請使用 `ctrl` 或 `meta`。

353 

354例如:

355 

356```text theme={null}

357ctrl+k Ctrl + K

358shift+tab Shift + Tab

359meta+p macOS 上的 Option + P,其他地方為 Alt + P

360ctrl+shift+c 多個修飾鍵

361```

362 

363### 大寫字母

364 

365獨立的大寫字母表示 Shift。例如,`K` 等同於 `shift+k`。這對於 vim 風格的繫結很有用,其中大寫和小寫鍵有不同的含義。

366 

367搭配修飾鍵的大寫字母(例如 `ctrl+K`)被視為風格上的,**不**表示 Shift:`ctrl+K` 與 `ctrl+k` 相同。

368 

369### 和弦

370 

371和弦是由空格分隔的按鍵組合序列:

372 

373```text theme={null}

374ctrl+k ctrl+s 按 Ctrl+K,放開,然後按 Ctrl+S

375```

376 

377### 特殊鍵

378 

379* `escape` 或 `esc` - Escape 鍵

380* `enter` 或 `return` - Enter 鍵

381* `tab` - Tab 鍵

382* `space` - 空格鍵

383* `up`、`down`、`left`、`right` - 方向鍵

384* `backspace`、`delete` - 刪除鍵

385 

386## 取消繫結預設快捷鍵

387 

388將動作設定為 `null` 以取消繫結預設快捷鍵:

389 

390```json theme={null}

391{

392 "bindings": [

393 {

394 "context": "Chat",

395 "bindings": {

396 "ctrl+s": null

397 }

398 }

399 ]

400}

401```

402 

403這也適用於和弦繫結。取消繫結共享前綴的每個和弦會釋放該前綴以用作單一鍵繫結:

404 

405```json theme={null}

406{

407 "bindings": [

408 {

409 "context": "Chat",

410 "bindings": {

411 "ctrl+x ctrl+k": null,

412 "ctrl+x ctrl+e": null,

413 "ctrl+x": "chat:newline"

414 }

415 }

416 ]

417}

418```

419 

420如果您取消繫結前綴上的某些但不是全部和弦,按下前綴仍會進入和弦等待模式以進行剩餘的繫結。

421 

422## 保留的快捷鍵

423 

424這些快捷鍵無法重新繫結:

425 

426| 快捷鍵 | 原因 |

427| :-------- | :------------------------ |

428| Ctrl+C | 硬編碼的中斷/取消 |

429| Ctrl+D | 硬編碼的結束 |

430| Ctrl+M | 與終端機中的 Enter 相同(兩者都傳送 CR) |

431| Caps Lock | 未傳遞至終端機應用程式 |

432 

433## 終端機衝突

434 

435某些快捷鍵可能與終端機多工器衝突:

436 

437| 快捷鍵 | 衝突 |

438| :----- | :------------------ |

439| Ctrl+B | tmux 前綴(按兩次以傳送) |

440| Ctrl+A | GNU screen 前綴 |

441| Ctrl+Z | Unix 程序暫停 (SIGTSTP) |

442 

443## Vim 模式互動

444 

445啟用 vim 模式時(透過 `/config` → 編輯器模式),快捷鍵和 vim 模式獨立運作:

446 

447* **Vim 模式**在文字輸入層級處理輸入(游標移動、模式、動作)

448* **快捷鍵**在元件層級處理動作(切換待辦事項、提交等)

449* vim 模式中的 Escape 鍵從 INSERT 切換到 NORMAL 模式;它不會觸發 `chat:cancel`

450* 大多數 Ctrl+鍵快捷鍵通過 vim 模式傳遞到快捷鍵系統

451* 在 vim NORMAL 模式中,`?` 顯示說明選單(vim 行為)

452 

453## 驗證

454 

455Claude Code 驗證您的快捷鍵並顯示以下警告:

456 

457* 解析錯誤(無效的 JSON 或結構)

458* 無效的上下文名稱

459* 保留快捷鍵衝突

460* 終端機多工器衝突

461* 同一上下文中的重複繫結

462 

463執行 `/doctor` 以查看任何快捷鍵警告。

llm-gateway.md +196 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# LLM gateway 配置

6 

7> 了解如何配置 Claude Code 以使用 LLM gateway 解決方案。涵蓋 gateway 要求、身份驗證配置、模型選擇和提供商特定的端點設置。

8 

9LLM gateway 提供了 Claude Code 和模型提供商之間的集中代理層,通常提供:

10 

11* **集中身份驗證** - 單一 API 密鑰管理點

12* **使用情況追蹤** - 監控跨團隊和項目的使用情況

13* **成本控制** - 實施預算和速率限制

14* **審計日誌** - 追蹤所有模型交互以進行合規性檢查

15* **模型路由** - 無需更改代碼即可在提供商之間切換

16 

17## Gateway 要求

18 

19為了讓 LLM gateway 與 Claude Code 配合使用,它必須滿足以下要求:

20 

21**API 格式**

22 

23gateway 必須向客戶端公開以下至少一種 API 格式:

24 

251. **Anthropic Messages**: `/v1/messages`, `/v1/messages/count_tokens`

26 * 必須轉發請求標頭:`anthropic-beta`、`anthropic-version`

27 

282. **Bedrock InvokeModel**: `/invoke`, `/invoke-with-response-stream`

29 * 必須保留請求正文字段:`anthropic_beta`、`anthropic_version`

30 

313. **Vertex rawPredict**: `:rawPredict`、`:streamRawPredict`、`/count-tokens:rawPredict`

32 * 必須轉發請求標頭:`anthropic-beta`、`anthropic-version`

33 

34未能轉發標頭或保留正文字段可能會導致功能減少或無法使用 Claude Code 功能。

35 

36<Note>

37 Claude Code 根據 API 格式確定要啟用的功能。使用 Bedrock 或 Vertex 的 Anthropic Messages 格式時,您可能需要設置環境變數 `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`。

38</Note>

39 

40**請求標頭**

41 

42Claude Code 在每個 API 請求上包含以下標頭:

43 

44| 標頭 | 描述 |

45| :------------------------- | :--------------------------------------------------------------- |

46| `X-Claude-Code-Session-Id` | 當前 Claude Code 會話的唯一識別符。代理可以使用此識別符來聚合來自單個會話的所有 API 請求,而無需解析請求正文。 |

47 

48Claude Code 還在系統提示前面添加了一個簡短的歸屬塊,其中包含客戶端版本和從對話派生的指紋。Anthropic API 在處理前會刪除此塊,因此不會影響第一方提示快取。如果您的 gateway 實現了自己的提示快取,其密鑰基於完整請求正文,請設置 [`CLAUDE_CODE_ATTRIBUTION_HEADER=0`](/zh-TW/env-vars) 以省略它。

49 

50## 配置

51 

52### 模型選擇

53 

54默認情況下,Claude Code 使用所選 API 格式的標準模型名稱。

55 

56當 `ANTHROPIC_BASE_URL` 指向公開 Anthropic Messages 格式的 gateway 時,Claude Code 在啟動時會查詢 gateway 的 `/v1/models` 端點,並將返回的模型添加到 `/model` 選擇器中。每個發現的條目都標記為「From gateway」,並在提供時使用響應中的 `display_name` 欄位。這需要 Claude Code v2.1.126 或更高版本。

57 

58發現功能僅適用於 Anthropic Messages 格式。它不會針對 Bedrock 或 Vertex 傳遞端點運行,也不會在 `ANTHROPIC_BASE_URL` 未設置或指向 `api.anthropic.com` 時運行。

59 

60發現請求的身份驗證方式與推理請求相同:它將 `ANTHROPIC_AUTH_TOKEN` 作為 bearer token 發送,或在未設置身份驗證令牌時將 `ANTHROPIC_API_KEY` 作為 `x-api-key` 標頭發送,以及來自 `ANTHROPIC_CUSTOM_HEADERS` 的任何標頭。只有 ID 以 `claude` 或 `anthropic` 開頭的模型才會添加到選擇器中。結果被緩存到 `~/.claude/cache/gateway-models.json`,並在每次啟動時刷新。如果請求失敗或 gateway 未實現 `/v1/models`,選擇器將回退到上次啟動時的緩存列表或內置模型列表。

61 

62如果您的 gateway 使用與發現篩選器不匹配的模型名稱,請使用 [模型配置](/zh-TW/model-config) 中記錄的環境變數手動添加它們。

63 

64## LiteLLM 配置

65 

66<Warning>

67 LiteLLM PyPI 版本 1.82.7 和 1.82.8 被盜竊憑證的惡意軟體破壞。請勿安裝這些版本。如果您已經安裝了它們:

68 

69 * 移除該軟體包

70 * 輪換受影響系統上的所有憑證

71 * 按照 [BerriAI/litellm#24518](https://github.com/BerriAI/litellm/issues/24518) 中的補救步驟進行操作

72 

73 LiteLLM 是第三方代理服務。Anthropic 不認可、維護或審計 LiteLLM 的安全性或功能。本指南僅供參考,可能會過時。請自行決定是否使用。

74</Warning>

75 

76### 先決條件

77 

78* Claude Code 已更新至最新版本

79* LiteLLM Proxy Server 已部署且可訪問

80* 通過您選擇的提供商訪問 Claude 模型

81 

82### 基本 LiteLLM 設置

83 

84**配置 Claude Code**:

85 

86#### 身份驗證方法

87 

88##### 靜態 API 密鑰

89 

90使用固定 API 密鑰的最簡單方法:

91 

92```bash theme={null}

93# 在環境中設置

94export ANTHROPIC_AUTH_TOKEN=sk-litellm-static-key

95 

96# 或在 Claude Code 設置中

97{

98 "env": {

99 "ANTHROPIC_AUTH_TOKEN": "sk-litellm-static-key"

100 }

101}

102```

103 

104此值將作為 `Authorization` 標頭發送。

105 

106##### 使用幫助程序的動態 API 密鑰

107 

108用於輪換密鑰或按用戶身份驗證:

109 

1101. 創建 API 密鑰幫助程序腳本:

111 

112```bash theme={null}

113#!/bin/bash

114# ~/bin/get-litellm-key.sh

115 

116# 示例:從保管庫獲取密鑰

117vault kv get -field=api_key secret/litellm/claude-code

118 

119# 示例:生成 JWT 令牌

120jwt encode \

121 --secret="${JWT_SECRET}" \

122 --exp="+1h" \

123 '{"user":"'${USER}'","team":"engineering"}'

124```

125 

1262. 配置 Claude Code 設置以使用幫助程序:

127 

128```json theme={null}

129{

130 "apiKeyHelper": "~/bin/get-litellm-key.sh"

131}

132```

133 

1343. 設置令牌刷新間隔:

135 

136```bash theme={null}

137# 每小時刷新一次(3600000 毫秒)

138export CLAUDE_CODE_API_KEY_HELPER_TTL_MS=3600000

139```

140 

141此值將作為 `Authorization` 和 `X-Api-Key` 標頭發送。`apiKeyHelper` 的優先級低於 `ANTHROPIC_AUTH_TOKEN` 或 `ANTHROPIC_API_KEY`。

142 

143#### 統一端點(推薦)

144 

145使用 LiteLLM 的 [Anthropic 格式端點](https://docs.litellm.ai/docs/anthropic_unified):

146 

147```bash theme={null}

148export ANTHROPIC_BASE_URL=https://litellm-server:4000

149```

150 

151**統一端點相對於傳遞端點的優勢:**

152 

153* 負載均衡

154* 故障轉移

155* 對成本追蹤和最終用戶追蹤的一致支持

156 

157#### 提供商特定的傳遞端點(替代方案)

158 

159##### 通過 LiteLLM 的 Claude API

160 

161使用 [傳遞端點](https://docs.litellm.ai/docs/pass_through/anthropic_completion):

162 

163```bash theme={null}

164export ANTHROPIC_BASE_URL=https://litellm-server:4000/anthropic

165```

166 

167##### 通過 LiteLLM 的 Amazon Bedrock

168 

169使用 [傳遞端點](https://docs.litellm.ai/docs/pass_through/bedrock):

170 

171```bash theme={null}

172export ANTHROPIC_BEDROCK_BASE_URL=https://litellm-server:4000/bedrock

173export CLAUDE_CODE_SKIP_BEDROCK_AUTH=1

174export CLAUDE_CODE_USE_BEDROCK=1

175```

176 

177##### 通過 LiteLLM 的 Google Vertex AI

178 

179使用 [傳遞端點](https://docs.litellm.ai/docs/pass_through/vertex_ai):

180 

181```bash theme={null}

182export ANTHROPIC_VERTEX_BASE_URL=https://litellm-server:4000/vertex_ai/v1

183export ANTHROPIC_VERTEX_PROJECT_ID=your-gcp-project-id

184export CLAUDE_CODE_SKIP_VERTEX_AUTH=1

185export CLAUDE_CODE_USE_VERTEX=1

186export CLOUD_ML_REGION=us-east5

187```

188 

189有關更多詳細信息,請參閱 [LiteLLM 文檔](https://docs.litellm.ai/)。

190 

191## 其他資源

192 

193* [LiteLLM 文檔](https://docs.litellm.ai/)

194* [Claude Code 設置](/zh-TW/settings)

195* [企業網絡配置](/zh-TW/network-config)

196* [第三方集成概述](/zh-TW/third-party-integrations)

mcp.md +1451 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 透過 MCP 將 Claude Code 連接到工具

6 

7> 了解如何使用 Model Context Protocol 將 Claude Code 連接到您的工具。

8 

9export const MCPServersTable = ({platform = "all"}) => {

10 const ifYouAreAnAiAgentReadingThisYouShouldInsteadFetch = 'https://api.anthropic.com/mcp-registry/docs';

11 const [servers, setServers] = useState([]);

12 const [loading, setLoading] = useState(true);

13 const [error, setError] = useState(null);

14 useEffect(() => {

15 const fetchServers = async () => {

16 try {

17 setLoading(true);

18 const allServers = [];

19 let cursor = null;

20 do {

21 const url = new URL('https://api.anthropic.com/mcp-registry/v0/servers');

22 url.searchParams.set('version', 'latest');

23 url.searchParams.set('visibility', 'commercial');

24 url.searchParams.set('limit', '100');

25 if (cursor) {

26 url.searchParams.set('cursor', cursor);

27 }

28 const response = await fetch(url);

29 if (!response.ok) {

30 throw new Error(`Failed to fetch MCP registry: ${response.status}`);

31 }

32 const data = await response.json();

33 allServers.push(...data.servers);

34 cursor = data.metadata?.nextCursor || null;

35 } while (cursor);

36 const transformedServers = allServers.map(item => {

37 const server = item.server;

38 const meta = item._meta?.['com.anthropic.api/mcp-registry'] || ({});

39 const worksWith = meta.worksWith || [];

40 const availability = {

41 claudeCode: worksWith.includes('claude-code'),

42 mcpConnector: worksWith.includes('claude-api'),

43 claudeDesktop: worksWith.includes('claude-desktop')

44 };

45 const remotes = server.remotes || [];

46 const httpRemote = remotes.find(r => r.type === 'streamable-http');

47 const sseRemote = remotes.find(r => r.type === 'sse');

48 const preferredRemote = httpRemote || sseRemote;

49 const remoteUrl = preferredRemote?.url || meta.url;

50 const remoteType = preferredRemote?.type;

51 const isTemplatedUrl = remoteUrl?.includes('{');

52 let setupUrl;

53 if (isTemplatedUrl && meta.requiredFields) {

54 const urlField = meta.requiredFields.find(f => f.field === 'url');

55 setupUrl = urlField?.sourceUrl || meta.documentation;

56 }

57 const urls = {};

58 if (!isTemplatedUrl) {

59 if (remoteType === 'streamable-http') {

60 urls.http = remoteUrl;

61 } else if (remoteType === 'sse') {

62 urls.sse = remoteUrl;

63 }

64 }

65 let envVars = [];

66 if (server.packages && server.packages.length > 0) {

67 const npmPackage = server.packages.find(p => p.registryType === 'npm');

68 if (npmPackage) {

69 urls.stdio = `npx -y ${npmPackage.identifier}`;

70 if (npmPackage.environmentVariables) {

71 envVars = npmPackage.environmentVariables;

72 }

73 }

74 }

75 return {

76 name: meta.displayName || server.title || server.name,

77 description: meta.oneLiner || server.description,

78 documentation: meta.documentation,

79 urls: urls,

80 envVars: envVars,

81 availability: availability,

82 customCommands: meta.claudeCodeCopyText ? {

83 claudeCode: meta.claudeCodeCopyText

84 } : undefined,

85 setupUrl: setupUrl

86 };

87 });

88 setServers(transformedServers);

89 setError(null);

90 } catch (err) {

91 setError(err.message);

92 console.error('Error fetching MCP registry:', err);

93 } finally {

94 setLoading(false);

95 }

96 };

97 fetchServers();

98 }, []);

99 const generateClaudeCodeCommand = server => {

100 if (server.customCommands && server.customCommands.claudeCode) {

101 return server.customCommands.claudeCode.replace('--transport streamable-http', '--transport http');

102 }

103 const serverSlug = server.name.toLowerCase().replace(/[^a-z0-9]/g, '-');

104 if (server.urls.http) {

105 return `claude mcp add ${serverSlug} --transport http ${server.urls.http}`;

106 }

107 if (server.urls.sse) {

108 return `claude mcp add ${serverSlug} --transport sse ${server.urls.sse}`;

109 }

110 if (server.urls.stdio) {

111 const envFlags = server.envVars && server.envVars.length > 0 ? server.envVars.map(v => `--env ${v.name}=YOUR_${v.name}`).join(' ') : '';

112 const baseCommand = `claude mcp add ${serverSlug} --transport stdio`;

113 return envFlags ? `${baseCommand} ${envFlags} -- ${server.urls.stdio}` : `${baseCommand} -- ${server.urls.stdio}`;

114 }

115 return null;

116 };

117 if (loading) {

118 return <div>Loading MCP servers...</div>;

119 }

120 if (error) {

121 return <div>Error loading MCP servers: {error}</div>;

122 }

123 const filteredServers = servers.filter(server => {

124 if (platform === "claudeCode") {

125 return server.availability.claudeCode;

126 } else if (platform === "mcpConnector") {

127 return server.availability.mcpConnector;

128 } else if (platform === "claudeDesktop") {

129 return server.availability.claudeDesktop;

130 } else if (platform === "all") {

131 return true;

132 } else {

133 throw new Error(`Unknown platform: ${platform}`);

134 }

135 });

136 return <>

137 <style jsx>{`

138 .cards-container {

139 display: grid;

140 gap: 1rem;

141 margin-bottom: 2rem;

142 }

143 .server-card {

144 border: 1px solid var(--border-color, #e5e7eb);

145 border-radius: 6px;

146 padding: 1rem;

147 }

148 .command-row {

149 display: flex;

150 align-items: center;

151 gap: 0.25rem;

152 }

153 .command-row code {

154 font-size: 0.75rem;

155 overflow-x: auto;

156 }

157 `}</style>

158 

159 <div className="cards-container">

160 {filteredServers.map(server => {

161 const claudeCodeCommand = generateClaudeCodeCommand(server);

162 const mcpUrl = server.urls.http || server.urls.sse;

163 const commandToShow = platform === "claudeCode" ? claudeCodeCommand : mcpUrl;

164 return <div key={server.name} className="server-card">

165 <div>

166 {server.documentation ? <a href={server.documentation}>

167 <strong>{server.name}</strong>

168 </a> : <strong>{server.name}</strong>}

169 </div>

170 

171 <p style={{

172 margin: '0.5rem 0',

173 fontSize: '0.9rem'

174 }}>

175 {server.description}

176 </p>

177 

178 {server.setupUrl && <p style={{

179 margin: '0.25rem 0',

180 fontSize: '0.8rem',

181 fontStyle: 'italic',

182 opacity: 0.7

183 }}>

184 Requires user-specific URL.{' '}

185 <a href={server.setupUrl} style={{

186 textDecoration: 'underline'

187 }}>

188 Get your URL here

189 </a>.

190 </p>}

191 

192 {commandToShow && !server.setupUrl && <>

193 <p style={{

194 display: 'block',

195 fontSize: '0.75rem',

196 fontWeight: 500,

197 minWidth: 'fit-content',

198 marginTop: '0.5rem',

199 marginBottom: 0

200 }}>

201 {platform === "claudeCode" ? "Command" : "URL"}

202 </p>

203 <div className="command-row">

204 <code>

205 {commandToShow}

206 </code>

207 </div>

208 </>}

209 </div>;

210 })}

211 </div>

212 </>;

213};

214 

215Claude Code 可以透過 [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) 連接到數百個外部工具和資料來源,這是一個開源標準,用於 AI 工具整合。MCP servers 讓 Claude Code 能夠存取您的工具、資料庫和 API。

216 

217當您發現自己從另一個工具(例如問題追蹤器或監控儀表板)複製資料到聊天中時,請連接一個 server。連接後,Claude 可以直接讀取和操作該系統,而不是根據您貼上的內容進行工作。

218 

219## 使用 MCP 可以做什麼

220 

221連接 MCP servers 後,您可以要求 Claude Code:

222 

223* **從問題追蹤器實現功能**:"新增 JIRA 問題 ENG-4521 中描述的功能,並在 GitHub 上建立 PR。"

224* **分析監控資料**:"檢查 Sentry 和 Statsig,以檢查 ENG-4521 中描述的功能使用情況。"

225* **查詢資料庫**:"根據我們的 PostgreSQL 資料庫,找到 10 個使用功能 ENG-4521 的隨機使用者的電子郵件。"

226* **整合設計**:"根據在 Slack 中發佈的新 Figma 設計更新我們的標準電子郵件範本"

227* **自動化工作流程**:"建立 Gmail 草稿,邀請這 10 個使用者參加關於新功能的回饋會議。"

228* **回應外部事件**:MCP server 也可以充當 [channel](/zh-TW/channels),將訊息推送到您的 session 中,因此當您不在時,Claude 可以回應 Telegram 訊息、Discord 聊天或 webhook 事件。

229 

230## 熱門 MCP servers

231 

232以下是一些您可以連接到 Claude Code 的常用 MCP servers:

233 

234<Warning>

235 使用第三方 MCP servers 需自行承擔風險 - Anthropic 尚未驗證

236 所有這些 servers 的正確性或安全性。

237 請確保您信任要安裝的 MCP servers。

238 使用可能會取得不受信任內容的 MCP servers 時要特別小心,

239 因為這些可能會使您面臨提示注入風險。

240</Warning>

241 

242<MCPServersTable platform="claudeCode" />

243 

244<Note>

245 **需要特定的整合?** [在 GitHub 上找到數百個更多 MCP servers](https://github.com/modelcontextprotocol/servers),或使用 [MCP SDK](https://modelcontextprotocol.io/quickstart/server) 建立您自己的。

246</Note>

247 

248## 安裝 MCP servers

249 

250MCP servers 可以根據您的需求以三種不同的方式進行配置:

251 

252### 選項 1:新增遠端 HTTP server

253 

254HTTP servers 是連接到遠端 MCP servers 的推薦選項。這是雲端服務最廣泛支援的傳輸方式。

255 

256```bash theme={null}

257# 基本語法

258claude mcp add --transport http <name> <url>

259 

260# 實際範例:連接到 Notion

261claude mcp add --transport http notion https://mcp.notion.com/mcp

262 

263# 使用 Bearer token 的範例

264claude mcp add --transport http secure-api https://api.example.com/mcp \

265 --header "Authorization: Bearer your-token"

266```

267 

268### 選項 2:新增遠端 SSE server

269 

270<Warning>

271 SSE (Server-Sent Events) 傳輸已棄用。請改用 HTTP servers(如果可用)。

272</Warning>

273 

274```bash theme={null}

275# 基本語法

276claude mcp add --transport sse <name> <url>

277 

278# 實際範例:連接到 Asana

279claude mcp add --transport sse asana https://mcp.asana.com/sse

280 

281# 使用驗證標頭的範例

282claude mcp add --transport sse private-api https://api.company.com/sse \

283 --header "X-API-Key: your-key-here"

284```

285 

286### 選項 3:新增本機 stdio server

287 

288Stdio servers 在您的機器上作為本機程序執行。它們非常適合需要直接系統存取或自訂指令碼的工具。

289 

290```bash theme={null}

291# 基本語法

292claude mcp add [options] <name> -- <command> [args...]

293 

294# 實際範例:新增 Airtable server

295claude mcp add --transport stdio --env AIRTABLE_API_KEY=YOUR_KEY airtable \

296 -- npx -y airtable-mcp-server

297```

298 

299<Note>

300 **重要:選項順序**

301 

302 所有選項(`--transport`、`--env`、`--scope`、`--header`)必須在 server 名稱**之前**。然後 `--` (雙破折號) 將 server 名稱與傳遞給 MCP server 的命令和引數分開。

303 

304 例如:

305 

306 * `claude mcp add --transport stdio myserver -- npx server` → 執行 `npx server`

307 * `claude mcp add --transport stdio --env KEY=value myserver -- python server.py --port 8080` → 執行 `python server.py --port 8080`,環境中有 `KEY=value`

308 

309 這可以防止 Claude 的旗標與 server 旗標之間的衝突。

310</Note>

311 

312### 管理您的 servers

313 

314配置後,您可以使用這些命令管理您的 MCP servers:

315 

316```bash theme={null}

317# 列出所有已配置的 servers

318claude mcp list

319 

320# 取得特定 server 的詳細資訊

321claude mcp get github

322 

323# 移除 server

324claude mcp remove github

325 

326# (在 Claude Code 中) 檢查 server 狀態

327/mcp

328```

329 

330### 動態工具更新

331 

332Claude Code 支援 MCP `list_changed` 通知,允許 MCP servers 動態更新其可用工具、提示和資源,而無需您斷開連接並重新連接。當 MCP server 傳送 `list_changed` 通知時,Claude Code 會自動重新整理該 server 的可用功能。

333 

334### 自動重新連接

335 

336如果 HTTP 或 SSE server 在 session 中途斷開連接,Claude Code 會自動以指數退避方式重新連接:最多五次嘗試,從一秒延遲開始,每次加倍。在 `/mcp` 中,server 會顯示為待處理狀態,同時重新連接正在進行中。五次失敗嘗試後,server 被標記為失敗,您可以從 `/mcp` 手動重試。Stdio servers 是本機程序,不會自動重新連接。

337 

338相同的退避策略適用於 HTTP 或 SSE server 在啟動時初始連接失敗的情況。自 v2.1.121 起,Claude Code 在暫時性錯誤(例如 5xx 回應、連接被拒絕或逾時)上最多重試初始連接三次,如果仍無法連接,則將 server 標記為失敗。驗證和找不到錯誤不會重試,因為它們需要配置變更才能解決。

339 

340### 使用 channels 推送訊息

341 

342MCP server 也可以直接將訊息推送到您的 session 中,以便 Claude 可以回應外部事件,例如 CI 結果、監控警報或聊天訊息。若要啟用此功能,您的 server 宣告 `claude/channel` 功能,並在啟動時使用 `--channels` 旗標選擇加入。請參閱 [Channels](/zh-TW/channels) 以使用官方支援的 channel,或 [Channels reference](/zh-TW/channels-reference) 以建立您自己的。

343 

344<Tip>

345 提示:

346 

347 * 使用 `--scope` 旗標指定配置的儲存位置:

348 * `local` (預設):僅在目前專案中對您可用 (在較舊版本中稱為 `project`)

349 * `project`:透過 `.mcp.json` 檔案與專案中的所有人共享

350 * `user`:在所有專案中對您可用 (在較舊版本中稱為 `global`)

351 * 使用 `--env` 旗標設定環境變數 (例如,`--env KEY=value`)

352 * 使用 MCP\_TIMEOUT 環境變數配置 MCP server 啟動逾時 (例如,`MCP_TIMEOUT=10000 claude` 設定 10 秒逾時)

353 * 當 MCP 工具輸出超過 10,000 個 tokens 時,Claude Code 會顯示警告。若要增加此限制,請設定 `MAX_MCP_OUTPUT_TOKENS` 環境變數 (例如,`MAX_MCP_OUTPUT_TOKENS=50000`)

354 * 使用 `/mcp` 向需要 OAuth 2.0 驗證的遠端 servers 進行驗證

355</Tip>

356 

357### Plugin 提供的 MCP servers

358 

359[Plugins](/zh-TW/plugins) 可以捆綁 MCP servers,在啟用 plugin 時自動提供工具和整合。Plugin MCP servers 的工作方式與使用者配置的 servers 相同。

360 

361**Plugin MCP servers 的工作方式**:

362 

363* Plugins 在 plugin 根目錄的 `.mcp.json` 中或在 `plugin.json` 中內聯定義 MCP servers

364* 啟用 plugin 時,其 MCP servers 會自動啟動

365* Plugin MCP 工具與手動配置的 MCP 工具一起出現

366* Plugin servers 透過 plugin 安裝進行管理 (不是 `/mcp` 命令)

367 

368**Plugin MCP 配置範例**:

369 

370在 plugin 根目錄的 `.mcp.json` 中:

371 

372```json theme={null}

373{

374 "mcpServers": {

375 "database-tools": {

376 "command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server",

377 "args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"],

378 "env": {

379 "DB_URL": "${DB_URL}"

380 }

381 }

382 }

383}

384```

385 

386或在 `plugin.json` 中內聯:

387 

388```json theme={null}

389{

390 "name": "my-plugin",

391 "mcpServers": {

392 "plugin-api": {

393 "command": "${CLAUDE_PLUGIN_ROOT}/servers/api-server",

394 "args": ["--port", "8080"]

395 }

396 }

397}

398```

399 

400**Plugin MCP 功能**:

401 

402* **自動生命週期**:在 session 啟動時,已啟用 plugins 的 servers 會自動連接。如果您在 session 期間啟用或停用 plugin,請執行 `/reload-plugins` 以連接或斷開其 MCP servers

403* **環境變數**:使用 `${CLAUDE_PLUGIN_ROOT}` 表示 plugin 根目錄中的捆綁 plugin 檔案,以及 `${CLAUDE_PLUGIN_DATA}` 表示 [persistent state](/zh-TW/plugins-reference#persistent-data-directory) 在 plugin 更新後仍然存在

404* **使用者環境存取**:存取與手動配置的 servers 相同的環境變數

405* **多種傳輸類型**:支援 stdio、SSE 和 HTTP 傳輸 (傳輸支援可能因 server 而異)

406 

407**檢視 plugin MCP servers**:

408 

409```bash theme={null}

410# 在 Claude Code 中,查看所有 MCP servers,包括 plugin 的

411/mcp

412```

413 

414Plugin servers 在列表中出現,並有指示器顯示它們來自 plugins。

415 

416**Plugin MCP servers 的優點**:

417 

418* **捆綁分發**:工具和 servers 一起打包

419* **自動設定**:無需手動 MCP 配置

420* **團隊一致性**:安裝 plugin 時,每個人都會獲得相同的工具

421 

422請參閱 [plugin 元件參考](/zh-TW/plugins-reference#mcp-servers),了解有關使用 plugins 捆綁 MCP servers 的詳細資訊。

423 

424## MCP 安裝範圍

425 

426MCP servers 可以在三個不同的範圍級別進行配置。您選擇的範圍控制 server 在哪些專案中載入,以及配置是否與您的團隊共享。

427 

428| 範圍 | 載入位置 | 與團隊共享 | 儲存位置 |

429| ------------------------- | ------ | -------- | ------------------- |

430| [Local](#local-scope) | 僅目前專案 | 否 | `~/.claude.json` |

431| [Project](#project-scope) | 僅目前專案 | 是,透過版本控制 | 專案根目錄中的 `.mcp.json` |

432| [User](#user-scope) | 您的所有專案 | 否 | `~/.claude.json` |

433 

434### Local scope

435 

436Local scope 是預設值。本機範圍的 server 僅在您新增它的專案中載入,並對您保持私密。Claude Code 將其儲存在 `~/.claude.json` 中該專案的路徑下,因此相同的 server 不會出現在您的其他專案中。使用本機範圍進行個人開發 servers、實驗配置或包含您不想在版本控制中的認證的 servers。

437 

438<Note>

439 MCP servers 的「local scope」術語與一般本機設定不同。MCP 本機範圍的 servers 儲存在 `~/.claude.json` (您的主目錄) 中,而一般本機設定使用 `.claude/settings.local.json` (在專案目錄中)。請參閱 [Settings](/zh-TW/settings#settings-files) 了解設定檔案位置的詳細資訊。

440</Note>

441 

442```bash theme={null}

443# 新增本機範圍的 server (預設)

444claude mcp add --transport http stripe https://mcp.stripe.com

445 

446# 明確指定本機範圍

447claude mcp add --transport http stripe --scope local https://mcp.stripe.com

448```

449 

450當您從 `/path/to/your/project` 執行命令時,該命令會將 server 寫入 `~/.claude.json` 中您目前專案的項目。下面的範例顯示結果:

451 

452```json theme={null}

453{

454 "projects": {

455 "/path/to/your/project": {

456 "mcpServers": {

457 "stripe": {

458 "type": "http",

459 "url": "https://mcp.stripe.com"

460 }

461 }

462 }

463 }

464}

465```

466 

467### Project scope

468 

469Project scope 的 servers 透過在專案根目錄中儲存配置在 `.mcp.json` 檔案中來啟用團隊協作。此檔案設計為簽入版本控制,確保所有團隊成員都能存取相同的 MCP 工具和服務。新增 project scope 的 server 時,Claude Code 會自動建立或更新此檔案,使用適當的配置結構。

470 

471```bash theme={null}

472# 新增 project scope 的 server

473claude mcp add --transport http paypal --scope project https://mcp.paypal.com/mcp

474```

475 

476產生的 `.mcp.json` 檔案遵循標準化格式:

477 

478```json theme={null}

479{

480 "mcpServers": {

481 "shared-server": {

482 "command": "/path/to/server",

483 "args": [],

484 "env": {}

485 }

486 }

487}

488```

489 

490出於安全考慮,Claude Code 在使用來自 `.mcp.json` 檔案的 project scope servers 之前會提示批准。如果您需要重設這些批准選擇,請使用 `claude mcp reset-project-choices` 命令。

491 

492### User scope

493 

494User scope 的 servers 儲存在 `~/.claude.json` 中,並提供跨專案可存取性,使其在您機器上的所有專案中可用,同時對您的使用者帳戶保持私密。此範圍非常適合個人公用程式 servers、開發工具或您在不同專案中經常使用的服務。

495 

496```bash theme={null}

497# 新增使用者 server

498claude mcp add --transport http hubspot --scope user https://mcp.hubspot.com/anthropic

499```

500 

501### Scope 階層和優先順序

502 

503當相同的 server 在多個位置定義時,Claude Code 連接到它一次,使用來自最高優先順序來源的定義:

504 

5051. Local scope

5062. Project scope

5073. User scope

5084. [Plugin-provided servers](/zh-TW/plugins)

5095. [claude.ai connectors](#use-mcp-servers-from-claude-ai)

510 

511三個範圍按名稱符合重複項。Plugins 和 connectors 按端點符合,因此指向與上述 server 相同 URL 或命令的端點被視為重複項。

512 

513### `.mcp.json` 中的環境變數擴展

514 

515Claude Code 支援 `.mcp.json` 檔案中的環境變數擴展,允許團隊共享配置,同時保持機器特定路徑和 API 金鑰等敏感值的靈活性。

516 

517**支援的語法:**

518 

519* `${VAR}` - 擴展為環境變數 `VAR` 的值

520* `${VAR:-default}` - 如果設定了 `VAR`,則擴展為 `VAR`,否則使用 `default`

521 

522**擴展位置:**

523環境變數可以在以下位置擴展:

524 

525* `command` - server 可執行檔路徑

526* `args` - 命令列引數

527* `env` - 傳遞給 server 的環境變數

528* `url` - 對於 HTTP server 類型

529* `headers` - 對於 HTTP server 驗證

530 

531**使用變數擴展的範例:**

532 

533```json theme={null}

534{

535 "mcpServers": {

536 "api-server": {

537 "type": "http",

538 "url": "${API_BASE_URL:-https://api.example.com}/mcp",

539 "headers": {

540 "Authorization": "Bearer ${API_KEY}"

541 }

542 }

543 }

544}

545```

546 

547如果未設定必需的環境變數且沒有預設值,Claude Code 將無法解析配置。

548 

549## 實用範例

550 

551{/* ### 範例:使用 Playwright 自動化瀏覽器測試

552 

553```bash

554claude mcp add --transport stdio playwright -- npx -y @playwright/mcp@latest

555```

556 

557然後編寫並執行瀏覽器測試:

558 

559```text

560Test if the login flow works with test@example.com

561```

562```text

563Take a screenshot of the checkout page on mobile

564```

565```text

566Verify that the search feature returns results

567``` */}

568 

569### 範例:使用 Sentry 監控錯誤

570 

571```bash theme={null}

572claude mcp add --transport http sentry https://mcp.sentry.dev/mcp

573```

574 

575使用您的 Sentry 帳戶進行驗證:

576 

577```text theme={null}

578/mcp

579```

580 

581然後除錯生產問題:

582 

583```text theme={null}

584過去 24 小時內最常見的錯誤是什麼?

585```

586 

587```text theme={null}

588顯示錯誤 ID abc123 的堆疊追蹤

589```

590 

591```text theme={null}

592哪個部署引入了這些新錯誤?

593```

594 

595### 範例:連接到 GitHub 進行程式碼審查

596 

597GitHub 的遠端 MCP server 使用作為標頭傳遞的 GitHub 個人存取 token 進行驗證。若要取得一個,請開啟您的 [GitHub token 設定](https://github.com/settings/personal-access-tokens),產生一個新的細粒度 token,具有對您希望 Claude 使用的儲存庫的存取權,然後新增 server:

598 

599```bash theme={null}

600claude mcp add --transport http github https://api.githubcopilot.com/mcp/ \

601 --header "Authorization: Bearer YOUR_GITHUB_PAT"

602```

603 

604然後使用 GitHub:

605 

606```text theme={null}

607審查 PR #456 並建議改進

608```

609 

610```text theme={null}

611為我們剛發現的錯誤建立新問題

612```

613 

614```text theme={null}

615顯示所有指派給我的開放 PRs

616```

617 

618### 範例:查詢您的 PostgreSQL 資料庫

619 

620```bash theme={null}

621claude mcp add --transport stdio db -- npx -y @bytebase/dbhub \

622 --dsn "postgresql://readonly:pass@prod.db.com:5432/analytics"

623```

624 

625然後自然地查詢您的資料庫:

626 

627```text theme={null}

628本月我們的總收入是多少?

629```

630 

631```text theme={null}

632顯示 orders 表的架構

633```

634 

635```text theme={null}

636找到 90 天內未進行購買的客戶

637```

638 

639## 使用遠端 MCP servers 進行驗證

640 

641許多雲端 MCP servers 需要驗證。Claude Code 支援 OAuth 2.0 以進行安全連接。

642 

643<Steps>

644 <Step title="新增需要驗證的 server">

645 例如:

646 

647 ```bash theme={null}

648 claude mcp add --transport http sentry https://mcp.sentry.dev/mcp

649 ```

650 </Step>

651 

652 <Step title="在 Claude Code 中使用 /mcp 命令">

653 在 Claude Code 中,使用命令:

654 

655 ```text theme={null}

656 /mcp

657 ```

658 

659 然後按照瀏覽器中的步驟登入。

660 </Step>

661</Steps>

662 

663<Tip>

664 提示:

665 

666 * 驗證 tokens 安全儲存並自動重新整理

667 * 使用 `/mcp` 功能表中的「Clear authentication」撤銷存取權

668 * 如果瀏覽器未自動開啟,請複製提供的 URL 並手動開啟

669 * 如果瀏覽器重新導向在驗證後失敗並出現連接錯誤,請將瀏覽器位址列中的完整回呼 URL 貼到 Claude Code 中出現的 URL 提示中

670 * OAuth 驗證適用於 HTTP servers

671</Tip>

672 

673### 使用固定的 OAuth 回呼連接埠

674 

675某些 MCP servers 需要預先註冊的特定重新導向 URI。根據預設,Claude Code 為 OAuth 回呼選擇隨機可用連接埠。使用 `--callback-port` 固定連接埠,使其符合 `http://localhost:PORT/callback` 形式的預先註冊重新導向 URI。

676 

677您可以單獨使用 `--callback-port` (使用動態用戶端註冊) 或與 `--client-id` 一起使用 (使用預先配置的認證)。

678 

679```bash theme={null}

680# 使用動態用戶端註冊的固定回呼連接埠

681claude mcp add --transport http \

682 --callback-port 8080 \

683 my-server https://mcp.example.com/mcp

684```

685 

686### 使用預先配置的 OAuth 認證

687 

688某些 MCP servers 不支援自動 OAuth 設定。如果您看到類似「Incompatible auth server: does not support dynamic client registration」的錯誤,server 需要預先配置的認證。Claude Code 也支援使用 Client ID Metadata Document (CIMD) 而不是 Dynamic Client Registration 的 servers,並自動探索這些。如果自動探索失敗,請先透過 server 的開發人員入口網站註冊 OAuth 應用程式,然後在新增 server 時提供認證。

689 

690<Steps>

691 <Step title="使用 server 註冊 OAuth 應用程式">

692 透過 server 的開發人員入口網站建立應用程式,並記下您的用戶端 ID 和用戶端密碼。

693 

694 許多 servers 也需要重新導向 URI。如果是這樣,請選擇一個連接埠並以 `http://localhost:PORT/callback` 的格式註冊重新導向 URI。在下一步中使用該相同連接埠搭配 `--callback-port`。

695 </Step>

696 

697 <Step title="使用您的認證新增 server">

698 選擇以下方法之一。用於 `--callback-port` 的連接埠可以是任何可用的連接埠。它只需要符合您在上一步中註冊的重新導向 URI。

699 

700 <Tabs>

701 <Tab title="claude mcp add">

702 使用 `--client-id` 傳遞您應用程式的用戶端 ID。`--client-secret` 旗標會提示輸入帶有遮罩輸入的密碼:

703 

704 ```bash theme={null}

705 claude mcp add --transport http \

706 --client-id your-client-id --client-secret --callback-port 8080 \

707 my-server https://mcp.example.com/mcp

708 ```

709 </Tab>

710 

711 <Tab title="claude mcp add-json">

712 在 JSON 配置中包含 `oauth` 物件,並將 `--client-secret` 作為單獨的旗標傳遞:

713 

714 ```bash theme={null}

715 claude mcp add-json my-server \

716 '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"clientId":"your-client-id","callbackPort":8080}}' \

717 --client-secret

718 ```

719 </Tab>

720 

721 <Tab title="claude mcp add-json (僅回呼連接埠)">

722 使用 `--callback-port` 而不使用用戶端 ID 來固定連接埠,同時使用動態用戶端註冊:

723 

724 ```bash theme={null}

725 claude mcp add-json my-server \

726 '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"callbackPort":8080}}'

727 ```

728 </Tab>

729 

730 <Tab title="CI / env var">

731 透過環境變數設定密碼以跳過互動式提示:

732 

733 ```bash theme={null}

734 MCP_CLIENT_SECRET=your-secret claude mcp add --transport http \

735 --client-id your-client-id --client-secret --callback-port 8080 \

736 my-server https://mcp.example.com/mcp

737 ```

738 </Tab>

739 </Tabs>

740 </Step>

741 

742 <Step title="在 Claude Code 中進行驗證">

743 在 Claude Code 中執行 `/mcp` 並按照瀏覽器登入流程。

744 </Step>

745</Steps>

746 

747<Tip>

748 提示:

749 

750 * 用戶端密碼安全地儲存在您的系統鑰匙圈 (macOS) 或認證檔案中,而不是在您的配置中

751 * 如果 server 使用沒有密碼的公開 OAuth 用戶端,請僅使用 `--client-id` 而不使用 `--client-secret`

752 * `--callback-port` 可以與或不與 `--client-id` 一起使用

753 * 這些旗標僅適用於 HTTP 和 SSE 傳輸。它們對 stdio servers 沒有影響

754 * 使用 `claude mcp get <name>` 驗證為 server 配置了 OAuth 認證

755</Tip>

756 

757### 覆蓋 OAuth 中繼資料探索

758 

759指向 Claude Code 特定的 OAuth 授權 server 中繼資料 URL 以繞過預設探索鏈。當 MCP server 的標準端點出錯時,或當您想要透過內部代理路由探索時,設定 `authServerMetadataUrl`。根據預設,Claude Code 首先檢查 RFC 9728 Protected Resource Metadata at `/.well-known/oauth-protected-resource`,然後回退到 RFC 8414 authorization server metadata at `/.well-known/oauth-authorization-server`。

760 

761在 `.mcp.json` 中 server 配置的 `oauth` 物件中設定 `authServerMetadataUrl`:

762 

763```json theme={null}

764{

765 "mcpServers": {

766 "my-server": {

767 "type": "http",

768 "url": "https://mcp.example.com/mcp",

769 "oauth": {

770 "authServerMetadataUrl": "https://auth.example.com/.well-known/openid-configuration"

771 }

772 }

773 }

774}

775```

776 

777URL 必須使用 `https://`。`authServerMetadataUrl` 需要 Claude Code v2.1.64 或更新版本。中繼資料 URL 的 `scopes_supported` 會覆蓋上游 server 宣傳的範圍。

778 

779### 限制 OAuth 範圍

780 

781設定 `oauth.scopes` 以固定 Claude Code 在授權流程中要求的範圍。這是限制 MCP server 到安全團隊批准的子集的支援方式,當上游授權 server 宣傳的範圍超過您想要授予的範圍時。該值是單個空格分隔的字串,符合 RFC 6749 §3.3 中的 `scope` 參數格式。

782 

783```json theme={null}

784{

785 "mcpServers": {

786 "slack": {

787 "type": "http",

788 "url": "https://mcp.slack.com/mcp",

789 "oauth": {

790 "scopes": "channels:read chat:write search:read"

791 }

792 }

793 }

794}

795```

796 

797`oauth.scopes` 優先於 `authServerMetadataUrl` 和 server 在 `/.well-known` 發現的範圍。保持未設定以讓 MCP server 決定要求的範圍集。

798 

799如果授權 server 在 `scopes_supported` 中宣傳 `offline_access`,Claude Code 會將其附加到固定範圍,以便可以在沒有新瀏覽器登入的情況下重新整理存取 token。

800 

801如果 server 稍後為工具呼叫傳回 403 `insufficient_scope`,Claude Code 會使用相同的固定範圍重新驗證。當您需要的工具需要固定範圍外的範圍時,擴展 `oauth.scopes`。

802 

803### 使用動態標頭進行自訂驗證

804 

805如果您的 MCP server 使用 OAuth 以外的驗證方案 (例如 Kerberos、短期 tokens 或內部 SSO),請使用 `headersHelper` 在連接時產生請求標頭。Claude Code 執行命令並將其輸出合併到連接標頭中。

806 

807```json theme={null}

808{

809 "mcpServers": {

810 "internal-api": {

811 "type": "http",

812 "url": "https://mcp.internal.example.com",

813 "headersHelper": "/opt/bin/get-mcp-auth-headers.sh"

814 }

815 }

816}

817```

818 

819命令也可以內聯:

820 

821```json theme={null}

822{

823 "mcpServers": {

824 "internal-api": {

825 "type": "http",

826 "url": "https://mcp.internal.example.com",

827 "headersHelper": "echo '{\"Authorization\": \"Bearer '\"$(get-token)\"'\"}'"

828 }

829 }

830}

831```

832 

833**需求:**

834 

835* 命令必須將字串鍵值對的 JSON 物件寫入 stdout

836* 命令在 shell 中執行,逾時時間為 10 秒

837* 動態標頭會覆蓋任何具有相同名稱的靜態 `headers`

838 

839helper 在每次連接時執行 (在 session 啟動和重新連接時)。沒有快取,因此您的指令碼負責任何 token 重複使用。

840 

841Claude Code 在執行 helper 時設定這些環境變數:

842 

843| 變數 | 值 |

844| :---------------------------- | :--------------- |

845| `CLAUDE_CODE_MCP_SERVER_NAME` | MCP server 的名稱 |

846| `CLAUDE_CODE_MCP_SERVER_URL` | MCP server 的 URL |

847 

848使用這些來編寫為多個 MCP servers 服務的單一 helper 指令碼。

849 

850<Note>

851 `headersHelper` 執行任意 shell 命令。在專案或本機範圍定義時,它僅在您接受工作區信任對話框後執行。

852</Note>

853 

854## 從 JSON 配置新增 MCP servers

855 

856如果您有 MCP server 的 JSON 配置,您可以直接新增它:

857 

858<Steps>

859 <Step title="從 JSON 新增 MCP server">

860 ```bash theme={null}

861 # 基本語法

862 claude mcp add-json <name> '<json>'

863 

864 # 範例:使用 JSON 配置新增 HTTP server

865 claude mcp add-json weather-api '{"type":"http","url":"https://api.weather.com/mcp","headers":{"Authorization":"Bearer token"}}'

866 

867 # 範例:使用 JSON 配置新增 stdio server

868 claude mcp add-json local-weather '{"type":"stdio","command":"/path/to/weather-cli","args":["--api-key","abc123"],"env":{"CACHE_DIR":"/tmp"}}'

869 

870 # 範例:使用預先配置的 OAuth 認證新增 HTTP server

871 claude mcp add-json my-server '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"clientId":"your-client-id","callbackPort":8080}}' --client-secret

872 ```

873 </Step>

874 

875 <Step title="驗證 server 已新增">

876 ```bash theme={null}

877 claude mcp get weather-api

878 ```

879 </Step>

880</Steps>

881 

882<Tip>

883 提示:

884 

885 * 確保 JSON 在您的 shell 中正確逸出

886 * JSON 必須符合 MCP server 配置架構

887 * 您可以使用 `--scope user` 將 server 新增到您的使用者配置,而不是專案特定的配置

888</Tip>

889 

890## 從 Claude Desktop 匯入 MCP servers

891 

892如果您已在 Claude Desktop 中配置了 MCP servers,您可以匯入它們:

893 

894<Steps>

895 <Step title="從 Claude Desktop 匯入 servers">

896 ```bash theme={null}

897 # 基本語法

898 claude mcp add-from-claude-desktop

899 ```

900 </Step>

901 

902 <Step title="選擇要匯入的 servers">

903 執行命令後,您會看到一個互動式對話框,允許您選擇要匯入的 servers。

904 </Step>

905 

906 <Step title="驗證 servers 已匯入">

907 ```bash theme={null}

908 claude mcp list

909 ```

910 </Step>

911</Steps>

912 

913<Tip>

914 提示:

915 

916 * 此功能僅適用於 macOS 和 Windows Subsystem for Linux (WSL)

917 * 它從這些平台上的標準位置讀取 Claude Desktop 配置檔案

918 * 使用 `--scope user` 旗標將 servers 新增到您的使用者配置

919 * 匯入的 servers 將具有與 Claude Desktop 中相同的名稱

920 * 如果已存在相同名稱的 servers,它們將獲得數字尾碼 (例如,`server_1`)

921</Tip>

922 

923## 使用來自 Claude.ai 的 MCP servers

924 

925如果您已使用 [Claude.ai](https://claude.ai) 帳戶登入 Claude Code,您在 Claude.ai 中新增的 MCP servers 會自動在 Claude Code 中可用:

926 

927<Steps>

928 <Step title="在 Claude.ai 中配置 MCP servers">

929 在 [claude.ai/customize/connectors](https://claude.ai/customize/connectors) 新增 servers。在 Team 和 Enterprise 計畫上,只有管理員可以新增 servers。

930 </Step>

931 

932 <Step title="驗證 MCP server">

933 在 Claude.ai 中完成任何必需的驗證步驟。

934 </Step>

935 

936 <Step title="在 Claude Code 中檢視和管理 servers">

937 在 Claude Code 中,使用命令:

938 

939 ```text theme={null}

940 /mcp

941 ```

942 

943 Claude.ai servers 在列表中出現,並有指示器顯示它們來自 Claude.ai。

944 </Step>

945</Steps>

946 

947若要在 Claude Code 中停用 claude.ai MCP servers,請將 `ENABLE_CLAUDEAI_MCP_SERVERS` 環境變數設定為 `false`:

948 

949```bash theme={null}

950ENABLE_CLAUDEAI_MCP_SERVERS=false claude

951```

952 

953## 使用 Claude Code 作為 MCP server

954 

955您可以使用 Claude Code 本身作為其他應用程式可以連接到的 MCP server:

956 

957```bash theme={null}

958# 啟動 Claude 作為 stdio MCP server

959claude mcp serve

960```

961 

962您可以透過將此配置新增到 claude\_desktop\_config.json 在 Claude Desktop 中使用它:

963 

964```json theme={null}

965{

966 "mcpServers": {

967 "claude-code": {

968 "type": "stdio",

969 "command": "claude",

970 "args": ["mcp", "serve"],

971 "env": {}

972 }

973 }

974}

975```

976 

977<Warning>

978 **配置可執行檔路徑**:`command` 欄位必須參考 Claude Code 可執行檔。如果 `claude` 命令不在您的系統 PATH 中,您需要指定可執行檔的完整路徑。

979 

980 若要找到完整路徑:

981 

982 ```bash theme={null}

983 which claude

984 ```

985 

986 然後在您的配置中使用完整路徑:

987 

988 ```json theme={null}

989 {

990 "mcpServers": {

991 "claude-code": {

992 "type": "stdio",

993 "command": "/full/path/to/claude",

994 "args": ["mcp", "serve"],

995 "env": {}

996 }

997 }

998 }

999 ```

1000 

1001 沒有正確的可執行檔路徑,您會遇到類似 `spawn claude ENOENT` 的錯誤。

1002</Warning>

1003 

1004<Tip>

1005 提示:

1006 

1007 * server 提供對 Claude 工具 (如 View、Edit、LS 等) 的存取

1008 * 在 Claude Desktop 中,嘗試要求 Claude 讀取目錄中的檔案、進行編輯等。

1009 * 請注意,此 MCP server 僅將 Claude Code 的工具公開給您的 MCP 用戶端,因此您自己的用戶端負責為個別工具呼叫實現使用者確認。

1010</Tip>

1011 

1012## MCP 輸出限制和警告

1013 

1014當 MCP 工具產生大型輸出時,Claude Code 可幫助管理 token 使用情況,以防止淹沒您的對話內容:

1015 

1016* **輸出警告閾值**:當任何 MCP 工具輸出超過 10,000 個 tokens 時,Claude Code 會顯示警告

1017* **可配置限制**:您可以使用 `MAX_MCP_OUTPUT_TOKENS` 環境變數調整最大允許的 MCP 輸出 tokens

1018* **預設限制**:預設最大值為 25,000 個 tokens

1019* **範圍**:環境變數適用於未宣告自己限制的工具。設定 [`anthropic/maxResultSizeChars`](#raise-the-limit-for-a-specific-tool) 的工具使用該值代替文字內容,無論 `MAX_MCP_OUTPUT_TOKENS` 設定為什麼。傳回影像資料的工具仍受 `MAX_MCP_OUTPUT_TOKENS` 限制

1020 

1021若要增加產生大型輸出的工具的限制:

1022 

1023```bash theme={null}

1024export MAX_MCP_OUTPUT_TOKENS=50000

1025claude

1026```

1027 

1028這在使用以下 MCP servers 時特別有用:

1029 

1030* 查詢大型資料集或資料庫

1031* 產生詳細報告或文件

1032* 處理廣泛的日誌檔案或除錯資訊

1033 

1034### 提高特定工具的限制

1035 

1036如果您正在建立 MCP server,您可以透過在工具的 `tools/list` 回應項目中設定 `_meta["anthropic/maxResultSizeChars"]` 來允許個別工具傳回超過預設持久化到磁碟閾值的結果。Claude Code 將該工具的閾值提高到註解值,最高為 500,000 個字元的硬上限。

1037 

1038這對於傳回本質上很大但必要的輸出的工具很有用,例如資料庫架構或完整檔案樹。沒有註解,超過預設閾值的結果會持久化到磁碟,並在對話中被檔案參考取代。

1039 

1040```json theme={null}

1041{

1042 "name": "get_schema",

1043 "description": "Returns the full database schema",

1044 "_meta": {

1045 "anthropic/maxResultSizeChars": 200000

1046 }

1047}

1048```

1049 

1050對於文字內容,註解獨立於 `MAX_MCP_OUTPUT_TOKENS` 應用,因此使用者無需提高環境變數來使用宣告它的工具。傳回影像資料的工具仍受 token 限制。

1051 

1052<Warning>

1053 如果您經常遇到特定 MCP servers 的輸出警告,請考慮增加 `MAX_MCP_OUTPUT_TOKENS` 限制。您也可以要求 server 作者新增 `anthropic/maxResultSizeChars` 註解或分頁其回應。註解對傳回影像內容的工具沒有影響;對於這些,提高 `MAX_MCP_OUTPUT_TOKENS` 是唯一的選項。

1054</Warning>

1055 

1056## 回應 MCP 引發請求

1057 

1058MCP servers 可以使用引發在任務中途要求您提供結構化輸入。當 server 需要無法自行取得的資訊時,Claude Code 會顯示互動式對話框並將您的回應傳回給 server。您無需進行任何配置:當 server 要求時,引發對話框會自動出現。

1059 

1060Servers 可以透過兩種方式要求輸入:

1061 

1062* **表單模式**:Claude Code 顯示一個對話框,其中包含 server 定義的表單欄位 (例如,使用者名稱和密碼提示)。填入欄位並提交。

1063* **URL 模式**:Claude Code 開啟瀏覽器 URL 以進行驗證或批准。在瀏覽器中完成流程,然後在 CLI 中確認。

1064 

1065若要自動回應引發請求而不顯示對話框,請使用 [`Elicitation` hook](/zh-TW/hooks#Elicitation)。

1066 

1067如果您正在建立使用引發的 MCP server,請參閱 [MCP 引發規格](https://modelcontextprotocol.io/docs/learn/client-concepts#elicitation),了解協議詳細資訊和架構範例。

1068 

1069## 使用 MCP 資源

1070 

1071MCP servers 可以公開資源,您可以使用 @ 提及來參考,類似於您參考檔案的方式。

1072 

1073### 參考 MCP 資源

1074 

1075<Steps>

1076 <Step title="列出可用資源">

1077 在您的提示中輸入 `@` 以查看所有連接的 MCP servers 中的可用資源。資源與檔案一起出現在自動完成功能表中。

1078 </Step>

1079 

1080 <Step title="參考特定資源">

1081 使用格式 `@server:protocol://resource/path` 來參考資源:

1082 

1083 ```text theme={null}

1084 Can you analyze @github:issue://123 and suggest a fix?

1085 ```

1086 

1087 ```text theme={null}

1088 Please review the API documentation at @docs:file://api/authentication

1089 ```

1090 </Step>

1091 

1092 <Step title="多個資源參考">

1093 您可以在單個提示中參考多個資源:

1094 

1095 ```text theme={null}

1096 Compare @postgres:schema://users with @docs:file://database/user-model

1097 ```

1098 </Step>

1099</Steps>

1100 

1101<Tip>

1102 提示:

1103 

1104 * 資源在參考時會自動取得並作為附件包含

1105 * 資源路徑在 @ 提及自動完成中可進行模糊搜尋

1106 * Claude Code 在 servers 支援時自動提供列出和讀取 MCP 資源的工具

1107 * 資源可以包含 MCP server 提供的任何類型的內容 (文字、JSON、結構化資料等)

1108</Tip>

1109 

1110## 使用 MCP Tool Search 進行擴展

1111 

1112Tool search 透過延遲工具定義直到 Claude 需要它們來保持 MCP 內容使用低。只有工具名稱在 session 啟動時載入,因此新增更多 MCP servers 對您的內容視窗的影響最小。

1113 

1114### 工作原理

1115 

1116Tool search 預設啟用。MCP 工具被延遲而不是預先載入到內容中,Claude 使用搜尋工具在任務需要時探索相關的工具。只有 Claude 實際使用的工具才會進入內容。從您的角度來看,MCP 工具的工作方式完全相同。

1117 

1118如果您偏好基於閾值的載入,請設定 `ENABLE_TOOL_SEARCH=auto` 以在工具適合內容視窗的 10% 內時預先載入架構,並僅延遲溢出。請參閱 [配置 tool search](#configure-tool-search) 了解所有選項。

1119 

1120### 對於 MCP server 作者

1121 

1122如果您正在建立 MCP server,啟用 Tool Search 時 server 指示欄位會變得更有用。Server 指示可幫助 Claude 了解何時搜尋您的工具,類似於 [skills](/zh-TW/skills) 的工作方式。

1123 

1124新增清晰、描述性的 server 指示,說明:

1125 

1126* 您的工具處理的任務類別

1127* Claude 應何時搜尋您的工具

1128* 您的 server 提供的關鍵功能

1129 

1130Claude Code 將工具描述和 server 指示截斷為每個 2KB。保持簡潔以避免截斷,並將關鍵詳細資訊放在開始處。

1131 

1132### 配置 tool search

1133 

1134Tool search 預設啟用:MCP 工具被延遲並按需探索。當 `ANTHROPIC_BASE_URL` 指向非第一方主機時,tool search 預設停用,因為大多數代理不轉發 `tool_reference` 區塊。設定 `ENABLE_TOOL_SEARCH` 明確選擇加入。此功能需要支援 `tool_reference` 區塊的模型:Sonnet 4 及更新版本,或 Opus 4 及更新版本。Haiku 模型不支援 tool search。

1135 

1136使用 `ENABLE_TOOL_SEARCH` 環境變數控制 tool search 行為:

1137 

1138| 值 | 行為 |

1139| :--------- | :------------------------------------------------------- |

1140| (未設定) | 所有 MCP 工具被延遲並按需載入。當 `ANTHROPIC_BASE_URL` 是非第一方主機時回退到預先載入 |

1141| `true` | 所有 MCP 工具被延遲,包括在 Vertex AI 上和對於非第一方 `ANTHROPIC_BASE_URL` |

1142| `auto` | 閾值模式:如果工具適合內容視窗的 10% 內,則預先載入,否則延遲 |

1143| `auto:<N>` | 閾值模式,具有自訂百分比,其中 `<N>` 是 0-100 (例如,`auto:5` 表示 5%) |

1144| `false` | 所有 MCP 工具預先載入,無延遲 |

1145 

1146```bash theme={null}

1147# 使用自訂 5% 閾值

1148ENABLE_TOOL_SEARCH=auto:5 claude

1149 

1150# 完全停用 tool search

1151ENABLE_TOOL_SEARCH=false claude

1152```

1153 

1154或在您的 [settings.json `env` 欄位](/zh-TW/settings#available-settings) 中設定值。

1155 

1156您也可以特別停用 `ToolSearch` 工具:

1157 

1158```json theme={null}

1159{

1160 "permissions": {

1161 "deny": ["ToolSearch"]

1162 }

1163}

1164```

1165 

1166### 豁免伺服器延遲

1167 

1168如果伺服器的工具應始終對 Claude 可見而無需搜尋步驟,請在該伺服器的配置中將 `alwaysLoad` 設定為 `true`。該伺服器的每個工具隨後都會在 session 啟動時載入到內容中,無論 `ENABLE_TOOL_SEARCH` 設定如何。對於 Claude 在每個回合都需要的少量工具,請使用此選項,因為每個預先載入的工具會消耗內容,否則這些內容將可用於您的對話。

1169 

1170以下 `.mcp.json` 項目豁免一個 HTTP 伺服器,同時保持其他伺服器延遲:

1171 

1172```json theme={null}

1173{

1174 "mcpServers": {

1175 "core-tools": {

1176 "type": "http",

1177 "url": "https://mcp.example.com/mcp",

1178 "alwaysLoad": true

1179 }

1180 }

1181}

1182```

1183 

1184`alwaysLoad` 欄位在所有伺服器類型上可用,需要 Claude Code v2.1.121 或更新版本。MCP 伺服器也可以透過在工具的 `_meta` 物件中包含 `"anthropic/alwaysLoad": true` 來標記個別工具為始終載入,這對該工具只有相同的效果。

1185 

1186## 使用 MCP 提示作為命令

1187 

1188MCP servers 可以公開提示,這些提示在 Claude Code 中變成可用的命令。

1189 

1190### 執行 MCP 提示

1191 

1192<Steps>

1193 <Step title="探索可用提示">

1194 輸入 `/` 以查看所有可用命令,包括來自 MCP servers 的命令。MCP 提示以 `/mcp__servername__promptname` 的格式出現。

1195 </Step>

1196 

1197 <Step title="執行沒有引數的提示">

1198 ```text theme={null}

1199 /mcp__github__list_prs

1200 ```

1201 </Step>

1202 

1203 <Step title="執行帶有引數的提示">

1204 許多提示接受引數。在命令後以空格分隔的方式傳遞它們:

1205 

1206 ```text theme={null}

1207 /mcp__github__pr_review 456

1208 ```

1209 

1210 ```text theme={null}

1211 /mcp__jira__create_issue "Bug in login flow" high

1212 ```

1213 </Step>

1214</Steps>

1215 

1216<Tip>

1217 提示:

1218 

1219 * MCP 提示從連接的 servers 動態探索

1220 * 引數根據提示的定義參數進行解析

1221 * 提示結果直接注入到對話中

1222 * Server 和提示名稱已標準化 (空格變成底線)

1223</Tip>

1224 

1225## 受管理的 MCP 配置

1226 

1227對於需要對 MCP servers 進行集中控制的組織,Claude Code 支援兩個配置選項:

1228 

12291. **使用 `managed-mcp.json` 的獨佔控制**:部署一組固定的 MCP servers,使用者無法修改或擴展

12302. **使用允許清單/拒絕清單的基於原則的控制**:允許使用者新增自己的 servers,但限制允許的 servers

1231 

1232這些選項允許 IT 管理員:

1233 

1234* **控制 MCP servers 員工可以存取的內容**:在整個組織中部署一組標準化的已批准 MCP servers

1235* **防止未授權的 MCP servers**:限制使用者新增未批准的 MCP servers

1236* **完全停用 MCP**:如果需要,完全移除 MCP 功能

1237 

1238### 選項 1:使用 managed-mcp.json 的獨佔控制

1239 

1240當您部署 `managed-mcp.json` 檔案時,它對所有 MCP servers 進行**獨佔控制**。使用者無法新增、修改或使用此檔案中定義的 MCP servers 以外的任何 MCP servers。這是希望完全控制的組織的最簡單方法。

1241 

1242系統管理員將配置檔案部署到系統範圍的目錄:

1243 

1244* macOS:`/Library/Application Support/ClaudeCode/managed-mcp.json`

1245* Linux 和 WSL:`/etc/claude-code/managed-mcp.json`

1246* Windows:`C:\Program Files\ClaudeCode\managed-mcp.json`

1247 

1248<Note>

1249 這些是系統範圍的路徑 (不是像 `~/Library/...` 這樣的使用者主目錄),需要管理員權限。它們設計為由 IT 管理員部署。

1250</Note>

1251 

1252`managed-mcp.json` 檔案使用與標準 `.mcp.json` 檔案相同的格式:

1253 

1254```json theme={null}

1255{

1256 "mcpServers": {

1257 "github": {

1258 "type": "http",

1259 "url": "https://api.githubcopilot.com/mcp/"

1260 },

1261 "sentry": {

1262 "type": "http",

1263 "url": "https://mcp.sentry.dev/mcp"

1264 },

1265 "company-internal": {

1266 "type": "stdio",

1267 "command": "/usr/local/bin/company-mcp-server",

1268 "args": ["--config", "/etc/company/mcp-config.json"],

1269 "env": {

1270 "COMPANY_API_URL": "https://internal.company.com"

1271 }

1272 }

1273 }

1274}

1275```

1276 

1277### 選項 2:使用允許清單和拒絕清單的基於原則的控制

1278 

1279管理員可以允許使用者配置自己的 MCP servers,同時對允許的 servers 強制執行限制,而不是進行獨佔控制。此方法在 [受管理設定檔案](/zh-TW/settings#settings-files) 中使用 `allowedMcpServers` 和 `deniedMcpServers`。

1280 

1281<Note>

1282 **在選項之間選擇**:當您想要部署一組固定的 servers 而不進行使用者自訂時,使用選項 1 (`managed-mcp.json`)。當您想要允許使用者在原則約束內新增自己的 servers 時,使用選項 2 (允許清單/拒絕清單)。

1283</Note>

1284 

1285#### 限制選項

1286 

1287允許清單或拒絕清單中的每個項目可以透過三種方式限制 servers:

1288 

12891. **按 server 名稱** (`serverName`):符合 server 的已配置名稱

12902. **按命令** (`serverCommand`):符合用於啟動 stdio servers 的確切命令和引數

12913. **按 URL 模式** (`serverUrl`):符合遠端 server URLs,支援萬用字元

1292 

1293**重要**:每個項目必須恰好有 `serverName`、`serverCommand` 或 `serverUrl` 之一。

1294 

1295#### 配置範例

1296 

1297```json theme={null}

1298{

1299 "allowedMcpServers": [

1300 // 按 server 名稱允許

1301 { "serverName": "github" },

1302 { "serverName": "sentry" },

1303 

1304 // 按確切命令允許 (對於 stdio servers)

1305 { "serverCommand": ["npx", "-y", "@modelcontextprotocol/server-filesystem"] },

1306 { "serverCommand": ["python", "/usr/local/bin/approved-server.py"] },

1307 

1308 // 按 URL 模式允許 (對於遠端 servers)

1309 { "serverUrl": "https://mcp.company.com/*" },

1310 { "serverUrl": "https://*.internal.corp/*" }

1311 ],

1312 "deniedMcpServers": [

1313 // 按 server 名稱阻止

1314 { "serverName": "dangerous-server" },

1315 

1316 // 按確切命令阻止 (對於 stdio servers)

1317 { "serverCommand": ["npx", "-y", "unapproved-package"] },

1318 

1319 // 按 URL 模式阻止 (對於遠端 servers)

1320 { "serverUrl": "https://*.untrusted.com/*" }

1321 ]

1322}

1323```

1324 

1325#### 基於命令的限制如何工作

1326 

1327**確切符合**:

1328 

1329* 命令陣列必須**確切**符合 - 命令和所有引數的順序正確

1330* 範例:`["npx", "-y", "server"]` 將**不**符合 `["npx", "server"]` 或 `["npx", "-y", "server", "--flag"]`

1331 

1332**Stdio server 行為**:

1333 

1334* 當允許清單包含**任何** `serverCommand` 項目時,stdio servers **必須**符合其中一個命令

1335* Stdio servers 在存在命令限制時無法單獨按名稱通過

1336* 這確保管理員可以強制執行允許執行的命令

1337 

1338**非 stdio server 行為**:

1339 

1340* 遠端 servers (HTTP、SSE、WebSocket) 在允許清單中存在 `serverUrl` 項目時使用基於 URL 的符合

1341* 如果不存在 URL 項目,遠端 servers 會回退到基於名稱的符合

1342* 命令限制不適用於遠端 servers

1343 

1344#### 基於 URL 的限制如何工作

1345 

1346URL 模式使用 `*` 支援萬用字元以符合任何字元序列。這對於允許整個網域或子網域很有用。

1347 

1348**萬用字元範例**:

1349 

1350* `https://mcp.company.com/*` - 允許特定網域上的所有路徑

1351* `https://*.example.com/*` - 允許 example.com 的任何子網域

1352* `http://localhost:*/*` - 允許 localhost 上的任何連接埠

1353 

1354**遠端 server 行為**:

1355 

1356* 當允許清單包含**任何** `serverUrl` 項目時,遠端 servers **必須**符合其中一個 URL 模式

1357* 遠端 servers 在存在 URL 限制時無法單獨按名稱通過

1358* 這確保管理員可以強制執行允許的遠端端點

1359 

1360<Accordion title="範例:僅 URL 允許清單">

1361 ```json theme={null}

1362 {

1363 "allowedMcpServers": [

1364 { "serverUrl": "https://mcp.company.com/*" },

1365 { "serverUrl": "https://*.internal.corp/*" }

1366 ]

1367 }

1368 ```

1369 

1370 **結果**:

1371 

1372 * `https://mcp.company.com/api` 上的 HTTP server:✅ 允許 (符合 URL 模式)

1373 * `https://api.internal.corp/mcp` 上的 HTTP server:✅ 允許 (符合萬用字元子網域)

1374 * `https://external.com/mcp` 上的 HTTP server:❌ 阻止 (不符合任何 URL 模式)

1375 * 任何命令的 Stdio server:❌ 阻止 (沒有名稱或命令項目可符合)

1376</Accordion>

1377 

1378<Accordion title="範例:僅命令允許清單">

1379 ```json theme={null}

1380 {

1381 "allowedMcpServers": [

1382 { "serverCommand": ["npx", "-y", "approved-package"] }

1383 ]

1384 }

1385 ```

1386 

1387 **結果**:

1388 

1389 * 使用 `["npx", "-y", "approved-package"]` 的 Stdio server:✅ 允許 (符合命令)

1390 * 使用 `["node", "server.js"]` 的 Stdio server:❌ 阻止 (不符合命令)

1391 * 名為「my-api」的 HTTP server:❌ 阻止 (沒有名稱項目可符合)

1392</Accordion>

1393 

1394<Accordion title="範例:混合名稱和命令允許清單">

1395 ```json theme={null}

1396 {

1397 "allowedMcpServers": [

1398 { "serverName": "github" },

1399 { "serverCommand": ["npx", "-y", "approved-package"] }

1400 ]

1401 }

1402 ```

1403 

1404 **結果**:

1405 

1406 * 名為「local-tool」、使用 `["npx", "-y", "approved-package"]` 的 Stdio server:✅ 允許 (符合命令)

1407 * 名為「local-tool」、使用 `["node", "server.js"]` 的 Stdio server:❌ 阻止 (存在命令項目但不符合)

1408 * 名為「github」、使用 `["node", "server.js"]` 的 Stdio server:❌ 阻止 (存在命令限制時 stdio servers 必須符合命令)

1409 * 名為「github」的 HTTP server:✅ 允許 (符合名稱)

1410 * 名為「other-api」的 HTTP server:❌ 阻止 (名稱不符合)

1411</Accordion>

1412 

1413<Accordion title="範例:僅名稱允許清單">

1414 ```json theme={null}

1415 {

1416 "allowedMcpServers": [

1417 { "serverName": "github" },

1418 { "serverName": "internal-tool" }

1419 ]

1420 }

1421 ```

1422 

1423 **結果**:

1424 

1425 * 名為「github」、任何命令的 Stdio server:✅ 允許 (沒有命令限制)

1426 * 名為「internal-tool」、任何命令的 Stdio server:✅ 允許 (沒有命令限制)

1427 * 名為「github」的 HTTP server:✅ 允許 (符合名稱)

1428 * 任何名為「other」的 server:❌ 阻止 (名稱不符合)

1429</Accordion>

1430 

1431#### 允許清單行為 (`allowedMcpServers`)

1432 

1433* `undefined` (預設):無限制 - 使用者可以配置任何 MCP server

1434* 空陣列 `[]`:完全鎖定 - 使用者無法配置任何 MCP servers

1435* 項目清單:使用者只能配置符合名稱、命令或 URL 模式的 servers

1436 

1437#### 拒絕清單行為 (`deniedMcpServers`)

1438 

1439* `undefined` (預設):沒有 servers 被阻止

1440* 空陣列 `[]`:沒有 servers 被阻止

1441* 項目清單:指定的 servers 在所有範圍中被明確阻止

1442 

1443#### 重要注意事項

1444 

1445* **選項 1 和選項 2 可以結合**:如果 `managed-mcp.json` 存在,它具有獨佔控制,使用者無法新增 servers。允許清單/拒絕清單仍然適用於受管理的 servers 本身。

1446* **拒絕清單具有絕對優先順序**:如果 server 符合拒絕清單項目 (按名稱、命令或 URL),即使它在允許清單上也會被阻止

1447* 基於名稱、基於命令和基於 URL 的限制一起工作:如果 server 符合**任何**名稱項目、命令項目或 URL 模式,它就會通過 (除非被拒絕清單阻止)

1448 

1449<Note>

1450 **使用 `managed-mcp.json` 時**:使用者無法透過 `claude mcp add` 或配置檔案新增 MCP servers。`allowedMcpServers` 和 `deniedMcpServers` 設定仍然適用於篩選實際載入的受管理 servers。

1451</Note>

memory.md +408 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Claude 如何記住您的專案

6 

7> 使用 CLAUDE.md 檔案為 Claude 提供持久指令,並讓 Claude 透過自動記憶自動累積學習。

8 

9每個 Claude Code 工作階段都以全新的 context window 開始。兩個機制可以跨工作階段傳遞知識:

10 

11* **CLAUDE.md 檔案**:您編寫的指令,為 Claude 提供持久的上下文

12* **自動記憶**:Claude 根據您的更正和偏好自己編寫的筆記

13 

14本頁涵蓋如何:

15 

16* [編寫和組織 CLAUDE.md 檔案](#claude-md-files)

17* [使用 `.claude/rules/` 將規則範圍限定於特定檔案類型](#organize-rules-with-clauderules)

18* [配置自動記憶](#auto-memory),使 Claude 自動記筆記

19* [疑難排解](#troubleshoot-memory-issues)指令未被遵循的情況

20 

21## CLAUDE.md 與自動記憶

22 

23Claude Code 有兩個互補的記憶系統。兩者都在每次對話開始時載入。Claude 將它們視為上下文,而不是強制配置。您的指令越具體和簡潔,Claude 遵循它們的一致性就越高。

24 

25| | CLAUDE.md 檔案 | 自動記憶 |

26| :------- | :------------- | :--------------------- |

27| **誰編寫** | 您 | Claude |

28| **包含內容** | 指令和規則 | 學習和模式 |

29| **範圍** | 專案、使用者或組織 | 每個工作樹 |

30| **載入到** | 每個工作階段 | 每個工作階段(前 200 行或 25KB) |

31| **用於** | 編碼標準、工作流程、專案架構 | 建置命令、除錯見解、Claude 發現的偏好 |

32 

33當您想引導 Claude 的行為時,使用 CLAUDE.md 檔案。自動記憶讓 Claude 從您的更正中學習,無需手動操作。

34 

35Subagents 也可以維護自己的自動記憶。有關詳細資訊,請參閱 [subagent 配置](/zh-TW/sub-agents#enable-persistent-memory)。

36 

37## CLAUDE.md 檔案

38 

39CLAUDE.md 檔案是 markdown 檔案,為專案、您的個人工作流程或整個組織為 Claude 提供持久指令。您以純文字編寫這些檔案;Claude 在每個工作階段開始時讀取它們。

40 

41### 何時新增到 CLAUDE.md

42 

43將 CLAUDE.md 視為您寫下您本來會重新解釋的內容的地方。在以下情況下新增到它:

44 

45* Claude 第二次犯同樣的錯誤

46* 程式碼審查發現 Claude 應該知道的關於此程式碼庫的內容

47* 您在聊天中輸入的相同更正或澄清是您上個工作階段輸入的

48* 新的團隊成員需要相同的上下文才能提高生產力

49 

50將其保持為 Claude 應該在每個工作階段中保留的事實:建置命令、慣例、專案佈局、「始終執行 X」規則。如果一個條目是多步驟程序或僅對程式碼庫的一部分重要,請將其移到 [skill](/zh-TW/skills) 或 [路徑範圍規則](#organize-rules-with-claude/rules/) 代替。[擴展概述](/zh-TW/features-overview#build-your-setup-over-time)涵蓋何時使用每個機制。

51 

52### 選擇 CLAUDE.md 檔案的位置

53 

54CLAUDE.md 檔案可以位於多個位置,每個位置都有不同的範圍。更具體的位置優先於更廣泛的位置。

55 

56| 範圍 | 位置 | 目的 | 使用案例示例 | 共享對象 |

57| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------- | ---------------- | ------------ |

58| **受管理的原則** | • macOS:`/Library/Application Support/ClaudeCode/CLAUDE.md`<br />• Linux 和 WSL:`/etc/claude-code/CLAUDE.md`<br />• Windows:`C:\Program Files\ClaudeCode\CLAUDE.md` | 由 IT/DevOps 管理的組織範圍指令 | 公司編碼標準、安全原則、合規要求 | 組織中的所有使用者 |

59| **專案指令** | `./CLAUDE.md` 或 `./.claude/CLAUDE.md` | 專案的團隊共享指令 | 專案架構、編碼標準、常見工作流程 | 透過原始碼控制的團隊成員 |

60| **使用者指令** | `~/.claude/CLAUDE.md` | 所有專案的個人偏好 | 程式碼樣式偏好、個人工具快捷方式 | 僅您(所有專案) |

61| **本地指令** | `./CLAUDE.local.md` | 個人專案特定偏好;新增到 `.gitignore` | 您的沙箱 URL、偏好的測試資料 | 僅您(目前專案) |

62 

63工作目錄上方目錄層級中的 CLAUDE.md 和 CLAUDE.local.md 檔案在啟動時完整載入。子目錄中的檔案在 Claude 讀取這些目錄中的檔案時按需載入。有關完整的解析順序,請參閱 [CLAUDE.md 檔案如何載入](#how-claude-md-files-load)。

64 

65對於大型專案,您可以使用 [專案規則](#organize-rules-with-claude/rules/) 將指令分解為主題特定的檔案。規則讓您將指令範圍限定於特定檔案類型或子目錄。

66 

67### 設定專案 CLAUDE.md

68 

69專案 CLAUDE.md 可以儲存在 `./CLAUDE.md` 或 `./.claude/CLAUDE.md` 中。建立此檔案並新增適用於在專案上工作的任何人的指令:建置和測試命令、編碼標準、架構決策、命名慣例和常見工作流程。這些指令透過版本控制與您的團隊共享,因此請專注於專案級別的標準,而不是個人偏好。

70 

71<Tip>

72 執行 `/init` 以自動產生起始 CLAUDE.md。Claude 分析您的程式碼庫並建立一個檔案,其中包含它發現的建置命令、測試指令和專案慣例。如果 CLAUDE.md 已存在,`/init` 會建議改進,而不是覆蓋它。從那裡進行細化,新增 Claude 不會自己發現的指令。

73 

74 設定 `CLAUDE_CODE_NEW_INIT=1` 以啟用互動式多階段流程。`/init` 詢問要設定哪些成品:CLAUDE.md 檔案、skills 和 hooks。然後它使用 subagent 探索您的程式碼庫,透過後續問題填補空白,並在寫入任何檔案之前呈現可審查的提案。

75</Tip>

76 

77### 編寫有效的指令

78 

79CLAUDE.md 檔案在每個工作階段開始時載入到 context window 中,與您的對話一起消耗令牌。[context window 視覺化](/zh-TW/context-window)顯示 CLAUDE.md 相對於其餘啟動上下文的載入位置。因為它們是上下文而不是強制配置,您編寫指令的方式會影響 Claude 遵循它們的可靠性。具體、簡潔、結構良好的指令效果最好。

80 

81**大小**:目標是每個 CLAUDE.md 檔案少於 200 行。較長的檔案消耗更多上下文並降低遵守度。如果您的指令變得很大,請使用 [路徑範圍規則](#path-specific-rules) 以便指令只在 Claude 處理匹配檔案時載入。您也可以將內容分割成 [匯入](#import-additional-files) 以進行組織,儘管匯入的檔案仍然會載入並在啟動時進入 context window。

82 

83**結構**:使用 markdown 標題和項目符號來分組相關指令。Claude 掃描結構的方式與讀者相同:組織良好的部分比密集的段落更容易遵循。

84 

85**具體性**:編寫具體到足以驗證的指令。例如:

86 

87* 「使用 2 空格縮排」而不是「正確格式化程式碼」

88* 「在提交前執行 `npm test`」而不是「測試您的變更」

89* 「API 處理程式位於 `src/api/handlers/`」而不是「保持檔案組織」

90 

91**一致性**:如果兩個規則相互矛盾,Claude 可能會任意選擇一個。定期檢查您的 CLAUDE.md 檔案、子目錄中的巢狀 CLAUDE.md 檔案和 [`.claude/rules/`](#organize-rules-with-claude/rules/),以移除過時或衝突的指令。在 monorepos 中,使用 [`claudeMdExcludes`](#exclude-specific-claude-md-files) 跳過與您的工作無關的其他團隊的 CLAUDE.md 檔案。

92 

93### 匯入其他檔案

94 

95CLAUDE.md 檔案可以使用 `@path/to/import` 語法匯入其他檔案。匯入的檔案會展開並在啟動時與參考它們的 CLAUDE.md 一起載入到上下文中。

96 

97允許相對和絕對路徑。相對路徑相對於包含匯入的檔案解析,而不是工作目錄。匯入的檔案可以遞迴匯入其他檔案,最大深度為五跳。

98 

99要引入 README、package.json 和工作流程指南,請在 CLAUDE.md 中的任何位置使用 `@` 語法參考它們:

100 

101```text theme={null}

102有關專案概述,請參閱 @README,有關此專案的可用 npm 命令,請參閱 @package.json。

103 

104# 其他指令

105- git 工作流程 @docs/git-instructions.md

106```

107 

108對於您不想簽入版本控制的個人偏好,請在專案根目錄建立 `CLAUDE.local.md`。它與 `CLAUDE.md` 一起載入並以相同方式處理。將 `CLAUDE.local.md` 新增到您的 `.gitignore`,以便不提交它;執行 `/init` 並選擇個人選項會為您執行此操作。

109 

110如果您在同一儲存庫的多個 git worktrees 中工作,gitignored 的 `CLAUDE.local.md` 只存在於您建立它的 worktree 中。要在 worktrees 之間共享個人指令,請改為從您的主目錄匯入檔案:

111 

112```text theme={null}

113# 個人偏好

114- @~/.claude/my-project-instructions.md

115```

116 

117<Warning>

118 Claude Code 第一次在專案中遇到外部匯入時,它會顯示一個核准對話,列出檔案。如果您拒絕,匯入將保持禁用狀態,對話不會再次出現。

119</Warning>

120 

121有關組織指令的更結構化方法,請參閱 [`.claude/rules/`](#organize-rules-with-claude/rules/)。

122 

123### AGENTS.md

124 

125Claude Code 讀取 `CLAUDE.md`,而不是 `AGENTS.md`。如果您的儲存庫已經為其他編碼代理使用 `AGENTS.md`,請建立一個 `CLAUDE.md` 來匯入它,以便兩個工具讀取相同的指令而不重複。您也可以在匯入下方新增 Claude 特定的指令。Claude 在工作階段開始時載入匯入的檔案,然後附加其餘部分:

126 

127```markdown CLAUDE.md theme={null}

128@AGENTS.md

129 

130## Claude Code

131 

132對 `src/billing/` 下的變更使用 plan mode。

133```

134 

135### CLAUDE.md 檔案如何載入

136 

137Claude Code 透過從您目前的工作目錄向上走目錄樹來讀取 CLAUDE.md 檔案,檢查沿途的每個目錄中是否有 `CLAUDE.md` 和 `CLAUDE.local.md` 檔案。這意味著如果您在 `foo/bar/` 中執行 Claude Code,它會從 `foo/bar/CLAUDE.md`、`foo/CLAUDE.md` 和沿途的任何 `CLAUDE.local.md` 檔案載入指令。

138 

139所有發現的檔案都被連接到上下文中,而不是相互覆蓋。在目錄樹中,內容按照從檔案系統根目錄到您的工作目錄的順序排列。對於 `foo/bar/` 示例,`foo/CLAUDE.md` 在上下文中出現在 `foo/bar/CLAUDE.md` 之前,因此更接近您啟動 Claude 的位置的指令最後被讀取。在每個目錄中,`CLAUDE.local.md` 附加在 `CLAUDE.md` 之後,因此您的個人筆記是 Claude 在該級別讀取的最後一件事。

140 

141Claude 也會在您目前工作目錄下的子目錄中發現 `CLAUDE.md` 和 `CLAUDE.local.md` 檔案。它們不是在啟動時載入,而是在 Claude 讀取這些子目錄中的檔案時包含。

142 

143如果您在大型 monorepo 中工作,其中其他團隊的 CLAUDE.md 檔案被拾取,請使用 [`claudeMdExcludes`](#exclude-specific-claude-md-files) 跳過它們。

144 

145CLAUDE.md 檔案中的區塊級 HTML 註解(`<!-- maintainer notes -->`)在內容被注入到 Claude 的上下文之前會被移除。使用它們為人類維護者留下筆記,而不會在令牌上花費上下文。程式碼區塊內的註解會被保留。當您直接使用 Read 工具開啟 CLAUDE.md 檔案時,註解保持可見。

146 

147#### 從其他目錄載入

148 

149`--add-dir` 旗標讓 Claude 可以存取主工作目錄外的其他目錄。預設情況下,不會載入這些目錄中的 CLAUDE.md 檔案。

150 

151要也從其他目錄載入記憶檔案,請設定 `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` 環境變數:

152 

153```bash theme={null}

154CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 claude --add-dir ../shared-config

155```

156 

157這會從其他目錄載入 `CLAUDE.md`、`.claude/CLAUDE.md`、`.claude/rules/*.md` 和 `CLAUDE.local.md`。如果您從 [`--setting-sources`](/zh-TW/cli-reference) 排除 `local`,則會跳過 `CLAUDE.local.md`。

158 

159### 使用 `.claude/rules/` 組織規則

160 

161對於較大的專案,您可以使用 `.claude/rules/` 目錄將指令組織成多個檔案。這使指令保持模組化,更容易讓團隊維護。規則也可以 [範圍限定於特定檔案路徑](#path-specific-rules),因此它們只在 Claude 處理匹配檔案時載入到上下文中,減少雜訊並節省上下文空間。

162 

163<Note>

164 規則在每個工作階段或開啟匹配檔案時載入到上下文中。對於不需要始終在上下文中的任務特定指令,請改用 [skills](/zh-TW/skills),它們只在您呼叫它們或 Claude 確定它們與您的提示相關時載入。

165</Note>

166 

167#### 設定規則

168 

169在您的專案的 `.claude/rules/` 目錄中放置 markdown 檔案。每個檔案應涵蓋一個主題,具有描述性檔案名稱,如 `testing.md` 或 `api-design.md`。所有 `.md` 檔案都被遞迴發現,因此您可以將規則組織到子目錄中,如 `frontend/` 或 `backend/`:

170 

171```text theme={null}

172your-project/

173├── .claude/

174│ ├── CLAUDE.md # 主要專案指令

175│ └── rules/

176│ ├── code-style.md # 程式碼樣式指南

177│ ├── testing.md # 測試慣例

178│ └── security.md # 安全要求

179```

180 

181沒有 [`paths` frontmatter](#path-specific-rules) 的規則在啟動時載入,優先級與 `.claude/CLAUDE.md` 相同。

182 

183#### 路徑特定規則

184 

185規則可以使用帶有 `paths` 欄位的 YAML frontmatter 範圍限定於特定檔案。這些條件規則僅在 Claude 處理與指定模式匹配的檔案時適用。

186 

187```markdown theme={null}

188---

189paths:

190 - "src/api/**/*.ts"

191---

192 

193# API 開發規則

194 

195- 所有 API 端點必須包括輸入驗證

196- 使用標準錯誤回應格式

197- 包括 OpenAPI 文件註解

198```

199 

200沒有 `paths` 欄位的規則無條件載入並適用於所有檔案。路徑範圍規則在 Claude 讀取與模式匹配的檔案時觸發,而不是在每次工具使用時觸發。

201 

202在 `paths` 欄位中使用 glob 模式,按副檔名、目錄或任何組合匹配檔案:

203 

204| 模式 | 匹配 |

205| ---------------------- | ---------------------- |

206| `**/*.ts` | 任何目錄中的所有 TypeScript 檔案 |

207| `src/**/*` | `src/` 目錄下的所有檔案 |

208| `*.md` | 專案根目錄中的 Markdown 檔案 |

209| `src/components/*.tsx` | 特定目錄中的 React 元件 |

210 

211您可以指定多個模式並使用大括號展開在一個模式中匹配多個副檔名:

212 

213```markdown theme={null}

214---

215paths:

216 - "src/**/*.{ts,tsx}"

217 - "lib/**/*.ts"

218 - "tests/**/*.test.ts"

219---

220```

221 

222#### 使用符號連結跨專案共享規則

223 

224`.claude/rules/` 目錄支援符號連結,因此您可以維護一組共享規則並將它們連結到多個專案中。符號連結被解析並正常載入,並且循環符號連結被檢測並妥善處理。

225 

226此示例連結共享目錄和單個檔案:

227 

228```bash theme={null}

229ln -s ~/shared-claude-rules .claude/rules/shared

230ln -s ~/company-standards/security.md .claude/rules/security.md

231```

232 

233#### 使用者級別規則

234 

235`~/.claude/rules/` 中的個人規則適用於您機器上的每個專案。使用它們來處理不是專案特定的偏好:

236 

237```text theme={null}

238~/.claude/rules/

239├── preferences.md # 您的個人編碼偏好

240└── workflows.md # 您偏好的工作流程

241```

242 

243使用者級別規則在專案規則之前載入,給予專案規則更高的優先級。

244 

245### 為大型團隊管理 CLAUDE.md

246 

247對於在團隊中部署 Claude Code 的組織,您可以集中指令並控制載入哪些 CLAUDE.md 檔案。

248 

249#### 部署組織範圍的 CLAUDE.md

250 

251組織可以部署一個集中管理的 CLAUDE.md,適用於機器上的所有使用者。此檔案無法被個人設定排除。

252 

253<Steps>

254 <Step title="在受管理的原則位置建立檔案">

255 * macOS:`/Library/Application Support/ClaudeCode/CLAUDE.md`

256 * Linux 和 WSL:`/etc/claude-code/CLAUDE.md`

257 * Windows:`C:\Program Files\ClaudeCode\CLAUDE.md`

258 </Step>

259 

260 <Step title="使用您的配置管理系統進行部署">

261 使用 MDM、群組原則、Ansible 或類似工具在開發人員機器上分發檔案。有關其他組織範圍配置選項,請參閱 [受管理的設定](/zh-TW/permissions#managed-settings)。

262 </Step>

263</Steps>

264 

265受管理的 CLAUDE.md 和 [受管理的設定](/zh-TW/settings#settings-files) 有不同的用途。使用設定進行技術強制執行,使用 CLAUDE.md 進行行為指導:

266 

267| 關注 | 配置在 |

268| :-------------- | :-------------------------------------------- |

269| 阻止特定工具、命令或檔案路徑 | 受管理的設定:`permissions.deny` |

270| 強制執行沙箱隔離 | 受管理的設定:`sandbox.enabled` |

271| 環境變數和 API 提供者路由 | 受管理的設定:`env` |

272| 驗證方法和組織鎖定 | 受管理的設定:`forceLoginMethod`、`forceLoginOrgUUID` |

273| 程式碼樣式和品質指南 | 受管理的 CLAUDE.md |

274| 資料處理和合規提醒 | 受管理的 CLAUDE.md |

275| Claude 的行為指令 | 受管理的 CLAUDE.md |

276 

277設定規則由用戶端強制執行,無論 Claude 決定做什麼。CLAUDE.md 指令塑造 Claude 的行為,但不是硬強制執行層。

278 

279#### 排除特定的 CLAUDE.md 檔案

280 

281在大型 monorepos 中,祖先 CLAUDE.md 檔案可能包含與您的工作無關的指令。`claudeMdExcludes` 設定讓您按路徑或 glob 模式跳過特定檔案。

282 

283此示例排除頂級 CLAUDE.md 和父資料夾中的規則目錄。將其新增到 `.claude/settings.local.json`,以便排除保留在您的機器本地:

284 

285```json theme={null}

286{

287 "claudeMdExcludes": [

288 "**/monorepo/CLAUDE.md",

289 "/home/user/monorepo/other-team/.claude/rules/**"

290 ]

291}

292```

293 

294模式使用 glob 語法與絕對檔案路徑匹配。您可以在任何 [設定層](/zh-TW/settings#settings-files):使用者、專案、本地或受管理的原則配置 `claudeMdExcludes`。陣列跨層合併。

295 

296受管理的原則 CLAUDE.md 檔案無法被排除。這確保組織範圍的指令始終適用,無論個人設定如何。

297 

298## 自動記憶

299 

300自動記憶讓 Claude 在您不編寫任何內容的情況下跨工作階段累積知識。Claude 在工作時為自己保存筆記:建置命令、除錯見解、架構筆記、程式碼樣式偏好和工作流程習慣。Claude 不會每個工作階段都保存內容。它根據資訊在未來對話中是否有用來決定值得記住的內容。

301 

302<Note>

303 自動記憶需要 Claude Code v2.1.59 或更高版本。使用 `claude --version` 檢查您的版本。

304</Note>

305 

306### 啟用或停用自動記憶

307 

308自動記憶預設為開啟。要切換它,請在工作階段中開啟 `/memory` 並使用自動記憶切換,或在您的專案設定中設定 `autoMemoryEnabled`:

309 

310```json theme={null}

311{

312 "autoMemoryEnabled": false

313}

314```

315 

316要透過環境變數停用自動記憶,請設定 `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1`。

317 

318### 儲存位置

319 

320每個專案在 `~/.claude/projects/<project>/memory/` 獲得自己的記憶目錄。`<project>` 路徑源自 git 儲存庫,因此同一儲存庫內的所有 worktrees 和子目錄共享一個自動記憶目錄。在 git 儲存庫外,改用專案根目錄。

321 

322要將自動記憶儲存在不同位置,請在您的使用者設定中設定 `autoMemoryDirectory`,位置在 `~/.claude/settings.json`:

323 

324```json theme={null}

325{

326 "autoMemoryDirectory": "~/my-custom-memory-dir"

327}

328```

329 

330此值必須是絕對路徑或以 `~/` 開頭。此設定從原則和使用者設定接受,以及從 `--settings` 旗標接受。它不從專案或本地設定接受,因為兩個檔案都位於專案目錄內,複製的儲存庫可能提供任一個以將自動記憶寫入重定向到敏感位置。

331 

332目錄包含 `MEMORY.md` 進入點和可選的主題檔案:

333 

334```text theme={null}

335~/.claude/projects/<project>/memory/

336├── MEMORY.md # 簡潔索引,載入到每個工作階段

337├── debugging.md # 除錯模式的詳細筆記

338├── api-conventions.md # API 設計決策

339└── ... # Claude 建立的任何其他主題檔案

340```

341 

342`MEMORY.md` 充當記憶目錄的索引。Claude 在您的工作階段中讀取和寫入此目錄中的檔案,使用 `MEMORY.md` 追蹤儲存的內容。

343 

344自動記憶是機器本地的。同一 git 儲存庫內的所有 worktrees 和子目錄共享一個自動記憶目錄。檔案不在機器或雲端環境之間共享。

345 

346### 它如何運作

347 

348`MEMORY.md` 的前 200 行或前 25KB(以先到者為準)在每次對話開始時載入。超過該閾值的內容在工作階段開始時不載入。Claude 透過將詳細筆記移到單獨的主題檔案中來保持 `MEMORY.md` 簡潔。

349 

350此限制僅適用於 `MEMORY.md`。CLAUDE.md 檔案無論長度如何都完整載入,儘管較短的檔案會產生更好的遵守度。

351 

352主題檔案如 `debugging.md` 或 `patterns.md` 在啟動時不載入。Claude 在需要資訊時使用其標準檔案工具按需讀取它們。

353 

354Claude 在您的工作階段中讀取和寫入記憶檔案。當您在 Claude Code 介面中看到「寫入記憶」或「回憶記憶」時,Claude 正在主動更新或讀取 `~/.claude/projects/<project>/memory/`。

355 

356### 審計和編輯您的記憶

357 

358自動記憶檔案是純 markdown,您可以隨時編輯或刪除。執行 [`/memory`](#view-and-edit-with-memory) 以從工作階段中瀏覽和開啟記憶檔案。

359 

360## 使用 `/memory` 檢視和編輯

361 

362`/memory` 命令列出在您目前工作階段中載入的所有 CLAUDE.md、CLAUDE.local.md 和規則檔案,讓您切換自動記憶開啟或關閉,並提供開啟自動記憶資料夾的連結。選擇任何檔案以在您的編輯器中開啟它。

363 

364當您要求 Claude 記住某些內容時,例如「始終使用 pnpm,而不是 npm」或「記住 API 測試需要本地 Redis 實例」,Claude 會將其保存到自動記憶。要改為將指令新增到 CLAUDE.md,請直接要求 Claude,例如「將此新增到 CLAUDE.md」,或透過 `/memory` 自己編輯檔案。

365 

366## 疑難排解記憶問題

367 

368這些是 CLAUDE.md 和自動記憶最常見的問題,以及除錯步驟。

369 

370### Claude 不遵循我的 CLAUDE.md

371 

372CLAUDE.md 內容作為系統提示後的使用者訊息傳遞,而不是系統提示本身的一部分。Claude 讀取它並嘗試遵循它,但沒有嚴格遵守的保證,特別是對於模糊或衝突的指令。

373 

374要除錯:

375 

376* 執行 `/memory` 以驗證您的 CLAUDE.md 和 CLAUDE.local.md 檔案是否被載入。如果檔案未列出,Claude 看不到它。

377* 檢查相關的 CLAUDE.md 是否位於為您的工作階段載入的位置(請參閱 [選擇 CLAUDE.md 檔案的位置](#choose-where-to-put-claude-md-files))。

378* 使指令更具體。「使用 2 空格縮排」比「正確格式化程式碼」效果更好。

379* 查找跨 CLAUDE.md 檔案的衝突指令。如果兩個檔案為相同行為提供不同的指導,Claude 可能會任意選擇一個。

380 

381對於您想要在系統提示級別的指令,請使用 [`--append-system-prompt`](/zh-TW/cli-reference#system-prompt-flags)。這必須在每次呼叫時傳遞,因此它更適合指令碼和自動化,而不是互動式使用。

382 

383<Tip>

384 使用 [`InstructionsLoaded` hook](/zh-TW/hooks#instructionsloaded) 記錄確切載入的指令檔案、何時載入以及為什麼。這對於除錯路徑特定規則或子目錄中的延遲載入檔案很有用。

385</Tip>

386 

387### 我不知道自動記憶保存了什麼

388 

389執行 `/memory` 並選擇自動記憶資料夾以瀏覽 Claude 保存的內容。一切都是純 markdown,您可以讀取、編輯或刪除。

390 

391### 我的 CLAUDE.md 太大了

392 

393超過 200 行的檔案消耗更多上下文,可能會降低遵守度。使用 [路徑範圍規則](#path-specific-rules) 僅在 Claude 處理符合的檔案時載入指令,或修剪不是每個工作階段都需要的內容。分割成 [`@path` 匯入](#import-additional-files) 有助於組織,但不會減少上下文,因為匯入的檔案在啟動時載入。

394 

395### 指令在 `/compact` 後似乎丟失了

396 

397專案根目錄 CLAUDE.md 在壓縮中倖存:在 `/compact` 之後,Claude 從磁碟重新讀取它並將其重新注入到工作階段中。子目錄中的巢狀 CLAUDE.md 檔案不會自動重新注入;它們在 Claude 下次讀取該子目錄中的檔案時重新載入。

398 

399如果指令在壓縮後消失,它要麼只在對話中給出,要麼位於尚未重新載入的巢狀 CLAUDE.md 中。將對話專用指令新增到 CLAUDE.md 以使其持久化。有關完整的細目,請參閱 [壓縮後倖存的內容](/zh-TW/context-window#what-survives-compaction)。

400 

401請參閱 [編寫有效的指令](#write-effective-instructions) 以取得有關大小、結構和具體性的指導。

402 

403## 相關資源

404 

405* [除錯您的配置](/zh-TW/debug-your-config):診斷為什麼 CLAUDE.md 或設定未生效

406* [Skills](/zh-TW/skills):封裝按需載入的可重複工作流程

407* [設定](/zh-TW/settings):使用設定檔案配置 Claude Code 行為

408* [Subagent 記憶](/zh-TW/sub-agents#enable-persistent-memory):讓 subagents 維護自己的自動記憶

microsoft-foundry.md +314 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Claude Code on Microsoft Foundry

6 

7> 了解如何透過 Microsoft Foundry 配置 Claude Code,包括設定、配置和故障排除。

8 

9export const ContactSalesCard = ({surface}) => {

10 const utm = content => `utm_source=claude_code&utm_medium=docs&utm_content=${surface}_${content}`;

11 const iconArrowRight = (size = 13) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

12 <line x1="5" y1="12" x2="19" y2="12" />

13 <polyline points="12 5 19 12 12 19" />

14 </svg>;

15 const STYLES = `

16.cc-cs {

17 --cs-slate: #141413;

18 --cs-clay: #d97757;

19 --cs-clay-deep: #c6613f;

20 --cs-gray-000: #ffffff;

21 --cs-gray-700: #3d3d3a;

22 --cs-border-default: rgba(31, 30, 29, 0.15);

23 font-family: inherit;

24}

25.dark .cc-cs {

26 --cs-slate: #f0eee6;

27 --cs-gray-000: #262624;

28 --cs-gray-700: #bfbdb4;

29 --cs-border-default: rgba(240, 238, 230, 0.14);

30}

31.cc-cs-card {

32 display: flex; align-items: center; justify-content: space-between;

33 gap: 16px; padding: 14px 16px; margin: 0;

34 background: var(--cs-gray-000); border: 0.5px solid var(--cs-border-default);

35 border-radius: 8px; flex-wrap: wrap;

36}

37.cc-cs-text { font-size: 13px; color: var(--cs-gray-700); line-height: 1.5; flex: 1; min-width: 240px; }

38.cc-cs-text strong { font-weight: 550; color: var(--cs-slate); }

39.cc-cs-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }

40.cc-cs-btn-clay {

41 display: inline-flex; align-items: center; gap: 8px;

42 background: var(--cs-clay-deep); color: #fff; border: none;

43 border-radius: 8px; padding: 8px 14px;

44 font-size: 13px; font-weight: 500;

45 transition: background-color 0.15s; white-space: nowrap;

46}

47.cc-cs-btn-clay:hover { background: var(--cs-clay); }

48.cc-cs-btn-ghost {

49 display: inline-flex; align-items: center; gap: 8px;

50 background: transparent; color: var(--cs-gray-700);

51 border: 0.5px solid var(--cs-border-default);

52 border-radius: 8px; padding: 8px 14px;

53 font-size: 13px; font-weight: 500;

54}

55.cc-cs-btn-ghost:hover { background: rgba(0, 0, 0, 0.04); }

56.dark .cc-cs-btn-ghost:hover { background: rgba(255, 255, 255, 0.04); }

57@media (max-width: 720px) {

58 .cc-cs-actions { width: 100%; }

59}

60`;

61 return <div className="cc-cs not-prose">

62 <style>{STYLES}</style>

63 <div className="cc-cs-card">

64 <div className="cc-cs-text">

65 <strong>Deploying Claude Code across your organization?</strong> Talk to sales about enterprise plans, SSO, and centralized billing.

66 </div>

67 <div className="cc-cs-actions">

68 <a href={`https://claude.com/pricing?${utm('view_plans')}#plans-business`} className="cc-cs-btn-ghost">

69 View plans

70 </a>

71 <a href={`https://claude.com/contact-sales?${utm('contact_sales')}`} className="cc-cs-btn-clay">

72 Contact sales {iconArrowRight()}

73 </a>

74 </div>

75 </div>

76 </div>;

77};

78 

79export const Experiment = ({flag, treatment, children}) => {

80 const VID_KEY = 'exp_vid';

81 const CONSENT_COUNTRIES = new Set(['AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'RE', 'GP', 'MQ', 'GF', 'YT', 'BL', 'MF', 'PM', 'WF', 'PF', 'NC', 'AW', 'CW', 'SX', 'FO', 'GL', 'AX', 'GB', 'UK', 'AI', 'BM', 'IO', 'VG', 'KY', 'FK', 'GI', 'MS', 'PN', 'SH', 'TC', 'GG', 'JE', 'IM', 'CA', 'BR', 'IN']);

82 const fnv1a = s => {

83 let h = 0x811c9dc5;

84 for (let i = 0; i < s.length; i++) {

85 h ^= s.charCodeAt(i);

86 h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);

87 }

88 return h >>> 0;

89 };

90 const bucket = (seed, vid) => fnv1a(fnv1a(seed + vid) + '') % 10000 < 5000 ? 'control' : 'treatment';

91 const [decision] = useState(() => {

92 const params = new URLSearchParams(location.search);

93 const preBucketed = document.documentElement.dataset['gb_' + flag.replace(/-/g, '_')];

94 const force = params.get('gb-force');

95 if (force) {

96 for (const p of force.split(',')) {

97 const [k, v] = p.split(':');

98 if (k === flag) return {

99 variant: v || 'treatment',

100 track: false

101 };

102 }

103 }

104 if (navigator.globalPrivacyControl) {

105 return {

106 variant: 'control',

107 track: false

108 };

109 }

110 const prefsMatch = document.cookie.match(/(?:^|; )anthropic-consent-preferences=([^;]+)/);

111 if (prefsMatch) {

112 try {

113 if (JSON.parse(decodeURIComponent(prefsMatch[1])).analytics !== true) {

114 return {

115 variant: 'control',

116 track: false

117 };

118 }

119 } catch {

120 return {

121 variant: 'control',

122 track: false

123 };

124 }

125 } else {

126 const country = params.get('country')?.toUpperCase() || (document.cookie.match(/(?:^|; )cf_geo=([A-Z]{2})/) || [])[1];

127 if (!country || CONSENT_COUNTRIES.has(country)) {

128 return {

129 variant: 'control',

130 track: false

131 };

132 }

133 }

134 let vid;

135 try {

136 const ajsMatch = document.cookie.match(/(?:^|; )ajs_anonymous_id=([^;]+)/);

137 if (ajsMatch) {

138 vid = decodeURIComponent(ajsMatch[1]).replace(/^"|"$/g, '');

139 } else {

140 vid = localStorage.getItem(VID_KEY);

141 if (!vid) {

142 vid = crypto.randomUUID();

143 }

144 document.cookie = `ajs_anonymous_id=${vid}; domain=.claude.com; path=/; Secure; SameSite=Lax; max-age=31536000`;

145 }

146 try {

147 localStorage.setItem(VID_KEY, vid);

148 } catch {}

149 } catch {

150 return {

151 variant: 'control',

152 track: false

153 };

154 }

155 const variant = preBucketed === '1' ? 'treatment' : preBucketed === '0' ? 'control' : bucket(flag, vid);

156 return {

157 variant,

158 track: true,

159 vid

160 };

161 });

162 useEffect(() => {

163 if (!decision.track) return;

164 fetch('https://api.anthropic.com/api/event_logging/v2/batch', {

165 method: 'POST',

166 headers: {

167 'Content-Type': 'application/json',

168 'x-service-name': 'claude_code_docs'

169 },

170 body: JSON.stringify({

171 events: [{

172 event_type: 'GrowthbookExperimentEvent',

173 event_data: {

174 device_id: decision.vid,

175 anonymous_id: decision.vid,

176 timestamp: new Date().toISOString(),

177 experiment_id: flag,

178 variation_id: decision.variant === 'treatment' ? 1 : 0,

179 environment: 'production'

180 }

181 }]

182 }),

183 keepalive: true

184 }).catch(() => {});

185 }, []);

186 return decision.variant === 'treatment' ? treatment : children;

187};

188 

189<Experiment flag="docs-contact-sales-cta" treatment={<ContactSalesCard surface="foundry" />} />

190 

191## 先決條件

192 

193在使用 Microsoft Foundry 配置 Claude Code 之前,請確保您具有:

194 

195* 具有 Microsoft Foundry 存取權限的 Azure 訂閱

196* 建立 Microsoft Foundry 資源和部署的 RBAC 權限

197* 已安裝並配置 Azure CLI(選用 - 僅在您沒有其他取得認證機制時才需要)

198 

199<Note>

200 如果您要將 Claude Code 部署給多個使用者,請[固定您的模型版本](#4-pin-model-versions)以防止在 Anthropic 發佈新模型時發生中斷。

201</Note>

202 

203## 設定

204 

205### 1. 佈建 Microsoft Foundry 資源

206 

207首先,在 Azure 中建立 Claude 資源:

208 

2091. 瀏覽至 [Microsoft Foundry 入口網站](https://ai.azure.com/)

2102. 建立新資源,並記下您的資源名稱

2113. 為 Claude 模型建立部署:

212 * Claude Opus

213 * Claude Sonnet

214 * Claude Haiku

215 

216### 2. 配置 Azure 認證

217 

218Claude Code 支援 Microsoft Foundry 的兩種驗證方法。選擇最適合您安全性要求的方法。

219 

220**選項 A:API 金鑰驗證**

221 

2221. 在 Microsoft Foundry 入口網站中瀏覽至您的資源

2232. 前往 **端點和金鑰** 部分

2243. 複製 **API 金鑰**

2254. 設定環境變數:

226 

227```bash theme={null}

228export ANTHROPIC_FOUNDRY_API_KEY=your-azure-api-key

229```

230 

231**選項 B:Microsoft Entra ID 驗證**

232 

233當未設定 `ANTHROPIC_FOUNDRY_API_KEY` 時,Claude Code 會自動使用 Azure SDK [預設認證鏈](https://learn.microsoft.com/en-us/azure/developer/javascript/sdk/authentication/credential-chains#defaultazurecredential-overview)。

234這支援多種方法來驗證本機和遠端工作負載。

235 

236在本機環境中,您通常可以使用 Azure CLI:

237 

238```bash theme={null}

239az login

240```

241 

242<Note>

243 使用 Microsoft Foundry 時,`/login` 和 `/logout` 命令已停用,因為驗證是透過 Azure 認證處理的。

244</Note>

245 

246### 3. 配置 Claude Code

247 

248設定下列環境變數以啟用 Microsoft Foundry:

249 

250```bash theme={null}

251# 啟用 Microsoft Foundry 整合

252export CLAUDE_CODE_USE_FOUNDRY=1

253 

254# Azure 資源名稱(將 {resource} 替換為您的資源名稱)

255export ANTHROPIC_FOUNDRY_RESOURCE={resource}

256# 或提供完整的基礎 URL:

257# export ANTHROPIC_FOUNDRY_BASE_URL=https://{resource}.services.ai.azure.com/anthropic

258```

259 

260### 4. 固定模型版本

261 

262<Warning>

263 為每個部署固定特定的模型版本。如果您使用模型別名(`sonnet`、`opus`、`haiku`)而不固定版本,Claude Code 可能會嘗試使用您的 Foundry 帳戶中不可用的較新模型版本,在 Anthropic 發佈更新時破壞現有使用者。建立 Azure 部署時,請選擇特定的模型版本,而不是「自動更新至最新版本」。

264</Warning>

265 

266設定模型變數以符合您在步驟 1 中建立的部署名稱。

267 

268如果沒有 `ANTHROPIC_DEFAULT_OPUS_MODEL`,Foundry 上的 `opus` 別名會解析為 Opus 4.6。將其設定為 Opus 4.7 ID 以使用最新模型:

269 

270```bash theme={null}

271export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-7'

272export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-6'

273export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5'

274```

275 

276如需目前和舊版模型 ID,請參閱[模型概覽](https://platform.claude.com/docs/en/about-claude/models/overview)。如需完整的環境變數清單,請參閱[模型配置](/zh-TW/model-config#pin-models-for-third-party-deployments)。

277 

278[Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) 會自動啟用。若要要求 1 小時的快取 TTL 而不是 5 分鐘的預設值,請設定下列變數;具有 1 小時 TTL 的快取寫入會以更高的費率計費:

279 

280```bash theme={null}

281export ENABLE_PROMPT_CACHING_1H=1

282```

283 

284## Azure RBAC 配置

285 

286`Azure AI User` 和 `Cognitive Services User` 預設角色包含叫用 Claude 模型所需的所有權限。

287 

288如需更嚴格的權限,請建立具有以下內容的自訂角色:

289 

290```json theme={null}

291{

292 "permissions": [

293 {

294 "dataActions": [

295 "Microsoft.CognitiveServices/accounts/providers/*"

296 ]

297 }

298 ]

299}

300```

301 

302如需詳細資訊,請參閱 [Microsoft Foundry RBAC 文件](https://learn.microsoft.com/en-us/azure/ai-foundry/concepts/rbac-azure-ai-foundry)。

303 

304## 故障排除

305 

306如果您收到錯誤「Failed to get token from azureADTokenProvider: ChainedTokenCredential authentication failed」:

307 

308* 在環境中配置 Entra ID,或設定 `ANTHROPIC_FOUNDRY_API_KEY`。

309 

310## 其他資源

311 

312* [Microsoft Foundry 文件](https://learn.microsoft.com/en-us/azure/ai-foundry/what-is-azure-ai-foundry)

313* [Microsoft Foundry 模型](https://ai.azure.com/explore/models)

314* [Microsoft Foundry 定價](https://azure.microsoft.com/en-us/pricing/details/ai-foundry/)

model-config.md +382 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 模型配置

6 

7> 了解 Claude Code 模型配置,包括模型別名如 `opusplan`

8 

9## 可用模型

10 

11對於 Claude Code 中的 `model` 設定,您可以配置以下任一項:

12 

13* 一個**模型別名**

14* 一個**模型名稱**

15 * Anthropic API:完整的\*\*[模型名稱](https://platform.claude.com/docs/zh-TW/about-claude/models/overview)\*\*

16 * Bedrock:推論設定檔 ARN

17 * Foundry:部署名稱

18 * Vertex:版本名稱

19 

20### 模型別名

21 

22模型別名提供了一種便捷的方式來選擇模型設定,無需記住確切的版本號:

23 

24| 模型別名 | 行為 |

25| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |

26| **`default`** | 特殊值,可清除任何模型覆蓋並還原為您帳戶類型的推薦模型。本身不是模型別名 |

27| **`best`** | 使用最強大的可用模型,目前相當於 `opus` |

28| **`sonnet`** | 使用最新的 Sonnet 模型進行日常編碼任務 |

29| **`opus`** | 使用最新的 Opus 模型進行複雜推理任務 |

30| **`haiku`** | 使用快速高效的 Haiku 模型進行簡單任務 |

31| **`sonnet[1m]`** | 使用 Sonnet 搭配[100 萬個 token 的 context window](https://platform.claude.com/docs/zh-TW/build-with-claude/context-windows#1m-token-context-window)進行長時間會話 |

32| **`opus[1m]`** | 使用 Opus 搭配[100 萬個 token 的 context window](https://platform.claude.com/docs/zh-TW/build-with-claude/context-windows#1m-token-context-window)進行長時間會話 |

33| **`opusplan`** | 特殊模式,在 Plan Mode 期間使用 `opus`,然後在執行時切換到 `sonnet` |

34 

35在 Anthropic API 上,`opus` 解析為 Opus 4.7,`sonnet` 解析為 Sonnet 4.6。在 Bedrock、Vertex 和 Foundry 上,`opus` 解析為 Opus 4.6,`sonnet` 解析為 Sonnet 4.5;透過明確選擇完整模型名稱或設定 `ANTHROPIC_DEFAULT_OPUS_MODEL` 或 `ANTHROPIC_DEFAULT_SONNET_MODEL`,這些提供者上可以使用更新的模型。

36 

37別名指向您提供者的推薦版本,並隨著時間推移而更新。若要固定到特定版本,請使用完整模型名稱(例如 `claude-opus-4-7`)或設定相應的環境變數,如 `ANTHROPIC_DEFAULT_OPUS_MODEL`。

38 

39<Note>

40 Opus 4.7 需要 Claude Code v2.1.111 或更新版本。執行 `claude update` 以升級。

41</Note>

42 

43### 設定您的模型

44 

45您可以透過多種方式配置模型,按優先順序列出:

46 

471. **在會話期間** - 使用 `/model <alias|name>` 立即切換,或執行 `/model` 不帶任何引數以開啟選擇器。當會話有先前的輸出時,選擇器會要求確認,因為下一個回應會重新讀取完整歷史記錄而不使用快取的 context

482. **在啟動時** - 使用 `claude --model <alias|name>` 啟動

493. **環境變數** - 設定 `ANTHROPIC_MODEL=<alias|name>`

504. **設定** - 在設定檔中使用 `model` 欄位永久配置。

51 

52您的 `/model` 選擇會儲存到使用者設定並在重新啟動後保持。自 v2.1.117 起,如果專案的 `.claude/settings.json` 固定了不同的模型,Claude Code 也會將您的選擇寫入 `.claude/settings.local.json`,以便在重新啟動後在該專案中繼續應用。受管設定優先級最高,並在下次啟動時重新應用。

53 

54當啟動時的活動模型來自專案或受管設定而非您自己的選擇時,啟動標題會顯示哪個設定檔設定了它。執行 `/model` 以覆蓋目前會話。

55 

56使用範例:

57 

58```bash theme={null}

59# 使用 Opus 啟動

60claude --model opus

61 

62# 在會話期間切換到 Sonnet

63/model sonnet

64```

65 

66設定檔範例:

67 

68```json theme={null}

69{

70 "permissions": {

71 ...

72 },

73 "model": "opus"

74}

75```

76 

77## 限制模型選擇

78 

79企業管理員可以在[受管理或政策設定](/zh-TW/settings#settings-files)中使用 `availableModels` 來限制使用者可以選擇的模型。

80 

81設定 `availableModels` 後,使用者無法透過 `/model`、`--model` 旗標或 `ANTHROPIC_MODEL` 環境變數切換到清單中沒有的模型。

82 

83```json theme={null}

84{

85 "availableModels": ["sonnet", "haiku"]

86}

87```

88 

89### 預設模型行為

90 

91模型選擇器中的「預設」選項不受 `availableModels` 影響。它始終保持可用,並代表系統的執行時預設值[基於使用者的訂閱層級](#default-model-setting)。

92 

93即使使用 `availableModels: []`,使用者仍然可以使用其層級的預設模型來使用 Claude Code。

94 

95### 控制使用者執行的模型

96 

97`model` 設定是初始選擇,而非強制執行。它設定會話啟動時哪個模型處於活動狀態,但使用者仍然可以開啟 `/model` 並選擇「預設」,這會解析為其層級的系統預設值,無論 `model` 設定為何。

98 

99若要完全控制模型體驗,請結合三個設定:

100 

101* **`availableModels`**:限制使用者可以切換到的具名模型

102* **`model`**:設定會話啟動時的初始模型選擇

103* **`ANTHROPIC_DEFAULT_SONNET_MODEL`** / **`ANTHROPIC_DEFAULT_OPUS_MODEL`** / **`ANTHROPIC_DEFAULT_HAIKU_MODEL`**:控制「預設」選項以及 `sonnet`、`opus` 和 `haiku` 別名解析為什麼

104 

105此範例在 Sonnet 4.5 上啟動使用者,將選擇器限制為 Sonnet 和 Haiku,並將「預設」固定為解析為 Sonnet 4.5 而不是最新版本:

106 

107```json theme={null}

108{

109 "model": "claude-sonnet-4-5",

110 "availableModels": ["claude-sonnet-4-5", "haiku"],

111 "env": {

112 "ANTHROPIC_DEFAULT_SONNET_MODEL": "claude-sonnet-4-5"

113 }

114}

115```

116 

117沒有 `env` 區塊,在選擇器中選擇「預設」的使用者會獲得最新的 Sonnet 版本,繞過 `model` 和 `availableModels` 中的版本固定。

118 

119### 合併行為

120 

121當 `availableModels` 在多個層級設定時,例如使用者設定和專案設定,陣列會被合併並去重。若要強制執行嚴格的允許清單,請在受管理或政策設定中設定 `availableModels`,這具有最高優先順序。

122 

123### Mantle 模型 ID

124 

125當[Bedrock Mantle 端點](/zh-TW/amazon-bedrock#use-the-mantle-endpoint)啟用時,`availableModels` 中以 `anthropic.` 開頭的項目會作為自訂選項新增到 `/model` 選擇器,並路由到 Mantle 端點。這是對[為第三方部署固定模型](#pin-models-for-third-party-deployments)中描述的僅別名匹配的例外。該設定仍然將選擇器限制為列出的項目,因此請在任何 Mantle ID 旁邊包含標準別名。

126 

127## 特殊模型行為

128 

129### `default` 模型設定

130 

131`default` 的行為取決於您的帳戶類型:

132 

133* **Max 和 Team Premium**:預設為 Opus 4.7

134* **Pro、Team Standard、Enterprise 和 Anthropic API**:預設為 Sonnet 4.6

135* **Bedrock、Vertex 和 Foundry**:預設為 Sonnet 4.5

136 

137如果您達到 Opus 的使用閾值,Claude Code 可能會自動回退到 Sonnet。

138 

139<Note>

140 2026 年 4 月 23 日,Enterprise 隨用隨付和 Anthropic API 使用者的預設模型將變更為 Opus 4.7。若要保持不同的預設值,請設定 `ANTHROPIC_MODEL` 或[伺服器管理設定](/zh-TW/server-managed-settings)中的 `model` 欄位。

141</Note>

142 

143### `opusplan` 模型設定

144 

145`opusplan` 模型別名提供了一種自動化的混合方法:

146 

147* **在 Plan Mode 中** - 使用 `opus` 進行複雜推理和架構決策

148* **在執行模式中** - 自動切換到 `sonnet` 進行程式碼生成和實現

149 

150這為您提供了兩全其美的方案:Opus 優越的推理能力用於計畫,Sonnet 的效率用於執行。

151 

152Plan Mode Opus 階段使用標準 200K context window 執行。[擴展 context](#extended-context) 中描述的自動 1M 升級適用於 `opus` 模型設定,不適用於 `opusplan`。

153 

154### 調整努力等級

155 

156[努力等級](https://platform.claude.com/docs/en/build-with-claude/effort)控制自適應推理,讓模型根據任務複雜性決定是否以及在每一步上思考多少。較低的努力對於直接的任務更快且更便宜,而較高的努力為複雜問題提供更深入的推理。

157 

158努力在 Opus 4.7、Opus 4.6 和 Sonnet 4.6 上受支援。可用的等級取決於模型:

159 

160| 模型 | 等級 |

161| :-------------------- | :---------------------------------- |

162| Opus 4.7 | `low`、`medium`、`high`、`xhigh`、`max` |

163| Opus 4.6 和 Sonnet 4.6 | `low`、`medium`、`high`、`max` |

164 

165如果您設定活動模型不支援的等級,Claude Code 會回退到您設定的等級處或以下的最高支援等級。例如,`xhigh` 在 Opus 4.6 上執行為 `high`。

166 

167自 v2.1.117 起,Opus 4.7 上的預設努力為 `xhigh`,Opus 4.6 和 Sonnet 4.6 上的預設努力為 `high`。

168 

169當您首次執行 Opus 4.7 時,Claude Code 會應用 `xhigh`,即使您之前為 Opus 4.6 或 Sonnet 4.6 設定了不同的努力等級。執行 `/effort` 以在切換後選擇不同的等級。

170 

171`low`、`medium`、`high` 和 `xhigh` 在會話間持續存在。`max` 提供最深入的推理,對 token 支出沒有限制,並且僅適用於目前會話,除非透過 `CLAUDE_CODE_EFFORT_LEVEL` 環境變數設定。

172 

173#### 選擇努力等級

174 

175每個等級都在 token 支出和能力之間進行權衡。預設值適合大多數編碼任務;當您想要不同的平衡時進行調整。

176 

177| 等級 | 何時使用 |

178| :------- | :---------------------------------------------------- |

179| `low` | 保留用於短期、範圍有限、延遲敏感且不是智能敏感的任務 |

180| `medium` | 減少成本敏感工作的 token 使用,可以權衡一些智能 |

181| `high` | 平衡 token 使用和智能。用作智能敏感工作的最低要求,或相對於 `xhigh` 減少 token 支出 |

182| `xhigh` | 大多數編碼和代理任務的最佳結果。Opus 4.7 上的推薦預設值 |

183| `max` | 可以改善困難任務的效能,但可能顯示遞減回報,容易過度思考。在廣泛採用前進行測試 |

184 

185努力量表按模型進行校準,因此相同的等級名稱在模型之間不代表相同的基礎值。

186 

187對於一次性的深入推理而不改變您的會話設定,在您的提示中包含「ultrathink」。這會新增一個上下文指令,告訴模型在該輪上進行更多推理;它不會改變發送到 API 的努力等級。

188 

189#### 設定努力等級

190 

191您可以透過以下任何方式改變努力:

192 

193* **`/effort`**:執行 `/effort` 不帶引數以開啟互動式滑塊,執行 `/effort` 後跟等級名稱以直接設定,或執行 `/effort auto` 以重設為模型預設值

194* **在 `/model` 中**:選擇模型時使用左/右箭頭鍵調整努力滑塊

195* **`--effort` 旗標**:在啟動 Claude Code 時傳遞等級名稱以為單一會話設定

196* **環境變數**:設定 `CLAUDE_CODE_EFFORT_LEVEL` 為等級名稱或 `auto`

197* **設定**:在設定檔中設定 `effortLevel`

198* **Skill 和 subagent frontmatter**:在 [skill](/zh-TW/skills#frontmatter-reference) 或 [subagent](/zh-TW/sub-agents#supported-frontmatter-fields) markdown 檔案中設定 `effort` 以在該 skill 或 subagent 執行時覆蓋努力等級

199 

200環境變數優先於所有其他方法,然後是您配置的等級,然後是模型預設值。Frontmatter 努力在該 skill 或 subagent 活動時適用,覆蓋會話等級但不覆蓋環境變數。

201 

202當選擇支援的模型時,努力滑塊會出現在 `/model` 中。目前的努力等級也會顯示在標誌和微調器旁邊,例如「with low effort」,因此您可以確認哪個設定處於活動狀態,而無需開啟 `/model`。

203 

204#### 自適應推理和固定思考預算

205 

206自適應推理使思考在每一步上都是可選的,因此 Claude 可以更快地回應常規提示,並為受益於思考的步驟保留更深入的思考。如果您想要 Claude 比目前等級產生的更頻繁或更少地思考,您可以直接在您的提示或 `CLAUDE.md` 中說明;模型在其努力設定範圍內回應該指導。

207 

208Opus 4.7 始終使用自適應推理。固定思考預算模式和 `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` 不適用於它。

209 

210在 Opus 4.6 和 Sonnet 4.6 上,您可以設定 `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1` 以恢復到由 `MAX_THINKING_TOKENS` 控制的先前固定思考預算。請參閱[環境變數](/zh-TW/env-vars)。

211 

212### 擴展 context

213 

214Opus 4.7、Opus 4.6 和 Sonnet 4.6 支援[100 萬個 token 的 context window](https://platform.claude.com/docs/en/build-with-claude/context-windows#1m-token-context-window),用於具有大型程式碼庫的長時間會話。

215 

216可用性因模型和計畫而異。在 Max、Team 和 Enterprise 計畫上,Opus 會自動升級到 1M context,無需額外配置。這適用於 Team Standard 和 Team Premium 席位。

217 

218| 計畫 | Opus 搭配 1M context | Sonnet 搭配 1M context |

219| --------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |

220| Max、Team 和 Enterprise | 包含在訂閱中 | 需要[額外使用](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) |

221| Pro | 需要[額外使用](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) | 需要[額外使用](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) |

222| API 和隨用隨付 | 完全存取 | 完全存取 |

223 

224若要完全禁用 1M context,請設定 `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`。這會從模型選擇器中移除 1M 模型變體。請參閱[環境變數](/zh-TW/env-vars)。

225 

2261M context window 使用標準模型定價,超過 200K 的 token 無需額外費用。對於訂閱中包含擴展 context 的計畫,使用量仍由您的訂閱涵蓋。對於透過額外使用存取擴展 context 的計畫,token 會計入額外使用。

227 

228如果您的帳戶支援 1M context,該選項會出現在最新版本 Claude Code 的模型選擇器(`/model`)中。如果您看不到它,請嘗試重新啟動您的會話。

229 

230您也可以將 `[1m]` 後綴與模型別名或完整模型名稱一起使用:

231 

232```bash theme={null}

233# 使用 opus[1m] 或 sonnet[1m] 別名

234/model opus[1m]

235/model sonnet[1m]

236 

237# 或將 [1m] 附加到完整模型名稱

238/model claude-opus-4-7[1m]

239```

240 

241## 檢查您目前的模型

242 

243您可以透過多種方式查看您目前使用的模型:

244 

2451. 在[狀態行](/zh-TW/statusline)中(如果已配置)

2462. 在 `/status` 中,它也會顯示您的帳戶資訊。

247 

248## 新增自訂模型選項

249 

250使用 `ANTHROPIC_CUSTOM_MODEL_OPTION` 將單一自訂項目新增到 `/model` 選擇器,而無需取代內建別名。這對於測試 Claude Code 預設不列出的模型 ID 很有用。對於 LLM 閘道部署,Claude Code 會自動從閘道的 `/v1/models` 端點填入選擇器,因此只有在探索未傳回您想要的模型時,才需要此變數。請參閱 [LLM 閘道模型選擇](/zh-TW/llm-gateway#model-selection)。

251 

252此範例設定所有三個變數以使閘道路由的 Opus 部署可選擇:

253 

254```bash theme={null}

255export ANTHROPIC_CUSTOM_MODEL_OPTION="my-gateway/claude-opus-4-7"

256export ANTHROPIC_CUSTOM_MODEL_OPTION_NAME="Opus via Gateway"

257export ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION="Custom deployment routed through the internal LLM gateway"

258```

259 

260自訂項目出現在 `/model` 選擇器的底部。`ANTHROPIC_CUSTOM_MODEL_OPTION_NAME` 和 `ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION` 是可選的。如果省略,模型 ID 會用作名稱,描述預設為 `Custom model (<model-id>)`。

261 

262Claude Code 會跳過在 `ANTHROPIC_CUSTOM_MODEL_OPTION` 中設定的模型 ID 的驗證,因此您可以使用您的 API 端點接受的任何字串。

263 

264## 環境變數

265 

266您可以使用以下環境變數,這些變數必須是完整的**模型名稱**(或您的 API 提供者的等效項),以控制別名對應到的模型名稱。

267 

268| 環境變數 | 描述 |

269| -------------------------------- | ----------------------------------------------------------- |

270| `ANTHROPIC_DEFAULT_OPUS_MODEL` | 用於 `opus` 的模型,或在 Plan Mode 活動時用於 `opusplan` 的模型。 |

271| `ANTHROPIC_DEFAULT_SONNET_MODEL` | 用於 `sonnet` 的模型,或在 Plan Mode 未活動時用於 `opusplan` 的模型。 |

272| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | 用於 `haiku` 的模型,或[背景功能](/zh-TW/costs#background-token-usage) |

273| `CLAUDE_CODE_SUBAGENT_MODEL` | 用於 [subagents](/zh-TW/sub-agents) 的模型 |

274 

275注意:`ANTHROPIC_SMALL_FAST_MODEL` 已棄用,改用 `ANTHROPIC_DEFAULT_HAIKU_MODEL`。

276 

277### 為第三方部署固定模型

278 

279透過 [Bedrock](/zh-TW/amazon-bedrock)、[Vertex AI](/zh-TW/google-vertex-ai) 或 [Foundry](/zh-TW/microsoft-foundry) 部署 Claude Code 時,在向使用者推出前固定模型版本。

280 

281不固定模型時,Claude Code 使用模型別名(`sonnet`、`opus`、`haiku`),這些別名會解析為最新版本。當 Anthropic 發佈新模型時,帳戶未啟用新版本的使用者會看到通知並回退到該會話的先前版本,而 Foundry 使用者會看到錯誤,因為 Foundry 沒有等效的啟動檢查。

282 

283<Warning>

284 在初始設定中將所有三個模型環境變數設定為特定版本 ID。固定讓您控制使用者何時移動到新模型。

285</Warning>

286 

287使用以下環境變數搭配您提供者的版本特定模型 ID:

288 

289| 提供者 | 範例 |

290| :-------- | :------------------------------------------------------------------- |

291| Bedrock | `export ANTHROPIC_DEFAULT_OPUS_MODEL='us.anthropic.claude-opus-4-7'` |

292| Vertex AI | `export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-7'` |

293| Foundry | `export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-7'` |

294 

295對 `ANTHROPIC_DEFAULT_SONNET_MODEL` 和 `ANTHROPIC_DEFAULT_HAIKU_MODEL` 應用相同的模式。有關所有提供者的目前和舊版模型 ID,請參閱[模型概述](https://platform.claude.com/docs/en/about-claude/models/overview)。若要將使用者升級到新模型版本,請更新這些環境變數並重新部署。

296 

297若要為固定模型啟用[擴展 context](#extended-context),請將 `[1m]` 附加到 `ANTHROPIC_DEFAULT_OPUS_MODEL` 或 `ANTHROPIC_DEFAULT_SONNET_MODEL` 中的模型 ID:

298 

299```bash theme={null}

300export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-7[1m]'

301```

302 

303`[1m]` 後綴將 1M context window 應用於該別名的所有使用,包括 `opusplan`。Claude Code 在將模型 ID 發送到您的提供者之前會移除該後綴。只有當基礎模型支援 1M context(例如 Opus 4.7 或 Sonnet 4.6)時,才附加 `[1m]`。

304 

305<Note>

306 使用第三方提供者時,`settings.availableModels` 允許清單仍然適用。篩選會根據模型別名(`opus`、`sonnet`、`haiku`)進行匹配,而不是提供者特定的模型 ID。

307</Note>

308 

309### 為第三方部署自訂固定模型顯示和能力

310 

311當您在第三方提供者上固定模型時,提供者特定的 ID 會按原樣出現在 `/model` 選擇器中,Claude Code 可能無法識別模型支援的功能。您可以使用每個固定模型的伴隨環境變數覆蓋顯示名稱並宣告能力。

312 

313這些變數在 Bedrock、Vertex AI 和 Foundry 等第三方提供者上生效。`_NAME` 和 `_DESCRIPTION` 變數在 `ANTHROPIC_BASE_URL` 指向 [LLM gateway](/zh-TW/llm-gateway) 時也會生效。當直接連接到 `api.anthropic.com` 時無效。

314 

315| 環境變數 | 描述 |

316| ----------------------------------------------------- | -------------------------------------------------------- |

317| `ANTHROPIC_DEFAULT_OPUS_MODEL_NAME` | `/model` 選擇器中固定 Opus 模型的顯示名稱。未設定時預設為模型 ID |

318| `ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION` | `/model` 選擇器中固定 Opus 模型的顯示描述。未設定時預設為 `Custom Opus model` |

319| `ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES` | 固定 Opus 模型支援的能力的逗號分隔清單 |

320 

321相同的 `_NAME`、`_DESCRIPTION` 和 `_SUPPORTED_CAPABILITIES` 後綴可用於 `ANTHROPIC_DEFAULT_SONNET_MODEL`、`ANTHROPIC_DEFAULT_HAIKU_MODEL` 和 `ANTHROPIC_CUSTOM_MODEL_OPTION`。

322 

323Claude Code 透過將模型 ID 與已知模式進行匹配來啟用[努力等級](#adjust-effort-level)和[擴展思考](/zh-TW/common-workflows#use-extended-thinking-thinking-mode)等功能。提供者特定的 ID(例如 Bedrock ARN 或自訂部署名稱)通常不符合這些模式,導致支援的功能被禁用。設定 `_SUPPORTED_CAPABILITIES` 以告訴 Claude Code 模型實際支援的功能:

324 

325| 能力值 | 啟用 |

326| ---------------------- | ------------------------------------------------------------------- |

327| `effort` | [努力等級](#adjust-effort-level)和 `/effort` 命令 |

328| `xhigh_effort` | {/* min-version: 2.1.111 */}`xhigh` 努力等級 |

329| `max_effort` | `max` 努力等級 |

330| `thinking` | [擴展思考](/zh-TW/common-workflows#use-extended-thinking-thinking-mode) |

331| `adaptive_thinking` | 根據任務複雜性動態分配思考的自適應推理 |

332| `interleaved_thinking` | 工具呼叫之間的思考 |

333 

334當設定 `_SUPPORTED_CAPABILITIES` 時,列出的能力會為匹配的固定模型啟用,未列出的能力會被禁用。當變數未設定時,Claude Code 會回退到基於模型 ID 的內建檢測。

335 

336此範例將 Opus 固定到 Bedrock 自訂模型 ARN,設定友善名稱,並宣告其能力:

337 

338```bash theme={null}

339export ANTHROPIC_DEFAULT_OPUS_MODEL='arn:aws:bedrock:us-east-1:123456789012:custom-model/abc'

340export ANTHROPIC_DEFAULT_OPUS_MODEL_NAME='Opus via Bedrock'

341export ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION='Opus 4.7 routed through a Bedrock custom endpoint'

342export ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES='effort,xhigh_effort,max_effort,thinking,adaptive_thinking,interleaved_thinking'

343```

344 

345### 按版本覆蓋模型 ID

346 

347上述家族級環境變數為每個家族別名配置一個模型 ID。如果您需要將同一家族內的多個版本對應到不同的提供者 ID,請改用 `modelOverrides` 設定。

348 

349`modelOverrides` 將個別 Anthropic 模型 ID 對應到 Claude Code 發送到您提供者 API 的提供者特定字串。當使用者在 `/model` 選擇器中選擇對應的模型時,Claude Code 會使用您配置的值而不是內建預設值。

350 

351這讓企業管理員可以將每個模型版本路由到特定的 Bedrock 推論設定檔 ARN、Vertex AI 版本名稱或 Foundry 部署名稱,以進行治理、成本分配或區域路由。

352 

353在您的[設定檔](/zh-TW/settings#settings-files)中設定 `modelOverrides`:

354 

355```json theme={null}

356{

357 "modelOverrides": {

358 "claude-opus-4-7": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-prod",

359 "claude-opus-4-6": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-46-prod",

360 "claude-sonnet-4-6": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/sonnet-prod"

361 }

362}

363```

364 

365鍵必須是[模型概述](https://platform.claude.com/docs/en/about-claude/models/overview)中列出的 Anthropic 模型 ID。對於日期模型 ID,請包含日期後綴,完全如其所示。未知的鍵會被忽略。

366 

367覆蓋會取代支援 `/model` 選擇器中每個項目的內建模型 ID。在 Bedrock 上,覆蓋優先於 Claude Code 在啟動時自動發現的任何推論設定檔。您直接透過 `ANTHROPIC_MODEL`、`--model` 或 `ANTHROPIC_DEFAULT_*_MODEL` 環境變數提供的值會按原樣傳遞給提供者,不會由 `modelOverrides` 轉換。

368 

369`modelOverrides` 與 `availableModels` 一起運作。允許清單會根據 Anthropic 模型 ID 進行評估,而不是覆蓋值,因此 `availableModels` 中的項目(如 `"opus"`)即使 Opus 版本對應到 ARN 時仍會繼續匹配。

370 

371### Prompt caching 配置

372 

373Claude Code 自動使用 [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) 來優化效能並降低成本。您可以全域禁用 prompt caching 或針對特定模型層級禁用:

374 

375| 環境變數 | 描述 |

376| ------------------------------- | ------------------------------------------- |

377| `DISABLE_PROMPT_CACHING` | 設定為 `1` 以禁用所有模型的 prompt caching(優先於每個模型的設定) |

378| `DISABLE_PROMPT_CACHING_HAIKU` | 設定為 `1` 以僅禁用 Haiku 模型的 prompt caching |

379| `DISABLE_PROMPT_CACHING_SONNET` | 設定為 `1` 以僅禁用 Sonnet 模型的 prompt caching |

380| `DISABLE_PROMPT_CACHING_OPUS` | 設定為 `1` 以僅禁用 Opus 模型的 prompt caching |

381 

382這些環境變數為您提供對 prompt caching 行為的細粒度控制。全域 `DISABLE_PROMPT_CACHING` 設定優先於模型特定的設定,讓您可以在需要時快速禁用所有快取。每個模型的設定對於選擇性控制很有用,例如在偵錯特定模型或使用可能具有不同快取實現的雲端提供者時。

monitoring-usage.md +955 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 監控

6 

7> 了解如何為 Claude Code 啟用和配置 OpenTelemetry。

8 

9透過 OpenTelemetry (OTel) 匯出遙測資料,追蹤 Claude Code 在整個組織中的使用情況、成本和工具活動。Claude Code 透過標準指標協議匯出指標作為時間序列資料、透過日誌/事件協議匯出事件,以及可選地透過[追蹤協議](#traces-beta)匯出分散式追蹤。配置您的指標、日誌和追蹤後端以符合您的監控需求。

10 

11## 快速開始

12 

13使用環境變數配置 OpenTelemetry:

14 

15```bash theme={null}

16# 1. 啟用遙測

17export CLAUDE_CODE_ENABLE_TELEMETRY=1

18 

19# 2. 選擇匯出器(兩者都是可選的 - 僅配置您需要的)

20export OTEL_METRICS_EXPORTER=otlp # 選項:otlp、prometheus、console、none

21export OTEL_LOGS_EXPORTER=otlp # 選項:otlp、console、none

22 

23# 3. 配置 OTLP 端點(用於 OTLP 匯出器)

24export OTEL_EXPORTER_OTLP_PROTOCOL=grpc

25export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317

26 

27# 4. 設定身份驗證(如果需要)

28export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-token"

29 

30# 5. 用於除錯:減少匯出間隔

31export OTEL_METRIC_EXPORT_INTERVAL=10000 # 10 秒(預設:60000ms)

32export OTEL_LOGS_EXPORT_INTERVAL=5000 # 5 秒(預設:5000ms)

33 

34# 6. 執行 Claude Code

35claude

36```

37 

38<Note>

39 預設匯出間隔為指標 60 秒和日誌 5 秒。在設定期間,您可能希望使用較短的間隔用於除錯目的。記得在生產環境中重設這些值。

40</Note>

41 

42如需完整配置選項,請參閱 [OpenTelemetry 規範](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options)。

43 

44## 管理員配置

45 

46管理員可以透過[受管設定檔](/zh-TW/settings#settings-files)為所有使用者配置 OpenTelemetry 設定。這允許在整個組織中集中控制遙測設定。請參閱[設定優先順序](/zh-TW/settings#settings-precedence)以了解有關如何應用設定的更多資訊。

47 

48受管設定配置範例:

49 

50```json theme={null}

51{

52 "env": {

53 "CLAUDE_CODE_ENABLE_TELEMETRY": "1",

54 "OTEL_METRICS_EXPORTER": "otlp",

55 "OTEL_LOGS_EXPORTER": "otlp",

56 "OTEL_EXPORTER_OTLP_PROTOCOL": "grpc",

57 "OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector.example.com:4317",

58 "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer example-token"

59 }

60}

61```

62 

63<Note>

64 受管設定可以透過 MDM(行動裝置管理)或其他裝置管理解決方案進行分發。在受管設定檔中定義的環境變數具有高優先順序,使用者無法覆蓋。

65</Note>

66 

67## 配置詳情

68 

69### 常見配置變數

70 

71| 環境變數 | 描述 | 範例值 |

72| --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |

73| `CLAUDE_CODE_ENABLE_TELEMETRY` | 啟用遙測收集(必需) | `1` |

74| `OTEL_METRICS_EXPORTER` | 指標匯出器類型,逗號分隔。使用 `none` 以停用 | `console`、`otlp`、`prometheus`、`none` |

75| `OTEL_LOGS_EXPORTER` | 日誌/事件匯出器類型,逗號分隔。使用 `none` 以停用 | `console`、`otlp`、`none` |

76| `OTEL_EXPORTER_OTLP_PROTOCOL` | OTLP 匯出器的協議,適用於所有訊號 | `grpc`、`http/json`、`http/protobuf` |

77| `OTEL_EXPORTER_OTLP_ENDPOINT` | 所有訊號的 OTLP 收集器端點 | `http://localhost:4317` |

78| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | 指標協議,覆蓋一般設定 | `grpc`、`http/json`、`http/protobuf` |

79| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | OTLP 指標端點,覆蓋一般設定 | `http://localhost:4318/v1/metrics` |

80| `OTEL_EXPORTER_OTLP_LOGS_PROTOCOL` | 日誌協議,覆蓋一般設定 | `grpc`、`http/json`、`http/protobuf` |

81| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | OTLP 日誌端點,覆蓋一般設定 | `http://localhost:4318/v1/logs` |

82| `OTEL_EXPORTER_OTLP_HEADERS` | OTLP 的身份驗證標頭 | `Authorization=Bearer token` |

83| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY` | mTLS 身份驗證的用戶端金鑰 | 用戶端金鑰檔案的路徑 |

84| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE` | mTLS 身份驗證的用戶端憑證 | 用戶端憑證檔案的路徑 |

85| `OTEL_METRIC_EXPORT_INTERVAL` | 匯出間隔(毫秒)(預設:60000) | `5000`、`60000` |

86| `OTEL_LOGS_EXPORT_INTERVAL` | 日誌匯出間隔(毫秒)(預設:5000) | `1000`、`10000` |

87| `OTEL_LOG_USER_PROMPTS` | 啟用使用者提示內容的日誌記錄(預設:停用) | `1` 以啟用 |

88| `OTEL_LOG_TOOL_DETAILS` | 啟用在工具事件和追蹤跨度屬性中記錄工具參數和輸入引數的日誌:Bash 命令、MCP 伺服器和工具名稱、技能名稱和工具輸入。也在 `user_prompt` 事件上啟用自訂、plugin 和 MCP 命令名稱(預設:停用) | `1` 以啟用 |

89| `OTEL_LOG_TOOL_CONTENT` | 啟用在跨度事件中記錄工具輸入和輸出內容的日誌(預設:停用)。需要[追蹤](#traces-beta)。內容在 60 KB 處截斷 | `1` 以啟用 |

90| `OTEL_LOG_RAW_API_BODIES` | 將完整的 Anthropic Messages API 請求和回應 JSON 作為 `api_request_body` / `api_response_body` 日誌事件發出(預設:停用)。主體包括整個對話歷史記錄。啟用此選項意味著同意 `OTEL_LOG_USER_PROMPTS`、`OTEL_LOG_TOOL_DETAILS` 和 `OTEL_LOG_TOOL_CONTENT` 會揭露的所有內容 | `1` 用於在 60 KB 處截斷的內聯主體,或 `file:<dir>` 用於磁碟上未截斷的主體,事件中有 `body_ref` 指標 |

91| `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE` | 指標時間性偏好(預設:`delta`)。如果您的後端期望累積時間性,請設定為 `cumulative` | `delta`、`cumulative` |

92| `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | 重新整理動態標頭的間隔(預設:1740000ms / 29 分鐘) | `900000` |

93 

94### 指標基數控制

95 

96以下環境變數控制指標中包含哪些屬性以管理基數:

97 

98| 環境變數 | 描述 | 預設值 | 停用範例 |

99| ----------------------------------- | ----------------------------------------------- | ------- | ------- |

100| `OTEL_METRICS_INCLUDE_SESSION_ID` | 在指標中包含 session.id 屬性 | `true` | `false` |

101| `OTEL_METRICS_INCLUDE_VERSION` | 在指標中包含 app.version 屬性 | `false` | `true` |

102| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` | 在指標中包含 user.account\_uuid 和 user.account\_id 屬性 | `true` | `false` |

103 

104這些變數有助於控制指標的基數,這會影響指標後端中的儲存需求和查詢效能。較低的基數通常意味著更好的效能和更低的儲存成本,但分析的資料粒度較低。

105 

106### Traces (beta)

107 

108分散式追蹤匯出跨度,將每個使用者提示連結到它觸發的 API 請求和工具執行,因此您可以在追蹤後端中將完整請求檢視為單個追蹤。

109 

110追蹤預設為關閉。若要啟用它,請同時設定 `CLAUDE_CODE_ENABLE_TELEMETRY=1` 和 `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`,然後設定 `OTEL_TRACES_EXPORTER` 以選擇跨度的傳送位置。追蹤重複使用[常見 OTLP 配置](#common-configuration-variables)以取得端點、協議和標頭。

111 

112| 環境變數 | 描述 | 範例值 |

113| ------------------------------------- | ----------------------------------------------- | ---------------------------------- |

114| `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA` | 啟用跨度追蹤(必需)。也接受 `ENABLE_ENHANCED_TELEMETRY_BETA` | `1` |

115| `OTEL_TRACES_EXPORTER` | 追蹤匯出器類型,逗號分隔。使用 `none` 以停用 | `console`、`otlp`、`none` |

116| `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` | 追蹤協議,覆蓋 `OTEL_EXPORTER_OTLP_PROTOCOL` | `grpc`、`http/json`、`http/protobuf` |

117| `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | OTLP 追蹤端點,覆蓋 `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318/v1/traces` |

118| `OTEL_TRACES_EXPORT_INTERVAL` | 跨度批次匯出間隔(毫秒)(預設:5000) | `1000`、`10000` |

119 

120跨度預設會編輯使用者提示文字、工具輸入詳情和工具內容。設定 `OTEL_LOG_USER_PROMPTS=1`、`OTEL_LOG_TOOL_DETAILS=1` 和 `OTEL_LOG_TOOL_CONTENT=1` 以包含它們。

121 

122當追蹤處於活動狀態時,Bash 和 PowerShell 子程序會自動繼承包含活動工具執行跨度的 W3C 追蹤上下文的 `TRACEPARENT` 環境變數。這讓任何讀取 `TRACEPARENT` 的子程序都可以在同一追蹤下將其自己的跨度作為父項,透過 Claude 執行的指令碼和命令啟用端到端分散式追蹤。

123 

124在 Agent SDK 和以 `-p` 啟動的非互動式工作階段中,Claude Code 也會在啟動每個互動跨度時從其自己的環境中讀取 `TRACEPARENT` 和 `TRACESTATE`。這讓嵌入程序將其活動 W3C 追蹤上下文傳遞到子程序中,以便 Claude Code 的跨度顯示為呼叫者分散式追蹤的子項。互動式工作階段會忽略入站 `TRACEPARENT` 以避免意外繼承來自 CI 或容器環境的環境值。

125 

126#### 跨度階層

127 

128每個使用者提示啟動一個 `claude_code.interaction` 根跨度。API 呼叫、工具呼叫和 hook 執行被記錄為其子項。工具跨度有兩個自己的子跨度:一個用於等待權限決定所花費的時間,一個用於執行本身。當 Task 工具產生子代理時,子代理的 API 和工具跨度會嵌套在父項的 `claude_code.tool` 跨度下。

129 

130```text theme={null}

131claude_code.interaction

132├── claude_code.llm_request

133├── claude_code.hook (requires detailed beta tracing)

134└── claude_code.tool

135 ├── claude_code.tool.blocked_on_user

136 ├── claude_code.tool.execution

137 └── (Task tool) subagent claude_code.llm_request / claude_code.tool spans

138```

139 

140在 Agent SDK 和 `claude -p` 工作階段中,當環境中設定 `TRACEPARENT` 時,`claude_code.interaction` 本身會成為呼叫者跨度的子項。

141 

142#### 跨度屬性

143 

144每個跨度都帶有[標準屬性](#standard-attributes)加上與其名稱相符的 `span.type` 屬性。下表列出在每個跨度上設定的其他屬性。`llm_request`、`tool.execution` 和 `hook` 跨度在記錄失敗時設定 OpenTelemetry 狀態 `ERROR`;其他跨度始終以狀態 `UNSET` 結束。

145 

146**`claude_code.interaction`**

147 

148| 屬性 | 描述 | 由以下控制 |

149| ------------------------- | ------------------------------ | ----------------------- |

150| `user_prompt` | 提示文字。除非設定了閘道,否則值為 `<REDACTED>` | `OTEL_LOG_USER_PROMPTS` |

151| `user_prompt_length` | 提示長度(字元) | |

152| `interaction.sequence` | 此工作階段中互動的 1 為基數計數器 | |

153| `interaction.duration_ms` | 輪次的牆上時間持續時間 | |

154 

155**`claude_code.llm_request`**

156 

157| 屬性 | 描述 | 由以下控制 |

158| -------------------------------- | --------------------------------------------------------------------------------------------------- | ----- |

159| `model` | 模型識別碼 | |

160| `gen_ai.system` | 始終為 `anthropic`。OpenTelemetry GenAI 語義慣例 | |

161| `gen_ai.request.model` | 與 `model` 相同的值。OpenTelemetry GenAI 語義慣例 | |

162| `query_source` | 發出請求的子系統,例如 `repl_main_thread` 或子代理名稱 | |

163| `speed` | `fast` 或 `normal` | |

164| `llm_request.context` | `interaction`、`tool` 或 `standalone`,取決於父跨度 | |

165| `duration_ms` | 包括重試的牆上時間持續時間 | |

166| `ttft_ms` | 首個權杖的時間(毫秒) | |

167| `input_tokens` | 來自 API 使用區塊的輸入權杖計數 | |

168| `output_tokens` | 輸出權杖計數 | |

169| `cache_read_tokens` | 從提示快取讀取的權杖 | |

170| `cache_creation_tokens` | 寫入提示快取的權杖 | |

171| `request_id` | 來自 `request-id` 回應標頭的 Anthropic API 請求 ID | |

172| `gen_ai.response.id` | 與 `request_id` 相同的值。OpenTelemetry GenAI 語義慣例 | |

173| `client_request_id` | 最後一次嘗試的用戶端產生的 `x-client-request-id` | |

174| `attempt` | 為此請求進行的總嘗試次數 | |

175| `success` | `true` 或 `false` | |

176| `status_code` | 請求失敗時的 HTTP 狀態碼 | |

177| `error` | 請求失敗時的錯誤訊息 | |

178| `response.has_tool_call` | 當回應包含工具使用區塊時為 `true` | |

179| `stop_reason` | API 回應 `stop_reason`,例如 `end_turn`、`tool_use`、`max_tokens`、`stop_sequence`、`pause_turn` 或 `refusal` | |

180| `gen_ai.response.finish_reasons` | 與 `stop_reason` 相同的值,包裝在字串陣列中。OpenTelemetry GenAI 語義慣例 | |

181 

182每次重試嘗試也被記錄為具有 `attempt` 和 `client_request_id` 屬性的 `gen_ai.request.attempt` 跨度事件。

183 

184**`claude_code.tool`**

185 

186| 屬性 | 描述 | 由以下控制 |

187| --------------- | --------------------------- | ----------------------- |

188| `tool_name` | 工具名稱 | |

189| `duration_ms` | 包括權限等待和執行的牆上時間持續時間 | |

190| `result_tokens` | 工具結果的近似權杖大小 | |

191| `file_path` | Read、Edit 和 Write 工具的目標檔案路徑 | `OTEL_LOG_TOOL_DETAILS` |

192| `full_command` | Bash 工具的命令字串 | `OTEL_LOG_TOOL_DETAILS` |

193| `skill_name` | Skill 工具的技能名稱 | `OTEL_LOG_TOOL_DETAILS` |

194| `subagent_type` | Task 工具的子代理類型 | `OTEL_LOG_TOOL_DETAILS` |

195 

196當 `OTEL_LOG_TOOL_CONTENT=1` 時,此跨度也會記錄一個 `tool.output` 跨度事件,其屬性包含工具的輸入和輸出主體,在每個屬性處截斷 60 KB。

197 

198**`claude_code.tool.blocked_on_user`**

199 

200| 屬性 | 描述 | 由以下控制 |

201| ------------- | ------------------------------------- | ----- |

202| `duration_ms` | 等待權限決定所花費的時間 | |

203| `decision` | `accept` 或 `reject` | |

204| `source` | 決定來源,符合[工具決定事件](#tool-decision-event) | |

205 

206**`claude_code.tool.execution`**

207 

208| 屬性 | 描述 | 由以下控制 |

209| ------------- | ------------------------------------------------------------- | ----------------------- |

210| `duration_ms` | 執行工具主體所花費的時間 | |

211| `success` | `true` 或 `false` | |

212| `error` | 執行失敗時的錯誤類別字串,例如 `Error:ENOENT` 或 `ShellError`。當設定了閘道時包含完整錯誤訊息 | `OTEL_LOG_TOOL_DETAILS` |

213 

214**`claude_code.hook`**

215 

216此跨度僅在詳細 beta 追蹤處於活動狀態時發出,除了上述追蹤匯出器配置外,還需要 `ENABLE_BETA_TRACING_DETAILED=1` 和 `BETA_TRACING_ENDPOINT`。在互動式 CLI 工作階段中,這也需要您的組織被列入該功能的允許清單。Agent SDK 和非互動式 `-p` 工作階段不受限制。當僅設定 `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA` 時不會發出。

217 

218| 屬性 | 描述 | 由以下控制 |

219| ------------------------ | -------------------------------- | ----------------------- |

220| `hook_event` | Hook 事件類型,例如 `PreToolUse` | |

221| `hook_name` | 完整 hook 名稱,例如 `PreToolUse:Write` | |

222| `num_hooks` | 執行的匹配 hook 命令數 | |

223| `hook_definitions` | JSON 序列化的 hook 配置 | `OTEL_LOG_TOOL_DETAILS` |

224| `duration_ms` | 所有匹配 hook 的牆上時間持續時間 | |

225| `num_success` | 成功完成的 hook 計數 | |

226| `num_blocking` | 傳回阻止決定的 hook 計數 | |

227| `num_non_blocking_error` | 在不阻止的情況下失敗的 hook 計數 | |

228| `num_cancelled` | 在完成前取消的 hook 計數 | |

229 

230<Note>

231 其他內容承載屬性,例如 `new_context`、`system_prompt_preview`、`user_system_prompt`、`tool_input` 和 `response.model_output`,僅在詳細 beta 追蹤處於活動狀態時發出。它們不是穩定跨度架構的一部分。`user_system_prompt` 另外需要 `OTEL_LOG_USER_PROMPTS=1`。它僅包含您透過 `systemPrompt` SDK 選項或 `--system-prompt` 和 `--append-system-prompt` 旗標提供的系統提示文字,在 60 KB 處截斷,並且每個工作階段發出一次而不是每個請求發出一次。

232</Note>

233 

234### 動態標頭

235 

236對於需要動態身份驗證的企業環境,您可以配置指令碼來動態產生標頭:

237 

238#### 設定配置

239 

240新增至您的 `.claude/settings.json`:

241 

242```json theme={null}

243{

244 "otelHeadersHelper": "/bin/generate_opentelemetry_headers.sh"

245}

246```

247 

248#### 指令碼需求

249 

250指令碼必須輸出有效的 JSON,其中包含代表 HTTP 標頭的字串鍵值對:

251 

252```bash theme={null}

253#!/bin/bash

254# 範例:多個標頭

255echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}"

256```

257 

258#### 重新整理行為

259 

260標頭協助程式指令碼在啟動時執行,之後定期執行以支援權杖重新整理。預設情況下,指令碼每 29 分鐘執行一次。使用 `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` 環境變數自訂間隔。

261 

262### 多團隊組織支援

263 

264具有多個團隊或部門的組織可以使用 `OTEL_RESOURCE_ATTRIBUTES` 環境變數新增自訂屬性以區分不同的群組:

265 

266```bash theme={null}

267# 新增自訂屬性以進行團隊識別

268export OTEL_RESOURCE_ATTRIBUTES="department=engineering,team.id=platform,cost_center=eng-123"

269```

270 

271這些自訂屬性將包含在所有指標和事件中,允許您:

272 

273* 按團隊或部門篩選指標

274* 追蹤每個成本中心的成本

275* 建立團隊特定的儀表板

276* 為特定團隊設定警報

277 

278<Warning>

279 **OTEL\_RESOURCE\_ATTRIBUTES 的重要格式要求:**

280 

281 `OTEL_RESOURCE_ATTRIBUTES` 環境變數使用逗號分隔的鍵=值對,具有嚴格的格式要求:

282 

283 * **不允許空格**:值不能包含空格。例如,`user.organizationName=My Company` 無效

284 * **格式**:必須是逗號分隔的鍵=值對:`key1=value1,key2=value2`

285 * **允許的字元**:僅限 US-ASCII 字元,不包括控制字元、空格、雙引號、逗號、分號和反斜線

286 * **特殊字元**:允許範圍外的字元必須進行百分比編碼

287 

288 **範例:**

289 

290 ```bash theme={null}

291 # ❌ 無效 - 包含空格

292 export OTEL_RESOURCE_ATTRIBUTES="org.name=John's Organization"

293 

294 # ✅ 有效 - 改用底線或駝峰式大小寫

295 export OTEL_RESOURCE_ATTRIBUTES="org.name=Johns_Organization"

296 export OTEL_RESOURCE_ATTRIBUTES="org.name=JohnsOrganization"

297 

298 # ✅ 有效 - 如果需要,對特殊字元進行百分比編碼

299 export OTEL_RESOURCE_ATTRIBUTES="org.name=John%27s%20Organization"

300 ```

301 

302 注意:將值用引號括起來不會逃逸空格。例如,`org.name="My Company"` 會產生字面值 `"My Company"`(包括引號),而不是 `My Company`。

303</Warning>

304 

305### 配置範例

306 

307在執行 `claude` 之前設定這些環境變數。每個區塊顯示不同匯出器或部署情境的完整配置:

308 

309```bash theme={null}

310# 控制台除錯(1 秒間隔)

311export CLAUDE_CODE_ENABLE_TELEMETRY=1

312export OTEL_METRICS_EXPORTER=console

313export OTEL_METRIC_EXPORT_INTERVAL=1000

314 

315# OTLP/gRPC

316export CLAUDE_CODE_ENABLE_TELEMETRY=1

317export OTEL_METRICS_EXPORTER=otlp

318export OTEL_EXPORTER_OTLP_PROTOCOL=grpc

319export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317

320 

321# Prometheus

322export CLAUDE_CODE_ENABLE_TELEMETRY=1

323export OTEL_METRICS_EXPORTER=prometheus

324 

325# 多個匯出器

326export CLAUDE_CODE_ENABLE_TELEMETRY=1

327export OTEL_METRICS_EXPORTER=console,otlp

328export OTEL_EXPORTER_OTLP_PROTOCOL=http/json

329 

330# 指標和日誌的不同端點/後端

331export CLAUDE_CODE_ENABLE_TELEMETRY=1

332export OTEL_METRICS_EXPORTER=otlp

333export OTEL_LOGS_EXPORTER=otlp

334export OTEL_EXPORTER_OTLP_METRICS_PROTOCOL=http/protobuf

335export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://metrics.example.com:4318

336export OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=grpc

337export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=http://logs.example.com:4317

338 

339# 僅指標(無事件/日誌)

340export CLAUDE_CODE_ENABLE_TELEMETRY=1

341export OTEL_METRICS_EXPORTER=otlp

342export OTEL_EXPORTER_OTLP_PROTOCOL=grpc

343export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317

344 

345# 僅事件/日誌(無指標)

346export CLAUDE_CODE_ENABLE_TELEMETRY=1

347export OTEL_LOGS_EXPORTER=otlp

348export OTEL_EXPORTER_OTLP_PROTOCOL=grpc

349export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317

350```

351 

352## 可用的指標和事件

353 

354### 標準屬性

355 

356所有指標和事件共享這些標準屬性:

357 

358| 屬性 | 描述 | 控制者 |

359| ------------------- | -------------------------------------------------------------- | -------------------------------------------- |

360| `session.id` | 唯一的工作階段識別碼 | `OTEL_METRICS_INCLUDE_SESSION_ID`(預設:true) |

361| `app.version` | 目前的 Claude Code 版本 | `OTEL_METRICS_INCLUDE_VERSION`(預設:false) |

362| `organization.id` | 組織 UUID(已驗證時) | 可用時始終包含 |

363| `user.account_uuid` | 帳戶 UUID(已驗證時) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID`(預設:true) |

364| `user.account_id` | 帳戶 ID(採用標籤格式,符合 Anthropic 管理 API),例如 `user_01BWBeN28...`(已驗證時) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID`(預設:true) |

365| `user.id` | 匿名裝置/安裝識別碼,每個 Claude Code 安裝產生一次 | 始終包含 |

366| `user.email` | 使用者電子郵件地址(透過 OAuth 驗證時) | 可用時始終包含 |

367| `terminal.type` | 終端機類型,例如 `iTerm.app`、`vscode`、`cursor` 或 `tmux` | 偵測到時始終包含 |

368 

369事件另外包含以下屬性。這些永遠不會附加到指標,因為它們會導致無限制的基數:

370 

371* `prompt.id`:UUID 將使用者提示與所有後續事件關聯到下一個提示。請參閱[事件關聯屬性](#event-correlation-attributes)。

372* `workspace.host_paths`:在桌面應用程式中選擇的主機工作區目錄,作為字串陣列

373 

374### 指標

375 

376Claude Code 匯出以下指標:

377 

378| 指標名稱 | 描述 | 單位 |

379| ------------------------------------- | ------------------- | ------ |

380| `claude_code.session.count` | 啟動的 CLI 工作階段計數 | count |

381| `claude_code.lines_of_code.count` | 修改的程式碼行數計數 | count |

382| `claude_code.pull_request.count` | 建立的提取請求數 | count |

383| `claude_code.commit.count` | 建立的 git 提交數 | count |

384| `claude_code.cost.usage` | Claude Code 工作階段的成本 | USD |

385| `claude_code.token.usage` | 使用的權杖數 | tokens |

386| `claude_code.code_edit_tool.decision` | 程式碼編輯工具權限決定的計數 | count |

387| `claude_code.active_time.total` | 總活躍時間(秒) | s |

388 

389### 指標詳情

390 

391每個指標都包含上面列出的標準屬性。具有額外內容特定屬性的指標如下所述。

392 

393#### 工作階段計數器

394 

395在每個工作階段開始時遞增。

396 

397**屬性**:

398 

399* 所有[標準屬性](#standard-attributes)

400* `start_type`:工作階段的啟動方式。`"fresh"`、`"resume"` 或 `"continue"` 之一

401 

402#### 程式碼行計數器

403 

404在新增或移除程式碼時遞增。

405 

406**屬性**:

407 

408* 所有[標準屬性](#standard-attributes)

409* `type`:(`"added"`、`"removed"`)

410 

411#### 提取請求計數器

412 

413透過 Claude Code 建立提取請求時遞增。

414 

415**屬性**:

416 

417* 所有[標準屬性](#standard-attributes)

418 

419#### 提交計數器

420 

421透過 Claude Code 建立 git 提交時遞增。

422 

423**屬性**:

424 

425* 所有[標準屬性](#standard-attributes)

426 

427#### 成本計數器

428 

429在每個 API 請求後遞增。

430 

431**屬性**:

432 

433* 所有[標準屬性](#standard-attributes)

434* `model`:模型識別碼(例如,"claude-sonnet-4-6")

435* `query_source`:發出請求的子系統的類別。`"main"`、`"subagent"` 或 `"auxiliary"` 之一

436* `speed`:當請求使用快速模式時為 `"fast"`。否則不存在

437* `effort`:應用於請求的[努力等級](/zh-TW/model-config#adjust-effort-level):`"low"`、`"medium"`、`"high"`、`"xhigh"` 或 `"max"`。當模型不支援努力時不存在。

438 

439#### 權杖計數器

440 

441在每個 API 請求後遞增。

442 

443**屬性**:

444 

445* 所有[標準屬性](#standard-attributes)

446* `type`:(`"input"`、`"output"`、`"cacheRead"`、`"cacheCreation"`)

447* `model`:模型識別碼(例如,"claude-sonnet-4-6")

448* `query_source`:發出請求的子系統的類別。`"main"`、`"subagent"` 或 `"auxiliary"` 之一

449* `speed`:當請求使用快速模式時為 `"fast"`。否則不存在

450* `effort`:應用於請求的[努力等級](/zh-TW/model-config#adjust-effort-level)。詳見[成本計數器](#cost-counter)。

451 

452#### 程式碼編輯工具決定計數器

453 

454當使用者接受或拒絕 Edit、Write 或 NotebookEdit 工具使用時遞增。

455 

456**屬性**:

457 

458* 所有[標準屬性](#standard-attributes)

459* `tool_name`:工具名稱(`"Edit"`、`"Write"`、`"NotebookEdit"`)

460* `decision`:使用者決定(`"accept"`、`"reject"`)

461* `source`:決定來源。`"config"`、`"hook"`、`"user_permanent"`、`"user_temporary"`、`"user_abort"` 或 `"user_reject"` 之一。詳見[工具決定事件](#tool-decision-event)以了解每個值的含義。

462* `language`:編輯檔案的程式設計語言,例如 `"TypeScript"`、`"Python"`、`"JavaScript"` 或 `"Markdown"`。對於無法識別的副檔名,傳回 `"unknown"`。

463 

464#### 活躍時間計數器

465 

466追蹤實際花費在主動使用 Claude Code 上的時間,不包括閒置時間。此指標在使用者互動期間遞增(輸入、讀取回應)以及在 CLI 處理期間遞增(工具執行、AI 回應產生)。

467 

468**屬性**:

469 

470* 所有[標準屬性](#standard-attributes)

471* `type`:`"user"` 用於鍵盤互動,`"cli"` 用於工具執行和 AI 回應

472 

473### 事件

474 

475Claude Code 透過 OpenTelemetry 日誌/事件匯出以下事件(當配置 `OTEL_LOGS_EXPORTER` 時):

476 

477#### 事件關聯屬性

478 

479當使用者提交提示時,Claude Code 可能會進行多個 API 呼叫並執行多個工具。`prompt.id` 屬性可讓您將所有這些事件與觸發它們的單個提示相關聯。

480 

481| 屬性 | 描述 |

482| ----------- | ------------------------------- |

483| `prompt.id` | UUID v4 識別碼,連結處理單個使用者提示時產生的所有事件 |

484 

485若要追蹤由單個提示觸發的所有活動,請按特定 `prompt.id` 值篩選您的事件。這會傳回使用者提示事件、任何 api\_request 事件以及處理該提示時發生的任何 tool\_result 事件。

486 

487<Note>

488 `prompt.id` 有意從指標中排除,因為每個提示都會產生唯一的 ID,這會建立不斷增長的時間序列數量。僅將其用於事件級分析和稽核追蹤。

489</Note>

490 

491#### 使用者提示事件

492 

493當使用者提交提示時記錄。

494 

495**事件名稱**:`claude_code.user_prompt`

496 

497**屬性**:

498 

499* 所有[標準屬性](#standard-attributes)

500* `event.name`:`"user_prompt"`

501* `event.timestamp`:ISO 8601 時間戳

502* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

503* `prompt_length`:提示的長度

504* `prompt`:提示內容(預設為編輯,使用 `OTEL_LOG_USER_PROMPTS=1` 啟用)

505* `command_name`:當提示叫用命令時的命令名稱。內建和捆綁的命令名稱(例如 `compact` 或 `debug`)按原樣發出;別名(例如 `reset`)按輸入方式發出而不是規範名稱。自訂、plugin 和 MCP 命令名稱除非設定 `OTEL_LOG_TOOL_DETAILS=1`,否則會摺疊為 `custom` 或 `mcp`

506* `command_source`:命令的來源(如果存在):`builtin`、`custom` 或 `mcp`。Plugin 提供的命令報告為 `custom`

507 

508#### 工具結果事件

509 

510當工具完成執行時記錄。

511 

512**事件名稱**:`claude_code.tool_result`

513 

514**屬性**:

515 

516* 所有[標準屬性](#standard-attributes)

517* `event.name`:`"tool_result"`

518* `event.timestamp`:ISO 8601 時間戳

519* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

520* `tool_name`:工具的名稱

521* `tool_use_id`:此工具叫用的唯一識別碼。符合傳遞給 hooks 的 `tool_use_id`,允許 OTel 事件和 hook 擷取資料之間的關聯。

522* `success`:`"true"` 或 `"false"`

523* `duration_ms`:執行時間(毫秒)

524* `error_type`:工具失敗時的錯誤類別字串,例如 `"Error:ENOENT"` 或 `"ShellError"`

525* `error`(當 `OTEL_LOG_TOOL_DETAILS=1` 時):工具失敗時的完整錯誤訊息

526* `decision_type`:`"accept"` 或 `"reject"`

527* `decision_source`:決定來源。`"config"`、`"hook"`、`"user_permanent"`、`"user_temporary"`、`"user_abort"` 或 `"user_reject"` 之一。詳見[工具決定事件](#tool-decision-event)以了解每個值的含義。

528* `tool_input_size_bytes`:JSON 序列化工具輸入的大小(位元組)

529* `tool_result_size_bytes`:工具結果的大小(位元組)

530* `mcp_server_scope`:MCP 伺服器範圍識別碼(用於 MCP 工具)

531* `tool_parameters`(當 `OTEL_LOG_TOOL_DETAILS=1` 時):包含工具特定參數的 JSON 字串:

532 * 對於 Bash 工具:包括 `bash_command`、`full_command`、`timeout`、`description`、`dangerouslyDisableSandbox` 和 `git_commit_id`(git commit 命令成功時的提交 SHA)

533 * 對於 MCP 工具:包括 `mcp_server_name`、`mcp_tool_name`

534 * 對於 Skill 工具:包括 `skill_name`

535 * 對於 Task 工具:包括 `subagent_type`

536* `tool_input`(當 `OTEL_LOG_TOOL_DETAILS=1` 時):JSON 序列化的工具引數。超過 512 個字元的個別值會被截斷,整個承載的上限約為 4 K 字元。適用於所有工具,包括 MCP 工具。

537 

538#### API 請求事件

539 

540為每個 API 請求記錄到 Claude。

541 

542**事件名稱**:`claude_code.api_request`

543 

544**屬性**:

545 

546* 所有[標準屬性](#standard-attributes)

547* `event.name`:`"api_request"`

548* `event.timestamp`:ISO 8601 時間戳

549* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

550* `model`:使用的模型(例如,"claude-sonnet-4-6")

551* `cost_usd`:估計成本(美元)

552* `duration_ms`:請求持續時間(毫秒)

553* `input_tokens`:輸入權杖數

554* `output_tokens`:輸出權杖數

555* `cache_read_tokens`:從快取讀取的權杖數

556* `cache_creation_tokens`:用於快取建立的權杖數

557* `request_id`:來自回應的 `request-id` 標頭的 Anthropic API 請求 ID,例如 `"req_011..."`。僅當 API 傳回時才存在。

558* `speed`:`"fast"` 或 `"normal"`,指示是否啟用了快速模式

559* `query_source`:發出請求的子系統,例如 `"repl_main_thread"`、`"compact"` 或子代理名稱

560* `effort`:應用於請求的[努力等級](/zh-TW/model-config#adjust-effort-level):`"low"`、`"medium"`、`"high"`、`"xhigh"` 或 `"max"`。當模型不支援努力時不存在。

561 

562#### API 錯誤事件

563 

564當 API 請求到 Claude 失敗時記錄。

565 

566**事件名稱**:`claude_code.api_error`

567 

568**屬性**:

569 

570* 所有[標準屬性](#standard-attributes)

571* `event.name`:`"api_error"`

572* `event.timestamp`:ISO 8601 時間戳

573* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

574* `model`:使用的模型(例如,"claude-sonnet-4-6")

575* `error`:錯誤訊息

576* `status_code`:HTTP 狀態碼(數字形式)。對於非 HTTP 錯誤(例如連線失敗),不存在。

577* `duration_ms`:請求持續時間(毫秒)

578* `attempt`:進行的嘗試總次數,包括初始請求(`1` 表示未發生重試)

579* `request_id`:來自回應的 `request-id` 標頭的 Anthropic API 請求 ID,例如 `"req_011..."`。僅當 API 傳回時才存在。

580* `speed`:`"fast"` 或 `"normal"`,指示是否啟用了快速模式

581* `query_source`:發出請求的子系統,例如 `"repl_main_thread"`、`"compact"` 或子代理名稱

582* `effort`:應用於請求的[努力等級](/zh-TW/model-config#adjust-effort-level)。當模型不支援努力時不存在。

583 

584#### API 請求主體事件

585 

586當設定 `OTEL_LOG_RAW_API_BODIES` 時,為每個 API 請求嘗試記錄。每次嘗試發出一個事件,因此使用調整參數的重試各自產生自己的事件。

587 

588**事件名稱**:`claude_code.api_request_body`

589 

590**屬性**:

591 

592* 所有[標準屬性](#standard-attributes)

593* `event.name`:`"api_request_body"`

594* `event.timestamp`:ISO 8601 時間戳

595* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

596* `body`:JSON 序列化的 Messages API 請求參數(系統提示、訊息、工具等),在 60 KB 處截斷。先前助手輪次中的擴展思考內容被編輯。僅在內聯模式下發出(`OTEL_LOG_RAW_API_BODIES=1`)。

597* `body_ref`:包含未截斷主體的 `<dir>/<uuid>.request.json` 檔案的絕對路徑。僅在檔案模式下發出(`OTEL_LOG_RAW_API_BODIES=file:<dir>`)。

598* `body_length`:未截斷的主體長度。當 `OTEL_LOG_RAW_API_BODIES=file:<dir>` 時為 UTF-8 位元組,或當 `=1` 時為 UTF-16 程式碼單位

599* `body_truncated`:當發生內聯截斷時為 `"true"`。在檔案模式下和未發生截斷時不存在。

600* `model`:來自請求參數的模型識別碼

601* `query_source`:發出請求的子系統(例如,`"compact"`)

602 

603#### API 回應主體事件

604 

605當設定 `OTEL_LOG_RAW_API_BODIES` 時,為每個成功的 API 回應記錄。

606 

607**事件名稱**:`claude_code.api_response_body`

608 

609**屬性**:

610 

611* 所有[標準屬性](#standard-attributes)

612* `event.name`:`"api_response_body"`

613* `event.timestamp`:ISO 8601 時間戳

614* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

615* `body`:JSON 序列化的 Messages API 回應(id、內容區塊、使用情況、停止原因),在 60 KB 處截斷。擴展思考內容被編輯。僅在內聯模式下發出(`OTEL_LOG_RAW_API_BODIES=1`)。

616* `body_ref`:包含未截斷主體的 `<dir>/<request_id>.response.json` 檔案的絕對路徑。僅在檔案模式下發出(`OTEL_LOG_RAW_API_BODIES=file:<dir>`)。

617* `body_length`:未截斷的主體長度。當 `OTEL_LOG_RAW_API_BODIES=file:<dir>` 時為 UTF-8 位元組,或當 `=1` 時為 UTF-16 程式碼單位

618* `body_truncated`:當發生內聯截斷時為 `"true"`。在檔案模式下和未發生截斷時不存在。

619* `model`:模型識別碼

620* `query_source`:發出請求的子系統

621* `request_id`:來自回應的 `request-id` 標頭的 Anthropic API 請求 ID,例如 `"req_011..."`。僅當 API 傳回時才存在。

622 

623#### 工具決定事件

624 

625當做出工具權限決定(接受/拒絕)時記錄。

626 

627**事件名稱**:`claude_code.tool_decision`

628 

629**屬性**:

630 

631* 所有[標準屬性](#standard-attributes)

632* `event.name`:`"tool_decision"`

633* `event.timestamp`:ISO 8601 時間戳

634* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

635* `tool_name`:工具的名稱(例如,"Read"、"Edit"、"Write"、"NotebookEdit")

636* `tool_use_id`:此工具叫用的唯一識別碼。符合傳遞給 hooks 的 `tool_use_id`,允許 OTel 事件和 hook 擷取資料之間的關聯。

637* `decision`:`"accept"` 或 `"reject"`

638* `source`:決定來源:

639 * `"config"`:根據專案設定、企業受管原則、`--allowedTools` 或 `--disallowedTools` 旗標、活躍權限模式或因為工具本身是安全的,自動決定而不提示。

640 * `"hook"`:`PreToolUse` 或 `PermissionRequest` hook 傳回了決定。

641 * `"user_permanent"`:當使用者在提示時選擇「始終允許」時發出,將規則儲存到其個人設定。也針對符合該儲存規則的後續呼叫發出。視為接受。

642 * `"user_temporary"`:當使用者在提示時選擇「是」或「是,此工作階段」時發出,不儲存規則。也針對同一工作階段中符合該工作階段範圍允許的後續呼叫發出。視為接受。

643 * `"user_abort"`:當使用者關閉權限提示而不回答時發出。視為拒絕。

644 * `"user_reject"`:當使用者選擇「否」時發出,或呼叫符合其個人設定中的拒絕規則。視為拒絕。

645 

646#### 權限模式變更事件

647 

648當權限模式變更時記錄,例如從 `Shift+Tab` 循環、退出計畫模式或自動模式閘道檢查。

649 

650**事件名稱**:`claude_code.permission_mode_changed`

651 

652**屬性**:

653 

654* 所有[標準屬性](#standard-attributes)

655* `event.name`:`"permission_mode_changed"`

656* `event.timestamp`:ISO 8601 時間戳

657* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

658* `from_mode`:先前的權限模式,例如 `"default"`、`"plan"`、`"acceptEdits"`、`"auto"` 或 `"bypassPermissions"`

659* `to_mode`:新的權限模式

660* `trigger`:導致變更的原因。`"shift_tab"`、`"exit_plan_mode"`、`"auto_gate_denied"` 或 `"auto_opt_in"` 之一。當轉換來自 SDK 或橋接時不存在。

661 

662#### 身份驗證事件

663 

664當 `/login` 或 `/logout` 完成時記錄。

665 

666**事件名稱**:`claude_code.auth`

667 

668**屬性**:

669 

670* 所有[標準屬性](#standard-attributes)

671* `event.name`:`"auth"`

672* `event.timestamp`:ISO 8601 時間戳

673* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

674* `action`:`"login"` 或 `"logout"`

675* `success`:`"true"` 或 `"false"`

676* `auth_method`:身份驗證方法,例如 `"oauth"`

677* `error_category`:操作失敗時的分類錯誤類型。永遠不包括原始錯誤訊息

678* `status_code`:操作因 HTTP 錯誤而失敗時的 HTTP 狀態碼(字串形式)

679 

680#### MCP 伺服器連線事件

681 

682當 MCP 伺服器連線、斷開連線或無法連線時記錄。

683 

684**事件名稱**:`claude_code.mcp_server_connection`

685 

686**屬性**:

687 

688* 所有[標準屬性](#standard-attributes)

689* `event.name`:`"mcp_server_connection"`

690* `event.timestamp`:ISO 8601 時間戳

691* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

692* `status`:`"connected"`、`"failed"` 或 `"disconnected"`

693* `transport_type`:伺服器傳輸,例如 `"stdio"`、`"sse"` 或 `"http"`

694* `server_scope`:伺服器配置的範圍,例如 `"user"`、`"project"` 或 `"local"`

695* `duration_ms`:連線嘗試持續時間(毫秒)

696* `error_code`:連線失敗時的錯誤碼

697* `server_name`(當 `OTEL_LOG_TOOL_DETAILS=1` 時):配置的伺服器名稱

698* `error`(當 `OTEL_LOG_TOOL_DETAILS=1` 時):連線失敗時的完整錯誤訊息

699 

700#### 內部錯誤事件

701 

702當 Claude Code 捕捉到意外的內部錯誤時記錄。僅記錄錯誤類別名稱和 errno 樣式碼。永遠不包括錯誤訊息和堆疊追蹤。當針對 Bedrock、Vertex 或 Foundry 執行或設定 `DISABLE_ERROR_REPORTING` 時,不會發出此事件。

703 

704**事件名稱**:`claude_code.internal_error`

705 

706**屬性**:

707 

708* 所有[標準屬性](#standard-attributes)

709* `event.name`:`"internal_error"`

710* `event.timestamp`:ISO 8601 時間戳

711* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

712* `error_name`:錯誤類別名稱,例如 `"TypeError"` 或 `"SyntaxError"`

713* `error_code`:Node.js errno 碼,例如 `"ENOENT"`(如果存在於錯誤上)

714 

715#### Plugin 已安裝事件

716 

717當 plugin 完成安裝時記錄,來自 `claude plugin install` CLI 命令和互動式 `/plugin` UI。

718 

719**事件名稱**:`claude_code.plugin_installed`

720 

721**屬性**:

722 

723* 所有[標準屬性](#standard-attributes)

724* `event.name`:`"plugin_installed"`

725* `event.timestamp`:ISO 8601 時間戳

726* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

727* `marketplace.is_official`:如果市場是官方 Anthropic 市場,則為 `"true"`,否則為 `"false"`

728* `install.trigger`:`"cli"` 或 `"ui"`

729* `plugin.name`:已安裝 plugin 的名稱。對於第三方市場,僅當 `OTEL_LOG_TOOL_DETAILS=1` 時才包含

730* `plugin.version`:Plugin 版本(如果在市場條目中宣告)。對於第三方市場,僅當 `OTEL_LOG_TOOL_DETAILS=1` 時才包含

731* `marketplace.name`:安裝 plugin 的市場。對於第三方市場,僅當 `OTEL_LOG_TOOL_DETAILS=1` 時才包含

732 

733#### Skill 已啟動事件

734 

735當叫用 skill 時記錄,無論 Claude 是透過 Skill 工具呼叫它,還是您將其作為 `/` 命令執行。

736 

737**事件名稱**:`claude_code.skill_activated`

738 

739**屬性**:

740 

741* 所有[標準屬性](#standard-attributes)

742* `event.name`:`"skill_activated"`

743* `event.timestamp`:ISO 8601 時間戳

744* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

745* `skill.name`:Skill 的名稱。對於使用者定義和第三方 plugin skill,除非 `OTEL_LOG_TOOL_DETAILS=1`,否則值為預留位置 `"custom_skill"`

746* `invocation_trigger`:Skill 的觸發方式(`"user-slash"`、`"claude-proactive"` 或 `"nested-skill"`)

747* `skill.source`:Skill 的載入位置(例如,`"bundled"`、`"userSettings"`、`"projectSettings"`、`"plugin"`)

748* `plugin.name`(當 `OTEL_LOG_TOOL_DETAILS=1` 或 plugin 來自官方市場時):當 skill 由 plugin 提供時的擁有 plugin 名稱

749* `marketplace.name`(當 `OTEL_LOG_TOOL_DETAILS=1` 或 plugin 來自官方市場時):當 skill 由 plugin 提供時,擁有 plugin 的安裝市場

750 

751#### @ 提及事件

752 

753當 Claude Code 解析提示中的 `@` 提及時記錄。並非每個提及都會發出事件:早期退出路徑(例如權限拒絕、超大檔案、PDF 參考附件和目錄列表失敗)會在不記錄的情況下返回。

754 

755**事件名稱**:`claude_code.at_mention`

756 

757**屬性**:

758 

759* 所有[標準屬性](#standard-attributes)

760* `event.name`:`"at_mention"`

761* `event.timestamp`:ISO 8601 時間戳

762* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

763* `mention_type`:提及的類型(`"file"`、`"directory"`、`"agent"`、`"mcp_resource"`)

764* `success`:提及是否成功解析(`"true"` 或 `"false"`)

765 

766#### API 重試已耗盡事件

767 

768當 API 請求在多次嘗試後失敗時記錄一次。與最終 `api_error` 事件一起發出。

769 

770**事件名稱**:`claude_code.api_retries_exhausted`

771 

772**屬性**:

773 

774* 所有[標準屬性](#standard-attributes)

775* `event.name`:`"api_retries_exhausted"`

776* `event.timestamp`:ISO 8601 時間戳

777* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

778* `model`:使用的模型

779* `error`:最終錯誤訊息

780* `status_code`:HTTP 狀態碼(數字形式)。對於非 HTTP 錯誤,不存在。

781* `total_attempts`:進行的嘗試總次數

782* `total_retry_duration_ms`:所有嘗試的總牆上時間

783* `speed`:`"fast"` 或 `"normal"`

784 

785#### Hook 執行開始事件

786 

787當一個或多個 hook 開始為 hook 事件執行時記錄。

788 

789**事件名稱**:`claude_code.hook_execution_start`

790 

791**屬性**:

792 

793* 所有[標準屬性](#standard-attributes)

794* `event.name`:`"hook_execution_start"`

795* `event.timestamp`:ISO 8601 時間戳

796* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

797* `hook_event`:Hook 事件類型,例如 `"PreToolUse"` 或 `"PostToolUse"`

798* `hook_name`:完整 hook 名稱,包括匹配器,例如 `"PreToolUse:Write"`

799* `num_hooks`:匹配 hook 命令的數量

800* `managed_only`:當僅允許受管原則 hook 時為 `"true"`

801* `hook_source`:`"policySettings"` 或 `"merged"`

802* `hook_definitions`:JSON 序列化的 hook 配置。僅當詳細 beta 追蹤和 `OTEL_LOG_TOOL_DETAILS=1` 都啟用時才包含

803 

804#### Hook 執行完成事件

805 

806當 hook 事件的所有 hook 完成時記錄。

807 

808**事件名稱**:`claude_code.hook_execution_complete`

809 

810**屬性**:

811 

812* 所有[標準屬性](#standard-attributes)

813* `event.name`:`"hook_execution_complete"`

814* `event.timestamp`:ISO 8601 時間戳

815* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

816* `hook_event`:Hook 事件類型

817* `hook_name`:完整 hook 名稱,包括匹配器

818* `num_hooks`:匹配 hook 命令的數量

819* `num_success`:成功完成的計數

820* `num_blocking`:傳回阻止決定的計數

821* `num_non_blocking_error`:在不阻止的情況下失敗的計數

822* `num_cancelled`:在完成前取消的計數

823* `total_duration_ms`:所有匹配 hook 的牆上時間持續時間

824* `managed_only`:當僅允許受管原則 hook 時為 `"true"`

825* `hook_source`:`"policySettings"` 或 `"merged"`

826* `hook_definitions`:JSON 序列化的 hook 配置。僅當詳細 beta 追蹤和 `OTEL_LOG_TOOL_DETAILS=1` 都啟用時才包含

827 

828#### 壓縮事件

829 

830當對話壓縮完成時記錄。

831 

832**事件名稱**:`claude_code.compaction`

833 

834**屬性**:

835 

836* 所有[標準屬性](#standard-attributes)

837* `event.name`:`"compaction"`

838* `event.timestamp`:ISO 8601 時間戳

839* `event.sequence`:單調遞增計數器,用於排序工作階段內的事件

840* `trigger`:`"auto"` 或 `"manual"`

841* `success`:`"true"` 或 `"false"`

842* `duration_ms`:壓縮持續時間

843* `pre_tokens`:壓縮前的近似權杖計數

844* `post_tokens`:壓縮後的近似權杖計數

845* `error`:壓縮失敗時的錯誤訊息

846 

847## 解釋指標和事件資料

848 

849匯出的指標和事件支援一系列分析:

850 

851### 使用情況監控

852 

853| 指標 | 分析機會 |

854| ------------------------------------------------------------- | ----------------------------- |

855| `claude_code.token.usage` | 按 `type`(輸入/輸出)、使用者、團隊或模型進行細分 |

856| `claude_code.session.count` | 追蹤一段時間內的採用和參與度 |

857| `claude_code.lines_of_code.count` | 透過追蹤程式碼新增/移除來衡量生產力 |

858| `claude_code.commit.count` & `claude_code.pull_request.count` | 了解對開發工作流程的影響 |

859 

860### 成本監控

861 

862`claude_code.cost.usage` 指標有助於:

863 

864* 追蹤跨團隊或個人的使用趨勢

865* 識別高使用量工作階段以進行最佳化

866 

867<Note>

868 成本指標是近似值。如需官方帳單資料,請參閱您的 API 提供者(Claude Console、Amazon Bedrock 或 Google Cloud Vertex)。

869</Note>

870 

871### 警報和分段

872 

873要考慮的常見警報:

874 

875* 成本尖峰

876* 異常的權杖消耗

877* 來自特定使用者的高工作階段量

878 

879所有指標都可以按 `user.account_uuid`、`user.account_id`、`organization.id`、`session.id`、`model` 和 `app.version` 進行分段。

880 

881### 偵測重試耗盡

882 

883Claude Code 在內部重試失敗的 API 請求,並僅在放棄後才發出單個 `claude_code.api_error` 事件,因此事件本身是該請求的終端訊號。中間重試嘗試不會作為單獨的事件記錄。

884 

885事件上的 `attempt` 屬性記錄進行的嘗試總次數。大於 `CLAUDE_CODE_MAX_RETRIES`(預設 `10`)的值表示請求在暫時性錯誤上耗盡了所有重試。較低的值表示不可重試的錯誤,例如 `400` 回應。

886 

887若要區分從一個恢復的工作階段與停滯的工作階段,請按 `session.id` 分組事件,並檢查錯誤後是否存在更晚的 `api_request` 事件。

888 

889### 事件分析

890 

891事件資料提供了對 Claude Code 互動的詳細見解:

892 

893**工具使用模式**:分析工具結果事件以識別:

894 

895* 最常使用的工具

896* 工具成功率

897* 平均工具執行時間

898* 按工具類型的錯誤模式

899 

900**效能監控**:追蹤 API 請求持續時間和工具執行時間以識別效能瓶頸。

901 

902## 後端考量

903 

904您選擇的指標、日誌和追蹤後端決定了您可以執行的分析類型:

905 

906### 對於指標

907 

908* **時間序列資料庫(例如,Prometheus)**:速率計算、聚合指標

909* **欄式存儲(例如,ClickHouse)**:複雜查詢、唯一使用者分析

910* **功能完整的可觀測性平台(例如,Honeycomb、Datadog)**:進階查詢、視覺化、警報

911 

912### 對於事件/日誌

913 

914* **日誌聚合系統(例如,Elasticsearch、Loki)**:全文搜尋、日誌分析

915* **欄式存儲(例如,ClickHouse)**:結構化事件分析

916* **功能完整的可觀測性平台(例如,Honeycomb、Datadog)**:指標和事件之間的關聯

917 

918### 對於追蹤

919 

920選擇支援分散式追蹤儲存和跨度關聯的後端:

921 

922* **分散式追蹤系統(例如,Jaeger、Zipkin、Grafana Tempo)**:跨度視覺化、請求瀑布圖、延遲分析

923* **功能完整的可觀測性平台(例如,Honeycomb、Datadog)**:追蹤搜尋和與指標和日誌的關聯

924 

925對於需要日活躍使用者/週活躍使用者/月活躍使用者 (DAU/WAU/MAU) 指標的組織,請考慮支援高效唯一值查詢的後端。

926 

927## 服務資訊

928 

929所有指標和事件都使用以下資源屬性匯出:

930 

931* `service.name`:`claude-code`

932* `service.version`:目前的 Claude Code 版本

933* `os.type`:作業系統類型(例如,`linux`、`darwin`、`windows`)

934* `os.version`:作業系統版本字串

935* `host.arch`:主機架構(例如,`amd64`、`arm64`)

936* `wsl.version`:WSL 版本號(僅在 Windows Subsystem for Linux 上執行時出現)

937* 計量器名稱:`com.anthropic.claude_code`

938 

939## ROI 測量資源

940 

941如需有關測量 Claude Code 投資回報率的綜合指南,包括遙測設定、成本分析、生產力指標和自動化報告,請參閱 [Claude Code ROI 測量指南](https://github.com/anthropics/claude-code-monitoring-guide)。此儲存庫提供現成可用的 Docker Compose 配置、Prometheus 和 OpenTelemetry 設定,以及用於產生與 Linear 等工具整合的生產力報告的範本。

942 

943## 安全性和隱私

944 

945* OpenTelemetry 匯出到您的後端是選擇加入的,需要明確配置。如需了解 Anthropic 的獨立營運遙測以及如何停用它,請參閱[資料使用](/zh-TW/data-usage#telemetry-services)

946* 原始檔案內容和程式碼片段不包含在指標或事件中。追蹤跨度是單獨的資料路徑:請參閱下面的 `OTEL_LOG_TOOL_CONTENT` 項目

947* 透過 OAuth 驗證時,`user.email` 包含在遙測屬性中。如果這對您的組織是個問題,請與您的遙測後端合作以篩選或編輯此欄位

948* 預設不收集使用者提示內容。僅記錄提示長度。若要包含提示內容,請設定 `OTEL_LOG_USER_PROMPTS=1`

949* 工具輸入引數和參數預設不記錄。若要包含它們,請設定 `OTEL_LOG_TOOL_DETAILS=1`。啟用時,`tool_result` 事件包含 `tool_parameters` 屬性,其中包含 Bash 命令、MCP 伺服器和工具名稱以及技能名稱,以及包含檔案路徑、URL、搜尋模式和其他引數的 `tool_input` 屬性。`user_prompt` 事件包含自訂、plugin 和 MCP 命令的逐字 `command_name`。追蹤跨度包含相同的 `tool_input` 屬性和輸入衍生屬性,例如 `file_path`。超過 512 個字元的個別值會被截斷,總計上限約為 4 K 字元,但引數仍可能包含敏感值。根據需要配置您的遙測後端以篩選或編輯這些屬性

950* 工具輸入和輸出內容預設不在追蹤跨度中記錄。若要包含它,請設定 `OTEL_LOG_TOOL_CONTENT=1`。啟用時,跨度事件包含完整工具輸入和輸出內容,在每個跨度處截斷 60 KB。這可以包含來自 Read 工具結果的原始檔案內容和 Bash 命令輸出。根據需要配置您的遙測後端以篩選或編輯這些屬性

951* 原始 Anthropic Messages API 請求和回應主體預設不記錄。若要包含它們,請設定 `OTEL_LOG_RAW_API_BODIES`。使用 `=1` 時,每個 API 呼叫發出 `api_request_body` 和 `api_response_body` 日誌事件,其 `body` 屬性是 JSON 序列化的承載,在 60 KB 處截斷。使用 `=file:<dir>` 時,未截斷的主體寫入該目錄下的 `.request.json` 和 `.response.json` 檔案,事件帶有 `body_ref` 路徑而不是內聯主體。使用日誌收集器或邊車傳送目錄,而不是透過遙測流。在兩種模式中,主體包含完整的對話歷史記錄(系統提示、每個先前的使用者和助手輪次、工具結果),因此啟用此選項意味著同意其他 `OTEL_LOG_*` 內容旗標會揭露的所有內容。Claude 的擴展思考內容始終從這些主體中編輯,無論其他設定如何

952 

953## 在 Amazon Bedrock 上監控 Claude Code

954 

955如需 Amazon Bedrock 上 Claude Code 使用情況監控的詳細指南,請參閱 [Claude Code 監控實作 (Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md)。

network-config.md +132 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 企業網路設定

6 

7> 為企業環境設定 Claude Code,包括代理伺服器、自訂憑證授權單位 (CA) 和相互傳輸層安全性 (mTLS) 驗證。

8 

9Claude Code 透過環境變數支援各種企業網路和安全設定。這包括透過公司代理伺服器路由流量、信任自訂憑證授權單位 (CA),以及使用相互傳輸層安全性 (mTLS) 憑證進行驗證以增強安全性。

10 

11<Note>

12 本頁面顯示的所有環境變數也可以在 [`settings.json`](/zh-TW/settings) 中設定。

13</Note>

14 

15## 代理設定

16 

17### 環境變數

18 

19Claude Code 遵守標準代理環境變數:

20 

21```bash theme={null}

22# HTTPS 代理(建議)

23export HTTPS_PROXY=https://proxy.example.com:8080

24 

25# HTTP 代理(如果 HTTPS 不可用)

26export HTTP_PROXY=http://proxy.example.com:8080

27 

28# 略過特定請求的代理 - 空格分隔格式

29export NO_PROXY="localhost 192.168.1.1 example.com .example.com"

30# 略過特定請求的代理 - 逗號分隔格式

31export NO_PROXY="localhost,192.168.1.1,example.com,.example.com"

32# 略過所有請求的代理

33export NO_PROXY="*"

34```

35 

36<Note>

37 Claude Code 不支援 SOCKS 代理。

38</Note>

39 

40### 基本驗證

41 

42如果您的代理需要基本驗證,請在代理 URL 中包含認證資訊:

43 

44```bash theme={null}

45export HTTPS_PROXY=http://username:password@proxy.example.com:8080

46```

47 

48<Warning>

49 避免在指令碼中硬編碼密碼。改用環境變數或安全認證儲存。

50</Warning>

51 

52<Tip>

53 對於需要進階驗證(NTLM、Kerberos 等)的代理,請考慮使用支援您驗證方法的 LLM Gateway 服務。

54</Tip>

55 

56## CA 憑證存放區

57 

58根據預設,Claude Code 信任其捆綁的 Mozilla CA 憑證和您作業系統的憑證存放區。企業 TLS 檢查代理(例如 CrowdStrike Falcon 和 Zscaler)在其根憑證安裝在作業系統信任存放區中時無需額外設定即可運作。

59 

60<Note>

61 系統 CA 存放區整合需要原生 Claude Code 二進位分發。在 Node.js 執行時上執行時,系統 CA 存放區不會自動合併。在這種情況下,設定 `NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem` 以信任企業根 CA。

62</Note>

63 

64`CLAUDE_CODE_CERT_STORE` 接受以逗號分隔的來源清單。認可的值為 `bundled`(Claude Code 隨附的 Mozilla CA 集合)和 `system`(作業系統信任存放區)。預設值為 `bundled,system`。

65 

66若只信任捆綁的 Mozilla CA 集合:

67 

68```bash theme={null}

69export CLAUDE_CODE_CERT_STORE=bundled

70```

71 

72若只信任作業系統憑證存放區:

73 

74```bash theme={null}

75export CLAUDE_CODE_CERT_STORE=system

76```

77 

78<Note>

79 `CLAUDE_CODE_CERT_STORE` 在 `settings.json` 中沒有專用的架構金鑰。透過 `~/.claude/settings.json` 中的 `env` 區塊或直接在程序環境中設定。

80</Note>

81 

82## 自訂 CA 憑證

83 

84如果您的企業環境使用自訂 CA,請設定 Claude Code 以直接信任它:

85 

86```bash theme={null}

87export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem

88```

89 

90## mTLS 驗證

91 

92對於需要用戶端憑證驗證的企業環境:

93 

94```bash theme={null}

95# 用於驗證的用戶端憑證

96export CLAUDE_CODE_CLIENT_CERT=/path/to/client-cert.pem

97 

98# 用戶端私密金鑰

99export CLAUDE_CODE_CLIENT_KEY=/path/to/client-key.pem

100 

101# 選用:加密私密金鑰的密碼

102export CLAUDE_CODE_CLIENT_KEY_PASSPHRASE="your-passphrase"

103```

104 

105## 網路存取需求

106 

107Claude Code 需要存取以下 URL。請在您的代理設定和防火牆規則中將這些 URL 列入允許清單,特別是在容器化或受限網路環境中。

108 

109| URL | 用途 |

110| ------------------------------ | -------------------------------------------------------- |

111| `api.anthropic.com` | Claude API 請求 |

112| `claude.ai` | claude.ai 帳戶驗證 |

113| `platform.claude.com` | Anthropic Console 帳戶驗證 |

114| `downloads.claude.ai` | 外掛程式可執行檔下載;原生安裝程式和原生自動更新程式 |

115| `storage.googleapis.com` | {/* max-version: 2.1.115 */}2.1.116 版本之前的原生安裝程式和原生自動更新程式 |

116| `bridge.claudeusercontent.com` | [Chrome 中的 Claude](/zh-TW/chrome) 擴充功能 WebSocket 橋接器 |

117 

118如果您透過 npm 安裝 Claude Code 或管理自己的二進位分發,終端使用者可能不需要存取 `downloads.claude.ai` 或 `storage.googleapis.com`。

119 

120Claude Code 預設也會傳送選用的操作遙測,您可以使用環境變數停用此功能。請參閱[遙測服務](/zh-TW/data-usage#telemetry-services)以了解如何在完成允許清單之前停用它。

121 

122使用 [Amazon Bedrock](/zh-TW/amazon-bedrock)、[Google Vertex AI](/zh-TW/google-vertex-ai) 或 [Microsoft Foundry](/zh-TW/microsoft-foundry) 時,模型流量和驗證會傳送到您的提供者,而不是 `api.anthropic.com`、`claude.ai` 或 `platform.claude.com`。WebFetch 工具仍會呼叫 `api.anthropic.com` 進行其[網域安全檢查](/zh-TW/data-usage#webfetch-domain-safety-check),除非您在[設定](/zh-TW/settings)中設定 `skipWebFetchPreflight: true`。

123 

124[Claude Code on the web](/zh-TW/claude-code-on-the-web) 和 [Code Review](/zh-TW/code-review) 從 Anthropic 管理的基礎設施連線到您的儲存庫。如果您的 GitHub Enterprise Cloud 組織按 IP 位址限制存取,請啟用[已安裝 GitHub Apps 的 IP 允許清單繼承](https://docs.github.com/en/enterprise-cloud@latest/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/managing-allowed-ip-addresses-for-your-organization#allowing-access-by-github-apps)。Claude GitHub App 會註冊其 IP 範圍,因此啟用此設定可允許存取而無需手動設定。若要[手動將範圍新增到允許清單](https://docs.github.com/en/enterprise-cloud@latest/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/managing-allowed-ip-addresses-for-your-organization#adding-an-allowed-ip-address),或設定其他防火牆,請參閱 [Anthropic API IP 位址](https://platform.claude.com/docs/en/api/ip-addresses)。

125 

126對於防火牆後的自託管 [GitHub Enterprise Server](/zh-TW/github-enterprise-server) 執行個體,請將相同的 [Anthropic API IP 位址](https://platform.claude.com/docs/en/api/ip-addresses) 列入允許清單,以便 Anthropic 基礎設施可以連線到您的 GHES 主機以複製儲存庫並發佈審查評論。

127 

128## 其他資源

129 

130* [Claude Code 設定](/zh-TW/settings)

131* [環境變數參考](/zh-TW/env-vars)

132* [疑難排解指南](/zh-TW/troubleshooting)

output-styles.md +90 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 輸出樣式

6 

7> 將 Claude Code 適配用於軟體工程以外的用途

8 

9輸出樣式允許您將 Claude Code 用作任何類型的代理,同時保留其核心功能,例如執行本地指令碼、讀取/寫入檔案和追蹤待辦事項。

10 

11## 內建輸出樣式

12 

13Claude Code 的**預設**輸出樣式是現有的系統提示,旨在幫助您有效地完成軟體工程任務。

14 

15還有兩種額外的內建輸出樣式,專注於教您了解程式碼庫和 Claude 的運作方式:

16 

17* **Explanatory**:在幫助您完成軟體工程任務的同時提供教育性的「Insights」。幫助您理解實現選擇和程式碼庫模式。

18 

19* **Learning**:協作式的邊做邊學模式,Claude 不僅會在編碼時分享「Insights」,還會要求您自己貢獻小的、策略性的程式碼片段。Claude Code 將在您的程式碼中添加 `TODO(human)` 標記供您實現。

20 

21## 輸出樣式的工作原理

22 

23輸出樣式直接修改 Claude Code 的系統提示。

24 

25* 自訂輸出樣式排除了編碼指令(例如使用測試驗證程式碼),除非 `keep-coding-instructions` 為真。

26* 所有輸出樣式都在系統提示的末尾添加了自己的自訂指令。

27* 所有輸出樣式都會在對話期間觸發提醒,讓 Claude 遵守輸出樣式指令。

28 

29Token 使用量取決於樣式。將指令添加到系統提示會增加輸入 token,儘管 prompt caching 在工作階段中的第一個請求之後會降低此成本。內建的 Explanatory 和 Learning 樣式按設計會產生比預設更長的回應,這會增加輸出 token。對於自訂樣式,輸出 token 使用量取決於您的指令告訴 Claude 要產生什麼。

30 

31## 變更您的輸出樣式

32 

33執行 `/config` 並選擇**輸出樣式**以從選單中選擇樣式。您的選擇會儲存到[本地專案層級](/zh-TW/settings)的 `.claude/settings.local.json`。

34 

35若要在不使用選單的情況下設定樣式,請直接編輯設定檔中的 `outputStyle` 欄位:

36 

37```json theme={null}

38{

39 "outputStyle": "Explanatory"

40}

41```

42 

43由於輸出樣式是在工作階段開始時在系統提示中設定的,變更將在您下次啟動新工作階段時生效。這使系統提示在整個對話中保持穩定,以便 prompt caching 可以降低延遲和成本。

44 

45## 建立自訂輸出樣式

46 

47自訂輸出樣式是具有 frontmatter 和將添加到系統提示的文字的 Markdown 檔案:

48 

49```markdown theme={null}

50---

51name: My Custom Style

52description:

53 A brief description of what this style does, to be displayed to the user

54---

55 

56# Custom Style Instructions

57 

58You are an interactive CLI tool that helps users with software engineering

59tasks. [Your custom instructions here...]

60 

61## Specific Behaviors

62 

63[Define how the assistant should behave in this style...]

64```

65 

66您可以在使用者層級 (`~/.claude/output-styles`) 或專案層級 (`.claude/output-styles`) 儲存這些檔案。

67 

68### Frontmatter

69 

70輸出樣式檔案支援 frontmatter 以指定中繼資料:

71 

72| Frontmatter | 用途 | 預設 |

73| :------------------------- | :------------------------------ | :------ |

74| `name` | 輸出樣式的名稱,如果不是檔案名稱 | 繼承自檔案名稱 |

75| `description` | 輸出樣式的描述,在 `/config` 選擇器中顯示 | 無 |

76| `keep-coding-instructions` | 是否保留 Claude Code 系統提示中與編碼相關的部分。 | false |

77 

78## 與相關功能的比較

79 

80### 輸出樣式 vs. CLAUDE.md vs. --append-system-prompt

81 

82輸出樣式完全「關閉」Claude Code 預設系統提示中特定於軟體工程的部分。CLAUDE.md 和 `--append-system-prompt` 都不會編輯 Claude Code 的預設系統提示。CLAUDE.md 將內容添加為 Claude Code 預設系統提示\_之後\_的使用者訊息。`--append-system-prompt` 將內容附加到系統提示。

83 

84### 輸出樣式 vs. [Agents](/zh-TW/sub-agents)

85 

86輸出樣式直接影響主代理迴圈,僅影響系統提示。Agents 被呼叫以處理特定任務,可以包括其他設定,例如要使用的模型、可用的工具以及有關何時使用代理的一些上下文。

87 

88### 輸出樣式 vs. [Skills](/zh-TW/skills)

89 

90輸出樣式修改 Claude 的回應方式(格式、語氣、結構),一旦選擇就始終處於活動狀態。Skills 是特定於任務的提示,您可以使用 `/skill-name` 呼叫或 Claude 在相關時自動載入。使用輸出樣式來實現一致的格式設定偏好;使用 skills 來實現可重複使用的工作流程和任務。

overview.md +875 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Claude Code 概述

6 

7> Claude Code 是一個代理編碼工具,可以讀取您的程式碼庫、編輯檔案、執行命令,並與您的開發工具整合。可在您的終端機、IDE、桌面應用程式和瀏覽器中使用。

8 

9export const InstallConfigurator = ({defaultSurface = 'terminal'}) => {

10 const TERM = {

11 mac: {

12 label: 'macOS / Linux',

13 cmd: 'curl -fsSL https://claude.ai/install.sh | bash'

14 },

15 win: {

16 label: 'Windows'

17 },

18 brew: {

19 label: 'Homebrew',

20 cmd: 'brew install --cask claude-code'

21 },

22 winget: {

23 label: 'WinGet',

24 cmd: 'winget install Anthropic.ClaudeCode'

25 }

26 };

27 const WIN_VARIANTS = {

28 ps: 'irm https://claude.ai/install.ps1 | iex',

29 cmd: 'curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd'

30 };

31 const TABS = [{

32 key: 'terminal',

33 label: 'Terminal'

34 }, {

35 key: 'desktop',

36 label: 'Desktop'

37 }, {

38 key: 'vscode',

39 label: 'VS Code'

40 }, {

41 key: 'jetbrains',

42 label: 'JetBrains'

43 }];

44 const ALT_TARGETS = {

45 desktop: {

46 name: 'Desktop',

47 tagline: 'The full agent in a native app for macOS and Windows.',

48 installLabel: 'Download the app',

49 installHref: 'https://claude.com/download?utm_source=claude_code&utm_medium=docs&utm_content=configurator_desktop_download',

50 guideHref: '/en/desktop-quickstart'

51 },

52 vscode: {

53 name: 'VS Code',

54 tagline: 'Review diffs, manage context, and chat without leaving your editor.',

55 installLabel: 'Install from Marketplace',

56 installHref: 'https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code',

57 altCmd: 'code --install-extension anthropic.claude-code',

58 guideHref: '/en/vs-code'

59 },

60 jetbrains: {

61 name: 'JetBrains',

62 tagline: 'Native plugin for IntelliJ, PyCharm, WebStorm, and other JetBrains IDEs.',

63 installLabel: 'Install from Marketplace',

64 installHref: 'https://plugins.jetbrains.com/plugin/27310-claude-code-beta-',

65 guideHref: '/en/jetbrains'

66 }

67 };

68 const PROVIDERS = [{

69 key: 'anthropic',

70 label: 'Anthropic'

71 }, {

72 key: 'bedrock',

73 label: 'Amazon Bedrock'

74 }, {

75 key: 'foundry',

76 label: 'Microsoft Foundry'

77 }, {

78 key: 'vertex',

79 label: 'Google Vertex AI'

80 }];

81 const PROVIDER_NOTICE = {

82 bedrock: <>

83 <strong>Configure your AWS account first.</strong> Running on Bedrock

84 requires model access enabled in the AWS console and IAM credentials.{' '}

85 <a href="/en/amazon-bedrock">Bedrock setup guide →</a>

86 </>,

87 vertex: <>

88 <strong>Configure your GCP project first.</strong> Running on Vertex AI

89 requires the Vertex API enabled and a service account with the right

90 permissions.{' '}

91 <a href="/en/google-vertex-ai">Vertex setup guide →</a>

92 </>,

93 foundry: <>

94 <strong>Configure your Azure resources first.</strong> Running on

95 Microsoft Foundry requires an Azure subscription with a Foundry resource

96 and model deployments provisioned.{' '}

97 <a href="/en/microsoft-foundry">Foundry setup guide →</a>

98 </>

99 };

100 const iconCheck = (size = 14) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

101 <polyline points="20 6 9 17 4 12" />

102 </svg>;

103 const iconCopy = (size = 14) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

104 <rect x="9" y="9" width="13" height="13" rx="2" />

105 <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />

106 </svg>;

107 const iconArrowRight = (size = 13) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

108 <line x1="5" y1="12" x2="19" y2="12" />

109 <polyline points="12 5 19 12 12 19" />

110 </svg>;

111 const iconArrowUpRight = (size = 14) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

112 <line x1="7" y1="17" x2="17" y2="7" />

113 <polyline points="7 7 17 7 17 17" />

114 </svg>;

115 const iconInfo = (size = 16) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

116 <circle cx="12" cy="12" r="10" />

117 <line x1="12" y1="16" x2="12" y2="12" />

118 <line x1="12" y1="8" x2="12.01" y2="8" />

119 </svg>;

120 const [target, setTarget] = useState(defaultSurface);

121 const [team, setTeam] = useState(false);

122 const [provider, setProvider] = useState('anthropic');

123 const [pkg, setPkg] = useState(() => (/Win/).test(navigator.userAgent) ? 'win' : 'mac');

124 const [winCmd, setWinCmd] = useState(false);

125 const [copied, setCopied] = useState(null);

126 const copyTimer = useRef(null);

127 const handleCopy = async (text, key) => {

128 try {

129 await navigator.clipboard.writeText(text);

130 } catch {

131 const ta = document.createElement('textarea');

132 ta.value = text;

133 document.body.appendChild(ta);

134 ta.select();

135 document.execCommand('copy');

136 document.body.removeChild(ta);

137 }

138 clearTimeout(copyTimer.current);

139 setCopied(key);

140 copyTimer.current = setTimeout(() => setCopied(null), 1800);

141 };

142 const cardBodyCmd = (cmd, prompt) => {

143 const on = copied === 'term';

144 return <div className="cc-ic-card-body">

145 <span className="cc-ic-prompt">{prompt || '$'}</span>

146 <div className="cc-ic-cmd">{cmd}</div>

147 <button type="button" className={'cc-ic-copy' + (on ? ' cc-ic-copied' : '')} onClick={() => handleCopy(cmd, 'term')}>

148 {on ? iconCheck(13) : iconCopy(13)}

149 <span>{on ? 'Copied' : 'Copy'}</span>

150 </button>

151 </div>;

152 };

153 const isWinInstaller = pkg === 'win';

154 const isWinPrompt = pkg === 'win' || pkg === 'winget';

155 const terminalCmd = isWinInstaller ? WIN_VARIANTS[winCmd ? 'cmd' : 'ps'] : TERM[pkg].cmd;

156 const alt = ALT_TARGETS[target];

157 const showNotice = team && provider !== 'anthropic';

158 const STYLES = `

159.cc-ic {

160 --ic-slate: #141413;

161 --ic-clay: #d97757;

162 --ic-clay-deep: #c6613f;

163 --ic-gray-000: #ffffff;

164 --ic-gray-150: #f0eee6;

165 --ic-gray-550: #73726c;

166 --ic-gray-700: #3d3d3a;

167 --ic-border-subtle: rgba(31, 30, 29, 0.08);

168 --ic-border-default: rgba(31, 30, 29, 0.15);

169 --ic-border-strong: rgba(31, 30, 29, 0.3);

170 --ic-font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, 'Courier New', monospace;

171 font-family: 'Anthropic Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;

172 font-size: 14px; line-height: 1.5; color: var(--ic-slate);

173 margin: 8px 0 32px;

174}

175.dark .cc-ic {

176 --ic-slate: #f0eee6;

177 --ic-gray-000: #262624;

178 --ic-gray-150: #1f1e1d;

179 --ic-gray-550: #91908a;

180 --ic-gray-700: #bfbdb4;

181 --ic-border-subtle: rgba(240, 238, 230, 0.08);

182 --ic-border-default: rgba(240, 238, 230, 0.14);

183 --ic-border-strong: rgba(240, 238, 230, 0.28);

184}

185.dark .cc-ic-check { background: transparent; }

186.dark .cc-ic-card { border: 0.5px solid var(--ic-border-subtle); }

187.dark .cc-ic-p-pill.cc-ic-active { box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); }

188.cc-ic *, .cc-ic *::before, .cc-ic *::after { box-sizing: border-box; }

189.cc-ic a { text-decoration: none; }

190.cc-ic a:not([class]) { color: inherit; }

191.cc-ic button { font-family: inherit; cursor: pointer; }

192 

193.cc-ic-tab-strip {

194 display: inline-flex; gap: 2px;

195 padding: 4px; background: var(--ic-gray-150);

196 border-radius: 10px; overflow-x: auto;

197 max-width: 100%;

198}

199.cc-ic-tab {

200 appearance: none; background: none; border: none;

201 padding: 10px 18px; font-size: 15px; font-weight: 430;

202 color: var(--ic-gray-550); border-radius: 7px;

203 white-space: nowrap;

204 transition: color 0.12s, background-color 0.12s;

205}

206.cc-ic-tab:hover { color: var(--ic-gray-700); }

207.cc-ic-tab.cc-ic-active {

208 color: var(--ic-slate); font-weight: 500;

209 background: var(--ic-gray-000);

210 box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);

211}

212.dark .cc-ic-tab.cc-ic-active { box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4); }

213 

214.cc-ic-team-wrap { padding: 16px 0 20px; }

215.cc-ic-team-toggle {

216 display: flex; align-items: center; gap: 12px; font-family: inherit;

217 padding: 12px 16px; font-size: 14px; font-weight: 430;

218 color: var(--ic-gray-700); cursor: pointer; user-select: none;

219 width: fit-content; background: var(--ic-gray-150);

220 border: 0.5px solid var(--ic-border-subtle); border-radius: 8px;

221 transition: border-color 0.15s;

222}

223.cc-ic-team-toggle:hover { border-color: var(--ic-border-default); }

224.cc-ic-team-toggle.cc-ic-checked {

225 background: rgba(217, 119, 87, 0.08);

226 border-color: rgba(217, 119, 87, 0.25);

227}

228.cc-ic-check {

229 width: 16px; height: 16px;

230 border: 1px solid var(--ic-border-strong); border-radius: 4px;

231 background: var(--ic-gray-000);

232 display: flex; align-items: center; justify-content: center;

233 flex-shrink: 0;

234}

235.cc-ic-check svg { color: #fff; display: none; }

236.cc-ic-team-toggle.cc-ic-checked .cc-ic-check { background: var(--ic-clay-deep); border-color: var(--ic-clay-deep); }

237.cc-ic-team-toggle.cc-ic-checked .cc-ic-check svg { display: block; }

238 

239.cc-ic-team-reveal { display: flex; flex-direction: column; gap: 12px; margin-bottom: 16px; }

240.cc-ic-sales {

241 display: flex; align-items: center; justify-content: space-between;

242 gap: 16px; padding: 14px 16px;

243 background: var(--ic-gray-000); border: 0.5px solid var(--ic-border-default);

244 border-radius: 8px; flex-wrap: wrap;

245}

246.cc-ic-sales-text { font-size: 13px; color: var(--ic-gray-700); line-height: 1.5; flex: 1; min-width: 200px; }

247.cc-ic-sales-text strong { font-weight: 550; color: var(--ic-slate); }

248.cc-ic-sales-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }

249.cc-ic-btn-clay {

250 display: inline-flex; align-items: center; gap: 8px;

251 background: var(--ic-clay-deep); color: #fff; border: none;

252 border-radius: 8px; padding: 8px 14px;

253 font-size: 13px; font-weight: 500;

254 transition: background-color 0.15s; white-space: nowrap;

255}

256.cc-ic-btn-clay:hover { background: var(--ic-clay); }

257.cc-ic-btn-ghost {

258 display: inline-flex; align-items: center; gap: 8px;

259 background: transparent; color: var(--ic-gray-700);

260 border: 0.5px solid var(--ic-border-default);

261 border-radius: 8px; padding: 8px 14px;

262 font-size: 13px; font-weight: 500;

263}

264.cc-ic-btn-ghost:hover { background: rgba(0, 0, 0, 0.04); }

265 

266.cc-ic-provider-bar {

267 display: flex; align-items: center; gap: 12px;

268 padding: 14px 16px; background: var(--ic-gray-150);

269 border-radius: 8px; font-size: 13px; flex-wrap: wrap;

270}

271.cc-ic-provider-bar .cc-ic-label { color: var(--ic-gray-550); flex-shrink: 0; }

272.cc-ic-provider-pills { display: flex; gap: 4px; flex-wrap: wrap; }

273.cc-ic-p-pill {

274 appearance: none; border: none; background: transparent;

275 padding: 6px 12px; border-radius: 6px;

276 font-size: 13px; font-weight: 430; color: var(--ic-gray-700);

277 white-space: nowrap;

278}

279.cc-ic-p-pill:hover { background: rgba(0, 0, 0, 0.04); }

280.cc-ic-p-pill.cc-ic-active {

281 background: var(--ic-gray-000); color: var(--ic-slate);

282 font-weight: 500; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

283}

284.cc-ic-provider-notice {

285 display: flex; padding: 16px 18px;

286 background: var(--ic-gray-000); border: 0.5px solid var(--ic-border-default);

287 border-radius: 8px; gap: 14px; align-items: flex-start;

288}

289.cc-ic-provider-notice > svg { color: var(--ic-gray-550); margin-top: 2px; flex-shrink: 0; }

290.cc-ic-provider-notice-body { font-size: 14px; line-height: 1.55; color: var(--ic-gray-700); }

291.cc-ic-provider-notice-body strong { font-weight: 550; color: var(--ic-slate); }

292.cc-ic-provider-notice-body a { color: var(--ic-clay-deep); font-weight: 500; }

293.cc-ic-provider-notice-body a:hover { text-decoration: underline; }

294 

295.cc-ic-card { background: #141413; border-radius: 12px; overflow: hidden; }

296.cc-ic-subtabs {

297 display: flex; align-items: center;

298 background: #1a1918;

299 border-bottom: 0.5px solid rgba(255, 255, 255, 0.08);

300 padding: 0 8px; overflow-x: auto;

301}

302.cc-ic-subtab {

303 appearance: none; background: none; border: none;

304 padding: 12px 16px; font-size: 12px;

305 color: rgba(255, 255, 255, 0.5);

306 position: relative; white-space: nowrap;

307}

308.cc-ic-subtab:hover { color: rgba(255, 255, 255, 0.75); }

309.cc-ic-subtab.cc-ic-active { color: #fff; }

310.cc-ic-subtab.cc-ic-active::after {

311 content: ''; position: absolute;

312 left: 12px; right: 12px; bottom: -0.5px;

313 height: 2px; background: var(--ic-clay);

314}

315.cc-ic-shell-switch {

316 display: inline-flex; gap: 2px;

317 margin: 14px 26px 0; padding: 3px;

318 background: rgba(255, 255, 255, 0.06);

319 border: 0.5px solid rgba(255, 255, 255, 0.08);

320 border-radius: 8px;

321 font-family: inherit;

322}

323.cc-ic-shell-option {

324 font: inherit; font-size: 12px; font-weight: 500;

325 padding: 5px 12px; border-radius: 6px;

326 background: transparent; border: none;

327 color: rgba(255, 255, 255, 0.55);

328 cursor: pointer; user-select: none; white-space: nowrap;

329 transition: color 120ms ease, background-color 120ms ease;

330}

331.cc-ic-shell-option:hover { color: rgba(255, 255, 255, 0.85); }

332.cc-ic-shell-option.cc-ic-active {

333 background: rgba(255, 255, 255, 0.12);

334 color: #fff;

335 box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);

336}

337 

338.cc-ic-card-body { padding: 24px 26px; display: flex; align-items: flex-start; gap: 14px; }

339.cc-ic-prompt {

340 color: var(--ic-clay); font-family: var(--ic-font-mono);

341 font-size: 17px; user-select: none; padding-top: 2px;

342}

343.cc-ic-cmd {

344 flex: 1; font-family: var(--ic-font-mono);

345 font-size: 17px; color: #f0eee6;

346 line-height: 1.55; white-space: pre-wrap; word-break: break-word;

347}

348.cc-ic-copy {

349 display: inline-flex; align-items: center; gap: 6px;

350 background: rgba(255, 255, 255, 0.08);

351 border: 0.5px solid rgba(255, 255, 255, 0.12);

352 color: rgba(255, 255, 255, 0.85);

353 padding: 7px 13px; border-radius: 8px;

354 font-size: 13px; font-weight: 500; flex-shrink: 0;

355}

356.cc-ic-copy:hover { background: rgba(255, 255, 255, 0.14); }

357.cc-ic-copy.cc-ic-copied { background: var(--ic-clay-deep); border-color: var(--ic-clay-deep); color: #fff; }

358 

359.cc-ic-below {

360 margin-top: 12px; font-size: 13px; color: var(--ic-gray-550);

361 display: flex; gap: 16px; flex-wrap: wrap; align-items: baseline;

362}

363.cc-ic-below a { color: var(--ic-gray-700); border-bottom: 0.5px solid var(--ic-border-default); }

364.cc-ic-below a:hover { color: var(--ic-clay-deep); border-bottom-color: var(--ic-clay-deep); }

365.cc-ic-handoff {

366 padding: 22px 24px;

367 background: linear-gradient(180deg, #faf9f4 0%, #f3f1e9 100%);

368 border: 0.5px solid var(--ic-border-default);

369 border-radius: 12px;

370 box-shadow: 0 1px 2px rgba(31, 30, 29, 0.04), 0 6px 16px -4px rgba(31, 30, 29, 0.06);

371}

372.dark .cc-ic-handoff {

373 background: linear-gradient(180deg, #262624 0%, #1f1e1d 100%);

374 box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3), 0 6px 16px -4px rgba(0, 0, 0, 0.4);

375}

376.cc-ic-handoff-title {

377 font-size: 16px; font-weight: 550; color: var(--ic-slate);

378 letter-spacing: -0.01em; margin-bottom: 4px;

379}

380.cc-ic-handoff-sub {

381 font-size: 14px; line-height: 1.5; color: var(--ic-gray-700);

382 margin-bottom: 18px;

383}

384.cc-ic-handoff-actions { display: flex; gap: 10px; flex-wrap: wrap; }

385.cc-ic-handoff-alt {

386 margin-top: 12px; font-size: 12px; color: var(--ic-gray-550);

387}

388.cc-ic-handoff-alt code {

389 font-family: var(--ic-font-mono); font-size: 11px;

390 background: var(--ic-gray-150); padding: 2px 6px;

391 border-radius: 4px; color: var(--ic-gray-700);

392}

393.cc-ic-copy-sm {

394 appearance: none; border: none;

395 display: inline-flex; align-items: center; justify-content: center;

396 width: 22px; height: 22px;

397 margin-left: 4px; vertical-align: middle;

398 background: var(--ic-gray-150); color: var(--ic-gray-550);

399 border-radius: 4px;

400 transition: color 0.1s, background-color 0.1s;

401}

402.cc-ic-copy-sm:hover { color: var(--ic-gray-700); background: var(--ic-border-default); }

403.cc-ic-copy-sm.cc-ic-copied { background: var(--ic-clay-deep); color: #fff; }

404 

405@media (max-width: 720px) {

406 .cc-ic-tab { padding: 12px 14px; font-size: 14px; }

407 .cc-ic-sales-actions { width: 100%; }

408 .cc-ic-card-body { padding: 20px; }

409 .cc-ic-cmd { font-size: 15px; }

410}

411`;

412 return <div className="cc-ic not-prose">

413 <style>{STYLES}</style>

414 

415 {}

416 <div className="cc-ic-tab-strip" role="tablist">

417 {TABS.map(t => <button key={t.key} type="button" role="tab" aria-selected={target === t.key} className={'cc-ic-tab' + (target === t.key ? ' cc-ic-active' : '')} onClick={() => setTarget(t.key)}>

418 {t.label}

419 </button>)}

420 </div>

421 

422 {}

423 <div className="cc-ic-team-wrap">

424 <button type="button" role="switch" aria-checked={team} className={'cc-ic-team-toggle' + (team ? ' cc-ic-checked' : '')} onClick={() => setTeam(!team)}>

425 <span className="cc-ic-check">{iconCheck(11)}</span>

426 <span>

427 I’m buying for a team or company (SSO, AWS/Azure/GCP, central billing)

428 </span>

429 </button>

430 </div>

431 

432 {}

433 {team && <div className="cc-ic-team-reveal">

434 <div className="cc-ic-sales">

435 <div className="cc-ic-sales-text">

436 <strong>Set up your team:</strong> self-serve or talk to sales.

437 </div>

438 <div className="cc-ic-sales-actions">

439 <a href="https://claude.ai/upgrade?initialPlanType=team&amp;utm_source=claude_code&amp;utm_medium=docs&amp;utm_content=configurator_team_get_started" className="cc-ic-btn-ghost">

440 Get started

441 </a>

442 <a href="https://www.anthropic.com/contact-sales?utm_source=claude_code&amp;utm_medium=docs&amp;utm_content=configurator_team_contact_sales" className="cc-ic-btn-clay">

443 Contact sales {iconArrowRight()}

444 </a>

445 </div>

446 </div>

447 

448 <div className="cc-ic-provider-bar">

449 <span className="cc-ic-label">Run on</span>

450 <div className="cc-ic-provider-pills" role="radiogroup" aria-label="Provider">

451 {PROVIDERS.map(p => <button key={p.key} type="button" role="radio" aria-checked={provider === p.key} className={'cc-ic-p-pill' + (provider === p.key ? ' cc-ic-active' : '')} onClick={() => setProvider(p.key)}>

452 {p.label}

453 </button>)}

454 </div>

455 </div>

456 

457 {showNotice && <div className="cc-ic-provider-notice">

458 {iconInfo()}

459 <div className="cc-ic-provider-notice-body">

460 {PROVIDER_NOTICE[provider]}

461 </div>

462 </div>}

463 </div>}

464 

465 {}

466 {target === 'terminal' && <div className="cc-ic-card">

467 <div className="cc-ic-subtabs" role="tablist" aria-label="Install method">

468 {Object.keys(TERM).map(k => <button key={k} type="button" role="tab" aria-selected={pkg === k} className={'cc-ic-subtab' + (pkg === k ? ' cc-ic-active' : '')} onClick={() => setPkg(k)}>

469 {TERM[k].label}

470 </button>)}

471 </div>

472 {isWinInstaller && <div className="cc-ic-shell-switch" role="tablist" aria-label="Shell">

473 {[{

474 k: 'ps',

475 label: 'PowerShell'

476 }, {

477 k: 'cmd',

478 label: 'CMD'

479 }].map(({k, label}) => {

480 const active = k === 'cmd' === winCmd;

481 return <button key={k} type="button" role="tab" aria-selected={active} className={'cc-ic-shell-option' + (active ? ' cc-ic-active' : '')} onClick={() => setWinCmd(k === 'cmd')}>

482 {label}

483 </button>;

484 })}

485 </div>}

486 {cardBodyCmd(terminalCmd, isWinPrompt ? '>' : '$')}

487 </div>}

488 

489 {}

490 {target === 'terminal' && <div className="cc-ic-below">

491 {isWinInstaller && <span>

492 <a href="https://git-scm.com/downloads/win" target="_blank" rel="noopener">

493 Git for Windows

494 </a>{' '}

495 recommended. PowerShell is used if Git Bash is absent.

496 </span>}

497 {(pkg === 'brew' || pkg === 'winget') && <span>

498 Does not auto-update. Run{' '}

499 <code>{pkg === 'brew' ? 'brew upgrade claude-code' : 'winget upgrade Anthropic.ClaudeCode'}</code>{' '}

500 periodically.

501 </span>}

502 <a href="/en/troubleshoot-install">Installation troubleshooting</a>

503 </div>}

504 

505 {alt && <div className="cc-ic-handoff">

506 <div className="cc-ic-handoff-title">Claude Code for {alt.name}</div>

507 <div className="cc-ic-handoff-sub">{alt.tagline}</div>

508 <div className="cc-ic-handoff-actions">

509 <a href={alt.installHref} className="cc-ic-btn-clay" {...alt.installHref.startsWith('http') ? {

510 target: '_blank',

511 rel: 'noopener'

512 } : {}}>

513 {alt.installLabel} {iconArrowUpRight(13)}

514 </a>

515 <a href={alt.guideHref} className="cc-ic-btn-ghost">

516 {alt.name} guide {iconArrowRight(12)}

517 </a>

518 </div>

519 {alt.altCmd && <div className="cc-ic-handoff-alt">

520 or run <code>{alt.altCmd}</code>

521 <button type="button" className={'cc-ic-copy-sm' + (copied === 'alt' ? ' cc-ic-copied' : '')} onClick={() => handleCopy(alt.altCmd, 'alt')} aria-label="Copy command">

522 {copied === 'alt' ? iconCheck(11) : iconCopy(11)}

523 </button>

524 </div>}

525 </div>}

526 </div>;

527};

528 

529export const Experiment = ({flag, treatment, children}) => {

530 const VID_KEY = 'exp_vid';

531 const CONSENT_COUNTRIES = new Set(['AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'RE', 'GP', 'MQ', 'GF', 'YT', 'BL', 'MF', 'PM', 'WF', 'PF', 'NC', 'AW', 'CW', 'SX', 'FO', 'GL', 'AX', 'GB', 'UK', 'AI', 'BM', 'IO', 'VG', 'KY', 'FK', 'GI', 'MS', 'PN', 'SH', 'TC', 'GG', 'JE', 'IM', 'CA', 'BR', 'IN']);

532 const fnv1a = s => {

533 let h = 0x811c9dc5;

534 for (let i = 0; i < s.length; i++) {

535 h ^= s.charCodeAt(i);

536 h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);

537 }

538 return h >>> 0;

539 };

540 const bucket = (seed, vid) => fnv1a(fnv1a(seed + vid) + '') % 10000 < 5000 ? 'control' : 'treatment';

541 const [decision] = useState(() => {

542 const params = new URLSearchParams(location.search);

543 const preBucketed = document.documentElement.dataset['gb_' + flag.replace(/-/g, '_')];

544 const force = params.get('gb-force');

545 if (force) {

546 for (const p of force.split(',')) {

547 const [k, v] = p.split(':');

548 if (k === flag) return {

549 variant: v || 'treatment',

550 track: false

551 };

552 }

553 }

554 if (navigator.globalPrivacyControl) {

555 return {

556 variant: 'control',

557 track: false

558 };

559 }

560 const prefsMatch = document.cookie.match(/(?:^|; )anthropic-consent-preferences=([^;]+)/);

561 if (prefsMatch) {

562 try {

563 if (JSON.parse(decodeURIComponent(prefsMatch[1])).analytics !== true) {

564 return {

565 variant: 'control',

566 track: false

567 };

568 }

569 } catch {

570 return {

571 variant: 'control',

572 track: false

573 };

574 }

575 } else {

576 const country = params.get('country')?.toUpperCase() || (document.cookie.match(/(?:^|; )cf_geo=([A-Z]{2})/) || [])[1];

577 if (!country || CONSENT_COUNTRIES.has(country)) {

578 return {

579 variant: 'control',

580 track: false

581 };

582 }

583 }

584 let vid;

585 try {

586 const ajsMatch = document.cookie.match(/(?:^|; )ajs_anonymous_id=([^;]+)/);

587 if (ajsMatch) {

588 vid = decodeURIComponent(ajsMatch[1]).replace(/^"|"$/g, '');

589 } else {

590 vid = localStorage.getItem(VID_KEY);

591 if (!vid) {

592 vid = crypto.randomUUID();

593 }

594 document.cookie = `ajs_anonymous_id=${vid}; domain=.claude.com; path=/; Secure; SameSite=Lax; max-age=31536000`;

595 }

596 try {

597 localStorage.setItem(VID_KEY, vid);

598 } catch {}

599 } catch {

600 return {

601 variant: 'control',

602 track: false

603 };

604 }

605 const variant = preBucketed === '1' ? 'treatment' : preBucketed === '0' ? 'control' : bucket(flag, vid);

606 return {

607 variant,

608 track: true,

609 vid

610 };

611 });

612 useEffect(() => {

613 if (!decision.track) return;

614 fetch('https://api.anthropic.com/api/event_logging/v2/batch', {

615 method: 'POST',

616 headers: {

617 'Content-Type': 'application/json',

618 'x-service-name': 'claude_code_docs'

619 },

620 body: JSON.stringify({

621 events: [{

622 event_type: 'GrowthbookExperimentEvent',

623 event_data: {

624 device_id: decision.vid,

625 anonymous_id: decision.vid,

626 timestamp: new Date().toISOString(),

627 experiment_id: flag,

628 variation_id: decision.variant === 'treatment' ? 1 : 0,

629 environment: 'production'

630 }

631 }]

632 }),

633 keepalive: true

634 }).catch(() => {});

635 }, []);

636 return decision.variant === 'treatment' ? treatment : children;

637};

638 

639Claude Code 是一個由 AI 驅動的編碼助手,可幫助您建立功能、修復錯誤和自動化開發任務。它理解您的整個程式碼庫,並可以跨多個檔案和工具工作以完成任務。

640 

641<div data-gb-slot="overview-install-configurator">

642 <Experiment flag="overview-install-configurator" treatment={<InstallConfigurator />} />

643</div>

644 

645## 開始使用

646 

647選擇您的環境以開始使用。大多數介面需要 [Claude 訂閱](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=overview_pricing)或 [Anthropic Console](https://console.anthropic.com/) 帳戶。終端機 CLI 和 VS Code 也支援[第三方提供商](/zh-TW/third-party-integrations)。

648 

649<Tabs>

650 <Tab title="終端機">

651 功能完整的 CLI,用於直接在您的終端機中使用 Claude Code。編輯檔案、執行命令,並從命令列管理您的整個專案。

652 

653 To install Claude Code, use one of the following methods:

654 

655 <Tabs>

656 <Tab title="Native Install (Recommended)">

657 **macOS, Linux, WSL:**

658 

659 ```bash theme={null}

660 curl -fsSL https://claude.ai/install.sh | bash

661 ```

662 

663 **Windows PowerShell:**

664 

665 ```powershell theme={null}

666 irm https://claude.ai/install.ps1 | iex

667 ```

668 

669 **Windows CMD:**

670 

671 ```batch theme={null}

672 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

673 ```

674 

675 If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you're in CMD, not PowerShell. Your prompt shows `PS C:\` when you're in PowerShell and `C:\` without the `PS` when you're in CMD.

676 

677 [Git for Windows](https://git-scm.com/downloads/win) is recommended on native Windows so Claude Code can use the Bash tool. If Git for Windows is not installed, Claude Code uses PowerShell as the shell tool instead. WSL setups do not need Git for Windows.

678 

679 <Info>

680 Native installations automatically update in the background to keep you on the latest version.

681 </Info>

682 </Tab>

683 

684 <Tab title="Homebrew">

685 ```bash theme={null}

686 brew install --cask claude-code

687 ```

688 

689 Homebrew offers two casks. `claude-code` tracks the stable release channel, which is typically about a week behind and skips releases with major regressions. `claude-code@latest` tracks the latest channel and receives new versions as soon as they ship.

690 

691 <Info>

692 Homebrew installations do not auto-update. Run `brew upgrade claude-code` or `brew upgrade claude-code@latest`, depending on which cask you installed, to get the latest features and security fixes.

693 </Info>

694 </Tab>

695 

696 <Tab title="WinGet">

697 ```powershell theme={null}

698 winget install Anthropic.ClaudeCode

699 ```

700 

701 <Info>

702 WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.

703 </Info>

704 </Tab>

705 </Tabs>

706 

707 You can also install with [apt, dnf, or apk](/en/setup#install-with-linux-package-managers) on Debian, Fedora, RHEL, and Alpine.

708 

709 然後在任何專案中啟動 Claude Code:

710 

711 ```bash theme={null}

712 cd your-project

713 claude

714 ```

715 

716 首次使用時,系統會提示您登入。就這麼簡單![繼續進行快速入門 →](/zh-TW/quickstart)

717 

718 <Tip>

719 請參閱[進階設定](/zh-TW/setup)以了解安裝選項、手動更新或卸載說明。如果遇到問題,請造訪[安裝疑難排解](/zh-TW/troubleshoot-install)。

720 </Tip>

721 </Tab>

722 

723 <Tab title="VS Code">

724 VS Code 擴充功能在您的編輯器中直接提供內嵌差異、@-提及、計畫審查和對話歷史記錄。

725 

726 * [安裝 VS Code](vscode:extension/anthropic.claude-code)

727 * [安裝 Cursor](cursor:extension/anthropic.claude-code)

728 

729 或在擴充功能檢視中搜尋「Claude Code」(Mac 上為 `Cmd+Shift+X`,Windows/Linux 上為 `Ctrl+Shift+X`)。安裝後,開啟命令選擇板(`Cmd+Shift+P` / `Ctrl+Shift+P`),輸入「Claude Code」,然後選擇**在新標籤中開啟**。

730 

731 [開始使用 VS Code →](/zh-TW/vs-code#get-started)

732 </Tab>

733 

734 <Tab title="桌面應用程式">

735 一個獨立應用程式,用於在 IDE 或終端機外執行 Claude Code。以視覺方式審查差異、並排執行多個工作階段、排程重複任務,以及啟動雲端工作階段。

736 

737 下載並安裝:

738 

739 * [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs)(Intel 和 Apple Silicon)

740 * [Windows](https://claude.ai/api/desktop/win32/x64/setup/latest/redirect?utm_source=claude_code\&utm_medium=docs)(x64)

741 * [Windows ARM64](https://claude.ai/api/desktop/win32/arm64/setup/latest/redirect?utm_source=claude_code\&utm_medium=docs)

742 

743 安裝後,啟動 Claude,登入,然後按一下**程式碼**標籤以開始編碼。需要[付費訂閱](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=overview_desktop_pricing)。

744 

745 [深入了解桌面應用程式 →](/zh-TW/desktop-quickstart)

746 </Tab>

747 

748 <Tab title="網頁">

749 在您的瀏覽器中執行 Claude Code,無需本機設定。啟動長時間執行的任務,並在完成時檢查,處理您本機沒有的儲存庫,或並行執行多個任務。可在桌面瀏覽器和 Claude iOS 應用程式上使用。

750 

751 在 [claude.ai/code](https://claude.ai/code) 開始編碼。

752 

753 [開始在網頁上使用 →](/zh-TW/web-quickstart)

754 </Tab>

755 

756 <Tab title="JetBrains">

757 IntelliJ IDEA、PyCharm、WebStorm 和其他 JetBrains IDE 的外掛程式,具有互動式差異檢視和選擇內容共享。

758 

759 從 JetBrains Marketplace 安裝 [Claude Code 外掛程式](https://plugins.jetbrains.com/plugin/27310-claude-code-beta-),然後重新啟動您的 IDE。

760 

761 [開始使用 JetBrains →](/zh-TW/jetbrains)

762 </Tab>

763</Tabs>

764 

765## 您可以做什麼

766 

767以下是您可以使用 Claude Code 的一些方式:

768 

769<AccordionGroup>

770 <Accordion title="自動化您一直在推遲的工作" icon="wand-magic-sparkles">

771 Claude Code 處理佔用您一整天的繁瑣任務:為未測試的程式碼編寫測試、修復整個專案中的 lint 錯誤、解決合併衝突、更新依賴項和編寫發行說明。

772 

773 ```bash theme={null}

774 claude "write tests for the auth module, run them, and fix any failures"

775 ```

776 </Accordion>

777 

778 <Accordion title="建立功能和修復錯誤" icon="hammer">

779 用純文字描述您想要的內容。Claude Code 規劃方法、跨多個檔案編寫程式碼,並驗證其是否有效。

780 

781 對於錯誤,貼上錯誤訊息或描述症狀。Claude Code 透過您的程式碼庫追蹤問題、識別根本原因並實施修復。請參閱[常見工作流程](/zh-TW/common-workflows)以了解更多範例。

782 </Accordion>

783 

784 <Accordion title="建立提交和拉取請求" icon="code-branch">

785 Claude Code 直接與 git 配合使用。它暫存變更、編寫提交訊息、建立分支並開啟拉取請求。

786 

787 ```bash theme={null}

788 claude "commit my changes with a descriptive message"

789 ```

790 

791 在 CI 中,您可以使用 [GitHub Actions](/zh-TW/github-actions) 或 [GitLab CI/CD](/zh-TW/gitlab-ci-cd) 自動化程式碼審查和問題分類。

792 </Accordion>

793 

794 <Accordion title="使用 MCP 連接您的工具" icon="plug">

795 [Model Context Protocol (MCP)](/zh-TW/mcp) 是一個開放標準,用於將 AI 工具連接到外部資料來源。使用 MCP,Claude Code 可以讀取 Google Drive 中的設計文件、更新 Jira 中的票證、從 Slack 提取資料,或使用您自己的自訂工具。

796 </Accordion>

797 

798 <Accordion title="使用說明、skills 和 hooks 進行自訂" icon="sliders">

799 [`CLAUDE.md`](/zh-TW/memory) 是您新增到專案根目錄的 markdown 檔案,Claude Code 在每個工作階段開始時都會讀取。使用它來設定編碼標準、架構決策、首選程式庫和審查檢查清單。Claude 也會在工作時建立[自動記憶](/zh-TW/memory#auto-memory),儲存學習內容,例如建置命令和除錯見解,跨工作階段而無需您編寫任何內容。

800 

801 建立[自訂命令](/zh-TW/skills)以封裝您的團隊可以共享的可重複工作流程,例如 `/review-pr` 或 `/deploy-staging`。

802 

803 [Hooks](/zh-TW/hooks) 可讓您在 Claude Code 動作之前或之後執行 shell 命令,例如在每次檔案編輯後自動格式化或在提交前執行 lint。

804 </Accordion>

805 

806 <Accordion title="執行代理團隊並建立自訂代理" icon="users">

807 生成[多個 Claude Code 代理](/zh-TW/sub-agents),同時處理任務的不同部分。主導代理協調工作、指派子任務並合併結果。

808 

809 對於完全自訂的工作流程,[Agent SDK](/zh-TW/agent-sdk/overview) 可讓您建立由 Claude Code 的工具和功能驅動的自己的代理,並完全控制編排、工具存取和權限。

810 </Accordion>

811 

812 <Accordion title="使用 CLI 進行管道、指令碼和自動化" icon="terminal">

813 Claude Code 是可組合的,遵循 Unix 哲學。將日誌管道傳入其中、在 CI 中執行它,或將其與其他工具鏈接:

814 

815 ```bash theme={null}

816 # 分析最近的日誌輸出

817 tail -200 app.log | claude -p "Slack me if you see any anomalies"

818 

819 # 在 CI 中自動化翻譯

820 claude -p "translate new strings into French and raise a PR for review"

821 

822 # 跨檔案的大量操作

823 git diff main --name-only | claude -p "review these changed files for security issues"

824 ```

825 

826 請參閱 [CLI 參考](/zh-TW/cli-reference)以了解完整的命令和旗標集。

827 </Accordion>

828 

829 <Accordion title="排程重複任務" icon="clock">

830 按排程執行 Claude 以自動化重複的工作:早上 PR 審查、隔夜 CI 失敗分析、每週依賴項審計或在 PR 合併後同步文件。

831 

832 * [Routines](/zh-TW/routines) 在 Anthropic 管理的基礎設施上執行,因此即使您的電腦關閉,它們也會繼續執行。它們也可以在 API 呼叫或 GitHub 事件上觸發。從網頁、桌面應用程式或在 CLI 中執行 `/schedule` 來建立它們。

833 * [桌面排程任務](/zh-TW/desktop-scheduled-tasks)在您的機器上執行,可直接存取您的本機檔案和工具

834 * [`/loop`](/zh-TW/scheduled-tasks) 在 CLI 工作階段中重複提示以進行快速輪詢

835 </Accordion>

836 

837 <Accordion title="從任何地方工作" icon="globe">

838 工作階段不受限於單一介面。當您的內容變更時,在環境之間移動工作:

839 

840 * 離開您的辦公桌,使用[遠端控制](/zh-TW/remote-control)從您的手機或任何瀏覽器繼續工作

841 * 從您的手機向 [Dispatch](/zh-TW/desktop#sessions-from-dispatch) 傳送任務,並開啟它建立的桌面工作階段

842 * 在[網頁](/zh-TW/claude-code-on-the-web)或 [iOS 應用程式](https://apps.apple.com/app/claude-by-anthropic/id6473753684)上啟動長時間執行的任務,然後使用 `claude --teleport` 將其提取到您的終端機中

843 * 使用 `/desktop` 將終端機工作階段交付給[桌面應用程式](/zh-TW/desktop)以進行視覺差異審查

844 * 從團隊聊天路由任務:在 [Slack](/zh-TW/slack) 中提及 `@Claude` 並提供錯誤報告,然後取回拉取請求

845 </Accordion>

846</AccordionGroup>

847 

848## 在任何地方使用 Claude Code

849 

850每個介面都連接到相同的基礎 Claude Code 引擎,因此您的 CLAUDE.md 檔案、設定和 MCP servers 可在所有介面中工作。

851 

852除了上述[終端機](/zh-TW/quickstart)、[VS Code](/zh-TW/vs-code)、[JetBrains](/zh-TW/jetbrains)、[桌面](/zh-TW/desktop)和[網頁](/zh-TW/claude-code-on-the-web)環境外,Claude Code 還與 CI/CD、聊天和瀏覽器工作流程整合:

853 

854| 我想要... | 最佳選項 |

855| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |

856| 從我的手機或其他裝置繼續本機工作階段 | [遠端控制](/zh-TW/remote-control) |

857| 從 Telegram、Discord、iMessage 或我自己的 webhooks 推送事件到工作階段 | [Channels](/zh-TW/channels) |

858| 在本機啟動任務,在行動裝置上繼續 | [網頁](/zh-TW/claude-code-on-the-web)或 [Claude iOS 應用程式](https://apps.apple.com/app/claude-by-anthropic/id6473753684) |

859| 按重複排程執行 Claude | [Routines](/zh-TW/routines) 或[桌面排程任務](/zh-TW/desktop-scheduled-tasks) |

860| 自動化 PR 審查和問題分類 | [GitHub Actions](/zh-TW/github-actions) 或 [GitLab CI/CD](/zh-TW/gitlab-ci-cd) |

861| 在每個 PR 上獲得自動程式碼審查 | [GitHub Code Review](/zh-TW/code-review) |

862| 將 Slack 中的錯誤報告路由到拉取請求 | [Slack](/zh-TW/slack) |

863| 除錯即時網頁應用程式 | [Chrome](/zh-TW/chrome) |

864| 為您自己的工作流程建立自訂代理 | [Agent SDK](/zh-TW/agent-sdk/overview) |

865 

866## 後續步驟

867 

868安裝 Claude Code 後,這些指南可幫助您深入了解。

869 

870* [快速入門](/zh-TW/quickstart):逐步完成您的第一個真實任務,從探索程式碼庫到提交修復

871* [儲存說明和記憶](/zh-TW/memory):使用 CLAUDE.md 檔案和自動記憶為 Claude 提供持久說明

872* [常見工作流程](/zh-TW/common-workflows)和[最佳實踐](/zh-TW/best-practices):充分利用 Claude Code 的模式

873* [設定](/zh-TW/settings):為您的工作流程自訂 Claude Code

874* [疑難排解](/zh-TW/troubleshooting):常見問題的解決方案

875* [code.claude.com](https://code.claude.com/):演示、定價和產品詳細資訊

permission-modes.md +290 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 選擇權限模式

6 

7> 控制 Claude 是否在編輯檔案或執行命令前詢問。在 CLI 中使用 Shift+Tab 循環模式,或在 VS Code、Desktop 和 claude.ai 中使用模式選擇器。

8 

9當 Claude 想要編輯檔案、執行 shell 命令或進行網路請求時,它會暫停並要求您批准該操作。權限模式控制該暫停發生的頻率。您選擇的模式塑造了會話的流程:預設模式讓您在操作進行時審查每個操作,而較寬鬆的模式讓 Claude 在較長的不間斷時間內工作並在完成時報告。對敏感工作選擇更多監督,或在您信任方向時選擇較少中斷。

10 

11## 可用模式

12 

13每種模式在便利性和監督之間進行不同的權衡。下表顯示在每種模式中 Claude 無需權限提示即可執行的操作。

14 

15| 模式 | 無需詢問即可執行的操作 | 最適合 |

16| :------------------------------------------------------------------ | :-------------------------------------------- | :-------------- |

17| `default` | 僅讀取 | 入門、敏感工作 |

18| [`acceptEdits`](#auto-approve-file-edits-with-acceptedits-mode) | 讀取、檔案編輯和常見檔案系統命令(`mkdir`、`touch`、`mv`、`cp` 等) | 迭代您正在審查的程式碼 |

19| [`plan`](#analyze-before-you-edit-with-plan-mode) | 僅讀取 | 在變更前探索程式碼庫 |

20| [`auto`](#eliminate-prompts-with-auto-mode) | 所有操作,具有背景安全檢查 | 長時間執行的任務、減少提示疲勞 |

21| [`dontAsk`](#allow-only-pre-approved-tools-with-dontask-mode) | 僅預先批准的工具 | 鎖定的 CI 和指令碼 |

22| [`bypassPermissions`](#skip-all-checks-with-bypasspermissions-mode) | 所有操作,具有背景安全檢查 | 隔離容器和 VM 僅 |

23 

24在除 `bypassPermissions` 外的每種模式中,寫入[受保護路徑](#protected-paths)永遠不會自動批准,保護倉庫狀態和 Claude 自己的配置免受意外損壞。

25 

26模式設定基線。在頂部分層[權限規則](/zh-TW/permissions#manage-permissions)以在除 `bypassPermissions` 外的任何模式中預先批准或阻止特定工具,`bypassPermissions` 完全跳過權限層。

27 

28## 切換權限模式

29 

30您可以在會話期間、啟動時或作為持久預設值切換模式。模式通過這些控制設定,而不是通過在聊天中詢問 Claude。選擇下面的您的介面以查看如何變更它。

31 

32<Tabs>

33 <Tab title="CLI">

34 **在會話期間**:按 `Shift+Tab` 循環 `default` → `acceptEdits` → `plan`。目前模式出現在狀態欄中。並非每種模式都在預設循環中:

35 

36 * `auto`:當您的帳戶符合 [auto 模式要求](#eliminate-prompts-with-auto-mode)時出現;循環到 auto 會顯示選擇加入提示,直到您接受它,或選擇**否,不要再問**以從循環中移除 auto

37 * `bypassPermissions`:在您使用 `--permission-mode bypassPermissions`、`--dangerously-skip-permissions` 或 `--allow-dangerously-skip-permissions` 啟動後出現;`--allow-` 變體將模式添加到循環中而不啟動它

38 * `dontAsk`:永遠不在循環中出現;使用 `--permission-mode dontAsk` 設定它

39 

40 啟用的可選模式在 `plan` 後插入,`bypassPermissions` 優先,`auto` 最後。如果您同時啟用了兩者,您將在前往 `auto` 的途中循環通過 `bypassPermissions`。

41 

42 **啟動時**:將模式作為標誌傳遞。

43 

44 ```bash theme={null}

45 claude --permission-mode plan

46 ```

47 

48 **作為預設值**:在[設定](/zh-TW/settings#settings-files)中設定 `defaultMode`。

49 

50 ```json theme={null}

51 {

52 "permissions": {

53 "defaultMode": "acceptEdits"

54 }

55 }

56 ```

57 

58 相同的 `--permission-mode` 標誌適用於 `-p` 用於[非互動式執行](/zh-TW/headless)。

59 </Tab>

60 

61 <Tab title="VS Code">

62 **在會話期間**:點擊提示框底部的模式指示器。

63 

64 **作為預設值**:在 VS Code 設定中設定 `claudeCode.initialPermissionMode`,或使用 Claude Code 擴充設定面板。

65 

66 模式指示器顯示這些標籤,對應於每個標籤適用的模式:

67 

68 | UI 標籤 | 模式 |

69 | :-------- | :------------------ |

70 | 編輯前詢問 | `default` |

71 | 自動編輯 | `acceptEdits` |

72 | Plan mode | `plan` |

73 | Auto mode | `auto` |

74 | 繞過權限 | `bypassPermissions` |

75 

76 Auto mode 在您在擴充設定中啟用**允許危險跳過權限**後出現在模式指示器中,但它保持不可用,直到您的帳戶符合 [auto 模式部分](#eliminate-prompts-with-auto-mode)中列出的每項要求。`claudeCode.initialPermissionMode` 設定不接受 `auto`;要預設啟動 auto mode,請改為在您的 Claude Code [`settings.json`](/zh-TW/settings#settings-files) 中設定 `defaultMode`。

77 

78 繞過權限也需要**允許危險跳過權限**切換,然後才會在模式指示器中出現。

79 

80 有關擴充特定詳細資訊,請參閱 [VS Code 指南](/zh-TW/vs-code)。

81 </Tab>

82 

83 <Tab title="JetBrains">

84 JetBrains 外掛在 IDE 終端中執行 Claude Code,因此切換模式的工作方式與 CLI 中相同:按 `Shift+Tab` 循環,或在啟動時傳遞 `--permission-mode`。

85 </Tab>

86 

87 <Tab title="Desktop">

88 使用傳送按鈕旁邊的模式選擇器。Auto 和 Bypass permissions 僅在您在 Desktop 設定中啟用它們後出現。有關詳細資訊,請參閱 [Desktop 指南](/zh-TW/desktop#choose-a-permission-mode)。

89 </Tab>

90 

91 <Tab title="Web and mobile">

92 在 [claude.ai/code](https://claude.ai/code) 或行動應用中使用提示框旁邊的模式下拉菜單。權限提示出現在 claude.ai 中以供批准。哪些模式出現取決於會話執行的位置:

93 

94 * **雲端會話**在 [Claude Code on the web](/zh-TW/claude-code-on-the-web):Auto accept edits 和 Plan mode。Ask permissions、Auto 和 Bypass permissions 不可用。

95 * **[Remote Control](/zh-TW/remote-control) 會話**在您的本地機器上:Ask permissions、Auto accept edits 和 Plan mode。Auto 和 Bypass permissions 不可用。

96 

97 對於 Remote Control,您也可以在啟動主機時設定啟動模式:

98 

99 ```bash theme={null}

100 claude remote-control --permission-mode acceptEdits

101 ```

102 </Tab>

103</Tabs>

104 

105## 使用 acceptEdits 模式自動批准檔案編輯

106 

107`acceptEdits` 模式讓 Claude 在您的工作目錄中建立和編輯檔案而不提示。狀態欄顯示 `⏵⏵ accept edits on` 當此模式處於活動狀態時。

108 

109除了檔案編輯外,`acceptEdits` 模式自動批准常見的檔案系統 Bash 命令:`mkdir`、`touch`、`rm`、`rmdir`、`mv`、`cp` 和 `sed`。這些命令在以安全環境變數(如 `LANG=C` 或 `NO_COLOR=1`)或流程包裝器(如 `timeout`、`nice` 或 `nohup`)為前綴時也會自動批准。與檔案編輯一樣,自動批准僅適用於您的工作目錄或 `additionalDirectories` 內的路徑。該範圍外的路徑、寫入[受保護路徑](#protected-paths)和所有其他 Bash 命令仍然提示。

110 

111當啟用 [PowerShell tool](/zh-TW/tools-reference#powershell-tool) 時,`acceptEdits` 模式也會自動批准 `Set-Content`、`Add-Content`、`Clear-Content` 和 `Remove-Item` 在範圍內的路徑上,以及它們的常見別名。相同的範圍和受保護路徑規則適用。

112 

113當您想在編輯器中或通過 `git diff` 之後審查變更而不是在線批准每個編輯時,使用 `acceptEdits`。從預設模式按 `Shift+Tab` 一次進入它,或直接啟動它:

114 

115```bash theme={null}

116claude --permission-mode acceptEdits

117```

118 

119## 使用 plan mode 在編輯前分析

120 

121Plan mode 告訴 Claude 研究和提議變更而不進行變更。Claude 讀取檔案、執行 shell 命令進行探索,並寫入計劃,但不編輯您的原始程式碼。權限提示的應用方式與預設模式相同。

122 

123通過按 `Shift+Tab` 或在單個提示前加上 `/plan` 進入 plan mode。您也可以從 CLI 啟動 plan mode:

124 

125```bash theme={null}

126claude --permission-mode plan

127```

128 

129再次按 `Shift+Tab` 離開 plan mode 而不批准計劃。

130 

131當計劃準備好時,Claude 呈現它並詢問如何進行。從該提示您可以:

132 

133* 批准並在 auto mode 中啟動

134* 批准並接受編輯

135* 批准並手動審查每個編輯

136* 繼續規劃並提供反饋

137* 使用 [Ultraplan](/zh-TW/ultraplan) 進行基於瀏覽器的審查進行細化

138 

139每個批准選項也提供首先清除規劃上下文的選項。

140 

141## 使用 auto mode 消除提示

142 

143<Note>

144 Auto mode 需要 Claude Code v2.1.83 或更新版本。

145</Note>

146 

147Auto mode 讓 Claude 執行而不顯示權限提示。單獨的分類器模型在執行前審查操作,阻止任何超出您要求的操作、針對無法識別的基礎設施的操作,或似乎由 Claude 讀到的敵對內容驅動的操作。

148 

149<Warning>

150 Auto mode 是研究預覽。它減少提示但不保證安全。將其用於您信任一般方向的任務,而不是作為敏感操作審查的替代品。

151</Warning>

152 

153Auto mode 僅在您的帳戶符合所有這些要求時可用:

154 

155* **計劃**:Max、Team、Enterprise 或 API。Pro 上不可用。

156* **管理員**:在 Team 和 Enterprise 上,管理員必須在 [Claude Code 管理設定](https://claude.ai/admin-settings/claude-code)中啟用它,使用者才能打開它。管理員也可以通過在[受管設定](/zh-TW/permissions#managed-settings)中將 `permissions.disableAutoMode` 設定為 `"disable"` 來鎖定它。

157* **模型**:Team、Enterprise 和 API 計劃上的 Claude Sonnet 4.6、Opus 4.6 或 Opus 4.7;Max 計劃上僅 Claude Opus 4.7。不支援其他模型,包括 Haiku 和 claude-3 模型。

158* **提供商**:僅 Anthropic API。在 Bedrock、Vertex 或 Foundry 上不可用。

159 

160如果 Claude Code 報告 auto mode 不可用,其中一項要求未滿足;這不是暫時性中斷。單獨的訊息命名模型並說 auto mode「無法確定」操作的安全性是暫時性分類器中斷;請參閱[錯誤參考](/zh-TW/errors#auto-mode-cannot-determine-the-safety-of-an-action)。

161 

162### 分類器預設阻止的內容

163 

164分類器信任您的工作目錄和您的倉庫配置的遠端。其他所有內容都被視為外部,直到您[配置受信任的基礎設施](/zh-TW/auto-mode-config)。

165 

166**預設阻止**:

167 

168* 下載和執行程式碼,如 `curl | bash`

169* 將敏感資料發送到外部端點

170* 生產部署和遷移

171* 雲端儲存上的大量刪除

172* 授予 IAM 或倉庫權限

173* 修改共享基礎設施

174* 不可逆轉地銷毀會話開始前存在的檔案

175* 強制推送或直接推送到 `main`

176 

177**預設允許**:

178 

179* 工作目錄中的本地檔案操作

180* 安裝在您的鎖定檔案或清單中聲明的依賴項

181* 讀取 `.env` 並將認證發送到其匹配的 API

182* 唯讀 HTTP 請求

183* 推送到您啟動的分支或 Claude 建立的分支

184 

185沙箱網路存取請求通過分類器路由,而不是預設允許。執行 `claude auto-mode defaults` 以查看完整規則列表。如果例行操作被阻止,管理員可以通過 `autoMode.environment` 設定添加受信任的倉庫、儲存桶和服務:請參閱[配置 auto mode](/zh-TW/auto-mode-config)。

186 

187### 您在對話中陳述的邊界

188 

189分類器將您在對話中陳述的邊界視為阻止信號。如果您告訴 Claude「不要推送」或「在我審查前等待再部署」,分類器阻止匹配的操作,即使預設規則會允許它們。邊界保持有效,直到您在稍後的訊息中解除它。Claude 自己的判斷條件已滿足不會解除它。

190 

191邊界不作為規則儲存。分類器在每次檢查時從記錄中重新讀取它們,因此如果[上下文壓縮](/zh-TW/costs#reduce-token-usage)移除陳述邊界的訊息,邊界可能會丟失。為了硬保證,請改為添加[拒絕規則](/zh-TW/permissions#permission-rule-syntax)。

192 

193### 當 auto mode 回退時

194 

195每個被拒絕的操作顯示通知並出現在 `/permissions` 下的「最近拒絕」標籤中,您可以按 `r` 使用手動批准重試它。

196 

197如果分類器連續 3 次或總共 20 次阻止操作,auto mode 暫停,Claude Code 恢復提示。批准提示的操作恢復 auto mode。這些閾值不可配置。任何允許的操作重置連續計數器,而總計數器在會話期間持續,僅在其自己的限制觸發回退時重置。

198 

199在[非互動式模式](/zh-TW/headless)中使用 `-p` 標誌,重複阻止中止會話,因為沒有使用者可以提示。

200 

201重複阻止通常意味著分類器缺少有關您的基礎設施的上下文。使用 `/feedback` 報告誤報,或讓管理員[配置受信任的基礎設施](/zh-TW/auto-mode-config)。

202 

203<AccordionGroup>

204 <Accordion title="分類器如何評估操作">

205 每個操作都經過固定的決策順序。第一個匹配的步驟獲勝:

206 

207 1. 與您的[允許或拒絕規則](/zh-TW/permissions#manage-permissions)相符的操作立即解決

208 2. 唯讀操作和工作目錄中的檔案編輯自動批准,除了寫入[受保護路徑](#protected-paths)

209 3. 其他所有內容都發送到分類器

210 4. 如果分類器阻止,Claude 接收原因並嘗試替代方法

211 

212 進入 auto mode 時,授予任意程式碼執行的廣泛允許規則被刪除:

213 

214 * 全面 `Bash(*)`

215 * 通配符解釋器,如 `Bash(python*)`

216 * 套件管理器執行命令

217 * `Agent` 允許規則

218 

219 像 `Bash(npm test)` 這樣的狹義規則保留。刪除的規則在您離開 auto mode 時恢復。

220 

221 分類器看到使用者訊息、工具呼叫和您的 CLAUDE.md 內容。工具結果被剝離,因此檔案或網頁中的敵對內容無法直接操縱它。單獨的伺服器端探針掃描傳入的工具結果並在 Claude 讀取前標記可疑內容。有關這些層如何協同工作的更多資訊,請參閱 [auto mode 公告](https://claude.com/blog/auto-mode)和[工程深度探討](https://www.anthropic.com/engineering/claude-code-auto-mode)。

222 </Accordion>

223 

224 <Accordion title="Auto mode 如何處理子代理">

225 分類器在三個點檢查[子代理](/zh-TW/sub-agents)工作:

226 

227 1. 在子代理啟動前,委派的任務描述被評估,因此看起來危險的任務在生成時被阻止。

228 2. 當子代理執行時,它的每個操作都通過分類器,使用與父會話相同的規則,子代理前置事項中的任何 `permissionMode` 都被忽略。

229 3. 當子代理完成時,分類器審查其完整操作歷史;如果該返回檢查標記了一個問題,安全警告被添加到子代理結果前面。

230 </Accordion>

231 

232 <Accordion title="成本和延遲">

233 分類器在伺服器配置的模型上執行,獨立於您的 `/model` 選擇,因此切換模型不會改變分類器可用性。分類器呼叫計入您的令牌使用量。每次檢查發送記錄的一部分加上待處理操作,在執行前添加往返。工作目錄外受保護路徑的讀取和編輯跳過分類器,因此開銷主要來自 shell 命令和網路操作。

234 </Accordion>

235</AccordionGroup>

236 

237## 使用 dontAsk 模式僅允許預先批准的工具

238 

239`dontAsk` 模式自動拒絕每個否則會提示的工具呼叫。僅與您的 `permissions.allow` 規則和[唯讀 Bash 命令](/zh-TW/permissions#read-only-commands)相符的操作可以執行;明確的 `ask` 規則被拒絕而不是提示。這使模式完全非互動式,適合 CI 管道或受限環境,您可以在其中預先定義 Claude 可能執行的操作。

240 

241在啟動時使用標誌設定它:

242 

243```bash theme={null}

244claude --permission-mode dontAsk

245```

246 

247## 使用 bypassPermissions 模式跳過所有檢查

248 

249`bypassPermissions` 模式禁用權限提示和安全檢查,因此工具呼叫立即執行。自 v2.1.126 起,這包括寫入[受保護路徑](#protected-paths),較早版本仍會提示。針對檔案系統根目錄或主目錄的移除操作,例如 `rm -rf /` 和 `rm -rf ~`,仍會作為針對模型錯誤的斷路器而提示。僅在隔離環境(如容器、VM 或 dev container)中使用此模式,沒有網際網路存取,其中 Claude Code 無法損害您的主機系統。

250 

251您無法從未使用啟用標誌啟動的會話進入 `bypassPermissions`;使用其中一個重新啟動以啟用它:

252 

253```bash theme={null}

254claude --permission-mode bypassPermissions

255```

256 

257`--dangerously-skip-permissions` 標誌等同於此。

258 

259<Warning>

260 `bypassPermissions` 不提供針對提示注入或意外操作的保護。對於沒有提示的背景安全檢查,請改為使用 [auto mode](#eliminate-prompts-with-auto-mode)。管理員可以通過在[受管設定](/zh-TW/permissions#managed-settings)中將 `permissions.disableBypassPermissionsMode` 設定為 `"disable"` 來阻止此模式。

261</Warning>

262 

263## 受保護的路徑

264 

265寫入一小組路徑永遠不會自動批准,在除了 `bypassPermissions` 之外的每種模式中。這防止了倉庫狀態和 Claude 自己的配置的意外損壞。在 `default`、`acceptEdits` 和 `plan` 中,這些寫入會提示;在 `auto` 中它們會路由到分類器;在 `dontAsk` 中它們被拒絕;在 `bypassPermissions` 中它們被允許。

266 

267受保護的目錄:

268 

269* `.git`

270* `.vscode`

271* `.idea`

272* `.husky`

273* `.claude`,除了 `.claude/commands`、`.claude/agents`、`.claude/skills` 和 `.claude/worktrees`,其中 Claude 例行建立內容

274 

275受保護的檔案:

276 

277* `.gitconfig`、`.gitmodules`

278* `.bashrc`、`.bash_profile`、`.zshrc`、`.zprofile`、`.profile`

279* `.ripgreprc`

280* `.mcp.json`、`.claude.json`

281 

282## 另請參閱

283 

284* [Permissions](/zh-TW/permissions):允許、詢問和拒絕規則;受管策略

285* [Configure auto mode](/zh-TW/auto-mode-config):告訴分類器您的組織信任哪些基礎設施

286* [Hooks](/zh-TW/hooks):通過 `PreToolUse` 和 `PermissionRequest` hooks 的自訂權限邏輯

287* [Ultraplan](/zh-TW/ultraplan):在 Claude Code on the web 會話中執行 plan mode,具有基於瀏覽器的審查

288* [Security](/zh-TW/security):安全保障和最佳實踐

289* [Sandboxing](/zh-TW/sandboxing):Bash 命令的檔案系統和網路隔離

290* [Non-interactive mode](/zh-TW/headless):使用 `-p` 標誌執行 Claude Code

permissions.md +358 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 設定權限

6 

7> 使用細粒度權限規則、模式和受管理原則來控制 Claude Code 可以存取和執行的操作。

8 

9Claude Code 支援細粒度權限,讓您可以精確指定代理允許執行和不允許執行的操作。權限設定可以簽入版本控制並分發給組織中的所有開發人員,也可以由個別開發人員自訂。

10 

11## 權限系統

12 

13Claude Code 使用分層權限系統來平衡功能和安全性:

14 

15| 工具類型 | 範例 | 需要批准 | "是,不要再問"行為 |

16| :------ | :------------ | :--- | :------------ |

17| 唯讀 | 檔案讀取、Grep | 否 | 不適用 |

18| Bash 命令 | Shell 執行 | 是 | 每個專案目錄和命令永久有效 |

19| 檔案修改 | Edit/Write 檔案 | 是 | 直到工作階段結束 |

20 

21## 管理權限

22 

23您可以使用 `/permissions` 檢視和管理 Claude Code 的工具權限。此 UI 列出所有權限規則及其來源的 settings.json 檔案。

24 

25* **Allow** 規則讓 Claude Code 使用指定的工具,無需手動批准。

26* **Ask** 規則在 Claude Code 嘗試使用指定工具時提示確認。

27* **Deny** 規則防止 Claude Code 使用指定的工具。

28 

29規則按順序評估:**deny -> ask -> allow**。第一個符合的規則獲勝,因此 deny 規則始終優先。

30 

31## 權限模式

32 

33Claude Code 支援多種權限模式來控制工具的批准方式。請參閱 [Permission modes](/zh-TW/permission-modes) 以了解何時使用每一種。在您的 [settings files](/zh-TW/settings#settings-files) 中設定 `defaultMode`:

34 

35| 模式 | 描述 |

36| :------------------ | :------------------------------------------------------------------------------- |

37| `default` | 標準行為:在首次使用每個工具時提示權限 |

38| `acceptEdits` | 自動接受工作目錄或 `additionalDirectories` 中路徑的檔案編輯和常見檔案系統命令(`mkdir`、`touch`、`mv`、`cp` 等) |

39| `plan` | Plan Mode:Claude 可以分析但不能修改檔案或執行命令 |

40| `auto` | 自動批准工具呼叫,並進行背景安全檢查以驗證操作是否符合您的要求。目前為研究預覽版 |

41| `dontAsk` | 自動拒絕工具,除非透過 `/permissions` 或 `permissions.allow` 規則預先批准 |

42| `bypassPermissions` | 跳過所有權限提示。根目錄和主目錄移除(例如 `rm -rf /`)仍會作為斷路器提示 |

43 

44<Warning>

45 `bypassPermissions` 模式會跳過所有權限提示,包括對 `.git`、`.claude`、`.vscode`、`.idea` 和 `.husky` 的寫入。針對檔案系統根目錄或主目錄的移除,例如 `rm -rf /` 和 `rm -rf ~`,仍會作為斷路器提示以防止模型錯誤。僅在隔離環境(如容器或虛擬機)中使用此模式,其中 Claude Code 無法造成損害。管理員可以透過在 [managed settings](#managed-settings) 中將 `permissions.disableBypassPermissionsMode` 設定為 `"disable"` 來防止此模式。

46</Warning>

47 

48若要防止 `bypassPermissions` 或 `auto` 模式被使用,請在任何 [settings files](/zh-TW/settings#settings-files) 中將 `permissions.disableBypassPermissionsMode` 或 `permissions.disableAutoMode` 設定為 `"disable"`。這些在 [managed settings](#managed-settings) 中最有用,因為它們無法被覆蓋。

49 

50## 權限規則語法

51 

52權限規則遵循格式 `Tool` 或 `Tool(specifier)`。

53 

54### 符合工具的所有使用

55 

56若要符合工具的所有使用,請使用不帶括號的工具名稱:

57 

58| 規則 | 效果 |

59| :--------- | :----------- |

60| `Bash` | 符合所有 Bash 命令 |

61| `WebFetch` | 符合所有網頁擷取請求 |

62| `Read` | 符合所有檔案讀取 |

63 

64`Bash(*)` 等同於 `Bash` 並符合所有 Bash 命令。

65 

66### 使用指定符進行細粒度控制

67 

68在括號中新增指定符以符合特定工具使用:

69 

70| 規則 | 效果 |

71| :----------------------------- | :--------------------- |

72| `Bash(npm run build)` | 符合確切命令 `npm run build` |

73| `Read(./.env)` | 符合讀取目前目錄中的 `.env` 檔案 |

74| `WebFetch(domain:example.com)` | 符合對 example.com 的擷取請求 |

75 

76### 萬用字元模式

77 

78Bash 規則支援使用 `*` 的 glob 模式。萬用字元可以出現在命令中的任何位置。此設定允許 npm 和 git commit 命令,同時阻止 git push:

79 

80```json theme={null}

81{

82 "permissions": {

83 "allow": [

84 "Bash(npm run *)",

85 "Bash(git commit *)",

86 "Bash(git * main)",

87 "Bash(* --version)",

88 "Bash(* --help *)"

89 ],

90 "deny": [

91 "Bash(git push *)"

92 ]

93 }

94}

95```

96 

97`*` 前的空格很重要:`Bash(ls *)` 符合 `ls -la` 但不符合 `lsof`,而 `Bash(ls*)` 兩者都符合。`:*` 後綴是寫入尾部萬用字元的等效方式,所以 `Bash(ls:*)` 符合與 `Bash(ls *)` 相同的命令。

98 

99當您為命令前綴選擇"是,不要再問"時,權限對話框會寫入空格分隔的形式。`:*` 形式僅在模式末尾被識別。在像 `Bash(git:* push)` 這樣的模式中,冒號被視為字面字元,不會符合 git 命令。

100 

101## 工具特定的權限規則

102 

103### Bash

104 

105Bash 權限規則支援使用 `*` 的萬用字元符合。萬用字元可以出現在命令中的任何位置,包括開頭、中間或結尾:

106 

107* `Bash(npm run build)` 符合確切的 Bash 命令 `npm run build`

108* `Bash(npm run test *)` 符合以 `npm run test` 開頭的 Bash 命令

109* `Bash(npm *)` 符合任何以 `npm ` 開頭的命令

110* `Bash(* install)` 符合任何以 ` install` 結尾的命令

111* `Bash(git * main)` 符合命令如 `git checkout main` 和 `git log --oneline main`

112 

113單一 `*` 符合任何字元序列,包括空格,所以一個萬用字元可以跨越多個引數。`Bash(git *)` 符合 `git log --oneline --all`,而 `Bash(git * main)` 符合 `git push origin main` 以及 `git merge main`。

114 

115當 `*` 出現在末尾且前面有空格時(如 `Bash(ls *)`),它會強制執行字邊界,要求前綴後面跟著空格或字串結尾。例如,`Bash(ls *)` 符合 `ls -la` 但不符合 `lsof`。相比之下,`Bash(ls*)` 沒有空格會同時符合 `ls -la` 和 `lsof`,因為沒有字邊界限制。

116 

117#### 複合命令

118 

119<Tip>

120 Claude Code 知道 shell 運算子,所以前綴符合規則如 `Bash(safe-cmd *)` 不會給它執行命令 `safe-cmd && other-cmd` 的權限。已識別的命令分隔符是 `&&`、`||`、`;`、`|`、`|&`、`&` 和換行符。規則必須獨立符合每個子命令。

121</Tip>

122 

123當您使用"是,不要再問"批准複合命令時,Claude Code 會為每個需要批准的子命令儲存一個單獨的規則,而不是為完整複合字串儲存單一規則。例如,批准 `git status && npm test` 會為 `npm test` 儲存一個規則,因此未來的 `npm test` 呼叫會被識別,無論 `&&` 前面是什麼。子命令如 `cd` 進入子目錄會為該路徑產生自己的 Read 規則。單一複合命令最多可能儲存 5 個規則。

124 

125#### 程序包裝器

126 

127在符合 Bash 規則之前,Claude Code 會移除一組固定的程序包裝器,所以像 `Bash(npm test *)` 這樣的規則也符合 `timeout 30 npm test`。已識別的包裝器是 `timeout`、`time`、`nice`、`nohup` 和 `stdbuf`。

128 

129裸 `xargs` 也會被移除,所以 `Bash(grep *)` 符合 `xargs grep pattern`。移除僅在 `xargs` 沒有旗標時適用:像 `xargs -n1 grep pattern` 這樣的呼叫被符合為 `xargs` 命令,所以為內部命令編寫的規則不涵蓋它。

130 

131此包裝器清單是內建的,不可設定。開發環境執行器如 `direnv exec`、`devbox run`、`mise exec`、`npx` 和 `docker exec` 不在清單中。因為這些工具將其引數作為命令執行,像 `Bash(devbox run *)` 這樣的規則符合 `run` 後面的任何內容,包括 `devbox run rm -rf .`。若要批准環境執行器內的工作,請編寫包含執行器和內部命令的特定規則,如 `Bash(devbox run npm test)`。為您想要允許的每個內部命令新增一個規則。

132 

133Exec 包裝器如 `watch`、`setsid`、`ionice` 和 `flock` 始終提示,無法透過像 `Bash(watch *)` 這樣的前綴規則自動批准。同樣適用於帶有 `-exec` 或 `-delete` 的 `find`:`Bash(find *)` 規則不涵蓋這些形式。若要批准特定呼叫,請為完整命令字串編寫精確符合規則。

134 

135#### 唯讀命令

136 

137Claude Code 將一組內建的 Bash 命令識別為唯讀,並在每種模式中無需權限提示即可執行它們。這些包括 `ls`、`cat`、`head`、`tail`、`grep`、`find`、`wc`、`diff`、`stat`、`du`、`cd` 和 `git` 的唯讀形式。該集合不可設定;若要要求其中一個命令的提示,請為其新增 `ask` 或 `deny` 規則。

138 

139對於每個旗標都是唯讀的命令,允許未引用的 glob 模式,所以 `ls *.ts` 和 `wc -l src/*.py` 無需提示即可執行。具有寫入能力或執行能力旗標的命令,如 `find`、`sort`、`sed` 和 `git`,在存在未引用的 glob 時仍會提示,因為 glob 可能會擴展為像 `-delete` 這樣的旗標。

140 

141`cd` 進入工作目錄或 [additional directory](#working-directories) 內的路徑也是唯讀的。像 `cd packages/api && ls` 這樣的複合命令在每個部分都符合時無需提示即可執行。在一個複合命令中結合 `cd` 和 `git` 始終提示,無論目標目錄如何。

142 

143<Warning>

144 嘗試限制命令引數的 Bash 權限模式很脆弱。例如,`Bash(curl http://github.com/ *)` 旨在將 curl 限制為 GitHub URL,但不會符合以下變化:

145 

146 * URL 前的選項:`curl -X GET http://github.com/...`

147 * 不同的協定:`curl https://github.com/...`

148 * 重新導向:`curl -L http://bit.ly/xyz`(重新導向到 github)

149 * 變數:`URL=http://github.com && curl $URL`

150 * 額外空格:`curl http://github.com`

151 

152 為了更可靠的 URL 篩選,請考慮:

153 

154 * **限制 Bash 網路工具**:使用 deny 規則阻止 `curl`、`wget` 和類似命令,然後使用 WebFetch 工具搭配 `WebFetch(domain:github.com)` 權限以允許的網域

155 * **使用 PreToolUse hooks**:實作一個 hook 來驗證 Bash 命令中的 URL 並阻止不允許的網域

156 * 透過 CLAUDE.md 指示 Claude Code 關於您允許的 curl 模式

157 

158 請注意,單獨使用 WebFetch 不會防止網路存取。如果允許 Bash,Claude 仍然可以使用 `curl`、`wget` 或其他工具來存取任何 URL。

159</Warning>

160 

161### PowerShell

162 

163PowerShell 權限規則使用與 Bash 規則相同的形式。使用 `*` 的萬用字元在任何位置符合,`:*` 後綴等同於尾部 ` *`,而裸 `PowerShell` 或 `PowerShell(*)` 符合每個命令。此設定允許 `Get-ChildItem` 和 `git commit` 命令,同時阻止 `Remove-Item`:

164 

165```json theme={null}

166{

167 "permissions": {

168 "allow": [

169 "PowerShell(Get-ChildItem *)",

170 "PowerShell(git commit *)"

171 ],

172 "deny": [

173 "PowerShell(Remove-Item *)"

174 ]

175 }

176}

177```

178 

179常見別名在符合前會被正規化。為 cmdlet 名稱編寫的規則也符合其別名,所以 `PowerShell(Get-ChildItem *)` 符合 `gci`、`ls` 和 `dir`。符合不區分大小寫。

180 

181Claude Code 解析 PowerShell AST 並獨立檢查複合命令中的每個命令。管道運算子 `|`、陳述式分隔符 `;` 和在 PowerShell 7+ 上的鏈運算子 `&&` 和 `||` 將複合命令分割為子命令。規則必須符合每個子命令才能允許複合命令。

182 

183### Read 和 Edit

184 

185`Edit` 規則適用於所有編輯檔案的內建工具。Claude 會盡力嘗試將 `Read` 規則應用於所有讀取檔案的內建工具,如 Grep 和 Glob。

186 

187<Warning>

188 Read 和 Edit deny 規則適用於 Claude 的內建檔案工具,不適用於 Bash 子程序。`Read(./.env)` deny 規則會阻止 Read 工具,但不會防止 Bash 中的 `cat .env`。為了進行作業系統級別的強制執行,以阻止所有程序存取路徑,請 [enable the sandbox](/zh-TW/sandboxing)。

189</Warning>

190 

191Read 和 Edit 規則都遵循 [gitignore](https://git-scm.com/docs/gitignore) 規格,具有四種不同的模式類型:

192 

193| 模式 | 意義 | 範例 | 符合 |

194| ----------------- | ------------------ | -------------------------------- | ------------------------------ |

195| `//path` | 來自檔案系統根目錄的**絕對**路徑 | `Read(//Users/alice/secrets/**)` | `/Users/alice/secrets/**` |

196| `~/path` | 來自**主目錄**的路徑 | `Read(~/Documents/*.pdf)` | `/Users/alice/Documents/*.pdf` |

197| `/path` | **相對於專案根目錄**的路徑 | `Edit(/src/**/*.ts)` | `<project root>/src/**/*.ts` |

198| `path` 或 `./path` | **相對於目前目錄**的路徑 | `Read(*.env)` | `<cwd>/*.env` |

199 

200<Warning>

201 像 `/Users/alice/file` 這樣的模式不是絕對路徑。它相對於專案根目錄。使用 `//Users/alice/file` 表示絕對路徑。

202</Warning>

203 

204在 Windows 上,路徑在符合前會被正規化為 POSIX 形式。`C:\Users\alice` 變成 `/c/Users/alice`,所以使用 `//c/**/.env` 來符合該磁碟上任何位置的 `.env` 檔案。若要符合所有磁碟,請使用 `//**/.env`。

205 

206範例:

207 

208* `Edit(/docs/**)`: 編輯 `<project>/docs/` 中的檔案(不是 `/docs/` 也不是 `<project>/.claude/docs/`)

209* `Read(~/.zshrc)`: 讀取您主目錄的 `.zshrc`

210* `Edit(//tmp/scratch.txt)`: 編輯絕對路徑 `/tmp/scratch.txt`

211* `Read(src/**)`: 從 `<current-directory>/src/` 讀取

212 

213<Note>

214 在 gitignore 模式中,`*` 符合單一目錄中的檔案,而 `**` 遞迴符合目錄。若要允許所有檔案存取,請使用不帶括號的工具名稱:`Read`、`Edit` 或 `Write`。

215</Note>

216 

217當 Claude 存取符號連結時,權限規則檢查兩個路徑:符號連結本身和它解析到的檔案。Allow 和 deny 規則對該對的處理方式不同:allow 規則回退到提示您,而 deny 規則直接阻止。

218 

219* **Allow 規則**:僅在符號連結路徑及其目標都符合時適用。允許目錄內的符號連結指向外部仍會提示您。

220* **Deny 規則**:在符號連結路徑或其目標符合時適用。指向被拒絕檔案的符號連結本身被拒絕。

221 

222例如,使用 `Read(./project/**)` 允許和 `Read(~/.ssh/**)` 拒絕,位於 `./project/key` 指向 `~/.ssh/id_rsa` 的符號連結被阻止:目標未通過 allow 規則且符合 deny 規則。

223 

224### WebFetch

225 

226* `WebFetch(domain:example.com)` 符合對 example.com 的擷取請求

227 

228### MCP

229 

230* `mcp__puppeteer` 符合由 `puppeteer` 伺服器提供的任何工具(在 Claude Code 中設定的名稱)

231* `mcp__puppeteer__*` 萬用字元語法,也符合來自 `puppeteer` 伺服器的所有工具

232* `mcp__puppeteer__puppeteer_navigate` 符合由 `puppeteer` 伺服器提供的 `puppeteer_navigate` 工具

233 

234### Agent(subagents)

235 

236使用 `Agent(AgentName)` 規則來控制 Claude 可以使用哪些 [subagents](/zh-TW/sub-agents):

237 

238* `Agent(Explore)` 符合 Explore subagent

239* `Agent(Plan)` 符合 Plan subagent

240* `Agent(my-custom-agent)` 符合名為 `my-custom-agent` 的自訂 subagent

241 

242將這些規則新增到您設定中的 `deny` 陣列,或使用 `--disallowedTools` CLI 旗標來停用特定代理。若要停用 Explore 代理:

243 

244```json theme={null}

245{

246 "permissions": {

247 "deny": ["Agent(Explore)"]

248 }

249}

250```

251 

252## 使用 hooks 擴展權限

253 

254[Claude Code hooks](/zh-TW/hooks-guide) 提供了一種方式來註冊自訂 shell 命令,以在執行時執行權限評估。當 Claude Code 進行工具呼叫時,PreToolUse hooks 在權限提示之前執行。hook 輸出可以拒絕工具呼叫、強制提示或跳過提示以讓呼叫繼續進行。

255 

256Hook 決定不會繞過權限規則。Deny 和 ask 規則在 hook 返回 `"allow"` 或 `"ask"` 後仍會被評估,因此符合的 deny 規則仍會阻止呼叫,符合的 ask 規則即使在 hook 返回 `"allow"` 或 `"ask"` 時仍會提示。這保留了 [Manage permissions](#manage-permissions) 中描述的 deny 優先順序,包括在受管理設定中設定的 deny 規則。

257 

258阻止 hook 也優先於 allow 規則。以代碼 2 退出的 hook 會在評估權限規則之前停止工具呼叫,因此即使 allow 規則會允許呼叫,該阻止也會適用。若要執行所有 Bash 命令而無需提示,除了您想要阻止的少數幾個,請將 `"Bash"` 新增到您的 allow 清單,並註冊一個 PreToolUse hook 來拒絕那些特定命令。請參閱 [Block edits to protected files](/zh-TW/hooks-guide#block-edits-to-protected-files) 以取得您可以調整的 hook 指令碼。

259 

260## 工作目錄

261 

262根據預設,Claude 可以存取啟動它的目錄中的檔案。您可以擴展此存取:

263 

264* **在啟動期間**:使用 `--add-dir <path>` CLI 引數

265* **在工作階段期間**:使用 `/add-dir` 命令

266* **持久設定**:新增到 [settings files](/zh-TW/settings#settings-files) 中的 `additionalDirectories`

267 

268其他目錄中的檔案遵循與原始工作目錄相同的權限規則:它們變成可讀的而無需提示,檔案編輯權限遵循目前的權限模式。

269 

270### 其他目錄授予檔案存取權,而非設定

271 

272新增目錄會擴展 Claude 可以讀取和編輯檔案的位置。它不會使該目錄成為完整的設定根目錄:大多數 `.claude/` 設定不會從其他目錄發現,儘管有幾種類型作為例外被載入。

273 

274以下設定類型從 `--add-dir` 目錄載入:

275 

276| 設定 | 從 `--add-dir` 載入 |

277| :----------------------------------------------------------------- | :----------------------------------------------------------------------------------------------- |

278| `.claude/skills/` 中的 [Skills](/zh-TW/skills) | 是,具有即時重新載入 |

279| `.claude/settings.json` 中的外掛設定 | 僅 `enabledPlugins` 和 `extraKnownMarketplaces` |

280| [CLAUDE.md](/zh-TW/memory) 檔案、`.claude/rules/` 和 `CLAUDE.local.md` | 僅當設定 `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1` 時。`CLAUDE.local.md` 另外需要 `local` 設定來源,預設啟用 |

281 

282其他所有內容,包括 subagents、命令、輸出樣式、hooks 和其他設定,僅從目前工作目錄及其父目錄、您在 `~/.claude/` 的使用者目錄和受管理設定發現。若要在專案間共享該設定,請使用以下方法之一:

283 

284* **使用者級別設定**:將檔案放在 `~/.claude/agents/`、`~/.claude/output-styles/` 或 `~/.claude/settings.json` 中,使其在每個專案中可用

285* **外掛**:將設定打包並分發為 [plugin](/zh-TW/plugins),供團隊安裝

286* **從設定目錄啟動**:從包含您想要的 `.claude/` 設定的目錄執行 Claude Code

287 

288## 權限如何與沙箱互動

289 

290權限和 [sandboxing](/zh-TW/sandboxing) 是互補的安全層:

291 

292* **權限**控制 Claude Code 可以使用哪些工具以及它可以存取哪些檔案或網域。它們適用於所有工具(Bash、Read、Edit、WebFetch、MCP 和其他)。

293* **沙箱**提供作業系統級別的強制執行,限制 Bash 工具的檔案系統和網路存取。它僅適用於 Bash 命令及其子程序。

294 

295使用兩者進行深度防禦:

296 

297* 權限 deny 規則阻止 Claude 甚至嘗試存取受限資源

298* 沙箱限制防止 Bash 命令到達定義邊界外的資源,即使提示注入繞過 Claude 的決策制定

299* 沙箱中的檔案系統限制使用 Read 和 Edit deny 規則,而不是單獨的沙箱設定

300* 網路限制結合 WebFetch 權限規則與沙箱的 `allowedDomains` 和 `deniedDomains` 清單

301 

302當沙箱啟用 `autoAllowBashIfSandboxed: true`(預設值)時,沙箱化 Bash 命令無需提示即可執行,即使您的權限包括 `ask: Bash(*)`。沙箱邊界替代每個命令提示。明確的 deny 規則仍然適用,以及針對 `/`、您的主目錄或其他關鍵系統路徑的 `rm` 或 `rmdir` 命令仍然會觸發提示。請參閱 [sandbox modes](/zh-TW/sandboxing#sandbox-modes) 以變更此行為。

303 

304## 受管理設定

305 

306對於需要集中控制 Claude Code 設定的組織,管理員可以部署無法被使用者或專案設定覆蓋的受管理設定。這些原則設定遵循與一般設定檔案相同的格式,可以透過 MDM/OS 級別原則、受管理設定檔案或 [server-managed settings](/zh-TW/server-managed-settings) 傳遞。請參閱 [settings files](/zh-TW/settings#settings-files) 以了解傳遞機制和檔案位置。

307 

308### 僅受管理的設定

309 

310以下設定僅在受管理設定中有效。將它們放在使用者或專案設定檔案中沒有效果。

311 

312| 設定 | 描述 |

313| :--------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

314| `allowedChannelPlugins` | 可能推送訊息的頻道外掛的允許清單。設定時替換預設 Anthropic 允許清單。需要 `channelsEnabled: true`。請參閱 [Restrict which channel plugins can run](/zh-TW/channels#restrict-which-channel-plugins-can-run) |

315| `allowManagedHooksOnly` | 當為 `true` 時,僅載入受管理 hooks、SDK hooks 和在受管理設定 `enabledPlugins` 中強制啟用的外掛中的 hooks。使用者、專案和所有其他外掛 hooks 被阻止 |

316| `allowManagedMcpServersOnly` | 當為 `true` 時,僅尊重受管理設定中的 `allowedMcpServers`。`deniedMcpServers` 仍然從所有來源合併。請參閱 [Managed MCP configuration](/zh-TW/mcp#managed-mcp-configuration) |

317| `allowManagedPermissionRulesOnly` | 當為 `true` 時,防止使用者和專案設定定義 `allow`、`ask` 或 `deny` 權限規則。僅套用受管理設定中的規則 |

318| `blockedMarketplaces` | 市場來源的封鎖清單。在下載前檢查被封鎖的來源,因此它們永遠不會接觸檔案系統。請參閱 [managed marketplace restrictions](/zh-TW/plugin-marketplaces#managed-marketplace-restrictions) |

319| `channelsEnabled` | 允許 Team 和 Enterprise 使用者使用 [channels](/zh-TW/channels)。未設定或 `false` 會阻止頻道訊息傳遞,無論使用者傳遞什麼給 `--channels` |

320| `forceRemoteSettingsRefresh` | 當為 `true` 時,阻止 CLI 啟動直到遠端受管理設定被新鮮擷取,如果擷取失敗則退出。請參閱 [fail-closed enforcement](/zh-TW/server-managed-settings#enforce-fail-closed-startup) |

321| `pluginTrustMessage` | 自訂訊息,附加到安裝前顯示的外掛信任警告 |

322| `sandbox.filesystem.allowManagedReadPathsOnly` | 當為 `true` 時,僅尊重受管理設定中的 `filesystem.allowRead` 路徑。`denyRead` 仍然從所有來源合併 |

323| `sandbox.network.allowManagedDomainsOnly` | 當為 `true` 時,僅尊重來自受管理設定的 `allowedDomains` 和 `WebFetch(domain:...)` allow 規則。非允許的網域會自動被阻止,無需提示使用者。被拒絕的網域仍然從所有來源合併 |

324| `strictKnownMarketplaces` | 控制使用者可以新增和安裝外掛的外掛市場來源。請參閱 [managed marketplace restrictions](/zh-TW/plugin-marketplaces#managed-marketplace-restrictions) |

325| `wslInheritsWindowsSettings` | 當在 Windows HKLM 登錄機碼或 `C:\Program Files\ClaudeCode\managed-settings.json` 中為 `true` 時,WSL 從 Windows 原則鏈以及 `/etc/claude-code` 讀取受管理設定。請參閱 [Settings files](/zh-TW/settings#settings-files) |

326 

327`disableBypassPermissionsMode` 通常放在受管理設定中以強制執行組織原則,但它可以從任何範圍工作。使用者可以在自己的設定中設定它以鎖定自己的繞過模式。

328 

329<Note>

330 [Remote Control](/zh-TW/remote-control) 和 [web sessions](/zh-TW/claude-code-on-the-web) 的存取不由受管理設定金鑰控制。在 Team 和 Enterprise 方案上,管理員在 [Claude Code admin settings](https://claude.ai/admin-settings/claude-code) 中啟用或停用這些功能。

331</Note>

332 

333## 設定優先順序

334 

335權限規則遵循與所有其他 Claude Code 設定相同的 [settings precedence](/zh-TW/settings#settings-precedence):

336 

3371. **受管理設定**:無法被任何其他級別覆蓋,包括命令列引數

3382. **命令列引數**:臨時工作階段覆蓋

3393. **本機專案設定** (`.claude/settings.local.json`)

3404. **共用專案設定** (`.claude/settings.json`)

3415. **使用者設定** (`~/.claude/settings.json`)

342 

343如果工具在任何級別被拒絕,沒有其他級別可以允許它。例如,受管理設定 deny 無法被 `--allowedTools` 覆蓋,`--disallowedTools` 可以新增超出受管理設定定義的限制。

344 

345如果權限在使用者設定中被允許但在專案設定中被拒絕,專案設定優先,權限被阻止。

346 

347## 範例設定

348 

349此 [repository](https://github.com/anthropics/claude-code/tree/main/examples/settings) 包含常見部署情境的入門設定設定。使用這些作為起點並根據您的需求進行調整。

350 

351## 另請參閱

352 

353* [Settings](/zh-TW/settings):完整設定參考,包括權限設定表

354* [Configure auto mode](/zh-TW/auto-mode-config):告訴 auto mode 分類器您的組織信任哪些基礎設施

355* [Sandboxing](/zh-TW/sandboxing):Bash 命令的作業系統級別檔案系統和網路隔離

356* [Authentication](/zh-TW/authentication):設定使用者對 Claude Code 的存取

357* [Security](/zh-TW/security):安全防護措施和最佳實踐

358* [Hooks](/zh-TW/hooks-guide):自動化工作流程並擴展權限評估

platforms.md +78 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 平台和整合

6 

7> 選擇在何處執行 Claude Code 以及要連接什麼。比較 CLI、Desktop、VS Code、JetBrains、Web 和 Chrome、Slack 和 CI/CD 等整合。

8 

9Claude Code 在各處執行相同的底層引擎,但每個介面都針對不同的工作方式進行了調整。此頁面幫助您為工作流程選擇合適的平台,並連接您已經使用的工具。

10 

11## 在何處執行 Claude Code

12 

13根據您喜歡的工作方式和專案所在位置選擇平台。

14 

15| 平台 | 最適合 | 您將獲得 |

16| :----------------------------------- | :------------------------------------------------ | :--------------------------------------------------------------------------------------------------------------------------------- |

17| [CLI](/zh-TW/quickstart) | 終端工作流程、指令碼、遠端伺服器 | 完整功能集、[Agent SDK](/zh-TW/headless)、第三方提供商 |

18| [Desktop](/zh-TW/desktop) | 視覺審查、並行會話、託管設定 | Diff 檢視器、應用程式預覽、Pro 和 Max 上的[電腦使用](/zh-TW/desktop#let-claude-use-your-computer)和 [Dispatch](/zh-TW/desktop#sessions-from-dispatch) |

19| [VS Code](/zh-TW/vs-code) | 在 VS Code 內工作而無需切換到終端 | 內聯 diff、整合終端、檔案上下文 |

20| [JetBrains](/zh-TW/jetbrains) | 在 IntelliJ、PyCharm、WebStorm 或其他 JetBrains IDE 內工作 | Diff 檢視器、選擇共享、終端會話 |

21| [Web](/zh-TW/claude-code-on-the-web) | 不需要太多操控的長時間執行任務,或應該在您離線時繼續進行的工作 | Anthropic 託管雲端、在您斷開連接後繼續 |

22 

23CLI 是終端原生工作的最完整介面:指令碼、第三方提供商和 Agent SDK 僅限 CLI。Desktop 和 IDE 擴充功能用視覺審查和更緊密的編輯器整合來交換一些僅限 CLI 的功能。Web 在 Anthropic 的雲端中執行,因此任務在您斷開連接後會繼續進行。

24 

25您可以在同一專案上混合使用介面。配置、專案記憶體和 MCP 伺服器在本地介面之間共享。

26 

27## 連接您的工具

28 

29整合讓 Claude 與程式碼庫外的服務協作。

30 

31| 整合 | 它的作用 | 用途 |

32| :-------------------------------------- | :----------------------------- | :----------------------------- |

33| [Chrome](/zh-TW/chrome) | 使用您已登入的會話控制您的瀏覽器 | 測試 Web 應用程式、填寫表單、自動化沒有 API 的網站 |

34| [GitHub Actions](/zh-TW/github-actions) | 在您的 CI 管道中執行 Claude | 自動化 PR 審查、問題分類、排程維護 |

35| [GitLab CI/CD](/zh-TW/gitlab-ci-cd) | 與 GitHub Actions 相同,但用於 GitLab | GitLab 上的 CI 驅動自動化 |

36| [Code Review](/zh-TW/code-review) | 自動審查每個 PR | 在人工審查之前捕捉錯誤 |

37| [Slack](/zh-TW/slack) | 回應您的頻道中的 `@Claude` 提及 | 將錯誤報告轉換為團隊聊天中的拉取請求 |

38 

39對於此處未列出的整合,[MCP 伺服器](/zh-TW/mcp)和[連接器](/zh-TW/desktop#connect-external-tools)讓您連接幾乎任何東西:Linear、Notion、Google Drive 或您自己的內部 API。

40 

41## 當您遠離終端時工作

42 

43Claude Code offers several ways to work when you're not at your terminal. They differ in what triggers the work, where Claude runs, and how much you need to set up.

44 

45| | Trigger | Claude runs on | Setup | Best for |

46| :--------------------------------------------- | :--------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------ |

47| [Dispatch](/en/desktop#sessions-from-dispatch) | Message a task from the Claude mobile app | Your machine (Desktop) | [Pair the mobile app with Desktop](https://support.claude.com/en/articles/13947068) | Delegating work while you're away, minimal setup |

48| [Remote Control](/en/remote-control) | Drive a running session from [claude.ai/code](https://claude.ai/code) or the Claude mobile app | Your machine (CLI or VS Code) | Run `claude remote-control` | Steering in-progress work from another device |

49| [Channels](/en/channels) | Push events from a chat app like Telegram or Discord, or your own server | Your machine (CLI) | [Install a channel plugin](/en/channels#quickstart) or [build your own](/en/channels-reference) | Reacting to external events like CI failures or chat messages |

50| [Slack](/en/slack) | Mention `@Claude` in a team channel | Anthropic cloud | [Install the Slack app](/en/slack#setting-up-claude-code-in-slack) with [Claude Code on the web](/en/claude-code-on-the-web) enabled | PRs and reviews from team chat |

51| [Scheduled tasks](/en/scheduled-tasks) | Set a schedule | [CLI](/en/scheduled-tasks), [Desktop](/en/desktop-scheduled-tasks), or [cloud](/en/routines) | Pick a frequency | Recurring automation like daily reviews |

52 

53如果您不確定從何處開始,[安裝 CLI](/zh-TW/quickstart) 並在專案目錄中執行它。如果您不想使用終端,[Desktop](/zh-TW/desktop-quickstart) 為您提供相同的引擎和圖形介面。

54 

55## 相關資源

56 

57### 平台

58 

59* [CLI 快速入門](/zh-TW/quickstart):在終端中安裝並執行您的第一個命令

60* [Desktop](/zh-TW/desktop):視覺 diff 審查、並行會話、電腦使用和 Dispatch

61* [VS Code](/zh-TW/vs-code):編輯器內的 Claude Code 擴充功能

62* [JetBrains](/zh-TW/jetbrains):IntelliJ、PyCharm 和其他 JetBrains IDE 的擴充功能

63* [Web 上的 Claude Code](/zh-TW/claude-code-on-the-web):在您斷開連接時繼續執行的雲端會話

64 

65### 整合

66 

67* [Chrome](/zh-TW/chrome):使用您已登入的會話自動化瀏覽器任務

68* [GitHub Actions](/zh-TW/github-actions):在您的 CI 管道中執行 Claude

69* [GitLab CI/CD](/zh-TW/gitlab-ci-cd):GitLab 的相同功能

70* [Code Review](/zh-TW/code-review):每個拉取請求上的自動審查

71* [Slack](/zh-TW/slack):從團隊聊天發送任務,取回 PR

72 

73### 遠端存取

74 

75* [Dispatch](/zh-TW/desktop#sessions-from-dispatch):從您的手機傳送任務,它可以生成 Desktop 會話

76* [Remote Control](/zh-TW/remote-control):從您的手機或瀏覽器驅動執行中的會話

77* [Channels](/zh-TW/channels):將來自聊天應用程式或您自己的伺服器的事件推送到會話中

78* [Scheduled tasks](/zh-TW/scheduled-tasks):按定期排程執行提示

plugin-dependencies.md +153 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 限制 plugin 依賴版本

6 

7> 在 plugin 依賴上聲明版本約束,以便當上游 plugin 發佈破壞性變更時,您的 plugin 能夠繼續運作。

8 

9一個 plugin 可以通過在 `plugin.json` 或其 marketplace 條目中列出其他 plugin 來依賴它們。預設情況下,依賴會追蹤最新可用版本,因此上游版本發佈可能會在沒有警告的情況下更改您 plugin 的依賴。版本約束讓您可以將依賴保持在經過測試的版本範圍內,直到您選擇升級。

10 

11當您安裝聲明依賴的 plugin 時,Claude Code 會自動解析並安裝它們,並在安裝輸出的末尾列出已添加的依賴。如果依賴後來遺失,`/reload-plugins` 和背景 plugin 自動更新會重新安裝它,前提是其 marketplace 已在您設定的 marketplace 中。重新執行 `claude plugin install` 在依賴的 plugin 上,或使用 `claude plugin marketplace add` 新增 marketplace,也會解析任何未解決的遺失依賴。來自您尚未新增的 marketplace 的依賴將保持未解決狀態。

12 

13本指南適用於在 `plugin.json` 中聲明依賴的 plugin 作者,以及標記版本發佈的 marketplace 維護者。若要安裝具有依賴的 plugin,請參閱[發現並安裝 plugin](/zh-TW/discover-plugins)。如需完整的 manifest 架構,請參閱 [Plugins 參考](/zh-TW/plugins-reference)。

14 

15<Note>

16 依賴版本約束需要 Claude Code v2.1.110 或更新版本。

17</Note>

18 

19## 為什麼要限制依賴版本

20 

21考慮一個內部 marketplace,其中兩個團隊發佈 plugin。平台團隊維護 `secrets-vault`,這是一個包裝 secrets 後端的 MCP 伺服器。部署團隊維護 `deploy-kit`,它在部署期間調用 `secrets-vault` 來獲取認證。

22 

23`deploy-kit` 已針對 `secrets-vault` v2.1.0 進行測試。沒有版本約束的情況下,下次平台團隊標記重新命名 MCP 工具的版本發佈時,自動更新會將每個工程師的 `secrets-vault` 移至新版本,`deploy-kit` 就會損壞。

24 

25使用版本約束,`deploy-kit` 聲明它需要 `~2.1.0` 範圍內的 `secrets-vault`。安裝了 `deploy-kit` 的工程師會保持在最高匹配的 `2.1.x` 修補程式版本。部署團隊通過發佈具有更寬鬆約束的新 `deploy-kit` 版本,按照自己的時間表進行升級。

26 

27## 聲明具有版本約束的依賴

28 

29在 plugin 的 `.claude-plugin/plugin.json` 的 `dependencies` 陣列中列出依賴。每個條目要麼是 plugin 名稱,要麼是具有版本約束的物件。

30 

31以下 manifest 聲明了一個未版本化的依賴和一個受約束的依賴:

32 

33```json .claude-plugin/plugin.json theme={null}

34{

35 "name": "deploy-kit",

36 "version": "3.1.0",

37 "dependencies": [

38 "audit-logger",

39 { "name": "secrets-vault", "version": "~2.1.0" }

40 ]

41}

42```

43 

44一個條目可以是只包含 plugin 名稱的純字符串,如上例中的 `"audit-logger"`,它依賴於該 plugin 的 marketplace 提供的任何版本。為了獲得更多控制,請使用具有以下欄位的物件:

45 

46| 欄位 | 類型 | 描述 |

47| :------------ | :----- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

48| `name` | string | Plugin 名稱。在與聲明 plugin 相同的 marketplace 內解析。必需。 |

49| `version` | string | 一個 [semver 範圍](https://github.com/npm/node-semver#ranges),例如 `~2.1.0`、`^2.0`、`>=1.4` 或 `=2.1.0`。依賴會在滿足此範圍的最高標記版本處獲取。 |

50| `marketplace` | string | 一個不同的 marketplace 來在其中解析 `name`。跨 marketplace 依賴被阻止,除非目標 marketplace 在根 marketplace 的 `marketplace.json` 中的 [`allowCrossMarketplaceDependenciesOn`](#depend-on-a-plugin-from-another-marketplace) 中列出。 |

51 

52`version` 欄位接受 Node 的 `semver` 套件支援的任何表達式,包括 caret、tilde、hyphen 和 comparator 範圍。預發佈版本(如 `2.0.0-beta.1`)被排除,除非您的範圍使用預發佈後綴(如 `^2.0.0-0`)選擇加入。

53 

54## 依賴來自另一個 marketplace 的 plugin

55 

56預設情況下,Claude Code 拒絕自動安裝位於與聲明它的 plugin 不同的 marketplace 中的依賴。這可防止一個 marketplace 無聲地從您未審查的來源拉入 plugin。

57 

58若要允許此操作,根 marketplace 的維護者將目標 marketplace 名稱添加到 `marketplace.json` 中的 `allowCrossMarketplaceDependenciesOn`。根 marketplace 是託管用戶正在安裝的 plugin 的 marketplace;只有其允許清單被查詢,因此信任不會通過中間 marketplace 鏈接。

59 

60以下 `marketplace.json` 允許 `deploy-kit` 依賴來自 `acme-shared` 的 plugin:

61 

62```json .claude-plugin/marketplace.json theme={null}

63{

64 "name": "acme-tools",

65 "owner": { "name": "Acme" },

66 "allowCrossMarketplaceDependenciesOn": ["acme-shared"],

67 "plugins": [

68 {

69 "name": "deploy-kit",

70 "source": "./deploy-kit",

71 "dependencies": [

72 { "name": "audit-logger", "marketplace": "acme-shared" }

73 ]

74 }

75 ]

76}

77```

78 

79如果欄位缺失或不包含目標 marketplace,安裝將失敗,並出現 `cross-marketplace` 錯誤,命名要設置的欄位。用戶仍然可以先手動安裝依賴,這會滿足約束而無需更改允許清單。

80 

81## 標記 plugin 版本發佈以進行版本解析

82 

83版本約束針對 marketplace 儲存庫上的 git 標籤進行解析。為了讓 Claude Code 找到依賴的可用版本,上游 plugin 的版本發佈必須使用特定的命名約定進行標記。

84 

85將每個版本發佈標記為 `{plugin-name}--v{version}`,其中 `{version}` 與該提交的 `plugin.json` 中的 `version` 欄位匹配。從 plugin 目錄中,執行:

86 

87```bash theme={null}

88claude plugin tag --push

89```

90 

91`claude plugin tag` 命令從 plugin 的清單和封閉的 marketplace 項目衍生標籤名稱。在建立標籤之前,它驗證 plugin 內容,檢查 `plugin.json` 和 marketplace 項目在版本上是否一致,要求 plugin 目錄下的工作樹乾淨,如果標籤已存在則拒絕。添加 `--dry-run` 以查看將被標記的內容而不建立它。如果您自己保持 `plugin.json` 和 marketplace 項目同步,直接執行 `git tag secrets-vault--v2.1.0` 是等效的。

92 

93plugin 名稱前綴讓一個 marketplace 儲存庫可以託管多個具有獨立版本線的 plugin。`--v` 分隔符被解析為完整 plugin 名稱上的前綴匹配,因此包含連字符的 plugin 名稱會被正確處理。

94 

95當您安裝聲明 `{ "name": "secrets-vault", "version": "~2.1.0" }` 的 plugin 時,Claude Code 會列出 marketplace 的標籤,篩選以 `secrets-vault--v` 開頭的標籤,並獲取滿足 `~2.1.0` 的最高版本。如果不存在匹配的標籤,依賴 plugin 將被禁用,並出現列出可用版本的錯誤。

96 

97已解析標籤的 semver 與 `plugin.json` 的 `version` 分開記錄,因此約束檢查使用實際獲取的標籤,即使該提交的 `plugin.json` 有過時的值。標籤解析安裝的快取目錄名稱包含 12 字元的提交 SHA 後綴,因此如果維護者強制移動標籤到不同的提交,下次安裝會獲得新的快取目錄,而不是重複使用過時的內容。

98 

99<Note>

100 對於 `npm` marketplace 來源,約束不控制獲取的版本,因為基於標籤的解析僅適用於 git 支援的來源。約束仍在載入時檢查,如果已安裝的版本不滿足它,依賴 plugin 將被禁用,並出現 `dependency-version-unsatisfied` 錯誤。

101</Note>

102 

103## 約束如何相互作用

104 

105當多個已安裝的 plugins 限制同一依賴時,Claude Code 會交集它們的範圍,並將依賴解析為滿足所有範圍的最高版本。下表顯示常見組合如何解析。

106 

107| Plugin A 要求 | Plugin B 要求 | 結果 |

108| :---------- | :---------- | :------------------------------------------------------- |

109| `^2.0` | `>=2.1` | 在最高 `2.x` 標籤處進行一次安裝,該標籤位於 `2.1.0` 或更高版本。兩個 plugins 都會載入。 |

110| `~2.1` | `~3.0` | Plugin B 的安裝失敗,出現 `range-conflict` 錯誤。Plugin A 和依賴保持原樣。 |

111| `=2.1.0` | 無 | 依賴保持在 `2.1.0`。在安裝了 Plugin A 時,自動更新會跳過較新版本。 |

112 

113自動更新會在滿足每個已安裝 plugin 範圍的最高 git 標籤處取得受約束的依賴,而不是在 marketplace 的最新版本處,因此依賴會在其允許的範圍內繼續接收更新。如果沒有標籤滿足所有範圍,更新將被跳過,跳過訊息會出現在 `/doctor` 和 `/plugin` 錯誤標籤中,並命名限制 plugin。

114 

115當您卸載最後一個限制依賴的 plugin 時,依賴不再被保持,並在下次更新時恢復追蹤其 marketplace 條目。

116 

117## 移除孤立的自動安裝依賴

118 

119自動安裝的依賴在安裝它們的 plugins 被卸載後仍會保留在磁碟上,以防您重新安裝依賴 plugin 或想要直接繼續使用依賴。若要清理它們,請執行 `claude plugin prune` 以列出不再有任何已安裝 plugin 需要的自動安裝依賴,並在確認提示後移除它們。這需要 Claude Code v2.1.121 或更新版本。

120 

121```bash theme={null}

122claude plugin prune

123```

124 

125預設情況下,prune 在用戶範圍內運作。使用 `--scope project` 或 `--scope local` 來針對不同的範圍。傳遞 `--dry-run` 以列出將被移除的內容而不更改任何內容。傳遞 `-y` 以跳過確認提示。當 stdin 或 stdout 不是終端時,prune 會列出孤立項並退出,除非傳遞了 `-y`。

126 

127若要在卸載時進行 prune,請將 `--prune` 傳遞給 `claude plugin uninstall`。移除命名的 plugin 後,Claude Code 會掃描並移除現在孤立的任何自動安裝依賴。您自己安裝的 plugins 永遠不會被 prune,只有通過另一個 plugin 的 `dependencies` 陣列自動安裝的 plugins 才會被 prune。

128 

129例如,若要卸載 `deploy-kit` 並清理它留下的依賴:

130 

131```bash theme={null}

132claude plugin uninstall deploy-kit --prune

133```

134 

135## 解析依賴錯誤

136 

137依賴問題會在 `claude plugin list`、`/plugin` 介面和 `/doctor` 中出現。受影響的 plugin 將被禁用,直到您解析錯誤。最常見的錯誤及其修復方法列在下表中。

138 

139| 錯誤 | 含義 | 如何解析 |

140| :------------------------------- | :---------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------- |

141| `dependency-unsatisfied` | 聲明的依賴未安裝,或已安裝但被禁用。 | 執行錯誤訊息中顯示的 `claude plugin install` 命令。如果依賴的 marketplace 尚未配置,請使用 `claude plugin marketplace add` 添加它,Claude Code 將自動解析依賴。如果依賴被禁用,請啟用它。 |

142| `range-conflict` | 依賴的版本要求無法組合。錯誤訊息命名原因:沒有版本滿足所有範圍、範圍不是有效的 semver 語法,或組合的範圍太複雜而無法交集。 | 卸載或更新其中一個衝突的 plugin,修復任何無效的 `version` 字符串,簡化長 `\|\|` 鏈,或要求上游作者擴寬其約束。 |

143| `dependency-version-unsatisfied` | 已安裝的依賴版本在此 plugin 的聲明範圍之外。 | 執行 `claude plugin install <dependency>@<marketplace>` 以根據所有當前約束重新解析依賴。 |

144| `no-matching-tag` | 依賴的儲存庫沒有滿足範圍的 `{name}--v*` 標籤。 | 檢查上游是否使用上述約定標記了版本發佈,或放寬您的範圍。 |

145 

146若要以程式設計方式檢查這些錯誤,請執行 `claude plugin list --json` 並讀取每個 plugin 上的 `errors` 欄位。

147 

148## 另請參閱

149 

150* [建立 plugins](/zh-TW/plugins):使用 skills、agents 和 hooks 建立 plugins

151* [建立並分發 plugin marketplace](/zh-TW/plugin-marketplaces):為您的團隊託管 plugins

152* [Plugins 參考](/zh-TW/plugins-reference#plugin-manifest-schema):完整的 `plugin.json` 架構

153* [版本管理](/zh-TW/plugins-reference#version-management):plugin 版本如何被解析並用作快取金鑰

plugin-marketplaces.md +1054 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 建立並分發 plugin marketplace

6 

7> 建立並託管 plugin marketplace,以在團隊和社群中分發 Claude Code 擴充功能。

8 

9**plugin marketplace** 是一個目錄,可讓您將 plugin 分發給他人。Marketplace 提供集中式發現、版本追蹤、自動更新,以及對多種來源類型(git 儲存庫、本機路徑等)的支援。本指南將向您展示如何建立自己的 marketplace,以與您的團隊或社群分享 plugin。

10 

11想要從現有 marketplace 安裝 plugin?請參閱[探索並安裝預先建立的 plugin](/zh-TW/discover-plugins)。

12 

13## 概述

14 

15建立並分發 marketplace 涉及:

16 

171. **建立 plugin**:使用 skills、agents、hooks、MCP servers 或 LSP servers 建立一個或多個 plugin。本指南假設您已經有要分發的 plugin;有關如何建立 plugin 的詳細資訊,請參閱[建立 plugin](/zh-TW/plugins)。

182. **建立 marketplace 檔案**:定義 `marketplace.json`,列出您的 plugin 及其位置(請參閱[建立 marketplace 檔案](#create-the-marketplace-file))。

193. **託管 marketplace**:推送到 GitHub、GitLab 或其他 git 主機(請參閱[託管並分發 marketplace](#host-and-distribute-marketplaces))。

204. **與使用者分享**:使用者使用 `/plugin marketplace add` 新增您的 marketplace 並安裝個別 plugin(請參閱[探索並安裝 plugin](/zh-TW/discover-plugins))。

21 

22一旦您的 marketplace 上線,您可以透過推送變更到您的儲存庫來更新它。使用者使用 `/plugin marketplace update` 重新整理其本機副本。

23 

24## 逐步解說:建立本機 marketplace

25 

26此範例建立一個包含一個 plugin 的 marketplace:用於程式碼審查的 `/quality-review` skill。您將建立目錄結構、新增 skill、建立 plugin manifest 和 marketplace 目錄,然後安裝並測試它。

27 

28<Steps>

29 <Step title="建立目錄結構">

30 ```bash theme={null}

31 mkdir -p my-marketplace/.claude-plugin

32 mkdir -p my-marketplace/plugins/quality-review-plugin/.claude-plugin

33 mkdir -p my-marketplace/plugins/quality-review-plugin/skills/quality-review

34 ```

35 </Step>

36 

37 <Step title="建立 skill">

38 建立 `SKILL.md` 檔案,定義 `/quality-review` skill 的功能。

39 

40 ```markdown my-marketplace/plugins/quality-review-plugin/skills/quality-review/SKILL.md theme={null}

41 ---

42 description: 檢查程式碼中的錯誤、安全性和效能問題

43 disable-model-invocation: true

44 ---

45 

46 檢查我選擇的程式碼或最近的變更,查找:

47 - 潛在的錯誤或邊界情況

48 - 安全性問題

49 - 效能問題

50 - 可讀性改進

51 

52 簡潔且可行動。

53 ```

54 </Step>

55 

56 <Step title="建立 plugin manifest">

57 建立 `plugin.json` 檔案,描述 plugin。manifest 位於 `.claude-plugin/` 目錄中。

58 

59 ```json my-marketplace/plugins/quality-review-plugin/.claude-plugin/plugin.json theme={null}

60 {

61 "name": "quality-review-plugin",

62 "description": "新增 /quality-review skill 以進行快速程式碼審查",

63 "version": "1.0.0"

64 }

65 ```

66 

67 <Note>

68 設定 `version` 表示使用者只會在您變更此欄位時收到更新,因此在每次發行時都要提升版本。如果您省略 `version` 並在 git 中託管此 marketplace,每次提交都會自動計為新版本。請參閱 [Version resolution](#version-resolution-and-release-channels) 以選擇正確的方法。

69 </Note>

70 </Step>

71 

72 <Step title="建立 marketplace 檔案">

73 建立列出您的 plugin 的 marketplace 目錄。

74 

75 ```json my-marketplace/.claude-plugin/marketplace.json theme={null}

76 {

77 "name": "my-plugins",

78 "owner": {

79 "name": "Your Name"

80 },

81 "plugins": [

82 {

83 "name": "quality-review-plugin",

84 "source": "./plugins/quality-review-plugin",

85 "description": "新增 /quality-review skill 以進行快速程式碼審查"

86 }

87 ]

88 }

89 ```

90 </Step>

91 

92 <Step title="新增並安裝">

93 新增 marketplace 並安裝 plugin。

94 

95 ```shell theme={null}

96 /plugin marketplace add ./my-marketplace

97 /plugin install quality-review-plugin@my-plugins

98 ```

99 </Step>

100 

101 <Step title="試試看">

102 在編輯器中選擇一些程式碼並執行您的新 skill。

103 

104 ```shell theme={null}

105 /quality-review

106 ```

107 </Step>

108</Steps>

109 

110若要深入瞭解 plugin 可以執行的操作,包括 hooks、agents、MCP servers 和 LSP servers,請參閱 [Plugins](/zh-TW/plugins)。

111 

112<Note>

113 **plugin 如何安裝**:當使用者安裝 plugin 時,Claude Code 會將 plugin 目錄複製到快取位置。這表示 plugin 無法使用 `../shared-utils` 之類的路徑參考其目錄外的檔案,因為這些檔案不會被複製。

114 

115 如果您需要在 plugin 之間共享檔案,請使用符號連結。有關詳細資訊,請參閱 [Plugin caching and file resolution](/zh-TW/plugins-reference#plugin-caching-and-file-resolution)。

116</Note>

117 

118## 建立 marketplace 檔案

119 

120在您的儲存庫根目錄中建立 `.claude-plugin/marketplace.json`。此檔案定義您的 marketplace 名稱、擁有者資訊以及包含其來源的 plugin 清單。

121 

122每個 plugin 項目至少需要 `name` 和 `source`(從何處取得)。有關所有可用欄位,請參閱下面的[完整架構](#marketplace-schema)。

123 

124```json theme={null}

125{

126 "name": "company-tools",

127 "owner": {

128 "name": "DevTools Team",

129 "email": "devtools@example.com"

130 },

131 "plugins": [

132 {

133 "name": "code-formatter",

134 "source": "./plugins/formatter",

135 "description": "在保存時自動格式化程式碼",

136 "version": "2.1.0",

137 "author": {

138 "name": "DevTools Team"

139 }

140 },

141 {

142 "name": "deployment-tools",

143 "source": {

144 "source": "github",

145 "repo": "company/deploy-plugin"

146 },

147 "description": "部署自動化工具"

148 }

149 ]

150}

151```

152 

153## Marketplace 架構

154 

155### 必需欄位

156 

157| 欄位 | 類型 | 描述 | 範例 |

158| :-------- | :----- | :-------------------------------------------------------------------------------------------------------- | :------------- |

159| `name` | string | Marketplace 識別碼(kebab-case,無空格)。這是公開的:使用者在安裝 plugin 時會看到它(例如,`/plugin install my-tool@your-marketplace`)。 | `"acme-tools"` |

160| `owner` | object | Marketplace 維護者資訊([請參閱下面的欄位](#owner-fields)) | |

161| `plugins` | array | 可用 plugin 的清單 | 請參閱下面 |

162 

163<Note>

164 **保留名稱**:以下 marketplace 名稱保留供 Anthropic 官方使用,第三方 marketplace 無法使用:`claude-code-marketplace`、`claude-code-plugins`、`claude-plugins-official`、`anthropic-marketplace`、`anthropic-plugins`、`agent-skills`、`knowledge-work-plugins`、`life-sciences`。模仿官方 marketplace 的名稱(如 `official-claude-plugins` 或 `anthropic-tools-v2`)也被阻止。

165</Note>

166 

167### 擁有者欄位

168 

169| 欄位 | 類型 | 必需 | 描述 |

170| :------ | :----- | :- | :--------- |

171| `name` | string | 是 | 維護者或團隊的名稱 |

172| `email` | string | 否 | 維護者的聯絡電子郵件 |

173 

174### 選用欄位

175 

176| 欄位 | 類型 | 描述 |

177| :------------------------------------ | :----- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

178| `$schema` | string | JSON Schema URL,用於編輯器自動完成和驗證。Claude Code 在載入時會忽略此欄位。 |

179| `description` | string | 簡短的 marketplace 描述 |

180| `version` | string | Marketplace 版本 |

181| `metadata.pluginRoot` | string | 前置於相對 plugin 來源路徑的基本目錄(例如,`"./plugins"` 可讓您寫入 `"source": "formatter"` 而不是 `"source": "./plugins/formatter"`) |

182| `allowCrossMarketplaceDependenciesOn` | array | 此 marketplace 中的 plugin 可能依賴的其他 marketplace。來自此處未列出的 marketplace 的相依性在安裝時被阻止。請參閱[依賴來自另一個 marketplace 的 plugin](/zh-TW/plugin-dependencies#depend-on-a-plugin-from-another-marketplace)。 |

183 

184`description` 和 `version` 也可在 `metadata` 下接受,以保持向後相容性。

185 

186## Plugin 項目

187 

188`plugins` 陣列中的每個 plugin 項目描述一個 plugin 及其位置。您可以包含 [plugin manifest 架構](/zh-TW/plugins-reference#plugin-manifest-schema)中的任何欄位(如 `description`、`version`、`author`、`commands`、`hooks` 等),加上這些 marketplace 特定欄位:`source`、`category`、`tags` 和 `strict`。

189 

190### 必需欄位

191 

192| 欄位 | 類型 | 描述 |

193| :------- | :------------- | :---------------------------------------------------------------------------------------- |

194| `name` | string | Plugin 識別碼(kebab-case,無空格)。這是公開的:使用者在安裝時會看到它(例如,`/plugin install my-plugin@marketplace`)。 |

195| `source` | string\|object | 從何處取得 plugin(請參閱下面的 [Plugin 來源](#plugin-sources)) |

196 

197### 選用 plugin 欄位

198 

199**標準中繼資料欄位:**

200 

201| 欄位 | 類型 | 描述 |

202| :------------ | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------- |

203| `description` | string | 簡短的 plugin 描述 |

204| `version` | string | Plugin 版本。如果設定(在此處或在 `plugin.json` 中),plugin 會固定到此字串,使用者只有在版本變更時才會收到更新。省略以回退到 git commit SHA。請參閱 [版本解析](#version-resolution-and-release-channels)。 |

205| `author` | object | Plugin 作者資訊(`name` 必需,`email` 選用) |

206| `homepage` | string | Plugin 首頁或文件 URL |

207| `repository` | string | 原始碼儲存庫 URL |

208| `license` | string | SPDX 授權識別碼(例如,MIT、Apache-2.0) |

209| `keywords` | array | 用於 plugin 發現和分類的標籤 |

210| `category` | string | Plugin 類別以供組織 |

211| `tags` | array | 用於可搜尋性的標籤 |

212| `strict` | boolean | 控制 `plugin.json` 是否為元件定義的權威(預設值:true)。請參閱下面的 [Strict mode](#strict-mode)。 |

213 

214**元件配置欄位:**

215 

216| 欄位 | 類型 | 描述 |

217| :----------- | :------------- | :----------------------------------- |

218| `skills` | string\|array | 包含 `<name>/SKILL.md` 的 skill 目錄的自訂路徑 |

219| `commands` | string\|array | 平面 `.md` skill 檔案或目錄的自訂路徑 |

220| `agents` | string\|array | agent 檔案的自訂路徑 |

221| `hooks` | string\|object | 自訂 hooks 配置或 hooks 檔案的路徑 |

222| `mcpServers` | string\|object | MCP server 配置或 MCP 配置的路徑 |

223| `lspServers` | string\|object | LSP server 配置或 LSP 配置的路徑 |

224 

225## Plugin 來源

226 

227Plugin 來源告訴 Claude Code 在您的 marketplace 中列出的每個個別 plugin 從何處取得。這些在 `marketplace.json` 中每個 plugin 項目的 `source` 欄位中設定。

228 

229一旦 plugin 被複製或複製到本機,它就會被複製到本機版本化 plugin 快取中,位於 `~/.claude/plugins/cache`。

230 

231| 來源 | 類型 | 欄位 | 備註 |

232| ------------ | ---------------------------- | -------------------------------- | -------------------------------------------------------------------------------- |

233| 相對路徑 | `string`(例如 `"./my-plugin"`) | 無 | marketplace 儲存庫內的本機目錄。必須以 `./` 開頭。相對於 marketplace 根目錄解析,而不是 `.claude-plugin/` 目錄 |

234| `github` | object | `repo`、`ref?`、`sha?` | |

235| `url` | object | `url`、`ref?`、`sha?` | Git URL 來源 |

236| `git-subdir` | object | `url`、`path`、`ref?`、`sha?` | git 儲存庫內的子目錄。稀疏複製以最小化大型 monorepo 的頻寬 |

237| `npm` | object | `package`、`version?`、`registry?` | 透過 `npm install` 安裝 |

238 

239<Note>

240 **Marketplace 來源與 plugin 來源**:這些是控制不同事物的不同概念。

241 

242 * **Marketplace 來源** — 從何處取得 `marketplace.json` 目錄本身。在使用者執行 `/plugin marketplace add` 或在 `extraKnownMarketplaces` 設定中設定。支援 `ref`(分支/標籤)但不支援 `sha`。

243 * **Plugin 來源** — 從何處取得 marketplace 中列出的個別 plugin。在 `marketplace.json` 內每個 plugin 項目的 `source` 欄位中設定。支援 `ref`(分支/標籤)和 `sha`(確切提交)。

244 

245 例如,託管在 `acme-corp/plugin-catalog`(marketplace 來源)的 marketplace 可以列出從 `acme-corp/code-formatter`(plugin 來源)取得的 plugin。marketplace 來源和 plugin 來源指向不同的儲存庫,並獨立固定。

246</Note>

247 

248### 相對路徑

249 

250對於同一儲存庫中的 plugin,使用以 `./` 開頭的路徑:

251 

252```json theme={null}

253{

254 "name": "my-plugin",

255 "source": "./plugins/my-plugin"

256}

257```

258 

259路徑相對於 marketplace 根目錄解析,即包含 `.claude-plugin/` 的目錄。在上面的範例中,`./plugins/my-plugin` 指向 `<repo>/plugins/my-plugin`,即使 `marketplace.json` 位於 `<repo>/.claude-plugin/marketplace.json`。不要使用 `../` 參考 marketplace 根目錄外的路徑。

260 

261<Note>

262 相對路徑僅在使用者透過 Git(GitHub、GitLab 或 git URL)新增您的 marketplace 時有效。如果使用者透過直接 URL 新增您的 marketplace 到 `marketplace.json` 檔案,相對路徑將無法正確解析。對於基於 URL 的分發,請改用 GitHub、npm 或 git URL 來源。有關詳細資訊,請參閱[疑難排解](#plugins-with-relative-paths-fail-in-url-based-marketplaces)。

263</Note>

264 

265### GitHub 儲存庫

266 

267```json theme={null}

268{

269 "name": "github-plugin",

270 "source": {

271 "source": "github",

272 "repo": "owner/plugin-repo"

273 }

274}

275```

276 

277您可以固定到特定分支、標籤或提交:

278 

279```json theme={null}

280{

281 "name": "github-plugin",

282 "source": {

283 "source": "github",

284 "repo": "owner/plugin-repo",

285 "ref": "v2.0.0",

286 "sha": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0"

287 }

288}

289```

290 

291| 欄位 | 類型 | 描述 |

292| :----- | :----- | :------------------------------- |

293| `repo` | string | 必需。`owner/repo` 格式的 GitHub 儲存庫 |

294| `ref` | string | 選用。Git 分支或標籤(預設為儲存庫預設分支) |

295| `sha` | string | 選用。完整的 40 字元 git 提交 SHA 以固定到確切版本 |

296 

297### Git 儲存庫

298 

299```json theme={null}

300{

301 "name": "git-plugin",

302 "source": {

303 "source": "url",

304 "url": "https://gitlab.com/team/plugin.git"

305 }

306}

307```

308 

309您可以固定到特定分支、標籤或提交:

310 

311```json theme={null}

312{

313 "name": "git-plugin",

314 "source": {

315 "source": "url",

316 "url": "https://gitlab.com/team/plugin.git",

317 "ref": "main",

318 "sha": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0"

319 }

320}

321```

322 

323| 欄位 | 類型 | 描述 |

324| :---- | :----- | :--------------------------------------------------------------------------------------------------- |

325| `url` | string | 必需。完整的 git 儲存庫 URL(`https://` 或 `git@`)。`.git` 後綴是選用的,因此 Azure DevOps 和 AWS CodeCommit URL 不含後綴也可以運作 |

326| `ref` | string | 選用。Git 分支或標籤(預設為儲存庫預設分支) |

327| `sha` | string | 選用。完整的 40 字元 git 提交 SHA 以固定到確切版本 |

328 

329### Git 子目錄

330 

331使用 `git-subdir` 指向位於 git 儲存庫子目錄內的 plugin。Claude Code 使用稀疏、部分複製來僅取得子目錄,最小化大型 monorepo 的頻寬。

332 

333```json theme={null}

334{

335 "name": "my-plugin",

336 "source": {

337 "source": "git-subdir",

338 "url": "https://github.com/acme-corp/monorepo.git",

339 "path": "tools/claude-plugin"

340 }

341}

342```

343 

344您可以固定到特定分支、標籤或提交:

345 

346```json theme={null}

347{

348 "name": "my-plugin",

349 "source": {

350 "source": "git-subdir",

351 "url": "https://github.com/acme-corp/monorepo.git",

352 "path": "tools/claude-plugin",

353 "ref": "v2.0.0",

354 "sha": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0"

355 }

356}

357```

358 

359`url` 欄位也接受 GitHub 簡寫(`owner/repo`)或 SSH URL(`git@github.com:owner/repo.git`)。

360 

361| 欄位 | 類型 | 描述 |

362| :----- | :----- | :-------------------------------------------------- |

363| `url` | string | 必需。Git 儲存庫 URL、GitHub `owner/repo` 簡寫或 SSH URL |

364| `path` | string | 必需。儲存庫內包含 plugin 的子目錄路徑(例如,`"tools/claude-plugin"`) |

365| `ref` | string | 選用。Git 分支或標籤(預設為儲存庫預設分支) |

366| `sha` | string | 選用。完整的 40 字元 git 提交 SHA 以固定到確切版本 |

367 

368### npm 套件

369 

370作為 npm 套件分發的 plugin 使用 `npm install` 安裝。這適用於公開 npm 登錄表或您的團隊託管的任何私人登錄表上的任何套件。

371 

372```json theme={null}

373{

374 "name": "my-npm-plugin",

375 "source": {

376 "source": "npm",

377 "package": "@acme/claude-plugin"

378 }

379}

380```

381 

382若要固定到特定版本,請新增 `version` 欄位:

383 

384```json theme={null}

385{

386 "name": "my-npm-plugin",

387 "source": {

388 "source": "npm",

389 "package": "@acme/claude-plugin",

390 "version": "2.1.0"

391 }

392}

393```

394 

395若要從私人或內部登錄表安裝,請新增 `registry` 欄位:

396 

397```json theme={null}

398{

399 "name": "my-npm-plugin",

400 "source": {

401 "source": "npm",

402 "package": "@acme/claude-plugin",

403 "version": "^2.0.0",

404 "registry": "https://npm.example.com"

405 }

406}

407```

408 

409| 欄位 | 類型 | 描述 |

410| :--------- | :----- | :--------------------------------------------- |

411| `package` | string | 必需。套件名稱或範圍套件(例如,`@org/plugin`) |

412| `version` | string | 選用。版本或版本範圍(例如,`2.1.0`、`^2.0.0`、`~1.5.0`) |

413| `registry` | string | 選用。自訂 npm 登錄表 URL。預設為系統 npm 登錄表(通常為 npmjs.org) |

414 

415### 進階 plugin 項目

416 

417此範例顯示使用許多選用欄位的 plugin 項目,包括 commands、agents、hooks 和 MCP servers 的自訂路徑:

418 

419```json theme={null}

420{

421 "name": "enterprise-tools",

422 "source": {

423 "source": "github",

424 "repo": "company/enterprise-plugin"

425 },

426 "description": "企業工作流程自動化工具",

427 "version": "2.1.0",

428 "author": {

429 "name": "Enterprise Team",

430 "email": "enterprise@example.com"

431 },

432 "homepage": "https://docs.example.com/plugins/enterprise-tools",

433 "repository": "https://github.com/company/enterprise-plugin",

434 "license": "MIT",

435 "keywords": ["enterprise", "workflow", "automation"],

436 "category": "productivity",

437 "commands": [

438 "./commands/core/",

439 "./commands/enterprise/",

440 "./commands/experimental/preview.md"

441 ],

442 "agents": ["./agents/security-reviewer.md", "./agents/compliance-checker.md"],

443 "hooks": {

444 "PostToolUse": [

445 {

446 "matcher": "Write|Edit",

447 "hooks": [

448 {

449 "type": "command",

450 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh"

451 }

452 ]

453 }

454 ]

455 },

456 "mcpServers": {

457 "enterprise-db": {

458 "command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server",

459 "args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"]

460 }

461 },

462 "strict": false

463}

464```

465 

466需要注意的關鍵事項:

467 

468* **`commands` 和 `agents`**:您可以指定多個目錄或個別檔案。路徑相對於 plugin 根目錄。

469* **`${CLAUDE_PLUGIN_ROOT}`**:在 hooks 和 MCP server 配置中使用此變數來參考 plugin 安裝目錄內的檔案。這是必要的,因為 plugin 在安裝時被複製到快取位置。對於應在 plugin 更新後保留的相依性或狀態,請改用 [`${CLAUDE_PLUGIN_DATA}`](/zh-TW/plugins-reference#persistent-data-directory)。

470* **`strict: false`**:由於此設定為 false,plugin 不需要自己的 `plugin.json`。marketplace 項目定義所有內容。請參閱下面的 [Strict mode](#strict-mode)。

471 

472### Strict mode

473 

474`strict` 欄位控制 `plugin.json` 是否為元件定義(skills、agents、hooks、MCP servers、輸出樣式)的權威。

475 

476| 值 | 行為 |

477| :--------- | :--------------------------------------------------------------------- |

478| `true`(預設) | `plugin.json` 是權威。marketplace 項目可以用額外的元件補充它,兩個來源都會合併。 |

479| `false` | marketplace 項目是完整定義。如果 plugin 也有宣告元件的 `plugin.json`,那就是衝突,plugin 無法載入。 |

480 

481**何時使用每種模式:**

482 

483* **`strict: true`**:plugin 有自己的 `plugin.json` 並管理自己的元件。marketplace 項目可以在頂部新增額外的 skills 或 hooks。這是預設值,適用於大多數 plugin。

484* **`strict: false`**:marketplace 運營商想要完全控制。plugin 儲存庫提供原始檔案,marketplace 項目定義這些檔案中的哪些被公開為 skills、agents、hooks 等。當 marketplace 以不同於 plugin 作者預期的方式重組或策劃 plugin 的元件時很有用。

485 

486## 託管並分發 marketplace

487 

488### 在 GitHub 上託管(推薦)

489 

490GitHub 提供最簡單的分發方法:

491 

4921. **建立儲存庫**:為您的 marketplace 設定新儲存庫

4932. **新增 marketplace 檔案**:使用您的 plugin 定義建立 `.claude-plugin/marketplace.json`

4943. **與團隊分享**:使用者使用 `/plugin marketplace add owner/repo` 新增您的 marketplace

495 

496**優點**:內建版本控制、問題追蹤和團隊協作功能。

497 

498### 在其他 git 服務上託管

499 

500任何 git 託管服務都可以使用,例如 GitLab、Bitbucket 和自託管伺服器。使用者使用完整儲存庫 URL 新增:

501 

502```shell theme={null}

503/plugin marketplace add https://gitlab.com/company/plugins.git

504```

505 

506### 私人儲存庫

507 

508Claude Code 支援從私人儲存庫安裝 plugin。對於手動安裝和更新,Claude Code 使用您現有的 git 認證助手,因此 HTTPS 存取透過 `gh auth login`、macOS Keychain 或 `git-credential-store` 的方式與在您的終端中相同。只要主機已在您的 `known_hosts` 檔案中且金鑰已載入 `ssh-agent`,SSH 存取就可以運作,因為 Claude Code 會抑制主機指紋和金鑰密碼的互動式 SSH 提示。

509 

510背景自動更新在啟動時執行,不使用認證助手,因為互動式提示會阻止 Claude Code 啟動。若要為私人 marketplace 啟用自動更新,請在您的環境中設定適當的驗證令牌:

511 

512| 提供者 | 環境變數 | 備註 |

513| :-------- | :-------------------------- | :-------------------- |

514| GitHub | `GITHUB_TOKEN` 或 `GH_TOKEN` | 個人存取令牌或 GitHub App 令牌 |

515| GitLab | `GITLAB_TOKEN` 或 `GL_TOKEN` | 個人存取令牌或專案令牌 |

516| Bitbucket | `BITBUCKET_TOKEN` | 應用程式密碼或儲存庫存取令牌 |

517 

518在您的 shell 配置中設定令牌(例如,`.bashrc`、`.zshrc`)或在執行 Claude Code 時傳遞它:

519 

520```bash theme={null}

521export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx

522```

523 

524<Note>

525 對於 CI/CD 環境,將令牌配置為秘密環境變數。GitHub Actions 自動為同一組織中的儲存庫提供 `GITHUB_TOKEN`。

526</Note>

527 

528### 在分發前在本機測試

529 

530在分享前在本機測試您的 marketplace:

531 

532```shell theme={null}

533/plugin marketplace add ./my-local-marketplace

534/plugin install test-plugin@my-local-marketplace

535```

536 

537有關完整的新增命令範圍(GitHub、Git URL、本機路徑、遠端 URL),請參閱[新增 marketplace](/zh-TW/discover-plugins#add-marketplaces)。

538 

539### 為您的團隊要求 marketplace

540 

541您可以配置您的儲存庫,以便當團隊成員信任專案資料夾時,他們會自動被提示安裝您的 marketplace。將您的 marketplace 新增到 `.claude/settings.json`:

542 

543```json theme={null}

544{

545 "extraKnownMarketplaces": {

546 "company-tools": {

547 "source": {

548 "source": "github",

549 "repo": "your-org/claude-plugins"

550 }

551 }

552 }

553}

554```

555 

556您也可以指定預設應啟用哪些 plugin:

557 

558```json theme={null}

559{

560 "enabledPlugins": {

561 "code-formatter@company-tools": true,

562 "deployment-tools@company-tools": true

563 }

564}

565```

566 

567有關完整的配置選項,請參閱 [Plugin settings](/zh-TW/settings#plugin-settings)。

568 

569<Note>

570 如果您使用具有相對路徑的本機 `directory` 或 `file` 來源,路徑會針對您的儲存庫的主要簽出進行解析。當您從 git worktree 執行 Claude Code 時,路徑仍然指向主要簽出,因此所有 worktrees 共享相同的 marketplace 位置。Marketplace 狀態每個使用者儲存一次在 `~/.claude/plugins/known_marketplaces.json` 中,而不是每個專案。

571</Note>

572 

573### 為容器預先填充 plugin

574 

575對於容器映像和 CI 環境,您可以在建置時預先填充 plugin 目錄,以便 Claude Code 啟動時已有 marketplace 和 plugin 可用,無需在執行時複製任何內容。設定 `CLAUDE_CODE_PLUGIN_SEED_DIR` 環境變數以指向此目錄。

576 

577若要分層多個種子目錄,請在 Unix 上使用 `:` 或在 Windows 上使用 `;` 分隔路徑。Claude Code 按順序搜尋每個目錄,第一個包含給定 marketplace 或 plugin 快取的種子獲勝。

578 

579種子目錄鏡像 `~/.claude/plugins` 的結構:

580 

581```

582$CLAUDE_CODE_PLUGIN_SEED_DIR/

583 known_marketplaces.json

584 marketplaces/<name>/...

585 cache/<marketplace>/<plugin>/<version>/...

586```

587 

588建立種子目錄的最簡單方法是在映像建置期間執行 Claude Code 一次,安裝您需要的 plugin,然後將產生的 `~/.claude/plugins` 目錄複製到您的映像中,並將 `CLAUDE_CODE_PLUGIN_SEED_DIR` 指向它。

589 

590若要跳過複製步驟,在建置期間將 `CLAUDE_CODE_PLUGIN_CACHE_DIR` 設定為您的目標種子路徑,以便 plugin 直接安裝到那裡:

591 

592```bash theme={null}

593CLAUDE_CODE_PLUGIN_CACHE_DIR=/opt/claude-seed claude plugin marketplace add your-org/plugins

594CLAUDE_CODE_PLUGIN_CACHE_DIR=/opt/claude-seed claude plugin install my-tool@your-plugins

595```

596 

597然後在您的容器的執行時環境中設定 `CLAUDE_CODE_PLUGIN_SEED_DIR=/opt/claude-seed`,以便 Claude Code 在啟動時從種子讀取。

598 

599在啟動時,Claude Code 將種子的 `known_marketplaces.json` 中找到的 marketplace 註冊到主要配置中,並使用在 `cache/` 下找到的 plugin 快取,而無需重新複製。這在互動模式和使用 `-p` 旗標的非互動模式中都有效。

600 

601行為詳細資訊:

602 

603* **唯讀**:種子目錄永遠不會被寫入。自動更新對種子 marketplace 被停用,因為 git pull 在唯讀檔案系統上會失敗。

604* **種子項目優先**:種子中宣告的 marketplace 在每次啟動時覆蓋使用者配置中的任何相符項目。若要選擇退出種子 plugin,請使用 `/plugin disable` 而不是移除 marketplace。

605* **路徑解析**:Claude Code 在執行時透過探測 `$CLAUDE_CODE_PLUGIN_SEED_DIR/marketplaces/<name>/` 來定位 marketplace 內容,而不是信任儲存在種子 JSON 內的路徑。這表示即使在與建置位置不同的路徑上掛載,種子也能正確運作。

606* **變更被阻止**:針對種子管理的 marketplace 執行 `/plugin marketplace remove` 或 `/plugin marketplace update` 會失敗,並提示您要求管理員更新種子映像。

607* **與設定組合**:如果 `extraKnownMarketplaces` 或 `enabledPlugins` 宣告已存在於種子中的 marketplace,Claude Code 使用種子副本而不是複製。

608 

609### 受管 marketplace 限制

610 

611對於需要對 plugin 來源進行嚴格控制的組織,管理員可以使用受管設定中的 [`strictKnownMarketplaces`](/zh-TW/settings#strictknownmarketplaces) 設定限制使用者允許新增的 plugin marketplace。

612 

613當在受管設定中配置 `strictKnownMarketplaces` 時,限制行為取決於值:

614 

615| 值 | 行為 |

616| -------- | ----------------------------- |

617| 未定義(預設) | 無限制。使用者可以新增任何 marketplace |

618| 空陣列 `[]` | 完全鎖定。使用者無法新增任何新 marketplace |

619| 來源清單 | 使用者只能新增與允許清單完全相符的 marketplace |

620 

621#### 常見配置

622 

623停用所有 marketplace 新增:

624 

625```json theme={null}

626{

627 "strictKnownMarketplaces": []

628}

629```

630 

631僅允許特定 marketplace:

632 

633```json theme={null}

634{

635 "strictKnownMarketplaces": [

636 {

637 "source": "github",

638 "repo": "acme-corp/approved-plugins"

639 },

640 {

641 "source": "github",

642 "repo": "acme-corp/security-tools",

643 "ref": "v2.0"

644 },

645 {

646 "source": "url",

647 "url": "https://plugins.example.com/marketplace.json"

648 }

649 ]

650}

651```

652 

653使用主機上的正規表達式模式匹配允許來自內部 git 伺服器的所有 marketplace。這是 [GitHub Enterprise Server](/zh-TW/github-enterprise-server#plugin-marketplaces-on-ghes) 或自託管 GitLab 執行個體的推薦方法:

654 

655```json theme={null}

656{

657 "strictKnownMarketplaces": [

658 {

659 "source": "hostPattern",

660 "hostPattern": "^github\\.example\\.com$"

661 }

662 ]

663}

664```

665 

666使用路徑上的正規表達式模式匹配允許來自特定目錄的檔案系統型 marketplace:

667 

668```json theme={null}

669{

670 "strictKnownMarketplaces": [

671 {

672 "source": "pathPattern",

673 "pathPattern": "^/opt/approved/"

674 }

675 ]

676}

677```

678 

679使用 `".*"` 作為 `pathPattern` 以允許任何檔案系統路徑,同時仍使用 `hostPattern` 控制網路來源。

680 

681<Note>

682 `strictKnownMarketplaces` 限制使用者可以新增的內容,但不會自行註冊 marketplace。若要在不需要使用者執行 `/plugin marketplace add` 的情況下自動提供允許的 marketplace,請將其與同一 `managed-settings.json` 中的 [`extraKnownMarketplaces`](/zh-TW/settings#extraknownmarketplaces) 配對。請參閱[同時使用兩者](/zh-TW/settings#strictknownmarketplaces)。

683</Note>

684 

685#### 限制如何運作

686 

687限制在任何網路或檔案系統操作之前進行檢查。檢查在 marketplace 新增以及 plugin 安裝、更新、重新整理和自動更新時執行。如果 marketplace 在配置原則之前被新增,且其來源不再符合允許清單,Claude Code 會拒絕從中安裝或更新 plugin。相同的強制執行也適用於 `blockedMarketplaces`。

688 

689允許清單對大多數來源類型使用精確匹配。若要允許 marketplace,所有指定的欄位必須完全相符:

690 

691* 對於 GitHub 來源:`repo` 是必需的,如果在允許清單中指定,`ref` 或 `path` 也必須相符

692* 對於 URL 來源:完整 URL 必須完全相符

693* 對於 `hostPattern` 來源:marketplace 主機與正規表達式模式相符

694* 對於 `pathPattern` 來源:marketplace 的檔案系統路徑與正規表達式模式相符

695 

696因為 `strictKnownMarketplaces` 在[受管設定](/zh-TW/settings#settings-files)中設定,個別使用者和專案配置無法覆蓋這些限制。

697 

698有關完整的配置詳細資訊,包括所有支援的來源類型和與 `extraKnownMarketplaces` 的比較,請參閱 [strictKnownMarketplaces 參考](/zh-TW/settings#strictknownmarketplaces)。

699 

700### 版本解析和發行通道

701 

702Plugin 版本決定快取路徑和更新偵測:如果解析的版本與使用者已有的版本相符,`/plugin update` 和自動更新會跳過 plugin。

703 

704Claude Code 從以下第一個設定的項目解析 plugin 的版本:

705 

7061. plugin 的 `plugin.json` 中的 `version`

7072. plugin 的 marketplace 項目中的 `version`

7083. plugin 來源的 git 提交 SHA

709 

710對於 git 型來源類型 `github`、`url`、`git-subdir` 和 git 託管 marketplace 內的相對路徑,您可以完全省略 `version`,每個新提交都被視為新版本。這是內部或積極開發的 plugin 的最簡單設定。

711 

712<Warning>

713 設定 `version` 會固定 plugin。如果 `plugin.json` 宣告 `"version": "1.0.0"`,推送新提交而不更改該字串對現有使用者沒有任何作用,因為 Claude Code 看到相同的版本並保留快取副本。在每次發行時提升該欄位,或省略它以使用提交 SHA。

714 

715 避免在 `plugin.json` 和 marketplace 項目中同時設定 `version`。`plugin.json` 值總是無聲地獲勝,因此過時的 manifest 版本可能會掩蓋您在 `marketplace.json` 中設定的版本。

716</Warning>

717 

718#### 設定發行通道

719 

720若要為您的 plugin 支援「穩定」和「最新」發行通道,您可以設定兩個指向同一儲存庫的不同 ref 或 SHA 的 marketplace。然後,您可以透過[受管設定](/zh-TW/settings#settings-files)將兩個 marketplace 指派給不同的使用者群組。

721 

722<Warning>

723 每個通道必須解析為不同的版本。如果您使用明確版本,`plugin.json` 必須在每個固定的 ref 處宣告不同的 `version`。如果您省略 `version`,不同的提交 SHA 已經區分通道。如果兩個 ref 解析為相同的版本字串,Claude Code 會將它們視為相同並跳過更新。

724</Warning>

725 

726##### 範例

727 

728```json theme={null}

729{

730 "name": "stable-tools",

731 "plugins": [

732 {

733 "name": "code-formatter",

734 "source": {

735 "source": "github",

736 "repo": "acme-corp/code-formatter",

737 "ref": "stable"

738 }

739 }

740 ]

741}

742```

743 

744```json theme={null}

745{

746 "name": "latest-tools",

747 "plugins": [

748 {

749 "name": "code-formatter",

750 "source": {

751 "source": "github",

752 "repo": "acme-corp/code-formatter",

753 "ref": "latest"

754 }

755 }

756 ]

757}

758```

759 

760##### 將通道指派給使用者群組

761 

762透過受管設定將每個 marketplace 指派給適當的使用者群組。例如,穩定群組接收:

763 

764```json theme={null}

765{

766 "extraKnownMarketplaces": {

767 "stable-tools": {

768 "source": {

769 "source": "github",

770 "repo": "acme-corp/stable-tools"

771 }

772 }

773 }

774}

775```

776 

777早期存取群組改為接收 `latest-tools`:

778 

779```json theme={null}

780{

781 "extraKnownMarketplaces": {

782 "latest-tools": {

783 "source": {

784 "source": "github",

785 "repo": "acme-corp/latest-tools"

786 }

787 }

788 }

789}

790```

791 

792#### 固定依賴版本

793 

794Plugin 可以將其依賴限制在 semver 範圍內,以便依賴的更新不會破壞依賴 plugin。請參閱[限制 plugin 依賴版本](/zh-TW/plugin-dependencies)以了解 `{plugin-name}--v{version}` git 標籤慣例、範圍語法,以及如何組合對同一依賴的多個限制。

795 

796## 驗證和測試

797 

798在分享前測試您的 marketplace。

799 

800驗證您的 marketplace JSON 語法:

801 

802```bash theme={null}

803claude plugin validate .

804```

805 

806或從 Claude Code 內:

807 

808```shell theme={null}

809/plugin validate .

810```

811 

812新增 marketplace 進行測試:

813 

814```shell theme={null}

815/plugin marketplace add ./path/to/marketplace

816```

817 

818安裝測試 plugin 以驗證一切正常運作:

819 

820```shell theme={null}

821/plugin install test-plugin@marketplace-name

822```

823 

824有關完整的 plugin 測試工作流程,請參閱[在本機測試您的 plugin](/zh-TW/plugins#test-your-plugins-locally)。有關技術疑難排解,請參閱 [Plugins reference](/zh-TW/plugins-reference)。

825 

826## 從 CLI 管理 marketplace

827 

828Claude Code 提供非互動式 `claude plugin marketplace` 子命令用於指令碼和自動化。這些等同於互動式工作階段內可用的 `/plugin marketplace` 命令。

829 

830### Plugin marketplace add

831 

832從 GitHub 儲存庫、git URL、遠端 URL 或本機路徑新增 marketplace。

833 

834```bash theme={null}

835claude plugin marketplace add <source> [options]

836```

837 

838**引數:**

839 

840* `<source>`:GitHub `owner/repo` 簡寫、git URL、遠端 URL 到 `marketplace.json` 檔案或本機目錄路徑。若要固定到分支或標籤,請將 `@ref` 附加到 GitHub 簡寫或 `#ref` 附加到 git URL

841 

842**選項:**

843 

844| 選項 | 描述 | 預設 |

845| :-------------------- | :---------------------------------------------------------------------------------------------------------------------------------- | :----- |

846| `--scope <scope>` | 宣告 marketplace 的位置:`user`、`project` 或 `local`。請參閱 [Plugin installation scopes](/zh-TW/plugins-reference#plugin-installation-scopes) | `user` |

847| `--sparse <paths...>` | 透過 git sparse-checkout 限制簽出到特定目錄。對 monorepo 很有用 | |

848 

849從 GitHub 使用 `owner/repo` 簡寫新增 marketplace:

850 

851```bash theme={null}

852claude plugin marketplace add acme-corp/claude-plugins

853```

854 

855使用 `@ref` 固定到特定分支或標籤:

856 

857```bash theme={null}

858claude plugin marketplace add acme-corp/claude-plugins@v2.0

859```

860 

861從非 GitHub 主機上的 git URL 新增:

862 

863```bash theme={null}

864claude plugin marketplace add https://gitlab.example.com/team/plugins.git

865```

866 

867從直接提供 `marketplace.json` 檔案的遠端 URL 新增:

868 

869```bash theme={null}

870claude plugin marketplace add https://example.com/marketplace.json

871```

872 

873從本機目錄新增以進行測試:

874 

875```bash theme={null}

876claude plugin marketplace add ./my-marketplace

877```

878 

879在專案範圍宣告 marketplace,以便透過 `.claude/settings.json` 與您的團隊共享:

880 

881```bash theme={null}

882claude plugin marketplace add acme-corp/claude-plugins --scope project

883```

884 

885對於 monorepo,限制簽出到包含 plugin 內容的目錄:

886 

887```bash theme={null}

888claude plugin marketplace add acme-corp/monorepo --sparse .claude-plugin plugins

889```

890 

891### Plugin marketplace list

892 

893列出所有已配置的 marketplace。

894 

895```bash theme={null}

896claude plugin marketplace list [options]

897```

898 

899**選項:**

900 

901| 選項 | 描述 |

902| :------- | :------- |

903| `--json` | 輸出為 JSON |

904 

905### Plugin marketplace remove

906 

907移除已配置的 marketplace。別名 `rm` 也被接受。

908 

909```bash theme={null}

910claude plugin marketplace remove <name>

911```

912 

913**引數:**

914 

915* `<name>`:marketplace 名稱以移除,如 `claude plugin marketplace list` 所示。這是 `marketplace.json` 中的 `name`,而不是您傳遞給 `add` 的來源

916 

917<Warning>

918 移除 marketplace 也會卸載您從中安裝的任何 plugin。若要重新整理 marketplace 而不失去已安裝的 plugin,請改用 `claude plugin marketplace update`。

919</Warning>

920 

921### Plugin marketplace update

922 

923從其來源重新整理 marketplace 以檢索新 plugin 和版本變更。

924 

925```bash theme={null}

926claude plugin marketplace update [name]

927```

928 

929**引數:**

930 

931* `[name]`:marketplace 名稱以更新,如 `claude plugin marketplace list` 所示。如果省略,更新所有 marketplace

932 

933`remove` 和 `update` 在針對種子管理的 marketplace 執行時都會失敗,該 marketplace 是唯讀的。更新所有 marketplace 時,種子管理的項目被跳過,其他 marketplace 仍然更新。若要變更種子提供的 plugin,請要求您的管理員更新種子映像。請參閱[為容器預先填充 plugin](#pre-populate-plugins-for-containers)。

934 

935## 疑難排解

936 

937### Marketplace 未載入

938 

939**症狀**:無法新增 marketplace 或看不到其中的 plugin

940 

941**解決方案**:

942 

943* 驗證 marketplace URL 可存取

944* 檢查 `.claude-plugin/marketplace.json` 是否存在於指定路徑

945* 使用 `claude plugin validate` 或 `/plugin validate` 確保 JSON 語法有效且 frontmatter 格式正確

946* 對於私人儲存庫,確認您有存取權限

947 

948### Marketplace 驗證錯誤

949 

950從您的 marketplace 目錄執行 `claude plugin validate .` 或 `/plugin validate .` 以檢查問題。驗證器檢查 `plugin.json`、skill/agent/command frontmatter 和 `hooks/hooks.json` 是否有語法和架構錯誤。常見錯誤:

951 

952| 錯誤 | 原因 | 解決方案 |

953| :------------------------------------------------ | :--------------------------------- | :---------------------------------------------------------- |

954| `File not found: .claude-plugin/marketplace.json` | 缺少 manifest | 使用必需欄位建立 `.claude-plugin/marketplace.json` |

955| `Invalid JSON syntax: Unexpected token...` | JSON 語法錯誤 | 檢查缺少的逗號、多餘的逗號或未引用的字串 |

956| `Duplicate plugin name "x" found in marketplace` | 兩個 plugin 共享相同名稱 | 為每個 plugin 指定唯一的 `name` 值 |

957| `plugins[0].source: Path contains ".."` | 來源路徑包含 `..` | 使用相對於 marketplace 根目錄的路徑,不含 `..`。請參閱[相對路徑](#relative-paths) |

958| `YAML frontmatter failed to parse: ...` | skill、agent 或 command 檔案中的 YAML 無效 | 修正 frontmatter 區塊中的 YAML 語法。在執行時,此檔案載入時不含中繼資料。 |

959| `Invalid JSON syntax: ...`(hooks.json) | 格式不正確的 `hooks/hooks.json` | 修正 JSON 語法。格式不正確的 `hooks/hooks.json` 會防止整個 plugin 載入。 |

960 

961**警告**(非阻止性):

962 

963* `Marketplace has no plugins defined`:將至少一個 plugin 新增到 `plugins` 陣列

964* `No marketplace description provided`:新增頂層 `description` 以幫助使用者瞭解您的 marketplace

965* `Plugin name "x" is not kebab-case`:plugin 名稱包含大寫字母、空格或特殊字元。重新命名為僅包含小寫字母、數字和連字號(例如,`my-plugin`)。Claude Code 接受其他形式,但 Claude.ai marketplace 同步會拒絕它們。

966 

967### Plugin 安裝失敗

968 

969**症狀**:Marketplace 出現但 plugin 安裝失敗

970 

971**解決方案**:

972 

973* 驗證 plugin 來源 URL 可存取

974* 檢查 plugin 目錄是否包含必需的檔案

975* 對於 GitHub 來源,確保儲存庫是公開的或您有存取權

976* 透過手動複製/下載測試 plugin 來源

977 

978### 私人儲存庫驗證失敗

979 

980**症狀**:從私人儲存庫安裝 plugin 時出現驗證錯誤

981 

982**解決方案**:

983 

984對於手動安裝和更新:

985 

986* 驗證您已使用您的 git 提供者進行驗證(例如,為 GitHub 執行 `gh auth status`)

987* 檢查您的認證助手是否正確配置:`git config --global credential.helper`

988* 嘗試手動複製儲存庫以驗證您的認證有效

989 

990對於背景自動更新:

991 

992* 在您的環境中設定適當的令牌:`echo $GITHUB_TOKEN`

993* 檢查令牌是否具有必需的權限(對儲存庫的讀取存取權)

994* 對於 GitHub,確保令牌對私人儲存庫具有 `repo` 範圍

995* 對於 GitLab,確保令牌至少具有 `read_repository` 範圍

996* 驗證令牌未過期

997 

998### Marketplace 更新在離線環境中失敗

999 

1000**症狀**:Marketplace `git pull` 失敗,Claude Code 清除現有快取,導致 plugin 變得不可用。

1001 

1002**原因**:預設情況下,當 `git pull` 失敗時,Claude Code 會移除過時的複製並嘗試重新複製。在離線或隔離環境中,重新複製以相同方式失敗,導致 marketplace 目錄為空。

1003 

1004**解決方案**:設定 `CLAUDE_CODE_PLUGIN_KEEP_MARKETPLACE_ON_FAILURE=1` 以在拉取失敗時保留現有快取,而不是清除它:

1005 

1006```bash theme={null}

1007export CLAUDE_CODE_PLUGIN_KEEP_MARKETPLACE_ON_FAILURE=1

1008```

1009 

1010設定此變數後,Claude Code 在 `git pull` 失敗時保留過時的 marketplace 複製,並繼續使用最後已知的良好狀態。對於儲存庫永遠無法到達的完全離線部署,請改用 [`CLAUDE_CODE_PLUGIN_SEED_DIR`](#pre-populate-plugins-for-containers) 在建置時預先填充 plugin 目錄。

1011 

1012### Git 操作逾時

1013 

1014**症狀**:Plugin 安裝或 marketplace 更新失敗,出現逾時錯誤,例如「Git clone timed out after 120s」或「Git pull timed out after 120s」。

1015 

1016**原因**:Claude Code 對所有 git 操作(包括複製 plugin 儲存庫和拉取 marketplace 更新)使用 120 秒逾時。大型儲存庫或緩慢的網路連線可能超過此限制。

1017 

1018**解決方案**:使用 `CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS` 環境變數增加逾時。值以毫秒為單位:

1019 

1020```bash theme={null}

1021export CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS=300000 # 5 分鐘

1022```

1023 

1024### 相對路徑 plugin 在基於 URL 的 marketplace 中失敗

1025 

1026**症狀**:透過 URL(例如 `https://example.com/marketplace.json`)新增 marketplace,但具有相對路徑來源(如 `"./plugins/my-plugin"`)的 plugin 無法安裝,出現「path not found」錯誤。

1027 

1028**原因**:基於 URL 的 marketplace 僅下載 `marketplace.json` 檔案本身。它們不從伺服器下載 plugin 檔案。marketplace 項目中的相對路徑參考未下載的遠端伺服器上的檔案。

1029 

1030**解決方案**:

1031 

1032* **使用外部來源**:將 plugin 項目變更為使用 GitHub、npm 或 git URL 來源,而不是相對路徑:

1033 ```json theme={null}

1034 { "name": "my-plugin", "source": { "source": "github", "repo": "owner/repo" } }

1035 ```

1036* **使用基於 Git 的 marketplace**:在 Git 儲存庫中託管您的 marketplace 並使用 git URL 新增它。基於 Git 的 marketplace 複製整個儲存庫,使相對路徑正常運作。

1037 

1038### 安裝後找不到檔案

1039 

1040**症狀**:Plugin 安裝但對檔案的參考失敗,特別是 plugin 目錄外的檔案

1041 

1042**原因**:Plugin 被複製到快取目錄而不是就地使用。參考 plugin 目錄外檔案的路徑(例如 `../shared-utils`)無法運作,因為這些檔案不會被複製。

1043 

1044**解決方案**:有關解決方案(包括符號連結和目錄重組),請參閱 [Plugin caching and file resolution](/zh-TW/plugins-reference#plugin-caching-and-file-resolution)。

1045 

1046有關其他偵錯工具和常見問題,請參閱 [Debugging and development tools](/zh-TW/plugins-reference#debugging-and-development-tools)。

1047 

1048## 另請參閱

1049 

1050* [探索並安裝預先建立的 plugin](/zh-TW/discover-plugins) - 從現有 marketplace 安裝 plugin

1051* [Plugins](/zh-TW/plugins) - 建立您自己的 plugin

1052* [Plugins reference](/zh-TW/plugins-reference) - 完整的技術規格和架構

1053* [Plugin settings](/zh-TW/settings#plugin-settings) - Plugin 配置選項

1054* [strictKnownMarketplaces reference](/zh-TW/settings#strictknownmarketplaces) - 受管 marketplace 限制

plugins.md +454 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 建立 plugins

6 

7> 建立自訂 plugins 以使用 skills、agents、hooks 和 MCP servers 擴展 Claude Code。

8 

9Plugins 讓您使用可在專案和團隊中共享的自訂功能來擴展 Claude Code。本指南涵蓋使用 skills、agents、hooks 和 MCP servers 建立您自己的 plugins。

10 

11想要安裝現有的 plugins?請參閱[探索和安裝 plugins](/zh-TW/discover-plugins)。如需完整的技術規格,請參閱 [Plugins 參考](/zh-TW/plugins-reference)。

12 

13## 何時使用 plugins 與獨立配置

14 

15Claude Code 支援兩種方式來新增自訂 skills、agents 和 hooks:

16 

17| 方法 | Skill 名稱 | 最適合 |

18| :----------------------------------------------- | :------------------- | :------------------------ |

19| **獨立**(`.claude/` 目錄) | `/hello` | 個人工作流程、專案特定的自訂、快速實驗 |

20| **Plugins**(包含 `.claude-plugin/plugin.json` 的目錄) | `/plugin-name:hello` | 與隊友共享、分發到社群、版本化發佈、跨專案重複使用 |

21 

22**在以下情況下使用獨立配置**:

23 

24* 您正在為單一專案自訂 Claude Code

25* 配置是個人的,不需要共享

26* 您在將 skills 或 hooks 打包之前進行實驗

27* 您想要簡短的 skill 名稱,例如 `/hello` 或 `/deploy`

28 

29**在以下情況下使用 plugins**:

30 

31* 您想與您的團隊或社群共享功能

32* 您需要在多個專案中使用相同的 skills/agents

33* 您想要版本控制和輕鬆更新您的擴展

34* 您正在透過市場進行分發

35* 您可以接受命名空間化的 skills,例如 `/my-plugin:hello`(命名空間可防止 plugins 之間的衝突)

36 

37<Tip>

38 在 `.claude/` 中從獨立配置開始進行快速迭代,然後在準備好共享時[轉換為 plugin](#convert-existing-configurations-to-plugins)。

39</Tip>

40 

41## 快速入門

42 

43本快速入門將引導您建立具有自訂 skill 的 plugin。您將建立一個清單(定義您的 plugin 的配置檔案)、新增一個 skill,並使用 `--plugin-dir` 旗標在本地進行測試。

44 

45### 先決條件

46 

47* Claude Code [已安裝並驗證](/zh-TW/quickstart#step-1-install-claude-code)

48 

49<Note>

50 如果您沒有看到 `/plugin` 命令,請將 Claude Code 更新到最新版本。如需升級說明,請參閱 [Troubleshooting](/zh-TW/troubleshooting)。

51</Note>

52 

53### 建立您的第一個 plugin

54 

55<Steps>

56 <Step title="建立 plugin 目錄">

57 每個 plugin 都位於其自己的目錄中,包含一個清單和您的 skills、agents 或 hooks。現在建立一個:

58 

59 ```bash theme={null}

60 mkdir my-first-plugin

61 ```

62 </Step>

63 

64 <Step title="建立 plugin 清單">

65 位於 `.claude-plugin/plugin.json` 的清單檔案定義您的 plugin 的身份:其名稱、描述和版本。Claude Code 使用此中繼資料在 plugin 管理器中顯示您的 plugin。

66 

67 在您的 plugin 資料夾內建立 `.claude-plugin` 目錄:

68 

69 ```bash theme={null}

70 mkdir my-first-plugin/.claude-plugin

71 ```

72 

73 然後使用此內容建立 `my-first-plugin/.claude-plugin/plugin.json`:

74 

75 ```json my-first-plugin/.claude-plugin/plugin.json theme={null}

76 {

77 "name": "my-first-plugin",

78 "description": "A greeting plugin to learn the basics",

79 "version": "1.0.0",

80 "author": {

81 "name": "Your Name"

82 }

83 }

84 ```

85 

86 | 欄位 | 用途 |

87 | :------------ | :----------------------------------------------------------------------------------------------------------------------------------------- |

88 | `name` | 唯一識別碼和 skill 命名空間。Skills 以此為前綴(例如 `/my-first-plugin:hello`)。 |

89 | `description` | 在瀏覽或安裝 plugins 時在 plugin 管理器中顯示。 |

90 | `version` | 選用。如果設定,使用者只會在您更新此欄位時收到更新。如果省略且您的 plugin 透過 git 分發,則使用 commit SHA,每個 commit 都算作新版本。請參閱[版本管理](/zh-TW/plugins-reference#version-management)。 |

91 | `author` | 選用。有助於歸屬。 |

92 

93 如需 `homepage`、`repository` 和 `license` 等其他欄位,請參閱[完整清單架構](/zh-TW/plugins-reference#plugin-manifest-schema)。

94 </Step>

95 

96 <Step title="新增 skill">

97 Skills 位於 `skills/` 目錄中。每個 skill 是一個包含 `SKILL.md` 檔案的資料夾。資料夾名稱成為 skill 名稱,以 plugin 的命名空間為前綴(在名為 `my-first-plugin` 的 plugin 中的 `hello/` 建立 `/my-first-plugin:hello`)。

98 

99 在您的 plugin 資料夾中建立一個 skill 目錄:

100 

101 ```bash theme={null}

102 mkdir -p my-first-plugin/skills/hello

103 ```

104 

105 然後使用此內容建立 `my-first-plugin/skills/hello/SKILL.md`:

106 

107 ```markdown my-first-plugin/skills/hello/SKILL.md theme={null}

108 ---

109 description: Greet the user with a friendly message

110 disable-model-invocation: true

111 ---

112 

113 Greet the user warmly and ask how you can help them today.

114 ```

115 </Step>

116 

117 <Step title="測試您的 plugin">

118 使用 `--plugin-dir` 旗標執行 Claude Code 以載入您的 plugin:

119 

120 ```bash theme={null}

121 claude --plugin-dir ./my-first-plugin

122 ```

123 

124 Claude Code 啟動後,嘗試您的新 skill:

125 

126 ```shell theme={null}

127 /my-first-plugin:hello

128 ```

129 

130 您將看到 Claude 以問候語回應。執行 `/help` 以查看您的 skill 列在 plugin 命名空間下。

131 

132 <Note>

133 **為什麼要命名空間?** Plugin skills 始終被命名空間化(例如 `/my-first-plugin:hello`),以防止多個 plugins 具有相同名稱的 skills 時發生衝突。

134 

135 若要變更命名空間前綴,請更新 `plugin.json` 中的 `name` 欄位。

136 </Note>

137 </Step>

138 

139 <Step title="新增 skill 引數">

140 透過接受使用者輸入使您的 skill 動態化。`$ARGUMENTS` 佔位符會擷取使用者在 skill 名稱後提供的任何文字。

141 

142 更新您的 `SKILL.md` 檔案:

143 

144 ```markdown my-first-plugin/skills/hello/SKILL.md theme={null}

145 ---

146 description: Greet the user with a personalized message

147 ---

148 

149 # Hello Skill

150 

151 Greet the user named "$ARGUMENTS" warmly and ask how you can help them today. Make the greeting personal and encouraging.

152 ```

153 

154 執行 `/reload-plugins` 以取得變更,然後嘗試使用您的名稱執行 skill:

155 

156 ```shell theme={null}

157 /my-first-plugin:hello Alex

158 ```

159 

160 Claude 將按名稱向您問候。如需有關將引數傳遞給 skills 的更多資訊,請參閱 [Skills](/zh-TW/skills#pass-arguments-to-skills)。

161 </Step>

162</Steps>

163 

164您已成功建立並測試了具有這些關鍵元件的 plugin:

165 

166* **Plugin 清單** (`.claude-plugin/plugin.json`):描述您的 plugin 的中繼資料

167* **Skills 目錄** (`skills/`):包含您的自訂 skills

168* **Skill 引數** (`$ARGUMENTS`):擷取使用者輸入以實現動態行為

169 

170<Tip>

171 `--plugin-dir` 旗標對於開發和測試很有用。當您準備好與他人共享您的 plugin 時,請參閱[建立和分發 plugin 市場](/zh-TW/plugin-marketplaces)。

172</Tip>

173 

174## Plugin 結構概述

175 

176您已建立了具有 skill 的 plugin,但 plugins 可以包含更多內容:自訂 agents、hooks、MCP servers、LSP servers 和背景監視器。

177 

178<Warning>

179 **常見錯誤**:不要將 `commands/`、`agents/`、`skills/` 或 `hooks/` 放在 `.claude-plugin/` 目錄內。只有 `plugin.json` 應該在 `.claude-plugin/` 內。所有其他目錄必須位於 plugin 根目錄級別。

180</Warning>

181 

182| 目錄 | 位置 | 用途 |

183| :---------------- | :--------- | :----------------------------------------------- |

184| `.claude-plugin/` | Plugin 根目錄 | 包含 `plugin.json` 清單(如果元件使用預設位置,則為選用) |

185| `skills/` | Plugin 根目錄 | 作為 `<name>/SKILL.md` 目錄的 Skills |

186| `commands/` | Plugin 根目錄 | 作為平面 Markdown 檔案的 Skills。新 plugins 請使用 `skills/` |

187| `agents/` | Plugin 根目錄 | 自訂 agent 定義 |

188| `hooks/` | Plugin 根目錄 | `hooks.json` 中的事件處理程式 |

189| `.mcp.json` | Plugin 根目錄 | MCP server 配置 |

190| `.lsp.json` | Plugin 根目錄 | 用於程式碼智慧的 LSP server 配置 |

191| `monitors/` | Plugin 根目錄 | `monitors.json` 中的背景監視器配置 |

192| `bin/` | Plugin 根目錄 | 在啟用 plugin 時新增到 Bash tool 的 `PATH` 的可執行檔 |

193| `settings.json` | Plugin 根目錄 | 啟用 plugin 時應用的預設[設定](/zh-TW/settings) |

194 

195<Note>

196 **後續步驟**:準備好新增更多功能?跳至[開發更複雜的 plugins](#develop-more-complex-plugins) 以新增 agents、hooks、MCP servers 和 LSP servers。如需所有 plugin 元件的完整技術規格,請參閱 [Plugins 參考](/zh-TW/plugins-reference)。

197</Note>

198 

199## 開發更複雜的 plugins

200 

201一旦您熟悉了基本 plugins,您就可以建立更複雜的擴展。

202 

203### 將 Skills 新增到您的 plugin

204 

205Plugins 可以包含 [Agent Skills](/zh-TW/skills) 以擴展 Claude 的功能。Skills 是模型調用的:Claude 根據任務上下文自動使用它們。

206 

207在您的 plugin 根目錄中新增 `skills/` 目錄,其中包含包含 `SKILL.md` 檔案的 Skill 資料夾:

208 

209```text theme={null}

210my-plugin/

211├── .claude-plugin/

212│ └── plugin.json

213└── skills/

214 └── code-review/

215 └── SKILL.md

216```

217 

218每個 `SKILL.md` 包含 YAML frontmatter 和說明。包含 `description` 以便 Claude 知道何時使用該 skill:

219 

220```yaml theme={null}

221---

222description: Reviews code for best practices and potential issues. Use when reviewing code, checking PRs, or analyzing code quality.

223---

224 

225When reviewing code, check for:

2261. Code organization and structure

2272. Error handling

2283. Security concerns

2294. Test coverage

230```

231 

232安裝 plugin 後,執行 `/reload-plugins` 以載入 Skills。如需完整的 Skill 編寫指南,包括漸進式揭露和工具限制,請參閱 [Agent Skills](/zh-TW/skills)。

233 

234### 將 LSP servers 新增到您的 plugin

235 

236<Tip>

237 對於 TypeScript、Python 和 Rust 等常見語言,請從官方市場安裝預先建立的 LSP plugins。只有在您需要支援尚未涵蓋的語言時,才建立自訂 LSP plugins。

238</Tip>

239 

240LSP(語言伺服器協議)plugins 為 Claude 提供即時程式碼智慧。如果您需要支援沒有官方 LSP plugin 的語言,您可以透過將 `.lsp.json` 檔案新增到您的 plugin 來建立自己的:

241 

242```json .lsp.json theme={null}

243{

244 "go": {

245 "command": "gopls",

246 "args": ["serve"],

247 "extensionToLanguage": {

248 ".go": "go"

249 }

250 }

251}

252```

253 

254安裝您的 plugin 的使用者必須在其機器上安裝語言伺服器二進位檔。

255 

256如需完整的 LSP 配置選項,請參閱 [LSP servers](/zh-TW/plugins-reference#lsp-servers)。

257 

258### 將背景監視器新增到您的 plugin

259 

260背景監視器讓您的 plugin 在背景中監視日誌、檔案或外部狀態,並在事件到達時通知 Claude。Claude Code 在 plugin 啟用時自動啟動每個監視器,因此您不需要指示 Claude 啟動監視。

261 

262在 plugin 根目錄中新增 `monitors/monitors.json` 檔案,其中包含監視器項目的陣列:

263 

264```json monitors/monitors.json theme={null}

265[

266 {

267 "name": "error-log",

268 "command": "tail -F ./logs/error.log",

269 "description": "Application error log"

270 }

271]

272```

273 

274來自 `command` 的每個 stdout 行都會在工作階段期間作為通知傳遞給 Claude。如需完整的架構,包括 `when` 觸發器和變數替換,請參閱 [Monitors](/zh-TW/plugins-reference#monitors)。

275 

276### 使用您的 plugin 提供預設設定

277 

278Plugins 可以在 plugin 根目錄中包含 `settings.json` 檔案,以在啟用 plugin 時應用預設配置。目前,只支援 `agent` 和 `subagentStatusLine` 金鑰。

279 

280設定 `agent` 會啟動 plugin 的其中一個[自訂 agents](/zh-TW/sub-agents) 作為主執行緒,應用其系統提示、工具限制和模型。這讓 plugin 可以在啟用時透過預設方式變更 Claude Code 的行為。

281 

282```json settings.json theme={null}

283{

284 "agent": "security-reviewer"

285}

286```

287 

288此範例啟動在 plugin 的 `agents/` 目錄中定義的 `security-reviewer` agent。來自 `settings.json` 的設定優先於在 `plugin.json` 中宣告的 `settings`。未知的金鑰會被無聲地忽略。

289 

290### 組織複雜的 plugins

291 

292對於具有許多元件的 plugins,請按功能組織您的目錄結構。如需完整的目錄配置和組織模式,請參閱 [Plugin 目錄結構](/zh-TW/plugins-reference#plugin-directory-structure)。

293 

294### 在本地測試您的 plugins

295 

296使用 `--plugin-dir` 旗標在開發期間測試 plugins。這會直接載入您的 plugin,無需安裝。

297 

298```bash theme={null}

299claude --plugin-dir ./my-plugin

300```

301 

302當 `--plugin-dir` plugin 與已安裝的市場 plugin 具有相同名稱時,本地副本在該工作階段中優先。這讓您可以測試已安裝的 plugin 的變更,而無需先卸載它。由受管設定強制啟用的市場 plugins 是唯一的例外,無法被覆蓋。

303 

304當您對 plugin 進行變更時,執行 `/reload-plugins` 以取得更新,無需重新啟動。這會重新載入 plugins、skills、agents、hooks、plugin MCP servers 和 plugin LSP servers。測試您的 plugin 元件:

305 

306* 使用 `/plugin-name:skill-name` 嘗試您的 skills

307* 檢查 agents 是否出現在 `/agents` 中

308* 驗證 hooks 是否按預期工作

309 

310<Tip>

311 您可以透過多次指定旗標來一次載入多個 plugins:

312 

313 ```bash theme={null}

314 claude --plugin-dir ./plugin-one --plugin-dir ./plugin-two

315 ```

316</Tip>

317 

318### 偵錯 plugin 問題

319 

320如果您的 plugin 未按預期工作:

321 

3221. **檢查結構**:確保您的目錄位於 plugin 根目錄,而不是在 `.claude-plugin/` 內

3232. **個別測試元件**:分別檢查每個 skill、agent 和 hook

3243. **使用驗證和偵錯工具**:如需 CLI 命令和故障排除技術,請參閱 [Debugging and development tools](/zh-TW/plugins-reference#debugging-and-development-tools)

325 

326### 共享您的 plugins

327 

328當您的 plugin 準備好共享時:

329 

3301. **新增文件**:包含 `README.md`,其中包含安裝和使用說明

3312. **選擇版本控制策略**:決定是否設定明確的 `version` 或依賴 git commit SHA。請參閱 [version management](/zh-TW/plugins-reference#version-management)

3323. **建立或使用市場**:透過 [plugin marketplaces](/zh-TW/plugin-marketplaces) 進行分發以進行安裝

3334. **與他人測試**:在更廣泛的分發之前讓團隊成員測試 plugin

334 

335一旦您的 plugin 在市場中,其他人可以使用 [Discover and install plugins](/zh-TW/discover-plugins) 中的說明進行安裝。若要將 plugin 保持在您的團隊內部,請在 [private repository](/zh-TW/plugin-marketplaces#private-repositories) 中託管市場。

336 

337### 將您的 plugin 提交到官方市場

338 

339若要將 plugin 提交到官方 Anthropic 市場,請使用其中一個應用內提交表單:

340 

341* **Claude.ai**:[claude.ai/settings/plugins/submit](https://claude.ai/settings/plugins/submit)

342* **Console**:[platform.claude.com/plugins/submit](https://platform.claude.com/plugins/submit)

343 

344一旦您的 plugin 被列出,您可以讓您自己的 CLI 提示 Claude Code 使用者安裝它。請參閱 [Recommend your plugin from your CLI](/zh-TW/plugin-hints)。

345 

346<Note>

347 如需完整的技術規格、偵錯技術和分發策略,請參閱 [Plugins reference](/zh-TW/plugins-reference)。

348</Note>

349 

350## 將現有配置轉換為 plugins

351 

352如果您已經在 `.claude/` 目錄中有 skills 或 hooks,您可以將它們轉換為 plugin,以便更輕鬆地共享和分發。

353 

354### 遷移步驟

355 

356<Steps>

357 <Step title="建立 plugin 結構">

358 建立新的 plugin 目錄:

359 

360 ```bash theme={null}

361 mkdir -p my-plugin/.claude-plugin

362 ```

363 

364 在 `my-plugin/.claude-plugin/plugin.json` 建立清單檔案:

365 

366 ```json my-plugin/.claude-plugin/plugin.json theme={null}

367 {

368 "name": "my-plugin",

369 "description": "Migrated from standalone configuration",

370 "version": "1.0.0"

371 }

372 ```

373 </Step>

374 

375 <Step title="複製您現有的檔案">

376 將您現有的配置複製到 plugin 目錄:

377 

378 ```bash theme={null}

379 # Copy commands

380 cp -r .claude/commands my-plugin/

381 

382 # Copy agents (if any)

383 cp -r .claude/agents my-plugin/

384 

385 # Copy skills (if any)

386 cp -r .claude/skills my-plugin/

387 ```

388 </Step>

389 

390 <Step title="遷移 hooks">

391 如果您在設定中有 hooks,請建立一個 hooks 目錄:

392 

393 ```bash theme={null}

394 mkdir my-plugin/hooks

395 ```

396 

397 使用您的 hooks 配置建立 `my-plugin/hooks/hooks.json`。從您的 `.claude/settings.json` 或 `settings.local.json` 複製 `hooks` 物件,因為格式相同。命令在 stdin 上接收 hook 輸入作為 JSON,因此使用 `jq` 來提取檔案路徑:

398 

399 ```json my-plugin/hooks/hooks.json theme={null}

400 {

401 "hooks": {

402 "PostToolUse": [

403 {

404 "matcher": "Write|Edit",

405 "hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npm run lint:fix" }]

406 }

407 ]

408 }

409 }

410 ```

411 </Step>

412 

413 <Step title="測試您遷移的 plugin">

414 載入您的 plugin 以驗證一切正常:

415 

416 ```bash theme={null}

417 claude --plugin-dir ./my-plugin

418 ```

419 

420 測試每個元件:執行您的命令、檢查 agents 是否出現在 `/agents` 中,並驗證 hooks 是否正確觸發。

421 </Step>

422</Steps>

423 

424### 遷移時的變更

425 

426| 獨立(`.claude/`) | Plugin |

427| :----------------------- | :--------------------------- |

428| 僅在一個專案中可用 | 可以透過市場共享 |

429| `.claude/commands/` 中的檔案 | `plugin-name/commands/` 中的檔案 |

430| `settings.json` 中的 Hooks | `hooks/hooks.json` 中的 Hooks |

431| 必須手動複製以共享 | 使用 `/plugin install` 安裝 |

432 

433<Note>

434 遷移後,您可以從 `.claude/` 中移除原始檔案以避免重複。載入時,plugin 版本將優先。

435</Note>

436 

437## 後續步驟

438 

439現在您已了解 Claude Code 的 plugin 系統,以下是針對不同目標的建議路徑:

440 

441### 對於 plugin 使用者

442 

443* [探索和安裝 plugins](/zh-TW/discover-plugins):瀏覽市場並安裝 plugins

444* [配置團隊市場](/zh-TW/discover-plugins#configure-team-marketplaces):為您的團隊設定儲存庫級別的 plugins

445 

446### 對於 plugin 開發人員

447 

448* [建立和分發市場](/zh-TW/plugin-marketplaces):打包和共享您的 plugins

449* [Plugins 參考](/zh-TW/plugins-reference):完整的技術規格

450* 深入探討特定的 plugin 元件:

451 * [Skills](/zh-TW/skills):skill 開發詳情

452 * [Subagents](/zh-TW/sub-agents):agent 配置和功能

453 * [Hooks](/zh-TW/hooks):事件處理和自動化

454 * [MCP](/zh-TW/mcp):外部工具整合

plugins-reference.md +1011 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Plugins 參考

6 

7> Claude Code 外掛系統的完整技術參考,包括架構、CLI 命令和元件規格。

8 

9<Tip>

10 想要安裝外掛?請參閱 [探索和安裝外掛](/zh-TW/discover-plugins)。如需建立外掛,請參閱 [Plugins](/zh-TW/plugins)。如需發佈外掛,請參閱 [Plugin marketplaces](/zh-TW/plugin-marketplaces)。

11</Tip>

12 

13本參考提供 Claude Code 外掛系統的完整技術規格,包括元件架構、CLI 命令和開發工具。

14 

15**plugin** 是一個自包含的目錄,包含擴展 Claude Code 功能的元件。Plugin 元件包括 skills、agents、hooks、MCP servers、LSP servers 和 monitors。

16 

17## Plugin 元件參考

18 

19### Skills

20 

21Plugins 將 skills 新增至 Claude Code,建立可由您或 Claude 叫用的 `/name` 快捷方式。

22 

23**位置**:plugin 根目錄中的 `skills/` 或 `commands/` 目錄

24 

25**檔案格式**:Skills 是包含 `SKILL.md` 的目錄;commands 是簡單的 markdown 檔案

26 

27**Skill 結構**:

28 

29```text theme={null}

30skills/

31├── pdf-processor/

32│ ├── SKILL.md

33│ ├── reference.md (optional)

34│ └── scripts/ (optional)

35└── code-reviewer/

36 └── SKILL.md

37```

38 

39**整合行為**:

40 

41* 安裝 plugin 時會自動探索 skills 和 commands

42* Claude 可以根據任務上下文自動叫用它們

43* Skills 可以在 SKILL.md 旁邊包含支援檔案

44 

45如需完整詳細資訊,請參閱 [Skills](/zh-TW/skills)。

46 

47### Agents

48 

49Plugins 可以提供專門的 subagents,用於 Claude 在適當時自動叫用的特定任務。

50 

51**位置**:plugin 根目錄中的 `agents/` 目錄

52 

53**檔案格式**:描述 agent 功能的 Markdown 檔案

54 

55**Agent 結構**:

56 

57```markdown theme={null}

58---

59name: agent-name

60description: What this agent specializes in and when Claude should invoke it

61model: sonnet

62effort: medium

63maxTurns: 20

64disallowedTools: Write, Edit

65---

66 

67Detailed system prompt for the agent describing its role, expertise, and behavior.

68```

69 

70Plugin agents 支援 `name`、`description`、`model`、`effort`、`maxTurns`、`tools`、`disallowedTools`、`skills`、`memory`、`background` 和 `isolation` frontmatter 欄位。唯一有效的 `isolation` 值是 `"worktree"`。出於安全原因,plugin 提供的 agents 不支援 `hooks`、`mcpServers` 和 `permissionMode`。

71 

72**整合點**:

73 

74* Agents 出現在 `/agents` 介面中

75* Claude 可以根據任務上下文自動叫用 agents

76* Users 可以手動叫用 agents

77* Plugin agents 與內建 Claude agents 一起運作

78 

79如需完整詳細資訊,請參閱 [Subagents](/zh-TW/sub-agents)。

80 

81### Hooks

82 

83Plugins 可以提供事件處理程式,自動回應 Claude Code 事件。

84 

85**位置**:plugin 根目錄中的 `hooks/hooks.json`,或在 plugin.json 中內聯

86 

87**格式**:具有事件匹配器和動作的 JSON 設定

88 

89**Hook 設定**:

90 

91```json theme={null}

92{

93 "hooks": {

94 "PostToolUse": [

95 {

96 "matcher": "Write|Edit",

97 "hooks": [

98 {

99 "type": "command",

100 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format-code.sh"

101 }

102 ]

103 }

104 ]

105 }

106}

107```

108 

109Plugin hooks 回應與 [user-defined hooks](/zh-TW/hooks) 相同的生命週期事件:

110 

111| Event | When it fires |

112| :-------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |

113| `SessionStart` | When a session begins or resumes |

114| `Setup` | When you start Claude Code with `--init-only`, or with `--init` or `--maintenance` in `-p` mode. For one-time preparation in CI or scripts |

115| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |

116| `UserPromptExpansion` | When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion |

117| `PreToolUse` | Before a tool call executes. Can block it |

118| `PermissionRequest` | When a permission dialog appears |

119| `PermissionDenied` | When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call |

120| `PostToolUse` | After a tool call succeeds |

121| `PostToolUseFailure` | After a tool call fails |

122| `PostToolBatch` | After a full batch of parallel tool calls resolves, before the next model call |

123| `Notification` | When Claude Code sends a notification |

124| `SubagentStart` | When a subagent is spawned |

125| `SubagentStop` | When a subagent finishes |

126| `TaskCreated` | When a task is being created via `TaskCreate` |

127| `TaskCompleted` | When a task is being marked as completed |

128| `Stop` | When Claude finishes responding |

129| `StopFailure` | When the turn ends due to an API error. Output and exit code are ignored |

130| `TeammateIdle` | When an [agent team](/en/agent-teams) teammate is about to go idle |

131| `InstructionsLoaded` | When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session |

132| `ConfigChange` | When a configuration file changes during a session |

133| `CwdChanged` | When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv |

134| `FileChanged` | When a watched file changes on disk. The `matcher` field specifies which filenames to watch |

135| `WorktreeCreate` | When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior |

136| `WorktreeRemove` | When a worktree is being removed, either at session exit or when a subagent finishes |

137| `PreCompact` | Before context compaction |

138| `PostCompact` | After context compaction completes |

139| `Elicitation` | When an MCP server requests user input during a tool call |

140| `ElicitationResult` | After a user responds to an MCP elicitation, before the response is sent back to the server |

141| `SessionEnd` | When a session terminates |

142 

143**Hook 類型**:

144 

145* `command`:執行 shell 命令或指令碼

146* `http`:將事件 JSON 作為 POST 請求傳送到 URL

147* `mcp_tool`:在已設定的 [MCP server](/zh-TW/mcp) 上呼叫工具

148* `prompt`:使用 LLM 評估提示(使用 `$ARGUMENTS` 佔位符表示上下文)

149* `agent`:執行具有工具的 agentic 驗證器以進行複雜驗證任務

150 

151### MCP servers

152 

153Plugins 可以捆綁 Model Context Protocol (MCP) servers,將 Claude Code 與外部工具和服務連接。

154 

155**位置**:plugin 根目錄中的 `.mcp.json`,或在 plugin.json 中內聯

156 

157**格式**:標準 MCP server 設定

158 

159**MCP server 設定**:

160 

161```json theme={null}

162{

163 "mcpServers": {

164 "plugin-database": {

165 "command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server",

166 "args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"],

167 "env": {

168 "DB_PATH": "${CLAUDE_PLUGIN_ROOT}/data"

169 }

170 },

171 "plugin-api-client": {

172 "command": "npx",

173 "args": ["@company/mcp-server", "--plugin-mode"],

174 "cwd": "${CLAUDE_PLUGIN_ROOT}"

175 }

176 }

177}

178```

179 

180**整合行為**:

181 

182* 啟用 plugin 時,Plugin MCP servers 會自動啟動

183* Servers 在 Claude 的工具組中顯示為標準 MCP 工具

184* Server 功能與 Claude 的現有工具無縫整合

185* Plugin servers 可以獨立於使用者 MCP servers 進行設定

186 

187### LSP servers

188 

189<Tip>

190 想要使用 LSP plugins?從官方 marketplace 安裝它們:在 `/plugin` Discover 標籤中搜尋「lsp」。本節記錄如何為官方 marketplace 未涵蓋的語言建立 LSP plugins。

191</Tip>

192 

193Plugins 可以提供 [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) (LSP) servers,在處理程式碼庫時為 Claude 提供即時程式碼智慧。

194 

195LSP 整合提供:

196 

197* **即時診斷**:Claude 在每次編輯後立即看到錯誤和警告

198* **程式碼導航**:前往定義、尋找參考和懸停資訊

199* **語言感知**:程式碼符號的類型資訊和文件

200 

201**位置**:plugin 根目錄中的 `.lsp.json`,或在 `plugin.json` 中內聯

202 

203**格式**:將語言伺服器名稱對應到其設定的 JSON 設定

204 

205**`.lsp.json` 檔案格式**:

206 

207```json theme={null}

208{

209 "go": {

210 "command": "gopls",

211 "args": ["serve"],

212 "extensionToLanguage": {

213 ".go": "go"

214 }

215 }

216}

217```

218 

219**在 `plugin.json` 中內聯**:

220 

221```json theme={null}

222{

223 "name": "my-plugin",

224 "lspServers": {

225 "go": {

226 "command": "gopls",

227 "args": ["serve"],

228 "extensionToLanguage": {

229 ".go": "go"

230 }

231 }

232 }

233}

234```

235 

236**必需欄位:**

237 

238| 欄位 | 描述 |

239| :-------------------- | :------------------------ |

240| `command` | 要執行的 LSP 二進位檔(必須在 PATH 中) |

241| `extensionToLanguage` | 將檔案副檔名對應到語言識別碼 |

242 

243**選用欄位:**

244 

245| 欄位 | 描述 |

246| :---------------------- | :------------------------------------------ |

247| `args` | LSP server 的命令列引數 |

248| `transport` | 通訊傳輸:`stdio`(預設)或 `socket` |

249| `env` | 啟動 server 時要設定的環境變數 |

250| `initializationOptions` | 在初始化期間傳遞給 server 的選項 |

251| `settings` | 透過 `workspace/didChangeConfiguration` 傳遞的設定 |

252| `workspaceFolder` | server 的工作區資料夾路徑 |

253| `startupTimeout` | 等待 server 啟動的最長時間(毫秒) |

254| `shutdownTimeout` | 等待正常關閉的最長時間(毫秒) |

255| `restartOnCrash` | 如果 server 當機,是否自動重新啟動 |

256| `maxRestarts` | 放棄前的最大重新啟動嘗試次數 |

257 

258<Warning>

259 **您必須單獨安裝語言伺服器二進位檔。** LSP plugins 設定 Claude Code 如何連接到語言伺服器,但它們不包括伺服器本身。如果您在 `/plugin` Errors 標籤中看到 `Executable not found in $PATH`,請為您的語言安裝所需的二進位檔。

260</Warning>

261 

262**可用的 LSP plugins:**

263 

264| Plugin | 語言伺服器 | 安裝命令 |

265| :--------------- | :------------------------- | :------------------------------------------------------------------------------ |

266| `pyright-lsp` | Pyright (Python) | `pip install pyright` 或 `npm install -g pyright` |

267| `typescript-lsp` | TypeScript Language Server | `npm install -g typescript-language-server typescript` |

268| `rust-lsp` | rust-analyzer | [參閱 rust-analyzer 安裝](https://rust-analyzer.github.io/manual.html#installation) |

269 

270先安裝語言伺服器,然後從 marketplace 安裝 plugin。

271 

272### Monitors

273 

274Plugins 可以宣告背景 monitors,Claude Code 在 plugin 啟用時自動啟動。每個 monitor 執行一個 shell 命令,持續整個工作階段,並將每個 stdout 行傳遞給 Claude 作為通知,以便 Claude 可以對日誌項目、狀態變更或輪詢事件做出反應,而無需被要求自行啟動監視。

275 

276Plugin monitors 使用與 [Monitor tool](/zh-TW/tools-reference#monitor-tool) 相同的機制,並共享其可用性限制。它們僅在互動式 CLI 工作階段中執行,以與 [hooks](#hooks) 相同的信任級別在未沙箱化的環境中執行,並在 Monitor tool 不可用的主機上被跳過。

277 

278<Note>

279 Plugin monitors 需要 Claude Code v2.1.105 或更新版本。

280</Note>

281 

282**位置**:plugin 根目錄中的 `monitors/monitors.json`,或在 `plugin.json` 中內聯

283 

284**格式**:monitor 項目的 JSON 陣列

285 

286以下 `monitors/monitors.json` 監視部署狀態端點和本機錯誤日誌:

287 

288```json theme={null}

289[

290 {

291 "name": "deploy-status",

292 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/poll-deploy.sh ${user_config.api_endpoint}",

293 "description": "Deployment status changes"

294 },

295 {

296 "name": "error-log",

297 "command": "tail -F ./logs/error.log",

298 "description": "Application error log",

299 "when": "on-skill-invoke:debug"

300 }

301]

302```

303 

304若要內聯宣告 monitors,請將 `plugin.json` 中的 `monitors` 金鑰設定為相同的陣列。若要從非預設路徑載入,請將 `monitors` 設定為相對路徑字串,例如 `"./config/monitors.json"`。

305 

306**必需欄位:**

307 

308| 欄位 | 描述 |

309| :------------ | :------------------------------------------------- |

310| `name` | 在 plugin 中唯一的識別碼。防止 plugin 重新載入或再次叫用 skill 時出現重複程序 |

311| `command` | 在工作階段工作目錄中作為持久背景程序執行的 shell 命令 |

312| `description` | 正在監視的內容的簡短摘要。顯示在任務面板和通知摘要中 |

313 

314**選用欄位:**

315 

316| 欄位 | 描述 |

317| :----- | :----------------------------------------------------------------------------------------------------------------------- |

318| `when` | 控制 monitor 何時啟動。`"always"` 在工作階段啟動和 plugin 重新載入時啟動它,是預設值。`"on-skill-invoke:<skill-name>"` 在此 plugin 中的命名 skill 首次被分派時啟動它 |

319 

320`command` 值支援與 MCP 和 LSP server 設定相同的 [variable substitutions](#environment-variables):`${CLAUDE_PLUGIN_ROOT}`、`${CLAUDE_PLUGIN_DATA}`、`${user_config.*}` 和環境中的任何 `${ENV_VAR}`。如果指令碼需要從 plugin 自己的目錄執行,請在命令前加上 `cd "${CLAUDE_PLUGIN_ROOT}" && `。

321 

322在工作階段中途停用 plugin 不會停止已在執行的 monitors。它們在工作階段結束時停止。

323 

324### Themes

325 

326Plugins 可以提供顏色主題,這些主題與內建預設值和使用者的本機主題一起出現在 `/theme` 中。主題是 `themes/` 中的 JSON 檔案,具有 `base` 預設值和稀疏的 `overrides` 顏色令牌對應。

327 

328```json theme={null}

329{

330 "name": "Dracula",

331 "base": "dark",

332 "overrides": {

333 "claude": "#bd93f9",

334 "error": "#ff5555",

335 "success": "#50fa7b"

336 }

337}

338```

339 

340選擇 plugin 主題會在使用者的設定中保留 `custom:<plugin-name>:<slug>`。Plugin 主題是唯讀的;在 `/theme` 中按 `Ctrl+E` 會將其複製到 `~/.claude/themes/`,以便使用者可以編輯副本。

341 

342***

343 

344## Plugin 安裝範圍

345 

346安裝 plugin 時,您選擇一個**範圍**,決定 plugin 的可用位置和誰可以使用它:

347 

348| 範圍 | 設定檔 | 使用案例 |

349| :-------- | :------------------------------------------------- | :----------------------- |

350| `user` | `~/.claude/settings.json` | 在所有專案中可用的個人 plugins(預設) |

351| `project` | `.claude/settings.json` | 透過版本控制共享的團隊 plugins |

352| `local` | `.claude/settings.local.json` | 專案特定的 plugins,gitignored |

353| `managed` | [Managed settings](/zh-TW/settings#settings-files) | 受管理的 plugins(唯讀,僅更新) |

354 

355Plugins 使用與其他 Claude Code 設定相同的範圍系統。如需安裝說明和範圍旗標,請參閱 [安裝 plugins](/zh-TW/discover-plugins#install-plugins)。如需範圍的完整說明,請參閱 [Configuration scopes](/zh-TW/settings#configuration-scopes)。

356 

357***

358 

359## Plugin manifest 架構

360 

361`.claude-plugin/plugin.json` 檔案定義您的 plugin 的中繼資料和設定。本節記錄所有支援的欄位和選項。

362 

363manifest 是選用的。如果省略,Claude Code 會自動探索 [預設位置](#file-locations-reference) 中的元件,並從目錄名稱衍生 plugin 名稱。當您需要提供中繼資料或自訂元件路徑時,請使用 manifest。

364 

365### 完整架構

366 

367```json theme={null}

368{

369 "name": "plugin-name",

370 "version": "1.2.0",

371 "description": "Brief plugin description",

372 "author": {

373 "name": "Author Name",

374 "email": "author@example.com",

375 "url": "https://github.com/author"

376 },

377 "homepage": "https://docs.example.com/plugin",

378 "repository": "https://github.com/author/plugin",

379 "license": "MIT",

380 "keywords": ["keyword1", "keyword2"],

381 "skills": "./custom/skills/",

382 "commands": ["./custom/commands/special.md"],

383 "agents": ["./custom/agents/reviewer.md"],

384 "hooks": "./config/hooks.json",

385 "mcpServers": "./mcp-config.json",

386 "outputStyles": "./styles/",

387 "themes": "./themes/",

388 "lspServers": "./.lsp.json",

389 "monitors": "./monitors.json",

390 "dependencies": [

391 "helper-lib",

392 { "name": "secrets-vault", "version": "~2.1.0" }

393 ]

394}

395```

396 

397### 必需欄位

398 

399如果您包含 manifest,`name` 是唯一必需的欄位。

400 

401| 欄位 | 類型 | 描述 | 範例 |

402| :----- | :----- | :-------------------- | :------------------- |

403| `name` | string | 唯一識別碼(kebab-case,無空格) | `"deployment-tools"` |

404 

405此名稱用於命名空間元件。例如,在 UI 中,名稱為 `plugin-dev` 的 plugin 的 agent `agent-creator` 將顯示為 `plugin-dev:agent-creator`。

406 

407### 中繼資料欄位

408 

409| 欄位 | 類型 | 描述 | 範例 |

410| :------------ | :----- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------- |

411| `$schema` | string | JSON Schema URL,用於編輯器自動完成和驗證。Claude Code 在載入時忽略此欄位。 | `"https://json.schemastore.org/claude-code-plugin-manifest.json"` |

412| `version` | string | 選用。語義版本。設定此項會將 plugin 固定到該版本字串,因此使用者只會在您提升版本時收到更新。如果省略,Claude Code 會回退到 git commit SHA,因此每個 commit 都被視為新版本。如果也在 marketplace 項目中設定,`plugin.json` 優先。請參閱 [Version management](#version-management)。 | `"2.1.0"` |

413| `description` | string | plugin 用途的簡短說明 | `"Deployment automation tools"` |

414| `author` | object | 作者資訊 | `{"name": "Dev Team", "email": "dev@company.com"}` |

415| `homepage` | string | 文件 URL | `"https://docs.example.com"` |

416| `repository` | string | 原始程式碼 URL | `"https://github.com/user/plugin"` |

417| `license` | string | 授權識別碼 | `"MIT"`、`"Apache-2.0"` |

418| `keywords` | array | 探索標籤 | `["deployment", "ci-cd"]` |

419 

420### 元件路徑欄位

421 

422| 欄位 | 類型 | 描述 | 範例 |

423| :------------- | :-------------------- | :-------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------- |

424| `skills` | string\|array | 包含 `<name>/SKILL.md` 的自訂 skill 目錄(取代預設 `skills/`) | `"./custom/skills/"` |

425| `commands` | string\|array | 自訂平面 `.md` skill 檔案或目錄(取代預設 `commands/`) | `"./custom/cmd.md"` 或 `["./cmd1.md"]` |

426| `agents` | string\|array | 自訂 agent 檔案(取代預設 `agents/`) | `"./custom/agents/reviewer.md"` |

427| `hooks` | string\|array\|object | Hook 設定路徑或內聯設定 | `"./my-extra-hooks.json"` |

428| `mcpServers` | string\|array\|object | MCP 設定路徑或內聯設定 | `"./my-extra-mcp-config.json"` |

429| `outputStyles` | string\|array | 自訂輸出樣式檔案/目錄(取代預設 `output-styles/`) | `"./styles/"` |

430| `themes` | string\|array | 色彩主題檔案/目錄(取代預設 `themes/`)。請參閱 [Themes](#themes) | `"./themes/"` |

431| `lspServers` | string\|array\|object | [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) 設定,用於程式碼智慧(前往定義、尋找參考等) | `"./.lsp.json"` |

432| `monitors` | string\|array | 背景 [Monitor](/zh-TW/tools-reference#monitor-tool) 設定,在 plugin 啟用時自動啟動。請參閱 [Monitors](#monitors) | `"./monitors.json"` |

433| `userConfig` | object | 在啟用時提示使用者的使用者可設定值。請參閱 [User configuration](#user-configuration) | 請參閱下方 |

434| `channels` | array | 訊息注入的頻道宣告(Telegram、Slack、Discord 風格)。請參閱 [Channels](#channels) | 請參閱下方 |

435| `dependencies` | array | 此 plugin 需要的其他 plugins,可選擇使用 semver 版本限制。請參閱 [Constrain plugin dependency versions](/zh-TW/plugin-dependencies) | `[{ "name": "secrets-vault", "version": "~2.1.0" }]` |

436 

437### User configuration

438 

439`userConfig` 欄位宣告 Claude Code 在啟用 plugin 時提示使用者的值。使用此方法而不是要求使用者手動編輯 `settings.json`。

440 

441```json theme={null}

442{

443 "userConfig": {

444 "api_endpoint": {

445 "type": "string",

446 "title": "API endpoint",

447 "description": "Your team's API endpoint"

448 },

449 "api_token": {

450 "type": "string",

451 "title": "API token",

452 "description": "API authentication token",

453 "sensitive": true

454 }

455 }

456}

457```

458 

459金鑰必須是有效的識別碼。每個選項支援這些欄位:

460 

461| 欄位 | 必需 | 描述 |

462| :------------ | :-- | :---------------------------------------------------- |

463| `type` | Yes | 其中之一:`string`、`number`、`boolean`、`directory` 或 `file` |

464| `title` | Yes | 設定對話方塊中顯示的標籤 |

465| `description` | Yes | 欄位下方顯示的說明文字 |

466| `sensitive` | No | 如果 `true`,遮罩輸入並將值儲存在安全儲存體中,而不是 `settings.json` |

467| `required` | No | 如果 `true`,當欄位為空時驗證失敗 |

468| `default` | No | 使用者未提供任何內容時使用的值 |

469| `multiple` | No | 對於 `string` 類型,允許字串陣列 |

470| `min` / `max` | No | `number` 類型的界限 |

471 

472每個值都可用於在 MCP 和 LSP server 設定、hook 命令、monitor 命令中替換為 `${user_config.KEY}`,以及(僅適用於非敏感值)skill 和 agent 內容。值也會匯出到 plugin 子程序作為 `CLAUDE_PLUGIN_OPTION_<KEY>` 環境變數。

473 

474非敏感值儲存在 `settings.json` 中的 `pluginConfigs[<plugin-id>].options` 下。敏感值進入系統鑰匙圈(或在鑰匙圈不可用的地方進入 `~/.claude/.credentials.json`)。鑰匙圈儲存與 OAuth 令牌共享,總限制約為 2 KB,因此請保持敏感值較小。

475 

476### Channels

477 

478`channels` 欄位讓 plugin 宣告一個或多個訊息頻道,將內容注入對話中。每個頻道繫結到 plugin 提供的 MCP server。

479 

480```json theme={null}

481{

482 "channels": [

483 {

484 "server": "telegram",

485 "userConfig": {

486 "bot_token": {

487 "type": "string",

488 "title": "Bot token",

489 "description": "Telegram bot token",

490 "sensitive": true

491 },

492 "owner_id": {

493 "type": "string",

494 "title": "Owner ID",

495 "description": "Your Telegram user ID"

496 }

497 }

498 }

499 ]

500}

501```

502 

503`server` 欄位是必需的,必須與 plugin 的 `mcpServers` 中的金鑰相符。選用的每個頻道 `userConfig` 使用與頂層欄位相同的架構,讓 plugin 在啟用 plugin 時提示輸入機器人令牌或擁有者 ID。

504 

505### 路徑行為規則

506 

507對於 `skills`、`commands`、`agents`、`outputStyles`、`themes` 和 `monitors`,自訂路徑取代預設值。如果 manifest 指定 `skills`,預設 `skills/` 目錄不會被掃描;如果它指定 `monitors`,預設 `monitors/monitors.json` 不會被載入。[Hooks](#hooks)、[MCP servers](#mcp-servers) 和 [LSP servers](#lsp-servers) 有不同的語義來處理多個來源。

508 

509* 所有路徑必須相對於 plugin 根目錄,並以 `./` 開頭

510* 來自自訂路徑的元件使用相同的命名和命名空間規則

511* 可以將多個路徑指定為陣列

512* 若要保留預設目錄並為 skills、commands、agents 或 output styles 新增更多路徑,請在陣列中包含預設值:`"skills": ["./skills/", "./extras/"]`

513* 當 skill 路徑指向直接包含 `SKILL.md` 的目錄時,例如 `"skills": ["./"]` 指向 plugin 根目錄,frontmatter 中的 `name` 欄位決定 skill 的叫用名稱。這提供了一個穩定的名稱,無論安裝目錄如何。如果 frontmatter 中未設定 `name`,目錄基名將用作後備。

514 

515**路徑範例**:

516 

517```json theme={null}

518{

519 "commands": [

520 "./specialized/deploy.md",

521 "./utilities/batch-process.md"

522 ],

523 "agents": [

524 "./custom-agents/reviewer.md",

525 "./custom-agents/tester.md"

526 ]

527}

528```

529 

530### 環境變數

531 

532Claude Code 提供兩個變數用於參考 plugin 路徑。兩者都在 skill 內容、agent 內容、hook 命令、monitor 命令以及 MCP 或 LSP server 設定中出現的任何地方內聯替換。兩者也會匯出為環境變數到 hook 程序和 MCP 或 LSP server 子程序。

533 

534**`${CLAUDE_PLUGIN_ROOT}`**:plugin 安裝目錄的絕對路徑。使用此方法參考與 plugin 捆綁的指令碼、二進位檔和設定檔。此路徑在 plugin 更新時會變更,因此您在此處寫入的檔案不會在更新後保留。

535 

536**`${CLAUDE_PLUGIN_DATA}`**:用於在更新後保留的 plugin 狀態的持久目錄。使用此方法用於已安裝的依賴項,例如 `node_modules` 或 Python 虛擬環境、生成的程式碼、快取和任何應在 plugin 版本之間保留的其他檔案。首次參考此變數時會自動建立目錄。

537 

538```json theme={null}

539{

540 "hooks": {

541 "PostToolUse": [

542 {

543 "hooks": [

544 {

545 "type": "command",

546 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/process.sh"

547 }

548 ]

549 }

550 ]

551 }

552}

553```

554 

555#### 持久資料目錄

556 

557`${CLAUDE_PLUGIN_DATA}` 目錄解析為 `~/.claude/plugins/data/{id}/`,其中 `{id}` 是 plugin 識別碼,其中 `a-z`、`A-Z`、`0-9`、`_` 和 `-` 以外的字元被替換為 `-`。對於安裝為 `formatter@my-marketplace` 的 plugin,目錄是 `~/.claude/plugins/data/formatter-my-marketplace/`。

558 

559常見用途是一次安裝語言依賴項並在工作階段和 plugin 更新中重複使用它們。因為資料目錄的壽命超過任何單一 plugin 版本,僅檢查目錄存在無法偵測更新何時變更 plugin 的依賴項清單。建議的模式是比較捆綁的清單與資料目錄中的副本,並在它們不同時重新安裝。

560 

561此 `SessionStart` hook 在第一次執行時安裝 `node_modules`,並在 plugin 更新包含變更的 `package.json` 時再次安裝:

562 

563```json theme={null}

564{

565 "hooks": {

566 "SessionStart": [

567 {

568 "hooks": [

569 {

570 "type": "command",

571 "command": "diff -q \"${CLAUDE_PLUGIN_ROOT}/package.json\" \"${CLAUDE_PLUGIN_DATA}/package.json\" >/dev/null 2>&1 || (cd \"${CLAUDE_PLUGIN_DATA}\" && cp \"${CLAUDE_PLUGIN_ROOT}/package.json\" . && npm install) || rm -f \"${CLAUDE_PLUGIN_DATA}/package.json\""

572 }

573 ]

574 }

575 ]

576 }

577}

578```

579 

580`diff` 在儲存的副本遺失或與捆綁的副本不同時以非零值退出,涵蓋第一次執行和依賴項變更更新。如果 `npm install` 失敗,尾部 `rm` 會移除複製的清單,以便下一個工作階段重試。

581 

582捆綁在 `${CLAUDE_PLUGIN_ROOT}` 中的指令碼可以針對保留的 `node_modules` 執行:

583 

584```json theme={null}

585{

586 "mcpServers": {

587 "routines": {

588 "command": "node",

589 "args": ["${CLAUDE_PLUGIN_ROOT}/server.js"],

590 "env": {

591 "NODE_PATH": "${CLAUDE_PLUGIN_DATA}/node_modules"

592 }

593 }

594 }

595}

596```

597 

598當您從最後一個安裝 plugin 的範圍卸載 plugin 時,資料目錄會自動刪除。`/plugin` 介面顯示目錄大小並在刪除前提示。CLI 預設刪除;傳遞 [`--keep-data`](#plugin-uninstall) 以保留它。

599 

600***

601 

602## Plugin 快取和檔案解析

603 

604Plugins 可以透過以下兩種方式之一指定:

605 

606* 透過 `claude --plugin-dir`,在工作階段期間。

607* 透過 marketplace,為未來的工作階段安裝。

608 

609出於安全和驗證目的,Claude Code 將 *marketplace* plugins 複製到使用者的本機 **plugin 快取**(`~/.claude/plugins/cache`),而不是就地使用它們。在開發參考外部檔案的 plugins 時,理解此行為很重要。

610 

611每個已安裝的版本是快取中的單獨目錄。當您更新或卸載 plugin 時,先前的版本目錄被標記為孤立,並在 7 天後自動移除。寬限期讓已載入舊版本的並行 Claude Code 工作階段繼續執行而不出錯。

612 

613Claude 的 Glob 和 Grep 工具在搜尋期間跳過孤立的版本目錄,因此檔案結果不包含過時的 plugin 程式碼。

614 

615### 路徑遍歷限制

616 

617已安裝的 plugins 無法參考其目錄外的檔案。遍歷 plugin 根目錄外的路徑(例如 `../shared-utils`)在安裝後將無法運作,因為這些外部檔案不會複製到快取中。

618 

619### 使用外部依賴項

620 

621如果您的 plugin 需要存取其目錄外的檔案,您可以在 plugin 目錄中建立指向外部檔案的符號連結。符號連結在快取中被保留而不是被取消參考,並在執行時解析到其目標。以下命令從 plugin 目錄內建立到共享公用程式位置的連結:

622 

623```bash theme={null}

624ln -s /path/to/shared-utils ./shared-utils

625```

626 

627這在維持快取系統安全優勢的同時提供了靈活性。

628 

629***

630 

631## Plugin 目錄結構

632 

633### 標準 plugin 配置

634 

635完整的 plugin 遵循此結構:

636 

637```text theme={null}

638enterprise-plugin/

639├── .claude-plugin/ # Metadata directory (optional)

640│ └── plugin.json # plugin manifest

641├── skills/ # Skills

642│ ├── code-reviewer/

643│ │ └── SKILL.md

644│ └── pdf-processor/

645│ ├── SKILL.md

646│ └── scripts/

647├── commands/ # Skills as flat .md files

648│ ├── status.md

649│ └── logs.md

650├── agents/ # Subagent definitions

651│ ├── security-reviewer.md

652│ ├── performance-tester.md

653│ └── compliance-checker.md

654├── output-styles/ # Output style definitions

655│ └── terse.md

656├── themes/ # Color theme definitions

657│ └── dracula.json

658├── monitors/ # Background monitor configurations

659│ └── monitors.json

660├── hooks/ # Hook configurations

661│ ├── hooks.json # Main hook config

662│ └── security-hooks.json # Additional hooks

663├── bin/ # Plugin executables added to PATH

664│ └── my-tool # Invokable as bare command in Bash tool

665├── settings.json # Default settings for the plugin

666├── .mcp.json # MCP server definitions

667├── .lsp.json # LSP server configurations

668├── scripts/ # Hook and utility scripts

669│ ├── security-scan.sh

670│ ├── format-code.py

671│ └── deploy.js

672├── LICENSE # License file

673└── CHANGELOG.md # Version history

674```

675 

676<Warning>

677 `.claude-plugin/` 目錄包含 `plugin.json` 檔案。所有其他目錄(commands/、agents/、skills/、output-styles/、themes/、monitors/、hooks/)必須位於 plugin 根目錄,而不是在 `.claude-plugin/` 內。

678</Warning>

679 

680### 檔案位置參考

681 

682| 元件 | 預設位置 | 用途 |

683| :---------------- | :--------------------------- | :------------------------------------------------------------------------------------------------------------------------- |

684| **Manifest** | `.claude-plugin/plugin.json` | Plugin 中繼資料和設定(選用) |

685| **Skills** | `skills/` | 具有 `<name>/SKILL.md` 結構的 Skills |

686| **Commands** | `commands/` | 作為平面 Markdown 檔案的 Skills。新 plugins 使用 `skills/` |

687| **Agents** | `agents/` | Subagent Markdown 檔案 |

688| **Output styles** | `output-styles/` | 輸出樣式定義 |

689| **Themes** | `themes/` | 色彩主題定義 |

690| **Hooks** | `hooks/hooks.json` | Hook 設定 |

691| **MCP servers** | `.mcp.json` | MCP server 定義 |

692| **LSP servers** | `.lsp.json` | 語言伺服器設定 |

693| **Monitors** | `monitors/monitors.json` | 背景 monitor 設定 |

694| **Executables** | `bin/` | 新增到 Bash tool 的 `PATH` 的可執行檔。此處的檔案在 plugin 啟用時可在任何 Bash tool 呼叫中作為裸命令叫用 |

695| **Settings** | `settings.json` | 啟用 plugin 時套用的預設設定。目前僅支援 [`agent`](/zh-TW/sub-agents) 和 [`subagentStatusLine`](/zh-TW/statusline#subagent-status-lines) 金鑰 |

696 

697***

698 

699## CLI 命令參考

700 

701Claude Code 提供 CLI 命令用於非互動式 plugin 管理,適用於指令碼和自動化。

702 

703### plugin install

704 

705從可用的 marketplaces 安裝 plugin。

706 

707```bash theme={null}

708claude plugin install <plugin> [options]

709```

710 

711**引數:**

712 

713* `<plugin>`:Plugin 名稱或 `plugin-name@marketplace-name` 用於特定 marketplace

714 

715**選項:**

716 

717| 選項 | 描述 | 預設 |

718| :-------------------- | :------------------------------ | :----- |

719| `-s, --scope <scope>` | 安裝範圍:`user`、`project` 或 `local` | `user` |

720| `-h, --help` | 顯示命令說明 | |

721 

722範圍決定已安裝的 plugin 新增到哪個設定檔。例如,`--scope project` 寫入 `.claude/settings.json` 中的 `enabledPlugins`,使 plugin 對克隆專案存放庫的每個人都可用。

723 

724**範例:**

725 

726```bash theme={null}

727# Install to user scope (default)

728claude plugin install formatter@my-marketplace

729 

730# Install to project scope (shared with team)

731claude plugin install formatter@my-marketplace --scope project

732 

733# Install to local scope (gitignored)

734claude plugin install formatter@my-marketplace --scope local

735```

736 

737### plugin uninstall

738 

739移除已安裝的 plugin。

740 

741```bash theme={null}

742claude plugin uninstall <plugin> [options]

743```

744 

745**引數:**

746 

747* `<plugin>`:Plugin 名稱或 `plugin-name@marketplace-name`

748 

749**選項:**

750 

751| 選項 | 描述 | 預設 |

752| :-------------------- | :------------------------------------------------------------------ | :----- |

753| `-s, --scope <scope>` | 從範圍卸載:`user`、`project` 或 `local` | `user` |

754| `--keep-data` | 保留 plugin 的 [persistent data directory](#persistent-data-directory) | |

755| `--prune` | 同時移除其他 plugin 不需要的自動安裝相依性。請參閱 [plugin prune](#plugin-prune) | |

756| `-y, --yes` | 跳過 `--prune` 確認提示。當 stdin 不是 TTY 時為必需 | |

757| `-h, --help` | 顯示命令說明 | |

758 

759**別名:** `remove`、`rm`

760 

761預設情況下,從最後一個剩餘範圍卸載也會刪除 plugin 的 `${CLAUDE_PLUGIN_DATA}` 目錄。使用 `--keep-data` 保留它,例如在測試新版本後重新安裝時。

762 

763### plugin prune

764 

765移除不再被任何已安裝 plugin 所需的自動安裝 plugin 相依性。Claude Code 為滿足另一個 plugin 的 [`dependencies`](/zh-TW/plugin-dependencies) 欄位而引入的相依性會被移除;您直接安裝的 plugins 永遠不會被觸及。

766 

767```bash theme={null}

768claude plugin prune [options]

769```

770 

771**選項:**

772 

773| 選項 | 描述 | 預設 |

774| :-------------------- | :--------------------------------- | :----- |

775| `-s, --scope <scope>` | 在範圍進行修剪:`user`、`project` 或 `local` | `user` |

776| `--dry-run` | 列出將被移除的內容而不實際移除 | |

777| `-y, --yes` | 跳過確認提示。當 stdin 不是 TTY 時為必需 | |

778| `-h, --help` | 顯示命令說明 | |

779 

780**別名:** `autoremove`

781 

782該命令列出孤立的相依性並在移除前要求確認。若要在一個步驟中移除 plugin 並清理其相依性,請執行 `claude plugin uninstall <plugin> --prune`。

783 

784<Note>

785 `claude plugin prune` 需要 Claude Code v2.1.121 或更新版本。

786</Note>

787 

788### plugin enable

789 

790啟用已停用的 plugin。

791 

792```bash theme={null}

793claude plugin enable <plugin> [options]

794```

795 

796**引數:**

797 

798* `<plugin>`:Plugin 名稱或 `plugin-name@marketplace-name`

799 

800**選項:**

801 

802| 選項 | 描述 | 預設 |

803| :-------------------- | :-------------------------------- | :----- |

804| `-s, --scope <scope>` | 要啟用的範圍:`user`、`project` 或 `local` | `user` |

805| `-h, --help` | 顯示命令說明 | |

806 

807### plugin disable

808 

809停用 plugin 而不卸載它。

810 

811```bash theme={null}

812claude plugin disable <plugin> [options]

813```

814 

815**引數:**

816 

817* `<plugin>`:Plugin 名稱或 `plugin-name@marketplace-name`

818 

819**選項:**

820 

821| 選項 | 描述 | 預設 |

822| :-------------------- | :-------------------------------- | :----- |

823| `-s, --scope <scope>` | 要停用的範圍:`user`、`project` 或 `local` | `user` |

824| `-h, --help` | 顯示命令說明 | |

825 

826### plugin update

827 

828將 plugin 更新到最新版本。

829 

830```bash theme={null}

831claude plugin update <plugin> [options]

832```

833 

834**引數:**

835 

836* `<plugin>`:Plugin 名稱或 `plugin-name@marketplace-name`

837 

838**選項:**

839 

840| 選項 | 描述 | 預設 |

841| :-------------------- | :------------------------------------------ | :----- |

842| `-s, --scope <scope>` | 要更新的範圍:`user`、`project`、`local` 或 `managed` | `user` |

843| `-h, --help` | 顯示命令說明 | |

844 

845***

846 

847### plugin list

848 

849列出已安裝的 plugins 及其版本、來源 marketplace 和啟用狀態。

850 

851```bash theme={null}

852claude plugin list [options]

853```

854 

855**選項:**

856 

857| 選項 | 描述 | 預設 |

858| :------------ | :---------------------------------------- | :- |

859| `--json` | 輸出為 JSON | |

860| `--available` | 包含來自 marketplaces 的可用 plugins。需要 `--json` | |

861| `-h, --help` | 顯示命令說明 | |

862 

863### plugin tag

864 

865為目前目錄中的 plugin 建立發行版 git 標籤。從 plugin 的資料夾內執行。請參閱 [Tag plugin releases](/zh-TW/plugin-dependencies#tag-plugin-releases-for-version-resolution)。

866 

867```bash theme={null}

868claude plugin tag [options]

869```

870 

871**選項:**

872 

873| 選項 | 描述 | 預設 |

874| :------------ | :----------------- | :- |

875| `--push` | 建立標籤後將其推送到遠端 | |

876| `--dry-run` | 列印將被標籤的內容而不建立標籤 | |

877| `-f, --force` | 即使工作樹髒污或標籤已存在也建立標籤 | |

878| `-h, --help` | 顯示命令說明 | |

879 

880***

881 

882## 偵錯和開發工具

883 

884### 偵錯命令

885 

886使用 `claude --debug` 查看 plugin 載入詳細資訊:

887 

888這會顯示:

889 

890* 正在載入哪些 plugins

891* plugin manifests 中的任何錯誤

892* Skill、agent 和 hook 註冊

893* MCP server 初始化

894 

895### 常見問題

896 

897| 問題 | 原因 | 解決方案 |

898| :---------------------------------- | :------------------------- | :------------------------------------------------------------------------------------------------------------------------------ |

899| Plugin 未載入 | 無效的 `plugin.json` | 執行 `claude plugin validate` 或 `/plugin validate` 檢查 `plugin.json`、skill/agent/command frontmatter 和 `hooks/hooks.json` 的語法和架構錯誤 |

900| Skills 未出現 | 目錄結構錯誤 | 確保 `skills/` 或 `commands/` 在 plugin 根目錄,而不是在 `.claude-plugin/` 中 |

901| Hooks 未觸發 | 指令碼不可執行 | 執行 `chmod +x script.sh` |

902| MCP server 失敗 | 缺少 `${CLAUDE_PLUGIN_ROOT}` | 對所有 plugin 路徑使用變數 |

903| 路徑錯誤 | 使用了絕對路徑 | 所有路徑必須是相對的,並以 `./` 開頭 |

904| LSP `Executable not found in $PATH` | 未安裝語言伺服器 | 安裝二進位檔(例如 `npm install -g typescript-language-server typescript`) |

905 

906### 範例錯誤訊息

907 

908**Manifest 驗證錯誤**:

909 

910* `Invalid JSON syntax: Unexpected token } in JSON at position 142`:檢查是否缺少逗號、多餘逗號或未引用的字串

911* `Plugin has an invalid manifest file at .claude-plugin/plugin.json. Validation errors: name: Required`:缺少必需欄位

912* `Plugin has a corrupt manifest file at .claude-plugin/plugin.json. JSON parse error: ...`:JSON 語法錯誤

913 

914**Plugin 載入錯誤**:

915 

916* `Warning: No commands found in plugin my-plugin custom directory: ./cmds. Expected .md files or SKILL.md in subdirectories.`:命令路徑存在但不包含有效的命令檔案

917* `Plugin directory not found at path: ./plugins/my-plugin. Check that the marketplace entry has the correct path.`:marketplace.json 中的 `source` 路徑指向不存在的目錄

918* `Plugin my-plugin has conflicting manifests: both plugin.json and marketplace entry specify components.`:移除重複的元件定義或移除 marketplace 項目中的 `strict: false`

919 

920### Hook 疑難排解

921 

922**Hook 指令碼未執行**:

923 

9241. 檢查指令碼是否可執行:`chmod +x ./scripts/your-script.sh`

9252. 驗證 shebang 行:第一行應為 `#!/bin/bash` 或 `#!/usr/bin/env bash`

9263. 檢查路徑是否使用 `${CLAUDE_PLUGIN_ROOT}`:`"command": "${CLAUDE_PLUGIN_ROOT}/scripts/your-script.sh"`

9274. 手動測試指令碼:`./scripts/your-script.sh`

928 

929**Hook 未在預期事件上觸發**:

930 

9311. 驗證事件名稱是否正確(區分大小寫):`PostToolUse`,而不是 `postToolUse`

9322. 檢查匹配器模式是否與您的工具相符:`"matcher": "Write|Edit"` 用於檔案操作

9333. 確認 hook 類型有效:`command`、`http`、`mcp_tool`、`prompt` 或 `agent`

934 

935### MCP server 疑難排解

936 

937**Server 未啟動**:

938 

9391. 檢查命令是否存在且可執行

9402. 驗證所有路徑是否使用 `${CLAUDE_PLUGIN_ROOT}` 變數

9413. 檢查 MCP server 日誌:`claude --debug` 顯示初始化錯誤

9424. 在 Claude Code 外手動測試 server

943 

944**Server 工具未出現**:

945 

9461. 確保 server 在 `.mcp.json` 或 `plugin.json` 中正確設定

9472. 驗證 server 是否正確實現 MCP 協定

9483. 檢查偵錯輸出中的連接逾時

949 

950### 目錄結構錯誤

951 

952**症狀**:Plugin 載入但元件(skills、agents、hooks)遺失。

953 

954**正確結構**:元件必須位於 plugin 根目錄,而不是在 `.claude-plugin/` 內。只有 `plugin.json` 屬於 `.claude-plugin/`。

955 

956```text theme={null}

957my-plugin/

958├── .claude-plugin/

959│ └── plugin.json ← Only manifest here

960├── commands/ ← At root level

961├── agents/ ← At root level

962└── hooks/ ← At root level

963```

964 

965如果您的元件在 `.claude-plugin/` 內,請將它們移到 plugin 根目錄。

966 

967**偵錯檢查清單**:

968 

9691. 執行 `claude --debug` 並查找「loading plugin」訊息

9702. 檢查每個元件目錄是否列在偵錯輸出中

9713. 驗證檔案權限允許讀取 plugin 檔案

972 

973***

974 

975## 發佈和版本控制參考

976 

977### 版本管理

978 

979Claude Code 使用 plugin 的版本作為快取金鑰,以決定是否有可用的更新。當您執行 `/plugin update` 或自動更新觸發時,Claude Code 會計算目前版本,如果與已安裝的版本相符,則跳過更新。

980 

981版本會從以下第一個設定的項目解析:

982 

9831. Plugin 的 `plugin.json` 中的 `version` 欄位

9842. Plugin 在 `marketplace.json` 中的 marketplace 項目中的 `version` 欄位

9853. Plugin 來源的 git commit SHA,適用於 git 託管 marketplace 中的 `github`、`url`、`git-subdir` 和相對路徑來源

9864. `unknown`,適用於 `npm` 來源或不在 git 儲存庫內的本機目錄

987 

988這為您提供了兩種方式來版本化 plugin:

989 

990| 方法 | 如何操作 | 更新行為 | 最適合 |

991| :---------------- | :-------------------------------------------- | :----------------------------------------------------------------------- | :------------------- |

992| **明確版本** | 在 `plugin.json` 中設定 `"version": "2.1.0"` | 使用者只有在您提升此欄位時才會獲得更新。推送新的 commit 而不提升版本沒有效果,`/plugin update` 會報告「已是最新版本」。 | 具有穩定發行週期的已發佈 plugin |

993| **Commit-SHA 版本** | 從 `plugin.json` 和 marketplace 項目中省略 `version` | 使用者在每次 plugin 的 git 來源有新 commit 時都會獲得更新 | 正在積極開發中的內部或團隊 plugin |

994 

995<Warning>

996 如果您在 `plugin.json` 中設定 `version`,每次您想讓使用者接收變更時,都必須提升它。僅推送新的 commit 是不夠的,因為 Claude Code 會看到相同的版本字串並保留快取副本。如果您正在快速迭代,請保持 `version` 未設定,以便改為使用 git commit SHA。

997</Warning>

998 

999如果您使用明確版本,請遵循 [semantic versioning](https://semver.org)(`MAJOR.MINOR.PATCH`):針對破壞性變更提升 MAJOR,針對新功能提升 MINOR,針對錯誤修正提升 PATCH。在 `CHANGELOG.md` 中記錄變更。

1000 

1001***

1002 

1003## 另請參閱

1004 

1005* [Plugins](/zh-TW/plugins) - 教學和實際使用

1006* [Plugin marketplaces](/zh-TW/plugin-marketplaces) - 建立和管理 marketplaces

1007* [Skills](/zh-TW/skills) - Skill 開發詳細資訊

1008* [Subagents](/zh-TW/sub-agents) - Agent 設定和功能

1009* [Hooks](/zh-TW/hooks) - 事件處理和自動化

1010* [MCP](/zh-TW/mcp) - 外部工具整合

1011* [Settings](/zh-TW/settings) - Plugins 的設定選項

quickstart.md +976 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 快速入門

6 

7> 歡迎使用 Claude Code!

8 

9export const InstallConfigurator = ({defaultSurface = 'terminal'}) => {

10 const TERM = {

11 mac: {

12 label: 'macOS / Linux',

13 cmd: 'curl -fsSL https://claude.ai/install.sh | bash'

14 },

15 win: {

16 label: 'Windows'

17 },

18 brew: {

19 label: 'Homebrew',

20 cmd: 'brew install --cask claude-code'

21 },

22 winget: {

23 label: 'WinGet',

24 cmd: 'winget install Anthropic.ClaudeCode'

25 }

26 };

27 const WIN_VARIANTS = {

28 ps: 'irm https://claude.ai/install.ps1 | iex',

29 cmd: 'curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd'

30 };

31 const TABS = [{

32 key: 'terminal',

33 label: 'Terminal'

34 }, {

35 key: 'desktop',

36 label: 'Desktop'

37 }, {

38 key: 'vscode',

39 label: 'VS Code'

40 }, {

41 key: 'jetbrains',

42 label: 'JetBrains'

43 }];

44 const ALT_TARGETS = {

45 desktop: {

46 name: 'Desktop',

47 tagline: 'The full agent in a native app for macOS and Windows.',

48 installLabel: 'Download the app',

49 installHref: 'https://claude.com/download?utm_source=claude_code&utm_medium=docs&utm_content=configurator_desktop_download',

50 guideHref: '/en/desktop-quickstart'

51 },

52 vscode: {

53 name: 'VS Code',

54 tagline: 'Review diffs, manage context, and chat without leaving your editor.',

55 installLabel: 'Install from Marketplace',

56 installHref: 'https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code',

57 altCmd: 'code --install-extension anthropic.claude-code',

58 guideHref: '/en/vs-code'

59 },

60 jetbrains: {

61 name: 'JetBrains',

62 tagline: 'Native plugin for IntelliJ, PyCharm, WebStorm, and other JetBrains IDEs.',

63 installLabel: 'Install from Marketplace',

64 installHref: 'https://plugins.jetbrains.com/plugin/27310-claude-code-beta-',

65 guideHref: '/en/jetbrains'

66 }

67 };

68 const PROVIDERS = [{

69 key: 'anthropic',

70 label: 'Anthropic'

71 }, {

72 key: 'bedrock',

73 label: 'Amazon Bedrock'

74 }, {

75 key: 'foundry',

76 label: 'Microsoft Foundry'

77 }, {

78 key: 'vertex',

79 label: 'Google Vertex AI'

80 }];

81 const PROVIDER_NOTICE = {

82 bedrock: <>

83 <strong>Configure your AWS account first.</strong> Running on Bedrock

84 requires model access enabled in the AWS console and IAM credentials.{' '}

85 <a href="/en/amazon-bedrock">Bedrock setup guide →</a>

86 </>,

87 vertex: <>

88 <strong>Configure your GCP project first.</strong> Running on Vertex AI

89 requires the Vertex API enabled and a service account with the right

90 permissions.{' '}

91 <a href="/en/google-vertex-ai">Vertex setup guide →</a>

92 </>,

93 foundry: <>

94 <strong>Configure your Azure resources first.</strong> Running on

95 Microsoft Foundry requires an Azure subscription with a Foundry resource

96 and model deployments provisioned.{' '}

97 <a href="/en/microsoft-foundry">Foundry setup guide →</a>

98 </>

99 };

100 const iconCheck = (size = 14) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

101 <polyline points="20 6 9 17 4 12" />

102 </svg>;

103 const iconCopy = (size = 14) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

104 <rect x="9" y="9" width="13" height="13" rx="2" />

105 <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />

106 </svg>;

107 const iconArrowRight = (size = 13) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

108 <line x1="5" y1="12" x2="19" y2="12" />

109 <polyline points="12 5 19 12 12 19" />

110 </svg>;

111 const iconArrowUpRight = (size = 14) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

112 <line x1="7" y1="17" x2="17" y2="7" />

113 <polyline points="7 7 17 7 17 17" />

114 </svg>;

115 const iconInfo = (size = 16) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

116 <circle cx="12" cy="12" r="10" />

117 <line x1="12" y1="16" x2="12" y2="12" />

118 <line x1="12" y1="8" x2="12.01" y2="8" />

119 </svg>;

120 const [target, setTarget] = useState(defaultSurface);

121 const [team, setTeam] = useState(false);

122 const [provider, setProvider] = useState('anthropic');

123 const [pkg, setPkg] = useState(() => (/Win/).test(navigator.userAgent) ? 'win' : 'mac');

124 const [winCmd, setWinCmd] = useState(false);

125 const [copied, setCopied] = useState(null);

126 const copyTimer = useRef(null);

127 const handleCopy = async (text, key) => {

128 try {

129 await navigator.clipboard.writeText(text);

130 } catch {

131 const ta = document.createElement('textarea');

132 ta.value = text;

133 document.body.appendChild(ta);

134 ta.select();

135 document.execCommand('copy');

136 document.body.removeChild(ta);

137 }

138 clearTimeout(copyTimer.current);

139 setCopied(key);

140 copyTimer.current = setTimeout(() => setCopied(null), 1800);

141 };

142 const cardBodyCmd = (cmd, prompt) => {

143 const on = copied === 'term';

144 return <div className="cc-ic-card-body">

145 <span className="cc-ic-prompt">{prompt || '$'}</span>

146 <div className="cc-ic-cmd">{cmd}</div>

147 <button type="button" className={'cc-ic-copy' + (on ? ' cc-ic-copied' : '')} onClick={() => handleCopy(cmd, 'term')}>

148 {on ? iconCheck(13) : iconCopy(13)}

149 <span>{on ? 'Copied' : 'Copy'}</span>

150 </button>

151 </div>;

152 };

153 const isWinInstaller = pkg === 'win';

154 const isWinPrompt = pkg === 'win' || pkg === 'winget';

155 const terminalCmd = isWinInstaller ? WIN_VARIANTS[winCmd ? 'cmd' : 'ps'] : TERM[pkg].cmd;

156 const alt = ALT_TARGETS[target];

157 const showNotice = team && provider !== 'anthropic';

158 const STYLES = `

159.cc-ic {

160 --ic-slate: #141413;

161 --ic-clay: #d97757;

162 --ic-clay-deep: #c6613f;

163 --ic-gray-000: #ffffff;

164 --ic-gray-150: #f0eee6;

165 --ic-gray-550: #73726c;

166 --ic-gray-700: #3d3d3a;

167 --ic-border-subtle: rgba(31, 30, 29, 0.08);

168 --ic-border-default: rgba(31, 30, 29, 0.15);

169 --ic-border-strong: rgba(31, 30, 29, 0.3);

170 --ic-font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, 'Courier New', monospace;

171 font-family: 'Anthropic Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;

172 font-size: 14px; line-height: 1.5; color: var(--ic-slate);

173 margin: 8px 0 32px;

174}

175.dark .cc-ic {

176 --ic-slate: #f0eee6;

177 --ic-gray-000: #262624;

178 --ic-gray-150: #1f1e1d;

179 --ic-gray-550: #91908a;

180 --ic-gray-700: #bfbdb4;

181 --ic-border-subtle: rgba(240, 238, 230, 0.08);

182 --ic-border-default: rgba(240, 238, 230, 0.14);

183 --ic-border-strong: rgba(240, 238, 230, 0.28);

184}

185.dark .cc-ic-check { background: transparent; }

186.dark .cc-ic-card { border: 0.5px solid var(--ic-border-subtle); }

187.dark .cc-ic-p-pill.cc-ic-active { box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); }

188.cc-ic *, .cc-ic *::before, .cc-ic *::after { box-sizing: border-box; }

189.cc-ic a { text-decoration: none; }

190.cc-ic a:not([class]) { color: inherit; }

191.cc-ic button { font-family: inherit; cursor: pointer; }

192 

193.cc-ic-tab-strip {

194 display: inline-flex; gap: 2px;

195 padding: 4px; background: var(--ic-gray-150);

196 border-radius: 10px; overflow-x: auto;

197 max-width: 100%;

198}

199.cc-ic-tab {

200 appearance: none; background: none; border: none;

201 padding: 10px 18px; font-size: 15px; font-weight: 430;

202 color: var(--ic-gray-550); border-radius: 7px;

203 white-space: nowrap;

204 transition: color 0.12s, background-color 0.12s;

205}

206.cc-ic-tab:hover { color: var(--ic-gray-700); }

207.cc-ic-tab.cc-ic-active {

208 color: var(--ic-slate); font-weight: 500;

209 background: var(--ic-gray-000);

210 box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);

211}

212.dark .cc-ic-tab.cc-ic-active { box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4); }

213 

214.cc-ic-team-wrap { padding: 16px 0 20px; }

215.cc-ic-team-toggle {

216 display: flex; align-items: center; gap: 12px; font-family: inherit;

217 padding: 12px 16px; font-size: 14px; font-weight: 430;

218 color: var(--ic-gray-700); cursor: pointer; user-select: none;

219 width: fit-content; background: var(--ic-gray-150);

220 border: 0.5px solid var(--ic-border-subtle); border-radius: 8px;

221 transition: border-color 0.15s;

222}

223.cc-ic-team-toggle:hover { border-color: var(--ic-border-default); }

224.cc-ic-team-toggle.cc-ic-checked {

225 background: rgba(217, 119, 87, 0.08);

226 border-color: rgba(217, 119, 87, 0.25);

227}

228.cc-ic-check {

229 width: 16px; height: 16px;

230 border: 1px solid var(--ic-border-strong); border-radius: 4px;

231 background: var(--ic-gray-000);

232 display: flex; align-items: center; justify-content: center;

233 flex-shrink: 0;

234}

235.cc-ic-check svg { color: #fff; display: none; }

236.cc-ic-team-toggle.cc-ic-checked .cc-ic-check { background: var(--ic-clay-deep); border-color: var(--ic-clay-deep); }

237.cc-ic-team-toggle.cc-ic-checked .cc-ic-check svg { display: block; }

238 

239.cc-ic-team-reveal { display: flex; flex-direction: column; gap: 12px; margin-bottom: 16px; }

240.cc-ic-sales {

241 display: flex; align-items: center; justify-content: space-between;

242 gap: 16px; padding: 14px 16px;

243 background: var(--ic-gray-000); border: 0.5px solid var(--ic-border-default);

244 border-radius: 8px; flex-wrap: wrap;

245}

246.cc-ic-sales-text { font-size: 13px; color: var(--ic-gray-700); line-height: 1.5; flex: 1; min-width: 200px; }

247.cc-ic-sales-text strong { font-weight: 550; color: var(--ic-slate); }

248.cc-ic-sales-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }

249.cc-ic-btn-clay {

250 display: inline-flex; align-items: center; gap: 8px;

251 background: var(--ic-clay-deep); color: #fff; border: none;

252 border-radius: 8px; padding: 8px 14px;

253 font-size: 13px; font-weight: 500;

254 transition: background-color 0.15s; white-space: nowrap;

255}

256.cc-ic-btn-clay:hover { background: var(--ic-clay); }

257.cc-ic-btn-ghost {

258 display: inline-flex; align-items: center; gap: 8px;

259 background: transparent; color: var(--ic-gray-700);

260 border: 0.5px solid var(--ic-border-default);

261 border-radius: 8px; padding: 8px 14px;

262 font-size: 13px; font-weight: 500;

263}

264.cc-ic-btn-ghost:hover { background: rgba(0, 0, 0, 0.04); }

265 

266.cc-ic-provider-bar {

267 display: flex; align-items: center; gap: 12px;

268 padding: 14px 16px; background: var(--ic-gray-150);

269 border-radius: 8px; font-size: 13px; flex-wrap: wrap;

270}

271.cc-ic-provider-bar .cc-ic-label { color: var(--ic-gray-550); flex-shrink: 0; }

272.cc-ic-provider-pills { display: flex; gap: 4px; flex-wrap: wrap; }

273.cc-ic-p-pill {

274 appearance: none; border: none; background: transparent;

275 padding: 6px 12px; border-radius: 6px;

276 font-size: 13px; font-weight: 430; color: var(--ic-gray-700);

277 white-space: nowrap;

278}

279.cc-ic-p-pill:hover { background: rgba(0, 0, 0, 0.04); }

280.cc-ic-p-pill.cc-ic-active {

281 background: var(--ic-gray-000); color: var(--ic-slate);

282 font-weight: 500; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

283}

284.cc-ic-provider-notice {

285 display: flex; padding: 16px 18px;

286 background: var(--ic-gray-000); border: 0.5px solid var(--ic-border-default);

287 border-radius: 8px; gap: 14px; align-items: flex-start;

288}

289.cc-ic-provider-notice > svg { color: var(--ic-gray-550); margin-top: 2px; flex-shrink: 0; }

290.cc-ic-provider-notice-body { font-size: 14px; line-height: 1.55; color: var(--ic-gray-700); }

291.cc-ic-provider-notice-body strong { font-weight: 550; color: var(--ic-slate); }

292.cc-ic-provider-notice-body a { color: var(--ic-clay-deep); font-weight: 500; }

293.cc-ic-provider-notice-body a:hover { text-decoration: underline; }

294 

295.cc-ic-card { background: #141413; border-radius: 12px; overflow: hidden; }

296.cc-ic-subtabs {

297 display: flex; align-items: center;

298 background: #1a1918;

299 border-bottom: 0.5px solid rgba(255, 255, 255, 0.08);

300 padding: 0 8px; overflow-x: auto;

301}

302.cc-ic-subtab {

303 appearance: none; background: none; border: none;

304 padding: 12px 16px; font-size: 12px;

305 color: rgba(255, 255, 255, 0.5);

306 position: relative; white-space: nowrap;

307}

308.cc-ic-subtab:hover { color: rgba(255, 255, 255, 0.75); }

309.cc-ic-subtab.cc-ic-active { color: #fff; }

310.cc-ic-subtab.cc-ic-active::after {

311 content: ''; position: absolute;

312 left: 12px; right: 12px; bottom: -0.5px;

313 height: 2px; background: var(--ic-clay);

314}

315.cc-ic-shell-switch {

316 display: inline-flex; gap: 2px;

317 margin: 14px 26px 0; padding: 3px;

318 background: rgba(255, 255, 255, 0.06);

319 border: 0.5px solid rgba(255, 255, 255, 0.08);

320 border-radius: 8px;

321 font-family: inherit;

322}

323.cc-ic-shell-option {

324 font: inherit; font-size: 12px; font-weight: 500;

325 padding: 5px 12px; border-radius: 6px;

326 background: transparent; border: none;

327 color: rgba(255, 255, 255, 0.55);

328 cursor: pointer; user-select: none; white-space: nowrap;

329 transition: color 120ms ease, background-color 120ms ease;

330}

331.cc-ic-shell-option:hover { color: rgba(255, 255, 255, 0.85); }

332.cc-ic-shell-option.cc-ic-active {

333 background: rgba(255, 255, 255, 0.12);

334 color: #fff;

335 box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);

336}

337 

338.cc-ic-card-body { padding: 24px 26px; display: flex; align-items: flex-start; gap: 14px; }

339.cc-ic-prompt {

340 color: var(--ic-clay); font-family: var(--ic-font-mono);

341 font-size: 17px; user-select: none; padding-top: 2px;

342}

343.cc-ic-cmd {

344 flex: 1; font-family: var(--ic-font-mono);

345 font-size: 17px; color: #f0eee6;

346 line-height: 1.55; white-space: pre-wrap; word-break: break-word;

347}

348.cc-ic-copy {

349 display: inline-flex; align-items: center; gap: 6px;

350 background: rgba(255, 255, 255, 0.08);

351 border: 0.5px solid rgba(255, 255, 255, 0.12);

352 color: rgba(255, 255, 255, 0.85);

353 padding: 7px 13px; border-radius: 8px;

354 font-size: 13px; font-weight: 500; flex-shrink: 0;

355}

356.cc-ic-copy:hover { background: rgba(255, 255, 255, 0.14); }

357.cc-ic-copy.cc-ic-copied { background: var(--ic-clay-deep); border-color: var(--ic-clay-deep); color: #fff; }

358 

359.cc-ic-below {

360 margin-top: 12px; font-size: 13px; color: var(--ic-gray-550);

361 display: flex; gap: 16px; flex-wrap: wrap; align-items: baseline;

362}

363.cc-ic-below a { color: var(--ic-gray-700); border-bottom: 0.5px solid var(--ic-border-default); }

364.cc-ic-below a:hover { color: var(--ic-clay-deep); border-bottom-color: var(--ic-clay-deep); }

365.cc-ic-handoff {

366 padding: 22px 24px;

367 background: linear-gradient(180deg, #faf9f4 0%, #f3f1e9 100%);

368 border: 0.5px solid var(--ic-border-default);

369 border-radius: 12px;

370 box-shadow: 0 1px 2px rgba(31, 30, 29, 0.04), 0 6px 16px -4px rgba(31, 30, 29, 0.06);

371}

372.dark .cc-ic-handoff {

373 background: linear-gradient(180deg, #262624 0%, #1f1e1d 100%);

374 box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3), 0 6px 16px -4px rgba(0, 0, 0, 0.4);

375}

376.cc-ic-handoff-title {

377 font-size: 16px; font-weight: 550; color: var(--ic-slate);

378 letter-spacing: -0.01em; margin-bottom: 4px;

379}

380.cc-ic-handoff-sub {

381 font-size: 14px; line-height: 1.5; color: var(--ic-gray-700);

382 margin-bottom: 18px;

383}

384.cc-ic-handoff-actions { display: flex; gap: 10px; flex-wrap: wrap; }

385.cc-ic-handoff-alt {

386 margin-top: 12px; font-size: 12px; color: var(--ic-gray-550);

387}

388.cc-ic-handoff-alt code {

389 font-family: var(--ic-font-mono); font-size: 11px;

390 background: var(--ic-gray-150); padding: 2px 6px;

391 border-radius: 4px; color: var(--ic-gray-700);

392}

393.cc-ic-copy-sm {

394 appearance: none; border: none;

395 display: inline-flex; align-items: center; justify-content: center;

396 width: 22px; height: 22px;

397 margin-left: 4px; vertical-align: middle;

398 background: var(--ic-gray-150); color: var(--ic-gray-550);

399 border-radius: 4px;

400 transition: color 0.1s, background-color 0.1s;

401}

402.cc-ic-copy-sm:hover { color: var(--ic-gray-700); background: var(--ic-border-default); }

403.cc-ic-copy-sm.cc-ic-copied { background: var(--ic-clay-deep); color: #fff; }

404 

405@media (max-width: 720px) {

406 .cc-ic-tab { padding: 12px 14px; font-size: 14px; }

407 .cc-ic-sales-actions { width: 100%; }

408 .cc-ic-card-body { padding: 20px; }

409 .cc-ic-cmd { font-size: 15px; }

410}

411`;

412 return <div className="cc-ic not-prose">

413 <style>{STYLES}</style>

414 

415 {}

416 <div className="cc-ic-tab-strip" role="tablist">

417 {TABS.map(t => <button key={t.key} type="button" role="tab" aria-selected={target === t.key} className={'cc-ic-tab' + (target === t.key ? ' cc-ic-active' : '')} onClick={() => setTarget(t.key)}>

418 {t.label}

419 </button>)}

420 </div>

421 

422 {}

423 <div className="cc-ic-team-wrap">

424 <button type="button" role="switch" aria-checked={team} className={'cc-ic-team-toggle' + (team ? ' cc-ic-checked' : '')} onClick={() => setTeam(!team)}>

425 <span className="cc-ic-check">{iconCheck(11)}</span>

426 <span>

427 I’m buying for a team or company (SSO, AWS/Azure/GCP, central billing)

428 </span>

429 </button>

430 </div>

431 

432 {}

433 {team && <div className="cc-ic-team-reveal">

434 <div className="cc-ic-sales">

435 <div className="cc-ic-sales-text">

436 <strong>Set up your team:</strong> self-serve or talk to sales.

437 </div>

438 <div className="cc-ic-sales-actions">

439 <a href="https://claude.ai/upgrade?initialPlanType=team&amp;utm_source=claude_code&amp;utm_medium=docs&amp;utm_content=configurator_team_get_started" className="cc-ic-btn-ghost">

440 Get started

441 </a>

442 <a href="https://www.anthropic.com/contact-sales?utm_source=claude_code&amp;utm_medium=docs&amp;utm_content=configurator_team_contact_sales" className="cc-ic-btn-clay">

443 Contact sales {iconArrowRight()}

444 </a>

445 </div>

446 </div>

447 

448 <div className="cc-ic-provider-bar">

449 <span className="cc-ic-label">Run on</span>

450 <div className="cc-ic-provider-pills" role="radiogroup" aria-label="Provider">

451 {PROVIDERS.map(p => <button key={p.key} type="button" role="radio" aria-checked={provider === p.key} className={'cc-ic-p-pill' + (provider === p.key ? ' cc-ic-active' : '')} onClick={() => setProvider(p.key)}>

452 {p.label}

453 </button>)}

454 </div>

455 </div>

456 

457 {showNotice && <div className="cc-ic-provider-notice">

458 {iconInfo()}

459 <div className="cc-ic-provider-notice-body">

460 {PROVIDER_NOTICE[provider]}

461 </div>

462 </div>}

463 </div>}

464 

465 {}

466 {target === 'terminal' && <div className="cc-ic-card">

467 <div className="cc-ic-subtabs" role="tablist" aria-label="Install method">

468 {Object.keys(TERM).map(k => <button key={k} type="button" role="tab" aria-selected={pkg === k} className={'cc-ic-subtab' + (pkg === k ? ' cc-ic-active' : '')} onClick={() => setPkg(k)}>

469 {TERM[k].label}

470 </button>)}

471 </div>

472 {isWinInstaller && <div className="cc-ic-shell-switch" role="tablist" aria-label="Shell">

473 {[{

474 k: 'ps',

475 label: 'PowerShell'

476 }, {

477 k: 'cmd',

478 label: 'CMD'

479 }].map(({k, label}) => {

480 const active = k === 'cmd' === winCmd;

481 return <button key={k} type="button" role="tab" aria-selected={active} className={'cc-ic-shell-option' + (active ? ' cc-ic-active' : '')} onClick={() => setWinCmd(k === 'cmd')}>

482 {label}

483 </button>;

484 })}

485 </div>}

486 {cardBodyCmd(terminalCmd, isWinPrompt ? '>' : '$')}

487 </div>}

488 

489 {}

490 {target === 'terminal' && <div className="cc-ic-below">

491 {isWinInstaller && <span>

492 <a href="https://git-scm.com/downloads/win" target="_blank" rel="noopener">

493 Git for Windows

494 </a>{' '}

495 recommended. PowerShell is used if Git Bash is absent.

496 </span>}

497 {(pkg === 'brew' || pkg === 'winget') && <span>

498 Does not auto-update. Run{' '}

499 <code>{pkg === 'brew' ? 'brew upgrade claude-code' : 'winget upgrade Anthropic.ClaudeCode'}</code>{' '}

500 periodically.

501 </span>}

502 <a href="/en/troubleshoot-install">Installation troubleshooting</a>

503 </div>}

504 

505 {alt && <div className="cc-ic-handoff">

506 <div className="cc-ic-handoff-title">Claude Code for {alt.name}</div>

507 <div className="cc-ic-handoff-sub">{alt.tagline}</div>

508 <div className="cc-ic-handoff-actions">

509 <a href={alt.installHref} className="cc-ic-btn-clay" {...alt.installHref.startsWith('http') ? {

510 target: '_blank',

511 rel: 'noopener'

512 } : {}}>

513 {alt.installLabel} {iconArrowUpRight(13)}

514 </a>

515 <a href={alt.guideHref} className="cc-ic-btn-ghost">

516 {alt.name} guide {iconArrowRight(12)}

517 </a>

518 </div>

519 {alt.altCmd && <div className="cc-ic-handoff-alt">

520 or run <code>{alt.altCmd}</code>

521 <button type="button" className={'cc-ic-copy-sm' + (copied === 'alt' ? ' cc-ic-copied' : '')} onClick={() => handleCopy(alt.altCmd, 'alt')} aria-label="Copy command">

522 {copied === 'alt' ? iconCheck(11) : iconCopy(11)}

523 </button>

524 </div>}

525 </div>}

526 </div>;

527};

528 

529export const Experiment = ({flag, treatment, children}) => {

530 const VID_KEY = 'exp_vid';

531 const CONSENT_COUNTRIES = new Set(['AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'RE', 'GP', 'MQ', 'GF', 'YT', 'BL', 'MF', 'PM', 'WF', 'PF', 'NC', 'AW', 'CW', 'SX', 'FO', 'GL', 'AX', 'GB', 'UK', 'AI', 'BM', 'IO', 'VG', 'KY', 'FK', 'GI', 'MS', 'PN', 'SH', 'TC', 'GG', 'JE', 'IM', 'CA', 'BR', 'IN']);

532 const fnv1a = s => {

533 let h = 0x811c9dc5;

534 for (let i = 0; i < s.length; i++) {

535 h ^= s.charCodeAt(i);

536 h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);

537 }

538 return h >>> 0;

539 };

540 const bucket = (seed, vid) => fnv1a(fnv1a(seed + vid) + '') % 10000 < 5000 ? 'control' : 'treatment';

541 const [decision] = useState(() => {

542 const params = new URLSearchParams(location.search);

543 const preBucketed = document.documentElement.dataset['gb_' + flag.replace(/-/g, '_')];

544 const force = params.get('gb-force');

545 if (force) {

546 for (const p of force.split(',')) {

547 const [k, v] = p.split(':');

548 if (k === flag) return {

549 variant: v || 'treatment',

550 track: false

551 };

552 }

553 }

554 if (navigator.globalPrivacyControl) {

555 return {

556 variant: 'control',

557 track: false

558 };

559 }

560 const prefsMatch = document.cookie.match(/(?:^|; )anthropic-consent-preferences=([^;]+)/);

561 if (prefsMatch) {

562 try {

563 if (JSON.parse(decodeURIComponent(prefsMatch[1])).analytics !== true) {

564 return {

565 variant: 'control',

566 track: false

567 };

568 }

569 } catch {

570 return {

571 variant: 'control',

572 track: false

573 };

574 }

575 } else {

576 const country = params.get('country')?.toUpperCase() || (document.cookie.match(/(?:^|; )cf_geo=([A-Z]{2})/) || [])[1];

577 if (!country || CONSENT_COUNTRIES.has(country)) {

578 return {

579 variant: 'control',

580 track: false

581 };

582 }

583 }

584 let vid;

585 try {

586 const ajsMatch = document.cookie.match(/(?:^|; )ajs_anonymous_id=([^;]+)/);

587 if (ajsMatch) {

588 vid = decodeURIComponent(ajsMatch[1]).replace(/^"|"$/g, '');

589 } else {

590 vid = localStorage.getItem(VID_KEY);

591 if (!vid) {

592 vid = crypto.randomUUID();

593 }

594 document.cookie = `ajs_anonymous_id=${vid}; domain=.claude.com; path=/; Secure; SameSite=Lax; max-age=31536000`;

595 }

596 try {

597 localStorage.setItem(VID_KEY, vid);

598 } catch {}

599 } catch {

600 return {

601 variant: 'control',

602 track: false

603 };

604 }

605 const variant = preBucketed === '1' ? 'treatment' : preBucketed === '0' ? 'control' : bucket(flag, vid);

606 return {

607 variant,

608 track: true,

609 vid

610 };

611 });

612 useEffect(() => {

613 if (!decision.track) return;

614 fetch('https://api.anthropic.com/api/event_logging/v2/batch', {

615 method: 'POST',

616 headers: {

617 'Content-Type': 'application/json',

618 'x-service-name': 'claude_code_docs'

619 },

620 body: JSON.stringify({

621 events: [{

622 event_type: 'GrowthbookExperimentEvent',

623 event_data: {

624 device_id: decision.vid,

625 anonymous_id: decision.vid,

626 timestamp: new Date().toISOString(),

627 experiment_id: flag,

628 variation_id: decision.variant === 'treatment' ? 1 : 0,

629 environment: 'production'

630 }

631 }]

632 }),

633 keepalive: true

634 }).catch(() => {});

635 }, []);

636 return decision.variant === 'treatment' ? treatment : children;

637};

638 

639本快速入門指南將在幾分鐘內讓您使用 AI 驅動的編碼協助。完成後,您將了解如何使用 Claude Code 進行常見的開發任務。

640 

641<Experiment flag="quickstart-install-configurator" treatment={<InstallConfigurator />} />

642 

643## 開始前

644 

645確保您擁有:

646 

647* 已開啟的終端或命令提示字元

648 * 如果您從未使用過終端,請查看[終端指南](/zh-TW/terminal-guide)

649* 一個可以使用的程式碼專案

650* 一個 [Claude 訂閱](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=quickstart_prereq)(Pro、Max、Teams 或 Enterprise)、[Claude Console](https://console.anthropic.com/) 帳戶,或透過[支援的雲端提供商](/zh-TW/third-party-integrations)存取

651 

652<Note>

653 本指南涵蓋終端 CLI。Claude Code 也可在[網頁](https://claude.ai/code)、[桌面應用程式](/zh-TW/desktop)、[VS Code](/zh-TW/vs-code) 和 [JetBrains IDE](/zh-TW/jetbrains)、[Slack](/zh-TW/slack) 中使用,以及透過 [GitHub Actions](/zh-TW/github-actions) 和 [GitLab](/zh-TW/gitlab-ci-cd) 進行 CI/CD。請參閱[所有介面](/zh-TW/overview#use-claude-code-everywhere)。

654</Note>

655 

656## 步驟 1:安裝 Claude Code

657 

658To install Claude Code, use one of the following methods:

659 

660<Tabs>

661 <Tab title="Native Install (Recommended)">

662 **macOS, Linux, WSL:**

663 

664 ```bash theme={null}

665 curl -fsSL https://claude.ai/install.sh | bash

666 ```

667 

668 **Windows PowerShell:**

669 

670 ```powershell theme={null}

671 irm https://claude.ai/install.ps1 | iex

672 ```

673 

674 **Windows CMD:**

675 

676 ```batch theme={null}

677 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

678 ```

679 

680 If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you're in CMD, not PowerShell. Your prompt shows `PS C:\` when you're in PowerShell and `C:\` without the `PS` when you're in CMD.

681 

682 [Git for Windows](https://git-scm.com/downloads/win) is recommended on native Windows so Claude Code can use the Bash tool. If Git for Windows is not installed, Claude Code uses PowerShell as the shell tool instead. WSL setups do not need Git for Windows.

683 

684 <Info>

685 Native installations automatically update in the background to keep you on the latest version.

686 </Info>

687 </Tab>

688 

689 <Tab title="Homebrew">

690 ```bash theme={null}

691 brew install --cask claude-code

692 ```

693 

694 Homebrew offers two casks. `claude-code` tracks the stable release channel, which is typically about a week behind and skips releases with major regressions. `claude-code@latest` tracks the latest channel and receives new versions as soon as they ship.

695 

696 <Info>

697 Homebrew installations do not auto-update. Run `brew upgrade claude-code` or `brew upgrade claude-code@latest`, depending on which cask you installed, to get the latest features and security fixes.

698 </Info>

699 </Tab>

700 

701 <Tab title="WinGet">

702 ```powershell theme={null}

703 winget install Anthropic.ClaudeCode

704 ```

705 

706 <Info>

707 WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.

708 </Info>

709 </Tab>

710</Tabs>

711 

712You can also install with [apt, dnf, or apk](/en/setup#install-with-linux-package-managers) on Debian, Fedora, RHEL, and Alpine.

713 

714## 步驟 2:登入您的帳戶

715 

716Claude Code 需要帳戶才能使用。當您使用 `claude` 命令啟動互動式工作階段時,您需要登入:

717 

718```bash theme={null}

719claude

720# 首次使用時系統會提示您登入

721```

722 

723```bash theme={null}

724/login

725# 按照提示使用您的帳戶登入

726```

727 

728您可以使用以下任何帳戶類型登入:

729 

730* [Claude Pro、Max、Teams 或 Enterprise](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=quickstart_login)(推薦)

731* [Claude Console](https://console.anthropic.com/)(具有預付額度的 API 存取)。首次登入時,Console 中會自動建立「Claude Code」工作區以進行集中成本追蹤。

732* [Amazon Bedrock、Google Vertex AI 或 Microsoft Foundry](/zh-TW/third-party-integrations)(企業雲端提供商)

733 

734登入後,您的認證將被儲存,您無需再次登入。若要稍後切換帳戶,請使用 `/login` 命令。

735 

736## 步驟 3:啟動您的第一個工作階段

737 

738在任何專案目錄中開啟您的終端並啟動 Claude Code:

739 

740```bash theme={null}

741cd /path/to/your/project

742claude

743```

744 

745您將看到 Claude Code 歡迎畫面,其中包含您的工作階段資訊、最近的對話和最新更新。輸入 `/help` 以查看可用命令,或輸入 `/resume` 以繼續之前的對話。

746 

747<Tip>

748 登入後(步驟 2),您的認證將儲存在您的系統上。在[認證管理](/zh-TW/authentication#credential-management)中了解更多。

749</Tip>

750 

751## 步驟 4:提出您的第一個問題

752 

753讓我們從了解您的程式碼庫開始。嘗試以下命令之一:

754 

755```text theme={null}

756what does this project do?

757```

758 

759Claude 將分析您的檔案並提供摘要。您也可以提出更具體的問題:

760 

761```text theme={null}

762what technologies does this project use?

763```

764 

765```text theme={null}

766where is the main entry point?

767```

768 

769```text theme={null}

770explain the folder structure

771```

772 

773您也可以詢問 Claude 其自身的功能:

774 

775```text theme={null}

776what can Claude Code do?

777```

778 

779```text theme={null}

780how do I create custom skills in Claude Code?

781```

782 

783```text theme={null}

784can Claude Code work with Docker?

785```

786 

787<Note>

788 Claude Code 會根據需要讀取您的專案檔案。您無需手動新增內容。

789</Note>

790 

791## 步驟 5:進行您的第一次程式碼變更

792 

793現在讓我們讓 Claude Code 進行一些實際的編碼。嘗試一個簡單的任務:

794 

795```text theme={null}

796add a hello world function to the main file

797```

798 

799Claude Code 將:

800 

8011. 找到適當的檔案

8022. 向您顯示建議的變更

8033. 要求您的批准

8044. 進行編輯

805 

806<Note>

807 Claude Code 在修改檔案前始終要求許可。您可以批准個別變更或為工作階段啟用「全部接受」模式。

808</Note>

809 

810## 步驟 6:使用 Git 與 Claude Code

811 

812Claude Code 使 Git 操作變得對話式:

813 

814```text theme={null}

815what files have I changed?

816```

817 

818```text theme={null}

819commit my changes with a descriptive message

820```

821 

822您也可以提示進行更複雜的 Git 操作:

823 

824```text theme={null}

825create a new branch called feature/quickstart

826```

827 

828```text theme={null}

829show me the last 5 commits

830```

831 

832```text theme={null}

833help me resolve merge conflicts

834```

835 

836## 步驟 7:修復錯誤或新增功能

837 

838Claude 擅長除錯和功能實現。

839 

840用自然語言描述您想要的內容:

841 

842```text theme={null}

843add input validation to the user registration form

844```

845 

846或修復現有問題:

847 

848```text theme={null}

849there's a bug where users can submit empty forms - fix it

850```

851 

852Claude Code 將:

853 

854* 定位相關程式碼

855* 理解上下文

856* 實現解決方案

857* 如果可用,執行測試

858 

859## 步驟 8:測試其他常見工作流程

860 

861有許多方式可以與 Claude 合作:

862 

863**重構程式碼**

864 

865```text theme={null}

866refactor the authentication module to use async/await instead of callbacks

867```

868 

869**編寫測試**

870 

871```text theme={null}

872write unit tests for the calculator functions

873```

874 

875**更新文件**

876 

877```text theme={null}

878update the README with installation instructions

879```

880 

881**程式碼審查**

882 

883```text theme={null}

884review my changes and suggest improvements

885```

886 

887<Tip>

888 像與有幫助的同事交談一樣與 Claude 交談。描述您想要達成的目標,它將幫助您實現。

889</Tip>

890 

891## 基本命令

892 

893以下是日常使用中最重要的命令:

894 

895| 命令 | 功能 | 範例 |

896| ------------------- | -------------- | ----------------------------------- |

897| `claude` | 啟動互動模式 | `claude` |

898| `claude "task"` | 執行一次性任務 | `claude "fix the build error"` |

899| `claude -p "query"` | 執行一次性查詢,然後退出 | `claude -p "explain this function"` |

900| `claude -c` | 在目前目錄中繼續最近的對話 | `claude -c` |

901| `claude -r` | 恢復之前的對話 | `claude -r` |

902| `claude commit` | 建立 Git 提交 | `claude commit` |

903| `/clear` | 清除對話歷史 | `/clear` |

904| `/help` | 顯示可用命令 | `/help` |

905| `exit` 或 Ctrl+C | 退出 Claude Code | `exit` |

906 

907請參閱 [CLI 參考](/zh-TW/cli-reference)以取得完整的命令清單。

908 

909## 初學者的專業提示

910 

911如需更多資訊,請參閱[最佳實踐](/zh-TW/best-practices)和[常見工作流程](/zh-TW/common-workflows)。

912 

913<AccordionGroup>

914 <Accordion title="對您的請求要具體">

915 不要這樣做:'修復錯誤'

916 

917 試試這樣:'修復登入錯誤,使用者輸入錯誤認證後看到空白畫面'

918 </Accordion>

919 

920 <Accordion title="使用逐步說明">

921 將複雜任務分解為步驟:

922 

923 ```text theme={null}

924 1. create a new database table for user profiles

925 2. create an API endpoint to get and update user profiles

926 3. build a webpage that allows users to see and edit their information

927 ```

928 </Accordion>

929 

930 <Accordion title="讓 Claude 先探索">

931 在進行變更之前,讓 Claude 了解您的程式碼:

932 

933 ```text theme={null}

934 analyze the database schema

935 ```

936 

937 ```text theme={null}

938 build a dashboard showing products that are most frequently returned by our UK customers

939 ```

940 </Accordion>

941 

942 <Accordion title="使用快捷方式節省時間">

943 * 按 `?` 查看所有可用的快捷鍵

944 * 使用 Tab 進行命令完成

945 * 按 ↑ 查看命令歷史

946 * 輸入 `/` 查看所有命令和 skills

947 </Accordion>

948</AccordionGroup>

949 

950## 接下來呢?

951 

952現在您已經學習了基礎知識,請探索更多進階功能:

953 

954<CardGroup cols={2}>

955 <Card title="Claude Code 如何運作" icon="microchip" href="/zh-TW/how-claude-code-works">

956 了解代理迴圈、內建工具以及 Claude Code 如何與您的專案互動

957 </Card>

958 

959 <Card title="最佳實踐" icon="star" href="/zh-TW/best-practices">

960 透過有效的提示和專案設定獲得更好的結果

961 </Card>

962 

963 <Card title="常見工作流程" icon="graduation-cap" href="/zh-TW/common-workflows">

964 常見任務的逐步指南

965 </Card>

966 

967 <Card title="擴展 Claude Code" icon="puzzle-piece" href="/zh-TW/features-overview">

968 使用 CLAUDE.md、skills、hooks、MCP 等進行自訂

969 </Card>

970</CardGroup>

971 

972## 獲取幫助

973 

974* **在 Claude Code 中**:輸入 `/help` 或詢問「how do I...」

975* **文件**:您在這裡!瀏覽其他指南

976* **社群**:加入我們的 [Discord](https://www.anthropic.com/discord) 以獲取提示和支援

remote-control.md +259 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 使用 Remote Control 從任何裝置繼續本地會話

6 

7> 使用 Remote Control 從您的手機、平板電腦或任何瀏覽器繼續本地 Claude Code 會話。適用於 claude.ai/code 和 Claude 行動應用程式。

8 

9<Note>

10 Remote Control 處於研究預覽階段,在所有方案上都可用。在 Team 和 Enterprise 上,預設為關閉,直到管理員在 [Claude Code 管理員設定](https://claude.ai/admin-settings/claude-code)中啟用 Remote Control 切換。

11</Note>

12 

13Remote Control 將 [claude.ai/code](https://claude.ai/code) 或 Claude 應用程式([iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) 和 [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude))連接到在您機器上執行的 Claude Code 會話。在您的辦公桌開始一項任務,然後從沙發上的手機或另一台電腦上的瀏覽器繼續。

14 

15當您在機器上啟動 Remote Control 會話時,Claude 會在整個過程中在本地執行,因此沒有任何內容會移至雲端。使用 Remote Control,您可以:

16 

17* **遠端使用您的完整本地環境**:您的檔案系統、[MCP servers](/zh-TW/mcp)、工具和專案配置都保持可用,輸入 `@` 會自動完成來自您本地專案的檔案路徑

18* **同時在兩個介面上工作**:對話在所有連接的裝置上保持同步,因此您可以從終端機、瀏覽器和手機交替發送訊息

19* **克服中斷**:如果您的筆記型電腦進入睡眠狀態或網路中斷,當您的機器重新上線時,會話會自動重新連接

20 

21與[網頁版 Claude Code](/zh-TW/claude-code-on-the-web)(在雲端基礎設施上執行)不同,Remote Control 會話直接在您的機器上執行並與您的本地檔案系統互動。網頁和行動介面只是該本地會話的一個窗口。

22 

23<Note>

24 Remote Control 需要 Claude Code v2.1.51 或更新版本。使用 `claude --version` 檢查您的版本。

25</Note>

26 

27本頁涵蓋設定、如何啟動和連接到會話,以及 Remote Control 與網頁版 Claude Code 的比較。

28 

29## 需求

30 

31在使用 Remote Control 之前,請確認您的環境符合以下條件:

32 

33* **訂閱**:在 Pro、Max、Team 和 Enterprise 方案上可用。不支援 API 金鑰。在 Team 和 Enterprise 上,管理員必須先在 [Claude Code 管理員設定](https://claude.ai/admin-settings/claude-code)中啟用 Remote Control 切換。

34* **驗證**:執行 `claude` 並使用 `/login` 透過 claude.ai 登入(如果您還沒有登入)。

35* **工作區信任**:在您的專案目錄中至少執行一次 `claude` 以接受工作區信任對話框。

36 

37## 啟動 Remote Control 會話

38 

39您可以從 CLI 或 VS Code 擴充功能啟動 Remote Control 會話。CLI 提供三種調用模式;VS Code 使用 `/remote-control` 命令。

40 

41<Tabs>

42 <Tab title="伺服器模式">

43 導航到您的專案目錄並執行:

44 

45 ```bash theme={null}

46 claude remote-control

47 ```

48 

49 該程序在您的終端機中以伺服器模式保持執行,等待遠端連接。它顯示一個會話 URL,您可以使用該 URL 從[另一個裝置連接](#connect-from-another-device),您可以按空格鍵顯示 QR 碼以從手機快速存取。當遠端會話處於活動狀態時,終端機會顯示連接狀態和工具活動。

50 

51 可用的旗標:

52 

53 | 旗標 | 說明 |

54 | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

55 | `--name "My Project"` | 設定自訂會話標題,在 claude.ai/code 的會話清單中可見。 |

56 | `--remote-control-session-name-prefix <prefix>` | 未設定明確名稱時自動生成會話名稱的前綴。預設為您機器的主機名稱,產生類似 `myhost-graceful-unicorn` 的名稱。設定 `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` 以獲得相同效果。 |

57 | `--spawn <mode>` | 伺服器如何建立會話。<br />• `same-dir`(預設):所有會話共享目前的工作目錄,因此如果編輯相同的檔案可能會衝突。<br />• `worktree`:每個按需會話都會獲得自己的 [git worktree](/zh-TW/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees)。需要 git 儲存庫。<br />• `session`:單一會話模式。恰好提供一個會話並拒絕其他連接。僅在啟動時設定。<br />在執行時按 `w` 在 `same-dir` 和 `worktree` 之間切換。 |

58 | `--capacity <N>` | 並行會話的最大數量。預設值為 32。不能與 `--spawn=session` 一起使用。 |

59 | `--verbose` | 顯示詳細的連接和會話日誌。 |

60 | `--sandbox` / `--no-sandbox` | 啟用或停用[沙箱](/zh-TW/sandboxing)以進行檔案系統和網路隔離。預設為關閉。 |

61 </Tab>

62 

63 <Tab title="互動式會話">

64 要啟動啟用了 Remote Control 的一般互動式 Claude Code 會話,請使用 `--remote-control` 旗標(或 `--rc`):

65 

66 ```bash theme={null}

67 claude --remote-control

68 ```

69 

70 可選地為會話傳遞一個名稱:

71 

72 ```bash theme={null}

73 claude --remote-control "My Project"

74 ```

75 

76 這為您提供了一個完整的互動式會話在您的終端機中,您也可以從 claude.ai 或 Claude 應用程式控制。與 `claude remote-control`(伺服器模式)不同,您可以在會話也可遠端使用時在本地輸入訊息。

77 </Tab>

78 

79 <Tab title="從現有會話">

80 如果您已經在 Claude Code 會話中並想遠端繼續它,請使用 `/remote-control`(或 `/rc`)命令:

81 

82 ```text theme={null}

83 /remote-control

84 ```

85 

86 傳遞一個名稱作為引數以設定自訂會話標題:

87 

88 ```text theme={null}

89 /remote-control My Project

90 ```

91 

92 這啟動一個 Remote Control 會話,該會話會延續您目前的對話歷史記錄,並顯示一個會話 URL 和 QR 碼,您可以使用它從[另一個裝置連接](#connect-from-another-device)。`--verbose`、`--sandbox` 和 `--no-sandbox` 旗標不適用於此命令。

93 </Tab>

94 

95 <Tab title="VS Code">

96 在 [Claude Code VS Code 擴充功能](/zh-TW/vs-code)中,在提示框中輸入 `/remote-control` 或 `/rc`,或使用 `/` 開啟命令選單並選擇它。需要 Claude Code v2.1.79 或更新版本。

97 

98 ```text theme={null}

99 /remote-control

100 ```

101 

102 提示框上方會出現一個橫幅,顯示連接狀態。連接後,點擊橫幅中的**在瀏覽器中開啟**直接進入會話,或在 [claude.ai/code](https://claude.ai/code) 的會話清單中找到它。會話 URL 也會發佈在對話中。

103 

104 要斷開連接,點擊橫幅上的關閉圖示或再次執行 `/remote-control`。

105 

106 與 CLI 不同,VS Code 命令不接受名稱引數或顯示 QR 碼。會話標題是從您的對話歷史記錄或第一個提示衍生的。

107 </Tab>

108</Tabs>

109 

110### 從另一個裝置連接

111 

112一旦 Remote Control 會話處於活動狀態,您有幾種方式從另一個裝置連接:

113 

114* **開啟會話 URL** 在任何瀏覽器中直接進入 [claude.ai/code](https://claude.ai/code) 上的會話。

115* **掃描 QR 碼** 顯示在會話 URL 旁邊,直接在 Claude 應用程式中開啟它。使用 `claude remote-control` 時,按空格鍵切換 QR 碼顯示。

116* **開啟 [claude.ai/code](https://claude.ai/code) 或 Claude 應用程式**,並在會話清單中按名稱找到會話。Remote Control 會話在線上時顯示帶有綠色狀態點的電腦圖示。

117 

118遠端會話標題按以下順序選擇:

119 

1201. 您傳遞給 `--name`、`--remote-control` 或 `/remote-control` 的名稱

1212. 您使用 `/rename` 設定的標題

1223. 現有對話歷史記錄中最後一條有意義的訊息

1234. 類似 `myhost-graceful-unicorn` 的自動生成名稱,其中 `myhost` 是您機器的主機名稱或您使用 `--remote-control-session-name-prefix` 設定的前綴

124 

125如果您沒有設定明確名稱,標題會在您發送提示後更新以反映您的提示。

126 

127如果環境已經有一個活動會話,您將被詢問是否繼續它或啟動一個新會話。

128 

129如果您還沒有 Claude 應用程式,請在 Claude Code 內使用 `/mobile` 命令顯示 [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) 或 [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude) 的下載 QR 碼。

130 

131### 為所有會話啟用 Remote Control

132 

133預設情況下,Remote Control 只在您明確執行 `claude remote-control`、`claude --remote-control` 或 `/remote-control` 時啟動。要為每個互動式會話自動啟用它,請在 Claude Code 內執行 `/config` 並將**為所有會話啟用 Remote Control** 設定為 `true`。將其設定回 `false` 以停用。

134 

135啟用此設定後,每個互動式 Claude Code 程序會註冊一個遠端會話。如果您執行多個實例,每個實例都會獲得自己的環境和會話。要從單個程序執行多個並行會話,請改用[伺服器模式](#start-a-remote-control-session)。

136 

137## 連接和安全性

138 

139您的本地 Claude Code 會話僅發出出站 HTTPS 請求,永遠不會在您的機器上開啟入站連接埠。當您啟動 Remote Control 時,它會向 Anthropic API 註冊並輪詢工作。當您從另一個裝置連接時,伺服器會透過串流連接在網頁或行動用戶端與您的本地會話之間路由訊息。

140 

141所有流量都透過 TLS 上的 Anthropic API 傳輸,與任何 Claude Code 會話相同的傳輸安全性。連接使用多個短期認證,每個認證的範圍限定為單一目的並獨立過期。

142 

143## Remote Control 與網頁版 Claude Code 的比較

144 

145Remote Control 和[網頁版 Claude Code](/zh-TW/claude-code-on-the-web)都使用 claude.ai/code 介面。關鍵區別在於會話執行的位置:Remote Control 在您的機器上執行,因此您的本地 MCP servers、工具和專案配置保持可用。網頁版 Claude Code 在 Anthropic 管理的雲端基礎設施中執行。

146 

147當您在本地工作中途並想從另一個裝置繼續時,請使用 Remote Control。當您想在沒有任何本地設定的情況下啟動任務、處理您沒有複製的儲存庫或並行執行多個任務時,請使用網頁版 Claude Code。

148 

149## 行動推播通知

150 

151當 Remote Control 處於活動狀態時,Claude 可以向您的手機發送推播通知。

152 

153Claude 決定何時推播。它通常在長時間執行的任務完成或需要您的決定以繼續時發送一個。您也可以在提示中請求推播,例如 `notify me when the tests finish`。除了下面的開啟/關閉切換外,沒有按事件配置。

154 

155<Note>

156 行動推播通知需要 Claude Code v2.1.110 或更新版本。

157</Note>

158 

159要設定行動推播通知:

160 

161<Steps>

162 <Step title="安裝 Claude 行動應用程式">

163 下載 Claude 應用程式([iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) 或 [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude))。

164 </Step>

165 

166 <Step title="使用您的 Claude Code 帳戶登入">

167 使用您在終端機中用於 Claude Code 的相同帳戶和組織。

168 </Step>

169 

170 <Step title="允許通知">

171 接受來自作業系統的通知權限提示。

172 </Step>

173 

174 <Step title="在 Claude Code 中啟用推播">

175 在您的終端機中,執行 `/config` 並啟用**當 Claude 決定時推播**。

176 </Step>

177</Steps>

178 

179如果通知未送達:

180 

181* 如果 `/config` 顯示**未註冊行動裝置**,請在手機上開啟 Claude 應用程式,以便它可以重新整理其推播令牌。下次 Remote Control 連接時,警告會清除。

182* 在 iOS 上,焦點模式和通知摘要可能會抑制或延遲推播。檢查設定 → 通知 → Claude。

183* 在 Android 上,激進的電池優化可能會延遲傳遞。在系統設定中將 Claude 應用程式豁免於電池優化。

184 

185## 限制

186 

187* **每個互動式程序一個遠端會話**:在伺服器模式之外,每個 Claude Code 實例一次支援一個遠端會話。使用[伺服器模式](#start-a-remote-control-session)從單個程序執行多個並行會話。

188* **本地程序必須保持執行**:Remote Control 作為本地程序執行。如果您關閉終端機、退出 VS Code 或以其他方式停止 `claude` 程序,會話結束。

189* **延長的網路中斷**:如果您的機器處於喚醒狀態但無法在大約 10 分鐘以上的時間內到達網路,會話會逾時並且程序退出。再次執行 `claude remote-control` 以啟動新會話。

190* **Ultraplan 斷開 Remote Control**:啟動 [ultraplan](/zh-TW/ultraplan) 會話會斷開任何活動的 Remote Control 會話,因為兩個功能都佔據 claude.ai/code 介面,一次只能連接一個。

191* **某些命令僅限本地**:在終端機中開啟互動式選擇器的命令,例如 `/mcp`、`/plugin` 或 `/resume`,只能從本地 CLI 使用。產生文字輸出的命令,包括 `/compact`、`/clear`、`/context`、`/usage`、`/exit`、`/extra-usage`、`/recap` 和 `/reload-plugins`,可從行動和網頁使用。

192 

193## 疑難排解

194 

195### 「Remote Control 需要 claude.ai 訂閱」

196 

197您未使用 claude.ai 帳戶進行驗證。執行 `claude auth login` 並選擇 claude.ai 選項。如果在您的環境中設定了 `ANTHROPIC_API_KEY`,請先取消設定它。

198 

199### 「Remote Control 需要完整範圍登入令牌」

200 

201您使用來自 `claude setup-token` 或 `CLAUDE_CODE_OAUTH_TOKEN` 環境變數的長期令牌進行驗證。這些令牌僅限於推論,無法建立 Remote Control 會話。執行 `claude auth login` 以改用完整範圍會話令牌進行驗證。

202 

203### 「無法確定您的組織以進行 Remote Control 資格檢查」

204 

205您的快取帳戶資訊已過期或不完整。執行 `claude auth login` 以重新整理它。

206 

207### 「Remote Control 尚未為您的帳戶啟用」

208 

209在存在某些環境變數的情況下,資格檢查可能會失敗:

210 

211* `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` 或 `DISABLE_TELEMETRY`:取消設定它們並重試。

212* `CLAUDE_CODE_USE_BEDROCK`、`CLAUDE_CODE_USE_VERTEX` 或 `CLAUDE_CODE_USE_FOUNDRY`:Remote Control 需要 claude.ai 驗證,不適用於第三方提供者。

213 

214如果這些都沒有設定,請執行 `/logout` 然後 `/login` 以重新整理。

215 

216### 「Remote Control 已被您的組織政策停用」

217 

218此錯誤有三個不同的原因。首先執行 `/status` 以查看您使用的登入方法和訂閱。

219 

220* **您使用 API 金鑰或 Console 帳戶進行驗證**:Remote Control 需要 claude.ai OAuth。執行 `/login` 並選擇 claude.ai 選項。如果在您的環境中設定了 `ANTHROPIC_API_KEY`,請取消設定它。

221* **您的 Team 或 Enterprise 管理員尚未啟用它**:Remote Control 在這些方案上預設為關閉。管理員可以在 [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) 透過開啟 **Remote Control** 切換來啟用它。這是伺服器端組織設定,不是[僅限管理的設定](/zh-TW/permissions#managed-only-settings)金鑰。

222* **管理員切換呈灰色**:您的組織具有與 Remote Control 不相容的資料保留或合規配置。這無法從管理面板更改。請聯絡 Anthropic 支援以討論選項。

223 

224### 「Remote credentials fetch failed」

225 

226Claude Code 無法從 Anthropic API 獲取短期認證以建立連接。使用 `--verbose` 重新執行以查看完整錯誤:

227 

228```bash theme={null}

229claude remote-control --verbose

230```

231 

232常見原因:

233 

234* 未登入:執行 `claude` 並使用 `/login` 透過您的 claude.ai 帳戶進行驗證。Remote Control 不支援 API 金鑰驗證。

235* 網路或代理問題:防火牆或代理可能阻止出站 HTTPS 請求。Remote Control 需要存取埠 443 上的 Anthropic API。

236* 會話建立失敗:如果您也看到 `Session creation failed — see debug log`,失敗發生在設定的早期。檢查您的訂閱是否有效。

237 

238## 選擇正確的方法

239 

240Claude Code offers several ways to work when you're not at your terminal. They differ in what triggers the work, where Claude runs, and how much you need to set up.

241 

242| | Trigger | Claude runs on | Setup | Best for |

243| :--------------------------------------------- | :--------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------ |

244| [Dispatch](/en/desktop#sessions-from-dispatch) | Message a task from the Claude mobile app | Your machine (Desktop) | [Pair the mobile app with Desktop](https://support.claude.com/en/articles/13947068) | Delegating work while you're away, minimal setup |

245| [Remote Control](/en/remote-control) | Drive a running session from [claude.ai/code](https://claude.ai/code) or the Claude mobile app | Your machine (CLI or VS Code) | Run `claude remote-control` | Steering in-progress work from another device |

246| [Channels](/en/channels) | Push events from a chat app like Telegram or Discord, or your own server | Your machine (CLI) | [Install a channel plugin](/en/channels#quickstart) or [build your own](/en/channels-reference) | Reacting to external events like CI failures or chat messages |

247| [Slack](/en/slack) | Mention `@Claude` in a team channel | Anthropic cloud | [Install the Slack app](/en/slack#setting-up-claude-code-in-slack) with [Claude Code on the web](/en/claude-code-on-the-web) enabled | PRs and reviews from team chat |

248| [Scheduled tasks](/en/scheduled-tasks) | Set a schedule | [CLI](/en/scheduled-tasks), [Desktop](/en/desktop-scheduled-tasks), or [cloud](/en/routines) | Pick a frequency | Recurring automation like daily reviews |

249 

250## 相關資源

251 

252* [網頁版 Claude Code](/zh-TW/claude-code-on-the-web):在 Anthropic 管理的雲端環境中執行會話,而不是在您的機器上

253* [Ultraplan](/zh-TW/ultraplan):從您的終端機啟動雲端規劃會話,並在瀏覽器中檢查計畫

254* [Channels](/zh-TW/channels):將 Telegram、Discord 或 iMessage 轉發到會話中,以便 Claude 在您離開時對訊息做出反應

255* [Dispatch](/zh-TW/desktop#sessions-from-dispatch):從您的手機傳送任務訊息,它可以生成 Desktop 會話來處理它

256* [驗證](/zh-TW/authentication):設定 `/login` 並管理 claude.ai 的認證

257* [CLI 參考](/zh-TW/cli-reference):包括 `claude remote-control` 的旗標和命令的完整清單

258* [安全性](/zh-TW/security):Remote Control 會話如何適應 Claude Code 安全模型

259* [資料使用](/zh-TW/data-usage):在本地和遠端會話期間透過 Anthropic API 流動的資料

routines.md +319 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 使用例行程序自動化工作

6 

7> 讓 Claude Code 自動運行。定義在排程上運行、在 API 呼叫時觸發或對來自 Anthropic 管理的雲端基礎設施的 GitHub 事件做出反應的例行程序。

8 

9<Note>

10 例行程序處於研究預覽階段。行為、限制和 API 表面可能會變更。

11</Note>

12 

13例行程序是一個已保存的 Claude Code 配置:一個提示、一個或多個存儲庫,以及一組 [connectors](/zh-TW/mcp),打包一次並自動運行。例行程序在 Anthropic 管理的雲端基礎設施上執行,因此當您的筆記本電腦關閉時它們仍會繼續運行。

14 

15每個例行程序可以附加一個或多個觸發器:

16 

17* **排程**:按照每小時、每晚或每週等定期節奏運行

18* **API**:通過向每個例行程序端點發送帶有持有人令牌的 HTTP POST 來按需觸發

19* **GitHub**:自動回應存儲庫事件,例如拉取請求或發佈

20 

21單個例行程序可以組合觸發器。例如,PR 審查例行程序可以每晚運行、從部署腳本觸發,也可以對每個新 PR 做出反應。

22 

23例行程序在啟用了 [Claude Code on the web](/zh-TW/claude-code-on-the-web) 的 Pro、Max、Team 和 Enterprise 計劃上可用。在 [claude.ai/code/routines](https://claude.ai/code/routines) 創建和管理它們,或使用 CLI 中的 `/schedule` 命令。

24 

25本頁涵蓋創建例行程序、配置每種觸發器類型、管理運行以及使用限制如何應用。

26 

27## 示例用例

28 

29每個示例將觸發器類型與例行程序適合的工作類型配對:無人值守、可重複且與明確結果相關。

30 

31**待辦事項維護。** 排程觸發器每個工作日晚上針對您的問題跟蹤器通過 connector 運行。例行程序讀取自上次運行以來打開的問題、應用標籤、根據引用的代碼區域分配所有者,並將摘要發佈到 Slack,以便團隊以整理好的隊列開始新的一天。

32 

33**警報分類。** 您的監控工具在錯誤閾值被超過時調用例行程序的 API 端點,將警報正文作為 `text` 傳遞。例行程序提取堆棧跟蹤、將其與存儲庫中的最近提交相關聯,並打開一個帶有建議修復和返回警報鏈接的草稿拉取請求。值班人員審查 PR 而不是從空白終端開始。

34 

35**定製代碼審查。** GitHub 觸發器在 `pull_request.opened` 上運行。例行程序應用您團隊自己的審查檢查清單,為安全性、性能和風格問題留下內聯評論,並添加摘要評論,以便人工審查者可以專注於設計而不是機械檢查。

36 

37**部署驗證。** 您的 CD 管道在每次生產部署後調用例行程序的 API 端點。例行程序針對新構建運行煙霧測試、掃描錯誤日誌以查找回歸,並在部署窗口關閉前向發佈頻道發佈是否可以部署。

38 

39**文檔漂移。** 排程觸發器每週運行。例行程序掃描自上次運行以來合併的 PR、標記引用已更改 API 的文檔,並針對文檔存儲庫打開更新 PR 供編輯者審查。

40 

41**庫移植。** GitHub 觸發器在 `pull_request.closed` 上運行,篩選為一個 SDK 存儲庫中的合併 PR。例行程序將更改移植到另一種語言的並行 SDK,並打開匹配的 PR,使兩個庫保持同步,而無需人工重新實現每個更改。

42 

43下面的部分將逐步介紹創建例行程序和配置每種觸發器類型。

44 

45## 創建例行程序

46 

47從 Web、Desktop 應用或 CLI 創建例行程序。所有三個界面都寫入同一個雲帳戶,因此您在 CLI 中創建的例行程序會立即顯示在 claude.ai/code/routines 上。在 Desktop 應用中,點擊 **New task** 並選擇 **New remote task**;選擇 **New local task** 會創建一個 [local Desktop scheduled task](/zh-TW/desktop-scheduled-tasks),它在您的機器上運行,不是例行程序。

48 

49創建表單設置例行程序的提示、存儲庫、環境、connectors 和觸發器。

50 

51例行程序作為完整的 Claude Code 雲會話自主運行:沒有權限模式選擇器,運行期間也沒有批准提示。會話可以運行 shell 命令、使用 [skills](/zh-TW/skills) 提交到克隆的存儲庫,並調用您包含的任何 connectors。例行程序可以到達的內容由您選擇的存儲庫及其分支推送設置、[環境的](/zh-TW/claude-code-on-the-web#the-cloud-environment)網絡訪問和變量,以及您包含的 connectors 決定。將每個範圍限制在例行程序實際需要的內容。

52 

53例行程序屬於您的個人 claude.ai 帳戶。它們不與隊友共享,並且計入您帳戶的每日運行配額。例行程序通過您連接的 GitHub 身份或 connectors 執行的任何操作都顯示為您:提交和拉取請求帶有您的 GitHub 用戶,Slack 消息、Linear 票證或其他 connector 操作使用您為這些服務鏈接的帳戶。

54 

55### 從 Web 創建

56 

57<Steps>

58 <Step title="打開創建表單">

59 訪問 [claude.ai/code/routines](https://claude.ai/code/routines) 並點擊 **New routine**。

60 </Step>

61 

62 <Step title="命名例行程序並編寫提示">

63 給例行程序一個描述性名稱並編寫 Claude 每次運行的提示。提示是最重要的部分:例行程序自主運行,因此提示必須是自包含的,並明確說明要做什麼以及成功是什麼樣子。

64 

65 提示輸入包括一個模型選擇器。Claude 在每次運行時使用選定的模型。

66 </Step>

67 

68 <Step title="選擇存儲庫">

69 添加一個或多個 GitHub 存儲庫供 Claude 在其中工作。每個存儲庫在運行開始時從默認分支克隆。Claude 為其更改創建 `claude/` 前綴的分支。要允許推送到任何分支,請為該存儲庫啟用 **Allow unrestricted branch pushes**。

70 </Step>

71 

72 <Step title="選擇環境">

73 為例行程序選擇一個 [cloud environment](/zh-TW/claude-code-on-the-web#the-cloud-environment)。環境控制雲會話可以訪問的內容:

74 

75 * **Network access**:設置每次運行期間可用的互聯網訪問級別

76 * **Environment variables**:提供 API 密鑰、令牌或其他 Claude 可以使用的機密

77 * **Setup script**:在每個會話開始前運行安裝命令,例如安裝依賴項或配置工具。結果是 [cached](/zh-TW/claude-code-on-the-web#environment-caching),因此腳本不會在每個會話上重新運行

78 

79 提供了一個 **Default** 環境。要使用自定義環境,請在創建例行程序前 [create one](/zh-TW/claude-code-on-the-web#the-cloud-environment)。

80 </Step>

81 

82 <Step title="選擇觸發器">

83 在 **Select a trigger** 下,選擇例行程序如何啟動。您可以選擇一種觸發器類型或組合多種。

84 

85 <Tabs>

86 <Tab title="Schedule">

87 選擇預設頻率:每小時、每天、工作日或每週。有關時區處理、交錯和自定義 cron 間隔,請參閱 [Add a schedule trigger](#add-a-schedule-trigger)。

88 </Tab>

89 

90 <Tab title="GitHub event">

91 選擇存儲庫、要反應的事件和可選篩選器。有關支持的事件和篩選字段的完整列表,請參閱 [Add a GitHub trigger](#add-a-github-trigger)。

92 </Tab>

93 

94 <Tab title="API">

95 在此選擇 **API**,然後保存例行程序。URL 和令牌在保存例行程序後生成,因為它們取決於例行程序 ID。請參閱 [Add an API trigger](#add-an-api-trigger) 以複製 URL 並生成令牌。

96 </Tab>

97 </Tabs>

98 </Step>

99 

100 <Step title="審查 connectors">

101 默認情況下包括您所有連接的 [MCP connectors](/zh-TW/mcp)。移除例行程序不需要的任何。Connectors 在每次運行期間讓 Claude 可以訪問外部服務,如 Slack、Linear 或 Google Drive。

102 </Step>

103 

104 <Step title="創建例行程序">

105 點擊 **Create**。例行程序出現在列表中,並在下次其觸發器之一匹配時運行。要立即開始運行,請在例行程序的詳細信息頁面上點擊 **Run now**。

106 

107 每次運行都會在您的其他會話旁邊創建一個新會話,您可以在其中查看 Claude 做了什麼、審查更改並創建拉取請求。

108 </Step>

109</Steps>

110 

111### 從 CLI 創建

112 

113在任何會話中運行 `/schedule` 以對話方式創建排程例行程序。您也可以直接傳遞描述,如 `/schedule daily PR review at 9am`。Claude 會逐步介紹 Web 表單收集的相同信息,然後將例行程序保存到您的帳戶。

114 

115CLI 中的 `/schedule` 僅創建排程例行程序。要添加 API 或 GitHub 觸發器,請在 [claude.ai/code/routines](https://claude.ai/code/routines) 的 Web 上編輯例行程序。

116 

117CLI 還支持管理現有例行程序。運行 `/schedule list` 查看所有例行程序,`/schedule update` 更改一個,或 `/schedule run` 立即觸發它。

118 

119### 從 Desktop 應用創建

120 

121在 Desktop 應用中打開 **Schedule** 頁面,點擊 **New task**,並選擇 **New remote task**。Desktop 應用在同一網格中顯示本地排程任務和例行程序。有關本地選項的詳細信息,請參閱 [Desktop scheduled tasks](/zh-TW/desktop-scheduled-tasks)。

122 

123## 配置觸發器

124 

125當其觸發器之一匹配時,例行程序啟動。您可以將排程、API 和 GitHub 觸發器的任何組合附加到同一例行程序,並可以隨時從例行程序編輯表單的 **Select a trigger** 部分添加或移除它們。

126 

127### 添加排程觸發器

128 

129排程觸發器按定期節奏運行例行程序。在 **Select a trigger** 部分中選擇預設頻率:每小時、每天、工作日或每週。時間以您的本地時區輸入並自動轉換,因此例行程序在該掛鐘時間運行,無論雲端基礎設施位於何處。

130 

131運行可能在排程時間後幾分鐘開始,原因是交錯。每個例行程序的偏移是一致的。

132 

133對於自定義間隔,例如每兩小時或每月的第一天,在表單中選擇最接近的預設,然後在 CLI 中運行 `/schedule update` 以設置特定的 cron 表達式。最小間隔是一小時;運行頻率更高的表達式會被拒絕。

134 

135### 添加 API 觸發器

136 

137API 觸發器為例行程序提供專用的 HTTP 端點。使用例行程序的持有人令牌 POST 到端點會啟動新會話並返回會話 URL。使用此功能將 Claude Code 連接到警報系統、部署管道、內部工具或任何可以進行身份驗證 HTTP 請求的地方。

138 

139API 觸發器從 Web 添加到現有例行程序。CLI 目前無法創建或撤銷令牌。

140 

141<Steps>

142 <Step title="打開例行程序進行編輯">

143 轉到 [claude.ai/code/routines](https://claude.ai/code/routines),點擊您想通過 API 觸發的例行程序,然後點擊鉛筆圖標打開 **Edit routine**。

144 </Step>

145 

146 <Step title="添加 API 觸發器">

147 滾動到提示下方的 **Select a trigger** 部分,點擊 **Add another trigger**,並選擇 **API**。

148 </Step>

149 

150 <Step title="複製 URL 並生成令牌">

151 模態框顯示此例行程序的 URL 以及示例 curl 命令。複製 URL,然後點擊 **Generate token** 並立即複製令牌。令牌只顯示一次,之後無法檢索,因此請將其存儲在安全的地方,例如您的警報工具的機密存儲。

152 </Step>

153 

154 <Step title="調用端點">

155 POST 到 URL 時在 `Authorization: Bearer` 標頭中發送令牌。下面的 [Trigger a routine](#trigger-a-routine) 部分顯示完整示例。

156 </Step>

157</Steps>

158 

159每個例行程序都有自己的令牌,範圍限於僅觸發該例行程序。要輪換或撤銷它,返回同一模態框並點擊 **Regenerate** 或 **Revoke**。

160 

161#### 觸發例行程序

162 

163向 `/fire` 端點發送 POST 請求,在 `Authorization` 標頭中包含持有人令牌。請求正文接受可選的 `text` 字段,用於運行特定的上下文,例如警報正文或失敗的日誌,與其保存的提示一起傳遞給例行程序。該值是自由格式文本,不被解析:如果您發送 JSON 或其他結構化有效負載,例行程序會將其作為文字字符串接收。

164 

165下面的示例從 shell 觸發例行程序:

166 

167```bash theme={null}

168curl -X POST https://api.anthropic.com/v1/claude_code/routines/trig_01ABCDEFGHJKLMNOPQRSTUVW/fire \

169 -H "Authorization: Bearer sk-ant-oat01-xxxxx" \

170 -H "anthropic-beta: experimental-cc-routine-2026-04-01" \

171 -H "anthropic-version: 2023-06-01" \

172 -H "Content-Type: application/json" \

173 -d '{"text": "Sentry alert SEN-4521 fired in prod. Stack trace attached."}'

174```

175 

176成功的請求返回一個 JSON 正文,包含新的會話 ID 和 URL:

177 

178```json theme={null}

179{

180 "type": "routine_fire",

181 "claude_code_session_id": "session_01HJKLMNOPQRSTUVWXYZ",

182 "claude_code_session_url": "https://claude.ai/code/session_01HJKLMNOPQRSTUVWXYZ"

183}

184```

185 

186在瀏覽器中打開會話 URL 以實時觀看運行、審查更改或手動繼續對話。

187 

188<Warning>

189 `/fire` 端點在 `experimental-cc-routine-2026-04-01` beta 標頭下發佈。請求和響應形狀、速率限制和令牌語義可能在功能處於研究預覽階段時變更。破壞性更改在新的日期 beta 標頭版本後發佈,最近的兩個先前標頭版本繼續工作,以便調用者有時間遷移。

190</Warning>

191 

192#### API 參考

193 

194有關完整的 API 參考,包括所有錯誤響應、驗證規則和字段限制,請參閱 Claude Platform 文檔中的 [Trigger a routine via API](https://platform.claude.com/docs/zh-TW/api/claude-code/routines-fire)。

195 

196`/fire` 端點僅對 claude.ai 用戶可用,不是 Claude Platform API 表面的一部分。

197 

198### 添加 GitHub 觸發器

199 

200GitHub 觸發器在連接的存儲庫上發生匹配事件時自動啟動新會話。每個匹配事件啟動自己的會話。

201 

202<Note>

203 在研究預覽期間,GitHub webhook 事件受每個例行程序和每個帳戶的每小時上限限制。超過限制的事件會被丟棄,直到窗口重置。在 [claude.ai/code/routines](https://claude.ai/code/routines) 查看您當前的限制。

204</Note>

205 

206GitHub 觸發器僅從 Web UI 配置。

207 

208<Steps>

209 <Step title="打開例行程序進行編輯">

210 轉到 [claude.ai/code/routines](https://claude.ai/code/routines),點擊例行程序,然後點擊鉛筆圖標打開 **Edit routine**。

211 </Step>

212 

213 <Step title="添加 GitHub 事件觸發器">

214 滾動到 **Select a trigger** 部分,點擊 **Add another trigger**,並選擇 **GitHub event**。

215 </Step>

216 

217 <Step title="安裝 Claude GitHub App">

218 Claude GitHub App 必須安裝在您想訂閱的存儲庫上。如果尚未安裝,觸發器設置會提示您安裝它。

219 

220 <Note>

221 在 CLI 中運行 `/web-setup` 授予存儲庫訪問權限以進行克隆,但它不安裝 Claude GitHub App,也不啟用 webhook 傳遞。GitHub 觸發器需要安裝 Claude GitHub App,觸發器設置會提示您執行此操作。

222 </Note>

223 </Step>

224 

225 <Step title="配置觸發器">

226 選擇存儲庫,從 [supported events](#supported-events) 列表中選擇事件,並可選地添加篩選器。保存觸發器。

227 </Step>

228</Steps>

229 

230#### 支持的事件

231 

232GitHub 觸發器可以訂閱以下事件類別之一。在每個類別中,您可以選擇特定操作,例如 `pull_request.opened`,或對類別中的所有操作做出反應。

233 

234| 事件 | 觸發時機 |

235| :----------- | :------------------------- |

236| Pull request | PR 被打開、關閉、分配、標記、同步或以其他方式更新 |

237| Release | 發佈被創建、發佈、編輯或刪除 |

238 

239#### 篩選拉取請求

240 

241使用篩選器縮小哪些拉取請求啟動新會話。所有篩選條件必須匹配才能觸發例行程序。可用的篩選字段是:

242 

243| 篩選器 | 匹配 |

244| :---------- | :---------------- |

245| Author | PR 作者的 GitHub 用戶名 |

246| Title | PR 標題文本 |

247| Body | PR 描述文本 |

248| Base branch | PR 目標的分支 |

249| Head branch | PR 來自的分支 |

250| Labels | 應用於 PR 的標籤 |

251| Is draft | PR 是否處於草稿狀態 |

252| Is merged | PR 是否已合併 |

253| From fork | PR 是否來自分支 |

254 

255每個篩選器將字段與運算符配對:等於、包含、開始於、是其中之一、不是其中之一或匹配正則表達式。

256 

257`matches regex` 運算符測試整個字段值,而不是其中的子字符串。要匹配任何包含 `hotfix` 的標題,請寫 `.*hotfix.*`。沒有周圍的 `.*`,篩選器僅匹配完全是 `hotfix` 的標題,前後沒有任何內容。對於不使用正則表達式語法的文字子字符串匹配,請改用 `contains` 運算符。

258 

259一些示例篩選器組合:

260 

261* **Auth module review**:base branch `main`,head branch 包含 `auth-provider`。將任何涉及身份驗證的 PR 發送給專注的審查者。

262* **External contributor triage**:from fork 是 `true`。在人工查看前,通過額外的安全和風格審查路由每個基於分支的 PR。

263* **Ready-for-review only**:is draft 是 `false`。跳過草稿,以便例行程序僅在 PR 準備好審查時運行。

264* **Label-gated backport**:labels 包括 `needs-backport`。僅當維護者標記 PR 時才觸發移植到另一分支的例行程序。

265 

266#### 會話如何映射到事件

267 

268每個匹配的 GitHub 事件啟動新會話。GitHub 觸發的例行程序不提供跨事件的會話重用,因此兩個 PR 更新會產生兩個獨立會話。

269 

270## 管理例行程序

271 

272點擊列表中的例行程序以打開其詳細信息頁面。詳細信息頁面顯示例行程序的存儲庫、connectors、提示、排程、API 令牌、GitHub 觸發器和過去運行的列表。

273 

274### 查看和交互運行

275 

276點擊任何運行以將其作為完整會話打開。從那裡您可以看到 Claude 做了什麼、審查更改、創建拉取請求或繼續對話。每個運行會話的工作方式與任何其他會話相同:使用會話標題旁邊的下拉菜單重命名、存檔或刪除它。

277 

278### 編輯和控制例行程序

279 

280從例行程序詳細信息頁面,您可以:

281 

282* 點擊 **Run now** 立即開始運行,無需等待下一個排程時間。

283* 使用 **Repeats** 部分中的切換暫停或恢復排程。暫停的例行程序保留其配置但不運行,直到您重新啟用它們。

284* 點擊鉛筆圖標打開 **Edit routine** 並更改名稱、提示、存儲庫、環境、connectors 或例行程序的任何觸發器。**Select a trigger** 部分是您添加或移除排程、API 令牌和 GitHub 事件觸發器的地方。

285* 點擊刪除圖標移除例行程序。由例行程序創建的過去會話保留在您的會話列表中。

286 

287### 存儲庫和分支權限

288 

289例行程序需要 GitHub 訪問權限來克隆存儲庫。當您使用 `/schedule` 從 CLI 創建例行程序時,Claude 檢查您的帳戶是否連接了 GitHub,如果沒有則提示您運行 `/web-setup`。有關授予訪問權限的兩種方式,請參閱 [GitHub authentication options](/zh-TW/claude-code-on-the-web#github-authentication-options)。

290 

291您添加的每個存儲庫在每次運行時都會被克隆。Claude 從存儲庫的默認分支開始,除非您的提示另有指定。

292 

293默認情況下,Claude 只能推送到以 `claude/` 為前綴的分支。這可以防止例行程序意外修改受保護或長期分支。要移除特定存儲庫的此限制,請在創建或編輯例行程序時為該存儲庫啟用 **Allow unrestricted branch pushes**。

294 

295### Connectors

296 

297例行程序可以使用您連接的 MCP connectors 在每次運行期間讀取和寫入外部服務。例如,分類支持請求的例行程序可能從 Slack 頻道讀取並在 Linear 中創建問題。

298 

299當您創建例行程序時,默認情況下包括您所有當前連接的 connectors。移除任何不需要的以限制 Claude 在運行期間可以訪問的工具。您也可以直接從例行程序表單添加 connectors。

300 

301要在例行程序表單外管理或添加 connectors,請訪問 claude.ai 上的 **Settings > Connectors** 或在 CLI 中使用 `/schedule update`。

302 

303### 環境

304 

305每個例行程序在 [cloud environment](/zh-TW/claude-code-on-the-web#the-cloud-environment) 中運行,該環境控制網絡訪問、環境變量和設置腳本。在創建例行程序前配置環境,以便 Claude 訪問 API、安裝依賴項或限制網絡範圍。有關完整的設置指南,請參閱 [cloud environment](/zh-TW/claude-code-on-the-web#the-cloud-environment)。

306 

307## 使用和限制

308 

309例行程序以與交互式會話相同的方式消耗訂閱使用量。除了標準訂閱限制外,例行程序還有每個帳戶每天可以啟動多少次運行的每日上限。在 [claude.ai/code/routines](https://claude.ai/code/routines) 或 [claude.ai/settings/usage](https://claude.ai/settings/usage) 查看您當前的消耗和剩餘的每日例行程序運行。

310 

311當例行程序達到每日上限或您的訂閱使用限制時,啟用了額外使用的組織可以繼續在計量超額上運行例行程序。沒有額外使用,額外運行會被拒絕,直到窗口重置。從 claude.ai 上的 **Settings > Billing** 啟用額外使用。

312 

313## 相關資源

314 

315* [`/loop` 和會話內排程](/zh-TW/scheduled-tasks):在打開的 CLI 會話中排程本地任務

316* [Desktop scheduled tasks](/zh-TW/desktop-scheduled-tasks):在您的機器上運行的本地排程任務,可以訪問本地文件

317* [Cloud environment](/zh-TW/claude-code-on-the-web#the-cloud-environment):為雲會話配置運行時環境

318* [MCP connectors](/zh-TW/mcp):連接外部服務,如 Slack、Linear 和 Google Drive

319* [GitHub Actions](/zh-TW/github-actions):在存儲庫事件上在您的 CI 管道中運行 Claude

sandboxing.md +329 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Sandboxing

6 

7> 了解 Claude Code 的沙箱化 bash 工具如何提供檔案系統和網路隔離,以實現更安全、更自主的代理執行。

8 

9## 概述

10 

11Claude Code 具有原生沙箱化功能,為代理執行提供更安全的環境,同時減少對持續權限提示的需求。沙箱化不是要求每個 bash 命令的權限,而是預先建立定義的邊界,讓 Claude Code 能夠以降低風險的方式更自由地工作。

12 

13沙箱化 bash 工具使用作業系統級別的原語來強制執行檔案系統和網路隔離。

14 

15## 為什麼沙箱化很重要

16 

17傳統的基於權限的安全性需要對 bash 命令進行持續的使用者批准。雖然這提供了控制,但可能導致:

18 

19* **批准疲勞**:重複點擊「批准」可能導致使用者對他們批准的內容關注度降低

20* **生產力降低**:持續的中斷會減慢開發工作流程

21* **自主性受限**:當等待批准時,Claude Code 無法高效工作

22 

23沙箱化通過以下方式解決這些挑戰:

24 

251. **定義清晰的邊界**:精確指定 Claude Code 可以存取的目錄和網路主機

262. **減少權限提示**:沙箱內的安全命令不需要批准

273. **維持安全性**:嘗試存取沙箱外的資源會觸發立即通知

284. **啟用自主性**:Claude Code 可以在定義的限制內更獨立地運行

29 

30<Warning>

31 有效的沙箱化需要**同時**進行檔案系統和網路隔離。沒有網路隔離,受損的代理可能會洩露敏感檔案,如 SSH 金鑰。沒有檔案系統隔離,受損的代理可能會後門系統資源以獲得網路存取。配置沙箱化時,重要的是確保您配置的設定不會在這些系統中建立繞過。

32</Warning>

33 

34## 它如何運作

35 

36### 檔案系統隔離

37 

38沙箱化 bash 工具將檔案系統存取限制在特定目錄:

39 

40* **預設寫入行為**:對目前工作目錄及其子目錄的讀取和寫入存取

41* **預設讀取行為**:對整個電腦的讀取存取,除了某些被拒絕的目錄

42* **被阻止的存取**:無法在沒有明確權限的情況下修改目前工作目錄外的檔案

43* **可配置**:通過設定定義自訂允許和拒絕的路徑

44 

45您可以使用設定中的 `sandbox.filesystem.allowWrite` 授予對其他路徑的寫入存取。這些限制在作業系統級別強制執行(macOS 上的 Seatbelt,Linux 上的 bubblewrap),因此它們適用於所有子流程命令,包括 `kubectl`、`terraform` 和 `npm` 等工具,而不僅僅是 Claude 的檔案工具。

46 

47### 網路隔離

48 

49網路存取通過在沙箱外運行的代理伺服器進行控制:

50 

51* **域名限制**:只能存取已批准的域名

52* **使用者確認**:新的域名請求會觸發權限提示(除非啟用了 [`allowManagedDomainsOnly`](/zh-TW/settings#sandbox-settings),它會自動阻止非允許的域名)

53* **自訂代理支援**:進階使用者可以在出站流量上實施自訂規則

54* **全面覆蓋**:限制適用於所有指令碼、程式和由命令產生的子流程

55 

56### 作業系統級別的強制執行

57 

58沙箱化 bash 工具利用作業系統安全原語:

59 

60* **macOS**:使用 Seatbelt 進行沙箱強制執行

61* **Linux**:使用 [bubblewrap](https://github.com/containers/bubblewrap) 進行隔離

62* **WSL2**:使用 bubblewrap,與 Linux 相同

63 

64不支援 WSL1,因為 bubblewrap 需要僅在 WSL2 中可用的核心功能。

65 

66這些作業系統級別的限制確保由 Claude Code 命令產生的所有子流程都繼承相同的安全邊界。

67 

68## 入門

69 

70### 先決條件

71 

72在 **macOS** 上,沙箱化使用內建的 Seatbelt 框架開箱即用。

73 

74在 **Linux 和 WSL2** 上,首先安裝所需的套件:

75 

76<Tabs>

77 <Tab title="Ubuntu/Debian">

78 ```bash theme={null}

79 sudo apt-get install bubblewrap socat

80 ```

81 </Tab>

82 

83 <Tab title="Fedora">

84 ```bash theme={null}

85 sudo dnf install bubblewrap socat

86 ```

87 </Tab>

88</Tabs>

89 

90WSL1 不支援沙箱化,因為它缺少所需的 Linux 命名空間原語。如果您看到 `Sandboxing requires WSL2`,請將您的發行版升級到 WSL2 或在沒有沙箱化的情況下執行 Claude Code。

91 

92在 WSL2 上,沙箱化命令無法啟動 Windows 二進位檔案,例如 `cmd.exe`、`powershell.exe` 或 `/mnt/c/` 下的任何內容。WSL 通過 Unix socket 將這些交給 Windows 主機,沙箱會阻止此操作。如果命令需要呼叫 Windows 二進位檔案,請將其新增到 [`excludedCommands`](/zh-TW/settings#sandbox-settings),以便它在沙箱外執行。

93 

94### 啟用沙箱化

95 

96您可以通過執行 `/sandbox` 命令來啟用沙箱化:

97 

98```text theme={null}

99/sandbox

100```

101 

102這會開啟一個選單,您可以在其中選擇沙箱模式。如果缺少所需的依賴項(例如 Linux 上的 `bubblewrap` 或 `socat`),選單會顯示您平台的安裝說明。

103 

104預設情況下,如果沙箱無法啟動(缺少依賴項或不支援的平台),Claude Code 會顯示警告並在沒有沙箱化的情況下運行命令。要改為將其設為硬失敗,請將 [`sandbox.failIfUnavailable`](/zh-TW/settings#sandbox-settings) 設定為 `true`。這適用於需要沙箱化作為安全閘道的受管部署。

105 

106### 沙箱模式

107 

108Claude Code 提供兩種沙箱模式:

109 

110**自動允許模式**:Bash 命令將嘗試在沙箱內運行,並自動允許而無需權限。無法沙箱化的命令(例如需要存取非允許主機的網路存取的命令)會回退到常規權限流程。明確拒絕規則始終被尊重,而且針對 `/`、您的主目錄或其他關鍵系統路徑的 `rm` 或 `rmdir` 命令仍然會觸發權限提示。詢問規則僅適用於回退到常規權限流程的命令。

111 

112**常規權限模式**:所有 bash 命令都通過標準權限流程進行,即使沙箱化也是如此。這提供了更多控制,但需要更多批准。

113 

114在兩種模式中,沙箱強制執行相同的檔案系統和網路限制。區別僅在於沙箱化命令是自動批准還是需要明確權限。

115 

116<Info>

117 自動允許模式獨立於您的權限模式設定工作。即使您不在「接受編輯」模式中,當啟用自動允許時,沙箱化 bash 命令也會自動運行。這意味著在沙箱邊界內修改檔案的 bash 命令將執行而不提示,即使檔案編輯工具通常需要批准。

118</Info>

119 

120### 配置沙箱化

121 

122通過您的 `settings.json` 檔案自訂沙箱行為。有關完整配置參考,請參閱 [Settings](/zh-TW/settings#sandbox-settings)。

123 

124#### 授予子流程對特定路徑的寫入存取

125 

126預設情況下,沙箱化命令只能寫入目前工作目錄。如果子流程命令(如 `kubectl`、`terraform` 或 `npm`)需要寫入專案目錄外,請使用 `sandbox.filesystem.allowWrite` 授予對特定路徑的存取:

127 

128```json theme={null}

129{

130 "sandbox": {

131 "enabled": true,

132 "filesystem": {

133 "allowWrite": ["~/.kube", "/tmp/build"]

134 }

135 }

136}

137```

138 

139這些路徑在作業系統級別強制執行,因此在沙箱內運行的所有命令(包括其子流程)都尊重它們。當工具需要對特定位置的寫入存取時,這是推薦的方法,而不是使用 `excludedCommands` 將工具排除在沙箱外。

140 

141當在多個 [settings scopes](/zh-TW/settings#settings-precedence) 中定義 `allowWrite`(或 `denyWrite`/`denyRead`/`allowRead`)時,陣列被**合併**,這意味著來自每個範圍的路徑被組合,而不是被替換。例如,如果受管設定允許寫入 `/opt/company-tools`,而使用者在其個人設定中新增 `~/.kube`,則兩個路徑都包含在最終沙箱配置中。這意味著使用者和專案可以擴展清單而無需複製或覆蓋由更高優先級範圍設定的路徑。

142 

143路徑前綴控制路徑的解析方式:

144 

145| 前綴 | 含義 | 範例 |

146| :-------- | :------------------------------------ | :---------------------------------------------------------------- |

147| `/` | 從檔案系統根目錄的絕對路徑 | `/tmp/build` 保持 `/tmp/build` |

148| `~/` | 相對於主目錄 | `~/.kube` 變成 `$HOME/.kube` |

149| `./` 或無前綴 | 相對於專案設定的專案根目錄,或相對於 `~/.claude` 的使用者設定 | `.claude/settings.json` 中的 `./output` 解析為 `<project-root>/output` |

150 

151較舊的 `//path` 前綴用於絕對路徑仍然有效。如果您之前使用單斜線 `/path` 期望專案相對解析,請切換到 `./path`。此語法與 [Read and Edit](/zh-TW/permissions#read-and-edit) 權限規則不同,後者使用 `//path` 表示絕對路徑,`/path` 表示專案相對路徑。沙箱檔案系統路徑使用標準慣例:`/tmp/build` 是絕對路徑。

152 

153您也可以使用 `sandbox.filesystem.denyWrite` 和 `sandbox.filesystem.denyRead` 拒絕寫入或讀取存取。這些與來自 `Edit(...)` 和 `Read(...)` 權限規則的任何路徑合併。要重新允許讀取 `denyRead` 區域內的特定路徑,請使用 `sandbox.filesystem.allowRead`,它優先於 `denyRead`。當在受管設定中啟用 `allowManagedReadPathsOnly` 時,只有受管 `allowRead` 項目被尊重;使用者、專案和本地 `allowRead` 項目被忽略。`denyRead` 仍然從所有來源合併。

154 

155例如,要阻止從整個主目錄讀取,同時仍允許從目前專案讀取,請將此新增到您的專案的 `.claude/settings.json`:

156 

157```json theme={null}

158{

159 "sandbox": {

160 "enabled": true,

161 "filesystem": {

162 "denyRead": ["~/"],

163 "allowRead": ["."]

164 }

165 }

166}

167```

168 

169`allowRead` 中的 `.` 解析為專案根目錄,因為此配置位於專案設定中。如果您將相同的配置放在 `~/.claude/settings.json` 中,`.` 將解析為 `~/.claude`,專案檔案將保持被 `denyRead` 規則阻止。

170 

171<Tip>

172 並非所有命令都與沙箱化開箱即用相容。一些可能幫助您充分利用沙箱的注意事項:

173 

174 * 許多 CLI 工具需要存取某些主機。當您使用這些工具時,它們將請求權限以存取某些主機。授予權限將允許它們現在和將來存取這些主機,使它們能夠在沙箱內安全執行。

175 * `watchman` 與在沙箱中運行不相容。如果您正在執行 `jest`,請考慮使用 `jest --no-watchman`

176 * `docker` 與在沙箱中運行不相容。考慮在 `excludedCommands` 中指定 `docker *` 以強制其在沙箱外運行。

177</Tip>

178 

179<Note>

180 Claude Code 包含一個有意的逃生艙機制,允許命令在必要時在沙箱外運行。當命令因沙箱限制而失敗時(例如網路連接問題或不相容的工具),Claude 會被提示分析失敗,並可能使用 `dangerouslyDisableSandbox` 參數重試命令。使用此參數的命令通過需要使用者權限執行的常規 Claude Code 權限流程進行。這允許 Claude Code 處理某些工具或網路操作無法在沙箱約束內運作的邊界情況。

181 

182 您可以通過在 [sandbox settings](/zh-TW/settings#sandbox-settings) 中設定 `"allowUnsandboxedCommands": false` 來禁用此逃生艙。禁用時,`dangerouslyDisableSandbox` 參數被完全忽略,所有命令必須沙箱化運行或在 `excludedCommands` 中明確列出。

183</Note>

184 

185## 安全優勢

186 

187### 防止提示注入

188 

189即使攻擊者通過提示注入成功操縱 Claude Code 的行為,沙箱也確保您的系統保持安全:

190 

191**檔案系統保護:**

192 

193* 無法修改關鍵配置檔案,如 `~/.bashrc`

194* 無法修改 `/bin/` 中的系統級檔案

195* 無法讀取在您的 [Claude 權限設定](/zh-TW/permissions#manage-permissions) 中被拒絕的檔案

196 

197**網路保護:**

198 

199* 無法將資料洩露到攻擊者控制的伺服器

200* 無法從未授權的域名下載惡意指令碼

201* 無法對未批准的服務進行意外的 API 呼叫

202* 無法聯繫任何未明確允許的域名

203 

204**監控和控制:**

205 

206* 所有在沙箱外的存取嘗試都在作業系統級別被阻止

207* 當邊界被測試時,您會收到立即通知

208* 您可以選擇拒絕、允許一次或永久更新您的配置

209 

210### 減少攻擊面

211 

212沙箱化限制了以下可能造成的損害:

213 

214* **惡意依賴項**:具有有害程式碼的 NPM 套件或其他依賴項

215* **受損指令碼**:具有安全漏洞的構建指令碼或工具

216* **社交工程**:欺騙使用者執行危險命令的攻擊

217* **提示注入**:欺騙 Claude 執行危險命令的攻擊

218 

219### 透明操作

220 

221當 Claude Code 嘗試存取沙箱外的網路資源時:

222 

2231. 操作在作業系統級別被阻止

2242. 您會收到立即通知

2253. 您可以選擇:

226 * 拒絕請求

227 * 允許一次

228 * 更新您的沙箱配置以永久允許它

229 

230## 安全限制

231 

232* 網路沙箱化限制:網路過濾系統通過限制流程允許連接的域名來運作。它不會以其他方式檢查通過代理的流量,使用者負責確保他們在其策略中只允許受信任的域名。

233 

234<Warning>

235 使用者應該意識到允許廣泛域名(如 `github.com`)可能帶來的潛在風險,這可能允許資料洩露。此外,在某些情況下,可能可以通過 [domain fronting](https://en.wikipedia.org/wiki/Domain_fronting) 繞過網路過濾。

236</Warning>

237 

238* Unix 套接字特權提升:`allowUnixSockets` 配置可能會無意中授予對強大系統服務的存取,這可能導致沙箱繞過。例如,如果它用於允許存取 `/var/run/docker.sock`,這將有效地通過利用 docker 套接字授予對主機系統的存取。鼓勵使用者仔細考慮他們通過沙箱允許的任何 unix 套接字。

239* 檔案系統權限提升:過於寬泛的檔案系統寫入權限可能導致特權提升攻擊。允許寫入包含 `$PATH` 中可執行檔案的目錄、系統配置目錄或使用者 shell 配置檔案(`.bashrc`、`.zshrc`)可能導致當其他使用者或系統流程存取這些檔案時在不同安全上下文中執行程式碼。

240* Linux 沙箱強度:Linux 實現提供強大的檔案系統和網路隔離,但包含一個 `enableWeakerNestedSandbox` 模式,使其能夠在 Docker 環境中工作而無需特權命名空間。此選項大大削弱了安全性,應僅在其他隔離被強制執行的情況下使用。

241 

242## 沙箱化與權限的關係

243 

244沙箱化和 [permissions](/zh-TW/permissions) 是協同工作的互補安全層:

245 

246* **權限**控制 Claude Code 可以使用哪些工具,並在任何工具運行之前進行評估。它們適用於所有工具:Bash、Read、Edit、WebFetch、MCP 和其他工具。

247* **沙箱化**提供作業系統級別的強制執行,限制 Bash 命令在檔案系統和網路級別可以存取的內容。它僅適用於 Bash 命令及其子流程。

248 

249檔案系統和網路限制通過沙箱設定和權限規則進行配置:

250 

251* 使用 `sandbox.filesystem.allowWrite` 授予子流程對工作目錄外路徑的寫入存取

252* 使用 `sandbox.filesystem.denyWrite` 和 `sandbox.filesystem.denyRead` 阻止子流程對特定路徑的存取

253* 使用 `sandbox.filesystem.allowRead` 重新允許讀取 `denyRead` 區域內的特定路徑

254* 使用 `Read` 和 `Edit` 拒絕規則阻止對特定檔案或目錄的存取

255* 使用 `WebFetch` 允許/拒絕規則控制域名存取

256* 使用沙箱 `allowedDomains` 控制 Bash 命令可以到達的域名

257* 使用沙箱 `deniedDomains` 阻止特定域名,即使更廣泛的 `allowedDomains` 萬用字元會允許它們

258 

259來自 `sandbox.filesystem` 設定和權限規則的路徑被合併到最終沙箱配置中。

260 

261此 [repository](https://github.com/anthropics/claude-code/tree/main/examples/settings) 包含常見部署場景的入門設定配置,包括沙箱特定的範例。使用這些作為起點,並根據您的需求進行調整。

262 

263## 進階用法

264 

265### 自訂代理配置

266 

267對於需要進階網路安全的組織,您可以實施自訂代理以:

268 

269* 解密和檢查 HTTPS 流量

270* 應用自訂過濾規則

271* 記錄所有網路請求

272* 與現有安全基礎設施整合

273 

274```json theme={null}

275{

276 "sandbox": {

277 "network": {

278 "httpProxyPort": 8080,

279 "socksProxyPort": 8081

280 }

281 }

282}

283```

284 

285### 與現有安全工具的整合

286 

287沙箱化 bash 工具與以下工具配合使用:

288 

289* **權限規則**:與 [permission settings](/zh-TW/permissions) 結合以實現深度防禦

290* **開發容器**:與 [dev containers](/zh-TW/devcontainer) 一起使用以獲得額外隔離

291* **企業策略**:通過 [managed settings](/zh-TW/settings#settings-precedence) 強制執行沙箱配置

292 

293## 最佳實踐

294 

2951. **從限制性開始**:從最小權限開始,根據需要擴展

2962. **監控日誌**:檢查沙箱違規嘗試以了解 Claude Code 的需求

2973. **使用環境特定配置**:開發與生產環境的不同沙箱規則

2984. **與權限結合**:將沙箱化與 IAM 策略一起使用以實現全面安全

2995. **測試配置**:驗證您的沙箱設定不會阻止合法工作流程

300 

301## 開源

302 

303沙箱執行時可作為開源 npm 套件供您在自己的代理專案中使用。這使更廣泛的 AI 代理社群能夠構建更安全、更安全的自主系統。這也可以用於沙箱化您可能希望運行的其他程式。例如,要沙箱化 MCP 伺服器,您可以執行:

304 

305```bash theme={null}

306npx @anthropic-ai/sandbox-runtime <command-to-sandbox>

307```

308 

309有關實現詳情和原始程式碼,請訪問 [GitHub repository](https://github.com/anthropic-experimental/sandbox-runtime)。

310 

311## 限制

312 

313* **效能開銷**:最小,但某些檔案系統操作可能稍慢

314* **相容性**:某些需要特定系統存取模式的工具可能需要配置調整,或甚至可能需要在沙箱外運行

315* **平台支援**:支援 macOS、Linux 和 WSL2。不支援 WSL1。計劃提供原生 Windows 支援。

316 

317## 沙箱化不涵蓋的內容

318 

319沙箱隔離 Bash 子流程。其他工具在不同的邊界下運作:

320 

321* **內建檔案工具**:Read、Edit 和 Write 直接使用權限系統,而不是通過沙箱運行。請參閱 [permissions](/zh-TW/permissions)。

322* **電腦使用**:當 Claude 打開應用程式並控制您的螢幕時,它在您的實際桌面上運行,而不是在隔離環境中。每個應用程式的權限提示控制每個應用程式。請參閱 [CLI 中的電腦使用](/zh-TW/computer-use) 或 [Desktop 中的電腦使用](/zh-TW/desktop#let-claude-use-your-computer)。

323 

324## 另請參閱

325 

326* [Security](/zh-TW/security) - 全面的安全功能和最佳實踐

327* [Permissions](/zh-TW/permissions) - 權限配置和存取控制

328* [Settings](/zh-TW/settings) - 完整配置參考

329* [CLI reference](/zh-TW/cli-reference) - 命令列選項

scheduled-tasks.md +213 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 按排程執行提示

6 

7> 使用 /loop 和 cron 排程工具在 Claude Code 工作階段內重複執行提示、輪詢狀態或設定一次性提醒。

8 

9<Note>

10 排程任務需要 Claude Code v2.1.72 或更新版本。使用 `claude --version` 檢查您的版本。

11</Note>

12 

13排程任務讓 Claude 按間隔自動重新執行提示。使用它們來輪詢部署、監督 PR、檢查長時間執行的建置,或在工作階段稍後提醒自己執行某些操作。若要改為對事件發生時做出反應而不是輪詢,請參閱 [Channels](/zh-TW/channels):您的 CI 可以直接將失敗推送到工作階段中。

14 

15任務的範圍限於工作階段:它們存在於目前的對話中,當您啟動新的對話時就會停止。使用 `--resume` 或 `--continue` 繼續會恢復任何尚未[過期](#seven-day-expiry)的任務:在過去 7 天內建立的重複執行任務,或排程時間尚未到達的一次性任務。對於獨立於任何工作階段而存在的排程,請使用 [Routines](/zh-TW/routines)、[Desktop 排程任務](/zh-TW/desktop-scheduled-tasks) 或 [GitHub Actions](/zh-TW/github-actions)。

16 

17## 比較排程選項

18 

19Claude Code offers three ways to schedule recurring or one-off work:

20 

21| | [Cloud](/en/routines) | [Desktop](/en/desktop-scheduled-tasks) | [`/loop`](/en/scheduled-tasks) |

22| :------------------------- | :----------------------------- | :------------------------------------- | :---------------------------------- |

23| Runs on | Anthropic cloud | Your machine | Your machine |

24| Requires machine on | No | Yes | Yes |

25| Requires open session | No | No | Yes |

26| Persistent across restarts | Yes | Yes | Restored on `--resume` if unexpired |

27| Access to local files | No (fresh clone) | Yes | Yes |

28| MCP servers | Connectors configured per task | [Config files](/en/mcp) and connectors | Inherits from session |

29| Permission prompts | No (runs autonomously) | Configurable per task | Inherits from session |

30| Customizable schedule | Via `/schedule` in the CLI | Yes | Yes |

31| Minimum interval | 1 hour | 1 minute | 1 minute |

32 

33<Tip>

34 Use **cloud tasks** for work that should run reliably without your machine. Use **Desktop tasks** when you need access to local files and tools. Use **`/loop`** for quick polling during a session.

35</Tip>

36 

37## 使用 /loop 重複執行提示

38 

39`/loop` [bundled skill](/zh-TW/commands) 是排程重複執行提示的最快方式,同時工作階段保持開啟。間隔和提示都是選用的,您提供的內容決定了迴圈的行為方式。

40 

41| 您提供的內容 | 範例 | 發生的情況 |

42| :----- | :-------------------------- | :------------------------------------------------------------------- |

43| 間隔和提示 | `/loop 5m check the deploy` | 您的提示在[固定排程](#run-on-a-fixed-interval)上執行 |

44| 僅提示 | `/loop check the deploy` | 您的提示在 [Claude 選擇的間隔](#let-claude-choose-the-interval)上執行,每次迭代 |

45| 僅間隔或無 | `/loop` | [內建維護提示](#run-the-built-in-maintenance-prompt)執行,或您的 `loop.md`(如果存在) |

46 

47您也可以傳遞另一個命令作為提示,例如 `/loop 20m /review-pr 1234`,以在每次迭代時重新執行打包的工作流程。

48 

49### 在固定間隔上執行

50 

51當您提供間隔時,Claude 會將其轉換為 cron 表達式、排程工作,並確認頻率和工作 ID。

52 

53```text theme={null}

54/loop 5m check if the deployment finished and tell me what happened

55```

56 

57間隔可以作為裸令牌(如 `30m`)在提示前面,或作為子句(如 `every 2 hours`)在後面。支援的單位為 `s`(秒)、`m`(分鐘)、`h`(小時)和 `d`(天)。

58 

59秒數會四捨五入到最近的分鐘,因為 cron 的粒度為一分鐘。不能均勻分割其單位的間隔(例如 `7m` 或 `90m`)會四捨五入到最近的整潔間隔,Claude 會告訴您它選擇了什麼。

60 

61### 讓 Claude 選擇間隔

62 

63當您省略間隔時,Claude 會動態選擇一個,而不是在固定的 cron 排程上執行。在每次迭代後,它會根據觀察到的情況選擇一個介於一分鐘到一小時之間的延遲:在建置完成或 PR 活躍時短暫等待,當沒有待處理項目時較長等待。選擇的延遲和原因會在每次迭代結束時列印。

64 

65下面的範例檢查 CI 和審查評論,Claude 在 PR 變得安靜後在迭代之間等待更長時間:

66 

67```text theme={null}

68/loop check whether CI passed and address any review comments

69```

70 

71當您要求動態 `/loop` 排程時,Claude 可能會直接使用 [Monitor tool](/zh-TW/tools-reference#monitor-tool)。Monitor 執行背景指令碼並串流回每個輸出行,這完全避免了輪詢,通常比在間隔上重新執行提示更具令牌效率和回應性。

72 

73動態排程的迴圈會像任何其他任務一樣出現在您的[排程任務清單](#manage-scheduled-tasks)中,因此您可以以相同的方式列出或取消它。[抖動規則](#jitter)不適用於它,但[七天過期](#seven-day-expiry)適用:迴圈在您啟動它七天後自動結束。

74 

75<Note>

76 在 Bedrock、Vertex AI 和 Microsoft Foundry 上,沒有間隔的提示會改為在固定的 10 分鐘排程上執行。

77</Note>

78 

79### 執行內建維護提示

80 

81當您省略提示時,Claude 會使用內建維護提示而不是您提供的提示。在每次迭代上,它會按順序進行以下操作:

82 

83* 繼續對話中任何未完成的工作

84* 照顧目前分支的拉取請求:審查評論、失敗的 CI 執行、合併衝突

85* 執行清理通過,例如當沒有其他待處理項目時的錯誤搜尋或簡化

86 

87Claude 不會在該範圍之外啟動新的計畫,不可逆的操作(例如推送或刪除)只在它們繼續文字記錄已授權的內容時進行。

88 

89```text theme={null}

90/loop

91```

92 

93裸 `/loop` 在[動態選擇的間隔](#let-claude-choose-the-interval)上執行此提示。新增間隔(例如 `/loop 15m`)以改為在固定排程上執行它。若要用您自己的預設值替換內建提示,請參閱[使用 loop.md 自訂預設提示](#customize-the-default-prompt-with-loop-md)。

94 

95<Note>

96 在 Bedrock、Vertex AI 和 Microsoft Foundry 上,沒有提示的 `/loop` 會列印使用訊息,而不是啟動維護迴圈。

97</Note>

98 

99### 使用 loop.md 自訂預設提示

100 

101`loop.md` 檔案用您自己的指示替換內建維護提示。它為裸 `/loop` 定義單一預設提示,而不是單獨排程任務的清單,並且每當您在命令行上提供提示時都會被忽略。若要在其旁邊排程其他提示,請使用 `/loop <prompt>` 或[直接要求 Claude](#manage-scheduled-tasks)。

102 

103Claude 在兩個位置尋找檔案,並使用它找到的第一個。

104 

105| 路徑 | 範圍 |

106| :------------------ | :------------------- |

107| `.claude/loop.md` | 專案層級。當兩個檔案都存在時優先。 |

108| `~/.claude/loop.md` | 使用者層級。適用於任何未定義自己的專案。 |

109 

110該檔案是純 Markdown,沒有必需的結構。將其寫成您直接輸入 `/loop` 提示的方式。以下範例保持發行分支健康:

111 

112```markdown title=".claude/loop.md" theme={null}

113Check the `release/next` PR. If CI is red, pull the failing job log,

114diagnose, and push a minimal fix. If new review comments have arrived,

115address each one and resolve the thread. If everything is green and

116quiet, say so in one line.

117```

118 

119對 `loop.md` 的編輯在下次迭代時生效,因此您可以在迴圈執行時精煉指示。當任一位置都不存在 `loop.md` 時,迴圈會回退到內建維護提示。保持檔案簡潔:超過 25,000 位元組的內容會被截斷。

120 

121### 停止迴圈

122 

123若要在 `/loop` 等待下一次迭代時停止它,請按 `Esc`。這會清除待處理的喚醒,使迴圈不會再次執行。您透過[直接要求 Claude](#manage-scheduled-tasks) 排程的任務不受 `Esc` 影響,會保留在原位,直到您刪除它們。

124 

125## 設定一次性提醒

126 

127對於一次性提醒,請用自然語言描述您想要的內容,而不是使用 `/loop`。Claude 會排程一個執行後自動刪除的單次執行任務。

128 

129```text theme={null}

130remind me at 3pm to push the release branch

131```

132 

133```text theme={null}

134in 45 minutes, check whether the integration tests passed

135```

136 

137Claude 會使用 cron 表達式將執行時間固定到特定的分鐘和小時,並確認何時執行。

138 

139## 管理排程任務

140 

141用自然語言要求 Claude 列出或取消任務,或直接參考基礎工具。

142 

143```text theme={null}

144what scheduled tasks do I have?

145```

146 

147```text theme={null}

148cancel the deploy check job

149```

150 

151在幕後,Claude 使用這些工具:

152 

153| 工具 | 用途 |

154| :----------- | :----------------------------------------- |

155| `CronCreate` | 排程新任務。接受 5 欄位 cron 表達式、要執行的提示,以及是否重複或執行一次。 |

156| `CronList` | 列出所有排程任務及其 ID、排程和提示。 |

157| `CronDelete` | 按 ID 取消任務。 |

158 

159每個排程任務都有一個 8 字元的 ID,您可以傳遞給 `CronDelete`。一個工作階段最多可以同時保存 50 個排程任務。

160 

161## 排程任務如何執行

162 

163排程器每秒檢查一次到期的任務,並以低優先級將其加入佇列。排程的提示在您的回合之間執行,而不是在 Claude 正在回應時執行。如果 Claude 在任務到期時忙碌,提示會等到目前回合結束。

164 

165所有時間都以您的本地時區解釋。cron 表達式(例如 `0 9 * * *`)表示您執行 Claude Code 的任何地方的上午 9 點,而不是 UTC。

166 

167### 抖動

168 

169為了避免每個工作階段在同一牆上時刻點擊 API,排程器會為執行時間添加一個小的確定性偏移:

170 

171* 重複執行的任務最多晚執行其週期的 10%,上限為 15 分鐘。每小時的工作可能在 `:00` 到 `:06` 之間的任何時間執行。

172* 為整點或半點排程的一次性任務最多提前執行 90 秒。

173 

174偏移是從任務 ID 衍生的,所以相同的任務總是獲得相同的偏移。如果精確計時很重要,請選擇不是 `:00` 或 `:30` 的分鐘,例如 `3 9 * * *` 而不是 `0 9 * * *`,一次性抖動將不適用。

175 

176### 七天過期

177 

178重複執行的任務在建立後 7 天自動過期。任務最後執行一次,然後刪除自己。這限制了被遺忘的迴圈可以執行多長時間。如果您需要重複執行的任務持續更長時間,請在過期前取消並重新建立它,或使用 [Routines](/zh-TW/routines) 或 [Desktop 排程任務](/zh-TW/desktop-scheduled-tasks) 進行持久排程。

179 

180## Cron 表達式參考

181 

182`CronCreate` 接受標準 5 欄位 cron 表達式:`minute hour day-of-month month day-of-week`。所有欄位都支援萬用字元 (`*`)、單一值 (`5`)、步驟 (`*/15`)、範圍 (`1-5`) 和逗號分隔的清單 (`1,15,30`)。

183 

184| 範例 | 含義 |

185| :------------- | :-------------------- |

186| `*/5 * * * *` | 每 5 分鐘 |

187| `0 * * * *` | 每小時整點 |

188| `7 * * * *` | 每小時的第 7 分鐘 |

189| `0 9 * * *` | 每天上午 9 點(本地時間) |

190| `0 9 * * 1-5` | 工作日上午 9 點(本地時間) |

191| `30 14 15 3 *` | 3 月 15 日下午 2:30(本地時間) |

192 

193星期幾使用 `0` 或 `7` 表示星期日,`6` 表示星期六。不支援擴展語法,例如 `L`、`W`、`?` 和名稱別名,例如 `MON` 或 `JAN`。

194 

195當月份日期和星期幾都受到限制時,如果任一欄位匹配,日期就匹配。這遵循標準 vixie-cron 語義。

196 

197## 停用排程任務

198 

199在您的環境中設定 `CLAUDE_CODE_DISABLE_CRON=1` 以完全停用排程器。cron 工具和 `/loop` 變得不可用,任何已排程的任務都停止執行。請參閱 [環境變數](/zh-TW/env-vars) 以取得完整的停用標誌清單。

200 

201## 限制

202 

203工作階段範圍的排程有固有的限制:

204 

205* 任務只在 Claude Code 執行且閒置時執行。關閉終端或讓工作階段退出會停止它們執行。

206* 沒有錯過執行的追趕。如果任務的排程時間在 Claude 忙於長時間執行的請求時經過,它會在 Claude 變為閒置時執行一次,而不是每個錯過的間隔執行一次。

207* 啟動新的對話會清除所有工作階段範圍的任務。使用 `claude --resume` 或 `claude --continue` 繼續會恢復尚未過期的任務:建立後七天內的重複執行任務,以及排程時間尚未到達的一次性任務。背景 Bash 和監視任務在繼續時永遠不會被恢復。

208 

209對於需要無人值守執行的 cron 驅動自動化:

210 

211* [Routines](/zh-TW/routines):在 Anthropic 管理的基礎設施上按排程執行、透過 API 呼叫或在 GitHub 事件上執行

212* [GitHub Actions](/zh-TW/github-actions):在 CI 中使用 `schedule` 觸發器

213* [Desktop 排程任務](/zh-TW/desktop-scheduled-tasks):在您的機器上本地執行

security.md +141 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 安全性

6 

7> 了解 Claude Code 的安全防護措施和安全使用的最佳實踐。

8 

9## 我們如何處理安全性

10 

11### 安全基礎

12 

13您的程式碼安全至關重要。Claude Code 以安全為核心進行構建,按照 Anthropic 的全面安全計畫開發。在 [Anthropic Trust Center](https://trust.anthropic.com) 了解更多資訊並存取資源(SOC 2 Type 2 報告、ISO 27001 證書等)。

14 

15### 基於權限的架構

16 

17Claude Code 預設使用嚴格的唯讀權限。當需要額外操作時(編輯檔案、執行測試、執行命令),Claude Code 會請求明確的權限。使用者可以控制是否批准一次性操作或自動允許操作。

18 

19我們設計 Claude Code 以實現透明和安全。例如,我們要求在執行 bash 命令前進行批准,讓您擁有直接控制權。這種方法使使用者和組織能夠直接配置權限。

20 

21有關詳細的權限配置,請參閱 [Permissions](/zh-TW/permissions)。

22 

23### 內建保護

24 

25為了降低代理系統中的風險:

26 

27* **沙箱化 bash 工具**:[Sandbox](/zh-TW/sandboxing) bash 命令具有檔案系統和網路隔離,減少權限提示同時保持安全性。使用 `/sandbox` 啟用以定義 Claude Code 可以自主工作的邊界

28* **寫入存取限制**:Claude Code 只能寫入啟動它的資料夾及其子資料夾——它無法在沒有明確權限的情況下修改父目錄中的檔案。雖然 Claude Code 可以讀取工作目錄外的檔案(對於存取系統庫和依賴項很有用),但寫入操作嚴格限制在專案範圍內,建立了清晰的安全邊界

29* **提示疲勞緩解**:支援按使用者、按程式碼庫或按組織允許列表常用的安全命令

30* **Accept Edits 模式**:批量接受多個編輯,同時為具有副作用的命令保持權限提示

31 

32### 使用者責任

33 

34Claude Code 只擁有您授予它的權限。您負責在批准前審查建議的程式碼和命令的安全性。

35 

36## 防止提示注入

37 

38提示注入是一種技術,攻擊者試圖通過插入惡意文本來覆蓋或操縱 AI 助手的指令。Claude Code 包括針對這些攻擊的多項防護措施:

39 

40### 核心保護

41 

42* **權限系統**:敏感操作需要明確批准

43* **上下文感知分析**:通過分析完整請求來檢測潛在有害的指令

44* **輸入淨化**:通過處理使用者輸入來防止命令注入

45* **命令黑名單**:預設阻止從網路獲取任意內容的風險命令,如 `curl` 和 `wget`。明確允許時,請注意 [permission pattern limitations](/zh-TW/permissions#tool-specific-permission-rules)

46 

47### 隱私保護

48 

49我們實施了多項保護措施來保護您的資料,包括:

50 

51* 敏感資訊的有限保留期(請參閱 [Privacy Center](https://privacy.anthropic.com/en/articles/10023548-how-long-do-you-store-my-data) 了解更多)

52* 對使用者會話資料的受限存取

53* 使用者對資料訓練偏好的控制。消費者使用者可以隨時更改其 [privacy settings](https://claude.ai/settings/privacy)。

54 

55有關完整詳情,請查閱我們的 [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms)(適用於 Team、Enterprise 和 API 使用者)或 [Consumer Terms](https://www.anthropic.com/legal/consumer-terms)(適用於 Free、Pro 和 Max 使用者)以及 [Privacy Policy](https://www.anthropic.com/legal/privacy)。

56 

57### 額外保護措施

58 

59* **網路請求批准**:進行網路請求的工具預設需要使用者批准

60* **隔離的上下文視窗**:Web fetch 使用單獨的上下文視窗以避免注入潛在的惡意提示

61* **信任驗證**:首次程式碼庫執行和新的 MCP servers 需要信任驗證

62 * 注意:使用 `-p` 標誌以非互動方式執行時,信任驗證被禁用

63* **命令注入檢測**:即使之前已允許列表,可疑的 bash 命令也需要手動批准

64* **故障關閉匹配**:不匹配的命令預設需要手動批准

65* **自然語言描述**:複雜的 bash 命令包括使用者理解的說明

66* **安全的認證儲存**:API 金鑰和令牌已加密。請參閱 [Credential Management](/zh-TW/authentication#credential-management)

67 

68<Warning>

69 **Windows WebDAV 安全風險**:在 Windows 上執行 Claude Code 時,我們建議不要啟用 WebDAV 或允許 Claude Code 存取可能包含 WebDAV 子目錄的路徑,如 `\\*`。[WebDAV 已被 Microsoft 棄用](https://learn.microsoft.com/en-us/windows/whats-new/deprecated-features#:~:text=The%20Webclient%20\(WebDAV\)%20service%20is%20deprecated),原因是安全風險。啟用 WebDAV 可能允許 Claude Code 觸發對遠端主機的網路請求,繞過權限系統。

70</Warning>

71 

72**使用不受信任內容的最佳實踐**:

73 

741. 在批准前審查建議的命令

752. 避免直接將不受信任的內容傳送給 Claude

763. 驗證對關鍵檔案的建議更改

774. 使用虛擬機器 (VM) 執行指令碼和進行工具呼叫,特別是在與外部網路服務互動時

785. 使用 `/feedback` 報告可疑行為

79 

80<Warning>

81 雖然這些保護措施大大降低了風險,但沒有任何系統完全免疫所有攻擊。在使用任何 AI 工具時,始終保持良好的安全實踐。

82</Warning>

83 

84## MCP 安全性

85 

86Claude Code 允許使用者配置 Model Context Protocol (MCP) servers。允許的 MCP servers 列表在您的原始程式碼中配置,作為 Claude Code 設定的一部分,工程師將其簽入原始碼控制。

87 

88我們鼓勵編寫您自己的 MCP servers 或使用來自您信任的提供者的 MCP servers。您能夠為 MCP servers 配置 Claude Code 權限。Anthropic 不管理或審計任何 MCP servers。

89 

90## IDE 安全性

91 

92有關在 IDE 中執行 Claude Code 的更多資訊,請參閱 [VS Code security and privacy](/zh-TW/vs-code#security-and-privacy)。

93 

94## 雲端執行安全性

95 

96使用 [Claude Code on the web](/zh-TW/claude-code-on-the-web) 時,會實施額外的安全控制:

97 

98* **隔離的虛擬機器**:每個雲端會話在隔離的、由 Anthropic 管理的 VM 中執行

99* **網路存取控制**:網路存取預設受限,可以配置為禁用或僅允許特定網域

100* **認證保護**:身份驗證通過安全代理進行處理,該代理在沙箱內使用範圍限定的認證,然後轉換為您的實際 GitHub 身份驗證令牌

101* **分支限制**:Git push 操作限制在目前工作分支

102* **審計日誌**:雲端環境中的所有操作都被記錄以用於合規和審計目的

103* **自動清理**:會話完成後,雲端環境會自動終止

104 

105有關雲端執行的更多詳情,請參閱 [Claude Code on the web](/zh-TW/claude-code-on-the-web)。

106 

107[Remote Control](/zh-TW/remote-control) 會話的工作方式不同:網路介面連接到在您本地機器上執行的 Claude Code 程序。所有程式碼執行和檔案存取保持本地,任何本地 Claude Code 會話期間流動的相同資料通過 TLS 上的 Anthropic API 傳輸。不涉及雲端 VM 或沙箱化。連接使用多個短期、範圍狹窄的認證,每個認證限制於特定目的並獨立過期,以限制任何單一洩露認證的影響範圍。

108 

109## 安全最佳實踐

110 

111### 使用敏感程式碼

112 

113* 在批准前審查所有建議的更改

114* 為敏感儲存庫使用專案特定的權限設定

115* 考慮使用 [dev containers](/zh-TW/devcontainer) 以獲得額外隔離

116* 使用 `/permissions` 定期審計您的權限設定

117 

118### 團隊安全性

119 

120* 使用 [managed settings](/zh-TW/settings#settings-files) 強制執行組織標準

121* 通過版本控制共享已批准的權限配置

122* 培訓團隊成員了解安全最佳實踐

123* 通過 [OpenTelemetry metrics](/zh-TW/monitoring-usage) 監控 Claude Code 使用情況

124* 使用 [`ConfigChange` hooks](/zh-TW/hooks#configchange) 審計或阻止會話期間的設定更改

125 

126### 報告安全問題

127 

128如果您在 Claude Code 中發現安全漏洞:

129 

1301. 不要公開披露

1312. 通過我們的 [HackerOne program](https://hackerone.com/4f1f16ba-10d3-4d09-9ecc-c721aad90f24/embedded_submissions/new) 報告

1323. 包括詳細的重現步驟

1334. 在公開披露前留出時間讓我們解決問題

134 

135## 相關資源

136 

137* [Sandboxing](/zh-TW/sandboxing) - bash 命令的檔案系統和網路隔離

138* [Permissions](/zh-TW/permissions) - 配置權限和存取控制

139* [Monitoring usage](/zh-TW/monitoring-usage) - 追蹤和審計 Claude Code 活動

140* [Development containers](/zh-TW/devcontainer) - 安全、隔離的環境

141* [Anthropic Trust Center](https://trust.anthropic.com) - 安全認證和合規性

server-managed-settings.md +224 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 設定伺服器管理的設定

6 

7> 透過伺服器傳遞的設定在 Claude.ai 上為您的組織集中設定 Claude Code,無需裝置管理基礎設施。

8 

9伺服器管理的設定允許管理員透過 Claude.ai 上的網頁介面集中設定 Claude Code。Claude Code 用戶端在使用者使用其組織認證進行身份驗證時會自動接收這些設定。

10 

11此方法適用於沒有裝置管理基礎設施的組織,或需要為非受管裝置上的使用者管理設定的組織。

12 

13<Note>

14 伺服器管理的設定適用於 [Claude for Teams](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=server_settings_teams#team-&-enterprise) 和 [Claude for Enterprise](https://anthropic.com/contact-sales?utm_source=claude_code\&utm_medium=docs\&utm_content=server_settings_enterprise) 客戶。

15</Note>

16 

17## 需求

18 

19若要使用伺服器管理的設定,您需要:

20 

21* Claude for Teams 或 Claude for Enterprise 方案

22* Claude for Teams 的 Claude Code 版本 2.1.38 或更新版本,或 Claude for Enterprise 的版本 2.1.30 或更新版本

23* 對 `api.anthropic.com` 的網路存取

24 

25## 在伺服器管理和端點管理的設定之間選擇

26 

27Claude Code 支援兩種集中設定方法。伺服器管理的設定從 Anthropic 的伺服器傳遞設定。[端點管理的設定](/zh-TW/settings#settings-files) 透過原生作業系統原則 (macOS 受管偏好設定、Windows 登錄) 或受管設定檔直接部署到裝置。

28 

29| 方法 | 最適合 | 安全模型 |

30| :-------------------------------------------- | :--------------------- | :---------------------------- |

31| **伺服器管理的設定** | 沒有 MDM 的組織,或非受管裝置上的使用者 | 在身份驗證時從 Anthropic 伺服器傳遞的設定 |

32| **[端點管理的設定](/zh-TW/settings#settings-files)** | 具有 MDM 或端點管理的組織 | 透過 MDM 設定檔、登錄原則或受管設定檔部署到裝置的設定 |

33 

34如果您的裝置已在 MDM 或端點管理解決方案中註冊,端點管理的設定提供更強的安全保證,因為設定檔可以在作業系統層級受到保護,防止使用者修改。

35 

36## 設定伺服器管理的設定

37 

38<Steps>

39 <Step title="開啟管理員主控台">

40 在 [Claude.ai](https://claude.ai) 中,導覽至 **Admin Settings > Claude Code > Managed settings**。

41 </Step>

42 

43 <Step title="定義您的設定">

44 將您的設定新增為 JSON。支援 [`settings.json` 中提供的所有設定](/zh-TW/settings#available-settings),包括 [hooks](/zh-TW/hooks)、[環境變數](/zh-TW/env-vars) 和[僅限受管的設定](/zh-TW/permissions#managed-only-settings),例如 `allowManagedPermissionRulesOnly`。

45 

46 此範例強制執行權限拒絕清單,防止使用者繞過權限,並將權限規則限制為在受管設定中定義的規則:

47 

48 ```json theme={null}

49 {

50 "permissions": {

51 "deny": [

52 "Bash(curl *)",

53 "Read(./.env)",

54 "Read(./.env.*)",

55 "Read(./secrets/**)"

56 ],

57 "disableBypassPermissionsMode": "disable"

58 },

59 "allowManagedPermissionRulesOnly": true

60 }

61 ```

62 

63 Hooks 使用與 `settings.json` 中相同的格式。

64 

65 此範例在整個組織中的每次檔案編輯後執行稽核指令碼:

66 

67 ```json theme={null}

68 {

69 "hooks": {

70 "PostToolUse": [

71 {

72 "matcher": "Edit|Write",

73 "hooks": [

74 { "type": "command", "command": "/usr/local/bin/audit-edit.sh" }

75 ]

76 }

77 ]

78 }

79 }

80 ```

81 

82 若要設定 [auto mode](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode) 分類器,使其知道您的組織信任哪些儲存庫、儲存桶和網域:

83 

84 ```json theme={null}

85 {

86 "autoMode": {

87 "environment": [

88 "Source control: github.example.com/acme-corp and all repos under it",

89 "Trusted cloud buckets: s3://acme-build-artifacts, gs://acme-ml-datasets",

90 "Trusted internal domains: *.corp.example.com"

91 ]

92 }

93 }

94 ```

95 

96 因為 hooks 執行 shell 命令,使用者在套用前會看到[安全核准對話方塊](#security-approval-dialogs)。請參閱[設定 auto mode](/zh-TW/auto-mode-config),了解 `autoMode` 項目如何影響分類器阻止的內容,以及關於 `allow` 和 `soft_deny` 欄位的重要警告。

97 </Step>

98 

99 <Step title="儲存並部署">

100 儲存您的變更。Claude Code 用戶端在下次啟動或每小時輪詢週期時會接收更新的設定。

101 </Step>

102</Steps>

103 

104### 驗證設定傳遞

105 

106若要確認設定正在套用,請要求使用者重新啟動 Claude Code。如果設定包含觸發[安全核准對話方塊](#security-approval-dialogs)的設定,使用者會在啟動時看到描述受管設定的提示。您也可以透過讓使用者執行 `/permissions` 來檢視其有效的權限規則,以驗證受管權限規則是否處於作用中。

107 

108### 存取控制

109 

110以下角色可以管理伺服器管理的設定:

111 

112* **主要擁有者**

113* **擁有者**

114 

115限制對受信任人員的存取,因為設定變更會套用到組織中的所有使用者。

116 

117### 僅限受管的設定

118 

119大多數[設定金鑰](/zh-TW/settings#available-settings)可在任何範圍中運作。少數金鑰只能從受管設定中讀取,在放置於使用者或專案設定檔中時無效。請參閱[僅限受管的設定](/zh-TW/permissions#managed-only-settings)以取得完整清單。任何不在該清單上的設定仍然可以放置在受管設定中,並具有最高優先順序。

120 

121### 目前的限制

122 

123伺服器管理的設定有以下限制:

124 

125* 設定統一套用到組織中的所有使用者。尚不支援每個群組的設定。

126* [MCP 伺服器設定](/zh-TW/mcp#managed-mcp-configuration) 無法透過伺服器管理的設定分發。

127 

128## 設定傳遞

129 

130### 設定優先順序

131 

132伺服器管理的設定和[端點管理的設定](/zh-TW/settings#settings-files)都佔據 Claude Code [設定階層](/zh-TW/settings#settings-precedence)中的最高層級。沒有其他設定層級可以覆蓋它們,包括命令列引數。

133 

134在受管層級內,第一個傳遞非空設定的來源會獲勝。伺服器管理的設定會先檢查,然後是端點管理的設定。來源不會合併:如果伺服器管理的設定傳遞任何金鑰,端點管理的設定會被完全忽略。如果伺服器管理的設定不傳遞任何內容,端點管理的設定會套用。

135 

136如果您在管理員主控台中清除伺服器管理的設定,意圖回退到端點管理的 plist 或登錄原則,請注意[快取的設定](#fetch-and-caching-behavior)會在用戶端機器上持續存在,直到下次成功擷取。執行 `/status` 以查看哪個受管來源處於作用中。

137 

138### 擷取和快取行為

139 

140Claude Code 在啟動時從 Anthropic 的伺服器擷取設定,並在作用中的工作階段期間每小時輪詢一次更新。

141 

142**首次啟動而無快取設定:**

143 

144* Claude Code 非同步擷取設定

145* 如果擷取失敗,Claude Code 會在沒有受管設定的情況下繼續

146* 在設定載入之前有一個簡短的視窗,其中限制尚未強制執行

147 

148**後續啟動並有快取設定:**

149 

150* 快取設定在啟動時立即套用

151* Claude Code 在背景擷取新鮮設定

152* 快取設定透過網路故障持續存在

153 

154Claude Code 自動套用設定更新而無需重新啟動,除了進階設定(例如 OpenTelemetry 設定)需要完整重新啟動才能生效。

155 

156### 強制執行失敗關閉啟動

157 

158根據預設,如果遠端設定擷取在啟動時失敗,CLI 會在沒有受管設定的情況下繼續。對於這個簡短的未強制執行視窗無法接受的環境,請在您的受管設定中設定 `forceRemoteSettingsRefresh: true`。

159 

160當此設定處於作用中時,CLI 會在啟動時阻止,直到遠端設定被新鮮擷取。如果擷取失敗,CLI 會結束而不是在沒有原則的情況下繼續。此設定會自我延續:一旦從伺服器傳遞,它也會在本機快取,以便後續啟動即使在新工作階段的第一次成功擷取之前也會強制執行相同的行為。

161 

162若要啟用此功能,請將金鑰新增到您的受管設定設定:

163 

164```json theme={null}

165{

166 "forceRemoteSettingsRefresh": true

167}

168```

169 

170在啟用此設定之前,請確保您的網路原則允許連線到 `api.anthropic.com`。如果該端點無法到達,CLI 會在啟動時結束,使用者無法啟動 Claude Code。

171 

172### 安全核准對話方塊

173 

174某些可能造成安全風險的設定需要明確的使用者核准才能套用:

175 

176* **Shell 命令設定**:執行 shell 命令的設定

177* **自訂環境變數**:不在已知安全允許清單中的變數

178* **Hook 設定**:任何 hook 定義

179 

180當這些設定存在時,使用者會看到安全對話方塊,說明正在設定的內容。使用者必須核准才能繼續。如果使用者拒絕設定,Claude Code 會結束。

181 

182<Note>

183 在使用 `-p` 旗標的非互動模式中,Claude Code 會略過安全對話方塊並在沒有使用者核准的情況下套用設定。

184</Note>

185 

186## 平台可用性

187 

188伺服器管理的設定需要直接連線到 `api.anthropic.com`,在使用第三方模型提供者時無法使用:

189 

190* Amazon Bedrock

191* Google Vertex AI

192* Microsoft Foundry

193* 透過 `ANTHROPIC_BASE_URL` 或 [LLM 閘道](/zh-TW/llm-gateway) 的自訂 API 端點

194 

195## 稽核記錄

196 

197設定變更的稽核記錄事件可透過合規性 API 或稽核記錄匯出取得。請聯絡您的 Anthropic 帳戶團隊以取得存取權。

198 

199稽核事件包括執行的動作類型、執行動作的帳戶和裝置,以及對先前和新值的參考。

200 

201## 安全考量

202 

203伺服器管理的設定提供集中式原則強制執行,但它們作為用戶端控制運作。在非受管裝置上,具有管理員或 sudo 存取權的使用者可以修改 Claude Code 二進位檔、檔案系統或網路設定。

204 

205| 情況 | 行為 |

206| :-------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------- |

207| 使用者編輯快取的設定檔 | 篡改的檔案在啟動時套用,但正確的設定會在下次伺服器擷取時還原 |

208| 使用者刪除快取的設定檔 | 首次啟動行為發生:設定非同步擷取,有一個簡短的未強制執行視窗 |

209| API 無法使用 | 如果可用,快取設定會套用,否則受管設定在下次成功擷取之前不會強制執行。使用 `forceRemoteSettingsRefresh: true` 時,CLI 會結束而不是繼續 |

210| 使用者使用不同的組織進行身份驗證 | 不會為受管組織外的帳戶傳遞設定 |

211| 使用者設定[第三方模型提供者](#platform-availability) | 伺服器管理的設定會被略過。這包括設定 `CLAUDE_CODE_USE_BEDROCK`、`CLAUDE_CODE_USE_MANTLE`、`CLAUDE_CODE_USE_VERTEX`、`CLAUDE_CODE_USE_FOUNDRY` 或非預設的 `ANTHROPIC_BASE_URL` |

212 

213若要偵測執行時期設定變更,請使用 [`ConfigChange` hooks](/zh-TW/hooks#configchange) 來記錄修改或在未授權的變更生效前阻止它們。

214 

215如需更強的強制執行保證,請在已在 MDM 解決方案中註冊的裝置上使用[端點管理的設定](/zh-TW/settings#settings-files)。

216 

217## 另請參閱

218 

219用於管理 Claude Code 設定的相關頁面:

220 

221* [Settings](/zh-TW/settings):完整的設定參考,包括所有可用的設定

222* [Endpoint-managed settings](/zh-TW/settings#settings-files):由 IT 部門部署到裝置的受管設定

223* [Authentication](/zh-TW/authentication):設定使用者對 Claude Code 的存取

224* [Security](/zh-TW/security):安全保護措施和最佳實踐

settings.md +914 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Claude Code 設定

6 

7> 使用全域和專案層級設定以及環境變數來設定 Claude Code。

8 

9Claude Code 提供多種設定選項,可根據您的需求配置其行為。您可以在使用互動式 REPL 時執行 `/config` 命令來設定 Claude Code,這會開啟一個標籤式設定介面,您可以在其中查看狀態資訊並修改設定選項。

10 

11## 設定範圍

12 

13Claude Code 使用**範圍系統**來決定設定的適用位置和共享對象。了解範圍可幫助您決定如何為個人使用、團隊協作或企業部署設定 Claude Code。

14 

15### 可用的範圍

16 

17| 範圍 | 位置 | 影響對象 | 與團隊共享? |

18| :---------- | :----------------------------------------------- | :--------- | :------------ |

19| **Managed** | 伺服器管理的設定、plist / 登錄或系統層級 `managed-settings.json` | 機器上的所有使用者 | 是(由 IT 部署) |

20| **User** | `~/.claude/` 目錄 | 您,跨所有專案 | 否 |

21| **Project** | 儲存庫中的 `.claude/` | 此儲存庫的所有協作者 | 是(提交到 git) |

22| **Local** | `.claude/settings.local.json` | 您,僅在此儲存庫中 | 否(gitignored) |

23 

24### 何時使用各個範圍

25 

26**Managed 範圍**用於:

27 

28* 必須在整個組織範圍內強制執行的安全政策

29* 無法覆蓋的合規要求

30* 由 IT/DevOps 部署的標準化設定

31 

32**User 範圍**最適合:

33 

34* 您想在任何地方使用的個人偏好設定(主題、編輯器設定)

35* 您在所有專案中使用的工具和 plugins

36* API 金鑰和身份驗證(安全儲存)

37 

38**Project 範圍**最適合:

39 

40* 團隊共享的設定(權限、hooks、MCP servers)

41* 整個團隊應該擁有的 plugins

42* 跨協作者標準化工具

43 

44**Local 範圍**最適合:

45 

46* 特定專案的個人覆蓋

47* 在與團隊共享之前測試設定

48* 對其他人不適用的機器特定設定

49 

50### 範圍如何互動

51 

52當相同的設定在多個範圍中配置時,更具體的範圍優先:

53 

541. **Managed**(最高)- 無法被任何東西覆蓋

552. **命令列引數** - 臨時工作階段覆蓋

563. **Local** - 覆蓋專案和使用者設定

574. **Project** - 覆蓋使用者設定

585. **User**(最低)- 當沒有其他東西指定設定時適用

59 

60例如,如果使用者設定中允許某個權限,但專案設定中拒絕該權限,則專案設定優先,該權限被阻止。

61 

62### 哪些功能使用範圍

63 

64範圍適用於許多 Claude Code 功能:

65 

66| 功能 | 使用者位置 | 專案位置 | 本機位置 |

67| :-------------- | :------------------------ | :-------------------------------- | :---------------------------- |

68| **Settings** | `~/.claude/settings.json` | `.claude/settings.json` | `.claude/settings.local.json` |

69| **Subagents** | `~/.claude/agents/` | `.claude/agents/` | 無 |

70| **MCP servers** | `~/.claude.json` | `.mcp.json` | `~/.claude.json`(每個專案) |

71| **Plugins** | `~/.claude/settings.json` | `.claude/settings.json` | `.claude/settings.local.json` |

72| **CLAUDE.md** | `~/.claude/CLAUDE.md` | `CLAUDE.md` 或 `.claude/CLAUDE.md` | `CLAUDE.local.md` |

73 

74***

75 

76## 設定檔案

77 

78`settings.json` 檔案是透過分層設定來設定 Claude Code 的官方機制:

79 

80* **使用者設定**在 `~/.claude/settings.json` 中定義,適用於所有專案。

81* **專案設定**儲存在您的專案目錄中:

82 * `.claude/settings.json` 用於簽入原始碼控制並與您的團隊共享的設定

83 * `.claude/settings.local.json` 用於未簽入的設定,適用於個人偏好和實驗。Claude Code 將在建立時設定 git 以忽略 `.claude/settings.local.json`。

84* **Managed 設定**:對於需要集中控制的組織,Claude Code 支援多種 managed 設定的傳遞機制。所有機制都使用相同的 JSON 格式,無法被使用者或專案設定覆蓋:

85 

86 * **伺服器管理的設定**:透過 Claude.ai 管理員主控台從 Anthropic 的伺服器傳遞。請參閱[伺服器管理的設定](/zh-TW/server-managed-settings)。

87 * **MDM/OS 層級政策**:透過 macOS 和 Windows 上的原生裝置管理傳遞:

88 * macOS:`com.anthropic.claudecode` managed preferences 網域。plist 的頂層金鑰鏡像 `managed-settings.json`,巢狀設定為字典,陣列為 plist 陣列。透過 Jamf、Iru (Kandji) 或類似 MDM 工具中的設定檔案部署。

89 * Windows:`HKLM\SOFTWARE\Policies\ClaudeCode` 登錄機碼,其中包含 `Settings` 值(REG\_SZ 或 REG\_EXPAND\_SZ)包含 JSON(透過群組原則或 Intune 部署)

90 * Windows(使用者層級):`HKCU\SOFTWARE\Policies\ClaudeCode`(最低政策優先順序,僅在沒有管理員層級來源時使用)

91 * **檔案型**:`managed-settings.json` 和 `managed-mcp.json` 部署到系統目錄:

92 

93 * macOS:`/Library/Application Support/ClaudeCode/`

94 * Linux 和 WSL:`/etc/claude-code/`

95 * Windows:`C:\Program Files\ClaudeCode\`

96 

97 <Warning>

98 自 v2.1.75 起,舊版 Windows 路徑 `C:\ProgramData\ClaudeCode\managed-settings.json` 不再受支援。已將設定部署到該位置的管理員必須將檔案遷移到 `C:\Program Files\ClaudeCode\managed-settings.json`。

99 </Warning>

100 

101 檔案型 managed 設定也支援在與 `managed-settings.json` 相同的系統目錄中的 `managed-settings.d/` 放入目錄。這讓不同的團隊可以部署獨立的政策片段,而無需協調對單一檔案的編輯。

102 

103 遵循 systemd 慣例,`managed-settings.json` 首先作為基礎合併,然後放入目錄中的所有 `*.json` 檔案按字母順序排序並合併在頂部。對於純量值,後面的檔案會覆蓋前面的檔案;陣列會連接並去重;物件會深度合併。以 `.` 開頭的隱藏檔案會被忽略。

104 

105 使用數字前綴來控制合併順序,例如 `10-telemetry.json` 和 `20-security.json`。

106 

107 請參閱 [managed 設定](/zh-TW/permissions#managed-only-settings) 和 [Managed MCP 設定](/zh-TW/mcp#managed-mcp-configuration) 以取得詳細資訊。

108 

109 此[儲存庫](https://github.com/anthropics/claude-code/tree/main/examples/mdm)包含 Jamf、Iru (Kandji)、Intune 和群組原則的入門部署範本。使用這些作為起點,並根據您的需求進行調整。

110 

111 <Note>

112 Managed 部署也可以使用 `strictKnownMarketplaces` 限制 **plugin marketplace 新增**。如需詳細資訊,請參閱 [Managed marketplace 限制](/zh-TW/plugin-marketplaces#managed-marketplace-restrictions)。

113 </Note>

114* **其他設定**儲存在 `~/.claude.json` 中。此檔案包含您的 OAuth 工作階段、[MCP server](/zh-TW/mcp) 設定(用於使用者和本機範圍)、每個專案的狀態(允許的工具、信任設定)和各種快取。專案範圍的 MCP servers 分別儲存在 `.mcp.json` 中。

115 

116<Note>

117 Claude Code 會自動建立設定檔案的時間戳記備份,並保留最近五個備份以防止資料遺失。

118</Note>

119 

120```JSON 設定檔案範例 theme={null}

121{

122 "$schema": "https://json.schemastore.org/claude-code-settings.json",

123 "permissions": {

124 "allow": [

125 "Bash(npm run lint)",

126 "Bash(npm run test *)",

127 "Read(~/.zshrc)"

128 ],

129 "deny": [

130 "Bash(curl *)",

131 "Read(./.env)",

132 "Read(./.env.*)",

133 "Read(./secrets/**)"

134 ]

135 },

136 "env": {

137 "CLAUDE_CODE_ENABLE_TELEMETRY": "1",

138 "OTEL_METRICS_EXPORTER": "otlp"

139 },

140 "companyAnnouncements": [

141 "Welcome to Acme Corp! Review our code guidelines at docs.acme.com",

142 "Reminder: Code reviews required for all PRs",

143 "New security policy in effect"

144 ]

145}

146```

147 

148上面範例中的 `$schema` 行指向 Claude Code 設定的[官方 JSON 架構](https://json.schemastore.org/claude-code-settings.json)。將其新增到您的 `settings.json` 可在 VS Code、Cursor 和任何其他支援 JSON 架構驗證的編輯器中啟用自動完成和內嵌驗證。

149 

150已發佈的架構會定期更新,可能不包含最新 CLI 版本中新增的設定,因此最近記錄的欄位上的驗證警告不一定表示您的設定無效。

151 

152### 可用的設定

153 

154`settings.json` 支援多個選項:

155 

156| 金鑰 | 說明 | 範例 |

157| :-------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------- |

158| `agent` | 將主執行緒作為命名 subagent 執行。應用該 subagent 的系統提示、工具限制和模型。請參閱[明確叫用 subagents](/zh-TW/sub-agents#invoke-subagents-explicitly) | `"code-reviewer"` |

159| `allowedChannelPlugins` | (Managed 設定僅限)可能推送訊息的頻道 plugins 白名單。在設定時替換預設 Anthropic 白名單。未定義 = 回退到預設值,空陣列 = 阻止所有頻道 plugins。需要 `channelsEnabled: true`。請參閱[限制哪些頻道 plugins 可以執行](/zh-TW/channels#restrict-which-channel-plugins-can-run) | `[{ "marketplace": "claude-plugins-official", "plugin": "telegram" }]` |

160| `allowedHttpHookUrls` | HTTP hooks 可能針對的 URL 模式白名單。支援 `*` 作為萬用字元。設定時,具有不匹配 URL 的 hooks 會被阻止。未定義 = 無限制,空陣列 = 阻止所有 HTTP hooks。陣列跨設定來源合併。請參閱 [Hook 設定](#hook-configuration) | `["https://hooks.example.com/*"]` |

161| `allowedMcpServers` | 在 managed-settings.json 中設定時,使用者可以設定的 MCP servers 白名單。未定義 = 無限制,空陣列 = 鎖定。適用於所有範圍。拒絕清單優先。請參閱 [Managed MCP 設定](/zh-TW/mcp#managed-mcp-configuration) | `[{ "serverName": "github" }]` |

162| `allowManagedHooksOnly` | (Managed 設定僅限)僅載入 managed hooks、SDK hooks 和在 managed 設定 `enabledPlugins` 中強制啟用的 plugins 中的 hooks。使用者、專案和所有其他 plugin hooks 被阻止。請參閱 [Hook 設定](#hook-configuration) | `true` |

163| `allowManagedMcpServersOnly` | (Managed 設定僅限)僅尊重 managed 設定中的 `allowedMcpServers`。`deniedMcpServers` 仍從所有來源合併。使用者仍可新增 MCP servers,但僅適用管理員定義的白名單。請參閱 [Managed MCP 設定](/zh-TW/mcp#managed-mcp-configuration) | `true` |

164| `allowManagedPermissionRulesOnly` | (Managed 設定僅限)防止使用者和專案設定定義 `allow`、`ask` 或 `deny` 權限規則。僅適用 managed 設定中的規則。請參閱 [Managed 專用設定](/zh-TW/permissions#managed-only-settings) | `true` |

165| `alwaysThinkingEnabled` | 為所有工作階段預設啟用[擴展思考](/zh-TW/model-config#extended-thinking)。通常透過 `/config` 命令而不是直接編輯來設定 | `true` |

166| `apiKeyHelper` | 自訂指令碼,在 `/bin/sh` 中執行,以產生驗證值。此值將作為 `X-Api-Key` 和 `Authorization: Bearer` 標頭傳送以進行模型請求 | `/bin/generate_temp_api_key.sh` |

167| `attribution` | 自訂 git 提交和拉取請求的歸屬。請參閱[歸屬設定](#attribution-settings) | `{"commit": "🤖 Generated with Claude Code", "pr": ""}` |

168| `autoMemoryDirectory` | [自動記憶](/zh-TW/memory#storage-location)儲存的自訂目錄。接受絕對路徑或 `~/` 前綴的路徑。從政策和使用者設定以及 `--settings` 旗標接受。不從專案或本機設定接受,因為複製的儲存庫可能提供任一檔案以將記憶寫入重定向到敏感位置 | `"~/my-memory-dir"` |

169| `autoMode` | 自訂[自動模式](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode)分類器阻止和允許的內容。包含 `environment`、`allow` 和 `soft_deny` 陣列的散文規則。在陣列中包含字面字串 `"$defaults"` 以在該位置繼承內建規則。請參閱[設定自動模式](/zh-TW/auto-mode-config)。不從共享專案設定讀取 | `{"soft_deny": ["$defaults", "Never run terraform apply"]}` |

170| `autoScrollEnabled` | 在[全螢幕渲染](/zh-TW/fullscreen)中,跟隨新輸出到對話的底部。預設:`true`。在 `/config` 中顯示為**自動捲軸**。當此設定關閉時,權限提示仍會捲軸進入檢視 | `false` |

171| `autoUpdatesChannel` | 遵循更新的發行頻道。使用 `"stable"` 以取得通常約一週舊的版本並跳過有重大迴歸的版本,或 `"latest"`(預設)以取得最新版本 | `"stable"` |

172| `availableModels` | 限制使用者可透過 `/model`、`--model` 或 `ANTHROPIC_MODEL` 選擇的模型。不影響預設選項。請參閱[限制模型選擇](/zh-TW/model-config#restrict-model-selection) | `["sonnet", "haiku"]` |

173| `awaySummaryEnabled` | 在您離開終端機幾分鐘後返回時顯示單行工作階段摘要。設定為 `false` 或在 `/config` 中關閉工作階段摘要以停用。與 [`CLAUDE_CODE_ENABLE_AWAY_SUMMARY`](/zh-TW/env-vars) 相同 | `true` |

174| `awsAuthRefresh` | 修改 `.aws` 目錄的自訂指令碼(請參閱[進階認證設定](/zh-TW/amazon-bedrock#advanced-credential-configuration)) | `aws sso login --profile myprofile` |

175| `awsCredentialExport` | 輸出包含 AWS 認證的 JSON 的自訂指令碼(請參閱[進階認證設定](/zh-TW/amazon-bedrock#advanced-credential-configuration)) | `/bin/generate_aws_grant.sh` |

176| `blockedMarketplaces` | (Managed 設定僅限)marketplace 來源的黑名單。在下載前檢查被阻止的來源,因此它們永遠不會接觸檔案系統。請參閱 [Managed marketplace 限制](/zh-TW/plugin-marketplaces#managed-marketplace-restrictions) | `[{ "source": "github", "repo": "untrusted/plugins" }]` |

177| `channelsEnabled` | (Managed 設定僅限)允許 Team 和 Enterprise 使用者使用[頻道](/zh-TW/channels)。未設定或 `false` 會阻止頻道訊息傳遞,無論使用者傳遞什麼給 `--channels` | `true` |

178| `cleanupPeriodDays` | 非使用中超過此期間的工作階段在啟動時刪除(預設:30 天,最少 1 天)。設定為 `0` 會被拒絕並出現驗證錯誤。也控制[孤立 subagent worktrees](/zh-TW/worktrees#clean-up-worktrees) 在啟動時自動移除的年齡截止。若要完全停用文字記錄寫入,請設定 [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](/zh-TW/env-vars) 環境變數,或在非互動模式(`-p`)中使用 `--no-session-persistence` 旗標或 `persistSession: false` SDK 選項。 | `20` |

179| `companyAnnouncements` | 在啟動時向使用者顯示的公告。如果提供多個公告,它們將隨機循環。 | `["Welcome to Acme Corp! Review our code guidelines at docs.acme.com"]` |

180| `defaultShell` | 輸入框 `!` 命令的預設 shell。接受 `"bash"`(預設)或 `"powershell"`。設定 `"powershell"` 會在 Windows 上透過 PowerShell 路由互動式 `!` 命令。需要 `CLAUDE_CODE_USE_POWERSHELL_TOOL=1`。請參閱 [PowerShell tool](/zh-TW/tools-reference#powershell-tool) | `"powershell"` |

181| `deniedMcpServers` | 在 managed-settings.json 中設定時,明確阻止的 MCP servers 拒絕清單。適用於所有範圍,包括 managed servers。拒絕清單優先於白名單。請參閱 [Managed MCP 設定](/zh-TW/mcp#managed-mcp-configuration) | `[{ "serverName": "filesystem" }]` |

182| `disableAllHooks` | 停用所有 [hooks](/zh-TW/hooks) 和任何自訂[狀態行](/zh-TW/statusline) | `true` |

183| `disableAutoMode` | 設定為 `"disable"` 以防止[自動模式](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode)被啟用。從 `Shift+Tab` 循環中移除 `auto` 並在啟動時拒絕 `--permission-mode auto`。在[managed 設定](/zh-TW/permissions#managed-settings)中最有用,使用者無法覆蓋它 | `"disable"` |

184| `disableDeepLinkRegistration` | 設定為 `"disable"` 以防止 Claude Code 在啟動時向作業系統註冊 `claude-cli://` 協議處理程式。[深層連結](/zh-TW/deep-links)讓外部工具透過預先填入的提示開啟 Claude Code 工作階段。在協議處理程式註冊受限或單獨管理的環境中很有用 | `"disable"` |

185| `disabledMcpjsonServers` | 要拒絕的 `.mcp.json` 檔案中特定 MCP servers 的清單 | `["filesystem"]` |

186| `disableSkillShellExecution` | 停用 [skills](/zh-TW/skills) 和來自使用者、專案、plugin 或其他目錄來源的自訂命令中的內嵌 shell 執行(`` !`...` `` 和 ` ```! ` 區塊)。命令會被替換為 `[shell command execution disabled by policy]` 而不是被執行。Bundled 和 managed skills 不受影響。在[managed 設定](/zh-TW/permissions#managed-settings)中最有用,使用者無法覆蓋它 | `true` |

187| `editorMode` | 輸入提示的快捷鍵模式:`"normal"` 或 `"vim"`。預設:`"normal"`。在 `/config` 中顯示為**編輯器模式** | `"vim"` |

188| `effortLevel` | 跨工作階段持久化[努力等級](/zh-TW/model-config#adjust-effort-level)。接受 `"low"`、`"medium"`、`"high"` 或 `"xhigh"`。當您執行 `/effort` 時自動寫入,其中包含其中一個值。請參閱[調整努力等級](/zh-TW/model-config#adjust-effort-level)以了解支援的模型 | `"xhigh"` |

189| `enableAllProjectMcpServers` | 自動批准專案 `.mcp.json` 檔案中定義的所有 MCP servers | `true` |

190| `enabledMcpjsonServers` | 要批准的 `.mcp.json` 檔案中特定 MCP servers 的清單 | `["memory", "github"]` |

191| `env` | 將應用於每個工作階段的環境變數 | `{"FOO": "bar"}` |

192| `fastModePerSessionOptIn` | 當為 `true` 時,快速模式不會跨工作階段持久化。每個工作階段都以快速模式關閉開始,需要使用者使用 `/fast` 啟用它。使用者的快速模式偏好仍會儲存。請參閱[需要每個工作階段的選擇加入](/zh-TW/fast-mode#require-per-session-opt-in) | `true` |

193| `feedbackSurveyRate` | [工作階段品質調查](/zh-TW/data-usage#session-quality-surveys)出現時符合條件的機率(0–1)。設定為 `0` 以完全抑制。在使用 Bedrock、Vertex 或 Foundry 時很有用,其中預設樣本率不適用 | `0.05` |

194| `fileSuggestion` | 為 `@` 檔案自動完成設定自訂指令碼。請參閱[檔案建議設定](#file-suggestion-settings) | `{"type": "command", "command": "~/.claude/file-suggestion.sh"}` |

195| `forceLoginMethod` | 使用 `claudeai` 限制登入到 Claude.ai 帳戶,`console` 限制登入到 Claude Console(API 使用計費)帳戶 | `claudeai` |

196| `forceLoginOrgUUID` | 要求登入屬於特定組織。接受單一 UUID 字串(也會在登入期間預先選擇該組織),或 UUID 陣列,其中接受任何列出的組織而不預先選擇。在 managed 設定中設定時,如果驗證帳戶不屬於列出的組織,登入會失敗;空陣列會失敗關閉並使用誤設定訊息阻止登入 | `"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"` 或 `["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"]` |

197| `forceRemoteSettingsRefresh` | (Managed 設定僅限)阻止 CLI 啟動,直到從伺服器新鮮擷取遠端 managed 設定。如果擷取失敗,CLI 會結束而不是繼續使用快取或無設定。未設定時,啟動會繼續而不等待遠端設定。請參閱[失敗關閉強制執行](/zh-TW/server-managed-settings#enforce-fail-closed-startup) | `true` |

198| `hooks` | 設定自訂命令以在生命週期事件執行。請參閱 [hooks 文件](/zh-TW/hooks)以了解格式 | 請參閱 [hooks](/zh-TW/hooks) |

199| `httpHookAllowedEnvVars` | HTTP hooks 可能插入到標頭中的環境變數名稱白名單。設定時,每個 hook 的有效 `allowedEnvVars` 是與此清單的交集。未定義 = 無限制。陣列跨設定來源合併。請參閱 [Hook 設定](#hook-configuration) | `["MY_TOKEN", "HOOK_SECRET"]` |

200| `includeCoAuthoredBy` | **已棄用**:改用 `attribution`。是否在 git 提交和拉取請求中包含 `co-authored-by Claude` 署名(預設:`true`) | `false` |

201| `includeGitInstructions` | 在 Claude 的系統提示中包含內建提交和 PR 工作流程指示和 git 狀態快照(預設:`true`)。設定為 `false` 以移除兩者,例如在使用您自己的 git 工作流程 skills 時。`CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` 環境變數在設定時優先於此設定 | `false` |

202| `language` | 設定 Claude 的首選回應語言(例如 `"japanese"`、`"spanish"`、`"french"`)。Claude 預設會以此語言回應。也設定[語音聽寫](/zh-TW/voice-dictation#change-the-dictation-language)語言 | `"japanese"` |

203| `minimumVersion` | 防止背景自動更新和 `claude update` 安裝低於此版本的版本。當從 `"latest"` 頻道切換到 `"stable"` 時透過 `/config` 提示您保持在目前版本或允許降級。選擇保持設定此值。也適用於[managed 設定](/zh-TW/permissions#managed-settings)以釘選組織範圍的最小值 | `"2.1.100"` |

204| `model` | 覆蓋 Claude Code 使用的預設模型 | `"claude-sonnet-4-6"` |

205| `modelOverrides` | 將 Anthropic 模型 ID 對應到提供者特定的模型 ID,例如 Bedrock 推論設定檔 ARN。每個模型選擇器項目在呼叫提供者 API 時使用其對應的值。請參閱[按版本覆蓋模型 ID](/zh-TW/model-config#override-model-ids-per-version) | `{"claude-opus-4-6": "arn:aws:bedrock:..."}` |

206| `otelHeadersHelper` | 產生動態 OpenTelemetry 標頭的指令碼。在啟動時和定期執行(請參閱[動態標頭](/zh-TW/monitoring-usage#dynamic-headers)) | `/bin/generate_otel_headers.sh` |

207| `outputStyle` | 設定輸出樣式以調整系統提示。請參閱[輸出樣式文件](/zh-TW/output-styles) | `"Explanatory"` |

208| `permissions` | 請參閱下表以了解權限的結構。 | |

209| `plansDirectory` | 自訂計畫檔案的儲存位置。路徑相對於專案根目錄。預設:`~/.claude/plans` | `"./plans"` |

210| `pluginTrustMessage` | (Managed 設定僅限)在安裝前顯示的 plugin 信任警告中附加的自訂訊息。使用此選項新增組織特定的內容,例如確認來自您內部 marketplace 的 plugins 已經過審查。 | `"All plugins from our marketplace are approved by IT"` |

211| `preferredNotifChannel` | 工作完成和權限提示通知的方法:`"auto"`、`"terminal_bell"`、`"iterm2"`、`"iterm2_with_bell"`、`"kitty"`、`"ghostty"` 或 `"notifications_disabled"`。預設:`"auto"`,在 iTerm2、Ghostty 和 Kitty 中傳送桌面通知,在其他終端機中不執行任何操作。設定 `"terminal_bell"` 以在任何終端機中響鈴字元。在 `/config` 中顯示為**通知**。請參閱[取得終端機鈴聲或通知](/zh-TW/terminal-config#get-a-terminal-bell-or-notification) | `"terminal_bell"` |

212| `prefersReducedMotion` | 減少或停用 UI 動畫(微調器、閃爍、閃光效果)以提高可訪問性 | `true` |

213| `prUrlTemplate` | PR 徽章的 URL 範本,顯示在頁尾和工具結果摘要中。替換 `gh` 報告的 PR URL 中的 `{host}`、`{owner}`、`{repo}`、`{number}` 和 `{url}`。使用以指向內部程式碼審查工具而不是 `github.com`。不影響 Claude 散文中的 `#123` 自動連結 | `"https://reviews.example.com/{owner}/{repo}/pull/{number}"` |

214| `respectGitignore` | 控制 `@` 檔案選擇器是否尊重 `.gitignore` 模式。當為 `true`(預設)時,符合 `.gitignore` 模式的檔案會從建議中排除 | `false` |

215| `showClearContextOnPlanAccept` | 在計畫接受畫面上顯示「清除內容」選項。預設為 `false`。設定為 `true` 以還原選項 | `true` |

216| `showThinkingSummaries` | 在互動式工作階段中顯示[擴展思考](/zh-TW/model-config#extended-thinking)摘要。未設定或 `false`(互動模式中的預設值)時,思考區塊由 API 編輯並顯示為摺疊的存根。編輯只會改變您看到的內容,而不是模型生成的內容:若要減少思考支出,請[降低預算或停用思考](/zh-TW/model-config#extended-thinking)。非互動模式(`-p`)和 SDK 呼叫者無論此設定如何都始終接收摘要 | `true` |

217| `showTurnDuration` | 在回應後顯示輪次持續時間訊息,例如「Cooked for 1m 6s」。預設:`true`。在 `/config` 中顯示為**顯示輪次持續時間** | `false` |

218| `skipWebFetchPreflight` | 跳過[WebFetch 網域安全檢查](/zh-TW/data-usage#webfetch-domain-safety-check),該檢查在擷取前將每個請求的主機名稱傳送到 `api.anthropic.com`。在阻止流量到 Anthropic 的環境中設定為 `true`,例如 Bedrock、Vertex AI 或 Foundry 部署,具有限制性的出站。跳過時,WebFetch 嘗試任何 URL 而不諮詢黑名單 | `true` |

219| `spinnerTipsEnabled` | 在 Claude 工作時在微調器中顯示提示。設定為 `false` 以停用提示(預設:`true`) | `false` |

220| `spinnerTipsOverride` | 使用自訂字串覆蓋微調器提示。`tips`:提示字串陣列。`excludeDefault`:如果為 `true`,僅顯示自訂提示;如果為 `false` 或不存在,自訂提示會與內建提示合併 | `{ "excludeDefault": true, "tips": ["Use our internal tool X"] }` |

221| `spinnerVerbs` | 自訂在微調器和輪次持續時間訊息中顯示的動作動詞。將 `mode` 設定為 `"replace"` 以僅使用您的動詞,或 `"append"` 以將它們新增到預設值 | `{"mode": "append", "verbs": ["Pondering", "Crafting"]}` |

222| `sshConfigs` | 要在[桌面](/zh-TW/desktop#pre-configure-ssh-connections-for-your-team)環境下拉式清單中顯示的 SSH 連線。每個項目需要 `id`、`name` 和 `sshHost`;`sshPort`、`sshIdentityFile` 和 `startDirectory` 是選用的。在 managed 設定中設定時,連線對使用者是唯讀的。僅從 managed 和使用者設定讀取 | `[{"id": "dev-vm", "name": "Dev VM", "sshHost": "user@dev.example.com"}]` |

223| `statusLine` | 設定自訂狀態行以顯示內容。請參閱 [`statusLine` 文件](/zh-TW/statusline) | `{"type": "command", "command": "~/.claude/statusline.sh"}` |

224| `strictKnownMarketplaces` | (Managed 設定僅限)plugin marketplaces 白名單。未定義 = 無限制,空陣列 = 鎖定。在 marketplace 新增和 plugin 安裝、更新、重新整理和自動更新時強制執行,因此在設定政策之前新增的 marketplace 無法用於擷取 plugins。請參閱 [Managed marketplace 限制](/zh-TW/plugin-marketplaces#managed-marketplace-restrictions) | `[{ "source": "github", "repo": "acme-corp/plugins" }]` |

225| `teammateMode` | [agent team](/zh-TW/agent-teams) 隊友的顯示方式:`auto`(在 tmux 或 iTerm2 中選擇分割窗格,否則為進程內)、`in-process` 或 `tmux`。請參閱[選擇顯示模式](/zh-TW/agent-teams#choose-a-display-mode) | `"in-process"` |

226| `terminalProgressBarEnabled` | 在支援的終端機中顯示終端機進度條:ConEmu、Ghostty 1.2.0+ 和 iTerm2 3.6.6+。預設:`true`。在 `/config` 中顯示為**終端機進度條** | `false` |

227| `tui` | 終端機 UI 渲染器。使用 `"fullscreen"` 以取得無閃爍[替代螢幕渲染器](/zh-TW/fullscreen),具有虛擬化捲軸。使用 `"default"` 以取得經典主螢幕渲染器。透過 `/tui` 設定 | `"fullscreen"` |

228| `useAutoModeDuringPlan` | Plan Mode 在自動模式可用時是否使用自動模式語義。預設:`true`。不從共享專案設定讀取。在 `/config` 中顯示為「在計畫期間使用自動模式」 | `false` |

229| `viewMode` | 啟動時的預設文字記錄檢視模式:`"default"`、`"verbose"` 或 `"focus"`。設定時覆蓋粘性 `/focus` 選擇 | `"verbose"` |

230| `voice` | [語音聽寫](/zh-TW/voice-dictation)設定:`enabled` 開啟聽寫,`mode` 選擇 `"hold"` 或 `"tap"`,`autoSubmit` 在保持模式中按鍵釋放時傳送提示。當您執行 `/voice` 時自動寫入。需要 Claude.ai 帳戶 | `{ "enabled": true, "mode": "tap" }` |

231| `voiceEnabled` | `voice.enabled` 的舊版別名。偏好 `voice` 物件 | `true` |

232| `wslInheritsWindowsSettings` | (Windows managed 設定僅限)當為 `true` 時,WSL 上的 Claude Code 除了 `/etc/claude-code` 外還會從 Windows 政策鏈讀取 managed 設定,Windows 來源優先。僅在 HKLM 登錄機碼或 `C:\Program Files\ClaudeCode\managed-settings.json` 中設定時受尊重,兩者都需要 Windows 管理員才能寫入。為了讓 HKCU 政策也在 WSL 上適用,旗標必須另外在 HKCU 本身中設定。對原生 Windows 無效 | `true` |

233 

234### 全域設定設定

235 

236這些設定儲存在 `~/.claude.json` 中,而不是 `settings.json`。將它們新增到 `settings.json` 將觸發架構驗證錯誤。

237 

238<Note>

239 v2.1.119 之前的版本也會在此處儲存 `autoScrollEnabled`、`editorMode`、`showTurnDuration`、`teammateMode` 和 `terminalProgressBarEnabled`,而不是在 `settings.json` 中。

240</Note>

241 

242| 金鑰 | 說明 | 範例 |

243| :------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------ |

244| `autoConnectIde` | 當 Claude Code 從外部終端機啟動時自動連線到執行中的 IDE。預設:`false`。在 VS Code 或 JetBrains 終端機外執行時在 `/config` 中顯示為**自動連線到 IDE(外部終端機)** | `true` |

245| `autoInstallIdeExtension` | 從 VS Code 終端機執行時自動安裝 Claude Code IDE 擴充功能。預設:`true`。在 VS Code 或 JetBrains 終端機內執行時在 `/config` 中顯示為**自動安裝 IDE 擴充功能**。您也可以設定 [`CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL`](/zh-TW/env-vars) 環境變數 | `false` |

246| `externalEditorContext` | 當您使用 `Ctrl+G` 開啟外部編輯器時,將 Claude 的前一個回應作為 `#` 註解內容前置。預設:`false`。在 `/config` 中顯示為**在外部編輯器中顯示最後回應** | `true` |

247 

248### Worktree 設定

249 

250設定 `--worktree` 如何建立和管理 git worktrees。使用這些設定來減少大型 monorepos 中的磁碟使用量和啟動時間。

251 

252| 金鑰 | 說明 | 範例 |

253| :---------------------------- | :---------------------------------------------------------------------------------- | :------------------------------------ |

254| `worktree.symlinkDirectories` | 要從主儲存庫符號連結到每個 worktree 的目錄,以避免在磁碟上複製大型目錄。預設不符號連結任何目錄 | `["node_modules", ".cache"]` |

255| `worktree.sparsePaths` | 要在每個 worktree 中透過 git sparse-checkout(cone 模式)簽出的目錄。僅將列出的路徑寫入磁碟,在大型 monorepos 中速度更快 | `["packages/my-app", "shared/utils"]` |

256 

257若要將 gitignored 檔案(如 `.env`)複製到新的 worktrees,請改用專案根目錄中的 [`.worktreeinclude` 檔案](/zh-TW/worktrees#copy-gitignored-files-into-worktrees),而不是設定。

258 

259### 權限設定

260 

261| 金鑰 | 說明 | 範例 |

262| :---------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------- |

263| `allow` | 允許工具使用的權限規則陣列。請參閱下面的[權限規則語法](#permission-rule-syntax)以了解模式匹配詳細資訊 | `[ "Bash(git diff *)" ]` |

264| `ask` | 要求在工具使用時確認的權限規則陣列。請參閱下面的[權限規則語法](#permission-rule-syntax) | `[ "Bash(git push *)" ]` |

265| `deny` | 拒絕工具使用的權限規則陣列。使用此選項從 Claude Code 存取中排除敏感檔案。請參閱[權限規則語法](#permission-rule-syntax)和 [Bash 權限限制](/zh-TW/permissions#tool-specific-permission-rules) | `[ "WebFetch", "Bash(curl *)", "Read(./.env)", "Read(./secrets/**)" ]` |

266| `additionalDirectories` | Claude 有權存取的其他[工作目錄](/zh-TW/permissions#working-directories)。大多數 `.claude/` 設定[未從這些目錄發現](/zh-TW/permissions#additional-directories-grant-file-access-not-configuration) | `[ "../docs/" ]` |

267| `defaultMode` | 開啟 Claude Code 時的預設[權限模式](/zh-TW/permission-modes)。有效值:`default`、`acceptEdits`、`plan`、`auto`、`dontAsk`、`bypassPermissions`。`--permission-mode` CLI 旗標會覆蓋此設定以進行單一工作階段 | `"acceptEdits"` |

268| `disableBypassPermissionsMode` | 設定為 `"disable"` 以防止啟用 `bypassPermissions` 模式。這會停用 `--dangerously-skip-permissions` 旗標。在[managed 設定](/zh-TW/permissions#managed-settings)中最有用,使用者無法覆蓋它 | `"disable"` |

269| `skipDangerousModePermissionPrompt` | 跳過透過 `--dangerously-skip-permissions` 或 `defaultMode: "bypassPermissions"` 進入 bypass permissions 模式之前顯示的確認提示。在專案設定(`.claude/settings.json`)中設定時被忽略,以防止不受信任的儲存庫自動繞過提示 | `true` |

270 

271### 權限規則語法

272 

273權限規則遵循 `Tool` 或 `Tool(specifier)` 的格式。規則按順序評估:首先是拒絕規則,然後是詢問,最後是允許。第一個匹配的規則獲勝。

274 

275快速範例:

276 

277| 規則 | 效果 |

278| :----------------------------- | :-------------------- |

279| `Bash` | 符合所有 Bash 命令 |

280| `Bash(npm run *)` | 符合以 `npm run` 開頭的命令 |

281| `Read(./.env)` | 符合讀取 `.env` 檔案 |

282| `WebFetch(domain:example.com)` | 符合對 example.com 的擷取請求 |

283 

284如需完整的規則語法參考,包括萬用字元行為、Read、Edit、WebFetch、MCP 和 Agent 規則的工具特定模式,以及 Bash 模式的安全限制,請參閱[權限規則語法](/zh-TW/permissions#permission-rule-syntax)。

285 

286### Sandbox 設定

287 

288設定進階 sandboxing 行為。Sandboxing 將 bash 命令與您的檔案系統和網路隔離。請參閱 [Sandboxing](/zh-TW/sandboxing) 以了解詳細資訊。

289 

290| 金鑰 | 說明 | 範例 |

291| :------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------- |

292| `enabled` | 啟用 bash sandboxing(macOS、Linux 和 WSL2)。預設:false | `true` |

293| `failIfUnavailable` | 如果 `sandbox.enabled` 為 true 但 sandbox 無法啟動(遺失相依性、不支援的平台),則在啟動時以錯誤結束。當為 false(預設)時,會顯示警告,命令會以 unsandboxed 方式執行。適用於需要 sandboxing 作為硬閘門的 managed 設定部署 | `true` |

294| `autoAllowBashIfSandboxed` | 在 sandboxed 時自動批准 bash 命令。預設:true | `true` |

295| `excludedCommands` | 應在 sandbox 外執行的命令 | `["docker *"]` |

296| `allowUnsandboxedCommands` | 允許命令透過 `dangerouslyDisableSandbox` 參數在 sandbox 外執行。當設定為 `false` 時,`dangerouslyDisableSandbox` 逃脫艙口完全停用,所有命令必須 sandboxed(或在 `excludedCommands` 中)。適用於需要嚴格 sandboxing 的企業政策。預設:true | `false` |

297| `filesystem.allowWrite` | sandboxed 命令可以寫入的其他路徑。陣列跨所有設定範圍合併:使用者、專案和 managed 路徑合併,不替換。也與 `Edit(...)` 允許權限規則中的路徑合併。請參閱下面的[路徑前綴](#sandbox-path-prefixes)。 | `["/tmp/build", "~/.kube"]` |

298| `filesystem.denyWrite` | sandboxed 命令無法寫入的路徑。陣列跨所有設定範圍合併。也與 `Edit(...)` 拒絕權限規則中的路徑合併。 | `["/etc", "/usr/local/bin"]` |

299| `filesystem.denyRead` | sandboxed 命令無法讀取的路徑。陣列跨所有設定範圍合併。也與 `Read(...)` 拒絕權限規則中的路徑合併。 | `["~/.aws/credentials"]` |

300| `filesystem.allowRead` | 在 `denyRead` 區域內重新允許讀取的路徑。優先於 `denyRead`。陣列跨所有設定範圍合併。使用此選項建立僅工作區讀取存取模式。 | `["."]` |

301| `filesystem.allowManagedReadPathsOnly` | (Managed 設定僅限)僅尊重 managed 設定中的 `filesystem.allowRead` 路徑。`denyRead` 仍從所有來源合併。預設:false | `true` |

302| `network.allowUnixSockets` | (僅限 macOS)sandbox 中可存取的 Unix socket 路徑。在 Linux 和 WSL2 上被忽略,其中 seccomp 篩選器無法檢查 socket 路徑;改用 `allowAllUnixSockets`。 | `["~/.ssh/agent-socket"]` |

303| `network.allowAllUnixSockets` | 允許 sandbox 中的所有 Unix socket 連線。在 Linux 和 WSL2 上,這是允許 Unix sockets 的唯一方式,因為它跳過了 seccomp 篩選器,否則會阻止 `socket(AF_UNIX, ...)` 呼叫。預設:false | `true` |

304| `network.allowLocalBinding` | 允許繫結到 localhost 連接埠(僅限 macOS)。預設:false | `true` |

305| `network.allowMachLookup` | sandbox 可能查詢的其他 XPC/Mach 服務名稱(僅限 macOS)。支援單一尾部 `*` 用於前綴匹配。iOS 模擬器或 Playwright 等透過 XPC 通訊的工具需要。 | `["com.apple.coresimulator.*"]` |

306| `network.allowedDomains` | 允許出站網路流量的網域陣列。支援萬用字元(例如 `*.example.com`)。 | `["github.com", "*.npmjs.org"]` |

307| `network.deniedDomains` | 允許阻止出站網路流量的網域陣列。支援與 `allowedDomains` 相同的萬用字元語法。當兩者都符合時優先於 `allowedDomains`。無論 `allowManagedDomainsOnly` 如何,都從所有設定來源合併。 | `["sensitive.cloud.example.com"]` |

308| `network.allowManagedDomainsOnly` | (Managed 設定僅限)僅尊重 managed 設定中的 `allowedDomains` 和 `WebFetch(domain:...)` 允許規則。來自使用者、專案和本機設定的網域會被忽略。非允許的網域會自動阻止,不會提示使用者。拒絕的網域仍從所有來源受尊重。預設:false | `true` |

309| `network.httpProxyPort` | 如果您想帶上自己的代理,使用的 HTTP 代理連接埠。如果未指定,Claude 將執行自己的代理。 | `8080` |

310| `network.socksProxyPort` | 如果您想帶上自己的代理,使用的 SOCKS5 代理連接埠。如果未指定,Claude 將執行自己的代理。 | `8081` |

311| `enableWeakerNestedSandbox` | 為無特權 Docker 環境啟用較弱的 sandbox(僅限 Linux 和 WSL2)。**降低安全性。** 預設:false | `true` |

312| `enableWeakerNetworkIsolation` | (僅限 macOS)允許在 sandbox 中存取系統 TLS 信任服務(`com.apple.trustd.agent`)。使用 `httpProxyPort` 和自訂 CA 的 MITM 代理時,Go 型工具(如 `gh`、`gcloud` 和 `terraform`)需要驗證 TLS 憑證。**透過開啟潛在的資料外洩路徑降低安全性**。預設:false | `true` |

313 

314#### Sandbox 路徑前綴

315 

316`filesystem.allowWrite`、`filesystem.denyWrite`、`filesystem.denyRead` 和 `filesystem.allowRead` 中的路徑支援這些前綴:

317 

318| 前綴 | 含義 | 範例 |

319| :-------- | :---------------------------------------- | :---------------------------------------------------------------- |

320| `/` | 從檔案系統根目錄的絕對路徑 | `/tmp/build` 保持 `/tmp/build` |

321| `~/` | 相對於主目錄 | `~/.kube` 變成 `$HOME/.kube` |

322| `./` 或無前綴 | 相對於專案根目錄(用於專案設定)或相對於 `~/.claude`(用於使用者設定) | `./output` 在 `.claude/settings.json` 中解析為 `<project-root>/output` |

323 

324較舊的 `//path` 前綴用於絕對路徑仍然有效。如果您之前使用單斜線 `/path` 期望專案相對解析,請切換到 `./path`。此語法與[讀取和編輯權限規則](/zh-TW/permissions#read-and-edit)不同,後者使用 `//path` 用於絕對和 `/path` 用於專案相對。Sandbox 檔案系統路徑使用標準慣例:`/tmp/build` 是絕對路徑。

325 

326**設定範例:**

327 

328```json theme={null}

329{

330 "sandbox": {

331 "enabled": true,

332 "autoAllowBashIfSandboxed": true,

333 "excludedCommands": ["docker *"],

334 "filesystem": {

335 "allowWrite": ["/tmp/build", "~/.kube"],

336 "denyRead": ["~/.aws/credentials"]

337 },

338 "network": {

339 "allowedDomains": ["github.com", "*.npmjs.org", "registry.yarnpkg.com"],

340 "deniedDomains": ["uploads.github.com"],

341 "allowUnixSockets": [

342 "/var/run/docker.sock"

343 ],

344 "allowLocalBinding": true

345 }

346 }

347}

348```

349 

350**檔案系統和網路限制**可以透過兩種合併在一起的方式設定:

351 

352* **`sandbox.filesystem` 設定**(如上所示):在 OS 層級 sandbox 邊界控制路徑。這些限制適用於所有子流程命令(例如 `kubectl`、`terraform`、`npm`),而不僅僅是 Claude 的檔案工具。

353* **權限規則**:使用 `Edit` 允許/拒絕規則控制 Claude 的檔案工具存取,`Read` 拒絕規則阻止讀取,`WebFetch` 允許/拒絕規則控制網路網域。這些規則中的路徑也會合併到 sandbox 設定中。

354 

355### 歸屬設定

356 

357Claude Code 將歸屬新增到 git 提交和拉取請求。這些分別設定:

358 

359* 提交預設使用 [git trailers](https://git-scm.com/docs/git-interpret-trailers)(如 `Co-Authored-By`),可以自訂或停用

360* 拉取請求說明是純文字

361 

362| 金鑰 | 說明 |

363| :------- | :-------------------------------- |

364| `commit` | git 提交的歸屬,包括任何 trailers。空字串隱藏提交歸屬 |

365| `pr` | 拉取請求說明的歸屬。空字串隱藏拉取請求歸屬 |

366 

367**預設提交歸屬:**

368 

369```text theme={null}

370🤖 Generated with [Claude Code](https://claude.com/claude-code)

371 

372 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

373```

374 

375**預設拉取請求歸屬:**

376 

377```text theme={null}

378🤖 Generated with [Claude Code](https://claude.com/claude-code)

379```

380 

381**範例:**

382 

383```json theme={null}

384{

385 "attribution": {

386 "commit": "Generated with AI\n\nCo-Authored-By: AI <ai@example.com>",

387 "pr": ""

388 }

389}

390```

391 

392<Note>

393 `attribution` 設定優先於已棄用的 `includeCoAuthoredBy` 設定。若要隱藏所有歸屬,請將 `commit` 和 `pr` 設定為空字串。

394</Note>

395 

396### 檔案建議設定

397 

398為 `@` 檔案路徑自動完成設定自訂命令。內建檔案建議使用快速檔案系統遍歷,但大型 monorepos 可能受益於專案特定的索引,例如預先建立的檔案索引或自訂工具。

399 

400```json theme={null}

401{

402 "fileSuggestion": {

403 "type": "command",

404 "command": "~/.claude/file-suggestion.sh"

405 }

406}

407```

408 

409該命令使用與 [hooks](/zh-TW/hooks) 相同的環境變數執行,包括 `CLAUDE_PROJECT_DIR`。它透過 stdin 接收包含 `query` 欄位的 JSON:

410 

411```json theme={null}

412{"query": "src/comp"}

413```

414 

415將換行符分隔的檔案路徑輸出到 stdout(目前限制為 15):

416 

417```text theme={null}

418src/components/Button.tsx

419src/components/Modal.tsx

420src/components/Form.tsx

421```

422 

423**範例:**

424 

425```bash theme={null}

426#!/bin/bash

427query=$(cat | jq -r '.query')

428your-repo-file-index --query "$query" | head -20

429```

430 

431### Hook 設定

432 

433這些設定控制允許執行哪些 hooks 以及 HTTP hooks 可以存取的內容。`allowManagedHooksOnly` 設定只能在 [managed 設定](#settings-files)中設定。URL 和環境變數白名單可以在任何設定層級設定,並跨來源合併。

434 

435**當 `allowManagedHooksOnly` 為 `true` 時的行為:**

436 

437* 載入 Managed hooks 和 SDK hooks

438* 從在 managed 設定 `enabledPlugins` 中強制啟用的 plugins 載入 Hooks。這讓管理員透過組織 marketplace 分發經過審查的 hooks,同時阻止其他所有內容。信任由完整 `plugin@marketplace` ID 授予,因此來自不同 marketplace 的同名 plugin 保持被阻止

439* 使用者 hooks、專案 hooks 和所有其他 plugin hooks 被阻止

440 

441**限制 HTTP hook URL:**

442 

443限制 HTTP hooks 可以針對的 URL。支援 `*` 作為匹配的萬用字元。定義陣列時,針對不匹配 URL 的 HTTP hooks 會被無聲地阻止。

444 

445```json theme={null}

446{

447 "allowedHttpHookUrls": ["https://hooks.example.com/*", "http://localhost:*"]

448}

449```

450 

451**限制 HTTP hook 環境變數:**

452 

453限制 HTTP hooks 可以插入到標頭值中的環境變數名稱。每個 hook 的有效 `allowedEnvVars` 是其自己清單與此設定的交集。

454 

455```json theme={null}

456{

457 "httpHookAllowedEnvVars": ["MY_TOKEN", "HOOK_SECRET"]

458}

459```

460 

461### 設定優先順序

462 

463設定按優先順序順序應用。從最高到最低:

464 

4651. **Managed 設定**([伺服器管理](/zh-TW/server-managed-settings)、[MDM/OS 層級政策](#configuration-scopes)或 [managed 設定](/zh-TW/settings#settings-files))

466 * 由 IT 透過伺服器傳遞、MDM 設定檔案、登錄政策或 managed 設定檔案部署的政策

467 * 無法被任何其他層級覆蓋,包括命令列引數

468 * 在 managed 層級內,優先順序為:伺服器管理 > MDM/OS 層級政策 > 檔案型(`managed-settings.d/*.json` + `managed-settings.json`)> HKCU 登錄(僅限 Windows)。僅使用一個 managed 來源;來源不合併跨層級。在檔案型層級內,放入檔案和基礎檔案會合併在一起。

469 

4702. **命令列引數**

471 * 特定工作階段的臨時覆蓋

472 

4733. **本機專案設定**(`.claude/settings.local.json`)

474 * 個人專案特定設定

475 

4764. **共享專案設定**(`.claude/settings.json`)

477 * 原始碼控制中的團隊共享專案設定

478 

4795. **使用者設定**(`~/.claude/settings.json`)

480 * 個人全域設定

481 

482此階層確保組織政策始終被強制執行,同時仍允許團隊和個人自訂其體驗。無論您從 CLI、[VS Code 擴充功能](/zh-TW/vs-code)或 [JetBrains IDE](/zh-TW/jetbrains) 執行 Claude Code,相同的優先順序都適用。

483 

484例如,如果您的使用者設定允許 `Bash(npm run *)`,但專案的共享設定拒絕它,則專案設定優先,命令被阻止。

485 

486<Note>

487 **陣列設定跨範圍合併。** 當相同的陣列值設定(例如 `sandbox.filesystem.allowWrite` 或 `permissions.allow`)出現在多個範圍中時,陣列會**連接和去重**,而不是替換。這意味著較低優先順序的範圍可以新增項目而不覆蓋由較高優先順序範圍設定的項目,反之亦然。例如,如果 managed 設定將 `allowWrite` 設定為 `["/opt/company-tools"]`,使用者新增 `["~/.kube"]`,則最終設定中包含兩個路徑。

488</Note>

489 

490### 驗證使用中的設定

491 

492在 Claude Code 內執行 `/status` 以查看哪些設定來源處於使用中以及它們來自何處。輸出顯示每個設定層(managed、使用者、專案)及其來源,例如 `Enterprise managed settings (remote)`、`Enterprise managed settings (plist)`、`Enterprise managed settings (HKLM)`、`Enterprise managed settings (HKCU)` 或 `Enterprise managed settings (file)`。如果設定檔案包含錯誤,`/status` 會報告問題,以便您可以修復它。

493 

494### 設定系統的關鍵要點

495 

496* **記憶檔案(`CLAUDE.md`)**:包含 Claude 在啟動時載入的指示和內容

497* **設定檔案(JSON)**:設定權限、環境變數和工具行為

498* **Skills**:可以使用 `/skill-name` 叫用或由 Claude 自動載入的自訂提示

499* **MCP servers**:使用其他工具和整合擴展 Claude Code

500* **優先順序**:較高層級的設定(Managed)覆蓋較低層級的設定(User/Project)

501* **繼承**:設定會合併,更具體的設定新增到或覆蓋更廣泛的設定

502 

503### 系統提示

504 

505Claude Code 的內部系統提示未發佈。若要新增自訂指示,請使用 `CLAUDE.md` 檔案或 `--append-system-prompt` 旗標。

506 

507### 排除敏感檔案

508 

509若要防止 Claude Code 存取包含敏感資訊(如 API 金鑰、機密和環境檔案)的檔案,請在您的 `.claude/settings.json` 檔案中使用 `permissions.deny` 設定:

510 

511```json theme={null}

512{

513 "permissions": {

514 "deny": [

515 "Read(./.env)",

516 "Read(./.env.*)",

517 "Read(./secrets/**)",

518 "Read(./config/credentials.json)",

519 "Read(./build)"

520 ]

521 }

522}

523```

524 

525這取代了已棄用的 `ignorePatterns` 設定。符合這些模式的檔案會從檔案發現和搜尋結果中排除,並拒絕對這些檔案的讀取操作。

526 

527## Subagent 設定

528 

529Claude Code 支援可在使用者和專案層級設定的自訂 AI subagents。這些 subagents 儲存為具有 YAML frontmatter 的 Markdown 檔案:

530 

531* **使用者 subagents**:`~/.claude/agents/` - 在所有專案中可用

532* **專案 subagents**:`.claude/agents/` - 特定於您的專案,可與您的團隊共享

533 

534Subagent 檔案定義具有自訂提示和工具權限的專門 AI 助手。在 [subagents 文件](/zh-TW/sub-agents)中深入了解建立和使用 subagents。

535 

536## Plugin 設定

537 

538Claude Code 支援 plugin 系統,可讓您使用 skills、agents、hooks 和 MCP servers 擴展功能。Plugins 透過 marketplaces 分發,可以在使用者和儲存庫層級設定。

539 

540### Plugin 設定

541 

542`settings.json` 中的 plugin 相關設定:

543 

544```json theme={null}

545{

546 "enabledPlugins": {

547 "formatter@acme-tools": true,

548 "deployer@acme-tools": true,

549 "analyzer@security-plugins": false

550 },

551 "extraKnownMarketplaces": {

552 "acme-tools": {

553 "source": "github",

554 "repo": "acme-corp/claude-plugins"

555 }

556 }

557}

558```

559 

560#### `enabledPlugins`

561 

562控制啟用哪些 plugins。格式:`"plugin-name@marketplace-name": true/false`

563 

564**範圍**:

565 

566* **使用者設定**(`~/.claude/settings.json`):個人 plugin 偏好設定

567* **專案設定**(`.claude/settings.json`):與團隊共享的專案特定 plugins

568* **本機設定**(`.claude/settings.local.json`):每台機器的覆蓋(未提交)

569* **Managed 設定**(`managed-settings.json`):組織範圍的政策覆蓋,在所有範圍阻止安裝並從 marketplace 隱藏 plugin

570 

571**範例**:

572 

573```json theme={null}

574{

575 "enabledPlugins": {

576 "code-formatter@team-tools": true,

577 "deployment-tools@team-tools": true,

578 "experimental-features@personal": false

579 }

580}

581```

582 

583#### `extraKnownMarketplaces`

584 

585定義應為儲存庫提供的其他 marketplaces。通常在儲存庫層級設定中使用,以確保團隊成員有權存取所需的 plugin 來源。

586 

587**當儲存庫包含 `extraKnownMarketplaces` 時**:

588 

5891. 當團隊成員信任資料夾時,系統會提示他們安裝 marketplace

5902. 然後提示團隊成員從該 marketplace 安裝 plugins

5913. 使用者可以跳過不需要的 marketplaces 或 plugins(儲存在使用者設定中)

5924. 安裝尊重信任邊界並需要明確同意

593 

594**範例**:

595 

596```json theme={null}

597{

598 "extraKnownMarketplaces": {

599 "acme-tools": {

600 "source": {

601 "source": "github",

602 "repo": "acme-corp/claude-plugins"

603 }

604 },

605 "security-plugins": {

606 "source": {

607 "source": "git",

608 "url": "https://git.example.com/security/plugins.git"

609 }

610 }

611 }

612}

613```

614 

615**Marketplace 來源類型**:

616 

617* `github`:GitHub 儲存庫(使用 `repo`)

618* `git`:任何 git URL(使用 `url`)

619* `directory`:本機檔案系統路徑(使用 `path`,僅用於開發)

620* `hostPattern`:正規表達式模式以符合 marketplace 主機(使用 `hostPattern`)

621* `settings`:直接在 settings.json 中宣告的內嵌 marketplace,無需單獨的託管儲存庫(使用 `name` 和 `plugins`)

622 

623使用 `source: 'settings'` 宣告一小組 plugins,無需設定託管 marketplace 儲存庫。此處列出的 Plugins 必須參考外部來源,例如 GitHub 或 npm。您仍需要在 `enabledPlugins` 中分別啟用每個 plugin。

624 

625```json theme={null}

626{

627 "extraKnownMarketplaces": {

628 "team-tools": {

629 "source": {

630 "source": "settings",

631 "name": "team-tools",

632 "plugins": [

633 {

634 "name": "code-formatter",

635 "source": {

636 "source": "github",

637 "repo": "acme-corp/code-formatter"

638 }

639 }

640 ]

641 }

642 }

643 }

644}

645```

646 

647#### `strictKnownMarketplaces`

648 

649**Managed 設定僅限**:控制使用者可以新增和安裝 plugins 的 plugin marketplaces。此設定只能在 [managed 設定](/zh-TW/settings#settings-files)中設定,並為管理員提供對 marketplace 來源的嚴格控制。

650 

651**Managed 設定檔案位置**:

652 

653* **macOS**:`/Library/Application Support/ClaudeCode/managed-settings.json`

654* **Linux 和 WSL**:`/etc/claude-code/managed-settings.json`

655* **Windows**:`C:\Program Files\ClaudeCode\managed-settings.json`

656 

657**關鍵特性**:

658 

659* 僅在 managed 設定(`managed-settings.json`)中可用

660* 無法被使用者或專案設定覆蓋(最高優先順序)

661* 在網路/檔案系統操作之前強制執行(被阻止的來源永遠不會執行)

662* 對來源規格使用精確匹配(包括 git 來源的 `ref`、`path`),除了 `hostPattern`,它使用正規表達式匹配

663 

664**白名單行為**:

665 

666* `undefined`(預設):無限制 - 使用者可以新增任何 marketplace

667* 空陣列 `[]`:完全鎖定 - 使用者無法新增任何新 marketplaces

668* 來源清單:使用者只能新增完全符合的 marketplaces

669 

670**所有支援的來源類型**:

671 

672白名單支援多種 marketplace 來源類型。大多數來源使用精確匹配,而 `hostPattern` 使用正規表達式匹配 marketplace 主機。

673 

6741. **GitHub 儲存庫**:

675 

676```json theme={null}

677{ "source": "github", "repo": "acme-corp/approved-plugins" }

678{ "source": "github", "repo": "acme-corp/security-tools", "ref": "v2.0" }

679{ "source": "github", "repo": "acme-corp/plugins", "ref": "main", "path": "marketplace" }

680```

681 

682欄位:`repo`(必需)、`ref`(選用:分支/標籤/SHA)、`path`(選用:子目錄)

683 

6842. **Git 儲存庫**:

685 

686```json theme={null}

687{ "source": "git", "url": "https://gitlab.example.com/tools/plugins.git" }

688{ "source": "git", "url": "https://bitbucket.org/acme-corp/plugins.git", "ref": "production" }

689{ "source": "git", "url": "ssh://git@git.example.com/plugins.git", "ref": "v3.1", "path": "approved" }

690```

691 

692欄位:`url`(必需)、`ref`(選用:分支/標籤/SHA)、`path`(選用:子目錄)

693 

6943. **基於 URL 的 marketplaces**:

695 

696```json theme={null}

697{ "source": "url", "url": "https://plugins.example.com/marketplace.json" }

698{ "source": "url", "url": "https://cdn.example.com/marketplace.json", "headers": { "Authorization": "Bearer ${TOKEN}" } }

699```

700 

701欄位:`url`(必需)、`headers`(選用:用於驗證存取的 HTTP 標頭)

702 

703<Note>

704 基於 URL 的 marketplaces 僅下載 `marketplace.json` 檔案。它們不從伺服器下載 plugin 檔案。基於 URL 的 marketplaces 中的 Plugins 必須使用外部來源(GitHub、npm 或 git URL),而不是相對路徑。對於具有相對路徑的 plugins,請改用基於 Git 的 marketplace。請參閱[疑難排解](/zh-TW/plugin-marketplaces#plugins-with-relative-paths-fail-in-url-based-marketplaces)以了解詳細資訊。

705</Note>

706 

7074. **NPM 套件**:

708 

709```json theme={null}

710{ "source": "npm", "package": "@acme-corp/claude-plugins" }

711{ "source": "npm", "package": "@acme-corp/approved-marketplace" }

712```

713 

714欄位:`package`(必需,支援範圍套件)

715 

7165. **檔案路徑**:

717 

718```json theme={null}

719{ "source": "file", "path": "/usr/local/share/claude/acme-marketplace.json" }

720{ "source": "file", "path": "/opt/acme-corp/plugins/marketplace.json" }

721```

722 

723欄位:`path`(必需:marketplace.json 檔案的絕對路徑)

724 

7256. **目錄路徑**:

726 

727```json theme={null}

728{ "source": "directory", "path": "/usr/local/share/claude/acme-plugins" }

729{ "source": "directory", "path": "/opt/acme-corp/approved-marketplaces" }

730```

731 

732欄位:`path`(必需:包含 `.claude-plugin/marketplace.json` 的目錄的絕對路徑)

733 

7347. **主機模式匹配**:

735 

736```json theme={null}

737{ "source": "hostPattern", "hostPattern": "^github\\.example\\.com$" }

738{ "source": "hostPattern", "hostPattern": "^gitlab\\.internal\\.example\\.com$" }

739```

740 

741欄位:`hostPattern`(必需:用於符合 marketplace 主機的正規表達式模式)

742 

743當您想允許來自特定主機的所有 marketplaces 而不列舉每個儲存庫時,請使用主機模式匹配。這對於具有內部 GitHub Enterprise 或 GitLab 伺服器的組織很有用,開發人員可以在其中建立自己的 marketplaces。

744 

745按來源類型的主機提取:

746 

747* `github`:始終符合 `github.com`

748* `git`:從 URL 提取主機名稱(支援 HTTPS 和 SSH 格式)

749* `url`:從 URL 提取主機名稱

750* `npm`、`file`、`directory`:不支援主機模式匹配

751 

752**設定範例**:

753 

754範例:僅允許特定 marketplaces:

755 

756```json theme={null}

757{

758 "strictKnownMarketplaces": [

759 {

760 "source": "github",

761 "repo": "acme-corp/approved-plugins"

762 },

763 {

764 "source": "github",

765 "repo": "acme-corp/security-tools",

766 "ref": "v2.0"

767 },

768 {

769 "source": "url",

770 "url": "https://plugins.example.com/marketplace.json"

771 },

772 {

773 "source": "npm",

774 "package": "@acme-corp/compliance-plugins"

775 }

776 ]

777}

778```

779 

780範例 - 停用所有 marketplace 新增:

781 

782```json theme={null}

783{

784 "strictKnownMarketplaces": []

785}

786```

787 

788範例:允許來自內部 git 伺服器的所有 marketplaces:

789 

790```json theme={null}

791{

792 "strictKnownMarketplaces": [

793 {

794 "source": "hostPattern",

795 "hostPattern": "^github\\.example\\.com$"

796 }

797 ]

798}

799```

800 

801**精確匹配要求**:

802 

803Marketplace 來源必須**完全符合**才能允許使用者的新增。對於基於 git 的來源(`github` 和 `git`),這包括所有選用欄位:

804 

805* `repo` 或 `url` 必須完全符合

806* `ref` 欄位必須完全符合(或兩者都未定義)

807* `path` 欄位必須完全符合(或兩者都未定義)

808 

809**不符合**的來源範例:

810 

811```json theme={null}

812// 這些是不同的來源:

813{ "source": "github", "repo": "acme-corp/plugins" }

814{ "source": "github", "repo": "acme-corp/plugins", "ref": "main" }

815 

816// 這些也不同:

817{ "source": "github", "repo": "acme-corp/plugins", "path": "marketplace" }

818{ "source": "github", "repo": "acme-corp/plugins" }

819```

820 

821**與 `extraKnownMarketplaces` 的比較**:

822 

823| 方面 | `strictKnownMarketplaces` | `extraKnownMarketplaces` |

824| ---------- | ------------------------- | ------------------------ |

825| **目的** | 組織政策強制執行 | 團隊便利 |

826| **設定檔案** | 僅 `managed-settings.json` | 任何設定檔案 |

827| **行為** | 阻止非白名單新增 | 自動安裝遺失的 marketplaces |

828| **何時強制執行** | 在網路/檔案系統操作之前 | 在使用者信任提示之後 |

829| **可以被覆蓋** | 否(最高優先順序) | 是(由較高優先順序設定) |

830| **來源格式** | 直接來源物件 | 具有巢狀來源的命名 marketplace |

831| **使用案例** | 合規、安全限制 | 上線、標準化 |

832 

833**格式差異**:

834 

835`strictKnownMarketplaces` 使用直接來源物件:

836 

837```json theme={null}

838{

839 "strictKnownMarketplaces": [

840 { "source": "github", "repo": "acme-corp/plugins" }

841 ]

842}

843```

844 

845`extraKnownMarketplaces` 需要命名 marketplaces:

846 

847```json theme={null}

848{

849 "extraKnownMarketplaces": {

850 "acme-tools": {

851 "source": { "source": "github", "repo": "acme-corp/plugins" }

852 }

853 }

854}

855```

856 

857**同時使用兩者**:

858 

859`strictKnownMarketplaces` 是政策閘門:它控制使用者可能新增的內容,但不註冊任何 marketplaces。若要同時限制和為所有使用者預先註冊 marketplace,請在 `managed-settings.json` 中設定兩者:

860 

861```json theme={null}

862{

863 "strictKnownMarketplaces": [

864 { "source": "github", "repo": "acme-corp/plugins" }

865 ],

866 "extraKnownMarketplaces": {

867 "acme-tools": {

868 "source": { "source": "github", "repo": "acme-corp/plugins" }

869 }

870 }

871}

872```

873 

874僅設定 `strictKnownMarketplaces` 時,使用者仍可透過 `/plugin marketplace add` 手動新增允許的 marketplace,但它不會自動提供。

875 

876**重要注意事項**:

877 

878* 限制在任何網路請求或檔案系統操作之前檢查

879* 被阻止時,使用者會看到清晰的錯誤訊息,指示來源被 managed 政策阻止

880* 限制在 marketplace 新增和 plugin 安裝、更新、重新整理和自動更新時強制執行。在設定政策之前新增的 marketplace 一旦其來源不再符合白名單,就無法用於安裝或更新 plugins

881* Managed 設定具有最高優先順序,無法被覆蓋

882 

883請參閱 [Managed marketplace 限制](/zh-TW/plugin-marketplaces#managed-marketplace-restrictions)以了解面向使用者的文件。

884 

885### 管理 plugins

886 

887使用 `/plugin` 命令以互動方式管理 plugins:

888 

889* 瀏覽 marketplaces 中的可用 plugins

890* 安裝/解除安裝 plugins

891* 啟用/停用 plugins

892* 檢視 plugin 詳細資訊(提供的 skills、agents、hooks)

893* 新增/移除 marketplaces

894 

895在 [plugins 文件](/zh-TW/plugins)中深入了解 plugin 系統。

896 

897## 環境變數

898 

899環境變數可讓您控制 Claude Code 行為,而無需編輯設定檔案。任何變數也可以在 [`settings.json`](#available-settings) 中的 `env` 金鑰下設定,以將其應用於每個工作階段或推出到您的團隊。

900 

901請參閱[環境變數參考](/zh-TW/env-vars)以了解完整清單。

902 

903## Claude 可用的工具

904 

905Claude Code 可以存取一組工具,用於讀取、編輯、搜尋、執行命令和協調 subagents。工具名稱是您在權限規則和 hook 匹配器中使用的確切字串。

906 

907請參閱[工具參考](/zh-TW/tools-reference)以了解完整清單和 Bash 工具行為詳細資訊。

908 

909## 另請參閱

910 

911* [Permissions](/zh-TW/permissions):權限系統、規則語法、工具特定模式和 managed 政策

912* [Authentication](/zh-TW/authentication):設定使用者對 Claude Code 的存取

913* [Debug your configuration](/zh-TW/debug-your-config):診斷為什麼設定、hook 或 MCP server 未生效

914* [Troubleshoot installation and login](/zh-TW/troubleshoot-install):安裝、authentication 和平台問題

setup.md +606 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 進階設定

6 

7> Claude Code 的系統需求、平台特定安裝、版本管理和卸載。

8 

9本頁涵蓋系統需求、平台特定安裝詳情、更新和卸載。如需首次會話的引導式逐步說明,請參閱[快速入門](/zh-TW/quickstart)。如果您從未使用過終端機,請參閱[終端機指南](/zh-TW/terminal-guide)。

10 

11## 系統需求

12 

13Claude Code 在以下平台和配置上運行:

14 

15* **作業系統**:

16 * macOS 13.0+

17 * Windows 10 1809+ 或 Windows Server 2019+

18 * Ubuntu 20.04+

19 * Debian 10+

20 * Alpine Linux 3.19+

21* **硬體**:4 GB+ RAM、x64 或 ARM64 處理器

22* **網路**:需要網際網路連線。請參閱[網路配置](/zh-TW/network-config#network-access-requirements)。

23* **Shell**:Bash、Zsh、PowerShell 或 CMD。在原生 Windows 上,建議使用 [Git for Windows](https://git-scm.com/downloads/win);當 Git Bash 不存在時,Claude Code 會回退到 PowerShell。WSL 設定不需要 Git for Windows。

24* **位置**:[Anthropic 支援的國家](https://www.anthropic.com/supported-countries)

25 

26### 其他依賴項

27 

28* **ripgrep**:通常包含在 Claude Code 中。如果搜尋失敗,請參閱[搜尋疑難排解](/zh-TW/troubleshooting#search-and-discovery-issues)。

29 

30## 安裝 Claude Code

31 

32<Tip>

33 偏好圖形介面?[桌面應用程式](/zh-TW/desktop-quickstart)讓您無需終端機即可使用 Claude Code。下載適用於 [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs) 或 [Windows](https://claude.com/download?utm_source=claude_code\&utm_medium=docs) 的版本。

34 

35 初次使用終端機?請參閱[終端機指南](/zh-TW/terminal-guide)以取得逐步說明。

36</Tip>

37 

38To install Claude Code, use one of the following methods:

39 

40<Tabs>

41 <Tab title="Native Install (Recommended)">

42 **macOS, Linux, WSL:**

43 

44 ```bash theme={null}

45 curl -fsSL https://claude.ai/install.sh | bash

46 ```

47 

48 **Windows PowerShell:**

49 

50 ```powershell theme={null}

51 irm https://claude.ai/install.ps1 | iex

52 ```

53 

54 **Windows CMD:**

55 

56 ```batch theme={null}

57 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

58 ```

59 

60 If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you're in CMD, not PowerShell. Your prompt shows `PS C:\` when you're in PowerShell and `C:\` without the `PS` when you're in CMD.

61 

62 [Git for Windows](https://git-scm.com/downloads/win) is recommended on native Windows so Claude Code can use the Bash tool. If Git for Windows is not installed, Claude Code uses PowerShell as the shell tool instead. WSL setups do not need Git for Windows.

63 

64 <Info>

65 Native installations automatically update in the background to keep you on the latest version.

66 </Info>

67 </Tab>

68 

69 <Tab title="Homebrew">

70 ```bash theme={null}

71 brew install --cask claude-code

72 ```

73 

74 Homebrew offers two casks. `claude-code` tracks the stable release channel, which is typically about a week behind and skips releases with major regressions. `claude-code@latest` tracks the latest channel and receives new versions as soon as they ship.

75 

76 <Info>

77 Homebrew installations do not auto-update. Run `brew upgrade claude-code` or `brew upgrade claude-code@latest`, depending on which cask you installed, to get the latest features and security fixes.

78 </Info>

79 </Tab>

80 

81 <Tab title="WinGet">

82 ```powershell theme={null}

83 winget install Anthropic.ClaudeCode

84 ```

85 

86 <Info>

87 WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.

88 </Info>

89 </Tab>

90</Tabs>

91 

92You can also install with [apt, dnf, or apk](/en/setup#install-with-linux-package-managers) on Debian, Fedora, RHEL, and Alpine.

93 

94安裝完成後,在您要使用的專案中開啟終端機並啟動 Claude Code:

95 

96```bash theme={null}

97claude

98```

99 

100如果您在安裝期間遇到任何問題,請參閱[疑難排解安裝和登入](/zh-TW/troubleshoot-install)。

101 

102### 在 Windows 上設定

103 

104您可以在 Windows 上原生執行 Claude Code 或在 WSL 內執行。根據您的專案位置和所需功能進行選擇:

105 

106| 選項 | 需要 | [沙箱](/zh-TW/sandboxing) | 何時使用 |

107| ---------- | -------------------------------------------------------------------------- | ----------------------- | ----------------- |

108| 原生 Windows | [Git for Windows](https://git-scm.com/downloads/win) 建議;如果沒有則使用 PowerShell | 不支援 | Windows 原生專案和工具 |

109| WSL 2 | WSL 2 已啟用 | 支援 | Linux 工具鏈或沙箱化命令執行 |

110| WSL 1 | WSL 1 已啟用 | 不支援 | 如果 WSL 2 無法使用 |

111 

112**選項 1:使用 Git Bash 的原生 Windows**

113 

114安裝 [Git for Windows](https://git-scm.com/downloads/win),然後從 PowerShell 或 CMD 執行安裝命令。您不需要以系統管理員身分執行。

115 

116無論您從 PowerShell 還是 CMD 安裝,只會影響您執行的安裝命令。您的提示在 PowerShell 中顯示 `PS C:\Users\YourName>`,在 CMD 中顯示 `C:\Users\YourName>`(沒有 `PS`)。如果您是終端機新手,[終端機指南](/zh-TW/terminal-guide#windows)會逐步說明每個步驟。

117 

118安裝後,從 PowerShell、CMD 或 Git Bash 啟動 `claude`。安裝 Git Bash 時,Claude Code 在內部使用它來執行命令,無論您從何處啟動它。如果 Claude Code 找不到您的 Git Bash 安裝,請在您的 [settings.json 檔案](/zh-TW/settings)中設定路徑:

119 

120```json theme={null}

121{

122 "env": {

123 "CLAUDE_CODE_GIT_BASH_PATH": "C:\\Program Files\\Git\\bin\\bash.exe"

124 }

125}

126```

127 

128Claude Code 也可以在 Windows 上原生執行 PowerShell。安裝 Git Bash 時,PowerShell 工具正在逐步推出作為額外選項:設定 `CLAUDE_CODE_USE_POWERSHELL_TOOL=1` 以選擇加入或 `0` 以選擇退出。請參閱 [PowerShell tool](/zh-TW/tools-reference#powershell-tool) 以了解設定和限制。

129 

130**選項 2:WSL**

131 

132開啟您的 WSL 發行版本並從上面的[安裝說明](#install-claude-code)執行 Linux 安裝程式。您在 WSL 終端機內安裝和啟動 `claude`,而不是從 PowerShell 或 CMD。

133 

134### Alpine Linux 和 musl 型發行版

135 

136Alpine 和其他 musl/uClibc 型發行版上的原生安裝程式需要 `libgcc`、`libstdc++` 和 `ripgrep`。使用您的發行版套件管理員安裝這些,然後設定 `USE_BUILTIN_RIPGREP=0`。

137 

138此範例在 Alpine 上安裝所需的套件:

139 

140```bash theme={null}

141apk add libgcc libstdc++ ripgrep

142```

143 

144然後在您的 [`settings.json`](/zh-TW/settings#available-settings) 檔案中將 `USE_BUILTIN_RIPGREP` 設定為 `0`:

145 

146```json theme={null}

147{

148 "env": {

149 "USE_BUILTIN_RIPGREP": "0"

150 }

151}

152```

153 

154## 驗證您的安裝

155 

156安裝後,確認 Claude Code 正常運作:

157 

158```bash theme={null}

159claude --version

160```

161 

162如果此命令失敗並出現 `command not found` 或其他錯誤,請參閱[疑難排解安裝和登入](/zh-TW/troubleshoot-install)。

163 

164如需更詳細的安裝和配置檢查,請執行 [`claude doctor`](/zh-TW/troubleshooting#get-more-help):

165 

166```bash theme={null}

167claude doctor

168```

169 

170## 驗證身份

171 

172Claude Code 需要 Pro、Max、Team、Enterprise 或 Console 帳戶。免費的 Claude.ai 方案不包括 Claude Code 存取權。您也可以透過第三方 API 提供者(如 [Amazon Bedrock](/zh-TW/amazon-bedrock)、[Google Vertex AI](/zh-TW/google-vertex-ai) 或 [Microsoft Foundry](/zh-TW/microsoft-foundry))使用 Claude Code。

173 

174安裝後,執行 `claude` 並按照瀏覽器提示登入。請參閱[驗證](/zh-TW/authentication)以了解所有帳戶類型和團隊設定選項。

175 

176## 更新 Claude Code

177 

178原生安裝會在背景自動更新。您可以[配置發行版本通道](#configure-release-channel)來控制您是立即接收更新還是按延遲穩定時間表接收,或[完全停用自動更新](#disable-auto-updates)。Homebrew、WinGet 和[Linux 套件管理員](#install-with-linux-package-managers)安裝需要手動更新。

179 

180### 自動更新

181 

182Claude Code 在啟動時和執行期間定期檢查更新。更新會在背景下載和安裝,然後在您下次啟動 Claude Code 時生效。

183 

184<Note>

185 Homebrew、WinGet、apt、dnf 和 apk 安裝不會自動更新。對於 Homebrew,執行 `brew upgrade claude-code` 或 `brew upgrade claude-code@latest`,取決於您安裝的 cask。對於 WinGet,執行 `winget upgrade Anthropic.ClaudeCode`。對於 Linux 套件管理員,請參閱[使用 Linux 套件管理員安裝](#install-with-linux-package-managers)中的升級命令。

186 

187 **已知問題**:Claude Code 可能會在新版本在這些套件管理員中可用之前通知您有更新。如果升級失敗,請稍候並稍後重試。

188 

189 Homebrew 在升級後會將舊版本保留在磁碟上。定期執行 `brew cleanup` 以回收磁碟空間。

190</Note>

191 

192### 配置發行版本通道

193 

194使用 `autoUpdatesChannel` 設定控制 Claude Code 為自動更新和 `claude update` 遵循的發行版本通道:

195 

196* `"latest"`,預設值:在新功能發佈時立即接收

197* `"stable"`:使用通常約一週舊的版本,跳過有重大迴歸的發佈

198 

199透過 `/config` → **自動更新通道**配置此項,或將其新增到您的 [settings.json 檔案](/zh-TW/settings):

200 

201```json theme={null}

202{

203 "autoUpdatesChannel": "stable"

204}

205```

206 

207對於企業部署,您可以使用[受管設定](/zh-TW/permissions#managed-settings)在整個組織中強制執行一致的發行版本通道。

208 

209Homebrew 安裝根據 cask 名稱而不是此設定選擇通道:`claude-code` 追蹤穩定版本,`claude-code@latest` 追蹤最新版本。

210 

211### 固定最低版本

212 

213`minimumVersion` 設定建立一個下限。背景自動更新和 `claude update` 拒絕安裝低於此值的任何版本,因此如果您已經在較新的 `"latest"` 組建上,移至 `"stable"` 通道不會降級您。

214 

215透過 `/config` 從 `"latest"` 切換到 `"stable"` 會提示您保留目前版本或允許降級。選擇保留會將 `minimumVersion` 設定為該版本。切換回 `"latest"` 會清除它。

216 

217將其新增到您的 [settings.json 檔案](/zh-TW/settings)以明確固定下限:

218 

219```json theme={null}

220{

221 "autoUpdatesChannel": "stable",

222 "minimumVersion": "2.1.100"

223}

224```

225 

226在[受管設定](/zh-TW/permissions#managed-settings)中,這會強制執行使用者和專案設定無法覆蓋的組織範圍最低版本。

227 

228### 停用自動更新

229 

230在您的 [`settings.json`](/zh-TW/settings#available-settings) 檔案的 `env` 鍵中將 `DISABLE_AUTOUPDATER` 設定為 `"1"`:

231 

232```json theme={null}

233{

234 "env": {

235 "DISABLE_AUTOUPDATER": "1"

236 }

237}

238```

239 

240`DISABLE_AUTOUPDATER` 只會停止背景檢查;`claude update` 和 `claude install` 仍然有效。若要阻止所有更新路徑(包括手動更新),請改為設定 [`DISABLE_UPDATES`](/zh-TW/env-vars)。當您透過自己的通道發佈 Claude Code 並需要使用者保持在您提供的版本上時,請使用此選項。

241 

242### 手動更新

243 

244若要立即套用更新而不等待下一次背景檢查,請執行:

245 

246```bash theme={null}

247claude update

248```

249 

250## 進階安裝選項

251 

252這些選項適用於版本固定、Linux 套件管理員、npm 和驗證二進位檔案完整性。

253 

254### 安裝特定版本

255 

256原生安裝程式接受特定版本號或發行版本通道(`latest` 或 `stable`)。您在安裝時選擇的通道將成為自動更新的預設值。請參閱[配置發行版本通道](#configure-release-channel)以取得更多資訊。

257 

258若要安裝最新版本(預設):

259 

260<Tabs>

261 <Tab title="macOS、Linux、WSL">

262 ```bash theme={null}

263 curl -fsSL https://claude.ai/install.sh | bash

264 ```

265 </Tab>

266 

267 <Tab title="Windows PowerShell">

268 ```powershell theme={null}

269 irm https://claude.ai/install.ps1 | iex

270 ```

271 </Tab>

272 

273 <Tab title="Windows CMD">

274 ```batch theme={null}

275 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

276 ```

277 </Tab>

278</Tabs>

279 

280若要安裝穩定版本:

281 

282<Tabs>

283 <Tab title="macOS、Linux、WSL">

284 ```bash theme={null}

285 curl -fsSL https://claude.ai/install.sh | bash -s stable

286 ```

287 </Tab>

288 

289 <Tab title="Windows PowerShell">

290 ```powershell theme={null}

291 & ([scriptblock]::Create((irm https://claude.ai/install.ps1))) stable

292 ```

293 </Tab>

294 

295 <Tab title="Windows CMD">

296 ```batch theme={null}

297 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd stable && del install.cmd

298 ```

299 </Tab>

300</Tabs>

301 

302若要安裝特定版本號:

303 

304<Tabs>

305 <Tab title="macOS、Linux、WSL">

306 ```bash theme={null}

307 curl -fsSL https://claude.ai/install.sh | bash -s 2.1.89

308 ```

309 </Tab>

310 

311 <Tab title="Windows PowerShell">

312 ```powershell theme={null}

313 & ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 2.1.89

314 ```

315 </Tab>

316 

317 <Tab title="Windows CMD">

318 ```batch theme={null}

319 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd 2.1.89 && del install.cmd

320 ```

321 </Tab>

322</Tabs>

323 

324### 使用 Linux 套件管理員安裝

325 

326Claude Code 發佈已簽署的 apt、dnf 和 apk 儲存庫。將 `stable` 替換為 `latest` 以使用滾動通道。套件管理員安裝不會透過 Claude Code 自動更新;更新會透過您的正常系統升級工作流程進行。

327 

328所有儲存庫都使用 [Claude Code 發佈簽署金鑰](#binary-integrity-and-code-signing)簽署。在信任金鑰之前,請按照每個標籤中的說明驗證它。

329 

330<Tabs>

331 <Tab title="apt">

332 適用於 Debian 和 Ubuntu。若要使用滾動通道,請變更 `deb` 行中的兩個 `stable` 出現次數:URL 路徑和套件組合名稱。

333 

334 ```bash theme={null}

335 sudo install -d -m 0755 /etc/apt/keyrings

336 sudo curl -fsSL https://downloads.claude.ai/keys/claude-code.asc \

337 -o /etc/apt/keyrings/claude-code.asc

338 echo "deb [signed-by=/etc/apt/keyrings/claude-code.asc] https://downloads.claude.ai/claude-code/apt/stable stable main" \

339 | sudo tee /etc/apt/sources.list.d/claude-code.list

340 sudo apt update

341 sudo apt install claude-code

342 ```

343 

344 在信任之前驗證 GPG 金鑰指紋:`gpg --show-keys /etc/apt/keyrings/claude-code.asc` 應該報告 `31DD DE24 DDFA B679 F42D 7BD2 BAA9 29FF 1A7E CACE`。

345 

346 若要稍後升級,請執行 `sudo apt update && sudo apt upgrade claude-code`。

347 </Tab>

348 

349 <Tab title="dnf">

350 適用於 Fedora 和 RHEL:

351 

352 ```bash theme={null}

353 sudo tee /etc/yum.repos.d/claude-code.repo <<'EOF'

354 [claude-code]

355 name=Claude Code

356 baseurl=https://downloads.claude.ai/claude-code/rpm/stable

357 enabled=1

358 gpgcheck=1

359 gpgkey=https://downloads.claude.ai/keys/claude-code.asc

360 EOF

361 sudo dnf install claude-code

362 ```

363 

364 dnf 在首次安裝時下載金鑰,並提示您確認指紋。在接受之前驗證它是否與 `31DD DE24 DDFA B679 F42D 7BD2 BAA9 29FF 1A7E CACE` 相符。

365 

366 若要稍後升級,請執行 `sudo dnf upgrade claude-code`。

367 </Tab>

368 

369 <Tab title="apk">

370 適用於 Alpine Linux:

371 

372 ```sh theme={null}

373 wget -O /etc/apk/keys/claude-code.rsa.pub \

374 https://downloads.claude.ai/keys/claude-code.rsa.pub

375 echo "https://downloads.claude.ai/claude-code/apk/stable" >> /etc/apk/repositories

376 apk add claude-code

377 ```

378 

379 使用 `sha256sum /etc/apk/keys/claude-code.rsa.pub` 驗證下載的金鑰,應該報告 `395759c1f7449ef4cdef305a42e820f3c766d6090d142634ebdb049f113168b6`。

380 

381 若要稍後升級,請執行 `apk update && apk upgrade claude-code`。

382 </Tab>

383</Tabs>

384 

385### 使用 npm 安裝

386 

387您也可以將 Claude Code 安裝為全域 npm 套件。該套件需要 [Node.js 18 或更新版本](https://nodejs.org/en/download)。

388 

389```bash theme={null}

390npm install -g @anthropic-ai/claude-code

391```

392 

393npm 套件安裝與獨立安裝程式相同的原生二進位檔案。npm 透過每個平台的選擇性依賴項(例如 `@anthropic-ai/claude-code-darwin-arm64`)提取二進位檔案,並透過 postinstall 步驟將其連結到位。已安裝的 `claude` 二進位檔案本身不會呼叫 Node。

394 

395支援的 npm 安裝平台為 `darwin-arm64`、`darwin-x64`、`linux-x64`、`linux-arm64`、`linux-x64-musl`、`linux-arm64-musl`、`win32-x64` 和 `win32-arm64`。您的套件管理員必須允許選擇性依賴項。如果安裝後二進位檔案遺失,請參閱[疑難排解](/zh-TW/troubleshoot-install#native-binary-not-found-after-npm-install)。

396 

397<Warning>

398 請勿使用 `sudo npm install -g`,因為這可能導致權限問題和安全風險。如果您遇到權限錯誤,請參閱[疑難排解權限錯誤](/zh-TW/troubleshoot-install#permission-errors-during-installation)。

399</Warning>

400 

401### 二進位檔案完整性和程式碼簽署

402 

403每個發佈都會發佈一個 `manifest.json`,其中包含每個平台二進位檔案的 SHA256 校驗和。該資訊清單使用 Anthropic GPG 金鑰簽署,因此驗證資訊清單上的簽名可以傳遞地驗證它列出的每個二進位檔案。

404 

405#### 驗證資訊清單簽名

406 

407步驟 1-3 需要具有 `gpg` 和 `curl` 的 POSIX shell。在 Windows 上,在 Git Bash 或 WSL 中執行它們。步驟 4 包括 PowerShell 選項。

408 

409<Steps>

410 <Step title="下載並匯入公開金鑰">

411 發佈簽署金鑰發佈在固定 URL。

412 

413 ```bash theme={null}

414 curl -fsSL https://downloads.claude.ai/keys/claude-code.asc | gpg --import

415 ```

416 

417 顯示匯入金鑰的指紋。

418 

419 ```bash theme={null}

420 gpg --fingerprint security@anthropic.com

421 ```

422 

423 確認輸出包含此指紋:

424 

425 ```text theme={null}

426 31DD DE24 DDFA B679 F42D 7BD2 BAA9 29FF 1A7E CACE

427 ```

428 </Step>

429 

430 <Step title="下載資訊清單和簽名">

431 將 `VERSION` 設定為您要驗證的發佈。

432 

433 ```bash theme={null}

434 REPO=https://downloads.claude.ai/claude-code-releases

435 VERSION=2.1.89

436 curl -fsSLO "$REPO/$VERSION/manifest.json"

437 curl -fsSLO "$REPO/$VERSION/manifest.json.sig"

438 ```

439 </Step>

440 

441 <Step title="驗證簽名">

442 驗證分離的簽名對比資訊清單。

443 

444 ```bash theme={null}

445 gpg --verify manifest.json.sig manifest.json

446 ```

447 

448 有效的結果報告 `Good signature from "Anthropic Claude Code Release Signing <security@anthropic.com>"`。

449 

450 `gpg` 也會為任何新匯入的金鑰列印 `WARNING: This key is not certified with a trusted signature!`。這是預期的。`Good signature` 行確認密碼檢查已通過。第 1 步中的指紋比較確認金鑰本身是真實的。

451 </Step>

452 

453 <Step title="根據資訊清單檢查二進位檔案">

454 將您下載的二進位檔案的 SHA256 校驗和與 `manifest.json` 中 `platforms.<platform>.checksum` 下列出的值進行比較。

455 

456 <Tabs>

457 <Tab title="Linux">

458 ```bash theme={null}

459 sha256sum claude

460 ```

461 </Tab>

462 

463 <Tab title="macOS">

464 ```bash theme={null}

465 shasum -a 256 claude

466 ```

467 </Tab>

468 

469 <Tab title="Windows PowerShell">

470 ```powershell theme={null}

471 (Get-FileHash claude.exe -Algorithm SHA256).Hash.ToLower()

472 ```

473 </Tab>

474 </Tabs>

475 </Step>

476</Steps>

477 

478<Note>

479 資訊清單簽名適用於 `2.1.89` 及以後的發佈。較早的發佈在 `manifest.json` 中發佈校驗和,但沒有分離的簽名。

480</Note>

481 

482#### 平台程式碼簽名

483 

484除了簽署的資訊清單外,個別二進位檔案在支援的地方還帶有平台原生程式碼簽名。

485 

486* **macOS**:由「Anthropic PBC」簽署並由 Apple 公證。使用 `codesign --verify --verbose ./claude` 驗證。

487* **Windows**:由「Anthropic, PBC」簽署。使用 `Get-AuthenticodeSignature .\claude.exe` 驗證。

488* **Linux**:二進位檔案不是單獨程式碼簽署的。如果您直接從 `claude-code-releases` 儲存庫下載或使用原生安裝程式,請使用上面的資訊清單簽名驗證完整性。如果您使用 [apt、dnf 或 apk](#install-with-linux-package-managers) 安裝,您的套件管理員會使用儲存庫簽署金鑰自動驗證簽名。

489 

490## 卸載 Claude Code

491 

492若要移除 Claude Code,請按照您的安裝方法的說明進行。

493 

494### 原生安裝

495 

496移除 Claude Code 二進位檔案和版本檔案:

497 

498<Tabs>

499 <Tab title="macOS、Linux、WSL">

500 ```bash theme={null}

501 rm -f ~/.local/bin/claude

502 rm -rf ~/.local/share/claude

503 ```

504 </Tab>

505 

506 <Tab title="Windows PowerShell">

507 ```powershell theme={null}

508 Remove-Item -Path "$env:USERPROFILE\.local\bin\claude.exe" -Force

509 Remove-Item -Path "$env:USERPROFILE\.local\share\claude" -Recurse -Force

510 ```

511 </Tab>

512</Tabs>

513 

514### Homebrew 安裝

515 

516移除您安裝的 Homebrew cask。如果您安裝了穩定版 cask:

517 

518```bash theme={null}

519brew uninstall --cask claude-code

520```

521 

522如果您安裝了最新版 cask:

523 

524```bash theme={null}

525brew uninstall --cask claude-code@latest

526```

527 

528### WinGet 安裝

529 

530移除 WinGet 套件:

531 

532```powershell theme={null}

533winget uninstall Anthropic.ClaudeCode

534```

535 

536### apt / dnf / apk

537 

538移除套件和儲存庫配置:

539 

540<Tabs>

541 <Tab title="apt">

542 ```bash theme={null}

543 sudo apt remove claude-code

544 sudo rm /etc/apt/sources.list.d/claude-code.list /etc/apt/keyrings/claude-code.asc

545 ```

546 </Tab>

547 

548 <Tab title="dnf">

549 ```bash theme={null}

550 sudo dnf remove claude-code

551 sudo rm /etc/yum.repos.d/claude-code.repo

552 ```

553 </Tab>

554 

555 <Tab title="apk">

556 ```sh theme={null}

557 apk del claude-code

558 sed -i '\|downloads.claude.ai/claude-code/apk|d' /etc/apk/repositories

559 rm /etc/apk/keys/claude-code.rsa.pub

560 ```

561 </Tab>

562</Tabs>

563 

564### npm

565 

566移除全域 npm 套件:

567 

568```bash theme={null}

569npm uninstall -g @anthropic-ai/claude-code

570```

571 

572### 移除配置檔案

573 

574<Warning>

575 移除配置檔案將刪除您的所有設定、允許的工具、MCP 伺服器配置和會話歷史記錄。

576</Warning>

577 

578VS Code 擴充功能、JetBrains 外掛程式和桌面應用程式也會寫入 `~/.claude/`。如果其中任何一個仍然安裝,下次執行時目錄會被重新建立。若要完全移除 Claude Code,請在刪除這些檔案之前卸載 [VS Code 擴充功能](/zh-TW/vs-code#uninstall-the-extension)、JetBrains 外掛程式和桌面應用程式。

579 

580若要移除 Claude Code 設定和快取資料:

581 

582<Tabs>

583 <Tab title="macOS、Linux、WSL">

584 ```bash theme={null}

585 # 移除使用者設定和狀態

586 rm -rf ~/.claude

587 rm ~/.claude.json

588 

589 # 移除專案特定設定(從您的專案目錄執行)

590 rm -rf .claude

591 rm -f .mcp.json

592 ```

593 </Tab>

594 

595 <Tab title="Windows PowerShell">

596 ```powershell theme={null}

597 # 移除使用者設定和狀態

598 Remove-Item -Path "$env:USERPROFILE\.claude" -Recurse -Force

599 Remove-Item -Path "$env:USERPROFILE\.claude.json" -Force

600 

601 # 移除專案特定設定(從您的專案目錄執行)

602 Remove-Item -Path ".claude" -Recurse -Force

603 Remove-Item -Path ".mcp.json" -Force

604 ```

605 </Tab>

606</Tabs>

skills.md +728 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 使用 skills 擴展 Claude

6 

7> 在 Claude Code 中建立、管理和分享 skills,以擴展 Claude 的功能。包括自訂命令和捆綁的 skills。

8 

9Skills 擴展了 Claude 能做的事情。建立一個 `SKILL.md` 檔案,其中包含說明,Claude 就會將其新增到其工具組中。Claude 在相關時會使用 skills,或者您可以直接使用 `/skill-name` 叫用一個。

10 

11當您不斷將相同的劇本、檢查清單或多步驟程序貼到聊天中時,或當 CLAUDE.md 的某個部分已成長為程序而不是事實時,請建立一個 skill。與 CLAUDE.md 內容不同,skill 的主體僅在使用時載入,因此長參考資料在您需要之前幾乎不花費任何成本。

12 

13<Note>

14 對於內建命令(如 `/help` 和 `/compact`)以及捆綁的 skills(如 `/debug` 和 `/simplify`),請參閱[命令參考](/zh-TW/commands)。

15 

16 **自訂命令已合併到 skills 中。** `.claude/commands/deploy.md` 中的檔案和 `.claude/skills/deploy/SKILL.md` 中的 skill 都會建立 `/deploy` 並以相同方式運作。您現有的 `.claude/commands/` 檔案會繼續運作。Skills 新增了可選功能:支援檔案的目錄、[控制您或 Claude 是否叫用它們](#control-who-invokes-a-skill)的 frontmatter,以及 Claude 在相關時自動載入它們的能力。

17</Note>

18 

19Claude Code skills 遵循 [Agent Skills](https://agentskills.io) 開放標準,該標準適用於多個 AI 工具。Claude Code 使用額外功能擴展了該標準,例如[叫用控制](#control-who-invokes-a-skill)、[subagent 執行](#run-skills-in-a-subagent)和[動態上下文注入](#inject-dynamic-context)。

20 

21## 捆綁的 skills

22 

23Claude Code 包含一組捆綁的 skills,在每個工作階段中都可用,包括 `/simplify`、`/batch`、`/debug`、`/loop` 和 `/claude-api`。與大多數內建命令不同,內建命令直接執行固定邏輯,捆綁的 skills 是基於提示的:它們為 Claude 提供詳細的劇本,並讓它使用其工具來協調工作。您叫用它們的方式與任何其他 skill 相同,輸入 `/` 後跟 skill 名稱。

24 

25捆綁的 skills 在[命令參考](/zh-TW/commands)中與內建命令一起列出,在「目的」欄中標記為 **Skill**。

26 

27## 開始使用

28 

29### 建立您的第一個 skill

30 

31此範例建立一個 skill,教導 Claude 使用視覺圖表和類比來解釋程式碼。由於它使用預設 frontmatter,Claude 可以在您詢問某事如何運作時自動載入它,或者您可以直接使用 `/explain-code` 叫用它。

32 

33<Steps>

34 <Step title="建立 skill 目錄">

35 在您的個人 skills 資料夾中為 skill 建立一個目錄。個人 skills 在您的所有專案中都可用。

36 

37 ```bash theme={null}

38 mkdir -p ~/.claude/skills/explain-code

39 ```

40 </Step>

41 

42 <Step title="編寫 SKILL.md">

43 每個 skill 都需要一個 `SKILL.md` 檔案,包含兩部分:YAML frontmatter(在 `---` 標記之間),告訴 Claude 何時使用該 skill,以及包含 Claude 在叫用該 skill 時遵循的說明的 markdown 內容。目錄名稱變成 `/slash-command`,`description` 幫助 Claude 決定何時自動載入它。

44 

45 建立 `~/.claude/skills/explain-code/SKILL.md`:

46 

47 ```yaml theme={null}

48 ---

49 description: Explains code with visual diagrams and analogies. Use when explaining how code works, teaching about a codebase, or when the user asks "how does this work?"

50 ---

51 

52 When explaining code, always include:

53 

54 1. **Start with an analogy**: Compare the code to something from everyday life

55 2. **Draw a diagram**: Use ASCII art to show the flow, structure, or relationships

56 3. **Walk through the code**: Explain step-by-step what happens

57 4. **Highlight a gotcha**: What's a common mistake or misconception?

58 

59 Keep explanations conversational. For complex concepts, use multiple analogies.

60 ```

61 </Step>

62 

63 <Step title="測試 skill">

64 您可以透過兩種方式測試它:

65 

66 **讓 Claude 自動叫用它**,詢問與描述相符的內容:

67 

68 ```text theme={null}

69 How does this code work?

70 ```

71 

72 **或直接使用 skill 名稱叫用它**:

73 

74 ```text theme={null}

75 /explain-code src/auth/login.ts

76 ```

77 

78 無論哪種方式,Claude 都應該在其解釋中包含類比和 ASCII 圖表。

79 </Step>

80</Steps>

81 

82### Skills 的位置

83 

84您儲存 skill 的位置決定了誰可以使用它:

85 

86| 位置 | 路徑 | 適用於 |

87| :- | :---------------------------------------- | :--------- |

88| 企業 | 請參閱[受管設定](/zh-TW/settings#settings-files) | 您組織中的所有使用者 |

89| 個人 | `~/.claude/skills/<skill-name>/SKILL.md` | 您的所有專案 |

90| 專案 | `.claude/skills/<skill-name>/SKILL.md` | 僅此專案 |

91| 外掛 | `<plugin>/skills/<skill-name>/SKILL.md` | 啟用外掛的位置 |

92 

93當 skills 在各個層級共享相同名稱時,企業會覆蓋個人,個人會覆蓋專案。外掛 skills 使用 `plugin-name:skill-name` 命名空間,因此它們不能與其他層級衝突。如果您在 `.claude/commands/` 中有檔案,它們的運作方式相同,但如果 skill 和命令共享相同名稱,skill 優先。

94 

95#### 即時變更偵測

96 

97Claude Code 監視 skill 目錄以尋找檔案變更。在 `~/.claude/skills/`、專案 `.claude/skills/` 或 `--add-dir` 目錄內的 `.claude/skills/` 中新增、編輯或移除 skill 會在目前工作階段內生效,無需重新啟動。建立在工作階段開始時不存在的頂級 skills 目錄需要重新啟動 Claude Code,以便可以監視新目錄。

98 

99#### 從巢狀目錄自動發現

100 

101當您在子目錄中使用檔案時,Claude Code 會自動從巢狀 `.claude/skills/` 目錄發現 skills。例如,如果您正在編輯 `packages/frontend/` 中的檔案,Claude Code 也會在 `packages/frontend/.claude/skills/` 中尋找 skills。這支援 monorepo 設定,其中套件有自己的 skills。

102 

103每個 skill 是一個以 `SKILL.md` 作為進入點的目錄:

104 

105```text theme={null}

106my-skill/

107├── SKILL.md # 主要說明(必需)

108├── template.md # Claude 要填入的範本

109├── examples/

110│ └── sample.md # 顯示預期格式的範例輸出

111└── scripts/

112 └── validate.sh # Claude 可以執行的指令碼

113```

114 

115`SKILL.md` 包含主要說明,是必需的。其他檔案是可選的,讓您建立更強大的 skills:Claude 要填入的範本、顯示預期格式的範例輸出、Claude 可以執行的指令碼或詳細的參考文件。從您的 `SKILL.md` 參考這些檔案,以便 Claude 知道它們包含什麼以及何時載入它們。請參閱[新增支援檔案](#add-supporting-files)以取得更多詳細資訊。

116 

117<Note>

118 `.claude/commands/` 中的檔案仍然有效,並支援相同的 [frontmatter](#frontmatter-reference)。建議使用 Skills,因為它們支援額外功能,例如支援檔案。

119</Note>

120 

121#### 來自其他目錄的 skills

122 

123`--add-dir` 旗標[授予檔案存取權](/zh-TW/permissions#additional-directories-grant-file-access-not-configuration)而不是設定發現,但 skills 是例外:已新增目錄中的 `.claude/skills/` 會自動載入。請參閱[即時變更偵測](#live-change-detection)以了解編輯在工作階段期間如何被拾取。

124 

125其他 `.claude/` 設定(例如 subagents、命令和輸出樣式)不會從其他目錄載入。請參閱[例外表](/zh-TW/permissions#additional-directories-grant-file-access-not-configuration)以取得完整的載入和未載入內容清單,以及跨專案共享設定的建議方式。

126 

127<Note>

128 來自 `--add-dir` 目錄的 CLAUDE.md 檔案預設不會載入。若要載入它們,請設定 `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`。請參閱[從其他目錄載入](/zh-TW/memory#load-from-additional-directories)。

129</Note>

130 

131## 設定 skills

132 

133Skills 透過 `SKILL.md` 頂部的 YAML frontmatter 和隨後的 markdown 內容進行設定。

134 

135### Skills 內容的類型

136 

137Skill 檔案可以包含任何說明,但思考您想如何叫用它們有助於指導要包含的內容:

138 

139**參考內容**新增 Claude 應用於您目前工作的知識。慣例、模式、風格指南、領域知識。此內容內聯執行,以便 Claude 可以將其與您的對話上下文一起使用。

140 

141```yaml theme={null}

142---

143name: api-conventions

144description: API design patterns for this codebase

145---

146 

147When writing API endpoints:

148- Use RESTful naming conventions

149- Return consistent error formats

150- Include request validation

151```

152 

153**任務內容**為 Claude 提供特定動作的逐步說明,例如部署、提交或程式碼生成。這些通常是您想使用 `/skill-name` 直接叫用的動作,而不是讓 Claude 決定何時執行它們。新增 `disable-model-invocation: true` 以防止 Claude 自動觸發它。

154 

155```yaml theme={null}

156---

157name: deploy

158description: Deploy the application to production

159context: fork

160disable-model-invocation: true

161---

162 

163Deploy the application:

1641. Run the test suite

1652. Build the application

1663. Push to the deployment target

167```

168 

169您的 `SKILL.md` 可以包含任何內容,但思考您想如何叫用該 skill(由您、由 Claude 或兩者)以及您想在哪裡執行它(內聯或在 subagent 中)有助於指導要包含的內容。對於複雜的 skills,您也可以[新增支援檔案](#add-supporting-files)以保持主要 skill 的焦點。

170 

171### Frontmatter 參考

172 

173除了 markdown 內容外,您可以使用 `SKILL.md` 檔案頂部 `---` 標記之間的 YAML frontmatter 欄位來設定 skill 行為:

174 

175```yaml theme={null}

176---

177name: my-skill

178description: What this skill does

179disable-model-invocation: true

180allowed-tools: Read Grep

181---

182 

183Your skill instructions here...

184```

185 

186所有欄位都是可選的。建議只使用 `description`,以便 Claude 知道何時使用該 skill。

187 

188| 欄位 | 必需 | 描述 |

189| :------------------------- | :- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

190| `name` | 否 | Skill 的顯示名稱。如果省略,使用目錄名稱。僅限小寫字母、數字和連字號(最多 64 個字元)。 |

191| `description` | 建議 | Skill 的功能以及何時使用它。Claude 使用此來決定何時應用該 skill。如果省略,使用 markdown 內容的第一段。前置關鍵使用案例:結合的 `description` 和 `when_to_use` 文字在 skill 清單中截斷至 1,536 個字元以減少上下文使用。 |

192| `when_to_use` | 否 | Claude 應何時叫用該 skill 的額外上下文,例如觸發短語或範例請求。附加到 skill 清單中的 `description`,並計入 1,536 個字元的上限。 |

193| `argument-hint` | 否 | 自動完成期間顯示的提示,指示預期的引數。範例:`[issue-number]` 或 `[filename] [format]`。 |

194| `arguments` | 否 | 用於 skill 內容中[`$name` 替換](#available-string-substitutions)的具名位置引數。接受空格分隔的字串或 YAML 清單。名稱按順序對應到引數位置。 |

195| `disable-model-invocation` | 否 | 設定為 `true` 以防止 Claude 自動載入此 skill。用於您想使用 `/name` 手動觸發的工作流程。也防止該 skill 被[預載入到 subagents](/zh-TW/sub-agents#preload-skills-into-subagents)。預設值:`false`。 |

196| `user-invocable` | 否 | 設定為 `false` 以從 `/` 功能表中隱藏。用於使用者不應直接叫用的背景知識。預設值:`true`。 |

197| `allowed-tools` | 否 | 當此 skill 處於作用中時,Claude 可以使用而無需詢問許可的工具。接受空格分隔的字串或 YAML 清單。 |

198| `model` | 否 | 當此 skill 處於作用中時要使用的模型。覆蓋適用於目前回合的其餘部分,不會儲存到設定;工作階段模型在您的下一個提示時恢復。接受與 [`/model`](/zh-TW/model-config) 相同的值,或 `inherit` 以保持作用中的模型。 |

199| `effort` | 否 | 當此 skill 處於作用中時的[努力級別](/zh-TW/model-config#adjust-effort-level)。覆蓋工作階段努力級別。預設值:繼承自工作階段。選項:`low`、`medium`、`high`、`xhigh`、`max`;可用級別取決於模型。 |

200| `context` | 否 | 設定為 `fork` 以在分叉的 subagent 上下文中執行。 |

201| `agent` | 否 | 當設定 `context: fork` 時要使用的 subagent 類型。 |

202| `hooks` | 否 | 限定於此 skill 生命週期的 hooks。請參閱 [Skills 和代理中的 Hooks](/zh-TW/hooks#hooks-in-skills-and-agents) 以取得設定格式。 |

203| `paths` | 否 | Glob 模式,限制何時啟動此 skill。接受逗號分隔的字串或 YAML 清單。設定時,Claude 僅在使用與模式相符的檔案時自動載入該 skill。使用與[路徑特定規則](/zh-TW/memory#path-specific-rules)相同的格式。 |

204| `shell` | 否 | 用於此 skill 中 `` !`command` `` 和 ` ```! ` 區塊的 shell。接受 `bash`(預設)或 `powershell`。設定 `powershell` 會在 Windows 上透過 PowerShell 執行內聯 shell 命令。需要 `CLAUDE_CODE_USE_POWERSHELL_TOOL=1`。 |

205 

206#### 可用的字串替換

207 

208Skills 支援 skill 內容中動態值的字串替換:

209 

210| 變數 | 描述 |

211| :--------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------- |

212| `$ARGUMENTS` | 叫用 skill 時傳遞的所有引數。如果 `$ARGUMENTS` 不在內容中,引數會附加為 `ARGUMENTS: <value>`。 |

213| `$ARGUMENTS[N]` | 透過 0 為基礎的索引存取特定引數,例如 `$ARGUMENTS[0]` 表示第一個引數。 |

214| `$N` | `$ARGUMENTS[N]` 的簡寫,例如 `$0` 表示第一個引數或 `$1` 表示第二個引數。 |

215| `$name` | 在 [`arguments`](#frontmatter-reference) frontmatter 清單中宣告的具名引數。名稱按順序對應到位置,因此使用 `arguments: [issue, branch]` 時,預留位置 `$issue` 擴展為第一個引數,`$branch` 擴展為第二個引數。 |

216| `${CLAUDE_SESSION_ID}` | 目前的工作階段 ID。適用於記錄、建立工作階段特定檔案或將 skill 輸出與工作階段相關聯。 |

217| `${CLAUDE_EFFORT}` | 目前的努力級別:`low`、`medium`、`high`、`xhigh` 或 `max`。使用此來根據作用中的努力設定調整 skill 說明。 |

218| `${CLAUDE_SKILL_DIR}` | 包含 skill 的 `SKILL.md` 檔案的目錄。對於外掛 skills,這是外掛中 skill 的子目錄,而不是外掛根目錄。在 bash 注入命令中使用此來參考與 skill 捆綁的指令碼或檔案,無論目前的工作目錄如何。 |

219 

220索引引數使用 shell 風格的引用,因此將多字值包裝在引號中以將其作為單個引數傳遞。例如,`/my-skill "hello world" second` 使 `$0` 擴展為 `hello world`,`$1` 擴展為 `second`。`$ARGUMENTS` 預留位置始終擴展為輸入的完整引數字串。

221 

222**使用替換的範例:**

223 

224```yaml theme={null}

225---

226name: session-logger

227description: Log activity for this session

228---

229 

230Log the following to logs/${CLAUDE_SESSION_ID}.log:

231 

232$ARGUMENTS

233```

234 

235### 新增支援檔案

236 

237Skills 可以在其目錄中包含多個檔案。這使 `SKILL.md` 專注於基本要素,同時讓 Claude 僅在需要時存取詳細的參考資料。大型參考文件、API 規格或範例集合不需要在每次 skill 執行時載入上下文。

238 

239```text theme={null}

240my-skill/

241├── SKILL.md (required - overview and navigation)

242├── reference.md (detailed API docs - loaded when needed)

243├── examples.md (usage examples - loaded when needed)

244└── scripts/

245 └── helper.py (utility script - executed, not loaded)

246```

247 

248從 `SKILL.md` 參考支援檔案,以便 Claude 知道每個檔案包含什麼以及何時載入它:

249 

250```markdown theme={null}

251## Additional resources

252 

253- For complete API details, see [reference.md](reference.md)

254- For usage examples, see [examples.md](examples.md)

255```

256 

257<Tip>將 `SKILL.md` 保持在 500 行以下。將詳細的參考資料移至單獨的檔案。</Tip>

258 

259### 控制誰叫用 skill

260 

261預設情況下,您和 Claude 都可以叫用任何 skill。您可以輸入 `/skill-name` 直接叫用它,Claude 可以在與您的對話相關時自動載入它。兩個 frontmatter 欄位讓您限制此:

262 

263* **`disable-model-invocation: true`**:只有您可以叫用該 skill。用於具有副作用或您想控制時機的工作流程,例如 `/commit`、`/deploy` 或 `/send-slack-message`。您不希望 Claude 因為您的程式碼看起來準備好就決定部署。

264 

265* **`user-invocable: false`**:只有 Claude 可以叫用該 skill。用於不可作為命令操作的背景知識。`legacy-system-context` skill 解釋舊系統如何運作。Claude 在相關時應該知道這一點,但 `/legacy-system-context` 對使用者來說不是有意義的動作。

266 

267此範例建立一個只有您可以觸發的部署 skill。`disable-model-invocation: true` 欄位防止 Claude 自動執行它:

268 

269```yaml theme={null}

270---

271name: deploy

272description: Deploy the application to production

273disable-model-invocation: true

274---

275 

276Deploy $ARGUMENTS to production:

277 

2781. Run the test suite

2792. Build the application

2803. Push to the deployment target

2814. Verify the deployment succeeded

282```

283 

284以下是兩個欄位如何影響叫用和上下文載入:

285 

286| Frontmatter | 您可以叫用 | Claude 可以叫用 | 何時載入上下文 |

287| :------------------------------- | :---- | :---------- | :---------------------- |

288| (預設) | 是 | 是 | 描述始終在上下文中,叫用時載入完整 skill |

289| `disable-model-invocation: true` | 是 | 否 | 描述不在上下文中,您叫用時載入完整 skill |

290| `user-invocable: false` | 否 | 是 | 描述始終在上下文中,叫用時載入完整 skill |

291 

292<Note>

293 在常規工作階段中,skill 描述會載入上下文,以便 Claude 知道可用的內容,但完整 skill 內容僅在叫用時載入。[預載入 skills 的 Subagents](/zh-TW/sub-agents#preload-skills-into-subagents) 的運作方式不同:完整 skill 內容在啟動時注入。

294</Note>

295 

296### Skill 內容生命週期

297 

298當您或 Claude 叫用 skill 時,呈現的 `SKILL.md` 內容作為單一訊息進入對話,並在工作階段的其餘部分保持在那裡。Claude Code 不會在稍後的回合中重新讀取 skill 檔案,因此應將應該在整個任務中應用的指導寫成常設說明,而不是一次性步驟。

299 

300[Auto-compact](/zh-TW/how-claude-code-works#when-context-fills-up) 在令牌預算內轉發叫用的 skills。當對話被摘要以釋放上下文時,Claude Code 在摘要後重新附加每個 skill 的最新叫用,保留每個的前 5,000 個令牌。重新附加的 skills 共享 25,000 個令牌的組合預算。Claude Code 從最近叫用的 skill 開始填充此預算,因此如果您在一個工作階段中叫用了許多 skills,較舊的 skills 可能在 compaction 後完全被丟棄。

301 

302如果 skill 在第一個回應後似乎停止影響行為,內容通常仍然存在,模型正在選擇其他工具或方法。加強 skill 的 `description` 和說明,以便模型繼續偏好它,或使用 [hooks](/zh-TW/hooks) 來確定性地強制行為。如果 skill 很大或您在它之後叫用了其他幾個,請在 compaction 後重新叫用它以恢復完整內容。

303 

304### 為 skill 預先批准工具

305 

306`allowed-tools` 欄位在 skill 處於作用中時授予列出的工具的許可,因此 Claude 可以使用它們而無需提示您批准。它不會限制哪些工具可用:每個工具仍然可呼叫,您的[許可設定](/zh-TW/permissions)仍然管理未列出的工具。

307 

308此 skill 讓 Claude 在您叫用它時執行 git 命令而無需每次使用批准:

309 

310```yaml theme={null}

311---

312name: commit

313description: Stage and commit the current changes

314disable-model-invocation: true

315allowed-tools: Bash(git add *) Bash(git commit *) Bash(git status *)

316---

317```

318 

319若要阻止 skill 使用某些工具,請在您的[許可設定](/zh-TW/permissions)中新增拒絕規則。

320 

321### 將引數傳遞給 skills

322 

323您和 Claude 都可以在叫用 skill 時傳遞引數。引數可透過 `$ARGUMENTS` 預留位置取得。

324 

325此 skill 透過編號修復 GitHub 問題。`$ARGUMENTS` 預留位置會被 skill 名稱後面的任何內容取代:

326 

327```yaml theme={null}

328---

329name: fix-issue

330description: Fix a GitHub issue

331disable-model-invocation: true

332---

333 

334Fix GitHub issue $ARGUMENTS following our coding standards.

335 

3361. Read the issue description

3372. Understand the requirements

3383. Implement the fix

3394. Write tests

3405. Create a commit

341```

342 

343當您執行 `/fix-issue 123` 時,Claude 會收到「Fix GitHub issue 123 following our coding standards...」

344 

345如果您使用引數叫用 skill,但 skill 不包含 `$ARGUMENTS`,Claude Code 會將 `ARGUMENTS: <your input>` 附加到 skill 內容的末尾,以便 Claude 仍然看到您輸入的內容。

346 

347若要按位置存取個別引數,請使用 `$ARGUMENTS[N]` 或較短的 `$N`:

348 

349```yaml theme={null}

350---

351name: migrate-component

352description: Migrate a component from one framework to another

353---

354 

355Migrate the $ARGUMENTS[0] component from $ARGUMENTS[1] to $ARGUMENTS[2].

356Preserve all existing behavior and tests.

357```

358 

359執行 `/migrate-component SearchBar React Vue` 會將 `$ARGUMENTS[0]` 替換為 `SearchBar`、`$ARGUMENTS[1]` 替換為 `React`、`$ARGUMENTS[2]` 替換為 `Vue`。使用 `$N` 簡寫的相同 skill:

360 

361```yaml theme={null}

362---

363name: migrate-component

364description: Migrate a component from one framework to another

365---

366 

367Migrate the $0 component from $1 to $2.

368Preserve all existing behavior and tests.

369```

370 

371## 進階模式

372 

373### 注入動態上下文

374 

375`` !`<command>` `` 語法在將 skill 內容傳送給 Claude 之前執行 shell 命令。命令輸出替換預留位置,因此 Claude 會收到實際資料,而不是命令本身。

376 

377此 skill 透過使用 GitHub CLI 擷取即時 PR 資料來總結拉取請求。`` !`gh pr diff` `` 和其他命令首先執行,其輸出會插入到提示中:

378 

379```yaml theme={null}

380---

381name: pr-summary

382description: Summarize changes in a pull request

383context: fork

384agent: Explore

385allowed-tools: Bash(gh *)

386---

387 

388## Pull request context

389- PR diff: !`gh pr diff`

390- PR comments: !`gh pr view --comments`

391- Changed files: !`gh pr diff --name-only`

392 

393## Your task

394Summarize this pull request...

395```

396 

397當此 skill 執行時:

398 

3991. 每個 `` !`<command>` `` 立即執行(在 Claude 看到任何內容之前)

4002. 輸出替換 skill 內容中的預留位置

4013. Claude 收到具有實際 PR 資料的完全呈現的提示

402 

403這是預處理,不是 Claude 執行的內容。Claude 只看到最終結果。

404 

405對於多行命令,請使用以 ` ```! ` 開啟的圍欄程式碼區塊,而不是內聯形式:

406 

407````markdown theme={null}

408## Environment

409```!

410node --version

411npm --version

412git status --short

413```

414````

415 

416若要停用來自使用者、專案、外掛或[其他目錄](#skills-from-additional-directories)來源的 skills 和自訂命令的此行為,請在[設定](/zh-TW/settings)中設定 `"disableSkillShellExecution": true`。每個命令會被替換為 `[shell command execution disabled by policy]` 而不是被執行。捆綁和受管 skills 不受影響。此設定在[受管設定](/zh-TW/permissions#managed-settings)中最有用,使用者無法覆蓋它。

417 

418<Tip>

419 若要在 skill 中啟用[擴展思考](/zh-TW/common-workflows#use-extended-thinking-thinking-mode),請在您的 skill 內容中的任何位置包含「ultrathink」一詞。

420</Tip>

421 

422### 在 subagent 中執行 skills

423 

424當您想要 skill 在隔離中執行時,將 `context: fork` 新增到您的 frontmatter。Skill 內容變成驅動 subagent 的提示。它將無法存取您的對話歷史記錄。

425 

426<Warning>

427 `context: fork` 僅對具有明確說明的 skills 有意義。如果您的 skill 包含「使用這些 API 慣例」之類的指南而沒有任務,subagent 會收到指南但沒有可操作的提示,並返回而沒有有意義的輸出。

428</Warning>

429 

430Skills 和 [subagents](/zh-TW/sub-agents) 以兩個方向協同運作:

431 

432| 方法 | 系統提示 | 任務 | 也載入 |

433| :------------------------- | :------------------------- | :----------- | :---------------------- |

434| 具有 `context: fork` 的 Skill | 來自代理類型(`Explore`、`Plan` 等) | SKILL.md 內容 | CLAUDE.md |

435| 具有 `skills` 欄位的 Subagent | Subagent 的 markdown 主體 | Claude 的委派訊息 | 預載入的 skills + CLAUDE.md |

436 

437使用 `context: fork`,您在 skill 中編寫任務並選擇代理類型來執行它。對於反向(定義使用 skills 作為參考資料的自訂 subagent),請參閱 [Subagents](/zh-TW/sub-agents#preload-skills-into-subagents)。

438 

439#### 範例:使用 Explore 代理的研究 skill

440 

441此 skill 在分叉的 Explore 代理中執行研究。Skill 內容變成任務,代理提供針對程式碼庫探索最佳化的唯讀工具:

442 

443```yaml theme={null}

444---

445name: deep-research

446description: Research a topic thoroughly

447context: fork

448agent: Explore

449---

450 

451Research $ARGUMENTS thoroughly:

452 

4531. Find relevant files using Glob and Grep

4542. Read and analyze the code

4553. Summarize findings with specific file references

456```

457 

458當此 skill 執行時:

459 

4601. 建立新的隔離上下文

4612. Subagent 收到 skill 內容作為其提示(「Research \$ARGUMENTS thoroughly...」)

4623. `agent` 欄位決定執行環境(模型、工具和許可)

4634. 結果會總結並返回到您的主要對話

464 

465`agent` 欄位指定要使用的 subagent 設定。選項包括內建代理(`Explore`、`Plan`、`general-purpose`)或來自 `.claude/agents/` 的任何自訂 subagent。如果省略,使用 `general-purpose`。

466 

467### 限制 Claude 的 skill 存取

468 

469預設情況下,Claude 可以叫用任何沒有設定 `disable-model-invocation: true` 的 skill。定義 `allowed-tools` 的 Skills 在 skill 處於作用中時授予 Claude 對這些工具的存取權,無需每次使用批准。您的[許可設定](/zh-TW/permissions)仍然管理所有其他工具的基準批准行為。一些內建命令也可透過 Skill 工具取得,包括 `/init`、`/review` 和 `/security-review`。其他內建命令(例如 `/compact`)則不行。

470 

471控制 Claude 可以叫用哪些 skills 的三種方式:

472 

473**透過在 `/permissions` 中拒絕 Skill 工具來停用所有 skills**:

474 

475```text theme={null}

476# Add to deny rules:

477Skill

478```

479 

480**使用[許可規則](/zh-TW/permissions)允許或拒絕特定 skills**:

481 

482```text theme={null}

483# Allow only specific skills

484Skill(commit)

485Skill(review-pr *)

486 

487# Deny specific skills

488Skill(deploy *)

489```

490 

491許可語法:`Skill(name)` 用於精確匹配,`Skill(name *)` 用於帶有任何引數的前綴匹配。

492 

493**透過將 `disable-model-invocation: true` 新增到其 frontmatter 來隱藏個別 skills**。這會從 Claude 的上下文中完全移除該 skill。

494 

495<Note>

496 `user-invocable` 欄位僅控制功能表可見性,不控制 Skill 工具存取。使用 `disable-model-invocation: true` 來阻止程式化叫用。

497</Note>

498 

499## 分享 skills

500 

501Skills 可以根據您的受眾在不同範圍內分發:

502 

503* **專案 skills**:將 `.claude/skills/` 提交到版本控制

504* **外掛**:在您的[外掛](/zh-TW/plugins)中建立 `skills/` 目錄

505* **受管**:透過[受管設定](/zh-TW/settings#settings-files)部署組織範圍

506 

507### 生成視覺輸出

508 

509Skills 可以捆綁並執行任何語言的指令碼,為 Claude 提供超越單個提示可能的功能。一個強大的模式是生成視覺輸出:在您的瀏覽器中開啟的互動式 HTML 檔案,用於探索資料、偵錯或建立報告。

510 

511此範例建立一個程式碼庫探索器:一個互動式樹狀檢視,您可以在其中展開和摺疊目錄、一目瞭然地查看檔案大小,並按顏色識別檔案類型。

512 

513建立 Skill 目錄:

514 

515```bash theme={null}

516mkdir -p ~/.claude/skills/codebase-visualizer/scripts

517```

518 

519建立 `~/.claude/skills/codebase-visualizer/SKILL.md`。描述告訴 Claude 何時啟動此 Skill,說明告訴 Claude 執行捆綁的指令碼:

520 

521````yaml theme={null}

522---

523name: codebase-visualizer

524description: Generate an interactive collapsible tree visualization of your codebase. Use when exploring a new repo, understanding project structure, or identifying large files.

525allowed-tools: Bash(python *)

526---

527 

528# Codebase Visualizer

529 

530Generate an interactive HTML tree view that shows your project's file structure with collapsible directories.

531 

532## Usage

533 

534Run the visualization script from your project root:

535 

536```bash

537python ~/.claude/skills/codebase-visualizer/scripts/visualize.py .

538```

539 

540This creates `codebase-map.html` in the current directory and opens it in your default browser.

541 

542## What the visualization shows

543 

544- **Collapsible directories**: Click folders to expand/collapse

545- **File sizes**: Displayed next to each file

546- **Colors**: Different colors for different file types

547- **Directory totals**: Shows aggregate size of each folder

548````

549 

550建立 `~/.claude/skills/codebase-visualizer/scripts/visualize.py`。此指令碼掃描目錄樹並生成一個自包含的 HTML 檔案,包含:

551 

552* 一個**摘要側邊欄**,顯示檔案計數、目錄計數、總大小和檔案類型數量

553* 一個**長條圖**,按檔案類型(按大小排名前 8)分解程式碼庫

554* 一個**可摺疊樹**,您可以在其中展開和摺疊目錄,具有顏色編碼的檔案類型指示器

555 

556該指令碼需要 Python,但僅使用內建程式庫,因此無需安裝套件:

557 

558```python expandable theme={null}

559#!/usr/bin/env python3

560"""Generate an interactive collapsible tree visualization of a codebase."""

561 

562import json

563import sys

564import webbrowser

565from pathlib import Path

566from collections import Counter

567 

568IGNORE = {'.git', 'node_modules', '__pycache__', '.venv', 'venv', 'dist', 'build'}

569 

570def scan(path: Path, stats: dict) -> dict:

571 result = {"name": path.name, "children": [], "size": 0}

572 try:

573 for item in sorted(path.iterdir()):

574 if item.name in IGNORE or item.name.startswith('.'):

575 continue

576 if item.is_file():

577 size = item.stat().st_size

578 ext = item.suffix.lower() or '(no ext)'

579 result["children"].append({"name": item.name, "size": size, "ext": ext})

580 result["size"] += size

581 stats["files"] += 1

582 stats["extensions"][ext] += 1

583 stats["ext_sizes"][ext] += size

584 elif item.is_dir():

585 stats["dirs"] += 1

586 child = scan(item, stats)

587 if child["children"]:

588 result["children"].append(child)

589 result["size"] += child["size"]

590 except PermissionError:

591 pass

592 return result

593 

594def generate_html(data: dict, stats: dict, output: Path) -> None:

595 ext_sizes = stats["ext_sizes"]

596 total_size = sum(ext_sizes.values()) or 1

597 sorted_exts = sorted(ext_sizes.items(), key=lambda x: -x[1])[:8]

598 colors = {

599 '.js': '#f7df1e', '.ts': '#3178c6', '.py': '#3776ab', '.go': '#00add8',

600 '.rs': '#dea584', '.rb': '#cc342d', '.css': '#264de4', '.html': '#e34c26',

601 '.json': '#6b7280', '.md': '#083fa1', '.yaml': '#cb171e', '.yml': '#cb171e',

602 '.mdx': '#083fa1', '.tsx': '#3178c6', '.jsx': '#61dafb', '.sh': '#4eaa25',

603 }

604 lang_bars = "".join(

605 f'<div class="bar-row"><span class="bar-label">{ext}</span>'

606 f'<div class="bar" style="width:{(size/total_size)*100}%;background:{colors.get(ext,"#6b7280")}"></div>'

607 f'<span class="bar-pct">{(size/total_size)*100:.1f}%</span></div>'

608 for ext, size in sorted_exts

609 )

610 def fmt(b):

611 if b < 1024: return f"{b} B"

612 if b < 1048576: return f"{b/1024:.1f} KB"

613 return f"{b/1048576:.1f} MB"

614 

615 html = f'''<!DOCTYPE html>

616<html><head>

617 <meta charset="utf-8"><title>Codebase Explorer</title>

618 <style>

619 body {{ font: 14px/1.5 system-ui, sans-serif; margin: 0; background: #1a1a2e; color: #eee; }}

620 .container {{ display: flex; height: 100vh; }}

621 .sidebar {{ width: 280px; background: #252542; padding: 20px; border-right: 1px solid #3d3d5c; overflow-y: auto; flex-shrink: 0; }}

622 .main {{ flex: 1; padding: 20px; overflow-y: auto; }}

623 h1 {{ margin: 0 0 10px 0; font-size: 18px; }}

624 h2 {{ margin: 20px 0 10px 0; font-size: 14px; color: #888; text-transform: uppercase; }}

625 .stat {{ display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #3d3d5c; }}

626 .stat-value {{ font-weight: bold; }}

627 .bar-row {{ display: flex; align-items: center; margin: 6px 0; }}

628 .bar-label {{ width: 55px; font-size: 12px; color: #aaa; }}

629 .bar {{ height: 18px; border-radius: 3px; }}

630 .bar-pct {{ margin-left: 8px; font-size: 12px; color: #666; }}

631 .tree {{ list-style: none; padding-left: 20px; }}

632 details {{ cursor: pointer; }}

633 summary {{ padding: 4px 8px; border-radius: 4px; }}

634 summary:hover {{ background: #2d2d44; }}

635 .folder {{ color: #ffd700; }}

636 .file {{ display: flex; align-items: center; padding: 4px 8px; border-radius: 4px; }}

637 .file:hover {{ background: #2d2d44; }}

638 .size {{ color: #888; margin-left: auto; font-size: 12px; }}

639 .dot {{ width: 8px; height: 8px; border-radius: 50%; margin-right: 8px; }}

640 </style>

641</head><body>

642 <div class="container">

643 <div class="sidebar">

644 <h1>📊 Summary</h1>

645 <div class="stat"><span>Files</span><span class="stat-value">{stats["files"]:,}</span></div>

646 <div class="stat"><span>Directories</span><span class="stat-value">{stats["dirs"]:,}</span></div>

647 <div class="stat"><span>Total size</span><span class="stat-value">{fmt(data["size"])}</span></div>

648 <div class="stat"><span>File types</span><span class="stat-value">{len(stats["extensions"])}</span></div>

649 <h2>By file type</h2>

650 {lang_bars}

651 </div>

652 <div class="main">

653 <h1>📁 {data["name"]}</h1>

654 <ul class="tree" id="root"></ul>

655 </div>

656 </div>

657 <script>

658 const data = {json.dumps(data)};

659 const colors = {json.dumps(colors)};

660 function fmt(b) {{ if (b < 1024) return b + ' B'; if (b < 1048576) return (b/1024).toFixed(1) + ' KB'; return (b/1048576).toFixed(1) + ' MB'; }}

661 function render(node, parent) {{

662 if (node.children) {{

663 const det = document.createElement('details');

664 det.open = parent === document.getElementById('root');

665 det.innerHTML = `<summary><span class="folder">📁 ${{node.name}}</span><span class="size">${{fmt(node.size)}}</span></summary>`;

666 const ul = document.createElement('ul'); ul.className = 'tree';

667 node.children.sort((a,b) => (b.children?1:0)-(a.children?1:0) || a.name.localeCompare(b.name));

668 node.children.forEach(c => render(c, ul));

669 det.appendChild(ul);

670 const li = document.createElement('li'); li.appendChild(det); parent.appendChild(li);

671 }} else {{

672 const li = document.createElement('li'); li.className = 'file';

673 li.innerHTML = `<span class="dot" style="background:${{colors[node.ext]||'#6b7280'}}"></span>${{node.name}}<span class="size">${{fmt(node.size)}}</span>`;

674 parent.appendChild(li);

675 }}

676 }}

677 data.children.forEach(c => render(c, document.getElementById('root')));

678 </script>

679</body></html>'''

680 output.write_text(html)

681 

682if __name__ == '__main__':

683 target = Path(sys.argv[1] if len(sys.argv) > 1 else '.').resolve()

684 stats = {"files": 0, "dirs": 0, "extensions": Counter(), "ext_sizes": Counter()}

685 data = scan(target, stats)

686 out = Path('codebase-map.html')

687 generate_html(data, stats, out)

688 print(f'Generated {out.absolute()}')

689 webbrowser.open(f'file://{out.absolute()}')

690```

691 

692若要測試,在任何專案中開啟 Claude Code 並詢問「Visualize this codebase.」Claude 執行指令碼、生成 `codebase-map.html` 並在您的瀏覽器中開啟它。

693 

694此模式適用於任何視覺輸出:相依性圖表、測試涵蓋範圍報告、API 文件或資料庫架構視覺化。捆綁的指令碼完成繁重工作,而 Claude 處理協調。

695 

696## 疑難排解

697 

698### Skill 未觸發

699 

700如果 Claude 在預期時不使用您的 skill:

701 

7021. 檢查描述是否包含使用者會自然說出的關鍵字

7032. 驗證 skill 是否出現在「What skills are available?」中

7043. 嘗試重新表述您的請求以更密切地匹配描述

7054. 如果 skill 是使用者可叫用的,請使用 `/skill-name` 直接叫用它

706 

707### Skill 觸發過於頻繁

708 

709如果 Claude 在您不想要時使用您的 skill:

710 

7111. 使描述更具體

7122. 如果您只想手動叫用,請新增 `disable-model-invocation: true`

713 

714### Skill 描述被截斷

715 

716Skill 描述會載入上下文,以便 Claude 知道可用的內容。所有 skill 名稱始終包含在內,但如果您有許多 skills,描述會被縮短以適應字元預算,這可能會去除 Claude 需要匹配您的請求的關鍵字。預算在上下文視窗的 1% 處動態縮放,回退為 8,000 個字元。

717 

718若要提高限制,請設定 `SLASH_COMMAND_TOOL_CHAR_BUDGET` 環境變數。或在來源處修剪描述和 `when_to_use` 文字:前置關鍵使用案例,因為每個項目的結合文字無論預算如何都限制在 1,536 個字元。

719 

720## 相關資源

721 

722* **[除錯您的設定](/zh-TW/debug-your-config)**:診斷為什麼 skill 沒有出現或觸發

723* **[Subagents](/zh-TW/sub-agents)**:委派任務給專門的代理

724* **[Plugins](/zh-TW/plugins)**:使用其他擴展功能打包和分發 skills

725* **[Hooks](/zh-TW/hooks)**:自動化工具事件周圍的工作流程

726* **[Memory](/zh-TW/memory)**:管理 CLAUDE.md 檔案以取得持久上下文

727* **[Commands](/zh-TW/commands)**:內建命令和捆綁 skills 的參考

728* **[Permissions](/zh-TW/permissions)**:控制工具和 skill 存取

slack.md +210 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Slack 中的 Claude Code

6 

7> 直接從您的 Slack 工作區委派編碼任務

8 

9Slack 中的 Claude Code 將 Claude Code 的強大功能直接帶入您的 Slack 工作區。當您提及 `@Claude` 並附帶編碼任務時,Claude 會自動檢測意圖並在網路上建立 Claude Code 工作階段,讓您無需離開團隊對話即可委派開發工作。

10 

11此整合建立在現有的 Claude for Slack 應用程式基礎上,但為編碼相關請求添加了智能路由到網路上的 Claude Code。

12 

13## 使用案例

14 

15* **錯誤調查和修復**:要求 Claude 在 Slack 頻道中報告錯誤時立即調查和修復。

16* **快速代碼審查和修改**:讓 Claude 根據團隊反饋實現小功能或重構代碼。

17* **協作調試**:當團隊討論提供關鍵背景資訊(例如錯誤重現或用戶報告)時,Claude 可以使用該資訊來指導其調試方法。

18* **並行任務執行**:在 Slack 中啟動編碼任務,同時繼續其他工作,完成時接收通知。

19 

20## 先決條件

21 

22在使用 Slack 中的 Claude Code 之前,請確保您具有以下條件:

23 

24| 要求 | 詳情 |

25| :--------------- | :--------------------------------------------------------- |

26| Claude 計畫 | Pro、Max、Team 或 Enterprise,具有 Claude Code 存取權限(高級席位) |

27| 網路上的 Claude Code | 必須啟用對[網路上的 Claude Code](/zh-TW/claude-code-on-the-web) 的存取 |

28| GitHub 帳戶 | 連接到網路上的 Claude Code,至少有一個存儲庫已驗證 |

29| Slack 驗證 | 您的 Slack 帳戶通過 Claude 應用程式連接到您的 Claude 帳戶 |

30 

31## 在 Slack 中設定 Claude Code

32 

33<Steps>

34 <Step title="在 Slack 中安裝 Claude 應用程式">

35 工作區管理員必須從 Slack 應用程式市場安裝 Claude 應用程式。訪問 [Slack 應用程式市場](https://slack.com/marketplace/A08SF47R6P4) 並點擊「Add to Slack」以開始安裝過程。

36 </Step>

37 

38 <Step title="連接您的 Claude 帳戶">

39 應用程式安裝後,驗證您的個人 Claude 帳戶:

40 

41 1. 通過點擊您的應用程式部分中的「Claude」在 Slack 中打開 Claude 應用程式

42 2. 導航到應用程式首頁標籤

43 3. 點擊「Connect」以將您的 Slack 帳戶與您的 Claude 帳戶連接

44 4. 在您的瀏覽器中完成驗證流程

45 </Step>

46 

47 <Step title="配置網路上的 Claude Code">

48 確保您的網路上的 Claude Code 已正確配置:

49 

50 * 訪問 [claude.ai/code](https://claude.ai/code) 並使用您連接到 Slack 的同一帳戶登入

51 * 如果尚未連接,請連接您的 GitHub 帳戶

52 * 驗證至少一個您希望 Claude 使用的存儲庫

53 </Step>

54 

55 <Step title="選擇您的路由模式">

56 連接帳戶後,配置 Claude 如何在 Slack 中處理您的訊息。導航到 Slack 中的 Claude 應用程式首頁以找到**路由模式**設定。

57 

58 | 模式 | 行為 |

59 | :---------- | :----------------------------------------------------------------------------------------------------- |

60 | **僅代碼** | Claude 將所有 @mentions 路由到 Claude Code 工作階段。最適合使用 Claude in Slack 專門用於開發任務的團隊。 |

61 | **代碼 + 聊天** | Claude 分析每條訊息並智能地在 Claude Code(用於編碼任務)和 Claude Chat(用於寫作、分析和一般問題)之間路由。最適合希望為所有類型工作提供單一 @Claude 入口點的團隊。 |

62 

63 <Note>

64 在代碼 + 聊天模式中,如果 Claude 將訊息路由到聊天但您想要編碼工作階段,您可以點擊「Retry as Code」以改為建立 Claude Code 工作階段。同樣,如果它被路由到代碼但您想要聊天工作階段,您可以在該執行緒中選擇該選項。

65 </Note>

66 </Step>

67</Steps>

68 

69## 工作原理

70 

71### 自動檢測

72 

73當您在 Slack 頻道或執行緒中提及 @Claude 時,Claude 會自動分析您的訊息以確定它是否是編碼任務。如果 Claude 檢測到編碼意圖,它將把您的請求路由到網路上的 Claude Code,而不是作為常規聊天助手回應。

74 

75您也可以明確告訴 Claude 將請求作為編碼任務處理,即使它沒有自動檢測到。

76 

77<Note>

78 Slack 中的 Claude Code 僅在頻道(公開或私人)中工作。它在直接訊息 (DM) 中不起作用。

79</Note>

80 

81### 背景資訊收集

82 

83**來自執行緒**:當您在執行緒中 @mention Claude 時,它會從該執行緒中的所有訊息收集背景資訊以理解完整對話。

84 

85**來自頻道**:當直接在頻道中提及時,Claude 會查看最近的頻道訊息以獲取相關背景資訊。

86 

87此背景資訊幫助 Claude 理解問題、選擇適當的存儲庫並指導其任務方法。

88 

89<Warning>

90 當在 Slack 中調用 @Claude 時,Claude 會獲得對對話背景資訊的存取權限以更好地理解您的請求。Claude 可能會遵循背景資訊中其他訊息的指示,因此用戶應確保僅在受信任的 Slack 對話中使用 Claude。

91</Warning>

92 

93### 工作階段流程

94 

951. **啟動**:您 @mention Claude 並提出編碼請求

962. **檢測**:Claude 分析您的訊息並檢測編碼意圖

973. **工作階段建立**:在 claude.ai/code 上建立新的 Claude Code 工作階段

984. **進度更新**:Claude 在工作進行時向您的 Slack 執行緒發佈狀態更新

995. **完成**:完成後,Claude @mentions 您並提供摘要和操作按鈕

1006. **審查**:點擊「View Session」以查看完整記錄,或點擊「Create PR」以開啟拉取請求

101 

102## 用戶介面元素

103 

104### 應用程式首頁

105 

106應用程式首頁標籤顯示您的連接狀態,並允許您連接或斷開您的 Claude 帳戶與 Slack 的連接。

107 

108### 訊息操作

109 

110* **View Session**:在您的瀏覽器中打開完整的 Claude Code 工作階段,您可以在其中查看所有執行的工作、繼續工作階段或提出其他請求。

111* **Create PR**:直接從工作階段的更改建立拉取請求。

112* **Retry as Code**:如果 Claude 最初作為聊天助手回應但您想要編碼工作階段,點擊此按鈕以將請求重試為 Claude Code 任務。

113* **Change Repo**:允許您選擇不同的存儲庫,如果 Claude 選擇不正確。

114 

115### 存儲庫選擇

116 

117Claude 根據您的 Slack 對話中的背景資訊自動選擇存儲庫。如果多個存儲庫可能適用,Claude 可能會顯示一個下拉菜單,允許您選擇正確的存儲庫。

118 

119## 存取和權限

120 

121### 用戶級別存取

122 

123| 存取類型 | 要求 |

124| :--------------- | :-------------------------------------------- |

125| Claude Code 工作階段 | 每個用戶在其自己的 Claude 帳戶下運行工作階段 |

126| 使用情況和速率限制 | 工作階段計入個人用戶的計畫限制 |

127| 存儲庫存取 | 用戶只能存取他們個人連接的存儲庫 |

128| 工作階段歷史記錄 | 工作階段出現在您的 Claude Code 歷史記錄中,位於 claude.ai/code |

129 

130### 工作區管理員權限

131 

132Slack 工作區管理員控制 Claude 應用程式是否可以在工作區中安裝。然後個人用戶使用他們自己的 Claude 帳戶進行驗證以使用此整合。

133 

134## 在何處可以存取什麼

135 

136**在 Slack 中**:您將看到狀態更新、完成摘要和操作按鈕。完整記錄被保留並始終可存取。

137 

138**在網路上**:完整的 Claude Code 工作階段,包含完整對話歷史記錄、所有代碼更改、文件操作以及繼續工作階段或建立拉取請求的能力。

139 

140## 最佳實踐

141 

142### 撰寫有效的請求

143 

144* **具體明確**:在相關時包括文件名、函數名或錯誤訊息。

145* **提供背景資訊**:如果從對話中不清楚,請提及存儲庫或專案。

146* **定義成功**:解釋「完成」的樣子——Claude 應該編寫測試嗎?更新文檔?建立拉取請求?

147* **使用執行緒**:在討論錯誤或功能時在執行緒中回覆,以便 Claude 可以收集完整背景資訊。

148 

149### 何時使用 Slack 與網路

150 

151**在以下情況下使用 Slack**:背景資訊已存在於 Slack 討論中、您想要非同步啟動任務或與需要可見性的隊友協作。

152 

153**直接在網路上使用**:當您需要上傳文件、想要在開發期間進行實時互動或正在處理更長、更複雜的任務時。

154 

155## 故障排除

156 

157### 工作階段未啟動

158 

1591. 驗證您的 Claude 帳戶已在 Claude 應用程式首頁中連接

1602. 檢查您是否已啟用網路上的 Claude Code 存取

1613. 確保您至少有一個 GitHub 存儲庫連接到 Claude Code

162 

163### 存儲庫未顯示

164 

1651. 在 [claude.ai/code](https://claude.ai/code) 的網路上的 Claude Code 中連接存儲庫

1662. 驗證您對該存儲庫的 GitHub 權限

1673. 嘗試斷開並重新連接您的 GitHub 帳戶

168 

169### 選擇了錯誤的存儲庫

170 

1711. 點擊「Change Repo」按鈕以選擇不同的存儲庫

1722. 在您的請求中包括存儲庫名稱以獲得更準確的選擇

173 

174### 驗證錯誤

175 

1761. 在應用程式首頁中斷開並重新連接您的 Claude 帳戶

1772. 確保您在瀏覽器中登入正確的 Claude 帳戶

1783. 檢查您的 Claude 計畫是否包括 Claude Code 存取

179 

180### 工作階段過期

181 

1821. 工作階段在網路上的 Claude Code 歷史記錄中保持可存取

1832. 您可以從 [claude.ai/code](https://claude.ai/code) 繼續或參考過去的工作階段

184 

185## 目前限制

186 

187* **僅 GitHub**:目前支持 GitHub 上的存儲庫。

188* **一次一個拉取請求**:每個工作階段可以建立一個拉取請求。

189* **速率限制適用**:工作階段使用您的個人 Claude 計畫的速率限制。

190* **需要網路存取**:用戶必須具有網路上的 Claude Code 存取;沒有它的用戶將只獲得標準 Claude 聊天回應。

191 

192## 相關資源

193 

194<CardGroup>

195 <Card title="網路上的 Claude Code" icon="globe" href="/zh-TW/claude-code-on-the-web">

196 了解更多關於網路上的 Claude Code

197 </Card>

198 

199 <Card title="Claude for Slack" icon="slack" href="https://claude.com/claude-and-slack">

200 Claude for Slack 一般文檔

201 </Card>

202 

203 <Card title="Slack 應用程式市場" icon="store" href="https://slack.com/marketplace/A08SF47R6P4">

204 從 Slack 市場安裝 Claude 應用程式

205 </Card>

206 

207 <Card title="Claude 幫助中心" icon="circle-question" href="https://support.claude.com">

208 獲取額外支援

209 </Card>

210</CardGroup>

statusline.md +1062 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 自訂您的狀態列

6 

7> 設定自訂狀態列以監控 Claude Code 中的 context window 使用情況、成本和 git 狀態

8 

9狀態列是 Claude Code 底部的可自訂列,可執行您設定的任何 shell 指令碼。它透過 stdin 接收 JSON 工作階段資料,並顯示您的指令碼列印的任何內容,為您提供 context 使用情況、成本、git 狀態或任何其他您想追蹤的內容的持久、一目瞭然的檢視。

10 

11狀態列在以下情況下很有用:

12 

13* 您想在工作時監控 context window 使用情況

14* 您需要追蹤工作階段成本

15* 您跨多個工作階段工作,需要區分它們

16* 您希望 git 分支和狀態始終可見

17 

18以下是一個[多行狀態列](#display-multiple-lines)的範例,在第一行顯示 git 資訊,在第二行顯示顏色編碼的 context 列。

19 

20<Frame>

21 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=60f11387658acc9ff75158ae85f2ac87" alt="多行狀態列,在第一行顯示模型名稱、目錄、git 分支,在第二行顯示 context 使用進度列、成本和持續時間" width="776" height="212" data-path="images/statusline-multiline.png" />

22</Frame>

23 

24本頁面介紹[設定基本狀態列](#set-up-a-status-line)、說明[資料如何從 Claude Code 流向您的指令碼](#how-status-lines-work)、列出[您可以顯示的所有欄位](#available-data),並提供[常見模式的現成範例](#examples),例如 git 狀態、成本追蹤和進度列。

25 

26## 設定狀態列

27 

28使用[`/statusline` 命令](#use-the-%2Fstatusline-command)讓 Claude Code 為您產生指令碼,或[手動建立指令碼](#manually-configure-a-status-line)並將其新增到您的設定。

29 

30### 使用 /statusline 命令

31 

32`/statusline` 命令接受描述您想顯示內容的自然語言指令。Claude Code 在 `~/.claude/` 中產生指令碼檔案並自動更新您的設定:

33 

34```text theme={null}

35/statusline show model name and context percentage with a progress bar

36```

37 

38### 手動設定狀態列

39 

40將 `statusLine` 欄位新增到您的使用者設定(`~/.claude/settings.json`,其中 `~` 是您的主目錄)或[專案設定](/zh-TW/settings#settings-files)。將 `type` 設定為 `"command"`,並將 `command` 指向指令碼路徑或內聯 shell 命令。如需建立指令碼的完整逐步說明,請參閱[逐步建立狀態列](#build-a-status-line-step-by-step)。

41 

42```json theme={null}

43{

44 "statusLine": {

45 "type": "command",

46 "command": "~/.claude/statusline.sh",

47 "padding": 2

48 }

49}

50```

51 

52`command` 欄位在 shell 中執行,因此您也可以使用內聯命令而不是指令碼檔案。此範例使用 `jq` 解析 JSON 輸入並顯示模型名稱和 context 百分比:

53 

54```json theme={null}

55{

56 "statusLine": {

57 "type": "command",

58 "command": "jq -r '\"[\\(.model.display_name)] \\(.context_window.used_percentage // 0)% context\"'"

59 }

60}

61```

62 

63可選的 `padding` 欄位為狀態列內容新增額外的水平間距(以字元為單位)。預設為 `0`。此填充是在介面的內建間距之外,因此它控制相對縮排而不是距離終端邊緣的絕對距離。

64 

65可選的 `refreshInterval` 欄位除了[事件驅動的更新](#how-status-lines-work)外,每 N 秒重新執行一次您的命令。最小值為 `1`。當您的狀態列顯示基於時間的資料(例如時鐘)或背景子代理在主工作階段閒置時變更 git 狀態時,請設定此項。保持未設定以僅在事件上執行。

66 

67可選的 `hideVimModeIndicator` 欄位會隱藏提示下方的內建 `-- INSERT --` 文字。當您的指令碼自行呈現 [`vim.mode`](#available-data) 時,請將此設定為 `true`,以便模式不會顯示兩次。

68 

69### 停用狀態列

70 

71執行 `/statusline` 並要求它移除或清除您的狀態列(例如 `/statusline delete`、`/statusline clear`、`/statusline remove it`)。您也可以手動從 settings.json 中刪除 `statusLine` 欄位。

72 

73## 逐步建立狀態列

74 

75此逐步說明透過手動建立顯示目前模型、工作目錄和 context window 使用百分比的狀態列來展示幕後發生的情況。

76 

77<Note>使用[`/statusline`](#use-the-statusline-command)和您想要的內容描述會自動為您設定所有這些。</Note>

78 

79這些範例使用 Bash 指令碼,適用於 macOS 和 Linux。在 Windows 上,請參閱 [Windows 設定](#windows-configuration)以取得 PowerShell 和 Git Bash 範例。

80 

81<Frame>

82 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-quickstart.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=696445e59ca0059213250651ad23db6b" alt="狀態列顯示模型名稱、目錄和 context 百分比" width="726" height="164" data-path="images/statusline-quickstart.png" />

83</Frame>

84 

85<Steps>

86 <Step title="建立讀取 JSON 並列印輸出的指令碼">

87 Claude Code 透過 stdin 將 JSON 資料傳送到您的指令碼。此指令碼使用 [`jq`](https://jqlang.github.io/jq/)(一個您可能需要安裝的命令列 JSON 解析器)來提取模型名稱、目錄和 context 百分比,然後列印格式化的行。

88 

89 將此儲存到 `~/.claude/statusline.sh`(其中 `~` 是您的主目錄,例如 macOS 上的 `/Users/username` 或 Linux 上的 `/home/username`):

90 

91 ```bash theme={null}

92 #!/bin/bash

93 # Read JSON data that Claude Code sends to stdin

94 input=$(cat)

95 

96 # Extract fields using jq

97 MODEL=$(echo "$input" | jq -r '.model.display_name')

98 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

99 # The "// 0" provides a fallback if the field is null

100 PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

101 

102 # Output the status line - ${DIR##*/} extracts just the folder name

103 echo "[$MODEL] 📁 ${DIR##*/} | ${PCT}% context"

104 ```

105 </Step>

106 

107 <Step title="使其可執行">

108 將指令碼標記為可執行,以便您的 shell 可以執行它:

109 

110 ```bash theme={null}

111 chmod +x ~/.claude/statusline.sh

112 ```

113 </Step>

114 

115 <Step title="新增到設定">

116 告訴 Claude Code 執行您的指令碼作為狀態列。將此設定新增到 `~/.claude/settings.json`,它將 `type` 設定為 `"command"`(意思是「執行此 shell 命令」)並將 `command` 指向您的指令碼:

117 

118 ```json theme={null}

119 {

120 "statusLine": {

121 "type": "command",

122 "command": "~/.claude/statusline.sh"

123 }

124 }

125 ```

126 

127 您的狀態列出現在介面底部。設定會自動重新載入,但變更在您與 Claude Code 的下一次互動之前不會出現。

128 </Step>

129</Steps>

130 

131## 狀態列如何運作

132 

133Claude Code 執行您的指令碼並透過 stdin 將 [JSON 工作階段資料](#available-data)傳送給它。您的指令碼讀取 JSON、提取所需內容並將文字列印到 stdout。Claude Code 顯示您的指令碼列印的任何內容。

134 

135**何時更新**

136 

137您的指令碼在每個新的助手訊息之後、權限模式變更時或 vim 模式切換時執行。更新在 300ms 處進行去抖動,這意味著快速變更會批次在一起,您的指令碼在事情穩定後執行一次。如果在您的指令碼仍在執行時觸發新的更新,則會取消進行中的執行。如果您編輯指令碼,變更在您與 Claude Code 的下一次互動觸發更新之前不會出現。

138 

139這些觸發器在主工作階段閒置時可能會安靜,例如當協調器等待背景子代理時。為了在閒置期間保持基於時間或外部來源的片段最新,請將 [`refreshInterval`](#manually-configure-a-status-line) 設定為也在固定計時器上重新執行命令。

140 

141**您的指令碼可以輸出什麼**

142 

143* **多行**:每個 `echo` 或 `print` 陳述式顯示為單獨的行。請參閱[多行範例](#display-multiple-lines)。

144* **顏色**:使用 [ANSI 逃逸碼](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors),例如 `\033[32m` 表示綠色(終端必須支援它們)。請參閱 [git 狀態範例](#git-status-with-colors)。

145* **連結**:使用 [OSC 8 逃逸序列](https://en.wikipedia.org/wiki/ANSI_escape_code#OSC)使文字可點擊(macOS 上為 Cmd+click,Windows/Linux 上為 Ctrl+click)。需要支援超連結的終端,例如 iTerm2、Kitty 或 WezTerm。請參閱[可點擊連結範例](#clickable-links)。

146 

147<Note>狀態列在本地執行,不消耗 API 令牌。在某些 UI 互動期間,它會暫時隱藏,包括自動完成建議、說明功能表和權限提示。</Note>

148 

149## 可用資料

150 

151Claude Code 透過 stdin 將以下 JSON 欄位傳送到您的指令碼:

152 

153| 欄位 | 描述 |

154| -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |

155| `model.id`, `model.display_name` | 目前的模型識別碼和顯示名稱 |

156| `cwd`, `workspace.current_dir` | 目前的工作目錄。兩個欄位包含相同的值;`workspace.current_dir` 因與 `workspace.project_dir` 一致而首選。 |

157| `workspace.project_dir` | 啟動 Claude Code 的目錄,如果工作階段期間工作目錄變更,可能與 `cwd` 不同 |

158| `workspace.added_dirs` | 透過 `/add-dir` 或 `--add-dir` 新增的其他目錄。如果未新增任何目錄,則為空陣列 |

159| `workspace.git_worktree` | 當目前目錄位於使用 `git worktree add` 建立的連結 worktree 內時的 Git worktree 名稱。在主工作樹中不存在。對任何 git worktree 都會填入,不同於 `worktree.*` 僅適用於 `--worktree` 工作階段 |

160| `cost.total_cost_usd` | 工作階段總成本(美元),在用戶端計算。可能與您的實際帳單不同 |

161| `cost.total_duration_ms` | 自工作階段開始以來的總掛鐘時間(毫秒) |

162| `cost.total_api_duration_ms` | 等待 API 回應所花費的總時間(毫秒) |

163| `cost.total_lines_added`, `cost.total_lines_removed` | 變更的程式碼行數 |

164| `context_window.total_input_tokens`, `context_window.total_output_tokens` | 整個工作階段中的累積令牌計數 |

165| `context_window.context_window_size` | 最大 context window 大小(令牌)。預設為 200000,或具有擴展 context 的模型為 1000000。 |

166| `context_window.used_percentage` | 預先計算的已使用 context window 百分比 |

167| `context_window.remaining_percentage` | 預先計算的剩餘 context window 百分比 |

168| `context_window.current_usage` | 最後一次 API 呼叫中的令牌計數,在 [context window 欄位](#context-window-fields)中描述 |

169| `exceeds_200k_tokens` | 最近 API 回應中的總令牌計數(輸入、快取和輸出令牌合併)是否超過 200k。這是一個固定閾值,與實際 context window 大小無關。 |

170| `effort.level` | 目前的推理努力等級(`low`、`medium`、`high`、`xhigh` 或 `max`)。反映即時工作階段值,包括工作階段中途的 `/effort` 變更。當目前模型不支援努力參數時不存在 |

171| `thinking.enabled` | 是否為工作階段啟用擴展思考 |

172| `rate_limits.five_hour.used_percentage`, `rate_limits.seven_day.used_percentage` | 消耗的 5 小時或 7 天速率限制的百分比,從 0 到 100 |

173| `rate_limits.five_hour.resets_at`, `rate_limits.seven_day.resets_at` | 5 小時或 7 天速率限制視窗重設時的 Unix 紀元秒數 |

174| `session_id` | 唯一的工作階段識別碼 |

175| `session_name` | 使用 `--name` 旗標或 `/rename` 設定的自訂工作階段名稱。如果未設定自訂名稱,則不存在 |

176| `transcript_path` | 對話記錄檔案的路徑 |

177| `version` | Claude Code 版本 |

178| `output_style.name` | 目前輸出樣式的名稱 |

179| `vim.mode` | 啟用 [vim 模式](/zh-TW/interactive-mode#vim-editor-mode)時的目前 vim 模式(`NORMAL`、`INSERT`、`VISUAL` 或 `VISUAL LINE`) |

180| `agent.name` | 使用 `--agent` 旗標或設定的代理設定執行時的代理名稱 |

181| `worktree.name` | 作用中 worktree 的名稱。僅在 `--worktree` 工作階段期間出現 |

182| `worktree.path` | worktree 目錄的絕對路徑 |

183| `worktree.branch` | worktree 的 Git 分支名稱(例如 `"worktree-my-feature"`)。對於基於 hook 的 worktree 不存在 |

184| `worktree.original_cwd` | Claude 進入 worktree 之前所在的目錄 |

185| `worktree.original_branch` | 進入 worktree 之前簽出的 Git 分支。對於基於 hook 的 worktree 不存在 |

186 

187<Accordion title="完整 JSON 架構">

188 您的狀態列命令透過 stdin 接收此 JSON 結構:

189 

190 ```json theme={null}

191 {

192 "cwd": "/current/working/directory",

193 "session_id": "abc123...",

194 "session_name": "my-session",

195 "transcript_path": "/path/to/transcript.jsonl",

196 "model": {

197 "id": "claude-opus-4-7",

198 "display_name": "Opus"

199 },

200 "workspace": {

201 "current_dir": "/current/working/directory",

202 "project_dir": "/original/project/directory",

203 "added_dirs": [],

204 "git_worktree": "feature-xyz"

205 },

206 "version": "2.1.90",

207 "output_style": {

208 "name": "default"

209 },

210 "cost": {

211 "total_cost_usd": 0.01234,

212 "total_duration_ms": 45000,

213 "total_api_duration_ms": 2300,

214 "total_lines_added": 156,

215 "total_lines_removed": 23

216 },

217 "context_window": {

218 "total_input_tokens": 15234,

219 "total_output_tokens": 4521,

220 "context_window_size": 200000,

221 "used_percentage": 8,

222 "remaining_percentage": 92,

223 "current_usage": {

224 "input_tokens": 8500,

225 "output_tokens": 1200,

226 "cache_creation_input_tokens": 5000,

227 "cache_read_input_tokens": 2000

228 }

229 },

230 "exceeds_200k_tokens": false,

231 "effort": {

232 "level": "high"

233 },

234 "thinking": {

235 "enabled": true

236 },

237 "rate_limits": {

238 "five_hour": {

239 "used_percentage": 23.5,

240 "resets_at": 1738425600

241 },

242 "seven_day": {

243 "used_percentage": 41.2,

244 "resets_at": 1738857600

245 }

246 },

247 "vim": {

248 "mode": "NORMAL"

249 },

250 "agent": {

251 "name": "security-reviewer"

252 },

253 "worktree": {

254 "name": "my-feature",

255 "path": "/path/to/.claude/worktrees/my-feature",

256 "branch": "worktree-my-feature",

257 "original_cwd": "/path/to/project",

258 "original_branch": "main"

259 }

260 }

261 ```

262 

263 **可能不存在的欄位**(不在 JSON 中):

264 

265 * `session_name`:僅在使用 `--name` 或 `/rename` 設定自訂名稱時出現

266 * `workspace.git_worktree`:僅當目前目錄位於連結 git worktree 內時出現

267 * `effort`:僅當目前模型支援推理努力參數時出現

268 * `vim`:僅在啟用 vim 模式時出現

269 * `agent`:僅在使用 `--agent` 旗標或設定的代理設定執行時出現

270 * `worktree`:僅在 `--worktree` 工作階段期間出現。存在時,`branch` 和 `original_branch` 對於基於 hook 的 worktree 也可能不存在

271 * `rate_limits`:僅對 Claude.ai 訂閱者(Pro/Max)在工作階段中第一次 API 回應後出現。每個視窗(`five_hour`、`seven_day`)可能獨立不存在。使用 `jq -r '.rate_limits.five_hour.used_percentage // empty'` 以優雅地處理不存在的情況。

272 

273 **可能為 `null` 的欄位**:

274 

275 * `context_window.current_usage`:在工作階段中第一次 API 呼叫之前為 `null`

276 * `context_window.used_percentage`, `context_window.remaining_percentage`:在工作階段早期可能為 `null`

277 

278 在您的指令碼中使用條件存取處理遺漏的欄位,並使用後備預設值處理 null 值。

279</Accordion>

280 

281### Context window 欄位

282 

283`context_window` 物件提供兩種追蹤 context 使用情況的方式:

284 

285* **累積總計**(`total_input_tokens`, `total_output_tokens`):整個工作階段中所有令牌的總和,用於追蹤總消耗

286* **目前使用情況**(`current_usage`):最後一次 API 呼叫中的令牌計數,使用此來取得準確的 context 百分比,因為它反映實際的 context 狀態

287 

288`current_usage` 物件包含:

289 

290* `input_tokens`:目前 context 中的輸入令牌

291* `output_tokens`:產生的輸出令牌

292* `cache_creation_input_tokens`:寫入快取的令牌

293* `cache_read_input_tokens`:從快取讀取的令牌

294 

295`used_percentage` 欄位僅從輸入令牌計算:`input_tokens + cache_creation_input_tokens + cache_read_input_tokens`。它不包括 `output_tokens`。

296 

297如果您從 `current_usage` 手動計算 context 百分比,請使用相同的僅輸入公式以符合 `used_percentage`。

298 

299`current_usage` 物件在工作階段中第一次 API 呼叫之前為 `null`。

300 

301## 範例

302 

303這些範例展示常見的狀態列模式。若要使用任何範例:

304 

3051. 將指令碼儲存到檔案,例如 `~/.claude/statusline.sh`(或 `.py`/`.js`)

3062. 使其可執行:`chmod +x ~/.claude/statusline.sh`

3073. 將路徑新增到您的[設定](#manually-configure-a-status-line)

308 

309Bash 範例使用 [`jq`](https://jqlang.github.io/jq/) 來解析 JSON。Python 和 Node.js 具有內建的 JSON 解析。

310 

311### Context window 使用情況

312 

313顯示目前模型和 context window 使用情況,帶有視覺進度列。每個指令碼從 stdin 讀取 JSON,提取 `used_percentage` 欄位,並建立一個 10 字元的列,其中填充的塊(▓)代表使用情況:

314 

315<Frame>

316 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-context-window-usage.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=15b58ab3602f036939145dde3165c6f7" alt="狀態列顯示模型名稱和帶有百分比的進度列" width="448" height="152" data-path="images/statusline-context-window-usage.png" />

317</Frame>

318 

319<CodeGroup>

320 ```bash Bash theme={null}

321 #!/bin/bash

322 # Read all of stdin into a variable

323 input=$(cat)

324 

325 # Extract fields with jq, "// 0" provides fallback for null

326 MODEL=$(echo "$input" | jq -r '.model.display_name')

327 PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

328 

329 # Build progress bar: printf -v creates a run of spaces, then

330 # ${var// /▓} replaces each space with a block character

331 BAR_WIDTH=10

332 FILLED=$((PCT * BAR_WIDTH / 100))

333 EMPTY=$((BAR_WIDTH - FILLED))

334 BAR=""

335 [ "$FILLED" -gt 0 ] && printf -v FILL "%${FILLED}s" && BAR="${FILL// /▓}"

336 [ "$EMPTY" -gt 0 ] && printf -v PAD "%${EMPTY}s" && BAR="${BAR}${PAD// /░}"

337 

338 echo "[$MODEL] $BAR $PCT%"

339 ```

340 

341 ```python Python theme={null}

342 #!/usr/bin/env python3

343 import json, sys

344 

345 # json.load reads and parses stdin in one step

346 data = json.load(sys.stdin)

347 model = data['model']['display_name']

348 # "or 0" handles null values

349 pct = int(data.get('context_window', {}).get('used_percentage', 0) or 0)

350 

351 # String multiplication builds the bar

352 filled = pct * 10 // 100

353 bar = '▓' * filled + '░' * (10 - filled)

354 

355 print(f"[{model}] {bar} {pct}%")

356 ```

357 

358 ```javascript Node.js theme={null}

359 #!/usr/bin/env node

360 // Node.js reads stdin asynchronously with events

361 let input = '';

362 process.stdin.on('data', chunk => input += chunk);

363 process.stdin.on('end', () => {

364 const data = JSON.parse(input);

365 const model = data.model.display_name;

366 // Optional chaining (?.) safely handles null fields

367 const pct = Math.floor(data.context_window?.used_percentage || 0);

368 

369 // String.repeat() builds the bar

370 const filled = Math.floor(pct * 10 / 100);

371 const bar = '▓'.repeat(filled) + '░'.repeat(10 - filled);

372 

373 console.log(`[${model}] ${bar} ${pct}%`);

374 });

375 ```

376</CodeGroup>

377 

378### Git 狀態與顏色

379 

380顯示 git 分支,帶有暫存和修改檔案的顏色編碼指示器。此指令碼使用 [ANSI 逃逸碼](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors)表示終端顏色:`\033[32m` 是綠色,`\033[33m` 是黃色,`\033[0m` 重設為預設值。

381 

382<Frame>

383 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-git-context.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=e656f34f90d1d9a1d0e220988914345f" alt="狀態列顯示模型、目錄、git 分支和暫存和修改檔案的彩色指示器" width="742" height="178" data-path="images/statusline-git-context.png" />

384</Frame>

385 

386每個指令碼檢查目前目錄是否是 git 儲存庫,計算暫存和修改檔案,並顯示顏色編碼的指示器:

387 

388<CodeGroup>

389 ```bash Bash theme={null}

390 #!/bin/bash

391 input=$(cat)

392 

393 MODEL=$(echo "$input" | jq -r '.model.display_name')

394 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

395 

396 GREEN='\033[32m'

397 YELLOW='\033[33m'

398 RESET='\033[0m'

399 

400 if git rev-parse --git-dir > /dev/null 2>&1; then

401 BRANCH=$(git branch --show-current 2>/dev/null)

402 STAGED=$(git diff --cached --numstat 2>/dev/null | wc -l | tr -d ' ')

403 MODIFIED=$(git diff --numstat 2>/dev/null | wc -l | tr -d ' ')

404 

405 GIT_STATUS=""

406 [ "$STAGED" -gt 0 ] && GIT_STATUS="${GREEN}+${STAGED}${RESET}"

407 [ "$MODIFIED" -gt 0 ] && GIT_STATUS="${GIT_STATUS}${YELLOW}~${MODIFIED}${RESET}"

408 

409 echo -e "[$MODEL] 📁 ${DIR##*/} | 🌿 $BRANCH $GIT_STATUS"

410 else

411 echo "[$MODEL] 📁 ${DIR##*/}"

412 fi

413 ```

414 

415 ```python Python theme={null}

416 #!/usr/bin/env python3

417 import json, sys, subprocess, os

418 

419 data = json.load(sys.stdin)

420 model = data['model']['display_name']

421 directory = os.path.basename(data['workspace']['current_dir'])

422 

423 GREEN, YELLOW, RESET = '\033[32m', '\033[33m', '\033[0m'

424 

425 try:

426 subprocess.check_output(['git', 'rev-parse', '--git-dir'], stderr=subprocess.DEVNULL)

427 branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True).strip()

428 staged_output = subprocess.check_output(['git', 'diff', '--cached', '--numstat'], text=True).strip()

429 modified_output = subprocess.check_output(['git', 'diff', '--numstat'], text=True).strip()

430 staged = len(staged_output.split('\n')) if staged_output else 0

431 modified = len(modified_output.split('\n')) if modified_output else 0

432 

433 git_status = f"{GREEN}+{staged}{RESET}" if staged else ""

434 git_status += f"{YELLOW}~{modified}{RESET}" if modified else ""

435 

436 print(f"[{model}] 📁 {directory} | 🌿 {branch} {git_status}")

437 except:

438 print(f"[{model}] 📁 {directory}")

439 ```

440 

441 ```javascript Node.js theme={null}

442 #!/usr/bin/env node

443 const { execSync } = require('child_process');

444 const path = require('path');

445 

446 let input = '';

447 process.stdin.on('data', chunk => input += chunk);

448 process.stdin.on('end', () => {

449 const data = JSON.parse(input);

450 const model = data.model.display_name;

451 const dir = path.basename(data.workspace.current_dir);

452 

453 const GREEN = '\x1b[32m', YELLOW = '\x1b[33m', RESET = '\x1b[0m';

454 

455 try {

456 execSync('git rev-parse --git-dir', { stdio: 'ignore' });

457 const branch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();

458 const staged = execSync('git diff --cached --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

459 const modified = execSync('git diff --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

460 

461 let gitStatus = staged ? `${GREEN}+${staged}${RESET}` : '';

462 gitStatus += modified ? `${YELLOW}~${modified}${RESET}` : '';

463 

464 console.log(`[${model}] 📁 ${dir} | 🌿 ${branch} ${gitStatus}`);

465 } catch {

466 console.log(`[${model}] 📁 ${dir}`);

467 }

468 });

469 ```

470</CodeGroup>

471 

472### 成本和持續時間追蹤

473 

474追蹤您的工作階段 API 成本和經過的時間。`cost.total_cost_usd` 欄位累積目前工作階段中所有 API 呼叫的估計成本。`cost.total_duration_ms` 欄位測量自工作階段開始以來的總經過時間,而 `cost.total_api_duration_ms` 僅追蹤等待 API 回應所花費的時間。

475 

476每個指令碼將成本格式化為貨幣,並將毫秒轉換為分鐘和秒:

477 

478<Frame>

479 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-cost-tracking.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=e3444a51fe6f3440c134bd5f1f08ad29" alt="狀態列顯示模型名稱、工作階段成本和持續時間" width="588" height="180" data-path="images/statusline-cost-tracking.png" />

480</Frame>

481 

482<CodeGroup>

483 ```bash Bash theme={null}

484 #!/bin/bash

485 input=$(cat)

486 

487 MODEL=$(echo "$input" | jq -r '.model.display_name')

488 COST=$(echo "$input" | jq -r '.cost.total_cost_usd // 0')

489 DURATION_MS=$(echo "$input" | jq -r '.cost.total_duration_ms // 0')

490 

491 COST_FMT=$(printf '$%.2f' "$COST")

492 DURATION_SEC=$((DURATION_MS / 1000))

493 MINS=$((DURATION_SEC / 60))

494 SECS=$((DURATION_SEC % 60))

495 

496 echo "[$MODEL] 💰 $COST_FMT | ⏱️ ${MINS}m ${SECS}s"

497 ```

498 

499 ```python Python theme={null}

500 #!/usr/bin/env python3

501 import json, sys

502 

503 data = json.load(sys.stdin)

504 model = data['model']['display_name']

505 cost = data.get('cost', {}).get('total_cost_usd', 0) or 0

506 duration_ms = data.get('cost', {}).get('total_duration_ms', 0) or 0

507 

508 duration_sec = duration_ms // 1000

509 mins, secs = duration_sec // 60, duration_sec % 60

510 

511 print(f"[{model}] 💰 ${cost:.2f} | ⏱️ {mins}m {secs}s")

512 ```

513 

514 ```javascript Node.js theme={null}

515 #!/usr/bin/env node

516 let input = '';

517 process.stdin.on('data', chunk => input += chunk);

518 process.stdin.on('end', () => {

519 const data = JSON.parse(input);

520 const model = data.model.display_name;

521 const cost = data.cost?.total_cost_usd || 0;

522 const durationMs = data.cost?.total_duration_ms || 0;

523 

524 const durationSec = Math.floor(durationMs / 1000);

525 const mins = Math.floor(durationSec / 60);

526 const secs = durationSec % 60;

527 

528 console.log(`[${model}] 💰 $${cost.toFixed(2)} | ⏱️ ${mins}m ${secs}s`);

529 });

530 ```

531</CodeGroup>

532 

533### 顯示多行

534 

535您的指令碼可以輸出多行以建立更豐富的顯示。每個 `echo` 陳述式在狀態區域中產生單獨的行。

536 

537<Frame>

538 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=60f11387658acc9ff75158ae85f2ac87" alt="多行狀態列,在第一行顯示模型名稱、目錄、git 分支,在第二行顯示 context 使用進度列、成本和持續時間" width="776" height="212" data-path="images/statusline-multiline.png" />

539</Frame>

540 

541此範例結合了多種技術:基於閾值的顏色(70% 以下為綠色,70-89% 為黃色,90%+ 為紅色)、進度列和 git 分支資訊。每個 `print` 或 `echo` 陳述式建立單獨的行:

542 

543<CodeGroup>

544 ```bash Bash theme={null}

545 #!/bin/bash

546 input=$(cat)

547 

548 MODEL=$(echo "$input" | jq -r '.model.display_name')

549 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

550 COST=$(echo "$input" | jq -r '.cost.total_cost_usd // 0')

551 PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

552 DURATION_MS=$(echo "$input" | jq -r '.cost.total_duration_ms // 0')

553 

554 CYAN='\033[36m'; GREEN='\033[32m'; YELLOW='\033[33m'; RED='\033[31m'; RESET='\033[0m'

555 

556 # Pick bar color based on context usage

557 if [ "$PCT" -ge 90 ]; then BAR_COLOR="$RED"

558 elif [ "$PCT" -ge 70 ]; then BAR_COLOR="$YELLOW"

559 else BAR_COLOR="$GREEN"; fi

560 

561 FILLED=$((PCT / 10)); EMPTY=$((10 - FILLED))

562 printf -v FILL "%${FILLED}s"; printf -v PAD "%${EMPTY}s"

563 BAR="${FILL// /█}${PAD// /░}"

564 

565 MINS=$((DURATION_MS / 60000)); SECS=$(((DURATION_MS % 60000) / 1000))

566 

567 BRANCH=""

568 git rev-parse --git-dir > /dev/null 2>&1 && BRANCH=" | 🌿 $(git branch --show-current 2>/dev/null)"

569 

570 echo -e "${CYAN}[$MODEL]${RESET} 📁 ${DIR##*/}$BRANCH"

571 COST_FMT=$(printf '$%.2f' "$COST")

572 echo -e "${BAR_COLOR}${BAR}${RESET} ${PCT}% | ${YELLOW}${COST_FMT}${RESET} | ⏱️ ${MINS}m ${SECS}s"

573 ```

574 

575 ```python Python theme={null}

576 #!/usr/bin/env python3

577 import json, sys, subprocess, os

578 

579 data = json.load(sys.stdin)

580 model = data['model']['display_name']

581 directory = os.path.basename(data['workspace']['current_dir'])

582 cost = data.get('cost', {}).get('total_cost_usd', 0) or 0

583 pct = int(data.get('context_window', {}).get('used_percentage', 0) or 0)

584 duration_ms = data.get('cost', {}).get('total_duration_ms', 0) or 0

585 

586 CYAN, GREEN, YELLOW, RED, RESET = '\033[36m', '\033[32m', '\033[33m', '\033[31m', '\033[0m'

587 

588 bar_color = RED if pct >= 90 else YELLOW if pct >= 70 else GREEN

589 filled = pct // 10

590 bar = '█' * filled + '░' * (10 - filled)

591 

592 mins, secs = duration_ms // 60000, (duration_ms % 60000) // 1000

593 

594 try:

595 branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True, stderr=subprocess.DEVNULL).strip()

596 branch = f" | 🌿 {branch}" if branch else ""

597 except:

598 branch = ""

599 

600 print(f"{CYAN}[{model}]{RESET} 📁 {directory}{branch}")

601 print(f"{bar_color}{bar}{RESET} {pct}% | {YELLOW}${cost:.2f}{RESET} | ⏱️ {mins}m {secs}s")

602 ```

603 

604 ```javascript Node.js theme={null}

605 #!/usr/bin/env node

606 const { execSync } = require('child_process');

607 const path = require('path');

608 

609 let input = '';

610 process.stdin.on('data', chunk => input += chunk);

611 process.stdin.on('end', () => {

612 const data = JSON.parse(input);

613 const model = data.model.display_name;

614 const dir = path.basename(data.workspace.current_dir);

615 const cost = data.cost?.total_cost_usd || 0;

616 const pct = Math.floor(data.context_window?.used_percentage || 0);

617 const durationMs = data.cost?.total_duration_ms || 0;

618 

619 const CYAN = '\x1b[36m', GREEN = '\x1b[32m', YELLOW = '\x1b[33m', RED = '\x1b[31m', RESET = '\x1b[0m';

620 

621 const barColor = pct >= 90 ? RED : pct >= 70 ? YELLOW : GREEN;

622 const filled = Math.floor(pct / 10);

623 const bar = '█'.repeat(filled) + '░'.repeat(10 - filled);

624 

625 const mins = Math.floor(durationMs / 60000);

626 const secs = Math.floor((durationMs % 60000) / 1000);

627 

628 let branch = '';

629 try {

630 branch = execSync('git branch --show-current', { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();

631 branch = branch ? ` | 🌿 ${branch}` : '';

632 } catch {}

633 

634 console.log(`${CYAN}[${model}]${RESET} 📁 ${dir}${branch}`);

635 console.log(`${barColor}${bar}${RESET} ${pct}% | ${YELLOW}$${cost.toFixed(2)}${RESET} | ⏱️ ${mins}m ${secs}s`);

636 });

637 ```

638</CodeGroup>

639 

640### 可點擊的連結

641 

642此範例建立指向您的 GitHub 儲存庫的可點擊連結。它讀取 git 遠端 URL,使用 `sed` 將 SSH 格式轉換為 HTTPS,並將儲存庫名稱包裝在 OSC 8 逃逸碼中。按住 Cmd(macOS)或 Ctrl(Windows/Linux)並點擊以在瀏覽器中開啟連結。

643 

644<Frame>

645 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-links.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=4bcc6e7deb7cf52f41ab85a219b52661" alt="狀態列顯示指向 GitHub 儲存庫的可點擊連結" width="726" height="198" data-path="images/statusline-links.png" />

646</Frame>

647 

648每個指令碼取得 git 遠端 URL,將 SSH 格式轉換為 HTTPS,並將儲存庫名稱包裝在 OSC 8 逃逸碼中。Bash 版本使用 `printf '%b'`,它比 `echo -e` 更可靠地跨不同 shell 解釋反斜杠逃逸:

649 

650<CodeGroup>

651 ```bash Bash theme={null}

652 #!/bin/bash

653 input=$(cat)

654 

655 MODEL=$(echo "$input" | jq -r '.model.display_name')

656 

657 # Convert git SSH URL to HTTPS

658 REMOTE=$(git remote get-url origin 2>/dev/null | sed 's/git@github.com:/https:\/\/github.com\//' | sed 's/\.git$//')

659 

660 if [ -n "$REMOTE" ]; then

661 REPO_NAME=$(basename "$REMOTE")

662 # OSC 8 format: \e]8;;URL\a then TEXT then \e]8;;\a

663 # printf %b interprets escape sequences reliably across shells

664 printf '%b' "[$MODEL] 🔗 \e]8;;${REMOTE}\a${REPO_NAME}\e]8;;\a\n"

665 else

666 echo "[$MODEL]"

667 fi

668 ```

669 

670 ```python Python theme={null}

671 #!/usr/bin/env python3

672 import json, sys, subprocess, re, os

673 

674 data = json.load(sys.stdin)

675 model = data['model']['display_name']

676 

677 # Get git remote URL

678 try:

679 remote = subprocess.check_output(

680 ['git', 'remote', 'get-url', 'origin'],

681 stderr=subprocess.DEVNULL, text=True

682 ).strip()

683 # Convert SSH to HTTPS format

684 remote = re.sub(r'^git@github\.com:', 'https://github.com/', remote)

685 remote = re.sub(r'\.git$', '', remote)

686 repo_name = os.path.basename(remote)

687 # OSC 8 escape sequences

688 link = f"\033]8;;{remote}\a{repo_name}\033]8;;\a"

689 print(f"[{model}] 🔗 {link}")

690 except:

691 print(f"[{model}]")

692 ```

693 

694 ```javascript Node.js theme={null}

695 #!/usr/bin/env node

696 const { execSync } = require('child_process');

697 const path = require('path');

698 

699 let input = '';

700 process.stdin.on('data', chunk => input += chunk);

701 process.stdin.on('end', () => {

702 const data = JSON.parse(input);

703 const model = data.model.display_name;

704 

705 try {

706 let remote = execSync('git remote get-url origin', { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();

707 // Convert SSH to HTTPS format

708 remote = remote.replace(/^git@github\.com:/, 'https://github.com/').replace(/\.git$/, '');

709 const repoName = path.basename(remote);

710 // OSC 8 escape sequences

711 const link = `\x1b]8;;${remote}\x07${repoName}\x1b]8;;\x07`;

712 console.log(`[${model}] 🔗 ${link}`);

713 } catch {

714 console.log(`[${model}]`);

715 }

716 });

717 ```

718</CodeGroup>

719 

720### 速率限制使用情況

721 

722在狀態列中顯示 Claude.ai 訂閱速率限制使用情況。`rate_limits` 物件包含 `five_hour`(5 小時滾動視窗)和 `seven_day`(每週)視窗。每個視窗提供 `used_percentage`(0-100)和 `resets_at`(Unix 紀元秒,視窗重設時)。

723 

724此欄位僅對 Claude.ai 訂閱者(Pro/Max)在第一次 API 回應後出現。每個指令碼優雅地處理不存在的欄位:

725 

726<CodeGroup>

727 ```bash Bash theme={null}

728 #!/bin/bash

729 input=$(cat)

730 

731 MODEL=$(echo "$input" | jq -r '.model.display_name')

732 # "// empty" produces no output when rate_limits is absent

733 FIVE_H=$(echo "$input" | jq -r '.rate_limits.five_hour.used_percentage // empty')

734 WEEK=$(echo "$input" | jq -r '.rate_limits.seven_day.used_percentage // empty')

735 

736 LIMITS=""

737 [ -n "$FIVE_H" ] && LIMITS="5h: $(printf '%.0f' "$FIVE_H")%"

738 [ -n "$WEEK" ] && LIMITS="${LIMITS:+$LIMITS }7d: $(printf '%.0f' "$WEEK")%"

739 

740 [ -n "$LIMITS" ] && echo "[$MODEL] | $LIMITS" || echo "[$MODEL]"

741 ```

742 

743 ```python Python theme={null}

744 #!/usr/bin/env python3

745 import json, sys

746 

747 data = json.load(sys.stdin)

748 model = data['model']['display_name']

749 

750 parts = []

751 rate = data.get('rate_limits', {})

752 five_h = rate.get('five_hour', {}).get('used_percentage')

753 week = rate.get('seven_day', {}).get('used_percentage')

754 

755 if five_h is not None:

756 parts.append(f"5h: {five_h:.0f}%")

757 if week is not None:

758 parts.append(f"7d: {week:.0f}%")

759 

760 if parts:

761 print(f"[{model}] | {' '.join(parts)}")

762 else:

763 print(f"[{model}]")

764 ```

765 

766 ```javascript Node.js theme={null}

767 #!/usr/bin/env node

768 let input = '';

769 process.stdin.on('data', chunk => input += chunk);

770 process.stdin.on('end', () => {

771 const data = JSON.parse(input);

772 const model = data.model.display_name;

773 

774 const parts = [];

775 const fiveH = data.rate_limits?.five_hour?.used_percentage;

776 const week = data.rate_limits?.seven_day?.used_percentage;

777 

778 if (fiveH != null) parts.push(`5h: ${Math.round(fiveH)}%`);

779 if (week != null) parts.push(`7d: ${Math.round(week)}%`);

780 

781 console.log(parts.length ? `[${model}] | ${parts.join(' ')}` : `[${model}]`);

782 });

783 ```

784</CodeGroup>

785 

786### 快取昂貴的操作

787 

788您的狀態列指令碼在活躍工作階段期間頻繁執行。`git status` 或 `git diff` 等命令可能很慢,特別是在大型儲存庫中。此範例將 git 資訊快取到臨時檔案,並且僅每 5 秒重新整理一次。

789 

790快取檔案名稱需要在工作階段內的狀態列呼叫中保持穩定,但在工作階段之間保持唯一,以便不同儲存庫中的並行工作階段不會讀取彼此的快取 git 狀態。基於程序的識別碼(如 `$$`、`os.getpid()` 或 `process.pid`)在每次呼叫時都會變更,並會破壞快取。改用 JSON 輸入中的 `session_id`:它在工作階段的生命週期內保持穩定,並且每個工作階段都是唯一的。

791 

792每個指令碼在執行 git 命令之前檢查快取檔案是否遺漏或超過 5 秒:

793 

794<CodeGroup>

795 ```bash Bash theme={null}

796 #!/bin/bash

797 input=$(cat)

798 

799 MODEL=$(echo "$input" | jq -r '.model.display_name')

800 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

801 SESSION_ID=$(echo "$input" | jq -r '.session_id')

802 

803 CACHE_FILE="/tmp/statusline-git-cache-$SESSION_ID"

804 CACHE_MAX_AGE=5 # seconds

805 

806 cache_is_stale() {

807 [ ! -f "$CACHE_FILE" ] || \

808 # stat -f %m is macOS, stat -c %Y is Linux

809 [ $(($(date +%s) - $(stat -f %m "$CACHE_FILE" 2>/dev/null || stat -c %Y "$CACHE_FILE" 2>/dev/null || echo 0))) -gt $CACHE_MAX_AGE ]

810 }

811 

812 if cache_is_stale; then

813 if git rev-parse --git-dir > /dev/null 2>&1; then

814 BRANCH=$(git branch --show-current 2>/dev/null)

815 STAGED=$(git diff --cached --numstat 2>/dev/null | wc -l | tr -d ' ')

816 MODIFIED=$(git diff --numstat 2>/dev/null | wc -l | tr -d ' ')

817 echo "$BRANCH|$STAGED|$MODIFIED" > "$CACHE_FILE"

818 else

819 echo "||" > "$CACHE_FILE"

820 fi

821 fi

822 

823 IFS='|' read -r BRANCH STAGED MODIFIED < "$CACHE_FILE"

824 

825 if [ -n "$BRANCH" ]; then

826 echo "[$MODEL] 📁 ${DIR##*/} | 🌿 $BRANCH +$STAGED ~$MODIFIED"

827 else

828 echo "[$MODEL] 📁 ${DIR##*/}"

829 fi

830 ```

831 

832 ```python Python theme={null}

833 #!/usr/bin/env python3

834 import json, sys, subprocess, os, time

835 

836 data = json.load(sys.stdin)

837 model = data['model']['display_name']

838 directory = os.path.basename(data['workspace']['current_dir'])

839 session_id = data['session_id']

840 

841 CACHE_FILE = f"/tmp/statusline-git-cache-{session_id}"

842 CACHE_MAX_AGE = 5 # seconds

843 

844 def cache_is_stale():

845 if not os.path.exists(CACHE_FILE):

846 return True

847 return time.time() - os.path.getmtime(CACHE_FILE) > CACHE_MAX_AGE

848 

849 if cache_is_stale():

850 try:

851 subprocess.check_output(['git', 'rev-parse', '--git-dir'], stderr=subprocess.DEVNULL)

852 branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True).strip()

853 staged = subprocess.check_output(['git', 'diff', '--cached', '--numstat'], text=True).strip()

854 modified = subprocess.check_output(['git', 'diff', '--numstat'], text=True).strip()

855 staged_count = len(staged.split('\n')) if staged else 0

856 modified_count = len(modified.split('\n')) if modified else 0

857 with open(CACHE_FILE, 'w') as f:

858 f.write(f"{branch}|{staged_count}|{modified_count}")

859 except:

860 with open(CACHE_FILE, 'w') as f:

861 f.write("||")

862 

863 with open(CACHE_FILE) as f:

864 branch, staged, modified = f.read().strip().split('|')

865 

866 if branch:

867 print(f"[{model}] 📁 {directory} | 🌿 {branch} +{staged} ~{modified}")

868 else:

869 print(f"[{model}] 📁 {directory}")

870 ```

871 

872 ```javascript Node.js theme={null}

873 #!/usr/bin/env node

874 const { execSync } = require('child_process');

875 const fs = require('fs');

876 const path = require('path');

877 

878 let input = '';

879 process.stdin.on('data', chunk => input += chunk);

880 process.stdin.on('end', () => {

881 const data = JSON.parse(input);

882 const model = data.model.display_name;

883 const dir = path.basename(data.workspace.current_dir);

884 const sessionId = data.session_id;

885 

886 const CACHE_FILE = `/tmp/statusline-git-cache-${sessionId}`;

887 const CACHE_MAX_AGE = 5; // seconds

888 

889 const cacheIsStale = () => {

890 if (!fs.existsSync(CACHE_FILE)) return true;

891 return (Date.now() / 1000) - fs.statSync(CACHE_FILE).mtimeMs / 1000 > CACHE_MAX_AGE;

892 };

893 

894 if (cacheIsStale()) {

895 try {

896 execSync('git rev-parse --git-dir', { stdio: 'ignore' });

897 const branch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();

898 const staged = execSync('git diff --cached --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

899 const modified = execSync('git diff --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

900 fs.writeFileSync(CACHE_FILE, `${branch}|${staged}|${modified}`);

901 } catch {

902 fs.writeFileSync(CACHE_FILE, '||');

903 }

904 }

905 

906 const [branch, staged, modified] = fs.readFileSync(CACHE_FILE, 'utf8').trim().split('|');

907 

908 if (branch) {

909 console.log(`[${model}] 📁 ${dir} | 🌿 ${branch} +${staged} ~${modified}`);

910 } else {

911 console.log(`[${model}] 📁 ${dir}`);

912 }

913 });

914 ```

915</CodeGroup>

916 

917### Windows 設定

918 

919在 Windows 上,Claude Code 透過 Git Bash 執行狀態列命令(如果已安裝 Git Bash),或在 Git Bash 不存在時透過 PowerShell 執行。若要執行 PowerShell 指令碼作為您的狀態列,請透過 `powershell` 呼叫它;這在任一 shell 中都有效:

920 

921<CodeGroup>

922 ```json settings.json theme={null}

923 {

924 "statusLine": {

925 "type": "command",

926 "command": "powershell -NoProfile -File C:/Users/username/.claude/statusline.ps1"

927 }

928 }

929 ```

930 

931 ```powershell statusline.ps1 theme={null}

932 $input_json = $input | Out-String | ConvertFrom-Json

933 $cwd = $input_json.cwd

934 $model = $input_json.model.display_name

935 $used = $input_json.context_window.used_percentage

936 $dirname = Split-Path $cwd -Leaf

937 

938 if ($used) {

939 Write-Host "$dirname [$model] ctx: $used%"

940 } else {

941 Write-Host "$dirname [$model]"

942 }

943 ```

944</CodeGroup>

945 

946或者,當已安裝 Git Bash 時,直接執行 Bash 指令碼:

947 

948<CodeGroup>

949 ```json settings.json theme={null}

950 {

951 "statusLine": {

952 "type": "command",

953 "command": "~/.claude/statusline.sh"

954 }

955 }

956 ```

957 

958 ```bash statusline.sh theme={null}

959 #!/usr/bin/env bash

960 input=$(cat)

961 cwd=$(echo "$input" | grep -o '"cwd":"[^"]*"' | cut -d'"' -f4)

962 model=$(echo "$input" | grep -o '"display_name":"[^"]*"' | cut -d'"' -f4)

963 dirname="${cwd##*[/\\]}"

964 echo "$dirname [$model]"

965 ```

966</CodeGroup>

967 

968## 子代理狀態列

969 

970`subagentStatusLine` 設定為[子代理](/zh-TW/sub-agents)面板中顯示的每個子代理呈現自訂行主體。使用它來用您自己的格式化取代預設的 `name · description · token count` 行。

971 

972```json theme={null}

973{

974 "subagentStatusLine": {

975 "type": "command",

976 "command": "~/.claude/subagent-statusline.sh"

977 }

978}

979```

980 

981命令在每個重新整理刻度上執行一次,所有可見的子代理行作為單個 JSON 物件在 stdin 上傳遞。輸入包括[基本 hook 欄位](/zh-TW/hooks#common-input-fields)加上 `columns`(可用行寬度)和 `tasks` 陣列,其中每個任務具有 `id`、`name`、`type`、`status`、`description`、`label`、`startTime`、`tokenCount`、`tokenSamples` 和 `cwd`。

982 

983將一個 JSON 行寫入 stdout,每行您想要覆蓋,形式為 `{"id": "<task id>", "content": "<row body>"}` 。`content` 字串按原樣呈現,包括 ANSI 顏色和 OSC 8 超連結。省略任務的 `id` 以保持該行的預設呈現;發出空 `content` 字串以隱藏它。

984 

985適用於 `statusLine` 的相同信任和 `disableAllHooks` 閘門也適用於此。外掛程式可以在其 [`settings.json`](/zh-TW/plugins-reference#standard-plugin-layout) 中提供預設 `subagentStatusLine`。

986 

987## 提示

988 

989* **使用模擬輸入測試**:`echo '{"model":{"display_name":"Opus"},"workspace":{"current_dir":"/home/user/project"},"context_window":{"used_percentage":25},"session_id":"test-session-abc"}' | ./statusline.sh`

990* **保持輸出簡短**:狀態列寬度有限,因此長輸出可能會被截斷或換行不當

991* **快取慢速操作**:您的指令碼在活躍工作階段期間頻繁執行,因此 `git status` 等命令可能會導致延遲。請參閱[快取範例](#cache-expensive-operations)以瞭解如何處理此問題。

992 

993社群專案如 [ccstatusline](https://github.com/sirmalloc/ccstatusline) 和 [starship-claude](https://github.com/martinemde/starship-claude) 提供具有主題和其他功能的預先建立設定。

994 

995## 疑難排解

996 

997**狀態列未出現**

998 

999* 驗證您的指令碼是否可執行:`chmod +x ~/.claude/statusline.sh`

1000* 檢查您的指令碼是否輸出到 stdout 而不是 stderr

1001* 手動執行您的指令碼以驗證它產生輸出

1002* 如果 `disableAllHooks` 在您的設定中設定為 `true`,狀態列也會被停用。移除此設定或將其設定為 `false` 以重新啟用。

1003* 執行 `claude --debug` 以記錄工作階段中第一次狀態列呼叫的結束代碼和 stderr

1004* 要求 Claude 讀取您的設定檔案並直接執行 `statusLine` 命令以顯示錯誤

1005 

1006**狀態列顯示 `--` 或空值**

1007 

1008* 欄位在第一次 API 回應完成之前可能為 `null`

1009* 在您的指令碼中使用後備(例如 jq 中的 `// 0`)處理 null 值

1010* 如果多個訊息後值仍為空,請重新啟動 Claude Code

1011 

1012**Context 百分比顯示意外值**

1013 

1014* 使用 `used_percentage` 以取得準確的 context 狀態,而不是累積總計

1015* `total_input_tokens` 和 `total_output_tokens` 在整個工作階段中累積,可能超過 context window 大小

1016* Context 百分比可能與 `/context` 輸出不同,因為每個計算時間不同

1017 

1018**OSC 8 連結不可點擊**

1019 

1020* 驗證您的終端支援 OSC 8 超連結(iTerm2、Kitty、WezTerm)

1021 

1022* Terminal.app 不支援可點擊連結

1023 

1024* 如果連結文字出現但不可點擊,Claude Code 可能未在您的終端中偵測到超連結支援。這通常會影響 Windows Terminal 和其他不在自動偵測清單中的模擬器。設定 `FORCE_HYPERLINK` 環境變數以在啟動 Claude Code 之前覆蓋偵測:

1025 

1026 ```bash theme={null}

1027 FORCE_HYPERLINK=1 claude

1028 ```

1029 

1030 在 PowerShell 中,先在目前工作階段中設定變數:

1031 

1032 ```powershell theme={null}

1033 $env:FORCE_HYPERLINK = "1"; claude

1034 ```

1035 

1036* SSH 和 tmux 工作階段可能根據設定去除 OSC 序列

1037 

1038* 如果逃逸序列顯示為文字(如 `\e]8;;`),請使用 `printf '%b'` 而不是 `echo -e` 以獲得更可靠的逃逸處理

1039 

1040**逃逸序列的顯示故障**

1041 

1042* 複雜的逃逸序列(ANSI 顏色、OSC 8 連結)如果與其他 UI 更新重疊,偶爾會導致輸出損壞

1043* 如果您看到損壞的文字,請嘗試簡化您的指令碼為純文字輸出

1044* 帶有逃逸碼的多行狀態列比單行純文字更容易出現呈現問題

1045 

1046**工作區信任必需**

1047 

1048* 狀態列命令僅在您已接受目前目錄的工作區信任對話時執行。因為 `statusLine` 執行 shell 命令,它需要與 hooks 和其他執行 shell 的設定相同的信任接受。

1049* 如果未接受信任,您將看到通知 `statusline skipped · restart to fix` 而不是您的狀態列輸出。重新啟動 Claude Code 並接受信任提示以啟用它。

1050 

1051**指令碼錯誤或掛起**

1052 

1053* 以非零代碼結束或不產生輸出的指令碼會導致狀態列變為空白

1054* 慢速指令碼會阻止狀態列更新,直到它們完成。保持指令碼快速以避免過時的輸出。

1055* 如果在慢速指令碼執行時觸發新的更新,進行中的指令碼會被取消

1056* 在設定之前使用模擬輸入獨立測試您的指令碼

1057 

1058**通知共享狀態列行**

1059 

1060* 系統通知(如 MCP 伺服器錯誤和自動更新)顯示在與您的狀態列相同行的右側。暫時性通知(例如 context-low 警告)也會在此區域循環。

1061* 啟用詳細模式會在此區域新增令牌計數器

1062* 在狹窄的終端上,這些通知可能會截斷您的狀態列輸出

sub-agents.md +1011 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 建立自訂 subagents

6 

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

8 

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

10 

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

12 

13<Note>

14 如果您需要多個代理並行工作並相互通訊,請改為參閱 [agent teams](/zh-TW/agent-teams)。Subagents 在單一工作階段內工作;agent teams 跨越多個獨立工作階段進行協調。

15</Note>

16 

17Subagents 可以幫助您:

18 

19* **保留上下文**,將探索和實現保持在主要對話之外

20* **強制執行約束**,限制 subagent 可以使用的工具

21* **跨專案重複使用配置**,使用使用者層級的 subagents

22* **專門化行為**,針對特定領域使用專注的系統提示

23* **控制成本**,將任務路由到更快、更便宜的模型,如 Haiku

24 

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

26 

27Claude Code 包括幾個內建 subagents,如 **Explore**、**Plan** 和 **general-purpose**。您也可以建立自訂 subagents 來處理特定任務。本頁涵蓋:

28 

29* [內建 subagents](#built-in-subagents)

30* [如何建立您自己的](#quickstart-create-your-first-subagent)

31* [完整配置選項](#configure-subagents)

32* [使用 subagents 的模式](#work-with-subagents)

33* [Forked subagents](#fork-the-current-conversation)

34* [範例 subagents](#example-subagents)

35 

36## 內建 subagents

37 

38Claude Code 包括內建 subagents,Claude 在適當時會自動使用。每個都繼承父對話的權限,並有額外的工具限制。

39 

40<Tabs>

41 <Tab title="Explore">

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

43 

44 * **Model**:Haiku(快速、低延遲)

45 * **Tools**:唯讀工具(拒絕存取 Write 和 Edit 工具)

46 * **Purpose**:檔案發現、程式碼搜尋、程式碼庫探索

47 

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

49 

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

51 </Tab>

52 

53 <Tab title="Plan">

54 一個研究代理,在 [plan mode](/zh-TW/common-workflows#use-plan-mode-for-safe-code-analysis) 期間使用,以在呈現計畫之前收集上下文。

55 

56 * **Model**:從主要對話繼承

57 * **Tools**:唯讀工具(拒絕存取 Write 和 Edit 工具)

58 * **Purpose**:用於規劃的程式碼庫研究

59 

60 當您處於 plan mode 且 Claude 需要理解您的程式碼庫時,它會將研究委派給 Plan subagent。這樣可以防止無限嵌套(subagents 無法產生其他 subagents),同時仍然收集必要的上下文。

61 </Tab>

62 

63 <Tab title="General-purpose">

64 一個能力強大的代理,用於需要探索和行動的複雜多步驟任務。

65 

66 * **Model**:從主要對話繼承

67 * **Tools**:所有工具

68 * **Purpose**:複雜研究、多步驟操作、程式碼修改

69 

70 當任務需要探索和修改、複雜推理來解釋結果或多個相依步驟時,Claude 會委派給 general-purpose。

71 </Tab>

72 

73 <Tab title="Other">

74 Claude Code 包括用於特定任務的其他輔助代理。這些通常會自動呼叫,因此您不需要直接使用它們。

75 

76 | Agent | Model | Claude 何時使用它 |

77 | :---------------- | :----- | :--------------------------- |

78 | statusline-setup | Sonnet | 當您執行 `/statusline` 來配置您的狀態行時 |

79 | Claude Code Guide | Haiku | 當您提出有關 Claude Code 功能的問題時 |

80 </Tab>

81</Tabs>

82 

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

84 

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

86 

87Subagents 在 Markdown 檔案中定義,具有 YAML frontmatter。您可以 [手動建立它們](#write-subagent-files) 或使用 `/agents` 命令。

88 

89本逐步指南將引導您使用 `/agents` 命令建立使用者層級的 subagent。該 subagent 審查程式碼並為程式碼庫提出改進建議。

90 

91<Steps>

92 <Step title="開啟 subagents 介面">

93 在 Claude Code 中,執行:

94 

95 ```text theme={null}

96 /agents

97 ```

98 </Step>

99 

100 <Step title="選擇位置">

101 切換到 **Library** 標籤,選擇 **Create new agent**,然後選擇 **Personal**。這會將 subagent 儲存到 `~/.claude/agents/`,以便在所有專案中使用。

102 </Step>

103 

104 <Step title="使用 Claude 生成">

105 選擇 **Generate with Claude**。出現提示時,描述 subagent:

106 

107 ```text theme={null}

108 A code improvement agent that scans files and suggests improvements

109 for readability, performance, and best practices. It should explain

110 each issue, show the current code, and provide an improved version.

111 ```

112 

113 Claude 為您生成識別碼、描述和系統提示。

114 </Step>

115 

116 <Step title="選擇工具">

117 對於唯讀審查者,取消選擇除 **Read-only tools** 之外的所有內容。如果您保持所有工具選中,subagent 將繼承主要對話可用的所有工具。

118 </Step>

119 

120 <Step title="選擇模型">

121 選擇 subagent 使用的模型。對於此範例代理,選擇 **Sonnet**,它在分析程式碼模式的能力和速度之間取得平衡。

122 </Step>

123 

124 <Step title="選擇顏色">

125 為 subagent 選擇背景顏色。這可以幫助您在 UI 中識別哪個 subagent 正在執行。

126 </Step>

127 

128 <Step title="配置記憶">

129 選擇 **User scope** 為 subagent 提供 [persistent memory directory](#enable-persistent-memory),位於 `~/.claude/agent-memory/`。Subagent 使用此目錄在對話之間累積見解,例如程式碼庫模式和重複出現的問題。如果您不希望 subagent 保留學習,請選擇 **None**。

130 </Step>

131 

132 <Step title="儲存並試用">

133 檢查配置摘要。按 `s` 或 `Enter` 儲存,或按 `e` 在編輯器中儲存並編輯檔案。Subagent 立即可用。試試看:

134 

135 ```text theme={null}

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

137 ```

138 

139 Claude 委派給您的新 subagent,它掃描程式碼庫並返回改進建議。

140 </Step>

141</Steps>

142 

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

144 

145您也可以手動建立 subagents 作為 Markdown 檔案、透過 CLI 標誌定義它們,或透過外掛程式分發它們。以下部分涵蓋所有配置選項。

146 

147## 配置 subagents

148 

149### 使用 /agents 命令

150 

151`/agents` 命令開啟用於管理 subagents 的分頁介面。**Running** 標籤顯示即時 subagents,讓您開啟或停止它們。**Library** 標籤讓您:

152 

153* 檢視所有可用的 subagents(內建、使用者、專案和外掛程式)

154* 使用引導式設定或 Claude 生成建立新的 subagents

155* 編輯現有 subagent 配置和工具存取

156* 刪除自訂 subagents

157* 查看當存在重複項時哪些 subagents 處於活動狀態

158 

159這是建立和管理 subagents 的建議方式。對於手動建立或自動化,您也可以直接新增 subagent 檔案。

160 

161若要從命令行列出所有配置的 subagents 而不啟動互動式工作階段,請執行 `claude agents`。這會按來源分組顯示代理,並指示哪些被更高優先級的定義覆蓋。

162 

163### 選擇 subagent 範圍

164 

165Subagents 是具有 YAML frontmatter 的 Markdown 檔案。根據範圍將它們儲存在不同位置。當多個 subagents 共享相同名稱時,更高優先級的位置獲勝。

166 

167| Location | Scope | Priority | 如何建立 |

168| :-------------------- | :-------- | :------- | :---------------------------------------- |

169| 受管設定 | 組織範圍 | 1(最高) | 透過 [managed settings](/zh-TW/settings) 部署 |

170| `--agents` CLI 標誌 | 目前工作階段 | 2 | 啟動 Claude Code 時傳遞 JSON |

171| `.claude/agents/` | 目前專案 | 3 | 互動式或手動 |

172| `~/.claude/agents/` | 所有您的專案 | 4 | 互動式或手動 |

173| Plugin 的 `agents/` 目錄 | 啟用外掛程式的位置 | 5(最低) | 使用 [plugins](/zh-TW/plugins) 安裝 |

174 

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

176 

177專案 subagents 是透過從目前工作目錄向上走來發現的。使用 `--add-dir` 新增的目錄 [僅授予檔案存取權限](/zh-TW/permissions#additional-directories-grant-file-access-not-configuration),不會掃描 subagents。若要跨專案共享 subagents,請使用 `~/.claude/agents/` 或 [plugin](/zh-TW/plugins)。

178 

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

180 

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

182 

183```bash theme={null}

184claude --agents '{

185 "code-reviewer": {

186 "description": "Expert code reviewer. Use proactively after code changes.",

187 "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",

188 "tools": ["Read", "Grep", "Glob", "Bash"],

189 "model": "sonnet"

190 },

191 "debugger": {

192 "description": "Debugging specialist for errors and test failures.",

193 "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes."

194 }

195}'

196```

197 

198`--agents` 標誌接受 JSON,具有與基於檔案的 subagents 相同的 [frontmatter](#supported-frontmatter-fields) 欄位:`description`、`prompt`、`tools`、`disallowedTools`、`model`、`permissionMode`、`mcpServers`、`hooks`、`maxTurns`、`skills`、`initialPrompt`、`memory`、`effort`、`background`、`isolation` 和 `color`。使用 `prompt` 作為系統提示,等同於基於檔案的 subagents 中的 markdown 主體。

199 

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

201 

202**外掛程式 subagents** 來自您已安裝的 [plugins](/zh-TW/plugins)。它們與您的自訂 subagents 一起出現在 `/agents` 中。請參閱 [外掛程式元件參考](/zh-TW/plugins-reference#agents) 以了解建立外掛程式 subagents 的詳細資訊。

203 

204<Note>

205 基於安全考慮,外掛程式 subagents 不支援 `hooks`、`mcpServers` 或 `permissionMode` frontmatter 欄位。從外掛程式載入代理時,這些欄位會被忽略。如果您需要它們,請將代理檔案複製到 `.claude/agents/` 或 `~/.claude/agents/`。您也可以在 `settings.json` 或 `settings.local.json` 中的 [`permissions.allow`](/zh-TW/settings#permission-settings) 新增規則,但這些規則適用於整個工作階段,而不僅僅是外掛程式 subagent。

206</Note>

207 

208來自任何這些範圍的 subagent 定義也可用於 [agent teams](/zh-TW/agent-teams#use-subagent-definitions-for-teammates):當產生隊友時,您可以參考 subagent 類型,隊友會使用其 `tools` 和 `model`,定義的主體作為額外指令附加到隊友的系統提示。請參閱 [agent teams](/zh-TW/agent-teams#use-subagent-definitions-for-teammates) 以了解哪些 frontmatter 欄位適用於該路徑。

209 

210### 編寫 subagent 檔案

211 

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

213 

214<Note>

215 Subagents 在工作階段開始時載入。如果您透過手動新增檔案來建立 subagent,請重新啟動您的工作階段或使用 `/agents` 立即載入它。

216</Note>

217 

218```markdown theme={null}

219---

220name: code-reviewer

221description: Reviews code for quality and best practices

222tools: Read, Glob, Grep

223model: sonnet

224---

225 

226You are a code reviewer. When invoked, analyze the code and provide

227specific, actionable feedback on quality, security, and best practices.

228```

229 

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

231 

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

233 

234#### 支援的 frontmatter 欄位

235 

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

237 

238| Field | Required | Description |

239| :---------------- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

240| `name` | Yes | 使用小寫字母和連字號的唯一識別碼 |

241| `description` | Yes | Claude 何時應委派給此 subagent |

242| `tools` | No | [Tools](#available-tools) subagent 可以使用。如果省略,繼承所有工具 |

243| `disallowedTools` | No | 要拒絕的工具,從繼承或指定的清單中移除 |

244| `model` | No | [Model](#choose-a-model) 使用:`sonnet`、`opus`、`haiku`、完整模型 ID(例如,`claude-opus-4-7`)或 `inherit`。預設為 `inherit` |

245| `permissionMode` | No | [Permission mode](#permission-modes):`default`、`acceptEdits`、`auto`、`dontAsk`、`bypassPermissions` 或 `plan`。針對 [plugin subagents](#choose-the-subagent-scope) 被忽略 |

246| `maxTurns` | No | subagent 停止前的最大代理轉數 |

247| `skills` | No | [Skills](/zh-TW/skills) 在啟動時載入到 subagent 的上下文中。注入完整技能內容,而不僅僅是可供呼叫。Subagents 不從父對話繼承技能 |

248| `mcpServers` | No | [MCP servers](/zh-TW/mcp) 可用於此 subagent。每個條目要麼是參考已配置伺服器的伺服器名稱(例如,`"slack"`),要麼是內聯定義,其中伺服器名稱為鍵,完整 [MCP server config](/zh-TW/mcp#installing-mcp-servers) 為值。針對 [plugin subagents](#choose-the-subagent-scope) 被忽略 |

249| `hooks` | No | [Lifecycle hooks](#define-hooks-for-subagents) 限定於此 subagent。針對 [plugin subagents](#choose-the-subagent-scope) 被忽略 |

250| `memory` | No | [Persistent memory scope](#enable-persistent-memory):`user`、`project` 或 `local`。啟用跨工作階段學習 |

251| `background` | No | 設定為 `true` 以始終將此 subagent 作為 [background task](#run-subagents-in-foreground-or-background) 執行。預設:`false` |

252| `effort` | No | 此 subagent 活動時的努力程度。覆蓋工作階段努力程度。預設:從工作階段繼承。選項:`low`、`medium`、`high`、`xhigh`、`max`;可用的層級取決於模型 |

253| `isolation` | No | 設定為 `worktree` 以在臨時 [git worktree](/zh-TW/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees) 中執行 subagent,為其提供儲存庫的隔離副本。如果 subagent 不進行任何更改,worktree 會自動清理 |

254| `color` | No | Subagent 在任務清單和文字中的顯示顏色。接受 `red`、`blue`、`green`、`yellow`、`purple`、`orange`、`pink` 或 `cyan` |

255| `initialPrompt` | No | 當此代理作為主工作階段代理執行時(透過 `--agent` 或 `agent` 設定),自動提交為第一個使用者轉數。[Commands](/zh-TW/commands) 和 [skills](/zh-TW/skills) 會被處理。前置於任何使用者提供的提示 |

256 

257### 選擇模型

258 

259`model` 欄位控制 subagent 使用的 [AI model](/zh-TW/model-config):

260 

261* **Model alias**:使用可用的別名之一:`sonnet`、`opus` 或 `haiku`

262* **Full model ID**:使用完整模型 ID,例如 `claude-opus-4-7` 或 `claude-sonnet-4-6`。接受與 `--model` 標誌相同的值

263* **inherit**:使用與主要對話相同的模型

264* **Omitted**:如果未指定,預設為 `inherit`(使用與主要對話相同的模型)

265 

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

267 

2681. [`CLAUDE_CODE_SUBAGENT_MODEL`](/zh-TW/model-config#environment-variables) 環境變數(如果設定)

2692. 每次呼叫的 `model` 參數

2703. Subagent 定義的 `model` frontmatter

2714. 主要對話的模型

272 

273### 控制 subagent 功能

274 

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

276 

277#### 可用工具

278 

279Subagents 可以使用 Claude Code 的任何 [internal tools](/zh-TW/tools-reference)。預設情況下,subagents 從主要對話繼承所有工具,包括 MCP 工具。

280 

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

282 

283```yaml theme={null}

284---

285name: safe-researcher

286description: Research agent with restricted capabilities

287tools: Read, Grep, Glob, Bash

288---

289```

290 

291此範例使用 `disallowedTools` 來繼承主要對話中的每個工具,除了 Write 和 Edit。Subagent 保留 Bash、MCP 工具和其他所有內容:

292 

293```yaml theme={null}

294---

295name: no-writes

296description: Inherits every tool except file writes

297disallowedTools: Write, Edit

298---

299```

300 

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

302 

303#### 限制可以產生的 subagents

304 

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

306 

307<Note>在版本 2.1.63 中,Task 工具已重新命名為 Agent。設定和代理定義中的現有 `Task(...)` 參考仍然作為別名工作。</Note>

308 

309```yaml theme={null}

310---

311name: coordinator

312description: Coordinates work across specialized agents

313tools: Agent(worker, researcher), Read, Bash

314---

315```

316 

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

318 

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

320 

321```yaml theme={null}

322tools: Agent, Read, Bash

323```

324 

325如果 `Agent` 完全從 `tools` 清單中省略,代理無法產生任何 subagents。此限制僅適用於以 `claude --agent` 作為主執行緒執行的代理。Subagents 無法產生其他 subagents,因此 `Agent(agent_type)` 在 subagent 定義中無效。

326 

327#### 將 MCP 伺服器限定於 subagent

328 

329使用 `mcpServers` 欄位為 subagent 提供對主要對話中不可用的 [MCP](/zh-TW/mcp) 伺服器的存取。此處定義的內聯伺服器在 subagent 啟動時連接,在完成時斷開連接。字串參考共享父工作階段的連接。

330 

331<Note>

332 `mcpServers` 欄位適用於代理檔案可以執行的兩個上下文:

333 

334 * 作為 subagent,透過 Agent 工具或 @-mention 產生

335 * 作為主工作階段,使用 [`--agent`](#invoke-subagents-explicitly) 或 `agent` 設定啟動

336 

337 當代理是主工作階段時,內聯伺服器定義在啟動時與來自 [`.mcp.json`](/zh-TW/mcp) 和設定檔案的伺服器一起連接。

338</Note>

339 

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

341 

342```yaml theme={null}

343---

344name: browser-tester

345description: Tests features in a real browser using Playwright

346mcpServers:

347 # Inline definition: scoped to this subagent only

348 - playwright:

349 type: stdio

350 command: npx

351 args: ["-y", "@playwright/mcp@latest"]

352 # Reference by name: reuses an already-configured server

353 - github

354---

355 

356Use the Playwright tools to navigate, screenshot, and interact with pages.

357```

358 

359內聯定義使用與 `.mcp.json` 伺服器條目相同的架構(`stdio`、`http`、`sse`、`ws`),由伺服器名稱鍵入。

360 

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

362 

363#### 權限模式

364 

365`permissionMode` 欄位控制 subagent 如何處理權限提示。Subagents 從主要對話繼承權限上下文,並可以覆蓋模式,除非父模式優先,如下所述。

366 

367| Mode | Behavior |

368| :------------------ | :-------------------------------------------------------------------------------------- |

369| `default` | 標準權限檢查,帶有提示 |

370| `acceptEdits` | 自動接受檔案編輯和工作目錄或 `additionalDirectories` 中路徑的常見檔案系統命令 |

371| `auto` | [Auto mode](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode):背景分類器審查命令和受保護目錄寫入 |

372| `dontAsk` | 自動拒絕權限提示(明確允許的工具仍然工作) |

373| `bypassPermissions` | 跳過權限提示 |

374| `plan` | Plan mode(唯讀探索) |

375 

376<Warning>

377 謹慎使用 `bypassPermissions`。它跳過權限提示,允許 subagent 執行操作而無需批准,包括寫入 `.git`、`.claude`、`.vscode`、`.idea` 和 `.husky`。根和主目錄移除(例如 `rm -rf /`)仍然會提示作為斷路器。請參閱 [permission modes](/zh-TW/permission-modes#skip-all-checks-with-bypasspermissions-mode) 以了解詳細資訊。

378</Warning>

379 

380如果父級使用 `bypassPermissions` 或 `acceptEdits`,這優先並且無法被覆蓋。如果父級使用 [auto mode](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode),subagent 繼承 auto mode,其 frontmatter 中的任何 `permissionMode` 都會被忽略:分類器使用與父工作階段相同的阻止和允許規則評估 subagent 的工具呼叫。

381 

382#### 將技能預載入 subagents

383 

384使用 `skills` 欄位在啟動時將技能內容注入到 subagent 的上下文中。這為 subagent 提供領域知識,而無需在執行期間發現和載入技能。

385 

386```yaml theme={null}

387---

388name: api-developer

389description: Implement API endpoints following team conventions

390skills:

391 - api-conventions

392 - error-handling-patterns

393---

394 

395Implement API endpoints. Follow the conventions and patterns from the preloaded skills.

396```

397 

398每個技能的完整內容被注入到 subagent 的上下文中,而不僅僅是可供呼叫。Subagents 不從父對話繼承技能;您必須明確列出它們。

399 

400您無法預載入設定 [`disable-model-invocation: true`](/zh-TW/skills#control-who-invokes-a-skill) 的技能,因為預載入來自 Claude 可以呼叫的相同技能集。如果列出的技能遺失或已停用,Claude Code 會跳過它並將警告記錄到除錯日誌。

401 

402<Note>

403 這與 [在 subagent 中執行技能](/zh-TW/skills#run-skills-in-a-subagent) 相反。使用 subagent 中的 `skills`,subagent 控制系統提示並載入技能內容。使用技能中的 `context: fork`,技能內容被注入到您指定的代理中。兩者都使用相同的基礎系統。

404</Note>

405 

406#### 啟用持久記憶

407 

408`memory` 欄位為 subagent 提供一個在對話之間存活的持久目錄。Subagent 使用此目錄隨著時間建立知識,例如程式碼庫模式、除錯見解和架構決策。

409 

410```yaml theme={null}

411---

412name: code-reviewer

413description: Reviews code for quality and best practices

414memory: user

415---

416 

417You are a code reviewer. As you review code, update your agent memory with

418patterns, conventions, and recurring issues you discover.

419```

420 

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

422 

423| Scope | Location | 使用時機 |

424| :-------- | :-------------------------------------------- | :---------------------------- |

425| `user` | `~/.claude/agent-memory/<name-of-agent>/` | subagent 應該記住跨所有專案的學習 |

426| `project` | `.claude/agent-memory/<name-of-agent>/` | subagent 的知識是特定於專案的,可透過版本控制共享 |

427| `local` | `.claude/agent-memory-local/<name-of-agent>/` | subagent 的知識是特定於專案的,但不應簽入版本控制 |

428 

429啟用記憶時:

430 

431* Subagent 的系統提示包括讀取和寫入記憶目錄的說明。

432* Subagent 的系統提示還包括記憶目錄中 `MEMORY.md` 的前 200 行或 25KB(以先到者為準),以及如果超過該限制則策劃 `MEMORY.md` 的說明。

433* Read、Write 和 Edit 工具會自動啟用,以便 subagent 可以管理其記憶檔案。

434 

435##### 持久記憶提示

436 

437* `project` 是建議的預設範圍。它使 subagent 知識可透過版本控制共享。當 subagent 的知識在所有專案中廣泛適用時使用 `user`,或當知識不應簽入版本控制時使用 `local`。

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

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

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

441 

442 ```markdown theme={null}

443 Update your agent memory as you discover codepaths, patterns, library

444 locations, and key architectural decisions. This builds up institutional

445 knowledge across conversations. Write concise notes about what you found

446 and where.

447 ```

448 

449#### 使用 hooks 的條件規則

450 

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

452 

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

454 

455```yaml theme={null}

456---

457name: db-reader

458description: Execute read-only database queries

459tools: Bash

460hooks:

461 PreToolUse:

462 - matcher: "Bash"

463 hooks:

464 - type: command

465 command: "./scripts/validate-readonly-query.sh"

466---

467```

468 

469Claude Code [透過 stdin 將 hook 輸入作為 JSON 傳遞](/zh-TW/hooks#pretooluse-input) 給 hook 命令。驗證指令碼讀取此 JSON,提取 Bash 命令,並 [以代碼 2 退出](/zh-TW/hooks#exit-code-2-behavior-per-event) 以阻止寫入操作:

470 

471```bash theme={null}

472#!/bin/bash

473# ./scripts/validate-readonly-query.sh

474 

475INPUT=$(cat)

476COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

477 

478# Block SQL write operations (case-insensitive)

479if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE)\b' > /dev/null; then

480 echo "Blocked: Only SELECT queries are allowed" >&2

481 exit 2

482fi

483 

484exit 0

485```

486 

487請參閱 [Hook input](/zh-TW/hooks#pretooluse-input) 以了解完整的輸入架構,以及 [exit codes](/zh-TW/hooks#exit-code-output) 以了解退出代碼如何影響行為。

488 

489#### 禁用特定 subagents

490 

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

492 

493```json theme={null}

494{

495 "permissions": {

496 "deny": ["Agent(Explore)", "Agent(my-custom-agent)"]

497 }

498}

499```

500 

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

502 

503```bash theme={null}

504claude --disallowedTools "Agent(Explore)"

505```

506 

507請參閱 [Permissions documentation](/zh-TW/permissions#tool-specific-permission-rules) 以了解有關權限規則的更多詳細資訊。

508 

509### 為 subagents 定義 hooks

510 

511Subagents 可以定義在 subagent 生命週期期間執行的 [hooks](/zh-TW/hooks)。有兩種方式來配置 hooks:

512 

5131. **在 subagent 的 frontmatter 中**:定義只在該 subagent 活動時執行的 hooks

5142. **在 `settings.json` 中**:定義在 subagents 啟動或停止時在主工作階段中執行的 hooks

515 

516#### Subagent frontmatter 中的 Hooks

517 

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

519 

520<Note>

521 Frontmatter hooks 在代理透過 Agent 工具或 @-mention 作為 subagent 產生時觸發,以及當代理透過 [`--agent`](#invoke-subagents-explicitly) 或 `agent` 設定作為主工作階段執行時觸發。在主工作階段情況下,它們與在 [`settings.json`](/zh-TW/hooks) 中定義的任何 hooks 一起執行。

522</Note>

523 

524支援所有 [hook events](/zh-TW/hooks#hook-events)。subagents 最常見的事件是:

525 

526| Event | Matcher input | 何時觸發 |

527| :------------ | :------------ | :------------------------------------- |

528| `PreToolUse` | Tool name | 在 subagent 使用工具之前 |

529| `PostToolUse` | Tool name | 在 subagent 使用工具之後 |

530| `Stop` | (none) | 當 subagent 完成時(在執行時轉換為 `SubagentStop`) |

531 

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

533 

534```yaml theme={null}

535---

536name: code-reviewer

537description: Review code changes with automatic linting

538hooks:

539 PreToolUse:

540 - matcher: "Bash"

541 hooks:

542 - type: command

543 command: "./scripts/validate-command.sh $TOOL_INPUT"

544 PostToolUse:

545 - matcher: "Edit|Write"

546 hooks:

547 - type: command

548 command: "./scripts/run-linter.sh"

549---

550```

551 

552Frontmatter 中的 `Stop` hooks 會自動轉換為 `SubagentStop` 事件。

553 

554#### 用於 subagent 事件的專案層級 hooks

555 

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

557 

558| Event | Matcher input | 何時觸發 |

559| :-------------- | :-------------- | :--------------- |

560| `SubagentStart` | Agent type name | 當 subagent 開始執行時 |

561| `SubagentStop` | Agent type name | 當 subagent 完成時 |

562 

563兩個事件都支援匹配器以按名稱針對特定代理類型。此範例僅在 `db-agent` subagent 啟動時執行設定指令碼,並在任何 subagent 停止時執行清理指令碼:

564 

565```json theme={null}

566{

567 "hooks": {

568 "SubagentStart": [

569 {

570 "matcher": "db-agent",

571 "hooks": [

572 { "type": "command", "command": "./scripts/setup-db-connection.sh" }

573 ]

574 }

575 ],

576 "SubagentStop": [

577 {

578 "hooks": [

579 { "type": "command", "command": "./scripts/cleanup-db-connection.sh" }

580 ]

581 }

582 ]

583 }

584}

585```

586 

587請參閱 [Hooks](/zh-TW/hooks) 以了解完整的 hook 配置格式。

588 

589## 使用 subagents

590 

591### 理解自動委派

592 

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

594 

595### 明確呼叫 subagents

596 

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

598 

599* **自然語言**:在提示中命名 subagent;Claude 決定是否委派

600* **@-mention**:保證 subagent 為一個任務執行

601* **工作階段範圍**:整個工作階段使用該 subagent 的系統提示、工具限制和模型,透過 `--agent` 標誌或 `agent` 設定

602 

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

604 

605```text theme={null}

606Use the test-runner subagent to fix failing tests

607Have the code-reviewer subagent look at my recent changes

608```

609 

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

611 

612```text theme={null}

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

614```

615 

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

617 

618由啟用的 [plugin](/zh-TW/plugins) 提供的 Subagents 在預輸入中顯示為 `<plugin-name>:<agent-name>`。名為背景 subagents 目前在工作階段中執行也出現在預輸入中,在名稱旁邊顯示其狀態。您也可以手動輸入提及而不使用選擇器:`@agent-<name>` 用於本地 subagents,或 `@agent-<plugin-name>:<agent-name>` 用於外掛程式 subagents。

619 

620**將整個工作階段作為 subagent 執行。** 傳遞 [`--agent <name>`](/zh-TW/cli-reference) 以啟動一個工作階段,其中主執行緒本身採用該 subagent 的系統提示、工具限制和模型:

621 

622```bash theme={null}

623claude --agent code-reviewer

624```

625 

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

627 

628這適用於內建和自訂 subagents,選擇在您恢復工作階段時持續。

629 

630對於外掛程式提供的 subagent,傳遞限定名稱:`claude --agent <plugin-name>:<agent-name>`。

631 

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

633 

634```json theme={null}

635{

636 "agent": "code-reviewer"

637}

638```

639 

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

641 

642### 在前景或背景中執行 subagents

643 

644Subagents 可以在前景(阻止)或背景(並行)中執行:

645 

646* **前景 subagents** 阻止主要對話直到完成。權限提示和澄清問題(如 [`AskUserQuestion`](/zh-TW/tools-reference))會傳遞給您。

647* **背景 subagents** 在您繼續工作時並行執行。啟動前,Claude Code 會提示輸入 subagent 需要的任何工具權限,確保它具有必要的批准。執行後,subagent 繼承這些權限並自動拒絕任何未預先批准的內容。如果背景 subagent 需要提出澄清問題,該工具呼叫失敗,但 subagent 繼續。

648 

649如果背景 subagent 因權限遺失而失敗,您可以啟動一個新的前景 subagent 執行相同任務以使用互動式提示重試。

650 

651Claude 根據任務決定是否在前景或背景中執行 subagents。您也可以:

652 

653* 要求 Claude "run this in the background"

654* 按 **Ctrl+B** 將執行中的任務放在背景中

655 

656若要禁用所有背景任務功能,請將 `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` 環境變數設定為 `1`。請參閱 [Environment variables](/zh-TW/env-vars)。

657 

658當 [fork mode](#fork-the-current-conversation) 啟用時,每個 subagent 產生都在背景中執行,無論 `background` 欄位如何。Forks 仍然在您的終端中出現權限提示,而不是預先批准;命名 subagents 遵循上述預先批准流程。

659 

660### 常見模式

661 

662#### 隔離高容量操作

663 

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

665 

666```text theme={null}

667Use a subagent to run the test suite and report only the failing tests with their error messages

668```

669 

670#### 執行並行研究

671 

672對於獨立調查,產生多個 subagents 以同時工作:

673 

674```text theme={null}

675Research the authentication, database, and API modules in parallel using separate subagents

676```

677 

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

679 

680<Warning>

681 當 subagents 完成時,其結果返回到主要對話。執行許多 subagents,每個都返回詳細結果,可能會消耗大量上下文。

682</Warning>

683 

684對於需要持續並行性或超過上下文視窗的任務,[agent teams](/zh-TW/agent-teams) 為每個工作者提供自己的獨立上下文。

685 

686#### 鏈接 subagents

687 

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

689 

690```text theme={null}

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

692```

693 

694### 在 subagents 和主要對話之間選擇

695 

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

697 

698* 任務需要頻繁的來回或反覆改進

699* 多個階段共享重要上下文(規劃 → 實現 → 測試)

700* 您正在進行快速、有針對性的更改

701* 延遲很重要。Subagents 從頭開始,可能需要時間收集上下文

702 

703在以下情況下使用 **subagents**:

704 

705* 任務產生您不需要在主要上下文中的詳細輸出

706* 您想強制執行特定的工具限制或權限

707* 工作是自包含的,可以返回摘要

708 

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

710 

711對於關於對話中已有內容的快速問題,請使用 [`/btw`](/zh-TW/interactive-mode#side-questions-with-%2Fbtw) 而不是 subagent。它看到您的完整上下文,但沒有工具存取,答案被丟棄而不是新增到歷史記錄。

712 

713<Note>

714 Subagents 無法產生其他 subagents。如果您的工作流程需要嵌套委派,請使用 [Skills](/zh-TW/skills) 或從主要對話 [鏈接 subagents](#chain-subagents)。

715</Note>

716 

717### 管理 subagent 上下文

718 

719#### 恢復 subagents

720 

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

722 

723恢復的 subagents 保留其完整對話歷史記錄,包括所有先前的工具呼叫、結果和推理。Subagent 從停止的地方精確繼續,而不是從頭開始。

724 

725當 subagent 完成時,Claude 接收其代理 ID。Claude 使用 `SendMessage` 工具,將代理的 ID 作為 `to` 欄位來恢復它。`SendMessage` 工具僅在透過 `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` 啟用 [agent teams](/zh-TW/agent-teams) 時可用。

726 

727若要恢復 subagent,請要求 Claude 繼續先前的工作:

728 

729```text theme={null}

730Use the code-reviewer subagent to review the authentication module

731[Agent completes]

732 

733Continue that code review and now analyze the authorization logic

734[Claude resumes the subagent with full context from previous conversation]

735```

736 

737如果停止的 subagent 接收 `SendMessage`,它會自動在背景中恢復,無需新的 `Agent` 呼叫。

738 

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

740 

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

742 

743* **主要對話壓縮**:當主要對話壓縮時,subagent 文字不受影響。它們儲存在單獨的檔案中。

744* **工作階段持續性**:Subagent 文字在其工作階段內持續存在。您可以透過恢復相同工作階段在重新啟動 Claude Code 後 [恢復 subagent](#resume-subagents)。

745* **自動清理**:文字根據 `cleanupPeriodDays` 設定進行清理(預設:30 天)。

746 

747#### 自動壓縮

748 

749Subagents 支援使用與主要對話相同的邏輯進行自動壓縮。預設情況下,自動壓縮在大約 95% 容量時觸發。若要更早觸發壓縮,請將 `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` 設定為較低的百分比(例如,`50`)。請參閱 [environment variables](/zh-TW/env-vars) 以了解詳細資訊。

750 

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

752 

753```json theme={null}

754{

755 "type": "system",

756 "subtype": "compact_boundary",

757 "compactMetadata": {

758 "trigger": "auto",

759 "preTokens": 167189

760 }

761}

762```

763 

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

765 

766## Fork 目前的對話

767 

768<Note>

769 Forked subagents 是實驗性的,需要 Claude Code v2.1.117 或更新版本。行為和配置可能在未來版本中變更。透過將 [`CLAUDE_CODE_FORK_SUBAGENT`](/zh-TW/env-vars) 環境變數設定為 `1` 來啟用它們。該變數在互動模式中以及透過 SDK 或 `claude -p` 被接受。

770</Note>

771 

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

773 

774啟用 fork mode 以三種方式改變 Claude Code:

775 

776* Claude 在它否則會使用 [general-purpose](#built-in-subagents) subagent 時產生 fork。命名 subagents,如 Explore 仍然像以前一樣產生。

777* 每個 subagent 產生都在 [background](#run-subagents-in-foreground-or-background) 中執行,無論它是 fork 還是命名 subagent。設定 `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` 為 `1` 以保持產生同步。

778* `/fork` 命令產生 fork 而不是充當 [`/branch`](/zh-TW/commands) 的別名。

779 

780您可以使用 `/fork` 後跟指令自己啟動 fork。Claude Code 從指令的前幾個詞命名 fork。以下範例 forks 對話以在您在主工作階段中繼續實現時草擬測試案例:

781 

782```text theme={null}

783/fork draft unit tests for the parser changes so far

784```

785 

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

787 

788### 觀察和引導執行中的 forks

789 

790執行中的 forks 出現在提示輸入下方的面板中,主工作階段有一行,每個 fork 有一行。使用這些鍵與面板互動:

791 

792| Key | Action |

793| :-------- | :----------------------- |

794| `↑` / `↓` | 在行之間移動 |

795| `Enter` | 開啟選定 fork 的文字記錄並向其發送後續訊息 |

796| `x` | 關閉完成的 fork 或停止執行中的 fork |

797| `Esc` | 將焦點返回到提示輸入 |

798 

799### Forks 與命名 subagents 的區別

800 

801Fork 繼承主工作階段在產生時擁有的所有內容。命名 subagent 從自己的定義開始。

802 

803| | Fork | 命名 subagent |

804| :----------- | :--------- | :--------------------------------------------------------------------- |

805| Context | 完整對話歷史記錄 | 新鮮上下文,帶有您傳遞的提示 |

806| 系統提示和工具 | 與主工作階段相同 | 來自 subagent 的 [definition file](#write-subagent-files) |

807| Model | 與主工作階段相同 | 來自 subagent 的 `model` 欄位 |

808| Permissions | 提示出現在您的終端中 | [Pre-approved](#run-subagents-in-foreground-or-background) 在啟動前,然後自動拒絕 |

809| Prompt cache | 與主工作階段共享 | 單獨的快取 |

810 

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

812 

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

814 

815### 限制

816 

817設定 `CLAUDE_CODE_FORK_SUBAGENT=1` 在互動式工作階段、[non-interactive mode](/zh-TW/headless) 和 Agent SDK 中啟用 fork mode。Fork 無法產生進一步的 forks。

818 

819## 範例 subagents

820 

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

822 

823<Tip>

824 **最佳實踐:**

825 

826 * **設計專注的 subagents:** 每個 subagent 應該在一個特定任務上表現出色

827 * **寫詳細的描述:** Claude 使用描述來決定何時委派

828 * **限制工具存取:** 僅授予必要的權限以確保安全和專注

829 * **簽入版本控制:** 與您的團隊共享專案 subagents

830</Tip>

831 

832### 程式碼審查者

833 

834一個唯讀 subagent,審查程式碼而不修改它。此範例展示如何設計一個具有有限工具存取(無 Edit 或 Write)和詳細提示的專注 subagent,該提示明確指定要查找的內容以及如何格式化輸出。

835 

836```markdown theme={null}

837---

838name: code-reviewer

839description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.

840tools: Read, Grep, Glob, Bash

841model: inherit

842---

843 

844You are a senior code reviewer ensuring high standards of code quality and security.

845 

846When invoked:

8471. Run git diff to see recent changes

8482. Focus on modified files

8493. Begin review immediately

850 

851Review checklist:

852- Code is clear and readable

853- Functions and variables are well-named

854- No duplicated code

855- Proper error handling

856- No exposed secrets or API keys

857- Input validation implemented

858- Good test coverage

859- Performance considerations addressed

860 

861Provide feedback organized by priority:

862- Critical issues (must fix)

863- Warnings (should fix)

864- Suggestions (consider improving)

865 

866Include specific examples of how to fix issues.

867```

868 

869### 除錯器

870 

871一個可以分析和修復問題的 subagent。與程式碼審查者不同,這個包括 Edit,因為修復錯誤需要修改程式碼。提示提供了從診斷到驗證的清晰工作流程。

872 

873```markdown theme={null}

874---

875name: debugger

876description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.

877tools: Read, Edit, Bash, Grep, Glob

878---

879 

880You are an expert debugger specializing in root cause analysis.

881 

882When invoked:

8831. Capture error message and stack trace

8842. Identify reproduction steps

8853. Isolate the failure location

8864. Implement minimal fix

8875. Verify solution works

888 

889Debugging process:

890- Analyze error messages and logs

891- Check recent code changes

892- Form and test hypotheses

893- Add strategic debug logging

894- Inspect variable states

895 

896For each issue, provide:

897- Root cause explanation

898- Evidence supporting the diagnosis

899- Specific code fix

900- Testing approach

901- Prevention recommendations

902 

903Focus on fixing the underlying issue, not the symptoms.

904```

905 

906### 資料科學家

907 

908一個用於資料分析工作的特定領域 subagent。此範例展示如何為典型編碼任務之外的專門工作流程建立 subagents。它明確設定 `model: sonnet` 以進行更有能力的分析。

909 

910```markdown theme={null}

911---

912name: data-scientist

913description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries.

914tools: Bash, Read, Write

915model: sonnet

916---

917 

918You are a data scientist specializing in SQL and BigQuery analysis.

919 

920When invoked:

9211. Understand the data analysis requirement

9222. Write efficient SQL queries

9233. Use BigQuery command line tools (bq) when appropriate

9244. Analyze and summarize results

9255. Present findings clearly

926 

927Key practices:

928- Write optimized SQL queries with proper filters

929- Use appropriate aggregations and joins

930- Include comments explaining complex logic

931- Format results for readability

932- Provide data-driven recommendations

933 

934For each analysis:

935- Explain the query approach

936- Document any assumptions

937- Highlight key findings

938- Suggest next steps based on data

939 

940Always ensure queries are efficient and cost-effective.

941```

942 

943### 資料庫查詢驗證器

944 

945一個允許 Bash 存取但驗證命令以僅允許唯讀 SQL 查詢的 subagent。此範例展示如何在需要比 `tools` 欄位提供的更精細控制時使用 `PreToolUse` hooks。

946 

947```markdown theme={null}

948---

949name: db-reader

950description: Execute read-only database queries. Use when analyzing data or generating reports.

951tools: Bash

952hooks:

953 PreToolUse:

954 - matcher: "Bash"

955 hooks:

956 - type: command

957 command: "./scripts/validate-readonly-query.sh"

958---

959 

960You are a database analyst with read-only access. Execute SELECT queries to answer questions about the data.

961 

962When asked to analyze data:

9631. Identify which tables contain the relevant data

9642. Write efficient SELECT queries with appropriate filters

9653. Present results clearly with context

966 

967You cannot modify data. If asked to INSERT, UPDATE, DELETE, or modify schema, explain that you only have read access.

968```

969 

970Claude Code [透過 stdin 將 hook 輸入作為 JSON 傳遞](/zh-TW/hooks#pretooluse-input) 給 hook 命令。驗證指令碼讀取此 JSON,提取正在執行的命令,並根據 SQL 寫入操作清單檢查它。如果檢測到寫入操作,指令碼 [以代碼 2 退出](/zh-TW/hooks#exit-code-2-behavior-per-event) 以阻止執行並透過 stderr 向 Claude 返回錯誤訊息。

971 

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

973 

974```bash theme={null}

975#!/bin/bash

976# Blocks SQL write operations, allows SELECT queries

977 

978# Read JSON input from stdin

979INPUT=$(cat)

980 

981# Extract the command field from tool_input using jq

982COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

983 

984if [ -z "$COMMAND" ]; then

985 exit 0

986fi

987 

988# Block write operations (case-insensitive)

989if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE|REPLACE|MERGE)\b' > /dev/null; then

990 echo "Blocked: Write operations not allowed. Use SELECT queries only." >&2

991 exit 2

992fi

993 

994exit 0

995```

996 

997使指令碼可執行:

998 

999```bash theme={null}

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

1001```

1002 

1003Hook 透過 stdin 接收 JSON,Bash 命令在 `tool_input.command` 中。退出代碼 2 阻止操作並將錯誤訊息反饋給 Claude。請參閱 [Hooks](/zh-TW/hooks#exit-code-output) 以了解退出代碼詳細資訊,以及 [Hook input](/zh-TW/hooks#pretooluse-input) 以了解完整的輸入架構。

1004 

1005## 後續步驟

1006 

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

1008 

1009* [使用外掛程式分發 subagents](/zh-TW/plugins) 以跨團隊或專案共享 subagents

1010* [以程式方式執行 Claude Code](/zh-TW/headless) 使用 Agent SDK 進行 CI/CD 和自動化

1011* [使用 MCP 伺服器](/zh-TW/mcp) 為 subagents 提供對外部工具和資料的存取

terminal-config.md +307 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 為 Claude Code 配置您的終端機

6 

7> 修復 Shift+Enter 以插入換行符、在 Claude 完成時獲得終端機鈴聲、配置 tmux、匹配色彩主題,以及在 Claude Code CLI 中啟用 Vim 模式。

8 

9Claude Code 在任何終端機中都可以無需配置而運作。此頁面適用於當某些特定功能的行為不符合您的預期時。在下方找到您的症狀。如果一切已經感覺正確,您不需要此頁面。

10 

11* [Shift+Enter 提交而不是插入換行符](#enter-multiline-prompts)

12* [Option 鍵快捷鍵在 macOS 上無效](#enable-option-key-shortcuts-on-macos)

13* [Claude 完成時沒有聲音或警報](#get-a-terminal-bell-or-notification)

14* [您在 tmux 內執行 Claude Code](#configure-tmux)

15* [顯示閃爍或捲動位置跳躍](#switch-to-fullscreen-rendering)

16* [您想在提示中使用 Vim 快捷鍵](#edit-prompts-with-vim-keybindings)

17 

18此頁面是關於讓您的終端機向 Claude Code 發送正確的信號。若要更改 Claude Code 本身回應的快捷鍵,請改為參閱[快捷鍵](/zh-TW/keybindings)。

19 

20## 輸入多行提示

21 

22按 Enter 提交您的訊息。若要在不提交的情況下新增換行符,請按 Ctrl+J,或輸入 `\` 然後按 Enter。兩者都在每個終端機中無需設置即可運作。

23 

24在大多數終端機中,您也可以按 Shift+Enter,但支援因終端機模擬器而異:

25 

26| 終端機 | Shift+Enter 用於換行符 |

27| :------------------------------------------------------------------------- | :--------------------------- |

28| Ghostty、Kitty、iTerm2、WezTerm、Warp、Apple Terminal | 無需設置即可運作 |

29| VS Code、Cursor、Windsurf、Alacritty、Zed | 執行一次 `/terminal-setup` |

30| Windows Terminal、gnome-terminal、JetBrains IDE(例如 PyCharm 和 Android Studio) | 不可用;使用 Ctrl+J 或 `\` 然後 Enter |

31 

32對於 VS Code、Cursor、Windsurf、Alacritty 和 Zed,`/terminal-setup` 將 Shift+Enter 和其他快捷鍵寫入終端機的配置檔案。在 VS Code、Cursor 和 Windsurf 中,它也會在編輯器設定中設定 `terminal.integrated.mouseWheelScrollSensitivity`,以在[全螢幕模式](/zh-TW/fullscreen)中實現更平順的滾動。現有的綁定和設定會保留在原位;如果您看到類似 `VSCode terminal Shift+Enter key binding already configured` 的訊息,則未進行任何變更。直接在主機終端機中執行 `/terminal-setup` 而不是在 tmux 或 screen 內,因為它需要寫入主機終端機的配置。

33 

34如果您在 tmux 內執行,即使外部終端機支援,Shift+Enter 也需要下面的 [tmux 配置](#configure-tmux)。

35 

36若要將換行符綁定到不同的快捷鍵,或交換行為使 Enter 插入換行符而 Shift+Enter 提交,請在您的[快捷鍵檔案](/zh-TW/keybindings)中對應 `chat:newline` 和 `chat:submit` 動作。

37 

38## 在 macOS 上啟用 Option 快捷鍵

39 

40某些 Claude Code 快捷鍵使用 Option 快捷鍵,例如 Option+Enter 用於換行符或 Option+P 用於切換模型。在 macOS 上,大多數終端機預設不會將 Option 作為修飾符發送,因此這些快捷鍵在您啟用它之前無法運作。終端機設定通常標記為「使用 Option 作為 Meta 快捷鍵」;Meta 是現在標記為 Option 或 Alt 的快捷鍵的歷史 Unix 名稱。

41 

42<Tabs>

43 <Tab title="Apple Terminal">

44 開啟設定 → 設定檔 → 鍵盤並勾選'使用 Option 作為 Meta 快捷鍵'。

45 

46 如果您接受了 Claude Code 的首次執行提示,該提示提供'Option+Enter 用於換行符和視覺鈴聲',這已經完成。該提示為您執行 `/terminal-setup`,它在您的 Apple Terminal 設定檔中啟用 Option 作為 Meta 並將音訊鈴聲切換為視覺螢幕閃爍。

47 </Tab>

48 

49 <Tab title="iTerm2">

50 開啟設定 → 設定檔 → 快捷鍵 → 一般並將左 Option 快捷鍵和右 Option 快捷鍵設置為「Esc+」。

51 

52 在 iTerm2 中執行 `/terminal-setup` 會在設定 → 一般 → 選取範圍下啟用「終端機中的應用程式可以存取剪貼簿」,以便 `/copy` 命令可以寫入您的系統剪貼簿。該命令即使在 tmux 內執行時也能偵測 iTerm2。重新啟動 iTerm2 以使變更生效。

53 </Tab>

54 

55 <Tab title="VS Code">

56 將 `"terminal.integrated.macOptionIsMeta": true` 新增至您的 VS Code 設定。

57 </Tab>

58</Tabs>

59 

60對於 Ghostty、Kitty 和其他終端機,請在終端機的配置檔案中尋找 Option-as-Alt 或 Option-as-Meta 設定。

61 

62## 獲得終端機鈴聲或通知

63 

64當 Claude 完成工作或暫停以進行權限提示時,它會觸發通知事件。將其顯示為終端機鈴聲或桌面通知可讓您在長工作執行時切換到其他工作。

65 

66Claude Code 預設僅在 Ghostty、Kitty 和 iTerm2 中發送桌面通知。在其他終端機中,將 [`preferredNotifChannel`](/zh-TW/settings#available-settings) 設定為 `"terminal_bell"` 以改為響起終端機鈴聲,或配置[通知 hook](#play-a-sound-with-a-notification-hook) 以獲得自訂聲音或命令。

67 

68桌面通知透過 SSH 到達您的本機,因此遠端工作階段仍然可以提醒您。Ghostty 和 Kitty 無需進一步設置即可將其轉發到您的 OS 通知中心。iTerm2 要求您啟用轉發:

69 

70<Steps>

71 <Step title="開啟 iTerm2 通知設定">

72 前往設定 → 設定檔 → 終端機。

73 </Step>

74 

75 <Step title="啟用警報">

76 勾選「通知中心警報」,然後點擊「篩選警報」並啟用「傳送逃脫序列產生的警報」。

77 </Step>

78</Steps>

79 

80如果通知仍未出現,請確認您的終端機應用程式在您的 OS 設定中具有通知權限,如果您在 tmux 內執行,請[啟用通過](#configure-tmux)。

81 

82### 使用通知 hook 播放聲音

83 

84在任何終端機中,您可以配置[通知 hook](/zh-TW/hooks-guide#get-notified-when-claude-needs-input) 以在 Claude 需要您的注意時播放聲音或執行自訂命令。Hooks 與內建通知一起執行,而不是替代它,因此不會收到桌面通知的終端機(例如 Warp 或 VS Code 整合終端機)可以使用 hook 或將 `preferredNotifChannel` 設定為 `"terminal_bell"` 代替。

85 

86下面的範例在 macOS 上播放系統聲音。連結的指南包含 macOS、Linux 和 Windows 的桌面通知命令。

87 

88```json ~/.claude/settings.json theme={null}

89{

90 "hooks": {

91 "Notification": [

92 {

93 "hooks": [{ "type": "command", "command": "afplay /System/Library/Sounds/Glass.aiff" }]

94 }

95 ]

96 }

97}

98```

99 

100## 配置 tmux

101 

102當 Claude Code 在 tmux 內執行時,預設情況下會發生兩件事:Shift+Enter 提交而不是插入換行符,桌面通知和[進度列](/zh-TW/settings#available-settings)永遠無法到達外部終端機。將這些行新增至 `~/.tmux.conf`,然後執行 `tmux source-file ~/.tmux.conf` 以將它們應用到執行中的伺服器:

103 

104```bash ~/.tmux.conf theme={null}

105set -g allow-passthrough on

106set -s extended-keys on

107set -as terminal-features 'xterm*:extkeys'

108```

109 

110`allow-passthrough` 行讓通知和進度更新到達 iTerm2、Ghostty 或 Kitty,而不是被 tmux 吞沒。`extended-keys` 行讓 tmux 區分 Shift+Enter 和純 Enter,以便換行符快捷鍵運作。

111 

112## 匹配色彩主題

113 

114使用 `/theme` 命令或 `/config` 中的主題選擇器來選擇與您的終端機相匹配的 Claude Code 主題。選擇自動選項會偵測您的終端機的淺色或深色背景,因此主題會在您的終端機執行時跟隨 OS 外觀變更。Claude Code 不控制終端機自己的色彩配置,該配置由終端機應用程式設定。

115 

116若要自訂介面底部出現的內容,請配置[自訂狀態列](/zh-TW/statusline),顯示目前的模型、工作目錄、git 分支或其他上下文。

117 

118### 建立自訂主題

119 

120<Note>

121 自訂主題需要 Claude Code v2.1.118 或更新版本。

122</Note>

123 

124除了內建預設值外,`/theme` 還會列出您已定義的任何自訂主題以及已安裝 [plugins](/zh-TW/plugins-reference#themes) 貢獻的任何主題。選擇清單末尾的 **New custom theme…** 以互動方式建立一個:您命名主題,然後選擇要覆蓋的個別色彩令牌。當自訂主題被突出顯示時,按 `Ctrl+E` 以編輯它。

125 

126每個自訂主題都是 `~/.claude/themes/` 中的 JSON 檔案。不含 `.json` 副檔名的檔案名稱是主題的 slug,選擇主題會將 `custom:<slug>` 儲存為您的主題偏好設定。該檔案有三個選用欄位:

127 

128| 欄位 | 類型 | 描述 |

129| :---------- | :----- | :--------------------------------------------------------------------------------------------------- |

130| `name` | string | 在 `/theme` 中顯示的標籤。預設為檔案名稱 slug |

131| `base` | string | 主題開始的內建預設值:`dark`、`light`、`dark-daltonized`、`light-daltonized`、`dark-ansi` 或 `light-ansi`。預設為 `dark` |

132| `overrides` | object | 色彩令牌名稱到色彩值的對應。此處未列出的令牌會落回到基礎預設值 |

133 

134色彩值接受 `#rrggbb`、`#rgb`、`rgb(r,g,b)`、`ansi256(n)` 或 `ansi:<name>`,其中 `<name>` 是 16 個標準 ANSI 色彩名稱之一,例如 `red` 或 `cyanBright`。未知的令牌和無效的色彩值會被忽略,因此打字錯誤無法破壞呈現。

135 

136以下範例定義了一個保留深色預設值但重新著色提示符號重點、錯誤文字和成功文字的主題:

137 

138```json ~/.claude/themes/dracula.json theme={null}

139{

140 "name": "Dracula",

141 "base": "dark",

142 "overrides": {

143 "claude": "#bd93f9",

144 "error": "#ff5555",

145 "success": "#50fa7b"

146 }

147}

148```

149 

150Claude Code 監視 `~/.claude/themes/` 並在檔案變更時重新載入,因此在您的編輯器中所做的編輯會在執行中的工作階段中應用,無需重新啟動。

151 

152以下參考涵蓋了您可以在 `overrides` 中設定的令牌。`/theme` 中的互動編輯器顯示相同的令牌,並提供即時預覽,加上此處未涵蓋的少數單一用途重點,例如上線畫面色彩。

153 

154<Accordion title="色彩令牌參考">

155 以下範例結合了下列幾個群組中的令牌:品牌重點、Plan Mode 邊框、diff 背景和全螢幕訊息背景。

156 

157 ```json ~/.claude/themes/midnight.json theme={null}

158 {

159 "name": "Midnight",

160 "base": "dark",

161 "overrides": {

162 "claude": "#a78bfa",

163 "planMode": "#38bdf8",

164 "diffAdded": "#14532d",

165 "diffRemoved": "#7f1d1d",

166 "userMessageBackground": "#1e1b4b"

167 }

168 }

169 ```

170 

171 #### 文字和重點色彩

172 

173 控制整個介面中使用的主要品牌重點和前景文字陰影。

174 

175 | 令牌 | 控制項 |

176 | :------------ | :------------------- |

177 | `claude` | 主要品牌重點,用於微調器和助手標籤 |

178 | `text` | 預設前景文字 |

179 | `inverseText` | 繪製在彩色背景上的文字,例如狀態徽章 |

180 | `inactive` | 次要文字,例如提示、時間戳記和停用的項目 |

181 | `subtle` | 淡色邊框和去強調的次要文字 |

182 | `suggestion` | 自動完成建議和選擇器中的選擇突出顯示 |

183 | `permission` | 對話方塊邊框,包括權限提示和選擇器 |

184 | `remember` | 記憶體和 `CLAUDE.md` 指示器 |

185 

186 #### 狀態色彩

187 

188 在訊息和指示器中發出成功、失敗和警告狀態的信號。

189 

190 | 令牌 | 控制項 |

191 | :-------- | :------------- |

192 | `success` | 成功訊息和通過的檢查 |

193 | `error` | 錯誤訊息和失敗 |

194 | `warning` | 警告、注意訊息和自動模式邊框 |

195 | `merged` | 合併的提取要求狀態 |

196 

197 #### 輸入框和模式指示器

198 

199 設定輸入框邊框色彩和權限模式或指示器作用中時顯示的重點。

200 

201 | 令牌 | 控制項 |

202 | :------------- | :--------------------- |

203 | `promptBorder` | 預設權限模式中的輸入框邊框 |

204 | `planMode` | Plan Mode 重點和邊框 |

205 | `autoAccept` | Accept-edits 模式重點和邊框 |

206 | `bashBorder` | 輸入 `!` shell 命令時的輸入框邊框 |

207 | `ide` | IDE 連線指示器 |

208 | `fastMode` | 快速模式指示器 |

209 

210 #### Diff 呈現

211 

212 在檔案編輯和審查中著色新增和移除的程式碼。

213 

214 | 令牌 | 控制項 |

215 | :------------------ | :------------- |

216 | `diffAdded` | 新增行的背景 |

217 | `diffRemoved` | 移除行的背景 |

218 | `diffAddedDimmed` | 新增行附近未變更上下文的背景 |

219 | `diffRemovedDimmed` | 移除行附近未變更上下文的背景 |

220 | `diffAddedWord` | 新增行內的字級突出顯示 |

221 | `diffRemovedWord` | 移除行內的字級突出顯示 |

222 

223 #### 全螢幕模式

224 

225 僅在[全螢幕呈現模式](/zh-TW/fullscreen)中套用,其中訊息具有背景填充。

226 

227 | 令牌 | 控制項 |

228 | :--------------------------- | :------------------------ |

229 | `userMessageBackground` | 文字記錄中您的訊息後面的背景 |

230 | `userMessageBackgroundHover` | 訊息被懸停或展開時其後面的背景 |

231 | `messageActionsBackground` | 動作列開啟時所選訊息後面的背景 |

232 | `bashMessageBackgroundColor` | 文字記錄中 `!` shell 命令項目後面的背景 |

233 | `memoryBackgroundColor` | 文字記錄中 `#` 記憶體項目後面的背景 |

234 | `selectionBg` | 使用滑鼠選取的文字背景 |

235 

236 #### 使用量計量和說話者標籤

237 

238 調整 `/usage` 檢視中顯示的列,以及區分您的訊息與 Claude 訊息的標籤。

239 

240 | 令牌 | 控制項 |

241 | :----------------- | :------------------- |

242 | `rate_limit_fill` | 使用量計量的填充部分 |

243 | `rate_limit_empty` | 使用量計量的未填充部分 |

244 | `briefLabelYou` | 您的訊息上 `You` 標籤的色彩 |

245 | `briefLabelClaude` | 助手訊息上 `Claude` 標籤的色彩 |

246 

247 #### 微光變體和子代理色彩

248 

249 多個令牌具有配對的微光變體,可提供微調器動畫漸層中使用的較淺色彩。如果動畫看起來不相符,請與其基礎令牌一起覆蓋微光。

250 

251 * `claude` 和 `claudeShimmer`

252 * `warning` 和 `warningShimmer`

253 * `permission` 和 `permissionShimmer`

254 * `promptBorder` 和 `promptBorderShimmer`

255 * `inactive` 和 `inactiveShimmer`

256 * `fastMode` 和 `fastModeShimmer`

257 

258 每個[子代理](/zh-TW/sub-agents)和平行工作都以八個命名色彩之一顯示,以便您可以在文字記錄中區分它們。令牌名稱遵循 `<color>_FOR_SUBAGENTS_ONLY` 的模式,其中 `<color>` 是 `red`、`blue`、`green`、`yellow`、`purple`、`orange`、`pink` 或 `cyan`。覆蓋這些以變更每個命名色彩的外觀。例如,定義中具有 `color: blue` 的子代理使用 `blue_FOR_SUBAGENTS_ONLY` 值繪製。

259 

260 [`ultrathink`](/zh-TW/model-config#use-ultrathink-for-one-off-deep-reasoning) 和 [`ultraplan`](/zh-TW/ultraplan) 提示輸入中的關鍵字使用七色彩虹漸層呈現。令牌名稱遵循 `rainbow_<color>` 和 `rainbow_<color>_shimmer` 的模式,其中 `<color>` 是 `red`、`orange`、`yellow`、`green`、`blue`、`indigo` 或 `violet`。

261</Accordion>

262 

263## 切換到全螢幕渲染

264 

265如果顯示閃爍或捲動位置在 Claude 工作時跳躍,請切換到[全螢幕渲染模式](/zh-TW/fullscreen)。它繪製到終端機為全螢幕應用程式保留的單獨螢幕,而不是附加到您的正常捲動,這保持記憶體使用平穩並新增滑鼠支援以進行捲動和選擇。在此模式中,您使用滑鼠或 PageUp 在 Claude Code 內捲動,而不是使用您的終端機的原生捲動;請參閱[全螢幕頁面](/zh-TW/fullscreen#search-and-review-the-conversation)以瞭解如何搜尋和複製。

266 

267執行 `/tui fullscreen` 以在目前工作階段中切換,您的對話保持完整。若要使其成為預設值,請在啟動 Claude Code 之前設置 `CLAUDE_CODE_NO_FLICKER` 環境變數:

268 

269<CodeGroup>

270 ```bash Bash and Zsh theme={null}

271 CLAUDE_CODE_NO_FLICKER=1 claude

272 ```

273 

274 ```powershell PowerShell theme={null}

275 $env:CLAUDE_CODE_NO_FLICKER = "1"; claude

276 ```

277 

278 ```json ~/.claude/settings.json theme={null}

279 {

280 "env": {

281 "CLAUDE_CODE_NO_FLICKER": "1"

282 }

283 }

284 ```

285</CodeGroup>

286 

287## 貼上大型內容

288 

289當您將超過 10,000 個字元貼上到提示中時,Claude Code 會將輸入摺疊為 `[Pasted text]` 預留位置,以便輸入框保持可用。完整內容在您提交時仍會發送到 Claude。

290 

291VS Code 整合終端機可能會在非常大的貼上中丟棄字元,然後才能到達 Claude Code,因此在那裡更喜歡基於檔案的工作流程。對於非常大的輸入(例如整個檔案或長日誌),請將內容寫入檔案並要求 Claude 讀取它,而不是貼上。這保持對話記錄可讀,並讓 Claude 在稍後的回合中按路徑參考檔案。

292 

293## 使用 Vim 快捷鍵編輯提示

294 

295Claude Code 包括提示輸入的 Vim 風格編輯模式。透過 `/config` → 編輯器模式啟用它,或透過在 `~/.claude/settings.json` 中將 [`editorMode`](/zh-TW/settings#available-settings) 設置為 `"vim"` 啟用它。將編輯器模式設置回 `normal` 以將其關閉。

296 

297Vim 模式支援 NORMAL 模式和 VISUAL 模式動作和運算子的子集,例如 `hjkl` 導覽、`v`/`V` 選取,以及 `d`/`c`/`y` 搭配文字物件。請參閱 [Vim 編輯器模式參考](/zh-TW/interactive-mode#vim-editor-mode)以取得完整快捷鍵表。Vim 動作無法透過快捷鍵檔案重新對應。

298 

299在 INSERT 模式中按 Enter 仍會提交您的提示,不同於標準 Vim。在 NORMAL 模式中使用 `o` 或 `O`,或 Ctrl+J,以插入換行符。

300 

301## 相關資源

302 

303* [互動模式](/zh-TW/interactive-mode):完整鍵盤快捷鍵參考和 Vim 快捷鍵表

304* [快捷鍵](/zh-TW/keybindings):重新對應任何 Claude Code 快捷鍵,包括 Enter 和 Shift+Enter

305* [全螢幕渲染](/zh-TW/fullscreen):全螢幕模式中捲動、搜尋和複製的詳細資訊

306* [Hooks 指南](/zh-TW/hooks-guide):Linux 和 Windows 的更多通知 hook 範例

307* [疑難排解](/zh-TW/troubleshooting):終端機配置外部問題的修復

third-party-integrations.md +262 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 企業部署概述

6 

7> 了解 Claude Code 如何與各種第三方服務和基礎設施整合,以滿足企業部署需求。

8 

9組織可以直接通過 Anthropic 或通過雲端提供商部署 Claude Code。本頁面幫助您選擇正確的配置。

10 

11## 比較部署選項

12 

13對於大多數組織,Claude for Teams 或 Claude for Enterprise 提供最佳體驗。團隊成員可以通過單一訂閱同時存取 Claude Code 和網頁版 Claude,具有集中計費和無需基礎設施設置的優勢。

14 

15**Claude for Teams** 是自助服務,包括協作功能、管理工具和計費管理。最適合需要快速開始的較小團隊。

16 

17**Claude for Enterprise** 增加了 SSO 和域名捕獲、基於角色的權限、合規性 API 存取和託管策略設置,用於部署組織範圍的 Claude Code 配置。最適合具有安全和合規性要求的大型組織。

18 

19了解更多關於 [Team 計劃](https://support.claude.com/en/articles/9266767-what-is-the-team-plan) 和 [Enterprise 計劃](https://support.claude.com/en/articles/9797531-what-is-the-enterprise-plan)。

20 

21如果您的組織有特定的基礎設施要求,請比較以下選項:

22 

23<table>

24 <thead>

25 <tr>

26 <th>功能</th>

27 <th>Claude for Teams/Enterprise</th>

28 <th>Anthropic Console</th>

29 <th>Amazon Bedrock</th>

30 <th>Google Vertex AI</th>

31 <th>Microsoft Foundry</th>

32 </tr>

33 </thead>

34 

35 <tbody>

36 <tr>

37 <td>最適合</td>

38 <td>大多數組織(推薦)</td>

39 <td>個人開發者</td>

40 <td>AWS 原生部署</td>

41 <td>GCP 原生部署</td>

42 <td>Azure 原生部署</td>

43 </tr>

44 

45 <tr>

46 <td>計費</td>

47 <td><strong>Teams:</strong> \$150/座位(Premium)提供 PAYG<br /><strong>Enterprise:</strong> <a href="https://claude.com/contact-sales?utm_source=claude_code&utm_medium=docs&utm_content=third_party_enterprise">聯絡銷售</a></td>

48 <td>PAYG</td>

49 <td>通過 AWS 的 PAYG</td>

50 <td>通過 GCP 的 PAYG</td>

51 <td>通過 Azure 的 PAYG</td>

52 </tr>

53 

54 <tr>

55 <td>地區</td>

56 <td>支援的 [國家/地區](https://www.anthropic.com/supported-countries)</td>

57 <td>支援的 [國家/地區](https://www.anthropic.com/supported-countries)</td>

58 <td>多個 AWS [地區](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html)</td>

59 <td>多個 GCP [地區](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations)</td>

60 <td>多個 Azure [地區](https://azure.microsoft.com/en-us/explore/global-infrastructure/products-by-region/)</td>

61 </tr>

62 

63 <tr>

64 <td>Prompt caching</td>

65 <td>預設啟用</td>

66 <td>預設啟用</td>

67 <td>預設啟用</td>

68 <td>預設啟用</td>

69 <td>預設啟用</td>

70 </tr>

71 

72 <tr>

73 <td>身份驗證</td>

74 <td>Claude.ai SSO 或電子郵件</td>

75 <td>API 金鑰</td>

76 <td>API 金鑰或 AWS 認證</td>

77 <td>GCP 認證</td>

78 <td>API 金鑰或 Microsoft Entra ID</td>

79 </tr>

80 

81 <tr>

82 <td>成本追蹤</td>

83 <td>使用儀表板</td>

84 <td>使用儀表板</td>

85 <td>AWS Cost Explorer</td>

86 <td>GCP Billing</td>

87 <td>Azure Cost Management</td>

88 </tr>

89 

90 <tr>

91 <td>包括網頁版 Claude</td>

92 <td>是</td>

93 <td>否</td>

94 <td>否</td>

95 <td>否</td>

96 <td>否</td>

97 </tr>

98 

99 <tr>

100 <td>企業功能</td>

101 <td>團隊管理、SSO、使用監控</td>

102 <td>無</td>

103 <td>IAM 策略、CloudTrail</td>

104 <td>IAM 角色、Cloud Audit Logs</td>

105 <td>RBAC 策略、Azure Monitor</td>

106 </tr>

107 </tbody>

108</table>

109 

110選擇部署選項以查看設置說明:

111 

112* [Claude for Teams 或 Enterprise](/zh-TW/authentication#claude-for-teams-or-enterprise)

113* [Anthropic Console](/zh-TW/authentication#claude-console-authentication)

114* [Amazon Bedrock](/zh-TW/amazon-bedrock)

115* [Google Vertex AI](/zh-TW/google-vertex-ai)

116* [Microsoft Foundry](/zh-TW/microsoft-foundry)

117 

118## 配置代理和網關

119 

120大多數組織可以直接使用雲端提供商,無需額外配置。但是,如果您的組織有特定的網路或管理要求,您可能需要配置公司代理或 LLM 網關。這些是可以一起使用的不同配置:

121 

122* **公司代理**:通過 HTTP/HTTPS 代理路由流量。如果您的組織要求所有出站流量都通過代理伺服器以進行安全監控、合規性或網路策略執行,請使用此選項。使用 `HTTPS_PROXY` 或 `HTTP_PROXY` 環境變數進行配置。在 [企業網路配置](/zh-TW/network-config) 中了解更多。

123* **LLM 網關**:位於 Claude Code 和雲端提供商之間的服務,用於處理身份驗證和路由。如果您需要跨團隊的集中使用追蹤、自訂速率限制或預算,或集中身份驗證管理,請使用此選項。使用 `ANTHROPIC_BASE_URL`、`ANTHROPIC_BEDROCK_BASE_URL` 或 `ANTHROPIC_VERTEX_BASE_URL` 環境變數進行配置。在 [LLM 網關配置](/zh-TW/llm-gateway) 中了解更多。

124 

125以下示例顯示在您的 shell 或 shell 配置文件(`.bashrc`、`.zshrc`)中設置的環境變數。有關其他配置方法,請參閱 [設置](/zh-TW/settings)。

126 

127### Amazon Bedrock

128 

129<Tabs>

130 <Tab title="公司代理">

131 通過設置以下 [環境變數](/zh-TW/env-vars) 將 Bedrock 流量路由通過您的公司代理:

132 

133 ```bash theme={null}

134 # 啟用 Bedrock

135 export CLAUDE_CODE_USE_BEDROCK=1

136 export AWS_REGION=us-east-1

137 

138 # 配置公司代理

139 export HTTPS_PROXY='https://proxy.example.com:8080'

140 ```

141 </Tab>

142 

143 <Tab title="LLM 網關">

144 通過設置以下 [環境變數](/zh-TW/env-vars) 將 Bedrock 流量路由通過您的 LLM 網關:

145 

146 ```bash theme={null}

147 # 啟用 Bedrock

148 export CLAUDE_CODE_USE_BEDROCK=1

149 

150 # 配置 LLM 網關

151 export ANTHROPIC_BEDROCK_BASE_URL='https://your-llm-gateway.com/bedrock'

152 export CLAUDE_CODE_SKIP_BEDROCK_AUTH=1 # 如果網關處理 AWS 身份驗證

153 ```

154 </Tab>

155</Tabs>

156 

157### Microsoft Foundry

158 

159<Tabs>

160 <Tab title="公司代理">

161 通過設置以下 [環境變數](/zh-TW/env-vars) 將 Foundry 流量路由通過您的公司代理:

162 

163 ```bash theme={null}

164 # 啟用 Microsoft Foundry

165 export CLAUDE_CODE_USE_FOUNDRY=1

166 export ANTHROPIC_FOUNDRY_RESOURCE=your-resource

167 export ANTHROPIC_FOUNDRY_API_KEY=your-api-key # 或省略以進行 Entra ID 身份驗證

168 

169 # 配置公司代理

170 export HTTPS_PROXY='https://proxy.example.com:8080'

171 ```

172 </Tab>

173 

174 <Tab title="LLM 網關">

175 通過設置以下 [環境變數](/zh-TW/env-vars) 將 Foundry 流量路由通過您的 LLM 網關:

176 

177 ```bash theme={null}

178 # 啟用 Microsoft Foundry

179 export CLAUDE_CODE_USE_FOUNDRY=1

180 

181 # 配置 LLM 網關

182 export ANTHROPIC_FOUNDRY_BASE_URL='https://your-llm-gateway.com'

183 export CLAUDE_CODE_SKIP_FOUNDRY_AUTH=1 # 如果網關處理 Azure 身份驗證

184 ```

185 </Tab>

186</Tabs>

187 

188### Google Vertex AI

189 

190<Tabs>

191 <Tab title="公司代理">

192 通過設置以下 [環境變數](/zh-TW/env-vars) 將 Vertex AI 流量路由通過您的公司代理:

193 

194 ```bash theme={null}

195 # 啟用 Vertex

196 export CLAUDE_CODE_USE_VERTEX=1

197 export CLOUD_ML_REGION=us-east5

198 export ANTHROPIC_VERTEX_PROJECT_ID=your-project-id

199 

200 # 配置公司代理

201 export HTTPS_PROXY='https://proxy.example.com:8080'

202 ```

203 </Tab>

204 

205 <Tab title="LLM 網關">

206 通過設置以下 [環境變數](/zh-TW/env-vars) 將 Vertex AI 流量路由通過您的 LLM 網關:

207 

208 ```bash theme={null}

209 # 啟用 Vertex

210 export CLAUDE_CODE_USE_VERTEX=1

211 

212 # 配置 LLM 網關

213 export ANTHROPIC_VERTEX_BASE_URL='https://your-llm-gateway.com/vertex'

214 export CLAUDE_CODE_SKIP_VERTEX_AUTH=1 # 如果網關處理 GCP 身份驗證

215 ```

216 </Tab>

217</Tabs>

218 

219<Tip>

220 在 Claude Code 中使用 `/status` 驗證您的代理和網關配置是否正確應用。

221</Tip>

222 

223## 組織的最佳實踐

224 

225### 投資於文件和記憶

226 

227我們強烈建議投資於文件,以便 Claude Code 理解您的程式碼庫。組織可以在多個級別部署 CLAUDE.md 文件:

228 

229* **組織範圍**:部署到系統目錄,如 `/Library/Application Support/ClaudeCode/CLAUDE.md`(macOS),用於公司範圍的標準

230* **存儲庫級別**:在存儲庫根目錄中建立 `CLAUDE.md` 文件,包含項目架構、構建命令和貢獻指南。將這些檢入源代碼控制,以便所有用戶受益

231 

232在 [記憶和 CLAUDE.md 文件](/zh-TW/memory) 中了解更多。

233 

234### 簡化部署

235 

236如果您有自訂開發環境,我們發現創建一個「一鍵」安裝 Claude Code 的方式是在組織中增加採用率的關鍵。

237 

238### 從引導式使用開始

239 

240鼓勵新用戶嘗試使用 Claude Code 進行程式碼庫問答,或在較小的錯誤修復或功能請求上使用。要求 Claude Code 制定計劃。檢查 Claude 的建議,如果偏離軌道,請提供反饋。隨著時間的推移,當用戶更好地理解這種新範式時,他們將更有效地讓 Claude Code 更自主地運行。

241 

242### 為雲端提供商固定模型版本

243 

244如果您通過 [Bedrock](/zh-TW/amazon-bedrock)、[Vertex AI](/zh-TW/google-vertex-ai) 或 [Foundry](/zh-TW/microsoft-foundry) 部署,請使用 `ANTHROPIC_DEFAULT_OPUS_MODEL`、`ANTHROPIC_DEFAULT_SONNET_MODEL` 和 `ANTHROPIC_DEFAULT_HAIKU_MODEL` 固定特定模型版本。如果不固定,Claude Code 別名會解析為最新版本,當 Anthropic 發佈您帳戶中尚未啟用的新模型時,可能會破壞用戶。有關詳細信息,請參閱 [模型配置](/zh-TW/model-config#pin-models-for-third-party-deployments)。

245 

246### 配置安全策略

247 

248安全團隊可以配置託管權限,以定義 Claude Code 允許和不允許執行的操作,這些操作無法被本地配置覆蓋。[了解更多](/zh-TW/security)。

249 

250### 利用 MCP 進行整合

251 

252MCP 是為 Claude Code 提供更多信息的絕佳方式,例如連接到票證管理系統或錯誤日誌。我們建議一個中央團隊配置 MCP servers 並將 `.mcp.json` 配置檢入程式碼庫,以便所有用戶受益。[了解更多](/zh-TW/mcp)。

253 

254在 Anthropic,我們信任 Claude Code 在每個 Anthropic 程式碼庫中推動開發。我們希望您享受使用 Claude Code 就像我們一樣。

255 

256## 後續步驟

257 

258選擇部署選項並為您的團隊配置存取權限後:

259 

2601. **向您的團隊推出**:分享安裝說明,並讓團隊成員 [安裝 Claude Code](/zh-TW/setup) 並使用其認證進行身份驗證。

2612. **設置共享配置**:在您的存儲庫中建立 [CLAUDE.md 文件](/zh-TW/memory),以幫助 Claude Code 理解您的程式碼庫和編碼標準。

2623. **配置權限**:查看 [安全設置](/zh-TW/security),以定義 Claude Code 在您的環境中可以和不能執行的操作。

tools-reference.md +148 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 工具參考

6 

7> Claude Code 可以使用的工具的完整參考,包括權限要求。

8 

9Claude Code 可以存取一組內建工具,幫助它理解和修改您的程式碼庫。工具名稱是您在 [權限規則](/zh-TW/permissions#tool-specific-permission-rules)、[subagent 工具清單](/zh-TW/sub-agents) 和 [hook 匹配器](/zh-TW/hooks) 中使用的確切字串。若要完全停用工具,請將其名稱新增到您的 [權限設定](/zh-TW/permissions#tool-specific-permission-rules) 中的 `deny` 陣列。

10 

11若要新增自訂工具,請連接 [MCP server](/zh-TW/mcp)。若要使用可重複使用的提示型工作流程擴展 Claude,請撰寫 [skill](/zh-TW/skills),它透過現有的 `Skill` 工具執行,而不是新增工具項目。

12 

13| 工具 | 描述 | 需要權限 |

14| :--------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--- |

15| `Agent` | 生成一個具有自己 context window 的 [subagent](/zh-TW/sub-agents),以處理任務 | 否 |

16| `AskUserQuestion` | 提出多選題以收集需求或澄清歧義 | 否 |

17| `Bash` | 在您的環境中執行 shell 命令。請參閱 [Bash 工具行為](#bash-tool-behavior) | 是 |

18| `CronCreate` | 在目前工作階段內排程定期或一次性提示。任務的範圍限於工作階段,並在 `--resume` 或 `--continue` 時恢復(如果未過期)。請參閱 [排程任務](/zh-TW/scheduled-tasks) | 否 |

19| `CronDelete` | 按 ID 取消排程任務 | 否 |

20| `CronList` | 列出工作階段中的所有排程任務 | 否 |

21| `Edit` | 對特定檔案進行目標編輯 | 是 |

22| `EnterPlanMode` | 切換到 Plan Mode 以在編碼前設計方法 | 否 |

23| `EnterWorktree` | 建立隔離的 [git worktree](/zh-TW/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees) 並切換到其中。傳遞 `path` 以切換到目前儲存庫的現有 worktree,而不是建立新的。不適用於 subagents | 否 |

24| `ExitPlanMode` | 提出計畫以供批准並退出 Plan Mode | 是 |

25| `ExitWorktree` | 退出 worktree 工作階段並返回原始目錄。不適用於 subagents | 否 |

26| `Glob` | 根據模式匹配查找檔案 | 否 |

27| `Grep` | 在檔案內容中搜尋模式 | 否 |

28| `ListMcpResourcesTool` | 列出連接的 [MCP servers](/zh-TW/mcp) 公開的資源 | 否 |

29| `LSP` | 透過語言伺服器進行程式碼智慧:跳轉到定義、尋找參考、報告型別錯誤和警告。請參閱 [LSP 工具行為](#lsp-tool-behavior) | 否 |

30| `Monitor` | 在背景執行命令,並將每個輸出行回饋給 Claude,以便它可以對日誌項目、檔案變更或輪詢狀態做出反應。請參閱 [Monitor 工具](#monitor-tool) | 是 |

31| `NotebookEdit` | 修改 Jupyter notebook 儲存格 | 是 |

32| `PowerShell` | 原生執行 PowerShell 命令。請參閱 [PowerShell 工具](#powershell-tool) 以了解可用性 | 是 |

33| `Read` | 讀取檔案的內容 | 否 |

34| `ReadMcpResourceTool` | 按 URI 讀取特定 MCP 資源 | 否 |

35| `SendMessage` | 傳送訊息給 [agent team](/zh-TW/agent-teams) 隊友,或按 agent ID [恢復 subagent](/zh-TW/sub-agents#resume-subagents)。已停止的 subagents 會在背景中自動恢復。僅在設定 `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` 時可用 | 否 |

36| `Skill` | 在主對話中執行 [skill](/zh-TW/skills#control-who-invokes-a-skill) | 是 |

37| `TaskCreate` | 在任務清單中建立新任務 | 否 |

38| `TaskGet` | 檢索特定任務的完整詳細資訊 | 否 |

39| `TaskList` | 列出所有任務及其目前狀態 | 否 |

40| `TaskOutput` | (已棄用)檢索背景任務的輸出。建議在任務的輸出檔案路徑上使用 `Read` | 否 |

41| `TaskStop` | 按 ID 終止執行中的背景任務 | 否 |

42| `TaskUpdate` | 更新任務狀態、依賴項、詳細資訊或刪除任務 | 否 |

43| `TeamCreate` | 建立具有多個隊友的 [agent team](/zh-TW/agent-teams)。僅在設定 `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` 時可用 | 否 |

44| `TeamDelete` | 解散 agent team 並清理隊友程序。僅在設定 `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` 時可用 | 否 |

45| `TodoWrite` | 管理工作階段任務檢查清單。在非互動模式和 [Agent SDK](/zh-TW/headless) 中可用;互動工作階段改用 TaskCreate、TaskGet、TaskList 和 TaskUpdate | 否 |

46| `ToolSearch` | 當啟用 [tool search](/zh-TW/mcp#scale-with-mcp-tool-search) 時,搜尋並載入延遲工具 | 否 |

47| `WebFetch` | 從指定 URL 擷取內容 | 是 |

48| `WebSearch` | 執行網路搜尋 | 是 |

49| `Write` | 建立或覆寫檔案 | 是 |

50 

51權限規則可以使用 `/permissions` 或在 [權限設定](/zh-TW/settings#available-settings) 中設定。另請參閱 [工具特定權限規則](/zh-TW/permissions#tool-specific-permission-rules)。

52 

53## Bash 工具行為

54 

55Bash 工具在單獨的程序中執行每個命令,具有以下持久性行為:

56 

57* 當 Claude 在主工作階段中執行 `cd` 時,只要新的工作目錄保持在專案目錄內或您使用 `--add-dir`、`/add-dir` 或設定中的 `additionalDirectories` 新增的 [額外工作目錄](/zh-TW/permissions#working-directories) 內,新的工作目錄就會延續到後續的 Bash 命令。Subagent 工作階段永遠不會延續工作目錄變更。

58 * 如果 `cd` 落在這些目錄之外,Claude Code 會重設為專案目錄,並將 `Shell cwd was reset to <dir>` 附加到工具結果。

59 * 若要停用此延續,使每個 Bash 命令都在專案目錄中啟動,請設定 `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1`。

60* 環境變數不持久化。一個命令中的 `export` 在下一個命令中將不可用。

61 

62在啟動 Claude Code 之前啟動您的 virtualenv 或 conda 環境。若要讓環境變數在 Bash 命令之間持久化,請在啟動 Claude Code 之前將 [`CLAUDE_ENV_FILE`](/zh-TW/env-vars) 設定為 shell 指令碼,或使用 [SessionStart hook](/zh-TW/hooks#persist-environment-variables) 動態填充它。

63 

64## LSP 工具行為

65 

66LSP 工具從執行中的語言伺服器為 Claude 提供程式碼智慧。在每次檔案編輯後,它會自動報告型別錯誤和警告,以便 Claude 可以在沒有單獨建置步驟的情況下修復問題。Claude 也可以直接呼叫它來導航程式碼:

67 

68* 跳轉到符號的定義

69* 尋找符號的所有參考

70* 取得位置的型別資訊

71* 列出檔案或工作區中的符號

72* 尋找介面的實作

73* 追蹤呼叫階層

74 

75該工具在您安裝您的語言的 [程式碼智慧外掛](/zh-TW/discover-plugins#code-intelligence) 之前處於非作用中狀態。該外掛包含語言伺服器設定,您需要單獨安裝伺服器二進位檔。

76 

77## Monitor 工具

78 

79<Note>

80 Monitor 工具需要 Claude Code v2.1.98 或更新版本。

81</Note>

82 

83Monitor 工具讓 Claude 在背景監視某些內容,並在其變更時做出反應,而無需暫停對話。要求 Claude:

84 

85* 追蹤日誌檔案並在錯誤出現時標記

86* 輪詢 PR 或 CI 工作,並在其狀態變更時報告

87* 監視目錄以查看檔案變更

88* 追蹤您指向的任何長時間執行指令碼的輸出

89 

90Claude 為監視編寫一個小指令碼,在背景執行它,並在每行到達時接收它。您可以在同一工作階段中繼續工作,Claude 會在事件發生時插入。透過要求 Claude 取消監視或結束工作階段來停止監視。

91 

92Monitor 使用與 [Bash 相同的權限規則](/zh-TW/permissions#tool-specific-permission-rules),因此您為 Bash 設定的 `allow` 和 `deny` 模式也適用於此處。它在 Amazon Bedrock、Google Vertex AI 或 Microsoft Foundry 上不可用。當設定 `DISABLE_TELEMETRY` 或 `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` 時,它也不可用。

93 

94外掛可以宣告在外掛啟用時自動啟動的監視,而不是要求 Claude 啟動它們。請參閱 [外掛監視](/zh-TW/plugins-reference#monitors)。

95 

96## PowerShell 工具

97 

98PowerShell 工具讓 Claude 原生執行 PowerShell 命令。在 Windows 上,這表示命令在 PowerShell 中執行,而不是透過 Git Bash 路由。在沒有 Git Bash 的 Windows 上,該工具會自動啟用。在安裝了 Git Bash 的 Windows 上,該工具正在逐步推出。在 Linux、macOS 和 WSL 上,該工具是選擇加入的。

99 

100### 啟用 PowerShell 工具

101 

102在您的環境或 `settings.json` 中設定 `CLAUDE_CODE_USE_POWERSHELL_TOOL=1`:

103 

104```json theme={null}

105{

106 "env": {

107 "CLAUDE_CODE_USE_POWERSHELL_TOOL": "1"

108 }

109}

110```

111 

112在 Windows 上,將變數設定為 `0` 以選擇退出推出。在 Linux、macOS 和 WSL 上,該工具需要 PowerShell 7 或更新版本:安裝 `pwsh` 並確保它在您的 `PATH` 上。

113 

114在 Windows 上,Claude Code 自動偵測 `pwsh.exe`(PowerShell 7+),並回退到 `powershell.exe`(PowerShell 5.1)。啟用該工具時,Claude 將 PowerShell 視為主要 shell。當安裝了 Git Bash 時,Bash 工具仍可用於 POSIX 指令碼。

115 

116### 設定、hooks 和 skills 中的 shell 選擇

117 

118三個額外的設定控制 PowerShell 的使用位置:

119 

120* [`settings.json`](/zh-TW/settings#available-settings) 中的 `"defaultShell": "powershell"`:透過 PowerShell 路由互動式 `!` 命令。需要啟用 PowerShell 工具。

121* 個別 [command hooks](/zh-TW/hooks#command-hook-fields) 上的 `"shell": "powershell"`:在 PowerShell 中執行該 hook。Hooks 直接生成 PowerShell,因此無論 `CLAUDE_CODE_USE_POWERSHELL_TOOL` 如何,這都有效。

122* [skill frontmatter](/zh-TW/skills#frontmatter-reference) 中的 `shell: powershell`:在 PowerShell 中執行 `` !`command` `` 區塊。需要啟用 PowerShell 工具。

123 

124Bash 工具部分中描述的相同主工作階段工作目錄重設行為適用於 PowerShell 命令,包括 `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` 環境變數。

125 

126### 預覽限制

127 

128PowerShell 工具在預覽期間有以下已知限制:

129 

130* PowerShell 設定檔未載入

131* 在 Windows 上,不支援 sandboxing

132 

133## 檢查哪些工具可用

134 

135您的確切工具集取決於您的提供者、平台和設定。若要檢查在執行中的工作階段中載入了什麼,請直接詢問 Claude:

136 

137```text theme={null}

138What tools do you have access to?

139```

140 

141Claude 提供對話摘要。如需確切的 MCP 工具名稱,請執行 `/mcp`。

142 

143## 另請參閱

144 

145* [MCP servers](/zh-TW/mcp):透過連接外部伺服器新增自訂工具

146* [權限](/zh-TW/permissions):權限系統、規則語法和工具特定模式

147* [Subagents](/zh-TW/sub-agents):為 subagents 設定工具存取

148* [Hooks](/zh-TW/hooks-guide):在工具執行前後執行自訂命令

troubleshoot-install.md +803 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 排除安裝和登入問題

6 

7> 修復安裝或登入 Claude Code 時的 command not found、PATH、權限、網路和身份驗證錯誤。

8 

9如果安裝失敗或無法登入,請在下方找到您的錯誤。如需 Claude Code 正常運作後的執行時問題,請參閱[排除故障](/zh-TW/troubleshooting)。如需設定問題(例如設定未套用或 hooks 未觸發),請參閱[偵錯您的設定](/zh-TW/debug-your-config)。

10 

11## 找到您的錯誤

12 

13將您看到的錯誤訊息或症狀與修復方案相符:

14 

15| 您看到的內容 | 解決方案 |

16| :----------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------- |

17| `command not found: claude` 或 `'claude' is not recognized` | [修復您的 PATH](#command-not-found-claude-after-installation) |

18| `syntax error near unexpected token '<'` | [安裝指令碼傳回 HTML](#install-script-returns-html-instead-of-a-shell-script) |

19| `curl: (56) Failure writing output to destination` | [檢查連線或使用替代安裝程式](#curl-56-failure-writing-output-to-destination) |

20| Linux 上安裝期間 `Killed` | [為低記憶體伺服器新增交換空間](#install-killed-on-low-memory-linux-servers) |

21| `TLS connect error` 或 `SSL/TLS secure channel` | [更新 CA 憑證](#tls-or-ssl-connection-errors) |

22| `Failed to fetch version` 或無法連線到下載伺服器 | [檢查網路和代理設定](#check-network-connectivity) |

23| `irm is not recognized` 或 `&& is not valid` | [在您的 shell 上使用正確的命令](#wrong-install-command-on-windows) |

24| `'bash' is not recognized as the name of a cmdlet` | [使用 Windows 安裝程式命令](#wrong-install-command-on-windows) |

25| `Claude Code on Windows requires either Git for Windows (for bash) or PowerShell` | [安裝 shell](#claude-code-on-windows-requires-either-git-for-windows-for-bash-or-powershell) |

26| `Claude Code does not support 32-bit Windows` | [開啟 Windows PowerShell,而非 x86 項目](#claude-code-does-not-support-32-bit-windows) |

27| `The process cannot access the file ... because it is being used by another process` | [清除下載資料夾並重試](#the-process-cannot-access-the-file-during-windows-install) |

28| `Error loading shared library` | [您的系統的二進位變體錯誤](#linux-musl-or-glibc-binary-mismatch) |

29| `Illegal instruction` | [架構或 CPU 指令集不相符](#illegal-instruction) |

30| WSL 中的 `cannot execute binary file: Exec format error` | [WSL1 原生二進位回歸](#exec-format-error-on-wsl1) |

31| PowerShell 安裝程式完成但找不到 `claude` 或顯示舊版本 | [重新啟動您的終端並驗證 PATH](#verify-your-path) |

32| macOS 上的 `dyld: cannot load`、`dyld: Symbol not found` 或 `Abort trap` | [二進位不相容](#dyld-cannot-load-on-macos) |

33| `Invoke-Expression: Missing argument in parameter list` | [安裝指令碼傳回 HTML](#install-script-returns-html-instead-of-a-shell-script) |

34| `App unavailable in region` | Claude Code 在您的國家/地區不可用。請參閱[支援的國家/地區](https://www.anthropic.com/supported-countries)。 |

35| `unable to get local issuer certificate` | [設定公司 CA 憑證](#tls-or-ssl-connection-errors) |

36| `OAuth error` 或 `403 Forbidden` | [修復身份驗證](#login-and-authentication) |

37| `Could not load the default credentials` 或 `Could not load credentials from any providers` | [Bedrock、Vertex 或 Foundry 認證](#bedrock-vertex-or-foundry-credentials-not-loading) |

38| `ChainedTokenCredential authentication failed` 或 `CredentialUnavailableError` | [Bedrock、Vertex 或 Foundry 認證](#bedrock-vertex-or-foundry-credentials-not-loading) |

39| `API Error: 500`、`529 Overloaded`、`429` 或上面未列出的其他 4xx 和 5xx 錯誤 | 請參閱[錯誤參考](/zh-TW/errors) |

40 

41如果您的問題未列出,請執行下面的診斷檢查以縮小原因範圍。

42 

43<Tip>

44 如果您寧願完全跳過終端,[Claude Code Desktop 應用程式](/zh-TW/desktop-quickstart)可讓您透過圖形介面安裝和使用 Claude Code。下載適用於 [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs) 或 [Windows](https://claude.com/download?utm_source=claude_code\&utm_medium=docs) 的版本,無需任何命令列設定即可開始編碼。

45</Tip>

46 

47## 執行診斷檢查

48 

49### 檢查網路連線

50 

51安裝程式從 `downloads.claude.ai` 下載。驗證您可以連線到它:

52 

53```bash theme={null}

54curl -sI https://downloads.claude.ai/claude-code-releases/latest

55```

56 

57`HTTP/2 200` 行表示您已連線到伺服器。如果您看不到任何輸出、`Could not resolve host` 或連線逾時,您的網路正在阻止連線。常見原因:

58 

59* 公司防火牆或代理阻止 `downloads.claude.ai`

60* 區域網路限制:嘗試 VPN 或替代網路

61* TLS/SSL 問題:更新您系統的 CA 憑證,或檢查是否設定了 `HTTPS_PROXY`

62 

63如果您在公司代理後面,在安裝前設定 `HTTPS_PROXY` 和 `HTTP_PROXY` 為您的代理位址。如果您不知道代理 URL,請詢問您的 IT 團隊,或檢查您的瀏覽器代理設定。

64 

65此範例設定兩個代理變數,然後透過您的代理執行安裝程式:

66 

67<Tabs>

68 <Tab title="macOS/Linux">

69 ```bash theme={null}

70 export HTTP_PROXY=http://proxy.example.com:8080

71 export HTTPS_PROXY=http://proxy.example.com:8080

72 curl -fsSL https://claude.ai/install.sh | bash

73 ```

74 </Tab>

75 

76 <Tab title="Windows PowerShell">

77 ```powershell theme={null}

78 $env:HTTP_PROXY = 'http://proxy.example.com:8080'

79 $env:HTTPS_PROXY = 'http://proxy.example.com:8080'

80 irm https://claude.ai/install.ps1 | iex

81 ```

82 </Tab>

83</Tabs>

84 

85### 驗證您的 PATH

86 

87如果安裝成功但執行 `claude` 時收到 `command not found` 或 `not recognized` 錯誤,安裝目錄不在您的 PATH 中。您的 shell 在 PATH 中列出的目錄中搜尋程式,安裝程式在 macOS/Linux 上將 `claude` 放在 `~/.local/bin/claude`,或在 Windows 上放在 `%USERPROFILE%\.local\bin\claude.exe`。

88 

89透過列出您的 PATH 項目並篩選 `local/bin` 來檢查安裝目錄是否在您的 PATH 中:

90 

91<Tabs>

92 <Tab title="macOS/Linux">

93 ```bash theme={null}

94 echo $PATH | tr ':' '\n' | grep -Fx "$HOME/.local/bin"

95 ```

96 

97 如果這列印 `/Users/you/.local/bin` 或 `/home/you/.local/bin`,該目錄在您的 PATH 中,您可以跳到[檢查衝突的安裝](#check-for-conflicting-installations)。如果沒有輸出,請將其新增到您的 shell 設定。

98 

99 對於 Zsh(macOS 上的預設值):

100 

101 ```bash theme={null}

102 echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc

103 source ~/.zshrc

104 ```

105 

106 對於 Bash(大多數 Linux 發行版上的預設值):

107 

108 ```bash theme={null}

109 echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc

110 source ~/.bashrc

111 ```

112 

113 或者,關閉並重新開啟您的終端。

114 

115 對於其他 shell(例如 fish 或 Nushell),使用您的 shell 自己的設定語法將 `~/.local/bin` 新增到您的 PATH,然後重新啟動您的終端。

116 

117 驗證修復是否有效:

118 

119 ```bash theme={null}

120 claude --version

121 ```

122 </Tab>

123 

124 <Tab title="Windows PowerShell">

125 ```powershell theme={null}

126 $env:PATH -split ';' | Select-String '\.local\\bin'

127 ```

128 

129 如果沒有輸出,請將安裝目錄新增到您的使用者 PATH:

130 

131 ```powershell theme={null}

132 $currentPath = [Environment]::GetEnvironmentVariable('PATH', 'User')

133 [Environment]::SetEnvironmentVariable('PATH', "$currentPath;$env:USERPROFILE\.local\bin", 'User')

134 ```

135 

136 重新啟動您的終端以使變更生效。

137 

138 驗證修復是否有效:

139 

140 ```powershell theme={null}

141 claude --version

142 ```

143 </Tab>

144 

145 <Tab title="Windows CMD">

146 ```batch theme={null}

147 echo %PATH% | findstr /i "local\bin"

148 ```

149 

150 如果沒有輸出,請開啟系統設定,前往環境變數,並將 `%USERPROFILE%\.local\bin` 新增到您的使用者 PATH 變數。重新啟動您的終端。

151 

152 驗證修復是否有效:

153 

154 ```batch theme={null}

155 claude --version

156 ```

157 </Tab>

158</Tabs>

159 

160### 檢查衝突的安裝

161 

162多個 Claude Code 安裝可能導致版本不相符或意外行為。檢查已安裝的內容:

163 

164<Tabs>

165 <Tab title="macOS/Linux">

166 列出在您的 PATH 中找到的所有 `claude` 二進位檔:

167 

168 ```bash theme={null}

169 which -a claude

170 ```

171 

172 如果這列印任何內容,沒有 `claude` 在您的 PATH 上。回到[驗證您的 PATH](#verify-your-path)。

173 

174 檢查 `claude` 二進位檔可能來自的三個位置。`~/.local/bin/claude` 是原生安裝程式,`~/.claude/local/` 是由舊版 Claude Code 建立的舊版本地 npm 安裝,npm 全域清單顯示 `-g` 安裝:

175 

176 ```bash theme={null}

177 ls -la ~/.local/bin/claude

178 ```

179 

180 ```bash theme={null}

181 ls -la ~/.claude/local/

182 ```

183 

184 ```bash theme={null}

185 npm -g ls @anthropic-ai/claude-code 2>/dev/null

186 ```

187 </Tab>

188 

189 <Tab title="Windows PowerShell">

190 列出在您的 PATH 中找到的所有 `claude` 二進位檔:

191 

192 ```powershell theme={null}

193 where.exe claude

194 ```

195 

196 檢查原生安裝程式是否放置了二進位檔:

197 

198 ```powershell theme={null}

199 Test-Path "$env:USERPROFILE\.local\bin\claude.exe"

200 ```

201 </Tab>

202</Tabs>

203 

204如果您找到多個安裝,只保留一個。macOS/Linux 上 `~/.local/bin/claude` 或 Windows 上 `%USERPROFILE%\.local\bin\claude.exe` 的原生安裝是推薦的。移除額外的:

205 

206解除安裝 npm 全域安裝:

207 

208```bash theme={null}

209npm uninstall -g @anthropic-ai/claude-code

210```

211 

212移除舊版本地 npm 安裝:

213 

214```bash theme={null}

215rm -rf ~/.claude/local

216```

217 

218在 Windows 上,使用 PowerShell:

219 

220```powershell theme={null}

221Remove-Item -Recurse -Force "$env:USERPROFILE\.claude\local"

222```

223 

224在 macOS 上移除 Homebrew 安裝。如果您安裝了 `claude-code@latest` cask,請替換該名稱:

225 

226```bash theme={null}

227brew uninstall --cask claude-code

228```

229 

230在 Windows 上移除 WinGet 安裝:

231 

232```powershell theme={null}

233winget uninstall Anthropic.ClaudeCode

234```

235 

236### 檢查目錄權限

237 

238安裝程式需要對 macOS 和 Linux 上的 `~/.local/bin/` 和 `~/.claude/` 有寫入存取權限。在 Windows 上,安裝位置在 `%USERPROFILE%` 下,預設情況下您的使用者可寫入,因此此部分很少適用於 Windows。

239 

240檢查目錄是否可寫入:

241 

242```bash theme={null}

243test -w ~/.local/bin && echo "writable" || echo "not writable"

244test -w ~/.claude && echo "writable" || echo "not writable"

245```

246 

247如果任一目錄不可寫入,請建立安裝目錄並將您的使用者設定為擁有者:

248 

249```bash theme={null}

250sudo mkdir -p ~/.local/bin

251sudo chown -R $(whoami) ~/.local

252```

253 

254### 驗證二進位檔是否有效

255 

256如果 `claude --version` 列印版本但 `claude` 在啟動時崩潰或掛起,請執行這些檢查以縮小原因範圍。如果 `claude --version` 說 command not found,請先前往[驗證您的 PATH](#verify-your-path);下面的命令假設 `claude` 在您的 PATH 上。

257 

258確認二進位檔存在且可執行:

259 

260```bash theme={null}

261ls -la "$(command -v claude)"

262```

263 

264在 Windows 上,使用 PowerShell:

265 

266```powershell theme={null}

267Get-Command claude | Select-Object Source

268```

269 

270在 Linux 上,檢查遺失的共用程式庫。如果 `ldd` 顯示遺失的程式庫,您可能需要安裝系統套件。在 Alpine Linux 和其他基於 musl 的發行版上,請參閱 [Alpine Linux 設定](/zh-TW/setup#alpine-linux-and-musl-based-distributions)。

271 

272```bash theme={null}

273ldd "$(command -v claude)" | grep "not found"

274```

275 

276確認二進位檔可以執行:

277 

278```bash theme={null}

279claude --version

280```

281 

282## 常見安裝問題

283 

284這些是最常見的安裝問題及其解決方案。

285 

286### 安裝指令碼傳回 HTML 而非 shell 指令碼

287 

288執行安裝命令時,您可能會看到以下其中一個錯誤:

289 

290```text theme={null}

291bash: line 1: syntax error near unexpected token `<'

292bash: line 1: `<!DOCTYPE html>'

293```

294 

295在 PowerShell 上,同樣的問題顯示為:

296 

297```text theme={null}

298Invoke-Expression: Missing argument in parameter list.

299```

300 

301這表示安裝 URL 傳回了 HTML 頁面而非安裝指令碼。如果 HTML 頁面顯示「App unavailable in region」,Claude Code 在您的國家/地區不可用。請參閱[支援的國家/地區](https://www.anthropic.com/supported-countries)。

302 

303否則,這可能由於網路問題、區域路由或暫時服務中斷而發生。

304 

305**解決方案:**

306 

3071. **使用替代安裝方法**:

308 

309 在 macOS 上,透過 Homebrew 安裝:

310 

311 ```bash theme={null}

312 brew install --cask claude-code

313 ```

314 

315 在 Windows 上,透過 WinGet 安裝:

316 

317 ```powershell theme={null}

318 winget install Anthropic.ClaudeCode

319 ```

320 

3212. **幾分鐘後重試**:問題通常是暫時的。等待並再次嘗試原始命令。

322 

323### 安裝後 `command not found: claude`

324 

325安裝完成但 `claude` 無法運作。確切的錯誤因平台而異:

326 

327| 平台 | 錯誤訊息 |

328| :---------- | :--------------------------------------------------------------------- |

329| macOS | `zsh: command not found: claude` |

330| Linux | `bash: claude: command not found` |

331| Windows CMD | `'claude' is not recognized as an internal or external command` |

332| PowerShell | `claude : The term 'claude' is not recognized as the name of a cmdlet` |

333 

334這表示安裝目錄不在您的 shell 搜尋路徑中。請參閱[驗證您的 PATH](#verify-your-path) 以取得每個平台上的修復。

335 

336### `curl: (56) Failure writing output to destination`

337 

338`curl ... | bash` 命令下載指令碼並將其傳送到 Bash 以執行。此錯誤表示連線在指令碼完成下載前中斷。常見原因包括網路中斷、下載在中途被阻止或系統資源限制。

339 

340**解決方案:**

341 

3421. **檢查網路穩定性**:Claude Code 二進位檔託管在 `downloads.claude.ai`。測試您是否可以連線到它:

343 ```bash theme={null}

344 curl -sI https://downloads.claude.ai/claude-code-releases/latest

345 ```

346 `HTTP/2 200` 行表示您已連線到伺服器,原始失敗可能是間歇性的;重試安裝命令。如果您看到 `Could not resolve host` 或連線逾時,您的網路正在阻止下載。

347 

3482. **嘗試替代安裝方法**:

349 

350 在 macOS 上:

351 

352 ```bash theme={null}

353 brew install --cask claude-code

354 ```

355 

356 在 Windows 上:

357 

358 ```powershell theme={null}

359 winget install Anthropic.ClaudeCode

360 ```

361 

362### TLS 或 SSL 連線錯誤

363 

364錯誤如 `curl: (35) TLS connect error`、`schannel: next InitializeSecurityContext failed` 或 PowerShell 的 `Could not establish trust relationship for the SSL/TLS secure channel` 表示 TLS 握手失敗。

365 

366**解決方案:**

367 

3681. **更新您的系統 CA 憑證**:

369 

370 在 Ubuntu/Debian 上:

371 

372 ```bash theme={null}

373 sudo apt-get update && sudo apt-get install ca-certificates

374 ```

375 

376 在 macOS 上,系統 curl 使用 Keychain 信任存放區;更新 macOS 本身會更新根憑證。

377 

3782. **在 Windows 上,在執行安裝程式前在 PowerShell 中啟用 TLS 1.2**:

379 ```powershell theme={null}

380 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

381 irm https://claude.ai/install.ps1 | iex

382 ```

383 

3843. **檢查代理或防火牆干擾**:執行 TLS 檢查的公司代理可能導致這些錯誤,包括 `unable to get local issuer certificate` 和 `SELF_SIGNED_CERT_IN_CHAIN`。對於安裝步驟,使用 `--cacert` 將 curl 指向您的公司 CA 套件:

385 ```bash theme={null}

386 curl --cacert /path/to/corporate-ca.pem -fsSL https://claude.ai/install.sh | bash

387 ```

388 對於安裝後的 Claude Code 本身,設定 `NODE_EXTRA_CA_CERTS` 以便 API 請求信任相同的套件:

389 ```bash theme={null}

390 export NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem

391 ```

392 如果您沒有憑證檔案,請詢問您的 IT 團隊。您也可以嘗試直接連線以確認代理是原因。

393 

3944. **在 Windows 上,如果您看到 `CRYPT_E_NO_REVOCATION_CHECK (0x80092012)` 或 `CRYPT_E_REVOCATION_OFFLINE (0x80092013)`,請略過憑證撤銷檢查**。這些表示 curl 已連線到伺服器,但您的網路阻止了憑證撤銷查詢,這在公司防火牆後面很常見。將 `--ssl-revoke-best-effort` 新增到安裝命令:

395 ```batch theme={null}

396 curl --ssl-revoke-best-effort -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

397 ```

398 或者,使用 `winget install Anthropic.ClaudeCode` 安裝,這完全避免了 curl。

399 

400### `Failed to fetch version from downloads.claude.ai`

401 

402安裝程式無法連線到下載伺服器。這通常表示 `downloads.claude.ai` 在您的網路上被阻止。

403 

404**解決方案:**

405 

4061. **直接測試連線**:

407 ```bash theme={null}

408 curl -sI https://downloads.claude.ai/claude-code-releases/latest

409 ```

410 

4112. **如果在代理後面**,設定 `HTTPS_PROXY` 以便安裝程式可以透過它路由。請參閱[代理設定](/zh-TW/network-config#proxy-configuration)以取得詳細資訊。

412 ```bash theme={null}

413 export HTTPS_PROXY=http://proxy.example.com:8080

414 curl -fsSL https://claude.ai/install.sh | bash

415 ```

416 

4173. **如果在受限網路上**,嘗試不同的網路或 VPN,或使用替代安裝方法:

418 

419 在 macOS 上:

420 

421 ```bash theme={null}

422 brew install --cask claude-code

423 ```

424 

425 在 Windows 上:

426 

427 ```powershell theme={null}

428 winget install Anthropic.ClaudeCode

429 ```

430 

431### Windows 上的錯誤安裝命令

432 

433如果您看到 `'irm' is not recognized`、`The token '&&' is not valid` 或 `'bash' is not recognized as the name of a cmdlet`,您複製了不同 shell 或作業系統的安裝命令。

434 

435* **`irm` 未被識別**:您在 CMD 中,而非 PowerShell。您有兩個選項:

436 

437 透過在開始功能表中搜尋「PowerShell」開啟 PowerShell,然後執行原始安裝命令:

438 

439 ```powershell theme={null}

440 irm https://claude.ai/install.ps1 | iex

441 ```

442 

443 或留在 CMD 中並改用 CMD 安裝程式:

444 

445 ```batch theme={null}

446 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

447 ```

448 

449* **`&&` 無效**:您在 PowerShell 中但執行了 CMD 安裝程式命令。使用 PowerShell 安裝程式:

450 ```powershell theme={null}

451 irm https://claude.ai/install.ps1 | iex

452 ```

453 

454* **`bash` 未被識別**:您在 Windows 上執行了 macOS/Linux 安裝程式。改用 PowerShell 安裝程式:

455 ```powershell theme={null}

456 irm https://claude.ai/install.ps1 | iex

457 ```

458 

459### Windows 上的 `The process cannot access the file` 在安裝期間

460 

461如果 PowerShell 安裝程式因 `Failed to download binary: The process cannot access the file ... because it is being used by another process` 而失敗,安裝程式無法寫入 `%USERPROFILE%\.claude\downloads`。這通常表示先前的安裝嘗試仍在執行,或防毒軟體正在掃描該資料夾中部分下載的二進位檔。

462 

463關閉任何其他執行安裝程式的 PowerShell 視窗,並等待防毒軟體掃描釋放該檔案。然後刪除下載資料夾並再次執行安裝程式:

464 

465```powershell theme={null}

466Remove-Item -Recurse -Force "$env:USERPROFILE\.claude\downloads"

467irm https://claude.ai/install.ps1 | iex

468```

469 

470### 低記憶體 Linux 伺服器上安裝被終止

471 

472如果您在 VPS 或雲端執行個體上的安裝期間看到 `Killed`:

473 

474```text theme={null}

475Setting up Claude Code...

476Installing Claude Code native build latest...

477bash: line 142: 34803 Killed "$binary_path" install ${TARGET:+"$TARGET"}

478```

479 

480Linux OOM 殺手終止了該程序,因為系統用盡了記憶體。Claude Code 需要至少 4 GB 的可用 RAM。

481 

482**解決方案:**

483 

4841. **新增交換空間**(如果您的伺服器 RAM 有限)。交換使用磁碟空間作為溢出記憶體,讓安裝即使在低物理 RAM 的情況下也能完成。

485 

486 建立 2 GB 交換檔案並啟用它:

487 

488 ```bash theme={null}

489 sudo fallocate -l 2G /swapfile

490 sudo chmod 600 /swapfile

491 sudo mkswap /swapfile

492 sudo swapon /swapfile

493 ```

494 

495 然後重試安裝:

496 

497 ```bash theme={null}

498 curl -fsSL https://claude.ai/install.sh | bash

499 ```

500 

5012. **在安裝前關閉其他程序**以釋放記憶體。

502 

5033. **如果可能,使用更大的執行個體**。Claude Code 需要至少 4 GB 的 RAM。

504 

505### Docker 中安裝掛起

506 

507在 Docker 容器中安裝 Claude Code 時,以 root 身份安裝到 `/` 可能導致掛起。

508 

509**解決方案:**

510 

5111. **在執行安裝程式前設定工作目錄**。在 `/` 執行時,安裝程式掃描整個檔案系統,導致過度的記憶體使用。設定 `WORKDIR` 將掃描限制在小目錄:

512 ```dockerfile theme={null}

513 WORKDIR /tmp

514 RUN curl -fsSL https://claude.ai/install.sh | bash

515 ```

516 

5172. **如果使用 Docker Desktop,請增加 Docker 記憶體限制**:

518 ```bash theme={null}

519 docker build --memory=4g .

520 ```

521 

522### Claude Desktop 在 Windows 上覆蓋 `claude` 命令

523 

524如果您安裝了舊版本的 Claude Desktop,它可能在 `WindowsApps` 目錄中註冊 `Claude.exe`,其 PATH 優先級高於 Claude Code CLI。執行 `claude` 會開啟 Desktop 應用程式而非 CLI。

525 

526更新 Claude Desktop 到最新版本以修復此問題。

527 

528### Windows 上的 Claude Code 需要 Git for Windows(用於 bash)或 PowerShell

529 

530Windows 上的原生 Claude Code 需要至少一個 shell:[Git for Windows](https://git-scm.com/downloads/win)(用於 Bash)或 PowerShell。當找不到任何一個時,此錯誤會在啟動時出現。如果只找到 PowerShell,Claude Code 會改用 PowerShell 工具而非 Bash。

531 

532**如果都未安裝**,請安裝其中一個:

533 

534* Git for Windows:從 [git-scm.com/downloads/win](https://git-scm.com/downloads/win) 下載。在設定期間,選擇「Add to PATH」。安裝後重新啟動您的終端。

535* PowerShell 7:從 [aka.ms/powershell](https://aka.ms/powershell) 下載。

536 

537**如果已安裝 Git** 但 Claude Code 找不到它,請在您的 [settings.json 檔案](/zh-TW/settings)中設定路徑:

538 

539```json theme={null}

540{

541 "env": {

542 "CLAUDE_CODE_GIT_BASH_PATH": "C:\\Program Files\\Git\\bin\\bash.exe"

543 }

544}

545```

546 

547如果您的 Git 安裝在其他地方,透過在 PowerShell 中執行 `where.exe git` 找到路徑,並使用該目錄中的 `bin\bash.exe` 路徑。

548 

549### Claude Code 不支援 32 位元 Windows

550 

551Windows 在開始功能表中包含兩個 PowerShell 項目:`Windows PowerShell` 和 `Windows PowerShell (x86)`。x86 項目以 32 位元程序執行,即使在 64 位元機器上也會觸發此錯誤。要檢查您在哪種情況下,請在產生錯誤的同一視窗中執行此命令:

552 

553```powershell theme={null}

554[Environment]::Is64BitOperatingSystem

555```

556 

557如果這列印 `True`,您的作業系統沒問題。關閉視窗,開啟不帶 x86 後綴的 `Windows PowerShell`,然後再次執行安裝命令。

558 

559如果這列印 `False`,您在 32 位元版本的 Windows 上。Claude Code 需要 64 位元作業系統。請參閱[系統需求](/zh-TW/setup#system-requirements)。

560 

561### Linux musl 或 glibc 二進位不相符

562 

563如果在安裝後看到有關遺失共用程式庫的錯誤,如 `libstdc++.so.6` 或 `libgcc_s.so.1`,安裝程式可能為您的系統下載了錯誤的二進位變體。

564 

565```text theme={null}

566Error loading shared library libstdc++.so.6: No such file or directory

567```

568 

569這可能發生在已安裝 musl 交叉編譯套件的基於 glibc 的系統上,導致安裝程式將系統誤檢測為 musl。

570 

571**解決方案:**

572 

5731. **檢查您的系統使用哪個 libc**:

574 ```bash theme={null}

575 ldd --version 2>&1 | head -1

576 ```

577 提及 `GNU libc` 或 `GLIBC` 的輸出表示 glibc。提及 `musl` 的輸出表示 musl。

578 

5792. **如果您在 glibc 上但得到了 musl 二進位檔**,移除安裝並重新安裝。您也可以使用 `https://downloads.claude.ai/claude-code-releases/{VERSION}/manifest.json` 上的清單手動下載正確的二進位檔。使用 `ldd --version` 和 `ls /lib/libc.musl*` 的輸出提交 [GitHub 問題](https://github.com/anthropics/claude-code/issues)。

580 

5813. **如果您實際上在 musl 上**,例如 Alpine Linux,請安裝所需的套件:

582 ```bash theme={null}

583 apk add libgcc libstdc++ ripgrep

584 ```

585 

586### `Illegal instruction`

587 

588如果執行 `claude` 或安裝程式列印 `Illegal instruction`,原生二進位檔使用您的處理器不支援的 CPU 指令。有兩個不同的原因。

589 

590**架構不相符。** 安裝程式下載了錯誤的二進位檔,例如在 ARM 伺服器上的 x86。在 macOS 或 Linux 上使用 `uname -m` 檢查,或在 PowerShell 中使用 `$env:PROCESSOR_ARCHITECTURE`。如果結果與您收到的二進位檔不相符,[提交 GitHub 問題](https://github.com/anthropics/claude-code/issues)並附上輸出。

591 

592**遺失 AVX 指令集。** 如果您的架構正確但仍然看到 `Illegal instruction`,您的 CPU 可能缺少 AVX 或二進位檔需要的其他指令。這影響大約 2013 年之前的 Intel 和 AMD 處理器,以及超管理程式不將 AVX 傳遞給客體的虛擬機器。

593 

594在 VPS 或 VM 上,執行 `grep -m1 -ow avx /proc/cpuinfo`;空結果表示 AVX 對客體不可用。

595 

596沒有原生二進位檔解決方法;追蹤[問題 #50384](https://github.com/anthropics/claude-code/issues/50384) 以取得狀態,並在報告時包含您的 CPU 型號,從 Linux 上的 `grep -m1 "model name" /proc/cpuinfo` 或 macOS 上的 `sysctl -n machdep.cpu.brand_string`。

597 

598替代安裝方法下載相同的原生二進位檔,不會解決任一原因。

599 

600### macOS 上的 `dyld: cannot load`

601 

602如果在安裝期間看到 `dyld: cannot load`、`dyld: Symbol not found` 或 `Abort trap: 6`,二進位檔與您的 macOS 版本或硬體不相容。

603 

604```text theme={null}

605dyld: cannot load 'claude-2.1.42-darwin-x64' (load command 0x80000034 is unknown)

606Abort trap: 6

607```

608 

609參考 `libicucore` 的 `Symbol not found` 錯誤也表示您的 macOS 版本比二進位檔支援的版本更舊:

610 

611```text theme={null}

612dyld: Symbol not found: _ubrk_clone

613 Referenced from: claude-darwin-x64 (which was built for Mac OS X 13.0)

614 Expected in: /usr/lib/libicucore.A.dylib

615```

616 

617**解決方案:**

618 

6191. **檢查您的 macOS 版本**:Claude Code 需要 macOS 13.0 或更新版本。開啟 Apple 功能表並選擇「關於本機」以檢查您的版本。

620 

6212. **更新 macOS**(如果您在舊版本上)。二進位檔使用舊 macOS 版本不支援的載入命令和系統程式庫。Homebrew 等替代安裝方法下載相同的二進位檔,不會解決此錯誤。

622 

623### WSL1 上的 `Exec format error`

624 

625如果在 WSL 中執行 `claude` 列印 `cannot execute binary file: Exec format error`,您在 WSL1 上並遇到[問題 #38788](https://github.com/anthropics/claude-code/issues/38788) 中追蹤的已知原生二進位檔回歸。二進位檔的程式頭以 WSL1 的載入器無法處理的方式改變。

626 

627最簡潔的修復是從 PowerShell 將您的發行版轉換為 WSL2:

628 

629```powershell theme={null}

630wsl --set-version <DistroName> 2

631```

632 

633如果您需要留在 WSL1 上,透過動態連結器叫用二進位檔。將此函數新增到 WSL 內的 `~/.bashrc`,如果您的主目錄不同,請替換路徑:

634 

635```bash theme={null}

636claude() {

637 /lib64/ld-linux-x86-64.so.2 "$(readlink -f "$HOME/.local/bin/claude")" "$@"

638}

639```

640 

641然後執行 `source ~/.bashrc` 並重試 `claude`。

642 

643### WSL 中的 npm 安裝錯誤

644 

645如果您在 WSL 內使用 `npm install -g` 安裝了 Claude Code,這些問題適用。如果您使用了[原生安裝程式](/zh-TW/setup),請跳過此部分。

646 

647**OS 或平台偵測問題。** 如果 npm 在安裝期間報告平台不相符,WSL 可能正在使用 Windows `npm`。首先執行 `npm config set os linux`,然後使用 `npm install -g @anthropic-ai/claude-code --force` 安裝。不要使用 `sudo`。

648 

649**執行 `claude` 時的 `exec: node: not found`。** 您的 WSL 環境可能使用 Windows 安裝的 Node.js。使用 `which npm` 和 `which node` 確認:以 `/mnt/c/` 開頭的路徑是 Windows 二進位檔,而 Linux 路徑以 `/usr/` 開頭。要修復此問題,請透過您的 Linux 發行版的套件管理器或透過 [`nvm`](https://github.com/nvm-sh/nvm) 安裝 Node。

650 

651**nvm 版本衝突。** 如果您在 WSL 和 Windows 中都安裝了 nvm,在 WSL 中切換 Node 版本可能會中斷,因為 WSL 預設匯入 Windows PATH,Windows nvm 優先。最常見的原因是 nvm 未在您的 shell 中載入。將 nvm 載入器新增到 `~/.bashrc` 或 `~/.zshrc`:

652 

653```bash theme={null}

654export NVM_DIR="$HOME/.nvm"

655[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

656[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

657```

658 

659或在您的目前工作階段中載入它:

660 

661```bash theme={null}

662source ~/.nvm/nvm.sh

663```

664 

665如果 nvm 已載入但 Windows 路徑仍優先,明確地預先設定您的 Linux Node 路徑:

666 

667```bash theme={null}

668export PATH="$HOME/.nvm/versions/node/$(node -v)/bin:$PATH"

669```

670 

671<Warning>

672 避免透過 `appendWindowsPath = false` 停用 Windows PATH 匯入,因為這會破壞從 WSL 呼叫 Windows 可執行檔的能力。同樣,如果您在 Windows 開發中使用 Node.js,請避免從 Windows 解除安裝它。

673</Warning>

674 

675### 安裝期間的權限錯誤

676 

677如果原生安裝程式因權限錯誤而失敗,目標目錄可能不可寫入。請參閱[檢查目錄權限](#check-directory-permissions)。

678 

679如果您之前使用 npm 安裝並遇到 npm 特定的權限錯誤,請切換到原生安裝程式:

680 

681```bash theme={null}

682curl -fsSL https://claude.ai/install.sh | bash

683```

684 

685### npm 安裝後找不到原生二進位檔

686 

687`@anthropic-ai/claude-code` npm 套件透過每個平台的可選相依性(如 `@anthropic-ai/claude-code-darwin-arm64`)拉入原生二進位檔。如果安裝後執行 `claude` 列印 `Could not find native binary package "@anthropic-ai/claude-code-<platform>"`,請檢查以下原因:

688 

689* **可選相依性已停用。** 從您的 npm 安裝命令中移除 `--omit=optional`、從 pnpm 移除 `--no-optional` 或從 yarn 移除 `--ignore-optional`,並檢查 `.npmrc` 是否未設定 `optional=false`。然後重新安裝。原生二進位檔僅作為可選相依性提供,因此如果跳過它,沒有 JavaScript 後備。

690* **不支援的平台。** 預建二進位檔針對 `darwin-arm64`、`darwin-x64`、`linux-x64`、`linux-arm64`、`linux-x64-musl`、`linux-arm64-musl`、`win32-x64` 和 `win32-arm64` 發佈。Claude Code 不為其他平台提供二進位檔;請參閱[系統需求](/zh-TW/setup#system-requirements)。

691* **公司 npm 鏡像缺少平台套件。** 確保您的登錄鏡像除了元套件外,還鏡像所有八個 `@anthropic-ai/claude-code-*` 平台套件。

692 

693使用 `--ignore-scripts` 安裝不會觸發此錯誤。跳過連結二進位檔到位置的 postinstall 步驟,因此 Claude Code 回退到在每次啟動時定位和生成平台二進位檔的包裝器。這有效但啟動速度較慢;使用啟用的指令碼重新安裝以進行直接執行。

694 

695## 登入和身份驗證

696 

697這些部分涉及登入失敗、OAuth 錯誤和令牌問題。

698 

699### 重設您的登入

700 

701當登入失敗且原因不明顯時,乾淨的重新身份驗證可解決大多數情況:

702 

7031. 執行 `/logout` 以完全登出

7042. 關閉 Claude Code

7053. 使用 `claude` 重新啟動並再次完成身份驗證程序

706 

707如果瀏覽器在登入期間未自動開啟,按 `c` 將 OAuth URL 複製到您的剪貼簿,然後手動將其貼到瀏覽器中。當 URL 在狹窄或 SSH 終端中跨行換行且無法直接點擊時,這也有效。

708 

709### OAuth 錯誤:無效代碼

710 

711如果您看到 `OAuth error: Invalid code. Please make sure the full code was copied`,登入代碼已過期或在複製貼上期間被截斷。

712 

713**解決方案:**

714 

715* 在瀏覽器開啟後按 Enter 以重試並快速完成登入

716* 如果瀏覽器未自動開啟,輸入 `c` 複製完整 URL

717* 如果使用遠端/SSH 工作階段,瀏覽器可能在錯誤的機器上開啟。複製終端中顯示的 URL 並在您的本地瀏覽器中開啟它。

718 

719### 登入後 403 Forbidden

720 

721如果您在登入後看到 `API Error: 403 {"error":{"type":"forbidden","message":"Request not allowed"}}`:

722 

723* **Claude Pro/Max 使用者**:在 [claude.ai/settings](https://claude.ai/settings) 驗證您的訂閱是否有效

724* **Anthropic Console 使用者**:確認您的帳戶具有「Claude Code」或「Developer」角色。管理員在 Anthropic Console 的「設定」→「成員」中指派此角色。

725* **在代理後面**:公司代理可能干擾 API 請求。請參閱[網路設定](/zh-TW/network-config)以取得代理設定。

726 

727### 此組織已停用,但有有效的訂閱

728 

729如果您看到 `API Error: 400 ... "This organization has been disabled"`,儘管有有效的 Claude 訂閱,`ANTHROPIC_API_KEY` 環境變數正在覆蓋您的訂閱。這通常發生在舊 API 金鑰(來自先前的雇主或專案)仍在您的 shell 設定檔中時。

730 

731當 `ANTHROPIC_API_KEY` 存在且您已核准它時,Claude Code 使用該金鑰而非您訂閱的 OAuth 認證。在使用 `-p` 旗標的非互動模式下,當存在時始終使用該金鑰。請參閱[身份驗證優先順序](/zh-TW/authentication#authentication-precedence)以取得完整的解決順序。

732 

733要改用您的訂閱,請取消設定環境變數並從您的 shell 設定檔中移除它:

734 

735```bash theme={null}

736unset ANTHROPIC_API_KEY

737claude

738```

739 

740檢查 `~/.zshrc`、`~/.bashrc` 或 `~/.profile` 中的 `export ANTHROPIC_API_KEY=...` 行並移除它們以永久進行變更。在 Windows 上,檢查您在 `$PROFILE` 的 PowerShell 設定檔和您的使用者環境變數中的 `ANTHROPIC_API_KEY`。在 Claude Code 內執行 `/status` 以確認哪個身份驗證方法是有效的。

741 

742### WSL2、SSH 或容器中的 OAuth 登入失敗

743 

744當 Claude Code 在 WSL2 中執行、透過 SSH 在遠端機器上執行或在容器內執行時,瀏覽器通常在不同的主機上開啟,其重新導向無法到達 Claude Code 的本地回呼伺服器。在您登入後,瀏覽器會顯示登入代碼而不是自動重新導向回來。將該代碼貼到終端的 `Paste code here if prompted` 提示中以完成登入。

745 

746如果瀏覽器根本不從 WSL2 開啟,請將 `BROWSER` 環境變數設定為您的 Windows 瀏覽器路徑:

747 

748```bash theme={null}

749export BROWSER="/mnt/c/Program Files/Google/Chrome/Application/chrome.exe"

750claude

751```

752 

753或者,在互動式登入提示時按 `c` 複製 OAuth URL,或複製 `claude auth login` 列印的 URL,並在您的本地機器上的瀏覽器中開啟它。

754 

755如果將代碼貼到互動式提示中沒有任何反應,您的終端的貼上繫結可能無法到達輸入欄位。嘗試您的終端的替代貼上快捷鍵,通常在 Windows Terminal 中是右鍵點擊或 Shift+Insert,或改用 `claude auth login`,它從標準輸入讀取貼上的代碼:

756 

757```bash theme={null}

758claude auth login

759```

760 

761此後備也適用於原生 Windows 或任何將代碼貼到互動式提示失敗的終端。

762 

763### 未登入或令牌已過期

764 

765如果 Claude Code 在工作階段後提示您再次登入,您的 OAuth 令牌可能已過期。

766 

767執行 `/login` 以重新身份驗證。如果這經常發生,請檢查您的系統時鐘是否準確,因為令牌驗證取決於正確的時間戳。

768 

769在 macOS 上,當 Keychain 被鎖定或其密碼與您的帳戶密碼不同步時,登入也可能失敗,這會阻止 Claude Code 儲存認證。執行 `claude doctor` 以檢查 Keychain 存取。要手動解鎖 Keychain,請執行 `security unlock-keychain ~/Library/Keychains/login.keychain-db`。如果解鎖無幫助,請開啟 Keychain Access,選擇 `login` keychain,並選擇「編輯」>「變更 Keychain 'login' 的密碼」以將其與您的帳戶密碼重新同步。

770 

771### Bedrock、Vertex 或 Foundry 認證未載入

772 

773如果您設定了 Claude Code 以使用雲端提供者,並在 Bedrock 上看到 `Could not load credentials from any providers`、在 Vertex 上看到 `Could not load the default credentials` 或在 Foundry 上看到 `ChainedTokenCredential authentication failed`,您的雲端提供者 CLI 可能在目前 shell 中未進行身份驗證。

774 

775對於 Bedrock,確認您的 AWS 認證有效:

776 

777```bash theme={null}

778aws sts get-caller-identity

779```

780 

781對於 Vertex AI,確認 `ANTHROPIC_VERTEX_PROJECT_ID` 和 `CLOUD_ML_REGION` 在您的 shell 中設定,然後設定應用程式預設認證:

782 

783```bash theme={null}

784gcloud auth application-default login

785```

786 

787對於 Microsoft Foundry,確認 `ANTHROPIC_FOUNDRY_API_KEY` 已設定,或使用 Azure CLI 登入,以便預設認證鏈可以找到您的帳戶:

788 

789```bash theme={null}

790az login

791```

792 

793如果認證在您的終端中有效但在 VS Code 或 JetBrains 擴充功能中無效,IDE 程序可能未繼承您的 shell 環境。在 IDE 自己的設定中設定提供者環境變數,或從已匯出它們的終端啟動 IDE。

794 

795請參閱 [Amazon Bedrock](/zh-TW/amazon-bedrock)、[Google Vertex AI](/zh-TW/google-vertex-ai) 或 [Microsoft Foundry](/zh-TW/microsoft-foundry) 以取得完整的提供者設定。

796 

797## 仍然卡住

798 

799如果上述任何方法都無法解決您的問題:

800 

8011. 檢查 [GitHub 儲存庫](https://github.com/anthropics/claude-code/issues)以了解已知問題,或使用您的作業系統、您執行的安裝命令和完整錯誤輸出開啟新問題

8022. 如果 `claude --version` 有效但其他內容有問題,執行 `claude doctor` 以取得自動診斷報告

8033. 如果您可以啟動工作階段,請在 Claude Code 內使用 `/feedback` 報告問題

troubleshooting.md +121 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 故障排除

6 

7> 修復 Claude Code 中的高 CPU 或記憶體使用、掛起、auto-compact 抖動和搜尋問題,並找到其他問題的正確頁面。

8 

9本頁涵蓋 Claude Code 執行後的效能、穩定性和搜尋問題。如需其他問題,請從符合您遇到問題位置的頁面開始:

10 

11| 症狀 | 前往 |

12| :-------------------------------------------------------------- | :---------------------------------------------------------------- |

13| `command not found`、安裝失敗、PATH 問題、`EACCES`、TLS 錯誤 | [故障排除安裝和登入](/zh-TW/troubleshoot-install) |

14| 登入迴圈、OAuth 錯誤、`403 Forbidden`、「組織已停用」、Bedrock/Vertex/Foundry 認證 | [故障排除安裝和登入](/zh-TW/troubleshoot-install#login-and-authentication) |

15| 設定未套用、hooks 未觸發、MCP 伺服器未載入 | [偵錯您的設定](/zh-TW/debug-your-config) |

16| `API Error: 5xx`、`529 Overloaded`、`429`、請求驗證錯誤 | [錯誤參考](/zh-TW/errors) |

17| `model not found` 或 `you may not have access to it` | [錯誤參考](/zh-TW/errors#theres-an-issue-with-the-selected-model) |

18| VS Code 擴充功能未連接或未偵測到 Claude | [VS Code 整合](/zh-TW/vs-code#fix-common-issues) |

19| JetBrains 外掛程式或 IDE 未偵測到 | [JetBrains 整合](/zh-TW/jetbrains#troubleshooting) |

20| 高 CPU 或記憶體、回應緩慢、掛起、搜尋找不到檔案 | [效能和穩定性](#performance-and-stability)下方 |

21 

22如果您不確定哪個適用,請在 Claude Code 內執行 `/doctor` 以自動檢查您的安裝、設定、MCP 伺服器和上下文使用情況。如果 `claude` 根本無法啟動,請改為從您的 shell 執行 `claude doctor`。

23 

24## 效能和穩定性

25 

26這些部分涵蓋與資源使用、回應性和搜尋行為相關的問題。

27 

28### 高 CPU 或記憶體使用

29 

30Claude Code 設計用於與大多數開發環境配合使用,但在處理大型程式碼庫時可能消耗大量資源。如果您遇到效能問題:

31 

321. 定期使用 `/compact` 減少上下文大小

332. 在主要任務之間關閉並重新啟動 Claude Code

343. 考慮將大型構建目錄新增到您的 `.gitignore` 檔案

35 

36如果在這些步驟後記憶體使用仍然很高,請執行 `/heapdump` 以將 JavaScript 堆快照和記憶體分解寫入 `~/Desktop`。在沒有 Desktop 資料夾的 Linux 上,檔案會寫入您的主目錄。

37 

38分解顯示駐留集大小、JS 堆、陣列緩衝區和未計算的原生記憶體,這有助於識別增長是在 JavaScript 物件還是原生程式碼中。若要檢查保留者,請在 Chrome DevTools 中的 Memory → Load 下開啟 `.heapsnapshot` 檔案。在 [GitHub](https://github.com/anthropics/claude-code/issues) 上報告記憶體問題時附加兩個檔案。

39 

40### Auto-compaction 停止並出現 thrashing 錯誤

41 

42如果您看到 `Autocompact is thrashing: the context refilled to the limit...`,自動 compaction 成功,但檔案或工具輸出立即多次重新填充上下文視窗。Claude Code 停止重試以避免在沒有進展的迴圈上浪費 API 呼叫。

43 

44若要復原:

45 

461. 要求 Claude 以較小的塊讀取超大檔案,例如特定行範圍或函式,而不是整個檔案

472. 執行 `/compact` 並關注丟棄大輸出,例如 `/compact keep only the plan and the diff`

483. 將大檔案工作移動到 [subagent](/zh-TW/sub-agents),以便它在單獨的上下文視窗中執行

494. 如果早期對話不再需要,執行 `/clear`

50 

51### 命令掛起或凍結

52 

53如果 Claude Code 似乎無回應:

54 

551. 按 Ctrl+C 嘗試取消目前操作

562. 如果無回應,您可能需要關閉終端並重新啟動

57 

58重新啟動不會遺失您的對話。在同一目錄中執行 `claude --resume` 以繼續會話。

59 

60### 搜尋和發現問題

61 

62如果搜尋工具、`@file` 提及、自訂代理或自訂 skills 找不到檔案,捆綁的 `ripgrep` 二進位檔可能無法在您的系統上執行。安裝您平台的 `ripgrep` 套件並告訴 Claude Code 改用它:

63 

64<Tabs>

65 <Tab title="macOS">

66 ```bash theme={null}

67 brew install ripgrep

68 ```

69 </Tab>

70 

71 <Tab title="Ubuntu/Debian">

72 ```bash theme={null}

73 sudo apt install ripgrep

74 ```

75 </Tab>

76 

77 <Tab title="Alpine">

78 ```bash theme={null}

79 apk add ripgrep

80 ```

81 </Tab>

82 

83 <Tab title="Arch">

84 ```bash theme={null}

85 pacman -S ripgrep

86 ```

87 </Tab>

88 

89 <Tab title="Windows">

90 ```powershell theme={null}

91 winget install BurntSushi.ripgrep.MSVC

92 ```

93 </Tab>

94</Tabs>

95 

96然後在您的[環境](/zh-TW/env-vars)中設定 `USE_BUILTIN_RIPGREP=0`。

97 

98### WSL 上的搜尋速度緩慢或結果不完整

99 

100在 WSL 上[跨檔案系統工作](https://learn.microsoft.com/en-us/windows/wsl/filesystems)時的磁碟讀取效能損失可能導致在 WSL 上使用 Claude Code 時匹配數少於預期。搜尋仍然有效,但在原生檔案系統上返回的結果較少。

101 

102<Note>

103 在這種情況下,`/doctor` 將顯示搜尋為正常。

104</Note>

105 

106**解決方案:**

107 

1081. **提交更具體的搜尋**:透過指定目錄或檔案類型來減少搜尋的檔案數量:「Search for JWT validation logic in the auth-service package」或「Find use of md5 hash in JS files」。

109 

1102. **將專案移動到 Linux 檔案系統**:如果可能,確保您的專案位於 Linux 檔案系統(`/home/`)而不是 Windows 檔案系統(`/mnt/c/`)。

111 

1123. **改用原生 Windows**:考慮在 Windows 上原生執行 Claude Code 而不是透過 WSL,以獲得更好的檔案系統效能。

113 

114## 取得更多幫助

115 

116如果您遇到此處未涵蓋的問題:

117 

1181. 執行 `/doctor` 以一次檢查安裝健康狀況、設定有效性、MCP 設定和上下文使用情況

1192. 在 Claude Code 內使用 `/feedback` 命令直接向 Anthropic 報告問題

1203. 檢查 [GitHub 存儲庫](https://github.com/anthropics/claude-code)以了解已知問題

1214. 直接向 Claude 詢問其功能和特性。Claude 內置訪問其文檔。

ultraplan.md +84 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 使用 ultraplan 在雲端進行規劃

6 

7> 從您的 CLI 開始規劃,在網路上的 Claude Code 中草擬,然後遠端執行或回到您的終端機執行

8 

9<Note>

10 Ultraplan 處於研究預覽階段,需要 Claude Code v2.1.91 或更新版本。行為和功能可能會根據反饋而改變。

11</Note>

12 

13Ultraplan 將規劃任務從您的本機 CLI 交給在 [plan mode](/zh-TW/permission-modes#analyze-before-you-edit-with-plan-mode) 中執行的 [Claude Code on the web](/zh-TW/claude-code-on-the-web) 工作階段。Claude 在雲端草擬計畫,同時您可以繼續在終端機中工作。當計畫準備好時,您可以在瀏覽器中開啟它來評論特定部分、要求修訂,並選擇在何處執行它。

14 

15當您想要比終端機提供的更豐富的審查介面時,這很有用:

16 

17* **有針對性的反饋**:對計畫的個別部分進行評論,而不是回覆整個計畫

18* **無需動手的草擬**:計畫在遠端生成,因此您的終端機可以自由進行其他工作

19* **靈活的執行**:批准計畫在網路上執行並開啟拉取請求,或將其發送回您的終端機

20 

21Ultraplan 需要 [Claude Code on the web](/zh-TW/claude-code-on-the-web) 帳戶和 GitHub 儲存庫。因為它在 Anthropic 的雲端基礎設施上執行,所以在使用 Amazon Bedrock、Google Cloud Vertex AI 或 Microsoft Foundry 時不可用。雲端工作階段在您帳戶的預設 [cloud environment](/zh-TW/claude-code-on-the-web#the-cloud-environment) 中執行。如果您還沒有雲端環境,ultraplan 會在首次啟動時自動建立一個。

22 

23## 從 CLI 啟動 ultraplan

24 

25從您的本機 CLI 工作階段,您可以透過三種方式啟動 ultraplan:

26 

27* **命令**:執行 `/ultraplan` 後跟您的提示

28* **關鍵字**:在正常提示中的任何地方包含 `ultraplan` 一詞

29* **從本機計畫**:當 Claude 完成本機計畫並顯示批准對話框時,選擇 **No, refine with Ultraplan on Claude Code on the web** 將草稿發送到雲端進行進一步迭代

30 

31例如,要使用命令規劃服務遷移:

32 

33```

34/ultraplan migrate the auth service from sessions to JWTs

35```

36 

37命令和關鍵字路徑在啟動前開啟確認對話框。本機計畫路徑會跳過此對話框,因為該選擇已作為確認。如果 [Remote Control](/zh-TW/remote-control) 處於活動狀態,當 ultraplan 啟動時它會斷開連接,因為兩個功能都佔用 claude.ai/code 介面,一次只能連接一個。

38 

39雲端工作階段啟動後,您的 CLI 的提示輸入會顯示狀態指示器,同時遠端工作階段工作:

40 

41| 狀態 | 含義 |

42| :----------------------------- | :----------------------- |

43| `◇ ultraplan` | Claude 正在研究您的程式碼庫並草擬計畫 |

44| `◇ ultraplan needs your input` | Claude 有澄清問題;開啟工作階段連結以回應 |

45| `◆ ultraplan ready` | 計畫已準備好在您的瀏覽器中審查 |

46 

47執行 `/tasks` 並選擇 ultraplan 項目以開啟詳細檢視,其中包含工作階段連結、代理活動和 **Stop ultraplan** 操作。停止會封存雲端工作階段並清除指示器;沒有任何內容保存到您的終端機。

48 

49## 在瀏覽器中審查和修訂計畫

50 

51當狀態變更為 `◆ ultraplan ready` 時,開啟工作階段連結以在 claude.ai 上檢視計畫。計畫出現在專用審查檢視中:

52 

53* **內嵌評論**:反白任何段落並留下評論供 Claude 處理

54* **表情符號反應**:對某個部分做出反應以表示批准或關注,無需撰寫完整評論

55* **大綱側邊欄**:在計畫的各個部分之間跳轉

56 

57當您要求 Claude 處理您的評論時,它會修訂計畫並呈現更新的草稿。您可以根據需要迭代多次,然後再選擇在何處執行。

58 

59## 選擇執行位置

60 

61當計畫看起來正確時,您可以從瀏覽器選擇 Claude 是在同一雲端工作階段中實施它,還是將其發送回您等待的終端機。

62 

63### 在網路上執行

64 

65在瀏覽器中選擇 **Approve Claude's plan and start coding** 以讓 Claude 在同一 Claude Code on the web 工作階段中實施它。您的終端機會顯示確認,狀態指示器會清除,工作會在雲端繼續。實施完成後,[review the diff](/zh-TW/claude-code-on-the-web#review-changes) 並從網路介面建立拉取請求。

66 

67### 將計畫發送回您的終端機

68 

69在瀏覽器中選擇 **Approve plan and teleport back to terminal** 以使用對您環境的完全存取權限在本機實施計畫。當工作階段是從您的 CLI 啟動且終端機仍在輪詢時,此選項會出現。網路工作階段被封存,因此它不會並行繼續工作。

70 

71您的終端機會在標題為 **Ultraplan approved** 的對話框中顯示計畫,有三個選項:

72 

73* **Implement here**:將計畫注入您目前的對話並從您停止的地方繼續

74* **Start new session**:清除目前的對話並僅以計畫作為上下文開始新的對話

75* **Cancel**:將計畫保存到檔案而不執行它;Claude 會列印檔案路徑,以便您稍後可以返回它

76 

77如果您開始新工作階段,Claude 會在頂部列印 `claude --resume` 命令,以便您稍後可以返回到您之前的對話。

78 

79## 相關資源

80 

81* [Claude Code on the web](/zh-TW/claude-code-on-the-web):ultraplan 執行的雲端基礎設施

82* [Plan mode](/zh-TW/permission-modes#analyze-before-you-edit-with-plan-mode):規劃在本機工作階段中的工作方式

83* [Find bugs with ultrareview](/zh-TW/ultrareview):ultraplan 的程式碼審查對應項,用於在合併前捕捉問題

84* [Remote Control](/zh-TW/remote-control):使用 claude.ai/code 介面與在您自己的機器上執行的工作階段

ultrareview.md +108 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 使用 Ultrareview 尋找錯誤

6 

7> 使用 /ultrareview 在雲端執行深度多代理程式碼審查,在合併前尋找並驗證錯誤。

8 

9<Note>

10 Ultrareview 是 Claude Code v2.1.86 及更新版本中提供的研究預覽功能。該功能、定價和可用性可能會根據反饋而變更。

11</Note>

12 

13Ultrareview 是在 Claude Code 網路基礎設施上執行的深度程式碼審查。當您執行 `/ultrareview` 時,Claude Code 會在遠端沙箱中啟動一群審查代理程式,以尋找您分支或拉取請求中的錯誤。

14 

15與本地 `/review` 相比,ultrareview 提供:

16 

17* **更高的信號品質**:每個報告的發現都經過獨立重現和驗證,因此結果專注於真實錯誤而非風格建議

18* **更廣泛的覆蓋範圍**:許多審查代理程式並行探索變更,這會發現單次審查可能遺漏的問題

19* **無本地資源使用**:審查完全在遠端沙箱中執行,因此您的終端在執行期間保持空閒,可用於其他工作

20 

21Ultrareview 需要使用 Claude.ai 帳戶進行身份驗證,因為它在 Claude Code 網路基礎設施上執行。如果您僅使用 API 金鑰登入,請先執行 `/login` 並使用 Claude.ai 進行身份驗證。使用 Amazon Bedrock、Google Cloud Vertex AI 或 Microsoft Foundry 的 Claude Code 時,Ultrareview 不可用,對於已啟用零資料保留的組織也不可用。

22 

23## 從 CLI 執行 ultrareview

24 

25從 Claude Code CLI 中的任何 git 儲存庫啟動審查。

26 

27```text theme={null}

28/ultrareview

29```

30 

31不帶引數時,ultrareview 審查您目前分支與預設分支之間的差異,包括工作樹中任何未提交和暫存的變更。Claude Code 會將儲存庫狀態打包並上傳到遠端沙箱進行審查。

32 

33若要改為審查 GitHub 拉取請求,請傳遞 PR 編號。

34 

35```text theme={null}

36/ultrareview 1234

37```

38 

39在 PR 模式中,遠端沙箱直接從 GitHub 複製拉取請求,而不是打包您的本地工作樹。PR 模式需要儲存庫上有 `github.com` 遠端。

40 

41<Tip>

42 如果您的儲存庫太大而無法打包,Claude Code 會提示您改用 PR 模式。推送您的分支並開啟草稿 PR,然後執行 `/ultrareview <PR-number>`。

43</Tip>

44 

45啟動前,Claude Code 會顯示確認對話框,其中包含審查範圍(審查分支時包括檔案和行數)、您剩餘的免費執行次數和估計成本。確認後,審查會在背景中繼續進行,您可以繼續使用您的工作階段。該命令僅在您使用 `/ultrareview` 叫用時執行;Claude 不會自動啟動 ultrareview。

46 

47## 定價和免費執行次數

48 

49Ultrareview 是一項高級功能,按額外使用量而非您計畫的包含使用量計費。

50 

51| 計畫 | 包含的免費執行次數 | 免費執行次數後 |

52| ----------------- | ------------------------ | -------------------------------------------------------------------------------------------------- |

53| Pro | 3 次免費執行,至 2026 年 5 月 5 日 | 按 [額外使用量](https://support.claude.com/zh-TW/articles/12429409-extra-usage-for-paid-claude-plans) 計費 |

54| Max | 3 次免費執行,至 2026 年 5 月 5 日 | 按 [額外使用量](https://support.claude.com/zh-TW/articles/12429409-extra-usage-for-paid-claude-plans) 計費 |

55| Team 和 Enterprise | 無 | 按 [額外使用量](https://support.claude.com/zh-TW/articles/12429409-extra-usage-for-paid-claude-plans) 計費 |

56 

57Pro 和 Max 訂閱者獲得三次免費 ultrareview 執行以試用該功能。這三次執行是每個帳戶的一次性配額,不會刷新,並於 2026 年 5 月 5 日過期。使用完全部三次後,或在免費執行期結束後,每次審查都會計入額外使用量,通常成本為 $5 至 $20,具體取決於變更的大小。一次執行在遠端工作階段開始時計算,因此您提前停止或未能完成的審查仍會使用一次免費執行。對於付費審查,額外使用量僅針對執行的部分計費。

58 

59由於 ultrareview 在免費執行次數外始終按額外使用量計費,您的帳戶或組織必須在啟動付費審查前啟用額外使用量。如果未啟用額外使用量,Claude Code 會阻止啟動並將您連結到計費設定,您可以在那裡開啟它。您也可以執行 `/extra-usage` 來檢查或變更您目前的設定。

60 

61## 追蹤執行中的審查

62 

63審查通常需要 5 到 10 分鐘。審查作為背景工作執行,因此您可以繼續在工作階段中工作、啟動其他命令或完全關閉終端。

64 

65使用 `/tasks` 查看執行中和已完成的審查、開啟審查的詳細檢視,或停止進行中的審查。停止審查會封存雲端工作階段,部分發現不會返回。審查完成後,已驗證的發現會在您的工作階段中顯示為通知。每個發現都包括檔案位置和問題說明,以便您可以直接要求 Claude 修復它。

66 

67## 非互動方式執行 ultrareview

68 

69使用 `claude ultrareview` 子命令從 CI 或指令碼啟動 ultrareview,無需互動工作階段。該子命令啟動與 `/ultrareview` 相同的審查,阻止直到遠端審查完成,將發現列印到 stdout,並在成功時以代碼 0 或失敗時以代碼 1 退出。

70 

71```bash theme={null}

72claude ultrareview

73claude ultrareview 1234

74claude ultrareview origin/main

75```

76 

77不帶引數時,該子命令審查您目前分支與預設分支之間的差異。傳遞 PR 編號以審查拉取請求,或傳遞基礎分支以改為審查與該分支的差異。叫用該子命令視為同意互動命令顯示的計費和條款提示。

78 

79進度訊息和即時工作階段 URL 會進入 stderr,以便 stdout 保持可解析。使用這些旗標來控制輸出和逾時:

80 

81| 旗標 | 說明 |

82| --------------------- | ---------------------------- |

83| `--json` | 列印原始 `bugs.json` 承載而不是格式化的發現 |

84| `--timeout <minutes>` | 等待審查完成的最大分鐘數。預設為 30 |

85 

86執行 `claude ultrareview` 需要與 `/ultrareview` 相同的身份驗證和額外使用量配置。當審查完成時(無論是否有發現),該子命令以代碼 0 退出;當審查無法啟動、遠端工作階段出錯或逾時時,以代碼 1 退出;當使用 Ctrl-C 中斷時,以代碼 130 退出。如果您中斷該子命令,遠端審查會繼續執行;請按照列印到 stderr 的工作階段 URL 在瀏覽器中觀看它。

87 

88如需在 GitHub 拉取請求上進行自動審查,[Code Review](/zh-TW/code-review) 直接與您的儲存庫整合,並將發現作為內嵌 PR 評論發佈,無需 CLI 步驟。

89 

90## Ultrareview 與 /review 的比較

91 

92兩個命令都審查程式碼,但它們針對工作流程的不同階段。

93 

94| | `/review` | `/ultrareview` |

95| ---- | ------------ | -------------------------------- |

96| 執行位置 | 在您的工作階段中本地執行 | 在雲端沙箱中遠端執行 |

97| 深度 | 單次審查 | 具有獨立驗證的多代理程式艦隊 |

98| 持續時間 | 幾秒到幾分鐘 | 大約 5 到 10 分鐘 |

99| 成本 | 計入正常使用量 | 免費執行次數,然後大約 $5 至 $20 每次審查作為額外使用量 |

100| 最適合 | 迭代時的快速反饋 | 在實質性變更前合併時的信心 |

101 

102使用 `/review` 在工作時獲得快速反饋。在合併實質性變更前使用 `/ultrareview`,當您想要更深入的審查以捕捉單次審查可能遺漏的問題時。

103 

104## 相關資源

105 

106* [Claude Code 網路版](/zh-TW/claude-code-on-the-web):了解遠端工作階段和雲端沙箱的工作原理

107* [使用 ultraplan 規劃複雜變更](/zh-TW/ultraplan):ultrareview 的規劃對應項,用於前期設計工作

108* [有效管理成本](/zh-TW/costs):追蹤使用量並設定支出限制

voice-dictation.md +191 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 語音聽寫

6 

7> 在 Claude Code CLI 中使用按住錄音或點擊錄音的語音聽寫功能來說出您的提示。

8 

9在 Claude Code CLI 中說出您的提示,而不是輸入它們。您的語音會即時轉錄到提示輸入中,因此您可以在同一條訊息中混合語音和輸入。使用 `/voice` 啟用聽寫,然後在說話時按住一個鍵或點擊一次開始,再點擊一次發送。

10 

11<Note>

12 語音聽寫需要 Claude Code v2.1.69 或更高版本。點擊模式需要 v2.1.116 或更高版本。使用 `claude --version` 檢查您的版本。

13</Note>

14 

15## 要求

16 

17語音聽寫會將您錄製的音頻串流傳輸到 Anthropic 的伺服器進行轉錄。音頻不在本地處理。語音轉文字服務僅在您使用 Claude.ai 帳戶進行身份驗證時可用,當 Claude Code 配置為直接使用 Anthropic API 金鑰、Amazon Bedrock、Google Vertex AI 或 Microsoft Foundry 時不可用。轉錄不會消耗 Claude 訊息或代幣,也不會計入 `/usage` 中顯示的限制。請參閱[資料使用](/zh-TW/data-usage)了解 Anthropic 如何處理您的資料。

18 

19語音聽寫還需要本地麥克風存取權限,因此它在遠端環境中不起作用,例如[網頁上的 Claude Code](/zh-TW/claude-code-on-the-web) 或 SSH 工作階段。在 WSL 中,語音聽寫需要 WSLg 來進行音頻存取,WSL2 在 Windows 11 上包含此功能。在 Windows 10 或 WSL1 上,改為在原生 Windows 中執行 Claude Code。

20 

21音頻錄製在 macOS、Linux 和 Windows 上使用內建的原生模組。在 Linux 上,如果原生模組無法載入,Claude Code 會回退到 ALSA utils 中的 `arecord` 或 SoX 中的 `rec`。如果兩者都不可用,`/voice` 會列印您的套件管理員的安裝命令。

22 

23Claude Code [VS Code 擴充功能](/zh-TW/vs-code)也支援語音聽寫,具有相同的 Claude.ai 帳戶要求。它在 VS Code Remote 工作階段中不可用,包括 SSH、Dev Containers 和 Codespaces,因為麥克風在您的本地機器上,而擴充功能在遠端主機上執行。

24 

25## 啟用語音聽寫

26 

27執行 `/voice` 以啟用聽寫。第一次啟用時,Claude Code 會執行麥克風檢查。在 macOS 上,如果您的終端機從未被授予權限,這會觸發系統麥克風權限提示。

28 

29```

30/voice

31Voice mode enabled (hold). Hold Space to record. Dictation language: en (/config to change).

32```

33 

34`/voice` 接受一個可選的模式引數:

35 

36| 命令 | 效果 |

37| :------------ | :---------------------------------- |

38| `/voice` | 切換開啟或關閉,保持目前模式 |

39| `/voice hold` | 在[按住模式](#hold-to-record)中啟用 |

40| `/voice tap` | 在[點擊模式](#tap-to-record-and-send)中啟用 |

41| `/voice off` | 停用 |

42 

43語音聽寫在工作階段之間保持。直接在您的[使用者設定檔案](/zh-TW/settings)中設定它,而不是執行 `/voice`:

44 

45```json theme={null}

46{

47 "voice": {

48 "enabled": true,

49 "mode": "tap"

50 }

51}

52```

53 

54啟用語音聽寫時,當提示為空時,輸入頁尾會顯示 `hold Space to speak` 提示。提示文字在兩種模式中都相同,如果您配置了[自訂狀態行](/zh-TW/statusline),則不會出現。

55 

56轉錄在兩種模式中都針對編碼詞彙進行了調整。常見的開發術語如 `regex`、`OAuth`、`JSON` 和 `localhost` 都能正確識別,您目前的專案名稱和 git 分支名稱會自動新增為識別提示。

57 

58## 按住錄音

59 

60按住模式是推送通話:錄製在您按住鍵時執行,在您鬆開時停止。這是預設模式。

61 

62按住 `Space` 開始錄製。Claude Code 通過監視來自您終端機的快速按鍵重複事件來偵測按住的鍵,因此在錄製開始前有一個簡短的預熱期。頁尾在預熱期間顯示 `keep holding…`,然後在錄製啟動後切換到即時波形。

63 

64前幾個按鍵重複字元在預熱期間輸入到輸入中,並在錄製啟動時自動移除。單個 `Space` 點擊仍會輸入一個空格,因為按住偵測只在快速重複時觸發。

65 

66<Tip>

67 若要跳過預熱,使用 `/voice tap` 切換到[點擊模式](#tap-to-record-and-send),或[重新繫結到修飾符組合](#rebind-the-dictation-key),例如 `meta+k`。修飾符組合在第一次按鍵時開始錄製。

68</Tip>

69 

70您的語音在您說話時出現在提示中,在轉錄最終確定之前會變暗。鬆開 `Space` 停止錄製並最終確定文字。轉錄會插入到您的游標位置,游標保持在插入文字的末尾,因此您可以按任何順序混合輸入和聽寫。再次按住 `Space` 以附加另一個錄製,或先移動游標以在提示中的其他位置插入語音:

71 

72```

73> refactor the auth middleware to ▮

74 # hold Space, speak "use the new token validation helper"

75> refactor the auth middleware to use the new token validation helper▮

76```

77 

78預設情況下,鬆開鍵會插入轉錄並等待您按 `Enter`。在 `voice` 設定物件中設定 `"autoSubmit": true` 以在您鬆開鍵時自動發送提示,只要轉錄至少有三個單詞。

79 

80## 點擊錄音並發送

81 

82點擊模式使用單個按鍵切換錄製:點擊一次開始,說話,然後再點擊一次發送提示。沒有預熱,您不需要保持鍵被按住。

83 

84使用 `/voice tap` 啟用點擊模式。當提示輸入為空時,點擊 `Space` 開始錄製。頁尾在錄製時顯示即時波形。再次點擊 `Space` 停止。Claude Code 插入轉錄,當轉錄至少有三個單詞時自動提交提示。較短的轉錄會被插入但不會被提交,因此意外點擊不會發送一個隨意的單詞。

85 

86第一次點擊只在提示輸入為空時開始錄製,因此您在撰寫訊息時仍然可以正常輸入空格。第二次點擊無論輸入內容如何都會停止錄製。錄製也會在 15 秒無聲或 2 分鐘總時間後自動停止。

87 

88## 變更聽寫語言

89 

90語音聽寫使用與控制 Claude 回應語言相同的[`language` 設定](/zh-TW/settings)。如果該設定為空,聽寫預設為英文。在 VS Code 擴充功能中,如果 `language` 為空,聽寫會在預設為英文之前使用 VS Code 的 `accessibility.voice.speechLanguage` 設定。

91 

92<Accordion title="支援的聽寫語言">

93 | 語言 | 代碼 |

94 | :--- | :--- |

95 | 捷克文 | `cs` |

96 | 丹麥文 | `da` |

97 | 荷蘭文 | `nl` |

98 | 英文 | `en` |

99 | 法文 | `fr` |

100 | 德文 | `de` |

101 | 希臘文 | `el` |

102 | 印地文 | `hi` |

103 | 印尼文 | `id` |

104 | 義大利文 | `it` |

105 | 日文 | `ja` |

106 | 韓文 | `ko` |

107 | 挪威文 | `no` |

108 | 波蘭文 | `pl` |

109 | 葡萄牙文 | `pt` |

110 | 俄文 | `ru` |

111 | 西班牙文 | `es` |

112 | 瑞典文 | `sv` |

113 | 土耳其文 | `tr` |

114 | 烏克蘭文 | `uk` |

115</Accordion>

116 

117在 `/config` 中或直接在設定中設定語言。您可以使用 [BCP 47 語言代碼](https://en.wikipedia.org/wiki/IETF_language_tag)或語言名稱:

118 

119```json theme={null}

120{

121 "language": "japanese"

122}

123```

124 

125如果您的 `language` 設定不在支援的清單中,`/voice` 會在啟用時警告您,並為聽寫回退到英文。Claude 的文字回應不受此回退的影響。

126 

127## 重新繫結聽寫鍵

128 

129聽寫鍵在 `Chat` 上下文中繫結到 `voice:pushToTalk`,預設為 `Space`。相同的繫結控制按住和點擊模式。在 [`~/.claude/keybindings.json`](/zh-TW/keybindings) 中重新繫結它:

130 

131```json theme={null}

132{

133 "bindings": [

134 {

135 "context": "Chat",

136 "bindings": {

137 "meta+k": "voice:pushToTalk",

138 "space": null

139 }

140 }

141 ]

142}

143```

144 

145設定 `"space": null` 會移除預設繫結。如果您想要兩個鍵都啟用,請省略它。

146 

147在按住模式中,避免繫結裸字母鍵,例如 `v`,因為按住偵測依賴於按鍵重複,字母在預熱期間輸入到提示中。使用 `Space`,或使用修飾符組合,例如 `meta+k` 以在第一次按鍵時開始錄製,無需預熱。點擊模式沒有預熱,因此大多數鍵都可以。

148 

149某些鍵不會傳遞到終端應用程式,根本無法繫結。例如,如果您嘗試繫結 `Caps Lock`,它會顯示錯誤。請參閱[自訂鍵盤快捷鍵](/zh-TW/keybindings)了解完整的快捷鍵語法和保留快捷鍵的清單。

150 

151## 疑難排解

152 

153語音聽寫未啟動或錄製時的常見問題:

154 

155* **`Voice mode requires a Claude.ai account`**:您使用 API 金鑰或第三方提供者進行了身份驗證。執行 `/login` 以使用 Claude.ai 帳戶登入。

156* **`Microphone access is denied`**:在系統設定中授予您的終端機麥克風權限。在 macOS 上,前往系統設定 → 隱私與安全 → 麥克風並啟用您的終端機應用程式,然後再次執行 `/voice`。在 Windows 上,前往設定 → 隱私與安全 → 麥克風並開啟桌面應用程式的麥克風存取,然後再次執行 `/voice`。如果您的終端機未列在 macOS 設定中,請參閱[終端機未列在 macOS 麥克風設定中](#terminal-not-listed-in-macos-microphone-settings)。

157* **Linux 上的 `No audio recording tool found`**:原生音頻模組無法載入,且未安裝回退。使用錯誤訊息中顯示的命令安裝 SoX,例如 `sudo apt-get install sox`。

158* **在按住模式中按住 `Space` 時沒有任何反應**:在按住時監視提示輸入。如果空格不斷累積,語音聽寫可能已關閉;執行 `/voice hold` 啟用它。如果只出現一個或兩個空格然後沒有任何反應,語音聽寫已開啟但按住偵測未觸發。按住偵測需要您的終端機發送按鍵重複事件,因此如果在作業系統層級停用了按鍵重複,它無法偵測按住的鍵。使用 `/voice tap` 切換到點擊模式以避免按鍵重複要求。

159* **在點擊模式中點擊 `Space` 輸入空格而不是錄製**:第一次點擊只在提示輸入為空時開始錄製。先清除輸入,或通過執行 `/voice tap` 檢查您是否處於點擊模式。

160* **`No audio detected from microphone`**:錄製已開始但捕獲了無聲。確認正確的輸入裝置設定為系統預設值,其輸入級別未靜音或接近零。在 Windows 上,開啟設定 → 系統 → 聲音 → 輸入並選擇您的麥克風。在 macOS 上,開啟系統設定 → 聲音 → 輸入。

161* **`No speech detected`**:音頻到達轉錄服務但未識別任何單詞。靠近麥克風說話,減少背景噪音,並確認您的[聽寫語言](#change-the-dictation-language)與您說話的語言相符。

162* **轉錄是亂碼或使用了錯誤的語言**:聽寫預設為英文。如果您用另一種語言聽寫,請先在 `/config` 中設定它。請參閱[變更聽寫語言](#change-the-dictation-language)。

163 

164### 終端機未列在 macOS 麥克風設定中

165 

166如果您的終端機應用程式未出現在系統設定 → 隱私與安全 → 麥克風下,則沒有您可以啟用的切換。重設您的終端機的權限狀態,以便下一次 `/voice` 執行觸發新的 macOS 權限提示。

167 

168<Steps>

169 <Step title="重設您的終端機的麥克風權限">

170 執行 `tccutil reset Microphone <bundle-id>`,將 `<bundle-id>` 替換為您的終端機的識別碼:內建終端機為 `com.apple.Terminal`,或 iTerm2 為 `com.googlecode.iterm2`。對於其他終端機,使用 `osascript -e 'id of app "AppName"'` 查詢識別碼。

171 

172 <Warning>

173 您可以執行 `tccutil reset Microphone` 而不需要套件 ID,但它會撤銷 Mac 上每個應用程式的麥克風存取權限,包括 Zoom 或 Slack 等應用程式。每個應用程式在下次使用時都需要重新請求存取權限,因此不要在活躍通話期間執行它。

174 </Warning>

175 </Step>

176 

177 <Step title="退出並重新啟動您的終端機">

178 macOS 不會重新提示已在執行的程序。使用 Cmd+Q 退出終端機應用程式,而不只是關閉其視窗,然後再次開啟它。

179 </Step>

180 

181 <Step title="觸發新的提示">

182 啟動 Claude Code 並執行 `/voice`。macOS 會提示麥克風存取;允許它。

183 </Step>

184</Steps>

185 

186## 另請參閱

187 

188* [自訂鍵盤快捷鍵](/zh-TW/keybindings):重新繫結 `voice:pushToTalk` 和其他 CLI 鍵盤動作

189* [設定設定](/zh-TW/settings):`voice`、`language` 和其他設定鍵的完整參考

190* [互動模式](/zh-TW/interactive-mode):鍵盤快捷鍵、輸入模式和工作階段控制

191* [命令](/zh-TW/commands):`/voice`、`/config` 和所有其他命令的參考

vs-code.md +511 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 在 VS Code 中使用 Claude Code

6 

7> 安裝並配置 VS Code 的 Claude Code 擴充功能。透過內聯差異、@-提及、計畫審查和快捷鍵獲得 AI 編碼協助。

8 

9<img src="https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=300652d5678c63905e6b0ea9e50835f8" alt="VS Code 編輯器,右側開啟 Claude Code 擴充功能面板,顯示與 Claude 的對話" width="2500" height="1155" data-path="images/vs-code-extension-interface.jpg" />

10 

11VS Code 擴充功能為 Claude Code 提供了原生圖形介面,直接整合到您的 IDE 中。這是在 VS Code 中使用 Claude Code 的推薦方式。

12 

13使用此擴充功能,您可以在接受 Claude 的計畫之前進行審查和編輯,在進行編輯時自動接受,從您的選擇中 @-提及具有特定行範圍的檔案,存取對話歷史記錄,以及在單獨的標籤或視窗中開啟多個對話。

14 

15## 先決條件

16 

17安裝前,請確保您擁有:

18 

19* VS Code 1.98.0 或更高版本

20* Anthropic 帳戶(首次開啟擴充功能時您將登入)。如果您使用第三方提供者(如 Amazon Bedrock 或 Google Vertex AI),請改為參閱[使用第三方提供者](#use-third-party-providers)。

21 

22<Tip>

23 此擴充功能包含 CLI(命令列介面),您可以從 VS Code 的整合終端機存取它以獲得進階功能。有關詳細資訊,請參閱 [VS Code 擴充功能與 Claude Code CLI](#vs-code-extension-vs-claude-code-cli)。

24</Tip>

25 

26## 安裝擴充功能

27 

28點擊您的 IDE 的連結以直接安裝:

29 

30* [為 VS Code 安裝](vscode:extension/anthropic.claude-code)

31* [為 Cursor 安裝](cursor:extension/anthropic.claude-code)

32 

33或在 VS Code 中,按 `Cmd+Shift+X`(Mac)或 `Ctrl+Shift+X`(Windows/Linux)開啟擴充功能檢視,搜尋「Claude Code」,然後點擊**安裝**。

34 

35<Note>如果安裝後擴充功能未出現,請重新啟動 VS Code 或從命令面板執行「Developer: Reload Window」。</Note>

36 

37## 開始使用

38 

39安裝後,您可以透過 VS Code 介面開始使用 Claude Code:

40 

41<Steps>

42 <Step title="開啟 Claude Code 面板">

43 在整個 VS Code 中,Spark 圖示表示 Claude Code:<img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/vs-code-spark-icon.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=3ca45e00deadec8c8f4b4f807da94505" alt="Spark icon" style={{display: "inline", height: "0.85em", verticalAlign: "middle"}} width="16" height="16" data-path="images/vs-code-spark-icon.svg" />

44 

45 開啟 Claude 的最快方式是點擊**編輯器工具列**(編輯器右上角)中的 Spark 圖示。當您開啟檔案時,該圖示才會出現。

46 

47 <img src="https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=eb4540325d94664c51776dbbfec4cf02" alt="VS Code 編輯器顯示編輯器工具列中的 Spark 圖示" width="2796" height="734" data-path="images/vs-code-editor-icon.png" />

48 

49 開啟 Claude Code 的其他方式:

50 

51 * **活動列**:點擊左側邊欄中的 Spark 圖示以開啟工作階段清單。點擊任何工作階段以將其作為完整編輯器標籤開啟,或開始新的工作階段。此圖示在活動列中始終可見。

52 * **命令面板**:`Cmd+Shift+P`(Mac)或 `Ctrl+Shift+P`(Windows/Linux),輸入「Claude Code」,然後選擇一個選項,例如「在新標籤中開啟」

53 * **狀態列**:點擊視窗右下角的 **✱ Claude Code**。即使沒有開啟檔案,這也有效。

54 

55 您可以拖動 Claude 面板以在 VS Code 中的任何位置重新定位它。有關詳細資訊,請參閱[自訂您的工作流程](#customize-your-workflow)。

56 </Step>

57 

58 <Step title="登入">

59 首次開啟面板時,會出現登入畫面。點擊**登入**並在您的瀏覽器中完成授權。

60 

61 如果您稍後看到**未登入 · 請執行 /login**,擴充功能會自動重新開啟登入畫面。如果它沒有出現,請從命令面板使用**Developer: Reload Window**重新載入視窗。

62 

63 如果您在 shell 中設定了 `ANTHROPIC_API_KEY` 但仍然看到登入提示,VS Code 可能沒有繼承您的 shell 環境。使用 `code .` 從終端機啟動 VS Code,以便它繼承您的環境變數,或改為使用您的 Claude 帳戶登入。

64 

65 登入後,會出現**學習 Claude Code** 檢查清單。透過點擊**顯示給我**來完成每一項,或用 X 關閉它。若要稍後重新開啟它,請在 VS Code 設定中的'擴充功能'→'Claude Code'下取消勾選**隱藏入門**。

66 </Step>

67 

68 <Step title="傳送提示">

69 要求 Claude 幫助您的程式碼或檔案,無論是解釋某些內容的工作原理、除錯問題還是進行變更。

70 

71 <Tip>Claude 會自動看到您選擇的文字。按 `Option+K`(Mac)/ `Alt+K`(Windows/Linux)也可以在您的提示中插入 @-提及參考(如 `@file.ts#5-10`)。</Tip>

72 

73 以下是詢問檔案中特定行的範例:

74 

75 <img src="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=ede3ed8d8d5f940e01c5de636d009cfd" alt="VS Code 編輯器,在 Python 檔案中選擇了第 2-3 行,Claude Code 面板顯示關於這些行的問題,帶有 @-提及參考" width="3288" height="1876" data-path="images/vs-code-send-prompt.png" />

76 </Step>

77 

78 <Step title="審查變更">

79 當 Claude 想要編輯檔案時,它會顯示原始內容和建議變更的並排比較,然後要求許可。您可以接受、拒絕或告訴 Claude 改為做什麼。如果您在接受前直接在差異檢視中編輯建議的內容,Claude 會被告知您修改了它,因此它不會假設檔案與其原始提案相符。

80 

81 <img src="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=e005f9b41c541c5c7c59c082f7c4841c" alt="VS Code 顯示 Claude 建議變更的差異,以及詢問是否進行編輯的許可提示" width="3292" height="1876" data-path="images/vs-code-edits.png" />

82 </Step>

83</Steps>

84 

85有關您可以使用 Claude Code 做什麼的更多想法,請參閱[常見工作流程](/zh-TW/common-workflows)。

86 

87<Tip>

88 從命令面板執行'Claude Code: Open Walkthrough'以獲得基礎知識的引導式導覽。

89</Tip>

90 

91## 使用提示框

92 

93提示框支援多項功能:

94 

95* **許可模式**:點擊提示框底部的模式指示器以切換模式。在正常模式下,Claude 在每個操作前要求許可。在 Plan Mode 中,Claude 描述它將做什麼,並在進行變更前等待批准。VS Code 會自動將計畫作為完整 markdown 文件開啟,您可以在其中添加內聯評論以在 Claude 開始前提供反饋。在自動接受模式下,Claude 進行編輯而不詢問。在 VS Code 設定中的 `claudeCode.initialPermissionMode` 下設定預設值。

96* **命令菜單**:點擊 `/` 或輸入 `/` 以開啟命令菜單。選項包括附加檔案、切換模型、切換擴展思考、查看計畫使用情況(`/usage`)以及啟動 [Remote Control](/zh-TW/remote-control) 工作階段(`/remote-control`)。'自訂'部分提供對 MCP servers、hooks、memory、permissions 和 plugins 的存取。帶有終端機圖示的項目在整合終端機中開啟。

97* **上下文指示器**:提示框顯示您使用了多少 Claude 的 context window。Claude 在需要時會自動壓縮,或您可以手動執行 `/compact`。

98* **擴展思考**:讓 Claude 花更多時間推理複雜問題。透過命令菜單(`/`)切換它。Claude 的推理在對話中顯示為摺疊的區塊:點擊一個區塊以讀取它,或按 `Ctrl+O` 以展開或摺疊工作階段中的每個思考區塊。有關詳細資訊,請參閱[擴展思考](/zh-TW/common-workflows#use-extended-thinking-thinking-mode)。

99* **多行輸入**:按 `Shift+Enter` 以添加新行而不傳送。這也適用於問題對話框的'其他'自由文字輸入。

100 

101### 參考檔案和資料夾

102 

103使用 @-提及為 Claude 提供有關特定檔案或資料夾的上下文。當您輸入 `@` 後跟檔案或資料夾名稱時,Claude 會讀取該內容,並可以回答有關它的問題或對其進行變更。Claude Code 支援模糊匹配,因此您可以輸入部分名稱來找到您需要的內容:

104 

105```text theme={null}

106> Explain the logic in @auth (fuzzy matches auth.js, AuthService.ts, etc.)

107> What's in @src/components/ (include a trailing slash for folders)

108```

109 

110對於大型 PDF,您可以要求 Claude 讀取特定頁面而不是整個檔案:單一頁面、範圍(如第 1-10 頁)或開放式範圍(如第 3 頁起)。

111 

112當您在編輯器中選擇文字時,Claude 可以自動看到您突出顯示的程式碼。提示框頁腳顯示選擇了多少行。按 `Option+K`(Mac)/ `Alt+K`(Windows/Linux)以插入帶有檔案路徑和行號的 @-提及(例如 `@app.ts#5-10`)。點擊選擇指示器以切換 Claude 是否可以看到您突出顯示的文字 - 眼睛斜線圖示表示選擇對 Claude 隱藏。

113 

114您也可以在將檔案拖動到提示框時按住 `Shift` 以將它們添加為附件。點擊任何附件上的 X 以將其從上下文中移除。

115 

116### 恢復過去的對話

117 

118點擊 Claude Code 面板頂部的**工作階段歷史記錄**按鈕以存取您的對話歷史記錄。您可以按關鍵字搜尋或按時間瀏覽(今天、昨天、過去 7 天等)。點擊任何對話以使用完整訊息歷史記錄恢復它。新工作階段會根據您的第一條訊息接收 AI 生成的標題。將滑鼠懸停在工作階段上以顯示重新命名和移除操作:重新命名以給它一個描述性標題,或移除以將其從清單中刪除。有關恢復工作階段的更多資訊,請參閱[常見工作流程](/zh-TW/common-workflows#resume-previous-conversations)。

119 

120### 從 Claude.ai 恢復遠端工作階段

121 

122如果您使用[網路上的 Claude Code](/zh-TW/claude-code-on-the-web),您可以直接在 VS Code 中恢復這些遠端工作階段。這需要使用 **Claude.ai Subscription** 登入,而不是 Anthropic Console。

123 

124<Steps>

125 <Step title="開啟工作階段歷史記錄">

126 點擊 Claude Code 面板頂部的**工作階段歷史記錄**按鈕。

127 </Step>

128 

129 <Step title="選擇遠端標籤">

130 對話框顯示兩個標籤:本機和遠端。點擊**遠端**以查看來自 claude.ai 的工作階段。

131 </Step>

132 

133 <Step title="選擇要恢復的工作階段">

134 瀏覽或搜尋您的遠端工作階段。點擊任何工作階段以下載它並在本機繼續對話。

135 </Step>

136</Steps>

137 

138<Note>

139 只有使用 GitHub 儲存庫啟動的網路工作階段才會出現在遠端標籤中。恢復會在本機載入對話歷史記錄;變更不會同步回 claude.ai。

140</Note>

141 

142## 自訂您的工作流程

143 

144一旦您啟動並執行,您可以重新定位 Claude 面板、執行多個工作階段或切換到終端機模式。

145 

146### 選擇 Claude 的位置

147 

148您可以拖動 Claude 面板以在 VS Code 中的任何位置重新定位它。抓住面板的標籤或標題列並拖動到:

149 

150* **次要邊欄**:視窗的右側。在您編碼時保持 Claude 可見。

151* **主要邊欄**:左側邊欄,帶有資源管理器、搜尋等圖示。

152* **編輯器區域**:將 Claude 作為標籤與您的檔案一起開啟。適用於側面任務。

153 

154<Tip>

155 將邊欄用於您的主要 Claude 工作階段,並為側面任務開啟其他標籤。Claude 會記住您偏好的位置。活動列工作階段清單圖示與 Claude 面板分開:工作階段清單在活動列中始終可見,而 Claude 面板圖示只有在面板停靠到左側邊欄時才會出現在那裡。

156</Tip>

157 

158### 執行多個對話

159 

160使用命令面板中的**在新標籤中開啟**或**在新視窗中開啟**以開始其他對話。每個對話維護自己的歷史記錄和上下文,允許您並行處理不同的任務。

161 

162使用標籤時,spark 圖示上的小彩色點表示狀態:藍色表示許可請求待處理,橙色表示 Claude 在標籤隱藏時完成。

163 

164### 切換到終端機模式

165 

166預設情況下,擴充功能開啟圖形聊天面板。如果您偏好 CLI 風格的介面,請開啟[使用終端機設定](vscode://settings/claudeCode.useTerminal)並勾選該框。

167 

168您也可以開啟 VS Code 設定(Mac 上的 `Cmd+,` 或 Windows/Linux 上的 `Ctrl+,`),前往「擴充功能」→「Claude Code」,然後勾選**使用終端機**。

169 

170## 管理 plugins

171 

172VS Code 擴充功能包含用於安裝和管理 [plugins](/zh-TW/plugins) 的圖形介面。在提示框中輸入 `/plugins` 以開啟**管理 plugins** 介面。

173 

174### 安裝 plugins

175 

176plugin 對話框顯示兩個標籤:**Plugins** 和 **Marketplaces**。

177 

178在 Plugins 標籤中:

179 

180* **已安裝的 plugins** 出現在頂部,帶有切換開關以啟用或停用它們

181* **來自您配置的市場的可用 plugins** 出現在下方

182* 搜尋以按名稱或描述篩選 plugins

183* 點擊任何可用 plugin 上的**安裝**

184 

185當您安裝 plugin 時,選擇安裝範圍:

186 

187* **為您安裝**:在您的所有專案中可用(使用者範圍)

188* **為此專案安裝**:與專案協作者共享(專案範圍)

189* **在本機安裝**:僅適用於您,僅在此儲存庫中(本機範圍)

190 

191### 管理市場

192 

193切換到 **Marketplaces** 標籤以添加或移除 plugin 來源:

194 

195* 輸入 GitHub 儲存庫、URL 或本機路徑以添加新市場

196* 點擊重新整理圖示以更新市場的 plugin 清單

197* 點擊垃圾桶圖示以移除市場

198 

199進行變更後,橫幅會提示您重新啟動 Claude Code 以應用更新。

200 

201<Note>

202 VS Code 中的 plugin 管理在幕後使用相同的 CLI 命令。您在擴充功能中配置的 plugins 和市場也可在 CLI 中使用,反之亦然。

203</Note>

204 

205有關 plugin 系統的更多資訊,請參閱 [Plugins](/zh-TW/plugins) 和 [Plugin marketplaces](/zh-TW/plugin-marketplaces)。

206 

207## 使用 Chrome 自動化瀏覽器任務

208 

209將 Claude 連接到您的 Chrome 瀏覽器以測試網路應用程式、使用主控台日誌進行除錯,以及在不離開 VS Code 的情況下自動化瀏覽器工作流程。這需要 [Claude in Chrome extension](https://chromewebstore.google.com/detail/claude/fcoeoabgfenejglbffodgkkbkcdhcgfn) 版本 1.0.36 或更高版本。

210 

211在提示框中輸入 `@browser` 後跟您想要 Claude 做的事情:

212 

213```text theme={null}

214@browser go to localhost:3000 and check the console for errors

215```

216 

217您也可以開啟附件菜單以選擇特定的瀏覽器工具,例如開啟新標籤或讀取頁面內容。

218 

219Claude 為瀏覽器任務開啟新標籤並共享您的瀏覽器登入狀態,因此它可以存取您已登入的任何網站。

220 

221有關設定說明、完整功能清單和故障排除,請參閱[使用 Claude Code 與 Chrome](/zh-TW/chrome)。

222 

223## VS Code 命令和快捷鍵

224 

225開啟命令面板(Mac 上的 `Cmd+Shift+P` 或 Windows/Linux 上的 `Ctrl+Shift+P`)並輸入「Claude Code」以查看 Claude Code 擴充功能的所有可用 VS Code 命令。

226 

227某些快捷鍵取決於哪個面板「獲得焦點」(接收鍵盤輸入)。當您的游標在程式碼檔案中時,編輯器獲得焦點。當您的游標在 Claude 的提示框中時,Claude 獲得焦點。使用 `Cmd+Esc` / `Ctrl+Esc` 在它們之間切換。

228 

229<Note>

230 這些是用於控制擴充功能的 VS Code 命令。並非所有內建 Claude Code 命令都在擴充功能中可用。有關詳細資訊,請參閱 [VS Code 擴充功能與 Claude Code CLI](#vs-code-extension-vs-claude-code-cli)。

231</Note>

232 

233| 命令 | 快捷鍵 | 描述 |

234| -------------------------- | ----------------------------------------------------- | ---------------------------------------------------------------- |

235| Focus Input | `Cmd+Esc`(Mac)/ `Ctrl+Esc`(Windows/Linux) | 在編輯器和 Claude 之間切換焦點 |

236| Open in Side Bar | - | 在左側邊欄中開啟 Claude |

237| Open in Terminal | - | 在終端機模式中開啟 Claude |

238| Open in New Tab | `Cmd+Shift+Esc`(Mac)/ `Ctrl+Shift+Esc`(Windows/Linux) | 將新對話作為編輯器標籤開啟 |

239| Open in New Window | - | 在單獨的視窗中開啟新對話 |

240| New Conversation | `Cmd+N`(Mac)/ `Ctrl+N`(Windows/Linux) | 開始新對話。需要 Claude 獲得焦點且 `enableNewConversationShortcut` 設定為 `true` |

241| Insert @-Mention Reference | `Option+K`(Mac)/ `Alt+K`(Windows/Linux) | 插入對目前檔案和選擇的參考(需要編輯器獲得焦點) |

242| Show Logs | - | 檢視擴充功能除錯日誌 |

243| Logout | - | 登出您的 Anthropic 帳戶 |

244 

245### 從其他工具啟動 VS Code 標籤

246 

247擴充功能在 `vscode://anthropic.claude-code/open` 註冊 URI 處理程式。使用它從您自己的工具開啟新的 Claude Code 標籤:shell 別名、瀏覽器書籤,或任何可以開啟 URL 的指令碼。如果 VS Code 尚未執行,開啟 URL 會先啟動它。如果 VS Code 已在執行,URL 會在目前獲得焦點的視窗中開啟。

248 

249使用您的作業系統的 URL 開啟程式叫用處理程式。

250 

251<Tabs>

252 <Tab title="macOS">

253 ```bash theme={null}

254 open "vscode://anthropic.claude-code/open"

255 ```

256 </Tab>

257 

258 <Tab title="Linux">

259 ```bash theme={null}

260 xdg-open "vscode://anthropic.claude-code/open"

261 ```

262 </Tab>

263 

264 <Tab title="Windows">

265 在 PowerShell 中:

266 

267 ```powershell theme={null}

268 Start-Process "vscode://anthropic.claude-code/open"

269 ```

270 

271 在 `cmd.exe` 中,`start` 將其第一個引號引數視為視窗標題,因此在 URL 之前傳遞空標題:

272 

273 ```cmd theme={null}

274 start "" "vscode://anthropic.claude-code/open"

275 ```

276 </Tab>

277</Tabs>

278 

279處理程式接受兩個選擇性查詢參數:

280 

281| 參數 | 描述 |

282| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |

283| `prompt` | 要在提示框中預先填入的文字。必須進行 URL 編碼。提示會預先填入但不會自動提交。 |

284| `session` | 要恢復的工作階段 ID,而不是開始新對話。工作階段必須屬於目前在 VS Code 中開啟的工作區。如果找不到工作階段,會改為開始新的對話。如果工作階段已在標籤中開啟,該標籤會獲得焦點。若要以程式設計方式擷取工作階段 ID,請參閱[繼續對話](/zh-TW/headless#continue-conversations)。 |

285 

286例如,若要開啟預先填入「review my changes」的標籤:

287 

288```text theme={null}

289vscode://anthropic.claude-code/open?prompt=review%20my%20changes

290```

291 

292若要啟動終端機工作階段而不是 VS Code 標籤,請使用 CLI 的 `claude-cli://` 處理程式。請參閱[從連結啟動工作階段](/zh-TW/deep-links)。

293 

294## 配置設定

295 

296擴充功能有兩種類型的設定:

297 

298* **VS Code 中的擴充功能設定**:控制擴充功能在 VS Code 中的行為。使用 `Cmd+,`(Mac)或 `Ctrl+,`(Windows/Linux)開啟,然後前往「擴充功能」→「Claude Code」。您也可以輸入 `/` 並選擇**一般配置**以開啟設定。

299* **`~/.claude/settings.json` 中的 Claude Code 設定**:在擴充功能和 CLI 之間共享。用於允許的命令、環境變數、hooks 和 MCP servers。有關詳細資訊,請參閱[設定](/zh-TW/settings)。

300 

301<Tip>

302 將 `"$schema": "https://json.schemastore.org/claude-code-settings.json"` 添加到您的 `settings.json` 以在 VS Code 中直接獲得所有可用設定的自動完成和內聯驗證。

303</Tip>

304 

305### 擴充功能設定

306 

307| 設定 | 預設值 | 描述 |

308| --------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

309| `useTerminal` | `false` | 以終端機模式而不是圖形面板啟動 Claude |

310| `initialPermissionMode` | `default` | 控制新對話的批准提示:`default`、`plan`、`acceptEdits` 或 `bypassPermissions`。請參閱[許可模式](/zh-TW/permission-modes)。 |

311| `preferredLocation` | `panel` | Claude 開啟的位置:`sidebar`(右側)或 `panel`(新標籤) |

312| `autosave` | `true` | Claude 讀取或寫入檔案前自動儲存檔案 |

313| `useCtrlEnterToSend` | `false` | 使用 Ctrl/Cmd+Enter 而不是 Enter 來傳送提示 |

314| `enableNewConversationShortcut` | `false` | 啟用 Cmd/Ctrl+N 以開始新對話 |

315| `hideOnboarding` | `false` | 隱藏入門檢查清單(畢業帽圖示) |

316| `respectGitIgnore` | `true` | 從檔案搜尋中排除 .gitignore 模式 |

317| `usePythonEnvironment` | `true` | 執行 Claude 時啟動工作區的 Python 環境。需要 Python 擴充功能。 |

318| `environmentVariables` | `[]` | 為 Claude 程序設定環境變數。改為使用 Claude Code 設定以進行共享配置。 |

319| `disableLoginPrompt` | `false` | 跳過身份驗證提示(用於第三方提供者設定) |

320| `allowDangerouslySkipPermissions` | `false` | 將 [Auto mode](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode) 和 Bypass permissions 添加到模式選擇器。Auto mode 有[計畫、管理員、模型和提供者要求](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode),因此即使此切換打開,該選項也可能保持不可用。僅在沒有網際網路存取的沙箱中使用 Bypass permissions。 |

321| `claudeProcessWrapper` | - | 用於啟動 Claude 程序的可執行檔路徑 |

322 

323## VS Code 擴充功能與 Claude Code CLI

324 

325Claude Code 既可作為 VS Code 擴充功能(圖形面板)也可作為 CLI(終端機中的命令列介面)使用。某些功能僅在 CLI 中可用。如果您需要 CLI 專用功能,請在 VS Code 的整合終端機中執行 `claude`。

326 

327| 功能 | CLI | VS Code 擴充功能 |

328| ------------- | --------------------- | ---------------------------------------- |

329| 命令和 skills | [全部](/zh-TW/commands) | 子集(輸入 `/` 以查看可用的) |

330| MCP server 配置 | 是 | 部分(透過 CLI 添加伺服器;使用聊天面板中的 `/mcp` 管理現有伺服器) |

331| Checkpoints | 是 | 是 |

332| `!` bash 快捷方式 | 是 | 否 |

333| Tab 完成 | 是 | 否 |

334 

335### 使用 checkpoints 進行倒帶

336 

337VS Code 擴充功能支援 checkpoints,它們追蹤 Claude 的檔案編輯並讓您倒帶到先前的狀態。將滑鼠懸停在任何訊息上以顯示倒帶按鈕,然後從三個選項中選擇:

338 

339* **從此處分支對話**:從此訊息開始新的對話分支,同時保持所有程式碼變更完整

340* **將程式碼倒帶到此處**:將檔案變更還原回對話中的此點,同時保持完整的對話歷史記錄

341* **分支對話並倒帶程式碼**:開始新的對話分支並將檔案變更還原到此點

342 

343有關 checkpoints 如何工作及其限制的完整詳細資訊,請參閱 [Checkpointing](/zh-TW/checkpointing)。

344 

345### 在 VS Code 中執行 CLI

346 

347若要在 VS Code 中使用 CLI,請開啟整合終端機(Windows/Linux 上的 `` Ctrl+` `` 或 Mac 上的 `` Cmd+` ``)並執行 `claude`。CLI 會自動與您的 IDE 整合,以獲得差異檢視和診斷共享等功能。

348 

349如果使用外部終端機,請在 Claude Code 中執行 `/ide` 以將其連接到 VS Code。

350 

351### 在擴充功能和 CLI 之間切換

352 

353擴充功能和 CLI 共享相同的對話歷史記錄。若要在 CLI 中繼續擴充功能對話,請在終端機中執行 `claude --resume`。這會開啟一個互動式選擇器,您可以在其中搜尋並選擇您的對話。

354 

355### 在提示中包含終端機輸出

356 

357使用 `@terminal:name` 在您的提示中參考終端機輸出,其中 `name` 是終端機的標題。這讓 Claude 可以看到命令輸出、錯誤訊息或日誌,而無需複製貼上。

358 

359### 監控背景程序

360 

361當 Claude 執行長時間執行的命令時,擴充功能在狀態列中顯示進度。但是,與 CLI 相比,背景任務的可見性受限。為了獲得更好的可見性,讓 Claude 輸出命令,以便您可以在 VS Code 的整合終端機中執行它。

362 

363### 使用 MCP 連接到外部工具

364 

365MCP(Model Context Protocol)servers 讓 Claude 存取外部工具、資料庫和 API。

366 

367若要添加 MCP server,請開啟整合終端機(`` Ctrl+` `` 或 `` Cmd+` ``)並執行 `claude mcp add`。下面的範例添加了 GitHub 的遠端 MCP server,它使用作為標頭傳遞的[個人存取令牌](https://github.com/settings/personal-access-tokens)進行身份驗證:

368 

369```bash theme={null}

370claude mcp add --transport http github https://api.githubcopilot.com/mcp/ \

371 --header "Authorization: Bearer YOUR_GITHUB_PAT"

372```

373 

374配置後,要求 Claude 使用工具(例如「Review PR #456」)。

375 

376若要在不離開 VS Code 的情況下管理 MCP servers,請在聊天面板中輸入 `/mcp`。MCP 管理對話框讓您啟用或停用伺服器、重新連接到伺服器以及管理 OAuth 身份驗證。有關可用伺服器,請參閱 [MCP 文件](/zh-TW/mcp)。

377 

378## 使用 git

379 

380Claude Code 與 git 整合以幫助直接在 VS Code 中進行版本控制工作流程。要求 Claude 提交變更、建立拉取請求或跨分支工作。

381 

382### 建立提交和拉取請求

383 

384Claude 可以暫存變更、編寫提交訊息並根據您的工作建立拉取請求:

385 

386```text theme={null}

387> commit my changes with a descriptive message

388> create a pr for this feature

389> summarize the changes I've made to the auth module

390```

391 

392建立拉取請求時,Claude 會根據實際程式碼變更生成描述,並可以添加有關測試或實現決策的上下文。

393 

394### 使用 git worktrees 進行並行任務

395 

396使用 `--worktree`(`-w`)標誌以在具有自己的檔案和分支的隔離 worktree 中啟動 Claude:

397 

398```bash theme={null}

399claude --worktree feature-auth

400```

401 

402每個 worktree 維護獨立的檔案狀態,同時共享 git 歷史記錄。這可防止 Claude 實例在處理不同任務時相互干擾。有關更多詳細資訊,請參閱[使用 Git worktrees 執行並行 Claude Code 工作階段](/zh-TW/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees)。

403 

404## 使用第三方提供者

405 

406預設情況下,Claude Code 直接連接到 Anthropic 的 API。如果您的組織使用 Amazon Bedrock、Google Vertex AI 或 Microsoft Foundry 來存取 Claude,請配置擴充功能以改為使用您的提供者:

407 

408<Steps>

409 <Step title="停用登入提示">

410 開啟[停用登入提示設定](vscode://settings/claudeCode.disableLoginPrompt)並勾選該框。

411 

412 您也可以開啟 VS Code 設定(Mac 上的 `Cmd+,` 或 Windows/Linux 上的 `Ctrl+,`),搜尋'Claude Code login',然後勾選**停用登入提示**。

413 </Step>

414 

415 <Step title="配置您的提供者">

416 遵循您的提供者的設定指南:

417 

418 * [Amazon Bedrock 上的 Claude Code](/zh-TW/amazon-bedrock)

419 * [Google Vertex AI 上的 Claude Code](/zh-TW/google-vertex-ai)

420 * [Microsoft Foundry 上的 Claude Code](/zh-TW/microsoft-foundry)

421 

422 這些指南涵蓋在 `~/.claude/settings.json` 中配置您的提供者,這確保您的設定在 VS Code 擴充功能和 CLI 之間共享。

423 </Step>

424</Steps>

425 

426## 安全和隱私

427 

428您的程式碼保持私密。Claude Code 處理您的程式碼以提供協助,但不使用它來訓練模型。有關資料處理和如何選擇退出日誌記錄的詳細資訊,請參閱[資料和隱私](/zh-TW/data-usage)。

429 

430啟用自動編輯許可後,Claude Code 可以修改 VS Code 配置檔案(如 `settings.json` 或 `tasks.json`),VS Code 可能會自動執行。為了在處理不受信任的程式碼時降低風險:

431 

432* 為不受信任的工作區啟用 [VS Code 受限模式](https://code.visualstudio.com/docs/editor/workspace-trust#_restricted-mode)

433* 使用手動批准模式而不是自動接受進行編輯

434* 在接受變更前仔細審查它們

435 

436### 內建 IDE MCP server

437 

438當擴充功能處於活動狀態時,它會執行一個本機 MCP server,CLI 會自動連接到該伺服器。這是 CLI 在 VS Code 的原生差異檢視器中開啟差異、讀取您目前的選擇以進行 `@`-提及,以及 — 當您在 Jupyter notebook 中工作時 — 要求 VS Code 執行儲存格的方式。

439 

440伺服器名為 `ide`,從 `/mcp` 隱藏,因為沒有什麼可配置的。但是,如果您的組織使用 `PreToolUse` hook 來允許列出 MCP 工具,您需要知道它存在。

441 

442**傳輸和身份驗證。** 伺服器綁定到 `127.0.0.1` 上的隨機高埠,無法從其他機器訪問。每次擴充功能啟動都會生成一個新的隨機身份驗證令牌,CLI 必須提供該令牌才能連接。令牌會寫入 `~/.claude/ide/` 下的鎖定檔案,權限為 `0600`,在 `0700` 目錄中,因此只有執行 VS Code 的使用者可以讀取它。

443 

444**向模型公開的工具。** 伺服器託管十幾個工具,但只有兩個對模型可見。其餘的是 CLI 用於自己的 UI 的內部 RPC — 開啟差異、讀取選擇、儲存檔案 — 在工具清單到達 Claude 之前被篩選出來。

445 

446| 工具名稱(如 hooks 所見) | 它的作用 | 寫入? |

447| -------------------------- | -------------------------------------------------- | --- |

448| `mcp__ide__getDiagnostics` | 返回語言伺服器診斷 — VS Code 的「問題」面板中的錯誤和警告。可選地限定於一個檔案。 | 否 |

449| `mcp__ide__executeCode` | 在活動 Jupyter notebook 的核心中執行 Python 程式碼。請參閱下面的確認流程。 | 是 |

450 

451**Jupyter 執行始終先詢問。** `mcp__ide__executeCode` 無法以靜默方式執行任何內容。在每次呼叫時,程式碼會作為新儲存格插入到活動 notebook 的末尾,VS Code 會將其滾動到檢視中,原生 Quick Pick 會要求您**執行**或**取消**。取消 — 或使用 `Esc` 關閉選擇器 — 會向 Claude 返回錯誤,沒有任何內容執行。當沒有活動 notebook、未安裝 Jupyter 擴充功能(`ms-toolsai.jupyter`)或核心不是 Python 時,該工具也會直接拒絕。

452 

453<Note>

454 Quick Pick 確認與 `PreToolUse` hooks 分開。`mcp__ide__executeCode` 的允許列表條目讓 Claude *提議*執行儲存格;VS Code 內的 Quick Pick 是讓它*實際*執行的原因。

455</Note>

456 

457<a id="troubleshooting" />

458 

459## 修復常見問題

460 

461### 擴充功能無法安裝

462 

463* 確保您有相容的 VS Code 版本(1.98.0 或更高版本)

464* 檢查 VS Code 是否有權限安裝擴充功能

465* 嘗試從 [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code) 直接安裝

466 

467### Spark 圖示不可見

468 

469當您開啟檔案時,Spark 圖示會出現在**編輯器工具列**(編輯器右上角)中。如果您看不到它:

470 

4711. **開啟檔案**:該圖示需要開啟檔案。僅開啟資料夾是不夠的。

4722. **檢查 VS Code 版本**:需要 1.98.0 或更高版本(幫助 → 關於)

4733. **重新啟動 VS Code**:從命令面板執行「Developer: Reload Window」

4744. **停用衝突的擴充功能**:暫時停用其他 AI 擴充功能(Cline、Continue 等)

4755. **檢查工作區信任**:擴充功能在受限模式下不工作

476 

477或者,點擊**狀態列**(右下角)中的「✱ Claude Code」。即使沒有開啟檔案,這也有效。您也可以使用**命令面板**(`Cmd+Shift+P` / `Ctrl+Shift+P`)並輸入「Claude Code」。

478 

479### Claude Code 從不回應

480 

481如果 Claude Code 沒有回應您的提示:

482 

4831. **檢查您的網際網路連接**:確保您有穩定的網際網路連接

4842. **開始新對話**:嘗試開始新的對話以查看問題是否持續

4853. **嘗試 CLI**:從終端機執行 `claude` 以查看您是否獲得更詳細的錯誤訊息

486 

487如果問題持續,請[在 GitHub 上提交問題](https://github.com/anthropics/claude-code/issues),並提供有關錯誤的詳細資訊。

488 

489## 卸載擴充功能

490 

491若要卸載 Claude Code 擴充功能:

492 

4931. 開啟擴充功能檢視(Mac 上的 `Cmd+Shift+X` 或 Windows/Linux 上的 `Ctrl+Shift+X`)

4942. 搜尋「Claude Code」

4953. 點擊**卸載**

496 

497若要也移除擴充功能資料並重設所有設定:

498 

499```bash theme={null}

500rm -rf ~/.vscode/globalStorage/anthropic.claude-code

501```

502 

503如需其他幫助,請參閱[故障排除指南](/zh-TW/troubleshooting)。

504 

505## 後續步驟

506 

507現在您已在 VS Code 中設定了 Claude Code:

508 

509* [探索常見工作流程](/zh-TW/common-workflows)以充分利用 Claude Code

510* [設定 MCP servers](/zh-TW/mcp) 以使用外部工具擴展 Claude 的功能。使用 CLI 添加伺服器,然後使用聊天面板中的 `/mcp` 管理它們。

511* [配置 Claude Code 設定](/zh-TW/settings)以自訂允許的命令、hooks 等。這些設定在擴充功能和 CLI 之間共享。

web-quickstart.md +220 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 在網頁上開始使用 Claude Code

6 

7> 在雲端從瀏覽器或手機執行 Claude Code。連接 GitHub 儲存庫、提交任務,並在無需本地設定的情況下檢查 PR。

8 

9<Note>

10 Claude Code on the web 目前處於研究預覽階段,適用於 Pro、Max 和 Team 用戶,以及擁有高級席位或 Chat + Claude Code 席位的企業用戶。

11</Note>

12 

13Claude Code on the web 在 Anthropic 管理的雲端基礎設施上執行,而不是在您的機器上。從瀏覽器或 Claude 行動應用程式的 [claude.ai/code](https://claude.ai/code) 提交任務。

14 

15您需要一個 GitHub 儲存庫來[開始使用](#connect-github-and-create-an-environment)。Claude 將其複製到隔離的虛擬機器中、進行更改,並為您推送一個分支以供檢查。會話在設備間持續存在,因此您在筆記型電腦上開始的任務可以稍後從手機上檢查。

16 

17Claude Code on the web 適用於:

18 

19* **並行任務**:同時執行多個獨立任務,每個任務在自己的會話和分支中,無需管理多個 worktrees

20* **您本地沒有的儲存庫**:Claude 在每個會話中新鮮複製儲存庫,因此您無需簽出它

21* **不需要頻繁引導的任務**:提交一個定義明確的任務,做其他事情,並在 Claude 完成時檢查結果

22* **代碼問題和探索**:理解代碼庫或追蹤功能如何實現,無需本地簽出

23 

24對於需要您本地配置、工具或環境的工作,在本地執行 Claude Code 或使用 [Remote Control](/zh-TW/remote-control) 更合適。

25 

26## 會話如何執行

27 

28當您提交任務時:

29 

301. **複製和準備**:您的儲存庫被複製到 Anthropic 管理的 VM,並且您的[設定指令碼](/zh-TW/claude-code-on-the-web#setup-scripts)會在配置時執行。

312. **配置網路**:根據您環境的[存取級別](/zh-TW/claude-code-on-the-web#access-levels)設定網際網路存取。

323. **工作**:Claude 分析代碼、進行更改、執行測試並檢查其工作。您可以全程觀看和引導,或者離開並在完成時返回。

334. **推送分支**:當 Claude 達到停止點時,它會將其分支推送到 GitHub。您檢查差異、留下內聯評論、建立 PR 或發送另一條訊息以繼續。

34 

35推送分支時會話不會關閉。PR 建立和進一步編輯都在同一對話中進行。

36 

37## 比較執行 Claude Code 的方式

38 

39Claude Code 在任何地方的行為都相同。改變的是代碼執行的位置以及您的本地配置是否可用。Desktop 應用程式提供本地和雲端會話,因此其下面的答案取決於您選擇的是哪一個:

40 

41| | 在網頁上 | Remote Control | Terminal CLI | Desktop 應用程式 |

42| :---------------------------------- | :----------------------------------------------------------------------------------------------- | :---------------- | :----------- | :----------- |

43| **代碼執行於** | Anthropic 雲端 VM | 您的機器 | 您的機器 | 您的機器或雲端 VM |

44| **您從以下位置聊天** | claude.ai 或行動應用程式 | claude.ai 或行動應用程式 | 您的終端 | Desktop UI |

45| **使用您的本地配置** | 否,僅儲存庫 | 是 | 是 | 本地為是,雲端為否 |

46| **需要 GitHub** | 是,或透過 `--remote` [捆綁本地儲存庫](/zh-TW/claude-code-on-the-web#send-local-repositories-without-github) | 否 | 否 | 僅限雲端會話 |

47| **如果您斷開連接,保持執行** | 是 | 終端保持開啟時 | 否 | 取決於會話類型 |

48| **[權限模式](/zh-TW/permission-modes)** | 自動接受編輯、Plan | 詢問、自動接受編輯、Plan | 所有模式 | 取決於會話類型 |

49| **網路存取** | 每個環境可配置 | 您機器的網路 | 您機器的網路 | 取決於會話類型 |

50 

51請參閱 [terminal quickstart](/zh-TW/quickstart)、[Desktop 應用程式](/zh-TW/desktop) 或 [Remote Control](/zh-TW/remote-control) 文件以設定這些。

52 

53## 連接 GitHub 並建立環境

54 

55設定是一次性過程。如果您已經使用 GitHub CLI,您可以[從您的終端執行此操作](#connect-from-your-terminal),而不是使用瀏覽器。

56 

57<Steps>

58 <Step title="訪問 claude.ai/code">

59 前往 [claude.ai/code](https://claude.ai/code) 並使用您的 Anthropic 帳戶登入。

60 </Step>

61 

62 <Step title="安裝 Claude GitHub App">

63 登入後,claude.ai/code 會提示您連接 GitHub。按照提示安裝 Claude GitHub App 並授予其存取您的儲存庫的權限。雲端會話適用於現有的 GitHub 儲存庫,因此要啟動新項目,請先[在 GitHub 上建立空儲存庫](https://github.com/new)。

64 </Step>

65 

66 <Step title="建立您的環境">

67 連接 GitHub 後,系統會提示您建立雲端環境。環境控制 Claude 在會話期間可以存取的網路以及在建立新會話時執行的內容。請參閱[已安裝的工具](/zh-TW/claude-code-on-the-web#installed-tools)以了解無需任何配置即可使用的內容。

68 

69 表單具有以下欄位:

70 

71 * **名稱**:顯示標籤。當您為不同的項目或存取級別有多個環境時很有用。

72 * **網路存取**:控制會話可以在網際網路上到達的內容。預設值 `Trusted` 允許連接到[常見套件登錄](/zh-TW/claude-code-on-the-web#default-allowed-domains)(如 npm、PyPI 和 RubyGems),同時阻止一般網際網路存取。

73 * **環境變數**:可選變數,在每個會話中可用,採用 `.env` 格式。不要用引號包裝值,因為引號會儲存為值的一部分。這些對任何可以編輯此環境的人都可見。

74 * **設定指令碼**:可選的 Bash 指令碼,在 Claude Code 啟動前執行。使用它來安裝雲端 VM 不包含的系統工具,如 `apt install -y gh`。結果會被[快取](/zh-TW/claude-code-on-the-web#environment-caching),因此指令碼不會在每個會話上重新執行。請參閱[設定指令碼](/zh-TW/claude-code-on-the-web#setup-scripts)以了解範例和除錯提示。

75 

76 對於第一個項目,保留預設值並點擊**建立環境**。您可以[稍後編輯它或為不同的項目建立其他環境](/zh-TW/claude-code-on-the-web#configure-your-environment)。

77 </Step>

78</Steps>

79 

80### 從您的終端連接

81 

82如果您已經使用 GitHub CLI (`gh`),您可以在不打開瀏覽器的情況下設定 Claude Code on the web。這需要 [Claude Code CLI](/zh-TW/quickstart)。`/web-setup` 讀取您的本地 `gh` 令牌,將其連結到您的 Claude 帳戶,並在您沒有雲端環境時建立預設雲端環境。

83 

84<Note>

85 啟用了[零資料保留](/zh-TW/zero-data-retention)的組織無法使用 `/web-setup` 或其他雲端會話功能。如果未安裝或驗證 GitHub CLI,`/web-setup` 會改為開啟瀏覽器上線流程。

86</Note>

87 

88<Steps>

89 <Step title="使用 GitHub CLI 進行驗證">

90 在您的 shell 中,如果您還沒有驗證 GitHub CLI,請進行驗證:

91 

92 ```bash theme={null}

93 gh auth login

94 ```

95 </Step>

96 

97 <Step title="登入 Claude">

98 在 Claude Code CLI 中,執行 `/login` 以使用您的 claude.ai 帳戶登入。如果您已經登入,請跳過此步驟。

99 </Step>

100 

101 <Step title="執行 /web-setup">

102 在 Claude Code CLI 中,執行:

103 

104 ```text theme={null}

105 /web-setup

106 ```

107 

108 這會將您的 `gh` 令牌同步到您的 Claude 帳戶。如果您還沒有雲端環境,`/web-setup` 會建立一個具有 Trusted 網路存取且沒有設定指令碼的環境。您可以[稍後編輯環境或新增變數](/zh-TW/claude-code-on-the-web#configure-your-environment)。一旦 `/web-setup` 完成,您可以使用 [`--remote`](/zh-TW/claude-code-on-the-web#from-terminal-to-web) 從您的終端啟動雲端會話,或使用 [`/schedule`](/zh-TW/routines) 設定定期任務。

109 </Step>

110</Steps>

111 

112## 啟動任務

113 

114連接 GitHub 並建立環境後,您就可以提交任務了。

115 

116<Steps>

117 <Step title="選擇儲存庫和分支">

118 從 [claude.ai/code](https://claude.ai/code) 或 Claude 行動應用程式中的 Code 標籤,點擊輸入框下方的儲存庫選擇器,並為 Claude 選擇要在其中工作的儲存庫。每個儲存庫都顯示一個分支選擇器。將其更改為從功能分支而不是預設分支啟動 Claude。您可以新增多個儲存庫以在一個會話中跨它們工作。

119 </Step>

120 

121 <Step title="選擇權限模式">

122 輸入框旁邊的模式下拉菜單預設為**自動接受編輯**,其中 Claude 進行更改並推送分支而無需停止以獲得批准。如果您希望 Claude 提出方法並在編輯文件前等待您的同意,請切換到 **Plan mode**。雲端會話不提供詢問權限、自動模式或繞過權限。請參閱[權限模式](/zh-TW/permission-modes)以了解完整列表。

123 </Step>

124 

125 <Step title="描述任務並提交">

126 輸入您想要的內容的描述並按 Enter。要具體:

127 

128 * 命名文件或函數:"新增帶有設定說明的 README" 或 "修復 `tests/test_auth.py` 中失敗的驗證測試" 比 "修復測試" 更好

129 * 如果您有錯誤輸出,請貼上

130 * 描述預期行為,而不僅僅是症狀

131 

132 Claude 複製儲存庫、執行您配置的設定指令碼(如果已配置)並開始工作。每個任務都有自己的會話和自己的分支,因此您無需等待一個完成就可以啟動另一個。

133 </Step>

134</Steps>

135 

136## 預填充會話

137 

138您可以透過將查詢參數新增到 [claude.ai/code](https://claude.ai/code) URL 來預填充新會話的提示、儲存庫和環境。使用此功能來建立整合,例如問題追蹤器中的按鈕,該按鈕使用問題描述作為提示打開 Claude Code。

139 

140| 參數 | 描述 |

141| :------------- | :------------------------------------------------------------- |

142| `prompt` | 要在輸入框中預填充的提示文本。也接受別名 `q`。 |

143| `prompt_url` | 要從中獲取提示文本的 URL,用於太長而無法嵌入查詢字符串的提示。URL 必須允許跨源請求。設定 `prompt` 時忽略。 |

144| `repositories` | 要預選的 `owner/repo` 段的逗號分隔列表。也接受別名 `repo`。 |

145| `environment` | [環境](#connect-github-and-create-an-environment)的名稱或 ID 以預選。 |

146 

147對每個值進行 URL 編碼。下面的範例使用已選擇的提示和儲存庫打開表單:

148 

149```text theme={null}

150https://claude.ai/code?prompt=Fix%20the%20login%20bug&repositories=acme/webapp

151```

152 

153## 檢查和迭代

154 

155當 Claude 完成時,檢查更改、在特定行上留下反饋,並繼續進行直到差異看起來正確。

156 

157<Steps>

158 <Step title="打開差異檢視">

159 差異指示器顯示整個會話中新增和移除的行,例如 `+42 -18`。選擇它以打開差異檢視,左側有文件列表,右側有更改。

160 </Step>

161 

162 <Step title="留下內聯評論">

163 選擇差異中的任何行,輸入您的反饋,然後按 Enter。評論會排隊直到您發送下一條訊息,然後它們會與其捆綁。Claude 看到 "在 `src/auth.ts:47`,不要在這裡捕捉錯誤" 以及您的主要指令,因此您無需描述問題所在。

164 </Step>

165 

166 <Step title="建立拉取請求">

167 當差異看起來正確時,選擇差異檢視頂部的**建立 PR**。您可以將其作為完整 PR、草稿打開,或跳轉到 GitHub 的撰寫頁面,其中包含生成的標題和描述。

168 </Step>

169 

170 <Step title="在 PR 後繼續迭代">

171 建立 PR 後會話保持活躍。將 CI 失敗輸出或審查者評論貼上到聊天中,並要求 Claude 解決它們。要讓 Claude 自動監控 PR,請參閱[自動修復拉取請求](/zh-TW/claude-code-on-the-web#auto-fix-pull-requests)。

172 </Step>

173</Steps>

174 

175## 設定故障排除

176 

177### 連接 GitHub 後沒有儲存庫出現

178 

179Claude GitHub App 需要對您想要使用的每個儲存庫的明確存取權限。在 github.com 上,打開**設定 → 應用程式 → Claude → 配置**並驗證您的儲存庫是否列在**儲存庫存取**下。私有儲存庫需要與公開儲存庫相同的授權。

180 

181### 頁面只顯示 GitHub 登入按鈕

182 

183雲端會話需要連接的 GitHub 帳戶。透過上面的瀏覽器流程連接,或者如果您使用 GitHub CLI,從您的終端執行 `/web-setup`。如果您根本不想連接 GitHub,請參閱 [Remote Control](/zh-TW/remote-control) 以在您自己的機器上執行 Claude Code 並從網頁監控它。

184 

185### "不適用於選定的組織"

186 

187企業組織可能需要管理員啟用 Claude Code on the web。聯繫您的 Anthropic 帳戶團隊。

188 

189### `/web-setup` 返回 "Unknown command"

190 

191`/web-setup` 在 Claude Code CLI 內執行,而不是在您的 shell 中。首先啟動 `claude`,然後在提示符處輸入 `/web-setup`。

192 

193如果您在 Claude Code 內輸入它並仍然看到錯誤,您的 CLI 版本早於 v2.1.80,或者您使用 API 金鑰或第三方提供商而不是 claude.ai 訂閱進行驗證。執行 `claude update`,然後執行 `/login` 以使用您的 claude.ai 帳戶登入。

194 

195### 使用 `--remote` 或 ultraplan 時出現 "Could not create a cloud environment" 或 "No cloud environment available"

196 

197遠端會話功能會在您沒有雲端環境時自動建立預設雲端環境。如果您看到 "Could not create a cloud environment",自動建立失敗。{/* max-version: 2.1.100 */}如果您看到 "No cloud environment available",您的 CLI 早於自動建立。在任何一種情況下,在 Claude Code CLI 中執行 `/web-setup` 以手動建立一個,或訪問 [claude.ai/code](https://claude.ai/code) 並按照上面的**建立您的環境**步驟進行。

198 

199### 設定指令碼失敗

200 

201設定指令碼以非零狀態退出,這會阻止會話啟動。常見原因:

202 

203* 套件安裝失敗,因為登錄不在您的[網路存取級別](/zh-TW/claude-code-on-the-web#access-levels)中。`Trusted` 涵蓋大多數套件管理器;`None` 阻止它們全部。

204* 指令碼引用在新鮮複製中不存在的文件或路徑。

205* 在本地工作的命令在 Ubuntu 上需要不同的調用。

206 

207要除錯,在指令碼頂部新增 `set -x` 以查看哪個命令失敗。對於非關鍵命令,附加 `|| true` 以便它們不會阻止會話啟動。

208 

209### 會話在關閉標籤後保持執行

210 

211這是設計使然。關閉標籤或導航離開不會停止會話。它在背景中繼續執行,直到 Claude 完成當前任務,然後閒置。從側邊欄,您可以[存檔會話](/zh-TW/claude-code-on-the-web#archive-sessions)以將其從列表中隱藏,或[刪除它](/zh-TW/claude-code-on-the-web#delete-sessions)以永久移除它。

212 

213## 後續步驟

214 

215現在您可以提交和檢查任務,這些頁面涵蓋接下來的內容:從您的終端啟動雲端會話、安排定期工作以及為 Claude 提供常設指令。

216 

217* [使用 Claude Code on the web](/zh-TW/claude-code-on-the-web):完整參考,包括將會話傳送到您的終端、設定指令碼、環境變數和網路配置

218* [Routines](/zh-TW/routines):按計劃、透過 API 呼叫或回應 GitHub 事件自動化工作

219* [CLAUDE.md](/zh-TW/memory):為 Claude 提供在每個會話開始時載入的持久指令和上下文

220* 安裝 Claude 行動應用程式以用於 [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) 或 [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude) 以從您的手機監控會話。從 Claude Code CLI,`/mobile` 顯示 QR 碼。

whats-new.md +49 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 最新動態

6 

7> Claude Code 功能的每週摘要,包含程式碼片段、示範和背景說明。

8 

9每週開發摘要重點介紹最有可能改變您工作方式的功能。每個條目都包含可執行的程式碼、簡短的示範和完整文件的連結。如需每個錯誤修復和次要改進,請參閱 [changelog](/zh-TW/changelog)。

10 

11<Update label="Week 17" description="April 20–24, 2026" tags={["v2.1.114–v2.1.119"]}>

12 **`/ultrareview`** 作為公開研究預覽版開放:一群除蟲代理在雲端執行,發現結果會自動回傳到您的 CLI 或桌面應用。

13 

14 本週還有:**session recap** 顯示終端機失焦時發生的情況;**custom themes** 讓您從 `/theme` 或外掛程式建立和發佈色彩調色板;**Claude Code on the web** 進行了重新設計,包含新的 sessions 側邊欄和拖放版面配置。

15 

16 [閱讀 Week 17 摘要 →](/zh-TW/whats-new/2026-w17)

17</Update>

18 

19<Update label="Week 16" description="April 13–17, 2026" tags={["v2.1.105–v2.1.113"]}>

20 **Claude Opus 4.7** 成為 Max 和 Team Premium 的新預設版本,具有新的 `xhigh` 努力等級(推薦用於大多數編碼工作)和互動式 `/effort` 滑桿來調整設定。

21 

22 本週還有:**Routines** 在 Claude Code on the web 上從排程、GitHub 事件或 API 呼叫觸發樣板化雲端代理;`/ultrareview` 在雲端執行平行多代理程式碼審查;`/usage` 顯示驅動您限制的因素;CLI 移至原生二進位檔。

23 

24 [閱讀 Week 16 摘要 →](/zh-TW/whats-new/2026-w16)

25</Update>

26 

27<Update label="Week 15" description="April 6–10, 2026" tags={["v2.1.92–v2.1.101"]}>

28 **Ultraplan** 進入早期預覽版:從您的 CLI 在雲端草擬計畫,在網頁編輯器中檢閱和評論,然後遠端執行或拉回本機。第一次執行現在會自動為您建立雲端環境。

29 

30 本週還有:**Monitor** 工具將背景事件串流到對話中,讓 Claude 可以追蹤日誌並即時反應,`/loop` 在您省略間隔時自動調整步調,`/team-onboarding` 將您的設定打包成可重播的指南,`/autofix-pr` 從您的終端機開啟 PR 自動修復。

31 

32 [閱讀 Week 15 摘要 →](/zh-TW/whats-new/2026-w15)

33</Update>

34 

35<Update label="Week 14" description="March 30 – April 3, 2026" tags={["v2.1.86–v2.1.91"]}>

36 **Computer use** 在研究預覽版中推出至 CLI:Claude 可以開啟原生應用程式、點擊 UI 並從您的終端機驗證變更。最適合用於關閉只有 GUI 才能驗證的事項。

37 

38 本週還有:`/powerup` 互動式課程、無閃爍的 alt-screen 渲染、每個工具的 MCP 結果大小覆蓋(最高 500K),以及 Bash 工具 `PATH` 上的外掛程式可執行檔。

39 

40 [閱讀 Week 14 摘要 →](/zh-TW/whats-new/2026-w14)

41</Update>

42 

43<Update label="Week 13" description="March 23–27, 2026" tags={["v2.1.83–v2.1.85"]}>

44 **Auto mode** 在研究預覽版中推出:分類器處理您的權限提示,讓安全操作無中斷執行,危險操作則被阻止。這是在核准所有操作和 `--dangerously-skip-permissions` 之間的折衷方案。

45 

46 本週還有:桌面應用中的 computer use、Web 上的 PR 自動修復、使用 `/` 進行文字記錄搜尋、適用於 Windows 的原生 PowerShell 工具,以及條件式 `if` hooks。

47 

48 [閱讀 Week 13 摘要 →](/zh-TW/whats-new/2026-w13)

49</Update>

whats-new/2026-w16.md +135 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 第 16 週 · 2026 年 4 月 13–17 日

6 

7> Claude Opus 4.7 搭配新的 xhigh 努力等級、Claude Code 網頁版上的 Routines、/ultrareview 雲端程式碼審查、顯示限制驅動因素的 /usage 細目分析,以及取代捆綁 JavaScript 的原生二進位檔。

8 

9<div className="digest-meta">

10 <span>版本 <a href="/zh-TW/docs/changelog#2-1-105">v2.1.105 → v2.1.113</a></span>

11 <span>5 項功能 · 4 月 13–17 日</span>

12</div>

13 

14<div className="digest-feature">

15 <div className="digest-feature-header">

16 <span className="digest-feature-title">Claude Opus 4.7</span>

17 <span className="digest-feature-pill">新模型</span>

18 </div>

19 

20 <p className="digest-feature-lede">Anthropic 最強大的編碼模型現在是 Max 和 Team Premium 的預設值,也可從 <code>/model</code> 在其他地方使用。它新增了一個 <code>xhigh</code> 努力等級,位於 <code>high</code> 和 <code>max</code> 之間:對大多數編碼和代理任務提供最佳結果,在您第一次切換到 4.7 時應用為預設值。<code>/effort</code> 現在在您不帶引數呼叫時會開啟互動式箭頭鍵滑塊,讓您可以在不記住等級名稱的情況下調整智能與速度。</p>

21 

22 <p className="digest-feature-try">一次切換模型和努力等級:</p>

23 

24 ```text Claude Code theme={null}

25 > /model opus

26 > /effort xhigh

27 ```

28 

29 <a className="digest-feature-link" href="/zh-TW/docs/model-config#adjust-effort-level">模型配置:努力等級</a>

30</div>

31 

32<div className="digest-feature">

33 <div className="digest-feature-header">

34 <span className="digest-feature-title">Routines</span>

35 <span className="digest-feature-pill">web</span>

36 </div>

37 

38 <p className="digest-feature-lede">範本化雲端代理,可按排程、GitHub 事件或 API 呼叫觸發。在 Claude Code 網頁版上定義一次 routine,包含提示、它可以接觸的儲存庫和所需的連接器,然後讓 PR 開啟、版本發佈或您自己的 webhook 在您的機器未執行時觸發它。觸發選擇器現在涵蓋具有選用篩選器的 GitHub 事件,並為每個 routine 提供一個令牌化的 <code>/fire</code> 端點供外部系統使用。</p>

39 

40 <Frame>

41 <img className="w-full" src="https://mintcdn.com/claude-code/FTi4SBJ9YRs7d-5X/images/whats-new/routines.png?fit=max&auto=format&n=FTi4SBJ9YRs7d-5X&q=85&s=2ba818ea9280c549511cb48b9b4d1dc5" alt="在 Claude Code 網頁版上建立 routine,具有排程、GitHub 事件和 API 觸發器" width="1440" height="810" data-path="images/whats-new/routines.png" />

42 </Frame>

43 

44 <p className="digest-feature-try">從網頁 UI 建立一個,或從您的終端機搭建:</p>

45 

46 ```text Claude Code theme={null}

47 > /schedule daily PR review at 9am

48 ```

49 

50 <a className="digest-feature-link" href="/zh-TW/docs/routines">Routines 指南</a>

51</div>

52 

53<div className="digest-feature">

54 <div className="digest-feature-header">

55 <span className="digest-feature-title">/usage 細目分析</span>

56 <span className="digest-feature-pill">CLI</span>

57 </div>

58 

59 <p className="digest-feature-lede">更清楚地了解您的 Claude Code 使用量流向何處。<code>/usage</code> 現在顯示驅動您限制的因素:平行工作階段、子代理、快取遺漏和長上下文,每個都有您過去 24 小時的百分比和最佳化提示。按 <code>d</code> 或 <code>w</code> 在日檢視和週檢視之間切換。</p>

60 

61 <Frame>

62 <img className="w-full" src="https://mintcdn.com/claude-code/FTi4SBJ9YRs7d-5X/images/whats-new/usage.png?fit=max&auto=format&n=FTi4SBJ9YRs7d-5X&q=85&s=792a4b43cbef4e2931974831f076bca6" alt="/usage 命令顯示對限制使用量有貢獻的細目分析" width="1204" height="1182" data-path="images/whats-new/usage.png" />

63 </Frame>

64 

65 <p className="digest-feature-try">隨時執行:</p>

66 

67 ```text Claude Code theme={null}

68 > /usage

69 ```

70 

71 <a className="digest-feature-link" href="/zh-TW/docs/commands">命令參考</a>

72</div>

73 

74<div className="digest-feature">

75 <div className="digest-feature-header">

76 <span className="digest-feature-title">/ultrareview</span>

77 <span className="digest-feature-pill">v2.1.111</span>

78 </div>

79 

80 <p className="digest-feature-lede">雲端中的全面程式碼審查。Ultrareview 在 Claude Code 網頁版上將您的分支分散到平行審查者,對每個發現執行對抗性批評傳遞,並傳回已驗證的發現報告,同時您的終端機保持空閒。不帶引數呼叫以審查您目前的分支,或傳遞 PR 編號以擷取並審查該 PR。啟動對話框現在顯示 diffstat,讓您在確認前知道要上傳的內容。</p>

81 

82 <p className="digest-feature-try">審查您所在的分支:</p>

83 

84 ```text Claude Code theme={null}

85 > /ultrareview

86 ```

87 

88 <p className="digest-feature-try">或將其指向 PR:</p>

89 

90 ```text Claude Code theme={null}

91 > /ultrareview 1234

92 ```

93 

94 <a className="digest-feature-link" href="/zh-TW/docs/ultrareview">Ultrareview 指南</a>

95</div>

96 

97<div className="digest-feature">

98 <div className="digest-feature-header">

99 <span className="digest-feature-title">原生二進位檔</span>

100 <span className="digest-feature-pill">v2.1.113</span>

101 </div>

102 

103 <p className="digest-feature-lede"><code>claude</code> CLI 現在生成原生的每平台二進位檔,而不是捆綁的 JavaScript,因此已安裝的 <code>claude</code> 命令不再呼叫 Node。npm 套件透過選用相依性(例如 <code>@anthropic-ai/claude-code-darwin-arm64</code>)拉入正確的二進位檔,因此您的安裝命令不會改變。獨立安裝程式已經提供此二進位檔;npm 現在與其相符。</p>

104 

105 <p className="digest-feature-try">升級並檢查您正在執行的內容:</p>

106 

107 ```bash theme={null}

108 claude update

109 claude --version

110 ```

111 

112 <a className="digest-feature-link" href="/zh-TW/docs/setup">設定指南</a>

113</div>

114 

115<div className="digest-wins">

116 <p className="digest-wins-title">其他成果</p>

117 

118 <div className="digest-wins-grid">

119 <div><a href="/zh-TW/docs/permission-modes#eliminate-prompts-with-auto-mode">自動模式</a>現在可供 Max 訂閱者在 Opus 4.7 上使用,<code>--enable-auto-mode</code> 旗標不再需要</div>

120 <div><a href="/zh-TW/docs/interactive-mode#session-recap">工作階段摘要</a>顯示您離開時發生的一行摘要;按需執行 <code>/recap</code> 或從 <code>/config</code> 關閉它</div>

121 <div>新的 <code>/tui</code> 命令和 <code>tui</code> 設定在對話中間切換經典和無閃爍渲染;焦點檢視從 <code>Ctrl+O</code> 移至其自己的 <code>/focus</code> 命令</div>

122 <div>推播通知工具:連接 <a href="/zh-TW/docs/remote-control">Remote Control</a> 並啟用「Claude 決定時推播」,Claude 可在需要您時 ping 您的手機</div>

123 <div>外掛程式可透過在工作階段開始或技能呼叫時自動啟用的頂層 <code>monitors</code> 資訊清單鍵來提供背景監視程式</div>

124 <div><code>/theme</code> 中的「自動(符合終端機)」選項遵循您終端機的深色/淺色模式</div>

125 <div><code>/fewer-permission-prompts</code> 掃描您的文字記錄以尋找常見的唯讀 Bash 和 MCP 呼叫,並為 <code>.claude/settings.json</code> 提議允許清單</div>

126 <div>Claude 現在可以透過 Skill 工具發現並執行內建命令,例如 <code>/init</code>、<code>/review</code> 和 <code>/security-review</code></div>

127 <div><code>PreCompact</code> hooks 可以透過以代碼 2 結束或傳回 <code>{"{"}"decision":"block"{"}"}</code> 來阻止壓縮</div>

128 <div><code>ENABLE\_PROMPT\_CACHING\_1H</code> 選擇 API 金鑰、Bedrock、Vertex 和 Foundry 使用者進入 1 小時 prompt cache TTL</div>

129 <div><code>sandbox.network.deniedDomains</code> 設定從更廣泛的 <code>allowedDomains</code> 萬用字元中切割特定網域</div>

130 <div><code>/undo</code> 現在是 <code>/rewind</code> 的別名,<code>/proactive</code> 是 <code>/loop</code> 的別名</div>

131 <div>強化的 Bash 權限:拒絕規則現在透過 <code>env</code>/<code>sudo</code>/<code>watch</code> 包裝器進行比對,<code>Bash(find:\*)</code> 允許規則不再自動核准 <code>-exec</code> 或 <code>-delete</code></div>

132 </div>

133</div>

134 

135[v2.1.105–v2.1.113 的完整變更日誌 →](/zh-TW/changelog#2-1-105)

whats-new/2026-w17.md +113 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 第 17 週 · 2026 年 4 月 20–24 日

6 

7> /ultrareview 作為研究預覽版開放,當您返回終端時自動生成會話摘要,您可以在插件中構建和發佈自訂色彩主題,以及重新設計的網頁版 Claude Code。

8 

9<div className="digest-meta">

10 <span>版本 <a href="/docs/zh-TW/changelog#2-1-114">v2.1.114 → v2.1.119</a></span>

11 <span>4 項功能 · 4 月 20–24 日</span>

12</div>

13 

14<div className="digest-feature">

15 <div className="digest-feature-header">

16 <span className="digest-feature-title">/ultrareview</span>

17 <span className="digest-feature-pill">研究預覽版</span>

18 </div>

19 

20 <p className="digest-feature-lede">現已推出公開研究預覽版。Ultrareview 在雲端針對您的分支或 PR 運行一群漏洞獵捕代理,發現結果會自動回傳到 CLI 或桌面應用。在合併關鍵變更(例如身份驗證或資料遷移)之前執行此操作。</p>

21 

22 <Frame>

23 <video autoPlay muted loop playsInline className="w-full" src="https://mintcdn.com/claude-code/FTi4SBJ9YRs7d-5X/images/whats-new/ultrareview.mp4?fit=max&auto=format&n=FTi4SBJ9YRs7d-5X&q=85&s=0fb1271365d38f414ad155aeb8edb08e" data-path="images/whats-new/ultrareview.mp4" />

24 </Frame>

25 

26 <p className="digest-feature-try">檢查您目前所在的分支:</p>

27 

28 ```text Claude Code theme={null}

29 > /ultrareview

30 ```

31 

32 <p className="digest-feature-try">或指向 PR:</p>

33 

34 ```text Claude Code theme={null}

35 > /ultrareview 1234

36 ```

37 

38 <a className="digest-feature-link" href="/docs/zh-TW/ultrareview">Ultrareview 指南</a>

39</div>

40 

41<div className="digest-feature">

42 <div className="digest-feature-header">

43 <span className="digest-feature-title">會話摘要</span>

44 <span className="digest-feature-pill">CLI</span>

45 </div>

46 

47 <p className="digest-feature-lede">將焦點轉移到其他地方,然後返回會話時,會看到一行摘要說明您離開期間發生的情況。在同時運行多個 Claude 會話時,有助於保持工作流程順暢。</p>

48 

49 <Frame>

50 <video autoPlay muted loop playsInline className="w-full" src="https://mintcdn.com/claude-code/FTi4SBJ9YRs7d-5X/images/whats-new/session-recap.mp4?fit=max&auto=format&n=FTi4SBJ9YRs7d-5X&q=85&s=0a8db1470bd0161a47efeb2f322af76f" data-path="images/whats-new/session-recap.mp4" />

51 </Frame>

52 

53 <p className="digest-feature-try">按需生成摘要,或從 <code>/config</code> 關閉自動摘要:</p>

54 

55 ```text Claude Code theme={null}

56 > /recap

57 ```

58 

59 <a className="digest-feature-link" href="/docs/zh-TW/interactive-mode#session-recap">互動模式:會話摘要</a>

60</div>

61 

62<div className="digest-feature">

63 <div className="digest-feature-header">

64 <span className="digest-feature-title">自訂主題</span>

65 <span className="digest-feature-pill">v2.1.118</span>

66 </div>

67 

68 <p className="digest-feature-lede">從 <code>/theme</code> 構建和切換命名色彩主題,或在 <code>\~/.claude/themes/</code> 中手動編輯 JSON 檔案。每個主題選擇一個基礎預設,並僅覆蓋您關心的令牌。插件也可以提供主題。</p>

69 

70 <p className="digest-feature-try">開啟主題選擇器並建立新主題:</p>

71 

72 ```text Claude Code theme={null}

73 > /theme

74 ```

75 

76 <a className="digest-feature-link" href="/docs/zh-TW/terminal-config#create-a-custom-theme">終端配置:建立自訂主題</a>

77</div>

78 

79<div className="digest-feature">

80 <div className="digest-feature-header">

81 <span className="digest-feature-title">網頁版 Claude Code</span>

82 <span className="digest-feature-pill">web</span>

83 </div>

84 

85 <p className="digest-feature-lede"><a href="https://claude.ai/code">claude.ai/code</a> 的新外觀與重新設計的桌面應用相符:會話側邊欄、拖放佈局和更新的例行工作檢視。關鍵部分已重新構建,以提供更快的回應速度和更可靠的體驗。</p>

86 

87 <Frame>

88 <img className="w-full" src="https://mintcdn.com/claude-code/FTi4SBJ9YRs7d-5X/images/whats-new/web-redesign.jpeg?fit=max&auto=format&n=FTi4SBJ9YRs7d-5X&q=85&s=a2aca1b49e295b7337f5779038db8e2c" alt="網頁版 Claude Code 重新設計概覽:新 UI、速度和可靠性、跨網頁、行動和 CLI 工作" width="1602" height="1610" data-path="images/whats-new/web-redesign.jpeg" />

89 </Frame>

90 

91 <a className="digest-feature-link" href="/docs/zh-TW/claude-code-on-the-web">網頁版 Claude Code</a>

92</div>

93 

94<div className="digest-wins">

95 <p className="digest-wins-title">其他亮點</p>

96 

97 <div className="digest-wins-grid">

98 <div><a href="/docs/zh-TW/interactive-mode#vim-editor-mode">Vim 視覺模式</a>:在提示輸入中按 <code>v</code> 進行字元選擇或按 <code>V</code> 進行行選擇,並提供運算子和視覺回饋</div>

99 <div>Hooks 現在可以透過 <a href="/docs/zh-TW/hooks#mcp-tool-hook-fields"><code>type: "mcp\_tool"</code></a> 直接呼叫 MCP 工具,因此 hook 可以連接到已連接的伺服器,而無需生成進程</div>

100 <div><code>/cost</code> 和 <code>/stats</code> 已合併到 <a href="/docs/zh-TW/commands"><code>/usage</code></a>;舊名稱仍可作為打字快捷方式使用,以開啟相關標籤</div>

101 <div><code>/config</code> 變更(主題、編輯器模式、詳細資訊等)現在會保存到 <code>\~/.claude/settings.json</code>,並遵循與其他 <a href="/docs/zh-TW/settings">設定</a> 相同的專案/本機/原則優先順序</div>

102 <div><a href="/docs/zh-TW/sub-agents#fork-the-current-conversation">分叉的子代理</a>可以在外部構建上啟用,使用 <code>CLAUDE\_CODE\_FORK\_SUBAGENT=1</code>:分叉會繼承您的完整對話內容,而不是從頭開始</div>

103 <div>Pro 和 Max 訂閱者在 Opus 4.6 和 Sonnet 4.6 上的預設 <a href="/docs/zh-TW/model-config#adjust-effort-level">努力等級</a> 現在是 <code>high</code>(之前是 <code>medium</code>)</div>

104 <div>原生 macOS 和 Linux 構建用嵌入式 <code>bfs</code> 和 <code>ugrep</code>(可透過 Bash 使用)取代 <code>Glob</code> 和 <code>Grep</code> 工具,以加快搜尋速度,無需單獨的工具往返</div>

105 <div><code>--from-pr</code> 現在除了接受 github.com 外,還接受 GitLab 合併請求、Bitbucket 拉取請求和 GitHub Enterprise PR URL</div>

106 <div>自動模式:在 <a href="/docs/zh-TW/auto-mode-config"><code>autoMode.allow</code>、<code>soft\_deny</code> 或 <code>environment</code></a> 中包含 <code>"\$defaults"</code>,以在內建清單旁邊新增自訂規則,而不是取代它</div>

107 <div>新的 <a href="/docs/zh-TW/plugin-dependencies#tag-plugin-releases-for-version-resolution"><code>claude plugin tag</code></a> 命令為插件建立版本驗證的發佈 git 標籤</div>

108 <div>Opus 4.7 會話現在針對模型的原生 1M 內容視窗進行計算,修復了膨脹的 <code>/context</code> 百分比和過早的自動壓縮</div>

109 <div><code>/resume</code> 在大型會話上的速度提高了 67%,現在在重新讀取之前提供摘要陳舊的大型會話的選項</div>

110 </div>

111</div>

112 

113[v2.1.114–v2.1.119 的完整變更日誌 →](/zh-TW/changelog#2-1-114)

zero-data-retention.md +66 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 零數據保留

6 

7> 了解 Claude for Enterprise 上 Claude Code 的零數據保留 (ZDR),包括範圍、禁用功能以及如何請求啟用。

8 

9零數據保留 (ZDR) 在通過 Claude for Enterprise 使用 Claude Code 時可用。啟用 ZDR 後,Claude Code 會話期間生成的提示和模型回應會實時處理,並在返回回應後不會由 Anthropic 存儲,除非需要遵守法律或防止濫用。

10 

11Claude for Enterprise 上的 ZDR 使企業客戶能夠使用 Claude Code 並實現零數據保留,同時獲得管理功能:

12 

13* 每個用戶的成本控制

14* [分析](/zh-TW/analytics)儀表板

15* [服務器管理的設置](/zh-TW/server-managed-settings)

16* 審計日誌

17 

18Claude for Enterprise 上 Claude Code 的 ZDR 僅適用於 Anthropic 的直接平台。對於在 Amazon Bedrock、Google Vertex AI 或 Microsoft Foundry 上的 Claude 部署,請參考這些平台的數據保留政策。

19 

20## ZDR 範圍

21 

22ZDR 涵蓋 Claude for Enterprise 上的 Claude Code 推理。

23 

24<Warning>

25 ZDR 在每個組織的基礎上啟用。每個新組織都需要由您的 Anthropic 帳戶團隊單獨啟用 ZDR。ZDR 不會自動應用於在同一帳戶下創建的新組織。請聯繫您的帳戶團隊為任何新組織啟用 ZDR。

26</Warning>

27 

28### ZDR 涵蓋的內容

29 

30ZDR 涵蓋通過 Claude for Enterprise 上的 Claude Code 進行的模型推理調用。當您在終端中使用 Claude Code 時,您發送的提示和 Claude 生成的回應不會由 Anthropic 保留。無論使用哪個 Claude 模型,這都適用。

31 

32### ZDR 不涵蓋的內容

33 

34即使對於啟用了 ZDR 的組織,ZDR 也不適用於以下內容。這些功能遵循[標準數據保留政策](/zh-TW/data-usage#data-retention):

35 

36| 功能 | 詳情 |

37| -------------- | ---------------------------------------------------------------------------------------- |

38| claude.ai 上的聊天 | 通過 Claude for Enterprise 網絡界面的聊天對話不受 ZDR 保護。 |

39| Cowork | Cowork 會話不受 ZDR 保護。 |

40| Claude Code 分析 | 不存儲提示或模型回應,但收集生產力元數據,例如帳戶電子郵件和使用統計信息。對於 ZDR 組織,貢獻指標不可用;[分析儀表板](/zh-TW/analytics)僅顯示使用指標。 |

41| 用戶和座位管理 | 管理數據(例如帳戶電子郵件和座位分配)根據標準政策保留。 |

42| 第三方集成 | 由第三方工具、MCP servers 或其他外部集成處理的數據不受 ZDR 保護。請獨立審查這些服務的數據處理實踐。 |

43 

44## ZDR 下禁用的功能

45 

46當為 Claude for Enterprise 上的 Claude Code 組織啟用 ZDR 時,某些需要存儲提示或完成的功能會在後端級別自動禁用:

47 

48| 功能 | 原因 |

49| --------------------------------------------------- | ------------------------ |

50| [Web 上的 Claude Code](/zh-TW/claude-code-on-the-web) | 需要服務器端存儲對話歷史記錄。 |

51| Desktop 應用程序的[遠程會話](/zh-TW/desktop#remote-sessions) | 需要包含提示和完成的持久會話數據。 |

52| 反饋提交 (`/feedback`) | 提交反饋會將對話數據發送給 Anthropic。 |

53 

54這些功能在後端被阻止,無論客戶端顯示如何。如果您在啟動期間在 Claude Code 終端中看到禁用的功能,嘗試使用它會返回一個錯誤,指示組織的政策不允許該操作。

55 

56如果未來的功能需要存儲提示或完成,它們也可能被禁用。

57 

58## 政策違規的數據保留

59 

60即使啟用了 ZDR,Anthropic 也可能在法律要求或解決使用政策違規時保留數據。如果會話因政策違規而被標記,Anthropic 可能會保留相關的輸入和輸出長達 2 年,與 Anthropic 的標準 ZDR 政策一致。

61 

62## 請求 ZDR

63 

64要為 Claude for Enterprise 上的 Claude Code 請求 ZDR,請[聯繫銷售](https://www.anthropic.com/contact-sales?utm_source=claude_code\&utm_medium=docs\&utm_content=zero_data_retention_request)或您的 Anthropic 帳戶團隊。您的帳戶團隊將在內部提交請求,Anthropic 將在確認符合條件後在您的組織上審查並啟用 ZDR。所有啟用操作都會被審計記錄。

65 

66如果您目前通過按使用量付費的 API 密鑰使用 Claude Code 的 ZDR,您可以過渡到 Claude for Enterprise 以獲得管理功能的訪問權限,同時為 Claude Code 保持 ZDR。請聯繫您的帳戶團隊以協調遷移。