-
Notifications
You must be signed in to change notification settings - Fork 287
Expand file tree
/
Copy pathmain.py
More file actions
2227 lines (2000 loc) · 88 KB
/
main.py
File metadata and controls
2227 lines (2000 loc) · 88 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 json
import re
from datetime import datetime, timedelta
from typing import List, Dict, Optional
import requests
from src.agent.capability import MatchingCapability
from src.agent.capability_worker import CapabilityWorker
from src.main import AgentWorker
# =============================================================================
# CONFIG (in production use environment variables or secrets)
# =============================================================================
GRAPH_BASE_URL = "https://graph.microsoft.com/v1.0"
CLIENT_ID = "YOUR_CLIENT_ID"
TENANT_ID = "consumers"
REFRESH_TOKEN = "YOUR_REFRESH_TOKEN"
EXIT_WORDS = [
"done",
"exit",
"stop",
"quit",
"bye",
"goodbye",
"nothing else",
"all good",
"nope",
"no thanks",
"i'm good",
"im good",
"that's it",
"thats it",
"that's all",
"thats all",
"go to sleep",
]
CONFIRM_YES_PHRASES = [
"yes",
"yeah",
"yep",
"sure",
"okay",
"ok",
"correct",
"right",
"do it",
"go ahead",
"sounds good",
"that's right",
"thats right",
"please",
"read it",
"send it",
"read the full",
"hear it",
]
CONFIRM_NO_PHRASES = [
"no",
"nope",
"never mind",
"nevermind",
"cancel",
"forget it",
"don't",
"dont",
"skip",
"not now",
"pass",
"next",
]
MAX_UNREAD_FETCH = 15
MAX_SUMMARY_INPUT = 15
MAX_SEARCH_RESULTS = 5
MAX_TRIAGE_BATCH = 10
PREFS_FILE = "outlook_connector_prefs.json"
CACHE_FILE = "outlook_connector_cache.json"
# Static message for all API/connection errors
OUTLOOK_ERROR_SPEAK = (
"I'm having trouble connecting to Outlook right now. Try again in a minute."
)
# =============================================================================
# WEATHER & GEO (ip-api.com + Open-Meteo)
# =============================================================================
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"]
# =============================================================================
# LLM PROMPTS
# =============================================================================
TRIGGER_INTENT_PROMPT = (
"You are the Outlook Connector, a voice-only assistant that manages the "
"user's Outlook / Microsoft 365 email.\n"
"You are classifying the user's email-related request.\n\n"
"Given the user's recent messages, return ONLY a JSON object:\n"
"{{\n"
' "intent": one of ["summary", "read_specific", "reply", "compose", '
'"search", "triage", "mark_read", "archive", "unknown"],\n'
' "mode": "quick" or "full",\n'
' "details": {{\n'
' "sender_name": null,\n'
' "subject_keywords": null,\n'
' "recipient": null,\n'
' "body_content": null,\n'
' "date_range": null,\n'
' "email_address": null,\n'
' "count_only": false\n'
" }}\n"
"}}\n\n"
"Rules:\n"
'- "summary" = user wants overview of inbox. Mode: quick if asking a count, '
'full if asking to "go through" or "catch me up". When the user asks ONLY '
'for the number of unread emails (e.g. "how many unread", "do I have any '
'new email"), set details.count_only to true and mode to quick.\n'
'- "read_specific" = user wants to hear a specific email. Mode: quick. '
'IMPORTANT: Questions like "did [Name] message me", "did [Name] email me", '
'"did Cursor message me", "any email from [Name]" are read_specific — set '
'sender_name to the name or company (e.g. "Cursor", "Cursor Team", "Sarah") '
"so we can match from the inbox list by display name.\n"
'- "reply" = user wants to reply to an email. Mode: quick\n'
'- "compose" = user wants to write a new email. Mode: quick\n'
'- "search" = user wants to find an email (e.g. by keyword or date). Use '
'for "find emails about X" or "emails from last week". For "did [Name] '
'message me" use read_specific instead. Mode: quick\n'
'- "triage" = user wants to go through emails one by one. Mode: full\n'
'- "mark_read" / "archive" = user wants to manage a specific email. '
"Mode: quick\n"
'- If the request is vague like just "email" or "check email", default to '
"summary with mode: full\n\n"
"Examples:\n"
'"What did Sarah say?" -> {{"intent": "read_specific", "details": '
'{{"sender_name": "Sarah"}}}}\n'
'"Reply to that one" -> {{"intent": "reply", "details": {{}}}}\n'
'"Send an email to Mike" -> {{"intent": "compose", "details": '
'{{"recipient": "Mike"}}}}\n'
'"Email Mike about the API spec and tell him I\'ll have it Friday" -> '
'{{"intent": "compose", "details": {{"recipient": "Mike", '
'"subject_keywords": "API spec", "body_content": "tell him I\'ll have it '
'Friday"}}}}\n'
'"Find the email about the budget" -> {{"intent": "search", "details": '
'{{"subject_keywords": "budget"}}}}\n'
'"Mark it as read" -> {{"intent": "mark_read", "details": {{}}}}\n'
'"Archive that" -> {{"intent": "archive", "details": {{}}}}\n'
'"Go through my inbox" -> {{"intent": "triage", "details": {{}}}}\n\n'
"User's recent messages:\n"
"{trigger_context}\n"
)
COMPOSE_EXTRACT_PROMPT = (
"You are the Outlook Connector. The user wants to send an email. Extract "
"whatever info is available from their message. Return ONLY valid JSON, "
"no markdown:\n"
"{{\n"
' "recipient": "name or email or null",\n'
' "subject": "subject line or null",\n'
' "body": "message content or null"\n'
"}}\n"
"If the user gave everything in one sentence, extract all three fields. "
"If only partial info, fill what you can and leave the rest as null.\n\n"
"User said or context:\n"
"{user_input}\n"
)
SEARCH_EXTRACT_PROMPT = (
"You are the Outlook Connector. Extract search parameters from the user's "
"email search request. Return ONLY valid JSON, no markdown:\n"
"{{\n"
' "sender": "sender name or email address or null",\n'
' "keywords": "search keywords for subject or body or null",\n'
' "date_range": "today|yesterday|this week|last week|last month|null"\n'
"}}\n"
"Use date_range only if the user mentioned a time range. Examples: "
'"this week" -> "this week", "last month" -> "last month", '
'"yesterday" -> "yesterday", "today" -> "today".\n\n'
"User said:\n"
"{user_input}\n"
)
TRIAGE_SUMMARY_PROMPT = (
"You are the Outlook Connector. Give a 1-sentence spoken summary of this "
"email for triage. Lead with who and what; mention the main point if clear "
"from the preview. Keep it short and natural for voice.\n\n"
"From: {from_name}\n"
"Subject: {subject}\n"
"Preview: {preview}\n"
)
SUMMARY_PROMPT = (
"You are the Outlook Connector, a voice-only assistant that manages the "
"user's Outlook / Microsoft 365 email.\n\n"
"Summarize these emails in 2-3 spoken sentences. Lead with the most "
"important or urgent ones. Keep it short.\n"
"Do NOT read every email. Summarize. The user can ask for details on "
"specific ones.\n"
"Do NOT end with a question or offer — just the summary.\n\n"
"Example voice output:\n"
'"You have 7 unread emails. Two look important — Sarah sent the Q3 deck '
"and flagged two issues, and Mike is asking about the API spec. The rest "
'are newsletters and notifications."\n\n'
"Emails:\n"
"{emails}\n"
)
EMAIL_SUMMARY_PROMPT = (
"You are the Outlook Connector, a voice-only assistant that manages the "
"user's Outlook / Microsoft 365 email.\n"
"Summarize this email body in 1-2 spoken sentences. Only the actual "
"message content — ignore signatures, reply chains, and disclaimers.\n"
"Format for voice — say 'at' for @, 'dot' for periods in emails, and "
"natural dates like 'Tuesday at 3 PM'. Say 'there's a link' instead of "
"reading URLs.\n\n"
"From: {sender}\n"
"Subject: {subject}\n"
"Body:\n"
"{body}\n"
)
DRAFT_REPLY_PROMPT = (
"You are the Outlook Connector, a voice-only assistant that manages the "
"user's Outlook / Microsoft 365 email.\n"
"Rewrite this into a complete, sendable email reply. The user is replying "
"to: {replying_to}.\n\n"
"User said:\n"
'"{user_input}"\n\n'
"Rules:\n"
"- Write the FULL reply body. Use the recipient's name in the greeting "
'(e.g. "Hi Sarah,") since you know who they are.\n'
'- Use a simple sign-off like "Thanks," or "Best," only — never use '
"placeholders like [Your Name], [My Name], [Recipient's Name], [Name], "
"or [Anything in brackets].\n"
"- Keep it concise and natural. Output only the email body text, ready "
"to send.\n"
)
DRAFT_COMPOSE_PROMPT = (
"You are the Outlook Connector, a voice-only assistant that composes and "
"manages the user's Outlook / Microsoft 365 email.\n"
"Turn this spoken request into a clean email that sounds natural when "
"read aloud.\n\n"
"If the user says something casual like:\n"
'- "tell him yeah I\'ll get it done by Friday no worries"\n\n'
"You should turn it into something like:\n"
"- \"Hi Mike, I'll have the API spec ready by Friday. Let me know if you "
'need anything before then."\n\n'
"Turn this spoken request into a complete, sendable email body. Use the "
"actual recipient and subject below.\n\n"
"Recipient: {recipient}\n"
"Subject: {subject}\n\n"
"User said:\n"
'"{body}"\n\n'
"Rules:\n"
"- Write the FULL email body. Use the recipient's name in the greeting "
'(e.g. "Hi Mike,").\n'
'- Use a simple sign-off like "Thanks," or "Best," only — never use '
"placeholders like [Your Name], [My Name], [Recipient's Name], [Name], "
"or [Anything in brackets].\n"
"- Output only the email body text, ready to send. No placeholders.\n"
)
# =============================================================================
# MAIN CLASS
# =============================================================================
class OutlookConnectorCapability(MatchingCapability):
worker: AgentWorker = None
capability_worker: CapabilityWorker = None
# Session state
emails: List[Dict] = []
current_email: Optional[Dict] = None
history: List = []
pending_reply: Optional[Dict] = None
pending_compose: Optional[Dict] = None
archive_folder_id: Optional[str] = None
mode: str = "quick"
idle_count: int = 0
prefs: Dict = {}
in_triage: bool = False
triage_index: int = 0
geo_context: Dict = {}
_just_gave_summary: bool = False # "yes" after summary → start triage
_triage_just_sent_reply: bool = (
False # after "Sent." in triage, advance to next email
)
_just_finished_read: bool = (
False # after "Want to reply, archive, or read?" → same reply/archive/read handlers
)
# =========================================================================
# REGISTRATION
# =========================================================================
# {{register capability}}
# =========================================================================
# ENTRY POINT
# =========================================================================
def call(self, worker: AgentWorker):
self.worker = worker
self.capability_worker = CapabilityWorker(self.worker)
self.reset_session_state()
self.worker.session_tasks.create(self.run())
def reset_session_state(self):
self.emails = []
self.current_email = None
self.history = []
self.pending_reply = None
self.pending_compose = None
self.archive_folder_id = None
self.mode = "quick"
self.idle_count = 0
self.in_triage = False
self.triage_index = 0
self._just_gave_summary = False
self._triage_just_sent_reply = False
self._just_finished_read = False
def log(self, msg):
self.worker.editor_logging_handler.info(f"[Outlook] {msg}")
def log_err(self, msg):
self.worker.editor_logging_handler.error(f"[Outlook] {msg}")
# =========================================================================
# MAIN RUN
# =========================================================================
async def run(self):
try:
await self.capability_worker.speak("One sec, checking your inbox.")
initial_history_len = 0
try:
history = self.worker.agent_memory.full_message_history
initial_history_len = len(history) if history else 0
except Exception:
pass
self.prefs = await self.load_preferences()
self.collect_geo_context()
try:
self.emails, err = self.outlook_list_unread(MAX_UNREAD_FETCH)
if err:
self.log_err(f"Outlook fetch failed: {err}")
await self.capability_worker.speak(OUTLOOK_ERROR_SPEAK)
self.capability_worker.resume_normal_flow()
return
except Exception as e:
self.log_err(f"Outlook fetch failed: {e}")
await self.capability_worker.speak(OUTLOOK_ERROR_SPEAK)
self.capability_worker.resume_normal_flow()
return
await self.save_json(CACHE_FILE, {"emails": self.emails}, temp=True)
trigger_context = None
for _ in range(6):
await self.worker.session_tasks.sleep(0.5)
try:
current = self.worker.agent_memory.full_message_history
current_len = len(current) if current else 0
if current_len > initial_history_len:
trigger_context = self.get_trigger_context()
break
except Exception:
pass
if trigger_context is None:
trigger_context = self.get_trigger_context()
intent_data = self.classify_trigger_intent(trigger_context)
self.mode = intent_data.get("mode", "quick")
if self.mode == "quick":
await self.handle_quick_intent(intent_data)
if self._just_finished_read:
await self._quick_after_read_then_exit()
else:
await self.capability_worker.speak(
"Let me know if you need anything else about your email."
)
await self.brief_follow_up_window()
return
if self.mode == "full":
await self.handle_full_mode(intent_data)
await self.session_loop()
return
except Exception as e:
self.log_err(str(e))
await self.capability_worker.speak(OUTLOOK_ERROR_SPEAK)
self.capability_worker.resume_normal_flow()
finally:
self.capability_worker.resume_normal_flow()
def fetch_emails(self):
"""Get unread emails from Microsoft Graph API.
Sets self.emails; returns (True, None) or (False, error_message)."""
self.emails, err = self.outlook_list_unread(MAX_UNREAD_FETCH)
return (err is None, err)
# =========================================================================
# TRIGGER CONTEXT
# =========================================================================
def get_trigger_context(self):
recent: List[str] = []
trigger = ""
try:
history = self.worker.agent_memory.full_message_history
for msg in reversed(history):
if hasattr(msg, "role") and "user" in str(msg.role).lower():
content = str(msg.content).strip()
if not content:
continue
recent.append(content)
if not trigger:
trigger = content
if len(recent) >= 5:
break
except Exception:
pass
recent_text = "\n".join(reversed(recent)) if recent else trigger
return {"trigger": trigger, "trigger_context": recent_text}
def classify_trigger_intent(self, trigger_context: dict) -> Dict:
"""Classify trigger intent and mode from context."""
raw_trigger = trigger_context.get("trigger", "")
raw_recent = trigger_context.get("trigger_context", raw_trigger)
trigger = (
" ".join(str(x) for x in raw_trigger)
if isinstance(raw_trigger, list)
else str(raw_trigger or "")
)
recent_text = (
" ".join(str(x) for x in raw_recent)
if isinstance(raw_recent, list)
else str(raw_recent or "")
)
if not trigger.strip():
return {"intent": "summary", "mode": "full", "details": {}}
# Vague triggers ("email", "inbox", etc.) → summary, full mode
lower_stripped = trigger.strip().lower().rstrip(".!?")
if lower_stripped in ("outlook", "email", "emails", "inbox"):
return {"intent": "summary", "mode": "full", "details": {}}
full_triggers = [
"check my email",
"triage",
"go through my email",
"go through my emails",
"go through my inbox",
"catch me up on email",
"read me my emails",
]
if any(ft in trigger.lower() for ft in full_triggers):
lower = trigger.lower()
# Triage = walk through one by one (brief: "let's go through my inbox", "triage my email")
is_triage = "triage" in lower or "go through" in lower
return {
"intent": "triage" if is_triage else "summary",
"mode": "full",
"details": {},
}
prompt = TRIGGER_INTENT_PROMPT.format(trigger_context=recent_text)
default = {"intent": "summary", "mode": "quick", "details": {}}
try:
response = self.capability_worker.text_to_text_response(prompt)
clean = (response or "").replace("```json", "").replace("```", "").strip()
start, end = clean.find("{"), clean.rfind("}")
if start != -1 and end > start:
clean = clean[start: end + 1]
result = json.loads(clean)
if isinstance(result, dict):
return result
except Exception as e:
self.log_err(f"Trigger classification error: {e}")
lower = (trigger or "").lower()
if "how many" in lower and (
"unread" in lower or "email" in lower or "mail" in lower
):
return {
"intent": "summary",
"mode": "quick",
"details": {"count_only": True},
}
if "do i have" in lower and ("email" in lower or "mail" in lower):
return {
"intent": "summary",
"mode": "quick",
"details": {"count_only": True},
}
if "any new" in lower and ("email" in lower or "mail" in lower):
return {
"intent": "summary",
"mode": "quick",
"details": {"count_only": True},
}
if any(w in lower for w in ["send", "write", "compose", "email to"]):
return {"intent": "compose", "mode": "quick", "details": {}}
if any(w in lower for w in ["reply", "respond"]):
return {"intent": "reply", "mode": "quick", "details": {}}
if any(w in lower for w in ["archive"]):
return {"intent": "archive", "mode": "quick", "details": {}}
if any(w in lower for w in ["search", "find"]):
return {"intent": "search", "mode": "quick", "details": {}}
return default
# =========================================================================
# QUICK MODE
# =========================================================================
async def handle_quick_intent(self, intent_data: Dict):
intent = intent_data.get("intent", "summary")
await self.route_intent(intent, intent_data.get("details", {}))
async def _quick_after_read_then_exit(self):
"""After read in quick mode: handle one reply/archive/read (same handlers), then say Done and exit."""
while True:
user = await self.user_response_with_timeout(15)
if not user:
await self.capability_worker.speak("Done.")
return
if any(word in user.lower() for word in EXIT_WORDS):
await self.capability_worker.speak("Done.")
return
if self.pending_reply:
await self.handle_pending_reply(user)
if not self.pending_reply:
await self.capability_worker.speak("Done.")
return
continue
if self._just_finished_read:
self._just_finished_read = False
lowered = user.lower()
if "reply" in lowered:
reply_body = self._extract_reply_body_from_triage_action(user)
if reply_body:
self.pending_reply = {
"email_id": self.current_email["id"],
"waiting_for": "body",
"draft": None,
}
await self.handle_pending_reply(reply_body)
else:
await self.start_reply({})
if not self.pending_reply:
await self.capability_worker.speak("Done.")
return
continue
if "archive" in lowered:
await self.handle_archive()
await self.capability_worker.speak("Done.")
return
if "read" in lowered:
await self._read_full_current_email()
await self.capability_worker.speak("Done.")
return
# unexpected: treat as done and exit
await self.capability_worker.speak("Done.")
return
await self.capability_worker.speak("Done.")
return
async def brief_follow_up_window(self):
user = await self.user_response_with_timeout(5)
if user:
intent_data = self.classify_trigger_intent(
{"trigger": user, "trigger_context": user}
)
await self.route_intent(
intent_data["intent"], intent_data.get("details", {})
)
self.capability_worker.resume_normal_flow()
# =========================================================================
# FULL MODE
# =========================================================================
async def handle_full_mode(self, intent_data: Dict):
intent = intent_data.get("intent", "summary")
await self.route_intent(intent, intent_data.get("details", {}))
async def session_loop(self):
while True:
user = await self.user_response_with_timeout(15)
if not user:
self.idle_count += 1
if self.idle_count >= 2:
await self.capability_worker.speak("Alright, closing your inbox.")
self.capability_worker.resume_normal_flow()
return
continue
self.idle_count = 0
if any(word in user.lower() for word in EXIT_WORDS):
await self.capability_worker.speak("Done.")
self.capability_worker.resume_normal_flow()
return
# After "Want me to go through them?" — only start triage on clear yes; no/cancel or trigger-like = don't
if self._just_gave_summary:
if self._is_confirm_no_or_cancel(user):
self._just_gave_summary = False
await self.capability_worker.speak("Okay.")
continue
if self._looks_like_trigger(user):
self._just_gave_summary = False
elif self._is_confirm_yes(user):
self._just_gave_summary = False
await self.handle_triage()
continue
if self.pending_reply:
await self.handle_pending_reply(user)
if self.in_triage and not self.pending_reply:
if self._triage_just_sent_reply:
self._triage_just_sent_reply = False
self.triage_index += 1
await self.handle_triage()
continue
if self.pending_compose:
await self.handle_pending_compose(user)
continue
# After read: same reply/archive/read flow as triage (one path: extract body when present, same handlers)
if self._just_finished_read:
self._just_finished_read = False
lowered = user.lower()
if "reply" in lowered:
reply_body = self._extract_reply_body_from_triage_action(user)
if reply_body:
self.pending_reply = {
"email_id": self.current_email["id"],
"waiting_for": "body",
"draft": None,
}
await self.handle_pending_reply(reply_body)
else:
await self.start_reply({})
continue
if "archive" in lowered:
await self.handle_archive()
continue
if "read" in lowered:
await self._read_full_current_email()
continue
# anything else: fall through to classify (e.g. "read the one from Sarah")
intent_data = self.classify_user_intent(
{"trigger": user, "trigger_context": user}
)
await self.route_intent(
intent_data["intent"], intent_data.get("details", {})
)
classify_user_intent = classify_trigger_intent # alias for session_loop
async def user_response_with_timeout(self, timeout):
try:
return await asyncio.wait_for(
self.capability_worker.user_response(), timeout=timeout
)
except Exception:
return None
# =========================================================================
# ROUTER
# =========================================================================
async def route_intent(self, intent: str, details: Dict):
if intent == "summary":
if details.get("count_only"):
await self.handle_count()
else:
await self.handle_summary()
elif intent == "read_specific":
await self.handle_read(details)
elif intent == "reply":
await self.start_reply(details)
elif intent == "compose":
await self.start_compose(details)
elif intent == "search":
await self.handle_search(details)
elif intent == "mark_read":
await self.handle_mark_read()
elif intent == "archive":
await self.handle_archive()
elif intent == "triage":
await self.handle_triage()
else:
await self.handle_summary()
# =========================================================================
# COUNT (quick: just the number, no full summary)
# =========================================================================
async def handle_count(self):
n = len(self.emails)
if n == 0:
await self.capability_worker.speak(
"Your inbox is clear — no unread emails."
)
elif n == 1:
await self.capability_worker.speak("You have 1 unread email.")
else:
await self.capability_worker.speak(f"You have {n} unread emails.")
# =========================================================================
# SUMMARY
# =========================================================================
async def handle_summary(self):
if not self.emails:
weather_line = self.build_weather_line()
msg = (weather_line + "Your inbox is clear — no unread emails.").strip()
await self.capability_worker.speak(msg)
return
# Summarize all fetched emails so spoken count matches count-only path (len(self.emails))
max_summary = min(len(self.emails), MAX_UNREAD_FETCH)
prompt = SUMMARY_PROMPT.format(emails=json.dumps(self.emails[:max_summary]))
summary = self.capability_worker.text_to_text_response(prompt)
weather_line = self.build_weather_line()
base = (summary or "").strip()
if weather_line:
base = weather_line + base
to_speak = (base + " Want me to go through them?").strip()
await self.capability_worker.speak(
to_speak or "You have unread emails. Want me to go through them?"
)
self._just_gave_summary = True # "yes" in session_loop starts triage
speak_summary = handle_summary # alias
# =========================================================================
# READ
# =========================================================================
async def handle_read(self, details: Dict):
if not self.emails:
await self.capability_worker.speak(
"Your inbox is clear — no unread emails."
)
return
email = self._select_email_for_details(details)
if (
details.get("sender_name") or details.get("subject_keywords")
) and email is None:
await self.capability_worker.speak(
"I don't see any recent emails from that person. Can you give me more details?"
)
return
if email is None:
email = self.emails[0]
self.current_email = email
await self.capability_worker.speak("One sec.")
try:
full_html, err = self.outlook_get_message(email["id"])
if err:
await self.capability_worker.speak(OUTLOOK_ERROR_SPEAK)
return
if not full_html:
await self.capability_worker.speak(
"I couldn't load that email from Outlook."
)
return
except Exception as e:
self.log_err(f"Get message failed: {e}")
await self.capability_worker.speak(OUTLOOK_ERROR_SPEAK)
return
body_text = self.strip_html(full_html)
sender_name = (
email.get("from", {}).get("emailAddress", {}).get("name") or "The sender"
)
subject = email.get("subject", "something without a subject")
spoken = self.capability_worker.text_to_text_response(
EMAIL_SUMMARY_PROMPT.format(
sender=sender_name, subject=subject, body=body_text[:2000]
)
)
await self.capability_worker.speak(
f"{sender_name} emailed about {subject}. {spoken}"
)
if len(body_text) > 600:
await self.capability_worker.speak(
"Want me to read the full email? Say yes to hear it, or no to continue."
)
follow_up = await self.user_response_with_timeout(10)
if self._is_confirm_yes(follow_up):
await self.capability_worker.speak(body_text[:3000])
await self.capability_worker.speak("Want to reply, archive, or read?")
self._just_finished_read = True
async def _read_full_current_email(self) -> bool:
"""Fetch full body for current_email, strip HTML, speak up to 3000 chars.
Returns True if spoken, False on error."""
if not self.current_email:
return False
try:
full_html, err = self.outlook_get_message(self.current_email["id"])
if err or not full_html:
await self.capability_worker.speak(
OUTLOOK_ERROR_SPEAK if err else "I couldn't load that email."
)
return False
body_text = self.strip_html(full_html)
await self.capability_worker.speak(body_text[:3000])
return True
except Exception as e:
self.log_err(f"Read full email failed: {e}")
await self.capability_worker.speak(OUTLOOK_ERROR_SPEAK)
return False
# =========================================================================
# REPLY (STATEFUL)
# =========================================================================
async def start_reply(self, details: Optional[Dict] = None):
details = details or {}
if (
not self.current_email
and self.emails
and (details.get("sender_name") or details.get("subject_keywords"))
):
email = self._select_email_for_details(details)
if email:
self.current_email = email
if not self.current_email:
self.pending_reply = {
"email_id": None,
"waiting_for": "which_email",
"draft": None,
}
await self.capability_worker.speak("Which email should I reply to?")
return
self.pending_reply = {
"email_id": self.current_email["id"],
"waiting_for": "body",
"draft": None,
}
await self.capability_worker.speak("What do you want to say?")
async def handle_pending_reply(self, user_input: str):
lowered = user_input.lower()
# Allow cancellation at any point (exit words or explicit cancel phrases)
if any(
phrase in lowered
for phrase in ["cancel", "never mind", "nevermind", "forget it"]
) or any(phrase in lowered for phrase in EXIT_WORDS):
self.pending_reply = None
await self.capability_worker.speak("Okay, not replying.")
return
if self.pending_reply["waiting_for"] == "which_email":
email = self._select_email_for_details(
{
"sender_name": user_input.strip(),
"subject_keywords": user_input.strip(),
}
)
if not email and self.emails:
q = user_input.strip().lower()
for e in self.emails:
from_name = (
e.get("from", {}).get("emailAddress", {}).get("name") or ""
).lower()
subj = (e.get("subject") or "").lower()
if q in from_name or q in subj:
email = e
break
if email:
self.current_email = email
self.pending_reply["email_id"] = email["id"]
self.pending_reply["waiting_for"] = "body"
await self.capability_worker.speak("What do you want to say?")
return
await self.capability_worker.speak(
"I couldn't find that email. Which email should I reply to?"
)
return
if self.pending_reply["waiting_for"] == "body":
# Don't draft when user said only "Reply" or something too short (would produce generic reply)
stripped = user_input.strip()
if (
not stripped
or len(stripped) < 4
or stripped.lower().rstrip(".,") in ("reply", "reply,")
):
await self.capability_worker.speak("What do you want to say?")
return
replying_to = "the sender"
if self.current_email:
from_obj = self.current_email.get("from") or {}
replying_to = (
from_obj.get("emailAddress", {}).get("name")
or from_obj.get("emailAddress", {}).get("address")
or replying_to
)
draft = self.capability_worker.text_to_text_response(
DRAFT_REPLY_PROMPT.format(
user_input=user_input,
replying_to=replying_to,
)
)
self.pending_reply["draft"] = draft
self.pending_reply["waiting_for"] = "confirm"
await self.capability_worker.speak(
f"Here's what I'll send: {draft}. Should I send it?"
)
return
if self.pending_reply["waiting_for"] == "confirm":
if self._is_confirm_yes(user_input):
await self.capability_worker.speak("Sending.")
try:
_, err = self.outlook_send_reply(
self.pending_reply["email_id"], self.pending_reply["draft"]
)
if err:
await self.capability_worker.speak(OUTLOOK_ERROR_SPEAK)
self.pending_reply = None
return
except Exception as e:
self.log_err(f"Send reply failed: {e}")
await self.capability_worker.speak(OUTLOOK_ERROR_SPEAK)
self.pending_reply = None
return
await self.capability_worker.speak("Sent.")
if self.in_triage:
self._triage_just_sent_reply = True
self.pending_reply = None
return
# "No, say X instead" or "could you say X" → re-draft with new content immediately
new_body = self._extract_revision_from_confirm(user_input)
if new_body:
replying_to = "the sender"
if self.current_email:
from_obj = self.current_email.get("from") or {}
replying_to = (