Codex SDK in TypeScript and Python: install, auth, sandbox
OpenAI's Codex SDK in TypeScript and Python (0.171.0): install, start and resume threads, stream events, JSON output, sign-in, billing, sandbox and approvals.
The Codex SDK is OpenAI’s library for running the Codex coding agent from your own program, in two languages, both at 0.171.0 on November 23, 2026: TypeScript, npm install @openai/codex-sdk (Node.js 18+, server side), and Python, pip install openai-codex (Python 3.10+). Each installs a matching Codex CLI and runs it as a child process on your machine, so it uses the same ~/.codex sign-in and config: a ChatGPT sign-in draws on your plan, an API key (the TypeScript apiKey option or CODEX_API_KEY) is billed at standard API rates. You start a thread, call run() once per turn, and keep the thread ID to resume it later; runStreamed() in TypeScript or turn().stream() in Python gives you events as they happen, and an output schema makes the final answer JSON. Set the sandbox yourself: with no sandboxMode and none in your config, the TypeScript SDK’s Codex runs read-only, or workspace-write in a project whose trust is already recorded.
Two libraries that work differently
OpenAI’s Codex SDK page pitches it for automation: “Use the Codex SDK to automate coding tasks, including jobs in CI.” The two packages share the Codex SDK name and a release number, but not a design. The TypeScript one, per its README, “spawns the CLI and exchanges JSONL events over stdin/stdout”: every turn is a fresh codex exec --json run. The Python one starts one codex app-server process and talks JSON-RPC to it for as long as the client is open, and exposes more of what that server can do.
| TypeScript | Python | |
|---|---|---|
Package | @openai/codex-sdk | openai-codex, imported as openai_codex |
Codex it runs | @openai/codex 0.171.0, a dependency | openai-codex-cli-bin 0.171.0, a dependency |
Process | A new codex exec per turn, prompt on stdin | One codex app-server over stdio for the client’s life |
Thread ID | null until the first turn starts | Set when thread_start() returns |
Streaming | Item-level events | Item events plus text deltas; steer() and interrupt() mid-turn |
Default approvals | None asked: headless exec defaults to never | ApprovalMode.auto_review: a reviewer agent decides |
Also | An AbortSignal per turn | Image inputs too; sign-in calls, thread list, fork and archive, models(), an async client |
The TypeScript package has been on npm since October 2025. The Python one reached PyPI as a beta in May 2026 and has carried the CLI’s version numbers since 0.144.4 in July. Two similar names on PyPI are other packages: openai-codex-sdk is a separate one, last released in January 2026, that links no repository and that OpenAI’s docs do not mention, and codex-sdk belongs to Cleanlab. The one OpenAI documents is openai-codex.
Install
# TypeScript (Node.js 18 or later)
npm install @openai/codex-sdk
# Python (3.10 or later)
pip install openai-codexCopiedYou do not need Codex installed separately. The npm package depends on @openai/codex at the same version, which brings the native binary for your platform (Linux, macOS or Windows, x64 or arm64) as an optional dependency. An install that skips optional dependencies, such as npm ci --omit=optional, leaves no binary, and new Codex() throws “Unable to locate Codex CLI binaries. Ensure @openai/codex is installed with optional dependencies.” The package is an ES module only (its exports map has an import entry and no require), so load it with import. OpenAI says to use it server-side.
The Python package pins openai-codex-cli-bin to its own version, with wheels for macOS, glibc and musl Linux on x86_64 and aarch64, and Windows on x64 and arm64. pip install --pre openai-codex opts into prereleases. To run against a Codex you installed yourself, pass codexPathOverride (TypeScript) or CodexConfig(codex_bin=...) (Python); otherwise the version on your PATH does not matter. Updating the SDK is how you update the Codex it runs.
Start a thread, continue it, resume it
A thread is one conversation; each run() is a turn in it, and the next call carries on with everything before. In TypeScript:
import { Codex } from "@openai/codex-sdk";
const codex = new Codex();
const thread = codex.startThread({
workingDirectory: "/srv/app",
sandboxMode: "workspace-write",
});
const first = await thread.run("Find why the date tests fail and fix it");
console.log(first.finalResponse);
console.log("thread id:", thread.id); // keep this to resume later
const second = await thread.run("Now add a regression test for it");
console.log(second.finalResponse);Copiedrun() waits for the turn to finish and returns finalResponse (Codex’s last message), items (every command, file change and message in the turn) and usage. A failed turn throws an Error with the failure’s message. thread.id stays null until the first turn has started, so read it after the first run().
Threads are saved in ~/.codex/sessions on the machine that ran them, and resumeThread() picks one up from there:
const thread = codex.resumeThread(savedThreadId, {
workingDirectory: "/srv/app",
sandboxMode: "workspace-write",
});
await thread.run("Pick up where you left off");CopiedPass the options again. The TypeScript Thread sends its options as command-line flags on every run, a resumed one has only what you give resumeThread(), and codex exec resumes a thread with the sandbox and approval settings of the run doing the resuming, not the ones it was started with, so a resume without sandboxMode falls back to the default sandbox. OpenAI’s own example repeats sandboxMode too. The working directory has to be inside a Git repository unless you set skipGitRepoCheck: true, and additionalDirectories adds folders beyond it.
The same in Python, where the ID exists from the start:
from openai_codex import Codex, Sandbox
with Codex() as codex:
thread = codex.thread_start(cwd="/srv/app", sandbox=Sandbox.workspace_write)
print("thread id:", thread.id)
result = thread.run("Find why the date tests fail and fix it")
print(result.final_response)
result = thread.run("Now add a regression test for it")
print(result.final_response)
# later, in another process
with Codex() as codex:
thread = codex.thread_resume(saved_thread_id)
print(thread.run("Continue where we left off.").final_response)CopiedCodex() starts the app server in its constructor, so use it as a context manager (or async with AsyncCodex() in async code) to make sure the process is closed. A failed turn raises RuntimeError. Unlike the TypeScript resume, thread_resume() needs no options repeated: the app server restores the thread’s saved approval and sandbox settings unless you pass new ones. Resuming a session from the terminal instead is in resuming a Codex or Claude Code session.
Streaming events
runStreamed() returns the turn as it happens. The events are thread.started, turn.started, item.started, item.updated, item.completed, turn.completed, turn.failed and error, and an item is one of agent_message, reasoning, command_execution, file_change, mcp_tool_call, web_search, todo_list or error:
const { events } = await thread.runStreamed("Diagnose the CI failure and fix it");
for await (const event of events) {
if (event.type === "item.completed") {
const item = event.item;
if (item.type === "command_execution") console.log("ran", item.command, "exit", item.exit_code);
if (item.type === "file_change") item.changes.forEach((c) => console.log(c.kind, c.path));
if (item.type === "agent_message") console.log(item.text);
} else if (event.type === "turn.completed") {
console.log(event.usage); // input_tokens, cached_input_tokens, output_tokens, ...
} else if (event.type === "turn.failed") {
console.error(event.error.message);
}
}CopiedThese are the same JSON lines codex exec --json prints, parsed and typed. They are item-level: the event types have no token-by-token text, and a command’s output arrives as aggregated_output on the item. The running to-do list comes as todo_list on item.updated. To stop a turn, pass an AbortSignal as { signal } in the turn options; it goes to the Codex process for that turn.
In Python, thread.turn() returns a handle whose stream() yields the app server’s notifications, text deltas included, as in this cut-down form of OpenAI’s streaming example:
turn = thread.turn("Explain the failing test in three bullets.")
for event in turn.stream():
if event.method == "item/agentMessage/delta":
print(event.payload.delta, end="", flush=True)
elif event.method == "turn/completed":
print("\nstatus:", event.payload.turn.status.value)CopiedKeep reading until turn/completed. The SDK’s FAQ answers a turn that seems to hang with “A turn is complete only when turn/completed arrives for that turn ID.” The same handle has steer(), to send more input into a running turn, and interrupt().
Structured output
Give a turn a JSON Schema and Codex’s final message is JSON that matches it. The SDK hands you that JSON as a string, so parse it:
const schema = {
type: "object",
properties: {
summary: { type: "string" },
status: { type: "string", enum: ["ok", "action_required"] },
},
required: ["summary", "status"],
additionalProperties: false,
} as const;
const turn = await thread.run("Summarize repository status", { outputSchema: schema });
const report = JSON.parse(turn.finalResponse);Copiedresult = thread.run("Summarize repository status", output_schema=schema)
report = json.loads(result.final_response)CopiedThe schema has to be a plain object (the TypeScript SDK throws “outputSchema must be a plain JSON object” otherwise); it writes it to a temporary file and passes --output-schema, and the schema applies to that turn only. The README’s route from Zod is the zod-to-json-schema package with target set to "openAi".
Sign-in, and who pays
Both libraries reuse whatever sign-in the Codex CLI already has on the machine, kept in ~/.codex/auth.json or the OS credential store. OpenAI’s authentication page gives the two kinds: “Sign in with ChatGPT for subscription access” and “Sign in with an API key for usage-based access.”
- A ChatGPT plan: SDK runs use the plan’s Codex usage, like the CLI. The pricing page marks “Codex SDK,
codex exec, and scriptable workflows” as available on Plus, Pro, Business, Enterprise and Edu; how much each plan allows is in which ChatGPT plans include Codex. To sign a machine in from Python, callcodex.login_chatgpt()(its handle carries anauth_url) orcodex.login_chatgpt_device_code()(averification_urlanduser_codefor a machine with no browser), thenwait(); the TypeScript SDK has no sign-in call, so sign in once withcodex loginon that machine. - An API key: “OpenAI bills API key usage through your OpenAI Platform account at standard API rates,” and Codex then uses “standard API pricing instead of included ChatGPT plan credits.” Models are the ones your key can use, and cloud features such as GitHub code review are not included. In TypeScript, pass
new Codex({ apiKey }), which setsCODEX_API_KEYon the Codex process it starts, or setCODEX_API_KEYyourself; in Python, callcodex.login_api_key(key).
For CI, OpenAI’s CI/CD auth page is direct: “The right way to authenticate automation is with an API key.” Running as your ChatGPT account on a runner means carrying auth.json between runs, with one machine or one serialized job stream per copy, and never for public or open-source repositories. The non-interactive mode page adds: “Do not set OPENAI_API_KEY or CODEX_API_KEY as a job-level environment variable in workflows that check out or run repository-controlled code.” For a run that fails with “401 Unauthorized”, see the Codex 401 guide.
One cost the Python default adds: its approval mode is auto-review, and OpenAI’s approvals page notes that “Auto-review uses extra model calls, so it can add to Codex usage.” Each turn’s token counts are in usage on the result in both languages.
Sandbox, approvals and project trust
The sandbox decides what Codex’s commands can touch: read-only, workspace-write (write inside the workspace: the working directory, temporary folders such as /tmp and any folders you add) or danger-full-access. Even in workspace-write, .git, .codex, .agents and .aws inside the workspace stay read-only, and commands get the network only once you allow it: networkAccessEnabled: true in TypeScript, or sandbox_workspace_write.network_access in config.
TypeScript. sandboxMode takes the three names above. Left out, the SDK passes no sandbox flag and Codex falls back to its own default: “by default, codex exec runs in a read-only sandbox”, but in a project with a recorded trust decision the default is workspace-write, which OpenAI’s Python SDK docs call “the normal default for projects with a recorded trust decision”. Pass sandboxMode either way, so what Codex may write does not depend on what this machine has trusted. Nobody is there to answer an approval prompt, and the exec source says “Default to never ask for approvals in headless mode”: Codex “makes a best effort within the constraints you set.” Exec keeps that default unless the approvals reviewer resolves to auto-review, the reviewer agent that judges, in your place, each request that needs approval. That is what the CLI’s --approve-for-me flag sets; in its source the flag is exactly three settings, and the SDK can pass the same three:
const codex = new Codex({
config: {
approvals_reviewer: "auto_review",
approval_policy: "on-request",
sandbox_mode: "workspace-write",
},
});CopiedThe approvalPolicy thread option’s type still lists on-failure and untrusted, but the configuration reference says “untrusted is unsupported, and on-failure is deprecated; use on-request for interactive runs or never for non-interactive runs.” There is no callback for approving individual commands from your code.
Python. sandbox= takes Sandbox.read_only, Sandbox.workspace_write or Sandbox.full_access, on thread_start() or on a single turn, where it also holds for later turns; left out, the app server’s configured default applies. approval_mode= is ApprovalMode.auto_review (the default: on-request approvals decided by the reviewer agent) or ApprovalMode.deny_all (never ask). The public API has no hook for answering approvals yourself either: the client’s built-in handler answers any command or file-change approval request that reaches it with accept. For text from somewhere you do not control, such as an issue body or a chat message, pass ExternalMessage(tool_name=..., content=...) instead of a string; it reaches the model “with tool-level authority, below user and developer instructions.”
Project trust. A repository’s own .codex/config.toml and the MCP servers it defines load in codex exec only for trusted projects, and the TypeScript SDK starts codex exec without --trust. The warning that says so goes to stderr, which the SDK keeps to itself unless the run fails, so an untrusted project’s settings are skipped without a visible sign. Trusting it once from a shell, as the same user, is in the untrusted project configuration guide. Trusting it also makes workspace-write the default sandbox for runs that set none. On Linux the SDK runs the same Codex binary, with the same bubblewrap sandbox, so a server that needs setup for the CLI’s sandbox needs it for the SDK too; that setup is in running Codex on a Linux server.
Config, environment and the model
The Codex the SDK starts reads your ~/.codex/config.toml like any other, so a model or sandbox set there applies unless the code overrides it. In TypeScript, config takes an object that the SDK flattens into --config key=value flags, and configOverrides takes raw TOML strings for keys that cannot be written as dotted paths. Raw overrides beat config, and the SDK’s own settings and the thread options beat both; none of them change your files. In Python, pass config= to thread_start() or CodexConfig(config_overrides=...). Which keys exist and which layer wins is in the Codex config.toml guide.
Leave the model out to use your configured default, or name one: model: "gpt-6.2-sol" in the thread options, model="gpt-6.2-sol" in Python, with modelReasoningEffort or config={"model_reasoning_effort": "high"} for effort. The model has to be one the signed-in account can use; the current list is in Codex models.
The environment is the trap that differs. TypeScript’s env replaces the inherited environment: “When provided, the SDK will not inherit variables from process.env,” so spread process.env into it if you only meant to add a variable. Python’s CodexConfig(env=...) is merged onto os.environ.
Errors you meet first
Codex Exec exited with code 1:(or another code) followed by Codex’s stderr is how the TypeScript SDK reports Codex exiting with an error; the stderr part also carries any warnings Codex printed. A turn that fails while Codex is running throws its own message instead.Not inside a trusted directory and --skip-git-repo-check was not specified.after that prefix means the working directory is not in a Git repository. Despite the wording it has nothing to do with project trust: pointworkingDirectoryat a repository or setskipGitRepoCheck: true.Unable to locate Codex CLI binaries.The platform package was not installed; reinstall without--omit=optional.Unable to locate the pinned Codex runtime.(Python) Theopenai-codex-cli-bindependency is missing; reinstallopenai-codexfrom PyPI rather than from a source checkout.
When codex exec or the app server fits better
codex exec is the TypeScript SDK without the TypeScript. For a cron job, a shell pipeline or a CI step, the flags do the same work with nothing to install but Codex, as in running a coding agent headless on a schedule:
codex exec --json --sandbox workspace-write \
--output-schema schema.json -o result.json "Summarize repository status"
codex exec resume <thread-id> "Now add a regression test for it"CopiedOn GitHub Actions, OpenAI says to use its Codex GitHub Action, openai/codex-action, instead of installing and authenticating the CLI yourself; the action “is designed to reduce API key exposure” by starting a Responses API proxy. Reach for the SDK when the run is part of a program: several turns with logic between them, typed events feeding a UI or a log, or results going straight into your own data.
The app server is what OpenAI’s app server page offers for “a deep integration inside your own product: authentication, conversation history, approvals, and streamed agent events”, the protocol behind Codex’s own IDE extension. It is the route for answering approval requests yourself (accept, accept for the session, decline or cancel) and showing them to a person. The Python SDK already speaks it; from TypeScript you write the JSON-RPC client yourself, starting from types generated for your exact Codex version with codex app-server generate-ts --out ./schemas. The same page says when not to: “If you are automating jobs or running Codex in CI, use the Codex SDK instead.” Older tutorials that drive Codex as an MCP server are out of date: “The codex mcp-server command and standalone codex-mcp-server binary have been removed.”
Against the Claude Agent SDK
Anthropic’s equivalent is built the same way, “a library that runs the Claude Code binary”, in the same two languages. The difference that shapes your code is control during a run. The Claude Agent SDK lets your program decide each tool call that still needs approval through a canUseTool callback. The Codex SDK has no per-call callback, so a run is bounded by the sandbox and approval settings fixed before the turn starts, and a request to go beyond them is either never made (the TypeScript default) or judged by auto-review, never by code you write. The Claude library’s install, permissions and billing are in the Claude Agent SDK guide.