-
Notifications
You must be signed in to change notification settings - Fork 287
Expand file tree
/
Copy pathmain.py
More file actions
1857 lines (1520 loc) · 62.9 KB
/
main.py
File metadata and controls
1857 lines (1520 loc) · 62.9 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 json
import time
from datetime import datetime, timedelta
from typing import ClassVar, List, Optional
import requests
from src.agent.capability import MatchingCapability
from src.agent.capability_worker import CapabilityWorker
from src.main import AgentWorker
class SalesforceCRMCapability(MatchingCapability):
# {{register capability}}
worker: AgentWorker = None
capability_worker: CapabilityWorker = None
PREFS_FILENAME: ClassVar[str] = "salesforce_crm_prefs.json"
PERSIST: ClassVar[bool] = False
# OAuth Credentials - REPLACE THESE WITH YOUR VALUES
CONSUMER_KEY: ClassVar[str] = "xxxx"
CONSUMER_SECRET: ClassVar[str] = "xxxxx"
INSTANCE_URL: ClassVar[str] = "https://orgfarm-e79624af49-dev-ed.develop.my.salesforce.com"
INITIAL_ACCESS_TOKEN: ClassVar[str] = "xxx"
INITIAL_REFRESH_TOKEN: ClassVar[str] = "xxxx"
# OAuth endpoints
AUTH_URL: ClassVar[str] = "https://login.salesforce.com/services/oauth2/authorize"
TOKEN_URL: ClassVar[str] = "https://login.salesforce.com/services/oauth2/token"
# API version
API_VERSION: ClassVar[str] = "v62.0"
# Token expiry (2 hours in seconds)
TOKEN_EXPIRY_SECONDS: ClassVar[int] = 7200
# Cache refresh interval (30 minutes)
CACHE_REFRESH_MINUTES: ClassVar[int] = 30
def call(self, worker: AgentWorker):
self.worker = worker
self.capability_worker = CapabilityWorker(self.worker)
self.worker.session_tasks.create(self.run_main())
# --- MAIN ENTRY POINT ---
async def run_main(self):
try:
# Step 1: Say "Salesforce Ready"
await self.capability_worker.speak("Salesforce Ready.")
await self.worker.session_tasks.sleep(0.5)
# Step 2: Ensure authenticated
if not await self.ensure_authenticated():
await self.capability_worker.speak(
"I couldn't connect to Salesforce. "
"Please check your setup and try again."
)
return
# Cache opportunity stages
await self.cache_opportunity_stages()
# Step 3: Loop for multiple commands
while True:
# Wait for user command
command = await self.capability_worker.run_io_loop(
"What would you like to do?"
)
if not command:
await self.capability_worker.speak("No command received.")
continue
# Check for exit
if self.is_exit(command):
await self.capability_worker.speak("Goodbye.")
break
# Step 4: Detect mode and route
mode = await self.detect_mode(command)
if mode == "disambiguate":
await self.handle_disambiguation(command)
elif mode == "search_contact":
await self.search_contacts(command)
elif mode == "search_opportunity":
await self.search_opportunities(command)
elif mode == "log_note":
await self.log_note(command)
elif mode == "create_task":
await self.create_task(command)
elif mode == "pipeline_summary":
await self.pipeline_summary()
elif mode == "move_stage":
await self.move_opportunity_stage(command)
else:
await self.capability_worker.speak(
"I'm not sure what you want me to do. "
"Try 'look up a contact', 'check an opportunity', "
"'log a note', 'create a task', or 'show my pipeline'."
)
except Exception as e:
self.worker.editor_logging_handler.error(
f"Salesforce CRM error: {e}"
)
await self.capability_worker.speak("Something went wrong.")
finally:
self.capability_worker.resume_normal_flow()
def is_exit(self, text: str) -> bool:
"""Check if user wants to exit."""
exit_words = ["exit", "quit", "done", "goodbye", "bye", "stop"]
return any(word in text.lower() for word in exit_words)
# --- MODE DETECTION ---
async def detect_mode(self, command: str) -> str:
"""Detect which mode based on user command."""
cmd_lower = command.lower()
# Check for disambiguation first (follow-up to multiple results)
if self.is_disambiguation(cmd_lower):
return "disambiguate"
# Log Note - check FIRST (most specific)
if any(word in cmd_lower for word in [
"log note", "add note", "note on", "note for"
]):
return "log_note"
# Create Task
if any(word in cmd_lower for word in [
"create task", "create a task", "add task", "add a task",
"remind me", "task for", "new task", "follow up with"
]):
return "create_task"
# Pipeline Summary - check for various patterns
if any(word in cmd_lower for word in [
"pipeline", "my pipeline", "open opportunities", "open opps",
"what opportunities do i have", "show my opportunities",
"how many opportunities", "what deals do i have"
]):
return "pipeline_summary"
# Move Stage - check BEFORE search
if any(word in cmd_lower for word in [
"move", "update opp", "update opportunity", "change stage",
"mark as", "closed won", "closed lost"
]):
return "move_stage"
# Search Opportunity
if any(word in cmd_lower for word in [
"opportunity", "opp", "deal", "how's the", "how is the",
"what's the status", "check the"
]):
return "search_opportunity"
# Search Contact - broad match (check LAST)
if any(word in cmd_lower for word in [
"look up", "find contact", "who is", "search contact",
"find", "search"
]):
return "search_contact"
return "unknown"
def is_disambiguation(self, text: str) -> bool:
"""Check if user is selecting from multiple results."""
disambiguation_patterns = [
"first one", "the first", "first", "1", "number one", "number 1",
"second one", "the second", "second", "2", "number two", "number 2",
"third one", "the third", "third", "3", "number three", "number 3",
"fourth one", "the fourth", "fourth", "4", "number four", "number 4",
"fifth one", "the fifth", "fifth", "5", "number five", "number 5"
]
return any(pattern in text for pattern in disambiguation_patterns)
# --- MODE 1: SEARCH CONTACTS (FULLY IMPLEMENTED) ---
async def search_contacts(self, query: str):
"""Search for contacts by name or email using SOQL/SOSL."""
await self.capability_worker.speak("Searching for contacts...")
# Load preferences
prefs = await self.get_preferences()
if not prefs.get("access_token") or not prefs.get("instance_url"):
await self.capability_worker.speak(
"Salesforce not connected. Please set up OAuth first."
)
return
# Extract search term from query using LLM
search_term = await self.extract_search_term(query)
if not search_term:
await self.capability_worker.speak(
"I didn't catch who you're looking for. Try again?"
)
return
self.worker.editor_logging_handler.info(
f"Searching for contact: {search_term}"
)
# Determine search strategy
if "@" in search_term:
# Email search - use SOQL exact match
contacts = await self.search_contacts_by_email(
search_term, prefs
)
else:
# Name search - use SOSL for fuzzy matching
contacts = await self.search_contacts_by_name(
search_term, prefs
)
if not contacts:
await self.capability_worker.speak(
f"I couldn't find any contacts matching {search_term}. "
"Want me to search accounts instead?"
)
return
if len(contacts) == 1:
# Single result - speak full details
await self.speak_contact_details(contacts[0])
else:
# Multiple results - list them and ask which one
await self.speak_multiple_contacts(contacts)
# Cache results for follow-up
await self.cache_recent_result("contact", contacts, prefs)
async def handle_disambiguation(self, command: str):
"""Handle user selecting from multiple results."""
prefs = await self.get_preferences()
recent = prefs.get("recent_results", {})
if not recent or not recent.get("items"):
await self.capability_worker.speak(
"I don't have any recent results to choose from. "
"Try searching for something first."
)
return
# Extract which number they want
selection = self.parse_selection(command)
if selection is None:
await self.capability_worker.speak(
"I didn't catch which one you want. Try 'the first one' or 'number two'."
)
return
items = recent.get("items", [])
# Check if selection is valid
if selection < 1 or selection > len(items):
await self.capability_worker.speak(
f"I only have {len(items)} results. Try a number between 1 and {len(items)}."
)
return
# Get the selected item (convert to 0-indexed)
selected_item = items[selection - 1]
result_type = recent.get("type")
# Show full details based on type
if result_type == "contact":
await self.speak_contact_details(selected_item)
elif result_type == "opportunity":
await self.speak_opportunity_details(selected_item)
else:
await self.capability_worker.speak(
"I'm not sure what type of result that was."
)
def parse_selection(self, command: str) -> Optional[int]:
"""Parse which item user selected from command."""
cmd_lower = command.lower()
# Number mapping
number_words = {
"first": 1, "1": 1, "one": 1, "number one": 1, "number 1": 1,
"second": 2, "2": 2, "two": 2, "number two": 2, "number 2": 2,
"third": 3, "3": 3, "three": 3, "number three": 3, "number 3": 3,
"fourth": 4, "4": 4, "four": 4, "number four": 4, "number 4": 4,
"fifth": 5, "5": 5, "five": 5, "number five": 5, "number 5": 5
}
for word, number in number_words.items():
if word in cmd_lower:
return number
return None
async def extract_search_term(self, query: str) -> str:
"""Extract the name or email from the query using LLM."""
prompt = (
f"Extract the person's name or email from this query: '{query}'\n"
"Return ONLY the name or email, nothing else.\n"
"Examples:\n"
"Query: 'look up Sarah Chen' → Sarah Chen\n"
"Query: 'find john@acme.com' → john@acme.com\n"
"Query: 'who is the CFO at Acme' → CFO Acme\n"
)
response = self.capability_worker.text_to_text_response(prompt).strip()
# Clean up response
response = response.replace('"', '').replace("'", '').strip()
return response
async def search_contacts_by_email(
self,
email: str,
prefs: dict
) -> List[dict]:
"""Search contacts by exact email match using SOQL."""
# Escape for SOQL injection prevention
email_escaped = self.escape_soql(email)
# Build SOQL query
soql = (
f"SELECT Id, Name, Email, Phone, Title, Account.Name "
f"FROM Contact "
f"WHERE Email = '{email_escaped}' "
f"LIMIT 5"
)
return await self.execute_soql_query(soql, prefs)
async def search_contacts_by_name(
self,
name: str,
prefs: dict
) -> List[dict]:
"""Search contacts by name using SOSL for fuzzy matching."""
# Escape for SOSL
name_escaped = self.escape_soql(name)
# Build SOSL query
sosl = (
f"FIND {{{name_escaped}}} IN NAME FIELDS "
f"RETURNING Contact(Id, Name, Email, Phone, Title, Account.Name) "
f"LIMIT 5"
)
# Execute SOSL search
result = await self.execute_sosl_search(sosl, prefs)
# Extract contacts from SOSL result
if result and "searchRecords" in result:
return result["searchRecords"]
return []
async def execute_soql_query(
self,
soql: str,
prefs: dict
) -> List[dict]:
"""Execute a SOQL query and return records."""
# Use the existing sf_query method
records = await self.sf_query(soql)
if records:
self.worker.editor_logging_handler.info(
f"SOQL query returned {len(records)} records"
)
return records
return []
async def execute_sosl_search(
self,
sosl: str,
prefs: dict
) -> Optional[dict]:
"""Execute a SOSL search and return results."""
# Manually URL encode the query
# Replace spaces with + and special chars
sosl_encoded = sosl.replace(" ", "+").replace("{", "%7B").replace("}", "%7D")
# Make API request
path = f"search?q={sosl_encoded}"
result = await self.sf_request("GET", path)
if result:
self.worker.editor_logging_handler.info(
"SOSL search completed"
)
return result
async def speak_contact_details(self, contact: dict):
"""Speak full details of a single contact."""
# Extract fields
name = contact.get("Name", "Unknown")
email = contact.get("Email", "no email on file")
phone = contact.get("Phone", "no phone on file")
title = contact.get("Title", "")
# Account.Name is a nested object
account_name = ""
if "Account" in contact and contact["Account"]:
account_name = contact["Account"].get("Name", "")
# Build response
response = f"I found {name}."
if title:
response += f" They're the {title}"
if account_name:
response += f" at {account_name}."
else:
response += "."
elif account_name:
response += f" They're at {account_name}."
response += f" Email: {email}."
if phone != "no phone on file":
response += f" Phone: {phone}."
await self.capability_worker.speak(response)
async def speak_multiple_contacts(self, contacts: List[dict]):
"""Speak a list of contacts and ask which one."""
count = len(contacts)
response = f"I found {count} contacts. "
# List first 3
for i, contact in enumerate(contacts[:3]):
name = contact.get("Name", "Unknown")
# Get company if available
company = ""
if "Account" in contact and contact["Account"]:
company = contact["Account"].get("Name", "")
if company:
response += f"{name} at {company}. "
else:
response += f"{name}. "
if count > 3:
response += f"And {count - 3} more. "
response += "Which one?"
await self.capability_worker.speak(response)
async def cache_recent_result(
self,
result_type: str,
items: List[dict],
prefs: dict
):
"""Cache search results for follow-up references."""
prefs["recent_results"] = {
"type": result_type,
"items": items,
"cached_at": datetime.utcnow().isoformat()
}
await self.save_preferences(prefs)
# --- MODE 2: SEARCH OPPORTUNITIES (FULLY IMPLEMENTED) ---
async def search_opportunities(self, query: str):
"""Search for opportunities by name."""
await self.capability_worker.speak("Searching for opportunities...")
prefs = await self.get_preferences()
# Extract opportunity name using LLM
opp_name = await self.extract_opportunity_name(query)
if not opp_name:
await self.capability_worker.speak(
"I didn't catch which opportunity you're looking for. Try again?"
)
return
self.worker.editor_logging_handler.info(
f"Searching for opportunity: {opp_name}"
)
# Search opportunities
opportunities = await self.search_opportunities_by_name(opp_name, prefs)
if not opportunities:
await self.capability_worker.speak(
f"I couldn't find any opportunities matching {opp_name}."
)
return
if len(opportunities) == 1:
# Single result - speak full details
await self.speak_opportunity_details(opportunities[0])
else:
# Multiple results - list and ask which one
await self.speak_multiple_opportunities(opportunities)
# Cache results for follow-up
await self.cache_recent_result("opportunity", opportunities, prefs)
async def extract_opportunity_name(self, query: str) -> str:
"""Extract opportunity name from query using LLM."""
prompt = (
f"Extract the opportunity or deal name from this query: '{query}'\n"
"Return ONLY the opportunity name, nothing else.\n"
"Examples:\n"
"Query: 'how's the Acme deal' → Acme\n"
"Query: 'what's the status of Project Phoenix' → Project Phoenix\n"
"Query: 'check the Widget Co opportunity' → Widget Co\n"
)
response = self.capability_worker.text_to_text_response(prompt).strip()
# Clean up response
response = response.replace('"', '').replace("'", '').strip()
return response
async def search_opportunities_by_name(
self,
name: str,
prefs: dict
) -> List[dict]:
"""Search opportunities by name using SOQL."""
# Escape for SOQL
name_escaped = self.escape_soql(name)
# Build SOQL query
soql = (
f"SELECT Id, Name, StageName, Amount, CloseDate, "
f"Account.Name, Owner.FirstName, Owner.LastName "
f"FROM Opportunity "
f"WHERE Name LIKE '%{name_escaped}%' "
f"AND IsClosed = false "
f"LIMIT 5"
)
return await self.execute_soql_query(soql, prefs)
async def speak_opportunity_details(self, opportunity: dict):
"""Speak full details of a single opportunity."""
# Extract fields
name = opportunity.get("Name", "Unknown opportunity")
stage = opportunity.get("StageName", "unknown stage")
amount = opportunity.get("Amount")
close_date = opportunity.get("CloseDate", "")
# Get account name
account = opportunity.get("Account", {})
account_name = account.get("Name", "") if account else ""
# Get owner name
owner = opportunity.get("Owner", {})
owner_first = owner.get("FirstName", "") if owner else ""
owner_last = owner.get("LastName", "") if owner else ""
owner_name = f"{owner_first} {owner_last}".strip()
# Format amount
amount_text = self.format_currency(amount) if amount else "no amount set"
# Format close date
close_date_text = self.format_date(close_date) if close_date else ""
# Build response
response = f"The {name} opportunity is in {stage}."
if amount_text:
response += f" It's worth {amount_text}."
if close_date_text:
response += f" Close date: {close_date_text}."
if account_name:
response += f" Account is {account_name}."
if owner_name:
response += f" Owned by {owner_name}."
await self.capability_worker.speak(response)
async def speak_multiple_opportunities(self, opportunities: List[dict]):
"""Speak a list of opportunities and ask which one."""
count = len(opportunities)
response = f"I found {count} opportunities. "
# List first 3
for i, opp in enumerate(opportunities[:3]):
name = opp.get("Name", "Unknown")
stage = opp.get("StageName", "unknown stage")
response += f"{name} in {stage}. "
if count > 3:
response += f"And {count - 3} more. "
response += "Which one?"
await self.capability_worker.speak(response)
def format_currency(self, amount) -> str:
"""Format amount as currency for speaking."""
if not amount:
return ""
try:
amount_float = float(amount)
amount_int = int(amount_float)
if amount_int >= 1000000:
# Millions
millions = amount_int / 1000000
if millions == int(millions):
return f"{int(millions)} million dollars"
else:
return f"{millions:.1f} million dollars"
elif amount_int >= 1000:
# Thousands
thousands = amount_int / 1000
if thousands == int(thousands):
return f"{int(thousands)} thousand dollars"
else:
return f"{thousands:.1f} thousand dollars"
else:
return f"{amount_int} dollars"
except Exception:
return ""
def format_date(self, date_str: str) -> str:
"""Format date for speaking."""
if not date_str:
return ""
try:
# Parse date (format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS)
date_part = date_str.split("T")[0]
year, month, day = date_part.split("-")
# Month names
months = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
]
month_name = months[int(month) - 1]
# Add ordinal suffix to day
day_int = int(day)
if 10 <= day_int % 100 <= 20:
suffix = "th"
else:
suffix = {1: "st", 2: "nd", 3: "rd"}.get(day_int % 10, "th")
return f"{month_name} {day_int}{suffix}"
except Exception:
return date_str
# --- MODE 3: LOG NOTE (FULLY IMPLEMENTED) ---
async def log_note(self, command: str):
"""Log a note via creating a completed Task."""
await self.capability_worker.speak("Logging a note...")
prefs = await self.get_preferences()
# Parse command to extract target and note content
parsed = await self.parse_note_command(command)
if not parsed:
await self.capability_worker.speak(
"I didn't catch what you want to log. Try again?"
)
return
target_name = parsed.get("target")
note_content = parsed.get("content")
if not target_name or not note_content:
await self.capability_worker.speak(
"I need both who to log the note on and what the note says."
)
return
self.worker.editor_logging_handler.info(
f"Logging note on '{target_name}': {note_content}"
)
# Find the target record (contact, account, or opportunity)
target_record = await self.find_note_target(target_name, prefs)
if not target_record:
await self.capability_worker.speak(
f"I couldn't find {target_name}. "
"Make sure they exist in your Salesforce."
)
return
# Create the note (as a completed Task)
success = await self.create_note_task(
note_content,
target_record,
prefs
)
if success:
await self.capability_worker.speak(
f"Done. I've logged a note on {target_record['name']}: {note_content}"
)
else:
await self.capability_worker.speak(
"I had trouble creating the note. Please try again."
)
async def parse_note_command(self, command: str) -> Optional[dict]:
"""Parse note command using LLM."""
prompt = (
f"Parse this note command: '{command}'\n"
"Extract the target (person/company name) and the note content.\n"
"Return ONLY valid JSON with 'target' and 'content' fields.\n\n"
"Examples:\n"
"Input: 'log a note on Acme: they want to move forward'\n"
"Output: {{\"target\": \"Acme\", \"content\": \"they want to move forward\"}}\n\n"
"Input: 'add a note to Sarah Chen: she's interested in the enterprise plan'\n"
"Output: {{\"target\": \"Sarah Chen\", \"content\": \"she's interested in the enterprise plan\"}}\n\n"
"Input: 'note for TechCorp: follow up about pricing'\n"
"Output: {{\"target\": \"TechCorp\", \"content\": \"follow up about pricing\"}}\n"
)
response = self.capability_worker.text_to_text_response(prompt).strip()
# Clean markdown fences if present
response = response.replace("```json", "").replace("```", "").strip()
try:
parsed = json.loads(response)
return parsed
except Exception as e:
self.worker.editor_logging_handler.error(
f"Failed to parse note command: {e}"
)
return None
async def find_note_target(
self,
target_name: str,
prefs: dict
) -> Optional[dict]:
"""Find target record for the note (contact, account, or opportunity)."""
# Try contact first
contact = await self.search_contact_by_name_single(target_name, prefs)
if contact:
return {
"type": "contact",
"id": contact.get("Id"),
"name": contact.get("Name", "Unknown")
}
# Try account
account = await self.search_account_by_name(target_name, prefs)
if account:
return {
"type": "account",
"id": account.get("Id"),
"name": account.get("Name", "Unknown")
}
# Try opportunity
opportunity = await self.search_opportunity_by_name_single(target_name, prefs)
if opportunity:
return {
"type": "opportunity",
"id": opportunity.get("Id"),
"name": opportunity.get("Name", "Unknown")
}
return None
async def search_contact_by_name_single(
self,
name: str,
prefs: dict
) -> Optional[dict]:
"""Search for a contact by name (returns first match)."""
contacts = await self.search_contacts_by_name(name, prefs)
return contacts[0] if contacts else None
async def search_account_by_name(
self,
name: str,
prefs: dict
) -> Optional[dict]:
"""Search for an account by name (returns first match)."""
name_escaped = self.escape_soql(name)
soql = (
f"SELECT Id, Name "
f"FROM Account "
f"WHERE Name LIKE '%{name_escaped}%' "
f"LIMIT 1"
)
accounts = await self.execute_soql_query(soql, prefs)
return accounts[0] if accounts else None
async def search_opportunity_by_name_single(
self,
name: str,
prefs: dict
) -> Optional[dict]:
"""Search for an opportunity by name (returns first match)."""
opps = await self.search_opportunities_by_name(name, prefs)
return opps[0] if opps else None
async def create_note_task(
self,
note_content: str,
target_record: dict,
prefs: dict
) -> bool:
"""Create a completed Task as a note."""
# Build subject (max 255 chars)
subject = f"Voice Note: {note_content[:50]}"
if len(note_content) > 50:
subject += "..."
# Build task data
task_data = {
"Subject": subject,
"Description": f"Captured via OpenHome voice: {note_content}",
"Status": "Completed",
"Priority": "Normal",
"ActivityDate": datetime.now().strftime("%Y-%m-%d")
}
# Add association based on target type
target_type = target_record["type"]
target_id = target_record["id"]
if target_type == "contact":
# WhoId for contacts/leads
task_data["WhoId"] = target_id
elif target_type == "account":
# WhatId for accounts
task_data["WhatId"] = target_id
elif target_type == "opportunity":
# WhatId for opportunities
task_data["WhatId"] = target_id
# Create task via API
result = await self.sf_request(
"POST",
"sobjects/Task",
task_data
)
if result and result.get("success"):
self.worker.editor_logging_handler.info(
f"Note task created: {result.get('id')}"
)
return True
return False
# --- MODE 4: CREATE TASK (FULLY IMPLEMENTED) ---
async def create_task(self, command: str):
"""Create a task with due date and priority."""
await self.capability_worker.speak("Creating a task...")
prefs = await self.get_preferences()
# Parse command to extract task details
parsed = await self.parse_task_command(command)
if not parsed:
await self.capability_worker.speak(
"I didn't catch the task details. Try again?"
)
return
subject = parsed.get("subject")
due_date_text = parsed.get("due_date")
priority = parsed.get("priority", "Normal")
target_name = parsed.get("target")
if not subject:
await self.capability_worker.speak(
"I need at least a task subject."
)
return
self.worker.editor_logging_handler.info(
f"Creating task: {subject} (due: {due_date_text}, priority: {priority})"
)
# Parse due date
due_date = self.parse_due_date(due_date_text)
# Find target if specified
target_record = None
if target_name:
target_record = await self.find_note_target(target_name, prefs)
# Create the task
success = await self.create_task_record(
subject,
due_date,
priority,
target_record,
prefs
)
if success:
# Build response
response = f"Done. I've created a task: {subject}"
if due_date_text:
response += f", due {due_date_text}"
if priority and priority != "Normal":
response += f", {priority.lower()} priority"
if target_record:
response += f", for {target_record['name']}"
response += "."
await self.capability_worker.speak(response)
else:
await self.capability_worker.speak(
"I had trouble creating the task. Please try again."
)
async def parse_task_command(self, command: str) -> Optional[dict]:
"""Parse task command using LLM."""
prompt = (
f"Parse this task command: '{command}'\n"
"Extract: subject, due_date (text like 'Friday' or 'tomorrow'), "
"priority (High/Normal/Low), and target (person/company).\n"
"Return ONLY valid JSON.\n\n"
"Examples:\n"
"Input: 'create a task: send proposal to Acme by Friday'\n"
"Output: {{\"subject\": \"send proposal to Acme\", \"due_date\": \"Friday\", "
"\"priority\": \"Normal\", \"target\": \"Acme\"}}\n\n"
"Input: 'remind me to follow up with Sarah next Monday'\n"
"Output: {{\"subject\": \"follow up with Sarah\", \"due_date\": \"next Monday\", "
"\"priority\": \"Normal\", \"target\": \"Sarah\"}}\n\n"
"Input: 'task for Widget Co: schedule a demo, high priority'\n"
"Output: {{\"subject\": \"schedule a demo\", \"due_date\": null, "
"\"priority\": \"High\", \"target\": \"Widget Co\"}}\n"
)
response = self.capability_worker.text_to_text_response(prompt).strip()
# Clean markdown fences
response = response.replace("```json", "").replace("```", "").strip()
try:
parsed = json.loads(response)
return parsed
except Exception as e:
self.worker.editor_logging_handler.error(
f"Failed to parse task command: {e}"
)
return None
def parse_due_date(self, date_text: Optional[str]) -> str:
"""Parse natural language date to YYYY-MM-DD format."""
if not date_text:
# Default to tomorrow
tomorrow = datetime.now() + timedelta(days=1)
return tomorrow.strftime("%Y-%m-%d")
date_lower = date_text.lower()
now = datetime.now()
# Handle common cases
if "tomorrow" in date_lower:
target = now + timedelta(days=1)
elif "today" in date_lower:
target = now
elif "monday" in date_lower:
# Next Monday
days_ahead = 0 - now.weekday() # Monday is 0
if days_ahead <= 0:
days_ahead += 7
if "next" in date_lower:
days_ahead += 7