# caowen2211891/claude-code-source-code architecture

> Architecture diagram of the GitHub repository caowen2211891/claude-code-source-code, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-01). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/caowen2211891/claude-code-source-code
- Repository: https://github.com/caowen2211891/claude-code-source-code

## Overview

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: [`src/query.ts`](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/query.ts) (Agent loop), [`src/tools.ts`](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/tools.ts) (Tool registry), [`src/components/App.tsx`](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/components/App.tsx) (App UI), [`src/bridge/bridgeMain.ts`](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/bridge/bridgeMain.ts) (Bridge mode)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_entrypoints["Entrypoints"]
  node_main_entry["App entry<br/>bootstrap<br/>[main.tsx]"]
  node_cli_entry["CLI entry<br/>command-line<br/>[cli.tsx]"]
  node_repl_screen["REPL screen<br/>interactive-screen<br/>[REPL.tsx]"]
end

subgraph group_core["Core Loop"]
  node_query_engine["Query engine<br/>headless-exec<br/>[QueryEngine.ts]"]
  node_agent_loop["Agent loop<br/>streaming-orchestrator<br/>[query.ts]"]
end

subgraph group_ui["Terminal UI"]
  node_ink_runtime["Ink runtime<br/>terminal-renderer<br/>[ink.tsx]"]
  node_app_ui["App UI<br/>terminal-ui<br/>[App.tsx]"]
  node_prompt_ui["Prompt UI<br/>input-and-status<br/>[PromptInput.tsx]"]
  node_permission_ui["Permission UI<br/>approval-dialogs"]
end

subgraph group_state["State"]
  node_app_state[("App state<br/>shared-state<br/>[AppState.tsx]")]
  node_state_store[("State store<br/>[AppStateStore.ts]")]
end

subgraph group_tools["Tools"]
  node_tool_registry["Tool registry<br/>tool-registry<br/>[tools.ts]"]
  node_tool_core["Tool base<br/>tool-framework<br/>[Tool.ts]"]
  node_file_shell_tools["File & shell<br/>tool-family<br/>[BashTool.tsx]"]
  node_agent_task_tools["Agent tasks<br/>tool-family<br/>[AgentTool.tsx]"]
  node_integration_tools["Integrations<br/>tool-family<br/>[MCPTool.ts]"]
end

subgraph group_permissions["Permissions"]
  node_permission_hooks["Tool guards<br/>policy-gates"]
  node_permissions_utils["Policy rules<br/>security-policy<br/>[permissions.ts]"]
end

subgraph group_services["Services"]
  node_api_service["Claude API<br/>model-api<br/>[claude.ts]"]
  node_mcp_service["MCP service<br/>protocol-service"]
  node_memory_compact["Memory & compact<br/>context-management<br/>[compact.ts]"]
  node_telemetry_service["Telemetry<br/>analytics<br/>[index.ts]"]
end

subgraph group_tasks["Tasks"]
  node_task_runtime["Task runtime<br/>execution-targets<br/>[tasks.ts]"]
end

subgraph group_bridge["Bridge/Remote"]
  node_bridge_runtime["Bridge mode<br/>session-transport<br/>[bridgeMain.ts]"]
  node_remote_service["Remote sessions<br/>remote-session"]
end

node_main_entry -->|"starts"| node_cli_entry
node_main_entry -->|"launches"| node_repl_screen
node_cli_entry -->|"mounts"| node_app_ui
node_repl_screen -->|"renders on"| node_ink_runtime
node_app_ui -->|"contains"| node_prompt_ui
node_app_ui -->|"shows"| node_permission_ui
node_prompt_ui -->|"reads/writes"| node_state_store
node_state_store -->|"backing store"| node_app_state
node_agent_loop -->|"streams"| node_api_service
node_query_engine -->|"invokes"| node_agent_loop
node_agent_loop -->|"requests tools"| node_tool_registry
node_tool_registry -->|"implements"| node_tool_core
node_tool_registry -->|"includes"| node_file_shell_tools
node_tool_registry -->|"includes"| node_agent_task_tools
node_tool_registry -->|"includes"| node_integration_tools
node_agent_loop -->|"checks"| node_permission_hooks
node_permission_hooks -->|"enforces"| node_permissions_utils
node_permission_ui -->|"drives"| node_permissions_utils
node_file_shell_tools -->|"guards"| node_permissions_utils
node_agent_loop -->|"manages context"| node_memory_compact
node_agent_loop -->|"spawns"| node_task_runtime
node_task_runtime -->|"serves"| node_agent_task_tools
node_integration_tools -->|"connects to"| node_mcp_service
node_agent_loop -->|"emits"| node_telemetry_service
node_bridge_runtime -->|"brokers"| node_remote_service
node_bridge_runtime -->|"feeds"| node_agent_loop
node_remote_service -->|"syncs"| node_agent_loop
node_app_state -->|"shares state"| node_bridge_runtime

click node_main_entry "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/main.tsx"
click node_cli_entry "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/entrypoints/cli.tsx"
click node_repl_screen "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/screens/REPL.tsx"
click node_query_engine "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/QueryEngine.ts"
click node_agent_loop "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/query.ts"
click node_app_state "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/state/AppState.tsx"
click node_state_store "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/state/AppStateStore.ts"
click node_ink_runtime "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/ink/ink.tsx"
click node_app_ui "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/components/App.tsx"
click node_prompt_ui "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/components/PromptInput/PromptInput.tsx"
click node_permission_ui "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/components/permissions/PermissionDialog.tsx"
click node_tool_registry "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/tools.ts"
click node_tool_core "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/Tool.ts"
click node_file_shell_tools "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/tools/BashTool/BashTool.tsx"
click node_agent_task_tools "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/tools/AgentTool/AgentTool.tsx"
click node_integration_tools "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/tools/MCPTool/MCPTool.ts"
click node_permission_hooks "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/hooks/toolPermission/PermissionContext.ts"
click node_permissions_utils "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/utils/permissions/permissions.ts"
click node_api_service "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/services/api/claude.ts"
click node_mcp_service "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/services/mcp/MCPConnectionManager.tsx"
click node_memory_compact "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/services/compact/compact.ts"
click node_telemetry_service "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/services/analytics/index.ts"
click node_task_runtime "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/tasks.ts"
click node_bridge_runtime "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/bridge/bridgeMain.ts"
click node_remote_service "https://github.com/caowen2211891/claude-code-source-code/blob/main/src/remote/RemoteSessionManager.ts"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_main_entry,node_cli_entry,node_repl_screen,node_api_service,node_mcp_service,node_memory_compact,node_telemetry_service toneBlue
class node_query_engine,node_agent_loop,node_task_runtime toneAmber
class node_ink_runtime,node_app_ui,node_prompt_ui,node_permission_ui,node_bridge_runtime,node_remote_service toneMint
class node_app_state,node_state_store toneRose
class node_tool_registry,node_tool_core,node_file_shell_tools,node_agent_task_tools,node_integration_tools toneIndigo
class node_permission_hooks,node_permissions_utils toneTeal
```

## Components

### Entrypoints

CLI, REPL, SDK, and browser/bridge startup paths.

- [App entry](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/main.tsx): bootstrap · Top-level process startup and app wiring. · `src/main.tsx`
- [CLI entry](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/entrypoints/cli.tsx): command-line · Terminal command entrypoint and argument handling. · `src/entrypoints/cli.tsx`
- [REPL screen](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/screens/REPL.tsx): interactive-screen · Interactive terminal session screen. · `src/screens/REPL.tsx`

### Core Loop

Agent execution, query orchestration, and streaming response handling.

- [Query engine](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/QueryEngine.ts): headless-exec · SDK/headless execution path for agent queries. · `src/QueryEngine.ts`
- [Agent loop](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/query.ts): streaming-orchestrator · 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](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/ink/ink.tsx): terminal-renderer · Custom terminal rendering and input runtime. · `src/ink/ink.tsx`
- [App UI](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/components/App.tsx): terminal-ui · Top-level terminal app composition and screens. · `src/components/App.tsx`
- [Prompt UI](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/components/PromptInput/PromptInput.tsx): input-and-status · Prompt, message list, status line, and session controls. · `src/components/PromptInput/PromptInput.tsx`
- [Permission UI](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/components/permissions/PermissionDialog.tsx): approval-dialogs · Interactive permission requests and safety dialogs. · `src/components/permissions/PermissionDialog.tsx`

### State

Shared application state and session-level coordination.

- [App state](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/state/AppState.tsx): shared-state · Central session and UI state model. · `src/state/AppState.tsx`
- [State store](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/state/AppStateStore.ts): store · State persistence, updates, and selectors. · `src/state/AppStateStore.ts`

### Tools

Model-facing tool implementations and tool orchestration.

- [Tool registry](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/tools.ts): tool-registry · Registers and exports model-facing tools. · `src/tools.ts`
- [Tool base](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/Tool.ts): tool-framework · Shared tool abstractions and tool lifecycle interfaces. · `src/Tool.ts`
- [File & shell](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/tools/BashTool/BashTool.tsx): tool-family · Read/write/edit/glob/grep and shell execution tools with safety layers. · `src/tools/BashTool/BashTool.tsx`
- [Agent tasks](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/tools/AgentTool/AgentTool.tsx): tool-family · Sub-agent, task, team, and orchestration tools. · `src/tools/AgentTool/AgentTool.tsx`
- [Integrations](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/tools/MCPTool/MCPTool.ts): tool-family · 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](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/hooks/toolPermission/PermissionContext.ts): policy-gates · Permission hooks and policy callbacks between model intent and tool execution. · `src/hooks/toolPermission/PermissionContext.ts`
- [Policy rules](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/utils/permissions/permissions.ts): security-policy · Permission modes, rule matching, path validation, and safety logic. · `src/utils/permissions/permissions.ts`

### Services

External integrations and long-running support services.

- [Claude API](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/services/api/claude.ts): model-api · Claude client, retries, errors, usage, and session ingress. · `src/services/api/claude.ts`
- [MCP service](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/services/mcp/MCPConnectionManager.tsx): protocol-service · Model Context Protocol connections, auth, and transports. · `src/services/mcp/MCPConnectionManager.tsx`
- [Memory & compact](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/services/compact/compact.ts): context-management · Summarization, memory retrieval, and context trimming. · `src/services/compact/compact.ts`
- [Telemetry](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/services/analytics/index.ts): analytics · 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](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/tasks.ts): execution-targets · 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](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/bridge/bridgeMain.ts): session-transport · Desktop/remote bridge lifecycle and message transport. · `src/bridge/bridgeMain.ts`
- [Remote sessions](https://github.com/caowen2211891/claude-code-source-code/blob/main/src/remote/RemoteSessionManager.ts): remote-session · Remote session manager and socket-based session transport. · `src/remote/RemoteSessionManager.ts`

## Connections

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