# System Architecture — AI Phone Assistant SaaS

## 1. High-Level Multi-Tenant Architecture

```mermaid
flowchart TD
    Caller["PSTN Caller / SIP Trunk"] -->|Inbound Call / *72 Forward| Twilio["Twilio Programmable Voice"]
    Twilio -->|POST /twilio/inbound-call| Engine["Call Engine (Node.js / Express 5 / WS)"]
    Twilio <-->|Bi-Directional 8kHz mulaw WebSocket| MediaWS["MediaStream Handler (/media-stream)"]

    subgraph VoicePipeline["Sub-Second Streaming Voice Pipeline"]
        MediaWS -->|PCM/mulaw Audio Stream| Deepgram["Deepgram Nova-3 Streaming STT + VAD"]
        Deepgram -->|SpeechStarted Barge-In Signal| MediaWS
        Deepgram -->|Final Utterance| Orchestrator["AI Orchestrator (gpt-4o-mini Streaming)"]
        Orchestrator <-->|Hybrid Vector + Keyword Search| RAG["RagService (OpenAI Embeddings + MongoDB)"]
        Orchestrator <-->|In-Call Tool Execution| Tools["Calendar Booking / Warm Transfer / Policy Lookup"]
        Orchestrator -->|Sentence Chunk Stream| TTS["ElevenLabs Turbo v2.5 + Deepgram Aura Failover"]
        TTS -->|8kHz mulaw Audio Frames| MediaWS
    end

    subgraph PostCallPipeline["Post-Call Intelligence Pipeline"]
        MediaWS -->|Call Hangup| PostCall["PostCallService"]
        PostCall -->|Structured JSON Summary & Outcome Tag| Mongo[("MongoDB Multi-Tenant Store")]
        PostCall -->|Retry w/ Exponential Backoff| Webhooks["CRM Webhooks (HubSpot / Zapier / Make)"]
        PostCall -->|Transactional Email| Email["NotificationService (SMTP)"]
    end

    Dashboard["React SaaS Dashboard (Vite + Tailwind)"] <-->|JWT Auth + RBAC + Socket.io| Engine
    Landing["Public Marketing Site"] -->|Signup / Trial Onboarding| Dashboard
```

---

## 2. Real-Time Call Lifecycle & Barge-In Sequence

```mermaid
sequenceDiagram
    participant Caller as Caller (PSTN / Browser)
    participant Twilio as Twilio Media Stream
    participant WS as MediaStream Handler
    participant DG as Deepgram Nova-3 STT
    participant AI as AI Orchestrator (LLM + RAG)
    participant TTS as ElevenLabs / Aura TTS

    Caller->>Twilio: Dials Business Number
    Twilio->>WS: WebSocket Connected + start event (customParameters)
    WS->>AI: Lookup Company by E.164 Number & Build Domain Prompt
    WS->>TTS: Synthesize Personalized Welcome Greeting
    TTS-->>Twilio: Stream 8kHz mulaw Greeting Audio
    Caller->>Twilio: Speaks ("I need an emergency dental appointment tomorrow")
    Twilio->>DG: Forward 8kHz mulaw frames
    Note over DG,WS: If AI is speaking, SpeechStarted triggers immediate Twilio "clear" (Barge-In <100ms)
    DG-->>WS: Final Transcript
    WS->>AI: Retrieve Top-4 RAG Chunks + Stream LLM Response
    AI->>AI: Execute check_availability / book_appointment tool
    AI-->>TTS: Stream Sentence 1 ("I have 10:00 AM or 2:00 PM open tomorrow...")
    TTS-->>Twilio: Stream 8kHz mulaw Audio Immediately
    Caller->>Twilio: Hangs up
    Twilio->>WS: stop event
    WS->>AI: Run PostCallService (AI Summary, Sentiment Score, Outcome Tag, CRM Webhook)
```

---

## 3. Repository & Service Structure

- **`services/call-engine`** (`Port 3000`):
  - `src/index.ts`: Express 5 HTTP server, WebSocket upgrade router (`/media-stream`), Socket.IO live dashboard feed, security headers, and rate limiters.
  - `src/websocket/mediaStream.handler.ts`: Bi-directional Twilio Media Stream state machine, VAD interruption (barge-in), silence timeout detection, and live tool invocation.
  - `src/services/`:
    - `aiOrchestrator.ts`: Domain-scoped prompt builder, streaming LLM orchestration, and in-call tool definitions.
    - `ragService.ts`: Document chunker, OpenAI `text-embedding-3-small` vector indexer, and hybrid cosine + keyword search engine.
    - `websiteCrawlerService.ts`: SSRF-guarded URL crawler that extracts business details and drafts an AI receptionist persona + 6 industry templates.
    - `postCallService.ts`: Post-call AI summary, sentiment analysis, outcome classification (`booked_appointment`, `lead_qualified`, `faq_resolved`, `escalated_transfer`, `general_inquiry`), and exponential-backoff webhook delivery.
    - `elevenlabsService.ts` & `deepgramService.ts`: Streaming STT and dual-provider TTS with automatic failover.
- **`services/react-dashboard`** (`Port 5173`):
  - Multi-tenant management portal with 5-Step Guided Onboarding Wizard, 1-Click Website-to-Agent generator, Browser Voice Simulator, Call Analytics & Summaries, Knowledge Base RAG uploader, Calendar/Appointments manager, CRM Webhooks, and Billing/Team/GDPR Center.
- **`services/landing-page`** (`Port 5174`):
  - Public marketing site with 6 Industry Vertical playbooks, Integrations showcase, Transparent Pricing, FAQ, and GDPR/AI Act & DPA legal modals.
