斜杠命令提供了一种使用以 / 开头的特殊命令来控制 Claude Code 会话的方法。这些命令可以通过 SDK 发送,以执行清除对话历史、压缩消息或获取帮助等操作。

发现可用的斜杠命令

Claude Code SDK 在系统初始化消息中提供有关可用斜杠命令的信息。在会话开始时访问此信息:
import { query } from "@anthropic-ai/claude-code";

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);
    // Example output: ["/compact", "/clear", "/help"]
  }
}

发送斜杠命令

通过在提示字符串中包含斜杠命令来发送它们,就像常规文本一样:
import { query } from "@anthropic-ai/claude-code";

// Send a slash command
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-code";

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-code";

// Clear conversation and start fresh
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 前置内容提供配置

基本示例

创建 .claude/commands/refactor.md
重构选定的代码以提高可读性和可维护性。
专注于清洁代码原则和最佳实践。
这将创建可通过 SDK 使用的 /refactor 命令。

带前置内容

创建 .claude/commands/security-check.md
---
allowed-tools: Read, Grep, Glob
description: Run security vulnerability scan
model: claude-3-5-sonnet-20241022
---

分析代码库的安全漏洞,包括:
- SQL 注入风险
- XSS 漏洞
- 暴露的凭据
- 不安全的配置

在 SDK 中使用自定义命令

一旦在文件系统中定义,自定义命令就会自动通过 SDK 可用:
import { query } from "@anthropic-ai/claude-code";

// Use a custom command
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);
  }
}

// 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") {
    // Will include both built-in and custom commands
    console.log("Available commands:", message.slash_commands);
    // Example: ["/compact", "/clear", "/help", "/refactor", "/security-check"]
  }
}

高级功能

参数和占位符

自定义命令支持使用占位符的动态参数: 创建 .claude/commands/fix-issue.md
---
argument-hint: [issue-number] [priority]
description: Fix a GitHub issue
---

修复问题 #$1,优先级为 $2。
检查问题描述并实施必要的更改。
在 SDK 中使用:
import { query } from "@anthropic-ai/claude-code";

// Pass arguments to custom command
for await (const message of query({
  prompt: "/fix-issue 123 high",
  options: { maxTurns: 5 }
})) {
  // Command will process with $1="123" and $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
---

## 上下文

- 当前状态:!`git status`
- 当前差异:!`git diff HEAD`

## 任务

根据更改创建适当消息的 git 提交。

文件引用

使用 @ 前缀包含文件内容: 创建 .claude/commands/review-config.md
---
description: Review configuration files
---

检查以下配置文件的问题:
- 包配置:@package.json
- TypeScript 配置:@tsconfig.json
- 环境配置:@.env

检查安全问题、过时的依赖项和错误配置。

使用命名空间进行组织

在子目录中组织命令以获得更好的结构:
.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)
子目录出现在命令描述中,但不影响命令名称本身。

实际示例

代码审查命令

创建 .claude/commands/code-review.md
---
allowed-tools: Read, Grep, Glob, Bash(git diff:*)
description: Comprehensive code review
---

## 更改的文件
!`git diff --name-only HEAD~1`

## 详细更改
!`git diff HEAD~1`

## 审查清单

审查上述更改:
1. 代码质量和可读性
2. 安全漏洞
3. 性能影响
4. 测试覆盖率
5. 文档完整性

提供按优先级组织的具体、可操作的反馈。

测试运行器命令

创建 .claude/commands/test.md
---
allowed-tools: Bash, Read, Edit
argument-hint: [test-pattern]
description: Run tests with optional pattern
---

运行匹配模式的测试:$ARGUMENTS

1. 检测测试框架(Jest、pytest 等)
2. 使用提供的模式运行测试
3. 如果测试失败,分析并修复它们
4. 重新运行以验证修复
通过 SDK 使用这些命令:
import { query } from "@anthropic-ai/claude-code";

// Run code review
for await (const message of query({
  prompt: "/code-review",
  options: { maxTurns: 3 }
})) {
  // Process review feedback
}

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

另请参阅