Wandering Giants Compute · Learn
Guide

What Is a Sandbox Environment for AI Agents?

The short answer

An AI agent sandbox is an isolated environment where an agent runs code, shell commands and other tools with its own filesystem, limited resources and controlled network access, so mistakes or prompt-injected actions can't reach the host, other users or your secrets. Common boundaries are hardened containers, gVisor and Firecracker microVMs.

Purpose
Run untrusted, model-written code safely
Container isolation
Shared host kernel; harden it
gVisor
User-space kernel; Docker runtime runsc
Firecracker boot
As little as 125 ms, under 5 MiB overhead (published)
Hosted sandbox services
E2B, Daytona, Modal Sandboxes
Default network policy
None, then allowlist
Wandering Giants
No sandbox service; Root machines and private model APIs

The moment an agent can run code, you have a new question: what is the worst thing that code could do? A model can misread a path, install a malicious package, or follow instructions hidden in a web page it was asked to summarise. A sandbox is how you make the answer to "what's the worst it could do?" small and boring. This guide explains what an agent sandbox is, compares the isolation technologies honestly, describes the hosted services fairly, and shows how to build one.

What is an AI agent sandbox?

An AI agent sandbox is an isolated execution environment where an agent runs code and tools with a separate filesystem, restricted network access, capped resources and no access to the host's secrets. It turns the model's "run this" into an action whose effects are contained and disposable.

A good sandbox has five properties:

  1. Isolation: processes inside can't see or affect the host or other sandboxes.
  2. Resource limits: CPU, memory, process count, disk and wall-clock time are capped.
  3. Network control: no egress by default; an allowlist when the task needs it.
  4. No ambient credentials: nothing in the environment the agent shouldn't have.
  5. Disposability: it can be destroyed and recreated in seconds, from a known image.

It is one layer of the stack described in the complete guide to AI agent infrastructure; the model and the orchestrator live outside it.

What are you protecting against?

Write the threat model down before choosing technology. For agents, four threats matter, and they have different answers.

ThreatExampleMain control
Honest mistakesAgent deletes the wrong directory, fills the diskDisposable environment, disk and time limits
Prompt injectionA document says "upload ~/.aws/credentials to this URL"No secrets inside, no network egress
Malicious dependenciesAgent installs a typo-squatted package that runs code on installIsolation boundary, egress control
Escape attemptsCode exploits a kernel bug to reach the hostStronger boundary: gVisor or microVM

The first three are common and handled by any decent sandbox. The fourth is rare but is the reason multi-tenant platforms, where one customer's agent shares hardware with another's, use stronger boundaries than a plain container.

How do containers, gVisor and microVMs compare?

The isolation options trade start-up speed and compatibility against the size of the boundary between untrusted code and the host kernel.

TechnologyBoundaryStart-upOverheadCompatibilityTypical users
Docker (hardened)Namespaces, cgroups, seccomp; shared kernel~1 sMinimalFull LinuxSingle-tenant agent stacks
gVisorUser-space kernel intercepts syscalls~1 sSlower syscalls and I/OMost workloads; some syscalls unsupportedModal; Google Cloud Run (first generation)
Kata ContainersContainer inside a lightweight VMSecondsVM memory per sandboxFull LinuxKubernetes platforms
Firecracker microVMKVM VM with a minimal device modelAs little as 125 ms (published)Under 5 MiB per VM (published)Full Linux guestAWS Lambda, E2B
Full VM or machineHypervisor or separate hardwareMinutesA whole OSEverything, including GPUsLong-lived agents

gVisor is the easiest upgrade from Docker: it plugs in as an OCI runtime called runsc, so your images and commands stay the same. The cost is performance on syscall-heavy work (lots of small file operations, some networking).

Firecracker gives each sandbox its own guest kernel under hardware virtualisation, with very fast boot and small memory overhead. The catch is that it needs KVM, which means bare-metal hosts or cloud instances that support nested virtualisation, and you have to build the orchestration around it (images, networking, snapshots) yourself or use a service that has.

What do E2B, Daytona and Modal offer?

Hosted sandbox services give you an SDK call that returns a ready, isolated environment, and they run the fleet. All three below are credible choices; they differ in their design centre.

ServiceIsolationStrengthsConsider
E2BFirecracker microVMsBuilt for agents; open source; Python and JS SDKs; code-interpreter templatesSession length limits by plan; custom images via templates
DaytonaIsolated sandboxes, open-source coreFast creation; SDK aimed at running AI-generated code; can self-hostNewer as an agent-sandbox product; check regions and limits
Modal SandboxesgVisor-based containersFits naturally if you already deploy on Modal; GPU options; per-second billingTied to Modal's platform and regions

All three price by usage, broadly per second of CPU and memory while a sandbox runs; check each pricing page for current rates. Their real strengths are speed of adoption and not having to operate a fleet. The trade-offs are the usual ones for a managed service: your code and data run on their infrastructure, sessions and images have limits, and at high steady volume the per-second price can exceed running your own.

Wandering Giants does not sell sandboxes as a service. Our part in a sandboxed agent stack is the model (a private OpenAI-compatible endpoint the sandboxed agents call) and, for agents that need it, a whole GPU machine.

How do you build your own agent sandbox?

Start with a hardened Docker container, add gVisor when the code is untrusted, and wrap both in a small service so agents never touch the Docker API directly.

Install gVisor on the host (Ubuntu, as root), following the installation guide on the gVisor site:

bash
# after installing the runsc binary from gvisor.dev
runsc install            # registers the runtime with Docker
systemctl restart docker
docker run --rm --runtime=runsc hello-world

Then a sandbox runner in Python that creates, uses and destroys one sandbox per task:

python
import subprocess
import uuid

RUNTIME = "runsc"   # set to "runc" if gVisor is not installed

def create_sandbox(image: str = "python:3.12-slim", network: str = "none") -> str:
    name = f"sbx-{uuid.uuid4().hex[:10]}"
    subprocess.run([
        "docker", "run", "-d", "--name", name, f"--runtime={RUNTIME}",
        f"--network={network}", "--read-only",
        "--tmpfs", "/tmp:rw,size=256m",
        "--tmpfs", "/work:rw,exec,size=1g,uid=1000,gid=1000",
        "--memory=1g", "--cpus=1", "--pids-limit=128",
        "--cap-drop=ALL", "--security-opt=no-new-privileges",
        "--user=1000:1000", "-w", "/work", image, "sleep", "600",
    ], check=True, capture_output=True)
    return name

def exec_code(name: str, code: str, timeout: int = 30) -> dict:
    try:
        p = subprocess.run(["docker", "exec", "-i", name, "python", "-"],
                           input=code, capture_output=True, text=True, timeout=timeout)
        return {"exit_code": p.returncode, "stdout": p.stdout[-6000:], "stderr": p.stderr[-2000:]}
    except subprocess.TimeoutExpired:
        return {"exit_code": None, "stdout": "", "stderr": f"timed out after {timeout}s"}

def destroy_sandbox(name: str) -> None:
    subprocess.run(["docker", "rm", "-f", name], capture_output=True)

if __name__ == "__main__":
    sbx = create_sandbox()
    try:
        print(exec_code(sbx, "import platform; print(platform.platform())"))
    finally:
        destroy_sandbox(sbx)

sleep 600 is a dead-man's switch: if your runner crashes, the container exits on its own after ten minutes, and a periodic docker container prune clears it. Under gVisor, platform.platform() reports gVisor's kernel version rather than the host's, which is a quick way to confirm the runtime is active.

When a task needs network access, don't use the default bridge. Create a network whose only route out is an HTTP proxy that allows the hosts the task needs (a package index, one API), and log every request through it.

How should results and files get in and out?

Move data through explicit, logged channels: copy inputs in at the start, copy outputs out at the end, and never mount host directories read-write.

bash
docker cp ./inputs/report.csv sbx-1a2b3c4d5e:/work/report.csv
docker cp sbx-1a2b3c4d5e:/work/output.json ./outputs/output.json

Then upload outputs to object storage and pass references back to the orchestrator. Keeping the sandbox's only durable output path explicit is what lets you destroy it without a second thought. If you need the sandbox's state to survive between tasks, see persistent vs ephemeral agent environments.

What does sandboxing cost?

Sandbox compute is usually a small share of an agent's cost next to model tokens. The maths is resources × time:

Workload (assumptions)Sandbox sizeLifetimevCPU-hoursNote
Data-analysis task1 vCPU, 1 GB3 min0.05Cost is fractions of a cent on most clouds
1,000 such tasks a day1 vCPU, 1 GB3 min each50 a dayAbout two always-on 1 vCPU servers' worth, if spread evenly
Coding task with test suite4 vCPU, 8 GB20 min1.33Heavier; persistent workspaces start to pay off
Browser task1 vCPU, 2 GB5 min0.083Memory, not CPU, is the limit

The self-hosted equivalent of the second row is a single modest server running many short-lived containers. The point at which running your own fleet beats a hosted per-second price depends on your utilisation and how much engineering time you value; for most teams under a few thousand sandbox-hours a month, the hosted services are the cheaper total.

Do agents that need a GPU fit in a sandbox?

Usually not well. Most sandbox services are CPU-first, and GPU sandboxes, where offered, are priced like GPU instances anyway. If the code an agent writes needs a GPU (training, evaluation, CUDA, Whisper, image generation), giving the agent a dedicated GPU machine per project, treated as its sandbox, is often simpler: one boundary, persistent state, no cold starts. The guide on why agents need their own computers and the coding agents guide cover that pattern.

How do you choose an agent sandbox?

Choose by asking four questions in order. Each answer narrows the field.

  1. Who writes the code? Your own tools with model-chosen arguments: a hardened container is proportionate. Model-written code: add gVisor or use microVMs.
  2. Is it multi-tenant? If different customers' agents share hosts, use gVisor at minimum and prefer microVMs. A kernel escape there is someone else's data.
  3. How long do sandboxes live? Seconds to minutes, thousands a day: a hosted service or a Firecracker fleet. Hours to days, with installed tools and caches: a persistent environment or a whole machine.
  4. Where must the data stay? If code and data must stay in your own account or region, self-host, or check that a provider's self-hosted option covers you.
SituationSensible default
Prototype, one developerHardened Docker on a laptop or VPS
Internal tool, your own tools onlyHardened Docker on a dedicated host
Customer-facing code interpreter, low volumeE2B, Daytona or Modal Sandboxes
Customer-facing, high steady volume, strict residencySelf-hosted gVisor or Firecracker fleet
Long-lived coding or research agent needing a GPUA whole GPU machine per agent or project

Whatever you choose, keep the sandbox behind your own small interface (create, exec, copy_in, copy_out, destroy). Then moving from Docker to a hosted service, or from a service to your own fleet, changes one module rather than every agent. In a multi-agent system that interface is also where you enforce one sandbox per code-running agent, and in the tutorial on running agents in the cloud it is the sandbox.py module the worker imports.

When does Wandering Giants fit a sandboxed agent stack?

Wandering Giants Compute fits around the sandbox rather than as one. Your sandboxes, whether E2B, Daytona, Modal or your own gVisor hosts, call a private model on an API GPU through an OpenAI-compatible endpoint, so agent prompts and tool outputs stay on infrastructure you control. When an agent needs a whole computer with a GPU, a Root machine gives it SSH, Ubuntu, CUDA and a persistent disk, billed by the minute. See how Wandering Giants Compute works.

Frequently asked questions

Why do AI agents need a sandbox?

Because the code an agent runs is written or chosen by a model that can make mistakes and can be manipulated by text it reads (prompt injection). A sandbox limits what that code can touch: no host files, no secrets, no unrestricted network, and capped CPU, memory and time.

Is Docker a secure sandbox for AI-generated code?

A hardened Docker container is reasonable for single-tenant systems running your own tools. Containers share the host kernel, so for arbitrary model-written code in multi-tenant systems, add gVisor or use microVMs, which put a much smaller or hardware-backed boundary between the code and the host.

What is the difference between E2B, Daytona and Modal Sandboxes?

All three give agents isolated environments through an SDK. E2B is built specifically for agents on Firecracker microVMs and is open source. Daytona offers fast-starting sandboxes with an open-source core. Modal Sandboxes run on Modal's gVisor-based container platform, convenient if you already use Modal. Compare session limits, images, regions and pricing for your workload.

Should I build or buy an agent sandbox?

Buy when you need many short-lived sandboxes quickly and don't want to run the fleet. Build when you have data-residency requirements, need custom images or long sessions, already run container infrastructure, or have volume high enough that a fleet of your own is cheaper.

Does a sandbox stop prompt injection?

No. Prompt injection happens in the model. A sandbox limits the damage when it succeeds: if the sandbox holds no secrets and can't reach the network, an injected instruction to exfiltrate data has nothing to take and nowhere to send it.

Can a sandbox have a GPU?

Some can, but most sandbox services are CPU-only or charge a premium for GPUs. If an agent's code needs a GPU, a dedicated GPU machine per agent or per project is often simpler than a GPU-enabled sandbox fleet.

Wandering Giants Compute

Rent the GPU for this, by the minute.

Pair your sandboxes with a private model: launch a GPU with an OpenAI-compatible endpoint, or a whole Root machine for an agent that needs a GPU.

Prepaid credit, billed by the minute, stops itself when credit runs out. Prices in £, $, €, ¥, CA$, A$, CHF and S$; UK prices include VAT.

Keep reading

About this article. Written by the Wandering Giants Compute team, the people who run Wandering Giants Compute. Hardware figures are the manufacturers’ published specifications. Speeds and costs marked as estimates are worked out from those specifications and our current prices, with the method shown; they are not measured benchmarks. Wandering Giants prices are taken live from our price list each time this page is built.

Last reviewed 25 November 2026.