-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_app.py
More file actions
4154 lines (3638 loc) · 150 KB
/
Copy pathapi_app.py
File metadata and controls
4154 lines (3638 loc) · 150 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
"""API-only FastAPI application for Lambda deployment.
This module contains ONLY the programmatic API routes (health, bootstrap, agents,
spaces, devices, memberships, LiveKit tokens). GUI routes are in app.py which
extends this for local development.
Architecture:
- api_app.py (this file): API routes only -> deployed to Lambda
- app.py: API + GUI routes -> local development only
- lambda_handler.py: imports from api_app.py
"""
from __future__ import annotations
import json
import logging
import os
import secrets
import uuid
from dataclasses import asdict
from typing import Any, Optional
import boto3
from agent_hub.audit import append_audit_entry
from agent_hub.auth import (
AuthenticatedAgent,
AuthenticatedDevice,
AuthenticatedUser,
authenticate_agent_token,
authenticate_device,
authenticate_user_access_token,
create_agent_token,
ensure_user_row,
generate_device_token,
hash_token,
list_agent_tokens,
lookup_cognito_user_by_email,
require_scope,
revoke_agent_token,
)
from agent_hub.broadcast import broadcast_event
from agent_hub.config import load_config
from agent_hub.integrations import (
IntegrationAccountCreate,
IntegrationAccountUpdate,
IntegrationQueueMessage,
create_integration_account,
enqueue_integration_event,
get_integration_account,
get_integration_message,
insert_integration_message,
link_integration_message_event,
list_integration_accounts,
normalize_github_webhook,
normalize_slack_webhook,
normalize_twilio_webhook,
parse_twilio_form_body,
update_integration_account,
verify_github_request,
verify_slack_request,
verify_twilio_request,
)
from agent_hub.integrations.models import _UNSET
from agent_hub.livekit_tokens import mint_livekit_join_token
from agent_hub.memberships import (
check_agent_permission,
claim_first_owner,
grant_membership,
list_agents_for_user,
list_members_for_agent,
revoke_membership,
update_membership,
)
from agent_hub.memory_taxonomy import normalize_memory_kind
from agent_hub.metrics import emit_count, emit_ms
from agent_hub.openai_http import call_embeddings
from agent_hub.personas import DEFAULT_AGENT_PERSONA_INSTRUCTIONS, DEFAULT_AGENT_PERSONA_NAME
from agent_hub.policy import is_agent_disabled, is_privacy_mode
from agent_hub.rds_data import RdsData, RdsDataEnv
from agent_hub.secrets import get_secret_json
from fastapi import Depends, FastAPI, Header, HTTPException, Request
from pydantic import BaseModel, Field
from starlette.middleware.sessions import SessionMiddleware
from starlette.responses import PlainTextResponse
logger = logging.getLogger(__name__)
logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"))
# Avoid leaking AWS response payloads (can include secrets) in local logs.
for _name in ("botocore", "urllib3", "httpcore", "httpx"):
logging.getLogger(_name).setLevel(logging.WARNING)
api_app = FastAPI(title="AgentHub API")
# Load config
_cfg = load_config()
def _get_session_secret() -> str:
"""Get session secret key, loading from Secrets Manager if needed."""
if _cfg.session_secret_key:
return _cfg.session_secret_key
if _cfg.session_secret_arn:
try:
data = get_secret_json(_cfg.session_secret_arn)
key = data.get("session_secret_key")
if key:
return str(key)
except Exception:
logger.warning("Failed to load session secret from Secrets Manager")
logger.warning("SESSION_SECRET_KEY not set - using random key")
return secrets.token_urlsafe(32)
# Add SessionMiddleware (needed for API routes that use sessions)
_session_secret = _get_session_secret()
_is_https = os.getenv("HTTPS_ENABLED", "true").lower() in ("true", "1", "yes")
_is_local = os.getenv("ENVIRONMENT", "").lower() in ("local", "dev", "test")
api_app.add_middleware(
SessionMiddleware,
secret_key=_session_secret,
session_cookie="marvain_session",
max_age=3600 * 8,
same_site="lax",
https_only=_is_https or not _is_local,
)
# Lazy-load clients
_db: RdsData | None = None
_sqs: Any = None
_s3: Any = None
_recognition_queue_url: str | None = os.getenv("RECOGNITION_QUEUE_URL")
def _get_db() -> RdsData:
global _db
if _db is None:
_db = RdsData(
RdsDataEnv(resource_arn=_cfg.db_resource_arn, secret_arn=_cfg.db_secret_arn, database=_cfg.db_name)
)
return _db
def _get_sqs() -> Any:
global _sqs
if _sqs is None:
_sqs = boto3.client("sqs")
return _sqs
def _get_s3() -> Any:
global _s3
if _s3 is None:
_s3 = boto3.client("s3")
return _s3
def _admin_key() -> str:
if not _cfg.admin_secret_arn:
raise RuntimeError("ADMIN_SECRET_ARN not set")
data = get_secret_json(_cfg.admin_secret_arn)
k = data.get("admin_api_key")
if not k:
raise RuntimeError("Admin API key not present in secret")
return str(k)
def require_admin(x_admin_key: str = Header(default="", alias="X-Admin-Key")) -> None:
if not x_admin_key or x_admin_key != _admin_key():
raise HTTPException(status_code=401, detail="Invalid admin key")
def get_device(request: Request) -> AuthenticatedDevice:
auth = request.headers.get("authorization") or request.headers.get("Authorization")
if not auth or not auth.lower().startswith("bearer "):
raise HTTPException(status_code=401, detail="Missing bearer token")
token = auth.split(" ", 1)[1].strip()
dev = authenticate_device(_get_db(), token)
if not dev:
raise HTTPException(status_code=401, detail="Invalid device token")
return dev
def get_user(request: Request) -> AuthenticatedUser:
auth = request.headers.get("authorization") or request.headers.get("Authorization")
if not auth or not auth.lower().startswith("bearer "):
raise HTTPException(status_code=401, detail="Missing bearer token")
token = auth.split(" ", 1)[1].strip()
try:
return authenticate_user_access_token(_get_db(), token)
except PermissionError:
raise HTTPException(status_code=401, detail="Invalid access token")
# Expose shared state for gui routes (app.py) to use
def get_config():
return _cfg
def _require_agent_space(agent_id: str, space_id: str) -> None:
rows = _get_db().query(
"""
SELECT 1
FROM spaces
WHERE agent_id = :agent_id::uuid
AND space_id = :space_id::uuid
LIMIT 1
""",
{"agent_id": agent_id, "space_id": space_id},
)
if not rows:
raise HTTPException(status_code=404, detail="Space not found")
VALID_INTEGRATION_PROVIDERS = {"slack", "gmail", "github", "linear", "twilio"}
def _validate_integration_provider(provider: str) -> str:
provider_n = str(provider or "").strip().lower()
if provider_n not in VALID_INTEGRATION_PROVIDERS:
raise HTTPException(status_code=400, detail="Invalid integration provider")
return provider_n
def _integration_account_dict(account: Any) -> dict[str, Any]:
return asdict(account)
def _integration_message_dict(message: Any) -> dict[str, Any]:
return asdict(message)
def _require_agent_integration_account(agent_id: str, integration_account_id: str) -> Any:
account = get_integration_account(_get_db(), integration_account_id=integration_account_id)
if account is None or account.agent_id != agent_id:
raise HTTPException(status_code=404, detail="Integration account not found")
return account
def _require_provider_integration_account(agent_id: str, integration_account_id: str, provider: str) -> Any:
account = _require_agent_integration_account(agent_id, integration_account_id)
if account.provider != provider:
raise HTTPException(status_code=400, detail="Integration account provider mismatch")
return account
def _require_integration_account_secret_data(integration_account: Any) -> dict[str, Any]:
secret_arn = str(integration_account.credentials_secret_arn or "").strip()
if not secret_arn:
raise HTTPException(status_code=500, detail="Integration account secret not configured")
data = get_secret_json(secret_arn)
if not isinstance(data, dict):
raise HTTPException(status_code=500, detail="Integration account secret invalid")
return data
def _require_webhook_account(integration_account_id: str, provider: str) -> Any:
account = get_integration_account(_get_db(), integration_account_id=integration_account_id)
if account is None:
raise HTTPException(status_code=404, detail="Integration account not found")
if account.provider != provider:
raise HTTPException(status_code=404, detail="Integration account not found")
if not account.default_space_id:
raise HTTPException(status_code=400, detail="Integration account missing default space")
return account
# -----------------------------
# Pydantic Models
# -----------------------------
class BootstrapIn(BaseModel):
agent_name: str = Field(default="Forge")
default_space_name: str = Field(default="home")
class BootstrapOut(BaseModel):
agent_id: str
space_id: str
device_id: str
device_token: str
class RegisterDeviceIn(BaseModel):
agent_id: str
name: Optional[str] = None
scopes: list[str] = Field(default_factory=list)
capabilities: dict[str, Any] = Field(default_factory=dict)
location_label: Optional[str] = Field(default=None, description="Human-readable location label")
location_coords: Optional[dict[str, Any]] = Field(
default=None, description="Optional geographic coordinates: {lat, lng}"
)
class RegisterDeviceOut(BaseModel):
device_id: str
device_token: str
class RotateDeviceTokenOut(BaseModel):
device_id: str
device_token: str
class DeviceLocationUpdateIn(BaseModel):
"""Request body for updating device location."""
location_label: Optional[str] = Field(default=None, description="Human-readable location label")
location_coords: Optional[dict[str, Any]] = Field(
default=None, description="Optional geographic coordinates: {lat, lng}"
)
class SetPrivacyIn(BaseModel):
privacy_mode: bool
class IngestEventIn(BaseModel):
space_id: str
type: str
payload: dict[str, Any] = Field(default_factory=dict)
person_id: Optional[str] = None
session_id: Optional[str] = None
class IngestEventOut(BaseModel):
event_id: str
queued: bool
class MeOut(BaseModel):
user_id: str
email: str | None = None
class CreateAgentIn(BaseModel):
name: str
relationship_label: str | None = None
class UpdateAgentIn(BaseModel):
name: str | None = None
disabled: bool | None = None
class AgentOut(BaseModel):
agent_id: str
name: str
role: str
relationship_label: str | None = None
disabled: bool
class AgentMemberOut(BaseModel):
user_id: str
cognito_sub: str | None = None
email: str | None = None
role: str
relationship_label: str | None = None
class GrantMemberIn(BaseModel):
email: str
role: str
relationship_label: str | None = None
class UpdateMemberIn(BaseModel):
role: str
relationship_label: str | None = None
class LiveKitTokenIn(BaseModel):
space_id: str
room_mode: str | None = Field(
default=None,
description="Optional room mode override: 'ephemeral' (default) or 'stable'. If omitted, uses spaces.livekit_room_mode.",
)
class LiveKitDeviceTokenIn(BaseModel):
space_id: str
capabilities: dict[str, Any] = Field(default_factory=dict)
room_mode: str | None = Field(default="stable", description="Only 'stable' is supported for device tokens.")
class LiveKitTokenOut(BaseModel):
url: str
token: str
room: str
identity: str
session_id: str | None = None
class PersonaOut(BaseModel):
persona_id: str
agent_id: str
name: str
instructions: str
source: str
class PresignIn(BaseModel):
filename: str
content_type: str = Field(default="application/octet-stream")
purpose: str | None = Field(default="general", description="general|recognition")
class IntegrationAccountCreateIn(BaseModel):
provider: str
display_name: str
credentials_secret_arn: str
external_account_id: str | None = None
default_space_id: str | None = None
scopes: list[str] = Field(default_factory=list)
config: dict[str, Any] = Field(default_factory=dict)
status: str = Field(default="active")
class IntegrationAccountUpdateIn(BaseModel):
display_name: str | None = None
credentials_secret_arn: str | None = None
external_account_id: str | None = None
default_space_id: str | None = None
scopes: list[str] | None = None
config: dict[str, Any] | None = None
status: str | None = None
class IntegrationMessageQueryParams(BaseModel):
provider: str | None = None
status: str | None = None
external_thread_id: str | None = None
limit: int = 50
# -----------------------------
# Helper Functions
# -----------------------------
def _require_agent_role(*, user: AuthenticatedUser, agent_id: str, required_role: str) -> None:
if not check_agent_permission(_get_db(), agent_id=agent_id, user_id=user.user_id, required_role=required_role):
raise HTTPException(status_code=403, detail="Forbidden")
def _require_livekit_config() -> tuple[str, str, str]:
url = str(_cfg.livekit_url or "").strip()
secret_arn = str(_cfg.livekit_secret_arn or "").strip()
if not url:
raise HTTPException(status_code=500, detail="LIVEKIT_URL not configured")
if not secret_arn:
raise HTTPException(status_code=500, detail="LIVEKIT_SECRET_ARN not configured")
data = get_secret_json(secret_arn)
api_key = str(data.get("api_key") or "").strip()
api_secret = str(data.get("api_secret") or "").strip()
if not api_key or not api_secret:
raise HTTPException(status_code=500, detail="LiveKit secret missing api_key/api_secret")
return url, api_key, api_secret
def _space_agent_id(*, space_id: str) -> str | None:
try:
rows = _get_db().query(
"SELECT agent_id::text AS agent_id FROM spaces WHERE space_id = CAST(:space_id AS uuid)",
params={"space_id": str(space_id)},
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to look up space: {e}")
if not rows:
return None
v = rows[0].get("agent_id")
return str(v) if v else None
def _space_livekit_room_mode(*, space_id: str) -> str:
"""Return the LiveKit room mode for a space."""
try:
rows = _get_db().query(
"SELECT livekit_room_mode FROM spaces WHERE space_id = CAST(:space_id AS uuid)",
params={"space_id": str(space_id)},
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to look up space room mode: {e}")
if not rows:
raise HTTPException(status_code=404, detail="Space not found")
v = str(rows[0].get("livekit_room_mode") or "").strip().lower()
if v not in {"ephemeral", "stable"}:
raise HTTPException(status_code=500, detail=f"Invalid livekit_room_mode for space: {v}")
return v
def _seed_default_persona(*, agent_id: str, transaction_id: str | None = None) -> str:
persona_id = str(uuid.uuid4())
_get_db().execute(
"""
INSERT INTO personas(persona_id, agent_id, name, instructions, is_default, lifecycle_state)
VALUES (:persona_id::uuid, :agent_id::uuid, :name, :instructions, true, 'active')
""",
{
"persona_id": persona_id,
"agent_id": agent_id,
"name": DEFAULT_AGENT_PERSONA_NAME,
"instructions": DEFAULT_AGENT_PERSONA_INSTRUCTIONS,
},
transaction_id=transaction_id,
)
return persona_id
def _create_session_record(
*,
agent_id: str,
space_id: str,
session_id: str,
livekit_room: str,
room_mode: str,
actor_type: str,
actor_id: str,
) -> None:
_get_db().execute(
"""
INSERT INTO sessions(session_id, agent_id, space_id, persona_id, livekit_room, status, metadata)
VALUES (
:session_id::uuid,
:agent_id::uuid,
:space_id::uuid,
(
SELECT persona_id
FROM personas
WHERE agent_id = :agent_id::uuid
AND is_default
AND lifecycle_state = 'active'
AND disabled_at IS NULL
ORDER BY created_at DESC
LIMIT 1
),
:livekit_room,
'open',
:metadata::jsonb
)
""",
{
"session_id": session_id,
"agent_id": agent_id,
"space_id": space_id,
"livekit_room": livekit_room,
"metadata": json.dumps({"room_mode": room_mode, "actor_type": actor_type, "actor_id": actor_id}),
},
)
def _device_is_admin(device: AuthenticatedDevice) -> bool:
kind = str((device.capabilities or {}).get("kind") or "").strip().lower()
# Local agent workers are trusted orchestrators and must access any space
# selected in LiveKit sessions, even when their bootstrap token is anchored
# to a different agent.
return kind in {"admin", "worker"}
def _resolve_space_agent_for_device(
*,
device: AuthenticatedDevice,
space_id: str,
not_found_detail: str = "Space not found",
mismatch_status: int = 403,
mismatch_detail: str = "Forbidden",
) -> str:
"""Resolve a space's owning agent and enforce device access rules."""
agent_id = _space_agent_id(space_id=space_id)
if not agent_id:
raise HTTPException(status_code=404, detail=not_found_detail)
if agent_id != str(device.agent_id) and not _device_is_admin(device):
raise HTTPException(status_code=mismatch_status, detail=mismatch_detail)
return agent_id
async def _mint_livekit_token_for_user(
*, user: AuthenticatedUser, space_id: str, room_mode: str | None = None
) -> LiveKitTokenOut:
"""Mint a LiveKit token with a unique room name per session.
Architecture:
- LiveKit "room" = ephemeral media session (unique per join)
- Marvain "space" = persistent conversation context (stored in Hub database)
- One space can have many sequential rooms over time
Room names are unique per session: "{space_id}:{session_id}". This guarantees
every join creates a NEW room, triggering reliable agent dispatch. The space_id
is passed to the agent via metadata so it can persist transcripts correctly.
Room cleanup: LiveKit Cloud automatically garbage collects empty rooms shortly
after all participants leave. We don't need to manually delete rooms because
each join uses a unique room name, avoiding the eventual consistency issues
that plagued the previous room-deletion approach.
"""
agent_id = _space_agent_id(space_id=space_id)
if not agent_id:
raise HTTPException(status_code=404, detail="Space not found")
if not check_agent_permission(_get_db(), agent_id=agent_id, user_id=user.user_id, required_role="member"):
raise HTTPException(status_code=403, detail="Forbidden")
url, api_key, api_secret = _require_livekit_config()
resolved_mode = str(room_mode or _space_livekit_room_mode(space_id=space_id) or "ephemeral").strip().lower()
if resolved_mode not in {"ephemeral", "stable"}:
resolved_mode = "ephemeral"
# Always generate a durable session row, even in stable room mode.
session_id = str(uuid.uuid4())
room_session_id = session_id.replace("-", "")[:12]
if resolved_mode == "stable":
room = str(space_id)
else:
# Ephemeral mode: guarantees a new room per join for reliable dispatch.
room = f"{space_id}:{room_session_id}"
identity = f"user:{user.user_id}"
_create_session_record(
agent_id=str(agent_id),
space_id=str(space_id),
session_id=session_id,
livekit_room=room,
room_mode=resolved_mode,
actor_type="user",
actor_id=user.user_id,
)
token = mint_livekit_join_token(
api_key=api_key,
api_secret=api_secret,
identity=identity,
room=room,
name=(user.email or user.user_id),
ttl_seconds=3600,
agent_metadata={
"space_id": str(space_id),
"agent_id": str(agent_id),
"session_id": session_id,
"room_session_id": room_session_id,
},
)
return LiveKitTokenOut(url=url, token=token, room=room, identity=identity, session_id=session_id)
# -----------------------------
# API Routes
# -----------------------------
@api_app.get("/health")
def health() -> dict[str, Any]:
return {"ok": True, "stage": _cfg.stage}
@api_app.get("/v1/tools")
def list_tools(device: AuthenticatedDevice = Depends(get_device)) -> dict[str, Any]:
"""Return all registered tools with name, description, and required scopes."""
from agent_hub.tools.registry import get_registry
registry = get_registry()
return {"tools": [t.to_dict() for t in registry.list_tools()]}
@api_app.get("/v1/me", response_model=MeOut)
def me(user: AuthenticatedUser = Depends(get_user)) -> MeOut:
return MeOut(user_id=user.user_id, email=user.email)
@api_app.get("/v1/agents", response_model=dict[str, list[AgentOut]])
def agents(user: AuthenticatedUser = Depends(get_user)) -> dict[str, list[AgentOut]]:
memberships = list_agents_for_user(_get_db(), user_id=user.user_id)
return {
"agents": [
AgentOut(
agent_id=m.agent_id,
name=m.name,
role=m.role,
relationship_label=m.relationship_label,
disabled=m.disabled,
)
for m in memberships
]
}
@api_app.post("/v1/agents", response_model=AgentOut)
def create_agent(body: CreateAgentIn, user: AuthenticatedUser = Depends(get_user)) -> AgentOut:
"""Create a new agent and make the creating user the owner."""
agent_id = str(uuid.uuid4())
tx = _get_db().begin()
try:
_get_db().execute(
"INSERT INTO agents(agent_id, name, disabled) VALUES (:agent_id::uuid, :name, false)",
{"agent_id": agent_id, "name": body.name},
transaction_id=tx,
)
_get_db().execute(
"""
INSERT INTO agent_memberships (agent_id, user_id, role, relationship_label)
VALUES (:agent_id::uuid, :user_id::uuid, 'owner', :relationship_label)
""",
{"agent_id": agent_id, "user_id": user.user_id, "relationship_label": body.relationship_label},
transaction_id=tx,
)
_seed_default_persona(agent_id=agent_id, transaction_id=tx)
_get_db().commit(tx)
except Exception:
_get_db().rollback(tx)
raise
if _cfg.audit_bucket:
append_audit_entry(
_get_db(),
bucket=_cfg.audit_bucket,
agent_id=agent_id,
entry_type="agent_created",
entry={"user_id": user.user_id, "name": body.name},
)
return AgentOut(
agent_id=agent_id,
name=body.name,
role="owner",
relationship_label=body.relationship_label,
disabled=False,
)
@api_app.patch("/v1/agents/{agent_id}", response_model=AgentOut)
def update_agent(agent_id: str, body: UpdateAgentIn, user: AuthenticatedUser = Depends(get_user)) -> AgentOut:
"""Update an agent's name or disabled status. Requires admin role."""
_require_agent_role(user=user, agent_id=agent_id, required_role="admin")
updates: list[str] = []
params: dict[str, Any] = {"agent_id": agent_id}
if body.name is not None:
name = body.name.strip()
if not name:
raise HTTPException(status_code=400, detail="Name cannot be empty")
updates.append("name = :name")
params["name"] = name
if body.disabled is not None:
updates.append("disabled = :disabled")
params["disabled"] = body.disabled
if not updates:
raise HTTPException(status_code=400, detail="No fields to update")
_get_db().execute(
f"UPDATE agents SET {', '.join(updates)} WHERE agent_id = :agent_id::uuid",
params,
)
if _cfg.audit_bucket:
append_audit_entry(
_get_db(),
bucket=_cfg.audit_bucket,
agent_id=agent_id,
entry_type="agent_updated",
entry={"user_id": user.user_id, "name": body.name, "disabled": body.disabled},
)
# Fetch current state to return
rows = _get_db().query(
"""SELECT a.name, a.disabled, am.role, am.relationship_label
FROM agents a
JOIN agent_memberships am ON a.agent_id = am.agent_id
WHERE a.agent_id = :agent_id::uuid AND am.user_id = :user_id::uuid AND am.revoked_at IS NULL""",
{"agent_id": agent_id, "user_id": user.user_id},
)
if not rows:
raise HTTPException(status_code=404, detail="Agent not found")
r = rows[0]
return AgentOut(
agent_id=agent_id,
name=r["name"],
role=r["role"],
relationship_label=r.get("relationship_label"),
disabled=r["disabled"],
)
@api_app.post("/v1/livekit/token", response_model=LiveKitTokenOut)
async def livekit_token(body: LiveKitTokenIn, user: AuthenticatedUser = Depends(get_user)) -> LiveKitTokenOut:
"""Mint a short-lived LiveKit token for a user to join the room for a space."""
return await _mint_livekit_token_for_user(user=user, space_id=body.space_id, room_mode=body.room_mode)
@api_app.post("/v1/livekit/device-token", response_model=LiveKitTokenOut)
async def livekit_device_token(
body: LiveKitDeviceTokenIn, device: AuthenticatedDevice = Depends(get_device)
) -> LiveKitTokenOut:
"""Mint a short-lived LiveKit token for a device to join a stable room for a space.
Intended for always-on Location Nodes that publish/consume AV in LiveKit.
"""
require_scope(device, "events:write")
if str(body.room_mode or "stable").strip().lower() != "stable":
raise HTTPException(status_code=400, detail="Only room_mode='stable' is supported for device tokens")
agent_id = _resolve_space_agent_for_device(
device=device,
space_id=body.space_id,
not_found_detail="Space not found",
mismatch_status=404,
mismatch_detail="Space not found",
)
if is_agent_disabled(_get_db(), agent_id):
raise HTTPException(status_code=403, detail="Agent is disabled")
url, api_key, api_secret = _require_livekit_config()
session_id = str(uuid.uuid4())
room_session_id = session_id.replace("-", "")[:12]
room = str(body.space_id)
identity = f"device:{device.device_id}"
caps = body.capabilities or {}
publish_audio = bool(caps.get("publish_audio", True))
publish_video = bool(caps.get("publish_video", True))
subscribe_audio = bool(caps.get("subscribe_audio", True))
_create_session_record(
agent_id=str(agent_id),
space_id=str(body.space_id),
session_id=session_id,
livekit_room=room,
room_mode="stable",
actor_type="device",
actor_id=device.device_id,
)
# LiveKit grants do not separate audio/video publish; treat any publish as can_publish.
token = mint_livekit_join_token(
api_key=api_key,
api_secret=api_secret,
identity=identity,
room=room,
name=(caps.get("name") or device.device_id),
ttl_seconds=3600,
can_publish=bool(publish_audio or publish_video),
can_subscribe=bool(subscribe_audio),
agent_metadata={
"space_id": str(body.space_id),
"agent_id": str(agent_id),
"session_id": session_id,
"room_session_id": room_session_id,
},
)
return LiveKitTokenOut(url=url, token=token, room=room, identity=identity, session_id=session_id)
@api_app.get("/v1/agents/{agent_id}/personas/default", response_model=PersonaOut)
def get_default_persona(
agent_id: str,
space_id: str | None = None,
session_id: str | None = None,
device: AuthenticatedDevice = Depends(get_device),
) -> PersonaOut:
"""Return the active default persona for agent-worker prompt hydration."""
require_scope(device, "events:read")
_require_device_agent_access(device=device, agent_id=agent_id)
if is_agent_disabled(_get_db(), agent_id):
raise HTTPException(status_code=403, detail="Agent is disabled")
if space_id:
_require_agent_space(agent_id, space_id)
rows = _get_db().query(
"""
SELECT persona_id::TEXT as persona_id, agent_id::TEXT as agent_id, name, instructions
FROM personas
WHERE agent_id = :agent_id::uuid
AND is_default
AND lifecycle_state = 'active'
AND disabled_at IS NULL
ORDER BY created_at DESC
LIMIT 1
""",
{"agent_id": agent_id},
)
if not rows:
raise HTTPException(status_code=404, detail="Default persona not configured")
row = rows[0]
if session_id:
_get_db().execute(
"""
UPDATE sessions
SET persona_id = :persona_id::uuid
WHERE session_id = :session_id::uuid
AND agent_id = :agent_id::uuid
""",
{"persona_id": row["persona_id"], "session_id": session_id, "agent_id": agent_id},
)
return PersonaOut(
persona_id=row["persona_id"],
agent_id=row["agent_id"],
name=row["name"],
instructions=row["instructions"],
source="hub",
)
@api_app.post("/v1/agents/{agent_id}/claim_owner")
def claim_owner(agent_id: str, user: AuthenticatedUser = Depends(get_user)) -> dict[str, Any]:
try:
claim_first_owner(_get_db(), agent_id=agent_id, user_id=user.user_id)
except PermissionError as e:
raise HTTPException(status_code=409, detail=str(e))
if _cfg.audit_bucket:
append_audit_entry(
_get_db(),
bucket=_cfg.audit_bucket,
agent_id=agent_id,
entry_type="owner_claimed",
entry={"user_id": user.user_id},
)
return {"agent_id": agent_id, "user_id": user.user_id, "role": "owner"}
@api_app.get("/v1/agents/{agent_id}/memberships", response_model=dict[str, list[AgentMemberOut]])
def list_members(agent_id: str, user: AuthenticatedUser = Depends(get_user)) -> dict[str, list[AgentMemberOut]]:
_require_agent_role(user=user, agent_id=agent_id, required_role="member")
members = list_members_for_agent(_get_db(), agent_id=agent_id, include_revoked=False)
return {
"memberships": [
AgentMemberOut(user_id=m.user_id, email=m.email, role=m.role, relationship_label=m.relationship_label)
for m in members
]
}
@api_app.post("/v1/agents/{agent_id}/memberships", response_model=AgentMemberOut)
def add_member(agent_id: str, body: GrantMemberIn, user: AuthenticatedUser = Depends(get_user)) -> AgentMemberOut:
"""Add (or update) a member to an agent."""
_require_agent_role(user=user, agent_id=agent_id, required_role="admin")
if not _cfg.cognito_user_pool_id:
raise HTTPException(status_code=500, detail="COGNITO_USER_POOL_ID not configured")
try:
cognito_sub, resolved_email = lookup_cognito_user_by_email(
user_pool_id=_cfg.cognito_user_pool_id,
email=body.email,
)
except LookupError as e:
raise HTTPException(status_code=404, detail=str(e))
user_id = ensure_user_row(_get_db(), cognito_sub=cognito_sub, email=(resolved_email or body.email))
try:
grant_membership(
_get_db(), agent_id=agent_id, user_id=user_id, role=body.role, relationship_label=body.relationship_label
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
if _cfg.audit_bucket:
append_audit_entry(
_get_db(),
bucket=_cfg.audit_bucket,
agent_id=agent_id,
entry_type="member_granted",
entry={
"by_user_id": user.user_id,
"user_id": user_id,
"cognito_sub": cognito_sub,
"email": (resolved_email or body.email),
"role": body.role,
"relationship_label": body.relationship_label,
},
)
return AgentMemberOut(
user_id=user_id,
cognito_sub=cognito_sub,
email=(resolved_email or body.email),
role=body.role,
relationship_label=body.relationship_label,
)
@api_app.patch("/v1/agents/{agent_id}/memberships/{member_user_id}")
def patch_member(
agent_id: str, member_user_id: str, body: UpdateMemberIn, user: AuthenticatedUser = Depends(get_user)
) -> dict[str, Any]:
_require_agent_role(user=user, agent_id=agent_id, required_role="admin")
try:
update_membership(
_get_db(),
agent_id=agent_id,
user_id=member_user_id,
role=body.role,
relationship_label=body.relationship_label,
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
if _cfg.audit_bucket:
append_audit_entry(
_get_db(),
bucket=_cfg.audit_bucket,
agent_id=agent_id,
entry_type="member_updated",