Inside Claude Code's 1400-line agent loop

The core agent logic in query.ts of Claude Code v2.1.88 is a 1400-line while(true) loop. Unlike textbook examples, this code handles real-world failures like network drops, context overflows, and script stalls.
The system is a single-threaded async generator. The single-threaded design avoids race conditions when executing tools. Nine conditions govern the loop, including API error retries, token limit handling, and sub-agent management.
A tiered compression system manages context. Aggressive prompt caching saves up to 90% of tokens per session. All events are logged to JSONL files in real-time.
Related stories
- Claude Code 2.1.283 keeps new models out until admins say so
- Claude Code skips AGENTS.md when telemetry is off
- In Claude Code hooks, exit 1 blocks nothing
- In Claude Code, one CLAUDE.md silently kills your AGENTS.md
- Without CLAUDE.md, Claude Code 2.1.277 reads AGENTS.md
- 57% of public Claude Code subagents inherit Bash
Comments
No comments yet. Be the first.
Join the conversation
Sign in with Google to leave a comment. Your name and avatar come from your Google profile, and the comment appears after moderation.
