> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zappway.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Livia - 360 Assistant

> Livia - 360 Assistant is your assistant inside ZappWay — it chats, automates recurring tasks through routines, surfaces business opportunities, and gives you a complete audit trail of everything it does.

> **What you will learn:**
> This page covers every feature of Livia: chat conversations, automated routines, action approvals, business opportunities, privacy controls, usage tracking, and integration diagnostics.

***

## 🔢 Table of Contents

1. [Overview](#1-overview)
2. [Prerequisites](#2-prerequisites)
3. [Endpoint Reference](#3-endpoint-reference)
4. [Chat](#4-chat)
5. [Conversations](#5-conversations)
6. [Routines](#6-routines)
7. [Approvals](#7-approvals)
8. [Opportunities](#8-opportunities)
9. [State & Capabilities](#9-state--capabilities)
10. [Privacy & Retention](#10-privacy--retention)
11. [Audit Log](#11-audit-log)
12. [Settings & Usage](#12-settings--usage)
13. [Integration Diagnostics](#13-integration-diagnostics)
14. [Error Handling](#14-error-handling)
15. [Best Practices](#15-best-practices)

***

## 1. Overview

### What is Livia - 360 Assistant?

**Livia - 360 Assistant** is a plan-gated AI assistant built directly into ZappWay. Unlike the AI Employees (which handle external customer conversations), Livia works **for you and your team** internally.

**Key Capabilities:**

* 💬 **Natural language chat** with full conversation history
* 🔄 **Automated routines** — recurring tasks that run on schedule
* ✅ **Action approvals** — review AI-proposed actions before they execute
* 📈 **Business opportunities** — AI-surfaced insights from your data
* 🔒 **Privacy controls** — full data retention management
* 📋 **Audit log** — complete history of every action the assistant took

### Plan Requirement

Livia is available only on plans that include the `personal_assistant` feature flag. Attempting to access any endpoint without the required plan returns:

```json theme={null}
{ "error": "Livia - 360 Assistant requires a PRO plan." }
```

***

## 2. Prerequisites

* Active ZappWay account with a plan that includes Livia
* Authenticated session (Livia is always user-bound, not organization-bound at the chat level)
* At least one integration configured for full functionality (optional for basic chat)

***

## 3. Endpoint Reference

| Method            | Endpoint                                                                 | Description                            | Auth                         |
| ----------------- | ------------------------------------------------------------------------ | -------------------------------------- | ---------------------------- |
| `POST`            | `/api/personal-assistant/chat`                                           | Send a message (streaming SSE or JSON) | `personal_assistant.execute` |
| `GET`             | `/api/personal-assistant/state`                                          | Get assistant state and context        | `personal_assistant.read`    |
| `GET`             | `/api/personal-assistant/capabilities`                                   | List assistant capabilities            | `personal_assistant.read`    |
| `PATCH`           | `/api/personal-assistant/settings`                                       | Update assistant settings              | `personal_assistant.manage`  |
| `GET`             | `/api/personal-assistant/usage`                                          | Get usage statistics                   | `personal_assistant.read`    |
| `POST`            | `/api/personal-assistant/feedback`                                       | Submit feedback on a response          | `personal_assistant.execute` |
| `POST`            | `/api/personal-assistant/context-help`                                   | Get contextual help                    | `personal_assistant.read`    |
| **Conversations** |                                                                          |                                        |                              |
| `GET`             | `/api/personal-assistant/conversations`                                  | List conversations                     | `personal_assistant.execute` |
| `POST`            | `/api/personal-assistant/conversations`                                  | Create a conversation                  | `personal_assistant.execute` |
| `PATCH`           | `/api/personal-assistant/conversations/[id]`                             | Update conversation                    | `personal_assistant.execute` |
| `DELETE`          | `/api/personal-assistant/conversations/[id]`                             | Delete conversation                    | `personal_assistant.execute` |
| `GET`             | `/api/personal-assistant/conversations/[id]/messages`                    | List messages in conversation          | `personal_assistant.read`    |
| `POST`            | `/api/personal-assistant/conversations/[id]/messages/[messageId]/cancel` | Cancel a streaming message             | `personal_assistant.execute` |
| `POST`            | `/api/personal-assistant/conversations/[id]/messages/[messageId]/retry`  | Retry a failed message                 | `personal_assistant.execute` |
| **Routines**      |                                                                          |                                        |                              |
| `GET`             | `/api/personal-assistant/routines`                                       | List routines                          | `personal_assistant.read`    |
| `POST`            | `/api/personal-assistant/routines`                                       | Create/update a routine                | `personal_assistant.manage`  |
| `GET`             | `/api/personal-assistant/routines/[id]`                                  | Get a specific routine                 | `personal_assistant.manage`  |
| `PATCH`           | `/api/personal-assistant/routines/[id]`                                  | Update a routine                       | `personal_assistant.manage`  |
| `DELETE`          | `/api/personal-assistant/routines/[id]`                                  | Delete a routine                       | `personal_assistant.manage`  |
| `POST`            | `/api/personal-assistant/routines/[id]/toggle`                           | Enable/disable a routine               | `personal_assistant.manage`  |
| `GET`             | `/api/personal-assistant/routines/[id]/executions`                       | Get routine execution history          | `personal_assistant.read`    |
| `POST`            | `/api/personal-assistant/routines/run`                                   | Manually trigger a routine             | `personal_assistant.execute` |
| **Approvals**     |                                                                          |                                        |                              |
| `GET`             | `/api/personal-assistant/approvals`                                      | List pending approvals                 | `personal_assistant.read`    |
| `POST`            | `/api/personal-assistant/actions/[id]/approve`                           | Approve an action                      | `personal_assistant.execute` |
| `POST`            | `/api/personal-assistant/actions/[id]/reject`                            | Reject an action                       | `personal_assistant.execute` |
| **Opportunities** |                                                                          |                                        |                              |
| `GET`             | `/api/personal-assistant/opportunities`                                  | List opportunities                     | `personal_assistant.read`    |
| `PATCH`           | `/api/personal-assistant/opportunities/[id]`                             | Update opportunity status              | `personal_assistant.manage`  |
| **Privacy**       |                                                                          |                                        |                              |
| `GET`             | `/api/personal-assistant/privacy`                                        | Get privacy settings                   | `personal_assistant.manage`  |
| `DELETE`          | `/api/personal-assistant/privacy`                                        | Delete all personal data               | `personal_assistant.manage`  |
| `GET`             | `/api/personal-assistant/privacy/retention`                              | Get retention policy                   | `personal_assistant.manage`  |
| `PATCH`           | `/api/personal-assistant/privacy/retention`                              | Update retention policy                | `personal_assistant.manage`  |
| **Audit**         |                                                                          |                                        |                              |
| `GET`             | `/api/personal-assistant/audit`                                          | Get audit log                          | `personal_assistant.audit`   |
| `GET`             | `/api/personal-assistant/audit/export`                                   | Export audit log                       | `personal_assistant.audit`   |
| **Diagnostics**   |                                                                          |                                        |                              |
| `GET`             | `/api/personal-assistant/integrations/[integration]/diagnostics`         | Run integration diagnostics            | `personal_assistant.manage`  |

***

## 4. Chat

### Send a Message

The chat endpoint is the core of Livia. It accepts a message and returns either a **streaming Server-Sent Events (SSE)** response or a **standard JSON** response.

```bash theme={null}
POST /api/personal-assistant/chat
Content-Type: application/json
```

**Request Body:**

| Field                          | Type        | Required | Description                                                                                                             |
| ------------------------------ | ----------- | -------- | ----------------------------------------------------------------------------------------------------------------------- |
| `message`                      | `string`    | ✅        | The user's message                                                                                                      |
| `requestedInteractionLanguage` | locale code | ❌        | Explicitly choose Livia's response language for this conversation; independent from the interface locale                |
| `conversationId`               | `string`    | ❌        | Continue an existing conversation                                                                                       |
| `stream`                       | `boolean`   | ❌        | Return SSE stream. Default: `false`                                                                                     |
| `context`                      | `object`    | ❌        | Current route, query/hash, active tabs, transient UI states, safe actions, and optional explicitly consented screenshot |

**Example (non-streaming):**

```json theme={null}
{
  "message": "Summarize my top 3 open conversations from this week",
  "requestedInteractionLanguage": "en",
  "conversationId": "conv_abc123",
  "context": {
    "contextRoute": "/analytics?period=7d#response-performance",
    "metadata": {
      "activeTab": "overview"
    }
  }
}
```

Livia keeps the interaction language stable across the conversation. Short
ambiguous replies such as “ok” do not replace that choice. Interface labels
continue to use the account's interface locale.

Route and integration guidance is generated from verified product teachings.
If a route, action, or integration capability cannot be verified, Livia
reports that limitation rather than inventing a label, link, or executable
action.

**Example (streaming):**

```json theme={null}
{
  "message": "Write a draft response to the enterprise proposal from Acme Corp",
  "stream": true
}
```

### Streaming Response Format (SSE)

When `stream: true`, the endpoint returns `Content-Type: text/event-stream`.

**Events:**

| Event   | Data                                           | Description                  |
| ------- | ---------------------------------------------- | ---------------------------- |
| `chunk` | `{ "delta": "partial text" }`                  | Incremental text chunk       |
| `done`  | Full result object                             | Final response with metadata |
| `error` | `{ "code": "CHAT_FAILED", "retryable": true }` | Error occurred               |

**Heartbeat:** A `: heartbeat` comment is sent every 15 seconds to keep the connection alive.

**Timeout:** Streams are automatically closed after 90 seconds.

**TypeScript (streaming):**

```ts theme={null}
const response = await fetch('/api/personal-assistant/chat', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    message: 'What are my priority tasks for today?',
    stream: true,
  }),
});

const reader = response.body!.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  
  const text = decoder.decode(value);
  const lines = text.split('\n');
  
  for (const line of lines) {
    if (line.startsWith('data: ')) {
      const data = JSON.parse(line.slice(6));
      console.log(data);
    }
  }
}
```

**Rate Limiting:** The chat endpoint enforces plan-based rate limits. Rate limit headers are included in every response:

* `X-RateLimit-Limit`
* `X-RateLimit-Remaining`
* `X-RateLimit-Reset`

***

## 5. Conversations

Livia maintains **persistent conversation history**. Each conversation is a thread of messages.

### List Conversations

```bash theme={null}
GET /api/personal-assistant/conversations
```

Returns all conversations for the authenticated user, ordered by last activity.

### Create a Conversation

```bash theme={null}
POST /api/personal-assistant/conversations
Content-Type: application/json
```

### Get Messages in a Conversation

```bash theme={null}
GET /api/personal-assistant/conversations/{conversationId}/messages
```

### Cancel a Streaming Message

If a streaming response is in progress and you want to stop it:

```bash theme={null}
POST /api/personal-assistant/conversations/{conversationId}/messages/{messageId}/cancel
```

### Retry a Failed Message

```bash theme={null}
POST /api/personal-assistant/conversations/{conversationId}/messages/{messageId}/retry
```

***

## 6. Routines

**Routines** are automated tasks that run on a schedule. Livia can execute routines automatically or on demand.

### List Routines

```bash theme={null}
GET /api/personal-assistant/routines
```

**Response:**

```json theme={null}
{
  "items": [
    {
      "id": "routine_abc123",
      "name": "Daily Leads Summary",
      "description": "Every morning, summarize new leads from the last 24 hours",
      "enabled": true,
      "schedule": "0 9 * * 1-5",
      "lastRunAt": "2025-01-15T09:00:00.000Z",
      "nextRunAt": "2025-01-16T09:00:00.000Z"
    }
  ]
}
```

### Create/Update a Routine

```bash theme={null}
POST /api/personal-assistant/routines
Content-Type: application/json
```

### Toggle a Routine

Enable or disable a routine without deleting it:

```bash theme={null}
POST /api/personal-assistant/routines/{routineId}/toggle
```

### Get Execution History

```bash theme={null}
GET /api/personal-assistant/routines/{routineId}/executions
```

Returns the last N executions of a routine, including status (success/failed) and output.

### Run a Routine Manually

```bash theme={null}
POST /api/personal-assistant/routines/run
Content-Type: application/json
```

**Request Body:**

```json theme={null}
{
  "routineId": "routine_abc123"
}
```

***

## 7. Approvals

Some actions proposed by Livia require your **explicit approval** before execution. The approvals system gives you full control over automated actions.

### List Pending Approvals

```bash theme={null}
GET /api/personal-assistant/approvals
```

**Response:**

```json theme={null}
{
  "approvals": [
    {
      "id": "approval_xyz",
      "actionType": "send_email",
      "description": "Send follow-up email to John Smith at Acme Corp",
      "payload": {
        "to": "john@acme.com",
        "subject": "Follow-up on Enterprise Proposal",
        "body": "..."
      },
      "createdAt": "2025-01-15T14:30:00.000Z"
    }
  ]
}
```

### Approve an Action

```bash theme={null}
POST /api/personal-assistant/actions/{approvalId}/approve
```

The action executes immediately upon approval.

### Reject an Action

```bash theme={null}
POST /api/personal-assistant/actions/{approvalId}/reject
```

The action is discarded. You can optionally provide a reason.

***

## 8. Opportunities

Livia surfaces **business opportunities** — AI-identified insights from your conversation data, contacts, and integrations.

### List Opportunities

```bash theme={null}
GET /api/personal-assistant/opportunities
```

### Update an Opportunity

Mark an opportunity as actioned, dismissed, or in-progress:

```bash theme={null}
PATCH /api/personal-assistant/opportunities/{opportunityId}
Content-Type: application/json
```

**Request Body:**

```json theme={null}
{
  "status": "actioned"
}
```

***

## 9. State & Capabilities

### Get Assistant State

Returns the current state of Livia, including context, integrations status, and active features.

```bash theme={null}
GET /api/personal-assistant/state
```

### Get Capabilities

Returns the list of actions and features available to the assistant based on your plan and configured integrations.

```bash theme={null}
GET /api/personal-assistant/capabilities
```

**Response:**

```json theme={null}
{
  "chat": true,
  "routines": true,
  "opportunities": true,
  "audit": true,
  "integrations": {
    "gmail": true,
    "calendar": false,
    "slack": true
  }
}
```

***

## 10. Privacy & Retention

You have full control over the data Livia stores.

### Get Privacy Settings

```bash theme={null}
GET /api/personal-assistant/privacy
```

### Delete All Personal Data

Permanently deletes all conversation history, routine data, and personal context stored by the assistant.

```bash theme={null}
DELETE /api/personal-assistant/privacy
```

> ⚠️ **This action is irreversible.** All conversation history and personal data will be permanently deleted.

### Get Retention Policy

```bash theme={null}
GET /api/personal-assistant/privacy/retention
```

### Update Retention Policy

```bash theme={null}
PATCH /api/personal-assistant/privacy/retention
Content-Type: application/json
```

**Request Body:**

```json theme={null}
{
  "retentionDays": 30
}
```

***

## 11. Audit Log

Every action Livia takes is logged for accountability and review.

### Get Audit Log

```bash theme={null}
GET /api/personal-assistant/audit
```

Supports pagination and date filtering via query parameters.

### Export Audit Log

Download the full audit log as a file:

```bash theme={null}
GET /api/personal-assistant/audit/export
```

The response is a downloadable file (CSV or JSON format, based on implementation).

***

## 12. Settings & Usage

### Update Settings

Configure Livia behavior:

```bash theme={null}
PATCH /api/personal-assistant/settings
Content-Type: application/json
```

### Get Usage

View your Livia usage statistics (message count, routine executions, etc.):

```bash theme={null}
GET /api/personal-assistant/usage
```

**Response:**

```json theme={null}
{
  "messagesThisMonth": 142,
  "routineExecutions": 38,
  "opportunitiesSurfaced": 12,
  "plan": {
    "messageLimit": 500,
    "routineLimit": 10
  }
}
```

***

## 13. Integration Diagnostics

Run diagnostics on a specific integration to verify connectivity and permissions:

```bash theme={null}
GET /api/personal-assistant/integrations/{integration}/diagnostics
```

**Path Parameters:**

| Parameter     | Type     | Description                                                 |
| ------------- | -------- | ----------------------------------------------------------- |
| `integration` | `string` | Integration identifier (e.g., `gmail`, `slack`, `calendar`) |

***

## 14. Error Handling

| Error                                       | Cause                                   | How to Fix                                 |
| ------------------------------------------- | --------------------------------------- | ------------------------------------------ |
| `Livia - 360 Assistant requires a PRO plan` | Plan does not include Livia             | Upgrade your plan                          |
| `Rate limit exceeded`                       | Too many chat requests                  | Wait for the rate limit window to reset    |
| `REQUEST_CANCELED`                          | Client disconnected during stream       | The user canceled — no action needed       |
| `CHAT_FAILED`                               | Internal error during chat              | Retry the request                          |
| `Routine not found`                         | Invalid routine ID                      | Verify the routine ID exists               |
| `Approval not found`                        | Invalid approval ID or already resolved | Check if the approval was already actioned |

### Status Codes

| Status | Meaning                                      |
| ------ | -------------------------------------------- |
| `200`  | Request successful                           |
| `201`  | Resource created                             |
| `400`  | Invalid request body                         |
| `401`  | Not authenticated                            |
| `403`  | Insufficient permissions or plan restriction |
| `404`  | Resource not found                           |
| `429`  | Rate limit exceeded                          |
| `500`  | Internal server error                        |

***

## 15. Best Practices

### Streaming Chat

* Always implement client-side disconnect handling to call the **cancel** endpoint if the user navigates away
* Show a loading indicator while waiting for the first `chunk` event
* Display text progressively as `chunk` events arrive for a better UX

### Routines

* Start with simple routines (e.g., daily summaries) before complex multi-step automations
* Use the **execution history** to verify routines are running correctly before enabling new ones
* Set up routines to run during off-peak hours (early morning) to avoid competing with interactive usage

### Approvals

* Check pending approvals regularly — time-sensitive actions may expire
* Review the action `payload` carefully before approving, especially for actions that send external communications
* Use the `reject` endpoint to provide feedback that helps the assistant learn your preferences

### Privacy

* Set a retention policy that matches your organization's data governance requirements
* Export the audit log periodically for compliance records
* Use `DELETE /privacy` as part of offboarding workflows for departing team members
