How chinasiro/claude-code-sourcemap works
1. What this repo is
- This is the reconstructed source for @anthropic-ai/claude-code v2.1.88, a terminal-first AI assistant/runtime rather than a conventional web app.
- The main executable lives in package/cli.js with the TypeScript app in restored-src/src, and the app is built around a React-style terminal UI.
2. Top-level runtime shape
- src/main.tsx, src/entrypoints/cli.tsx, and src/entrypoints/init.ts are the main startup path.
- The app runs as a CLI process, manages its own event loop, and uses Node/Bun-oriented tooling plus native terminal handling.
3. Terminal UI layer
- src/ink/ is a custom terminal rendering/runtime layer, and src/components/ contains the visible UI.
- The UI is organized as dialogs, message feeds, input controls, status lines, permission prompts, and settings panes.
- This layer is responsible for rendering session state, prompts, tool results, approvals, and notifications to the terminal.
4. Session and application state
- src/state/, src/context/, src/history.ts, src/assistant/, and src/bootstrap/ hold the app’s mutable session model.
- These modules track conversation history, queued messages, session metadata, selected model/mode, and UI overlay state.
- src/hooks/ stitches state into the UI via many reactive hooks for input, session lifecycle, notifications, and integrations.
5. Core interaction flow
- User input enters through components/PromptInput and related hooks.
- Input is classified into text prompts, slash commands, or shell/tool actions via src/utils/processUserInput.
- The resulting action is routed into the main session loop, where it becomes either a model request, a command handler call, or a tool invocation.
6. Model and API boundary
- src/services/api/, src/query/, src/services/claudeAiLimits.ts, src/utils/model/, and src/services/tokenEstimation.ts define the AI/backend boundary.
- This layer handles Claude API calls, retries, usage/rate limits, model selection, prompt construction, token budgeting, and error normalization.
- It is the main outbound dependency to Anthropic services and related account/usage endpoints.
7. Tool execution pipeline
- src/tools/ contains the concrete capabilities the assistant can invoke: shell, file read/write/edit, grep/glob, web fetch/search, tasks, agent spawning, MCP, notebook edits, and more.
- src/services/tools/ and src/utils/toolPool.ts / toolOrchestration.ts manage execution, streaming results, and lifecycle tracking.
- Tool results are converted into typed messages and fed back into the conversation UI and model context.
8. Permissions, sandboxing, and safety
- Safety is a major architectural boundary: src/utils/permissions/, src/components/permissions/, and src/tools/BashTool / PowerShellTool implement approval flows and command validation.
- Sandbox-related behavior is handled by src/utils/sandbox/, src/components/sandbox/, and shell policy helpers.
- File edits, shell commands, and external access all pass through permission decisions, policy rules, and destructive-action checks before execution.
9. Integrations with developer tools and local environment
- The repo integrates with IDEs, LSP, Git, browser/chrome handoff, voice, and local shell environments through modules under src/services/lsp, src/utils/ide, src/utils/git, src/voice, and src/utils/claudeInChrome.
- These integrations feed status, diagnostics, file context, and external actions back into the assistant workflow.
- MCP support (src/services/mcp, src/components/mcp, src/tools/MCPTool) is a first-class extension boundary for connecting external tool servers.
10. Remote control and multi-device/session transport
- src/bridge/, src/remote/, src/server/, and src/upstreamproxy/ implement remote sessions, bridge control, websocket/SSE transport, and direct-connect flows.
- This is the boundary for controlling or resuming sessions outside the local terminal, including trusted device handling and session ingress.
- It separates local interactive execution from networked session management and remote orchestration.
11. Agents, tasks, and swarm/coordinator modes
- src/tools/AgentTool, src/tasks/, src/coordinator/, and src/utils/swarm/ support subordinate agents, background tasks, teammate modes, and multi-agent coordination.
- The architecture treats agents/tasks as durable execution units with their own status, progress, permissions, and resumability.
- This subsystem is distinct from the main chat loop: it fans work out to background or remote actors and then merges their outputs back into the parent session.
12. Plugins, skills, and extensibility
- src/plugins/, src/services/plugins/, src/skills/, and src/utils/hooks/ provide the extension model.
- Plugins can add commands, tools, hooks, output styles, and marketplace-distributed content; skills inject task-specific behavior and prompts.
- This is the main customization boundary, and it affects startup, command routing, tool availability, and UI affordances.
13. Persistence, memory, and session recovery
- src/memdir/, src/services/SessionMemory/, src/utils/sessionStorage*, src/utils/filePersistence/, and src/utils/conversationRecovery.ts handle local state and recall.
- The app persists session history, summaries, memories, settings, and cached outputs so sessions can be resumed or compacted later.
- Memory files and session artifacts form a second data plane beside the live conversation stream.
14. Telemetry, analytics, and operational services
- src/services/analytics/, src/utils/telemetry/, src/services/notifier.ts, and logging/tracing utilities provide observability.
- External sinks include Datadog, GrowthBook, BigQuery, and first-party event logging, with opt-out and killswitch support.
- This is not core to user interaction, but it materially affects startup checks, experiment gating, and post-run diagnostics.
15. How to think about the architecture diagram
- The central hub is the terminal session loop: user input → command/tool dispatch → permission/safety gate → model/API or local tool execution → message/state update → UI render.
- Around that core sit extensibility boundaries (plugins, skills, MCP), collaboration boundaries (agents/tasks/swarm/remote), and operational boundaries (storage, telemetry, auth, updates).
Main entry points: useMainLoopModel.ts Hooks layer · toolOrchestration.ts Tool executor · App.tsx App shell · QueryEngine.ts Query engine
Components 30
Runtime
CLI startup, entrypoints, and terminal engine
- Main entry · Process startup and app wiring
restored-src/src/main.tsx - CLI entry · CLI process initialization and dispatch
restored-src/src/entrypoints/cli.tsx - Init entry · One-time initialization path
restored-src/src/entrypoints/init.ts - Ink runtime · Custom terminal rendering, events, layout, and screen output
restored-src/src/ink/ink.tsx
Terminal UI
React-style screen composition and interactive panels
- App shell · Top-level app composition and screen orchestration
restored-src/src/components/App.tsx - Prompt input · User command entry, shortcuts, and queued actions
restored-src/src/components/PromptInput/PromptInput.tsx - Message feed · Session transcript, tool results, and assistant/user messages
restored-src/src/components/Messages.tsx - Permissions UI · Approval dialogs and safety prompts
restored-src/src/components/permissions/PermissionDialog.tsx - Status panels · Status line, overlays, settings, and notifications
restored-src/src/components/StatusLine.tsx
Core Loop
Session state, message routing, commands, and hooks
- App state · Mutable session model and selectors
restored-src/src/state/AppState.tsx - Contexts · React contexts for overlays, mailbox, notifications, voice, and prompts
restored-src/src/context.ts - History · Conversation history and session replay state
restored-src/src/history.ts - Command router · Routes text, slash commands, and shell/tool actions
restored-src/src/utils/processUserInput/processUserInput.ts - Hooks layer · Session lifecycle, input, notifications, and integration hooks
restored-src/src/hooks/useMainLoopModel.ts
Model Boundary
API access, token budgeting, limits, and query orchestration
- Query engine · Prompt construction, budgeting, and execution coordination
restored-src/src/QueryEngine.ts - API client · Outbound Anthropic/backend requests, retry, and error normalization
restored-src/src/services/api/claude.ts - Limits & budget · Rate limits, usage, token budgets, and model constraints
restored-src/src/services/claudeAiLimits.ts
Tooling
Tool execution, permissions, and task orchestration
- Tool executor · Streaming execution, orchestration, and lifecycle tracking
restored-src/src/services/tools/toolOrchestration.ts - Tool catalog · Concrete tool implementations for shell, files, web, tasks, agents, and MCP
restored-src/src/tools.ts - Permission engine · Permission modes, rule evaluation, sandboxing, and command validation
restored-src/src/utils/permissions/permissions.ts - Task system · Local, remote, and teammate tasks plus progress reporting
restored-src/src/tasks.ts
Integrations
Remote control, IDE/LSP, MCP, plugins, and voice
- Agent system · Agent spawning, built-in agents, memory, and resume flow
restored-src/src/tools/AgentTool/AgentTool.tsx - MCP boundary · Model Context Protocol servers, approvals, and tool exposure
restored-src/src/services/mcp/MCPConnectionManager.tsx - Plugin system · Plugin loading, commands, hooks, output styles, and marketplace integration
restored-src/src/plugins/builtinPlugins.ts - IDE & LSP · Editor, IDE, and language-server integration
restored-src/src/services/lsp/LSPServerManager.ts - Remote bridge · Remote sessions, websocket/SSE transport, and direct-connect ingress
restored-src/src/bridge/bridgeMain.ts
Persistence
Session memory, local storage, and recovery
- Session memory · Memory files, summaries, and recovery artifacts
restored-src/src/services/SessionMemory/sessionMemory.ts - Memdir · Filesystem-backed memory discovery and team memory paths
restored-src/src/memdir/memdir.ts - Session storage · Session persistence, portable storage, and recovery helpers
restored-src/src/utils/sessionStorage.ts
Operations
Telemetry, analytics, updates, and diagnostics
- Telemetry · Analytics, tracing, logging, and experiment sinks
restored-src/src/services/analytics/index.ts
Connections 31
- Main entry → CLI entry: starts · CLI startup hands off to the main command entrypoint
- Main entry → Init entry: initializes · Runs startup initialization before interactive work
- CLI entry → Ink runtime: mounts · Creates the terminal UI runtime
- Ink runtime → App shell: renders · Hosts the application root component
- App shell → Prompt input: includes · Provides the user input surface
- App shell → Message feed: includes · Displays conversation and tool messages
- App shell → Permissions UI: includes · Surfaces approvals and safety prompts
- App shell → Status panels: includes · Shows status, notifications, and settings
- Prompt input → Command router: submits · User input is classified into action types
- Command router → Hooks layer: dispatches · Actions enter the reactive session loop
- Hooks layer → App state: updates · Hooks mutate session/application state
- Hooks layer → History: records · Conversation turns are appended to history
- Hooks layer → Query engine: requests · Model turns are scheduled through the query layer
- Query engine → API client: calls · Executes Claude/backend requests
- Query engine → Limits & budget: checks · Applies model, usage, and token constraints
- Query engine → Tool executor: invokes · Model tool calls are routed into execution
- Tool executor → Tool catalog: executes · Dispatches concrete tool implementations
- Tool executor → Permission engine: gates · Tool activity is filtered through safety policy
- Permission engine → Permissions UI: prompts · Approval decisions are surfaced to the user
- Tool executor → Task system: spawns · Background and delegated work is tracked as tasks
- Tool executor → Agent system: fans out · Agent tool use creates subordinate execution units
- Tool executor → MCP boundary: bridges · MCP tools and servers are mediated through the extension boundary
- Tool executor → Message feed: feeds · Tool results are converted back into conversation messages
- Hooks layer → Plugin system: loads · Plugins contribute commands, tools, hooks, and styles
- Hooks layer → IDE & LSP: syncs · IDE and LSP state is observed through hooks
- Hooks layer → Remote bridge: connects · Remote session and bridge state is wired into the loop
- Hooks layer → Session memory: persists · Session summaries and memory artifacts are stored
- Session memory → Memdir: writes · Memory files live in the local memory directory
- Hooks layer → Session storage: saves · Session recovery and local state are persisted
- App state → Telemetry: emits · Operational events and traces are produced from state changes
- Query engine → Telemetry: logs · Model and request activity is observed