23. Headless Codex: exec and the SDKs

codex exec runs one turn without a person at the keyboard: it embeds an app server in its own process, prints progress or dot-named JSONL events, rejects every approval request with error -32000, and exits 1 when the turn fails. The TypeScript SDK wraps that command; the Python SDK skips it and speaks the app-server protocol to codex app-server directly.

The terminal user interface (TUI) from Chapter 22 assumes someone is watching. Scripts, continuous integration (CI) jobs, and programs that embed an agent cannot answer a prompt or read a screen. For them Codex offers three headless doors: the codex exec command, a TypeScript software development kit (SDK) that drives it, and a Python SDK that talks to the app server from Chapter 21.

This chapter walks through codex exec from prompt to final message, then its JSON Lines (JSONL) output, output schemas, resume, approval handling, and exit codes. It then shows both SDKs, their main objects, and a minimal program for each, and ends with a rule for choosing among the four options.

The picture

The TypeScript SDK spawns codex exec, writes the prompt to its stdin, and reads JSONL events from its stdout; codex exec runs an embedded app server in the same process; the Python SDK spawns codex app-server with a stdio listener and exchanges JSON-RPC lines with it; both servers drive codex-core.

There are two paths into the same engine. On the top path, a TypeScript program calls thread.run(), CodexExec spawns codex exec --experimental-json, and the process translates app-server notifications into a simpler event stream. A shell script or CI job uses the same process directly. On the bottom path, a Python program calls thread.run(), and CodexClient spawns codex app-server --listen stdio:// and sends JSON-RPC requests itself. The top path hides the protocol and gives up approvals and steering; the bottom path exposes both.

codex exec

From prompt to final message

codex_exec::run_main in codex-rs/exec/src/lib.rs first checks --remote. When it names a server, run_main hands off to remote::run, which connects to that server instead of starting one. Otherwise it follows a fixed sequence for a new turn:

  1. Load configuration, then read the prompt from the argument, or from stdin when the argument is missing or -. If stdin is piped and a prompt is also given, stdin is appended as a <stdin> block.
  2. Load the output schema file, if any.
  3. Refuse to run outside a Git repository unless --skip-git-repo-check or --dangerously-bypass-approvals-and-sandbox is set.
  4. Start an InProcessAppServerClient.
  5. Send thread/start, or thread/resume or thread/fork for those subcommands.
  6. Send turn/start with the prompt, turnTrigger set to exec, and the output schema.
  7. Loop over server events until turn/completed, then unsubscribe and shut the client down.
  8. Print the final message and exit with 0 or 1.

The embedded server is the same MessageProcessor the TUI uses, started through codex_app_server::in_process (see Chapter 21). exec identifies itself as codex_exec, uses SessionSource::Exec, opts into the experimental API, and sets enable_codex_api_key_env: true, so the CODEX_API_KEY environment variable can supply credentials. The TUI sets that last field to false. exec never consults the shared daemon: a CI job gets a private server that lives and dies with the command.

Without --json, progress goes to stderr. The final message goes to stdout when stdout or stderr is not a terminal, which is the piped case, so codex exec "summarize" > out.txt captures only the answer. -o FILE also writes the last message to a file.

Approvals when nobody is watching

A headless run cannot show an overlay. handle_server_request answers each server request at once:

ServerRequest::CommandExecutionRequestApproval { request_id, params } => {
    reject_server_request(
        client,
        request_id,
        &method,
        format!(
            "command execution approval is not supported in exec mode for thread `{}`",
            params.thread_id
        ),
    )
    .await
}

The excerpt is from codex-rs/exec/src/lib.rs. reject_server_request sends a JSON-RPC error with code -32000. File-change, permissions, user-input, dynamic tool, token refresh, and attestation requests get the same treatment, and so do the two version 1 approval variants. MCP elicitations are the exception: exec answers them with a cancel, not an error, so a cancel never turns into a decline.

On the server side, an error answer to an approval reaches fail_exec_approval, and the engine treats the command as denied with the reason “approval request failed.” The turn continues and the model sees the denial. A rejection alone therefore does not fail the run. Before the turn starts, warn_if_human_approval prints a warning when the thread asks a human: codex exec “immediately rejects approval requests it receives.” It suggests --config 'approval_policy="never"' or approvals_reviewer="auto_review" on codex exec resume. Chapter 13 explains those settings.

Ctrl-C

An interrupt sends turn/interrupt. For the in-process client the turn id is empty; a comment explains that “an untargeted interrupt also works before the server announces the turn as active.” Remote and cloud clients send the real turn id. An interrupted turn ends with status 1.

The JSONL event stream

--json, with the alias --experimental-json, switches the output to one JSON object per line on stdout. The schema lives in codex-rs/exec/src/exec_events.rs and differs from the app-server notifications: names use dots, fields use snake case, and there are only eight event types. The table lists them.

type Payload Emitted when
thread.started thread_id The thread exists
turn.started none The turn begins
item.started item An item begins, if tracked
item.updated item The to-do list changes
item.completed item An item reaches a final state
turn.completed usage The turn succeeds
turn.failed error The turn fails
error message An error notification for the turn, even one the server will retry

Items flatten an id and a type. The nine item types are agent_message, reasoning, command_execution, file_change, mcp_tool_call, collab_tool_call, web_search, todo_list, and error. EventProcessorWithJsonOutput assigns ids of the form item_0, item_1, and so on. It emits no text deltas: an agent message appears once, complete. A plan update becomes a todo_list item that starts, updates, and completes when the turn ends. Warnings, deprecation notices, and model reroutes become error items, so a consumer sees them without failing the run.

The TypeScript SDK test returns thread events in sdk/typescript/tests/runStreamed.test.ts pins a complete stream for one prompt and one reply from a mock model:

{"type":"thread.started","thread_id":"<uuid>"}
{"type":"turn.started"}
{"type":"item.completed","item":{"id":"item_0","type":"agent_message","text":"Hi!"}}
{"type":"turn.completed","usage":{"cache_write_input_tokens":0,"cached_input_tokens":12,"input_tokens":42,"output_tokens":5,"reasoning_output_tokens":0}}

The simpler schema is a deliberate adapter. A shell script or a small SDK can consume it with a line reader and a switch on type, without knowing about server requests, request ids, or the 89 notification methods.

Output schemas

--output-schema FILE asks for structured output. load_output_schema reads the file and parses it as JSON; if the file cannot be read or is not valid JSON, exec prints an error and exits 1. It does not check that the JSON is a valid schema. The value travels in turn/start as outputSchema, and the model client sends it as a JSON Schema text format named codex_output_schema (see Chapter 6). The final agent_message then holds a JSON string.

Resume and fork

codex exec resume continues an earlier thread. It takes a session id or thread name, or --last for the most recent; --all disables filtering by working directory. With --last, exec pages through thread/list sorted by update time, 100 threads per page, and picks the first match. It then sends thread/resume and starts a turn with the new prompt. codex exec fork copies a thread into a new one, and codex exec review runs a code review instead of a prompt. Where threads are stored and how resume rebuilds them belongs to Chapter 24.

Exit codes

exec uses two exit codes. Status 0 means the turn completed and nothing below happened; every failure exits 1, so a script cannot tell failures apart by status alone. The table lists the causes read in run_main and its helpers.

Cause Status
Turn completed without errors 0
Turn ended failed or interrupted 1
Non-retrying error notification for this turn 1
A reply to a server request could not be sent 1
Output truncated by an interrupt 1
Outside a Git repository without the skip flag 1
Output schema unreadable or not JSON 1
Configuration errors, or an error returned from main 1

The last row relies on standard Rust behavior: main returns anyhow::Result<()>, and an Err ends the process with status 1. A failed or interrupted turn also sets emit_final_message_on_shutdown to false, so exec does not write a last message for it, to stdout or to the -o file.

The TypeScript SDK

@openai/codex-sdk wraps the command line. Its README says it “spawns the CLI and exchanges JSONL events over stdin/stdout.” The main objects are Codex, which holds options and a CodexExec; Thread, returned by startThread() or resumeThread(id); and the result types Turn, with items, finalResponse, and usage, and StreamedTurn, whose events is an async generator of ThreadEvent. The README’s quickstart is the whole program:

import { Codex } from "@openai/codex-sdk";

const codex = new Codex();
const thread = codex.startThread();
const turn = await thread.run("Diagnose the test failure and propose a fix");

console.log(turn.finalResponse);
console.log(turn.items);

Each call to run or runStreamed spawns a new process, so a thread’s turns run in a series of short-lived codex exec processes that share only the stored thread. CodexExec.run in sdk/typescript/src/exec.ts builds the arguments exec --experimental-json, turns thread options into flags such as --model, --sandbox, --cd, and --config approval_policy="...", and appends resume <threadId> after the first turn. It writes the prompt to the child’s stdin, closes it, and yields stdout lines through readline. A schema passed as outputSchema goes to a temporary file for --output-schema and is deleted afterward. The SDK sets CODEX_INTERNAL_ORIGINATOR_OVERRIDE=codex_sdk_ts and maps an apiKey option to CODEX_API_KEY.

Errors surface in two ways. run throws when it sees turn.failed. CodexExec.run throws when the process exits with a nonzero code or a signal, and includes the child’s stderr. Because every turn is a fresh codex exec, the SDK inherits its limits: approvals are rejected, and a running turn cannot be steered. The process boundary buys simplicity and isolation, and costs a process start per turn.

The Python SDK

The openai-codex package takes the other path. CodexClient in sdk/python/src/openai_codex/client.py is a “synchronous typed JSON-RPC client for codex app-server over stdio.” It spawns codex app-server --listen stdio://, sends initialize with client name codex_python_sdk and experimentalApi: true, then the initialized notification. Request ids are uuid4 strings, and messages carry no jsonrpc field. A single reader thread classifies each line: a message with both method and id is a server request, one with only method is a notification, and the rest are responses.

The public objects sit above that client. Codex and AsyncCodex own the process; thread_start, thread_resume, and thread_fork return a Thread. Thread.run returns a TurnResult with final_response, items, usage, and timing fields. Thread.turn returns a TurnHandle, which can steer, interrupt, or stream notifications for that turn. The README quickstart:

from openai_codex import Codex

with Codex() as codex:
    thread = codex.thread_start()
    result = thread.run("Explain this repository in three bullets.")
    print(result.final_response)

Approvals work differently from exec. thread_start takes an ApprovalMode that defaults to auto_review, which maps to approval policy on-request with the auto_review reviewer, so a model-based reviewer decides (see Chapter 16). deny_all maps to approval policy never. If a server request still reaches the client, the default handler answers command and file-change approvals with {"decision": "accept"} and returns an empty result for anything else; a caller that builds a CodexClient directly can pass its own approval_handler. The models in generated/v2_all.py come from the checked-in codex_app_server_protocol.v2.schemas.json through datamodel-codegen, and the package pins its binary through a dependency on openai-codex-cli-bin==0.153.4.

Choosing a path

The four options trade simplicity against control. OpenAI’s developer blog post “Codex as a platform: build on the open agent harness” (no date on the page) draws the same line: codex exec for scripts and CI, the app server when the agent is part of the product itself. The table compares the options.

Option Talks to Approvals Best for
codex exec Embedded server Rejected Scripts and CI
TypeScript SDK codex exec per turn Rejected Node programs, simple turns
Python SDK codex app-server over stdio Reviewer, handler, or none Programs that steer turns
App server directly Any transport Full protocol Editors and custom clients

Pick codex exec when a shell is the integration and a status code is enough. Pick the TypeScript SDK when a Node program needs typed events but no mid-turn control. Pick the Python SDK when the program must steer, interrupt, or answer requests. Speak the protocol directly when you build a client with its own interface; generate types with codex app-server generate-ts and start from Chapter 21.

Status at commit 081295be9d. codex exec on an embedded app server: IMPLEMENTED; --remote selects a remote server. --json: IMPLEMENTED; --experimental-json remains as an alias. Headless approval rejection with -32000: IMPLEMENTED. TypeScript SDK on codex exec: IMPLEMENTED. Python SDK on codex app-server over stdio: IMPLEMENTED, with the experimental API on by default. Read in code, tests, and READMEs, not run.

What breaks

Symptom Cause Check
“Not inside a trusted directory…” and exit 1 Not in a Git repository --skip-git-repo-check
Commands keep being denied Approvals rejected headless approval_policy="never" or a reviewer
“Output schema file … is not valid JSON” Bad --output-schema file Validate the JSON
No streaming text in JSONL exec emits completed messages only Use the Python SDK
TypeScript run throws with stderr text codex exec exited nonzero Read the stderr in the error
-o file holds no answer Turn failed or was interrupted Check turn.failed and the status

Code map

What it is Where it lives Identifier
exec entry codex:codex-rs/exec/src/lib.rs run_main
Headless approvals codex:codex-rs/exec/src/lib.rs reject_server_request
Approval warning codex:codex-rs/exec/src/approval_warning.rs warn_if_human_approval
JSONL schema codex:codex-rs/exec/src/exec_events.rs ThreadEvent
JSONL mapping codex:codex-rs/exec/src/event_processor_with_jsonl_output.rs EventProcessorWithJsonOutput
TypeScript process wrapper codex:sdk/typescript/src/exec.ts CodexExec
Python protocol client codex:sdk/python/src/openai_codex/client.py CodexClient
Python approval modes codex:sdk/python/src/openai_codex/_approval_mode.py ApprovalMode

Recall check

Does codex exec use the shared daemon?
No; it embeds an app server in-process unless --remote names a server.

What does exec send when the server asks for a command approval?
A JSON-RPC error with code -32000; the engine then treats the command as denied.

How does the TypeScript SDK continue a thread?
It spawns codex exec --experimental-json again with resume <threadId>.

Why does --json output have no text deltas?
The JSONL processor emits only completed agent messages, not item/agentMessage/delta.

Who decides approvals for a default Python SDK thread?
The auto_review reviewer, because ApprovalMode.auto_review is the default.