# Multi-Agent Orchestrator

**Auto-invoke:** When user requests complex tasks requiring multiple specialized agents, workflow composition, or agent coordination.

**Description:**
Multi-agent orchestration system inspired by Agno's A2A (Agent-to-Agent) communication. Enables workflow composition, specialist delegation, and shared "culture" memory across agents.

## Core Capabilities

### 1. Agent Registry
- Maintain catalog of available agents
- Track agent capabilities and specializations
- Register/unregister agents dynamically
- Agent discovery by capability

### 2. Workflow Composition
- Chain multiple agents sequentially
- Execute agents in parallel
- Route tasks to appropriate specialists
- Merge results from multiple agents

### 3. A2A Communication
- Agent-to-Agent messaging
- Shared context/memory
- Result passing between agents
- Coordination protocols

### 4. Culture Memory
- Long-term shared knowledge
- Learned patterns and solutions
- Cross-agent context
- Persistent experience

## Available Agents

### Core Agents
```yaml
plan-executor:
  type: workflow
  capabilities: [planning, approval, execution, validation]
  triggers: [complex_feature, multi_file_change, refactoring]

codebase-indexer:
  type: skill
  capabilities: [semantic_search, navigation, indexing]
  triggers: [find_file, codebase_question, search]

mcp-client:
  type: integration
  capabilities: [external_tools, api_integration]
  triggers: [api_call, external_service, database_query]

document-generator:
  type: specialist
  capabilities: [documentation, markdown, pdf_export]
  triggers: [create_docs, generate_readme]

self-learner:
  type: meta
  capabilities: [optimization, learning, pattern_detection]
  triggers: [performance_tune, analyze_patterns]

coder-agent:
  type: implementation
  capabilities: [coding, refactoring, debugging]
  triggers: [write_code, fix_bug, optimize]

tester:
  type: validation
  capabilities: [testing, test_generation, validation]
  triggers: [write_tests, run_tests, test_coverage]

reviewer:
  type: quality
  capabilities: [review, security_analysis, best_practices]
  triggers: [review_code, security_check]
```

## Workflow Patterns

### Pattern 1: Sequential Chain
```yaml
workflow: "feature-implementation"
steps:
  - agent: plan-executor
    action: create_plan
  - agent: coder-agent
    action: implement
  - agent: tester
    action: test
  - agent: reviewer
    action: review
```

### Pattern 2: Parallel Execution
```yaml
workflow: "comprehensive-analysis"
parallel:
  - agent: codebase-indexer
    action: analyze_structure
  - agent: reviewer
    action: security_audit
  - agent: tester
    action: coverage_report
merge: combine_results
```

### Pattern 3: Routing
```yaml
workflow: "task-router"
condition: task_type
routes:
  coding: coder-agent
  documentation: document-generator
  analysis: codebase-indexer
  testing: tester
```

### Pattern 4: Loop
```yaml
workflow: "iterative-improvement"
loop:
  - agent: coder-agent
    action: implement
  - agent: tester
    action: test
  - agent: self-learner
    action: suggest_improvements
until: tests_pass AND quality_threshold_met
```

## Orchestration Commands

```bash
# Delegate to specialist
/delegate <agent-name> <task>

# Run workflow
/workflow <workflow-name>

# List agents
/agents list

# Show agent details
/agents info <agent-name>

# Compose workflow
/workflow create <name> <steps>
```

## Example Interactions

### Example 1: Feature Implementation (Sequential)
```
User: "Add user authentication"

[Orchestrator analyzes task]
Type: feature_implementation
Complexity: high
Agents needed: plan-executor, coder-agent, tester, reviewer

[Step 1] Delegate to plan-executor
→ Plan created: 5 steps
→ User approval obtained

[Step 2] Delegate to coder-agent
→ Implementation complete: 4 files created

[Step 3] Delegate to tester
→ Tests written: 15 test cases
→ All tests passing ✓

[Step 4] Delegate to reviewer
→ Review complete: 3 suggestions
→ All quality checks passed ✓

[Result] Feature implemented and validated
```

### Example 2: Parallel Analysis
```
User: "Analyze this codebase comprehensively"

[Orchestrator routes to multiple agents]
Parallel execution:

[→ codebase-indexer]: Scanning structure...
   Found 237 files, 45k lines of code
   
[→ reviewer]: Security audit...
   3 vulnerabilities found
   
[→ tester]: Coverage analysis...
   67% coverage, 12 files untested

[Merge results]
Comprehensive analysis ready:
- Architecture: MVC pattern detected
- Security: 3 issues (medium severity)
- Testing: 67% coverage
- Technical debt: Medium

Recommendations:
1. Fix security issues
2. Increase test coverage
3. Refactor large modules
```

### Example 3: Dynamic Routing
```
User: "Help me with X"

[Orchestrator classifies request]
Task type: documentation
Route: document-generator

[→ document-generator]: Creating docs...
Documentation generated: README.md
```

## Agent Communication

### Message Format
```json
{
  "from": "orchestrator",
  "to": "coder-agent",
  "type": "task",
  "task": "implement authentication",
  "context": {
    "plan_id": "123",
    "previous_results": []
  }
}
```

### Shared Memory
```yaml
culture_memory:
  patterns:
    - name: "auth_pattern"
      learned_by: reviewer
      usage: "JWT-based auth is preferred"
      
  lessons:
    - topic: "testing"
      lesson: "Always test edge cases"
      source: "tester"
      
  solutions:
    - problem: "slow_queries"
      solution: "add database indexes"
      verified: true
```

## Workflow DSL

```yaml
# Define workflows in YAML
name: "full-features"
description: "Complete feature development workflow"

triggers:
  - "implement.*feature"
  - "add.*functionality"

steps:
  - name: plan
    agent: plan-executor
    action: create_implementation_plan
    outputs: [plan_file]
    
  - name: implement
    agent: coder-agent
    action: execute_plan
    inputs: [plan_file]
    outputs: [code_files]
    
  - name: test
    agent: tester
    action: generate_and_run_tests
    inputs: [code_files]
    condition: tests_must_pass
    
  - name: review
    agent: reviewer
    action: review_and_validate
    inputs: [code_files, test_results]
    
  - name: document
    agent: document-generator
    action: create_documentation
    inputs: [code_files, plan_file]
```

## Coordination Strategies

### Strategy 1: Centralized Orchestrator
```
Orchestrator → Agent 1 → Orchestrator → Agent 2 → Orchestrator
```
**Pros:** Full control, easy monitoring
**Cons:** Bottleneck potential

### Strategy 2: Peer-to-Peer
```
Agent 1 → Agent 2 → Agent 3
```
**Pros:** Faster, decentralized
**Cons:** Harder to coordinate

### Strategy 3: Hybrid
```
Orchestrator → [Agent 1 || Agent 2] → Orchestrator → Agent 3
```
**Pros:** Best of both
**Cons:** More complex

## Error Handling

### Agent Failure
```yaml
on_agent_failure:
  - log_error
  - retry: 3
  - fallback_agent: alternate_agent
  - notify_user: true
```

### Workflow Failure
```yaml
on_workflow_failure:
  - save_state
  - offer_resume
  - suggest_fixes
  - partial_results: true
```

### Timeout Handling
```yaml
timeouts:
  agent: 300  # 5 minutes per agent
  workflow: 1800  # 30 minutes total
  on_timeout:
    - graceful_shutdown
    - save_progress
    - resume_option
```

## Performance Optimization

### Parallel Execution
```python
# Execute independent agents in parallel
async def parallel_workflow():
    results = await asyncio.gather(
        agent1.execute(),
        agent2.execute(),
        agent3.execute()
    )
    return merge_results(results)
```

### Caching
```yaml
cache:
  agent_results: true
  ttl: 3600  # 1 hour
  invalidation: file_change
```

### Resource Management
```yaml
limits:
  max_parallel_agents: 5
  max_concurrent_workflows: 3
  memory_per_agent: 100MB
```

## Monitoring

### Metrics
```yaml
metrics:
  - agent_execution_time
  - workflow_completion_rate
  - agent_success_rate
  - parallel_efficiency
```

### Logging
```yaml
logging:
  workflow_start: true
  agent_delegate: true
  agent_complete: true
  workflow_end: true
  errors: detailed
```

### Observability
```yaml
dashboard:
  - active_workflows
  - agent_pool_status
  - recent_results
  - performance_metrics
```

## Best Practices

1. **Clear Responsibilities**: Each agent has one clear purpose
2. **Loose Coupling**: Agents communicate via messages, not direct calls
3. **Fail Gracefully**: Always have fallback strategies
4. **Monitor Everything**: Track all agent interactions
5. **Share Knowledge**: Use culture memory for learned patterns

---

**Remember:** Your job is to conduct the symphony of agents, ensuring each specialist performs at the right time and their contributions harmonize into the final result.
