Last week (2026-08-19) OpenAI announced "Codex as a platform," making the Codex Harness an officially embeddable agent foundation for third-party products (background in OpenAI Hands Over the Agent's Engine). Three entry points are on the table: codex exec, the Codex SDK, and codex app-server.
This SOP answers one concrete question: how an ordinary team puts this foundation to work at a "three-stage rocket" cadence - from one working command, to calling it from code, to a production-grade runtime. Every stage ships a minimal runnable example and an upgrade criterion, all based on the openai/codex repository's official docs (GitHub API snapshot 2026-08-22).
Two boundaries up front. First: the Harness being open source (Apache-2.0) does not make the models free - tokens still bill normally. Second: this is an integration path write-up, not legal or security-compliance advice; run it through your own security review before production.
Stage 0: Authentication and Environment
All three stages share one auth layer. The official recommended path from the Python SDK:
from openai_codex import Codex
with Codex() as codex:
login = codex.login_chatgpt() # ChatGPT browser login
print(login.auth_url, login.wait().success)
# or API key: codex.login_api_key("sk-...")Key points: an existing Codex login is reused automatically; the Python SDK (pip install openai-codex, Python 3.10+) bundles the matching CLI automatically; the TS SDK (npm install @openai/codex-sdk, Node 18+) instead spawns the CLI and exchanges JSONL events over stdin/stdout. Keys go through environment variables or the login flow - never into the prompt.
Stage 1: codex exec - a One-Command Integration
For: CI pipelines, cron jobs, one-off background tasks. Zero code refactoring.
codex exec --json "Analyze this repo and produce a risk list"Upgrade criterion: move to Stage 2 when you need to pass state between tasks (feed one task's conclusions into the next) or need structured output for downstream programs.
Stage 2: The Codex SDK - Calling the Agent Like a Function
For: orchestrating the agent from your own TS / Python services. Two core capabilities:
Multi-turn threads + breakpoint resume (threads persist in ~/.codex/sessions; a restarted process picks up where it left off):
import { Codex } from "@openai/codex-sdk";
const codex = new Codex();
const thread = codex.startThread({ workingDirectory: "/path/to/project" });
const turn = await thread.run("Diagnose the test failure and propose a fix");
console.log(turn.finalResponse);
// after a restart: codex.resumeThread(savedThreadId) carries onJSON Schema structured output (the agent's answer is forced to conform to your schema - downstream systems never parse prose again):
const schema = {
type: "object",
properties: {
summary: { type: "string" },
status: { type: "string", enum: ["ok", "action_required"] },
},
required: ["summary", "status"],
} as const;
const turn = await thread.run("Summarize repository status", { outputSchema: schema });When you need real-time progress (tool calls, file changes), use runStreamed() for the event stream instead of the buffered run().
The official switches for safety and sandboxing (these parameters are your first set of reins):
const codex = new Codex({
config: {
sandbox_workspace_write: { network_access: false }, // no network egress inside the sandbox
default_permissions: "audit",
},
configOverrides: [
// filesystem granularity: root read-only, .env explicitly denied
'permissions.audit.filesystem={":root"="read","/path/to/project/.env"="deny"}',
],
});Upgrade criterion: move to Stage 3 when you need a custom UI, your own approval flow, or event streams forwarded raw to the frontend.
Stage 3: codex app-server - a Production-Grade Agent Runtime
For: the agent itself is part of your product. codex app-server is the same interface that powers the Codex VS Code extension: a JSON-RPC 2.0 protocol service supporting stdio (default, JSONL), WebSocket (experimental), and Unix socket transports.
Grab the schema first (generated per version so interfaces stay aligned):
codex app-server generate-ts # TypeScript types
codex app-server generate-json-schema # JSON Schema bundleThree engineering points (all from the official README):
- Approvals are a first-class protocol citizen. The App Server API includes Approvals semantics - high-risk actions suspend and wait for your confirmation. Build this into your product as a human-in-the-loop screen; do not take the shortcut of auto-approving everything.
- Treat overload as retryable. Under saturation the server returns JSON-RPC error
-32001("Server overloaded; retry later"), and the official guidance is exponential backoff with jitter on the client. - Health probes come for free. In
--listen ws://mode,GET /readyz(listener ready) andGET /healthz(200 when no Origin header) plug straight into your liveness checks.
The 10-Item Pre-Launch Checklist
- Credentials via environment variables / KMS - not in code, not in prompts
- Sandbox mode declared explicitly (workspace-write, network egress off unless required)
- Filesystem-granularity permissions:
.envand secret directories explicitly denied - High-risk actions (deletes, external sends, payments) gated by approval - no default allow
- Full behavioral logs: thread id, per-turn usage, tool-call sequence
- Dual caps on tokens and action counts + automatic circuit-breaking on anomalies
- Long tasks resume via
resumeThread()- never blindly re-run (you pay twice) - Structured output via
outputSchema- never regex-parse prose - Retry logic wired for the
-32001app-server overload error - Canary first: read-only tasks for two weeks before enabling writes
Five Classic Pitfalls
- Pasting the key into the prompt to "save time" - logging systems store prompts wholesale, which means the key lands in your logs.
- Trusting default sandbox settings - defaults lean permissive; tighten network egress and file scope yourself (for the cautionary tale, see OpenAI Hits the Brakes: OpenAI's own eval sandbox was breached from the inside by its own agent).
- Starting in a non-Git directory - Codex requires the working directory to be a Git repo (so actions stay reversible); to skip it use
skipGitRepoCheck: true, but know which insurance you're dropping. - Re-running the whole task after a failure - thread persistence exists precisely for resuming; a full re-run burns double the tokens.
- Jumping to app-server on day one - the protocol layer couples deeply and is expensive to migrate; if two stages of SDK solve it, don't take the third. For the five-way vendor comparison, see the Agent Runtime Comparison.
One-line closer: the two-to-three months you save by freeloading the foundation is exactly enough to build approvals, audit, and circuit-breaking properly - where you spend the saved time decides whether this foundation is a productivity engine or an incident factory.
FAQ
Q1: Do I need to install all three of exec / SDK / app-server?
A1: No - pick one by integration depth: scripts and CI use codex exec; in-code orchestration uses the SDK; only custom UI and approval flows need app-server. Coupling depth doubles at each level; always start at the lowest level that suffices.
Q2: What's the SDK's relationship to the CLI - will versions conflict?
A2: The SDK isn't a rewrite; it wraps the CLI. The TS SDK spawns the @openai/codex CLI and exchanges JSONL events; the Python SDK (openai-codex) bundles the matching CLI (openai-codex-cli-bin) automatically, with SDK versions tracking CLI releases - you never manage version matching by hand.
Q3: The process died mid-task - is the progress gone?
A3: No. Threads persist in ~/.codex/sessions; resumeThread(threadId) picks up where it left off without re-running (and without re-burning tokens). Passing the thread id across processes via something like process.env.CODEX_THREAD_ID is the common pattern in TS.
Q4: With Apache-2.0 open source, what do I still pay for in commercial use? A4: The framework layer is free - modify and commercialize it. Model inference bills through OpenAI (API key or ChatGPT account quota). Also note the IDE Extension and Codex Cloud are outside the open-source scope.
Q5: My product already has a homegrown agent loop - is migrating worth it? A5: The test is "where's your differentiation." If your team's energy goes into maintaining the loop, context management, and tool scheduling - things official runtimes now give away - migration is net positive. If your differentiation is the execution layer itself (or you need deep customization), keep your build but benchmark against Codex's designs (thread resume, approval semantics, structured output) to close gaps. The reins layer (approvals / audit / circuit-breaking) you build yourself either way - see the Agent Guardrails Deployment SOP.
References
- openai/codex repository (GitHub API snapshot 2026-08-22, Apache-2.0, 111,646 stars)
sdk/typescript/README.md: startThread / run / runStreamed / outputSchema / resumeThread / workingDirectory / env / config overridessdk/python/docs/getting-started.md: installation, the three login flows, the thread_start(sandbox=...) examplecodex-rs/app-server/README.md: JSON-RPC 2.0 protocol, stdio/ws/unix transports, Approvals, the-32001overload retry, /readyz /healthz, generate-ts / generate-json-schema- OpenAI official blog (2026-08-19): Codex as a platform
This article is based on official documentation (as of 2026-08-22) and is not legal or security-compliance advice; run production launches through your own security review.