Skip to main content
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, and isolation, 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: worktree is needed, whether to preload skills, and whether permissionMode is appropriate.
  • Explain the division between subagents and skills: a skill is a procedure; a subagent is an execution container. A skill uses context: fork to run a procedure inside a subagent; a subagent uses skills: 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.
Connecting back to 01-4 context engineering01-4 compares the context window to RAM: cost accumulates linearly over the conversation. A subagent is “putting a large task into swap space.” Main RAM sees only the final conclusion, not the intermediate search noise. The distinction from a skill is that a skill puts “a procedure description” into the current context, while a subagent puts “the entire execution” into an isolated context.

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-purpose is 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].
When to choose project-level vs user-levelProject-level (.claude/agents/) goes into version control and is shared with the team, so it is appropriate for subagents specific to this codebase. User-level (~/.claude/agents/) is available across all projects and is appropriate for subagents you use in all your work, such as a personal code review agent.
Plugin subagents restrict three frontmatter fieldsFor security reasons, plugin subagents do not support the hooks, mcpServers, or permissionMode fields; these are silently ignored [1]. If you need any of the three, copy the agent file into .claude/agents/ or ~/.claude/agents/. Alternatively, add rules to settings.json’s permissions.allow, but that rule applies to the entire session, not just the plugin agent.

4. Full frontmatter reference

Subagent file format (as of 2026-06, per the official subagents documentation [1]):
Only 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.
Use a cheaper model (Haiku) for repetitive, structurally clear sub-tasks; reserve Sonnet / Opus for tasks with genuine reasoning demands. This is the most direct cost-saving lever in subagent design.

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):
Blocklist example (inherit all tools but block writes):
Tools that cannot be used in subagentsEven if listed in tools, the following tools cannot be used in a subagent [1]:
  • Agent (a subagent cannot spawn another subagent)
  • AskUserQuestion
  • EnterPlanMode
  • ExitPlanMode (unless permissionMode: plan)
  • ScheduleWakeup
  • WaitForMcpServers

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]:
This is an allowlist: only 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

Parent session mode takes precedenceIf the main session uses bypassPermissions or acceptEdits, the subagent cannot override it ([1]). If the main session uses auto mode, the subagent inherits auto mode and the permissionMode in frontmatter is ignored: the classifier evaluates subagent tool calls using the same rules as the main session.bypassPermissions skips all permission prompts, including writes to .git, .claude, .vscode, .idea, .husky, and .cargo. rm -rf on root or home directories still prompts as a circuit breaker [1].

4.5 skills: preloading skill content into a subagent

The full content of each listed skill is injected into the subagent context at startup. This controls “what is preloaded,” not “what can be invoked”: skills not listed can still be discovered and invoked at runtime via the Skill tool from project / user / plugin skills [1]. Preloading has one reverse constraint: skills with 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].
Subagent preloading a skill vs a skill running inside a subagentThese are two views of the same underlying mechanism ([1]):
  • Subagent frontmatter skills: [...]: the subagent controls its system prompt and loads skill content into it.
  • Skill frontmatter context: fork + agent: ...: skill content becomes the task prompt for the specified agent, which runs in a clean context.
The two are the same thing underneath, just written from opposite ends.

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].
Worktree behavior:
  • 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.
cd inside a subagent does not persistA cd inside a subagent does not persist across Bash / PowerShell tool calls and does not affect the main session’s working directory [1]. Use isolation: worktree when you need an isolated working directory.

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
  1. Will this subagent write files or modify external state? No: no worktree needed.
  2. Will the subagents running in parallel write to overlapping paths? Yes: use worktrees.
  3. 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: [...])
Path B: skill uses context: fork to push into a subagent
Both paths share the same underlying mechanism; the difference is “who defines the procedure and who defines the container” [1].
context: fork requires the skill to contain an explicit taskIf the skill content is purely prescriptive (“follow these API conventions”) with no explicit task, context: fork delivers “conventions” to the subagent with nothing to do, and it returns an empty result. context: fork is for procedural skills that contain concrete steps [1].

7. Invoking a subagent

7.1 Automatic invocation

Claude reads the subagent’s description 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 Task to Agent in v2.1.63 (old Task(...) 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/*.md or codex.md; persistent instructions use AGENTS.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
  1. Write a read-only subagent: create ~/.claude/agents/api-explorer.md, give the frontmatter tools: Read, Glob, Grep and model: haiku, and write a body that says “scan the endpoints under src/api/ and report each endpoint’s method, path, and authentication requirements.” Use /agents to confirm it appears in the Library.
  2. Write a writable subagent: create .claude/agents/doc-fixer.md, give it tools: Read, Edit, Grep, model: haiku, and permissionMode: acceptEdits, with a body that says “replace every TODO in .md files with an anchor linking to the corresponding issue.” Invoke it explicitly with @doc-fixer in the same project.
  3. Isolation test: write a subagent with isolation: worktree and 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.
  4. Skill + subagent: write a skill using context: fork and agent: Explore; invoke the skill and observe it running in an isolated context, with the result summary returned to the main conversation.
  5. 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

Anti-pattern list
  • Using the strongest model for every subagent: repetitive, structured sub-tasks need only Haiku-class models; reserve Opus for tasks that genuinely require deep reasoning, otherwise costs compound linearly.
  • Granting overly broad tool permissions: giving Write and Bash to a read-only task defeats the purpose of isolation and increases supply chain risk. Default to an allowlist of the minimum required set.
  • Writing a skill procedure into the subagent description when there is no reuse need: if you only use it once, there is no need to force a skill; writing the procedure directly in the subagent body is simpler.
  • isolation: worktree on a read-only task: no writes means no need for a worktree; adding one wastes disk space and creation time.
  • Expecting the model to trigger without a designed description: model triggering is semantic matching; descriptions that are too vague, too technical, or too broad will all cause missed triggers.
  • Using a subagent as a thread: subagents are one-shot containers that are destroyed when the task ends. For persistent conversation and addressable agents, use an agent team (see 04-11).
  • Putting sensitive information in the subagent body: the body goes into context and, if version-controlled, is visible to everyone. Use environment variables or dynamic injection for secrets.

Self-check

Self-check
  1. 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)?
  2. Can you write a subagent with complete frontmatter and a description that triggers reliably?
  3. For a real sub-task you have at hand, can you clearly state: the reasoning behind the model choice, the minimum tools set, whether isolation: worktree is needed, whether and which permissionMode to use, and whether skills preloading applies?
  4. 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; skills preloading; memory persistence; v2.1.63 Task renamed to Agent) 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: fork and skills: 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: worktree mechanism 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 parameters max_threads / max_depth / job_max_runtime_seconds; individual agent TOML at ~/.codex/agents/ (personal) and .codex/agents/ (project); required fields name / description / developer_instructions, optional model / sandbox_mode / mcp_servers; no prompts/*.md or codex.md; persistent instructions use AGENTS.md) https://developers.openai.com/codex/subagents (as of 2026-06)