How alesha-pro/claude-code works
1. Overall shape
- This is a Bun + TypeScript CLI application built around a terminal React UI (Ink). The architecture centers on an interactive session loop that takes user input, routes it through a command/tool system, talks to Anthropic’s API, and renders updates back into the terminal.
2. Startup and bootstrap
- src/main.tsx, src/entrypoints/, src/setup.ts, and src/bootstrap/ form the launch path.
- Startup does more than parse CLI args: it preloads settings, auth, feature flags, and environment state so the interactive session can begin quickly.
- src/screens/ contains top-level modes like REPL, doctor, and resume-conversation screens.
3. Core conversation engine
- src/QueryEngine.ts is the central orchestration layer for model interactions.
- It handles streaming responses, tool-call loops, retries, token accounting, and conversation state transitions.
- Supporting modules in src/query/, src/context.ts, src/history.ts, and src/cost-tracker.ts feed the engine prompt context, budgets, and prior turns.
4. Command layer
- src/commands.ts and src/commands/** implement slash commands such as /commit, /compact, /mcp, /config, /resume, /tasks, and /memory.
- Commands are a user-facing control plane for session management, environment inspection, and workflow shortcuts.
- They usually mutate app state, open dialogs, or trigger services rather than directly performing model inference.
5. Tool execution layer
- src/tools.ts and src/tools/** define the agent’s action surface: shell, file read/write/edit, search, web fetch/search, MCP, LSP, agent spawning, task ops, plan/worktree toggles, and remote triggers.
- Tools are strongly typed and each has its own permission model, UI, and execution logic.
- Tool calls are the main data path from model output to real-world side effects.
6. Permission and policy boundary
- src/hooks/toolPermission/, src/components/permissions/, and src/utils/permissions/ enforce the security boundary around tool usage.
- Every potentially dangerous tool invocation passes through permission checks, policy rules, and sometimes classifier-based decisions.
- The UI layer can prompt the user, while noninteractive modes and auto modes resolve permissions through configured policy.
7. Terminal UI, state, and interaction
- The main user experience lives in src/components/, src/state/, src/context/, src/hooks/, and the custom src/ink/ renderer wrapper.
- Ink/React components render the prompt, message stream, diffs, dialogs, status lines, and task panels.
- Global state and contexts coordinate the live session, notifications, overlays, queued messages, and terminal behaviors.
8. External service integrations
- src/services/ contains the outbound integrations: Anthropic API client, OAuth, analytics, telemetry, rate limits, policy limits, and remote settings.
- This layer is the boundary to cloud services and persists or fetches data needed for auth, usage tracking, feature rollout, and organization policy.
- It also includes compacting, memory extraction, and token estimation services that shape what gets sent to the model.
9. IDE and bridge subsystem
- src/bridge/ implements bidirectional communication with external editors, especially VS Code and JetBrains.
- The bridge handles messaging, permissions callbacks, session creation, REPL bridging, JWT auth, and status reporting.
- Architecturally, this is a separate control plane that lets the CLI session be driven or mirrored from an IDE environment.
10. Remote, server, and transport paths
- src/remote/, src/server/, src/upstreamproxy/, and src/cli/transports/ handle non-local session flows.
- These modules support remote sessions, websocket/SSE/WebSocket-like transport abstraction, direct-connect sessions, and proxying to upstream services.
- They form the boundary for background or distributed execution rather than the local interactive terminal loop.
11. Multi-agent, tasks, and coordination
- src/coordinator/, src/tasks/, src/tools/AgentTool/, and src/tools/Task* implement parallel or delegated work.
- Agents can spawn sub-agents, create/update/list tasks, send messages, and operate in coordinated or swarm-like modes.
- The task subsystem provides a durable view of background work separate from the main chat transcript.
12. Memory, compacting, and long-running context
- src/memdir/, src/services/compact/, src/services/SessionMemory/, and src/services/extractMemories/ manage persistence and context reduction.
- These subsystems preserve useful facts across sessions, extract memories from turns, and compress long conversations when token pressure rises.
- This is a key data-flow boundary: raw interaction history is distilled into smaller, persistent artifacts.
13. Plugins, skills, MCP, and extensibility
- src/plugins/, src/skills/, src/services/mcp/, src/components/mcp/, and the MCP-related tools expose extension points.
- Plugins contribute commands, tools, output styles, and startup checks; skills package reusable workflows; MCP connects to external tool servers.
- This is the main extensibility layer for adding capabilities without changing the core app.
14. Supporting subsystems
- src/keybindings/, src/vim/, src/voice/, src/buddy/, src/outputStyles/, src/migrations/, and src/schemas/ are auxiliary but important.
- They handle input modalities, visual mode, voice features, easter-egg UI, migration of persisted settings, and schema validation.
- src/utils/ is the shared foundation: shell parsing, filesystem helpers, auth, git, telemetry, terminal ops, and many protocol adapters.
15. Primary architectural flow
- The typical flow is: user input → command or prompt processing → permission/policy evaluation → query engine / tool execution → external service or local side effect → UI update + history/state persistence.
- Most subsystems exist to support one of those transitions: collecting context, enforcing safety, rendering state, or bridging to external systems.
Main entry points: QueryEngine.ts QueryEngine · services services · tools.ts tools · components components
Components 29
Boot & entry
Startup paths, modes, and initialization.
- main · Bun/TypeScript CLI bootstrap.
src/main.tsx - entrypoints · CLI and SDK entrypaths.
src/entrypoints - setup · Preloads settings, auth, and environment state.
src/setup.ts - screens · Top-level screens like REPL, doctor, resume.
src/screens
Session core
Conversation orchestration and stateful session data.
- QueryEngine · Streaming model loop, retries, token accounting, tool-call cycles.
src/QueryEngine.ts - query ctx · Prompt context, config, stop hooks, and token budget.
src/query - context · Shared conversation and runtime context.
src/context.ts
Terminal UI
Ink/React rendering, state, and interaction.
- App state · Central UI/session state store and selectors.
src/state - components · React/Ink views for prompts, messages, dialogs, and panels.
src/components - ink · Custom Ink renderer and terminal primitives.
src/ink - hooks · Interaction, polling, and integration hooks.
src/hooks
Tools & commands
User commands and agent tool execution surface.
- commands · Slash command registry and command implementations.
src/commands.ts - tools · Tool registry and typed action surface.
src/tools.ts - tool impls · Shell, file, search, MCP, LSP, task, and agent tools.
src/tools
Policy & permissions
Security checks, tool approval, and policy enforcement.
- permission hooks · Permission request handling for risky tool calls.
src/hooks/toolPermission - permission UI · Dialogs and prompts for user approvals.
src/components/permissions - permission utils · Policy rules, classifiers, and permission mode logic.
src/utils/permissions
Services
External integrations and long-running background services.
- services · Cloud API, analytics, telemetry, limits, and background services.
src/services
Extensibility
Plugins, skills, and MCP-based extension points.
Remote & bridge
IDE, remote, server, and transport control planes.
- bridge · IDE-facing bidirectional bridge and session control.
src/bridge - remote · Remote session manager and session transports.
src/remote - server · Direct-connect session server and manager.
src/server - transports · SSE, WebSocket, and batch transport adapters.
src/cli/transports
Persistence & memory
History, memory, compacting, and persistence layers.
- history · Conversation turn history and replay support.
src/history.ts - cost tracker · Tracks token and cost usage.
src/cost-tracker.ts - memdir · Persistent memory discovery and team memory paths.
src/memdir - compact · Compacting and session-memory reduction pipeline.
src/services/compact
Connections 31
- main → entrypoints: starts · Main dispatches into CLI entrypoints.
- entrypoints → setup: bootstraps · Startup loads configuration and environment state.
- setup → screens: selects mode · Bootstrap chooses the active screen or workflow.
- screens → QueryEngine: drives · Interactive screens hand off to the conversation engine.
- QueryEngine → query ctx: reads · Engine consumes prompt context and execution config.
- QueryEngine → history: appends · Turns and outcomes are persisted to history.
- QueryEngine → cost tracker: tracks · Token and usage accounting is updated during runs.
- QueryEngine → tools: invokes · Model tool calls are dispatched through the tool layer.
- commands → App state: mutates · Commands update session and UI state.
- commands → services: calls · Commands may trigger service workflows or remote actions.
- tools → tool impls: implements · Registry is backed by concrete tool modules.
- tool impls → permission hooks: checks · Potentially dangerous tools flow through permission hooks.
- permission hooks → permission UI: prompts · Interactive approval dialogs collect user decisions.
- permission hooks → permission utils: evaluates · Policy and classifier rules determine allowed usage.
- components → App state: renders · UI is driven by central state and selectors.
- components → hooks: uses · Components rely on app hooks for behavior and data.
- components → ink: built on · Terminal UI is rendered through Ink primitives.
- services → compact: runs · Background services include compacting and memory reduction.
- services → memdir: persists · Services read/write durable memory artifacts.
- services → MCP: integrates · Services coordinate MCP connections and server auth.
- plugins → tools: extends · Plugins can add tools and commands.
- plugins → commands: extends · Plugins contribute slash commands and UI flows.
- skills → tools: guides · Skills package reusable workflows exposed to the agent.
- bridge → services: auths via · Bridge sessions use service-backed auth and status.
- bridge → remote: connects · Bridge can route into remote session control flows.
- remote → server: spawns · Remote session handling includes direct-connect server paths.
- remote → transports: transports · Remote I/O uses SSE and WebSocket adapters.
- QueryEngine → services: requests · Model inference, telemetry, and limits depend on service clients.
- QueryEngine → compact: triggers · Long conversations can be compacted by the engine.
- QueryEngine → context: updates · Session context is mutated as the conversation evolves.
- history → memdir: informs · Historical turns feed durable memory discovery.