3. One Turn, End to End

A turn is one request and everything Codex does to answer it. It crosses every layer of the system: the client sends turn/start, the session’s actor spawns a task, the turn loop samples the model, tool calls run inside the sandbox while the model is still streaming, an approval may pause one of them, and the loop samples again until the model stops asking for tools. Follow one turn and you have seen every part of Codex once.

Chapter 2 drew the map. This chapter walks it. The example is a request that every coding agent meets daily: you type “Run the parser tests and fix the failure” into the terminal UI and press Enter. Over the next minute Codex streams a plan, runs a test command, reads the failure, edits a file, runs the tests again, and reports back. From your seat that is one exchange. Inside Codex it is one turn with several sampling requests, several tool calls, and dozens of events.

The walk uses the preset that the approval-presets crate labels “Default” (identifier auto): approvals “on request” and a sandbox that lets Codex write inside the workspace. It also assumes that you review approvals yourself, with approvals_reviewer = "user" in your configuration. Without that line, and with the built-in OpenAI provider, Codex would hand approvals for this preset to the Guardian model reviewer instead, a path Chapter 16 follows. The walk has eight phases, from keystroke to the bytes left on disk. Each phase names the functions that do the work, so you can open the code beside the text. The chapters of Parts II to IV take each phase apart in detail.

The picture

One turn: the terminal UI sends turn/start to the app server, which calls start_or_steer_turn on the session; the session spawns the turn loop, which sends request 1 to the model and receives an exec_command call; the tool harness runs it in the sandbox, with an optional approval detour through the app server to the user; the loop sends request 2 with the output, receives the final message, and the app server reports turn/completed.

Time runs downward. The green arrows are the main path: the request enters at the top left and reaches the turn loop in three hops. The loop then talks to the model twice. Between the two model requests, the tool harness runs a command and returns its output as a function_call_output item. The purple dashed arrows are the approval detour. They appear only when the policy asks a person to decide, and they travel the same route as everything else: from the engine through the app server to the client and back. The last two arrows close the turn and tell the client it is done.

Phase 1: the keystroke becomes a request

The terminal UI’s composer holds your text until you press Enter. The UI then sends one app-server request, turn/start, through its AppServerClient to the shared local daemon (Chapter 2 explains why the daemon is the default). The parameters are camel-cased JSON; trimmed to the fields that matter here, they look like this:

{
  "id": 42,
  "method": "turn/start",
  "params": {
    "threadId": "019a5c1e-...",
    "input": [{ "type": "text", "text": "Run the parser tests and fix the failure" }]
  }
}

There is no "jsonrpc" field, by design. Inside the app server, MessageProcessor routes the TurnStart request to the turn processor, whose turn_start method converts the parameters into a core TurnInputRequest and calls CodexThread::start_or_steer_turn on the thread. The name is honest: the same call either starts a new turn or steers one that is already running. The engine answers with a TurnInputSubmission, usually Started with the new turn’s ID, and the app server replies to the client with a TurnStartResponse whose turn carries that ID and the status inProgress.

Phase 2: the session admits the turn

Every thread is served by one Session, and every session runs one submission loop. The loop is an actor: a single Tokio task that owns the session’s mutable state and receives work through a queue. SessionIo::submit_turn_input wraps your input in a submission with a fresh UUID version 7 identifier, attaches a one-shot reply channel, and sends it into a bounded queue whose capacity is SUBMISSION_CHANNEL_CAPACITY, 512. User input is deliberately not one of the 36 Op variants; it travels as its own submission kind so that the reply can say whether the input started a turn or joined one.

submission_loop in codex-rs/core/src/session/handlers.rs hands the submission to turn_input::admit. Admission first tries to steer: if a turn were already running, the input would join its pending-input queue and the running turn would pick it up at its next step. Here no turn is running, so admission asks the session to start one, and the session calls spawn_task with a RegularTask. The first thing spawn_task does is make room:

pub async fn spawn_task<T: SessionTask>(
    // ...
) {
    self.abort_all_tasks(TurnAbortReason::Replaced).await;
    // ...
}

A session runs at most one task at a time, so starting a task always replaces whatever ran before. The new task gets a cancellation token, the session records it as the active turn, and the task future starts on its own Tokio task so the submission loop stays free to receive an interrupt. The loop answers the one-shot channel with Started { turn_id }. The task’s first act, in emit_turn_started, is to emit TurnStarted, which the app server forwards to the client as the turn/started notification. Chapter 4 describes the actor, and Chapter 5 the task.

Phase 3: the prompt is assembled

The regular task calls run_turn in codex-rs/core/src/session/turn.rs, the function that holds the turn loop. Before it asks the model anything, it does three things.

First, it checks the token budget. If the conversation already fills too much of the model’s context window, run_pre_sampling_compact replaces the history with a summary before the new message lands (Chapter 8). Second, it brings the model’s view of the world up to date. Codex keeps the instructions, the permissions, the AGENTS.md files, and the environment as named sections; on a new thread it renders them in full, and on later turns it sends only what changed, so that the start of the prompt stays byte-identical across requests (Chapter 7). Third, it records your message: it runs any hooks that watch user input, writes the item to the thread’s history, and emits ItemStarted and ItemCompleted events for a user-message item.

Then build_prompt assembles the request. Codex speaks only the OpenAI Responses API. It sends the base instructions not in an instructions field but as a developer message at the front of the input array, followed by the history, with the tool specifications beside it. It sets store: false, so the provider keeps no conversation state between requests, and over a plain HTTP connection it resends the whole history every time. Over a WebSocket connection, when the new request exactly extends the previous one, Codex sends only the new items and a previous_response_id. Chapter 6 explains both modes and why prompt caching makes the resend affordable.

Phase 4: the model streams

run_sampling_request calls try_run_sampling_request, which opens a streaming response and consumes a sequence of ResponseEvent values. Text deltas become item/agentMessage/delta notifications, which the terminal UI renders line by line. Reasoning summaries stream the same way. When the model finishes an output item, handle_output_item_done decides what it is.

In this turn, the model’s first complete item is a function call:

{"type": "function_call", "name": "exec_command", "call_id": "call_1",
 "arguments": "{\"cmd\":\"cargo test -p parser\",\"yield_time_ms\":10000}"}

exec_command is the shell tool at this commit; Chapter 10 describes it and its partner write_stdin. Whether the model emits this item directly depends on its tool mode. In the bundled model catalog at the pinned commit, 13 of the 14 models set tool_mode to code_mode_only; only gpt-5.5 calls tools directly. A code-mode model instead emits a free-form exec call whose JavaScript runs await tools.exec_command({cmd: "cargo test -p parser"}) in a V8 isolate inside a separate host process, and the host sends that nested call back to core (Chapter 12). From the tool router on, the nested call takes the same path as the direct one, with the same hooks, approvals, and sandbox, so this walk follows the direct form. The tool router’s build_tool_call turns the item into a ToolCall, the call item is recorded in history at once, and the session starts the tool through ToolCallRuntime::handle_tool_call. It does not wait for the stream to end. The tool future joins a set of in-flight calls and starts running while the model may still be producing more items. The turn loop also marks that it needs a follow-up request, because the model will want to see the command’s output.

Phase 5: the harness acts

The tool call now crosses the harness, which Part III describes. Because exec_command is safe to run beside other read-mostly tools, it takes the read side of an admission lock that the turn loop creates for each sampling request; an apply_patch call would take the write side and run alone. The registry runs PreToolUse hooks, which may rewrite or block the call, and hands it to the exec_command handler. The handler parses the arguments, wraps the command for your login shell, such as ["/bin/zsh", "-lc", "cargo test -p parser"], and checks whether the command is secretly an apply_patch invocation, which would take the patch path instead.

Next comes the safety decision, made by the tool orchestrator. The command does not match any execpolicy rule, it is not on the short list of dangerous commands, and it asks for no extra permissions. Under on-request approvals with a restricted sandbox, the decision for such a command is to run it without asking, as the code in codex-rs/core/src/exec_policy.rs records:

FileSystemSandboxKind::Restricted => {
    // In restricted sandboxes, do not prompt for non-escalated,
    // non-dangerous commands; let the sandbox enforce
    // restrictions without a user prompt.
    if sandbox_permissions.requests_sandbox_override() {
        Decision::Prompt
    } else {
        Decision::Allow
    }
}

So the orchestrator selects the platform sandbox (Seatbelt on macOS, bubblewrap with seccomp on Linux, a restricted token on Windows; see Chapter 14) and starts the command in a unified-exec session. Output streams into a buffer that keeps the head and the tail. After the yield time, or when the process exits, the handler returns a result whose text begins with a short header: a chunk ID, the wall time, and either the exit code or a session ID that the model can use to keep talking to a still-running process.

The approval detour

Suppose the tests needed the network, which the default sandbox blocks. The model would retry with "sandbox_permissions": "require_escalated" and a one-line justification. Now the decision is Prompt, and the call takes the purple path in the diagram. Deciders are consulted in order: PermissionRequest hooks first, then the Guardian reviewer when the effective reviewer is auto_review, and otherwise you (Chapter 13). A Guardian verdict is final: when the Guardian decides, no prompt reaches you. Because this walk set the reviewer to user, the request comes to you.

To ask you, the tool calls Session::request_command_approval. That function creates a one-shot channel, parks the sender as a pending approval in the turn’s state, emits EventMsg::ExecApprovalRequest, and awaits the receiver. The tool future is now suspended, and so is the turn, because the loop waits for its in-flight tools. In the app server, bespoke_event_handling.rs turns the event into one of the eight server-to-client requests, item/commandExecution/requestApproval. The terminal UI shows its approval overlay. For a command, the default choices are to approve it once, to approve it and save a prefix rule so that matching commands run without asking (when the model proposed one), or to abort; a network prompt also offers approval for the rest of the session. When you approve the command once, the UI answers the request:

{"id": 8, "result": {"decision": "accept"}}

The app server submits Op::ExecApproval to the session; the submission loop finds the pending approval and sends the decision down the one-shot channel; and the tool future wakes up and runs the command, now outside the sandbox. The whole detour is ordinary message passing. No thread blocks, and an interrupt can still cancel the turn while it waits.

Phase 6: the loop continues

When the model’s stream reports Completed, the turn loop records the token usage and calls drain_in_flight. That function awaits each pending tool future and records its output in the order the model made the calls, not the order they finished, so the history stays deterministic. The output becomes a function_call_output item with the same call_id as the call. A TokenCount event tells the client how full the context window is.

The loop now asks whether to sample again. It does, because a tool ran and the model has not seen its output. Before it samples, it checks the token budget once more and compacts if needed. The second request carries the whole conversation, now including the failing test output. This time the model reads the failure, calls apply_patch to fix the parser (Chapter 11), which takes the write lock and runs alone, and calls exec_command again to rerun the tests. Each tool call is another pass through phases 4 to 6. The turn’s diff tracker records every file the patch touched, so the client can show one unified diff for the whole turn.

Phase 7: the turn ends

Eventually the model answers in plain text: the tests pass, and here is what changed. That message arrives as an agent-message item, which produces ItemCompleted and needs no tool. With no tool calls outstanding and no new input waiting, the loop has nothing left to do. It runs any Stop hooks, considers one last compaction, leaves the loop, and returns the last agent message.

The task then finishes in a fixed order. It flushes the rollout, records metrics, emits TurnDiff if files changed, emits TurnComplete, clears the active turn, marks the thread idle, and flushes again. The app server forwards turn/completed, and the terminal UI returns the composer to you. If you had typed a follow-up while the turn was finishing, the session would notice the pending input in on_task_finished and run the loop once more within the same turn, which is why a late message is never lost.

Phase 8: what stayed behind

Every phase left a trace. Each recorded item went to the thread’s rollout as a response_item line, and each persisted event as an event_msg line, in a JSON Lines file under CODEX_HOME/sessions/. Not every event is kept: streaming deltas and transient approval prompts are dropped by a single persistence policy, because the completed items already contain their content. The rollout is an append-only log, and it is the source of truth when you resume the thread tomorrow: Codex replays it to rebuild the model’s history. Chapter 24 describes the format, the SQLite index beside it, and resume and fork.

What can change the path

The walk above is the common case. The table lists the main variations and where each is covered.

Event during a turn What Codex does Chapter
You type while the turn runs start_or_steer_turn steers: the input joins the running turn 5
You press Escape Op::Interrupt; the task’s token is cancelled and the turn aborts 5
The context window fills Compaction replaces history with a summary, then the loop continues 8
The model calls several tools at once Read-safe tools run in parallel; edits run alone 9
A sandboxed command is denied The output reports the denial; under on-request the shell command is not retried unsandboxed 13
The approval is declined The tool returns a rejection, and the model decides what to do next 13

Status at commit 081295be9d. The path in this chapter is IMPLEMENTED for every client that uses the app server. The auto preset (“Default”) pairs on-request approvals with a workspace-write permission profile. When approvals_reviewer is unset, the reviewer resolves to auto_review (the Guardian) if the provider is the built-in OpenAI provider, the guardian_approval flag is on (STABLE, on by default), the permission profile is workspace-write, and approvals are on-request or granular; otherwise it resolves to the user. Sandbox mechanisms are PLATFORM-SPECIFIC (Chapter 14).

What breaks

Symptom Cause Check
A turn never ends and the UI shows an approval prompt elsewhere A pending approval is waiting for a decision Answer or dismiss the prompt; in codex exec approvals are rejected automatically
Your follow-up message starts no new turn It steered the running turn instead Check whether the turn/start response carries the running turn’s ID
A command fails with a permission error inside the workspace The path is a protected location or outside the writable roots Read the permission profile (Chapter 13); try the command with codex sandbox
The model repeats a command after a denial The denial came back as ordinary tool output Check the approval policy and whether escalation is allowed
The rollout lacks the streamed text you saw Deltas are not persisted; the completed item is Search the rollout for the response_item line instead

Code map

What it is Where Identifier
Turn start in the app server codex:codex-rs/app-server/src/request_processors/turn_processor.rs start_or_steer_turn
Submission queue capacity codex:codex-rs/core/src/session/mod.rs SUBMISSION_CHANNEL_CAPACITY
The submission loop codex:codex-rs/core/src/session/handlers.rs submission_loop
Turn admission codex:codex-rs/core/src/session/turn_input.rs async fn admit
Task replacement codex:codex-rs/core/src/tasks/mod.rs TurnAbortReason::Replaced
The turn loop codex:codex-rs/core/src/session/turn.rs pub(crate) async fn run_turn
Tool call from a stream item codex:codex-rs/core/src/stream_events_utils.rs handle_output_item_done
Approval to client request codex:codex-rs/app-server/src/bespoke_event_handling.rs EventMsg::ExecApprovalRequest

Recall check

Which call does the app server make on the engine for turn/start?
CodexThread::start_or_steer_turn, which either starts a new turn or steers the running one.

Why does spawn_task call abort_all_tasks first?
A session runs at most one task, so a new task always replaces the old one with reason Replaced.

When does a tool call start running?
As soon as its item completes in the stream, before the model’s response ends.

Under the Default preset, does an ordinary test command need approval?
No; a non-dangerous command that asks for no extra permissions runs in the sandbox without a prompt.

How does an approval pause the turn without blocking a thread?
The tool awaits a one-shot channel whose sender waits in the turn state until Op::ExecApproval arrives.