Agent Sandboxing & Code Execution Environments

Agentic AI Systems advanced Building with AI 12 min read

Overview

AI agents that can write and execute code are among the most powerful — and most dangerous — applications in production AI systems. When an LLM generates code and runs it directly, the execution environment becomes a critical security boundary. Without proper sandboxing, a single hallucinated rm -rf / or a prompt injection that exfiltrates environment variables can cause catastrophic damage.

The scale of this challenge is significant: E2B, one of the leading sandbox providers, went from 40,000 sandbox sessions per month in March 2024 to roughly 15 million per month by March 2025, with approximately 50% of Fortune 500 companies now running agent workloads. Meanwhile, Veracode’s 2025 report found that 45% of AI-generated code fails security tests. This combination — massive adoption plus unreliable code quality — makes sandboxing an essential engineering discipline, not an optional hardening step.

This topic covers the isolation technologies, architectural patterns, and security considerations for safely executing AI-generated code in production systems.

How It Works

The Isolation Spectrum

Sandbox technologies exist on a spectrum from lightweight process isolation to full hardware virtualization. Each level trades off security strength against performance and resource overhead:

Key Concept: Kernel Sharing is the Core Risk

Container-based solutions (Docker, macOS Seatbelt, Linux Bubblewrap, Windows AppContainer) share the host kernel with the sandboxed process. Because agentic tools execute arbitrary code by design, kernel vulnerabilities can be directly targeted as a path to full system compromise. To prevent these attacks at an architectural level, run agentic tools within a fully virtualized environment isolated from the host kernel — VMs, unikernels, or Kata containers.

Firecracker MicroVMs: The Industry Standard

Firecracker, originally developed by AWS for Lambda and Fargate, has become the dominant technology for agent sandboxing. It creates lightweight virtual machines called microVMs that boot in under 200 milliseconds while providing full kernel-level isolation.

E2B, the most widely adopted agent sandbox platform, builds on Firecracker with a template-based architecture:

  1. Template Definition: You define an environment using a standard Dockerfile specifying the OS, language runtimes, packages, and tools your agent needs.
  2. Snapshot Creation: E2B uses the Dockerfile not to run a container, but as a build artifact to create a pre-configured, snapshotted microVM image.
  3. Instant Provisioning: When a new sandbox is requested, E2B restores the snapshot rather than building from scratch, achieving sub-200ms cold starts.
  4. Ephemeral Execution: Each sandbox is isolated, disposable, and destroyed after use. No state persists between sessions unless explicitly saved.
# E2B sandbox usage example (Python SDK)
from e2b_code_interpreter import Sandbox

# Create a sandboxed environment (boots in ~200ms)
sandbox = Sandbox()

# Execute AI-generated code safely
result = sandbox.run_code("""
import pandas as pd
import numpy as np

# This runs in an isolated microVM - can't access host
data = pd.DataFrame({'values': np.random.randn(1000)})
print(f"Mean: {data['values'].mean():.4f}")
print(f"Std:  {data['values'].std():.4f}")
""")

print(result.text)  # Get stdout from sandbox

# Sandbox is destroyed - no persistent state
sandbox.close()

The Kubernetes Agent Sandbox

For organizations already running Kubernetes, the Agent Sandbox project (a Kubernetes SIG initiative) provides a standardized way to run agent workloads. It defines custom resource definitions (CRDs) for sandbox environments that integrate with existing cluster management, RBAC policies, and network policies. This approach leverages gVisor or Kata Containers for isolation within the Kubernetes ecosystem.

Cloudflare Sandbox SDK

Cloudflare’s Sandbox SDK takes a different approach: sandboxes run at the edge on Cloudflare’s global network. This is particularly suited for applications where agents need to execute code close to users with minimal latency. The SDK provides a V8 isolate-based sandbox for JavaScript/TypeScript execution and a microVM-based sandbox for general-purpose code.

Critical Security Considerations

Environment Variable Leakage

This is the biggest security blind spot in agent sandboxing. Even a properly isolated sandbox can exfiltrate secrets if environment variables containing API keys, database credentials, or tokens are passed into the sandbox environment. A prompt injection or hallucinated code can read os.environ and send the contents to an external server.

Key Concept: Secret Hygiene

Never pass secrets as environment variables into agent sandboxes. Instead, use a proxy architecture: the sandbox communicates with your backend through an authenticated API gateway that injects credentials server-side. The sandbox never sees the actual secrets — it only knows the gateway endpoint.

# BAD: Passing secrets into sandbox
sandbox = Sandbox(env_vars={
    "DATABASE_URL": "postgres://user:password@host/db",  # Exposed!
    "OPENAI_API_KEY": "sk-..."                            # Exposed!
})

# GOOD: Proxy architecture
sandbox = Sandbox(env_vars={
    "API_GATEWAY": "https://internal-gateway.myapp.com/agent-proxy"
    # Gateway handles auth server-side; sandbox never sees credentials
})

Network Egress Control

Without network restrictions, sandboxed code can exfiltrate data by making HTTP requests to attacker-controlled servers. Production sandboxes should implement strict network egress policies:

Resource Limits

Agent-generated code can accidentally (or maliciously) consume unbounded resources through infinite loops, memory allocation bombs, or fork bombs. Every sandbox must enforce:

Filesystem Isolation

Sandboxes should use read-only root filesystems with writable tmpfs mounts for agent work. Input data should be injected as read-only volumes, and output should be extracted through defined channels (stdout, specific output directories) rather than giving the sandbox write access to shared storage.

Practical Applications

AI Coding Assistants

Tools like Manus, Devin, and Claude Code use sandboxed environments to let AI agents write, test, and debug code iteratively. The agent generates code, executes it in a sandbox, observes the output, and refines its approach — all without any risk to the host system. E2B reports that Manus uses their platform to provide agents with “virtual computers” that persist for hours across multi-step coding sessions.

Data Analysis Pipelines

AI agents that analyze user-uploaded data need to execute arbitrary Python/R code against potentially untrusted datasets. Sandboxing ensures that a malicious CSV with embedded formulas or a crafted Pickle file can’t compromise the analysis infrastructure. The sandbox contains the blast radius to a single ephemeral VM.

Automated Testing and CI/CD

AI-powered code review tools that actually run generated tests or suggested fixes use sandboxes to verify that the code works before presenting results to the developer. Each test run gets a clean, isolated environment that mirrors the target deployment stack.

Research and Experimentation

ML researchers use sandboxed environments to let agents explore hyperparameter spaces, run training experiments, and analyze results autonomously. The sandbox provides reproducible environments while preventing runaway experiments from consuming cluster resources.

Key Takeaways

Further Reading