How rishabhk103/claude-code works
1. What this repo is
- This is a terminal-based AI agent client, not a generic library. The architecture centers on an interactive CLI that runs sessions, streams LLM output, executes tools, and renders everything in a React/Ink terminal UI.
2. Top-level runtime path
- The startup path begins in src/main.tsx and the CLI entrypoints under src/entrypoints/.
- Command parsing and app bootstrapping fan out into the UI, session state, config loading, auth, and service initialization.
- The app is built for Bun and TypeScript, with React + Ink for terminal rendering and Commander.js-style CLI parsing.
3. Core conversation engine
- src/QueryEngine.ts, src/context.ts, src/Task.ts, and src/Tool.ts are the core runtime abstractions.
- The QueryEngine is the central loop that sends prompts to Anthropic, handles streaming responses, processes tool calls, and advances the session.
- Tool.ts defines the contract for tools: input schema, permission behavior, execution state, and result shapes.
4. Tool execution layer
- src/tools/ contains the actual capabilities the model can invoke: shell, file read/write/edit, grep/glob, web fetch/search, MCP, LSP, notebook editing, sub-agents, tasks, cron, messaging, and remote triggers.
- This layer is one of the main architecture boundaries: model outputs are converted into structured tool invocations, then into user-visible messages and state updates.
- Tool implementations depend heavily on the utility layer for shell safety, filesystem access, parsing, and protocol adapters.
5. Permission and safety boundary
- Tool execution is gated by src/hooks/toolPermission/ and the broader permission utilities in src/utils/permissions/.
- This subsystem decides whether a tool call is allowed, denied, or requires interactive approval.
- It is tightly coupled to UI permission dialogs in src/components/permissions/ and to policy modes such as default, plan, auto, and bypass-style behaviors.
6. Command subsystem
- src/commands.ts and src/commands/ implement user-facing slash commands like config, doctor, compact, review, memory, tasks, mcp, diff, theme, resume, and others.
- Commands are not the same as tools: commands are user-initiated control surfaces for the CLI itself, while tools are model-invoked capabilities.
- Many commands are full-screen Ink flows and interact with the same state, settings, and services as the main session UI.
7. UI and interaction model
- src/components/, src/screens/, src/context/, src/hooks/, src/keybindings/, and src/vim/ form the interactive terminal experience.
- The UI is organized around message streams, prompt input, dialogs, status lines, permission prompts, task views, and settings panes.
- Keybindings and vim mode are separate interaction layers, so the terminal UX is highly stateful and input-mode driven.
8. Session, state, and history
- src/state/, src/history.ts, src/bootstrap/, src/assistant/, and src/tasks/ manage the lifecycle of a conversation/session.
- These modules hold current app state, persisted session history, queued messages, task objects, and restoration/resume logic.
- The app treats sessions as long-lived entities that can be compacted, resumed, branched, rewound, or handed off to another device or process.
9. Integrations and external services
- src/services/api/ wraps Anthropic API calls and related usage, file, bootstrap, and error flows.
- src/services/oauth/ and src/utils/secureStorage/ handle authentication and credential persistence.
- src/services/analytics/, src/services/policyLimits/, and related telemetry modules feed product analytics, limit enforcement, and feature-flag behavior.
- src/services/lsp/ and src/services/mcp/ connect the app to external code intelligence and tool servers.
10. Bridge and remote-control architecture
- src/bridge/, src/remote/, src/server/, and src/upstreamproxy/ provide cross-process and remote-session communication.
- The bridge layer exists specifically to connect the CLI with IDE integrations and external controllers.
- Remote session support appears to be a first-class subsystem, not an add-on: it includes session management, transport, permission bridging, and reconnect logic.
11. Extensibility via plugins and skills
- src/plugins/ and src/utils/plugins/ implement plugin discovery, loading, validation, marketplace integration, and lifecycle management.
- src/skills/ and src/tools/SkillTool/ provide reusable agent workflows that can be bundled with the product or loaded from disk.
- This creates two extensibility axes: plugins extend the application, while skills extend the agent’s behavior and prompting.
12. Memory, context, and compaction
- src/memdir/, src/services/SessionMemory/, src/services/compact/, src/services/extractMemories/, and src/utils/context*.ts manage long-running context.
- The system actively summarizes, extracts, and stores memories to fit within token limits and to preserve useful session state.
- Context management is therefore a core architectural concern, not just a utility.
13. Task and multi-agent orchestration
- src/tasks/, src/tools/AgentTool/, src/coordinator/, and related swarm utilities support background work, delegated subtasks, and multi-agent coordination.
- Tasks are represented as explicit runtime objects with UI views, status updates, and lifecycle controls.
- This subsystem sits between the main conversation loop and parallel execution environments.
14. Cross-cutting infrastructure
- src/utils/ is the large shared foundation: shell parsing/execution, filesystem helpers, git utilities, prompt handling, token estimation, sandbox support, telemetry helpers, and platform-specific logic.
- src/constants/, src/types/, src/schemas/, and src/migrations/ support stable configuration, validation, and backward compatibility.
- Overall, the repository is organized around a few strong boundaries: session orchestration, model/tool execution, interactive UI, external integrations, and persistence/state management.
Main entry points: QueryEngine.ts Query loop · toolExecution.ts Tool exec · App.tsx App shell · AppState.tsx App state
Components 31
Runtime
CLI bootstrap, session loop, state, and task orchestration
- CLI entry · Process startup and top-level entrypoints.
src/main.tsx - Query loop · Central conversation engine that streams model output and advances turns.
src/QueryEngine.ts - Session context · Conversation context, prompts, and runtime abstractions shared across turns.
src/context.ts - Task model · Core task abstraction used for background and delegated work.
src/Task.ts - App state · Persistent and in-memory session/app state plus resume history.
src/state/AppState.tsx - History · Session history and restoration support.
src/history.ts - Task views · Runtime task objects and UI-facing task lifecycle surfaces.
src/tasks.ts
Terminal UI
Ink/React screens, components, input, and interaction layers
- App shell · Root UI composition and overall terminal layout.
src/components/App.tsx - Prompt input · Prompt, command, and mode-aware terminal input handling.
src/components/PromptInput/PromptInput.tsx - Messages · Streamed assistant, user, tool, and system message rendering.
src/components/messages/AssistantTextMessage.tsx - Permission UI · Interactive approval flows for tool use and policy decisions.
src/components/permissions/PermissionDialog.tsx - Slash cmds · User-initiated CLI commands and full-screen command flows.
src/commands.ts - Keybindings · Shortcut parsing, binding resolution, and vim-style input modes.
src/keybindings/defaultBindings.ts
Tools
Model-invoked capabilities and their execution wrappers
- Tool contract · Common tool interface, permissions, and result shapes.
src/Tool.ts - Tool exec · Streaming tool execution and orchestration layer.
src/services/tools/toolExecution.ts - Shell tools · Bash and PowerShell execution with safety, sandbox, and read-only checks.
src/tools/BashTool/BashTool.tsx - File tools · Read, write, edit, glob, and grep capabilities.
src/tools/FileEditTool/FileEditTool.ts - Agent tools · Sub-agents, tasks, and agent workflow tools.
src/tools/AgentTool/AgentTool.tsx - MCP/Web tools · Model context protocol, web fetch/search, and remote resource access.
src/tools/MCPTool/MCPTool.ts
Policy
Permission checks, approvals, and safety gates
- Permission gate · Tool permission decision logic and approval routing.
src/hooks/toolPermission/PermissionContext.ts - Permission rules · Mode selection, rule matching, denials, and safety helpers.
src/utils/permissions/permissions.ts
Integrations
External services, remote control, plugins, and auth
- Bridge · Cross-process bridge for IDE and remote-session control.
src/bridge/bridgeMain.ts - Remote sessions · Remote session manager, websocket transport, and reconnect flows.
src/remote/RemoteSessionManager.ts - Plugins · Plugin discovery, loading, validation, and marketplace flows.
src/plugins/builtinPlugins.ts - Skills · Bundled and loaded skill workflows that extend agent behavior.
src/skills/bundledSkills.ts - API services · Anthropic client, usage, bootstrap, and error-handling wrappers.
src/services/api/claude.ts - Auth storage · OAuth flows and credential persistence.
src/services/oauth/client.ts - LSP/MCP svc · LSP management and MCP connection services.
src/services/lsp/LSPServerManager.ts
Shared Infra
Cross-cutting utilities, settings, persistence, and protocol helpers
Connections 36
- CLI entry → Query loop: boots · Startup initializes the core agent loop.
- CLI entry → App shell: mounts · CLI startup mounts the terminal application UI.
- CLI entry → Slash cmds: dispatches · Entry path routes user command invocations.
- Query loop → Session context: uses · The query loop reads and updates session context.
- Query loop → Tool contract: invokes · Model tool calls are validated against the tool contract.
- Query loop → Tool exec: executes · Structured tool calls are handed to the execution layer.
- Query loop → API services: calls · Conversation turns stream through the Anthropic API wrapper.
- Query loop → App state: updates · Each turn mutates app/session state.
- App state → History: persists · State and session history are stored for resume and rewind.
- App state → Task views: tracks · Tasks are reflected in the session state.
- App shell → Prompt input: contains · Main shell contains prompt and command input.
- App shell → Messages: renders · Conversation content is rendered as message streams.
- App shell → Permission UI: shows · UI surfaces approval dialogs and prompts.
- App shell → Keybindings: reads · Terminal interaction depends on keybinding state.
- Slash cmds → App state: controls · Commands operate on current session and app state.
- Slash cmds → Settings: reads · Command flows inspect and modify configuration.
- Tool contract → Permission gate: checks · Tool contract consults permission policy before execution.
- Permission gate → Permission rules: evaluates · Policy engine uses shared permission rules and helpers.
- Permission gate → Permission UI: prompts · Interactive approvals are surfaced through the UI.
- Tool exec → Shell tools: runs · Execution layer dispatches shell-capable tools.
- Tool exec → File tools: runs · Execution layer dispatches filesystem tools.
- Tool exec → Agent tools: runs · Execution layer dispatches delegated agent tools.
- Tool exec → MCP/Web tools: runs · Execution layer dispatches external/network tools.
- Tool exec → Permission gate: gated by · Tool execution is blocked or approved by permissions.
- Shell tools → Utilities: depends on · Shell tools rely on shared shell, git, and safety helpers.
- File tools → Utilities: depends on · File tools use filesystem, path, and diff utilities.
- Agent tools → Task model: spawns · Agent tools create and manage task-like work units.
- MCP/Web tools → LSP/MCP svc: connects · MCP and web-facing tools use external protocol services.
- Bridge → Remote sessions: feeds · Bridge layer connects to remote session control.
- Bridge → Permission UI: bridges · Remote actions still route through permission handling.
- Plugins → Settings: extends · Plugins integrate with configuration and startup settings.
- Skills → Agent tools: enhances · Skills influence agent behavior and delegated workflows.
- API services → Auth storage: auths via · API access relies on OAuth and secure credential storage.
- API services → Storage: persists · API and session-related data use persistence helpers.
- LSP/MCP svc → Plugins: loads via · LSP/MCP integrations are exposed through plugin and service layers.
- Utilities → Settings: supports · Shared utilities underpin configuration and validation.