The full internal source code of Anthropic's Claude Code CLI (v1.0.x), reverse-engineered and decompiled from the official npm package.
This repository contains decompiled source code from Anthropic's proprietary Claude Code product. It is published for educational and research purposes only. All intellectual property belongs to Anthropic, PBC. This code is not licensed for redistribution, modification, or commercial use. Use responsibly.
Claude Code is Anthropic's agentic AI coding assistant β a terminal-based CLI tool that integrates the Claude AI model directly into your development workflow. It can:
- Read, write, and edit files autonomously
- Execute shell commands with intelligent sandboxing
- Search codebases using grep, glob, and ripgrep
- Interact with MCP (Model Context Protocol) servers
- Manage multi-agent workflows ("swarms")
- Connect to IDEs (VS Code, JetBrains, etc.)
- Resume, branch, and fork conversations
- Operate in interactive (REPL) and headless (SDK) modes
This repository contains the complete decompiled src/ directory β every internal module, every tool, every prompt, every hook.
src/
βββ main.tsx # CLI entrypoint β argument parsing, migrations, session bootstrap
βββ query.ts # Core agentic query loop β the heart of Claude Code
βββ QueryEngine.ts # Headless query engine for SDK/non-interactive modes
βββ Tool.ts # Tool type system β defines the interface for ALL tools
βββ commands.ts # Slash-command registry and loader
βββ context.ts # System & user context builders
βββ cost-tracker.ts # Token usage & cost tracking
βββ history.ts # Session history management
βββ setup.ts # First-run setup and onboarding
βββ tools.ts # Tool pool assembly and filtering
βββ tasks.ts # Background task definitions
β
βββ screens/ # Full-screen TUI screens
β βββ REPL.tsx # The main REPL (895KB, 5,006 lines β the largest file)
β βββ Doctor.tsx # Diagnostic screen
β βββ ResumeConversation.tsx
β
βββ tools/ # All 40+ built-in tools
β βββ BashTool/ # Shell command execution (with sandbox)
β βββ FileEditTool/ # AI-powered file editing
β βββ FileReadTool/ # File reading with range support
β βββ FileWriteTool/ # Full file creation/overwrite
β βββ GrepTool/ # Ripgrep-powered code search
β βββ GlobTool/ # File pattern matching
β βββ AgentTool/ # Sub-agent spawning (multi-agent)
β βββ WebSearchTool/ # Web search capability
β βββ WebFetchTool/ # URL content fetching
β βββ MCPTool/ # MCP server tool proxying
β βββ NotebookEditTool/ # Jupyter notebook editing
β βββ REPLTool/ # REPL tool execution
β βββ LSPTool/ # Language Server Protocol integration
β βββ TaskCreateTool/ # Background task creation
β βββ TeamCreateTool/ # Multi-agent team creation
β βββ TodoWriteTool/ # TODO list management
β βββ SkillTool/ # Skill/workflow invocation
β βββ SleepTool/ # Timed delay tool
β βββ ScheduleCronTool/ # Cron job scheduling
β βββ SendMessageTool/ # Inter-agent messaging
β βββ ... (40+ tools total)
β
βββ components/ # 140+ Ink (React-for-CLI) UI components
β βββ Messages.tsx # Conversation message renderer
β βββ PromptInput/ # User input with autocomplete, vim mode
β βββ StatusLine.tsx # Bottom status bar
β βββ Spinner.tsx # Activity spinner with tips
β βββ ModelPicker.tsx # Model selection dialog
β βββ ThemePicker.tsx # Theme customization
β βββ PermissionRequest.tsx # Tool permission dialogs
β βββ StructuredDiff/ # Side-by-side diff viewer
β βββ VirtualMessageList.tsx # Virtualized scrolling message list
β βββ ScrollKeybindingHandler.tsx # Keyboard navigation
β βββ ConsoleOAuthFlow.tsx # OAuth authentication flow
β βββ ... (140+ components)
β
βββ hooks/ # 85+ React hooks
β βββ useCanUseTool.tsx # Tool permission checking
β βββ useReplBridge.tsx # Remote control bridge (115KB!)
β βββ useVoiceIntegration.tsx # Voice mode (99KB!)
β βββ useTypeahead.tsx # Autocomplete engine (212KB!)
β βββ useGlobalKeybindings.tsx # Keyboard shortcut system
β βββ ... (85+ hooks)
β
βββ utils/ # 300+ utility modules
β βββ auth.ts # Authentication (OAuth, API keys, keychain)
β βββ config.ts # Configuration management
β βββ hooks.ts # Hook lifecycle system (159KB!)
β βββ messages.ts # Message construction & normalization (193KB!)
β βββ sessionStorage.ts # Session persistence (180KB!)
β βββ teleport.tsx # Session teleportation (cloud sync, 175KB!)
β βββ attachments.ts # File/memory attachments (127KB!)
β βββ worktree.ts # Git worktree operations
β βββ permissions/ # Permission system
β βββ model/ # Model selection & capabilities
β βββ settings/ # Settings management
β βββ swarm/ # Multi-agent swarm system
β βββ mcp/ # MCP client utilities
β βββ telemetry/ # Analytics & tracing
β βββ sandbox/ # Command sandboxing
β βββ ... (300+ files)
β
βββ services/ # Backend service integrations
β βββ mcp/ # Model Context Protocol client
β βββ oauth/ # OAuth 2.0 flow
β βββ analytics/ # GrowthBook, Statsig, telemetry
β βββ lsp/ # Language Server Protocol client
β βββ compact/ # Auto-compaction (context management)
β βββ api/ # Anthropic API client
β βββ plugins/ # Plugin system
β βββ tips/ # User tips & suggestions
β βββ voice.ts # Voice input/STT
β
βββ commands/ # 100+ slash commands (/command)
β βββ init.ts # /init β project initialization
β βββ commit.ts # /commit β git commit
β βββ review.ts # /review β code review
β βββ compact/ # /compact β context compaction
β βββ doctor/ # /doctor β diagnostics
β βββ mcp/ # /mcp β MCP server management
β βββ model/ # /model β model switching
β βββ teleport/ # /teleport β session sync
β βββ ultraplan.tsx # /ultraplan β advanced planning
β βββ insights.ts # /insights β usage analytics (113KB!)
β βββ ... (100+ commands)
β
βββ bridge/ # Remote Control Bridge (mobile/web)
β βββ replBridge.ts # Bridge core (100KB!)
β βββ bridgeMain.ts # Bridge lifecycle (115KB!)
β βββ remoteBridgeCore.ts # Remote session bridging
β βββ jwtUtils.ts # JWT authentication
β βββ trustedDevice.ts # Device trust management
β
βββ state/ # Global state management
β βββ AppState.tsx # React context-based state
β βββ AppStateStore.ts # State store definition
β βββ store.ts # Zustand-like store
β
βββ types/ # TypeScript type definitions
β βββ message.ts # Message types
β βββ permissions.ts # Permission types
β βββ hooks.ts # Hook event types
β βββ plugin.ts # Plugin types
β
βββ entrypoints/ # Multiple entry points
β βββ cli.tsx # Interactive CLI entrypoint
β βββ mcp.ts # MCP server mode
β βββ sdk/ # SDK entrypoint
β βββ init.ts # Initialization
β
βββ coordinator/ # Multi-agent coordinator mode
β βββ coordinatorMode.ts # Orchestrates agent teams
β
βββ plugins/ # Plugin system
β βββ builtinPlugins.ts # Built-in plugin loader
β βββ bundled/ # Bundled plugins
β
βββ skills/ # Skill system
β βββ bundledSkills.ts # Built-in skills registry
β βββ loadSkillsDir.ts # Dynamic skill loader
β βββ bundled/ # Bundled skill definitions
β
βββ migrations/ # Settings/config migrations
β βββ migrateSonnet45ToSonnet46.ts
β βββ migrateOpusToOpus1m.ts
β βββ ... (11 migration scripts)
β
βββ vim/ # Vim mode implementation
β βββ motions.ts # Cursor motions
β βββ operators.ts # Vim operators
β βββ textObjects.ts # Text objects
β βββ transitions.ts # Mode transitions
β
βββ buddy/ # Companion sprite system (Easter egg)
β βββ CompanionSprite.tsx # Animated ASCII companion
β βββ sprites.ts # Sprite definitions
β βββ companion.ts # Companion logic
β
βββ voice/ # Voice mode
β βββ voiceModeEnabled.ts # Voice feature gate
β
βββ ink/ # Custom Ink (React terminal) extensions
βββ keybindings/ # Keybinding system
βββ outputStyles/ # Output formatting styles
βββ schemas/ # Zod schemas
βββ constants/ # Constants and configuration
βββ context/ # React contexts
βββ native-ts/ # Native TypeScript helpers
βββ server/ # Direct-connect server
βββ remote/ # Remote session management
βββ upstreamproxy/ # Upstream proxy support
βββ moreright/ # Layout system
βββ memdir/ # In-memory directory abstraction
The core of Claude Code is an async generator function query() that:
- Manages the agentic loop (model call β tool execution β model call β ...)
- Handles auto-compaction when context gets too large
- Implements reactive compaction for
prompt_too_longerrors - Supports
max_output_tokensrecovery with automatic continuation - Manages microcompact (cache-aware context shrinking)
- Tracks token budgets (
task_budgetAPI parameter) - Handles streaming tool execution (parallel tool calls)
Claude Code actively detects and terminates if running under a debugger:
if ("external" !== 'ant' && isBeingDebugged()) {
process.exit(1);
}It checks for --inspect, --debug, Node.js inspector API, and NODE_OPTIONS environment variables. Internal Anthropic builds ("ant") bypass this check.
The codebase uses bun:bundle feature flags extensively:
feature('COORDINATOR_MODE')β Multi-agent orchestrationfeature('KAIROS')β Assistant mode (proactive agent)feature('VOICE_MODE')β Voice inputfeature('BRIDGE_MODE')β Mobile/web remote controlfeature('SSH_REMOTE')β SSH remote executionfeature('DIRECT_CONNECT')β Direct server connectionsfeature('ULTRAPLAN')β Advanced planning modefeature('BUDDY')β Companion sprite Easter eggfeature('FORK_SUBAGENT')β Agent forkingfeature('TRANSCRIPT_CLASSIFIER')β Auto-mode safety classifierfeature('EXPERIMENTAL_SKILL_SEARCH')β Skill discoveryfeature('WEB_BROWSER_TOOL')β Browser automation tool
Code marked "external" === 'ant' is Anthropic-internal only and dead-code-eliminated from public builds.
Claude Code supports multiple authentication methods:
- OAuth 2.0 via
claude.aisubscription - API Keys from
ANTHROPIC_API_KEYenvironment variable - macOS Keychain integration for secure key storage
- API Key Helper β custom scripts that provide API keys on demand
- File Descriptor β keys passed via fd (for subprocess isolation)
- AWS STS β Bedrock authentication with credential refresh
- GCP β Vertex AI authentication
- Foundry β Azure Foundry authentication
A sophisticated multi-level permission system:
- Permission Modes:
default,plan,auto,bypassPermissions - Auto-Mode Classifier: A transcript-based safety classifier that auto-approves safe actions
- Hook-Based Permissions: External scripts can approve/deny tool usage
- Always Allow/Deny Rules: Configurable per-tool permission patterns
- Sandbox: Command sandboxing using OS-level primitives
- Trust Dialog: First-run workspace trust confirmation
Claude Code can be controlled remotely from mobile/web:
- WebSocket-based real-time communication
- JWT authentication for device trust
- Capacity wake system for mobile push notifications
- Message bridging between local and remote sessions
- QR code generation for mobile connection
Full multi-agent orchestration support:
- Agent Types: Custom agents via
.claude/agents/directory - Team Creation:
TeamCreateToolspawns agent teams - Inter-Agent Communication:
SendMessageToolfor mailbox messaging - Coordinator Mode: Central orchestrator that delegates to workers
- In-Process Teammates: Agents run in the same process (lightweight)
- tmux/iTerm2 Backends: Agents in separate terminal panes
Detailed financial tracking:
- Per-model token usage (input, output, cache read, cache creation)
- USD cost calculation using internal pricing tables
- Web search request counting
- Session cost persistence and restoration on resume
- Cost threshold dialogs (warns at spending limits)
Four-tier context management to stay within model limits:
- Snip Compact β Removes old messages from the middle
- Microcompact β Cache-aware content shrinking (preserves cache keys)
- Auto Compact β Full summarization of conversation history
- Reactive Compact β Emergency compaction on API
prompt_too_longerrors - Context Collapse β Staged collapsing of tool-use sequences
Comprehensive session persistence:
- JSONL-based transcript storage
- Session search by title, content, and metadata
- File history snapshots for undo/redo
- Attribution tracking for git commit decoration
- Content replacement records for resumed sessions
- Background session management (concurrent sessions)
A full React-based terminal UI built on Ink:
- Virtual scrolling message list
- Structured diff viewer
- Model picker dialog
- Theme system with multiple themes
- Vim mode with full motion/operator/text-object support
- Fullscreen layout with alternate screen buffer
- Animated spinner with contextual tips
Extensible plugin architecture:
- DXT format β Declarative extension toolkit
- MCP servers β Model Context Protocol integration
- Bundled plugins β Built-in extensions (GitHub, Slack, etc.)
- Marketplace β Official plugin marketplace support
- Version management β Automatic updates and orphan cleanup
Full voice input support:
- Speech-to-Text streaming
- Voice keyterm detection
- Integration with the prompt input system
- 99KB of voice integration hooks
Cloud-based session synchronization:
- Transfer sessions between machines
- Git-based session state serialization
- Branch checkout for teleported sessions
- Error recovery and retry logic
Comprehensive analytics infrastructure:
- GrowthBook β Feature flag & A/B testing
- Statsig β Event logging
- OpenTelemetry β Session tracing with Perfetto export
- BigQuery exporter β Internal data pipeline
- Diagnostic logging β PII-free diagnostic events
Automated model string migrations:
Sonnet 4.5 β Sonnet 4.6Opus β Opus 1MFennec β Opus(internal codename)Legacy Opus β Current Opus- Model-specific config updates
| Metric | Value |
|---|---|
| Total Files | 1,902 |
| TypeScript/TSX Files | 1,884 |
| Total Lines of Code | 512,664 |
| Largest File | screens/REPL.tsx (895 KB, 5,006 lines) |
| Main Entry Point | main.tsx (803 KB, 4,684 lines) |
| Built-in Tools | 40+ |
| Slash Commands | 100+ |
| UI Components | 140+ |
| React Hooks | 85+ |
| Utility Modules | 300+ |
| Technology | Purpose |
|---|---|
| TypeScript | Primary language |
| Bun | Runtime & bundler (via bun:bundle feature flags) |
| React / Ink | Terminal UI framework |
| Anthropic SDK | Claude API client |
| Commander.js | CLI argument parsing |
| Zod | Runtime type validation |
| chalk | Terminal coloring |
| execa | Child process execution |
| lodash-es | Utility functions |
| MCP SDK | Model Context Protocol |
| GrowthBook | Feature flags |
| Codename | Meaning |
|---|---|
| Tengu | Analytics event prefix (tengu_*) β Claude Code's internal name |
| Kairos | Assistant/proactive mode |
| Fennec | An earlier Claude model variant |
| Lodestone | Deep link / URL protocol handler |
| Tungsten | An experimental tool type |
| Walrus | Reactive compact feature |
| Torch | An experimental command |
| Ultraplan | Advanced multi-step planning |
| Grove | A UI component system |
| Buddy | Animated companion sprite |
Claude Code is distributed as a compiled JavaScript bundle via npm (@anthropic-ai/claude-code). The source was obtained by:
- Installing the official npm package
- Extracting the bundled JavaScript
- Decompiling/reformatting the minified source
- Reconstructing the module structure from import paths
- Recovering TypeScript types from the build artifacts
The code retains original comments, function names, and module structure β Anthropic did not obfuscate the source beyond standard bundling.
This code is the intellectual property of Anthropic, PBC. It is published here for:
- Security research and vulnerability analysis
- Understanding AI agent architectures
- Educational purposes
Do NOT use this code to:
- Build competing products
- Bypass security or licensing mechanisms
- Distribute modified versions commercially
If Anthropic requests removal, this repository will be taken down immediately.
This is a static snapshot of the decompiled source. No contributions to the source code are accepted. Issues documenting findings, architecture insights, or security observations are welcome.
This code is NOT open source. It is proprietary software owned by Anthropic, PBC. No license is granted for use, modification, or distribution.
β Star this repo if you found it insightful
Understanding how AI agents work internally is key to building better ones.