Agent & Sub-Agent System

Claude Code is not a single-threaded assistant. Under the hood, it operates a multi-agent architecture where the main conversation can spawn specialised sub-agents for parallel work, background verification, codebase exploration, and even full team coordination via swarm mode. This page documents the complete agent lifecycle, communication protocols, and configuration options.

Architecture Overview

The main Claude Code session acts as the primary agent. It can spawn sub-agents via the AgentTool, each running in its own API conversation loop with a restricted tool set, a potentially different model, and an independent turn budget. Sub-agents report results back to the parent when they complete.

Main Agent Primary conversation loop Explore Agent Haiku / Read-only / Fast General Agent All tools / Default model Plan Agent Read-only / Inherit model Agent Lifecycle Spawn Build Messages API Loop Tool Execution repeat until done Turn Limit? Complete -- Report to Parent SendMessage Tool Inter-agent messaging Running: queue msg Stopped: auto-resume Unreachable: mailbox Mailbox System Async team coordination

Agent Spawning

Agents are spawned via the AgentTool, which the main agent (or another agent with permission) can invoke like any other tool. The tool accepts a prompt and an agent type, then creates an independent conversation loop.

AgentTool Invocation Example
// Main agent spawning an Explore sub-agent { "tool": "Agent", "params": { "prompt": "Find all files that import the DatabaseConnection class", "agentType": "explore" } } // Main agent spawning a general sub-agent with specific tools { "tool": "Agent", "params": { "prompt": "Refactor the auth module to use JWT tokens", "agentType": "general" } }

Built-In Agent Types

Agent Type Model Tools Key Behaviour Status
General-Purpose Default (inherits parent) All tools Full capabilities, same model as parent. Default when no type specified. Public
Explore Haiku Glob, Grep, Bash, Read Read-only codebase search. Skips CLAUDE.md. ONE_SHOT mode. Three thoroughness levels. Public
Plan Inherits parent Read-only subset Reads code and produces a plan. Cannot write files or execute commands. Public
Verification Varies Read-only + Bash (limited) Background agent that verifies outputs. Part of an A/B experiment. Ant-Only
Claude Code Guide Default Read, Glob, Grep Helps users understand Claude Code itself. Searches internal documentation. Public

Explore Agent Deep Dive

The Explore agent is the most frequently spawned sub-agent. It is deliberately cheap and fast, running on Haiku with a minimal tool set and no CLAUDE.md loading overhead.

Cost Optimisation: omitClaudeMd = true

The Explore agent sets omitClaudeMd: true, which skips loading all three CLAUDE.md files (global, project, workspace). This reduces the system prompt size and avoids cache invalidation from CLAUDE.md changes. It also means any project-specific instructions you have written will not apply to Explore agents.

Medium Impact

Thoroughness Levels

The Explore agent supports three thoroughness levels that control how deeply it searches. The level is selected automatically based on the complexity of the query, or can be hinted at by the parent agent.

Level Behaviour Typical Use
Quick Single glob or grep, return first match "Where is the config file?"
Standard Multiple search passes, cross-reference results "Find all usages of the deprecated API"
Thorough Exhaustive search, reads files for context, follows import chains "Map the complete dependency graph of the auth module"
Explore Agent Configuration
const EXPLORE_AGENT_CONFIG = { model: "haiku", tools: ["Glob", "Grep", "Bash", "Read"], omitClaudeMd: true, mode: "ONE_SHOT", // No multi-turn conversation maxTurns: 15, // Hard ceiling };

Tool Resolution

When an agent is spawned, its available tool set is resolved from three inputs: the agent's allowlist, its denylist, and a global disallowed set. MCP tools receive special treatment.

Tool Resolution Logic
// Tool resolution priority: // 1. Start with allowlist (or wildcard ['*'] for all tools) // 2. Remove denylist entries // 3. Remove CUSTOM_AGENT_DISALLOWED_TOOLS // 4. Always add MCP tools (they bypass restrictions) function resolveTools(config: AgentConfig): Tool[] { let tools = config.tools === ['*'] ? getAllBuiltinTools() : getToolsByName(config.tools); tools = tools.filter(t => !config.disallowedTools?.includes(t.name) && !CUSTOM_AGENT_DISALLOWED_TOOLS.includes(t.name) ); // MCP tools always pass through tools.push(...getMcpTools()); return tools; }
Resolution Method Syntax Example
Wildcard (all tools) tools: ['*'] General-purpose agent gets everything
Allowlist tools: ["Read", "Glob"] Explore agent only gets search tools
Denylist disallowedTools: ["Write"] Plan agent cannot write files
Global block CUSTOM_AGENT_DISALLOWED_TOOLS Prevents agents from spawning further agents (recursion guard)
MCP bypass Automatic MCP tools are always available regardless of allow/deny lists
MCP Tools Bypass All Restrictions

MCP tools are always injected into every agent's tool set, regardless of allowlists or denylists. This is by design -- MCP servers are user-configured and trusted. But it means a restrictive agent (like Explore) can still invoke MCP tools if any servers are connected.


Agent Lifecycle

Every agent follows the same lifecycle from spawn to completion. The lifecycle is managed by the agent executor, which handles the API loop, tool dispatch, and turn counting.

1
Spawn: Parent invokes AgentTool with prompt and type. Agent ID is generated, config is resolved.
2
Build Messages: System prompt is assembled (with agent-specific overrides), initial user message is set from the prompt parameter.
3
API Loop: Agent sends messages to the API, receives responses, and processes tool calls in a loop.
4
Tool Execution: Each tool call is dispatched, results are appended to the conversation, and the loop continues.
5
Turn Limit Check: After each API response, the turn counter is incremented. If it exceeds maxTurns, the agent is forced to complete.
Complete: Agent produces a final text result. This is returned to the parent as the tool result of the AgentTool invocation.

Resume Phase

If a session is interrupted (e.g., terminal closed), agents can be resumed. The transcript is persisted to ~/.claude/tasks/<agentId>/ and the agent state is reconstructed on resume.

Resume Path Structure
~/.claude/tasks/ <agentId>/ transcript.json # Full conversation history state.json # Agent config, turn count, status tool-results/ # Cached tool outputs for replay

Agent Memory

Agents can access memory files at three scopes. The scope determines which MEMORY.md files are loaded into the agent's system prompt.

Scope Path Shared With
User ~/.claude/CLAUDE.md All sessions, all projects for this user
Project .claude/CLAUDE.md + ~/.claude/projects/<hash>/memory/ All sessions in this project directory
Local ~/.claude/projects/<hash>/local-memory/ Only this user on this machine
Agent Memory Scope Selection

When defining a custom agent, the memory frontmatter field controls which scope is loaded. Setting memory: user loads only global preferences. Setting memory: project loads both global and project memories. The Explore agent effectively uses no memory (since it sets omitClaudeMd: true).


Inter-Agent Communication

Agents communicate via the SendMessage tool. The routing logic determines how messages are delivered based on the target agent's current state.

Target State Routing Behaviour When This Happens
Running Message is queued for the next turn Agent is actively processing; message will be injected as a user message on the next API loop iteration
Stopped Agent is auto-resumed with the message Agent has completed but the sender needs something from it; the message becomes the resume prompt
Unreachable Message goes to the mailbox Agent does not exist, has been cleaned up, or is on a different machine (remote teammates)
SendMessage Tool Invocation
// Sending a message to another agent { "tool": "SendMessage", "params": { "targetAgentId": "agent-abc123", "message": "I've finished refactoring the auth module. Please verify the tests pass." } }

Mailbox System

When a message cannot be delivered directly (target unreachable), it is stored in a mailbox. Agents check their mailbox when they start or resume. This enables asynchronous coordination between agents that are not running simultaneously -- critical for team-based workflows where agents may be in different terminal panes or even on different machines.


Multi-Agent Swarm

The swarm system enables a team of agents to work together on a large task. A team configuration defines a leader agent and one or more worker agents, each with their own specialisation.

Team Architecture

Role Responsibility Backing Mode
Leader Decomposes the task, delegates to workers, aggregates results, reports to the user In-process (main terminal)
Worker (In-Process) Runs in the same process as the leader. Lightweight, no separate terminal. In-process
Worker (Pane-Backed) Runs in a separate tmux/terminal pane. Visible to the user, independent process. Pane-backed
Worker (Remote) Runs on a different machine. Communicates via the mailbox system. Remote
Pane-Backed Workers

Pane-backed workers are particularly useful for long-running tasks. Each worker gets its own terminal pane (via tmux or a similar multiplexer), so you can watch their progress in real time. The leader communicates with them via SendMessage and receives completion signals automatically.


Worktree Isolation

Agents can be configured to run in an isolated git worktree. This prevents file conflicts when multiple agents write to the same repository simultaneously.

Worktree Lifecycle
# 1. Agent spawns with isolation: worktree git worktree add /tmp/claude-worktree-abc123 -b agent/task-abc123 # 2. Agent works in the worktree directory # All file paths are translated: /project/src/foo.ts -> /tmp/claude-worktree-abc123/src/foo.ts # 3. Agent completes, commits its changes git add -A && git commit -m "Agent task: refactor auth module" # 4. Worktree is cleaned up automatically git worktree remove /tmp/claude-worktree-abc123
Path Translation Notice

When an agent runs in a worktree, all file paths in tool calls are automatically translated to the worktree directory. If the agent reports a file path in its output, that path points to the worktree, not the main checkout. The parent agent needs to account for this when processing results.


Fork Sub-Agent

Enabled via CLAUDE_CODE_FORK_SUBAGENT=1, fork sub-agents receive a full copy of the parent's conversation context at the point of forking. This is different from a normal agent spawn, which starts with a fresh conversation.

Fork Safety Rules

Forked agents have strict constraints to prevent runaway recursion and ensure clean handoffs:

High Impact
  • No recursion: A forked agent cannot fork further sub-agents. The fork depth is capped at 1.
  • No sub-agents: Forked agents cannot use the AgentTool to spawn additional agents of any type.
  • Commit and report: The expected workflow is: do the work, commit the changes, then report the result back to the parent. The fork should be self-contained.
Fork Sub-Agent Constraints
const FORK_AGENT_RULES = { maxForkDepth: 1, // Cannot fork from a fork canSpawnAgents: false, // AgentTool is disabled inheritContext: true, // Gets full parent conversation expectedWorkflow: "commit-and-report", };

User-Defined Agents

Beyond the built-in types, you can define custom agents using Markdown files with YAML frontmatter. Agents are loaded from multiple sources, resolved in priority order.

Source Location Priority
Built-in Bundled with Claude Code Lowest (fallback)
Plugin Installed plugin agents Low
User ~/.claude/agents/*.md Medium
Project .claude/agents/*.md High
Managed Organisation-managed agent configs Higher
CLI Flags --agent-type argument Highest (overrides all)

YAML Frontmatter Format

.claude/agents/lint-checker.md
--- name: lint-checker description: Run linting and report issues concisely tools: [Bash, Read, Glob] disallowedTools: [Write, Edit] model: haiku maxTurns: 10 memory: project isolation: worktree background: true colour: yellow --- You are a linting agent. Run the project's lint command and report any errors or warnings. Group issues by file. Do not attempt fixes.

Coordinator Mode

Activated via CLAUDE_CODE_COORDINATOR_MODE=1, coordinator mode transforms Claude into an orchestrator that follows a structured four-phase workflow. Rather than doing the work itself, the coordinator delegates to worker agents.

Phase 1 -- Research: Spawn Explore agents to understand the codebase, gather context, and identify relevant files. Multiple Explore agents can run in parallel.
Phase 2 -- Synthesis: Analyse research results, identify the approach, and create a detailed plan. May spawn a Plan agent.
Phase 3 -- Implementation: Delegate the actual work to general-purpose worker agents. Each worker handles one logical piece. Workers can use worktree isolation to avoid conflicts.
Phase 4 -- Verification: Run tests, check for regressions, verify the implementation matches the plan. May spawn a Verification agent if available (ant-only).
Activating Coordinator Mode
CLAUDE_CODE_COORDINATOR_MODE=1 claude # Or in .claude/settings.json: { "env": { "CLAUDE_CODE_COORDINATOR_MODE": "1" } }
When to Use Coordinator Mode

Coordinator mode shines for large, multi-file tasks: feature implementations spanning 5+ files, cross-cutting refactors, or any task where the research and implementation phases benefit from parallelism. For simple single-file changes, it adds unnecessary overhead.


Agent Spawning & Lifecycle Flow

The complete flow from user request through agent orchestration to result delivery:

User Request Main Agent: Analyse Task Delegate? No Do Work Yes Resolve Agent Config Resolve Tool Set Build System Prompt API Loop Call API -> Process Response -> Execute Tools Repeat until done or maxTurns reached Return Result to Parent Complete Worktree? git worktree add
Key Takeaway

The agent system is Claude Code's mechanism for parallelism and specialisation. Use Explore agents liberally (they are cheap), define custom Haiku agents for repetitive tasks, and consider coordinator mode for large multi-file changes. Understanding the tool resolution rules ensures your custom agents get exactly the capabilities they need -- no more, no less.