What this unit solvesA subagent is an isolated context window container for sub-tasks: you assign it a model, constrain its tool permissions, optionally isolate it in a git worktree, and it returns only its conclusion to the main flow. Claude Code v2.1 introduces a two-layer structure: built-in sub-agents (Explore, Plan, general-purpose invoked automatically) plus custom sub-agents (defined by Markdown frontmatter you write). This unit covers how to write a working subagent from scratch, how to choose a model and the minimum tool set, when to use
isolation: worktree to prevent parallel conflicts, and how to clarify the division of responsibility with skills.Learning objectives
- Describe the two-layer subagent structure introduced in Claude Code v2.1: built-in (Explore, Plan, general-purpose) and custom (Markdown files), and explain when each applies.
- Write a correct subagent frontmatter including
model,tools,permissionMode,skills, andisolation, and explain the reasoning behind each field’s value. - For a given sub-task, decide which model to use, which tools to grant, whether
isolation: worktreeis needed, whether to preloadskills, and whetherpermissionModeis appropriate. - Explain the division between subagents and skills: a skill is a procedure; a subagent is an execution container. A skill uses
context: forkto run a procedure inside a subagent; a subagent usesskills:to preload procedures into its own context. - Correctly invoke a subagent from the main-flow prompt (via description matching or explicit
@-mention) and retrieve the result.
1. What a subagent is
A subagent is a sub-task execution unit with its own isolated context window, assignable model, and tool set. The main conversation hands work to it, the subagent completes the entire task inside its own context, and returns only the conclusion to the main conversation (as of 2026-06, per the official subagents documentation [1]). The core problem it solves: confine the side-effects that would flood the main conversation context into an isolated context. Scanning 200 files for deprecated imports, running bulk grep to gather information, running a ten-minute test suite and returning a failure summary. If all that happens in the main conversation, tens of thousands of tokens get consumed by search results, and the model pays attention costs to scan over them in every subsequent turn. The subagent does all of it inside its own context and returns the summary. The main conversation pays only once for the summary. Two key facts to internalize first:- A subagent cannot spawn another subagent (no nesting). When parallel delegation is needed, the main conversation invokes multiple subagents in parallel, or uses an agent team (see 04-11).
- The subagent’s system prompt is the Markdown body you write after the frontmatter, not Claude Code’s full system prompt. The quality of your instructions directly determines the subagent’s behavior.
2. Two-layer structure: built-in and custom
Claude Code v2.1 introduces a two-layer subagent structure ([1]):| Layer | Contents | How triggered | Purpose |
|---|---|---|---|
| Built-in | Explore, Plan, general-purpose, plus auxiliaries such as statusline-setup and claude-code-guide | Automatically invoked by the model based on task semantics; the user does not interact with them directly | Exploration, planning, complex multi-step tasks |
| Custom | Markdown files you write, stored in ~/.claude/agents/, .claude/agents/, plugin agents/, managed settings, or passed via claude --agents CLI | Automatically invoked by the model based on description, or explicitly via @subagent-name | Specialized workers for specific domains |
2.1 Built-in subagents
| Name | Model | Tools | Purpose |
|---|---|---|---|
| Explore | Haiku (fast, low latency) | Read-only (Write / Edit refused) | File search, codebase exploration |
| Plan | Inherits main conversation | Read-only | Research in plan mode (avoids infinite nesting) |
| general-purpose | Inherits main conversation | All tools | Complex multi-step tasks mixing exploration and modification |
| statusline-setup | Sonnet | (auxiliary) | Invoked when running /statusline |
| claude-code-guide | Haiku | (auxiliary) | Answering questions about Claude Code itself |
CLAUDE.md and the parent session’s git status, keeping research fast and cheap. All other built-in and all custom subagents do load CLAUDE.md [1].
When invoking Explore you can specify a thoroughness level: quick (targeted query), medium (balanced), very thorough (comprehensive analysis).
2.2 Custom subagents vs built-in
A custom subagent is a single Markdown file containing YAML frontmatter (configuration) and a body (system prompt). It can be placed in multiple scopes; the scope determines which sessions can use it and its priority. The most important design distinction:- Built-in subagents primarily run read-only tasks (Plan, Explore).
general-purposeis the only built-in that can write. - Custom subagents are entirely your design: read-only or writable, model-specified, skill-preloaded, worktree-isolated.
3. Placement locations and priority order
Custom subagents can be placed in five scopes, from highest to lowest priority [1]:| Location | Scope | Priority | How to create |
|---|---|---|---|
| Managed settings | Organization-wide | 1 (highest) | Admin deployment |
--agents CLI flag | Current session | 2 | Pass JSON when launching Claude Code |
.claude/agents/ | Current project (version-controlled) | 3 | Interactive or manual |
~/.claude/agents/ | All your projects | 4 | Interactive or manual |
Plugin agents/ directory | Within plugin’s enabled scope | 5 (lowest) | Installed with the plugin |
.claude/agents/ and ~/.claude/agents/, so subdirectories work (agents/review/, agents/research/). Directory path does not affect subagent identity; identity comes from the name field in frontmatter only. If two files in the same scope declare the same name, Claude Code keeps one and silently discards the other [1].
Plugin agents/ directories are also scanned recursively, but subdirectories become part of the scoped identifier: my-plugin/agents/review/security.md is identified inside plugin my-plugin as my-plugin:review:security [1].
4. Full frontmatter reference
Subagent file format (as of 2026-06, per the official subagents documentation [1]):name and description are required; all other fields are optional. Complete field list:
| Field | Required | Purpose |
|---|---|---|
name | Yes | Unique identifier (lowercase letters and hyphens). The agent_type received by the SubagentStart hook is this value [1] |
description | Yes | The basis on which the model decides when to delegate to this subagent |
tools | No | Allowlist of tools available to the subagent. Omitting this inherits all tools. To preload skills, use the skills field, not Skill in tools [1] |
disallowedTools | No | Blocklist, removing tools from the inherited or specified list |
model | No | sonnet / opus / haiku / full model ID / inherit (default) |
permissionMode | No | default / acceptEdits / auto / dontAsk / bypassPermissions / plan |
maxTurns | No | Maximum agentic turns for this subagent in this invocation |
skills | No | List of skill names to preload into the subagent context; full content is injected |
mcpServers | No | MCP servers dedicated to this subagent; can be inline or reference an already-connected server |
hooks | No | Lifecycle-specific hooks for this subagent |
memory | No | Persistent memory scope: user / project / local |
background | No | Default background mode false; set to true to always run as a background task |
effort | No | Override session effort: low / medium / high / xhigh / max |
isolation | No | Set to worktree to run the subagent in a temporary git worktree |
color | No | UI display color: red / blue / green / yellow / purple / orange / pink / cyan |
initialPrompt | No | The first user turn when this agent runs as the main session (via --agent or agent setting) |
Task renamed to Agent in v2.1.63In v2.1.63, the Task tool was renamed to Agent ([1]). The old Task(...) syntax still works as an alias in settings and agent definitions. tools: Agent(worker, researcher) is the v2.1+ standard syntax for restricting which types a subagent can spawn.4.1 Model resolution order
When Claude invokes a subagent, the model is resolved in the following order [1]:CLAUDE_CODE_SUBAGENT_MODEL environment variable
Highest priority. Set this at launch to uniformly specify the model for all subagents, overriding everything else.
model parameter at invocation time
The model parameter passed by the caller at invocation time, taking precedence over frontmatter.
Subagent frontmatter model
The
model field declared in the subagent file. model: inherit (default) means use the same model as the main conversation.4.2 Tool allowlist vs blocklist
tools sets an allowlist; disallowedTools sets a blocklist. When both are set, the blocklist is applied first, then the allowlist is applied to what remains [1].
Allowlist example (strict restriction):
4.3 Restricting spawnable subagent types
When an agent runs as the main thread (claude --agent), it can spawn subagents. Use tools: Agent(worker, researcher) to restrict which types it can spawn [1]:
worker and researcher can be spawned. To allow any type, use tools: Agent, Read, Bash (no parentheses). Omitting Agent entirely means the agent cannot spawn any subagents. This restriction applies only to main-thread agents; subagents themselves cannot spawn any subagents (no nesting), so Agent(agent_type) in a subagent frontmatter has no effect [1].
4.4 permissionMode details
| Mode | Behavior |
|---|---|
default | Standard permission checks and prompts |
acceptEdits | Automatically accepts file edits within the working directory and additionalDirectories |
auto | Auto mode: background classifier reviews commands and writes to protected directories |
dontAsk | Automatically rejects permission prompts (explicitly allowed tools remain usable) |
bypassPermissions | Skips all permission prompts |
plan | Plan mode (read-only exploration) |
4.5 skills: preloading skill content into a subagent
disable-model-invocation: true cannot be preloaded, because preloading and model invokability share the same skill set. If a listed skill is missing or disabled, Claude Code skips it and writes a warning to the debug log [1].
4.6 isolation: worktree
isolation: worktree runs the subagent inside a temporary git worktree, giving it an isolated copy of the repo (forked from the default branch, not the parent session’s HEAD) [1].
- A temporary worktree is created automatically when the subagent starts.
- All writes by the subagent occur only in this worktree; the main working directory is unaffected.
- If the subagent makes no changes, the worktree is cleaned up automatically [1].
- If changes are made, you decide whether to merge, keep, or discard them.
5. Read-only vs writable, and when to use worktree isolation
The only criterion is: will this subagent modify files or external state?| Type | Task | Tools | worktree |
|---|---|---|---|
| Read-only | Search, review, summarize, analyze | Read, Glob, Grep; block Write / Edit | Not needed |
| Writable (no parallel conflict) | Refactoring, doc generation, single-file edits | Includes Write / Edit | Not needed (single subagent) |
| Writable (multiple subagents in parallel) | Multiple subagents simultaneously writing different files | Includes Write / Edit | Needed, one worktree per subagent |
| Untrusted input | Processing external documents, URLs, PR content | Minimum set | Strongly recommended (blast radius isolation) |
Decision checklist
- Will this subagent write files or modify external state? No: no worktree needed.
- Will the subagents running in parallel write to overlapping paths? Yes: use worktrees.
- Will the subagent process untrusted content (external documents, arbitrary PRs)? Yes: use a worktree for blast radius isolation.
6. Pairing with skills: procedure vs container
This is the most common point of confusion between subagents and skills. To clarify the division:| Dimension | Skill | Subagent |
|---|---|---|
| Nature | Procedure definition (steps, criteria, format) | Execution container (context, model, tools, isolation) |
| When loaded | Invoked when the model judges semantic relevance | Delegated by the model based on description, or via @-mention |
| Who executes | The Claude in the current conversation (main or subagent) | The subagent itself |
| Reuse | The same skill can be used in different conversations | The same subagent definition can be delegated from multiple sessions |
| Best for | ”This flow should run this way" | "Run this task in an isolated context” |
6.1 Three typical pairings
Skill only: the procedure runs in the main conversation; no isolation needed. Example: “Rewrite the document in this writing style.” Subagent only: the sub-task procedure is simple enough to write into the subagent description; no reuse needed. Example: “Search the codebase for all places that use a deprecated API.” Skill + subagent together: two paths. Path A: subagent preloads skill (skills: [...])
context: fork to push into a subagent
7. Invoking a subagent
7.1 Automatic invocation
Claude reads the subagent’sdescription and delegates automatically when the task semantics match. Writing a good description is the key to reliable triggering.
Description phrasing comparisonToo broad, causes false positives:Too narrow, causes missed triggers:About right:
7.2 Explicit invocation: @-mention
Use @subagent-name in the main conversation for explicit invocation. Example: “Use @code-reviewer to look at what this PR changed.”
Plugin subagents use their namespaced identifier: @my-plugin:review:security [1].
7.3 Background mode
background: true makes the subagent always run as a background task, running in parallel with the main conversation; Claude Code notifies the main conversation when the subagent completes [1].
8. Tool comparison
The mechanism for “isolated context sub-agents” differs significantly across tools (as of 2026-06):| Concept | Anthropic Claude (primary) | OpenAI Codex | Google Antigravity | GitHub Copilot CLI | Cursor (brief) |
|---|---|---|---|---|---|
| Custom subagent format | Markdown frontmatter file | ~/.codex/agents/*.toml (personal) / .codex/agents/*.toml (project) + config.toml’s [agents] global params; required: name/description/developer_instructions [6] | .agents/agents/*.md frontmatter [needs source verification] | Not applicable (CLI is single-agent) | .cursor/agents/ and built-in subagents [needs source verification] |
| Built-in sub-agents | Explore (Haiku, read-only), Plan (inherited, read-only), general-purpose (inherited, all tools) | System-layer provider agent | System-layer sub-agent | Not applicable | Composer, Background Agent, etc. [needs source verification] |
| Model specification | model: sonnet/opus/haiku/inherit/<id> | Configuration-based | Configuration-based | Configuration-based | Configuration-based |
| Tool convergence | tools allowlist + disallowedTools blocklist | Configuration-based | Configuration-based | Tool allowlist / blocklist | Configuration-based |
| Isolation mechanism | isolation: worktree | Environment layer | Environment layer | Environment layer | Environment layer |
| Skill preloading | skills: [...] frontmatter | Not applicable | Configuration-based | Not applicable | Not applicable |
| Permission mode | permissionMode: default/acceptEdits/auto/dontAsk/bypassPermissions/plan | Configuration-based | Configuration-based | Configuration-based | Configuration-based |
| Persistent memory | memory: user/project/local | Not applicable | Memory mechanism | Not applicable | Not applicable |
| Explicit invocation | @subagent-name | /agent command | Configuration-based | Configuration-based | @agent |
Naming clarification
- Claude Code’s subagent tool name: renamed from
TasktoAgentin v2.1.63 (oldTask(...)still works as an alias) ([1]).tools: Agent(worker, researcher)to restrict spawnable types is the v2.1+ standard syntax. - OpenAI Codex subagents have been verified against official documentation [6]:
config.toml’s[agents]defines global parameters (max_threads/max_depth/job_max_runtime_seconds); individual agent roles go in~/.codex/agents/*.toml(personal) or.codex/agents/*.toml(project). There is no~/.codex/prompts/*.mdorcodex.md; persistent instructions useAGENTS.md. - Antigravity and Cursor mechanisms should be verified against each vendor’s current documentation; items marked “needs source verification” are pending confirmation.
- GitHub Copilot CLI is a single-agent model as of 2026-06 and does not offer a first-class subagent mechanism; the cloud coding agent is a separate track.
- Cursor is a third-party IDE (Anysphere); this Playbook mentions it in a single column only.
9. Hands-on exercises
30-minute exercises
- Write a read-only subagent: create
~/.claude/agents/api-explorer.md, give the frontmattertools: Read, Glob, Grepandmodel: haiku, and write a body that says “scan the endpoints undersrc/api/and report each endpoint’s method, path, and authentication requirements.” Use/agentsto confirm it appears in the Library. - Write a writable subagent: create
.claude/agents/doc-fixer.md, give ittools: Read, Edit, Grep,model: haiku, andpermissionMode: acceptEdits, with a body that says “replace everyTODOin.mdfiles with an anchor linking to the corresponding issue.” Invoke it explicitly with@doc-fixerin the same project. - Isolation test: write a subagent with
isolation: worktreeand have it modify a file. Observe the worktree being created automatically, the worktree persisting after the subagent finishes, and the diff against the main working directory. When no changes are made, the worktree should clean itself up. - Skill + subagent: write a skill using
context: forkandagent: Explore; invoke the skill and observe it running in an isolated context, with the result summary returned to the main conversation. - Preload a skill: write a subagent using
skills: [api-conventions]; after starting a session, verify whether the skill content is already in the subagent’s context by asking the subagent “do you see api-conventions?“
10. Common pitfalls
Self-check
Self-check
- Can you describe the two-layer structure of Claude Code v2.1 subagents, and the default model and tool set for each of the three built-ins (Explore, Plan, general-purpose)?
- Can you write a subagent with complete frontmatter and a
descriptionthat triggers reliably? - For a real sub-task you have at hand, can you clearly state: the reasoning behind the
modelchoice, the minimumtoolsset, whetherisolation: worktreeis needed, whether and whichpermissionModeto use, and whetherskillspreloading applies? - Can you distinguish the relationship between subagents and skills? When should you use only one or the other, and when should you combine them?
Sources and further reading
Factual claims are grounded in official documentation; fast-changing items are annotated as of 2026-05.-
[1] Anthropic, “Create custom subagents,” code.claude.com, 2026. (two-layer structure; complete frontmatter reference;
isolation: worktree;skillspreloading;memorypersistence; v2.1.63Taskrenamed toAgent) https://code.claude.com/docs/en/subagents (as of 2026-06) -
[2] Anthropic, “Extend Claude with skills,” code.claude.com, 2026. (the two pairing paths between skills and subagents via
context: forkandskills:preloading) https://code.claude.com/docs/en/skills (as of 2026-06) -
[3] Anthropic, “Plugins reference,” code.claude.com, 2026. (plugin subagent restriction on
hooks/mcpServers/permissionMode) https://code.claude.com/docs/en/plugins-reference (as of 2026-06) -
[4] Anthropic, “Worktrees,” code.claude.com, 2026. (
isolation: worktreemechanism and default base branch behavior) https://code.claude.com/docs/en/worktrees (as of 2026-06) - [5] Agent Skills Open Standard, “Agent Skills,” 2026. (open standard for skill and subagent interoperability) https://agentskills.io (as of 2026-06)
-
[6] OpenAI, “Subagents,” developers.openai.com/codex, 2026. (
config.toml’s[agents]global parametersmax_threads/max_depth/job_max_runtime_seconds; individual agent TOML at~/.codex/agents/(personal) and.codex/agents/(project); required fieldsname/description/developer_instructions, optionalmodel/sandbox_mode/mcp_servers; noprompts/*.mdorcodex.md; persistent instructions useAGENTS.md) https://developers.openai.com/codex/subagents (as of 2026-06)
CLAUDE.mdand rules: see 04-1 CLAUDE.md and memory files and 04-2 rules.- Skills and frontmatter: see 04-4 Skills.
- Deterministic enforcement via hooks: see 04-6 Hooks.
- Context isolation concepts: see 01-4 Context engineering.
- Agent teams and multi-agent orchestration: see 04-11 Agent teams and sub-agents.