Home › Blog › OpenAI Agents API
Harness Engineering · Product Case Study #1 · Snapshot: September 2026 🧩

OpenAI Agents API: the Codex Harness as a Managed Production Runtime

On 10 September 2026 OpenAI put the harness behind Codex into a public-beta API. Instead of a model endpoint, applications get a managed agent runtime — durable sessions, orchestration, context compaction, tool search, subagents and recovery — and choose where code runs: nowhere, an OpenAI sandbox, a partner sandbox or their own machines. This visual deep dive takes the product apart from its public documentation: the system boundary, the four runtime objects, the managed loop, compaction, tools and MCP, execution environments, and a full incident-investigation run.

How to read this: this is the first product case study in the harness case-study lens. Facts come from OpenAI's Agents API documentation and launch coverage, checked in September 2026 and linked in References. The API is in public beta and will change. Code-like snippets are illustrative shapes, not the exact API schema; internal implementation details are not public.

01 What This Product Is

The Agents API gives applications access to an OpenAI-managed Codex harness as a service — the same harness that runs Codex and ChatGPT for Work. The key idea: not just a model endpoint, but a managed agent runtime with orchestration, durable sessions, tools and execution capabilities.

10 Sep 2026public beta, open to all API developers
$0platform fee — pay for model tokens and tools used
gpt-6-astradefault model (cheaper tiers such as gpt-5.6-luna available)
4building blocks: agents, environments, sessions, events/items
✓Recommended by OpenAI for new managed-runtime agent applications.
✓The application connects tools and chooses the execution environment.
✓Alternatives: the Agents SDK (self-hosted runtime) or the Responses API (direct model calls) — see section 12.

02 The System Boundary: OpenAI vs Developer

The product is best understood as a line through the agent stack. Click any responsibility to see which side of the line it sits on, and why:

▶ Who owns what Managed by OpenAI (left) vs built and operated by the developer (right).
Click a responsibility.

03 High-Level Architecture

A user talks to the developer's application; the application sends API requests (streaming or asynchronous) to the Codex harness; the harness calls the model and orchestrates tools across three kinds of endpoint. Press play to follow one request:

▶ One request through the system Developer-operated (left), OpenAI-managed (centre), tools and environments (bottom).

04 Core Runtime Objects

Four objects make up the API. Click each to see its role and an illustrative shape:

▶ Agents, environments, sessions, events Illustrative shapes — consult the API reference for exact fields.

05 The Managed Agent Loop

Inside a session, the harness repeats one loop until the task is done — and every step of it is now OpenAI's code, not yours:

▶ The loop, step by step Press play; the loop repeats for each step of the task.

06 Durable Sessions and Context Compaction

A session is a durable agent instance: it keeps configuration, conversation and saved work, so an application can send follow-ups, steer the agent mid-task, or resume days later. As a session nears its context limit, OpenAI automatically compacts earlier context so work spans multiple context windows — preserving key decisions and constraints, references to important artifacts and files, and unresolved tasks, while removing or compressing less relevant detail.

▶ Context size across a long session Computed from the session model below. Move the compaction threshold.

The same model as a runnable script, priced at GPT-6 Astra's list rates:

"""What automatic context compaction does to a long agent session's size and cost.

Each model call in an agent session re-reads the whole context (instructions + history), then adds
new tool results and output to it. Without compaction the context keeps growing until it hits the
window; with compaction, when the context nears a threshold the harness replaces older history with
a compact summary of decisions, artifacts and open tasks, and the session continues.

Price: GPT-6 Astra list price, $10 per 1M input tokens and $50 per 1M output tokens (September 2026),
without prompt-caching discounts. Session shape is an assumption. Standard library only.
"""
WINDOW = 1_050_000                 # GPT-6 Astra context window (reported ~1.05M tokens)
IN_PRICE, OUT_PRICE = 10 / 1e6, 50 / 1e6
BASE, GROWTH, OUT = 12_000, 6_000, 800   # instructions+tools, new tokens per step, output per step

def run(steps, threshold=None, summary=40_000):
    ctx, in_tok, out_tok, peak, compactions = BASE, 0, 0, 0, 0
    for _ in range(steps):
        if ctx + OUT > WINDOW:
            return None                                   # the session cannot continue
        in_tok += ctx; out_tok += OUT; peak = max(peak, ctx)
        ctx += GROWTH + OUT
        if threshold and ctx > threshold:
            ctx = BASE + summary; compactions += 1        # older history -> compact summary
    return in_tok, out_tok, peak, compactions

print("Long agent session: each step re-reads the context, adds ~6,800 tokens\n")
print(f"   {'steps':>6}  {'strategy':<24}{'peak context':>14}{'input tokens':>15}{'cost':>10}{'compactions':>13}")
for steps in (50, 150, 400):
    for name, thr in (("no compaction", None), ("compact at 200K", 200_000), ("compact at 100K", 100_000)):
        r = run(steps, thr)
        if r is None:
            print(f"   {steps:>6}  {name:<24}{'exceeds window - run fails':>52}")
            continue
        i, o, peak, c = r
        print(f"   {steps:>6}  {name:<24}{peak:>14,}{i / 1e6:>13.1f}M{'$' + format(i * IN_PRICE + o * OUT_PRICE, ',.0f'):>10}{c:>13}")
    print()
print("Input tokens dominate: every step pays again for everything still in context.")

Output:

Long agent session: each step re-reads the context, adds ~6,800 tokens

    steps  strategy                  peak context   input tokens      cost  compactions
       50  no compaction                  345,200          8.9M       $91            0
       50  compact at 200K                195,600          5.6M       $58            2
       50  compact at 100K                 99,600          3.4M       $36            5

      150  no compaction                1,025,200         77.8M      $784            0
      150  compact at 200K                195,600         17.6M      $182            6
      150  compact at 100K                 99,600         11.0M      $116           18

      400  no compaction                                     exceeds window - run fails
      400  compact at 200K                195,600         48.7M      $503           17
      400  compact at 100K                 99,600         30.0M      $316           49

Input tokens dominate: every step pays again for everything still in context.

Because every step re-reads everything still in context, input tokens dominate a long session's cost, and compaction cuts them by several times — and keeps a 400-step session running at all. The trade-off is fidelity: whatever the summary drops is gone, which is why compaction keeps decisions, artifacts and open tasks explicitly. Prompt caching (not modelled) reduces the uncompacted cost further.

07 Tools and MCP Architecture

The harness can use the developer's function tools and remote MCP servers, with support for tool search and programmatic tool calling. The two paths run differently — pick one:

▶ Three tool paths Where each call goes, and who runs it.
🔎 Tool searchDefer loading tool definitions; the agent finds the tools it needs, keeping context small.
🧮 Programmatic tool callingThe model writes code that calls tools in parallel, chains and filters results, so only the final output returns to its context.
📥 Results flow back into contextTool results become items in the session, available to later steps.
👁️ Tool visibility & approvalsControlled by the application and its policies.

08 Execution Environment Choices

Environments are optional. An agent that only reasons and calls tools needs none; one that runs commands and edits files needs a workspace. Answer three questions:

▶ Choose an environment A simplified decision guide.
OptionDescriptionBest forKey characteristics
NoneNo code execution environmentQ&A, remote tools, data retrievalHarness runs with model + tools only
OpenAI-hosted sandboxIsolated, managed Linux workspace run by OpenAICode execution, file operations, package install, analysisFile system, shell, packages, mounted data, controlled ports, snapshots; billed at container rates
Partner sandboxIntegrated providers such as Cloudflare, Daytona, DigitalOcean, E2B, Modal, Vercel and othersTeams already standardized on a sandbox vendorProvider-managed isolation and billing
Self-hosted environmentAn executor in your infrastructure runs commands at the harness's requestSensitive data, custom infrastructure, on-premises resourcesYour laptop, a Docker container or a serverless function; outbound-only connection; you manage security, network and access

09 The Sandbox and the Self-Hosted Executor

The control plane / execution plane split is the architecture's core. With a self-hosted environment, OpenAI still runs the harness; you run an executor (codex exec-server) that registers with an environment ID and a restricted API key, then opens an outbound WebSocket to receive commands and return results. No inbound ports are opened, and the executor reconnects if the connection drops.

▶ Outbound-only execution Press play: the harness sends a command; your executor runs it behind your firewall.
A subtle boundary: MCP servers configured in the executor are reached from your environment; remote MCP servers are reached from OpenAI's service. An egress rule on your executor governs only the first path — the second needs its own controls (allow-listed servers, scoped credentials).
Isolated sandbox environment
  • File system (read/write)
  • Shell (command execution)
  • Packages (install as needed)
  • Mounted data
Controls
  • Network access (controlled/limited)
  • Ports (controlled)
  • Snapshots (save/restore)
  • Artifacts (files, logs, results)
Security characteristics
  • Isolated Unix-like environment
  • Narrow, controlled credentials
  • Controlled external access
  • Snapshot and resume

10 Subagents and Long-Running Work

The harness can decompose complex tasks into subagents and run them asynchronously, while the application streams progress, steers mid-run and resumes later in the same session:

▶ Planner and subagents Press play; then try steering the run.

11 Reliability, Observability and Recovery

The application watches a session through streamed events (tokens, tool calls, status, logs) or webhooks for state changes without holding a stream open — and can steer, pause or cancel. The harness handles retries and recovery. Watch an event stream with a failure in it:

▶ A session's event stream Illustrative event names.
Observability (from the harness)
  • Streaming events and webhooks
  • Run tracing and event history
  • Tool calls and results
  • Subagent progress, state and metadata
Failure recovery
  • Automatic retries (where possible)
  • Resume from the last state
  • Recover from transient failures
  • Session integrity; clean-up of resources
Steering and control
  • Add input during a run
  • Change direction
  • Approve or block actions (via app policies)
  • Cancel, pause, continue later

12 Where It Fits vs Other OpenAI Agent Options

FeatureAgents API (managed harness)Agents SDK (self-hosted)Responses API (model calls)
What it providesOpenAI-managed Codex harnessA harness library in your infrastructureDirect model calls with built-in tools
Agent loopManaged by OpenAISDK runner in your processYou write it
Durable sessionsYesYou build/manage (sessions, snapshots)You build/manage
Context compactionAutomaticYou manageYou manage (compaction endpoint available)
Tools & MCPSupported, incl. tool searchSupportedSupported (you manage the loop)
Execution environmentNone, OpenAI, partner or self-hostedYour infrastructure or sandbox providersN/A (you manage)
Best forNew managed-runtime agent applicationsFull control, custom deploymentDirect model usage and custom agent loops
▶ Which should you use? Pick the statement that sounds most like you.

13 End-to-End Example: "Investigate a production incident and prepare a mitigation report"

▶ The whole run Press play to step through it; the event log fills as it goes. Illustrative.
Architectural takeaway: the key separation is control plane vs execution plane. The managed harness coordinates reasoning, state, tools and recovery; the chosen environment performs file, code and computer work.
The product in one paragraph
The Agents API turns the harness from something every team builds into something it rents. OpenAI runs the Codex harness — the agent loop, durable sessions, automatic compaction, tool search and programmatic tool calling, subagents, tracing and recovery — while the developer keeps the application, the business logic, the function tools, the data sources, the policies and the choice of where code runs, down to an outbound-only executor inside their own network. It charges no platform fee beyond tokens and sandbox time. The trade is familiar from every managed service: much less to build and operate, in exchange for depending on OpenAI's runtime, its limits and a beta that will keep changing.

Next: Product case study #2 — Claude Agent SDK and Managed Agents: the Claude Code harness in production.

⚠️ Notes

The source infographic matches OpenAI's public documentation closely; additions and refinements: (1) execution environments — besides none, OpenAI-hosted and self-hosted, the API supports integrated partner sandboxes (Cloudflare, Daytona, DigitalOcean, E2B, Modal, Vercel and others), which the infographic omits; (2) the self-hosted path specifically runs OpenAI's codex exec-server executor over an outbound WebSocket, registered with an environment ID and a restricted API key; (3) MCP egress — remote MCP calls leave from OpenAI's service, not from your executor, so executor egress rules don't cover them; (4) pricing and models — there is no separate API fee (tokens and tools, hosted sandboxes at container rates) and the default model is gpt-6-astra; the infographic states neither. The compaction chart and script use a stated session model; event names, object shapes and the incident run are illustrative.

🔗 References