결과 정의하기

결과 정의하기 (Define outcomes)

outcome(결과)은 세션에게 최종 결과가 어떤 모습이어야 하고 품질을 어떻게 측정할지 알려줘요. 에이전트는 그 목표를 향해 작업하고, 스스로 평가하면서 반복하다가 outcome이 충족되면 멈춰요. outcome을 정의하면 실행 프레임워크(harness)가 산출물을 루브릭(rubric)에 대해 평가하는 grader(평가자)를 자동으로 프로비저닝하고, 그 평가자는 주 에이전트의 구현 선택에 영향을 받지 않도록 별도의 컨텍스트 창을 사용해요.

출처: 문서

본문

outcome은 세션에게 최종 결과가 어떤 모습이어야 하고 품질을 어떻게 측정할지 알려줘요. 에이전트는 그 목표를 향해 작업하며, outcome이 충족될 때까지 스스로 평가하고 반복해요.

outcome을 정의하면 실행 프레임워크가 산출물을 루브릭에 대해 평가할 grader를 자동으로 프로비저닝해요. grader는 주 에이전트의 구현 선택에 영향을 받지 않도록 별도의 컨텍스트 창을 사용해요.

grader는 어떤 기준이 통과했는지·실패했는지 요약한 설명을 반환하거나, 산출물이 루브릭을 충족함을 확인해요. 그 피드백은 다음 반복을 위해 에이전트에게 돌아가요.

Create a rubric

루브릭은 기준별 채점을 설명하는 마크다운 문서예요. 루브릭은 필수예요.

Structure the rubric as explicit, gradeable criteria, such as "The CSV contains a price column with numeric values" rather than "The data looks good." The grader scores each criterion independently, so vague criteria produce noisy evaluations.

If you don't have a rubric on hand, try giving Claude an example of a known-good artifact and asking it to analyze what makes that content good, then turn that analysis into a rubric. This middle-ground approach often produces better results than writing criteria from scratch.

루브릭 예시:

# 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(Create a session with an outcome)에 인라인 텍스트로 전달하거나, 여러 세션에서 재사용하려면 Files API를 통해 업로드하세요.

```bash cURL curl -fsSL https://api.anthropic.com/v1/files \ -H "x-api-key: $ANTHR...KEY" \ -H "anthropic-version: 2023-06-01" \ -H "anthropic-beta: managed-agents-2026-04-01" \ -F file=@/tmp/rubric.md ```
ant files upload --file /tmp/rubric.md
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}")
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}`);
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}");
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)
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.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());
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";
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}"

Create a session with an outcome

다음 예시는 기존 에이전트환경(둘 다 별도로 생성)에 대한 세션을 만든 다음 user.define_outcome 이벤트를 보내요. 에이전트는 즉시 작업을 시작하며, 추가 사용자 메시지 이벤트는 필요 없어요.

```bash cURL # Create a session session=$(curl -fsSL https://api.anthropic.com/v1/sessions \ -H "x-api-key: $ANTHR...KEY" \ -H "anthropic-version: 2023-06-01" \ -H "anthropic-beta: managed-agents-2026-04-01" \ --json @- <Define the outcome — agent starts working on receipt

curl -fsSL "https://api.anthropic.com/v1/sessions/$SESSION_ID/events"
-H "x-api-key: $ANTHR...KEY"
-H "anthropic-version: 2023-06-01"
-H "anthropic-beta: managed-agents-2026-04-01"
--json @- >/dev/null <<EOF { "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 } ] } EOF

or: "rubric": {"type": "file", "file_id": "$RUBRIC_ID"}

"max_iterations" is optional; default 3, max 20


```bash CLI
# Create a session
SESSION_ID=$(ant beta:sessions create \
  --agent "$AGENT_ID" \
  --environment-id "$ENVIRONMENT_ID" \
  --title "Financial analysis on Costco" \
  --transform id --raw-output)

# Define the outcome — agent starts working on receipt
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
# Create a session
session = client.beta.sessions.create(
    agent=agent.id,
    environment_id=environment.id,
    title="Financial analysis on Costco",
)

# Define the outcome — agent starts working on receipt
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},
            # or: "rubric": {"type": "file", "file_id": rubric.id},
            "max_iterations": 5,  # optional; default 3, max 20
        }
    ],
)
// Create a session
const session = await client.beta.sessions.create({
  agent: agent.id,
  environment_id: environment.id,
  title: "Financial analysis on Costco",
});

// Define the outcome — agent starts working on receipt
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 },
      // or: rubric: { type: "file", file_id: rubric.id },
      max_iterations: 5, // optional; default 3, max 20
    },
  ],
});
// Create a session
var session = await client.Beta.Sessions.Create(new()
{
    Agent = agent.ID,
    EnvironmentID = environment.ID,
    Title = "Financial analysis on Costco",
});

// Define the outcome — agent starts working on receipt
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,
            },
            // or: Rubric = new BetaManagedAgentsFileRubricParams
            //     { Type = BetaManagedAgentsFileRubricParamsType.File, FileID = rubric.ID },
            MaxIterations = 5, // optional; default 3, max 20
        },
    ],
});
// Create a session
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)
}

// Define the outcome — agent starts working on receipt
_, 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,
				},
			},
			// or: OfFile: &anthropic.BetaManagedAgentsFileRubricParams{
			//     Type: anthropic.BetaManagedAgentsFileRubricParamsTypeFile, FileID: uploaded.ID},
			MaxIterations: anthropic.Int(5), // optional; default 3, max 20
		},
	}},
})
if err != nil {
	panic(err)
}
// Create a session
var session = client.beta().sessions().create(
    SessionCreateParams.builder()
        .agent(agent.id())
        .environmentId(environment.id())
        .title("Financial analysis on Costco")
        .build());

// Define the outcome — agent starts working on receipt
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())
            // or: .rubric(BetaManagedAgentsFileRubricParams.builder()
            //     .type(BetaManagedAgentsFileRubricParams.Type.FILE).fileId(rubric.id()).build())
            .maxIterations(5) // optional; default 3, max 20
            .build())
        .build());
// Create a session
$session = $client->beta->sessions->create(
    agent: $agent->id,
    environmentID: $environment->id,
    title: 'Financial analysis on Costco',
);

// Define the outcome — agent starts working on receipt
$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],
            // or: 'rubric' => ['type' => 'file', 'file_id' => $rubric->id],
            'max_iterations' => 5, // optional; default 3, max 20
        ],
    ],
);
# Create a session
session = client.beta.sessions.create(
  agent: agent.id,
  environment_id: environment.id,
  title: "Financial analysis on Costco"
)

# Define the outcome — agent starts working on receipt
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},
      # or: rubric: {type: "file", file_id: rubric.id},
      max_iterations: 5 # optional; default 3, max 20
    }
  ]
)
You can also define the outcome in the create request itself: pass a single `user.define_outcome` event in [`initial_events`](https://platform.claude.com/docs/en/managed-agents/sessions#seed-the-session-with-initial-events) to create the session and start work toward the outcome in one call.

Outcome events

outcome 지향 세션의 진행은 이벤트 스트림에 표시돼요.

  • agent.* events (such as messages and tool use) show progress toward the outcome.
  • span.outcome_evaluation_* events are only emitted for outcome-oriented sessions and show the number of iteration loops and the grader's feedback process.
  • You can also send user.message events to an outcome-oriented session to direct the agent's work as it progresses, but it isn't required: the agent works toward the outcome on its own, iterating until it succeeds or runs out of iterations.
  • A user.interrupt event pauses work on the current outcome and marks the span.outcome_evaluation_end.result as interrupted, allowing you to kick off a new outcome.
  • After the final outcome evaluation, the session can be continued as a conversational session, or a new outcome can be started. The session retains history of the prior outcome.

Define outcome user event

Only one outcome is supported at a time, but you may chain outcomes in sequence. To do this, send a new `user.define_outcome` event after the terminal `span.outcome_evaluation_end` event of the previous outcome.

outcome을 시작하기 위해 보내는 이벤트예요. 수신 시 processed_at 타임스탬프와 outcome_id를 포함해 반향(echo)돼요.

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

Outcome evaluation start

grader가 한 번의 반복 루프에 대한 평가를 시작하면 발행돼요. iteration 필드는 0부터 시작하는 수정 카운터예요: 0은 첫 평가, 1은 첫 수정 후 재평가, 이런 식이에요.

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

Outcome evaluation ongoing

grader가 실행되는 동안 발행되는 하트비트예요. grader의 내부 추론은 불투명해요: 작업 중이라는 것만 보이고 무엇을 생각하는지는 보이지 않아요.

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

Outcome evaluation end

outcome 평가 주기가 끝나면 발행돼요: grader가 한 반복의 평가를 끝냈을 때, 또는 outcome이 활성인 동안 세션이 중단됐을 때요. result 필드는 다음에 일어날 일을 나타내요.

Result Next
satisfied Session transitions to idle.
needs_revision Agent starts a new iteration cycle.
max_iterations_reached One final acknowledgment turn follows before the session transitions to idle. No further evaluation runs.
failed Session transitions to idle. Returned when the rubric does not apply to the deliverables, for example if the description and rubric contradict each other.
interrupted Emitted when the session is interrupted while an outcome is active, even if evaluation hadn't started yet. If no outcome_evaluation_start fired before the interrupt, outcome_evaluation_start_id is an empty string.
{
  "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"
}

Check outcome status

이벤트 스트림에서 span.outcome_evaluation_end를 듣거나, GET /v1/sessions/{session_id}를 폴링해 outcome_evaluations[].result를 읽을 수 있어요. 평가가 완료될 때까지 resultpending, running, evaluating을 보고해요:

```bash cURL curl -fsSL "https://api.anthropic.com/v1/sessions/$SESSION_ID" \ -H "x-api-key: $ANTHR...KEY" \ -H "anthropic-version: 2023-06-01" \ -H "anthropic-beta: managed-agents-2026-04-01" ```
ant beta:sessions retrieve --session-id "$SESSION_ID"
session = client.beta.sessions.retrieve(session.id)

for outcome in session.outcome_evaluations:
    print(f"{outcome.outcome_id}: {outcome.result}")
    # outc_01a...: satisfied
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
}
session = await client.Beta.Sessions.Retrieve(session.ID);

foreach (var outcome in session.OutcomeEvaluations)
{
    Console.WriteLine($"{outcome.OutcomeID}: {outcome.Result}");
    // outc_01a...: satisfied
}
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
}
var retrieved = client.beta().sessions().retrieve(session.id());

for (var outcome : retrieved.outcomeEvaluations()) {
    IO.println(outcome.outcomeId() + ": " + outcome.result());
    // outc_01a...: satisfied
}
$session = $client->beta->sessions->retrieve($session->id);

foreach ($session->outcomeEvaluations as $outcome) {
    echo "{$outcome->outcomeID}: {$outcome->result}\n";
    // outc_01a...: satisfied
}
session = client.beta.sessions.retrieve(session.id)

session.outcome_evaluations.each do
  puts "#{it.outcome_id}: #{it.result}"
  # outc_01a...: satisfied
end

Retrieve deliverables

에이전트는 출력 파일을 샌드박스 안의 /mnt/session/outputs/에 써요. 가져오려면 Files API에서 세션 ID를 scope_id로 해 목록화한 다음, ID로 다운로드하세요. scope_id 필터링은 목록 요청에 managed-agents-2026-04-01 베타 헤더가 필요하므로, SDK와 CLI 예시는 beta 네임스페이스를 통해 그 호출을 하고 헤더를 명시적으로 전달해요. 파일은 에이전트가 쓰기를 마친 직후, 때로는 세션이 유휴 상태가 된 후 몇 초 뒤에 목록에 나타나요. 기대한 파일이 아직 나열되지 않았다면 잠시 후 다시 나열하세요. 목록에 나타나면 업로드가 끝난 거예요.

```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: $ANTHR...KEY" \ -H "anthropic-version: 2023-06-01" \ -H "anthropic-beta: managed-agents-2026-04-01"

Download a file

FILE_ID=$(curl -fsSL "https://api.anthropic.com/v1/files?scope_id=$SESSION_ID"
-H "x-api-key: $ANTHR...KEY"
-H "anthropic-version: 2023-06-01"
-H "anthropic-beta: managed-agents-2026-04-01" | jq -r '.data[0].id // empty') if [[ -n $FILE_ID ]]; then curl -fsSL "https://api.anthropic.com/v1/files/$FILE_ID/content"
-H "x-api-key: $ANTHR...KEY"
-H "anthropic-version: 2023-06-01"
-H "anthropic-beta: managed-agents-2026-04-01"
-o /tmp/output.txt fi


```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
FILE_ID=$(ant beta:files list --scope-id "$SESSION_ID" \
  --beta managed-agents-2026-04-01 \
  --transform 'data[0].id' --raw-output)
if [[ -n $FILE_ID ]]; then
  ant files download --file-id "$FILE_ID" --output /tmp/output.txt
fi
# List files produced by this session
# scope_id filtering requires the managed-agents beta on the files request
files = client.beta.files.list(scope_id=session.id, betas=["managed-agents-2026-04-01"])
for file in files:
    print(file.id, file.filename)

# Download a file
if files.data:
    content = client.files.download(files.data[0].id)
    content.write_to_file("/tmp/output.txt")
// List files produced by this session
// scope_id filtering requires the managed-agents beta on the files request
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);
}

// Download a 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()));
}
// List files produced by this session
// (scope_id filtering requires the managed-agents beta on the files request)
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}");
}

// Download a 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);
}
// List files produced by this session
// (scope_id filtering requires the managed-agents beta on the files request)
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)
}

// Download a 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)
	}
}
// List files produced by this session
// (scope_id filtering requires the managed-agents beta on the files request)
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());
}

// Download a 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);
        }
    }
}
// List files produced by this session
// scope_id filtering requires the managed-agents beta on the files request
$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";
}

// Download a file
if (count($files->getItems()) > 0) {
    $content = $client->files->download($files->getItems()[0]->id);
    file_put_contents('/tmp/output.txt', $content);
}
# List files produced by this session
# scope_id filtering requires the managed-agents beta on the files request
files = client.beta.files.list(scope_id: session.id, betas: ["managed-agents-2026-04-01"])
files.data.each { |file| puts "#{file.id} #{file.filename}" }

# Download a file
if (first = files.data.first)
  content = client.files.download(first.id)
  File.binwrite("/tmp/output.txt", content.read)
end

Next steps

Register per-user credentials when creating sessions. Send events, stream responses, and interrupt or redirect your session mid-execution. Upload files and mount them in your sandbox for reading and processing.

더 알아보기 (Learn more)