Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
721 lines (605 loc) · 27.6 KB
/
Copy pathindex.js
File metadata and controls
721 lines (605 loc) · 27.6 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
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { GoogleGenerativeAI } from '@google/generative-ai';
import { taskRegistry } from './agents.js';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;
// CORS configuration - allow requests from Vercel frontend
const corsOptions = {
origin: process.env.FRONTEND_URL || '*', // In production, set FRONTEND_URL to your Vercel domain
credentials: true,
optionsSuccessStatus: 200
};
app.use(cors(corsOptions));
app.use(express.json());
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey || apiKey === 'your_api_key_here') {
console.error('[Server] GEMINI_API_KEY not set or using placeholder. Please set a valid API key in .env file');
}
const genAI = new GoogleGenerativeAI(apiKey);
const model = genAI.getGenerativeModel({ model: 'gemini-2.5-flash-lite' });
const taskState = new Map();
function calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371;
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLon = (lon2 - lon1) * Math.PI / 180;
const a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
const tools = {
searchPharmacies: async (location, radius = 5, coordinates = null) => {
try {
let lat, lng;
if (coordinates && coordinates.lat && coordinates.lng) {
lat = coordinates.lat;
lng = coordinates.lng;
} else {
const geocodeResponse = await fetch(
`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(location)}&limit=1`,
{
headers: {
'User-Agent': 'CursorTaskEngine/1.0'
}
}
);
const geocodeData = await geocodeResponse.json();
if (geocodeData.length === 0) {
console.error(`[Server] Geocoding failed for location: ${location}`);
throw new Error('Location not found');
}
lat = parseFloat(geocodeData[0].lat);
lng = parseFloat(geocodeData[0].lon);
console.log(`[Server] Geocoded ${location} to coordinates: ${lat}, ${lng}`);
}
console.log(`[Server] Searching pharmacies near ${location} at coordinates ${lat}, ${lng}`);
let searchRadius = radius * 1000;
if (searchRadius > 5000) {
searchRadius = 5000;
console.log(`[Server] Reduced search radius to 5km for dense area`);
}
const overpassQuery = `[out:json][timeout:15];(node["amenity"="pharmacy"](around:${searchRadius},${lat},${lng});node["shop"="pharmacy"](around:${searchRadius},${lat},${lng});way["amenity"="pharmacy"](around:${searchRadius},${lat},${lng}););out center;`;
const endpoints = [
'https://overpass.kumi.systems/api/interpreter',
'https://overpass-api.de/api/interpreter'
];
let overpassData = null;
let lastError = null;
for (const endpoint of endpoints) {
try {
console.log(`[Server] Trying Overpass endpoint: ${endpoint}`);
const overpassResponse = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `data=${encodeURIComponent(overpassQuery)}`
});
const responseText = await overpassResponse.text();
console.log(`[Server] Response status: ${overpassResponse.status}, length: ${responseText.length}`);
if (overpassResponse.status === 504 || overpassResponse.status === 429) {
console.log(`[Server] Endpoint ${endpoint} returned ${overpassResponse.status}, trying next...`);
lastError = `HTTP ${overpassResponse.status}`;
continue;
}
if (!responseText.trim().startsWith('{')) {
console.log(`[Server] Endpoint ${endpoint} returned non-JSON, trying next...`);
lastError = 'Non-JSON response';
continue;
}
try {
overpassData = JSON.parse(responseText);
if (overpassData.elements && overpassData.elements.length >= 0) {
console.log(`[Server] Successfully got ${overpassData.elements.length} elements from ${endpoint}`);
break;
}
} catch (e) {
console.error(`[Server] Failed to parse response from ${endpoint}:`, e.message);
lastError = e.message;
continue;
}
} catch (error) {
console.error(`[Server] Request to ${endpoint} failed:`, error.message);
lastError = error.message;
continue;
}
}
if (!overpassData) {
console.error(`[Server] All Overpass endpoints failed. Last error: ${lastError}`);
return [];
}
console.log(`[Server] Found ${overpassData.elements?.length || 0} pharmacy elements`);
if (!overpassData || !overpassData.elements || overpassData.elements.length === 0) {
console.log(`[Server] No pharmacies found. OSM data may be limited in this area.`);
return [];
}
const pharmacies = overpassData.elements
.slice(0, 15)
.map((element) => {
const elat = element.lat || element.center?.lat;
const elng = element.lon || element.center?.lon;
if (!elat || !elng) return null;
const distance = calculateDistance(lat, lng, elat, elng);
let phone = 'Not available';
let addressParts = [];
if (element.tags?.['addr:street']) addressParts.push(element.tags['addr:street']);
if (element.tags?.['addr:housenumber']) addressParts.push(element.tags['addr:housenumber']);
if (element.tags?.['addr:city']) addressParts.push(element.tags['addr:city']);
if (element.tags?.['addr:state']) addressParts.push(element.tags['addr:state']);
let address = element.tags?.['addr:full'] ||
(addressParts.length > 0 ? addressParts.join(', ') : null) ||
element.tags?.['addr:city'] ||
location ||
'Address not available';
if (element.tags?.['phone']) {
phone = element.tags.phone;
} else if (element.tags?.['contact:phone']) {
phone = element.tags['contact:phone'];
}
const name = element.tags?.name || element.tags?.['name:en'] || 'Pharmacy';
return {
name,
address: address || location,
distance: `${distance.toFixed(1)} km`,
phone,
lat: elat,
lng: elng,
stock: true
};
})
.filter(Boolean);
return pharmacies.sort((a, b) =>
parseFloat(a.distance) - parseFloat(b.distance)
);
} catch (error) {
console.error('[Server] Pharmacy search error:', error.message);
console.error('[Server] Error stack:', error.stack);
return [];
}
},
searchBaliData: async (query) => {
const mockData = {
attractions: ['Ubud Monkey Forest', 'Tanah Lot Temple', 'Tegallalang Rice Terraces'],
hotels: ['The St. Regis Bali Resort', 'Four Seasons Resort Bali', 'COMO Shambhala Estate'],
restaurants: ['Locavore', 'Merah Putih', 'Mozaic Restaurant Gastronomique']
};
return mockData;
},
generateCallTranscript: async (pharmacy, medicine, dosage, brand = null, quantity = null, urgency = 'normal', model = null) => {
// Use Gemini to generate a realistic call transcript
if (model) {
try {
const brandText = brand ? ` (preferred brand: ${brand})` : '';
const quantityText = quantity ? `, quantity needed: ${quantity}` : '';
const urgencyText = urgency === 'urgent' ? ' (urgent request)' : urgency === 'emergency' ? ' (emergency - needed immediately)' : '';
const prompt = `Generate a realistic, natural phone call transcript between a customer and a pharmacist.
Context:
- Pharmacy: ${pharmacy.name}
- Phone: ${pharmacy.phone || 'Not available'}
- Customer is calling to check availability of: ${medicine} ${dosage}${brandText}${quantityText}${urgencyText}
Generate a realistic conversation transcript that includes:
1. Customer greeting and request
2. Pharmacist checking stock
3. Natural back-and-forth conversation
4. Outcome (available or limited stock)
5. If available: confirmation and hold request
6. If limited: alternative suggestions
Make it sound natural and realistic. Include some variation - sometimes the medicine is available, sometimes it's limited stock. Be conversational and professional.
Format the transcript as:
[SIMULATED CALL TRANSCRIPT]
Calling: ${pharmacy.name}
Phone: ${pharmacy.phone || 'Not available'}
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
You: "[customer's opening]"
Pharmacist: "[pharmacist's response]"
[Continue the conversation naturally...]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Note: This is a simulated call transcript for demonstration purposes.
Respond with ONLY the transcript, no additional text.`;
const result = await model.generateContent(prompt);
const generatedTranscript = result.response.text();
// Determine availability from the transcript
const hasStock = generatedTranscript.toLowerCase().includes('available') ||
generatedTranscript.toLowerCase().includes('yes') ||
generatedTranscript.toLowerCase().includes('have it') ||
generatedTranscript.toLowerCase().includes('in stock');
const availability = hasStock ? 'available' : 'limited stock';
return {
pharmacy: pharmacy.name,
phone: pharmacy.phone,
transcript: generatedTranscript.trim(),
confirmed: hasStock,
availability: availability
};
} catch (error) {
console.error('[Server] Error generating call transcript with Gemini:', error.message);
// Fallback to template if Gemini fails
}
}
// Fallback template if Gemini is not available
const brandText = brand ? ` (${brand} brand)` : '';
const quantityText = quantity ? ` - ${quantity}` : '';
const urgencyText = urgency === 'urgent' ? ' urgently' : urgency === 'emergency' ? ' immediately (emergency)' : '';
const availability = Math.random() > 0.3 ? 'available' : 'limited stock';
const hasStock = availability === 'available';
let transcript = `[SIMULATED CALL TRANSCRIPT]\n\n`;
transcript += `Calling: ${pharmacy.name}\n`;
transcript += `Phone: ${pharmacy.phone || 'Not available'}\n`;
transcript += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n`;
transcript += `You: "Hello, I'm calling to check if you have ${medicine}${brandText} ${dosage}${quantityText} in stock${urgencyText}?"\n\n`;
if (hasStock) {
transcript += `Pharmacist: "Yes, we have ${medicine} ${dosage}${brandText ? ` - ${brand} brand` : ''} in stock.`;
if (quantity) {
transcript += ` We can provide ${quantity}.`;
}
transcript += ` Would you like us to hold it for you?"\n\n`;
transcript += `You: "Yes, please hold it. I'll be there in about 20 minutes."\n\n`;
transcript += `Pharmacist: "Perfect! I'll have it ready at the counter.`;
if (urgency === 'urgent' || urgency === 'emergency') {
transcript += ` We'll prioritize your order.`;
}
transcript += ` See you soon!"\n\n`;
transcript += `Confirmed: Medicine will be held for pickup`;
} else {
transcript += `Pharmacist: "I'm sorry, we currently have limited stock of ${medicine} ${dosage}.`;
if (brand) {
transcript += ` We don't have the ${brand} brand, but we have other brands available.`;
}
transcript += ` Would you like me to check our other branch or suggest an alternative?"\n\n`;
transcript += `You: "Yes, please check if your other branch has it, or suggest an alternative."\n\n`;
transcript += `Pharmacist: "Let me check... Our branch on Main Street has it in stock. Would you like me to transfer you or provide their number?"\n\n`;
transcript += `You: "Please provide their number. Thank you!"\n\n`;
transcript += `Pharmacist: "Sure! Their number is [Branch Phone]. Have a good day!"\n\n`;
transcript += `Limited Stock: Alternative location suggested`;
}
transcript += `\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
transcript += `Note: This is a simulated call transcript for demonstration purposes.`;
return {
pharmacy: pharmacy.name,
phone: pharmacy.phone,
transcript: transcript,
confirmed: hasStock,
availability: availability
};
}
};
function extractContext(userMessage, currentContext, model = null) {
const lowerMessage = userMessage.toLowerCase();
const context = { ...currentContext };
if (lowerMessage.includes('medicine') || lowerMessage.includes('pharmacy') || lowerMessage.includes('drug') || lowerMessage.includes('pill') ||
lowerMessage.includes('paracetamol') || lowerMessage.includes('ibuprofen') || lowerMessage.includes('aspirin') ||
lowerMessage.includes('find') && (lowerMessage.includes('near') || lowerMessage.includes('me'))) {
// Better medicine name extraction - handles "find paracetamol", "need ibuprofen", etc.
const medicinePatterns = [
/(?:find|search|need|looking for|want|get)\s+(?:me\s+)?([a-z]+(?:\s+[a-z]+)*?)(?:\s+\d+[mg]|\s+near|\s+me|\s+in|$)/i,
/(?:find|search|need|looking for|want|get)\s+([a-z]+(?:\s+[a-z]+)*?)\s+(?:near|in|at)/i,
/\b(paracetamol|ibuprofen|aspirin|dolo|crocin|calpol|disprin|combiflam|vicks|strepsils|betadine|bandaid|band-aid)\b/i
];
for (const pattern of medicinePatterns) {
const match = userMessage.match(pattern);
if (match && match[1]) {
const potentialMedicine = match[1].trim().toLowerCase();
// Exclude common location words
if (!['near', 'me', 'in', 'at', 'location', 'city'].includes(potentialMedicine)) {
context.medicine = match[1].trim();
break;
}
}
}
// Dosage extraction - handles "200mg", "500 mg", "500mg"
const dosageMatch = userMessage.match(/(\d+\s*mg|mg\s*\d+)/i);
if (dosageMatch) {
context.dosage = dosageMatch[1].replace(/\s+/g, '').toLowerCase();
}
// Brand extraction
const brandMatch = userMessage.match(/(?:brand|prefer|want)\s+([a-z]+(?:\s+[a-z]+)*)/i);
if (brandMatch) {
context.brand = brandMatch[1].trim();
}
// Quantity extraction
const quantityMatch = userMessage.match(/(\d+)\s*(?:strips?|tablets?|pills?|packets?|boxes?)/i);
if (quantityMatch) {
context.quantity = quantityMatch[1];
}
// Urgency extraction
if (lowerMessage.includes('urgent') || lowerMessage.includes('asap') || lowerMessage.includes('emergency') || lowerMessage.includes('immediately')) {
context.urgency = 'urgent';
}
// Location extraction
const locationMatch = userMessage.match(/(?:near|in|at|search|find).*?(?:in|near|at)\s+([a-z\s,]+?)(?:\s+\d+[mg]|\s+for|$)/i);
if (locationMatch) {
context.location = locationMatch[1].trim();
} else if (lowerMessage.includes('near me')) {
// "near me" is handled by userCoordinates
context.location = 'near me';
}
}
if (lowerMessage.includes('bali') || lowerMessage.includes('itinerary') || lowerMessage.includes('trip')) {
const budgetMatch = userMessage.match(/(?:budget|spend|have|allocation)[:\s]*\$?(\d+)/i) || userMessage.match(/budget:\s*(\d+)/i);
if (budgetMatch) {
context.budget = budgetMatch[1];
}
const dateMatch = userMessage.match(/(?:dates?|from|trip|travel)[:\s]*([a-z]+\s+\d+(?:\s*-\s*[a-z]+\s+\d+)?|\d+\s+days?)/i) || userMessage.match(/dates?:\s*([^,]+)/i);
if (dateMatch) {
context.dates = dateMatch[1];
} else if (lowerMessage.includes('day') && !context.dates) {
const dayMatch = userMessage.match(/(\d+)\s*day/i);
if (dayMatch) {
context.dates = `${dayMatch[1]} days`;
}
}
const interestsMatch = userMessage.match(/(?:interest|like|enjoy|prefer|want)[:\s]*([^,]+(?:,\s*[^,]+)*)/i) || userMessage.match(/interests?:\s*([^,]+(?:,\s*[^,]+)*)/i);
if (interestsMatch) {
context.interests = interestsMatch[1].trim();
}
const travelersMatch = userMessage.match(/(?:people|travelers?|persons?|guests?)[:\s]*(\d+)/i) || userMessage.match(/(\d+)\s*(?:people|travelers?|persons?)/i);
if (travelersMatch) {
context.travelers = travelersMatch[1];
}
}
const keyValuePairs = userMessage.match(/(\w+):\s*([^,]+)/g);
if (keyValuePairs) {
keyValuePairs.forEach(pair => {
const [key, value] = pair.split(':').map(s => s.trim());
if (['medicine', 'location', 'dosage', 'dates', 'budget', 'interests'].includes(key.toLowerCase())) {
context[key.toLowerCase()] = value;
}
});
}
return context;
}
async function processWithRuleBasedFallback(userMessage, state) {
const lowerMessage = userMessage.toLowerCase();
const context = state.context;
if (lowerMessage.includes('medicine') || lowerMessage.includes('pharmacy') || lowerMessage.includes('drug') || lowerMessage.includes('pill')) {
const medicineMatch = userMessage.match(/(?:find|search|need|looking for|want)\s+(?:me\s+)?([a-z]+(?:\s+[a-z]+)*?)(?:\s+\d+[mg]|\s+near|\s+in|$)/i);
const dosageMatch = userMessage.match(/(\d+\s*mg)/i);
const locationMatch = userMessage.match(/(?:near|in|at|search|find).*?(?:in|near|at)\s+([a-z\s,]+?)(?:\s+\d+[mg]|\s+for|$)/i);
if (medicineMatch) context.medicine = medicineMatch[1].trim();
if (dosageMatch) context.dosage = dosageMatch[1];
if (locationMatch) context.location = locationMatch[1].trim();
const keyValuePairs = userMessage.match(/(\w+):\s*([^,]+)/g);
if (keyValuePairs) {
keyValuePairs.forEach(pair => {
const [key, value] = pair.split(':').map(s => s.trim());
if (['medicine', 'location', 'dosage'].includes(key.toLowerCase())) {
context[key.toLowerCase()] = value;
}
});
}
if (!context.medicine || !context.location || !context.dosage) {
const missingFields = [];
if (!context.medicine) missingFields.push({ name: 'medicine', label: 'Medicine Name', type: 'text' });
if (!context.dosage) missingFields.push({ name: 'dosage', label: 'Dosage (e.g., 200mg)', type: 'text' });
if (!context.location) {
return {
message: 'Please select a location to search for pharmacies.',
component: 'LocationSelector',
props: { currentLocation: state.userCoordinates ? 'Using your current location' : undefined },
agentStatus: 'Planning',
nextSuggestedActions: []
};
}
if (missingFields.length > 0) {
return {
message: 'I need a bit more information to help you find your medicine.',
component: 'ClarificationForm',
props: { fields: missingFields, task: 'medicine_finder' },
agentStatus: 'Planning',
nextSuggestedActions: []
};
}
}
if (context.medicine && context.location && context.dosage) {
const taskHandler = taskRegistry.medicine_finder;
const taskResult = await taskHandler(
{ message: `Find ${context.medicine} ${context.dosage} in ${context.location}` },
state,
tools
);
return {
message: taskResult.message,
component: taskResult.component,
props: taskResult.props || {},
agentStatus: taskResult.agentStatus || 'Checking Stores',
nextSuggestedActions: []
};
}
}
return {
message: 'I\'m currently experiencing high API usage. Please try again in a few minutes, or be more specific with your request (e.g., "Find ibuprofen 200mg in Kolkata").',
component: null,
props: {},
agentStatus: 'Error',
nextSuggestedActions: []
};
}
async function processWithOrchestrator(userMessage, sessionId, userLocation = null) {
if (!taskState.has(sessionId)) {
taskState.set(sessionId, {
currentTask: null,
context: {},
history: []
});
}
const state = taskState.get(sessionId);
if (userLocation && userLocation.lat && userLocation.lng) {
state.userCoordinates = { lat: userLocation.lat, lng: userLocation.lng };
if (userLocation.address) {
state.context.location = userLocation.address;
}
}
state.context = extractContext(userMessage, state.context, model);
if (userMessage.toLowerCase().includes('search pharmacies in') || userMessage.toLowerCase().includes('pharmacies in')) {
const locationMatch = userMessage.match(/(?:search pharmacies in|pharmacies in)\s+(.+)/i);
if (locationMatch) {
const newLocation = locationMatch[1].trim();
state.context.location = newLocation;
state.userCoordinates = null;
state.context.lastSearchedLocation = null;
console.log(`[Server] Extracted new location from message: ${newLocation}, cleared old coordinates`);
}
}
// Handle "use my current location" or "using my current location"
if (userMessage.toLowerCase().includes('using my current location') ||
userMessage.toLowerCase().includes('use my current location') ||
userMessage.toLowerCase().includes('find medicine using my current location')) {
if (userLocation && userLocation.lat && userLocation.lng) {
state.userCoordinates = { lat: userLocation.lat, lng: userLocation.lng };
if (userLocation.address) {
state.context.location = userLocation.address;
}
console.log(`[Server] Using user's current location: ${state.context.location || 'coordinates only'}`);
}
}
state.history.push({ role: 'user', content: userMessage });
const systemPrompt = `You are an orchestrator that manages task completion. Extract information and decide:
1. Which task the user wants (medicine_finder, bali_itinerary, or unknown)
2. What information is still missing
3. What component to render
4. What actions to suggest
Available tasks: ${Object.keys(taskRegistry).join(', ')}
Current extracted context: ${JSON.stringify(state.context)}
Respond ONLY with valid JSON:
{
"task": "medicine_finder or bali_itinerary or null",
"missingInfo": ["field1", "field2"],
"component": "ComponentName or null",
"props": {},
"agentStatus": "Thinking|Planning|Calling|Checking Stores|Building Schedule",
"nextActions": ["action1", "action2"],
"message": "Brief response to user",
"contextUpdate": {"field": "value"}
}`;
try {
const previousHistory = state.history
.slice(0, -1)
.slice(-6)
.map(msg => ({
role: msg.role === 'user' ? 'user' : 'model',
parts: [{ text: msg.content }]
}));
let result;
let response;
try {
if (previousHistory.length > 0 && previousHistory[0].role === 'user') {
const chat = model.startChat({ history: previousHistory });
const prompt = `${systemPrompt}\n\nUser message: ${userMessage}\n\nRespond with JSON only, no markdown.`;
result = await chat.sendMessage(prompt);
} else {
const prompt = `${systemPrompt}\n\nUser message: ${userMessage}\n\nRespond with JSON only, no markdown.`;
result = await model.generateContent(prompt);
}
response = result.response.text();
} catch (error) {
if (error.message.includes('429') || error.message.includes('quota') || error.message.includes('rate limit')) {
console.error('[Server] Gemini API quota exceeded. Using rule-based fallback.');
return await processWithRuleBasedFallback(userMessage, state);
}
throw error;
}
let parsed;
try {
const jsonMatch = response.match(/\{[\s\S]*\}/);
parsed = JSON.parse(jsonMatch ? jsonMatch[0] : response);
} catch (e) {
parsed = {
task: null,
message: response,
component: null,
props: {},
agentStatus: 'Thinking',
nextActions: []
};
}
if (parsed.toolCalls && parsed.toolCalls.length > 0) {
for (const toolCall of parsed.toolCalls) {
const tool = tools[toolCall.name];
if (tool) {
const toolResult = await tool(...Object.values(toolCall.args || {}));
parsed.toolResults = parsed.toolResults || {};
parsed.toolResults[toolCall.name] = toolResult;
}
}
}
if (parsed.contextUpdate) {
Object.assign(state.context, parsed.contextUpdate);
}
if (parsed.task && taskRegistry[parsed.task]) {
const taskHandler = taskRegistry[parsed.task];
const taskResult = await taskHandler(parsed, state, tools, model);
Object.assign(parsed, taskResult);
if (taskResult.contextUpdate) {
Object.assign(state.context, taskResult.contextUpdate);
}
}
state.history.push({ role: 'assistant', content: parsed.message });
const apiResponse = {
message: parsed.message,
component: parsed.component,
props: parsed.props || {},
agentStatus: parsed.agentStatus || 'Thinking',
nextSuggestedActions: parsed.nextActions || []
};
// If there's a nextComponent (e.g., CallTerminal after MapView), include it
if (parsed.nextComponent) {
apiResponse.nextComponent = parsed.nextComponent;
}
return apiResponse;
} catch (error) {
console.error('[Server] Error:', error.message);
return {
message: 'An error occurred while processing your request.',
component: null,
props: {},
agentStatus: 'Error',
nextSuggestedActions: []
};
}
}
app.post('/api/chat', async (req, res) => {
try {
const { message, sessionId = 'default', userLocation } = req.body;
if (!message) {
return res.status(400).json({ error: 'Message is required' });
}
console.log(`[Server] Received message: "${message}"`);
if (userLocation) {
console.log(`[Server] User location provided: ${JSON.stringify(userLocation)}`);
}
const result = await processWithOrchestrator(message, sessionId, userLocation);
console.log(`[Server] Response: component=${result.component}, status=${result.agentStatus}`);
res.json(result);
} catch (error) {
console.error('[Server] Chat error:', error.message);
console.error('[Server] Error stack:', error.stack);
res.status(500).json({ error: 'Internal server error' });
}
});
app.get('/api/test-pharmacy/:location', async (req, res) => {
try {
const { location } = req.params;
console.log(`[Server] Test pharmacy search for: ${location}`);
const pharmacies = await tools.searchPharmacies(location, 5);
res.json({ location, count: pharmacies.length, pharmacies });
} catch (error) {
console.error('[Server] Test error:', error.message);
res.status(500).json({ error: error.message });
}
});
app.use((err, req, res, next) => {
console.error('[Server] Unhandled error:', err.message);
res.status(500).json({ error: 'Internal server error' });
});
app.listen(PORT, '0.0.0.0', () => {
console.log(`[Server] Listening on port ${PORT}`);
console.log(`[Server] Environment: ${process.env.NODE_ENV || 'development'}`);
if (process.env.FRONTEND_URL) {
console.log(`[Server] Frontend URL: ${process.env.FRONTEND_URL}`);
}
});