Claude
Skills
Sign in
Back

claude-code-source-analysis

Included with Lifetime
$97 forever

```markdown

Writing & Docs

What this skill does

```markdown
---
name: claude-code-source-analysis
description: Expertise in exploring, understanding, and extending the Claude Code decompiled source archive and its Python reimplementation (claw-code)
triggers:
  - explore claude code source code
  - understand claude code architecture
  - analyze claude code internals
  - work with claude code tools system
  - study claude code agent loop
  - implement claude code patterns
  - extend claude code slash commands
  - understand claude code memory system
---

# Claude Code Source Code Collection

> Skill by [ara.so](https://ara.so) — Daily 2026 Skills collection

A research repository containing the decompiled TypeScript source of Claude Code v2.1.88 (~163,318 lines across 1,884 files) and a clean-room Python reimplementation (`claw-code`). Use this repository to study, extend, or reimplement Anthropic's CLI coding agent.

---

## Repository Structure

```
collection-claude-code-source-code/
├── claude-code-source-code/   # Decompiled TypeScript (v2.1.88)
│   └── src/
│       ├── main.tsx           # CLI entry + REPL bootstrap
│       ├── query.ts           # Core agent loop (785KB)
│       ├── QueryEngine.ts     # SDK/Headless lifecycle engine
│       ├── Tool.ts            # Tool interface + buildTool factory
│       ├── commands.ts        # Slash command definitions
│       ├── tools/             # 40+ tool implementations
│       ├── commands/          # ~87 slash command handlers
│       ├── components/        # React/Ink terminal UI
│       ├── services/          # Business logic layer
│       ├── coordinator/       # Multi-agent coordination
│       ├── memdir/            # Long-term memory management
│       └── plugins/           # Plugin system
├── claw-code/                 # Python clean-room rewrite (66 files)
└── docs/                      # Bilingual analysis (en/ + zh/)
```

---

## Installation & Setup

```bash
# Clone the repository
git clone https://github.com/chauncygu/collection-claude-code-source-code.git
cd collection-claude-code-source-code

# Explore the TypeScript source
cd claude-code-source-code
npm install   # if package.json dependencies are needed for tooling

# Work with the Python rewrite
cd ../claw-code
pip install -r requirements.txt
```

---

## Core Architecture: The Agent Loop

The central execution model lives in `src/query.ts`. Understanding it is key to understanding the whole system.

```typescript
// Simplified agent loop pattern from query.ts
async function* query(
  userMessage: string,
  context: ConversationContext,
  tools: Tool[],
): AsyncGenerator<SDKMessage> {
  // 1. Assemble system prompt from parts
  const systemPromptParts = await fetchSystemPromptParts(context);

  // 2. Run streaming tool executor with auto-compaction
  const executor = new StreamingToolExecutor(tools);

  while (true) {
    const response = await callClaude({ systemPromptParts, userMessage, tools });

    // 3. Yield streamed messages back to consumer
    for await (const chunk of response) {
      yield chunk;
    }

    // 4. Execute tool calls in parallel
    const toolResults = await executor.runTools(response.toolCalls);

    // 5. Auto-compact context if approaching token limit
    if (shouldCompact(context)) {
      await autoCompact(context);
    }

    if (!hasMoreToolCalls(response)) break;
  }
}
```

### Entry Point Pattern (`main.tsx`)

```typescript
// CLI bootstrap pattern
import { render } from 'ink';
import { App } from './components/App';

async function main() {
  const args = parseArgs(process.argv.slice(2));

  if (args.headless) {
    // SDK/headless mode via QueryEngine
    const engine = new QueryEngine(args);
    await engine.run();
  } else {
    // Interactive REPL mode via React/Ink
    render(<App initialArgs={args} />);
  }
}

main().catch(console.error);
```

---

## Tool System

### Tool Interface (`src/Tool.ts`)

```typescript
interface Tool {
  name: string;
  description: string;
  inputSchema: ZodSchema;
  execute(input: unknown, context: ToolContext): Promise<ToolResult>;
}

// buildTool factory pattern
const MyTool = buildTool({
  name: 'my_tool',
  description: 'Does something useful',
  inputSchema: z.object({
    path: z.string().describe('File path to operate on'),
    content: z.string().optional(),
  }),
  async execute({ path, content }, ctx) {
    // tool implementation
    return { type: 'text', text: `Processed ${path}` };
  },
});
```

### Key Built-in Tools

```typescript
// File operations
import { FileReadTool }  from './tools/FileReadTool';
import { FileEditTool }  from './tools/FileEditTool';
import { FileWriteTool } from './tools/FileWriteTool';

// Code search
import { GlobTool } from './tools/GlobTool';
import { GrepTool } from './tools/GrepTool';

// Execution
import { BashTool } from './tools/BashTool';

// Web
import { WebFetchTool }  from './tools/WebFetchTool';
import { WebSearchTool } from './tools/WebSearchTool';

// Sub-agents
import { AgentTool } from './tools/AgentTool';

// Memory
import { TodoWriteTool } from './tools/TodoWriteTool';
```

### Registering Tools (`src/tools.ts`)

```typescript
// Tool registration pattern
export function getTools(config: Config): Tool[] {
  const baseTools = [
    FileReadTool,
    FileEditTool,
    FileWriteTool,
    GlobTool,
    GrepTool,
    BashTool,
  ];

  if (config.enableWebTools) {
    baseTools.push(WebFetchTool, WebSearchTool);
  }

  if (config.enableAgentTools) {
    baseTools.push(AgentTool);
  }

  return baseTools;
}
```

---

## Slash Commands

### Command Definition Pattern (`src/commands/`)

```typescript
// Pattern for defining a slash command
export const reviewCommand = {
  name: 'review',
  description: 'Review code changes',
  aliases: ['/review'],
  async execute(args: string[], context: CommandContext) {
    const diff = await context.tools.bash.execute('git diff HEAD');
    return context.query(`Please review these changes:\n${diff}`);
  },
};

// Registration in commands.ts
export const SLASH_COMMANDS = [
  reviewCommand,
  commitCommand,
  sessionCommand,
  memoryCommand,
  configCommand,
  // ... ~87 total
];
```

### Common Slash Commands Reference

| Command | Purpose |
|---|---|
| `/commit` | Stage and commit changes |
| `/commit-push-pr` | Commit, push, and open PR |
| `/review` | Review current diff |
| `/resume` | Resume last session |
| `/memory` | Manage long-term memory |
| `/config` | Edit configuration |
| `/skills` | List available skills |
| `/permissions` | Manage tool permissions |
| `/mcp` | MCP server management |
| `/vim` | Toggle vim keybindings |

---

## Permission System

```typescript
// Three permission modes
type PermissionMode = 'default' | 'bypass' | 'strict';

// default  → ask user before executing sensitive tools
// bypass   → auto-allow all tools (headless/CI use)
// strict   → auto-deny all unwhitelisted tools

// Permission rule structure
interface PermissionRule {
  tool: string;           // e.g. 'bash', 'file_write'
  pattern?: string;       // glob pattern for path-based rules
  mode: PermissionMode;
}

// Checking permissions at runtime
async function checkPermission(
  tool: Tool,
  input: unknown,
  rules: PermissionRule[],
): Promise<'allow' | 'deny' | 'ask'> {
  const matchingRule = rules.find(r => matchesRule(r, tool, input));
  if (matchingRule) return matchingRule.mode === 'bypass' ? 'allow' : 'deny';
  return 'ask'; // default: prompt user
}
```

---

## Context Management & Auto-Compaction

```typescript
// Auto-compact strategies from query.ts
type CompactionStrategy =
  | 'reactive'   // compress when near token limit
  | 'micro'      // compress small incremental chunks
  | 'trimmed';   // trim oldest turns first

async function autoCompact(
  context: ConversationContext,
  strategy: CompactionStrategy = 'reactive',
): Promise<void> {
  const tokenCount = await estimateTokens(context.messages);

  if (tokenCount > CONTEXT_COLLAPSE_THRESHOLD) {
    const summary = await summarizeHistory(context.mess

Related in Writing & Docs