AI Agent Sandbox Architecture: How to Let Agents Run Code Without Letting Them Run Everything
From the publisher’s feed, collected in the ZeroLabs newsroom.
AI Agent Sandbox ArchitectureA practical developer guide to isolation, egress, secrets, file sync, observability, and approval gates for production AI agents.An AI agent with terminal access is not just a chatbot with extra buttons. It is a process that can write files, install packages, call APIs, browse hostile pages, mutate state, and chain small decisions into large side effects.That is useful. It is also the exact reason sandboxing has moved from “nice security feature” to core agent infrastructure.The mistake many teams make is treating sandboxing as a checkbox. They run the agent in Docker, restrict a few commands, and assume the problem is solved. But production AI agent sandboxes are not only about containers. A useful sandbox architecture controls the full execution boundary: what the agent can see, what it can write, what it can call, which secrets it can touch, how files move in and out, how long work can run, and how humans review risky actions.This guide is for developers, founders, platform engineers, and AI builders who are ready to move past demos. If your agent can execute code or tools, this is the architecture you need before giving it real work.Why AI Agent Sandboxes Matter NowAgent sandboxes are getting attention because the market has crossed an important line. AI systems are no longer limited to drafting answers. They are increasingly expected to operate software: clone repositories, run tests, edit files, automate browsers, inspect logs, transform data, call internal tools, and trigger workflows.Recent production writeups show the same direction. Gobii describes a sandboxed agent system built around per-agent isolation, proxy-only egress, deterministic file sync, strict timeouts, and audit trails. Fly.io frames agent sandboxes as controlled runtimes where agents can call tools and run code without touching production systems or live data. OpenAI’s Codex safety documentation describes isolated cloud containers, network access disabled by default, workspace-scoped file access, and allowlist-based internet access as risk controls for agent execution.The security data also points in the same direction. Endor Labs’ AI Coding Agent Security Benchmark reported a sharp gap between functional correctness and secure correctness across evaluated coding-agent setups. In other words, an agent can produce code that works while still producing code that is unsafe. The CIBER benchmark paper makes a related point for code interpreter agents: dynamic code execution, tool interaction, prompt injection, memory poisoning, and multi-turn context create risks that static checks do not fully capture.The practical lesson is simple: do not ask, “Can the model be trusted?” Ask, “What can happen if this run goes wrong?” Then design the sandbox so the worst realistic failure is boring.The Core Principle: Separate the Brain From the Blast RadiusA production agent system usually has two broad halves.The trusted control plane owns identity, policy, routing, billing, orchestration, audit logs, and user-visible state. The untrusted execution plane runs the agent’s messy work: shell commands, code execution, temporary files, browser automation, package installation, and tool adapters.That separation is the heart of AI agent sandbox architecture. The control plane should remain boring, explicit, and conservative.A sandbox is not where you put work you trust. It is where you put work that is useful enough to run and risky enough to contain.The clean architecture looks like this:The user asks for work in the app or API.The control plane creates a task, loads policy, and provisions a sandbox.The sandbox receives scoped input, not full production access.The agent uses tools inside the sandbox boundary.Network calls pass through an egress proxy or are blocked.Secrets are brokered through short-lived, scoped credentials.Files are synced through a deterministic handoff layer.Logs, traces, commands, file diffs, and approvals are recorded outside the sandbox.The sandbox is destroyed, paused, or snapshotted after the run.Notice what is missing: the agent never gets direct access to the host machine, production database, unrestricted network, long-lived credentials, or internal admin APIs just because the model asked nicely.What Belongs Inside the Sandbox?Put actions inside the sandbox when they involve untrusted content, mutation, code execution, dynamic browsing, or uncertain tool behavior.That includes shell commands, Python or JavaScript execution, package installs, browser automation, scraping, file writes, build steps, test runs, document parsing, user-uploaded files, third-party webpage reading, and MCP tools that touch external systems.Keep control-plane responsibilities outside the sandbox. That includes authentication, billing, persistent user permissions, policy decisions, production secrets, global audit storage, task assignment, user notifications, and final approval workflows.A helpful rule: if the model can influence the operation directly, assume the operation is untrusted. If the operation decides what the model is allowed to do, keep it outside the model’s reach.Three Sandbox Patterns Developers Actually UseThere is no one correct sandbox runtime. The right choice depends on latency, isolation, cost, workload shape, and how much infrastructure your team can operate.1. Container SandboxesContainers are the easiest starting point. You can run each task in a dedicated container with resource limits, a mounted workspace, read-only base image, restricted capabilities, no privileged mode, and a short lifetime.This is a good fit for internal tools, short code execution, build/test workflows, and early production systems where speed matters. But a plain container should not be your final answer for high-risk workloads. Harden it with user namespaces, seccomp, AppArmor or SELinux, read-only root filesystems, dropped Linux capabilities, strict cgroups, and network policy.2. MicroVM or Kernel-Isolated SandboxesMicroVMs and stronger sandboxed runtimes add a more serious boundary. Firecracker-style microVMs, gVisor-backed pods, and similar isolation layers can reduce the risk that a hostile workload breaks out into the host. They usually cost more in startup complexity, networking design, image management, and operations.Use this pattern when agents run arbitrary user code, process sensitive data, browse unknown sites, install dependencies, or operate in multi-tenant environments. For many AI products, this is where production architecture eventually lands.3. Remote Sandbox-as-a-ToolSome teams keep the agent loop in their own service and call a remote sandbox only when execution is needed. The sandbox becomes a tool: run code, inspect files, render a browser, or execute a command, then return structured output.This can be easier to integrate because your control plane stays stable. It also avoids moving every part of the agent into a remote runtime. The tradeoff is that you must be careful about file sync, state continuity, network policy, and latency between the agent loop and the sandbox.A useful sandbox is a system boundary, not just a container.The Seven Controls Every Agent Sandbox Needs1. Scoped Filesystem AccessThe agent should see a task workspace, not your whole machine. Give it a clean working directory with the files required for the task. Mount source code read-write only when editing is required. Mount reference files read-only. Keep home directories, SSH keys, shell history, cloud credentials, browser cookies, and unrelated repositories out of reach.For coding agents, file sync deserves special attention. Treat the final output as a diff or artifact bundle, not as a magical mutation of production state.2. Network Egress ControlMost dangerous agent failures need the network. Data exfiltration, unexpected API calls, package confusion, dependency downloads, tracking pixels, and prompt-injection payloads all become worse when outbound traffic is open.Default to no network. Then add allowlists by domain, protocol, and HTTP method. For example, a build task may need access to npm, PyPI, GitHub, or a private package registry. It probably does not need arbitrary outbound POST requests to unknown domains.Put outbound traffic through an egress proxy so you can log requests, block risky destinations, enforce rate limits, and redact sensitive headers. If the task requires browsing the public web, make that a conscious permission mode, not the default.3. Secret Brokering Instead of Secret MountingDo not mount long-lived production secrets into an agent sandbox. If the agent needs credentials, issue short-lived, scoped, auditable tokens through a broker. Prefer capability-specific tokens: read-only issue tracker access, one repository token, one storage bucket prefix, one staging API scope.The agent should not learn secrets unless the task absolutely requires it. Many workflows can be designed so the sandbox asks the control plane to perform a privileged action after policy checks, rather than holding the secret itself.4. Resource Limits and TimeoutsAgents can loop. Code can hang. Package installs can explode. Browser sessions can leak memory. Treat resource limits as part of the product contract.Set CPU, memory, disk, process count, wall-clock, stdout, stderr, network bandwidth, and tool-call limits. Return clear failure messages when limits are hit. A timeout should create a useful trace, not a mystery.5. Tool Policy GatesNot every tool call has the same risk. Reading a file is different from deleting a directory. Running tests is different from deploying. Fetching a public page is different from posting to Slack or charging a card.Model this directly. Assign each tool action a risk level and a policy:Auto-allow low-risk reads inside the workspace.Auto-allow test and build commands with resource limits.Require approval for writes outside the workspace.Require approval for network access to new domains.Block credential access unless explicitly granted.Block production mutations by default.A simple policy wrapper makes this explicit:type ToolAction = { name: string; args: Record; workspaceId: string; requestedBy: "agent" | "user";};function classify(action: ToolAction) { if (action.name === "read_file") return "low"; if (action.name === "run_tests") return "low"; if (action.name === "write_file") return "medium"; if (action.name === "http_request") return "medium"; if (action.name === "deploy" || action.name === "delete_file") return "high"; return "review";}function policyDecision(action: ToolAction, allowedDomains: string[]) { const risk = classify(action); if (risk === "low") return { decision: "allow" }; if (action.name === "http_request") { const url = new URL(String(action.args.url)); if (!allowedDomains.includes(url.hostname)) { return { decision: "review", reason: "new outbound domain" }; } } if (risk === "high") { return { decision: "review", reason: "high-impact tool action" }; } return { decision: "allow" };}This changes the mental model. The model proposes actions. The policy layer decides which actions are allowed.6. Observability Designed for ReplaysLogging agent output is not enough. You need to reconstruct what happened.Capture the user request, model configuration, system instructions hash, tool schema version, policy version, sandbox image version, command history, stdout and stderr summaries, file diffs, network attempts, approval decisions, token usage, cost, duration, and final artifacts.For sensitive systems, store enough data to replay the run against a fresh sandbox with redacted secrets. When something goes wrong, you want to know whether the failure came from the prompt, model, tool wrapper, policy, dependency, file state, or human approval.7. Cleanup and RetentionSandboxes should not quietly become permanent servers. Decide what happens after each run. Destroy the sandbox for low-trust tasks. Snapshot it only when continuity is required. Retain artifacts intentionally. Expire logs according to data policy. Wipe temporary credentials. Revoke network grants.The safest sandbox is often the one that no longer exists.How to Design the Permission ModelDo not copy human developer permissions into the agent. Humans carry context, judgment, accountability, and social friction. Agents need narrower, task-shaped permissions.Start with four layers:Workspace permissions: which files can be read, written, created, or deleted.Tool permissions: which commands, APIs, and integrations are available.Network permissions: which hosts and methods are allowed.State permissions: which changes can persist after the run.Then make permissions visible. The user or developer should be able to inspect the run profile before work begins:{ "profile": "repo-maintenance-agent", "filesystem": { "read": ["./"], "write": ["./src", "./tests"], "deny": ["./.env", "./secrets", "./deploy"] }, "network": { "default": "deny", "allow": ["registry.npmjs.org", "api.github.com"] }, "tools": { "allow": ["read_file", "write_file", "grep", "npm_test", "git_diff"], "review": ["install_package", "open_pull_request"], "deny": ["deploy_production", "delete_repository"] }, "retention": { "sandbox": "destroy_after_run", "artifacts": "keep_30_days" }}This is also where many teams discover hidden risk. If the run profile needs broad workspace access, open network, write access to credentials, and production mutation permissions, the problem is probably not the sandbox. The workflow is too broad.Common Failure Modes“We Use Docker, So We Are Safe”Docker is a useful packaging and isolation tool. It is not automatically a safe agent boundary. Privileged containers, mounted Docker sockets, broad host mounts, shared credentials, and open egress can erase most of the safety benefit.“The Agent Only Runs Internal Tools”Internal tools can be more dangerous than public tools because they carry real privileges. A support-ticket tool may expose customer secrets. A billing tool may mutate subscriptions. A Slack tool may leak incident details. Treat internal tools as high-value capabilities.“We Review the Final Output”Final review is necessary, but it cannot catch every side effect that already happened. If the agent posted data to an external API, deleted a file, or queried sensitive records, the damage may happen before the final answer appears.“The Model Is Aligned”Alignment helps. It does not replace boundaries. Prompt injection, confusing instructions, malicious webpages, poisoned memories, dependency scripts, and ambiguous goals can still push the run into unexpected behavior. The sandbox should assume the model can make a bad decision.Production sandboxes need operational visibility: traces, policy decisions, egress events, approvals, and diffs.A Practical Rollout PlanPhase 1: Local Safe DefaultsStart by running agent tasks in a dedicated workspace. Block network by default. Remove access to secrets. Require approval for destructive commands. Log every command and file diff. This is enough to catch obvious workflow problems before you invest in a heavier runtime.Phase 2: Disposable Remote ExecutionMove shell execution, browser automation, and code interpretation into disposable remote sandboxes. Give each task a fresh environment. Sync only the files needed for the task. Return diffs and artifacts, not direct production mutations.Phase 3: Policy-Aware Agent PlatformAdd run profiles, domain allowlists, approval queues, tool risk levels, secrets brokering, trace storage, and replay. At this stage, the sandbox is no longer a hidden infrastructure detail. It becomes part of your developer platform.Phase 4: Continuous EvaluationBuild adversarial test cases. Try prompt injection through webpages, README files, tickets, PDFs, and tool outputs. Test whether the agent can read denied files, reach blocked domains, leak secrets, bypass approval, exhaust resources, or persist state unexpectedly.Measure both task success and containment success. A run that solves the task while violating policy should count as a failure.Build vs. Buy: How to ChooseBuy or use a managed sandbox when you need speed, multi-tenant isolation, browser support, warm starts, and operational reliability more than runtime customization.Build your own when your workload has strict data residency requirements, unusual network rules, private cloud constraints, custom kernel-level needs, or deep integration with internal developer infrastructure.A balanced path is common: start with a managed sandbox for product learning, then move high-risk workloads into your own VPC or hardened environment once the permission model is clear.The Best Sandbox Is a Smaller TaskSandboxing is not a license to give an agent an enormous goal and hope for the best. The safest architecture still benefits from small, inspectable tasks.Instead of “fix the production billing system,” ask the agent to inspect a failing test, propose a patch, run the test suite, and produce a diff. Instead of “deploy this change,” ask it to prepare a release checklist and wait for approval.Good agent systems combine three things: capable models, narrow tasks, and strong boundaries. Remove any one of those and the system becomes either useless or unsafe.Final Checklist for AI Agent Sandbox ArchitectureBefore you let an AI agent run code in a real workflow, answer these questions:What files can the agent read, write, create, and delete?Is network access denied by default?Which domains, methods, and protocols are allowed?Can the agent access long-lived secrets?Are privileged actions brokered through policy checks?Are commands, tool calls, network attempts, approvals, and diffs logged?Can risky actions trigger human review before execution?Are CPU, memory, disk, process, time, and output limits enforced?Can the run be replayed or audited after failure?Is the sandbox destroyed or cleaned after the task?If these answers are vague, the agent is not ready for production autonomy. It may still be useful, but it should stay in a limited workflow until the boundary is explicit.FAQWhat is AI agent sandbox architecture?AI agent sandbox architecture is the system design used to run agent actions inside a controlled execution boundary. It usually includes isolated compute, scoped file access, network restrictions, secrets brokering, policy gates, observability, and cleanup rules.Is Docker enough for AI agent sandboxing?Docker can be part of the answer, especially for early systems, but it is not enough by itself. You still need hardened runtime settings, no privileged mode, restricted mounts, resource limits, network egress controls, secret isolation, audit logs, and approval gates.Should AI agents have internet access?Default to no internet access. Enable it only when the task requires it, and prefer allowlists, safe HTTP methods, egress logging, rate limits, and domain-specific approvals. Open internet access increases prompt-injection and data-exfiltration risk.How should developers handle secrets in agent sandboxes?Use short-lived, scoped credentials issued by a broker. Avoid mounting broad production secrets into the sandbox. When possible, let the trusted control plane perform privileged actions after policy checks instead of exposing secrets to the agent runtime.How do you test whether an AI agent sandbox is working?Create adversarial test runs. Try to make the agent read denied files, call blocked domains, leak fake secrets, bypass approvals, run destructive commands, exhaust resources, or persist unauthorized state. A sandbox passes when it blocks or routes these actions to review while preserving useful work.Sources and Further ReadingGobii: How We Sandbox AI Agents in ProductionFly.io: Agent SandboxesEndor Labs: AI Coding Agent Security BenchmarkCIBER: Security Evaluation of Code Interpreter AgentsOpenAI GPT-5.2-Codex System Card AddendumAI Agent Sandbox Architecture: How to Let Agents Run Code Without Letting Them Run Everything was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.