
How Claude Code’s Agent Loop Works: Tool Calls, Permission Gates and Context Compaction
Follow one "fix the failing test" request through Claude Code: how a plain while loop turns model tool calls into file reads, edits and shell commands, how every call passes a six-step permission gate, and how the context window survives a long session.
By Ghazi Khan
Architecture reconstructed from public sources. See Sources at the end.
Ask Claude Code to "fix the failing test" and it runs your tests, reads a few files, edits one, reruns the tests and reports back. It is mostly one loop. The interesting engineering sits around it: who may run what, and what the model sees each turn. Details come from Anthropic's docs for Claude Code and the Claude Agent SDK (which runs the same loop), plus Anthropic's engineering blog.
TL;DR
Claude Code is a client-side harness around a model. It sends the conversation plus a list of tool definitions to the model, the model replies with text and tool calls, the harness runs those tools on your machine and sends the results back, and this repeats until the model replies with no tool calls. Every tool call passes a permission pipeline before it runs, and the conversation is trimmed and summarized as it nears the context limit. The one design decision that makes it work: the model decides the plan, the harness decides what is allowed. The model never touches your file system. It only asks, and the harness checks every request against rules, modes and you.
What the user sees
From the terminal (or the VS Code panel, desktop app or web), the experience looks like this:
- You type a task and press Enter.
- Text streams in as Claude explains what it will check first.
- A tool row appears, for example running
npm test, with a spinner, then its collapsed output. - Sometimes the run stops at a prompt: allow this command once, allow it from now on, or reject it.
- More reads, searches and edits appear, each as its own row. Edits show a diff.
- Claude runs the tests again and ends with a short summary.
Two things are easy to miss. Esc cancels the running tool call and Claude waits for you. A correction typed mid-run is queued and read once the current tool calls finish, within the same turn. Pressing Esc twice rewinds files to an earlier checkpoint.
Requirements
If an interviewer asked you to design this, here is how I would frame it.
Functional
- Accept a natural language task and work on it over many steps without the user driving each step.
- Read, search and edit files, and run shell commands, in the user's project.
- Show progress live: streamed text, each tool call, its result.
- Let the user approve, deny, interrupt and redirect at any point.
- Resume or fork a session later.
Non-functional
- Safety: nothing changes on the user's machine without a rule or a person allowing it. File edits must be undoable.
- Latency: first text within a second or two; read-only work should not wait on slow serial execution.
- Cost: a session may make dozens of model calls, each resending the whole conversation, so repeated prefixes must be cheap.
- Context limits: a long session will outgrow the model's context window and must keep working.
- Reliability: a crashed tool, cut stream or denied call must become information for the model, not a dead session.
High-level architecture
Diagram100%flowchart LR U["User in terminal / IDE"] --> UI["UI layer<br/>(React + Ink in the terminal)"] UI --> L["Agent loop<br/>(turn controller)"] L --> CM["Context manager<br/>system prompt, CLAUDE.md,<br/>history, tool schemas"] CM --> API["Model API<br/>(streaming)"] API -- "text + tool_use blocks" --> L L --> PG["Permission gate<br/>hooks, rules, mode, prompt"] PG -- "allowed" --> EX["Tool executor<br/>Read, Grep, Edit, Bash, MCP..."] PG -- "denied" --> L PG -. "ask" .-> UI EX --> FS["Project files, shell,<br/>MCP servers"] EX -- "tool_result" --> L EX --> CP["Checkpoints<br/>(file snapshots)"] L --> T["Session transcript<br/>(JSONL on disk)"]visualized by
The walkthrough, left to right:
- UI layer. Claude Code is written in TypeScript and renders with React through Ink, with Yoga for layout. You already know this rendering model.
- Agent loop. Owns the conversation array. Anthropic describes three phases (gather context, take action, verify results), but in code it is one loop: call the model, run the requested tools, append results, repeat.
- Context manager. Builds each request: system instructions, your
CLAUDE.md, core tool schemas, and the history so far. Content that stays the same across turns is prompt cached. - Model API. A normal streaming Messages API call. When the model wants a tool, the response ends with
stop_reason: "tool_use"and contains one or moretool_useblocks. - Permission gate. Every tool call passes through it before it runs. More on this below.
- Tool executor. Runs built-in tools (
Read,Edit,Write,Glob,Grep,Bash,WebFetchand more) and MCP tools. Before an edit, it snapshots the file so it can be restored. - Transcript. Every message, tool use and result is written to a plaintext JSONL file under
~/.claude/projects/, which is what makes resume, fork and rewind possible.
Notice what is missing: no planner service, no task graph, no vector index. The team describes Claude Code as a thin shell over the model, built on a stack the model already writes well. As Boris Cherny put it: "We wanted a tech stack which we didn't need to teach."
Deep dive 1: the permission gate
The model can ask for rm -rf as easily as ls. So the core safety property lives entirely in the harness. The Agent SDK docs spell out the order in which a tool request is checked:
Diagram100%flowchart TD R["Tool request from model"] --> H{"1. Hooks<br/>(PreToolUse)"} H -- "deny" --> B["Blocked: rejection sent<br/>back as tool_result"] H -- "pass" --> D{"2. Deny rules"} D -- "match" --> B D -- "no match" --> A{"3. Ask rules"} A -- "match" --> C{"6. Ask the user<br/>(canUseTool)"} A -- "no match" --> M{"4. Permission mode"} M -- "approves" --> X["Execute tool"] M -- "falls through" --> AL{"5. Allow rules"} AL -- "match" --> X AL -- "no match" --> C C -- "yes" --> X C -- "no" --> Bvisualized by
A few details carry most of the design value:
- Deny beats everything. A deny rule blocks a call even when a hook said allow and even in
bypassPermissionsmode. Think of it like a CSP header: it is checked before any convenience setting. - Rules are scoped, not just per tool.
Bash(npm *)allows npm commands without allowing all of Bash.Edit(path)rules cover every tool that writes files. - Modes are presets.
defaultasks for anything not covered by a rule.acceptEditsauto-approves file edits and simple filesystem commands inside the project.planexplores without editing source files.autohands the decision to a classifier model. - A denial is not an exception. When a call is denied, the model receives a rejection message as the tool result and usually tries another approach. The loop keeps running.
Why so many layers? Anthropic's auto mode write-up says users approve 93% of permission prompts anyway, which trains people to click yes without reading. Two answers came out of that. Sandboxing runs the Bash tool with filesystem and network isolation enforced by the OS (bubblewrap on Linux, Seatbelt on macOS), and Anthropic reports it cut permission prompts by 84% in internal use. Auto mode puts a classifier in front of each action. That classifier sees only the user's messages and the agent's tool calls, not the agent's prose or the tool outputs, which the post calls "reasoning-blind by design", so a prompt injection hidden in a file cannot argue its way past it. Anthropic is open about its limits: on a set of real overeager actions it still missed 17%.
The frontend lesson: a permission prompt is not a modal you bolt on. It is a step in an async pipeline that can pause a running loop.
Deep dive 2: keeping the context window alive
Every turn resends the whole conversation, and tool output is large. One cat of a big file or one verbose test run can cost thousands of tokens. Claude Code uses several techniques, cheapest first:
- Load less up front. Core tools like
Read,EditandBashship their schemas on every request. MCP tools are deferred by default: only their names are visible until the model searches for one and loads its schema. Skills work the same way: a short description at session start, the full content only when used. - Search instead of index. There is no embedding index of your repo. Anthropic calls this agentic search: the model uses
Glob,Grep,headandtailto pull in only what it needs, just in time.CLAUDE.mdis the exception and is loaded up front, every request. - Clear old tool results. As the window fills, older tool outputs are cleared first. Anthropic describes this as one of the lightest forms of compaction: once a result is deep in history, the model rarely needs the raw text again.
- Summarize. If that is not enough, the conversation is summarized. Anthropic's context engineering post (September 2025) says the summary keeps architectural decisions, unresolved bugs and implementation details, and the agent continues with that summary plus the five most recently accessed files. Early instructions can get lost, which is why the docs tell you to put lasting rules in
CLAUDE.md, which is re-sent on every request. The Agent SDK emits acompact_boundarysystem message when this happens, and aPreCompacthook lets you archive the full transcript first. - Delegate. A subagent works in its own fresh context window and returns only a summary, often 1,000 to 2,000 tokens according to Anthropic, so the main conversation grows by the summary rather than by every file the subagent read.
The React analogy is list virtualization: render only the visible window and keep a cheap placeholder for the rest. Compaction does that for tokens, except the placeholder is lossy.
Prompt caching covers cost: the system prompt, tool definitions and CLAUDE.md form a stable prefix, so only the first request pays full price for them.
Deep dive 3: the frontend, a React app streaming an agent
A chat app streams one answer. An agent UI streams a sequence of blocks: text, a tool call whose input arrives in pieces, a pause for approval, a result, then another model call.
The Agent SDK exposes what the UI consumes. With partial messages on, you receive raw API stream events: message_start, content_block_start (a text or tool_use block begins), content_block_delta (either text_delta or input_json_delta, the tool input arriving as partial JSON), content_block_stop, message_delta (carries the stop reason) and message_stop. Complete AssistantMessage objects arrive per content block, and a UserMessage arrives with each tool result.
A reasonable client state model looks like this:
Diagram100%stateDiagram-v2 [*] --> Idle Idle --> Streaming: user submits Streaming --> ToolPending: tool_use block complete ToolPending --> AwaitingApproval: gate says ask AwaitingApproval --> ToolRunning: user allows AwaitingApproval --> Streaming: user denies (rejection sent to model) ToolPending --> ToolRunning: gate allows ToolRunning --> Streaming: tool_result appended, next model call Streaming --> Idle: response with no tool calls Streaming --> Idle: Esc (abort) ToolRunning --> Idle: Esc (cancel tool)visualized by
Three frontend lessons fall out of it:
- Render blocks, not strings. Each content block is its own row with its own lifecycle, keyed by block id. A text row appends deltas; a tool row shows a spinner, then a collapsed result. It is the same idea as keyed list rendering in React: stable identity per block means no re-mounting the whole transcript on every token.
- Treat partial tool input as untrusted.
input_json_deltachunks are not valid JSON until the block stops. The docs also warn that if a stream is cut off, a tool call block may never get itscontent_block_stop, so the UI must mark that call as incomplete instead of running it. - Interrupts are AbortController with state.
Esccancels the in-flight tool and stops the loop. A typed correction is a queue: it is held until the current tool calls finish and then joins the conversation within the same turn. If you have built "cancel previous search request" withAbortController, this is the same pattern with a message queue attached.
With Ink, a permission prompt is just a component rendered in the AwaitingApproval state, whose selection resolves the promise the executor awaits.
Data flow: one request, end to end
The task: "Fix the failing test in cart.test.ts."
Diagram100%sequenceDiagram participant U as User participant UI as Terminal UI participant L as Agent loop participant M as Model API participant G as Permission gate participant X as Tool executor U->>UI: "Fix the failing test in cart.test.ts" UI->>L: submit prompt L->>M: system + CLAUDE.md + tools + history M-->>UI: text delta "Let me run the tests" M-->>L: tool_use Bash("npm test") L->>G: check Bash("npm test") G-->>L: allow (matches Bash(npm *)) L->>X: run npm test X-->>L: tool_result: 1 failing test L->>M: history + tool_result M-->>L: tool_use Read(cart.ts), Read(cart.test.ts) L->>X: run both reads in parallel X-->>L: two tool_results L->>M: history + results M-->>L: tool_use Edit(cart.ts) L->>G: check Edit(cart.ts) G-->>UI: ask user U->>UI: allow L->>X: snapshot file, apply edit L->>M: history + tool_result M-->>L: tool_use Bash("npm test") L->>X: run npm test (allowed by rule) X-->>L: all tests pass L->>M: history + tool_result M-->>UI: final text, stop_reason end_turn UI-->>U: summary + diffvisualized by
Step by step:
- The loop builds a request: cached prefix (system prompt,
CLAUDE.md, tool schemas) plus history. - The model streams some text, then a
tool_useblock forBash(npm test), ending withstop_reason: "tool_use". - The gate runs its checks. An allow rule like
Bash(npm *)matches, so no prompt. - The output (one failing test) becomes a
tool_resultblock in the next user message, linked to the call by id. - The model asks for two
Readcalls in one response. Reads are read-only, so they run concurrently. Mutating tools (Edit,Write,Bash) run one at a time. - The model asks to
Editcart.ts. Indefaultmode no rule covers it, so the gate asks the user and the loop waits. - On approval, the executor snapshots the file (the checkpoint) and applies the edit.
- The model reruns the tests: the verify phase is just the same tool call again.
- The tests pass. The model replies with text and no tool calls, the response ends with
end_turn, and the loop exits. In the Agent SDK, aResultMessagethen reports the final text, usage, cost and the number of turns: five in this example.
Trade-offs
| Decision | What it gives up | Why it is still worth it |
|---|---|---|
| Agentic search (grep, glob) instead of a vector index | Speed on huge repos; more tool calls per task | Always fresh, no index to build or keep in sync, transparent to the user |
| Runs locally on the user's machine | Isolation from the user's real environment | Uses the real toolchain, git state and credentials the developer already has |
| Mutating tools run one at a time | Some wall-clock time | No two edits or commands racing on the same files |
| Permission prompts by default | Speed and user patience (93% of prompts approved) | A human stays in the loop for anything not covered by a rule; sandboxing and auto mode reduce the friction |
| Compaction by summary | Detail from early in the session | Sessions can run far longer than one context window |
| Model-driven control flow | Predictability; you cannot see the plan in code | Each new model can be used without rewriting a planner; the harness stays thin |
| Denials returned as tool results | Simplicity of throwing an error | The model adapts and keeps going instead of crashing the session |
Confirmed vs inferred
Confirmed by sources
- The loop: model call, tool calls, results fed back, repeat until a response has no tool calls.
- Built-in tool names and categories, and that the Agent SDK runs the same loop as Claude Code.
- Read-only tools can run concurrently;
Edit,WriteandBashrun sequentially. - The six-step permission order and the modes
default,acceptEdits,plan,dontAsk,autoandbypassPermissions. - Denied calls come back to the model as rejection messages.
- Transcripts as JSONL under
~/.claude/projects/, file snapshots before edits,Escto cancel, queued messages read within the same turn. - Tool results cleared first, then summarization; deferred MCP tool schemas; subagents with their own context.
- Sandboxing with bubblewrap and Seatbelt, the 84% prompt reduction, the 93% approval rate and auto mode's classifier design.
- Tech stack: TypeScript, React, Ink, Yoga, Bun.
- Stream event names and the cut-stream behaviour for tool calls.
Inferred or reconstructed
- The component boundaries in the architecture diagram are my grouping, not Anthropic's internal module names.
- The client state machine and the idea that the approval component resolves a promise the executor awaits.
- That the UI renders one keyed row per content block.
- The exact threshold at which tool results are cleared or summarization starts: [N], not published.
- Whether the "five most recent files" detail from September 2025 still holds in current versions.
Build a mini version in JS/TS
The smallest agent that does the same job: four tools, a prompt for anything that changes state, and an explicit loop, using AI SDK 7 and zod. The model string goes through the Vercel AI Gateway.
First, a tiny shell helper that never throws, so a failing command becomes information for the model:
// run.ts
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
const sh = promisify(execFile);
export const clip = (s: string, max = 8000) =>
s.length > max ? `${s.slice(0, max)}\n[truncated]` : s;
export async function run(cmd: string, args: string[]) {
try {
const { stdout, stderr } = await sh(cmd, args, { maxBuffer: 10_000_000 });
return clip(stdout + stderr);
} catch (e: any) {
// Non-zero exit (failing tests, grep with no match) is a result, not a crash
return clip(`exit ${e.code}\n${e.stdout ?? ''}${e.stderr ?? ''}`);
}
}
Next, the permission gate. Read-only tools pass; anything else asks. A denial is returned as a normal result, exactly like Claude Code does:
// gate.ts
import { createInterface } from 'node:readline/promises';
const rl = createInterface({ input: process.stdin, output: process.stdout });
export const closeGate = () => rl.close();
export const gated =
<I>(name: string, fn: (input: I) => Promise<string>) =>
async (input: I) => {
const answer = await rl.question(
`Allow ${name} ${JSON.stringify(input)}? [y/N] `,
);
return answer.trim().toLowerCase() === 'y'
? fn(input)
: 'Denied by the user. Try a different approach or explain what you need.';
};
The read-only tools run without asking. Descriptions matter: they are the only documentation the model gets:
// tools-read.ts
import { readFile } from 'node:fs/promises';
import { tool } from 'ai';
import { z } from 'zod';
import { run } from './run';
export const readTools = {
readFile: tool({
description: 'Read a UTF-8 file, path relative to the project root.',
inputSchema: z.object({ path: z.string() }),
execute: async ({ path }) => readFile(path, 'utf8'),
}),
grep: tool({
description: 'Search the project with a regex. Returns file:line:match.',
inputSchema: z.object({ pattern: z.string() }),
execute: async ({ pattern }) =>
run('grep', ['-rnE', '--exclude-dir=node_modules', pattern, '.']),
}),
};
The tools that change state go through the gate:
// tools-write.ts
import { readFile, writeFile } from 'node:fs/promises';
import { tool } from 'ai';
import { z } from 'zod';
import { gated } from './gate';
import { run } from './run';
const Edit = z.object({
path: z.string(),
oldText: z.string(),
newText: z.string(),
});
const Script = z.object({
script: z.string().describe('npm script name, e.g. "test"'),
});
export const writeTools = {
editFile: tool({
description: 'Replace one exact string that appears once in a file.',
inputSchema: Edit,
execute: gated(
'editFile',
async ({ path, oldText, newText }: z.infer<typeof Edit>) => {
const src = await readFile(path, 'utf8');
if (src.split(oldText).length !== 2)
return 'Error: oldText must match exactly once.';
await writeFile(
path,
src.replace(oldText, () => newText),
);
return 'ok';
},
),
}),
runScript: tool({
description: 'Run an npm script and return its output.',
inputSchema: Script,
execute: gated('runScript', async ({ script }: z.infer<typeof Script>) =>
run('npm', ['run', script]),
),
}),
};
Note () => newText in replace: a plain string replacement would treat $& and friends in the model's code as special patterns.
Finally, the loop. Each generateText call is one step: one model call plus the tools it asked for. If the step made no tool calls, the model is done:
// agent.ts
import { generateText, type ModelMessage } from 'ai';
import { closeGate } from './gate';
import { readTools } from './tools-read';
import { writeTools } from './tools-write';
const MAX_TURNS = 20;
const tools = { ...readTools, ...writeTools };
const instructions = [
'You are a coding agent working in the current directory.',
'Gather context with grep and readFile before editing.',
'After an edit, run the tests. Repeat until they pass, then summarise.',
].join('\n');
async function runAgent(task: string) {
const messages: ModelMessage[] = [{ role: 'user', content: task }];
for (let turn = 1; turn <= MAX_TURNS; turn++) {
const step = await generateText({
model: 'anthropic/claude-sonnet-5.5',
instructions,
messages,
tools,
});
messages.push(...step.responseMessages);
for (const call of step.toolCalls)
console.log(`> ${call.toolName}`, call.input);
if (step.toolCalls.length === 0) return step.text;
}
return `Stopped after ${MAX_TURNS} turns.`;
}
console.log(await runAgent(process.argv.slice(2).join(' ')));
closeGate();
Run it inside an ESM project (top-level await needs "type": "module") with AI_GATEWAY_API_KEY in .env.local: node --env-file=.env.local --import tsx agent.ts "fix the failing test in cart.test.ts". Once you understand the loop, you can delete it: passing stopWhen: isStepCount(20) to a single generateText call, or using ToolLoopAgent, runs the same loop inside the SDK. Good next steps are clearing old tool results in prepareStep and a --plan flag that removes the mutating tools. This week's post on tool calling in TypeScript goes deeper on tool design and stop conditions.
Interview angle
If the frontend system design round says "design an AI coding agent like Claude Code", here is the order I would answer in:
- Clarify scope. Local CLI or web? Can it run shell commands? Who approves risky actions? Is cost per task capped?
- Draw the loop first. Model call, tool calls, results appended, repeat until no tool calls. Name the stop conditions: no tool calls, max turns, budget, user abort.
- Define the tool contract. Name, description, JSON schema input, string result. Errors and denials are results, not exceptions.
- Put the safety boundary in the harness. A permission pipeline (deny rules first, then mode, then allow rules, then ask the user), plus checkpoints for undo and optional OS sandboxing.
- Handle the context window. Stable cached prefix, just-in-time search, clear old tool results, summarize, subagents for isolated work.
- Design the client. Per-block streaming rows, partial JSON for tool input, an approval state that pauses the loop,
AbortControllerforEsc, a queue for mid-run messages. - Close with trade-offs. Index vs search, prompts vs autonomy, local vs sandboxed, and how you would measure success (tasks completed, prompts per task, cost per task).
Sources
- Claude Code Docs: How Claude Code works (accessed 2026-11-16)
- Claude Code Docs: How the agent loop works (Agent SDK) (accessed 2026-11-16)
- Claude Code Docs: Configure permissions (Agent SDK) (accessed 2026-11-16)
- Claude Code Docs: Stream responses in real-time (Agent SDK) (accessed 2026-11-16)
- Claude Docs: How tool use works (accessed 2026-11-16)
- Anthropic Engineering: Effective context engineering for AI agents (2025-09-29)
- Claude Blog: Building agents with the Claude Agent SDK (2025-09-29)
- Anthropic Engineering: Making Claude Code safer with sandboxing (2025-10-20)
- Anthropic Engineering: How we built Claude Code auto mode (2026-03-25)
- The Pragmatic Engineer: How Claude Code is built (2025-09-23)
- AI SDK Docs: Tools and tool calling (accessed 2026-11-16)
- AI SDK Docs: Loop control (accessed 2026-11-16)
- AI SDK Docs: generateText reference (accessed 2026-11-16)
Advertisement