Spec

3.20.1 Omnichannel Communications Framework

Specification, workflow, and technical reference for the omnichannel communications framework module.

TEXTBOOK SPECIFICATION

1. The Pattern

Every organisation uses different communication channels. Some use SMS as primary, others WhatsApp or Email. Some have a legacy phone system that must be forwarded through Twilio. The framework mirrors the Legacy Data Integration Framework (4.0): a generic template defines how RAIA (Real estate Artificial Intelligence Agent) analyses and maps all communication channels in an organisation into the Universal Inbox, and per-organisation channel maps document each org's specific setup.

The pipeline: Channel Discovery → Ingress Adapter → Normalisation → Universal Inbox → Concierge Triage → Outbound Queue → Reply Adapter.

2. Pipeline Architecture

CHANNEL DISCOVERY 📞 Voice / SMS (Twilio) 💬 WhatsApp (Meta API) 📧 Email (IMAP/SMTP) 📸 IG / TikTok / X INGRESS ADAPTERS Webhook verifiers (HMAC) IMAP poller / OAuth Graph API long-poll Attachment eager-download Dedup (sha256 hash) NORMALISATION Canonical message schema PII tier classification Turn assembly (buffer timer) → tbl_conversations → tbl_messages CONCIERGE TRIAGE Isolated triage LLM Code-based escalation rules Confidence gating OUTBOUND QUEUE tbl_outbound_queue Channel dispatcher Circuit breaker REPLY COMPOSER Privileged LLM (templates) HITL draft review Legend: Source Ingress Normalise Concierge Queue Reply
Channel Ingress Protocol Latency Outbound Mechanism Security Gate Existing Doc
📞 Phone Call Twilio Voice webhooks Real-time (sub-second) Twilio Voice API + Gather X-Twilio-Signature HMAC 3.13
💬 SMS Twilio SMS webhook Real-time (sub-second) Twilio REST API POST /Messages X-Twilio-Signature HMAC 3.13
💬 WhatsApp Twilio/Meta webhook Real-time (sub-second) Twilio REST + template pre-approval X-Twilio-Signature HMAC —
📧 Email (Gmail) IMAP IDLE + OAuth 2.0 30s poll (batch) SMTP via Gmail API OAuth 2.0, limited scope Gmail / 2.5
📧 Email (generic) IMAP/SMTP Poll configurable SMTP SPF/DKIM/DMARC —
📸 Instagram Meta Graph API + webhooks Near-real-time Graph API POST /me/messages X-Hub-Signature HMAC —
🎵 TikTok Scraper + API poll (rate limited) Minutes (batch) API POST /message/send Bearer token, IP allow-list —
🐦 X/Twitter DM Twitter API v2 + Account Activity webhook Real-time API POST /direct_messages CRC challenge + Bearer token —
📝 Web Forms HTTP POST (JSON) → API Real-time Email/SMS reply CAPTCHA + Rate limit —
🤖 Telegram Telegram Bot webhook Real-time Telegram Bot API POST X-Telegram-Bot-Api-Secret-Token —

The Universal Inbox uses a canonical message schema. All channel adapters normalise to this:

tbl_conversations
├── conversation_id: uuid (PK)
├── org_id: uuid (FK → tbl_organisations)
├── primary_channel: enum           # twilio_sms|whatsapp|email|instagram|tiktok|x|web_form|phone|telegram
├── primary_customer_ref: text      # the customer's primary handle in the channel
├── subject: text                   # email Subject, or auto-generated
├── status: enum                    # active|pending|resolved|archived|spam
├── lawful_basis: enum              # consent|contract|legal_obligation|legitimate_interests
├── jurisdiction: text              # GB | TH | MY | VN
├── retention_expires_at: timestamptz
├── person_id: uuid (FK if resolved)
│
tbl_messages
├── message_id: uuid (PK)           # deterministic: sha256(channel + channel_msg_id)
├── conversation_id: uuid (FK)
├── channel: enum
├── channel_message_id: text        # native ID (Twilio MessageSid, IMAP UID, etc.)
├── direction: enum                 # inbound | outbound
├── from_address: text
├── to_addresses: jsonb
├── body_text: text | null
├── body_html: text | null
├── attachments: jsonb              # [{filename, mime, storage_url}]
├── pii_classification: enum        # none|contact|financial|identity|special|criminal
├── data_purpose: enum              # enquiry|tenancy|maintenance|accounts|legal|compliance|marketing
├── consent_ref: text | null
├── retention_expires_at: timestamptz
├── raw_payload: jsonb              # original ingress payload (for debugging/compliance)
├── received_at: timestamptz
│
tbl_outbound_queue
├── id: uuid (PK)
├── org_id: uuid
├── channel: enum
├── to_address: text
├── body: text
├── attachments: jsonb
├── priority: int (1-5)
├── status: enum                    # queued|sending|sent|failed|delivered
├── retry_count: int
├── last_error: text | null
├── circuit_broken_until: timestamptz | null
├── scheduled_at: timestamptz
├── delivered_at: timestamptz | null

3. Channel Discovery & Mapping

When onboarding an organisation, RAIA (Real estate Artificial Intelligence Agent) analyses all communication channels they use and maps them to the Universal Inbox. The discovery process:

  1. Audit existing channels — Identify all phone numbers, email accounts, social inboxes, messaging platforms used by the org
  2. Classify ingress type — Webhook-capable (Twilio, Meta) vs poll-only (email IMAP) vs scraper (TikTok, legacy portals)
  3. Determine forwarding — For legacy phone numbers: set up Twilio number porting or SIP forwarding → RAIA (Real estate Artificial Intelligence Agent) Twilio account. For email: set up forwarding rule or IMAP OAuth grant
  4. Create per-org channel map — One YAML file per organisation (analogous to 4.0 data mapping) documenting each channel's credentials, ingress config, and reply config
  5. Wire into Vercel frontend — Each channel appears as a tab/filter in the Universal Inbox UI

4. Per-Organisation Channel Maps

Each organisation has a channel mapping specification documenting their specific setup. The format mirrors the data integration framework (4.0) — a YAML mapping spec with credentials referenced via vault IDs.

# Channel Map — Sovereign Pilot Agency
org_id: "a0450010-0778-4000-8000-000000000010"

channels:
  voice:
    ingress:
      type: twilio_webhook
      phone_numbers:
        - "+447****2000"    # Main landline (Twilio ported)
        - "+447****2001"    # Enquiries line
      credentials: vault://rlf/twilio-auth
      forwarding:
        legacy_phone: "+4420****1234"  # Original legacy number → Twilio SIP
    outbound:
      type: twilio_voice_api
      caller_id: "+447****2000"

  sms:
    ingress:
      type: twilio_webhook
      numbers: ["+447****2000", "+447****2001"]
    outbound:
      type: twilio_rest_api

  email:
    ingress:
      type: imap_oauth
      accounts:
        - address: "enquiries@rentlondonflat.com"
          provider: gmail
          credentials: vault://rlf/gmail-enquiries
        - address: "service@rentlondonflat.com"
          provider: gmail
          credentials: vault://rlf/gmail-service
      poll_interval_seconds: 30
    outbound:
      type: smtp
      from: "raia@rentlondonflat.com"

  whatsapp:
    ingress:
      type: whatsapp_business_api
      phone_number_id: "123456789"
      credentials: vault://rlf/meta-whatsapp
    outbound:
      type: whatsapp_api

5. Concierge Triage & Reply

After red-teaming across 3 LLM perspectives (Systems Architect, Security & Compliance, AI Agent Developer), the following design is mandated:

REJECTED: Monolithic LLM
  • Single LLM sees raw user input + has tool access → prompt injection RCE
  • LLM decides escalation → attacker overrides
  • No dedup → double billing, double replies
ACCEPTED: Dual-LLM Isolation
  • Isolated triage LLM — read-only, no tools, outputs structured JSON only
  • Code-based escalation rules — LLM provides features, code decides
  • Confidence gating — low confidence → always escalate to human
REQUIRED: Outbound Queue
  • tbl_outbound_queue prevents reply race conditions
  • Per-channel rate limiting + circuit breaker
  • Delivery status tracking per message

Triage Decision Flow

Dedup Check sha256 hash Turn Assembly Buffer: 2s SMS 5s Email / 1s webhook Isolated Triage LLM No tools JSON output Code Escalation Hard rules (security) Soft rules (confidence) Auto-Reply LLM + templates Human Ticket + context summary

Escalation Rules (Code-Based)

RuleTypeAction
Security keywords / CVE / "data breach"HardHuman ticket (urgent)
Financial data detected (card, bank)HardHuman ticket (urgent)
PII detected (passport, NI number)HardHuman ticket + PII audit log
LLM confidence < 0.5HardHuman ticket
Urgency >= 4 (LLM classification)HardHuman ticket (urgent)
Negative sentiment + confidence < 0.7SoftHuman ticket
"manager" / "human" / "escalate" keywordsSoftHuman ticket
First message from unknown senderSoftHuman ticket
FAQ exact match (cosine > 0.9)AutoAuto-reply (no LLM)
Status check / simple account queryAutoAuto-reply (LLM, high conf)

6. Security & Compliance Gates

Red team findings that are now mandated:

GateRequirementSource Finding
🔴 Webhook signature verificationEvery webhook endpoint MUST verify HMAC signature before processing. Twilio (X-Twilio-Signature), Meta (X-Hub-Signature), Telegram (X-Telegram-Bot-Api-Secret-Token)Security Architect, Finding 1
🔴 Per-org credential vaultCredentials stored in separate encrypted table, per-org KMS envelope. Channel configs reference vault IDs, never inline credentialsSecurity Architect, Finding 5
🔴 Dual-LLM isolationTriage LLM is read-only with no tool access. Outputs structured JSON only. Code-based escalation rules use LLM features, not LLM decisionsAI Agent Developer, Finding 1.1
🔴 Message idempotencysha256(channel + channel_message_id) dedup key with UNIQUE constraint. Webhook at-least-once delivery is absorbedSecurity Architect, Finding 7
🟡 PII classification on ingressEvery message gets pii_classification (none/contact/financial/identity/special/criminal) + data_purpose + consent_refSecurity & Compliance, Section 1
🟡 Retention expiryPer-channel retention policies: tenancy-linked messages 6 yrs, enquiries 2 yrs, spam 90 daysSecurity & Compliance, Section 2
🟡 Scraper PII quarantineScraper-sourced PII goes to quarantine table, not live inbox. Human compliance officer must approveSecurity & Compliance, Section 3

7. Existing Related Pages

The following existing docs are children of this framework — they document specific channel implementations:

8. Red Team Consensus Summary

Three independent LLM perspectives critiqued the Universal Inbox design. Key findings integrated into this spec:

PerspectiveCritical FindingResolution in v1.0
Systems ArchitectNo outbound queue → reply race conditions; no thread merging; credential storage risktbl_outbound_queue with circuit breaker; thread merging backfill; vault-only credential refs
Security & Compliance🔴 exec_sql callable by anon users (RCE); 33 tables with RLS but no policies; no PII classification on messagesPII classification + data_purpose + consent_ref on every message; retention policies applied
AI Agent DeveloperMonolithic LLM = prompt injection RCE; LLM must not decide escalation; no context window strategyDual-LLM isolation (triage read-only, code decides); structured JSON only; hierarchical summarization

Repository Code

The live codebase implementation for this textbook logic sits within the following repository folder:

Repository Code

The live codebase implementation for this textbook logic sits within the following repository folder: