Star 历史趋势
数据来源: GitHub API · 生成自 Stargazers.cn
README.md

Claude Code Unveiled

The first architecture deep-dive, hidden feature catalog, and cost optimization guide for Claude Code — based on v2.1.88 source analysis (1,884 files, 132K lines of TypeScript).

中文版 | English


On March 31, 2026, Claude Code's TypeScript source (1,884 files, ~132K lines) was exposed through an unstripped .map file in the npm package. This repository includes the complete restored source code in src/ plus original analysis. This project extracts actionable insights — architecture patterns, hidden features, cost optimization, and best practices — all with source file references.

Table of Contents


System Prompt (Complete Reconstruction)

Full document | Source: src/constants/prompts.ts, src/utils/systemPrompt.ts

5-Layer Priority System

Priority 0: Override (loop mode, testing)        ← highest
Priority 1: Coordinator (multi-worker orchestration)
Priority 2: Agent (subagent definitions)
Priority 3: Custom (--system-prompt flag)
Priority 4: Default (standard Claude Code)       ← lowest
         + appendSystemPrompt (always appended unless override)

What the Default Prompt Actually Says

The system prompt is 9 major sections:

  1. Identity — "You are an interactive agent that helps users with software engineering tasks"
  2. System Rules — Tool execution, permission modes, prompt injection detection
  3. Task Execution — The most detailed section:
    • Read code before modifying (mandatory)
    • Don't add unrequested features/refactoring
    • Don't create helpers for one-time operations
    • "Three similar lines of code is better than a premature abstraction"
    • Avoid OWASP Top 10 vulnerabilities
  4. Careful Actions — Destructive operations need user confirmation (rm -rf, force push, etc.)
  5. Tool Usage — Use dedicated tools (Read/Edit/Glob/Grep) instead of Bash
  6. Tone — No emojis, concise, file_path:line_number format
  7. Output Efficiency — "If you can say it in one sentence, don't use three"
  8. Cache Boundary__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__ splits static/dynamic parts
  9. Environment — CWD, platform, model name, knowledge cutoff

Cache Optimization

The prompt is split by __SYSTEM_PROMPT_DYNAMIC_BOUNDARY__:

  • Before boundary (static): Cached globally, saves tokens on repeat calls
  • After boundary (dynamic): User/session-specific, recalculated each time (memory, MCP, language, etc.)

Model Knowledge Cutoffs

ModelDisplay NameCutoff
claude-opus-4-6Claude Opus 4.6May 2025
claude-sonnet-4-6Claude Sonnet 4.6August 2025
claude-haiku-4-5Claude Haiku 4.5February 2025

87 Hidden Feature Flags

Full document | Source: src/commands.ts, various

These are compile-time switches via bun:bundle feature(). Most are dead-code-eliminated in the public npm build.

Core Codenames

CodenameWhat It DoesCross-file References
KAIROSAutonomous assistant platform (assistant mode, brief, channels, cron, webhooks)210 files
PROACTIVEProactive task planning and automationLinked to KAIROS
COORDINATOR_MODEMulti-agent orchestration with workers45 files
VOICE_MODEVoice input/output with cross-platform binaries38 files
BUDDYAI companion sprite with animation system14 files, 1,298 lines
ULTRATHINKExtended deep reasoning modeCompile-time
ULTRAPLANSuper planner with selection dialogCompile-time
TORCHInference enhancementCompile-time
BRIDGE_MODEMobile/web remote controlCompile-time
CHICAGO_MCPComputer-use MCP serverInternal

Context & Compression

FlagPurpose
CONTEXT_COLLAPSESmart context folding
REACTIVE_COMPACTReactive session compression
CACHED_MICROCOMPACTMicro cache compression
HISTORY_SNIPHistory message fragmentation
BG_SESSIONSBackground session management
AWAY_SUMMARYAuto-summary when user is away

Obfuscated Runtime Config (tengu_* gates)

Runtime flags use tengu_ + random word pairs to deliberately hide their purpose:

tengu_frond_boric       → Analytics killswitch (Datadog/FirstParty)
tengu_passport_quail    → Memory extraction gate
tengu_moth_copse        → Memory extraction enable
tengu_bramble_lintel    → Memory extraction frequency
tengu_cicada_nap_ms     → Background refresh throttle
tengu_slate_prism       → Connector text summarization
tengu_amber_json_tools  → JSON tool format (token-efficient)
tengu_tool_pear         → Structured output (strict tools)

15 Hidden Slash Commands

Source: src/commands.ts

These require specific feature flags to appear:

CommandFunctionRequired Flag
/assistantAssistant modeKAIROS
/briefBrief messagesKAIROS_BRIEF
/bridgeRemote control bridgeBRIDGE_MODE
/voiceVoice modeVOICE_MODE
/buddyAI companion spriteBUDDY
/ultraplanSuper plannerULTRAPLAN
/torchInference boostTORCH
/workflowsWorkflow scriptsWORKFLOW_SCRIPTS
/forkSubagent branchingFORK_SUBAGENT
/peersPeer messagingUDS_INBOX
/proactiveProactive planningPROACTIVE
/force-snipForce history snipHISTORY_SNIP
/subscribe-prPR subscriptionsKAIROS_GITHUB_WEBHOOKS
/remote-setupRemote CCR setupCCR_REMOTE_SETUP
/remote-control-serverRemote control serverDAEMON + BRIDGE_MODE

25 Internal-Only Commands

Condition: USER_TYPE === 'ant' && !IS_DEMO

CommandFunction
/bughunterAutomated bug detection
/good-claudeModel evaluation tool
/commitHidden git commit
/commit-push-prOne-click commit → push → create PR
/ctx-vizContext visualization
/break-cacheForce cache invalidation
/mock-limitsSimulate rate limits
/reset-limitsReset rate limits
/ant-traceAnthropic internal tracing
/perf-issuePerformance diagnostics
/debug-tool-callTool call debugger
/agents-platformAgents platform management
/autofix-prAuto-fix PR
/backfill-sessionsBackfill session data
/shareSession sharing
/summarySession summary
/onboardingOnboarding flow
/init-verifiersInitialize verifiers
/bridge-kickKick bridge connection
/versionVersion display
/oauth-refreshOAuth token refresh
/envEnvironment variables
/issueIssue tracking
/teleportSession teleport
/tagsSession tags

Undercover Mode

Full document | Source: src/utils/undercover.ts

When Anthropic employees (USER_TYPE=ant) work in public repositories, Claude Code automatically hides all internal information.

How It Works

isUndercover() check:
  USER_TYPE !== 'ant' → always OFF (external users unaffected)
  USER_TYPE === 'ant' →
    CLAUDE_CODE_UNDERCOVER=1 → forced ON
    Repo in internal allowlist → OFF
    Repo is public/unknown → ON (safe default)

There is NO force-OFF option. If Claude Code can't confirm it's an internal repo, undercover stays ON.

What Gets Injected

## UNDERCOVER MODE — CRITICAL

You are operating UNDERCOVER in a PUBLIC/OPEN-SOURCE repository.
NEVER include in commit messages or PR descriptions:
- Internal model codenames (Capybara, Tengu, etc.)
- Unreleased model version numbers
- Internal repo or project names
- The phrase "Claude Code" or any mention that you are an AI
- Co-Authored-By lines or any other attribution

Internal Repo Allowlist (22 private repos)

anthropics/claude-cli-internal, anthropics/anthropic, anthropics/apps,
anthropics/casino, anthropics/dbt, anthropics/dotfiles,
anthropics/terraform-config, anthropics/hex-export, anthropics/feedback-v2,
anthropics/labs, anthropics/argo-rollouts, anthropics/starling-configs,
anthropics/ts-tools, anthropics/ts-capsules, anthropics/feldspar-testing,
anthropics/trellis, anthropics/claude-for-hiring, anthropics/forge-web,
anthropics/infra-manifests, anthropics/mycro_manifests,
anthropics/mycro_configs, anthropics/mobile-apps

Source: src/utils/commitAttribution.ts lines 30-75


Cost Optimization

Full document | Sources: src/utils/modelCost.ts, src/utils/context.ts, src/services/compact/

Model Pricing (per million tokens)

ModelInputOutputCache ReadCache Write
Haiku 4.5$1$5$0.10$1.25
Sonnet 4.6$3$15$0.30$3.75
Opus 4.6$5$25$0.50$6.25
Opus 4.6 Fast$30$150$3.00$37.50

Fast mode is 6x the price. Use it only for short, time-sensitive tasks.

Source: src/utils/modelCost.ts lines 36-69

10 Money-Saving Tips

#TipSource Evidence
1Output reservation is 8K (not 32K) — auto-escalates to 64K on hitcontext.ts:24-25
2Keep CLAUDE.md under 500 words — it's sent with every requestcontext.ts getUserContext()
3Use /compact proactively — manual compact uses only 3K buffer vs auto's 13KautoCompact.ts:62,65
4Don't switch models mid-session — 18 dimensions of cache invalidationpromptCacheBreakDetection.ts:28-99
5Fast mode = 6x cost — toggle off for long tasksmodelCost.ts:62-69
6API Key users default to Sonnet (cheaper) — don't switch to Opus unless neededmodel.ts:178-207
7Set CLAUDE_CODE_SUBAGENT_MODEL=haiku — subagents do simple tasks, 5x cheaperagent.ts:37-95
8Background tasks never retry 429/529 errors (built-in, saves cascade costs)withRetry.ts:62-88
9Post-compact file restore is budgeted: 5 files max, 5K tokens eachcompact.ts:122-130
10Cache reads are 90% off — keep system prompt stable to maximize cache hitsmodelCost.ts

Key Thresholds

Context window:        200,000 tokens
Auto-compact trigger:  ~167,000 tokens (200K - 20K output - 13K buffer)
Manual compact buffer:   3,000 tokens
Default max_output:      8,000 tokens (escalates to 64,000 on retry)
Session memory min:     10,000 tokens
Session memory max:     40,000 tokens
Post-compact restore:   50,000 tokens budget, 5 files max

Architecture Diagrams

Request Lifecycle

Full document

sequenceDiagram
    participant User
    participant REPL
    participant Query as QueryEngine
    participant API as Claude API
    participant Tool as Tool Executor

    User->>REPL: Input message
    REPL->>Query: submitMessage()
    Query->>Query: Build system prompt (5-layer priority)
    Query->>Query: Load CLAUDE.md + Memory
    Query->>API: messages.create(stream)

    loop Tool Loop
        API-->>Query: tool_use response
        Query->>Tool: Permission check → Execute
        Tool-->>Query: Tool result
        Query->>API: Continue with result
    end

    API-->>REPL: Final text response
    Query->>Query: Cost tracking + auto-compact check

Tool System

Full document

40+ built-in tools across 4 permission levels:

LevelAuto-AllowExamples
0AlwaysRead, Glob, Grep, LSP, TaskGet, ToolSearch
1First-time confirmWrite, Edit, WebFetch, WebSearch, Bash (safe)
2Every-time confirmBash (dangerous: rm, git push, chmod)
3Block + warnrm -rf /, git push --force origin main, DROP TABLE

Permission Model

Full document

4 modes: Default (ask) → Plan (read-only) → Auto (smart judge) → Bypass (allow all)

Multi-Agent Architecture

Full document

Main Thread → Agent tool → Subagent (fresh context, isolated)
                        → Subagent (can use different model)
                        → Subagent (can run in git worktree)

Subagent model priority: CLAUDE_CODE_SUBAGENT_MODEL env > tool-specified > agent config > inherit parent


Claude Code vs Cursor vs Cline

Full documents: vs Cursor | vs Cline | Feature Matrix

AspectClaude CodeCursorCline
FormTerminal CLIVS Code forkVS Code extension
ModelsClaude onlyOpenAI/Claude/Gemini/xAIAny OpenAI-compatible
Open SourceNoNoYes (Apache 2.0)
Max Context1M tokens~272K (RAG)Provider-dependent
Multi-AgentSubagents (unlimited)8 parallelSingle only
Permission4-level classificationImplicit trustPer-action approval
MemoryPersistent cross-sessionSession onlyNone
CostPer-token / subscription$20-40/monthFree (BYO keys)
Codebase Searchripgrep on-demandAST + embeddings indexVS Code search
AutomationHooks + SkillsLimitedLimited

Telemetry — What Data Is Collected

Full document | Source: src/services/analytics/

Dual-Channel Architecture

Claude Code → First-Party (api.anthropic.com/api/event_logging/batch)  [640+ event types]
           → Datadog (us5.datadoghq.com)                              [64 allowed events]
           → BigQuery Metrics (api.anthropic.com/api/claude_code/metrics)

What's Collected

  • Environment: platform, arch, terminal, package managers, runtimes, CI detection
  • User ID: device_id (de-identified), user_bucket (SHA256 % 30), session_id
  • Events: session lifecycle, API calls (model, tokens, latency), tool usage, permission decisions, voice toggles
  • NOT collected by default: user prompts (requires OTEL_LOG_USER_PROMPTS=1), full file paths (extension only)

How to Disable

DISABLE_TELEMETRY=1                              # Disable analytics
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1       # Disable all non-API network

Remote Control & Killswitches

Full document | Source: src/services/remoteManagedSettings/

Polling Mechanism

  • Endpoint: {BASE_URL}/api/claude_code/settings
  • Interval: Every 1 hour
  • Cache: ETag-based with SHA256 checksum verification
  • Failure mode: Fail-open (continues working with cached/default settings)

Known Killswitches

SwitchControls
tengu_frond_boricAnalytics data flow (Datadog/FirstParty)
tengu_auto_mode_configAuto mode enable/disable
Statsig gatePermission bypass control
tengu_bridge_poll_interval_configBridge polling frequency
tengu_kairos_cron_configKAIROS cron task rate limiting
tengu_event_sampling_configEvent sampling rate (0-100%)

Remotely Modifiable Behaviors

Data reporting, auto mode, permission bypass, polling frequency, event sampling, model routing, memory system, cache strategy, Bash classification, version limits.


Unreleased Features — Future Roadmap

Full document

Assessed by verifiable code metrics, not subjective percentages:

FeatureDedicated CodeCross-file ReferencesInfrastructure
KAIROS597 lines210 files3 GrowthBook gates
Voice Mode54 lines38 files6-platform native binaries
Coordinator369 lines45 filesDedicated system prompt
Buddy1,298 lines14 filesAnimation + notification system
UltraPlan/Think/TorchCommand registrationScatteredCompile-time flags
Web Browser0 files (in npm)Feature-gatedLikely in internal monorepo

108 modules are dead-code-eliminated from the npm build and exist only in Anthropic's internal monorepo.


CLAUDE.md Best Practices

Full document | Source: src/context.ts

Loading Order

~/.claude/CLAUDE.md (global) + project/CLAUDE.md (project) + .claude/CLAUDE.md
  → Merged → Injected into system prompt dynamic section → Sent with EVERY request

Recommended Template

# CLAUDE.md

## Tech Stack
- Language: TypeScript 5.x, strict mode
- Framework: Next.js 14, App Router
- Testing: vitest
- Package manager: pnpm

## Conventions
- Components: PascalCase, hooks: camelCase
- Commits: conventional commits (feat/fix/chore)

## Project Structure
- src/app/ — routes
- src/components/ — shared components
- src/lib/ — utilities

What NOT to Write

  • Don't repeat system prompt rules (already hardcoded)
  • Don't write long descriptions (wastes tokens every request)
  • Don't paste API docs (let Claude read the actual files)
  • Don't put TODO lists (use conversation, not CLAUDE.md)

Accuracy & Methodology

Based on static source code reading of Claude Code v2.1.88:

  • All numeric constants verified against source with file paths and line numbers
  • Architecture diagrams are simplified — actual flow may have uncaptured edge cases
  • Feature assessments use verifiable metrics (file count, LOC, cross-references)
  • Cursor/Cline comparison uses public documentation; internals may differ
  • No code was executed or tested at runtime

Found an error? Open an issue with the source file and line number.

Disclaimer

  • NOT affiliated with, endorsed by, or maintained by Anthropic
  • All original source code is Anthropic's intellectual property
  • For educational and security research purposes only
  • No proprietary source code is redistributed — all content is original analysis

License

Analysis and documentation: MIT | Original Claude Code source: Anthropic (all rights reserved)

关于 About

Claude Code v2.1.88 source analysis: system prompts, 87 hidden feature flags, cost optimization, architecture diagrams, undercover mode, and comparison with Cursor/Cline. No source code redistributed.
ai-agentai-codinganthropicarchitectureclaudeclaude-codeclinecost-optimizationcursordeveloper-toolsfeature-flagsreverse-engineeringsecurity-researchsource-analysissystem-prompt

语言 Languages

TypeScript100.0%
JavaScript0.0%

提交活跃度 Commit Activity

代码提交热力图
过去 52 周的开发活跃度
4
Total Commits
峰值: 4次/周
Less
More