OpenAI Agents SDK Sandbox Agents: The Production Isolation Playbook

Use OpenAI Agents SDK Sandbox Agents safely: choose the execution boundary, protect secrets, persist state, log runs, and gate production rollout.

Thursday, July 23, 2026Omid Saffari
OpenAI Agents SDK Sandbox Agents: The Production Isolation Playbook

Use OpenAI Agents SDK Sandbox Agents when the workspace itself is part of the job: files must persist, commands must run behind a controlled compute boundary, or a failed run must resume. For one occasional shell call, hosted shell is the smaller abstraction.

The verdict: use a sandbox for workspace jobs

Sandbox Agents are a good production primitive when the agent needs a living filesystem, but they are not a safety policy. The useful boundary is concrete: the model can inspect files, run commands, edit a working tree, generate artifacts, and continue from saved state without receiving access to the application host.

OpenAI added the JavaScript surface in openai-agents-js v0.9.0 on May 5, 2026. It remains beta, so production teams should isolate the SDK behind an application-owned adapter rather than letting beta types and provider details spread across the product. The current Sandbox Agents quickstart requires Node.js 22 or higher.

The decision rule is narrow:

  • Use hosted shell when the agent needs an occasional bounded command and no durable workspace.
  • Use SandboxAgent when workspace isolation, execution-backend choice, or resume behavior is part of the product.
  • Keep a normal Agent with narrow function tools when the task does not need a filesystem at all.

That line prevents an expensive architecture mistake: creating a persistent compute environment for work that should have remained a single typed tool call.

Treat the production system as three boundaries

Reliable Sandbox Agents separate control, execution, and recovery. OpenAI's architecture makes the split explicit: the outer runtime owns approvals, tracing, handoffs, and resume bookkeeping, while the sandbox session owns commands, file changes, and environment isolation. Saved sandbox state then carries work across failures or later runs.

BoundaryOwnsMust recordMust not decide
Outer runtimeIdentity, policy, approvals, model loop, tool routingUser, tenant, prompt version, policy result, approval, model usageFilesystem implementation details
Sandbox sessionCommands, files, processes, environment boundaryClient, image digest, manifest hash, operations, artifacts, cleanupBusiness authorization
Saved stateReconnection or fresh-workspace recoveryState kind, storage key, creation policy, retention, restore resultWhether a new action is approved

This separation changes how you debug a failed run. A model error belongs to the outer trace. A command failure belongs to the sandbox operation. A failed restore belongs to the saved-state path. Folding all three into one generic "agent failed" event removes the evidence needed to retry safely.

It also makes replacement possible. SandboxAgent extends the normal Agent surface, while the sandbox run option selects or reconnects the execution environment. Your application can keep the agent contract stable and change the sandbox client without rewriting prompts, handoffs, or output schemas.

Three production boundaries for Sandbox Agents: outer control, sandbox execution, and saved-state recovery
Keep policy, execution, and recovery as separate contracts.

For a document-processing agent, the outer runtime can authorize a tenant's request and issue an input bundle. The sandbox can extract, transform, and validate files. The saved-state layer can preserve the workspace after an interrupted run. None of those layers needs to impersonate another.

Pick the client by the boundary you need

Use Unix-local for development, Docker for local isolation and image parity, and a hosted client for production-style separation. The agent definition can remain stable while the run config changes the client.

Client classExecution locationIsolation claimBest useProduction concern
UnixLocalSandboxClientLocal host workspaceNo separate container boundaryFast macOS or Linux developmentModel-generated commands run on the host
DockerSandboxClientLocal containerBasic container isolationCI, integration tests, image parityHost daemon, mounts, network, cleanup
Hosted sandbox clientProvider-managed environmentWorkspace boundary moved off the app hostProduction jobs and elastic workersProvider identity, egress, retention, cost, regional controls

The TypeScript SDK currently lists seven hosted providers: Blaxel, Cloudflare, Daytona, E2B, Modal, Runloop, and Vercel. That list is integration coverage, not a claim that the providers have identical security models. OpenAI's sandbox client guide tells developers to check each provider's port behavior, PTY support, snapshot behavior, mounts, credentials, and cleanup semantics.

Sandbox client selection ladder from Unix-local development to Docker isolation and hosted production compute
Move the workspace boundary outward as the workflow approaches production.

Choose the provider only after defining the boundary:

  • If code must never execute on the application host, Unix-local is disqualified.
  • If the workload needs a specific image and runs inside controlled CI, Docker may be sufficient.
  • If tenants run concurrently, jobs outlive web requests, or model-generated code is untrusted, use hosted compute with per-run isolation and explicit teardown.
  • If data residency or private networking is mandatory, verify those controls in the provider contract before adapting the SDK.

Framework choice and execution choice are separate decisions. The OpenAI Agents SDK versus Pydantic AI comparison helps set the orchestration boundary; the sandbox client decides where model-directed work executes.

Build the smallest safe workspace contract

Materialize only the inputs the task needs, expose a dedicated output path, and keep broad host access out of the manifest. A Manifest can describe files, directories, repositories, mounts, environment values, users, groups, and narrowly granted host paths. That makes it powerful enough to become an accidental privilege bundle.

The safest first implementation is intentionally plain:

TypeScript
import { run } from '@openai/agents';
import {
  Capabilities,
  Manifest,
  SandboxAgent,
  localDir,
} from '@openai/agents/sandbox';
import { DockerSandboxClient } from '@openai/agents/sandbox/local';
import { resolve } from 'node:path';

const model = process.env.OPENAI_MODEL;
if (!model) throw new Error('OPENAI_MODEL is required');

const manifest = new Manifest({
  entries: {
    repo: localDir({ src: resolve('repo') }),
  },
});

const agent = new SandboxAgent({
  name: 'Patch verifier',
  model,
  instructions:
    'Work only inside `repo/`. Run the targeted test. Return the changed files, verification command, and remaining risk.',
  defaultManifest: manifest,
  capabilities: [...Capabilities.default()],
});

const result = await run(
  agent,
  'Repair the failing test described in `repo/task.md`.',
  {
    sandbox: {
      client: new DockerSandboxClient({
        image: 'node:22-bookworm-slim',
      }),
    },
  },
);

console.log(result.finalOutput);

This baseline stages a dedicated working directory and runs sandbox-native capabilities in Docker. Capabilities.default() includes filesystem(), shell(), and compaction(). If you replace it with an explicit capabilities array, the explicit list replaces the defaults, so include only the capabilities the workflow actually needs.

For production, turn the manifest into a reviewed contract.

  1. Stage task inputs

    Copy or fetch the minimum input bundle into a task-specific workspace. Do not point a local client at the application repository, a developer home directory, or a shared credentials directory.

  2. Separate outputs

    Give the agent a named output directory or artifact contract. Publish artifacts only after schema validation, malware scanning where relevant, and an application-owned approval decision.

  3. Narrow capabilities

    Remove shell access when filesystem tools are enough. Remove filesystem mutation when the task is inspection-only. A smaller tool surface is easier to evaluate and cheaper to trace.

  4. Pin execution

    Pin the container image by digest in the deployment layer, record that digest on every run, and review image changes as code. The example image is a readable starting point, not an immutable production reference.

  5. Prove cleanup

    Verify that the sandbox, temporary storage, provider session, and any issued credentials are closed or revoked on success, failure, timeout, and cancellation.

Manifest paths are workspace-relative and cannot escape with .., but local materialization can still expose more host data than intended through source selection or extra path grants. Treat every path grant and mount as a security-sensitive code change. Use readOnly: true for reference repositories, skills, and datasets that the task should not mutate.

Keep credentials and approvals outside model-generated code

Do not give the sandbox a standing application credential. OpenAI's security rationale for separating the agent runtime and compute is to keep credentials out of the environment where model-generated code runs. Preserve that property in your implementation.

Manifest environment values persist by default. The SDK documents { value: "...", ephemeral: true } for short-lived credentials that should not be saved with sandbox state. Ephemeral storage solves persistence, not exposure: code running inside the sandbox can still read a credential while it exists.

Use this order of preference:

  • Keep credentials in the outer runtime and expose a narrow, policy-checked function tool.
  • If the sandbox must call a service directly, mint a task-scoped token with the smallest audience and lifetime the provider supports.
  • Mount reference data read-only instead of granting the sandbox storage credentials.
  • Block outbound network access by default, then allow only required destinations in the sandbox provider or network layer.
  • Redact command output, traces, artifacts, and exception payloads before they leave the execution boundary.

Filesystem Permissions do not replace this policy. The SDK documentation is explicit that Permissions controls materialized file access, not model permissions, approval policy, or API credentials.

A useful approval packet contains the proposed effect, normalized arguments, target resource, tenant, policy result, relevant diff or artifact, and the exact credential scope that will be used. The human approves the effect, not a vague instruction such as "let the agent continue."

Resume the right state after failure

Choose recovery by artifact type, not by convenience. Conversation state, backend session state, and workspace snapshots solve different problems.

StateWhat it preservesUse it whenMain risk
Conversation stateModel-visible interaction historyThe agent needs conversational continuityReplaying stale assumptions or sensitive context
sessionStateConnection data for the same sandbox backend sessionThe provider session still exists and should be reconnectedSerialized provider credentials or expired sessions
SnapshotFiles and artifacts used to seed a fresh sessionCompute was lost or a clean environment is preferableMissing excluded paths or persisting sensitive files

OpenAI's client guide distinguishes sessionState from snapshots: session state reconnects to the same backend session, while a snapshot creates a fresh session from saved workspace contents. Mounted and ephemeral paths are not copied into durable snapshots.

That distinction matters during recovery. If an agent installed a dependency into an ephemeral mount, restored files may exist while the executable does not. If a short-lived credential was correctly excluded, the resumed run needs a fresh credential from the outer runtime. Recovery logic must rebuild non-durable dependencies rather than assuming a snapshot is a complete machine image.

Run a recovery drill before launch:

  • Interrupt work after the agent has produced an intermediate artifact.
  • Restore the snapshot into fresh compute.
  • Reissue only the current task and approved context.
  • Confirm the artifact, manifest, image, and dependency contract.
  • Mint new short-lived credentials.
  • Verify that already completed external side effects are not repeated.

The last check requires idempotency in the application layer. Snapshotting a filesystem cannot make a payment, ticket update, deployment, or message send safe to repeat.

Make every sandbox run observable and evaluable

Correlate the outer trace with sandbox operations and saved-state events. The JavaScript v0.9.0 release added sandbox operation spans for session startup, command execution, filesystem work, snapshots, memory, and provider operations. Those spans are useful raw evidence, but the application still needs business context and policy outcomes.

Record an event contract like this:

JSON
{
  "run_id": "application run identifier",
  "tenant_id": "authorized tenant",
  "agent_version": "deployed agent contract",
  "prompt_version": "reviewed instruction contract",
  "sandbox_client": "local, docker, or hosted adapter",
  "image_digest": "immutable execution image",
  "manifest_hash": "reviewed workspace contract",
  "operation": "command, file write, snapshot, restore, or cleanup",
  "approval": "not_required, approved, or denied",
  "artifact_ids": ["validated artifact reference"],
  "credential_scope": "redacted scope description",
  "result": "success, failure, cancelled, or timed_out"
}

Keep command output and file contents in a separately governed payload store. The event stream should be searchable without exposing source code, user documents, or secrets to every observability consumer.

Your eval set should attack the boundary, not just grade the final prose:

  • A permitted file is readable and a forbidden path is not.
  • A read-only input cannot be changed.
  • A malicious instruction inside a repository cannot widen credentials or network access.
  • A destructive or external action pauses at the application approval gate.
  • A snapshot restores required artifacts without retaining ephemeral credentials.
  • A retry does not repeat an already completed side effect.
  • Cancellation and failure both trigger cleanup.
  • The run attributes model usage, tool charges, sandbox compute, storage, and egress to the correct tenant and workflow.

OpenAI states that the SDK capabilities use standard API pricing based on tokens and tool use. Hosted compute, storage, and egress belong to the selected sandbox provider, so the production cost equation is:

run cost = model usage + tool charges + sandbox compute + storage + egress

Track each term per run. A cheap model loop can still produce an expensive system if sandboxes remain warm, snapshots accumulate, or materialization repeatedly copies large repositories.

Roll out from local convenience to hosted isolation

Promote the same agent contract through progressively stronger execution boundaries. The language runtime matters less than ownership: the team that owns the worker should own image updates, credentials, cleanup, state retention, and incident response. If that split is unsettled, resolve it with the TypeScript versus Python production ownership rule before adding another execution backend.

  1. Develop locally

    Use UnixLocalSandboxClient only with synthetic or disposable workspaces. Prove the prompt, manifest shape, artifact contract, and capability minimum.

  2. Test in Docker

    Run boundary evals against the production image family. Verify path restrictions, user identity, network rules, cancellation, output validation, and cleanup.

  3. Canary hosted compute

    Switch the client adapter while keeping the agent contract stable. Use synthetic and internal tasks first, inspect every approval and artifact, and compare recovery behavior with Docker.

  4. Enable bounded traffic

    Admit only workflows whose side effects, data classification, credential scopes, and rollback paths are explicit. Keep high-impact actions behind human approval.

  5. Operate the state lifecycle

    Set application policies for session expiry, snapshot retention, artifact deletion, credential revocation, and provider cleanup. Alert when any lifecycle event fails.

Sandbox Agents are beta, so keep a fallback path. The fallback may be a narrower function-tool workflow, a queued human task, or a clean restart from approved inputs. A beta SDK should not become the only route to recover a customer-facing workflow.

Who should use Sandbox Agents, and who should not

Use Sandbox Agents when the workspace is a first-class product object:

  • Coding, document, data, or media jobs that create and validate artifacts.
  • Long-running work that must survive worker or container loss.
  • Multi-agent patterns where each worker needs its own mutable workspace.
  • Tasks that require a selectable local, container, or hosted execution backend.
  • Workflows where a manifest and snapshot can become auditable handover artifacts.

Do not use them when a narrower primitive is enough:

  • A typed API call with no filesystem.
  • An occasional shell command supported by hosted shell.
  • A read-only lookup that belongs in retrieval or a function tool.
  • A workflow whose external side effects cannot be made idempotent or approved.
  • A team that cannot yet operate credentials, traces, retention, cleanup, and incident response for ephemeral compute.

The value is not that an agent can run arbitrary commands. The value is that file-heavy work can run inside an explicit, replaceable, observable execution contract.

Frequently asked questions

When should you use a SandboxAgent instead of hosted shell?

Use a SandboxAgent when the filesystem workspace, execution backend, or resume behavior is part of the workflow. Use hosted shell for an occasional bounded command that does not need a living workspace.

Does UnixLocalSandboxClient isolate model-generated code from the host?

No. It runs in a local host workspace. Use it for controlled development inputs, then move to Docker or a hosted client when you need a stronger environment boundary.

What is the difference between sessionState and a snapshot?

sessionState reconnects through a client to the same backend sandbox session. A snapshot seeds a fresh session with saved workspace contents. Conversation history is separate from both.

Which hosted sandbox providers does the Agents SDK support?

The current TypeScript documentation lists Blaxel, Cloudflare, Daytona, E2B, Modal, Runloop, and Vercel. Verify each provider's identity, networking, mounts, snapshots, ports, cleanup, retention, and pricing before production use.

Are secrets saved in sandbox snapshots?

Manifest environment values persist by default. Mark short-lived credentials ephemeral: true; mounted and ephemeral paths are excluded from durable snapshot contents. Also prevent secrets from being copied into ordinary files, command output, traces, or artifacts.

How are Sandbox Agents priced?

OpenAI says the SDK capabilities use standard API pricing based on tokens and tool use. Add the chosen sandbox provider's compute, storage, and egress costs to get the full per-run cost.

Last Updated

Jul 23, 2026

CategoryAgents

More from Agents

View all Agents articles
Newsletter

One letter, every week. Working systems — not hot takes.

Build logs, agentic engineering decisions, agent failures, evals, and what survives real users. Sent weekly, never more.

Weekly. No spam. Unsubscribe anytime.