AI Agent Guides 10 min read

AI Agent Sandbox: What It Isolates and How to Choose One

Five layers, the options from Docker to microVMs, the exact Claude Code and Codex switches, and the part no sandbox covers.

What an AI agent sandbox isolates (files, network, secrets, writes), Docker vs gVisor vs microVMs, and a staged test before an agent touches real data.

Shabnam Katoch

Growth Head

AI agent sandbox: the four layers it isolates where the agent runs, and the connected accounts no sandbox covers

An AI agent sandbox is an isolated place where an agent can run code, use tools and browse without reaching your real files, credentials or production systems. It limits the damage from a bad command or a prompt injection. It does not limit what the agent can do with the accounts you connect, so you still need scoped permissions and approvals.

If your agent...Start with
Writes code on your laptopIts built-in sandbox, credential files denied, a domain allowlist
Runs code you didn't writeA separate kernel: gVisor, Kata or a microVM
Sends email, edits a CRM or takes paymentsTest accounts, then writes held for your approval

Checked on Claude Code 2.1.334 and Codex CLI 0.173.0. For the wider threat list, see our guide to AI agent security risks.

Picture this: you ask an agent to clear out old build files, and it runs rm -rf one folder too high.

Or a web page it reads tells it to email your customer list to a stranger.

Would a sandbox have stopped either? The first, yes. The second, usually not.

What an AI agent sandbox isolates: five layers

A sandbox isn't one switch. It's five controls, and each tool covers a different mix.

LayerWhat goes wrong without itTypical control
FilesThe agent reads ~/.ssh or deletes the repoMount one working directory; deny reads on credential paths
Network egressIt sends your data out or downloads a payloadA proxy with a domain allowlist, or no network
SecretsKeys sit in env vars or files it can printInject per task; short-lived, scoped tokens
Host kernel and processesA container escape, or a crypto-miner on your hostgVisor, Kata or a microVM instead of a shared kernel
Side effects in real systemsEmails sent, records changed, money movedTest accounts and writes held for approval (not a sandbox feature)

The layers lean on each other: Claude Code's docs warn that without network limits, "a compromised agent could exfiltrate sensitive files like SSH keys."

A sandbox decides what an agent can reach. It doesn't decide what the agent does with the access you hand it.

The first four live where the agent runs. The fifth lives in the systems it touches, where the confused deputy problem bites: an agent using your access on someone else's behalf.

What an AI agent sandbox isolates: files, network egress, secrets and the host kernel where the agent runs, and side effects in the systems it touches

AI agent sandbox options, from lightest to strongest

Setup times are our estimates; claims and prices are each project's own.

OptionWhat it isolatesSetupCostGood for
Your laptop, no sandboxNothingNone$0Throwaway experiments
Docker or a dev containerNamespaces on the shared host kernelMinutes$0Code you trust
gVisor (runsc)A userspace "application kernel" in front of yoursAbout an hour$0, open sourceUntrusted code on Linux
Kata ContainersA lightweight VM, with its own kernel, per workloadHours$0, open sourceClusters that need VM isolation
FirecrackerKVM microVMs that "Boot in <125ms" (vendor claim)Days, to build on$0, open sourceYour own sandbox service
Docker Sandboxes (sbx)A microVM per sandbox, with its own kernelMinutesLocal $0; cloud pay as you goCoding agents on your machine
E2B or Daytona (hosted)A sandbox per session (E2B uses Firecracker)Minutes, via an APIE2B Pro $150 a month plus per-second usage (Hobby $0, one-time $100 credit); Daytona $0.0504 per vCPU hour plus memoryApps running model-written code
Kubernetes agent-sandboxA Sandbox resource; gVisor or Kata do the isolatingHours, on a cluster$0, open sourceTeams on Kubernetes
A VM per agent, or a managed hostA whole machine per agentVariesVariesLong-running business agents

Checked: 2 December 2026

The cheapest step up from plain Docker is a runtime swap; Docker documents gVisor and Kata as alternatives to runc. With gVisor installed:

sudo runsc install
sudo systemctl restart docker
docker run --runtime=runsc --rm hello-world

The catch, per gVisor's docs: "reduced application compatibility and higher per-system call overhead." Docker Sandboxes is a separate product: "The primary trust boundary is the microVM," and outbound traffic needs a matching policy rule.

Running Hermes Agent in plain Docker? Our Hermes Agent Docker guide covers that setup.

AI agent sandbox options from lightest to strongest: laptop, Docker, gVisor, Kata, Docker Sandboxes, Firecracker and a VM per agent

Coding agents have built-in sandboxes

Most sandbox searches are about coding agents. The two biggest ship their own: Codex starts sandboxed, Claude Code doesn't.

Claude Code: off until you turn it on

Run /sandbox in a session, or set sandbox.enabled to true in ~/.claude/settings.json. It uses Seatbelt on macOS and bubblewrap plus socat on Linux and WSL2; on native Windows, "Claude Code runs commands unsandboxed."

Know its edges:

  • It wraps shell commands only: "Claude's file tools, MCP servers, and hooks run outside it."
  • Reads cover "most of the machine, including credential files such as ~/.ssh and ~/.aws/credentials," and "There is no built-in credential deny list."
  • Network goes through a local proxy, and your allowed domains "start empty."
  • If the sandbox can't start, commands run unsandboxed unless you set failIfUnavailable.

A tighter user-level setup:

{
  "sandbox": {
    "enabled": true,
    "failIfUnavailable": true,
    "allowUnsandboxedCommands": false,
    "network": {
      "allowedDomains": ["registry.npmjs.org"],
      "strictAllowlist": true
    },
    "credentials": {
      "files": [
        { "path": "~/.ssh", "mode": "deny" },
        { "path": "~/.aws/credentials", "mode": "deny" }
      ],
      "envVars": [{ "name": "GITHUB_TOKEN", "mode": "deny" }]
    }
  }
}

allowUnsandboxedCommands: false blocks retries outside the sandbox, strictAllowlist refuses unlisted hosts, and filesystem.denyRead covers other paths. Keep excludedCommands empty: those commands skip the sandbox. Test it by asking Claude, not the ! prompt, to run touch ~/sandbox-probe; it should fail.

To cover file tools and MCP servers too, run the whole process in Anthropic's sandbox runtime (srt claude, a beta), a dev container or a VM.

Codex: sandboxed by default

The Codex CLI starts with network off and writes limited to the workspace, enforced by Seatbelt on macOS, bwrap plus seccomp on Linux and MXC on Windows:

codex --sandbox read-only --ask-for-approval on-request        # read, don't write
codex --sandbox workspace-write --ask-for-approval on-request  # the "Auto" preset

Current values (older guides still show retired ones):

  • --sandbox takes read-only, workspace-write or danger-full-access.
  • --ask-for-approval takes only on-request or never. untrusted is retired, and an old config with it "can prevent either client from starting."
  • --full-auto is in neither the CLI reference nor the 0.173.0 flag code. --approve-for-me pairs workspace-write with a reviewer agent that vets approval requests.
  • --yolo drops the sandbox and approvals: "Only use inside an externally hardened environment."

Network stays off unless you set network_access = true; then add features.network_proxy with domain rules, or outbound access is unrestricted. codex sandbox linux (or macos) shows what the sandbox blocks, and our read-only sandbox error decoder covers "patch rejected: writing is blocked by read-only sandbox".

Gemini CLI

Turn it on with -s or GEMINI_SANDBOX; it can use Seatbelt, Docker or Podman, gVisor, LXC or a Windows sandbox, and its default macOS profile still allows network access.

Any agent: a worktree and a diff

Give the agent a disposable git worktree and read the diff before merging. Claude Code makes one with claude --worktree <name>; Codex's docs say to treat its changes "like any other PR."

Claude Code and Codex CLI sandboxes side by side: default state, what each wraps, network defaults and the current flags

Business agents need a different kind of sandbox

An email, CRM or payments agent can sit in the tightest microVM and still email the wrong customer. The risk lives in the other system, so test against a fake copy.

SystemTest versionWhat you get
Gmail or Google WorkspaceA separate Google account as a test inboxReal mail, no real customers (we found no Gmail sandbox)
HubSpotDeveloper test accountsUp to 10 at $0, "without affecting any real HubSpot data"
StripeA sandboxPayments that "aren't processed by card networks or payment providers"
Anything that sends, deletes or paysReads allowed, writes heldApproval before the write runs

Checked: 2 December 2026

HubSpot test accounts only send marketing email to users you've added, and standard sandboxes need Enterprise. Stripe's CLI makes an anonymous sandbox with working API keys (stripe sandbox create), no account needed.

Test in three stages before real data

Test two things separately: can the agent do the job, and what happens when it does? Stage one answers the first safely.

  1. Replay past tasks against test accounts, with every write logged instead of sent.
  2. Point it at real data with every send, update and payment held for approval.
  3. Give it a small slice of real traffic, with logs on and a kill switch you've tried.

Widen only when stage three stays boring. Our guide on how to test an AI agent covers the full method.

Business agent testing: a test inbox, HubSpot test account and Stripe sandbox, then three stages from replayed tasks to a small slice of real traffic

What an AI agent sandbox won't protect you from

These go straight through the box:

  • The confused deputy. Your Gmail or CRM access, used for someone else because a message or web page asked.
  • Broad OAuth scopes and keys. If the connection can delete mail, a sandboxed agent can delete mail.
  • Approvals typed in the same chat. If the person asking can reply "approved" there, the approval proves little.
  • Tools outside the box. Claude Code's file tools and MCP servers run outside its sandbox, and Codex's network proxy "does not filter web search, app or connector tool calls, MCP server connections."
  • Access passed in on purpose. Docker Sandboxes forwards your SSH agent by default, so "any process inside the sandbox can ask the forwarded agent to authenticate or sign data."

Anthropic's guide to sandbox environments: "Any approach that allows network egress can still leak data the agent can read."

Self-hosting OpenClaw? Our OpenClaw security checklist covers the host side.

What an AI agent sandbox won't stop: a contained command inside the box, while connected accounts, allowed domains and in-chat approvals pass straight through

How BetterClaw isolates agents

Here's our own setup, gaps included:

  • Each BetterClaw agent runs on its own machine (a Fly.io Machine) with its own storage bucket and a storage key scoped to that bucket, no public IP and no inbound ports; it dials out to BetterClaw.
  • Agents have open outbound internet access (they need it for browsing and APIs); there's no per-agent outbound allowlist today.
  • Agents in the same Project share that Project's computer and files; separate Projects are sealed from each other.
  • Connector and MCP credentials stay with BetterClaw; the agent calls the tools, it never sees those credentials. Workspace secrets an agent fetches with a secret tool are returned to it so it can use them.
  • In a workflow, any step can be set to ask you first before it runs.

For side effects, the control is yours to add: a workflow step that asks first sends nothing until someone decides, and an unanswered request expires after 24 hours. If you need an egress allowlist, we don't offer one today.

How BetterClaw isolates agents: a machine and storage bucket per agent, a shared Project computer for teammates, no inbound ports and open outbound internet

AI agent sandbox checklist (copyable)

[ ] Working directory only; nothing else writable
[ ] Credential paths (~/.ssh, ~/.aws) denied for reads
[ ] Network through an allowlist, or off
[ ] Secrets injected per task: scoped and short-lived
[ ] Separate kernel (gVisor, Kata, microVM) for untrusted code
[ ] Test accounts for email, CRM and payments
[ ] Writes held for approval
[ ] Disposable worktree, diff reviewed before merge
[ ] Logs kept for every tool call
[ ] A kill switch you have actually tried

If an OpenClaw container breaks after you tighten it, start with our OpenClaw Docker troubleshooting guide.

The sandbox is for the command you didn't see coming. The approval step is for the email you did.

Let BetterClaw run the machine

Rather not build this stack? BetterClaw runs each agent on its own machine with no inbound ports (teammates in a Project share one), and any workflow step can ask before it acts. Outbound stays open, so keep the checklist's approvals.

Plans start at $19 a month, BYOK with zero markup on LLM inference. Your first workspace gets a 7-day trial: BetterClaw charges your card $5 to verify it, refunds it right away and bills the plan when the trial ends unless you cancel. Start a 7-day trial · BYOK

Frequently Asked Questions

What is an AI agent sandbox?

An isolated environment where an agent runs code, uses tools and browses without reaching your real files, credentials or production systems. It limits damage from bad commands and prompt injection, not misuse of accounts you connect.

How do you properly sandbox an AI agent?

Cover five layers: files limited to a working directory, network through an allowlist, scoped secrets per task, a separate kernel for untrusted code, and writes held for approval. Then test in stages before real data.

Do I need a sandbox for an AI agent?

If it runs code, installs packages or browses, yes. If it only handles email or CRM records, test accounts and approval steps matter more, because the risk sits in those systems.

Is Docker enough to sandbox an AI agent?

For code you trust, usually. A container shares the host kernel, so a kernel or runtime bug can become an escape. For untrusted or model-written code, add gVisor (docker run --runtime=runsc), Kata or a microVM.

How do I sandbox Claude Code?

Run /sandbox or set sandbox.enabled to true in ~/.claude/settings.json. It wraps shell commands only, and by default commands can still read ~/.ssh, so deny credential files under sandbox.credentials and set failIfUnavailable.

Can an AI agent break out of a sandbox?

Yes, through real bugs: in November 2025 runc, Docker's default runtime, fixed three flaws that could lead to a container escape (CVE-2025-31133, CVE-2025-52565, CVE-2025-52881). A separate kernel lowers that risk; the bigger leak is access you hand the agent.

Can a sandboxed agent still leak data?

Yes. Anything it can read can leave through an allowed domain; Claude Code's docs warn that broad entries such as github.com can create paths for exfiltration. It can also email or post what it read through connected accounts.

What's the difference between a sandbox and a staging environment?

A sandbox is where the agent runs: its files, network and kernel. Staging is the systems it acts on, like a test inbox or a Stripe sandbox. A perfect sandbox still sends real email if it's wired to your real inbox.

Want to skip the setup?

BetterClaw does this in 60 seconds. No Docker, no config files.

Start free
Tags:ai agent sandboxagent sandboxsandbox for ai agentshow to sandbox ai coding agentclaude code sandboxcodex sandboxai agent isolationdocker sandbox ai agent
Shabnam Katoch

Written by

Growth Head

Shabnam leads growth at BetterClaw and has spent the past three years building organic distribution for AI-native products. She writes about no-code agent builders, content strategy, and what it actually takes to grow without an ads budget.

Share this article
Was this helpful?