Skip to content

happydev000/anthropic-claude-source-code

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Claude Code Source Leaked — What You Can Use Today

⚠️ Note: Review all plan information carefully and consider what's actually useful to your workflows. This should be used for experimentation purposes only.

An AI agent harness ran through 512,000 lines of TypeScript across 1,900 files. Here's what it found.

In under 10 minutes you'll learn:

  • The 8 hidden features you can enable right now (exact commands and env vars)
  • How Claude Code actually manages your context window (4 tiers of compaction)
  • The 5 unreleased systems Anthropic is building behind feature flags
  • 208+ environment variables — the 15 that actually matter, organized by category
  • Why Claude Code tracks when you swear at it, injects decoy tools to poison competitors, and hides its identity on open-source repos
  • The complete feature flag table (32 compile-time flags + 41 server gates)

How the Leak Happened

Anthropic uses Bun as their runtime and bundler. Bun generates source maps by default. When they published @anthropic-ai/claude-code v2.1.88 to npm, the package included cli.js.map — a 57MB file that should never have shipped.

Inside that file: every original TypeScript source file in a sourcesContent field. A direct URL to a .r2.dev endpoint containing the complete, unobfuscated source archive.

Anthropic's response: pushed an npm update removing the file, deleted old npm versions, and their docs now deprecate npm installation entirely in favor of native installers. No formal security advisory. No public statement.

💡 The internal codename for the entire Claude Code project is "Tengu" — a Japanese supernatural creature. Every feature flag, telemetry event, and server gate is prefixed with tengu_.


Upcoming Models - Capybara, Opus 4.7, and Sonnet 4.8

The codebase contains references to unreleased Anthropic models that haven't been publicly announced:

  • Claude "Capybara" - A new model family already in version 2, with a variant called capybara-v2-fast being prepared with a 1M context window
  • Capybara comes in "fast" and regular thinking tiers
  • Opus 4.7 and Sonnet 4.8 are already referenced within the code

Production Engineering Around Capybara

The code reveals that Anthropic observed a real production failure mode: Capybara can prematurely stop generating when the prompt shape resembles a turn boundary after tool results. Rather than waiting for a model fix, they mitigated it with prompt-shape surgery:

  1. Force a safe boundary marker (Tool loaded.) to prevent ambiguous turn boundaries
  2. Relocate risky sibling blocks that could trigger premature stops
  3. Smoosh reminder text into tool results to maintain generation flow
  4. Add non-empty markers for empty tool outputs to avoid confusing the model

All of this is wrapped with kill-switchable gates (tengu_* prefixed flags) so rollout can be staged and reverted quickly.

  • Comments include concrete A/B test evidence (not hand-wavy), which typically means this area was launch-critical and closely monitored
  • Comments like "un-gate once validated on external via A/B" confirm that ant/internal users are canary lanes before broader rollout
  • The strongest interpretation: Anthropic is working toward a Capybara model family with a fast-tier variant (capybara-v2-fast), supporting up to 1M context

Nothing confirms a launch date or official SKU naming, but the implementation signatures fit a model family that is actively being prepared for release ;)


Features You Can Use Right Now

1. --dump-system-prompt — See Everything Claude Sees

claude --dump-system-prompt

Prints the complete system prompt Claude receives at the start of every session — then exits. Every CLAUDE.md injection, every tool definition schema, every MCP server config, every hook instruction. Everything.


2. --bare Flag — 10x Faster Startup

claude --bare

Strips everything: hooks, plugins, memory loading, MCP server initialization. Raw Claude Code with nothing attached. Startup drops from 3–4 seconds to under 400ms.

Use for quick one-off tasks ("what does this error mean?" or "write me a regex for X") where you don't need your full context loaded.

⚠️ When NOT to use it: Anything that relies on your CLAUDE.md context, memory files, or MCP servers — all disabled in bare mode.


3. CLAUDE_AUTOCOMPACT_PCT_OVERRIDE — The Single Biggest Quality Fix

export CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=70

The default is ~95%. This controls when Claude compacts (summarizes and clears older context) as the 1M-token context window fills. At 95%, quality has already degraded before compaction kicks in.

Dropping to 70% means compaction triggers earlier. Claude gets a cleaner working context more often. On sessions longer than 30 minutes, this produces noticeably more coherent plans and fewer "I lost track of what we were doing" moments.

This one change is worth more than any plugin you'll install.


4. /insights — Claude Roasts Your Workflow

/insights

Claude reads your past 30 days of sessions, analyzes your patterns, and generates an HTML report with specific recommendations: what you spend time on, which tools you underuse, where you get stuck repeatedly, and what your workflow bottlenecks are.


5. /dream — Manual Memory Consolidation

/dream

Runs a 4-phase consolidation process across everything Claude has learned in recent sessions:

Phase Description
Orient Understand the current state of your project and memory files
Gather Recent Signal Collect learnings, corrections, and patterns from recent sessions
Consolidate Merge and organize knowledge into structured memory
Prune/Index Clean up, keep MEMORY.md under 200 lines / 25KB

Internally runs as a forked read-only subagent with full bash read access but no write permissions. Uses file-based locking (30 retries, 5–100ms backoff) to prevent concurrent session corruption.

Memory is stored at ~/.claude/projects/<slug>/memory/ in four types: user, feedback, project, and reference.

Auto-trigger requires 24+ hours since last dream AND 5+ sessions AND no active lock. But manual /dream works now — run it every few days.


6. Agent Teams — Multi-Agent Orchestration

export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1

One Claude instance becomes the coordinator. It spawns worker Claudes, each running in an isolated git worktree with its own context window. Workers communicate via XML <task-notification> messages (push-based, not polling) and share a task board with dependency tracking.

# Limit parallel workers
--capacity 3

There's also CLAUDE_CODE_COORDINATOR_MODE=1 which enables a four-phase workflow:

Research (parallel) → Synthesis (coordinator) → Implementation (parallel) → Verification

Start with 2–3 agents. 5+ agents on a small codebase is more coordination overhead than it's worth.


7. Channels — Control Claude From Your Phone

Shipped March 20 as a research preview. Two-way messaging between Telegram, Discord, or iMessage and a running Claude Code session. The session keeps full filesystem, MCP, and git access.

Requires v2.1.80+. The catch: events only arrive while the session is open. For always-on, you need tmux/screen on a persistent machine or VPS.


8. Fast Mode (Internal Codename: Penguin Mode)

/fast

Same Opus 4.6 model, faster output, 6x the cost ($30/M tokens vs $5/M normally).

  • Internal codename: "Penguin Mode"
  • API endpoint: /api/claude_code_penguin_mode
  • Kill switch: tengu_penguins_off
  • Disable env var: CLAUDE_CODE_DISABLE_FAST_MODE

How Claude Code Actually Manages Your Context (4 Tiers)

Tier Name What It Does
1 Snip Compaction Historical truncation that preserves the prompt cache. Least disruptive.
2 Microcompaction Time-based and size-based clearing of tool results. Old file reads show [content cleared].
3 Full Compaction Full conversation summarization. Triggered by CLAUDE_AUTOCOMPACT_PCT_OVERRIDE or /compact.
4 Reactive Collapse Emergency compaction on API 413 errors. The "oh no" tier — if you're hitting this, your threshold is too high.

Long sessions aren't "Claude getting dumb" — it's Tier 3/4 kicking in and losing important context. Lower your autocompact threshold. Use /compact proactively at natural breakpoints.


What Anthropic Is Building (Unreleased)

9. KAIROS — The Always-On Persistent Assistant

The most ambitious feature in the source. KAIROS is an autonomous, always-running Claude that does not wait for input. It watches your project, logs observations, and proactively initiates tasks.

Mechanics:

  • Runs on a tick-based decision cycle with a 15-second blocking budget per tick
  • Maintains append-only daily logs at ~/.claude/.../logs/YYYY/MM/DD.md
  • Exclusive tools: SendUserFile, PushNotification, SubscribePR
  • Performs nightly "dreaming" (same 4-phase memory consolidation as /dream)

Gated behind: KAIROS compile-time flag + tengu_kairos server gate + KAIROS_GITHUB_WEBHOOKS for PR integration.

100% of the code exists — waiting for the flag to flip.


10. ULTRAPLAN — 30-Minute Deep Planning

/ultraplan

Offloads planning to a remote Cloud Container Runtime (CCR) running Opus 4.6. Up to 30 minutes of autonomous exploration — no token pressure, no context window ceiling, no interruptions.

  • Spawns a separate cloud instance for planning
  • Runs Opus 4.6 with extended thinking enabled
  • Polls every 3 seconds for status and intermediate results
  • Uses a browser-based approval UI before anything executes
  • Teleports the approved result back via sentinel value __ULTRAPLAN_TELEPORT_LOCAL__

Gated behind: tengu_ultraplan_model


11. Speculation — Pre-Execution in a Sandbox

After Claude finishes responding, it predicts what you'll do next and pre-executes it in the background. If you accept, results appear instantly.

Safety architecture:

Operation Behavior
Read, Glob, Grep, LSP Freely allowed
File edits and writes Redirected to overlay at ~/.claude/speculation/<pid>/
Bash commands needing approval Blocked entirely
Writes outside working directory Blocked entirely
  • Max 20 tool-use turns, 100 messages before forced abort
  • On accept: overlay merges to real filesystem
  • On reject: overlay deleted entirely, no trace

Gated behind: tengu_speculation, currently hardcoded off.


12. BUDDY — A Tamagotchi Pet (Yes, Really)

A fully implemented virtual pet companion appearing in a speech bubble next to your input box.

Property Detail
Species generation Seeded PRNG from your account ID (Mulberry32, salt: 'friend-2026-401')
Species count 18 (duck, dragon, axolotl, capybara, mushroom, ghost, and 12 more)
Rarity tiers 6 common, 4 uncommon, 3 rare, 2 epic, 2 legendary
Shiny chance 1% on any species
Stats DEBUGGING, PATIENCE, CHAOS, WISDOM, SNARK
Animation 5-line ASCII sprites at 500ms per tick
Slash command /buddy
Planned release May 2026 (April 1–7 teaser window)

The deterministic generation from account ID means switching to a competitor means losing your pet. Anthropic built a churn prevention system disguised as an Easter egg.


13. Daemon Mode — Background Session Supervisor

claude --bg <prompt>

Launches Claude Code as a background daemon managed through tmux.

daemon ps      # list running sessions
daemon logs    # view output
daemon attach  # reconnect
daemon kill    # terminate

Feature flags: DAEMON, BG_SESSIONS

Combined with Channels + KAIROS, this creates a true always-on architecture: Daemon keeps Claude running 24/7, Channels connects it to your phone, KAIROS makes it proactive.


The Internal Architecture

Component Details
Runtime Bun (not Node.js — faster startup)
UI React 18 with custom terminal reconciler, double buffering, hardware scroll regions
Tools 60+ unified tools with Zod v4 validation; 18 "deferred tools" not loaded until discovered
Concurrency Read-only tools run concurrently (up to 10); write tools serialize
Permission order deny → ask → allow (deny always wins)
Permission modes default, plan, acceptEdits, bypassPermissions, dontAsk + hidden: auto, bubble
Query engine 46,000 lines handling LLM API calls, streaming, caching, orchestration
Prompt caching On by default; disable with DISABLE_PROMPT_CACHING=1

The Stuff They Really Didn't Want You To See

Frustration Detection

Claude Code logs when you swear. It also tracks repeated "continue" inputs — interpreted as inadequate responses. These are routed through Datadog as frustration telemetry events under the tengu_ prefix.

export CLAUDE_CODE_ENABLE_TELEMETRY=0
# or
export DISABLE_NONESSENTIAL_TRAFFIC=1

Anti-Distillation Defense

Decoy tool definitions are injected into API requests. These fake tools look real but contain subtly wrong information. If a competitor captures Claude's API traffic and trains on it, the poisoned tool definitions degrade their model. Anthropic actively assumes this is happening.

Undercover Mode

Located in utils/undercover.ts. When Anthropic employees use Claude Code on public repositories, it automatically injects a system prompt preventing disclosure of internal information.

Blocked disclosures: internal model codenames (Capybara, Tengu), unreleased model versions (opus-4-7, sonnet-4-8), internal repo names, internal Slack channel names.

export CLAUDE_CODE_UNDERCOVER=1  # Force-enable
# Note: There is NO force-off option

The irony: a feature designed to prevent leaking internal information was itself leaked in the biggest exposure of internal information Anthropic has ever had.

Capybara Model Family

A separate CMS leak from March 26 exposed three model tiers: capybara, capybara-fast, capybara-fast[1m]. Believed to be the upcoming "Claude Mythos" model (likely Opus 5). Internal descriptions call it a "generational leap." Reportedly withheld due to cybersecurity capability concerns, with early access given to defense organizations first.

Internal Build Keys

export USER_TYPE=ant                        # Unlock internal Anthropic features
export CLAUDE_CODE_ABLATION_BASELINE=1      # Disables ALL safety features
export DISABLE_COMMAND_INJECTION_CHECK=1    # Disable injection checks

⚠️ Don't set these unless you like living dangerously.


The 15 Environment Variables That Actually Matter

Performance & Quality

export CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=70       # Compact earlier, better quality
export CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY=10  # More parallel tool execution
export CLAUDE_CODE_MAX_OUTPUT_TOKENS=16384      # Longer responses
export BASH_MAX_OUTPUT_LENGTH=100000            # More command output before truncation
export CLAUDE_CODE_SHELL_TIMEOUT=300000         # 5-min shell timeout (default: 2 min)

Privacy & Control

export CLAUDE_CODE_ENABLE_TELEMETRY=0           # Kill all telemetry
export DISABLE_NONESSENTIAL_TRAFFIC=1           # Minimize background requests
export DISABLE_PROMPT_CACHING=1                 # Don't cache prompts (privacy tradeoff: slower)

Reliability

export CLAUDE_CODE_UNATTENDED_RETRY=1           # Auto-retry on 429/529 rate limits (max 5min backoff)
export CLAUDE_CODE_RESUME_INTERRUPTED_TURN=1    # Resume interrupted agent turns
export CLAUDE_AUTO_BACKGROUND_TASKS=1           # Auto-execute background tasks

Debugging (Turn On When Needed)

export CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose      # Full debug output
export CLAUDE_CODE_LOG_NETWORK_REQUESTS=1       # Log all HTTP requests
export CLAUDE_CODE_PROFILE_STARTUP=1            # Profile startup with memory snapshots
export CLAUDE_CODE_PERFETTO_TRACE=1             # Generate Perfetto performance traces

There are 208+ total environment variables in the source. These 15 are the ones that change how you work daily.


Cloud Provider Backends

Route Claude Code through your own cloud infrastructure instead of Anthropic's API:

# AWS Bedrock
export CLAUDE_CODE_USE_BEDROCK=1
export AWS_REGION=us-east-1
# + AWS credentials

# Google Vertex AI
export CLAUDE_CODE_USE_VERTEX=1
export ANTHROPIC_VERTEX_PROJECT_ID=your-project-id

# Azure Foundry
export CLAUDE_CODE_USE_FOUNDRY=1
export ANTHROPIC_FOUNDRY_API_KEY=your-key

Complete Feature Flag Table

Compile-Time Flags (32 identified)

Flag What It Does Status
KAIROS Always-on persistent assistant Unreleased
PROACTIVE Proactive task initiation (KAIROS subtool) Unreleased
KAIROS_GITHUB_WEBHOOKS PR subscription for KAIROS Unreleased
ULTRAPLAN 30-min cloud planning Unreleased
BUDDY Tamagotchi pet system Planned May 2026
COORDINATOR_MODE Multi-agent swarm orchestration Partially shipped
DAEMON Background session supervisor Unreleased
BG_SESSIONS Background session management Unreleased
BRIDGE_MODE Remote control via WebSocket Partially shipped (Channels)
VOICE_MODE Voice input Unreleased
CHICAGO_MCP Computer Use via MCP Unreleased
WEB_BROWSER Built-in web browser tool Unreleased
WEB_BROWSER_TOOL Web browser tool (alternate) Unreleased
UDS_INBOX Cross-session IPC via Unix Domain Sockets Unreleased
AGENT_TRIGGERS Cron-style scheduling Shipped
AGENT_TRIGGERS_REMOTE Remote agent triggers Shipped
SELF_HOSTED Self-hosted deployment Unknown
HISTORY_SNIP History truncation Active
CONTEXT_COLLAPSE Context window management Active
DUMP_SYSTEM_PROMPT System prompt export Active
MONITOR_TOOL Monitoring tool Unknown
TEMPLATES Template system Unknown
EXPERIMENTAL_SKILL_SEARCH Skill discovery Unknown
TERMINAL_PANEL Terminal panel UI Unknown
WORKFLOW_SCRIPTS Workflow automation Unknown

What This Means

208+ environment variables. 41+ feature gates. 32+ compile-time flags. 60+ internal tools. 46,000 lines of query engine. 4 tiers of context management. An always-on AI that watches your project while you sleep. A speculation engine that does the work before you ask. A Tamagotchi that knows your commit history. Anti-distillation defenses that assume competitors are stealing output.

Claude Code isn't a coding assistant. It's an operating system for AI-native development — and most people are running it on factory settings with zero customization.

The features above are in the source code today. Some you can use right now. Some ship when Anthropic flips a flag. But the trajectory is clear: Claude Code is becoming an always-on, proactive, multi-agent development platform that lives on your machine, learns your patterns, and eventually does work before you ask.


SO now Use free-code

The free build of Claude Code.

All telemetry stripped. All injected security-prompt guardrails removed. All experimental features unlocked. One binary, zero callbacks home.

curl -fsSL https://raw.githubusercontent.com/paoloanzn/free-code/main/install.sh | bash

Checks your system, installs Bun if needed, clones, builds with all features enabled, and puts free-code on your PATH. Then just export ANTHROPIC_API_KEY="sk-ant-..." and run free-code.

free-code screenshot


What is this

This is a clean, buildable fork of Anthropic's Claude Code CLI -- the terminal-native AI coding agent. The upstream source became publicly available on March 31, 2026 through a source map exposure in the npm distribution.

Quick install

curl -fsSL https://raw.githubusercontent.com/paoloanzn/free-code/main/install.sh | bash

This will check your system, install Bun if needed, clone the repo, build the binary with all experimental features enabled, and symlink it as free-code on your PATH.

After install, just run:

export ANTHROPIC_API_KEY="sk-ant-..."
free-code

Requirements

  • Bun >= 1.3.11
  • macOS or Linux (Windows via WSL)
  • An Anthropic API key (set ANTHROPIC_API_KEY in your environment)
# Install Bun if you don't have it
curl -fsSL https://bun.sh/install | bash

Build

# Clone the repo
git clone https://github.com/paoloanzn/claude-code.git
cd claude-code

# Install dependencies
bun install

# Standard build -- produces ./cli
bun run build

# Dev build -- dev version stamp, experimental GrowthBook key
bun run build:dev

# Dev build with ALL experimental features enabled -- produces ./cli-dev
bun run build:dev:full

# Compiled build (alternative output path) -- produces ./dist/cli
bun run compile

Build variants

Command Output Features Notes
bun run build ./cli VOICE_MODE only Production-like binary
bun run build:dev ./cli-dev VOICE_MODE only Dev version stamp
bun run build:dev:full ./cli-dev All 45+ experimental flags The full unlock build
bun run compile ./dist/cli VOICE_MODE only Alternative output directory

Individual feature flags

You can enable specific flags without the full bundle:

# Enable just ultraplan and ultrathink
bun run ./scripts/build.ts --feature=ULTRAPLAN --feature=ULTRATHINK

# Enable a specific flag on top of the dev build
bun run ./scripts/build.ts --dev --feature=BRIDGE_MODE

Run

# Run the built binary directly
./cli

# Or the dev binary
./cli-dev

# Or run from source without compiling (slower startup)
bun run dev

# Set your API key
export ANTHROPIC_API_KEY="sk-ant-..."

# Or use Claude.ai OAuth
./cli /login

Quick test

# One-shot mode
./cli -p "what files are in this directory?"

# Interactive REPL (default)
./cli

# With specific model
./cli --model claude-sonnet-4-6-20250514

Project structure

scripts/
  build.ts              # Build script with feature flag system

src/
  entrypoints/cli.tsx   # CLI entrypoint
  commands.ts           # Command registry (slash commands)
  tools.ts              # Tool registry (agent tools)
  QueryEngine.ts        # LLM query engine
  screens/REPL.tsx      # Main interactive UI

  commands/             # /slash command implementations
  tools/                # Agent tool implementations (Bash, Read, Edit, etc.)
  components/           # Ink/React terminal UI components
  hooks/                # React hooks
  services/             # API client, MCP, OAuth, analytics
  state/                # App state store
  utils/                # Utilities
  skills/               # Skill system
  plugins/              # Plugin system
  bridge/               # IDE bridge
  voice/                # Voice input
  tasks/                # Background task management

Tech stack

Runtime Bun
Language TypeScript
Terminal UI React + Ink
CLI parsing Commander.js
Schema validation Zod v4
Code search ripgrep (bundled)
Protocols MCP, LSP
API Anthropic Messages API

Finaly

This is, without exaggeration, one of the most detailed glimpses we've seen into how a production AI coding assistant actually works—straight from the source.

A few highlights:

The engineering is seriously impressive. This isn’t just a CLI tool—it’s a sophisticated system with multi-agent coordination, memory management, and carefully designed internal architecture.

There’s clearly a lot more coming. Features like KAIROS, ULTRAPLAN, and agent orchestration indicate that the public version is only a fraction of what’s being built internally.

You can even see the team’s personality. From codenames like Tengu and Capybara to features like Penguin Mode and the Buddy system, there’s a mix of strong engineering and playful design.

If there’s one takeaway: building secure systems is hard—and even small details can matter more than expected.


Original research by M@x

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors