claude-almanac
Agents

Agents and Subagents

Specialized AI assistants that handle tasks independently with isolated context and custom tool access.

Claude Code Agents and Subagents

Agents are specialized AI assistants that handle specific types of tasks independently. Each agent runs in its own isolated context window with a custom system prompt, specific tool access controls, independent permissions, and full conversation history isolation.

Overview

Agent feedback loop: gather context, take action, verify work, repeat Source: Building agents with the Claude Agent SDK — the core loop that every Claude Code agent (main session, subagent, or teammate) runs.

When Claude encounters a task that matches an agent's description, it automatically delegates to that agent. The agent works independently and returns results to the main conversation.

Key Benefits:

  • Preserve context by keeping exploration and implementation separate
  • Enforce tool restrictions for security and focus
  • Reuse configurations across projects
  • Specialize behavior for specific domains
  • Control costs by routing tasks to faster, cheaper models

Built-in Agent Types

Explore Agent

  • Model: Haiku (fast, low-latency)
  • Tools: Read-only tools only (no Write or Edit)
  • Purpose: File discovery, code search, codebase exploration
  • Thoroughness levels: Quick, Medium, Very Thorough

Plan Agent

  • Model: Inherits from main conversation
  • Tools: Read-only tools only
  • Purpose: Codebase research during plan mode
  • Restriction: Cannot spawn other subagents

General-Purpose Agent

  • Model: Inherits from main conversation
  • Tools: All tools available
  • Purpose: Complex, multi-step tasks requiring exploration and action

Other Built-in Agents

AgentModelPurpose
BashInheritsRunning terminal commands in separate context
statusline-setupSonnetWhen running /statusline command
Claude Code GuideHaikuWhen asking about Claude Code features

Using the Task Tool

Automatic Delegation

Claude automatically delegates based on:

  • Agent's description field
  • Task requirements
  • Current context

Explicit Requests

Use the code-reviewer agent to suggest improvements
Have the debugger subagent investigate the login issue
Use a subagent to run tests and report failures only

Background vs. Foreground Execution

Foreground (blocking):

  • Blocks main conversation until complete
  • Allows permission prompts and clarifying questions
  • Best for interactive workflows

Background (concurrent):

  • Runs while you continue working
  • Auto-denies unpre-approved permissions
  • MCP tools not available
  • Can be resumed later

How to background:

  • Ask: "Run this task in the background"
  • Press Ctrl+B during execution (Tmux users: press twice)

Disable background tasks:

export CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1

Creating Custom Agents

Using /agents Command

  1. Run /agents
  2. Select "Create new agent"
  3. Choose scope (User-level or Project-level)
  4. Select "Generate with Claude" and describe your agent
  5. Select tools, model, and color
  6. Save and use immediately

Agent File Structure

Agents are Markdown files with YAML frontmatter:

---
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability.
tools: Read, Grep, Glob, Bash
model: sonnet
permissionMode: default
---

You are a senior code reviewer ensuring high standards.

When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately

Frontmatter Fields

FieldRequiredDescription
nameYesUnique identifier (lowercase, hyphens)
descriptionYesWhen Claude should delegate to this agent
toolsNoWhich tools agent can use (comma-separated). Inherits all if omitted
disallowedToolsNoTools to deny/block (applied before tools)
modelNosonnet, opus, haiku, full model ID, or inherit (default)
permissionModeNoPermission handling mode
mcpServersNoMCP servers: name references or inline definitions
maxTurnsNoMaximum agentic turns before stopping
skillsNoSkills to preload into agent context (full content injected)
hooksNoLifecycle hooks scoped to this agent
memoryNoPersistent memory scope: user, project, or local
effortNoEffort level override: low, medium, high, max (Opus 4.6 only)
backgroundNoSet to true to always run as background task
isolationNoSet to worktree for isolated git worktree copy
colorNoDisplay color: red, blue, green, yellow, purple, orange, etc
initialPromptNoAuto-submitted first user turn with --agent or agent setting

Permission Modes

ModeBehavior
defaultStandard permission checking
acceptEditsAuto-accept file edits
autoAI-powered safety classifier (inherited from parent, cannot override)
dontAskAuto-deny prompts (allowed tools still work)
bypassPermissionsSkip all permission checks (parent takes precedence if set)
planPlan mode (read-only exploration)

Model Configuration

model: sonnet        # High capability
model: opus          # Maximum capability
model: haiku         # Fast and cheap
model: inherit       # Same as parent

Using Hooks with Agents

---
name: db-reader
description: Execute read-only database queries
tools: Bash
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/validate-readonly-query.sh"
---

Agent Scopes

LocationScopePriority
--agents CLI flagCurrent session only1 (highest)
.claude/agents/Current project2
~/.claude/agents/All your projects3
Plugin's agents/Where plugin installed4 (lowest)

CLI-Defined Agents

claude --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer",
    "prompt": "You are a senior code reviewer...",
    "tools": ["Read", "Grep", "Glob"],
    "model": "sonnet"
  }
}'

Running a Session as an Agent

Use --agent to start a session where the main thread uses a subagent's system prompt, tools, and model:

claude --agent code-reviewer

Works with built-in and custom agents. The choice persists when you resume the session.

Agent Tool Restrictions

Use Agent(agent_type) syntax in the tools field to control which subagents can be spawned:

# Only allow spawning specific agents
tools: Agent(worker, researcher), Read, Bash

# Allow spawning any agent
tools: Agent, Read, Bash

If Agent is omitted from tools entirely, the agent cannot spawn subagents.

Persistent Memory

The memory field gives subagents a persistent directory that survives across conversations:

---
name: code-reviewer
description: Expert code reviewer
memory: user
---
ScopeStorage Location
user~/.claude/agent-memory/<name>/
projectPer working tree, like auto memory
localPer working tree, private to this machine

The subagent accumulates insights over time (codebase patterns, debugging tips, architecture decisions).

MCP Servers in Subagents

Give a subagent access to MCP servers by name reference or inline definition:

---
name: data-analyst
description: Analyze data using database tools
mcpServers:
  db: {}
  custom-api:
    command: npx
    args: ["-y", "custom-api-server"]
---

String references share the parent session's connection. Inline servers are connected when the subagent starts and disconnected when it finishes.

Background Agents

How They Work

  • Run asynchronously while main conversation continues
  • Have unique task IDs for tracking
  • Buffered output retrievable via TaskOutput tool
  • Auto-deny unpre-approved permissions
  • Automatically cleaned up on exit

Managing Background Agents

# List background agents
/tasks

# Or ask Claude
show me all tasks
list background agents

Resuming Agents

Use the code-reviewer agent to review the auth module
[Agent completes and returns agent ID]

Continue that code review and analyze authorization logic

The resumed agent retains full conversation history.

Use Cases

Explore Agent

Research the authentication, database, and API modules in parallel
Use a subagent to investigate how token refresh works
Use the Explore agent to find all error handling code

Plan Agent

claude --permission-mode plan
# "I need to refactor authentication to use OAuth2. Create a migration plan."

Custom Code Review Agent

Use the code-reviewer agent to suggest improvements

Custom Debugger Agent

Have the debugger subagent investigate why users can't log in

Best Practices

Design Focused Agents

Each agent should excel at one specific task:

  • Good: code-reviewer, db-reader, security-reviewer
  • Avoid: all-purpose-helper

Write Detailed Descriptions

# Good
description: Expert code reviewer. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.

# Avoid
description: Review code

Limit Tool Access

# Code reviewer doesn't need to modify files
tools: Read, Grep, Glob, Bash
disallowedTools: Write, Edit

Check Project Agents Into Version Control

git add .claude/agents/
git commit -m "feat: add code-reviewer and security-reviewer agents"

Use Subagents for Investigation

Use a subagent to run the test suite and report only failing tests

Run Independent Research in Parallel

Research the authentication, database, and API modules in parallel using separate subagents

Chain Agents for Workflows

Use the code-reviewer agent to find issues, then use the fixer agent to resolve them

Resource Limits

Agents operate within the following constraints:

ResourceLimitNotes
Context windowSame as parent modelShared token budget
Max turnsConfigurable via max_turnsDefault: unlimited
TimeoutNo hard limitUse --max-turns for control
Concurrent agentsPlatform-dependentBackground tasks may queue

Controlling agent execution:

# Limit agentic turns
claude -p "Review code" --max-turns 10

# Set spending limit
claude -p "Analyze project" --max-budget-usd 5.00

Environment variables:

VariablePurpose
CLAUDE_CODE_SUBAGENT_MODELOverride model for all subagents
CLAUDE_CODE_DISABLE_BACKGROUND_TASKSDisable background execution

Context Management

Auto-compaction:

  • Agents support automatic compaction at ~95% capacity
  • Trigger earlier: CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=50

Transcript persistence:

  • Agent transcripts persist within their session
  • Can resume after Claude Code restart
  • Cleaned up after 30 days (default)

Sources

On this page