Agent Runtime Sandboxes & Code Execution

Agent Runtime Sandboxes & Code Execution

Secure, ephemeral cloud environments where an AI agent runs LLM-generated code, uses a computer, or executes tools — provisioned by SDK/API in milliseconds-to-seconds, isolated from your host and other tenants, and torn down (or snapshotted) when the task ends. This skill is the agent-facing SaaS/SDK layer: which managed sandbox to pick and how to drive it (create / exec / files / snapshot / fork / egress policy). The kernel/OS isolation mechanics it sits on top of live elsewhere.

When to use / Skip

Use when you are choosing or wiring a managed sandbox to run untrusted or model-generated code: “where should my agent run the code it wrote”, picking E2B vs Modal vs Daytona vs Cloudflare, SDK calls to create/exec/upload/snapshot/fork a sandbox, configuring network egress for an agent, GPU sandboxes for ML agents, MCP-in-a-sandbox, or comparing latency/pricing/limits across providers.

Skip — kernel/OS isolation primitives go to devops-linux-internals -> Linux Sandboxing & Confinement (seccomp-bpf, Landlock, gVisor internals, Kata Containers, Firecracker internals, cgroups v2 & namespaces). That peer reference explains how the isolation layers work; this skill names them only as a selection criterion and points there for mechanics. Also skip: the general agent-guardrails / prompt-injection topic (Dual-LLM, CaMeL, OWASP-LLM as a subject in its own right) -> ai-agents-orchestration (references/agent-reliability-and-guardrails.md) — this skill covers the trifecta only as it bears on where agent code runs; building an agent loop/harness -> ai-agents-orchestration; MCP server authoring -> ai-mcp-sdk-prompting; generic container/CI build -> devops-containers-cicd.

Why agents need sandboxes

  1. LLM-generated code is untrusted by construction. A model can emit rm -rf, an infinite loop, a fork bomb, a crypto-miner, or a package install that runs a malicious post-install script — not maliciously, just because it pattern-matched. You cannot run that in your app process or build host.
  2. The lethal trifecta (Simon Willison, Jun 2025). An agent becomes exfiltration-ready when it combines (1) access to private data + (2) exposure to untrusted content + (3) the ability to communicate externally. With all three, a prompt-injection payload hidden in fetched content can read your secrets and POST them to an attacker. A sandbox is the blast-radius container for #1 and the egress chokepoint for #3 — but it does not by itself break the trifecta (see Security).
  3. Isolation / multi-tenancy. One user’s (or one agent task’s) code must not see another’s data, files, or network. MicroVM/gVisor boundaries give VM-grade separation that shared-kernel containers cannot guarantee against a determined escape.
  4. Reproducibility & determinism. Declarative images + snapshots/templates pin an exact environment (OS, packages, files) so the same agent run is reproducible, forkable for parallel exploration, and rollback-able after a risky operation. This is the property that turns “run some code” into a controllable, restartable workflow.

The managed-sandbox landscape

Isolation tech is a first-order selection criterion (see devops-linux-internals for how each works): Firecracker microVM (E2B, Vercel, Fly, CodeSandbox) = strongest, dedicated guest kernel; gVisor user-space kernel (Modal; Northflank cloud default) = strong + GPU-friendly; hardened OCI/Docker (Daytona, also offers Kata/Sysbox) = fastest start, smaller attack-surface cut.

Tier 1 — full SDKs, build your patterns here

Tier 2 — concrete specifics, narrower fit

Tier 3 — built-in (lab-hosted) interpreters: zero infra, vendor’s data plane

SDK patterns

The shape is near-identical across vendors: create -> exec/run -> move files -> snapshot -> fork -> dispose. Representative real calls:

Create + run a command, then run code (E2B):

from e2b_code_interpreter import Sandbox
with Sandbox.create(timeout=300, allow_internet_access=True) as sbx:
    sbx.commands.run("pip install pandas")          # shell command
    ex = sbx.run_code("import pandas as pd; pd.__version__")  # stateful REPL cell
    print(ex.text)                                   # -> result; ex.logs, ex.results also available
import { Sandbox } from '@e2b/code-interpreter'
const sbx = await Sandbox.create()
const ex = await sbx.runCode('x = 1; x += 1; x')     // outputs 2

Create with resources/GPU + exec with streamed output (Modal):

import modal
app = modal.App.lookup("agent", create_if_missing=True)
sb = modal.Sandbox.create(
    app=app, image=modal.Image.debian_slim().pip_install("torch"),
    gpu="A100", cpu=2, memory=8192,
    block_network=False, outbound_cidr_allowlist=["140.82.112.0/20"],  # GitHub only
)
p = sb.exec("python", "-c", "import torch; print(torch.cuda.is_available())", timeout=60)
print(p.stdout.read())

Upload / download files:

# Modal filesystem API (read up to 5 GB, write any size)
sb.filesystem.write_text("hello\n", "/tmp/in.txt")
out = sb.filesystem.read_text("/work/result.json")
// E2B
await sbx.files.write('/home/user/data.csv', csvString)
const bytes = await sbx.files.read('/home/user/out.parquet')

Snapshot (checkpoint) and restore:

# E2B: one snapshot -> many sandboxes; survives deletion
snap = sbx.create_snapshot()
fresh = Sandbox.create(snap.snapshot_id)            # boot from captured FS+memory state
# Modal: filesystem snapshot returns a reusable Image (stores only the diff)
image = sb.snapshot_filesystem(); sb.terminate()
sb2 = modal.Sandbox.create(image=image, app=app)

Fork (copy-on-write branch) — for parallel exploration / rollback:

# Daytona: independent COW clone (sandbox must be 'started')
forked = sandbox._experimental_fork()               # diverges from here; original untouched
// CodeSandbox: fast fork from a hibernated parent (1-3s)
const child = await sdk.sandboxes.create({ id: parentSandboxId })

E2B has no fork; emulate it by create_snapshot() then spawning N sandboxes from the snapshot_id.

Persist on idle instead of killing (cost control):

# E2B auto-pause: stop billing, keep state; resume later from the same point
sbx = Sandbox.create(timeout=600, on_timeout="pause")
# ... later: Sandbox.connect(sandbox_id) auto-resumes a paused sandbox

Block network entirely (egress chokepoint):

sb = modal.Sandbox.create(app=app, block_network=True)              # Modal: no egress at all
const executor = new DynamicWorkerExecutor({ loader: env.LOADER, globalOutbound: null }) // Cloudflare: fetch()/connect() blocked; host reachable only via codemode.* RPC

Selection / decision guidance

Need Pick Why
Coding agent, great SDK, fast pause/resume E2B Firecracker; memory pause/resume; MCP gateway
GPU / ML workload in the sandbox Modal (or Northflank, Daytona GPU) first-class gpu=, autoscale 0->20k
Sub-100 ms starts, unlimited runtime, computer-use Daytona OCI 27-90 ms; computer_use; archive
Already on Cloudflare; token-cheap tool orchestration Cloudflare Code Mode isolates start in ms; 80% token cut
Already on Vercel / Next.js Vercel Sandbox Firecracker; persistent-by-default
Fastest possible resume (intermittent agents) Fly suspend resume < 100 ms
Compliance: code must run in your cloud Northflank / Daytona / Runloop / E2B (self-host) BYOC / self-hostable
Just run model Python, no infra OpenAI / Anthropic built-in turnkey; accept vendor data plane
Lowest-latency tool execution, no env Riza <10 ms, no cold start, per-run egress
Drive RL training loops cheaply Together TCI $0.03 / 60-min session

Latency is contested — report ranges, not single numbers. Vendor/marketing figures (E2B ~150 ms, Daytona 27-90 ms, Modal sub-second) disagree with an independent benchmark (sandbox-comparison.pages.dev: E2B 0.515 s, Daytona 0.753 s, Modal 1.512 s cold start). Numbers swing 3-10x with region, warm pools, image size, and what you count as “start”. Benchmark your path.

Security model from the consumer side

Anti-patterns & failure modes

2025-2026 frontier

Sources

  1. Simon Willison — The lethal trifecta for AI agents (Jun 16 2025): https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/
  2. E2B — Sandbox persistence / snapshots / Python SDK / pricing / MCP: https://e2b.dev/docs (sandbox/persistence, sandbox/snapshots, sdk-reference, billing, mcp)
  3. Modal — Sandboxes guide + modal.Sandbox reference: https://modal.com/docs/guide/sandboxes , https://modal.com/docs/reference/modal.Sandbox
  4. Daytona — Sandboxes / snapshots / declarative builder / pricing: https://www.daytona.io/docs/en/sandboxes/ , https://www.daytona.io/pricing
  5. Cloudflare — Code Mode (Sep 2025) & Dynamic Workers (Mar 2026) + Sandbox SDK: https://blog.cloudflare.com/code-mode/ , https://blog.cloudflare.com/dynamic-workers/ , https://developers.cloudflare.com/sandbox/get-started/
  6. Vercel — Sandbox docs + GA blog + repo: https://vercel.com/docs/vercel-sandbox , https://github.com/vercel/sandbox
  7. Fly Machines (Firecracker, suspend/resume): https://qu3ry.net/articles/memory-resident-execution/fly-machines
  8. Runloop — Devbox overview + agent gateway: https://docs.runloop.ai/docs/devboxes/overview
  9. CodeSandbox SDK — overview + create/fork: https://codesandbox.io/docs/sdk , https://codesandbox.io/docs/sdk/create
  10. Together — Code Sandbox & Code Interpreter launch + TCI docs: https://www.together.ai/blog/code-sandbox-code-interpreter , https://docs.together.ai/docs/together-code-interpreter
  11. Riza (<10 ms, per-run egress): https://riza.io/
  12. Northflank — Sandboxes product + docs: https://northflank.com/product/sandboxes
  13. OpenAI — Code Interpreter tool (containers, memory tiers): https://developers.openai.com/api/docs/guides/tools-code-interpreter
  14. Anthropic — Code execution tool + Advanced tool use (programmatic tool calling): https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool , https://www.anthropic.com/engineering/advanced-tool-use
  15. Simon Willison — CaMeL (Apr 11 2025) + Google research repo: https://simonwillison.net/2025/Apr/11/camel/ , https://github.com/google-research/camel-prompt-injection
  16. Independent sandbox benchmarks (cold-start, contested): https://sandbox-comparison.pages.dev/ , https://agentmarketcap.ai/blog/2026/04/10/sandboxed-code-execution-ai-agents-e2b-modal-daytona
  17. Cohere — tool use / client-side Python interpreter: https://docs.cohere.com/v2/page/basic-multi-step

Boundary note: kernel/OS isolation primitives (gVisor/Kata/Firecracker internals, seccomp, namespaces) defer to devops-linux-internals (references/linux-sandboxing-confinement.md); the general guardrails/prompt-injection topic (Dual-LLM, CaMeL) to ai-agents-orchestration (references/agent-reliability-and-guardrails.md); agent loop design to ai-agents-orchestration. Cold-start latency is contested — vendor claims vs independent benchmarks diverge 3-10x; benchmark your own path.