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.
Up next
Claude Code update v2.1.162
Claude Code v2.1.162 enhances access control handling on Windows and fixes hangs on launch with restrictive system permissions. The autocomplete menu now inserts commands into the input line for editing before running.
Related stories
- Tokendoctor cut its author’s Claude Code cost 38%
- Claude Code on desktop folds an iPhone Duo to test layouts
- memsaga gives Claude Code’s memory files a git history
- Scientists use Claude least where they say it matters most
- LSP plugin made Claude Code 11% pricier on C++ fixes
- Claude Code 2.1.318: login expiry warning, runner log change
Comments
No comments yet. Be the first.
Join the conversation
Sign in to leave a comment. It appears after moderation.

