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.
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.
These modules have no source files anywhere in the npm package. They are internal Anthropic infrastructure.
| 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 |
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 |
These are internal prompt templates and documentation, never published.
| 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 |
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 (c) Anthropic PBC. All rights reserved.
All source code in this repository is the intellectual property of Anthropic.
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.
| 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 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.
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
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 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 β
ββββββββββββββββββββ
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 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 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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
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()
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 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 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) β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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 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
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
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 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 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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.
| 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 |
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.
All source code in this repository is copyright Anthropic PBC. This repository is for technical research and education only. See the original npm package for full license terms.