Skip to content
AnswerWell geo Documentation

Research · 10 min read · Answerwell

Untrusted Code Sandboxes: Containers, Agents, Interpreter, and Backup

How Linux sandboxes run model-generated code and coding agents with isolation, egress control, interpreters, and workspace snapshots.

This page summarises Cloudflare documentation on Sandboxes: isolated environments where Workers run untrusted code—especially code that models or users generate—without handing that code your credentials or full platform access. The same platform also supports Containers (full Linux VMs) and Dynamic Workers (bounded JavaScript); picking the right layer is central to every design below.

Sandbox vs Container vs Dynamic Worker: when to use which

Section titled “Sandbox vs Container vs Dynamic Worker: when to use which”

A sandbox runs code you did not write and do not trust. Cloudflare places it in one of two execution environments, and one Worker can use both.

A sandbox runs code that you did not write and do not trust, such as code that a model generates or the test suite of a repository. Cloudflare runs it in one of two environments: a Container, which runs a Linux image, or a Dynamic Worker, which runs JavaScript against methods that your Worker provides.

— Cloudflare, Choose a sandbox environment

Need Prefer Why
npm install, shells, preview servers, native tools Linux sandbox (Container) Full OS, processes, ports
Only calls APIs you define on the Worker Dynamic Worker Fast start, no shell
Mixed coding agent Both Q&A in Dynamic Worker; tests/build in Container

Most existing tools expect an operating system as well as a language runtime. npm test needs Node.js, dependencies on a filesystem, and child processes. A preview server keeps a process running and listens on a port.

— Cloudflare, Choose a sandbox environment

For vibe coding and agent products, Linux sandboxes on Containers are the default when generated code must install packages, run dev servers, or expose preview URLs:

Linux sandboxes run on Containers. Each one has a shell, a filesystem, and processes, for code that installs packages, builds a project, or runs a development server.

— Cloudflare, AI Vibe Coding Platform

Containers offer complete runtime control through custom Docker images, allowing you to run any language or framework with up to 4GB RAM and dedicated vCPU and are best when you need custom runtimes or resource-intensive workloads.

— Cloudflare, AI Vibe Coding Platform

At the runtime layer, the Container tier is VM-isolated Linux:

Executes code in isolation with full Linux capabilities.

Purpose: Safely execute untrusted code.

Why containers:

VM-based isolation - Each sandbox runs in its own VM Full environment - Ubuntu Linux with Python, Node.js, Git, etc.

— Cloudflare, Architecture

Sandboxes on Cloudflare: microVM and Worker gate

Section titled “Sandboxes on Cloudflare: microVM and Worker gate”

Each container instance is a microVM with its own kernel; HTTP from the Internet reaches it only through your Worker:

Each instance is a microVM with its own kernel and network, so no other workload shares it.

— Cloudflare, Sandboxes on Cloudflare

Sandbox SDK 1.0: your Durable Object owns the container

Section titled “Sandbox SDK 1.0: your Durable Object owns the container”

With Sandbox SDK 1.0, your Durable Object class drives the container through this.ctx.container instead of relying on a fixed helper-only lifecycle.

Sandbox SDK 1.0 is available. Your own Durable Object class now controls each sandbox container directly, through the Durable Object container API on this.ctx.container.

— Cloudflare, Sandbox SDK 1.0

Capabilities you implement in that class include image/size choice, snapshots, outbound handling, previews, and exposing only the methods callers should use. The @cloudflare/sandbox package adds Files, S3Mount (Worker-signed R2 access), and DirectoryBackup for directories in R2.

A minimal pattern starts the image with enableInternet: false, writes a script, and runs it—see Sandbox SDK 1.0.

Sandbox lifetime: Durable Object storage vs container disk

Section titled “Sandbox lifetime: Durable Object storage vs container disk”

The name (for example a session ID) always routes to the same Durable Object. Storage in the DO survives; processes and local disk die when the instance stops unless you snapshot or back up.

The Durable Object and the instance last for different lengths of time. The Durable Object keeps its storage, such as session details or a snapshot ID, until your code deletes it. An instance runs only until something stops it, and its processes and the files on its disk end with it.

— Cloudflare, Sandbox lifetime

For coding sessions, that distinction explains why a dev server survives an idle hour only if the instance stayed running—not merely because the DO still exists. Details and diagrams are in Sandbox lifetime.

Run AI-generated code: exec, interpreter, and tool-calling patterns

Section titled “Run AI-generated code: exec, interpreter, and tool-calling patterns”

People usually want one of three shapes: one-shot exec after the model writes code, a code interpreter with rich outputs, or an agent tool that the model calls repeatedly.

The Build an AI code executor tutorial accepts a question, asks Claude for Python, runs sandbox.exec('python /tmp/code.py'), and returns stdout, stderr, and the generated source.

For data analysis, the same flow uploads CSV into /workspace, inspects structure with exec, generates analysis code via tool calling, runs it, and optionally reads chart.png from the sandbox—see Analyze data with AI.

The SDK’s interpreter returns multiple MIME-shaped outputs (text, HTML tables, PNG/SVG charts, JSON):

Interpreter outputs are auto-formatted and returned in multiple formats:

text html (e.g., Pandas tables) png, svg (e.g., Matplotlib charts) json (structured data) chart (parsed visualizations)

— Cloudflare, Sandbox SDK major update

Workers AI plus tool calling is illustrated in Code interpreter with Workers AI and Build an AI code interpreter. API detail lives under Code interpreter and Use code interpreter.

AI is supercharging app development for everyone, but we need a safe way to run untrusted, LLM-written code. We’re introducing Sandboxes ↗︎, which let your Worker run actual processes in a secure, container-based environment.

— Cloudflare, Run AI-generated code on-demand with Code Sandboxes

The introductory getSandbox + exec pattern is documented on that same changelog page.

Coding agents in a Linux sandbox: runner, credentials, and diffs

Section titled “Coding agents in a Linux sandbox: runner, credentials, and diffs”

Coding agents (Claude Code, Codex, OpenCode, and similar) edit repos and run shell commands until a task finishes. Cloudflare’s model: your Worker starts the sandbox, holds secrets, and restricts hostnames; the agent only talks to allowed endpoints (typically AI Gateway and github.com).

Your Worker starts the sandbox, holds the credentials, and decides which hostnames the sandbox can reach. The agent calls its model over HTTP, for example through AI Gateway. Your Worker adds the API token to each request, so the sandbox never receives it.

— Cloudflare, Run coding agents in a sandbox

The reference implementation is Build a coding agent runner:

  • POST /sandboxes/<NAME>/repository clones a GitHub repo (only https://github.com/ URLs are accepted because outbound policy blocks other Git hosts).
  • POST /sandboxes/<NAME>/task starts the agent with the body as the prompt (max 128 KiB).
  • GET /sandboxes/<NAME>/task polls task state (running, succeeded, failed, lost, none).
  • GET /sandboxes/<NAME>/diff returns git diff including new files via git add --intent-to-add.

Long tasks run in the background: startTask() returns 202 while Claude Code writes stream-json events to files under /workspace/task so the process is not killed by SIGPIPE when the HTTP request ends. Agent-specific Dockerfiles and outcome parsing are in Run Claude Code in a sandbox, Run Codex in a sandbox, and Run OpenCode in a sandbox.

Other integrations keep the vendor agent loop off your account but run tools in your sandboxes: Devin Outposts, Cursor Cloud Agents, Claude Managed Agents, and OpenAI Agents API with Codex. For an agent inside a Durable Object with a run_command tool, see Sandbox in the Agents SDK.

Give an agent a Linux sandbox for shell commands, language runtimes, package installation, and project files that last across turns. The sandbox is a Container attached to the agent.

— Cloudflare, Sandbox

Use Code Mode (Dynamic Worker) when generated code only calls methods you define—see the note in that same doc and Choose a sandbox environment.

Egress, outbound Workers, and credential injection

Section titled “Egress, outbound Workers, and credential injection”

Untrusted code must not see API keys. The coding-agent runner sets enableInternet: false and routes HTTPS through an Outbound Worker that injects the AI Gateway token and strips client-supplied keys (for example deleting x-api-key so Claude Code’s placeholder does not reach Anthropic).

Platform-wide, outbound control expanded to:

Outbound Workers for Sandboxes and Containers now support zero-trust credential injection, TLS interception, allow/deny lists, and dynamic per-instance egress policies. These features give platforms running agentic workloads full control over what leaves the sandbox, without exposing secrets to untrusted workloads, like user-generated code or coding agents.

— Cloudflare, Secure credential injection and dynamic egress policies

Containers can also call Workers and bindings (KV, R2) at specific hostnames over HTTP—see Easily connect Containers and Sandboxes to Workers.

For browser agents, additional sandbox boundaries apply:

LLM-generated code runs in isolated Worker sandboxes — each execution gets its own Worker instance External network access (fetch, connect) is blocked in the sandbox at the runtime level

— Cloudflare, Browser agent

Workspace backup and restore: skip repeated git clone and npm install

Section titled “Workspace backup and restore: skip repeated git clone and npm install”

Agent workspaces often need minutes of setup. createBackup() / restoreBackup() snapshot a directory (typically /workspace) to R2:

Now, after the initial setup, you can just call createBackup(), then restoreBackup() the next time this environment is needed. This makes it practical to pick up exactly where a user left off, even after days of inactivity, without repeating expensive setup steps.

— Cloudflare, Backup and restore API for Sandbox SDK

Handles can live in KV, D1, or Durable Object storage; backups support named labels, TTLs, and reuse across many sandboxes. Today’s implementation uses a FUSE overlay; native snapshotting is planned with a similar API—see the note on Backup and restore API for Sandbox SDK.

Sandbox bridge: HTTP API for non-Worker clients

Section titled “Sandbox bridge: HTTP API for non-Worker clients”

The Sandbox bridge is a Worker that exposes the Sandbox API over HTTP so clients such as a Python OpenAI Agents SDK script can create sessions. Deploy verifies with:

curl https://cloudflare-sandbox-bridge.<your-subdomain>.workers.dev/health

Expected body: {"ok":true} per Build an AI coding agent with OpenAI Agents SDK. The bridge image pre-installs Python, Node.js, Bun, git, ripgrep, and common CLI tools—customise the Dockerfile as needed (Sandbox bridge).

Platform capabilities that surround execution

Section titled “Platform capabilities that surround execution”
Feature What it does Doc
sandbox.watch() SSE filesystem events (inotify) Real-time file watching
Preview URLs Long-lived services reachable via your Worker Containers and Sandboxes GA
Docker-in-Docker Build/run images inside the sandbox Docker-in-Docker
PTY / terminals Interactive shells in the browser Open a terminal in the browser
sandbox.exec errors Non-zero exit vs thrown exec errors Execute commands

Containers and Sandboxes are generally available on Workers, with active-CPU pricing and higher concurrency limits—summary in Containers and Sandboxes are now generally available.

Image variants (-python, -musl) are described in Dockerfile reference.

  • Deploying a coding agent runner without authenticating callers (unbounded AI Gateway spend).
  • Leaving Claude Code’s x-api-key header in outbound requests (invalid key errors)—fix in Run Claude Code in a sandbox.
  • Piping long agent stdout to the Durable Object instead of writing logs under /workspace/task (risk of SIGPIPE mid-task)—see Build a coding agent runner.
  • Assuming a backup restores running processes; only filesystem state returns (Sandbox lifetime).
  • Using enableInternet: true for coding agents without an outbound allow list (Open a terminal in the browser points to interceptOutboundHttps() when agents need network).
  1. After deploying a bridge or sandbox Worker, call the health or root route documented for that template—for example curl against the bridge /health endpoint described in Build an AI coding agent with OpenAI Agents SDK.
  2. For a coding agent runner, run the clone → task → poll → diff sequence from Build a coding agent runner against your workers.dev URL and confirm task state becomes succeeded and the diff shows expected file changes.
  3. Stream logs with Wrangler while reproducing failures (npx wrangler tail as used in Run Cursor Cloud Agents in a sandbox troubleshooting).
  4. List container instances with the Containers API (name_prefix, state=active) to confirm sandboxes start and stop as expected.
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact sentence you are asking about, and we will correct or clarify it.