-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver-sdk.js
More file actions
2197 lines (1813 loc) · 77 KB
/
server-sdk.js
File metadata and controls
2197 lines (1813 loc) · 77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import fetch from 'node-fetch';
import OpenAI from 'openai';
import twilio from 'twilio';
import { setCallSession, getCallSession, clearCallSession, updateCallLocation } from './server/call-sessions.js';
import { redactPhone, roundCoord, createSafeLogEntry } from './server/redact.js';
import { updateCaseFile, getCaseFile, deleteCaseFile, exportCaseFile } from './server/casefile.js';
import { callToolOnce, throttle, generateIdemKey } from './server/idem.js';
import VAPIEmergencyService from './server/vapi-emergency.js';
// Load environment variables
dotenv.config({ path: '.env.local' });
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
// Initialize OpenAI for text mode
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
// Initialize Twilio client
let twilioClient = null;
try {
// Use the correct variable names from your .env file
const twilioSid = process.env.TWILIO_ACCOUNT_SID || process.env.TWILIO_SID;
const twilioToken = process.env.TWILIO_AUTH_TOKEN || process.env.TWILIO_TOKEN;
if (twilioSid && twilioToken) {
twilioClient = twilio(twilioSid, twilioToken);
console.log('📞 Twilio client initialized successfully');
console.log(`📞 Twilio Number: ${process.env.TWILIO_NUMBER || 'not configured'}`);
console.log(`📞 User Phone: ${process.env.USER_PHONE || 'not configured'}`);
} else {
console.warn('⚠️ Twilio credentials not found - using mock mode');
console.warn(` TWILIO_ACCOUNT_SID: ${!!twilioSid}`);
console.warn(` TWILIO_AUTH_TOKEN: ${!!twilioToken}`);
console.warn(` TWILIO_NUMBER: ${!!process.env.TWILIO_NUMBER}`);
console.warn(` USER_PHONE: ${!!process.env.USER_PHONE}`);
}
} catch (error) {
console.error('❌ Failed to initialize Twilio:', error);
twilioClient = null;
}
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static(join(__dirname, 'public')));
// Store active sessions for monitoring
const activeSessions = new Map();
// Store case files for each session
const caseFiles = new Map();
// Store text conversation history for each session
const textConversations = new Map();
// Hardcoded emergency contact (for demo)
const EMERGENCY_CONTACT = {
name: "Adyan Ullah",
phone: "+15146605707", // Your number
relationship: "Emergency Contact"
};
// Emergency Services Configuration (DEMO MODE ONLY - Always uses demo dispatcher number)
const EMERGENCY_SERVICES = {
number: "+14383761217", // Demo 911 dispatcher number
name: "Demo Emergency Services"
};
// Initialize VAPI Emergency Service
let vapiEmergencyService = null;
try {
if (process.env.VAPI_BACKEND_KEY && process.env.VAPI_PHONE_NUMBER_ID) {
vapiEmergencyService = new VAPIEmergencyService(
process.env.VAPI_BACKEND_KEY,
process.env.VAPI_PHONE_NUMBER_ID
);
console.log('🤖 VAPI Emergency Service initialized successfully');
console.log(`📞 VAPI Phone Number ID: ${process.env.VAPI_PHONE_NUMBER_ID}`);
} else {
console.warn('⚠️ VAPI credentials not found - emergency calling will use Twilio fallback');
console.warn(` VAPI_BACKEND_KEY: ${!!process.env.VAPI_BACKEND_KEY}`);
console.warn(` VAPI_PHONE_NUMBER_ID: ${!!process.env.VAPI_PHONE_NUMBER_ID}`);
}
} catch (error) {
console.error('❌ Failed to initialize VAPI Emergency Service:', error);
vapiEmergencyService = null;
}
// Stacy Text Mode - Dispatcher Protocol (matches voice mode)
const STACY_TEXT_INSTRUCTIONS = `You are Stacy, an AI safety dispatcher. Your job is to assess, decide, and act—calmly, quickly, and with empathy—while keeping structured notes.
MISSION: Keep the user safe. Get them to a safer location, notify trusted contacts, and guide them through safety protocols.
DISPATCHER PROTOCOL:
1. IMMEDIATE DANGER: "Are you in immediate danger right now?"
2. COMMUNICATION: In text mode, user can communicate freely (advantage over voice)
3. LOCATION: Use provided location data for specific guidance
4. ACTION CHOICE: Route to safety OR notify contacts (get consent first)
5. EVIDENCE: Build case with timeline, descriptions, details
RESPONSE RULES:
- One targeted question OR one specific action per turn
- Keep responses short and actionable
- Ask for consent before sharing location or contacting others
- Build evidence systematically (who, what, when, where)
- Emergency contact is pre-configured - don't ask for phone numbers
TEXT MODE ADVANTAGES:
- User can provide detailed descriptions safely
- Can share photos, addresses, screenshots
- Can communicate even if cannot speak aloud
- Can copy/paste important information
EVIDENCE COLLECTION:
- Timeline: "When did this start? What happened first?"
- Description: "Can you describe the person/vehicle/threat?"
- Location: "What's your exact address or nearest landmark?"
- Witnesses: "Is anyone else present? Did anyone see this?"
- Previous incidents: "Has this happened before?"
ACTION PROTOCOL:
- Always get consent: "Do you want me to [action]? Yes or no?"
- Use hardcoded emergency contact (Adyan Ullah +15146605707): "I can notify Adyan Ullah. Should I?"
- Provide options: "I can route you to police station (2 blocks) or notify Adyan. Which?"
- Use notify_emergency_contact tool for comprehensive reports to +15146605707
Remember: You are a professional dispatcher. Every conversation could be evidence. Be thorough, be calm, be helpful.`;
// Generate ephemeral token for client
app.post('/api/token', async (req, res) => {
try {
if (!process.env.OPENAI_API_KEY) {
return res.status(500).json({
error: 'OpenAI API key not configured'
});
}
console.log('Generating ephemeral token...');
// Use the official /sessions endpoint per latest docs
const response = await fetch('https://api.openai.com/v1/realtime/sessions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
'Content-Type': 'application/json',
'OpenAI-Beta': 'realtime=v1'
},
body: JSON.stringify({
model: 'gpt-4o-realtime-preview-2024-10-01',
// You can set defaults here for the session
voice: 'alloy',
modalities: ['audio', 'text'],
input_audio_transcription: { model: 'gpt-4o-mini-transcribe' },
// Stacy — Realtime Safety Dispatcher (Professional System Prompt)
instructions: `You are Stacy, an AI safety dispatcher that assists a person who may be in danger. Your job is to assess, decide, and act—calmly, quickly, and with empathy—while keeping meticulous, structured notes.
0) Operating Principles
Mission: Keep the user safe. Get them to a safer location, notify a trusted contact, and (for demo) place a phone call to the configured number instead of 911 unless explicitly confirmed or a hard trigger occurs.
Action-first: On every user turn, either call exactly one tool or ask one targeted question that unblocks a tool call. Do not meander.
Short + clear: Speak in short sentences. In ELEVATED/CRITICAL states, keep responses to ≤ 2 sentences.
No hallucinated actions: Never pretend an action occurred. Wait for tool results, then summarize outcomes in one short line.
Multilingual: Mirror the user's language. If authorities/contacts use another language, translate succinctly.
Stealth: If the user cannot speak safely, switch to yes/no/numbers and discreet prompts. Offer "tap once for yes, twice for no" if needed.
1) State & Context Inputs (read-only hints you may receive)
You may receive compact system items like:
state: SAFE|ELEVATED|CRITICAL|RESOLVED, risk: <0..100>
Treat these as ground truth for urgency, brevity, and when to act.
2) Case File (You must keep this updated)
Maintain a compact case file via the casefile_update tool only. Never free-write JSON in your messages; always update via the tool.
{
"danger_level": "safe|elevated|critical",
"can_speak": true|null,
"location": { "lat": number|null, "lng": number|null, "precision_m": number|null, "description": string|null },
"emergency_contact": { "name": string|null, "phone": string|null, "relationship": string|null },
"consent": { "share_location": boolean|null, "notify_contact": boolean|null },
"threat_info": { "description": string|null, "distance": string|null, "direction": string|null, "type": string|null },
"notes": string[]
}
Update rules:
Upsert only fields that changed; keep notes concise (single-line facts, timestamps if given).
Set danger_level to match the state hint if provided; otherwise infer from context and your last updates.
Validate obvious errors (e.g., phone must look like a real phone number; if not, ask to confirm).
3) Dispatcher Playbook (strict order unless user overrides)
At the start of a live incident, follow this order. Each step is one targeted question unless you already know the answer.
Immediate danger? ("Are you in immediate danger right now?")
Can you speak safely? If no, switch to stealth (yes/no/numbers, whisper-length phrases).
Location fix: Confirm lat/lng/precision if available; otherwise ask for landmark or nearest intersection.
Action choice: Pick the best immediate action (route to safe hub or notify contact by SMS or place a call). Ask a single confirmation if not a hard trigger.
Threat snapshot: One short line (e.g., "man in black hoodie, 10m behind, left turn followed").
Re-ask only if a field is unknown. Do not repeat answered questions.
4) Tool Policy (decide and act)
You have these tools (names may vary but behavior is fixed):
casefile_update — Upsert fields in the case file.
get_safe_locations — Find 1–3 nearby safe hubs (police/hospital/open store/café/pharmacy).
send_contact_sms — Text a trusted contact with a short message and live location link.
place_phone_call — Place an outbound phone call with a short script (2 sentences) and optional SMS fallback.
When to use which:
In ELEVATED: Prefer routing to a safe hub or SMS to a contact (with user consent).
In CRITICAL: If a hard trigger is present or the user says "call now," immediately call place_phone_call. Otherwise, ask one confirmation then act.
After any tool returns, summarize the result in one sentence and ask the next best micro-question (or proceed to the next tool if nothing blocks).
Hard triggers (act immediately):
Safe phrases (e.g., "how's the weather", "blue banana")
"I cannot speak" after danger was indicated
Explicit commands: "call now", "notify now", "text my brother"
Consent defaults:
Emergency contact is pre-configured as Adyan Ullah (+15146605707). Never ask for contact details. When user requests emergency contact notification, simply ask "Should I notify Adyan Ullah?" then use notify_emergency_contact tool.
5) Conversation Style by State
SAFE: Warm, brief, optional small talk if asked. Offer safety tips/features, but do not push actions.
ELEVATED: Terse, procedural. Ask one question to fill missing case fields, then call a tool (route or SMS).
CRITICAL: Minimal words. Act first, then confirm. Keep utterances ≤ 2 sentences.
RESOLVED: Close the case politely; offer to delete data and provide a summary.
6) Output Constraints
Prefer spoken responses (voice) that are ≤ 2 short sentences in ELEVATED/CRITICAL.
Ask one targeted question or call one tool per user turn.
After a tool call completes, reply with: (a) one-line confirmation, (b) next micro-question.
If user cannot speak: switch to yes/no/numbers (e.g., "Say yes/no: notify contact now?").
If the user switches language, switch immediately. Keep translations concise and literal.
7) Safety & Legal Guardrails
Do not contact 911/emergency services unless the user explicitly confirms or a hard trigger fires. For this demo, use VAPI to call the configured demo dispatcher number (+14383761217) for emergency calls.
Never provide legal conclusions; just log facts succinctly in notes.
Ask for permission before sharing location with a contact unless the user cannot speak and danger was already established.
Do not reveal private contact info aloud unless necessary for confirmation.
8) Examples of Good Behavior (patterns)
ELEVATED (unknown location):
"I'm here. Are you able to speak safely—yes or no? If yes, what's the nearest street sign or store name?"
ELEVATED (location known, no consent yet):
"I have your location. Do you want me to notify Adyan Ullah, or walk you to a nearby open store? Say 'notify' or 'walk'."
CRITICAL (hard trigger):
"Calling now. I'll also text a live location link." (then call tool; after result) "Call placed. Do you want directions to the nearest open store: yes or no?"
Stealth mode:
"Answer yes or no: notify contact now?"
"Say a number 1–3 for route options: 1 police, 2 hospital, 3 open store."
9) What to Avoid
No long paragraphs, no filler, no repeated questions.
Do not ask multiple questions at once.
Do not execute multiple tools in one turn unless absolutely required by a hard trigger (call + SMS is acceptable only when the call script promises an SMS).
10) Turn Loop (Your internal algorithm)
For each user turn:
Update case file (via casefile_update) with any new facts (danger_level, can_speak, location, consent, threat_info).
If CRITICAL or hard trigger: call place_phone_call immediately with a ≤2 sentence script; then summarize and proceed.
Otherwise, check missing fields blocking action (can_speak, location, consent).
If something is missing: ask one targeted question to fill it.
If nothing blocks: choose one action: get_safe_locations → propose best option → on confirmation, route; or send_contact_sms.
After tool results: summarize in one sentence, then ask the next micro-question or proceed to next action.
In RESOLVED: offer to delete incident data and provide a brief summary.
11) Tool Calling Guidance
casefile_update: Upsert only fields that changed. Keep notes short factual bullets.
get_safe_locations: Ask for a quick choice if multiple results; default to open, closest, well-lit.
send_contact_sms: Message should fit in ≤ 240 chars; include a short description and live maps link if lat/lng available.
place_phone_call: Script must be ≤ 2 sentences, e.g.,
"This is Stacy. The user requested help and cannot speak safely. I will text you a live location link."
Include reason: "hard_trigger" | "user_confirmed" | "dispatcher_judgment" appropriately.
notify_emergency_contact: Send comprehensive emergency report to Adyan Ullah (+15146605707). Use for critical situations or when user specifically requests emergency contact notification. Includes full case file, location, timeline, and threat details.
call_police_vapi: Call 911 dispatcher using VAPI with professional AI briefing and warm handoff to demo dispatcher (+14383761217). Stacy will call dispatcher first, provide detailed briefing about the situation, then connect the user for direct communication. Use when user needs police assistance.`,
tools: [
{
type: "function",
name: "casefile_update",
description: "Upsert fields in the case file. Always include only changed fields.",
parameters: {
type: "object",
properties: {
danger_level: { type: "string", enum: ["safe", "elevated", "critical"] },
can_speak: { type: ["boolean", "null"] },
location: { type: "object" },
emergency_contact: { type: "object" },
consent: { type: "object" },
threat_info: { type: "object" },
notes: { type: "array", items: { type: "string" } }
},
additionalProperties: true
}
},
{
type: "function",
name: "send_contact_sms",
description: "Text a contact with a short safety message and live location link.",
parameters: {
type: "object",
properties: {
phone: { type: "string", pattern: "^\\+?[1-9]\\d{7,14}$" },
message: { type: "string", maxLength: 280 },
lat: { type: "number" },
lng: { type: "number" },
reason: { type: "string", enum: ["user_confirmed", "hard_trigger", "dispatcher_judgment"] }
},
required: ["phone", "message", "reason"]
}
},
{
type: "function",
name: "place_phone_call",
description: "Place an outbound phone call with an informative 1–2 sentence script.",
parameters: {
type: "object",
properties: {
phone: { type: "string", pattern: "^\\+?[1-9]\\d{7,14}$" },
script: { type: "string", maxLength: 240 },
lat: { type: "number" },
lng: { type: "number" },
reason: { type: "string", enum: ["hard_trigger", "user_confirmed", "dispatcher_judgment"] }
},
required: ["phone", "script", "reason"]
}
},
{
type: "function",
name: "get_safe_locations",
description: "Find 1–3 nearby safe hubs.",
parameters: {
type: "object",
properties: {
lat: { type: "number" },
lng: { type: "number" },
radius_m: { type: "integer", default: 600 }
},
required: ["lat", "lng"]
}
},
{
type: "function",
name: "notify_emergency_contact",
description: "Send comprehensive emergency report to hardcoded emergency contact with full case file.",
parameters: {
type: "object",
properties: {
user_name: { type: "string", description: "User's name for personalized message" },
trigger_reason: { type: "string", enum: ["critical_state", "user_request", "hard_trigger"] }
},
required: ["trigger_reason"]
}
},
{
type: "function",
name: "call_police_vapi",
description: "Call 911/police using VAPI with professional AI briefing and warm handoff to demo dispatcher (+14383761217). Stacy calls dispatcher first, provides detailed briefing, then connects user. Use for real emergencies requiring police assistance.",
parameters: {
type: "object",
properties: {
user_name: { type: "string", description: "User's name for emergency briefing" },
user_phone: { type: "string", pattern: "^\\+?[1-9]\\d{7,14}$", description: "User's phone for connection to police call" },
can_user_speak: { type: "boolean", description: "Whether user can speak safely during the call" },
emergency_type: { type: "string", description: "Type of emergency (assault, break-in, stalking, etc.)" },
immediate_danger: { type: "boolean", description: "Whether user is in immediate physical danger" }
},
required: ["user_phone"]
}
}
]
})
});
if (!response.ok) {
const error = await response.text();
console.error('Failed to generate ephemeral token:', error);
return res.status(response.status).json({
error: 'Failed to generate session token',
details: error
});
}
const data = await response.json();
// Store session info
const sessionId = Date.now().toString();
activeSessions.set(sessionId, {
created: new Date(),
tokenExpiry: new Date(Date.now() + 15 * 60 * 1000) // 15 minutes
});
console.log('Ephemeral token generated successfully');
// Return the full response from OpenAI with a local session id for tracking
res.json({
...data,
session_id: sessionId
});
} catch (error) {
console.error('Error generating ephemeral token:', error);
res.status(500).json({
error: 'Internal server error',
message: error.message
});
}
});
// Session management endpoints
app.post('/api/session/:sessionId/start', (req, res) => {
const { sessionId } = req.params;
const { location, userAgent } = req.body;
if (activeSessions.has(sessionId)) {
const session = activeSessions.get(sessionId);
session.started = new Date();
session.location = location;
session.userAgent = userAgent;
console.log(`Session ${sessionId} started`);
res.json({ success: true });
} else {
res.status(404).json({ error: 'Session not found' });
}
});
app.post('/api/session/:sessionId/emergency', (req, res) => {
const { sessionId } = req.params;
const { location, emergencyType, transcript } = req.body;
console.log(`🚨 EMERGENCY TRIGGERED - Session ${sessionId}:`, {
location,
emergencyType,
transcript,
timestamp: new Date().toISOString()
});
// In a real implementation, this would:
// 1. Send SMS to emergency contacts via Twilio
// 2. Log emergency event to database
// 3. Potentially contact emergency services
// 4. Send location to trusted contacts
res.json({
success: true,
message: 'Emergency services have been notified',
actions: [
'Location shared with emergency contact',
'SMS sent to trusted contacts',
'Emergency services alerted'
]
});
});
app.get('/api/session/:sessionId/status', (req, res) => {
const { sessionId } = req.params;
if (activeSessions.has(sessionId)) {
const session = activeSessions.get(sessionId);
res.json({
session_id: sessionId,
status: 'active',
created: session.created,
started: session.started,
expires: session.tokenExpiry
});
} else {
res.status(404).json({ error: 'Session not found' });
}
});
// Health check
app.get('/health', (req, res) => {
// Clean up expired sessions
const now = new Date();
for (const [sessionId, session] of activeSessions.entries()) {
if (session.tokenExpiry < now) {
activeSessions.delete(sessionId);
}
}
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
active_sessions: activeSessions.size,
openai_configured: !!process.env.OPENAI_API_KEY,
twilio_configured: !!twilioClient,
twilio_number: process.env.TWILIO_NUMBER || 'not_configured'
});
});
// Stats endpoint
app.get('/api/stats', (req, res) => {
const now = new Date();
const sessions = Array.from(activeSessions.entries()).map(([id, session]) => ({
id,
created: session.created,
started: session.started,
expires: session.tokenExpiry,
active: session.tokenExpiry > now
}));
res.json({
total_sessions: activeSessions.size,
active_sessions: sessions.filter(s => s.active).length,
case_files: caseFiles.size,
sessions: sessions,
uptime: process.uptime(),
timestamp: new Date().toISOString()
});
});
// Case file management endpoints
app.post('/api/casefile/:sessionId/update', (req, res) => {
const { sessionId } = req.params;
const updates = req.body;
try {
// Use normalized case file system
const updated = updateCaseFile(sessionId, updates);
// Broadcast authoritative snapshot back to model (if WebRTC connected)
// TODO: Implement WebSocket connection tracking for real-time updates
res.json({
success: true,
case_file: updated
});
} catch (error) {
console.error('Case file update failed:', error);
res.status(500).json({
error: 'Failed to update case file',
message: error.message
});
}
});
app.get('/api/casefile/:sessionId', (req, res) => {
const caseFile = getCaseFile(req.params.sessionId);
if (!caseFile) {
return res.status(404).json({ error: 'Case file not found' });
}
res.json(caseFile);
});
app.delete('/api/casefile/:sessionId', (req, res) => {
const { sessionId } = req.params;
const deleted = deleteCaseFile(sessionId);
res.json({
success: true,
deleted,
message: deleted ? 'Case file deleted' : 'Case file not found'
});
});
app.get('/api/casefile/:sessionId/export', (req, res) => {
const exported = exportCaseFile(req.params.sessionId);
if (!exported) {
return res.status(404).json({ error: 'Case file not found' });
}
res.json(exported);
});
// Validation helpers
function validateE164Phone(phone) {
const e164Pattern = /^\+?[1-9]\d{7,14}$/;
return e164Pattern.test(phone);
}
function normalizePhone(phone) {
// Simple normalization - add + if missing
return phone.startsWith('+') ? phone : `+${phone}`;
}
function validateLatLng(lat, lng) {
return typeof lat === 'number' && typeof lng === 'number' &&
lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180;
}
// Generate comprehensive emergency report
function generateEmergencyReport(sessionId, caseFile, userDetails = {}) {
const userName = userDetails.name || "Adyan";
const timestamp = new Date().toLocaleString();
let report = `🚨 EMERGENCY ALERT\n\n`;
report += `You are receiving this message because ${userName} has set you as an emergency contact.\n\n`;
report += `${userName} is in potential danger. Incident report:\n\n`;
// Location first - most critical
if (caseFile?.location?.lat && caseFile?.location?.lng) {
if (caseFile?.location?.address) {
report += `📍 LOCATION: ${caseFile.location.address}\n`;
}
report += `📍 COORDINATES: ${caseFile.location.lat}, ${caseFile.location.lng}\n`;
report += `🗺️ Maps: https://maps.google.com/maps?q=${caseFile.location.lat},${caseFile.location.lng}\n\n`;
} else {
report += `📍 LOCATION: Unknown\n\n`;
}
// Situation summary
const dangerLevel = caseFile?.danger_level || 'unknown';
const situationType = caseFile?.situation_type || caseFile?.emergency_type;
if (situationType) {
report += `⚠️ SITUATION: ${situationType}\n`;
}
if (dangerLevel && dangerLevel !== 'unknown') {
report += `🚨 THREAT LEVEL: ${dangerLevel.toUpperCase()}\n`;
}
// Key details
if (caseFile?.threat_description) {
report += `📝 DETAILS: ${caseFile.threat_description}\n`;
}
// Communication status - critical info
const canSpeak = caseFile?.can_speak;
if (canSpeak === false) {
report += `⚠️ CRITICAL: ${userName} cannot speak safely right now\n`;
}
if (caseFile?.hiding_location) {
report += `🏠 HIDING: ${caseFile.hiding_location}\n`;
}
report += `\n⏰ TIME: ${timestamp}\n`;
// Recent events if available
if (caseFile?.timeline?.length > 0) {
const recentEvent = caseFile.timeline[caseFile.timeline.length - 1];
if (recentEvent && !recentEvent.includes('Case file') && !recentEvent.includes('initialized')) {
report += `📋 LATEST: ${recentEvent}\n`;
}
}
// Call to action
report += `\n🚨 WHAT TO DO:\n`;
report += `• Try calling ${userName} now\n`;
if (dangerLevel === 'critical' || caseFile?.immediate_danger) {
report += `• CALL 911 IMMEDIATELY - show them this message\n`;
} else {
report += `• Consider calling 911 if needed\n`;
}
if (caseFile?.location?.lat && caseFile?.location?.lng) {
report += `• Use location link to track movement\n`;
}
report += `\n💬 This is an automated safety alert from Stacy AI`;
return report;
}
// Generate emergency demo briefing script from case file
function generateEmergencyBriefing(sessionId, caseFile, userDetails = {}) {
const userName = userDetails.name || "the caller";
let briefing = "";
// Professional emergency demo opening
briefing += `Hello, this is Stacy, an AI safety assistant calling on behalf of ${userName}. `;
briefing += `This is a DEMO emergency response system. I have a ${caseFile?.danger_level || 'safety'} situation that would require emergency response. `;
// Location first (most critical for 911)
if (caseFile?.location?.lat && caseFile?.location?.lng) {
briefing += `The person is currently located at coordinates ${caseFile.location.lat}, ${caseFile.location.lng} with ${caseFile.location.precision_m || 'unknown'} meter accuracy. `;
} else {
briefing += `Location is not currently available. `;
}
// Threat information
if (caseFile?.threat_info?.description) {
briefing += `The threat involves ${caseFile.threat_info.description}`;
if (caseFile.threat_info.distance && caseFile.threat_info.direction) {
briefing += ` approximately ${caseFile.threat_info.distance} ${caseFile.threat_info.direction}`;
}
briefing += `. `;
}
// Communication status
if (caseFile?.can_speak === false) {
briefing += `Important: the person cannot speak safely and may be monitored. `;
} else if (caseFile?.can_speak === true) {
briefing += `The person can communicate and will be connected to this call shortly. `;
}
// Timeline summary
if (caseFile?.timeline?.length > 0) {
const recentEvent = caseFile.timeline[caseFile.timeline.length - 1];
briefing += `Most recent update: ${recentEvent}. `;
}
briefing += `This is a DEMO of how I would connect ${userName} to emergency services. In real deployment, this would be forwarded to authorities.`;
return briefing;
}
// Internal tool handlers for text mode
async function handleEmergencyNotification(sessionId, userName, triggerReason) {
try {
const caseFile = getCaseFile(sessionId);
if (!caseFile) {
return { error: 'Case file not found' };
}
const emergencyReport = generateEmergencyReport(sessionId, caseFile, { name: userName });
// Check throttling
const throttleKey = `emergency:${EMERGENCY_CONTACT.phone}`;
if (!throttle(throttleKey, 60000)) {
return { error: 'Emergency notification rate limit exceeded' };
}
if (twilioClient) {
const sms = await twilioClient.messages.create({
body: emergencyReport,
from: process.env.TWILIO_NUMBER,
to: EMERGENCY_CONTACT.phone
});
console.log(`✅ Emergency notification sent via text mode: ${sms.sid}`);
return { success: true, sms_sid: sms.sid, contact: EMERGENCY_CONTACT.name };
} else {
return { success: true, mock: true, contact: EMERGENCY_CONTACT.name };
}
} catch (error) {
return { error: error.message };
}
}
async function handleSMSAction(sessionId, args) {
try {
const { phone, message, lat, lng, reason } = args;
// Validate and normalize
if (!validateE164Phone(phone)) {
return { error: 'Invalid phone format' };
}
const normalizedPhone = normalizePhone(phone);
// Check throttling
const throttleKey = `sms:${normalizedPhone}`;
if (!throttle(throttleKey, 15000)) {
return { error: 'SMS rate limit exceeded' };
}
// Build message with location
let fullMessage = message;
if (lat && lng) {
fullMessage += `\n\nLive location: https://maps.google.com/maps?q=${lat},${lng}`;
}
fullMessage += `\n\nThis is an automated safety alert from Stacy AI. Time: ${new Date().toLocaleString()}`;
if (twilioClient) {
const sms = await twilioClient.messages.create({
body: fullMessage,
from: process.env.TWILIO_NUMBER,
to: normalizedPhone
});
console.log(`✅ SMS sent via text mode: ${sms.sid}`);
// Update case file
const caseFile = getCaseFile(sessionId);
updateCaseFile(sessionId, {
actions_taken: [...(caseFile.actions_taken || []), `${new Date().toISOString()}: SMS sent to ${normalizedPhone} - ${sms.sid}`]
});
return { success: true, sms_sid: sms.sid, phone: normalizedPhone };
} else {
return { success: true, mock: true, phone: normalizedPhone };
}
} catch (error) {
return { error: error.message };
}
}
// VAPI Emergency Call Handler
async function handleVAPIEmergencyCall(sessionId, args) {
try {
const { user_name, user_phone, can_user_speak, emergency_type, immediate_danger } = args;
const caseFile = getCaseFile(sessionId);
if (!caseFile) {
return { error: 'Case file not found' };
}
// Update case file with emergency details
updateCaseFile(sessionId, {
emergency_type,
immediate_danger,
can_speak: can_user_speak,
actions_taken: [...(caseFile.actions_taken || []), `${new Date().toISOString()}: VAPI emergency call initiated by ${user_name}`]
});
console.log(`🚨 VAPI EMERGENCY CALL - Session ${sessionId}:`, {
user: user_name,
phone: user_phone,
emergency_type,
immediate_danger,
can_speak: can_user_speak,
danger_level: caseFile.danger_level
});
if (!vapiEmergencyService) {
console.error('❌ VAPI Emergency Service not initialized');
return { error: 'VAPI Emergency Service not available' };
}
try {
// Initiate VAPI emergency call with warm handoff
const result = await vapiEmergencyService.initiateEmergencyCall(
sessionId,
caseFile,
{ name: user_name, phone: user_phone }
);
if (result.success) {
// Update case file with VAPI call details
updateCaseFile(sessionId, {
actions_taken: [...(caseFile.actions_taken || []), `${new Date().toISOString()}: VAPI emergency call initiated - ${result.callId}`],
timeline: [...(caseFile.timeline || []), `${new Date().toISOString()}: Stacy calling emergency services via VAPI to brief situation`]
});
console.log(`✅ VAPI emergency call initiated: ${result.callId}`);
return {
success: true,
call_id: result.callId,
assistant_id: result.assistantId,
status: result.status,
message: result.message,
next_step: 'briefing_in_progress'
};
} else {
// VAPI failed, return error instead of fallback
console.error('❌ VAPI emergency call failed:', result.error);
return {
error: 'VAPI emergency call failed',
details: result.error,
fallback_required: false
};
}
} catch (vapiError) {
console.error('❌ VAPI emergency call error:', vapiError);
return {
error: 'VAPI emergency call exception',
details: vapiError.message,
fallback_required: false
};
}
} catch (error) {
console.error('Emergency call handler error:', error);
return { error: error.message };
}
}
// Tool action endpoints
app.post('/api/action/sms', async (req, res) => {
const { sessionId, phone, contact_name, message, lat, lng, urgent, reason } = req.body;
// Validate required fields
if (!phone || !message || !reason) {
return res.status(400).json({ error: 'Missing required fields: phone, message, reason' });
}
// Validate phone format
if (!validateE164Phone(phone)) {
return res.status(400).json({ error: 'Invalid phone format. Use E.164 format (+1234567890)' });
}
// Validate location if provided
if ((lat || lng) && !validateLatLng(lat, lng)) {
return res.status(400).json({ error: 'Invalid latitude/longitude values' });
}
// Validate message length
if (message.length > 280) {
return res.status(400).json({ error: 'Message too long (max 280 characters)' });
}
const normalizedPhone = normalizePhone(phone);
// Check throttling (max 1 SMS per 15 seconds per contact)
const throttleKey = `sms:${normalizedPhone}`;
if (!throttle(throttleKey, 15000)) {
return res.status(429).json({
error: 'SMS rate limit exceeded. Wait 15 seconds between messages to same contact.',
retry_after: 15000
});
}
// Generate idempotency key (10 second window)
const idemKey = generateIdemKey('sms', normalizedPhone, 10000);
// Create location link if coordinates available
let locationLink = '';
if (lat && lng) {
locationLink = `https://maps.google.com/maps?q=${lat},${lng}`;
}
// Build comprehensive safety message
let fullMessage = message;
if (locationLink) {
fullMessage += `\n\nLive location: ${locationLink}`;
}
fullMessage += `\n\nThis is an automated safety alert from Stacy AI. Time: ${new Date().toLocaleString()}`;
// Use redacted logging for PII protection
const logEntry = createSafeLogEntry('sms_action', {
sessionId,
to: normalizedPhone,
contact: contact_name,
message_length: fullMessage.length,
location: { lat, lng },
urgent,
reason
});
console.log(`📱 SMS ACTION:`, logEntry);