How zhx178/claude-code works
1. Overall shape
- This is a Bun + TypeScript CLI application with a React/Ink terminal UI.
- It behaves like an agentic developer workstation: user input enters a command/UI layer, then flows through a query engine, tools, permissions, and service integrations.
2. Startup and boot path
- src/main.tsx, src/entrypoints/cli.tsx, and related entrypoints initialize the app.
- Bootstrapping includes config/state loading, environment detection, and early prefetch/initialization work before the main UI loop starts.
- src/bootstrap/, src/setup.ts, and src/state/ provide the early app state and startup wiring.
3. Primary execution loop
- src/QueryEngine.ts is the central orchestrator for model interactions.
- It handles streaming model responses, tool-call loops, retries, thinking/response state, and token/context accounting.
- The QueryEngine is the main bridge between user prompts and downstream tool execution.
4. User-facing command surface
- src/commands/ contains the slash-command system; src/commands.ts is the registry/router.
- These commands cover session control, config, auth, review, compacting context, memory, tasks, plugins, remote/desktop handoff, and diagnostics.
- Many commands are UI-driven React screens under src/commands/<name>/ or src/screens/.
5. Tool execution layer
- src/tools/ is the core agent capability layer: bash, file read/write/edit, grep/glob, web fetch/search, MCP, LSP, notebook edits, agent spawning, tasks, message passing, scheduling, and remote triggers.
- src/Tool.ts and src/tools.ts define the shared tool abstractions and registry.
- Tools are not just helpers; they are the main action endpoints the model can invoke.
6. Permission and safety boundary
- src/hooks/toolPermission/ and src/components/permissions/ implement the approval boundary around dangerous or sensitive tool actions.
- Permission mode logic, rule evaluation, and user prompts decide whether a tool call proceeds, is denied, or is auto-approved.
- Shell and file tools have additional safety layers in src/tools/BashTool/, src/tools/PowerShellTool/, and related utility modules.
7. Terminal UI and interaction model
- The UI is built from src/components/ and rendered through the custom Ink wrapper in src/ink/.
- src/components/App.tsx, prompt input components, message renderers, dialogs, and status widgets make up the conversational terminal experience.
- State changes flow through React hooks and context providers in src/context/, src/hooks/, and src/state/.
8. External integrations and service layer
- src/services/ contains the non-UI integration layer: Anthropic API client, OAuth, analytics, LSP, MCP connections, plugin installation, token estimation, memory extraction, compaction, and policy/limits handling.
- src/services/api/ is the model/backend API boundary.
- src/services/mcp/ and src/services/lsp/ connect the agent to external developer tooling protocols.
- src/services/analytics/ and src/services/oauth/ are important operational boundaries for telemetry and authentication.
9. Bridge and remote-control subsystem
- src/bridge/ implements bidirectional communication with IDEs and remote sessions, including messaging, session management, permissions, and transport handling.
- src/remote/, src/server/, and src/utils/teleport/ support remote session management and handoff flows.
- This subsystem is a distinct boundary from local CLI interaction: it synchronizes state, permissions, and session events across processes/devices.
10. Multi-agent, task, and swarm architecture
- src/coordinator/, src/tasks/, src/tools/AgentTool/, and src/utils/swarm/ support concurrent agent/task execution.
- There are separate task types for local shell, local agent, remote agent, and in-process teammate workflows.
- The architecture supports spawning sub-agents, routing messages, and coordinating team-style work, not just single-threaded chat.
11. Persistence and local memory
- src/memdir/, src/utils/memory/, src/services/SessionMemory/, and src/services/teamMemorySync/ handle durable memory and session knowledge.
- src/history.ts, src/assistant/sessionHistory.ts, and session storage utilities support resume/restore behavior.
- This is a local-first state layer with sync paths for team/shared memory where enabled.
12. Plugins, skills, and extensibility
- src/plugins/, src/services/plugins/, src/skills/, and src/tools/SkillTool/ form the extensibility model.
- Plugins can add commands, tools, hooks, output styles, and model behavior.
- Skills are packaged workflows/prompt assets that can be loaded from built-ins or user-managed directories.
13. Configuration, settings, and migrations
- src/utils/settings/, src/constants/, src/schemas/, and src/migrations/ manage app configuration and schema evolution.
- Settings are a first-class subsystem because many runtime behaviors depend on policy, environment, and enterprise-managed configuration.
- Managed settings and remote sync are treated as separate input sources from local user preferences.
14. Observability and diagnostics
- src/services/analytics/, src/utils/telemetry/, src/services/internalLogging.ts, and src/utils/diagLogs.ts provide event logging, tracing, and diagnostics.
- src/commands/doctor/, src/screens/Doctor.tsx, and related components expose environment checks and troubleshooting flows.
- This layer is important because the app is highly stateful and integrates with shell, IDE, network, and permissions.
15. Useful diagram boundaries
- For an architecture diagram, the most important boxes are:
- CLI/Ink UI
- Command registry
- QueryEngine/model loop
- Tool subsystem
- Permission/safety gate
- Services/integrations
- Bridge/remote control
- Persistence/memory/session state
- Plugins/skills/extensibility
- The main arrows are: user input → command/UI layer → QueryEngine → tool/service calls → permission checks → model/tool results → UI/state updates, with side channels for remote bridge, telemetry, and persistence.
Main entry points: QueryEngine.ts Query engine · tools.ts Tool registry · App.tsx Terminal app · PermissionContext.ts Permission gate
Components 24
CLI + UI
Startup, terminal rendering, and the conversational interface.
- CLI entry · Bootstraps the Bun/TypeScript application and starts the terminal app.
src/main.tsx - CLI init · CLI entrypoint wiring and startup handoff.
src/entrypoints/cli.tsx - Terminal app · Top-level Ink/React application shell and conversational UI composition.
src/components/App.tsx - Bootstrap · Early initialization, prefetch, and environment setup.
src/bootstrap/state.ts - Input router · Routes text prompts, slash commands, and bash-like user input into the runtime.
src/utils/processUserInput/processUserInput.ts
Agent runtime
Main prompt loop, task execution, tools, and permissions.
- Query engine · Central model loop that streams responses, manages tool calls, retries, and token accounting.
src/QueryEngine.ts - Tool registry · Shared tool abstractions and registry used by the model to act on the world.
src/tools.ts - Shell tools · Bash and PowerShell execution with safety, path, and command validation.
src/tools/BashTool/BashTool.tsx - File tools · Read, write, edit, grep, glob, and notebook/file manipulation tools.
src/tools/FileEditTool/FileEditTool.ts - Agent tools · Sub-agent spawning, task creation, messaging, and teammate workflows.
src/tools/AgentTool/AgentTool.tsx - Permission gate · Approval boundary for dangerous or sensitive tool calls.
src/hooks/toolPermission/PermissionContext.ts - Tasks · Task abstractions for local shell, local agent, remote agent, and teammates.
src/tasks.ts
Integrations
Model API, MCP/LSP, OAuth, analytics, and plugin services.
- Model API · Backend/model API boundary and request orchestration.
src/services/api/client.ts - MCP + LSP · External developer-tool protocol connections and server management.
src/services/mcp/MCPConnectionManager.tsx - Telemetry · Analytics, logging, diagnostics, and usage/event reporting.
src/services/analytics/index.ts
Remote + bridge
Cross-process session control and remote handoff.
- Bridge layer · Bidirectional bridge for IDEs, remote sessions, and permission/session sync.
src/bridge/bridgeMain.ts - Remote sessions · Remote session manager and handoff/control path.
src/remote/RemoteSessionManager.ts
State + memory
Session storage, memory, history, and durable app state.
- App state · Central state store and React state plumbing.
src/state/store.ts - Memory store · Session history, memory directories, and durable conversation state.
src/memdir/memdir.ts
Extensibility
Commands, plugins, and skills.
- Command router · Slash-command registry and dispatch layer for user-facing commands.
src/commands.ts - Command screens · Representative command UIs for session control, config, review, resume, diagnostics, and plugins.
src/commands/config/config.tsx - Plugins · Plugin loading, installation, and lifecycle management.
src/plugins/builtinPlugins.ts - Skills · Bundled and loadable skills used to extend agent behavior.
src/skills/bundledSkills.ts
Platform
Shared runtime helpers, Ink renderer, and low-level utilities.
- Ink runtime · Custom Ink renderer, terminal events, and layout system.
src/ink/ink.tsx
Connections 31
- CLI entry → CLI init: starts · Main entry hands off to CLI initialization.
- CLI init → Bootstrap: bootstraps · CLI init loads startup state and environment.
- Bootstrap → App state: hydrates · Startup populates the app state store.
- CLI init → Terminal app: mounts · Starts the terminal UI shell.
- Terminal app → Ink runtime: renders on · UI is rendered through the custom Ink runtime.
- Terminal app → Input router: accepts input · User input is normalized before routing.
- Input router → Command router: slash commands · Slash commands are dispatched through the command registry.
- Input router → Query engine: prompts · Plain prompts flow into the query engine.
- Command router → Command screens: opens · Commands surface dedicated UI screens and dialogs.
- Command router → App state: updates · Command actions mutate app/session state.
- Query engine → Model API: calls model · Query engine streams requests to the model/API layer.
- Query engine → Tool registry: invokes tools · Model responses can trigger registered tools.
- Tool registry → Shell tools: includes · Shell execution is a core tool family.
- Tool registry → File tools: includes · Filesystem and edit tools are core capabilities.
- Tool registry → Agent tools: includes · Agent/task spawning tools are part of the action layer.
- Query engine → Permission gate: checks · Sensitive tool calls pass through the permission gate.
- Permission gate → Shell tools: guards · Shell and destructive operations require approval.
- Permission gate → File tools: guards · File edits and writes are mediated by permissions.
- Query engine → Tasks: spawns · The main loop can create and coordinate background tasks.
- Tasks → App state: reports · Task progress and results feed back into state/UI.
- Query engine → Memory store: reads/writes · Conversation history and durable memory influence prompts.
- Terminal app → Telemetry: logs · UI and runtime events are emitted for telemetry and diagnostics.
- Model API → Telemetry: reports · API activity contributes to analytics and logging.
- Model API → MCP + LSP: extends · Service layer connects to MCP and LSP integrations.
- Bridge layer → Remote sessions: manages · Bridge layer coordinates remote sessions and handoff.
- Bridge layer → App state: syncs · Remote events synchronize with local app state.
- Bridge layer → Permission gate: shares approvals · Remote control needs the same permission boundary.
- Plugins → Command router: adds commands · Plugins can contribute command surface.
- Plugins → Tool registry: adds tools · Plugins can register tools and hooks.
- Plugins → Skills: loads skills · Skill assets are part of the extensibility model.
- Skills → Query engine: guides · Loaded skills shape model behavior and prompts.