🧠 Core Architecture

QueryEngine.ts

The Brain - Heart of Claude Code's Intelligence

1,295 Lines
46KB Size
src/ Location
TS Language
01

Purpose

QueryEngine is the heart of Claude Code. It owns the entire query lifecycle - managing conversations with the Claude API, orchestrating tool execution, handling permissions, tracking token usage, and managing message history.

💬

API Conversations

Manages the full conversation lifecycle with Claude

🛠

Tool Orchestration

Executes 45+ tools based on model decisions

🔐

Permissions

Enforces security policies for every tool call

📊

Token Tracking

Monitors usage, costs, and budget limits

02

Configuration Type (Complete)

QueryEngine.ts - QueryEngineConfig
export type QueryEngineConfig = {
  cwd: string                          // Working directory
  tools: Tools                         // Available tools (45+)
  commands: Command[]                  // CLI commands (100+)
  mcpClients: MCPServerConnection[]    // MCP server connections
  agents: AgentDefinition[]            // Agent definitions
  canUseTool: CanUseToolFn             // Permission checker
  getAppState: () => AppState          // State getter
  setAppState: (f) => void             // State setter
  initialMessages?: Message[]         // Pre-loaded conversation
  readFileCache: FileStateCache        // File content cache
  customSystemPrompt?: string         // Custom system instructions
  appendSystemPrompt?: string         // Additional instructions
  userSpecifiedModel?: string         // Model override
  fallbackModel?: string              // Fallback if primary fails
  thinkingConfig?: ThinkingConfig      // Extended thinking setup
  maxTurns?: number                    // Max conversation turns
  maxBudgetUsd?: number                // Cost limit in USD
  taskBudget?: { total: number }       // Task budget allocation
  jsonSchema?: Record<string, unknown> // Structured output schema
  verbose?: boolean                    // Debug logging
}
03

Internal State

Field Type Purpose
mutableMessages Message[] Full conversation history
abortController AbortController Turn cancellation signal
permissionDenials SDKPermissionDenial[] Tracks denied permissions
totalUsage NonNullableUsage Accumulated API token usage
discoveredSkillNames Set<string> Skills found during turn
loadedNestedMemoryPaths Set<string> Memory files already loaded
💡 Try This Experiment

Search for mutableMessages in the codebase. How many files reference it? This shows how central QueryEngine is.

grep -r "mutableMessages" src/ --include="*.ts" | wc -l grep -r "QueryEngine" src/ --include="*.ts" -l