T7yrttrd commited on
Commit
c625f24
·
verified ·
1 Parent(s): 8bc4b4d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +661 -533
app.py CHANGED
@@ -66,7 +66,7 @@ OAUTH_CONFIGS = {
66
  "client_secret": "ec8548ef297ed59d8372e5bc549d8ed9adc996f7",
67
  "auth_url": "https://github.com/login/oauth/authorize",
68
  "token_url": "https://github.com/login/oauth/access_token",
69
- "scope": "repo read:user user"
70
  },
71
  "figma": {
72
  "client_id": "Cg79RWBHaeyW2afGJVSQi8",
@@ -138,17 +138,15 @@ STRICT IDENTITY RULES:
138
  - To Create a new page: Use `notion_create_page`.
139
 
140
  4. GITHUB CONNECTOR WORKFLOW RULES:
141
- - Always call `github_list_repos` first if you do not know the exact owner or repo name.
142
- - To inspect repository structure or read files, use `github_get_file_or_dir`.
143
- - To search code or find functions across repository, use `github_search_code`.
144
- - To create or edit code/files, use `github_create_or_update_file`.
145
- - To delete files, use `github_delete_file`.
146
- - For Git workflow, use `github_list_branches`, `github_create_branch`, `github_list_commits`, `github_create_pull_request`, or `github_merge_pull_request`.
147
- - For Issue management, use `github_list_issues`, `github_create_issue`, `github_update_issue`, or `github_add_issue_comment`.
148
 
149
  5. NATURAL CONVERSATION & TOOL RESPONSE STYLE:
150
  - Do NOT introduce your company, founder, or model name in general responses unless requested.
151
- - Always summarize and format Google, Notion, and GitHub Connector execution results into clean, polite, and natural language automatically matching the language used by the user.
152
  - Never output raw technical logs, IDs, or developer headers directly to the user."""
153
 
154
  TOOLS = [
@@ -467,12 +465,12 @@ TOOLS = [
467
  {
468
  "type": "function",
469
  "function": {
470
- "name": "github_list_repos",
471
- "description": "List all GitHub repositories accessible by the user",
472
  "parameters": {
473
  "type": "object",
474
  "properties": {
475
- "max_results": {"type": "integer", "description": "Max repositories to list, default 10"}
476
  }
477
  }
478
  }
@@ -480,32 +478,49 @@ TOOLS = [
480
  {
481
  "type": "function",
482
  "function": {
483
- "name": "github_get_file_or_dir",
484
- "description": "Read file content or list directory contents in a GitHub repository",
485
  "parameters": {
486
  "type": "object",
487
  "properties": {
488
- "owner": {"type": "string", "description": "Repository owner/username"},
489
- "repo": {"type": "string", "description": "Repository name"},
490
- "path": {"type": "string", "description": "File or folder path e.g. 'src/index.js' or '' for root"},
491
- "ref": {"type": "string", "description": "Branch, tag, or commit SHA, default 'main'"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
492
  },
493
- "required": ["owner", "repo"]
494
  }
495
  }
496
  },
497
  {
498
  "type": "function",
499
  "function": {
500
- "name": "github_search_code",
501
- "description": "Search code, functions, or text across GitHub repositories",
502
  "parameters": {
503
  "type": "object",
504
  "properties": {
505
- "query": {"type": "string", "description": "Code or text to search for"},
506
- "repo": {"type": "string", "description": "Optional target repository e.g. 'owner/repo'"}
 
 
507
  },
508
- "required": ["query"]
509
  }
510
  }
511
  },
@@ -513,19 +528,19 @@ TOOLS = [
513
  "type": "function",
514
  "function": {
515
  "name": "github_create_or_update_file",
516
- "description": "Create a new file or update/edit an existing file in GitHub repository",
517
  "parameters": {
518
  "type": "object",
519
  "properties": {
520
- "owner": {"type": "string", "description": "Repository owner"},
521
  "repo": {"type": "string", "description": "Repository name"},
522
- "path": {"type": "string", "description": "File path in repository"},
 
523
  "message": {"type": "string", "description": "Commit message"},
524
- "content": {"type": "string", "description": "Text content of the file"},
525
- "branch": {"type": "string", "description": "Target branch, default 'main'"},
526
- "sha": {"type": "string", "description": "SHA of existing file if updating"}
527
  },
528
- "required": ["owner", "repo", "path", "message", "content"]
529
  }
530
  }
531
  },
@@ -533,18 +548,18 @@ TOOLS = [
533
  "type": "function",
534
  "function": {
535
  "name": "github_delete_file",
536
- "description": "Delete a file from GitHub repository",
537
  "parameters": {
538
  "type": "object",
539
  "properties": {
540
  "owner": {"type": "string", "description": "Repository owner"},
541
  "repo": {"type": "string", "description": "Repository name"},
542
  "path": {"type": "string", "description": "File path to delete"},
543
- "message": {"type": "string", "description": "Commit message for deletion"},
544
- "branch": {"type": "string", "description": "Target branch, default 'main'"},
545
- "sha": {"type": "string", "description": "SHA of file to delete"}
546
  },
547
- "required": ["owner", "repo", "path", "message"]
548
  }
549
  }
550
  },
@@ -552,7 +567,7 @@ TOOLS = [
552
  "type": "function",
553
  "function": {
554
  "name": "github_list_branches",
555
- "description": "List all branches in a GitHub repository",
556
  "parameters": {
557
  "type": "object",
558
  "properties": {
@@ -573,7 +588,7 @@ TOOLS = [
573
  "properties": {
574
  "owner": {"type": "string", "description": "Repository owner"},
575
  "repo": {"type": "string", "description": "Repository name"},
576
- "branch_name": {"type": "string", "description": "Name for new branch"},
577
  "from_branch": {"type": "string", "description": "Source branch name, default 'main'"}
578
  },
579
  "required": ["owner", "repo", "branch_name"]
@@ -584,14 +599,14 @@ TOOLS = [
584
  "type": "function",
585
  "function": {
586
  "name": "github_list_commits",
587
- "description": "List recent commits in a GitHub repository branch",
588
  "parameters": {
589
  "type": "object",
590
  "properties": {
591
  "owner": {"type": "string", "description": "Repository owner"},
592
  "repo": {"type": "string", "description": "Repository name"},
593
- "branch": {"type": "string", "description": "Branch name, default 'main'"},
594
- "max_results": {"type": "integer", "description": "Max commits to list, default 10"}
595
  },
596
  "required": ["owner", "repo"]
597
  }
@@ -600,14 +615,14 @@ TOOLS = [
600
  {
601
  "type": "function",
602
  "function": {
603
- "name": "github_list_pull_requests",
604
- "description": "List Pull Requests in a GitHub repository",
605
  "parameters": {
606
  "type": "object",
607
  "properties": {
608
  "owner": {"type": "string", "description": "Repository owner"},
609
  "repo": {"type": "string", "description": "Repository name"},
610
- "state": {"type": "string", "description": "'open', 'closed', or 'all', default 'open'"}
611
  },
612
  "required": ["owner", "repo"]
613
  }
@@ -616,107 +631,137 @@ TOOLS = [
616
  {
617
  "type": "function",
618
  "function": {
619
- "name": "github_create_pull_request",
620
- "description": "Create a new Pull Request in a GitHub repository",
621
  "parameters": {
622
  "type": "object",
623
  "properties": {
624
  "owner": {"type": "string", "description": "Repository owner"},
625
  "repo": {"type": "string", "description": "Repository name"},
626
- "title": {"type": "string", "description": "PR title"},
627
- "head": {"type": "string", "description": "Feature branch name containing changes"},
628
- "base": {"type": "string", "description": "Target branch to merge into, default 'main'"},
629
- "body": {"type": "string", "description": "PR description"}
630
  },
631
- "required": ["owner", "repo", "title", "head"]
632
  }
633
  }
634
  },
635
  {
636
  "type": "function",
637
  "function": {
638
- "name": "github_merge_pull_request",
639
- "description": "Merge a Pull Request in a GitHub repository",
640
  "parameters": {
641
  "type": "object",
642
  "properties": {
643
  "owner": {"type": "string", "description": "Repository owner"},
644
  "repo": {"type": "string", "description": "Repository name"},
645
- "pull_number": {"type": "integer", "description": "PR number"},
646
- "commit_title": {"type": "string", "description": "Optional merge commit message"}
 
 
647
  },
648
- "required": ["owner", "repo", "pull_number"]
649
  }
650
  }
651
  },
652
  {
653
  "type": "function",
654
  "function": {
655
- "name": "github_list_issues",
656
- "description": "List issues in a GitHub repository",
657
  "parameters": {
658
  "type": "object",
659
  "properties": {
660
  "owner": {"type": "string", "description": "Repository owner"},
661
  "repo": {"type": "string", "description": "Repository name"},
662
- "state": {"type": "string", "description": "'open', 'closed', or 'all', default 'open'"}
 
663
  },
664
- "required": ["owner", "repo"]
665
  }
666
  }
667
  },
668
  {
669
  "type": "function",
670
  "function": {
671
- "name": "github_create_issue",
672
- "description": "Create a new Issue in a GitHub repository",
673
  "parameters": {
674
  "type": "object",
675
  "properties": {
676
  "owner": {"type": "string", "description": "Repository owner"},
677
  "repo": {"type": "string", "description": "Repository name"},
678
- "title": {"type": "string", "description": "Issue title"},
679
- "body": {"type": "string", "description": "Issue body content"},
680
- "labels": {"type": "array", "items": {"type": "string"}, "description": "Labels list"},
681
- "assignees": {"type": "array", "items": {"type": "string"}, "description": "Usernames to assign"}
682
  },
683
- "required": ["owner", "repo", "title"]
684
  }
685
  }
686
  },
687
  {
688
  "type": "function",
689
  "function": {
690
- "name": "github_update_issue",
691
- "description": "Update or close an Issue in GitHub repository",
692
  "parameters": {
693
  "type": "object",
694
  "properties": {
695
  "owner": {"type": "string", "description": "Repository owner"},
696
  "repo": {"type": "string", "description": "Repository name"},
697
- "issue_number": {"type": "integer", "description": "Issue number"},
698
- "title": {"type": "string", "description": "New title"},
699
- "body": {"type": "string", "description": "New body"},
700
- "state": {"type": "string", "description": "'open' or 'closed'"}
701
  },
702
- "required": ["owner", "repo", "issue_number"]
703
  }
704
  }
705
  },
706
  {
707
  "type": "function",
708
  "function": {
709
- "name": "github_add_issue_comment",
710
- "description": "Add a comment to an Issue or PR in GitHub",
711
  "parameters": {
712
  "type": "object",
713
  "properties": {
714
  "owner": {"type": "string", "description": "Repository owner"},
715
  "repo": {"type": "string", "description": "Repository name"},
716
- "issue_number": {"type": "integer", "description": "Issue or PR number"},
717
- "body": {"type": "string", "description": "Comment text"}
 
718
  },
719
- "required": ["owner", "repo", "issue_number", "body"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
720
  }
721
  }
722
  }
@@ -750,7 +795,7 @@ async def save_token_to_supabase(user_id: str, service: str, token_data: dict):
750
  pass
751
 
752
  async def get_token_from_supabase(user_id: str, service: str):
753
- check_services = [service, "google", "gmail", "calendar", "drive"]
754
  for s in check_services:
755
  if (user_id, s) in user_tokens:
756
  return user_tokens[(user_id, s)]
@@ -1013,130 +1058,539 @@ async def notion_append_block_children(user_id: str, page_id: str, content: str)
1013
  except Exception as e:
1014
  return f"Error appending content to Notion: {str(e)}"
1015
 
1016
- async def gmail_search_emails(user_id: str, query: str = "", max_results: int = 5):
1017
- creds = await get_google_creds(user_id, "gmail")
1018
- if not creds:
1019
- return "Gmail is not connected. Please connect Google account."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1020
  try:
1021
- service = build("gmail", "v1", credentials=creds)
1022
- q_str = query if query else ""
1023
- results = service.users().messages().list(userId="me", q=q_str, maxResults=max_results).execute()
1024
- messages = results.get("messages", [])
1025
- if not messages:
1026
- return "No emails found matching the query."
1027
- email_list = []
1028
- for msg in messages:
1029
- detail = service.users().messages().get(userId="me", id=msg["id"], format="metadata", metadataHeaders=["Subject", "From", "Date"]).execute()
1030
- headers = {h["name"]: h["value"] for h in detail.get("payload", {}).get("headers", [])}
1031
- snippet = detail.get("snippet", "")
1032
- email_list.append(f"Message ID: {msg['id']} | From: {headers.get('From', 'N/A')} | Subject: {headers.get('Subject', 'N/A')} | Date: {headers.get('Date', 'N/A')} | Snippet: {snippet}")
1033
- return "\n".join(email_list)
 
1034
  except Exception as e:
1035
- return f"Error executing Gmail search: {str(e)}"
1036
 
1037
- async def gmail_get_email_detail(user_id: str, message_id: str):
1038
- creds = await get_google_creds(user_id, "gmail")
1039
- if not creds:
1040
- return "Gmail is not connected."
1041
  try:
1042
- service = build("gmail", "v1", credentials=creds)
1043
- detail = service.users().messages().get(userId="me", id=message_id, format="full").execute()
1044
- headers = {h["name"]: h["value"] for h in detail.get("payload", {}).get("headers", [])}
1045
- snippet = detail.get("snippet", "")
1046
- return f"From: {headers.get('From')}\nTo: {headers.get('To')}\nSubject: {headers.get('Subject')}\nDate: {headers.get('Date')}\nContent Snippet: {snippet}"
 
 
 
 
 
 
 
 
 
 
 
 
 
1047
  except Exception as e:
1048
- return f"Error getting email detail: {str(e)}"
1049
 
1050
- async def gmail_create_draft(user_id: str, to: str, subject: str, body: str):
1051
- creds = await get_google_creds(user_id, "gmail")
1052
- if not creds:
1053
- return "Gmail is not connected."
1054
  try:
1055
- service = build("gmail", "v1", credentials=creds)
1056
- msg = EmailMessage()
1057
- msg.set_content(body)
1058
- msg["To"] = to
1059
- msg["Subject"] = subject
1060
- raw = base64.urlsafe_b64encode(msg.as_bytes()).decode()
1061
- draft = service.users().drafts().create(userId="me", body={"message": {"raw": raw}}).execute()
1062
- return f"Successfully created draft to {to} with Subject: '{subject}' (Draft ID: {draft.get('id')})."
 
 
 
 
 
1063
  except Exception as e:
1064
- return f"Error creating draft: {str(e)}"
1065
 
1066
- async def gmail_send_email(user_id: str, to: str, subject: str, body: str):
1067
- creds = await get_google_creds(user_id, "gmail")
1068
- if not creds:
1069
- return "Gmail is not connected."
1070
  try:
1071
- service = build("gmail", "v1", credentials=creds)
1072
- msg = EmailMessage()
1073
- msg.set_content(body)
1074
- msg["To"] = to
1075
- msg["Subject"] = subject
1076
- raw = base64.urlsafe_b64encode(msg.as_bytes()).decode()
1077
- res = service.users().messages().send(userId="me", body={"raw": raw}).execute()
1078
- return f"Successfully sent email to {to} with Subject: '{subject}' (Message ID: {res.get('id')})."
 
 
 
 
 
 
 
 
 
 
 
1079
  except Exception as e:
1080
- return f"Error sending email: {str(e)}"
1081
 
1082
- async def gmail_delete_email(user_id: str, message_id: str):
1083
- creds = await get_google_creds(user_id, "gmail")
1084
- if not creds:
1085
- return "Gmail is not connected."
1086
  try:
1087
- service = build("gmail", "v1", credentials=creds)
1088
- try:
1089
- service.users().messages().delete(userId="me", id=message_id).execute()
1090
- except Exception:
1091
- service.users().messages().trash(userId="me", id=message_id).execute()
1092
- return f"Successfully deleted email with ID: {message_id}."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1093
  except Exception as e:
1094
- return f"Error deleting email: {str(e)}"
1095
 
1096
- async def gmail_delete_draft(user_id: str, draft_id: str = None, query: str = None):
1097
- creds = await get_google_creds(user_id, "gmail")
1098
- if not creds:
1099
- return "Gmail is not connected."
1100
  try:
1101
- service = build("gmail", "v1", credentials=creds)
1102
- target_id = draft_id
1103
- if not target_id and query:
1104
- drafts_res = service.users().drafts().list(userId="me").execute()
1105
- drafts = drafts_res.get("drafts", [])
1106
- for d in drafts:
1107
- detail = service.users().drafts().get(userId="me", id=d["id"]).execute()
1108
- snippet = detail.get("message", {}).get("snippet", "")
1109
- if query.lower() in snippet.lower():
1110
- target_id = d["id"]
1111
- break
1112
- if not target_id:
1113
- return f"No matching draft found for query: {query}"
1114
- service.users().drafts().delete(userId="me", id=target_id).execute()
1115
- return f"Successfully deleted draft with ID: {target_id}."
1116
  except Exception as e:
1117
- return f"Error deleting draft: {str(e)}"
1118
 
1119
- async def calendar_list_events(user_id: str, max_results: int = 10):
1120
- creds = await get_google_creds(user_id, "calendar")
1121
- if not creds:
1122
- return "Google Calendar is not connected."
1123
  try:
1124
- service = build("calendar", "v3", credentials=creds)
1125
- events_result = service.events().list(calendarId="primary", maxResults=max_results, singleEvents=True, orderBy="startTime").execute()
1126
- events = events_result.get("items", [])
1127
- if not events:
1128
- return "No upcoming events found in Google Calendar."
1129
- event_list = []
1130
- for event in events:
1131
- start = event["start"].get("dateTime", event["start"].get("date"))
1132
- end = event["end"].get("dateTime", event["end"].get("date"))
1133
- summary = event.get("summary", "No Title")
1134
- event_list.append(f"Event ID: {event['id']} | Title: {summary} | Start: {start} | End: {end}")
1135
- return "\n".join(event_list)
1136
  except Exception as e:
1137
- return f"Error listing calendar events: {str(e)}"
1138
 
1139
- async def calendar_create_event(user_id: str, summary: str, start_time: str, end_time: str, description: str = "", location: str = ""):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1140
  creds = await get_google_creds(user_id, "calendar")
1141
  if not creds:
1142
  return "Google Calendar is not connected."
@@ -1262,338 +1716,6 @@ async def drive_update_file(user_id: str, file_id: str, content: str):
1262
  except Exception as e:
1263
  return f"Error updating Drive file: {str(e)}"
1264
 
1265
- async def github_get_headers(user_id: str):
1266
- token_data = await get_token_from_supabase(user_id, "github")
1267
- if not token_data:
1268
- return None
1269
- token = token_data.get("access_token") or token_data.get("token")
1270
- if not token:
1271
- return None
1272
- return {
1273
- "Authorization": f"Bearer {token}",
1274
- "Accept": "application/vnd.github.v3+json",
1275
- "User-Agent": "Spark-App"
1276
- }
1277
-
1278
- async def github_list_repos(user_id: str, max_results: int = 10):
1279
- headers = await github_get_headers(user_id)
1280
- if not headers:
1281
- return "GitHub is not connected. Please connect your GitHub account."
1282
- try:
1283
- url = f"https://api.github.com/user/repos?sort=updated&per_page={max_results}"
1284
- async with httpx.AsyncClient() as c:
1285
- res = await c.get(url, headers=headers)
1286
- if res.status_code != 200:
1287
- return f"Error fetching GitHub repositories: {res.text}"
1288
- data = res.json()
1289
- if not data:
1290
- return "No repositories found in user's GitHub account."
1291
- repos = []
1292
- for r in data:
1293
- repos.append(f"Repo: {r.get('full_name')} | Default Branch: {r.get('default_branch', 'main')} | Private: {r.get('private')} | URL: {r.get('html_url')}")
1294
- return "\n".join(repos)
1295
- except Exception as e:
1296
- return f"Error fetching GitHub repositories: {str(e)}"
1297
-
1298
- async def github_get_file_or_dir(user_id: str, owner: str, repo: str, path: str = "", ref: str = "main"):
1299
- headers = await github_get_headers(user_id)
1300
- if not headers:
1301
- return "GitHub is not connected."
1302
- try:
1303
- url = f"https://api.github.com/repos/{owner}/{repo}/contents/{path}?ref={ref}"
1304
- async with httpx.AsyncClient() as c:
1305
- res = await c.get(url, headers=headers)
1306
- if res.status_code != 200:
1307
- return f"Error reading GitHub path '{path}': {res.text}"
1308
- data = res.json()
1309
- if isinstance(data, list):
1310
- items = []
1311
- for item in data:
1312
- items.append(f"[{item.get('type')}] {item.get('name')} (Path: {item.get('path')})")
1313
- return "\n".join(items)
1314
- elif isinstance(data, dict):
1315
- content_b64 = data.get("content", "")
1316
- if content_b64:
1317
- decoded = base64.b64decode(content_b64.encode()).decode("utf-8", errors="ignore")
1318
- sha = data.get("sha", "")
1319
- return f"File: {data.get('path')} | SHA: {sha}\n\nContent:\n{decoded}"
1320
- return f"File metadata retrieved (Path: {data.get('path')}, SHA: {data.get('sha')}). Content unavailable or empty."
1321
- return "Unknown content structure."
1322
- except Exception as e:
1323
- return f"Error accessing GitHub repository: {str(e)}"
1324
-
1325
- async def github_search_code(user_id: str, query: str, repo: str = None):
1326
- headers = await github_get_headers(user_id)
1327
- if not headers:
1328
- return "GitHub is not connected."
1329
- try:
1330
- q = f"{query}+repo:{repo}" if repo else query
1331
- url = f"https://api.github.com/search/code?q={q}"
1332
- async with httpx.AsyncClient() as c:
1333
- res = await c.get(url, headers=headers)
1334
- if res.status_code != 200:
1335
- return f"Error searching GitHub code: {res.text}"
1336
- data = res.json()
1337
- items = data.get("items", [])
1338
- if not items:
1339
- return f"No code found matching query: '{query}'"
1340
- results = []
1341
- for item in items[:10]:
1342
- results.append(f"Repo: {item.get('repository', {}).get('full_name')} | File: {item.get('path')} | URL: {item.get('html_url')}")
1343
- return "\n".join(results)
1344
- except Exception as e:
1345
- return f"Error searching code: {str(e)}"
1346
-
1347
- async def github_create_or_update_file(user_id: str, owner: str, repo: str, path: str, message: str, content: str, branch: str = "main", sha: str = None):
1348
- headers = await github_get_headers(user_id)
1349
- if not headers:
1350
- return "GitHub is not connected."
1351
- try:
1352
- url = f"https://api.github.com/repos/{owner}/{repo}/contents/{path}"
1353
- if not sha:
1354
- async with httpx.AsyncClient() as c:
1355
- get_res = await c.get(f"{url}?ref={branch}", headers=headers)
1356
- if get_res.status_code == 200:
1357
- sha = get_res.json().get("sha")
1358
-
1359
- encoded_content = base64.b64encode(content.encode("utf-8")).decode("utf-8")
1360
- payload = {
1361
- "message": message,
1362
- "content": encoded_content,
1363
- "branch": branch
1364
- }
1365
- if sha:
1366
- payload["sha"] = sha
1367
-
1368
- async with httpx.AsyncClient() as c:
1369
- res = await c.put(url, headers=headers, json=payload)
1370
- if res.status_code not in [200, 201]:
1371
- return f"Error committing file to GitHub: {res.text}"
1372
- res_data = res.json()
1373
- commit_sha = res_data.get("commit", {}).get("sha", "")
1374
- return f"Successfully committed file '{path}' to branch '{branch}' (Commit SHA: {commit_sha})."
1375
- except Exception as e:
1376
- return f"Error writing file to GitHub: {str(e)}"
1377
-
1378
- async def github_delete_file(user_id: str, owner: str, repo: str, path: str, message: str, branch: str = "main", sha: str = None):
1379
- headers = await github_get_headers(user_id)
1380
- if not headers:
1381
- return "GitHub is not connected."
1382
- try:
1383
- url = f"https://api.github.com/repos/{owner}/{repo}/contents/{path}"
1384
- if not sha:
1385
- async with httpx.AsyncClient() as c:
1386
- get_res = await c.get(f"{url}?ref={branch}", headers=headers)
1387
- if get_res.status_code == 200:
1388
- sha = get_res.json().get("sha")
1389
- else:
1390
- return f"Cannot find file '{path}' to delete."
1391
-
1392
- payload = {
1393
- "message": message,
1394
- "sha": sha,
1395
- "branch": branch
1396
- }
1397
- async with httpx.AsyncClient() as c:
1398
- res = await c.request("DELETE", url, headers=headers, json=payload)
1399
- if res.status_code != 200:
1400
- return f"Error deleting file from GitHub: {res.text}"
1401
- return f"Successfully deleted file '{path}' from branch '{branch}'."
1402
- except Exception as e:
1403
- return f"Error deleting GitHub file: {str(e)}"
1404
-
1405
- async def github_list_branches(user_id: str, owner: str, repo: str):
1406
- headers = await github_get_headers(user_id)
1407
- if not headers:
1408
- return "GitHub is not connected."
1409
- try:
1410
- url = f"https://api.github.com/repos/{owner}/{repo}/branches"
1411
- async with httpx.AsyncClient() as c:
1412
- res = await c.get(url, headers=headers)
1413
- if res.status_code != 200:
1414
- return f"Error listing branches: {res.text}"
1415
- data = res.json()
1416
- branches = [f"Branch: {b.get('name')} | SHA: {b.get('commit', {}).get('sha')}" for b in data]
1417
- return "\n".join(branches) if branches else "No branches found."
1418
- except Exception as e:
1419
- return f"Error listing branches: {str(e)}"
1420
-
1421
- async def github_create_branch(user_id: str, owner: str, repo: str, branch_name: str, from_branch: str = "main"):
1422
- headers = await github_get_headers(user_id)
1423
- if not headers:
1424
- return "GitHub is not connected."
1425
- try:
1426
- async with httpx.AsyncClient() as c:
1427
- ref_res = await c.get(f"https://api.github.com/repos/{owner}/{repo}/git/ref/heads/{from_branch}", headers=headers)
1428
- if ref_res.status_code != 200:
1429
- return f"Error getting reference SHA for branch '{from_branch}': {ref_res.text}"
1430
- source_sha = ref_res.json().get("object", {}).get("sha")
1431
-
1432
- payload = {
1433
- "ref": f"refs/heads/{branch_name}",
1434
- "sha": source_sha
1435
- }
1436
- res = await c.post(f"https://api.github.com/repos/{owner}/{repo}/git/refs", headers=headers, json=payload)
1437
- if res.status_code != 201:
1438
- return f"Error creating branch: {res.text}"
1439
- return f"Successfully created branch '{branch_name}' from '{from_branch}'."
1440
- except Exception as e:
1441
- return f"Error creating branch: {str(e)}"
1442
-
1443
- async def github_list_commits(user_id: str, owner: str, repo: str, branch: str = "main", max_results: int = 10):
1444
- headers = await github_get_headers(user_id)
1445
- if not headers:
1446
- return "GitHub is not connected."
1447
- try:
1448
- url = f"https://api.github.com/repos/{owner}/{repo}/commits?sha={branch}&per_page={max_results}"
1449
- async with httpx.AsyncClient() as c:
1450
- res = await c.get(url, headers=headers)
1451
- if res.status_code != 200:
1452
- return f"Error fetching commits: {res.text}"
1453
- data = res.json()
1454
- commits = []
1455
- for cm in data:
1456
- sha = cm.get("sha", "")[:7]
1457
- msg = cm.get("commit", {}).get("message", "").split("\n")[0]
1458
- author = cm.get("commit", {}).get("author", {}).get("name", "Unknown")
1459
- commits.append(f"Commit: {sha} | Author: {author} | Message: {msg}")
1460
- return "\n".join(commits) if commits else "No commits found."
1461
- except Exception as e:
1462
- return f"Error fetching commits: {str(e)}"
1463
-
1464
- async def github_list_pull_requests(user_id: str, owner: str, repo: str, state: str = "open"):
1465
- headers = await github_get_headers(user_id)
1466
- if not headers:
1467
- return "GitHub is not connected."
1468
- try:
1469
- url = f"https://api.github.com/repos/{owner}/{repo}/pulls?state={state}"
1470
- async with httpx.AsyncClient() as c:
1471
- res = await c.get(url, headers=headers)
1472
- if res.status_code != 200:
1473
- return f"Error fetching pull requests: {res.text}"
1474
- data = res.json()
1475
- prs = []
1476
- for pr in data:
1477
- prs.append(f"PR #{pr.get('number')}: {pr.get('title')} | State: {pr.get('state')} | Head: {pr.get('head', {}).get('ref')} -> Base: {pr.get('base', {}).get('ref')}")
1478
- return "\n".join(prs) if prs else f"No {state} Pull Requests found."
1479
- except Exception as e:
1480
- return f"Error fetching Pull Requests: {str(e)}"
1481
-
1482
- async def github_create_pull_request(user_id: str, owner: str, repo: str, title: str, head: str, base: str = "main", body: str = ""):
1483
- headers = await github_get_headers(user_id)
1484
- if not headers:
1485
- return "GitHub is not connected."
1486
- try:
1487
- url = f"https://api.github.com/repos/{owner}/{repo}/pulls"
1488
- payload = {
1489
- "title": title,
1490
- "head": head,
1491
- "base": base,
1492
- "body": body
1493
- }
1494
- async with httpx.AsyncClient() as c:
1495
- res = await c.post(url, headers=headers, json=payload)
1496
- if res.status_code != 201:
1497
- return f"Error creating Pull Request: {res.text}"
1498
- data = res.json()
1499
- return f"Successfully created Pull Request #{data.get('number')} '{title}' (URL: {data.get('html_url')})."
1500
- except Exception as e:
1501
- return f"Error creating Pull Request: {str(e)}"
1502
-
1503
- async def github_merge_pull_request(user_id: str, owner: str, repo: str, pull_number: int, commit_title: str = ""):
1504
- headers = await github_get_headers(user_id)
1505
- if not headers:
1506
- return "GitHub is not connected."
1507
- try:
1508
- url = f"https://api.github.com/repos/{owner}/{repo}/pulls/{pull_number}/merge"
1509
- payload = {}
1510
- if commit_title:
1511
- payload["commit_title"] = commit_title
1512
- async with httpx.AsyncClient() as c:
1513
- res = await c.put(url, headers=headers, json=payload)
1514
- if res.status_code != 200:
1515
- return f"Error merging Pull Request: {res.text}"
1516
- return f"Successfully merged Pull Request #{pull_number}."
1517
- except Exception as e:
1518
- return f"Error merging Pull Request: {str(e)}"
1519
-
1520
- async def github_list_issues(user_id: str, owner: str, repo: str, state: str = "open"):
1521
- headers = await github_get_headers(user_id)
1522
- if not headers:
1523
- return "GitHub is not connected."
1524
- try:
1525
- url = f"https://api.github.com/repos/{owner}/{repo}/issues?state={state}"
1526
- async with httpx.AsyncClient() as c:
1527
- res = await c.get(url, headers=headers)
1528
- if res.status_code != 200:
1529
- return f"Error fetching issues: {res.text}"
1530
- data = res.json()
1531
- issues = []
1532
- for issue in data:
1533
- if "pull_request" not in issue:
1534
- issues.append(f"Issue #{issue.get('number')}: {issue.get('title')} | State: {issue.get('state')} | Author: {issue.get('user', {}).get('login')}")
1535
- return "\n".join(issues) if issues else f"No {state} issues found."
1536
- except Exception as e:
1537
- return f"Error fetching issues: {str(e)}"
1538
-
1539
- async def github_create_issue(user_id: str, owner: str, repo: str, title: str, body: str = "", labels: list = None, assignees: list = None):
1540
- headers = await github_get_headers(user_id)
1541
- if not headers:
1542
- return "GitHub is not connected."
1543
- try:
1544
- url = f"https://api.github.com/repos/{owner}/{repo}/issues"
1545
- payload = {
1546
- "title": title,
1547
- "body": body
1548
- }
1549
- if labels:
1550
- payload["labels"] = labels
1551
- if assignees:
1552
- payload["assignees"] = assignees
1553
-
1554
- async with httpx.AsyncClient() as c:
1555
- res = await c.post(url, headers=headers, json=payload)
1556
- if res.status_code != 201:
1557
- return f"Error creating issue: {res.text}"
1558
- data = res.json()
1559
- return f"Successfully created Issue #{data.get('number')} '{title}' (URL: {data.get('html_url')})."
1560
- except Exception as e:
1561
- return f"Error creating GitHub issue: {str(e)}"
1562
-
1563
- async def github_update_issue(user_id: str, owner: str, repo: str, issue_number: int, title: str = None, body: str = None, state: str = None):
1564
- headers = await github_get_headers(user_id)
1565
- if not headers:
1566
- return "GitHub is not connected."
1567
- try:
1568
- url = f"https://api.github.com/repos/{owner}/{repo}/issues/{issue_number}"
1569
- payload = {}
1570
- if title: payload["title"] = title
1571
- if body: payload["body"] = body
1572
- if state: payload["state"] = state
1573
-
1574
- async with httpx.AsyncClient() as c:
1575
- res = await c.patch(url, headers=headers, json=payload)
1576
- if res.status_code != 200:
1577
- return f"Error updating issue: {res.text}"
1578
- return f"Successfully updated Issue #{issue_number}."
1579
- except Exception as e:
1580
- return f"Error updating GitHub issue: {str(e)}"
1581
-
1582
- async def github_add_issue_comment(user_id: str, owner: str, repo: str, issue_number: int, body: str):
1583
- headers = await github_get_headers(user_id)
1584
- if not headers:
1585
- return "GitHub is not connected."
1586
- try:
1587
- url = f"https://api.github.com/repos/{owner}/{repo}/issues/{issue_number}/comments"
1588
- payload = {"body": body}
1589
- async with httpx.AsyncClient() as c:
1590
- res = await c.post(url, headers=headers, json=payload)
1591
- if res.status_code != 201:
1592
- return f"Error adding comment: {res.text}"
1593
- return f"Successfully commented on Issue/PR #{issue_number}."
1594
- except Exception as e:
1595
- return f"Error commenting on GitHub issue: {str(e)}"
1596
-
1597
  async def execute_tool_call(user_id: str, func_name: str, args: dict) -> str:
1598
  if func_name == "gmail_search_emails":
1599
  return await gmail_search_emails(user_id, args.get("query", ""), args.get("max_results", 5))
@@ -1637,36 +1759,42 @@ async def execute_tool_call(user_id: str, func_name: str, args: dict) -> str:
1637
  return await notion_delete_page(user_id, args.get("page_id", ""))
1638
  elif func_name == "notion_append_block_children":
1639
  return await notion_append_block_children(user_id, args.get("page_id", ""), args.get("content", ""))
1640
- elif func_name == "github_list_repos":
1641
- return await github_list_repos(user_id, args.get("max_results", 10))
1642
- elif func_name == "github_get_file_or_dir":
1643
- return await github_get_file_or_dir(user_id, args.get("owner", ""), args.get("repo", ""), args.get("path", ""), args.get("ref", "main"))
1644
- elif func_name == "github_search_code":
1645
- return await github_search_code(user_id, args.get("query", ""), args.get("repo"))
 
 
1646
  elif func_name == "github_create_or_update_file":
1647
- return await github_create_or_update_file(user_id, args.get("owner", ""), args.get("repo", ""), args.get("path", ""), args.get("message", ""), args.get("content", ""), args.get("branch", "main"), args.get("sha"))
1648
  elif func_name == "github_delete_file":
1649
- return await github_delete_file(user_id, args.get("owner", ""), args.get("repo", ""), args.get("path", ""), args.get("message", ""), args.get("branch", "main"), args.get("sha"))
1650
  elif func_name == "github_list_branches":
1651
  return await github_list_branches(user_id, args.get("owner", ""), args.get("repo", ""))
1652
  elif func_name == "github_create_branch":
1653
  return await github_create_branch(user_id, args.get("owner", ""), args.get("repo", ""), args.get("branch_name", ""), args.get("from_branch", "main"))
1654
  elif func_name == "github_list_commits":
1655
- return await github_list_commits(user_id, args.get("owner", ""), args.get("repo", ""), args.get("branch", "main"), args.get("max_results", 10))
 
 
 
 
 
 
 
 
1656
  elif func_name == "github_list_pull_requests":
1657
  return await github_list_pull_requests(user_id, args.get("owner", ""), args.get("repo", ""), args.get("state", "open"))
1658
  elif func_name == "github_create_pull_request":
1659
  return await github_create_pull_request(user_id, args.get("owner", ""), args.get("repo", ""), args.get("title", ""), args.get("head", ""), args.get("base", "main"), args.get("body", ""))
1660
  elif func_name == "github_merge_pull_request":
1661
- return await github_merge_pull_request(user_id, args.get("owner", ""), args.get("repo", ""), args.get("pull_number", 0), args.get("commit_title", ""))
1662
- elif func_name == "github_list_issues":
1663
- return await github_list_issues(user_id, args.get("owner", ""), args.get("repo", ""), args.get("state", "open"))
1664
- elif func_name == "github_create_issue":
1665
- return await github_create_issue(user_id, args.get("owner", ""), args.get("repo", ""), args.get("title", ""), args.get("body", ""), args.get("labels"), args.get("assignees"))
1666
- elif func_name == "github_update_issue":
1667
- return await github_update_issue(user_id, args.get("owner", ""), args.get("repo", ""), args.get("issue_number", 0), args.get("title"), args.get("body"), args.get("state"))
1668
- elif func_name == "github_add_issue_comment":
1669
- return await github_add_issue_comment(user_id, args.get("owner", ""), args.get("repo", ""), args.get("issue_number", 0), args.get("body", ""))
1670
  return "Unknown tool function."
1671
 
1672
  def count_tokens(messages):
 
66
  "client_secret": "ec8548ef297ed59d8372e5bc549d8ed9adc996f7",
67
  "auth_url": "https://github.com/login/oauth/authorize",
68
  "token_url": "https://github.com/login/oauth/access_token",
69
+ "scope": "read:user user repo workflow delete_repo"
70
  },
71
  "figma": {
72
  "client_id": "Cg79RWBHaeyW2afGJVSQi8",
 
138
  - To Create a new page: Use `notion_create_page`.
139
 
140
  4. GITHUB CONNECTOR WORKFLOW RULES:
141
+ - You have full access to GitHub tools via Function Calling.
142
+ - When asked to inspect a repository or account, use `github_get_user_profile`, `github_list_repositories`, `github_get_file_content`, or `github_list_commits`.
143
+ - When editing or updating code in files, use `github_get_file_content` first to retrieve the current content and `sha`, then call `github_create_or_update_file` with the latest `sha`.
144
+ - When asked to create branches, commits, pull requests, or issues, perform them sequentially using the respective GitHub tools.
145
+ - For repository creation, use `github_create_repository`.
 
 
146
 
147
  5. NATURAL CONVERSATION & TOOL RESPONSE STYLE:
148
  - Do NOT introduce your company, founder, or model name in general responses unless requested.
149
+ - Always summarize and format Google, Notion, and GitHub execution results into clean, polite, and natural language automatically matching the language used by the user.
150
  - Never output raw technical logs, IDs, or developer headers directly to the user."""
151
 
152
  TOOLS = [
 
465
  {
466
  "type": "function",
467
  "function": {
468
+ "name": "github_get_user_profile",
469
+ "description": "Get authenticated GitHub user profile or target user information",
470
  "parameters": {
471
  "type": "object",
472
  "properties": {
473
+ "username": {"type": "string", "description": "Optional GitHub username. If not specified, returns current authenticated user."}
474
  }
475
  }
476
  }
 
478
  {
479
  "type": "function",
480
  "function": {
481
+ "name": "github_list_repositories",
482
+ "description": "List repositories for the authenticated user or organization",
483
  "parameters": {
484
  "type": "object",
485
  "properties": {
486
+ "type": {"type": "string", "description": "Type of repos: all, owner, public, private, member", "default": "all"},
487
+ "sort": {"type": "string", "description": "Sort order: created, updated, pushed, full_name", "default": "updated"},
488
+ "per_page": {"type": "integer", "description": "Results per page, default 10"}
489
+ }
490
+ }
491
+ }
492
+ },
493
+ {
494
+ "type": "function",
495
+ "function": {
496
+ "name": "github_create_repository",
497
+ "description": "Create a new GitHub repository",
498
+ "parameters": {
499
+ "type": "object",
500
+ "properties": {
501
+ "name": {"type": "string", "description": "Repository name"},
502
+ "description": {"type": "string", "description": "Repository description"},
503
+ "private": {"type": "boolean", "description": "True for private repo, False for public", "default": False},
504
+ "auto_init": {"type": "boolean", "description": "Initialize with README", "default": True}
505
  },
506
+ "required": ["name"]
507
  }
508
  }
509
  },
510
  {
511
  "type": "function",
512
  "function": {
513
+ "name": "github_get_file_content",
514
+ "description": "Read file content from a GitHub repository",
515
  "parameters": {
516
  "type": "object",
517
  "properties": {
518
+ "owner": {"type": "string", "description": "Repository owner username or org"},
519
+ "repo": {"type": "string", "description": "Repository name"},
520
+ "path": {"type": "string", "description": "File path within repository (e.g. README.md or src/index.js)"},
521
+ "ref": {"type": "string", "description": "Branch, tag, or commit ref"}
522
  },
523
+ "required": ["owner", "repo", "path"]
524
  }
525
  }
526
  },
 
528
  "type": "function",
529
  "function": {
530
  "name": "github_create_or_update_file",
531
+ "description": "Create a new file or update an existing file in a GitHub repository",
532
  "parameters": {
533
  "type": "object",
534
  "properties": {
535
+ "owner": {"type": "string", "description": "Repository owner username or org"},
536
  "repo": {"type": "string", "description": "Repository name"},
537
+ "path": {"type": "string", "description": "File path within repository"},
538
+ "content": {"type": "string", "description": "Text content to save into the file"},
539
  "message": {"type": "string", "description": "Commit message"},
540
+ "branch": {"type": "string", "description": "Branch name to commit to"},
541
+ "sha": {"type": "string", "description": "Required when updating an existing file. Obtain via github_get_file_content."}
 
542
  },
543
+ "required": ["owner", "repo", "path", "content", "message"]
544
  }
545
  }
546
  },
 
548
  "type": "function",
549
  "function": {
550
  "name": "github_delete_file",
551
+ "description": "Delete a file from a GitHub repository",
552
  "parameters": {
553
  "type": "object",
554
  "properties": {
555
  "owner": {"type": "string", "description": "Repository owner"},
556
  "repo": {"type": "string", "description": "Repository name"},
557
  "path": {"type": "string", "description": "File path to delete"},
558
+ "message": {"type": "string", "description": "Commit message"},
559
+ "sha": {"type": "string", "description": "Blob SHA of the file to delete"},
560
+ "branch": {"type": "string", "description": "Branch name"}
561
  },
562
+ "required": ["owner", "repo", "path", "message", "sha"]
563
  }
564
  }
565
  },
 
567
  "type": "function",
568
  "function": {
569
  "name": "github_list_branches",
570
+ "description": "List branches in a GitHub repository",
571
  "parameters": {
572
  "type": "object",
573
  "properties": {
 
588
  "properties": {
589
  "owner": {"type": "string", "description": "Repository owner"},
590
  "repo": {"type": "string", "description": "Repository name"},
591
+ "branch_name": {"type": "string", "description": "Name for the new branch"},
592
  "from_branch": {"type": "string", "description": "Source branch name, default 'main'"}
593
  },
594
  "required": ["owner", "repo", "branch_name"]
 
599
  "type": "function",
600
  "function": {
601
  "name": "github_list_commits",
602
+ "description": "List commits for a GitHub repository",
603
  "parameters": {
604
  "type": "object",
605
  "properties": {
606
  "owner": {"type": "string", "description": "Repository owner"},
607
  "repo": {"type": "string", "description": "Repository name"},
608
+ "branch": {"type": "string", "description": "Branch name"},
609
+ "per_page": {"type": "integer", "description": "Commits per page, default 10"}
610
  },
611
  "required": ["owner", "repo"]
612
  }
 
615
  {
616
  "type": "function",
617
  "function": {
618
+ "name": "github_list_issues",
619
+ "description": "List issues in a GitHub repository",
620
  "parameters": {
621
  "type": "object",
622
  "properties": {
623
  "owner": {"type": "string", "description": "Repository owner"},
624
  "repo": {"type": "string", "description": "Repository name"},
625
+ "state": {"type": "string", "description": "open, closed, or all", "default": "open"}
626
  },
627
  "required": ["owner", "repo"]
628
  }
 
631
  {
632
  "type": "function",
633
  "function": {
634
+ "name": "github_create_issue",
635
+ "description": "Create a new issue in a GitHub repository",
636
  "parameters": {
637
  "type": "object",
638
  "properties": {
639
  "owner": {"type": "string", "description": "Repository owner"},
640
  "repo": {"type": "string", "description": "Repository name"},
641
+ "title": {"type": "string", "description": "Issue title"},
642
+ "body": {"type": "string", "description": "Issue body content"},
643
+ "labels": {"type": "array", "items": {"type": "string"}, "description": "List of label names"}
 
644
  },
645
+ "required": ["owner", "repo", "title"]
646
  }
647
  }
648
  },
649
  {
650
  "type": "function",
651
  "function": {
652
+ "name": "github_update_issue",
653
+ "description": "Update or close an existing issue in a GitHub repository",
654
  "parameters": {
655
  "type": "object",
656
  "properties": {
657
  "owner": {"type": "string", "description": "Repository owner"},
658
  "repo": {"type": "string", "description": "Repository name"},
659
+ "issue_number": {"type": "integer", "description": "Issue number"},
660
+ "state": {"type": "string", "description": "open or closed"},
661
+ "title": {"type": "string", "description": "New title"},
662
+ "body": {"type": "string", "description": "New body content"}
663
  },
664
+ "required": ["owner", "repo", "issue_number"]
665
  }
666
  }
667
  },
668
  {
669
  "type": "function",
670
  "function": {
671
+ "name": "github_create_issue_comment",
672
+ "description": "Add a comment to an issue or pull request",
673
  "parameters": {
674
  "type": "object",
675
  "properties": {
676
  "owner": {"type": "string", "description": "Repository owner"},
677
  "repo": {"type": "string", "description": "Repository name"},
678
+ "issue_number": {"type": "integer", "description": "Issue or Pull Request number"},
679
+ "body": {"type": "string", "description": "Comment text"}
680
  },
681
+ "required": ["owner", "repo", "issue_number", "body"]
682
  }
683
  }
684
  },
685
  {
686
  "type": "function",
687
  "function": {
688
+ "name": "github_list_pull_requests",
689
+ "description": "List pull requests in a GitHub repository",
690
  "parameters": {
691
  "type": "object",
692
  "properties": {
693
  "owner": {"type": "string", "description": "Repository owner"},
694
  "repo": {"type": "string", "description": "Repository name"},
695
+ "state": {"type": "string", "description": "open, closed, or all", "default": "open"}
 
 
 
696
  },
697
+ "required": ["owner", "repo"]
698
  }
699
  }
700
  },
701
  {
702
  "type": "function",
703
  "function": {
704
+ "name": "github_create_pull_request",
705
+ "description": "Create a new pull request in a GitHub repository",
706
  "parameters": {
707
  "type": "object",
708
  "properties": {
709
  "owner": {"type": "string", "description": "Repository owner"},
710
  "repo": {"type": "string", "description": "Repository name"},
711
+ "title": {"type": "string", "description": "Pull request title"},
712
+ "head": {"type": "string", "description": "The name of the branch where your changes are implemented"},
713
+ "base": {"type": "string", "description": "The name of the branch you want the changes pulled into, e.g. main", "default": "main"},
714
+ "body": {"type": "string", "description": "Pull request description"}
715
  },
716
+ "required": ["owner", "repo", "title", "head"]
717
  }
718
  }
719
  },
720
  {
721
  "type": "function",
722
  "function": {
723
+ "name": "github_merge_pull_request",
724
+ "description": "Merge a pull request in a GitHub repository",
725
  "parameters": {
726
  "type": "object",
727
  "properties": {
728
  "owner": {"type": "string", "description": "Repository owner"},
729
  "repo": {"type": "string", "description": "Repository name"},
730
+ "pull_number": {"type": "integer", "description": "Pull request number"},
731
+ "commit_title": {"type": "string", "description": "Optional title for the merge commit"},
732
+ "merge_method": {"type": "string", "description": "merge, squash, or rebase", "default": "merge"}
733
  },
734
+ "required": ["owner", "repo", "pull_number"]
735
+ }
736
+ }
737
+ },
738
+ {
739
+ "type": "function",
740
+ "function": {
741
+ "name": "github_search_repositories",
742
+ "description": "Search GitHub repositories by query keyword",
743
+ "parameters": {
744
+ "type": "object",
745
+ "properties": {
746
+ "query": {"type": "string", "description": "Search query string"},
747
+ "per_page": {"type": "integer", "description": "Results per page, default 10"}
748
+ },
749
+ "required": ["query"]
750
+ }
751
+ }
752
+ },
753
+ {
754
+ "type": "function",
755
+ "function": {
756
+ "name": "github_search_code",
757
+ "description": "Search code across GitHub repositories",
758
+ "parameters": {
759
+ "type": "object",
760
+ "properties": {
761
+ "query": {"type": "string", "description": "Search query string (e.g. 'repo:owner/repo filename:app.py' or 'function_name')"},
762
+ "per_page": {"type": "integer", "description": "Results per page, default 10"}
763
+ },
764
+ "required": ["query"]
765
  }
766
  }
767
  }
 
795
  pass
796
 
797
  async def get_token_from_supabase(user_id: str, service: str):
798
+ check_services = [service, "google", "gmail", "calendar", "drive"] if service in ["google", "gmail", "calendar", "drive"] else [service]
799
  for s in check_services:
800
  if (user_id, s) in user_tokens:
801
  return user_tokens[(user_id, s)]
 
1058
  except Exception as e:
1059
  return f"Error appending content to Notion: {str(e)}"
1060
 
1061
+ async def github_get_headers(user_id: str):
1062
+ token_data = await get_token_from_supabase(user_id, "github")
1063
+ if not token_data:
1064
+ return None
1065
+ access_token = token_data.get("access_token") or token_data.get("token")
1066
+ if not access_token:
1067
+ return None
1068
+ return {
1069
+ "Authorization": f"Bearer {access_token}",
1070
+ "Accept": "application/vnd.github+json",
1071
+ "X-GitHub-Api-Version": "2022-11-28",
1072
+ "User-Agent": "OpenSort-Clade"
1073
+ }
1074
+
1075
+ async def github_get_user_profile(user_id: str, username: str = None):
1076
+ headers = await github_get_headers(user_id)
1077
+ if not headers:
1078
+ return "GitHub is not connected. Please connect GitHub account."
1079
  try:
1080
+ url = f"https://api.github.com/users/{username}" if username else "https://api.github.com/user"
1081
+ async with httpx.AsyncClient() as c:
1082
+ res = await c.get(url, headers=headers)
1083
+ if res.status_code != 200:
1084
+ return f"Error fetching GitHub profile: {res.text}"
1085
+ data = res.json()
1086
+ login = data.get("login", "N/A")
1087
+ name = data.get("name", "N/A")
1088
+ public_repos = data.get("public_repos", 0)
1089
+ total_private_repos = data.get("total_private_repos", 0)
1090
+ followers = data.get("followers", 0)
1091
+ following = data.get("following", 0)
1092
+ html_url = data.get("html_url", "")
1093
+ return f"GitHub User: {login} ({name})\nPublic Repos: {public_repos} | Private Repos: {total_private_repos}\nFollowers: {followers} | Following: {following}\nURL: {html_url}"
1094
  except Exception as e:
1095
+ return f"Error fetching GitHub profile: {str(e)}"
1096
 
1097
+ async def github_list_repositories(user_id: str, type: str = "all", sort: str = "updated", per_page: int = 10):
1098
+ headers = await github_get_headers(user_id)
1099
+ if not headers:
1100
+ return "GitHub is not connected."
1101
  try:
1102
+ url = f"https://api.github.com/user/repos?type={type}&sort={sort}&per_page={per_page}"
1103
+ async with httpx.AsyncClient() as c:
1104
+ res = await c.get(url, headers=headers)
1105
+ if res.status_code != 200:
1106
+ return f"Error listing GitHub repositories: {res.text}"
1107
+ repos = res.json()
1108
+ if not repos:
1109
+ return "No repositories found."
1110
+ items = []
1111
+ for r in repos:
1112
+ name = r.get("full_name", "")
1113
+ is_private = "Private" if r.get("private") else "Public"
1114
+ stars = r.get("stargazers_count", 0)
1115
+ forks = r.get("forks_count", 0)
1116
+ lang = r.get("language") or "N/A"
1117
+ url_val = r.get("html_url", "")
1118
+ items.append(f"Repo: {name} [{is_private}] | Language: {lang} | Stars: {stars} | Forks: {forks} | URL: {url_val}")
1119
+ return "\n".join(items)
1120
  except Exception as e:
1121
+ return f"Error listing repositories: {str(e)}"
1122
 
1123
+ async def github_create_repository(user_id: str, name: str, description: str = "", private: bool = False, auto_init: bool = True):
1124
+ headers = await github_get_headers(user_id)
1125
+ if not headers:
1126
+ return "GitHub is not connected."
1127
  try:
1128
+ url = "https://api.github.com/user/repos"
1129
+ payload = {
1130
+ "name": name,
1131
+ "description": description,
1132
+ "private": private,
1133
+ "auto_init": auto_init
1134
+ }
1135
+ async with httpx.AsyncClient() as c:
1136
+ res = await c.post(url, headers=headers, json=payload)
1137
+ if res.status_code not in [200, 201]:
1138
+ return f"Error creating GitHub repository: {res.text}"
1139
+ data = res.json()
1140
+ return f"Successfully created repository '{data.get('full_name')}' ({data.get('html_url')})."
1141
  except Exception as e:
1142
+ return f"Error creating repository: {str(e)}"
1143
 
1144
+ async def github_get_file_content(user_id: str, owner: str, repo: str, path: str, ref: str = None):
1145
+ headers = await github_get_headers(user_id)
1146
+ if not headers:
1147
+ return "GitHub is not connected."
1148
  try:
1149
+ clean_path = path.lstrip("/")
1150
+ url = f"https://api.github.com/repos/{owner}/{repo}/contents/{clean_path}"
1151
+ if ref:
1152
+ url += f"?ref={ref}"
1153
+ async with httpx.AsyncClient() as c:
1154
+ res = await c.get(url, headers=headers)
1155
+ if res.status_code != 200:
1156
+ return f"Error reading file '{path}': {res.text}"
1157
+ data = res.json()
1158
+ if isinstance(data, list):
1159
+ items = [f"{item.get('type')}: {item.get('name')} (path: {item.get('path')})" for item in data]
1160
+ return f"Directory contents of {path}:\n" + "\n".join(items)
1161
+ sha = data.get("sha", "")
1162
+ raw_content = data.get("content", "")
1163
+ encoding = data.get("encoding", "")
1164
+ if encoding == "base64" and raw_content:
1165
+ decoded = base64.b64decode(raw_content).decode("utf-8", errors="replace")
1166
+ return f"SHA: {sha}\nPath: {path}\n\nContent:\n{decoded}"
1167
+ return f"SHA: {sha}\nPath: {path}\nContent: {raw_content}"
1168
  except Exception as e:
1169
+ return f"Error reading file: {str(e)}"
1170
 
1171
+ async def github_create_or_update_file(user_id: str, owner: str, repo: str, path: str, content: str, message: str, branch: str = None, sha: str = None):
1172
+ headers = await github_get_headers(user_id)
1173
+ if not headers:
1174
+ return "GitHub is not connected."
1175
  try:
1176
+ clean_path = path.lstrip("/")
1177
+ url = f"https://api.github.com/repos/{owner}/{repo}/contents/{clean_path}"
1178
+ b64_content = base64.b64encode(content.encode("utf-8")).decode("utf-8")
1179
+ payload = {
1180
+ "message": message,
1181
+ "content": b64_content
1182
+ }
1183
+ if branch:
1184
+ payload["branch"] = branch
1185
+ if sha:
1186
+ payload["sha"] = sha
1187
+ else:
1188
+ async with httpx.AsyncClient() as c:
1189
+ get_url = url if not branch else f"{url}?ref={branch}"
1190
+ check_res = await c.get(get_url, headers=headers)
1191
+ if check_res.status_code == 200:
1192
+ existing_sha = check_res.json().get("sha")
1193
+ if existing_sha:
1194
+ payload["sha"] = existing_sha
1195
+ async with httpx.AsyncClient() as c:
1196
+ res = await c.put(url, headers=headers, json=payload)
1197
+ if res.status_code not in [200, 201]:
1198
+ return f"Error saving file '{path}': {res.text}"
1199
+ res_data = res.json()
1200
+ commit_sha = res_data.get("commit", {}).get("sha", "")
1201
+ return f"Successfully saved '{path}' in repository {owner}/{repo}. Commit SHA: {commit_sha}"
1202
  except Exception as e:
1203
+ return f"Error saving file: {str(e)}"
1204
 
1205
+ async def github_delete_file(user_id: str, owner: str, repo: str, path: str, message: str, sha: str, branch: str = None):
1206
+ headers = await github_get_headers(user_id)
1207
+ if not headers:
1208
+ return "GitHub is not connected."
1209
  try:
1210
+ clean_path = path.lstrip("/")
1211
+ url = f"https://api.github.com/repos/{owner}/{repo}/contents/{clean_path}"
1212
+ payload = {
1213
+ "message": message,
1214
+ "sha": sha
1215
+ }
1216
+ if branch:
1217
+ payload["branch"] = branch
1218
+ async with httpx.AsyncClient() as c:
1219
+ req = c.build_request("DELETE", url, headers=headers, json=payload)
1220
+ res = await c.send(req)
1221
+ if res.status_code != 200:
1222
+ return f"Error deleting file '{path}': {res.text}"
1223
+ return f"Successfully deleted file '{path}' from repository {owner}/{repo}. "
 
1224
  except Exception as e:
1225
+ return f"Error deleting file: {str(e)}"
1226
 
1227
+ async def github_list_branches(user_id: str, owner: str, repo: str):
1228
+ headers = await github_get_headers(user_id)
1229
+ if not headers:
1230
+ return "GitHub is not connected."
1231
  try:
1232
+ url = f"https://api.github.com/repos/{owner}/{repo}/branches"
1233
+ async with httpx.AsyncClient() as c:
1234
+ res = await c.get(url, headers=headers)
1235
+ if res.status_code != 200:
1236
+ return f"Error listing branches: {res.text}"
1237
+ branches = res.json()
1238
+ if not branches:
1239
+ return "No branches found."
1240
+ items = [f"Branch: {b.get('name')} | Commit SHA: {b.get('commit', {}).get('sha')}" for b in branches]
1241
+ return "\n".join(items)
 
 
1242
  except Exception as e:
1243
+ return f"Error listing branches: {str(e)}"
1244
 
1245
+ async def github_create_branch(user_id: str, owner: str, repo: str, branch_name: str, from_branch: str = "main"):
1246
+ headers = await github_get_headers(user_id)
1247
+ if not headers:
1248
+ return "GitHub is not connected."
1249
+ try:
1250
+ async with httpx.AsyncClient() as c:
1251
+ ref_res = await c.get(f"https://api.github.com/repos/{owner}/{repo}/git/ref/heads/{from_branch}", headers=headers)
1252
+ if ref_res.status_code != 200:
1253
+ ref_res = await c.get(f"https://api.github.com/repos/{owner}/{repo}/git/ref/heads/master", headers=headers)
1254
+ if ref_res.status_code != 200:
1255
+ return f"Error getting base branch ref: {ref_res.text}"
1256
+ sha = ref_res.json().get("object", {}).get("sha")
1257
+ create_payload = {
1258
+ "ref": f"refs/heads/{branch_name}",
1259
+ "sha": sha
1260
+ }
1261
+ create_res = await c.post(f"https://api.github.com/repos/{owner}/{repo}/git/refs", headers=headers, json=create_payload)
1262
+ if create_res.status_code not in [200, 201]:
1263
+ return f"Error creating branch '{branch_name}': {create_res.text}"
1264
+ return f"Successfully created branch '{branch_name}' from SHA {sha}."
1265
+ except Exception as e:
1266
+ return f"Error creating branch: {str(e)}"
1267
+
1268
+ async def github_list_commits(user_id: str, owner: str, repo: str, branch: str = None, per_page: int = 10):
1269
+ headers = await github_get_headers(user_id)
1270
+ if not headers:
1271
+ return "GitHub is not connected."
1272
+ try:
1273
+ url = f"https://api.github.com/repos/{owner}/{repo}/commits?per_page={per_page}"
1274
+ if branch:
1275
+ url += f"&sha={branch}"
1276
+ async with httpx.AsyncClient() as c:
1277
+ res = await c.get(url, headers=headers)
1278
+ if res.status_code != 200:
1279
+ return f"Error listing commits: {res.text}"
1280
+ commits = res.json()
1281
+ if not commits:
1282
+ return "No commits found."
1283
+ items = []
1284
+ for cm in commits:
1285
+ sha_short = cm.get("sha", "")[:7]
1286
+ msg = cm.get("commit", {}).get("message", "").replace("\n", " ")
1287
+ author = cm.get("commit", {}).get("author", {}).get("name", "N/A")
1288
+ date_val = cm.get("commit", {}).get("author", {}).get("date", "N/A")
1289
+ items.append(f"Commit: {sha_short} | Msg: {msg} | Author: {author} | Date: {date_val}")
1290
+ return "\n".join(items)
1291
+ except Exception as e:
1292
+ return f"Error listing commits: {str(e)}"
1293
+
1294
+ async def github_list_issues(user_id: str, owner: str, repo: str, state: str = "open"):
1295
+ headers = await github_get_headers(user_id)
1296
+ if not headers:
1297
+ return "GitHub is not connected."
1298
+ try:
1299
+ url = f"https://api.github.com/repos/{owner}/{repo}/issues?state={state}"
1300
+ async with httpx.AsyncClient() as c:
1301
+ res = await c.get(url, headers=headers)
1302
+ if res.status_code != 200:
1303
+ return f"Error listing issues: {res.text}"
1304
+ issues = res.json()
1305
+ if not issues:
1306
+ return f"No {state} issues found in {owner}/{repo}."
1307
+ items = []
1308
+ for iss in issues:
1309
+ if "pull_request" in iss:
1310
+ continue
1311
+ num = iss.get("number")
1312
+ title = iss.get("title")
1313
+ st = iss.get("state")
1314
+ items.append(f"Issue #{num} [{st}]: {title}")
1315
+ return "\n".join(items) if items else f"No {state} issues found."
1316
+ except Exception as e:
1317
+ return f"Error listing issues: {str(e)}"
1318
+
1319
+ async def github_create_issue(user_id: str, owner: str, repo: str, title: str, body: str = "", labels: list = None):
1320
+ headers = await github_get_headers(user_id)
1321
+ if not headers:
1322
+ return "GitHub is not connected."
1323
+ try:
1324
+ url = f"https://api.github.com/repos/{owner}/{repo}/issues"
1325
+ payload = {"title": title, "body": body}
1326
+ if labels:
1327
+ payload["labels"] = labels
1328
+ async with httpx.AsyncClient() as c:
1329
+ res = await c.post(url, headers=headers, json=payload)
1330
+ if res.status_code not in [200, 201]:
1331
+ return f"Error creating issue: {res.text}"
1332
+ data = res.json()
1333
+ return f"Successfully created Issue #{data.get('number')} '{title}' ({data.get('html_url')})."
1334
+ except Exception as e:
1335
+ return f"Error creating issue: {str(e)}"
1336
+
1337
+ async def github_update_issue(user_id: str, owner: str, repo: str, issue_number: int, state: str = None, title: str = None, body: str = None):
1338
+ headers = await github_get_headers(user_id)
1339
+ if not headers:
1340
+ return "GitHub is not connected."
1341
+ try:
1342
+ url = f"https://api.github.com/repos/{owner}/{repo}/issues/{issue_number}"
1343
+ payload = {}
1344
+ if state: payload["state"] = state
1345
+ if title: payload["title"] = title
1346
+ if body: payload["body"] = body
1347
+ async with httpx.AsyncClient() as c:
1348
+ res = await c.patch(url, headers=headers, json=payload)
1349
+ if res.status_code != 200:
1350
+ return f"Error updating issue #{issue_number}: {res.text}"
1351
+ return f"Successfully updated Issue #{issue_number} in {owner}/{repo}."
1352
+ except Exception as e:
1353
+ return f"Error updating issue: {str(e)}"
1354
+
1355
+ async def github_create_issue_comment(user_id: str, owner: str, repo: str, issue_number: int, body: str):
1356
+ headers = await github_get_headers(user_id)
1357
+ if not headers:
1358
+ return "GitHub is not connected."
1359
+ try:
1360
+ url = f"https://api.github.com/repos/{owner}/{repo}/issues/{issue_number}/comments"
1361
+ payload = {"body": body}
1362
+ async with httpx.AsyncClient() as c:
1363
+ res = await c.post(url, headers=headers, json=payload)
1364
+ if res.status_code not in [200, 201]:
1365
+ return f"Error adding comment to issue #{issue_number}: {res.text}"
1366
+ return f"Successfully added comment to #{issue_number} in {owner}/{repo}."
1367
+ except Exception as e:
1368
+ return f"Error creating comment: {str(e)}"
1369
+
1370
+ async def github_list_pull_requests(user_id: str, owner: str, repo: str, state: str = "open"):
1371
+ headers = await github_get_headers(user_id)
1372
+ if not headers:
1373
+ return "GitHub is not connected."
1374
+ try:
1375
+ url = f"https://api.github.com/repos/{owner}/{repo}/pulls?state={state}"
1376
+ async with httpx.AsyncClient() as c:
1377
+ res = await c.get(url, headers=headers)
1378
+ if res.status_code != 200:
1379
+ return f"Error listing pull requests: {res.text}"
1380
+ prs = res.json()
1381
+ if not prs:
1382
+ return f"No {state} pull requests found in {owner}/{repo}."
1383
+ items = []
1384
+ for pr in prs:
1385
+ num = pr.get("number")
1386
+ title = pr.get("title")
1387
+ head_ref = pr.get("head", {}).get("ref")
1388
+ base_ref = pr.get("base", {}).get("ref")
1389
+ url_val = pr.get("html_url")
1390
+ items.append(f"PR #{num}: {title} ({head_ref} -> {base_ref}) | URL: {url_val}")
1391
+ return "\n".join(items)
1392
+ except Exception as e:
1393
+ return f"Error listing pull requests: {str(e)}"
1394
+
1395
+ async def github_create_pull_request(user_id: str, owner: str, repo: str, title: str, head: str, base: str = "main", body: str = ""):
1396
+ headers = await github_get_headers(user_id)
1397
+ if not headers:
1398
+ return "GitHub is not connected."
1399
+ try:
1400
+ url = f"https://api.github.com/repos/{owner}/{repo}/pulls"
1401
+ payload = {
1402
+ "title": title,
1403
+ "head": head,
1404
+ "base": base,
1405
+ "body": body
1406
+ }
1407
+ async with httpx.AsyncClient() as c:
1408
+ res = await c.post(url, headers=headers, json=payload)
1409
+ if res.status_code not in [200, 201]:
1410
+ return f"Error creating pull request: {res.text}"
1411
+ data = res.json()
1412
+ return f"Successfully created PR #{data.get('number')} '{title}' ({data.get('html_url')})."
1413
+ except Exception as e:
1414
+ return f"Error creating pull request: {str(e)}"
1415
+
1416
+ async def github_merge_pull_request(user_id: str, owner: str, repo: str, pull_number: int, commit_title: str = None, merge_method: str = "merge"):
1417
+ headers = await github_get_headers(user_id)
1418
+ if not headers:
1419
+ return "GitHub is not connected."
1420
+ try:
1421
+ url = f"https://api.github.com/repos/{owner}/{repo}/pulls/{pull_number}/merge"
1422
+ payload = {"merge_method": merge_method}
1423
+ if commit_title:
1424
+ payload["commit_title"] = commit_title
1425
+ async with httpx.AsyncClient() as c:
1426
+ res = await c.put(url, headers=headers, json=payload)
1427
+ if res.status_code != 200:
1428
+ return f"Error merging PR #{pull_number}: {res.text}"
1429
+ data = res.json()
1430
+ return f"Successfully merged PR #{pull_number}. Message: {data.get('message')}"
1431
+ except Exception as e:
1432
+ return f"Error merging pull request: {str(e)}"
1433
+
1434
+ async def github_search_repositories(user_id: str, query: str, per_page: int = 10):
1435
+ headers = await github_get_headers(user_id)
1436
+ if not headers:
1437
+ return "GitHub is not connected."
1438
+ try:
1439
+ url = f"https://api.github.com/search/repositories?q={urllib.parse.quote(query)}&per_page={per_page}"
1440
+ async with httpx.AsyncClient() as c:
1441
+ res = await c.get(url, headers=headers)
1442
+ if res.status_code != 200:
1443
+ return f"Error searching repositories: {res.text}"
1444
+ items = res.json().get("items", [])
1445
+ if not items:
1446
+ return "No repositories found matching the query."
1447
+ res_list = [f"Repo: {r.get('full_name')} | Stars: {r.get('stargazers_count')} | URL: {r.get('html_url')}" for r in items]
1448
+ return "\n".join(res_list)
1449
+ except Exception as e:
1450
+ return f"Error searching repositories: {str(e)}"
1451
+
1452
+ async def github_search_code(user_id: str, query: str, per_page: int = 10):
1453
+ headers = await github_get_headers(user_id)
1454
+ if not headers:
1455
+ return "GitHub is not connected."
1456
+ try:
1457
+ url = f"https://api.github.com/search/code?q={urllib.parse.quote(query)}&per_page={per_page}"
1458
+ async with httpx.AsyncClient() as c:
1459
+ res = await c.get(url, headers=headers)
1460
+ if res.status_code != 200:
1461
+ return f"Error searching code: {res.text}"
1462
+ items = res.json().get("items", [])
1463
+ if not items:
1464
+ return "No code matches found."
1465
+ res_list = [f"File: {item.get('name')} | Path: {item.get('path')} | Repo: {item.get('repository', {}).get('full_name')} | URL: {item.get('html_url')}" for item in items]
1466
+ return "\n".join(res_list)
1467
+ except Exception as e:
1468
+ return f"Error searching code: {str(e)}"
1469
+
1470
+ async def gmail_search_emails(user_id: str, query: str = "", max_results: int = 5):
1471
+ creds = await get_google_creds(user_id, "gmail")
1472
+ if not creds:
1473
+ return "Gmail is not connected. Please connect Google account."
1474
+ try:
1475
+ service = build("gmail", "v1", credentials=creds)
1476
+ q_str = query if query else ""
1477
+ results = service.users().messages().list(userId="me", q=q_str, maxResults=max_results).execute()
1478
+ messages = results.get("messages", [])
1479
+ if not messages:
1480
+ return "No emails found matching the query."
1481
+ email_list = []
1482
+ for msg in messages:
1483
+ detail = service.users().messages().get(userId="me", id=msg["id"], format="metadata", metadataHeaders=["Subject", "From", "Date"]).execute()
1484
+ headers = {h["name"]: h["value"] for h in detail.get("payload", {}).get("headers", [])}
1485
+ snippet = detail.get("snippet", "")
1486
+ email_list.append(f"Message ID: {msg['id']} | From: {headers.get('From', 'N/A')} | Subject: {headers.get('Subject', 'N/A')} | Date: {headers.get('Date', 'N/A')} | Snippet: {snippet}")
1487
+ return "\n".join(email_list)
1488
+ except Exception as e:
1489
+ return f"Error executing Gmail search: {str(e)}"
1490
+
1491
+ async def gmail_get_email_detail(user_id: str, message_id: str):
1492
+ creds = await get_google_creds(user_id, "gmail")
1493
+ if not creds:
1494
+ return "Gmail is not connected."
1495
+ try:
1496
+ service = build("gmail", "v1", credentials=creds)
1497
+ detail = service.users().messages().get(userId="me", id=message_id, format="full").execute()
1498
+ headers = {h["name"]: h["value"] for h in detail.get("payload", {}).get("headers", [])}
1499
+ snippet = detail.get("snippet", "")
1500
+ return f"From: {headers.get('From')}\nTo: {headers.get('To')}\nSubject: {headers.get('Subject')}\nDate: {headers.get('Date')}\nContent Snippet: {snippet}"
1501
+ except Exception as e:
1502
+ return f"Error getting email detail: {str(e)}"
1503
+
1504
+ async def gmail_create_draft(user_id: str, to: str, subject: str, body: str):
1505
+ creds = await get_google_creds(user_id, "gmail")
1506
+ if not creds:
1507
+ return "Gmail is not connected."
1508
+ try:
1509
+ service = build("gmail", "v1", credentials=creds)
1510
+ msg = EmailMessage()
1511
+ msg.set_content(body)
1512
+ msg["To"] = to
1513
+ msg["Subject"] = subject
1514
+ raw = base64.urlsafe_b64encode(msg.as_bytes()).decode()
1515
+ draft = service.users().drafts().create(userId="me", body={"message": {"raw": raw}}).execute()
1516
+ return f"Successfully created draft to {to} with Subject: '{subject}' (Draft ID: {draft.get('id')})."
1517
+ except Exception as e:
1518
+ return f"Error creating draft: {str(e)}"
1519
+
1520
+ async def gmail_send_email(user_id: str, to: str, subject: str, body: str):
1521
+ creds = await get_google_creds(user_id, "gmail")
1522
+ if not creds:
1523
+ return "Gmail is not connected."
1524
+ try:
1525
+ service = build("gmail", "v1", credentials=creds)
1526
+ msg = EmailMessage()
1527
+ msg.set_content(body)
1528
+ msg["To"] = to
1529
+ msg["Subject"] = subject
1530
+ raw = base64.urlsafe_b64encode(msg.as_bytes()).decode()
1531
+ res = service.users().messages().send(userId="me", body={"raw": raw}).execute()
1532
+ return f"Successfully sent email to {to} with Subject: '{subject}' (Message ID: {res.get('id')})."
1533
+ except Exception as e:
1534
+ return f"Error sending email: {str(e)}"
1535
+
1536
+ async def gmail_delete_email(user_id: str, message_id: str):
1537
+ creds = await get_google_creds(user_id, "gmail")
1538
+ if not creds:
1539
+ return "Gmail is not connected."
1540
+ try:
1541
+ service = build("gmail", "v1", credentials=creds)
1542
+ try:
1543
+ service.users().messages().delete(userId="me", id=message_id).execute()
1544
+ except Exception:
1545
+ service.users().messages().trash(userId="me", id=message_id).execute()
1546
+ return f"Successfully deleted email with ID: {message_id}."
1547
+ except Exception as e:
1548
+ return f"Error deleting email: {str(e)}"
1549
+
1550
+ async def gmail_delete_draft(user_id: str, draft_id: str = None, query: str = None):
1551
+ creds = await get_google_creds(user_id, "gmail")
1552
+ if not creds:
1553
+ return "Gmail is not connected."
1554
+ try:
1555
+ service = build("gmail", "v1", credentials=creds)
1556
+ target_id = draft_id
1557
+ if not target_id and query:
1558
+ drafts_res = service.users().drafts().list(userId="me").execute()
1559
+ drafts = drafts_res.get("drafts", [])
1560
+ for d in drafts:
1561
+ detail = service.users().drafts().get(userId="me", id=d["id"]).execute()
1562
+ snippet = detail.get("message", {}).get("snippet", "")
1563
+ if query.lower() in snippet.lower():
1564
+ target_id = d["id"]
1565
+ break
1566
+ if not target_id:
1567
+ return f"No matching draft found for query: {query}"
1568
+ service.users().drafts().delete(userId="me", id=target_id).execute()
1569
+ return f"Successfully deleted draft with ID: {target_id}."
1570
+ except Exception as e:
1571
+ return f"Error deleting draft: {str(e)}"
1572
+
1573
+ async def calendar_list_events(user_id: str, max_results: int = 10):
1574
+ creds = await get_google_creds(user_id, "calendar")
1575
+ if not creds:
1576
+ return "Google Calendar is not connected."
1577
+ try:
1578
+ service = build("calendar", "v3", credentials=creds)
1579
+ events_result = service.events().list(calendarId="primary", maxResults=max_results, singleEvents=True, orderBy="startTime").execute()
1580
+ events = events_result.get("items", [])
1581
+ if not events:
1582
+ return "No upcoming events found in Google Calendar."
1583
+ event_list = []
1584
+ for event in events:
1585
+ start = event["start"].get("dateTime", event["start"].get("date"))
1586
+ end = event["end"].get("dateTime", event["end"].get("date"))
1587
+ summary = event.get("summary", "No Title")
1588
+ event_list.append(f"Event ID: {event['id']} | Title: {summary} | Start: {start} | End: {end}")
1589
+ return "\n".join(event_list)
1590
+ except Exception as e:
1591
+ return f"Error listing calendar events: {str(e)}"
1592
+
1593
+ async def calendar_create_event(user_id: str, summary: str, start_time: str, end_time: str, description: str = "", location: str = ""):
1594
  creds = await get_google_creds(user_id, "calendar")
1595
  if not creds:
1596
  return "Google Calendar is not connected."
 
1716
  except Exception as e:
1717
  return f"Error updating Drive file: {str(e)}"
1718
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1719
  async def execute_tool_call(user_id: str, func_name: str, args: dict) -> str:
1720
  if func_name == "gmail_search_emails":
1721
  return await gmail_search_emails(user_id, args.get("query", ""), args.get("max_results", 5))
 
1759
  return await notion_delete_page(user_id, args.get("page_id", ""))
1760
  elif func_name == "notion_append_block_children":
1761
  return await notion_append_block_children(user_id, args.get("page_id", ""), args.get("content", ""))
1762
+ elif func_name == "github_get_user_profile":
1763
+ return await github_get_user_profile(user_id, args.get("username"))
1764
+ elif func_name == "github_list_repositories":
1765
+ return await github_list_repositories(user_id, args.get("type", "all"), args.get("sort", "updated"), args.get("per_page", 10))
1766
+ elif func_name == "github_create_repository":
1767
+ return await github_create_repository(user_id, args.get("name", ""), args.get("description", ""), args.get("private", False), args.get("auto_init", True))
1768
+ elif func_name == "github_get_file_content":
1769
+ return await github_get_file_content(user_id, args.get("owner", ""), args.get("repo", ""), args.get("path", ""), args.get("ref"))
1770
  elif func_name == "github_create_or_update_file":
1771
+ return await github_create_or_update_file(user_id, args.get("owner", ""), args.get("repo", ""), args.get("path", ""), args.get("content", ""), args.get("message", ""), args.get("branch"), args.get("sha"))
1772
  elif func_name == "github_delete_file":
1773
+ return await github_delete_file(user_id, args.get("owner", ""), args.get("repo", ""), args.get("path", ""), args.get("message", ""), args.get("sha", ""), args.get("branch"))
1774
  elif func_name == "github_list_branches":
1775
  return await github_list_branches(user_id, args.get("owner", ""), args.get("repo", ""))
1776
  elif func_name == "github_create_branch":
1777
  return await github_create_branch(user_id, args.get("owner", ""), args.get("repo", ""), args.get("branch_name", ""), args.get("from_branch", "main"))
1778
  elif func_name == "github_list_commits":
1779
+ return await github_list_commits(user_id, args.get("owner", ""), args.get("repo", ""), args.get("branch"), args.get("per_page", 10))
1780
+ elif func_name == "github_list_issues":
1781
+ return await github_list_issues(user_id, args.get("owner", ""), args.get("repo", ""), args.get("state", "open"))
1782
+ elif func_name == "github_create_issue":
1783
+ return await github_create_issue(user_id, args.get("owner", ""), args.get("repo", ""), args.get("title", ""), args.get("body", ""), args.get("labels"))
1784
+ elif func_name == "github_update_issue":
1785
+ return await github_update_issue(user_id, args.get("owner", ""), args.get("repo", ""), args.get("issue_number", 0), args.get("state"), args.get("title"), args.get("body"))
1786
+ elif func_name == "github_create_issue_comment":
1787
+ return await github_create_issue_comment(user_id, args.get("owner", ""), args.get("repo", ""), args.get("issue_number", 0), args.get("body", ""))
1788
  elif func_name == "github_list_pull_requests":
1789
  return await github_list_pull_requests(user_id, args.get("owner", ""), args.get("repo", ""), args.get("state", "open"))
1790
  elif func_name == "github_create_pull_request":
1791
  return await github_create_pull_request(user_id, args.get("owner", ""), args.get("repo", ""), args.get("title", ""), args.get("head", ""), args.get("base", "main"), args.get("body", ""))
1792
  elif func_name == "github_merge_pull_request":
1793
+ return await github_merge_pull_request(user_id, args.get("owner", ""), args.get("repo", ""), args.get("pull_number", 0), args.get("commit_title"), args.get("merge_method", "merge"))
1794
+ elif func_name == "github_search_repositories":
1795
+ return await github_search_repositories(user_id, args.get("query", ""), args.get("per_page", 10))
1796
+ elif func_name == "github_search_code":
1797
+ return await github_search_code(user_id, args.get("query", ""), args.get("per_page", 10))
 
 
 
 
1798
  return "Unknown tool function."
1799
 
1800
  def count_tokens(messages):