> ## 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 nell'SDK

> Scopri come utilizzare slash commands per controllare le sessioni di Claude Code attraverso l'SDK

Gli slash commands forniscono un modo per controllare le sessioni di Claude Code con comandi speciali che iniziano con `/`. Questi comandi possono essere inviati attraverso l'SDK per eseguire azioni come compattare il contesto, elencare l'utilizzo del contesto o invocare comandi personalizzati. Solo i comandi che funzionano senza un terminale interattivo sono dispatchable attraverso l'SDK; il messaggio `system/init` elenca quelli disponibili nella vostra sessione.

<h2 id="discovering-available-slash-commands">
  Scoprire gli Slash Commands Disponibili
</h2>

L'SDK Claude Agent fornisce informazioni sui slash commands disponibili nel messaggio di inizializzazione del sistema. Accedete a queste informazioni quando la vostra sessione inizia:

<CodeGroup>
  ```typescript TypeScript theme={null}
  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);
      // Include i comandi integrati più le skill raggruppate, ad esempio:
      // ["clear", "compact", "context", "usage", "code-review", "verify", ...]
    }
  }
  ```

  ```python Python theme={null}
  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"])
              # Include i comandi integrati più le skill raggruppate, ad esempio:
              # ["clear", "compact", "context", "usage", "code-review", "verify", ...]


  asyncio.run(main())
  ```
</CodeGroup>

<h2 id="sending-slash-commands">
  Invio di Slash Commands
</h2>

Inviate slash commands includendoli nella vostra stringa di prompt, proprio come testo normale. I comandi che agiscono sulla cronologia della conversazione, come `/compact`, necessitano di messaggi precedenti per funzionare, quindi gli esempi seguenti pongono prima una domanda e poi inviano il comando come follow-up alla stessa conversazione:

<CodeGroup>
  ```typescript TypeScript theme={null}
  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
    }
  }
  ```

  ```python Python theme={null}
  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())
  ```
</CodeGroup>

<Note>
  Una query può terminare con un risultato di errore, ad esempio quando il limite `maxTurns` / `max_turns` viene raggiunto prima che il lavoro si completi. Il messaggio di risultato finale ha quindi `is_error: true` e un sottotipo di errore come `error_max_turns` invece di `success`.

  Dopo aver restituito quel messaggio di risultato finale, l'SDK genera un errore, perché il processo CLI esce con un codice non zero.

  Avvolgete il ciclo in un `try`/`catch` in TypeScript o `try`/`except` in Python se il vostro comando potrebbe raggiungere il limite, come mostrato in [Single Message Input](/docs/it/agent-sdk/streaming-vs-single-mode#single-message-input), oppure impostate `maxTurns` abbastanza alto affinché il lavoro si completi. In Python, catturate `Exception`: l'SDK presenta i risultati di errore come una semplice `Exception`.
</Note>

<h2 id="common-slash-commands">
  Slash Commands Comuni
</h2>

<h3 id="/compact-compact-conversation-history">
  `/compact` - Compatta la Cronologia della Conversazione
</h3>

Il comando `/compact` riduce la dimensione della vostra cronologia di conversazione riassumendo i messaggi più vecchi preservando il contesto importante. La compattazione richiede una conversazione esistente con almeno due scambi precedenti da riassumere. Questo esempio ha una conversazione prima, poi la compatta e legge il messaggio di sistema `compact_boundary` che riporta il risultato:

<CodeGroup>
  ```typescript TypeScript theme={null}
  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
    }
  }
  ```

  ```python Python theme={null}
  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())
  ```
</CodeGroup>

<Note>
  Un messaggio `compact_boundary` arriva solo quando la compattazione è stata eseguita. Se non c'è nulla da riassumere, `/compact` riporta il motivo invece di generare un errore: l'esecuzione termina comunque con un risultato `success`, nessun messaggio `compact_boundary` viene emesso, e il testo del risultato contiene il messaggio, ad esempio `Not enough messages to compact.` dopo un singolo breve scambio. Una nuova chiamata `query()` una tantum inizia con un contesto vuoto, quindi utilizzate questo modello in una sessione con turni precedenti, ad esempio nella [modalità di input in streaming](/docs/it/agent-sdk/streaming-vs-single-mode) o quando riprendete una sessione.
</Note>

<h3 id="/clear-reset-conversation-context">
  `/clear` - Ripristina il Contesto della Conversazione
</h3>

Il comando `/clear` ripristina la conversazione a un contesto vuoto, in modo che i prompt successivi inizino senza alcuna cronologia di conversazione precedente. La conversazione precedente rimane su disco e può essere ripresa passando il suo ID di sessione all'[opzione `resume`](/docs/it/agent-sdk/sessions#resume-by-id).

Questo è utile nella [modalità di input in streaming](/docs/it/agent-sdk/streaming-vs-single-mode), dove inviate più prompt su una singola connessione. Per le chiamate `query()` una tantum, ogni chiamata inizia già con un contesto vuoto, quindi inviare `/clear` non ha alcun effetto pratico; avviate invece una nuova `query()`.

<Note>
  `/clear` nell'SDK richiede Claude Code v2.1.117 o successivo. Nelle versioni precedenti è omesso da `slash_commands`.
</Note>

<h2 id="creating-custom-slash-commands">
  Creazione di Slash Commands Personalizzati
</h2>

Oltre a utilizzare gli slash commands integrati, potete creare i vostri comandi personalizzati disponibili attraverso l'SDK. I comandi personalizzati sono definiti come file markdown in directory specifiche, simile a come sono configurati i subagenti.

<Note>
  La directory `.claude/commands/` è il formato legacy. Il formato consigliato è `.claude/skills/<name>/SKILL.md`, che supporta la stessa invocazione slash-command (`/name`) più l'invocazione autonoma da parte di Claude. Vedere [Skills](/docs/it/agent-sdk/skills) per il formato attuale. La CLI continua a supportare entrambi i formati, e gli esempi seguenti rimangono accurati per `.claude/commands/`.
</Note>

<h3 id="file-locations">
  Posizioni dei File
</h3>

I comandi slash personalizzati sono archiviati in directory designate in base al loro ambito:

* **Comandi di progetto**: `.claude/commands/` - Disponibili solo nel progetto corrente (legacy; preferire `.claude/skills/`)
* **Comandi personali**: `~/.claude/commands/` - Disponibili in tutti i vostri progetti (legacy; preferire `~/.claude/skills/`)

<h3 id="file-format">
  Formato del File
</h3>

Ogni comando personalizzato è un file markdown dove:

* Il nome del file (senza estensione `.md`) diventa il nome del comando
* Il contenuto del file definisce cosa fa il comando
* Il frontmatter YAML opzionale fornisce la configurazione

<h4 id="basic-example">
  Esempio di Base
</h4>

Create la directory `.claude/commands` nel vostro progetto se non esiste, quindi create `.claude/commands/refactor.md`:

```markdown theme={null}
Refactor the selected code to improve readability and maintainability.
Focus on clean code principles and best practices.
```

Questo crea il comando `/refactor` che potete utilizzare attraverso l'SDK.

<h4 id="with-frontmatter">
  Con Frontmatter
</h4>

Create `.claude/commands/security-check.md`:

```markdown theme={null}
---
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
```

<h3 id="using-custom-commands-in-the-sdk">
  Utilizzo di Comandi Personalizzati nell'SDK
</h3>

Una volta definiti nel filesystem, i comandi personalizzati sono automaticamente disponibili attraverso l'SDK:

<CodeGroup>
  ```typescript TypeScript theme={null}
  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", ...]
    }
  }
  ```

  ```python Python theme={null}
  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())
  ```
</CodeGroup>

<h3 id="advanced-features">
  Funzionalità Avanzate
</h3>

<h4 id="arguments-and-placeholders">
  Argomenti e Segnaposti
</h4>

I comandi personalizzati supportano argomenti dinamici utilizzando segnaposti:

Create `.claude/commands/fix-issue.md`:

```markdown theme={null}
---
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.
```

Utilizzo nell'SDK:

<CodeGroup>
  ```typescript TypeScript theme={null}
  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);
    }
  }
  ```

  ```python Python theme={null}
  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())
  ```
</CodeGroup>

<h4 id="bash-command-execution">
  Esecuzione di Comandi Bash
</h4>

I comandi personalizzati possono eseguire comandi bash e includere il loro output:

Create `.claude/commands/git-commit.md`:

```markdown theme={null}
---
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.
```

<h4 id="file-references">
  Riferimenti ai File
</h4>

Includete i contenuti dei file utilizzando il prefisso `@`:

Create `.claude/commands/review-config.md`:

```markdown theme={null}
---
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.
```

<h3 id="organization-with-namespacing">
  Organizzazione con Namespacing
</h3>

Organizzate i comandi in sottodirectory per una struttura migliore:

```bash theme={null}
.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)
```

La sottodirectory appare nella descrizione del comando ma non influisce sul nome del comando stesso.

<h3 id="practical-examples">
  Esempi Pratici
</h3>

<h4 id="pull-request-review-command">
  Comando di Revisione del Pull Request
</h4>

Create `.claude/commands/review-pr.md`:

```markdown theme={null}
---
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.
```

<Note>
  Claude Code include skills bundled `code-review` e `verify`. Se nominate un comando personalizzato dopo uno di essi, ad esempio `.claude/commands/code-review.md`, il vostro comando oscura lo skill bundled e `slash_commands` elenca il nome una sola volta.
</Note>

<h4 id="test-runner-command">
  Comando Test Runner
</h4>

Create `.claude/commands/test.md`:

```markdown theme={null}
---
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
```

Utilizzate questi comandi attraverso l'SDK:

<CodeGroup>
  ```typescript TypeScript theme={null}
  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
  }
  ```

  ```python Python theme={null}
  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())
  ```
</CodeGroup>

<h2 id="see-also">
  Vedere Anche
</h2>

* [Slash Commands](/docs/it/skills) - Documentazione completa degli slash commands
* [Subagenti nell'SDK](/docs/it/agent-sdk/subagents) - Configurazione basata su filesystem simile per i subagenti
* [Riferimento SDK TypeScript](/docs/it/agent-sdk/typescript) - Documentazione API completa
* [Panoramica SDK](/docs/it/agent-sdk/overview) - Concetti generali dell'SDK
* [Riferimento CLI](/docs/it/cli-reference) - Interfaccia della riga di comando
