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

# Architecture

> How requests move through auth, intent detection, action execution, and escalation.

# System architecture

## High-level flow

```txt theme={null}
User/Widget -> Chat API or WebSocket -> Auth middleware -> Intent service
          -> Action service -> External integration (e.g. Shopify)
          -> Response formatter -> Conversation storage -> Client response
                           \-> Escalation service -> Ticket + audit logs
```

## Core backend modules

| Module                           | Responsibility                                                     |
| -------------------------------- | ------------------------------------------------------------------ |
| `middleware/auth.ts`             | Tenant JWT/API key auth for widget/chat routes.                    |
| `middleware/admin-auth.ts`       | Supabase auth + tenant mapping for admin routes.                   |
| `routes/chat.ts`                 | Message processing, conversation read, manual escalation.          |
| `routes/admin.ts`                | Tenant admin operations: stats, tickets, intents, settings, audit. |
| `services/intent.service.ts`     | Detects intent and required entities from user messages.           |
| `services/action.service.ts`     | Executes configured intent actions.                                |
| `services/escalation.service.ts` | Creates escalation tickets and user-facing escalation text.        |
| `ws/websocket.ts`                | Real-time chat protocol with optional streaming responses.         |

## Tenant isolation model

Every request is scoped to `tenantId`, including:

* conversations
* tickets
* intents
* integrations
* audit logs
* settings

This prevents cross-tenant data leakage and keeps all analytics and operations tenant-safe.

## Request lifecycle (Chat HTTP)

1. Auth middleware validates token and attaches `auth` context.
2. Message is written to `messages` table.
3. Recent conversation history is loaded for context.
4. Intent is detected with confidence score + entities.
5. If confidence low or missing intent -> escalation workflow.
6. Otherwise action executes and response is formatted.
7. Assistant message and metadata are persisted.
8. API returns assistant response + metadata.

## Request lifecycle (Admin HTTP)

1. Supabase token is validated.
2. User is mapped to tenant via `admin_users`.
3. Route handler loads/updates tenant-scoped records.
4. Mutations write audit log entries.
5. Response returns filtered, tenant-scoped objects.

## Real-time lifecycle (WebSocket)

1. Client connects with token query string.
2. Server authenticates token and replies `connected`.
3. Client sends `message`, `typing`, `history`, or `ping` events.
4. Server streams or returns message responses.
5. Heartbeat (`ping/pong`) keeps sessions healthy.
