---
title: Definire gli esiti
url: https://platform.claude.com/docs/it/managed-agents/define-outcomes
description: Indica all'agente come si presenta un lavoro 'completato' e lascialo iterare finché non ci arriva.
featureMetadata:
  topic:
    title: Managed Agents
    url: https://platform.claude.com/docs/en/managed-agents/overview
  status: beta
  betaHeader: managed-agents-2026-04-01
---

Un esito indica alla sessione come dovrebbe apparire il risultato finale e come misurarne la qualità. L'agente lavora verso quell'obiettivo, autovalutandosi e iterando finché l'esito non viene raggiunto.

Quando definisci un esito, l'harness fornisce automaticamente un *grader* per valutare l'artefatto rispetto a una rubrica. Il grader utilizza una finestra di contesto separata per evitare di essere influenzato dalle scelte di implementazione dell'agente principale.

Il grader restituisce una spiegazione che riassume quali criteri sono stati superati o falliti, oppure conferma che l'artefatto soddisfa la rubrica. Quel feedback viene restituito all'agente per l'iterazione successiva.

## Creare una rubrica

Una rubrica è un documento markdown che descrive il punteggio per ciascun criterio. La rubrica è obbligatoria.

<Accordion title="Suggerimenti per scrivere rubriche efficaci">
  Struttura la rubrica come criteri espliciti e valutabili, come "Il CSV contiene una colonna dei prezzi con valori numerici" piuttosto che "I dati sembrano buoni." Il grader valuta ogni criterio in modo indipendente, quindi criteri vaghi producono valutazioni rumorose.

  Se non hai una rubrica a portata di mano, prova a fornire a Claude un esempio di un artefatto noto come valido e chiedigli di analizzare cosa rende buono quel contenuto, poi trasforma quell'analisi in una rubrica. Questo approccio intermedio spesso produce risultati migliori rispetto a scrivere i criteri da zero.
</Accordion>

Esempio di rubrica:

```markdown
# DCF Model Rubric

## Revenue Projections
- Uses historical revenue data from the last 5 fiscal years
- Projects revenue for at least 5 years forward
- Growth rate assumptions are explicitly stated and reasonable

## Cost Structure
- COGS and operating expenses are modeled separately
- Margins are consistent with historical trends or deviations are justified

## Discount Rate
- WACC is calculated with stated assumptions for cost of equity and cost of debt
- Beta, risk-free rate, and equity risk premium are sourced or justified

## Terminal Value
- Uses either perpetuity growth or exit multiple method (stated which)
- Terminal growth rate does not exceed long-term GDP growth

## Output Quality
- All figures are in a single .xlsx file with clearly labeled sheets
- Key assumptions are on a separate "Assumptions" sheet
- Sensitivity analysis on WACC and terminal growth rate is included
```

Passa la rubrica come testo inline su `user.define_outcome` (vedi [Creare una sessione con un esito](https://platform.claude.com/docs/it/managed-agents/define-outcomes#create-a-session-with-an-outcome)), oppure caricala tramite la Files API per riutilizzarla tra le sessioni.

<CodeGroup>
  ```bash cURL
  curl -fsSL https://api.anthropic.com/v1/files \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "anthropic-beta: managed-agents-2026-04-01" \
    -F file=@/tmp/rubric.md
  ```

  ```bash CLI
  ant files upload --file /tmp/rubric.md
  ```

  ```python Python
  import time
  from pathlib import Path

  from anthropic import Anthropic

  client = Anthropic()

  RUBRIC = """# DCF Model Rubric

  ## Revenue Projections
  - Uses historical revenue data from the last 5 fiscal years
  - Projects revenue for at least 5 years forward

  ## Output Quality
  - All figures are in a single .xlsx file with clearly labeled sheets
  """
  Path("/tmp/rubric.md").write_text(RUBRIC)

  rubric = client.files.upload(file=Path("/tmp/rubric.md"))
  print(f"Uploaded rubric: {rubric.id}")
  ```

  ```typescript TypeScript
  import { writeFile, readFile } from "node:fs/promises";

  import Anthropic from "@anthropic-ai/sdk";
  import { toFile } from "@anthropic-ai/sdk";

  const client = new Anthropic();

  const RUBRIC = `# DCF Model Rubric

  ## Revenue Projections
  - Uses historical revenue data from the last 5 fiscal years
  - Projects revenue for at least 5 years forward

  ## Output Quality
  - All figures are in a single .xlsx file with clearly labeled sheets
  `;
  await writeFile("/tmp/rubric.md", RUBRIC);

  const rubric = await client.files.upload({
    file: await toFile(readFile("/tmp/rubric.md"), "/tmp/rubric.md")
  });
  console.log(`Uploaded rubric: ${rubric.id}`);
  ```

  ```csharp C#
  using Anthropic;
  using Anthropic.Models.Beta.Agents;
  using Anthropic.Models.Beta.Environments;
  using Anthropic.Models.Beta.Sessions;
  using Anthropic.Models.Beta.Sessions.Events;
  using Anthropic.Models.Files;

  var client = new AnthropicClient();

  const string Rubric = """
      # DCF Model Rubric

      ## Revenue Projections
      - Uses historical revenue data from the last 5 fiscal years
      - Projects revenue for at least 5 years forward

      ## Output Quality
      - All figures are in a single .xlsx file with clearly labeled sheets
      """;
  await File.WriteAllTextAsync("/tmp/rubric.md", Rubric);

  var rubric = await client.Files.Upload(new()
  {
      File = File.OpenRead("/tmp/rubric.md"),
  });
  Console.WriteLine($"Uploaded rubric: {rubric.ID}");
  ```

  ```go Go
  package main

  import (
  	"context"
  	"fmt"
  	"io"
  	"os"
  	"time"

  	"github.com/anthropics/anthropic-sdk-go"
  )

  const rubric = `# DCF Model Rubric

  ## Revenue Projections
  - Uses historical revenue data from the last 5 fiscal years
  - Projects revenue for at least 5 years forward

  ## Output Quality
  - All figures are in a single .xlsx file with clearly labeled sheets
  `

  func main() {
  	ctx := context.Background()
  	client := anthropic.NewClient()

  	if err := os.WriteFile("/tmp/rubric.md", []byte(rubric), 0o644); err != nil {
  		panic(err)
  	}

  	f, err := os.Open("/tmp/rubric.md")
  	if err != nil {
  		panic(err)
  	}

  	uploaded, err := client.Files.Upload(ctx, anthropic.FileUploadParams{
  		File: anthropic.File(f, "rubric.md", "text/markdown"),
  	})
  	if err != nil {
  		panic(err)
  	}
  	fmt.Printf("Uploaded rubric: %s\n", uploaded.ID)
  ```

  ```java Java
  import com.anthropic.client.okhttp.AnthropicOkHttpClient;
  import com.anthropic.core.http.HttpResponse;
  import com.anthropic.models.beta.AnthropicBeta;
  import com.anthropic.models.beta.agents.AgentCreateParams;
  import com.anthropic.models.beta.agents.BetaManagedAgentsAgentToolset20260401Params;
  import com.anthropic.models.beta.agents.BetaManagedAgentsModel;
  import com.anthropic.models.beta.environments.BetaCloudConfigParams;
  import com.anthropic.models.beta.environments.BetaLimitedNetworkParams;
  import com.anthropic.models.beta.environments.EnvironmentCreateParams;
  import com.anthropic.models.beta.files.FileListParams;
  import com.anthropic.models.beta.sessions.SessionCreateParams;
  import com.anthropic.models.beta.sessions.events.BetaManagedAgentsTextRubricParams;
  import com.anthropic.models.beta.sessions.events.BetaManagedAgentsUserDefineOutcomeEventParams;
  import com.anthropic.models.beta.sessions.events.BetaManagedAgentsUserInterruptEventParams;
  import com.anthropic.models.beta.sessions.events.EventSendParams;
  import com.anthropic.models.files.FileUploadParams;

  import java.io.InputStream;
  import java.nio.file.Files;
  import java.nio.file.Path;
  import java.nio.file.StandardCopyOption;

  void main() throws Exception {
      var client = AnthropicOkHttpClient.fromEnv();

      var RUBRIC = """
          # DCF Model Rubric

          ## Revenue Projections
          - Uses historical revenue data from the last 5 fiscal years
          - Projects revenue for at least 5 years forward

          ## Output Quality
          - All figures are in a single .xlsx file with clearly labeled sheets
          """;
      Files.writeString(Path.of("/tmp/rubric.md"), RUBRIC);

      var rubric = client.files().upload(
          FileUploadParams.builder()
              .file(Path.of("/tmp/rubric.md"))
              .build());
      IO.println("Uploaded rubric: " + rubric.id());
  ```

  ```php PHP
  use Anthropic\Client;
  use Anthropic\Core\FileParam;

  $client = new Client();

  $rubricText = <<<'MD'
  # DCF Model Rubric

  ## Revenue Projections
  - Uses historical revenue data from the last 5 fiscal years
  - Projects revenue for at least 5 years forward

  ## Output Quality
  - All figures are in a single .xlsx file with clearly labeled sheets
  MD;
  file_put_contents('/tmp/rubric.md', $rubricText);

  $rubric = $client->files->upload(
      file: FileParam::fromResource(fopen('/tmp/rubric.md', 'r'), contentType: 'text/markdown'),
  );
  echo "Uploaded rubric: {$rubric->id}\n";
  ```

  ```ruby Ruby
  require "anthropic"
  require "pathname"

  client = Anthropic::Client.new

  RUBRIC = <<~MD
    # DCF Model Rubric

    ## Revenue Projections
    - Uses historical revenue data from the last 5 fiscal years
    - Projects revenue for at least 5 years forward

    ## Output Quality
    - All figures are in a single .xlsx file with clearly labeled sheets
  MD
  File.write("/tmp/rubric.md", RUBRIC)

  rubric = client.files.upload(file: Pathname.new("/tmp/rubric.md"))
  puts "Uploaded rubric: #{rubric.id}"
  ```
</CodeGroup>

## Creare una sessione con un esito

I seguenti esempi creano una [sessione](https://platform.claude.com/docs/it/managed-agents/sessions) per un [agente](https://platform.claude.com/docs/it/managed-agents/agent-setup) e un [ambiente](https://platform.claude.com/docs/it/managed-agents/environments) esistenti (entrambi creati separatamente), poi inviano un evento `user.define_outcome`. L'agente inizia a lavorare immediatamente. Non è richiesto alcun evento di messaggio utente aggiuntivo.

<CodeGroup>
  ```bash cURL
  # Create a session
  curl -fsSL https://api.anthropic.com/v1/sessions \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "anthropic-beta: managed-agents-2026-04-01" \
    --json '{
      "agent": "'"$AGENT_ID"'",
      "environment_id": "'"$ENVIRONMENT_ID"'",
      "title": "Financial analysis on Costco"
    }'

  # Define the outcome: SESSION_ID is the id from the create response
  # The agent starts working when it receives the event
  curl -fsSL "https://api.anthropic.com/v1/sessions/$SESSION_ID/events" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "anthropic-beta: managed-agents-2026-04-01" \
    --json '{
      "events": [
        {
          "type": "user.define_outcome",
          "description": "Build a DCF model for Costco in .xlsx",
          "rubric": {"type": "text", "content": "# DCF Model Rubric\n..."},
          "max_iterations": 5
        }
      ]
    }'
  # or: "rubric": {"type": "file", "file_id": "'"$RUBRIC_ID"'"}
  # "max_iterations" is optional; default 3, max 20
  ```

  ```bash CLI
  # Create a session
  ant beta:sessions create \
    --agent "$AGENT_ID" \
    --environment-id "$ENVIRONMENT_ID" \
    --title "Financial analysis on Costco"

  # Define the outcome: SESSION_ID is the id from the create response
  # The agent starts working when it receives the event
  ant beta:sessions:events send --session-id "$SESSION_ID" <<YAML
  events:
    - type: user.define_outcome
      description: Build a DCF model for Costco in .xlsx
      rubric: {type: file, file_id: $RUBRIC_ID}
      # or: rubric: {type: text, content: "..."}
      max_iterations: 5  # optional; default 3, max 20
  YAML
  ```

  ```python Python
  # Crea una sessione
  session = client.beta.sessions.create(
      agent=agent.id,
      environment_id=environment.id,
      title="Financial analysis on Costco",
  )

  # Definisci l'esito — l'agente inizia a lavorare alla ricezione
  client.beta.sessions.events.send(
      session_id=session.id,
      events=[
          {
              "type": "user.define_outcome",
              "description": "Build a DCF model for Costco in .xlsx",
              "rubric": {"type": "text", "content": RUBRIC},
              # oppure: "rubric": {"type": "file", "file_id": rubric.id},
              "max_iterations": 5,  # optional; default 3, max 20
          }
      ],
  )
  ```

  ```typescript TypeScript
  // Crea una sessione
  const session = await client.beta.sessions.create({
    agent: agent.id,
    environment_id: environment.id,
    title: "Financial analysis on Costco"
  });

  // Definisci l'esito — l'agente inizia a lavorare alla ricezione
  await client.beta.sessions.events.send(session.id, {
    events: [
      {
        type: "user.define_outcome",
        description: "Build a DCF model for Costco in .xlsx",
        rubric: { type: "text", content: RUBRIC },
        // oppure: rubric: { type: "file", file_id: rubric.id },
        max_iterations: 5 // optional; default 3, max 20
      }
    ]
  });
  ```

  ```csharp C#
  // Crea una sessione
  var session = await client.Beta.Sessions.Create(new()
  {
      Agent = agent.ID,
      EnvironmentID = environment.ID,
      Title = "Financial analysis on Costco",
  });

  // Definisci l'esito — l'agente inizia a lavorare alla ricezione
  await client.Beta.Sessions.Events.Send(session.ID, new()
  {
      Events =
      [
          new BetaManagedAgentsUserDefineOutcomeEventParams
          {
              Type = BetaManagedAgentsUserDefineOutcomeEventParamsType.UserDefineOutcome,
              Description = "Build a DCF model for Costco in .xlsx",
              Rubric = new BetaManagedAgentsTextRubricParams
              {
                  Type = BetaManagedAgentsTextRubricParamsType.Text,
                  Content = Rubric,
              },
              // oppure: Rubric = new BetaManagedAgentsFileRubricParams
              //     { Type = BetaManagedAgentsFileRubricParamsType.File, FileID = rubric.ID },
              MaxIterations = 5, // optional; default 3, max 20
          },
      ],
  });
  ```

  ```go Go
  // Crea una sessione
  session, err := client.Beta.Sessions.New(ctx, anthropic.BetaSessionNewParams{
  	Agent: anthropic.BetaSessionNewParamsAgentUnion{
  		OfString: anthropic.String(agent.ID),
  	},
  	EnvironmentID: environment.ID,
  	Title:         anthropic.String("Financial analysis on Costco"),
  })
  if err != nil {
  	panic(err)
  }

  // Definisci il risultato — l'agente inizia a lavorare alla ricezione
  _, err = client.Beta.Sessions.Events.Send(ctx, session.ID, anthropic.BetaSessionEventSendParams{
  	Events: []anthropic.BetaManagedAgentsEventParamsUnion{{
  		OfUserDefineOutcome: &anthropic.BetaManagedAgentsUserDefineOutcomeEventParams{
  			Type:        anthropic.BetaManagedAgentsUserDefineOutcomeEventParamsTypeUserDefineOutcome,
  			Description: "Build a DCF model for Costco in .xlsx",
  			Rubric: anthropic.BetaManagedAgentsUserDefineOutcomeEventParamsRubricUnion{
  				OfText: &anthropic.BetaManagedAgentsTextRubricParams{
  					Type:    anthropic.BetaManagedAgentsTextRubricParamsTypeText,
  					Content: rubric,
  				},
  			},
  			// oppure: OfFile: &anthropic.BetaManagedAgentsFileRubricParams{
  			//     Type: anthropic.BetaManagedAgentsFileRubricParamsTypeFile, FileID: uploaded.ID},
  			MaxIterations: anthropic.Int(5), // optional; default 3, max 20
  		},
  	}},
  })
  if err != nil {
  	panic(err)
  }
  ```

  ```java Java
  // Crea una sessione
  var session = client.beta().sessions().create(
      SessionCreateParams.builder()
          .agent(agent.id())
          .environmentId(environment.id())
          .title("Financial analysis on Costco")
          .build());

  // Definisci il risultato — l'agente inizia a lavorare alla ricezione
  client.beta().sessions().events().send(
      session.id(),
      EventSendParams.builder()
          .addEvent(BetaManagedAgentsUserDefineOutcomeEventParams.builder()
              .type(BetaManagedAgentsUserDefineOutcomeEventParams.Type.USER_DEFINE_OUTCOME)
              .description("Build a DCF model for Costco in .xlsx")
              .rubric(BetaManagedAgentsTextRubricParams.builder()
                  .type(BetaManagedAgentsTextRubricParams.Type.TEXT)
                  .content(RUBRIC)
                  .build())
              // oppure: .rubric(BetaManagedAgentsFileRubricParams.builder()
              //     .type(BetaManagedAgentsFileRubricParams.Type.FILE).fileId(rubric.id()).build())
              .maxIterations(5) // optional; default 3, max 20
              .build())
          .build());
  ```

  ```php PHP
  // Crea una sessione
  $session = $client->beta->sessions->create(
      agent: $agent->id,
      environmentID: $environment->id,
      title: 'Financial analysis on Costco',
  );

  // Definisci l'esito — l'agente inizia a lavorare alla ricezione
  $client->beta->sessions->events->send(
      $session->id,
      events: [
          [
              'type' => 'user.define_outcome',
              'description' => 'Build a DCF model for Costco in .xlsx',
              'rubric' => ['type' => 'text', 'content' => $rubricText],
              // oppure: 'rubric' => ['type' => 'file', 'file_id' => $rubric->id],
              'max_iterations' => 5, // optional; default 3, max 20
          ],
      ],
  );
  ```

  ```ruby Ruby
  # Crea una sessione
  session = client.beta.sessions.create(
    agent: agent.id,
    environment_id: environment.id,
    title: "Financial analysis on Costco"
  )

  # Definisci il risultato — l'agente inizia a lavorare alla ricezione
  client.beta.sessions.events.send_(
    session.id,
    events: [
      {
        type: "user.define_outcome",
        description: "Build a DCF model for Costco in .xlsx",
        rubric: {type: "text", content: RUBRIC},
        # oppure: rubric: {type: "file", file_id: rubric.id},
        max_iterations: 5 # optional; default 3, max 20
      }
    ]
  )
  ```
</CodeGroup>

<Note>
  Puoi anche definire l'esito nella richiesta di creazione stessa: passa un singolo evento `user.define_outcome` in [`initial_events` (java, php: `initialEvents`; csharp, go: `InitialEvents`)](https://platform.claude.com/docs/it/managed-agents/sessions#seed-the-session-with-initial-events) per creare la sessione e avviare il lavoro verso l'esito in un'unica chiamata.
</Note>

## Eventi di esito

Il progresso su una sessione orientata agli esiti viene mostrato sullo [stream](https://platform.claude.com/docs/it/managed-agents/events-and-streaming) degli eventi.

* Gli eventi `agent.*` (come messaggi e uso degli strumenti) mostrano il progresso verso l'esito.
* Gli eventi `span.outcome_evaluation_*` vengono emessi solo per le sessioni orientate agli esiti e mostrano il numero di cicli di iterazione e il processo di feedback del grader.
* Puoi anche inviare [eventi](https://platform.claude.com/docs/it/managed-agents/reference#event-types) `user.message` a una sessione orientata agli esiti per indirizzare il lavoro dell'agente man mano che procede, ma non è obbligatorio: l'agente lavora verso l'esito da solo, iterando finché non ci riesce o esaurisce le iterazioni.
* Un evento `user.interrupt` mette in pausa il lavoro sull'esito corrente e imposta il `result` (csharp, go: `Result`) dell'evento `span.outcome_evaluation_end` su `interrupted`, consentendoti di avviare un nuovo esito.
* Dopo la valutazione finale dell'esito, la sessione può essere continuata come sessione conversazionale, oppure può essere avviato un nuovo esito. La sessione conserva la cronologia dell'esito precedente.

### Evento utente di definizione dell'esito

<Note>
  È supportato un solo esito alla volta, ma puoi concatenare gli esiti in sequenza. Per farlo, invia un nuovo evento `user.define_outcome` dopo l'evento terminale `span.outcome_evaluation_end` dell'esito precedente.
</Note>

Questo è l'evento che invii per avviare un esito. Viene restituito come eco alla ricezione, includendo un timestamp `processed_at` (java, php: `processedAt`; csharp, go: `ProcessedAt`) e un `outcome_id` (java: `outcomeId`; php: `outcomeID`; csharp, go: `OutcomeID`).

```json
{
  "type": "user.define_outcome",
  "description": "Build a DCF model for Costco in .xlsx",
  "rubric": { "type": "file", "file_id": "file_01..." },
  "max_iterations": 5
}
```

### Inizio della valutazione dell'esito

Emesso una volta che il grader avvia una valutazione su un ciclo di iterazione. Il campo `iteration` è un contatore di revisioni con indice a partire da 0: `0` è la prima valutazione, `1` è la rivalutazione dopo la prima revisione, e così via.

```json
{
  "type": "span.outcome_evaluation_start",
  "id": "sevt_01def...",
  "outcome_id": "outc_01a...",
  "iteration": 0,
  "processed_at": "2026-03-25T14:01:45Z"
}
```

### Valutazione dell'esito in corso

Heartbeat emesso mentre il grader è in esecuzione. Il ragionamento interno del grader è opaco: vedi che sta lavorando, non cosa sta pensando.

```json
{
  "type": "span.outcome_evaluation_ongoing",
  "id": "sevt_01ghi...",
  "outcome_id": "outc_01a...",
  "iteration": 0,
  "processed_at": "2026-03-25T14:02:10Z"
}
```

### Fine della valutazione dell'esito

Emesso quando un ciclo di valutazione dell'esito termina: dopo che il grader ha finito di valutare un'iterazione, o quando la sessione viene interrotta mentre un esito è attivo. Il campo `result` indica cosa succede dopo.

| Risultato                | Successivo                                                                                                                                                                                                                                              |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `satisfied`              | La sessione passa a `idle`.                                                                                                                                                                                                                             |
| `needs_revision`         | L'agente avvia un nuovo ciclo di iterazione.                                                                                                                                                                                                            |
| `max_iterations_reached` | Segue un turno finale di conferma prima che la sessione passi a `idle`. Non viene eseguita alcuna ulteriore valutazione.                                                                                                                                |
| `failed`                 | La sessione passa a `idle`. Restituito quando la rubrica non si applica ai deliverable, ad esempio se la descrizione e la rubrica si contraddicono a vicenda.                                                                                           |
| `interrupted`            | Emesso quando la sessione viene interrotta mentre un esito è attivo, anche se la valutazione non era ancora iniziata. Se nessun `outcome_evaluation_start` è stato attivato prima dell'interruzione, `outcome_evaluation_start_id` è una stringa vuota. |

```json
{
  "type": "span.outcome_evaluation_end",
  "id": "sevt_01jkl...",
  "outcome_evaluation_start_id": "sevt_01def...",
  "outcome_id": "outc_01a...",
  "result": "satisfied",
  "explanation": "All 12 criteria met: revenue projections use 5 years of historical data, WACC assumptions are stated, sensitivity table is included...",
  "iteration": 0,
  "usage": {
    "input_tokens": 2400,
    "output_tokens": 350,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 1800
  },
  "processed_at": "2026-03-25T14:03:00Z"
}
```

## Verificare lo stato dell'esito

Puoi ascoltare sullo [stream degli eventi](https://platform.claude.com/docs/it/managed-agents/events-and-streaming) per `span.outcome_evaluation_end`, oppure effettuare il polling di `GET /v1/sessions/{session_id}` e leggere `outcome_evaluations[].result`. Finché una valutazione non è completata, `result` riporta `pending`, `running` o `evaluating`:

<CodeGroup>
  ```bash cURL
  curl -fsSL "https://api.anthropic.com/v1/sessions/$SESSION_ID" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "anthropic-beta: managed-agents-2026-04-01"
  ```

  ```bash CLI
  ant beta:sessions retrieve --session-id "$SESSION_ID"
  ```

  ```python Python
  session = client.beta.sessions.retrieve(session.id)

  for outcome in session.outcome_evaluations:
      print(f"{outcome.outcome_id}: {outcome.result}")
      # outc_01a...: satisfied
  ```

  ```typescript TypeScript
  const retrieved = await client.beta.sessions.retrieve(session.id);

  for (const outcome of retrieved.outcome_evaluations) {
    console.log(`${outcome.outcome_id}: ${outcome.result}`);
    // outc_01a...: satisfied
  }
  ```

  ```csharp C#
  session = await client.Beta.Sessions.Retrieve(session.ID);

  foreach (var outcome in session.OutcomeEvaluations)
  {
      Console.WriteLine($"{outcome.OutcomeID}: {outcome.Result}");
      // outc_01a...: satisfied
  }
  ```

  ```go Go
  session, err = client.Beta.Sessions.Get(ctx, session.ID, anthropic.BetaSessionGetParams{})
  if err != nil {
  	panic(err)
  }

  for _, outcome := range session.OutcomeEvaluations {
  	fmt.Printf("%s: %s\n", outcome.OutcomeID, outcome.Result)
  	// outc_01a...: satisfied
  }
  ```

  ```java Java
  var retrieved = client.beta().sessions().retrieve(session.id());

  for (var outcome : retrieved.outcomeEvaluations()) {
      IO.println(outcome.outcomeId() + ": " + outcome.result());
      // outc_01a...: satisfied
  }
  ```

  ```php PHP
  $session = $client->beta->sessions->retrieve($session->id);

  foreach ($session->outcomeEvaluations as $outcome) {
      echo "{$outcome->outcomeID}: {$outcome->result}\n";
      // outc_01a...: satisfied
  }
  ```

  ```ruby Ruby
  session = client.beta.sessions.retrieve(session.id)

  session.outcome_evaluations.each do
    puts "#{it.outcome_id}: #{it.result}"
    # outc_01a...: satisfied
  end
  ```
</CodeGroup>

## Recuperare i deliverable

L'agente scrive i file di output in `/mnt/session/outputs/` all'interno della sandbox. Per recuperarli, elenca i file tramite la [Files API](https://platform.claude.com/docs/it/build-with-claude/files) con l'ID della sessione come `scope_id` (java: `scopeId`; php: `scopeID`; csharp, go: `ScopeID`), quindi scaricali tramite ID. Il filtraggio per `scope_id` (java: `scopeId`; php: `scopeID`; csharp, go: `ScopeID`) richiede l'header beta `managed-agents-2026-04-01` nella richiesta di elenco, quindi gli esempi SDK e CLI effettuano quella chiamata tramite il namespace `beta` e passano l'header esplicitamente. I file compaiono nell'elenco poco dopo che l'agente ha finito di scriverli, a volte alcuni secondi dopo che la sessione è diventata inattiva. Se un file che ti aspetti non è ancora elencato, ripeti l'elenco dopo un breve intervallo; una volta che compare nell'elenco, il suo caricamento è terminato.

<CodeGroup>
  ```bash cURL
  # List files produced by this session
  # scope_id filtering requires the managed-agents beta
  curl -fsSL "https://api.anthropic.com/v1/files?scope_id=$SESSION_ID" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "anthropic-beta: managed-agents-2026-04-01"

  # Download a file by the ID from the list
  curl -fsSL "https://api.anthropic.com/v1/files/$FILE_ID/content" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "anthropic-beta: managed-agents-2026-04-01" \
    -o /tmp/output.txt
  ```

  ```bash CLI
  # List files produced by this session
  # scope_id filtering requires the managed-agents beta on the files request
  ant beta:files list --scope-id "$SESSION_ID" --beta managed-agents-2026-04-01

  # Download a file by the ID from the list
  ant files download --file-id "$FILE_ID" --output /tmp/output.txt
  ```

  ```python Python
  # Elenca i file prodotti da questa sessione
  # il filtro scope_id richiede la beta managed-agents nella richiesta files
  files = client.beta.files.list(scope_id=session.id, betas=["managed-agents-2026-04-01"])
  for file in files:
      print(file.id, file.filename)

  # Scarica un file
  if files.data:
      content = client.files.download(files.data[0].id)
      content.write_to_file("/tmp/output.txt")
  ```

  ```typescript TypeScript
  // Elenca i file prodotti da questa sessione
  // Il filtro scope_id richiede la beta managed-agents nella richiesta files
  const files = await client.beta.files.list({
    scope_id: session.id,
    betas: ["managed-agents-2026-04-01"]
  });
  for (const file of files.data) {
    console.log(file.id, file.filename);
  }

  // Scarica un file
  if (files.data.length > 0) {
    const content = await client.files.download(files.data[0].id);
    await writeFile("/tmp/output.txt", new Uint8Array(await content.arrayBuffer()));
  }
  ```

  ```csharp C#
  // Elenca i file prodotti da questa sessione
  // (il filtro scope_id richiede la beta managed-agents nella richiesta files)
  var files = await client.Beta.Files.List(new()
  {
      ScopeID = session.ID,
      Betas = ["managed-agents-2026-04-01"],
  });
  foreach (var file in files.Items)
  {
      Console.WriteLine($"{file.ID} {file.Filename}");
  }

  // Scarica un file
  if (files.Items.Count > 0)
  {
      using var download = await client.Files.Download(files.Items[0].ID);
      await using var output = File.Create("/tmp/output.txt");
      await (await download.ReadAsStream()).CopyToAsync(output);
  }
  ```

  ```go Go
  // Elenca i file prodotti da questa sessione
  // (il filtro scope_id richiede la beta managed-agents nella richiesta files)
  files, err := client.Beta.Files.List(ctx, anthropic.BetaFileListParams{
  	ScopeID: anthropic.String(session.ID),
  	Betas:   []anthropic.AnthropicBeta{anthropic.AnthropicBetaManagedAgents2026_04_01},
  })
  if err != nil {
  	panic(err)
  }
  for _, file := range files.Data {
  	fmt.Println(file.ID, file.Filename)
  }

  // Scarica un file
  if len(files.Data) > 0 {
  	resp, err := client.Files.Download(ctx, files.Data[0].ID, anthropic.FileDownloadParams{})
  	if err != nil {
  		panic(err)
  	}
  	defer resp.Body.Close()
  	out, err := os.Create("/tmp/output.txt")
  	if err != nil {
  		panic(err)
  	}
  	defer out.Close()
  	if _, err := io.Copy(out, resp.Body); err != nil {
  		panic(err)
  	}
  }
  ```

  ```java Java
  // Elenca i file prodotti da questa sessione
  // (il filtro scope_id richiede la beta managed-agents nella richiesta dei file)
  var files = client.beta().files().list(
      FileListParams.builder()
          .scopeId(session.id())
          .addBeta(AnthropicBeta.MANAGED_AGENTS_2026_04_01)
          .build());
  for (var file : files.data()) {
      IO.println(file.id() + " " + file.filename());
  }

  // Scarica un file
  if (!files.data().isEmpty()) {
      try (HttpResponse response = client.files().download(files.data().getFirst().id())) {
          try (InputStream body = response.body()) {
              Files.copy(body, Path.of("/tmp/output.txt"), StandardCopyOption.REPLACE_EXISTING);
          }
      }
  }
  ```

  ```php PHP
  // Elenca i file prodotti da questa sessione
  // Il filtro scope_id richiede la beta managed-agents nella richiesta files
  $files = $client->beta->files->list(scopeID: $session->id, betas: ['managed-agents-2026-04-01']);
  foreach ($files->getItems() as $file) {
      echo "{$file->id} {$file->filename}\n";
  }

  // Scarica un file
  if (count($files->getItems()) > 0) {
      $content = $client->files->download($files->getItems()[0]->id);
      file_put_contents('/tmp/output.txt', $content);
  }
  ```

  ```ruby Ruby
  # Elenca i file prodotti da questa sessione
  # Il filtro scope_id richiede la beta managed-agents nella richiesta dei file
  files = client.beta.files.list(scope_id: session.id, betas: ["managed-agents-2026-04-01"])
  files.data.each { |file| puts "#{file.id} #{file.filename}" }

  # Scarica un file
  if (first = files.data.first)
    content = client.files.download(first.id)
    File.binwrite("/tmp/output.txt", content.read)
  end
  ```
</CodeGroup>

## Passaggi successivi

<CardGroup cols={3}>
  <Card title="Autenticarsi con i vault" icon="fingerprint" href="https://platform.claude.com/docs/it/managed-agents/vaults">
    Registra credenziali per utente durante la creazione delle sessioni.
  </Card>

  <Card title="Stream degli eventi della sessione" icon="lightning" href="https://platform.claude.com/docs/it/managed-agents/events-and-streaming">
    Invia eventi, esegui lo streaming delle risposte e interrompi o reindirizza la tua sessione durante l'esecuzione.
  </Card>

  <Card title="Aggiungere file" icon="file" href="https://platform.claude.com/docs/it/managed-agents/files">
    Carica file e montali nella tua sandbox per la lettura e l'elaborazione.
  </Card>
</CardGroup>
