arpit solanki

← all posts

Claude Code architecture breakdown

Claude Code architecture overview

Essentially when you see, most of the coding agents are almost same as shown below but there are some specific things that matter in these coding agents.

The basic loop every coding agent shares

The agent loop is dead simple. The core pattern is: get user input → assemble prompt (system prompt + memory + tools) → call API → if model returns tool calls, execute them → feed results back → repeat until done. Every coding agent (Cursor, Codex, Windsurf) uses this same loop. Then where the f this difference in code output comes from?
→ The architecture ……….

Let's start with flow of codebase. I have explained every point in this flowchart below.

Flowchart of a prompt's path through the Claude Code codebase

Architecture of claude code

1. CLI frontend

The frontend that you see in cli is in react i.e. Ink → React for interactive command-line apps (Repo link). This was quite surprising.
So you start with giving prompts to claude in CLI → this goes to REPL.tsx. Wtf is this?
→ it's an abbreviation for Read-Eval-Print Loop. It's the standard term for any interactive program that does this cycle: reads your input → evaluates/processes it → prints the result → loops back waiting for more input. Your Python shell is a REPL. Node.js interactive mode is a REPL. Claude Code's terminal interface is a REPL you type a message, it processes it, shows the response, and waits for your next message.

2. QueryEngine.ts → The brain

Prompt given by user is passed to query.tsx. This file is like the control center of Claude code. Like the chef that takes input ingredients from everyone and utilises them. It takes the base instructions (you are Claude, a coding assistant and all that to give the model persona…), merges in your CLAUDE.md memories (we will discuss about the memory parts later), attaches tool definitions (telling the model what tools it can use and their input schemas), and adds any active skills. This full payload is what the model sees as its "identity + capabilities."

→ Further it calls the Anthropic API to pass all this to their model that user has currently selected. The payload that we created above and the previous conversation history are streamed to the model (instead of sending the whole prompt in one go, output is also streamed so you see text appearing character by character.)

→ Using this payload model decides whether it needs to read some files that are related to the prompt → if permitted, it is passed to model and this loop is continued until we reach desired outputs.

3. Anthropic API (Streaming + tool calls)

→ Streaming works like this — instead of the API waiting until the full response is generated (which could take 10–30 seconds), it sends tokens as they're produced. The response comes as a series of Server-Sent Events (SSE). Each event contains a small chunk of text. Claude Code renders each chunk immediately, which is why you see the "typing" effect.

→ Tool calls are how the model tells Claude Code "I need to do something in the real world." The model doesn't directly execute code or read files- it can only generate text. So when it needs to read a file, it generates a structured JSON message saying "call FileReadTool with path=src/index.ts". Claude Code parses this, executes the tool locally on your machine, and sends the result back as the next message in the conversation
below flowchart explain this ……

How streaming and tool calls flow between Claude Code and the API

4. Tool Execution Loop

there are several tools defined in claude code that help in doing various things, what are tools? If you think model as brain then tools are functions defined in code that do some actions and act as workers of a model to execute something instead of just spitting text (LLM models are prompted to spit JSON that is used as command to trigger functions → that act as tools). → IF model says that it wants to use a tool like reading output or executing something from terminal → it does a lookup in tool's registry where name and the input schema of tool lies along with its capabilities.

→ checkPermissions() - This is the multi-layered gate. First, the tool's own checkPermissions() -> Method runs (some tools always need approval). Then pattern-matching rules check if the command matches an allowed pattern. For example, you might have a rule that says Bash(git *) is always allowed but Bash(rm -rf *) always needs approval.

tool.call() → The actual execution. For a tool, it might spawn a child process and run the command. For FileReadTool, it reads from disk (is not allowed to read more than 2,000 lines). For FileEditTool, it applies a diff. Each tool also declares

isConcurrencySafe() → i.e. whether its safe to execute those tools parallely to save time. FileReadTool returns true (reading multiple files simultaneously is safe), but FileEditTool returns false (writing to files must be serialized). But why writing to files must be serialized? I have answered this later in the blog

The tool execution loop: lookup, permission check, call

5. Hooks (lifecycle events)

Hooks are Claude Code's plugin system. They let you inject custom behavior at specific points in the pipeline without modifying the core code. Think of them like middleware in Express.js or lifecycle methods in React. If you are not able to get this explanation, read the below para and example to grasp → The 9 events fire in this order during a session:

SessionStart fires when you launch Claude Code.

UserPromptSubmit -> fires after you press Enter on a message.

PreToolUse -> fires before any tool executes (you can block it here).

PostToolUse -> fires after a tool completes (you can run linting or Type Checking like tasks here).

PreCompact -> fires before context compaction.

PostCompact -> fires after compaction.

SessionEnd -> fires when you quit.

→ A practical example: say you want to auto-run ESLint after every file edit. You'd write a PostToolUse hook that checks if the tool was FileEditTool, and if so, runs eslint fix on the modified file. The hook can be a shell script, a JavaScript callback via the SDK, or a webhook to an external service. This is what makes the CLAUDE.md advice about "forced verification" actually implementable, you don't rely on prompting the model to verify, you wire it into the hook system so it happens automatically.

6. Compaction (for token cap)

This is the system that deals with coding agents fundamental constraint: the model has a finite context window. As your conversation grows (messages, tool results, file contents), it eats into that window. When you hit roughly 167,000 tokens, compaction kicks in. Below chart explains it sequentially.

It uses Three compaction strategies

  1. Standard : LLM summarizes old messages into one block
  2. Micro: Lightweight trim of non-essential details
  3. Snip : Aggressivly strips entire intermediate turns i.e. it just deletes entire intermediate turns (tool calls and their results) and keeps only the final outcomes.

What gets destroyed?
→ Every file read, every reasoning chain, every intermediate decision

The three compaction strategies, step by step

7. Terminal Output (REPL.tsx rendering)

The final piece is simpler but architecturally interesting. REPL.tsx that we previously talked about is a 2,000-line React application running in your terminal using Ink. It handles rendering streamed tokens as they arrive (the typing effect), permission dialogs (when a tool needs approval, it renders an interactive prompt), progress indicators during tool execution, virtual scroll for long outputs, and markdown formatting.

This i find something better than those electron based coding agent IDEs like cursor. I have been using cursor pro for past one year and their UI in agent chat always feels laggy and i hate that But claude code's UI and smoothness is just chef's kiss.

-> The React model makes this surprisingly clean. Each of these is a component:
<StreamingOutput />, <PermissionDialog />, <ToolProgress />. State flows through React's normal hooks and context system. When a new token arrives from the API, state updates, React re-renders the relevant component, and Ink translates that into terminal escape codes.

-> I see that React-in-terminal choice isn't a gimmick, building all these interactive UI states imperatively (like Codex does with Ratatui in Rust) would be significantly harder to maintain. The tradeoff is memory usage (React + Node.js is heavier than a Rust binary), but since the model's thinking time dominates everything, that extra RAM doesn't matter in practice.

8. Memory and context management -

Think of this as Claude Code's "notebook" that persists between sessions. When you close your terminal and come back tomorrow, the model itself has zero memory of yesterday. CLAUDE.md is how it fakes long-term memory.

There are three layers working together:
The first is your global memory at ~/.claude/CLAUDE.md → this applies to every project. Things like "I prefer tabs over spaces" or "always use TypeScript strict mode."

The second is project memory at your-project/CLAUDE.md → rules specific to this codebase, like "we use Prisma for database access" or "never modify the legacy/ folder."

The third is auto-learned memory at ~/.claude/projects/*/memory/ → things Claude Code figured out itself from past sessions.

The clever design is that CLAUDE.md acts as an index, not a database. Each line is about 150 characters → just a pointer like "User prefers functional React components." The actual detailed knowledge lives in separate topic files that only get loaded when relevant. This saves token budget massively. If you're working on the frontend, it doesn't load backend-related memories into context.

At query time, the QueryEngine reads these files and injects them into the system prompt, so the model sees your preferences as if it "knows" them natively.

How is it not slow even when there are so many back and forth calls between model and tools?

read file → call API → read another file → call API again. This seems time taking But several engineering decisions make it much faster than you'd expect:

→ Parallel tool execution. When the model returns multiple tool calls in a single response (which it often does), Claude Code doesn't execute them one by one. It checks each tool's isConcurrencySafe() flag, and runs all safe tools simultaneously. So the command "read these 5 files" becomes one parallel batch, not 5 sequential reads. The model gets all 5 results at once in the next API call.

→ Tool execution is local and fast. Reading a file takes 1–5ms. Running a grep takes 10–50ms. These happen on your machine, not over a network. The only slow part is the API round trip (sending data to Anthropic's servers and the model thinking), which is 2–30 seconds

→ The model batches intelligently. A good model doesn't call tools one at a time. When you say "refactor these 3 files," the model will often generate a plan in its first response, then issue 3 file reads in parallel in the next tool call, get all results at once, then issue all 3 edits. So a 3-file refactor might be only 3–4 API round trips, not 9.

The model thinking is 99.9% of the total time. This is why optimizing the CLI in Rust (saving 2ms per operation) is irrelevant, you'd go from 16.020s to 16.018s. Nobody can feel that difference. Just to tell you, codex is written in Rust 😂

Why writing to files must be serialized?

This is a classic concurrency problem, and it's worth understanding because it shows up everywhere in backend/systems work.

Imagine the model wants to make two edits to the same file simultaneously:

Edit A: Change line 10 from const x = 5 to const x = 10

Edit B: Change line 15 from return x to return x + 1
If both run at the same time, here's what can go wrong.

Race condition: Both read the file at the same time. Both see the original file. Edit A writes its version (line 10 changed). Edit B writes its version (line 15 changed, but line 10 is still the original). Edit B overwrites Edit A's change. You've lost work silently.

Line shift problem: Edit A inserts 3 new lines above line 10. Now what was line 15 is actually line 18. But Edit B still targets line 15, it edits the wrong line. The file is now corrupted.

Partial write overlap: Both edits start writing to disk at the same time. One gets a half-written file mid operation. The file ends up with garbled content.

If you made it this far, you get why the coding agent wars just started. Anthropic isn't competing on model power, they're competing on architecture. In the next post, I'll break down exactly what makes Claude Code's tool execution loop different from Cursor, Codex, and Windsurf. Follow so you don't miss it.