Query/Engine Module
15 files · ~15K linesThe Orchestrator — every user message passes through here. QueryEngine.ts owns the conversation lifecycle; query.ts implements the 7-phase agentic loop state machine. This is the heart of everything.
QueryEngine vs query() — the distinction
QueryEngineStateful class · one per conversationOwns the conversation: message history, system prompt assembly, session config. Async generator — call .input() with user text, get an async iterator of SDKMessage back.
query()Stateless loop · called per turnThe inner loop. Runs the 7 phases using state QueryEngine passes in. Does NOT store state — each call is independent. This makes the loop testable and forkable for subagents.
The 7-Phase query() Loop
Each iteration of query.ts goes through exactly these 7 phases. Every tool execution, every compaction, every token passes through this 1729-line file.
LoopState — What query() Carries
The state object passed through all 7 phases. Each phase reads and mutates parts of it.
messagesMessage[]Full conversation history, including all tool calls and results
systemPromptstringAssembled system prompt including project context, CLAUDE.md, memory
toolsTool[]Active tools for this query — built-in + MCP-proxied
tokenBudgetTokenBudgetTracks used/remaining tokens across prompt, output, and tool results
loopCountnumberCurrent iteration count — guard against infinite tool loops
stopReasonStopReason | nullend_turn | max_tokens | tool_use | error | cancelled
permissionRulesPermissionRule[]Session-scoped rules the user has approved during this conversation
Token Budget Math — 200K Context Window
How the 200K context window of Claude Sonnet splits up in a typical session.
Key Files
QueryEngine.ts~1295 linesConversation lifecycle, system prompt assembly, message buffering
query.ts~1729 linesThe main agentic loop state machine, 7 distinct phases
Task.ts~300 linesTask abstraction for multi-agent parallel work
entrypoints/cli.tsx~200 linesCLI bootstrap — fast-path (--version, daemon) then calls QueryEngine
entrypoints/sdk/~400 linesHeadless SDK entrypoint — exposes QueryEngine as a programmatic API
Related Pages
Phase 4 executes tools. 43 tools, all flowing through StreamingToolExecutor.
Phase 2 triggers compaction. Phase 3 uses the API client. Phase 7 fires extractMemories.
Phase 4 checks permissions before every tool execute.
Bridge wraps QueryEngine for headless/SDK use. Same loop, no terminal.
The main site's full analysis of the query loop with annotated code.