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]):2.1 Built-in subagents
Explore and Plan have a special design: they skip
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]:
Claude Code recursively scans
.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:
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]:1
CLAUDE_CODE_SUBAGENT_MODEL environment variable
Highest priority. Set this at launch to uniformly specify the model for all subagents, overriding everything else.
2
model parameter at invocation time
The model parameter passed by the caller at invocation time, taking precedence over frontmatter.
3
Subagent frontmatter model
The
model field declared in the subagent file. model: inherit (default) means use the same model as the main conversation.4
The main conversation's model
Fallback to the model currently in use by the main conversation when none of the above is specified.
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
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?
Worktree workflow:
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: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):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 evolve quickly; verify against each vendor’s current documentation before adopting.
- 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.