ai-agent-deep-dive
```markdown
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
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.