跪拜 Guibai
← Back to the summary

Codex's Architecture: From a Single Model Call to a Recoverable Runtime System

Analysis target: openai/codex main
Tech stack: Rust (edition 2024)
Analysis method: Codatlas source-anchored modeling
External reading: Deep Dive into the Codex Agent Loop

Preface

Many people's first reaction to Codex is "isn't this just a CLI?"
But if you read it purely by modules, you get a pile of names: app-server, ThreadManager, Session, ContextManager, ToolInvocation, RolloutRecorder. You still don't know why they had to look this way.

So this article doesn't walk through modules; it walks through the complete path of one conversation:

User input -> Session admission -> Context projection -> Model request -> Tool execution
        -> Result write-back -> History persistence -> memory background task -> Restart recovery

At every step, I answer the same question:

Where does a naive Agent break down at this step, and what boundary must it grow?

This is the architectural roadmap feeling Codex gives me: not feature accumulation, but boundaries being nailed down step by step.

Conclusion first

Codex is not "a CLI stuffed with prompt templates." It's a local Coding Agent runtime system:

Entry carrier -> app-server JSON-RPC -> ThreadManager -> CodexThread / Session
        -> Context Projection -> Prompt Builder -> Model Client
        -> Tool / MCP / Code Mode Boundary -> ThreadStore / RolloutRecorder

Each layer in this chain is not a "handy module"; it answers a concrete problem:

Naive Agent's problem Codex's architectural answer
Multiple entry points scatter logic CLI/TUI/app-server reuse the JSON-RPC semantic boundary
A single request can't carry a continuous conversation thread/session/turn become resources with lifecycles
Message arrays are not model input ContextManager does explicit projection
Tool calls spiral out of control native/MCP/Code Mode are unified into ToolInvocation
Tool results become bare text Results are written back with call context
Restart loses context JSONL rollout is the source of truth, SQLite is the index
End of conversation is not the end memory settles asynchronously in two phases
Background tasks can't recurse infinitely memory agent is explicitly capability-limited

One-sentence summary:

Codex's roadmap is not "from CLI to a big tool," but "from a single model call to a runtime system with boundaries, an audit log, and recoverability."

Global Chain

Look at the whole task chain first. Suggested reading starts from User / Client at the bottom left, all the way to Rollout and Memory Pipeline on the right, then returns to ThreadManager along the recovery path.

2026-11-29-codex-main-architecture-01.png

There are two main lines in this diagram:

  1. Execution main line: input -> session -> projection -> model -> tool -> result write-back.
  2. Lifecycle main line: result -> rollout -> memory -> recovery -> next session.

If you only see the first line, you'd think Codex is a call orchestrator. Add the second line, and you see it's a runtime system.

Step 0: Starting from a Naive Agent

The simplest Coding Agent has only three steps:

User inputs prompt -> call model -> return result

This model has no problems. It's simple enough and fast enough. The real problem is that it only holds under "single conversation, single entry, no side effects, no recovery."

Once you actually want it to do work, four problems appear:

  1. Users may come in from CLI, TUI, IDE, Web.
  2. Conversations aren't a single request; they have history, interruptions, and recovery.
  3. The model has to call tools, which read/write files, execute commands, and access external systems.
  4. After the process exits, users want to continue from the previous context.

Each time you answer one problem, Codex grows a new boundary. Steps 1 through 8 below are this "growth" path.

Step 1: Where Input Comes From

The first layer of upgrade is entry points.

Codex doesn't stuff all logic into a CLI. It has three primary carriers:

The key one is app-server. It's not an ordinary HTTP server; it's a JSON-RPC semantic boundary.

MessageProcessor in codex-rs/app-server/src/message_processor.rs does three things:

  1. Receives typed JSON-RPC requests;
  2. Composes process-scoped ThreadStore;
  3. Attaches runtime services like models refresh worker, turn cost worker, and model catalog.

This means the client isn't "randomly calling a function" but hitting a constrained protocol surface.

The architectural value of the entry layer is:

Carriers can be replaced, but protocol semantics must not drift.

If CLI, TUI, and IDE each built their own logic, the Agent would quickly show "one set of behavior at the entry, another set at the core." app-server nails this layer down.

Step 2: Input Isn't a Single Call, It's a Turn in a Thread

The second layer of upgrade is conversation resource-ification.

A JSON-RPC request doesn't equal a conversation. Codex splits conversations into three layers:

thread -> session -> turn

ThreadManager in codex-rs/core/src/thread_manager.rs manages thread lifecycles and composes MCP manager, plugins manager, skills service, environment manager, and model catalog.

CodexThread in codex-rs/core/src/codex_thread.rs holds:

TurnAdmissionState has three states:

Idle       no current turn slot
Pending    slot reserved, execution not yet admitted
Admitted   execution admitted until finishing

This isn't an implementation detail; it's an architectural judgment:

A turn isn't a function call, but an execution unit that needs admission.

With this layer, continuous conversations, concurrent requests, and interrupted recovery don't trample each other.

Step 3: The Model Doesn't See History; It Sees a Projection

The third layer of upgrade is context.

In a naive Agent, what gets sent to the model is just a "message array." But in Codex's source there's a clear chain:

canonical history -> runtime history -> model input

These three are not the same thing.

The key boundary is in codex-rs/core/src/context_manager/history.rs:

ContextManager::for_prompt

It is responsible for:

  1. Normalizing history;
  2. Stripping unsupported image/audio based on the model's input_modalities;
  3. Replacing unavailable file image / tool audio with text placeholders;
  4. Handling file audio projection.

Then build_prompt in codex-rs/core/src/session/turn.rs assembles the Prompt:

Field Meaning
input Session history and current input
tools Model-visible tool declarations
parallel_tool_calls Whether parallel tool calls are allowed
base_instructions Base instructions
output_schema Output schema
prompt_cache_ttl Prompt cache TTL

This shows two things:

  1. The model doesn't see the source of truth itself, but a projection of it.
  2. Tool declarations and base instructions are also controlled by context policy; they aren't fixed.

This layer solves the most easily spiraling problem in long conversations:

What's recorded on disk is what happened; what the model sees is what is allowed this turn.

Step 4: The Model Says It Wants to Call a Tool; Who Governs That?

The fourth layer of upgrade is tool governance.

In a naive Agent, a tool call is just "the model outputs a function name, then execute it." That works in small demos, but not in a local Coding Agent.

The reason is simple: tools can read/write files, execute commands, access MCP, and enter Code Mode. They aren't ordinary functions; they're side-effect entry points.

ToolInvocation in codex-rs/core/src/tools/context.rs is the unified call context. ToolCallSource can express:

The benefits of a unified boundary:

  1. Approval and permission checks have a single place.
  2. Tool outputs can uniformly enter history.
  3. Tools from different sources don't each invent their own call protocol.
  4. Plugins, MCP, and Code Mode can't bypass the runtime.

So the architectural judgment here is:

Tools aren't capabilities; they're governed side-effect boundaries.

Step 5: How Do Tool Results Come Back?

The fifth layer of upgrade is result write-back.

Many Agents only care about "did the tool execute successfully," but not how the tool result enters the next round of model context.

Codex doesn't stuff stdout bare into the message list. In codex-rs/core/src/tools/executed_tool_calls/request_metadata.rs there's:

ExecutedToolCalls::attach_to_prompt

It attaches tool request metadata back to the prompt input, letting the model know:

This solves a very practical problem in long sessions:

Tool output without call context makes the model misread where the result came from.

This is also another reason why "what the model sees" and "what actually happened" must stay separate. Tool results aren't isolated text; they're projections with context.

Step 6: What Happened This Turn Must Be Recorded

The sixth layer of upgrade is persistence.

At this point, the execution chain is complete:

Input -> session -> projection -> model -> tool -> result write-back

But what about after process exit?

Codex's answer is to write "what happened" as canonical history.

LocalThreadStore in codex-rs/thread-store/src/local/mod.rs splits into two APIs:

RolloutRecorder in codex-rs/rollout/src/recorder.rs writes JSONL rollout through a writer task:

The architectural judgment here is clear:

Separate the source of truth from the index.

JSONL records what happened; SQLite only does queryable metadata index. This prevents "query efficiency" from polluting canonical history.

Step 7: End of Turn Is Not the End

The seventh layer of upgrade is memory.

If the system only went to Step 6, it could recover sessions but not accumulate experience.

Codex's memory isn't "summarize immediately after every turn." Its entry point is:

codex-rs/app-server/src/request_processors/turn_processor.rs

Once a user turn starts successfully, it calls:

codex-rs/memories/write/src/start.rs
start_memories_startup_task

Then it enters a two-phase process:

Phase 1: Rollout Extraction

codex-rs/memories/write/src/phase1.rs does:

  1. Claims bounded rollout jobs from the state DB;
  2. Reads recent rollout items;
  3. Filters memory-relevant response items;
  4. Builds an extraction prompt;
  5. Generates raw_memory, rollout_summary, and rollout_slug;
  6. Writes back to the state DB.

Phase 2: Global Consolidation

codex-rs/memories/write/src/phase2.rs does:

  1. Gets global jobs and workspace lock;
  2. Reads selected stage-1 outputs;
  3. Syncs raw_memories.md and rollout_summaries/;
  4. Generates workspace diff based on git baseline;
  5. Starts a consolidation agent when there's a diff.

This consolidation agent has strict limits:

This layer solves the safety problem of self-improving systems:

A background agent cannot recursively amplify its own capabilities.

So memory isn't "remember a bit more"; it's:

  1. Reading goes through prompt context;
  2. Writing is asynchronous, bounded, and retryable;
  3. Background agents are explicitly privilege-limited.

Step 8: How to Recover After Restart

The last layer is recovery.

This closes the loop on Step 2: sessions are resources, so they must be recoverable.

The recovery chain is roughly:

SQLite selected rollout path -> JSONL replay -> thread id -> resumed history

load_rollout_items behaves as:

  1. Reads rollout lines one by one;
  2. Skips empty lines;
  3. JSON parse failures warn and count parse_errors;
  4. The first SessionMeta determines the canonical thread id;
  5. Later SessionMeta from forked copies doesn't change the thread id;
  6. Returns items, thread id, and parse errors.

The value of this layer:

Recovery doesn't depend on "memory being alive," but on a replayable ledger.

At this point, Codex is truly a runtime system: entry, session, projection, tools, side effects, history, memory, and recovery all have boundaries.

Codex's Architectural Roadmap

Compress Steps 0 through 8 into one diagram, and you get Codex's architectural path:

2026-11-29-codex-main-architecture-02.png

This diagram isn't an official product roadmap; it's an architectural roadmap reverse-engineered from source structure. Each step corresponds to a place where a naive Agent would collapse:

Step Naive Agent's problem Codex's solution
1 Multi-entry logic drift app-server unifies protocol semantics
2 Conversation can't be continuously governed thread/session/turn layering
3 Message arrays don't equal model input ContextManager projection
4 Tool side effects spiral ToolInvocation unified boundary
5 Tool output loses context attach_to_prompt writes back metadata
6 Restart loses context JSONL rollout as source of truth
7 Experience can't settle memory two-phase task
8 Recovery semantics vague replay + selected path + reconcile

This is the source of the "roadmap feeling": each step is forced to grow, not stacked from a feature checklist.

Transferable Design Judgments

From Codex's chain, the six things I think are most worth taking away.

1. Define the Source of Truth First, Then the UI

UI state should never be the source of truth. Codex puts canonical history in rollout, metadata in SQLite, and leaves UI to projection.

2. Conversations Are Resources, Not Message Lists

The thread/session/turn layering gives concurrency, recovery, and shutdown clear ownership. Without it, an Agent can only hold on with an in-memory message array.

3. Model Input Is a Projection, Not a Ledger

for_prompt is the explicit boundary. Media normalization, unsupported media stripping, and placeholder replacement are centralized here, not scattered across provider adapters.

4. Tools Are Side-Effect Boundaries, Not Function Calls

native/MCP/Code Mode enter ToolInvocation uniformly, so approval, permissions, and result write-back have a single place.

5. Tool Results Must Be Written Back with Context

attach_to_prompt ensures the model knows which call the output corresponds to. In long sessions, this matters more than "stuff in an extra output."

6. Background Tasks Must Be Privilege-Limited

The memory consolidation agent doesn't generate memory, doesn't read memory, has no MCP, no network, and no normal workspace. This is key to preventing recursive amplification.

Summary

Codex's architectural path can be compressed into one sentence:

From a single model call, it grows into a local runtime system with entry boundaries, session lifecycle, context projection, tool governance, source of truth, and recovery semantics.

If you read by modules, you'll see many names.
If you read by a single conversation, you'll see each step solving a problem a naive Agent inevitably hits.

This is the roadmap feeling Codex gives me: not more features, but clearer boundaries.

Additionally, this is a Codex analysis series. The reason for the analysis is that Codex hasn't been performing great recently, and we wanted to see what changed. The full series plan:

  1. Codex Architecture Analysis: How a Conversation Grows into a Runtime System
  2. Codex Architecture Analysis (Memory): The Prompt-Memory Loop, What Really Happens Around a Conversation
  3. (Preview: Storage)
  4. (Preview: Contrast with recently analyzed AI Agents)

Source Anchor List

Module Source location Responsibility
MessageProcessor codex-rs/app-server/src/message_processor.rs JSON-RPC boundary & runtime composition
ThreadManager codex-rs/core/src/thread_manager.rs thread lifecycle & agent tree
CodexThread codex-rs/core/src/codex_thread.rs session runtime & turn admission
ContextManager::for_prompt codex-rs/core/src/context_manager/history.rs Session history to model input projection
build_prompt codex-rs/core/src/session/turn.rs Assembles structured Prompt
ModelClient / ModelClientSession codex-rs/core/src/client.rs provider seam & turn-scoped transport
ToolInvocation codex-rs/core/src/tools/context.rs native/MCP/Code Mode tool call context
ExecutedToolCalls::attach_to_prompt codex-rs/core/src/tools/executed_tool_calls/request_metadata.rs Attach tool metadata back to prompt
LocalThreadStore codex-rs/thread-store/src/local/mod.rs local thread storage
RolloutRecorder codex-rs/rollout/src/recorder.rs JSONL writer & recovery
start_memories_startup_task codex-rs/memories/write/src/start.rs Starts two-phase memory pipeline
phase1.rs / phase2.rs codex-rs/memories/write/src/ rollout extraction & global consolidation