A comprehensive architectural analysis of Anthropic's official CLI coding assistant
This repository is a restored Claude Code source tree reconstructed primarily from source maps and missing-module backfilling. It is not the original upstream repository state. Some files were unrecoverable from source maps and have been replaced with compatibility shims or degraded implementations so the project can install and run again.
Requirements:
- Bun 1.3.5 or newer
- Node.js 24 or newer
bun install
bun run devPrint the restored version:
bun run versionClaude Code is Anthropic's command-line AI coding assistant. Users interact with Claude through a terminal via natural language, combining slash commands and tool invocations to accomplish software engineering tasks. It supports multiple execution modes:
| Mode | Description |
|---|---|
| Interactive REPL | Real-time terminal conversation β the primary use case |
| MCP Server | Exposes tools to external programs via Model Context Protocol |
| Headless/SDK | Unattended mode for automation pipelines and Agent SDK integration |
| Bridge/Remote | Remote control mode, orchestrated from claude.ai web UI |
| Assistant Daemon | Background daemon process |
src/
βββ main.tsx # CLI entry + command registration (~800KB, core hub)
βββ QueryEngine.ts # Query engine β manages conversation lifecycle
βββ Tool.ts # Tool abstract base class
βββ Task.ts # Background task abstraction
βββ commands.ts # Slash command registry
βββ tools.ts # Tool registry
βββ query.ts # Main interaction loop
βββ context.ts # Context management
βββ setup.ts # Session initialization
βββ cost-tracker.ts # Token cost tracking
βββ history.ts # Conversation history management
βββ interactiveHelpers.tsx # Interactive helper components
β
βββ entrypoints/ # Application entry points
βββ screens/ # Top-level screens (REPL, Doctor, Resume)
βββ components/ # React/Ink UI components (~146 files)
βββ commands/ # Slash command implementations (~60+)
βββ tools/ # Tool implementations (~43)
βββ services/ # Backend service integrations (~38)
βββ hooks/ # React Hooks (~87)
βββ utils/ # Utility functions (~331)
βββ ink/ # Custom terminal rendering engine
βββ bridge/ # Remote control / Bridge mode
βββ vim/ # Vim emulator
βββ state/ # State management
βββ tasks/ # Background task implementations
βββ query/ # Query engine support modules
βββ context/ # React Context providers
βββ keybindings/ # Configurable keyboard shortcuts
βββ skills/ # Skill system
βββ plugins/ # Plugin system
βββ migrations/ # Version migrations
βββ constants/ # Constant definitions
βββ types/ # Type definitions
βββ cli/ # Non-interactive CLI mode
βββ buddy/ # Companion sprite animations
βββ native-ts/ # Native module bindings
βββ voice/ # Voice input integration
main.tsx
βββ Pre-init (MDM reads, Keychain prefetch, startup profiling)
βββ Commander.js parses CLI arguments
βββ Fast-path routing (--version, --dump-system-prompt, --mcp, bridge)
βββ Full REPL initialization
βββ entrypoints/init.ts β Config / env / telemetry / OAuth
βββ setup.ts β Git detection / permissions / session / worktree
βββ replLauncher.tsx β Ink render root
βββ screens/REPL.tsx β Main REPL interaction loop
Every capability exposed to the AI is abstracted as a Tool, defined in Tool.ts:
interface Tool<Input, Output, Progress> {
call(input: Input, context: ToolUseContext): Promise<ToolResult<Output>>
description(): string
inputSchema: ZodSchema // Zod v4 validation
isReadOnly(): boolean // Read-only operation
isDestructive(): boolean // Destructive operation
isConcurrencySafe(): boolean // Safe for concurrent execution
isEnabled(context): boolean // Feature flag gate
interruptBehavior(): InterruptBehavior
}Core Tool Inventory (tools/ directory):
| Category | Tools |
|---|---|
| File Ops | FileEdit, FileRead, FileWrite, Glob, Grep |
| Execution | Bash (shell commands), NotebookEdit (Jupyter) |
| Search | WebSearch, WebFetch, ToolSearch |
| Multi-Agent | Agent (sub-agent), TeamCreate, TeamDelete, SendMessage |
| Task Mgmt | TaskCreate, TaskGet, TaskUpdate, TaskList, TaskStop, TaskOutput |
| Planning | EnterPlanMode, ExitPlanMode |
| Isolation | EnterWorktree, ExitWorktree |
| Scheduling | ScheduleCron (cron jobs) |
| Integration | MCP (dynamic MCP tool proxy), Skill, LSP, Config |
| Other | TodoWrite, Clipboard, Diff, Sleep |
QueryEngine.ts is the heart of the application, managing the full conversation loop:
User Input β Build Messages β Call Anthropic API (streaming) β Parse Response
β β
β β β β β β β Tool Results β β β β β β β β β β β Tool Use detected?
β No β Yes
Output to user Route to Tool
β
Execute & collect result
Key responsibilities:
- Message construction and API invocation
- Streaming response processing
- Tool Use detection and routing
- Context window management (auto-compaction)
- Message queuing and command lifecycle
Uses a lightweight Observable Store pattern:
state/
βββ store.ts # createStore<T>() β getState / setState / subscribe
βββ AppStateStore.ts # AppState type definition (deeply immutable)
βββ AppState.tsx # React Provider + useAppState() selector hook
βββ selectors.ts # Derived state selectors
βββ onChangeAppState.ts # State-change side effects
AppState encompasses: settings, model selection, verbose mode, speculation state, task list, messages, tool permissions, todos, MCP connections, and more.
Automatically compresses conversations when they exceed the context window, with multiple strategies:
- Auto-compact β Triggered automatically
- Micro-compact β Lightweight compression
- API micro-compact β Server-side compression
- Reactive compact β Reactive compression
- Session memory compact β Memory-based compression
Claude Code supports Swarm mode for parallel multi-agent collaboration:
Team Lead (Primary Agent)
βββ Teammate A (InProcessTeammateTask) β Isolated Git Worktree
βββ Teammate B (InProcessTeammateTask) β Isolated Git Worktree
βββ Teammate C (LocalAgentTask) β Sub-agent
Coordination mechanisms:
- Shared TaskList (task assignment & status sync)
- Mailbox messaging system (inter-agent communication)
- SendMessage tool (cross-agent interaction)
| Technology | Purpose |
|---|---|
| Bun | Runtime, bun:bundle feature flags + dead-code elimination |
| TypeScript | Strict mode, Zod v4 runtime validation |
| React Compiler | Optimized re-renders (react/compiler-runtime) |
| Commander.js | CLI argument parsing (@commander-js/extra-typings) |
| Biome | Linting and formatting |
| Build Macros | MACRO.VERSION injection, feature() feature gating |
Built on a heavily customized Ink (React-for-terminal) engine (ink/ directory):
- Custom React Reconciler β terminal output
- Flexbox-style layout engine
- Full terminal I/O layer (ANSI parsing, keyboard/mouse events, focus detection)
- Design system: ThemedBox/Text, Dialog, FuzzyPicker, ProgressBar, Tabs
- Virtual scrolling message list
- Anthropic SDK (
@anthropic-ai/sdk) with streaming - Extended Thinking support
- Multi-model: Sonnet / Opus / Haiku families
- AWS Bedrock / GCP Vertex AI proxies
- Token budget management and cost tracking
- Full MCP Client (connects to external MCP servers for additional tools/resources)
- Full MCP Server (exposes Claude Code tools to external programs)
- OAuth authentication, permission management, Elicitation handling
- OpenTelemetry β Distributed tracing, metrics, logs
- GrowthBook β Feature flags
- Datadog β Monitoring integration
- Startup profiler (
utils/startupProfiler.ts) - FPS tracking (
context/fpsMetrics.tsx)
- OAuth 2.0 (claude.ai authentication)
- API Key support (direct / Bedrock / Vertex)
- mTLS certificate configuration
- Permission system (default / auto / bypass modes)
- Sandbox isolation
- macOS Keychain secure storage
A complete Vim state machine built into the prompt input:
Modes: INSERT / NORMAL
Operators: d(delete), c(change), y(yank), p(paste), >(indent), <(outdent)
Motions: h/l/j/k, w/b/e, 0/^/$, gg, G, f/F/t/T
Text objects: iw, iW, i", i(, i{, i[, it, ip
Features: dot-repeat(.), registers, count prefixes, find/till, case toggle, join lines
The state machine core lives in vim/transitions.ts (driving state changes); vim/operators.ts executes concrete operations.
60+ slash commands, organized by function:
| Category | Commands |
|---|---|
| Core | /help, /init, /login, /logout, /config, /status, /cost, /exit, /clear, /compact, /resume |
| Dev | /commit, /review, /pr-comments, /diff, /bughunter, /autofix-pr |
| Config | /model, /permissions, /mcp, /vim, /theme, /keybindings, /effort |
| Agent | /agents, /tasks, /teleport |
| Integration | /ide, /desktop, /mobile, /chrome, /voice |
| Diagnostics | /doctor, /stats, /memory, /hooks, /skills |
Enables remote orchestration of Claude Code sessions from claude.ai:
claude.ai ββ Bridge API ββ bridgeMain.ts (Worker)
βββ Register as Worker
βββ Poll for work assignments
βββ sessionRunner.ts β Isolated session
βββ Single-session mode
βββ Worktree mode (Git isolation)
βββ Same-directory mode
Bun compile-time feature flags enable dead-code elimination:
if (feature("PROACTIVE")) { /* Internal builds only */ }
if (feature("KAIROS")) { /* Specific releases */ }
if (feature("AGENT_TRIGGERS")) { /* Scheduled triggers */ }Internal builds (ant) and external releases are differentiated via feature flags.
All Tool executions require permission checks:
PermissionMode: default | auto | bypass
PermissionRule: always-allow | always-deny | always-ask
Execution flow: Tool.call() β Permission check β User confirmation (if needed) β Execute β Return result
- Skills β Loaded from
.claude/skills/, user-customizable - Plugins β Installed/updated/removed via CLI, extend functionality
- MCP Skills β Skills built via the MCP protocol
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β User Input (Prompt) β
ββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QueryEngine β
β ββββββββββββ βββββββββββββ ββββββββββββββββββββ β
β β Message βββ API Call βββ Streaming Parser β β
β β Builder β β β β β β
β ββββββββββββ βββββββββββββ ββββββββββ¬ββββββββββ β
β β β
β ββββββββββββββββββββ β
β β Tool Use Detector β β
β ββββββββββ¬ββββββββββ β
β β Text Output β Tool Call β
β ββββββββββββ ββββββββββββββββ β
β β Terminal β β Tool Executor β β
β β Renderer β β + Permissions β β
β β (Ink) β β β β
β ββββββββββββ ββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| Module | Files | Description |
|---|---|---|
utils/ |
~331 | Utility functions (largest dir) |
hooks/ |
~87 | React Hooks |
components/ |
~146 | UI components |
commands/ |
~60+ | Slash commands |
tools/ |
~43 | Tool implementations |
services/ |
~38 | Backend services |
ink/ |
~50 | Terminal rendering engine |
bridge/ |
~33 | Bridge mode |
- Runtime: Bun (with
bun:bundlecompile optimization) - Language: TypeScript (strict mode)
- Minimum Node.js: v18+
- Validation: Zod v4
- Linting: Biome
- Version injection: Build-time
MACRO.VERSION
This document was generated from a deep source code analysis and reflects the project's architectural design.
