mirror of
https://github.com/codeaashu/claude-code.git
synced 2026-04-08 14:18:50 +03:00
claude-code
This commit is contained in:
224
docs/architecture.md
Normal file
224
docs/architecture.md
Normal file
@@ -0,0 +1,224 @@
|
||||
# Architecture
|
||||
|
||||
> Deep-dive into how Claude Code is structured internally.
|
||||
|
||||
---
|
||||
|
||||
## High-Level Overview
|
||||
|
||||
Claude Code is a terminal-native AI coding assistant built as a single-binary CLI. The architecture follows a pipeline model:
|
||||
|
||||
```
|
||||
User Input → CLI Parser → Query Engine → LLM API → Tool Execution Loop → Terminal UI
|
||||
```
|
||||
|
||||
The entire UI layer is built with **React + Ink** (React for the terminal), making it a fully reactive CLI application with components, hooks, state management, and all the patterns you'd expect in a React web app — just rendered to the terminal.
|
||||
|
||||
---
|
||||
|
||||
## Core Pipeline
|
||||
|
||||
### 1. Entrypoint (`src/main.tsx`)
|
||||
|
||||
The CLI parser is built with [Commander.js](https://github.com/tj/commander.js) (`@commander-js/extra-typings`). On startup, it:
|
||||
|
||||
- Fires parallel prefetch side-effects (MDM settings, Keychain, API preconnect) before heavy module imports
|
||||
- Parses CLI arguments and flags
|
||||
- Initializes the React/Ink renderer
|
||||
- Hands off to the REPL launcher (`src/replLauncher.tsx`)
|
||||
|
||||
### 2. Initialization (`src/entrypoints/`)
|
||||
|
||||
| File | Role |
|
||||
|------|------|
|
||||
| `cli.tsx` | CLI session orchestration — the main path from launch to REPL |
|
||||
| `init.ts` | Config, telemetry, OAuth, MDM policy initialization |
|
||||
| `mcp.ts` | MCP server mode entrypoint (Claude Code as an MCP server) |
|
||||
| `sdk/` | Agent SDK — programmatic API for embedding Claude Code |
|
||||
|
||||
Startup performs parallel initialization: MDM policy reads, Keychain prefetch, feature flag checks, then core init.
|
||||
|
||||
### 3. Query Engine (`src/QueryEngine.ts`, ~46K lines)
|
||||
|
||||
The heart of Claude Code. Handles:
|
||||
|
||||
- **Streaming responses** from the Anthropic API
|
||||
- **Tool-call loops** — when the LLM requests a tool, execute it and feed the result back
|
||||
- **Thinking mode** — extended thinking with budget management
|
||||
- **Retry logic** — automatic retries with backoff for transient failures
|
||||
- **Token counting** — tracks input/output tokens and cost per turn
|
||||
- **Context management** — manages conversation history and context windows
|
||||
|
||||
### 4. Tool System (`src/Tool.ts` + `src/tools/`)
|
||||
|
||||
Every capability Claude can invoke is a **tool**. Each tool is self-contained with:
|
||||
|
||||
- **Input schema** (Zod validation)
|
||||
- **Permission model** (what needs user approval)
|
||||
- **Execution logic** (the actual implementation)
|
||||
- **UI components** (how invocation/results render in the terminal)
|
||||
|
||||
Tools are registered in `src/tools.ts` and discovered by the Query Engine during tool-call loops.
|
||||
|
||||
See [Tools Reference](tools.md) for the complete catalog.
|
||||
|
||||
### 5. Command System (`src/commands.ts` + `src/commands/`)
|
||||
|
||||
User-facing slash commands (`/commit`, `/review`, `/mcp`, etc.) that can be typed in the REPL. Three types:
|
||||
|
||||
| Type | Description | Example |
|
||||
|------|-------------|---------|
|
||||
| **PromptCommand** | Sends a formatted prompt to the LLM with injected tools | `/review`, `/commit` |
|
||||
| **LocalCommand** | Runs in-process, returns plain text | `/cost`, `/version` |
|
||||
| **LocalJSXCommand** | Runs in-process, returns React JSX | `/doctor`, `/install` |
|
||||
|
||||
Commands are registered in `src/commands.ts` and invoked via `/command-name` in the REPL.
|
||||
|
||||
See [Commands Reference](commands.md) for the complete catalog.
|
||||
|
||||
---
|
||||
|
||||
## State Management
|
||||
|
||||
Claude Code uses a **React context + custom store** pattern:
|
||||
|
||||
| Component | Location | Purpose |
|
||||
|-----------|----------|---------|
|
||||
| `AppState` | `src/state/AppStateStore.ts` | Global mutable state object |
|
||||
| Context Providers | `src/context/` | React context for notifications, stats, FPS |
|
||||
| Selectors | `src/state/` | Derived state functions |
|
||||
| Change Observers | `src/state/onChangeAppState.ts` | Side-effects on state changes |
|
||||
|
||||
The `AppState` object is passed into tool contexts, giving tools access to conversation history, settings, and runtime state.
|
||||
|
||||
---
|
||||
|
||||
## UI Layer
|
||||
|
||||
### Components (`src/components/`, ~140 components)
|
||||
|
||||
- Functional React components using Ink primitives (`Box`, `Text`, `useInput()`)
|
||||
- Styled with [Chalk](https://github.com/chalk/chalk) for terminal colors
|
||||
- React Compiler enabled for optimized re-renders
|
||||
- Design system primitives in `src/components/design-system/`
|
||||
|
||||
### Screens (`src/screens/`)
|
||||
|
||||
Full-screen UI modes:
|
||||
|
||||
| Screen | Purpose |
|
||||
|--------|---------|
|
||||
| `REPL.tsx` | Main interactive REPL (the default screen) |
|
||||
| `Doctor.tsx` | Environment diagnostics (`/doctor`) |
|
||||
| `ResumeConversation.tsx` | Session restore (`/resume`) |
|
||||
|
||||
### Hooks (`src/hooks/`, ~80 hooks)
|
||||
|
||||
Standard React hooks pattern. Notable categories:
|
||||
|
||||
- **Permission hooks** — `useCanUseTool`, `src/hooks/toolPermission/`
|
||||
- **IDE integration** — `useIDEIntegration`, `useIdeConnectionStatus`, `useDiffInIDE`
|
||||
- **Input handling** — `useTextInput`, `useVimInput`, `usePasteHandler`, `useInputBuffer`
|
||||
- **Session management** — `useSessionBackgrounding`, `useRemoteSession`, `useAssistantHistory`
|
||||
- **Plugin/skill hooks** — `useManagePlugins`, `useSkillsChange`
|
||||
- **Notification hooks** — `src/hooks/notifs/` (rate limits, deprecation warnings, etc.)
|
||||
|
||||
---
|
||||
|
||||
## Configuration & Schemas
|
||||
|
||||
### Config Schemas (`src/schemas/`)
|
||||
|
||||
Zod v4-based schemas for all configuration:
|
||||
|
||||
- User settings
|
||||
- Project-level settings
|
||||
- Organization/enterprise policies
|
||||
- Permission rules
|
||||
|
||||
### Migrations (`src/migrations/`)
|
||||
|
||||
Handles config format changes between versions — reads old configs and transforms them to the current schema.
|
||||
|
||||
---
|
||||
|
||||
## Build System
|
||||
|
||||
### Bun Runtime
|
||||
|
||||
Claude Code runs on [Bun](https://bun.sh) (not Node.js). Key implications:
|
||||
|
||||
- Native JSX/TSX support without a transpilation step
|
||||
- `bun:bundle` feature flags for dead-code elimination
|
||||
- ES modules with `.js` extensions (Bun convention)
|
||||
|
||||
### Feature Flags (Dead Code Elimination)
|
||||
|
||||
```typescript
|
||||
import { feature } from 'bun:bundle'
|
||||
|
||||
// Code inside inactive feature flags is completely stripped at build time
|
||||
if (feature('VOICE_MODE')) {
|
||||
const voiceCommand = require('./commands/voice/index.js').default
|
||||
}
|
||||
```
|
||||
|
||||
Notable flags:
|
||||
|
||||
| Flag | Feature |
|
||||
|------|---------|
|
||||
| `PROACTIVE` | Proactive agent mode (autonomous actions) |
|
||||
| `KAIROS` | Kairos subsystem |
|
||||
| `BRIDGE_MODE` | IDE bridge integration |
|
||||
| `DAEMON` | Background daemon mode |
|
||||
| `VOICE_MODE` | Voice input/output |
|
||||
| `AGENT_TRIGGERS` | Triggered agent actions |
|
||||
| `MONITOR_TOOL` | Monitoring tool |
|
||||
| `COORDINATOR_MODE` | Multi-agent coordinator |
|
||||
| `WORKFLOW_SCRIPTS` | Workflow automation scripts |
|
||||
|
||||
### Lazy Loading
|
||||
|
||||
Heavy modules are deferred via dynamic `import()` until first use:
|
||||
|
||||
- OpenTelemetry (~400KB)
|
||||
- gRPC (~700KB)
|
||||
- Other optional dependencies
|
||||
|
||||
---
|
||||
|
||||
## Error Handling & Telemetry
|
||||
|
||||
### Telemetry (`src/services/analytics/`)
|
||||
|
||||
- [GrowthBook](https://www.growthbook.io/) for feature flags and A/B testing
|
||||
- [OpenTelemetry](https://opentelemetry.io/) for distributed tracing and metrics
|
||||
- Custom event tracking for usage analytics
|
||||
|
||||
### Cost Tracking (`src/cost-tracker.ts`)
|
||||
|
||||
Tracks token usage and estimated cost per conversation turn. Accessible via the `/cost` command.
|
||||
|
||||
### Diagnostics (`/doctor` command)
|
||||
|
||||
The `Doctor.tsx` screen runs environment checks: API connectivity, authentication, tool availability, MCP server status, and more.
|
||||
|
||||
---
|
||||
|
||||
## Concurrency Model
|
||||
|
||||
Claude Code uses a **single-threaded event loop** (Bun/Node.js model) with:
|
||||
|
||||
- Async/await for I/O operations
|
||||
- React's concurrent rendering for UI updates
|
||||
- Web Workers or child processes for CPU-intensive tasks (gRPC, etc.)
|
||||
- Tool concurrency safety — each tool declares `isConcurrencySafe()` to indicate if it can run in parallel with other tools
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Tools Reference](tools.md) — Complete catalog of all 40 agent tools
|
||||
- [Commands Reference](commands.md) — Complete catalog of all slash commands
|
||||
- [Subsystems Guide](subsystems.md) — Bridge, MCP, permissions, skills, plugins, and more
|
||||
- [Exploration Guide](exploration-guide.md) — How to navigate this codebase
|
||||
239
docs/bridge.md
Normal file
239
docs/bridge.md
Normal file
@@ -0,0 +1,239 @@
|
||||
# Bridge Layer (VS Code / JetBrains IDE Integration)
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
The bridge (`src/bridge/`, ~31 files) connects Claude Code CLI sessions to
|
||||
remote IDE extensions (VS Code, JetBrains) and the claude.ai web UI. It is
|
||||
gated behind `feature('BRIDGE_MODE')` which defaults to `false`.
|
||||
|
||||
### Protocols
|
||||
|
||||
The bridge uses **two transport generations**:
|
||||
|
||||
| Version | Read Path | Write Path | Negotiation |
|
||||
|---------|-----------|------------|-------------|
|
||||
| **v1 (env-based)** | WebSocket to Session-Ingress (`ws(s)://.../v1/session_ingress/ws/{sessionId}`) | HTTP POST to Session-Ingress | Environments API poll/ack/dispatch |
|
||||
| **v2 (env-less)** | SSE stream via `SSETransport` | `CCRClient` → `/worker/*` endpoints | Direct `POST /v1/code/sessions/{id}/bridge` → worker JWT |
|
||||
|
||||
Both wrapped behind `ReplBridgeTransport` interface (`replBridgeTransport.ts`).
|
||||
|
||||
The v1 path: register environment → poll for work → acknowledge → spawn session.
|
||||
The v2 path: create session → POST `/bridge` for JWT → SSE + CCRClient directly.
|
||||
|
||||
### Authentication
|
||||
|
||||
1. **OAuth tokens** — claude.ai subscription required (`isClaudeAISubscriber()`)
|
||||
2. **JWT** — Session-Ingress tokens (`sk-ant-si-` prefixed) with `exp` claims.
|
||||
`jwtUtils.ts` decodes and schedules proactive refresh before expiry.
|
||||
3. **Trusted Device token** — `X-Trusted-Device-Token` header for elevated
|
||||
security tier sessions. Enrolled via `trustedDevice.ts`.
|
||||
4. **Environment secret** — base64url-encoded `WorkSecret` containing
|
||||
`session_ingress_token`, `api_base_url`, git sources, auth tokens.
|
||||
|
||||
Dev override: `CLAUDE_BRIDGE_OAUTH_TOKEN` and `CLAUDE_BRIDGE_BASE_URL`
|
||||
(ant-only, `process.env.USER_TYPE === 'ant'`).
|
||||
|
||||
### Message Flow (IDE ↔ CLI)
|
||||
|
||||
```
|
||||
IDE / claude.ai ──WebSocket/SSE──→ Session-Ingress ──→ CLI (replBridge)
|
||||
←── POST / CCRClient writes ──── Session-Ingress ←── CLI
|
||||
```
|
||||
|
||||
**Inbound** (server → CLI):
|
||||
- `user` messages (prompts from web UI) → `handleIngressMessage()` → enqueued to REPL
|
||||
- `control_request` (initialize, set_model, interrupt, set_permission_mode, set_max_thinking_tokens)
|
||||
- `control_response` (permission decisions from IDE)
|
||||
|
||||
**Outbound** (CLI → server):
|
||||
- `assistant` messages (Claude's responses)
|
||||
- `user` messages (echoed for sync)
|
||||
- `result` messages (turn completion)
|
||||
- System events, tool starts, activities
|
||||
|
||||
Dedup: `BoundedUUIDSet` tracks recent posted/inbound UUIDs to reject echoes
|
||||
and re-deliveries.
|
||||
|
||||
### Lifecycle
|
||||
|
||||
1. **Entitlement check**: `isBridgeEnabled()` / `isBridgeEnabledBlocking()` →
|
||||
GrowthBook gate `tengu_ccr_bridge` + OAuth subscriber check
|
||||
2. **Session creation**: `createBridgeSession()` → POST to API
|
||||
3. **Transport init**: v1 `HybridTransport` or v2 `SSETransport` + `CCRClient`
|
||||
4. **Message pump**: Read inbound via transport, write outbound via batch
|
||||
5. **Token refresh**: Proactive JWT refresh via `createTokenRefreshScheduler()`
|
||||
6. **Teardown**: `teardown()` → flush pending → close transport → archive session
|
||||
|
||||
Spawn modes for `claude remote-control`:
|
||||
- `single-session`: One session in cwd, bridge tears down when it ends
|
||||
- `worktree`: Persistent server, each session gets an isolated git worktree
|
||||
- `same-dir`: Persistent server, sessions share cwd
|
||||
|
||||
### Key Types
|
||||
|
||||
- `BridgeConfig` — Full bridge configuration (dir, auth, URLs, spawn mode, timeouts)
|
||||
- `WorkSecret` — Decoded work payload (token, API URL, git sources, MCP config)
|
||||
- `SessionHandle` — Running session (kill, activities, stdin, token update)
|
||||
- `ReplBridgeHandle` — REPL bridge API (write messages, control requests, teardown)
|
||||
- `BridgeState` — `'ready' | 'connected' | 'reconnecting' | 'failed'`
|
||||
- `SpawnMode` — `'single-session' | 'worktree' | 'same-dir'`
|
||||
|
||||
---
|
||||
|
||||
## Feature Gate Analysis
|
||||
|
||||
### Must Work (currently works correctly)
|
||||
|
||||
The `feature('BRIDGE_MODE')` gate in `src/shims/bun-bundle.ts` defaults to
|
||||
`false` (reads `CLAUDE_CODE_BRIDGE_MODE` env var). All critical code paths
|
||||
are properly guarded:
|
||||
|
||||
| Location | Guard |
|
||||
|----------|-------|
|
||||
| `src/entrypoints/cli.tsx:112` | `feature('BRIDGE_MODE') && args[0] === 'remote-control'` |
|
||||
| `src/main.tsx:2246` | `feature('BRIDGE_MODE') && remoteControlOption !== undefined` |
|
||||
| `src/main.tsx:3866` | `if (feature('BRIDGE_MODE'))` (Commander subcommand) |
|
||||
| `src/hooks/useReplBridge.tsx:79-88` | All `useAppState` calls gated by `feature('BRIDGE_MODE')` ternary |
|
||||
| `src/hooks/useReplBridge.tsx:99` | `useEffect` body gated by `feature('BRIDGE_MODE')` |
|
||||
| `src/components/PromptInput/PromptInputFooter.tsx:160` | `if (!feature('BRIDGE_MODE')) return null` |
|
||||
| `src/components/Settings/Config.tsx:930` | `feature('BRIDGE_MODE') && isBridgeEnabled()` spread |
|
||||
| `src/tools/BriefTool/upload.ts:99` | `if (feature('BRIDGE_MODE'))` |
|
||||
| `src/tools/ConfigTool/supportedSettings.ts:153` | `feature('BRIDGE_MODE')` spread |
|
||||
|
||||
### Can Defer (full bridge functionality)
|
||||
|
||||
All of the following are behind the feature gate and inactive:
|
||||
- `runBridgeLoop()` — Full bridge orchestration in `bridgeMain.ts`
|
||||
- `initReplBridge()` — REPL bridge initialization
|
||||
- `initBridgeCore()` / `initEnvLessBridgeCore()` — Transport negotiation
|
||||
- `createBridgeApiClient()` — Environments API calls
|
||||
- `BridgeUI` — Bridge status display and QR codes
|
||||
- Token refresh scheduling
|
||||
- Multi-session management (worktree mode)
|
||||
- Permission delegation to IDE
|
||||
|
||||
### Won't Break
|
||||
|
||||
Static imports of bridge modules from outside `src/bridge/` do NOT crash because:
|
||||
|
||||
1. **All bridge files exist** — they're in the repo, so imports resolve.
|
||||
2. **No side effects at import time** — bridge modules define functions/types
|
||||
but don't execute bridge logic on import.
|
||||
3. **Runtime guards** — Functions like `isBridgeEnabled()` return `false`
|
||||
when `feature('BRIDGE_MODE')` is false. `getReplBridgeHandle()` returns
|
||||
`null`. `useReplBridge` short-circuits via ternary operators.
|
||||
|
||||
Files with unguarded static imports (safe because files exist):
|
||||
- `src/hooks/useReplBridge.tsx` — imports types and utils from bridge
|
||||
- `src/components/Settings/Config.tsx` — imports `isBridgeEnabled` (returns false)
|
||||
- `src/components/PromptInput/PromptInputFooter.tsx` — early-returns null
|
||||
- `src/tools/SendMessageTool/SendMessageTool.ts` — `getReplBridgeHandle()` returns null
|
||||
- `src/tools/BriefTool/upload.ts` — guarded at call site
|
||||
- `src/commands/logout/logout.tsx` — `clearTrustedDeviceTokenCache` is a no-op
|
||||
|
||||
---
|
||||
|
||||
## Bridge Stub
|
||||
|
||||
Created `src/bridge/stub.ts` with:
|
||||
- `isBridgeAvailable()` → always returns `false`
|
||||
- `noopBridgeHandle` — silent no-op `ReplBridgeHandle`
|
||||
- `noopBridgeLogger` — silent no-op `BridgeLogger`
|
||||
|
||||
Available for any future code that needs a safe fallback when bridge is off.
|
||||
|
||||
---
|
||||
|
||||
## Bridge Activation (Future Work)
|
||||
|
||||
To enable the bridge:
|
||||
|
||||
### 1. Environment Variable
|
||||
```bash
|
||||
export CLAUDE_CODE_BRIDGE_MODE=true
|
||||
```
|
||||
|
||||
### 2. Authentication Requirements
|
||||
- Must be logged in to claude.ai with an active subscription
|
||||
(`isClaudeAISubscriber()` must return `true`)
|
||||
- OAuth tokens obtained via `claude auth login` (needs `user:profile` scope)
|
||||
- GrowthBook gate `tengu_ccr_bridge` must be enabled for the user's org
|
||||
|
||||
### 3. IDE Extension
|
||||
- VS Code: Claude Code extension (connects via the bridge's Session-Ingress layer)
|
||||
- JetBrains: Similar integration (same protocol)
|
||||
- Web: `claude.ai/code?bridge={environmentId}` URL
|
||||
|
||||
### 4. Network / Ports
|
||||
- **Session-Ingress**: WebSocket (`wss://`) or SSE for reads; HTTPS POST for writes
|
||||
- **API base**: Production `api.claude.ai` (configured via OAuth config)
|
||||
- Dev overrides: `CLAUDE_BRIDGE_BASE_URL`, localhost uses `ws://` and `/v2/` paths
|
||||
- QR code displayed in terminal links to `claude.ai/code?bridge={envId}`
|
||||
|
||||
### 5. Running Remote Control
|
||||
```bash
|
||||
# Single session (tears down when session ends)
|
||||
claude remote-control
|
||||
|
||||
# Named session
|
||||
claude remote-control "my-project"
|
||||
|
||||
# With specific spawn mode (requires tengu_ccr_bridge_multi_session gate)
|
||||
claude remote-control --spawn worktree
|
||||
claude remote-control --spawn same-dir
|
||||
```
|
||||
|
||||
### 6. Additional Flags
|
||||
- `--remote-control [name]` / `--rc [name]` — Start REPL with bridge pre-enabled
|
||||
- `--debug-file <path>` — Write debug log to file
|
||||
- `--session-id <id>` — Resume an existing session
|
||||
|
||||
---
|
||||
|
||||
## Chrome Extension Bridge
|
||||
|
||||
### `--claude-in-chrome-mcp` (cli.tsx:72)
|
||||
|
||||
Launches a **Claude-in-Chrome MCP server** via `runClaudeInChromeMcpServer()` from
|
||||
`src/utils/claudeInChrome/mcpServer.ts`. This:
|
||||
- Creates a `StdioServerTransport` (MCP over stdin/stdout)
|
||||
- Uses `@ant/claude-for-chrome-mcp` package to create an MCP server
|
||||
- Bridges between Claude Code and the Chrome extension
|
||||
- Supports both native socket (local) and WebSocket bridge (`wss://bridge.claudeusercontent.com`)
|
||||
- Gated by `tengu_copper_bridge` GrowthBook flag (or `USER_TYPE=ant`)
|
||||
|
||||
**Not gated by `feature('BRIDGE_MODE')`** — this is a separate subsystem. It only
|
||||
runs when explicitly invoked with `--claude-in-chrome-mcp` flag.
|
||||
|
||||
### `--chrome-native-host` (cli.tsx:79)
|
||||
|
||||
Launches the **Chrome Native Messaging Host** via `runChromeNativeHost()` from
|
||||
`src/utils/claudeInChrome/chromeNativeHost.ts`. This:
|
||||
- Implements Chrome's native messaging protocol (4-byte length prefix + JSON over stdin/stdout)
|
||||
- Creates a Unix domain socket server at a secure path
|
||||
- Proxies MCP messages between Chrome extension and local Claude Code instances
|
||||
- Has its own debug logging to `~/.claude/debug/chrome-native-host.txt` (ant-only)
|
||||
|
||||
**Not gated by `feature('BRIDGE_MODE')`** — separate entry point. Only activated
|
||||
when Chrome calls the registered native messaging host binary.
|
||||
|
||||
### Safety
|
||||
|
||||
Both Chrome paths:
|
||||
- Are **dynamic imports** — only loaded when the specific flag is passed
|
||||
- Return immediately after their own `await` — no side effects on normal CLI startup
|
||||
- Cannot crash normal operation because they're entirely separate code paths
|
||||
- Have no dependency on the bridge feature flag
|
||||
|
||||
---
|
||||
|
||||
## Verification Summary
|
||||
|
||||
| Check | Status |
|
||||
|-------|--------|
|
||||
| `feature('BRIDGE_MODE')` returns `false` by default | ✅ Verified in `src/shims/bun-bundle.ts` |
|
||||
| Bridge code not executed when disabled | ✅ All call sites use `feature()` guard |
|
||||
| No bridge-related errors on startup | ✅ Imports resolve (files exist), no side effects |
|
||||
| CLI works in terminal-only mode | ✅ Bridge is purely additive |
|
||||
| Chrome paths don't crash | ✅ Separate dynamic imports, only on explicit flags |
|
||||
| Stub available for safety | ✅ Created `src/bridge/stub.ts` |
|
||||
211
docs/commands.md
Normal file
211
docs/commands.md
Normal file
@@ -0,0 +1,211 @@
|
||||
# Commands Reference
|
||||
|
||||
> Complete catalog of all slash commands in Claude Code.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Commands are user-facing actions invoked with a `/` prefix in the REPL (e.g., `/commit`, `/review`). They live in `src/commands/` and are registered in `src/commands.ts`.
|
||||
|
||||
### Command Types
|
||||
|
||||
| Type | Description | Example |
|
||||
|------|-------------|---------|
|
||||
| **PromptCommand** | Sends a formatted prompt to the LLM with injected tools | `/review`, `/commit` |
|
||||
| **LocalCommand** | Runs in-process, returns plain text | `/cost`, `/version` |
|
||||
| **LocalJSXCommand** | Runs in-process, returns React JSX | `/install`, `/doctor` |
|
||||
|
||||
### Command Definition Pattern
|
||||
|
||||
```typescript
|
||||
const command = {
|
||||
type: 'prompt',
|
||||
name: 'my-command',
|
||||
description: 'What this command does',
|
||||
progressMessage: 'working...',
|
||||
allowedTools: ['Bash(git *)', 'FileRead(*)'],
|
||||
source: 'builtin',
|
||||
async getPromptForCommand(args, context) {
|
||||
return [{ type: 'text', text: '...' }]
|
||||
},
|
||||
} satisfies Command
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Git & Version Control
|
||||
|
||||
| Command | Source | Description |
|
||||
|---------|--------|-------------|
|
||||
| `/commit` | `commit.ts` | Create a git commit with an AI-generated message |
|
||||
| `/commit-push-pr` | `commit-push-pr.ts` | Commit, push, and create a PR in one step |
|
||||
| `/branch` | `branch/` | Create or switch git branches |
|
||||
| `/diff` | `diff/` | View file changes (staged, unstaged, or against a ref) |
|
||||
| `/pr_comments` | `pr_comments/` | View and address PR review comments |
|
||||
| `/rewind` | `rewind/` | Revert to a previous state |
|
||||
|
||||
## Code Quality
|
||||
|
||||
| Command | Source | Description |
|
||||
|---------|--------|-------------|
|
||||
| `/review` | `review.ts` | AI-powered code review of staged/unstaged changes |
|
||||
| `/security-review` | `security-review.ts` | Security-focused code review |
|
||||
| `/advisor` | `advisor.ts` | Get architectural or design advice |
|
||||
| `/bughunter` | `bughunter/` | Find potential bugs in the codebase |
|
||||
|
||||
## Session & Context
|
||||
|
||||
| Command | Source | Description |
|
||||
|---------|--------|-------------|
|
||||
| `/compact` | `compact/` | Compress conversation context to fit more history |
|
||||
| `/context` | `context/` | Visualize current context (files, memory, etc.) |
|
||||
| `/resume` | `resume/` | Restore a previous conversation session |
|
||||
| `/session` | `session/` | Manage sessions (list, switch, delete) |
|
||||
| `/share` | `share/` | Share a session via link |
|
||||
| `/export` | `export/` | Export conversation to a file |
|
||||
| `/summary` | `summary/` | Generate a summary of the current session |
|
||||
| `/clear` | `clear/` | Clear the conversation history |
|
||||
|
||||
## Configuration & Settings
|
||||
|
||||
| Command | Source | Description |
|
||||
|---------|--------|-------------|
|
||||
| `/config` | `config/` | View or modify Claude Code settings |
|
||||
| `/permissions` | `permissions/` | Manage tool permission rules |
|
||||
| `/theme` | `theme/` | Change the terminal color theme |
|
||||
| `/output-style` | `output-style/` | Change output formatting style |
|
||||
| `/color` | `color/` | Toggle color output |
|
||||
| `/keybindings` | `keybindings/` | View or customize keybindings |
|
||||
| `/vim` | `vim/` | Toggle vim mode for input |
|
||||
| `/effort` | `effort/` | Adjust response effort level |
|
||||
| `/model` | `model/` | Switch the active model |
|
||||
| `/privacy-settings` | `privacy-settings/` | Manage privacy/data settings |
|
||||
| `/fast` | `fast/` | Toggle fast mode (shorter responses) |
|
||||
| `/brief` | `brief.ts` | Toggle brief output mode |
|
||||
|
||||
## Memory & Knowledge
|
||||
|
||||
| Command | Source | Description |
|
||||
|---------|--------|-------------|
|
||||
| `/memory` | `memory/` | Manage persistent memory (CLAUDE.md files) |
|
||||
| `/add-dir` | `add-dir/` | Add a directory to the project context |
|
||||
| `/files` | `files/` | List files in the current context |
|
||||
|
||||
## MCP & Plugins
|
||||
|
||||
| Command | Source | Description |
|
||||
|---------|--------|-------------|
|
||||
| `/mcp` | `mcp/` | Manage MCP server connections |
|
||||
| `/plugin` | `plugin/` | Install, remove, or manage plugins |
|
||||
| `/reload-plugins` | `reload-plugins/` | Reload all installed plugins |
|
||||
| `/skills` | `skills/` | View and manage skills |
|
||||
|
||||
## Authentication
|
||||
|
||||
| Command | Source | Description |
|
||||
|---------|--------|-------------|
|
||||
| `/login` | `login/` | Authenticate with Anthropic |
|
||||
| `/logout` | `logout/` | Sign out |
|
||||
| `/oauth-refresh` | `oauth-refresh/` | Refresh OAuth tokens |
|
||||
|
||||
## Tasks & Agents
|
||||
|
||||
| Command | Source | Description |
|
||||
|---------|--------|-------------|
|
||||
| `/tasks` | `tasks/` | Manage background tasks |
|
||||
| `/agents` | `agents/` | Manage sub-agents |
|
||||
| `/ultraplan` | `ultraplan.tsx` | Generate a detailed execution plan |
|
||||
| `/plan` | `plan/` | Enter planning mode |
|
||||
|
||||
## Diagnostics & Status
|
||||
|
||||
| Command | Source | Description |
|
||||
|---------|--------|-------------|
|
||||
| `/doctor` | `doctor/` | Run environment diagnostics |
|
||||
| `/status` | `status/` | Show system and session status |
|
||||
| `/stats` | `stats/` | Show session statistics |
|
||||
| `/cost` | `cost/` | Display token usage and estimated cost |
|
||||
| `/version` | `version.ts` | Show Claude Code version |
|
||||
| `/usage` | `usage/` | Show detailed API usage |
|
||||
| `/extra-usage` | `extra-usage/` | Show extended usage details |
|
||||
| `/rate-limit-options` | `rate-limit-options/` | View rate limit configuration |
|
||||
|
||||
## Installation & Setup
|
||||
|
||||
| Command | Source | Description |
|
||||
|---------|--------|-------------|
|
||||
| `/install` | `install.tsx` | Install or update Claude Code |
|
||||
| `/upgrade` | `upgrade/` | Upgrade to the latest version |
|
||||
| `/init` | `init.ts` | Initialize a project (create CLAUDE.md) |
|
||||
| `/init-verifiers` | `init-verifiers.ts` | Set up verifier hooks |
|
||||
| `/onboarding` | `onboarding/` | Run the first-time setup wizard |
|
||||
| `/terminalSetup` | `terminalSetup/` | Configure terminal integration |
|
||||
|
||||
## IDE & Desktop Integration
|
||||
|
||||
| Command | Source | Description |
|
||||
|---------|--------|-------------|
|
||||
| `/bridge` | `bridge/` | Manage IDE bridge connections |
|
||||
| `/bridge-kick` | `bridge-kick.ts` | Force-restart the IDE bridge |
|
||||
| `/ide` | `ide/` | Open in IDE |
|
||||
| `/desktop` | `desktop/` | Hand off to the desktop app |
|
||||
| `/mobile` | `mobile/` | Hand off to the mobile app |
|
||||
| `/teleport` | `teleport/` | Transfer session to another device |
|
||||
|
||||
## Remote & Environment
|
||||
|
||||
| Command | Source | Description |
|
||||
|---------|--------|-------------|
|
||||
| `/remote-env` | `remote-env/` | Configure remote environment |
|
||||
| `/remote-setup` | `remote-setup/` | Set up remote session |
|
||||
| `/env` | `env/` | View environment variables |
|
||||
| `/sandbox-toggle` | `sandbox-toggle/` | Toggle sandbox mode |
|
||||
|
||||
## Misc
|
||||
|
||||
| Command | Source | Description |
|
||||
|---------|--------|-------------|
|
||||
| `/help` | `help/` | Show help and available commands |
|
||||
| `/exit` | `exit/` | Exit Claude Code |
|
||||
| `/copy` | `copy/` | Copy content to clipboard |
|
||||
| `/feedback` | `feedback/` | Send feedback to Anthropic |
|
||||
| `/release-notes` | `release-notes/` | View release notes |
|
||||
| `/rename` | `rename/` | Rename the current session |
|
||||
| `/tag` | `tag/` | Tag the current session |
|
||||
| `/insights` | `insights.ts` | Show codebase insights |
|
||||
| `/stickers` | `stickers/` | Easter egg — stickers |
|
||||
| `/good-claude` | `good-claude/` | Easter egg — praise Claude |
|
||||
| `/voice` | `voice/` | Toggle voice input mode |
|
||||
| `/chrome` | `chrome/` | Chrome extension integration |
|
||||
| `/issue` | `issue/` | File a GitHub issue |
|
||||
| `/statusline` | `statusline.tsx` | Customize the status line |
|
||||
| `/thinkback` | `thinkback/` | Replay Claude's thinking process |
|
||||
| `/thinkback-play` | `thinkback-play/` | Animated thinking replay |
|
||||
| `/passes` | `passes/` | Multi-pass execution |
|
||||
| `/x402` | `x402/` | x402 payment protocol integration |
|
||||
|
||||
## Internal / Debug Commands
|
||||
|
||||
| Command | Source | Description |
|
||||
|---------|--------|-------------|
|
||||
| `/ant-trace` | `ant-trace/` | Anthropic-internal tracing |
|
||||
| `/autofix-pr` | `autofix-pr/` | Auto-fix PR issues |
|
||||
| `/backfill-sessions` | `backfill-sessions/` | Backfill session data |
|
||||
| `/break-cache` | `break-cache/` | Invalidate caches |
|
||||
| `/btw` | `btw/` | "By the way" interjection |
|
||||
| `/ctx_viz` | `ctx_viz/` | Context visualization (debug) |
|
||||
| `/debug-tool-call` | `debug-tool-call/` | Debug a specific tool call |
|
||||
| `/heapdump` | `heapdump/` | Dump heap for memory analysis |
|
||||
| `/hooks` | `hooks/` | Manage hook scripts |
|
||||
| `/mock-limits` | `mock-limits/` | Mock rate limits for testing |
|
||||
| `/perf-issue` | `perf-issue/` | Report performance issues |
|
||||
| `/reset-limits` | `reset-limits/` | Reset rate limit counters |
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Architecture](architecture.md) — How the command system fits into the pipeline
|
||||
- [Tools Reference](tools.md) — Agent tools (different from slash commands)
|
||||
- [Exploration Guide](exploration-guide.md) — Finding command source code
|
||||
246
docs/exploration-guide.md
Normal file
246
docs/exploration-guide.md
Normal file
@@ -0,0 +1,246 @@
|
||||
# Exploration Guide
|
||||
|
||||
> How to navigate and study the Claude Code source code.
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
This is a **read-only reference codebase** — there's no build system or test suite. The goal is to understand how a production AI coding assistant is built.
|
||||
|
||||
### Orientation
|
||||
|
||||
| What | Where |
|
||||
|------|-------|
|
||||
| CLI entrypoint | `src/main.tsx` |
|
||||
| Core LLM engine | `src/QueryEngine.ts` (~46K lines) |
|
||||
| Tool definitions | `src/Tool.ts` (~29K lines) |
|
||||
| Command registry | `src/commands.ts` (~25K lines) |
|
||||
| Tool registry | `src/tools.ts` |
|
||||
| Context collection | `src/context.ts` |
|
||||
| All tool implementations | `src/tools/` (40 subdirectories) |
|
||||
| All command implementations | `src/commands/` (~85 subdirectories + 15 files) |
|
||||
|
||||
---
|
||||
|
||||
## Finding Things
|
||||
|
||||
### "How does tool X work?"
|
||||
|
||||
1. Go to `src/tools/{ToolName}/`
|
||||
2. Main implementation is `{ToolName}.ts` or `.tsx`
|
||||
3. UI rendering is in `UI.tsx`
|
||||
4. System prompt contribution is in `prompt.ts`
|
||||
|
||||
Example — understanding BashTool:
|
||||
```
|
||||
src/tools/BashTool/
|
||||
├── BashTool.ts ← Core execution logic
|
||||
├── UI.tsx ← How bash output renders in terminal
|
||||
├── prompt.ts ← What the system prompt says about bash
|
||||
└── ...
|
||||
```
|
||||
|
||||
### "How does command X work?"
|
||||
|
||||
1. Check `src/commands/{command-name}/` (directory) or `src/commands/{command-name}.ts` (file)
|
||||
2. Look for the `getPromptForCommand()` function (PromptCommands) or direct implementation (LocalCommands)
|
||||
|
||||
### "How does feature X work?"
|
||||
|
||||
| Feature | Start Here |
|
||||
|---------|-----------|
|
||||
| Permissions | `src/hooks/toolPermission/` |
|
||||
| IDE bridge | `src/bridge/bridgeMain.ts` |
|
||||
| MCP client | `src/services/mcp/` |
|
||||
| Plugin system | `src/plugins/` + `src/services/plugins/` |
|
||||
| Skills | `src/skills/` |
|
||||
| Voice input | `src/voice/` + `src/services/voice.ts` |
|
||||
| Multi-agent | `src/coordinator/` |
|
||||
| Memory | `src/memdir/` |
|
||||
| Authentication | `src/services/oauth/` |
|
||||
| Config schemas | `src/schemas/` |
|
||||
| State management | `src/state/` |
|
||||
|
||||
### "How does an API call flow?"
|
||||
|
||||
Trace from user input to API response:
|
||||
|
||||
```
|
||||
src/main.tsx ← CLI parsing
|
||||
→ src/replLauncher.tsx ← REPL session start
|
||||
→ src/QueryEngine.ts ← Core engine
|
||||
→ src/services/api/ ← Anthropic SDK client
|
||||
→ (Anthropic API) ← HTTP/streaming
|
||||
← Tool use response
|
||||
→ src/tools/{ToolName}/ ← Tool execution
|
||||
← Tool result
|
||||
→ (feed back to API) ← Continue the loop
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Code Patterns to Recognize
|
||||
|
||||
### `buildTool()` — Tool Factory
|
||||
|
||||
Every tool uses this pattern:
|
||||
|
||||
```typescript
|
||||
export const MyTool = buildTool({
|
||||
name: 'MyTool',
|
||||
inputSchema: z.object({ ... }),
|
||||
async call(args, context) { ... },
|
||||
async checkPermissions(input, context) { ... },
|
||||
})
|
||||
```
|
||||
|
||||
### Feature Flag Gates
|
||||
|
||||
```typescript
|
||||
import { feature } from 'bun:bundle'
|
||||
|
||||
if (feature('VOICE_MODE')) {
|
||||
// This code is stripped at build time if VOICE_MODE is off
|
||||
}
|
||||
```
|
||||
|
||||
### Anthropic-Internal Gates
|
||||
|
||||
```typescript
|
||||
if (process.env.USER_TYPE === 'ant') {
|
||||
// Anthropic employee-only features
|
||||
}
|
||||
```
|
||||
|
||||
### Index Re-exports
|
||||
|
||||
Most directories have an `index.ts` that re-exports the public API:
|
||||
|
||||
```typescript
|
||||
// src/tools/BashTool/index.ts
|
||||
export { BashTool } from './BashTool.js'
|
||||
```
|
||||
|
||||
### Lazy Dynamic Imports
|
||||
|
||||
Heavy modules are loaded only when needed:
|
||||
|
||||
```typescript
|
||||
const { OpenTelemetry } = await import('./heavy-module.js')
|
||||
```
|
||||
|
||||
### ESM with `.js` Extensions
|
||||
|
||||
Bun convention — all imports use `.js` extensions even for `.ts` files:
|
||||
|
||||
```typescript
|
||||
import { something } from './utils.js' // Actually imports utils.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Key Files by Size
|
||||
|
||||
The largest files contain the most logic and are worth studying:
|
||||
|
||||
| File | Lines | What's Inside |
|
||||
|------|-------|---------------|
|
||||
| `QueryEngine.ts` | ~46K | Streaming, tool loops, retries, token counting |
|
||||
| `Tool.ts` | ~29K | Tool types, `buildTool`, permission models |
|
||||
| `commands.ts` | ~25K | Command registry, conditional loading |
|
||||
| `main.tsx` | — | CLI parser, startup optimization |
|
||||
| `context.ts` | — | OS, shell, git, user context assembly |
|
||||
|
||||
---
|
||||
|
||||
## Study Paths
|
||||
|
||||
### Path 1: "How does a tool work end-to-end?"
|
||||
|
||||
1. Read `src/Tool.ts` — understand the `buildTool` interface
|
||||
2. Pick a simple tool like `FileReadTool` in `src/tools/FileReadTool/`
|
||||
3. Trace how `QueryEngine.ts` calls tools during the tool loop
|
||||
4. See how permissions are checked in `src/hooks/toolPermission/`
|
||||
|
||||
### Path 2: "How does the UI work?"
|
||||
|
||||
1. Read `src/screens/REPL.tsx` — the main screen
|
||||
2. Explore `src/components/` — pick a few components
|
||||
3. See `src/hooks/useTextInput.ts` — how user input is captured
|
||||
4. Check `src/ink/` — the Ink renderer wrapper
|
||||
|
||||
### Path 3: "How does the IDE integration work?"
|
||||
|
||||
1. Start at `src/bridge/bridgeMain.ts`
|
||||
2. Follow `bridgeMessaging.ts` for the message protocol
|
||||
3. See `bridgePermissionCallbacks.ts` for how permissions route to the IDE
|
||||
4. Check `replBridge.ts` for REPL session bridging
|
||||
|
||||
### Path 4: "How do plugins extend Claude Code?"
|
||||
|
||||
1. Read `src/types/plugin.ts` — the plugin API surface
|
||||
2. See `src/services/plugins/` — how plugins are loaded
|
||||
3. Check `src/plugins/builtinPlugins.ts` — built-in examples
|
||||
4. Look at `src/plugins/bundled/` — bundled plugin code
|
||||
|
||||
### Path 5: "How does MCP work?"
|
||||
|
||||
1. Read `src/services/mcp/` — the MCP client
|
||||
2. See `src/tools/MCPTool/` — how MCP tools are invoked
|
||||
3. Check `src/entrypoints/mcp.ts` — Claude Code as an MCP server
|
||||
4. Look at `src/skills/mcpSkillBuilders.ts` — skills from MCP
|
||||
|
||||
---
|
||||
|
||||
## Using the MCP Server for Exploration
|
||||
|
||||
This repo includes a standalone MCP server (`mcp-server/`) that lets any MCP-compatible client explore the source code. See the [MCP Server README](../mcp-server/README.md) for setup.
|
||||
|
||||
Once connected, you can ask an AI assistant to explore the source:
|
||||
|
||||
- "How does the BashTool work?"
|
||||
- "Search for where permissions are checked"
|
||||
- "List all files in the bridge directory"
|
||||
- "Read QueryEngine.ts lines 1-100"
|
||||
|
||||
---
|
||||
|
||||
## Grep Patterns
|
||||
|
||||
Useful grep/ripgrep patterns for finding things:
|
||||
|
||||
```bash
|
||||
# Find all tool definitions
|
||||
rg "buildTool\(" src/tools/
|
||||
|
||||
# Find all command definitions
|
||||
rg "satisfies Command" src/commands/
|
||||
|
||||
# Find feature flag usage
|
||||
rg "feature\(" src/
|
||||
|
||||
# Find Anthropic-internal gates
|
||||
rg "USER_TYPE.*ant" src/
|
||||
|
||||
# Find all React hooks
|
||||
rg "^export function use" src/hooks/
|
||||
|
||||
# Find all Zod schemas
|
||||
rg "z\.object\(" src/schemas/
|
||||
|
||||
# Find all system prompt contributions
|
||||
rg "prompt\(" src/tools/*/prompt.ts
|
||||
|
||||
# Find permission rule patterns
|
||||
rg "checkPermissions" src/tools/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Architecture](architecture.md) — Overall system design
|
||||
- [Tools Reference](tools.md) — Complete tool catalog
|
||||
- [Commands Reference](commands.md) — All slash commands
|
||||
- [Subsystems Guide](subsystems.md) — Deep dives into Bridge, MCP, Permissions, etc.
|
||||
346
docs/subsystems.md
Normal file
346
docs/subsystems.md
Normal file
@@ -0,0 +1,346 @@
|
||||
# Subsystems Guide
|
||||
|
||||
> Detailed documentation of Claude Code's major subsystems.
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Bridge (IDE Integration)](#bridge-ide-integration)
|
||||
- [MCP (Model Context Protocol)](#mcp-model-context-protocol)
|
||||
- [Permission System](#permission-system)
|
||||
- [Plugin System](#plugin-system)
|
||||
- [Skill System](#skill-system)
|
||||
- [Task System](#task-system)
|
||||
- [Memory System](#memory-system)
|
||||
- [Coordinator (Multi-Agent)](#coordinator-multi-agent)
|
||||
- [Voice System](#voice-system)
|
||||
- [Service Layer](#service-layer)
|
||||
|
||||
---
|
||||
|
||||
## Bridge (IDE Integration)
|
||||
|
||||
**Location:** `src/bridge/`
|
||||
|
||||
The bridge is a bidirectional communication layer connecting Claude Code's CLI with IDE extensions (VS Code, JetBrains). It allows the CLI to run as a backend for IDE-based interfaces.
|
||||
|
||||
### Architecture
|
||||
|
||||
```
|
||||
┌──────────────────┐ ┌──────────────────────┐
|
||||
│ IDE Extension │◄───────►│ Bridge Layer │
|
||||
│ (VS Code, JB) │ JWT │ (src/bridge/) │
|
||||
│ │ Auth │ │
|
||||
│ - UI rendering │ │ - Session mgmt │
|
||||
│ - File watching │ │ - Message routing │
|
||||
│ - Diff display │ │ - Permission proxy │
|
||||
└──────────────────┘ └──────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────────────┐
|
||||
│ Claude Code Core │
|
||||
│ (QueryEngine, Tools) │
|
||||
└──────────────────────┘
|
||||
```
|
||||
|
||||
### Key Files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `bridgeMain.ts` | Main bridge loop — starts the bidirectional channel |
|
||||
| `bridgeMessaging.ts` | Message protocol (serialize/deserialize) |
|
||||
| `bridgePermissionCallbacks.ts` | Routes permission prompts to the IDE |
|
||||
| `bridgeApi.ts` | API surface exposed to the IDE |
|
||||
| `bridgeConfig.ts` | Bridge configuration |
|
||||
| `replBridge.ts` | Connects the REPL session to the bridge |
|
||||
| `jwtUtils.ts` | JWT-based authentication between CLI and IDE |
|
||||
| `sessionRunner.ts` | Manages bridge session execution |
|
||||
| `createSession.ts` | Creates new bridge sessions |
|
||||
| `trustedDevice.ts` | Device trust verification |
|
||||
| `workSecret.ts` | Workspace-scoped secrets |
|
||||
| `inboundMessages.ts` | Handles messages coming from the IDE |
|
||||
| `inboundAttachments.ts` | Handles file attachments from the IDE |
|
||||
| `types.ts` | TypeScript types for the bridge protocol |
|
||||
|
||||
### Feature Flag
|
||||
|
||||
The bridge is gated behind the `BRIDGE_MODE` feature flag and is stripped from non-IDE builds.
|
||||
|
||||
---
|
||||
|
||||
## MCP (Model Context Protocol)
|
||||
|
||||
**Location:** `src/services/mcp/`
|
||||
|
||||
Claude Code acts as both an **MCP client** (consuming tools/resources from MCP servers) and can run as an **MCP server** (exposing its own tools via `src/entrypoints/mcp.ts`).
|
||||
|
||||
### Client Features
|
||||
|
||||
- **Tool discovery** — Enumerates tools from connected MCP servers
|
||||
- **Resource browsing** — Lists and reads MCP-exposed resources
|
||||
- **Dynamic tool loading** — `ToolSearchTool` discovers tools at runtime
|
||||
- **Authentication** — `McpAuthTool` handles MCP server auth flows
|
||||
- **Connectivity monitoring** — `useMcpConnectivityStatus` hook tracks connection health
|
||||
|
||||
### Server Mode
|
||||
|
||||
When launched via `src/entrypoints/mcp.ts`, Claude Code exposes its own tools and resources via the MCP protocol, allowing other AI agents to use Claude Code as a tool server.
|
||||
|
||||
### Related Tools
|
||||
|
||||
| Tool | Purpose |
|
||||
|------|---------|
|
||||
| `MCPTool` | Invoke tools on connected MCP servers |
|
||||
| `ListMcpResourcesTool` | List available MCP resources |
|
||||
| `ReadMcpResourceTool` | Read a specific MCP resource |
|
||||
| `McpAuthTool` | Authenticate with an MCP server |
|
||||
| `ToolSearchTool` | Discover deferred tools from MCP servers |
|
||||
|
||||
### Configuration
|
||||
|
||||
MCP servers are configured via `/mcp` command or settings files. The server approval flow lives in `src/services/mcpServerApproval.tsx`.
|
||||
|
||||
---
|
||||
|
||||
## Permission System
|
||||
|
||||
**Location:** `src/hooks/toolPermission/`
|
||||
|
||||
Every tool invocation passes through a centralized permission check before execution.
|
||||
|
||||
### Permission Modes
|
||||
|
||||
| Mode | Behavior |
|
||||
|------|----------|
|
||||
| `default` | Prompts the user for each potentially destructive operation |
|
||||
| `plan` | Shows the full execution plan, asks once for batch approval |
|
||||
| `bypassPermissions` | Auto-approves all operations (dangerous — for trusted environments) |
|
||||
| `auto` | ML-based classifier automatically decides (experimental) |
|
||||
|
||||
### How It Works
|
||||
|
||||
1. Tool is invoked by the Query Engine
|
||||
2. `checkPermissions(input, context)` is called on the tool
|
||||
3. Permission handler checks against configured rules
|
||||
4. If not auto-approved, user is prompted via terminal or IDE
|
||||
|
||||
### Permission Rules
|
||||
|
||||
Rules use wildcard patterns to match tool invocations:
|
||||
|
||||
```
|
||||
Bash(git *) # Allow all git commands without prompt
|
||||
Bash(npm test) # Allow 'npm test' specifically
|
||||
FileEdit(/src/*) # Allow edits to anything under src/
|
||||
FileRead(*) # Allow reading any file
|
||||
```
|
||||
|
||||
### Key Files
|
||||
|
||||
| File | Path |
|
||||
|------|------|
|
||||
| Permission context | `src/hooks/toolPermission/PermissionContext.ts` |
|
||||
| Permission handlers | `src/hooks/toolPermission/handlers/` |
|
||||
| Permission logging | `src/hooks/toolPermission/permissionLogging.ts` |
|
||||
| Permission types | `src/types/permissions.ts` |
|
||||
|
||||
---
|
||||
|
||||
## Plugin System
|
||||
|
||||
**Location:** `src/plugins/`, `src/services/plugins/`
|
||||
|
||||
Claude Code supports installable plugins that can extend its capabilities.
|
||||
|
||||
### Structure
|
||||
|
||||
| Component | Location | Purpose |
|
||||
|-----------|----------|---------|
|
||||
| Plugin loader | `src/services/plugins/` | Discovers and loads plugins |
|
||||
| Built-in plugins | `src/plugins/builtinPlugins.ts` | Plugins that ship with Claude Code |
|
||||
| Bundled plugins | `src/plugins/bundled/` | Plugin code bundled into the binary |
|
||||
| Plugin types | `src/types/plugin.ts` | TypeScript types for plugin API |
|
||||
|
||||
### Plugin Lifecycle
|
||||
|
||||
1. **Discovery** — Scans plugin directories and marketplace
|
||||
2. **Installation** — Downloaded and registered (`/plugin` command)
|
||||
3. **Loading** — Initialized at startup or on-demand
|
||||
4. **Execution** — Plugins can contribute tools, commands, and prompts
|
||||
5. **Auto-update** — `usePluginAutoupdateNotification` handles updates
|
||||
|
||||
### Related Commands
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `/plugin` | Install, remove, or manage plugins |
|
||||
| `/reload-plugins` | Reload all installed plugins |
|
||||
|
||||
---
|
||||
|
||||
## Skill System
|
||||
|
||||
**Location:** `src/skills/`
|
||||
|
||||
Skills are reusable, named workflows that bundle prompts and tool configurations for specific tasks.
|
||||
|
||||
### Structure
|
||||
|
||||
| Component | Location | Purpose |
|
||||
|-----------|----------|---------|
|
||||
| Bundled skills | `src/skills/bundled/` | Skills that ship with Claude Code |
|
||||
| Skill loader | `src/skills/loadSkillsDir.ts` | Loads skills from disk |
|
||||
| MCP skill builders | `src/skills/mcpSkillBuilders.ts` | Creates skills from MCP resources |
|
||||
| Skill registry | `src/skills/bundledSkills.ts` | Registration of all bundled skills |
|
||||
|
||||
### Bundled Skills (16)
|
||||
|
||||
| Skill | Purpose |
|
||||
|-------|---------|
|
||||
| `batch` | Batch operations across multiple files |
|
||||
| `claudeApi` | Direct Anthropic API interaction |
|
||||
| `claudeInChrome` | Chrome extension integration |
|
||||
| `debug` | Debugging workflows |
|
||||
| `keybindings` | Keybinding configuration |
|
||||
| `loop` | Iterative refinement loops |
|
||||
| `loremIpsum` | Generate placeholder text |
|
||||
| `remember` | Persist information to memory |
|
||||
| `scheduleRemoteAgents` | Schedule agents for remote execution |
|
||||
| `simplify` | Simplify complex code |
|
||||
| `skillify` | Create new skills from workflows |
|
||||
| `stuck` | Get unstuck when blocked |
|
||||
| `updateConfig` | Modify configuration programmatically |
|
||||
| `verify` / `verifyContent` | Verify code correctness |
|
||||
|
||||
### Execution
|
||||
|
||||
Skills are invoked via the `SkillTool` or the `/skills` command. Users can also create custom skills.
|
||||
|
||||
---
|
||||
|
||||
## Task System
|
||||
|
||||
**Location:** `src/tasks/`
|
||||
|
||||
Manages background and parallel work items — shell tasks, agent tasks, and teammate agents.
|
||||
|
||||
### Task Types
|
||||
|
||||
| Type | Location | Purpose |
|
||||
|------|----------|---------|
|
||||
| `LocalShellTask` | `LocalShellTask/` | Background shell command execution |
|
||||
| `LocalAgentTask` | `LocalAgentTask/` | Sub-agent running locally |
|
||||
| `RemoteAgentTask` | `RemoteAgentTask/` | Agent running on a remote machine |
|
||||
| `InProcessTeammateTask` | `InProcessTeammateTask/` | Parallel teammate agent |
|
||||
| `DreamTask` | `DreamTask/` | Background "dreaming" process |
|
||||
| `LocalMainSessionTask` | `LocalMainSessionTask.ts` | Main session as a task |
|
||||
|
||||
### Task Tools
|
||||
|
||||
| Tool | Purpose |
|
||||
|------|---------|
|
||||
| `TaskCreateTool` | Create a new background task |
|
||||
| `TaskUpdateTool` | Update task status |
|
||||
| `TaskGetTool` | Retrieve task details |
|
||||
| `TaskListTool` | List all tasks |
|
||||
| `TaskOutputTool` | Get task output |
|
||||
| `TaskStopTool` | Stop a running task |
|
||||
|
||||
---
|
||||
|
||||
## Memory System
|
||||
|
||||
**Location:** `src/memdir/`
|
||||
|
||||
Claude Code's persistent memory system, based on `CLAUDE.md` files.
|
||||
|
||||
### Memory Hierarchy
|
||||
|
||||
| Scope | Location | Purpose |
|
||||
|-------|----------|---------|
|
||||
| Project memory | `CLAUDE.md` in project root | Project-specific facts, conventions |
|
||||
| User memory | `~/.claude/CLAUDE.md` | User preferences, cross-project |
|
||||
| Extracted memories | `src/services/extractMemories/` | Auto-extracted from conversations |
|
||||
| Team memory sync | `src/services/teamMemorySync/` | Shared team knowledge |
|
||||
|
||||
### Related
|
||||
|
||||
- `/memory` command for managing memories
|
||||
- `remember` skill for persisting information
|
||||
- `useMemoryUsage` hook for tracking memory size
|
||||
|
||||
---
|
||||
|
||||
## Coordinator (Multi-Agent)
|
||||
|
||||
**Location:** `src/coordinator/`
|
||||
|
||||
Orchestrates multiple agents working in parallel on different aspects of a task.
|
||||
|
||||
### How It Works
|
||||
|
||||
- `coordinatorMode.ts` manages the coordinator lifecycle
|
||||
- `TeamCreateTool` and `TeamDeleteTool` manage agent teams
|
||||
- `SendMessageTool` enables inter-agent communication
|
||||
- `AgentTool` spawns sub-agents
|
||||
|
||||
Gated behind the `COORDINATOR_MODE` feature flag.
|
||||
|
||||
---
|
||||
|
||||
## Voice System
|
||||
|
||||
**Location:** `src/voice/`
|
||||
|
||||
Voice input/output support for hands-free interaction.
|
||||
|
||||
### Components
|
||||
|
||||
| File | Location | Purpose |
|
||||
|------|----------|---------|
|
||||
| Voice service | `src/services/voice.ts` | Core voice processing |
|
||||
| STT streaming | `src/services/voiceStreamSTT.ts` | Speech-to-text streaming |
|
||||
| Key terms | `src/services/voiceKeyterms.ts` | Domain-specific vocabulary |
|
||||
| Voice hooks | `src/hooks/useVoice.ts`, `useVoiceEnabled.ts`, `useVoiceIntegration.tsx` | React hooks |
|
||||
| Voice command | `src/commands/voice/` | `/voice` slash command |
|
||||
|
||||
Gated behind the `VOICE_MODE` feature flag.
|
||||
|
||||
---
|
||||
|
||||
## Service Layer
|
||||
|
||||
**Location:** `src/services/`
|
||||
|
||||
External integrations and shared services.
|
||||
|
||||
| Service | Path | Purpose |
|
||||
|---------|------|---------|
|
||||
| **API** | `api/` | Anthropic SDK client, file uploads, bootstrap |
|
||||
| **MCP** | `mcp/` | MCP client connections and tool discovery |
|
||||
| **OAuth** | `oauth/` | OAuth 2.0 authentication flow |
|
||||
| **LSP** | `lsp/` | Language Server Protocol manager |
|
||||
| **Analytics** | `analytics/` | GrowthBook feature flags, telemetry |
|
||||
| **Plugins** | `plugins/` | Plugin loader and marketplace |
|
||||
| **Compact** | `compact/` | Conversation context compression |
|
||||
| **Policy Limits** | `policyLimits/` | Organization rate limits/quota |
|
||||
| **Remote Settings** | `remoteManagedSettings/` | Enterprise managed settings sync |
|
||||
| **Token Estimation** | `tokenEstimation.ts` | Token count estimation |
|
||||
| **Team Memory** | `teamMemorySync/` | Team knowledge synchronization |
|
||||
| **Tips** | `tips/` | Contextual usage tips |
|
||||
| **Agent Summary** | `AgentSummary/` | Agent work summaries |
|
||||
| **Prompt Suggestion** | `PromptSuggestion/` | Suggested follow-up prompts |
|
||||
| **Session Memory** | `SessionMemory/` | Session-level memory |
|
||||
| **Magic Docs** | `MagicDocs/` | Documentation generation |
|
||||
| **Auto Dream** | `autoDream/` | Background ideation |
|
||||
| **x402** | `x402/` | x402 payment protocol |
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Architecture](architecture.md) — How subsystems connect in the core pipeline
|
||||
- [Tools Reference](tools.md) — Tools related to each subsystem
|
||||
- [Commands Reference](commands.md) — Commands for managing subsystems
|
||||
- [Exploration Guide](exploration-guide.md) — Finding subsystem source code
|
||||
173
docs/tools.md
Normal file
173
docs/tools.md
Normal file
@@ -0,0 +1,173 @@
|
||||
# Tools Reference
|
||||
|
||||
> Complete catalog of all ~40 agent tools in Claude Code.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Every tool lives in `src/tools/<ToolName>/` as a self-contained module. Each tool defines:
|
||||
|
||||
- **Input schema** — Zod-validated parameters
|
||||
- **Permission model** — What requires user approval
|
||||
- **Execution logic** — The tool's implementation
|
||||
- **UI components** — Terminal rendering for invocation and results
|
||||
- **Concurrency safety** — Whether it can run in parallel
|
||||
|
||||
Tools are registered in `src/tools.ts` and invoked by the Query Engine during LLM tool-call loops.
|
||||
|
||||
### Tool Definition Pattern
|
||||
|
||||
```typescript
|
||||
export const MyTool = buildTool({
|
||||
name: 'MyTool',
|
||||
aliases: ['my_tool'],
|
||||
description: 'What this tool does',
|
||||
inputSchema: z.object({
|
||||
param: z.string(),
|
||||
}),
|
||||
async call(args, context, canUseTool, parentMessage, onProgress) {
|
||||
// Execute and return { data: result, newMessages?: [...] }
|
||||
},
|
||||
async checkPermissions(input, context) { /* Permission checks */ },
|
||||
isConcurrencySafe(input) { /* Can run in parallel? */ },
|
||||
isReadOnly(input) { /* Non-destructive? */ },
|
||||
prompt(options) { /* System prompt injection */ },
|
||||
renderToolUseMessage(input, options) { /* UI for invocation */ },
|
||||
renderToolResultMessage(content, progressMessages, options) { /* UI for result */ },
|
||||
})
|
||||
```
|
||||
|
||||
**Directory structure per tool:**
|
||||
|
||||
```
|
||||
src/tools/MyTool/
|
||||
├── MyTool.ts # Main implementation
|
||||
├── UI.tsx # Terminal rendering
|
||||
├── prompt.ts # System prompt contribution
|
||||
└── utils.ts # Tool-specific helpers
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## File System Tools
|
||||
|
||||
| Tool | Description | Read-Only |
|
||||
|------|-------------|-----------|
|
||||
| **FileReadTool** | Read file contents (text, images, PDFs, notebooks). Supports line ranges | Yes |
|
||||
| **FileWriteTool** | Create or overwrite files | No |
|
||||
| **FileEditTool** | Partial file modification via string replacement | No |
|
||||
| **GlobTool** | Find files matching glob patterns (e.g. `**/*.ts`) | Yes |
|
||||
| **GrepTool** | Content search using ripgrep (regex-capable) | Yes |
|
||||
| **NotebookEditTool** | Edit Jupyter notebook cells | No |
|
||||
| **TodoWriteTool** | Write to a structured todo/task file | No |
|
||||
|
||||
## Shell & Execution Tools
|
||||
|
||||
| Tool | Description | Read-Only |
|
||||
|------|-------------|-----------|
|
||||
| **BashTool** | Execute shell commands in bash | No |
|
||||
| **PowerShellTool** | Execute PowerShell commands (Windows) | No |
|
||||
| **REPLTool** | Run code in a REPL session (Python, Node, etc.) | No |
|
||||
|
||||
## Agent & Orchestration Tools
|
||||
|
||||
| Tool | Description | Read-Only |
|
||||
|------|-------------|-----------|
|
||||
| **AgentTool** | Spawn a sub-agent for complex tasks | No |
|
||||
| **SendMessageTool** | Send messages between agents | No |
|
||||
| **TeamCreateTool** | Create a team of parallel agents | No |
|
||||
| **TeamDeleteTool** | Remove a team agent | No |
|
||||
| **EnterPlanModeTool** | Switch to planning mode (no execution) | No |
|
||||
| **ExitPlanModeTool** | Exit planning mode, resume execution | No |
|
||||
| **EnterWorktreeTool** | Isolate work in a git worktree | No |
|
||||
| **ExitWorktreeTool** | Exit worktree isolation | No |
|
||||
| **SleepTool** | Pause execution (proactive mode) | Yes |
|
||||
| **SyntheticOutputTool** | Generate structured output | Yes |
|
||||
|
||||
## Task Management Tools
|
||||
|
||||
| Tool | Description | Read-Only |
|
||||
|------|-------------|-----------|
|
||||
| **TaskCreateTool** | Create a new background task | No |
|
||||
| **TaskUpdateTool** | Update a task's status or details | No |
|
||||
| **TaskGetTool** | Get details of a specific task | Yes |
|
||||
| **TaskListTool** | List all tasks | Yes |
|
||||
| **TaskOutputTool** | Get output from a completed task | Yes |
|
||||
| **TaskStopTool** | Stop a running task | No |
|
||||
|
||||
## Web Tools
|
||||
|
||||
| Tool | Description | Read-Only |
|
||||
|------|-------------|-----------|
|
||||
| **WebFetchTool** | Fetch content from a URL | Yes |
|
||||
| **WebSearchTool** | Search the web | Yes |
|
||||
|
||||
## MCP (Model Context Protocol) Tools
|
||||
|
||||
| Tool | Description | Read-Only |
|
||||
|------|-------------|-----------|
|
||||
| **MCPTool** | Invoke tools on connected MCP servers | Varies |
|
||||
| **ListMcpResourcesTool** | List resources exposed by MCP servers | Yes |
|
||||
| **ReadMcpResourceTool** | Read a specific MCP resource | Yes |
|
||||
| **McpAuthTool** | Handle MCP server authentication | No |
|
||||
| **ToolSearchTool** | Discover deferred/dynamic tools from MCP servers | Yes |
|
||||
|
||||
## Integration Tools
|
||||
|
||||
| Tool | Description | Read-Only |
|
||||
|------|-------------|-----------|
|
||||
| **LSPTool** | Language Server Protocol operations (go-to-definition, find references, etc.) | Yes |
|
||||
| **SkillTool** | Execute a registered skill | Varies |
|
||||
|
||||
## Scheduling & Triggers
|
||||
|
||||
| Tool | Description | Read-Only |
|
||||
|------|-------------|-----------|
|
||||
| **ScheduleCronTool** | Create a scheduled cron trigger | No |
|
||||
| **RemoteTriggerTool** | Fire a remote trigger | No |
|
||||
|
||||
## Utility Tools
|
||||
|
||||
| Tool | Description | Read-Only |
|
||||
|------|-------------|-----------|
|
||||
| **AskUserQuestionTool** | Prompt the user for input during execution | Yes |
|
||||
| **BriefTool** | Generate a brief/summary | Yes |
|
||||
| **ConfigTool** | Read or modify Claude Code configuration | No |
|
||||
|
||||
---
|
||||
|
||||
## Permission Model
|
||||
|
||||
Every tool invocation passes through the permission system (`src/hooks/toolPermission/`). Permission modes:
|
||||
|
||||
| Mode | Behavior |
|
||||
|------|----------|
|
||||
| `default` | Prompt the user for each potentially destructive operation |
|
||||
| `plan` | Show the full plan, ask once |
|
||||
| `bypassPermissions` | Auto-approve everything (dangerous) |
|
||||
| `auto` | ML-based classifier decides |
|
||||
|
||||
Permission rules use wildcard patterns:
|
||||
|
||||
```
|
||||
Bash(git *) # Allow all git commands
|
||||
FileEdit(/src/*) # Allow edits to anything in src/
|
||||
FileRead(*) # Allow reading any file
|
||||
```
|
||||
|
||||
Each tool implements `checkPermissions()` returning `{ granted: boolean, reason?, prompt? }`.
|
||||
|
||||
---
|
||||
|
||||
## Tool Presets
|
||||
|
||||
Tools are grouped into presets in `src/tools.ts` for different contexts (e.g. read-only tools for code review, full toolset for development).
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Architecture](architecture.md) — How tools fit into the overall pipeline
|
||||
- [Subsystems Guide](subsystems.md) — MCP, permissions, and other tool-related subsystems
|
||||
- [Exploration Guide](exploration-guide.md) — How to read tool source code
|
||||
Reference in New Issue
Block a user