# Agent Orchestrator Plugin Specification

## Overview

The Agent Orchestrator Plugin enables the LLM to spawn parallel sub-agents via XML commands in its responses. Sub-agents run in tmux sessions and are monitored for completion via MD5 hashing, enabling concurrent task execution.

**Location:** `plugins/agent_orchestrator/`

**Version:** 1.0.0

## Features

### Parallel Agent Spawning

- **Concurrent execution**: Spawn multiple agents working in parallel
- **Tmux isolation**: Each agent runs in its own tmux session
- **Activity monitoring**: Auto-detects completion via MD5 hash (idle for 3+ seconds)
- **Result injection**: Captures output and injects back to main conversation
- **File attachment**: Auto-attaches specified files to agent context

### Agent Communication

- **Send messages**: Inject instructions to running agents
- **Capture output**: Retrieve buffered output from agents
- **Stop agents**: Graceful termination with final output capture
- **Team spawning**: Lead agent with worker delegation

### LLM Integration

- **XML tool calls**: LLM uses `<agent>` tags to spawn sub-agents
- **Keyword injection**: Instructions injected when user mentions "spawn agent" etc.
- **Tool call indicators**: Shows `⏺ spawn_agent(name)` during execution
- **Force continuation**: LLM automatically responds to agent results

## XML Syntax

### Spawn Single Agent

```xml
<agent>
  <agent-name>
    <task>
    objective: What to accomplish

    context:
    - Relevant constraints
    - Background info

    todo:
    [ ] Step 1
    [ ] Step 2

    success: How to verify completion
    </task>
    <files>
      <file>path/to/file.py</file>
    </files>
  </agent-name>
</agent>
```

### Spawn Multiple Agents

```xml
<agent>
  <worker-1>
    <task>objective: Task for worker 1</task>
  </worker-1>
  <worker-2>
    <task>objective: Task for worker 2</task>
  </worker-2>
</agent>
```

### Other Commands

```xml
<message to="agent-name">Send instruction to running agent</message>
<capture>agent-name 200</capture>
<stop>agent-name</stop>
<status></status>
```

### Clone Agent with Context

```xml
<clone>
  <agent-name>
    <task>objective: Clone with conversation context</task>
  </agent-name>
</clone>
```

### Team Spawn

```xml
<team lead="lead-agent" workers="5">
  <lead-agent>
    <task>objective: Coordinate team task</task>
  </lead-agent>
</team>
```

### Broadcast

```xml
<pattern="worker-*">Message to all matching agents</broadcast>
```

## CLI Arguments

### Early Exit Commands

These commands can be used before the main app starts:

| Argument | Description | Example |
|----------|-------------|---------|
| `--session NAME` | Interact with specific agent session | `kollab --session worker-1` |
| `--capture LINES` | Capture N lines from session (requires --session) | `kollab --session worker-1 --capture 100` |
| `--list-agents` | List all active agents and exit | `kollab --list-agents` |

## Configuration

### Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `enabled` | boolean | `true` | Enable the plugin |
| `poll_interval` | int | `2` | Activity monitor poll interval (seconds) |
| `idle_threshold` | int | `3` | Seconds of idle before agent considered complete |
| `capture_lines` | int | `500` | Lines to capture on completion |
| `max_concurrent` | int | `10` | Maximum concurrent agents |
| `enable_mode` | string | `"keyword"` | How to inject LLM instructions |
| `trigger_delay` | string | `"0"` | Trigger delay for keyword mode |

### Enable Modes

| Mode | Description |
|------|-------------|
| `"startup"` | Add instructions to system prompt at initialization |
| `"keyword"` | Inject when user mentions trigger keywords (default) |
| `"disabled"` | Don't inject automatically |

### Trigger Keywords

The following keywords trigger instruction injection in keyword mode:
- "spawn agent", "spawn agents", "spawn an agent"
- "parallel agent", "parallel agents", "sub-agent", "subagent"
- "<agent>", "tmux agent", "agent orchestrat"
- "launch agent", "create agent"

### Configuration File

Edit `~/.kollabor-cli/config.json`:

```json
{
  "plugins": {
    "agent_orchestrator": {
      "enabled": true,
      "poll_interval": 2,
      "idle_threshold": 3,
      "capture_lines": 500,
      "max_concurrent": 10,
      "enable_mode": "keyword",
      "trigger_delay": "0"
    }
  }
}
```

## Architecture

### Plugin Structure

```
plugins/agent_orchestrator/
├── __init__.py
├── plugin.py              # Main plugin class
├── orchestrator.py        # Agent spawning and management
├── activity_monitor.py    # MD5-based idle detection
├── message_injector.py    # Result injection to conversation
├── xml_parser.py          # XML command parsing
├── models.py              # Data models (AgentTask, ParsedCommand)
├── file_attacher.py       # File attachment logic
└── plugin_dependency.py   # Plugin factory discovery
```

### Data Models

```python
@dataclass
class AgentTask:
    name: str                      # Agent identifier
    task: str                      # Task description/objective
    files: List[str]               # Files to attach

@dataclass
class ParsedCommand:
    type: str                      # Command type: agent, message, status, etc.
    agents: List[AgentTask]        # For agent/clone/team commands
    target: str                    # For message/status/capture/stop
    content: str                   # Message content
    lines: int                     # Capture line count
    lead: str                      # Team lead name
    workers: int                   # Team max workers
    pattern: str                   # Broadcast pattern
```

### Event Integration

| Event Type | Description |
|------------|-------------|
| `LLM_RESPONSE_POST` | Parse XML commands and execute |
| `USER_INPUT_PRE` | Keyword-triggered instruction injection |

### Custom Events

| Event | Data | Description |
|-------|------|-------------|
| `agent_spawned` | `{name, task}` | Emitted when agent spawned |
| `agent_stopped` | `{name, duration, output}` | Emitted when agent stopped |
| `agent_completed` | `{name, duration, output}` | Emitted when auto-detected complete |

### Component Architecture

1. **XMLCommandParser**: Parses `<agent>`, `<message>`, `<status>`, `<capture>`, `<stop>`, `<clone>`, `<team>`, `<broadcast>` tags
2. **AgentOrchestrator**: Manages tmux sessions, spawns agents, executes commands
3. **ActivityMonitor**: Polls agents for MD5 hash changes, detects idle state
4. **MessageInjector**: Injects results back to conversation history
5. **FileAttacher**: Attaches files to agent startup context

## Display Filter

The plugin registers a display filter that strips orchestrator XML from displayed messages to avoid duplication with tool indicators.

```python
# Filter name: "agent_orchestrator"
# Strips: <agent>, <status>, <capture>, <stop>, <message>, <clone>, <team>, <broadcast>
```

## Tool Call Indicators

The plugin mimics real tool call behavior:

- **Spawn**: `⏺ spawn_agent(name1, name2)`
- **Status**: `⏺ status()`
- **Capture**: `⏺ capture(name, lines)`
- **Stop**: `⏺ stop(name1, name2)`
- **Message**: `⏺ message(name)`
- **Clone**: `⏺ clone(name)`
- **Team**: `⏺ spawn_team(lead)`
- **Broadcast**: `⏺ broadcast(pattern)`

Results are displayed as:
- Success: `[spawned: name1, name2]`
- Error: `[error: message]`

## Implementation Checklist

### Core Functionality
- [x] XML command parsing for all agent commands
- [x] Agent spawning in tmux sessions
- [x] Activity monitoring with MD5 hashing
- [x] Result injection to conversation
- [x] File attachment support
- [x] Display filter for XML stripping

### Advanced Features
- [x] Clone with conversation context
- [x] Team spawning with workers
- [x] Broadcast to multiple agents
- [x] CLI early exit commands
- [x] Keyword-triggered instruction injection
- [x] Tool call indicator display

### Configuration
- [x] Enable modes (startup, keyword, disabled)
- [x] Trigger delay configuration
- [x] Poll interval and idle threshold
- [x] Capture lines limit
- [x] Max concurrent agents

### Testing
- [ ] Unit tests for XML parser
- [ ] Integration tests for agent spawning
- [ ] Activity monitoring tests
- [ ] Error handling tests

## Error Handling

### Common Errors

| Error | Cause | Resolution |
|-------|-------|------------|
| `[error: orchestrator not initialized]` | Plugin not initialized | Check event bus and config |
| `[error: agent name not found]` | Agent doesn't exist | Check agent name with `<status/>` |
| `[error: tmux not found]` | tmux not installed | Install tmux: `brew install tmux` |
| `[error: no agents spawned]` | Spawn failed | Check tmux session logs |

## Related Documentation

- /docs/reference/hook-system-sdk.md - Hook system
- /docs/plugins/core/tmux_plugin_spec.md - Tmux session management
- /docs/plugins/core/background_tasks_plugin_spec.md - Background task alternative

## Usage Examples

### Parallel Code Review

```xml
<agent>
  <reviewer-1>
    <task>
    objective: Review authentication code for security issues

    files:
    - auth/login.py
    - auth/session.py
    </task>
  </reviewer-1>
  <reviewer-2>
    <task>
    objective: Review API endpoints for rate limiting

    files:
    - api/v1/endpoints.py
    - api/middleware.py
    </task>
  </reviewer-2>
</agent>
```

### Continuous Integration Agent

```xml
<agent>
  <ci-runner>
    <task>
    objective: Run full test suite and generate report

    todo:
    [ ] pytest tests/ --cov
    [ ] flake8 src/
    [ ] mypy src/
    [ ] Generate HTML coverage report

    success: All tests passing, coverage > 80%
    </task>
  </ci-runner>
</agent>
```
