SpyBara
Go Premium

Documentation 2026-05-07 22:59 UTC to 2026-05-08 22:00 UTC

29 files changed +2,204 −1,650. View all changes and history on the product overview
2026
Sun 31 06:39 Sat 30 06:23 Fri 29 06:38 Thu 28 06:37 Wed 27 06:42 Tue 26 06:33 Sun 24 06:25 Sat 23 06:18 Fri 22 06:33 Thu 21 06:36 Wed 20 06:35 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 Sat 2 18:14 Fri 1 18:19
Details

14 14 

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

16 16 

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

18 18 

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

20 20 


65 ```65 ```

66</CodeGroup>66</CodeGroup>

67 67 

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

69 69 

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

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


119 119 

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

121 121 

122Skills 透過 `settingSources` 從檔案系統中發現。使用預設選項使用者和專案 skills 會自動載入當您未指定 `allowedTools` 時,`Skill` 工具預設啟用如果您使用 `allowedTools` 允許清單請明確包含 `"Skill"`。122Skills 透過 `settingSources` 從檔案系統中發現。當 `query()` 上的 `skills` 選項被省略時已發現的使用者和專案 skills 會被啟用,且 Skill 工具可用,符合 CLI 行為若要控制啟用哪些 skills,請將 `skills` 傳遞為 `"all"`、skill 名稱清單或 `[]` 以停用全部SDK 在設定 `skills` 時會自動啟用 Skill 工具因此您不需要將其新增至 `allowedTools`。

123 123 

124<CodeGroup>124<CodeGroup>

125 ```python Python theme={null}125 ```python Python theme={null}


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

132 options=ClaudeAgentOptions(132 options=ClaudeAgentOptions(

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

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

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

135 ),136 ),

136 ):137 ):

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


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

148 options: {149 options: {

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

150 allowedTools: ["Skill", "Read", "Grep", "Glob"]151 skills: "all",

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

151 }153 }

152 })) {154 })) {

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


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

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

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

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

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

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

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

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

agent-sdk/mcp.md +772 −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 連接外部工具

6 

7> 配置 MCP 伺服器以擴展您的代理程式的外部工具。涵蓋傳輸類型、大型工具集的工具搜尋、身份驗證和錯誤處理。

8 

9[Model Context Protocol (MCP)](https://modelcontextprotocol.io/docs/getting-started/intro) 是一個開放標準,用於將 AI 代理程式連接到外部工具和資料來源。使用 MCP,您的代理程式可以查詢資料庫、與 Slack 和 GitHub 等 API 整合,以及連接到其他服務,而無需編寫自訂工具實現。

10 

11MCP 伺服器可以作為本地進程運行、通過 HTTP 連接或直接在您的 SDK 應用程式中執行。

12 

13<Note>

14 本頁涵蓋 Agent SDK 的 MCP 配置。若要將 MCP 伺服器添加到 Claude Code CLI 以便在每個項目中加載,請參閱 [MCP 安裝範圍](/zh-TW/mcp#mcp-installation-scopes)。

15</Note>

16 

17## 快速開始

18 

19此示例使用 [HTTP 傳輸](#httpsse-servers) 連接到 [Claude Code 文檔](https://code.claude.com/docs) MCP 伺服器,並使用 [`allowedTools`](#allow-mcp-tools) 與通配符來允許來自伺服器的所有工具。

20 

21<CodeGroup>

22 ```typescript TypeScript theme={null}

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

24 

25 for await (const message of query({

26 prompt: "Use the docs MCP server to explain what hooks are in Claude Code",

27 options: {

28 mcpServers: {

29 "claude-code-docs": {

30 type: "http",

31 url: "https://code.claude.com/docs/mcp"

32 }

33 },

34 allowedTools: ["mcp__claude-code-docs__*"]

35 }

36 })) {

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

38 console.log(message.result);

39 }

40 }

41 ```

42 

43 ```python Python theme={null}

44 import asyncio

45 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

46 

47 

48 async def main():

49 options = ClaudeAgentOptions(

50 mcp_servers={

51 "claude-code-docs": {

52 "type": "http",

53 "url": "https://code.claude.com/docs/mcp",

54 }

55 },

56 allowed_tools=["mcp__claude-code-docs__*"],

57 )

58 

59 async for message in query(

60 prompt="Use the docs MCP server to explain what hooks are in Claude Code",

61 options=options,

62 ):

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

64 print(message.result)

65 

66 

67 asyncio.run(main())

68 ```

69</CodeGroup>

70 

71代理程式連接到文檔伺服器,搜尋有關 hooks 的信息,並返回結果。

72 

73## 添加 MCP 伺服器

74 

75您可以在調用 `query()` 時在代碼中配置 MCP 伺服器,或在通過 [`settingSources`](#from-a-config-file) 加載的 `.mcp.json` 文件中配置。

76 

77### 在代碼中

78 

79在 `mcpServers` 選項中直接傳遞 MCP 伺服器:

80 

81<CodeGroup>

82 ```typescript TypeScript theme={null}

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

84 

85 for await (const message of query({

86 prompt: "List files in my project",

87 options: {

88 mcpServers: {

89 filesystem: {

90 command: "npx",

91 args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]

92 }

93 },

94 allowedTools: ["mcp__filesystem__*"]

95 }

96 })) {

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

98 console.log(message.result);

99 }

100 }

101 ```

102 

103 ```python Python theme={null}

104 import asyncio

105 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

106 

107 

108 async def main():

109 options = ClaudeAgentOptions(

110 mcp_servers={

111 "filesystem": {

112 "command": "npx",

113 "args": [

114 "-y",

115 "@modelcontextprotocol/server-filesystem",

116 "/Users/me/projects",

117 ],

118 }

119 },

120 allowed_tools=["mcp__filesystem__*"],

121 )

122 

123 async for message in query(prompt="List files in my project", options=options):

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

125 print(message.result)

126 

127 

128 asyncio.run(main())

129 ```

130</CodeGroup>

131 

132### 從配置文件

133 

134在您的項目根目錄創建一個 `.mcp.json` 文件。當啟用 `project` 設置源時,該文件會被選取,這對於默認 `query()` 選項是默認的。如果您明確設置 `settingSources`,請包含 `"project"` 以便加載此文件:

135 

136```json theme={null}

137{

138 "mcpServers": {

139 "filesystem": {

140 "command": "npx",

141 "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]

142 }

143 }

144}

145```

146 

147## 允許 MCP 工具

148 

149MCP 工具需要明確的權限才能讓 Claude 使用它們。沒有權限,Claude 會看到工具可用,但無法調用它們。

150 

151### 工具命名約定

152 

153MCP 工具遵循命名模式 `mcp__<server-name>__<tool-name>`。例如,名為 `"github"` 的 GitHub 伺服器,其 `list_issues` 工具變為 `mcp__github__list_issues`。

154 

155### 使用 allowedTools 授予訪問權限

156 

157使用 `allowedTools` 指定 Claude 可以使用哪些 MCP 工具:

158 

159```typescript hidelines={1,-1} theme={null}

160const _ = {

161 options: {

162 mcpServers: {

163 // your servers

164 },

165 allowedTools: [

166 "mcp__github__*", // All tools from the github server

167 "mcp__db__query", // Only the query tool from db server

168 "mcp__slack__send_message" // Only send_message from slack server

169 ]

170 }

171};

172```

173 

174通配符 (`*`) 讓您允許來自伺服器的所有工具,而無需逐個列出。

175 

176<Note>

177 **對於 MCP 訪問,優先使用 `allowedTools` 而不是權限模式。** `permissionMode: "acceptEdits"` 不會自動批准 MCP 工具(僅限文件編輯和文件系統 Bash 命令)。`permissionMode: "bypassPermissions"` 會自動批准 MCP 工具,但也會禁用所有其他安全提示,這比必要的範圍更廣。`allowedTools` 中的通配符只授予您想要的 MCP 伺服器,沒有其他。有關完整比較,請參閱[權限模式](/zh-TW/agent-sdk/permissions#permission-modes)。

178</Note>

179 

180### 發現可用工具

181 

182要查看 MCP 伺服器提供的工具,請檢查伺服器的文檔或連接到伺服器並檢查 `system` init 消息:

183 

184```typescript theme={null}

185for await (const message of query({ prompt: "...", options })) {

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

187 console.log("Available MCP tools:", message.mcp_servers);

188 }

189}

190```

191 

192## 傳輸類型

193 

194MCP 伺服器使用不同的傳輸協議與您的代理程式通信。檢查伺服器的文檔以查看它支持哪種傳輸:

195 

196* 如果文檔給您一個**要運行的命令**(如 `npx @modelcontextprotocol/server-github`),請使用 stdio

197* 如果文檔給您一個 **URL**,請使用 HTTP 或 SSE

198* 如果您在代碼中構建自己的工具,請使用 SDK MCP 伺服器

199 

200### stdio 伺服器

201 

202通過 stdin/stdout 通信的本地進程。對於在同一台機器上運行的 MCP 伺服器,請使用此方法:

203 

204<Tabs>

205 <Tab title="In code">

206 <CodeGroup>

207 ```typescript TypeScript hidelines={1,-1} theme={null}

208 const _ = {

209 options: {

210 mcpServers: {

211 github: {

212 command: "npx",

213 args: ["-y", "@modelcontextprotocol/server-github"],

214 env: {

215 GITHUB_TOKEN: process.env.GITHUB_TOKEN

216 }

217 }

218 },

219 allowedTools: ["mcp__github__list_issues", "mcp__github__search_issues"]

220 }

221 };

222 ```

223 

224 ```python Python theme={null}

225 options = ClaudeAgentOptions(

226 mcp_servers={

227 "github": {

228 "command": "npx",

229 "args": ["-y", "@modelcontextprotocol/server-github"],

230 "env": {"GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]},

231 }

232 },

233 allowed_tools=["mcp__github__list_issues", "mcp__github__search_issues"],

234 )

235 ```

236 </CodeGroup>

237 </Tab>

238 

239 <Tab title=".mcp.json">

240 ```json theme={null}

241 {

242 "mcpServers": {

243 "github": {

244 "command": "npx",

245 "args": ["-y", "@modelcontextprotocol/server-github"],

246 "env": {

247 "GITHUB_TOKEN": "${GITHUB_TOKEN}"

248 }

249 }

250 }

251 }

252 ```

253 </Tab>

254</Tabs>

255 

256### HTTP/SSE 伺服器

257 

258對於雲託管的 MCP 伺服器和遠程 API,請使用 HTTP 或 SSE:

259 

260<Tabs>

261 <Tab title="In code">

262 <CodeGroup>

263 ```typescript TypeScript hidelines={1,-1} theme={null}

264 const _ = {

265 options: {

266 mcpServers: {

267 "remote-api": {

268 type: "sse",

269 url: "https://api.example.com/mcp/sse",

270 headers: {

271 Authorization: `Bearer ${process.env.API_TOKEN}`

272 }

273 }

274 },

275 allowedTools: ["mcp__remote-api__*"]

276 }

277 };

278 ```

279 

280 ```python Python theme={null}

281 options = ClaudeAgentOptions(

282 mcp_servers={

283 "remote-api": {

284 "type": "sse",

285 "url": "https://api.example.com/mcp/sse",

286 "headers": {"Authorization": f"Bearer {os.environ['API_TOKEN']}"},

287 }

288 },

289 allowed_tools=["mcp__remote-api__*"],

290 )

291 ```

292 </CodeGroup>

293 </Tab>

294 

295 <Tab title=".mcp.json">

296 ```json theme={null}

297 {

298 "mcpServers": {

299 "remote-api": {

300 "type": "sse",

301 "url": "https://api.example.com/mcp/sse",

302 "headers": {

303 "Authorization": "Bearer ${API_TOKEN}"

304 }

305 }

306 }

307 }

308 ```

309 </Tab>

310</Tabs>

311 

312對於 HTTP(非流式),請改用 `"type": "http"`。

313 

314### SDK MCP 伺服器

315 

316直接在應用程式代碼中定義自訂工具,而不是運行單獨的伺服器進程。有關實現詳情,請參閱[自訂工具指南](/zh-TW/agent-sdk/custom-tools)。

317 

318## MCP 工具搜尋

319 

320當您配置了許多 MCP 工具時,工具定義可能會消耗上下文窗口的很大一部分。工具搜尋通過從上下文中隱藏工具定義並僅加載 Claude 每次轉換所需的工具來解決此問題。

321 

322工具搜尋默認啟用。有關配置選項和詳情,請參閱[工具搜尋](/zh-TW/agent-sdk/tool-search)。

323 

324有關更多詳情,包括最佳實踐和將工具搜尋與自訂 SDK 工具一起使用,請參閱[工具搜尋指南](/zh-TW/agent-sdk/tool-search)。

325 

326## 身份驗證

327 

328大多數 MCP 伺服器需要身份驗證才能訪問外部服務。通過伺服器配置中的環境變數傳遞憑據。

329 

330### 通過環境變數傳遞憑據

331 

332使用 `env` 字段將 API 密鑰、令牌和其他憑據傳遞給 MCP 伺服器:

333 

334<Tabs>

335 <Tab title="In code">

336 <CodeGroup>

337 ```typescript TypeScript hidelines={1,-1} theme={null}

338 const _ = {

339 options: {

340 mcpServers: {

341 github: {

342 command: "npx",

343 args: ["-y", "@modelcontextprotocol/server-github"],

344 env: {

345 GITHUB_TOKEN: process.env.GITHUB_TOKEN

346 }

347 }

348 },

349 allowedTools: ["mcp__github__list_issues"]

350 }

351 };

352 ```

353 

354 ```python Python theme={null}

355 options = ClaudeAgentOptions(

356 mcp_servers={

357 "github": {

358 "command": "npx",

359 "args": ["-y", "@modelcontextprotocol/server-github"],

360 "env": {"GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]},

361 }

362 },

363 allowed_tools=["mcp__github__list_issues"],

364 )

365 ```

366 </CodeGroup>

367 </Tab>

368 

369 <Tab title=".mcp.json">

370 ```json theme={null}

371 {

372 "mcpServers": {

373 "github": {

374 "command": "npx",

375 "args": ["-y", "@modelcontextprotocol/server-github"],

376 "env": {

377 "GITHUB_TOKEN": "${GITHUB_TOKEN}"

378 }

379 }

380 }

381 }

382 ```

383 

384 `${GITHUB_TOKEN}` 語法在運行時展開環境變數。

385 </Tab>

386</Tabs>

387 

388有關帶有調試日誌的完整工作示例,請參閱[從存儲庫列出問題](#list-issues-from-a-repository)。

389 

390### 遠程伺服器的 HTTP 標頭

391 

392對於 HTTP 和 SSE 伺服器,直接在伺服器配置中傳遞身份驗證標頭:

393 

394<Tabs>

395 <Tab title="In code">

396 <CodeGroup>

397 ```typescript TypeScript hidelines={1,-1} theme={null}

398 const _ = {

399 options: {

400 mcpServers: {

401 "secure-api": {

402 type: "http",

403 url: "https://api.example.com/mcp",

404 headers: {

405 Authorization: `Bearer ${process.env.API_TOKEN}`

406 }

407 }

408 },

409 allowedTools: ["mcp__secure-api__*"]

410 }

411 };

412 ```

413 

414 ```python Python theme={null}

415 options = ClaudeAgentOptions(

416 mcp_servers={

417 "secure-api": {

418 "type": "http",

419 "url": "https://api.example.com/mcp",

420 "headers": {"Authorization": f"Bearer {os.environ['API_TOKEN']}"},

421 }

422 },

423 allowed_tools=["mcp__secure-api__*"],

424 )

425 ```

426 </CodeGroup>

427 </Tab>

428 

429 <Tab title=".mcp.json">

430 ```json theme={null}

431 {

432 "mcpServers": {

433 "secure-api": {

434 "type": "http",

435 "url": "https://api.example.com/mcp",

436 "headers": {

437 "Authorization": "Bearer ${API_TOKEN}"

438 }

439 }

440 }

441 }

442 ```

443 

444 `${API_TOKEN}` 語法在運行時展開環境變數。

445 </Tab>

446</Tabs>

447 

448### OAuth2 身份驗證

449 

450[MCP 規範支持 OAuth 2.1](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization) 用於授權。SDK 不會自動處理 OAuth 流程,但您可以在應用程式中完成 OAuth 流程後通過標頭傳遞訪問令牌:

451 

452<CodeGroup>

453 ```typescript TypeScript theme={null}

454 // After completing OAuth flow in your app

455 const accessToken = await getAccessTokenFromOAuthFlow();

456 

457 const options = {

458 mcpServers: {

459 "oauth-api": {

460 type: "http",

461 url: "https://api.example.com/mcp",

462 headers: {

463 Authorization: `Bearer ${accessToken}`

464 }

465 }

466 },

467 allowedTools: ["mcp__oauth-api__*"]

468 };

469 ```

470 

471 ```python Python theme={null}

472 # After completing OAuth flow in your app

473 access_token = await get_access_token_from_oauth_flow()

474 

475 options = ClaudeAgentOptions(

476 mcp_servers={

477 "oauth-api": {

478 "type": "http",

479 "url": "https://api.example.com/mcp",

480 "headers": {"Authorization": f"Bearer {access_token}"},

481 }

482 },

483 allowed_tools=["mcp__oauth-api__*"],

484 )

485 ```

486</CodeGroup>

487 

488## 示例

489 

490### 從存儲庫列出問題

491 

492此示例連接到 [GitHub MCP 伺服器](https://github.com/modelcontextprotocol/servers/tree/main/src/github) 以列出最近的問題。該示例包括調試日誌以驗證 MCP 連接和工具調用。

493 

494運行前,創建一個具有 `repo` 範圍的 [GitHub 個人訪問令牌](https://github.com/settings/tokens),並將其設置為環境變數:

495 

496```bash theme={null}

497export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx

498```

499 

500<CodeGroup>

501 ```typescript TypeScript theme={null}

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

503 

504 for await (const message of query({

505 prompt: "List the 3 most recent issues in anthropics/claude-code",

506 options: {

507 mcpServers: {

508 github: {

509 command: "npx",

510 args: ["-y", "@modelcontextprotocol/server-github"],

511 env: {

512 GITHUB_TOKEN: process.env.GITHUB_TOKEN

513 }

514 }

515 },

516 allowedTools: ["mcp__github__list_issues"]

517 }

518 })) {

519 // Verify MCP server connected successfully

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

521 console.log("MCP servers:", message.mcp_servers);

522 }

523 

524 // Log when Claude calls an MCP tool

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

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

527 if (block.type === "tool_use" && block.name.startsWith("mcp__")) {

528 console.log("MCP tool called:", block.name);

529 }

530 }

531 }

532 

533 // Print the final result

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

535 console.log(message.result);

536 }

537 }

538 ```

539 

540 ```python Python theme={null}

541 import asyncio

542 import os

543 from claude_agent_sdk import (

544 query,

545 ClaudeAgentOptions,

546 ResultMessage,

547 SystemMessage,

548 AssistantMessage,

549 )

550 

551 

552 async def main():

553 options = ClaudeAgentOptions(

554 mcp_servers={

555 "github": {

556 "command": "npx",

557 "args": ["-y", "@modelcontextprotocol/server-github"],

558 "env": {"GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]},

559 }

560 },

561 allowed_tools=["mcp__github__list_issues"],

562 )

563 

564 async for message in query(

565 prompt="List the 3 most recent issues in anthropics/claude-code",

566 options=options,

567 ):

568 # Verify MCP server connected successfully

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

570 print("MCP servers:", message.data.get("mcp_servers"))

571 

572 # Log when Claude calls an MCP tool

573 if isinstance(message, AssistantMessage):

574 for block in message.content:

575 if hasattr(block, "name") and block.name.startswith("mcp__"):

576 print("MCP tool called:", block.name)

577 

578 # Print the final result

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

580 print(message.result)

581 

582 

583 asyncio.run(main())

584 ```

585</CodeGroup>

586 

587### 查詢資料庫

588 

589此示例使用 [Postgres MCP 伺服器](https://github.com/modelcontextprotocol/servers/tree/main/src/postgres) 查詢資料庫。連接字符串作為參數傳遞給伺服器。代理程式自動發現資料庫架構、編寫 SQL 查詢並返回結果:

590 

591<CodeGroup>

592 ```typescript TypeScript theme={null}

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

594 

595 // Connection string from environment variable

596 const connectionString = process.env.DATABASE_URL;

597 

598 for await (const message of query({

599 // Natural language query - Claude writes the SQL

600 prompt: "How many users signed up last week? Break it down by day.",

601 options: {

602 mcpServers: {

603 postgres: {

604 command: "npx",

605 // Pass connection string as argument to the server

606 args: ["-y", "@modelcontextprotocol/server-postgres", connectionString]

607 }

608 },

609 // Allow only read queries, not writes

610 allowedTools: ["mcp__postgres__query"]

611 }

612 })) {

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

614 console.log(message.result);

615 }

616 }

617 ```

618 

619 ```python Python theme={null}

620 import asyncio

621 import os

622 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

623 

624 

625 async def main():

626 # Connection string from environment variable

627 connection_string = os.environ["DATABASE_URL"]

628 

629 options = ClaudeAgentOptions(

630 mcp_servers={

631 "postgres": {

632 "command": "npx",

633 # Pass connection string as argument to the server

634 "args": [

635 "-y",

636 "@modelcontextprotocol/server-postgres",

637 connection_string,

638 ],

639 }

640 },

641 # Allow only read queries, not writes

642 allowed_tools=["mcp__postgres__query"],

643 )

644 

645 # Natural language query - Claude writes the SQL

646 async for message in query(

647 prompt="How many users signed up last week? Break it down by day.",

648 options=options,

649 ):

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

651 print(message.result)

652 

653 

654 asyncio.run(main())

655 ```

656</CodeGroup>

657 

658## 錯誤處理

659 

660MCP 伺服器可能因各種原因無法連接:伺服器進程可能未安裝、憑據可能無效,或遠程伺服器可能無法訪問。

661 

662SDK 在每個查詢開始時發出一個 `system` 消息,子類型為 `init`。此消息包括每個 MCP 伺服器的連接狀態。檢查 `status` 字段以在代理程式開始工作前檢測連接失敗:

663 

664<CodeGroup>

665 ```typescript TypeScript theme={null}

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

667 

668 for await (const message of query({

669 prompt: "Process data",

670 options: {

671 mcpServers: {

672 "data-processor": dataServer

673 }

674 }

675 })) {

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

677 const failedServers = message.mcp_servers.filter((s) => s.status !== "connected");

678 

679 if (failedServers.length > 0) {

680 console.warn("Failed to connect:", failedServers);

681 }

682 }

683 

684 if (message.type === "result" && message.subtype === "error_during_execution") {

685 console.error("Execution failed");

686 }

687 }

688 ```

689 

690 ```python Python theme={null}

691 import asyncio

692 from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage, ResultMessage

693 

694 

695 async def main():

696 options = ClaudeAgentOptions(mcp_servers={"data-processor": data_server})

697 

698 async for message in query(prompt="Process data", options=options):

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

700 failed_servers = [

701 s

702 for s in message.data.get("mcp_servers", [])

703 if s.get("status") != "connected"

704 ]

705 

706 if failed_servers:

707 print(f"Failed to connect: {failed_servers}")

708 

709 if (

710 isinstance(message, ResultMessage)

711 and message.subtype == "error_during_execution"

712 ):

713 print("Execution failed")

714 

715 

716 asyncio.run(main())

717 ```

718</CodeGroup>

719 

720## 故障排除

721 

722### 伺服器顯示"失敗"狀態

723 

724檢查 `init` 消息以查看哪些伺服器無法連接:

725 

726```typescript theme={null}

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

728 for (const server of message.mcp_servers) {

729 if (server.status === "failed") {

730 console.error(`Server ${server.name} failed to connect`);

731 }

732 }

733}

734```

735 

736常見原因:

737 

738* **缺少環境變數**:確保設置了所需的令牌和憑據。對於 stdio 伺服器,檢查 `env` 字段是否與伺服器期望的相匹配。

739* **伺服器未安裝**:對於 `npx` 命令,驗證包存在且 Node.js 在您的 PATH 中。

740* **無效的連接字符串**:對於資料庫伺服器,驗證連接字符串格式以及資料庫是否可訪問。

741* **網絡問題**:對於遠程 HTTP/SSE 伺服器,檢查 URL 是否可訪問以及任何防火牆是否允許連接。

742 

743### 工具未被調用

744 

745如果 Claude 看到工具但不使用它們,請檢查您是否已使用 `allowedTools` 授予權限:

746 

747```typescript hidelines={1,-1} theme={null}

748const _ = {

749 options: {

750 mcpServers: {

751 // your servers

752 },

753 allowedTools: ["mcp__servername__*"] // Required for Claude to use the tools

754 }

755};

756```

757 

758### 連接超時

759 

760MCP SDK 對伺服器連接的默認超時為 60 秒。如果您的伺服器需要更長時間才能啟動,連接將失敗。對於需要更多啟動時間的伺服器,請考慮:

761 

762* 使用更輕量級的伺服器(如果可用)

763* 在啟動代理程式前預熱伺服器

764* 檢查伺服器日誌以查找緩慢初始化的原因

765 

766## 相關資源

767 

768* **[自訂工具指南](/zh-TW/agent-sdk/custom-tools)**:構建您自己的 MCP 伺服器,與您的 SDK 應用程式在進程中運行

769* **[權限](/zh-TW/agent-sdk/permissions)**:使用 `allowedTools` 和 `disallowedTools` 控制您的代理程式可以使用哪些 MCP 工具

770* **[TypeScript SDK 參考](/zh-TW/agent-sdk/typescript)**:完整的 API 參考,包括 MCP 配置選項

771* **[Python SDK 參考](/zh-TW/agent-sdk/python)**:完整的 API 參考,包括 MCP 配置選項

772* **[MCP 伺服器目錄](https://github.com/modelcontextprotocol/servers)**:瀏覽可用的 MCP 伺服器,用於資料庫、API 等

Details

825| `debug_stderr` | `Any` | `sys.stderr` | *已棄用* - 用於偵錯輸出的類似檔案的物件。改用 `stderr` 回呼 |825| `debug_stderr` | `Any` | `sys.stderr` | *已棄用* - 用於偵錯輸出的類似檔案的物件。改用 `stderr` 回呼 |

826| `stderr` | `Callable[[str], None] \| None` | `None` | 用於 CLI stderr 輸出的回呼函數 |826| `stderr` | `Callable[[str], None] \| None` | `None` | 用於 CLI stderr 輸出的回呼函數 |

827| `can_use_tool` | [`CanUseTool`](#canusetool) ` \| None` | `None` | tool 權限回呼函數。見 [權限類型](#canusetool) 以了解詳情 |827| `can_use_tool` | [`CanUseTool`](#canusetool) ` \| None` | `None` | tool 權限回呼函數。見 [權限類型](#canusetool) 以了解詳情 |

828| `hooks` | `dict[HookEvent, list[HookMatcher]] \| None` | `None` | 用於攔截事件的 hook 配置 |828| `hooks` | `dict[HookEvent, list[HookMatcher]] \| None` | `None` | 用於攔截事件的 hooks 配置 |

829| `user` | `str \| None` | `None` | 使用者識別碼 |829| `user` | `str \| None` | `None` | 使用者識別碼 |

830| `include_partial_messages` | `bool` | `False` | 包括部分消息串流事件。啟用時,[`StreamEvent`](#streamevent) 消息會被產生 |830| `include_partial_messages` | `bool` | `False` | 包括部分消息串流事件。啟用時,[`StreamEvent`](#streamevent) 消息會被產生 |

831| `include_hook_events` | `bool` | `False` | 在消息流中包括 hook 生命週期事件作為 `HookEventMessage` 物件 |831| `include_hook_events` | `bool` | `False` | 在消息流中包括 hook 生命週期事件作為 `HookEventMessage` 物件 |


834| `plugins` | `list[SdkPluginConfig]` | `[]` | 從本地路徑載入自訂外掛程式。見 [外掛程式](/zh-TW/agent-sdk/plugins) 以了解詳情 |834| `plugins` | `list[SdkPluginConfig]` | `[]` | 從本地路徑載入自訂外掛程式。見 [外掛程式](/zh-TW/agent-sdk/plugins) 以了解詳情 |

835| `sandbox` | [`SandboxSettings`](#sandboxsettings) ` \| None` | `None` | 以程式設計方式配置沙箱行為。見 [沙箱設定](#sandboxsettings) 以了解詳情 |835| `sandbox` | [`SandboxSettings`](#sandboxsettings) ` \| None` | `None` | 以程式設計方式配置沙箱行為。見 [沙箱設定](#sandboxsettings) 以了解詳情 |

836| `setting_sources` | `list[SettingSource] \| None` | `None`(CLI 預設值:所有來源) | 控制要載入哪些檔案系統設定。傳遞 `[]` 以停用使用者、專案和本地設定。無論如何都會載入受管原則設定。見 [使用 Claude Code 功能](/zh-TW/agent-sdk/claude-code-features#what-settingsources-does-not-control) |836| `setting_sources` | `list[SettingSource] \| None` | `None`(CLI 預設值:所有來源) | 控制要載入哪些檔案系統設定。傳遞 `[]` 以停用使用者、專案和本地設定。無論如何都會載入受管原則設定。見 [使用 Claude Code 功能](/zh-TW/agent-sdk/claude-code-features#what-settingsources-does-not-control) |

837| `skills` | `list[str] \| Literal["all"] \| None` | `None` | 可供 session 使用的 skills。傳遞 `"all"` 以啟用每個發現的 skill,或傳遞 skill 名稱清單。設定時,SDK 會自動啟用 Skill tool,無需在 `allowed_tools` 中列出。見 [Skills](/zh-TW/agent-sdk/skills) |

837| `max_thinking_tokens` | `int \| None` | `None` | *已棄用* - 思考區塊的最大令牌數。改用 `thinking` |838| `max_thinking_tokens` | `int \| None` | `None` | *已棄用* - 思考區塊的最大令牌數。改用 `thinking` |

838| `thinking` | [`ThinkingConfig`](#thinkingconfig) ` \| None` | `None` | 控制擴展思考行為。優先於 `max_thinking_tokens` |839| `thinking` | [`ThinkingConfig`](#thinkingconfig) ` \| None` | `None` | 控制擴展思考行為。優先於 `max_thinking_tokens` |

839| `effort` | `Literal["low", "medium", "high", "xhigh", "max"] \| None` | `None` | 思考深度的努力級別 |840| `effort` | `Literal["low", "medium", "high", "xhigh", "max"] \| None` | `None` | 思考深度的努力級別 |


1049| `tools` | 否 | 允許的 tool 名稱陣列。如果省略,繼承所有 tools |1050| `tools` | 否 | 允許的 tool 名稱陣列。如果省略,繼承所有 tools |

1050| `disallowedTools` | 否 | 要從代理的 tool 集中移除的 tool 名稱陣列 |1051| `disallowedTools` | 否 | 要從代理的 tool 集中移除的 tool 名稱陣列 |

1051| `model` | 否 | 此代理的模型覆蓋。接受別名,例如 `"sonnet"`、`"opus"`、`"haiku"` 或 `"inherit"`,或完整模型 ID。如果省略,使用主模型 |1052| `model` | 否 | 此代理的模型覆蓋。接受別名,例如 `"sonnet"`、`"opus"`、`"haiku"` 或 `"inherit"`,或完整模型 ID。如果省略,使用主模型 |

1052| `skills` | 否 | 此代理可用的技能名稱清單 |1053| `skills` | 否 | 此代理可用的 skill 名稱清單 |

1053| `memory` | 否 | 此代理的記憶體來源:`"user"`、`"project"` 或 `"local"` |1054| `memory` | 否 | 此代理的記憶體來源:`"user"`、`"project"` 或 `"local"` |

1054| `mcpServers` | 否 | 此代理可用的 MCP 伺服器。每個項目是伺服器名稱或內聯 `{name: config}` 字典 |1055| `mcpServers` | 否 | 此代理可用的 MCP 伺服器。每個項目是伺服器名稱或內聯 `{name: config}` 字典 |

1055| `initialPrompt` | 否 | 當此代理作為主執行緒代理執行時自動提交為第一個使用者轉 |1056| `initialPrompt` | 否 | 當此代理作為主執行緒代理執行時自動提交為第一個使用者轉 |

agent-sdk/sessions.md +324 −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# 使用 sessions

6 

7> Sessions 如何保持代理對話歷史,以及何時使用 continue、resume 和 fork 返回到先前的運行。

8 

9Session 是 SDK 在您的代理工作時累積的對話歷史。它包含您的提示、代理進行的每個工具呼叫、每個工具結果和每個回應。SDK 會自動將其寫入磁碟,以便您稍後可以返回它。

10 

11返回 session 意味著代理具有之前的完整上下文:它已經讀取的文件、它已經執行的分析、它已經做出的決定。您可以提出後續問題、從中斷中恢復,或分支以嘗試不同的方法。

12 

13<Note>

14 Sessions 保持**對話**,而不是文件系統。要快照和還原代理所做的文件更改,請使用[文件檢查點](/zh-TW/agent-sdk/file-checkpointing)。

15</Note>

16 

17本指南涵蓋如何為您的應用選擇正確的方法、自動追蹤 sessions 的 SDK 介面、如何捕獲 session ID 並手動使用 `resume` 和 `fork`,以及關於跨主機恢復 sessions 的注意事項。

18 

19## 選擇一個方法

20 

21您需要多少 session 處理取決於您的應用程式的形狀。當您發送應該共享上下文的多個提示時,session 管理就會發揮作用。在單個 `query()` 呼叫中,代理已經根據需要進行了盡可能多的轉換,並且權限提示和 `AskUserQuestion` 是[在迴圈中處理](/zh-TW/agent-sdk/user-input)的(它們不會結束呼叫)。

22 

23| 您正在構建的內容 | 使用什麼 |

24| :------------------------------- | :------------------------------------------------------------------------------------------------------------------ |

25| 一次性任務:單個提示,無後續 | 無需額外操作。一個 `query()` 呼叫可以處理它。 |

26| 在一個進程中進行多轉對話 | [`ClaudeSDKClient`(Python)或 `continue: true`(TypeScript)](#automatic-session-management)。SDK 為您追蹤 session,無需 ID 處理。 |

27| 在進程重新啟動後從中斷處繼續 | `continue_conversation=True`(Python)/ `continue: true`(TypeScript)。恢復目錄中最近的 session,無需 ID。 |

28| 恢復特定的過去 session(不是最近的) | 捕獲 session ID 並將其傳遞給 `resume`。 |

29| 嘗試替代方法而不失去原始方法 | Fork session。 |

30| 無狀態任務,不想將任何內容寫入磁碟(僅限 TypeScript) | 設定 [`persistSession: false`](/zh-TW/agent-sdk/typescript#options)。Session 僅在呼叫期間存在於記憶體中。Python 始終保持到磁碟。 |

31 

32### Continue、resume 和 fork

33 

34Continue、resume 和 fork 是您在 `query()` 上設定的選項欄位(Python 中的 [`ClaudeAgentOptions`](/zh-TW/agent-sdk/python#claudeagentoptions),TypeScript 中的 [`Options`](/zh-TW/agent-sdk/typescript#options))。

35 

36**Continue** 和 **resume** 都會拾取現有 session 並將其添加到其中。區別在於它們如何找到該 session:

37 

38* **Continue** 在當前目錄中找到最近的 session。您無需追蹤任何內容。當您的應用一次運行一個對話時效果很好。

39* **Resume** 採用特定的 session ID。您追蹤 ID。當您有多個 sessions(例如,多使用者應用中每個使用者一個)或想要返回不是最近的 session 時需要。

40 

41**Fork** 不同:它創建一個新 session,從原始 session 的歷史副本開始。原始 session 保持不變。使用 fork 嘗試不同的方向,同時保持返回的選項。

42 

43## 自動 session 管理

44 

45兩個 SDK 都提供一個介面,可以跨呼叫為您追蹤 session 狀態,因此您無需手動傳遞 ID。將這些用於單個進程中的多轉對話。

46 

47### Python:`ClaudeSDKClient`

48 

49[`ClaudeSDKClient`](/zh-TW/agent-sdk/python#claudesdkclient) 在內部處理 session ID。每次呼叫 `client.query()` 都會自動繼續相同的 session。呼叫 [`client.receive_response()`](/zh-TW/agent-sdk/python#claudesdkclient) 以迭代當前查詢的訊息。客戶端必須用作非同步上下文管理器。

50 

51此示例針對相同的 `client` 運行兩個查詢。第一個要求代理分析一個模組;第二個要求它重構該模組。因為兩個呼叫都通過相同的客戶端實例進行,第二個查詢具有來自第一個的完整上下文,無需任何明確的 `resume` 或 session ID:

52 

53```python Python theme={null}

54import asyncio

55from claude_agent_sdk import (

56 ClaudeSDKClient,

57 ClaudeAgentOptions,

58 AssistantMessage,

59 ResultMessage,

60 TextBlock,

61)

62 

63 

64def print_response(message):

65 """Print only the human-readable parts of a message."""

66 if isinstance(message, AssistantMessage):

67 for block in message.content:

68 if isinstance(block, TextBlock):

69 print(block.text)

70 elif isinstance(message, ResultMessage):

71 cost = (

72 f"${message.total_cost_usd:.4f}"

73 if message.total_cost_usd is not None

74 else "N/A"

75 )

76 print(f"[done: {message.subtype}, cost: {cost}]")

77 

78 

79async def main():

80 options = ClaudeAgentOptions(

81 allowed_tools=["Read", "Edit", "Glob", "Grep"],

82 )

83 

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

85 # First query: client captures the session ID internally

86 await client.query("Analyze the auth module")

87 async for message in client.receive_response():

88 print_response(message)

89 

90 # Second query: automatically continues the same session

91 await client.query("Now refactor it to use JWT")

92 async for message in client.receive_response():

93 print_response(message)

94 

95 

96asyncio.run(main())

97```

98 

99有關何時使用 `ClaudeSDKClient` 與獨立 `query()` 函數的詳細信息,請參閱 [Python SDK 參考](/zh-TW/agent-sdk/python#choosing-between-query-and-claudesdkclient)。

100 

101### TypeScript:`continue: true`

102 

103穩定的 TypeScript SDK(整個文檔中使用的 `query()` 函數,有時稱為 V1)沒有像 Python 的 `ClaudeSDKClient` 那樣的 session 持有客戶端物件。相反,在每個後續 `query()` 呼叫上傳遞 `continue: true`,SDK 會在當前目錄中拾取最近的 session。無需 ID 追蹤。

104 

105此示例進行兩個單獨的 `query()` 呼叫。第一個創建一個新 session;第二個設定 `continue: true`,這告訴 SDK 在磁碟上找到並恢復最近的 session。代理具有來自第一個呼叫的完整上下文:

106 

107```typescript TypeScript theme={null}

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

109 

110// First query: creates a new session

111for await (const message of query({

112 prompt: "Analyze the auth module",

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

114})) {

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

116 console.log(message.result);

117 }

118}

119 

120// Second query: continue: true resumes the most recent session

121for await (const message of query({

122 prompt: "Now refactor it to use JWT",

123 options: {

124 continue: true,

125 allowedTools: ["Read", "Edit", "Write", "Glob", "Grep"]

126 }

127})) {

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

129 console.log(message.result);

130 }

131}

132```

133 

134<Note>

135 實驗性的 [V2 session API](/zh-TW/agent-sdk/typescript-v2-preview)(提供了 `createSession()` 與 `send` / `stream` 模式)已棄用。改用 V1 `query()` 函數和本頁面上描述的 session 選項。

136</Note>

137 

138## 使用 session 選項與 `query()`

139 

140### 捕獲 session ID

141 

142Resume 和 fork 需要 session ID。從結果訊息上的 `session_id` 欄位讀取它(Python 中的 [`ResultMessage`](/zh-TW/agent-sdk/python#resultmessage),TypeScript 中的 [`SDKResultMessage`](/zh-TW/agent-sdk/typescript#sdkresultmessage)),無論成功或錯誤,它都存在於每個結果上。在 TypeScript 中,ID 也可以作為初始化 `SystemMessage` 上的直接欄位更早獲得;在 Python 中,它嵌套在 `SystemMessage.data` 內。

143 

144<CodeGroup>

145 ```python Python theme={null}

146 import asyncio

147 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

148 

149 

150 async def main():

151 session_id = None

152 

153 async for message in query(

154 prompt="Analyze the auth module and suggest improvements",

155 options=ClaudeAgentOptions(

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

157 ),

158 ):

159 if isinstance(message, ResultMessage):

160 session_id = message.session_id

161 if message.subtype == "success":

162 print(message.result)

163 

164 print(f"Session ID: {session_id}")

165 return session_id

166 

167 

168 session_id = asyncio.run(main())

169 ```

170 

171 ```typescript TypeScript theme={null}

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

173 

174 let sessionId: string | undefined;

175 

176 for await (const message of query({

177 prompt: "Analyze the auth module and suggest improvements",

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

179 })) {

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

181 sessionId = message.session_id;

182 if (message.subtype === "success") {

183 console.log(message.result);

184 }

185 }

186 }

187 

188 console.log(`Session ID: ${sessionId}`);

189 ```

190</CodeGroup>

191 

192### 按 ID 恢復

193 

194將 session ID 傳遞給 `resume` 以返回到該特定 session。代理從 session 中斷的任何地方拾取完整上下文。恢復的常見原因:

195 

196* **跟進已完成的任務。** 代理已經分析了某些內容;現在您希望它根據該分析採取行動,而無需重新讀取文件。

197* **從限制中恢復。** 第一次運行以 `error_max_turns` 或 `error_max_budget_usd` 結束(請參閱[處理結果](/zh-TW/agent-sdk/agent-loop#handle-the-result));以更高的限制恢復。

198* **重新啟動您的進程。** 您在關閉前捕獲了 ID,並想恢復對話。

199 

200此示例使用後續提示恢復[捕獲 session ID](#capture-the-session-id) 中的 session。因為您正在恢復,代理已經在上下文中具有先前的分析:

201 

202<CodeGroup>

203 ```python Python theme={null}

204 # Earlier session analyzed the code; now build on that analysis

205 async for message in query(

206 prompt="Now implement the refactoring you suggested",

207 options=ClaudeAgentOptions(

208 resume=session_id,

209 allowed_tools=["Read", "Edit", "Write", "Glob", "Grep"],

210 ),

211 ):

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

213 print(message.result)

214 ```

215 

216 ```typescript TypeScript theme={null}

217 // Earlier session analyzed the code; now build on that analysis

218 for await (const message of query({

219 prompt: "Now implement the refactoring you suggested",

220 options: {

221 resume: sessionId,

222 allowedTools: ["Read", "Edit", "Write", "Glob", "Grep"]

223 }

224 })) {

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

226 console.log(message.result);

227 }

228 }

229 ```

230</CodeGroup>

231 

232<Tip>

233 如果 `resume` 呼叫返回新 session 而不是預期的歷史,最常見的原因是不匹配的 `cwd`。Sessions 存儲在 `~/.claude/projects/<encoded-cwd>/*.jsonl` 下,其中 `<encoded-cwd>` 是絕對工作目錄,每個非英數字元都被替換為 `-`(所以 `/Users/me/proj` 變成 `-Users-me-proj`)。如果您的 resume 呼叫從不同的目錄運行,SDK 會在錯誤的位置查找。session 文件也需要存在於當前機器上。

234</Tip>

235 

236要跨機器或在無伺服器環境中恢復 sessions,請使用 [`SessionStore` 適配器](/zh-TW/agent-sdk/session-storage)將記錄鏡像到共享存儲。

237 

238### Fork 以探索替代方案

239 

240Forking 創建一個新 session,從原始 session 的歷史副本開始,但從該點開始分歧。fork 獲得自己的 session ID;原始的 ID 和歷史保持不變。您最終得到兩個獨立的 sessions,可以分別恢復。

241 

242<Note>

243 Forking 分支對話歷史,而不是文件系統。如果 forked 代理編輯文件,這些更改是真實的,對在同一目錄中工作的任何 session 都可見。要分支和還原文件更改,請使用[文件檢查點](/zh-TW/agent-sdk/file-checkpointing)。

244</Note>

245 

246此示例基於[捕獲 session ID](#capture-the-session-id):您已經在 `session_id` 中分析了一個 auth 模組,並想探索 OAuth2 而不失去 JWT 焦點的線程。第一個塊 forks session 並捕獲 fork 的 ID(`forked_id`);第二個塊恢復原始 `session_id` 以繼續沿著 JWT 路徑。您現在有兩個 session ID 指向兩個單獨的歷史:

247 

248<CodeGroup>

249 ```python Python theme={null}

250 # Fork: branch from session_id into a new session

251 forked_id = None

252 async for message in query(

253 prompt="Instead of JWT, implement OAuth2 for the auth module",

254 options=ClaudeAgentOptions(

255 resume=session_id,

256 fork_session=True,

257 ),

258 ):

259 if isinstance(message, ResultMessage):

260 forked_id = message.session_id # The fork's ID, distinct from session_id

261 if message.subtype == "success":

262 print(message.result)

263 

264 print(f"Forked session: {forked_id}")

265 

266 # Original session is untouched; resuming it continues the JWT thread

267 async for message in query(

268 prompt="Continue with the JWT approach",

269 options=ClaudeAgentOptions(resume=session_id),

270 ):

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

272 print(message.result)

273 ```

274 

275 ```typescript TypeScript theme={null}

276 // Fork: branch from sessionId into a new session

277 let forkedId: string | undefined;

278 

279 for await (const message of query({

280 prompt: "Instead of JWT, implement OAuth2 for the auth module",

281 options: {

282 resume: sessionId,

283 forkSession: true

284 }

285 })) {

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

287 forkedId = message.session_id; // The fork's ID, distinct from sessionId

288 }

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

290 console.log(message.result);

291 }

292 }

293 

294 console.log(`Forked session: ${forkedId}`);

295 

296 // Original session is untouched; resuming it continues the JWT thread

297 for await (const message of query({

298 prompt: "Continue with the JWT approach",

299 options: { resume: sessionId }

300 })) {

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

302 console.log(message.result);

303 }

304 }

305 ```

306</CodeGroup>

307 

308## 跨主機恢復

309 

310Session 文件是創建它們的機器的本地文件。要在不同的主機上恢復 session(CI 工作者、臨時容器、無伺服器),您有兩個選項:

311 

312* **移動 session 文件。** 從第一次運行中保持 `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl`,並在呼叫 `resume` 之前將其恢復到新主機上的相同路徑。`cwd` 必須匹配。

313* **不依賴 session 恢復。** 捕獲您需要的結果(分析輸出、決定、文件差異)作為應用程式狀態,並將其傳遞到新 session 的提示中。這通常比運送記錄文件更穩健。

314 

315兩個 SDK 都公開用於列舉磁碟上的 sessions 和讀取其訊息的函數:TypeScript 中的 [`listSessions()`](/zh-TW/agent-sdk/typescript#listsessions) 和 [`getSessionMessages()`](/zh-TW/agent-sdk/typescript#getsessionmessages),Python 中的 [`list_sessions()`](/zh-TW/agent-sdk/python#list_sessions) 和 [`get_session_messages()`](/zh-TW/agent-sdk/python#get_session_messages)。使用它們構建自訂 session 選擇器、清理邏輯或記錄檢視器。

316 

317兩個 SDK 也公開用於查找和變更個別 sessions 的函數:Python 中的 [`get_session_info()`](/zh-TW/agent-sdk/python#get_session_info)、[`rename_session()`](/zh-TW/agent-sdk/python#rename_session) 和 [`tag_session()`](/zh-TW/agent-sdk/python#tag_session),以及 TypeScript 中的 [`getSessionInfo()`](/zh-TW/agent-sdk/typescript#getsessioninfo)、[`renameSession()`](/zh-TW/agent-sdk/typescript#renamesession) 和 [`tagSession()`](/zh-TW/agent-sdk/typescript#tagsession)。使用它們按標籤組織 sessions 或給它們人類可讀的標題。

318 

319## 相關資源

320 

321* [代理迴圈如何工作](/zh-TW/agent-sdk/agent-loop):了解 session 中的轉換、訊息和上下文累積

322* [文件檢查點](/zh-TW/agent-sdk/file-checkpointing):跨 sessions 追蹤和還原文件更改

323* [Python `ClaudeAgentOptions`](/zh-TW/agent-sdk/python#claudeagentoptions):Python 的完整 session 選項參考

324* [TypeScript `Options`](/zh-TW/agent-sdk/typescript#options):TypeScript 的完整 session 選項參考

agent-sdk/skills.md +315 −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 中的 Agent Skills

6 

7> 使用 Claude Agent SDK 中的 Agent Skills 擴展 Claude 的專門功能

8 

9## 概述

10 

11Agent Skills 使用專門功能擴展 Claude,Claude 會在相關時自動調用這些功能。Skills 被打包為 `SKILL.md` 文件,包含說明、描述和可選的支持資源。

12 

13有關 Skills 的全面信息,包括優勢、架構和編寫指南,請參閱 [Agent Skills 概述](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview)。

14 

15## Skills 如何與 SDK 配合使用

16 

17使用 Claude Agent SDK 時,Skills 的特點是:

18 

191. **定義為文件系統工件**:在特定目錄(`.claude/skills/`)中創建為 `SKILL.md` 文件

202. **從文件系統加載**:Skills 從由 `settingSources`(TypeScript)或 `setting_sources`(Python)控制的文件系統位置加載

213. **自動發現**:加載文件系統設置後,在啟動時從用戶和項目目錄發現 Skill 元數據;觸發時加載完整內容

224. **由模型調用**:Claude 根據上下文自動選擇何時使用它們

235. **通過 `skills` 選項進行篩選**:發現的 Skills 默認啟用。傳遞 Skill 名稱列表、`"all"` 或 `[]` 來控制會話中可用的 Skills

24 

25與子代理不同(可以以編程方式定義),Skills 必須創建為文件系統工件。SDK 不提供用於註冊 Skills 的編程 API。

26 

27<Note>

28 Skills 通過文件系統設置源發現。使用默認 `query()` 選項時,SDK 加載用戶和項目源,因此 `~/.claude/skills/` 和 `<cwd>/.claude/skills/` 中的 Skills 可用。如果您明確設置 `settingSources`,請包含 `'user'` 或 `'project'` 以保持 Skill 發現,或使用 [`plugins` 選項](/zh-TW/agent-sdk/plugins) 從特定路徑加載 Skills。

29</Note>

30 

31## 在 SDK 中使用 Skills

32 

33在 `query()` 上設置 `skills` 選項以控制會話中可用的 Skills。省略時,發現的 Skills 啟用且 Skill 工具可用,與 CLI 行為匹配。傳遞 `"all"` 以啟用每個發現的 Skill,傳遞 Skill 名稱列表以僅啟用那些,或傳遞 `[]` 以禁用全部。設置 `skills` 時,SDK 自動啟用 Skill 工具,因此您無需在 `allowedTools` 中列出它。

34 

35配置後,Claude 自動從文件系統發現 Skills 並在與用戶請求相關時調用它們。

36 

37<CodeGroup>

38 ```python Python theme={null}

39 import asyncio

40 from claude_agent_sdk import query, ClaudeAgentOptions

41 

42 

43 async def main():

44 options = ClaudeAgentOptions(

45 cwd="/path/to/project", # Project with .claude/skills/

46 setting_sources=["user", "project"], # Load Skills from filesystem

47 skills="all", # Enable every discovered Skill

48 allowed_tools=["Read", "Write", "Bash"],

49 )

50 

51 async for message in query(

52 prompt="Help me process this PDF document", options=options

53 ):

54 print(message)

55 

56 

57 asyncio.run(main())

58 ```

59 

60 ```typescript TypeScript theme={null}

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

62 

63 for await (const message of query({

64 prompt: "Help me process this PDF document",

65 options: {

66 cwd: "/path/to/project", // Project with .claude/skills/

67 settingSources: ["user", "project"], // Load Skills from filesystem

68 skills: "all", // Enable every discovered Skill

69 allowedTools: ["Read", "Write", "Bash"]

70 }

71 })) {

72 console.log(message);

73 }

74 ```

75</CodeGroup>

76 

77要僅啟用特定 Skills,請傳遞它們的名稱。名稱與 `SKILL.md` 中的 `name` 字段或 Skill 的目錄名稱匹配。對於插件提供的 Skills,使用 `plugin:skill`。

78 

79<CodeGroup>

80 ```python Python theme={null}

81 options = ClaudeAgentOptions(skills=["pdf", "docx"])

82 ```

83 

84 ```typescript TypeScript theme={null}

85 const options = { skills: ["pdf", "docx"] };

86 ```

87</CodeGroup>

88 

89`skills` 選項是上下文篩選器,不是沙箱。未列出的 Skills 對模型隱藏並被 Skill 工具拒絕,但它們的文件仍在磁盤上,可通過 Read 和 Bash 訪問。

90 

91## Skill 位置

92 

93Skills 根據您的 `settingSources`/`setting_sources` 配置從文件系統目錄加載:

94 

95* **項目 Skills**(`.claude/skills/`):通過 git 與您的團隊共享 - 當 `setting_sources` 包含 `"project"` 時加載

96* **用戶 Skills**(`~/.claude/skills/`):跨所有項目的個人 Skills - 當 `setting_sources` 包含 `"user"` 時加載

97* **插件 Skills**:與已安裝的 Claude Code 插件捆綁

98 

99## 創建 Skills

100 

101Skills 定義為包含具有 YAML frontmatter 和 Markdown 內容的 `SKILL.md` 文件的目錄。`description` 字段確定 Claude 何時調用您的 Skill。

102 

103**示例目錄結構**:

104 

105```bash theme={null}

106.claude/skills/processing-pdfs/

107└── SKILL.md

108```

109 

110有關創建 Skills 的完整指導,包括 SKILL.md 結構、多文件 Skills 和示例,請參閱:

111 

112* [Claude Code 中的 Agent Skills](/zh-TW/skills):包含示例和故障排除的完整指南

113* [Agent Skills 最佳實踐](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices):編寫指南和命名約定

114* [Agent Skills Cookbook](https://platform.claude.com/cookbook/skills-notebooks-01-skills-introduction):示例 Skills 和模板

115 

116## 工具限制

117 

118<Note>

119 SKILL.md 中的 `allowed-tools` frontmatter 字段僅在直接使用 Claude Code CLI 時受支持。**通過 SDK 使用 Skills 時不適用**。

120 

121 使用 SDK 時,通過查詢配置中的主 `allowedTools` 選項控制工具訪問。

122</Note>

123 

124要在 SDK 應用程序中控制 Skills 的工具訪問,使用 `allowedTools` 預先批准特定工具。沒有 `canUseTool` 回調時,列表中沒有的任何內容都被拒絕:

125 

126<Note>

127 假設第一個示例中的導入語句在以下代碼片段中。

128</Note>

129 

130<CodeGroup>

131 ```python Python theme={null}

132 options = ClaudeAgentOptions(

133 setting_sources=["user", "project"], # Load Skills from filesystem

134 skills="all",

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

136 )

137 

138 async for message in query(prompt="Analyze the codebase structure", options=options):

139 print(message)

140 ```

141 

142 ```typescript TypeScript theme={null}

143 for await (const message of query({

144 prompt: "Analyze the codebase structure",

145 options: {

146 settingSources: ["user", "project"], // Load Skills from filesystem

147 skills: "all",

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

149 permissionMode: "dontAsk" // Deny anything not in allowedTools

150 }

151 })) {

152 console.log(message);

153 }

154 ```

155</CodeGroup>

156 

157## 發現可用的 Skills

158 

159要查看 SDK 應用程序中可用的 Skills,只需詢問 Claude:

160 

161<CodeGroup>

162 ```python Python theme={null}

163 options = ClaudeAgentOptions(

164 setting_sources=["user", "project"], # Load Skills from filesystem

165 skills="all",

166 )

167 

168 async for message in query(prompt="What Skills are available?", options=options):

169 print(message)

170 ```

171 

172 ```typescript TypeScript theme={null}

173 for await (const message of query({

174 prompt: "What Skills are available?",

175 options: {

176 settingSources: ["user", "project"], // Load Skills from filesystem

177 skills: "all"

178 }

179 })) {

180 console.log(message);

181 }

182 ```

183</CodeGroup>

184 

185Claude 將根據您當前的工作目錄和已安裝的插件列出可用的 Skills。

186 

187## 測試 Skills

188 

189通過提出與其描述相匹配的問題來測試 Skills:

190 

191<CodeGroup>

192 ```python Python theme={null}

193 options = ClaudeAgentOptions(

194 cwd="/path/to/project",

195 setting_sources=["user", "project"], # Load Skills from filesystem

196 skills="all",

197 allowed_tools=["Read", "Bash"],

198 )

199 

200 async for message in query(prompt="Extract text from invoice.pdf", options=options):

201 print(message)

202 ```

203 

204 ```typescript TypeScript theme={null}

205 for await (const message of query({

206 prompt: "Extract text from invoice.pdf",

207 options: {

208 cwd: "/path/to/project",

209 settingSources: ["user", "project"], // Load Skills from filesystem

210 skills: "all",

211 allowedTools: ["Read", "Bash"]

212 }

213 })) {

214 console.log(message);

215 }

216 ```

217</CodeGroup>

218 

219如果描述與您的請求相匹配,Claude 會自動調用相關的 Skill。

220 

221## 故障排除

222 

223### 找不到 Skills

224 

225**檢查 settingSources 配置**:Skills 通過 `user` 和 `project` 設置源發現。如果您明確設置 `settingSources`/`setting_sources` 並省略這些源,Skills 不會加載:

226 

227<CodeGroup>

228 ```python Python theme={null}

229 # Skills not loaded: setting_sources excludes user and project

230 options = ClaudeAgentOptions(setting_sources=[], skills="all")

231 

232 # Skills loaded: user and project sources included

233 options = ClaudeAgentOptions(

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

235 skills="all",

236 )

237 ```

238 

239 ```typescript TypeScript theme={null}

240 // Skills not loaded: settingSources excludes user and project

241 const options = {

242 settingSources: [],

243 skills: "all"

244 };

245 

246 // Skills loaded: user and project sources included

247 const options = {

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

249 skills: "all"

250 };

251 ```

252</CodeGroup>

253 

254有關 `settingSources`/`setting_sources` 的更多詳細信息,請參閱 [TypeScript SDK 參考](/zh-TW/agent-sdk/typescript#settingsource) 或 [Python SDK 參考](/zh-TW/agent-sdk/python#settingsource)。

255 

256**檢查工作目錄**:SDK 相對於 `cwd` 選項加載 Skills。確保它指向包含 `.claude/skills/` 的目錄:

257 

258<CodeGroup>

259 ```python Python theme={null}

260 # Ensure your cwd points to the directory containing .claude/skills/

261 options = ClaudeAgentOptions(

262 cwd="/path/to/project", # Must contain .claude/skills/

263 setting_sources=["user", "project"], # Loads skills from these sources

264 skills="all",

265 )

266 ```

267 

268 ```typescript TypeScript theme={null}

269 // Ensure your cwd points to the directory containing .claude/skills/

270 const options = {

271 cwd: "/path/to/project", // Must contain .claude/skills/

272 settingSources: ["user", "project"], // Loads skills from these sources

273 skills: "all"

274 };

275 ```

276</CodeGroup>

277 

278有關完整模式,請參閱上面的"在 SDK 中使用 Skills"部分。

279 

280**驗證文件系統位置**:

281 

282```bash theme={null}

283# Check project Skills

284ls .claude/skills/*/SKILL.md

285 

286# Check personal Skills

287ls ~/.claude/skills/*/SKILL.md

288```

289 

290### Skill 未被使用

291 

292**檢查 `skills` 選項**:如果您傳遞了 `skills` 列表,確認 Skill 的名稱已包含。傳遞 `[]` 會禁用所有 Skills。

293 

294**檢查描述**:確保它具體且包含相關關鍵字。有關編寫有效描述的指導,請參閱 [Agent Skills 最佳實踐](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices#writing-effective-descriptions)。

295 

296### 其他故障排除

297 

298有關一般 Skills 故障排除(YAML 語法、調試等),請參閱 [Claude Code Skills 故障排除部分](/zh-TW/skills#troubleshooting)。

299 

300## 相關文檔

301 

302### Skills 指南

303 

304* [Claude Code 中的 Agent Skills](/zh-TW/skills):包含創建、示例和故障排除的完整 Skills 指南

305* [Agent Skills 概述](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview):概念概述、優勢和架構

306* [Agent Skills 最佳實踐](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices):有效 Skills 的編寫指南

307* [Agent Skills Cookbook](https://platform.claude.com/cookbook/skills-notebooks-01-skills-introduction):示例 Skills 和模板

308 

309### SDK 資源

310 

311* [SDK 中的子代理](/zh-TW/agent-sdk/subagents):類似的基於文件系統的代理,具有編程選項

312* [SDK 中的斜杠命令](/zh-TW/agent-sdk/slash-commands):用戶調用的命令

313* [SDK 概述](/zh-TW/agent-sdk/overview):一般 SDK 概念

314* [TypeScript SDK 參考](/zh-TW/agent-sdk/typescript):完整 API 文檔

315* [Python SDK 參考](/zh-TW/agent-sdk/python):完整 API 文檔

agent-sdk/subagents.md +601 −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 中的子代理

6 

7> 定義和調用子代理以隔離上下文、並行運行任務,以及在 Claude Agent SDK 應用程式中應用專門化指令。

8 

9子代理是您的主代理可以生成的獨立代理實例,用於處理專注的子任務。

10使用子代理來隔離專注子任務的上下文、並行運行多個分析,以及應用專門化指令,而不會使主代理的提示詞變得臃腫。

11 

12本指南說明如何使用 `agents` 參數在 SDK 中定義和使用子代理。

13 

14## 概述

15 

16您可以通過三種方式創建子代理:

17 

18* **以程式方式**:在您的 `query()` 選項中使用 `agents` 參數([TypeScript](/zh-TW/agent-sdk/typescript#agentdefinition)、[Python](/zh-TW/agent-sdk/python#agentdefinition))

19* **基於檔案系統**:在 `.claude/agents/` 目錄中將代理定義為 markdown 檔案(請參閱[將子代理定義為檔案](/zh-TW/sub-agents))

20* **內置通用代理**:Claude 可以隨時通過 Agent 工具調用內置的 `general-purpose` 子代理,無需您定義任何內容

21 

22本指南重點介紹程式化方法,這是 SDK 應用程式的推薦方法。

23 

24定義子代理時,Claude 根據每個子代理的 `description` 欄位確定是否調用它。編寫清晰的描述,說明何時應使用子代理,Claude 將自動委派適當的任務。您也可以在提示詞中按名稱明確請求子代理(例如,「使用代碼審查員代理來...」)。

25 

26## 使用子代理的好處

27 

28### 上下文隔離

29 

30每個子代理在其自己的新對話中運行。中間工具調用和結果保留在子代理內;只有其最終消息返回到父代理。請參閱[子代理繼承的內容](#what-subagents-inherit)以了解子代理上下文中的確切內容。

31 

32**示例:** `research-assistant` 子代理可以探索數十個檔案,而無需任何該內容在主對話中累積。父代理接收簡潔的摘要,而不是子代理讀取的每個檔案。

33 

34### 並行化

35 

36多個子代理可以並發運行,大大加快複雜工作流程的速度。

37 

38**示例:** 在代碼審查期間,您可以同時運行 `style-checker`、`security-scanner` 和 `test-coverage` 子代理,將審查時間從幾分鐘縮短到幾秒鐘。

39 

40### 專門化指令和知識

41 

42每個子代理可以有具有特定專業知識、最佳實踐和約束的定製系統提示詞。

43 

44**示例:** `database-migration` 子代理可以具有有關 SQL 最佳實踐、回滾策略和數據完整性檢查的詳細知識,這些在主代理的指令中將是不必要的噪音。

45 

46### 工具限制

47 

48子代理可以限制為特定工具,降低意外操作的風險。

49 

50**示例:** `doc-reviewer` 子代理可能只能訪問 Read 和 Grep 工具,確保它可以分析但永遠不會意外修改您的文檔檔案。

51 

52## 創建子代理

53 

54### 程式化定義(推薦)

55 

56使用 `agents` 參數直接在代碼中定義子代理。此示例創建兩個子代理:一個具有唯讀訪問權限的代碼審查員和一個可以執行命令的測試運行器。由於 Claude 通過 Agent 工具調用子代理,因此 `Agent` 工具必須包含在 `allowedTools` 中。

57 

58<CodeGroup>

59 ```python Python theme={null}

60 import asyncio

61 from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

62 

63 

64 async def main():

65 async for message in query(

66 prompt="Review the authentication module for security issues",

67 options=ClaudeAgentOptions(

68 # Agent tool is required for subagent invocation

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

70 agents={

71 "code-reviewer": AgentDefinition(

72 # description tells Claude when to use this subagent

73 description="Expert code review specialist. Use for quality, security, and maintainability reviews.",

74 # prompt defines the subagent's behavior and expertise

75 prompt="""You are a code review specialist with expertise in security, performance, and best practices.

76 

77 When reviewing code:

78 - Identify security vulnerabilities

79 - Check for performance issues

80 - Verify adherence to coding standards

81 - Suggest specific improvements

82 

83 Be thorough but concise in your feedback.""",

84 # tools restricts what the subagent can do (read-only here)

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

86 # model overrides the default model for this subagent

87 model="sonnet",

88 ),

89 "test-runner": AgentDefinition(

90 description="Runs and analyzes test suites. Use for test execution and coverage analysis.",

91 prompt="""You are a test execution specialist. Run tests and provide clear analysis of results.

92 

93 Focus on:

94 - Running test commands

95 - Analyzing test output

96 - Identifying failing tests

97 - Suggesting fixes for failures""",

98 # Bash access lets this subagent run test commands

99 tools=["Bash", "Read", "Grep"],

100 ),

101 },

102 ),

103 ):

104 if hasattr(message, "result"):

105 print(message.result)

106 

107 

108 asyncio.run(main())

109 ```

110 

111 ```typescript TypeScript theme={null}

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

113 

114 for await (const message of query({

115 prompt: "Review the authentication module for security issues",

116 options: {

117 // Agent tool is required for subagent invocation

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

119 agents: {

120 "code-reviewer": {

121 // description tells Claude when to use this subagent

122 description:

123 "Expert code review specialist. Use for quality, security, and maintainability reviews.",

124 // prompt defines the subagent's behavior and expertise

125 prompt: `You are a code review specialist with expertise in security, performance, and best practices.

126 

127 When reviewing code:

128 - Identify security vulnerabilities

129 - Check for performance issues

130 - Verify adherence to coding standards

131 - Suggest specific improvements

132 

133 Be thorough but concise in your feedback.`,

134 // tools restricts what the subagent can do (read-only here)

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

136 // model overrides the default model for this subagent

137 model: "sonnet"

138 },

139 "test-runner": {

140 description:

141 "Runs and analyzes test suites. Use for test execution and coverage analysis.",

142 prompt: `You are a test execution specialist. Run tests and provide clear analysis of results.

143 

144 Focus on:

145 - Running test commands

146 - Analyzing test output

147 - Identifying failing tests

148 - Suggesting fixes for failures`,

149 // Bash access lets this subagent run test commands

150 tools: ["Bash", "Read", "Grep"]

151 }

152 }

153 }

154 })) {

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

156 }

157 ```

158</CodeGroup>

159 

160### AgentDefinition 配置

161 

162| 欄位 | 類型 | 必需 | 描述 |

163| :---------------- | :---------------------------------------------------------- | :- | :------------------------------------------------------------------------------ |

164| `description` | `string` | 是 | 何時使用此代理的自然語言描述 |

165| `prompt` | `string` | 是 | 代理的系統提示詞,定義其角色和行為 |

166| `tools` | `string[]` | 否 | 允許的工具名稱陣列。如果省略,繼承所有工具 |

167| `disallowedTools` | `string[]` | 否 | 要從代理的工具集中移除的工具名稱陣列 |

168| `model` | `string` | 否 | 此代理的模型覆蓋。接受別名,例如 `'sonnet'`、`'opus'`、`'haiku'`、`'inherit'`,或完整模型 ID。如果省略,預設為主模型 |

169| `skills` | `string[]` | 否 | 在啟動時預加載到代理上下文中的技能名稱列表。未列出的技能仍可通過 Skill 工具調用 |

170| `memory` | `'user' \| 'project' \| 'local'` | 否 | 此代理的記憶體來源 |

171| `mcpServers` | `(string \| object)[]` | 否 | 此代理可用的 MCP 伺服器,按名稱或內聯配置 |

172| `maxTurns` | `number` | 否 | 代理停止前的最大代理轉數 |

173| `background` | `boolean` | 否 | 調用時將此代理作為非阻塞背景任務運行 |

174| `effort` | `'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max' \| number` | 否 | 此代理的推理努力級別 |

175| `permissionMode` | `PermissionMode` | 否 | 此代理內工具執行的權限模式 |

176 

177在 Python SDK 中,這些欄位名稱使用 camelCase 以匹配線路格式。有關詳細信息,請參閱 [`AgentDefinition` 參考](/zh-TW/agent-sdk/python#agentdefinition)。

178 

179<Note>

180 子代理無法生成自己的子代理。不要在子代理的 `tools` 陣列中包含 `Agent`。

181</Note>

182 

183### 基於檔案系統的定義(替代方案)

184 

185您也可以在 `.claude/agents/` 目錄中將子代理定義為 markdown 檔案。有關此方法的詳細信息,請參閱 [Claude Code 子代理文檔](/zh-TW/sub-agents)。以程式方式定義的代理優先於具有相同名稱的基於檔案系統的代理。

186 

187<Note>

188 即使不定義自訂子代理,當 `Agent` 在您的 `allowedTools` 中時,Claude 也可以生成內置的 `general-purpose` 子代理。這對於委派研究或探索任務而無需創建專門代理很有用。

189</Note>

190 

191## 子代理繼承的內容

192 

193子代理的上下文窗口從新開始(無父對話),但並非空的。從父代理到子代理的唯一通道是 Agent 工具的提示詞字符串,因此請直接在該提示詞中包含子代理需要的任何檔案路徑、錯誤消息或決策。

194 

195| 子代理接收 | 子代理不接收 |

196| :------------------------------------------------ | :---------------------------------------- |

197| 其自己的系統提示詞(`AgentDefinition.prompt`)和 Agent 工具的提示詞 | 父代理的對話歷史或工具結果 |

198| 項目 CLAUDE.md(通過 `settingSources` 加載) | 預加載的技能內容,除非在 `AgentDefinition.skills` 中列出 |

199| 工具定義(從父代理繼承,或 `tools` 中的子集) | 父代理的系統提示詞 |

200 

201<Note>

202 父代理逐字接收子代理的最終消息作為 Agent 工具結果,但可能在其自己的回應中進行摘要。要在面向用戶的回應中逐字保留子代理輸出,請在您傳遞給**主** `query()` 調用的提示詞或 `systemPrompt` 選項中包含執行此操作的指令。

203</Note>

204 

205## 調用子代理

206 

207### 自動調用

208 

209Claude 根據任務和每個子代理的 `description` 自動決定何時調用子代理。例如,如果您定義了一個 `performance-optimizer` 子代理,其描述為「查詢調優的性能優化專家」,當您的提示詞提到優化查詢時,Claude 將調用它。

210 

211編寫清晰、具體的描述,以便 Claude 可以將任務匹配到正確的子代理。

212 

213### 明確調用

214 

215要保證 Claude 使用特定的子代理,請在提示詞中按名稱提及它:

216 

217```text theme={null}

218"Use the code-reviewer agent to check the authentication module"

219```

220 

221這繞過自動匹配並直接調用命名的子代理。

222 

223### 動態代理配置

224 

225您可以根據運行時條件動態創建代理定義。此示例創建一個安全審查員,具有不同的嚴格級別,對嚴格審查使用更強大的模型。

226 

227<CodeGroup>

228 ```python Python theme={null}

229 import asyncio

230 from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

231 

232 

233 # Factory function that returns an AgentDefinition

234 # This pattern lets you customize agents based on runtime conditions

235 def create_security_agent(security_level: str) -> AgentDefinition:

236 is_strict = security_level == "strict"

237 return AgentDefinition(

238 description="Security code reviewer",

239 # Customize the prompt based on strictness level

240 prompt=f"You are a {'strict' if is_strict else 'balanced'} security reviewer...",

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

242 # Key insight: use a more capable model for high-stakes reviews

243 model="opus" if is_strict else "sonnet",

244 )

245 

246 

247 async def main():

248 # The agent is created at query time, so each request can use different settings

249 async for message in query(

250 prompt="Review this PR for security issues",

251 options=ClaudeAgentOptions(

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

253 agents={

254 # Call the factory with your desired configuration

255 "security-reviewer": create_security_agent("strict")

256 },

257 ),

258 ):

259 if hasattr(message, "result"):

260 print(message.result)

261 

262 

263 asyncio.run(main())

264 ```

265 

266 ```typescript TypeScript theme={null}

267 import { query, type AgentDefinition } from "@anthropic-ai/claude-agent-sdk";

268 

269 // Factory function that returns an AgentDefinition

270 // This pattern lets you customize agents based on runtime conditions

271 function createSecurityAgent(securityLevel: "basic" | "strict"): AgentDefinition {

272 const isStrict = securityLevel === "strict";

273 return {

274 description: "Security code reviewer",

275 // Customize the prompt based on strictness level

276 prompt: `You are a ${isStrict ? "strict" : "balanced"} security reviewer...`,

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

278 // Key insight: use a more capable model for high-stakes reviews

279 model: isStrict ? "opus" : "sonnet"

280 };

281 }

282 

283 // The agent is created at query time, so each request can use different settings

284 for await (const message of query({

285 prompt: "Review this PR for security issues",

286 options: {

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

288 agents: {

289 // Call the factory with your desired configuration

290 "security-reviewer": createSecurityAgent("strict")

291 }

292 }

293 })) {

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

295 }

296 ```

297</CodeGroup>

298 

299## 檢測子代理調用

300 

301子代理通過 Agent 工具調用。要檢測何時調用子代理,請檢查 `tool_use` 塊,其中 `name` 是 `"Agent"`。來自子代理上下文內的消息包括 `parent_tool_use_id` 欄位。

302 

303<Note>

304 工具名稱在 Claude Code v2.1.63 中從 `"Task"` 重命名為 `"Agent"`。當前 SDK 版本在 `tool_use` 塊中發出 `"Agent"`,但在 `system:init` 工具列表和 `result.permission_denials[].tool_name` 中仍使用 `"Task"`。檢查 `block.name` 中的兩個值可確保跨 SDK 版本的兼容性。

305</Note>

306 

307此示例遍歷流式消息,記錄何時調用子代理以及後續消息何時源自該子代理的執行上下文。

308 

309<Note>

310 消息結構在 SDK 之間有所不同。在 Python 中,內容塊直接通過 `message.content` 訪問。在 TypeScript 中,`SDKAssistantMessage` 包裝 Claude API 消息,因此內容通過 `message.message.content` 訪問。

311</Note>

312 

313<CodeGroup>

314 ```python Python theme={null}

315 import asyncio

316 from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

317 

318 

319 async def main():

320 async for message in query(

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

322 options=ClaudeAgentOptions(

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

324 agents={

325 "code-reviewer": AgentDefinition(

326 description="Expert code reviewer.",

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

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

329 )

330 },

331 ),

332 ):

333 # Check for subagent invocation. Match both names: older SDK

334 # versions emitted "Task", current versions emit "Agent".

335 if hasattr(message, "content") and message.content:

336 for block in message.content:

337 if getattr(block, "type", None) == "tool_use" and block.name in (

338 "Task",

339 "Agent",

340 ):

341 print(f"Subagent invoked: {block.input.get('subagent_type')}")

342 

343 # Check if this message is from within a subagent's context

344 if hasattr(message, "parent_tool_use_id") and message.parent_tool_use_id:

345 print(" (running inside subagent)")

346 

347 if hasattr(message, "result"):

348 print(message.result)

349 

350 

351 asyncio.run(main())

352 ```

353 

354 ```typescript TypeScript theme={null}

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

356 

357 for await (const message of query({

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

359 options: {

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

361 agents: {

362 "code-reviewer": {

363 description: "Expert code reviewer.",

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

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

366 }

367 }

368 }

369 })) {

370 const msg = message as any;

371 

372 // Check for subagent invocation. Match both names: older SDK versions

373 // emitted "Task", current versions emit "Agent".

374 for (const block of msg.message?.content ?? []) {

375 if (block.type === "tool_use" && (block.name === "Task" || block.name === "Agent")) {

376 console.log(`Subagent invoked: ${block.input.subagent_type}`);

377 }

378 }

379 

380 // Check if this message is from within a subagent's context

381 if (msg.parent_tool_use_id) {

382 console.log(" (running inside subagent)");

383 }

384 

385 if ("result" in message) {

386 console.log(message.result);

387 }

388 }

389 ```

390</CodeGroup>

391 

392## 恢復子代理

393 

394子代理可以恢復以繼續中斷的地方。恢復的子代理保留其完整的對話歷史,包括所有先前的工具調用、結果和推理。子代理從停止的地方繼續,而不是從頭開始。

395 

396當子代理完成時,Claude 在 Agent 工具結果中接收其代理 ID。要以程式方式恢復子代理:

397 

3981. **捕獲會話 ID**:在第一個查詢期間從消息中提取 `session_id`

3992. **提取代理 ID**:從消息內容中解析 `agentId`

4003. **恢復會話**:在第二個查詢的選項中傳遞 `resume: sessionId`,並在提示詞中包含代理 ID

401 

402<Note>

403 您必須恢復相同的會話以訪問子代理的記錄。默認情況下,每個 `query()` 調用都會啟動一個新會話,因此傳遞 `resume: sessionId` 以在相同會話中繼續。

404 

405 如果您使用的是自訂代理(不是內置代理),您還需要在兩個查詢的 `agents` 參數中傳遞相同的代理定義。

406</Note>

407 

408下面的示例演示了此流程:第一個查詢運行子代理並捕獲會話 ID 和代理 ID,然後第二個查詢恢復會話以提出需要來自第一個分析的上下文的後續問題。

409 

410<CodeGroup>

411 ```typescript TypeScript theme={null}

412 import { query, type SDKMessage } from "@anthropic-ai/claude-agent-sdk";

413 

414 // Helper to extract agentId from message content

415 // Stringify to avoid traversing different block types (TextBlock, ToolResultBlock, etc.)

416 function extractAgentId(message: SDKMessage): string | undefined {

417 if (!("message" in message)) return undefined;

418 // Stringify the content so we can search it without traversing nested blocks

419 const content = JSON.stringify(message.message.content);

420 const match = content.match(/agentId:\s*([a-f0-9-]+)/);

421 return match?.[1];

422 }

423 

424 let agentId: string | undefined;

425 let sessionId: string | undefined;

426 

427 // First invocation - use the Explore agent to find API endpoints

428 for await (const message of query({

429 prompt: "Use the Explore agent to find all API endpoints in this codebase",

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

431 })) {

432 // Capture session_id from ResultMessage (needed to resume this session)

433 if ("session_id" in message) sessionId = message.session_id;

434 // Search message content for the agentId (appears in Agent tool results)

435 const extractedId = extractAgentId(message);

436 if (extractedId) agentId = extractedId;

437 // Print the final result

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

439 }

440 

441 // Second invocation - resume and ask follow-up

442 if (agentId && sessionId) {

443 for await (const message of query({

444 prompt: `Resume agent ${agentId} and list the top 3 most complex endpoints`,

445 options: { allowedTools: ["Read", "Grep", "Glob", "Agent"], resume: sessionId }

446 })) {

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

448 }

449 }

450 ```

451 

452 ```python Python theme={null}

453 import asyncio

454 import json

455 import re

456 from claude_agent_sdk import query, ClaudeAgentOptions

457 

458 

459 def extract_agent_id(text: str) -> str | None:

460 """Extract agentId from Agent tool result text."""

461 match = re.search(r"agentId:\s*([a-f0-9-]+)", text)

462 return match.group(1) if match else None

463 

464 

465 async def main():

466 agent_id = None

467 session_id = None

468 

469 # First invocation - use the Explore agent to find API endpoints

470 async for message in query(

471 prompt="Use the Explore agent to find all API endpoints in this codebase",

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

473 ):

474 # Capture session_id from ResultMessage (needed to resume this session)

475 if hasattr(message, "session_id"):

476 session_id = message.session_id

477 # Search message content for the agentId (appears in Agent tool results)

478 if hasattr(message, "content"):

479 # Stringify the content so we can search it without traversing nested blocks

480 content_str = json.dumps(message.content, default=str)

481 extracted = extract_agent_id(content_str)

482 if extracted:

483 agent_id = extracted

484 # Print the final result

485 if hasattr(message, "result"):

486 print(message.result)

487 

488 # Second invocation - resume and ask follow-up

489 if agent_id and session_id:

490 async for message in query(

491 prompt=f"Resume agent {agent_id} and list the top 3 most complex endpoints",

492 options=ClaudeAgentOptions(

493 allowed_tools=["Read", "Grep", "Glob", "Agent"], resume=session_id

494 ),

495 ):

496 if hasattr(message, "result"):

497 print(message.result)

498 

499 

500 asyncio.run(main())

501 ```

502</CodeGroup>

503 

504子代理記錄獨立於主對話而持續存在:

505 

506* **主對話壓縮**:當主對話壓縮時,子代理記錄不受影響。它們存儲在單獨的檔案中。

507* **會話持久性**:子代理記錄在其會話內持續存在。您可以通過恢復相同會話在重新啟動 Claude Code 後恢復子代理。

508* **自動清理**:記錄根據 `cleanupPeriodDays` 設置進行清理(預設:30 天)。

509 

510## 工具限制

511 

512子代理可以通過 `tools` 欄位具有受限的工具訪問:

513 

514* **省略欄位**:代理繼承所有可用工具(預設)

515* **指定工具**:代理只能使用列出的工具

516 

517此示例創建一個唯讀分析代理,可以檢查代碼但無法修改檔案或運行命令。

518 

519<CodeGroup>

520 ```python Python theme={null}

521 import asyncio

522 from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

523 

524 

525 async def main():

526 async for message in query(

527 prompt="Analyze the architecture of this codebase",

528 options=ClaudeAgentOptions(

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

530 agents={

531 "code-analyzer": AgentDefinition(

532 description="Static code analysis and architecture review",

533 prompt="""You are a code architecture analyst. Analyze code structure,

534 identify patterns, and suggest improvements without making changes.""",

535 # Read-only tools: no Edit, Write, or Bash access

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

537 )

538 },

539 ),

540 ):

541 if hasattr(message, "result"):

542 print(message.result)

543 

544 

545 asyncio.run(main())

546 ```

547 

548 ```typescript TypeScript theme={null}

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

550 

551 for await (const message of query({

552 prompt: "Analyze the architecture of this codebase",

553 options: {

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

555 agents: {

556 "code-analyzer": {

557 description: "Static code analysis and architecture review",

558 prompt: `You are a code architecture analyst. Analyze code structure,

559 identify patterns, and suggest improvements without making changes.`,

560 // Read-only tools: no Edit, Write, or Bash access

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

562 }

563 }

564 }

565 })) {

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

567 }

568 ```

569</CodeGroup>

570 

571### 常見工具組合

572 

573| 使用案例 | 工具 | 描述 |

574| :--- | :---------------------------------- | :------------------------ |

575| 唯讀分析 | `Read`、`Grep`、`Glob` | 可以檢查代碼但不能修改或執行 |

576| 測試執行 | `Bash`、`Read`、`Grep` | 可以運行命令並分析輸出 |

577| 代碼修改 | `Read`、`Edit`、`Write`、`Grep`、`Glob` | 完整的讀/寫訪問,無需命令執行 |

578| 完全訪問 | 所有工具 | 從父代理繼承所有工具(省略 `tools` 欄位) |

579 

580## 故障排除

581 

582### Claude 不委派給子代理

583 

584如果 Claude 直接完成任務而不是委派給您的子代理:

585 

5861. **包含 Agent 工具**:子代理通過 Agent 工具調用,因此它必須在 `allowedTools` 中

5872. **使用明確提示**:在提示詞中按名稱提及子代理(例如,「使用代碼審查員代理來...」)

5883. **編寫清晰的描述**:準確解釋何時應使用子代理,以便 Claude 可以適當地匹配任務

589 

590### 基於檔案系統的代理未加載

591 

592在 `.claude/agents/` 中定義的代理僅在啟動時加載。如果在 Claude Code 運行時創建新的代理檔案,請重新啟動會話以加載它。

593 

594### Windows:長提示詞失敗

595 

596在 Windows 上,具有非常長提示詞的子代理可能因命令行長度限制(8191 個字符)而失敗。保持提示詞簡潔或使用基於檔案系統的代理來處理複雜指令。

597 

598## 相關文檔

599 

600* [Claude Code 子代理](/zh-TW/sub-agents):包括基於檔案系統定義的全面子代理文檔

601* [SDK 概述](/zh-TW/agent-sdk/overview):Claude Agent SDK 入門

Details

358| `sessionStore` | [`SessionStore`](/zh-TW/agent-sdk/session-storage#the-sessionstore-interface) | `undefined` | 將會話記錄鏡像到外部後端,以便任何主機都可以恢復它們。見 [將會話持久化到外部存儲](/zh-TW/agent-sdk/session-storage) |358| `sessionStore` | [`SessionStore`](/zh-TW/agent-sdk/session-storage#the-sessionstore-interface) | `undefined` | 將會話記錄鏡像到外部後端,以便任何主機都可以恢復它們。見 [將會話持久化到外部存儲](/zh-TW/agent-sdk/session-storage) |

359| `settings` | `string \| Settings` | `undefined` | 內聯 [設置](/zh-TW/settings) 對象或設置文件的路徑。填充 [優先級順序](/zh-TW/settings#settings-precedence) 中的標誌設置層。使用 [`applyFlagSettings()`](#applyflagsettings) 在運行時更改 |359| `settings` | `string \| Settings` | `undefined` | 內聯 [設置](/zh-TW/settings) 對象或設置文件的路徑。填充 [優先級順序](/zh-TW/settings#settings-precedence) 中的標誌設置層。使用 [`applyFlagSettings()`](#applyflagsettings) 在運行時更改 |

360| `settingSources` | [`SettingSource`](#settingsource)`[]` | CLI 默認值(所有源) | 控制加載哪些文件系統設置。傳遞 `[]` 以禁用用戶、項目和本地設置。無論如何都會加載託管策略設置。見 [使用 Claude Code 功能](/zh-TW/agent-sdk/claude-code-features#what-settingsources-does-not-control) |360| `settingSources` | [`SettingSource`](#settingsource)`[]` | CLI 默認值(所有源) | 控制加載哪些文件系統設置。傳遞 `[]` 以禁用用戶、項目和本地設置。無論如何都會加載託管策略設置。見 [使用 Claude Code 功能](/zh-TW/agent-sdk/claude-code-features#what-settingsources-does-not-control) |

361| `skills` | `string[] \| 'all'` | `undefined` | 會話可用的技能。傳遞 `'all'` 以啟用每個發現的技能,或傳遞技能名稱列表。設置後,SDK 會自動啟用 Skill 工具,無需在 `allowedTools` 中列出。見 [Skills](/zh-TW/agent-sdk/skills) |

361| `spawnClaudeCodeProcess` | `(options: SpawnOptions) => SpawnedProcess` | `undefined` | 用於生成 Claude Code 進程的自定義函數。用於在 VM、容器或遠程環境中運行 Claude Code |362| `spawnClaudeCodeProcess` | `(options: SpawnOptions) => SpawnedProcess` | `undefined` | 用於生成 Claude Code 進程的自定義函數。用於在 VM、容器或遠程環境中運行 Claude Code |

362| `stderr` | `(data: string) => void` | `undefined` | stderr 輸出的回調 |363| `stderr` | `(data: string) => void` | `undefined` | stderr 輸出的回調 |

363| `strictMcpConfig` | `boolean` | `false` | 強制執行嚴格的 MCP 驗證 |364| `strictMcpConfig` | `boolean` | `false` | 強制執行嚴格的 MCP 驗證 |


530| 字段 | 必需 | 描述 |531| 字段 | 必需 | 描述 |

531| :------------------------------------ | :- | :---------------------------------------------------------------------------------------- |532| :------------------------------------ | :- | :---------------------------------------------------------------------------------------- |

532| `description` | 是 | 何時使用此代理的自然語言描述 |533| `description` | 是 | 何時使用此代理的自然語言描述 |

533| `tools` | 否 | 允許的工具名稱數組。如果省略,從父代理繼承所有工具 |534| `tools` | 否 | 允許的工具名稱數組。如果省略,從父代理繼承所有工具。要將 Skills 預加載到代理的上下文中,請使用 `skills` 字段而不是在此處列出 `'Skill'` |

534| `disallowedTools` | 否 | 要為此代理明確禁止的工具名稱數組 |535| `disallowedTools` | 否 | 要為此代理明確禁止的工具名稱數組 |

535| `prompt` | 是 | 代理的系統提示 |536| `prompt` | 是 | 代理的系統提示 |

536| `model` | 否 | 此代理的模型覆蓋。接受別名如 `'sonnet'`、`'opus'`、`'haiku'`、`'inherit'` 或完整模型 ID。如果省略或 `'inherit'`,使用主模型 |537| `model` | 否 | 此代理的模型覆蓋。接受別名如 `'sonnet'`、`'opus'`、`'haiku'`、`'inherit'` 或完整模型 ID。如果省略或 `'inherit'`,使用主模型 |


1176 transcript_path: string;1177 transcript_path: string;

1177 cwd: string;1178 cwd: string;

1178 permission_mode?: string;1179 permission_mode?: string;

1180 effort?: { level: string };

1179 agent_id?: string;1181 agent_id?: string;

1180 agent_type?: string;1182 agent_type?: string;

1181};1183};

Details

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt2> 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.3> Use this file to discover all available pages before exploring further.

4 4 

5# TypeScript SDK V2 介面預覽5# TypeScript SDK V2 會話 API已棄用

6 6 

7> 簡化的 V2 TypeScript Agent SDK 預覽,具有用於多輪對話的基於會話的 send/stream 模式。7> 已棄用的 V2 TypeScript Agent SDK 會話 API 參考,具有用於多輪對話的基於會話的 send/stream 模式。

8 8 

9<Warning>9<Warning>

10 V2 介面是一個**不穩定的預覽版本**。API 可能會根據反饋進行更改然後才能變成穩定版本某些功能(如會話分叉)僅在 [V1 SDK](/zh-TW/agent-sdk/typescript) 中可用10 V2 會話 API 函數 `unstable_v2_createSession`、`unstable_v2_resumeSession` 和 `unstable_v2_prompt` 已棄用將在未來版本中移除請改用 [V1 `query()` API](/zh-TW/agent-sdk/typescript)。

11</Warning>11</Warning>

12 12 

13V2 Claude Agent TypeScript SDK 消除了對非同步生成器和 yield 協調的需求。這使多輪對話變得更簡單,而不是在各輪之間管理生成器狀態,每一輪都是一個單獨的 `send()`/`stream()` 週期。API 表面縮減為三個概念:13V2 是一個實驗性會話 API,消除了對非同步生成器和 yield 協調的需求。與其在各輪之間管理生成器狀態,每一輪都是一個單獨的 `send()`/`stream()` 週期。API 表面縮減為三個概念:

14 14 

15* `createSession()` / `resumeSession()`:開始或繼續對話15* `createSession()` / `resumeSession()`:開始或繼續對話

16* `session.send()`:發送訊息16* `session.send()`:發送訊息


380 380 

381## 功能可用性381## 功能可用性

382 382 

383並非所有 V1 功能在 V2 中都可用。以下功能需要使用 [V1 SDK](/zh-TW/agent-sdk/typescript):383V2 會話 API 不支援每個 V1 功能。以下功能需要使用 [V1 SDK](/zh-TW/agent-sdk/typescript):

384 384 

385* 會話分叉(`forkSession` 選項)385* 會話分叉(`forkSession` 選項)

386* 某些進階串流輸入模式386* 某些進階串流輸入模式

387 387 

388## 反饋

389 

390在 V2 介面變成穩定版本之前分享您的反饋。通過 [GitHub Issues](https://github.com/anthropics/claude-code/issues) 報告問題和建議。

391 

392## 另請參閱388## 另請參閱

393 389 

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

agent-teams.md +1 −1

Details

420探索並行工作和委派的相關方法:420探索並行工作和委派的相關方法:

421 421 

422* **輕量級委派**:[subagents](/zh-TW/sub-agents) 在您的工作階段內為研究或驗證生成幫助代理,更適合不需要代理間協調的任務422* **輕量級委派**:[subagents](/zh-TW/sub-agents) 在您的工作階段內為研究或驗證生成幫助代理,更適合不需要代理間協調的任務

423* **手動並行工作階段**:[Git worktrees](/zh-TW/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees) 讓您自己運行多個 Claude Code 工作階段,無需自動化團隊協調423* **手動並行工作階段**:[Git worktrees](/zh-TW/worktrees) 讓您自己運行多個 Claude Code 工作階段,無需自動化團隊協調

424* **比較方法**:請參閱 [subagent vs agent team](/zh-TW/features-overview#compare-similar-features) 比較以了解並排細分424* **比較方法**:請參閱 [subagent vs agent team](/zh-TW/features-overview#compare-similar-features) 比較以了解並排細分

amazon-bedrock.md +1 −111

Details

76 </div>;76 </div>;

77};77};

78 78 

79export const Experiment = ({flag, treatment, children}) => {79<ContactSalesCard surface="bedrock" />

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 80 

191## 先決條件81## 先決條件

192 82 

Details

84| `--permission-mode` | 以指定的 [permission mode](/zh-TW/permission-modes) 開始。接受 `default`、`acceptEdits`、`plan`、`auto`、`dontAsk` 或 `bypassPermissions`。覆蓋設定檔案中的 `defaultMode` | `claude --permission-mode plan` |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"` |85| `--permission-prompt-tool` | 指定 MCP 工具以在非互動模式下處理權限提示 | `claude -p --permission-prompt-tool mcp_auth_tool "query"` |

86| `--plugin-dir` | 為此工作階段僅從目錄或 `.zip` 封存載入 plugin。每個旗標採用一個路徑。重複旗標以使用多個 plugins:`--plugin-dir A --plugin-dir B.zip` | `claude --plugin-dir ./my-plugin` |86| `--plugin-dir` | 為此工作階段僅從目錄或 `.zip` 封存載入 plugin。每個旗標採用一個路徑。重複旗標以使用多個 plugins:`--plugin-dir A --plugin-dir B.zip` | `claude --plugin-dir ./my-plugin` |

87| `--plugin-url` | 為此工作階段僅從 URL 擷取 plugin `.zip` 封存。每個旗標採用一個 URL。重複旗標以使用多個 plugins | `claude --plugin-url https://example.com/plugin.zip` |87| `--plugin-url` | 為此工作階段僅從 URL 擷取 plugin `.zip` 封存。重複旗標以使用多個 plugins,或在單一引用值中傳遞以空格分隔的 URL | `claude --plugin-url https://example.com/plugin.zip` |

88| `--print`, `-p` | 列印回應而不進入互動模式(請參閱 [Agent SDK 文件](/zh-TW/agent-sdk/overview) 以了解程式化使用詳細資訊) | `claude -p "query"` |88| `--print`, `-p` | 列印回應而不進入互動模式(請參閱 [Agent SDK 文件](/zh-TW/agent-sdk/overview) 以了解程式化使用詳細資訊) | `claude -p "query"` |

89| `--remote` | 在 claude.ai 上建立新的 [web session](/zh-TW/claude-code-on-the-web),並提供工作描述 | `claude --remote "Fix the login bug"` |89| `--remote` | 在 claude.ai 上建立新的 [web session](/zh-TW/claude-code-on-the-web),並提供工作描述 | `claude --remote "Fix the login bug"` |

90| `--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`, `--rc` | 啟動互動式工作階段,並啟用 [Remote Control](/zh-TW/remote-control#start-a-remote-control-session),以便您也可以從 claude.ai 或 Claude 應用程式控制它。可選擇傳遞工作階段的名稱 | `claude --remote-control "My Project"` |


103| `--tools` | 限制 Claude 可以使用的內建工具。使用 `""` 停用全部,`"default"` 為全部,或工具名稱如 `"Bash,Edit,Read"` | `claude --tools "Bash,Edit,Read"` |103| `--tools` | 限制 Claude 可以使用的內建工具。使用 `""` 停用全部,`"default"` 為全部,或工具名稱如 `"Bash,Edit,Read"` | `claude --tools "Bash,Edit,Read"` |

104| `--verbose` | 啟用詳細記錄,顯示完整的逐轉輸出。覆蓋此工作階段的 [`viewMode`](/zh-TW/settings#available-settings) 設定 | `claude --verbose` |104| `--verbose` | 啟用詳細記錄,顯示完整的逐轉輸出。覆蓋此工作階段的 [`viewMode`](/zh-TW/settings#available-settings) 設定 | `claude --verbose` |

105| `--version`, `-v` | 輸出版本號 | `claude -v` |105| `--version`, `-v` | 輸出版本號 | `claude -v` |

106| `--worktree`, `-w` | 在隔離的 [git worktree](/zh-TW/worktrees) 中啟動 Claude,位於 `<repo>/.claude/worktrees/<name>`。如果未提供名稱,則會自動產生一個 | `claude -w feature-auth` |106| `--worktree`, `-w` | 在隔離的 [git worktree](/zh-TW/worktrees) 中啟動 Claude,位於 `<repo>/.claude/worktrees/<name>`。如果未提供名稱,則會自動產生一個。傳遞 `#<number>` 或 GitHub 提取請求 URL 以從 `origin` 擷取該 PR 並從它分支 worktree | `claude -w feature-auth` |

107 107 

108### 系統提示旗標108### 系統提示旗標

109 109 

commands.md +21 −3

Details

12 12 

13命令只有在您的訊息開始時才會被識別。命令名稱後面的文字會作為引數傳遞給它。13命令只有在您的訊息開始時才會被識別。命令名稱後面的文字會作為引數傳遞給它。

14 14 

15下表列出了 Claude Code 中包含的所有命令。標記為 **[Skill](/zh-TW/skills#bundled-skills)** 的項目是捆綁的 skills。它們使用與您自己編寫的 skills 相同的機制:提示交給 Claude,Claude 也可以在相關時自動調用。其他所有項目都是內建命令,其行為被編碼到 CLI 中。若要添加您自己的命令,請參閱 [skills](/zh-TW/skills)。15## 典型工作流程中的命令

16 

17大多數命令在工作階段的特定時刻很有用,從設定專案到推送變更。

18 

19**存放庫中的首次工作階段。** 執行 `/init` 以產生啟動程式 `CLAUDE.md`,然後執行 `/memory` 以精煉它。使用 `/mcp` 和 `/agents` 以設定專案需要的任何伺服器或子代理,並使用 `/permissions` 以設定您想要的批准規則。

20 

21**在工作期間。** `/plan` 在大型變更前切換到 Plan Mode。`/model` 和 `/effort` 調整您花費的推理量。當對話變得冗長時,`/context` 顯示視窗的去向,`/compact` 將其總結下來;使用 `/btw` 進行快速旁註,不應該膨脹歷史記錄。

22 

23**在您推送前。** `/diff` 顯示變更的內容,`/simplify` 審閱最近的檔案並應用品質和效率修復,`/review` 或 `/security-review` 進行更深入的唯讀檢查。

16 24 

17並非每個命令都對每個使用者顯示。可用性取決於您的平台、方案和環境例如,`/desktop` 僅在 macOSWindows 上顯示,`/upgrade` 僅在 Pro 和 Max 方案上顯示25**在工作階段之間** `/clear` 在保持專案記憶的同時開始新工作的新鮮開始。`/resume` 和 `/branch` 讓您返回或分叉較早的對話。`/teleport` 將網頁工作階段拉入此終端機,`/remote-control` 讓您從另一個裝置繼續此本地工作階段

26 

27**當出現問題時。** `/rewind` 將程式碼和對話倒帶到 checkpoint。`/doctor` 和 `/debug` 診斷安裝和執行時問題,`/feedback` 報告附加工作階段上下文的錯誤。

28 

29## 所有命令

30 

31下表列出了 Claude Code 中包含的所有命令。標記為 **[Skill](/zh-TW/skills#bundled-skills)** 的項目是捆綁的 skills。它們使用與您自己編寫的 skills 相同的機制:提示交給 Claude,Claude 也可以在相關時自動調用。其他所有項目都是內建命令,其行為被編碼到 CLI 中。若要添加您自己的命令,請參閱 [skills](/zh-TW/skills)。

18 32 

19在下表中,`<arg>` 表示必需的引數,`[arg]` 表示可選的引數。33在下表中,`<arg>` 表示必需的引數,`[arg]` 表示可選的引數。

20 34 

35<Note>

36 並非每個命令都對每個使用者顯示。可用性取決於您的平台、方案和環境。例如,`/desktop` 僅在 macOS 和 Windows 上顯示,`/upgrade` 僅在 Pro 和 Max 方案上顯示。

37</Note>

38 

21| 命令 | 用途 |39| 命令 | 用途 |

22| :---------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |40| :---------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

23| `/add-dir <path>` | 為目前工作階段期間的檔案存取添加工作目錄。大多數 `.claude/` 配置[未從添加的目錄發現](/zh-TW/permissions#additional-directories-grant-file-access-not-configuration)。您可以稍後使用 `--continue` 或 `--resume` 從添加的目錄繼續工作階段 |41| `/add-dir <path>` | 為目前工作階段期間的檔案存取添加工作目錄。大多數 `.claude/` 配置[未從添加的目錄發現](/zh-TW/permissions#additional-directories-grant-file-access-not-configuration)。您可以稍後使用 `--continue` 或 `--resume` 從添加的目錄繼續工作階段 |


80| `/review [PR]` | 在您目前的工作階段中本地審閱 pull request。如需更深入的雲端審閱,請參閱 [`/ultrareview`](/zh-TW/ultrareview) |98| `/review [PR]` | 在您目前的工作階段中本地審閱 pull request。如需更深入的雲端審閱,請參閱 [`/ultrareview`](/zh-TW/ultrareview) |

81| `/rewind` | 將對話和/或程式碼倒帶到上一個時刻,或從選定的訊息進行摘要。請參閱 [checkpointing](/zh-TW/checkpointing)。別名:`/checkpoint`、`/undo` |99| `/rewind` | 將對話和/或程式碼倒帶到上一個時刻,或從選定的訊息進行摘要。請參閱 [checkpointing](/zh-TW/checkpointing)。別名:`/checkpoint`、`/undo` |

82| `/sandbox` | 切換 [sandbox 模式](/zh-TW/sandboxing)。僅在支援的平台上可用 |100| `/sandbox` | 切換 [sandbox 模式](/zh-TW/sandboxing)。僅在支援的平台上可用 |

83| `/schedule [description]` | 建立、更新、列出或執行[例行工作](/zh-TW/routines)。Claude 會以對話方式引導您完成設定。別名:`/routines` |101| `/schedule [description]` | 建立、更新、列出或執行[例行工作](/zh-TW/routines),在 Anthropic 管理的雲端基礎設施上執行。Claude 會以對話方式引導您完成設定。別名:`/routines` |

84| `/security-review` | 分析目前分支上的待處理變更以查找安全漏洞。檢查 git 差異並識別注入、驗證問題和資料洩露等風險 |102| `/security-review` | 分析目前分支上的待處理變更以查找安全漏洞。檢查 git 差異並識別注入、驗證問題和資料洩露等風險 |

85| `/setup-bedrock` | 通過互動式精靈配置 [Amazon Bedrock](/zh-TW/amazon-bedrock) 驗證、區域和模型釘選。僅在設定 `CLAUDE_CODE_USE_BEDROCK=1` 時可見。首次 Bedrock 使用者也可以從登入螢幕訪問此精靈 |103| `/setup-bedrock` | 通過互動式精靈配置 [Amazon Bedrock](/zh-TW/amazon-bedrock) 驗證、區域和模型釘選。僅在設定 `CLAUDE_CODE_USE_BEDROCK=1` 時可見。首次 Bedrock 使用者也可以從登入螢幕訪問此精靈 |

86| `/setup-vertex` | 通過互動式精靈配置 [Google Vertex AI](/zh-TW/google-vertex-ai) 驗證、專案、區域和模型釘選。僅在設定 `CLAUDE_CODE_USE_VERTEX=1` 時可見。首次 Vertex AI 使用者也可以從登入螢幕訪問此精靈 |104| `/setup-vertex` | 通過互動式精靈配置 [Google Vertex AI](/zh-TW/google-vertex-ai) 驗證、專案、區域和模型釘選。僅在設定 `CLAUDE_CODE_USE_VERTEX=1` 時可見。首次 Vertex AI 使用者也可以從登入螢幕訪問此精靈 |

desktop.md +17 −0

Details

564 564 

565每個項目都需要 `id`、`name` 和 `sshHost`。`sshPort`、`sshIdentityFile` 和 `startDirectory` 欄位是選用的。使用者也可以將 `sshConfigs` 新增到他們自己的 `~/.claude/settings.json`,這是透過對話框新增的連線的儲存位置。565每個項目都需要 `id`、`name` 和 `sshHost`。`sshPort`、`sshIdentityFile` 和 `startDirectory` 欄位是選用的。使用者也可以將 `sshConfigs` 新增到他們自己的 `~/.claude/settings.json`,這是透過對話框新增的連線的儲存位置。

566 566 

567#### 限制使用者可以連接的 SSH 主機

568 

569管理員可以透過將 `sshHostAllowlist` 新增到[受管設定](/zh-TW/settings#settings-precedence)檔案來限制 Desktop 的 SSH 會話到已核准的主機集合。設定後,使用者只能連接到其解析的主機名稱與其中一個模式相符的主機。將其設定為空陣列以完全停用 SSH 會話。

570 

571以下範例允許連接到 `devboxes.example.com` 下的任何主機以及單一命名的堡壘主機:

572 

573```json theme={null}

574{

575 "sshHostAllowlist": ["*.devboxes.example.com", "bastion.example.com"]

576}

577```

578 

579模式不區分大小寫。`*` 符合任何主機,`*.example.com` 符合 `example.com` 和任何子網域。其他任何內容都是精確符合。檢查會針對透過 `ssh -G` 進行 `~/.ssh/config` 解析後的主機名稱執行,因此允許 `Host` 別名和 `ProxyCommand`/`ProxyJump` 項目,只要解析的 `HostName` 相符即可。

580 

581`sshHostAllowlist` 僅從受管設定讀取;使用者或專案設定中的值會被忽略。只有 Claude Desktop 應用程式遵守此設定;Claude Code CLI 和 IDE 擴充功能不讀取它,它也不限制透過 Bash 工具執行的 `ssh` 命令。它控制 Desktop 應用程式連接的主機,而不是網路出口,因此如果您需要硬邊界,請將其與您組織的網路或零信任控制配對。

582 

567## 企業配置583## 企業配置

568 584 

569Teams 或 Enterprise 計畫上的組織可以透過管理員主控台控制、受管設定檔案和裝置管理原則來管理桌面應用程式行為。585Teams 或 Enterprise 計畫上的組織可以透過管理員主控台控制、受管設定檔案和裝置管理原則來管理桌面應用程式行為。


587| `disableAutoMode` | 設定為 `"disable"` 以防止使用者啟用 [Auto](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode) 模式。從模式選擇器中移除 Auto。也在 `permissions` 下接受。 |603| `disableAutoMode` | 設定為 `"disable"` 以防止使用者啟用 [Auto](/zh-TW/permission-modes#eliminate-prompts-with-auto-mode) 模式。從模式選擇器中移除 Auto。也在 `permissions` 下接受。 |

588| `autoMode` | 自訂 auto 模式分類器在您的組織中信任和阻止的內容。請參閱[配置 auto 模式](/zh-TW/auto-mode-config)。 |604| `autoMode` | 自訂 auto 模式分類器在您的組織中信任和阻止的內容。請參閱[配置 auto 模式](/zh-TW/auto-mode-config)。 |

589| `sshConfigs` | 預先配置[SSH 連線](#pre-configure-ssh-connections-for-your-team),在環境下拉式選單中顯示。使用者無法編輯或刪除受管連線。 |605| `sshConfigs` | 預先配置[SSH 連線](#pre-configure-ssh-connections-for-your-team),在環境下拉式選單中顯示。使用者無法編輯或刪除受管連線。 |

606| `sshHostAllowlist` | 限制 [SSH 會話](#restrict-which-ssh-hosts-users-can-connect-to)連線到已解析主機名稱符合這些模式之一的主機。空陣列會停用 SSH 會話。僅從受管設定讀取。 |

590 607 

591部署到每台機器上磁碟的受管設定檔案適用於 Desktop 會話。透過管理員主控台推送的遠端受管設定目前僅適用於 CLI 和 IDE 會話,因此對於 Desktop 部署,請透過 MDM 分發檔案或使用上面的[管理員主控台控制](#admin-console-controls)。608部署到每台機器上磁碟的受管設定檔案適用於 Desktop 會話。透過管理員主控台推送的遠端受管設定目前僅適用於 CLI 和 IDE 會話,因此對於 Desktop 部署,請透過 MDM 分發檔案或使用上面的[管理員主控台控制](#admin-console-controls)。

592 609 

env-vars.md +4 −2

Details

92| `CLAUDE_CODE_EFFORT_LEVEL` | 為支援的模型設定努力級別。值:`low`、`medium`、`high`、`xhigh`、`max` 或 `auto` 以使用模型預設值。可用級別取決於模型。優先於 `/effort` 和 `effortLevel` 設定。請參閱 [Adjust effort level](/zh-TW/model-config#adjust-effort-level) |92| `CLAUDE_CODE_EFFORT_LEVEL` | 為支援的模型設定努力級別。值:`low`、`medium`、`high`、`xhigh`、`max` 或 `auto` 以使用模型預設值。可用級別取決於模型。優先於 `/effort` 和 `effortLevel` 設定。請參閱 [Adjust effort level](/zh-TW/model-config#adjust-effort-level) |

93| `CLAUDE_CODE_ENABLE_AWAY_SUMMARY` | 覆蓋 [session recap](/zh-TW/interactive-mode#session-recap) 可用性。設定為 `0` 以強制關閉摘要,無論 `/config` 切換如何。設定為 `1` 以在 [`awaySummaryEnabled`](/zh-TW/settings#available-settings) 為 `false` 時強制啟用摘要。優先於設定和 `/config` 切換 |93| `CLAUDE_CODE_ENABLE_AWAY_SUMMARY` | 覆蓋 [session recap](/zh-TW/interactive-mode#session-recap) 可用性。設定為 `0` 以強制關閉摘要,無論 `/config` 切換如何。設定為 `1` 以在 [`awaySummaryEnabled`](/zh-TW/settings#available-settings) 為 `false` 時強制啟用摘要。優先於設定和 `/config` 切換 |

94| `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) 失效 |94| `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) 失效 |

95| `CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING` | 控制工具呼叫輸入是否在 Claude 生成時從 API 串流。關閉此選項時,大型工具輸入(例如長檔案寫入)僅在 Claude 完成生成後才到達,這可能看起來像是掛起。預設為直接 Anthropic API 連線啟用。設定為 `0` 以選擇退出。設定為 `1` 以強制啟用,即使伺服器端預設為關閉 BedrockVertexFoundry [gateway](/zh-TW/llm-gateway) 連線無效 |95| `CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING` | 控制工具呼叫輸入是否在 Claude 生成時從 API 串流。關閉此選項時,大型工具輸入(例如長檔案寫入)僅在 Claude 完成生成後才到達,這可能看起來像是掛起。 Anthropic API 上預設啟用。設定為 `0` 以選擇退出。設定為 `1` 以在透過 `ANTHROPIC_BASE_URL`、`ANTHROPIC_VERTEX_BASE_URL` 或 `ANTHROPIC_BEDROCK_BASE_URL` 路由時強制啟用 BedrockVertex 上,按模型啟用,其中已部署的容器支援它。在 Foundry [gateway](/zh-TW/llm-gateway) 連線上預設關閉 |

96| `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY` | 設定為 `1` 以在 `ANTHROPIC_BASE_URL` 指向 Anthropic 相容閘道(例如 LiteLLM、Kong 或內部代理)時從您的閘道的 `/v1/models` 端點填充 `/model` 選擇器。預設關閉,因為由共享 API 金鑰支援的閘道會以其他方式向每個使用者顯示該金鑰可以存取的每個模型。探索的模型仍由 [`availableModels`](/zh-TW/settings#available-settings) 允許清單篩選 |96| `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY` | 設定為 `1` 以在 `ANTHROPIC_BASE_URL` 指向 Anthropic 相容閘道(例如 LiteLLM、Kong 或內部代理)時從您的閘道的 `/v1/models` 端點填充 `/model` 選擇器。預設關閉,因為由共享 API 金鑰支援的閘道會以其他方式向每個使用者顯示該金鑰可以存取的每個模型。探索的模型仍由 [`availableModels`](/zh-TW/settings#available-settings) 允許清單篩選 |

97| `CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION` | 設定為 `false` 以停用提示建議(`/config` 中的「提示建議」切換)。這些是在 Claude 回應後出現在您的提示輸入中的灰顯預測。請參閱 [Prompt suggestions](/zh-TW/interactive-mode#prompt-suggestions) |97| `CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION` | 設定為 `false` 以停用提示建議(`/config` 中的「提示建議」切換)。這些是在 Claude 回應後出現在您的提示輸入中的灰顯預測。請參閱 [Prompt suggestions](/zh-TW/interactive-mode#prompt-suggestions) |

98| `CLAUDE_CODE_ENABLE_TASKS` | 設定為 `1` 以在非互動式模式(`-p` 旗標)中啟用任務追蹤系統。任務在互動式模式中預設為開啟。請參閱 [Task list](/zh-TW/interactive-mode#task-list) |98| `CLAUDE_CODE_ENABLE_TASKS` | 設定為 `1` 以在非互動式模式(`-p` 旗標)中啟用任務追蹤系統。任務在互動式模式中預設為開啟。請參閱 [Task list](/zh-TW/interactive-mode#task-list) |


152| `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` 會自動設定此項 |152| `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` 會自動設定此項 |

153| `CLAUDE_CODE_SYNC_PLUGIN_INSTALL` | 在非互動式模式(`-p` 旗標)中設定為 `1` 以等待外掛程式安裝完成,然後再進行第一個查詢。沒有此選項,外掛程式會在背景中安裝,可能在第一個回合時不可用。與 `CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS` 結合以限制等待時間 |153| `CLAUDE_CODE_SYNC_PLUGIN_INSTALL` | 在非互動式模式(`-p` 旗標)中設定為 `1` 以等待外掛程式安裝完成,然後再進行第一個查詢。沒有此選項,外掛程式會在背景中安裝,可能在第一個回合時不可用。與 `CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS` 結合以限制等待時間 |

154| `CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS` | 同步外掛程式安裝的逾時(以毫秒為單位)。超過時,Claude Code 會在沒有外掛程式的情況下繼續並記錄錯誤。無預設值:沒有此變數,同步安裝會等待直到完成 |154| `CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS` | 同步外掛程式安裝的逾時(以毫秒為單位)。超過時,Claude Code 會在沒有外掛程式的情況下繼續並記錄錯誤。無預設值:沒有此變數,同步安裝會等待直到完成 |

155| `CLAUDE_CODE_SYNTAX_HIGHLIGHT` | 設定為 `false` 以停用 diff 輸出中的語法醒目提示。當顏色干擾您的終端設定時很有用 |155| `CLAUDE_CODE_SYNTAX_HIGHLIGHT` | 設定為 `false` 以停用 diff 輸出中的語法醒目提示。當顏色干擾您的終端設定時很有用。若要也停用程式碼區塊和檔案預覽中的醒目提示,請使用 [`syntaxHighlightingDisabled`](/zh-TW/settings) 設定 |

156| `CLAUDE_CODE_TASK_LIST_ID` | 跨工作階段共享任務清單。在多個 Claude Code 實例中設定相同的 ID 以協調共享任務清單。請參閱 [Task list](/zh-TW/interactive-mode#task-list) |156| `CLAUDE_CODE_TASK_LIST_ID` | 跨工作階段共享任務清單。在多個 Claude Code 實例中設定相同的 ID 以協調共享任務清單。請參閱 [Task list](/zh-TW/interactive-mode#task-list) |

157| `CLAUDE_CODE_TEAM_NAME` | 此隊友所屬的 agent team 名稱。在 [agent team](/zh-TW/agent-teams) 成員上自動設定 |157| `CLAUDE_CODE_TEAM_NAME` | 此隊友所屬的 agent team 名稱。在 [agent team](/zh-TW/agent-teams) 成員上自動設定 |

158| `CLAUDE_CODE_TMPDIR` | 覆蓋用於內部臨時檔案的臨時目錄。Claude Code 將 `/claude-{uid}/`(Unix)或 `/claude/`(Windows)附加到此路徑。預設值:macOS 上的 `/tmp`、Linux/Windows 上的 `os.tmpdir()` |158| `CLAUDE_CODE_TMPDIR` | 覆蓋用於內部臨時檔案的臨時目錄。Claude Code 將 `/claude-{uid}/`(Unix)或 `/claude/`(Windows)附加到此路徑。預設值:macOS 上的 `/tmp`、Linux/Windows 上的 `os.tmpdir()` |


164| `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) |164| `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) |

165| `CLAUDE_CODE_USE_VERTEX` | 使用 [Vertex](/zh-TW/google-vertex-ai) |165| `CLAUDE_CODE_USE_VERTEX` | 使用 [Vertex](/zh-TW/google-vertex-ai) |

166| `CLAUDE_CONFIG_DIR` | 覆蓋配置目錄(預設值:`~/.claude`)。所有設定、認證、工作階段歷史記錄和外掛程式都儲存在此路徑下。對於並排執行多個帳戶很有用:例如,`alias claude-work='CLAUDE_CONFIG_DIR=~/.claude-work claude'` |166| `CLAUDE_CONFIG_DIR` | 覆蓋配置目錄(預設值:`~/.claude`)。所有設定、認證、工作階段歷史記錄和外掛程式都儲存在此路徑下。對於並排執行多個帳戶很有用:例如,`alias claude-work='CLAUDE_CONFIG_DIR=~/.claude-work claude'` |

167| `CLAUDE_EFFORT` | 在 Bash 工具子程序和 hook 命令中自動設定為該回合的作用中 [effort level](/zh-TW/model-config#adjust-effort-level):`low`、`medium`、`high`、`xhigh` 或 `max`。符合傳遞給 [hooks](/zh-TW/hooks) 的 `effort.level` 欄位。僅在目前模型支援努力參數時設定 |

167| `CLAUDE_ENABLE_BYTE_WATCHDOG` | 設定為 `1` 以強制啟用位元級串流閒置監視程式,或設定為 `0` 以強制停用它。未設定時,監視程式預設對 Anthropic API 連線啟用。位元監視程式會在 `CLAUDE_STREAM_IDLE_TIMEOUT_MS` 設定的持續時間內沒有位元到達線路時中止連線,最少 5 分鐘,獨立於事件級監視程式 |168| `CLAUDE_ENABLE_BYTE_WATCHDOG` | 設定為 `1` 以強制啟用位元級串流閒置監視程式,或設定為 `0` 以強制停用它。未設定時,監視程式預設對 Anthropic API 連線啟用。位元監視程式會在 `CLAUDE_STREAM_IDLE_TIMEOUT_MS` 設定的持續時間內沒有位元到達線路時中止連線,最少 5 分鐘,獨立於事件級監視程式 |

168| `CLAUDE_ENABLE_STREAM_WATCHDOG` | 設定為 `1` 以啟用事件級串流閒置監視程式。預設關閉。對於 Bedrock、Vertex 和 Foundry,這是唯一可用的閒置監視程式。使用 `CLAUDE_STREAM_IDLE_TIMEOUT_MS` 配置逾時 |169| `CLAUDE_ENABLE_STREAM_WATCHDOG` | 設定為 `1` 以啟用事件級串流閒置監視程式。預設關閉。對於 Bedrock、Vertex 和 Foundry,這是唯一可用的閒置監視程式。使用 `CLAUDE_STREAM_IDLE_TIMEOUT_MS` 配置逾時 |

169| `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 動態填充 |170| `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 動態填充 |


205| `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` 停用自適應推理 |206| `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` 停用自適應推理 |

206| `MCP_CLIENT_SECRET` | 需要 [pre-configured credentials](/zh-TW/mcp#use-pre-configured-oauth-credentials) 的 MCP 伺服器的 OAuth 用戶端密碼。在使用 `--client-secret` 新增伺服器時避免互動式提示 |207| `MCP_CLIENT_SECRET` | 需要 [pre-configured credentials](/zh-TW/mcp#use-pre-configured-oauth-credentials) 的 MCP 伺服器的 OAuth 用戶端密碼。在使用 `--client-secret` 新增伺服器時避免互動式提示 |

207| `MCP_CONNECTION_NONBLOCKING` | 在非互動式模式(`-p`)中設定為 `true` 以完全跳過 MCP 連線等待。對於不需要 MCP 工具的指令碼化管道很有用。沒有此變數,第一個查詢會等待最多 5 秒以進行 `--mcp-config` 伺服器連線。配置 [`alwaysLoad: true`](/zh-TW/mcp#exempt-a-server-from-deferral) 的伺服器始終會阻止啟動,無論此變數如何,因為其工具必須在建立第一個提示時存在 |208| `MCP_CONNECTION_NONBLOCKING` | 在非互動式模式(`-p`)中設定為 `true` 以完全跳過 MCP 連線等待。對於不需要 MCP 工具的指令碼化管道很有用。沒有此變數,第一個查詢會等待最多 5 秒以進行 `--mcp-config` 伺服器連線。配置 [`alwaysLoad: true`](/zh-TW/mcp#exempt-a-server-from-deferral) 的伺服器始終會阻止啟動,無論此變數如何,因為其工具必須在建立第一個提示時存在 |

209| `MCP_CONNECT_TIMEOUT_MS` | 第一個查詢在拍攝工具清單快照之前等待 MCP 連線批次的時間(以毫秒為單位)(預設值:5000)。在截止時間時仍待處理的伺服器會在背景中繼續連線,但在下一個查詢之前不會出現。與 `MCP_TIMEOUT` 不同,後者限制個別伺服器的連線嘗試。最相關於發出單一查詢且需要緩慢連線伺服器可見的非互動式工作階段 |

208| `MCP_OAUTH_CALLBACK_PORT` | OAuth 重新導向回呼的固定連接埠,作為在使用 [pre-configured credentials](/zh-TW/mcp#use-pre-configured-oauth-credentials) 新增 MCP 伺服器時 `--callback-port` 的替代方案 |210| `MCP_OAUTH_CALLBACK_PORT` | OAuth 重新導向回呼的固定連接埠,作為在使用 [pre-configured credentials](/zh-TW/mcp#use-pre-configured-oauth-credentials) 新增 MCP 伺服器時 `--callback-port` 的替代方案 |

209| `MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE` | 啟動期間並行連線的遠端 MCP 伺服器(HTTP/SSE)的最大數量(預設值:20) |211| `MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE` | 啟動期間並行連線的遠端 MCP 伺服器(HTTP/SSE)的最大數量(預設值:20) |

210| `MCP_SERVER_CONNECTION_BATCH_SIZE` | 啟動期間並行連線的本機 MCP 伺服器(stdio)的最大數量(預設值:3) |212| `MCP_SERVER_CONNECTION_BATCH_SIZE` | 啟動期間並行連線的本機 MCP 伺服器(stdio)的最大數量(預設值:3) |

Details

249 249 

250 **上下文成本:** 低,直到使用。僅使用者 skills 在調用前成本為零。250 **上下文成本:** 低,直到使用。僅使用者 skills 在調用前成本為零。

251 251 

252 **在 subagents 中:** Skills 在 subagents 中的工作方式不同。不是按需載入,傳遞給 subagent skills 在啟動時完全預載入其上下文。Subagents 不從主會話繼承 skills;您必須明確指定它們252 **在 subagents 中:** Skills 在 subagents 中的工作方式不同。不是按需載入,skills 列表中列出的 skills 在啟動時完全預載入其上下文。Subagents 仍然可以通過 Skill 工具發現和調用未列出的專案、使用者和 plugin skills。

253 253 

254 <Tip>對具有副作用的 skills 使用 `disable-model-invocation: true`。這節省上下文並確保只有您觸發它們。</Tip>254 <Tip>對具有副作用的 skills 使用 `disable-model-invocation: true`。這節省上下文並確保只有您觸發它們。</Tip>

255 </Tab>255 </Tab>

Details

76 </div>;76 </div>;

77};77};

78 78 

79export const Experiment = ({flag, treatment, children}) => {79<ContactSalesCard surface="vertex" />

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 80 

191## 先決條件81## 先決條件

192 82 

hooks.md +7 −8

Details

518除了每個 [hook 事件](#hook-events) 部分中記錄的事件特定欄位外,所有 hook 事件都接收這些欄位作為 JSON。對於命令 hooks,此 JSON 通過 stdin 到達。對於 HTTP hooks,它作為 POST 請求正文到達。518除了每個 [hook 事件](#hook-events) 部分中記錄的事件特定欄位外,所有 hook 事件都接收這些欄位作為 JSON。對於命令 hooks,此 JSON 通過 stdin 到達。對於 HTTP hooks,它作為 POST 請求正文到達。

519 519 

520| 欄位 | 描述 |520| 欄位 | 描述 |

521| :---------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |521| :---------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

522| `session_id` | 目前工作階段識別碼 |522| `session_id` | 目前工作階段識別碼 |

523| `transcript_path` | 對話 JSON 的路徑 |523| `transcript_path` | 對話 JSON 的路徑 |

524| `cwd` | 叫用 hook 時的目前工作目錄 |524| `cwd` | 叫用 hook 時的目前工作目錄 |

525| `permission_mode` | 目前 [權限模式](/zh-TW/permissions#permission-modes):`"default"`、`"plan"`、`"acceptEdits"`、`"auto"`、`"dontAsk"` 或 `"bypassPermissions"`。並非所有事件都接收此欄位:請參閱下面每個事件的 JSON 範例以檢查 |525| `permission_mode` | 目前 [權限模式](/zh-TW/permissions#permission-modes):`"default"`、`"plan"`、`"acceptEdits"`、`"auto"`、`"dontAsk"` 或 `"bypassPermissions"`。並非所有事件都接收此欄位:請參閱下面每個事件的 JSON 範例以檢查 |

526| `effort` | 物件,其 `level` 欄位保存該回合的活躍 [努力等級](/zh-TW/model-config#adjust-effort-level):`"low"`、`"medium"`、`"high"`、`"xhigh"` 或 `"max"`。如果請求的努力等級超過目前模型支援的等級,這是模型實際使用的降級等級,而不是您請求的等級。該物件與 [狀態行](/zh-TW/statusline#available-data) `effort` 欄位相符。存在於在工具使用上下文中觸發的事件,例如 `PreToolUse`、`PostToolUse`、`Stop` 和 `SubagentStop`,當目前模型支援努力參數時。該等級也可作為 `$CLAUDE_EFFORT` 環境變數提供給 hook 命令和 Bash 工具。 |

526| `hook_event_name` | 觸發的事件名稱 |527| `hook_event_name` | 觸發的事件名稱 |

527 528 

528使用 `--agent` 執行或在 subagent 內執行時,包括兩個額外欄位:529使用 `--agent` 執行或在 subagent 內執行時,包括兩個額外欄位:


1225 1226 

1226如果恢復時延遲的工具不再可用,程序以 `stop_reason: "tool_deferred_unavailable"` 和 `is_error: true` 退出,在 hook 觸發之前。這發生在提供工具的 MCP 伺服器對於恢復的工作階段未連接時。`deferred_tool_use` 有效負載仍然包括在內,以便您可以識別哪個工具遺失。1227如果恢復時延遲的工具不再可用,程序以 `stop_reason: "tool_deferred_unavailable"` 和 `is_error: true` 退出,在 hook 觸發之前。這發生在提供工具的 MCP 伺服器對於恢復的工作階段未連接時。`deferred_tool_use` 有效負載仍然包括在內,以便您可以識別哪個工具遺失。

1227 1228 

1228<Warning>1229<Note>

1229 `--resume` 不會從先前的工作階段恢復權限模式。在恢復時傳遞與工具被延遲時活動的相同 `--permission-mode` 標誌Claude Code 在模式不同時記錄警告1230 `--resume` 恢復工具被延遲時活動的權限模式,因此您不需要再次傳遞 `--permission-mode`。例外是 `plan` 和 `bypassPermissions`,它們永遠不會被帶過在恢復時明確傳遞 `--permission-mode` 會覆蓋恢復的值

1230</Warning>1231</Note>

1231 1232 

1232### PermissionRequest1233### PermissionRequest

1233 1234 


1493}1494}

1494```1495```

1495 1496 

1496<Note>1497注入的 `additionalContext` 被持久化到工作階段成績單。在 `--continue` 或 `--resume` 時,保存的文字從磁碟重新播放,hook 不會針對過去的轉向重新執行。優先選擇靜態上下文,例如慣例或檔案類型指導,而不是動態值,例如時間戳或目前提交 SHA,因為這些在恢復時變得陳舊。

1497 注入的 `additionalContext` 被持久化到工作階段成績單。在 `--continue` 或 `--resume` 時,保存的文字從磁碟重新播放,hook 不會針對過去的轉向重新執行。優先選擇靜態上下文,例如慣例或檔案類型指導,而不是動態值,例如時間戳或目前提交 SHA,因為這些在恢復時變得陳舊。

1498 1498 

1499 將上下文框架為事實資訊而不是命令式系統指令。寫成帶外系統命令的文字可以觸發 Claude 的提示注入防禦,這會將注入呈現給使用者而不是對其採取行動。1499將上下文框架為事實資訊而不是命令式系統指令。寫成帶外系統命令的文字可以觸發 Claude 的提示注入防禦,這會將注入呈現給使用者而不是對其採取行動。

1500</Note>

1501 1500 

1502返回 `decision: "block"` 或 `continue: false` 在下一個模型呼叫之前停止代理迴圈。1501返回 `decision: "block"` 或 `continue: false` 在下一個模型呼叫之前停止代理迴圈。

1503 1502 

memory.md +10 −0

Details

132對 `src/billing/` 下的變更使用 plan mode。132對 `src/billing/` 下的變更使用 plan mode。

133```133```

134 134 

135符號連結也可以運作,如果您不需要新增 Claude 特定的內容:

136 

137```bash theme={null}

138ln -s AGENTS.md CLAUDE.md

139```

140 

141在 Windows 上,建立符號連結需要系統管理員權限或開發人員模式,因此請改用 `@AGENTS.md` 匯入。

142 

143在已經有 `AGENTS.md` 的儲存庫中執行 [`/init`](/zh-TW/commands) 會讀取它並將相關部分合併到產生的 `CLAUDE.md` 中。它也會讀取其他工具配置,如 `.cursorrules` 和 `.windsurfrules`。

144 

135### CLAUDE.md 檔案如何載入145### CLAUDE.md 檔案如何載入

136 146 

137Claude Code 透過從您目前的工作目錄向上走目錄樹來讀取 CLAUDE.md 檔案,檢查沿途的每個目錄中是否有 `CLAUDE.md` 和 `CLAUDE.local.md` 檔案。這意味著如果您在 `foo/bar/` 中執行 Claude Code,它會從 `foo/bar/CLAUDE.md`、`foo/CLAUDE.md` 和沿途的任何 `CLAUDE.local.md` 檔案載入指令。147Claude Code 透過從您目前的工作目錄向上走目錄樹來讀取 CLAUDE.md 檔案,檢查沿途的每個目錄中是否有 `CLAUDE.md` 和 `CLAUDE.local.md` 檔案。這意味著如果您在 `foo/bar/` 中執行 Claude Code,它會從 `foo/bar/CLAUDE.md`、`foo/CLAUDE.md` 和沿途的任何 `CLAUDE.local.md` 檔案載入指令。

Details

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt2> 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.3> Use this file to discover all available pages before exploring further.

4 4 

5# Claude Code on Microsoft Foundry5# Microsoft Foundry 上的 Claude Code

6 6 

7> 了解如何透過 Microsoft Foundry 配置 Claude Code,包括設定、配置和故障排除。7> 了解如何透過 Microsoft Foundry 配置 Claude Code,包括設定、配置和故障排除。

8 8 


76 </div>;76 </div>;

77};77};

78 78 

79export const Experiment = ({flag, treatment, children}) => {79<ContactSalesCard surface="foundry" />

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 80 

191## 先決條件81## 先決條件

192 82 

model-config.md +4 −0

Details

17 * Foundry:部署名稱17 * Foundry:部署名稱

18 * Vertex:版本名稱18 * Vertex:版本名稱

19 19 

20<Note>

21 `ANTHROPIC_BASE_URL` 改變請求的發送位置,而不是哪個模型回答它們。若要透過 LLM 閘道路由 Claude,請參閱 [LLM 閘道配置](/zh-TW/llm-gateway)。

22</Note>

23 

20### 模型別名24### 模型別名

21 25 

22模型別名提供了一種便捷的方式來選擇模型設定,無需記住確切的版本號:26模型別名提供了一種便捷的方式來選擇模型設定,無需記住確切的版本號:

overview.md +1 −635

Details

6 6 

7> Claude Code 是一個代理編碼工具,可以讀取您的程式碼庫、編輯檔案、執行命令,並與您的開發工具整合。可在您的終端機、IDE、桌面應用程式和瀏覽器中使用。7> Claude Code 是一個代理編碼工具,可以讀取您的程式碼庫、編輯檔案、執行命令,並與您的開發工具整合。可在您的終端機、IDE、桌面應用程式和瀏覽器中使用。

8 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 驅動的編碼助手,可幫助您建立功能、修復錯誤和自動化開發任務。它理解您的整個程式碼庫,並可以跨多個檔案和工具工作以完成任務。9Claude Code 是一個由 AI 驅動的編碼助手,可幫助您建立功能、修復錯誤和自動化開發任務。它理解您的整個程式碼庫,並可以跨多個檔案和工具工作以完成任務。

640 10 

641<div data-gb-slot="overview-install-configurator">

642 <Experiment flag="overview-install-configurator" treatment={<InstallConfigurator />} />

643</div>

644 

645## 開始使用11## 開始使用

646 12 

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)。13選擇您的環境以開始使用。大多數介面需要 [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)。


798 <Accordion title="使用說明、skills 和 hooks 進行自訂" icon="sliders">164 <Accordion title="使用說明、skills 和 hooks 進行自訂" icon="sliders">

799 [`CLAUDE.md`](/zh-TW/memory) 是您新增到專案根目錄的 markdown 檔案,Claude Code 在每個工作階段開始時都會讀取。使用它來設定編碼標準、架構決策、首選程式庫和審查檢查清單。Claude 也會在工作時建立[自動記憶](/zh-TW/memory#auto-memory),儲存學習內容,例如建置命令和除錯見解,跨工作階段而無需您編寫任何內容。165 [`CLAUDE.md`](/zh-TW/memory) 是您新增到專案根目錄的 markdown 檔案,Claude Code 在每個工作階段開始時都會讀取。使用它來設定編碼標準、架構決策、首選程式庫和審查檢查清單。Claude 也會在工作時建立[自動記憶](/zh-TW/memory#auto-memory),儲存學習內容,例如建置命令和除錯見解,跨工作階段而無需您編寫任何內容。

800 166 

801 建立[自訂命令](/zh-TW/skills)以封裝您的團隊可以共享的可重複工作流程,例如 `/review-pr` 或 `/deploy-staging`。167 建立[skills](/zh-TW/skills) 以封裝您的團隊可以共享的可重複工作流程,例如 `/review-pr` 或 `/deploy-staging`。

802 168 

803 [Hooks](/zh-TW/hooks) 可讓您在 Claude Code 動作之前或之後執行 shell 命令,例如在每次檔案編輯後自動格式化或在提交前執行 lint。169 [Hooks](/zh-TW/hooks) 可讓您在 Claude Code 動作之前或之後執行 shell 命令,例如在每次檔案編輯後自動格式化或在提交前執行 lint。

804 </Accordion>170 </Accordion>

plugins.md +9 −1

Details

317 317 

318若要測試已打包為 `.zip` 檔案並託管在 URL 上的 plugin(例如 CI 建置成品),請改用 `--plugin-url`。Claude Code 在啟動時擷取檔案並僅為該工作階段載入它。如果擷取失敗或檔案無效,Claude Code 會報告 plugin 載入錯誤並在沒有它的情況下啟動。與任何 plugin 來源相同的[信任考量](/zh-TW/discover-plugins#security)適用:只將此旗標指向您控制或信任的檔案。318若要測試已打包為 `.zip` 檔案並託管在 URL 上的 plugin(例如 CI 建置成品),請改用 `--plugin-url`。Claude Code 在啟動時擷取檔案並僅為該工作階段載入它。如果擷取失敗或檔案無效,Claude Code 會報告 plugin 載入錯誤並在沒有它的情況下啟動。與任何 plugin 來源相同的[信任考量](/zh-TW/discover-plugins#security)適用:只將此旗標指向您控制或信任的檔案。

319 319 

320若要載入多個 plugins,請為每個 URL 重複該旗標:

321 

322```bash theme={null}

323claude --plugin-url https://example.com/my-plugin.zip --plugin-url https://example.com/other.zip

324```

325 

326或將以空格分隔的 URL 作為一個引用的引數傳遞:

327 

320```bash theme={null}328```bash theme={null}

321claude --plugin-url https://example.com/my-plugin.zip329claude --plugin-url "https://example.com/my-plugin.zip https://example.com/other.zip"

322```330```

323 331 

324### 偵錯 plugin 問題332### 偵錯 plugin 問題

quickstart.md +3 −636

Details

6 6 

7> 歡迎使用 Claude Code!7> 歡迎使用 Claude Code!

8 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 進行常見的開發任務。9本快速入門指南將在幾分鐘內讓您使用 AI 驅動的編碼協助。完成後,您將了解如何使用 Claude Code 進行常見的開發任務。

640 10 

641<Experiment flag="quickstart-install-configurator" treatment={<InstallConfigurator />} />

642 

643## 開始前11## 開始前

644 12 

645確保您擁有:13確保您擁有:


647* 已開啟的終端或命令提示字元15* 已開啟的終端或命令提示字元

648 * 如果您從未使用過終端,請查看[終端指南](/zh-TW/terminal-guide)16 * 如果您從未使用過終端,請查看[終端指南](/zh-TW/terminal-guide)

649* 一個可以使用的程式碼專案17* 一個可以使用的程式碼專案

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)存取18* 一個 [Claude 訂閱](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=quickstart_prereq)(Pro、Max、Team 或 Enterprise)、[Claude Console](https://console.anthropic.com/) 帳戶,或透過[支援的雲端提供商](/zh-TW/third-party-integrations)存取

651 19 

652<Note>20<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)。21 本指南涵蓋終端 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)。


727 95 

728您可以使用以下任何帳戶類型登入:96您可以使用以下任何帳戶類型登入:

729 97 

730* [Claude Pro、Max、Teams 或 Enterprise](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=quickstart_login)(推薦)98* [Claude Pro、Max、Team 或 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」工作區以進行集中成本追蹤。99* [Claude Console](https://console.anthropic.com/)(具有預付額度的 API 存取)。首次登入時,Console 中會自動建立「Claude Code」工作區以進行集中成本追蹤。

732* [Amazon Bedrock、Google Vertex AI 或 Microsoft Foundry](/zh-TW/third-party-integrations)(企業雲端提供商)100* [Amazon Bedrock、Google Vertex AI 或 Microsoft Foundry](/zh-TW/third-party-integrations)(企業雲端提供商)

733 101 


899| `claude -p "query"` | 執行一次性查詢,然後退出 | `claude -p "explain this function"` |267| `claude -p "query"` | 執行一次性查詢,然後退出 | `claude -p "explain this function"` |

900| `claude -c` | 在目前目錄中繼續最近的對話 | `claude -c` |268| `claude -c` | 在目前目錄中繼續最近的對話 | `claude -c` |

901| `claude -r` | 恢復之前的對話 | `claude -r` |269| `claude -r` | 恢復之前的對話 | `claude -r` |

902| `claude commit` | 建立 Git 提交 | `claude commit` |

903| `/clear` | 清除對話歷史 | `/clear` |270| `/clear` | 清除對話歷史 | `/clear` |

904| `/help` | 顯示可用命令 | `/help` |271| `/help` | 顯示可用命令 | `/help` |

905| `exit` 或 Ctrl+C | 退出 Claude Code | `exit` |272| `exit` 或 Ctrl+D | 退出 Claude Code | `exit` |

906 273 

907請參閱 [CLI 參考](/zh-TW/cli-reference)以取得完整的命令清單。274請參閱 [CLI 參考](/zh-TW/cli-reference)以取得完整的命令清單。

908 275 

settings.md +6 −2

Details

211| `modelOverrides` | 將 Anthropic 模型 ID 對應到提供者特定的模型 ID,例如 Bedrock 推論設定檔 ARN。每個模型選擇器項目在呼叫提供者 API 時使用其對應的值。請參閱[按版本覆蓋模型 ID](/zh-TW/model-config#override-model-ids-per-version) | `{"claude-opus-4-6": "arn:aws:bedrock:..."}` |211| `modelOverrides` | 將 Anthropic 模型 ID 對應到提供者特定的模型 ID,例如 Bedrock 推論設定檔 ARN。每個模型選擇器項目在呼叫提供者 API 時使用其對應的值。請參閱[按版本覆蓋模型 ID](/zh-TW/model-config#override-model-ids-per-version) | `{"claude-opus-4-6": "arn:aws:bedrock:..."}` |

212| `otelHeadersHelper` | 產生動態 OpenTelemetry 標頭的指令碼。在啟動時和定期執行。使用 [`CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`](/zh-TW/env-vars) 設定重新整理間隔。請參閱[動態標頭](/zh-TW/monitoring-usage#dynamic-headers) | `/bin/generate_otel_headers.sh` |212| `otelHeadersHelper` | 產生動態 OpenTelemetry 標頭的指令碼。在啟動時和定期執行。使用 [`CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`](/zh-TW/env-vars) 設定重新整理間隔。請參閱[動態標頭](/zh-TW/monitoring-usage#dynamic-headers) | `/bin/generate_otel_headers.sh` |

213| `outputStyle` | 設定輸出樣式以調整系統提示。請參閱[輸出樣式文件](/zh-TW/output-styles) | `"Explanatory"` |213| `outputStyle` | 設定輸出樣式以調整系統提示。請參閱[輸出樣式文件](/zh-TW/output-styles) | `"Explanatory"` |

214| `parentSettingsBehavior` | {/* min-version: 2.1.133 */}(Managed 設定僅限)控制由嵌入主機流程(例如 Agent SDK 或 IDE 擴充功能)以程式設計方式提供的 managed 設定在同時存在管理員部署的 managed 層級時是否適用。`"first-wins"`:父級提供的設定被丟棄,僅適用管理員層級。`"merge"`:父級提供的設定適用於管理員層級下方,經過篩選以便它們可以收緊政策但不能放鬆政策。當未部署管理員層級時無效。預設:`"first-wins"`。需要 Claude Code v2.1.133 或更新版本 | `"merge"` |

214| `permissions` | 請參閱下表以了解權限的結構。 | |215| `permissions` | 請參閱下表以了解權限的結構。 | |

215| `plansDirectory` | 自訂計畫檔案的儲存位置。路徑相對於專案根目錄。預設:`~/.claude/plans` | `"./plans"` |216| `plansDirectory` | 自訂計畫檔案的儲存位置。路徑相對於專案根目錄。預設:`~/.claude/plans` | `"./plans"` |

216| `pluginTrustMessage` | (Managed 設定僅限)在安裝前顯示的 plugin 信任警告中附加的自訂訊息。使用此選項新增組織特定的內容,例如確認來自您內部 marketplace 的 plugins 已經過審查。 | `"All plugins from our marketplace are approved by IT"` |217| `pluginTrustMessage` | (Managed 設定僅限)在安裝前顯示的 plugin 信任警告中附加的自訂訊息。使用此選項新增組織特定的內容,例如確認來自您內部 marketplace 的 plugins 已經過審查。 | `"All plugins from our marketplace are approved by IT"` |


255 256 

256### Worktree 設定257### Worktree 設定

257 258 

258設定 `--worktree` 如何建立和管理 git worktrees。使用這些設定來減少大型 monorepos 中的磁碟使用量和啟動時間。259設定 `--worktree` 如何建立和管理 git worktrees。

259 260 

260| 金鑰 | 說明 | 範例 |261| 金鑰 | 說明 | 範例 |

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

263| `worktree.baseRef` | 新 worktrees 分支的來源 ref。`"fresh"`(預設)從 `origin/<default-branch>` 分支以取得與遠端相符的乾淨樹。`"head"` 從您目前的本機 `HEAD` 分支,因此未推送的提交和功能分支狀態存在於 worktree 中。適用於 `--worktree`、`EnterWorktree` 工具和 subagent 隔離 | `"head"` |

262| `worktree.symlinkDirectories` | 要從主儲存庫符號連結到每個 worktree 的目錄,以避免在磁碟上複製大型目錄。預設不符號連結任何目錄 | `["node_modules", ".cache"]` |264| `worktree.symlinkDirectories` | 要從主儲存庫符號連結到每個 worktree 的目錄,以避免在磁碟上複製大型目錄。預設不符號連結任何目錄 | `["node_modules", ".cache"]` |

263| `worktree.sparsePaths` | 要在每個 worktree 中透過 git sparse-checkout(cone 模式)簽出的目錄。僅將列出的路徑寫入磁碟,在大型 monorepos 中速度更快 | `["packages/my-app", "shared/utils"]` |265| `worktree.sparsePaths` | 要在每個 worktree 中透過 git sparse-checkout(cone 模式)簽出的目錄。僅將列出的路徑寫入磁碟,在大型 monorepos 中速度更快 | `["packages/my-app", "shared/utils"]` |

264 266 


318| `network.socksProxyPort` | 如果您想帶上自己的代理,使用的 SOCKS5 代理連接埠。如果未指定,Claude 將執行自己的代理。 | `8081` |320| `network.socksProxyPort` | 如果您想帶上自己的代理,使用的 SOCKS5 代理連接埠。如果未指定,Claude 將執行自己的代理。 | `8081` |

319| `enableWeakerNestedSandbox` | 為無特權 Docker 環境啟用較弱的 sandbox(僅限 Linux 和 WSL2)。**降低安全性。** 預設:false | `true` |321| `enableWeakerNestedSandbox` | 為無特權 Docker 環境啟用較弱的 sandbox(僅限 Linux 和 WSL2)。**降低安全性。** 預設:false | `true` |

320| `enableWeakerNetworkIsolation` | (僅限 macOS)允許在 sandbox 中存取系統 TLS 信任服務(`com.apple.trustd.agent`)。使用 `httpProxyPort` 和自訂 CA 的 MITM 代理時,Go 型工具(如 `gh`、`gcloud` 和 `terraform`)需要驗證 TLS 憑證。**透過開啟潛在的資料外洩路徑降低安全性**。預設:false | `true` |322| `enableWeakerNetworkIsolation` | (僅限 macOS)允許在 sandbox 中存取系統 TLS 信任服務(`com.apple.trustd.agent`)。使用 `httpProxyPort` 和自訂 CA 的 MITM 代理時,Go 型工具(如 `gh`、`gcloud` 和 `terraform`)需要驗證 TLS 憑證。**透過開啟潛在的資料外洩路徑降低安全性**。預設:false | `true` |

323| `bwrapPath` | (Managed 設定僅限,Linux/WSL2)bubblewrap (`bwrap`) 二進位檔的絕對路徑。覆蓋透過 `PATH` 的自動偵測。僅從 [managed 設定](/zh-TW/settings#settings-files)受尊重,不從使用者或專案設定。在 managed 環境中 `bwrap` 安裝在非標準位置時很有用。 | `/opt/admin/bwrap` |

324| `socatPath` | (Managed 設定僅限,Linux/WSL2)用於 sandbox 網路代理的 `socat` 二進位檔的絕對路徑。覆蓋透過 `PATH` 的自動偵測。僅從 managed 設定受尊重。 | `/opt/admin/socat` |

321 325 

322#### Sandbox 路徑前綴326#### Sandbox 路徑前綴

323 327 

setup.md +2 −0

Details

398 398 

399支援的 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)。399支援的 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)。

400 400 

401若要升級 npm 安裝,請執行 `npm install -g @anthropic-ai/claude-code@latest`。避免使用 `npm update -g`,因為它會遵守原始安裝的 semver 範圍,可能無法將您移至最新版本。

402 

401<Warning>403<Warning>

402 請勿使用 `sudo npm install -g`,因為這可能導致權限問題和安全風險。如果您遇到權限錯誤,請參閱[疑難排解權限錯誤](/zh-TW/troubleshoot-install#permission-errors-during-installation)。404 請勿使用 `sudo npm install -g`,因為這可能導致權限問題和安全風險。如果您遇到權限錯誤,請參閱[疑難排解權限錯誤](/zh-TW/troubleshoot-install#permission-errors-during-installation)。

403</Warning>405</Warning>

sub-agents.md +3 −3

Details

262| :---------------- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |262| :---------------- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

263| `name` | Yes | 使用小寫字母和連字號的唯一識別碼 |263| `name` | Yes | 使用小寫字母和連字號的唯一識別碼 |

264| `description` | Yes | Claude 何時應委派給此 subagent |264| `description` | Yes | Claude 何時應委派給此 subagent |

265| `tools` | No | [Tools](#available-tools) subagent 可以使用。如果省略,繼承所有工具 |265| `tools` | No | [Tools](#available-tools) subagent 可以使用。如果省略,繼承所有工具。若要將 Skills 預載入上下文,請使用 `skills` 欄位而不是在此列出 `Skill` |

266| `disallowedTools` | No | 要拒絕的工具,從繼承或指定的清單中移除 |266| `disallowedTools` | No | 要拒絕的工具,從繼承或指定的清單中移除 |

267| `model` | No | [Model](#choose-a-model) 使用:`sonnet`、`opus`、`haiku`、完整模型 ID(例如,`claude-opus-4-7`)或 `inherit`。預設為 `inherit` |267| `model` | No | [Model](#choose-a-model) 使用:`sonnet`、`opus`、`haiku`、完整模型 ID(例如,`claude-opus-4-7`)或 `inherit`。預設為 `inherit` |

268| `permissionMode` | No | [Permission mode](#permission-modes):`default`、`acceptEdits`、`auto`、`dontAsk`、`bypassPermissions` 或 `plan`。針對 [plugin subagents](#choose-the-subagent-scope) 被忽略 |268| `permissionMode` | No | [Permission mode](#permission-modes):`default`、`acceptEdits`、`auto`、`dontAsk`、`bypassPermissions` 或 `plan`。針對 [plugin subagents](#choose-the-subagent-scope) 被忽略 |

269| `maxTurns` | No | subagent 停止前的最大代理轉數 |269| `maxTurns` | No | subagent 停止前的最大代理轉數 |

270| `skills` | No | [Skills](/zh-TW/skills) 在啟動時載入到 subagent 的上下文中。注入完整技能內容,而不僅僅是可供呼叫。Subagents 不從父對話繼承技能 |270| `skills` | No | [Skills](/zh-TW/skills) 在啟動時預載入到 subagent 的上下文中。注入完整技能內容,而不僅僅是描述。Subagents 仍然可以透過 Skill 工具呼叫未列出的專案、使用者和外掛程式技能 |

271| `mcpServers` | No | [MCP servers](/zh-TW/mcp) 可用於此 subagent。每個條目要麼是參考已配置伺服器的伺服器名稱(例如,`"slack"`),要麼是內聯定義,其中伺服器名稱為鍵,完整 [MCP server config](/zh-TW/mcp#installing-mcp-servers) 為值。針對 [plugin subagents](#choose-the-subagent-scope) 被忽略 |271| `mcpServers` | No | [MCP servers](/zh-TW/mcp) 可用於此 subagent。每個條目要麼是參考已配置伺服器的伺服器名稱(例如,`"slack"`),要麼是內聯定義,其中伺服器名稱為鍵,完整 [MCP server config](/zh-TW/mcp#installing-mcp-servers) 為值。針對 [plugin subagents](#choose-the-subagent-scope) 被忽略 |

272| `hooks` | No | [Lifecycle hooks](#define-hooks-for-subagents) 限定於此 subagent。針對 [plugin subagents](#choose-the-subagent-scope) 被忽略 |272| `hooks` | No | [Lifecycle hooks](#define-hooks-for-subagents) 限定於此 subagent。針對 [plugin subagents](#choose-the-subagent-scope) 被忽略 |

273| `memory` | No | [Persistent memory scope](#enable-persistent-memory):`user`、`project` 或 `local`。啟用跨工作階段學習 |273| `memory` | No | [Persistent memory scope](#enable-persistent-memory):`user`、`project` 或 `local`。啟用跨工作階段學習 |


418Implement API endpoints. Follow the conventions and patterns from the preloaded skills.418Implement API endpoints. Follow the conventions and patterns from the preloaded skills.

419```419```

420 420 

421每個技能的完整內容被注入到 subagent 的上下文中,而不僅僅是可供呼叫Subagents 不從父對話繼承技能;您必須明確列出它們421每個列出的技能的完整內容被注入到 subagent 的上下文中。此欄位控制哪些技能被預載入而不是 subagent 可以存取哪些技能:沒有它,subagent 仍然可以在執行期間透過 Skill 工具發現和呼叫專案、使用者和外掛程式技能若要防止 subagent 完全呼叫技能,請從 [`tools`](#available-tools) 清單中省略 `Skill` 或將其新增到 `disallowedTools`

422 422 

423您無法預載入設定 [`disable-model-invocation: true`](/zh-TW/skills#control-who-invokes-a-skill) 的技能,因為預載入來自 Claude 可以呼叫的相同技能集。如果列出的技能遺失或已停用,Claude Code 會跳過它並將警告記錄到除錯日誌。423您無法預載入設定 [`disable-model-invocation: true`](/zh-TW/skills#control-who-invokes-a-skill) 的技能,因為預載入來自 Claude 可以呼叫的相同技能集。如果列出的技能遺失或已停用,Claude Code 會跳過它並將警告記錄到除錯日誌。

424 424 

Details

107set -as terminal-features 'xterm*:extkeys'107set -as terminal-features 'xterm*:extkeys'

108```108```

109 109 

110`allow-passthrough` 行讓通知和進度更新到達 iTerm2、Ghostty 或 Kitty,而不是被 tmux 吞沒。`extended-keys` 行讓 tmux 區分 Shift+Enter 和純 Enter,以便換行符快捷鍵運作。110`allow-passthrough` 行讓通知和進度更新到達外部終端機,而不是被 tmux 吞沒。`extended-keys` 行讓 tmux 區分 Shift+Enter 和純 Enter,以便換行符快捷鍵運作。

111 111 

112## 匹配色彩主題112## 匹配色彩主題

113 113 

Details

6 6 

7> 了解 Claude Code 如何與各種第三方服務和基礎設施整合,以滿足企業部署需求。7> 了解 Claude Code 如何與各種第三方服務和基礎設施整合,以滿足企業部署需求。

8 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 

9組織可以直接通過 Anthropic 或通過雲端提供商部署 Claude Code。本頁面幫助您選擇正確的配置。79組織可以直接通過 Anthropic 或通過雲端提供商部署 Claude Code。本頁面幫助您選擇正確的配置。

10 80 

81<ContactSalesCard surface="third_party_overview" />

82 

11## 比較部署選項83## 比較部署選項

12 84 

13對於大多數組織,Claude for Teams 或 Claude for Enterprise 提供最佳體驗。團隊成員可以通過單一訂閱同時存取 Claude Code 和網頁版 Claude,具有集中計費和無需基礎設施設置的優勢。85對於大多數組織,Claude for Teams 或 Claude for Enterprise 提供最佳體驗。團隊成員可以通過單一訂閱同時存取 Claude Code 和網頁版 Claude,具有集中計費和無需基礎設施設置的優勢。


241 313 

242### 為雲端提供商固定模型版本314### 為雲端提供商固定模型版本

243 315 

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)。316如果您通過 [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` 固定特定模型版本。如果不固定,模型別名會解析為最新版本,當 Anthropic 發佈您帳戶中尚未啟用的新模型時,可能會破壞用戶。固定讓您控制用戶何時移至新模型。有關每個提供商在最新版本不可用時的操作,請參閱 [模型配置](/zh-TW/model-config#pin-models-for-third-party-deployments)。

245 317 

246### 配置安全策略318### 配置安全策略

247 319 

vs-code.md +3 −1

Details

32 32 

33或在 VS Code 中,按 `Cmd+Shift+X`(Mac)或 `Ctrl+Shift+X`(Windows/Linux)開啟擴充功能檢視,搜尋「Claude Code」,然後點擊**安裝**。33或在 VS Code 中,按 `Cmd+Shift+X`(Mac)或 `Ctrl+Shift+X`(Windows/Linux)開啟擴充功能檢視,搜尋「Claude Code」,然後點擊**安裝**。

34 34 

35擴充功能也會安裝在其他 VS Code 分支中,例如 Windsurf 或 Kiro。在編輯器的擴充功能檢視中搜尋「Claude Code」,或從 [Open VSX registry](https://open-vsx.org/extension/Anthropic/claude-code) 安裝。如果您的編輯器無法安裝擴充功能,請在其整合終端中執行 `claude`。[CLI](/zh-TW/quickstart) 可在任何終端中運作。

36 

35<Note>如果安裝後擴充功能未出現,請重新啟動 VS Code 或從命令面板執行「Developer: Reload Window」。</Note>37<Note>如果安裝後擴充功能未出現,請重新啟動 VS Code 或從命令面板執行「Developer: Reload Window」。</Note>

36 38 

37## 開始使用39## 開始使用


318| `environmentVariables` | `[]` | 為 Claude 程序設定環境變數。改為使用 Claude Code 設定以進行共享配置。 |320| `environmentVariables` | `[]` | 為 Claude 程序設定環境變數。改為使用 Claude Code 設定以進行共享配置。 |

319| `disableLoginPrompt` | `false` | 跳過身份驗證提示(用於第三方提供者設定) |321| `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。 |322| `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 程序的可執行檔路徑 |323| `claudeProcessWrapper` | - | 用於啟動 Claude 程序的可執行檔。當存在時,捆綁的二進制檔案路徑會作為引數傳遞。如果擴充功能組建不包含您平台的二進制檔案,請將此設定為單獨安裝的 `claude` 二進制檔案。 |

322 324 

323## VS Code 擴充功能與 Claude Code CLI325## VS Code 擴充功能與 Claude Code CLI

324 326