The Agent Loop
This is the most important page in this documentation. Every feature of Claude Code connects to this loop.
When you give Claude Code an instruction — "fix the bug in auth.ts" — it doesn't just call an API and return text. It enters an agentic loop: a cycle of reasoning, tool execution, and re-evaluation that continues until the task is done.
How an Instruction Becomes an Outcome
Click any step to see the implementation details.
The Key Insight: It's a Loop
The critical thing to understand is that steps 3–7 repeat. When the model calls a tool, it gets the result back, reasons about it, and decides what to do next. It might:
- Read a file, then edit it
- Run a test, see it fail, fix the code, run the test again
- Search for code, read multiple files, then make a plan
- Ask for permission, get denied, try a different approach
The loop only stops when the model returns stop_reason: "end_turn" — meaning it has nothing more to do.
A Real Example
Here's what actually happens when you say "Fix the bug in auth.ts":
| Turn | Model Action | Tool | Result |
|---|---|---|---|
| 1 | "Let me read the file first" | Read("src/auth.ts") | File contents (200 lines) |
| 2 | "I see the issue on line 42..." | FileEdit("src/auth.ts", ...) | Diff applied |
| 3 | "Let me verify the fix works" | Bash("npm test") | Tests pass |
| 4 | "The bug was a null check..." | (end_turn) | Final response to user |
Four API calls. Three tool executions. One coherent outcome.
Exit Conditions
The loop terminates when:
| Condition | What Happens |
|---|---|
| end_turn | Model finished — response rendered to user |
| abort | User pressed Ctrl+C — cleanup and stop |
| max_turns | Turn limit reached — return partial result |
| hook_stopped | A lifecycle hook vetoed continuation |
| prompt_too_long | Context exceeded — trigger compaction and retry |
Key Source Files
| File | Purpose |
|---|---|
src/query.ts | Main query loop: prompt assembly, stream processing, message normalization |
src/services/api/claude.ts | Streaming API call orchestration and provider-facing request handling |
src/services/tools/toolExecution.ts | Permission resolution, hook checks, and per-tool execution decisions |
src/services/tools/toolOrchestration.ts | Parallel vs sequential tool scheduling and result collection |
src/screens/REPL.tsx | REPL entry point where user input enters and loop output is rendered |