Claude Code v2.1.88 โ Source Code Analysis
Disclaimer: All source code in this repository is the intellectual property of Anthropic and Claude. This repository is provided strictly for technical research, study, and educational exchange among enthusiasts. Commercial use is strictly prohibited. No individual, organization, or entity may use this content for commercial purposes, profit-making activities, illegal activities, or any other unauthorized scenarios. If any content infringes upon your legal rights, intellectual property, or other interests, please contact us and we will verify and remove it immediately.
Extracted from npm package
@anthropic-ai/claude-codeversion 2.1.88. The published package ships a single bundledcli.js(~12MB). Thesrc/directory in this repo contains the unbundled TypeScript source extracted from the npm tarball.
Language: English | ไธญๆ | ํ๊ตญ์ด | ๆฅๆฌ่ช
Table of Contents
- Deep Analysis Reports (
docs/) โ Telemetry, codenames, undercover mode, remote control, future roadmap - Missing Modules Notice โ 108 feature-gated modules not in the npm package
- Architecture Overview โ Entry โ Query Engine โ Tools/Services/State
- Tool System & Permissions โ 40+ tools, permission flow, sub-agents
- The 12 Progressive Harness Mechanisms โ How Claude Code layers production features on the agent loop
- Build Notes โ Why this source isn't directly compilable
Deep Analysis Reports (docs/)
Source code analysis reports derived from decompiled v2.1.88. Quadrilingual (EN/JA/KO/ZH).
docs/
โโโ en/ # English
โ โโโ [01-telemetry-and-privacy.md] # Telemetry & Privacy โ what's collected, why you can't opt out
โ โโโ [02-hidden-features-and-codenames.md] # Codenames (Capybara/Tengu/Numbat), feature flags, internal vs external
โ โโโ [03-undercover-mode.md] # Undercover Mode โ hiding AI authorship in open-source repos
โ โโโ [04-remote-control-and-killswitches.md]# Remote Control โ managed settings, killswitches, model overrides
โ โโโ [05-future-roadmap.md] # Future Roadmap โ Numbat, KAIROS, voice mode, unreleased tools
โ
โโโ ja/ # ๆฅๆฌ่ช
โ โโโ [01-ใใฌใกใใชใจใใฉใคใใทใผ.md] # ใใฌใกใใชใจใใฉใคใใทใผ โ ๅ้้
็ฎใ็กๅนๅไธๅฏใฎ็็ฑ
โ โโโ [02-้ ใๆฉ่ฝใจใณใผใใใผใ .md] # ้ ใๆฉ่ฝ โ ใขใใซใณใผใใใผใ ใfeature flagใๅ
้จ/ๅค้จใฆใผใถใผใฎ้ใ
โ โโโ [03-ใขใณใใผใซใใผใขใผใ.md] # ใขใณใใผใซใใผใขใผใ โ ใชใผใใณใฝใผในใงใฎAI่ไฝ้ ๅฟ
โ โโโ [04-ใชใขใผใๅถๅพกใจใญใซในใคใใ.md] # ใชใขใผใๅถๅพก โ ็ฎก็่จญๅฎใใญใซในใคใใใใขใใซใชใผใใผใฉใคใ
โ โโโ [05-ไปๅพใฎใญใผใใใใ.md] # ไปๅพใฎใญใผใใใใ โ NumbatใKAIROSใ้ณๅฃฐใขใผใใๆชๅ
ฌ้ใใผใซ
โ
โโโ ko/ # ํ๊ตญ์ด
โ โโโ [01-ํ
๋ ๋ฉํธ๋ฆฌ์-ํ๋ผ์ด๋ฒ์.md] # ํ
๋ ๋ฉํธ๋ฆฌ ๋ฐ ํ๋ผ์ด๋ฒ์ โ ์์ง ํญ๋ชฉ, ๋นํ์ฑํ ๋ถ๊ฐ ์ด์
โ โโโ [02-์จ๊ฒจ์ง-๊ธฐ๋ฅ๊ณผ-์ฝ๋๋ค์.md] # ์จ๊ฒจ์ง ๊ธฐ๋ฅ โ ๋ชจ๋ธ ์ฝ๋๋ค์, feature flag, ๋ด๋ถ/์ธ๋ถ ์ฌ์ฉ์ ์ฐจ์ด
โ โโโ [03-์ธ๋์ปค๋ฒ-๋ชจ๋.md] # ์ธ๋์ปค๋ฒ ๋ชจ๋ โ ์คํ์์ค์์ AI ์ ์ ์ํ
โ โโโ [04-์๊ฒฉ-์ ์ด์-ํฌ์ค์์น.md] # ์๊ฒฉ ์ ์ด โ ๊ด๋ฆฌ ์ค์ , ํฌ์ค์์น, ๋ชจ๋ธ ์ค๋ฒ๋ผ์ด๋
โ โโโ [05-ํฅํ-๋ก๋๋งต.md] # ํฅํ ๋ก๋๋งต โ Numbat, KAIROS, ์์ฑ ๋ชจ๋, ๋ฏธ๊ณต๊ฐ ๋๊ตฌ
โ
โโโ zh/ # ไธญๆ
โโโ [01-้ฅๆตไธ้็งๅๆ.md] # ้ฅๆตไธ้็ง โ ๆถ้ไบไปไน๏ผไธบไปไนๆ ๆณ้ๅบ
โโโ [02-้่ๅ่ฝไธๆจกๅไปฃๅท.md] # ้่ๅ่ฝ โ ๆจกๅไปฃๅท๏ผfeature flag๏ผๅ
ๅค็จๆทๅทฎๅผ
โโโ [03-ๅงๅบๆจกๅผๅๆ.md] # ๅงๅบๆจกๅผ โ ๅจๅผๆบ้กน็ฎไธญ้่ AI ่บซไปฝ
โโโ [04-่ฟ็จๆงๅถไธ็ดงๆฅๅผๅ
ณ.md] # ่ฟ็จๆงๅถ โ ๆ็ฎก่ฎพ็ฝฎ๏ผ็ดงๆฅๅผๅ
ณ๏ผๆจกๅ่ฆ็
โโโ [05-ๆชๆฅ่ทฏ็บฟๅพ.md] # ๆชๆฅ่ทฏ็บฟๅพ โ Numbat๏ผKAIROS๏ผ่ฏญ้ณๆจกๅผ๏ผๆชไธ็บฟๅทฅๅ
ท
Click any filename above to jump to the full report.
| # | Topic | Key Findings |
|---|---|---|
| 01 | Telemetry & Privacy | Two analytics sinks (1P โ Anthropic, Datadog). Environment fingerprint, process metrics, repo hash on every event. No UI-exposed opt-out for 1st-party logging. OTEL_LOG_TOOL_DETAILS=1 enables full tool input capture. |
| 02 | Hidden Features & Codenames | Animal codenames (Capybara v8, Tengu, FennecโOpus 4.6, Numbat next). Feature flags use random word pairs (tengu_frond_boric) to obscure purpose. Internal users get better prompts, verification agents, and effort anchors. Hidden commands: /btw, /stickers. |
| 03 | Undercover Mode | Anthropic employees auto-enter undercover mode in public repos. Model instructed: "Do not blow your cover" โ strip all AI attribution, write commits "as a human developer would." No force-OFF exists. Raises transparency questions for open-source communities. |
| 04 | Remote Control | Hourly polling of /api/claude_code/settings. Dangerous changes show blocking dialog โ reject = app exits. 6+ killswitches (bypass permissions, fast mode, voice mode, analytics sink). GrowthBook flags can change any user's behavior without consent. |
| 05 | Future Roadmap | Numbat codename confirmed. Opus 4.7 / Sonnet 4.8 in development. KAIROS = fully autonomous agent mode with <tick> heartbeats, push notifications, PR subscriptions. Voice mode (push-to-talk) ready but gated. 17 unreleased tools found. |
Missing Modules Notice (108 modules)
This source is incomplete. 108 modules referenced by
feature()-gated branches are not included in the npm package. They exist only in Anthropic's internal monorepo and were dead-code-eliminated at compile time. They cannot be recovered fromcli.js,sdk-tools.d.ts, or any published artifact.
Anthropic Internal Code (~70 modules, never published)
These modules have no source files anywhere in the npm package. They are internal Anthropic infrastructure.
<details> <summary>Click to expand full list</summary>| Module | Purpose | Feature Gate |
|---|---|---|
daemon/main.js | Background daemon supervisor | DAEMON |
daemon/workerRegistry.js | Daemon worker registry | DAEMON |
proactive/index.js | Proactive notification system | PROACTIVE |
contextCollapse/index.js | Context collapse service (experimental) | CONTEXT_COLLAPSE |
contextCollapse/operations.js | Collapse operations | CONTEXT_COLLAPSE |
contextCollapse/persist.js | Collapse persistence | CONTEXT_COLLAPSE |
skillSearch/featureCheck.js | Remote skill feature check | EXPERIMENTAL_SKILL_SEARCH |
skillSearch/remoteSkillLoader.js | Remote skill loader | EXPERIMENTAL_SKILL_SEARCH |
skillSearch/remoteSkillState.js | Remote skill state | EXPERIMENTAL_SKILL_SEARCH |
skillSearch/telemetry.js | Skill search telemetry | EXPERIMENTAL_SKILL_SEARCH |
skillSearch/localSearch.js | Local skill search | EXPERIMENTAL_SKILL_SEARCH |
skillSearch/prefetch.js | Skill prefetch | EXPERIMENTAL_SKILL_SEARCH |
coordinator/workerAgent.js | Multi-agent coordinator worker | COORDINATOR_MODE |
bridge/peerSessions.js | Bridge peer session management | BRIDGE_MODE |
assistant/index.js | Kairos assistant mode | KAIROS |
assistant/AssistantSessionChooser.js | Assistant session picker | KAIROS |
compact/reactiveCompact.js | Reactive context compaction | CACHED_MICROCOMPACT |
compact/snipCompact.js | Snip-based compaction | HISTORY_SNIP |
compact/snipProjection.js | Snip projection | HISTORY_SNIP |
compact/cachedMCConfig.js | Cached micro-compact config | CACHED_MICROCOMPACT |
sessionTranscript/sessionTranscript.js | Session transcript service | TRANSCRIPT_CLASSIFIER |
commands/agents-platform/index.js | Internal agents platform | ant (internal) |
commands/assistant/index.js | Assistant command | KAIROS |
commands/buddy/index.js | Buddy system notifications | BUDDY |
commands/fork/index.js | Fork subagent command | FORK_SUBAGENT |
commands/peers/index.js | Multi-peer commands | BRIDGE_MODE |
commands/proactive.js | Proactive command | PROACTIVE |
commands/remoteControlServer/index.js | Remote control server | DAEMON + BRIDGE_MODE |
commands/subscribe-pr.js | GitHub PR subscription | KAIROS_GITHUB_WEBHOOKS |
commands/torch.js | Internal debug tool | TORCH |
commands/workflows/index.js | Workflow commands | WORKFLOW_SCRIPTS |
jobs/classifier.js | Internal job classifier | TEMPLATES |
memdir/memoryShapeTelemetry.js | Memory shape telemetry | MEMORY_SHAPE_TELEMETRY |
services/sessionTranscript/sessionTranscript.js | Session transcript | TRANSCRIPT_CLASSIFIER |
tasks/LocalWorkflowTask/LocalWorkflowTask.js | Local workflow task | WORKFLOW_SCRIPTS |
protectedNamespace.js | Internal namespace guard | ant (internal) |
protectedNamespace.js (envUtils) | Protected namespace runtime | ant (internal) |
coreTypes.generated.js | Generated core types | ant (internal) |
devtools.js | Internal dev tools | ant (internal) |
attributionHooks.js | Internal attribution hooks | COMMIT_ATTRIBUTION |
systemThemeWatcher.js | System theme watcher | AUTO_THEME |
udsClient.js / udsMessaging.js | UDS messaging client | UDS_INBOX |
systemThemeWatcher.js | Theme watcher | AUTO_THEME |
Feature-Gated Tools (~20 modules, DCE'd from bundle)
These tools have type signatures in sdk-tools.d.ts but their implementations were stripped at compile time.
| Tool | Purpose | Feature Gate |
|---|---|---|
REPLTool | Interactive REPL (VM sandbox) | ant (internal) |
SnipTool | Context snipping | HISTORY_SNIP |
SleepTool | Sleep/delay in agent loop | PROACTIVE / KAIROS |
MonitorTool | MCP monitoring | MONITOR_TOOL |
OverflowTestTool | Overflow testing | OVERFLOW_TEST_TOOL |
WorkflowTool | Workflow execution | WORKFLOW_SCRIPTS |
WebBrowserTool | Browser automation | WEB_BROWSER_TOOL |
TerminalCaptureTool | Terminal capture | TERMINAL_PANEL |
TungstenTool | Internal perf monitoring | ant (internal) |
VerifyPlanExecutionTool | Plan verification | CLAUDE_CODE_VERIFY_PLAN |
SendUserFileTool | Send files to users | KAIROS |
SubscribePRTool | GitHub PR subscription | KAIROS_GITHUB_WEBHOOKS |
SuggestBackgroundPRTool | Suggest background PRs | KAIROS |
PushNotificationTool | Push notifications | KAIROS |
CtxInspectTool | Context inspection | CONTEXT_COLLAPSE |
ListPeersTool | List active peers | UDS_INBOX |
DiscoverSkillsTool | Skill discovery | EXPERIMENTAL_SKILL_SEARCH |
Text/Prompt Assets (~6 files)
These are internal prompt templates and documentation, never published.
<details> <summary>Click to expand</summary>| File | Purpose |
|---|---|
yolo-classifier-prompts/auto_mode_system_prompt.txt | Auto-mode system prompt for classifier |
yolo-classifier-prompts/permissions_anthropic.txt | Anthropic-internal permission prompt |
yolo-classifier-prompts/permissions_external.txt | External user permission prompt |
verify/SKILL.md | Verification skill documentation |
verify/examples/cli.md | CLI verification examples |
verify/examples/server.md | Server verification examples |
Why They're Missing
Anthropic Internal Monorepo Published npm Package
โโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ
feature('DAEMON') โ true โโbuildโโโ feature('DAEMON') โ false
โ โ
daemon/main.js โ INCLUDED โโbundleโโ daemon/main.js โ DELETED (DCE)
tools/REPLTool โ INCLUDED โโbundleโโ tools/REPLTool โ DELETED (DCE)
proactive/ โ INCLUDED โโbundleโโ (referenced but absent from src/)
Bun's feature() is a compile-time intrinsic:
- Returns
truein Anthropic's internal build โ code is kept in the bundle - Returns
falsein the published build โ code is dead-code-eliminated - The 108 modules simply do not exist anywhere in the published artifact
Copyright & Disclaimer
Copyright (c) Anthropic. All rights reserved.
All source code in this repository is the intellectual property of Anthropic and Claude.
This repository is provided strictly for technical research and educational purposes.
Commercial use is strictly prohibited.
If you are the copyright owner and believe this repository infringes your rights,
please contact the repository owner for immediate removal.
Stats
| Item | Count |
|---|---|
| Source files (.ts/.tsx) | ~1,884 |
| Lines of code | ~512,664 |
| Largest single file | query.ts (~785KB) |
| Built-in tools | ~40+ |
| Slash commands | ~80+ |
| Dependencies (node_modules) | ~192 packages |
| Runtime | Bun (compiled to Node.js >= 18 bundle) |
The Agent Pattern
THE CORE LOOP
=============
User --> messages[] --> Claude API --> response
|
stop_reason == "tool_use"?
/ \
yes no
| |
execute tools return text
append tool_result
loop back -----------------> messages[]
That is the minimal agent loop. Claude Code wraps this loop
with a production-grade harness: permissions, streaming,
concurrency, compaction, sub-agents, persistence, and MCP.
Directory Reference
src/
โโโ main.tsx # REPL bootstrap, 4,683 lines
โโโ QueryEngine.ts # SDK/headless query lifecycle engine
โโโ query.ts # Main agent loop (785KB, largest file)
โโโ Tool.ts # Tool interface + buildTool factory
โโโ Task.ts # Task types, IDs, state base
โโโ tools.ts # Tool registry, presets, filtering
โโโ commands.ts # Slash command definitions
โโโ context.ts # User input context
โโโ cost-tracker.ts # API cost accumulation
โโโ setup.ts # First-run setup flow
โ
โโโ bridge/ # Claude Desktop / remote bridge
โ โโโ bridgeMain.ts # Session lifecycle manager
โ โโโ bridgeApi.ts # HTTP client
โ โโโ bridgeConfig.ts # Connection config
โ โโโ bridgeMessaging.ts # Message relay
โ โโโ sessionRunner.ts # Process spawning
โ โโโ jwtUtils.ts # JWT refresh
โ โโโ workSecret.ts # Auth tokens
โ โโโ capacityWake.ts # Capacity-based wakeup
โ
โโโ cli/ # CLI infrastructure
โ โโโ handlers/ # Command handlers
โ โโโ transports/ # I/O transports (stdio, structured)
โ
โโโ commands/ # ~80 slash commands
โ โโโ agents/ # Agent management
โ โโโ compact/ # Context compaction
โ โโโ config/ # Settings management
โ โโโ help/ # Help display
โ โโโ login/ # Authentication
โ โโโ mcp/ # MCP server management
โ โโโ memory/ # Memory system
โ โโโ plan/ # Plan mode
โ โโโ resume/ # Session resume
โ โโโ review/ # Code review
โ โโโ ... # 70+ more commands
โ
โโโ components/ # React/Ink terminal UI
โ โโโ design-system/ # Reusable UI primitives
โ โโโ messages/ # Message rendering
โ โโโ permissions/ # Permission dialogs
โ โโโ PromptInput/ # Input field + suggestions
โ โโโ LogoV2/ # Branding + welcome screen
โ โโโ Settings/ # Settings panels
โ โโโ Spinner.tsx # Loading indicators
โ โโโ ... # 40+ component groups
โ
โโโ entrypoints/ # Application entry points
โ โโโ cli.tsx # CLI main (version, help, daemon)
โ โโโ sdk/ # Agent SDK (types, sessions)
โ โโโ mcp.ts # MCP server entry
โ
โโโ hooks/ # React hooks
โ โโโ useCanUseTool.tsx # Permission checking
โ โโโ useReplBridge.tsx # Bridge connection
โ โโโ notifs/ # Notification hooks
โ โโโ toolPermission/ # Tool permission handlers
โ
โโโ services/ # Business logic layer
โ โโโ api/ # Claude API client
โ โ โโโ claude.ts # Streaming API calls
โ โ โโโ errors.ts # Error categorization
โ โ โโโ withRetry.ts # Retry logic
โ โโโ analytics/ # Telemetry + GrowthBook
โ โโโ compact/ # Context compression
โ โโโ mcp/ # MCP connection management
โ โโโ tools/ # Tool execution engine
โ โ โโโ StreamingToolExecutor.ts # Parallel tool runner
โ โ โโโ toolOrchestration.ts # Batch orchestration
โ โโโ plugins/ # Plugin loader
โ โโโ settingsSync/ # Cross-device settings
โ
โโโ state/ # Application state
โ โโโ AppStateStore.ts # Store definition
โ โโโ AppState.tsx # React provider + hooks
โ
โโโ tasks/ # Task implementations
โ โโโ LocalShellTask/ # Bash command execution
โ โโโ LocalAgentTask/ # Sub-agent execution
โ โโโ RemoteAgentTask/ # Remote agent via bridge
โ โโโ InProcessTeammateTask/ # In-process teammate
โ โโโ DreamTask/ # Background thinking
โ
โโโ tools/ # 40+ tool implementations
โ โโโ AgentTool/ # Sub-agent spawning + fork
โ โโโ BashTool/ # Shell command execution
โ โโโ FileReadTool/ # File reading (PDF, image, etc)
โ โโโ FileEditTool/ # String-replace editing
โ โโโ FileWriteTool/ # Full file creation
โ โโโ GlobTool/ # File pattern search
โ โโโ GrepTool/ # Content search (ripgrep)
โ โโโ WebFetchTool/ # HTTP fetching
โ โโโ WebSearchTool/ # Web search
โ โโโ MCPTool/ # MCP tool wrapper
โ โโโ SkillTool/ # Skill invocation
โ โโโ AskUserQuestionTool/ # User interaction
โ โโโ ... # 30+ more tools
โ
โโโ types/ # Type definitions
โ โโโ message.ts # Message discriminated unions
โ โโโ permissions.ts # Permission types
โ โโโ tools.ts # Tool progress types
โ โโโ ids.ts # Branded ID types
โ
โโโ utils/ # Utilities (largest directory)
โ โโโ permissions/ # Permission rule engine
โ โโโ messages/ # Message formatting
โ โโโ model/ # Model selection logic
โ โโโ settings/ # Settings management
โ โโโ sandbox/ # Sandbox runtime adapter
โ โโโ hooks/ # Hook execution
โ โโโ memory/ # Memory system utils
โ โโโ git/ # Git operations
โ โโโ github/ # GitHub API
โ โโโ bash/ # Bash execution helpers
โ โโโ swarm/ # Multi-agent swarm
โ โโโ telemetry/ # Telemetry reporting
โ โโโ ... # 30+ more util groups
โ
โโโ vendor/ # Native module source stubs
โโโ audio-capture-src/ # Audio input
โโโ image-processor-src/ # Image processing
โโโ modifiers-napi-src/ # Native modifiers
โโโ url-handler-src/ # URL handling
Architecture Overview
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ENTRY LAYER โ
โ cli.tsx โโ> main.tsx โโ> REPL.tsx (interactive) โ
โ โโโ> QueryEngine.ts (headless/SDK) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ QUERY ENGINE โ
โ submitMessage(prompt) โโ> AsyncGenerator<SDKMessage> โ
โ โ โ
โ โโโ fetchSystemPromptParts() โโ> assemble system prompt โ
โ โโโ processUserInput() โโ> handle /commands โ
โ โโโ query() โโ> main agent loop โ
โ โ โโโ StreamingToolExecutor โโ> parallel tool execution โ
โ โ โโโ autoCompact() โโ> context compression โ
โ โ โโโ runTools() โโ> tool orchestration โ
โ โโโ yield SDKMessage โโ> stream to consumer โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโ
โผ โผ โผ
โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ
โ TOOL SYSTEM โ โ SERVICE LAYER โ โ STATE LAYER โ
โ โ โ โ โ โ
โ Tool Interface โ โ api/claude.ts โ โ AppState Store โ
โ โโ call() โ โ API client โ โ โโ permissions โ
โ โโ validate() โ โ compact/ โ โ โโ fileHistory โ
โ โโ checkPerms() โ โ auto-compact โ โ โโ agents โ
โ โโ render() โ โ mcp/ โ โ โโ fastMode โ
โ โโ prompt() โ โ MCP protocol โ โ โ
โ โ โ analytics/ โ โ React Context โ
โ 40+ Built-in: โ โ telemetry โ โ โโ useAppState โ
โ โโ BashTool โ โ tools/ โ โ โโ useSetState โ
โ โโ FileRead โ โ executor โ โ โ
โ โโ FileEdit โ โ plugins/ โ โโโโโโโโโโโโโโโโโโโโ
โ โโ Glob/Grep โ โ loader โ
โ โโ AgentTool โ โ settingsSync/ โ
โ โโ WebFetch โ โ cross-device โ
โ โโ MCPTool โ โ oauth/ โ
โ โ โ auth flow โ
โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ โ
โผ โผ
โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ TASK SYSTEM โ โ BRIDGE LAYER โ
โ โ โ โ
โ Task Types: โ โ bridgeMain.ts โ
โ โโ local_bash โ โ session mgmt โ
โ โโ local_agent โ โ bridgeApi.ts โ
โ โโ remote_agent โ โ HTTP client โ
โ โโ in_process โ โ workSecret.ts โ
โ โโ dream โ โ auth tokens โ
โ โโ workflow โ โ sessionRunner โ
โ โ โ process spawn โ
โ ID: prefix+8chr โ โโโโโโโโโโโโโโโโโโโ
โ b=bash a=agent โ
โ r=remote t=team โ
โโโโโโโโโโโโโโโโโโโโ
Data Flow: A Single Query Lifecycle
USER INPUT (prompt / slash command)
โ
โผ
processUserInput() โ parse /commands, build UserMessage
โ
โผ
fetchSystemPromptParts() โ tools โ prompt sections, CLAUDE.md memory
โ
โผ
recordTranscript() โ persist user message to disk (JSONL)
โ
โผ
โโโ normalizeMessagesForAPI() โ strip UI-only fields, compact if needed
โ โ
โ โผ
โ Claude API (streaming) โ POST /v1/messages with tools + system prompt
โ โ
โ โผ
โ stream events โ message_start โ content_block_delta โ message_stop
โ โ
โ โโ text block โโโโโโโโโโโโโโโ yield to consumer (SDK / REPL)
โ โ
โ โโ tool_use block?
โ โ
โ โผ
โ StreamingToolExecutor โ partition: concurrent-safe vs serial
โ โ
โ โผ
โ canUseTool() โ permission check (hooks + rules + UI prompt)
โ โ
โ โโ DENY โโโโโโโโโโโโโโโโโ append tool_result(error), continue loop
โ โ
โ โโ ALLOW
โ โ
โ โผ
โ tool.call() โ execute the tool (Bash, Read, Edit, etc.)
โ โ
โ โผ
โ append tool_result โ push to messages[], recordTranscript()
โ โ
โโโโโโโโโโโ โ loop back to API call
โ
โผ (stop_reason != "tool_use")
yield result message โ final text, usage, cost, session_id
Tool System Architecture
TOOL INTERFACE
==============
buildTool(definition) โโ> Tool<Input, Output, Progress>
Every tool implements:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LIFECYCLE โ
โ โโโ validateInput() โ reject bad args early โ
โ โโโ checkPermissions() โ tool-specific authz โ
โ โโโ call() โ execute and return result โ
โ โ
โ CAPABILITIES โ
โ โโโ isEnabled() โ feature gate check โ
โ โโโ isConcurrencySafe() โ can run in parallel? โ
โ โโโ isReadOnly() โ no side effects? โ
โ โโโ isDestructive() โ irreversible ops? โ
โ โโโ interruptBehavior() โ cancel or block on user? โ
โ โ
โ RENDERING (React/Ink) โ
โ โโโ renderToolUseMessage() โ input display โ
โ โโโ renderToolResultMessage() โ output display โ
โ โโโ renderToolUseProgressMessage() โ spinner/status โ
โ โโโ renderGroupedToolUse() โ parallel tool groups โ
โ โ
โ AI FACING โ
โ โโโ prompt() โ tool description for LLM โ
โ โโโ description() โ dynamic description โ
โ โโโ mapToolResultToAPI() โ format for API response โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Complete Tool Inventory
FILE OPERATIONS SEARCH & DISCOVERY EXECUTION
โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโ
FileReadTool GlobTool BashTool
FileEditTool GrepTool PowerShellTool
FileWriteTool ToolSearchTool
NotebookEditTool INTERACTION
โโโโโโโโโโโ
WEB & NETWORK AGENT / TASK AskUserQuestionTool
โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโ BriefTool
WebFetchTool AgentTool
WebSearchTool SendMessageTool PLANNING & WORKFLOW
TeamCreateTool โโโโโโโโโโโโโโโโโโโโ
MCP PROTOCOL TeamDeleteTool EnterPlanModeTool
โโโโโโโโโโโโโโ TaskCreateTool ExitPlanModeTool
MCPTool TaskGetTool EnterWorktreeTool
ListMcpResourcesTool TaskUpdateTool ExitWorktreeTool
ReadMcpResourceTool TaskListTool TodoWriteTool
TaskStopTool
TaskOutputTool SYSTEM
โโโโโโโโ
SKILLS & EXTENSIONS ConfigTool
โโโโโโโโโโโโโโโโโโโโโ SkillTool
SkillTool ScheduleCronTool
LSPTool SleepTool
TungstenTool
Permission System
TOOL CALL REQUEST
โ
โผ
โโ validateInput() โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ reject invalid inputs before any permission check โ
โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโ PreToolUse Hooks โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ user-defined shell commands (settings.json hooks) โ
โ can: approve, deny, or modify input โ
โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโ Permission Rules โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ alwaysAllowRules: match tool name/pattern โ auto โ
โ alwaysDenyRules: match tool name/pattern โ deny โ
โ alwaysAskRules: match tool name/pattern โ ask โ
โ Sources: settings, CLI args, session decisions โ
โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
no rule match?
โ
โผ
โโ Interactive Prompt โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ User sees tool name + input โ
โ Options: Allow Once / Allow Always / Deny โ
โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโ checkPermissions() โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Tool-specific logic (e.g. path sandboxing) โ
โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
APPROVED โ tool.call()
Sub-Agent & Multi-Agent Architecture
MAIN AGENT
==========
โ
โโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโ
โผ โผ โผ
โโโโโโโโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโโโโโโโ
โ FORK AGENT โ โ REMOTE โ โ IN-PROCESS โ
โ โ โ AGENT โ โ TEAMMATE โ
โ Fork process โ โ Bridge โ โ Same process โ
โ Shared cache โ โ session โ โ Async contextโ
โ Fresh msgs[] โ โ Isolated โ โ Shared state โ
โโโโโโโโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโโโโโโโ
SPAWN MODES:
โโ default โ in-process, shared conversation
โโ fork โ child process, fresh messages[], shared file cache
โโ worktree โ isolated git worktree + fork
โโ remote โ bridge to Claude Code Remote / container
COMMUNICATION:
โโ SendMessageTool โ agent-to-agent messages
โโ TaskCreate/Update โ shared task board
โโ TeamCreate/Delete โ team lifecycle management
SWARM MODE (feature-gated):
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Lead Agent โ
โ โโโ Teammate A โโ> claims Task 1 โ
โ โโโ Teammate B โโ> claims Task 2 โ
โ โโโ Teammate C โโ> claims Task 3 โ
โ โ
โ Shared: task board, message inbox โ
โ Isolated: messages[], file cache, cwd โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Context Management (Compact System)
CONTEXT WINDOW BUDGET
โโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ System Prompt (tools, permissions, CLAUDE.md) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ Conversation History โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ [compacted summary of older messages] โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โ [compact_boundary marker] โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โ [recent messages โ full fidelity] โ โ
โ โ user โ assistant โ tool_use โ tool_result โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ Current Turn (user + assistant response) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
THREE COMPRESSION STRATEGIES:
โโ autoCompact โ triggers when token count exceeds threshold
โ summarizes old messages via a compact API call
โโ snipCompact โ removes zombie messages and stale markers
โ (HISTORY_SNIP feature flag)
โโ contextCollapse โ restructures context for efficiency
(CONTEXT_COLLAPSE feature flag)
COMPACTION FLOW:
messages[] โโ> getMessagesAfterCompactBoundary()
โ
โผ
older messages โโ> Claude API (summarize) โโ> compact summary
โ
โผ
[summary] + [compact_boundary] + [recent messages]
MCP (Model Context Protocol) Integration
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ MCP ARCHITECTURE โ
โ โ
โ MCPConnectionManager.tsx โ
โ โโโ Server Discovery (config from settings.json) โ
โ โ โโโ stdio โ spawn child process โ
โ โ โโโ sse โ HTTP EventSource โ
โ โ โโโ http โ Streamable HTTP โ
โ โ โโโ ws โ WebSocket โ
โ โ โโโ sdk โ in-process transport โ
โ โ โ
โ โโโ Client Lifecycle โ
โ โ โโโ connect โ initialize โ list tools โ
โ โ โโโ tool calls via MCPTool wrapper โ
โ โ โโโ disconnect / reconnect with backoff โ
โ โ โ
โ โโโ Authentication โ
โ โ โโโ OAuth 2.0 flow (McpOAuthConfig) โ
โ โ โโโ Cross-App Access (XAA / SEP-990) โ
โ โ โโโ API key via headers โ
โ โ โ
โ โโโ Tool Registration โ
โ โโโ mcp__<server>__<tool> naming convention โ
โ โโโ Dynamic schema from MCP server โ
โ โโโ Permission passthrough to Claude Code โ
โ โโโ Resource listing (ListMcpResourcesTool) โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Bridge Layer (Claude Desktop / Remote)
Claude Desktop / Web / Cowork Claude Code CLI
โโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ
โ Bridge Client โ โโ HTTP โโโ โ bridgeMain.ts โ
โ (Desktop App) โ โ โ
โโโโโโโโโโโโโโโโโโโโโ โ Session Manager โ
โ โโโ spawn CLI โ
PROTOCOL: โ โโโ poll status โ
โโ JWT authentication โ โโโ relay msgs โ
โโ Work secret exchange โ โโโ capacityWake โ
โโ Session lifecycle โ โ
โ โโโ create โ Backoff: โ
โ โโโ run โ โโ conn: 2sโ2m โ
โ โโ stop โ โโ gen: 500msโ30sโ
โโ Token refresh scheduler โโโโโโโโโโโโโโโโโโโโ
Session Persistence
SESSION STORAGE
โโโโโโโโโโโโโโ
~/.claude/projects/<hash>/sessions/
โโโ <session-id>.jsonl โ append-only log
โโโ {"type":"user",...}
โโโ {"type":"assistant",...}
โโโ {"type":"progress",...}
โโโ {"type":"system","subtype":"compact_boundary",...}
RESUME FLOW:
getLastSessionLog() โโ> parse JSONL โโ> rebuild messages[]
โ
โโโ --continue โ last session in cwd
โโโ --resume <id> โ specific session
โโโ --fork-session โ new ID, copy history
PERSISTENCE STRATEGY:
โโ User messages โ await write (blocking, for crash recovery)
โโ Assistant msgs โ fire-and-forget (order-preserving queue)
โโ Progress โ inline write (dedup on next query)
โโ Flush โ on result yield / cowork eager flush
Feature Flag System
DEAD CODE ELIMINATION (Bun compile-time)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
feature('FLAG_NAME') โโโ true โ included in bundle
โโโ false โ stripped from bundle
FLAGS (observed in source):
โโ COORDINATOR_MODE โ multi-agent coordinator
โโ HISTORY_SNIP โ aggressive history trimming
โโ CONTEXT_COLLAPSE โ context restructuring
โโ DAEMON โ background daemon workers
โโ AGENT_TRIGGERS โ cron/remote triggers
โโ AGENT_TRIGGERS_REMOTE โ remote trigger support
โโ MONITOR_TOOL โ MCP monitoring tool
โโ WEB_BROWSER_TOOL โ browser automation
โโ VOICE_MODE โ voice input/output
โโ TEMPLATES โ job classifier
โโ EXPERIMENTAL_SKILL_SEARCH โ skill discovery
โโ KAIROS โ push notifications, file sends
โโ PROACTIVE โ sleep tool, proactive behavior
โโ OVERFLOW_TEST_TOOL โ testing tool
โโ TERMINAL_PANEL โ terminal capture
โโ WORKFLOW_SCRIPTS โ workflow tool
โโ CHICAGO_MCP โ computer use MCP
โโ DUMP_SYSTEM_PROMPT โ prompt extraction (ant-only)
โโ UDS_INBOX โ peer discovery
โโ ABLATION_BASELINE โ experiment ablation
โโ UPGRADE_NOTICE โ upgrade notifications
RUNTIME GATES:
โโ process.env.USER_TYPE === 'ant' โ Anthropic-internal features
โโ GrowthBook feature flags โ A/B experiments at runtime
State Management
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ AppState Store โ
โ โ
โ AppState { โ
โ toolPermissionContext: { โ
โ mode: PermissionMode, โ default/plan/etc โ
โ additionalWorkingDirectories, โ
โ alwaysAllowRules, โ auto-approve โ
โ alwaysDenyRules, โ auto-reject โ
โ alwaysAskRules, โ always prompt โ
โ isBypassPermissionsModeAvailable โ
โ }, โ
โ fileHistory: FileHistoryState, โ undo snapshots โ
โ attribution: AttributionState, โ commit tracking โ
โ verbose: boolean, โ
โ mainLoopModel: string, โ active model โ
โ fastMode: FastModeState, โ
โ speculation: SpeculationState โ
โ } โ
โ โ
โ React Integration: โ
โ โโโ AppStateProvider โ creates store via createContext โ
โ โโโ useAppState(sel) โ selector-based subscriptions โ
โ โโโ useSetAppState() โ immer-style updater function โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The 12 Progressive Harness Mechanisms
This source code demonstrates 12 layered mechanisms that a production AI agent harness needs beyond the basic loop. Each builds on the previous:
s01 THE LOOP "One loop & Bash is all you need"
query.ts: the while-true loop that calls Claude API,
checks stop_reason, executes tools, appends results.
s02 TOOL DISPATCH "Adding a tool = adding one handler"
Tool.ts + tools.ts: every tool registers into the dispatch
map. The loop stays identical. buildTool() factory provides
safe defaults.
s03 PLANNING "An agent without a plan drifts"
EnterPlanModeTool/ExitPlanModeTool + TodoWriteTool:
list steps first, then execute. Doubles completion rate.
s04 SUB-AGENTS "Break big tasks; clean context per subtask"
AgentTool + forkSubagent.ts: each child gets fresh messages[],
keeping the main conversation clean.
s05 KNOWLEDGE ON DEMAND "Load knowledge when you need it"
SkillTool + memdir/: inject via tool_result, not system prompt.
CLAUDE.md files loaded lazily per directory.
s06 CONTEXT COMPRESSION "Context fills up; make room"
services/compact/: three-layer strategy:
autoCompact (summarize) + snipCompact (trim) + contextCollapse
s07 PERSISTENT TASKS "Big goals โ small tasks โ disk"
TaskCreate/Update/Get/List: file-based task graph with
status tracking, dependencies, and persistence.
s08 BACKGROUND TASKS "Slow ops in background; agent keeps thinking"
DreamTask + LocalShellTask: daemon threads run commands,
inject notifications on completion.
s09 AGENT TEAMS "Too big for one โ delegate to teammates"
TeamCreate/Delete + InProcessTeammateTask: persistent
teammates with async mailboxes.
s10 TEAM PROTOCOLS "Shared communication rules"
SendMessageTool: one request-response pattern drives
all negotiation between agents.
s11 AUTONOMOUS AGENTS "Teammates scan and claim tasks themselves"
coordinator/coordinatorMode.ts: idle cycle + auto-claim,
no need for lead to assign each task.
s12 WORKTREE ISOLATION "Each works in its own directory"
EnterWorktreeTool/ExitWorktreeTool: tasks manage goals,
worktrees manage directories, bound by ID.
Key Design Patterns
| Pattern | Where | Purpose |
|---|---|---|
| AsyncGenerator streaming | QueryEngine, query() | Full-chain streaming from API to consumer |
| Builder + Factory | buildTool() | Safe defaults for tool definitions |
| Branded Types | SystemPrompt, asSystemPrompt() | Prevent string/array confusion |
| Feature Flags + DCE | feature() from bun:bundle | Compile-time dead code elimination |
| Discriminated Unions | Message types | Type-safe message handling |
| Observer + State Machine | StreamingToolExecutor | Tool execution lifecycle tracking |
| Snapshot State | FileHistoryState | Undo/redo for file operations |
| Ring Buffer | Error log | Bounded memory for long sessions |
| Fire-and-Forget Write | recordTranscript() | Non-blocking persistence with ordering |
| Lazy Schema | lazySchema() | Defer Zod schema evaluation for performance |
| Context Isolation | AsyncLocalStorage | Per-agent context in shared process |
Build Notes
This source is not directly compilable from this repo alone:
- Missing
tsconfig.json, build scripts, and Bun bundler config feature()calls are Bun compile-time intrinsics โ resolved during bundlingMACRO.VERSIONis injected at build timeprocess.env.USER_TYPE === 'ant'sections are Anthropic-internal- The compiled
cli.jsis a self-contained 12MB bundle requiring only Node.js >= 18 - Source maps (
cli.js.map, 60MB) map back to these source files for debugging
See QUICKSTART.md for build instructions and workarounds.
License
All source code in this repository is copyright Anthropic and Claude. This repository is for technical research and education only. See the original npm package for full license terms.