Claude Code Internals: An AI-Assisted Analysis of the Leaked Source
Methodology note: The Claude Code CLI source leaked today (March 31, 2026). This analysis was produced by pointing Claude Code (Opus 4.6) at its own source tree and asking it to explore the codebase. I reviewed the findings, verified claims where possible, and added my own observations. The technical content comes from Claude’s analysis. The editorial is mine.
The leaked source is ~512K lines of TypeScript across 1,884 files, running on Bun. What follows is a structured breakdown of the architecture, interesting implementation details, and unreleased features found in the code.
1. Architecture Overview
| Metric | Value |
|---|---|
| Language | TypeScript (100%) |
| Runtime | Bun |
| UI framework | Custom React-based terminal renderer |
| Files | 1,884 |
| Lines of code | ~512,000 |
| Size on disk | 33 MB |
main.tsx | 803 KB |
| Built-in tools | 80+ |
| Top-level modules | 35 |
The application is a single Bun-bundled binary. The entry point (main.tsx) performs parallel prefetch of system info (MDM, Keychain) during module load, and routes commands through Commander.js.
Core loop: user input → API call → stream response → execute tool calls → loop until stop_reason="end_turn" or budget exceeded.
2. Custom Terminal Renderer
The ink/ directory (~50 files) is not the npm ink package. It’s a from-scratch React-based terminal UI engine:
- Layout engine: Pure TypeScript port of Meta’s Yoga flexbox engine. No C++ bindings. Supports flex-direction, flex-grow/shrink, align-items, justify-content, margins, padding.
- Rendering pipeline: React Fiber → custom DOM → Yoga layout → screen buffer → terminal output.
- React reconciler: Custom Fiber reconciler (
reconciler.ts) bridging React to the terminal DOM. - Interactive features: Mouse tracking with hit-testing, text selection with word/line boundaries, OSC 8 hyperlinks, clipboard integration, alternative screen mode.
- Input handling: Extended key support for Kitty protocol, CSI encoding. Full terminal capability detection for iTerm2, Kitty, xterm.js, multiplexers.
- Terminal I/O layer: Custom parser (
ink/termio/) for ANSI, CSI, OSC, SGR, DEC sequences.
3. Tool Execution Model
Tools are defined with a consistent interface:
1
2
3
4
5
6
7
8
interface Tool {
name: string
schema: z.ZodSchema // Zod input validation
description: string
execute(input, context: ToolUseContext): Promise<ToolResult>
canUseInNonInteractive?: boolean
isConcurrencySafe?: boolean
}
Key implementation detail: the StreamingToolExecutor begins executing tools as they arrive in the API stream, not after the full response completes. Tools marked isConcurrencySafe run in parallel. Non-concurrent tools get exclusive access. Results are buffered and emitted in request order.
Large tool results are persisted to disk — the conversation holds a file reference, not the content. This prevents memory bloat in long-running sessions.
4. Permission System
Three-tiered architecture:
Tier 1 — Rules-based fast path. Pattern matching on tool inputs (file paths, shell commands) using glob and regex. Three classifications: always-allow, always-ask, always-deny. Implemented in utils/permissions/filesystem.ts (62 KB).
Tier 2 — ML classifier. For ambiguous cases, calls the Claude API to classify whether a bash command or file edit is dangerous. Feature-gated as BASH_CLASSIFIER and TRANSCRIPT_CLASSIFIER.
Tier 3 — User prompts. Interactive approval dialogs with plan mode preview.
Additional protections: symlink traversal detection prevents sandbox escapes via symlinks to sensitive paths.
5. Query Engine (Two-Layer Design)
The LLM interaction loop is split:
QueryEngine.ts(1,295 lines) — Outer loop. Agentic control: retries, budget enforcement (per-model token + USD tracking), permission checks, max turn limits.query.ts(1,729 lines) — Inner loop. Mechanics: system prompt assembly, message history management, API streaming, hook execution, tool result collection.
Budget tracking is granular — tracks total USD cost, API duration, cache read/creation tokens, tool execution duration, and lines changed per session.
6. Build System and Feature Gates
The codebase uses Bun’s dead-code elimination (DCE) extensively. Feature gates are compile-time constants — entire subsystems are stripped from public builds.
Notable gates found in the source:
| Gate | Purpose |
|---|---|
KAIROS | Long-running assistant mode |
COORDINATOR_MODE | Multi-worker agent distribution |
VOICE_MODE | Speech input |
PROACTIVE | Autonomous agent behavior |
ULTRAPLAN | Browser-based plan approval |
KAIROS_DREAM | Nightly memory distillation |
TORCH | Unknown (1 reference) |
LODESTONE | Unknown (6 references) |
ANTIADDISTILLATION_CC | Model distillation prevention |
NATIVE_CLIENT_ATTESTATION | Secure enclave verification |
BYOC_ENVIRONMENT_RUNNER | Bring-your-own-compute |
PERFETTO_TRACING | Performance profiling |
Internal builds are further gated by process.env.USER_TYPE === 'ant', which enables stricter system prompts, enhanced telemetry, pre-release model access via getAntModelOverrideConfig(), and advanced agent spawning. Bun constant-folds these checks at build time so none of it ships in public binaries.
7. Unreleased Features
7.1 KAIROS — Persistent Background Agent
The assistant/ directory implements a long-running agent mode:
- Append-only daily logs in
logs/YYYY/MM/YYYY-MM-DD.md - GitHub webhook subscriptions (
KAIROS_GITHUB_WEBHOOKS) - Push notifications (
KAIROS_PUSH_NOTIFICATION) - Channel integrations (
KAIROS_CHANNELS) - Dream mode (
KAIROS_DREAM) — nightly memory distillation - Timezone-aware session rollovers
This is Claude Code that persists across terminal sessions — a background daemon that monitors your project.
7.2 ULTRAPLAN — Browser-Based Plan Approval
- Keyword detection triggers on
ultraplanorultrareview - Sends plan to a remote session with browser-based UI
- User can edit the plan in-browser and “teleport” it back to terminal
- Teleport sentinel:
__ULTRAPLAN_TELEPORT_LOCAL__ - 30-minute timeout, rejection count tracking
- Polling with exponential backoff
7.3 Coordinator Mode — Multi-Agent Distribution
The coordinator/ directory implements:
- Multiple worker processes (one per logical CPU)
- Centralized task distribution across workers
- Shared context via team mailbox +
SendMessagetool
7.4 Voice Mode
- Hold-to-talk with language detection and English fallback
- 16kHz mono audio recording
- Platform-specific: native audio APIs (macOS/Windows/Linux), fallback to SoX/arecord
- Lazy-loads audio capture on first keypress (1-8s cold start)
- Kill-switch:
tengu_amber_quartz_disabled
7.5 Buddy System — Companion Creatures
This one’s unexpected. The buddy/ directory implements a deterministic companion creature generator:
- 18 species: duck, goose, blob, cat, dragon, octopus, owl, penguin, turtle, snail, ghost, axolotl, capybara, cactus, robot, rabbit, mushroom, chonk
- 5 stats: DEBUGGING, PATIENCE, CHAOS, WISDOM, SNARK (1-100 each)
- Rarity tiers: common (60%), uncommon (25%), rare (10%), epic (4%), legendary (1%)
- 1% chance of shiny variant
- Hats: none, crown, tophat, propeller, halo, wizard, beanie, tinyduck
- Eyes:
·,✦,×,◉,@,° - Deterministic per user (Mulberry32 PRNG seeded with user ID +
friend-2026-401salt) - Teaser window: April 1-7, 2026 (rainbow text on
/buddycommand)
Peak stat gets 50-80 bonus points, dump stat gets penalized. Rarity sets the floor (legendary starts at 50 minimum).
8. Undercover Mode
Auto-enabled in public/open-source repositories to prevent internal codename leaks:
- Strips model codenames (Capybara, Tengu, etc.) from commits and PRs
- Blocks
Co-Authored-Byattribution lines - Force-enable via
CLAUDE_CODE_UNDERCOVER=1 - Internal repo allowlist in
commitAttribution.ts - One companion species name is obfuscated via
String.fromCharCode()to bypass the build system’s own codename scanner
9. Agent Spawning and Isolation
The AgentTool supports three isolation modes:
- In-process — shared memory, same context
- Git worktree — temporary
git worktreegives child agent a sandboxed repo copy - Remote (CCR) — cloud execution via Cross-Code Runtime
Child agents get forked message context with UUID tracking. Background agents emit progress updates and can be queried via TaskGet. Inter-agent communication uses SendMessage over a shared mailbox.
CCR sessions use beta API header anthropic-beta: ccr-byoc-2025-07-29, with paginated event history and 15-second long-polling.
10. MCP Integration
Claude Code is a first-class MCP (Model Context Protocol) client:
- Transport: stdio, SSE, WebSocket
- Auto-discovery from
~/.claude/mcp.json - Dynamic OAuth flows for authenticated servers
- Tool + resource discovery with rate limiting and caching
- MCP tools wrapped in
MCPTooladapter — indistinguishable from built-in tools at the model level
The MCP client implementation is in services/mcp/client.ts (119 KB).
11. Other Notable Details
Vim mode. Full vim keybinding emulation — INSERT/NORMAL modes, operators (delete, change, yank), motions, text objects, find (f/F/t/T), dot-repeat. Max repeat count capped at 10,000.
Session persistence. Full checkpoint/restore — message history, permission states, MCP connections, cost tracking, in-progress tasks. Sessions can be resumed across restarts.
Prompt caching. Large file reads are tagged for API-level caching. Re-reading the same file in a session doesn’t burn additional tokens.
Telemetry. OpenTelemetry instrumentation throughout. GrowthBook for feature flagging and A/B testing (ABLATION_BASELINE).
IDE bridges. bridge/ directory implements JSON-RPC for VS Code and a custom protocol for JetBrains. Detects IDE context for file navigation.
Startup optimization. MDM and Keychain prefetches run in parallel with module loading. Multiple timing checkpoints for cold start profiling.
Why Publish This
The source leaked. Thousands of developers will be curious. Many will do what I did — paste it into an AI and ask the same questions.
That’s thousands of independent analyses burning tokens and GPU cycles for the same answers. If one person runs the analysis and publishes the results, the rest can just read. Less compute, less energy.
Do the work once, share the findings.
Disclosure: Analysis performed by Claude Code (Opus 4.6) on its own source tree. Findings reviewed and structured by me. Published for research and educational purposes. I have no affiliation with Anthropic.
