Skip to main content
The Claurst workspace is a Cargo workspace with resolver = "2", edition 2021, and version 1.0.0 across all member crates. Every crate lives under src-rust/crates/.

Dependency flow

cli → query → tools → core
         ↓         ↗
        api  →  core

       commands → core

        tui   → core

        mcp   → core

       bridge → core
cc-core is the shared foundation consumed by every other crate. claude-code (the binary) sits at the top and wires everything together.

Crates

Package: cc-core
Path: crates/core
Type: Library
Central shared crate. Defines all types consumed by every other crate. Contains 9 inline submodules.

Key types

TypeModuleDescription
ClaudeErrorerrorTyped error enum — API, auth, permission, I/O, rate-limit, context-limit, and more
ConfigconfigRuntime configuration struct (model, max tokens, permission mode, hooks, MCP servers, etc.)
PermissionModeconfigDefault | AcceptEdits | BypassPermissions | Plan
OutputFormatconfigText | Json | StreamJson
HookEventconfigPreToolUse | PostToolUse | Stop | UserPromptSubmit | Notification
HookEntryconfig{ command, tool_filter, blocking }
SettingsconfigPersisted user preferences at ~/.claude/settings.json
McpServerConfigconfigPer-server MCP configuration
RoletypesUser | Assistant
ContentBlocktypesUntagged enum — Text, Image, ToolUse, ToolResult, Thinking, RedactedThinking, Document
Messagetypes{ role, content } with convenience constructors and accessors
UsageInfotypesToken counts — input, output, cache creation, cache read
ToolDefinitiontypes{ name, description, input_schema }
PermissionDecisionpermissionsAllow | AllowPermanently | Deny | DenyPermanently
PermissionHandlerpermissionsTrait for permission checks and requests
AutoPermissionHandlerpermissionsNon-interactive handler — gates operations by PermissionMode
ConversationSessionhistorySession with UUID, timestamps, messages, model, title, and working directory
CostTrackercostLock-free token and cost accumulator using AtomicU64
HookContexthooksContext passed to hook shell commands as JSON on stdin
HookOutcomehooksAllowed | Blocked(String) | Modified(Value)
ContextBuildercontextBuilds system and user context strings from git state and CLAUDE.md discovery

Selected constants (cc-core::constants)

ConstantValue
DEFAULT_MODEL"claude-opus-4-6"
SONNET_MODEL"claude-sonnet-4-6"
HAIKU_MODEL"claude-haiku-4-5-20251001"
DEFAULT_MAX_TOKENS32_000
MAX_TOKENS_HARD_LIMIT65_536
DEFAULT_COMPACT_THRESHOLD0.9
ANTHROPIC_API_BASE"https://api.anthropic.com"
ANTHROPIC_API_VERSION"2023-06-01"
ANTHROPIC_BETA_HEADER"interleaved-thinking-2025-05-14,token-efficient-tools-2025-02-19,files-api-2025-04-14"
CLAUDE_MD_FILENAME"CLAUDE.md"
CONFIG_DIR_NAME".claude"

Key dependencies

thiserror, serde, serde_json, tokio, chrono, once_cell, glob, walkdir, uuid
Package: cc-api
Path: crates/api
Type: Library
Complete async Messages API client with SSE streaming support. Corresponds to the TypeScript src/services/api/ layer.

Key types

TypeModuleDescription
AnthropicClientclientMain API client — validates key, builds reqwest::Client with rustls-tls, sets anthropic-version and anthropic-beta headers
ClientConfigclient{ api_key, api_base, timeout_secs, max_retries }
CreateMessageRequesttypesFull request type — model, max_tokens, messages, system, tools, temperature, thinking, stream
CreateMessageRequestBuildertypesFluent builder for CreateMessageRequest
ThinkingConfigtypes{ type: "enabled", budget_tokens: u32 }
SystemPrompttypesText(String) or Blocks(Vec<SystemBlock>) for prompt caching
CacheControltypes{ type: "ephemeral" } — applied automatically to the last tool definition
ApiMessagetypes{ role, content }From<&Message> conversion included
StreamEventstreamingTagged enum — MessageStart, MessageDelta, MessageStop, ContentBlockStart, ContentBlockDelta, ContentBlockStop, Ping, Error
ContentDeltastreamingTextDelta, InputJsonDelta, ThinkingDelta, SignatureDelta
StreamHandlerstreamingTrait called for each SSE event
StreamAccumulatorstreamingCollects stream events into a complete (Message, UsageInfo, stop_reason)
SseLineParsersse_parserStateful 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-core
Package: cc-tools
Path: crates/tools
Type: Library
Implements 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

SymbolDescription
ToolAsync trait — name, description, permission_level, input_schema, execute, to_definition
ToolResult{ content, is_error, metadata }ToolResult::success(content) / ToolResult::error(content)
PermissionLevelNone | ReadOnly | Write | Execute | Dangerous
ToolContextExecution 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 structName constantPermission
BashToolBashExecute
FileReadToolReadReadOnly
FileEditToolEditWrite
FileWriteToolWriteWrite
GlobToolGlobReadOnly
GrepToolGrepReadOnly
WebFetchToolWebFetchReadOnly
WebSearchToolWebSearchReadOnly
NotebookEditToolNotebookEditWrite
TaskCreateToolTaskCreateNone
TaskGetToolTaskGetNone
TaskUpdateToolTaskUpdateNone
TaskListToolTaskListNone
TaskStopToolTaskStopNone
TaskOutputToolTaskOutputNone
CronCreateToolCronCreateNone
CronDeleteToolCronDeleteNone
CronListToolCronListNone
TodoWriteToolTodoWriteNone
AskUserQuestionToolAskUserQuestionNone
EnterPlanModeToolEnterPlanModeNone
ExitPlanModeToolExitPlanModeNone
PowerShellToolPowerShellExecute
EnterWorktreeToolEnterWorktreeExecute
ExitWorktreeToolExitWorktreeExecute
SendMessageToolSendMessageNone
SkillToolSkillNone
SleepToolSleepNone
ToolSearchToolToolSearchNone
BriefToolBriefNone
ConfigToolConfigNone
ListMcpResourcesToolListMcpResourcesNone
ReadMcpResourceToolReadMcpResourceNone

Global singletons

SingletonTypeCrate file
TASK_STORELazy<Arc<DashMap<String, Task>>>tasks.rs
INBOXLazy<DashMap<String, Vec<AgentMessage>>>send_message.rs
CRON_STORELazy<Arc<RwLock<HashMap<String, CronTask>>>>cron.rs
WORKTREE_SESSIONLazy<Arc<RwLock<Option<WorktreeSession>>>>worktree.rs

Key dependencies

schemars, tokio, regex, walkdir, glob, reqwest, serde_json, dashmap, cc-core, cc-mcp
Package: cc-query
Path: crates/query
Type: Library
The 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

TypeDescription
QueryOutcomeEndTurn | MaxTokens | Cancelled | Error(ClaudeError)
QueryConfigModel, max tokens, max turns, system prompt, thinking budget, temperature
QueryEventStream(StreamEvent) | ToolStart | ToolEnd | TurnComplete | Status | Error
AutoCompactStateTracks compaction count, consecutive failures, and circuit-breaker disabled flag
TokenWarningStateOk | Warning | Critical

Key functions

FunctionDescription
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

ConstantValue
AUTOCOMPACT_TRIGGER_FRACTION0.90
AUTOCOMPACT_BUFFER_TOKENS13_000
WARNING_THRESHOLD_BUFFER_TOKENS20_000
KEEP_RECENT_MESSAGES10
MAX_CONSECUTIVE_FAILURES3

Key dependencies

tokio, tokio-util, cc-core, cc-api, cc-tools, cc-mcp
Package: cc-tui
Path: crates/tui
Type: Library
Terminal UI built on ratatui + crossterm. Replaces the TypeScript ink/React rendering layer with immediate-mode rendering.

Key types

TypeDescription
AppTop-level application state — messages, input, history, scroll offset, streaming state, cost tracker
TuiTerminal handle wrapping CrosstermBackend

Key functions

FunctionDescription
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

ElementColor
User messagesCyan
Assistant messagesGreen
Streaming (partial) textYellow italic
Status barDark gray

Key dependencies

ratatui, crossterm, syntect, unicode-width, cc-core, cc-query
Package: cc-commands
Path: crates/commands
Type: Library
Slash command implementations for the interactive REPL. Corresponds to the TypeScript src/commands/ directory.

Core types

TypeDescription
SlashCommandAsync trait — name, aliases, description, help, hidden, execute
CommandContext{ config, cost_tracker, messages, working_dir }
CommandResultMessage | UserMessage | ConfigChange | ClearConversation | SetMessages | Exit | Silent | Error

Registry functions

FunctionDescription
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

CommandAliasesDescription
helph, ?List available slash commands
clearclsClear conversation history
compactManually compact conversation
costShow current session cost
exitquit, qExit the REPL
modelShow or change the current model
configShow or update configuration
versionShow version information
resumeResume a previous conversation
statusShow session status
diffShow file diffs
memoryManage CLAUDE.md memories
bugFile a bug report
doctorRun diagnostics
loginAuthenticate
logoutClear authentication
initInitialize project CLAUDE.md
reviewCode review workflow
hooksManage event hooks
mcpManage MCP servers
permissionsShow or edit permissions
planEnter or exit plan mode
tasksView background tasks
sessionSession management
thinkingToggle extended thinking
exportExport conversation
skillsList or manage skills
rewindRewind conversation state
statsShow usage statistics
filesList context files
renameRename the current session
effortSet effort/thinking level
summarySummarize conversation
commitRun git commit workflow

Key dependencies

async-trait, tokio, cc-core, cc-query
Package: cc-mcp
Path: crates/mcp
Type: Library
Full MCP (Model Context Protocol) client over JSON-RPC 2.0 + stdio subprocess transport. Implements protocol version 2024-11-05.

Key types

TypeDescription
McpClientSingle server connection — connects, initializes, lists tools/resources/prompts
McpManagerManages multiple named server connections; namespaces tools as "{server_name}_{tool_name}"
StdioTransportSubprocess transport — spawns command, pipes stdin/stdout, background reader task
McpTool{ name, description, input_schema }From<&McpTool> for ToolDefinition
McpResource{ uri, name, description, mime_type }
McpContentTagged 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

MethodDescription
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-core
Package: cc-bridge
Path: crates/bridge
Type: Library
Implements 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

TypeDescription
BridgeClientMain bridge client — manages state, channels, and polling loop
BridgeConfig{ enabled, server_url, device_id, session_token, polling_interval_ms, max_reconnect_attempts }
BridgeMessageServer → client — UserMessage, PermissionResponse, Cancel, Ping
BridgeEventClient → server — TextDelta, ToolStart, ToolEnd, PermissionRequest, TurnComplete, Error, Pong
BridgeStateConnecting | 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-core
Package: cc-buddy
Path: crates/buddy
Type: Library
cc-buddy is compiled only when the BUDDY feature flag is enabled. It is absent from standard external builds.
Tamagotchi-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

TypeDescription
BuddyMain companion struct — species, name, rarity, is_shiny, stats, soul description, sprite
Species18 species enum with associated rarity tier
StatsFive stats 0–100: DEBUGGING, PATIENCE, CHAOS, WISDOM, SNARK

PRNG

Species and stats are determined by a Mulberry32 PRNG seeded from your userId 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)
Package: cc-plugins
Path: crates/plugins
Type: Library
Plugin 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-tools
Package: claude-code
Path: crates/cli
Type: 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

FlagTypeDescription
promptOption<String> (positional)Non-interactive prompt
-p, --printboolPrint mode (alias for non-interactive)
-m, --modelOption<String>Override model
--permission-modeOption<CliPermissionMode>Default | AcceptEdits | BypassPermissions | Plan
--resumeOption<String>Resume session by ID
--max-turnsu32 (default: 10)Max conversation turns
-s, --system-promptOption<String>Override system prompt
--append-system-promptOption<String>Append to system prompt
--no-claude-mdboolSkip CLAUDE.md loading
--output-formatOption<CliOutputFormat>Text | Json | StreamJson
-v, --verboseboolEnable verbose logging (DEBUG level)
--api-keyOption<String>API key override
--max-tokensOption<u32>Override max tokens
--cwdOption<PathBuf>Working directory
--dangerously-skip-permissionsboolEnable BypassPermissions mode
--dump-system-promptboolPrint compiled system prompt and exit
--mcp-configOption<PathBuf>MCP server config JSON file
--no-auto-compactboolDisable auto-compact

Startup sequence

  1. Parse CLI args with clap
  2. Initialize tracing_subscriber (verbose → DEBUG, default → WARN)
  3. Load Settings from ~/.claude/settings.json
  4. Build Config by layering settings → CLI overrides
  5. Create Arc<CostTracker>
  6. Build system context (embedded system_prompt.txt + ContextBuilder)
  7. Create AnthropicClient and ToolContext
  8. Connect MCP servers if --mcp-config provided
  9. Build tool list: cc_tools::all_tools() + AgentTool + McpToolWrapper for each MCP tool
  10. Start cron scheduler via start_cron_scheduler()
  11. Dispatch to run_headless() (prompt provided) or run_interactive() (TUI REPL)

Key dependencies

clap, tokio, tracing-subscriber, cc-core, cc-api, cc-tools, cc-query, cc-tui, cc-commands, cc-mcp, cc-bridge

Workspace dependencies

Key shared dependencies declared in [workspace.dependencies]:
CrateVersionNotes
tokio1.44full features — async runtime for all crates
reqwest0.12json, stream, native-tls, multipart
reqwest-eventsource0.6SSE streaming in cc-api
ratatui0.29Terminal UI in cc-tui
crossterm0.28event-stream — terminal input in cc-tui
clap4derive, env, string — CLI argument parsing
serde / serde_json1Serialization throughout
anyhow / thiserror1 / 2Error handling — libraries use thiserror, CLI uses anyhow
tracing / tracing-subscriber0.1 / 0.3Structured logging with env-filter
uuid1v4 — session and task IDs
chrono0.4serde — timestamps
schemars0.8derive — JSON schema generation for tool inputs
dashmap6Concurrent hash maps for global singletons
parking_lot0.12Efficient RwLock and Mutex
tokio-util0.7codec, rt — cancellation tokens
nix0.29process, signal, user — Unix process management
syntect5Syntax highlighting in cc-tui
base64 / sha2 / hex0.22 / 0.10 / 0.4Crypto utilities in cc-bridge
walkdir2Directory traversal in cc-tools
similar2Diff computation
once_cell1Lazy singletons

Build docs developers (and LLMs) love