collection-claude-code-source-code
```markdown
What this skill does
```markdown --- name: collection-claude-code-source-code description: A collection and analysis of Claude Code open source artifacts, including decompiled TypeScript source (v2.1.88) and a Python clean-room rewrite reference triggers: - explore claude code source code - understand how claude code works internally - study claude code architecture - analyze claude code tool system - learn claude code agent loop - implement claude code patterns - reference claude code slash commands - build something like claude code --- # Collection: Claude Code Source Code > Skill by [ara.so](https://ara.so) — Daily 2026 Skills collection. This repository archives and analyzes the internals of Anthropic's Claude Code CLI tool (`@anthropic-ai/[email protected]`), providing ~163,318 lines of reconstructed TypeScript source plus a clean-room Python rewrite for study. Use this collection to understand how a production AI coding agent is architected, how its tool system works, and how to replicate its patterns in your own projects. --- ## Repository Structure ``` collection-claude-code-source-code/ ├── claude-code-source-code/ # Decompiled TypeScript source (v2.1.88) │ └── src/ │ ├── main.tsx # CLI entry + REPL bootstrap (~4,683 lines) │ ├── query.ts # Core agent loop (~785KB) │ ├── QueryEngine.ts # SDK/Headless query lifecycle │ ├── Tool.ts # Tool interface + buildTool factory │ ├── commands.ts # Slash command definitions (~25K lines) │ ├── tools/ # 40+ tool implementations │ ├── components/ # React/Ink terminal UI │ ├── services/ # Business logic layer │ ├── coordinator/ # Multi-agent coordination │ ├── memdir/ # Long-term memory management │ └── plugins/ # Plugin system ├── claw-code/ # Clean-room Python rewrite (66 files) └── docs/ # Analysis docs (English + Chinese) ├── en/ └── zh/ ``` --- ## Installation / Setup ```bash # Clone the collection git clone https://github.com/chauncygu/collection-claude-code-source-code.git cd collection-claude-code-source-code # Install the actual Claude Code CLI (official) npm install -g @anthropic-ai/claude-code # Or explore the TypeScript source directly cd claude-code-source-code npm install ``` Set your Anthropic API key before using Claude Code: ```bash export ANTHROPIC_API_KEY=your_key_here ``` --- ## Core Architecture Patterns ### Agent Loop (query.ts) The central loop drives all agent behavior. Key stages: ```typescript // Simplified representation of the main agent loop pattern from query.ts async function* query( input: UserInput, context: AgentContext ): AsyncGenerator<SDKMessage> { // 1. Assemble system prompt const systemPromptParts = await fetchSystemPromptParts(context); // 2. Stream Claude API response const stream = client.messages.stream({ model: context.model, system: systemPromptParts.join('\n'), messages: context.history, tools: context.tools, }); // 3. Execute tools in parallel as they arrive const executor = new StreamingToolExecutor(); for await (const event of stream) { if (event.type === 'tool_use') { yield* executor.run(event, context); } else { yield event; } } // 4. Auto-compact context if token limit approaches await autoCompact(context); } ``` ### Tool Interface (Tool.ts) Every tool follows this contract: ```typescript interface Tool<TInput, TOutput> { name: string; description: string; inputSchema: ZodSchema<TInput>; call(input: TInput, context: ToolContext): Promise<TOutput>; isReadOnly?: boolean; requiresPermission?: boolean; } // Build a tool using the factory const MyFileTool = buildTool({ name: 'read_file', description: 'Read a file from disk', inputSchema: z.object({ path: z.string().describe('Absolute path to file'), }), async call({ path }, context) { const content = await fs.readFile(path, 'utf-8'); return { content, lines: content.split('\n').length }; }, }); ``` ### Implementing a Custom Tool (TypeScript) ```typescript import { z } from 'zod'; import { buildTool } from './src/Tool'; export const WebhookTool = buildTool({ name: 'send_webhook', description: 'Send a POST request to a webhook URL with a JSON payload', inputSchema: z.object({ url: z.string().url(), payload: z.record(z.unknown()), }), isReadOnly: false, requiresPermission: true, async call({ url, payload }, _context) { const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), }); return { status: res.status, ok: res.ok, body: await res.text(), }; }, }); ``` --- ## Key Tool Categories | Category | Tools | |---|---| | File Operations | `FileReadTool`, `FileEditTool`, `FileWriteTool` | | Code Search | `GlobTool`, `GrepTool` | | System Execution | `BashTool` | | Web Access | `WebFetchTool`, `WebSearchTool` | | Task Management | `TaskCreateTool`, `TaskUpdateTool`, `TaskGetTool`, `TaskListTool` | | Sub-agents | `AgentTool` | | Code Environments | `NotebookEditTool`, `REPLTool`, `LSPTool` | | Git Workflow | `EnterWorktreeTool`, `ExitWorktreeTool` | | Memory & Planning | `TodoWriteTool`, `EnterPlanModeTool`, `ExitPlanModeTool` | | Automation | `ScheduleCronTool`, `RemoteTriggerTool`, `SleepTool` | | MCP Integration | `MCPTool` | --- ## Permission System Three enforcement modes control tool access: ```typescript type PermissionMode = 'default' | 'bypass' | 'strict'; // default → ask the user before executing sensitive tools // bypass → auto-allow all tools (headless/CI use) // strict → auto-deny all tools requiring permissions // Example: configuring permissions in headless mode const context: AgentContext = { permissionMode: 'bypass', // useful in CI pipelines toolPermissions: { BashTool: 'allow', FileWriteTool: 'ask', WebFetchTool: 'deny', }, }; ``` --- ## Context Compression Strategies Claude Code uses three auto-compaction strategies when context grows large: ```typescript // From autoCompact() in query.ts — simplified async function autoCompact(context: AgentContext) { const tokenCount = estimateTokens(context.history); if (tokenCount > REACTIVE_THRESHOLD) { // Strategy 1: Reactive — summarize old turns context.history = await summarizeOldTurns(context.history); } if (tokenCount > MICRO_THRESHOLD) { // Strategy 2: Micro — strip whitespace + comments context.history = microCompress(context.history); } if (tokenCount > COLLAPSE_THRESHOLD) { // Strategy 3: Collapse — keep only key tool results context.history = collapseContext(context.history); } } ``` --- ## Slash Commands Reference Claude Code exposes ~87 slash commands. Key ones: | Command | Purpose | |---|---| | `/commit` | Stage and commit changes | | `/commit-push-pr` | Commit, push, and open a PR | | `/review` | AI code review of current diff | | `/resume` | Resume a previous session | | `/session` | Manage session state | | `/memory` | View/edit long-term memory | | `/config` | Adjust configuration | | `/skills` | Manage installed skills | | `/permissions` | Manage tool permissions | | `/mcp` | Model Context Protocol tools | | `/vim` | Toggle Vim keybindings | | `/voice` | Toggle voice mode | ### Implementing a Custom Slash Command ```typescript // Pattern from src/commands/ directory export const myCommand = { name: 'deploy', description: 'Deploy the current project to production', aliases: ['/deploy'], async execute(args: string[], context: CommandContext) { const env = args[0] ?? 'staging'; await context.runTool('BashTool', { command: `./scripts/deploy.sh ${env}`, }); return `Deployed to ${env}`; }, }; ``` --- ## Memory System (memdir/) Claude Code implements 7 layer
Related in Writing & Docs
jax-development
IncludedUse this skill when the user is writing, debugging, profiling, refactoring, reviewing, benchmarking, parallelising, exporting, or explaining JAX code, or when they mention JAX, jax.numpy, jit, grad, value_and_grad, vmap, scan, lax, random keys, pytrees, jax.Array, sharding, Mesh, PartitionSpec, NamedSharding, pmap, shard_map, Pallas, XLA, StableHLO, checkify, profiler, or the JAX repo. It helps turn NumPy or PyTorch-style code into pure functional JAX, fix tracer/control-flow/shape/PRNG bugs, remove recompiles and host-device syncs, choose transforms and sharding strategies, inspect jaxpr/lowering/IR, and benchmark compiled code correctly.
nature-article-writer
IncludedDrafts, rewrites, diagnostically critiques, and style-calibrates primary research manuscripts for Nature and Nature Portfolio journals. Use when the user wants a Nature-style title, summary paragraph or abstract, introduction, results, discussion, methods, figure legends, presubmission enquiry, cover letter, reviewer response, or when a scientific draft sounds generic, jargon-heavy, structurally weak, or AI-ish and needs precise, broad-reader-friendly prose without inventing data, analyses, or references. Best for primary research articles and letters rather than reviews or press releases unless explicitly adapting one.
deckrd
IncludedDocument-driven framework that derives requirements, specifications, implementation plans, and executable tasks from goals through structured AI dialogue. Use when user says "write requirements", "create spec", "plan implementation", "derive tasks", "structure this feature", "break down into tasks", or "document this module". Also use for reverse engineering existing code into docs (/deckrd rev). Do NOT use for direct code writing — use /deckrd-coder after tasks are generated. Do NOT use when the user only wants to run or fix existing code without planning.
clinical-decision-support
IncludedGenerate professional clinical decision support (CDS) documents for pharmaceutical and clinical research settings, including patient cohort analyses (biomarker-stratified with outcomes) and treatment recommendation reports (evidence-based guidelines with decision algorithms). Supports GRADE evidence grading, statistical analysis (hazard ratios, survival curves, waterfall plots), biomarker integration, and regulatory compliance. Outputs publication-ready LaTeX/PDF format optimized for drug development, clinical research, and evidence synthesis.
handling-sf-data
IncludedSalesforce data operations with 130-point scoring. Use this skill to create, update, delete, bulk import/export, generate test data, and clean up org records using sf CLI and anonymous Apex. TRIGGER when: user creates test data, performs bulk import/export, uses sf data CLI commands, needs data factory patterns for Apex tests, or needs to seed/clean records in a Salesforce org. DO NOT TRIGGER when: SOQL query writing only (use querying-soql), Apex test execution (use running-apex-tests), or metadata deployment (use deploying-metadata).
accelint-ac-to-playwright
IncludedConvert and validate acceptance criteria for Playwright test automation. Use when user asks to (1) review/evaluate/check if AC are ready for automation, (2) assess if AC can be converted as-is, (3) validate AC quality for Playwright, (4) turn AC into tests, (5) generate tests from acceptance criteria, (6) convert .md bullets or .feature Gherkin files to Playwright specs, (7) create test automation from requirements. Handles both bullet-style markdown and Gherkin syntax with JSON test plan generation and validation.