-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1309 lines (1116 loc) · 43.6 KB
/
main.py
File metadata and controls
1309 lines (1116 loc) · 43.6 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
"""
Linear Integration App for Omi
This app provides Linear integration through OAuth authentication
and chat tools for managing issues, projects, and workflows.
"""
import os
import base64
import urllib.parse
from datetime import datetime
from typing import Optional, Dict, Any, List
import requests
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request, Query
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from db import (
store_linear_tokens,
get_linear_tokens,
delete_linear_tokens,
is_token_expired,
store_default_team,
get_default_team,
get_user_settings,
)
from models import (
ChatToolResponse,
LinearIssue,
LinearTeam,
LinearProject,
LinearComment,
LinearUser,
WorkflowState,
)
load_dotenv()
# Linear API Configuration
LINEAR_CLIENT_ID = os.getenv("LINEAR_CLIENT_ID", "")
LINEAR_CLIENT_SECRET = os.getenv("LINEAR_CLIENT_SECRET", "")
LINEAR_REDIRECT_URI = os.getenv("LINEAR_REDIRECT_URI", "http://localhost:8000/auth/linear/callback")
# Linear API endpoints
LINEAR_AUTH_URL = "https://linear.app/oauth/authorize"
LINEAR_TOKEN_URL = "https://api.linear.app/oauth/token"
LINEAR_API_URL = "https://api.linear.app/graphql"
# Required Linear scopes
LINEAR_SCOPES = [
"read",
"write",
"issues:create",
"comments:create",
]
app = FastAPI(
title="Linear Omi Integration",
description="Linear integration for Omi - Manage issues, projects, and workflows with voice",
version="1.0.0"
)
# Mount static files and templates
templates_dir = os.path.join(os.path.dirname(__file__), "templates")
if os.path.exists(templates_dir):
static_dir = os.path.join(templates_dir, "static")
if os.path.exists(static_dir):
app.mount("/static", StaticFiles(directory=static_dir), name="static")
templates = Jinja2Templates(directory=templates_dir)
# ============================================
# Helper Functions
# ============================================
def get_auth_header(access_token: str) -> Dict[str, str]:
"""Get authorization header for Linear API requests."""
return {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
}
def refresh_access_token(refresh_token: str) -> Optional[Dict[str, Any]]:
"""Refresh the Linear access token."""
response = requests.post(
LINEAR_TOKEN_URL,
headers={"Content-Type": "application/x-www-form-urlencoded"},
data={
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"client_id": LINEAR_CLIENT_ID,
"client_secret": LINEAR_CLIENT_SECRET,
},
)
if response.status_code == 200:
return response.json()
return None
def get_valid_access_token(uid: str) -> Optional[str]:
"""Get a valid access token, refreshing if necessary."""
tokens = get_linear_tokens(uid)
if not tokens:
return None
if is_token_expired(uid):
# Refresh the token
new_tokens = refresh_access_token(tokens["refresh_token"])
if new_tokens:
expires_at = int(datetime.utcnow().timestamp()) + new_tokens.get("expires_in", 315360000)
store_linear_tokens(
uid,
new_tokens["access_token"],
new_tokens.get("refresh_token", tokens["refresh_token"]),
expires_at
)
return new_tokens["access_token"]
return None
return tokens["access_token"]
def linear_graphql_request(
uid: str,
query: str,
variables: Optional[Dict] = None
) -> Dict[str, Any]:
"""Make an authenticated GraphQL request to Linear API."""
access_token = get_valid_access_token(uid)
if not access_token:
return {"error": "User not authenticated with Linear"}
headers = get_auth_header(access_token)
try:
response = requests.post(
LINEAR_API_URL,
headers=headers,
json={"query": query, "variables": variables or {}}
)
if response.status_code >= 400:
error_data = response.json() if response.content else {}
errors = error_data.get("errors", [])
if errors:
return {"error": errors[0].get("message", f"API error: {response.status_code}")}
return {"error": f"API error: {response.status_code}"}
result = response.json()
if "errors" in result:
return {"error": result["errors"][0].get("message", "GraphQL error")}
return result.get("data", {})
except requests.RequestException as e:
return {"error": f"Request failed: {str(e)}"}
def get_user_teams(uid: str) -> List[LinearTeam]:
"""Get teams the user belongs to."""
query = """
query {
teams {
nodes {
id
name
key
description
}
}
}
"""
result = linear_graphql_request(uid, query)
if "error" in result:
return []
teams = []
for team in result.get("teams", {}).get("nodes", []):
teams.append(LinearTeam(
id=team["id"],
name=team["name"],
key=team["key"],
description=team.get("description") or ""
))
return teams
def get_team_states(uid: str, team_id: str) -> List[WorkflowState]:
"""Get workflow states for a team."""
query = """
query($teamId: String!) {
team(id: $teamId) {
states {
nodes {
id
name
type
color
position
}
}
}
}
"""
result = linear_graphql_request(uid, query, {"teamId": team_id})
if "error" in result:
return []
states = []
for state in result.get("team", {}).get("states", {}).get("nodes", []):
states.append(WorkflowState(
id=state["id"],
name=state["name"],
type=state["type"],
color=state.get("color", "#888"),
position=state.get("position", 0)
))
return sorted(states, key=lambda s: s.position)
def find_state_by_name(uid: str, team_id: str, state_name: str) -> Optional[WorkflowState]:
"""Find a workflow state by name (case-insensitive partial match)."""
states = get_team_states(uid, team_id)
state_name_lower = state_name.lower()
# Map common names to Linear state types
state_mapping = {
"backlog": "backlog",
"todo": "unstarted",
"to do": "unstarted",
"to-do": "unstarted",
"in progress": "started",
"in-progress": "started",
"working": "started",
"doing": "started",
"done": "completed",
"complete": "completed",
"completed": "completed",
"finished": "completed",
"cancelled": "canceled",
"canceled": "canceled",
}
# First try exact match
for state in states:
if state.name.lower() == state_name_lower:
return state
# Then try partial match
for state in states:
if state_name_lower in state.name.lower():
return state
# Then try type match
mapped_type = state_mapping.get(state_name_lower)
if mapped_type:
for state in states:
if state.type == mapped_type:
return state
return None
def get_user_profile(uid: str) -> Optional[LinearUser]:
"""Get the authenticated user's profile."""
query = """
query {
viewer {
id
name
email
displayName
avatarUrl
}
}
"""
result = linear_graphql_request(uid, query)
if "error" in result or not result.get("viewer"):
return None
viewer = result["viewer"]
return LinearUser(
id=viewer["id"],
name=viewer["name"],
email=viewer.get("email", ""),
display_name=viewer.get("displayName", viewer["name"]),
avatar_url=viewer.get("avatarUrl")
)
# ============================================
# OAuth Endpoints
# ============================================
@app.get("/", response_class=HTMLResponse)
async def home(request: Request, uid: Optional[str] = None):
"""Home page / App settings page."""
if not uid:
return templates.TemplateResponse("setup.html", {
"request": request,
"authenticated": False,
"error": "Missing user ID"
})
tokens = get_linear_tokens(uid)
authenticated = tokens is not None
# Get user profile if authenticated
user_profile = None
teams = []
default_team = None
if authenticated:
user_profile = get_user_profile(uid)
teams = get_user_teams(uid)
default_team = get_default_team(uid)
return templates.TemplateResponse("setup.html", {
"request": request,
"uid": uid,
"authenticated": authenticated,
"user_profile": user_profile,
"teams": teams,
"default_team": default_team,
"oauth_url": f"/auth/linear?uid={uid}"
})
@app.get("/auth/linear")
async def linear_auth(uid: str):
"""Initiate Linear OAuth flow."""
if not uid:
raise HTTPException(status_code=400, detail="User ID is required")
params = {
"client_id": LINEAR_CLIENT_ID,
"response_type": "code",
"redirect_uri": LINEAR_REDIRECT_URI,
"scope": ",".join(LINEAR_SCOPES),
"state": uid,
"prompt": "consent",
}
auth_url = f"{LINEAR_AUTH_URL}?{urllib.parse.urlencode(params)}"
return RedirectResponse(url=auth_url)
@app.get("/auth/linear/callback", response_class=HTMLResponse)
async def linear_callback(request: Request, code: str = None, state: str = None, error: str = None):
"""Handle Linear OAuth callback."""
if error:
return templates.TemplateResponse("setup.html", {
"request": request,
"authenticated": False,
"error": f"Authorization failed: {error}"
})
if not code or not state:
return templates.TemplateResponse("setup.html", {
"request": request,
"authenticated": False,
"error": "Invalid callback parameters"
})
uid = state
# Exchange code for tokens
response = requests.post(
LINEAR_TOKEN_URL,
headers={"Content-Type": "application/x-www-form-urlencoded"},
data={
"grant_type": "authorization_code",
"code": code,
"redirect_uri": LINEAR_REDIRECT_URI,
"client_id": LINEAR_CLIENT_ID,
"client_secret": LINEAR_CLIENT_SECRET,
},
)
if response.status_code != 200:
return templates.TemplateResponse("setup.html", {
"request": request,
"authenticated": False,
"error": "Failed to exchange authorization code"
})
token_data = response.json()
# Linear tokens are long-lived (10 years), but we set a reasonable expiry
expires_at = int(datetime.utcnow().timestamp()) + token_data.get("expires_in", 315360000)
store_linear_tokens(
uid,
token_data["access_token"],
token_data.get("refresh_token", ""),
expires_at
)
# Redirect to home with uid
return RedirectResponse(url=f"/?uid={uid}")
@app.get("/setup/linear", tags=["setup"])
async def check_setup(uid: str):
"""Check if the user has completed Linear setup (used by Omi)."""
tokens = get_linear_tokens(uid)
return {"is_setup_completed": tokens is not None}
@app.post("/settings/default-team")
async def set_default_team(uid: str, team_id: str, team_name: str):
"""Set the default team for a user."""
store_default_team(uid, team_id, team_name)
return {"success": True, "message": f"Default team set to: {team_name}"}
@app.get("/disconnect")
async def disconnect_linear(uid: str):
"""Disconnect Linear account."""
delete_linear_tokens(uid)
return RedirectResponse(url=f"/?uid={uid}")
# ============================================
# Chat Tool Endpoints
# ============================================
@app.post("/tools/create_issue", tags=["chat_tools"], response_model=ChatToolResponse)
async def tool_create_issue(request: Request):
"""
Create a new issue in Linear.
Chat tool for Omi - creates issues with title, description, and priority.
"""
try:
body = await request.json()
uid = body.get("uid")
title = body.get("title", "")
description = body.get("description", "")
priority = body.get("priority") # 0 = No priority, 1 = Urgent, 2 = High, 3 = Medium, 4 = Low
team_id = body.get("team_id")
if not uid:
return ChatToolResponse(error="User ID is required")
if not title:
return ChatToolResponse(error="Issue title is required")
# Check authentication
if not get_linear_tokens(uid):
return ChatToolResponse(error="Please connect your Linear account first in the app settings.")
# Get team ID if not provided
if not team_id:
default = get_default_team(uid)
if default:
team_id = default["id"]
else:
# Use first team
teams = get_user_teams(uid)
if not teams:
return ChatToolResponse(error="No teams found in your Linear workspace.")
team_id = teams[0].id
# Map priority text to number
priority_map = {
"urgent": 1,
"high": 2,
"medium": 3,
"normal": 3,
"low": 4,
"none": 0,
}
if isinstance(priority, str):
priority = priority_map.get(priority.lower(), 0)
# Create the issue
mutation = """
mutation CreateIssue($input: IssueCreateInput!) {
issueCreate(input: $input) {
success
issue {
id
identifier
title
url
state {
name
}
}
}
}
"""
variables = {
"input": {
"teamId": team_id,
"title": title,
}
}
if description:
variables["input"]["description"] = description
if priority:
variables["input"]["priority"] = priority
result = linear_graphql_request(uid, mutation, variables)
if "error" in result:
return ChatToolResponse(error=f"Failed to create issue: {result['error']}")
issue_data = result.get("issueCreate", {})
if not issue_data.get("success"):
return ChatToolResponse(error="Failed to create issue")
issue = issue_data.get("issue", {})
identifier = issue.get("identifier", "")
url = issue.get("url", "")
state_name = issue.get("state", {}).get("name", "Unknown")
return ChatToolResponse(
result=f"✅ Created issue **{identifier}**: {title}\n\n"
f"Status: {state_name}\n"
f"🔗 {url}"
)
except Exception as e:
return ChatToolResponse(error=f"Failed to create issue: {str(e)}")
@app.post("/tools/list_my_issues", tags=["chat_tools"], response_model=ChatToolResponse)
async def tool_list_my_issues(request: Request):
"""
List issues assigned to the user.
Chat tool for Omi - shows the user's assigned issues.
"""
try:
body = await request.json()
uid = body.get("uid")
limit = body.get("limit", 10)
status_filter = body.get("status") # Optional: filter by status
if not uid:
return ChatToolResponse(error="User ID is required")
# Check authentication
if not get_linear_tokens(uid):
return ChatToolResponse(error="Please connect your Linear account first in the app settings.")
# Build filter
filter_clause = '{ assignee: { isMe: { eq: true } } }'
if status_filter:
status_lower = status_filter.lower()
state_types = {
"backlog": "backlog",
"todo": "unstarted",
"in progress": "started",
"done": "completed",
"cancelled": "canceled",
}
state_type = state_types.get(status_lower)
if state_type:
filter_clause = f'{{ assignee: {{ isMe: {{ eq: true }} }}, state: {{ type: {{ eq: "{state_type}" }} }} }}'
query = f"""
query {{
issues(first: {limit}, filter: {filter_clause}, orderBy: updatedAt) {{
nodes {{
id
identifier
title
priority
state {{
name
type
}}
url
updatedAt
}}
}}
}}
"""
result = linear_graphql_request(uid, query)
if "error" in result:
return ChatToolResponse(error=f"Failed to get issues: {result['error']}")
issues = result.get("issues", {}).get("nodes", [])
if not issues:
filter_msg = f" with status '{status_filter}'" if status_filter else ""
return ChatToolResponse(result=f"📋 No issues assigned to you{filter_msg}.")
# Format results with priority indicators
priority_icons = {0: "⚪", 1: "🔴", 2: "🟠", 3: "🟡", 4: "🔵"}
results = []
for issue in issues:
priority_icon = priority_icons.get(issue.get("priority", 0), "⚪")
state = issue.get("state", {}).get("name", "Unknown")
results.append(
f"{priority_icon} **{issue['identifier']}** - {issue['title']}\n"
f" └ Status: {state}"
)
return ChatToolResponse(
result=f"📋 Your assigned issues:\n\n" + "\n\n".join(results)
)
except Exception as e:
return ChatToolResponse(error=f"Failed to list issues: {str(e)}")
@app.post("/tools/list_recent_issues", tags=["chat_tools"], response_model=ChatToolResponse)
async def tool_list_recent_issues(request: Request):
"""
List recent issues in Linear workspace.
Chat tool for Omi - shows recent issues regardless of assignee.
"""
try:
body = await request.json()
uid = body.get("uid")
limit = body.get("limit", 5)
team_key = body.get("team") # Optional: filter by team key like "OMI", "ENG"
if not uid:
return ChatToolResponse(error="User ID is required")
# Check authentication
if not get_linear_tokens(uid):
return ChatToolResponse(error="Please connect your Linear account first in the app settings.")
# Build query - get recent issues ordered by created date
if team_key:
query = f"""
query {{
issues(first: {limit}, orderBy: createdAt, filter: {{ team: {{ key: {{ eq: "{team_key.upper()}" }} }} }}) {{
nodes {{
id
identifier
title
priority
state {{
name
}}
assignee {{
name
}}
createdAt
url
}}
}}
}}
"""
else:
query = f"""
query {{
issues(first: {limit}, orderBy: createdAt) {{
nodes {{
id
identifier
title
priority
state {{
name
}}
assignee {{
name
}}
createdAt
url
}}
}}
}}
"""
result = linear_graphql_request(uid, query)
if "error" in result:
return ChatToolResponse(error=f"Failed to get issues: {result['error']}")
issues = result.get("issues", {}).get("nodes", [])
if not issues:
return ChatToolResponse(result=f"📋 No recent issues found in Linear.")
# Format results with priority indicators
priority_icons = {0: "⚪", 1: "🔴", 2: "🟠", 3: "🟡", 4: "🔵"}
results = []
for issue in issues:
priority_icon = priority_icons.get(issue.get("priority", 0), "⚪")
state = issue.get("state", {}).get("name", "Unknown")
assignee = issue.get("assignee", {})
assignee_name = assignee.get("name", "Unassigned") if assignee else "Unassigned"
results.append(
f"{priority_icon} **{issue['identifier']}** - {issue['title']}\n"
f" └ {state} • {assignee_name}"
)
team_msg = f" in {team_key.upper()}" if team_key else ""
return ChatToolResponse(
result=f"📋 Latest {len(issues)} issues{team_msg} in Linear:\n\n" + "\n\n".join(results)
)
except Exception as e:
return ChatToolResponse(error=f"Failed to list issues: {str(e)}")
@app.post("/tools/update_issue_status", tags=["chat_tools"], response_model=ChatToolResponse)
async def tool_update_issue_status(request: Request):
"""
Update the status of an issue.
Chat tool for Omi - moves issues between workflow states.
"""
try:
body = await request.json()
uid = body.get("uid")
issue_identifier = body.get("issue_identifier", "") # e.g., "ENG-123"
new_status = body.get("new_status", "") # e.g., "In Progress", "Done"
if not uid:
return ChatToolResponse(error="User ID is required")
if not issue_identifier:
return ChatToolResponse(error="Issue identifier is required (e.g., ENG-123)")
if not new_status:
return ChatToolResponse(error="New status is required (e.g., 'In Progress', 'Done')")
# Check authentication
if not get_linear_tokens(uid):
return ChatToolResponse(error="Please connect your Linear account first in the app settings.")
# Search for the issue by identifier using searchIssues
search_query = """
query($term: String!) {
searchIssues(term: $term, first: 1) {
nodes {
id
identifier
title
team {
id
}
}
}
}
"""
result = linear_graphql_request(uid, search_query, {
"term": issue_identifier.upper()
})
if "error" in result:
return ChatToolResponse(error=f"Failed to find issue: {result['error']}")
issues = result.get("searchIssues", {}).get("nodes", [])
if not issues:
return ChatToolResponse(error=f"Could not find issue: {issue_identifier}")
issue = issues[0]
team_id = issue["team"]["id"]
issue_id = issue["id"]
# Find the target state
target_state = find_state_by_name(uid, team_id, new_status)
if not target_state:
states = get_team_states(uid, team_id)
state_names = [s.name for s in states]
return ChatToolResponse(
error=f"Could not find status '{new_status}'. Available states: {', '.join(state_names)}"
)
# Update the issue
mutation = """
mutation UpdateIssue($id: String!, $input: IssueUpdateInput!) {
issueUpdate(id: $id, input: $input) {
success
issue {
id
identifier
title
state {
name
}
url
}
}
}
"""
result = linear_graphql_request(uid, mutation, {
"id": issue_id,
"input": {"stateId": target_state.id}
})
if "error" in result:
return ChatToolResponse(error=f"Failed to update issue: {result['error']}")
update_data = result.get("issueUpdate", {})
if not update_data.get("success"):
return ChatToolResponse(error="Failed to update issue status")
updated_issue = update_data.get("issue", {})
new_state = updated_issue.get("state", {}).get("name", target_state.name)
return ChatToolResponse(
result=f"✅ Updated **{issue['identifier']}** to **{new_state}**\n\n"
f"{issue['title']}"
)
except Exception as e:
return ChatToolResponse(error=f"Failed to update issue: {str(e)}")
@app.post("/tools/search_issues", tags=["chat_tools"], response_model=ChatToolResponse)
async def tool_search_issues(request: Request):
"""
Search for issues in Linear.
Chat tool for Omi - searches issues by text query.
"""
try:
body = await request.json()
uid = body.get("uid")
query_text = body.get("query", "")
limit = body.get("limit", 5)
if not uid:
return ChatToolResponse(error="User ID is required")
if not query_text:
return ChatToolResponse(error="Search query is required")
# Check authentication
if not get_linear_tokens(uid):
return ChatToolResponse(error="Please connect your Linear account first in the app settings.")
query = """
query($term: String!, $first: Int!) {
searchIssues(term: $term, first: $first) {
nodes {
id
identifier
title
priority
state {
name
}
assignee {
name
}
url
}
}
}
"""
result = linear_graphql_request(uid, query, {
"term": query_text,
"first": limit
})
if "error" in result:
# Fall back to filter-based search
filter_query = """
query($filter: IssueFilter!, $first: Int!) {
issues(filter: $filter, first: $first) {
nodes {
id
identifier
title
priority
state {
name
}
assignee {
name
}
url
}
}
}
"""
result = linear_graphql_request(uid, filter_query, {
"filter": {"title": {"containsIgnoreCase": query_text}},
"first": limit
})
if "error" in result:
return ChatToolResponse(error=f"Search failed: {result['error']}")
issues = result.get("issues", {}).get("nodes", [])
else:
issues = result.get("searchIssues", {}).get("nodes", [])
if not issues:
return ChatToolResponse(result=f"🔍 No issues found for '{query_text}'")
# Format results
priority_icons = {0: "⚪", 1: "🔴", 2: "🟠", 3: "🟡", 4: "🔵"}
results = []
for i, issue in enumerate(issues, 1):
priority_icon = priority_icons.get(issue.get("priority", 0), "⚪")
state = issue.get("state", {}).get("name", "Unknown")
assignee = issue.get("assignee", {})
assignee_name = assignee.get("name", "Unassigned") if assignee else "Unassigned"
results.append(
f"{i}. {priority_icon} **{issue['identifier']}** - {issue['title']}\n"
f" └ {state} • Assigned to: {assignee_name}"
)
return ChatToolResponse(
result=f"🔍 Found {len(issues)} issue(s) for '{query_text}':\n\n" + "\n\n".join(results)
)
except Exception as e:
return ChatToolResponse(error=f"Search failed: {str(e)}")
@app.post("/tools/get_issue", tags=["chat_tools"], response_model=ChatToolResponse)
async def tool_get_issue(request: Request):
"""
Get details of a specific issue.
Chat tool for Omi - retrieves full issue details.
"""
try:
body = await request.json()
uid = body.get("uid")
issue_identifier = body.get("issue_identifier", "")
if not uid:
return ChatToolResponse(error="User ID is required")
if not issue_identifier:
return ChatToolResponse(error="Issue identifier is required (e.g., ENG-123)")
# Check authentication
if not get_linear_tokens(uid):
return ChatToolResponse(error="Please connect your Linear account first in the app settings.")
query = """
query($term: String!) {
searchIssues(term: $term, first: 1) {
nodes {
id
identifier
title
description
priority
estimate
state {
name
type
}
assignee {
name
}
creator {
name
}
team {
name
}
project {
name
}
labels {
nodes {
name
}
}
url
createdAt
updatedAt
}
}
}
"""
result = linear_graphql_request(uid, query, {
"term": issue_identifier.upper()
})
if "error" in result:
return ChatToolResponse(error=f"Failed to get issue: {result['error']}")
issues = result.get("searchIssues", {}).get("nodes", [])
if not issues:
return ChatToolResponse(error=f"Could not find issue: {issue_identifier}")
issue = issues[0]
# Format the issue details
priority_map = {0: "No priority", 1: "🔴 Urgent", 2: "🟠 High", 3: "🟡 Medium", 4: "🔵 Low"}
priority = priority_map.get(issue.get("priority", 0), "No priority")