Subagents: How They Work in Claude Code, Cursor, Codex, and VS Code

A subagent is a secondary agent a primary agent delegates a task to, running in its own context window and returning only its result. How subagents are defined and invoked in Claude Code, Cursor, Codex, VS Code, Gemini CLI, and GitHub Copilot CLI, the orchestration patterns that work, and the specialized models built to run underneath them.

August 12, 2026 · 2 min read
Multi-agent over single-agent on Anthropic's research eval
90.2%
Multi-agent over single-agent on Anthropic's research eval
Of an agent's first turn spent retrieving context
60%+
Of an agent's first turn spent retrieving context
Token usage of multi-agent systems vs chat
15x
Token usage of multi-agent systems vs chat
Coding tools shipping native subagents
6
Coding tools shipping native subagents

What Is a Subagent?

A subagent is a secondary agent that a primary agent delegates a task to. It runs in its own context window, with its own system prompt and its own tool list, does the work, and returns only its result. The parent never sees the intermediate steps.

That isolation is what the primitive buys you. A search across a large repository might read 40 files to find the 2 that matter. Run inline, all 40 stay in the conversation for the rest of the session. Run in a subagent, the parent gets two file paths and a summary, and the other 38 are discarded with the subagent.

Three properties define the primitive, and all four major coding tools implement all three:

  • Isolated context. The subagent starts fresh and its working context is thrown away on return. Nothing it read enters the parent's context except what it chose to report.
  • Restricted tools. The subagent gets a narrower tool list than its parent. A search subagent that can read but not write cannot damage the repository, regardless of what it concludes.
  • Bounded lifetime. One task, one result, then it terminates. VS Code states this outright: "Each subagent invocation is stateless. The main agent can't send follow-up messages to the same subagent."

A subagent is not a separate process, a separate session, or a separate model by necessity. It is a scoped call that happens to be made by a language model instead of a function. The parent asks for a result and gets a result.

Why Subagents Exist

Agents got long-running before context windows got useful. A coding agent working a real task spends most of its turns finding things, and every one of those turns writes into the same context the model has to reason over later. Cognition measured this directly while building their search model: their agent trajectories were often spending more than 60 percent of the first turn just retrieving context.

Expanding the context window does not fix it. A model with a million tokens of room still has to attend across everything in that room, and the signal-to-noise ratio of a context full of rejected grep results is bad in a way that more room makes worse. The fix is to not put the rejected results there in the first place.

90.2%
“A multi-agent system with Claude Opus 4 as the lead agent and Claude Sonnet 4 subagents outperformed single-agent Claude Opus 4 by 90.2% on our internal research eval.”
Anthropic, How we built our multi-agent research system

The lead agent in that system was not smarter than the single agent. It was the same model. What changed is that the exploration happened somewhere else, and the lead agent's context stayed clean enough to plan over.

Anthropic reported that multi-agent systems use roughly 15 times more tokens than chat interactions. Subagents do not save tokens. They move tokens from an expensive context to a cheap one, which is a different and better property: the main model never pays to read the 38 files that did not matter.

For the retrieval half of this problem specifically, see agentic search and context engineering.

Subagents Across Six Coding Tools

Claude Code, Cursor, Codex, VS Code, Gemini CLI, and GitHub Copilot CLI all ship subagents, and the designs converged more than they diverged. The differences are in file format, in whether a subagent can spawn its own subagents, and in how much the user can invoke one directly.

Subagent implementations (October 2026)
Claude CodeCursorCodexVS CodeGemini CLICopilot CLI
Definition file.claude/agents/*.md.cursor/agents/.codex/agents/*.toml*.agent.md.gemini/agents/*.md.github/agents/*.agent.md
FormatMarkdown + YAML frontmatterAgent file (also reads .claude and .codex dirs)TOMLMarkdown + frontmatterMarkdown + YAML frontmatterMarkdown agent profile
Required fieldsname, descriptionall optionalname, description, developer_instructionsnone requiredname, descriptionname, description, instructions
Own context windowYesYesYes (agent thread)Yes (stateless per invocation)Yes (separate context loop)Yes (temporary subagent)
Built-in subagentsExplore, Plan, general-purposeExplore, Bash, Browserdefault, worker, explorerNone (user-defined)codebase_investigator, cli_help, generalist, browser_agentExplore, Task, General-purpose, Code-review
Background executionDefault in interactive sessions (fork mode)is_background flagParallel threads, consolidated resultAgent-initiatedAutomatic or forced with @nameExplore runs in parallel with other subagents
Nested subagentsUp to 3 layers by defaultYes, since Cursor 2.5agents.max_depth, default 1Up to 5 levels, opt-inNo (blocked by design)Not documented

Claude Code Subagents

Claude Code subagents are Markdown files with YAML frontmatter. Put one in .claude/agents/ to scope it to a project, or ~/.claude/agents/ to make it available in every project on your machine. Both directories are scanned recursively, and identity comes only from the name field, so the subdirectory layout is yours to organize.

.claude/agents/code-reviewer.md

---
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Glob, Grep
model: sonnet
---

You are a strict code reviewer. Report only correctness
issues and their file:line locations.

Only name and description are required. The description is what Claude reads to decide when to delegate, so it is a routing instruction, not documentation. The Markdown body becomes the system prompt: the docs note that subagents receive only this prompt plus basic environment details like the working directory, not the full Claude Code system prompt.

The frontmatter fields worth knowing

  • tools and disallowedTools scope what the subagent can call. Omit tools and it inherits everything available to subagents.
  • model takes an alias (sonnet, opus, haiku, fable), a full model ID, or inherit, which is the default. Routing a search subagent to a cheaper model is the main cost lever.
  • isolation: worktree runs the subagent in a temporary git worktree, giving it an isolated copy of the repository, cleaned up automatically if it makes no changes.
  • maxTurns caps agentic turns, which is the practical guard against a subagent that will not stop searching.
  • omitClaudeMd: true launches the subagent without the user, project, and local CLAUDE.md files, which suits a subagent that gets everything it needs from the task prompt.
  • background, memory, effort, skills, mcpServers, hooks, permissionMode, initialPrompt, and color round out the list.

Invocation goes through the Agent tool, which was called Task before v2.1.63; existing Task(...) references still work as aliases. By default a subagent can spawn subagents of its own, up to three layers below the main conversation. At the depth limit Claude Code withholds the Agent tool, so the deepest subagent does the work itself and returns one summary. Set CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH in settings.json to change the limit. When an agent runs as the main thread with claude --agent, Agent(worker, researcher) in its tools restricts which subagent types it can spawn.

Built-in Claude Code subagents

Claude Code registers three built-in subagents in interactive sessions. Explore is read-only and handles file discovery and code search. Plan does read-only research during plan mode. General-purpose gets every tool available to subagents and takes tasks that need both exploration and edits.

Explore changed in v2.1.198. It now inherits the main conversation's model instead of always running on Haiku, capped at Opus on the Claude API. To keep exploration cheap, define your own subagent named Explore with model: haiku; a user or project definition overrides the built-in. Set CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS=1 to remove Explore and Plan entirely. The same release removed the interactive wizard from /agents, so you create subagents by asking Claude or by writing the file. Run /tasks to see which model each running subagent is on.

Subagents in the Claude Agent SDK

In the Agent SDK, pass subagents through the agents option of query(). Each AgentDefinition needs a description and a prompt; tools, disallowedTools, model, skills, maxTurns, background, effort, and permissionMode are optional. Include Agent in allowedTools so delegation runs without a permission prompt. Programmatic definitions take precedence over files in .claude/agents/ with the same name.

agent_sdk_subagent.py

from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

options = ClaudeAgentOptions(
    allowed_tools=["Read", "Grep", "Glob", "Agent"],
    agents={
        "code-reviewer": AgentDefinition(
            description="Code review specialist. Use for security reviews.",
            prompt="Report security bugs with file:line. Skip style.",
            tools=["Read", "Grep", "Glob"],
            model="sonnet",
        ),
    },
)

async for message in query(prompt="Review the auth module", options=options):
    print(message)

The SDK guide says SDK subagents cannot spawn their own subagents, so leave Agent out of a subagent's tools list. The only channel from parent to subagent is the Agent tool's prompt string, so file paths, error messages, and earlier decisions have to be written into that prompt.

Editing subagents live

Claude Code watches .claude/agents/ and ~/.claude/agents/. Edit a subagent file mid-session and the next delegation uses the updated definition within a few seconds, with no restart. The one exception: if ~/.claude/agents/ did not exist when the session started, a running session will not detect it.

Related: skills, MCP, and plugins in Claude Code, and Claude Code hooks, which can be scoped to a single subagent through the hooks frontmatter field.

Cursor Subagents

Cursor documents subagents as "specialized AI assistants that Cursor's agent can delegate tasks to," each operating in its own context window and returning its result to the parent agent. Custom subagents live in .cursor/agents/ for a project and ~/.cursor/agents/ for a user, and Cursor also reads .claude/agents/ and .codex/agents/, so a repo with subagents defined for one tool works in the others without duplication.

The configuration surface is deliberately small: name, description, model (default inherit), readonly (default false), and is_background (default false). Three subagents ship built in: Explore searches and analyzes codebases, Bash runs series of shell commands, and Browser controls a browser via MCP tools.

Execution mode is the decision that matters. Foreground blocks until the subagent completes and returns the result immediately, which is right when the next step depends on it. Background returns immediately and lets the subagent work independently, which is right for long jobs and parallel streams. Since Cursor 2.5, subagents can launch child subagents.

Codex Subagents

Codex defines a subagent as "a delegated agent that Codex starts to handle a specific task," and an agent thread as "the thread where a subagent does its work." Supported clients let you open those threads to inspect progress, and /agent switches between them while they run.

Three agents are built in: default is the general-purpose fallback, worker is execution-focused for implementation and fixes, and explorer is the read-heavy codebase exploration agent. That split is the delegation pattern encoded as defaults, and it maps to what agents actually spend turns on.

Custom agents are standalone TOML files in ~/.codex/agents/ or .codex/agents/. Each must define name, description, and developer_instructions. Optional keys such as model, model_reasoning_effort, sandbox_mode, mcp_servers, and nickname_candidates inherit from the parent session when omitted. A custom agent named explorer overrides the built-in one.

.codex/agents/reviewer.toml

name = "reviewer"
description = "Reviews diffs for correctness before a PR opens"
model_reasoning_effort = "high"
sandbox_mode = "read-only"
developer_instructions = """
Read the diff. Report correctness bugs with file:line.
Do not comment on style.
"""

Concurrency and depth are global settings under [agents] in config.toml. agents.max_threads caps concurrent open agent threads and defaults to 6. agents.max_depth caps nesting and defaults to 1, which lets a direct child spawn but blocks deeper recursion. agents.job_max_runtime_seconds sets the per-worker timeout for spawn_agents_on_csv jobs and falls back to 1800 seconds. Codex only spawns a subagent when you ask it to, and when several are running it waits for every requested result before returning one consolidated response. Subagents inherit the parent's sandbox policy, and approval prompts from inactive threads surface in the main thread with the source thread labeled.

.codex/config.toml

[agents]
max_threads = 6
max_depth = 1
Looking for max_concurrent_threads_per_session or default_subagent_model?

Those key names come up in searches that land on this page, but neither appears in the current Codex subagents guide or configuration reference (checked October 1, 2026). Use agents.max_threads for the concurrency cap, and set model and model_reasoning_effort in each custom agent's TOML file to pick the model a spawned agent runs on.

More on this pattern: Codex multi-agent workflows.

VS Code Subagents

VS Code has no separate subagent type. A subagent is a custom agent, defined in an .agent.md file, that another agent invokes. Two frontmatter fields control which side of that line an agent sits on. user-invocable: false keeps the agent out of the agents dropdown in chat, creating an agent that is only accessible as a subagent. disable-model-invocation: true does the reverse, preventing the agent from being invoked as a subagent by other agents.

Invocation is agent-initiated rather than user-driven. The main agent needs the agent/runSubagent tool enabled, and the agents field on the parent restricts which subagents it may invoke: a list of names, * for all, or [] for none.

Two constraints are worth planning around. Each subagent invocation is stateless, so the main agent cannot send follow-up messages to the same subagent: whatever the parent needs must be in the initial task. And the requested model cannot exceed the cost tier of the main model, so a cheap parent cannot delegate upward to an expensive child. Subagents cannot invoke further subagents by default; enabling chat.subagents.allowInvocationsFromSubagents permits nesting up to 5 levels.

Gemini CLI Subagents

Gemini CLI exposes each subagent to the main agent as a tool with the subagent's name. The main agent delegates on its own when a task matches a subagent's description, or you can force one by starting a prompt with @ and the name, as in @codebase_investigator Map out the AgentRegistry.

Four subagents ship built in. codebase_investigator analyzes code and dependencies, cli_help answers questions about Gemini CLI itself, and generalist inherits the main agent's tools for broad multi-step work. browser_agent drives Chrome through the bundled chrome-devtools-mcp server and is off until you enable it under agents.overrides in settings.json.

.gemini/agents/security-auditor.md

---
name: security-auditor
description: Finds security vulnerabilities in code.
kind: local
tools:
  - read_file
  - grep_search
max_turns: 10
---

Report vulnerabilities with file:line. Do not fix them.

Custom subagents live in .gemini/agents/ for a project or ~/.gemini/agents/ for a user. Only name and description are required. model defaults to inherit, max_turns defaults to 30, and timeout_mins defaults to 10. The tools list accepts wildcards like mcp_*, and omitting it inherits every tool. Gemini CLI blocks recursion outright: a subagent cannot see or call other subagents, even with the * wildcard. Remote subagents over the Agent2Agent protocol use kind: remote.

GitHub Copilot Subagents

GitHub Copilot CLI runs custom agents as subagents. Each one is an .agent.md profile in .github/agents/ for a repository or ~/.copilot/agents/ for a user; when both define the same name, the home-directory version wins. The work runs in a temporary subagent with its own context window, so the main agent keeps its context for planning.

Four default agents ship with the CLI. Explore does quick read-only codebase analysis and can run in parallel with other subagents. Task runs tests and builds and returns a short summary on success or full output on failure. General-purpose takes complex multi-step work in a separate context, and Code-review reports only real issues in a change. You can pick a custom agent with /agent, name it in the prompt, let Copilot infer it from the agent's description, or select it from the command line. Restart the CLI after creating a new agent so it loads.

The Copilot SDK takes the same idea programmatically: pass customAgents when creating a session, each with a name and prompt plus optional tools, mcpServers, skills, model, and infer (default true, which lets the runtime pick the agent on its own).

Subagent Orchestration Patterns

Three patterns account for nearly all production subagent use. They differ in how results flow back, and that determines the cost profile.

Delegation

The parent hands one bounded task to one subagent and waits. Search, review, test-run. The simplest pattern and the one every tool optimizes for. Cost is one extra context, and the parent stays clean.

Fan-out

The parent spawns N subagents on independent slices of a problem and merges their results. Codex consolidates all requested results into one response. Latency is the slowest subagent, not the sum, but token cost scales with N.

Pipeline

One subagent's output is the next one's input: explore, then plan, then implement. Codex encodes this in its built-ins with explorer and worker. Each stage discards its own working context before the next begins.

Rules that hold across all three

  • Fan out on independence, not on size. Two subagents editing the same file serialize on merge conflicts and cost more than doing the work inline. Cursor's parallel-agent workflow gives each agent its own git worktree for exactly this reason, and Claude Code offers the same through isolation: worktree.
  • The return value is the design. A subagent returns a summary, and everything it saw but did not report is gone. Specify the output format in the system prompt: file paths and line ranges, not prose about what it looked at.
  • Restrict tools by default. A subagent that only needs to read should not be able to write. Cursor has readonly, Claude Code has tools and disallowedTools, VS Code has per-agent tool lists.
  • Cap the turns. Without maxTurns or its equivalent, an unproductive search subagent burns its whole budget before reporting failure.
  • Do not use a subagent for a short task. Spawn overhead and the summarization round trip cost more than the work.

Specialized Models for Subagents

A subagent runs one kind of task repeatedly. That is the condition under which a specialized model beats a frontier model, and it is why the 15x token multiplier is survivable: the multiplier applies to the cheap contexts.

Three workloads dominate subagent traffic, and Morph builds a model for each.

WarpGrep: the search subagent

Agentic repository search, #1 on SWE-Bench Pro. Issues parallel tool calls across a small number of turns and returns file spans rather than whole files, which is the output format a parent context can actually afford.

Fast Apply: the edit subagent

Merges LLM-proposed code edits into files at 10,500+ tok/s with sub-second cold starts. The frontier model writes the diff intent; Fast Apply does the mechanical merge, so no frontier tokens are spent reproducing unchanged lines.

Compact: the context subagent

Compresses context at 33,000 tok/s, shrinking it 50-70% while keeping every surviving sentence verbatim. A 90-second compaction stall becomes about 2.5 seconds, which is the difference between a visible pause and none.

The pattern is the same in all three cases. Take the loop the parent agent runs most, and make it a model that does only that. WarpGrep replaces the exploration turns that Cognition measured at more than 60 percent of the first turn. Fast Apply replaces full-file rewrites. Compact replaces the compaction pause.

Point a subagent at a different model

Every implementation here supports per-subagent model selection: model in Claude Code and Cursor, model in a Codex agent's TOML file, model in VS Code and Gemini CLI. Morph serves an OpenAI-compatible API, so pointing a subagent at a specialized model is a base-URL and model-name change, not a rewrite.

FAQ

What is a subagent?

A subagent is a secondary agent that a primary agent delegates a task to. It runs in its own context window, with its own system prompt and its own tool list, performs the task independently, and returns only its result to the parent. The parent never sees the intermediate steps. This keeps exploration output out of the main conversation, which is why every major coding tool now ships subagents.

What is the difference between an agent and a subagent?

An agent owns the conversation with the user and decides what to do next. A subagent is spawned by that agent to handle one bounded task and then terminates. The structural difference is context: the agent accumulates the full session history, while a subagent starts with only its system prompt plus the task it was handed, and its working context is discarded when it returns. A subagent also usually has a narrower tool list than its parent.

How do I create a subagent in Claude Code?

Create a Markdown file with YAML frontmatter in .claude/agents/ for a project-scoped subagent, or ~/.claude/agents/ for one available everywhere. Only name and description are required; tools, model, maxTurns, isolation, and the rest are optional. The Markdown body becomes the system prompt. Claude Code watches both directories and picks up edits within a few seconds without a restart.

Do subagents have their own context window?

Yes, in every implementation covered here. Claude Code documents that each subagent runs in its own context window with a custom system prompt, specific tool access, and independent permissions. Cursor documents that each subagent operates in its own context window. VS Code documents that each subagent invocation is stateless and the main agent cannot send follow-up messages to the same subagent. Codex runs each subagent in its own agent thread.

Can subagents run in parallel?

Yes. Codex spawns agents in parallel when you ask it to and waits until all requested results are available before returning a consolidated response; agents.max_threads caps concurrent open threads and defaults to 6. Cursor offers foreground mode (blocks until complete) and background mode (returns immediately). Claude Code runs the subagents Claude spawns in the background in interactive sessions, where fork mode is on by default. GitHub Copilot CLI can run its read-only Explore agent in parallel with other subagents.

Do subagents cost more tokens?

In aggregate, yes. Anthropic reported that multi-agent systems use roughly 15 times more tokens than chat interactions. The trade is that those tokens are spent in cheap, disposable contexts rather than the expensive main one, and the main model never pays to read the exploration output. Routing subagent work to a smaller or specialized model is the standard way to make the economics work.

When should you not use a subagent?

When the parent needs the intermediate reasoning rather than just the answer. Subagents return a summary, so anything seen but not reported is gone. If the task needs back-and-forth, a subagent is the wrong primitive: VS Code makes this explicit by documenting that each invocation is stateless. Short tasks are also a bad fit, because spawn overhead exceeds the work.

Can a subagent spawn its own subagents?

In Claude Code, yes, up to three layers below the main conversation by default, adjustable with CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH; Agent SDK subagents cannot. In Cursor, yes since version 2.5. In VS Code, not by default, but enabling chat.subagents.allowInvocationsFromSubagents allows nesting up to 5 levels. In Codex, agents.max_depth defaults to 1, so a direct child can spawn and deeper nesting is blocked. In Gemini CLI, no: subagents cannot call other subagents.

How do I limit Codex subagent concurrency and depth?

Set them under [agents] in config.toml. agents.max_threads caps concurrent open agent threads and defaults to 6, and agents.max_depth defaults to 1. Set the model and reasoning effort for a spawned agent in its TOML file with model and model_reasoning_effort. The current Codex docs do not list max_concurrent_threads_per_session or default_subagent_model.

Does Gemini CLI support subagents?

Yes. Gemini CLI ships codebase_investigator, cli_help, generalist, and a browser_agent that is off by default. Custom subagents are Markdown files in .gemini/agents/ or ~/.gemini/agents/ with name and description required. Force one with @name at the start of a prompt.

Specialized models for the subagents you already run

WarpGrep for search, Fast Apply for edits at 10,500+ tok/s, Compact for context compression at 33,000 tok/s. One OpenAI-compatible API. Point any subagent at it with a base-URL change.