Codex SDK
Read the two badges separately: the first is whether this page is backed by evidence, the second is whether the product is still maintained. An archived product can have complete evidence; complete evidence does not mean the product is active.
30-second check: should it make your shortlist?
"Turns the Codex CLI into an object you can drive inside a Node process" — the…
Local / self-hosted · Framework / SDK
Open licence
Read the original licence before commercial useBlocked · Not in filing list
These four cards help you rule things out, not decide for you. The real differences are in the eight questions and sources below.
Information not confirmed
- Per-platform implementation differences of the three sandbox tiers on Windows / macOS / Linux (especially whether Windows goes through WSL)
- Tool-calling and structured-output quality alignment after switching to third-party providers
- Whether the Python SDK's API aligns with the TS version (whether
Thread/run/resumeThreadconcepts match) - Concurrent-write and cross-machine migration semantics of
~/.codex/sessions - The full syntax of
permissions.auditrules (the official docs give only the filesystem example)
"Turns the Codex CLI into an object you can drive inside a Node process" — the official README opens with "Embed the Codex agent in your workflows and apps"; the second sentence settles the form:
The TypeScript SDK wraps thecodexCLI from@openai/codex. It spawns the CLI and exchanges JSONL events over stdin/stdout.
When to use it, when not to
A good fit in four cases:
- You want to put Codex inside your own Node app, Electron app or CI
- You need non-interactive execution
- You need file-level permission rules
- You are on a TypeScript or Python stack, have settled on OpenAI models, but want the model layer swappable
Not a fit in two cases:
- You want a pure library and do not want to carry a spawned CLI child process — use the OpenAI Agents SDK instead
- Your target directory is not a Git repository and you do not want to pass
skipGitRepoCheck
⚠ One more capability boundary: if you need a compaction API exposed at the SDK layer, it does not have one. The CLI side has compact_prompt / experimental_compact_prompt_file plus PreCompact / PostCompact hooks, but the SDK layer has no dedicated compaction interface — config pass-through is the only route.
China availability domestic / direct access / CAC filing · snapshot 2026-10-23
- Origin
- foreign-made foreign entity (no matching filing entity in the CAC registry).
- Direct access
- direct blocked developers.openai.com 403 direct from mainland, 200 via proxy.
- CAC filing
- not in filing list:not in the CAC public registry (13 batch attachments searched 2026-10-20, https://www.cac.gov.cn/2024-04/02/c_1713729983803145.htm); the product does not serve the mainland public, so filing does not apply.
Filing status is quoted from the CAC public registry (updated batch by batch; this site copies the number and does not interpret it). "Direct access" is this site's own reachability measurement from a mainland network, not a vendor promise. GitHub-hosted sites fluctuated on the measurement day — the note says so.
8 questions, one table
8 questions, each comparable item by item with its peers.
- Model & openness
Defaults to OpenAI, but the architecture is not locked down.
Three pieces of evidence:
- the README's config example translates
baseUrlinto--config openai_base_url=...passed to the CLI — i.e. switching the API endpoint is a first-class config item
- the official
config-advancedpage has a dedicated Custom model providers section (verified): top-levelmodel = ...withmodel_provider = "proxy", then[model_providers.<id>](fields includebase_url/env_key/wire_api/http_headers/auth.command)
ThreadOptionshas its ownmodel?: stringfield
Built-in provider IDs: reserved
openai,ollama,lmstudio, plus built-inamazon-bedrockandazure.openai_base_urlcan change a built-in provider's base URL.The official example directly gives a third party:
Official example:
[model_providers.mistral]base_url = "https://api.mistral.ai/v1"OSS mode is also supported:
--osswithoss_provider = "ollama" | "lmstudio".That is: the official docs explicitly support non-OpenAI models (local Ollama / LM Studio, Mistral, Bedrock etc.).
README wording: If you set
baseUrl, the SDK passes it as a--config openai_base_url=...override⚠ But after switching to a third-party model? How good are tool calling and structured output quality? The official docs give no quantified conclusion. This site has not measured either.
- the README's config example translates
- Where it runs
The process form is "your Node process + a spawned CLI subprocess."
The README's
envparameter note is worth attention. By default the CLI inherits the Node process environment. So you can fully control which variables the CLI sees. The official use case given is sandboxed hosts (e.g. Electron apps).The SDK injects its own needed variables (like
CODEX_API_KEY) on top of the inheritance.This is decisive for Electron / desktop-app integration — the official docs call out this scenario explicitly.
README wording: By default, the Codex CLI inherits the Node.js process environment
- Local files
Local files are a native CLI capability; the SDK side only needs a working directory.
Three relevant parameters:
workingDirectory— sets the run directoryadditionalDirectories— appends extra directorieslocal_imagetype input items — pass local images to the CLI (via--image)
⚠ One behavior you must know: Codex requires the working directory to be a Git repository. It refuses to run otherwise. The check can be skipped with
skipGitRepoCheck.This is a selection-level hard constraint: it does not work out of the box in non-Git directories (pure data dirs, temp dirs).
Official wording: To avoid unrecoverable errors, Codex requires the working directory to be a Git repository
- Tasks after shutdown
Among objects collected on this site, this is the only one officially and explicitly supported for non-interactive execution.
Verified: the official
noninteractivepage is verified (docs/exec.mdpoints to it).codex exectargets scripts and CI.- default read-only sandbox;
--sandbox workspace-writeordanger-full-accessavailable --jsonoutputs JSONL--output-schemafor structured output--ephemeralwrites nothing to disk- resumable:
codex exec resume --last, orcodex exec resume <SESSION_ID>
The SDK-side counterpart is
resumeThread(); Threads persist under~/.codex/sessions.(This forms a pair with the CLI entry. Over there, "Gemini CLI is the only one explicitly supporting non-interactive".)
⚠ Note
~/.codex/sessionsis a file directory, not a database. State and process live on the same machine.Cross-machine migration and multi-process concurrent-write semantics are not stated officially. (noninteractive and config-reference pages checked; they only cover
history.persistenceand resume.)The official positioning of
codex exec: scripts and CI- default read-only sandbox;
- Tools & extensions
The tool surface is entirely decided by the CLI — the SDK neither adds nor trims.
On the SDK side you get a structured event stream.
runStreamed()returns an async generator. Event types:item.completed— tool calls, streaming responses, file-change notificationsturn.completed— includes usage stats
Structured output is a first-class capability the SDK explicitly supports:
outputSchematakes a JSON Schema, and the official docs also recommend the Zod conversion pathzodToJsonSchema(schema, { target: "openAi" }).⚠ There is a naming trap here: that target says
"openAi". But what it produces is generic JSON Schema. Any model honoring that schema can use it — it does not mean OpenAI only.The MCP situation needs stating clearly. The README never mentions MCP. None of the 9 MCP servers collected on this site involve it either. But Codex CLI's MCP support is verified (the official docs have a standalone MCP page):
- transports: STDIO (command / args / env / env_vars / cwd) and Streamable HTTP (url / bearer / headers)
- config: the
codex mcpcommand line, or[mcp_servers.<name>]inconfig.toml - tool switches:
enabled_tools/disabled_tools - approvals: per-server and per-tool
approval_mode(auto/prompt/approve) - auth:
codex mcp loginvia OAuth
Official wording: Codex supports MCP servers in both the CLI and the IDE extension SDK side: the SDK's
configpassthrough writes into the CLI'sconfig.toml, so MCP is reachable this way; but the official SDK README does not spell out this linkage, so this site records it only as a CLI capability and still does not link it to the MCP-site servers.- Context & memory
What it provides is "session continuation", not "context management".
The evidence is
resumeThread(threadId). It can restore a conversation and keep running, but there is no compaction, summarization or offloading mechanism.In other words,
Threadsolves reliable resume (the "state" surface as this site defines it), not long context (the "context" surface as this site defines it).To compact context you can only rely on CLI-side config or switch models — the SDK layer exposes no related options.
⚠ SDK-side linkage with MCP: the SDK's
configpassthrough writes into the CLI'sconfig.toml, so MCP is theoretically reachable this way. But the official SDK README does not spell out this linkage — this site records it only as a CLI capability and does not link it to the MCP-site servers.- Permissions & limits
This is the most valuable finding from this site's cross-check: it fills the approval-enum gap left in the CLI entry.
The evidence comes from SDK source (not docs), the type definitions in
sdk/typescript/src/threadOptions.ts:- four approval modes —
ApprovalMode = "never" | "on-request" | "on-failure" | "untrusted" - three sandbox tiers —
SandboxMode = "read-only" | "workspace-write" | "danger-full-access" - network controlled separately —
networkAccessEnabled?: boolean,webSearchMode?: "disabled" | "cached" | "live",webSearchEnabled?: boolean
- reasoning effort has 8 levels —
ModelReasoningEffort: minimal / low / medium / high / xhigh / max / ultra / persistent
The other layer is config passthrough. The SDK supports
config, auto-flattened into dotted paths and converted to TOML for--config. There is alsoconfigOverrides(raw TOML passed item by item). The official example directly gives filesystem-level rules:Official example:
permissions.audit.filesystem={":root"="read","/path/to/project/.env"="deny"}That means reading a file like
.envcan be denied precisely by path. The official precedence: raw overrides > structured config > SDK-managed settings.Sandbox and approval official defaults verified (
agent-approvals-securityandconfig-advanced):- local default workspace-write + network off; non-version-controlled dirs default to read-only
- top-level keys
approval_policy(untrusted/on-request/never/granular, includingapprovals_reviewer = "auto_review") pair withsandbox_mode
[sandbox_workspace_write]can setwritable_roots,network_access- there are named profiles:
:read-only/:workspace/:danger-full-access - under
workspace-write,.git/.agents/.codexremain recursively read-only - network additionally has
features.network_proxydomain allowlist + DNS-rebinding protection
⚠ The three sandbox tiers differ in per-platform implementation. Platforms mean Windows / macOS / Linux. The official docs do not enumerate these differences item by item. They only say "OS-level mechanisms enforce sandbox policies", with no network by default and writes limited to the workspace.
(
agent-approvals-security,config-advanced,config-referencepages checked.)- four approval modes —
- Best for
Fits four scenarios:
- embedding Codex into your own Node app / Electron app / CI
- needing non-interactive execution
- needing file-path-precise permission rules
- TypeScript or Python stacks, already committed to OpenAI models but wanting the model layer swappable
Does not fit two scenarios:
- wanting a pure library without carrying an extra CLI subprocess — use the OpenAI Agents SDK for that
- the target directory is not a Git repo and you are unwilling to enable
skipGitRepoCheck
⚠ One more capability boundary: if you need a compaction API exposed directly at the SDK layer, it does not deliver.
The CLI side has
compact_prompt/experimental_compact_prompt_fileandPreCompact/PostCompacthooks configurable, but the SDK layer has no dedicated compaction interface, only config passthrough.
Licence and terms of use
Apache-2.0
Top misconception
- Assuming openai/codex-sdk from the v3 roadmap exists — that repo 404s; the SDK is a subdirectory of the monorepo
- Assuming the SDK version number reflects the capability — package.json says 0.0.0-dev; the real version tracks the CLI (currently 0.159.3)
- Expecting it to work out of the box outside a Git directory — the CLI requires the working directory to be a Git repository, so you must skip explicitly
- Treating
sandbox_workspace_write.network_accessand the SDK'snetworkAccessEnabledas two separate things — the latter is the SDK-level entry point; the former is a config passthrough - Treating OpenAI Agents SDK (a pure Python library) as a like-for-like alternative — the forms differ, see layer_position
Evidence sources
Checked 2026-10-23,Content updated 2026-10-01。This is the date of the entry, not a claim that every field was rechecked that day.
| Type | Name | Link |
|---|---|---|
| repo | openai/codex · repository (monorepo, SDK under sdk/ subdirectories) | https://github.com/openai/codex |
| docs | TypeScript SDK README (wraps the CLI, JSONL communication, thread/turn, resume, config passthrough) | https://github.com/openai/codex/tree/main/sdk/typescript |
| code | Source sdk/typescript/src/threadOptions.ts (ApprovalMode four tiers / SandboxMode three tiers / network and reasoning effort) | https://github.com/openai/codex/blob/main/sdk/typescript/src/threadOptions.ts |
| code | sdk/typescript/package.json (package name @openai/codex-sdk, Apache-2.0, Node≥18) | https://github.com/openai/codex/blob/main/sdk/typescript/package.json |
| docs | docs/exec.md · Non-interactive mode (body is an external link only) | https://github.com/openai/codex/blob/main/docs/exec.md |
| docs | docs/sandbox.md · Sandbox & approvals (body is an external link only) | https://github.com/openai/codex/blob/main/docs/sandbox.md |
| docs | Official Agent approvals & security (three sandbox tiers, approval policies, network policies, protected paths) | https://developers.openai.com/codex/agent-approvals-security |
| docs | Official Configuration Reference (approval_policy / sandbox_mode / model_provider etc. keys) | https://developers.openai.com/codex/config-reference |
| docs | Official Advanced Configuration (Custom model providers, OSS mode, compaction, hooks) | https://developers.openai.com/codex/config-advanced |
| docs | Official MCP docs (CLI and IDE support STDIO / Streamable HTTP) | https://developers.openai.com/codex/mcp |
| docs | Official Non-interactive mode (codex exec, resume, read-only default) | https://developers.openai.com/codex/noninteractive |
| repo | Python SDK directory (existence recorded by this site; details unverified) | https://github.com/openai/codex/tree/main/sdk/python |
| changelog | Releases (0.159.3 @ 2026-09-30, plus 0.161.0-alpha pre-releases) | https://github.com/openai/codex/releases |
| docs | Official security docs (sandbox and approvals, JS-rendered; body not captured by this site) | https://developers.openai.com/codex/security |
Test notes
This site has not completed measured runs.
The test protocol is at protocols/framework/_protocol.md.
Suggested measurement (tailored to this SDK's form):
| # | What to test | Why it is worth testing |
|---|---|---|
| 1 | CLI × SDK version combination matrix (CLI 0.159.3 / 0.161.0-alpha × SDK) | the SDK version does not reflect capability; you need to know which combinations are validated |
| 2 | Whether permissions.audit.filesystem deny rules actually block reading .env | the official example gives the syntax, but interception strength is unverified |
| 3 | How complete resumeThread recovery is after a process crash | this site's top concern: "reliable long-running operation" |
| 4 | Real time and cost differences across the 8 modelReasoningEffort levels | the official docs give the enum but not the price |
| 5 | Failure rate and interruption behavior of running a real task chain in non-interactive mode | the core metric of unattended scenarios |
| 6 | Whether structured output stays reliable after switching baseUrl to a third-party provider | the architecture is not locked down, but reliability is unknown |
Form clarification: this is the first "CLI-wrapped" object on this site
Of this site's three coding-base forms, this belongs to type 2 (wrapping an existing CLI):
| Form | Who runs the agent loop | Objects on this site |
|---|---|---|
| ① build-your-own-loop framework | a library inside your process | OpenAI Agents SDK, Deep Agents |
| ② wrapping an existing CLI | an external CLI subprocess | Codex SDK, Claude Agent SDK |
| ③ ships a full runtime | vendor-hosted | (none yet) |
This difference is not a matter of wording; it decides several practical things:
- Behavior boundary = CLI version boundary. The SDK's own version number is
0.0.0-dev(measured in package.json); what really decides capability is the CLI it spawns — currently0.159.3(releases @ 2026-09-30, with0.161.0-alpha.7pre-release). Upgrading the CLI equals upgrading the SDK's capability and risk surface. - Sandbox and approvals are not yours to define. They are CLI capabilities; the SDK can only influence them via parameters (see permissions below).
- One more process means one more overhead and one more failure point. But in exchange you get the CLI's full capabilities without implementing them.
The permission surface: source code gives four approval modes and three sandbox tiers
⚠ This passage corrects an "unverified" in this site's CLI-site entry: this site's CLI entry (cli/products/codex-cli.md) once carried one sentence. It read "the specific approval modes were not verified the 2026-10-08 pass" (translated). The reason: no enum could be found in the CLI docs. (On 2026-10-08 that entry was completed with the four official approval tiers.) This time the enum was found in the SDK source's type definitions — not in the doc external links, but in the source:
// sdk/typescript/src/threadOptions.ts (verified 2026-10-01)
export type ApprovalMode = "never" | "on-request" | "on-failure" | "untrusted";
export type SandboxMode = "read-only" | "workspace-write" | "danger-full-access";
Accompanying options:
| Option | Values | Role |
|---|---|---|
networkAccessEnabled | bool | whether the sandbox allows network |
webSearchMode | disabled / cached / live | three tiers of web search |
webSearchEnabled | bool | master search switch |
modelReasoningEffort | 8 levels: minimal / low / medium / high / xhigh / max / ultra / persistent | reasoning effort |
additionalDirectories | string[] | append accessible directories |
One layer deeper: reading files can be denied precisely by path. The SDK supports configOverrides passing raw TOML item by item, and the official example directly gives filesystem rules:
configOverrides: ['permissions.audit.filesystem={":root"="read","/path/to/project/.env"="deny"}']
This means files like .env can be denied individually. It is not coarse-grained "sandbox blocks all writes" protection. The official precedence, high to low: raw overrides, structured config, SDK-managed settings.
Sandbox / approval defaults verified (see axes.permissions): local default workspace-write + network off, non-version-controlled dirs default read-only; under workspace-write, .git / .agents / .codex are recursively read-only. The per-platform implementation differences of the three sandbox tiers are not enumerated officially: they only say "OS-level mechanisms enforce sandbox policies", without listing Windows / macOS / Linux differences separately (agent-approvals-security and config-advanced pages checked). Windows users especially should verify themselves.
Local files: there is a hard constraint you must know
To avoid unrecoverable errors, Codex requires the working directory to be a Git repository.
It refuses to run otherwise; skipGitRepoCheck: true can skip it.
This is a selection-level constraint: out-of-the-box use in pure data dirs, temp dirs, upload dirs does not work, and those scenarios are exactly what you hit most when "embedding into your own product".
State vs context: it only solves the former
| The surface this site cares about | This SDK's official means | Enough? |
|---|---|---|
| state (reliable resume) | resumeThread(id), Threads persisted under ~/.codex/sessions | ✅ official support exists |
| context (long-task compaction) | none. No compaction/summarization/offloading options at the SDK layer | ❌ only CLI-side config |
The "state ≠ context" stance is confirmed right here: it preserves the conversation completely, but does no compaction of content — cost and latency once threads grow is a separate matter.
⚠ ~/.codex/sessions is a file directory, not a database. Cross-machine migration and multi-process concurrent writes to the same session are not stated officially.
Non-interactive execution: the only candidate here with official evidence so far
The title of docs/exec.md is Non-interactive mode.
This forms an interesting pair with that CLI-site entry: among the CLI site's 6 objects, only Gemini CLI explicitly supports non-interactive script mode. The rest are marked unverified on this item. And on this harness site, Codex SDK is currently the only object with official non-interactive documentation.
If what you want is "run a chain of tasks unattended", these two are the only evidence-backed landing points — one in your terminal, one inside your Node process.
Structured output: supported quite completely
const turn = await thread.run("Summarize repository status", { outputSchema: schema });
- JSON Schema can be passed directly (
as constwith types) - or converted from Zod:
zodToJsonSchema(schema, { target: "openAi" })
⚠ There is a naming trap here. That target: "openAi" only tells the converter which target format to use. What it produces is standard JSON Schema — it does not mean only OpenAI models can use it.
MCP: officially supported by Codex CLI, reachable on the SDK side via config passthrough
The SDK README never mentions MCP, and the main repo's docs/ directory has no mcp.md either (verified 2026-10-01). But the official developer docs have a standalone MCP page (verified 2026-10-08):
Codex supports MCP servers in both the CLI and the IDE extension.
STDIO and Streamable HTTP transports are both supported, configurable via codex mcp add ... and [mcp_servers.<name>] in config.toml, with per-server / per-tool approval_mode (auto / prompt / approve) and enabled_tools / disabled_tools. SDK side: the SDK's config passthrough writes into the CLI's config.toml, so MCP servers are reachable this way; but the official SDK README does not spell out this linkage, so this site records it only as a CLI capability and still does not link it to the 9 official servers on this site's MCP section.
Verification notes
Basis for confidence: partial (downgraded from verified on 2026-10-03):
Why downgraded: the subject of the ❌ items below is this site's evidence gap, not "not provided officially". Per the v3 rule "say unknown when unknown", marking verified while these items exist would be inflated, hence partial. Main gaps: per-platform implementation differences of the three sandbox tiers, third-party provider capability alignment, permission-audit rule syntax. (2026-10-08 additions: official MCP support, model/provider config surface, sandbox and approval defaults, non-interactive config all verified.)
- ✅ Verified: repository exists and star count (130,474 · rolling check 2026-10-23), license (Apache-2.0), last push (2026-10-22, still active), latest stable 0.163.0 (releases @ 2026-10-15), full
sdk/typescript/package.json(package name@openai/codex-sdk, version 0.0.0-dev, Node≥18), full six sections ofsdk/typescript/README.md(quickstart / streaming / structured output / images / resume / environment and config), full type definitions ofsdk/typescript/src/threadOptions.ts(four approval tiers, three sandbox tiers, network and search, eight reasoning levels), thedocs/directory listing, and the existence of python/typescript/python-runtime subdirectories undersdk/
- ❌ Not verified: per-platform implementation differences of the three sandbox tiers (official only says OS-level enforcement, not enumerated item by item), tool-calling and structured-output quality alignment after switching to third-party models, whether the Python SDK's API shape matches the TS version, concurrent-write semantics of
~/.codex/sessions
⚠ Also correcting the plan. The codex-sdk written in the v3 plan (labeled 127k★) does not exist as a standalone repository. gh api returns 404. The 127,448★ is the star count of the openai/codex monorepo; the SDK is its sdk/typescript subdirectory.
Related entries
- Claude Agent SDKThe pair this site should contrast most: both are CLI-wrapped (bundled / spawn CLI + inter-process communication), but the Claude side's README states Claude-only with no provider bypass, while this SDK has
baseUrlandmodel_providers. - OpenAI Agents SDKTwo forms from the same vendor: that one is a pure Python library (primitives-only), this one is a Node + CLI-subprocess wrapper. The first selection question is "do you want to carry an extra CLI process".
- Deep AgentsThe batteries-included contrast surface: this SDK presets nothing; tools and sandbox are entirely decided by the CLI version.
- LangGraphIf you need "non-interactive + graph structure + multi-agent collaboration", an orchestration framework is the matching layer; this SDK only gives single-thread execution.
- Codex CLIOther layer · AI coding
Same-category peers
Look at these three before reading further
Selected by overlap in jobs, not ranked. Compare where it runs, licence and status first; if one of the three fails, skip it.
| Object | Where | Licence | Evidence / status | What it is for |
|---|---|---|---|---|
| Claude Agent SDK | Local / self-hosted | Open licence | 8 questions checked Active | The Python programming interface to Claude Code — a polished coding CLI |
| DSPy | Local / self-hosted | Open licence | 8 questions checked Active | DSPy turns 'tuning prompts' into a programming problem (MIT, Stanford NL |
| Pydantic AI | Local / self-hosted | Open licence | 8 questions checked Active | Pydantic AI is the type-safe Python agent loop — official README: "Pydan |
Same vendor
More from OpenAI
One vendor’s products are often split across categories. This list puts them together so you do not have to assemble them across five sites.
This page is generated from the ai-handbook data layer (CC BY 4.0).
For the judging criteria and method notes, see METHODOLOGY.md.