Loading...
    • 開發者指南
    • API 參考
    • MCP
    • 資源
    • 發行說明
    Search...
    ⌘K
    入門
    Claude 簡介快速開始
    模型與定價
    模型概覽選擇模型Claude 4.6 新功能遷移指南模型棄用定價
    使用 Claude 構建
    功能概覽使用 Messages API處理停止原因提示詞最佳實踐
    上下文管理
    上下文視窗壓縮上下文編輯
    功能
    提示詞快取延伸思考自適應思考思考力度串流訊息批次處理引用多語言支援Token 計數嵌入視覺PDF 支援Files API搜尋結果結構化輸出
    工具
    概覽如何實作工具使用細粒度工具串流Bash 工具程式碼執行工具程式化工具呼叫電腦使用工具文字編輯器工具網頁擷取工具網頁搜尋工具記憶工具工具搜尋工具
    Agent Skills
    概覽快速開始最佳實踐企業級 Skills透過 API 使用 Skills
    Agent SDK
    概覽快速開始TypeScript SDKTypeScript V2(預覽版)Python SDK遷移指南
    串流輸入即時串流回應處理停止原因處理權限使用者核准與輸入使用 hooks 控制執行工作階段管理檔案檢查點SDK 中的結構化輸出託管 Agent SDK安全部署 AI 代理修改系統提示詞SDK 中的 MCP自訂工具SDK 中的子代理SDK 中的斜線命令SDK 中的 Agent Skills追蹤成本與用量待辦清單SDK 中的外掛
    API 中的 MCP
    MCP 連接器遠端 MCP 伺服器
    第三方平台上的 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    提示詞工程
    概覽提示詞產生器使用提示詞範本提示詞改進器清晰直接使用範例(多範例提示)讓 Claude 思考(CoT)使用 XML 標籤賦予 Claude 角色(系統提示詞)串聯複雜提示詞長上下文技巧延伸思考技巧
    測試與評估
    定義成功標準開發測試案例使用評估工具降低延遲
    強化防護機制
    減少幻覺提高輸出一致性防範越獄攻擊串流拒絕減少提示詞洩漏讓 Claude 保持角色
    管理與監控
    Admin API 概覽資料駐留工作區用量與成本 APIClaude Code Analytics API零資料保留
    Console
    Log in
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Partners

    • Amazon Bedrock
    • Google Cloud's Vertex AI

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Help and security

    • Availability
    • Status
    • Support
    • Discord

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    指南

    SDK 中的斜線命令

    了解如何使用斜線命令透過 SDK 控制 Claude Code 工作階段

    斜線命令提供了一種使用以 / 開頭的特殊命令來控制 Claude Code 工作階段的方式。這些命令可以透過 SDK 發送,以執行清除對話歷史、壓縮訊息或取得幫助等操作。

    探索可用的斜線命令

    Claude Agent SDK 在系統初始化訊息中提供有關可用斜線命令的資訊。在工作階段開始時存取此資訊:

    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);
        // 範例輸出: ["/compact", "/clear", "/help"]
      }
    }

    發送斜線命令

    透過在提示字串中包含斜線命令來發送,就像普通文字一樣:

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    // 發送斜線命令
    for await (const message of query({
      prompt: "/compact",
      options: { maxTurns: 1 }
    })) {
      if (message.type === "result") {
        console.log("Command executed:", message.result);
      }
    }

    常用斜線命令

    /compact - 壓縮對話歷史

    /compact 命令透過摘要較舊的訊息來減少對話歷史的大小,同時保留重要的上下文:

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    for await (const message of query({
      prompt: "/compact",
      options: { 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);
      }
    }

    /clear - 清除對話

    /clear 命令透過清除所有先前的歷史記錄來開始全新的對話:

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    // 清除對話並重新開始
    for await (const message of query({
      prompt: "/clear",
      options: { maxTurns: 1 }
    })) {
      if (message.type === "system" && message.subtype === "init") {
        console.log("Conversation cleared, new session started");
        console.log("Session ID:", message.session_id);
      }
    }

    建立自訂斜線命令

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

    檔案位置

    自訂斜線命令根據其範圍儲存在指定的目錄中:

    • 專案命令:.claude/commands/ - 僅在目前專案中可用
    • 個人命令:~/.claude/commands/ - 在您所有的專案中都可用

    檔案格式

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

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

    基本範例

    建立 .claude/commands/refactor.md:

    Refactor the selected code to improve readability and maintainability.
    Focus on clean code principles and best practices.

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

    使用 Frontmatter

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

    ---
    allowed-tools: Read, Grep, Glob
    description: Run security vulnerability scan
    model: claude-opus-4-6
    ---
    
    Analyze the codebase for security vulnerabilities including:
    - SQL injection risks
    - XSS vulnerabilities
    - Exposed credentials
    - Insecure configurations

    在 SDK 中使用自訂命令

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

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    // 使用自訂命令
    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);
      }
    }
    
    // 自訂命令會出現在 slash_commands 列表中
    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);
        // 範例: ["/compact", "/clear", "/help", "/refactor", "/security-check"]
      }
    }

    進階功能

    引數和佔位符

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

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

    ---
    argument-hint: [issue-number] [priority]
    description: Fix a GitHub issue
    ---
    
    Fix issue #$1 with priority $2.
    Check the issue description and implement the necessary changes.

    在 SDK 中使用:

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    // 將引數傳遞給自訂命令
    for await (const message of query({
      prompt: "/fix-issue 123 high",
      options: { maxTurns: 5 }
    })) {
      // 命令將以 $1="123" 和 $2="high" 處理
      if (message.type === "result") {
        console.log("Issue fixed:", message.result);
      }
    }

    Bash 命令執行

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

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

    ---
    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.

    檔案參考

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

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

    ---
    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.

    使用命名空間組織

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

    .claude/commands/
    ├── frontend/
    │   ├── component.md      # 建立 /component (project:frontend)
    │   └── style-check.md     # 建立 /style-check (project:frontend)
    ├── backend/
    │   ├── api-test.md        # 建立 /api-test (project:backend)
    │   └── db-migrate.md      # 建立 /db-migrate (project:backend)
    └── review.md              # 建立 /review (project)

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

    實用範例

    程式碼審查命令

    建立 .claude/commands/code-review.md:

    ---
    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.

    測試執行命令

    建立 .claude/commands/test.md:

    ---
    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 使用這些命令:

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    // 執行程式碼審查
    for await (const message of query({
      prompt: "/code-review",
      options: { maxTurns: 3 }
    })) {
      // 處理審查回饋
    }
    
    // 執行特定測試
    for await (const message of query({
      prompt: "/test auth",
      options: { maxTurns: 5 }
    })) {
      // 處理測試結果
    }

    另請參閱

    • 斜線命令 - 完整的斜線命令文件
    • SDK 中的子代理 - 類似的基於檔案系統的子代理配置
    • TypeScript SDK 參考 - 完整的 API 文件
    • SDK 概覽 - 一般 SDK 概念
    • CLI 參考 - 命令列介面

    Was this page helpful?

    • /compact - 壓縮對話歷史
    • /clear - 清除對話
    • 在 SDK 中使用自訂命令