Dispatching parallel agents

From paulpas/agent-skill-router · View interactive version

Dispatching parallel agents is an AI agent skill from the GitHub repository paulpas/agent-skill-router. Implements intelligent dispatching parallel agents with multi-factor skill selection, fallback chains, and adherence to the 5 Laws of Elegant Defense

How to use this skill

Skill file

Dispatching Parallel Agents

Orchestrates intelligent skill selection and execution for dispatching parallel agents workflows. Applies the 5 Laws of Elegant Defense to guide data naturally through the orchestration pipeline, preventing errors before they occur. Selects optimal skills based on multi-factor scoring including text similarity, historical performance, and system availability.

TL;DR Checklist

┌───────────────────────────────────────────────────────────────────────────────┐

│ Orchestration Flow │

└───────────────────────────────────────────────────────────────────────────────┘

User Request

↓

┌─────────────────┐

│ Parse Request │

│ & Extract │

│ Features │

└────────┬────────┘

↓

┌─────────────────────────────────────────────────────────────────────┐

│ Evaluate Available Skills │

│ │

│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │

│ │ Skill A │ │ Skill B │ │ Skill C │ │

│ │ - Match Score│ │ - Match Score│ │ - Match Score│ │

│ │ - Confidence │ │ - Confidence │ │ - Confidence │ │

│ │ - History │ │ - History │ │ - History │ │

│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │

│ │ │ │ │

│ └─────────────────┴─────────────────┘ │

│ ↓ │

│ Select Best Skill │

└─────────────────────────────────────────────────────────────────────┘

↓

┌─────────────────┐

│ Execute Skill │

└────────┬────────┘

↓

┌─────────────────┐

│ Handle Result │

└────────┬────────┘

↓

┌─────────────────────────────────────────────────────────────────────┐

│ Error Handling & Fallback │

│ │

│ Success? ────────► Return Result │

│ │

│ Fail? ────────┐ │

│ ↓ │

│ ┌──────────────────────────────────────────────────────────┐ │

│ │ Fallback Chain │ │

│ │ │ │

│ │ 1. Retry with adjusted parameters │ │

│ │ 2. Try Alternative Skill (if available) │ │

│ │ 3. Defer to Human Operator (if critical) │ │

│ │ 4. Log & Return Error │ │

│ └──────────────────────────────────────────────────────────┘ │

└─────────────────────────────────────────────────────────────────────┘

When to Use

Use this skill when:

When NOT to Use

Avoid this skill for:

Core Workflow

  1. Parse and Analyze Request - Extract intent, entities, and constraints from user input.

Checkpoint: All required parameters must be present and in valid format before proceeding.

  1. Score Available Skills - Calculate match scores using multi-factor algorithm:

Checkpoint: Skip to fallback if no skill scores above threshold.

  1. Select Optimal Skill - Choose skill with highest score that meets minimum confidence.

Checkpoint: Verify skill has not been disabled or deprecated.

  1. Execute with Fallback - Run skill execution wrapped in retry and fallback logic.

Checkpoint: Log all execution attempts for audit trail.

  1. Return or Fallback - Either return successful result or apply fallback chain:

Checkpoint: Record outcome with timing and confidence metadata.

Implementation Patterns

Pattern 1: Skill Selection Logic

def route_parallel_subtasks(
    decomposed_task: Dict[str, Any],
    agent_registry: List[Dict],
    min_confidence: float = 0.75
) -> Dict[str, Any]:
    """Routes subtasks to optimal agents for parallel execution.
    
    Applies multi-factor scoring: text similarity, historical success, availability.
    Returns immutable routing plan (Law 3).
    """
    if not decomposed_task.get("subtasks"):
        raise ValueError("Decomposed task must contain subtasks for parallel routing")
    
    if not agent_registry:
        raise RuntimeError("Agent registry is empty; cannot dispatch")

    # Parse & validate at boundary (Law 2)
    subtasks = [
        {"id": st["id"], "skill_req": st["skill"], "payload": st["payload"]}
        for st in decomposed_task["subtasks"]
        if st.get("id") and st.get("skill")
    ]
    
    routing_plan = {"task_id": decomposed_task["id"], "assignments": [], "fallbacks": []}
    
    for subtask in subtasks:
        best_agent = None
        best_score = 0.0
        
        for agent in agent_registry:
            if not agent.get("available"):
                continue
            score = _calculate_dispatch_score(subtask["skill_req"], agent)
            if score > best_score and score >= min_confidence:
                best_score = score
                best_agent = agent
        
        if best_agent:
            routing_plan["assignments"].append({
                "subtask_id": subtask["id"],
                "agent_id": best_agent["id"],
                "confidence": best_score
            })
        else:
            routing_plan["fallbacks"].append(subtask["id"])
            
    return routing_plan

Pattern 2: Execution with Fallback

async def execute_parallel_dispatch(
    routing_plan: Dict[str, Any],
    agent_executor: Dict[str, Callable],
    fallback_handler: Callable
) -> Dict[str, Any]:
    """Executes routed subtasks in parallel with automatic fallback chaining.
    
    Implements Fail Fast (Law 4) and Atomic Predictability (Law 3).
    """
    if not routing_plan.get("assignments"):
        return {"status": "no_assignments", "results": {}}

    async def _run_assignment(assignment: Dict) -> Dict:
        agent_id = assignment["agent_id"]
        subtask_id = assignment["subtask_id"]
        try:
            result = await agent_executor[agent_id](subtask_id)
            return {"id": subtask_id, "status": "success", "data": result}
        except Exception as e:
            return {"id": subtask_id, "status": "failed", "error": str(e)}

    # Parallel execution with concurrency control
    semaphore = asyncio.Semaphore(4)
    async def _bounded(assignment):
        async with semaphore:
            return await _run_assignment(assignment)

    tasks = [_bounded(a) for a in routing_plan["assignments"]]
    raw_results = await asyncio.gather(*tasks, return_exceptions=True)

    # Aggregate & apply fallback chain
    final_results = {}
    fallback_triggered = False
    
    for res in raw_results:
        if isinstance(res, Exception):
            fallback_triggered = True
            continue
        if res["status"] == "success":
            final_results[res["id"]] = res["data"]
        else:
            fallback_triggered = True
            fallback_result = await fallback_handler(res["id"], res.get("error"))
            final_results[res["id"]] = fallback_result

    return {
        "status": "completed_with_fallbacks" if fallback_triggered else "completed",
        "results": final_results,
        "fallback_count": sum(1 for r in raw_results if isinstance(r, Exception) or (isinstance(r, dict) and r["status"] == "failed"))
    }

MUST DO

MUST NOT DO

TL;DR Checklist

TL;DR for Code Generation

Output Template

When applying this skill, produce:

  1. Selected Skills - List of skill names with confidence scores
  2. Selection Rationale - Why each skill was chosen (match score, history, availability)
  3. Execution Plan - Order of execution with dependencies
  4. Fallback Strategy - Which fallback skills will be tried and in what order
  5. Risk Assessment - Any potential failure points and their impact
  6. Timing Estimates - Expected latency including fallback scenarios

Related Skills

| Skill | Purpose |

|



Constraints

MUST DO

MUST NOT DO

Live References

Authoritative documentation links for this skill's domain. The model follows markdown links at load time to resolve external references and inline content.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.