# sanbuphy/claude-code-source-code architecture

> Architecture diagram of the GitHub repository sanbuphy/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/sanbuphy/claude-code-source-code
- Repository: https://github.com/sanbuphy/claude-code-source-code

## Overview

1. **What this repo is**
   This is the extracted TypeScript source for `@anthropic-ai/claude-code` v2.1.88: a terminal-first AI agent harness, not a typical web app. The core product is an interactive REPL/CLI plus a headless SDK/query engine, both backed by the same agent loop and tool system.

2. **Top-level runtime boundary**
   The main entrypoints are `src/entrypoints/cli.tsx`, `src/main.tsx`, and `src/QueryEngine.ts`. The CLI path drives the interactive terminal app; the SDK/query path exposes a streaming async API for programmatic use. `src/screens/REPL.tsx` and `src/screens/ResumeConversation.tsx` are the primary user-facing shell screens.

3. **Core agent loop**
   The central data flow is: user input → prompt assembly → Claude API streaming response → tool-use detection → tool execution → append tool result → repeat. That loop lives mainly in `src/query.ts`, with `src/services/api/claude.ts` handling the model call and `src/services/tools/*` orchestrating execution.

4. **Tooling is the main extension point**
   Tools are first-class modules with a shared interface defined in `src/Tool.ts` and registered through `src/tools.ts`. Built-ins span filesystem, shell, web, MCP, skills, tasks, planning, messaging, and agent spawning. Each tool typically has input validation, permission checks, prompt text, and UI renderers under `src/tools/<ToolName>/`.

5. **Permission and safety boundary**
   Tool execution is gated by a permission system centered in `src/utils/permissions/` and wired through hooks in `src/hooks/toolPermission/`. The flow includes rules from settings, interactive approval dialogs, and tool-specific checks like path safety, sandboxing, and destructive-command detection. This is a key architectural boundary between model intent and host-side side effects.

6. **Task and agent topology**
   The repo supports multiple execution contexts: local shell tasks, local sub-agents, remote agents, in-process teammates, and background “dream” tasks. These are modeled in `src/tasks/` and coordinated through tools like `AgentTool`, `TaskCreateTool`, `TeamCreateTool`, `SendMessageTool`, and worktree-related commands. This is how the product scales from a single chat loop to multi-agent delegation.

7. **Context management and memory**
   Conversation state is not just raw chat history. It is compacted, summarized, and partitioned by `src/services/compact/`, persisted in session logs, and augmented by memory and CLAUDE.md-style directory context from `src/memdir/` and `src/services/SessionMemory/`. This layer keeps long-running sessions within token limits while preserving relevant history.

8. **Session persistence and resume**
   Sessions are written as append-only JSONL logs under project-specific storage, then rehydrated for continue/resume/fork flows. Related logic appears in `src/history.ts`, `src/utils/sessionStorage.ts`, `src/utils/sessionRestore.ts`, and `src/commands/resume/`. Persistence is part of the core architecture, not an afterthought.

9. **Terminal UI architecture**
   The UI is built on a custom Ink-based terminal rendering layer under `src/ink/`, with React components in `src/components/`. The UI handles prompt input, message rendering, permission dialogs, task/status panels, settings, onboarding, and visual feedback like spinners and progress lines. The UI is a presentation layer over the same underlying state and services.

10. **Application state**
   Global state lives in `src/state/`, with `AppStateStore` and React context providers exposing selectors and setters. This state tracks permission mode, fast mode, model selection, file history, attribution, and other cross-cutting UI/runtime flags. It acts as the coordination layer between the UI, tools, and services.

11. **External integrations**
   The repo integrates with the Claude API, MCP servers, OAuth flows, GitHub/Slack install flows, LSP, plugins, and remote session infrastructure. Key subsystems are `src/services/mcp/`, `src/services/plugins/`, `src/services/oauth/`, `src/services/lsp/`, and `src/remote/`. These integrations widen the agent’s capabilities without changing the core loop.

12. **Bridge and remote control**
   `src/bridge/` implements a remote/session bridge used for desktop or managed control scenarios. It includes session lifecycle management, message relaying, JWT/work-secret handling, polling, and wake/capacity logic. Architecturally, this is a separate transport/control plane from the local CLI loop.

13. **Telemetry, analytics, and runtime governance**
   `src/services/analytics/` and `src/utils/telemetry/` collect event, usage, and performance data; feature flags and runtime policies are threaded through `src/utils/betas.ts`, `src/utils/model/`, and settings sync modules. This repo is heavily governed by runtime configuration, experimentation, and remote policy updates.

14. **Build shape and missing code**
   The source tree is extracted from a bundled CLI, so it is larger and more modular than the published runtime artifact. The README notes that some feature-gated modules are absent because they were dead-code-eliminated in the published package. For architecture diagrams, treat `src/` as the logical system design, but note that some advanced modes are compile-time gated and not present in the shipped bundle.

Main entry points: [`src/query.ts`](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/query.ts) (Agent loop), [`src/screens/REPL.tsx`](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/screens/REPL.tsx) (REPL screen), [`src/tools.ts`](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/tools.ts) (Built-in tools), [`src/utils/sessionStorage.ts`](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/utils/sessionStorage.ts) (Session logs)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_runtime["Runtime entrypoints"]
  node_entry_cli["CLI entry<br/>entrypoint<br/>[cli.tsx]"]
  node_entry_main["Main runtime<br/>entrypoint<br/>[main.tsx]"]
  node_query_engine["Query engine<br/>sdk api<br/>[QueryEngine.ts]"]
end

subgraph group_agent["Agent core"]
  node_query_loop(("Agent loop<br/>orchestrator<br/>[query.ts]"))
  node_claude_api["Claude API<br/>model client<br/>[claude.ts]"]
  node_tool_registry["Tool registry<br/>tool catalog"]
  node_tool_execution["Tool execution<br/>execution layer<br/>[toolExecution.ts]"]
  node_permission_gate{{"Permission gate<br/>safety layer<br/>[permissions.ts]"}}
  node_tool_suite["Built-in tools<br/>tool family<br/>[tools.ts]"]
end

subgraph group_ui["Terminal UI"]
  node_repl_screen["REPL screen<br/>terminal screen<br/>[REPL.tsx]"]
  node_resume_screen["Resume screen<br/>terminal screen"]
  node_ink_ui["Ink UI<br/>rendering layer<br/>[ink.tsx]"]
end

subgraph group_state["App state"]
  node_app_state[("App state<br/>store<br/>[AppStateStore.ts]")]
end

subgraph group_sessions["Sessions & memory"]
  node_session_store[("Session logs<br/>persistence<br/>[sessionStorage.ts]")]
  node_compaction["Compaction<br/>context mgmt<br/>[compact.ts]"]
  node_memory_layer["Memory layer<br/>context memory<br/>[sessionMemory.ts]"]
end

subgraph group_integrations["Integrations"]
  node_bridge_plane["Bridge plane<br/>remote control<br/>[bridgeMain.ts]"]
  node_mcp_integration["MCP integration"]
  node_plugin_system["Plugin system<br/>extension platform"]
  node_telemetry["Telemetry<br/>governance<br/>[index.ts]"]
end

subgraph group_tasks["Task topology"]
  node_task_system["Task system<br/>multi-agent runtime<br/>[tasks.ts]"]
end

node_entry_cli -->|"starts"| node_entry_main
node_entry_main -->|"opens"| node_repl_screen
node_entry_main -->|"exposes"| node_query_engine
node_repl_screen -->|"renders with"| node_ink_ui
node_resume_screen -->|"restores"| node_session_store
node_repl_screen -->|"reads/writes"| node_app_state
node_query_engine -->|"drives"| node_query_loop
node_repl_screen -->|"submits input"| node_query_loop
node_query_loop -->|"calls"| node_claude_api
node_query_loop -->|"selects tools"| node_tool_registry
node_tool_registry -->|"registers"| node_tool_suite
node_tool_suite -->|"runs through"| node_tool_execution
node_tool_execution -->|"checks"| node_permission_gate
node_permission_gate -->|"updates"| node_app_state
node_query_loop -->|"appends"| node_session_store
node_session_store -->|"feeds"| node_compaction
node_compaction -->|"augments"| node_memory_layer
node_task_system -->|"used by"| node_tool_suite
node_bridge_plane -->|"rehydrates"| node_session_store
node_bridge_plane -->|"relays"| node_query_loop
node_mcp_integration -->|"extends"| node_tool_suite
node_plugin_system -->|"adds"| node_tool_registry
node_telemetry -->|"observes"| node_query_loop
node_telemetry -->|"observes"| node_plugin_system

click node_entry_cli "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/entrypoints/cli.tsx"
click node_entry_main "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/main.tsx"
click node_query_engine "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/QueryEngine.ts"
click node_query_loop "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/query.ts"
click node_claude_api "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/services/api/claude.ts"
click node_tool_execution "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/services/tools/toolExecution.ts"
click node_permission_gate "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/utils/permissions/permissions.ts"
click node_repl_screen "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/screens/REPL.tsx"
click node_resume_screen "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/screens/ResumeConversation.tsx"
click node_ink_ui "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/ink/ink.tsx"
click node_app_state "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/state/AppStateStore.ts"
click node_session_store "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/utils/sessionStorage.ts"
click node_compaction "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/services/compact/compact.ts"
click node_memory_layer "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/services/SessionMemory/sessionMemory.ts"
click node_bridge_plane "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/bridge/bridgeMain.ts"
click node_mcp_integration "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/services/mcp/MCPConnectionManager.tsx"
click node_plugin_system "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/services/plugins/PluginInstallationManager.ts"
click node_telemetry "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/services/analytics/index.ts"
click node_task_system "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/tasks.ts"
click node_tool_suite "https://github.com/sanbuphy/claude-code-source-code/blob/main/src/tools.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_entry_cli,node_entry_main,node_query_engine,node_task_system toneBlue
class node_query_loop,node_claude_api,node_tool_registry,node_tool_execution,node_permission_gate,node_tool_suite toneAmber
class node_repl_screen,node_resume_screen,node_ink_ui toneMint
class node_app_state toneRose
class node_session_store,node_compaction,node_memory_layer toneIndigo
class node_bridge_plane,node_mcp_integration,node_plugin_system,node_telemetry toneTeal
```

## Components

### Runtime entrypoints

Local CLI and SDK entry paths

- [CLI entry](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/entrypoints/cli.tsx): entrypoint · Terminal app startup and command dispatch · `src/entrypoints/cli.tsx`
- [Main runtime](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/main.tsx): entrypoint · Bootstraps the application shell and runtime wiring · `src/main.tsx`
- [Query engine](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/QueryEngine.ts): sdk api · Headless streaming interface for programmatic use · `src/QueryEngine.ts`

### Agent core

Prompt, model, tools, and orchestration loop

- [Agent loop](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/query.ts): orchestrator · Input to model to tool-use to continuation loop · `src/query.ts`
- [Claude API](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/services/api/claude.ts): model client · Streaming model calls and response handling · `src/services/api/claude.ts`
- **Tool registry**: tool catalog · Shared tool interface and registration surface
- [Tool execution](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/services/tools/toolExecution.ts): execution layer · Streaming tool runs and orchestration plumbing · `src/services/tools/toolExecution.ts`
- [Permission gate](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/utils/permissions/permissions.ts): safety layer · Approvals, rules, and host-side side-effect controls · `src/utils/permissions/permissions.ts`
- [Built-in tools](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/tools.ts): tool family · Filesystem, shell, web, task, agent, and messaging tools · `src/tools.ts`

### Terminal UI

Ink-based presentation and screen flow

- [REPL screen](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/screens/REPL.tsx): terminal screen · Primary interactive conversation shell · `src/screens/REPL.tsx`
- [Resume screen](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/screens/ResumeConversation.tsx): terminal screen · Conversation continuation and restore flow · `src/screens/ResumeConversation.tsx`
- [Ink UI](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/ink/ink.tsx): rendering layer · Custom terminal rendering and event layer · `src/ink/ink.tsx`

### App state

Cross-cutting runtime state and coordination

- [App state](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/state/AppStateStore.ts): store · Global runtime flags, selectors, and shared state · `src/state/AppStateStore.ts`

### Sessions & memory

Persistence, resume, compaction, and memory

- [Session logs](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/utils/sessionStorage.ts): persistence · Append-only conversation history and restore data · `src/utils/sessionStorage.ts`
- [Compaction](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/services/compact/compact.ts): context mgmt · Summarization and token-budget control · `src/services/compact/compact.ts`
- [Memory layer](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/services/SessionMemory/sessionMemory.ts): context memory · Directory memory and session memory augmentation · `src/services/SessionMemory/sessionMemory.ts`

### Integrations

External services and managed connections

- [Bridge plane](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/bridge/bridgeMain.ts): remote control · Remote session bridge and managed control transport · `src/bridge/bridgeMain.ts`
- [MCP integration](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/services/mcp/MCPConnectionManager.tsx): integration · Model Context Protocol server/client coordination · `src/services/mcp/MCPConnectionManager.tsx`
- [Plugin system](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/services/plugins/PluginInstallationManager.ts): extension platform · Plugin loading, validation, and marketplace handling · `src/services/plugins/PluginInstallationManager.ts`
- [Telemetry](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/services/analytics/index.ts): governance · Analytics, tracing, and usage reporting · `src/services/analytics/index.ts`

### Task topology

Local and remote execution contexts

- [Task system](https://github.com/sanbuphy/claude-code-source-code/blob/main/src/tasks.ts): multi-agent runtime · Shell tasks, local agents, teammates, and remote workers · `src/tasks.ts`

## Connections

- CLI entry → Main runtime: starts · CLI launches the main application runtime
- Main runtime → REPL screen: opens · Interactive runs enter the terminal shell
- Main runtime → Query engine: exposes · Main runtime also supports headless SDK usage
- REPL screen → Ink UI: renders with · Screens are presented through the Ink rendering layer
- Resume screen → Session logs: restores · Resume flows rehydrate prior session state
- REPL screen → App state: reads/writes · UI coordinates through shared application state
- Query engine → Agent loop: drives · SDK requests enter the same agent loop
- REPL screen → Agent loop: submits input · User prompts are forwarded into the loop
- Agent loop → Claude API: calls · The loop streams model responses
- Agent loop → Tool registry: selects tools · Tool-use decisions are resolved against the registry
- Tool registry → Built-in tools: registers · Built-in tools implement the shared interface
- Built-in tools → Tool execution: runs through · Tool invocations are executed by the tool layer
- Tool execution → Permission gate: checks · Side effects require permission and safety approval
- Permission gate → App state: updates · Permission mode and approvals are reflected in global state
- Agent loop → Session logs: appends · Conversation turns and tool results are persisted
- Session logs → Compaction: feeds · Stored history is compacted for long sessions
- Compaction → Memory layer: augments · Summaries are combined with directory and session memory
- Task system → Built-in tools: used by · Task-oriented tools create and manage execution contexts
- Bridge plane → Session logs: rehydrates · Remote control flows attach to existing sessions
- Bridge plane → Agent loop: relays · Bridge transport forwards messages into the agent loop
- MCP integration → Built-in tools: extends · MCP exposes external capabilities as tools
- Plugin system → Tool registry: adds · Plugins contribute commands, tools, and behaviors
- Telemetry → Agent loop: observes · Runtime events and usage are captured around the loop
- Telemetry → Plugin system: observes · Plugin activity is also instrumented
