Contents

OpenAI Agents API and Pluggable Sandboxes

Shipping a production coding or operations agent usually forces teams to rebuild the same runtime plumbing from scratch: durable session persistence, long-horizon context compaction, crash recovery, command sandboxing, egress restrictions, and artifact collection. OpenAI’s Agents API (public beta since September 10, 2026 under OpenAI-Beta: agents=v1) exposes OpenAI’s managed Codex harness directly as a cloud runtime. On November 18–19, 2026, OpenAI followed up with Inside the Codex Sandbox and Performance Factory, detailing cross-platform kernel isolation and automated performance regression triage at scale.

Codex Best Practices covers day-to-day workflows across the CLI, IDE, and desktop app; on the backend side, the hard questions are modeling durable sessions, evaluating hosted versus self-hosted execution and data-residency boundaries, understanding OS-native sandboxing, and applying the Performance Factory verification loop.

Core Runtime Model: Sessions, Turns, and the Managed Harness

Stateless inference endpoints leave the entire execution loop in application code—every tool dispatch, retry, history truncation, and checkpoint becomes your responsibility. The Agents API moves that loop into a platform-managed Session primitive:

flowchart LR App["Backend Service / CI Trigger"] -->|"POST /v1/agents/sessions (agents=v1)"| Harness["OpenAI-Managed Codex Harness"] Harness -->|"Auto Compaction & Cloud State"| Session["Durable Session"] Harness -->|"Dispatch Commands"| Env["Pluggable Execution Environment"] Env -->|"Return Results"| Harness Env --> Hosted["OpenAI-Hosted Linux Container"] Env --> SelfHosted["Self-Hosted codex exec-server (Outbound WebSocket)"] Env --> Partner["Partner Sandboxes (E2B / Modal / Daytona)"] Harness -->|"SSE Stream / Webhooks"| App

Your service supplies the goal, permission boundaries, and event consumer; the harness manages the loop and recovery; side effects remain inside the execution environment. Note the return path in the diagram: even with a self-hosted executor, command outputs and tool results travel back to OpenAI’s cloud session for reasoning and state persistence.

Four runtime behaviors shape production reliability:

  • Durable sessions vs. workspace file lifetime: Sessions persist agent configuration and conversation state across turns via session_id. However, live workspace files inside OpenAI-hosted sandboxes only survive while the sandbox container exists—any output you need to keep must be published explicitly as an artifact.
  • Turns and live steering: Sending input to an idle session starts a new turn; sending input during an active turn steers execution in flight when an operator or alert needs to redirect work.
  • Background context compaction: Long tool outputs quickly exhaust context windows and dilute attention (see AI Context Management Guide). The harness compacts verbose earlier steps automatically while preserving key decisions and change summaries.
  • Disconnecting does not cancel work: Interactive clients read progress over SSE while batch jobs subscribe via webhooks. Closing an SSE stream stops local delivery but does not cancel the running server-side turn—cancellation requires an explicit cancel request, and reconnecting lets you resume from the persisted session.

Execution Environments and Data Residency Boundaries

The environment object is a required field in the Create Session API Reference. Picking the right mode avoids both avoidable container overhead and false compliance assumptions.

Environment Mode Request Configuration Key Strengths Best Fit & Real Boundaries
No environment environment: { type: "none" } Explicitly opts out of a workspace; zero container overhead Pure text tasks, structured extraction, or external HTTP / MCP tools only
OpenAI-hosted sandbox environment: { type: "openai_hosted" } Managed Linux containers (Node.js / Python pre-installed) with configurable sizing, file uploads, env vars, and setup scripts General code generation, data processing, automated test fixes; no direct private VPC reachability
Pre-warmed sandbox Provision and run setup first, then attach via environment_id Eliminates dependency install and checkout cold starts High-frequency interactive tasks or large repositories with heavy build caches
Self-hosted / partner sandbox Run codex exec-server in your VPC, or integrate E2B / Modal / Daytona Keeps command execution, internal registries, and custom toolchains inside your network Internal staging targets, private package registries, custom build images

Be precise about compliance boundaries—self-hosted execution is not a “data never leaves your network” guarantee:

  1. Data residency and retention: Per the Agents API Overview, the public beta currently supports US data residency only and does not support Zero Data Retention (ZDR)—including when running self-hosted executors, since codex exec-server opens an outbound WebSocket to OpenAI to exchange commands and results.
  2. Separate network egress from data authorization: Subnet firewalls control which internal hosts and ports the executor can reach, not whether a database query is read-only. Enforce read/write authorization at the database role, scoped tool, or short-lived credential layer.

Inside the Codex Sandbox: OS-Native Kernel Isolation

Containers are not always practical on developer machines or native build hosts where Docker breaks host toolchains such as macOS/iOS simulators. In Inside the Codex Sandbox (November 18, 2026), OpenAI detailed its OS-level sandboxing layer across all three major desktop platforms:

  • macOS: Enforces filesystem write restrictions and network boundaries via Apple’s Seatbelt framework.
  • Linux: Uses Bubblewrap to construct an isolated filesystem view paired with seccomp-bpf filters to narrow allowed syscalls, without requiring privileged root containers.
  • Windows: Combines restricted user tokens, Security Identifiers (SIDs), explicit ACLs, and dedicated local accounts (CodexSandboxOffline and CodexSandboxOnline), while migrating compatible devices to the MXC backend.

Above these primitives, teams select from three permission profiles (see Codex Config Reference):

  1. Read-Only: Permits repository inspection and read-only diagnostics while blocking workspace writes—well suited for triage and audits.
  2. Workspace-Write: Permits writes to the current working directory, temporary directories, and explicitly configured extra writable roots. Crucially, blocking writes does not block reads—read access is governed separately, so host secrets still require read isolation or dedicated runtime separation.
  3. Danger-Full-Access: Disables sandbox write guards; appropriate only inside disposable CI runners or outer VMs, never as a workstation default.

This reinforces the core principle of Harness Engineering: safety boundaries must be enforced by the OS or container, never by system-prompt reminders.

TypeScript Session Creation and Follow-Up Example

During public beta, REST requests target POST https://api.openai.com/v1/agents/sessions (note there is no /beta path segment—beta exists only as a client SDK namespace) with header OpenAI-Beta: agents=v1. The example below creates a session with an OpenAI-hosted sandbox, reads session_id, and dispatches a follow-up turn (for streaming consumption and SDK result helpers, see the Agents API Quickstart):

type EnvironmentConfig =
  | { type: "none" }
  | { type: "openai_hosted" }
  | { type: "environment_id"; environment_id: string };

interface CreateSessionPayload {
  agent: {
    model: string;
    instructions: string;
  };
  environment: EnvironmentConfig;
  input: string;
  stream: boolean;
}

const SESSIONS_URL = "https://api.openai.com/v1/agents/sessions";

function buildHeaders(): Record<string, string> {
  const apiKey = process.env.OPENAI_API_KEY;
  if (!apiKey) {
    throw new Error("Missing OPENAI_API_KEY");
  }
  return {
    Authorization: `Bearer ${apiKey}`,
    "Content-Type": "application/json",
    "OpenAI-Beta": "agents=v1",
  };
}

export async function createAndContinueSession(
  initialPrompt: string,
  followUpPrompt: string,
): Promise<{ sessionId: string; followUpStatus: number }> {
  const payload: CreateSessionPayload = {
    agent: {
      model: "gpt-6-astra",
      instructions:
        "Inspect the workspace, run verification commands, and report actual command output.",
    },
    environment: { type: "openai_hosted" },
    input: initialPrompt,
    stream: false,
  };

  const createRes = await fetch(SESSIONS_URL, {
    method: "POST",
    headers: buildHeaders(),
    body: JSON.stringify(payload),
  });
  if (!createRes.ok) {
    throw new Error(`Create session failed: ${createRes.status} ${await createRes.text()}`);
  }

  const created = (await createRes.json()) as { id?: string };
  if (!created.id) {
    throw new Error("Agents API response missing session id");
  }

  // Send a follow-up turn on the same durable session (use the official SDK's result collection for streaming)
  const followUpRes = await fetch(`${SESSIONS_URL}/${created.id}/turns`, {
    method: "POST",
    headers: buildHeaders(),
    body: JSON.stringify({ input: followUpPrompt, stream: false }),
  });

  return { sessionId: created.id, followUpStatus: followUpRes.status };
}

In production, wrap this behind three guardrails: enforce wall-clock timeouts and token ceilings at your gateway; store session_id alongside your internal job ID so callers distinguish stream reconnection from explicit turn cancellation; and keep beta schemas behind a thin adapter.

Lessons from Performance Factory: Closed-Loop Verification

On November 19, 2026, OpenAI published How OpenAI’s Performance Factory keeps ChatGPT fast. Over three-plus months, the system tracked more than 1,700 automated investigations and identified root causes in more than 600 cases. In a companion VentureBeat interview with OpenAI’s performance team, they added that roughly 400 cases reached fix proposals, about 50 shipped fixes were influenced by those proposals, and roughly 15 PRs were merged verbatim.

Beyond standard multi-agent role separation (covered in Multi-Agent Systems Guide), the highest-leverage design choice is challenging the diagnosis before writing code and verifying regressions after deployment:

flowchart LR Alert["Latency Alert / Regression"] --> Triage["Investigation (Recommended: Read-Only)"] Triage --> Challenge["Diagnosis Challenge / Falsification"] Challenge -->|"Weak Evidence"| Triage Challenge -->|"Root Cause Confirmed"| Fixer["Fix Proposal (Recommended: Workspace-Write)"] Fixer --> Critic["Adversarial Patch Review"] Critic -->|"Regression / Weak Proof"| Fixer Critic -->|"Approved"| SRE["Human SRE Final Merge"] SRE --> PostCheck["Post-Deploy Metric Verification"]

Validating root causes before remediation prevents agents from shipping plausible-looking patches for the wrong bottleneck, while post-deploy verification closes the feedback loop without removing human SRE approval.

Boundaries and Pitfalls to Avoid

  • Skip stateful sessions for stateless tasks: Single-shot classification or extraction runs faster and cheaper on stateless endpoints; when using Agents API without a workspace, pass environment: { type: "none" } explicitly.
  • Do not treat sandbox files as durable storage: Publish anything that must outlive the container as an artifact or sync it back to your own storage.
  • Keep long-lived credentials out of sandbox env vars: Expose databases and external APIs via scoped tools or short-lived credentials rather than injecting broad static keys into containers.

References