-
Notifications
You must be signed in to change notification settings - Fork 654
Expand file tree
/
Copy pathrouter.py
More file actions
1788 lines (1608 loc) · 61.2 KB
/
Copy pathrouter.py
File metadata and controls
1788 lines (1608 loc) · 61.2 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
"""Unified sessions API router.
Composes the sub-domain routers:
- SessionStreamsRouter — /sessions/streams/*
- RecordsRouter — /sessions/records/*
- InteractionsRouter — /sessions/interactions/*
- SessionTurnsRouter — /sessions/turns/*
- SessionsRootRouter — /sessions/query, /sessions/ (DELETE),
/sessions/archive, /sessions/unarchive
peek (S12/E1) is NOT a verb and NOT a server-side aggregate. It is the front-end
composing the individual reads already exposed here:
1. `POST /sessions/query` (this router) -> a list of session_ids.
2. Per session_id: `GET /sessions/streams/?session_id=` (fetch the stream),
`POST /sessions/turns/query` (turns), `POST /sessions/records/query`
(records). No overlay/aggregate endpoint exists or is planned.
"""
import re
from functools import wraps
from uuid import UUID
from fastapi import (
APIRouter,
HTTPException,
Query,
Request,
Response,
status,
)
from fastapi.responses import JSONResponse, StreamingResponse
# FastAPI route params need fastapi.UploadFile; request.form() yields starlette's base class.
from fastapi import UploadFile as FastAPIUploadFile
from starlette.datastructures import UploadFile
from typing import Any, Optional, Union
from oss.src.utils.env import env
from oss.src.utils.exceptions import intercept_exceptions
from oss.src.utils.logging import get_module_logger
from oss.src.dbs.redis.sessions.contract import watch_channel
from oss.src.dbs.redis.shared.engine import get_streams_engine
from oss.src.apis.fastapi.sessions.watch import watch_event_stream
from oss.src.core.access.permissions.types import Permission
from oss.src.core.access.permissions.service import check_action_access
from oss.src.apis.fastapi.shared.exceptions import FORBIDDEN_EXCEPTION
# Core domain imports — new paths
from oss.src.core.sessions.streams.dtos import (
SessionHeartbeatRequest,
SessionHeartbeatResult,
SessionStreamCommandRequest,
SessionStreamCommandResponse,
SessionStreamHeaderEdit,
SessionStreamQuery,
SessionStreamQueryFlags,
)
from oss.src.core.sessions.streams.types import (
ConcurrencyLimitExceeded,
SessionIdInvalid,
SessionTurnInUse,
SessionStreamAlreadyExists,
SessionStreamNotFound,
)
from oss.src.core.sessions.streams.service import SessionStreamsService
from oss.src.core.sessions.records.service import RecordsService
from oss.src.core.sessions.records.dtos import SessionRecordEvent
from oss.src.core.sessions.records.streaming import publish_record
from oss.src.core.sessions.interactions.dtos import (
SessionInteractionCreate,
SessionInteractionKind,
SessionInteractionQuery,
SessionInteractionStatus,
SessionInteractionTransition,
)
from oss.src.core.sessions.interactions.service import SessionInteractionsService
from oss.src.core.sessions.interactions.types import InteractionNotFound
from oss.src.core.sessions.attachments.dtos import Attachment
from oss.src.core.sessions.attachments.service import SessionAttachmentsService
from oss.src.core.sessions.attachments.types import (
AttachmentConflict,
AttachmentInvalid,
AttachmentLengthRequired,
AttachmentNotFound,
AttachmentQuotaExceeded,
AttachmentRequestInvalid,
AttachmentStateConflict,
AttachmentTooLarge,
AttachmentUploadInFlight,
)
from oss.src.core.sessions.mounts.service import SessionMountsService
from oss.src.core.sessions.mounts.dtos import SessionMountQuery
from oss.src.core.sessions.turns.dtos import SessionTurnComplete, SessionTurnCreate
from oss.src.core.sessions.turns.service import SessionTurnsService
from oss.src.core.sessions.turns.types import SessionTurnNotFound
from oss.src.core.sessions.dtos import SessionQuery
from oss.src.core.sessions.service import SessionsService
from oss.src.core.mounts.service import MountsService
from oss.src.apis.fastapi.mounts.router import handle_mount_exceptions
from oss.src.apis.fastapi.mounts.utils import (
BINARY_RESPONSE,
_content_disposition_attachment,
download_mount_file,
sign_mount_credentials,
upload_mount_file,
)
from oss.src.apis.fastapi.mounts.models import (
MountCredentialsResponse,
MountFileWrittenResponse,
)
from oss.src.core.workflows.dtos import (
WorkflowServiceRequest,
WorkflowServiceRequestData,
)
from oss.src.core.workflows.service import WorkflowsService
from oss.src.apis.fastapi.sessions.models import (
# streams
SessionDetachRequest,
SessionStreamQueryRequest,
SessionStreamResponse,
SessionStreamsResponse,
# records
SessionRecordIngestRequest,
SessionRecordQueryRequest,
SessionRecordResponse,
SessionRecordsQueryResponse,
# interactions
SessionInteractionCancelStaleRequest,
SessionInteractionCreateRequest,
SessionInteractionQueryRequest,
SessionInteractionRespondRequest,
SessionInteractionResponse,
SessionInteractionsResponse,
SessionInteractionTransitionRequest,
SessionAttachment,
SessionAttachmentReferenceRequest,
SessionAttachmentResponse,
SessionAttachmentsResponse,
# mounts
SessionMountQueryRequest,
SessionMountResponse, # noqa: F401 (exported for OpenAPI/single-mount future use)
SessionMountsResponse,
# turns
SessionTurnAppendRequest,
SessionTurnCompleteRequest,
SessionTurnQueryRequest,
SessionTurnResponse,
SessionTurnsResponse,
# root session-level ops
SessionQueryRequest,
SessionResponse,
SessionsResponse,
)
log = get_module_logger(__name__)
_ATTACHMENT_MULTIPART_OVERHEAD_BYTES = 64 * 1024
_MAX_IDEMPOTENCY_KEY_CHARACTERS = 255
# matches the streams contract allowlist (dbs/redis/sessions/contract.py)
_SESSION_ID_RE = re.compile(r"^[a-zA-Z0-9_\-]{1,128}$")
def _validate_session_id_http(session_id: str) -> None:
if not _SESSION_ID_RE.match(session_id):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="session_id contains invalid characters or is empty.",
)
def _handle_session_exceptions():
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except SessionIdInvalid as e:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=e.message,
) from e
except SessionTurnInUse as e:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail={
"message": e.message,
"liveness": e.liveness,
},
) from e
except ConcurrencyLimitExceeded as e:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail=e.message,
) from e
except SessionStreamNotFound as e:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=e.message,
) from e
except SessionStreamAlreadyExists as e:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=e.message,
) from e
return wrapper
return decorator
def _handle_attachment_exceptions():
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except (AttachmentInvalid, AttachmentRequestInvalid) as e:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=e.message,
) from e
except AttachmentLengthRequired as e:
raise HTTPException(
status_code=status.HTTP_411_LENGTH_REQUIRED,
detail=e.message,
) from e
except AttachmentTooLarge as e:
raise HTTPException(
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
detail=e.message,
) from e
except AttachmentQuotaExceeded as e:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail=e.message,
) from e
except AttachmentNotFound as e:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=e.message,
) from e
except AttachmentUploadInFlight as e:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=e.message,
headers={"Retry-After": str(e.retry_after_seconds)},
) from e
except (AttachmentConflict, AttachmentStateConflict) as e:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=e.message,
) from e
return wrapper
return decorator
def _to_session_attachment(attachment: Attachment) -> SessionAttachment:
return SessionAttachment(
attachment_id=attachment.id,
filename=attachment.filename,
media_type=attachment.media_type,
size=attachment.size,
created_at=attachment.created_at,
)
# ---------------------------------------------------------------------------
# Sub-routers
# ---------------------------------------------------------------------------
class SessionStreamsRouter:
"""Streams sub-router — /sessions/streams/*"""
def __init__(
self,
*,
service: SessionStreamsService,
interactions_service: SessionInteractionsService,
) -> None:
self._service = service
self._interactions_service = interactions_service
self.router = APIRouter()
# Unified collection surface on /sessions/streams/, keyed by ?session_id=.
self.router.add_api_route(
"/sessions/streams/",
self.fetch_session_stream,
methods=["GET"],
operation_id="fetch_session_stream",
tags=["Sessions"],
)
self.router.add_api_route(
"/sessions/streams/",
self.set_session_stream,
methods=["POST"],
operation_id="set_session_stream",
tags=["Sessions"],
)
self.router.add_api_route(
"/sessions/streams/",
self.delete_session_stream,
methods=["DELETE"],
operation_id="delete_session_stream",
tags=["Sessions"],
)
self.router.add_api_route(
"/sessions/streams/query",
self.query_session_streams,
methods=["POST"],
operation_id="query_session_streams",
tags=["Sessions"],
)
self.router.add_api_route(
"/sessions/streams/detach",
self.detach_session_stream,
methods=["POST"],
operation_id="detach_session_stream",
tags=["Sessions"],
)
self.router.add_api_route(
"/sessions/streams/heartbeat",
self.heartbeat_session_stream,
methods=["POST"],
operation_id="heartbeat_session_stream",
tags=["Sessions"],
)
self.router.add_api_route(
"/sessions/streams/header",
self.set_session_stream_header,
methods=["PUT", "POST"],
operation_id="set_session_stream_header",
tags=["Sessions"],
)
self.router.add_api_route(
"/sessions/streams/watch",
self.watch_session_stream,
methods=["GET"],
operation_id="watch_session_stream",
tags=["Sessions"],
response_model=None,
)
@intercept_exceptions()
@_handle_session_exceptions()
async def set_session_stream(
self,
request: Request,
payload: SessionStreamCommandRequest,
) -> SessionStreamCommandResponse:
project_id = request.state.project_id
user_id = request.state.user_id
has_permission = await check_action_access(
user_uid=str(user_id),
project_id=str(project_id),
permission=Permission.RUN_SESSIONS,
)
if not has_permission:
raise FORBIDDEN_EXCEPTION
await self._service.check_runner_concurrency_limit(project_id=project_id)
return await self._service.command(
project_id=project_id,
user_id=user_id,
request=payload,
)
@intercept_exceptions()
@_handle_session_exceptions()
async def fetch_session_stream(
self,
request: Request,
session_id: str = Query(...),
) -> SessionStreamResponse:
project_id = request.state.project_id
user_id = request.state.user_id
has_permission = await check_action_access(
user_uid=str(user_id),
project_id=str(project_id),
permission=Permission.VIEW_SESSIONS,
)
if not has_permission:
raise FORBIDDEN_EXCEPTION
stream = await self._service.fetch(
project_id=UUID(str(project_id)),
session_id=session_id,
)
return SessionStreamResponse(stream=stream)
@intercept_exceptions()
@_handle_session_exceptions()
async def delete_session_stream(
self,
request: Request,
session_id: str = Query(...),
) -> dict:
project_id = request.state.project_id
user_id = request.state.user_id
has_permission = await check_action_access(
user_uid=str(user_id),
project_id=str(project_id),
permission=Permission.RUN_SESSIONS,
)
if not has_permission:
raise FORBIDDEN_EXCEPTION
await self._service.kill(
project_id=UUID(str(project_id)),
user_id=UUID(str(user_id)),
session_id=session_id,
)
# kill orphans every pending gate — no one will answer them.
await self._interactions_service.cancel_session_pending(
project_id=UUID(str(project_id)),
session_id=session_id,
)
return {"ok": True}
@intercept_exceptions()
@_handle_session_exceptions()
async def detach_session_stream(
self,
request: Request,
payload: SessionDetachRequest,
) -> dict:
project_id = request.state.project_id
user_id = request.state.user_id
has_permission = await check_action_access(
user_uid=str(user_id),
project_id=str(project_id),
permission=Permission.RUN_SESSIONS,
)
if not has_permission:
raise FORBIDDEN_EXCEPTION
await self._service.detach(
project_id=UUID(str(project_id)),
user_id=UUID(str(user_id)),
session_id=payload.session_id,
watcher_id=payload.watcher_id,
)
return {"ok": True}
@intercept_exceptions()
@_handle_session_exceptions()
async def heartbeat_session_stream(
self,
request: Request,
payload: SessionHeartbeatRequest,
) -> SessionHeartbeatResult:
project_id = request.state.project_id
user_id = request.state.user_id
has_permission = await check_action_access(
user_uid=str(user_id),
project_id=str(project_id),
permission=Permission.RUN_SESSIONS,
)
if not has_permission:
raise FORBIDDEN_EXCEPTION
return await self._service.heartbeat(
project_id=project_id,
request=payload,
)
@intercept_exceptions()
@_handle_session_exceptions()
async def query_session_streams(
self,
request: Request,
payload: SessionStreamQueryRequest,
) -> SessionStreamsResponse:
project_id = request.state.project_id
user_id = request.state.user_id
has_permission = await check_action_access(
user_uid=str(user_id),
project_id=str(project_id),
permission=Permission.VIEW_SESSIONS,
)
if not has_permission:
raise FORBIDDEN_EXCEPTION
streams = await self._service.query_streams(
project_id=project_id,
filter=SessionStreamQuery(
session_id=payload.session_id,
flags=SessionStreamQueryFlags(
is_alive=payload.is_alive,
is_running=payload.is_running,
),
),
)
return SessionStreamsResponse(count=len(streams), streams=streams)
@intercept_exceptions()
@_handle_session_exceptions()
async def set_session_stream_header(
self,
request: Request,
*,
header: SessionStreamHeaderEdit,
session_id: str = Query(...),
) -> SessionStreamResponse:
_validate_session_id_http(session_id)
if not await check_action_access(
user_uid=request.state.user_id,
project_id=request.state.project_id,
permission=Permission.EDIT_SESSIONS,
):
raise FORBIDDEN_EXCEPTION
stream = await self._service.set_header(
project_id=UUID(request.state.project_id),
user_id=UUID(request.state.user_id),
session_id=session_id,
header=header,
)
return SessionStreamResponse(stream=stream)
@intercept_exceptions()
@_handle_session_exceptions()
async def watch_session_stream(
self,
request: Request,
session_id: str = Query(...),
) -> StreamingResponse:
"""Server-sent events relay for one session (M3 live relay).
Emits change notifications only — never record payloads; clients
revalidate through the regular query endpoints on each event:
- ``event: records-changed`` — ``{"session_id"}``; new/updated rows
landed in the record log (published post-DB-commit).
- ``event: lifecycle`` — ``{"session_id", "state": "running"|"ended"}``.
- ``event: interaction`` — ``{"session_id", "status": "pending"|"resolved"}``.
- ``: heartbeat`` comment frames while idle (keep-alive).
Auth is the standard middleware (cookie ``sAccessToken``, ApiKey, or
Bearer) evaluated once at connect; scope is the credential's project.
Browsers authenticate by cookie — ``EventSource`` cannot set headers —
so a connect landing on an expired access token 401s like any other
request. There is no interceptor to refresh-and-retry a stream, so the
client must refresh the session itself and reopen (see the web hooks).
The stream has no replay/cursor semantics — ``EventSource`` reconnects
and clients revalidate once on every ``open``, which covers any missed
notifications.
NOTE (spec surface): this route appears in OpenAPI for documentation,
but Fern does not model SSE — consume it with a native ``EventSource``
(same-origin ``/api`` + cookie auth needs no custom headers), not the
generated client.
"""
_validate_session_id_http(session_id)
project_id = request.state.project_id
user_id = request.state.user_id
has_permission = await check_action_access(
user_uid=str(user_id),
project_id=str(project_id),
permission=Permission.VIEW_SESSIONS,
)
if not has_permission:
raise FORBIDDEN_EXCEPTION
stream = watch_event_stream(
channel=watch_channel(str(project_id), session_id),
# One pubsub connection per SSE connection (v1 — simplest correct
# teardown story; revisit with a shared listener if counts grow).
pubsub_factory=lambda: get_streams_engine().get_redis().pubsub(),
heartbeat_seconds=env.sessions.watch_heartbeat_seconds,
retry_milliseconds=env.sessions.watch_retry_milliseconds,
)
return StreamingResponse(
stream,
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
# Disable proxy buffering so frames flush immediately.
"X-Accel-Buffering": "no",
},
)
class RecordsRouter:
"""Records sub-router — /sessions/records/*"""
def __init__(self, records_service: RecordsService):
self.records_service = records_service
self.router = APIRouter()
self.router.add_api_route(
"/query",
self.query_records,
methods=["POST"],
operation_id="query_records",
status_code=status.HTTP_200_OK,
response_model=SessionRecordsQueryResponse,
response_model_exclude_none=True,
)
self.router.add_api_route(
"/{record_id}",
self.get_record_event,
methods=["GET"],
operation_id="get_record_event",
status_code=status.HTTP_200_OK,
response_model=SessionRecordResponse,
response_model_exclude_none=True,
)
self.router.add_api_route(
"/ingest",
self.ingest_record_event,
methods=["POST"],
operation_id="ingest_record",
tags=["Sessions"],
)
@intercept_exceptions()
async def query_records(
self,
request: Request,
*,
query_request: SessionRecordQueryRequest,
) -> Union[SessionRecordsQueryResponse, JSONResponse]:
if not await check_action_access(
user_uid=request.state.user_id,
project_id=request.state.project_id,
permission=Permission.VIEW_SESSIONS,
):
raise FORBIDDEN_EXCEPTION
records = await self.records_service.get_records(
project_id=UUID(request.state.project_id),
session_id=query_request.session_id,
)
return SessionRecordsQueryResponse(
count=len(records),
records=records,
)
@intercept_exceptions()
async def get_record_event(
self,
request: Request,
record_id: UUID,
) -> Union[SessionRecordResponse, JSONResponse]:
if not await check_action_access(
user_uid=request.state.user_id,
project_id=request.state.project_id,
permission=Permission.VIEW_SESSIONS,
):
raise FORBIDDEN_EXCEPTION
record = await self.records_service.get_event(
project_id=UUID(request.state.project_id),
record_id=record_id,
)
return SessionRecordResponse(record=record)
@intercept_exceptions()
async def ingest_record_event(
self,
request: Request,
body: SessionRecordIngestRequest,
) -> dict:
project_id = request.state.project_id
if not await check_action_access(
user_uid=request.state.user_id,
project_id=project_id,
permission=Permission.RUN_SESSIONS,
):
raise FORBIDDEN_EXCEPTION
await publish_record(
organization_id=UUID(request.state.organization_id),
project_id=UUID(project_id),
record_event=SessionRecordEvent(
project_id=UUID(project_id),
session_id=body.session_id,
record_id=body.record_id,
record_index=body.record_index,
timestamp=body.timestamp,
record_type=body.record_type,
record_source=body.record_source,
attributes=body.attributes,
turn_id=body.turn_id,
span_id=body.span_id,
),
)
return {"ok": True}
class InteractionsRouter:
"""Interactions sub-router — /sessions/interactions/*"""
def __init__(
self,
*,
interactions_service: SessionInteractionsService,
workflows_service: WorkflowsService,
respond_task: Optional[Any] = None,
# InteractionsDispatcher (typed loosely, like respond_task: the API layer does not
# import the tasks layer). When present, the no-worker respond fallback goes through
# it so both paths share ONE answer-composition implementation.
interactions_dispatcher: Optional[Any] = None,
) -> None:
self.interactions_service = interactions_service
self.workflows_service = workflows_service
self.respond_task = respond_task
self.interactions_dispatcher = interactions_dispatcher
self.router = APIRouter()
self.router.add_api_route(
"/",
self.create_interaction,
methods=["POST"],
operation_id="create_interaction",
)
self.router.add_api_route(
"/query",
self.query_interactions,
methods=["POST"],
operation_id="query_interactions",
)
self.router.add_api_route(
"/transition",
self.transition_interaction,
methods=["POST"],
operation_id="transition_interaction",
)
self.router.add_api_route(
"/cancel-stale",
self.cancel_stale_interactions,
methods=["POST"],
operation_id="cancel_stale_interactions",
)
self.router.add_api_route(
"/{interaction_id}",
self.fetch_interaction,
methods=["GET"],
operation_id="fetch_interaction",
)
self.router.add_api_route(
"/{interaction_id}/respond",
self.respond_interaction,
methods=["POST"],
operation_id="respond_interaction",
)
@intercept_exceptions()
async def create_interaction(
self,
request: Request,
body: SessionInteractionCreateRequest,
) -> SessionInteractionResponse:
project_id: UUID = request.state.project_id
user_id: UUID = request.state.user_id
if not await check_action_access(
user_uid=str(user_id),
project_id=str(project_id),
permission=Permission.RUN_SESSIONS,
):
raise FORBIDDEN_EXCEPTION
interaction = await self.interactions_service.create_interaction(
project_id=project_id,
user_id=user_id,
interaction=SessionInteractionCreate(
project_id=project_id,
session_id=body.session_id,
turn_id=body.turn_id,
token=body.token,
kind=body.kind,
data=body.data,
flags=body.flags,
tags=body.tags,
meta=body.meta,
),
)
return SessionInteractionResponse(count=1, interaction=interaction)
@intercept_exceptions()
async def transition_interaction(
self,
request: Request,
body: SessionInteractionTransitionRequest,
) -> SessionInteractionResponse:
project_id: UUID = request.state.project_id
user_id: UUID = request.state.user_id
if not await check_action_access(
user_uid=str(user_id),
project_id=str(project_id),
permission=Permission.RUN_SESSIONS,
):
raise FORBIDDEN_EXCEPTION
resolution = (
body.resolution.model_dump() if body.resolution is not None else None
)
if resolution is not None:
interactions = await self.interactions_service.query_interactions(
project_id=project_id,
query=SessionInteractionQuery(session_id=body.session_id),
)
source = next(
(
interaction
for interaction in interactions
if interaction.token == body.token
),
None,
)
if source is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Interaction not found or already terminal",
)
if source.kind != SessionInteractionKind.user_approval:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Resolution is only valid for user approval interactions",
)
try:
interaction = await self.interactions_service.transition_interaction(
transition=SessionInteractionTransition(
project_id=project_id,
session_id=body.session_id,
token=body.token,
status=body.status,
resolution=resolution,
),
)
except InteractionNotFound:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Interaction not found or already terminal",
)
return SessionInteractionResponse(count=1, interaction=interaction)
@intercept_exceptions()
async def cancel_stale_interactions(
self,
request: Request,
body: SessionInteractionCancelStaleRequest,
) -> dict:
project_id: UUID = request.state.project_id
user_id: UUID = request.state.user_id
if not await check_action_access(
user_uid=str(user_id),
project_id=str(project_id),
permission=Permission.RUN_SESSIONS,
):
raise FORBIDDEN_EXCEPTION
cancelled = await self.interactions_service.cancel_session_pending(
project_id=project_id,
session_id=body.session_id,
except_turn_id=body.turn_id,
except_tokens=body.tokens,
)
return {"cancelled": cancelled}
@intercept_exceptions()
async def query_interactions(
self,
request: Request,
body: SessionInteractionQueryRequest,
) -> SessionInteractionsResponse:
project_id: UUID = request.state.project_id
authorized = await check_action_access(
user_uid=str(request.state.user_id),
project_id=str(project_id),
permission=Permission.VIEW_SESSIONS,
)
if not authorized:
raise FORBIDDEN_EXCEPTION
interactions = await self.interactions_service.query_interactions(
project_id=project_id,
query=body.query,
windowing=body.windowing,
)
return SessionInteractionsResponse(
count=len(interactions), interactions=interactions
)
@intercept_exceptions()
async def fetch_interaction(
self,
request: Request,
interaction_id: UUID,
) -> SessionInteractionResponse:
project_id: UUID = request.state.project_id
authorized = await check_action_access(
user_uid=str(request.state.user_id),
project_id=str(project_id),
permission=Permission.VIEW_SESSIONS,
)
if not authorized:
raise FORBIDDEN_EXCEPTION
try:
interaction = await self.interactions_service.fetch_interaction(
project_id=project_id,
interaction_id=interaction_id,
)
except InteractionNotFound:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Interaction not found",
)
return SessionInteractionResponse(count=1, interaction=interaction)
@intercept_exceptions()
async def respond_interaction(
self,
request: Request,
interaction_id: UUID,
body: SessionInteractionRespondRequest,
) -> SessionInteractionResponse:
project_id: UUID = request.state.project_id
user_id: UUID = request.state.user_id
authorized = await check_action_access(
user_uid=str(user_id),
project_id=str(project_id),
permission=Permission.RUN_SESSIONS,
)
if not authorized:
raise FORBIDDEN_EXCEPTION
try:
interaction = await self.interactions_service.fetch_interaction(
project_id=project_id,
interaction_id=interaction_id,
)
except InteractionNotFound:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Interaction not found",
)
if (
interaction.status
and interaction.status != SessionInteractionStatus.pending
):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Interaction is no longer pending",
)
answer = body.answer or {}
# CAS flips first: only the responder that wins the row enqueues, so
# concurrent responds fire exactly once.
try:
interaction = await self.interactions_service.transition_interaction(
transition=SessionInteractionTransition(
project_id=project_id,
session_id=interaction.session_id,
token=interaction.token,
status=SessionInteractionStatus.responded,
),
)
except InteractionNotFound:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Interaction is no longer pending",
)
# Enqueue onto the interactions worker when wired; otherwise fall back to the
# dispatcher directly (same answer composition, fired in-process), or as a last
# resort an inline blocking invoke (keeps minimal/test compositions usable).
if self.respond_task is not None: