> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK 中的 Slash Commands

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

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

<h2 id="discovering-available-slash-commands">
  發現可用的 Slash Commands
</h2>

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

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { query } from "@anthropic-ai/claude-agent-sdk";

  for await (const message of query({
    prompt: "Hello Claude",
    options: { maxTurns: 1 }
  })) {
    if (message.type === "system" && message.subtype === "init") {
      console.log("Available slash commands:", message.slash_commands);
      // 包括內建命令加上捆綁的技能，例如：
      // ["clear", "compact", "context", "usage", "code-review", "verify", ...]
    }
  }
  ```

  ```python Python theme={null}
  import asyncio
  from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage


  async def main():
      async for message in query(prompt="Hello Claude", options=ClaudeAgentOptions(max_turns=1)):
          if isinstance(message, SystemMessage) and message.subtype == "init":
              print("Available slash commands:", message.data["slash_commands"])
              # 包括內建命令加上捆綁的技能，例如：
              # ["clear", "compact", "context", "usage", "code-review", "verify", ...]


  asyncio.run(main())
  ```
</CodeGroup>

<h2 id="sending-slash-commands">
  發送 Slash Commands
</h2>

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

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { query } from "@anthropic-ai/claude-agent-sdk";

  // Build up conversation history first
  try {
    for await (const message of query({
      prompt: "What does the README in this directory cover?",
      options: { maxTurns: 2 }
    })) {
      if (message.type === "result" && message.subtype === "success") {
        console.log(message.result);
      }
    }
  } catch (error) {
    // A single-shot query() throws after yielding an error result,
    // so the follow-up query below still runs.
    console.error(`Session ended with an error: ${error}`);
  }

  // Send a slash command as a follow-up to the same conversation
  for await (const message of query({
    prompt: "/compact",
    options: { continue: true, maxTurns: 1 }
  })) {
    if (message.type === "result") {
      console.log("Command executed, result subtype:", message.subtype);
      // Example output: Command executed, result subtype: success
    }
  }
  ```

  ```python Python theme={null}
  import asyncio
  from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage


  async def main():
      # Build up conversation history first
      try:
          async for message in query(
              prompt="What does the README in this directory cover?",
              options=ClaudeAgentOptions(max_turns=2),
          ):
              if isinstance(message, ResultMessage) and message.subtype == "success":
                  print(message.result)
      except Exception as error:
          # A single-shot query() raises after yielding an error result,
          # so the follow-up query below still runs.
          print(f"Session ended with an error: {error}")

      # Send a slash command as a follow-up to the same conversation
      async for message in query(
          prompt="/compact",
          options=ClaudeAgentOptions(continue_conversation=True, max_turns=1),
      ):
          if isinstance(message, ResultMessage):
              print("Command executed, result subtype:", message.subtype)
              # Example output: Command executed, result subtype: success


  asyncio.run(main())
  ```
</CodeGroup>

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

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

  如果您的命令可能達到限制，請在 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`。
</Note>

<h2 id="common-slash-commands">
  常見的 Slash Commands
</h2>

<h3 id="/compact-compact-conversation-history">
  `/compact` - 壓縮對話歷史
</h3>

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

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { query } from "@anthropic-ai/claude-agent-sdk";

  // Compaction needs existing history, so have a conversation first
  try {
    for await (const message of query({
      prompt: "Explain what this project does",
      options: { maxTurns: 2 }
    })) {
      if (message.type === "result" && message.subtype === "success") {
        console.log(message.result);
      }
    }
  } catch (error) {
    // A single-shot query() throws after yielding an error result,
    // so the follow-up query below still runs.
    console.error(`Session ended with an error: ${error}`);
  }

  // Compact the same conversation
  for await (const message of query({
    prompt: "/compact",
    options: { continue: true, maxTurns: 1 }
  })) {
    if (message.type === "system" && message.subtype === "compact_boundary") {
      console.log("Compaction completed");
      console.log("Pre-compaction tokens:", message.compact_metadata.pre_tokens);
      console.log("Trigger:", message.compact_metadata.trigger);
      // Example output:
      // Compaction completed
      // Pre-compaction tokens: 1842
      // Trigger: manual
    }
  }
  ```

  ```python Python theme={null}
  import asyncio
  from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage, SystemMessage


  async def main():
      # Compaction needs existing history, so have a conversation first
      try:
          async for message in query(
              prompt="Explain what this project does",
              options=ClaudeAgentOptions(max_turns=2),
          ):
              if isinstance(message, ResultMessage) and message.subtype == "success":
                  print(message.result)
      except Exception as error:
          # A single-shot query() raises after yielding an error result,
          # so the follow-up query below still runs.
          print(f"Session ended with an error: {error}")

      # Compact the same conversation
      async for message in query(
          prompt="/compact",
          options=ClaudeAgentOptions(continue_conversation=True, max_turns=1),
      ):
          if isinstance(message, SystemMessage) and message.subtype == "compact_boundary":
              print("Compaction completed")
              print("Pre-compaction tokens:", message.data["compact_metadata"]["pre_tokens"])
              print("Trigger:", message.data["compact_metadata"]["trigger"])
              # Example output:
              # Compaction completed
              # Pre-compaction tokens: 1842
              # Trigger: manual


  asyncio.run(main())
  ```
</CodeGroup>

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

<h3 id="/clear-reset-conversation-context">
  `/clear` - 重設對話上下文
</h3>

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

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

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

<h2 id="creating-custom-slash-commands">
  建立自訂 Slash Commands
</h2>

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

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

<h3 id="file-locations">
  檔案位置
</h3>

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

* **專案命令**：`.claude/commands/` - 僅在目前專案中可用（舊版；建議使用 `.claude/skills/`）
* **個人命令**：`~/.claude/commands/` - 在您的所有專案中可用（舊版；建議使用 `~/.claude/skills/`）

<h3 id="file-format">
  檔案格式
</h3>

每個自訂命令都是一個 markdown 檔案，其中：

* 檔案名稱（不含 `.md` 副檔名）成為命令名稱
* 檔案內容定義命令的功能
* 可選的 YAML frontmatter 提供配置

<h4 id="basic-example">
  基本範例
</h4>

在您的專案中建立 `.claude/commands` 目錄（如果不存在），然後建立 `.claude/commands/refactor.md`：

```markdown theme={null}
Refactor the selected code to improve readability and maintainability.
Focus on clean code principles and best practices.
```

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

<h4 id="with-frontmatter">
  使用 Frontmatter
</h4>

建立 `.claude/commands/security-check.md`：

```markdown theme={null}
---
allowed-tools: Read, Grep, Glob
description: Run security vulnerability scan
model: claude-opus-4-8
---

Analyze the codebase for security vulnerabilities including:
- SQL injection risks
- XSS vulnerabilities
- Exposed credentials
- Insecure configurations
```

<h3 id="using-custom-commands-in-the-sdk">
  在 SDK 中使用自訂命令
</h3>

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

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { query } from "@anthropic-ai/claude-agent-sdk";

  // Use a custom command
  try {
    for await (const message of query({
      prompt: "/refactor src/auth/login.ts",
      options: { maxTurns: 3 }
    })) {
      if (message.type === "assistant") {
        console.log("Refactoring suggestions:", message.message);
      }
    }
  } catch (error) {
    // A single-shot query() throws after yielding an error result,
    // so the second query below still runs.
    console.error(`Session ended with an error: ${error}`);
  }

  // Custom commands appear in the slash_commands list
  for await (const message of query({
    prompt: "Hello",
    options: { maxTurns: 1 }
  })) {
    if (message.type === "system" && message.subtype === "init") {
      console.log("Available commands:", message.slash_commands);
      // Includes built-in commands plus bundled skills and your custom commands, for example:
      // ["clear", "compact", "context", "usage", "code-review", "verify", "refactor", "security-check", ...]
    }
  }
  ```

  ```python Python theme={null}
  import asyncio
  from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, SystemMessage


  async def main():
      # Use a custom command
      try:
          async for message in query(
              prompt="/refactor src/auth/login.py", options=ClaudeAgentOptions(max_turns=3)
          ):
              if isinstance(message, AssistantMessage):
                  for block in message.content:
                      if hasattr(block, "text"):
                          print("Refactoring suggestions:", block.text)
      except Exception as error:
          # A single-shot query() raises after yielding an error result,
          # so the second query below still runs.
          print(f"Session ended with an error: {error}")

      # Custom commands appear in the slash_commands list
      async for message in query(prompt="Hello", options=ClaudeAgentOptions(max_turns=1)):
          if isinstance(message, SystemMessage) and message.subtype == "init":
              print("Available commands:", message.data["slash_commands"])
              # Includes built-in commands plus bundled skills and your custom commands, for example:
              # ["clear", "compact", "context", "usage", "code-review", "verify", "refactor", "security-check", ...]


  asyncio.run(main())
  ```
</CodeGroup>

<h3 id="advanced-features">
  進階功能
</h3>

<h4 id="arguments-and-placeholders">
  引數和佔位符
</h4>

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

建立 `.claude/commands/fix-issue.md`：

```markdown theme={null}
---
argument-hint: [issue-number] [priority]
description: Fix a GitHub issue
---

Fix issue #$0 with priority $1.
Check the issue description and implement the necessary changes.
```

在 SDK 中使用：

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { query } from "@anthropic-ai/claude-agent-sdk";

  // Pass arguments to custom command
  for await (const message of query({
    prompt: "/fix-issue 123 high",
    options: { maxTurns: 5 }
  })) {
    // Command will process with $0="123" and $1="high"
    if (message.type === "result" && message.subtype === "success") {
      console.log("Issue fixed:", message.result);
    }
  }
  ```

  ```python Python theme={null}
  import asyncio
  from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage


  async def main():
      # Pass arguments to custom command
      async for message in query(prompt="/fix-issue 123 high", options=ClaudeAgentOptions(max_turns=5)):
          # Command will process with $0="123" and $1="high"
          if isinstance(message, ResultMessage):
              print("Issue fixed:", message.result)


  asyncio.run(main())
  ```
</CodeGroup>

<h4 id="bash-command-execution">
  Bash 命令執行
</h4>

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

建立 `.claude/commands/git-commit.md`：

```markdown theme={null}
---
allowed-tools: Bash(git add *), Bash(git status *), Bash(git commit *)
description: Create a git commit
---

## Context

- Current status: !`git status`
- Current diff: !`git diff HEAD`

## Task

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

<h4 id="file-references">
  檔案參考
</h4>

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

建立 `.claude/commands/review-config.md`：

```markdown theme={null}
---
description: Review configuration files
---

Review the following configuration files for issues:
- Package config: @package.json
- TypeScript config: @tsconfig.json
- Environment config: @.env

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

<h3 id="organization-with-namespacing">
  使用命名空間組織
</h3>

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

```bash theme={null}
.claude/commands/
├── frontend/
│   ├── component.md      # Creates /component (project:frontend)
│   └── style-check.md     # Creates /style-check (project:frontend)
├── backend/
│   ├── api-test.md        # Creates /api-test (project:backend)
│   └── db-migrate.md      # Creates /db-migrate (project:backend)
└── review.md              # Creates /review (project)
```

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

<h3 id="practical-examples">
  實用範例
</h3>

<h4 id="pull-request-review-command">
  Pull Request 審查命令
</h4>

建立 `.claude/commands/review-pr.md`：

```markdown theme={null}
---
allowed-tools: Read, Grep, Glob, Bash(git diff *)
description: Comprehensive code review
---

## Changed Files
!`git diff --name-only HEAD~1`

## Detailed Changes
!`git diff HEAD~1`

## Review Checklist

Review the above changes for:
1. Code quality and readability
2. Security vulnerabilities
3. Performance implications
4. Test coverage
5. Documentation completeness

Provide specific, actionable feedback organized by priority.
```

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

<h4 id="test-runner-command">
  測試執行器命令
</h4>

建立 `.claude/commands/test.md`：

```markdown theme={null}
---
allowed-tools: Bash, Read, Edit
argument-hint: [test-pattern]
description: Run tests with optional pattern
---

Run tests matching pattern: $ARGUMENTS

1. Detect the test framework (Jest, pytest, etc.)
2. Run tests with the provided pattern
3. If tests fail, analyze and fix them
4. Re-run to verify fixes
```

透過 SDK 使用這些命令：

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { query } from "@anthropic-ai/claude-agent-sdk";

  // Run code review
  try {
    for await (const message of query({
      prompt: "/review-pr",
      options: { maxTurns: 3 }
    })) {
      // Process review feedback
    }
  } catch (error) {
    // A single-shot query() throws after yielding an error result,
    // so the second query below still runs.
    console.error(`Session ended with an error: ${error}`);
  }

  // Run specific tests
  for await (const message of query({
    prompt: "/test auth",
    options: { maxTurns: 5 }
  })) {
    // Handle test results
  }
  ```

  ```python Python theme={null}
  import asyncio
  from claude_agent_sdk import query, ClaudeAgentOptions


  async def main():
      # Run code review
      try:
          async for message in query(prompt="/review-pr", options=ClaudeAgentOptions(max_turns=3)):
              # Process review feedback
              pass
      except Exception as error:
          # A single-shot query() raises after yielding an error result,
          # so the second query below still runs.
          print(f"Session ended with an error: {error}")

      # Run specific tests
      async for message in query(prompt="/test auth", options=ClaudeAgentOptions(max_turns=5)):
          # Handle test results
          pass


  asyncio.run(main())
  ```
</CodeGroup>

<h2 id="see-also">
  另請參閱
</h2>

* [Slash Commands](/zh-TW/skills) - 完整的 slash command 文件
* [SDK 中的子代理](/zh-TW/agent-sdk/subagents) - 子代理的類似檔案系統配置
* [TypeScript SDK 參考](/zh-TW/agent-sdk/typescript) - 完整的 API 文件
* [SDK 概述](/zh-TW/agent-sdk/overview) - 一般 SDK 概念
* [CLI 參考](/zh-TW/cli-reference) - 命令列介面
