Codex CLI: The Architecture Behind Terminal Agents
Outline
- 0:00 Title and source guarantee
- 0:30 The wrong mental model
- 0:59 Multiple front doors
- 1:43 Thread, turn, and item
- 2:06 Items are the audit trail
- 2:29 Session as the live boundary
- 3:12 Configuration snapshot
- 3:37 Config as debug evidence
- 4:02 The turn loop
- 4:32 Tool result becomes new context
- 5:02 Prompt assembly
- 5:40 Responses stream
- 6:22 Tool calls force continuation
- 7:03 Tool router and registry
- 7:30 Dispatch is not side effects
- 7:57 Tool exposure plan
- 8:41 Shell execution path
- 9:05 CWD changes the command
- 9:29 Apply patch special case
- 10:10 Process and output limits
- 10:48 Approval policy
- 11:16 Ambiguity suspends the turn
- 11:44 Platform sandbox reality
- 12:17 Command policy and patch policy
- 13:01 Project instructions
- 13:27 Scoped context beats context landfill
- 13:52 Skills and plugins
- 14:35 App-server and IDEs
- 15:06 Codex as an MCP server
- 15:44 Thread persistence
- 16:07 History as a flight recorder
- 16:30 Context compaction
- 17:06 Memories
- 17:43 Failure modes
- 18:06 Recovery is part of the runtime
- 18:29 Rebuild order, part one
- 18:52 Fake tools before real power
- 19:14 Rebuild order, part two
- 19:50 Rebuild order, part three
- 20:26 Closing source reminder
- 20:51 Boundaries make agents real
Transcript
0:00 Imagine you ask Codex to clean build files, and 10 seconds later the plan is drifting toward deleting half your repo. Right. That is why the terminal prompt is the least interesting part. Right. This episode comes straight from the public OpenAI Codex repository and the official OpenAI Codex docs. We pinned the repo snapshot; the commit and links are in the description. Good. No folklore version, no vibes version. Sources first, then architecture. From that opening scare, the wrong mental model is that the chatbot made a suggestion and the terminal did the rest.
0:36 That is the nightmare that makes local agents different from chatbots. Exactly. The thing protecting you is not just model alignment. It is this paranoid local runtime that turns model intent into machine action, one checked step at a time. Right. So the terminal prompt is not the system. Right. The prompt is paint on the outside of the house. The runtime is the house. From that runtime-first view, the repo makes the client split obvious once you stop staring at the TUI. There is the TUI, `codex exec`, review and resume flows, app-server, MCP server, desktop bridges, plugins, and debug surfaces.
1:16 A whole row of front doors. That is the architectural tell: it is a client problem, not a terminal problem. Front doors, yeah. But they all need the same core. First, a session, a thread, and a turn loop. Then model transport, tool routing, local execution, approval checks, and persistence. So if I am reconstructing the system, I do not start by drawing terminal boxes. Exactly. You start with the engine the boxes are clients of. With those front doors separated, the first source-backed primitives are thread, turn, and item. I like this because it forces the architecture to admit that agent work is not a single request.
1:54 Give me the practical version. A thread is the durable container for the whole task. For example, migrate the schema, update the ORM, run tests, fix the failures, maybe resume tomorrow. That whole lifecycle is one thread. Right. And the turn is not one model call. Right. A turn is one user input moving through the model and local tools until the model stops asking for more actions. An item is the event record inside that turn: user input, assistant text, tool call, tool result, each one appended in order.
2:29 After thread and turn, the session is where the live machine boundary shows up. The source puts the live authority pieces inside session configuration. Provider config and approval policy travel together. Permission profile, cwd, and workspace roots define where the run is allowed to act. Instructions, dynamic tools, history persistence, and the original config snapshot ride with that boundary. That is already more than a model client. Much more. The session is where model intent collides with machine authority.
2:58 Collision is the right word. The model says, I want to run this command. The session says, from this directory, under this permission profile, with these roots, maybe. Maybe is the product. From session config, the snapshot part matters more than people think. If behavior depends on scattered globals, environment state, remembered flags, and whatever the UI happened to pass in, debugging an agent run becomes archaeology. We've all debugged some version of that. I have shipped that kind of bug, and it is miserable. A repro says "the agent edited the wrong file," and nobody can say which cwd or approval policy it had.
3:40 Exactly. For example, the same "clean the build output" prompt means one thing from slash Users slash you slash app slash frontend and a much scarier thing from the repo root. A serious runtime captures the config shape up front: source, mode, permissions, roots, model choices, and instructions. Same words, different authority. Once the session boundary is fixed, the first thing the engine has to survive is a loop, not a prompt. The heart of the runtime is the turn loop. User input enters. The runtime builds prompt context.
4:15 It adds instructions, history, tool schemas, output constraints, and whatever recent state survived compaction. Then it opens a Responses stream. And the stream is not just text. It is a mixed event stream, and that changes the whole control loop. Right, and that is where the chatbot mental model breaks. The stream can contain assistant text, reasoning deltas, tool calls, tool results, and completion signals. If the model requests a file read, the runtime pauses the loop, executes the read through the approved tool path, appends the result, and calls the model again.
4:51 Oh, wow. So one request can become several model calls without the UI pretending it was one answer. Exactly. That is the mental-model flip. Inside that turn loop, prompt assembly is part of the runtime, not a string template in a UI component. That is easy to underbuild. Yeah. If you just concatenate user text and old messages, I mean, you miss the important part: the tool menu. For example, a read-only review session should see file-reading tools and maybe search, not `apply_patch` and shell-write paths.
5:21 The model only sees the schemas for tools this session can legally use right now. I like that phrasing: the current legal menu. Legal menu, yes. History, instructions, personality, tool specs, parallel-tool-call flags, output schema. All of that becomes the request. The prompt is runtime state in serialized form. After prompt assembly, once the request is live, the runtime has to parse a stream that can change type mid-flight. One moment it is assistant text. Then it is a function call. Then maybe an internal event.
5:53 Then a tool result comes back and becomes fresh context. Which is why a standard REST mental model breaks. Because the response is still alive. The model can ask for four tools before the user sees one final sentence. It can ask for one command, learn from stderr, ask for a file, then ask for a patch. And the UI has to be okay with that. It cannot assume one input equals one response bubble. From that stream view, the stream only matters once it changes what the machine does. Yes, for example, take a database migration prompt.
6:30 The prompt needs the schema, so the runtime reads it. Then it needs the ORM file, so the runtime reads that too. Then it asks to run tests, and the runtime runs them. Right. And every result becomes another item in the same turn. Yes. It is not chatting with the shell. It is steering a loop where local evidence keeps changing the next model call. Right. That is why toy agents feel fine until they need three tools in sequence. Yeah. Three tools, one approval pause, and one noisy failure log. Then the toy version shatters.
7:03 After tool continuation, the source splits tool exposure from tool dispatch. The router keeps model-visible specs and maps model function calls into typed invocations. The registry dispatches those invocations and converts results back into model input items. So not one giant switch statement doing every dispatch job by hand. This is where the prototype starts to creak. That switch statement is tempting for a weekend prototype. I would absolutely write it first, and I would regret it the second plugins arrived.
7:34 Same. Then MCP tools, hosted tools, plugins, dynamic tools, image view, plan tools, user input, and multi-agent tools arrive. The switch becomes a security nightmare. Yeah. The model needs a menu. The runtime needs a kitchen and a bouncer. I love that. The menu is declarative. The kitchen has side effects. The bouncer checks authority again. From that router view, the tool exposure plan is, honestly, where the menu gets assembled. So what decides the menu, the plugin, the permission profile, or the current session?
8:06 Built-ins, exec, patch, MCP, plugins, and hosted tools can all feed the visible surface. That is already a huge surface. The dangerous part is that every extra visible tool adds another bit of authority pressure on the model. Right, but the point is not catalog trivia. The point is curation. A model should not see a delete-capable tool just because some plugin exists somewhere on disk. Visibility itself is authority pressure. If you show the model a tool it cannot use, you waste turns. If you hide a tool it should use, you cripple the agent. Planning the menu is core architecture.
8:41 After tool routing, shell execution is where the abstraction gets real. The model emits a command-shaped request. The handler resolves arguments, cwd, environment, shell text, skill invocation, sandbox permissions, and extra permission requirements before it allocates a process. Walk me through the mechanism there. How does a model-shaped command become a real child process without the shell becoming the escape hatch? It has to be. Environment variables can leak secrets. The cwd changes what the command means.
9:07 A harmless-looking command can write somewhere surprising. And the runtime may need to intercept special cases before they hit the shell. The shell is not an escape hatch. No. It is a controlled tool path with process hygiene wrapped around it. Take a concrete case: `rm -rf build` inside `frontend/` is cleanup; the same shape one directory higher can wipe generated assets for the whole repo. Next, file edits deserve their own lane. I use text-replacement commands constantly, but I do not want a language model improvising shell text to rewrite source files.
9:40 Same. A bad text-replacement expression corrupts quietly. Right. Apply patch gives the runtime a structured edit object. The source can reject empty patches, check paths against workspace roots, and decide whether the current trust and sandbox conditions allow the change. Right. So patch safety is not just formatting. Exactly the scary part. It is formatting plus path containment plus approval policy. File edits are where agent convenience becomes durable damage. From file edits to process output, process hygiene is boring until it saves the thread.
10:15 The runtime defines timeouts, output byte caps, maximum output-delta events, kill behavior, and a drain period after termination. Oh, wow. Compilation confetti prevention. If the model runs `npm install` in verbose mode, or starts a dev server in the foreground, raw stdout can bury the useful error and freeze the turn. Yeah. We've all watched that happen. I once lost the thread in a wall of build logs and started debugging npm noise instead of the original test failure. Byte caps and timeouts are not cosmetic.
10:44 They preserve attention, cost, and liveness. After process limits, here is the user pushback I actually care about. If I voluntarily launched the agent inside my project, did I not already trust it? That is exactly the staff engineer in the room saying, "I ran your binary in my repo. Why are you still asking me?" Sure, and that sounds reasonable until the session starts spawning child processes. Let's hear it. That is the dangerous shortcut. Launching the binary is not blanket consent for every future child process in a long-running autonomous session.
11:19 Right. "Fix the layout" does not imply "run a package manager upgrade" or "drop my local database." Exactly, the axis is delegated authority. Skip means the runtime can proceed without interrupting the user. Needs approval means the turn pauses for human consent. Forbidden means the runtime refuses even if the model asks confidently. Right. Friction is not failure there. Yeah. It is the boundary doing its job. From approval policy, the boundary is not portable magic; it has to become a real operating-system mechanism.
11:49 Right. Sandboxing is where generic architecture talk usually lies. There is no universal sandbox. On macOS, Codex uses Seatbelt through `sandbox-exec`. On Linux, the source talks about Landlock or bubblewrap. WSL2 can support the bubblewrap path because it has a real Linux kernel. WSL1 cannot. Oh, right. So "sandboxed" is not one feature flag. It is a policy promise mapped onto different operating-system mechanisms. Exactly. Local power forces local boundaries, and local boundaries are operating-system work.
12:17 After platform sandboxing, command policy and patch policy are separate because intent and effect are separate. The command text might look safe while the filesystem effect is not. Give me a concrete failure, not a policy slogan. What actually goes wrong on a developer machine? For example, a user gets tired of prompts and wants to always allow commands starting with `python3`. Sounds convenient. Then the model can run a one-liner that imports `os` and shells out to something destructive. Yeah, that is scarier: the allowlist itself becomes a capability grant before patch policy gets involved.
12:49 The broad prefix is dangerous by itself. The policy code can reject overly broad allow rules, recognize dangerous command shapes, and still let patch safety catch writes outside the intended roots. Once policies exist, instructions are loaded like configuration. `AGENTS.md` is not a sticky note the UI happens to paste in. For example, the implementation scans from a project root marker toward the current working directory, merges applicable instruction files, supports fallback names, and enforces byte budgets.
13:20 Right. The byte budget is the unsung part. Without it, instruction loading turns from guidance into context spam. Right. Completely. A monorepo can have a root instruction file, a frontend instruction file, and a backend instruction file. If the agent blindly injects every document in the tree, the context window becomes a policy landfill. All the words are there, but the useful rule is buried. Exactly. The runtime needs the right rules, not all rules, and that is the difference between guidance and context spam.
13:52 After instructions, skills and plugins extend that idea. A skill can add procedural memory for a repeated workflow. A plugin can add new tools. But extension surface is also blast radius. More tools, more authority edges. Yes, and the scary version is a plugin author saying, relax, my tool only reads email. If a community plugin can read email, you know, it cannot bypass the same tool routing, permission checks, and approval posture as a built-in shell tool. Otherwise the plugin becomes the hole in the sandbox.
14:25 Exactly. The execution plumbing has to stay centralized even when the tool surface becomes dynamic. Right. Otherwise extension becomes the escape hatch. With extensions in place, the app-server crate shows why the runtime split matters. For example, it is the bridge for richer interfaces like the VS Code extension, and the README describes JSON-RPC over standard input and output by default. Exactly. So the IDE is another client. Right. It can call thread and turn APIs, file-system calls, command execution, MCP status, plugins, and remote control.
14:56 But the IDE does not. Own execution logic. Exactly. That is the split. The IDE formats requests and renders events. The runtime owns the dangerous work. From that client split, the weirdest version is Codex becoming an MCP server. Usually we think of Codex as an MCP client that reaches out to tools. The source flips that. Wait, really? Yeah. Another MCP client can connect to Codex, make a tool call, and that creates a native Codex thread through a thread manager with an MCP session source. So Codex becomes the execution engine another agent can call.
15:34 Exactly. Agents calling agents is fun to say, but architecturally it means Codex exposes local operating-system capability as a controlled service. After that MCP inversion, persistence is the next survival boundary. Right. After remote clients, long-running work needs durable history. The thread-store docs separate raw history append from metadata updates, recommend a live thread abstraction, and describe local persistence through JSONL rollout plus SQLite metadata when available. Wait, why not just keep an in-memory array?
16:04 Because agent work is expensive and fragile. Persistence is the flight recorder. Imagine a 6-hour migration thread: schema file, ORM edits, failed test run, three patches, then a laptop sleep. You need the thread back, not a blank prompt. Oh, man, it really is. Losing 6 hours of context because one tool handler panicked is not acceptable. Exactly. Persistence is not a nice dashboard feature. It is survival for autonomous work. After persistence, compaction is the part that makes me nervous. It is not just "make the prompt shorter." It is deciding what the next model call is allowed to forget.
16:39 Allowed to forget, yeah. That is the honest framing. The source implements manual and automatic summaries, selected recent messages, and retries when context is exceeded by trimming older history. Which keeps the turn alive. It does, but it is lossy. If the only useful compiler error was hidden in old output, a summary can turn a precise failure into "build failed." That is a real failure mode. Compaction is necessary, not free. From compaction, memory is a different promise. Memories sit outside the immediate turn loop.
17:11 The README describes a pipeline that runs when memory is enabled, the session is not ephemeral, it is not a sub-agent, and state storage is available. So it is not slowing down every tool call. Right. It scans eligible completed threads, extracts durable learnings, and consolidates them into filesystem artifacts. Right. Different purpose than compaction. So memory is not just compaction with a longer timeout? Exactly. Compaction kind of forgets enough noise to survive today. Memory tries to preserve the structural thing that should help next week.
17:43 After those pieces are in place, the architecture exists because failure is normal. Permission policy and platform sandbox can disagree. Project instructions can go stale. Tool schemas can drift from handlers. Output caps can hide the one line you needed. Provider streams can fail mid-turn. Tool-schema drift is my favorite painful one. For example, the model sees a schema with `filePath`, but the Rust struct now expects `file_path`. The model sends exactly what it was told. The handler rejects it. The model retries because the schema still says it is right.
18:18 Oh, that is painfully real. You burn money in a loop that looks intelligent from the outside, but the system is just faithfully retrying a contract it cannot satisfy. Given that failure list, the rebuild order is not feature order. It is risk order. The sequence is the architecture lesson. If I were rebuilding this from scratch, I would start smaller than Codex. One provider connection. One prompt builder. One turn loop. Hard-code a string, send it to the model, print the text back. Prove you can talk to the brain before you give it hands.
18:54 Then add tool-result continuation. Parse one JSON-shaped tool request. Return a fake result. Append it. Call the model again. Prove the loop can spin before any real filesystem power enters. Not plugins. Not a beautiful terminal UI. First prove the core loop can survive evidence changing under it. After the loop can spin, give the agent hands, carefully. Add shell execution and apply patch with hard-coded roots. Resolve cwd and environment. Add output caps. Add timeouts. Then approvals, because the dangerous part starts right there.
19:29 Yes. Approval policy, command policy, patch safety, and a platform sandbox. This is the half-built danger point. A tool loop without boundaries is worse than no agent. Yeah. That line should be on a sticky note for anyone rebuilding this. Because now the model can act locally before the runtime knows how to say no, and that is the point. After safety is in place, only then do you add thread persistence, compaction, richer clients, Codex exec-style non-interactive mode, app server, MCP server support, skills, plugins, memories, and sub-agents.
20:04 Surfaces after safety. Surfaces after the core loop and safety, yes. Otherwise you are putting polished doors on a building with no load-bearing walls. Oh, that is the architectural lesson of Codex CLI. Right. The attractive part is the terminal assistant. The serious engineering is the runtime that makes terminal assistance survivable. To close the loop, the model emits intent. The local runtime decides whether that intent becomes action. And that runtime has to own session state, tool schemas, turn continuation, process execution, approvals, sandboxing, project instructions, persistence, compaction, and extension surfaces.
20:45 Exactly. That is the part I like. The boundary is not paperwork; it is the product. Right. The runtime is the system. Exactly. The real object is the runtime boundary around local action, not the terminal window. Our source pack was the pinned Codex repo snapshot plus the official docs, including approvals, AGENTS.md, config, app-server, thread-store, and memories links below. Next time in Systems in the Open, we will take another real system and rebuild the shape from sources. Thanks for listening to Learning Podcasts.