---
title: アウトカムを定義する
url: https://platform.claude.com/docs/ja/managed-agents/define-outcomes
description: エージェントに「完了」の状態を伝え、そこに到達するまで反復させます。
featureMetadata:
  topic:
    title: Managed Agents
    url: https://platform.claude.com/docs/en/managed-agents/overview
  status: beta
  betaHeader: managed-agents-2026-04-01
---

「outcome」（アウトカム）は、最終結果がどのようなものであるべきか、そしてその品質をどのように測定するかをセッションに伝えます。エージェントはその目標に向かって作業し、アウトカムが満たされるまで自己評価と反復を繰り返します。

アウトカムを定義すると、「harness」（ハーネス）が自動的に「*grader*」（グレーダー）をプロビジョニングし、「rubric」（ルーブリック）に照らして「artifact」（成果物）を評価します。グレーダーは、メインエージェントの実装上の選択に影響されないよう、別の「context window」（コンテキストウィンドウ）を使用します。

グレーダーは、どの基準が合格または不合格だったかを要約した説明、または成果物がルーブリックを満たしていることを確認する説明を返します。そのフィードバックは、次の反復のためにエージェントに渡されます。

## ルーブリックを作成する

ルーブリックは、基準ごとの採点方法を記述したMarkdownドキュメントです。ルーブリックは必須です。

<Accordion title="効果的なルーブリックを書くためのヒント">
  ルーブリックは、「データが良さそうに見える」ではなく「CSVに数値を含むprice列がある」のように、明示的で採点可能な基準として構成してください。グレーダーは各基準を個別に採点するため、曖昧な基準はばらつきのある評価につながります。

  手元にルーブリックがない場合は、良いことがわかっている成果物の例をClaudeに渡し、そのコンテンツの何が優れているのかを分析するよう依頼してから、その分析をルーブリックに変換してみてください。この中間的なアプローチは、基準をゼロから書くよりも良い結果を生むことがよくあります。
</Accordion>

ルーブリックの例：

```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
```

ルーブリックは、`user.define_outcome`にインラインテキストとして渡すか（[アウトカムを指定してセッションを作成する](https://platform.claude.com/docs/ja/managed-agents/define-outcomes#create-a-session-with-an-outcome)を参照）、セッション間で再利用するためにFiles APIを通じてアップロードします。

<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>

## アウトカムを指定してセッションを作成する

以下の例では、既存の[エージェント](https://platform.claude.com/docs/ja/managed-agents/agent-setup)と[環境](https://platform.claude.com/docs/ja/managed-agents/environments)（いずれも別途作成済み）に対して[セッション](https://platform.claude.com/docs/ja/managed-agents/sessions)を作成し、`user.define_outcome`イベントを送信します。エージェントはすぐに作業を開始します。追加のユーザーメッセージイベントは必要ありません。

<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
  # セッションを作成
  session = client.beta.sessions.create(
      agent=agent.id,
      environment_id=environment.id,
      title="Financial analysis on Costco",
  )

  # 成果を定義 — エージェントは受信時に作業を開始します
  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},
              # または: "rubric": {"type": "file", "file_id": rubric.id},
              "max_iterations": 5,  # optional; default 3, max 20
          }
      ],
  )
  ```

  ```typescript TypeScript
  // セッションを作成
  const session = await client.beta.sessions.create({
    agent: agent.id,
    environment_id: environment.id,
    title: "Financial analysis on Costco"
  });

  // 成果を定義 — エージェントは受信時に作業を開始します
  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 },
        // または: rubric: { type: "file", file_id: rubric.id },
        max_iterations: 5 // optional; default 3, max 20
      }
    ]
  });
  ```

  ```csharp C#
  // セッションを作成
  var session = await client.Beta.Sessions.Create(new()
  {
      Agent = agent.ID,
      EnvironmentID = environment.ID,
      Title = "Financial analysis on Costco",
  });

  // 成果を定義 — エージェントは受信時に作業を開始します
  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,
              },
              // または: Rubric = new BetaManagedAgentsFileRubricParams
              //     { Type = BetaManagedAgentsFileRubricParamsType.File, FileID = rubric.ID },
              MaxIterations = 5, // optional; default 3, max 20
          },
      ],
  });
  ```

  ```go Go
  // セッションを作成
  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)
  }

  // 成果を定義 — エージェントは受信時に作業を開始します
  _, 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,
  				},
  			},
  			// または: 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
  // セッションを作成
  var session = client.beta().sessions().create(
      SessionCreateParams.builder()
          .agent(agent.id())
          .environmentId(environment.id())
          .title("Financial analysis on Costco")
          .build());

  // 成果を定義 — エージェントは受信時に作業を開始します
  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())
              // または: .rubric(BetaManagedAgentsFileRubricParams.builder()
              //     .type(BetaManagedAgentsFileRubricParams.Type.FILE).fileId(rubric.id()).build())
              .maxIterations(5) // optional; default 3, max 20
              .build())
          .build());
  ```

  ```php PHP
  // セッションを作成
  $session = $client->beta->sessions->create(
      agent: $agent->id,
      environmentID: $environment->id,
      title: 'Financial analysis on Costco',
  );

  // 成果を定義 — エージェントは受信時に作業を開始します
  $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],
              // または: 'rubric' => ['type' => 'file', 'file_id' => $rubric->id],
              'max_iterations' => 5, // optional; default 3, max 20
          ],
      ],
  );
  ```

  ```ruby Ruby
  # セッションを作成
  session = client.beta.sessions.create(
    agent: agent.id,
    environment_id: environment.id,
    title: "Financial analysis on Costco"
  )

  # 成果を定義 — エージェントは受信時に作業を開始します
  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},
        # または: rubric: {type: "file", file_id: rubric.id},
        max_iterations: 5 # optional; default 3, max 20
      }
    ]
  )
  ```
</CodeGroup>

<Note>
  作成リクエスト自体でアウトカムを定義することもできます。[`initial_events` (java, php: `initialEvents`; csharp, go: `InitialEvents`)](https://platform.claude.com/docs/ja/managed-agents/sessions#seed-the-session-with-initial-events)に単一の`user.define_outcome`イベントを渡すと、1回の呼び出しでセッションを作成し、アウトカムに向けた作業を開始できます。
</Note>

## アウトカムイベント

アウトカム指向のセッションの進捗は、イベント[ストリーム](https://platform.claude.com/docs/ja/managed-agents/events-and-streaming)上に表示されます。

* `agent.*`イベント（メッセージやツール使用など）は、アウトカムに向けた進捗を示します。
* `span.outcome_evaluation_*`イベントはアウトカム指向のセッションでのみ発行され、反復ループの回数とグレーダーのフィードバックプロセスを示します。
* アウトカム指向のセッションに`user.message`[イベント](https://platform.claude.com/docs/ja/managed-agents/reference#event-types)を送信して、進行中のエージェントの作業を指示することもできますが、必須ではありません。エージェントは自律的にアウトカムに向けて作業し、成功するか反復回数の上限に達するまで反復を続けます。
* `user.interrupt`イベントは現在のアウトカムに対する作業を一時停止し、`span.outcome_evaluation_end`イベントの`result` (csharp, go: `Result`)を`interrupted`としてマークするため、新しいアウトカムを開始できるようになります。
* 最後のアウトカム評価の後、セッションは会話型セッションとして継続することも、新しいアウトカムを開始することもできます。セッションは以前のアウトカムの履歴を保持します。

### アウトカム定義ユーザーイベント

<Note>
  一度にサポートされるアウトカムは1つだけですが、アウトカムを順番に連鎖させることはできます。そのためには、前のアウトカムの終端となる`span.outcome_evaluation_end`イベントの後に、新しい`user.define_outcome`イベントを送信します。
</Note>

これはアウトカムを開始するために送信するイベントです。受信時に、`processed_at` (java, php: `processedAt`; csharp, go: `ProcessedAt`)タイムスタンプと`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
}
```

### アウトカム評価の開始

グレーダーが1回の反復ループに対する評価を開始したときに発行されます。`iteration`フィールドは0から始まるリビジョンカウンターです。`0`は最初の評価、`1`は最初の修正後の再評価、というように続きます。

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

### アウトカム評価の進行中

グレーダーの実行中に発行されるハートビートです。グレーダーの内部推論は不透明です。グレーダーが動作していることはわかりますが、何を考えているかはわかりません。

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

### アウトカム評価の終了

アウトカム評価サイクルが終了したとき、つまりグレーダーが1回の反復の評価を終えたとき、またはアウトカムがアクティブな間にセッションが中断されたときに発行されます。`result`フィールドは次に何が起こるかを示します。

| 結果                       | 次の動作                                                                                                                                        |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `satisfied`              | セッションは`idle`に移行します。                                                                                                                         |
| `needs_revision`         | エージェントが新しい反復サイクルを開始します。                                                                                                                     |
| `max_iterations_reached` | セッションが`idle`に移行する前に、最後の確認ターンが1回行われます。それ以上の評価は実行されません。                                                                                       |
| `failed`                 | セッションは`idle`に移行します。ルーブリックが成果物に適用できない場合、たとえば説明とルーブリックが互いに矛盾している場合に返されます。                                                                     |
| `interrupted`            | アウトカムがアクティブな間にセッションが中断されたときに、評価がまだ開始されていなかった場合でも発行されます。中断前に`outcome_evaluation_start`が発行されていなかった場合、`outcome_evaluation_start_id`は空文字列になります。 |

```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"
}
```

## アウトカムのステータスを確認する

[イベントストリーム](https://platform.claude.com/docs/ja/managed-agents/events-and-streaming)で`span.outcome_evaluation_end`をリッスンするか、`GET /v1/sessions/{session_id}`をポーリングして`outcome_evaluations[].result`を読み取ることができます。評価が完了するまで、`result`は`pending`、`running`、または`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>

## 成果物を取得する

エージェントは、サンドボックス内の`/mnt/session/outputs/`に出力ファイルを書き込みます。それらを取得するには、セッションIDを`scope_id` (java: `scopeId`; php: `scopeID`; csharp, go: `ScopeID`)として[Files API](https://platform.claude.com/docs/ja/build-with-claude/files)でファイルを一覧表示し、IDを指定してダウンロードします。`scope_id` (java: `scopeId`; php: `scopeID`; csharp, go: `ScopeID`)によるフィルタリングには一覧リクエストに`managed-agents-2026-04-01`ベータヘッダーが必要なため、SDKとCLIの例では`beta`名前空間を通じてその呼び出しを行い、ヘッダーを明示的に渡しています。ファイルは、エージェントが書き込みを終えた直後に一覧に表示されますが、セッションがアイドル状態になってから数秒後になることもあります。期待するファイルがまだ一覧にない場合は、少し待ってから再度一覧を取得してください。一覧に表示された時点で、そのアップロードは完了しています。

<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
  # このセッションで生成されたファイルを一覧表示
  # scope_id フィルタリングにはファイルリクエストで managed-agents ベータが必要です
  files = client.beta.files.list(scope_id=session.id, betas=["managed-agents-2026-04-01"])
  for file in files:
      print(file.id, file.filename)

  # ファイルをダウンロード
  if files.data:
      content = client.files.download(files.data[0].id)
      content.write_to_file("/tmp/output.txt")
  ```

  ```typescript TypeScript
  // このセッションで生成されたファイルを一覧表示
  // scope_id によるフィルタリングには、files リクエストで managed-agents ベータが必要です
  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);
  }

  // ファイルをダウンロード
  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#
  // このセッションで生成されたファイルを一覧表示
  // （scope_id によるフィルタリングには、files リクエストで managed-agents ベータが必要です）
  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}");
  }

  // ファイルをダウンロード
  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
  // このセッションで生成されたファイルを一覧表示
  // （scope_id によるフィルタリングには、files リクエストで managed-agents ベータが必要です）
  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)
  }

  // ファイルをダウンロード
  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
  // このセッションで生成されたファイルを一覧表示
  // （scope_id によるフィルタリングには、files リクエストで managed-agents ベータが必要です）
  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());
  }

  // ファイルをダウンロード
  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
  // このセッションで生成されたファイルを一覧表示
  // scope_id によるフィルタリングには、files リクエストで managed-agents ベータが必要です
  $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";
  }

  // ファイルをダウンロード
  if (count($files->getItems()) > 0) {
      $content = $client->files->download($files->getItems()[0]->id);
      file_put_contents('/tmp/output.txt', $content);
  }
  ```

  ```ruby Ruby
  # このセッションで生成されたファイルを一覧表示
  # scope_id によるフィルタリングには、files リクエストで managed-agents ベータが必要です
  files = client.beta.files.list(scope_id: session.id, betas: ["managed-agents-2026-04-01"])
  files.data.each { |file| puts "#{file.id} #{file.filename}" }

  # ファイルをダウンロード
  if (first = files.data.first)
    content = client.files.download(first.id)
    File.binwrite("/tmp/output.txt", content.read)
  end
  ```
</CodeGroup>

## 次のステップ

<CardGroup cols={3}>
  <Card title="Vaultで認証する" icon="fingerprint" href="https://platform.claude.com/docs/ja/managed-agents/vaults">
    セッション作成時にユーザーごとの認証情報を登録します。
  </Card>

  <Card title="セッションイベントストリーム" icon="lightning" href="https://platform.claude.com/docs/ja/managed-agents/events-and-streaming">
    イベントを送信し、レスポンスをストリーミングし、実行中のセッションを中断またはリダイレクトします。
  </Card>

  <Card title="ファイルの追加" icon="file" href="https://platform.claude.com/docs/ja/managed-agents/files">
    ファイルをアップロードし、読み取りと処理のためにサンドボックスにマウントします。
  </Card>
</CardGroup>
