Skip to content
shhhivam12Public

About

EasyEV agentic EV decision room powered by Agora voice and real-time decision tools

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

136 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

EasyEV AI - Autonomous Multimodal EV Discovery, Negotiation & Action Platform



EasyEV Conversational AI Guide
Meet Clay • India's First Autonomous Indic Conversational EV Advisor

Agora Conversational AI Agora RTC & RTM Sarvam AI Indic Voice Anthropic MCP Protocol
OpenAI GPT-4o Azure Neural Speech Three.js 3D Node.js Runtime


Real-Time Voice Pipeline & SD-RTN Agora Real-Time Voice Pipeline × Sovereign Indic Voice Synthesis Sarvam AI Sovereign Indic Voice

Sub-300ms Conversational Voice over Agora SD-RTN Edge Network with Sovereign Indic Hindi Synthesis via Sarvam bulbul:v3


From initial voice discovery to verified dealership test-drive execution.
Bridging India's electric mobility transition through full-duplex conversational voice AI, interactive 3D virtual showrooms, dual-AI vehicle debate arenas, autonomous dealer onboarding, and real-time decision tooling.

Platform Experiences • Innovations • Project Structure • MCP Tools • Architecture • API Reference • Data Models • Quickstart • Testing • Deployment • Security • Troubleshooting


Evaluation Compliance

Hackathon Submission Deliverables

This repository fulfills all seven mandatory submission criteria for the Adaptive AI Sales and Negotiation Agent Hackathon Track:

# Submission Requirement Implementation & Asset Location in Repository Verification Status
1 Working Prototype Full-duplex local dev server on port 4173 (npm run dev), Render IaC (render.yaml), multi-container docker-compose.yml, and 5 operational browser experiences (/, /showroom/, #compare, #for-dealers, /rep.html). Operational & Verified
2 GitHub Repository Public open-source repository with full version history, automated test suites, and clean documentation: shhhivam12/easyev. Live on GitHub
3 Project Description Comprehensive Executive Overview, strategic problem analysis, legacy portal comparison matrix, and end-to-end User Journey. Documented
4 Demo Video Recorded end-to-end consultation demo: assets/easyev-hero-consultation.mp4 (H.264/AAC), assets/easyev-hero-consultation.webm, and live animated mascot visual. Included in Repo
5 Technical Architecture 6 complete Mermaid architectural specifications: High-Level Topology, Level 1 DFD, User Journey, Voice & MCP Sequence, Dealer FSM, and Specialist Escalation. Fully Visualized
6 Agora Technology Integration In-depth breakdown of Agora Conversational AI SDK & RTC/RTM 2.x, dual client/server Voice Activity Detection (VAD), Sub-300ms Latency Budget Waterfall, dynamic token generation, and channel security isolation. Production Integrated
7 Pitch Deck Official 12-slide Round II Idea & Technical Presentation deck: PPT.pdf and PowerPoint source file output/EasyEV_AI_Mentor_Discussion.pptx. Included in Repo

Strategic Context

Executive Overview

The transition to electric vehicles in India is hindered by significant consumer friction:

  1. Range and Operating Uncertainty: Difficulty reconciling real-world degradation, passenger payload, air conditioning load, and regional topography against certified range figures.
  2. Total Cost of Ownership (TCO) Ambiguity: Complex calculations involving state-specific subsidies, tiered electricity tariffs, and battery lifecycle expectations versus internal combustion engine (ICE) benchmarks.
  3. Fragmented Dealer Networks: Coordinating test drives across distinct original equipment manufacturers (OEMs) typically requires visiting multiple disjointed physical dealerships.
  4. Dealer Onboarding Inefficiency: Dealerships and commercial vendors frequently abandon complex digital onboarding workflows.

EasyEV solves these challenges by deploying a connected multimodal intelligence stack:

Natural Voice Discovery (Hindi / Hinglish / English)
        |
        v
Realtime Conversational AI Pipeline (Sub-300ms Barge-In)
        |
        v
Deterministic Buyer Decision Passport (Context Engine)
        |
        v
Streamable Model Context Protocol (MCP) Decision Tools
        |
        v
Interactive Visual Deal Room & 3D Virtual Showroom Stage
        |
        v
Verified CRM Integration, Calendar Sync, and Dealership Test Drive

Industry Paradigm Comparison: Legacy Portals vs. EasyEV

Capability Dimension Traditional Automotive Portals EasyEV Autonomous Platform
Discovery Interaction Static filter dropdowns and text-based chatbots Full-duplex conversational voice with sub-300ms barge-in over Agora SD-RTN
Vernacular Dialect Handling English-centric with literal machine translation Native Hindi and Hinglish with colloquial prosody via Sarvam AI bulbul:v3
Vehicle Inspection Static 2D compressed dealer photo galleries WebGL 360-degree progressive exterior spin, 4K cubemap interior panoramas, and door opening animations
Range Assessment Idealized certified figures (ARAI/NEDC) causing range anxiety Physics-derated isochrone maps factoring passenger load, AC thermal load, and topography
Comparative Evaluation Tabular raw spec grids leaving trade-offs unresolved Podcast-style Dual-AI debate arena with live telemetry meters benchmarking price, battery, and real range
Dealership Scheduling Generic lead generation forms resold to telemarketers Autonomous 15-state Cal.com scheduling with instant calendar invite and transactional email dispatch
Dealer Network Onboarding Multi-page static web forms with high drop-off rates Conversational AI Voice Copilot parsing 150+ spoken affirmations into instant verified digital certificates
Human Specialist Handoff Disconnected call centers starting from scratch Real-time session state transfer with live buyer Decision Passport and telemetry handoff

Core Technology Stack & Infrastructure Matrix

Architecture Layer Technology & Provider Primary Operational Responsibility
Real-Time Voice Streaming Agora RTC & Conversational AI Ultra-low-latency WebRTC audio streaming, SD-RTN edge distribution, sub-300ms barge-in, and client/server VAD
Indic Voice Synthesis (TTS) Sarvam AI (bulbul:v3) Sovereign Indic neural speech synthesis for Hindi and Hinglish, native cadence, Indian automotive terminology, 20+ male voices
Global Voice Fallback (TTS) Microsoft Azure Neural Speech Secondary TTS fallback using hi-IN-MadhurNeural and en-IN-NeerjaNeural
Multimodal Real-Time LLM OpenAI GPT-4o Realtime Multilingual reasoning, intent extraction, conversational turn-taking, and tool orchestration
Agent Tooling Standard Anthropic Model Context Protocol (MCP) Streamable JSON-RPC 2.0 tool execution over HTTP at /mcp with HMAC-SHA256 signature verification
Real-Time State Sync Agora RTM 2.x Sub-millisecond synchronized visual telemetry, deal room stage cards, and live debate battle meters
3D Graphics & Showroom Three.js & Pannellum WebGL 360-degree progressive exterior rotation, interior cubemap panoramas, and interactive door animations
Geospatial & Route Isochrones Mapbox GL JS & OpenChargeMap Interactive range simulation, elevation contours, live charging station discovery, and route planning
Booking & CRM Orchestration Cal.com API & HubSpot CRM Real-time dealership test-drive calendar slot resolution, automated CRM contact and deal ingestion
Autonomous Telephony & Vision Bland AI & Gemini 2.0 Flash Outbound dealer telephony confirmation and multimodal inspection of vehicle condition and charging plugs

Repository Layout

Project Structure

easyev/
├── assets/                          # Static branding, 3D assets, vehicle imagery, and media
│   ├── easyev-hero-banner.svg       # Base64-embedded Plus Jakarta Sans brand cover banner
│   ├── clay-guide-animated.webp     # Transparent animated mascot (20 fps yuva420p WebP)
│   ├── sarvam-logo.svg              # Official Sarvam AI vector mark
│   ├── agora-transparent-bg.webp    # Official Agora transparent wordmark
│   ├── screenshots/                 # High-resolution documentation captures (01-09)
│   └── vehicles/                    # Multi-category EV photography and asset manifests
├── client/                          # Client-side WebRTC and audio processing sources
│   └── agora-client.js              # Agora RTC 4.x / RTM 2.x dual-agent browser bundle source
├── data/                            # Persistent JSON file-backed database storage
│   ├── dealers.json                 # Verified dealership network registry
│   └── test-drives.json             # Test-drive booking records and FSM history
├── scripts/                         # Automated test scripts and headless verification suites
│   ├── verify-agentic.mjs           # Full-system headless browser verification pipeline
│   ├── deep-e2e-curl-test.sh        # API route regression and endpoint payload test suite
│   └── test-dealer-agent-deep.mjs   # 150+ affirmation dialect parsing unit tests
├── showroom/                        # Virtual 3D EV Showroom progressive web app
│   ├── index.html                   # 360-degree interactive viewer layout
│   ├── showroom.js                  # Three.js / Pannellum orbit controls and door triggers
│   ├── showroom.css                 # Glassmorphic showroom HUD interface styles
│   └── vehicle-catalog.js           # Multi-category 3D specification catalog
├── index.html                       # Primary EasyEV web application and consultation deal room
├── rep.html                         # Human sales specialist live escalation desk console
├── server.mjs                       # Unified Node.js application server and HTTP dispatcher
├── decision-tools.mjs               # 8 Model Context Protocol (MCP) decision tools engine
├── dealer-voice-agent.mjs           # Autonomous 4-step dealer onboarding FSM (150+ regexes)
├── test-drive-service.mjs           # Conversational temporal slot resolution and validation
├── test-drive-db.mjs                # 15-state test drive FSM data access layer
├── dealer-db.mjs                    # Dealership CRUD and geospatial query engine
├── crm-calendar.mjs                 # Cal.com calendar scheduling and HubSpot CRM connector
├── mailer.mjs                       # Transactional SMTP emailer and PDF attachment engine
├── package.json                     # Project manifest, scripts, and runtime dependencies
├── render.yaml                      # Infrastructure-as-code production deployment blueprint
└── .env.example                     # Environment variable configuration template

Five User Journeys

Platform Experiences

EasyEV structures the EV buyer and dealer lifecycle into five dedicated operational pillars:

EasyEV Landing Page Hero
Conversion Hero & Agora Real-Time Voice Showcase
EasyEV Experiences Suite
Three Ways to Find Your EV Experience Suite

1. Virtual 3D EV Showroom (/showroom/)

An interactive, browser-native 3D inspection suite presenting high-fidelity vehicle models with manufacturer-backed specifications:

  • Progressive 360-Degree Exterior Spin Viewer: Smooth drag rotation with calibrated inertia, auto-rotation, and progressive image frame loading.
  • Cubemap Interior Panoramas: Real 360-degree cabin interior exploration powered by vendored Pannellum for models such as the Tata Nexon.ev.
  • Interactive Door Animations: Dedicated multi-frame open-door view sequences for models including the Tata Nexon.ev and MG Comet EV.
  • Commercial Vehicle Body and Color Configuration: 96-frame configuration matrix for commercial vehicles (such as the TVS King Kargo HD EV) supporting two colorways and four specialized cargo-body configurations.
  • Voice-Controlled Scene Manipulation: Natural language command interpretation that directly rotates the 3D asset or changes camera angles in response to spoken prompts (for example: "show the Nexon interior", "open the Comet doors", "show me the back", "show the blue container", or "rotate left").
  • Specialist AI Vehicle Guides: Dynamic reconnection to model-specific voice agents when alternating vehicles, with fluent Hindi and Hinglish speech synthesized via Sarvam AI bulbul:v3 at 1.08x conversational pace.
EasyEV Virtual 3D Showroom

Virtual 3D Showroom with 360-degree interactive progressive rotation, vehicle specifications, and real-time voice controls.

2. Compare Arena & Dual-AI Vehicle Debates (#compare)

A real-time, podcast-style comparative debate stage where two independent AI advocates champion competing vehicles:

  • Dual-Advocate Realtime Voice: Two distinct AI personas simultaneously evaluate the specifications, trade-offs, and practical usage of two selected EVs over Agora RTC, rendered with custom 0.88x deliberative pacing using Sarvam AI Indic neural voices.
  • EasyEV AI Moderator: An autonomous referee managing turn-taking, summarizing core arguments, and keeping comparisons objective.
  • Live Specification Battle Meters: Synchronized visual telemetry dynamically benchmarking Affordability, Real-World Range, and Usable Battery Capacity.
  • Direct Voice Consultation Elevation: Seamless one-click transition from public debate analysis into a personalized private consultation.
Compare EVs Selection Grid
Selection Matrix & Multi-Category EV Filter
Live Dual-AI Debate Arena Stage
Live Dual-AI Debate Arena with Split Podiums & Battle Meters

3. Live Multimodal Consultation Room

A synchronized visual and audio consultation suite modeled after enterprise video collaboration tools:

  • Full-Duplex Conversational Audio: Sub-300ms barge-in and Voice Activity Detection (VAD) enabling fluid, natural interruptions, voiced by Sarvam AI's sovereign Indic speech synthesis engine (bulbul:v3, default speaker shubh).
  • Pre-Join Profile Ingestion: Collection of buyer identity, location, and travel requirements prior to call initiation, immediately seeded into the Buyer Decision Passport.
  • Synchronized Deal Room Stage: Real-time visual cards displaying vehicle comparisons, route range maps, charger discovery, and financial breakdowns synchronized with the agent's voice.
  • Dynamic Latency Mitigation: Intelligent conversational filler phrases in English, Hindi, and Hinglish deployed automatically during tool execution to maintain conversational momentum.
  • Server-Generated Decision Passport: Automated PDF generation summarizing the full rationale, financial calculations, and recommended options, dispatched directly to the buyer's email.
Pre-Join Consultation Setup
Pre-Join Profile Ingestion & Voice Setup
Live Consultation Deal Room
Live AI-Controlled Deal Room & Stage

Conversational AI Emotional and Cognitive States

Listening Thinking & MCP Query Presenting & Guiding Decision Achieved
Active VAD & Barge-in Real-time Tool Engine Calls Synchronized Visual Cards Instant CRM & Booking

4. Autonomous Dealer Onboarding Portal (#for-dealers)

A dedicated interface eliminating administrative overhead for electric mobility dealerships:

  • Four-Stage Progressive Profile Architecture: Structured registration across Dealership Profile, Physical Location, Brand Representation, and Value-Added Services.
  • AI Voice Copilot Autofill: In-browser voice assistant capable of parsing unstructured conversational responses directly into structured form fields.
  • Robust Dialect Parsing: Advanced regular expression matching supporting over 150 colloquial Hindi and Hinglish affirmations with strict word-boundary isolation.
  • Digital Partner Certification: Automatic issuance of a verified EasyEV Partner ID and digital credentials upon validation.
  • Transactional Email Delivery: Instant dispatch of verified onboarding packages and documentation via SMTP.
Dealer Registration Form with AI Voice Copilot
4-Step Progressive Registration with AI Voice Copilot Autofill
Verified Dealer Partner Certificate
Instant Digital Partner Certificate & Unique Partner ID Card

5. Specialist Console & Live Human Handoff (/rep or /rep.html)

An enterprise-grade console designed for human sales advisors and dealership specialists:

  • Real-Time Escalation Queue: Live tracking of buyer consultations requesting human assistance, complete with elapsed wait-time counters.
  • Context Preservation: Full transcript histories, current Buyer Decision Passport state, and contact records transferred instantly to the human advisor.
  • Priority Routing: Visual tags indicating urgent buyer criteria, high-intent leads, and specific model interests.
  • Presentation Mode: High-contrast, large-format display mode optimized for showroom video walls, auditorium presentations, and stage demonstrations.
  • External Notification Webhooks: Automated notification dispatch to configured Slack channels when an escalation occurs.
Human Specialist Desk Queue

Specialist Desk Console showing live waiting queue, elapsed wait-time counters, lead telemetry, and instant call takeover.


Engineering Innovations

Core Technological Innovations

1. Agora Real-Time Voice Pipeline & Multi-Tier Audio Stack

The EasyEV voice experience is built upon Agora's Conversational AI and Real-Time Communication (RTC/RTM) infrastructure, which delivers the sub-second responsiveness required for high-stakes automotive discovery:

  • Agora Conversational AI Engine: Direct integration with Agora's real-time edge processing for full-duplex conversational audio, ultra-low packet loss over unstable mobile networks, and sub-300ms barge-in latency.
  • Intelligent Voice Activity Detection (VAD): Dual client-side and server-side VAD enabling immediate speech interruption without clipping or delayed cutoff.
  • Synchronized Real-Time Messaging (Agora RTM 2.x): Concurrently streams vehicle specification cards, range map coordinates, and stage transitions synchronized to spoken turns.
  • Sarvam AI Neural Hindi TTS: Integration of Sarvam AI bulbul:v3 supporting male Hindi speakers (shubh, aditya, rahul) with authentic regional cadence.
  • Microsoft Azure Neural Speech: High-reliability fallback utilizing hi-IN-MadhurNeural and hi-IN-AaravNeural.
  • OpenAI Voice Services: Multilingual synthesis fallback for specialized operational modes.

2. Sarvam AI Indic Neural Voice Synthesis Engine

To serve Indian EV buyers authentically across Hindi and Hinglish dialects, EasyEV incorporates Sarvam AI's Sovereign Indic Speech Engine (bulbul:v3) integrated directly into the Agora conversational agent voice processing pipeline:

  • Vernacular Accent & Vocabulary Precision: Conventional TTS engines frequently mispronounce Indian automotive terms, state subsidy nomenclature, and colloquial units ("lakh", "on-road price", "15A 3-pin socket", "FAME-II", "range anxiety"). Sarvam AI delivers natural Indian prosody, cadence, and phonetically accurate pronunciation.
  • Calm Automotive Advisory Persona: The default male voice (shubh) is tuned for an empathetic, consultative tone that builds buyer trust during high-stakes financial calculations and battery life evaluations.
  • Dynamic Experience Pacing (1.08x vs 0.88x): The pipeline dynamically modulates the voice pace:
    • 1.08x Pace: Deployed in the Live Consultation Room and 3D Showroom Guide for energetic, fluid, and quick conversational turns.
    • 0.88x Pace: Deployed in the Dual-AI Debate Arena for deliberate, measured, and authoritative argumentative delivery.
  • Speaker Customization: Fully configurable across 20+ Indic male speaker profiles (shubh, aditya, rahul, rohan, amit, dev, ratan, varun, manan, sumit, kabir, aayan, ashutosh, advait, anand, tarun, sunny, mani, gokul, vijay, mohit, rehan, soham) via the SARVAM_TTS_SPEAKER environment variable.
  • Live System Health Diagnostics (/api/ready): The server continuously monitors and exposes Sarvam API readiness, selected voice persona, and target model (bulbul:v3) over the /api/ready diagnostic endpoint.
  • Seamless Multi-Tier Fallback: When Sarvam credentials are not supplied, the platform falls back seamlessly to Microsoft Azure Neural Voice (hi-IN-MadhurNeural) and OpenAI TTS (onyx) without restarting or dropping active sessions.
// Native SarvamTTS integration and bulbul:v3 subclass in server.mjs
import { SarvamTTS, MicrosoftTTS, OpenAITTS } from 'agora-agents';

// agora-agents defaults to bulbul:v2 without exposing custom params.
// We subclass SarvamTTS to explicitly inject model: 'bulbul:v3' and custom pace into Agora cloud:
class SarvamV3TTS extends SarvamTTS {
  toConfig() {
    const config = super.toConfig();
    return { ...config, params: { ...config.params, model: 'bulbul:v3' } };
  }
}

function sarvamTts(pace) {
  return new SarvamV3TTS({
    key: SARVAM_API_KEY,
    speaker: SARVAM_TTS_SPEAKER, // Default: 'shubh'
    targetLanguageCode: 'hi-IN',
    pace,                        // 1.08 for consultation/showroom, 0.88 for debate
    sampleRate: 24000,
  });
}

// Multi-tier voice selection per session:
const tts = language !== 'English' && SARVAM_TTS_READY
  ? sarvamTts(isDebate ? 0.88 : 1.08)
  : AZURE_SPEECH_READY
    ? new MicrosoftTTS({ azureKey: AZURE_SPEECH_KEY, region: AZURE_SPEECH_REGION, voiceName: 'hi-IN-MadhurNeural' })
    : new OpenAITTS({ apiKey: OPENAI_API_KEY, voice: 'onyx' });

3. Conversational Date and Slot Resolution Engine

Test-drive scheduling integrates natural language parsing for both English and vernacular Indian expressions:

  • Vernacular Temporal Parsing: Native interpretation of colloquial expressions including "aaj" (today), "kal" (tomorrow), "parso" (day after tomorrow), "this saturday", or "next monday".
  • Ordinal & Clock Time Matching: Disambiguation of spoken choices such as "the second one", "2 pm", "Tuesday 10:30", or "dus baje wala", converting spoken intent directly into verified calendar availability.
  • Collision Detection & Operating Windows: Validation against dealership operational hours (09:30 to 20:00) with automatic alternative slot generation if requested times are occupied.

4. Autonomous Dealer Onboarding State Machine

The vendor registration system utilizes a canonical finite state machine (FSM) backed by robust intent parsing:

// Strict word-boundary intent validation in dealer-voice-agent.mjs
const affPattern = /\b(?:haan+|ha+|haaji|haanji|ji\s*haan|yes+|yeah+|sure+|ok+|absolutely|definitely|exactly|right|correct|theek|thik|sahi|sahi\s*hai|bilkul|ekdam\s*sahi|chalega|available|milta\s*hai|dete\s*hain|karwate\s*hai|karte\s*hai|kardo|daldo|likh\s*do|rakh\s*do|add\s*kardo|sab\s*hai|saare\s*brands|dono\s*dete|submit\s*kardo|h|hai)\b/i;
  • Word-boundary isolation prevents partial-string false positives.
  • In-flight corrections allow users to revise individual fields without resetting completed stages.
  • State synchronization persists form state across voice and manual input simultaneously.

5. Realistic Physics Range Derating & Thermal Impact Engine

Commercial EV brochures in India routinely quote standard test-cycle ranges (ARAI / MIDC) that diverge significantly from real-world Indian road and climate realities. EasyEV incorporates a deterministic multi-factor derating engine that computes expected real-world range ($R_{\text{real}}$):

$$R_{\text{real}} = R_{\text{claimed}} \times \eta_{\text{temp}} \times \eta_{\text{speed}} \times \eta_{\text{payload}} \times \eta_{\text{terrain}}$$

Where:

  • $R_{\text{claimed}}$: ARAI or MIDC certified laboratory range in kilometres.
  • $\eta_{\text{temp}}$ (Thermal & Climate Coefficient): Captures HVAC auxiliary electrical load and battery electrochemical degradation under extreme ambient temperatures: $$\eta_{\text{temp}} = \begin{cases} 0.76 & \text{Extreme Summer } (T_{\text{amb}} \ge 42^\circ\text{C with continuous cabin AC cooling}) \ 0.88 & \text{Moderate Summer / Monsoon } (28^\circ\text{C} \le T_{\text{amb}} < 42^\circ\text{C with intermittent AC}) \ 0.96 & \text{Optimal Ambient } (20^\circ\text{C} \le T_{\text{amb}} < 28^\circ\text{C, minimal climate load}) \ 0.82 & \text{Northern Winter } (T_{\text{amb}} < 10^\circ\text{C, cold battery impedance}) \end{cases}$$
  • $\eta_{\text{speed}}$ (Aerodynamic & Velocity Factor): Models quadratic aerodynamic drag ($F_{\text{drag}} \propto v^2$) on Indian highways versus congested urban crawls:
    • Pure Stop-and-Go City Traffic ($v_{\text{avg}} \approx 22\text{ km/h}$, high regenerative braking recovery): $\eta_{\text{speed}} = 1.05$
    • Mixed Urban-Ring Road ($v_{\text{avg}} \approx 45\text{ km/h}$): $\eta_{\text{speed}} = 0.95$
    • Expressway / Highway Cruising ($v_{\text{avg}} \ge 90\text{ km/h}$, sustained high motor draw): $\eta_{\text{speed}} = 0.74$
  • $\eta_{\text{payload}}$ (Mass & Incline Factor): Standardized for 4-wheelers ($75\text{ kg}$ driver baseline) derated by $-2.5%$ per additional passenger ($+65\text{ kg}$) or luggage cargo ($+50\text{ kg}$). For 3-wheelers (Euler HiLoad, Treo Plus), derates linearly up to $-18%$ at maximum certified gross vehicle weight (GVW).

6. Deterministic Total Cost of Ownership (TCO) & Payback Math

The /mcp calculate_ownership decision tool executes multi-variable financial amortization models contrasting EV purchase and operation against internal combustion engine (ICE) benchmarks:

$$\Delta \text{Cost}_{N} = \left( \text{CapEx}_{\text{EV}} + \sum_{t=1}^{N} \frac{\text{OpEx}_{\text{EV}, t}}{(1 + r)^t} \right) - \left( \text{CapEx}_{\text{ICE}} + \sum_{t=1}^{N} \frac{\text{OpEx}_{\text{ICE}, t}}{(1 + r)^t} \right)$$

$$\text{OpEx}_{\text{EV}, t} = \text{AnnualKm} \times \left( \frac{\text{kWh}}{100\text{km}} \times \frac{\bar{T}_{\text{elec}}}{100} \right) + \text{AnnualService}_{\text{EV}}$$

$$\text{OpEx}_{\text{ICE}, t} = \left( \frac{\text{AnnualKm}}{\text{Mileage}_{\text{ICE}}} \times P_{\text{fuel}} \right) + \text{AnnualService}_{\text{ICE}}$$

Where:

  • Blended Electricity Tariff ($\bar{T}_{\text{elec}}$): $$\bar{T}{\text{elec}} = (\alpha{\text{home}} \times T_{\text{home}}) + ((1 - \alpha_{\text{home}}) \times T_{\text{public}})$$
    • $T_{\text{home}}$: State DISCOM residential slab rate (default: INR 7.50 / kWh).
    • $T_{\text{public}}$: CPO public fast-DC tariff (default: INR 18.00 / kWh).
    • $\alpha_{\text{home}}$: Buyer home charging split fraction (default: $0.80$).
  • Equated Monthly Installment (EMI): $$\text{EMI} = P \times r \times \frac{(1 + r)^n}{(1 + r)^n - 1}$$ Where $P = \text{ExShowroom} \times (1 - \text{DownPaymentRate})$, $r = \text{AnnualInterest} / 1200$, and $n = \text{TenureYears} \times 12$.
  • Break-Even Amortization Horizon ($T_{\text{break-even}}$): $$T_{\text{break-even}} = \frac{\text{CapEx}{\text{EV}} - \text{CapEx}{\text{ICE}}}{\text{AnnualSavings}_{\text{OpEx}}} \text{ (years)}$$

Agentic Interoperability

Model Context Protocol (MCP) Decision Tools

EasyEV implements an enterprise Streamable HTTP Model Context Protocol (MCP) Server at /mcp conforming to the official Anthropic Model Context Protocol specification (@modelcontextprotocol/sdk/server/mcp.js). The conversational LLM executes real-time decision tools across catalog discovery, spatial mapping, financial simulation, computer vision, CRM syncing, and calendar booking.

MCP Core Tool Registry

MCP Tool Name Operational Capability Data Sources & Integration
compare_vehicles Multi-dimensional specification and operational comparison across 4W, 2W, and 3W categories. Internal curated catalog & verified manufacturer specs
find_nearby_chargers Geospatial resolution of nearby public fast chargers with connector compatibility and operator details. OpenChargeMap API & Overpass OpenStreetMap (OSM)
calculate_ownership 5-Year comprehensive lifecycle cost analysis contrasting EV versus ICE economics. State electricity tariffs, maintenance benchmarks & fuel indices
analyze_readiness_snapshot Multimodal computer vision inspection of residential parking, electrical meters, or sockets. Gemini 2.0 Flash Vision API
generate_decision_report Dynamic server-side compilation of the Buyer Decision Passport into a verified PDF report. Node.js PDFKit streaming engine
escalate_to_human Direct escalation of the consultation to the human specialist desk with state transfer. Specialist queue state machine & Slack Webhook
capture_lead Creation and updating of customer contact records and qualified deal stages. HubSpot CRM REST API
book_test_drive Real-time dealership test-drive calendar slot reservation with transactional email confirmation. Cal.com scheduling API & SMTP Mailer

JSON-RPC 2.0 Wire Protocol & Streaming Execution

Every tool invocation dispatched to EasyEV's /mcp endpoint uses JSON-RPC 2.0 formatting and emits synchronized Server-Sent Events (SSE) back to the browser client over event: tool-event.

1. Vehicle Comparison Tool (compare_vehicles)

Dispatches multi-model comparison across battery chemistry, verified real-world range, DC fast charging rates, and pricing envelopes:

// JSON-RPC 2.0 Request Payload
{
  "jsonrpc": "2.0",
  "id": "req-mcp-01a",
  "method": "tools/call",
  "params": {
    "name": "compare_vehicles",
    "arguments": {
      "vehicles": ["Tata Nexon.ev", "MG Windsor EV"],
      "presentation": "comparison",
      "priorities": ["fast charging", "family boot space", "highway range"]
    }
  }
}
// JSON-RPC 2.0 Response Result
{
  "jsonrpc": "2.0",
  "id": "req-mcp-01a",
  "result": {
    "stage": "comparison",
    "payload": {
      "vehicles": [
        {
          "id": "tata-nexon-ev",
          "name": "Tata Nexon.ev Empowered+",
          "priceRange": "INR 12.49 - 17.19 Lakh",
          "battery": "45 kWh Prismatic LFP",
          "claimedRangeKm": 489,
          "realWorldRangeEstKm": 350,
          "dcFastChargeTime": "40 min (10-80% at 60 kW)",
          "bootCapacityLitres": 350,
          "groundClearanceMm": 190,
          "warranty": "8 years / 160,000 km battery & motor"
        },
        {
          "id": "mg-windsor-ev",
          "name": "MG Windsor EV Essence",
          "priceRange": "INR 13.99 - 18.39 Lakh",
          "battery": "38 kWh Prismatic LFP",
          "claimedRangeKm": 449,
          "realWorldRangeEstKm": 320,
          "dcFastChargeTime": "55 min (0-80% at 50 kW)",
          "bootCapacityLitres": 604,
          "groundClearanceMm": 186,
          "warranty": "8 years / 160,000 km battery"
        }
      ],
      "keyDifferentiator": "Nexon.ev leads on real-world highway range (350 km) and DC fast-charge rate (40 min). Windsor EV leads on passenger cabin space and rear luggage volume (604 L)."
    },
    "spoken": "I have put the Nexon.ev and Windsor EV side by side on your screen. The Nexon.ev charges quicker at public DC stations and offers greater highway range, while the Windsor provides significantly larger boot space."
  }
}

2. Total Cost of Ownership Engine (calculate_ownership)

Calculates net operational savings, monthly EMI, and break-even timeline:

// JSON-RPC 2.0 Request Payload
{
  "jsonrpc": "2.0",
  "id": "req-mcp-02b",
  "method": "tools/call",
  "params": {
    "name": "calculate_ownership",
    "arguments": {
      "vehicle": "Tata Punch.ev",
      "dailyKm": 45,
      "years": 5,
      "electricityRate": 7.5,
      "publicChargingRate": 18.0,
      "homeChargingShare": 0.85,
      "petrolPrice": 96.72,
      "petrolMileage": 14.5,
      "downPaymentPercent": 20,
      "annualInterest": 8.75,
      "loanYears": 5
    }
  }
}
// JSON-RPC 2.0 Response Result
{
  "jsonrpc": "2.0",
  "id": "req-mcp-02b",
  "result": {
    "stage": "ownership",
    "payload": {
      "vehicle": { "id": "tata-punch-ev", "name": "Tata Punch.ev" },
      "assumptions": {
        "dailyKm": 45,
        "annualKm": 16425,
        "electricityRateInr": 7.5,
        "petrolPriceInr": 96.72,
        "energyUseKwhPer100Km": 12.5
      },
      "results": {
        "monthlyEmi": 18940,
        "annualChargingInr": 18635,
        "annualFuelInr": 109559,
        "annualSavingsInr": 96424,
        "fiveYearNetSavingsInr": 482120,
        "breakEvenHorizonYears": 2.4
      }
    },
    "spoken": "At 45 kilometres per day, the Punch.ev saves approximately 96,400 rupees every year compared to a petrol equivalent, paying back its purchase price premium in just 2.4 years."
  }
}

3. Real-Time Geospatial Charger Discovery (find_nearby_chargers)

Resolves live public charging infrastructure with explicit user geocoding consent:

// JSON-RPC 2.0 Request Payload
{
  "jsonrpc": "2.0",
  "id": "req-mcp-03c",
  "method": "tools/call",
  "params": {
    "name": "find_nearby_chargers",
    "arguments": {
      "radiusKm": 10
    }
  }
}
// JSON-RPC 2.0 Response Result
{
  "jsonrpc": "2.0",
  "id": "req-mcp-03c",
  "result": {
    "stage": "charging-map",
    "payload": {
      "center": { "lat": 28.5684, "lng": 77.2183 },
      "radiusKm": 10,
      "stations": [
        {
          "id": "stat-del-01",
          "name": "Tata Power EZ Charge - South Extension",
          "operator": "Tata Power",
          "distanceKm": 1.2,
          "direction": "northeast",
          "connectors": ["CCS2 60kW DC Fast", "Type 2 22kW AC"],
          "availableSockets": 2,
          "totalSockets": 4,
          "status": "Operational",
          "access": "Public 24x7"
        },
        {
          "id": "stat-del-02",
          "name": "Jio-bp pulse - Defence Colony",
          "operator": "Jio-bp",
          "distanceKm": 2.8,
          "direction": "east",
          "connectors": ["CCS2 120kW Dual Gun", "Bharat DC-001"],
          "availableSockets": 3,
          "totalSockets": 4,
          "status": "Operational",
          "access": "Public 24x7"
        }
      ]
    },
    "spoken": "The interactive map is active. I found 8 operational fast-charging stations within 10 kilometres. The closest is Tata Power EZ Charge, 1.2 kilometres northeast on South Extension."
  }
}

4. Multimodal Readiness Snapshot Analysis (analyze_readiness_snapshot)

Performs privacy-first computer vision inspection of residential parking, meter boxes, and sockets:

// JSON-RPC 2.0 Request Payload
{
  "jsonrpc": "2.0",
  "id": "req-mcp-04d",
  "method": "tools/call",
  "params": {
    "name": "analyze_readiness_snapshot",
    "arguments": {
      "focus": "electrical-label"
    }
  }
}
// JSON-RPC 2.0 Response Result
{
  "jsonrpc": "2.0",
  "id": "req-mcp-04d",
  "result": {
    "stage": "snapshot-result",
    "payload": {
      "rejected": false,
      "sceneType": "Residential MCB Distribution Board",
      "observations": [
        "Dedicated 32A single-phase miniature circuit breaker (MCB) identified",
        "Earthing wire copper terminal verified",
        "Adequate clearance for 7.2 kW AC wallbox installation"
      ],
      "visibleConnector": "16A 3-Pin Industrial Socket",
      "electricalLabelText": "240V AC 50Hz 32A Main Distribution Board",
      "installerQuestions": [
        "Is the connected load sanctioned with DISCOM for 7.2 kW addition?",
        "What is the wire gauge distance from meter box to parking slot?"
      ],
      "deleted": true,
      "provider": "Google Gemini"
    },
    "spoken": "I completed the advisory check on your electrical board and purged the image buffer. Your panel shows a 32-amp circuit suitable for AC wallbox installation; check with your DISCOM regarding sanctioned load capacity."
  }
}

5. Dealership Test-Drive Reservation (book_test_drive)

Coordinates calendar slot booking, collision detection, and email delivery:

// JSON-RPC 2.0 Request Payload
{
  "jsonrpc": "2.0",
  "id": "req-mcp-05e",
  "method": "tools/call",
  "params": {
    "name": "book_test_drive",
    "arguments": {
      "slot": "Tuesday, 8 September at 2:00 PM",
      "demoType": "Dealership visit",
      "name": "Arjun Verma",
      "phone": "+91 98765 43210",
      "email": "[email protected]"
    }
  }
}
// JSON-RPC 2.0 Response Result
{
  "jsonrpc": "2.0",
  "id": "req-mcp-05e",
  "result": {
    "stage": "booking-confirmed",
    "payload": {
      "bookingId": "BK-2026-0906-8821",
      "confirmed": true,
      "when": "Tuesday, 8 September 2026 at 2:00 PM IST",
      "startISO": "2026-09-08T14:00:00+05:30",
      "demoType": "Dealership visit",
      "provider": "cal.com",
      "dealer": "Tata Motors EV Hub - South Extension",
      "emailSent": true
    },
    "spoken": "Done! Your dealership test drive for the Nexon.ev is booked for Tuesday, September 8th at 2:00 PM. A calendar invite and your Decision Passport summary have been sent to [email protected]."
  }
}

System Blueprints & Telemetry

Architecture & Flow Diagrams

This section provides comprehensive visual specifications of EasyEV's architecture, data movement, user experience pathways, sub-second voice sequencing, and state transitions.

1. High-Level System Architecture Topology

The application is structured across four decoupled tiers: a multimodal client presentation layer, an edge real-time communication gateway, a Node.js enterprise application server, and external SaaS integrations.

flowchart TB
    subgraph Client_Layer ["Client Presentation Layer (Browser Native)"]
        WebLanding["Modern Web Application (index.html)"]
        Showroom3D["Virtual 3D Showroom (/showroom/)"]
        CompareArena["Dual-AI Debate Arena (#compare)"]
        DealerPortal["Dealer Onboarding Portal (#for-dealers)"]
        RepConsole["Human Specialist Console (/rep)"]
        AgoraBundle["Agora RTC / RTM Client Bundle (agora-client.bundle.js)"]
    end

    subgraph Edge_Gateway ["Edge Communication & Voice Gateway"]
        AgoraCloud["Agora Conversational AI Cloud Engine"]
        STT_VAD["Deepgram / Ares Speech-to-Text & Realtime VAD"]
        TTS_Engine["Sarvam AI bulbul:v3 / Azure Neural / OpenAI TTS"]
        LLM_Core["OpenAI GPT-4o Realtime Engine"]
    end

    subgraph Backend_Layer ["EasyEV Node.js Application Server (Port 4173)"]
        ServerCore["HTTP Server & Request Dispatcher (server.mjs)"]
        MCPServer["Streamable HTTP MCP Server (/mcp)"]
        DecisionEngine["Decision Tools Engine (decision-tools.mjs)"]
        DealerFSM["Dealer Voice Agent FSM (dealer-voice-agent.mjs)"]
        TestDriveService["Test-Drive Service & Booking FSM (test-drive-service.mjs)"]
        HandoffManager["Human Specialist Escalation Manager"]
    end

    subgraph External_Services ["Integrated External Ecosystem"]
        HubSpot["HubSpot CRM (Lead & Deal Sync)"]
        CalCom["Cal.com Scheduling (Slot Calendar)"]
        OpenChargeMap["OpenChargeMap & Overpass OSM (Geospatial)"]
        GeminiVision["Gemini 2.0 Flash Vision (Photo Inspection)"]
        BlandAI["Bland AI Telephony (Outbound Calls)"]
        GmailSMTP["Transactional SMTP Mailer (PDF & Confirmations)"]
        Slack["Slack Webhook Dispatch (Urgent Lead Escalations)"]
    end

    Client_Layer <-->|"WebRTC Audio & Agora RTM Telemetry"| AgoraBundle
    AgoraBundle <-->|"Sub-300ms SD-RTN Channel"| AgoraCloud
    AgoraCloud <--> STT_VAD & TTS_Engine & LLM_Core
    LLM_Core <-->|"JSON-RPC 2.0 Protocol"| MCPServer
    MCPServer <--> DecisionEngine

    ServerCore --> DealerFSM
    ServerCore --> TestDriveService
    ServerCore --> HandoffManager

    DecisionEngine --> HubSpot & CalCom & OpenChargeMap & GeminiVision
    TestDriveService --> BlandAI & GmailSMTP
    HandoffManager --> RepConsole & Slack
Loading

2. Level 1 Data Flow Diagram (DFD)

The Data Flow Diagram illustrates how unstructured audio, profile inputs, and vehicle preferences are ingested, transformed by edge and server processes, and persisted across databases and external platforms.

flowchart TD
    Buyer(["EV Buyer"])
    Dealer(["Dealership Manager"])
    Specialist(["Human Specialist"])

    P1["1.0 Pre-Join Ingestion & Language Selection"]
    P2["2.0 Edge Voice Stream & VAD Processing"]
    P3["3.0 Intent Orchestration & Prompt Routing"]
    P4["4.0 Model Context Protocol (MCP) Execution"]
    P5["5.0 Dealer Onboarding State Machine & Regex Parsing"]
    P6["6.0 Test-Drive Slot Scheduling & Booking"]
    P7["7.0 Specialist Escalation & Session Handoff"]

    D1[("D1: Active Consultation Session & Decision Passport")]
    D2[("D2: Dealer Directory Registry (dealers.json)")]
    D3[("D3: Verified Multi-Category EV Catalog")]
    D4[("D4: External CRM & Calendar Records (HubSpot / Cal.com)")]
    D5[("D5: External Geo & Vision Services (OpenChargeMap / Gemini)")]

    Buyer -->|"Spoken Audio & Video Stream"| P2
    Buyer -->|"Pre-call Identity & Preferences"| P1
    P1 -->|"Seed Initial Context"| D1

    P2 -->|"STT Transcript (Hindi / Hinglish / English)"| P3
    P3 <-->|"Read / Update Context"| D1
    P3 -->|"Tool Call (JSON-RPC 2.0)"| P4

    P4 <-->|"Catalog Query"| D3
    P4 <-->|"Geo Charging & Photo Vision"| D5
    P4 -->|"Lead Contact & Slot Booking"| D4
    P4 -->|"Escalation Request"| P7

    P7 <-->|"Session State & Transcript"| D1
    P7 -->|"Live Waiting Ticket"| Specialist
    Specialist -->|"Accept & Control Session"| P7

    Dealer -->|"Voice Turns & Slang Affirmations"| P5
    P5 <-->|"Persist Dealer Record"| D2
    P5 -->|"Transactional Confirmation Kit"| Dealer

    P4 -->|"Synthesized Voice + Visual Telemetry"| P2
    P2 -->|"WebRTC Audio Playback & Stage Card Sync"| Buyer
Loading

3. End-to-End User Experience & Journey Flow

Visualizes the branching buyer and dealer user journeys from landing discovery to confirmed action across all four operational experiences.

flowchart TD
    Start(["User Lands on EasyEV Platform"]) --> ChoosePath{"Select Operational Experience"}

    ChoosePath -->|"Explore Vehicle Catalog"| ShowroomFlow["Virtual 3D Showroom (/showroom/)"]
    ChoosePath -->|"Listen to AI Debate"| ArenaFlow["Compare Arena (#compare)"]
    ChoosePath -->|"Direct Consultation"| ConsultFlow["Live Multimodal Consultation"]
    ChoosePath -->|"Dealership Registration"| DealerFlow["Dealer Onboarding Portal (#for-dealers)"]

    subgraph Showroom_Journey ["Virtual Showroom User Journey"]
        ShowroomFlow --> Spin360["Inspect 360-Degree Exterior Progressive Spin"]
        Spin360 --> InteriorView["Explore Cubemap Interior or Open Doors"]
        InteriorView --> VoiceCmd["Speak Voice Commands ('open doors', 'show blue container')"]
        VoiceCmd --> SpecGuide["Model-Specific Voice AI Agent Explanation"]
        SpecGuide --> BookDriveBtn["Click 'Book Test Drive'"]
    end

    subgraph Debate_Journey ["Compare Arena User Journey"]
        ArenaFlow --> SelectTwo["Select 2 Vehicles (Cars / Scooters / 3-Wheelers)"]
        SelectTwo --> LaunchDebate["Launch Live Dual-AI Debate Arena"]
        LaunchDebate --> DualSpeakers["Advocate 1 vs. Advocate 2 Audio Debate via Agora RTC"]
        DualSpeakers --> LiveMeters["Inspect Real-Time Spec Battle Meters (Price, Range, Battery)"]
        LiveMeters --> RefereeSummary["EasyEV AI Referee Moderation & Summary"]
        RefereeSummary --> ElevateConsult["Elevate to 1-on-1 Voice Consultation"]
    end

    subgraph Consultation_Journey ["Consultation & Action User Journey"]
        ConsultFlow --> Prejoin["Pre-Join Modal: Enter Name, Email, Phone, Category & Language"]
        Prejoin --> VoiceRoom["Enter Full-Duplex Consultation Room (Agora RTC/RTM)"]
        VoiceRoom --> AI_Guide["3D AI Guide Interaction (Sub-300ms Barge-in VAD)"]
        AI_Guide --> MCP_Triggers{"Real-Time Decision Inquiries"}
        MCP_Triggers -->|"5-Yr Savings Math"| TCO_Tool["calculate_ownership: Indian Electricity Tariff Math"]
        MCP_Triggers -->|"Range & Waypoints"| Charger_Tool["find_nearby_chargers: Live OpenChargeMap Stations"]
        MCP_Triggers -->|"Socket Inspection"| Vision_Tool["analyze_readiness_snapshot: Gemini Vision Photo Check"]
        MCP_Triggers -->|"Human Assistance"| Human_Tool["escalate_to_human: Transfer to Specialist Desk (/rep)"]
        TCO_Tool & Charger_Tool & Vision_Tool --> SlotBooking["book_test_drive: Natural Language Slot Resolution ('dus baje wala')"]
        SlotBooking --> DecisionPDF["generate_decision_report: Verified PDF Decision Passport Emailed"]
    end

    subgraph Dealer_Journey ["Dealer Onboarding User Journey"]
        DealerFlow --> SelectMode{"Input Mode"}
        SelectMode -->|"Voice Copilot"| VoiceFill["Hover on Virtual Salesperson & Speak in Hindi/Hinglish"]
        SelectMode -->|"Manual Form"| StepForm["4-Step Stepper (Profile, Location, Brands, Services)"]
        VoiceFill --> RegexFSM["150+ Affirmation FSM Engine Auto-fills Form Fields"]
        RegexFSM --> VerifyStep["Step 5: Issue Verified Digital Partner Certificate"]
        StepForm --> VerifyStep
        VerifyStep --> EmailKit["Branded Onboarding Kit & Certificate Dispatched via SMTP"]
    end
Loading

4. Real-Time Voice Pipeline & MCP Tool Execution Sequence

A detailed UML Sequence Diagram detailing the sub-second interaction cycle: user utterance, barge-in detection, parallel filler speech generation, model context tool invocation, and synchronized audio-visual rendering.

sequenceDiagram
    autonumber
    actor User as EV Buyer (Browser)
    participant SDK as Agora Web RTC/RTM SDK
    participant Edge as Agora Edge AI Cloud (STT + VAD)
    participant Core as EasyEV Server (Port 4173)
    participant LLM as OpenAI GPT-4o Realtime
    participant MCP as Streamable HTTP MCP Server (/mcp)
    participant Engine as Decision Tools Engine
    participant Ext as External APIs (Cal.com / HubSpot / OSM)
    participant TTS as Sarvam AI / Azure Neural TTS

    User->>SDK: Speaks: "2 pm wala slot book kardo aur TCO calculate karo"
    SDK->>Edge: Stream WebRTC Audio Upstream
    Edge->>Edge: Speech Detected (VAD Barge-In stops active playback)
    Edge->>LLM: Stream Final STT Transcript
    LLM->>Core: Emit Tool Invocations: book_test_drive & calculate_ownership
    Core->>TTS: Request Latency Filler Phrase ("Ek second, main check kar raha hoon...")
    TTS-->>User: Spoken Filler Audio Playback (0 perceived latency)
    Core->>MCP: Streamable HTTP POST /mcp (JSON-RPC 2.0 Tool Call)
    MCP->>Engine: Dispatch tool execution with user session context
    Engine->>Ext: Resolve Cal.com availability & verify slot collision
    Ext-->>Engine: Slot 14:00 confirmed & calendar invitation created
    Engine->>MCP: Return structured tool results (TCO delta & booking record)
    MCP-->>LLM: JSON-RPC 2.0 Structured Tool Response
    LLM->>Core: Generate natural language response in Hinglish
    Core->>TTS: Synthesize final conversational response (Sarvam bulbul:v3)
    Core->>SDK: Stream Agora RTM visual telemetry (Deal Room Stage update)
    SDK-->>User: Visual Card Update: Booking confirmation & 5-Yr TCO graph
    TTS-->>User: Stream Real-Time WebRTC Audio Playback
Loading

5. Autonomous Dealer Onboarding Finite State Machine (FSM)

The state transition graph shows how unstructured voice input progresses the dealer registration through strict validation checkpoints to certificate issuance.

stateDiagram-v2
    [*] --> STATE_UNINITIALIZED: Page Load / New Session
    
    STATE_UNINITIALIZED --> STEP_1_PROFILE: Voice Copilot Start or Form Focus
    
    state STEP_1_PROFILE {
        [*] --> AwaitDealershipName
        AwaitDealershipName --> AwaitOwnerName: Name Captured
        AwaitOwnerName --> AwaitContactNumber: Phone Validated (+91)
        AwaitContactNumber --> AwaitCity: Location Parsed
        AwaitCity --> AwaitOfficialEmail: Valid Email Pattern
        AwaitOfficialEmail --> ProfileCompleted: All Fields Validated
    }

    STEP_1_PROFILE --> STEP_2_LOCATION: "Continue to Location" or Voice Affirmation
    
    state STEP_2_LOCATION {
        [*] --> AwaitAddress
        AwaitAddress --> AwaitPincode: 6-Digit Pincode Verified
        AwaitPincode --> AwaitWorkingDays: Operating Schedule Defined
        AwaitWorkingDays --> AwaitHours: 09:30 - 20:00 Range Set
        AwaitHours --> LocationCompleted: Step 2 Complete
    }

    STEP_2_LOCATION --> STEP_3_BRANDS: "Continue to Inventory" or Voice Affirmation
    
    state STEP_3_BRANDS {
        [*] --> AwaitCategories
        AwaitCategories --> AwaitBrandChips: Categories Selected (4W/2W/3W/Commercial)
        AwaitBrandChips --> AwaitInventoryScale: Brands Toggled (Tata, Mahindra, Ather, etc.)
        AwaitInventoryScale --> BrandsCompleted: Step 3 Complete
    }

    STEP_3_BRANDS --> STEP_4_SERVICES: "Continue to Services" or Voice Affirmation
    
    state STEP_4_SERVICES {
        [*] --> AwaitFinanceSetup
        AwaitFinanceSetup --> AwaitInsuranceSetup: EMI & Bank Partners Configured
        AwaitInsuranceSetup --> AwaitTestDriveTypes: Insurance Covers Selected
        AwaitTestDriveTypes --> ServicesCompleted: Showroom & Home Test Drive Active
    }

    STEP_4_SERVICES --> STEP_5_VERIFIED_CERTIFICATE: Form Submit or Voice "Haan submit kardo"
    
    state STEP_5_VERIFIED_CERTIFICATE {
        [*] --> GeneratePartnerID: Issue EEV-DLR-2026-XXXX
        GeneratePartnerID --> PersistDatabase: Write to data/dealers.json
        PersistDatabase --> DispatchEmail: Send Onboarding Kit via SMTP
        DispatchEmail --> ActiveInNetwork: Display Digital Certificate Card
    }

    STEP_5_VERIFIED_CERTIFICATE --> [*]: Registration Finalized
Loading

6. Human-in-the-Loop Specialist Escalation Sequence

Demonstrates the seamless session handover protocol from the automated conversational agent to a human automotive advisor.

sequenceDiagram
    autonumber
    actor Buyer as EV Buyer
    participant AI as Agora Conversational Voice Agent
    participant MCP as EasyEV MCP Server
    participant Handoff as Handoff State Manager
    participant Slack as Dealership Slack Channel
    actor Specialist as Human EV Specialist (/rep)

    Buyer->>AI: "Can I speak to a real person about home solar charging?"
    AI->>MCP: Invoke escalate_to_human(reason="Solar charging installation inquiry")
    MCP->>Handoff: Register waiting session (Passport state + Full transcript)
    Handoff->>Slack: Dispatch Webhook (Urgent lead notification & direct console URL)
    Handoff->>Specialist: Stream Server-Sent Event (SSE) to Specialist Queue
    Note over Specialist: Specialist Desk displays call card,<br/>wait counter (0s... 15s...),<br/>shortlist & buyer facts
    Specialist->>Handoff: Clicks "Take this call" (POST /api/handoff/take)
    Handoff->>AI: Pause AI LLM agent turn generation
    Handoff->>Specialist: Issue authenticated Agora RTC specialist token
    Specialist->>Buyer: Direct full-duplex WebRTC audio connection established
    Note over Buyer,Specialist: Human specialist continues consultation<br/>with full Buyer Decision Passport context<br/>without disconnecting the call
Loading

Verified Multi-Category Fleet

EV Fleet & Virtual Showroom Collection

The EasyEV platform provides verified intelligence across all primary electric vehicle categories in India:

1. Passenger Cars (4-Wheelers)

Vehicle Model Battery & Chemistry Certified Range Fast Charging Speed
Tata Nexon.ev 40.5 – 45.0 kWh LFP 465 km 10%–80% in 40 min (60 kW DC)
Tata Punch.ev 25.0 – 35.0 kWh LFP 421 km 10%–80% in 56 min (50 kW DC)
MG Windsor EV 38.0 kWh Prismatic 331 km Battery-as-a-Service (BaaS) option
Mahindra XUV400 34.5 – 39.4 kWh NMC 456 km 0%–80% in 50 min (50 kW DC)
MG Comet EV 17.3 kWh Prismatic 230 km 3.3 kW AC City Optimized
Citroën C3 29.2 kWh LFP 320 km 10%–80% in 57 min (DC Fast)
Tata Nexon.ev Tata Punch.ev MG Windsor EV Mahindra XUV400
465 km • 45 kWh 421 km • 35 kWh 331 km • BaaS 456 km • 39.4 kWh

2. Scooters & Commuters (2-Wheelers)

Vehicle Model Battery Capacity TrueRange / Real Notable Highlights
Ather 450X 3.7 kWh Lithium-ion 110 km Warp Mode, Google Maps Dashboard
Ather Rizta 2.9 – 3.7 kWh 125 – 160 km 34L Boot Storage, SkidControl
Ola S1 Pro 4.0 kWh Lithium-ion 195 km HyperMode, Cruise Control
TVS iQube 3.4 – 5.1 kWh 100 – 145 km Q-Park Assist, Alexa Integration
Ather 450X Ather Rizta Ola S1 Pro TVS iQube
110 km TrueRange 160 km • 34L Boot 195 km • HyperMode 145 km • Q-Park Assist

3. Commercial & Auto-Rickshaws (3-Wheelers)

Vehicle Model Payload Capacity Real-World Range Application Focus
Mahindra Treo Plus 500 kg Payload 150 km Passenger Fleet & Metro Feeder
Piaggio Ape E-City 4 Passenger Cap 110 km Swappable Battery Architecture
Euler HiLoad EV 688 kg Payload 170 km Heavy Intra-City Commercial Cargo
Bajaj RE E-Tec 9.0 Passenger / Cargo 178 km Regenerative Braking, High Uptime
TVS King Kargo HD Customizable Body 140 km Multiple Cargo Configurations
Mahindra Treo Plus Piaggio Ape E-City Euler HiLoad EV Bajaj RE E-Tec 9.0
500 kg Payload 110 km • Swappable 688 kg Payload 178 km • Fast Charging

Geospatial Intelligence

Live Range Simulation & Route Mapping

Interactive Range and Charging Station Map

Real-time dynamic isochrone range contour mapping factoring payload weight, air conditioning usage, driving elevation, and nearest verified fast-charging stations.


Backend Dispatch & Contracts

API Reference

The EasyEV server exposes standardized HTTP and REST endpoints:

Multimodal Consultation Sessions

  • GET /api/session/token: Issues authenticated Agora RTC/RTM tokens for the client.
  • POST /api/session/start: Initializes a conversational AI session with language, persona, and prejoin context.
  • POST /api/session/think: Triggers tool execution requests and updates session generation counters.
  • POST /api/session/interrupt: Signals immediate audio cut-off and cancels pending asynchronous tool executions.
  • POST /api/session/stop: Cleans up active Agora sessions and finalizes the Buyer Decision Passport.

Virtual 3D Showroom

  • GET /showroom/: Serves the 3D Showroom application.
  • GET /showroom-assets/*: Delivers progressive 360-degree vehicle image sequences and Pannellum cubemaps.
  • GET /api/vehicle-session/token: Generates session tokens for product-specific showroom guides.
  • POST /api/vehicle-session/start: Instantiates a voice guide configured with vehicle-specific specifications.

Compare Arena & Dual-AI Debates

  • GET /api/debate-session/token: Allocates RTC tokens for dual-AI debate channels.
  • POST /api/debate-session/start: Launches an automated vehicle debate between two advocate models.

Dealer Onboarding & Directory

  • GET /api/dealers: Lists registered and verified dealerships with filtering by city and brand.
  • GET /api/dealers/stats: Aggregates active dealer counts, coverage cities, and supported categories.
  • POST /api/dealers/register: Processes manual dealer registration requests.
  • GET /api/dealer-session/token: Provides authentication tokens for the dealer voice copilot.
  • POST /api/dealer-session/start: Starts a conversational voice session for dealership onboarding.
  • POST /api/dealer-session/process-turn: Submits recognized speech turns to the dealer onboarding FSM.
  • POST /api/dealer-session/submit: Validates complete onboarding submissions and triggers confirmation emails.
  • GET /api/dealer-session/telemetry: Retrieves session diagnostics and completion progress.

Test-Drive Booking Engine

  • GET /api/test-drive-session/token: Issues tokens for the in-browser test-drive booking agent.
  • POST /api/test-drive-session/start: Launches a test-drive scheduling voice agent.
  • POST /api/test-drive-session/process-turn: Processes conversational slot selections and user contact details.
  • POST /api/test-drive/check-availability: Programmatically queries slot availability for a specified date and location.
  • POST /api/test-drive/book: Finalizes bookings, updates the local database, and dispatches confirmation emails.
  • POST /api/test-drive/initiate: Triggers an automated outbound scheduling workflow (via Bland AI integration).
  • POST /api/bland/post-call: Webhook receiver for automated telephony call outcomes.

Human Specialist Console & Escalations

  • GET /rep or GET /rep.html: Serves the specialist console.
  • GET /api/handoff/waiting: Lists active consultation sessions awaiting human intervention.
  • POST /api/handoff/take: Assigns an awaiting consultation session to an authenticated specialist.
  • GET /api/handoff/status: Polling endpoint for clients to detect specialist assignment.

Model Context Protocol (MCP)

  • POST /mcp: Handles standard JSON-RPC 2.0 Streamable HTTP MCP initialization and tool invocation requests.

Data Persistence & Schemas

Database & Data Models

EasyEV operates a dual-tier persistence architecture: an ultra-fast in-memory session graph synchronized with an atomic file-backed JSON database (dealer-db.mjs and test-drive-db.mjs), with automated migration hooks for PostgreSQL via DATABASE_URL in production.

1. Dealership Profile Schema (data/dealers.json)

Every registered dealership partner is stored under a canonical identifier (EEV-DLR-YYYY-XXXX):

{
  "id": "EEV-DLR-2026-1001",
  "shopName": "Tata Motors EV Hub - South Extension",
  "dealerType": "Authorized OEM Dealership",
  "contactPerson": {
    "name": "Rajesh Sharma",
    "role": "Showroom Manager",
    "phone": "+91 98112 34567",
    "email": "[email protected]",
    "whatsapp": "+91 98112 34567"
  },
  "location": {
    "address": "Plot 42, Ring Road, South Extension Part II",
    "city": "New Delhi",
    "state": "Delhi",
    "pincode": "110049",
    "coordinates": { "lat": 28.5684, "lng": 77.2183 }
  },
  "timings": {
    "openTime": "09:30 AM",
    "closeTime": "08:30 PM",
    "workingDays": "All 7 Days",
    "allDaysOpen": true
  },
  "categories": ["4W"],
  "brands": ["Tata Motors"],
  "inventoryScale": "15+ EVs",
  "services": {
    "emiAvailable": true,
    "emiPartners": ["HDFC Bank", "SBI", "Tata Capital"],
    "insuranceAvailable": true,
    "chargingOnSite": true,
    "chargerType": "Fast DC (60kW)"
  },
  "testDrive": {
    "showroomTestDrive": true,
    "homeTestDrive": true,
    "availableSlots": [
      { "id": "morning", "label": "Morning (10:00 AM - 01:00 PM)", "active": true },
      { "id": "afternoon", "label": "Afternoon (01:00 PM - 05:00 PM)", "active": true },
      { "id": "evening", "label": "Evening (05:00 PM - 08:00 PM)", "active": true }
    ]
  },
  "verificationStatus": "verified",
  "registeredAt": "2026-09-01T10:00:00.000Z"
}

2. Test-Drive Booking FSM Schema (data/test-drives.json)

Tracks customer test-drive appointments across a strict 15-state finite state machine:

{
  "bookingId": "BK-2026-0906-8821",
  "status": "BOOKED",
  "fsmState": "BOOKED",
  "buyer": {
    "name": "Arjun Verma",
    "phone": "+91 98765 43210",
    "email": "[email protected]",
    "city": "New Delhi"
  },
  "vehicle": {
    "vehicleId": "nexon-ev",
    "name": "Tata Nexon.ev Empowered+",
    "brand": "Tata Motors",
    "category": "4W"
  },
  "appointment": {
    "date": "2026-09-08",
    "time": "14:00",
    "slotLabel": "Tuesday, 8 September 2026 at 2:00 PM",
    "dealerId": "EEV-DLR-2026-1001",
    "calComBookingId": 482910,
    "calComUid": "bkg_ee89a1f2"
  },
  "createdAt": "2026-09-06T00:21:00.000Z",
  "stateHistory": [
    { "state": "INITIATED", "timestamp": "2026-09-06T00:20:10.000Z" },
    { "state": "SLOT_CHECKING", "timestamp": "2026-09-06T00:20:35.000Z" },
    { "state": "SLOT_CHECKED", "timestamp": "2026-09-06T00:20:38.000Z" },
    { "state": "AWAITING_CONFIRMATION", "timestamp": "2026-09-06T00:20:45.000Z" },
    { "state": "BOOKED", "timestamp": "2026-09-06T00:21:00.000Z" }
  ]
}

3. Buyer Decision Passport Schema

Constructed incrementally across spoken voice turns and compiled into a structured decision payload:

Field Type Description
buyerProfile Object Name, verified mobile, city of registration, daily commuting distance in km
usagePattern String Commercial passenger, daily highway commute, city intra-day, fleet logistics
chargingAccess String 15A home wall socket, dedicated residential 7.2kW AC wallbox, public fast-charging only
financialEnvelope Object Target ex-showroom budget (INR), down-payment threshold, preferred loan tenure (3-7 yrs)
recommendedVehicle Object Top scoring vehicle model, battery capacity (kWh), certified vs real-world range
fiveYearTcoDelta Number Net operational savings versus comparable internal combustion engine (ICE) vehicle
verifiedHandoff Object Target dealership ID, allocated human specialist, scheduled test drive booking ID

4. Production PostgreSQL Relational DDL & Migration Schema

When running in cloud production (DATABASE_URL configured via Render managed PostgreSQL or self-hosted cluster), EasyEV executes automatic migration on server initialization (decision-tools.mjs), ensuring transactional consistency, foreign key cascades, and high-performance JSONB/GIN querying:

-- Production DDL: EasyEV Core Relational & Geospatial Schema
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "pgcrypto";

-- 1. Verified Catalog Vehicles
CREATE TABLE IF NOT EXISTS vehicles (
  id TEXT PRIMARY KEY,
  category TEXT NOT NULL CHECK (category IN ('Electric car', 'Electric scooter', 'Electric 3-wheeler', 'Cars')),
  name TEXT NOT NULL,
  facts JSONB NOT NULL,
  source_url TEXT NOT NULL,
  verified_at DATE NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- 2. Buyer Consultation Sessions & Decision Passports
CREATE TABLE IF NOT EXISTS buyer_sessions (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  category TEXT NOT NULL,
  language TEXT NOT NULL,
  passport JSONB NOT NULL DEFAULT '{}'::jsonb,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- 3. Model Context Protocol Tool Execution Audit Trail
CREATE TABLE IF NOT EXISTS tool_runs (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  session_id UUID NOT NULL REFERENCES buyer_sessions(id) ON DELETE CASCADE,
  tool TEXT NOT NULL,
  phase TEXT NOT NULL,
  payload JSONB NOT NULL DEFAULT '{}'::jsonb,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- 4. Registered Dealership Partners
CREATE TABLE IF NOT EXISTS dealers (
  id TEXT PRIMARY KEY,
  shop_name TEXT NOT NULL,
  dealer_type TEXT NOT NULL,
  contact_person JSONB NOT NULL,
  location JSONB NOT NULL,
  timings JSONB NOT NULL,
  categories TEXT[] NOT NULL,
  brands TEXT[] NOT NULL,
  inventory_scale TEXT,
  services JSONB NOT NULL,
  test_drive JSONB NOT NULL,
  verification_status TEXT NOT NULL DEFAULT 'verified',
  registered_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- 5. Dealership Test-Drive Reservations
CREATE TABLE IF NOT EXISTS test_drives (
  booking_id TEXT PRIMARY KEY,
  status TEXT NOT NULL DEFAULT 'BOOKED',
  fsm_state TEXT NOT NULL DEFAULT 'BOOKED',
  buyer JSONB NOT NULL,
  vehicle JSONB NOT NULL,
  appointment JSONB NOT NULL,
  dealer_id TEXT REFERENCES dealers(id) ON DELETE SET NULL,
  state_history JSONB NOT NULL DEFAULT '[]'::jsonb,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- High-Performance GIN and B-Tree Indexes
CREATE INDEX IF NOT EXISTS idx_buyer_sessions_category ON buyer_sessions(category);
CREATE INDEX IF NOT EXISTS idx_buyer_sessions_passport_gin ON buyer_sessions USING GIN (passport);
CREATE INDEX IF NOT EXISTS idx_tool_runs_session ON tool_runs(session_id);
CREATE INDEX IF NOT EXISTS idx_tool_runs_created ON tool_runs(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_test_drives_date ON test_drives((appointment->>'date'));
CREATE INDEX IF NOT EXISTS idx_dealers_city ON dealers((location->>'city'));

Environment Schema

Configuration & Environment Variables

Create a .env file in the project root based on the template below:

# Server Configuration
PORT=4173
HOST=0.0.0.0
PUBLIC_BASE_URL=http://localhost:4173

# Agora Realtime AI WebRTC Credentials
AGORA_APP_ID="your_agora_app_id"
AGORA_APP_CERTIFICATE="your_agora_app_certificate"

# Speech-to-Text and Text-to-Speech Providers
SARVAM_API_KEY="your_sarvam_api_key"
SARVAM_TTS_SPEAKER="shubh"

AZURE_SPEECH_KEY="your_azure_speech_key"
AZURE_SPEECH_REGION="centralindia"

OPENAI_API_KEY="your_openai_api_key"

# Multimodal Computer Vision
GEMINI_API_KEY="your_gemini_api_key"
GEMINI_MODEL="gemini-2.0-flash"

# Model Context Protocol Security
MCP_SIGNING_SECRET="generated_secure_random_hex"

# Specialist Desk & Notification Webhooks
REP_DESK_KEY="optional_secure_desk_access_key"
SLACK_WEBHOOK_URL="https://hooks.slack.com/services/..."

# CRM and Scheduling Integrations
HUBSPOT_TOKEN="your_hubspot_private_app_token"
CALCOM_API_KEY="your_calcom_api_key"
CALCOM_EVENT_TYPE_ID="your_event_type_id"
BOOKING_TIMEZONE="Asia/Kolkata"

# Transactional Email Service (Gmail SMTP)
GMAIL_USER="[email protected]"
GMAIL_APP_PASSWORD="your_16_character_app_password"
MAIL_FROM_NAME="EasyEV"

# External Charging Station API
OPENCHARGEMAP_API_KEY="your_openchargemap_key"

Reproduction & Local Execution

Developer Quickstart

Prerequisites

  • Node.js: v22.0.0 or higher
  • npm: v10.0.0 or higher
  • Agora Developer Credentials: App ID and App Certificate

1. Clone Repository & Install Dependencies

git clone https://github.com/shhhivam12/easyev.git
cd easyev
npm install

2. Configure Environment Variables

cp .env.example .env
# Open .env and add your respective service credentials

3. Build Client Bundles & Launch Development Server

npm run dev

The server will initialize at http://localhost:4173:

  • Main Consultation & Decision Platform: http://localhost:4173/
  • Virtual 3D EV Showroom: http://localhost:4173/showroom/
  • Specialist Escalation Console: http://localhost:4173/rep

Verification & Quality Assurance

Testing

The EasyEV platform incorporates automated regression scripts, headless browser integration tests, and unit verification for state machines and conversational parsers:

1. Headless Browser Verification Suite

Executes headless browser automation across the landing hero, 3D virtual showroom, dual-AI debate arena, dealer onboarding form, and specialist console:

npm run verify:agentic

2. End-to-End API Route & MCP Tests

Executes multi-scenario curl transactions validating all 25+ HTTP routes, streaming MCP JSON-RPC 2.0 payloads, and session token generation:

# Execute deep E2E test suite across all API endpoints
bash scripts/deep-e2e-curl-test.sh

# Run multi-scenario live backend test script
node scripts/test-live-curl-scenarios.mjs

3. Dialect Parsing & FSM Unit Tests

Validates over 150 colloquial Hindi, Hinglish, and regional affirmative patterns with strict word-boundary isolation:

node scripts/test-dealer-agent-deep.mjs

4. Transactional Mailer Verification

Validates SMTP credentials and HTML / PDF decision report generation:

node scripts/test-email-gmail-scenarios.mjs

Cloud Production Blueprint

Deployment

EasyEV is architected for cloud container platforms, PaaS providers, and bare-metal servers.

1. Render Deployment (Blueprint Included)

The repository includes an infrastructure-as-code render.yaml manifest configuring the Node.js web service, environment variables, health checks, and managed PostgreSQL:

# Deploy directly via Git
git push origin main

Blueprint configuration in render.yaml:

  • Runtime: Node.js v24.19.0
  • Build Command: npm install --legacy-peer-deps && npm run build
  • Start Command: npm start
  • Health Check: /api/ready
  • Managed Database: PostgreSQL (easyev-db) automatically bound via DATABASE_URL

2. Docker Containerization

Run EasyEV within an isolated Linux container:

# Multi-stage production container
FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --legacy-peer-deps
COPY . .
RUN npm run build

FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=4173
COPY --from=builder /app/package*.json ./
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/server.mjs ./server.mjs
COPY --from=builder /app/crm-calendar.mjs ./crm-calendar.mjs
COPY --from=builder /app/dealer-db.mjs ./dealer-db.mjs
COPY --from=builder /app/dealer-voice-agent.mjs ./dealer-voice-agent.mjs
COPY --from=builder /app/decision-tools.mjs ./decision-tools.mjs
COPY --from=builder /app/email-mailer.mjs ./email-mailer.mjs
COPY --from=builder /app/test-drive-db.mjs ./test-drive-db.mjs
COPY --from=builder /app/data ./data
COPY --from=builder /app/assets ./assets
COPY --from=builder /app/showroom ./showroom
COPY --from=builder /app/showroom-assets ./showroom-assets
COPY --from=builder /app/dist ./dist

EXPOSE 4173
USER node
CMD ["node", "server.mjs"]

Build and execute:

docker build -t easyev-live:latest .
docker run -d -p 4173:4173 --env-file .env --name easyev easyev-live:latest

3. Production Docker Compose Multi-Container Orchestration

Deploy the complete stack with isolated networking, auto-restart policies, health checks, and persistent PostgreSQL storage:

# docker-compose.yml
version: '3.8'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: easyev-web
    restart: always
    ports:
      - "4173:4173"
    environment:
      - NODE_ENV=production
      - PORT=4173
      - DATABASE_URL=postgres://easyev_admin:secure_pg_pass@postgres:5432/easyev_production
      - PUBLIC_BASE_URL=https://easyev.example.com
      - AGORA_APP_ID=${AGORA_APP_ID}
      - AGORA_APP_CERTIFICATE=${AGORA_APP_CERTIFICATE}
      - SARVAM_API_KEY=${SARVAM_API_KEY}
      - SARVAM_TTS_SPEAKER=shubh
      - MCP_SIGNING_SECRET=${MCP_SIGNING_SECRET}
      - GEMINI_API_KEY=${GEMINI_API_KEY}
      - GEMINI_MODEL=gemini-2.0-flash
    depends_on:
      postgres:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://localhost:4173/api/ready"]
      interval: 15s
      timeout: 5s
      retries: 3

  postgres:
    image: postgres:16-alpine
    container_name: easyev-db
    restart: always
    environment:
      POSTGRES_USER: easyev_admin
      POSTGRES_PASSWORD: secure_pg_pass
      POSTGRES_DB: easyev_production
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U easyev_admin -d easyev_production"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  pgdata:

Launch the cluster:

docker compose up -d

4. Production Nginx Reverse Proxy (TLS 1.3 & WebSockets)

Deploy Nginx in front of EasyEV to terminate TLS 1.3, proxy full-duplex WebSockets, handle SSE event streams without buffering, and enforce strict security headers:

# /etc/nginx/sites-available/easyev.conf

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;
    server_name easyev.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name easyev.example.com;

    # SSL / TLS 1.3 Configuration
    ssl_certificate /etc/letsencrypt/live/easyev.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/easyev.example.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:10m;

    # Security Headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

    client_max_body_size 12M;

    # Static Assets & Showroom Media Caching
    location /showroom-assets/ {
        proxy_pass http://127.0.0.1:4173;
        expires 30d;
        add_header Cache-Control "public, no-transform";
    }

    # Real-Time SSE Streams (Zero Buffering Mandate)
    location ~* ^/api/(session|events|tool-event)/ {
        proxy_pass http://127.0.0.1:4173;
        proxy_http_version 1.1;
        proxy_set_header Connection '';
        proxy_buffering off;
        proxy_cache off;
        chunked_transfer_encoding off;
        proxy_read_timeout 24h;
    }

    # Core Application & WebSocket Gateway
    location / {
        proxy_pass http://127.0.0.1:4173;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

5. Production HTTPS & WebRTC Network Requirements

[!IMPORTANT] Modern web browsers mandate an HTTPS context (https://) to grant microphone and WebRTC permissions. When deploying behind a reverse proxy (Nginx, Caddy, or Cloudflare), ensure:

  1. TLS 1.3 encryption is active with a valid SSL certificate.
  2. WebSockets and SSE streams are passed without aggressive buffering (proxy_buffering off;).
  3. Outbound UDP ports 10000-65535 are open for Agora SD-RTN edge audio media streaming.

Security & Compliance

Security

EasyEV enforces enterprise-grade security protocols across conversational endpoints, authentication, and external integration layers:

1. Digital Personal Data Protection (DPDP) Act 2023 Compliance Matrix

EasyEV adheres to the Indian Digital Personal Data Protection (DPDP) Act 2023 across all customer-facing voice, camera, and geospatial touchpoints:

DPDP Statutory Principle Regulatory Requirement EasyEV Architectural Implementation
Purpose Limitation Data processed strictly for declared intent Microphone and camera streams activate only upon explicit user gesture; deactivated immediately upon session termination.
Data Minimization Collect only data necessary for discovery Voice audio is streamed directly over Agora WebRTC buffers. No raw user voice recordings are ever persisted to disk or external cloud buckets.
Storage Limitation Purge ephemeral data immediately Parking and electrical snapshot image buffers are cryptographically zero-filled (snapshot.buffer.fill(0)) in memory immediately after vision classification completes.
Consent Architecture Explicit, verifiable, withdrawable consent Browser geolocation and camera access require affirmative user opt-in via interactive on-screen consent modals before tool invocation.
PII Redaction & Sanitization Prevent accidental leakage to external LLMs Spoken phone numbers, PAN identifiers, and GST numbers are parsed, normalized, and masked before prompt construction.
Right to Erasure Delete data upon request Users can purge their active Decision Passport and associated CRM deal draft instantly via the reset control or DELETE /api/session/:id.

2. Cryptographic HMAC-SHA256 Tool Authentication

Every tool invocation dispatched to /mcp is verified against an HMAC-SHA256 digest using a timing-safe comparison to prevent timing attacks:

// Timing-safe cryptographic HMAC-SHA256 validation in server.mjs
import { createHmac, timingSafeEqual } from 'node:crypto';

export function verifyMcpSignature(rawBody, clientSignature, secret) {
  if (!clientSignature || !secret) return false;
  const expectedSignature = createHmac('sha256', secret)
    .update(rawBody)
    .digest('hex');
  const clientBuf = Buffer.from(clientSignature, 'hex');
  const expectedBuf = Buffer.from(expectedSignature, 'hex');
  if (clientBuf.length !== expectedBuf.length) return false;
  return timingSafeEqual(clientBuf, expectedBuf);
}

3. Agora Dynamic Token Authentication & Channel Isolation

RTC and RTM session tokens are generated on the server using agora-token with strict 24-hour expiration windows and channel-level access grants. Channel identifiers are cryptographically randomized UUIDs, preventing unauthorized eavesdropping or channel traversal across consultation rooms.


Operational Telemetry

Monitoring & Logging

1. Sub-300ms End-to-End Voice Latency Budget Waterfall

To achieve realistic, full-duplex conversational advisory without awkward pauses or clipped turn-taking, EasyEV optimizes every millisecond of the audio-inference loop:

Stage Processing Subsystem Latency Allocation Architectural Optimization
1. Audio Capture & Encode Browser WebRTC AudioWorklet 15 - 25 ms Opus 48kHz codec at 32 kbps with echo cancellation
2. Edge Transport Ingestion Agora SD-RTN Global Network 25 - 45 ms Optimized UDP packet routing via nearest Indian edge POP
3. Voice Activity Detection Client + Server VAD Pipeline 30 - 45 ms Dual-tier energy and acoustic threshold interrupt detection
4. Speech-to-Text (STT) Streaming Whisper / Agora STT 60 - 80 ms Real-time sliding window chunk transcription
5. LLM Token / Tool Emit GPT-4o Real-Time Engine 70 - 95 ms Speculative token generation with early tool call dispatch
6. MCP Tool Execution EasyEV Node.js Engine 15 - 30 ms In-memory catalog lookup & indexed PostgreSQL queries
7. Indic Speech Synthesis Sarvam AI bulbul:v3 80 - 100 ms Native Indic neural streaming first-chunk synthesis
8. Audio Downlink & Playback Agora WebRTC Downlink 25 - 40 ms Direct PCM streaming to client Web Audio Context
Total Roundtrip Latency Full Conversational Loop 320 - 460 ms Sub-500ms conversational turn benchmark achieved

2. Real-Time System Health Diagnostics (/api/ready)

EasyEV provides an automated self-diagnostic health check returning live operational status across every integrated subsystem:

curl -s http://localhost:4173/api/ready | jq .
{
  "status": "ready",
  "uptimeSeconds": 14280,
  "timestamp": "2026-09-06T00:30:00.000Z",
  "subsystems": {
    "agoraRtc": { "status": "operational", "appIdConfigured": true, "certificateConfigured": true },
    "sarvamTts": { "status": "operational", "model": "bulbul:v3", "speaker": "shubh", "targetLanguage": "hi-IN" },
    "azureSpeech": { "status": "ready", "voice": "hi-IN-MadhurNeural" },
    "database": { "status": "connected", "mode": "postgres", "poolSize": 4 },
    "mcpServer": { "status": "active", "toolsRegistered": 8, "hmacEnforced": true },
    "crmSync": { "status": "operational", "provider": "cal.com", "calendarActive": true },
    "visionEngine": { "status": "operational", "model": "gemini-2.0-flash" }
  }
}

3. Structured JSON Telemetry & Observability Logs

Every voice session, tool run, and handoff escalation emits structured JSON telemetry to standard output, compatible with Datadog, Grafana Loki, and AWS CloudWatch:

{
  "timestamp": "2026-09-06T00:30:12.482Z",
  "level": "info",
  "correlationId": "sess-ee89-4a1b-9f20",
  "event": "mcp_tool_execution",
  "tool": "calculate_ownership",
  "durationMs": 18.4,
  "input": { "vehicle": "tata-punch-ev", "dailyKm": 45, "years": 5 },
  "output": { "annualSavingsInr": 96424, "breakEvenYears": 2.4 },
  "clientIp": "103.21.244.12",
  "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"
}

Developer Extensibility

Developer Extensibility & SDK Guide

EasyEV is architected for rapid modular expansion. Follow the step-by-step guides below to extend the vehicle catalog, register new MCP tools, or configure regional language synthesis.

1. Adding a New Vehicle to the Catalog

To add a new EV model to the 3D Virtual Showroom and Decision Engine:

  1. Open showroom/vehicle-catalog.js and append your vehicle definition:
// showroom/vehicle-catalog.js
{
  id: "hyundai-creta-ev",
  name: "Hyundai Creta Electric",
  company: "Hyundai Motor India",
  category: "Cars",
  powertrain: "Electric",
  badge: "Electric mid-size SUV",
  price: "INR 18.50 lakh",
  priceNote: "Indicative starting ex-showroom",
  thumbnail: "/assets/vehicles/hyundai-creta-ev.jpg",
  sourceUrl: "https://www.hyundai.com/in",
  specs: [
    ["Certified range", "452 km"],
    ["Battery", "45 kWh"],
    ["Power / torque", "105 kW / 255 Nm"],
    ["DC Fast Charge", "50 min (10-80%)"],
    ["Boot", "433 L"],
    ["Seats", "5"]
  ],
  features: ["360-degree camera", "Level 2 ADAS suite", "V2L vehicle-to-load supply"],
  views: {
    exterior: {
      label: "Exterior 360",
      type: "spin",
      folder: "/showroom-assets/cars/creta-ev/exterior",
      pattern: "frame-{nn}.jpg",
      frames: 36
    }
  },
  greeting: "Welcome to the Hyundai Creta Electric showroom. Ask me about real-world highway range, DC fast-charging rates, or interior space.",
  knowledgePrompt: "You are the Hyundai Creta Electric showroom expert. Use 45 kWh battery, 452 km certified range, 105 kW motor. Separate certified laboratory range from real-world Indian highway estimates."
}
  1. Register the vehicle in decision-tools.mjs within the VEHICLES constant to activate catalog matching, range derating, and TCO calculations.

2. Registering a Custom Model Context Protocol (MCP) Tool

To expose a new decision tool to the LLM agent:

  1. Open decision-tools.mjs and define the tool in the definitions() method:
// decision-tools.mjs
check_state_subsidies: {
  description: "Check state-specific EV subsidies, road tax exemptions, and registration fee waivers across Indian states and union territories.",
  inputSchema: {
    state: z.string().describe("Indian state name, e.g. Delhi, Maharashtra, Karnataka, Uttar Pradesh"),
    vehicleCategory: z.enum(["4W", "2W", "3W"]).describe("Vehicle category")
  },
  run: this.checkStateSubsidies.bind(this),
}
  1. Implement the tool handler method:
async checkStateSubsidies(record, args) {
  const { state, vehicleCategory } = unpackArgs(args);
  const subsidyData = await fetchSubsidyMatrix(state, vehicleCategory);
  return {
    stage: "subsidy-breakdown",
    payload: subsidyData,
    spoken: `In ${state}, electric ${vehicleCategory}s receive a 100% waiver on road tax and registration fees, saving approximately ${money(subsidyData.roadTaxSavings)} upfront.`
  };
}

The tool is automatically exposed via /mcp over JSON-RPC 2.0 with zero manual routing boilerplate.

3. Adding a Regional Indic Dialect to Sarvam AI Pipeline

To configure a new regional language (e.g. Marathi, Tamil, or Telugu):

  1. Set the target language code in server.mjs:
function createRegionalTts(languageCode, speaker) {
  return new SarvamV3TTS({
    key: SARVAM_API_KEY,
    speaker: speaker, // 'shubh' for Hindi, 'kavya' for Tamil, etc.
    targetLanguageCode: languageCode, // 'te-IN', 'ta-IN', 'mr-IN'
    pace: 1.05,
    sampleRate: 24000,
  });
}

System Boundaries

Known Limitations

  1. Browser HTTPS Requirement: Browsers block microphone capture over insecure HTTP on non-localhost hosts. Production deployments must run behind a verified HTTPS domain.
  2. Hardware Audio Capture: Conversational voice sessions require an active microphone input device; systems lacking audio input fall back to text-only mode.
  3. Cal.com Rate Limits: Calendar slot synchronization relies on Cal.com API rate limits; high-frequency automated testing should utilize the mock slot generator.
  4. Third-Party Model Latency: While Agora RTC latency remains sub-300ms, overall response speed depends on external LLM inference and TTS provider response times.

Resolution Runbook

Troubleshooting

Issue Root Cause Resolution
Microphone NotAllowedError Browser denied microphone permission Click the lock/tune icon in the browser address bar, set Microphone to "Allow", and refresh the page.
Port 4173 in use (EADDRINUSE) A previous node server instance is still running Run lsof -i :4173 and terminate the orphaned process with kill -9 <PID>, then restart npm start.
Agora Token Error (401 / 403) Missing AGORA_APP_ID or AGORA_APP_CERTIFICATE Verify that your .env contains valid credentials from the Agora Developer Console.
Sarvam Voice Inactive (Fallback) SARVAM_API_KEY is missing or empty The server automatically falls back to Microsoft Azure Speech or OpenAI TTS. Add a valid Sarvam key to activate bulbul:v3.
MCP 403 Invalid Signature MCP_SIGNING_SECRET mismatch Ensure MCP_SIGNING_SECRET is defined in .env and matches between the dispatcher and MCP transport.
Deal Room Map Isochrone Missing Network block on OSM Overpass API Verify internet connectivity to OpenStreetMap and OpenChargeMap endpoints.

Future Horizons

Roadmap

  • Q4 2026: Multi-Regional Vernacular Expansion: Expand Sarvam AI Indic voice synthesis to Tamil, Telugu, Kannada, Marathi, and Bengali regional dialects.
  • Q1 2027: Direct OEM Dealership Integrations: Native webhook synchronizers for major Indian automotive dealer management systems (Tata Motors, Mahindra, Ather Energy, Ola Electric).
  • Q1 2027: WhatsApp Conversational Bridge: Continuous conversation handoff allowing buyers to resume their Decision Passport consultation over WhatsApp audio and text.
  • Q2 2027: Computer Vision Battery Degradation Scanner: In-browser camera inspection utilizing Gemini 2.0 Flash to detect battery pack physical corrosion and tyre wear patterns.
  • Q2 2027: Offline-First PWA Mode: Localized showroom caching enabling dealership sales reps to present 3D vehicle models in areas with low internet connectivity.

Collaboration Standards

Contributing

We welcome contributions to expand India's autonomous electric vehicle intelligence ecosystem.

Contribution Workflow

  1. Fork the Repository: Create an independent fork on GitHub.
  2. Create a Feature Branch: Use conventional branch naming (feature/new-ev-model, fix/slot-parsing).
  3. Adhere to Code Guidelines:
    • Maintain ECMAScript Module (.mjs / type: module) standards.
    • Preserve zero-emoji styling across all customer-facing interfaces and documentation.
    • Write unit tests for new regex patterns or decision tool algorithms.
  4. Run Verification:
    npm run build
    npm run verify:agentic
  5. Submit a Pull Request: Provide a detailed description of features added, test output, and relevant media assets.

Acknowledgements & Technology Credits

Special credit and appreciation to:

  • Agora: For providing the underlying real-time communication fabric, Conversational AI SDK, RTC/RTM infrastructure, and Voice Activity Detection (VAD) pipeline that powers EasyEV's real-time voice experiences across the Consultation Room, 3D Virtual Showroom, Dual-AI Debate Arena, and Dealer Voice Copilot.
  • Sarvam AI: For providing the sovereign Indic neural speech synthesis engine (bulbul:v3) that powers EasyEV's authentic Hindi and Hinglish advisory voice personas, accurate regional automotive terminology, and dynamic cadence control across consultation, showroom, and debate experiences.

Additional technology credits:

  • Anthropic: For establishing the Model Context Protocol (MCP) specification.
  • OpenAI: For the GPT-4o real-time multimodal intelligence framework.
  • Microsoft Azure: For Azure Neural Speech cloud fallback services.

License & Attribution

This project is developed for the Adaptive AI Sales and Negotiation Agent Hackathon Track.

All vehicle specifications, certification data, and imagery are referenced for demonstration and educational purposes under applicable fair-use and vendor attribution standards. Refer to assets/vehicle-media-attribution.json for detailed asset manifests.


Community & Maintainers

Contact & Community

  • GitHub Repository: shhhivam12/easyev
  • Issue Tracker: GitHub Issues
  • Hackathon Track: Adaptive AI Sales and Negotiation Agent Hackathon Track
  • Maintainers: EasyEV AI Core Engineering Team

About

EasyEV agentic EV decision room powered by Agora voice and real-time decision tools

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages