The Infinite Context Problem

Imagine you ask Claude to investigate how authentication works in your project. It starts reading files. Lots of files. Suddenly you have 50,000 tokens of context filled with code you only needed to consult, not remember.

Now every response is slower. And more expensive. And when you want to do something else, all that context is still there, taking up mental space.

The solution: subagents. You launch a specialized agent that does the dirty work in its own isolated context, returns a summary, and disappears. Your main conversation stays clean.

What is a Subagent

A subagent is a separate Claude instance that:

  • Has its own context (doesn’t contaminate your conversation)
  • Can have restricted tools (read-only, bash-only, etc.)
  • Can use a different model (haiku for simple tasks, opus for complex ones)
  • Can run in foreground (blocking) or background (parallel)

Think of them as specialized interns. You assign them a task, they work independently, and report back when they’re done.

The Subagents You Already Have

Claude Code comes with several built-in subagents:

AgentModelWhat it’s forTools
ExploreHaikuSearch and analyze codeRead-only
PlanInheritsResearch during planningRead-only
general-purposeInheritsComplex multi-step tasksAll
BashInheritsCommands in separate contextBash only
Claude Code GuideHaikuQuestions about Claude CodeDocumentation

The most useful is Explore. When Claude needs to search for something in your codebase, it launches an Explore that reads files like crazy, processes everything, and returns only what’s relevant.

How to Launch Subagents

From the REPL (normal conversation)

Simply ask in natural language:

Use a subagent to investigate how the cache system works
Launch the Explore agent to find all API endpoints
Investigate authentication in parallel while I keep working

Claude understands these requests and uses the Task tool internally to launch the appropriate subagent.

From a Skill

In a skill, you can force execution in an isolated subagent with context: fork:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
---
name: deep-analysis
description: Deep architecture analysis
context: fork
agent: Explore
---

Analyze the complete project architecture.
Generate a report with:
- Directory structure
- Main dependencies
- Detected design patterns

With context: fork, the skill runs in a subagent. With agent: Explore, you specify which type of agent to use.

Explicit launch by type

If you want to be specific:

Use the Explore agent to map the project structure
Use a general-purpose agent to refactor the payments module
Use the Bash agent to run the complete test suite

Foreground vs Background

Foreground (blocking)

By default, subagents run in foreground. Your session waits for them to finish.

Investigate how rate limiting works
[Claude launches subagent, you wait, receive result]

Useful when you need the result immediately.

Background (parallel)

You can send a subagent to background in two ways:

1. Explicitly asking:

Investigate the cache system in the background while I review something else

2. With Ctrl+B while it’s running:

If a subagent is already running and you want to keep working, press Ctrl+B. The agent goes to background and you can continue.

> Analyze all project tests
[Starts executing...]
[You press Ctrl+B]
> Okay, meanwhile, explain what this file does
[You keep working, analysis continues in parallel]

View background tasks

Use the /tasks command to see what’s running:

/tasks

This shows all background tasks with their IDs, status, and progress.

Communication with Subagents

Knowing what it’s doing

While a subagent is in foreground, you see its progress in real-time (what files it reads, what commands it executes).

If it’s in background, use /tasks to see status. When it finishes, Claude automatically notifies you with the result.

Giving additional instructions

If a subagent is running and you want to add context:

By the way, ignore test files, I'm only interested in production code

Claude tries to pass this information to the subagent if possible.

Stopping a subagent

To stop a background task:

Stop the analysis task
Cancel the running subagent

Or from /tasks, you can cancel specific tasks by ID.

Resuming a subagent

Subagents maintain their history within the session. You can resume where they left off:

Continue the authentication analysis you did before
and now also review authorization

Claude resumes the subagent with all its previous context.

Creating Your Own Subagents

/agents

Select Create new agent, choose the scope (user or project), describe what you want, and Claude generates the file for you.

Manually

Create a Markdown file in .claude/agents/ (project) or ~/.claude/agents/ (global):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
---
name: security-scanner
description: Scans code for vulnerabilities. Use proactively after changes to authentication or data handling.
tools: Read, Grep, Glob
model: opus
---

You're a security expert. Analyze the code looking for:

- SQL injection
- XSS
- Hardcoded secrets
- Insufficient input validation
- Vulnerable dependencies

Report by severity: Critical > High > Medium > Low.
DO NOT modify code, only report.

Frontmatter configuration

FieldRequiredDescription
nameYesUnique identifier (lowercase and hyphens)
descriptionYesWhen to use the agent (Claude reads this)
toolsNoAllowed tools (default: all)
disallowedToolsNoForbidden tools
modelNohaiku, sonnet, opus, or inherit
permissionModeNoHow to handle permissions
skillsNoSkills to inject into context
hooksNoLifecycle hooks

Permission modes

ModeBehavior
defaultAsk for permission as usual
acceptEditsAuto-accept file edits
dontAskAuto-deny unsolicited operations
bypassPermissionsSkip all permissions (dangerous)
planRead-only mode

Example: Read-only agent

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
---
name: code-reader
description: Reads and analyzes code without modifying anything
tools: Read, Grep, Glob
disallowedTools: Write, Edit, Bash
permissionMode: plan
---

Analyze the requested code.
NEVER suggest modifications, only describe what you find.

Example: Test agent

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
---
name: test-runner
description: Runs tests and reports failures. Use after code changes.
tools: Bash, Read
model: haiku
---

1. Execute: `uv run pytest -x --tb=short`
2. If there are failures, read relevant files
3. Report:
   - Tests passed: X
   - Tests failed: Y
   - Summary of each failure (file, line, error)

DO NOT try to fix tests, only report.

Common Use Cases

1. Codebase investigation

Use Explore to understand how the notification system works

The Explore reads everything necessary, you get a summary without contaminating your context.

2. Parallel analysis

Investigate in parallel:
- How authentication works
- How the payment system works
- How email sending works

Claude launches three simultaneous subagents. Each one investigates its area.

3. Background tests

Run tests in the background while I implement this feature

You don’t have to wait. When they fail (or pass), it notifies you.

4. Isolated code review

Use a subagent to review the security of the changes I just made

The review happens in separate context. You get feedback without noise.

5. Safe refactoring

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
---
name: safe-refactor
description: Refactors code with verifications
tools: Read, Edit, Bash
hooks:
  PostToolUse:
    - matcher: "Edit"
      hooks:
        - type: command
          command: "uv run pytest -x"
---

Each edit automatically triggers tests.

Subagents vs Skills: When to Use Each

NeedUse
Reusable instructions in main contextSkill
Task that generates lots of outputSubagent
Restrict tools for an operationSubagent
Independent parallel workSubagent
Process with defined steps I want to seeSkill
Research I don’t need to rememberSubagent

You can also combine them: a skill with context: fork launches a subagent.

Limitations

  • Can’t nest: A subagent can’t launch another subagent
  • Background permissions: Background subagents auto-deny non-pre-approved permissions
  • Session only: Subagent context only lives during the session

Advanced Tips

Disable specific subagents

In settings.json:

1
2
3
4
5
{
  "permissions": {
    "deny": ["Task(Explore)", "Task(my-custom-agent)"]
  }
}

Auto-compaction

Subagents have auto-compaction at 95% context. To trigger it earlier:

1
export CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=50

View transcripts

Subagent logs are saved in:

~/.claude/projects/{project}/{session}/subagents/agent-{id}.jsonl

Useful for debugging or auditing.

Disable background tasks

If you prefer everything to be blocking:

1
export CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1

Conclusion

Subagents are the way to scale your Claude Code usage without exploding context. They delegate dirty work, keep your conversation clean, and can work in parallel.

Use them for research, analysis, tests, and any task that generates lots of output you don’t need to remember. Create your own for repetitive tasks with specific restrictions.

The combination of skills (what to do) + subagents (where to do it) + hooks (when to validate) gives you pretty fine control over how Claude works.


TL;DR: Subagents are isolated Claude instances for specific tasks. They keep your context clean, can run in parallel (Ctrl+B), and you can create your own in .claude/agents/. Use /tasks to monitor them and /agents to manage them.

Official documentation: Subagents - Claude Code Docs