Claude
Skills
Sign in
Back

claude-code-deep-dive

Included with Lifetime
$97 forever

```markdown

Writing & Docs

What this skill does

```markdown
---
name: claude-code-deep-dive
description: Expertise in the Claude Code deep dive research report — navigating the extracted source, understanding the agent architecture, prompt assembly system, tool execution pipeline, and all major subsystems reverse-engineered from the npm package source map.
triggers:
  - "explain how Claude Code works internally"
  - "show me the claude code architecture"
  - "how does claude code assemble its system prompt"
  - "explain the agent tool and subagent system"
  - "how do skills plugins and hooks work in claude code"
  - "walk me through the tool execution pipeline"
  - "what files are in the extracted source"
  - "how does claude code handle permissions and mcp"
---

# Claude Code Deep Dive

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

## What This Project Is

This repository is a **systematic reverse-engineering research report** of `@anthropic-ai/claude-code` — reconstructed from the `cli.js.map` source map bundled inside the published npm package. The map's `sourcesContent` field contained **4,756 original TypeScript source files**, making full architectural analysis possible.

The report covers:
- Complete source structure of Claude Code
- How the system prompt is dynamically assembled
- The AgentTool / SkillTool protocol
- Built-in agent roles and the agent dispatch chain
- Plugin / Skill / Hook / MCP runtime integration
- Permission and tool execution pipelines
- Why Claude Code behaves more like an Agent Operating System than a simple CLI wrapper

### Primary Artifacts

| Path | Description |
|---|---|
| `claude-code-deep-dive-xelatex.pdf` | Full research report (PDF) |
| `extracted-source/` | All 4,756 reconstructed TypeScript source files |
| `extracted-source/src/constants/prompts.ts` | Main system prompt assembly |
| `extracted-source/src/tools/AgentTool/` | Agent dispatch system |
| `extracted-source/src/tools/SkillTool/` | Skill invocation system |
| `extracted-source/src/services/tools/` | Tool execution + hook pipeline |

---

## Navigating the Extracted Source

```bash
# Clone the repo
git clone https://github.com/tvytlx/claude-code-deep-dive.git
cd claude-code-deep-dive

# Top-level source layout
ls extracted-source/src/
# entrypoints/   constants/   tools/   services/   utils/
# commands/      components/  coordinator/  memdir/
# plugins/       hooks/       bootstrap/    tasks/
```

### Key File Locations

```
extracted-source/src/
├── constants/
│   └── prompts.ts                    # ← THE main system prompt assembler
├── tools/
│   ├── AgentTool/
│   │   ├── AgentTool.tsx             # Agent tool definition + UI
│   │   ├── runAgent.ts               # Agent execution loop
│   │   └── prompt.ts                 # Agent-specific prompt fragments
│   ├── SkillTool/
│   │   ├── SkillTool.tsx
│   │   └── prompt.ts
│   ├── FileRead.ts
│   ├── FileEdit.ts
│   ├── FileWrite.ts
│   ├── Bash.ts
│   ├── Glob.ts
│   ├── Grep.ts
│   └── TodoWrite.ts
├── services/
│   ├── tools/
│   │   ├── toolExecution.ts          # Full tool execution pipeline
│   │   └── toolHooks.ts             # Pre/post hook integration
│   └── mcp/                         # MCP bridge
├── entrypoints/
│   ├── cli.tsx                       # Main CLI entry
│   ├── init.ts
│   ├── mcp.ts                        # MCP server mode
│   └── sdk/                          # SDK consumer entry
└── commands.ts                       # All slash commands registered
```

---

## Core Architecture Concepts

### 1. System Prompt Assembly (`prompts.ts`)

Claude Code does **not** use a static system prompt. `getSystemPrompt()` is a runtime assembler:

```typescript
// Conceptual reconstruction of getSystemPrompt()
function getSystemPrompt(context: SessionContext): string {
  // STATIC PREFIX — suitable for prompt caching
  const staticSections = [
    getSimpleIntroSection(),           // Identity + CYBER_RISK_INSTRUCTION
    getSimpleSystemSection(),          // Runtime rules (hooks, compression, tags)
    getSimpleDoingTasksSection(),      // Engineering behavior constraints
    getActionsSection(),               // Risk/destructive action rules
    getUsingYourToolsSection(),        // Tool grammar (FileRead > cat, etc.)
    getSimpleToneAndStyleSection(),
    getOutputEfficiencySection(),
  ].join('\n');

  // DYNAMIC SUFFIX — session-specific, NOT cached
  // Boundary: SYSTEM_PROMPT_DYNAMIC_BOUNDARY
  const dynamicSections = [
    getSessionSpecificGuidanceSection(context),  // Current tool set + feature gates
    getMemorySection(context),
    getEnvInfoSection(context),
    getLanguageSection(context),
    getOutputStyleSection(context),
    getMcpInstructionsSection(context),
    getScratchpadSection(context),
    getFunctionResultClearingSection(context),
    getTokenBudgetSection(context),
  ].filter(Boolean).join('\n');

  return staticSections + SYSTEM_PROMPT_DYNAMIC_BOUNDARY + dynamicSections;
}
```

**Key insight**: The `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` marker separates cache-friendly static content from per-session dynamic content. Moving content across this boundary has cost implications.

### 2. Agent Dispatch Chain

```
User Request
     │
     ▼
AgentTool.tsx          ← tool definition, permission check, UI rendering
     │
     ▼
runAgent.ts            ← spawns isolated agent context
     │  - forks session state
     │  - injects agent-specific system prompt (prompt.ts)
     │  - sets up sub-tool allowlist
     ▼
query()                ← model inference loop (shared with main loop)
     │
     ▼
toolExecution.ts       ← same pipeline as main agent
```

```typescript
// Simplified agent invocation pattern (from AgentTool reconstruction)
const agentResult = await runAgent({
  task: toolInput.task,
  parentSession: currentSession,
  allowedTools: resolveAgentTools(context),   // Subset of parent tools
  agentPrompt: getAgentPrompt(agentType),     // From AgentTool/prompt.ts
  mcpTools: filteredMcpTools,
});
```

### 3. Tool Execution Pipeline

Every tool call (including MCP tools) passes through:

```
Model emits tool_use block
         │
         ▼
toolExecution.ts
  ├── 1. Permission check (permission mode + user grants)
  ├── 2. Pre-execution hooks (toolHooks.ts → external hook scripts)
  ├── 3. Actual tool.call() invocation
  ├── 4. Post-execution hooks
  ├── 5. Analytics event emission
  └── 6. Result returned as tool_result block
```

```typescript
// Conceptual pipeline (reconstructed from toolExecution.ts)
async function executeTool(tool: Tool, input: unknown, ctx: ExecContext) {
  // Step 1: Permission
  const permitted = await checkPermission(tool, input, ctx);
  if (!permitted) return permissionDeniedResult(tool);

  // Step 2: Pre-hook
  const hookDecision = await runPreHooks(tool, input, ctx);
  if (hookDecision.block) return hookDecision.result;

  // Step 3: Execute
  const result = await tool.call(input, ctx);

  // Step 4: Post-hook
  await runPostHooks(tool, input, result, ctx);

  // Step 5: Analytics
  emitToolEvent(tool.name, input, result);

  return result;
}
```

### 4. Built-in Agent Types

From `AgentTool/prompt.ts` and session guidance sections:

| Agent Type | Role |
|---|---|
| Default subagent | General task execution with full tool access |
| Explore agent | Read-only codebase exploration |
| Plan agent | Task decomposition and planning (no file writes) |
| Verification agent | Mandatory post-task verification contract |
| Review agent | Code review with structured output |

### 5. Skill System

Skills are **prompt-native workflow packages** — not just documentation:

```typescript
// SkillTool invocation (reconstructed)
interface SkillInvocation {
  skillName: string;        // e.g. "fix-tests"
  args: Record<string, string>;
}

// Skills contribute to command system at startup
const allCommands = [
  ...builtinCommands,
  ...pluginCommands,
  ...skillCommands,          // Slash commands from installed skills
  ...bundledSkills,
  ...dynamicSkills,          // Disc

Related in Writing & Docs