SpyBara
Go Premium

Documentation 2026-08-19 17:02 UTC to 2026-08-20 23:01 UTC

1 file changed +0 −594. View all changes and history on the product overview
2026
Sat 29 18:58 Thu 27 23:57 Mon 24 23:01 Sat 22 19:01 Fri 21 22:58 Thu 20 23:01 Wed 12 23:59 Tue 11 22:03 Fri 7 23:57 Tue 4 22:59 Sun 2 19:00

agent-sdk/slash-commands.md +0 −594 deleted

File Deleted View Diff

1> ## Documentation Index

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

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

4 

5# SDK 中的 Slash Commands

6 

7> 了解如何透過 SDK 使用 slash commands 來控制 Claude Code 會話

8 

9Slash commands 提供了一種方式來控制 Claude Code 會話,使用以 `/` 開頭的特殊命令。這些命令可以透過 SDK 發送,以執行諸如壓縮上下文、列出上下文使用情況或調用自訂命令等操作。只有在不需要互動式終端的情況下才能工作的命令才能透過 SDK 分派;`system/init` 訊息列出了您會話中可用的命令。

10 

11<h2 id="discovering-available-slash-commands">

12 發現可用的 Slash Commands

13</h2>

14 

15Claude Agent SDK 在系統初始化訊息中提供有關可用 slash commands 的資訊。在您的會話開始時存取此資訊:

16 

17<CodeGroup>

18 ```typescript TypeScript theme={null}

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

20 

21 for await (const message of query({

22 prompt: "Hello Claude",

23 options: { maxTurns: 1 }

24 })) {

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

26 console.log("Available slash commands:", message.slash_commands);

27 // 包括內建命令加上捆綁的技能,例如:

28 // ["clear", "compact", "context", "usage", "code-review", "verify", ...]

29 }

30 }

31 ```

32 

33 ```python Python theme={null}

34 import asyncio

35 from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage

36 

37 

38 async def main():

39 async for message in query(prompt="Hello Claude", options=ClaudeAgentOptions(max_turns=1)):

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

41 print("Available slash commands:", message.data["slash_commands"])

42 # 包括內建命令加上捆綁的技能,例如:

43 # ["clear", "compact", "context", "usage", "code-review", "verify", ...]

44 

45 

46 asyncio.run(main())

47 ```

48</CodeGroup>

49 

50<h2 id="sending-slash-commands">

51 發送 Slash Commands

52</h2>

53 

54透過在您的提示字串中包含 slash commands 來發送它們,就像常規文字一樣。作用於對話歷史記錄的命令,例如 `/compact`,需要先前的訊息才能運作,因此下面的範例首先提出一個問題,然後將命令作為後續訊息發送到同一對話:

55 

56<CodeGroup>

57 ```typescript TypeScript theme={null}

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

59 

60 // Build up conversation history first

61 try {

62 for await (const message of query({

63 prompt: "What does the README in this directory cover?",

64 options: { maxTurns: 2 }

65 })) {

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

67 console.log(message.result);

68 }

69 }

70 } catch (error) {

71 // A single-shot query() throws after yielding an error result,

72 // so the follow-up query below still runs.

73 console.error(`Session ended with an error: ${error}`);

74 }

75 

76 // Send a slash command as a follow-up to the same conversation

77 for await (const message of query({

78 prompt: "/compact",

79 options: { continue: true, maxTurns: 1 }

80 })) {

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

82 console.log("Command executed, result subtype:", message.subtype);

83 // Example output: Command executed, result subtype: success

84 }

85 }

86 ```

87 

88 ```python Python theme={null}

89 import asyncio

90 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

91 

92 

93 async def main():

94 # Build up conversation history first

95 try:

96 async for message in query(

97 prompt="What does the README in this directory cover?",

98 options=ClaudeAgentOptions(max_turns=2),

99 ):

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

101 print(message.result)

102 except Exception as error:

103 # A single-shot query() raises after yielding an error result,

104 # so the follow-up query below still runs.

105 print(f"Session ended with an error: {error}")

106 

107 # Send a slash command as a follow-up to the same conversation

108 async for message in query(

109 prompt="/compact",

110 options=ClaudeAgentOptions(continue_conversation=True, max_turns=1),

111 ):

112 if isinstance(message, ResultMessage):

113 print("Command executed, result subtype:", message.subtype)

114 # Example output: Command executed, result subtype: success

115 

116 

117 asyncio.run(main())

118 ```

119</CodeGroup>

120 

121<Note>

122 查詢可能以錯誤結果結束,例如當 `maxTurns` / `max_turns` 限制在工作完成前達到時。最終結果訊息則具有 `is_error: true` 和錯誤子類型(例如 `error_max_turns`)而不是 `success`。

123 

124 在產生該最終結果訊息後,SDK 會拋出錯誤,因為 CLI 程序以非零代碼退出。

125 

126 如果您的命令可能達到限制,請在 TypeScript 中使用 `try`/`catch` 或在 Python 中使用 `try`/`except` 包裝迴圈,如 [Single Message Input](/zh-TW/agent-sdk/streaming-vs-single-mode#single-message-input) 中所示,或設定 `maxTurns` 足夠高以完成工作。在 Python 中,捕捉 `Exception`:SDK 將錯誤結果表示為純 `Exception`。

127</Note>

128 

129<h2 id="common-slash-commands">

130 常見的 Slash Commands

131</h2>

132 

133<h3 id="/compact-compact-conversation-history">

134 `/compact` - 壓縮對話歷史

135</h3>

136 

137`/compact` 命令透過總結較舊的訊息同時保留重要上下文來減少您的對話歷史的大小。壓縮需要至少有兩次先前交換的現有對話才能進行總結。此範例首先進行對話,然後壓縮它並讀取報告結果的 `compact_boundary` 系統訊息:

138 

139<CodeGroup>

140 ```typescript TypeScript theme={null}

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

142 

143 // Compaction needs existing history, so have a conversation first

144 try {

145 for await (const message of query({

146 prompt: "Explain what this project does",

147 options: { maxTurns: 2 }

148 })) {

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

150 console.log(message.result);

151 }

152 }

153 } catch (error) {

154 // A single-shot query() throws after yielding an error result,

155 // so the follow-up query below still runs.

156 console.error(`Session ended with an error: ${error}`);

157 }

158 

159 // Compact the same conversation

160 for await (const message of query({

161 prompt: "/compact",

162 options: { continue: true, maxTurns: 1 }

163 })) {

164 if (message.type === "system" && message.subtype === "compact_boundary") {

165 console.log("Compaction completed");

166 console.log("Pre-compaction tokens:", message.compact_metadata.pre_tokens);

167 console.log("Trigger:", message.compact_metadata.trigger);

168 // Example output:

169 // Compaction completed

170 // Pre-compaction tokens: 1842

171 // Trigger: manual

172 }

173 }

174 ```

175 

176 ```python Python theme={null}

177 import asyncio

178 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage, SystemMessage

179 

180 

181 async def main():

182 # Compaction needs existing history, so have a conversation first

183 try:

184 async for message in query(

185 prompt="Explain what this project does",

186 options=ClaudeAgentOptions(max_turns=2),

187 ):

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

189 print(message.result)

190 except Exception as error:

191 # A single-shot query() raises after yielding an error result,

192 # so the follow-up query below still runs.

193 print(f"Session ended with an error: {error}")

194 

195 # Compact the same conversation

196 async for message in query(

197 prompt="/compact",

198 options=ClaudeAgentOptions(continue_conversation=True, max_turns=1),

199 ):

200 if isinstance(message, SystemMessage) and message.subtype == "compact_boundary":

201 print("Compaction completed")

202 print("Pre-compaction tokens:", message.data["compact_metadata"]["pre_tokens"])

203 print("Trigger:", message.data["compact_metadata"]["trigger"])

204 # Example output:

205 # Compaction completed

206 # Pre-compaction tokens: 1842

207 # Trigger: manual

208 

209 

210 asyncio.run(main())

211 ```

212</CodeGroup>

213 

214<Note>

215 `compact_boundary` 訊息只在壓縮執行時才會到達。如果沒有任何內容可以總結,`/compact` 會報告原因而不是引發錯誤:執行仍然以 `success` 結果結束,不會發出 `compact_boundary` 訊息,結果文字會帶有訊息,例如在單一簡短交換後的 `Not enough messages to compact.`。全新的一次性 `query()` 呼叫開始時具有空上下文,因此請在具有先前輪次的會話中使用此模式,例如在[串流輸入模式](/zh-TW/agent-sdk/streaming-vs-single-mode)中或恢復會話時。

216</Note>

217 

218<h3 id="/clear-reset-conversation-context">

219 `/clear` - 重設對話上下文

220</h3>

221 

222`/clear` 命令將對話重設為空上下文,因此後續提示會從沒有先前對話歷史的狀態開始。先前的對話保存在磁碟上,可以透過將其會話 ID 傳遞給 [`resume` 選項](/zh-TW/agent-sdk/sessions#resume-by-id) 來返回。

223 

224這在[串流輸入模式](/zh-TW/agent-sdk/streaming-vs-single-mode)中很有用,您可以在單一連線上傳送多個提示。對於一次性的 `query()` 呼叫,每個呼叫已經開始時具有空上下文,因此傳送 `/clear` 沒有實際效果;請改為開始一個新的 `query()`。

225 

226<Note>

227 SDK 中的 `/clear` 需要 Claude Code v2.1.117 或更新版本。在較早的版本中,它會從 `slash_commands` 中省略。

228</Note>

229 

230<h2 id="creating-custom-slash-commands">

231 建立自訂 Slash Commands

232</h2>

233 

234除了使用內建 slash commands 外,您還可以建立自己的自訂命令,這些命令可透過 SDK 使用。自訂命令定義為特定目錄中的 markdown 檔案,類似於子代理的配置方式。

235 

236<Note>

237 `.claude/commands/` 目錄是舊版格式。建議的格式是 `.claude/skills/<name>/SKILL.md`,它支援相同的 slash command 調用(`/name`)加上 Claude 的自主調用。請參閱 [Skills](/zh-TW/agent-sdk/skills) 以了解目前的格式。CLI 繼續支援兩種格式,下面的範例對於 `.claude/commands/` 仍然準確。

238</Note>

239 

240<h3 id="file-locations">

241 檔案位置

242</h3>

243 

244自訂 slash commands 根據其範圍儲存在指定的目錄中:

245 

246* **專案命令**:`.claude/commands/` - 僅在目前專案中可用(舊版;建議使用 `.claude/skills/`)

247* **個人命令**:`~/.claude/commands/` - 在您的所有專案中可用(舊版;建議使用 `~/.claude/skills/`)

248 

249<h3 id="file-format">

250 檔案格式

251</h3>

252 

253每個自訂命令都是一個 markdown 檔案,其中:

254 

255* 檔案名稱(不含 `.md` 副檔名)成為命令名稱

256* 檔案內容定義命令的功能

257* 可選的 YAML frontmatter 提供配置

258 

259<h4 id="basic-example">

260 基本範例

261</h4>

262 

263在您的專案中建立 `.claude/commands` 目錄(如果不存在),然後建立 `.claude/commands/refactor.md`:

264 

265```markdown theme={null}

266Refactor the selected code to improve readability and maintainability.

267Focus on clean code principles and best practices.

268```

269 

270這會建立 `/refactor` 命令,您可以透過 SDK 使用。

271 

272<h4 id="with-frontmatter">

273 使用 Frontmatter

274</h4>

275 

276建立 `.claude/commands/security-check.md`:

277 

278```markdown theme={null}

279allowed-tools: Read, Grep, Glob

280description: Run security vulnerability scan

281model: claude-opus-4-8

282 

283Analyze the codebase for security vulnerabilities including:

284- SQL injection risks

285- XSS vulnerabilities

286- Exposed credentials

287- Insecure configurations

288```

289 

290<h3 id="using-custom-commands-in-the-sdk">

291 在 SDK 中使用自訂命令

292</h3>

293 

294一旦在檔案系統中定義,自訂命令就會自動透過 SDK 可用:

295 

296<CodeGroup>

297 ```typescript TypeScript theme={null}

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

299 

300 // Use a custom command

301 try {

302 for await (const message of query({

303 prompt: "/refactor src/auth/login.ts",

304 options: { maxTurns: 3 }

305 })) {

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

307 console.log("Refactoring suggestions:", message.message);

308 }

309 }

310 } catch (error) {

311 // A single-shot query() throws after yielding an error result,

312 // so the second query below still runs.

313 console.error(`Session ended with an error: ${error}`);

314 }

315 

316 // Custom commands appear in the slash_commands list

317 for await (const message of query({

318 prompt: "Hello",

319 options: { maxTurns: 1 }

320 })) {

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

322 console.log("Available commands:", message.slash_commands);

323 // Includes built-in commands plus bundled skills and your custom commands, for example:

324 // ["clear", "compact", "context", "usage", "code-review", "verify", "refactor", "security-check", ...]

325 }

326 }

327 ```

328 

329 ```python Python theme={null}

330 import asyncio

331 from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, SystemMessage

332 

333 

334 async def main():

335 # Use a custom command

336 try:

337 async for message in query(

338 prompt="/refactor src/auth/login.py", options=ClaudeAgentOptions(max_turns=3)

339 ):

340 if isinstance(message, AssistantMessage):

341 for block in message.content:

342 if hasattr(block, "text"):

343 print("Refactoring suggestions:", block.text)

344 except Exception as error:

345 # A single-shot query() raises after yielding an error result,

346 # so the second query below still runs.

347 print(f"Session ended with an error: {error}")

348 

349 # Custom commands appear in the slash_commands list

350 async for message in query(prompt="Hello", options=ClaudeAgentOptions(max_turns=1)):

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

352 print("Available commands:", message.data["slash_commands"])

353 # Includes built-in commands plus bundled skills and your custom commands, for example:

354 # ["clear", "compact", "context", "usage", "code-review", "verify", "refactor", "security-check", ...]

355 

356 

357 asyncio.run(main())

358 ```

359</CodeGroup>

360 

361<h3 id="advanced-features">

362 進階功能

363</h3>

364 

365<h4 id="arguments-and-placeholders">

366 引數和佔位符

367</h4>

368 

369自訂命令支援使用佔位符的動態引數:

370 

371建立 `.claude/commands/fix-issue.md`:

372 

373```markdown theme={null}

374argument-hint: [issue-number] [priority]

375description: Fix a GitHub issue

376 

377Fix issue #$0 with priority $1.

378Check the issue description and implement the necessary changes.

379```

380 

381在 SDK 中使用:

382 

383<CodeGroup>

384 ```typescript TypeScript theme={null}

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

386 

387 // Pass arguments to custom command

388 for await (const message of query({

389 prompt: "/fix-issue 123 high",

390 options: { maxTurns: 5 }

391 })) {

392 // Command will process with $0="123" and $1="high"

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

394 console.log("Issue fixed:", message.result);

395 }

396 }

397 ```

398 

399 ```python Python theme={null}

400 import asyncio

401 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

402 

403 

404 async def main():

405 # Pass arguments to custom command

406 async for message in query(prompt="/fix-issue 123 high", options=ClaudeAgentOptions(max_turns=5)):

407 # Command will process with $0="123" and $1="high"

408 if isinstance(message, ResultMessage):

409 print("Issue fixed:", message.result)

410 

411 

412 asyncio.run(main())

413 ```

414</CodeGroup>

415 

416<h4 id="bash-command-execution">

417 Bash 命令執行

418</h4>

419 

420自訂命令可以執行 bash 命令並包含其輸出:

421 

422建立 `.claude/commands/git-commit.md`:

423 

424```markdown theme={null}

425allowed-tools: Bash(git add *), Bash(git status *), Bash(git commit *)

426description: Create a git commit

427 

428## Context

429 

430- Current status: !`git status`

431- Current diff: !`git diff HEAD`

432 

433## Task

434 

435Create a git commit with appropriate message based on the changes.

436```

437 

438<h4 id="file-references">

439 檔案參考

440</h4>

441 

442使用 `@` 前綴包含檔案內容:

443 

444建立 `.claude/commands/review-config.md`:

445 

446```markdown theme={null}

447description: Review configuration files

448 

449Review the following configuration files for issues:

450- Package config: @package.json

451- TypeScript config: @tsconfig.json

452- Environment config: @.env

453 

454Check for security issues, outdated dependencies, and misconfigurations.

455```

456 

457<h3 id="organization-with-namespacing">

458 使用命名空間組織

459</h3>

460 

461在子目錄中組織命令以獲得更好的結構:

462 

463```bash theme={null}

464.claude/commands/

465├── frontend/

466│ ├── component.md # Creates /component (project:frontend)

467│ └── style-check.md # Creates /style-check (project:frontend)

468├── backend/

469│ ├── api-test.md # Creates /api-test (project:backend)

470│ └── db-migrate.md # Creates /db-migrate (project:backend)

471└── review.md # Creates /review (project)

472```

473 

474子目錄出現在命令描述中,但不會影響命令名稱本身。

475 

476<h3 id="practical-examples">

477 實用範例

478</h3>

479 

480<h4 id="pull-request-review-command">

481 Pull Request 審查命令

482</h4>

483 

484建立 `.claude/commands/review-pr.md`:

485 

486```markdown theme={null}

487allowed-tools: Read, Grep, Glob, Bash(git diff *)

488description: Comprehensive code review

489 

490## Changed Files

491!`git diff --name-only HEAD~1`

492 

493## Detailed Changes

494!`git diff HEAD~1`

495 

496## Review Checklist

497 

498Review the above changes for:

4991. Code quality and readability

5002. Security vulnerabilities

5013. Performance implications

5024. Test coverage

5035. Documentation completeness

504 

505Provide specific, actionable feedback organized by priority.

506```

507 

508<Note>

509 Claude Code 包含捆綁的 `code-review` 和 `verify` skills。如果您以其中一個命名自訂命令,例如 `.claude/commands/code-review.md`,您的命令會遮蔽捆綁的 skill,而 `slash_commands` 列表會列出該名稱一次。

510</Note>

511 

512<h4 id="test-runner-command">

513 測試執行器命令

514</h4>

515 

516建立 `.claude/commands/test.md`:

517 

518```markdown theme={null}

519allowed-tools: Bash, Read, Edit

520argument-hint: [test-pattern]

521description: Run tests with optional pattern

522 

523Run tests matching pattern: $ARGUMENTS

524 

5251. Detect the test framework (Jest, pytest, etc.)

5262. Run tests with the provided pattern

5273. If tests fail, analyze and fix them

5284. Re-run to verify fixes

529```

530 

531透過 SDK 使用這些命令:

532 

533<CodeGroup>

534 ```typescript TypeScript theme={null}

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

536 

537 // Run code review

538 try {

539 for await (const message of query({

540 prompt: "/review-pr",

541 options: { maxTurns: 3 }

542 })) {

543 // Process review feedback

544 }

545 } catch (error) {

546 // A single-shot query() throws after yielding an error result,

547 // so the second query below still runs.

548 console.error(`Session ended with an error: ${error}`);

549 }

550 

551 // Run specific tests

552 for await (const message of query({

553 prompt: "/test auth",

554 options: { maxTurns: 5 }

555 })) {

556 // Handle test results

557 }

558 ```

559 

560 ```python Python theme={null}

561 import asyncio

562 from claude_agent_sdk import query, ClaudeAgentOptions

563 

564 

565 async def main():

566 # Run code review

567 try:

568 async for message in query(prompt="/review-pr", options=ClaudeAgentOptions(max_turns=3)):

569 # Process review feedback

570 pass

571 except Exception as error:

572 # A single-shot query() raises after yielding an error result,

573 # so the second query below still runs.

574 print(f"Session ended with an error: {error}")

575 

576 # Run specific tests

577 async for message in query(prompt="/test auth", options=ClaudeAgentOptions(max_turns=5)):

578 # Handle test results

579 pass

580 

581 

582 asyncio.run(main())

583 ```

584</CodeGroup>

585 

586<h2 id="see-also">

587 另請參閱

588</h2>

589 

590* [Slash Commands](/zh-TW/skills) - 完整的 slash command 文件

591* [SDK 中的子代理](/zh-TW/agent-sdk/subagents) - 子代理的類似檔案系統配置

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

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

594* [CLI 參考](/zh-TW/cli-reference) - 命令列介面