Comprehensive multi-agent analysis of the Claude Code internal source codebase. This document covers architecture, hidden features, tools, commands, models, feature flags, and internal systems.
- Overview
- Hidden Feature: Voice Mode
- Hidden Feature: Buddy System (ASCII Pet Companion)
- Hidden Feature: Dream Tasks (Auto-Memory Consolidation)
- Multi-Agent Architecture
- Bridge System — Remote Control
- Complete Tool Inventory
- Upstream Proxy
- Native TypeScript Ports
- Memory System (memdir)
- Commands & Keybindings
- Screens & UI Architecture
- Skills System
- Hooks System
- Services Ecosystem
- State Management
- Context Management
- Query Engine & Query Loop
- Model Definitions & Pricing
- Feature Flags (89+)
- API Beta Headers
- Authentication & Authorization
- Cost Tracking & Billing
- Analytics & Telemetry
- Bootstrap & Initialization Flow
- Moreright — Internal Query Hook
- Migrations
- Entrypoints
- Vim Mode
- Ink Rendering System
- Component Library
- Output Styles
- Plugin System
- MCP Integration
- Computer Use & Chrome Integration
- Notification System
- Permission System
- Key Architecture Patterns
- File Reference Map
- Summary Statistics
This is the internal source code for Claude Code (Anthropic's CLI/IDE agent), a ~500-file TypeScript codebase built on React/Ink for terminal UI. It reveals a far more sophisticated system than what's publicly visible, with 89+ feature flags, 41+ tools, 67+ commands, and several entirely hidden subsystems.
assistant/ — KAIROS assistant session history
bootstrap/ — Application state initialization
bridge/ — Remote control IPC & session management (33 files, 400KB+)
buddy/ — ASCII pet companion system (April 2026 launch)
cli/ — CLI argument parsing
commands/ — 67+ slash commands
components/ — 146 React/Ink UI components
constants/ — Feature flags, prompts, API limits, tools config
context/ — React contexts (voice, stats, notifications, modals)
coordinator/ — Multi-agent orchestration mode
entrypoints/ — CLI, MCP, SDK entry points
hooks/ — 68+ custom React hooks + 16 notification hooks
ink/ — Custom Ink fork (terminal UI framework, 96 files, 40K+ lines)
keybindings/ — 100+ keybindings across 17 contexts
memdir/ — Persistent memory system with typed taxonomy
migrations/ — 11 incremental settings/model migrations
moreright/ — Internal-only query interception hook (stubbed externally)
native-ts/ — Pure TS ports of Rust/C++ native modules
outputStyles/ — Configurable output formatting
plugins/ — Plugin loading & management
query/ — Query support utilities
remote/ — Remote session management (CCR)
schemas/ — Data validation schemas
screens/ — 3 UI screens (REPL, Doctor, ResumeConversation)
server/ — Direct Connect server sessions
services/ — 35+ service modules
skills/ — Bundled skill definitions
state/ — Centralized immutable state management
tasks/ — 7 task type implementations
tools/ — 41+ tool implementations
types/ — TypeScript type definitions
upstreamproxy/ — HTTPS MITM proxy for CCR containers
utils/ — Shared utilities (model, worktree, config, etc.)
vim/ — Full vim mode implementation
voice/ — Voice mode feature gating
main.tsx — Main launch flow (4,683 lines)
commands.ts — Command registry & loading
context.ts — Conversation context injection
cost-tracker.ts — Per-model cost tracking (324 lines)
costHook.ts — Cost summary React hook
dialogLaunchers.tsx — Dialog launchers for setup flows
history.ts — Session history
ink.ts — Ink instance management
interactiveHelpers.tsx — Interactive setup helpers (57KB)
projectOnboardingState.ts — Onboarding state tracking
query.ts — Core query loop (generator-based)
QueryEngine.ts — Query orchestrator
replLauncher.tsx — REPL component launcher
setup.ts — Startup sequence (477 lines)
Task.ts — Base task types & ID generation
tasks.ts — Task factory/registry
Tool.ts — Tool type definitions
tools.ts — Tool registry & getTools()
2. Hidden Feature: Voice Mode
Status: Feature-flagged (VOICE_MODE), with GrowthBook kill-switch tengu_amber_quartz_disabled
A complete push-to-talk voice input system.
Feature Gating (voice/voiceModeEnabled.ts):
isVoiceGrowthBookEnabled(): Checksfeature('VOICE_MODE')+ GrowthBook kill-switchtengu_amber_quartz_disabledhasVoiceAuth(): Verifies Anthropic OAuth token exists (NOT available with API keys, Bedrock, Vertex, or Foundry)isVoiceModeEnabled(): Combined auth + kill-switch check
Audio Capture (services/voice.ts — 526 lines):
- Native recording: Uses
audio-capture-napimodule (cpal-based) on macOS/Linux/Windows- Lazy-loaded on first voice keypress (~1-8s cold, memoized after)
- Captures 16kHz, 16-bit signed, mono PCM
- Fallbacks:
- Linux:
arecord(ALSA) with device probing - macOS/Linux: SoX
reccommand with silence detection
- Linux:
- Dependency checking: Automatically detects and suggests package manager installs (brew, apt-get, dnf, pacman)
- Microphone permissions: TCC dialog trigger on macOS (probed during
/voicecommand)
Speech-to-Text (services/voiceStreamSTT.ts — 545 lines):
- Endpoint: Anthropic's private
/api/ws/speech_to_text/voice_streamWebSocket - Route: Uses
api.anthropic.comlistener instead ofclaude.ai(avoids CF TLS fingerprinting) - STT Backend: Deepgram Nova 3 (via GrowthBook gate
tengu_cobalt_frost+ conversation-engine) - Protocol: JSON control messages (KeepAlive, CloseStream) + binary audio frames
- Transcript handling:
- TranscriptText messages with interim vs. final flag
- TranscriptEndpoint signals utterance end
- Auto-finalize: Detects segment switches and finalizes old text (not on Nova 3)
- Silent-drop replay: Re-sends buffered audio if server accepted but returned nothing
- Timeouts:
- KeepAlive every 8 seconds (prevents idle timeout)
- finalize() resolves via: TranscriptEndpoint (fastest ~300ms), no-data timer (1.5s), safety timeout (5s), WS close
- Error handling: Distinguishes temporary (retry) vs. fatal (4xx) HTTP upgrades
Voice Keyterms (services/voiceKeyterms.ts — 107 lines):
- Builds domain-specific vocabulary hints (Deepgram "keywords") for better STT accuracy
- Sources:
- Global hardcoded: MCP, symlink, grep, regex, localhost, TypeScript, JSON, OAuth, webhook, gRPC, subagent, worktree
- Project name (basename of root directory)
- Git branch words (split identifiers: feat/voice-keyterms → feat, voice, keyterms)
- Recent file names (max 50 terms total)
React Integration (hooks/useVoice.ts — 250+ lines):
- Language normalization: Maps 90+ language names + native names to BCP-47 codes
- Supported STT languages: en, es, fr, ja, de, pt, it, ko, hi, id, ru, pl, tr, nl, uk, el, cs, da, sv, no
- Falls back to English if unsupported language configured
- Audio level detection (RMS envelope) for recording feedback
- Silent-drop replay mechanism: If server accepted audio but returned zero transcript, retry with fresh connection
- Accumulates transcript chunks until TranscriptEndpoint or safety timeout
- Handles both silence-detection (continuous speech mode) and push-to-talk (manual stop)
UI Integration (hooks/useVoiceIntegration.tsx + PromptInput):
- Keyboard binding detection (matches KeyboardEvent to ParsedKeystroke)
- Hold-threshold logic: Bare-char bindings (space, v) require 5 rapid presses; modifier combos activate on first press
- Warmup feedback: Shows feedback after 2 rapid keystrokes
- Interim transcript insertion: Places live transcript at cursor without clobbering surrounding text
- Prefix/suffix preservation: Captures text before/after cursor for replay on error
Voice Command (/voice toggle):
- Checks auth, GrowthBook, recording availability, microphone permissions, STT API key, and recording tool dependencies
- Enables voiceEnabled setting if all pass
settings.voiceEnabled: boolean— User's toggle~/.claude/config.json: voiceLangHintShownCount, voiceLangHintLastLanguage (avoids repeating language tips)- Environment overrides:
VOICE_STREAM_BASE_URL(testing),CLAUDE_CODE_REMOTE(disables in remote environments)
- Silent-drop detection (anthropics/anthropic#287008): If server accepts audio (WS open) but sends TranscriptEndpoint with no TranscriptText, the connection likely hit a broken backend. Buffers the audio and retries on fresh connection.
- GrowthBook emergency kill-switch:
tengu_amber_quartz_disabledfeature flag can turn off voice instantly. - Language hint counter: Resets whenever STT language changes, shows hint max 2 times.
- Deepgram Nova 3 opt-in (tengu_cobalt_frost): Uses conversation-engine route for better accuracy; cumulative transcripts + mid-text revisions require different finalize logic.
- Platform-specific TLS: Uses mTLS on Linux/Windows; browser-fingerprint JA3 on macOS (CF zone allows).
- Native module warmup trade-off: No preload during startup (would freeze ~1-8s), accepts ~1s delay on first voice press.
voice/voiceModeEnabled.ts(55 lines) — Feature gatingservices/voice.ts(526 lines) — Audio captureservices/voiceStreamSTT.ts(545 lines) — STT WebSocketservices/voiceKeyterms.ts(107 lines) — Vocab hintshooks/useVoice.ts(250+ lines) — Main hookhooks/useVoiceEnabled.ts(26 lines) — Memoized authhooks/useVoiceIntegration.tsx(200+ lines) — UI integrationcontext/voice.tsx(87 lines) — State providercommands/voice/index.ts(20 lines) — Command defcommands/voice/voice.ts(151 lines) — Command impl
3. Hidden Feature: Buddy System (ASCII Pet Companion)
Status: Feature-flagged (BUDDY), launching April 1-7, 2026 (staggered by timezone for sustained Twitter buzz)
An ASCII-art companion pet that sits beside your input box.
Deterministic RNG: Uses Mulberry32 seeded PRNG on hash(userId + salt) for reproducible generation.
Bones (deterministic, regenerated from userId hash on every read):
| Property | Options |
|---|---|
| Rarity | 60% common, 25% uncommon, 10% rare, 4% epic, 1% legendary |
| Species | 18: duck, goose, blob, cat, dragon, octopus, owl, penguin, turtle, snail, ghost, axolotl, capybara, cactus, robot, rabbit, mushroom, chonk |
| Eyes | 6: ·, ✦, ×, ◉, @, ° |
| Hats | 8: none, crown, tophat, propeller, halo, wizard, beanie, tinyduck (common = none only) |
| Shiny | 1% chance (gold variant) |
| Stats | DEBUGGING, PATIENCE, CHAOS, WISDOM, SNARK (1-100 scale) |
Stat Generation:
- One peak stat (floor + 50-80), one dump stat (floor - 10 to +5), rest scattered (0-40)
- Rarity sets floor: common 5, uncommon 15, rare 25, epic 35, legendary 50
Soul (model-generated, persisted in config.companion):
name: Generated by Claudepersonality: Generated by ClaudehatchedAt: Timestamp
Caching: roll(userId) caches result with memoization (hot path: 500ms sprite tick, keystroke, per-turn)
18 species using String.fromCharCode to obfuscate (avoids excluded-strings.txt collision with model codename):
duck, goose, blob, cat, dragon, octopus, owl, penguin, turtle, snail,
ghost, axolotl, capybara, cactus, robot, rabbit, mushroom, chonk
- Each species has 5-line ASCII art with multiple animation frames
- Frame 0: rest, Frame 1-2: fidget animations
- Eye placeholder
{E}replaced with selected eye character - Hat line 0 (blank in frames 0-1, may have smoke/antenna in frame 2)
Face emoji examples:
- Duck:
(·>| Blob:(··)| Cat:=·ω·=| Dragon:<·~·>
- Idle animation loop:
IDLE_SEQUENCE = [0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 2, 0, 0, 0]- Mostly rest, occasional fidgets, rare blinks (-1 = close eyes on frame 0)
- Ticks every 500ms
- Speech bubble: Shows reactions for ~10 seconds (20 ticks), last 3 seconds fading
- Pet hearts: Float up for ~2.5 seconds when user runs
/buddy pet - Rarity colors: common=inactive, uncommon=success, rare=permission, epic=autoAccept, legendary=warning
- Rendering modes:
- Full sprite (normal terminal width)
- Floating bubble (fullscreen narrow layout)
- Hidden when: BUDDY feature off, no companion,
companionMuted=true
Automatically injects companion_intro attachment on first message mentioning the companion:
A small {species} named {name} sits beside the user's input box and occasionally comments.
You're not {name} — it's a separate watcher. When user addresses {name} directly,
its bubble answers. Stay out of the way: one line or less, or just answer the user's part.
Don't explain you're not {name} — they know.
- Teaser window: April 1-7, 2026 (local date, 24h rolling wave across timezones)
- Shows rainbow-colored
/buddynotification on startup (if no companion hatched) - Detects
/buddyin input (findBuddyTriggerPositions)
{
"companion": {
"name": "string (model-generated)",
"personality": "string (model-generated)",
"hatchedAt": "number (timestamp)"
},
"companionMuted": "boolean (hide sprite + reactions)"
}companionReaction?: string // Latest speech bubble text
companionPetAt?: number // Timestamp of /buddy pet
footerSelection: FooterItem // Can be 'companion' for footer pill
- 4,320+ unique looks (18 species × 6 eyes × 8 hats × 5 rarities)
- Bones persistence as non-persistence: Species/eye/hat/stats regenerate from userId hash on every read. If you rename a species or add new ones, old companions automatically get new bones.
- Users can't fake a legendary — deterministic from userId hash.
- Teaser rollout strategy: April 1-7 for "sustained Twitter buzz instead of single UTC-midnight spike, gentler on soul-gen load." After April 7, stays live forever.
4. Hidden Feature: Dream Tasks (Auto-Memory Consolidation)
Task type dream (prefix d) — a background agent that automatically consolidates session memories.
- Runs as a forked async agent, visible in UI footer and Shift+Down dialog
- Phases:
starting→updating(when first Edit/Write tool used) sessionsReviewing: count of sessions analyzedfilesTouched[]: paths observed in tool callsturns[]: assistant responses with tool counts collapsed- On completion/kill →
rollbackConsolidationLock()(rewind lock mtime so next session can retry) - Gated by
KAIROS/KAIROS_DREAMfeature flags - Triggered by
services/autoDream.ts
Enabled via CLAUDE_CODE_COORDINATOR_MODE env var — transforms Claude Code into a multi-agent orchestrator:
┌─────────────────────────────────────────────────┐
│ Coordinator (main session) │
│ - Reads findings from workers │
│ - Synthesizes implementation specs │
│ - Manages concurrency │
└──────┬──────────────────────────────────────────┘
│
├─→ Worker 1 (LocalAgentTask) - Research [parallel]
├─→ Worker 2 (LocalAgentTask) - Research [parallel]
├─→ Worker 3 (LocalAgentTask) - Implement [serialized per file set]
└─→ Worker 4 (LocalAgentTask) - Verify [fresh agent, independent]
Concurrency Rules:
- Read-only tasks (research): Run in parallel freely
- Write-heavy tasks (implementation): Serialize per file set
- Verification: Can run alongside implementation on different file areas
| Type | Prefix | Purpose | Execution Context |
|---|---|---|---|
local_agent |
a |
Worker agents spawned via Agent tool | Local async query() |
local_bash |
b |
Shell commands (bash/monitor) | Local process |
remote_agent |
r |
Remote/cloud agents (CCR sessions) | Remote WebSocket |
in_process_teammate |
t |
Team-mode agents (swarms) | Local async in-process |
local_workflow |
w |
Workflow scripts (feature-gated) | Local |
dream |
d |
Auto-memory consolidation agent | Local forked async |
monitor_mcp |
m |
MCP monitoring (feature-gated) | Local process |
TaskStatus: pending → running → {completed | failed | killed}
{
id: string // Prefixed unique ID (e.g., "a7x9q2m1")
type: TaskType
status: TaskStatus
description: string
toolUseId?: string
startTime: number
endTime?: number
totalPausedMs?: number
outputFile: string // /tmp/.../tasks/{taskId}.output
outputOffset: number
notified: boolean // Prevents duplicate notifications
}generateTaskId(type): string
// prefix + 8 random chars from [0-9a-z]
// 36^8 ≈ 2.8 trillion combinations → resist brute-force symlink attacks
// Example IDs: a7x9q2m1, b3k8p5n2, r9x2m8p4<task-notification>
<task-id>a7x9q2m1</task-id>
<tool-use-id>...</tool-use-id>
<output-file>/path/to/output</output-file>
<status>completed | failed | killed</status>
<summary>Human-readable message</summary>
<result>Optional: agent's final response text</result>
<usage>
<total_tokens>1234</total_tokens>
<tool_uses>12</tool_uses>
<duration_ms>45000</duration_ms>
</usage>
<worktree>
<path>/path/to/worktree</path>
<branch>branch-name</branch>
</worktree>
</task-notification>- TeamCreateTool / TeamDeleteTool — spawn/manage teams of agents
- Leader-teammate architecture with mailbox-pattern IPC
TeammateIdentity:{ agentId, teamName, agentName, color }- Each teammate cycles permission modes independently (Shift+Tab)
TEAMMATE_MESSAGES_UI_CAP = 50: Limits in-memory message copies per teammate- Prevents 36.8GB+ memory usage in swarm bursts (observed with 292 agents)
- Full history stored on disk, UI shows recent only
RemoteSessionManager
├─ connect() → wss://api.anthropic.com/v1/sessions/ws/{sessionId}/subscribe
├─ sendMessage(content) → HTTP POST message to CCR
├─ respondToPermissionRequest(requestId, result)
├─ cancelSession() → Send interrupt signal
└─ reconnect()
SessionsWebSocket
├─ RECONNECT_DELAY_MS = 2000
├─ MAX_RECONNECT_ATTEMPTS = 5
├─ PERMANENT_CLOSE_CODES = {4003} (unauthorized)
└─ Ping every 30s to keep aliveclaude-code --worktree # Auto-generate worktree name
claude-code --worktree my-feature # Named worktree
claude-code --worktree '#123' # PR reference
claude-code --worktree --tmux # Open in tmux terminal- Each agent can make independent commits in isolated branches
- Original main branch untouched
- Always enabled (
isWorktreeModeEnabled() → true)
- Workers are async — launch concurrently
- Never delegate understanding — include specific file paths, line numbers
- Match context: Continue worker if it explored the right files; spawn fresh if broad research
- Verify independently: Verifier should see code with fresh eyes
- Be skeptical — if something looks off, dig in
ALL_AGENT_DISALLOWED_TOOLS (blocked for subagents):
- TaskOutputTool, ExitPlanModeV2Tool, EnterPlanModeTool
- AgentTool (unless USER_TYPE=ant for nested agents)
- AskUserQuestionTool, TaskStopTool, WorkflowTool
ASYNC_AGENT_ALLOWED_TOOLS:
- File operations (Read, Write, Edit), Web tools (Search, Fetch)
- Search tools (Grep, Glob), Shells (Bash, PowerShell)
- Notebooks, Skills, TodoWrite
COORDINATOR_MODE_ALLOWED_TOOLS:
- AgentTool, TaskStopTool, SendMessageTool, SyntheticOutputTool
Location: bridge/ (33 files, 400KB+)
Bidirectional WebSocket bridge between claude.ai web UI and local CLI instances.
-
Registration: Bridge registers as "environment" with Anthropic backend
- Generates unique
bridgeId,environmentId(UUIDs) - Sends: machine name, branch, git repo, max sessions, spawn mode
- Receives:
environment_secretfor ongoing auth
- Generates unique
-
Work Polling Loop:
- Polls
/environments/{id}/workendpoint - Receives
WorkResponsewith session assignment - Decodes base64url JSON
WorkSecretwith:session_ingress_token(WebSocket auth)api_base_url(session server endpoint)- Git sources (repo + token)
- Auth credentials (Anthropic API keys)
claude_code_args(CLI overrides:--model,--memory, etc.)mcp_config(MCP servers for this session)- Environment variables
- CCR v2 selector flag
- Polls
-
Session Spawning:
- single-session mode: One session in cwd, tears down when done
- worktree mode: Git worktree per session (persistent server, isolated branches)
- same-dir mode: All sessions in same cwd (can stomp each other)
-
Bidirectional Messaging:
- Sessions send: inbound messages, tool execution, status updates
- Relay sends: outbound messages, permission responses, model/config changes
- Real-time activity tracking at 1Hz
- Connection backoff: 2s → 120s → give up at 10m
- General backoff: 500ms → 30s → give up at 10m
- Sleep detection: if poll exceeds 2× backoff cap, error budget resets
- Token refresh: hourly JWT refresh with 5-minute pre-expiry threshold
- Max concurrent sessions: 32 (gated by GrowthBook
tengu_ccr_bridge_multi_session) - Per-session timeout: 24 hours
| File | Purpose |
|---|---|
bridgeMain.ts (100KB+) |
Main event loop for standalone bridge mode |
replBridge.ts (100KB+) |
REPL-integrated bridge (auto-start via useReplBridge) |
remoteBridgeCore.ts (40KB) |
Core WebSocket state machine |
initReplBridge.ts |
Bootstrap wrapper |
bridgeApi.ts |
HTTP client for environment/work registration |
sessionRunner.ts |
Spawns child sessions with isolation |
createSession.ts |
Session lifecycle |
jwtUtils.ts |
JWT token refresh scheduling |
trustedDevice.ts |
Trusted device token management |
workSecret.ts |
Decoding/registering work secrets |
- AgentTool — Spawn subagents for parallel/specialized tasks
- BashTool — Execute shell commands
- FileReadTool — Read file contents with token budgeting
- FileEditTool — Edit file content with diffs
- FileWriteTool — Write new files
- WebFetchTool — Fetch and process content from URLs (deferred)
- WebSearchTool — Search the web
- GlobTool — File pattern matching
- GrepTool — Regex-based file content search
- NotebookEditTool — Edit Jupyter notebooks
- TaskOutputTool — Generate tool output
- ExitPlanModeV2Tool — Exit plan mode
- EnterPlanModeTool — Enter planning mode
- BriefTool — Generate brief responses
- TodoWriteTool — Write/manage TODO items
- SkillTool — Invoke skills and custom commands
- AskUserQuestionTool — Ask user for input/confirmation
- TaskStopTool — Stop executing tasks
- ToolSearchTool — Search for available tools (deferred load)
- ListMcpResourcesTool — List MCP server resources
- ReadMcpResourceTool — Read MCP resource content
- MCPTool — Execute MCP tools (wrapper)
- McpAuthTool — Handle MCP authentication
- SendMessageTool — Send messages between agents
| Tool | Feature Gate |
|---|---|
| LSPTool | ENABLE_LSP_TOOL env var |
| SleepTool | PROACTIVE or KAIROS |
| CronCreateTool | AGENT_TRIGGERS |
| CronDeleteTool | AGENT_TRIGGERS |
| CronListTool | AGENT_TRIGGERS |
| RemoteTriggerTool | AGENT_TRIGGERS_REMOTE |
| MonitorTool | MONITOR_TOOL |
| WebBrowserTool | WEB_BROWSER_TOOL |
| TerminalCaptureTool | TERMINAL_PANEL |
| CtxInspectTool | CONTEXT_COLLAPSE |
| SnipTool | HISTORY_SNIP |
| WorkflowTool | WORKFLOW_SCRIPTS |
| TeamCreateTool | AGENT_SWARMS |
| TeamDeleteTool | AGENT_SWARMS |
| ListPeersTool | UDS_INBOX |
| PushNotificationTool | KAIROS or KAIROS_PUSH_NOTIFICATION |
| SubscribePRTool | KAIROS_GITHUB_WEBHOOKS |
| SendUserFileTool | KAIROS |
| SuggestBackgroundPRTool | ANT user type |
| OverflowTestTool | OVERFLOW_TEST_TOOL |
| VerifyPlanExecutionTool | CLAUDE_CODE_VERIFY_PLAN env var |
| EnterWorktreeTool | worktree mode enabled |
| ExitWorktreeTool | worktree mode enabled |
| Tool | Purpose |
|---|---|
| ConfigTool | Configuration management |
| TungstenTool | Virtual terminal wrapper |
| REPLTool | JavaScript REPL environment |
| Tool | Condition |
|---|---|
| TestingPermissionTool | NODE_ENV=test |
| PowerShellTool | Windows, when enabled |
Permission Modes:
default— User prompts for dangerous operationsbypass— Automatic approval (dangerous)auto— Machine-based classifier with fallback to prompting
Tool Deferred Loading:
- Tools marked with
shouldDefer: trueare sent withdefer_loading: true - Require ToolSearchTool to be called first
- Built-in tools take precedence over MCP tools in name conflicts
Location: upstreamproxy/ — HTTPS MITM proxy for CCR container environments.
- Reads
CLAUDE_CODE_REMOTEandCCR_UPSTREAM_PROXY_ENABLEDenv vars - Reads session token from
/run/ccr/session_token, immediately unlinks it - Calls
prctl(PR_SET_DUMPABLE, 0)via Bun FFI to block same-UID ptrace - Downloads proxy CA cert from
{base_url}/v1/code/upstreamproxy/ca-cert - Launches local CONNECT→WebSocket relay on localhost TCP
- Exposes
HTTPS_PROXY,SSL_CERT_FILE,NO_PROXYenv vars
- Loopback, RFC1918, IMDS range
*.anthropic.com(prevents MITM of Anthropic API calls)- github.com, npm registry, PyPI, crates.io, golang proxy
- Transport: TCP CONNECT → WebSocket upgrade over HTTPS
- Why WebSocket? CCR ingress is GKE L7 with path-prefix routing (no raw CONNECT support)
- Message Encoding: UpstreamProxyChunk protobuf (hand-encoded, no runtime dep)
- Chunk Size: Max 512KB per chunk
- Keep-alive: Ping every 30s (sidecar timeout is 50s)
- Fails open: Any error logs warning and disables proxy (never breaks working session)
Location: native-ts/ — Pure TypeScript ports of native NAPI modules.
| Module | Upstream | Purpose |
|---|---|---|
color-diff/ |
Rust (syntect + bat + similar) | Syntax-highlighted diff rendering via highlight.js |
file-index/ |
Rust (nucleo/helix fuzzy matcher) | Fuzzy file search with fzf-v2/nucleo scoring |
yoga-layout/ |
C++ (Meta Yoga) | Flexbox layout for terminal UI (single-pass TS subset) |
- highlight.js for syntax highlighting +
diffnpm for word diffing - Output: Colored ANSI escape sequences, line numbers, word-level markers
- Scoring: position-in-results / result-count (0.0 = perfect, 1.05 test penalty)
- Constants: Match=16, boundary/first-char bonus=8, camel/consecutive=6/4
- Async variant yields to event loop every ~8-12k paths (270k-path indexes don't block >10ms)
- Flex-direction, flex-grow/shrink/basis, align-items/self, justify-content
- Margin/padding/border/gap, width/height/min/max, position relative/absolute
- flex-wrap, align-content, display: contents, baseline alignment
- Not implemented: aspect-ratio, content-box, RTL direction
Why Native-TS Matters:
- Eliminates native compilation in bundled builds
- Reduces distribution size (no .node binaries)
- Improves startup speed (no NAPI FFI cost)
- Maintains API compatibility with original modules
Location: memdir/ (8 files) — Multi-scoped persistent memory.
| Type | Scope | Description |
|---|---|---|
user |
Always private | User's role, goals, preferences |
feedback |
Private or team | Guidance on how to approach work |
project |
Private or team | Ongoing work, goals, deadlines |
reference |
Usually team | Pointers to external systems |
- Memories stored in
~/.claude/projects/{slug}/memory/ - YAML frontmatter markdown files
- MEMORY.md index (max 200 lines / 25KB, truncated with warning)
- Loaded into context at system prompt time
~/.claude/projects/{slug}/memory/
MEMORY.md # consolidated index
memory-log/
2026-03-31.log # append-only daily entries
topic-files/
architecture.md # distilled from logs
user.md
feedback.md
- GrowthBook:
tengu_passport_quail(main),tengu_slate_thimble(non-interactive) - Disabled in CCR containers,
--baremode, SIMPLE mode CLAUDE_CODE_DISABLE_AUTO_MEMORYenv var
teamMemPaths.ts— Team scope paths (gated byTEAMMEMfeature)teamMemPrompts.ts— Team scope prompt text- Shared via git for team collaboration
| Command | Description | Aliases |
|---|---|---|
/add-dir |
Add a new working directory | |
/agents |
Manage agent configurations | |
/branch |
Create conversation branch | |
/btw |
Quick side question | |
/chrome |
Claude in Chrome settings | |
/clear |
Clear conversation history | reset, new |
/color |
Set prompt bar color | |
/compact |
Shrink context usage | |
/config |
Open config panel | settings |
/copy |
Copy last message | |
/cost |
Show total cost/duration | |
/desktop |
Continue in Claude Desktop | app |
/diff |
View uncommitted changes | |
/doctor |
Diagnose installation | |
/effort |
Set effort level | |
/exit |
Exit the REPL | quit |
/export |
Export conversation | |
/extra-usage |
Configure extra usage | |
/fast |
Fast mode (hidden) | |
/feedback |
Submit feedback | bug |
/files |
List files in context (ant-only) | |
/help |
Show help | |
/hooks |
View hook configurations | |
/ide |
Manage IDE integrations | |
/insights |
Generate session analysis | |
/install-github-app |
Set up GitHub Actions | |
/install-slack-app |
Install Slack app | |
/keybindings |
Manage keybindings | |
/login |
Sign in | |
/logout |
Sign out | |
/mcp |
Manage MCP servers | |
/memory |
Edit memory files | |
/mobile |
Show mobile QR code | ios, android |
/model |
Change model | |
/output-style |
Change output style | |
/passes |
View available passes | |
/permissions |
Manage tool permissions | allowed-tools |
/plan |
Enable plan mode | |
/plugin |
Manage plugins | |
/pr-comments |
Get GitHub PR comments | |
/privacy-settings |
Privacy settings | |
/rate-limit-options |
Rate limit options | |
/release-notes |
View release notes | |
/reload-plugins |
Activate pending plugins | |
/remote-env |
Configure remote env | |
/rename |
Rename conversation | |
/resume |
Resume previous conversation | continue |
/review |
Review a pull request | |
/rewind |
Restore to previous point | checkpoint |
/sandbox |
Toggle sandbox (hidden) | |
/session |
Remote-control sessions | remote |
/skills |
List available skills | |
/stats |
Show usage statistics | |
/status |
Show session status | |
/stickers |
Order Claude Code stickers | |
/tag |
Toggle session tag | |
/tasks |
Manage background tasks | bashes |
/theme |
Change theme | |
/thinkback |
2025 Year in Review | |
/thinkback-play |
Play thinkback animation | |
/ultrareview |
Find/verify bugs (10-20 min) | |
/upgrade |
Upgrade to Max | |
/usage |
Show plan usage limits | |
/vim |
Toggle Vim mode | |
/voice |
Toggle voice mode |
Only available when USER_TYPE=ant:
| Command | Purpose |
|---|---|
/autofixpr |
Autofix PRs |
/backfill-sessions |
Backfill sessions |
/break-cache |
Break cache (testing) |
/commit |
Create git commit |
/commit-push-pr |
Commit, push, and open PR |
/context |
Visualize context usage as grid |
/debug-tool-call |
Debug tool calls |
/env |
Environment variables |
/heapdump |
Dump JS heap |
/init-verifiers |
Initialize verifiers |
/mock-limits |
Mock rate limits |
/oauth-refresh |
Refresh OAuth tokens |
/reset-limits |
Reset rate limits |
/share |
Share conversation |
/summary |
Summarize conversation |
/teleport |
Move session |
/ant-trace |
ANT tracing |
/version |
Version info |
/bridge-kick |
Inject bridge failure states |
/agents-platform |
Agents platform |
| Command | Status |
|---|---|
/good-claude |
Disabled |
/issue |
Disabled |
/ctx-viz |
Disabled |
/perf-issue |
Disabled |
/bughunter |
Disabled |
| Command | Feature Gate |
|---|---|
/brief |
KAIROS or KAIROS_BRIEF |
/assistant |
KAIROS |
/subscribe-pr |
KAIROS_GITHUB_WEBHOOKS |
/proactive |
PROACTIVE or KAIROS |
/ultraplan |
ULTRAPLAN |
/torch |
TORCH |
/buddy |
BUDDY |
/fork |
FORK_SUBAGENT |
/peers |
UDS_INBOX |
/workflows |
WORKFLOW_SCRIPTS |
/web-setup |
CCR_REMOTE_SETUP |
/voice |
VOICE_MODE |
/bridge / /rc |
BRIDGE_MODE |
/force-snip |
HISTORY_SNIP |
Hidden Commands
Commands with isHidden: true that don't appear in /help:
/advisor,/bridge,/context,/cost,/desktop,/extra-usage,/fast,/sandbox
Global Context:
| Shortcut | Action |
|---|---|
ctrl+c |
Interrupt (double-press handling) |
ctrl+d |
Exit (double-press handling) |
ctrl+l |
Redraw |
ctrl+t |
Toggle todos |
ctrl+o |
Toggle transcript |
ctrl+shift+b |
Toggle brief (KAIROS) |
ctrl+shift+o |
Toggle teammate preview |
ctrl+r |
History search |
ctrl+shift+f / cmd+shift+f |
Global search (QUICK_SEARCH) |
ctrl+shift+p / cmd+shift+p |
Quick open (QUICK_SEARCH) |
meta+j |
Toggle terminal (TERMINAL_PANEL) |
Chat Context:
| Shortcut | Action |
|---|---|
escape |
Cancel |
ctrl+x ctrl+k |
Kill agents |
shift+tab / meta+m |
Cycle mode |
meta+p |
Model picker |
meta+o |
Fast mode |
meta+t |
Thinking toggle |
enter |
Submit |
up/down |
History navigation |
ctrl+_ / ctrl+shift+- |
Undo |
ctrl+x ctrl+e / ctrl+g |
External editor |
ctrl+s |
Stash |
shift+up |
Message actions (MESSAGE_ACTIONS) |
space |
Voice push-to-talk (VOICE_MODE) |
Vim Mode: INSERT ↔ NORMAL with escape / i/a/o
17 total keybinding contexts including: autocomplete, settings, confirmation, transcript, diff dialog, select, message selector (rewind), footer, scroll, plugin dialog
- REPL.tsx (5,005 lines) — Main conversation loop/prompt input
- Doctor.tsx (574 lines) — Diagnostic/verification screen
- ResumeConversation.tsx (398 lines) — Resume previous conversations
- Full conversation rendering with streaming
- Tool result visualization
- Background task management
- Companion sprite rendering (Buddy)
- Voice input integration
- Virtual scrolling (300 max items)
- Bridge sync with claude.ai
- Coordinator mode task panels
| Skill | Purpose |
|---|---|
/update-config |
Update configuration |
/keybindings |
Manage keybindings |
/verify |
Verify tool |
/debug |
Debug skill |
/loremIpsum |
Lorem ipsum generator |
/skillify |
Convert commands to skills |
/remember |
Remember/memory skill |
/simplify |
Code simplification |
/batch |
Batch operations |
/stuck |
Help when stuck |
| Skill | Feature Gate |
|---|---|
/dream |
KAIROS or KAIROS_DREAM |
/hunter |
REVIEW_ARTIFACT |
/loop |
AGENT_TRIGGERS |
/scheduleRemoteAgents |
AGENT_TRIGGERS_REMOTE |
/claudeApi |
BUILDING_CLAUDE_APPS |
/claudeInChrome |
auto-enabled if conditions met |
/runSkillGenerator |
RUN_SKILL_GENERATOR |
- Bundled skills — Shipped with CLI
- Plugin skills — From installed plugins
- Built-in plugin skills — From enabled built-in plugins
- Skill directory commands — From
.claude/skills/directories - Dynamic skills — Discovered during file operations
- Workflow commands — From workflow automation
68+ custom React hooks + 16 notification hooks in hooks/.
| Hook | Lines | Purpose |
|---|---|---|
useVimInput.ts |
— | Full vim mode with INSERT/NORMAL state machine |
useTextInput.ts |
— | Base text input with cursor, history, completion |
useTypeahead.tsx |
1,384 | Advanced typeahead with unified suggestions engine |
useSearchInput.ts |
— | Search with kill-ring, yank support |
useVirtualScroll.ts |
1,000+ | Virtual scrolling (300 max items, scroll quantum) |
useArrowKeyHistory.tsx |
— | Arrow key history navigation |
| Hook | Purpose |
|---|---|
useVoice.ts (1,500+ lines) |
Hold-to-talk voice with 88+ languages |
useVoiceIntegration.tsx |
Voice integration with keybindings |
useVoiceEnabled.ts |
Voice enablement detection |
| Hook | Lines | Purpose |
|---|---|---|
useReplBridge.tsx |
722 | Always-on bridge to claude.ai |
useGlobalKeybindings.tsx |
31KB | Global keybinding handlers |
useCanUseTool.tsx |
40KB | Tool permission system |
useHistorySearch.ts |
— | Session history search |
useInboxPoller.ts |
— | Inbox messages from teammates |
useRemoteSession.ts |
23KB | Remote session management |
useTeleportResume.tsx |
— | Session teleport/resume |
useAutoModeUnavailableNotification— Auto mode blockersuseCanSwitchToExistingSubscription— Plan upgrade hintsuseDeprecationWarningNotification— Model deprecation noticesuseFastModeNotification— Fast mode statususeIDEStatusIndicator— IDE connection statususeInstallMessages— Plugin/dependency feedbackuseLspInitializationNotification— LSP server statususeMcpConnectivityStatus— MCP server healthuseModelMigrationNotifications— Model upgrade suggestionsuseNpmDeprecationNotification— Npm package warningsusePluginAutoupdateNotification— Plugin update statususePluginInstallationStatus— Plugin install progressuseRateLimitWarningNotification— Rate limit warningsuseSettingsErrors— Settings validationuseStartupNotification— Startup progressuseTeammateShutdownNotification— Swarm shutdown events
35+ major service modules in services/.
| Service | Purpose |
|---|---|
analytics/ |
OpenTelemetry + Datadog + GrowthBook |
api/ |
API requests, retries, error handling, prompt caching |
compact/ |
Auto-compaction, microcompaction, reactive compaction, history snipping |
tools/ |
Tool orchestration, streaming execution, tool hooks |
mcp/ |
MCP server connections, permissions, resources, registry |
oauth/ |
OAuth 2.0 with PKCE, profile fetching, subscription detection |
plugins/ |
Plugin loading and management |
skills/ |
Built-in skill management and discovery |
lsp/ |
Language Server Protocol integration |
| Service | Purpose |
|---|---|
remoteManagedSettings/ |
Remote configuration sync with cache |
policyLimits/ |
Policy enforcement and limits |
extractMemories/ |
Memory extraction capabilities |
MagicDocs/ |
Automatic documentation generation |
SessionMemory/ |
Session-scoped memory management |
voice.ts |
Voice audio recording (526 lines) |
voiceStreamSTT.ts |
Speech-to-text WebSocket (545 lines) |
voiceKeyterms.ts |
Domain vocabulary hints (107 lines) |
autoDream.ts |
Autonomous dreaming/background processing |
AgentSummary/ |
Agent execution summarization |
tokenEstimation.ts |
Token counting and estimation |
diagnosticTracking.ts |
IDE diagnostic tracking |
toolUseSummary/ |
Tool usage summarization |
Located in state/AppStateStore.ts:
- Session configuration (settings, verbose mode, model selection)
- UI state (expanded views, footer selection, teammate preview)
- Tool permissions and bypass mode
- Remote connection status (CCR/bridge mode)
- Speculation state for pipelined responses
- File history and attribution state
- Task and agent management
- Companion state (reaction, pet timestamp)
Global singleton tracking:
- Cost tracking (total USD, API/tool duration, lines added/removed)
- Token usage by model with cache read/creation tokens
- Session metadata (ID, parent session, user type)
- Permission modes (autoMode, bypassPermissions, defaultMode)
- Model configuration and overrides
- Telemetry counters (OpenTelemetry metrics)
- Hook registration state
- Agent color mapping
- Last API request metadata for bug reports
- Cached system prompt sections
- Prompt cache eligibility (1h TTL allowlist)
- Post-compaction tracking
- Teleported session tracking
- Queries current branch, main branch, file status, recent commits
- Memoized for session duration (refreshed on cache-breaking)
- Truncated at 2,000 characters
- Disabled in CCR or when git instructions disabled
- Claude.md files — Project-specific documentation auto-discovery
- Memory files injection (filtered for security)
- Current date injection
- Controlled by:
CLAUDE_CODE_DISABLE_CLAUDE_MDS, bare mode
- Prepended to each conversation turn
- Cached for duration of session
- Observable performance metrics with diagnostic logging
- Coordinates entire message-to-response flow
- Manages tool execution context
- Handles model selection and fallbacks
- Tracks file state and write cache
- Manages permission contexts
- Supports thinking mode with depth config
- Handles structured outputs via JSON schema
- Task budget tracking
queryLoop():
1. Initialize state (messages, toolUseContext, autoCompactTracking)
2. Build query config (immutable, env/feature-flag driven)
3. For each turn:
a. Prefetch memories/skills if enabled
b. Call API with current messages
c. Handle API response:
- Tool use? → Execute tools, add results
- Error? → Recovery (reactive compact, max_output_tokens retry)
- Complete? → Post-sampling hooks, stop hooks
- Continue? → Token budget check, diminishing returns
d. Update state
e. Return/yield events to caller
4. Cleanup (command lifecycle, session storage)
- Auto-compaction: When context approaches limits
- Reactive compaction: Triggered by token limits
- Microcompaction: Cached config
- History snipping: Aggressive history compression
- Token budget:
TOKEN_BUDGETfeature enables budget tracking and auto-continuation - Max output recovery: Automatic recovery from overrun (up to 3 attempts)
- Thinking preservation: Rules to maintain thinking blocks through tool use
- Tool use summary: Automatic summarization of tool output to save context
- Context collapse: Remove duplicate context sections
| Model ID | Alias | Notes |
|---|---|---|
claude-opus-4-20250514 |
— | Opus 4.0 (legacy, remapped) |
claude-opus-4-1-20250805 |
— | Opus 4.1 (legacy, remapped) |
claude-opus-4-5-20251101 |
— | Opus 4.5 |
claude-opus-4-6 |
opus |
Current default (no date suffix) |
claude-opus-4-6[1m] |
opus[1m] |
1M context variant |
| Model ID | Alias | Notes |
|---|---|---|
claude-3-5-sonnet-20241022 |
— | Sonnet 3.5 v2 |
claude-3-7-sonnet-20250219 |
— | Sonnet 3.7 (deprecated) |
claude-sonnet-4-20250514 |
— | Sonnet 4.0 |
claude-sonnet-4-5-20250929 |
— | Sonnet 4.5 |
claude-sonnet-4-6 |
sonnet |
Current default (no date suffix) |
claude-sonnet-4-6[1m] |
sonnet[1m] |
1M context variant |
| Model ID | Alias | Notes |
|---|---|---|
claude-3-5-haiku-20241022 |
— | Haiku 3.5 (deprecated 1P) |
claude-haiku-4-5-20251001 |
haiku |
Current default |
| Alias | Resolves To |
|---|---|
best |
Current best Opus model |
opusplan |
Opus in plan mode, Sonnet elsewhere |
fennec-latest |
Legacy codename for Opus (migrated) |
fennec-fast-latest |
Legacy → opus[1m] + fast mode |
Bedrock (AWS):
- Sonnet 4.6:
us.anthropic.claude-sonnet-4-6 - Opus 4.6:
us.anthropic.claude-opus-4-6-v1 - Regional prefixes:
us,eu,apac,global
Vertex AI (Google Cloud):
- Sonnet 4.6:
claude-sonnet-4-6 - Opus 4.6:
claude-opus-4-6 - Older models use
@datesuffix:claude-opus-4@20250514
Foundry:
- Simple format:
claude-opus-4-6,claude-sonnet-4-6
| Tier | Input/Mtok | Output/Mtok | Models |
|---|---|---|---|
| Haiku 3.5 | $0.80 | $4.00 | claude-3-5-haiku |
| Haiku 4.5 | $1.00 | $5.00 | claude-haiku-4-5 |
| Sonnet | $3.00 | $15.00 | All Sonnet models |
| Opus 4.5/4.6 | $5.00 | $25.00 | Opus 4.5, 4.6 (base) |
| Opus 4.0/4.1 | $15.00 | $75.00 | Opus 4, 4.1 (legacy) |
| Opus 4.6 fast | $30.00 | $150.00 | 6x multiplier |
| User Tier | Default Model |
|---|---|
| Ant (internal) | Dynamic via GrowthBook, fallback opus[1m] |
| Max | Opus 4.6 (or opus[1m] if eligible) |
| Team Premium | Opus 4.6 |
| Pro / Team Standard / Enterprise / PAYG | Sonnet 4.6 |
| Bedrock / Vertex / Foundry (3P) | May use Sonnet 4.5 |
Models supporting [1m] suffix:
claude-opus-4-6[1m]claude-sonnet-4-6[1m]claude-sonnet-4-5-20250929[1m]claude-sonnet-4-20250514[1m]
Can be disabled via CLAUDE_CODE_DISABLE_1M_CONTEXT (HIPAA compliance).
| Model | Retirement Date |
|---|---|
claude-3-opus |
Jan 5-15, 2026 (varies by provider) |
claude-3-7-sonnet |
Feb 19 - May 11, 2026 (varies) |
claude-3-5-haiku |
Feb 19, 2026 (firstParty only) |
- "Fennec" — Internal codename for Opus before public launch
- "Capybara" — Referenced throughout codebase, likely internal test model, masked in UI as
cap***** - Ant-only models fetched dynamically from GrowthBook
tengu_ant_model_override
- Default context: 200,000 tokens
- Max output tokens: Default 32,000, Upper limit 64,000
- Capabilities cached at
~/.claude/cache/model-capabilities.json
| Variable | Purpose |
|---|---|
ANTHROPIC_MODEL |
Runtime model override |
ANTHROPIC_DEFAULT_OPUS_MODEL |
Custom Opus model (3P) |
ANTHROPIC_DEFAULT_SONNET_MODEL |
Custom Sonnet model (3P) |
ANTHROPIC_DEFAULT_HAIKU_MODEL |
Custom Haiku model (3P) |
ANTHROPIC_CUSTOM_MODEL_OPTION |
Custom model for /model picker |
Setting availableModels in settings controls which models users can select:
- Supports family aliases ("opus", "sonnet", "haiku") — wildcard for entire family
- Supports version prefixes ("opus-4-5")
- Supports full model IDs with exact match
| Flag | Description |
|---|---|
KAIROS |
AI agent/assistant mode |
KAIROS_BRIEF |
Brief-only mode |
KAIROS_CHANNELS |
Channel support |
KAIROS_DREAM |
Background autonomous operation |
KAIROS_GITHUB_WEBHOOKS |
GitHub webhook integration |
KAIROS_PUSH_NOTIFICATION |
Push notifications |
ULTRATHINK |
Maximum reasoning mode |
ULTRAPLAN |
Extended planning |
TORCH |
Torch reasoning enhancement |
PROACTIVE |
Proactive thinking |
TOKEN_BUDGET |
Token budget tracking and auto-continue |
VERIFICATION_AGENT |
Independent verification subprocess |
EXPERIMENTAL_SKILL_SEARCH |
Experimental skill discovery |
| Flag | Description |
|---|---|
COORDINATOR_MODE |
Multi-agent coordinator mode |
AGENT_SWARMS |
Multi-agent swarm support |
AGENT_TRIGGERS |
Scheduled/triggered agents |
AGENT_TRIGGERS_REMOTE |
Remote agent triggers |
FORK_SUBAGENT |
Background forked execution |
BG_SESSIONS |
Background session management |
UDS_INBOX |
Unix domain socket inbox (peer messaging) |
TEMPLATES |
Template-based task creation |
| Flag | Description |
|---|---|
REACTIVE_COMPACT |
Context compaction on token limits |
HISTORY_SNIP |
History snipping for context reduction |
CONTEXT_COLLAPSE |
Duplicate context collapse |
CACHED_MICROCOMPACT |
Cached microcompaction config |
| Flag | Description |
|---|---|
VOICE_MODE |
Voice input/output |
BRIDGE_MODE |
claude.ai bridge connection |
WEB_BROWSER_TOOL |
Web browsing capability |
CHICAGO_MCP |
Computer use capabilities |
TERMINAL_PANEL |
Terminal panel UI |
QUICK_SEARCH |
Quick search/open |
MESSAGE_ACTIONS |
Message action UI |
BUDDY |
ASCII pet companion |
| Flag | Description |
|---|---|
CCR_REMOTE_SETUP |
Claude Code Remote setup |
NATIVE_CLIENT_ATTESTATION |
Client attestation |
PERFETTO_TRACING |
Performance tracing |
SLOW_OPERATION_LOGGING |
Slow operation diagnostics |
FAST_MODE |
Speed vs quality tradeoff |
HARD_FAIL |
Hard failure mode for testing |
ENHANCED_TELEMETRY_BETA |
Extended telemetry |
PROMPT_CACHE_BREAK_DETECTION |
Cache invalidation detection |
WORKFLOW_SCRIPTS |
Workflow automation |
MCP_SKILLS |
MCP server skills |
DAEMON |
Daemon process support |
REVIEW_ARTIFACT |
Artifact review tools |
BUILDING_CLAUDE_APPS |
Claude API skills |
RUN_SKILL_GENERATOR |
Skill generation |
ABLATION_BASELINE |
Experimental ablation testing |
OVERFLOW_TEST_TOOL |
Overflow test tool |
TRANSCRIPT_CLASSIFIER |
AFK mode detection |
| Header | Feature |
|---|---|
claude-code-20250219 |
Claude Code beta |
interleaved-thinking-2025-05-14 |
Interleaved thinking |
context-1m-2025-08-07 |
1M context window |
context-management-2025-06-27 |
Advanced context management |
web-search-2025-03-05 |
Web search integration |
advanced-tool-use-2025-11-20 |
Advanced tool use (1P) |
tool-search-tool-2025-10-19 |
Tool search (3P) |
effort-2025-11-24 |
Effort levels |
task-budgets-2026-03-13 |
Task budgeting |
fast-mode-2026-02-01 |
Fast mode (speed vs quality) |
redact-thinking-2026-02-12 |
Thinking redaction |
afk-mode-2026-01-31 |
Away/AFK mode |
advisor-tool-2026-03-01 |
Advisor tool integration |
Provider-specific handling for Bedrock and Vertex.
- OAuth 2.0 with PKCE — Code verifier, challenge, state management
- Dual flow support: Automatic (browser redirect to localhost) and manual (copy-paste)
- Subscription type detection — Fetches profile info with subscription and rate limit tier
- Token management: Access/refresh tokens, expiration tracking
- Account info: UUID, email, organization association
- Session token exchange
| Mode | Behavior |
|---|---|
default |
User prompted for dangerous operations |
bypass |
Automatic approval (dangerous, sandbox-only) |
auto |
Machine-based classifier with fallback to prompting |
Comprehensive cost tracking:
- Total USD cost calculation
- Per-model usage breakdown
- Input/output token accounting
- Cache read/creation tokens
- Web search request counting
- API duration tracking (with and without retries)
- Tool execution duration
- Code changes (lines added/removed)
Features:
- Session cost persistence to
.claude/config.json - Cost state restoration on session resume
- Last session ID matching (prevents cost mixing)
- Advisor model cost tracking (recursive)
- OpenTelemetry metrics emission
- Format:
$XX.XXfor costs >$0.50, otherwise 4 decimal places
Output Format:
Total cost: $X.XX
Total duration (API): X.XXs
Total duration (wall): X.XXs
Total code changes: X lines added, Y lines removed
Usage by model:
claude-opus: Z input, W output, V cache read, U cache write ($0.XX)
OpenTelemetry Integration:
firstPartyEventLogger.ts— Event logging with batch processingfirstPartyEventLoggingExporter.ts— Custom log exporter- Batch configuration (scheduledDelayMillis, maxExportBatchSize, maxQueueSize)
- Event sampling per event type
GrowthBook Integration:
growthbook.ts— Feature flags with caching- Cached feature flag values (may be stale)
- User attributes propagation
Datadog Integration:
datadog.ts— Metrics and logs export
Killswitch:
sinkKillswitch.ts— Analytics can be disabledconfig.ts— Analytics disabled via env/settings
Event Types:
- Cost/usage events (token, advisor)
- Hook execution tracking
- Plugin load errors
- Skill discovery events
- Permission decisions
- Auth events
- Tool execution tracking
- Diagnostic events (no-PII)
All use tengu_* naming convention:
tengu_amber_quartz_disabled— Voice kill-switchtengu_cobalt_frost— Deepgram Nova 3 STTtengu_passport_quail— Auto-memorytengu_slate_thimble— Non-interactive memorytengu_ccr_bridge_multi_session— Multi-session bridgetengu_ant_model_override— Ant model overridetengu_memdir_loaded— Memory loaded telemetry- And many more...
- Node.js version check (requires 18+)
- Custom session ID handling
- UDS messaging server (Mac/Linux, unless --bare)
- Teammate snapshot capture (if swarms enabled)
- Terminal backup restoration (iTerm2, Terminal.app)
- CWD establishment (setCwd before hooks)
- Hooks configuration snapshot (prevent hidden modifications)
- FileChanged hook watcher initialization
- Worktree creation (if --worktree flag)
- UDS socket export to
$CLAUDE_CODE_MESSAGING_SOCKET - Background jobs (SessionMemory, context collapse)
- Plugin prefetch (unless
CLAUDE_CODE_SYNC_PLUGIN_INSTALL) - Release notes check (interactive sessions)
- Permission bypass validation (Docker/sandbox checks)
- Previous session cost logging (
tengu_exitevent)
- Profiling checkpoints (startupProfiler)
- MDM raw read (managed settings) — parallel
- Keychain prefetch (OAuth + API key) — parallel
- Feature flag initialization (GrowthBook)
- Command initialization (
getCommands) - Plugin loading (bundled + user plugins)
- Skill registration (bundled skills)
- MCP servers (official registry, enterprise config)
- Policy limits (wait for loading)
- Remote managed settings
- Permission setup (dialog flow)
- Model configuration (selection, deprecation warnings)
- REPL launch (
replLauncher)
launchResumeChooser— Resume previous sessionlaunchAssistantSessionChooser— Assistant mode sessionlaunchAssistantInstallWizard— Assistant setuplaunchSnapshotUpdateDialog— Team memory updateslaunchTeleportResumeWrapper— Teleported session resumelaunchTeleportRepoMismatchDialog— Teleport conflictlaunchInvalidSettingsDialog— Settings validation
Location: moreright/useMoreRight.tsx — Stubbed for external builds.
A React hook that intercepts and enhances the REPL message flow:
onBeforeQuery(input, allMessages, n)— Intercepts before query; can returnfalseto blockonTurnComplete(allMessages, aborted)— Called after each turn completesrender()— Renders custom UI (returns null in stub)
Takes setMessages, inputValue, setInputValue, setToolJSX as parameters.
Comment: "Stub for external builds — the real hook is internal only"
Location: migrations/ — 11 idempotent, one-shot migration functions.
| Migration | What It Does |
|---|---|
migrateAutoUpdatesToSettings |
globalConfig.autoUpdates=false → settings.json DISABLE_AUTOUPDATER |
migrateBypassPermissionsAcceptedToSettings |
globalConfig.bypassPermissionsModeAccepted → settings.json |
migrateEnableAllProjectMcpServersToSettings |
Project MCP approval → local settings |
migrateFennecToOpus |
fennec-latest → opus, fennec-fast-latest → opus + fast mode |
migrateLegacyOpusToCurrent |
opus-4.0/4.1 → opus alias |
migrateOpusToOpus1m |
opus → opus[1m] for Max/Team Premium |
migrateSonnet1mToSonnet45 |
sonnet[1m] → sonnet-4-5-20250929[1m] (pinning) |
migrateSonnet45ToSonnet46 |
Sonnet 4.5 → sonnet (now 4.6) |
migrateReplBridgeEnabledToRemoteControlAtStartup |
Rename config key |
resetAutoModeOptInForDefaultOffer |
Clear skipAutoPermissionPrompt |
resetProToOpusDefault |
Reset Pro users to Opus 4.5 default |
Design Principles:
- Idempotent (safe to run multiple times)
- Fail silent (errors don't break startup)
- Scope-aware (project vs global)
- Telemetry logged
Location: entrypoints/
-
CLI Entry (
cli.tsx) — Main CLI bootstrap with fast-paths:--version/-v/-V— Version output (zero-import fast path)--dump-system-prompt— Render system prompt--claude-in-chrome-mcp— Chrome extension MCP server--chrome-native-host— Chrome native messaging host--computer-use-mcp— Computer use MCP server (CHICAGO_MCP)--daemon-worker=<kind>— Daemon worker supervisor spawn--remote— Remote mode (CCR)
-
MCP Entry (
mcp.ts) — MCP protocol server integration -
SDK Types (
sdk/) — TypeScript SDK definitionscoreTypes.ts,coreSchemas.ts,controlSchemas.ts
Location: vim/ (5 files, ~500 lines)
Modes: INSERT ↔ NORMAL via escape / i/a/o
Motions (vim/motions.ts):
h/l/j/k— arrow movementgj/gk— visual line movementw/b/e/W/B/E— word boundaries0/^/$— line positioningG/gg— document positioning
Operators (vim/operators.ts):
d(delete),c(change),y(yank)- Text objects:
w/W,"/',()/b,[]/B,</> - Find operators:
f/F/t/T - Registers (unnamed register)
- Dot-repeat recording
State Machine (vim/transitions.ts):
- idle → count → operator → operatorCount → operatorFind/operatorTextObj
- find, g, operatorG, replace, indent states
- Count accumulation up to 10,000
Location: ink/ (96 files, 40K+ lines) — Custom fork of Ink terminal UI framework.
| Component | Purpose |
|---|---|
ink.tsx |
Main component renderer |
dom.ts |
DOM tree abstraction for terminal |
layout/engine.ts |
Layout calculation |
layout/yoga.ts |
Yoga binding (native-ts port) |
render-node-to-output.ts |
Node → terminal output |
render-to-screen.ts |
Final screen rendering |
render-border.ts |
Border drawing |
output.ts |
Output buffer management |
colorize.ts |
ANSI color application |
| Feature | File |
|---|---|
| Focus management | focus.ts |
| Text selection | selection.ts |
| Search highlighting | searchHighlight.ts |
| Mouse/click detection | hit-test.ts |
| Keyboard parsing | parse-keypress.ts |
| Terminal capabilities | terminal.ts |
| Bidirectional text | bidi.ts |
| Tab stops | tabstops.ts |
| Hyperlinks | supports-hyperlinks.ts |
| Terminal I/O | termio.ts |
App.tsx,AlternateScreen.tsx,ScrollBox.tsx,Link.tsx,Spacer.tsx,Newline.tsxTerminalSizeContext.tsx,TerminalFocusContext.tsx,ClockContext.tsx
Location: components/ (146 files)
| Component | Purpose |
|---|---|
App.tsx |
Root component wrapper |
FullscreenLayout.tsx |
Full-screen layout container |
BridgeDialog.tsx |
Remote control sync dialog |
ContextVisualization.tsx (76KB) |
Context window visualization |
ConsoleOAuthFlow.tsx (79KB) |
OAuth flow in CLI |
Feedback.tsx (87KB) |
Feedback collection |
Settings.tsx |
Configuration UI |
Status.tsx |
Status display |
Usage.tsx |
Usage/cost display |
ApproveApiKey.tsx,AutoModeOptInDialog.tsx,AutoUpdater.tsxBypassPermissionsModeDialog.tsx,ChannelDowngradeDialog.tsxCostThresholdDialog.tsx,InvalidConfigDialog.tsxClaudeInChromeOnboarding.tsx,IdeAutoConnectDialog.tsxIdleReturnDialog.tsx,HistorySearchDialog.tsxGlobalSearchDialog.tsx,ExportDialog.tsx
FileEditToolDiff.tsx— File edit visualizationShellProgress.tsx— Shell command progressDevBar.tsx— Developer toolbar (ant-only)DiagnosticsDisplay.tsx— Diagnostic informationdesign-system/— Reusable design componentsagents/— Agent-specific UI
Location: outputStyles/loadOutputStylesDir.ts
- Loads markdown files from
.claude/output-styles/and~/.claude/output-styles/ - Frontmatter support: name, description, keep-coding-instructions
- Project styles override user styles
- Caching with cache clearing on plugin updates
Location: plugins/
builtinPlugins.ts— Registry for built-in plugins (user-toggleable)bundled/index.ts— Bundled plugin initialization- Plugins can provide: skills, hooks, MCP servers
- Format:
{name}@builtinfor built-in plugins - User preferences stored in settings (
enabledPluginsmap)
Location: services/mcp/
- Full Model Context Protocol (MCP) server support
- Dynamic tool loading from MCP servers
- OAuth integration for MCP authentication
- WebSocket, SSE, Stdio, and StreamableHTTP transports
- In-process MCP server support
1. Claude-for-Chrome MCP (@ant/claude-for-chrome-mcp):
- Runs in-process to avoid subprocess overhead
- Provides access to user's logged-in Chrome browser
- OAuth and authenticated session support
- Tools:
mcp__claude-in-chrome__* - Skill:
claude-in-chrome(must invoke before tool use)
2. Computer Use MCP (CHICAGO_MCP feature):
- Mouse/keyboard control via
@ant/computer-use-input(Rust/enigo) - Screenshots via
@ant/computer-use-swift(SCContentFilter, NSWorkspace) - System app detection and control
- TCC (privacy) integration
Format: mcp__<serverName>__<toolName> (e.g., mcp__claude-in-chrome__navigate_to)
- Browser automation for user's real Chrome
- OAuth and authenticated site support
- Contrasts with WebBrowser (dev servers, JS eval)
- Rendering pipeline for browser interactions
- Desktop automation and control
- Screenshot capture with privacy filter
- Mouse and keyboard input via Rust/enigo
- Application management and detection
- Clipboard operations (pbpaste/pbcopy)
16 notification hooks providing real-time feedback:
| Hook | Purpose |
|---|---|
useAutoModeUnavailableNotification |
Auto mode blockers |
useCanSwitchToExistingSubscription |
Plan upgrade hints |
useDeprecationWarningNotification |
Model deprecation |
useFastModeNotification |
Fast mode status |
useIDEStatusIndicator |
IDE connection |
useInstallMessages |
Plugin/dependency feedback |
useLspInitializationNotification |
LSP server status |
useMcpConnectivityStatus |
MCP server health |
useModelMigrationNotifications |
Model upgrade suggestions |
useNpmDeprecationNotification |
Npm package warnings |
usePluginAutoupdateNotification |
Plugin updates |
usePluginInstallationStatus |
Plugin install progress |
useRateLimitWarningNotification |
Rate limits |
useSettingsErrors |
Settings validation |
useStartupNotification |
Startup progress |
useTeammateShutdownNotification |
Swarm shutdown |
- Per-tool approval state with detailed analytics
- Blanket deny rules filter tools before model sees them
- MCP server-prefix rules strip entire servers
- Built-in tools take precedence over MCP tools
| Mode | Behavior |
|---|---|
default |
Interactive approval dialogs |
auto |
Intelligent defaults with classifier |
bypass |
Skip all checks (sandbox-only) |
- Each teammate cycles independently (Shift+Tab)
- Coordinator has global permission mode
- MCP tools inherited from parent
- Orphaned permission cleanup for legacy rules
updateTaskState(taskId, setAppState, task => {
if (task.status !== 'running') return task // Guard
return { ...task, status: 'killed', endTime: Date.now() }
})void persistRemoteAgentMetadata(meta).catch(err =>
logForDebugging(`persistence failed: ${err}`)
)export const TEAMMATE_MESSAGES_UI_CAP = 50
// Prevents 36GB+ memory usage with 292 agentsabortController.abort() // Parent: abort entire subtree
currentWorkAbortController.abort() // Child: abort only current turnO_NOFOLLOWprevents symlink attacks in sandboxMAX_TASK_OUTPUT_BYTES = 5GBcap per task- Task IDs use
randomBytes(8)with 36-char alphabet (2.8 trillion combinations)
| Responsibility | Files |
|---|---|
| Main entry | main.tsx, entrypoints/cli.tsx |
| Setup | setup.ts, bootstrap/state.ts |
| Query loop | query.ts, QueryEngine.ts |
| State management | state/AppStateStore.ts, state/AppState.tsx |
| Context | context.ts, context/ |
| Commands | commands.ts, commands/ |
| Tools | Tool.ts, tools.ts, tools/ |
| Tasks | Task.ts, tasks.ts, tasks/ |
| Feature | Files |
|---|---|
| Voice | voice/, services/voice*.ts, hooks/useVoice*.ts |
| Buddy | buddy/ |
| Bridge | bridge/ (33 files) |
| Coordinator | coordinator/coordinatorMode.ts |
| Memory | memdir/ (8 files) |
| Upstream Proxy | upstreamproxy/ |
| Native TS | native-ts/ |
| MCP | services/mcp/ |
| Computer Use | utils/computerUse/ |
| Chrome | utils/claudeInChrome/ |
| Remote | remote/ |
| Vim | vim/ (5 files) |
| Ink | ink/ (96 files) |
| Migrations | migrations/ (11 files) |
| Skills | skills/bundled/ |
| Plugins | plugins/ |
| Analytics | services/analytics/ |
| OAuth | services/oauth/ |
| Cost | cost-tracker.ts, utils/modelCost.ts |
| Models | utils/model/ |
| Category | Count |
|---|---|
| Total source files | ~500+ |
| Feature flags | 89+ |
| Tools (always available) | 24 |
| Tools (feature-gated) | 17+ |
| Public commands | 67+ |
| Ant-only commands | 24+ |
| Feature-gated commands | 14+ |
| Bundled skills | 10 (always) + 7 (gated) |
| React hooks | 68 + 16 notification |
| UI components | 146 files |
| Ink framework files | 96 files, 40K+ lines |
| Keybinding contexts | 17 |
| Default keybindings | 100+ |
| Service modules | 35+ |
| Task types | 7 |
| Model configs | 11 |
| Migrations | 11 |
| Screens | 3 |
| Bridge files | 33 (400KB+) |
| API beta headers | 16+ |
| MCP transports | 4 (WebSocket, SSE, Stdio, StreamableHTTP) |
- Claude Code is a full-featured autonomous agent platform — far beyond a simple CLI chat tool.
- Voice input launching with Deepgram Nova 3 STT, 90+ languages, push-to-talk.
- Buddy companion launching April 1, 2026 — 18 species, deterministic from userId, AI-generated personality.
- Dream tasks consolidate memory automatically in background.
- Agent swarms support up to 292+ agents with memory optimization (36GB fix).
- Bridge system enables remote control from claude.ai with up to 32 concurrent sessions.
- Computer use via MCP with Rust/Swift native modules for mouse/keyboard/screenshots.
- 89+ feature flags via GrowthBook enable extremely rapid experimentation.
- "Fennec" was the internal codename for Opus; "Capybara" is likely a current internal test model.
- Fast mode is the same model at 6x cost ($30/$150 for Opus 4.6).
- Opus 4.6 is the current top model with 1M context support.
- Internal Anthropic developers (
USER_TYPE=ant) get 24+ additional commands, custom model overrides, and features like JS REPL, heap dumps, and trace tools. - Moreright is an internal-only query hook stubbed out in external builds — likely used for internal experimentation.
- Upstream proxy in CCR containers uses
prctlto block ptrace and immediately erases session tokens from disk. - Native TypeScript ports of Rust/C++ modules (syntax highlighting, fuzzy search, flexbox layout) eliminate native dependencies.
Agent Tool invocation
↓
generateTaskId('local_agent') → "a7x9q2m1"
↓
createTaskStateBase(id, 'local_agent', description)
↓
registerTask(taskState, setAppState)
├─ Stores in AppState.tasks[taskId]
└─ Emits SDK event 'task_started'
↓
Run agent asynchronously via query() in background
├─ Messages stored in task.messages[]
├─ Progress tracked (tokenCount, toolUseCount, recentActivities)
└─ Output appended to task.outputFile
↓
On completion → enqueueAgentNotification()
├─ Sets notified=true (prevents duplicate)
├─ Enqueues XML notification to message queue
└─ Submitted as message to coordinator
↓
Coordinator reads notification (arrives as user-role message)
└─ Continues with next phase
Key Mechanisms:
AbortController: Allows killing agent via TaskStopToolpendingMessages: Queue for mid-turn user messages (SendMessageTool)isBackgrounded: UI visibility (false=foreground, true=backgrounded)retain: Blocks eviction when UI is viewing (entered via CoordinatorTaskPanel)
Bash Tool invocation
↓
registerForeground() (if long-running) OR spawnShellTask()
├─ Creates taskState with status='running'
├─ Links to ShellCommand process
└─ Starts stall watchdog
↓
Process runs in background (isBackgrounded=true)
├─ Output streamed to DiskTaskOutput
├─ File polled every POLL_INTERVAL_MS (1000ms)
└─ Watchdog checks for frozen output + prompt-like tail
↓
On exit/failure → enqueueShellNotification()
├─ Status transitions to completed|failed|killed
├─ Exit code captured
└─ XML notification enqueued
Stall Detection:
Watchdog checks:
1. File size stable for STALL_THRESHOLD_MS (45s)
2. Tail of output matches PROMPT_PATTERNS (y/n?, Press Enter, etc.)
3. Enqueues notification suggesting kill + piped input
Remote Agent spawn (via background remote) OR Ultraplan/Ultrareview mode
↓
checkRemoteAgentEligibility()
├─ User logged in?
├─ Git repo with remote?
├─ GitHub app installed?
└─ Policy enabled?
↓
registerRemoteAgentTask()
├─ Creates sessionId (remote session on CCR)
├─ pollStartedAt = Date.now()
└─ Registers task in AppState
↓
pollRemoteSessionEvents() runs in background
├─ Fetches CCR session status/events
├─ Extracts log (SDKMessage[] array)
├─ Checks completionCheckers for task-specific done conditions
└─ Polls every ~few seconds
↓
On completion → enqueueRemoteNotification()
Completion Checkers: Per-task-type handlers:
registerCompletionChecker(remoteTaskType, checker)- Examples: autofix-pr, background-pr, ultraplan, ultrareview
Teammate ← Leader
↓
Register as in_process_teammate task
├─ identity: { agentId: "analyst@my-team", teamName: "my-team", ... }
├─ awaitingPlanApproval: false
├─ permissionMode: 'ask' | 'allow' | 'deny'
└─ messages: [] (UI mirror, capped at 50)
↓
Run locally with runAgent()
├─ Full conversation history on disk
├─ Agent context injected via AsyncLocalStorage
└─ Spinnerverbs for UI (random animation text)
↓
On idle/completion → Notify leader via onIdleCallbacks[]
Trigger: Auto-consolidation when sessions grow large
↓
DreamTask registers as UI-surfaced task
├─ Makes forked agent visible in footer pill & Shift+Down dialog
├─ phase: 'starting' → 'updating' (when first Edit/Write tool used)
├─ sessionsReviewing: count of sessions analyzed
├─ filesTouched[]: paths observed in tool calls
└─ turns[]: assistant responses with tool counts collapsed
↓
On completion/kill → rollbackConsolidationLock()
└─ Rewind lock mtime so next session can retry
/tmp/.claude/{projectTempDir}/{sessionId}/tasks/
├── {taskId}.output ← Flat text accumulation
├── a7x9q2m1.output
├── b9k2m8p1.output
└── r5x3q7n2.output
Security: O_NOFOLLOW prevents symlink attacks in sandbox
Disk Cap: MAX_TASK_OUTPUT_BYTES = 5GB — process killed if exceeded
generateTaskAttachments()
├─ For each task in AppState.tasks:
│ ├─ If notified + terminal → mark for eviction
│ ├─ If running → getTaskOutputDelta(taskId, lastOffset)
│ │ └─ Async file read (tail since lastOffset)
│ └─ Collect delta content
│
├─ Evict terminal+notified tasks from AppState
│ └─ Frees memory when done
│
└─ Return { attachments, updatedTaskOffsets, evictedTaskIds }
applyTaskOffsetsAndEvictions()
├─ Re-check fresh state (task may have changed during await)
├─ Update outputOffset if still running
└─ Remove from AppState if terminal + notified + no UI hold
Polling interval: POLL_INTERVAL_MS = 1000ms
Grace Periods:
- Killed tasks show in UI for
STOPPED_DISPLAY_MS(3s) - Coordinator panel tasks hold for
PANEL_GRACE_MS(30s) if user is viewing
let shouldEnqueue = false
updateTaskState(taskId, setAppState, task => {
if (task.notified) return task // Already notified, skip
shouldEnqueue = true
return { ...task, notified: true }
})
if (shouldEnqueue) {
enqueuePendingNotification(...)
}enqueuePendingNotification({ value, mode: 'task-notification' })
├─ mode: 'task-notification' | 'informational'
├─ priority: 'next' | 'later'
└─ agentId?: (for routing to specific agent)
↓
Message queue drains on next query() turn
└─ Submitted as user-role message with XML content
Converts CCR's SDKMessage format to REPL Message types:
| SDK Message Type | → REPL Message Type |
|---|---|
SDKAssistantMessage |
AssistantMessage |
SDKPartialAssistantMessage |
StreamEvent |
SDKResultMessage |
SystemMessage (error/success) |
SDKSystemMessage (init) |
SystemMessage |
SDKStatusMessage |
SystemMessage (compacting, etc.) |
SDKToolProgressMessage |
SystemMessage (tool X running for Ys) |
SDKCompactBoundaryMessage |
SystemMessage (conversation compacted) |
SDKUserMessage |
UserMessage (tool results, or skip if ignored) |
User: "Fix the null pointer in auth module"
Coordinator (Turn 1):
Agent({
description: "Investigate auth bug",
subagent_type: "worker",
prompt: "Investigate src/auth/. Find null pointer risks.
Report file paths, line numbers, types."
})
Agent({
description: "Research auth tests",
subagent_type: "worker",
prompt: "Find all test files for src/auth/.
Report structure and gaps. Do not modify."
})
→ "Investigating from two angles — I'll report back."
[Workers run in parallel]
<task-notification>
<task-id>a1b2c3</task-id>
<status>completed</status>
<summary>Agent "Investigate auth bug" completed</summary>
<result>Found null pointer in src/auth/validate.ts:42.
User field is undefined when...</result>
</task-notification>
Coordinator (Turn 2):
[Reads findings, synthesizes spec]
SendMessage({
to: "a1b2c3",
message: "Fix the null pointer in src/auth/validate.ts:42.
Add null check before user.id access.
If null, return 401 with 'Session expired'.
Commit and report the hash."
})
→ "Fix is in progress."
[Worker resumes with full context, makes changes, commits]
<task-notification>
<task-id>a1b2c3</task-id>
<status>completed</status>
<result>Fixed. Tests pass. Committed as abc123.</result>
</task-notification>
Coordinator (Turn 3):
Agent({
description: "Verify auth fix",
subagent_type: "verifier", // Fresh agent — sees code with fresh eyes
prompt: "Test the fix in src/auth/validate.ts:42.
Run auth tests. Try edge cases:
expired session, missing token, invalid JWT.
Report pass/fail."
})
[Verifier tests independently]
<task-notification>
<task-id>v4e5f6</task-id>
<status>completed</status>
<result>All tests pass. Edge cases handled. Fix is solid.</result>
</task-notification>
Coordinator (Turn 4):
"Fixed and verified. Null pointer in Session.user now returns
401 'Session expired'."
// AsyncLocalStorage isolates concurrent agents
SubagentContext = {
agentId: string // Task ID or agent identifier
agentType: string // 'worker'|'teammate'|'main-session'
subagentName: string // Human-readable (e.g., 'analyst')
isBuiltIn: boolean // true for system agents
}
runWithAgentContext(context, async () => {
// Code runs with isolated context
// Skill invocations scope to this agentId
// clearInvokedSkills(preservedAgentIds) selectively preserves
})hooks/useVirtualScroll.ts (1,000+ lines)
| Constant | Value | Purpose |
|---|---|---|
MAX_MOUNTED_ITEMS |
300 | Maximum items rendered in DOM |
OVERSCAN_ROWS |
80 | Extra rows rendered above/below viewport |
SCROLL_QUANTUM |
40 | Minimum scroll jump size |
SLIDE_STEP |
25 | Catch-up items per render cycle |
PESSIMISTIC_HEIGHT |
1 | Default 1 row per item (before measurement) |
- Items outside the 300-item window are unmounted (saves memory/render time)
- 80-row overscan prevents flicker on fast scrolls
- Scroll quantum of 40 rows avoids jittery partial-row scrolls
- Slide steps of 25 items allow smooth catch-up when window shifts
- Pessimistic 1-row height prevents layout jumps
hooks/useTypeahead.tsx (1,384 lines)
The typeahead provides suggestions from multiple sources simultaneously:
- Commands — All registered slash commands with descriptions
- Files — Fuzzy file search via
file-index(native-ts port) - Sessions — Previous conversation sessions for
/resume - Slack channels — When Slack app is connected
- Shell history — Recent bash/zsh history entries
- Argument hints — Per-command argument completion
/at start of input → command completion@→ file/directory mention- Tab key → context-aware completion
- After command name → argument completion
/session, /exit, /clear, /help, /theme, /color, /vim, /cost,
/usage, /copy, /feedback
/session, /exit, /clear, /help, /theme, /color
local-jsxcommands (Ink UI) — cannot render remotely- Most
localcommands — except those explicitly whitelisted
AppState {
// Session
settings: Settings
verbose: boolean
model: string
sessionId: string
// UI State
expandedViews: Set<string>
footerSelection: FooterItem // 'companion' | 'tasks' | 'teammates' | ...
teammatePreviewId?: string
briefOnlyView: boolean
// Tools & Permissions
toolPermissions: Record<string, PermissionState>
bypassPermissions: boolean
autoMode: boolean
// Remote/Bridge
remoteConnected: boolean
bridgeMode: boolean
ccrMode: boolean
// Speculation (Pipelined responses)
speculationResult?: SpeculationResult
speculationInput?: string
// Files
fileHistory: FileHistoryEntry[]
fileAttribution: Record<string, string>
// Tasks & Agents
tasks: Record<string, TaskState>
foregroundedTaskId?: string
// Companion (Buddy)
companionReaction?: string
companionPetAt?: number
// Completion Boundaries
completionBoundaries: CompletionBoundary[]
// Types: 'complete' | 'bash' | 'edit' | 'denied_tool'
}| Event | When Fired |
|---|---|
PreToolUse |
Before any tool execution |
PostToolUse |
After tool execution completes |
UserPromptSubmit |
When user submits a message |
SessionStart |
When a new session begins |
FileChanged |
When a watched file changes on disk |
Notification |
When a notification is triggered |
Stop |
When the session/agent stops |
// PreToolUse can:
{ decision: 'allow' } // Proceed with tool
{ decision: 'deny' } // Block tool execution
{ decision: 'modify', input: {...} } // Modify tool input
// UserPromptSubmit can:
{ decision: 'allow' } // Proceed with query
{ decision: 'block' } // Block the submission
{ decision: 'modify', message: '...' } // Rewrite the message- Hooks configured in
settings.jsonunderhookskey - Snapshot captured at startup to prevent hidden modifications
- FileChanged hooks watch specific paths with debouncing
- Hooks execute shell commands and parse JSON/text output
- AbortSignal support for cancellation
Triggered when context window approaches limits:
- Standard compact — Summarizes older messages, keeps recent
- Microcompaction — Lighter-weight compression of tool results
- Reactive compact — Emergency compaction when API returns context-too-long error
- History snipping — Aggressive removal of old conversation turns
Context approaching limit
↓
Check auto-compact eligibility
├─ Has enough compactable content?
├─ Not already compacted recently?
└─ Not in middle of tool execution?
↓
Select strategy:
├─ microcompact (tool results only, preserves conversation)
├─ standard compact (summarize + trim)
└─ history snip (HISTORY_SNIP flag, aggressive cut)
↓
Apply compaction
├─ Insert <system-reminder> compaction boundary
├─ Update token tracking
└─ Continue query loop
When enabled, removes duplicate context sections that accumulate during long conversations:
- Duplicate system reminders
- Repeated file contents
- Redundant tool results
| Variable | Purpose |
|---|---|
ANTHROPIC_API_KEY |
API key for authentication |
ANTHROPIC_MODEL |
Model override |
ANTHROPIC_BASE_URL |
Custom API endpoint |
CLAUDE_CODE_REMOTE |
Remote/CCR mode flag |
CLAUDE_CODE_COORDINATOR_MODE |
Coordinator mode |
CLAUDE_CODE_SIMPLE |
Simple mode (reduced tools) |
CLAUDE_CODE_DISABLE_AUTO_MEMORY |
Disable auto-memory |
CLAUDE_CODE_DISABLE_CLAUDE_MDS |
Disable Claude.md loading |
CLAUDE_CODE_DISABLE_1M_CONTEXT |
Disable 1M context (HIPAA) |
CLAUDE_CODE_SYNC_PLUGIN_INSTALL |
Synchronous plugin install |
CLAUDE_CODE_MESSAGING_SOCKET |
UDS socket path |
CLAUDE_CODE_VERIFY_PLAN |
Enable plan verification |
| Variable | Purpose |
|---|---|
ANTHROPIC_DEFAULT_OPUS_MODEL |
Custom Opus (3P) |
ANTHROPIC_DEFAULT_SONNET_MODEL |
Custom Sonnet (3P) |
ANTHROPIC_DEFAULT_HAIKU_MODEL |
Custom Haiku (3P) |
ANTHROPIC_CUSTOM_MODEL_OPTION |
Custom picker option |
ANTHROPIC_DEFAULT_OPUS_MODEL_NAME |
Display name override |
ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION |
Description override |
| Variable | Purpose |
|---|---|
ENABLE_LSP_TOOL |
Enable LSP tool |
ENABLE_AGENT_SWARMS |
Enable swarm mode |
USER_TYPE |
ant for internal Anthropic mode |
NODE_ENV |
test enables testing tools |
VOICE_STREAM_BASE_URL |
Voice STT endpoint override |
CCR_UPSTREAM_PROXY_ENABLED |
Enable upstream proxy |
| Variable | Purpose |
|---|---|
DISABLE_COMPACT |
Disable compact command |
DISABLE_DOCTOR_COMMAND |
Disable doctor |
DISABLE_LOGIN_COMMAND |
Disable login |
DISABLE_LOGOUT_COMMAND |
Disable logout |
DISABLE_INSTALL_GITHUB_APP_COMMAND |
Disable GitHub setup |
CLAUDE_CODE_ABLATION_BASELINE |
Ablation testing mode |
Location: constants/prompts.ts (1,400+ lines)
The system prompt is dynamically assembled from conditional sections:
- Role definition — "You are Claude Code, Anthropic's official CLI..."
- System info — Platform, shell, OS version, model name, knowledge cutoff
- Tool instructions — Per-tool usage guidance
- Git instructions — Commit, PR, safety protocols
- Memory prompt — From
memdir/system - User context — Claude.md files, project docs
- Git status — Current branch, recent commits
- Date injection — Current date
- Output style — If custom output style configured
- Coordinator context — Worker tools, scratchpad path (if coordinator mode)
- Companion intro — Buddy system prompt (if buddy active)
- Feature-specific sections — Brief mode, voice hints, etc.
if (coordinatorMode) → Add worker tools context, concurrency rules
if (buddy && mentioned) → Add companion intro attachment
if (voiceMode) → Add voice usage hints
if (briefMode) → Add brief-only instructions
if (outputStyle) → Add custom style instructions
if (!bare && !simple) → Add memory prompt
- Sections marked as cacheable for prompt cache optimization
- 1-hour TTL allowlist for cache eligibility
PROMPT_CACHE_BREAK_DETECTIONflag validates cache hits- Cache breakpoints tracked for cost analysis
The system supports speculative pipelining where responses begin generating before the user finishes typing:
SpeculationResult {
input: string // The speculated user input
messages: Message[] // Pre-generated response messages
completionBoundary: CompletionBoundary
}How it works:
- After assistant completes, system guesses next likely user input
- Begins generating response speculatively in background
- If user's actual input matches speculation, response appears instantly
- If input differs, speculated response is discarded
- Completion boundaries track:
complete,bash,edit,denied_tool
Sessions can be "teleported" between machines/environments:
useTeleportResume.tsx— Handles teleported session resumelaunchTeleportResumeWrapper— Resume wrapper dialoglaunchTeleportRepoMismatchDialog— Detects repo mismatches
Flow:
- Session serialized on source machine
- Transferred to target (via bridge or manual)
- Target checks repository match
- If mismatch → dialog offers options
- If match → seamless resume with full context
- Bidirectional communication with VS Code and JetBrains extensions
- Selection/context sharing from editor to CLI
- Diff viewing in IDE (
hooks/useDiffInIDE.ts) - Diagnostic tracking from IDE (
services/diagnosticTracking.ts) - Status indicator in IDE (
hooks/useIDEStatusIndicator.tsx) - Auto-connect detection (
components/IdeAutoConnectDialog.tsx) - Logging bridge (
hooks/useIdeLogging.ts)
- Full Language Server Protocol client
- Symbol resolution, goto definition, find references
- Diagnostic information (errors, warnings)
- Opt-in via
ENABLE_LSP_TOOLenv var - Plugin recommendation system (
hooks/useLspPluginRecommendation.tsx— 21KB)
From types/hooks.ts — hooks can elicit information from the user:
// Hook can request user input before proceeding
PromptElicitation {
type: 'text' | 'confirm' | 'select'
message: string
options?: string[] // For 'select' type
default?: string | boolean // Default value
}
// Hook response includes elicited data
HookResponse {
decision: 'allow' | 'deny' | 'modify'
elicited?: Record<string, string | boolean>
}This enables hooks to create interactive approval flows before tool execution.
Readline-compatible editing with Emacs-style kill-ring:
| Shortcut | Action |
|---|---|
Ctrl+K |
Kill to end of line (push to kill-ring) |
Ctrl+U |
Kill to start of line (push to kill-ring) |
Ctrl+W |
Kill word backward (push to kill-ring) |
Ctrl+Y |
Yank (paste from kill-ring) |
Ctrl+A |
Move to start |
Ctrl+E |
Move to end |
Ctrl+F |
Move forward one char |
Ctrl+B |
Move backward one char |
Alt+F |
Move forward one word |
Alt+B |
Move backward one word |
Kill-ring stores multiple killed text segments; consecutive kills are concatenated.
type SessionActivity = {
type: 'tool_start' | 'text' | 'result' | 'error'
summary: string // "Editing src/foo.ts", "Reading package.json"
timestamp: number
}Tracked at 1Hz refresh — displayed in bridge UI as live status updates.
Compatibility layer for CCR v2 sessions — translates between v1 and v2 session APIs.
Optional verified-device auth that replaces one-time permission prompts:
- Generated on first trust approval
- Stored securely in keychain
- Sent with session registration
- Avoids repeated permission dialogs for known devices
Each model config (utils/model/configs.ts) contains:
ModelConfig {
id: string // e.g., "claude-opus-4-6"
family: 'opus' | 'sonnet' | 'haiku'
version: string // e.g., "4.6"
contextWindow: number // Default 200000
maxOutputTokens: number // Default 32000
defaultMaxTokens: number // Model-specific default
supports1m: boolean // Can use [1m] suffix
supportsThinking: boolean // Interleaved thinking
supportsFastMode: boolean // Speed vs quality
supportsImages: boolean // Image input
supportsPDFs: boolean // PDF input
costTier: CostTier // Pricing reference
deprecated?: DeprecationInfo // If being retired
}ALL_MODEL_CONFIGS = {
haiku35: CLAUDE_3_5_HAIKU_CONFIG,
haiku45: CLAUDE_HAIKU_4_5_CONFIG,
sonnet35: CLAUDE_3_5_V2_SONNET_CONFIG,
sonnet37: CLAUDE_3_7_SONNET_CONFIG,
sonnet40: CLAUDE_SONNET_4_CONFIG,
sonnet45: CLAUDE_SONNET_4_5_CONFIG,
sonnet46: CLAUDE_SONNET_4_6_CONFIG,
opus40: CLAUDE_OPUS_4_CONFIG,
opus41: CLAUDE_OPUS_4_1_CONFIG,
opus45: CLAUDE_OPUS_4_5_CONFIG,
opus46: CLAUDE_OPUS_4_6_CONFIG,
}
From constants/apiLimits.ts:
| Resource | Limit |
|---|---|
| Image size (base64) | 5 MB |
| PDF pages | 100 per document |
| PDF raw size | 20 MB |
| Media items per request | 100 |
| Max output tokens (default) | 32,000 |
| Max output tokens (upper) | 64,000 |
| Max output tokens (escalated) | 64,000 |
| Max context (standard) | 200,000 tokens |
| Max context (1M) | 1,000,000 tokens |
| Rarity | Probability | Stat Floor | Peak Range | Hat Options |
|---|---|---|---|---|
| Common | 60% | 5 | 55-85 | none only |
| Uncommon | 25% | 15 | 65-95 | all 8 |
| Rare | 10% | 25 | 75-100 (capped) | all 8 |
| Epic | 4% | 35 | 85-100 (capped) | all 8 |
| Legendary | 1% | 50 | 100 (capped) | all 8 |
- 1% additional chance on top of rarity
- Gold rendering variant
- Stacks with any rarity (e.g., Shiny Legendary = 0.01%)
1. Pick one stat index as "peak" → floor + random(50, 80)
2. Pick one stat index as "dump" → floor + random(-10, 5)
3. Remaining stats → random(0, 40)
4. Cap all values at 100
| Rarity | Color Token |
|---|---|
| Common | inactive (gray) |
| Uncommon | success (green) |
| Rare | permission (blue) |
| Epic | autoAccept (purple) |
| Legendary | warning (gold) |
Analysis performed 2026-03-31 using 7 parallel exploration agents + 1 model-specific agent.