# Sub-Agents

Sub-agents are specialized agent instances spawned by the main agent to handle specific tasks. They enable parallelization, specialization, and isolation while keeping the main context clean.

## Why Sub-Agents?

| Benefit | Description |
|---|---|
| **Context isolation** | Each sub-agent has its own context, doesn't pollute main agent's context |
| **Specialization** | Can be configured with different system prompts, tools, models |
| **Parallelization** | Multiple sub-agents can work simultaneously on independent tasks |
| **Cost optimization** | Use cheaper/faster models for simple tasks |
| **Scalability** | Break complex work into manageable pieces |
| **Safety** | Restricted permissions for specific tasks |

## Sub-Agent Architecture

```mermaid
graph TD
    A[Main Agent] --> B[Task Decomposition]
    B --> C[Spawn Sub-Agent 1]
    B --> D[Spawn Sub-Agent 2]
    B --> E[Spawn Sub-Agent 3]
    C --> F[Sub-Agent 1 Context]
    D --> G[Sub-Agent 2 Context]
    E --> H[Sub-Agent 3 Context]
    F --> I[Results]
    G --> I
    H --> I
    I --> A[Main Agent Synthesizes]
    
    style A fill:#e1f5fe
    style C fill:#f3e5f5
    style D fill:#f3e5f5
    style E fill:#f3e5f5
    style I fill:#e8f5e9
```

## When to Use Sub-Agents

| Scenario | Good Use? | Reason |
|---|---|---|
| **Search across large codebase** | Yes | Isolate exploration, summarize findings |
| **Run tests and fix failures** | Yes | Focused task with specific tools |
| **Research external docs** | Yes | Web search + synthesis |
| **Refactor large module** | Yes | Complex but focused scope |
| **Quick file read** | No | Overhead not worth it |
| **Simple edit** | No | Main agent can do directly |
| **Coordinating multiple systems** | Maybe | Depends on complexity |

## Sub-Agent Configuration

```typescript
interface SubAgentConfig {
  name: string;           // Purpose identifier
  description: string;    // When to use this sub-agent
  systemPrompt: string;   // Specialized instructions
  tools: string[];        // Allowed tools (restrictive)
  model?: string;         // Override model (cheaper/faster)
  maxTurns?: number;      // Limit iterations
  permissions?: PermissionProfile;
  context?: {
    includeFiles?: string[];
    includeMemory?: boolean;
  };
}
```

## Built-in Sub-Agent Patterns

| Pattern | Purpose | Tools | Model |
|---|---|---|---|
| **Explore** | Codebase exploration, finding files/patterns | read, glob, grep | Fast/cheap model |
| **Plan** | Task breakdown and planning | read, grep (read-only) | Reasoning model |
| **Execute** | Implement changes | read, write, edit, bash | Task-appropriate |
| **Review** | Code review, find issues | read, grep, diff | Reasoning model |
| **Test** | Run tests, debug failures | read, bash, edit | General purpose |

## Spawning Sub-Agents

```python
async def spawn_subagent(config: SubAgentConfig, task: string) -> SubAgentResult:
    # Create isolated session
    sub_session = await create_sub_session(parent_session_id)
    
    # Build context for sub-agent
    context = build_subagent_context(config, task)
    
    # Run sub-agent loop with restrictions
    result = await run_agent_loop(
        session=sub_session,
        system_prompt=config.systemPrompt,
        tools=filter_tools(config.tools),
        model=config.model or parent_model,
        max_turns=config.max_turns or 10,
        permissions=config.permissions
    )
    
    return SubAgentResult(
        summary=result.summary,
        findings=result.findings,
        files_changed=result.files_changed,
        success=result.success
    )
```

## Communication Patterns

### Fire and Forget
Main agent spawns and continues, doesn't wait for result.

```python
await spawn_background_subagent(config, task)
# Continue with other work
```

### Synchronous (Wait for Result)
Main agent waits for sub-agent to complete and uses results.

```python
result = await spawn_subagent(config, task)
# Use result in main agent context
```

### Parallel
Multiple sub-agents working simultaneously.

```python
results = await asyncio.gather(
    spawn_subagent(explore_config, "find auth code"),
    spawn_subagent(test_config, "run related tests"),
)
```

## Result Summarization

Sub-agents should return concise summaries to avoid bloating main context:

```typescript
interface SubAgentResult {
  summary: string;        // Brief summary of what was done
  keyFindings: string[];  // Important discoveries
  filesModified: string[];
  filesRead: string[];
  recommendations?: string[];
  needsFollowUp: boolean;
  rawOutput?: string;     // Only if necessary
}
```

## Context Passing

### What to pass TO sub-agent:
- Specific task description
- Relevant file paths
- Relevant context from main session
- Constraints/requirements
- Tool restrictions

### What NOT to pass:
- Full conversation history
- Unrelated files
- All tool results
- Personal preferences (unless relevant)

## Best Practices

### Design
1. **Narrow scope** - Give sub-agent a specific, well-defined task
2. **Clear instructions** - Include goal, constraints, and expected output
3. **Minimal tools** - Only tools needed for the task
4. **Appropriate model** - Use cheaper models for simple tasks
5. **Set turn limits** - Prevent runaway sub-agents

### Execution
1. **Summarize results** - Main agent should get condensed results
2. **Parallelize wisely** - Only independent tasks in parallel
3. **Handle failures** - Sub-agent failures shouldn't crash main agent
4. **Track costs** - Monitor token usage across all sub-agents
5. **Avoid deep nesting** - Usually 1-2 levels max

### Safety
1. **Restrict permissions** - Sub-agents often need fewer permissions
2. **Isolate work** - Consider using worktrees for code changes
3. **Review changes** - Main agent should review sub-agent changes
4. **Limit scope** - Don't let sub-agents modify unrelated files

## Example: Explore Sub-Agent

```yaml
name: explore
description: "Search and explore codebase to understand patterns"
systemPrompt: |
  You are an exploration specialist. Your job is to find and understand code.
  Be thorough but concise. Return a clear summary of findings.
  Don't make changes - only read and search.
tools:
  - read_file
  - glob
  - grep
  - list_dir
model: "fast-model"
maxTurns: 15
permissions:
  mode: "read-only"
```

## Example: Implementation Sub-Agent

```yaml
name: implement
description: "Implement a specific feature or fix"
systemPrompt: |
  You are an implementation specialist. Focus on the specific task.
  Follow existing code patterns. Make minimal, focused changes.
  Run tests if they exist for the modified code.
tools:
  - read_file
  - write_file
  - edit
  - grep
  - glob
  - bash
model: "balanced-model"
maxTurns: 30
permissions:
  mode: "interactive"
```

## Debugging Sub-Agents

- **Log sub-agent sessions separately** - Easier to trace
- **Show sub-agent status in UI** - Keep user informed
- **Allow inspection** - View sub-agent's thinking/tool calls
- **Track hierarchy** - Know parent-child relationships

## Related Notes

- [[../Execution/Parallel-Execution.md]] — Parallel tool execution
- [[../Core-Components/Task-Management.md]] — Task decomposition
- [[../Core-Components/Permission-System.md]] — Permissions
- [[../StateManagement/Session-Management.md]] — Sessions
- [[../Fundamentals/Agent-Loop.md]] — Agent loop

## Sources

* Claude Code sub-agents documentation  
* OpenCode task/subagent patterns  
* Anthropic multi-agent research  
* LangGraph sub-graphs  
* "Agentic Patterns" - sub-agent delegation  
