How coordinator agents intelligently route tasks to the right specialist agents based on capabilities, current load, and task requirements.
The TaskDelegator is the brain of multi-agent coordination. It analyzes incoming tasks, matches them to available agents, and routes work for optimal execution.
┌─────────────────────────────────────────────────────────────┐
│ INCOMING TASK │
│ "Analyze market and set optimal price" │
└─────────────────────────┬───────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ TASK DELEGATOR │
│ │
│ 1. Parse Task Requirements │
│ → Capabilities: [market_analysis, pricing] │
│ → Priority: high │
│ → Timeout: 30s │
│ │
│ 2. Query Agent Registry │
│ → Find agents with required capabilities │
│ → Check agent availability & load │
│ │
│ 3. Score & Select │
│ → Market Agent: 0.92 (best match) │
│ → Pricing Agent: 0.88 │
│ → General Agent: 0.45 (fallback) │
│ │
│ 4. Delegate │
│ → Route to Market Agent │
│ → Pass context & constraints │
└─────────────────────────────────────────────────────────────┘Match task requirements to agent capabilities. Each agent declares what it can do, and the delegator finds the best match.
// Agent capability declaration
const pricingAgent = {
id: "pricing-specialist-001",
capabilities: [
"pricing_optimization",
"competitor_analysis",
"discount_calculation",
"revenue_forecasting"
],
maxConcurrentTasks: 5,
averageResponseTime: 2000 // ms
}
// Task delegation based on capabilities
const delegation = await delegator.delegate({
task: "Calculate optimal price for beach property in July",
requiredCapabilities: ["pricing_optimization"],
preferredCapabilities: ["competitor_analysis"],
context: { propertyId, dates, marketData }
})Distribute tasks evenly across agents to prevent bottlenecks and ensure optimal response times.
// Load-balanced delegation
const delegation = await delegator.delegate({
task: "Process booking inquiry",
strategy: "load_balanced",
options: {
// Prefer agents with fewer active tasks
loadWeight: 0.4,
// Consider response time history
performanceWeight: 0.3,
// Match capabilities
capabilityWeight: 0.3,
// Maximum queue depth before rejection
maxQueueDepth: 10
}
})
// Delegator automatically selects least-loaded capable agentHigh-priority tasks get routed to the fastest, most capable agents, even if it means preempting lower-priority work.
// Priority-based delegation
const delegation = await delegator.delegate({
task: "Urgent: Guest locked out, needs immediate assistance",
priority: "critical",
options: {
// Can interrupt lower-priority tasks
allowPreemption: true,
// Skip load balancing, use fastest agent
fastTrack: true,
// Shorter timeout for critical tasks
timeout: 10000,
// Escalate to human if not handled in time
escalationThreshold: 15000
}
})Delegate to multiple specialists simultaneously when a task requires diverse expertise, then aggregate results.
// Parallel delegation to multiple specialists
const results = await delegator.fanOut({
task: "Prepare comprehensive property listing",
delegations: [
{
agentType: "content_writer",
subtask: "Write compelling property description"
},
{
agentType: "pricing_analyst",
subtask: "Research competitive pricing"
},
{
agentType: "photographer_assistant",
subtask: "Select and enhance best photos"
},
{
agentType: "seo_specialist",
subtask: "Optimize for search visibility"
}
],
aggregation: "merge", // combine all results
timeout: 60000
})
// All specialists work simultaneously
// Results aggregated into unified listingThe delegator scores each candidate agent to find the optimal match:
function scoreAgent(agent, task, options) {
const weights = options.weights || {
capability: 0.35, // How well capabilities match
performance: 0.25, // Historical success rate
load: 0.20, // Current task queue depth
latency: 0.15, // Average response time
cost: 0.05 // Token/API cost efficiency
}
// Capability score: % of required capabilities met
const capabilityScore = calculateCapabilityMatch(
agent.capabilities,
task.requiredCapabilities,
task.preferredCapabilities
)
// Performance score: success rate over last 100 tasks
const performanceScore = agent.metrics.successRate
// Load score: inverse of queue depth (less load = higher score)
const loadScore = 1 - (agent.currentTasks / agent.maxConcurrentTasks)
// Latency score: normalized against SLA
const latencyScore = Math.min(1, task.sla / agent.avgResponseTime)
// Cost score: normalized token efficiency
const costScore = 1 - (agent.avgTokenCost / maxTokenBudget)
// Weighted sum
return (
weights.capability * capabilityScore +
weights.performance * performanceScore +
weights.load * loadScore +
weights.latency * latencyScore +
weights.cost * costScore
)
}Agent selection typically completes in <50ms, even with 100+ registered agents. The registry maintains an optimized index for capability lookups.
The delegator has multiple fallback strategies when the primary agent is unavailable or fails:
// Robust delegation with fallbacks
const result = await delegator.delegateWithFallback({
task: "Process urgent maintenance request",
priority: "high",
fallbackChain: [
{ strategy: "capability_match", timeout: 5000 },
{ strategy: "general_agent", timeout: 10000 },
{ strategy: "coordinator_direct", timeout: 15000 },
{ strategy: "human_escalation", timeout: 0 } // No timeout, wait for human
],
onFallback: (fromAgent, toAgent, reason) => {
logger.warn(`Delegation fallback: ${fromAgent} -> ${toAgent}: ${reason}`)
metrics.increment("delegation.fallbacks")
}
})Use specific, granular capability names rather than broad categories
Base timeouts on actual agent performance metrics, not guesses
Track which agents get tasks and identify bottlenecks early
If everything is high priority, nothing is. Reserve for true urgency
Regularly verify fallback chains work as expected