Part II. The Engine

The Rust core that owns a conversation: threads, sessions, the turn loop, the model client, the context window, and compaction.

4. Threads, Sessions, and the Protocol

Each thread is a small actor. A ThreadManager builds it, a CodexThread handle fronts it, and one submission_loop task inside its Session takes commands from a bounded queue in order and answers through an unbounded stream of typed events. User input travels beside the protocol, not inside it, so that the caller learns at once whether its message started a turn or steered one.

Chapter 3 followed one message through every layer. This chapter looks at the first layer below the surfaces: how a thread comes to exist, what the CodexThread handle and the Session each own, and how commands and events cross between them.

Clients send Op values wrapped in a Submission, and Codex answers with Event values. A typed item model, TurnItem, rides on top of the events, beside the older per-tool events. The chapter ends with the one input that is deliberately not an Op: the user’s message.

The picture

ThreadManager registers each CodexThread in its registry; the CodexThread holds the Session and the SessionIo endpoints; submissions flow through a bounded channel into one submission_loop task, which drives the Session and its active turn, and events flow back through an unbounded channel to the client and into the rollout.

Start with the client on the left. It asks ThreadManager for a thread and gets back a CodexThread, which the manager also keeps in its ThreadRegistry. Every command goes through the CodexThread onto a bounded submission channel of 512 slots. One tokio task, submission_loop, drains that channel and calls into the Session, which owns the history and at most one ActiveTurn. Events go out on an unbounded channel to whoever reads next_event; each is first written to the rollout (Chapter 24).

ThreadManager: the registry of live threads

ThreadManager is, in its own doc comment, “responsible for creating threads and maintaining them in memory.” It wraps an Arc<ThreadManagerState> so that the multi-agent controller, LocalAgentControl, can hold a weak reference to the state without keeping it alive (see Chapter 20).

ThreadManagerState holds the services every thread shares, and two fields that matter here. threads is a ThreadRegistry, an RwLock around a HashMap<ThreadId, Arc<CodexThread>>. thread_created_tx is a broadcast channel with THREAD_CREATED_CHANNEL_CAPACITY of 1024 slots, which callers read through subscribe_thread_created. Only the agent spawn paths call notify_thread_created; a plain start_thread does not announce itself there.

Starting a thread

ThreadManager::start_thread(StartThreadOptions) calls start_thread_inner, which builds a ThreadSpawnRequest and hands it to ThreadManagerState::spawn_thread. That function boxes the startup future, and its comment gives a compile-time reason: “Erase the startup future here so each caller doesn’t compile its own copy.” Resume, fork, and internal sessions reach the same function, so the startup path exists once. Its inner half prepares configuration, models, MCP servers, and plugins, then calls Session::spawn(SessionSpawnArgs { .. }). That returns an Arc<Session>, the engine state, and a SessionIo, the queue endpoints.

Registration and NewThread

finalize_thread_spawn turns a spawned session into a registered thread. It starts with a check on the first event, in codex-rs/core/src/thread_manager.rs:

let event = io.next_event().await?;
let mut session_configured = match event {
    Event {
        id,
        msg: EventMsg::SessionConfigured(session_configured),
    } if id == INITIAL_SUBMIT_ID => session_configured,
    _ => {
        return Err(CodexErr::SessionConfiguredNotFirstEvent);
    }
};

INITIAL_SUBMIT_ID is the empty string. The session sends SessionConfigured with that ID before any other event, and the manager treats anything else as a broken startup. The event carries the model, the working directory, the rollout path, and the approvals reviewer, so the client learns the thread’s real configuration before it sends a command.

Next, under the registry’s write lock, the function checks that the managed Guardian policy did not change during startup (see Chapter 16). It then looks for a vacant entry for the thread ID. If the entry is vacant, it builds CodexThread::new(session, io, ..), flips a ThreadRegistrationReceipt with registered.store(true, Ordering::Release), and inserts the thread. If the ID is already present, startup fails with “thread {thread_id} is already running”, and the function calls io.shutdown_and_wait() so the orphaned session does not leak.

A successful start returns NewThread with three fields: thread_id, thread: Arc<CodexThread>, and the session_configured event, so no caller has to read it again.

Resume, fork, and shutdown

Resume and fork differ from a new start mainly in the InitialHistory they pass. resume_thread_with_history takes history the caller already loaded. resume_legacy_thread_from_rollout reads a whole rollout file first and then calls the same function.

fork_thread_from_history copies history into a new thread with ForkPersistence::Copied. A ForkSnapshot chooses where to cut. TruncateBeforeNthUserMessage(usize) cuts before the nth user message. Interrupted takes the persisted history as if the source thread had been interrupted now; if that history ends mid-turn, the doc comment says the fork gets “the same <turn_aborted> marker produced by a real interrupt.” A second entry point, fork_prepared_thread, references the parent’s history instead of copying it (Chapter 24).

Removal and shutdown are separate. remove_thread drops the registry entry, though other Arc holders may keep the thread alive. remove_thread_for_client refuses an internal worker with “live internal threads can only be removed by their owner”. shutdown_all_threads_bounded(timeout) sends a shutdown to every thread at once, waits under tokio::time::timeout, and sorts each thread into completed, submit_failed, or timed_out. It removes only the threads that completed, so a caller can retry the rest.

CodexThread and Session

Two halves of one thread

This book uses “thread” for one conversation and “session” for the in-memory engine state that serves it, and the code draws the same line. CodexThread is the public handle; its doc comment calls it the “Conduit for the bidirectional stream of messages that compose a thread”. It holds the session: Arc<Session>, the io: SessionIo, a residency_gate used by multi-agent mail, the session_source, startup metadata, and the rollout_path.

Most CodexThread methods do one of two things. Commands such as submit, start_or_steer_turn, and shutdown_and_wait go through io onto the submission channel. Queries such as has_active_turn and token_usage_info read session directly. Reads stay cheap, and every mutation stays in queue order.

What a Session holds

Session is defined in codex-rs/core/src/session/session.rs. Its doc comment states the central invariant: “A session has at most 1 running task at a time, and can be interrupted by user input.” The fields that carry that invariant are these:

Field Type Role
state Mutex<SessionState> History, rate limits, token usage, settings
active_turn Mutex<Option<ActiveTurn>> The one turn slot (Chapter 5)
input_queue InputQueue Steered input and agent mail
tx_event Sender<Event> The sending end of the event channel
agent_status watch::Sender<AgentStatus> Last known status

SessionState holds the conversation history as a ContextManager (Chapter 7), the latest rate limits and token usage, and the previous turn’s settings. ActiveTurn holds the running task and the turn’s pending approvals and input; Chapter 5 takes it apart with TurnContext.

The submission queue

Submission and SubmissionOp

Session::spawn creates the channels in two lines of codex-rs/core/src/session/mod.rs:

let (tx_sub, rx_sub) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY);
let (tx_event, rx_event) = async_channel::unbounded();

SUBMISSION_CHANNEL_CAPACITY is 512. The submission channel carries Box<Submission>, and a comment on SessionIo explains the box: the bounded channel reserves all its slots at startup, so boxing reserves only a pointer per slot. A Submission has eight fields: the id, the op, turn_extension_init, a W3C trace carrier, parent_turn_id, root_turn_id, a residency_guard, and a message_delivery handle.

The op field is not a protocol Op but a core-only SubmissionOp, defined in codex-rs/core/src/session/submission.rs:

/// Turn input crosses this queue only after the submitting host has resolved its attachments.
pub(crate) enum SubmissionOp {
    Protocol(Box<Op>),
    StopWorker(oneshot::Sender<std::sync::Arc<super::worker_stop::WorkerSlots>>),
    TurnInput {
        request: Box<TurnInputRequest<ResolvedUserInput>>,
        mode: TurnInputMode,
        reply: oneshot::Sender<CodexResult<TurnInputSubmission>>,
    },
}

Protocol wraps any public Op. StopWorker stops a multi-agent worker and returns its execution slots. TurnInput is the user’s message, discussed at the end of the chapter. Submission IDs come from new_submission_id, a UUIDv7; the doc comment notes that the app server exposes turn-creating submission IDs as public turn IDs (Chapter 21) and that some callers rely on the embedded timestamp.

One loop, one order

Session::spawn starts the consumer with tokio::spawn. The comment above it reads “This task will run until Op::Shutdown is received.” The task is submission_loop in codex-rs/core/src/session/handlers.rs. Each pass runs a tokio::select! marked biased, so the branches are polled in written order:

  1. Tree shutdown: the agent tree’s shutdown token fired.
  2. Model catalog updates: apply new model settings and loop.
  3. The next submission from the channel.
  4. pending_work_wake: start a turn for queued work if the session is idle.
  5. Turn-start admission updates from extensions.
  6. Mailbox updates from other agents.

For a submission, the loop dispatches on SubmissionOp, then on Op with one match arm per variant, and awaits the handler before it takes the next submission. That rule gives Codex its ordering guarantee: an Op::ThreadSettings sent before a message applies before that message. The ThreadSettings doc comment names this as the reason it shares the queue: “so app-server can preserve caller order between both kinds of mutation.”

Awaiting each handler has a cost: a slow handler would delay every later command, including Op::Interrupt. So handlers that start long work spawn it; a turn runs on its own tokio task (Chapter 5).

Three exits end the loop. Op::Shutdown calls shutdown, which returns true. A closed channel returns None, and the loop still tears down the runtime and closes persistence, without a ShutdownComplete event. A tree shutdown stops the member and breaks. Any Op the loop does not know falls through _ => false, with the comment “Ignore unknown ops; enum is non_exhaustive to allow extensions.”

shutdown tears down the session runtime, records a turn-count metric, and closes thread persistence with live_thread.shutdown(). Only then does it deliver EventMsg::ShutdownComplete, directly to the event channel. SessionIo::shutdown_and_wait submits Op::Shutdown, tolerates an InternalAgentDied error from a loop that already stopped, and awaits session_loop_termination, a shared future that resolves when the loop task ends.

The event stream

An Event is a two-field envelope:

pub struct Event {
    /// Submission `id` that this event is correlated with.
    pub id: String,
    /// Payload
    pub msg: EventMsg,
}

The id ties each event to the submission that caused it. For events inside a turn it is the turn’s ID, the sub_id of its TurnContext. EventMsg serializes with #[serde(tag = "type", rename_all = "snake_case")], but a per-variant rename keeps the v1 name for a turn start: it appears on the wire as {"type":"task_started", ...}, and turn_started is accepted only as an alias.

Session::send_event is the normal producer. It writes the event to the rollout as RolloutItem::EventMsg and then delivers it. Delivery, in deliver_event_raw, updates the agent_status watch from the event and sends it on tx_event. If the receiver is gone, the send failure is logged at debug level and dropped; the engine does not stop because nobody is listening. On the other side, CodexThread::next_event maps a closed channel to CodexErr::InternalAgentDied.

The event channel is unbounded, so a slow client cannot block the session in the middle of a model stream or a tool. The price is memory: a client that stops reading lets events pile up, and queued_event_count exposes the backlog.

The protocol vocabulary

Op: 36 commands

Op lives in codex-rs/protocol/src/protocol.rs and is #[non_exhaustive]. Its 36 variants fall into six families; the family names are this book’s labels, not the code’s.

Family Count Variants
Interrupt and stop 5 Interrupt, InterruptAgent, InterruptIfNoPendingInput, SuspendTurnAndShutdown, Shutdown
Realtime voice 10 RealtimeConversationStart, ...Attach, ...Audio, ...Close, and six more
Turn and thread settings 5 RecoverTurn, ThreadSettings, TurnSettings, ReplaceDynamicTools, SetThreadMemoryMode
Replies to requests 9 ExecApproval, PatchApproval, CancelPatchApproval, ResolveElicitation, UserInputAnswer, and four more
Task starters 4 Compact, Review, RunUserShellCommand, InterAgentCommunication
Runtime maintenance 3 CleanBackgroundTerminals, RefreshMcpServers, ReloadUserConfig

Several variants carry a oneshot::Sender in their payload: InterruptIfNoPendingInput, RecoverTurn, TurnSettings, and ReplaceDynamicTools, among others. Those are request and reply calls threaded through the queue. A sender cannot be serialized, and Op derives only Debug, so it is an in-process type. The app server translates its JSON-RPC methods into Op values and turn-input calls (Chapter 21); Op itself never crosses a socket.

The replies family closes loops that events open: ExecApprovalRequest parks a oneshot sender in the turn’s state, and the client’s Op::ExecApproval resolves it (Chapter 13).

EventMsg: 86 events

EventMsg has 86 variants. Two of them, PrivateSessionEvent and NetworkApprovalResolved, are marked #[serde(skip)], so they stay in process and never reach the wire. The table groups the rest by family; again the labels are this book’s.

Family Count Examples
Turn lifecycle 8 TurnStarted, TurnComplete, TurnAborted, TurnDiff, TokenCount
Typed items and deltas 8 ItemStarted, ItemCompleted, AgentMessageContentDelta, HookStarted
Older per-tool and message events 20 AgentMessage, UserMessage, ExecCommandBegin, ExecCommandEnd, PatchApplyEnd
Requests to the client 9 ExecApprovalRequest, ApplyPatchApprovalRequest, RequestUserInput, ElicitationRequest
Session and environment 9 SessionConfigured, ShutdownComplete, McpStartupComplete, ThreadQueueChanged
Errors and notices 7 Error, Warning, StreamError, DeprecationNotice
Model and server metadata 7 ModelReroute, SafetyBuffering, RawResponseItem
Multi-agent 11 CollabAgentSpawnBegin, CollabWaitingEnd, SubAgentActivity
Realtime voice 5 RealtimeConversationStarted, RealtimeConversationClosed
Review mode 2 EnteredReviewMode, ExitedReviewMode

Every client must handle the lifecycle family: a turn opens with TurnStarted and ends with one TurnComplete or TurnAborted (Chapter 5).

Typed items and the older events

The protocol grew in two layers. The older layer has one event pair per kind of work: ExecCommandBegin and ExecCommandEnd for a command, McpToolCallBegin and McpToolCallEnd for an MCP call, AgentMessage for a finished reply. The newer layer has one pair for everything: ItemStarted and ItemCompleted, each carrying a TurnItem.

TurnItem, in codex-rs/protocol/src/items.rs, is an enum of 19 variants tagged by type, from UserMessage and AgentMessage through CommandExecution and FileChange to ContextCompaction, plus an Extension variant whose schema an extension owns. ItemStartedEvent carries thread_id, turn_id, the item, and started_at_ms. ItemCompletedEvent carries the same plus completed_at_ms, which defaults through default_item_completed_at_ms so that old rollouts without the field still load.

Codex sends both layers. The bridge is the HasLegacyEvent trait in codex-rs/protocol/src/legacy_events.rs, whose doc comment says it “converts canonical item lifecycle events back into the legacy raw event stream used by compatibility consumers that have not migrated to TurnItem.” Session::send_event calls it after it sends each canonical event:

let show_raw_agent_reasoning = self.show_raw_agent_reasoning();
for legacy in legacy_source.as_legacy_events(show_raw_agent_reasoning) {
    // ...
    let legacy_event = Event {
        id: turn_context.sub_id.clone(),
        msg: legacy,
    };
    self.send_event_raw(legacy_event).await;
}

Only ItemStarted, ItemCompleted, and the three content-delta events have an implementation, and the three delta implementations return nothing. So in practice the fan-out happens on item start and completion. An ItemStarted with a CommandExecution item yields an ExecCommandBegin. An ItemCompleted with that item yields an ExecCommandEnd, unless the command is still InProgress. A completed UserMessage item yields the older UserMessage event, with the text inputs flattened into one message string.

The test user_message_item_is_emitted in codex-rs/core/tests/suite/items.rs shows the order a client sees. It submits a text input and a file image, then asserts three events: ItemStarted with a TurnItem::UserMessage, then ItemCompleted with the same item id and content, then the older EventMsg::UserMessage with message equal to “please inspect sample.txt” and file_ids equal to Some(vec!["file_123"]).

Why user input is not an Op

No Op variant carries a user message. The message goes on the same queue as SubmissionOp::TurnInput, and the reason is the reply. A client that sends a message while a turn runs needs to know whether it started a new turn, joined the running one, or bounced. A fire-and-forget Op could answer only through a later event that the client would have to correlate.

CodexThread::start_or_steer_turn passes TurnInputMode::StartOrSteer. The other modes are StartIfIdle, ContinueIfIdle { expected_previous_turn_id }, and Steer { expected_turn_id }, each with its own entry point. Before the request enters the queue, resolve_client_inputs reads local images and audio; it moves that work onto tokio::task::spawn_blocking only when the input has a LocalImage or LocalAudio. Every mode except Steer also calls ensure_execution_capacity_for_turn_start. Then SessionIo::submit_turn_input does the rest:

let id = new_submission_id();
let (reply_tx, reply_rx) = oneshot::channel();
// ...
self.submit_with_id(Box::new(Submission {
    id,
    op: SubmissionOp::TurnInput {
        request: Box::new(request),
        mode,
        reply: reply_tx,
    },
    // ...
}))
.await?;
reply_rx.await.unwrap_or(Err(CodexErr::InternalAgentDied))

In the loop, the TurnInput arm awaits turn_input::admit and sends its result on the oneshot. The answer is a TurnInputSubmission with four variants. Started { turn_id, root_turn_id } means a new turn exists. Steered { turn_id, root_turn_id } means the input joined the active turn. Accepted covers agent messages handed to native delivery. NotSubmitted { reason } carries one of ten NotSubmittedReason values, such as ServerDraining, NoActiveTurn, ActiveTurnNotSteerable, and EmptyInput.

The doc comment on TurnInputSubmission limits the promise: Started and Steered “do not wait for user-prompt hooks, updating the in-memory model context, rollout persistence, or sampling.” The reply reports a routing decision only, and dropping the waiter does not retract a queued call. Chapter 5 shows what admit does on each branch.

Why this shape

Three patterns carry the design. The actor with a submission queue solves ordering: one task owns dispatch, callers hold cheap SessionIo clones, and at 512 queued submissions submit waits. Its cost is that a slow handler delays every later command. The event stream solves fan-out and replay: because send_event writes each event to the rollout before delivery, a resumed thread can rebuild what a client saw. Typed items solve protocol growth: a new kind of work needs one new TurnItem variant, not a new event pair in every client. Keeping both layers costs duplicate traffic until the older consumers migrate.

Status at commit 081295be9d. ThreadManager, CodexThread, SessionIo, and submission_loop: IMPLEMENTED. Typed items with the HasLegacyEvent fan-out: IMPLEMENTED; both event layers are sent on every turn. Feature::WakeOnAgentMessages (UNDER DEVELOPMENT, off by default) lets agent mail wake an idle session from the loop’s mailbox branch. Read in code, not run.

What breaks

Symptom Cause Check
A call returns InternalAgentDied The loop ended or the oneshot reply was dropped SessionIo::submit_turn_input; has session_loop_termination resolved?
Thread start fails with SessionConfiguredNotFirstEvent Startup emitted another event first finalize_thread_spawn
Start fails with “thread … is already running” The ThreadId is already registered ThreadRegistryState.threads; remove the old entry first
remove_thread_for_client returns an error The thread is an internal worker session_source.is_internal()
Shutdown report lists threads as timed_out A loop did not finish within the timeout shutdown_all_threads_bounded; the thread stays registered
A client sees each command twice in two shapes It handles both items and older events Choose ItemStarted/ItemCompleted or the older pairs, not both
Memory grows while a client is idle Nobody reads the unbounded event channel CodexThread::queued_event_count

Code map

What it is Where it lives Identifier
Thread manager codex:codex-rs/core/src/thread_manager.rs pub struct ThreadManager
Registration codex:codex-rs/core/src/thread_manager.rs async fn finalize_thread_spawn
Thread handle codex:codex-rs/core/src/codex_thread.rs pub struct CodexThread
Queue endpoints codex:codex-rs/core/src/session/mod.rs pub(crate) struct SessionIo
Queue item codex:codex-rs/core/src/session/submission.rs pub(crate) enum SubmissionOp
Dispatcher codex:codex-rs/core/src/session/handlers.rs pub(super) async fn submission_loop
Commands and events codex:codex-rs/protocol/src/protocol.rs pub enum EventMsg
Typed items codex:codex-rs/protocol/src/items.rs pub enum TurnItem

Recall check

What must the first event of a new session be, and why does the manager check it?
SessionConfigured with the empty INITIAL_SUBMIT_ID; it carries the thread’s real configuration, and anything else means startup broke.

Why can a slow Op handler hurt interrupts?
submission_loop awaits each handler before the next submission, so long work must leave the loop or it delays Op::Interrupt.

Why is the submission channel bounded and the event channel unbounded?
The bound gives back-pressure on callers; an unbounded event channel keeps a slow client from blocking the engine inside a turn.

What does Codex send when a command item completes?
ItemCompleted with a CommandExecution item, then the older ExecCommandEnd produced by HasLegacyEvent.

Why is user input a SubmissionOp::TurnInput and not an Op?
It carries a oneshot reply that tells the caller whether the input started a turn, steered one, or was not submitted.