Claude CodeArchitecture

Architecture

~1800 files

High-level system design of Claude Code — how the TypeScript monolith is organized, key abstractions, and the data flow between components.

Directory Structure

src/
├── 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.)
├── 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 definitions

Core Abstractions

QueryEngine

Owns 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.

ToolUseContext

Central communication channel between tools and the query loop. Contains options, state accessors, abort controller, analytics.

Design Patterns

Async Generator Architecture

Both QueryEngine and query() are async generators that yield intermediate results for real-time streaming.

Streaming Concurrency

Tools start executing while the model is still generating. StreamingToolExecutor queues tool_use blocks as they arrive.

Cache Sharing (CacheSafeParams)

Frozen system prompt bytes enable zero-cost forked queries for subagents. Identical bytes = automatic prompt cache hit.

DeepImmutable State

Zustand-like AppState with type-safe mutations. setAppState(prev => {...prev, field: newValue}).

Codebase Size Comparison

Lines of code compared to well-known projects (approximate):

Linux 1.0 (1994)
176K
jQuery 3.x
10K
Express.js
14K
React (core)
200K
Claude Code v2.1.88
513K

Top 10 Largest Files

1cli/print.tsFormatted terminal output
5,594
2utils/messages.tsMessage creation & formatting
5,512
3utils/sessionStorage.tsSession persistence
5,105
4utils/hooks.tsReact hooks for REPL
5,022
5screens/REPL.tsxMain REPL screen
5,005
6main.tsxCLI initialization
4,683
7utils/bash/bashParser.tsBash AST parser
4,436
8utils/attachments.tsAttachment prefetch
3,997
9services/api/claude.tsAPI client + streaming
3,419
10services/mcp/client.tsMCP protocol client
3,348

Module Size Breakdown

Tools
140 files · ~65K lines
Services
110 files · ~80K lines
Utils
220 files · ~60K lines
Components
346 files · ~40K lines
Commands
110 files · ~8K lines
Query/Engine
15 files · ~15K lines
Permissions
30 files · ~20K lines
Bridge
12 files · ~13K lines

Technology Stack

TechnologyUsageNotes
TypeScriptPrimary languageStrict mode, Zod for runtime validation
Ink (React)Terminal UICustom fork with layout engine, focus, selection
ZodSchema validationTool input/output schemas, config validation
Yoga LayoutTerminal layoutFlexbox for terminal via yoga-layout
RipgrepFile searchGrepTool wraps rg for fast content search
Tree-sitterBash parsingAST-based security analysis of shell commands
SharpImage processingResize/compress images for API token limits
MCP ProtocolExternal toolsstdio, SSE, HTTP, WebSocket transports
GrowthBookFeature flagsA/B testing with cached gate values

High-Level Data Flow

┌─ Entry Point (cli.tsx / SDK) ─────────────────────────────────────┐
│  Fast-path: --version, --dump-system-prompt, daemon workers       │
│  Full init: MDM settings, keychain, GrowthBook (~135ms parallel)  │
└──────────────────────────┬────────────────────────────────────────┘
                           │
┌─ QueryEngine ────────────▼────────────────────────────────────────┐
│  1. Fetch system prompt parts (CLAUDE.md, tools, env)             │
│  2. Process user input (slash commands, attachments)              │
│  3. Load skills & plugins                                         │
│  4. Yield system init message                                     │
└──────────────────────────┬────────────────────────────────────────┘
                           │
┌─ query() Loop ───────────▼────────────────────────────────────────┐
│  ┌─────────────────────────────────────────────────┐              │
│  │ 1. Context projection (snip, microcompact)      │              │
│  │ 2. Auto-compaction if threshold exceeded        │              │
│  │ 3. API streaming call                           │              │
│  │ 4. Tool execution (streaming or batch)          │              │
│  │ 5. Attachments (memory, skills, tasks)          │              │
│  │ 6. Continue or exit                             │              │
│  └──────────────────┬──────────────────────────────┘              │
│                     │ loop while tools called                     │
└─────────────────────┴─────────────────────────────────────────────┘
                           │
┌─ Terminal ───────────────▼────────────────────────────────────────┐
│  completed | prompt_too_long | aborted | token_budget_completed   │
└───────────────────────────────────────────────────────────────────┘