Slash Commands в SDK
Узнайте, как использовать slash commands для управления сеансами Claude Code через SDK
Slash commands предоставляют способ управления сеансами Claude Code с помощью специальных команд, которые начинаются с /. Эти команды можно отправлять через SDK для выполнения действий, таких как компактирование контекста, список использования контекста или вызов пользовательских команд. Только команды, которые работают без интерактивного терминала, могут быть отправлены через SDK; сообщение system/init содержит список доступных в вашем сеансе.
Обнаружение доступных Slash Commands
Claude Agent SDK предоставляет информацию о доступных slash commands в сообщении инициализации системы. Получите доступ к этой информации при запуске вашего сеанса:
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);
// Включает встроенные команды плюс связанные skills, например:
// ["clear", "compact", "context", "usage", "code-review", "verify", ...]
}
}
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"])
# Включает встроенные команды плюс связанные skills, например:
# ["clear", "compact", "context", "usage", "code-review", "verify", ...]
asyncio.run(main())
Отправка Slash Commands
Отправляйте slash commands, включая их в строку подсказки, как обычный текст. Команды, которые действуют на историю разговора, такие как /compact, требуют предыдущих сообщений для работы, поэтому примеры ниже сначала задают вопрос, а затем отправляют команду как продолжение того же разговора:
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
}
}
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())
Запрос может завершиться с результатом ошибки, например когда достигнут лимит maxTurns / max_turns до завершения работы. Финальное сообщение результата имеет is_error: true и подтип ошибки, такой как error_max_turns, вместо success.
После выдачи этого финального сообщения результата SDK выбрасывает ошибку, потому что процесс CLI завершается с ненулевым кодом.
Оберните цикл в try/catch в TypeScript или try/except в Python, если ваша команда может достичь лимита, как показано в Single Message Input, или установите maxTurns достаточно высоко для завершения работы. В Python перехватывайте Exception: SDK выводит результаты ошибок как простое Exception.
Распространённые Slash Commands
`/compact` - Компактирование истории разговора
Команда /compact уменьшает размер истории вашего разговора путём суммирования старых сообщений при сохранении важного контекста. Компактирование требует существующего разговора с минимум двумя предыдущими обменами для суммирования. Этот пример сначала содержит разговор, затем компактирует его и читает системное сообщение compact_boundary, которое сообщает результат:
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
}
}
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())
Сообщение compact_boundary поступает только при выполнении компактирования. Если нечего суммировать, /compact сообщает причину вместо возникновения ошибки: выполнение всё ещё заканчивается результатом success, сообщение compact_boundary не выдаётся, и текст результата содержит сообщение, например Not enough messages to compact. после одного короткого обмена. Новый одноразовый вызов query() начинается с пустым контекстом, поэтому используйте этот паттерн в сеансе с предыдущими ходами, например в режиме потоковой передачи входных данных или при возобновлении сеанса.
`/clear` - Сброс контекста разговора
Команда /clear сбрасывает разговор в пустой контекст, поэтому последующие запросы начинаются без предыдущей истории разговора. Предыдущий разговор остаётся на диске и может быть восстановлен путём передачи его ID сеанса в опцию resume.
Это полезно в режиме потоковой передачи входных данных, где вы отправляете несколько запросов через одно соединение. Для одноразовых вызовов query() каждый вызов уже начинает с пустого контекста, поэтому отправка /clear не имеет практического эффекта; вместо этого начните новый query().
/clear в SDK требует Claude Code v2.1.117 или более поздней версии. В более ранних версиях он опущен из slash_commands.
Создание пользовательских Slash Commands
Помимо использования встроенных slash commands, вы можете создавать свои собственные пользовательские команды, доступные через SDK. Пользовательские команды определяются как файлы markdown в определённых каталогах, аналогично тому, как настраиваются подагенты.
Каталог .claude/commands/ — это устаревший формат. Рекомендуемый формат — .claude/skills/<name>/SKILL.md, который поддерживает то же самое вызывание slash-команды (/name) плюс автономный вызов Claude. Смотрите Skills для текущего формата. CLI продолжает поддерживать оба формата, и приведённые ниже примеры остаются точными для .claude/commands/.
Расположение файлов
Пользовательские slash commands хранятся в назначенных каталогах в зависимости от их области действия:
- Команды проекта:
.claude/commands/- Доступны только в текущем проекте (устаревший; предпочитайте.claude/skills/) - Личные команды:
~/.claude/commands/- Доступны во всех ваших проектах (устаревший; предпочитайте~/.claude/skills/)
Формат файла
Каждая пользовательская команда — это файл markdown, где:
- Имя файла (без расширения
.md) становится именем команды - Содержимое файла определяет, что делает команда
- Опциональный YAML frontmatter предоставляет конфигурацию
Базовый пример
Создайте каталог .claude/commands в вашем проекте, если его ещё нет, затем создайте .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-8
---
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";
// 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", ...]
}
}
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())
Расширенные возможности
Аргументы и заполнители
Пользовательские команды поддерживают динамические аргументы с использованием заполнителей:
Создайте .claude/commands/fix-issue.md:
---
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:
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);
}
}
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())
Выполнение команд 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 # 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)
Подкаталог появляется в описании команды, но не влияет на само имя команды.
Практические примеры
Команда проверки Pull Request
Создайте .claude/commands/review-pr.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 Code включает встроенные skills code-review и verify. Если вы назовёте пользовательскую команду в честь одного из них, например .claude/commands/code-review.md, ваша команда затенит встроенный skill и slash_commands выведет имя один раз.
Команда запуска тестов
Создайте .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";
// 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
}
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())
Смотрите также
- Slash Commands - Полная документация slash commands
- Subagents в SDK - Аналогичная конфигурация на основе файловой системы для подагентов
- Справочник TypeScript SDK - Полная документация API
- Обзор SDK - Общие концепции SDK
- Справочник CLI - Интерфейс командной строки