Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save michaellee8/664aaf8a53305dbbd0ff31d5303c3352 to your computer and use it in GitHub Desktop.

Select an option

Save michaellee8/664aaf8a53305dbbd0ff31d5303c3352 to your computer and use it in GitHub Desktop.

Claude Code Source Analysis — Complete Report (2026-03-31)

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.


Table of Contents

  1. Overview
  2. Hidden Feature: Voice Mode
  3. Hidden Feature: Buddy System (ASCII Pet Companion)
  4. Hidden Feature: Dream Tasks (Auto-Memory Consolidation)
  5. Multi-Agent Architecture
  6. Bridge System — Remote Control
  7. Complete Tool Inventory
  8. Upstream Proxy
  9. Native TypeScript Ports
  10. Memory System (memdir)
  11. Commands & Keybindings
  12. Screens & UI Architecture
  13. Skills System
  14. Hooks System
  15. Services Ecosystem
  16. State Management
  17. Context Management
  18. Query Engine & Query Loop
  19. Model Definitions & Pricing
  20. Feature Flags (89+)
  21. API Beta Headers
  22. Authentication & Authorization
  23. Cost Tracking & Billing
  24. Analytics & Telemetry
  25. Bootstrap & Initialization Flow
  26. Moreright — Internal Query Hook
  27. Migrations
  28. Entrypoints
  29. Vim Mode
  30. Ink Rendering System
  31. Component Library
  32. Output Styles
  33. Plugin System
  34. MCP Integration
  35. Computer Use & Chrome Integration
  36. Notification System
  37. Permission System
  38. Key Architecture Patterns
  39. File Reference Map
  40. Summary Statistics

1. Overview

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.

Top-Level Directory Structure

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

Key Root-Level Files

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.

Architecture

Feature Gating (voice/voiceModeEnabled.ts):

  • isVoiceGrowthBookEnabled(): Checks feature('VOICE_MODE') + GrowthBook kill-switch tengu_amber_quartz_disabled
  • hasVoiceAuth(): 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-napi module (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 rec command with silence detection
  • Dependency checking: Automatically detects and suggests package manager installs (brew, apt-get, dnf, pacman)
  • Microphone permissions: TCC dialog trigger on macOS (probed during /voice command)

Speech-to-Text (services/voiceStreamSTT.ts — 545 lines):

  • Endpoint: Anthropic's private /api/ws/speech_to_text/voice_stream WebSocket
  • Route: Uses api.anthropic.com listener instead of claude.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

Configuration

  • 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)

Interesting Implementation Details

  1. 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.
  2. GrowthBook emergency kill-switch: tengu_amber_quartz_disabled feature flag can turn off voice instantly.
  3. Language hint counter: Resets whenever STT language changes, shows hint max 2 times.
  4. Deepgram Nova 3 opt-in (tengu_cobalt_frost): Uses conversation-engine route for better accuracy; cumulative transcripts + mid-text revisions require different finalize logic.
  5. Platform-specific TLS: Uses mTLS on Linux/Windows; browser-fingerprint JA3 on macOS (CF zone allows).
  6. Native module warmup trade-off: No preload during startup (would freeze ~1-8s), accepts ~1s delay on first voice press.

File Reference

  • voice/voiceModeEnabled.ts (55 lines) — Feature gating
  • services/voice.ts (526 lines) — Audio capture
  • services/voiceStreamSTT.ts (545 lines) — STT WebSocket
  • services/voiceKeyterms.ts (107 lines) — Vocab hints
  • hooks/useVoice.ts (250+ lines) — Main hook
  • hooks/useVoiceEnabled.ts (26 lines) — Memoized auth
  • hooks/useVoiceIntegration.tsx (200+ lines) — UI integration
  • context/voice.tsx (87 lines) — State provider
  • commands/voice/index.ts (20 lines) — Command def
  • commands/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.

Companion Generation (buddy/companion.ts — 134 lines)

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 Claude
  • personality: Generated by Claude
  • hatchedAt: Timestamp

Caching: roll(userId) caches result with memoization (hot path: 500ms sprite tick, keystroke, per-turn)

Species (buddy/types.ts — 149 lines)

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

Sprites (buddy/sprites.ts — 515 lines)

  • 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: <·~·>

UI Rendering (buddy/CompanionSprite.tsx — 371 lines)

  • 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

System Prompt Integration (buddy/prompt.ts — 37 lines)

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 & Notification (buddy/useBuddyNotification.tsx — 98 lines)

  • Teaser window: April 1-7, 2026 (local date, 24h rolling wave across timezones)
  • Shows rainbow-colored /buddy notification on startup (if no companion hatched)
  • Detects /buddy in input (findBuddyTriggerPositions)

Configuration

{
  "companion": {
    "name": "string (model-generated)",
    "personality": "string (model-generated)",
    "hatchedAt": "number (timestamp)"
  },
  "companionMuted": "boolean (hide sprite + reactions)"
}

State (AppStateStore.ts)

companionReaction?: string    // Latest speech bubble text
companionPetAt?: number       // Timestamp of /buddy pet
footerSelection: FooterItem   // Can be 'companion' for footer pill

Unique Characteristics

  1. 4,320+ unique looks (18 species × 6 eyes × 8 hats × 5 rarities)
  2. 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.
  3. Users can't fake a legendary — deterministic from userId hash.
  4. 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: startingupdating (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)
  • Gated by KAIROS / KAIROS_DREAM feature flags
  • Triggered by services/autoDream.ts

5. Multi-Agent Architecture

Coordinator Mode (coordinator/coordinatorMode.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

7 Task Types

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

Task Lifecycle

TaskStatus: pending → running → {completed | failed | killed}

Task State Structure

{
  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
}

Task ID Generation (Cryptographic)

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

XML Notification Format

<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>

Agent Swarms (AGENT_SWARMS)

  • 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

Remote Agent Tasks (CCR Integration)

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 alive

Worktree System (Git Isolation)

claude-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)

Coordinator System Prompt Directives

  1. Workers are async — launch concurrently
  2. Never delegate understanding — include specific file paths, line numbers
  3. Match context: Continue worker if it explored the right files; spawn fresh if broad research
  4. Verify independently: Verifier should see code with fresh eyes
  5. Be skeptical — if something looks off, dig in

Tool Availability by Agent Type

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

6. Bridge System — Remote Control

Location: bridge/ (33 files, 400KB+)

Bidirectional WebSocket bridge between claude.ai web UI and local CLI instances.

Session Protocol

  1. 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_secret for ongoing auth
  2. Work Polling Loop:

    • Polls /environments/{id}/work endpoint
    • Receives WorkResponse with session assignment
    • Decodes base64url JSON WorkSecret with:
      • 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
  3. 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)
  4. 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

Resilience

  • 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

Key Files

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

7. Complete Tool Inventory

Always-Available Built-in Tools (24)

  1. AgentTool — Spawn subagents for parallel/specialized tasks
  2. BashTool — Execute shell commands
  3. FileReadTool — Read file contents with token budgeting
  4. FileEditTool — Edit file content with diffs
  5. FileWriteTool — Write new files
  6. WebFetchTool — Fetch and process content from URLs (deferred)
  7. WebSearchTool — Search the web
  8. GlobTool — File pattern matching
  9. GrepTool — Regex-based file content search
  10. NotebookEditTool — Edit Jupyter notebooks
  11. TaskOutputTool — Generate tool output
  12. ExitPlanModeV2Tool — Exit plan mode
  13. EnterPlanModeTool — Enter planning mode
  14. BriefTool — Generate brief responses
  15. TodoWriteTool — Write/manage TODO items
  16. SkillTool — Invoke skills and custom commands
  17. AskUserQuestionTool — Ask user for input/confirmation
  18. TaskStopTool — Stop executing tasks
  19. ToolSearchTool — Search for available tools (deferred load)
  20. ListMcpResourcesTool — List MCP server resources
  21. ReadMcpResourceTool — Read MCP resource content
  22. MCPTool — Execute MCP tools (wrapper)
  23. McpAuthTool — Handle MCP authentication
  24. SendMessageTool — Send messages between agents

Feature-Gated Tools (17+)

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

Ant-Only Tools (Internal Anthropic)

Tool Purpose
ConfigTool Configuration management
TungstenTool Virtual terminal wrapper
REPLTool JavaScript REPL environment

Testing-Only Tools

Tool Condition
TestingPermissionTool NODE_ENV=test
PowerShellTool Windows, when enabled

Tool Permission System

Permission Modes:

  • default — User prompts for dangerous operations
  • bypass — Automatic approval (dangerous)
  • auto — Machine-based classifier with fallback to prompting

Tool Deferred Loading:

  • Tools marked with shouldDefer: true are sent with defer_loading: true
  • Require ToolSearchTool to be called first
  • Built-in tools take precedence over MCP tools in name conflicts

8. Upstream Proxy

Location: upstreamproxy/ — HTTPS MITM proxy for CCR container environments.

Initialization Flow

  1. Reads CLAUDE_CODE_REMOTE and CCR_UPSTREAM_PROXY_ENABLED env vars
  2. Reads session token from /run/ccr/session_token, immediately unlinks it
  3. Calls prctl(PR_SET_DUMPABLE, 0) via Bun FFI to block same-UID ptrace
  4. Downloads proxy CA cert from {base_url}/v1/code/upstreamproxy/ca-cert
  5. Launches local CONNECT→WebSocket relay on localhost TCP
  6. Exposes HTTPS_PROXY, SSL_CERT_FILE, NO_PROXY env vars

NO_PROXY Whitelist

  • Loopback, RFC1918, IMDS range
  • *.anthropic.com (prevents MITM of Anthropic API calls)
  • github.com, npm registry, PyPI, crates.io, golang proxy

Relay Protocol (relay.ts — 300+ lines)

  • 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)

9. Native TypeScript Ports

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)

color-diff

  • highlight.js for syntax highlighting + diff npm for word diffing
  • Output: Colored ANSI escape sequences, line numbers, word-level markers

file-index

  • 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)

yoga-layout

  • 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

10. Memory System (memdir)

Location: memdir/ (8 files) — Multi-scoped persistent memory.

Memory Types

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

Architecture

  • 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

Logging Architecture

~/.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

Feature Gating

  • GrowthBook: tengu_passport_quail (main), tengu_slate_thimble (non-interactive)
  • Disabled in CCR containers, --bare mode, SIMPLE mode
  • CLAUDE_CODE_DISABLE_AUTO_MEMORY env var

Team Memory

  • teamMemPaths.ts — Team scope paths (gated by TEAMMEM feature)
  • teamMemPrompts.ts — Team scope prompt text
  • Shared via git for team collaboration

11. Commands & Keybindings

All Public Commands (67+)

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

Ant-Only (Internal) Commands (24+)

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

Disabled Stubs

Command Status
/good-claude Disabled
/issue Disabled
/ctx-viz Disabled
/perf-issue Disabled
/bughunter Disabled

Feature-Flagged Commands (14+)

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

Keyboard Shortcuts

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


12. Screens & UI Architecture

Three Main Screens

  1. REPL.tsx (5,005 lines) — Main conversation loop/prompt input
  2. Doctor.tsx (574 lines) — Diagnostic/verification screen
  3. ResumeConversation.tsx (398 lines) — Resume previous conversations

REPL Features

  • 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

13. Skills System

Bundled Skills (Always Enabled)

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

Feature-Gated Skills

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

Skill Types

  • 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

14. Hooks System

68+ custom React hooks + 16 notification hooks in hooks/.

Core Input/Display 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

Audio/Voice Hooks

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

Major Feature Hooks

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

Notification Hooks (16)

  • useAutoModeUnavailableNotification — Auto mode blockers
  • useCanSwitchToExistingSubscription — Plan upgrade hints
  • useDeprecationWarningNotification — Model deprecation notices
  • useFastModeNotification — Fast mode status
  • useIDEStatusIndicator — IDE connection status
  • useInstallMessages — Plugin/dependency feedback
  • useLspInitializationNotification — LSP server status
  • useMcpConnectivityStatus — MCP server health
  • useModelMigrationNotifications — Model upgrade suggestions
  • useNpmDeprecationNotification — Npm package warnings
  • usePluginAutoupdateNotification — Plugin update status
  • usePluginInstallationStatus — Plugin install progress
  • useRateLimitWarningNotification — Rate limit warnings
  • useSettingsErrors — Settings validation
  • useStartupNotification — Startup progress
  • useTeammateShutdownNotification — Swarm shutdown events

15. Services Ecosystem

35+ major service modules in services/.

Core 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

Advanced Services

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

16. State Management

AppState (Centralized, Immutable)

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)

Bootstrap State (bootstrap/state.ts — 56KB)

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

17. Context Management

Git Status Context (context.ts)

  • 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

User Context

  • 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

Context Injection Points

  • Prepended to each conversation turn
  • Cached for duration of session
  • Observable performance metrics with diagnostic logging

18. Query Engine & Query Loop

QueryEngine.ts (Main Orchestrator)

  • 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

query.ts (Generator-Based Loop)

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)

Key Features

  • Auto-compaction: When context approaches limits
  • Reactive compaction: Triggered by token limits
  • Microcompaction: Cached config
  • History snipping: Aggressive history compression
  • Token budget: TOKEN_BUDGET feature 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

19. Model Definitions & Pricing

All Model IDs

Opus Family

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

Sonnet Family

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

Haiku Family

Model ID Alias Notes
claude-3-5-haiku-20241022 Haiku 3.5 (deprecated 1P)
claude-haiku-4-5-20251001 haiku Current default

Special Aliases

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

Provider-Specific Model IDs

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 @date suffix: claude-opus-4@20250514

Foundry:

  • Simple format: claude-opus-4-6, claude-sonnet-4-6

Pricing

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

Default Model by User Tier

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

1M Context Support

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).

Deprecated Models

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)

Internal Codenames

  • "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

Model Capabilities

  • Default context: 200,000 tokens
  • Max output tokens: Default 32,000, Upper limit 64,000
  • Capabilities cached at ~/.claude/cache/model-capabilities.json

Environment Variable Overrides

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

Model Allowlist

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

20. Feature Flags (89+)

AI/ML Features

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

Agent Systems

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

Context Management

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

I/O & UI

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

Infrastructure

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

21. API Beta Headers

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.


22. Authentication & Authorization

OAuth System (services/oauth/)

  • 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

Permission Modes

Mode Behavior
default User prompted for dangerous operations
bypass Automatic approval (dangerous, sandbox-only)
auto Machine-based classifier with fallback to prompting

23. Cost Tracking & Billing

cost-tracker.ts (324 lines)

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.XX for 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)

24. Analytics & Telemetry

Architecture (services/analytics/)

OpenTelemetry Integration:

  • firstPartyEventLogger.ts — Event logging with batch processing
  • firstPartyEventLoggingExporter.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 disabled
  • config.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)

GrowthBook Feature Flags

All use tengu_* naming convention:

  • tengu_amber_quartz_disabled — Voice kill-switch
  • tengu_cobalt_frost — Deepgram Nova 3 STT
  • tengu_passport_quail — Auto-memory
  • tengu_slate_thimble — Non-interactive memory
  • tengu_ccr_bridge_multi_session — Multi-session bridge
  • tengu_ant_model_override — Ant model override
  • tengu_memdir_loaded — Memory loaded telemetry
  • And many more...

25. Bootstrap & Initialization Flow

Startup Sequence (setup.ts — 477 lines)

  1. Node.js version check (requires 18+)
  2. Custom session ID handling
  3. UDS messaging server (Mac/Linux, unless --bare)
  4. Teammate snapshot capture (if swarms enabled)
  5. Terminal backup restoration (iTerm2, Terminal.app)
  6. CWD establishment (setCwd before hooks)
  7. Hooks configuration snapshot (prevent hidden modifications)
  8. FileChanged hook watcher initialization
  9. Worktree creation (if --worktree flag)
  10. UDS socket export to $CLAUDE_CODE_MESSAGING_SOCKET
  11. Background jobs (SessionMemory, context collapse)
  12. Plugin prefetch (unless CLAUDE_CODE_SYNC_PLUGIN_INSTALL)
  13. Release notes check (interactive sessions)
  14. Permission bypass validation (Docker/sandbox checks)
  15. Previous session cost logging (tengu_exit event)

Main Launch Flow (main.tsx — 4,683 lines)

  1. Profiling checkpoints (startupProfiler)
  2. MDM raw read (managed settings) — parallel
  3. Keychain prefetch (OAuth + API key) — parallel
  4. Feature flag initialization (GrowthBook)
  5. Command initialization (getCommands)
  6. Plugin loading (bundled + user plugins)
  7. Skill registration (bundled skills)
  8. MCP servers (official registry, enterprise config)
  9. Policy limits (wait for loading)
  10. Remote managed settings
  11. Permission setup (dialog flow)
  12. Model configuration (selection, deprecation warnings)
  13. REPL launch (replLauncher)

Dialog Launchers

  • launchResumeChooser — Resume previous session
  • launchAssistantSessionChooser — Assistant mode session
  • launchAssistantInstallWizard — Assistant setup
  • launchSnapshotUpdateDialog — Team memory updates
  • launchTeleportResumeWrapper — Teleported session resume
  • launchTeleportRepoMismatchDialog — Teleport conflict
  • launchInvalidSettingsDialog — Settings validation

26. Moreright — Internal Query Hook

Location: moreright/useMoreRight.tsxStubbed for external builds.

A React hook that intercepts and enhances the REPL message flow:

  • onBeforeQuery(input, allMessages, n) — Intercepts before query; can return false to block
  • onTurnComplete(allMessages, aborted) — Called after each turn completes
  • render() — 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"


27. Migrations

Location: migrations/ — 11 idempotent, one-shot migration functions.

Migration What It Does
migrateAutoUpdatesToSettings globalConfig.autoUpdates=falsesettings.json DISABLE_AUTOUPDATER
migrateBypassPermissionsAcceptedToSettings globalConfig.bypassPermissionsModeAcceptedsettings.json
migrateEnableAllProjectMcpServersToSettings Project MCP approval → local settings
migrateFennecToOpus fennec-latestopus, fennec-fast-latestopus + fast mode
migrateLegacyOpusToCurrent opus-4.0/4.1opus alias
migrateOpusToOpus1m opusopus[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

28. Entrypoints

Location: entrypoints/

  1. 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)
  2. MCP Entry (mcp.ts) — MCP protocol server integration

  3. SDK Types (sdk/) — TypeScript SDK definitions

    • coreTypes.ts, coreSchemas.ts, controlSchemas.ts

29. Vim Mode

Location: vim/ (5 files, ~500 lines)

Full Implementation

Modes: INSERT ↔ NORMAL via escape / i/a/o

Motions (vim/motions.ts):

  • h/l/j/k — arrow movement
  • gj/gk — visual line movement
  • w/b/e/W/B/E — word boundaries
  • 0/^/$ — line positioning
  • G/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

30. Ink Rendering System

Location: ink/ (96 files, 40K+ lines) — Custom fork of Ink terminal UI framework.

Core Architecture

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

Interactive Features

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

Built-in Components

  • App.tsx, AlternateScreen.tsx, ScrollBox.tsx, Link.tsx, Spacer.tsx, Newline.tsx
  • TerminalSizeContext.tsx, TerminalFocusContext.tsx, ClockContext.tsx

31. Component Library

Location: components/ (146 files)

Major UI Components

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

Dialog Components

  • ApproveApiKey.tsx, AutoModeOptInDialog.tsx, AutoUpdater.tsx
  • BypassPermissionsModeDialog.tsx, ChannelDowngradeDialog.tsx
  • CostThresholdDialog.tsx, InvalidConfigDialog.tsx
  • ClaudeInChromeOnboarding.tsx, IdeAutoConnectDialog.tsx
  • IdleReturnDialog.tsx, HistorySearchDialog.tsx
  • GlobalSearchDialog.tsx, ExportDialog.tsx

Specialized

  • FileEditToolDiff.tsx — File edit visualization
  • ShellProgress.tsx — Shell command progress
  • DevBar.tsx — Developer toolbar (ant-only)
  • DiagnosticsDisplay.tsx — Diagnostic information
  • design-system/ — Reusable design components
  • agents/ — Agent-specific UI

32. Output Styles

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

33. Plugin System

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}@builtin for built-in plugins
  • User preferences stored in settings (enabledPlugins map)

34. MCP Integration

Location: services/mcp/

Key Capabilities

  • 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

Special Built-in MCP Servers

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

MCP Tool Naming Convention

Format: mcp__<serverName>__<toolName> (e.g., mcp__claude-in-chrome__navigate_to)


35. Computer Use & Chrome Integration

Claude in Chrome (utils/claudeInChrome/)

  • Browser automation for user's real Chrome
  • OAuth and authenticated site support
  • Contrasts with WebBrowser (dev servers, JS eval)
  • Rendering pipeline for browser interactions

Computer Use (utils/computerUse/)

  • Desktop automation and control
  • Screenshot capture with privacy filter
  • Mouse and keyboard input via Rust/enigo
  • Application management and detection
  • Clipboard operations (pbpaste/pbcopy)

36. Notification System

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

37. Permission System

Tool Permissions (hooks/useCanUseTool.tsx — 40KB)

  • 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

Permission Modes

Mode Behavior
default Interactive approval dialogs
auto Intelligent defaults with classifier
bypass Skip all checks (sandbox-only)

Permission Contexts

  • Each teammate cycles independently (Shift+Tab)
  • Coordinator has global permission mode
  • MCP tools inherited from parent
  • Orphaned permission cleanup for legacy rules

38. Key Architecture Patterns

Atomic State Updates

updateTaskState(taskId, setAppState, task => {
  if (task.status !== 'running') return task  // Guard
  return { ...task, status: 'killed', endTime: Date.now() }
})

Fire-and-Forget Async

void persistRemoteAgentMetadata(meta).catch(err =>
  logForDebugging(`persistence failed: ${err}`)
)

Memory-Efficient Message Capping

export const TEAMMATE_MESSAGES_UI_CAP = 50
// Prevents 36GB+ memory usage with 292 agents

Abort Controller Hierarchies

abortController.abort()             // Parent: abort entire subtree
currentWorkAbortController.abort()  // Child: abort only current turn

Task Output Security

  • O_NOFOLLOW prevents symlink attacks in sandbox
  • MAX_TASK_OUTPUT_BYTES = 5GB cap per task
  • Task IDs use randomBytes(8) with 36-char alphabet (2.8 trillion combinations)

39. File Reference Map

Core System

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-Specific

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/

40. Summary Statistics

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)

Key Takeaways

  1. Claude Code is a full-featured autonomous agent platform — far beyond a simple CLI chat tool.
  2. Voice input launching with Deepgram Nova 3 STT, 90+ languages, push-to-talk.
  3. Buddy companion launching April 1, 2026 — 18 species, deterministic from userId, AI-generated personality.
  4. Dream tasks consolidate memory automatically in background.
  5. Agent swarms support up to 292+ agents with memory optimization (36GB fix).
  6. Bridge system enables remote control from claude.ai with up to 32 concurrent sessions.
  7. Computer use via MCP with Rust/Swift native modules for mouse/keyboard/screenshots.
  8. 89+ feature flags via GrowthBook enable extremely rapid experimentation.
  9. "Fennec" was the internal codename for Opus; "Capybara" is likely a current internal test model.
  10. Fast mode is the same model at 6x cost ($30/$150 for Opus 4.6).
  11. Opus 4.6 is the current top model with 1M context support.
  12. Internal Anthropic developers (USER_TYPE=ant) get 24+ additional commands, custom model overrides, and features like JS REPL, heap dumps, and trace tools.
  13. Moreright is an internal-only query hook stubbed out in external builds — likely used for internal experimentation.
  14. Upstream proxy in CCR containers uses prctl to block ptrace and immediately erases session tokens from disk.
  15. Native TypeScript ports of Rust/C++ modules (syntax highlighting, fuzzy search, flexbox layout) eliminate native dependencies.

APPENDIX A: Detailed Task Execution Flows

A.1 LocalAgentTask — Full Spawning Flow

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 TaskStopTool
  • pendingMessages: Queue for mid-turn user messages (SendMessageTool)
  • isBackgrounded: UI visibility (false=foreground, true=backgrounded)
  • retain: Blocks eviction when UI is viewing (entered via CoordinatorTaskPanel)

A.2 LocalShellTask — Background Bash

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

A.3 RemoteAgentTask — Cloud/CCR Sessions

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

A.4 InProcessTeammateTask — Team Mode / Swarm Agents

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[]

A.5 DreamTask — Auto-Memory Consolidation

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

APPENDIX B: Polling & Output Infrastructure

B.1 Task Output File System

/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

B.2 Main Polling Loop (utils/task/framework.ts)

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

B.3 Atomic Notification (Prevent Duplicates)

let shouldEnqueue = false
updateTaskState(taskId, setAppState, task => {
  if (task.notified) return task  // Already notified, skip
  shouldEnqueue = true
  return { ...task, notified: true }
})
if (shouldEnqueue) {
  enqueuePendingNotification(...)
}

B.4 Notification Queue

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

APPENDIX C: SDK Message Adapter Mappings

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)

APPENDIX D: Coordinator Mode — Complete Orchestration Example

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'."

APPENDIX E: Agent Context Isolation

// 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
})

APPENDIX F: Virtual Scroll Implementation

hooks/useVirtualScroll.ts (1,000+ lines)

Configuration

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)

Behavior

  • 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

APPENDIX G: Typeahead Engine

hooks/useTypeahead.tsx (1,384 lines)

Unified Suggestion Sources

The typeahead provides suggestions from multiple sources simultaneously:

  1. Commands — All registered slash commands with descriptions
  2. Files — Fuzzy file search via file-index (native-ts port)
  3. Sessions — Previous conversation sessions for /resume
  4. Slack channels — When Slack app is connected
  5. Shell history — Recent bash/zsh history entries
  6. Argument hints — Per-command argument completion

Trigger Detection

  • / at start of input → command completion
  • @ → file/directory mention
  • Tab key → context-aware completion
  • After command name → argument completion

APPENDIX H: Remote/Bridge Safe Command Lists

REMOTE_SAFE_COMMANDS (11 commands safe in --remote mode)

/session, /exit, /clear, /help, /theme, /color, /vim, /cost,
/usage, /copy, /feedback

BRIDGE_SAFE_COMMANDS (6 commands safe over Remote Control bridge)

/session, /exit, /clear, /help, /theme, /color

Blocked Command Types in Remote/Bridge

  • local-jsx commands (Ink UI) — cannot render remotely
  • Most local commands — except those explicitly whitelisted

APPENDIX I: Complete AppState Fields

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'
}

APPENDIX J: Hook Events & Lifecycle

Available Hook Events (types/hooks.ts)

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

Hook Response Types

// 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

Hook Configuration (hooks/ system)

  • Hooks configured in settings.json under hooks key
  • 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

APPENDIX K: Compact & Context Management Strategies

Auto-Compaction

Triggered when context window approaches limits:

  1. Standard compact — Summarizes older messages, keeps recent
  2. Microcompaction — Lighter-weight compression of tool results
  3. Reactive compact — Emergency compaction when API returns context-too-long error
  4. History snipping — Aggressive removal of old conversation turns

Compaction Flow

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

Context Collapse (CONTEXT_COLLAPSE)

When enabled, removes duplicate context sections that accumulate during long conversations:

  • Duplicate system reminders
  • Repeated file contents
  • Redundant tool results

APPENDIX L: Complete Environment Variables

Core Configuration

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

Provider Selection

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

Feature Toggles

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

Disable Commands

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

APPENDIX M: System Prompt Architecture

Location: constants/prompts.ts (1,400+ lines)

The system prompt is dynamically assembled from conditional sections:

Prompt Sections (in order)

  1. Role definition — "You are Claude Code, Anthropic's official CLI..."
  2. System info — Platform, shell, OS version, model name, knowledge cutoff
  3. Tool instructions — Per-tool usage guidance
  4. Git instructions — Commit, PR, safety protocols
  5. Memory prompt — From memdir/ system
  6. User context — Claude.md files, project docs
  7. Git status — Current branch, recent commits
  8. Date injection — Current date
  9. Output style — If custom output style configured
  10. Coordinator context — Worker tools, scratchpad path (if coordinator mode)
  11. Companion intro — Buddy system prompt (if buddy active)
  12. Feature-specific sections — Brief mode, voice hints, etc.

Conditional Sections

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

Prompt Caching

  • Sections marked as cacheable for prompt cache optimization
  • 1-hour TTL allowlist for cache eligibility
  • PROMPT_CACHE_BREAK_DETECTION flag validates cache hits
  • Cache breakpoints tracked for cost analysis

APPENDIX N: Speculation / Pipelined Responses

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:

  1. After assistant completes, system guesses next likely user input
  2. Begins generating response speculatively in background
  3. If user's actual input matches speculation, response appears instantly
  4. If input differs, speculated response is discarded
  5. Completion boundaries track: complete, bash, edit, denied_tool

APPENDIX O: Session Teleport

Sessions can be "teleported" between machines/environments:

  • useTeleportResume.tsx — Handles teleported session resume
  • launchTeleportResumeWrapper — Resume wrapper dialog
  • launchTeleportRepoMismatchDialog — Detects repo mismatches

Flow:

  1. Session serialized on source machine
  2. Transferred to target (via bridge or manual)
  3. Target checks repository match
  4. If mismatch → dialog offers options
  5. If match → seamless resume with full context

APPENDIX P: IDE Integration Details

IDE Bridge (hooks/useIDEIntegration.tsx)

  • 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)

LSP Integration (services/lsp/)

  • Full Language Server Protocol client
  • Symbol resolution, goto definition, find references
  • Diagnostic information (errors, warnings)
  • Opt-in via ENABLE_LSP_TOOL env var
  • Plugin recommendation system (hooks/useLspPluginRecommendation.tsx — 21KB)

APPENDIX Q: Prompt Elicitation Protocol

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.


APPENDIX R: Search & Kill-Ring System

Search Input (hooks/useSearchInput.ts)

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.


APPENDIX S: Bridge Session Activity Tracking

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.

CSE Shim

Compatibility layer for CCR v2 sessions — translates between v1 and v2 session APIs.

Trusted Device Tokens

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

APPENDIX T: Model Config Registry Structure

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 Registered Configs

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,
}

APPENDIX U: API Limits

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

APPENDIX V: Complete Rarity System (Buddy)

Rarity Distribution

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

Shiny Variant

  • 1% additional chance on top of rarity
  • Gold rendering variant
  • Stacks with any rarity (e.g., Shiny Legendary = 0.01%)

Stat Generation Algorithm

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 Colors in UI

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment