How caowen2211891/claude-code-source-code works
1. What this repository is
- This is the unbundled TypeScript source for Claude Code v2.1.88, a terminal-first AI agent application.
- The core product is a CLI + REPL + SDK/headless query engine wrapped around a streaming agent loop, tool execution, local state, and optional remote/desktop bridge modes.
2. Top-level architecture
- The main flow is: entrypoints → query engine → tool execution/services → state/UI updates.
- src/main.tsx, src/entrypoints/cli.tsx, and src/screens/REPL.tsx boot the interactive app.
- src/QueryEngine.ts is the headless/SDK-facing execution path, while src/query.ts is the main agent loop used by both interactive and non-interactive flows.
3. The agent loop is the center of the system
- User input is parsed, turned into messages, sent to the Claude API, and streamed back as text/tool-use events.
- When the model emits tool calls, the loop routes them into the tool system, appends tool results, and continues until the response completes.
- This loop is the main boundary for architecture diagrams: everything else exists to support, constrain, or enrich it.
4. Tooling is a first-class subsystem
- Tools live in src/tools/ and are registered through src/tools.ts and src/Tool.ts.
- The major tool families are:
- file and repo operations: read, write, edit, glob, grep, notebook edit
- execution: Bash, PowerShell
- network/web: WebFetch, WebSearch
- agent/task orchestration: AgentTool, TaskCreate/Get/List/Update/Stop, TeamCreate/Delete
- integration/protocol: MCP tools, skill invocation, user-question tools
- Each tool has its own input validation, permission checks, rendering, and model-facing prompt text.
5. Permission and safety boundaries sit between the model and tools
- Tool execution is not direct; it passes through permission hooks, policy rules, tool-specific security checks, and sometimes interactive prompts.
- The permission logic is concentrated in src/hooks/toolPermission/, src/components/permissions/, and src/utils/permissions/.
- Shell/file tools also have extra safety layers for path validation, destructive command detection, sandboxing, and read-only modes.
6. UI is terminal-native, not browser-native
- The main UI is built with Ink/React, not a web frontend.
- src/components/ holds the terminal UI: message rendering, prompt input, permission dialogs, settings panels, task views, and status indicators.
- src/ink/ is a custom rendering/runtime layer for terminal layout, focus, input handling, and screen updates.
7. Application state is centralized
- src/state/AppStateStore.ts and src/state/AppState.tsx provide the shared state model.
- State covers permissions, file history, model selection, fast mode, attribution, queues, and other session-level UI/runtime concerns.
- This state layer is the bridge between the query engine, the UI, and command handlers.
8. Commands provide the user-facing control surface
- src/commands/ contains a large slash-command system: auth, config, resume, compact, agents, MCP, memory, model, permissions, review, plugins, and many more.
- These commands are not separate apps; they are alternate entry paths into the same session/state/tool infrastructure.
- Architecture-wise, commands are a control plane over the core agent runtime.
9. Tasks and sub-agents form the work orchestration layer
- src/tasks/ models different execution targets: local shell tasks, local agents, remote agents, in-process teammates, and “dream” background tasks.
- src/tools/AgentTool/ and related utilities support sub-agent spawning and delegation.
- This repo supports multi-agent patterns: a main agent can delegate work, coordinate teammates, and track outputs as structured task state.
10. Context management is a dedicated subsystem
- The repo includes compaction and memory systems to keep long sessions usable.
- src/services/compact/, src/memdir/, src/services/SessionMemory/, and related utilities handle summarization, memory retrieval, and context trimming.
- This is important in diagrams because the system is not a simple request/response bot; it continuously manages limited context across long-lived sessions.
11. External integrations are isolated behind service layers
- src/services/api/ is the Claude API client layer.
- src/services/mcp/ manages Model Context Protocol servers and transports.
- src/services/oauth/, src/services/plugins/, src/services/settingsSync/, src/services/lsp/, and src/remote/ cover auth, extensions, syncing, language-server integration, and remote sessions.
- These services are boundaries around external systems rather than direct concerns of the UI or tool loop.
12. Remote/bridge mode is a separate session transport
- src/bridge/ and src/server/ implement the bridge/session lifecycle used for desktop or remote control scenarios.
- src/remote/ manages remote sessions and websocket-style communication.
- This subsystem is distinct from the local CLI loop: it brokers session state, messages, authentication tokens, and process spawning across machines or app boundaries.
13. Telemetry, analytics, and policy are cross-cutting
- src/services/analytics/ and src/utils/telemetry/ collect usage, performance, and event data.
- The docs in docs/ indicate this repo also contains analysis of privacy, hidden features, remote control, and feature gating, which materially affects architecture.
- src/utils/settings/, src/services/remoteManagedSettings/, and src/utils/plugins/ show that runtime behavior can be centrally adjusted through settings, feature flags, and policy checks.
14. Build/runtime shape
- The project is extracted from a bundled CLI package and is intended to run in a Bun/Node.js-oriented environment, with extensive compile-time feature gating in the original build.
- There are many missing feature-gated modules referenced by the analysis notes, so this source tree represents the published, decompiled surface rather than the full internal monorepo.
- For architecture diagrams, treat the repo as a monolithic agent platform with multiple optional subsystems: interactive CLI, SDK/headless execution, bridge/remote, MCP/plugin integrations, and multi-agent orchestration.
Main entry points: query.ts Agent loop · tools.ts Tool registry · App.tsx App UI · bridgeMain.ts Bridge mode
Components 25
Entrypoints
CLI, REPL, SDK, and browser/bridge startup paths.
- App entry · Top-level process startup and app wiring.
src/main.tsx - CLI entry · Terminal command entrypoint and argument handling.
src/entrypoints/cli.tsx - REPL screen · Interactive terminal session screen.
src/screens/REPL.tsx
Core Loop
Agent execution, query orchestration, and streaming response handling.
- Query engine · SDK/headless execution path for agent queries.
src/QueryEngine.ts - Agent loop · Main Claude message loop that streams responses and tool calls.
src/query.ts
Terminal UI
Ink-based screens, components, prompts, and rendering/runtime layers.
- Ink runtime · Custom terminal rendering and input runtime.
src/ink/ink.tsx - App UI · Top-level terminal app composition and screens.
src/components/App.tsx - Prompt UI · Prompt, message list, status line, and session controls.
src/components/PromptInput/PromptInput.tsx - Permission UI · Interactive permission requests and safety dialogs.
src/components/permissions/PermissionDialog.tsx
State
Shared application state and session-level coordination.
- App state · Central session and UI state model.
src/state/AppState.tsx - State store · State persistence, updates, and selectors.
src/state/AppStateStore.ts
Tools
Model-facing tool implementations and tool orchestration.
- Tool registry · Registers and exports model-facing tools.
src/tools.ts - Tool base · Shared tool abstractions and tool lifecycle interfaces.
src/Tool.ts - File & shell · Read/write/edit/glob/grep and shell execution tools with safety layers.
src/tools/BashTool/BashTool.tsx - Agent tasks · Sub-agent, task, team, and orchestration tools.
src/tools/AgentTool/AgentTool.tsx - Integrations · MCP, skills, web, user-question, and remote-trigger tools.
src/tools/MCPTool/MCPTool.ts
Permissions
Safety gates, approval flows, and policy checks between model and tools.
- Tool guards · Permission hooks and policy callbacks between model intent and tool execution.
src/hooks/toolPermission/PermissionContext.ts - Policy rules · Permission modes, rule matching, path validation, and safety logic.
src/utils/permissions/permissions.ts
Services
External integrations and long-running support services.
- Claude API · Claude client, retries, errors, usage, and session ingress.
src/services/api/claude.ts - MCP service · Model Context Protocol connections, auth, and transports.
src/services/mcp/MCPConnectionManager.tsx - Memory & compact · Summarization, memory retrieval, and context trimming.
src/services/compact/compact.ts - Telemetry · Event logging, performance tracing, and opt-out aware reporting.
src/services/analytics/index.ts
Tasks
Execution targets for local, remote, and delegated work.
- Task runtime · Local shell, local agent, remote agent, and teammate task models.
src/tasks.ts
Bridge/Remote
Session transport for desktop, remote, and direct-connect modes.
- Bridge mode · Desktop/remote bridge lifecycle and message transport.
src/bridge/bridgeMain.ts - Remote sessions · Remote session manager and socket-based session transport.
src/remote/RemoteSessionManager.ts
Connections 28
- App entry → CLI entry: starts · Boots the terminal CLI process.
- App entry → REPL screen: launches · Opens the interactive REPL experience.
- CLI entry → App UI: mounts · Connects CLI lifecycle to the terminal UI.
- REPL screen → Ink runtime: renders on · Uses Ink for terminal layout and input handling.
- App UI → Prompt UI: contains · Composes prompt, messages, status, and controls.
- App UI → Permission UI: shows · Surfaces approval and safety dialogs.
- Prompt UI → State store: reads/writes · Consumes command, history, and session state.
- State store → App state: backing store · Holds centralized application/session state.
- Agent loop → Claude API: streams · Sends prompts and receives model responses.
- Query engine → Agent loop: invokes · Headless SDK path delegates to the main loop.
- Agent loop → Tool registry: requests tools · Resolves model tool calls through the registry.
- Tool registry → Tool base: implements · Tool definitions share the common tool contract.
- Tool registry → File & shell: includes · Registers file and shell execution tools.
- Tool registry → Agent tasks: includes · Registers sub-agent and task orchestration tools.
- Tool registry → Integrations: includes · Registers protocol, web, skill, and messaging tools.
- Agent loop → Tool guards: checks · Routes tool use through permission interception.
- Tool guards → Policy rules: enforces · Applies policy rules and safety decisions.
- Permission UI → Policy rules: drives · Interactive approval UI updates permission state.
- File & shell → Policy rules: guards · Shell and filesystem actions run through extra safety checks.
- Agent loop → Memory & compact: manages context · Compaction and memory keep long sessions workable.
- Agent loop → Task runtime: spawns · Delegates work to local, remote, or teammate tasks.
- Task runtime → Agent tasks: serves · Task tools create and control task objects.
- Integrations → MCP service: connects to · MCP tools rely on protocol service connections.
- Agent loop → Telemetry: emits · Session and tool activity is traced and logged.
- Bridge mode → Remote sessions: brokers · Bridge mode forwards session events and state.
- Bridge mode → Agent loop: feeds · Remote/desktop bridge still drives the same agent loop.
- Remote sessions → Agent loop: syncs · Remote sessions exchange messages with the core loop.
- App state → Bridge mode: shares state · Bridge mode is coordinated through shared session state.