Claude Code: Architecture Overview

🇬🇧 English claude-codearchitectureanalysisenglish
📋 Table of Contents (13 sections)
  1. Architecture
  2. Key Metrics
  3. Directory Structure
  4. High-Level Overview
  5. Core Pipeline
  6. State Management
  7. UI Layer
  8. Configuration & Schemas
  9. Build System
  10. Error Handling & Telemetry
  11. Key Files Reference
  12. Concurrency Model
  13. See Also

Architecture

Deep-dive into how Claude Code is structured internally.


Key Metrics

MetricValue
Lines of code~512,000+
Total files~1,900
Agent tools~40
Slash commands~85
React components~140
React hooks~80
Utility modules~331

Directory Structure

src/
├── Core Engine
│   ├── QueryEngine.ts (~46K lines) - Main query lifecycle
│   └── Tool.ts (~29K lines) - Tool system abstraction

├── Tools (src/tools/)
│   ├── BashTool/
│   ├── FileReadTool/
│   ├── FileWriteTool/
│   ├── FileEditTool/
│   ├── AgentTool/
│   ├── MCPTool/
│   └── [40+ tool directories]

├── Commands (src/commands/)
│   ├── commitCommand.ts
│   ├── mcpCommand.ts
│   ├── memoryCommand.ts
│   └── [85+ command files]

├── Services (src/services/)
│   ├── api/ - Anthropic SDK, file uploads, bootstrap
│   ├── mcp/ - Model Context Protocol client
│   ├── oauth/ - Authentication flows
│   ├── lsp/ - Language Server Protocol manager
│   ├── analytics/ - GrowthBook feature flags
│   └── [10+ service modules]

├── UI Layer
│   ├── components/ (~140 React components)
│   ├── hooks/ (~80 React hooks)
│   └── state/ (AppState, selectors)

├── Utilities (src/utils/)
│   └── [331 utility modules]

└── Entry Points
    ├── main.tsx (~1,800 lines)
    ├── ink.tsx - Terminal UI rendering
    └── bootstrap/ - Initialization logic

High-Level Overview

Claude Code is a terminal-native AI coding assistant built as a single-binary CLI. The architecture follows a pipeline model:

User Input → CLI Parser → Query Engine → LLM API → Tool Execution Loop → Terminal UI

The entire UI layer is built with React + Ink (React for the terminal), making it a fully reactive CLI application with components, hooks, state management, and all the patterns you’d expect in a React web app — just rendered to the terminal.


Core Pipeline

1. Entrypoint (src/main.tsx)

The CLI parser is built with Commander.js (@commander-js/extra-typings). On startup, it:

  • Fires parallel prefetch side-effects (MDM settings, Keychain, API preconnect) before heavy module imports
  • Parses CLI arguments and flags
  • Initializes the React/Ink renderer
  • Hands off to the REPL launcher (src/replLauncher.tsx)

2. Initialization (src/entrypoints/)

FileRole
cli.tsxCLI session orchestration — the main path from launch to REPL
init.tsConfig, telemetry, OAuth, MDM policy initialization
mcp.tsMCP server mode entrypoint (Claude Code as an MCP server)
sdk/Agent SDK — programmatic API for embedding Claude Code

Startup performs parallel initialization: MDM policy reads, Keychain prefetch, feature flag checks, then core init.

3. Query Engine (src/QueryEngine.ts, ~46K lines)

The heart of Claude Code. Handles:

  • Streaming responses from the Anthropic API
  • Tool-call loops — when the LLM requests a tool, execute it and feed the result back
  • Thinking mode — extended thinking with budget management
  • Retry logic — automatic retries with backoff for transient failures
  • Token counting — tracks input/output tokens and cost per turn
  • Context management — manages conversation history and context windows

4. Tool System (src/Tool.ts + src/tools/)

Every capability Claude can invoke is a tool. Each tool is self-contained with:

  • Input schema (Zod validation)
  • Permission model (what needs user approval)
  • Execution logic (the actual implementation)
  • UI components (how invocation/results render in the terminal)

Tools are registered in src/tools.ts and discovered by the Query Engine during tool-call loops.

See Tools Reference for the complete catalog.

5. Command System (src/commands.ts + src/commands/)

User-facing slash commands (/commit, /review, /mcp, etc.) that can be typed in the REPL. Three types:

TypeDescriptionExample
PromptCommandSends a formatted prompt to the LLM with injected tools/review, /commit
LocalCommandRuns in-process, returns plain text/cost, /version
LocalJSXCommandRuns in-process, returns React JSX/doctor, /install

Commands are registered in src/commands.ts and invoked via /command-name in the REPL.

See Commands Reference for the complete catalog.


State Management

Claude Code uses a React context + custom store pattern:

ComponentLocationPurpose
AppStatesrc/state/AppStateStore.tsGlobal mutable state object
Context Providerssrc/context/React context for notifications, stats, FPS
Selectorssrc/state/Derived state functions
Change Observerssrc/state/onChangeAppState.tsSide-effects on state changes

The AppState object is passed into tool contexts, giving tools access to conversation history, settings, and runtime state.


UI Layer

Components (src/components/, ~140 components)

  • Functional React components using Ink primitives (Box, Text, useInput())
  • Styled with Chalk for terminal colors
  • React Compiler enabled for optimized re-renders
  • Design system primitives in src/components/design-system/

Screens (src/screens/)

Full-screen UI modes:

ScreenPurpose
REPL.tsxMain interactive REPL (the default screen)
Doctor.tsxEnvironment diagnostics (/doctor)
ResumeConversation.tsxSession restore (/resume)

Hooks (src/hooks/, ~80 hooks)

Standard React hooks pattern. Notable categories:

  • Permission hooksuseCanUseTool, src/hooks/toolPermission/
  • IDE integrationuseIDEIntegration, useIdeConnectionStatus, useDiffInIDE
  • Input handlinguseTextInput, useVimInput, usePasteHandler, useInputBuffer
  • Session managementuseSessionBackgrounding, useRemoteSession, useAssistantHistory
  • Plugin/skill hooksuseManagePlugins, useSkillsChange
  • Notification hookssrc/hooks/notifs/ (rate limits, deprecation warnings, etc.)

Configuration & Schemas

Config Schemas (src/schemas/)

Zod v4-based schemas for all configuration:

  • User settings
  • Project-level settings
  • Organization/enterprise policies
  • Permission rules

Migrations (src/migrations/)

Handles config format changes between versions — reads old configs and transforms them to the current schema.


Build System

Bun Runtime

Claude Code runs on Bun (not Node.js). Key implications:

  • Native JSX/TSX support without a transpilation step
  • bun:bundle feature flags for dead-code elimination
  • ES modules with .js extensions (Bun convention)

Feature Flags (Dead Code Elimination)

import { feature } from 'bun:bundle'

// Code inside inactive feature flags is completely stripped at build time
if (feature('VOICE_MODE')) {
  const voiceCommand = require('./commands/voice/index.js').default
}

Notable flags:

FlagFeature
PROACTIVEProactive agent mode (autonomous actions)
KAIROSKairos subsystem
BRIDGE_MODEIDE bridge integration
DAEMONBackground daemon mode
VOICE_MODEVoice input/output
AGENT_TRIGGERSTriggered agent actions
MONITOR_TOOLMonitoring tool
COORDINATOR_MODEMulti-agent coordinator
WORKFLOW_SCRIPTSWorkflow automation scripts

Lazy Loading

Heavy modules are deferred via dynamic import() until first use:

  • OpenTelemetry (~400KB)
  • gRPC (~700KB)
  • Other optional dependencies

Error Handling & Telemetry

Telemetry (src/services/analytics/)

  • GrowthBook for feature flags and A/B testing
  • OpenTelemetry for distributed tracing and metrics
  • Custom event tracking for usage analytics

Cost Tracking (src/cost-tracker.ts)

Tracks token usage and estimated cost per conversation turn. Accessible via the /cost command.

Diagnostics (/doctor command)

The Doctor.tsx screen runs environment checks: API connectivity, authentication, tool availability, MCP server status, and more.


Key Files Reference

FileLinesPurpose
src/QueryEngine.ts~46KCore query lifecycle, message management
src/Tool.ts~29KTool system abstraction and permissions
src/commands.ts~25KSlash command system
src/main.tsx~1.8KEntry point, startup optimization
src/tools.ts~3KTool registry and loading

Concurrency Model

Claude Code uses a single-threaded event loop (Bun/Node.js model) with:

  • Async/await for I/O operations
  • React’s concurrent rendering for UI updates
  • Web Workers or child processes for CPU-intensive tasks (gRPC, etc.)
  • Tool concurrency safety — each tool declares isConcurrencySafe() to indicate if it can run in parallel with other tools

See Also

← Back to claudecodeanalysis