How Claude Code and Codex work
A deep dive into the publicly documented architecture of the two leading coding agents — Anthropic's Claude Code and OpenAI's Codex. Both are, at heart, a surprisingly short loop around a model call. The hard part, and almost every real difference between them, lives in the engineering around that loop.
The one-paragraph answer
A coding agent is a program — the vendors call it a harness — that repeatedly does five things: build a prompt out of instructions, tool descriptions and the conversation so far; send it to a language model; read back either a final answer or a request to use a tool (“run npm test”, “open src/auth.ts”); check whether that action is allowed and execute it, usually inside an operating-system sandbox; then append the tool's output to the conversation and go round again. The loop ends when the model replies with plain text instead of a tool call. OpenAI's own engineering write-up notes that a single user request can involve hundreds of these iterations. Neither product has a secret planner or a hidden symbolic engine: the model decides every step, and the harness decides what the model can see and what it is allowed to touch.
The common skeleton. Everything that distinguishes the two products — what goes into step ①, which tools exist in step ④, how step ③ decides, and how step ⑤ keeps the history from overflowing — is harness engineering. The model only ever does step ②.
A short history
Anthropic released Claude Code as a research preview in February 2025 alongside Claude 3.7 Sonnet, and made it generally available in May 2025 with the Claude 4 models. In September 2025 it renamed the underlying “Claude Code SDK” the Claude Agent SDK, making explicit that the coding tool and the general-purpose agent framework are the same harness. Claude Code itself is closed source; in March 2026 its full TypeScript source was briefly exposed through a source map accidentally shipped in an npm release, which Anthropic described as a packaging error. This page deliberately relies only on what Anthropic documents.
OpenAI recycled the name Codex — originally the 2021 code model behind GitHub Copilot — for an open-source terminal agent, the Codex CLI, in April 2025, followed in May 2025 by a cloud agent inside ChatGPT that works in parallel containers and opens pull requests. The CLI was first written in TypeScript and then rewritten in Rust; the repository is Apache-2.0 licensed and the same Rust “harness” powers the CLI, the IDE extension and the cloud product. In January 2026 OpenAI engineer Michael Bolin published “Unrolling the Codex agent loop”, the most detailed first-party account of either system, which much of the Codex half of this page draws on.
1 · The loop, and the arithmetic that shapes it
Language-model APIs are, at the level that matters here, stateless functions: text in, text out. So on every iteration the harness sends the whole conversation again. Codex makes this a principle — it does not use the Responses API's optional server-side memory (previous_response_id), precisely so that every request is self-contained and works for customers who require zero data retention.
That has a cost worth writing down. Suppose each iteration adds about c tokens (a tool call and its output). At step k the prompt is about k·c tokens long, so after n steps the model has read
c + 2c + … + nc = c · n(n+1)/2 ≈ c·n²/2 tokens,
which is quadratic in the length of the task. A 200-step session would cost a hundred times more than a 20-step one, not ten times more. The escape is prompt caching: if a new prompt begins with exactly the same tokens as the previous one, the provider reuses the internal state it already computed for that prefix and only processes the new tail. The genuinely expensive work then grows linearly — about c new tokens per step — while the cached prefix is billed at a steep discount. OpenAI's post puts it plainly: with cache hits, sampling scales linearly rather than quadratically.
The catch is that a cache hit requires an exact prefix match, and this single constraint explains a lot of design choices in both harnesses. Static content goes first and changing content last. The history is only ever appended to, never edited in place: when you switch Codex's sandbox mode or working directory mid-session, the harness does not rewrite its opening instructions, it appends a new message restating the setting. Changing the model or the list of tools mid-conversation invalidates the cache, and Bolin recounts an early bug in which MCP tools were listed in a non-deterministic order — enough to break the prefix and silently multiply costs.
2 · Context: what the model actually sees
Because the model knows nothing beyond its prompt, “context engineering” — choosing what goes in it — is the core of both products.
Codex builds each request in a fixed order: a server-controlled system message, then the tool definitions, then the instructions, then the input items (the conversation). Messages carry a role with a strict priority — system, developer, user, assistant — and Codex uses the developer role to tell the model about its sandbox: what it may write, whether it has network access. Project guidance comes from AGENTS.md files: Codex reads a global one from its home folder, then walks from the repository root down to the current directory, concatenating every AGENTS.md it finds (an AGENTS.override.md takes precedence), capped by default at 32 KiB. A description of the environment — the working directory and shell — is added as a user-role message.
Claude Code follows the same idea with its own file, CLAUDE.md, layered from organisation policy to the user's home folder to the project and its sub-folders (it can also read an AGENTS.md). On top of that it adds an auto memory file the agent maintains itself — the first 200 lines or 25 KB of MEMORY.md load at the start of each session — and short “system reminders” that it injects as work proceeds, for instance when a file it read earlier has changed on disk. Its distinctive technique is progressive disclosure: skills (packaged instructions for a kind of task) appear only as one-line descriptions until the model decides to use one, and tool definitions from MCP servers are deferred by default — only names are listed, and the full schema is fetched by a tool-search step when needed. The aim is to keep thousands of tokens of rarely used documentation out of every single prompt, which by the arithmetic above is paid for on every iteration.
3 · Tools: many specialists versus a few generalists
Here the two designs genuinely diverge. Claude Code exposes a fairly large set of dedicated tools, which its documentation groups as file operations (Read, Edit, Write), search (Glob for file names, Grep for contents), execution (Bash), web (search and fetch), code intelligence (type errors and definitions via language-server plugins), plus orchestration tools for spawning sub-agents, tracking a to-do list and asking the user a question. Edits are made by exact string replacement: the model names a file it has already read, a passage that must occur exactly once, and its replacement — a deliberately narrow interface that fails loudly rather than editing the wrong spot.
Codex leans the other way: a small set of general tools, chief among them a shell tool for running commands and an apply_patch tool for editing. A patch is written in a custom, line-oriented diff grammar (*** Begin Patch … *** End Patch) that can add, delete, move and modify files in one call; the Rust binary even re-invokes itself as the patcher so that edits run under the same sandbox as everything else. Searching code is just a shell command (typically rg). Beyond these there is a planning tool, web search and image viewing, and any number of tools from MCP servers.
Neither choice is arbitrary, because neither tool set is independent of the model. Anthropic trains Claude on its string-replacement editor and OpenAI trains its GPT-Codex models on the apply_patch format; each harness is co-designed with its model. The trade-off is a familiar one in software. Specialised tools are easier to permission (“may read anything, must ask before Bash”), easier to show a human, and cheaper in tokens; a general shell is more powerful and more uniform, but every action looks the same to a permission system — a string of shell — which pushes safety down into the operating-system sandbox. That is exactly where Codex puts it.
4 · Safety: what is allowed versus what is possible
Both harnesses separate two questions that are easy to blur: what the agent is allowed to do (a policy, enforced by the harness asking or refusing) and what it is able to do (a hard limit, enforced by the operating system). The first fails if the model or an attacker talks its way around it; the second does not care what the model says.
Codex makes the split explicit as two independent settings. The sandbox mode — read-only, workspace-write (the usual default: edit inside the project, network off unless enabled) or danger-full-access — is enforced by the kernel: Apple's Seatbelt on macOS, bubblewrap namespaces and Landlock/seccomp filters on Linux, and a dedicated sandbox on Windows. The approval policy — untrusted, on-request or never — decides when Codex stops to ask you. One documented subtlety: tools supplied by MCP servers run outside Codex's sandbox and must police themselves.
Claude Code started from the policy side. Its permission modes range from asking before every edit and command, through “accept edits” and a read-only “plan” mode, to an “auto” mode in which a classifier reviews actions in the background and blocks risky ones instead of asking. Fine-grained allow / ask / deny rules (“always allow npm test”) live in settings files layered from organisation to user to project, and hooks let you run your own scripts before or after any tool call — deterministic code, not model judgement. In late 2025 Anthropic added an OS-level sandbox for the Bash tool, using the same Seatbelt and bubblewrap primitives, with network traffic routed through a proxy that only lets approved domains through; it reported that in its internal use this cut permission prompts by 84%, because commands that stay inside the sandbox no longer need a human. Separately, every file edit is checkpointed so it can be rewound — though, as the docs warn, nothing can checkpoint a database write or a deploy.
The reason both teams converged on kernel sandboxes is prompt injection: a coding agent reads untrusted text all day (web pages, issues, dependency READMEs), and any of it might contain instructions. A permission prompt asks a tired human to catch that; a sandbox makes the dangerous action impossible regardless.
5 · Long tasks: compaction, sub-agents and memory
Every model has a finite context window, and a long agent session fills it. Both harnesses therefore compact: they replace old history with something shorter, accepting some loss.
Claude Code does it in stages — first clearing the bulky outputs of old tool calls, then, if still needed, summarising the conversation. Your requests and key code are kept; detailed instructions from early on may not be, which is why the documentation insists that durable rules belong in CLAUDE.md (re-read every session) rather than in chat. You can steer the summary with /compact focus on …. Its second weapon is the sub-agent: the main agent can delegate a task to a fresh instance with its own empty context window; the sub-agent may read fifty files, but only its short report comes back into the main conversation. That keeps the orchestrator's context small, and lets several sub-agents run in parallel. Sessions are written to local JSONL files, so they can be resumed or forked later.
Codex moved compaction to the server. When the token count passes a threshold (auto_compact_limit), it calls a dedicated /responses/compact endpoint that returns a replacement list of items, including a compaction item whose content is encrypted — a summary in a form the model can use but the client cannot read. The same trick lets the model's hidden reasoning from earlier turns be carried forward as encrypted content, even for customers whose data OpenAI does not store.
6 · One engine, many surfaces
Both companies built the loop once and put several front-ends on it. Claude Code's loop, tools and permission system are identical in the terminal, the IDE extensions, the desktop app, the web version (which runs in Anthropic-managed cloud machines), Slack and CI pipelines, and the Agent SDK offers that same harness to developers building non-coding agents. Codex's Rust core sits behind the terminal interface, a non-interactive codex exec mode for scripts, the IDE extension, and the cloud product; Codex can even run as an MCP server, so another agent can call it as a tool. The cloud versions of both change where the loop runs, not what it is: a disposable container with the repository cloned in, network access governed by an environment policy, and the result delivered as a branch or pull request.
Side by side
| Aspect | Claude Code | Codex |
|---|---|---|
| Maker / launch | Anthropic — research preview Feb 2025, generally available May 2025 | OpenAI — Codex CLI Apr 2025, Codex cloud agent May 2025 |
| Source | Closed source (TypeScript); the same harness is sold as the Claude Agent SDK | Open source, Apache-2.0; rewritten from TypeScript to Rust (codex-rs) |
| Model API | Anthropic Messages API, Claude models | OpenAI Responses API, GPT-Codex models (or a local model via --oss) |
| Project instructions | CLAUDE.md (org, user, project, sub-folders) + auto memory | AGENTS.md cascade, root to current folder, capped at 32 KiB |
| Tool philosophy | Many specialised tools: Read, Edit, Write, Glob, Grep, Bash, Web, Agent… | Few general tools: shell, apply_patch, plan, web search, images |
| How edits are made | Exact string replacement in a file the agent has read | A patch in a custom diff grammar the model is trained to emit |
| Permission model | Modes (manual, accept edits, plan, auto) + allow/ask/deny rules + hooks | Sandbox mode × approval policy (two independent axes) |
| OS sandbox | Seatbelt (macOS), bubblewrap (Linux/WSL2); network via an allow-listing proxy | Seatbelt (macOS), bubblewrap / Landlock + seccomp (Linux), Windows sandbox |
| Long tasks | Clear old tool output, then summarise; sub-agents with their own context | Server-side /responses/compact returning an encrypted summary item |
| State | Sessions logged locally as JSONL; file checkpoints for undo | Stateless requests (full history re-sent), compatible with zero data retention |
What the architecture teaches
- The loop is trivial; the harness is not. The core algorithm fits on an index card. What took two of the best-funded labs years is everything around it: cache-friendly prompt layout, context budgeting, tool interfaces the model handles reliably, sandboxes, recovery from overflowing context.
- Model and harness are trained together. Each model is trained on its own harness's edit format and tools, so “which is better” is never a question about the model alone — a model tends to do best inside the harness it was trained with, and benchmarks that swap harnesses measure the pairing.
- Cost is a design constraint, not an afterthought. The quadratic-versus-linear arithmetic of re-sending history decides ordering rules, the append-only discipline, deferred tool loading and compaction. Much of what looks like product taste is really cache economics.
- Safety moved from asking to containing. Both began with “ask the human” and both converged on kernel sandboxes, because approvals do not scale to hundreds of actions per task and do not stop an injected instruction the human fails to notice.
- Open versus closed matters for trust, less for design. Codex's source can be audited line by line; Claude Code must be understood through its documentation and SDK. Yet the documented architectures are strikingly similar — evidence that this is close to what the problem itself demands.
Sources
- Anthropic — How Claude Code works (official docs)
- Anthropic — Building agents with the Claude Agent SDK (Sept 2025)
- Anthropic — Claude Code sandboxing (official docs)
- Anthropic Engineering — Making Claude Code more secure and autonomous (Oct 2025)
- OpenAI — Unrolling the Codex agent loop, Michael Bolin (Jan 2026)
- OpenAI — openai/codex repository (Apache-2.0)
- OpenAI — Codex sandboxing concepts (official docs)
- heise — Claude Code source exposed via an npm source map (Mar 2026)