> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/QwenLM/qwen-code/llms.txt
> Use this file to discover all available pages before exploring further.

# Subagents

> Delegate specialized tasks to focused AI agents for parallel execution

## Overview

Subagents are specialized AI agents that can be delegated specific tasks. They operate independently from the main agent, allowing for:

* **Parallel execution** of multiple tasks
* **Domain specialization** with focused instructions
* **Isolated reasoning** for complex problems
* **Reduced context pollution** in the main conversation

Think of subagents as coworkers you delegate work to - each with their own expertise and focus.

## How Subagents Work

<Steps>
  <Step title="Task Delegation">
    The main agent identifies a subtask suitable for delegation and invokes the `task` tool.
  </Step>

  <Step title="Subagent Initialization">
    A specialized agent is spawned with:

    * The specific task description
    * Relevant context from the main conversation
    * Access to the same tools as the main agent
    * Independent conversation history
  </Step>

  <Step title="Independent Execution">
    The subagent:

    * Reasons about the task independently
    * Calls tools as needed
    * Builds its own conversation context
    * Requests approvals separately (in default mode)
  </Step>

  <Step title="Result Return">
    When complete, the subagent returns:

    * Task results
    * Any artifacts created
    * Summary of actions taken
    * Token usage statistics
  </Step>

  <Step title="Main Agent Continues">
    The main agent receives the results and continues with the overall task.
  </Step>
</Steps>

## Using Subagents

### Natural Language

The AI automatically delegates when appropriate:

```
> Build a REST API with authentication, database, and tests

I'll break this down into specialized tasks:

1. Delegating to subagent: Design database schema
   ➜ Subagent analyzing requirements...
   ➜ Created schema.sql
   ✓ Subagent complete

2. Delegating to subagent: Implement authentication
   ➜ Subagent building auth module...
   ➜ Created src/auth/
   ✓ Subagent complete

3. Delegating to subagent: Create API endpoints
   ➜ Subagent implementing REST routes...
   ➜ Created src/api/
   ✓ Subagent complete

4. Delegating to subagent: Write integration tests
   ➜ Subagent writing test suite...
   ➜ Created tests/integration/
   ✓ Subagent complete

All components complete! The API is ready.
```

### Explicit Delegation

You can also use the `/agents` command:

```bash theme={null}
# Create a specialized subagent
/agents create
```

This opens a configuration dialog where you specify:

* **Name**: Identifier for this subagent type
* **Instructions**: Specialized system prompt
* **Tools**: Which tools this agent can use
* **Model**: Specific model for this agent (optional)

## Subagent Types

### Built-in Subagent Patterns

<Tabs>
  <Tab title="Code Reviewer">
    **Purpose:** Analyze code for issues

    **Instructions:**

    ```
    You are a code reviewer focused on:
    - Security vulnerabilities
    - Performance issues
    - Code style consistency
    - Best practices

    Provide specific, actionable feedback.
    ```

    **Tools:** `read`, `grep`, `glob`, `web_fetch` (read-only)

    **Usage:**

    ```
    > Review the auth module for security issues

    Delegating to code-reviewer subagent...
    ```
  </Tab>

  <Tab title="Test Writer">
    **Purpose:** Generate comprehensive tests

    **Instructions:**

    ```
    You are a test specialist who writes:
    - Unit tests with high coverage
    - Integration tests for critical paths
    - Edge case handling
    - Clear test descriptions

    Follow the project's testing conventions.
    ```

    **Tools:** `read`, `grep`, `write_file`, `bash` (for running tests)

    **Usage:**

    ```
    > Add tests for the payment processing module

    Delegating to test-writer subagent...
    ```
  </Tab>

  <Tab title="Documentation Writer">
    **Purpose:** Create and maintain docs

    **Instructions:**

    ```
    You are a technical writer who creates:
    - Clear API documentation
    - Usage examples
    - Architecture diagrams (in Markdown)
    - README files

    Match the existing documentation style.
    ```

    **Tools:** `read`, `grep`, `glob`, `write_file`

    **Usage:**

    ```
    > Document all exported functions in the API

    Delegating to docs-writer subagent...
    ```
  </Tab>

  <Tab title="Refactoring Specialist">
    **Purpose:** Improve code structure

    **Instructions:**

    ```
    You are a refactoring expert who:
    - Identifies code smells
    - Extracts reusable components
    - Improves naming and structure
    - Maintains behavior (add tests first)

    Make small, safe refactorings.
    ```

    **Tools:** `read`, `grep`, `edit`, `bash` (for tests)

    **Usage:**

    ```
    > Refactor the database layer to use dependency injection

    Delegating to refactor-specialist subagent...
    ```
  </Tab>
</Tabs>

## Managing Subagents

### Creating Custom Subagents

```bash theme={null}
# Open subagent creator
/agents create
```

Configuration example:

```json theme={null}
{
  "name": "api-generator",
  "description": "Generates REST API endpoints from specifications",
  "instructions": [
    "You are an API generator specialist.",
    "Given an API specification, you create:",
    "- Express/Fastify routes",
    "- Request validation schemas",
    "- OpenAPI documentation",
    "- Basic integration tests",
    "",
    "Follow RESTful conventions and the project's existing patterns."
  ],
  "tools": [
    "read",
    "grep",
    "glob",
    "write_file",
    "edit",
    "bash"
  ],
  "model": "gemini-2.5-pro",
  "approvalMode": "auto-edit"
}
```

### Managing Existing Subagents

```bash theme={null}
# View and manage subagents
/agents manage
```

Actions available:

* **View**: See subagent configuration
* **Edit**: Modify instructions or settings
* **Delete**: Remove a subagent
* **Duplicate**: Copy and customize an existing subagent
* **Export**: Save subagent to a file
* **Import**: Load subagent from a file

### Sharing Subagents

Subagent configurations are stored in:

```
~/.qwen/subagents/
  ├── code-reviewer.json
  ├── test-writer.json
  └── api-generator.json
```

Share with team:

```bash theme={null}
# Export to project
cp ~/.qwen/subagents/api-generator.json .qwen/subagents/

# Team members automatically load project subagents
```

## Subagent Behavior

### Independent Context

Each subagent has its own conversation history:

```
Main Agent:
  User: Build a full-stack app
  Assistant: Breaking this into tasks...
  
  Subagent "backend":
    Task: Create Express API with auth
    Reasoning: Need to set up Express, middleware, routes...
    Tool: write_file("src/server.ts", ...)
    Tool: write_file("src/auth.ts", ...)
    Result: API created with auth endpoints
  
  Subagent "frontend":
    Task: Create React app with login
    Reasoning: Need React, routing, auth hooks...
    Tool: write_file("src/App.tsx", ...)
    Tool: write_file("src/hooks/useAuth.ts", ...)
    Result: React app created with login flow
  
  Assistant: Both backend and frontend complete!
```

### Tool Access

Subagents can use the same tools as the main agent:

<Tabs>
  <Tab title="File Operations">
    * `read` - Read files
    * `write_file` - Create files
    * `edit` - Modify files
    * `glob` - Find files
    * `ls` - List directories
  </Tab>

  <Tab title="Code Analysis">
    * `grep` - Search code
    * `ripgrep` - Fast search
    * `lsp` - Language server queries (if configured)
  </Tab>

  <Tab title="Execution">
    * `bash` - Run commands (with approval)
    * `task` - Delegate to nested subagents (yes, they can nest!)
  </Tab>

  <Tab title="External">
    * `web_fetch` - Fetch documentation
    * `web_search` - Search the web
    * `mcp_tool` - Use MCP server tools
  </Tab>
</Tabs>

### Approval Modes

Subagents respect the global approval mode but can have overrides:

```json theme={null}
{
  "name": "safe-analyzer",
  "approvalMode": "plan",  // Always read-only
  "tools": ["read", "grep", "glob"]
}
```

```json theme={null}
{
  "name": "test-automator",
  "approvalMode": "auto-edit",  // Auto-approve edits only
  "tools": ["read", "write_file", "edit", "bash"]
}
```

## Nested Subagents

Subagents can delegate to other subagents:

```
Main: Build a microservices architecture
  └─ Subagent "architect": Design the system
      ├─ Subagent "api-gateway": Design gateway
      ├─ Subagent "service-auth": Design auth service
      └─ Subagent "service-data": Design data service
```

Nesting is limited to prevent infinite recursion:

```json theme={null}
{
  "maxNestingDepth": 3  // Default: 2 levels deep
}
```

## Monitoring Subagents

### In Interactive Mode

Subagent activity is displayed with indentation:

```
➜ Main: Analyzing the codebase...
  ➜ Subagent [security]: Checking for vulnerabilities...
    ✓ Tool: grep("password", "**/*.ts")
    ✓ Tool: read("src/auth.ts")
  ✓ Subagent [security]: Found 2 issues
  
  ➜ Subagent [performance]: Analyzing hot paths...
    ✓ Tool: grep("setTimeout", "**/*.ts")
    ✓ Tool: read("src/polling.ts")
  ✓ Subagent [performance]: Found 3 optimizations
✓ Main: Analysis complete
```

### Stats and Metrics

```bash theme={null}
# View subagent usage
/stats tools
```

Shows:

* Number of subagent invocations
* Average duration per subagent
* Token usage per subagent type
* Success/failure rates

## Use Cases

<AccordionGroup>
  <Accordion title="Parallel Feature Development">
    **Scenario:** Building multiple independent features

    ```
    > Add user profiles, notifications, and search

    Main agent delegates:
    - Subagent 1: User profiles (works on profile components)
    - Subagent 2: Notifications (works on notification system)
    - Subagent 3: Search (works on search functionality)

    All three work in parallel, then results are integrated.
    ```
  </Accordion>

  <Accordion title="Multi-Step Refactoring">
    **Scenario:** Complex refactoring with multiple phases

    ```
    > Refactor to use TypeScript and modern React

    Phase 1 - Subagent "analyzer": Analyze current code
    Phase 2 - Subagent "ts-converter": Convert to TypeScript
    Phase 3 - Subagent "react-updater": Update to modern React
    Phase 4 - Subagent "test-updater": Update tests

    Each phase's subagent has specialized knowledge.
    ```
  </Accordion>

  <Accordion title="Code Review Pipeline">
    **Scenario:** Comprehensive code review

    ```
    > Review this PR thoroughly

    Delegates to specialized reviewers:
    - Subagent "security": Security analysis
    - Subagent "performance": Performance review
    - Subagent "style": Style and conventions
    - Subagent "tests": Test coverage analysis

    Main agent synthesizes all feedback.
    ```
  </Accordion>

  <Accordion title="Documentation Generation">
    **Scenario:** Creating comprehensive docs

    ```
    > Document the entire API

    Main agent delegates by module:
    - Subagent: Document auth module
    - Subagent: Document database module
    - Subagent: Document API routes
    - Subagent: Create usage examples

    Each subagent focuses on one area deeply.
    ```
  </Accordion>
</AccordionGroup>

## Configuration

### Project-Level Subagents

```json theme={null}
// .qwen/subagents/custom-reviewer.json
{
  "name": "custom-reviewer",
  "description": "Reviews code according to our team standards",
  "instructions": [
    "You are a code reviewer for our team.",
    "Check for:",
    "- Our custom ESLint rules",
    "- Proper error handling patterns",
    "- Test coverage",
    "- Documentation completeness"
  ],
  "tools": ["read", "grep", "bash"],
  "approvalMode": "plan"
}
```

### Global Settings

```json theme={null}
// ~/.qwen/settings.json
{
  "subagents": {
    "maxConcurrent": 4,
    "maxNestingDepth": 2,
    "defaultModel": "gemini-2.5-flash",
    "inheritApprovalMode": true,
    "enabled": [
      "code-reviewer",
      "test-writer",
      "docs-writer"
    ]
  }
}
```

## Advanced Features

### Subagent Communication

Subagents can pass data between each other:

```json theme={null}
{
  "name": "coordinator",
  "instructions": [
    "Delegate tasks and coordinate results.",
    "Pass data between subagents as needed."
  ],
  "allowSubagentCommunication": true
}
```

### Custom Models per Subagent

```json theme={null}
{
  "name": "fast-linter",
  "model": "gemini-2.5-flash",  // Fast model for simple tasks
  "instructions": ["Run linting checks"]
}
```

```json theme={null}
{
  "name": "deep-analyzer",
  "model": "gemini-2.5-pro",  // Powerful model for complex analysis
  "instructions": ["Analyze architecture and suggest improvements"]
}
```

### Resource Limits

```json theme={null}
{
  "name": "bounded-task",
  "maxTokens": 10000,
  "maxTurns": 5,
  "timeout": 60000  // 60 seconds
}
```

## Troubleshooting

<AccordionGroup>
  <Accordion title="Subagent not being used">
    **Problem:** Main agent isn't delegating to subagents.

    **Solutions:**

    * Make the task more complex (simple tasks don't need delegation)
    * Explicitly mention using specialized agents
    * Check that subagents are enabled in settings
    * Ensure the task matches subagent capabilities
  </Accordion>

  <Accordion title="Too much delegation">
    **Problem:** Everything is delegated, making things slower.

    **Solutions:**

    * Adjust delegation threshold in settings
    * Be more specific in prompts
    * Disable some subagents temporarily
    * Use simpler prompts for simple tasks
  </Accordion>

  <Accordion title="Subagent conflicts">
    **Problem:** Multiple subagents editing the same files.

    **Solutions:**

    * More specific task delegation
    * Use sequential rather than parallel delegation
    * Define clear boundaries in subagent instructions
    * Let main agent coordinate conflicts
  </Accordion>

  <Accordion title="High token usage">
    **Problem:** Subagents consuming too many tokens.

    **Solutions:**

    * Set `maxTokens` per subagent
    * Use faster models for simple subagents
    * Limit nesting depth
    * Reduce `maxConcurrent` subagents
  </Accordion>
</AccordionGroup>

## Best Practices

1. **Clear boundaries**: Define what each subagent should (and shouldn't) do
2. **Specialized instructions**: Make subagents experts in narrow domains
3. **Limit tools**: Only give subagents the tools they need
4. **Set resource limits**: Prevent runaway subagents with timeouts and token limits
5. **Test subagents**: Try them with specific prompts before relying on them
6. **Monitor usage**: Check stats to optimize subagent configuration
7. **Version control**: Keep subagent configs in your repo for team sharing
8. **Start simple**: Begin with basic subagents, add complexity as needed

## Next Steps

<CardGroup cols={2}>
  <Card title="Skills System" icon="book" href="/features/skills">
    Combine subagents with skills for powerful workflows
  </Card>

  <Card title="Approval Modes" icon="shield" href="/features/approval-modes">
    Configure approval for subagent actions
  </Card>

  <Card title="Session Commands" icon="terminal" href="/features/commands">
    Use /agents commands to manage subagents
  </Card>

  <Card title="Configuration" icon="gear" href="/configuration/settings">
    Advanced subagent configuration options
  </Card>
</CardGroup>
