The complete TypeScript source of Anthropic's Claude Code CLI · Architecture Deep Dive
The original unmodified leaked source is preserved in the
backupbranch.
| Leaked | 2026-03-31 |
| Language | TypeScript (strict) |
| Runtime | Bun |
| Terminal UI | React 19 + Ink (Custom Reconciler) |
| Scale | ~1,900 files · 512,000+ lines of code |
- How It Leaked
- Architecture Overview
- Tool System
- Command System
- Service Layer
- Key Files
- Tech Stack
- Design Patterns
- Directory Structure
- Documentation
- Explore with MCP Server
- Contributing
Chaofan Shou (@Fried_rice) discovered that the published npm package for Claude Code included a .map file referencing the full, unobfuscated TypeScript source — downloadable as a zip from Anthropic's R2 storage bucket.
"Claude code source code has been leaked via a map file in their npm registry!"
Six-layer architecture from CLI entry to external interfaces — with Agent Coordination, Rendering Pipeline, and Zustand State as cross-cutting sidecars.
| L0 Entry | cli.tsx — Fast-path detection for --version, daemon, bridge, CCR modes. Zero module loading on fast paths. |
| L1 Orchestration | main.tsx (4,684 lines) — Commander.js CLI → Auth/Settings init → Tool/Command assembly → MCP/Agent setup → REPL or headless dispatch. |
| L2 Mode | REPL/TUI (React + Ink interactive terminal) or QueryEngine (SDK/Headless async generator for non-interactive use). |
| L3 Query Loop | query.ts — 4-stage state machine: API Call → Stream Response → Tool Dispatch → Continue/Terminal transition. |
| L4 Dispatch | Tools (44+ built-in + MCP, permission-filtered) · Permissions (5-layer cascade) · Commands (85+ slash commands). |
| L5 Services | 23 subsystems: API · MCP · LSP · OAuth · Analytics · Compact · Plugin · Memory · Bridge · State · and 13 more. |
| L6 External | Anthropic API · MCP Servers · LSP Servers · File System · IDE Bridge · Web/OAuth. |
4-stage state machine driven by async generators — from context setup to tool execution, with loop-back on
tool_useand terminal oncompleted.
| Stage 1 — Setup | Build immutable QueryConfig, initialize mutable State, prefetch Memory and Skills in parallel. |
| Stage 2 — API Call | Normalize messages, apply token budgets, stream response from Claude API with max_output_tokens recovery. |
| Stage 3 — Tool Exec | Partition tool calls: read-only tools run in parallel (max 10), writes run serially. Apply context modifiers after each batch. |
| Stage 4 — Transition | Continue (tool_use · compact_retry · token_budget) or Terminal (completed · max_turns · model_error). |
5-layer progressive cascade — each layer can short-circuit with an allow/deny decision.
| Layer | Name | Description |
|---|---|---|
| L1 | validateInput() |
Input schema validation — reject malformed requests |
| L2 | checkPermissions() |
Per-tool permission logic — tool-specific rules |
| L3 | Hooks | settings.json pre-configured allow/deny rules |
| L4 | ML Classifier | Bash-only security classifier for auto-approve |
| L5 | User Dialog | Interactive confirmation — final human-in-the-loop |
Permission Modes
| Mode | Behavior |
|---|---|
default |
Standard — ask for each tool invocation |
auto |
ML classifier auto-approves safe operations |
plan |
Read-only mode — no write operations allowed |
bypassPermissions |
Skip all permission checks |
acceptEdits |
Auto-accept file edit operations |
bubble |
Propagate to parent agent |
Handlers: interactiveHandler (REPL) · coordinatorHandler (workers) · swarmWorkerHandler (async agents)
Five agent types with recursive query isolation — Coordinator dispatches workers via
AgentTooland collects results through<task-notification>.
| Type | Description | Key Parameter |
|---|---|---|
| Sync | Inline execution, immediate return | run_in_background: false |
| Async | Background execution, completion notification | run_in_background: true |
| Fork | Git worktree isolation for parallel edits | isolation: 'worktree' |
| Teammate | Multi-agent team in shared tmux session | team_name + name |
| Remote | CCR cloud environment execution | isolation: 'remote' |
Context Inheritance
Workers inherit: fileReadingLimits · toolPermissionContext · contentReplacementState
Each worker gets: recursive query() call · cloned context · filtered tool set · isolated message window · independent token tracking.
Custom React Reconciler → Yoga WASM layout → Screen buffer diff → ANSI output, with 6 optimization layers.
REPL Component Hierarchy
App (Context Providers: AppState · StatsProvider · FpsMetrics)
└── REPL (main loop + state management)
├── AlternateScreen
│ └── Box (Flex layout)
│ ├── VirtualMessageList (virtual scroll · 100+ components)
│ │ ├── AssistantContent
│ │ ├── ToolUseLoader
│ │ └── ToolOutput
│ └── PromptInput (modes: bash · prompt · task-notification)
├── PermissionRequest (overlay dialog)
├── Spinner (animated processing indicator)
└── Notifications (stacked)
src/tools/— 44+ tools with unifiedTool<Input, Output, Progress>interface. Built viabuildTool()factory.
| Category | Tools |
|---|---|
| File I/O | FileReadTool · FileWriteTool · FileEditTool · NotebookEditTool |
| Search | GlobTool · GrepTool (ripgrep) · WebSearchTool · WebFetchTool |
| Execution | BashTool · SkillTool · MCPTool · LSPTool |
| Agents | AgentTool · SendMessageTool · TeamCreateTool · TeamDeleteTool |
| Tasks | TaskCreateTool · TaskGetTool · TaskUpdateTool · TaskListTool |
| Mode | EnterPlanModeTool · ExitPlanModeTool · EnterWorktreeTool · ExitWorktreeTool |
| Special | ToolSearchTool · SleepTool · CronCreateTool · SyntheticOutputTool · AskUserQuestionTool |
Tool Registration Flow
getAllBaseTools() ← Environment + Feature Flag filtering
↓
getTools() ← Permission deny rules filtering
↓
assembleToolPool() ← Built-in + MCP merge & dedup (built-ins win)
Concurrency: Tools declare isConcurrencySafe() → orchestrator batches read-only tools in parallel (max 10), writes run serially. Context modifiers applied after each batch.
src/commands/— 85+ slash commands from multiple sources, filtered by availability and feature flags.
| Command | Description | Command | Description | |
|---|---|---|---|---|
/commit |
Git commit | /memory |
Persistent memory | |
/review |
Code review | /skills |
Skill management | |
/compact |
Context compression | /tasks |
Task management | |
/mcp |
MCP server management | /vim |
Vim mode toggle | |
/config |
Settings | /diff |
View changes | |
/doctor |
Environment diagnostics | /cost |
Check usage cost | |
/login |
Auth | /theme |
Change theme | |
/context |
Context visualization | /share |
Share session | |
/pr_comments |
PR comments | /resume |
Restore session | |
/desktop |
Desktop handoff | /plan |
Plan mode |
Command Sources (priority order)
- Bundled Skills — always available, fastest
- Built-in Plugin Skills — enabled plugins
- Skill Directory —
.claude/skills/*.md - Workflow Commands —
.claude/workflows/*.toml - Plugin Commands — installed third-party plugins
- Built-in Commands —
COMMANDS()registry
src/services/— 23 subsystems providing cross-cutting infrastructure.
| Service | Key File | Description |
|---|---|---|
| API | claude.ts (125KB) |
Anthropic API client — Direct / Bedrock / Vertex / Foundry multi-provider |
| MCP | client.ts (119KB) |
Model Context Protocol — Stdio / SSE / HTTP / WebSocket transports |
| OAuth | oauth/client.ts |
PKCE flow — Claude.ai / Console / org login |
| LSP | LSPClient.ts |
Language Server Protocol — multi-server management |
| Analytics | growthbook.ts |
GrowthBook feature flags + Datadog + 1P events |
| Compact | compact.ts (60KB) |
Context compression — Auto / Reactive / Micro modes |
| Bridge | bridgeMain.ts (115KB) |
IDE bidirectional communication — VS Code / JetBrains |
| Memory | memdir/ |
Structured persistent memory — MEMORY.md index (200 line cap) |
| Skills | loadSkillsDir.ts |
5-level priority: Bundled → Managed → Project → User → MCP |
| Plugins | plugins/ |
Discovery → install → activate → tool registration |
| State | AppStateStore.ts |
Zustand reactive store — session, remote, bridge, permissions |
| Tasks | tasks/ |
Background task coordination — Shell / Agent / Remote / Workflow types |
| File | Size | Purpose |
|---|---|---|
src/entrypoints/cli.tsx |
303 | CLI entry — fast-path optimization, zero-load --version |
src/main.tsx |
4,684 | Main orchestrator — Commander.js + auth + settings cascade + REPL |
src/QueryEngine.ts |
1,297 | Session engine — async generator, message history, usage tracking |
src/query.ts |
large | Query loop — 4-stage FSM, Continue/Terminal transitions |
src/Tool.ts |
800+ | Tool interface — unified Tool<I,O,P> generic, buildTool() factory |
src/tools.ts |
391 | Tool registry — 3-level filtering, MCP merge, prompt cache ordering |
src/commands.ts |
759 | Command registry — multi-source loading, feature flag gating |
src/context.ts |
190 | Context collection — Git status + CLAUDE.md, session-level memoize |
services/api/claude.ts |
125KB | API core — multi-provider, prompt cache, advanced retry (529) |
services/mcp/client.ts |
119KB | MCP implementation — 4 transports, resource/tool/prompt enumeration |
bridge/bridgeMain.ts |
115KB | Bridge event loop — multi-session, auto-reconnect, sleep detection |
services/compact/compact.ts |
60KB | Compaction algorithm — Auto/Reactive/Micro modes |
| Category | Technology |
|---|---|
| Runtime | Bun |
| Language | TypeScript (strict) |
| Terminal UI | React 19 + Ink (Custom Reconciler + Yoga WASM) |
| CLI Parsing | Commander.js (extra-typings) |
| Schema | Zod v4 |
| Code Search | ripgrep |
| Protocols | MCP SDK · LSP |
| API | Anthropic SDK |
| State | Zustand |
| Telemetry | OpenTelemetry + gRPC |
| Feature Flags | GrowthBook |
| Auth | OAuth 2.0 (PKCE) · JWT · macOS Keychain |
| ⚡ Parallel Prefetch | MDM config, Keychain reads, API preconnect fire in parallel as side-effects before heavy module evaluation — minimizes startup latency. |
| 💤 Lazy Loading | OpenTelemetry (~400KB), gRPC (~700KB) loaded via dynamic import() only when needed. Circular deps broken with require(). |
| 🏗 Feature Flag DCE | feature('FLAG') + Bun bundler physically removes disabled code paths at build time — different builds for internal/public/simple modes. |
| 🔄 Async Generator | async *submitMessage() streams results incrementally — supports REPL, SDK, and remote consumption modes. |
| ⚙️ Concurrency Batching | Read-only tools declare isConcurrencySafe() → parallel batch (max 10). Writes run serially. Context modifiers applied after batch. |
| 🛡 5-Layer Permissions | Validate → Tool Perm → Hook → ML Classifier → User Dialog. Each layer can short-circuit. Progressive fallback to human-in-the-loop. |
| 🤖 Recursive Agent Isolation | runAgent() recursively calls query() with cloned context, filtered tools, isolated messages, and independent token tracking. |
| 📌 Prompt Cache Stability | Tool and command ordering is fixed to keep API prompt prefix stable — maximizes prompt cache hit rate and reduces cost. |
| 🎨 Frame Diff Rendering | React → Yoga → Screen Buffer → Frame Diff → Patch[]. Multi-level: dirty marking, viewport culling, memory pools, 16ms throttle. |
src/
├── main.tsx # Entrypoint — Commander.js CLI parser + React/Ink renderer
├── QueryEngine.ts # Core session engine — async generator
├── Tool.ts # Tool type definitions & buildTool() factory
├── commands.ts # Command registry — multi-source loading
├── tools.ts # Tool registry — 3-level filtering
├── context.ts # System/user context collection
├── cost-tracker.ts # Token cost tracking
│
├── tools/ # Agent tool implementations (44+)
├── commands/ # Slash command implementations (85+)
├── components/ # Ink UI components (~140)
├── services/ # External service integrations (23 subsystems)
├── hooks/ # React hooks (90+, incl. permission checks)
├── types/ # TypeScript type definitions
├── utils/ # Utility functions
├── screens/ # Full-screen UIs (Doctor, REPL, Resume)
│
├── bridge/ # IDE integration (VS Code, JetBrains)
├── coordinator/ # Multi-agent orchestration
├── plugins/ # Plugin system
├── skills/ # Skill system (5-level priority)
├── server/ # Server mode
├── remote/ # Remote sessions (CCR)
├── memdir/ # Persistent memory directory
├── tasks/ # Task management
├── state/ # Zustand state management
│
├── voice/ # Voice input
├── vim/ # Vim mode (full state machine)
├── keybindings/ # Keybinding configuration
├── schemas/ # Config schemas (Zod)
├── migrations/ # Config migrations
├── entrypoints/ # Initialization logic
├── query/ # Query pipeline (FSM)
├── ink/ # Custom Ink renderer (Reconciler + Yoga)
├── buddy/ # Companion sprite (Easter egg)
├── native-ts/ # Native TypeScript utils
├── outputStyles/ # Output styling
└── upstreamproxy/ # Proxy configuration
For in-depth guides, see the docs/ directory:
| Guide | Description |
|---|---|
| Architecture | Core pipeline, startup sequence, state management, rendering, data flow |
| Tools Reference | Complete catalog of all ~44 agent tools with categories and permission model |
| Commands Reference | All ~85 slash commands organized by category |
| Subsystems Guide | Deep dives into Bridge, MCP, Permissions, Plugins, Skills, Tasks, Memory, Voice |
| Exploration Guide | How to navigate the codebase — study paths, grep patterns, key files |
This repo ships an MCP server that lets any MCP-compatible client (Claude Code, Claude Desktop, VS Code Copilot, Cursor) explore the full source interactively.
claude mcp add claude-code-explorer -- npx -y claude-code-explorer-mcpFrom source / VS Code / Cursor / Claude Desktop config
One-liner (from source):
git clone https://github.com/nirholas/claude-code.git ~/claude-code \
&& cd ~/claude-code/mcp-server \
&& npm install && npm run build \
&& claude mcp add claude-code-explorer -- node ~/claude-code/mcp-server/dist/index.jsVS Code — add to .vscode/mcp.json:
{
"servers": {
"claude-code-explorer": {
"type": "stdio",
"command": "node",
"args": ["${workspaceFolder}/mcp-server/dist/index.js"],
"env": { "CLAUDE_CODE_SRC_ROOT": "${workspaceFolder}/src" }
}
}
}Claude Desktop / Cursor — add to config:
{
"mcpServers": {
"claude-code-explorer": {
"command": "node",
"args": ["/path/to/claude-code/mcp-server/dist/index.js"],
"env": { "CLAUDE_CODE_SRC_ROOT": "/path/to/claude-code/src" }
}
}
}| Tool | Description |
|---|---|
list_tools |
List all ~44 agent tools with source files |
list_commands |
List all ~85 slash commands with source files |
get_tool_source |
Read full source of any tool |
get_command_source |
Read source of any slash command |
read_source_file |
Read any file from src/ |
search_source |
Grep across the entire source tree |
get_architecture |
High-level architecture overview |
Contributions to documentation, the MCP server, and exploration tooling are welcome. See CONTRIBUTING.md for guidelines.
Note: The
src/directory is the original leaked source and should not be modified.
Disclaimer — This repository archives source code leaked from Anthropic's npm registry on 2026-03-31. All original source code is the property of Anthropic. This is not an official release and is not licensed for redistribution.