# Getting Started with Agent Orchestrator

This guide walks you through setting up and using the Agent Orchestrator system.

## Prerequisites

- **Python 3.11+** - Required for running the orchestrator
- **tmux** - For CLI agent workspace isolation
- **Git** - For worktree management
- **At least one CLI agent installed**:
  - Claude Code (`claude-code`)
  - Gemini CLI (`gemini`)
  - Codex CLI (`codex`)

## Installation

### From Source

```bash
# Clone the repository
git clone https://github.com/your-org/agent-orchestrator.git
cd agent-orchestrator

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install with all dependencies
pip install -e ".[dev]"
```

### From PyPI (Coming Soon)

```bash
pip install agent-orchestrator
```

## Configuration

### 1. Environment Variables

Copy the example environment file:

```bash
cp .env.example .env
```

Edit `.env` with your settings:

```bash
# Database
DATABASE_URL=sqlite:///./orchestrator.db

# Optional API keys (only needed for API-based agents)
ANTHROPIC_API_KEY=sk-ant-...
OPENAI_API_KEY=sk-...
GOOGLE_API_KEY=AIza...

# Observability (optional)
SLACK_WEBHOOK_URL=https://hooks.slack.com/...

# Budget limits
DAILY_BUDGET_USD=50.00
```

### 2. Authenticate CLI Agents

Before using CLI agents, authenticate each one:

```bash
# Claude Code
claude-code --version
# Follow the web authentication flow

# Gemini CLI
gemini --version
# Follow the authentication flow

# Codex CLI
codex --version
# Follow the authentication flow
```

### 3. Verify Installation

```bash
# Run tests to verify setup
pytest tests/unit/ -v

# Check CLI agent availability
python -c "from agent_orchestrator import check_agents; check_agents()"
```

## Quick Start

### Start the Orchestrator

```bash
# Start in background mode
python -m agent_orchestrator start

# Or start with TUI dashboard
python -m agent_orchestrator.tui

# Or start the REST API
python -m agent_orchestrator.api
```

### Submit Your First Task

#### Via CLI

```bash
python -m agent_orchestrator task create \
  --description "Create a Python function that calculates prime numbers" \
  --priority 5
```

#### Via Python

```python
import asyncio
from agent_orchestrator import Orchestrator

async def main():
    orchestrator = Orchestrator()
    await orchestrator.start()

    try:
        # Submit a task
        task = await orchestrator.submit_task(
            description="Create a Python function that calculates prime numbers",
            priority=5,
        )
        print(f"Task submitted: {task.id}")

        # Wait for completion
        result = await orchestrator.wait_for_task(task.id)
        print(f"Status: {result.status}")
        print(f"Output: {result.output}")

    finally:
        await orchestrator.shutdown()

asyncio.run(main())
```

#### Via REST API

```bash
# Create task
curl -X POST \
  -H "X-API-Key: your-key" \
  -H "Content-Type: application/json" \
  -d '{"description": "Create a Python function that calculates prime numbers"}' \
  http://localhost:8080/api/tasks

# Check status
curl -H "X-API-Key: your-key" \
  http://localhost:8080/api/tasks/task-123
```

### Monitor Progress

#### TUI Dashboard

```bash
python -m agent_orchestrator.tui
```

The dashboard shows:
- Agent status (available, busy, exhausted)
- Task queue with priorities
- Active task output
- Cost summary

Key bindings:
- `q` - Quit
- `n` - New task
- `p` - Pause selected agent
- `r` - Refresh

#### REST API

```bash
# System health
curl http://localhost:8080/api/health

# List agents
curl http://localhost:8080/api/agents

# List tasks
curl http://localhost:8080/api/tasks

# Get costs
curl http://localhost:8080/api/costs
```

## Core Concepts

### Agents

Agents are AI coding assistants that execute tasks. The orchestrator supports:

| Agent | Type | Best For |
|-------|------|----------|
| Claude Code | CLI | Interactive coding, complex reasoning |
| Gemini CLI | CLI | Large context analysis, search |
| Codex CLI | CLI | CI/CD automation, scripts |
| Claude SDK | API | Programmatic access |
| OpenAI Agents | API | Structured outputs |

### Tasks

Tasks are units of work submitted to agents:

```python
task = await orchestrator.submit_task(
    description="Implement user authentication",  # What to do
    agent_id="claude-code",                       # Specific agent (optional)
    priority=7,                                    # 1-10, higher = more urgent
    run_until_done=True,                          # Retry on failure
    max_retries=3,                                # Max retry attempts
)
```

### Risk Levels

All operations are classified by risk:

| Level | Behavior | Examples |
|-------|----------|----------|
| LOW | Auto-approved | Read files, run tests |
| MEDIUM | Confirm | Install packages, git commit |
| HIGH | Approve + warn | Auth changes, migrations |
| CRITICAL | Auto-reject | Force push, rm -rf |

### Workflows

Define complex multi-step workflows in JSON:

```python
from agent_orchestrator.workflows import WorkflowEngine

workflow = {
    "name": "feature-implementation",
    "steps": [
        {
            "id": "design",
            "type": "task",
            "agent_id": "claude-code",
            "prompt": "Design the architecture for ${feature_name}"
        },
        {
            "id": "implement",
            "type": "parallel",
            "steps": [
                {"id": "backend", "type": "task", "prompt": "Implement backend"},
                {"id": "frontend", "type": "task", "prompt": "Implement frontend"}
            ]
        },
        {
            "id": "test",
            "type": "task",
            "prompt": "Run tests",
            "dependencies": ["implement"]
        }
    ]
}

engine = WorkflowEngine()
result = await engine.execute(workflow, variables={"feature_name": "user-auth"})
```

## Next Steps

- [Configuration Reference](./CONFIGURATION.md) - Detailed configuration options
- [Architecture Overview](./ARCHITECTURE.md) - System design
- [API Documentation](./api/overview.md) - REST API reference
- [Examples](../examples/) - Code examples
- [Troubleshooting](./TROUBLESHOOTING.md) - Common issues

## Getting Help

- **Issues**: [GitHub Issues](https://github.com/your-org/agent-orchestrator/issues)
- **Discussions**: [GitHub Discussions](https://github.com/your-org/agent-orchestrator/discussions)
- **Runbooks**: [ops/runbooks/](../ops/runbooks/) - Operational guides
