-
Notifications
You must be signed in to change notification settings - Fork 287
Expand file tree
/
Copy pathmain.py
More file actions
3709 lines (3140 loc) · 145 KB
/
main.py
File metadata and controls
3709 lines (3140 loc) · 145 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 asyncio
import datetime
import json
import os
import random
import re
import requests
from src.agent.capability import MatchingCapability
from src.agent.capability_worker import CapabilityWorker
from src.main import AgentWorker
# =============================================================================
# CONFIG
# =============================================================================
GRAPH_ACCESS_TOKEN = "YOUR_TOKEN_HERE"
GRAPH_BASE_URL = "https://graph.microsoft.com/v1.0"
YOUR_EMAIL = "YOUR_EMAIL_HERE"
EXIT_WORDS = [
"done",
"that's it",
"thats it",
"exit",
"stop",
"quit",
"go to sleep",
"goodbye",
"bye",
"nothing else",
"all good",
"nope",
"no thanks",
"i'm good",
"im good",
]
# =============================================================================
# WEATHER & GEO CONSTANTS
# =============================================================================
CLOUD_INDICATORS = [
"amazon",
"aws",
"google",
"microsoft",
"azure",
"digitalocean",
"linode",
"vultr",
"hetzner",
"ovh",
"oracle",
"cloudflare",
"rackspace",
"ibm cloud",
]
WEATHER_DESCRIPTIONS = {
0: "clear skies",
1: "mostly clear",
2: "partly cloudy",
3: "overcast",
45: "foggy",
48: "foggy with frost",
51: "light drizzle",
53: "drizzle",
55: "heavy drizzle",
61: "light rain",
63: "rain",
65: "heavy rain",
71: "light snow",
73: "snow",
75: "heavy snow",
77: "snow grains",
80: "light rain showers",
81: "rain showers",
82: "heavy rain showers",
85: "light snow showers",
86: "heavy snow showers",
95: "thunderstorm",
96: "thunderstorm with light hail",
99: "thunderstorm with heavy hail",
}
IMPERIAL_COUNTRIES = ["US"]
# =============================================================================
# DYNAMIC GREETINGS
# =============================================================================
TIME_GREETINGS = {
"morning": ["Good morning", "Morning", "Hey, good morning"],
"afternoon": ["Good afternoon", "Afternoon", "Hey"],
"evening": ["Good evening", "Evening", "Hey there"],
"night": ["Hey", "Hi there", "Hey there"],
}
FILLER_LINES = {
"morning": [
"One sec, pulling up your day.",
"Let me check what's on tap today.",
"Grabbing your schedule.",
],
"afternoon": [
"One sec, checking what's left today.",
"Let me see what's coming up.",
"Pulling up the rest of your day.",
],
"evening": [
"One sec, checking your evening.",
"Let me see what's left tonight.",
"Pulling up the rest of your day.",
],
"night": [
"One sec, checking your schedule.",
"Let me see what's on the books.",
"Hang on, pulling things up.",
],
}
def get_time_bucket(hour):
"""Return time bucket based on hour."""
if 5 <= hour < 12:
return "morning"
elif 12 <= hour < 17:
return "afternoon"
elif 17 <= hour < 21:
return "evening"
else:
return "night"
# =============================================================================
# SYSTEM PROMPT
# =============================================================================
HUB_SYSTEM_PROMPT = """You are Smart Hub, a concise voice assistant that gives quick, natural spoken briefings.
USER CONTEXT:
- Name: {user_name}
- Location: {city}, {region}
- Local time: {current_time} ({time_bucket})
- Day: {day_of_week}, {current_date}
{weather_line}
Rules:
- Keep responses to 2-4 sentences max. This is voice, not text.
- Be conversational and natural, like a sharp assistant who knows their day.
- Never use bullet points, numbered lists, or markdown formatting.
- When summarizing calendar events, mention time, title, and relevant context.
- For events marked [IN PROGRESS], say they're "happening now" or "going on right now" and mention how much time is left.
- For events marked [STARTING IN Xm], give a heads up that they're coming up soon.
- If there's nothing notable, say so briefly.
- When the user seems done or says goodbye, respond with a short sign-off.
- Use the user's name naturally when it fits.
- ONLY mention weather if there's an in-person meeting with a physical address/location.
- When reading email addresses, say "at" instead of "@" (e.g., "jane at example dot com").
- You can help reschedule, push back, shorten, cancel, or invite people to calendar events when asked.
"""
# =============================================================================
# TRIGGER CONTEXT CLASSIFIER (determines Quick vs Full mode)
# =============================================================================
TRIGGER_INTENT_PROMPT = """What does the user want from their calendar based on their CURRENT request?
The user just said: "{trigger}"
IMPORTANT: Only classify based on what the user JUST said (the trigger above). Ignore any previous conversation context.
Classify the intent:
- "read_today" - wants to know their schedule (e.g. "what's on my calendar", "my schedule today")
- "read_specific" - asking about a specific time or event
- "create" - explicitly wants to create/schedule a new event
- "modify" - wants to change an existing event
- "cancel" - wants to cancel/delete an event
- "invite" - wants to add someone to an event
- "full_briefing" - wants a comprehensive catch-up (e.g. "catch me up", "what's going on")
Determine mode:
- "quick" - specific question or action
- "full" - wants comprehensive briefing
If the trigger is about CREATING an event, extract specifics:
- time: the time mentioned (e.g. "3pm", "8 PM")
- person: any person name mentioned
- event_name: the meeting/event title
- duration: how long (if mentioned)
Return JSON only:
{{"intent": "...", "mode": "quick|full", "details": {{"time": null, "person": null, "event_name": null, "duration": null, "email": null}}}}
"""
# =============================================================================
# CALENDAR INTENT CLASSIFIER (for in-session modifications)
# =============================================================================
CALENDAR_INTENT_PROMPT = """Analyze if the user wants to modify their calendar. Return ONLY valid JSON.
User message: "{user_message}"
Current calendar context:
{calendar_context}
Classify the intent:
- "none" - No calendar modification requested (just asking questions, chatting)
- "reschedule" - Move an event to a different time (push back, bump, move, reschedule)
- "shorten" - Make an event shorter/end earlier
- "extend" - Make an event longer
- "cancel" - Cancel/delete an event
- "create" - Create a new event/meeting
- "invite" - Add a person/guest/attendee to an existing event (invite someone, add guest, include someone)
CRITICAL - change_minutes sign convention:
- POSITIVE = event moves to a LATER time (into the future)
- NEGATIVE = event moves to an EARLIER time (into the past)
Common phrases and their CORRECT sign:
- "push back 30 minutes" → change_minutes: 30 (positive, later)
- "move back 30 minutes" → change_minutes: 30 (positive, later)
- "bump back an hour" → change_minutes: 60 (positive, later)
- "delay by 15 minutes" → change_minutes: 15 (positive, later)
- "move up 30 minutes" → change_minutes: -30 (negative, earlier)
- "bump up an hour" → change_minutes: -60 (negative, earlier)
- "make it earlier by 15" → change_minutes: -15 (negative, earlier)
"Back" = LATER = POSITIVE. "Up" = EARLIER = NEGATIVE.
If a calendar action is detected, identify:
- Which event (by title, attendee name, or time) for modify/cancel/invite actions
- What change (minutes to push, new duration, etc.)
- For CREATE: extract the title, time, and duration if mentioned
- For INVITE: extract the email address if mentioned, and which meeting to add them to
Return JSON only:
{{"intent": "none|reschedule|shorten|extend|cancel|create|invite", "event_match": "string describing which event or null", "change_minutes": number_or_null, "new_duration_minutes": number_or_null, "new_event_title": "title for new event or null", "new_event_time": "time like '4AM' or '3:30 PM' or null", "new_event_duration_minutes": number_or_null, "invite_email": "email address to invite or null", "reason": "brief explanation"}}
"""
CONFLICT_CHECK_PROMPT = """Check if this calendar change causes conflicts.
Proposed change: {change_description}
All events today (with times):
{all_events}
Current time: {current_time}
Analyze:
1. Will moving/extending this event overlap with another?
2. Which events are affected?
3. What adjustments would fix the conflicts?
Return JSON only:
{{"has_conflict": true|false, "conflicting_events": ["event titles"], "suggested_fix": "brief suggestion", "cascade_needed": true|false}}
"""
# =============================================================================
# MAIN CLASS
# =============================================================================
class OutlookCapability(MatchingCapability):
worker: AgentWorker = None
capability_worker: CapabilityWorker = None
context: dict = None
session_history: list = None
geo_context: dict = None
last_session_timestamp: str = None
user_name: str = ""
user_email: str = ""
pending_calendar_action: dict = None # Tracks pending cascade/confirmation
pending_create: dict = (
None # Tracks create flow: {"title": "...", "waiting_for": "title|time"}
)
pending_invite: dict = (
None # Tracks invite flow: {"event": ..., "waiting_for": "email|event"}
)
calendar_timezone: str = (
"America/New_York" # Default, will be overridden by calendar data
)
session_mode: str = "full" # "quick" or "full"
trigger_data: dict = None # Stores classified trigger intent
# {{register capability}}
#{{register_capability}}
def call(self, worker: AgentWorker):
self.worker = worker
self.capability_worker = CapabilityWorker(self.worker)
self.context = {}
self.session_history = []
self.geo_context = {}
self.last_session_timestamp = None
self.user_name = ""
self.user_email = ""
self.pending_calendar_action = None
self.pending_create = None
self.pending_invite = None
self.calendar_timezone = "America/New_York"
self.session_mode = "full"
self.trigger_data = {}
self.worker.session_tasks.create(self.run_hub())
def log(self, msg):
self.worker.editor_logging_handler.info(f"[Hub] {msg}")
def log_err(self, msg):
self.worker.editor_logging_handler.error(f"[Hub] {msg}")
async def user_response_with_timeout(self, timeout_seconds: float = 15.0):
"""Wait for user response with timeout. Returns None on silence/timeout."""
try:
response = await asyncio.wait_for(
self.capability_worker.user_response(), timeout=timeout_seconds
)
return response
except asyncio.TimeoutError:
self.log("User response timeout - silence detected")
return None
except Exception as e:
self.log_err(f"User response error: {e}")
return None
# =========================================================================
# COMPOSIO LAYER
# =========================================================================
def execute_tool(self, tool_slug, params):
"""
Microsoft Graph adapter.
Converts Graph responses into the Google-shaped format
expected by the rest of SmartHub.
"""
headers = {
"Authorization": f"Bearer {GRAPH_ACCESS_TOKEN}",
"Content-Type": "application/json",
}
try:
# ==========================================================
# PROFILE
# ==========================================================
if tool_slug == "OUTLOOKSUPER_GET_PROFILE":
url = f"{GRAPH_BASE_URL}/me"
resp = requests.get(url, headers=headers, timeout=15)
if resp.status_code != 200:
self.log_err(f"Graph profile error: {resp.text}")
return None
data = resp.json()
# Normalize to expected format
return {
"emailAddress": data.get("mail") or data.get("userPrincipalName"),
"displayName": data.get("displayName"),
}
# ==========================================================
# FIND EVENTS
# ==========================================================
if tool_slug == "OUTLOOKCALENDAR_FIND_EVENT":
url = f"{GRAPH_BASE_URL}/users/{YOUR_EMAIL}/calendarView"
query = {
"startDateTime": params.get("timeMin"),
"endDateTime": params.get("timeMax"),
"$orderby": "start/dateTime",
"$top": params.get("maxResults", 15),
}
resp = requests.get(url, headers=headers, params=query, timeout=15)
if resp.status_code != 200:
self.log_err(f"Graph fetch error: {resp.text}")
return None
graph_data = resp.json()
items = graph_data.get("value", [])
# Normalize Graph → Google-style shape
WINDOWS_TZ_MAP = {
"Eastern Standard Time": "America/New_York",
"Central Standard Time": "America/Chicago",
"Mountain Standard Time": "America/Denver",
"Pacific Standard Time": "America/Los_Angeles",
}
def trim_iso(dt):
if dt and "." in dt:
return dt[:26] # Fix 7-digit microseconds
return dt
normalized_items = []
for event in items:
# ---- TIMEZONE FIX ----
raw_start_tz = event.get("start", {}).get("timeZone")
raw_end_tz = event.get("end", {}).get("timeZone")
start_tz = WINDOWS_TZ_MAP.get(raw_start_tz, raw_start_tz)
end_tz = WINDOWS_TZ_MAP.get(raw_end_tz, raw_end_tz)
# ---- ATTENDEES FIX ----
attendees = []
for a in event.get("attendees", []):
email_obj = a.get("emailAddress", {})
attendees.append(
{
"displayName": email_obj.get("name") or "",
"email": email_obj.get("address") or "",
}
)
# ---- LOCATION SAFE ----
location_obj = event.get("location") or {}
location = location_obj.get("displayName") or ""
# ---- ONLINE MEETING SAFE ----
online = event.get("onlineMeeting") or {}
join_url = online.get("joinUrl")
normalized_items.append(
{
"id": event.get("id", ""),
"summary": event.get("subject") or "Untitled",
"start": {
"dateTime": trim_iso(
event.get("start", {}).get("dateTime")
),
"timeZone": start_tz or "UTC",
},
"end": {
"dateTime": trim_iso(
event.get("end", {}).get("dateTime")
),
"timeZone": end_tz or "UTC",
},
"location": location,
"attendees": attendees,
"description": event.get("bodyPreview") or "",
"status": event.get("showAs") or "",
"hangoutLink": join_url,
"htmlLink": event.get("webLink"),
"conferenceData": online or None,
}
)
return {"items": normalized_items}
# ==========================================================
# CREATE EVENT
# ==========================================================
if tool_slug == "OUTLOOKCALENDAR_CREATE_EVENT":
url = f"{GRAPH_BASE_URL}/me/events"
start_dt = datetime.datetime.fromisoformat(
params["start_datetime"].replace("Z", "+00:00")
)
duration_minutes = params.get(
"event_duration_hour", 0
) * 60 + params.get("event_duration_minutes", 0)
end_dt = start_dt + datetime.timedelta(minutes=duration_minutes)
body = {
"subject": params.get("summary"),
"start": {
"dateTime": start_dt.isoformat(),
"timeZone": params.get("timezone", "UTC"),
},
"end": {
"dateTime": end_dt.isoformat(),
"timeZone": params.get("timezone", "UTC"),
},
}
if params.get("location"):
body["location"] = {"displayName": params.get("location")}
if params.get("description"):
body["body"] = {
"contentType": "text",
"content": params.get("description"),
}
if params.get("attendees"):
body["attendees"] = [
{"emailAddress": {"address": email}, "type": "required"}
for email in params.get("attendees", [])
]
resp = requests.post(url, headers=headers, json=body, timeout=15)
if resp.status_code not in [200, 201]:
self.log_err(f"Graph create error: {resp.text}")
return None
return {"success": True}
# ==========================================================
# UPDATE EVENT
# ==========================================================
if tool_slug == "OUTLOOKCALENDAR_UPDATE_EVENT":
event_id = params.get("eventId")
url = f"{GRAPH_BASE_URL}/me/events/{event_id}"
start_dt = datetime.datetime.fromisoformat(
params["start_datetime"].replace("Z", "+00:00")
)
duration_minutes = params.get(
"event_duration_hour", 0
) * 60 + params.get("event_duration_minutes", 0)
end_dt = start_dt + datetime.timedelta(minutes=duration_minutes)
body = {
"subject": params.get("summary"),
"start": {
"dateTime": start_dt.isoformat(),
"timeZone": params.get("timezone", "UTC"),
},
"end": {
"dateTime": end_dt.isoformat(),
"timeZone": params.get("timezone", "UTC"),
},
}
if params.get("location"):
body["location"] = {"displayName": params.get("location")}
if params.get("description"):
body["body"] = {
"contentType": "text",
"content": params.get("description"),
}
if params.get("attendees"):
body["attendees"] = [
{"emailAddress": {"address": email}, "type": "required"}
for email in params.get("attendees", [])
]
resp = requests.patch(url, headers=headers, json=body, timeout=15)
if resp.status_code not in [200, 202]:
self.log_err(f"Graph update error: {resp.text}")
return None
return {"success": True}
# ==========================================================
# DELETE EVENT
# ==========================================================
if tool_slug == "OUTLOOKCALENDAR_DELETE_EVENT":
event_id = params.get("eventId")
url = f"{GRAPH_BASE_URL}/me/events/{event_id}"
resp = requests.delete(url, headers=headers, timeout=15)
if resp.status_code != 204:
self.log_err(f"Graph delete error: {resp.text}")
return None
return {"success": True}
self.log_err(f"Unknown tool slug: {tool_slug}")
return None
except Exception as e:
self.log_err(f"Graph exception: {e}")
return None
# =========================================================================
# USER PROFILE (from Outlook Super)
# =========================================================================
def fetch_user_profile(self):
"""Get user's email and extract name from Outlook Super."""
data = self.execute_tool("OUTLOOKSUPER_GET_PROFILE", {})
if data:
pdata = data.get("response_data") or data
self.log(f"Profile data: {json.dumps(pdata)[:300]}")
email = pdata.get("emailAddress") or pdata.get("email") or ""
if email:
self.user_email = email
local_part = email.split("@")[0]
name_part = local_part.split(".")[0].split("_")[0]
self.user_name = name_part.capitalize()
self.log(f"Extracted name '{self.user_name}' from email '{email}'")
return
self.log("Could not fetch user profile from Outlook Super")
# =========================================================================
# TRIGGER CONTEXT (reads Main Flow history)
# =========================================================================
def get_trigger_context(self):
"""Extract recent conversation context that triggered this ability."""
recent_user_messages = []
# Primary source: agent_memory.full_message_history
try:
history = self.worker.agent_memory.full_message_history
if not history:
self.log("full_message_history is empty or None")
else:
self.log(f"Message history length: {len(history)}")
# Debug: log the last 5 messages
for i, msg in enumerate(history[-5:]):
try:
msg_type = type(msg).__name__
if hasattr(msg, "content"):
content_preview = str(msg.content)[:50]
else:
content_preview = str(msg)[:50]
role = (
str(msg.role).lower() if hasattr(msg, "role") else "unknown"
)
self.log(
f"History[{i}]: type={msg_type}, role={role}, content={content_preview}"
)
except Exception as e:
self.log(f"History[{i}]: error - {e}")
# Extract the most recent USER messages (skip assistant messages)
for msg in reversed(history):
try:
if hasattr(msg, "content"):
content = str(msg.content).strip()
else:
content = str(msg).strip()
# Skip empty or system content
if (
not content
or "[HUB_SESSION_END|" in content
or "[SYSTEM CONTEXT]" in content
):
continue
# Check if this is a user message
if hasattr(msg, "role"):
role = str(msg.role).lower()
is_user = "user" in role
else:
is_user = True
if is_user and content not in recent_user_messages:
recent_user_messages.append(content)
if len(recent_user_messages) >= 5:
break
except Exception as e:
self.log_err(f"Error parsing message: {e}")
continue
except Exception as e:
self.log_err(f"Error reading message history: {e}")
# The FIRST item in recent_user_messages is the most recent (we iterated in reverse)
trigger_message = recent_user_messages[0] if recent_user_messages else ""
self.log(
f"Trigger context: {len(recent_user_messages)} messages, trigger: '{trigger_message[:80] if trigger_message else 'none'}'"
)
return {
"messages": list(reversed(recent_user_messages)), # Chronological order
"trigger": trigger_message,
}
def classify_trigger_intent(self, trigger_context: dict):
"""Use LLM to classify the trigger intent and determine mode."""
trigger = trigger_context.get("trigger", "")
if not trigger:
# No trigger found - will ask user what they need
self.log("No trigger message found, will ask user")
return {
"intent": "ask_user",
"mode": "quick",
"details": {},
"no_trigger": True,
}
# Check for explicit full briefing triggers
full_triggers = [
"catch me up",
"smart hub",
"what's going on",
"brief me",
"run through my day",
"overview",
]
if any(ft in trigger.lower() for ft in full_triggers):
self.log("Full briefing trigger detected")
return {"intent": "full_briefing", "mode": "full", "details": {}}
prompt = TRIGGER_INTENT_PROMPT.format(trigger=trigger)
try:
response = self.capability_worker.text_to_text_response(prompt)
clean = response.replace("```json", "").replace("```", "").strip()
result = json.loads(clean)
self.log(
f"Trigger classification: intent={result.get('intent')}, mode={result.get('mode')}, details={result.get('details')}"
)
return result
except Exception as e:
self.log_err(f"Trigger classification error: {e}")
# Simple keyword fallback
lower = trigger.lower()
if any(
w in lower
for w in ["what's on", "schedule", "calendar today", "my day"]
):
return {"intent": "read_today", "mode": "quick", "details": {}}
elif any(
w in lower
for w in ["create", "schedule a", "set up", "new meeting", "new event"]
):
return {"intent": "create", "mode": "quick", "details": {}}
# Default to asking user
return {"intent": "ask_user", "mode": "quick", "details": {}}
# =========================================================================
# SESSION SIGNATURE (Cross-Session Timestamp Tracking)
# =========================================================================
def find_last_session_signature(self):
"""Scan message history for the most recent HUB_SESSION_END marker."""
try:
history = self.worker.agent_memory.full_message_history
if not history:
self.log("No message history found")
return None
for msg in reversed(history):
try:
content = msg.content
except AttributeError:
content = str(msg)
if "[HUB_SESSION_END|" in content:
start = content.find("[HUB_SESSION_END|") + len("[HUB_SESSION_END|")
end = content.find("|", start)
if end > start:
timestamp = content[start:end]
self.log(f"Found last session: {timestamp}")
return timestamp
self.log("No previous session signature found")
return None
except Exception as e:
self.log_err(f"Error reading session signature: {e}")
return None
def stamp_session_signature(self):
"""Generate a signature to embed in the exit message."""
now = datetime.datetime.utcnow().isoformat()
cal_count = len(self.context.get("calendar", []))
signature = f"[HUB_SESSION_END|{now}|cal:{cal_count}]"
return signature
# =========================================================================
# GEO + WEATHER
# =========================================================================
def fetch_ip_geo(self):
"""Fetch geolocation from IP."""
try:
user_ip = self.worker.user_socket.client.host
self.log(f"User IP: {user_ip}")
resp = requests.get(f"http://ip-api.com/json/{user_ip}", timeout=5)
data = resp.json()
self.log(f"Geo response: {json.dumps(data)[:200]}")
return data
except Exception as e:
self.log_err(f"IP geo failed: {e}")
return {}
def is_cloud_ip(self, geo_data):
"""Check if IP belongs to a cloud provider."""
isp = geo_data.get("isp", "").lower()
org = geo_data.get("org", "").lower()
combined = isp + " " + org
for indicator in CLOUD_INDICATORS:
if indicator in combined:
return True
return False
def fetch_weather(self, lat, lon, use_fahrenheit=True):
"""Fetch current weather from Open-Meteo."""
try:
temp_unit = "fahrenheit" if use_fahrenheit else "celsius"
speed_unit = "mph" if use_fahrenheit else "kmh"
url = (
f"https://api.open-meteo.com/v1/forecast"
f"?latitude={lat}&longitude={lon}"
f"¤t=temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m"
f"&temperature_unit={temp_unit}"
f"&wind_speed_unit={speed_unit}"
)
resp = requests.get(url, timeout=5)
data = resp.json()
current = data.get("current", {})
weather_code = current.get("weather_code", 0)
return {
"temp": current.get("temperature_2m"),
"humidity": current.get("relative_humidity_2m"),
"condition": WEATHER_DESCRIPTIONS.get(
weather_code, "unclear conditions"
),
"wind": current.get("wind_speed_10m"),
}
except Exception as e:
self.log_err(f"Weather failed: {e}")
return {}
def collect_geo_context(self):
"""Collect IP geo and weather data."""
geo = self.fetch_ip_geo()
if geo and geo.get("status") == "success" and not self.is_cloud_ip(geo):
city = geo.get("city", "")
region = geo.get("regionName", "")
country = geo.get("countryCode", "US")
lat = geo.get("lat", 0)
lon = geo.get("lon", 0)
timezone = geo.get("timezone", "America/New_York")
else:
# Fallback defaults — replace with your own location if desired
city = "New York"
region = "New York"
country = "US"
lat = 40.71
lon = -74.01
timezone = "America/New_York"
is_imperial = country in IMPERIAL_COUNTRIES
weather = self.fetch_weather(lat, lon, use_fahrenheit=is_imperial)
try:
from zoneinfo import ZoneInfo
tz = ZoneInfo(timezone)
now = datetime.datetime.now(tz)
except Exception:
now = datetime.datetime.now()
hour = now.hour
time_bucket = get_time_bucket(hour)
self.geo_context = {
"city": city,
"region": region,
"country": country,
"timezone": timezone,
"lat": lat,
"lon": lon,
"weather_temp": weather.get("temp", "unknown"),
"weather_condition": weather.get("condition", "unknown"),
"weather_humidity": weather.get("humidity", "unknown"),
"weather_wind": weather.get("wind", "unknown"),
"time_bucket": time_bucket,
"current_time": now.strftime("%I:%M %p").lstrip("0"),
"current_date": now.strftime("%B %d, %Y"),
"day_of_week": now.strftime("%A"),
"hour": hour,
"is_imperial": is_imperial,
}
self.log(
f"Geo context: {city}, {region} | {time_bucket} | {weather.get('temp')}°"
)
def has_in_person_meeting(self):
"""Check if any calendar event has a physical location (address)."""
for event in self.context.get("calendar", []):
location = event.get("location", "")
if location and not any(
x in location.lower()
for x in ["http", "zoom", "meet.google", "teams.microsoft"]
):
return True
return False
def build_weather_remark(self):
"""Build a natural spoken weather remark - only if there's an in-person meeting."""
if not self.has_in_person_meeting():
return ""
condition = self.geo_context.get("weather_condition", "")
temp = self.geo_context.get("weather_temp", "")
city = self.geo_context.get("city", "there")
if not temp or temp == "unknown":
return ""
try:
temp_rounded = int(round(float(temp)))
except (TypeError, ValueError):
return ""
if "rain" in condition or "drizzle" in condition:
return f"A bit wet out in {city} right now."
elif "snow" in condition:
return f"Snowy in {city} right now."
elif "thunder" in condition:
return f"Sounds like some thunder out in {city}."
elif temp_rounded < 40:
return f"Pretty cold out there at {temp_rounded} degrees."
elif temp_rounded > 85:
return f"Hot one today, about {temp_rounded} degrees."
elif "clear" in condition:
return f"Nice and clear out in {city}."
return ""
# =========================================================================
# CALENDAR MODULE
# =========================================================================
def fetch_upcoming_today(self):
"""Fetch calendar events from now through rest of today (in user's local timezone)."""
now_utc = datetime.datetime.now(datetime.timezone.utc)
# To properly get "rest of today", we need to account for user's timezone
# Most US timezones are UTC-5 to UTC-10, so looking ahead 12 hours
# from any UTC time should capture until midnight local time
hours_ahead = 12
# If we have timezone info, calculate more precisely
user_tz = self.geo_context.get("timezone", "")
if user_tz:
# Rough timezone offset mapping for common US timezones
tz_offsets = {
"America/New_York": -5,
"America/Chicago": -6,
"America/Denver": -7,
"America/Los_Angeles": -8,
"America/Phoenix": -7,
"America/Anchorage": -9,
"Pacific/Honolulu": -10,
"America/Detroit": -5,
"America/Indiana/Indianapolis": -5,
"America/Boise": -7,
}
offset = tz_offsets.get(user_tz, -5) # Default to Eastern
# Calculate hours until midnight local time
# Local time = UTC + offset
local_hour = (now_utc.hour + offset) % 24
hours_until_midnight = 24 - local_hour
hours_ahead = min(
hours_until_midnight + 1, 14
) # Cap at 14 hours, add 1 for buffer
end_time = now_utc + datetime.timedelta(hours=hours_ahead)
time_min = now_utc.strftime("%Y-%m-%dT%H:%M:%SZ")
time_max = end_time.strftime("%Y-%m-%dT%H:%M:%SZ")
self.log(f"Calendar fetch: {time_min} to {time_max} ({hours_ahead}h window)")
params = {
"calendarId": "primary",
"timeMin": time_min,
"timeMax": time_max,
"singleEvents": True,
"maxResults": 15,
"orderBy": "startTime",
}
raw = self.execute_tool("OUTLOOKCALENDAR_FIND_EVENT", params)
if not raw:
self.log("No calendar data retrieved")
return []