Educational Only — Analysis of leaked source code. Not affiliated with Anthropic. April Fools? Leaked March 31!
Leaked March 31, 2026 • npm v2.1.88

The Complete Source of Claude Code Exposed

Anthropic accidentally shipped a source map in their npm package, exposing 512,000+ lines of TypeScript. This is the most advanced AI coding assistant ever built — and now we can see exactly how it works.

512K+
Lines of Code
1,900+
Files
40+
AI Tools
85+
Commands
🔧
Tools
40+
⌨️
Commands
85+
🚩
Feature Flags
44+
query.ts — The Agentic Loop
async function* queryLoop(params): AsyncGenerator {
  let state = initialState;
  
  while (true) {
    // Stream from the model
    for await (const msg of callModel(state)) {
      yield msg;
    }
    
    // Execute tools in parallel
    for await (const result of executeTools()) {
      yield result;
    }
    
    if (!needsFollowUp) {
      return { reason: 'completed' };
    }
    
    state = computeNextState(state);
  }
}
📁
1,900+
TypeScript Files
📝
512K+
Lines of Code
🔧
40+
AI Agent Tools
⌨️
85+
Slash Commands
🚩
44+
Feature Flags
System Architecture

Built for Autonomous Agents

A layered architecture designed for streaming AI interactions, tool orchestration, and intelligent context management.

USER INTERFACES
CLI
VS Code
JetBrains
Web
Desktop
TRANSPORT LAYER
SSE Server-Sent Events
WebSocket Bidirectional
Hybrid Best of Both
CORE ENGINE

QueryEngine

46,000 lines
  • Agentic Loop
  • State Machine
  • Streaming

Tool System

40+ Tools
  • Zod Validation
  • Parallel Exec
  • MCP Protocol

Permissions

3 Modes
  • Per-Tool Rules
  • Denial Tracking
  • Auto-Classify

Context

5 Layers
  • Auto-Compact
  • Microcompact
  • Recovery
EXTERNAL SERVICES
Anthropic API Claude Models
MCP Servers External Tools
Git / GitHub Version Control
File System Local Storage

Request Flow Pipeline

1
User Input
2
Context Setup
3
API Stream
4
Tool Dispatch
5
Loop / Return

Core Components Deep Dive

QueryEngine.ts

46,000+ lines

The brain of Claude Code. Orchestrates the entire agentic loop including model calls, tool execution, state transitions, and error recovery.

Streaming responses Parallel tools Auto-recovery Token budgets

Tool System

40+ tools

Every tool implements a structured interface with Zod schemas, permission checks, progress streaming, and customizable rendering.

Zod validation MCP support Concurrent exec Progress events

Context Manager

5 layers

Sophisticated context management with cascading compaction strategies ensuring conversations never hit limits.

History snip Microcompact Auto-compact Reactive

Project Structure

claude-code/
Core Files Entry Points
main.tsx
query.ts 1,730 lines
QueryEngine.ts 46K lines
Tool.ts
commands.ts 85+ cmds
services/ Backend
api/ Claude client
compact/ Compaction
mcp/ Protocol
analytics/ Telemetry
tools/ 40+ Tools
BashTool/ Shell
FileReadTool/
AgentTool/ Sub-agents
MCPTool/
Other Support
components/ React/Ink
skills/ Extensions
memdir/ Memory
utils/ Helpers
Tool Arsenal

40+ Specialized AI Tools

From file operations to sub-agent spawning, every tool is designed for autonomous AI execution with Zod validation and permission checking.

📁 File Operations

  • FileReadTool
  • FileWriteTool
  • FileEditTool
  • NotebookEditTool

🔍 Search & Navigation

  • GlobTool
  • GrepTool
  • LSPTool
  • ToolSearchTool

⚡ Execution

  • BashTool
  • PowerShellTool
  • AgentTool
  • REPLTool

🌐 Web & External

  • WebFetchTool
  • WebSearchTool
  • MCPTool
  • ReadMcpResourceTool

FileRead

Read with line numbers

FileEdit

Search & replace

Bash

Shell commands

Grep

Regex search

Agent

Spawn sub-agents

WebFetch

Fetch URLs

MCP

External tools

TodoWrite

Task management

Glob

File patterns

Notebook

Jupyter cells

Schedule

Cron automation

AskUser

Interactive prompts

Technical Analysis

10 Engineering Breakthroughs

The patterns and innovations that make Claude Code genuinely state-of-the-art.

01 Streaming Tool Execution

Traditional AI tools wait for the model to finish generating, then execute tools, then continue. This creates noticeable latency. Claude Code's StreamingToolExecutor starts executing tools while the model is still generating.

Result: While Claude is writing "Let me check that file...", the file is already being read. By the time the model finishes the sentence, the result is ready.

// Start tools during streaming
for (const block of toolBlocks) {
  executor.addTool(block);  // Execute immediately
}

// Get results as they complete
for (const r of executor.getCompletedResults()) {
  yield r.message;
}

02 5-Layer Context Management

Context limits are the Achilles' heel of AI assistants. Claude Code implements five cascading strategies that work together. Users never see "context limit exceeded."

  • Layer 1: History Snip — Remove old conversation turns
  • Layer 2: Microcompact — Compress verbose tool results
  • Layer 3: Context Collapse — Summarize sections while preserving detail
  • Layer 4: Auto-Compact — Proactive summarization before hitting limits
  • Layer 5: Reactive Compact — Emergency compaction on 413 errors

Key insight: Each layer handles what the previous one couldn't. If snipping isn't enough, microcompact kicks in. And so on.

03 Build-Time Feature Elimination

Using Bun's feature() function, Anthropic can completely remove code from builds based on feature flags. Not disabled — eliminated.

import { feature } from 'bun:bundle';

const buddyModule = feature('BUDDY') 
  ? require('./commands/buddy/index.js') 
  : null;

// If BUDDY=false, the entire module is stripped from the bundle

The codebase has 44+ feature flags including KAIROS (autonomous mode), BUDDY (digital pet!), VOICE_MODE, and PROACTIVE.

04 Multi-Layer Permission System

AI that can execute code is inherently risky. Claude Code's permission system includes:

  • Permission Modes: Default (ask everything), Plan (read-only), Auto (approve safe actions)
  • Per-Tool Rules: Always allow, always deny, always ask — per tool/command
  • Denial Tracking: After N denials, stop asking and assume "no"
  • Security Classification: Every tool feeds into an automated classifier

05 Async Generator State Machine

The agentic loop isn't a simple while loop. It's a sophisticated state machine using async generators:

async function* queryLoop(params): AsyncGenerator<Event, Terminal> {
  while (true) {
    // Stream from model
    for await (const msg of callModel(state)) {
      yield msg;
    }
    
    // Execute tools
    for await (const result of executeTools()) {
      yield result;
    }
    
    if (!needsFollowUp) return { reason: 'completed' };
    state = computeNextState(state);
  }
}

Generators provide natural streaming, backpressure handling, clean cancellation via .return(), and composability.

06 Skills System

Claude Code is extensible through prompts, not just code. Skills are markdown files with YAML frontmatter:

---
name: debug
description: Help debug issues systematically
---

# Debug Skill

When debugging, follow these steps:
1. Reproduce the issue
2. Isolate the cause
3. Form a hypothesis
4. Test the hypothesis
5. Fix and verify

Skills can be bundled (ships with Claude Code), global (~/.claude/skills/), or project-specific (.claude/skills/).

07-10 More Innovations

  • Terminal UI with React: Built using Ink, rendering React components to the terminal
  • MCP Protocol: External tool discovery and integration via Model Context Protocol
  • Startup Optimization: Aggressive parallel initialization, lazy imports, memory prefetch
  • Error Recovery: Max output tokens recovery, prompt-too-long recovery, model fallback
True Agency

Why It's a Real Agent

Not a chatbot with tools. A genuine autonomous system that pursues goals, spawns helpers, and corrects itself.

Everyone claims "agentic AI" now. It's a buzzword. But Claude Code genuinely earns that label — and the source code proves it. Here's what separates a true agent from a chatbot with extra steps:

Autonomous Goal Pursuit

The agent runs until it decides the task is complete. No artificial "maximum 3 steps" limit. The query loop continues until needsFollowUp is false.

Hierarchical Delegation

Complex tasks spawn sub-agents via AgentTool. Explore agents investigate, verification agents (Tengu) check work. True delegation, not just execution.

Persistent Memory

The memdir system stores project knowledge, user preferences, and learned patterns. Selective retrieval based on current context — not just chat history.

Self-Correction

Hit a limit? Compact and retry. Tests failing? Analyze and fix. The agent diagnoses problems, applies fixes, and retries automatically.

Work Verification

The Tengu verification agent reviews changes before declaring "done." Closed-loop verification for correct, not just changed, code.

Resource Management

Token budgets, cost tracking, turn limits. The agent knows its constraints and operates within them intelligently.

The Agentic Spectrum

Chatbot

Q&A only

Tool Calling

On-demand

Simple Loop

Limited steps

Multi-Agent

Delegation

Claude Code

Full autonomy

Less Agentic More Agentic
Command Reference

85+ Slash Commands

From session management to hidden easter eggs, Claude Code has a command for everything.

Session Management

  • /session Manage sessions
  • /resume Resume previous
  • /clear Clear conversation
  • /compact Compact context
  • /export Export session

Git & Version Control

  • /commit Create commit
  • /commit-push-pr Full workflow
  • /branch Manage branches
  • /diff Show diffs
  • /review Code review

Configuration

  • /config Edit config
  • /permissions Manage perms
  • /theme Change theme
  • /vim Toggle vim mode
  • /model Switch models

Development

  • /doctor Run diagnostics
  • /init Initialize project
  • /mcp Manage MCP
  • /skills List skills
  • /agents List agents

Mode Switching

  • /plan Enter plan mode
  • /fast Toggle fast mode
  • /voice Toggle voice
  • /assistant Hidden mode
  • /proactive Autonomous

Hidden Commands

  • /buddy 🐾 Digital pet!
  • /dream Dream mode
  • /stickers Sticker system
  • /ultraplan Adv. planning
  • /torch Unknown
Feature Flags

44+ Build-Time Feature Flags

Compile-time feature elimination enables safe A/B testing, gradual rollouts, and instant rollbacks.

Core
KAIROS
Autonomous agent mode
Core
PROACTIVE
Proactive assistance
Core
BRIDGE_MODE
Remote sessions
Core
VOICE_MODE
Voice input/output
Easter Egg
BUDDY
🐾 Digital pet system
Context
CACHED_MICROCOMPACT
Cached compaction
Context
CONTEXT_COLLAPSE
Context collapsing
Context
REACTIVE_COMPACT
Emergency compaction
Context
HISTORY_SNIP
History trimming
Context
TOKEN_BUDGET
Budget tracking
Internal
VERIFICATION_AGENT
Tengu verification
Experimental
FORK_SUBAGENT
Fork-based agents
Technology

The Tech Stack

Modern technologies chosen for performance, developer experience, and extensibility.

Bun

Fast JS Runtime

TypeScript

Type Safety

React + Ink

Terminal UI

Zod

Schema Validation

Anthropic SDK

Claude API

MCP SDK

Tool Protocol

Security

Defense in Depth

Multiple overlapping security layers protect against dangerous actions.

Permission System

Three modes with per-tool rules and denial tracking.

  • Default mode: Ask for everything
  • Plan mode: Read-only operations
  • Auto mode: Approve safe actions
  • Per-tool allow/deny rules

Cyber Risk Guardrails

Built-in restrictions in cyberRiskInstruction.ts:

  • Destructive techniques
  • DoS attacks
  • Mass targeting
  • Supply chain compromise
Hidden Gems

Easter Eggs Discovered

Because even the most sophisticated AI needs a little fun.

🐾

BUDDY

A digital pet system. Your coding companion that lives in the terminal.

💭

Dream Mode

What does an AI dream about? Enabled with the KAIROS flag.

🎨

Stickers

Yes, there's a /stickers command. In a CLI tool.

🥷

Undercover

Mode that hides model names. For testing unreleased models?

The Leak

How It Happened

The accidental exposure that revealed 512,000 lines of code.

March 31, 2026 — Morning

npm Publish

Anthropic publishes Claude Code v2.1.88 to npm with source map accidentally included.

Within Hours

Discovery

Developers notice the 59.8MB .map file and begin extraction.

Same Day

Mirrors Created

Multiple GitHub repositories mirror the extracted source before takedowns.

Ongoing

DMCA & Analysis

Anthropic issues takedowns. Community analyzes the revolutionary codebase.

Explore Further

Dive into the leaked source code, try the official CLI, or read the documentation.