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.
Task Tool (task)
The task tool enables delegation of complex, multi-step tasks to specialized subagents that work autonomously with their own tool access.
Overview
Tool Name: task
Display Name: Task
Kind: Other
Description: Launches specialized subagents to handle complex tasks autonomously. Supports parallel execution and real-time progress updates.
Parameters
interface TaskParams {
description: string; // Required: Short (3-5 word) description
prompt: string; // Required: Detailed task instructions
subagent_type: string; // Required: Type of subagent to use
}
Usage
Basic Task Delegation
task({
description: 'Code review',
prompt: 'Review the authentication module for security issues and best practices',
subagent_type: 'code-reviewer',
});
Detailed Instructions
task({
description: 'Refactor module',
prompt: `Refactor the user management module:
1. Convert callbacks to async/await
2. Add proper error handling
3. Update tests
4. Update documentation`,
subagent_type: 'general-purpose',
});
Multiple Parallel Tasks
// Launch multiple subagents concurrently
task({
description: 'Code review',
prompt: 'Review recent changes for code quality',
subagent_type: 'code-reviewer',
});
task({
description: 'Run tests',
prompt: 'Execute test suite and analyze failures',
subagent_type: 'test-runner',
});
task({
description: 'Update docs',
prompt: 'Generate API documentation for new endpoints',
subagent_type: 'documentation-writer',
});
Available Subagents
Subagents are configured in your project or user settings. Common types:
Built-in Subagents
General Purpose
name: general-purpose
description: Handles complex multi-step tasks with full tool access
tools: [all tools]
Use for:
- Complex refactoring
- Feature implementation
- Multi-file changes
- General development tasks
Code Search
name: code-search
description: Find code patterns and definitions across the codebase
tools:
- read_file
- grep_search
- glob
- list_directory
Use for:
- Finding function definitions
- Locating usage patterns
- Searching across multiple files
- Code exploration
Custom Subagents
Create your own subagents for specific needs. See Subagents System for details.
Viewing Available Subagents
In Qwen Code CLI:
This shows all available subagents with their descriptions and tool access.
Task Execution Flow
1. Initialization
User/Model
│
v
Task Tool
│
├─ Load subagent configuration
├─ Create SubAgentScope
├─ Initialize tool registry (subset)
└─ Set up event emitter
2. Execution
SubAgent
│
├─ Receive task prompt
│
├─ Process with model
│
├─ Execute tools (with confirmation if needed)
│
├─ Iterate until complete
│
└─ Return final result
3. Termination
Task Tool
│
├─ Receive final result
├─ Emit finish event
├─ Clean up resources
└─ Return to parent agent
Real-time Progress Updates
The task tool provides live updates:
Event Types
enum SubAgentEventType {
START = 'start', // Subagent started
ROUND = 'round', // New conversation round
TOOL_CALL = 'tool_call', // Tool being called
TOOL_RESULT = 'tool_result', // Tool result received
APPROVAL_REQUEST = 'approval_request', // User confirmation needed
FINISH = 'finish', // Task completed
ERROR = 'error', // Error occurred
USAGE = 'usage', // Token usage update
}
UI Display
Progress is shown in the CLI:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Subagent: code-reviewer ┃
┃ Status: Running ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┨
┃ ▶ read_file(src/auth.ts) ┃
┃ ✓ grep_search(pattern="function") ┃
┃ ▶ read_file(src/auth.test.ts) ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
Round 2/10 | Tokens: 1.2K/10K
Good Use Cases
✅ Complex multi-step tasks
task({
description: 'Feature implementation',
prompt: 'Implement user authentication with OAuth, including tests and docs',
subagent_type: 'general-purpose',
});
✅ Specialized expertise
task({
description: 'Security audit',
prompt: 'Audit the API endpoints for security vulnerabilities',
subagent_type: 'security-auditor',
});
✅ Parallel execution
// Launch 3 tasks simultaneously
task({ description: 'Task 1', prompt: '...', subagent_type: 'type1' });
task({ description: 'Task 2', prompt: '...', subagent_type: 'type2' });
task({ description: 'Task 3', prompt: '...', subagent_type: 'type3' });
✅ Autonomous workflows
task({
description: 'Fix failing tests',
prompt: 'Run test suite, identify failures, and fix them',
subagent_type: 'test-fixer',
});
When NOT to Use
❌ Simple file reads
// ❌ DON'T use task
task({
description: 'Read file',
prompt: 'Read src/index.ts',
subagent_type: 'code-search',
});
// ✅ DO use read_file directly
read_file({ absolute_path: '/path/to/src/index.ts' });
❌ Single-step operations
// ❌ DON'T use task
task({
description: 'List files',
prompt: 'List files in src/',
subagent_type: 'general-purpose',
});
// ✅ DO use list_directory
list_directory({ path: '/path/to/src' });
❌ Interactive tasks
- Tasks requiring back-and-forth communication
- Tasks needing user input during execution
- Exploratory tasks with unclear requirements
Subagent Configuration
Subagents need proper configuration to work effectively.
Configuration Structure
---
name: my-agent
description: What this agent does and when to use it
tools:
- read_file
- write_file
- grep_search
modelConfig:
model: qwen-coder-plus
temperature: 0.3
runConfig:
max_turns: 15
max_time_minutes: 10
---
# System Prompt
You are a specialized agent for [purpose].
Your responsibilities:
1. [Task 1]
2. [Task 2]
Guidelines:
- [Guideline 1]
- [Guideline 2]
Creating Subagents
See Subagents System for detailed instructions on:
- Creating custom subagents
- Configuring tool access
- Setting model parameters
- Defining system prompts
- Managing subagent lifecycle
Subagents only have access to tools specified in their configuration:
tools:
- read_file # ✅ Can read files
- grep_search # ✅ Can search code
- glob # ✅ Can find files
# write_file not listed ❌ Cannot write files
# edit not listed ❌ Cannot edit files
This provides isolation and security:
- Read-only agents: Only read/search tools
- Editor agents: Read + write/edit tools
- Full-access agents: All tools (use carefully)
Execution Limits
Subagents have configurable limits:
runConfig:
max_turns: 20 # Max conversation rounds
max_time_minutes: 30 # Max execution time
terminate_mode: graceful # Or 'immediate'
Reaching Limits
Max Turns:
Subagent terminated: Maximum turns (20) reached
Partial result: [what was completed]
Timeout:
Subagent terminated: Maximum time (30 minutes) exceeded
Partial result: [what was completed]
- Graceful: Allows subagent to summarize results
- Immediate: Stops immediately and returns current state
Result Handling
Subagents return a single final message:
interface SubagentResult {
result: string; // Final result message
success: boolean; // Whether task completed successfully
statistics: {
totalDurationMs: number;
rounds: number;
toolCalls: number;
tokens: number;
};
}
The parent agent receives this result and can:
- Use it directly in response
- Process it further
- Delegate to another subagent
- Present it to the user
Statistics and Monitoring
Task execution is tracked:
interface TaskStatistics {
totalDurationMs: number; // Total execution time
rounds: number; // Conversation rounds
totalToolCalls: number; // Tools called
successfulToolCalls: number; // Successful calls
failedToolCalls: number; // Failed calls
inputTokens: number; // Input tokens used
outputTokens: number; // Output tokens used
totalTokens: number; // Total tokens
estimatedCost: number; // Estimated cost
}
Statistics are logged (respecting privacy settings) for analytics and optimization.
Error Handling
Task Errors
try {
const result = await task({
description: 'Complex task',
prompt: 'Do something',
subagent_type: 'unknown-agent', // Error: not found
});
} catch (error) {
// Handle SubagentError
console.error(error.code); // 'NOT_FOUND'
console.error(error.message); // 'Subagent "unknown-agent" not found'
}
Execution Errors
If a subagent encounters an error:
Subagent error: [error message]
Partial work completed:
- [action 1]
- [action 2]
Suggested next steps:
- [suggestion 1]
- [suggestion 2]
Best Practices
1. Clear, Detailed Prompts
✅ Good:
task({
description: 'Refactor module',
prompt: `Refactor the authentication module:
1. Extract JWT logic into separate file
2. Add input validation
3. Update tests
4. Add JSDoc comments
Files to modify: src/auth/*.ts
Keep existing API unchanged.`,
subagent_type: 'general-purpose',
});
❌ Bad:
task({
description: 'Fix auth',
prompt: 'Fix the auth stuff',
subagent_type: 'general-purpose',
});
2. Choose Right Subagent
Match task to subagent capabilities:
// ✅ Specialized agent for specialized task
task({
description: 'Security review',
prompt: 'Review for SQL injection vulnerabilities',
subagent_type: 'security-auditor',
});
// ❌ General agent for specialized task
task({
description: 'Security review',
prompt: 'Review for SQL injection vulnerabilities',
subagent_type: 'general-purpose', // Less effective
});
3. Provide Context
Include relevant context in the prompt:
task({
description: 'Fix bug',
prompt: `Fix the bug in user login:
Symptom: Users can't log in with email addresses containing '+'
Location: src/auth/validator.ts
Error: "Invalid email format"
The email validation regex needs to accept '+' character.
Update tests after fixing.`,
subagent_type: 'general-purpose',
});
4. Set Appropriate Limits
Configure limits based on task complexity:
# Simple tasks
runConfig:
max_turns: 10
max_time_minutes: 5
# Complex tasks
runConfig:
max_turns: 30
max_time_minutes: 20
5. Monitor Progress
Watch the progress updates to ensure the subagent is on track:
- Check tool calls are relevant
- Verify approach makes sense
- Abort if going in wrong direction
Implementation
Location: packages/core/src/tools/task.ts
export class TaskTool extends BaseDeclarativeTool<TaskParams, ToolResult> {
static readonly Name = ToolNames.TASK;
private subagentManager: SubagentManager;
private availableSubagents: SubagentConfig[] = [];
constructor(private readonly config: Config) {
super(
TaskTool.Name,
ToolDisplayNames.TASK,
'Launches specialized subagents...',
Kind.Other,
{ /* schema */ },
true, // isOutputMarkdown
true, // canUpdateOutput
);
this.subagentManager = config.getSubagentManager();
this.subagentManager.addChangeListener(() => {
void this.refreshSubagents();
});
this.refreshSubagents();
}
async refreshSubagents(): Promise<void> {
this.availableSubagents = await this.subagentManager.listSubagents();
this.updateDescriptionAndSchema();
}
}
Next Steps