# Psyche Domain: API Documentation

This document provides comprehensive API documentation for the Psyche (Serwaa)
AI Virtual Assistant Platform, covering REST APIs, WebSocket events, and gRPC
services.

## API Overview

The Psyche platform exposes three primary API interfaces:

| Interface | Protocol  | Use Case                        | Latency |
| --------- | --------- | ------------------------------- | ------- |
| REST API  | HTTP/JSON | CRUD operations, client API     | <50ms   |
| WebSocket | WS/JSON   | Real-time events, streaming     | <20ms   |
| gRPC      | HTTP/2    | Service-to-service, audio/video | <10ms   |

**Base URL:** `https://api.serwaa.ai` (production) **API Version:** `v1`
**Prefix:** `/api/v1`

---

## 1. REST API Reference

### 1.1 Authentication

All REST API requests require authentication via JWT tokens or API keys.

#### JWT Authentication

```http
Authorization: Bearer <jwt_token>
```

**Token Acquisition:**

```http
POST /api/v1/auth/token
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "secure_password"
}
```

**Response:**

```json
{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "refresh_token": "eyJhbGciOiJSUzI1NiIs...",
  "token_type": "Bearer",
  "expires_in": 3600
}
```

#### API Key Authentication

```http
X-API-Key: sk_live_xxxxxxxxxxxxx
```

API keys are managed via the Admin Dashboard.

---

### 1.2 Sessions API

Manage AI virtual assistant sessions in video conferences.

#### Create Session

Creates a new session with a specified persona.

```http
POST /api/v1/sessions
Content-Type: application/json
Authorization: Bearer <token>
```

**Request Body:**

```json
{
  "persona_id": "550e8400-e29b-41d4-a716-446655440000",
  "meeting_url": "https://zoom.us/j/1234567890",
  "platform": "zoom",
  "config": {
    "auto_join": true,
    "record": false,
    "computer_use_enabled": false
  },
  "metadata": {
    "customer_id": "cust_123",
    "department": "sales"
  }
}
```

**Parameters:**

| Field                         | Type   | Required | Description                          |
| ----------------------------- | ------ | -------- | ------------------------------------ |
| `persona_id`                  | UUID   | Yes      | ID of the AI persona to use          |
| `meeting_url`                 | string | No       | Video conference URL                 |
| `platform`                    | enum   | No       | Platform: zoom, teams, meet, webex   |
| `config.auto_join`            | bool   | No       | Auto-join meeting (default: false)   |
| `config.record`               | bool   | No       | Record session (default: false)      |
| `config.computer_use_enabled` | bool   | No       | Enable computer use (default: false) |
| `metadata`                    | object | No       | Custom metadata                      |

**Response:** `201 Created`

```json
{
  "data": {
    "id": "660e8400-e29b-41d4-a716-446655440001",
    "persona_id": "550e8400-e29b-41d4-a716-446655440000",
    "status": "pending",
    "meeting_url": "https://zoom.us/j/1234567890",
    "platform": "zoom",
    "config": {
      "auto_join": true,
      "record": false,
      "computer_use_enabled": false
    },
    "metadata": {
      "customer_id": "cust_123",
      "department": "sales"
    },
    "created_at": "2026-01-31T10:00:00Z",
    "updated_at": "2026-01-31T10:00:00Z"
  }
}
```

**Session Status Values:**

| Status       | Description                      |
| ------------ | -------------------------------- |
| `pending`    | Session created, awaiting start  |
| `connecting` | Connecting to video conference   |
| `active`     | Session active, AI participating |
| `paused`     | Session temporarily paused       |
| `ended`      | Session completed                |
| `error`      | Session encountered an error     |

---

#### List Sessions

Retrieve paginated list of sessions with optional filtering.

```http
GET /api/v1/sessions?page=1&per_page=20&status=active
Authorization: Bearer <token>
```

**Query Parameters:**

| Parameter    | Type | Default | Description             |
| ------------ | ---- | ------- | ----------------------- |
| `page`       | int  | 1       | Page number (1-indexed) |
| `per_page`   | int  | 20      | Items per page (1-100)  |
| `status`     | enum | -       | Filter by status        |
| `persona_id` | UUID | -       | Filter by persona       |
| `platform`   | enum | -       | Filter by platform      |

**Response:** `200 OK`

```json
{
  "data": [
    {
      "id": "660e8400-e29b-41d4-a716-446655440001",
      "persona_id": "550e8400-e29b-41d4-a716-446655440000",
      "status": "active",
      "platform": "zoom",
      "created_at": "2026-01-31T10:00:00Z"
    }
  ],
  "meta": {
    "page": 1,
    "per_page": 20,
    "total": 42,
    "total_pages": 3
  }
}
```

---

#### Get Session

Retrieve details for a specific session.

```http
GET /api/v1/sessions/{session_id}
Authorization: Bearer <token>
```

**Response:** `200 OK`

```json
{
  "data": {
    "id": "660e8400-e29b-41d4-a716-446655440001",
    "persona_id": "550e8400-e29b-41d4-a716-446655440000",
    "status": "active",
    "meeting_url": "https://zoom.us/j/1234567890",
    "platform": "zoom",
    "config": {...},
    "metadata": {...},
    "started_at": "2026-01-31T10:05:00Z",
    "created_at": "2026-01-31T10:00:00Z",
    "updated_at": "2026-01-31T10:05:00Z",
    "stats": {
      "duration_seconds": 300,
      "turns": 15,
      "tools_used": 2
    }
  }
}
```

---

#### Session Actions

```http
POST /api/v1/sessions/{session_id}/start
POST /api/v1/sessions/{session_id}/join-meeting
POST /api/v1/sessions/{session_id}/pause
POST /api/v1/sessions/{session_id}/resume
POST /api/v1/sessions/{session_id}/end
DELETE /api/v1/sessions/{session_id}
```

**Join Meeting Request:**

```json
{
  "meeting_url": "https://zoom.us/j/1234567890",
  "meeting_password": "optional_password"
}
```

---

#### Get Session Metrics

Retrieve aggregate session metrics.

```http
GET /api/v1/sessions/metrics
Authorization: Bearer <token>
```

**Response:**

```json
{
  "data": {
    "total_sessions": 1542,
    "active_sessions": 12,
    "average_duration_seconds": 845,
    "sessions_by_status": {
      "pending": 5,
      "active": 12,
      "ended": 1520,
      "error": 5
    },
    "sessions_by_platform": {
      "zoom": 850,
      "teams": 420,
      "meet": 250,
      "webex": 22
    }
  }
}
```

---

### 1.3 Personas API

Manage AI persona configurations including personality, voice, and avatar.

#### Create Persona

```http
POST /api/v1/personas
Content-Type: application/json
Authorization: Bearer <token>
```

**Request Body:**

```json
{
  "name": "sales-assistant",
  "display_name": "Sarah - Sales Assistant",
  "description": "Professional sales assistant with product expertise",
  "system_prompt": "You are Sarah, a knowledgeable sales assistant...",
  "personality": {
    "formality": 0.7,
    "friendliness": 0.8,
    "verbosity": 0.5,
    "humor": 0.3,
    "empathy": 0.9,
    "assertiveness": 0.6
  },
  "voice": {
    "voice_id": "elevenlabs_sarah",
    "provider": "elevenlabs",
    "speed": 1.0,
    "pitch": 1.0,
    "custom_voice_enabled": false
  },
  "avatar": {
    "model_id": "3dgs_professional_female_001",
    "style": "professional",
    "background": "office",
    "camera_position": "front"
  },
  "expertise": ["sales", "product-knowledge", "customer-service"],
  "tools": ["crm-lookup", "product-catalog", "calendar-booking"]
}
```

**Personality Traits (0.0 - 1.0):**

| Trait           | Low Value       | High Value           |
| --------------- | --------------- | -------------------- |
| `formality`     | Casual, relaxed | Professional, formal |
| `friendliness`  | Reserved        | Warm, approachable   |
| `verbosity`     | Concise         | Detailed, thorough   |
| `humor`         | Serious         | Light-hearted        |
| `empathy`       | Task-focused    | Emotionally attuned  |
| `assertiveness` | Accommodating   | Direct, confident    |

**Voice Providers:**

| Provider     | Features                       |
| ------------ | ------------------------------ |
| `elevenlabs` | Premium quality, voice cloning |
| `xtts`       | Local model, 19 languages      |
| `cartesia`   | Low latency (<50ms)            |
| `openai`     | Good quality, wide language    |

**Response:** `201 Created`

---

#### List Personas

```http
GET /api/v1/personas?page=1&per_page=20&search=sales
Authorization: Bearer <token>
```

**Query Parameters:**

| Parameter   | Type   | Description                |
| ----------- | ------ | -------------------------- |
| `search`    | string | Search by name/description |
| `is_active` | bool   | Filter by active status    |
| `expertise` | string | Filter by expertise tag    |

---

#### Update Persona

```http
PATCH /api/v1/personas/{persona_id}
Content-Type: application/json
Authorization: Bearer <token>
```

**Request Body (partial update):**

```json
{
  "personality": {
    "friendliness": 0.9
  },
  "voice": {
    "speed": 1.1
  }
}
```

---

#### Persona Actions

```http
POST /api/v1/personas/{persona_id}/activate
POST /api/v1/personas/{persona_id}/deactivate
POST /api/v1/personas/{persona_id}/clone
DELETE /api/v1/personas/{persona_id}
```

---

### 1.4 Knowledge Base API

Manage documents and perform semantic search for RAG.

#### Upload Document

```http
POST /api/v1/knowledge/documents/upload
Content-Type: multipart/form-data
Authorization: Bearer <token>
```

**Form Data:**

| Field        | Type   | Required | Description            |
| ------------ | ------ | -------- | ---------------------- |
| `file`       | file   | Yes      | Document file          |
| `persona_id` | UUID   | No       | Associate with persona |
| `tags`       | array  | No       | Tags for filtering     |
| `metadata`   | object | No       | Custom metadata        |

**Supported File Types:**

| Type       | Extensions      | Max Size |
| ---------- | --------------- | -------- |
| PDF        | `.pdf`          | 50 MB    |
| Word       | `.docx`, `.doc` | 25 MB    |
| HTML       | `.html`, `.htm` | 10 MB    |
| Markdown   | `.md`           | 5 MB     |
| CSV        | `.csv`          | 25 MB    |
| JSON       | `.json`         | 10 MB    |
| Plain Text | `.txt`          | 5 MB     |

**Response:** `201 Created`

```json
{
  "data": {
    "id": "770e8400-e29b-41d4-a716-446655440002",
    "title": "Product Catalog 2026",
    "source_type": "pdf",
    "status": "processing",
    "chunk_count": 0,
    "file_size_bytes": 2456789,
    "created_at": "2026-01-31T10:00:00Z"
  }
}
```

**Document Status:**

| Status       | Description                |
| ------------ | -------------------------- |
| `pending`    | Awaiting processing        |
| `processing` | Being chunked and embedded |
| `ready`      | Available for search       |
| `error`      | Processing failed          |

---

#### Semantic Search

```http
POST /api/v1/knowledge/search
Content-Type: application/json
Authorization: Bearer <token>
```

**Request Body:**

```json
{
  "query": "What are the pricing options for enterprise customers?",
  "persona_id": "550e8400-e29b-41d4-a716-446655440000",
  "tags": ["pricing", "enterprise"],
  "top_k": 10,
  "score_threshold": 0.7
}
```

**Parameters:**

| Field             | Type   | Default | Description                |
| ----------------- | ------ | ------- | -------------------------- |
| `query`           | string | -       | Search query (required)    |
| `persona_id`      | UUID   | -       | Filter by persona          |
| `tags`            | array  | -       | Filter by tags             |
| `top_k`           | int    | 10      | Max results (1-100)        |
| `score_threshold` | float  | 0.5     | Min similarity score (0-1) |

**Response:**

```json
{
  "data": {
    "results": [
      {
        "document_id": "770e8400-e29b-41d4-a716-446655440002",
        "document_title": "Product Catalog 2026",
        "chunk_index": 42,
        "content": "Enterprise pricing starts at $10,000/month...",
        "score": 0.92,
        "metadata": {
          "section": "Pricing",
          "page": 15
        }
      }
    ],
    "query": "What are the pricing options for enterprise customers?",
    "total_results": 5,
    "processing_time_ms": 45
  }
}
```

---

### 1.5 Tools API

Register and manage tools for AI persona capabilities.

#### Register Tool

```http
POST /api/v1/tools
Content-Type: application/json
Authorization: Bearer <token>
```

**Request Body:**

```json
{
  "name": "calendar-booking",
  "display_name": "Calendar Booking",
  "description": "Book meetings on the calendar",
  "type": "api",
  "config": {
    "endpoint": "https://api.calendar.example.com/v1/bookings",
    "method": "POST",
    "auth_type": "oauth2",
    "auth_config": {
      "client_id": "calendar_client_123"
    }
  },
  "parameters": {
    "type": "object",
    "properties": {
      "title": {
        "type": "string",
        "description": "Meeting title"
      },
      "start_time": {
        "type": "string",
        "format": "date-time",
        "description": "Meeting start time (ISO 8601)"
      },
      "duration_minutes": {
        "type": "integer",
        "description": "Meeting duration in minutes"
      },
      "attendees": {
        "type": "array",
        "items": { "type": "string", "format": "email" },
        "description": "List of attendee emails"
      }
    },
    "required": ["title", "start_time", "duration_minutes"]
  }
}
```

**Tool Types:**

| Type       | Description                   |
| ---------- | ----------------------------- |
| `function` | Local function execution      |
| `api`      | External API call             |
| `mcp`      | Model Context Protocol server |
| `webhook`  | Webhook trigger               |

**Auth Types:**

| Type      | Description               |
| --------- | ------------------------- |
| `none`    | No authentication         |
| `api_key` | API key in header         |
| `basic`   | HTTP Basic authentication |
| `bearer`  | Bearer token              |
| `oauth2`  | OAuth 2.0 flow            |

---

#### Tool Actions

```http
GET /api/v1/tools/{tool_id}
GET /api/v1/tools/{tool_id}/schema
PATCH /api/v1/tools/{tool_id}
DELETE /api/v1/tools/{tool_id}
POST /api/v1/tools/{tool_id}/test
POST /api/v1/tools/{tool_id}/activate
POST /api/v1/tools/{tool_id}/deactivate
```

**Test Tool:**

```json
{
  "parameters": {
    "title": "Demo Meeting",
    "start_time": "2026-02-01T14:00:00Z",
    "duration_minutes": 30
  }
}
```

---

### 1.6 Webhooks API

Configure webhooks for event notifications.

#### Create Webhook

```http
POST /api/v1/webhooks
Content-Type: application/json
Authorization: Bearer <token>
```

**Request Body:**

```json
{
  "name": "session-events-webhook",
  "url": "https://api.example.com/webhooks/serwaa",
  "events": ["session.started", "session.ended", "conversation.message"],
  "secret": "whsec_xxxxxxxxxxxxxxxxxxxxxxxx",
  "headers": {
    "X-Custom-Header": "custom-value"
  }
}
```

**Available Events (14 types):**

| Event                  | Description                 |
| ---------------------- | --------------------------- |
| `session.started`      | Session became active       |
| `session.ended`        | Session completed           |
| `session.paused`       | Session paused              |
| `session.resumed`      | Session resumed             |
| `session.error`        | Session encountered error   |
| `conversation.started` | Conversation began          |
| `conversation.turn`    | Conversation turn completed |
| `conversation.message` | New message in conversation |
| `meeting.joined`       | Joined video conference     |
| `meeting.left`         | Left video conference       |
| `tool.executed`        | Tool was executed           |
| `tool.error`           | Tool execution failed       |
| `emotion.detected`     | User emotion detected       |
| `error.occurred`       | General error occurred      |

**Webhook Payload:**

```json
{
  "id": "evt_xxxxxxxxxxxxxxxx",
  "type": "session.started",
  "created_at": "2026-01-31T10:05:00Z",
  "data": {
    "session_id": "660e8400-e29b-41d4-a716-446655440001",
    "persona_id": "550e8400-e29b-41d4-a716-446655440000",
    "platform": "zoom"
  }
}
```

**Webhook Signature:**

```
X-Webhook-Signature: sha256=xxxxxxxxxxxxxxxxxxxxxxxxx
```

Verify using HMAC-SHA256 with your webhook secret.

---

### 1.7 Health & Status API

#### Health Check

```http
GET /health
```

**Response:**

```json
{
  "status": "healthy",
  "version": "1.0.0",
  "timestamp": "2026-01-31T10:00:00Z"
}
```

#### Readiness Probe

```http
GET /ready
```

Returns `200 OK` when all dependencies are available.

#### Liveness Probe

```http
GET /live
```

Returns `200 OK` when service is alive.

---

### 1.8 Error Responses

All errors follow a consistent format:

```json
{
  "error": {
    "code": "RESOURCE_NOT_FOUND",
    "message": "Session with ID 'xxx' not found",
    "details": {
      "resource_type": "session",
      "resource_id": "xxx"
    },
    "correlation_id": "req_xxxxxxxxxxxxxxxx"
  }
}
```

**Error Codes:**

| HTTP Status | Code                   | Description                |
| ----------- | ---------------------- | -------------------------- |
| 400         | `BAD_REQUEST`          | Invalid request format     |
| 400         | `VALIDATION_ERROR`     | Field validation failed    |
| 401         | `UNAUTHORIZED`         | Authentication required    |
| 403         | `FORBIDDEN`            | Insufficient permissions   |
| 404         | `RESOURCE_NOT_FOUND`   | Resource does not exist    |
| 409         | `CONFLICT`             | Resource state conflict    |
| 422         | `UNPROCESSABLE_ENTITY` | Semantic validation failed |
| 429         | `RATE_LIMITED`         | Too many requests          |
| 500         | `INTERNAL_ERROR`       | Server error               |
| 503         | `SERVICE_UNAVAILABLE`  | Service temporarily down   |

---

### 1.9 Rate Limiting

API requests are rate limited per API key or user token:

| Tier       | Requests/Minute | Requests/Hour |
| ---------- | --------------- | ------------- |
| Free       | 60              | 1,000         |
| Pro        | 300             | 10,000        |
| Enterprise | 1,000           | 50,000        |

**Rate Limit Headers:**

```http
X-RateLimit-Limit: 300
X-RateLimit-Remaining: 295
X-RateLimit-Reset: 1706698800
```

---

## 2. WebSocket API Reference

Real-time bidirectional communication for session events and control.

### 2.1 Connection

```javascript
const ws = new WebSocket('wss://api.serwaa.ai/api/v1/ws');

// Or session-specific connection
const ws = new WebSocket('wss://api.serwaa.ai/api/v1/ws/sessions/{session_id}');
```

**Authentication:**

```javascript
// Option 1: Query parameter
const ws = new WebSocket('wss://api.serwaa.ai/api/v1/ws?token=<jwt_token>');

// Option 2: First message
ws.send(
  JSON.stringify({
    type: 'auth',
    token: '<jwt_token>',
  })
);
```

---

### 2.2 Message Format

All WebSocket messages use JSON format:

```json
{
  "type": "<message_type>",
  "id": "<optional_message_id>",
  "data": { ... },
  "timestamp": "2026-01-31T10:00:00.000Z"
}
```

---

### 2.3 Client → Server Messages

#### Subscribe to Session

```json
{
  "type": "subscribe",
  "data": {
    "session_id": "660e8400-e29b-41d4-a716-446655440001",
    "events": ["session.*", "conversation.*"]
  }
}
```

**Event Patterns:**

- `*` - All events
- `session.*` - All session events
- `session.started` - Specific event

#### Unsubscribe

```json
{
  "type": "unsubscribe",
  "data": {
    "session_id": "660e8400-e29b-41d4-a716-446655440001"
  }
}
```

#### Control Commands

```json
{
  "type": "command",
  "id": "cmd_123",
  "data": {
    "session_id": "660e8400-e29b-41d4-a716-446655440001",
    "command": "session.pause",
    "parameters": {}
  }
}
```

**Available Commands:**

| Command          | Parameters              | Description                 |
| ---------------- | ----------------------- | --------------------------- |
| `session.start`  | -                       | Start pending session       |
| `session.pause`  | -                       | Pause active session        |
| `session.resume` | -                       | Resume paused session       |
| `session.end`    | -                       | End session                 |
| `audio.mute`     | -                       | Mute AI microphone          |
| `audio.unmute`   | -                       | Unmute AI microphone        |
| `video.enable`   | -                       | Enable AI camera            |
| `video.disable`  | -                       | Disable AI camera           |
| `ai.interrupt`   | -                       | Interrupt AI speech         |
| `ai.set_mode`    | `{ mode: "listening" }` | Set AI behavior mode        |
| `tool.execute`   | `{ tool_id, params }`   | Execute a tool              |
| `persona.switch` | `{ persona_id }`        | Switch to different persona |

#### Ping

```json
{
  "type": "ping",
  "timestamp": "2026-01-31T10:00:00.000Z"
}
```

---

### 2.4 Server → Client Messages

#### Session Events

```json
{
  "type": "event",
  "data": {
    "event": "session.started",
    "session_id": "660e8400-e29b-41d4-a716-446655440001",
    "timestamp": "2026-01-31T10:05:00.000Z",
    "payload": {
      "persona_id": "550e8400-e29b-41d4-a716-446655440000",
      "platform": "zoom"
    }
  }
}
```

**Event Types:**

| Event                        | Payload                        |
| ---------------------------- | ------------------------------ |
| `session.started`            | `{ persona_id, platform }`     |
| `session.ended`              | `{ duration_seconds, turns }`  |
| `session.paused`             | `{ reason }`                   |
| `session.resumed`            | -                              |
| `session.error`              | `{ error_code, message }`      |
| `session.state_changed`      | `{ old_state, new_state }`     |
| `meeting.joining`            | `{ platform, meeting_url }`    |
| `meeting.joined`             | `{ meeting_id, participants }` |
| `meeting.left`               | `{ reason }`                   |
| `meeting.participant_joined` | `{ participant_id, name }`     |
| `meeting.participant_left`   | `{ participant_id, name }`     |
| `conversation.turn_started`  | `{ turn_id, speaker }`         |
| `conversation.turn_ended`    | `{ turn_id, duration_ms }`     |
| `conversation.message`       | `{ role, content, turn_id }`   |
| `ai.thinking`                | -                              |
| `ai.speaking`                | `{ text }`                     |
| `ai.listening`               | -                              |
| `ai.idle`                    | -                              |
| `tool.executing`             | `{ tool_id, tool_name }`       |
| `tool.completed`             | `{ tool_id, result }`          |
| `tool.error`                 | `{ tool_id, error }`           |
| `emotion.detected`           | `{ emotion, confidence }`      |

#### Transcript Events

Real-time speech transcription:

```json
{
  "type": "transcript",
  "data": {
    "session_id": "660e8400-e29b-41d4-a716-446655440001",
    "segments": [
      {
        "speaker": "user",
        "text": "Can you tell me about",
        "start_time_ms": 1500,
        "end_time_ms": 2100,
        "confidence": 0.95,
        "is_final": false
      }
    ]
  }
}
```

#### Metrics Events

Real-time performance metrics:

```json
{
  "type": "metrics",
  "data": {
    "session_id": "660e8400-e29b-41d4-a716-446655440001",
    "timestamp": "2026-01-31T10:05:00.000Z",
    "metrics": {
      "avatar_fps": 30,
      "avatar_latency_ms": 22,
      "voice_latency_ms": 85,
      "perception_latency_ms": 15,
      "end_to_end_latency_ms": 420,
      "gpu_memory_usage_mb": 7500
    }
  }
}
```

#### Acknowledgment

Response to commands:

```json
{
  "type": "ack",
  "data": {
    "command_id": "cmd_123",
    "success": true,
    "result": {}
  }
}
```

#### Error

```json
{
  "type": "error",
  "data": {
    "code": "INVALID_COMMAND",
    "message": "Unknown command: session.invalid",
    "correlation_id": "req_xxxxxxxx"
  }
}
```

#### Pong

```json
{
  "type": "pong",
  "timestamp": "2026-01-31T10:00:00.001Z"
}
```

---

### 2.5 Connection Management

**Heartbeat:** Send `ping` every 30 seconds to maintain connection.

**Reconnection:** Implement exponential backoff (1s, 2s, 4s, 8s, max 30s).

**Connection Limits:**

| Tier       | Max Connections | Max Subscriptions |
| ---------- | --------------- | ----------------- |
| Free       | 5               | 10                |
| Pro        | 50              | 100               |
| Enterprise | 500             | 1,000             |

---

## 3. gRPC API Reference

High-performance service-to-service communication.

### 3.1 Agent Service

Multi-agent orchestration for session management.

**Proto File:** `libs/proto/src/agent/agent.proto`

#### Service Definition

```protobuf
service AgentService {
  // Agent Management
  rpc RegisterAgent(RegisterAgentRequest) returns (RegisterAgentResponse);
  rpc GetAgent(GetAgentRequest) returns (GetAgentResponse);
  rpc UpdateAgent(UpdateAgentRequest) returns (UpdateAgentResponse);
  rpc DeregisterAgent(DeregisterAgentRequest) returns (DeregisterAgentResponse);
  rpc ListAgents(ListAgentsRequest) returns (ListAgentsResponse);

  // Lifecycle
  rpc StartAgent(StartAgentRequest) returns (StartAgentResponse);
  rpc StopAgent(StopAgentRequest) returns (StopAgentResponse);
  rpc RestartAgent(RestartAgentRequest) returns (RestartAgentResponse);
  rpc Heartbeat(HeartbeatRequest) returns (HeartbeatResponse);

  // Task Management
  rpc AssignTask(AssignTaskRequest) returns (AssignTaskResponse);
  rpc GetTask(GetTaskRequest) returns (GetTaskResponse);
  rpc UpdateTaskStatus(UpdateTaskStatusRequest) returns (UpdateTaskStatusResponse);
  rpc CancelTask(CancelTaskRequest) returns (CancelTaskResponse);
  rpc ListTasks(ListTasksRequest) returns (ListTasksResponse);

  // Streaming
  rpc StreamTaskOutput(stream TaskOutputChunk) returns (stream TaskOutputChunk);
  rpc SendTaskInput(stream TaskInputChunk) returns (stream TaskInputAck);

  // Pools
  rpc CreatePool(CreatePoolRequest) returns (CreatePoolResponse);
  rpc GetPool(GetPoolRequest) returns (GetPoolResponse);
  rpc UpdatePool(UpdatePoolRequest) returns (UpdatePoolResponse);
  rpc DeletePool(DeletePoolRequest) returns (DeletePoolResponse);
  rpc ListPools(ListPoolsRequest) returns (ListPoolsResponse);
  rpc AddAgentToPool(AddAgentToPoolRequest) returns (AddAgentToPoolResponse);
  rpc RemoveAgentFromPool(RemoveAgentFromPoolRequest) returns (RemoveAgentFromPoolResponse);

  // Messaging
  rpc SendMessage(SendMessageRequest) returns (SendMessageResponse);
  rpc StreamMessages(StreamMessagesRequest) returns (stream AgentMessage);
  rpc BroadcastMessage(BroadcastMessageRequest) returns (BroadcastMessageResponse);

  // Metrics
  rpc GetAgentMetrics(GetAgentMetricsRequest) returns (GetAgentMetricsResponse);
  rpc GetPoolMetrics(GetPoolMetricsRequest) returns (GetPoolMetricsResponse);
}
```

#### Agent Types

```protobuf
enum AgentType {
  AGENT_TYPE_UNSPECIFIED = 0;
  AGENT_TYPE_WORKER = 1;      // General-purpose worker
  AGENT_TYPE_COORDINATOR = 2; // Coordinates other agents
  AGENT_TYPE_SUPERVISOR = 3;  // Monitors and manages agents
  AGENT_TYPE_SPECIALIST = 4;  // Domain-specific agent
}
```

#### Agent Status

```protobuf
enum AgentStatus {
  AGENT_STATUS_UNSPECIFIED = 0;
  AGENT_STATUS_REGISTERING = 1;  // Initial registration
  AGENT_STATUS_IDLE = 2;         // Ready for tasks
  AGENT_STATUS_BUSY = 3;         // Processing task
  AGENT_STATUS_PAUSED = 4;       // Temporarily paused
  AGENT_STATUS_ERROR = 5;        // Error state
  AGENT_STATUS_OFFLINE = 6;      // Not responding
  AGENT_STATUS_TERMINATING = 7;  // Shutting down
}
```

#### Task Priority

```protobuf
enum TaskPriority {
  TASK_PRIORITY_UNSPECIFIED = 0;
  TASK_PRIORITY_LOW = 1;
  TASK_PRIORITY_NORMAL = 2;
  TASK_PRIORITY_HIGH = 3;
  TASK_PRIORITY_CRITICAL = 4;
}
```

#### Example Usage (Python)

```python
import grpc
from agent_pb2 import RegisterAgentRequest, AgentType, AgentConfig
from agent_pb2_grpc import AgentServiceStub

# Connect to gRPC server
channel = grpc.insecure_channel('localhost:50051')
stub = AgentServiceStub(channel)

# Register an agent
response = stub.RegisterAgent(RegisterAgentRequest(
    name="avatar-renderer-1",
    agent_type=AgentType.AGENT_TYPE_WORKER,
    version="1.0.0",
    capabilities=["render_3dgs", "flame_deformation"],
    config=AgentConfig(
        max_concurrent_tasks=2,
        heartbeat_interval_ms=5000
    )
))

print(f"Registered agent: {response.agent.id}")
```

---

### 3.2 Common Types

Shared types across all gRPC services.

**Proto File:** `libs/proto/src/common/types.proto`

```protobuf
message UUID {
  string value = 1;
}

message Pagination {
  int32 page = 1;
  int32 per_page = 2;
}

message PaginationMeta {
  int32 page = 1;
  int32 per_page = 2;
  int32 total = 3;
  int32 total_pages = 4;
}

message Timestamp {
  int64 seconds = 1;
  int32 nanos = 2;
}

message Empty {}
```

---

### 3.3 Health Service

```protobuf
service HealthService {
  rpc Check(HealthCheckRequest) returns (HealthCheckResponse);
  rpc Watch(HealthCheckRequest) returns (stream HealthCheckResponse);
}

message HealthCheckRequest {
  string service = 1;
}

message HealthCheckResponse {
  enum ServingStatus {
    UNKNOWN = 0;
    SERVING = 1;
    NOT_SERVING = 2;
  }
  ServingStatus status = 1;
}
```

---

## 4. OpenAPI Specification

The complete OpenAPI 3.0 specification is available at:

- **Development:** `http://localhost:8000/openapi.json`
- **Swagger UI:** `http://localhost:8000/docs`
- **ReDoc:** `http://localhost:8000/redoc`

**Export OpenAPI Spec:**

```bash
curl http://localhost:8000/openapi.json > openapi.json
```

---

## 5. SDK & Client Libraries

### 5.1 Python SDK

```python
from serwaa import SerwaaClient

client = SerwaaClient(api_key="sk_live_xxxxx")

# Create session
session = client.sessions.create(
    persona_id="550e8400-e29b-41d4-a716-446655440000",
    meeting_url="https://zoom.us/j/1234567890"
)

# Join meeting
client.sessions.join_meeting(session.id)

# Subscribe to events
async for event in client.sessions.stream_events(session.id):
    print(f"Event: {event.type}")
```

### 5.2 TypeScript/JavaScript SDK

```typescript
import { SerwaaClient } from '@serwaa/client';

const client = new SerwaaClient({ apiKey: 'sk_live_xxxxx' });

// Create session
const session = await client.sessions.create({
  personaId: '550e8400-e29b-41d4-a716-446655440000',
  meetingUrl: 'https://zoom.us/j/1234567890',
});

// Join meeting
await client.sessions.joinMeeting(session.id);

// Subscribe to events
client.sessions.on('event', (event) => {
  console.log('Event:', event.type);
});
```

---

## 6. API Versioning

### Current Version

- **REST API:** `v1` (prefix: `/api/v1`)
- **WebSocket:** `v1` (path: `/api/v1/ws`)
- **gRPC:** Semantic versioning in proto package

### Deprecation Policy

- **Notice Period:** 6 months before removal
- **Headers:** `X-API-Deprecated: true` on deprecated endpoints
- **Response:** `deprecation` field in response metadata

---

## 7. Related Documentation

- [Architecture Overview](./architecture.md)
- [Service Inventory](./service-inventory.md)
- [Communication Architecture](./communication-architecture.md)
- [Security Audit](./security-audit.md)

---

## Revision History

| Version | Date       | Author      | Changes                   |
| ------- | ---------- | ----------- | ------------------------- |
| 1.0.0   | 2026-01-31 | Claude Opus | Initial API documentation |
