Claude Code Subagents: How They Work and When to Use Them

Claude Code subagents run a side task in their own context window with their own tools. How to build one, when to use them, and when to skip.

Published Updated

Claude Code Subagents: How They Work and When to Use Them

Claude Code subagents are specialized assistants that do a side task in their own context window and hand back a summary. Use them to keep search results, logs, and file reads out of your main build conversation when the task can return a compact answer.

A subagent is a function you delegate to: Claude hands it a job, it works in a separate context, and it returns a result. Used well, it keeps Claude Code focused across a long session. Used badly, it burns tokens and adds latency for no gain. The decision turns on whether the task can stand alone and whether its conclusion is more useful than its intermediate output.

The quick version

A non-fork subagent runs a self-contained side task in its own isolated context, then returns a summary to your main conversation. It solves a specific problem: long agentic sessions fill up with noise, including search results, build logs, and files read once and never referenced again.

Move that noisy work into a subagent and the clutter stays over there. Your main thread sees the conclusion. The useful mental model is context hygiene with a return value. Isolation earns its keep when the worker can investigate independently and report what you need to decide next. Anthropic's subagent guide describes this same division of work.

What a subagent actually is

A subagent runs in its own context window with a custom system prompt and configured tool access. Its permissions remain subject to the main session's permission rules. When Claude hits a task that matches a subagent's stated job, it can delegate; the subagent works and returns its result.

A non-fork subagent starts fresh. It does not inherit your conversation history, the files Claude already read, or the skills you already invoked. Claude composes a delegation message that summarizes the task. The subagent gets its own system prompt and environment details, not the full Claude Code system prompt. Custom subagents normally also load your CLAUDE.md instructions and a git-status snapshot, plus any configured skills and persistent memory. Explore and Plan skip CLAUDE.md and git status. A conversation fork is the exception to the fresh-start rule. Startup context reference.

That isolation cuts both ways:

  • The win: the verbose middle, including files read and logs scanned, stays out of your main context. You get the answer without the mess.
  • The cost: the subagent may need to gather context you already had. If the task depends on your discussion, include the relevant decisions in its brief or use a conversation fork.

Before writing a custom worker, check the built-in subagents:

  • Explore handles code search and codebase investigation with read-only tools. It normally uses the main conversation's model; when the main model is Fable, the connection type can instead make Explore use the Opus alias. It is not automatically a Haiku worker.
  • Plan gathers codebase context during plan mode with read-only tools and normally inherits the main model.
  • general-purpose handles research that also needs action, including code changes, using the available subagent tools and normal model-selection rules.
  • claude is a catch-all worker; statusline-setup uses Sonnet for /statusline; claude-code-guide uses Haiku for questions about Claude Code.

Create a custom definition when you repeatedly need the same instructions, tool restrictions, or model choice. A one-off search usually does not need its own agent file.

The file that defines one

A custom subagent is a Markdown file with YAML frontmatter. The frontmatter is the configuration; the Markdown body becomes the subagent's system prompt. Only two fields are required: name and description. Field names are case-sensitive configuration keys: use the documented camelCase spelling. Frontmatter reference.

Markdown
---
name: code-reviewer
description: Reviews modified files for quality and best practices. Use after code changes.
tools: Read, Glob, Grep
model: sonnet
effort: medium
---

Review the files identified in the delegation message. Check clarity,
error handling, exposed secrets, input validation, and test coverage.
Use any supplied diff as context. Do not modify files. Return findings
with file paths and reasons, grouped as critical issues, warnings,
then suggestions. Say which files or evidence you could not inspect.

The parent should supply the changed-file list or relevant diff. This worker has no shell tool, so its prompt does not ask it to run git diff. The description tells Claude when to delegate; the body tells the worker how to do the job. Keep the description specific and put detailed review rules in the body.

Claude Code product page
Claude Code

You do not have to hand-write the file. Ask Claude to create it in the appropriate agent directory. The current /agents command prints a reminder to ask Claude or edit the files; it no longer opens the old Running and Library wizard. Claude Code watches existing .claude/agents/ and ~/.claude/agents/ directories, so edits normally apply to the next delegation without a restart. Restart after creating a scope's first agents directory, editing agents in an added directory, or when the session uses --disable-slash-commands. File-loading behavior.

Other fields let you set a permission mode with permissionMode, cap a run with maxTurns, preload skills, attach mcpServers or hooks, enable memory, choose background execution, omit selected instructions with omitClaudeMd, or isolate repository work with isolation. They are optional controls for a defined job, not a checklist every worker needs. Plugin definitions have additional field restrictions, so consult the reference before copying a local agent into a plugin.

Where subagents live, and who wins

Location decides who can use a definition and which one wins when names collide.

LocationScopeCheck into git?
.claude/agents/This project onlyYes, share it with the team
~/.claude/agents/All your projects, personalNo, it is your home directory
Plugin agents/Where the plugin is enabledVia the plugin
Managed settingsOrganization-wideOrganization-controlled
--agents JSONCurrent sessionNo agent file is saved

The priority order is managed, CLI --agents, project, user, plugin. Project subagents are discovered by walking up from your working directory to the repository root; the nearest project definition wins a nested name clash. The session-only --agents option is useful for automation or a temporary worker. Its JSON uses agent names as keys and a prompt field for the system prompt, alongside settings such as model, effort, and tools. Scope and CLI reference.

The practical rule: a subagent that encodes how this codebase should be reviewed or tested belongs in .claude/agents/ and goes into version control. A subagent that reflects how you personally like to work belongs in ~/.claude/agents/.

Model, effort, and tools: the dials that matter

Choose the model for the task, effort for the requested depth, and tools for the actions the worker should take. These settings affect whether splitting the work is worth the overhead.

Verified and updated October 12, 2026: since October 9, Claude Code 2.1.296 supports autoCompactWindow in subagent frontmatter and --agents definitions for earlier worker compaction. 2.1.295, October 8 capped skill preloading at 32 distinct skills; 2.1.292, October 6 added per-invocation effort to the Agent tool. Together, these controls help you size a worker's starting instructions and execution to its job.

Model. The model field accepts sonnet, opus, haiku, fable, a full model ID, or inherit. Explicit model: inherit selects the main conversation's model. Omitting the field is different: the normal resolution order is the invocation's model, then the definition's model, then CLAUDE_CODE_SUBAGENT_MODEL, then the main model. Organization policies can substitute an allowed model, and an installed mod can replace the invocation's choice. Model selection.

Effort. Set effort in the agent definition when that worker should routinely use a particular level. The documented options are low, medium, high, xhigh, and max, with availability depending on the model. You can also ask Claude to run a particular non-fork worker at a chosen effort: the Agent tool's invocation parameter overrides the definition and persists when the worker resumes. CLAUDE_CODE_EFFORT_LEVEL takes precedence over both. That lets an occasional difficult review request more effort without creating another agent definition. Effort precedence.

Tools. A subagent inherits the tools available to its kind of run, not necessarily every tool in the main session. Background workers have a narrower built-in pool. tools is an allowlist; disallowedTools removes tools from the pool, including a tool named in both fields. For the read-only reviewer above, keep Read, Glob, Grep and omit shell, editing, and external-action tools. Subagent tool rules.

Adding Bash breaks the claim that a worker cannot change files: Bash executes shell commands. Removing Write and Edit while retaining a shell is not a filesystem write barrier. Likewise, adding persistent memory automatically enables writing tools, so review that choice before calling a worker read-only. Tool reference, memory behavior.

Starting context and compaction. Use skills for instructions the worker needs immediately. The first 32 distinct skill names are preloaded in full; a worker with the Skill tool can still invoke other available skills later. Put essential conventions first and keep the list focused. A long preload list is a reason to narrow the worker's job, not automatically a reason to spawn more workers. Skill preloading.

autoCompactWindow lets a long-running subagent compact earlier than the main conversation's window. Compaction summarizes accumulated context so work can continue. This can suit a worker collecting verbose investigation output, but it does not make an interdependent task self-contained. The changelog confirms the field; the current subagents reference does not yet document its accepted values. Compaction release note.

One more control worth knowing: isolation: worktree gives the worker a temporary git worktree, a separate repository checkout. It normally starts from your default branch rather than the parent session's current HEAD, and is cleaned up automatically if unchanged. Use it for work that should not edit your current checkout, while making sure the worker starts from the code it needs. Worktree behavior.

When to use a subagent, and when not to

A subagent consumes tokens and coordination time, so ask whether isolation pays for itself on this task.

  1. Ask: is the output verbose and disposable?

    The classic win is a task that generates intermediate output you will not need later: scanning a codebase, answering a question across many files, or triaging a noisy log. Ask the worker to return the conclusion, supporting file paths, and unresolved questions.

  2. Ask: is the task self-contained?

    A non-fork subagent shines when the delegation message contains the job. "Find every place we call the billing API and list them" is self-contained. "Continue what we were discussing" needs the missing decisions supplied, or a conversation fork that inherits them.

  3. Ask: do I need a tool boundary?

    Use an explicit allowlist when the worker should only inspect files. Keep shell tools and memory-enabled writing out of a read-only definition. Choose a separate worktree when the worker should make changes without editing your current checkout.

Keep these cases in the main conversation:

  • Iterative back-and-forth. Frequent refinement and your judgment in the loop are easier to retain in the same thread.
  • Phases that share substantial context. Planning, implementation, and testing may be better together. Chaining subagents is supported, but the caller must pass the relevant findings onward.
  • Quick, targeted changes. Delegation overhead rarely earns its keep on a typo.
  • Latency-sensitive work. A fresh worker may spend time gathering context before it can answer.

Subagent vs skill vs fork vs agent team

Choose by how much context and coordination the work needs.

MechanismContextReach for it when
SkillUsually the main conversation; can run in an isolated subagent with context: forkYou want reusable instructions or a workflow
Non-fork subagentFresh context; reports to its callerThe work is verbose and self-contained
Conversation forkInherits the conversation so farA side task needs your existing decisions and history
Agent teamEach teammate has an independent contextWorkers need discussion and shared coordination

A skill packages reusable instructions. A subagent packages a worker's prompt and execution settings. They can work together: a subagent can preload skills, and a skill can launch a subagent with context: fork. Despite that name, a skill's context: fork does not copy your conversation history. Skill execution reference.

A conversation fork does inherit the system prompt, tools, model, and message history. Its own tool output stays outside the main conversation and its final result returns. Use /subtask to start one. Fork mode is enabled by default in interactive sessions and disabled by default in non-interactive -p and Agent SDK sessions; CLAUDE_CODE_FORK_SUBAGENT overrides those defaults. Conversation forks.

An agent team adds sustained peer coordination and is experimental, disabled by default. You do not need a team merely to run independent subagent investigations in parallel. Agent-team comparison.

The power features, and their limits

Nesting and memory help repeated or larger jobs, but each changes the worker's responsibilities.

Nesting. The default is now three subagent layers below the main conversation, configurable with CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH. Set it to 1 to disable nesting. At the depth limit, ordinary subagents do not receive Agent; forks retain the tool but further spawn attempts fail. The old fixed five-layer rule no longer applies. In an interactive session, nested workers report through their launcher; in non-interactive and SDK runs, a nested background worker can report to main if its launcher has already finished. Keep a reviewer from delegating at all by omitting Agent from its tool allowlist. Nesting limits.

Memory. Add memory: project, user, or local to give the worker a persistent directory. Project memory is shareable through version control; user memory spans projects; local memory stays project-specific without being checked in. Claude Code includes the first 200 lines or 25KB of MEMORY.md, whichever comes first, so curate that file. Memory requires auto memory to be enabled and automatically enables Read, Write, and Edit. It is useful for retaining conventions, but changes the tool access of a supposedly read-only reviewer. Persistent memory.

The upside
What it does well
8 points

  • Keeps verbose investigations out of the main session
  • Supports focused tool allowlists and separate repository worktrees
  • Lets model and effort choices match the delegated job
  • Can retain curated conventions through persistent memory
  • Fresh workers may repeat context gathering, adding latency and tokens
  • Large returned reports still consume main-session context
  • Peer messaging is possible, but coordination still needs a clear owner
  • Nesting, skill preloads, and memory can expand a worker beyond its intended scope

A good first move: define a focused read-only code-reviewer, check it into .claude/agents/, and supply the files and decisions it needs for each review. Add another specialist when a recurring job justifies different instructions, model, effort, or tools. If you are choosing between coding tools in the first place, that is a different decision, covered in Codex vs Claude Code vs Cursor and the wider field in the best AI coding agents.

What is the difference between Claude Code subagents and skills?

A skill supplies reusable instructions; a subagent supplies a worker with its own prompt and execution settings. Skills usually run in your main context, but context: fork runs one in a fresh subagent without your conversation history. A conversation fork is different: it inherits that history.

How deep can Claude Code subagents nest?

The default is three layers below the main conversation. Change it with CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH; setting it to 1 prevents subagents from spawning their own workers. A tool allowlist without Agent prevents an individual worker from delegating.

Do Claude Code subagents cost extra?

Subagents send their own requests and count toward the same usage limits as the main conversation. They consume tokens, and returned reports also occupy main-session context. Use them for work where isolation is useful, not as a promise of lower total cost.

Where do I store a subagent file?

Put project-specific definitions in .claude/agents/ and personal ones in ~/.claude/agents/. On a name clash, priority runs from managed definitions to CLI --agents, project, user, then plugin definitions. Within nested project directories, the closest definition wins.

Can I make a subagent use a cheaper model?

Yes. Set model: haiku for a suitable bounded task. Explicit model: inherit uses the main model, while an omitted field follows the model-selection order. A per-invocation choice normally outranks the definition; forcing the subagent model through environment settings changes that behavior. Check /tasks for the model used.

If you are wiring Claude Code into how you actually ship, that is most of what I write about. Join the newsletter for the working setups, not the launch-day hype.

Last Updated
Category
AI
Related Articles
NotebookLM vs ChatGPT

NotebookLM vs ChatGPT

Compare NotebookLM and ChatGPT Projects for client research, onboarding, meeting prep and reports, with verified limits and sharing rules.Oct 20, 2026AI
AI Acceptable Use Policy: A One-Page Template for Small Business

AI Acceptable Use Policy: A One-Page Template for Small Business

Copy a one-page AI acceptable use policy covering approved accounts, customer data, human review and disclosure, then roll it out in one team meeting.Oct 19, 2026AI
Best AI for Data Analysis in 2026: ChatGPT, Claude, Julius AI, Gemini and Copilot (Compared)

Best AI for Data Analysis in 2026: ChatGPT, Claude, Julius AI, Gemini and Copilot (Compared)

Compare ChatGPT, Claude, Julius AI, Gemini and Copilot for CSVs, spreadsheets and reports, with maker-sourced file limits and data policies.Oct 19, 2026AI
Microsoft 365 Copilot Pricing: Plans, Bundles and Agent Costs

Microsoft 365 Copilot Pricing: Plans, Bundles and Agent Costs

Compare Microsoft 365 Copilot prices, Business bundles, annual commitments and agent charges, with seat-cost comparisons against ChatGPT and Claude.Oct 19, 2026AI
Multimodal AI: What It Means for Your Business

Multimodal AI: What It Means for Your Business

What multimodal AI accepts and returns, how current models differ, and what invoices, meetings, product videos and voice agents need.Oct 19, 2026AI
ChatGPT for Business: What Your Team Gets Beyond Plus

ChatGPT for Business: What Your Team Gets Beyond Plus

What ChatGPT Business adds beyond Plus: shared work, Work, Codex, data privacy and admin controls, plus when your company needs Enterprise.Oct 19, 2026AI
Kimi vs Claude

Kimi vs Claude

Kimi vs Claude for coding, agents and long documents: current models, context limits, hosting choices and when switching to K3 makes sense.Oct 19, 2026AI
Claude vs Copilot: Microsoft 365 for Daily Work

Claude vs Copilot: Microsoft 365 for Daily Work

Choose Claude or Microsoft 365 Copilot for documents, email, meetings and analysis, with verified access controls and three worked business jobs.Oct 19, 2026AI
Newsletter

One letter, every Sunday.Working systems, not hot takes.

Weekly. No spam. Unsubscribe anytime.