self-hosted-sandboxes-workers changedmanaged-agents/self-hosted-sandboxes-workers
Nearest release: v2.1.328, published 7 hours after this site recorded the change. Shown because the two are within 24 hours of each other. Nothing here says the release caused the edit.
Recorded here
Lines+49added
Lines−487removed
From line
1
where the diff opens
First seen
2 Oct 2026
this site's first read of the page
Recorded edits37to this page, all time
## Run one sandbox per session ### Forward the work item’s secret ### Launch sandboxes from the SDK poller ### Run the SDK worker inside the sandbox ## Stage files for a session
The whole hunk
from line 1, old and new numbered
/
The two sides of this change are more than 400 edits apart, too far apart to line up, so this is the differ's own diff of it and the words inside a line are not marked.
from line 1
11---
22title: Deploy self-hosted workers
33url: https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers
4description: "Choose how self-hosted sandbox workers claim work and where sessions run: always-on or webhook-triggered, in one process or one sandbox per session."
4description: Choose how self-hosted sandbox workers claim work and where sessions run, then run an always-on worker or trigger workers from webhooks.
55featureMetadata:
66 topic:
77 title: Managed Agents
from line 36
3636 Claude Platform on AWS: beta
3737---
3838
39The [quickstart](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes#quickstart) runs one `ant` CLI worker that polls continuously and runs every session in one process. This page covers the other ways to run a worker and how to choose among them.
39The [self-hosted sandboxes quickstart](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes#quickstart) runs one `ant` CLI worker that polls continuously and runs every session in one process. This page helps you choose a deployment pattern and then covers always-on and webhook-triggered workers.
4040
4141## Choose a deployment pattern
4242
from line 44
4444
4545**How the worker claims work:**
4646
47* **Always-on:** A long-running process polls the queue continuously and needs only outbound HTTPS. This is the simplest setup.
47* **Always-on:** A long-running process polls the queue continuously. The process makes only outbound HTTPS requests, so you don’t expose an endpoint to Anthropic.
4848* **Webhook-triggered:** A handler wakes on `session.status_run_started` and starts polling. This avoids an idle poller, but requires a [webhook](https://platform.claude.com/docs/en/managed-agents/webhooks) endpoint that Anthropic can reach.
4949
5050**Where each session runs:**
5151
5252* **In process:** The worker that claims a session also runs its tool calls, in one shared working directory.
53* **Sandbox per session:** A poller launches a fresh sandbox for each claimed session. Choose this for stronger isolation: a fresh filesystem, resource limits, or per-session network controls.
53* **Sandbox per session:** A poller launches a fresh sandbox for each claimed session. Choose this for stronger isolation: a fresh filesystem, resource limits, or per-session network controls. See [Run one sandbox per session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session), which also covers the Helm chart for Kubernetes.
5454
5555The CLI and SDK workers support different combinations:
5656
57| Capability | `ant` CLI | SDK (Python, TypeScript, Go) |
58| ----------------------------------------------------------------------------------------------------- | ------------------------------- | ---------------------------- |
59| Always-on polling | Yes | Yes |
60| Webhook-triggered | No | Yes |
61| Sandbox per session | Yes | Yes |
62| [Memory stores](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory) | Yes, with default sync settings | Yes, with configurable sync |
63| [Custom tools](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-custom-tools) | No | Yes |
64
65See [Self-hosted worker reference](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference) for every CLI flag and SDK option. For more control, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work) directly and implement your own worker.
57| Capability | `ant` CLI | SDK (Python, TypeScript, Go) |
58| ----------------------------------------------------------------------------------------------------------- | ------------------------------- | ---------------------------- |
59| Always-on polling | Yes | Yes |
60| Webhook-triggered | No | Yes |
61| [Sandbox per session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session) | Yes | Yes |
62| [Memory stores](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory) | Yes, with default sync settings | Yes, with configurable sync |
63| [Custom tools](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-custom-tools) | No | Yes |
64
65See [Self-hosted worker reference](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference) for every CLI flag and SDK option.
66
67For more control, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work) directly and implement your own worker. Your worker then does what the SDK workers do. Among other things, it acknowledges each work item, sends heartbeats, and downloads the agent’s skills. It runs only the tool calls that the session’s [permission policy](https://platform.claude.com/docs/en/managed-agents/permission-policies#see-how-each-call-was-evaluated) allows. It returns each result as a `user.tool_result` or `user.custom_tool_result` event. At the end, it stops the item. Use the worker’s source in the [Python SDK](https://github.com/anthropics/anthropic-sdk-python/tree/main/src/anthropic/lib/environments), the [TypeScript SDK](https://github.com/anthropics/anthropic-sdk-typescript/tree/main/src/lib/environments), or the [Go SDK](https://github.com/anthropics/anthropic-sdk-go/tree/main/lib/environments) as a reference.
6668
6769## Run an always-on worker
6870
71These samples use `/workspace` as the worker’s working directory. The directory must exist before the worker starts. On a new host, create it and give the worker’s user write access, as in the “Start the worker” step of [Run your first session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes#run-your-first-session).
72
73On macOS, `mkdir` can’t create `/workspace`, because the root volume is read-only. Create `~/workspace` instead, as that step shows. In place of `/workspace`, use the full path that `echo ~/workspace` prints, because the SDK doesn’t expand `~`.
74
6975Start a worker that polls the queue continuously. It authenticates with the [environment key](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes#run-your-first-session) from the quickstart:
7076
7177<CodeGroup exclude="shell:cURL, csharp, java, php, ruby">
78 <CodeGroupItem language="cURL">
79 A worker is a long-running process, not a single HTTP request. Run the `ant` CLI worker instead: `ant beta:worker poll --workdir /workspace`.
80 </CodeGroupItem>
81
7282 ```bash CLI
7383 ant beta:worker poll --workdir /workspace
7484 ```
from line 103
93103 workdir="/workspace",
94104 )
95105 task = asyncio.create_task(worker.run())
96 # Cancelling the task, rather than killing the process, lets the worker stop its
106 # Canceling the task, rather than killing the process, lets the worker stop its
97107 # in-flight work item and upload changed memory files before it exits.
98108 loop = asyncio.get_running_loop()
99109 for signum in (signal.SIGINT, signal.SIGTERM):
from line 193
183193
184194<Steps>
185195 <Step title="Subscribe to session webhooks">
186 In the [Claude Console](https://platform.claude.com/settings/workspaces/default/webhooks), define a webhook endpoint that listens for `session.status_run_started` events. See [Webhooks](https://platform.claude.com/docs/en/managed-agents/webhooks) for details.
196 In the [Claude Console](https://platform.claude.com/settings/workspaces/default/webhooks), define a webhook endpoint that listens for `session.status_run_started` events. See [Subscribe to webhooks](https://platform.claude.com/docs/en/managed-agents/webhooks) for details.
187197 </Step>
188198
189199 <Step title="Export the webhook signing key">
from line 205
195205 </Step>
196206
197207 <Step title="Implement the webhook handler">
198 Start the worker when `session.status_run_started` fires. The handler drains the queue and hands each claimed work item to `handle_item()` (typescript: `handleItem()`; go: `HandleItem()`), which downloads skills, runs tool calls, posts results back, and returns.
208 Start the worker when `session.status_run_started` fires. The handler drains the queue and hands each claimed work item to `handle_item()` (typescript: `handleItem()`; go: `HandleItem()`) (in the Python, TypeScript, and Go SDKs). That method downloads skills, runs tool calls, posts results back, and returns.
209
210 The samples use `/workspace` as the working directory. Before you start the handler, create that directory on the handler host. Make sure that the handler’s user can write to it, as in the “Start the worker” step of [Run your first session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes#run-your-first-session).
199211
200212 <CodeGroup exclude="shell, csharp, java, php, ruby">
213 <CodeGroupItem language="cURL">
214 This handler needs more logic than a single shell command. Use the Python, TypeScript, or Go SDK to run it.
215 </CodeGroupItem>
216
217 <CodeGroupItem language="CLI">
218 This handler needs more logic than a single shell command. Use the Python, TypeScript, or Go SDK to run it.
219 </CodeGroupItem>
220
201221 <CodeGroupItem>
202222 To verify webhook signatures, install the webhooks extra: `pip install "anthropic[webhooks]"`.
203223
from line 232
212232 client = anthropic.AsyncAnthropic(
213233 auth_token=environment_key,
214234 )
215 # Cancelled by shutdown() so an in-flight work item can upload changed memory files and
235 # Canceled by shutdown() so an in-flight work item can upload changed memory files and
216236 # remove its store directories before the process exits.
217237 inflight: set[asyncio.Task[None]] = set()
218238
from line 341
321341 ```
322342
323343 <CodeGroupItem language="C#">
324 The C# SDK does not have `EnvironmentWorker`. To handle work items from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work).
344 The C# SDK does not have `EnvironmentWorker`. To handle work items from your own code, implement your own worker, as [Choose a deployment pattern](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#choose-a-deployment-pattern) describes.
325345 </CodeGroupItem>
326346
327347 ```go Go
from line 374
354374 worker = environments.NewEnvironmentWorker(client, environments.EnvironmentWorkerOptions{
355375 Workdir: "/workspace",
356376 })
357 // Cancelled on SIGINT or SIGTERM (set in main) so an in-flight work item can
377 // Canceled on SIGINT or SIGTERM (set in main) so an in-flight work item can
358378 // upload changed memory files and remove its store directories before exit.
359379 shutdown context.Context
360380 )
from line 455
435455 ```
436456
437457 <CodeGroupItem language="Java">
438 The Java SDK does not have `EnvironmentWorker`. To handle work items from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work).
458 The Java SDK does not have `EnvironmentWorker`. To handle work items from your own code, implement your own worker, as [Choose a deployment pattern](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#choose-a-deployment-pattern) describes.
439459 </CodeGroupItem>
440460
441461 <CodeGroupItem language="PHP">
442 The PHP SDK does not have `EnvironmentWorker`. To handle work items from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work).
462 The PHP SDK does not have `EnvironmentWorker`. To handle work items from your own code, implement your own worker, as [Choose a deployment pattern](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#choose-a-deployment-pattern) describes.
443463 </CodeGroupItem>
444464
445465 <CodeGroupItem language="Ruby">
446 The Ruby SDK does not have `EnvironmentWorker`. To handle work items from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work).
466 The Ruby SDK does not have `EnvironmentWorker`. To handle work items from your own code, implement your own worker, as [Choose a deployment pattern](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#choose-a-deployment-pattern) describes.
447467 </CodeGroupItem>
448468 </CodeGroup>
449469
450 Because the handler claims work itself, it must [forward the work item’s secret](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#forward-the-work-items-secret), as the `work_secret` (typescript: `workSecret`; go: `WorkSecret`) argument does here.
470 In the Python, TypeScript, and Go SDKs, `handle_item()` (typescript: `handleItem()`; go: `HandleItem()`) needs the work item’s secret to mount memory stores. A worker that polls with `run()` (go: `Run()`) already has the secret. This handler claims each item itself, so it passes the secret in the `work_secret` (typescript: `workSecret`; go: `WorkSecret`) argument. See [Forward the work item’s secret](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#forward-the-work-items-secret).
451471 </Step>
452472</Steps>
453473
454This handler runs every claimed item in one process on one host. If your sessions attach the same memory store, see [Isolate sessions that share a store](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#isolate-sessions-that-share-a-store).
455
456## Run one sandbox per session
457
458A poller on the host claims work and calls your script once for each work item. The script launches a sandbox for that one session.
459
460<Steps>
461 <Step title="Build the sandbox image">
462 Install `ant` and set `ant beta:worker run` as the entrypoint. When a sandbox starts, it reads session details from environment variables, handles that session, and exits. The base image must provide `/bin/bash`; `curl` is only used at build time.
463
464 ```dockerfile
465 FROM your-base-image
466 ARG ANT_VERSION=2.11.0
467 ARG TARGETARCH
468 RUN ARCH=$([ "$TARGETARCH" = "arm64" ] && echo arm64 || echo amd64) && \
469 curl -fsSL "https://github.com/anthropics/anthropic-cli/releases/download/v${ANT_VERSION}/ant_${ANT_VERSION}_linux_${ARCH}.tar.gz" \
470 | tar -xz -C /usr/local/bin ant
471 WORKDIR /workspace
472 VOLUME /workspace
473 ENTRYPOINT ["ant", "beta:worker", "run"]
474 ```
475 </Step>
476
477 <Step title="Write the spawn script">
478 The script forwards the session details into a fresh sandbox. It requires `jq` on the poller host.
479
480 ```bash
481 #!/bin/bash
482 # spawn.sh: called once for each claimed work item
483 # The claimed work item arrives as JSON on stdin.
484 ANTHROPIC_WORK_SECRET="$(jq -r '.secret // empty')"
485 export ANTHROPIC_WORK_SECRET
486 mkdir -p "/host/outputs/$ANTHROPIC_SESSION_ID"
487 exec docker run --rm \
488 -e ANTHROPIC_SESSION_ID -e ANTHROPIC_ENVIRONMENT_KEY \
489 -e ANTHROPIC_WORK_ID -e ANTHROPIC_ENVIRONMENT_ID -e ANTHROPIC_BASE_URL \
490 -e ANTHROPIC_WORK_SECRET \
491 -v "/host/outputs/$ANTHROPIC_SESSION_ID":/workspace \
492 your-image
493 ```
494
495 The poller sets the `ANTHROPIC_*` variables that the script forwards, except the secret. See [Environment variables](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference#environment-variables).
496
497 `/host/outputs` is a host directory you choose. Mounting it at `/workspace` lets you retrieve the session’s deliverables after the sandbox exits. The mount also picks up the downloaded `skills/` tree and any intermediate files.
498 </Step>
499
500 <Step title="Start the poller">
501 ```bash
502 ant beta:worker poll --on-work ./spawn.sh
503 ```
504 </Step>
505</Steps>
506
507### Forward the work item’s secret
508
509Each claimed work item can carry a per-session `secret` (csharp, go: `Secret`), which Anthropic issues. The worker that runs the session needs it to mount [memory stores](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory).
510
511A worker that claims and runs sessions in one process (`ant beta:worker poll` without `--on-work`, or `EnvironmentWorker` with `run()` (go: `Run()`)) passes the secret along itself. When your own code sits between the claim and the worker, you forward it:
512
513| You claim work with | The secret arrives as | Pass it to the worker as |
514| -------------------------------------------------------------- | ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
515| `ant beta:worker poll --on-work` | The `secret` field of the work item JSON on your script’s standard input | `ANTHROPIC_WORK_SECRET` in the sandbox’s environment |
516| The SDK’s `work.poller()` (go: `environments.NewWorkPoller()`) | The `secret` (go: `Secret`) field of each claimed work item | `ANTHROPIC_WORK_SECRET` in the sandbox’s environment, or the `work_secret` (typescript: `workSecret`; go: `WorkSecret`) argument to `handle_item()` (typescript: `handleItem()`; go: `HandleItem()`) |
517
518Pass the secret only into the sandbox that serves that session, and never log it. See [Security model](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-security) for how it relates to the environment key.
519
520### Launch sandboxes from the SDK poller
521
522To claim work from your own code instead of `ant beta:worker poll --on-work`, use `work.poller()` (typescript: `new WorkPoller()`; go: `environments.NewWorkPoller()`). It polls the queue and gives you each claimed session, and you launch the sandbox:
523
524<CodeGroup exclude="shell, csharp, java, php, ruby">
525 <CodeGroupItem language="cURL">
526 Claiming work in a loop and launching a sandbox for each session needs more logic than a single shell command. From the shell, run `ant beta:worker poll --on-work` with a spawn script, as in [Run one sandbox per session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#run-one-sandbox-per-session).
527 </CodeGroupItem>
528
529 <CodeGroupItem language="CLI">
530 To claim work from the shell and launch a sandbox for each session, run `ant beta:worker poll --on-work` with a spawn script, as in [Run one sandbox per session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#run-one-sandbox-per-session).
531 </CodeGroupItem>
532
533 ```python Python
534 import asyncio
535 import os
536
537 from anthropic import AsyncAnthropic
538 from anthropic.types.beta.environments import BetaSelfHostedWork
539
540 SANDBOX_ENV = (
541 "ANTHROPIC_ENVIRONMENT_ID",
542 "ANTHROPIC_ENVIRONMENT_KEY",
543 "ANTHROPIC_WORK_ID",
544 "ANTHROPIC_SESSION_ID",
545 "ANTHROPIC_WORK_SECRET",
546 "ANTHROPIC_BASE_URL", # forwarded only when set on this host
547 )
548
549
550 async def launch_container(work: BetaSelfHostedWork) -> None:
551 print(f"claimed session {work.data.id}")
552 # Replace `docker run` with your own sandbox launcher. Forward the environment
553 # key (never your API key) and the work item's per-session secret: the worker
554 # inside needs the secret to mount the session's memory stores.
555 env = os.environ | {
556 "ANTHROPIC_WORK_ID": work.id,
557 "ANTHROPIC_SESSION_ID": work.data.id,
558 "ANTHROPIC_WORK_SECRET": work.secret or "",
559 }
560 forward = [arg for name in SANDBOX_ENV for arg in ("-e", name)]
561 launcher = await asyncio.create_subprocess_exec(
562 "docker", "run", "--rm", "--detach", *forward, "your-image", env=env
563 )
564 await launcher.wait()
565
566
567 async def main() -> None:
568 environment_key = os.environ["ANTHROPIC_ENVIRONMENT_KEY"]
569 environment_id = os.environ["ANTHROPIC_ENVIRONMENT_ID"]
570 async with AsyncAnthropic(auth_token=environment_key) as client:
571 async for work in client.beta.environments.work.poller(
572 environment_id=environment_id,
573 environment_key=environment_key,
574 auto_stop=False, # the launched sandbox owns the stop call
575 ):
576 await launch_container(work)
577
578
579 asyncio.run(main())
580 ```
581
582 ```typescript TypeScript
583 import { spawn } from "node:child_process";
584 import { once } from "node:events";
585 import Anthropic from "@anthropic-ai/sdk";
586 import { WorkPoller } from "@anthropic-ai/sdk/helpers/beta/environments";
587 import type { BetaSelfHostedWork } from "@anthropic-ai/sdk/resources/beta/environments";
588
589 const SANDBOX_ENV = [
590 "ANTHROPIC_ENVIRONMENT_ID",
591 "ANTHROPIC_ENVIRONMENT_KEY",
592 "ANTHROPIC_WORK_ID",
593 "ANTHROPIC_SESSION_ID",
594 "ANTHROPIC_WORK_SECRET",
595 "ANTHROPIC_BASE_URL" // forwarded only when set on this host
596 ];
597
598 const environmentKey = process.env.ANTHROPIC_ENVIRONMENT_KEY!;
599 const environmentId = process.env.ANTHROPIC_ENVIRONMENT_ID!;
600 const client = new Anthropic({ authToken: environmentKey });
601
602 async function launchContainer(work: BetaSelfHostedWork): Promise<void> {
603 console.log(`claimed session ${work.data.id}`);
604 // Replace `docker run` with your own sandbox launcher. Forward the environment
605 // key (never your API key) and the work item's per-session secret: the worker
606 // inside needs the secret to mount the session's memory stores.
607 const env = {
608 ...process.env,
609 ANTHROPIC_WORK_ID: work.id,
610 ANTHROPIC_SESSION_ID: work.data.id,
611 ANTHROPIC_WORK_SECRET: work.secret ?? ""
612 };
613 const forward = SANDBOX_ENV.flatMap((name) => ["-e", name]);
614 const launcher = spawn("docker", ["run", "--rm", "--detach", ...forward, "your-image"], {
615 env,
616 stdio: "inherit"
617 });
618 await once(launcher, "close");
619 }
620
621 const poller = new WorkPoller({
622 client,
623 environmentId,
624 environmentKey,
625 autoStop: false // the launched sandbox owns the stop call
626 });
627
628 for await (const work of poller) {
629 await launchContainer(work);
630 }
631 ```
632
633 <CodeGroupItem language="C#">
634 The C# SDK does not have a helper that polls for work. To claim work from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work).
635 </CodeGroupItem>
636
637 ```go Go
638 package main
639
640 import (
641 "context"
642 "fmt"
643 "log"
644 "os"
645 "os/exec"
646
647 "github.com/anthropics/anthropic-sdk-go/v2"
648 "github.com/anthropics/anthropic-sdk-go/v2/lib/environments"
649 "github.com/anthropics/anthropic-sdk-go/v2/option"
650 "github.com/anthropics/anthropic-sdk-go/v2/packages/param"
651 )
652
653 var sandboxEnv = []string{
654 "ANTHROPIC_ENVIRONMENT_ID",
655 "ANTHROPIC_ENVIRONMENT_KEY",
656 "ANTHROPIC_WORK_ID",
657 "ANTHROPIC_SESSION_ID",
658 "ANTHROPIC_WORK_SECRET",
659 "ANTHROPIC_BASE_URL", // forwarded only when set on this host
660 }
661
662 func launchContainer(ctx context.Context, work *anthropic.BetaSelfHostedWork) error {
663 fmt.Printf("claimed session %s\n", work.Data.ID)
664 // Replace `docker run` with your own sandbox launcher. Forward the environment
665 // key (never your API key) and the work item's per-session secret: the worker
666 // inside needs the secret to mount the session's memory stores.
667 args := []string{"run", "--rm", "--detach"}
668 for _, name := range sandboxEnv {
669 args = append(args, "-e", name)
670 }
671 launcher := exec.CommandContext(ctx, "docker", append(args, "your-image")...)
672 launcher.Env = append(os.Environ(),
673 "ANTHROPIC_WORK_ID="+work.ID,
674 "ANTHROPIC_SESSION_ID="+work.Data.ID,
675 "ANTHROPIC_WORK_SECRET="+work.Secret,
676 )
677 launcher.Stdout, launcher.Stderr = os.Stdout, os.Stderr
678 return launcher.Run()
679 }
680
681 func main() {
682 environmentID := os.Getenv("ANTHROPIC_ENVIRONMENT_ID")
683 environmentKey := os.Getenv("ANTHROPIC_ENVIRONMENT_KEY")
684
685 client := anthropic.NewClient(option.WithAuthToken(environmentKey))
686
687 ctx := context.Background()
688
689 poller := environments.NewWorkPoller(ctx, client, environments.WorkPollerOptions{
690 EnvironmentID: environmentID,
691 EnvironmentKey: environmentKey,
692 AutoStop: param.NewOpt(false), // the launched sandbox owns the stop call
693 })
694 defer poller.Close()
695
696 for work, err := range poller.All() {
697 if err != nil {
698 log.Fatal(err)
699 }
700 if err := launchContainer(ctx, work); err != nil {
701 log.Fatal(err)
702 }
703 }
704 }
705 ```
706
707 <CodeGroupItem language="Java">
708 The Java SDK does not have a helper that polls for work. To claim work from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work).
709 </CodeGroupItem>
710
711 <CodeGroupItem language="PHP">
712 The PHP SDK does not have a helper that polls for work. To claim work from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work).
713 </CodeGroupItem>
714
715 <CodeGroupItem language="Ruby">
716 The Ruby SDK does not have a helper that polls for work. To claim work from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work).
717 </CodeGroupItem>
718</CodeGroup>
719
720### Run the SDK worker inside the sandbox
721
722Replace the `ant beta:worker run` entrypoint with an SDK entrypoint when the sandbox must [serve custom tools](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-custom-tools) or use [non-default memory sync settings](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#configure-sync). The entrypoint constructs `EnvironmentWorker` and calls `handle_item()` (typescript: `handleItem()`; go: `HandleItem()`), which reads the same `ANTHROPIC_*` variables that the spawn script forwards.
723
724<CodeGroup exclude="shell, csharp, java, php, ruby">
725 ```python Python
726 import asyncio
727 import contextlib
728 import os
729 import signal
730 from anthropic import AsyncAnthropic
731 from anthropic.lib.environments import EnvironmentWorker
732
733
734 async def main() -> None:
735 async with AsyncAnthropic(
736 auth_token=os.environ["ANTHROPIC_ENVIRONMENT_KEY"]
737 ) as client:
738 worker = EnvironmentWorker(client, workdir="/workspace")
739 # With no arguments, handle_item() reads the ANTHROPIC_* variables the spawn
740 # script forwarded, including ANTHROPIC_WORK_SECRET.
741 task = asyncio.create_task(worker.handle_item())
742 # Cancelling the task when the container is stopped lets the worker upload
743 # changed memory files and remove the store directories before it exits.
744 loop = asyncio.get_running_loop()
745 for signum in (signal.SIGINT, signal.SIGTERM):
746 loop.add_signal_handler(signum, task.cancel)
747 with contextlib.suppress(asyncio.CancelledError):
748 await task
749
750
751 asyncio.run(main())
752 ```
753
754 ```typescript TypeScript
755 import Anthropic from "@anthropic-ai/sdk";
756 import { EnvironmentWorker } from "@anthropic-ai/sdk/helpers/beta/environments";
757
758 const client = new Anthropic({ authToken: process.env.ANTHROPIC_ENVIRONMENT_KEY });
759 const controller = new AbortController();
760 // Aborting when the container is stopped lets the worker upload changed memory
761 // files and remove the store directories before it exits.
762 process.once("SIGTERM", () => controller.abort());
763 process.once("SIGINT", () => controller.abort());
764
765 // With no arguments, handleItem() reads the ANTHROPIC_* variables the spawn
766 // script forwarded, including ANTHROPIC_WORK_SECRET.
767 await new EnvironmentWorker({
768 client,
769 workdir: "/workspace",
770 signal: controller.signal
771 }).handleItem();
772 ```
773
774 <CodeGroupItem language="C#">
775 The C# SDK does not have `EnvironmentWorker`.
776 </CodeGroupItem>
777
778 ```go Go
779 package main
780
781 import (
782 "context"
783 "log"
784 "os"
785 "os/signal"
786 "syscall"
787
788 "github.com/anthropics/anthropic-sdk-go/v2"
789 "github.com/anthropics/anthropic-sdk-go/v2/lib/environments"
790 "github.com/anthropics/anthropic-sdk-go/v2/option"
791 )
792
793 func main() {
794 // Cancelling the context when the container is stopped lets the worker upload
795 // changed memory files and remove the store directories before it exits.
796 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
797 defer stop()
798
799 client := anthropic.NewClient(option.WithAuthToken(os.Getenv("ANTHROPIC_ENVIRONMENT_KEY")))
800 worker := environments.NewEnvironmentWorker(client, environments.EnvironmentWorkerOptions{
801 Workdir: "/workspace",
802 })
803 // With zero-value options, HandleItem reads the ANTHROPIC_* variables the spawn
804 // script forwarded, including ANTHROPIC_WORK_SECRET.
805 if err := worker.HandleItem(ctx, environments.HandleItemOptions{}); err != nil {
806 log.Fatalf("worker: %v", err)
807 }
808 }
809 ```
810
811 <CodeGroupItem language="Java">
812 The Java SDK does not have `EnvironmentWorker`.
813 </CodeGroupItem>
814
815 <CodeGroupItem language="PHP">
816 The PHP SDK does not have `EnvironmentWorker`.
817 </CodeGroupItem>
818
819 <CodeGroupItem language="Ruby">
820 The Ruby SDK does not have `EnvironmentWorker`.
821 </CodeGroupItem>
822</CodeGroup>
823
824## Stage files for a session
825
826Anthropic doesn’t mount files or GitHub repositories into self-hosted sandboxes. To make session-specific files available:
827
8281. Pass file references, such as an S3 path or commit SHA, in the session’s `metadata` field.
8292. In your spawn script or `--on-work` handler, retrieve the session (`GET /v1/sessions/{session_id}`) and read `metadata`. The claimed work item carries the session ID but not the metadata.
8303. Stage the files into the working directory before any tool runs.
831
832<CodeGroup>
833 ```bash cURL
834 curl -sS --fail-with-body https://api.anthropic.com/v1/sessions \
835 -H "x-api-key: $ANTHROPIC_API_KEY" \
836 -H "anthropic-version: 2026-10-21" \
837 -H "anthropic-beta: managed-agents-2026-04-01" \
838 -H "content-type: application/json" \
839 -d '{
840 "agent": "'"$AGENT_ID"'",
841 "environment_id": "'"$ANTHROPIC_ENVIRONMENT_ID"'",
842 "metadata": {"input_file": "s3://my-bucket/data.csv"}
843 }'
844 ```
845
846 ```bash CLI
847 ant beta:sessions create \
848 --agent "$AGENT_ID" \
849 --environment-id "$ANTHROPIC_ENVIRONMENT_ID" \
850 --metadata '{"input_file": "s3://my-bucket/data.csv"}'
851 ```
852
853 ```python Python
854 session = client.beta.sessions.create(
855 agent=agent.id,
856 environment_id=environment.id,
857 metadata={"input_file": "s3://my-bucket/data.csv"},
858 )
859 ```
860
861 ```typescript TypeScript
862 const session = await client.beta.sessions.create({
863 agent: agent.id,
864 environment_id: environment.id,
865 metadata: { input_file: "s3://my-bucket/data.csv" }
866 });
867 ```
868
869 ```csharp C#
870 var session = await client.Beta.Sessions.Create(new()
871 {
872 Agent = agent.ID,
873 EnvironmentID = environment.ID,
874 Metadata = new Dictionary<string, string> { ["input_file"] = "s3://my-bucket/data.csv" },
875 });
876 ```
877
878 ```go Go
879 session, err := client.Beta.Sessions.New(ctx, anthropic.BetaSessionNewParams{
880 Agent: anthropic.BetaSessionNewParamsAgentUnion{OfString: anthropic.String(agent.ID)},
881 EnvironmentID: environment.ID,
882 Metadata: map[string]string{
883 "input_file": "s3://my-bucket/data.csv",
884 },
885 })
886 if err != nil {
887 panic(err)
888 }
889 ```
890
891 ```java Java
892 var session = client.beta().sessions().create(SessionCreateParams.builder()
893 .agent(agent.id())
894 .environmentId(environment.id())
895 .metadata(SessionCreateParams.Metadata.builder()
896 .putAdditionalProperty("input_file", JsonValue.from("s3://my-bucket/data.csv"))
897 .build())
898 .build());
899 ```
900
901 ```php PHP
902 $session = $client->beta->sessions->create(
903 agent: $agent->id,
904 environmentID: $environment->id,
905 metadata: ['input_file' => 's3://my-bucket/data.csv'],
906 );
907 ```
908
909 ```ruby Ruby
910 session = client.beta.sessions.create(
911 agent: agent.id,
912 environment_id: environment.id,
913 metadata: {input_file: "s3://my-bucket/data.csv"}
914 )
915 ```
916</CodeGroup>
474This handler runs every claimed item in one process, and it runs items from separate webhook deliveries at the same time. Those sessions share one filesystem, including `/workspace` and `/mnt/memory`. If your sessions attach the same memory store, see [Isolate sessions that share a store](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#isolate-sessions-that-share-a-store).
917475
918476## Next steps
919477
920478<CardGroup cols={2}>
921 <Card title="Monitor and troubleshoot" icon="lightning" href="https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations">
479 <Card title="Run one sandbox per session" icon="cube" href="https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session">
480 Launch sandboxes with the Helm chart on Kubernetes, a spawn script, or the SDK poller.
481 </Card>
482
483 <Card title="Monitor and troubleshoot self-hosted workers" icon="lightning" href="https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations">
922484 Read queue depth, stop sessions and workers cleanly, and fix common failures.
923485 </Card>
924486
925487
No line in this hunk matches that.