Claude Code
Claude Code is Anthropic's agentic coding tool that lives in your terminal. It understands your codebase, executes commands, edits files, and manages complex development workflows through natural language. This wiki documents the internal TypeScript source architecture.
💻 Terminal REPL 🤖 Agentic Tool Use 🔌 MCP Integration 🔒 Permission System
📚 What is this & why does it exist?
Claude Code is a terminal-based AI assistant that acts as an intelligent pair programmer. Rather than a simple chatbot, it is an agentic system that can read files, write code, run shell commands, search codebases, and orchestrate multi-step development workflows. This wiki documents the internal source architecture of the Claude Code application itself.
💡 Real-world analogy
Think of Claude Code like a fully-staffed software development office. The REPL is the front desk where you talk to the receptionist (prompt input). Your request goes to the Query Engine (project manager) who figures out which Tools (specialist departments—file editing, shell commands, web search) to dispatch. The Services layer is the back-office infrastructure (API connections, authentication, analytics). Commands are like speed-dial buttons for common requests. And the State system is the shared whiteboard that keeps everyone in sync.
System Architecture
flowchart TD
subgraph Entry["Entry Points"]
MAIN["main.tsx"]
SETUP["setup.ts"]
EP["entrypoints/"]
end
subgraph UI["Terminal UI Layer"]
INK["ink/ - Rendering Engine"]
COMP["components/ - React Components"]
SCREENS["screens/ - REPL, Doctor, Resume"]
HOOKS["hooks/ - State Hooks"]
end
subgraph Core["Core Engine"]
QE["query.ts - Query Engine"]
TOOLS["tools/ - 40+ Tool Implementations"]
CMDS["commands/ - 80+ Slash Commands"]
TASKS["tasks/ - Background Task System"]
end
subgraph Services["Backend Services"]
API["services/api/ - Anthropic API Client"]
MCP["services/mcp/ - MCP Protocol"]
LSP["services/lsp/ - Language Server"]
COMPACT["services/compact/ - Compaction"]
ANALYTICS["services/analytics/ - Telemetry"]
end
subgraph Infra["Infrastructure"]
UTILS["utils/ - 300+ Utilities"]
STATE["state/ - Zustand Store"]
BRIDGE["bridge/ - Remote Control"]
PERMS["types/ - Permissions & Types"]
end
MAIN --> SETUP --> SCREENS
SCREENS --> HOOKS --> QE
QE --> TOOLS
QE --> CMDS
QE --> API
TOOLS --> UTILS
CMDS --> UTILS
COMP --> INK
HOOKS --> STATE
MCP --> TOOLS
API --> BRIDGE
TASKS --> QE
LSP --> UTILS
Request Lifecycle
sequenceDiagram
participant User
participant REPL as screens/REPL.tsx
participant QE as query.ts
participant API as services/api/
participant Tools as tools/*
participant FS as File System
User->>REPL: Type prompt or /command
REPL->>QE: Submit query with context
QE->>QE: Build system prompt + memory
QE->>API: Stream API request
API-->>QE: Assistant response (text + tool_use)
loop Tool Execution Loop
QE->>Tools: Execute tool (bash, file_edit, grep...)
Tools->>FS: Read/write files, run commands
FS-->>Tools: Results
Tools-->>QE: Tool result
QE->>API: Continue with tool results
API-->>QE: Next response
end
QE-->>REPL: Final response
REPL-->>User: Render markdown + diffs
Key insight: Claude Code follows an agentic loop: the model produces tool calls, the runtime executes them, and results feed back to the model until the task is complete. The Query Engine orchestrates this loop with token budgets, compaction, and permission checks at every step.
Core Engine
tools
Plugin architecture with 40+ tools: BashTool, FileEditTool, GrepTool, AgentTool, MCPTool, WebFetchTool, and more. Each tool defines schema, validation, permissions, and execution logic.
commands
80+ slash commands from /commit to /mcp to /review. Three execution models: prompt-based (model-invoked), local JSX (UI), and local (pure function). Extensible via skills, plugins, and MCP.
services
Orchestrates external integrations: Anthropic API client, MCP protocol, LSP language servers, session memory, compaction engine, OAuth, rate limiting, and telemetry.
User Interface
components
389 React (Ink) components: PromptInput, Messages, StructuredDiff, ModelPicker, Settings panels, MCP dialogs, agent views, and the full design system.
hooks
104 hooks powering the interactive REPL: useLogMessages, useCommandQueue, useArrowKeyHistory, useInputBuffer, useVirtualScroll, useDiffData, and model selection.
ink
Custom Ink fork: reconciler, optimizer, render-to-screen, Box/Text/Button components, focus management, keypress parsing, animation hooks, and string width utilities.
Infrastructure & Utilities
utils
Massive utility library: git operations, file system helpers, token counting, permissions engine, sandbox, config management, telemetry, MCP validation, session storage, and more.
bridge
Connects local Claude Code to claude.ai cloud sessions. JWT authentication, permission delegation, WebSocket transport, and cross-version session compatibility.
state
Redux-like state management with Zustand: AppStateStore, React Context provider, selectors, and change notifiers. Central hub for all REPL state.
CLI & Configuration
cli
Structured NDJSON output for machine-readable commands, pretty-print utilities, normalized exit codes, and remote I/O routing.
skills
Extensible command system: user-defined skills from .claude/skills/, bundled skills, MCP skill builders, and skill search service integration.
tasks
Task lifecycle for bash scripts, agents, and workflows. Types: LocalShellTask, LocalAgentTask, RemoteAgentTask, DreamTask. Status tracking and output capture.
keybindings
Vim/Emacs mode defaults, user-configurable bindings, keypress parser, command resolver, and React hook integration.
constants
Tool permissions, prompt templates, message types, system prompt sections, API rate limits, beta features, and XML tag constants.
types
Central type hub: Message union types, permission modes, command interfaces, hook types, branded ID types, and plugin definitions.
Navigation Guide
| Level | What You'll Find | When to Use |
|---|---|---|
| 0 — Project Hub (this page) | Architecture overview, module map, system diagrams | Getting started, finding the right module |
| 1 — Module Overview | Architecture diagram, key components, sub-module cards, walkthrough | Understanding a module's purpose and structure |
| 2 — Sub-Module Deep Dive | Source-level classes, algorithms, configs, code examples | Implementing, debugging, or extending code |
How the Core Engine Connects
The query engine sits at the center, orchestrating tool execution and model communication. Here's how a typical agentic loop flows across module boundaries:
sequenceDiagram participant REPL as REPL (screens/) participant State as AppState (state/) participant QE as QueryEngine (query.ts) participant API as API Client (services/api/) participant Tools as Tool Registry (tools.ts) participant Bash as BashTool participant FE as FileEditTool participant Perms as Permissions (utils/) REPL->>State: setMessages(userInput) REPL->>QE: runQuery(messages, tools) QE->>API: stream(systemPrompt + messages) API-->>QE: tool_use: bash(command) QE->>Perms: checkPermission(bash, command) Perms-->>QE: allowed (or prompt user) QE->>Tools: findToolByName(Bash) Tools->>Bash: execute(command) Bash-->>QE: stdout + stderr QE->>API: tool_result(output) API-->>QE: tool_use: file_edit(path, diff) QE->>FE: execute(path, diff) FE-->>QE: success QE->>API: tool_result(applied) API-->>QE: text(Done! I edited the file.) QE->>State: appendAssistantMessage QE-->>REPL: render response
Key insight: The Query Engine owns the agentic loop. Tools are stateless executors. The permission system gates every tool invocation. AppState is the single source of truth for UI rendering. The API client handles streaming, retries, and rate limiting.
Directory Map
Project source tree
src/
├── main.tsx ← Entry point: CLI bootstrap, arg parsing
├── setup.ts ← System initialization
├── query.ts ← Core query engine (agentic loop)
├── QueryEngine.ts ← Message builder, API orchestration
├── Tool.ts ← Base tool interface & types
├── Task.ts ← Task type definitions
├── commands.ts ← Slash command registry (100+)
├── tools.ts ← Tool registry & assembly
├── tasks.ts ← Task type registry
├── context.ts ← System/user context injection
├── ink.ts ← Terminal UI wrapper
├── history.ts ← Prompt history persistence
├── cost-tracker.ts ← Token & cost accounting
├── tools/ ← 40+ tool implementations
├── commands/ ← 87 slash command modules
├── services/ ← Backend services (API, MCP, LSP...)
├── components/ ← 389 React UI components
├── utils/ ← 300+ utility functions
├── hooks/ ← 104 React state hooks
├── ink/ ← Terminal rendering engine
├── bridge/ ← Remote control integration
├── cli/ ← CLI output formatting
├── state/ ← Zustand state management
├── types/ ← Shared type definitions
├── constants/ ← Global constants
├── keybindings/ ← Keyboard shortcut system
├── skills/ ← Custom skill system
├── tasks/ ← Background task management
├── context/ ← React Context providers
├── entrypoints/ ← App initialization
├── memdir/ ← In-memory MEMORY.md system
├── migrations/ ← Data schema migrations
├── screens/ ← Top-level UI screens
├── server/ ← Direct Connect server mode
├── remote/ ← Remote session management
├── vim/ ← Vim mode keybindings
├── buddy/ ← AI companion sprite
├── plugins/ ← Plugin system bootstrap
├── schemas/ ← JSON Schema definitions
├── voice/ ← Voice mode (Kairos)
└── ... (18 root-level .ts/.tsx files)
Build & Tech Stack
Languages
TypeScript (.ts/.tsx) — 1,332 TS + 552 TSX + 18 JS files
UI Framework
Ink (React for terminal) with custom fork, Zustand state management
Key Protocols
MCP (Model Context Protocol), LSP (Language Server Protocol), OAuth 2.0, WebSocket
API Integration
Anthropic Claude API (streaming), GrowthBook feature flags, telemetry