tencent cloud

Subagent

Download
Focus Mode
Font Size
Last updated: 2026-09-30 18:41:45
AI-Translated

Overview

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

What Is a Subagent?

Subagents are preconfigured AI personas to which CodeBuddy Code can delegate tasks. Each subagent:
Have a specific purpose and area of expertise.
Use their own context window, separate from the main conversation.
Can be configured to allow specific tools.
Contain custom system prompts that guide their behavior.
When CodeBuddy Code encounters a task that matches a subagent's area of expertise, it can delegate the task to that specialized subagent, which works independently and returns the result.

Key Benefits

Strength
Description
Context retention
Each subagent runs in its own context, preventing the main conversation from being contaminated and keeping it focused on high-level goals.
Specialized knowledge
Subagents can be fine-tuned with domain-specific detailed instructions, thereby improving the success rate of designated tasks.
Reusability
Once created, subagents can be used across different projects and shared with your team to achieve consistent workflows.
Flexible permissions
Each subagent can have different tool access levels, allowing you to restrict powerful tools to specific subagent types.

Quick Start

To create your first subagent:
1. Open the subagent page
Run the following command:
/agents
2. Select "Create New Agent"
Choose whether to create a project-level or user-level subagent.
3. Define the subagent
Recommended: Start with AI generation, then customize it to make it your own.
Describe your subagent in detail, including when it should be used.
Select the tools you want to grant access to, or leave it blank to inherit all tools.
The page displays all available tools.
If you use AI generation, you can also press e to edit the system prompt in your own editor.
4. Save and Use
Your subagent is now available. CodeBuddy Code will automatically use it when appropriate, or you can explicitly invoke it:
> Use the code-reviewer subagent to check my recent changes.

Subagent Configuration

File Location

Subagents are stored as Markdown files with YAML frontmatter in two locations:
Type
Position
Scope
Priority
Project subagent
.codebuddy/agents/
Available in the current project
Highest
User subagent
~/.codebuddy/agents/
Available in all projects
Moderately Low
When subagent names conflict, project-level subagents take precedence over user-level subagents.

Plugin Agent

Plugins can provide custom subagents that integrate seamlessly with CodeBuddy Code. Plugin agents work the same way as user-defined agents and are displayed on the /agents page.
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 together with your custom agents on the /agents page.
You can explicitly invoke it: "Use the code-reviewer agent from security-plugin".
It can be automatically invoked by CodeBuddy Code when appropriate.
You can manage them (view and inspect) on the /agents page.
For details on creating plugin agents, see the Plugin Components Reference.

CLI-Based Configuration

You can also define subagents dynamically using the --agents CLI flag, which accepts a JSON object:
codebuddy --agents '{
"code-reviewer": {
"description": "Code review expert. 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: Subagents defined via CLI have lower priority than project-level subagents, but higher priority than user-level subagents.
Use Cases: This method is suitable for
Quickly test the subagent configuration.
Session-specific subagents that do not need to be saved
Automation scripts that require custom subagents
Share subagent definitions in documents or scripts.
For details on the JSON format and all available options, see the CLI Reference documentation.

File format

Each subagent is defined in a Markdown file with the following structure:
---
name: your-sub-agent-name
description: Describes when this subagent should be called.
tools: tool1, tool2, tool3 # Optional - If omitted, all tools are inherited.
model: gpt-5.1-codex # Optional - Specify a model alias or 'inherit'.
permissionMode: default # Optional - The permission mode for the subagent.
skills: skill1, skill2 # Optional - Skills to load automatically.
---

Write the system prompt for the subagent here. It can contain multiple paragraphs.
Clearly define the subagent's role, capabilities, and approach to solving problems.

Include specific instructions, best practices, and any constraints that the subagent should follow.

Configuration Field

Field
Required
Description
name
Yes
Unique identifier using lowercase letters and hyphens
description
Yes
Natural language description of the subagent's purpose
tools
No
A comma-separated list of specific tools. If the list is omitted, all tools in the main thread are inherited. You can use the Defer(X) / NoDefer(X) modifiers to adjust the deferred loading state of tools. For details, see Tool Deferred Loading Override.
model
No
A model ID, name, or alias, a scenario variant lite / reasoning, or inherit / default. When the value is omitted or set to inherit / default, no specific model is enforced, and the model continues to be selected through the normal subagent resolution chain.
permissionMode
No
Permission mode of the subagent. Valid values: default, acceptEdits, bypassPermissions, plan, ignore. Controls how the subagent handles permission requests.
skills
No
Names of skills automatically loaded when the subagent starts, separated by commas
mcpServers
No
Declaration of MCP servers dedicated to the subagent. Supports referencing existing global MCP servers or declaring private inline MCP servers for the current subagent. For details, see the description below.
disallowedTools
No
List of tools disallowed for the subagent (array or comma-separated), which takes effect as the union with the session-level disallowedTools
effort
No
Reasoning effort: minimal / low / medium / high / xhigh / max. If the reasoning effort is omitted, the session effort is inherited.
maxTurns
No
Maximum execution turns of the subagent (a positive integer). Priority: env CODEBUDDY_CODE_SUBAGENT_MAX_TURNS > the max_turns parameter of the Agent tool > this field.
background
No
When set to true, the subagent always runs in the background (equivalent to the caller passing run_in_background: true); when CODEBUDDY_CODE_DISABLE_BACKGROUND_TASKS is enabled, it degrades to synchronous execution (only logs are written, with no user-visible alarm).
initialPrompt
No
When this agent runs as the main session agent (--agent or the settings agent), it is automatically prefixed to the first user message and injected only in the first turn of the main session.
memory
No
Persistent memory scope: user (~/.codebuddy/agent-memory/<name>/), project (<cwd>/.codebuddy/agent-memory/<name>/), local (not stored in version control). When persistent memory is enabled, MEMORY.md is automatically injected at spawn time (truncated to 200 lines / 25 KB), and an explicit tools allowlist automatically adds Read/Write/Edit.

Nesting Depth and Session Budget

Subagent nesting depth is capped at 5 levels (the main session is level 0 and cannot be configured). When this limit is exceeded, the Agent tool returns an error and prompts the subagent to use its own tools to complete the remaining work. Subagents do not have the Agent tool by default. Only agents whose definitions explicitly list tools: Agent can continue nesting.
The per-session spawn budget defaults to 200 and can be adjusted up or down using CODEBUDDY_CODE_MAX_SUBAGENTS_PER_SESSION (a positive integer that cannot be disabled). Nested spawns share the same budget, which is reset after /clear. The budget counts only spawns through the Agent tool path. The workflow/skill path constructs AgentTask directly and does not pass through this gate.

Subagent Output Scanning

Before the final report from a subagent is sent back to the main conversation, non-destructive detoxification is performed (using a proprietary ruleset with no equivalent mechanism in the Claude Code client). Spoofed <system-reminder> tags are rewritten to <\\system-reminder>, and a backslash is added to Human: / Assistant: at the beginning of a line. When a match occurs, a marker line [harness: subagent output matched ...] is added to the beginning of the report. Detoxification only inserts backslashes into matched segments and does not delete content. Tool calls induced by the report still go through normal permission checks.

Subagent-Specific MCP server

mcpServers is used to declare MCP servers for a subagent that are visible only while that subagent is running. It is not written to the global MCP configuration, and it is not automatically visible to the main conversation or other subagents. Two syntaxes are supported.
Reference an existing global MCP server:
---
name: docs-searcher
description: Use the existing docs MCP for search.
tools:
- Read
mcpServers:
- docs
---
The docs here must already be a globally connected MCP server. The subagent only borrows it and does not close it when the subagent ends.
Declare an inline MCP server:
---
name: browser-checker
description: Use a private MCP for browser inspection.
tools:
- ToolSearch
- DeferExecuteTool
mcpServers:
- browser_private:
type: stdio
command: node
args:
- /absolute/path/to/browser-mcp-server.js
defer_loading: true
---
An inline MCP server is created only within the subagent session and is automatically closed when the subagent ends. It does not enter the global MCP pool.

Security Policies

Source
mcpServers Behavior
User subagent: ~/.codebuddy/agents/*.md
Allows inline MCP.
Project subagent: .codebuddy/agents/*.md
Allows inline MCP, but requires local project approval.
Plugin agent
Ignores mcpServers.
strictMcpConfig=true
Skips all agent frontmatter/product mcpServers.
The inline MCP of a project subagent must be written to the project's local configuration, which is located at .codebuddy/settings.local.json in the current workspace:
{
"enabledMcpjsonServers": ["browser_private"]
}
You can also approve it through CLI settings at this launch:
codebuddy --settings '{"enabledMcpjsonServers":["browser_private"]}'
Note:
Use the server name here, consistent with the approval method for existing PROJECT MCPs. Do not write it to the user-level global settings.json, because project MCP approval reads only the project-local and CLI scopes.

Direct and deferred

scoped MCP uses the same lazy loading policy as the global CodeBuddy MCP. By default, MCP tools go through deferred loading: the model first discovers tools through ToolSearch and then invokes them through DeferExecuteTool.
Example of the default deferred configuration:
tools:
- ToolSearch
- DeferExecuteTool
mcpServers:
- finance_data:
type: stdio
command: node
args:
- /absolute/path/to/finance-mcp-server.js
If you want MCP tools to appear directly in the subagent tool list, you can explicitly disable defer:
mcpServers:
- finance_data:
type: stdio
command: node
args:
- /absolute/path/to/finance-mcp-server.js
defer_loading: false
You can also adjust the lazy loading behavior for individual tools by using the Defer(...) / NoDefer(...) modifiers in the tools field.

Model Selection

The model field allows you to control the AI model used by the subagent:
Model ID, name, or alias: Select an available model directly.
Scenario variants: Use lite or reasoning, which are then mapped to a specific model by /model or variantModels.
inherit / default, or omitted: No specific model is enforced, and resolution continues in the order of environment variables, per-invocation settings, per-subagent settings, built-in declarations, and the main conversation model.
Note:
When inherit is used, if no higher-priority configuration exists, the subagent ultimately inherits the main conversation model, which helps maintain consistency in features and response style.

Available Tools

Subagents can be granted access to any internal tool of CodeBuddy Code. For a complete list of available tools, see the Settings documentation.
Note:
It is recommended to use the /agents command to modify tool access permissions - it provides an interactive interface that lists all available tools, including any connected MCP server tools, making it easier to select the desired tools.
You have two options to configure 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 finer control (which can be edited manually or through /agents).
MCP tools: Subagents can access MCP tools from configured MCP servers. When the tools field is omitted, subagents inherit all MCP tools available to the main thread.

Managing Subagents

Using the /agents Command (Recommended)

The /agents command provides a comprehensive interface for subagent management:
/agents
This opens an interactive menu where you can:
View all available subagents (built-in, user, and project).
View the currently effective routing values for built-in subagents and their subagent-level sources. The specific models corresponding to scenario variants can be viewed in /model.
Set a model or a lite / reasoning scenario variant for a built-in subagent through Edit Model.
View the built-in subagent definition through View Definition.
Create a new subagent using guided setup.
Edit an existing custom subagent, including its tool access permissions.
Delete a custom subagent.
View which subagents are active when duplicates exist.
Manage Tool Permissions, including a complete list of all available tools.

Configuring Models for Built-in Subagents (per-Agent Models)

Built-in subagents (such as Explore, general-purpose, and Plan) can also specify models independently at the subagent level, with no impact on each other and free combination. This resolves the previous pain point where only a one-size-fits-all approach through environment variables was possible, making differentiation impossible.
Visually configure on the /agents panel:
1. Run /agents, select a built-in subagent with ↑/↓, and press Enter to open its action menu.
2. Select Edit Model to open the model selector:
The first option, Inherit / Default, clears the subagent's configuration and falls back to the default orchestration.
General-purpose scenario variants lite / reasoning.
All available models (consistent with /model).
3. Use Tab to switch between the Global and Project save scopes, and press Enter to confirm.
4. The list refreshes immediately to show the effective routing value + subagent-level source. This value may be a specific model or a scenario variant such as lite / reasoning. The specific model and source that a scenario variant ultimately maps to can be viewed through /model:lite / /model:reasoning.
The SOURCE column on the panel shows the source of each subagent's routing value, making the default orchestration transparent:
Source Tag
Description
env-global
Environment variable CODEBUDDY_CODE_SUBAGENT_MODEL takes over across the board (see priority below).
settings-project
Project-level configuration (.codebuddy/settings.json)
settings-user
Global configuration (~/.codebuddy/settings.json)
product-default
Built-in default declaration (for example, Explore = lite)
inherit
No declaration is made, and the main conversation model is inherited.
fallback-main
The configured model is disabled/locally unknown, and the system falls back to the main conversation model.
Configure storage: Write to the subagents.agents.<subagent_name>.model field in settings (where the key of agents is the subagent name, and model is the model ID / alias / variant / inherit / default). You can also manually edit settings.json. For details, see Settings documentation.
Priority (from highest to lowest):
1. Environment variable CODEBUDDY_CODE_SUBAGENT_MODEL (a one-size-fits-all override that applies uniformly to all subagents, with the highest priority)
2. The tool input parameter for this call (default / lite / reasoning, effective for a single call)
3. Project-level subagents.agents.<subagent_name>.model
4. Global-level subagents.agents.<subagent_name>.model
5. Built-in default declarations (the agents[].models[0] in product.json, such as Explore = lite)
6. Inherit the main conversation model (fallback).
Note:
When CODEBUDDY_CODE_SUBAGENT_MODEL is set, the panel still allows saving per-Agent configurations without reporting an error, but it displays a message indicating that they are uniformly overridden by the environment variable. After the environment variable is removed, the per-Agent configurations take effect again.

Direct File Management

You can also manage subagents by directly working with their files:
# Create a project subagent
mkdir -p .codebuddy/agents
echo '---
name: test-runner
description: Proactively run tests and fix failures
---

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

# Create a user subagent
mkdir -p ~/.codebuddy/agents
# ... Create the subagent file
Note:
Subagents created by manually adding files are loaded the next time a CodeBuddy Code session starts. To create and use a subagent immediately without restarting, use the /agents command instead.

Using Subagents Effectively

Automatic Delegation

CodeBuddy Code proactively delegates tasks based on the following factors:
The task description in your request
The description field in the subagent configuration
Current context and available tools
Note:
To encourage more proactive subagent use, include phrases such as "use PROACTIVELY" or "MUST BE USED" in your description field.

Explicit Invocation

Request a specific subagent by mentioning it in your command:
> Use the test-runner subagent to fix failing tests
> Have the code-reviewer subagent check my recent changes.
> Ask the debugger subagent to investigate this error.

Built-in Subagents

CodeBuddy Code includes built-in subagents that work out of the box:

General-Purpose Subagent

The General-Purpose subagent is a powerful agent suited for complex multi-step tasks that require exploration and manipulation. Unlike the Explore subagent, it can modify files and perform a broader range of operations.
Key features:
Model: Uses the default orchestration and can be independently adjusted for this subagent through /agents.
Tools: Can access all tools.
Mode: Can read and write files, run commands, and make modifications.
Purpose: Complex research tasks, multi-step operations, and code modifications.
When to use CodeBuddy Code:
CodeBuddy Code delegates to the General-Purpose subagent in the following cases:
The task requires both exploration and modification.
Requires complex reasoning to interpret search results.
If the initial search fails, multiple strategies may be required.
The task has multiple interdependent steps.
Example scenario:
User: Find all places that handle authentication and update them to use the new token format.

CodeBuddy Code: [Invoke the general-purpose subagent]
[The agent searches the codebase for authentication-related code.]
[The agent reads and analyzes multiple files.]
[The agent makes the necessary edits.]
[Return a detailed description of the changes made.]

Plan Subagent

The Plan subagent is a specialized built-in agent designed for use during plan mode. When CodeBuddy Code runs in plan mode (not execution mode), it uses the Plan subagent to research and gather information about your codebase before presenting a plan.
Key features:
Model: Uses the default orchestration and can be independently adjusted for this subagent through /agents.
Tools: Can access the 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 automatically uses this agent.
How it works: When you are in plan mode and CodeBuddy Code needs to understand your codebase to create a plan, it delegates research tasks to the Plan subagent. This prevents infinite nesting of agents (subagents cannot spawn other subagents) while still allowing CodeBuddy Code to gather the necessary context.
Example scenario:
User: [In plan mode] Help me refactor the authentication module.

CodeBuddy Code: Let me first look into your authentication implementation...
[Internally invokes the Plan subagent to explore authentication-related files]
[The Plan subagent searches the codebase and returns findings]
CodeBuddy Code: Based on my research, here is my proposed plan...
Note:
The Plan subagent is used only in plan mode. In normal execution mode, CodeBuddy Code uses the General-Purpose agent or other custom subagents that you create.

Explore Subagent

The Explore subagent 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: Built-in declared as the lite scenario variant. The actual model is determined by the corresponding environment variable, project-level and user-level variantModels, the main model's relatedModels, and default orchestration.
Mode: Strictly read-only — cannot create, modify, or delete files.
Available tools:
Glob - File pattern matching
Grep - Content search using regular expressions
Read - Read file content
Bash - Read-only commands only (ls, git status, git log, git diff, find, cat, head, tail)
When to use CodeBuddy Code:
When CodeBuddy Code needs to search or understand a codebase without making changes, it delegates to the Explore subagent. This is more efficient than the main agent running multiple search commands directly, because the content found during exploration does not bloat the main conversation.
Thoroughness level
When invoking the Explore subagent, CodeBuddy Code specifies a thoroughness level:
Quick - Fast search with minimal exploration. Suitable for targeted lookups.
Medium - Moderate exploration. Balances speed and thoroughness.
Very thorough - Comprehensive analysis across multiple locations and naming conventions. Use when the target may be in unexpected locations.
Example scenario:
User: Where are client errors handled?

CodeBuddy Code: [Invoke the Explore subagent with "medium" thoroughness]
[Explore uses Grep to search for error handling patterns]
[Explore uses Read to inspect potentially relevant files]
[Return findings with absolute file paths]
CodeBuddy Code: Client errors are handled in src/services/process.ts:712...
User: What is the structure of the codebase?

CodeBuddy Code: [Invoke the Explore subagent with "quick" thoroughness]
[Explore uses Glob and ls to map the directory structure]
[Return an overview of key directories and their purposes]

Example Subagent

Code Reviewer

---
name: code-reviewer
description: Code review expert. Proactively review code quality, security, and maintainability. Use immediately after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: inherit
---

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

When invoked:
1. Run git diff to view recent changes
2. Focus on modified files
3. Start the review immediately

Review Checklist:
- Code is clear and readable.
- Functions and variables are well named.
- No duplicate code.
- Proper error handling
- No exposed secrets or API keys.
- Input validation implemented.
- Good test coverage
- Performance issues considered.

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

Contains specific examples of how to fix the issue.

Debugger

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

You are an expert-level debugger specializing in root cause analysis.

When invoked:
1. Capture error messages and stack traces.
2. Determine the reproduction steps.
3. Isolate the fault location.
4. Implement the minimal fix.
5. Verify that the solution is effective.

Debugging process:
- Analyze error messages and logs.
- Check recent code changes.
- Form and test hypotheses.
- Add strategic debug logs.
- Check the variable status.

For each question, provide the following:
- Root cause explanation.
- Evidence supporting the diagnosis.
- Specific code fixes.
- Test methods.
- Prevention recommendations.

Focus on fixing the root cause rather than just the symptoms.

Data Scientist

---
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 analytics.

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

Key Practices:
- Write optimized SQL queries with appropriate filters.
- Use appropriate aggregations and joins.
- Include comments that explain complex logic.
- Format the results to improve readability.
- Provide data-driven recommendations.

For each analysis:
- Explain the query method.
- Document any assumptions.
- Highlight key findings.
- Recommend next steps based on the data.

Always ensure that queries are efficient and cost-effective.

Best Practices

Start with an AI-generated agent: We strongly recommend using AI to generate your initial subagent, then iterating on it to make it your own. This approach gives you the best result - a solid foundation that you can customize to meet your specific needs.
Design focused subagents: Create subagents with a single, clear responsibility instead of trying to make one subagent do everything. This improves performance and makes subagents more predictable.
Write detailed prompts: Include specific instructions, examples, and constraints in your system prompt. The more guidance you provide, the better your subagent will perform.
Limit tool access: Grant only the tools required for the subagent's purpose. This improves security and helps the subagent focus on relevant operations.
Version control: Check project subagents into version control so that your team can benefit from them and collaboratively improve them.

Advanced Usage

Link Subagent

For complex workflows, you can chain multiple subagents:
> First, use the code-analyzer subagent to identify performance issues, and then use the optimizer subagent to fix them.

Dynamic Subagent Selection

CodeBuddy Code intelligently selects subagents based on context. Make your description field specific and action-oriented to achieve the best results.

Recoverable Subagent

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

How It Works:

Each subagent execution is assigned a unique agentId.
Agent conversations are stored in separate record files: agent-{agentId}.jsonl
You can resume a previous agent by providing its agentId through the resume parameter.
Upon restoration, the agent continues to use the full context of its previous conversation.

Example Workflow:

Initial invocation
> Start reviewing the authentication module using the code-analyzer agent.

[The agent completes the initial analysis and returns agentId: "abc123"]
Resume agent
> Resume agent abc123 and continue analyzing the authorization logic.

[The agent continues to use the full context of the previous conversation.]
Use Cases:
Long-running research: Break down large codebase analysis into multiple sessions.
Iterative refinement: Continue refining the subagent's work without losing context.
Multi-step workflow: Enable subagents to process related tasks sequentially while maintaining context.
Technical details:
The subagent's conversation history and tool results are stored in the subagents/ subdirectory of the parent session.
Disable logging during recovery to avoid duplicate messages.
Both synchronous agents and [background agents](#background-agents) can be resumed.
The resume parameter accepts an agent ID from a previous execution.
Runtime data storage directory:
~/.codebuddy/projects/{projectDir}/
└── {parentSessionId}/
├── tool-results/ ← Tool output files for the main session
└── subagents/ ← Subagent data
├── agent-{agentId}.jsonl ← Subagent conversation history
└── agent-{agentId}/
└── tool-results/ ← Tool output files for the subagent
└── {callId}.txt
Note:
When tool output is too large, the complete output is saved to a file in the tool-results/ directory. The model receives the truncated content and a file path pointer, and can read the full content on demand. For details, see Environment Variables Reference.
Programmatic Usage:
If you use the Agent SDK or interact with AgentTool directly, you can pass the resume parameter:
{
"description": "Continue analysis",
"prompt": "Now check the error handling pattern",
"subagent_type": "code-analyzer",
"resume": "abc123" // Agent ID from a previous execution
}
Track the agent ID of a task that you may want to resume later. CodeBuddy Code displays the agent ID when a subagent completes its work.

Background Agent

Background agents allow you to run subagent tasks in the background without blocking the main conversation. This is especially useful for long-running tasks, as you can continue interacting with CodeBuddy Code while the task executes in the background.
How it works:
Start a background agent with the run_in_background: true parameter.
The task returns a task ID immediately without blocking the main conversation.
Background agents run in detached mode, so intermediate messages do not interfere with the main conversation.
Use the TaskOutput tool to get the status and results of background tasks.
Start a background agent:
> Run the code-analyzer agent in the background to review the entire codebase.

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

**Get background task output:**

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

Check the status of background task task-abc123.
Task ID: task-abc123
Status: running
Duration: 2m 30s
Prompt: Review code quality issues across the entire codebase.
Response: (The task is still running)
**Background task status:**

| Status | Description |
| :--- | :--- |
| `pending` | The task has been created and is waiting to be executed. |
| `running` | The task is running. |
| `completed` | The task has been completed successfully. |
| `failed` | The task failed to execute. |
| `cancelled` | The task was cancelled by the user. |
| `killed` | The task was forcibly terminated. |

**Programmatic Usage:**

If you use the Agent SDK or interact with the Agent tool directly, you can pass the `run_in_background` parameter:

```typescript
{
"description": "Analyze the codebase",
"prompt": "Review all TypeScript files for potential issues",
"subagent_type": "code-analyzer",
"run_in_background": true // Run in the background
}
Parameters for obtaining output: The TaskOutput tool supports the following parameters.
Parameter
Type
Description
task_id
string
Required. ID of the background task.
block
boolean
Whether to wait for task completion. Defaults to true.
timeout
number
Timeout to wait in milliseconds. Defaults to 30000ms, with a maximum of 600000ms.
Use Cases:
Parallel Analysis: Run multiple code analysis tasks simultaneously without blocking the main conversation.
Long-Running Tasks: Perform time-consuming codebase scanning or refactoring analysis.
Batch Processing: Process a large number of files in the background or perform complex multi-step tasks.
Non-blocking workflow: Continue other work while waiting for background tasks to complete.
Permission Handling:
Permissions are automatically handled by tool calls made by background agents during execution, requiring no user interaction. This ensures that background tasks can run smoothly without being blocked by waiting for user input.
Note:
Background agents are suitable for tasks that do not require frequent user interaction. If a task requires multiple user confirmations or inputs, use foreground mode.

Performance Considerations

Context Efficiency: Agents help preserve the main context, enabling longer overall conversations.
Latency: Subagents start from a clean state on each invocation and may add latency as they gather the context needed to complete their work effectively.

References

Plugins - Extend CodeBuddy Code with custom agents through plugins.
Slash Commands - Learn about other built-in commands.
Settings configuration - Configure CodeBuddy Code behavior.
Hooks - Automate workflows with event handlers.


Help and Support

Was this page helpful?

Help us improve! Rate your documentation experience in 5 mins.

Feedback