Claude Code Sub-Agents: Delegate, Specialize, and Scale Your Coding Workflows
Learn Claude Code's sub-agent system: built-in agents like Explore and Plan, custom specialists, routing tasks to cheaper models, and scaling complex projects.
#Why Sub-Agents Matter
When you ask Claude Code to build a feature, it often needs to do several things: explore the codebase, understand patterns, write code, and verify it works. All of that happens in one context window, which means exploration noise mixes with implementation work. As your conversation grows, context fills up and quality drops.
Sub-agents solve this by splitting work into separate context windows. Each sub-agent gets its own conversation, its own system prompt, and its own tool access. When it finishes, it returns results to the main session — keeping your primary context clean.
Think of it like delegation in a real team. You don't want your lead engineer also doing every grep search and log scan. You hand those tasks to specialists.
#Built-In Sub-Agents
Claude Code ships with several built-in sub-agents that fire automatically when appropriate. You don't need to configure anything — Claude decides when to delegate.
#Explore
Model: Haiku (fast, cheap) Tools: Read-only Purpose: Searching and analyzing codebases
When Claude needs to find a file, understand a pattern, or scan a directory structure, it delegates to Explore. This keeps search noise out of your main conversation.
Explore has three thoroughness levels:
- Quick — targeted lookups ("find the auth middleware file")
- Medium — balanced exploration ("how is error handling done across the API layer")
- Very thorough — comprehensive analysis ("map all the data flow from input to database")
#Plan
Model: Inherits from main session Tools: Read-only Purpose: Research before presenting a plan
When you're in plan mode and ask Claude to make changes, it sends Plan out to gather context before presenting its approach. This prevents the main session from filling up with research artifacts.
#General-Purpose
Model: Inherits from main session Tools: All tools Purpose: Complex multi-step tasks
For work that needs both exploration and action — research a problem, then implement a fix — Claude delegates to General-Purpose. It has full tool access and can make changes.
#Other Built-Ins
| Agent | Model | Purpose |
|---|---|---|
| Bash | Inherits | Terminal commands in separate context |
| Claude Code Guide | Haiku | Answering questions about Claude Code itself |
| statusline-setup | Sonnet | Configuring your terminal status line |
Want step-by-step guides for this and more?
ClawDocx Pro includes 500+ curated prompts, setup guides, SKILL.md files, and templates — everything to make your AI agent unstoppable.
See plans & pricing#Creating Custom Sub-Agents
The real power is building your own. Custom sub-agents let you:
- Lock down tools — a reviewer that can only read, never write
- Route to cheaper models — send simple tasks to Haiku instead of Opus
- Enforce patterns — a sub-agent that always follows your team's code style
- Specialize prompts — domain-specific instructions for testing, security, docs
#Quickstart: The /agents Command
The fastest way to create a sub-agent:
# In a Claude Code session/agentsSelect "Create new agent" and follow the prompts. Claude Code generates the Markdown definition file for you.
#Manual Creation
Sub-agents are Markdown files with YAML frontmatter. Place them in:
- User-level:
~/.claude/agents/my-agent.md(available in all projects) - Project-level:
.claude/agents/my-agent.md(available in this repo only)
Here's a complete example — a security reviewer:
---name: security-reviewerdescription: Reviews code changes for security vulnerabilities, auth issues, and data exposure risksmodel: sonnettools: - Read - Bashdeny_tools: - Write - Edit---You are a security-focused code reviewer. When given code to review, check for:1. **Injection vulnerabilities** — SQL injection, XSS, command injection2. **Authentication/authorization gaps** — missing auth checks, privilege escalation3. **Data exposure** — secrets in code, PII logging, missing encryption4. **Input validation** — unsanitized user input, missing bounds checks5. **Dependency risks** — known CVEs in importsFormat your review as:- 🔴 **Critical** — must fix before merge- 🟡 **Warning** — should fix, potential risk- 🟢 **Note** — suggestion for improvementBe specific. Reference file paths and line numbers.#Key Frontmatter Fields
| Field | What It Does | Example |
|---|---|---|
name | Identifier Claude uses to delegate | security-reviewer |
description | How Claude decides when to use this agent | Reviews code for security issues |
model | Which model to use (opus, sonnet, haiku) | haiku |
tools | Allowlist of tools (empty = all tools) | [Read, Bash] |
deny_tools | Blocklist of tools | [Write, Edit] |
permissions | Permission mode (default, auto-accept) | auto-accept |
background | Run in background (don't block main session) | true |
isolation | Git isolation mode | worktree |
#Practical Sub-Agent Recipes
#Test Runner (Cheap & Fast)
---name: test-runnerdescription: Runs tests and reports results. Use for checking test suites after changes.model: haikutools: - Read - Bashdeny_tools: - Write - Edit---Run the test suite and report results concisely:- Total tests, passed, failed, skipped- For failures: file path, test name, error message, and likely cause- Suggest fixes if the cause is obviousDo not modify any files. Report only.#Documentation Writer
---name: doc-writerdescription: Writes and updates documentation for code changesmodel: sonnettools: - Read - Write - Editdeny_tools: - Bash---You write clear, accurate documentation. When asked to document code:1. Read the code thoroughly before writing2. Write for developers who are new to the codebase3. Include usage examples with realistic inputs4. Document edge cases and error conditions5. Follow JSDoc/TSDoc format for inline docs6. Keep README updates concise and scannable#Commit Message Generator
---name: commit-gendescription: Generates conventional commit messages from staged changesmodel: haikutools: - Bash - Readdeny_tools: - Write - Edit---Generate a commit message following Conventional Commits format:1. Run `git diff --staged` to see changes2. Categorize: feat, fix, docs, style, refactor, test, chore3. Write a concise subject line (< 72 chars)4. Add body with bullet points for significant changes5. Reference issue numbers if mentioned in the codeOutput ONLY the commit message, nothing else.#Sub-Agent Patterns
#Cost Optimization: Route by Complexity
Use model in your agent definitions to send simple tasks to cheaper models:
- Haiku ($) → file search, test running, log scanning, simple formatting
- Sonnet ($$) → code review, documentation, refactoring
- Opus ($$$) → architecture decisions, complex debugging, security audits
Claude decides which agent to delegate to based on the description field. Write descriptions that clearly match the task complexity.
#Background Agents
Add background: true to run agents without blocking your main session:
---name: background-linterdescription: Runs comprehensive lint checks in the backgroundbackground: truemodel: haiku---Background agents run independently. Use Ctrl+F to list and kill them.
#Worktree Isolation
For agents that make changes, isolation: worktree creates a temporary git worktree so changes don't affect your working branch:
---name: experimental-refactordescription: Tries experimental refactoring approaches in an isolated branchisolation: worktree---The worktree is cleaned up when the sub-agent finishes. If you like the changes, they're on a branch you can merge.
#Persistent Memory
Sub-agents can maintain their own auto-memory across sessions:
---name: project-expertdescription: Deep knowledge of this project's architecture and conventionsauto_memory: true---Over time, this agent builds up project-specific knowledge that persists between sessions.
#Sub-Agents vs Agent Teams
This is a common point of confusion. Here's the distinction:
| Sub-Agents | Agent Teams | |
|---|---|---|
| Communication | Report back to main session only | Talk to each other directly |
| Coordination | Main session manages everything | Shared task list, self-organizing |
| Scope | Single session | Multiple parallel sessions |
| Best for | Delegating specific tasks | Parallel work on large features |
| Overhead | Low | High (more tokens, coordination cost) |
Rule of thumb: If the tasks are independent (review this, run those tests, write that doc), use sub-agents. If the tasks need coordination (frontend + backend + tests for one feature), consider agent teams.
#Tips for OpenClaw Users
When running Claude Code through OpenClaw's ACP integration:
- Sub-agents run inside the Claude Code session — they're invisible to OpenClaw's session management
- If you need OpenClaw-visible delegation, use OpenClaw's own sub-agent system (
sessions_spawn) instead - For complex workflows: use OpenClaw for orchestration (which repo, which branch, what to build) and Claude Code sub-agents for internal task splitting (explore, implement, test)
The two delegation systems are complementary, not competing.
#Getting Started
- Start with the built-in agents — they work out of the box
- Create one custom agent for your most repetitive task (testing, linting, docs)
- Route cheap tasks to Haiku to save costs
- Add
background: truefor non-blocking agents - Use
isolation: worktreefor risky experiments
Sub-agents are how Claude Code scales from "helpful assistant" to "autonomous development team." Start small, see what sticks, and build up.
For advanced sub-agent configurations, multi-project setups, and team-wide agent libraries, check out the premium guides on ClawDocx.