sessionyard 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. agent_chat/001_core.sql +172 -0
  2. agent_chat/002_coordination.sql +63 -0
  3. agent_chat/003_harness_admission.sql +10 -0
  4. agent_chat/004_session_titles.sql +3 -0
  5. agent_chat/005_viewer.sql +9 -0
  6. agent_chat/006_quotas.sql +6 -0
  7. agent_chat/007_sender_receipts.sql +20 -0
  8. agent_chat/008_direct_threads.sql +49 -0
  9. agent_chat/009_pm_mark.sql +23 -0
  10. agent_chat/010_quota_backfill.sql +12 -0
  11. agent_chat/011_roles_and_work.sql +31 -0
  12. agent_chat/__init__.py +1 -0
  13. agent_chat/adapter.py +414 -0
  14. agent_chat/admin.py +524 -0
  15. agent_chat/api.py +641 -0
  16. agent_chat/auth.py +226 -0
  17. agent_chat/browser.py +118 -0
  18. agent_chat/browser_verify.py +487 -0
  19. agent_chat/browser_verify_artifacts.py +280 -0
  20. agent_chat/browser_verify_checks.py +236 -0
  21. agent_chat/browser_verify_run.py +523 -0
  22. agent_chat/cli.py +532 -0
  23. agent_chat/client.py +272 -0
  24. agent_chat/deliveries.py +555 -0
  25. agent_chat/events.py +48 -0
  26. agent_chat/feed.py +193 -0
  27. agent_chat/http_boundary.py +154 -0
  28. agent_chat/instance_client.py +349 -0
  29. agent_chat/instance_file.py +207 -0
  30. agent_chat/instance_worker.py +326 -0
  31. agent_chat/mcp/__init__.py +5 -0
  32. agent_chat/mcp/__main__.py +39 -0
  33. agent_chat/mcp/app.py +183 -0
  34. agent_chat/mcp/auth.py +67 -0
  35. agent_chat/mcp/config.py +55 -0
  36. agent_chat/mcp/tools.py +295 -0
  37. agent_chat/metrics.py +60 -0
  38. agent_chat/models.py +430 -0
  39. agent_chat/openapi.py +322 -0
  40. agent_chat/producer.py +208 -0
  41. agent_chat/protocol.py +71 -0
  42. agent_chat/publication.py +252 -0
  43. agent_chat/receipts.py +225 -0
  44. agent_chat/retention.py +154 -0
  45. agent_chat/roles.py +153 -0
  46. agent_chat/rooms.py +179 -0
  47. agent_chat/sessions.py +340 -0
  48. agent_chat/skills/agent-chat/SKILL.md +64 -0
  49. agent_chat/state.py +144 -0
  50. agent_chat/storage.py +110 -0
  51. agent_chat/threads.py +50 -0
  52. agent_chat/web/Manrope-OFL.txt +93 -0
  53. agent_chat/web/Manrope-Variable.ttf +0 -0
  54. agent_chat/web/chat.css +936 -0
  55. agent_chat/web/chat.js +1922 -0
  56. agent_chat/web/i18n.js +340 -0
  57. agent_chat/web/index.html +264 -0
  58. sessionyard-0.7.0.dist-info/METADATA +314 -0
  59. sessionyard-0.7.0.dist-info/RECORD +62 -0
  60. sessionyard-0.7.0.dist-info/WHEEL +4 -0
  61. sessionyard-0.7.0.dist-info/entry_points.txt +3 -0
  62. sessionyard-0.7.0.dist-info/licenses/LICENSE +661 -0
agent_chat/api.py ADDED
@@ -0,0 +1,641 @@
1
+ """Opt-in API factory. No credential loading, migrations, listener or activation on import."""
2
+
3
+ # Keep annotations eager: FastAPI's route dependencies refer to the factory-local connection function.
4
+ import asyncio
5
+ import json
6
+ import logging
7
+ import secrets
8
+ import time
9
+ from collections.abc import Iterator
10
+ from http import HTTPStatus
11
+ from importlib.resources import files
12
+ from typing import Annotated, Any, Literal
13
+ from uuid import UUID
14
+
15
+ from fastapi import Depends, FastAPI, Header, Query, Request, Response
16
+ from fastapi.encoders import jsonable_encoder
17
+ from fastapi.exceptions import RequestValidationError
18
+ from psycopg import Connection
19
+ from psycopg import Error as DatabaseError
20
+ from starlette.concurrency import run_in_threadpool
21
+ from starlette.exceptions import HTTPException
22
+ from starlette.responses import StreamingResponse
23
+
24
+ from . import browser, deliveries, feed, receipts, roles, sessions, state, threads
25
+ from . import events as event_store
26
+ from . import rooms as room_store
27
+ from .auth import authenticate, authenticate_producer, lock_actor
28
+ from .http_boundary import LOG, UNMATCHED, RequestBoundary, error_response, log_error
29
+ from .metrics import Metrics
30
+ from .models import (
31
+ BACKOFF_SECONDS,
32
+ DELIVERY_MAX_AGE_SECONDS,
33
+ HTTP_ERROR_STATUS,
34
+ LEASE_SECONDS,
35
+ REF_KEY_PATTERN,
36
+ STATE_KEY_PATTERN,
37
+ Actor,
38
+ ChatError,
39
+ DeliveryClaim,
40
+ DeliveryResult,
41
+ EmptyRequest,
42
+ Heartbeat,
43
+ LaneDeclaration,
44
+ Login,
45
+ Membership,
46
+ Mute,
47
+ PmMark,
48
+ Publication,
49
+ ReceiptDelivery,
50
+ Registration,
51
+ Reply,
52
+ Resolution,
53
+ RoleMark,
54
+ RoomCreation,
55
+ StateUpsert,
56
+ WorkDeclaration,
57
+ )
58
+ from .protocol import cursor, validate_origin
59
+ from .publication import publish
60
+ from .storage import MIGRATIONS, connect
61
+
62
+
63
+ def _log_handled(
64
+ level: int, request: Request, code: str, status: int, error: Exception, *, mid_stream: bool = False
65
+ ) -> None:
66
+ route = getattr(request.scope.get("route"), "path", UNMATCHED)
67
+ log_error(level, code, route, status, type(error).__name__, mid_stream=mid_stream)
68
+
69
+
70
+ def create_app(
71
+ dsn: str,
72
+ *,
73
+ enabled: bool = False,
74
+ public_origin: str | None = None,
75
+ delivery_enabled: bool = False,
76
+ stream_lifetime: float = 60,
77
+ stream_poll: float = 1,
78
+ ) -> FastAPI:
79
+ if not enabled:
80
+ raise ChatError("INTEGRATION_DISABLED")
81
+ if stream_lifetime <= 0 or stream_poll <= 0:
82
+ raise ValueError("event stream lifetime and poll interval must be positive")
83
+ if public_origin is not None:
84
+ try:
85
+ validate_origin(public_origin, https_only=True)
86
+ except ChatError:
87
+ raise ValueError("public_origin must be a canonical HTTPS origin") from None
88
+ metrics = Metrics()
89
+ metrics.gauge("agent_chat_sse_connections_active", 0)
90
+ app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None, redirect_slashes=False)
91
+ app.add_middleware(RequestBoundary, public_origin=public_origin, metrics=metrics)
92
+
93
+ @app.exception_handler(ChatError)
94
+ async def chat_error(request: Request, error: ChatError):
95
+ status = HTTP_ERROR_STATUS.get(error.code, 503)
96
+ _log_handled(logging.WARNING, request, error.code, status, error)
97
+ metrics.inc(
98
+ "agent_chat_http_errors_total",
99
+ {
100
+ "route": getattr(request.scope.get("route"), "path", UNMATCHED),
101
+ "status": str(status),
102
+ "code": error.code,
103
+ },
104
+ )
105
+ return error_response(error.code, status)
106
+
107
+ @app.exception_handler(RequestValidationError)
108
+ async def invalid_request(request: Request, error: RequestValidationError):
109
+ # FastAPI's default includes the submitted input, which can be private.
110
+ _log_handled(logging.WARNING, request, "INVALID_REQUEST", 422, error)
111
+ metrics.inc(
112
+ "agent_chat_http_errors_total",
113
+ {
114
+ "route": getattr(request.scope.get("route"), "path", UNMATCHED),
115
+ "status": "422",
116
+ "code": "INVALID_REQUEST",
117
+ },
118
+ )
119
+ return error_response("INVALID_REQUEST", 422)
120
+
121
+ @app.exception_handler(DatabaseError)
122
+ async def database_error(request: Request, error: DatabaseError):
123
+ _log_handled(logging.ERROR, request, "DATABASE_UNAVAILABLE", 503, error)
124
+ metrics.inc(
125
+ "agent_chat_http_errors_total",
126
+ {
127
+ "route": getattr(request.scope.get("route"), "path", UNMATCHED),
128
+ "status": "503",
129
+ "code": "DATABASE_UNAVAILABLE",
130
+ },
131
+ )
132
+ return error_response("DATABASE_UNAVAILABLE", 503)
133
+
134
+ @app.exception_handler(HTTPException)
135
+ async def http_error(request: Request, error: HTTPException):
136
+ # Unknown routes and methods. FastAPI's default {"detail": ...} is not this API's envelope.
137
+ code = HTTPStatus(error.status_code).name
138
+ _log_handled(logging.WARNING, request, code, error.status_code, error)
139
+ metrics.inc(
140
+ "agent_chat_http_errors_total",
141
+ {
142
+ "route": getattr(request.scope.get("route"), "path", UNMATCHED),
143
+ "status": str(error.status_code),
144
+ "code": code,
145
+ },
146
+ )
147
+ return error_response(code, error.status_code, error.headers)
148
+
149
+ @app.exception_handler(Exception)
150
+ async def unexpected_error(_request: Request, _error: Exception):
151
+ # Runs outside RequestBoundary, so the security headers come from error_response itself.
152
+ # The body names nothing; the server still logs the traceback.
153
+ return error_response("INTERNAL_ERROR", 500)
154
+
155
+ def connection() -> Iterator[Connection[dict[str, Any]]]:
156
+ with connect(dsn) as db:
157
+ yield db
158
+
159
+ def bearer(request: Request) -> str:
160
+ authorization = request.headers.get("authorization", "")
161
+ scheme, separator, token = authorization.partition(" ")
162
+ if scheme.lower() != "bearer" or not separator:
163
+ raise ChatError("UNAUTHENTICATED")
164
+ return token
165
+
166
+ def current_actor(request: Request, db: Connection[dict[str, Any]]) -> Actor:
167
+ cookie = request.cookies.get(browser.SESSION_COOKIE)
168
+ if cookie is None:
169
+ return authenticate(db, bearer(request))
170
+ if request.method not in ("GET", "HEAD", "OPTIONS"):
171
+ browser.check_csrf(cookie, request.headers.get("x-csrf-token", ""))
172
+ return browser.authenticate_cookie(db, cookie)
173
+
174
+ if public_origin is not None:
175
+
176
+ @app.get("/")
177
+ def viewer():
178
+ return Response(files("agent_chat").joinpath("web/index.html").read_bytes(), media_type="text/html")
179
+
180
+ @app.get("/ui/{asset}")
181
+ def viewer_asset(asset: str):
182
+ # No generic directory mount, path joining from arbitrary input or index listing.
183
+ assets = {
184
+ "chat.js": "text/javascript",
185
+ "i18n.js": "text/javascript",
186
+ "chat.css": "text/css",
187
+ "Manrope-Variable.ttf": "font/ttf",
188
+ }
189
+ if asset not in assets:
190
+ raise ChatError("NOT_FOUND")
191
+ return Response(files("agent_chat").joinpath("web", asset).read_bytes(), media_type=assets[asset])
192
+
193
+ @app.get("/v1/login")
194
+ def login_challenge(response: Response):
195
+ nonce = secrets.token_hex(32)
196
+ response.set_cookie(
197
+ browser.LOGIN_COOKIE, nonce, max_age=600, path="/", secure=True, httponly=True, samesite="strict"
198
+ )
199
+ return {"csrf_token": browser.csrf(nonce)}
200
+
201
+ @app.post("/v1/login")
202
+ def login(
203
+ payload: Login,
204
+ request: Request,
205
+ response: Response,
206
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
207
+ ):
208
+ browser.check_csrf(request.cookies.get(browser.LOGIN_COOKIE, ""), request.headers.get("x-csrf-token", ""))
209
+ session = browser.login(db, payload.token, request.cookies.get(browser.SESSION_COOKIE))
210
+ response.set_cookie(
211
+ browser.SESSION_COOKIE,
212
+ session.token,
213
+ max_age=session.expires_in,
214
+ path="/",
215
+ secure=True,
216
+ httponly=True,
217
+ samesite="strict",
218
+ )
219
+ response.delete_cookie(browser.LOGIN_COOKIE, path="/", secure=True, httponly=True, samesite="strict")
220
+ return {
221
+ "csrf_token": browser.csrf(session.token),
222
+ "expires_in": session.expires_in,
223
+ "access": session.access,
224
+ }
225
+
226
+ @app.get("/v1/browser/session")
227
+ def browser_session(request: Request, db: Annotated[Connection[dict[str, Any]], Depends(connection)]):
228
+ actor = current_actor(request, db)
229
+ if actor.browser_session_hash is None:
230
+ raise ChatError("UNAUTHENTICATED")
231
+ with db.transaction():
232
+ access = lock_actor(db, actor, read=True)
233
+ return {
234
+ "principal_id": actor.principal_id,
235
+ "access": access,
236
+ "csrf_token": browser.csrf(request.cookies[browser.SESSION_COOKIE]),
237
+ }
238
+
239
+ @app.post("/v1/logout")
240
+ def logout(
241
+ request: Request,
242
+ response: Response,
243
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
244
+ payload: EmptyRequest = EmptyRequest(),
245
+ ):
246
+ browser.logout(db, current_actor(request, db))
247
+ response.delete_cookie(browser.SESSION_COOKIE, path="/", secure=True, httponly=True, samesite="strict")
248
+ return {"status": "logged_out"}
249
+
250
+ @app.get("/healthz")
251
+ def health():
252
+ return {"status": "ok"}
253
+
254
+ @app.get("/readyz")
255
+ def ready(db: Annotated[Connection[dict[str, Any]], Depends(connection)]):
256
+ # Readiness requires the application schema, not merely a reachable PostgreSQL.
257
+ if (
258
+ db.execute(
259
+ """
260
+ SELECT 1 FROM agent_chat.event_clock WHERE singleton
261
+ AND (SELECT array_agg(version ORDER BY version) FROM agent_chat.schema_migrations) = %s::integer[]
262
+ """,
263
+ (list(range(1, len(MIGRATIONS) + 1)),),
264
+ ).fetchone()
265
+ is None
266
+ ):
267
+ raise ChatError("SCHEMA_MISMATCH")
268
+ return {"status": "ready"}
269
+
270
+ @app.post("/v1/sessions")
271
+ def register(
272
+ payload: Registration,
273
+ token: Annotated[str, Depends(bearer)],
274
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
275
+ ):
276
+ return sessions.register(db, authenticate(db, token, registration=True), payload)
277
+
278
+ @app.post("/v1/instance/heartbeat")
279
+ def heartbeat(
280
+ payload: Heartbeat,
281
+ token: Annotated[str, Depends(bearer)],
282
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
283
+ ):
284
+ return sessions.heartbeat(db, authenticate(db, token), payload)
285
+
286
+ @app.post("/v1/instance/lane")
287
+ def declare_lane(
288
+ payload: LaneDeclaration,
289
+ token: Annotated[str, Depends(bearer)],
290
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
291
+ ):
292
+ return sessions.declare_lane(db, authenticate(db, token), payload)
293
+
294
+ @app.post("/v1/instance/work")
295
+ def declare_work(
296
+ payload: WorkDeclaration,
297
+ token: Annotated[str, Depends(bearer)],
298
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
299
+ ):
300
+ return sessions.declare_work(db, authenticate(db, token), payload)
301
+
302
+ @app.post("/v1/instance/end")
303
+ def end(
304
+ token: Annotated[str, Depends(bearer)],
305
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
306
+ payload: EmptyRequest = EmptyRequest(),
307
+ ):
308
+ return sessions.end(db, authenticate(db, token))
309
+
310
+ @app.get("/v1/instance/status")
311
+ def instance_status(
312
+ token: Annotated[str, Depends(bearer)], db: Annotated[Connection[dict[str, Any]], Depends(connection)]
313
+ ):
314
+ return sessions.status(db, authenticate(db, token), delivery_enabled=delivery_enabled)
315
+
316
+ @app.get("/v1/instance/deliveries/pending")
317
+ def pending_deliveries(
318
+ token: Annotated[str, Depends(bearer)], db: Annotated[Connection[dict[str, Any]], Depends(connection)]
319
+ ):
320
+ actor = authenticate(db, token)
321
+ if not delivery_enabled:
322
+ raise ChatError("DELIVERY_DISABLED")
323
+ return deliveries.pending(db, actor)
324
+
325
+ @app.post("/v1/instance/deliveries/claim")
326
+ def claim_delivery(
327
+ payload: DeliveryClaim,
328
+ token: Annotated[str, Depends(bearer)],
329
+ key: Annotated[UUID, Header(alias="Idempotency-Key")],
330
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
331
+ ):
332
+ actor = authenticate(db, token)
333
+ if not delivery_enabled:
334
+ raise ChatError("DELIVERY_DISABLED")
335
+ return deliveries.claim(db, actor, key, payload)
336
+
337
+ @app.post("/v1/instance/deliveries/{attempt}/result")
338
+ def delivery_result(
339
+ attempt: UUID,
340
+ payload: DeliveryResult,
341
+ token: Annotated[str, Depends(bearer)],
342
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
343
+ ):
344
+ # Disabling new admissions must not discard an already-issued reservation's evidence.
345
+ return deliveries.result(db, authenticate(db, token), attempt, payload)
346
+
347
+ @app.get("/v1/instance/receipts")
348
+ def sender_receipts(
349
+ token: Annotated[str, Depends(bearer)], db: Annotated[Connection[dict[str, Any]], Depends(connection)]
350
+ ):
351
+ # The sender's non-waking receipt ledger is independent of delivery admission: an ack needs no claim.
352
+ return receipts.sender_feed(db, authenticate(db, token))
353
+
354
+ @app.post("/v1/instance/receipts/delivered")
355
+ def sender_receipts_delivered(
356
+ payload: ReceiptDelivery,
357
+ token: Annotated[str, Depends(bearer)],
358
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
359
+ ):
360
+ return receipts.mark_delivered(db, authenticate(db, token), payload)
361
+
362
+ @app.post("/v1/sessions/{session}/mute")
363
+ def mute(
364
+ session: UUID, payload: Mute, request: Request, db: Annotated[Connection[dict[str, Any]], Depends(connection)]
365
+ ):
366
+ return sessions.mute(db, current_actor(request, db), session, payload.muted)
367
+
368
+ @app.post("/v1/threads/{thread}/resolution")
369
+ def resolve_thread(
370
+ thread: UUID,
371
+ payload: Resolution,
372
+ request: Request,
373
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
374
+ ):
375
+ return threads.resolve(db, current_actor(request, db), thread, payload.resolved)
376
+
377
+ @app.post("/v1/messages/{message}/ack")
378
+ def acknowledge(
379
+ message: UUID,
380
+ token: Annotated[str, Depends(bearer)],
381
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
382
+ payload: EmptyRequest = EmptyRequest(),
383
+ ):
384
+ return receipts.acknowledge(db, authenticate(db, token), message)
385
+
386
+ @app.post("/v1/messages/{message}/replies")
387
+ def reply(
388
+ message: UUID,
389
+ payload: Reply,
390
+ request: Request,
391
+ key: Annotated[UUID, Header(alias="Idempotency-Key")],
392
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
393
+ ):
394
+ actor = current_actor(request, db)
395
+ with db.transaction():
396
+ event_store.lock(db)
397
+ # `publish` answers a repeated key before it reads the parent, so a replay survives the parent's expiry.
398
+ parent = receipts.locate(db, actor, message)
399
+ publication = Publication(
400
+ kind="reply",
401
+ body=payload.body,
402
+ recipients=payload.recipients,
403
+ reply_to=message,
404
+ receipts=payload.receipts,
405
+ )
406
+ return feed.message_view(publish(db, actor, parent["room_id"], key, publication))
407
+
408
+ @app.get("/v1/rooms")
409
+ def rooms(
410
+ request: Request,
411
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
412
+ ):
413
+ return {"rooms": room_store.visible(db, current_actor(request, db), read=True)}
414
+
415
+ @app.post("/v1/rooms")
416
+ def create_room(
417
+ payload: RoomCreation, request: Request, db: Annotated[Connection[dict[str, Any]], Depends(connection)]
418
+ ):
419
+ return room_store.create(db, current_actor(request, db), payload)
420
+
421
+ @app.post("/v1/rooms/{room}/memberships")
422
+ def join_room(
423
+ room: UUID,
424
+ payload: Membership,
425
+ request: Request,
426
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
427
+ ):
428
+ return room_store.join(db, current_actor(request, db), room, payload.session_id)
429
+
430
+ @app.post("/v1/rooms/{room}/pm")
431
+ def pm_mark(
432
+ room: UUID, payload: PmMark, request: Request, db: Annotated[Connection[dict[str, Any]], Depends(connection)]
433
+ ):
434
+ # Operator only: the domain call refuses every other credential before it reads or writes the mark.
435
+ change = roles.assign if payload.pm else roles.clear
436
+ result = change(db, current_actor(request, db), room, "pm", payload.session_id)
437
+ # The domain call has committed. A refused or rolled-back call raised and never logs. The line holds
438
+ # identifiers only; it is the audit trail of the mark, which has no event or history table of its own.
439
+ LOG.info("pm_mark action=%s room=%s session=%s", "set" if payload.pm else "clear", room, payload.session_id)
440
+ return {"room_id": result["room_id"], "pm": result["roles"]["pm"]}
441
+
442
+ @app.post("/v1/rooms/{room}/roles")
443
+ def role_mark(
444
+ room: UUID, payload: RoleMark, request: Request, db: Annotated[Connection[dict[str, Any]], Depends(connection)]
445
+ ):
446
+ # Operator only: the domain call refuses every other credential before it reads or writes a mark.
447
+ change = roles.assign if payload.assigned else roles.clear
448
+ result = change(db, current_actor(request, db), room, payload.role, payload.session_id)
449
+ LOG.info(
450
+ "role_mark action=%s role=%s room=%s session=%s",
451
+ "set" if payload.assigned else "clear",
452
+ payload.role,
453
+ room,
454
+ payload.session_id,
455
+ )
456
+ return result
457
+
458
+ @app.get("/v1/rooms/{room}/participants")
459
+ def participants(
460
+ room: UUID,
461
+ request: Request,
462
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
463
+ after_session: UUID | None = None,
464
+ limit: Annotated[int, Query(ge=1, le=100)] = 100,
465
+ online: bool = False,
466
+ ):
467
+ return room_store.participants(db, current_actor(request, db), room, after_session, limit, online)
468
+
469
+ @app.get("/v1/rooms/{room}/history")
470
+ def history(
471
+ room: UUID,
472
+ request: Request,
473
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
474
+ after: str | None = None,
475
+ limit: Annotated[int, Query(ge=1, le=100)] = 100,
476
+ thread_id: UUID | None = None,
477
+ before: str | None = None,
478
+ ref_key: Annotated[str | None, Query(pattern=REF_KEY_PATTERN)] = None,
479
+ sender_role: Literal[
480
+ "pm", "forgejo_pm", "forgejo-pm", "github_pm", "github-pm", "delivery_manager", "delivery-manager", "dm"
481
+ ]
482
+ | None = None,
483
+ ):
484
+ return feed.history(
485
+ db,
486
+ current_actor(request, db),
487
+ room,
488
+ cursor(after) if after is not None else None,
489
+ limit,
490
+ thread_id,
491
+ cursor(before) if before is not None else None,
492
+ ref_key,
493
+ sender_role,
494
+ )
495
+
496
+ @app.post("/v1/rooms/{room}/state")
497
+ def upsert_state(
498
+ room: UUID,
499
+ payload: StateUpsert,
500
+ token: Annotated[str, Depends(bearer)],
501
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
502
+ ):
503
+ # A producer credential, never a cookie: authenticate_producer is the only door it opens.
504
+ return state.upsert(db, authenticate_producer(db, token), room, payload)
505
+
506
+ @app.get("/v1/rooms/{room}/state")
507
+ def read_state(
508
+ room: UUID,
509
+ request: Request,
510
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
511
+ ref_key: Annotated[str | None, Query(pattern=REF_KEY_PATTERN)] = None,
512
+ after_key: Annotated[str | None, Query(pattern=STATE_KEY_PATTERN)] = None,
513
+ limit: Annotated[int, Query(ge=1, le=100)] = 100,
514
+ ):
515
+ return state.read(db, current_actor(request, db), room, ref_key, after_key, limit)
516
+
517
+ @app.get("/v1/events")
518
+ async def events(request: Request, after: str = "0"):
519
+ position = cursor(after)
520
+ header = request.headers.get("last-event-id")
521
+ if header is not None:
522
+ position = cursor(header) # Both inputs are validated; header wins.
523
+
524
+ def read_batch(cursor: int, expected: tuple[UUID, ...] | None):
525
+ # Never suspend an HTTP stream with a database connection or row lock held.
526
+ with connect(dsn) as db:
527
+ return feed.events(db, current_actor(request, db), cursor, expected)
528
+
529
+ batch = await run_in_threadpool(read_batch, position, None)
530
+
531
+ async def _stream():
532
+ nonlocal batch
533
+ started = last_comment = time.monotonic()
534
+ yield ": connected\n\n"
535
+ while True:
536
+ for event in batch["events"]:
537
+ data = json.dumps(jsonable_encoder(event["data"]), separators=(",", ":"))
538
+ yield f"id: {event['id']}\nevent: {event['event']}\ndata: {data}\n\n"
539
+ # Bound each connection lifetime; reconnect uses the last durable event ID.
540
+ if time.monotonic() - started >= stream_lifetime:
541
+ return
542
+ # A full page means the client is behind; poll only once it has caught up.
543
+ if not batch["full"]:
544
+ await asyncio.sleep(stream_poll)
545
+ try:
546
+ batch = await run_in_threadpool(read_batch, batch["next_cursor"], batch["rooms"])
547
+ except (ChatError, DatabaseError) as error:
548
+ code = error.code if isinstance(error, ChatError) else "DATABASE_UNAVAILABLE"
549
+ level = logging.WARNING if isinstance(error, ChatError) else logging.ERROR
550
+ _log_handled(level, request, code, 200, error, mid_stream=True)
551
+ # Headers already went out. This control has no id and cannot advance replay.
552
+ yield "event: control\ndata: " + json.dumps({"error": {"code": code}}) + "\n\n"
553
+ return
554
+ if time.monotonic() - last_comment >= 15:
555
+ yield ": keepalive\n\n"
556
+ last_comment = time.monotonic()
557
+
558
+ async def stream():
559
+ metrics.adjust("agent_chat_sse_connections_active", 1)
560
+ try:
561
+ async for chunk in _stream():
562
+ yield chunk
563
+ finally:
564
+ metrics.adjust("agent_chat_sse_connections_active", -1)
565
+
566
+ return StreamingResponse(
567
+ stream(), media_type="text/event-stream", headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"}
568
+ )
569
+
570
+ @app.post("/v1/rooms/{room}/messages")
571
+ def message(
572
+ room: UUID,
573
+ payload: Publication,
574
+ key: Annotated[UUID, Header(alias="Idempotency-Key")],
575
+ request: Request,
576
+ db: Annotated[Connection[dict[str, Any]], Depends(connection)],
577
+ ):
578
+ stored = publish(db, current_actor(request, db), room, key, payload)
579
+ return feed.message_view(stored)
580
+
581
+ @app.get("/metrics")
582
+ def metrics_route(db: Annotated[Connection[dict[str, Any]], Depends(connection)]):
583
+ counts = db.execute(
584
+ """
585
+ SELECT
586
+ (SELECT count(*) FROM agent_chat.instances
587
+ WHERE ended_at IS NULL
588
+ AND heartbeat_at > clock_timestamp() - make_interval(secs => %s)) AS instances,
589
+ (WITH eligible AS MATERIALIZED (
590
+ SELECT r.message_id, r.session_id, r.delivery_batch_id
591
+ FROM agent_chat.recipients r
592
+ JOIN agent_chat.messages m ON m.id = r.message_id
593
+ WHERE m.kind IN ('question', 'consultation', 'reply')
594
+ AND m.body IS NOT NULL
595
+ AND m.expires_at > clock_timestamp()
596
+ AND r.handed_at IS NULL
597
+ AND r.acknowledged_at IS NULL
598
+ AND r.replying_message_id IS NULL
599
+ AND r.uncertainty_reason IS NULL
600
+ AND r.stored_at > clock_timestamp() - make_interval(secs => %s)
601
+ ), retry AS (
602
+ SELECT b.id
603
+ FROM agent_chat.delivery_batches b
604
+ JOIN LATERAL (
605
+ SELECT outcome, ordinal, completed_at
606
+ FROM agent_chat.delivery_attempts
607
+ WHERE batch_id = b.id ORDER BY ordinal DESC LIMIT 1
608
+ ) last ON true
609
+ WHERE last.outcome IN ('failed', 'deferred')
610
+ AND last.ordinal < 3
611
+ AND last.completed_at + make_interval(
612
+ secs => CASE WHEN last.ordinal = 1 THEN %s ELSE %s END
613
+ ) <= clock_timestamp()
614
+ AND NOT EXISTS (
615
+ SELECT 1 FROM unnest(b.message_ids) AS item(id)
616
+ WHERE NOT EXISTS (
617
+ SELECT 1 FROM eligible e
618
+ WHERE e.message_id = item.id AND e.session_id = b.session_id
619
+ )
620
+ )
621
+ )
622
+ SELECT count(*) FROM eligible e
623
+ WHERE e.delivery_batch_id IS NULL
624
+ OR e.delivery_batch_id IN (SELECT id FROM retry)) AS pending,
625
+ (SELECT count(*) FROM agent_chat.recipients r
626
+ JOIN agent_chat.messages m ON m.id = r.message_id
627
+ WHERE r.uncertainty_reason IS NOT NULL
628
+ AND r.acknowledged_at IS NULL
629
+ AND r.replying_message_id IS NULL
630
+ AND m.expires_at > clock_timestamp()) AS uncertain
631
+ """,
632
+ (LEASE_SECONDS, DELIVERY_MAX_AGE_SECONDS, BACKOFF_SECONDS[0], BACKOFF_SECONDS[1]),
633
+ ).fetchone()
634
+ if counts is None: # an aggregate SELECT always yields a row; this is the same refusal as `events._take`
635
+ raise ChatError("SCHEMA_MISMATCH")
636
+ metrics.gauge("agent_chat_instances_active", counts["instances"])
637
+ metrics.gauge("agent_chat_delivery_pending", counts["pending"])
638
+ metrics.gauge("agent_chat_delivery_uncertain", counts["uncertain"])
639
+ return Response(metrics.render(), media_type="text/plain; version=0.0.4")
640
+
641
+ return app