Part VI. The Runtime and Its Surfaces

The app server that hosts threads, and the terminal, headless, and SDK clients that talk to it.

21. The App Server and Its Protocol

Every Codex client reaches the engine through one runtime, codex app-server, and one protocol: JSON-RPC messages without the version field, declared once in a macro table that also generates TypeScript and JSON Schema. A client starts threads and turns with requests, follows progress through notifications, and answers approvals when the server sends requests of its own.

Chapter 4 described the engine’s own protocol: Op submissions go into a CodexThread, and Event values come out. No user-facing client speaks that protocol directly. The terminal user interface (TUI), codex exec, the Python software development kit (SDK), and remote clients all speak a second protocol to a second component, the app server, which hosts codex-core and translates between the two. The codex-tui crate does not even depend on codex-core; it reaches the engine only through codex-app-server-client.

This chapter explains that runtime and its wire contract: why one server serves every client, its transports, the message shapes, the macro table behind 194 client methods, the lifecycle a client observes, approvals as server-to-client requests, schema export, and experimental gating. Chapters 22 and 23 show the clients built on it.

The picture

Clients reach the app server through one of several transports; MessageProcessor checks the handshake and experimental gate, request processors queue work per thread and call codex-core, and engine events come back through an event mapper and an outgoing router that filters what each connection may see.

Read the loop clockwise from the left. A client sends a JSON-RPC message over its transport: the TUI through a Unix socket or in-process channels, codex exec through channels, the Python SDK through stdin and stdout. MessageProcessor rejects anything sent before initialize and anything experimental the client did not opt into, then turns the message into a typed ClientRequest. A request processor queues it behind earlier work on the same thread and calls into codex-core, for a turn through CodexThread::start_or_steer_turn. Engine events flow back through the event mapper, which emits version 2 notifications and server requests, and the outgoing router writes each message only to connections allowed to see it. The dashed line is remote control: the app server dials out to a relay instead of listening.

One runtime for every client

The seam

The app server is the only crate that turns the engine into a service. At the pinned commit only three workspace crates depend on codex-app-server: codex-app-server-client, codex-cli, and codex-exec-server-cli. The TUI and codex exec both use codex-app-server-client, whose AppServerClient enum has three variants: InProcess, Remote, and Cloud. A client written against that enum gets the same requests, notifications, and server requests whether the server runs in its own process, in a background daemon, or on another machine.

This is the ports-and-adapters pattern applied to a whole product. The protocol is the port, and each transport is an adapter. The engine knows a client only by the clientInfo it declares at initialize. A new client needs no engine code, and an engine change reaches every client at once.

The public record explains how the design got here. OpenAI’s engineering post “Unlocking the Codex harness: how we built the App Server” (February 4, 2026) describes an earlier attempt to expose Codex as a Model Context Protocol (MCP) server, which proved hard to fit to the VS Code extension. The first JSON-RPC protocol then mirrored the TUI’s own event loop, and the post called moving the TUI onto the app server future work. At this commit that move is done: the tui_app_server feature flag is REMOVED, and its doc comment says the TUI “now always uses the app-server implementation.”

What the seam costs

The protocol boundary is not free, even in one process. codex_app_server::in_process runs the same MessageProcessor on Tokio tasks and replaces sockets with bounded channels. Its module comment states the trade-off directly: requests are typed ClientRequest values, yet responses “still come back through the same JSON-RPC result envelope,” which “keeps in-process behavior aligned with app-server rather than creating a second execution contract.” The TUI and codex exec pay a serialization step on every response to keep one contract.

The second trade-off is memory. InProcessAppServerClient::start keeps its command queue bounded but makes the event queue unbounded, because a bounded one “can deadlock a foreground request whose response is behind unread notifications.” Memory can grow if a consumer stalls, but a response never waits behind a notification nobody reads.

Transports

AppServerTransport::from_listen_url parses the --listen flag of codex app-server. The default is stdio://, and --stdio is shorthand for it. The table compares the listeners with the two transports that need no listener.

Endpoint Variant Framing Typical user
stdio:// Stdio One JSON object per line Python SDK, spawned hosts
unix:// or unix://PATH UnixSocket WebSocket frames over the socket TUI to the local daemon
ws://IP:PORT WebSocket WebSocket over TCP Remote clients
off Off No local listener Remote control only
none in-process Typed values in channels Embedded TUI, codex exec

A bare unix:// resolves to CODEX_HOME/app-server-control/app-server-control.sock. The Unix socket carries WebSocket frames rather than raw lines; the client side in codex-app-server-remote-client performs a WebSocket handshake against the placeholder URL ws://localhost/rpc over the socket. The TCP WebSocket listener also serves GET /readyz and GET /healthz, rejects any HTTP request that carries an Origin header (a defense against browser pages), and accepts --ws-auth with either a capability token or a signed JSON Web Token (JWT) bearer token. With off, startup fails with “no transport configured; use –listen or enable remote control” unless remote control is on.

The local daemon

The daemon is not a separate program. codex-app-server-daemon spawns the same binary as codex app-server --listen unix://, adding --remote-control when that setting is on, and keeps daemon.pid, daemon.lock, and settings.json in CODEX_HOME/app-server-daemon. It waits up to 30 seconds for readiness on macOS and Linux and 10 seconds elsewhere, polling every 50 milliseconds; a comment notes that a Linux cold start from a rotational disk “can take more than ten seconds.” codex app-server daemon exposes start, stop, restart, and version, plus subcommands for bootstrap, updates, and remote control. Chapter 22 shows how the TUI starts and attaches to it.

Remote control

Remote control inverts the connection. Instead of listening, the app server opens an outbound WebSocket to a relay. normalize_remote_control_url joins wham/remote/control/server onto the configured base URL, and a test fixture in the same file shows the production form wss://chatgpt.com/backend-api/wham/remote/control/server. Remote clients reach the server through that relay and enter the same router with origin ConnectionOrigin::RemoteControl. How the relay authorizes them is not visible in this repository.

Backpressure

Every transport feeds one bounded queue of CHANNEL_CAPACITY, which is 128 events. When it is full, enqueue_incoming_message treats requests and other messages differently. A request is answered at once with error code -32001 and the message “Server overloaded; retry later.” A response or notification waits for space. The asymmetry matches who can recover: a sender can retry a request, but a lost approval response would leave the engine waiting.

The wire format

JSON-RPC without the version field

The protocol borrows JSON-RPC 2.0 shapes and drops one field. The module comment in codex-rs/app-server-protocol/src/rpc.rs is two lines long:

//! We do not do true JSON-RPC 2.0, as we neither send nor expect the
//! "jsonrpc": "2.0" field.
// ...
#[serde(untagged)]
pub enum JSONRPCMessage {
    Request(JSONRPCRequest),
    Notification(JSONRPCNotification),
    Response(JSONRPCResponse),
    Error(JSONRPCError),
}

The enum is untagged, so serde tells the four kinds apart by their fields. A request has id, method, and optional params. A notification has method and no id. A response has id and result. An error has id and error with code, message, and optional data. The code gives no reason for dropping the version field. The likely one, and it is an inference, is that the field never varies: it adds bytes to every line and tells the receiver nothing the shape does not already say. The App Server post describes the result as a lighter variant of JSON-RPC. The constant JSONRPC_VERSION still exists in the file, unused. A client that sends the field is accepted, because these structs do not deny unknown fields, but it never sees the field in replies.

RequestId is untagged too: a string or a 64-bit integer. The Python SDK sends uuid4 strings; the Rust test clients send integers. The server numbers its own requests from an AtomicI64 that starts at 0. Ids in the two directions never collide in meaning, because a response always answers a request that went the other way. JSONRPCRequest also has an optional trace field that carries World Wide Web Consortium (W3C) trace context, so a client can stitch its spans to the server’s.

A real exchange

The stdio test in codex-rs/app-server/tests/suite/v2/connection_handling_stdio_tests.rs spawns the binary and writes this line to its stdin:

{"id": 1, "method": "initialize", "params": {"clientInfo": {"name": "stdio-stderr-test", "version": "1"}}}

It then reads one line from stdout and asserts that it parses as JSONRPCMessage::Response. A client normally follows with the notification {"method": "initialized"}. The server does not depend on it: MessageProcessor::process_notification only logs client notifications. What matters is initialize itself. Any other request before it gets “Not initialized”, and a second initialize gets “Already initialized”.

The initialize parameters also carry capabilities. The test serialize_initialize_capabilities in common.rs shows experimentalApi, requestAttestation, and optOutNotificationMethods, which names notifications the connection never wants, such as item/agentMessage/delta.

One table declares the protocol

The macro

Every method lives in one file, codex-rs/app-server-protocol/src/protocol/common.rs, as a row inside a declarative macro call. The turn/start row reads:

TurnStart => "turn/start" {
    params: v2::TurnStartParams,
    inspect_params: true,
    serialization: thread_id(params.thread_id),
    response: v2::TurnStartResponse,
},

From each row, client_request_definitions! generates a variant of ClientRequest tagged by method, with the id field renamed from request_id to id; the matching ClientResponse variant; method_name(); and serialization_scope(). Three sibling macros do the same for server requests, server notifications, and client notifications. One row is the single source for the Rust enum, the wire name, the TypeScript type, and the JSON Schema. This is the registry pattern implemented at compile time: adding a method means adding one row.

The serialization field decides ordering. MessageProcessor reads serialization_scope() for each request. A request with a scope, such as Thread { thread_id }, joins a queue keyed by that scope in RequestSerializationQueues and runs only after earlier requests with the same key. A request with no scope runs at once on its own Tokio task. So two turn/start requests on one thread run in order, while a file search runs beside them.

What the table declares

A count over the four tables gives 194 client request methods, 8 server requests with slash names, 89 server notifications, and 1 client notification, initialized. Of the 194 client methods, 81 carry #[experimental(...)]; so do 26 of the 89 notifications. The next table groups the client methods by the first segment of their wire name (counted by script).

Family Methods Experimental Examples
thread/* 61 34 thread/start, thread/resume, thread/fork
account/* 19 6 account/read, account/login/start
plugin/* 13 1 plugin/list, plugin/install
fs/* 9 0 fs/readFile, fs/watch
project/*, remoteControl/* 7 each 7 each project/list, remoteControl/enable
turn/* 4 1 turn/start, turn/steer, turn/interrupt
32 other families 74 25 config/read, skills/list, review/start

The notifications split the same way: thread/* has 34, item/* 14, and turn/* 5. The server request table also keeps two version 1 variants, ApplyPatchApproval and ExecCommandApproval, without slash names; they serialize as applyPatchApproval and execCommandApproval. The version 2 event path sends the slash-named requests instead, but both the TUI and codex exec still match the old variants. Their parameter types, like InitializeParams, live in protocol/v1; most other types live in 50 files under protocol/v2.

Threads, turns, and items

The lifecycle a client sees

A client’s view of the engine has three nested objects. A thread is a conversation. A turn is one user input and the work that answers it. An item is a typed unit inside a turn; the generated ThreadItem type has 19 variants, including userMessage, agentMessage, reasoning, commandExecution, fileChange, mcpToolCall, and contextCompaction. Each object has a start notification and an end notification, and items have deltas in between.

  1. The client sends thread/start and receives ThreadStartResponse with the thread, the resolved model, and the effective approval and sandbox settings. The server also broadcasts thread/started.
  2. The client sends turn/start with threadId and an input array, for example [{"type": "text", "text": "run python"}]. The response arrives at once and holds a Turn with status inProgress and no items.
  3. The server sends turn/started, then item/started, any deltas such as item/agentMessage/delta (with threadId, turnId, itemId, and delta), and item/completed for each item.
  4. The server sends turn/completed with the final Turn, whose status is completed, interrupted, or failed.

The early response is a design choice. turn_start_inner calls CodexThread::start_or_steer_turn and returns as soon as the engine accepts the input, so no request stays pending for the minutes a turn can take. The same call also steers: if a turn is already running, the engine adds the input to it and returns TurnInputSubmission::Steered instead of Started. A draining server returns a dedicated error. Chapter 5 shows what the engine does with that input.

Notifications are small and typed. The test serialize_thread_status_changed_notification in common.rs pins this shape:

{"method": "thread/status/changed", "params": {"threadId": "thr_123", "status": {"type": "idle"}}}

Output schemas and other turn options

TurnStartParams carries per-turn overrides: cwd, approvalPolicy, sandboxPolicy, model, and others, each documented as applying “for this turn and subsequent turns.” Its outputSchema field becomes the core field final_output_json_schema, which the model client sends as a JSON Schema text format named codex_output_schema. Chapter 23 shows codex exec --output-schema using it.

Approvals are server requests

Eight requests the server can send

When the engine needs a decision it cannot make alone, the app server sends a JSON-RPC request to the client and waits for the response. The eight slash-named server requests are below.

Method Asks the client to
item/commandExecution/requestApproval Approve a shell command
item/fileChange/requestApproval Approve a patch
item/permissions/requestApproval Grant extra permissions
item/tool/requestUserInput Answer a question from a tool
mcpServer/elicitation/request Answer an MCP server’s form
item/tool/call Run a client-side dynamic tool
account/chatgptAuthTokens/refresh Refresh host-managed tokens
attestation/generate Produce an attestation header

Inverting the direction keeps the engine’s pause visible on the wire. OutgoingMessageSender::send_request assigns the next server id, stores a one-shot channel under it, and writes the request; MessageProcessor::process_response completes the channel when the answer arrives. This is request correlation by id, the mechanism JSON-RPC already uses in the other direction.

A round trip

The test turn_start_exec_approval_toggle_v2 in codex-rs/app-server/tests/suite/v2/turn_start.rs drives a full approval. A mock model asks for an escalated shell command with call id call1, and the configured approval policy is on-request. The test asserts this order. The lines below show the wire shapes with identifiers elided; the id values are illustrative.

-> {"id": 2, "method": "turn/start", "params": {"threadId": "...", "input": [...]}}
<- {"id": 2, "result": {"turn": {"id": "...", "status": "inProgress", "items": []}}}
<- {"id": 0, "method": "item/commandExecution/requestApproval",
    "params": {"threadId": "...", "turnId": "...", "itemId": "call1", "command": "..."}}
-> {"id": 0, "result": {"decision": "accept"}}
<- {"method": "serverRequest/resolved", "params": {"threadId": "...", "requestId": 0}}
<- {"method": "item/completed", "params": {"item": {"type": "commandExecution", "id": "call1"}}}
<- {"method": "turn/completed", "params": {"threadId": "...", "turn": {"status": "completed"}}}

The test checks that serverRequest/resolved arrives before turn/completed and that the command item completes with exit code 0. It also checks a redaction detail: the approval request shows the command as the model wrote it, bearer token included, while the completed item shows [REDACTED_SECRET] in its place. The serialization test serialize_server_response pins the decision spelling: {"decision": "acceptForSession"}.

From decision to engine

on_command_execution_request_approval_response in bespoke_event_handling.rs maps the client’s answer onto the engine’s ReviewDecision. The six decisions are accept, acceptForSession, acceptWithExecpolicyAmendment, applyNetworkPolicyAmendment, decline, and cancel. decline becomes a denial and the turn continues; cancel becomes ReviewDecision::Abort and also interrupts the turn. The handler then submits Op::ExecApproval to the CodexThread. If the client answers with a JSON-RPC error or an unparseable result, the handler calls fail_exec_approval, and the engine treats the command as denied with the reason “approval request failed.” That failure path is what codex exec relies on when it rejects approvals (see Chapter 23). The policy that decides when to ask belongs to Chapter 13.

Schemas, gating, and versions

Schema export

codex app-server generate-ts --out DIR writes TypeScript bindings, and generate-json-schema --out DIR writes a JSON Schema bundle; both accept --experimental to include experimental methods and fields. The help text marks both commands “[experimental]”. The repository checks in the output under app-server-protocol/schema/: 95 top-level TypeScript files, 712 under v2/, and bundles such as codex_app_server_protocol.v2.schemas.json. The Python SDK generates its pydantic models from that bundle.

The export path has a twist. In non-test builds, the JsonSchema and TS derives resolve to no-op macros from codex_app_server_protocol_noop_macros; the real schemars and ts_rs derives run only under cfg(test). The shipping binary therefore cannot compute schemas. Instead, precomputed_exports.rs embeds two zstd-compressed snapshots with include_bytes!, one stable and one experimental, and the generate commands unpack them. The no-op crate’s doc comment gives the reason: normal builds keep the annotations readable but avoid “generating implementations that cannot be reached at runtime.” Tests in schema_fixtures_tests.rs, such as experimental_precomputed_exports_match_generated, regenerate the exports with the real derives and fail if they differ from the snapshots or the checked-in files.

Experimental gating

A client opts into experimental surface with capabilities.experimentalApi: true at initialize. The gate then works in three places:

  1. Requests. dispatch_initialized_client_request asks the request for its experimental_reason() and, without the capability, rejects it with “<reason> requires experimentalApi capability”. Rows marked inspect_params: true gate individual fields, so a stable thread/start with one experimental field is still refused.
  2. Notifications. should_skip_notification_for_connection drops experimental notifications for connections without the capability, and drops any method the client listed in optOutNotificationMethods.
  3. Server requests. filter_outgoing_message_for_connection calls strip_experimental_fields on command approval requests, which today clears only additionalPermissions. A TODO in the source calls the per-field stripping a stopgap.

A comment in initialize_processor.rs warns that the capability is per connection, which behaves oddly when two clients share a thread and only one opted in. The TUI, codex exec, and the Python SDK all opt in.

Versions

The protocol has no version number. InitializeResponse returns userAgent, codexHome, platformFamily, and platformOs, and nothing that negotiates a revision. Compatibility rests on the v1 and v2 type namespaces, the experimental gate, and exported schemas a client can pin. The App Server post says the IDE and desktop clients pin a tested binary, which fits that model. The daemon adds its own check, comparing a launching client’s feature flags with the running server’s (see Chapter 22).

Status at commit 081295be9d. App server as the only client path for the TUI and codex exec: IMPLEMENTED (tui_app_server is REMOVED, default true). Experimental methods: 81 of 194 client methods and 26 of 89 notifications, gated by experimentalApi. generate-ts and generate-json-schema: labeled “[experimental]” in help. remote_control feature flag: REMOVED, default false; remote control is now a daemon and CLI setting. daemon_updates: STABLE, on by default. Read in code and tests, not run.

What breaks

Symptom Cause Check
Every request returns “Not initialized” Client skipped initialize Send initialize first, once
“… requires experimentalApi capability” Experimental method or field without opt-in capabilities.experimentalApi
A notification never arrives Experimental, or listed in optOutNotificationMethods should_skip_notification_for_connection
Error -32001 “Server overloaded” Incoming queue of 128 full Retry the request with backoff
Browser page cannot open ws:// Listener rejects any Origin header reject_requests_with_origin_header
Approval answered, command still denied Result did not parse as a decision fail_exec_approval path
Generated types miss a method Exported without --experimental Rerun with --experimental

Code map

What it is Where it lives Identifier
Wire message types codex:codex-rs/app-server-protocol/src/rpc.rs JSONRPCMessage
Method table macro codex:codex-rs/app-server-protocol/src/protocol/common.rs client_request_definitions
Listen URL parsing codex:codex-rs/app-server-transport/src/transport/mod.rs from_listen_url
Overload reply codex:codex-rs/app-server-transport/src/transport/mod.rs OVERLOADED_ERROR_CODE
Initialize and gate codex:codex-rs/app-server/src/message_processor.rs dispatch_initialized_client_request
Turn start handler codex:codex-rs/app-server/src/request_processors/turn_processor.rs turn_start_inner
Approval response mapping codex:codex-rs/app-server/src/bespoke_event_handling.rs on_command_execution_request_approval_response
Precomputed schemas codex:codex-rs/app-server-protocol/src/precomputed_exports.rs STABLE_EXPORTS

Recall check

Why does a turn/start response arrive before the turn finishes?
turn_start_inner returns once the engine accepts the input; the work streams as notifications.

What happens when the incoming queue is full?
Requests get error -32001 at once; responses and notifications wait for space.

How does the server keep two requests on one thread in order?
Each row declares a serialization scope, and requests with the same key share a queue.

How does the shipping binary export schemas when its derives are no-ops?
It unpacks zstd snapshots embedded at build time, which a test keeps in sync with the code.

What does the engine do if a client answers an approval with an error?
fail_exec_approval denies the command with “approval request failed,” and the turn continues.