Repository navigation
Expand file tree
/
Copy pathagents.js
More file actions
386 lines (351 loc) · 14.3 KB
/
Copy pathagents.js
File metadata and controls
386 lines (351 loc) · 14.3 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
export const taskRegistry = {
medicine_finder: async (parsed, state, tools, model) => {
const context = state.context;
let { medicine, location, dosage, brand, quantity, urgency } = context;
// Check for missing essential information
const missingFields = [];
if (!medicine) {
missingFields.push({ name: 'medicine', label: 'Medicine Name (e.g., Paracetamol, Ibuprofen)', type: 'text' });
}
if (!dosage) {
missingFields.push({
name: 'dosage',
label: 'Dosage (e.g., 200mg, 500mg)',
type: 'text',
placeholder: 'Enter dosage strength'
});
}
// Optional fields - ask if not provided
if (!brand) {
missingFields.push({
name: 'brand',
label: 'Brand Preference (optional, e.g., Crocin, Dolo)',
type: 'text',
optional: true
});
}
if (!quantity) {
missingFields.push({
name: 'quantity',
label: 'Quantity (optional, e.g., 1 strip, 10 tablets)',
type: 'text',
optional: true
});
}
if (!urgency) {
missingFields.push({
name: 'urgency',
label: 'Urgency (optional)',
type: 'select',
options: ['Normal', 'Urgent', 'Emergency'],
optional: true
});
}
if (missingFields.length > 0) {
// Separate required and optional fields
const requiredFields = missingFields.filter(f => !f.optional);
const optionalFields = missingFields.filter(f => f.optional);
// If essential fields are missing, ask for them first
if (requiredFields.length > 0) {
return {
component: 'ClarificationForm',
props: {
fields: requiredFields,
task: 'medicine_finder'
},
agentStatus: 'Planning',
message: parsed.message || 'I need a few details to help you find your medicine. Please provide the medicine name and dosage.'
};
}
// If only optional fields are missing, we can proceed but show them as optional
// For now, let's proceed with what we have
}
// Auto-use user's location if available and no location specified
if (!location && state.userCoordinates && state.userCoordinates.lat && state.userCoordinates.lng) {
if (state.context.location) {
location = state.context.location;
console.log(`[Agent] Auto-using user's location: ${location}`);
} else {
// Reverse geocode to get address
try {
const reverseGeocodeResponse = await fetch(
`https://nominatim.openstreetmap.org/reverse?format=json&lat=${state.userCoordinates.lat}&lon=${state.userCoordinates.lng}`,
{
headers: {
'User-Agent': 'CursorTaskEngine/1.0'
}
}
);
const reverseData = await reverseGeocodeResponse.json();
location = reverseData.display_name || 'Your location';
state.context.location = location;
console.log(`[Agent] Reverse geocoded user coordinates to: ${location}`);
} catch (error) {
location = 'Your location';
state.context.location = location;
console.log(`[Agent] Using default location name for user coordinates`);
}
}
}
if (!location) {
return {
component: 'LocationSelector',
props: {
currentLocation: state.userCoordinates ? 'Using your current location' : undefined,
showUseCurrentLocation: !!state.userCoordinates
},
agentStatus: 'Planning',
message: parsed.message || 'Please select a location or use your current location to search for pharmacies.'
};
}
let searchCoordinates = null;
// Prioritize user's GPS coordinates if available and location matches
const lastLocation = state.context.lastSearchedLocation;
const isUsingUserLocation = location === state.context.location &&
state.userCoordinates &&
state.userCoordinates.lat &&
state.userCoordinates.lng;
if (isUsingUserLocation || (lastLocation === location && state.userCoordinates && state.userCoordinates.lat && state.userCoordinates.lng)) {
searchCoordinates = state.userCoordinates;
console.log(`[Agent] Using user's GPS coordinates for ${location}: ${searchCoordinates.lat}, ${searchCoordinates.lng}`);
} else {
console.log(`[Agent] Geocoding location: ${location} (previous: ${lastLocation || 'none'}, hasCoords: ${!!state.userCoordinates})`);
try {
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) {
searchCoordinates = {
lat: parseFloat(geocodeData[0].lat),
lng: parseFloat(geocodeData[0].lon)
};
// Only update userCoordinates if user explicitly selected a new location
if (!state.userCoordinates || location !== state.context.location) {
state.userCoordinates = searchCoordinates;
state.context.lastSearchedLocation = location;
}
console.log(`[Agent] Geocoded ${location} to: ${searchCoordinates.lat}, ${searchCoordinates.lng}`);
} else {
console.error(`[Agent] Geocoding returned no results for: ${location}`);
}
} catch (error) {
console.error(`[Agent] Geocoding failed:`, error.message);
}
}
console.log(`[Agent] Searching for pharmacies: location=${location}, coordinates=${JSON.stringify(searchCoordinates)}`);
const pharmacies = await tools.searchPharmacies(location, 5, searchCoordinates);
console.log(`[Agent] Found ${pharmacies.length} pharmacies`);
if (pharmacies.length === 0) {
return {
component: 'LocationSelector',
props: {
currentLocation: location,
showUseCurrentLocation: !!state.userCoordinates
},
agentStatus: 'Checking Stores',
message: `I couldn't find any pharmacies in OpenStreetMap data for ${location}. This might be because the area has limited mapping data. Try selecting a major city or use your GPS location.`,
contextUpdate: { medicine, location, dosage }
};
}
// Show MapView with all pharmacies, and CallTerminal below it
const selectedPharmacy = pharmacies[0];
// Generate call transcript using Gemini
const callResult = await tools.generateCallTranscript(
selectedPharmacy,
medicine,
dosage || 'standard',
brand || null,
quantity || null,
urgency || 'normal',
model || null
);
return {
component: 'MapView',
props: {
pharmacies: pharmacies,
userLocation: location,
medicine: medicine,
dosage: dosage || 'standard',
// Include CallTerminal props so it can be rendered together
callTerminal: {
transcript: callResult.transcript,
pharmacy: selectedPharmacy,
medicine: medicine,
dosage: dosage || 'standard',
brand: brand || null,
quantity: quantity || null,
confirmed: callResult.confirmed,
availability: callResult.availability
}
},
agentStatus: 'Found Stores',
message: `Found ${pharmacies.length} nearby pharmacies in ${location}. Showing results and checking availability of ${medicine}${dosage ? ` ${dosage}` : ''}${brand ? ` (${brand} brand)` : ''}.`,
contextUpdate: { medicine, location, dosage, brand, quantity, urgency }
};
},
bali_itinerary: async (parsed, state, tools, model) => {
const context = state.context;
const { dates, budget, interests, itinerary, travelers } = context;
const essentialFields = {
dates: dates,
budget: budget,
interests: interests
};
const hasEssentialInfo = essentialFields.dates && essentialFields.budget && essentialFields.interests;
if (!hasEssentialInfo) {
const missingFields = [];
if (!dates) missingFields.push({ name: 'dates', label: 'Travel Dates (e.g., Jan 1-5 or 5 days)', type: 'text' });
if (!budget) missingFields.push({ name: 'budget', label: 'Budget (USD)', type: 'number' });
if (!interests) missingFields.push({ name: 'interests', label: 'Interests (e.g., rock climbing, seafood, trekking)', type: 'text' });
return {
component: 'ClarificationForm',
props: {
fields: missingFields,
task: 'bali_itinerary'
},
agentStatus: 'Planning',
message: 'I need a few essential details to create your Bali itinerary. Please provide your travel dates, budget, and interests.'
};
}
if (!itinerary) {
let dayCount = 5;
let startDate = 'Jan 1';
if (dates) {
const dayMatch = dates.match(/(\d+)\s*days?/i);
if (dayMatch) {
dayCount = parseInt(dayMatch[1]);
} else {
const dateRangeMatch = dates.match(/([a-z]+)\s+(\d+)[-\s]+(\d+)/i);
if (dateRangeMatch) {
startDate = `${dateRangeMatch[1]} ${dateRangeMatch[2]}`;
const endDay = parseInt(dateRangeMatch[3]);
const startDay = parseInt(dateRangeMatch[2]);
dayCount = endDay - startDay + 1;
}
}
}
const itineraryPrompt = `Create a detailed ${dayCount}-day Bali itinerary for a solo traveler based on:
- Budget: $${budget} USD
- Interests: ${interests}
- Dates: ${dates || `${startDate} onwards`}
- Traveler: Solo
Generate a personalized itinerary that matches ALL the interests mentioned. Make it realistic and detailed with specific place names.
Respond with JSON ONLY in this exact format (no other text):
{
"days": [
{
"day": 1,
"date": "${startDate}",
"activities": [
{"time": "09:00", "activity": "Specific activity name with location", "type": "meal"},
{"time": "10:30", "activity": "Another specific activity", "type": "attraction"},
{"time": "13:00", "activity": "Lunch at specific restaurant", "type": "meal"},
{"time": "15:00", "activity": "Activity matching interests", "type": "activity"},
{"time": "19:00", "activity": "Dinner at specific place", "type": "meal"}
]
},
{
"day": 2,
"date": "Jan 2",
"activities": [...]
}
]
}
Requirements:
- Include activities that match ALL interests: ${interests}
- Use specific place names (e.g., "Rock climbing at Uluwatu cliffs", "Seafood dinner at Jimbaran Bay", "Trekking at Campuhan Ridge")
- Include 4-6 activities per day
- Use realistic times
- Types must be: "meal", "attraction", "activity", or "transport"
- Generate ${dayCount} days total`;
try {
const itineraryResult = await model.generateContent(itineraryPrompt);
const itineraryText = itineraryResult.response.text();
console.log('[Agent] Raw Gemini response length:', itineraryText.length);
const jsonMatch = itineraryText.match(/\{[\s\S]*\}/);
if (!jsonMatch) {
throw new Error('No JSON found in Gemini response');
}
const generatedItinerary = JSON.parse(jsonMatch[0]);
if (generatedItinerary.days && Array.isArray(generatedItinerary.days) && generatedItinerary.days.length > 0) {
context.itinerary = {
days: generatedItinerary.days.map((day, idx) => ({
day: day.day || idx + 1,
date: day.date || `${startDate.split(' ')[0]} ${parseInt(startDate.split(' ')[1] || '1') + idx}`,
activities: (day.activities || []).map(act => ({
time: act.time || '09:00',
activity: act.activity || 'Activity',
type: act.type || 'activity'
}))
})),
budget: budget,
interests: interests
};
console.log('[Agent] Successfully generated itinerary with', context.itinerary.days.length, 'days');
} else {
throw new Error('Invalid itinerary format - missing or empty days array');
}
} catch (error) {
console.error('[Agent] Error generating itinerary:', error.message);
return {
component: null,
props: {},
agentStatus: 'Error',
message: 'I encountered an error generating your itinerary. Please try again.'
};
}
}
const userMessage = parsed.message?.toLowerCase() || '';
if (userMessage.includes('change day') || userMessage.includes('update day')) {
const dayMatch = userMessage.match(/day\s*(\d+)/i);
if (dayMatch) {
const dayNum = parseInt(dayMatch[1]) - 1;
if (context.itinerary && context.itinerary.days[dayNum]) {
const updatePrompt = `Update Day ${dayNum + 1} of a Bali itinerary. User request: "${userMessage}". Current day activities: ${JSON.stringify(context.itinerary.days[dayNum].activities)}.
Respond with JSON only:
{
"activities": [
{"time": "09:00", "activity": "Updated activity", "type": "meal|attraction|activity"}
]
}`;
try {
const updateResult = await model.generateContent(updatePrompt);
const updateText = updateResult.response.text();
const updateJsonMatch = updateText.match(/\{[\s\S]*\}/);
const updated = JSON.parse(updateJsonMatch ? updateJsonMatch[0] : '{}');
if (updated.activities) {
context.itinerary.days[dayNum].activities = updated.activities;
}
} catch (error) {
console.error('[Agent] Error updating day:', error.message);
}
}
}
}
if (!context.itinerary || !context.itinerary.days || context.itinerary.days.length === 0) {
return {
component: null,
props: {},
agentStatus: 'Building Schedule',
message: 'Generating your personalized itinerary... This may take a moment.',
contextUpdate: context
};
}
return {
component: 'ItineraryCard',
props: {
itinerary: context.itinerary,
editable: true
},
agentStatus: 'Building Schedule',
message: parsed.message || 'Here\'s your personalized Bali itinerary!',
contextUpdate: context
};
}
};