slash-commands
Show diff (537 lines)
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -1,534 +0,0 @@
-Slash commands provide a way to control Claude Code sessions with special commands that start with `/`. These commands can be sent through the SDK to perform actions like compacting context, listing context usage, or invoking custom commands. Only commands that work without an interactive terminal are dispatchable through the SDK; the `system/init` message lists the ones available in your session.
-
-##
-
-
-
-Discovering Available Slash Commands
-
-The Claude Agent SDK provides information about available slash commands in the system initialization message. Access this information when your session starts:
-
-TypeScript
-
-Python
-
- 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);
- // Includes built-in commands plus bundled skills, for example:
- // ["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"])
- # Includes built-in commands plus bundled skills, for example:
- # ["clear", "compact", "context", "usage", "code-review", "verify", ...]
-
- asyncio.run(main())
-
-##
-
-
-
-Sending Slash Commands
-
-Send slash commands by including them in your prompt string, just like regular text. Commands that act on conversation history, such as `/compact`, need prior messages to work with, so the examples below ask a question first and then send the command as a follow-up to the same conversation:
-
-TypeScript
-
-Python
-
- 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())
-
-A query can end with an error result, for example when the `maxTurns` / `max_turns` limit is reached before the work completes. The final result message then has `is_error: true` and an error subtype such as `error_max_turns` instead of `success`.After yielding that final result message, the SDK raises an error, because the CLI process exits with a non-zero code.Wrap the loop in a `try`/`catch` in TypeScript or `try`/`except` in Python if your command might hit the limit, as shown in [Single Message Input](</docs/en/agent-sdk/streaming-vs-single-mode#single-message-input>), or set `maxTurns` high enough for the work to complete. In Python, catch `Exception`: the SDK surfaces error results as a plain `Exception`.
-
-##
-
-
-
-Common Slash Commands
-
-###
-
-
-
-`/compact` \- Compact conversation history
-
-The `/compact` command reduces the size of your conversation history by summarizing older messages while preserving important context. Compaction needs an existing conversation with at least two prior exchanges to summarize. This example has a conversation first, then compacts it and reads the `compact_boundary` system message that reports the result:
-
-TypeScript
-
-Python
-
- 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())
-
-A `compact_boundary` message only arrives when compaction ran. With nothing to summarize, `/compact` reports the reason instead of raising: the run still ends with a `success` result, no `compact_boundary` message is emitted, and the result text carries the message, for example `Not enough messages to compact.` after a single short exchange. A fresh one-shot `query()` call starts with empty context, so use this pattern in a session with prior turns, for example in [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>) or when resuming a session.
-
-###
-
-
-
-`/clear` \- Reset conversation context
-
-The `/clear` command resets the conversation to an empty context, so subsequent prompts start with no prior conversation history. The previous conversation remains on disk and can be returned to by passing its session ID to the [`resume` option](</docs/en/agent-sdk/sessions#resume-by-id>). This is useful in [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), where you send multiple prompts over a single connection. For one-shot `query()` calls, each call already starts with empty context, so sending `/clear` has no practical effect; start a new `query()` instead.
-
-##
-
-
-
-Creating Custom Slash Commands
-
-In addition to using built-in slash commands, you can create your own custom commands that are available through the SDK. You define custom commands as markdown files in specific directories, the same way you configure subagents.
-
-Custom commands have been merged into skills. A file in `.claude/commands/` and a skill at `.claude/skills/<name>/SKILL.md` both create `/name` and work the same way. For new work, prefer skills, which add features like a directory for supporting files; see [Skills](</docs/en/agent-sdk/skills>) for SDK usage. The CLI supports both locations, and the examples below remain accurate for `.claude/commands/`.
-
-###
-
-
-
-File Locations
-
-Save custom slash commands in one of these directories, depending on their scope:
-
- * **Project commands** : `.claude/commands/` \- Available only in the current project. For new work, prefer `.claude/skills/`.
- * **Personal commands** : `~/.claude/commands/` \- Available across all your projects. For new work, prefer `~/.claude/skills/`.
-
-###
-
-
-
-File Format
-
-Each custom command is a markdown file where:
-
- * The filename (without `.md` extension) becomes the command name
- * The file content defines what the command does
- * Optional YAML frontmatter provides configuration
-
-####
-
-
-
-Basic Example
-
-Create the `.claude/commands` directory in your project if it doesn’t exist, then create `.claude/commands/refactor.md`:
-
- Refactor the selected code to improve readability and maintainability.
- Focus on clean code principles and best practices.
-
-This creates the `/refactor` command that you can use through the SDK.
-
-####
-
-
-
-With Frontmatter
-
-Create `.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
-
-###
-
-
-
-Using Custom Commands in the SDK
-
-Once defined in the filesystem, custom commands are automatically available through the SDK:
-
-TypeScript
-
-Python
-
- 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())
-
-###
-
-
-
-Advanced Features
-
-####
-
-
-
-Arguments and Placeholders
-
-Custom commands support dynamic arguments using placeholders: Create `.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.
-
-Use in SDK:
-
-TypeScript
-
-Python
-
- import { query } from "@anthropic-ai/claude-agent-sdk";
-
- // Pass arguments to custom command
- try {
- 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);
- }
- }
- } catch (err) {
- // The run ends with an error when it reaches the maxTurns limit
- console.error("Session ended with an error:", err);
- }
-
- import asyncio
- from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
-
- async def main():
- # Pass arguments to custom command
- try:
- 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)
- except Exception as error:
- # The run ends with an error when it reaches the max_turns limit
- print(f"Session ended with an error: {error}")
-
- asyncio.run(main())
-
-If the prompt passes fewer arguments than the placeholders reference, unmatched indexed placeholders such as `$1` stay in the command text verbatim. For the full substitution behavior, including named arguments, see [available string substitutions](</docs/en/skills#available-string-substitutions>).
-
-####
-
-
-
-Bash Command Execution
-
-Custom commands can execute bash commands and include their output: Create `.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.
-
-####
-
-
-
-File References
-
-Include file contents using the `@` prefix: Create `.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.
-
-###
-
-
-
-Organization with Namespacing
-
-Organize commands in subdirectories for better structure:
-
- .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)
-
-The subdirectory appears in the command description but doesn’t affect the command name itself.
-
-###
-
-
-
-Practical Examples
-
-####
-
-
-
-Pull Request Review Command
-
-Create `.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 includes bundled `code-review` and `verify` skills. If you name a custom command after one of them, for example `.claude/commands/code-review.md`, your command shadows the bundled skill and `slash_commands` lists the name once.
-
-####
-
-
-
-Test Runner Command
-
-Create `.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
-
-##
-
-
-
-See Also
-
- * [Slash Commands](</docs/en/skills>) \- Complete slash command documentation
- * [Subagents in the SDK](</docs/en/agent-sdk/subagents>) \- Similar filesystem-based configuration for subagents
- * [TypeScript SDK reference](</docs/en/agent-sdk/typescript>) \- Complete API documentation
- * [SDK overview](</docs/en/agent-sdk/overview>) \- General SDK concepts
- * [CLI reference](</docs/en/cli-reference>) \- Command-line interface
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -211,7 +211,7 @@
In addition to using built-in slash commands, you can create your own custom commands that are available through the SDK. You define custom commands as markdown files in specific directories, the same way you configure subagents.
-The `.claude/commands/` directory is the legacy format. The recommended format is `.claude/skills/<name>/SKILL.md`, which supports the same slash-command invocation (`/name`) plus autonomous invocation by Claude. See [Skills](</docs/en/agent-sdk/skills>) for the current format. The CLI continues to support both formats, and the examples below remain accurate for `.claude/commands/`.
+Custom commands have been merged into skills. A file in `.claude/commands/` and a skill at `.claude/skills/<name>/SKILL.md` both create `/name` and work the same way. For new work, prefer skills, which add features like a directory for supporting files; see [Skills](</docs/en/agent-sdk/skills>) for SDK usage. The CLI supports both locations, and the examples below remain accurate for `.claude/commands/`.
###
@@ -221,8 +221,8 @@
Save custom slash commands in one of these directories, depending on their scope:
- * **Project commands** : `.claude/commands/` \- Available only in the current project (legacy; prefer `.claude/skills/`)
- * **Personal commands** : `~/.claude/commands/` \- Available across all your projects (legacy; prefer `~/.claude/skills/`)
+ * **Project commands** : `.claude/commands/` \- Available only in the current project. For new work, prefer `.claude/skills/`.
+ * **Personal commands** : `~/.claude/commands/` \- Available across all your projects. For new work, prefer `~/.claude/skills/`.
###
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -521,57 +521,6 @@
3. If tests fail, analyze and fix them
4. Re-run to verify fixes
-Use these commands through the SDK:
-
-TypeScript
-
-Python
-
- 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())
-
##
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -202,8 +202,6 @@
`/clear` \- Reset conversation context
The `/clear` command resets the conversation to an empty context, so subsequent prompts start with no prior conversation history. The previous conversation remains on disk and can be returned to by passing its session ID to the [`resume` option](</docs/en/agent-sdk/sessions#resume-by-id>). This is useful in [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), where you send multiple prompts over a single connection. For one-shot `query()` calls, each call already starts with empty context, so sending `/clear` has no practical effect; start a new `query()` instead.
-
-`/clear` in the SDK requires Claude Code v2.1.117 or later. In earlier versions it is omitted from `slash_commands`.
##
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -211,7 +211,7 @@
Creating Custom Slash Commands
-In addition to using built-in slash commands, you can create your own custom commands that are available through the SDK. Custom commands are defined as markdown files in specific directories, similar to how subagents are configured.
+In addition to using built-in slash commands, you can create your own custom commands that are available through the SDK. You define custom commands as markdown files in specific directories, the same way you configure subagents.
The `.claude/commands/` directory is the legacy format. The recommended format is `.claude/skills/<name>/SKILL.md`, which supports the same slash-command invocation (`/name`) plus autonomous invocation by Claude. See [Skills](</docs/en/agent-sdk/skills>) for the current format. The CLI continues to support both formats, and the examples below remain accurate for `.claude/commands/`.
@@ -221,7 +221,7 @@
File Locations
-Custom slash commands are stored in designated directories based on their scope:
+Save custom slash commands in one of these directories, depending on their scope:
* **Project commands** : `.claude/commands/` \- Available only in the current project (legacy; prefer `.claude/skills/`)
* **Personal commands** : `~/.claude/commands/` \- Available across all your projects (legacy; prefer `~/.claude/skills/`)
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -402,6 +402,8 @@
asyncio.run(main())
+If the prompt passes fewer arguments than the placeholders reference, unmatched indexed placeholders such as `$1` stay in the command text verbatim. For the full substitution behavior, including named arguments, see [available string substitutions](</docs/en/skills#available-string-substitutions>).
+
####
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -371,14 +371,19 @@
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);
- }
+ try {
+ 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);
+ }
+ }
+ } catch (err) {
+ // The run ends with an error when it reaches the maxTurns limit
+ console.error("Session ended with an error:", err);
}
import asyncio
@@ -386,10 +391,14 @@
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)
+ try:
+ 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)
+ except Exception as error:
+ # The run ends with an error when it reaches the max_turns limit
+ print(f"Session ended with an error: {error}")
asyncio.run(main())
Show diff (177 lines)
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -24,6 +24,18 @@
// ["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"])
+ # Includes built-in commands plus bundled skills, for example:
+ # ["clear", "compact", "context", "usage", "code-review", "verify", ...]
+
+ asyncio.run(main())
##
@@ -65,6 +77,34 @@
// 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())
A query can end with an error result, for example when the `maxTurns` / `max_turns` limit is reached before the work completes. The final result message then has `is_error: true` and an error subtype such as `error_max_turns` instead of `success`.After yielding that final result message, the SDK raises an error, because the CLI process exits with a non-zero code.Wrap the loop in a `try`/`catch` in TypeScript or `try`/`except` in Python if your command might hit the limit, as shown in [Single Message Input](</docs/en/agent-sdk/streaming-vs-single-mode#single-message-input>), or set `maxTurns` high enough for the work to complete. In Python, catch `Exception`: the SDK surfaces error results as a plain `Exception`.
@@ -120,6 +160,39 @@
}
}
+ 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())
+
A `compact_boundary` message only arrives when compaction ran. With nothing to summarize, `/compact` reports the reason instead of raising: the run still ends with a `success` result, no `compact_boundary` message is emitted, and the result text carries the message, for example `Not enough messages to compact.` after a single short exchange. A fresh one-shot `query()` call starts with empty context, so use this pattern in a session with prior turns, for example in [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>) or when resuming a session.
###
@@ -240,6 +313,33 @@
}
}
+ 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())
+
###
@@ -281,6 +381,18 @@
}
}
+ 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())
+
####
@@ -430,6 +542,27 @@
// 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())
+
##
Show diff (231 lines)
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -20,7 +20,8 @@
})) {
if (message.type === "system" && message.subtype === "init") {
console.log("Available slash commands:", message.slash_commands);
- // Example output: ["clear", "compact", "context", "usage"]
+ // Includes built-in commands plus bundled skills, for example:
+ // ["clear", "compact", "context", "usage", "code-review", "verify", ...]
}
}
@@ -30,23 +31,42 @@
Sending Slash Commands
-Send slash commands by including them in your prompt string, just like regular text:
-
-TypeScript
-
-Python
-
- import { query } from "@anthropic-ai/claude-agent-sdk";
-
- // Send a slash command
+Send slash commands by including them in your prompt string, just like regular text. Commands that act on conversation history, such as `/compact`, need prior messages to work with, so the examples below ask a question first and then send the command as a follow-up to the same conversation:
+
+TypeScript
+
+Python
+
+ 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: { maxTurns: 1 }
- })) {
- if (message.type === "result" && message.subtype === "success") {
- console.log("Command executed:", message.result);
- }
- }
+ options: { continue: true, maxTurns: 1 }
+ })) {
+ if (message.type === "result") {
+ console.log("Command executed, result subtype:", message.subtype);
+ // Example output: Command executed, result subtype: success
+ }
+ }
+
+A query can end with an error result, for example when the `maxTurns` / `max_turns` limit is reached before the work completes. The final result message then has `is_error: true` and an error subtype such as `error_max_turns` instead of `success`.After yielding that final result message, the SDK raises an error, because the CLI process exits with a non-zero code.Wrap the loop in a `try`/`catch` in TypeScript or `try`/`except` in Python if your command might hit the limit, as shown in [Single Message Input](</docs/en/agent-sdk/streaming-vs-single-mode#single-message-input>), or set `maxTurns` high enough for the work to complete. In Python, catch `Exception`: the SDK surfaces error results as a plain `Exception`.
##
@@ -60,24 +80,47 @@
`/compact` \- Compact conversation history
-The `/compact` command reduces the size of your conversation history by summarizing older messages while preserving important context:
-
-TypeScript
-
-Python
-
- import { query } from "@anthropic-ai/claude-agent-sdk";
-
+The `/compact` command reduces the size of your conversation history by summarizing older messages while preserving important context. Compaction needs an existing conversation with at least two prior exchanges to summarize. This example has a conversation first, then compacts it and reads the `compact_boundary` system message that reports the result:
+
+TypeScript
+
+Python
+
+ 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: { maxTurns: 1 }
+ 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
+ }
+ }
+
+A `compact_boundary` message only arrives when compaction ran. With nothing to summarize, `/compact` reports the reason instead of raising: the run still ends with a `success` result, no `compact_boundary` message is emitted, and the result text carries the message, for example `Not enough messages to compact.` after a single short exchange. A fresh one-shot `query()` call starts with empty context, so use this pattern in a session with prior turns, for example in [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>) or when resuming a session.
###
@@ -128,7 +171,7 @@
Basic Example
-Create `.claude/commands/refactor.md`:
+Create the `.claude/commands` directory in your project if it doesn’t exist, then create `.claude/commands/refactor.md`:
Refactor the selected code to improve readability and maintainability.
Focus on clean code principles and best practices.
@@ -146,7 +189,7 @@
---
allowed-tools: Read, Grep, Glob
description: Run security vulnerability scan
- model: claude-opus-4-7
+ model: claude-opus-4-8
---
Analyze the codebase for security vulnerabilities including:
@@ -170,13 +213,19 @@
import { query } from "@anthropic-ai/claude-agent-sdk";
// 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);
- }
+ 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
@@ -185,9 +234,9 @@
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: ["clear", "compact", "context", "usage", "refactor", "security-check"]
+ // Includes built-in commands plus bundled skills and your custom commands, for example:
+ // ["clear", "compact", "context", "usage", "code-review", "verify", "refactor", "security-check", ...]
}
}
@@ -302,9 +351,9 @@
-Code Review Command
-
-Create `.claude/commands/code-review.md`:
+Pull Request Review Command
+
+Create `.claude/commands/review-pr.md`:
---
allowed-tools: Read, Grep, Glob, Bash(git diff *)
@@ -328,6 +377,8 @@
Provide specific, actionable feedback organized by priority.
+Claude Code includes bundled `code-review` and `verify` skills. If you name a custom command after one of them, for example `.claude/commands/code-review.md`, your command shadows the bundled skill and `slash_commands` lists the name once.
+
####
@@ -358,11 +409,17 @@
import { query } from "@anthropic-ai/claude-agent-sdk";
// Run code review
- for await (const message of query({
- prompt: "/code-review",
- options: { maxTurns: 3 }
- })) {
- // Process review feedback
+ 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
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -1,9 +1,3 @@
-> ## 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.
-
Slash commands provide a way to control Claude Code sessions with special commands that start with `/`. These commands can be sent through the SDK to perform actions like compacting context, listing context usage, or invoking custom commands. Only commands that work without an interactive terminal are dispatchable through the SDK; the `system/init` message lists the ones available in your session.
##
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -216,7 +216,7 @@
description: Fix a GitHub issue
---
- Fix issue #$1 with priority $2.
+ Fix issue #$0 with priority $1.
Check the issue description and implement the necessary changes.
Use in SDK:
@@ -232,7 +232,7 @@
prompt: "/fix-issue 123 high",
options: { maxTurns: 5 }
})) {
- // Command will process with $1="123" and $2="high"
+ // Command will process with $0="123" and $1="high"
if (message.type === "result" && message.subtype === "success") {
console.log("Issue fixed:", message.result);
}
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -26,7 +26,7 @@
})) {
if (message.type === "system" && message.subtype === "init") {
console.log("Available slash commands:", message.slash_commands);
- // Example output: ["/compact", "/context", "/usage"]
+ // Example output: ["clear", "compact", "context", "usage"]
}
}
@@ -64,7 +64,7 @@
-`/compact` \- Compact Conversation History
+`/compact` \- Compact conversation history
The `/compact` command reduces the size of your conversation history by summarizing older messages while preserving important context:
@@ -89,9 +89,11 @@
-Clearing the conversation
-
-The interactive `/clear` command is not available in the SDK. Each `query()` call already starts a fresh conversation, so to clear context, end the current `query()` and start a new one. The previous conversation stays on disk and can be returned to by passing its session ID to the [`resume` option](</docs/en/agent-sdk/sessions#resume-by-id>).
+`/clear` \- Reset conversation context
+
+The `/clear` command resets the conversation to an empty context, so subsequent prompts start with no prior conversation history. The previous conversation remains on disk and can be returned to by passing its session ID to the [`resume` option](</docs/en/agent-sdk/sessions#resume-by-id>). This is useful in [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), where you send multiple prompts over a single connection. For one-shot `query()` calls, each call already starts with empty context, so sending `/clear` has no practical effect; start a new `query()` instead.
+
+`/clear` in the SDK requires Claude Code v2.1.117 or later. In earlier versions it is omitted from `slash_commands`.
##
@@ -191,7 +193,7 @@
if (message.type === "system" && message.subtype === "init") {
// Will include both built-in and custom commands
console.log("Available commands:", message.slash_commands);
- // Example: ["/compact", "/context", "/usage", "/refactor", "/security-check"]
+ // Example: ["clear", "compact", "context", "usage", "refactor", "security-check"]
}
}
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -49,7 +49,7 @@
prompt: "/compact",
options: { maxTurns: 1 }
})) {
- if (message.type === "result") {
+ if (message.type === "result" && message.subtype === "success") {
console.log("Command executed:", message.result);
}
}
@@ -231,7 +231,7 @@
options: { maxTurns: 5 }
})) {
// Command will process with $1="123" and $2="high"
- if (message.type === "result") {
+ if (message.type === "result" && message.subtype === "success") {
console.log("Issue fixed:", message.result);
}
}
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -1,3 +1,9 @@
+> ## 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.
+
Slash commands provide a way to control Claude Code sessions with special commands that start with `/`. These commands can be sent through the SDK to perform actions like compacting context, listing context usage, or invoking custom commands. Only commands that work without an interactive terminal are dispatchable through the SDK; the `system/init` message lists the ones available in your session.
##
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -20,7 +20,7 @@
})) {
if (message.type === "system" && message.subtype === "init") {
console.log("Available slash commands:", message.slash_commands);
- // Example output: ["/compact", "/context", "/cost"]
+ // Example output: ["/compact", "/context", "/usage"]
}
}
@@ -185,7 +185,7 @@
if (message.type === "system" && message.subtype === "init") {
// Will include both built-in and custom commands
console.log("Available commands:", message.slash_commands);
- // Example: ["/compact", "/context", "/cost", "/refactor", "/security-check"]
+ // Example: ["/compact", "/context", "/usage", "/refactor", "/security-check"]
}
}
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -1,4 +1,4 @@
-Slash commands provide a way to control Claude Code sessions with special commands that start with `/`. These commands can be sent through the SDK to perform actions like clearing conversation history, compacting messages, or getting help.
+Slash commands provide a way to control Claude Code sessions with special commands that start with `/`. These commands can be sent through the SDK to perform actions like compacting context, listing context usage, or invoking custom commands. Only commands that work without an interactive terminal are dispatchable through the SDK; the `system/init` message lists the ones available in your session.
##
@@ -20,7 +20,7 @@
})) {
if (message.type === "system" && message.subtype === "init") {
console.log("Available slash commands:", message.slash_commands);
- // Example output: ["/compact", "/clear", "/help"]
+ // Example output: ["/compact", "/context", "/cost"]
}
}
@@ -83,26 +83,9 @@
-`/clear` \- Clear Conversation
-
-The `/clear` command starts a fresh conversation by clearing all previous history:
-
-TypeScript
-
-Python
-
- import { query } from "@anthropic-ai/claude-agent-sdk";
-
- // 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);
- }
- }
+Clearing the conversation
+
+The interactive `/clear` command is not available in the SDK. Each `query()` call already starts a fresh conversation, so to clear context, end the current `query()` and start a new one. The previous conversation stays on disk and can be returned to by passing its session ID to the [`resume` option](</docs/en/agent-sdk/sessions#resume-by-id>).
##
@@ -161,7 +144,7 @@
---
allowed-tools: Read, Grep, Glob
description: Run security vulnerability scan
- model: claude-opus-4-6
+ model: claude-opus-4-7
---
Analyze the codebase for security vulnerabilities including:
@@ -202,7 +185,7 @@
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"]
+ // Example: ["/compact", "/context", "/cost", "/refactor", "/security-check"]
}
}
@@ -256,7 +239,7 @@
Custom commands can execute bash commands and include their output: Create `.claude/commands/git-commit.md`:
---
- allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)
+ allowed-tools: Bash(git add *), Bash(git status *), Bash(git commit *)
description: Create a git commit
---
@@ -322,7 +305,7 @@
Create `.claude/commands/code-review.md`:
---
- allowed-tools: Read, Grep, Glob, Bash(git diff:*)
+ allowed-tools: Read, Grep, Glob, Bash(git diff *)
description: Comprehensive code review
---
Show diff (404 lines)
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -0,0 +1,401 @@
+Slash commands provide a way to control Claude Code sessions with special commands that start with `/`. These commands can be sent through the SDK to perform actions like clearing conversation history, compacting messages, or getting help.
+
+##
+
+
+
+Discovering Available Slash Commands
+
+The Claude Agent SDK provides information about available slash commands in the system initialization message. Access this information when your session starts:
+
+TypeScript
+
+Python
+
+ 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);
+ // Example output: ["/compact", "/clear", "/help"]
+ }
+ }
+
+##
+
+
+
+Sending Slash Commands
+
+Send slash commands by including them in your prompt string, just like regular text:
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // 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);
+ }
+ }
+
+##
+
+
+
+Common Slash Commands
+
+###
+
+
+
+`/compact` \- Compact Conversation History
+
+The `/compact` command reduces the size of your conversation history by summarizing older messages while preserving important context:
+
+TypeScript
+
+Python
+
+ 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 Conversation
+
+The `/clear` command starts a fresh conversation by clearing all previous history:
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // 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);
+ }
+ }
+
+##
+
+
+
+Creating Custom Slash Commands
+
+In addition to using built-in slash commands, you can create your own custom commands that are available through the SDK. Custom commands are defined as markdown files in specific directories, similar to how subagents are configured.
+
+The `.claude/commands/` directory is the legacy format. The recommended format is `.claude/skills/<name>/SKILL.md`, which supports the same slash-command invocation (`/name`) plus autonomous invocation by Claude. See [Skills](</docs/en/agent-sdk/skills>) for the current format. The CLI continues to support both formats, and the examples below remain accurate for `.claude/commands/`.
+
+###
+
+
+
+File Locations
+
+Custom slash commands are stored in designated directories based on their scope:
+
+ * **Project commands** : `.claude/commands/` \- Available only in the current project (legacy; prefer `.claude/skills/`)
+ * **Personal commands** : `~/.claude/commands/` \- Available across all your projects (legacy; prefer `~/.claude/skills/`)
+
+###
+
+
+
+File Format
+
+Each custom command is a markdown file where:
+
+ * The filename (without `.md` extension) becomes the command name
+ * The file content defines what the command does
+ * Optional YAML frontmatter provides configuration
+
+####
+
+
+
+Basic Example
+
+Create `.claude/commands/refactor.md`:
+
+ Refactor the selected code to improve readability and maintainability.
+ Focus on clean code principles and best practices.
+
+This creates the `/refactor` command that you can use through the SDK.
+
+####
+
+
+
+With Frontmatter
+
+Create `.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
+
+###
+
+
+
+Using Custom Commands in the SDK
+
+Once defined in the filesystem, custom commands are automatically available through the SDK:
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // 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"]
+ }
+ }
+
+###
+
+
+
+Advanced Features
+
+####
+
+
+
+Arguments and Placeholders
+
+Custom commands support dynamic arguments using placeholders: Create `.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.
+
+Use in SDK:
+
+TypeScript
+
+Python
+
+ 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 $1="123" and $2="high"
+ if (message.type === "result") {
+ console.log("Issue fixed:", message.result);
+ }
+ }
+
+####
+
+
+
+Bash Command Execution
+
+Custom commands can execute bash commands and include their output: Create `.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.
+
+####
+
+
+
+File References
+
+Include file contents using the `@` prefix: Create `.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.
+
+###
+
+
+
+Organization with Namespacing
+
+Organize commands in subdirectories for better structure:
+
+ .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)
+
+The subdirectory appears in the command description but doesn’t affect the command name itself.
+
+###
+
+
+
+Practical Examples
+
+####
+
+
+
+Code Review Command
+
+Create `.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.
+
+####
+
+
+
+Test Runner Command
+
+Create `.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
+
+Use these commands through the SDK:
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // 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
+ }
+
+##
+
+
+
+See Also
+
+ * [Slash Commands](</docs/en/skills>) \- Complete slash command documentation
+ * [Subagents in the SDK](</docs/en/agent-sdk/subagents>) \- Similar filesystem-based configuration for subagents
+ * [TypeScript SDK reference](</docs/en/agent-sdk/typescript>) \- Complete API documentation
+ * [SDK overview](</docs/en/agent-sdk/overview>) \- General SDK concepts
+ * [CLI reference](</docs/en/cli-reference>) \- Command-line interface