跳转到内容

Codebase Stats

此内容尚不支持你的语言。

This page provides a quantitative overview of the Claude Code codebase, helping you understand its scale, structure, and where complexity concentrates.

MetricValue
Total files~1,884
Total lines512,000+
Primary languageTypeScript (100% of application code)
RuntimeBun
Build systemBun bundler with feature flags

Claude Code is a large-scale TypeScript application — comparable in size to mid-size open-source projects like Vite or Remix.

The source code is organized into several major directories under src/:

The root of src/ contains the critical orchestration files:

FileRoleEstimated Size
main.tsxCLI framework, Commander.js registration~785KB (largest file)
commands.tsCommand registry, 60+ command management~755 lines
query.tsAgentic loop, turn orchestrationLarge
QueryEngine.tsSession lifecycle manager~1,296 lines
Tool.tsTool interface definition~793 lines
tools.tsTool pool assembly~390 lines
setup.tsPost-init environment setup~478 lines
cost-tracker.tsUsage/cost trackingMedium
pie title Source Code Distribution (estimated)
"tools/" : 25
"utils/" : 20
"services/" : 15
"commands/" : 15
"components/" : 8
"entrypoints/" : 3
"types/" : 3
"Other" : 11

src/tools/ — Tool Implementations (~25% of codebase)

Section titled “src/tools/ — Tool Implementations (~25% of codebase)”

The largest directory, containing 30+ tool implementations:

Tool DirectoryPurpose
AgentTool/Sub-agent spawning and orchestration
BashTool/Shell command execution
FileEditTool/Surgical file editing with diff-based patches
FileReadTool/File reading with image/PDF support
FileWriteTool/File creation and overwriting
GlobTool/File pattern matching (ripgrep-based)
GrepTool/Content search (ripgrep-based)
WebFetchTool/URL fetching and content extraction
WebSearchTool/Web search integration
NotebookEditTool/Jupyter notebook editing
SkillTool/Skill invocation bridge
TodoWriteTool/Task list management
ToolSearchTool/Deferred tool discovery
MCPTool/MCP tool wrapper
TaskOutputTool/Background task monitoring
TaskStopTool/Task termination
EnterPlanModeTool/Plan mode activation
ExitPlanModeTool/Plan mode exit
AskUserQuestionTool/User interaction requests
SendMessageTool/Inter-agent messaging
TeamCreateTool/Agent swarm creation
REPLTool/REPL environment (ant-only)
PowerShellTool/Windows PowerShell support
LSPTool/Language Server Protocol bridge

Cross-cutting utility functions and subsystems:

SubdirectoryPurpose
settings/Configuration loading, validation, caching
permissions/Permission engine, filesystem guards
model/Model selection, deprecation, provider routing
plugins/Plugin loading, caching, hot-reload
hooks/Tool use hooks, file change watching
swarm/Agent swarm reconnection, teammate snapshots

Backend services and external integrations:

SubdirectoryPurpose
api/claude.ts, withRetry.ts, errors.ts, bootstrap.ts
analytics/GrowthBook feature flags, telemetry
mcp/MCP client, server management, config
compact/Auto-compaction, reactive compaction
tools/StreamingToolExecutor, toolOrchestration
oauth/OAuth client and token management
policyLimits/Enterprise policy enforcement
remoteManagedSettings/Remote settings synchronization

60+ user-facing slash commands:

CategoryCommands
Navigation/help, /status, /doctor, /config
Model/model, /fast, /effort
Session/resume, /session, /compact, /clear
Files/files, /diff, /context
Git/commit, /pr_comments, /review
System/login, /logout, /upgrade
Customization/theme, /color, /vim, /keybindings
Development/mcp, /skills, /hooks, /plugin

React/Ink TUI components:

ComponentPurpose
Spinner.jsActivity indicator with mode support
MessageSelector.jsMessage filtering and selection
Various UI primitivesText rendering, progress, dialogs

These are the files you should read first to understand Claude Code’s architecture:

RankFileWhy It Matters
1src/main.tsxCLI entry, Commander.js, REPL launch — the spine
2src/query.tsAgentic loop — the brain
3src/QueryEngine.tsSession lifecycle — SDK/headless entry
4src/Tool.tsTool interface — the contract every tool implements
5src/tools.tsTool pool assembly — which tools are available
6src/commands.tsCommand registry — slash command management
7src/services/api/claude.tsAPI streaming — raw communication layer
8src/services/api/withRetry.tsRetry logic — resilience backbone
9src/services/api/errors.tsError handling — user-facing error messages
10src/setup.tsEnvironment setup — post-init configuration
11src/entrypoints/cli.tsxBootstrap — fast-path routing
12src/entrypoints/init.tsInitialization — configs, proxy, telemetry
13src/services/tools/StreamingToolExecutor.tsConcurrent tool execution
14src/utils/settings/settings.tsConfiguration loading and merging
15src/utils/settings/constants.tsSetting sources and precedence
16src/utils/claudemd.tsCLAUDE.md loading and processing
17src/utils/permissions/permissions.tsPermission engine core
18src/services/compact/autoCompact.tsAuto-compaction logic
19src/tools/BashTool/BashTool.tsShell execution (most complex tool)
20src/tools/AgentTool/AgentTool.tsSub-agent orchestration

The codebase extensively uses:

  • Zod schemas for runtime validation (tool inputs, settings)
  • AsyncGenerator for streaming data flow
  • Discriminated unions for message types and command types
  • Branded types for IDs (AgentId, UUID)
  • Conditional types for tool definitions (BuiltTool<D>)

Bun’s feature() function enables dead code elimination:

// Features are compile-time constants
feature('PROACTIVE') // Proactive agent features
feature('KAIROS') // Assistant mode
feature('BRIDGE_MODE') // Remote control bridge
feature('COORDINATOR_MODE') // Multi-agent coordinator
feature('HISTORY_SNIP') // History snipping
feature('WORKFLOW_SCRIPTS') // Workflow automation
feature('VOICE_MODE') // Voice input
feature('UDS_INBOX') // Unix domain socket messaging
feature('CONTEXT_COLLAPSE') // Context window management

Core runtime dependencies:

CategoryPackages
API@anthropic-ai/sdk
CLI@commander-js/extra-typings, chalk
UIreact, ink (Ink renderer)
Validationzod/v4
Utilitieslodash-es, strip-ansi, picomatch
Markdownmarked
MCP@modelcontextprotocol/sdk
Searchripgrep (via subprocess)

Internal module dependencies (high fan-out files):

FileApproximate Import Count
main.tsx100+ imports
query.ts40+ imports
QueryEngine.ts30+ imports
claude.ts40+ imports
Tool.ts20+ imports

Areas with the highest density of logic:

  1. src/main.tsx — The 785KB monolith handles CLI parsing, MCP config, authentication, and REPL launch. This is the primary candidate for future decomposition.

  2. src/services/api/errors.ts — 1,200+ lines of error classification covering every API error variant across direct, Bedrock, and Vertex providers.

  3. src/services/api/withRetry.ts — 823 lines handling 10+ retry scenarios including persistent retry for unattended sessions, fast mode fallback, and OAuth token refresh.

  4. src/utils/claudemd.ts — Complex file discovery traversing directory trees, handling @include directives, frontmatter parsing, and deduplication.

  5. src/services/tools/StreamingToolExecutor.ts — Concurrent tool execution with ordering guarantees, error propagation, and abort handling.