Part VIII. Reference

The design patterns that recur across the code base, and a glossary of the terms this book uses.

27. Design Patterns in Codex

Codex solves the same few problems again and again: who owns a piece of state, how layers talk, how features plug in, how actions are allowed, what is kept and sent, and how the code changes without breaking users. Each problem has a recurring answer in the code, and each answer has a cost the maintainers accepted. Knowing the patterns lets you predict how an unfamiliar part of Codex works before you open it.

The earlier chapters met these patterns one at a time, each inside its own subsystem. This chapter collects them. It groups them into six families, names the places in the code where each one appears, states the problem it solves in Codex specifically, and states its cost. The costs matter as much as the benefits: a pattern is a trade, and Codex’s choices make sense only when you can see what was given up.

The chapter closes with advice for anyone building an agent of their own, drawn from what the code shows works.

The picture

Codex’s recurring designs fall into six families: concurrency (actor with mailbox, cancellation tree, reader-writer admission), boundaries (protocol-only boundary, server-to-client requests), extensibility (strategy traits, contributor registry, progressive disclosure), safety (sandbox first and ask later, chain of reviewers, capability narrowing), data and context (event-sourced rollout, append-only prompt prefix, head and tail capture), and evolution (staged feature table, dual event surface).

Read the tree as a checklist of questions. Concurrency asks who owns mutable state. Boundaries ask how two layers agree on a contract. Extensibility asks how a feature joins without edits to the code it joins. Safety asks who decides whether an action runs. Data and context ask what is kept, what is sent to the model, and what is thrown away. Evolution asks how a fast-moving code base changes without breaking the people who use it. Each leaf is a pattern this chapter explains.

Concurrency: one owner per piece of state

Actor with a mailbox

Every session runs one submission loop, a Tokio task that owns the session’s dispatch order and receives work through a bounded channel of capacity SUBMISSION_CHANNEL_CAPACITY (512). Callers hold cheap clones of the sending side and never touch the state directly. The rollout recorder uses the same shape: one writer task, fed by a bounded channel of 256 commands, owns the file. So does the app-server client, whose worker sits between a bounded command channel and an ordered event channel.

The problem the actor solves is ordering. A turn’s input, an interrupt, an approval decision, and a shutdown can all arrive at once; one task processing them in order removes whole classes of races. The cost is that a slow handler delays everything behind it. Codex pays it down with a rule visible throughout session/handlers.rs: a handler does not wait for long work itself. It spawns the work onto its own task and returns, so the loop stays free to receive the next Interrupt (Chapters 3 and 4).

A variant appears where the caller needs an answer: request and reply over a one-shot channel inside the queue. User input travels as a submission carrying a one-shot sender, so the caller learns whether its input started a turn or steered one. The cost is two channel hops per input, which is negligible next to a model call.

A cancellation tree

spawn_task creates a CancellationToken for each task, and codex-rs/core/src/tasks/mod.rs derives child tokens from it with child_token(): one for the turn, and further children for each sampling request and each tool call. Cancelling the root reaches all of them. An abort then waits 100 ms for the task to wind down and record what it can before it hard-aborts the future.

The problem solved is clean interruption of deeply nested asynchronous work: a running test command, a streaming model response, and a pending approval all stop when you press Escape. The cost is discipline. Every await point must observe its token, and the grace period is a compromise between losing partial history and leaving the user waiting (Chapter 5).

Reader-writer admission for tools

codex-rs/core/src/tools/parallel.rs holds one RwLock<()> per ToolCallRuntime, which the turn loop creates for each sampling request. A tool that is safe to run beside others, such as exec_command or view_image, takes the read side. A tool that mutates shared state, such as apply_patch or update_plan, takes the write side and runs alone. The lock guards no data; it only admits.

This lets the model fan out read-only work while keeping edits strictly sequential, without a scheduler. The cost is that one exclusive tool serializes the whole batch around it, and the classification lives in each handler’s supports_parallel_tool_calls (Chapter 9). Outputs are still recorded in call order through an ordered set of futures, so history stays deterministic even when tools finish out of order.

Boundaries: one contract per seam

The protocol as the only boundary

Every surface reaches the engine through the app-server protocol, even when the server runs in the same process. The in-process client keeps the JSON-RPC result envelope “rather than creating a second execution contract,” as codex-rs/app-server/src/in_process.rs puts it. One macro table declares every method, notification, and server request, and generates Rust types, TypeScript types, and JSON Schema from the same rows.

The problem solved is drift between clients. The terminal UI, codex exec, editors, and SDKs exercise one code path, so a fix for one is a fix for all. The cost is an envelope on every in-process call, a large macro, and a long migration of older configuration paths onto RPCs (Chapters 2 and 21).

Server-to-client requests for decisions

When the engine needs a person, it does not block. It sends one of eight server-to-client requests, such as item/commandExecution/requestApproval, and parks a one-shot sender in the turn’s state until the answer arrives as an Op. Elicitations from MCP servers and user-input requests work the same way. The pattern turns a blocking question into two messages, so a UI can show it, a headless client can reject it, and an interrupt can cancel it. The cost falls on clients: every client must answer or reject these requests, and codex exec cancels elicitations and rejects the other requests with error -32000 (Chapters 13 and 23).

Extensibility: adding without editing

Strategy traits

The engine names its variation points as traits. SessionTask lets a regular turn, a review, a compaction, and a user shell command share one lifecycle. ToolHandler lets each tool plug into the same router, orchestrator, and hooks. Compaction chooses between remote and local strategies by provider capability. The cost is type erasure and boxed futures, plus several code paths to keep in step when the shared lifecycle changes.

A contributor registry

Features such as goals, memories, web search, image generation, and the Guardian reviewers enter through ExtensionRegistryBuilder, which the app server fills by calling each extension crate’s install function. An extension contributes tools, prompt fragments, MCP servers, or lifecycle callbacks, and keeps private per-session or per-turn state in typed extension data. Core never names the features. The cost is implicit ordering: rules such as “first result wins” or “later setting replaces” live in the registry, and state keyed by type is invisible to ordinary debugging (Chapter 19).

One rule keeps the registry auditable: observers may watch tool calls, but only hooks may block or rewrite them. Mutation has one door.

Progressive disclosure

The model’s attention is the scarcest resource in the system, so Codex shows a catalog first and the details only on demand. Skills appear in the prompt as names and short descriptions; a skill’s full body loads only when it is selected. The catalog itself has a budget, computed in codex-rs/ext/skills/src/render.rs:

where is the token budget for skill metadata, is the model’s context window in tokens, and is SKILL_METADATA_CONTEXT_WINDOW_PERCENT, which is 2. A configured limit replaces the computed one, capped at 10,000 tokens, and with no known window the budget falls back to a character count. For a 272,000-token window, tokens. Deferred tools in tool search follow the same idea. The cost is that the model must notice and select what it needs, and descriptions are truncated at 1,024 characters (Chapter 18).

Safety: deciding what may run

Sandbox first, ask later

Codex does not ask before every command. It runs ordinary commands inside the operating system’s sandbox without a prompt and asks only when a command wants more than the sandbox allows, or matches a dangerous pattern. The code in codex-rs/core/src/exec_policy.rs says it plainly for restricted sandboxes: “do not prompt for non-escalated, non-dangerous commands; let the sandbox enforce restrictions without a user prompt.”

The problem solved is prompt fatigue: a user who approves fifty commands a session stops reading them. The sandbox becomes the real boundary and the prompt becomes rare and meaningful. The cost is reliance on the platform sandbox, and a denial detector that is heuristic, so a failure unrelated to the sandbox can look like one (Chapters 13 and 14).

A chain of reviewers

When an action does need a decision, deciders are consulted in a fixed order: PermissionRequest hooks, then the Guardian model reviewer if the effective approvals_reviewer is auto_review (the default for the built-in OpenAI provider with a workspace-write profile, on-request or granular approvals, and the guardian_approval flag on), and otherwise the user. A managed rule can force a person. This is the chain-of-responsibility pattern, and it lets an enterprise enforce policy through hooks, lets a user cut prompts with an automated reviewer, and still keeps a person in the loop where policy demands one.

The chain carries a subtle rule, fresh authority per escalation: a Guardian approval of a sandboxed command does not authorize an unsandboxed retry of it, while a user or hook approval does. The orchestrator computes this as retry_preapproved in codex-rs/core/src/tools/orchestrator.rs. The cost is three code paths per decision and special cases that must be tested together (Chapters 13 and 16).

Capability narrowing

Anything Codex starts on your behalf gets at most your authority. A child agent inherits its parent’s sandbox and approval policy through apply_spawn_agent_runtime_overrides, and an agent role can switch features off but never on. A project’s own config cannot set the model provider, base URL, or telemetry keys, and repository hooks do not run until you trust them, with trust tied to a hash of the hook’s definition. The network proxy fails closed on traffic it cannot attribute to a call. The cost is friction: roles cannot grant a tool the parent lacks, and the first run of a project hook needs a trust step (Chapters 18, 20, and 25).

Data and context: what is kept and what is sent

An event-sourced rollout

The thread’s durable record is an append-only JSON Lines log of items and events. A single policy function, persisted_rollout_item in codex-rs/rollout/src/policy.rs, decides what is kept, and a SQLite projection beside the log makes paginated history fast. Resume replays the log to rebuild the model’s history. The pattern gives Codex an audit trail, crash safety, and fork and resume for free. The costs are two representations to keep consistent, a migration path between formats, and a rule that every new event variant must be classified, which an exhaustive match enforces at compile time (Chapter 24).

An append-only prompt prefix

Prompt caching rewards a request whose beginning is byte-identical to the last one. Codex therefore never edits the start of the conversation to reflect a change. It renders instructions, permissions, AGENTS.md, and the environment in full once, then appends small diff messages when they change. Over WebSocket it goes further and sends only the new items with a previous_response_id, but only when get_incremental_items proves the new request extends the previous one exactly. The cost is that stale context stays in history until compaction rewrites it (Chapters 6 to 8).

Head and tail capture

A command can print gigabytes. HeadTailBuffer in codex-rs/utils/head-tail-buffer keeps the beginning and the end of the output within a fixed byte budget and drops the middle, because the start of a build log names the command and the end names the error. Long-lived terminal sessions are kept in a store with a cap and least-recently-used eviction that protects the most recent ones. The cost is that the middle of the output is gone for good, and a busy agent can lose an old background process (Chapter 10).

Evolution: changing without breaking

A staged feature table

Every feature flag lives in one reviewed table with a stage and a default: 237 specs at the pinned commit. A feature moves from UNDER DEVELOPMENT through EXPERIMENTAL to STABLE, and a retired flag stays as REMOVED so that old configuration files still parse. The pattern lets unfinished work ship dark and lets users opt in from a menu. The cost is a table that keeps 52 dead entries for compatibility (Chapter 25).

A dual event surface

When Codex introduced typed items, it did not switch every client at once. Each ItemStarted and ItemCompleted is still re-sent as the legacy event the item replaces, so old clients keep working while new ones read items. Forward-compatible enums follow the same thinking: serde aliases keep old configuration names loading, and unknown variants degrade instead of failing. The costs are duplicate events on the wire, a rollout policy that must keep only one form per history mode, and dead aliases that stay in the types (Chapters 4 and 24).

Failing over once

Two smaller patterns protect sessions from flaky infrastructure. A retry policy table, retry_policy on the error type in codex-rs/protocol/src/error.rs, classifies every error into one of four variants: never retried, retried with backoff, retried when the server directs, or fall back to HTTP. And a one-way transport downgrade, force_http_fallback in codex-rs/core/src/client.rs, moves a session from WebSocket to HTTP when retries run out or an error demands it, and never moves it back. Stability wins over the faster transport (Chapter 6).

Lessons for your own agent

The patterns above suggest six rules for anyone building an agent, each grounded in what Codex does.

  1. Give each conversation one owner. An actor with a mailbox removes races between input, interrupts, and approvals.
  2. Make waiting a message, not a block. Approvals and user questions should be requests the client answers, so they can be cancelled and automated.
  3. Confine first, ask second. A real sandbox lets you ask rarely, and a rare prompt is a prompt people read.
  4. Keep the prompt prefix stable. Append changes instead of editing history, and caching will pay for the resend.
  5. Log everything as events. An append-only record gives you resume, fork, audit, and debugging from one mechanism.
  6. Stage your features. A single table of flags with stages lets you ship unfinished work safely and retire it cleanly.

What breaks

Symptom Pattern involved Check
An interrupt takes seconds to land Actor with a mailbox: a handler is awaiting long work Look for a handler in session/handlers.rs that does not spawn
Tool calls run one at a time Reader-writer admission: an exclusive tool is in the batch Check which tools return supports_parallel_tool_calls false
Prompt cache hit rate drops after a settings change Append-only prefix: a full re-render replaced a diff Compare consecutive requests’ leading items
A Guardian-approved command is asked about again Fresh authority per escalation Expected: the unsandboxed retry needs a user or hook approval
A skill never appears to the model Progressive disclosure budget exceeded Look for “Exceeded skills context budget” in the logs

Code map

What it is Where Identifier
Session mailbox capacity codex:codex-rs/core/src/session/mod.rs SUBMISSION_CHANNEL_CAPACITY
Cancellation tree codex:codex-rs/core/src/tasks/mod.rs child_token()
Tool admission lock codex:codex-rs/core/src/tools/parallel.rs RwLock<()>
Retry preapproval rule codex:codex-rs/core/src/tools/orchestrator.rs retry_preapproved
Persistence policy codex:codex-rs/rollout/src/policy.rs persisted_rollout_item
Skills catalog budget codex:codex-rs/ext/skills/src/render.rs SKILL_METADATA_CONTEXT_WINDOW_PERCENT
Head and tail buffer codex:codex-rs/utils/head-tail-buffer/src/lib.rs HeadTailBuffer
Transport downgrade codex:codex-rs/core/src/client.rs force_http_fallback

Recall check

What problem does the session’s actor solve, and what does it cost?
It orders concurrent inputs without races; a slow handler delays everything, so handlers spawn long work.

Why does a tool lock guard no data?
It only admits: read-safe tools share it, mutating tools hold it alone.

What is fresh authority per escalation?
A Guardian approval of a sandboxed command does not authorize its unsandboxed retry; a user or hook approval does.

Why does Codex append diffs instead of editing the prompt’s start?
To keep the cached prefix byte-identical so prompt caching keeps working.

How large is the skills catalog budget for a 272,000-token window?
5,440 tokens, 2 percent of the window.