Skip to main content
reopt Handbook
reopt Handbook
Claude Code Complete Guide

Setup

Plan and Environment SetupMastering CLAUDE.md

Multi-session & Agents

Multi-session WorkflowSubagents

Automation & Extension

HooksMCP IntegrationSkills and Slash Commands

Workflow

Plan ModeContext ManagementIDE IntegrationHeadless and CI/CD

Practice

Vibe Coding PatternsPrompting Best Practices

Verification

Verification ReportUpdate Log
Handbook›Claude Code Complete Guide›Subagents
한국어English

Subagents

Delegate bounded work while keeping the main Claude Code session accountable.

Key takeaways

  • Subagents run inside one session, each in its own context window with custom prompt, tools, and permissions, returning only a summary — ideal when a side task would flood the main context.
  • Subagents differ from background sessions: subagents run inside one conversation and nested agent delegation is capped at three levels, while background sessions are full independent conversations managed from Agent View.
  • Built-in subagents include Explore (fast read-only Haiku search), Plan (read-only research), and general-purpose; Explore and Plan skip CLAUDE.md and parent git status to stay cheap.
  • Define custom subagents as Markdown with YAML frontmatter (/agents recommended); only name and description are required, and model resolves via env var, invocation param, frontmatter, then main conversation.
  • Give every delegated task a bounded scope and review its returned patch like another engineer's — subagents increase throughput, not a replacement for judgment.

Subagents are useful for parallel discovery, focused implementation, and independent verification. They are not a substitute for ownership in the main session.

Subagents vs. Background Sessions

Claude Code separates two related but distinct mechanisms, and it helps to keep them straight:

  • Subagents run inside a single session. Each spawns in its own context window with a custom system prompt, specific tool access, and independent permissions, then returns only a summary to the main conversation. They are the right tool when a side task would flood your main context with search results, logs, or file contents you will not reference again. On v2.1.261, nested delegation defaults to three levels and the concurrent limit is 20 (CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS). v2.1.224 removed the old 200-per-session total and CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION policy. If a subagent reaches maxTurns, it now returns a partial result plus a hint to continue with SendMessage. Resume that same agent by its existing agent ID or name; the release note does not define a separate continuation-ID contract. Built-in Explore and Plan agents do not expose IDs and cannot be resumed this way. Orchestration patterns need explicit allowlists and deny rules rather than assuming no nesting can happen.
  • Background sessions are full, independent Claude Code conversations that keep running without a terminal attached. You dispatch and monitor them from Agent View (claude agents). For sessions that message each other, see agent teams.

Built-in subagents that Claude delegates to automatically include Explore (a fast, read-only search agent on Haiku), Plan (read-only research used during plan mode), and general-purpose (all tools, inherits the main model). Explore and Plan skip your CLAUDE.md files and the parent session's git status to stay fast and cheap; every other built-in and custom subagent loads both.

Current Agent Surface

In current Claude Code, agent work spans custom subagents, Agent View, background sessions, and dynamic workflows.

claude agents
/bg run tests and fix failures
claude --agent code-reviewer --bg "review PR 1234"
claude --bg --exec 'pnpm test -- --runInBand'
/workflows

Since v2.1.212, /fork [prompt] copies the current conversation into a separate background session while the original continues. Use /subtask <prompt> for the former inherited-context behavior: it delegates a bounded task inside the current conversation and returns the result here. /branch instead creates and switches to a new conversation branch.

Since v2.1.232, inherited-context fork mode is on by default in interactive sessions and spawned subagents normally run in the background. It remains off by default for -p and SDK use. Set CLAUDE_CODE_FORK_SUBAGENT=1 to enable it there or 0 to disable it everywhere. A fork subagent cannot create another fork.

Agent View (claude agents, research preview, requires Claude Code v2.1.139 or later) shows running, blocked, and completed sessions. From its dispatch input you can start a session with a plain prompt, run a custom subagent as the session's main agent with <agent-name> <prompt> (first word match) or @<agent-name>, target a sibling repository under the directory you opened Agent View from with @<repo>, dispatch a skill or command with /<command>, or run a shell-only background job with ! <command>. When the same @name matches both a subagent and a sibling repository, the subagent wins.

Bring an existing session in

Inside any session, run /background (alias /bg) to move the current conversation into a background session, or press the left arrow on an empty prompt to background it and open Agent View in one step. From the shell, claude --bg "<prompt>" starts a session that goes straight to the background; add --agent <name> to run a specific subagent as its main agent, or --name to set the display name.

Background sessions isolate file edits in a git worktree under .claude/worktrees/ before writing, so parallel sessions can read the same checkout but each writes to its own. Claude skips the worktree when the session is already inside a linked worktree, when the working directory is not a git repo (and no WorktreeCreate hook is configured), or when the write is outside the working directory. Only turn isolation off with worktree.bgIsolation: "none" in the project's .claude/settings.json for repositories where worktrees are impractical (requires Claude Code v2.1.143 or later). To make a custom subagent always run in its own worktree regardless of how it was started, set isolation: worktree in its frontmatter.

Good Subagent Tasks

Good tasks are bounded and self-contained:

  • Inspect one subsystem and answer a specific question.
  • Implement one slice with a disjoint write scope.
  • Run a verification command while the main session continues other work.
  • Compare two options and return a recommendation with file references.

Poor tasks are open-ended:

  • "Fix the app."
  • "Review everything."
  • "Make the architecture better."

The main session should decide the shape of the work before delegating.

Defining a Custom Subagent

Custom subagents are Markdown files with YAML frontmatter. The body becomes the system prompt; the subagent receives only that prompt plus basic environment details, not the full Claude Code system prompt. Create and manage them with the /agents command (recommended), or write the files directly.

Store the file by scope. When two subagents share a name, the higher-priority location wins:

LocationScopePriority
Managed settingsOrganization-wide1 (highest)
--agents CLI flag (JSON)Current session2
.claude/agents/Current project3
~/.claude/agents/All your projects4
Plugin's agents/ directoryWhere enabled5 (lowest)
---
name: code-reviewer
description: Reviews code for quality and best practices. Use proactively after code changes.
tools: Read, Glob, Grep
model: sonnet
---

You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.

Only name and description are required. name must use lowercase letters and hyphens; it is the identifier Claude uses to delegate, and the filename does not have to match. Other supported frontmatter fields include tools (allowlist), disallowedTools (denylist, applied before tools), model, permissionMode, mcpServers, hooks, maxTurns, skills (preloads full skill content), memory (user, project, or local persistent memory), effort, background, isolation, and color.

Files load at session start

A subagent file added or edited directly on disk loads only when you restart the session. Subagents created through /agents take effect immediately.

Prompt Template

When delegating an ad hoc task, give scope, ownership, collaboration rules, and output format:

You are not alone in this repository.
Own only apps/handbook/e2e/home.spec.ts.
Update tests for English locale availability.
Do not revert changes outside this file.
Return changed files, commands run, and any failures.

Integration Discipline

When a subagent returns, review its patch as if it came from another engineer:

  • Does it satisfy the exact task?
  • Did it edit only its assigned files?
  • Did it preserve existing user changes?
  • Did its verification actually exercise the changed behavior?

If the answer is unclear, inspect the diff before stacking more changes on top.

Failure Modes

  • Duplicate exploration wastes time and produces conflicting advice.
  • Broad write scopes create merge conflicts.
  • Delegating the critical path leaves the main session idle.
  • Treating a subagent report as proof without checking risky code hides regressions.
  • Running many subagents that each return detailed results consumes significant context, because every result comes back into the main conversation.

Use subagents to increase throughput, not to avoid judgment.

Model and Effort

Each background session can use a different model. Set the dispatch default with Agent View --model (the model shown in the Agent View header), pass --model to claude --bg, switch inside an attached session with /model and s (persists for that session), or set model in a custom subagent's frontmatter.

The model field accepts a model alias (fable, sonnet, opus, haiku), a full model ID (for example claude-fable-5-1, claude-opus-5, or claude-sonnet-5), or inherit, and defaults to inherit (the main conversation's model) when omitted. Use full model IDs for reproducible subagents; use an alias such as fable or opus only when you accept provider-specific alias movement (fable resolves to Fable 5.1 from v2.1.255). Reserve Fable 5.1 for long-running investigation subagents, and configure a fallback model chain for availability failures. From v2.1.257, CLAUDE_CODE_SUBAGENT_MODEL_FORCE applies CLAUDE_CODE_SUBAGENT_MODEL (or the main model) to every subagent and ignores per-spawn and frontmatter overrides; v2.1.260 fixed model: fable agents ignoring the [1m] tag on an ANTHROPIC_DEFAULT_FABLE_MODEL pin. When Claude invokes a subagent, the model resolves in this order:

  1. The CLAUDE_CODE_SUBAGENT_MODEL environment variable, if set.
  2. The per-invocation model parameter Claude passes.
  3. The subagent definition's model frontmatter.
  4. The main conversation's model.

The optional effort frontmatter field overrides the session effort level while the subagent is active (low, medium, high, xhigh, max; available levels depend on the model).

Recent model validation changes restrict Haiku as a main conversation model, but Haiku remains useful for Explore and custom low-cost subagents. When you rely on Haiku for subagents, pin that behavior in the agent frontmatter and verify it after each stable-channel update.

Related docs

Multi-session Workflow

Run parallel Claude Code sessions with git worktrees and agent view without losing branch, context, or verification control.

Cmd. /fork

Claude Code Command Master · Copy the conversation into a new background session.

Ch10. Subagents, Workflows, Remote Agents

Enterprise Eve Agent Development · Use Eve built-in agent tool, declared subagents, remote agents, and experimental Workflow for multi-agent design.

Automation and Web Commands

Claude Code Command Master · Commands for Claude Code on the web, PR automation, routines, Agent View background sessions, Desktop, and remote control.

Cmd. /tasks

Claude Code Command Master · Manage current-session background work (/bashes).

Multi-session Workflow

Run parallel Claude Code sessions with git worktrees and agent view without losing branch, context, or verification control.

Hooks

Use Claude Code hooks for predictable automation and repository guardrails.

On this page

Subagents vs. Background SessionsCurrent Agent SurfaceGood Subagent TasksDefining a Custom SubagentPrompt TemplateIntegration DisciplineFailure ModesModel and Effort