Slash Commandها در SDK
Learn how to use slash commands to control Claude Code sessions through the SDK
Slash commandها راهی برای کنترلِ نشستهای Claude Code با دستورهای ویژهای هستند که با / شروع میشوند. این دستورها را میتوان از طریقِ SDK فرستاد تا کارهایی مثلِ فشردهسازیِ کانتکست، فهرستکردنِ مصرفِ کانتکست، یا فراخوانیِ دستورهای سفارشی انجام شود. فقط دستورهایی که بدونِ ترمینالِ تعاملی کار میکنند از طریقِ SDK قابلِ ارسالاند؛ پیامِ system/init آنهایی که در نشستِ تو در دسترساند را فهرست میکند.
کشفِ Slash Commandهای در دسترس
Section titled “کشفِ Slash Commandهای در دسترس”Claude Agent SDK اطلاعاتِ مربوط به slash commandهای در دسترس را در پیامِ مقداردهیِ اولیهی سیستم ارائه میدهد. هنگامِ شروعِ نشست به این اطلاعات دسترسی پیدا کن:
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: ["clear", "compact", "context", "usage"] }}import asynciofrom 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"]) # Example output: ["clear", "compact", "context", "usage"]
asyncio.run(main())فرستادنِ Slash Commandها
Section titled “فرستادنِ Slash Commandها”slash commandها را با گنجاندنِ آنها در رشتهی پرامپتت بفرست، درست مثلِ متنِ معمولی:
import { query } from "@anthropic-ai/claude-agent-sdk";
// Send a slash commandfor await (const message of query({ prompt: "/compact", options: { maxTurns: 1 }})) { if (message.type === "result" && message.subtype === "success") { console.log("Command executed:", message.result); }}import asynciofrom claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
async def main(): # Send a slash command async for message in query(prompt="/compact", options=ClaudeAgentOptions(max_turns=1)): if isinstance(message, ResultMessage): print("Command executed:", message.result)
asyncio.run(main())Slash Commandهای رایج
Section titled “Slash Commandهای رایج”/compact — فشردهسازیِ تاریخچهی گفتگو
Section titled “/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); }}import asynciofrom claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage
async def main(): async for message in query(prompt="/compact", options=ClaudeAgentOptions(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"])
asyncio.run(main())/clear — بازنشانیِ کانتکستِ گفتگو
Section titled “/clear — بازنشانیِ کانتکستِ گفتگو”دستورِ /clear گفتگو را به یک کانتکستِ خالی بازنشانی میکند، طوری که پرامپتهای بعدی بدونِ هیچ تاریخچهی پیشینِ گفتگو شروع شوند. گفتگوی قبلی روی دیسک باقی میماند و با پاسدادنِ session ID آن به گزینهی resume میتوان به آن بازگشت.
این در حالتِ ورودیِ استریمی مفید است، جایی که چندین پرامپت را روی یک اتصالِ واحد میفرستی. برای فراخوانیهای تکمرحلهای (one-shot) query()، هر فراخوانی خودش با کانتکستِ خالی شروع میشود، پس فرستادنِ /clear اثرِ عملی ندارد؛ بهجایش یک query() جدید شروع کن.
ساختنِ Slash Commandهای سفارشی
Section titled “ساختنِ Slash Commandهای سفارشی”علاوه بر استفاده از slash commandهای داخلی، میتوانی دستورهای سفارشیِ خودت را بسازی که از طریقِ SDK در دسترس باشند. دستورهای سفارشی بهصورتِ فایلهای markdown در دایرکتوریهای مشخص تعریف میشوند، شبیه به نحوهی پیکربندیِ سابایجنتها.
مکانِ فایلها
Section titled “مکانِ فایلها”slash commandهای سفارشی بر اساسِ دامنهشان در دایرکتوریهای مشخص ذخیره میشوند:
- دستورهای پروژه:
.claude/commands/— فقط در پروژهی فعلی در دسترساند (قدیمی؛.claude/skills/را ترجیح بده) - دستورهای شخصی:
~/.claude/commands/— در همهی پروژههایت در دسترساند (قدیمی؛~/.claude/skills/را ترجیح بده)
فرمتِ فایل
Section titled “فرمتِ فایل”هر دستورِ سفارشی یک فایلِ markdown است که در آن:
- نامِ فایل (بدونِ پسوندِ
.md) نامِ دستور میشود - محتوای فایل تعریف میکند دستور چه میکند
- frontmatterِ اختیاریِ YAML پیکربندی را فراهم میکند
مثالِ پایه
Section titled “مثالِ پایه”فایلِ .claude/commands/refactor.md را بساز:
Refactor the selected code to improve readability and maintainability.Focus on clean code principles and best practices.این دستورِ /refactor را میسازد که میتوانی از طریقِ SDK از آن استفاده کنی.
همراه با Frontmatter
Section titled “همراه با Frontmatter”فایلِ .claude/commands/security-check.md را بساز:
---allowed-tools: Read, Grep, Globdescription: Run security vulnerability scanmodel: claude-opus-4-7---
Analyze the codebase for security vulnerabilities including:- SQL injection risks- XSS vulnerabilities- Exposed credentials- Insecure configurationsاستفاده از دستورهای سفارشی در SDK
Section titled “استفاده از دستورهای سفارشی در SDK”بهمحضِ تعریف در فایلسیستم، دستورهای سفارشی بهصورت خودکار از طریقِ SDK در دسترساند:
import { query } from "@anthropic-ai/claude-agent-sdk";
// Use a custom commandfor 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 listfor 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: ["clear", "compact", "context", "usage", "refactor", "security-check"] }}import asynciofrom claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, SystemMessage
async def main(): # Use a custom command 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)
# 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": # Will include both built-in and custom commands print("Available commands:", message.data["slash_commands"]) # Example: ["clear", "compact", "context", "usage", "refactor", "security-check"]
asyncio.run(main())قابلیتهای پیشرفته
Section titled “قابلیتهای پیشرفته”آرگومانها و Placeholderها
Section titled “آرگومانها و Placeholderها”دستورهای سفارشی از آرگومانهای پویا با استفاده از placeholderها پشتیبانی میکنند:
فایلِ .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 commandfor 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 asynciofrom 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
Section titled “اجرای دستورهای 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.ارجاع به فایلها
Section titled “ارجاع به فایلها”محتوای فایلها را با پیشوندِ @ بگنجان:
فایلِ .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.سازماندهی با Namespacing
Section titled “سازماندهی با Namespacing”برای ساختارِ بهتر، دستورها را در زیردایرکتوریها سازماندهی کن:
.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)زیردایرکتوری در توضیحاتِ دستور ظاهر میشود اما روی خودِ نامِ دستور اثری ندارد.
مثالهای کاربردی
Section titled “مثالهای کاربردی”دستورِ Code Review
Section titled “دستورِ Code Review”فایلِ .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 readability2. Security vulnerabilities3. Performance implications4. Test coverage5. Documentation completeness
Provide specific, actionable feedback organized by priority.دستورِ Test Runner
Section titled “دستورِ Test Runner”فایلِ .claude/commands/test.md را بساز:
---allowed-tools: Bash, Read, Editargument-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 pattern3. If tests fail, analyze and fix them4. Re-run to verify fixesاین دستورها را از طریقِ SDK استفاده کن:
import { query } from "@anthropic-ai/claude-agent-sdk";
// Run code reviewfor await (const message of query({ prompt: "/code-review", options: { maxTurns: 3 }})) { // Process review feedback}
// Run specific testsfor await (const message of query({ prompt: "/test auth", options: { maxTurns: 5 }})) { // Handle test results}import asynciofrom claude_agent_sdk import query, ClaudeAgentOptions
async def main(): # Run code review async for message in query(prompt="/code-review", options=ClaudeAgentOptions(max_turns=3)): # Process review feedback pass
# Run specific tests async for message in query(prompt="/test auth", options=ClaudeAgentOptions(max_turns=5)): # Handle test results pass
asyncio.run(main())همچنین ببین
Section titled “همچنین ببین”- Slash Commands — مستنداتِ کاملِ slash command
- سابایجنتها در SDK — پیکربندیِ مشابهِ مبتنیبر فایلسیستم برای سابایجنتها
- مرجعِ TypeScript SDK — مستنداتِ کاملِ API
- مرورِ کلیِ SDK — مفاهیمِ عمومیِ SDK
- مرجعِ CLI — رابطِ خطِ فرمان