How sanbuphy/claude-code-source-code works
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: query.ts Agent loop · REPL.tsx REPL screen · tools.ts Built-in tools · sessionStorage.ts Session logs
Components 21
Runtime entrypoints
Local CLI and SDK entry paths
- CLI entry · Terminal app startup and command dispatch
src/entrypoints/cli.tsx - Main runtime · Bootstraps the application shell and runtime wiring
src/main.tsx - Query engine · Headless streaming interface for programmatic use
src/QueryEngine.ts
Agent core
Prompt, model, tools, and orchestration loop
- Agent loop · Input to model to tool-use to continuation loop
src/query.ts - Claude API · Streaming model calls and response handling
src/services/api/claude.ts - Tool registry · Shared tool interface and registration surface
- Tool execution · Streaming tool runs and orchestration plumbing
src/services/tools/toolExecution.ts - Permission gate · Approvals, rules, and host-side side-effect controls
src/utils/permissions/permissions.ts - Built-in tools · Filesystem, shell, web, task, agent, and messaging tools
src/tools.ts
Terminal UI
Ink-based presentation and screen flow
- REPL screen · Primary interactive conversation shell
src/screens/REPL.tsx - Resume screen · Conversation continuation and restore flow
src/screens/ResumeConversation.tsx - Ink UI · Custom terminal rendering and event layer
src/ink/ink.tsx
App state
Cross-cutting runtime state and coordination
- App state · Global runtime flags, selectors, and shared state
src/state/AppStateStore.ts
Sessions & memory
Persistence, resume, compaction, and memory
- Session logs · Append-only conversation history and restore data
src/utils/sessionStorage.ts - Compaction · Summarization and token-budget control
src/services/compact/compact.ts - Memory layer · Directory memory and session memory augmentation
src/services/SessionMemory/sessionMemory.ts
Integrations
External services and managed connections
- Bridge plane · Remote session bridge and managed control transport
src/bridge/bridgeMain.ts - MCP integration · Model Context Protocol server/client coordination
src/services/mcp/MCPConnectionManager.tsx - Plugin system · Plugin loading, validation, and marketplace handling
src/services/plugins/PluginInstallationManager.ts - Telemetry · Analytics, tracing, and usage reporting
src/services/analytics/index.ts
Task topology
Local and remote execution contexts
- Task system · Shell tasks, local agents, teammates, and remote workers
src/tasks.ts
Connections 24
- 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