> ## Documentation Index
> Fetch the complete documentation index at: https://lib.findy.co.jp/llms.txt
> Use this file to discover all available pages before exploring further.

# What is a subagent? Delegating scoped tasks to agents

> A subagent is a separate agent instance with its own context window, system prompt, and tool scope. A main agent delegates a scoped task to it and receives only the result.

## Overview

A subagent is a separate agent instance that a main agent delegates a scoped
task to. It runs with its own context window, its own system prompt, and its
own set of tools, and returns only its final message to the caller.

The boundary that defines it is the context boundary. Work that produces bulky
intermediate output — searching a codebase, reading logs, fetching API
responses — happens inside the subagent, and the main conversation receives the
conclusion instead of the raw material.

The mechanism is not specific to one product, so this page treats the subagent
as a general pattern and gives each tool's concrete definition format and paths
where they matter. It covers what subagents are for, how a definition is
structured, how one is invoked and composed, and how to design one.

## What subagents are for

Delegating to a subagent buys four things. A given subagent usually exists for
one of them, and naming which one clarifies how it should be defined.

<CardGroup cols={2}>
  <Card title="Context isolation" icon="layer-group">
    Exploration, log analysis, and API responses stay inside the subagent's own
    context window. Only the summary crosses back, so the main conversation
    does not fill with material that no decision depends on.
  </Card>

  <Card title="Constrained capability" icon="lock">
    A subagent runs with the tools its definition grants and nothing else. A
    judgment-only role can be given no write tools at all, which makes the
    restriction structural rather than a matter of following instructions.
  </Card>

  <Card title="Reusable roles" icon="arrows-rotate">
    A role definition is a file. Checked into a repository it is shared by the
    team; placed in the user directory it follows one person across projects.
  </Card>

  <Card title="Cost control" icon="coins">
    Each subagent selects its own model, so mechanical classification runs on a
    cheaper tier without lowering the model the main conversation uses.
  </Card>
</CardGroup>

## Anatomy of a subagent

### Definition file

A subagent is defined as a file holding two things: metadata that identifies the
role and scopes its capability, and the instructions that become the subagent's
system prompt.

The file format differs by tool. Claude Code and GitHub Copilot CLI use Markdown
with YAML frontmatter, where the frontmatter is the metadata and the body is the
system prompt. Codex CLI uses TOML, where the instructions are one field among
the rest.

<CodeGroup>
  ```md Claude Code theme={null}
  ---
  name: code-reviewer
  description: Code review specialist. Reviews a diff for quality, security, and maintainability. Use immediately after writing or modifying code.
  tools: Read, Grep, Glob, Bash
  model: sonnet
  ---

  You are a code reviewer responsible for quality and security.

  Read the diff for the range given in the prompt, review only the changed files,
  and report findings. Do not edit files.

  Group findings by priority (critical / warning / suggestion) and give a
  specific fix for each. Return only the findings block, with no preamble.
  ```

  ```md GitHub Copilot CLI theme={null}
  ---
  name: code-reviewer
  description: Code review specialist. Reviews a diff for quality, security, and maintainability. Use immediately after writing or modifying code.
  ---

  You are a code reviewer responsible for quality and security.

  Read the diff for the range given in the prompt, review only the changed files,
  and report findings. Do not edit files.

  Group findings by priority (critical / warning / suggestion) and give a
  specific fix for each. Return only the findings block, with no preamble.
  ```

  ```toml Codex CLI theme={null}
  name = "code_reviewer"
  description = "Code review specialist. Reviews a diff for quality, security, and maintainability."
  sandbox_mode = "read-only"
  developer_instructions = """
  You are a code reviewer responsible for quality and security.

  Read the diff for the range given in the prompt, review only the changed files,
  and report findings. Do not edit files.

  Group findings by priority (critical / warning / suggestion) and give a
  specific fix for each. Return only the findings block, with no preamble.
  """
  ```
</CodeGroup>

The metadata covers the same handful of roles, though not every tool exposes
all of them, and the field names and requirements differ.

| Role           | Typical field                           | Purpose                                                                                                                                                    |
| -------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Identifier     | `name`                                  | The handle used to address the subagent explicitly.                                                                                                        |
| When to use it | `description`                           | The main agent matches requests against this text to decide whether to delegate, so it determines whether the subagent is reached at all.                  |
| Tool scope     | `tools`, or `sandbox_mode` in Codex CLI | What the subagent may do. Where a tool list can be omitted, the subagent inherits the tools available to subagents.                                        |
| Model          | `model`                                 | Which model runs the subagent. Claude Code accepts an alias such as `haiku`, a full model ID, or `inherit`, and defaults to inheriting the caller's model. |
| Instructions   | The body, or `developer_instructions`   | The system prompt the subagent runs under.                                                                                                                 |

<Note>
  Requirements differ by tool: Claude Code requires `name` and `description`,
  GitHub Copilot CLI requires only `description`, and Codex CLI requires
  `name`, `description`, and `developer_instructions`. Each tool also adds
  optional fields of its own — disallowed tools, permission or sandbox mode,
  preloaded skills, lifecycle hooks, MCP servers. Confirm the field names and
  requirements in the documentation of the tool you use.
</Note>

### Where definitions live

Definition files are picked up from several locations, and the location decides
who the subagent is available to. The scopes are the same across tools; the
paths differ.

| Scope   | Available to                                                          | Claude Code         | GitHub Copilot CLI   | Codex CLI          |
| ------- | --------------------------------------------------------------------- | ------------------- | -------------------- | ------------------ |
| Project | The repository. Version-controlled, so the team shares one definition | `.claude/agents/`   | `.github/agents/`    | `.codex/agents/`   |
| User    | Every project of one user                                             | `~/.claude/agents/` | `~/.copilot/agents/` | `~/.codex/agents/` |

Check which side wins when the same name exists in both, because tools
disagree. Claude Code takes the project definition over the user one; GitHub
Copilot CLI takes the user's home directory over the repository. Confirm the
order for whichever tool you use rather than assuming it.

Two further sources sit outside that pair. A plugin can ship agent definitions,
which become available wherever the plugin is enabled — distributing subagents
together with the skills and commands that call them is covered in
[Plugins](/ai/plugin). And in Claude Code an organization can apply definitions
through managed settings, which take precedence over every other location.

## Invoking a subagent

A subagent is reached in three ways, which differ in how reproducible the
delegation is.

* **Automatic delegation.** The main agent matches the request against each
  `description` and delegates when one fits. This is why the `description`
  states both what the subagent does and when to use it.
* **Explicit request.** Naming the subagent in the instruction steers the
  choice; a dedicated mention syntax, where the tool provides one, pins it
  outright and skips the matching.
* **From a skill or command.** A [skill](/ai/skill) body specifies which
  subagent runs at which step, with what prompt. This is the reproducible path:
  the delegation is written down rather than re-decided each time.

### Chaining subagents in sequence

Chaining passes one subagent's result to the next — find the problems, then fix
them. The handoff runs through the main agent, which receives the first result
and puts it into the second subagent's prompt.

```mermaid theme={null}
flowchart LR
  A[Subagent A<br/>find the problems] -->|result| MAIN[Main agent]
  MAIN -->|result as input| B[Subagent B<br/>fix them]
  B -->|result| MAIN
```

Each link receives only what the previous one concluded, not the material it
read to reach that conclusion. The main agent holds those summaries and nothing
else, so the chain can grow long without its context growing at each link.

The cost of that is real: a later link cannot go back to evidence an earlier one
saw and did not report. Where the second step needs the detail, either pass it
explicitly in the prompt or give the second subagent the means to read it again.

### Fanning out in parallel

Fanning out runs independent subtasks at the same time. There is one condition:
no subtask needs another's result.

```mermaid theme={null}
flowchart LR
  MAIN[Main agent] --> A[Subagent A]
  MAIN --> B[Subagent B]
  MAIN --> C[Subagent C]
  A -->|result only| BACK[Main agent]
  B -->|result only| BACK
  C -->|result only| BACK
```

Two shapes cover most fan-outs, and they differ in what is held fixed. Either
the target is fixed and the purpose varies, or the purpose is fixed and the
target varies.

|                         | Vary the purpose                 | Vary the target                       |
| ----------------------- | -------------------------------- | ------------------------------------- |
| What is held fixed      | The target every agent reads     | The purpose every agent applies       |
| What the prompt carries | The purpose this agent takes     | The target this agent works on        |
| Earns its place when    | One pass cannot cover the target | The targets are too many for one pass |

**Different purposes on the same target.** For one diff, run an agent looking
for security problems, another for gaps in test coverage, another for naming.
All three read the same diff; what differs is what each is looking for.

```text The target is fixed, the purpose moves theme={null}
Run 1 → Dimension: security.      Review the diff at main...HEAD.
Run 2 → Dimension: test coverage. Review the diff at main...HEAD.
Run 3 → Dimension: naming.        Review the diff at main...HEAD.
```

Give a single agent all three purposes and its context fills with concerns
unrelated to each other, and findings get missed. Split by purpose and each
agent attends to one.

**The same agent on different targets.** Enumerate the repositories in an
organization and run the same audit agent once per repository. Every run asks
the same question — do this repository's CI workflows follow the policy — and
what differs is which repository it reads.

```text The purpose is fixed, the target moves theme={null}
Run 1 → Repository: web-frontend. Audit its CI workflows against the policy.
Run 2 → Repository: billing-api.  Audit its CI workflows against the policy.
Run 3 → Repository: batch-jobs.   Audit its CI workflows against the policy.
```

Show one agent every repository in turn and its context fills as it goes, so
accuracy drops the further it gets. Split by target and each agent reads one.

Choose a unit the caller can enumerate before any run starts — repositories in
an organization, files in a diff, records in a batch. If the list can only be
built by doing the work, the fan-out cannot be planned and this shape does not
apply.

## Designing a subagent

Five decisions determine whether a subagent behaves the same way twice. Each is
made in the definition, not in the prompt that happens to invoke it.

| Decision        | What it fixes                                                          | What happens without it                                                 |
| --------------- | ---------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| Responsibility  | What the subagent is for, and the `description` that gets it delegated | The delegation decision blurs and the tool list widens                  |
| Capability      | Which tools it holds, and what an injected instruction can reach       | "Do not edit files" stays an instruction rather than a property         |
| Interface       | What arrives in the prompt, and what the final message returns         | Results vary per run, and the caller must re-read reports to merge them |
| Reproducibility | How it computes, and what it does with missing data                    | The same input yields different verdicts                                |
| Model           | Which grade of model runs the role                                     | A wide fan-out costs more than it returns                               |

### Give one subagent one responsibility

A definition covering several responsibilities has to describe all of them in
its `description`, which blurs the delegation decision, and needs the union of
their tools, which widens what it can do. Split by responsibility, and both the
description and the tool list stay sharp.

That responsibility reaches the caller through the `description`, which is not
a summary for humans but the text the main agent matches against. State what
the subagent does, when to use it, and what it returns — in the words a request
would actually use.

### Constrain capability, not just instructions

Diffs, pull request bodies, dependency changelogs, and third-party
documentation are data, not instructions. State in the definition that text
embedded in the material is never followed — then make that hold even when it
does not, by granting only the tools the workflow uses. Why that instruction
alone is not enough is covered in [Security](/ai/security).

* A judgment or review role needs no write tools. Withholding them turns "do
  not edit files" from an instruction into a property of the environment, and
  an agent holding no write tools cannot act on an injected instruction even if
  it accepts one.
* Granting `Bash` grants the whole shell. Which commands may actually run is
  narrowed outside the definition — by the session's permission rules, which
  apply inside subagents too, or by a pre-tool hook that validates each
  command — not by the tool list.
* Keep intermediate files out of the user's working tree. Writing scratch data
  under a temporary directory keeps a read-only role read-only in practice.

Write those command patterns so the prefix cannot match a broader command. A
trailing `*` behaves differently depending on the space before it:

| Pattern                         | Also matches                         | Result                                                            |
| ------------------------------- | ------------------------------------ | ----------------------------------------------------------------- |
| `Bash(git diff*)`               | `git difftool --extcmd=<command>`    | ❌ Arbitrary command execution through a rule meant to allow reads |
| `Bash(git diff --no-renames *)` | Nothing — the word boundary stops it | ✅ Stays the read-only allowance it looks like                     |

<Warning>
  The space before `*` is what enforces the word boundary. Without it the
  pattern matches any continuation of the prefix, so a rule that reads as
  "allow diffs" can allow considerably more.
</Warning>

### Define both ends of the interface

A subagent sees its prompt and returns its final message. Nothing else crosses
the boundary in either direction.

```mermaid theme={null}
flowchart LR
  CTX["Caller's context<br/>conversation, decisions, files read"] -.->|does not cross| SUB
  IN["Prompt<br/>range, paths, rules, mode"] --> SUB["Subagent<br/>own context window"]
  SUB --> OUT["Final message<br/>the agreed format"]
  SUB -.->|discarded on return| WORK["Working state<br/>everything it read"]
```

Both ends have to be specified, and for the same reason: what is not stated
does not arrive.

| End                     | What to specify                                                                      | Why it matters                                                                                                  |
| ----------------------- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- |
| In — the prompt         | The target range, the paths, the rules to apply, the mode it runs in                 | A subagent cannot see the calling conversation, so instructions that assume shared context vary from run to run |
| Out — the final message | The exact format, keyed on something stable, with no greeting or trailing commentary | When a skill parses the message to build a table or join results, the format is a contract                      |

### Make the judgment reproducible

| Situation                                  | Avoid                                               | Do instead                                                      |
| ------------------------------------------ | --------------------------------------------------- | --------------------------------------------------------------- |
| The decision rests on counts or thresholds | Estimating them from the text the subagent read     | Calculating them with a tool and using the printed values       |
| The data the decision needs is missing     | Leaving the fallback unstated, so it varies per run | Stating the behavior explicitly and choosing the safe direction |

<Tip>
  The safe direction is the one that surfaces the problem: report a requirement
  as undetermined rather than satisfied, raise a risk level rather than lower
  it. Reserve the model's work for the part that genuinely needs judgment.
</Tip>

### Choose the model per role

A subagent that omits `model` inherits the caller's model. Pin it where the
role justifies doing otherwise.

| Role                                             | Model grade                                                    |
| ------------------------------------------------ | -------------------------------------------------------------- |
| Mechanical classification, structured extraction | A cheaper model — this is what keeps a wide fan-out affordable |
| Analysis that carries real judgment              | A more capable model                                           |

## Operational limits

Subagents have ceilings and costs that decide how far the pattern scales. Two
are limits the implementation sets. Three are properties of delegation itself,
which no configuration removes.

| Limit                                    | What it means                                                             | What it forces                                                                                    |
| ---------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| Concurrency cap                          | Only so many subagents run at once                                        | A wider fan-out still completes, but stops buying wall-clock time                                 |
| Nesting depth cap                        | The chain downward from the main conversation is a few levels deep        | Composition belongs at the caller, not inside a subagent that spawns its own                      |
| No shared context                        | A subagent sees its prompt, not the conversation                          | Restate what the caller holds, and expect the subagent's working state to be lost when it returns |
| Context degrades inside the subagent too | A subagent given too broad a task fills its own window and loses accuracy | Scope each task — the isolation protects the caller, not the subagent                             |
| Delegation has a floor cost              | Every run re-reads its own instructions and its own share of the codebase | Do not delegate what the caller could finish in a couple of tool calls                            |

<Info>
  The concurrency cap is rarely what binds first. Consolidation cost grows with
  every result the caller has to merge, so a fan-out usually stops being worth
  widening well before it stops running in parallel.
</Info>

<Note>
  Subagents are the delegation primitive; the model that decides what to
  delegate is covered in [Agentic Workflow](/ai/agentic-workflow), and the unit
  that writes the delegation down as a reproducible procedure is covered in
  [Skills](/ai/skill).
</Note>

## Related pages

<CardGroup cols={3}>
  <Card title="Agentic Workflow" icon="diagram-project" href="/ai/agentic-workflow">
    The delegation model subagents implement — managing context, dividing roles
    along context boundaries, and running work in parallel.
  </Card>

  <Card title="Skills" icon="puzzle-piece" href="/ai/skill">
    Package a workflow as a reusable unit that orchestrates subagents at
    specified steps.
  </Card>

  <Card title="Context Engineering" icon="layer-group" href="/ai/context-engineering">
    Why a task is worth moving into its own window, and how the context that
    stays behind is designed.
  </Card>

  <Card title="Security" icon="shield-halved" href="/ai/security">
    Why constraining capability — rather than instructing behavior — is the
    load-bearing control, starting from where the risk arises.
  </Card>
</CardGroup>
