Architecture
~1800 filesHigh-level system design of Claude Code — how the TypeScript monolith is organized, key abstractions, and the data flow between components.
- Claude Code is a TypeScript monolith of ~512K lines across ~1,800 files — 3× larger than the Linux 1.0 kernel.
- The entry point (cli.tsx) starts fast-path detection immediately, then spawns parallel init tasks: MDM, keychain, GrowthBook — all before the first user prompt.
- QueryEngine.ts owns the conversation lifecycle: it assembles the system prompt, loads skills/plugins, and yields the first message to the loop.
- query.ts is the heart — a 7-phase loop that handles context projection, streaming, tool execution, and token budget management. A single turn can call this loop many times.
entrypoints/cli.tsxBootstrap, fast-path & full initQueryEngine.tsConversation lifecycle ownerquery.ts7-phase agentic loop ~1700 linessrc/
├── entrypoints/ # CLI & SDK entry points
│ ├── cli.tsx # Bootstrap, fast-path (--version, daemon)
│ └── sdk/ # Programmatic API for headless use
├── QueryEngine.ts # Query lifecycle, message buffering
├── query.ts # Main agentic loop state machine (~1700 lines)
├── Tool.ts # Tool interface, ToolUseContext, buildTool()
├── Task.ts # Task abstraction
│
├── tools/ # 50+ tool implementations
│ ├── BashTool/ # Command execution + security (300KB!)
│ ├── FileEditTool/ # String find/replace with diff
│ ├── FileReadTool/ # Read with PDF/notebook/image support
│ ├── AgentTool/ # Subagent spawning + isolation
│ ├── SkillTool/ # User-defined prompt templates
│ ├── MCPTool/ # External tool proxy (MCP protocol)
│ ├── GrepTool/ # Ripgrep-based search
│ ├── GlobTool/ # File pattern matching
│ └── shared/ # Git tracking, multi-agent spawn
│
├── services/ # Core backend services
│ ├── api/ # Claude API client + streaming
│ ├── compact/ # Context window management (13 files)
│ ├── mcp/ # MCP integration (25 files, 470KB!)
│ ├── lsp/ # Language Server Protocol
│ ├── extractMemories/ # Auto-memory background agent
│ ├── SessionMemory/ # Periodic conversation notes
│ ├── analytics/ # Event pipeline (Datadog + 1P)
│ ├── tools/ # Tool orchestration & streaming executor
│ └── plugins/ # Plugin management
│
├── context/ # Context management (CLAUDE.md, git, env)
├── state/ # Zustand-like AppState store
├── coordinator/ # Multi-worker orchestration
├── memdir/ # Memory directory system (~/.claude/projects/)
├── skills/ # Skill loading & bundled skills
├── commands/ # 90+ slash commands (/compact, /model, etc.)
├── bridge/ # Remote session bridge / control plane
├── remote/ # Remote session manager + websocket adapters
├── components/ # Ink UI components (React for terminal)
├── ink/ # Terminal rendering engine (custom fork)
├── hooks/ # React hooks + permission hooks
├── utils/ # Utilities (bash, git, permissions, etc.)
└── types/ # TypeScript type definitionsClaude Code is no longer just a REPL + tools. It now has bridge/remote subsystems, speculation services, and rich session infrastructure around the core query loop.
Key Insight
Core Abstractions
These abstractions are the vocabulary of the rest of the system.
QueryEngineOwns the complete conversation lifecycle. Async generator that yields SDKMessage objects. Handles system prompt assembly, user input processing, and delegates to query() loop.
query()The main agentic loop — a state machine that streams API responses, executes tools, handles recovery, and decides whether to continue or exit.
Tool<Input, Output, Progress>Unified interface for all tools. Built via buildTool() factory. Declares permissions, concurrency safety, and rendering.
ToolUseContextCentral communication channel between tools and the query loop. Contains options, state accessors, abort controller, analytics.
Design Patterns
Both QueryEngine and query() are async generators that yield intermediate results for real-time streaming.
Tools start executing while the model is still generating. StreamingToolExecutor queues tool_use blocks as they arrive.
Frozen system prompt bytes enable zero-cost forked queries for subagents. Identical bytes = automatic prompt cache hit.
Zustand-like AppState with type-safe mutations. setAppState(prev => {...prev, field: newValue}).
High-Level Data Flow
Visual walkthrough of a request from entry to terminal state.
cli.tsx / SDKFast-path: --version, daemon workers | Full init: MDM, keychain, GrowthBook (~135ms parallel)
QueryEngine.tsSystem prompt assembly · User input processing · Skill & plugin loading · Yield init message
query.ts ~1700 linesloops while tools calledContext projection · Auto-compaction · API streaming · Tool execution · Attachments · Continuation
Session endscompleted · prompt_too_long · aborted · token_budget_completed
A second top-level flow now exists beside the local REPL path: bridge/remote execution. In that mode, a bridge loop polls for work, spawns or reconnects sessions, and lets the same QueryEngine/query() core run inside managed remote capacity. Architecturally, that means the agent loop is the center, but not the whole product anymore.
AppState Families
remoteConnectionStatus · replBridgeConnected · remoteBackgroundTaskCount
tasks · agentNameRegistry · coordinatorTaskIndex · viewingAgentTaskId
promptSuggestionEnabled · speculationState · notifications · elicitation
companionReaction · bagelActive · tungstenActiveSession · footerSelection
Codebase Size Comparison
Lines of code compared to well-known projects (approximate):
Top 10 Largest Files
Use this table when you want to know where the codebase is densest and worth deeper reading.
cli/print.tsFormatted terminal outpututils/messages.tsMessage creation & formattingutils/sessionStorage.tsSession persistenceutils/hooks.tsReact hooks for REPLscreens/REPL.tsxMain REPL screenmain.tsxCLI initializationutils/bash/bashParser.tsBash AST parserutils/attachments.tsAttachment prefetchservices/api/claude.tsAPI client + streamingservices/mcp/client.tsMCP protocol clientKey Insight
Module Size Breakdown
Technology Stack
| Technology | Usage | Notes |
|---|---|---|
TypeScript | Primary language | Strict mode, Zod for runtime validation |
Ink (React) | Terminal UI | Custom fork with layout engine, focus, selection |
Zod | Schema validation | Tool input/output schemas, config validation |
Yoga Layout | Terminal layout | Flexbox for terminal via yoga-layout |
Ripgrep | File search | GrepTool wraps rg for fast content search |
Tree-sitter | Bash parsing | AST-based security analysis of shell commands |
Sharp | Image processing | Resize/compress images for API token limits |
MCP Protocol | External tools | stdio, SSE, HTTP, WebSocket transports |
GrowthBook | Feature flags | A/B testing with cached gate values |
Key Insight