Managed agent infrastructure | September 13, 2026

The Agents API manages the loop. Your application still owns the ledger.

OpenAI's Agents API turns the Codex harness into a managed primitive with sessions, environments, events, steering, recovery, and artifacts. That removes real plumbing. It does not remove the need to prove who requested the work, what authority it received, what it changed, what it cost, and why an output was released.

Session contract Event reducer Artifact release gate Evidence checked Sep 13
Operational ledger surrounding a managed AI agent session, environment, events, artifacts, and release gate

A hosted harness changes the build-versus-buy boundary

OpenAI released the Agents API in public beta on September 10, 2026. The API exposes the managed harness behind Codex: developers define an agent, give it an execution environment, create a session, receive a stream of structured events, steer or resume work, and retrieve artifacts. OpenAI describes session orchestration, context compaction, and recovery as managed concerns. The application can use an OpenAI-hosted sandbox, a partner environment, or infrastructure it hosts itself.

This is more consequential than another chat endpoint. A production agent loop has accumulated a pile of undifferentiated infrastructure: turn state, tool scheduling, context management, retries, environment lifecycle, interruption, subagents, artifact transfer, and stream recovery. Converting those concerns into a service can shorten a build substantially. The launch discussion on Hacker News reached hundreds of points and comments during the research window, while OpenAI's Python and JavaScript agent SDKs continued to attract active issue traffic. That activity is a signal of developer interest, not a quality benchmark.

The useful architectural distinction is between execution truth and business truth. The managed session can tell an application which events occurred inside the harness. Only the application knows whether the request was approved, whether a customer record was in scope, whether a spend ceiling was exceeded, whether the produced change passed its release tests, and whether a human accepted an irreversible action. Moving the loop behind an API makes that distinction easier to ignore precisely because the happy path becomes easier.

Use the Agents API as an execution substrate. Keep an application-owned operational ledger as the durable record of intent, authority, evidence, cost, and release.

This guide focuses on that ledger. It does not attempt to reproduce the entire API reference, and it does not treat first-party launch claims as independent performance evidence. The API is a public beta, the harness is versioned and evolving, and OpenAI's SDK documentation marks sandbox-agent interfaces and defaults as subject to change. A production integration therefore needs an explicit compatibility contract and a reversible adoption plan.

Split the system into a managed execution plane and an application control plane

The Agents API documentation centers four concepts: an agent defines model and behavioral configuration; an environment supplies a computer and tools; a session is the durable container for work; and events plus items describe what happened. These are powerful runtime primitives. None is a substitute for the business object's own lifecycle.

Managed execution plane

Agent-loop scheduling, session continuity, event production, context compaction, interruption, steering, recovery, tool orchestration, environment interaction, and artifact exposure.

Application control plane

User and tenant identity, request snapshot, authorization, policy versions, budgets, retention, approval, evaluation, incident ownership, release state, and customer-visible status.

The boundary is not a criticism of the service. It is the normal division of responsibility for a managed primitive. A hosted database manages pages and replication; the application still owns its data model and access policy. A payment processor performs a charge; the merchant still owns order state, fulfillment, refunds, and reconciliation. A managed agent harness executes work; the application still owns why that work was allowed and whether its result can cross a business boundary.

ConcernUse the managed session forPersist in the application ledger
IdentitySession and agent identifiersUser, tenant, service principal, delegated role, originating request
EnvironmentRuntime type, files, tools, network configurationApproved template, policy digest, data classification, evidence of isolation
ProgressStreaming events and itemsReduced task state, durable cursor, retry history, user-facing milestones
AuthorityAvailable tools and environment capabilitiesBusiness scopes, exact approvals, expiry, separation of duties
ArtifactsFiles produced in a sessionExpected manifest, hashes, validation, provenance, retention, release destination
CostProvider usage observations where exposedPer-task totals, internal rates, hard limits, anomaly decisions, chargeback
CompletionHarness state and action eventsAcceptance tests, reviewer, release verdict, compensating action

OpenAI says the Agents API itself has no additional fee beyond the model tokens and tools used. That statement is about provider billing, not total cost of ownership. Environment runtime, external tools, retries, human review, storage, observability, and failed work still have cost. Community reports about token growth in other Codex harness contexts are useful reasons to instrument spend, but they are not proof of this API's billing behavior. Keep those evidence classes separate.

Make environment selection a workload decision

The application chooses where the agent executes. OpenAI-hosted environments reduce setup and integrate directly with session lifecycle. Partner environments may align with an existing sandbox vendor. Self-hosting provides the most direct control over images, locality, monitoring, and network boundaries, but transfers patching, isolation, capacity, and cleanup to the operator. “Hosted” and “self-hosted” are deployment facts, not security verdicts.

EnvironmentGood fitControl questionOperational cost
OpenAI-hostedFast pilots, common development tools, disposable workloadsDo data rules and network policy permit the hosted boundary?Lowest environment engineering; validate defaults and evidence export
Partner-hostedTeams standardized on a supported sandbox providerWhich party owns logs, retention, incident response, and regional placement?Integration plus vendor coordination
Self-hostedCustom runtimes, strict locality, proprietary tooling, deep observabilityCan the team prove isolation, patching, teardown, quotas, and egress control?Highest platform and on-call burden

Network access deserves an explicit line item. OpenAI's hosted-environment guide says network access is enabled by default unless a session inherits a template with another policy. Teams that assume “sandbox” means “offline” can therefore create an avoidable data path. Set access deliberately to disabled or to a restricted allowlist, record the normalized policy in the ledger, and test DNS, redirects, package managers, and alternate protocols. If a task legitimately needs broad internet access, label the input and resulting artifacts as externally influenced.

A minimal environment admission checklist

  • Classify the input data and name the allowed execution regions.
  • Pin an approved environment template or immutable image identifier.
  • Declare network access as disabled, restricted, or open; never inherit it silently.
  • Inventory eager and deferred tools, credentials, writable mounts, and maximum runtime.
  • Define teardown evidence and confirm whether artifacts or caches survive the session.
  • Assign an incident owner for provider, partner, and self-hosted failure modes.

Create the application record before creating the API session

The durable business identifier should exist before any provider request. That lets the application attach idempotency, policy, budget, and data classification even when session creation times out or returns an ambiguous result. It also prevents a provider session ID from becoming the only key that links a user request to its effects.

task_contract:
  task_id: task_01K54R8M8PN9
  tenant_id: tenant_acme
  requested_by: user_1842
  purpose: "Update dependency and prepare reviewed patch"
  input_snapshot_sha256: "7a10..."
  data_class: internal_source
  agent:
    model: gpt-6-astra
    instruction_version: agent-policy-18
  environment:
    type: openai_hosted
    template: dev-sandbox-2026-09-01
    network: restricted
    allowed_domains: [registry.npmjs.org]
  authority:
    tools: [shell, apply_patch]
    forbidden_paths: [secrets/, production/]
    external_effects: deny
  budget:
    max_runtime_seconds: 900
    max_cost_usd: 3.00
  release:
    required_checks: [unit, lint, dependency_audit]
    human_review: required

The adapter then translates this contract into the current API representation. Keep translation isolated so a beta field change does not leak through the product. Validate the provider response against the requested contract, store the session ID and API version, and move task state through an explicit transition such as created → running → validating → awaiting_review → released. A failed or lost create response should enter reconciling, not start a second untracked task.

Version all inputs that can change behavior

Model name alone is not enough. Record the agent instructions, environment template, tool catalog, deferred-tool namespace, MCP configuration, network policy, injected files, policy engine version, client SDK, and application adapter. If the service exposes a harness version, persist it. If it does not, retain the response metadata and deployment time as the best available compatibility evidence. A rollback needs the complete behavioral envelope, not a marketing model label.

Tool Search allows tools to be loaded only when the model needs them, reducing up-front schema volume for large tool catalogs. That can improve token and latency characteristics, but it introduces another decision point. OpenAI advises evaluating task success, token use, and latency and generally avoiding a mixed eager/deferred setup without reason. Log which namespace was searched, which tools were loaded, their schema versions, and whether the client or provider executed them. An allowed namespace is not the same as permission to perform every action it contains.

Store a compact operational ledger, not a duplicate transcript

The ledger is a normalized record of consequential facts. It does not need to copy every token or terminal byte. Large raw streams can live in lower-cost evidence storage under a retention policy, while the ledger holds references and digests. The key is that a reviewer can reconstruct the decision path even if the session UI, SDK, or hosted environment is unavailable.

{
  "task_id": "task_01K54R8M8PN9",
  "provider_session_id": "sess_...",
  "state": "awaiting_review",
  "request": {"snapshot": "sha256:7a10...", "purpose": "dependency patch"},
  "versions": {"agent": "18", "environment": "2026-09-01", "adapter": "4.2.0"},
  "authority": {"policy": "sha256:3f21...", "approvals": []},
  "events": {"cursor": "evt_...", "raw_stream": "s3://evidence/...jsonl"},
  "usage": {"input_tokens": 42130, "output_tokens": 8840, "estimated_usd": 1.92},
  "artifacts": [
    {"path": "patch.diff", "provider_id": "artifact_...", "sha256": "b918..."}
  ],
  "checks": [
    {"name": "unit", "result": "pass", "evidence": "sha256:9d0c..."},
    {"name": "dependency_audit", "result": "pass", "evidence": "sha256:6aa1..."}
  ],
  "release": {"decision": "pending", "reviewer": null},
  "created_at": "2026-09-13T09:14:22Z",
  "updated_at": "2026-09-13T09:22:51Z"
}

Separate provider observations from application conclusions. “The session emitted an action-completed item” is an observation. “The customer task is complete” is a conclusion that requires expected outputs and acceptance checks. “The artifact path is patch.diff” is an observation. “This patch is safe to merge” is a conclusion based on hash verification, diff review, tests, protected-path policy, and a reviewer.

Ledger invariants worth enforcing in the database

  • One business task may have multiple provider sessions, but only one active release decision.
  • Every session creation links to a pre-existing task contract and immutable input digest.
  • Every consequential tool action links to the policy version and approval that authorized it.
  • Every retrieved artifact stores provider identity, path, size, content hash, and validation status.
  • Every state transition is monotonic or records an explicit recovery reason.
  • No released artifact can be replaced in place; a changed hash creates a new candidate release.

Reduce the event stream into an idempotent state machine

Streaming is a delivery mechanism, not a database transaction. Connections drop, consumers restart, webhooks can arrive late, and the application may see duplicate events. Store the last durable cursor, deduplicate by event or item identity, and make each reducer transition safe to repeat. Reconcile from the provider after an ambiguous disconnect instead of assuming failure or success.

function reduceAgentEvent(task, event) {
  if (task.seenEventIds.has(event.id)) return task;
  assert(event.session_id === task.providerSessionId);

  appendRawEvidence(event);
  task.seenEventIds.add(event.id);
  task.lastCursor = event.cursor;

  if (event.type === "item.created") indexItem(task, event.item);
  if (event.type === "usage.updated") enforceBudget(task, event.usage);
  if (event.type === "artifact.created") queueArtifactValidation(task, event.artifact);
  if (event.type === "session.failed") transition(task, "needs_investigation");
  if (event.type === "session.completed") transition(task, "validating");

  persistAtomically(task);
  return task;
}

Steering and resuming are first-class lifecycle events. Record the actor, reason, old instruction digest, new instruction digest, event cursor, and whether the change expanded authority. A steering message that changes style is different from one that adds a target repository or asks for deployment. Route authority expansion through the same approval system used for the initial contract.

Multi-agent work needs another caution. OpenAI documents that subagents can inherit MCP credentials, allowed tools, and web settings from the parent context. It also notes that an action item indicating a create or wait operation completed does not necessarily mean the delegated task itself is finished, and that the parent event stream does not expose a full child conversation transcript. Persist parent-child identifiers, delegated scope, inherited authority, expected deliverable, and an explicit join result. Never translate “subagent created” into “work completed.”

Treat artifacts as untrusted candidates until release

The artifact API makes files from a session retrievable using session and artifact identity. That solves transport. It does not certify content. An artifact can be incomplete, malicious, generated from stale input, mislabeled, or valid for a different task. Retrieve into quarantine, verify metadata and size, compute a local content hash, scan the type, and run the acceptance suite in a separate release environment.

Candidate zone

Provider artifacts, raw diffs, generated documents, logs, and test proposals remain tied to the session and cannot reach production destinations.

Release zone

Only hash-pinned artifacts that pass deterministic checks, policy review, and any required human gate receive a new release identity.

For code, compare the changed paths against the contract, reject hidden binaries and unexpected symlinks, rebuild from source when practical, run tests outside the agent environment, and preserve the reviewed diff hash. For documents, scan active content, verify cited evidence, mark inference, and render for visual review. For data, validate schema, row counts, freshness, lineage, and allowed destinations. The release record should state what passed, what was waived, who approved it, and which exact hash moved.

Release decision table

ConditionDecisionRequired next action
Expected artifact missingRejectResume with bounded instruction or close as failed
Hash changes after reviewInvalidate approvalRun checks and review the new candidate
Deterministic check failsQuarantinePreserve evidence; do not ask the model to waive it
Budget exceeded before completionPauseRequire an explicit budget amendment
All checks pass; external effect remainsAwait approvalPresent the exact effect and compensating action
All checks and required approvals passReleaseRecord destination, release ID, reviewer, and timestamp

This is the same principle as an agent execution receipt, applied to a managed harness: completion evidence must bind input, authority, execution, result, and reviewer. The provider session contributes important execution evidence. The application assembles the business receipt.

Design for failures that look like successful execution

Failure modeWhy it slips throughControl and metric
Duplicate task after timeoutCreate succeeded but response was lostApplication idempotency key; count reconciled ambiguous creates
Session done, outcome incompleteHarness completion is treated as business completionExpected-artifact manifest; incomplete completion rate
Network wider than assumedHosted sandbox inherits enabled accessExplicit network policy; denied-egress and unexpected-host metrics
Tool authority expands silentlyDeferred discovery loads a capability outside reviewed scopeNamespace plus action policy; newly loaded tools per task
Child task orphanedParent sees subagent action, not full child lifecycleParent-child join record; active children after parent terminal state
Artifact substitutedPath is stable while content changesContent-addressed candidates; approvals invalidated on hash change
Spend drifts through retriesEach attempt looks locally reasonableCumulative task budget; retry cost and p95 cost-to-success
Beta change alters behaviorSDK or harness default changes without product releaseContract tests pinned to adapter and environment versions

Choose service-level indicators that reflect useful work rather than API availability alone: accepted tasks per 100 starts, median and p95 cost per accepted task, artifact validation failure rate, tasks requiring reconciliation, approval invalidations, orphaned environments, unreconciled external effects, and time from session completion to release. A fast agent that produces rejected artifacts is not an efficient system.

A 30-day adoption plan that preserves an exit

Days 1–7: contract one reversible workload

Pick a bounded internal task with deterministic acceptance, such as preparing a dependency patch in a disposable repository. Define the task contract, ledger schema, environment policy, budget, expected artifacts, and release state machine before connecting the API. Deny external effects. Run the same fixtures against the current harness to establish success, cost, and latency baselines.

Days 8–14: prove recovery and evidence

Inject stream disconnects, worker restarts, duplicated events, session timeouts, missing artifacts, and changed artifact hashes. Confirm that every ambiguity enters reconciliation, every reducer is idempotent, and no candidate bypasses validation. Export enough evidence that an operator can explain a failed task without opening the provider UI.

Days 15–21: exercise tools, steering, and budgets

Add a small deferred-tool namespace and a restricted network allowlist. Measure whether discovery improves total tokens or latency without reducing task success. Steer a running task and confirm that expanded authority triggers a new approval. Force budget exhaustion and prove that the agent pauses before additional spend or external action.

Days 22–30: shadow production and decide

Run the managed path beside the existing workflow on sampled tasks without releasing its output automatically. Compare accepted-task rate, human review time, cost, operational incidents, and evidence completeness. Adopt only if the managed path improves the whole system. Preserve an adapter boundary, exportable ledger, task fixtures, and environment-independent release tests so the team can migrate if beta behavior, pricing, or requirements change.

  • Application task exists before provider session creation.
  • Environment and network policy are explicit and versioned.
  • Event consumption is replay-safe and has a reconciliation path.
  • Tool discovery is observed and action authority remains separate.
  • Subagent scope, inheritance, and join state are recorded.
  • Spend is capped across the entire business task, including retries.
  • Artifacts are content-addressed, quarantined, validated, and released separately.
  • The old workflow remains usable until shadow metrics justify migration.

Frequently asked questions

Does the Agents API replace the Agents SDK?

They sit at different layers. The API provides a managed execution harness and session service; the SDKs provide libraries and patterns for building agent applications. Choose the interface that fits the workload, but keep the application control-plane records independent enough to compare or migrate implementations.

Should every event be stored forever?

No. Store consequential normalized facts in the ledger and retain raw streams according to data class, debugging need, regulation, and cost. Preserve hashes and references when raw evidence expires so the release record still shows exactly what evidence existed and which policy removed it.

Can the event stream be the user-facing progress model?

Use it as input, not as the presentation contract. Reduce detailed harness events into stable business milestones such as queued, executing, validating, awaiting approval, released, or needs attention. That protects users from provider-specific churn and avoids presenting a completed tool action as a completed outcome.

What should be tested after an API or SDK upgrade?

Replay fixed tasks that cover environment creation, network denial, eager and deferred tools, interruption, steering, reconnection, subagents, budget limits, artifact retrieval, hash validation, and release rejection. Compare output quality, accepted-task rate, token use, latency, event ordering, and cleanup evidence with the pinned baseline.

Primary documentation and current discussion

Product behavior and defaults were checked on September 13, 2026. First-party documentation establishes intended behavior; community threads are used only as discussion and operational signals.