Claude
Skills
Sign in
Back

ai-agent-deep-dive

Included with Lifetime
$97 forever

```markdown

AI Agents

What this skill does

```markdown
---
name: ai-agent-deep-dive
description: Research notes and analysis on modern Coding Agent architecture — covers prompt systems, agent orchestration, skills, plugins, hooks, MCP, and tool execution pipelines as seen in Claude Code.
triggers:
  - help me understand how Claude Code works internally
  - explain the architecture of a coding agent
  - how does agent orchestration work in Claude Code
  - what is the MCP integration pattern for agents
  - how do skills and plugins work in coding agents
  - explain the system prompt assembly for AI agents
  - how does tool permission and hook execution work
  - I want to build a coding agent like Claude Code
---

# AI Agent Deep Dive

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

A structured research report and analysis of modern Coding Agent architecture, using Claude Code as the primary reference. This repository contains a PDF report and annotated notes covering prompt engineering, agent orchestration, tool execution pipelines, permission models, and extensibility systems (Skills, Plugins, Hooks, MCP).

---

## What This Project Is

This is **not a runnable library** — it is a **deep-dive research document** (`ai-agent-deep-dive-report.pdf`) analyzing how a mature Coding Agent (Claude Code) works from an architectural perspective. It is useful for:

- Developers building their own coding agents
- Teams designing agent orchestration systems
- Engineers integrating MCP, hooks, or tool pipelines
- Researchers studying production-grade LLM agent systems

The core thesis: *Claude Code's strength is not a clever system prompt — it is a complete Agent Operating System.*

---

## How to Access the Report

```bash
# Clone the repository
git clone https://github.com/tvytlx/ai-agent-deep-dive.git
cd ai-agent-deep-dive

# Open the PDF report (primary artifact)
open ai-agent-deep-dive-report.pdf
# or
xdg-open ai-agent-deep-dive-report.pdf  # Linux
```

The README itself also contains the full annotated notes inline — no build step needed.

---

## Core Architecture Concepts Covered

### 1. Agent Operating System Mental Model

A mature coding agent is structured as a platform, not a script:

```
src/
├── entrypoints/        # cli.tsx, init.ts, mcp.ts, sdk/
├── constants/          # prompts.ts — system prompt assembly
├── tools/              # FileRead, FileEdit, Bash, Agent, Skill, MCP...
├── services/           # tools, mcp, analytics runtime services
├── commands/           # slash commands (/mcp, /hooks, /skills, /plan...)
├── coordinator/        # agent coordination layer
├── plugins/            # plugin ecosystem
├── hooks/              # hook system
├── tasks/              # local, remote, async agent tasks
├── memdir/             # memory/prompt injection
└── bootstrap/          # state initialization
```

Key insight: the same agent runtime serves CLI, MCP mode, and SDK consumers simultaneously.

---

### 2. System Prompt Assembly Pattern

The system prompt is **not a static string** — it is a runtime-assembled module chain:

```typescript
// Conceptual reconstruction of getSystemPrompt() architecture
function getSystemPrompt(session: SessionContext): string {
  // --- STATIC PREFIX (cache-friendly) ---
  const staticSections = [
    getSimpleIntroSection(),        // identity + role
    getSimpleSystemSection(),       // base rules
    getSimpleDoingTasksSection(),   // task philosophy
    getActionsSection(),            // allowed actions
    getUsingYourToolsSection(),     // tool usage norms
    getSimpleToneAndStyleSection(), // communication style
    getOutputEfficiencySection(),   // token hygiene
  ].join("\n\n");

  // --- DYNAMIC SUFFIX (session-specific) ---
  const dynamicSections = [
    session.guidance     ? getSessionGuidance(session)     : "",
    session.memory       ? getMemoryPrompt(session)        : "",
    getEnvInfoSection(session.env),
    session.language     ? getLanguageSection(session)     : "",
    session.outputStyle  ? getOutputStyleSection(session)  : "",
    session.mcpServers   ? getMCPInstructions(session)     : "",
    getScratchpadSection(),
    getFunctionResultClearingPrompt(),
    session.tokenBudget  ? getTokenBudgetSection(session)  : "",
    session.brief        ? getBriefModeSection()           : "",
  ].filter(Boolean).join("\n\n");

  return [staticSections, dynamicSections].join("\n\n");
}
```

**Why this matters:** Static sections are cache-stable (cheaper), dynamic sections adapt per session. This is prompt architecture, not prompt writing.

---

### 3. Tool Execution Pipeline

Tools are never called directly — every invocation goes through a governance pipeline:

```typescript
// Conceptual tool execution pipeline
async function executeTool(toolCall: ToolCall, context: AgentContext) {
  // 1. Schema validation
  const parsed = toolSchema.parse(toolCall.input);

  // 2. Input validation (tool-specific)
  const validationResult = await tool.validateInput(parsed, context);
  if (!validationResult.ok) throw new ValidationError(validationResult.error);

  // 3. Pre-tool hooks (can modify input, inject context, or BLOCK)
  const hookDecision = await runPreToolHooks(toolCall, context);
  if (hookDecision.action === "block") {
    return { blocked: true, reason: hookDecision.reason };
  }

  // 4. Permission check
  const permission = await checkPermission(toolCall, context);
  if (!permission.granted) {
    return await requestUserPermission(toolCall, context);
  }

  // 5. Actual tool execution
  const result = await tool.execute(parsed, context);

  // 6. Telemetry / analytics
  await recordToolUsage(toolCall, result, context);

  // 7. Post-tool hooks
  const finalResult = await runPostToolHooks(toolCall, result, context);

  return finalResult;
}
```

**Available built-in tools:**

| Tool | Purpose |
|---|---|
| `FileRead` | Read file contents |
| `FileEdit` | Patch/edit existing files |
| `FileWrite` | Create or overwrite files |
| `Bash` | Execute shell commands |
| `Glob` | File pattern matching |
| `Grep` | Content search |
| `TodoWrite` | Task tracking |
| `TaskCreate` | Async agent task creation |
| `AskUserQuestion` | Clarify ambiguity |
| `Skill` | Invoke a packaged workflow |
| `Agent` | Spawn a subagent |
| `MCPTool` | Call an MCP-registered tool |
| `Sleep` | Delay execution |

---

### 4. Agent Orchestration and Subagents

The `AgentTool` is how the main agent spawns specialized subagents:

```typescript
// Conceptual AgentTool dispatch logic
async function agentToolHandler(input: AgentToolInput, ctx: AgentContext) {
  const mode = resolveAgentMode(input, ctx);
  // mode: "fork" | "normal" | "background" | "remote" | "worktree"

  const subagentPrompt = buildSubagentPrompt(input.task, mode);
  const tools = selectToolsForMode(mode, ctx);
  const systemPrompt = getSystemPrompt(buildSubagentSession(ctx, mode));

  return await runAgent({
    messages: subagentPrompt,
    systemPrompt,
    tools,
    context: ctx,
  });
}
```

**Built-in specialized agents:**

```
General Purpose Agent  → default task execution
Explore Agent          → codebase discovery, read-only recon
Plan Agent             → structured planning before execution  
Verification Agent     → post-implementation validation
```

**Verification Agent pattern** (especially valuable):

```typescript
// What Verification Agent checks:
const verificationChecklist = [
  "npm run build",          // does it compile?
  "npm test",               // do tests pass?
  "npx tsc --noEmit",       // type errors?
  // ... real command outputs, not assumptions
  "final verdict: PASS | FAIL with specific reasons"
];
```

---

### 5. Hook System

Hooks provide runtime governance — they can observe, modify, or block agent behavior:

```typescript
// Hook interface pattern
interface AgentHook {
  name: string;
  event: "pre-tool" | "post-tool" | "on-failure" | "on-permission-request";
  handler: (context: HookContext) => Promise<HookDecision>;
}

interface HookDecision {

Related in AI Agents