System Foundation

Destiny Ecosystem

Destiny is an industrial-grade, multi-tenant telephony orchestration platform. It is designed to bridge the gap between high-scale communication (Voice/SMS) and advanced AI synthesis. Whether handling thousands of concurrent outbound appointments or managing sophisticated inbound IVR trees, Destiny provides a single source of truth for all communication events.

The Neural Core

Google Cloud Chirp 3 HD (Leda)

Conversational Prosody

The "Leda" engine (en-US-Chirp3-HD-Leda) is not just another TTS. It is a neural model trained specifically for conversational high-fidelity. It handles nuances, breathiness, and emotional cadence that standard robotic voices (like Twilio's default) lack.

Pre-Synthesis Optimization: To eliminate "AI lag" during calls, Destiny's Worker pre-synthesizes all possible script branches into high-quality .ulaw buffers stored in S3 before the call even begins.

ENGINE SPECS

  • Model: Chirp 3 HD
  • Persona: Leda
  • Format: 8kHz u-law
  • Latency: <50ms (Pre-cached)
Logic definition

Destiny-Script DSL

The Destiny-Script is a high-level domain language used by Admins to define complex conversation trees. These are saved in Script.content and parsed into a flowJson structure in the database.

// [node_name] defines a conversational state
[start]
Hi {{firstName}}, this is Destiny calling from {{tenantName}}. How are you?
-> 1, "good", "great": positive_node
-> 2, "bad", "not well": negative_node

[positive_node]
That's wonderful! I'm calling to confirm your appointment.
-> END

Key Features:

  • Dynamic Injection: Variables like {{firstName}} are resolved from the Contact or Campaign context at call-time.
  • Multimodal Input: Transitions support both DTMF (keypad) and NLP-based Speech Keyword matching.
  • Persistence: Every script change generates a unique hash, ensuring the Worker knows when to re-prime the S3 audio cache.
Execution Flow

Outbound Campaign Pipeline

Campaign "Start" Triggered
API: Create "Queued" Calls in DB
API: Dispatch Jobs to "destiny_calls" Queue
Worker: TTS Pre-Synthesis (Leda Engine)
Worker: Initiate Twilio Outbound Dial
Twilio: AMD (Answering Machine Detection)
Sarah Interacts / SMS Fallback if No-Answer

Technical Safeguards:

Rate Limiting: Redis manages the concurrency of the destiny_calls queue to prevent hitting Twilio's CPS (Calls Per Second) limits.

Retry Logic: Failed calls (Busy, No-Answer) are automatically re-queued with exponential backoff (e.g., 10 mins, 30 mins, 2 hours).

Smart Routing

Inbound Intelligence Flow

Incoming Call to Provisioned Number
Twilio Webhook: /twilio/inbound
API: Resolve Tenant by E.164 Mapping
API: Fetch Tenant's Latest Master Script
Sarah Greet: Intelligent IVR Menu
Action: Route to Online Agents / "transfer" node
Infrastructure

Worker & Queue Architecture

BullMQ Worker

Located in apps/worker/src/worker.ts, this is the heavy lifter of the system. It handles two primary job types:

  • prime_script: Regenerates S3 audio for an entire script.
  • call_job: Handles the 5-step call lifecycle (Vars snapshot -> TTS Gen -> Twilio Dial -> SID Update -> Logging).

Redis (Queue State)

Acts as the message broker. Stores the state of every call attempt, ensuring that if the API crashes, the Worker can still resume pending dials once it's back online.

Database Schema

Prisma Data Architecture

The schema is built for high-performance multi-tenancy. Key relations:

Model Critical Role
Tenant Global root of isolation. All data (Users, Calls, Scripts) must have a tenantId.
Call The ledger of communication. Tracks twilioSid, recordingUrl, and outcome.
CallEvent Immutable log of every sub-second event (e.g. tts.generate.start, twilio.status).
PhoneNumber Provisioned E.164 assets linked to Twilio SIDs for Inbound routing.
Governance

Roles & Subscription Plans

Subscription Tiers

  • OUTBOUND Focus on massive campaigns and lead outreach.
  • INBOUND Focused on IVR, routing, and live agent connectivity.
  • FULL Unrestricted access to both communication vectors.

Account Permissions

  • AGENT: Dashboard viewing, recording playback, taking live transfers.
  • ADMIN: Campaign creation, Script editing, User management.
  • SUPERADMIN: System-wide access to /system to manage all Tenants and global infra.
Intelligence

Real-time Analytics Engine

The API (analytics.ts) provides high-speed aggregation for the dashboard:

  • Dashboard Summary: Calculates Answer Rate, Confirmation Rate, and Escalation metrics over flexible time windows (24h, 7d, 30d).
  • Event Stream: A live feed of CallEvents allows admins to "debug" a live call while it is happening.
  • Recording Presigning: Audio files in S3 are protected; the API generates temporary 1-hour signed URLs for the browser to play them securely.
Operations

Troubleshooting Knowledge Base

Issue Root Cause Diagnosis Resolution Path
"Sarah" sounds robotic Google TTS Leda fallback triggered. Verify GOOGLE_APPLICATION_CREDENTIALS path in .env.
Inbound calls hit busy signal Number not mapped in PhoneNumber table. Check E.164 format and Tenant assignment in /system.
Recordings are missing URLs S3 upload from Twilio failed. Check destiny-recordings bucket permissions and CORS.
500 Error on Dashboard API can't reach Redis or MariaDB. Check docker ps status for destiny_redis.