resolver = "2", edition 2021, and version 1.0.0 across all member crates. Every crate lives under src-rust/crates/.
Dependency flow
cc-core is the shared foundation consumed by every other crate. claude-code (the binary) sits at the top and wires everything together.
Crates
cc-core — shared types, config, permissions, history
cc-core — shared types, config, permissions, history
cc-api — Claude API client and SSE streaming
cc-api — Claude API client and SSE streaming
Package:
Path:
Type: LibraryComplete async Messages API client with SSE streaming support. Corresponds to the TypeScript
cc-apiPath:
crates/apiType: LibraryComplete async Messages API client with SSE streaming support. Corresponds to the TypeScript
src/services/api/ layer.Key types
| Type | Module | Description |
|---|---|---|
AnthropicClient | client | Main API client — validates key, builds reqwest::Client with rustls-tls, sets anthropic-version and anthropic-beta headers |
ClientConfig | client | { api_key, api_base, timeout_secs, max_retries } |
CreateMessageRequest | types | Full request type — model, max_tokens, messages, system, tools, temperature, thinking, stream |
CreateMessageRequestBuilder | types | Fluent builder for CreateMessageRequest |
ThinkingConfig | types | { type: "enabled", budget_tokens: u32 } |
SystemPrompt | types | Text(String) or Blocks(Vec<SystemBlock>) for prompt caching |
CacheControl | types | { type: "ephemeral" } — applied automatically to the last tool definition |
ApiMessage | types | { role, content } — From<&Message> conversion included |
StreamEvent | streaming | Tagged enum — MessageStart, MessageDelta, MessageStop, ContentBlockStart, ContentBlockDelta, ContentBlockStop, Ping, Error |
ContentDelta | streaming | TextDelta, InputJsonDelta, ThinkingDelta, SignatureDelta |
StreamHandler | streaming | Trait called for each SSE event |
StreamAccumulator | streaming | Collects stream events into a complete (Message, UsageInfo, stop_reason) |
SseLineParser | sse_parser | Stateful line-by-line SSE parser |
Retry and backoff
send_with_retry retries on HTTP 429 and 529 with exponential backoff: initial delay 1 s, 2× multiplier, capped at 60 s, max 5 attempts. Honors the Retry-After response header.Prompt caching
CacheControl::ephemeral() is automatically applied to system prompt blocks (when using SystemPrompt::Blocks) and to the last tool definition in the tools list.Key dependencies
reqwest, reqwest-eventsource, tokio, serde, serde_json, base64, cc-corecc-tools — all 33 tool implementations
cc-tools — all 33 tool implementations
Package:
Path:
Type: LibraryImplements all 33 built-in tools. Each tool is a zero-sized struct implementing the
cc-toolsPath:
crates/toolsType: LibraryImplements all 33 built-in tools. Each tool is a zero-sized struct implementing the
Tool trait. JSON schemas are generated with schemars.Core trait and registry
| Symbol | Description |
|---|---|
Tool | Async trait — name, description, permission_level, input_schema, execute, to_definition |
ToolResult | { content, is_error, metadata } — ToolResult::success(content) / ToolResult::error(content) |
PermissionLevel | None | ReadOnly | Write | Execute | Dangerous |
ToolContext | Execution context — working dir, permission mode, permission handler, cost tracker, session ID, MCP manager, config |
all_tools() | Returns all 33 tools as Vec<Box<dyn Tool>> |
find_tool(name) | Finds a tool by exact name |
Implemented tools
| Tool struct | Name constant | Permission |
|---|---|---|
BashTool | Bash | Execute |
FileReadTool | Read | ReadOnly |
FileEditTool | Edit | Write |
FileWriteTool | Write | Write |
GlobTool | Glob | ReadOnly |
GrepTool | Grep | ReadOnly |
WebFetchTool | WebFetch | ReadOnly |
WebSearchTool | WebSearch | ReadOnly |
NotebookEditTool | NotebookEdit | Write |
TaskCreateTool | TaskCreate | None |
TaskGetTool | TaskGet | None |
TaskUpdateTool | TaskUpdate | None |
TaskListTool | TaskList | None |
TaskStopTool | TaskStop | None |
TaskOutputTool | TaskOutput | None |
CronCreateTool | CronCreate | None |
CronDeleteTool | CronDelete | None |
CronListTool | CronList | None |
TodoWriteTool | TodoWrite | None |
AskUserQuestionTool | AskUserQuestion | None |
EnterPlanModeTool | EnterPlanMode | None |
ExitPlanModeTool | ExitPlanMode | None |
PowerShellTool | PowerShell | Execute |
EnterWorktreeTool | EnterWorktree | Execute |
ExitWorktreeTool | ExitWorktree | Execute |
SendMessageTool | SendMessage | None |
SkillTool | Skill | None |
SleepTool | Sleep | None |
ToolSearchTool | ToolSearch | None |
BriefTool | Brief | None |
ConfigTool | Config | None |
ListMcpResourcesTool | ListMcpResources | None |
ReadMcpResourceTool | ReadMcpResource | None |
Global singletons
| Singleton | Type | Crate file |
|---|---|---|
TASK_STORE | Lazy<Arc<DashMap<String, Task>>> | tasks.rs |
INBOX | Lazy<DashMap<String, Vec<AgentMessage>>> | send_message.rs |
CRON_STORE | Lazy<Arc<RwLock<HashMap<String, CronTask>>>> | cron.rs |
WORKTREE_SESSION | Lazy<Arc<RwLock<Option<WorktreeSession>>>> | worktree.rs |
Key dependencies
schemars, tokio, regex, walkdir, glob, reqwest, serde_json, dashmap, cc-core, cc-mcpcc-query — agentic query loop
cc-query — agentic query loop
Package:
Path:
Type: LibraryThe core agentic query loop. Drives the multi-turn conversation with the API, executes tools, manages context compaction, and runs the background cron scheduler.
The sub-agent tool (
cc-queryPath:
crates/queryType: LibraryThe core agentic query loop. Drives the multi-turn conversation with the API, executes tools, manages context compaction, and runs the background cron scheduler.
Key types
| Type | Description |
|---|---|
QueryOutcome | EndTurn | MaxTokens | Cancelled | Error(ClaudeError) |
QueryConfig | Model, max tokens, max turns, system prompt, thinking budget, temperature |
QueryEvent | Stream(StreamEvent) | ToolStart | ToolEnd | TurnComplete | Status | Error |
AutoCompactState | Tracks compaction count, consecutive failures, and circuit-breaker disabled flag |
TokenWarningState | Ok | Warning | Critical |
Key functions
| Function | Description |
|---|---|
run_query_loop(...) | Main agentic loop — drives multi-turn conversation, executes tools, fires hooks, handles compaction |
run_single_query(...) | Single non-agentic API call, no tool loop |
auto_compact_if_needed(...) | Triggers context compaction when token use exceeds 90% of the context window |
compact_conversation(...) | Splits conversation into head + tail, summarizes head, returns compacted history |
start_cron_scheduler(...) | Spawns background task that fires due cron jobs as sub-queries |
AgentTool (agent_tool.rs)
The sub-agent tool (Task) lives in this crate rather than cc-tools because it must call run_query_loop recursively. It always excludes itself from the child tool list to prevent infinite recursion.Auto-compact constants
| Constant | Value |
|---|---|
AUTOCOMPACT_TRIGGER_FRACTION | 0.90 |
AUTOCOMPACT_BUFFER_TOKENS | 13_000 |
WARNING_THRESHOLD_BUFFER_TOKENS | 20_000 |
KEEP_RECENT_MESSAGES | 10 |
MAX_CONSECUTIVE_FAILURES | 3 |
Key dependencies
tokio, tokio-util, cc-core, cc-api, cc-tools, cc-mcpcc-tui — terminal UI
cc-tui — terminal UI
Package:
Path:
Type: LibraryTerminal UI built on
cc-tuiPath:
crates/tuiType: LibraryTerminal UI built on
ratatui + crossterm. Replaces the TypeScript ink/React rendering layer with immediate-mode rendering.Key types
| Type | Description |
|---|---|
App | Top-level application state — messages, input, history, scroll offset, streaming state, cost tracker |
Tui | Terminal handle wrapping CrosstermBackend |
Key functions
| Function | Description |
|---|---|
setup_terminal() | Enables raw mode, enters alternate screen, returns Terminal<CrosstermBackend<Stdout>> |
restore_terminal(...) | Disables raw mode, leaves alternate screen, shows cursor |
render_app(f, app) | Immediate-mode render — messages area, input area (3 rows), status bar (1 row) |
render_permission_dialog(...) | Centered popup overlay with question and numbered options |
render_spinner(...) | Braille spinner (⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏) indexed by frame count |
App::handle_key_event(...) | Keyboard handler — Ctrl+C, Ctrl+D, Enter, Up/Down history, PageUp/Down scroll, F1 help |
App::handle_query_event(...) | Updates TUI state from QueryEvent — streaming text, tool status, turn completion |
is_slash_command(input) | Returns true if input starts with "/" |
parse_slash_command(input) | Splits "/name args" into ("name", "args") |
Rendering colors
| Element | Color |
|---|---|
| User messages | Cyan |
| Assistant messages | Green |
| Streaming (partial) text | Yellow italic |
| Status bar | Dark gray |
Key dependencies
ratatui, crossterm, syntect, unicode-width, cc-core, cc-querycc-commands — slash command implementations
cc-commands — slash command implementations
Package:
Path:
Type: LibrarySlash command implementations for the interactive REPL. Corresponds to the TypeScript
cc-commandsPath:
crates/commandsType: LibrarySlash command implementations for the interactive REPL. Corresponds to the TypeScript
src/commands/ directory.Core types
| Type | Description |
|---|---|
SlashCommand | Async trait — name, aliases, description, help, hidden, execute |
CommandContext | { config, cost_tracker, messages, working_dir } |
CommandResult | Message | UserMessage | ConfigChange | ClearConversation | SetMessages | Exit | Silent | Error |
Registry functions
| Function | Description |
|---|---|
all_commands() | Returns all built-in slash commands |
find_command(name) | Finds by name or alias |
execute_command(input, ctx) | Parses and executes a slash command; returns None if no match |
Implemented commands
| Command | Aliases | Description |
|---|---|---|
help | h, ? | List available slash commands |
clear | cls | Clear conversation history |
compact | — | Manually compact conversation |
cost | — | Show current session cost |
exit | quit, q | Exit the REPL |
model | — | Show or change the current model |
config | — | Show or update configuration |
version | — | Show version information |
resume | — | Resume a previous conversation |
status | — | Show session status |
diff | — | Show file diffs |
memory | — | Manage CLAUDE.md memories |
bug | — | File a bug report |
doctor | — | Run diagnostics |
login | — | Authenticate |
logout | — | Clear authentication |
init | — | Initialize project CLAUDE.md |
review | — | Code review workflow |
hooks | — | Manage event hooks |
mcp | — | Manage MCP servers |
permissions | — | Show or edit permissions |
plan | — | Enter or exit plan mode |
tasks | — | View background tasks |
session | — | Session management |
thinking | — | Toggle extended thinking |
export | — | Export conversation |
skills | — | List or manage skills |
rewind | — | Rewind conversation state |
stats | — | Show usage statistics |
files | — | List context files |
rename | — | Rename the current session |
effort | — | Set effort/thinking level |
summary | — | Summarize conversation |
commit | — | Run git commit workflow |
Key dependencies
async-trait, tokio, cc-core, cc-querycc-mcp — MCP client
cc-mcp — MCP client
Package:
Path:
Type: LibraryFull MCP (Model Context Protocol) client over JSON-RPC 2.0 + stdio subprocess transport. Implements protocol version
cc-mcpPath:
crates/mcpType: LibraryFull MCP (Model Context Protocol) client over JSON-RPC 2.0 + stdio subprocess transport. Implements protocol version
2024-11-05.Key types
| Type | Description |
|---|---|
McpClient | Single server connection — connects, initializes, lists tools/resources/prompts |
McpManager | Manages multiple named server connections; namespaces tools as "{server_name}_{tool_name}" |
StdioTransport | Subprocess transport — spawns command, pipes stdin/stdout, background reader task |
McpTool | { name, description, input_schema } — From<&McpTool> for ToolDefinition |
McpResource | { uri, name, description, mime_type } |
McpContent | Tagged enum — Text, Image, Resource |
CallToolResult | { content: Vec<McpContent>, is_error: Option<bool> } |
JsonRpcRequest | { jsonrpc: "2.0", method, params, id } |
JsonRpcResponse | { jsonrpc: "2.0", id, result, error } |
InitializeParams | { protocol_version: "2024-11-05", capabilities, client_info } |
ServerCapabilities | { tools, resources, prompts } |
McpManager operations
| Method | Description |
|---|---|
connect_all(configs) | Connects all configured servers; logs warnings on failure |
all_tool_definitions() | Aggregates tools from all servers, prefixed with server name |
call_tool(prefixed_name, args) | Routes to the correct server after stripping prefix |
list_all_resources() | Aggregates resources from all connected servers |
read_resource(uri) | Tries each server until one returns a result |
Key dependencies
tokio, serde, serde_json, cc-corecc-bridge — bridge to claude.ai
cc-bridge — bridge to claude.ai
Package:
Path:
Type: LibraryImplements the bridge protocol connecting the local CLI to the claude.ai web UI. Enables remote control from a browser session via long polling.
cc-bridgePath:
crates/bridgeType: LibraryImplements the bridge protocol connecting the local CLI to the claude.ai web UI. Enables remote control from a browser session via long polling.
Key types
| Type | Description |
|---|---|
BridgeClient | Main bridge client — manages state, channels, and polling loop |
BridgeConfig | { enabled, server_url, device_id, session_token, polling_interval_ms, max_reconnect_attempts } |
BridgeMessage | Server → client — UserMessage, PermissionResponse, Cancel, Ping |
BridgeEvent | Client → server — TextDelta, ToolStart, ToolEnd, PermissionRequest, TurnComplete, Error, Pong |
BridgeState | Connecting | Connected | Reconnecting { attempt } | Disconnected |
JwtClaims | { sub, exp, iat, device_id } — parsed from session token |
Transport
The polling loop long-polls{server_url}/sessions/{id}/poll for incoming messages and flushes outgoing BridgeEvent items to {server_url}/sessions/{id}/events. Exponential backoff on network errors; disconnects on 401/403.Work modes
Supported work modes (from README):single-session, worktree, same-dir.Key dependencies
reqwest, tokio, serde, serde_json, base64, sha2, hex, cc-corecc-buddy — companion pet system
cc-buddy — companion pet system
Package:
Path:
Type: LibraryTamagotchi-style companion pet system. Provides species hatching, ASCII art sprites, procedurally generated stats, and a soul description generated by Claude on first hatch.
cc-buddyPath:
crates/buddyType: LibraryTamagotchi-style companion pet system. Provides species hatching, ASCII art sprites, procedurally generated stats, and a soul description generated by Claude on first hatch.
Key types
| Type | Description |
|---|---|
Buddy | Main companion struct — species, name, rarity, is_shiny, stats, soul description, sprite |
Species | 18 species enum with associated rarity tier |
Stats | Five stats 0–100: DEBUGGING, PATIENCE, CHAOS, WISDOM, SNARK |
PRNG
Species and stats are determined by a Mulberry32 PRNG seeded from youruserId hash with the salt 'friend-2026-401'. The same user always gets the same buddy.Sprites
ASCII art sprites are 5 lines × 12 characters, with multiple animation frames for idle and reaction states.Key dependencies
cc-core, cc-api (for soul generation)cc-plugins — plugin system
cc-plugins — plugin system
Package:
Path:
Type: LibraryPlugin loader with a trust model and skill macros. Enables third-party extensions to register additional tools and commands.
cc-pluginsPath:
crates/pluginsType: LibraryPlugin loader with a trust model and skill macros. Enables third-party extensions to register additional tools and commands.
Key capabilities
- Plugin loader and lifecycle management
- Trust model for plugin verification
- Skill macros for defining plugin-provided skills
Key dependencies
cc-core, cc-toolsclaude-code — binary entry point
claude-code — binary entry point
Package:
Path:
Type: Binary (
claude-codePath:
crates/cliType: Binary (
[[bin]] name = "claude")Binary entry point. Produces the claude executable. Wires all crates together and starts either the interactive TUI REPL or headless (non-interactive) mode.CLI flags
| Flag | Type | Description |
|---|---|---|
prompt | Option<String> (positional) | Non-interactive prompt |
-p, --print | bool | Print mode (alias for non-interactive) |
-m, --model | Option<String> | Override model |
--permission-mode | Option<CliPermissionMode> | Default | AcceptEdits | BypassPermissions | Plan |
--resume | Option<String> | Resume session by ID |
--max-turns | u32 (default: 10) | Max conversation turns |
-s, --system-prompt | Option<String> | Override system prompt |
--append-system-prompt | Option<String> | Append to system prompt |
--no-claude-md | bool | Skip CLAUDE.md loading |
--output-format | Option<CliOutputFormat> | Text | Json | StreamJson |
-v, --verbose | bool | Enable verbose logging (DEBUG level) |
--api-key | Option<String> | API key override |
--max-tokens | Option<u32> | Override max tokens |
--cwd | Option<PathBuf> | Working directory |
--dangerously-skip-permissions | bool | Enable BypassPermissions mode |
--dump-system-prompt | bool | Print compiled system prompt and exit |
--mcp-config | Option<PathBuf> | MCP server config JSON file |
--no-auto-compact | bool | Disable auto-compact |
Startup sequence
- Parse CLI args with
clap - Initialize
tracing_subscriber(verbose → DEBUG, default → WARN) - Load
Settingsfrom~/.claude/settings.json - Build
Configby layering settings → CLI overrides - Create
Arc<CostTracker> - Build system context (embedded
system_prompt.txt+ContextBuilder) - Create
AnthropicClientandToolContext - Connect MCP servers if
--mcp-configprovided - Build tool list:
cc_tools::all_tools()+AgentTool+McpToolWrapperfor each MCP tool - Start cron scheduler via
start_cron_scheduler() - Dispatch to
run_headless()(prompt provided) orrun_interactive()(TUI REPL)
Key dependencies
clap, tokio, tracing-subscriber, cc-core, cc-api, cc-tools, cc-query, cc-tui, cc-commands, cc-mcp, cc-bridgeWorkspace dependencies
Key shared dependencies declared in[workspace.dependencies]:
| Crate | Version | Notes |
|---|---|---|
tokio | 1.44 | full features — async runtime for all crates |
reqwest | 0.12 | json, stream, native-tls, multipart |
reqwest-eventsource | 0.6 | SSE streaming in cc-api |
ratatui | 0.29 | Terminal UI in cc-tui |
crossterm | 0.28 | event-stream — terminal input in cc-tui |
clap | 4 | derive, env, string — CLI argument parsing |
serde / serde_json | 1 | Serialization throughout |
anyhow / thiserror | 1 / 2 | Error handling — libraries use thiserror, CLI uses anyhow |
tracing / tracing-subscriber | 0.1 / 0.3 | Structured logging with env-filter |
uuid | 1 | v4 — session and task IDs |
chrono | 0.4 | serde — timestamps |
schemars | 0.8 | derive — JSON schema generation for tool inputs |
dashmap | 6 | Concurrent hash maps for global singletons |
parking_lot | 0.12 | Efficient RwLock and Mutex |
tokio-util | 0.7 | codec, rt — cancellation tokens |
nix | 0.29 | process, signal, user — Unix process management |
syntect | 5 | Syntax highlighting in cc-tui |
base64 / sha2 / hex | 0.22 / 0.10 / 0.4 | Crypto utilities in cc-bridge |
walkdir | 2 | Directory traversal in cc-tools |
similar | 2 | Diff computation |
once_cell | 1 | Lazy singletons |