Xiaobai
Developer · Builder
Building AI engineering systems, developer tools and long-term digital assets at XBSTACK.
About Xiaobai & XBSTACK →
AI Agent Sandbox Design: Hosted vs Self-Hosted, Files, Secrets, Network, and Persistence
A production AI agent sandbox guide focused on AI security and isolation. Compare hosted vs self-hosted across files, secrets, network access, persistence, tenant boundaries, and operations.
The conclusion first: a sandbox is not “a machine for the agent” — it is an enforceable boundary
When an agent only produces text, the main failure mode is a bad answer. Once it can run shell commands, install packages, write files, open a browser, or call APIs, the failure mode becomes an execution-boundary failure.
A production sandbox should answer five questions independently of the prompt:
- Which files can the agent read or write?
- Which network destinations can it reach?
- When and with what scope can it use a secret?
- How long should workspace state and generated files survive?
- Are users, projects, and workloads actually isolated?
If those answers exist only in natural-language instructions, they are preferences rather than security controls.
OpenAI currently describes sandbox agents as isolated Unix-like environments with filesystems, shells, packages, ports, snapshots, and controlled external access. It supports both hosted and self-hosted environment models. Anthropic’s Claude Code sandboxing focuses on the same two fundamental boundaries: filesystem access and network access.
Hosted vs self-hosted: compare responsibility, not branding
The useful distinction is not merely “cloud versus local.” It is who creates, isolates, patches, destroys, and audits the execution environment, and how much infrastructure control your workload requires.
| Dimension | Hosted Sandbox | Self-hosted Sandbox |
|---|---|---|
| Provisioning and lifecycle | Provider-managed | You manage it |
| Base environment | Provider image/templates | Fully customizable |
| Private network access | Provider-dependent | Most flexible |
| Special hardware and internal tools | Provider-dependent | Most controllable |
| Network policy | Provider policy/allowlist | You enforce it |
| Secrets | Prefer provider vault/broker | Your secret manager/proxy |
| Persistence | Provider files/snapshots/mounts | Volumes/object storage/snapshots |
| Security patching | More provider responsibility | Your responsibility |
| Portability | Lower | Higher |
| Time to production | Faster | Slower |
| Infrastructure control | Medium | High |
There is no universal rule that hosted is always safer or that self-hosted is always more professional.

Choose hosted when the task mostly needs a standard Linux environment, common runtimes and CLIs, task-scoped files, no private network, and minimal infrastructure operations.
Choose self-hosted when the agent must enter private networks, use proprietary images or system packages, consume special hardware, integrate deeply with existing Kubernetes/VM/IAM/SIEM controls, or satisfy strict data-residency requirements.
Boundary 1: do not let unrelated workloads share the same file world by default
OpenAI’s current self-hosted guidance explicitly notes that agents sharing an environment can access the same files, credentials, and other resources, and recommends isolating environments by user or workload.
Common isolation scopes include:
- per-task: a short-lived sandbox per job;
- per-chat/session: preserve one workspace during an ongoing task;
- per-project: project files persist, but projects are isolated;
- per-user: a durable personal workspace;
- shared worker: acceptable only when filesystem, identity, secrets, tools, and resource quotas are separately enforced.
A working-directory name, Unix username, or prompt instruction is not an isolation boundary when agent-generated code can execute arbitrary commands.
Boundary 2: a secret should not become part of the agent’s knowledge
OpenAI’s current security guidance distinguishes between environment values a process genuinely needs and long-lived third-party credentials. For hosted sandboxes, its recommended pattern is vault-backed placeholders with a network proxy injecting the real credential only for approved destinations. In self-hosted environments, teams need to provide the trusted proxy or service layer themselves.
The principle is simple:
The model may decide that an approved service should be called, but that should not automatically give generated code the service’s long-lived plaintext credential.
If a production key is injected as a normal environment variable, sandbox code may be able to read it. Prompt injection, malicious packages, debug logs, error traces, or generated artifacts can then expose it.
A stronger flow is:
Agent → request intent → Policy Gate → Secret/Network Broker → target service

rather than:
Agent → read production API key → send arbitrary request
This complements XBSTACK’s AI Agent Policy Gate: the policy layer decides whether a call is authorized, while the sandbox and broker determine whether the runtime actually has the credential and network path needed to perform it.
Boundary 3: networking should not default to unrestricted
OpenAI-hosted sandboxes currently expose three network modes: enabled, disabled, and restricted. Restricted mode uses an allowlist of exact hosts.
That suggests a practical default:
- local-only processing: network disabled;
- fixed external APIs: restricted + allowlist;
- general browsing or dependency installation: grant broader access only when needed and keep the sandbox lifetime short.
A self-hosted environment should reproduce the same semantics using container networking, network policies, firewalls, egress proxies, or comparable infrastructure.
Avoid collapsing package downloads, business APIs, browser access, and private services into one unrestricted egress path.
Boundary 4: separate workspace persistence from business-data persistence
A common agent-platform mistake is using the sandbox directory as a database.
A stronger design separates three classes of state.
1. Ephemeral workspace
Clones, extracted archives, caches, build output, and dependencies that can be recreated.
2. Resumable workspace
State required to continue a long-running task, restored through snapshots, volumes, or a controlled persistent directory. It is still execution state.
3. Durable business data and artifacts
Final documents, datasets, patches, uploaded source files, and official reports belong in independent object storage, databases, Git, or document systems with access control, versioning, backup, and deletion policies.
This prevents “the sandbox is still alive” from becoming synonymous with “the business data is safely stored.”

Boundary 5: artifacts still need an egress check
A sandbox limits what code can touch. It does not guarantee that generated output is safe to export.
An artifact may accidentally contain:
- API keys or tokens;
- personal data;
- environment configuration and internal URLs;
- proprietary source code;
- malicious scripts inherited from prompt injection;
- oversized caches or intermediate files.
Treat export as an explicit operation:
Sandbox → Artifact Scanner / Policy → Durable Storage / User Download
At minimum, validate type, size, path, sensitive data, and provenance. Higher-risk systems should also record a hash, generating task, user, timestamp, and approval decision.
A sandbox and a Policy Gate solve different problems
Policy Gate asks: Is this user and task authorized to make this specific tool call with these parameters?
Sandbox asks: Once code is running, which compute, files, networks, and credentials can it actually reach?
Human-in-the-loop asks: Which high-risk actions require a person to confirm again?
Audit asks: Who did what, through which agent and tool, under what context?
Production systems often need all four.
A practical hosted-vs-self-hosted decision tree
1. Does the agent need private-network access?
Yes: strongly consider self-hosting, or verify that the hosted provider offers a private-network model that actually satisfies your requirements.
No: continue.
2. Do you need a custom base image, kernel capability, GPU, or system-level tooling?
Yes: self-hosting usually gives you the necessary control.
No: continue.
3. Does the team want to own patching, scheduling, cleanup, capacity, and isolation?
No: hosted environments have a strong operational advantage.
Yes, and infrastructure is already standardized: self-hosting becomes more attractive.
4. Can long-lived secrets stay outside the sandbox?
If the answer is “no, every production key must be placed into normal environment variables,” stop and redesign before choosing either deployment model.
5. Must work resume across hours or days?
If yes, design snapshots, volumes, and artifact storage explicitly. Do not rely on one running container surviving forever.
What OpenAI’s current hosted and self-hosted models demonstrate
As of September 2026, OpenAI’s documentation makes the responsibility split concrete.
An OpenAI-hosted sandbox provides a Linux workspace with Python, Node.js, command-line tools, files, environment configuration, and network policies. When teams need their own image, compute, or private network, OpenAI explicitly points them toward self-hosted environments.
In self-hosted mode, OpenAI runs the agent harness while an executor runs inside your environment, which can be a laptop, container, or remote sandbox. The executor initiates outbound connections. OpenAI also recommends keeping the application’s API key outside the sandbox and giving the executor a restricted environment credential instead.
The durable lesson is not the API naming. It is the responsibility model:
- what the provider manages;
- what your infrastructure manages;
- what generated code can actually read;
- which credentials never enter the workspace;
- who enforces network and filesystem policy.
Anthropic provides another useful signal: fewer approvals should come from stronger boundaries
Anthropic’s Claude Code sandboxing centers on filesystem and network isolation. One practical motivation is approval fatigue: asking a human to approve every shell command can make users stop paying attention.
A stronger model is to define a machine-enforced boundary first, then allow the agent to act more autonomously inside that boundary.
So a sandbox is not only a breach-containment tool. It also converts a large number of ad-hoc human approvals into a smaller number of durable environment policies.
Production checklist
Isolation
- Is the sandbox scope explicit: user, project, session, or task?
- Can one tenant read another tenant’s files, cache, or credentials?
- Can the agent reach host home directories, SSH keys, browser cookies, or cloud CLI config?
Files
- Is the writable filesystem minimized?
- Are uploads mounted only where the task needs them?
- Do temporary files, snapshots, and final artifacts have different lifecycles?
Secrets
- Are long-lived third-party credentials kept outside the sandbox whenever possible?
- Is there a secret manager, vault, broker, or server-side function tool?
- Are sandbox-visible credentials short-lived, narrowly scoped, and revocable?
Network
- Are offline tasks disconnected by default?
- Do fixed APIs use an allowlist?
- Are metadata endpoints, admin services, and unnecessary private services blocked?
Execution
- Are CPU, memory, disk, process count, and maximum runtime bounded?
- Do package installs, service startup, or port exposure require stronger permissions?
- Do high-risk commands go through a Policy Gate or human approval?
Persistence
- Which state must survive sandbox teardown?
- Has final business data left the temporary filesystem?
- Are snapshot, volume, and artifact retention rules explicit?
Audit
- Can you trace user → agent → tool → sandbox → artifact?
- Are authorization decisions recorded, not just model text?
- Can you revoke secrets, quarantine the environment, and determine blast radius after an incident?
Final decision
If your team mainly needs agents to execute Python, Node, shell commands, process uploaded files, and return artifacts safely, a hosted sandbox is usually the faster starting point.
If the agent must operate deeply inside private infrastructure, requires a custom OS/toolchain or special hardware, or the company already has mature Kubernetes/VM/IAM/secret/audit controls, self-hosting often gives better long-term control.
Whichever model you choose, the strongest production architecture makes four rules enforceable by machines rather than prompts:
minimum filesystem access, secrets kept outside generated code, minimum network access, and a clean separation between execution state and durable data.
Those constraints remain useful even when models, frameworks, and sandbox providers change.
Related reading
- AI Agent Tool Authorization: Policy Gate, HITL, and Per-Call Controls
- AI Agent Security: Prompt Injection, Tool Risk, and Production Controls
- OpenAI Agents API vs Agents SDK vs Responses API
- OpenClaw Sandbox Architecture
Sources
- OpenAI: Sandbox Agents
- OpenAI: OpenAI-hosted sandboxes
- OpenAI: Self-hosted sandboxes
- OpenAI: Sandbox security
- Anthropic: Making Claude Code more secure and autonomous with sandboxing
Continue from one agent pattern to the complete production system
The AI Agent hub organizes architecture, memory, tool use, evaluation, security, deployment and multi-agent coordination into a single learning path.
More to Explore
Topic hub →AI Engineering Weekly
Production changes, real failures, experiments and new XBSTACK assets.
DISCUSSION
Questions, verification and corrections
Sign in to comment. Every new comment is reviewed before publication; while pending, it is visible only to you and the administrator.