How dhrbc/claude-code works
1. Overall shape
- This repo is a terminal-first agentic CLI built in TypeScript on Bun, with a React + Ink UI layer for rendering in the terminal.
- The main architectural pattern is: user input → command/tool dispatch → query engine / service layer → streamed output back to the terminal, with many side systems attached for permissions, sessions, plugins, remote control, and background tasks.
2. Startup and runtime entrypoints
- src/main.tsx, src/entrypoints/*, and src/setup.ts are the startup boundary.
- Bootstrapping initializes config, settings, analytics/feature flags, keychain/credential access, and terminal/UI state before the interactive session begins.
- src/bootstrap/* and src/state/* hold early app state and cross-cutting state management that the rest of the app reads from.
3. Interactive shell UI
- src/ink/ is a custom Ink/terminal rendering layer rather than a thin wrapper; it owns terminal layout, input events, focus, selection, screen rendering, and terminal-specific primitives.
- src/components/ contains most UI building blocks: prompt input, message timeline, dialogs, task panels, permission dialogs, settings, onboarding, and status indicators.
- src/screens/ provides full-screen flows such as Doctor, REPL, and Resume conversation.
4. Core conversation and LLM orchestration
- src/QueryEngine.ts, src/query/, src/utils/query*, and src/constants/* form the central agent loop.
- This layer is responsible for sending prompts to the model, streaming responses, handling retries, managing context budgets, and orchestrating tool calls.
- src/context.ts, src/history.ts, src/assistant/sessionHistory.ts, and src/cost-tracker.ts feed the engine with conversation state, prior turns, and usage accounting.
5. Tool execution boundary
- src/tools/ defines each actionable capability as an isolated tool module: shell execution, file read/write/edit, search, web fetch/search, notebook edits, MCP, LSP, tasks, team messaging, plan/worktree toggles, cron, and remote triggers.
- src/Tool.ts and src/tools.ts define the tool type system and registry.
- Tool execution is mediated by src/services/tools/* and src/utils/tool*, which handle streaming execution, orchestration, result storage, schema caching, and collapsing/formatting outputs for the UI.
6. Permission and safety boundary
- Tool calls do not execute directly; they pass through src/hooks/toolPermission/* and src/components/permissions/*.
- This layer decides whether a request is auto-approved, denied, or surfaced to the user based on permission mode, workspace rules, sandbox state, and tool-specific safety checks.
- Shell-related tools have extra guardrails in src/tools/BashTool/*, src/tools/PowerShellTool/*, and src/utils/permissions/* for destructive commands, path validation, and read-only enforcement.
7. Commands vs tools
- src/commands/ is the user-facing slash-command subsystem; these commands configure the app, manage sessions, inspect state, and launch specialized workflows.
- src/commands.ts acts as the registry/dispatch layer for command discovery.
- In diagram terms: commands are control-plane actions, while tools are data-plane actions that the model can invoke during a conversation.
8. External service integrations
- src/services/api/* is the Anthropic API/client boundary and includes bootstrap, usage, file APIs, session ingress, retries, and error handling.
- src/services/oauth/* handles authentication flows and token management.
- src/services/analytics/* provides telemetry and feature-flag infrastructure, while src/services/notifier.ts and related utilities feed user-facing status/notification paths.
- src/services/lsp/*, src/services/mcp/*, and src/services/plugins/* are the primary integration surfaces with external developer tooling ecosystems.
9. Bridge and remote-control subsystem
- src/bridge/ is a dedicated bidirectional bridge between the CLI and IDE/remote environments.
- It includes session creation, bridge messaging, permission callbacks, JWT/auth utilities, remote bridge transport, and REPL bridge handling.
- This is a distinct boundary from normal local CLI execution: it enables the app to be controlled or observed by IDE extensions, remote sessions, or connected runtimes.
10. Tasks, agents, and multi-worker orchestration
- src/tasks/, src/task.ts, src/tasks.ts, and src/components/tasks/* model background work, shell tasks, remote tasks, and in-process teammate/agent tasks.
- src/coordinator/, src/tools/AgentTool/*, and src/utils/swarm/* support multi-agent coordination and team-style parallel work.
- src/utils/task/*, src/utils/concurrentSessions.ts, and related helpers handle task lifecycle, output formatting, and task visibility in the UI.
11. Plugins, skills, and extensibility
- src/plugins/, src/services/plugins/*, and src/utils/plugins/* implement a plugin platform for loading commands, tools, hooks, output styles, and marketplace content.
- src/skills/ and src/tools/SkillTool/* provide reusable workflows that can be bundled or loaded from disk.
- src/utils/hooks/* and src/schemas/hooks.ts suggest a hook system that lets plugins and skills participate in lifecycle events, prompt processing, and post-processing.
12. Persistence, memory, and session recovery
- src/memdir/, src/services/SessionMemory/*, src/services/teamMemorySync/*, src/utils/session*, and src/utils/filePersistence/* manage long-lived memory, session artifacts, and resumable state.
- src/commands/resume, src/commands/clear, src/commands/rename, and src/commands/export expose user control over that persisted state.
- The important architectural boundary is between ephemeral turn state in the active session and persistent memory/session stores used across launches.
13. Platform-specific and terminal-adjacent subsystems
- src/keybindings/, src/vim/, src/voice/, src/buddy/, and src/components/PromptInput/* add interaction modes and input processing around the core CLI.
- src/upstreamproxy/, src/server/, src/remote/, and src/utils/deepLink/* support networking, remote sessions, and environment handoff.
- src/native-ts/ contains lower-level utilities that back some performance-sensitive functionality such as layout or file indexing.
14. How to draw the main flow
- A good diagram centers on the path: terminal input/UI → command or prompt processing → query engine → tool/permission layer → external services and filesystem/shell → streamed results back to UI.
- Around that core, show side bands for bridge/remote control, tasks/agents, plugins/skills/hooks, and persistent memory/session state.
- The main trust boundaries are: user vs automated tool execution, local CLI vs remote/IDE bridge, and application state vs external services.
Main entry points: QueryEngine.ts Query Engine · toolOrchestration.ts Tool Exec · App.tsx App Shell · setup.ts Setup
Components 30
Runtime
Startup, CLI entrypoints, app state, and shell loop
Terminal UI
Ink renderer, screens, and interactive components
- Ink Runtime · Custom terminal rendering and event system
src/ink/ink.tsx - App Shell · Top-level terminal UI composition
src/components/App.tsx - Prompt Input · User text, modes, and queued commands
src/components/PromptInput/PromptInput.tsx - Messages · Conversation transcript and message rendering
src/components/Messages.tsx
Agent Core
Conversation loop, context, history, and command processing
- Query Engine · Central prompt-to-response orchestration
src/QueryEngine.ts - Input Router · Routes slash commands, bash input, and text prompts
src/utils/processUserInput/processUserInput.ts - Commands · Slash-command registry and dispatch
src/commands.ts - Context · Active context, turn state, and budgets
src/context.ts
Tools
Tool registry, execution, and representative tool implementations
- Tools · Tool definitions and registry
src/tools.ts - Tool Types · Shared tool type system
src/Tool.ts - Tool Exec · Streaming tool execution and result handling
src/services/tools/toolOrchestration.ts - Bash Tool · Shell execution with validation and guardrails
src/tools/BashTool/BashTool.tsx - File Tool · Read/write/edit file actions
src/tools/FileReadTool/FileReadTool.ts
Integrations
External APIs and developer-tool bridges
- Anthropic API · Model API client and retries
src/services/api/client.ts - OAuth · Token and login flow handling
src/services/oauth/client.ts - LSP · Language server management and diagnostics
src/services/lsp/manager.ts - MCP · Model Context Protocol connections and transport
src/services/mcp/MCPConnectionManager.tsx - Bridge · IDE and remote control bridge boundary
src/bridge/bridgeMain.ts
Extensibility
Plugins, skills, hooks, and custom workflows
Persistence
Sessions, memory, and long-lived artifacts
- History · Conversation history and resume data
src/history.ts - Session Memory · Session memory prompts and storage
src/services/SessionMemory/sessionMemory.ts - Memdir · On-disk memory and session artifacts
src/memdir/memdir.ts
Execution
Tasks, background work, and remote/session orchestration
- Remote Sessions · Remote session lifecycle and transport
src/remote/RemoteSessionManager.ts - Tasks · Task model and task lifecycle
src/tasks.ts - Shell Task · Local shell task execution and output
src/tasks/LocalShellTask/LocalShellTask.tsx
Connections 34
- Main → Setup: bootstraps · Startup initialization begins here
- Setup → CLI Entry: launches · Prepares the CLI entrypoint
- Setup → App State: initializes · Builds shared app state
- CLI Entry → Ink Runtime: starts UI · Hands control to terminal rendering
- Ink Runtime → App Shell: renders · Root UI composition
- App Shell → Prompt Input: captures input · Primary user interaction path
- App Shell → Messages: shows transcript · Conversation and tool output display
- Prompt Input → Input Router: submits · Routes user input into the app pipeline
- Input Router → Commands: slash commands · Control-plane command dispatch
- Input Router → Query Engine: prompt text · Conversation input goes to the agent loop
- Commands → App State: updates state · Commands mutate session and app settings
- Query Engine → Context: reads context · Uses active conversation context
- Query Engine → History: reads history · Uses prior turns and resume state
- Query Engine → Tools: selects tools · Requests capabilities from the registry
- Query Engine → Anthropic API: calls model · Sends prompts and streams responses
- Tools → Tool Types: typed by · Tools share a common schema
- Tools → Tool Exec: executes via · Tool calls are mediated by the execution layer
- Tool Exec → Bash Tool: runs shell · Representative high-risk tool path
- Tool Exec → File Tool: reads files · Representative filesystem tool path
- Bash Tool → Tool Exec: returns result · Tool outputs stream back through orchestration
- File Tool → Tool Exec: returns result · Tool outputs stream back through orchestration
- Tool Exec → Messages: streams output · Tool progress and results are rendered in the transcript
- Tool Exec → Session Memory: persists artifacts · Selected results and session artifacts may be stored
- Session Memory → Memdir: writes disk · Persistent memory lives on disk
- Query Engine → LSP: consults · Language tooling and diagnostics support
- Query Engine → MCP: uses tooling · External developer-tool integrations
- Query Engine → Plugins: extends · Commands, tools, hooks, and UI can be plugin-backed
- Query Engine → Skills: loads skills · Reusable workflows can be injected into the loop
- Bridge → Remote Sessions: bridges · Separate remote/IDE control boundary
- Bridge → App State: syncs state · Bridge mirrors or mutates app session state
- Remote Sessions → Tasks: spawns · Remote sessions produce task-like work units
- Tasks → Shell Task: includes · Local shell execution is a core task kind
- Tasks → App Shell: surfaces status · Task lifecycle is shown in the terminal UI
- OAuth → Anthropic API: authenticates · API access depends on token management