claude-source-leaked

作者 noya21th已验证

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.

126
Stars
146
Forks
TypeScript
语言
2026/8/23
添加时间

⚠️ 第三方软件声明

本 Skill 为第三方开源软件,独立托管于 GitHub。SkillTip 仅为信息目录,不控制或维护底层仓库。所显示的安全检查为自动化且范围有限,安装前请自行审查源码。

阅读服务条款

安装

添加到你的 Claude Code skills 目录:

# Add to your Claude Code skills
git clone https://github.com/noya21th/claude-source-leaked

快速入门

使用 claude-source-leaked 等 Skills 的指南。

安全报告

已验证

上次扫描:—

{
  "status": "PASSED",
  "issues": []
}

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)

常见问题

What is claude-source-leaked?

claude-source-leaked is an open-source ai agents skill for AI coding assistants such as Claude Code, Codex CLI, and ChatGPT, built by noya21th. 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. It has 126 GitHub stars.

Is claude-source-leaked safe to use?

Yes. claude-source-leaked passed SkillsLLM's automated security scan — a dependency vulnerability audit plus prompt-injection heuristics — with no high-severity issues. You can read the full report in the Security Report section on this page.

How do I install claude-source-leaked?

Clone the repository with "git clone https://github.com/noya21th/claude-source-leaked" and add it to your Claude Code skills directory (see the Installation section above).

What programming language is claude-source-leaked written in?

claude-source-leaked is primarily written in TypeScript. It is open-source under noya21th on GitHub, so you can review or fork the full source.

Are there alternatives to claude-source-leaked?

Yes. SkillsLLM lists many other AI Agents skills you can browse and compare side by side. Open the AI Agents category from the badge at the top of this page, or use the Related Skills and comparison links further down to weigh claude-source-leaked against similar tools.

评论 (0)

暂无评论,成为第一个分享想法的人!

ECC

by affaan-m

10

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

242,21936,702JavaScript
AI 智能体ai-agentsanthropicclaude-code
查看详情
15

An agentic skills framework & software development methodology that works.

234,96620,863Shell
AI 智能体ai-agentsbrainstorming
查看详情

hermes-agent

by NousResearch

10

The agent that grows with you

234,43747,175Python
AI 智能体ai-agentsagent-orchestration
查看详情

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

185,94028,768JavaScript
AI 智能体ai-agentsanthropicclaude-code
查看详情

cc-switch

by farion1231

3

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode, OpenClaw, Grok Build & Hermes Agent. Only official website: ccswitch.io

128,8688,826Rust
AI 智能体claude-codeai-tools
查看详情

claude-code

by anthropics

Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.

120,03119,897Shell
AI 智能体
查看详情

开发者还喜欢

基于喜欢此 Skill 的开发者投票和收藏

ECC

by affaan-m

10

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

242,21936,702JavaScript
AI 智能体ai-agentsanthropicclaude-code
查看详情
15

An agentic skills framework & software development methodology that works.

234,96620,863Shell
AI 智能体ai-agentsbrainstorming
查看详情

hermes-agent

by NousResearch

10

The agent that grows with you

234,43747,175Python
AI 智能体ai-agentsagent-orchestration
查看详情

n8n

by n8n-io

12

Fair-code workflow automation platform with native AI capabilities. Combine visual building with custom code, self-host or cloud, 400+ integrations.

201,88160,308TypeScript
MCP 服务器apisai-tools
查看详情

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

185,94028,768JavaScript
AI 智能体ai-agentsanthropicclaude-code
查看详情

cc-switch

by farion1231

3

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode, OpenClaw, Grok Build & Hermes Agent. Only official website: ccswitch.io

128,8688,826Rust
AI 智能体claude-codeai-tools
查看详情