2. The Architecture at a Glance

Codex is one Rust workspace that ships as one binary. Every client reaches the engine through one contract, the app server’s JSON-RPC protocol. Behind it, the engine owns conversations, the harness turns the model’s requests into confined actions, and persistence and the model client sit at the edges. Learn the five layers and the one boundary, and every later chapter has a place on the map.

Chapter 1 described what Codex does. This chapter describes how the code is arranged to do it. The arrangement matters because Codex has many front ends, from the terminal to editors to scripts, and they all need the same agent with the same safety rules. The repository solves that with a strict shape: a protocol boundary that every client crosses, an engine below it that knows nothing about terminals or editors, and a set of harness crates that the engine calls to act on the machine.

The chapter first walks the whole-system diagram, then names the five layers and the direction their dependencies point. It then explains three design moves that make the shape work: one binary that acts as several programs, one server that runs in three placements, and one protocol that is the only way in. It ends with the numbers that describe the code base and the costs of these choices.

The picture

Every client reaches the engine through the app server: the terminal UI and codex exec use the app-server client, which runs the server in-process or attaches to a shared local daemon over a Unix socket; other clients speak JSON-RPC to the server directly; the server installs extensions and starts turns on the engine, which calls the model client, the tool harness, the OS sandbox, MCP servers, and persistence.

Read the diagram from the top. The four client boxes are the surfaces. The terminal UI and codex exec live inside the codex binary and talk through the app-server client, which either embeds the app server in the same process or attaches to a shared local daemon over a WebSocket carried on a Unix domain socket (UDS). The TypeScript SDK does not speak the protocol itself; it spawns codex exec and reads its JSON Lines output. The Python SDK speaks JSON-RPC to the app server directly. The editor extension and the desktop app live outside this repository; the code suggests they are clients of the same protocol, since SessionSource defaults to VSCode, but this book cannot show their side. Every arrow into the engine passes through the app server, which calls start_or_steer_turn on a thread. The engine then fans out: to the model client and the model provider on the right, to the tool harness and the operating-system sandbox below, to Model Context Protocol (MCP) servers outside the binary, and to persistence on the left. The green path is the main journey of a turn, which Chapter 3 follows step by step.

Five layers in one workspace

The workspace manifest codex-rs/Cargo.toml lists 175 member crates. They hold 2,515,380 lines of Rust in 6,265 files, a count this book made at the pinned commit; about 1.29 million of those lines sit in files whose path contains “test”. The crates fall into five layers plus a ring of extensions. The table names each layer, a few of its crates, and what it owns.

Layer Representative crates Owns
Shared types codex-protocol, codex-app-server-protocol, codex-config, codex-features Wire types, items, events, config, flags
Engine codex-core, codex-thread-store, codex-rollout, codex-history Threads, sessions, turns, context, compaction
Harness codex-tools, codex-apply-patch, codex-sandboxing, codex-linux-sandbox, codex-execpolicy, codex-network-proxy, codex-exec-server, codex-rmcp-client Tools, edits, confinement, command rules, MCP
Runtime codex-app-server, codex-app-server-transport, codex-app-server-client, codex-app-server-daemon Hosting threads for clients over JSON-RPC
Surfaces codex-cli, codex-tui, codex-exec, plus sdk/typescript and sdk/python Front ends and entry points

Two more groups sit beside the layers. The codex-rs/ext/ directory holds 17 crates: the extension contract codex-extension-api, a shared item-types crate, and 15 extensions built on the contract, such as the goal, memories, web search, and Guardian reviewers (Chapter 19). The model and identity crates, codex-api, codex-model-provider, and codex-login, connect the engine to model providers and to sign-in (Chapters 6 and 25). A further 30 small crates under utils/ hold shared helpers.

Dependencies point at the protocol

The direction of dependencies tells you who knows about whom. codex-protocol, the crate of shared wire types, is a normal dependency of 83 workspace crates, the most of any crate. codex-core, the engine, is a dependency of only 19 crates, most of them the app server, its client, codex exec, and extensions. codex-app-server is a dependency of just three: codex-app-server-client, codex-cli, and codex-exec-server-cli. Only codex-exec and codex-tui take codex-app-server-client as a normal dependency.

The most telling fact is a negative one. codex-tui, which at 576,883 lines is the largest crate in the workspace, slightly larger than codex-core at 569,876, does not depend on codex-core at all. The terminal UI reaches the engine only through codex-app-server-client. A short module in that client crate, legacy_core, still re-exports some engine configuration types, and its doc comment says why: it “exists so clients can remove a direct codex-core dependency while legacy startup/config paths are migrated to RPCs.” The migration is nearly done.

The engine, in turn, points “up” at two crates: codex-app-server-protocol and codex-extension-api. That looks backwards for a layered design, but it is deliberate. The engine emits items and accepts extensions in the shapes those crates define, so the protocol and the extension contract stay the single source of truth for both sides.

One binary, many programs

Codex ships as one native executable named codex. The npm package @openai/codex is only a launcher: its script codex-cli/bin/codex.js maps the platform to one of six packages, such as @openai/codex-darwin-arm64, finds the native binary inside it, and, outside Windows, replaces the Node process with it when Node supports process.execve. Linux builds use the statically linked musl targets, so one Linux binary runs on most distributions.

The single binary plays several roles through a multicall trick that Unix tools such as BusyBox made familiar: the program looks at the name it was started under, argv[0], and at its first argument, and becomes a different tool. The codex-arg0 crate implements it, and every entry point runs it before anything else. The dispatch in codex-rs/arg0/src/lib.rs reads:

pub fn arg0_dispatch() -> Option<Arg0PathEntryGuard> {
    // ...
    if exe_name == CODEX_LINUX_SANDBOX_ARG0 {
        // Safety: [`run_main`] never returns.
        codex_linux_sandbox::run_main();
    } else if exe_name == APPLY_PATCH_ARG0 || exe_name == MISSPELLED_APPLY_PATCH_ARG0 {
        codex_apply_patch::main();
    }

    let argv1 = args.next().unwrap_or_default();
    if argv1 == codex_sandboxing::CODEX_WINDOWS_MXC_ARG1 {
        codex_sandboxing::run_windows_mxc_main();
    }
    #[cfg(unix)]
    if argv1 == CODEX_ARG0_EXEC_HELPER_ARG1 {
        codex_exec_server::run_arg0_exec_helper_main();
    }
    if argv1 == CODEX_FS_HELPER_ARG1 {
        codex_exec_server::run_fs_helper_main();
    }
    // ...
}

Started as codex-linux-sandbox, the binary becomes the Linux sandbox helper. Started as apply_patch or the common misspelling applypatch, it becomes the patch tool. With one of five hidden first arguments it becomes a file-system helper, an exec helper, the patch tool, or one of two Windows sandbox wrappers. To make the names resolvable, prepare_aliases_in_home creates a locked temporary directory under CODEX_HOME/tmp/arg0-<os>, links those names to the running executable, and puts the directory on PATH; Windows gets .bat shims instead of links.

Why go to this trouble? Because the harness often needs to run a small trusted program inside a confined child process. A sandboxed command cannot reach the parent’s memory, so the parent re-executes itself under a helper name and lets the child do the work. One binary means the helper is always present and always the same version as the engine that started it. The cost is some path manipulation at startup, and a rule that this dispatch must run before any other thread starts. The dispatch also loads ~/.codex/.env but drops every key that begins with CODEX_, so a stray file cannot reconfigure Codex itself. It then runs the real main function on a thread with a 16 MiB stack (THREAD_STACK_SIZE_BYTES).

With no subcommand, codex launches the terminal UI; codex exec (alias e) runs headless; codex app-server runs the protocol server; and the remaining subcommands, 29 in all, manage sign-in, MCP servers, plugins, sandboxes, and sessions. Chapter 1 lists the user-facing ones.

One server, three placements

The app server is a library as much as a process. The client crate wraps it in an enum with three variants, defined in codex-rs/app-server-client/src/lib.rs:

pub enum AppServerClient {
    Cloud(CloudClient),
    InProcess(InProcessAppServerClient),
    Remote(RemoteAppServerClient),
}

The InProcess and Remote variants carry the same requests, notifications, and server-to-client requests, so a front end does not change its code when the server moves. The table compares the placements.

Placement Who uses it by default Transport Lifetime
In-process codex exec Tokio channels in one process Ends with the command
Local daemon The terminal UI WebSocket frames over a Unix socket Shared, outlives one window
Remote --remote, remote control WebSocket or Unix socket to another host Managed elsewhere

The Cloud variant is different: it talks to hosted Codex Cloud threads over the gRPC protocol and is selected by the --cloud flag. The open-source repository holds only its client.

The terminal UI’s default surprises many readers. With the daemon_auto_start feature, which is STABLE and on by default, the TUI starts or reuses a shared app-server daemon and attaches to it. It falls back to an embedded in-process server only when an exclusion applies, such as --no-daemon, a --profile, or most -c overrides. The exclusions appear to share one theme: each is a setting that one window needs privately, which a shared daemon could not honor. Chapter 22 walks the decision. codex exec, by contrast, always embeds the server unless you pass --remote.

The in-process path keeps the envelope

An embedded server could have skipped the protocol and called the engine directly. It does not. The module comment in codex-rs/app-server/src/in_process.rs explains that requests travel as typed values, “yet responses still come back through the same JSON-RPC result envelope that MessageProcessor uses for stdio and websocket transports. This keeps in-process behavior aligned with app-server rather than creating a second execution contract.” The cost is a little serialization work. The benefit is that the terminal UI, codex exec, and an editor extension all exercise the same code path, so a fix for one is a fix for all.

The in-process client also shows a concurrency rule that recurs throughout Codex. Commands from the front end go into a bounded channel, which applies backpressure. Events from the server go into an unbounded but ordered channel. A comment beside that channel records why: an earlier bounded event queue “can deadlock a foreground request whose response is behind unread notifications.” If the reader of events is busy waiting for a response, and the response is queued behind events nobody is reading, both sides wait forever. Making only the local event queue unbounded removes the cycle while keeping the rest of the system bounded.

The protocol is the only way in

Every placement speaks the same protocol, which Chapter 21 covers in depth. It is JSON-RPC with one deliberate difference stated at the top of codex-rs/app-server-protocol/src/rpc.rs: “We do not do true JSON-RPC 2.0, as we neither send nor expect the”jsonrpc”: “2.0” field.” One macro table declares 194 client methods (81 marked experimental), 89 server notifications, and 8 server-to-client requests. Five of those 8 requests are how the engine asks a human for something, such as approval to run a command or apply a file change; the other three ask the client to run a dynamic tool, refresh ChatGPT tokens, or generate an attestation. The same table generates Rust types, TypeScript types, and JSON Schema, so the Python SDK’s models and the editor clients’ types come from one definition.

The protocol also carries the conversation model that the rest of this book uses. A client starts a thread (thread/start), starts turns on it (turn/start), and receives a stream of item notifications as the agent works: an item started, deltas while it streams, an item completed, and finally the turn completed. Chapter 4 shows how those items come from the engine’s own event stream.

Inside the engine box

The single “Engine” box in the diagram holds most of the machinery that Parts II and III describe. A short map helps before diving in.

Component Main type What it does Chapter
Thread registry ThreadManager Creates, resumes, forks, and stops threads 4
Thread handle CodexThread Public handle; submits input, reads state 4
Session Session One submission loop per thread; owns history and the active turn 4, 5
Turn loop run_turn Samples the model, runs tools, decides whether to continue 5
Model client ModelClient Builds Responses API requests and parses the stream 6
Context ContextManager Holds history; renders world state and diffs 7, 8
Tools ToolRouter Maps model calls to handlers, approvals, and sandboxes 9 to 12
Recorder RolloutRecorder Appends every item and event to the thread’s log 24

Each Session runs one submission loop: a single task that receives submissions from a bounded queue and emits events on an unbounded one. That is the actor pattern, and it gives each conversation a single owner for its state. Chapter 4 explains it, and Chapter 5 follows the turn loop that the actor starts.

The app server assembles the extensions

The app server, not the engine, decides which extensions a thread gets. codex-rs/app-server/src/extensions.rs builds an ExtensionRegistryBuilder and calls each extension crate’s install function: queue, history notes, the agent message board, goals, git attribution, two Guardian generations, memories, MCP, web search, image generation, and skills. Some are conditional. The multi-environment copy-file extension is installed only when its feature is enabled, and when guardianv3 is off the app server installs only a shadow of the third-generation Guardian, which stays idle unless guardianv3.shadow_enabled and guardianv2, both off by default, are on. Because extensions plug in at the runtime layer, a feature such as goals or memories can ship, change, or be removed without editing the engine’s turn loop. Chapter 19 describes the registry.

The system by the numbers

The table collects the counts that describe the code base at the pinned commit. Counts marked “computed” were made by this book with scripts over the source.

Measure Value Source
Workspace member crates 175 codex-rs/Cargo.toml
Rust source lines (computed) 2,515,380 in 6,265 files Count over codex-rs
Largest crates (computed) codex-tui 576,883 lines; codex-core 569,876 Count over each crate
Crates depending on codex-protocol (computed) 83 Manifests
Crates depending on codex-core (computed) 19 Manifests
App-server client methods 194, of which 81 experimental Protocol macro tables
Server notifications and server requests 89 and 8 Protocol macro tables
Feature flag specs 237 codex-rs/features/src/lib.rs
Commits since the first, 2025-04-16 (computed) 14,582 git log

Design choices and their costs

Four choices give Codex its shape, and each has a price.

The protocol as the only engine boundary. Every surface shares one contract, so the terminal UI, scripts, and editors behave alike, and new clients need no engine changes. The price is an envelope on every in-process call and a long migration, still visible in legacy_core, to move old configuration paths onto RPCs.

One binary that becomes its own helpers. Sandboxed helpers are always present and always version-matched. The price is startup work under CODEX_HOME and platform-specific shims.

One server in three placements. A shared daemon lets several windows share threads and background work, and the same server runs embedded or remote. The price is two startup paths to test and a set of exclusions that send some launches back to an embedded server.

Extensions at the runtime layer. Features enter through a registry rather than through edits to the turn loop. The price is an upward dependency from the engine to the extension contract, and one more indirection to trace when you debug.

Status at commit 081295be9d. daemon_auto_start: STABLE, on by default (the TUI attaches to a shared local daemon). daemon_updates: STABLE, on by default. tui_app_server: REMOVED with default on, meaning the move of the TUI onto the app server is complete and no longer switchable. guardianv3: UNDER DEVELOPMENT, off by default (the app server installs its shadow mode). multi_env_copy_file: UNDER DEVELOPMENT, off by default.

What breaks

Symptom Cause Check
The TUI prints a hint to rerun with --no-daemon The shared daemon failed to start or answer Rerun with --no-daemon; inspect CODEX_HOME/app-server-control/
A -c override seems ignored in one window The launch fell back to an embedded server, or the daemon was reused Look for the daemon exclusion rules in codex-rs/tui/src/daemon_startup.rs
A sandboxed helper fails with “command not found” The arg0 aliases were not created under CODEX_HOME/tmp Check that CODEX_HOME is not inside the system temporary directory
A client receives an error about the experimental API The method is marked experimental and the client did not opt in Send capabilities.experimentalApi in initialize
A variable from ~/.codex/.env has no effect Keys starting with CODEX_ are dropped by design Set it in the real environment instead

Code map

What it is Where Identifier
Workspace members codex:codex-rs/Cargo.toml members
Multicall dispatch codex:codex-rs/arg0/src/lib.rs arg0_dispatch
npm launcher platform table codex:codex-cli/bin/codex.js PLATFORM_PACKAGE_BY_TARGET
Client placements codex:codex-rs/app-server-client/src/lib.rs pub enum AppServerClient
In-process server contract codex:codex-rs/app-server/src/in_process.rs second execution contract
Protocol wire note codex:codex-rs/app-server-protocol/src/rpc.rs neither send nor expect
Extension assembly codex:codex-rs/app-server/src/extensions.rs ExtensionRegistryBuilder
Daemon auto-start flag codex:codex-rs/features/src/lib.rs daemon_auto_start

Recall check

Which crate does the terminal UI depend on to reach the engine?
codex-app-server-client; codex-tui has no dependency on codex-core.

What does the arg0 crate let one binary do?
Act as apply_patch, the Linux sandbox helper, and other helpers, chosen by the start name or a hidden first argument.

What are the three in-process, daemon, and remote placements for, and which does the TUI use by default?
They run the same app server embedded, shared on the machine, or on another host; the TUI attaches to the local daemon by default.

Why is the in-process event channel unbounded when commands are bounded?
A bounded event queue could deadlock a request whose response waits behind unread notifications.

How does the protocol differ from strict JSON-RPC 2.0?
It neither sends nor expects the "jsonrpc": "2.0" field.