VerBodh

VerBodh · AI KB Internals · Claude Code

AI KB Internals

Build your own coding agent: the components and the architecture

VerBodh · 21 October 2026

A coding agent like Claude Code has one small core, the agent loop. Every other part feeds the loop, guards it, extends it, or makes it cheap to run. This page lists 18 parts. Sections 5, 6, 11 and 14 cover the four hard parts: the cache, decision making, subagent orchestration and settings.json.

Each fact about Claude Code and the Claude API was checked against the official docs. The last section lists the sources.

0. The architecture

SURFACES (17)CLI terminal UI · IDE · desktop · web · SDK · headless modeHARNESS4. Context buildertools · prompt · messages5. Cache layout2 cache points1. Model APItext or tool calls6. Decision gate8 hooks → 7 rules → user3. Toolsfiles · shell · web9. Skillsload SKILL.md10. Commandsuser types /x11. Subagentsown loop + context12. MCP toolsoutside services2. Loop: every result goes back into the messages, then the model is called againSTATE · EXTEND · PLATFORM14. settings.json · 15. Memory + CLAUDE.md · 16. Sessions + compaction13. Plugins (skills, commands, agents, hooks, MCP) · 18. Distribution, cost, telemetry
The harness in the middle: every model reply passes the decision gate, and every tool result goes back into the messages.

1. Model API

2. Agent loop (the core)

while (true) {
  const reply = await model.create({ tools, system, messages });   // 1
  messages.push(reply);
  const calls = reply.content.filter(b => b.type === "tool_use");
  if (calls.length === 0) {                                         // the model wants to stop
    if (await stopHookBlocks(reply)) { messages.push(reason); continue; }   // 8
    break;
  }
  const results = await Promise.all(calls.map(gateThenRun));        // 6 → 3/9/11/12
  messages.push({ role: "user", content: results });                // all results in ONE message
}

3. Tools

4. Context builder: what goes into every request

The order matters, because the cache works on the start of the request (section 5).

  1. Tools: the tool list, always in the same order.
  2. System prompt: who the agent is, how it works, its rules. Frozen for the whole session.
  3. Project instructions: CLAUDE.md or AGENTS.md, from the user folder, the repo root and parent folders. @path lines import other files. Claude Code reads AGENTS.md when a folder has no CLAUDE.md.
  4. Catalogues: one line per skill, per subagent type and per deferred tool. Only the names and descriptions, never the full text.
  5. Memory index: the first 200 lines or 25 KB of MEMORY.md, whichever comes first.
  6. Messages: the conversation so far, including every tool result.
  7. Reminders: new facts (a file changed, today's date, a new tool) are added as a small note at the end of the newest message. Earlier messages are never edited.

5. Cache management

How the model provider's prompt cache works

Price, from the Claude API docs

Token type Price, as a multiple of the normal input price
Cache write, 5 minutes 1.25×
Cache write, 1 hour 2×
Cache read, most models 0.1×
Cache read, Claude Opus 5.5 and Claude Sonnet 5.5 0.05×
Cache read, Claude Fable 5.1 and Claude Mythos 5.1 0.025×

Example, Claude Opus 5.5: input $4, 5-minute write $5, 1-hour write $8, cache read $0.20, all per million tokens.

Minimum length to cache

The start of the request must be long enough. A shorter one does not cache, and gives no error.

Model Minimum tokens
Claude Fable 5.1, Mythos 5.1, Opus 5.5, Opus 5, Sonnet 5.5, Fable 5, Mythos 5, Haiku 5.5 512
Claude Opus 4.8, Sonnet 5, Sonnet 4.6, Sonnet 4.5, Opus 4.1, Opus 4, Sonnet 4 1,024
Claude Mythos Preview, Opus 4.7 2,048
Claude Opus 4.6, Opus 4.5, Haiku 4.5 4,096
ToolsSystem + CLAUDE.mdTurns 1 … n-1Turn n (new)cache point 1cache point 2read from cache: about 0.1× pricewritten once: 1.25× (5 min) or 2× (1 h)
Two cache points: everything before the newest turn is read from the cache.

How the agent uses it

Rules that keep the cache working

Check it

6. Decision making: who decides what

There are two deciders. The model decides what to do next. The harness decides if it may.

What the model decides from

What the harness does with each tool call

model asks for a tool
  └► PreToolUse hooks ── exit 2 blocks here, before any rule
      │                  JSON can deny, allow, ask, defer, or change the input
      └► permission rules ── deny, then ask, then allow; the first match wins
          │                  a hook "allow" does NOT skip a matching deny or ask rule
          └► permission mode ── decides the calls no rule matched (section 7)
              └► ask the user ── yes once · yes, don't ask again (saves a rule) · no (the model is told why)
                  └► run the tool ──► PostToolUse hooks ──► result back to the model

When the loop stops

7. Permissions and safety

Modes (permissions.defaultMode)

Mode What it does
default Asks the first time each tool is used. Shown as "Manual"; manual is an alias
acceptEdits Accepts file edits and common file commands (mkdir, touch, mv, cp) in the working folders
plan Reads and runs read-only commands; does not edit source files
auto No routine prompts. A background classifier checks shell commands and network requests against your request
dontAsk Denies every call that would ask. Allowed rules and calls that need no approval still run. Good for locked-down CI
bypassPermissions Skips prompts, except for a few actions no mode approves. Use it only in a sandbox

auto and bypassPermissions do not take effect from project or local settings files. Set them in user settings, managed settings, or with --permission-mode for one session.

Rules

Other guards

8. Hooks

Hooks are your scripts that the harness runs at fixed moments. They enforce team rules without a change to the agent.

The events Claude Code has

Group Events
Session SessionStart, Setup, SessionEnd
User input UserPromptSubmit, UserPromptExpansion
Tool calls PreToolUse, PermissionRequest, PermissionDenied, PostToolUse, PostToolUseFailure, PostToolBatch
Stopping Stop, StopFailure, SubagentStart, SubagentStop, TeammateIdle
Tasks TaskCreated, TaskCompleted
Context InstructionsLoaded, PreCompact, PostCompact, PreModelSwitch, PostModelSwitch
Files and folders ConfigChange, CwdChanged, DirectoryAdded, FileChanged, WorktreeCreate, WorktreeRemove
Interface Notification, MessageDisplay
MCP Elicitation, ElicitationResult

The ones most agents need first:

How a hook talks to the harness

Exit code Result
0 Go on. A single JSON object on stdout is read as a decision
2 Block, on events that can block. The text on stderr goes to the model as the reason
Any other, also 1 Not a block. The action goes on, and the user sees a hook error notice
{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Database writes are not allowed"
  }
}

Where hooks are wired: settings.json

{
  "hooks": {
    "SessionStart": [{ "hooks": [{ "type": "command", "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/sync-main.sh\"" }] }],
    "PreToolUse": [
      { "matcher": "Bash", "hooks": [{ "type": "command", "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/block-db-delete.sh\"" }] }
    ]
  }
}

$CLAUDE_PROJECT_DIR is the project root. Quote it, so a path with spaces stays one argument.

9. Skills

Where they live

Scope Path
Personal, all your projects ~/.claude/skills/<name>/SKILL.md
Project, commit it for the team .claude/skills/<name>/SKILL.md
A sub-folder of the project <subdir>/.claude/skills/<name>/SKILL.md
Plugin <plugin>/skills/<name>/SKILL.md, called as plugin:skill
Organization .claude/skills/ in the managed settings folder
---
name: simplified-technical-english
description: Writes and rewrites text in Simplified Technical English. Use when the user asks for STE or plain technical writing...
---
# The rules...

10. Slash commands

11. Subagents and orchestration

What a subagent is

Main loop3 Agent calls, one replyHelper A: search src/own context · Read, GrepHelper B: search tests/own context · Read, GrepHelper C: review diffbackground · notice when done3 short summariesreturn as tool results
Fan-out: three helpers run at the same time, and only their summaries come back.

How a subagent type is defined: a Markdown file with frontmatter

---
name: code-reviewer
description: Reviews a diff for bugs. Use after code changes.
tools: Read, Grep, Glob
model: sonnet
---
You are a code reviewer. Report only real bugs, each with file and line...
Where the file lives Scope Wins a name clash
Managed settings Organization 1st
--agents flag This session 2nd
.claude/agents/ This project 3rd
~/.claude/agents/ All your projects 4th
A plugin's agents/ Where the plugin is on 5th

How orchestration runs, step by step

  1. The main model sees the list of subagent types and their descriptions (section 4).
  2. It calls the Agent tool with a type, a short description and a full task prompt. The prompt must hold everything, because the helper does not see the main conversation.
  3. The harness starts a new loop: that type's system prompt, its allowed tools, and the task as the first message.
  4. The helper runs to its end. Its hooks, permissions and the user's approvals still apply.
  5. Its final message comes back to the main model as the Agent tool's result.
  6. The main model checks the result and decides the next step. The user does not see the helper's report unless the main model passes it on.

The patterns

Limits

Cost

12. MCP servers

13. Plugins and marketplaces

Standard layout

my-plugin/
├── .claude-plugin/plugin.json   manifest (optional)
├── skills/<name>/SKILL.md
├── commands/                    old form; prefer skills/
├── agents/<name>.md
├── hooks/hooks.json
├── .mcp.json
└── bin/                         on the shell PATH while the plugin is on

Paths inside a plugin

Variable Points to Use it for
${CLAUDE_PLUGIN_ROOT} The installed plugin folder. It changes on each update Bundled scripts and config. Never write state here
${CLAUDE_PLUGIN_DATA} ~/.claude/plugins/data/<id>/. Kept across updates Installed packages, caches
${CLAUDE_PROJECT_DIR} The project root Project scripts and config

14. settings.json

The layers, strongest first

  1. Managed: set by the company, cannot be changed by the user.
  2. Command line: JSON passed with --settings <file-or-json>, for this run only.
  3. Local project: .claude/settings.local.json, not committed.
  4. Project: .claude/settings.json, committed and shared with the team.
  5. User: ~/.claude/settings.json, for all your projects.

Where the user files are

macOS and Linux Windows
User settings ~/.claude/settings.json %USERPROFILE%\.claude\settings.json
Auto memory, default ~/.claude/projects/<project>/memory/ %USERPROFILE%\.claude\projects\<project>\memory\

CLAUDE_CONFIG_DIR moves the whole ~/.claude folder to another place.

What goes in it

{
  "$schema": "https://json.schemastore.org/claude-code-settings.json",
  "model": "claude-opus-5-5",
  "permissions": {
    "allow": ["Bash(git status)", "Bash(npm test *)"],
    "ask":   ["Bash(git push *)"],
    "deny":  ["Read(./.env)", "Read(./.env.*)", "Bash(rm -rf *)"],
    "defaultMode": "default"
  },
  "hooks": { "PreToolUse": [ ... ] },
  "env": { "NODE_ENV": "development" },
  "autoMemoryDirectory": "~/claude-memory",
  "statusLine": { "type": "command", "command": "~/.claude/statusline.sh" }
}

15. Memory and instructions

16. Sessions and compaction

17. Surfaces

18. Distribution, cost and telemetry

Build order

  1. Model API, the loop, and read, edit and shell tools. You now have a working agent.
  2. Permissions, the approval screen and settings.json, before anyone else uses it.
  3. The context builder with cache points, and CLAUDE.md. Check cache_read_input_tokens now, not later.
  4. Search tools, the to-do list, sessions and compaction.
  5. Hooks.
  6. Skills and slash commands.
  7. Subagents, then background helpers and scripted workflows.
  8. MCP, tool search and plugins.
  9. Headless mode, the SDK and other surfaces.

Build it, or build on it

Where each fact comes from

Topic Source
Cache order, cache points, lifetimes, prices, minimum length, usage fields Claude API docs, prompt caching: https://platform.claude.com/docs/en/build-with-claude/prompt-caching
Hook events, exit codes, JSON decisions Claude Code docs, hooks: https://code.claude.com/docs/en/hooks
Rule order, modes, hooks and rules together Claude Code docs, permissions: https://code.claude.com/docs/en/permissions
Settings layers, file paths, list merging Claude Code docs, settings: https://code.claude.com/docs/en/settings
Subagent files, fields, nesting limits Claude Code docs, subagents: https://code.claude.com/docs/en/sub-agents
Skill paths, commands merged into skills Claude Code docs, skills: https://code.claude.com/docs/en/skills
Auto memory folder, MEMORY.md limit Claude Code docs, memory: https://code.claude.com/docs/en/memory
Plugin layout and variables Claude Code docs, plugin reference: https://code.claude.com/docs/en/plugins-reference
Headless flags, resume Claude Code docs, headless: https://code.claude.com/docs/en/headless
Status line shape Claude Code docs, status line: https://code.claude.com/docs/en/statusline
Deferred tools, ToolSearch, Agent, SendMessage, Workflow, background notices, reminders Seen in a running Claude Code session
How the parts are built inside A suggested design, not Anthropic's code. Anthropic does not publish all of it

The docs change often. Check the source pages before you rely on a number.

VERBODH PTE. LTD. · SINGAPORE · support@verbodh.com
UEN 202640155R · Privacy, Terms & Security