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.
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.
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.
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" |
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.
| 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 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.
maxTurns, the agent is forced to complete.
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.
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 |
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) |
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 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.
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.
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
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.
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:
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.