forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapps.py
More file actions
2475 lines (2015 loc) · 95.7 KB
/
Copy pathapps.py
File metadata and controls
2475 lines (2015 loc) · 95.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import logging
import os
import time
from html import escape
from datetime import datetime, timezone
import httpx
from typing import List, Optional
from urllib.parse import urlparse
from pydantic import BaseModel as PydanticBaseModel, ConfigDict, Field, ValidationError
from ulid import ULID
from fastapi import APIRouter, Body, Depends, Form, UploadFile, File, HTTPException, Header, Query
from fastapi.responses import HTMLResponse
from langchain_core.messages import SystemMessage, HumanMessage
from utils.apps import _clamp_review_score, fetch_app_chat_tools_from_manifest
from utils.executors import (
critical_executor,
db_executor,
llm_executor,
storage_executor,
run_blocking,
start_background_task,
)
from utils.http_client import get_webhook_client
from utils.multipart import APP_IMAGE_MAX_PART_SIZE, MultipartMaxPartSizeRoute, max_part_size
from utils.mcp_client import (
discover_oauth_metadata,
register_oauth_client,
build_authorization_url,
exchange_oauth_code,
refresh_oauth_token,
discover_mcp_tools,
fetch_brandfetch_logo,
generate_state_token,
parse_state_token,
generate_pkce_pair,
)
from database.apps import (
change_app_approval_status,
get_unapproved_public_apps_db,
get_app_by_id_db,
add_app_to_db,
update_app_in_db,
delete_app_from_db,
update_app_visibility_in_db,
get_personas_by_username_db,
get_persona_by_id_db,
delete_persona_db,
get_persona_by_twitter_handle_db,
get_persona_by_username_db,
migrate_app_owner_id_db,
get_user_persona_by_uid,
get_omi_persona_apps_by_uid_db,
create_api_key_db,
list_api_keys_db,
delete_api_key_db,
set_app_popular_db,
search_apps_db,
)
from database.webhook_health import clear_app_webhook_health
from database.auth import get_user_from_uid
from database.redis_db import (
get_generic_cache,
set_generic_cache,
get_specific_user_review,
increase_app_installs_count,
decrease_app_installs_count,
enable_app,
disable_app,
is_app_enabled,
delete_app_cache_by_id,
save_username,
get_enabled_apps,
get_conversation_summary_app_ids,
add_conversation_summary_app_id,
remove_conversation_summary_app_id,
get_apps_installs_count,
get_apps_reviews,
)
from utils.apps import (
get_available_apps,
get_available_app_by_id,
get_approved_available_apps,
invalidate_approved_apps_cache,
invalidate_popular_apps_cache,
get_available_app_by_id_with_reviews,
set_app_review,
get_app_reviews,
add_tester,
is_tester,
add_app_access_for_tester,
remove_app_access_for_tester,
upsert_app_payment_link,
get_is_user_paid_app,
is_permit_payment_plan_get,
generate_persona_prompt,
generate_persona_desc,
get_persona_by_uid,
increment_username,
generate_api_key,
get_popular_apps,
paginate_apps,
build_pagination_metadata,
get_capabilities_list,
normalize_app_numeric_fields,
filter_apps_by_capability,
sort_apps_by_installs,
group_apps_by_capability,
build_capability_groups_response,
group_capability_apps_by_category,
build_capability_category_groups_response,
validate_app_endpoints_for_reenable,
)
from database.memories import migrate_memories
from utils.llm.persona import generate_persona_intro_message
from utils.llm.app_generator import generate_description, generate_description_and_emoji
from utils.llm.app_generation_prompts import app_generation_prompts_from_llm_payload, app_generation_prompts_response
from utils.subscription import enforce_chat_quota
from utils.llm.usage_tracker import track_usage, Features
from utils.notifications import send_notification, send_app_review_reply_notification, send_new_app_review_notification
from utils.other import endpoints as auth
from utils.request_validation import (
backfill_app_home_url_from_auth_steps,
normalize_required_webhook_url,
parse_form_json,
)
from models.app import (
App,
ActionType,
AppCreate,
AppUpdate,
AppBaseModel,
AppReview,
AppCatalogItem,
)
from utils.other.storage import upload_app_logo, delete_app_logo, upload_app_thumbnail, get_app_thumbnail_url
from utils.social import (
get_twitter_profile,
verify_latest_tweet,
upsert_persona_from_twitter_profile,
add_twitter_to_persona,
)
logger = logging.getLogger(__name__)
router = APIRouter(route_class=MultipartMaxPartSizeRoute)
class AppSelectOption(PydanticBaseModel):
title: str
id: str
class AppCapabilityAction(AppSelectOption):
doc_url: Optional[str] = None
description: Optional[str] = None
class AppCapabilityResponse(AppSelectOption):
triggers: List[AppSelectOption] = Field(default_factory=list)
actions: List[AppCapabilityAction] = Field(default_factory=list)
scopes: List[AppSelectOption] = Field(default_factory=list)
class AppThumbnailUploadResponse(PydanticBaseModel):
thumbnail_url: str
thumbnail_id: str
class AppMutationResponse(PydanticBaseModel):
status: str
class AppStatusMessageResponse(AppMutationResponse):
message: str
class AppManifestRefreshResponse(AppMutationResponse):
tools_count: int = 0
class AppCreateResponse(AppMutationResponse):
app_id: str
class AppMigrationResponse(AppMutationResponse):
message: str
class McpAddServerResponse(PydanticBaseModel):
app_id: str
requires_oauth: bool
auth_url: Optional[str] = None
tools_count: Optional[int] = None
tool_names: List[str] = Field(default_factory=list)
class McpRefreshToolsResponse(PydanticBaseModel):
tools_count: int
tool_names: List[str] = Field(default_factory=list)
class AppTesterCheckResponse(PydanticBaseModel):
is_tester: bool
class UnapprovedPublicAppResponse(PydanticBaseModel):
model_config = ConfigDict(extra='allow')
id: Optional[str] = None
name: Optional[str] = None
uid: Optional[str] = None
private: Optional[bool] = None
approved: Optional[bool] = None
status: Optional[str] = None
category: Optional[str] = None
author: Optional[str] = None
description: Optional[str] = None
image: Optional[str] = None
capabilities: List[str] = Field(default_factory=list)
class AppDescriptionGenerationResponse(PydanticBaseModel):
description: str
class AppDescriptionEmojiGenerationResponse(PydanticBaseModel):
description: str
emoji: str
class AppPromptsGenerationResponse(PydanticBaseModel):
prompts: List[str]
class AppDraftGenerationResponse(PydanticBaseModel):
name: str
description: str
category: str
capabilities: List[str]
chat_prompt: Optional[str] = None
memory_prompt: Optional[str] = None
class AppGenerationResponse(PydanticBaseModel):
status: str
app: AppDraftGenerationResponse
class AppIconGenerationResponse(PydanticBaseModel):
status: str
icon_base64: str
mime_type: str
class AppPaginationLinks(PydanticBaseModel):
next: Optional[str] = None
previous: Optional[str] = None
class AppPagination(PydanticBaseModel):
total: int
count: int
offset: int
limit: int
hasNext: bool
hasPrevious: bool
links: Optional[AppPaginationLinks] = None
class AppCatalogGroup(PydanticBaseModel):
capability: Optional[AppSelectOption] = None
category: Optional[AppSelectOption] = None
data: List[AppCatalogItem] = Field(default_factory=list)
pagination: Optional[AppPagination] = None
count: Optional[int] = None
class AppCatalogMeta(PydanticBaseModel):
capabilities: List[AppSelectOption] = Field(default_factory=list)
groupCount: int = 0
limit: Optional[int] = None
offset: Optional[int] = None
totalApps: Optional[int] = None
class AppCatalogResponse(PydanticBaseModel):
data: List[AppCatalogItem] = Field(default_factory=list)
pagination: Optional[AppPagination] = None
capability: Optional[AppSelectOption] = None
category: Optional[AppSelectOption] = None
groups: List[AppCatalogGroup] = Field(default_factory=list)
meta: Optional[AppCatalogMeta] = None
class AppSearchFilters(PydanticBaseModel):
query: Optional[str] = None
category: Optional[str] = None
rating: Optional[float] = None
capability: Optional[str] = None
sort: str
my_apps: Optional[bool] = None
installed_apps: Optional[bool] = None
class AppSearchResponse(PydanticBaseModel):
data: List[AppCatalogItem] = Field(default_factory=list)
pagination: AppPagination
filters: AppSearchFilters
class AppApiKeyResponse(PydanticBaseModel):
id: str
label: str
created_at: Optional[datetime] = None
secret: Optional[str] = None
class PersonaMutationResponse(AppMutationResponse):
app_id: str
username: str
class TwitterProfileResponse(PydanticBaseModel):
name: str
profile: str
rest_id: str
avatar: str
desc: str
friends: int
sub_count: int
id: str
status: str
persona_id: Optional[str] = None
persona_username: Optional[str] = None
class TwitterOwnershipVerificationResponse(PydanticBaseModel):
tweet: str
verified: bool
persona_id: Optional[str] = None
class TwitterInitialMessageResponse(PydanticBaseModel):
message: str
class ConversationSummaryAppIdsResponse(PydanticBaseModel):
app_ids: List[str] = Field(default_factory=list)
class PersonaRecordResponse(App):
doc_id: Optional[str] = None
# ******************************************************
# ******************* REQUEST MODELS *******************
# ******************************************************
class ReviewAppRequest(PydanticBaseModel):
score: float
review: Optional[str] = None
username: Optional[str] = None
response: Optional[str] = None
class ReplyToReviewRequest(PydanticBaseModel):
reviewer_uid: str
response: str
class GenerateDescriptionRequest(PydanticBaseModel):
name: str
description: str
class GenerateDescriptionEmojiRequest(PydanticBaseModel):
name: str
prompt: str
class GenerateAppRequest(PydanticBaseModel):
prompt: str = ''
class GenerateAppIconRequest(PydanticBaseModel):
name: str = ''
description: str = ''
category: str = 'other'
class AddTesterRequest(PydanticBaseModel):
model_config = ConfigDict(extra='allow')
uid: str
apps: List[str]
class TesterAccessRequest(PydanticBaseModel):
uid: str
app_id: str
def _write_file(path: str, data: bytes):
"""Write bytes to file — offloaded to storage_executor."""
with open(path, 'wb') as f:
f.write(data)
def _process_chat_tools_manifest(external_integration: dict, app_dict: dict) -> dict:
"""Fetch and process chat tools manifest, updating and returning app_dict.
Fetches the manifest from chat_tools_manifest_url, resolves relative endpoints
to absolute URLs using app_home_url, and stores chat_messages config.
Args:
external_integration: The external_integration dict from app data
app_dict: The app dict to update with chat_tools and chat_messages config
Returns:
The updated app_dict
"""
manifest_url = external_integration.get('chat_tools_manifest_url')
if not manifest_url:
return app_dict
manifest_result = fetch_app_chat_tools_from_manifest(manifest_url)
if not manifest_result:
return app_dict
fetched_tools = manifest_result.get('tools')
if fetched_tools:
# Resolve relative endpoints to absolute URLs
base_url = (external_integration.get('app_home_url') or '').rstrip('/')
if base_url:
for tool in fetched_tools:
endpoint = tool.get('endpoint', '')
if endpoint.startswith('/') and not endpoint.startswith('//'):
tool['endpoint'] = f"{base_url}{endpoint}"
app_dict['chat_tools'] = fetched_tools
# Store chat_messages config in external_integration
chat_messages = manifest_result.get('chat_messages')
if 'external_integration' not in app_dict:
app_dict['external_integration'] = {}
if chat_messages:
app_dict['external_integration']['chat_messages_enabled'] = chat_messages.get('enabled', False)
app_dict['external_integration']['chat_messages_target'] = chat_messages.get('target', 'app')
app_dict['external_integration']['chat_messages_notify'] = chat_messages.get('notify', False)
else:
# Reset all chat_messages fields to defaults when not in manifest
app_dict['external_integration']['chat_messages_enabled'] = False
app_dict['external_integration']['chat_messages_target'] = 'app'
app_dict['external_integration']['chat_messages_notify'] = False
return app_dict
def _get_categories():
return [
{'title': 'Popular', 'id': 'popular'},
{'title': 'Conversation Analysis', 'id': 'conversation-analysis'},
{'title': 'Personality Clone', 'id': 'personality-emulation'},
{'title': 'Health', 'id': 'health-and-wellness'},
{'title': 'Education', 'id': 'education-and-learning'},
{'title': 'Communication', 'id': 'communication-improvement'},
{'title': 'Emotional Support', 'id': 'emotional-and-mental-support'},
{'title': 'Productivity', 'id': 'productivity-and-organization'},
{'title': 'Entertainment', 'id': 'entertainment-and-fun'},
{'title': 'Financial', 'id': 'financial'},
{'title': 'Travel', 'id': 'travel-and-exploration'},
{'title': 'Safety', 'id': 'safety-and-security'},
{'title': 'Shopping', 'id': 'shopping-and-commerce'},
{'title': 'Social', 'id': 'social-and-relationships'},
{'title': 'News', 'id': 'news-and-information'},
{'title': 'Utilities', 'id': 'utilities-and-tools'},
{'title': 'Other', 'id': 'other'},
]
# ******************************************************
# ********************* APPS CRUD **********************
# ******************************************************
@router.get('/v1/apps', tags=['v1'], response_model=List[AppBaseModel])
def get_apps(uid: str = Depends(auth.get_current_user_uid), include_reviews: bool = True):
apps = get_available_apps(uid, include_reviews=include_reviews)
return [normalize_app_numeric_fields(app.to_reduced_dict()) for app in apps]
@router.get('/v1/apps/enabled', tags=['v1'], response_model=List[str])
def get_user_enabled_apps(uid: str = Depends(auth.get_current_user_uid)):
"""Returns the list of app IDs the user has enabled/installed."""
return get_enabled_apps(uid)
@router.get('/v2/apps', tags=['v2'], response_model=AppCatalogResponse)
def get_apps_v2(
capability: str | None = Query(default=None, description='Filter by capability id'),
category: str | None = Query(default=None, description='Filter by category id'),
offset: int = Query(default=0, ge=0),
limit: int = Query(default=20, ge=1, le=100),
include_reviews: bool = Query(default=False),
):
"""Public omi apps, paginated by capability groups.
Notes:
- Uses approved public apps only (no private/tester apps).
- Groups: Popular, Integrations, Chat Assistants, Summary Apps, Realtime Notifications.
- Popular section is shown first.
- Always excludes persona type apps.
"""
capabilities = get_capabilities_list()
if capability:
cache_key = f"apps:capability:v2:{capability}:offset={offset}:limit={limit}:reviews={int(include_reviews)}"
elif category:
cache_key = f"apps:category:v2:{category}:offset={offset}:limit={limit}:reviews={int(include_reviews)}"
else:
cache_key = f"apps:capability_groups:v2:offset={offset}:limit={limit}:reviews={int(include_reviews)}"
cached = get_generic_cache(cache_key)
if cached:
return cached
# Fetch and filter approved public apps
apps = get_approved_available_apps(include_reviews=include_reviews)
approved_apps = [a for a in apps if a.approved and (a.private is None or not a.private)]
# Always exclude persona type apps
approved_apps = [a for a in approved_apps if not a.is_a_persona()]
# Capability-specific response
if capability:
filtered_apps = filter_apps_by_capability(approved_apps, capability)
sorted_apps = sort_apps_by_installs(filtered_apps)
page = paginate_apps(sorted_apps, offset, limit)
res = {
'data': [normalize_app_numeric_fields(app.to_reduced_dict()) for app in page],
'pagination': build_pagination_metadata(len(sorted_apps), offset, limit, capability),
'capability': {
'id': capability,
'title': next(
(c['title'] for c in capabilities if c['id'] == capability), capability.title().replace('_', ' ')
),
},
}
set_generic_cache(cache_key, res, ttl=60 * 10)
return res
if category:
filtered_apps = [app for app in approved_apps if app.category == category]
sorted_apps = sort_apps_by_installs(filtered_apps)
page = paginate_apps(sorted_apps, offset, limit)
categories = _get_categories()
res = {
'data': [normalize_app_numeric_fields(app.to_reduced_dict()) for app in page],
'pagination': build_pagination_metadata(len(sorted_apps), offset, limit, category),
'category': {
'id': category,
'title': next(
(c['title'] for c in categories if c['id'] == category), category.title().replace('-', ' ')
),
},
}
set_generic_cache(cache_key, res, ttl=60 * 10)
return res
# Grouped response by capability
grouped_apps = group_apps_by_capability(approved_apps, capabilities)
groups = build_capability_groups_response(grouped_apps, capabilities, offset, limit)
res = {
'groups': groups,
'meta': {
'capabilities': capabilities,
'groupCount': len(groups),
'limit': limit,
'offset': offset,
},
}
set_generic_cache(cache_key, res, ttl=60 * 10)
return res
@router.get('/v2/apps/capability/{capability_id}/grouped', tags=['v2'], response_model=AppCatalogResponse)
def get_capability_apps_grouped_by_category(
capability_id: str,
include_reviews: bool = Query(default=True),
):
"""Get all apps for a specific capability, grouped by master category.
Returns apps grouped into master categories like:
- For chat: Personality Clones, Productivity & Lifestyle, Social & Entertainment
- For others: Productivity & Tools, Personal & Lifestyle, Social & Entertainment
"""
cache_key = f"apps:capability:{capability_id}:grouped:reviews={int(include_reviews)}"
cached = get_generic_cache(cache_key)
if cached:
return cached
capabilities = get_capabilities_list()
# Fetch and filter approved public apps
apps = get_approved_available_apps(include_reviews=include_reviews)
approved_apps = [a for a in apps if a.approved and (a.private is None or not a.private)]
# Always exclude persona type apps
approved_apps = [a for a in approved_apps if not a.is_a_persona()]
# Filter apps by capability
filtered_apps = filter_apps_by_capability(approved_apps, capability_id)
# Group filtered apps by master category
grouped_apps = group_capability_apps_by_category(filtered_apps, capability_id)
groups = build_capability_category_groups_response(grouped_apps, capability_id)
res = {
'groups': groups,
'capability': {
'id': capability_id,
'title': next(
(c['title'] for c in capabilities if c['id'] == capability_id),
capability_id.title().replace('_', ' '),
),
},
'meta': {
'totalApps': len(filtered_apps),
'groupCount': len(groups),
},
}
set_generic_cache(cache_key, res, ttl=60 * 10)
return res
def _matches_search_text(app: App, query: str) -> bool:
"""Whether `app` matches a lowercased search query.
Name *or* description — the contract the `q` parameter documents, and the same fields the
clients' offline fallback ranks over (desktop `appRanking.ts`). Matching the name alone made
the remote endpoint strictly narrower than that fallback: an app found offline by a word in
its description returned "No apps found" once the endpoint answered.
"""
return query in app.name.lower() or query in (app.description or '').lower()
def _name_match_tier(app: App, query: str) -> int:
"""Relevance tier for a search hit: 0 exact name, 1 name prefix, 2 matched elsewhere.
Mirrors `nameMatchTier` in the desktop client so both orderings agree.
"""
name = app.name.lower()
if name == query:
return 0
if name.startswith(query):
return 1
return 2
@router.get('/v2/apps/search', tags=['v2'], response_model=AppSearchResponse)
def search_apps(
q: str | None = Query(default=None, description='Search query for app name or description'),
category: str | None = Query(default=None, description='Filter by category id'),
rating: float | None = Query(default=None, ge=0, le=5, description='Minimum rating filter'),
capability: str | None = Query(default=None, description='Filter by capability id'),
sort: str | None = Query(
default=None, description='Sort order: installs, rating_asc, rating_desc, name_asc, name_desc'
),
my_apps: bool | None = Query(default=None, description='Filter to show only user\'s apps'),
installed_apps: bool | None = Query(default=None, description='Filter to show only installed/enabled apps'),
offset: int = Query(default=0, ge=0),
limit: int = Query(default=20, ge=1, le=100),
uid: str = Depends(auth.get_current_user_uid),
):
"""Search and filter apps with pagination.
Returns a flat list of apps matching the search and filter criteria.
"""
enabled_app_ids = None
if installed_apps:
enabled_app_ids = list(get_enabled_apps(uid))
apps_data = search_apps_db(
uid=uid,
category=category,
capability=capability,
my_apps=my_apps or False,
installed_apps=installed_apps or False,
enabled_app_ids=enabled_app_ids,
)
user_enabled = set(get_enabled_apps(uid))
# Drop any malformed record missing an id before enrichment: id drives the installs/reviews/
# enabled lookups below and the pre-loop app_ids list, so a missing id would KeyError before the
# per-record ValidationError guard can catch it.
valid_apps_data = [a for a in apps_data if a.get('id')]
skipped_no_id = len(apps_data) - len(valid_apps_data)
if skipped_no_id:
logger.warning("Skipping %d malformed app record(s) without an id in search results", skipped_no_id)
apps_data = valid_apps_data
app_ids = [app['id'] for app in apps_data]
apps_installs = get_apps_installs_count(app_ids)
apps_reviews = get_apps_reviews(app_ids)
apps = []
for app_dict in apps_data:
app_dict['enabled'] = app_dict['id'] in user_enabled
app_dict['rejected'] = app_dict.get('approved') is False
app_dict['installs'] = apps_installs.get(app_dict['id'], 0)
# Calculate average from reviews
reviews = apps_reviews.get(app_dict['id'], {})
scores = [_clamp_review_score(x['score']) for x in reviews.values()]
app_dict['rating_avg'] = sum(scores) / len(scores) if scores else None
app_dict['rating_count'] = len(scores)
# Skip a malformed/legacy app document rather than 500 the whole search page.
try:
apps.append(App(**app_dict))
except ValidationError as e:
logger.warning(
"Skipping malformed app %s in search results: %s",
app_dict.get('id'),
[err['loc'][0] for err in e.errors() if err.get('loc')],
)
# Always exclude persona type apps from results
filtered_apps = [app for app in apps if not app.is_a_persona()]
# Apply text search filter
if q and q.strip():
search_query = q.strip().lower()
filtered_apps = [app for app in filtered_apps if _matches_search_text(app, search_query)]
# Apply rating filter
if rating is not None:
filtered_apps = [app for app in filtered_apps if (app.rating_avg or 0) >= rating]
# Apply sorting
if sort == 'rating_desc':
filtered_apps = sorted(filtered_apps, key=lambda a: (a.rating_avg or 0), reverse=True)
elif sort == 'rating_asc':
filtered_apps = sorted(filtered_apps, key=lambda a: (a.rating_avg or 0))
elif sort == 'name_asc':
filtered_apps = sorted(filtered_apps, key=lambda a: a.name.lower())
elif sort == 'name_desc':
filtered_apps = sorted(filtered_apps, key=lambda a: a.name.lower(), reverse=True)
elif sort == 'installs_desc':
filtered_apps = sorted(filtered_apps, key=lambda a: (a.installs or 0), reverse=True)
else:
# sort by installs when searching, otherwise by name
if q and q.strip():
search_query = q.strip().lower()
# Name matches rank above description-only matches before popularity: results are
# paginated, so an exact-name app must not be pushed off page 1 by a more-installed
# app that only mentions the query in its description.
filtered_apps = sorted(filtered_apps, key=lambda a: (_name_match_tier(a, search_query), -(a.installs or 0)))
else:
filtered_apps = sorted(filtered_apps, key=lambda a: a.name.lower())
# Paginate results
total = len(filtered_apps)
page = paginate_apps(filtered_apps, offset, limit)
return {
'data': [normalize_app_numeric_fields(app.to_reduced_dict()) for app in page],
'pagination': build_pagination_metadata(total, offset, limit),
'filters': {
'query': q,
'category': category,
'rating': rating,
'capability': capability,
'sort': sort or 'name',
'my_apps': my_apps,
'installed_apps': installed_apps,
},
}
@router.get('/v1/approved-apps', tags=['v1'], response_model=List[AppBaseModel])
def get_approved_apps(include_reviews: bool = False):
apps = get_approved_available_apps(include_reviews=include_reviews)
# Always exclude persona type apps
filtered_apps = [app for app in apps if not app.is_a_persona()]
return [normalize_app_numeric_fields(app.to_reduced_dict()) for app in filtered_apps]
@router.get('/v1/apps/popular', tags=['v1'], response_model=List[AppBaseModel])
def get_popular_apps_endpoint(uid: str = Depends(auth.get_current_user_uid)):
apps = get_popular_apps()
# Always exclude persona type apps
filtered_apps = [app for app in apps if not app.is_a_persona()]
return [normalize_app_numeric_fields(app.to_reduced_dict()) for app in filtered_apps]
@router.post('/v1/apps', tags=['v1'], response_model=AppCreateResponse)
@max_part_size(APP_IMAGE_MAX_PART_SIZE)
def create_app(app_data: str = Form(...), file: UploadFile = File(...), uid=Depends(auth.get_current_user_uid)):
data = parse_form_json(dict, app_data, 'app_data')
data['approved'] = False
data['status'] = 'under-review'
data['name'] = (data.get('name') or '').strip()
data['id'] = str(ULID())
data['uid'] = uid
if not data.get('author') and not data.get('email'):
user = get_user_from_uid(uid) or {}
email = user.get('email')
# author is required + non-null on AppCreate; display_name/email can both be null.
data['author'] = user.get('display_name') or (email.split('@')[0] if email else None) or 'Anonymous'
data['email'] = email
if not data.get('is_paid'):
data['is_paid'] = False
else:
if data['is_paid'] is True:
if data.get('price') is None:
raise HTTPException(status_code=422, detail='App price is required')
if data.get('price') < 0.0:
raise HTTPException(status_code=422, detail='Price cannot be a negative value')
if data.get('payment_plan') is None:
raise HTTPException(status_code=422, detail='Payment plan is required')
if external_integration := data.get('external_integration'):
if external_integration.get('triggers_on') is None and len(external_integration.get('actions', [])) == 0:
raise HTTPException(status_code=422, detail='Triggers on or actions is required')
# Trigger on
if external_integration.get('triggers_on'):
normalize_required_webhook_url(external_integration)
if external_integration.get('setup_instructions_file_path'):
external_integration['setup_instructions_file_path'] = external_integration[
'setup_instructions_file_path'
].strip()
if external_integration['setup_instructions_file_path'].startswith('http'):
external_integration['is_instructions_url'] = True
else:
external_integration['is_instructions_url'] = False
# Actions
if actions := external_integration.get('actions'):
for action in actions:
if not action.get('action'):
raise HTTPException(status_code=422, detail='Action field is required for each action')
if action.get('action') not in [action_type.value for action_type in ActionType]:
raise HTTPException(
status_code=422,
detail=f'Unsupported action type. Supported types: {", ".join([action_type.value for action_type in ActionType])}',
)
os.makedirs('_temp/apps', exist_ok=True)
file_path = f"_temp/apps/{file.filename}"
with open(file_path, 'wb') as f:
f.write(file.file.read())
img_url = upload_app_logo(file_path, data['id'])
data['image'] = img_url
data['created_at'] = datetime.now(timezone.utc)
# Backward compatibility: Set app_home_url from first auth step if not provided
if 'external_integration' in data:
backfill_app_home_url_from_auth_steps(data['external_integration'])
try:
app = AppCreate.model_validate(data)
except ValidationError as e:
raise HTTPException(status_code=422, detail=str(e))
# Build app dict
app_dict = app.model_dump(exclude_unset=True)
# Fetch chat tools from manifest URL (only way to add chat tools)
if external_integration := data.get('external_integration'):
app_dict = _process_chat_tools_manifest(external_integration, app_dict)
add_app_to_db(app_dict)
# payment link
upsert_app_payment_link(app.id, app.is_paid, app.price, app.payment_plan, app.uid)
return {'status': 'ok', 'app_id': app.id}
@router.post('/v1/personas', tags=['v1'], response_model=PersonaMutationResponse)
@max_part_size(APP_IMAGE_MAX_PART_SIZE)
async def create_persona(
persona_data: str = Form(...), file: UploadFile = File(...), uid=Depends(auth.get_current_user_uid)
):
data = parse_form_json(dict, persona_data, 'persona_data')
data['approved'] = False
data['status'] = 'under-review'
data['category'] = 'personality-emulation'
data['name'] = (data.get('name') or '').strip()
data['id'] = str(ULID())
data['uid'] = uid
data['capabilities'] = ['persona']
user = await run_blocking(db_executor, get_user_from_uid, uid) or {}
data['author'] = user.get('display_name', '')
data['email'] = user.get('email')
if 'username' not in data or data['username'] == '' or data['username'] is None:
data['username'] = data['name'].replace(' ', '').lower()
data['username'] = await run_blocking(db_executor, increment_username, data['username'])
await run_blocking(db_executor, save_username, data['username'], uid)
if 'connected_accounts' not in data or data['connected_accounts'] is None:
data['connected_accounts'] = ['omi']
data['persona_prompt'] = await generate_persona_prompt(uid, data)
data['description'] = await run_blocking(llm_executor, generate_persona_desc, uid, data['name'])
os.makedirs('_temp/apps', exist_ok=True)
file_path = f"_temp/apps/{file.filename}"
contents = await file.read()
await run_blocking(storage_executor, _write_file, file_path, contents)
img_url = await run_blocking(storage_executor, upload_app_logo, file_path, data['id'])
data['image'] = img_url
data['created_at'] = datetime.now(timezone.utc)
try:
app_create = AppCreate.model_validate(data)
except ValidationError as e:
raise HTTPException(status_code=422, detail=str(e))
await run_blocking(db_executor, add_app_to_db, app_create.model_dump(exclude_unset=True))
return {'status': 'ok', 'app_id': data['id'], 'username': data['username']}
@router.patch('/v1/personas/{persona_id}', tags=['v1'], response_model=PersonaMutationResponse)
@max_part_size(APP_IMAGE_MAX_PART_SIZE)
async def update_persona(
persona_id: str,
persona_data: str = Form(...),
file: UploadFile = File(None),
uid=Depends(auth.get_current_user_uid),
):
data = parse_form_json(dict, persona_data, 'persona_data')
persona = await run_blocking(db_executor, get_available_app_by_id, persona_id, uid)
if not persona:
raise HTTPException(status_code=404, detail='Persona not found')
if persona['uid'] != uid:
raise HTTPException(status_code=403, detail='You are not authorized to perform this action')
# Image
if file:
if (
'image' in persona
and len(persona['image']) > 0
and persona['image'].startswith('https://storage.googleapis.com/')
):
await run_blocking(storage_executor, delete_app_logo, persona['image'])
os.makedirs('_temp/apps', exist_ok=True)
file_path = f"_temp/apps/{file.filename}"
contents = await file.read()
await run_blocking(storage_executor, _write_file, file_path, contents)
img_url = await run_blocking(storage_executor, upload_app_logo, file_path, persona_id)
data['image'] = img_url
# Partial update: released clients PATCH the whole persona, but a client that
# sends only the fields it changed must not have the rest silently rewritten.
# `username` claims the handle, and `name` drives an LLM description rewrite —
# both are destructive to do on a field the caller never mentioned.
if 'username' in data and data['username'] and data['username'] != persona.get('username'):
await run_blocking(db_executor, save_username, data['username'], uid)
if 'name' in data and data['name'] and data['name'] != persona.get('name'):
# The name changed, so the generated description no longer matches it,
# unless the caller supplied its own.
if 'description' not in data:
data['description'] = await run_blocking(llm_executor, generate_persona_desc, uid, data['name'])
# AppUpdate needs the identity fields even when the caller omitted them.
data['id'] = persona_id
data['updated_at'] = datetime.now(timezone.utc)
# Update 'omi' connected_accounts
if 'omi' in data.get('connected_accounts', []) and 'omi' not in persona.get('connected_accounts', []):
data['persona_prompt'] = await generate_persona_prompt(uid, persona)
try:
update_app = AppUpdate.model_validate(data)
except ValidationError as e:
raise HTTPException(status_code=422, detail=str(e))
await run_blocking(db_executor, update_app_in_db, update_app.model_dump(exclude_unset=True))
if persona['approved'] and (persona['private'] is None or persona['private'] is False):
await run_blocking(db_executor, invalidate_approved_apps_cache)
await run_blocking(db_executor, delete_app_cache_by_id, persona_id)
username = data.get('username', persona.get('username'))
return {'status': 'ok', 'app_id': persona_id, 'username': username}