Claude Code, Taken Apart
Anthropic's coding agent, dismantled the way its architects might draw it: eight layers from the interfaces down to the model, one task traced through all of them, how the layers connect, where it fails, and what it would take to build one yourself.
1. Case file
- In one sentence.
- A coding agent built as one general loop with strong built-in tools, where everything that makes it yours (rules, integrations, guardrails, helpers) is added as configuration rather than code.
- How to read this teardown.
- First the whole system on one diagram, with one task traced through it. Then each of the eight layers in turn. Then how they connect, how it evolved, where it fails, how to build one, and what people use it for.
2. The whole system in one picture
๐๏ธ The whole system, layer by layer, with one task traced
Same eight-layer reference stack in every article of the series. Components and calls are drawn from the project's documentation and code; where internals are not public the drawing is inferred from documented behaviour. The monospace box shows what actually moves between layers at each step (simplified).
3. Layer by layer
- Each layer answers one question. The colours match the diagram above and every other article in the series.
L1๐ฅ๏ธ Interfaces ยท Where people (or other agents) talk to it
- What it does
- Gives people (and programs) a way in: a terminal session, an editor panel, a browser tab, or code.
- How it is built here
- Terminal CLI first, then IDE extensions, desktop and web apps; the Agent SDK exposes the same agent to your own programs.
- Design choice
- Many front ends, one engine. Every surface drives the same loop, so behaviour is consistent and features ship everywhere at once.
- Without it
- Each surface would grow its own agent, and a fix in one would not reach the others.
L2๐งญ Sessions & orchestration ยท Who owns a task: sessions, background tasks, subagents
- What it does
- Decides who owns a piece of work and for how long: sessions, resuming, background work, helpers.
- How it is built here
- Sessions with transcripts that can be resumed; subagents spawned and coordinated by a lead agent; cloud sessions for long tasks started from the web.
- Design choice
- Subagents isolate context, not just parallelise: exploration stays out of the main conversation, so the lead agent keeps room to think.
- Without it
- A single conversation fills up with search results, and long tasks either stop or forget their own beginning.
L3๐ Agent loop ยท How it decides the next step
- What it does
- The engine: ask the model for the next action, run it, feed back the result, repeat.
- How it is built here
- One general gather-context โ act โ verify loop for every task; no fixed workflow. The model emits tool calls; the harness executes them and returns results.
- Design choice
- Generality over workflows. The loop is deliberately simple; capability comes from the model and from what the other layers add.
- Without it
- You would have to draw every workflow in advance, which breaks on open-ended work like debugging.
๐ How this loop compares with the other four, dial by dial, and its RSI level: Inside the Agent Loop
L4๐ง Context engine ยท What the model sees on each turn
- What it does
- Decides what the model sees on every turn, inside a fixed context window.
- How it is built here
- CLAUDE.md files (user, project, folder), auto memory, skills loaded on demand, subagent summaries, and compaction of older turns.
- Design choice
- Load little, fetch on demand. Instructions are short files; detail arrives through tools and skills only when needed.
- Without it
- Either the model forgets project rules, or the window fills with irrelevant text and quality drops.
L5๐ ๏ธ Tools ยท What it can do
- What it does
- Turns intentions into actions: reading, editing, running, searching, calling outside systems.
- How it is built here
- Built-in file, shell and search tools; MCP servers for outside tools and data; skills that bundle instructions with scripts.
- Design choice
- A small set of powerful built-in tools (a shell can do almost anything) plus an open protocol for everything else.
- Without it
- Every integration would need custom code inside the harness, and the agent could not use your existing tools.
L6๐ก๏ธ Policy & safety ยท What it may do
- What it does
- Decides what the agent may do without asking, and enforces your own rules.
- How it is built here
- Allow / ask / deny permission rules per tool and pattern; session modes such as planning without edits โ ๏ธ; hooks that run your commands before or after actions; administrator-managed settings โ ๏ธ.
- Design choice
- Two kinds of control: probabilistic (instructions the model usually follows) and deterministic (permissions and hooks it cannot skip). Anything that must happen goes in the second kind.
- Without it
- The agent either asks about everything (approval fatigue) or nothing (risk), and "always run the formatter" depends on the model remembering.
L7๐ฆ Execution ยท Where actions actually run
- What it does
- Where commands actually run, with whose access.
- How it is built here
- Locally: your shell, your working directory, your user's permissions, with optional sandboxing โ ๏ธ. Web sessions run in Anthropic's cloud.
- Design choice
- Run where the developer already works, so the agent sees the real build, tests and tools, then add limits on top.
- Without it
- An agent in a separate environment cannot reproduce your bugs; an unrestricted one can damage your machine.
L8๐งฌ Model & telemetry ยท Which model, and what gets logged
- What it does
- The model that decides, and the records of what happened.
- How it is built here
- Claude models over the API (or through cloud providers โ ๏ธ); session transcripts, cost and usage reporting, organisation telemetry โ ๏ธ.
- Design choice
- The model is a dependency the harness is designed around; the harness keeps the record.
- Without it
- No way to review what the agent did, attribute cost, or debug a bad run.
4. Connecting the dots
- Quality comes mostly from layers 4 and 5, not only the model.
- What the model sees (context) and what it can do (tools) decide most outcomes; the loop itself is simple.
- Two kinds of control.
- Instructions in CLAUDE.md and skills shape behaviour probabilistically; permissions and hooks enforce it deterministically. Good setups put anything that must happen in the second kind.
- Where time and money go.
- Every turn re-sends the context to the model, so long sessions cost more per turn; subagents and compaction exist largely to keep the context small.
- Where the security boundary really is.
- Not around the model but around layer 7: commands run with your access. Layer 6 is the gate in front of it.
๐งฌ Design DNA: the three decisions that define it
๐ธ Where the tokens go in the traced task (our estimate)
An illustrative split for a ~300k-token task: about $1.20 at an assumed blended $4 per million tokens. Real numbers vary widely with the repo, the model and caching; the shape (context re-sent every turn dominates) is the point.
5. How it evolved
- The pattern.
- Each addition moved control from prompts into configuration: hooks for deterministic actions, subagents for context isolation, skills for on-demand know-how, the SDK for reuse.
- โ ๏ธ Dates are from Anthropic's announcements as we recall them; they could not be re-checked from our build environment.
6. Where it breaks, and what it does about it
| Failure | Layer | What happens | What this system does about it |
|---|---|---|---|
| Context overflow | L4 | Long tasks fill the window; early instructions get lost. | Compaction, subagents, short CLAUDE.md files, skills loaded on demand. |
| Going in circles | L3 | The agent retries the same failing approach. | You can interrupt and redirect at any turn; planning before acting helps โ ๏ธ. |
| Wrong or destructive edits | L6 | Edits the wrong file or runs a harmful command. | Ask/deny rules, reviewing diffs, version control as the safety net. |
| Prompt injection | L5 | A file, web page or tool result contains instructions that hijack the agent. | Permission prompts for risky tools, trusted MCP servers only, sandboxing โ ๏ธ. |
| Approval fatigue | L6 | Too many prompts, so people approve without reading. | Allow rules for safe commands; ask only for what matters. |
| Rules ignored | L4 | The model forgets a convention in CLAUDE.md. | Move must-do rules into hooks (deterministic). |
| Cost surprises | L8 | Long sessions re-send large contexts many times. | Usage reporting; smaller contexts; choosing the model per task. |
7. Security and threat model
๐งฑ Trust boundaries
Our summary of the threat model implied by the documented features.
- Three rules that follow.
- Treat everything the agent reads as data, never as orders.
- Give MCP servers the same trust you would give a new dependency.
- Keep the most dangerous actions on "ask" or "deny", whatever the convenience cost.
8. Standards it shares, and benchmarks
- Interoperability.
- MCP: the open protocol for tools and data; the same servers work with many harnesses.
- Agent Skills: a folder with a SKILL.md; the format is also used by other agents (Hermes Agent says its skills follow the agentskills.io standard).
- Agent SDK: the loop as a library, for building your own agents.
- Benchmarks.
- Agentic-coding benchmarks score a model and a harness together; a vendor's own harness and a third-party one can give different scores for the same model. See the Frontier Benchmark Tracker for sourced numbers and their setups.
9. What people use it for
10. How to build one from scratch
- Start small: a harness that runs.
- The script below is a separate toy for this article: the Claude Code ideas (instructions file, permission rules, a post-edit hook, a subagent with its own context) in about 70 lines. The "model" is a scripted stub so the run is repeatable; a real build calls an LLM API where marked.
"""mini_claude_code.py โ a toy harness in the style of Claude Code (illustrative).
One general agent loop + configuration: an instructions file loaded every session,
built-in tools, permission rules, a post-edit hook and a subagent with its own
context. The "model" is a scripted stub so the run is repeatable; a real harness
calls an LLM API at the marked line. Standard library only.
"""
REPO = {"dates.py": "def parse(s):\n d, m, y = s.split('/')\n return (int(y), int(m), int(d))\n",
"test_dates.py": "from dates import parse\nassert parse('2026-11-07') == (2026, 11, 7)\n"}
MEMORY = "Run tests with: python test_dates.py\nKeep diffs minimal." # CLAUDE.md
PERMS = {"read": "allow", "search": "allow", "edit": "ask", "bash": "allow:tests"}
APPROVE = {"edit"} # the human says yes to edits
def run_tests():
try:
ns = {}; exec(REPO["dates.py"], ns)
y = ns["parse"]("2026-11-07"); return "PASS" if y == (2026, 11, 7) else f"FAIL got {y}"
except Exception as e:
return f"FAIL {type(e).__name__}: {e}"
def tool(name, arg):
rule = PERMS.get(name, "deny")
if rule == "ask" and name not in APPROVE: return "denied by user"
if name == "read": return REPO[arg]
if name == "search": return [f for f, t in REPO.items() if arg in t]
if name == "bash": return run_tests()
if name == "edit":
REPO[arg[0]] = arg[1]; return "edited " + arg[0] + " | hook: formatted" # PostToolUse-style hook
return "unknown tool"
def subagent(task): # own context: only the summary returns to the main loop
hits = tool("search", "parse")
return f"subagent summary: '{task}' -> parse() lives in {hits[0]}, test expects ISO dates"
SCRIPT = [("subagent", "find the failing test and the code it covers"), ("bash", None),
("edit", ("dates.py", "def parse(s):\n y, m, d = s.split('-')\n return (int(y), int(m), int(d))\n")),
("bash", None), ("done", "fixed parse() for ISO dates; tests pass; PR ready")]
def model(turn, context): # <- a real harness calls the LLM here
return SCRIPT[turn]
def main():
context = ["system: " + MEMORY.splitlines()[0], "user: the date test fails, fix it and open a PR"]
for turn in range(10):
act, arg = model(turn, context)
if act == "done": print(f"turn {turn + 1}: DONE {arg}"); break
out = subagent(arg) if act == "subagent" else tool(act, arg)
context.append(f"{act} -> {out}")
print(f"turn {turn + 1}: {act:8} [{PERMS.get(act, 'allow')}] -> {str(out).splitlines()[0]}")
print(f"context lines: {len(context)} (the subagent's search stayed out of the main context)")
if __name__ == "__main__":
main()| Phase | What you build | Time* | Team* | Cost* |
|---|---|---|---|---|
| 0 ยท Prototype | Loop, file and shell tools, one model API, an instructions file | 1โ2 weeks | 1 engineer | $15โ40k |
| 1 ยท Usable CLI | Diff-based edits, permission prompts, test running, session resume | 1โ3 months | 2โ3 | $150โ400k |
| 2 ยท Reliable | Context compaction, retries, transcripts, evaluation suite, sandboxing | 3โ6 months | 4โ8 | $0.5โ1.5M |
| 3 ยท Extensible | MCP client, skills, hooks, subagents, settings hierarchy | +3โ4 months | 6โ10 | $0.5โ1M |
| 4 ยท Product | IDE extensions, web and cloud sessions, accounts, admin policies, telemetry, security review | 6โ12 months | 15โ40+ | $3โ10M+ a year |
*Our estimates, not vendor figures: fully loaded engineer cost assumed at $250k a year (US-style salaries; lower elsewhere), plus model API and infrastructure. Treat as orders of magnitude.
- What actually takes the time.
- Not the loop: that is the first week.
- Context management (what to load, when to summarise), tool reliability (edits that apply cleanly), the approval experience, and an evaluation suite that catches regressions.
- Resources you need.
- Model API budget (see the calculator), a set of real tasks for evaluation (SWE-bench-style), sandbox infrastructure, and people who know agent loops, developer tools and security.
- Build or extend?
- To ship an agent for your own domain, start from a library (the Claude Agent SDK, Deep Agents) or an open-source harness (Codex CLI, Gemini CLI) rather than from scratch; build from scratch only if the harness itself is your product.
๐งฎ What would running your own cost a month?
Our model: model cost = tasks ร tokens ร price ร 30 days; people = engineers ร $250k รท 12; infrastructure (sandboxes, storage, logs) assumed at 15% of model cost. A blended price mixes cached input, fresh input and output; check your provider's current prices.
11. When to choose it
โ Choose it when
- Open-ended, multi-step work in a real codebase.
- You want one agent across terminal, IDE and web.
- You extend with MCP, skills and hooks rather than writing orchestration code.
โ ๏ธ Think twice when
- You need a fixed, auditable workflow with known steps: use a framework.
- You need to modify the harness itself: choose an open-source one.
- You must serve agents to thousands of users: add a runtime (wave 3).
12. How it compares, layer by layer
| Harness | L1Interfaces | L2Sessions & orchestration | L3Agent loop | L4Context engine | L5Tools | L6Policy & safety | L7Execution | L8Model & telemetry |
|---|---|---|---|---|---|---|---|---|
| Claude Code | Terminal, IDE, desktop, web, Slack; Agent SDK | Sessions with resume; subagents; cloud sessions on the web | One general think โ act โ observe loop | CLAUDE.md, auto memory, compaction | Built-in file/shell/search tools, MCP, skills | Permission rules and modes, hooks | Your machine (optional sandboxing โ ๏ธ); cloud for web sessions | Claude models; transcripts, cost and usage telemetry |
| Codex | Terminal, IDE, web (chatgpt.com/codex) | Parallel cloud tasks; local sessions | Agent loop per task | AGENTS.md, repo context | Shell, file edits, MCP | Approval modes โ ๏ธ | OS sandbox locally โ ๏ธ; container per cloud task | OpenAI models; task logs and diffs |
| Gemini CLI / Jules | Terminal (CLI); browser + GitHub (Jules) | Interactive session vs asynchronous task | Agent loop (CLI); plan-then-execute (Jules โ ๏ธ) | GEMINI.md context files | Built-in tools, MCP | Confirmations in the CLI; plan approval in Jules โ ๏ธ | Your machine (CLI); cloud VM (Jules โ ๏ธ) | Gemini models (CLI "not optimized for Gemini 4+") |
| Deep Agents | Your own app (library) | LangGraph threads; sub-agents | Planning loop on LangGraph | Filesystem as memory; offloading | Your tools, MCP, skills | Human-in-the-loop interrupts | Pluggable backends: local, sandboxed, remote | Any chat model; LangGraph state and tracing |
| Hermes Agent | Terminal + Telegram, Discord, Slack, WhatsApp, Signal, email | Gateway, subagents, cron scheduler | Agent loop (details on its docs site โ ๏ธ) | Curated memory, FTS5 session search, user model | Tools, self-written skills (agentskills.io), Python RPC scripts | Depends on backend and configuration โ ๏ธ | Six backends: local, Docker, SSH, Modal, Daytona, Vercel Sandbox | Model you configure โ ๏ธ |
One line per layer; our reading of each project's documentation and code as of 7 Nov 2026.
| Harness | Runs where | Open source | Subagents | Persistent memory | Skills | MCP | Sandbox | Human approval | Async / cloud tasks |
|---|---|---|---|---|---|---|---|---|---|
| Claude Code | Terminal, IDE, desktop, web | โ | โ | โ | โ | โ | โ | โ | โ |
| Codex | Terminal, IDE, cloud | โ (CLI) | โ | โ | โ | โ | โ | โ | โ |
| Gemini CLI / Jules | Terminal (CLI), cloud VM (Jules) | โ (CLI) | โ | โ | โ | โ | โ | โ | โ |
| Deep Agents | Your Python / JS app | โ | โ | โ | โ | โ | โ | โ | โ |
| Hermes Agent | Terminal + chat apps | โ | โ | โ | โ | โ | โ | โ | โ |
โ built in ยท โ partial or via add-ons ยท โ not a feature. Our reading of each project's documentation as of 7 Nov 2026; check before relying on it.
13. The series
Agentic AI System Designs: four kinds of agent system, one teardown each
All of them on one page: Agentic Systems at a Glance.
๐ Glossary: 15 terms used across the series
- Agent loop
- The repeat cycle: the model picks an action, the harness runs it, the result goes back to the model.
- Harness
- Everything around the model that turns it into a working agent: loop, tools, context, policy, execution.
- Context window
- The text the model can see at once. Everything the agent knows on a turn has to fit in it.
- Context compaction
- Summarising older conversation so a long task keeps fitting in the context window.
- Tool schema
- A machine-readable description of a tool (name, inputs) that tells the model how to call it.
- MCP
- Model Context Protocol: an open standard for connecting agents to outside tools and data.
- Subagent
- A second agent with its own context, used for a side task; only its summary comes back.
- Skill
- A packaged set of instructions (and sometimes scripts) the agent loads when relevant.
- Hook
- Your own command that runs automatically before or after an agent action.
- Sandbox
- A restricted place to run commands so mistakes or attacks cannot reach the rest of the system.
- Approval mode
- The rule for what the agent may do without asking you first.
- Prompt injection
- Instructions hidden in data the agent reads (a file, a web page) that try to hijack it.
- Trace
- The full record of a run: every model call, tool call and result.
- AGENTS.md / CLAUDE.md / GEMINI.md
- Plain markdown files of project instructions that harnesses read at the start of a session.
- Asynchronous agent
- An agent you hand a task to and leave; it returns a result (often a pull request) later.