Why Claude Code's Agent Loop Is 1,421 Lines

A deep dive into query.ts — the 1,729-line async generator at the heart of Claude Code. 10 steps per iteration, 9 continue points, 4-stage compression, streaming tool execution, and error recovery. The engine behind every AI coding agent.

April 6, 2026
Harrison Guo
Video by: HarrisonSecurityLab
Published on YouTube: 2026-04-06
Claude Code AI Agent Architecture Source Code while loop State Machine

Every AI coding agent runs the same core pattern: send context to an LLM, get back text and tool calls, execute tools, feed results back, repeat. LLM talks, program walks.

Claude Code’s implementation lives in query.ts — a 1,729-line async generator where the while(true) loop spans from line 307 to line 1728. That’s 1,421 lines of production state machine logic handling context compression, streaming tool execution, error recovery, and token budget management for millions of users.

This video walks through the entire engine, line by line.

🎧 More Ways to Consume This Content

Comments

This space is waiting for your voice.

Comments will be supported shortly. Stay connected for updates!

Preview of future curated comments

This section will display user comments from various platforms like X, Reddit, YouTube, and more. Comments will be curated for quality and relevance.