# Sub-Agents

> Create and use specialized AI sub-agents in CodeBuddy Code for specific task workflows and improved context management.

Custom sub-agents in CodeBuddy Code are specialized AI assistants that can be invoked to handle specific types of tasks. They enable more efficient problem-solving by providing task-specific configurations with custom system prompts, tools, and independent context windows.

## What are Sub-Agents?

Sub-agents are pre-configured AI personas that CodeBuddy Code can delegate tasks to. Each sub-agent:

* Has a specific purpose and area of expertise
* Uses its own context window, separate from the main conversation
* Can be configured to allow specific tool usage
* Contains a custom system prompt that guides its behavior

When CodeBuddy Code encounters a task that matches a sub-agent's area of expertise, it can delegate that task to the specialized sub-agent, which works independently and returns results.

## Key Benefits

| Benefit | Description |
| :--- | :--- |
| **Context Preservation** | Each sub-agent runs in its own context, preventing pollution of the main conversation and keeping it focused on high-level goals. |
| **Specialized Expertise** | Sub-agents can be fine-tuned with domain-specific detailed instructions, improving success rates for designated tasks. |
| **Reusability** | Once created, sub-agents can be used across different projects and shared with your team for consistent workflows. |
| **Flexible Permissions** | Each sub-agent can have different tool access levels, allowing you to restrict powerful tools to specific sub-agent types. |

## Quick Start

To create your first sub-agent:

1. **Open Sub-Agent Interface**

   Run the following command:

   ```
   /agents
   ```

2. **Select "Create New Agent"**

   Choose whether to create a project-level or user-level sub-agent

3. **Define Sub-Agent**

   * **Recommended**: Start with AI generation, then customize to make it your own
   * Describe your sub-agent and when it should be used in detail
   * Select the tools you want to grant access to, or leave empty to inherit all tools
   * The interface shows all available tools
   * If you use AI generation, you can also edit the system prompt in your own editor by pressing `e`

4. **Save and Use**

   Your sub-agent is now available. CodeBuddy Code will automatically use it when appropriate, or you can invoke it explicitly:

   ```
   > Use the code-reviewer sub-agent to check my recent changes
   ```

## Sub-Agent Configuration

### File Location

Sub-agents are stored as Markdown files with YAML frontmatter in two locations:

| Type | Location | Scope | Priority |
| :--- | :--- | :--- | :--- |
| **Project Sub-Agents** | `.codebuddy/agents/` | Available in current project | Highest |
| **User Sub-Agents** | `~/.codebuddy/agents/` | Available in all projects | Lower |

When sub-agent names conflict, project-level sub-agents take priority over user-level sub-agents.

### Plugin Agents

[Plugins](plugins.md) can provide custom sub-agents that integrate seamlessly with CodeBuddy Code. Plugin agents work the same way as user-defined agents and are displayed in the `/agents` interface.

**Plugin Agent Location**: Plugins include agents in their `agents/` directory (or a custom path specified in the plugin manifest).

**Using Plugin Agents**:

* Plugin agents are displayed in `/agents` alongside your custom agents
* Can be explicitly invoked: "Use the code-reviewer agent from the security-plugin"
* Can be automatically invoked by CodeBuddy Code when appropriate
* Can be managed (viewed, inspected) through the `/agents` interface

For details on creating plugin agents, see the [Plugin Component Reference](plugins-reference.md).

### CLI-Based Configuration

You can also dynamically define sub-agents using the `--agents` CLI flag, which accepts a JSON object:

```bash
codebuddy --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "gemini-3.0-flash"
  }
}'
```

**Priority**: CLI-defined sub-agents have lower priority than project-level sub-agents but higher priority than user-level sub-agents.

**Use Cases**: This method is suitable for:

* Quickly testing sub-agent configurations
* Session-specific sub-agents that don't need to be saved
* Automated scripts that require custom sub-agents
* Sharing sub-agent definitions in documentation or scripts

For details on JSON format and all available options, see the [CLI Reference](cli-reference.md).

### File Format

Each sub-agent is defined in a Markdown file with the following structure:

```markdown

Your sub-agent's system prompt goes here. This can be multiple paragraphs
and should clearly define the sub-agent's role, capabilities, and approach
to solving problems.

Include specific instructions, best practices, and any constraints
the sub-agent should follow.
```

#### Configuration Fields

| Field | Required | Description |
| :--- | :--- | :--- |
| `name` | Yes | Unique identifier using lowercase letters and hyphens |
| `description` | Yes | Natural language description of the sub-agent's purpose |
| `tools` | No | Comma-separated list of specific tools. If omitted, inherits all tools from the main thread |
| `model` | No | Model to use for this sub-agent. Can be a model alias (`gpt-5.1-codex`, `gemini-3.0-flash`, etc.) or `'inherit'` to use the main conversation's model. If omitted, defaults to configured sub-agent model |
| `permissionMode` | No | Permission mode for the sub-agent. Valid values: `default`, `acceptEdits`, `bypassPermissions`, `plan`, `ignore`. Controls how the sub-agent handles permission requests |
| `skills` | No | Comma-separated skill names to auto-load when the sub-agent starts |

### Model Selection

The `model` field allows you to control which [AI model](models.md) the sub-agent uses:

* **Model Alias**: Use one of the available aliases: `gpt-5.1-codex`, `gemini-3.0-flash`, `gemini-3.1-pro`, `gpt-5.1-codex`, etc.
* **`'inherit'`**: Use the same model as the main conversation (useful for consistency)
* **Omitted**: If not specified, uses the default model configured for sub-agents

> **Note**: Using `'inherit'` is particularly useful when you want the sub-agent to adapt to the main conversation's model choice, ensuring consistent capabilities and response styles throughout the session.

### Available Tools

Sub-agents can be granted access to any of CodeBuddy Code's internal tools. For a complete list of available tools, see the [Settings Documentation](settings.md).

> **Tip**: **Recommended**: Use the `/agents` command to modify tool access - it provides an interactive interface that lists all available tools, including any connected MCP server tools, making it easier to select the tools you need.

You have two options for configuring tools:

* **Omit the `tools` field** to inherit all tools from the main thread (default), including MCP tools
* **Specify individual tools** as a comma-separated list for more fine-grained control (can be manually edited or edited via `/agents`)

**MCP Tools**: Sub-agents can access MCP tools from configured MCP servers. When the `tools` field is omitted, the sub-agent inherits all MCP tools available to the main thread.

## Managing Sub-Agents

### Using /agents Command (Recommended)

The `/agents` command provides a comprehensive sub-agent management interface:

```
/agents
```

This opens an interactive menu where you can:

* View all available sub-agents (built-in, user, and project)
* Create new sub-agents with guided setup
* Edit existing custom sub-agents, including their tool access
* Delete custom sub-agents
* See which sub-agents are active when duplicates exist
* **Manage tool permissions** with a complete list of all available tools

### Direct File Management

You can also manage sub-agents by working directly with their files:

```bash
# Create a project sub-agent
mkdir -p .codebuddy/agents
echo '---
name: test-runner
description: Use proactively to run tests and fix failures
---

You are a test automation expert. When you see code changes, proactively run the appropriate tests.
If tests fail, analyze the failures and fix them while preserving the original test intent.' > .codebuddy/agents/test-runner.md

# Create a user sub-agent
mkdir -p ~/.codebuddy/agents
# ... create sub-agent file
```

> **Note**: Sub-agents created by manually adding files will load on the next CodeBuddy Code session start. To create and use a sub-agent immediately without restart, use the `/agents` command instead.

## Effective Use of Sub-Agents

### Automatic Delegation

CodeBuddy Code proactively delegates tasks based on:

* The task description in your request
* The `description` field in the sub-agent configuration
* Current context and available tools

> **Tip**: To encourage more proactive sub-agent use, include phrases like "use PROACTIVELY" or "MUST BE USED" in your `description` field.

### Explicit Invocation

Request a specific sub-agent by mentioning it in your command:

```
> Use the test-runner sub-agent to fix failing tests
> Have the code-reviewer sub-agent look at my recent changes
> Ask the debugger sub-agent to investigate this error
```

## Built-in Sub-Agents

CodeBuddy Code includes built-in sub-agents out of the box:

### General-Purpose Sub-Agent

The General-Purpose sub-agent is a powerful agent suitable for complex multi-step tasks that require exploration and manipulation. Unlike the Explore sub-agent, it can modify files and perform a wider range of operations.

**Key Features:**

* **Model**: Uses default model for more robust reasoning
* **Tools**: Has access to all tools
* **Mode**: Can read and write files, execute commands, make modifications
* **Purpose**: Complex research tasks, multi-step operations, code modifications

**When CodeBuddy Code Uses It:**

CodeBuddy Code delegates to the General-Purpose sub-agent when:

* Tasks require both exploration and modification
* Complex reasoning is needed to interpret search results
* Multiple strategies may be needed if initial searches fail
* Tasks have multiple interdependent steps

**Example Scenario:**

```
User: Find all places that handle authentication and update them to use the new token format

CodeBuddy Code: [Invokes general-purpose sub-agent]
[Agent searches codebase for authentication-related code]
[Agent reads and analyzes multiple files]
[Agent makes necessary edits]
[Returns detailed description of changes made]
```

### Plan Sub-Agent

The Plan sub-agent is a specialized built-in agent designed for use during plan mode. When CodeBuddy Code is running in plan mode (non-execution mode), it uses the Plan sub-agent to research and gather information about your codebase before presenting a plan.

**Key Features:**

* **Model**: Uses default model for more robust analysis
* **Tools**: Has access to Read, Glob, Grep, and Bash tools for codebase exploration
* **Purpose**: Search files, analyze code structure, and gather context
* **Automatic Invocation**: When CodeBuddy Code is in plan mode and needs to research the codebase, it will automatically use this agent

**How It Works:**
When you're in plan mode and CodeBuddy Code needs to understand your codebase to create a plan, it delegates research tasks to the Plan sub-agent. This prevents infinite nesting of agents (sub-agents cannot spawn other sub-agents), while still allowing CodeBuddy Code to gather necessary context.

**Example Scenario:**

```
User: [In plan mode] Help me refactor the authentication module

CodeBuddy Code: Let me research your authentication implementation first...
[Internally invokes Plan sub-agent to explore auth-related files]
[Plan sub-agent searches codebase and returns findings]
CodeBuddy Code: Based on my research, here's my proposed plan...
```

> **Tip**: The Plan sub-agent is only used in plan mode. In normal execution mode, CodeBuddy Code uses the General-Purpose agent or other custom sub-agents you've created.

### Explore Sub-Agent

The Explore sub-agent is a fast, lightweight agent optimized for searching and analyzing codebases. It runs in strict read-only mode and is designed for rapid file discovery and code exploration.

**Key Features:**

* **Model**: Uses gemini-3.0-flash for fast, low-latency searches
* **Mode**: Strict read-only - cannot create, modify, or delete files
* **Available Tools**:
  * Glob - File pattern matching
  * Grep - Content search with regex
  * Read - Read file contents
  * Bash - Read-only commands only (ls, git status, git log, git diff, find, cat, head, tail)

**When CodeBuddy Code Uses It:**

When CodeBuddy Code needs to search or understand the codebase but doesn't need to make changes, it delegates to the Explore sub-agent. This is more efficient than the main agent running multiple search commands directly, as content found during exploration doesn't bloat the main conversation.

**Thoroughness Levels:**

When invoking the Explore sub-agent, CodeBuddy Code specifies a thoroughness level:

* **Quick** - Fast searches with minimal exploration. Suitable for targeted finds.
* **Medium** - Moderate exploration. Balances speed and thoroughness.
* **Very thorough** - Comprehensive analysis across multiple locations and naming conventions. Used when targets may be in unexpected places.

**Example Scenarios:**

```
User: Where are errors handled on the client?

CodeBuddy Code: [Invokes Explore sub-agent with "medium" thoroughness]
[Explore searches for error handling patterns using Grep]
[Explore checks potentially relevant files using Read]
[Returns findings with absolute file paths]
CodeBuddy Code: Client errors are handled in src/services/process.ts:712...
```

```
User: What's the structure of the codebase?

CodeBuddy Code: [Invokes Explore sub-agent with "quick" thoroughness]
[Explore uses Glob and ls to map directory structure]
[Returns overview of key directories and their purposes]
```

## Example Sub-Agents

### Code Reviewer

```markdown
---
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: inherit
---

You are a senior code reviewer ensuring high standards of code quality and security.

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

Review checklist:
- Code is simple and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed

Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)

Include specific examples of how to fix issues.
```

### Debugger

```markdown
---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
tools: Read, Edit, Bash, Grep, Glob
---

You are an expert debugger specializing in root cause analysis.

When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works

Debugging process:
- Analyze error messages and logs
- Check recent code changes
- Form and test hypotheses
- Add strategic debug logging
- Inspect variable states

For each issue, provide:
- Root cause explanation
- Evidence supporting the diagnosis
- Specific code fix
- Testing approach
- Prevention recommendations

Focus on fixing the underlying issue, not just symptoms.
```

### Data Scientist

```markdown
---
name: data-scientist
description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries.
tools: Bash, Read, Write
model: gpt-5.1-codex
---

You are a data scientist specializing in SQL and BigQuery analysis.

When invoked:
1. Understand the data analysis requirement
2. Write efficient SQL queries
3. Use BigQuery command line tools (bq) when appropriate
4. Analyze and summarize results
5. Present findings clearly

Key practices:
- Write optimized SQL queries with proper filters
- Use appropriate aggregations and joins
- Include comments explaining complex logic
- Format results for readability
- Provide data-driven recommendations

For each analysis:
- Explain the query approach
- Document any assumptions
- Highlight key findings
- Suggest next steps based on data

Always ensure queries are efficient and cost-effective.
```

## Best Practices

* **Start with AI-Generated Agents**: We strongly recommend using AI to generate your initial sub-agent, then iterating on it to make it your own. This approach gives you the best results - a solid foundation that you can customize to meet your specific needs.

* **Design Focused Sub-Agents**: Create sub-agents with a single, clear responsibility instead of trying to make one sub-agent do everything. This improves performance and makes sub-agents more predictable.

* **Write Detailed Prompts**: Include specific instructions, examples, and constraints in your system prompt. The more guidance you provide, the better the sub-agent will perform.

* **Limit Tool Access**: Only grant the tools necessary for the sub-agent's purpose. This improves security and helps the sub-agent focus on relevant operations.

* **Version Control**: Check project sub-agents into version control so your team can benefit from them and collaborate on improvements.

## Advanced Usage

### Chaining Sub-Agents

For complex workflows, you can chain multiple sub-agents:

```
> First use the code-analyzer sub-agent to find performance issues, then use the optimizer sub-agent to fix them
```

### Dynamic Sub-Agent Selection

CodeBuddy Code intelligently selects sub-agents based on context. Make your `description` field specific and action-oriented for best results.

### Resumable Sub-Agents

Sub-agents can be resumed to continue previous conversations, which is particularly useful for long-running research or analysis tasks that need to continue across multiple invocations.

**How It Works:**

* Each sub-agent execution is assigned a unique `agentId`
* The agent's conversation is stored in a separate record file: `agent-{agentId}.jsonl`
* You can resume a previous agent by providing its `agentId` via the `resume` parameter
* When resumed, the agent continues with the full context of its previous conversation

**Example Workflow:**

Initial invocation:

```
> Use the code-analyzer agent to start reviewing the authentication module

[Agent completes initial analysis and returns agentId: "abc123"]
```

Resume agent:

```
> Resume agent abc123 and now analyze the authorization logic as well

[Agent continues with full context from previous conversation]
```

**Use Cases:**

* **Long-Running Research**: Break large codebase analysis into multiple sessions
* **Iterative Refinement**: Continue refining the sub-agent's work without losing context
* **Multi-Step Workflows**: Have a sub-agent sequentially handle related tasks while maintaining context

**Technical Details:**

* Agent records are stored in your project directory
* Recording is disabled during resumption to avoid duplicate messages
* Both synchronous agents and [background agents](#background-agents) can be resumed
* The `resume` parameter accepts the agent ID from a previous execution

**Programmatic Usage:**

If you're using the Agent SDK or interacting with the AgentTool directly, you can pass the `resume` parameter:

```typescript
{
  "description": "Continue analysis",
  "prompt": "Now examine the error handling patterns",
  "subagent_type": "code-analyzer",
  "resume": "abc123"  // Agent ID from previous execution
}
```

Keep track of agent IDs for tasks you may want to resume later. CodeBuddy Code displays the agent ID when a sub-agent completes its work.

### Background Agents

Background agents allow you to run sub-agent tasks in the background without blocking the main conversation. This is particularly useful for long-running tasks where you can continue interacting with CodeBuddy Code while the task executes in the background.

**How It Works:**

* Launch a background agent using the `run_in_background: true` parameter
* The task immediately returns a task ID without blocking the main conversation
* Background agents run in detached mode, with intermediate messages not interfering with the main conversation
* Use the `TaskOutput` tool to get the status and results of background tasks

**Launching a Background Agent:**

```
> Run the code-analyzer agent in the background to review the entire codebase

[Task started in background. Task ID: task-abc123]
```

**Getting Background Task Output:**

Use the `TaskOutput` tool to query the status and results of a background task:

```
> Check the status of background task task-abc123

Task ID: task-abc123
Status: running
Elapsed time: 2m 30s

Prompt:
Review entire codebase for code quality issues

Response:
(Task still running)
```

**Background Task Status:**

| Status | Description |
| :--- | :--- |
| `pending` | Task created, waiting for execution |
| `running` | Task is executing |
| `completed` | Task completed successfully |
| `failed` | Task execution failed |
| `cancelled` | Task was cancelled by user |
| `killed` | Task was forcibly terminated |

**Programmatic Usage:**

If you're using the Agent SDK or interacting with the Task tool directly, you can pass the `run_in_background` parameter:

```typescript
{
  "description": "Analyze codebase",
  "prompt": "Review all TypeScript files for potential issues",
  "subagent_type": "code-analyzer",
  "run_in_background": true  // Run in background
}
```

**Parameters for Getting Output:**

The `TaskOutput` tool supports the following parameters:

| Parameter | Type | Description |
| :--- | :--- | :--- |
| `task_id` | string | Required. The ID of the background task |
| `block` | boolean | Whether to wait for task completion. Defaults to `true` |
| `timeout` | number | Wait timeout in milliseconds. Default 30000ms, max 600000ms |

**Use Cases:**

* **Parallel Analysis**: Run multiple code analysis tasks simultaneously without blocking the main conversation
* **Long-Running Tasks**: Execute time-consuming codebase scans or refactoring analyses
* **Batch Processing**: Process large numbers of files or perform complex multi-step tasks in the background
* **Non-Blocking Workflows**: Continue other work while waiting for background tasks to complete

**Permission Handling:**

Background agents automatically handle permissions for tool calls during execution without user interaction. This ensures background tasks can execute smoothly without blocking due to waiting for user input.

> **Note**: Background agents are suitable for tasks that don't require frequent user interaction. If a task requires multiple user confirmations or inputs, foreground mode execution is recommended.

## Performance Considerations

* **Context Efficiency**: Agents help preserve main context, enabling longer overall sessions
* **Latency**: Sub-agents start from a clean state each invocation and may add latency as they gather context needed to work effectively.

## Related Documentation

* [Plugins](plugins.md) - Extend CodeBuddy Code with custom agents via plugins
* [Slash Commands](slash-commands.md) - Learn about other built-in commands
* [Settings Configuration](settings.md) - Configure CodeBuddy Code behavior
* [Hooks](hooks.md) - Automate workflows with event handlers

---

*This documentation helps you understand how to create and use sub-agents in CodeBuddy Code to improve productivity.*
