Single agents hit limits. They can only do one thing at a time. They get bogged down in complex tasks. Their context windows fill up with irrelevant information. When you need real power, you need multiple agents working together.
Subagents are OpenClaw's solution. They are background agent runs spawned from a parent agent, operating in isolated sessions with their own workspaces. Think of them as specialized workers that your main agent (the orchestrator) can hire, assign tasks to, and collect results from. This guide shows you how to use them effectively.
What Are Subagents?
Subagents are ephemeral agent instances created on demand using the sessions_spawn tool. Unlike your main agent, which persists and handles ongoing conversations, subagents exist for specific tasks and clean up automatically when done.
Key Characteristics
- Isolation: Each subagent has its own workspace, state directory, and tool access. What happens in one subagent stays there unless explicitly shared
- Inheritance: Subagents can inherit model settings, thinking preferences, and context from their parent agent, or override them as needed
- Non-blocking: Spawning a subagent returns immediately with a runId. The parent agent continues working while the subagent processes its task
- Auto-archival: Subagents automatically archive after a timeout (default 60 minutes), preserving results while freeing resources
- Nested capability: Subagents can spawn their own subagents, up to a depth of two levels
When to Use Subagents
Subagents shine in specific scenarios:
- Parallel processing: Run multiple independent tasks simultaneously instead of sequentially
- Specialization: Assign different agent types to different tasks (researcher, writer, coder, reviewer)
- Cognitive load distribution: Break complex problems into smaller pieces that fit in context windows
- Sandboxing: Isolate risky operations (like executing untrusted code) from your main agent
- Cost optimization: Use cheaper models for simple subtasks while reserving expensive models for complex reasoning
Creating Your First Subagent
The sessions_spawn tool creates subagents. Here is the basic pattern:
// Spawn a subagent with a specific task
const runId = await sessions_spawn({
task: "Research the latest OpenClaw updates and summarize key features",
model: "claude-sonnet-4-6", // Optional: override parent model
thinking: "low", // Optional: thinking level
timeout: 300 // Optional: timeout in seconds
});This spawns an isolated agent that executes the task independently. The parent agent receives a runId immediately and can continue with other work.
Basic Example: Simple Delegation
Here is a complete example of delegating a research task to a subagent:
// Orchestrator agent
async function handleUserRequest(userQuery) {
// Spawn a researcher subagent
const researchRunId = await sessions_spawn({
task: `Research this topic thoroughly: ${userQuery}`,
model: "claude-sonnet-4-6",
thinking: "medium"
});
// Continue with other work (or wait for results)
await doOtherWork();
// Collect results when ready
const results = await sessions_history({
sessionKey: researchRunId,
limit: 50
});
// Use the research to generate response
return generateResponse(results);
}Subagent Communication Patterns
Subagents need to communicate results back to their parent. OpenClaw provides several mechanisms for this.
Pattern 1: Direct Session History
The simplest approach: read the subagent's message history when it completes.
// Wait for subagent completion and read results
const history = await sessions_history({
sessionKey: subagentRunId,
includeTools: true,
limit: 100
});
// Extract the final result from the history
const finalResult = history.messages[history.messages.length - 1].content;This pattern works well for simple tasks with clear outputs. The parent agent polls or waits for the subagent to finish, then extracts results from its session history.
Pattern 2: Shared Workspace Files
For complex workflows, subagents can write results to shared files:
// Subagent writes results to a file
await fs.writeFile('/workspace/results/research.json', JSON.stringify({
topic: userQuery,
findings: researchResults,
sources: sourceList,
confidence: confidenceScore
}));
// Parent agent reads the file later
const results = JSON.parse(
await fs.readFile('/workspace/results/research.json', 'utf8')
);This pattern excels when multiple subagents contribute to shared outputs or when results need to persist beyond the subagent's lifetime.
Pattern 3: Message Passing
For real-time coordination, use sessions_send for direct agent-to-agent messaging:
// Send a message to another agent's session
await sessions_send({
sessionKey: targetAgentRunId,
message: "Research complete. Starting phase 2.",
timeoutSeconds: 30
});Note: Direct messaging must be explicitly enabled in configuration. For most workflows, routing through the orchestrator is preferred for easier auditing and debugging.
Multi-Subagent Orchestration
The real power emerges when orchestrating multiple subagents together. Here are proven patterns.
Pattern 1: Parallel Map
Spawn multiple subagents simultaneously to process independent tasks:
// Process 10 articles in parallel
const articles = await fetchArticleList();
const runIds = await Promise.all(
articles.map(article =>
sessions_spawn({
task: `Summarize this article: ${article.url}`,
model: "claude-haiku-4-6" // Cheap model for simple task
})
)
);
// Wait for all to complete and collect results
const summaries = await Promise.all(
runIds.map(id => sessions_history({ sessionKey: id, limit: 20 }))
);This pattern reduces total processing time from the sum of individual tasks to the duration of the slowest task.
Pattern 2: Sequential Pipeline
Chain subagents where each step's output feeds into the next:
// Research -> Write -> Edit pipeline
const researchRunId = await sessions_spawn({
task: "Research: benefits of multi-agent systems",
model: "claude-sonnet-4-6"
});
const research = await waitForCompletion(researchRunId);
const writingRunId = await sessions_spawn({
task: `Write article based on this research: ${research}`,
model: "claude-opus-4-6"
});
const draft = await waitForCompletion(writingRunId);
const editingRunId = await sessions_spawn({
task: `Edit this article for clarity: ${draft}`,
model: "claude-sonnet-4-6"
});This pattern ensures quality at each stage before proceeding. Use it when steps have clear dependencies and quality gates.
Pattern 3: Hub and Spoke
A central orchestrator delegates to specialized subagents based on task type:
// Orchestrator analyzes request and routes appropriately
async function routeTask(userRequest) {
const intent = await classifyIntent(userRequest);
switch(intent) {
case 'code':
return sessions_spawn({
task: userRequest,
model: "claude-opus-4-6",
context: "You are an expert programmer."
});
case 'research':
return sessions_spawn({
task: userRequest,
model: "claude-sonnet-4-6",
context: "You are a thorough researcher."
});
case 'creative':
return sessions_spawn({
task: userRequest,
model: "gpt-4",
context: "You are a creative writer."
});
}
}This pattern matches task types to optimal agent configurations. It is the most common production pattern for multi-agent systems.
Nested Subagents
For complex workflows, subagents can spawn their own subagents. This enables hierarchical task decomposition.
Example: Hierarchical Research
A meta-researcher subagent can delegate to specialized researcher sub-subagents:
// Level 1: Meta-researcher (subagent of orchestrator)
async function metaResearch(topic) {
// Break topic into sub-topics
const subTopics = await analyzeTopic(topic);
// Spawn specialist researchers (level 2 subagents)
const researchRuns = await Promise.all(
subTopics.map(st =>
sessions_spawn({
task: `Deep research on: ${st}`,
model: "claude-sonnet-4-6",
timeout: 600
})
)
);
// Synthesize results
const findings = await Promise.all(
researchRuns.map(r => sessions_history({ sessionKey: r }))
);
return synthesizeReport(findings);
}This pattern scales to arbitrary complexity while keeping each agent's context focused and manageable.
Error Handling and Recovery
Subagents can fail. Your orchestration must handle this gracefully.
Pattern: Retry with Fallback
async function resilientSpawn(task, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
const runId = await sessions_spawn({
task: task,
model: i === 0 ? "claude-sonnet-4-6" : "claude-opus-4-6"
// Escalate model on retry
});
try {
const result = await waitWithTimeout(runId, 300);
if (result.success) return result;
} catch (error) {
if (i === maxRetries - 1) throw error;
// Log and retry
}
}
}This pattern retries failed subagents with stronger models, maximizing success rates while minimizing costs.
Cost Optimization Strategies
Subagents enable sophisticated cost management.
Strategy 1: Tiered Model Selection
Use cheaper models for simple subtasks:
- Haiku/GPT-3.5: Summarization, formatting, simple extraction
- Sonnet/GPT-4: Research, analysis, moderate complexity
- Opus/GPT-4 Turbo: Complex reasoning, coding, final quality review
Strategy 2: Parallelization Savings
Parallel subagents reduce wall-clock time, which can reduce total costs in time-billed environments. They also prevent context window overflow that would require restarting expensive conversations.
Strategy 3: Early Termination
Monitor subagent progress and terminate early if quality thresholds are not met:
// Check intermediate results and abort if needed
const intermediate = await sessions_history({
sessionKey: runId,
limit: 10
});
if (detectLowQuality(intermediate)) {
await process_kill({ sessionId: runId });
return fallbackApproach();
}Best Practices
Lessons learned from production multi-agent systems:
Keep Subagents Focused
Give each subagent a single, well-defined task. Vague instructions produce vague results. Specific tasks produce specific outputs.
Limit Concurrency
Set maxConcurrentRuns to prevent overwhelming APIs or your own infrastructure. Start with 3-5 parallel subagents and increase based on performance.
Version Your Workflows
Store workflow definitions in version control. Subagent orchestration is code. Treat it with the same rigor as any other codebase.
Monitor and Log
Log all subagent spawns, completions, and failures. Track which subagents produce the best results. This data guides future optimization.
Test in Isolation
Test subagent tasks independently before integrating them into complex workflows. A broken subagent breaks the entire pipeline.
FAQ
What exactly is a subagent in OpenClaw?
A subagent is a background agent run spawned from an existing agent (the orchestrator). It operates in an isolated session with its own workspace and can inherit or override settings from its parent agent. Subagents enable parallel task execution and distributed cognition.
How do subagents differ from regular agents?
Regular agents are persistent and bound to communication channels. Subagents are ephemeral, spawned on demand for specific tasks, and auto-archive after completion or timeout. They share the parent agent's context but have isolated workspaces.
Can subagents spawn other subagents?
Yes, OpenClaw supports nested subagents up to a depth of two. An orchestrator can spawn subagents, and those subagents can spawn worker sub-subagents. This enables hierarchical task decomposition and complex workflow patterns.
How long do subagents live?
Subagents auto-archive after a configurable timeout period (default 60 minutes). You can adjust this based on your workflow needs. Archived subagents preserve their results but no longer consume active resources.
Are subagents secure?
Yes. Each subagent has its own isolated workspace, state directory, and authentication scope. Tasks cannot collide, and credentials remain scoped to the correct job. This isolation is a core security feature of the subagent system.
Common Pitfalls
Avoid these mistakes:
Over-Subagenting
Not every task needs a subagent. Simple operations that fit easily in your main agent's context are faster and cheaper without spawning. Use subagents for parallelization, specialization, or sandboxing.
Context Loss
Subagents do not automatically inherit all parent context. Pass essential context explicitly in the task description or shared files.
Premature Optimization
Do not optimize subagent models or parallelization until you have baseline metrics. Measure first, then optimize.
Ignoring Timeouts
Always set reasonable timeouts. A hung subagent wastes resources and blocks your workflow. Default to 5-10 minutes for most tasks.
Next Steps
Start simple. Create one subagent for a single task. Get comfortable with spawning, monitoring, and collecting results. Then gradually increase complexity.
When you are ready, explore our multi-agent systems guide for orchestration patterns, communication strategies, and production deployment advice. Combine subagents with skills, model routing, and memory management for truly powerful AI systems.
Need help from people who already use this stuff?
Need help with subagents?
Join My AI Agent Profit Lab for practical help, faster answers, and real-world multi-agent examples from the community.