agent2dashboard 0.2.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 (79) hide show
  1. agent2dashboard/__init__.py +593 -0
  2. agent2dashboard/__main__.py +3 -0
  3. agent2dashboard/_env.py +79 -0
  4. agent2dashboard/a2ui/__init__.py +1 -0
  5. agent2dashboard/a2ui/catalogs/dashboard/v1/catalog.json +496 -0
  6. agent2dashboard/a2ui/checks.py +656 -0
  7. agent2dashboard/a2ui/express.py +349 -0
  8. agent2dashboard/a2ui/layout_actions.py +409 -0
  9. agent2dashboard/a2ui/render.py +252 -0
  10. agent2dashboard/a2ui/state.py +600 -0
  11. agent2dashboard/a2ui/surfaces.py +23 -0
  12. agent2dashboard/agent/__init__.py +83 -0
  13. agent2dashboard/agent/builtin_tools.py +258 -0
  14. agent2dashboard/agent/history.py +218 -0
  15. agent2dashboard/agent/loop.py +341 -0
  16. agent2dashboard/agent/prompt.py +66 -0
  17. agent2dashboard/agent/tools.py +162 -0
  18. agent2dashboard/agent/turn.py +201 -0
  19. agent2dashboard/auth.py +350 -0
  20. agent2dashboard/cli/__init__.py +50 -0
  21. agent2dashboard/errors.py +18 -0
  22. agent2dashboard/http/__init__.py +40 -0
  23. agent2dashboard/http/dashboards.py +100 -0
  24. agent2dashboard/http/functions.py +462 -0
  25. agent2dashboard/http/queries.py +168 -0
  26. agent2dashboard/http/revisions.py +126 -0
  27. agent2dashboard/http/router.py +353 -0
  28. agent2dashboard/http/schemas.py +102 -0
  29. agent2dashboard/llm/__init__.py +7 -0
  30. agent2dashboard/llm/_messages_api.py +123 -0
  31. agent2dashboard/llm/bedrock.py +96 -0
  32. agent2dashboard/llm/direct.py +40 -0
  33. agent2dashboard/llm/messages.py +45 -0
  34. agent2dashboard/migrations/__init__.py +383 -0
  35. agent2dashboard/migrations/versions/0001_initial.py +228 -0
  36. agent2dashboard/ports.py +538 -0
  37. agent2dashboard/py.typed +0 -0
  38. agent2dashboard/query/__init__.py +65 -0
  39. agent2dashboard/query/errors.py +39 -0
  40. agent2dashboard/query/executor.py +203 -0
  41. agent2dashboard/query/filters.py +446 -0
  42. agent2dashboard/query/governed.py +155 -0
  43. agent2dashboard/query/readonly.py +166 -0
  44. agent2dashboard/query/registry.py +213 -0
  45. agent2dashboard/query/row_filter.py +135 -0
  46. agent2dashboard/query/service.py +93 -0
  47. agent2dashboard/query/sql_guard.py +219 -0
  48. agent2dashboard/runs/__init__.py +87 -0
  49. agent2dashboard/runs/errors.py +65 -0
  50. agent2dashboard/runs/events.py +147 -0
  51. agent2dashboard/runs/hooks.py +135 -0
  52. agent2dashboard/runs/http.py +169 -0
  53. agent2dashboard/runs/memory.py +148 -0
  54. agent2dashboard/runs/redis_bus.py +219 -0
  55. agent2dashboard/runs/service.py +728 -0
  56. agent2dashboard/runs/writer.py +95 -0
  57. agent2dashboard/semantic/__init__.py +6 -0
  58. agent2dashboard/semantic/cube.py +39 -0
  59. agent2dashboard/semantic/static.py +81 -0
  60. agent2dashboard/storage/__init__.py +60 -0
  61. agent2dashboard/storage/lifecycle.py +105 -0
  62. agent2dashboard/storage/memory.py +488 -0
  63. agent2dashboard/storage/records.py +219 -0
  64. agent2dashboard/storage/sql.py +666 -0
  65. agent2dashboard/storage/tables.py +387 -0
  66. agent2dashboard/testing/__init__.py +20 -0
  67. agent2dashboard/testing/event_bus.py +10 -0
  68. agent2dashboard/testing/fake_llm.py +129 -0
  69. agent2dashboard/testing/host.py +191 -0
  70. agent2dashboard/tracing/__init__.py +36 -0
  71. agent2dashboard/tracing/db.py +143 -0
  72. agent2dashboard/tracing/fanout.py +153 -0
  73. agent2dashboard/tracing/langfuse.py +339 -0
  74. agent2dashboard/tracing/masking.py +26 -0
  75. agent2dashboard-0.2.0.dist-info/METADATA +81 -0
  76. agent2dashboard-0.2.0.dist-info/RECORD +79 -0
  77. agent2dashboard-0.2.0.dist-info/WHEEL +4 -0
  78. agent2dashboard-0.2.0.dist-info/entry_points.txt +3 -0
  79. agent2dashboard-0.2.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,666 @@
1
+ """`SqlAlchemyStorage`: the default `Storage`, over the host's `AsyncSession` factory (§3.7).
2
+
3
+ These repositories are the only SQL the SDK writes against its own tables.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import uuid
9
+ from collections.abc import AsyncIterator, Callable, Mapping, Sequence
10
+ from contextlib import AbstractAsyncContextManager, asynccontextmanager
11
+ from datetime import datetime
12
+ from typing import Any, Literal
13
+
14
+ from sqlalchemy import delete, func, insert, select, update
15
+ from sqlalchemy.dialects.postgresql import insert as pg_insert
16
+ from sqlalchemy.exc import IntegrityError
17
+ from sqlalchemy.ext.asyncio import AsyncSession
18
+
19
+ from agent2dashboard.ports import RunStatus
20
+ from agent2dashboard.storage.records import (
21
+ ActiveRunExists,
22
+ ConversationRecord,
23
+ DashboardRecord,
24
+ DuplicateClientMessage,
25
+ LlmCallRecord,
26
+ MessageRecord,
27
+ NewLlmCall,
28
+ NotFound,
29
+ RevisionConflict,
30
+ RevisionRecord,
31
+ RevisionSource,
32
+ RunRecord,
33
+ to_new_llm_call,
34
+ )
35
+ from agent2dashboard.storage.tables import (
36
+ ACTIVE_RUN_STATUSES,
37
+ PrincipalColumn,
38
+ StorageTables,
39
+ TableNames,
40
+ build_tables,
41
+ client_message_constraint_name,
42
+ )
43
+
44
+ __all__ = ["SqlAlchemyStorage"]
45
+
46
+ SessionFactory = Callable[[], AsyncSession]
47
+ _Scope = Callable[[], AbstractAsyncContextManager[AsyncSession]]
48
+ _ACTIVE = [s.value for s in ACTIVE_RUN_STATUSES]
49
+ _TERMINAL = {RunStatus.SUCCEEDED, RunStatus.FAILED, RunStatus.CANCELLED, RunStatus.INTERRUPTED}
50
+
51
+
52
+ def _violated(exc: IntegrityError, constraint: str) -> bool:
53
+ diag = getattr(getattr(exc, "orig", None), "diag", None)
54
+ name = getattr(diag, "constraint_name", None)
55
+ return name == constraint if name else constraint in str(exc.orig)
56
+
57
+
58
+ def _at(at: datetime | None) -> Any:
59
+ return at if at is not None else func.now()
60
+
61
+
62
+ class _Repo:
63
+ def __init__(self, scope: _Scope, tables: StorageTables) -> None:
64
+ self._scope = scope
65
+ self._t = tables
66
+
67
+
68
+ class _ConversationRepo(_Repo):
69
+ async def create(
70
+ self, *, principal_id: str, title: str | None = None, conversation_id: str | None = None
71
+ ) -> ConversationRecord:
72
+ c = self._t.conversation
73
+ stmt = (
74
+ insert(c)
75
+ .values(id=conversation_id or str(uuid.uuid4()), principal_id=principal_id, title=title)
76
+ .returning(*c.c)
77
+ )
78
+ async with self._scope() as s:
79
+ row = (await s.execute(stmt)).one()
80
+ return _conversation(row)
81
+
82
+ async def get(
83
+ self, conversation_id: str, *, principal_id: str | None = None
84
+ ) -> ConversationRecord | None:
85
+ c = self._t.conversation
86
+ stmt = select(c).where(c.c.id == conversation_id)
87
+ if principal_id is not None:
88
+ stmt = stmt.where(c.c.principal_id == principal_id)
89
+ async with self._scope() as s:
90
+ row = (await s.execute(stmt)).one_or_none()
91
+ return _conversation(row) if row else None
92
+
93
+ async def list_for_principal(
94
+ self, principal_id: str, *, limit: int = 50, before: datetime | None = None
95
+ ) -> list[ConversationRecord]:
96
+ c = self._t.conversation
97
+ stmt = select(c).where(c.c.principal_id == principal_id)
98
+ if before is not None:
99
+ stmt = stmt.where(c.c.last_message_at < before)
100
+ stmt = stmt.order_by(c.c.last_message_at.desc(), c.c.id).limit(limit)
101
+ async with self._scope() as s:
102
+ rows = (await s.execute(stmt)).all()
103
+ return [_conversation(r) for r in rows]
104
+
105
+ async def rename(self, conversation_id: str, title: str | None) -> bool:
106
+ c = self._t.conversation
107
+ stmt = (
108
+ update(c)
109
+ .where(c.c.id == conversation_id)
110
+ .values(title=title, updated_at=func.now())
111
+ .returning(c.c.id)
112
+ )
113
+ async with self._scope() as s:
114
+ return (await s.execute(stmt)).first() is not None
115
+
116
+ async def touch(self, conversation_id: str, *, at: datetime | None = None) -> None:
117
+ c = self._t.conversation
118
+ async with self._scope() as s:
119
+ await s.execute(
120
+ update(c)
121
+ .where(c.c.id == conversation_id)
122
+ .values(last_message_at=_at(at), updated_at=_at(at))
123
+ )
124
+
125
+ async def delete(self, conversation_id: str) -> bool:
126
+ t = self._t
127
+ # Explicit, in dependency order, so the result does not depend on FK cascades.
128
+ run_ids = select(t.run.c.id).where(t.run.c.conversation_id == conversation_id)
129
+ async with self._scope() as s:
130
+ await s.execute(delete(t.llm_call).where(t.llm_call.c.run_id.in_(run_ids)))
131
+ await s.execute(
132
+ delete(t.dashboard_revision).where(
133
+ t.dashboard_revision.c.conversation_id == conversation_id
134
+ )
135
+ )
136
+ await s.execute(
137
+ delete(t.dashboard).where(t.dashboard.c.conversation_id == conversation_id)
138
+ )
139
+ await s.execute(delete(t.run).where(t.run.c.conversation_id == conversation_id))
140
+ await s.execute(delete(t.message).where(t.message.c.conversation_id == conversation_id))
141
+ row = (
142
+ await s.execute(
143
+ delete(t.conversation)
144
+ .where(t.conversation.c.id == conversation_id)
145
+ .returning(t.conversation.c.id)
146
+ )
147
+ ).first()
148
+ return row is not None
149
+
150
+ async def list_inactive(self, *, before: datetime, limit: int = 100) -> list[str]:
151
+ c = self._t.conversation
152
+ stmt = (
153
+ select(c.c.id)
154
+ .where(c.c.last_message_at < before)
155
+ .order_by(c.c.last_message_at, c.c.id)
156
+ .limit(limit)
157
+ )
158
+ async with self._scope() as s:
159
+ return [str(r[0]) for r in (await s.execute(stmt)).all()]
160
+
161
+
162
+ class _MessageRepo(_Repo):
163
+ async def add(
164
+ self,
165
+ *,
166
+ conversation_id: str,
167
+ role: Literal["user", "assistant"],
168
+ content: str,
169
+ stop_reason: str | None = None,
170
+ input_tokens: int | None = None,
171
+ output_tokens: int | None = None,
172
+ run_id: str | None = None,
173
+ a2ui: str | None = None,
174
+ revision: int | None = None,
175
+ tool_trace: Sequence[Mapping[str, Any]] | None = None,
176
+ client_message_id: str | None = None,
177
+ note: Mapping[str, Any] | None = None,
178
+ ) -> MessageRecord:
179
+ t = self._t
180
+ touched = (
181
+ update(t.conversation)
182
+ .where(t.conversation.c.id == conversation_id)
183
+ .values(last_message_at=func.now(), updated_at=func.now())
184
+ .returning(t.conversation.c.id)
185
+ )
186
+ stmt = (
187
+ insert(t.message)
188
+ .values(
189
+ conversation_id=conversation_id,
190
+ role=role,
191
+ content=content,
192
+ stop_reason=stop_reason,
193
+ input_tokens=input_tokens,
194
+ output_tokens=output_tokens,
195
+ run_id=run_id,
196
+ a2ui=a2ui,
197
+ revision=revision,
198
+ tool_trace=[dict(x) for x in tool_trace] if tool_trace is not None else None,
199
+ client_message_id=client_message_id,
200
+ note=dict(note) if note is not None else None,
201
+ )
202
+ .returning(*t.message.c)
203
+ )
204
+ async with self._scope() as s:
205
+ if (await s.execute(touched)).first() is None:
206
+ raise NotFound(f"conversation {conversation_id}")
207
+ try:
208
+ async with s.begin_nested():
209
+ row = (await s.execute(stmt)).one()
210
+ except IntegrityError as exc:
211
+ if _violated(exc, client_message_constraint_name(t.names)):
212
+ raise DuplicateClientMessage(conversation_id, client_message_id or "") from None
213
+ raise
214
+ return _message(row)
215
+
216
+ async def get(self, message_id: int) -> MessageRecord | None:
217
+ m = self._t.message
218
+ async with self._scope() as s:
219
+ row = (await s.execute(select(m).where(m.c.id == message_id))).one_or_none()
220
+ return _message(row) if row else None
221
+
222
+ async def get_by_client_message_id(
223
+ self, conversation_id: str, client_message_id: str
224
+ ) -> MessageRecord | None:
225
+ m = self._t.message
226
+ stmt = select(m).where(
227
+ m.c.conversation_id == conversation_id, m.c.client_message_id == client_message_id
228
+ )
229
+ async with self._scope() as s:
230
+ row = (await s.execute(stmt)).one_or_none()
231
+ return _message(row) if row else None
232
+
233
+ async def list(
234
+ self, conversation_id: str, *, up_to_message_id: int | None = None
235
+ ) -> list[MessageRecord]:
236
+ m = self._t.message
237
+ stmt = select(m).where(m.c.conversation_id == conversation_id)
238
+ if up_to_message_id is not None:
239
+ stmt = stmt.where(m.c.id <= up_to_message_id)
240
+ async with self._scope() as s:
241
+ rows = (await s.execute(stmt.order_by(m.c.id))).all()
242
+ return [_message(r) for r in rows]
243
+
244
+
245
+ class _RunRepo(_Repo):
246
+ async def create(
247
+ self,
248
+ *,
249
+ conversation_id: str,
250
+ principal_id: str,
251
+ user_message_id: int,
252
+ model_id: str | None = None,
253
+ run_id: str | None = None,
254
+ ) -> RunRecord:
255
+ r = self._t.run
256
+ stmt = (
257
+ insert(r)
258
+ .values(
259
+ id=run_id or str(uuid.uuid4()),
260
+ conversation_id=conversation_id,
261
+ principal_id=principal_id,
262
+ user_message_id=user_message_id,
263
+ model_id=model_id,
264
+ status=RunStatus.QUEUED.value,
265
+ )
266
+ .returning(*r.c)
267
+ )
268
+ async with self._scope() as s:
269
+ try:
270
+ async with s.begin_nested():
271
+ row = (await s.execute(stmt)).one()
272
+ except IntegrityError as exc:
273
+ if _violated(exc, self._t.active_run_index):
274
+ raise ActiveRunExists(conversation_id) from None
275
+ raise
276
+ return _run(row)
277
+
278
+ async def _one(self, stmt: Any) -> RunRecord | None:
279
+ async with self._scope() as s:
280
+ row = (await s.execute(stmt)).one_or_none()
281
+ return _run(row) if row else None
282
+
283
+ async def get(self, run_id: str) -> RunRecord | None:
284
+ r = self._t.run
285
+ return await self._one(select(r).where(r.c.id == run_id))
286
+
287
+ async def get_active(self, conversation_id: str) -> RunRecord | None:
288
+ r = self._t.run
289
+ return await self._one(
290
+ select(r).where(r.c.conversation_id == conversation_id, r.c.status.in_(_ACTIVE))
291
+ )
292
+
293
+ async def get_by_user_message(self, user_message_id: int) -> RunRecord | None:
294
+ r = self._t.run
295
+ return await self._one(
296
+ select(r)
297
+ .where(r.c.user_message_id == user_message_id)
298
+ .order_by(r.c.created_at.desc())
299
+ .limit(1)
300
+ )
301
+
302
+ async def list_for_conversation(self, conversation_id: str) -> list[RunRecord]:
303
+ r = self._t.run
304
+ stmt = select(r).where(r.c.conversation_id == conversation_id).order_by(r.c.created_at)
305
+ async with self._scope() as s:
306
+ return [_run(row) for row in (await s.execute(stmt)).all()]
307
+
308
+ async def list_active(self, *, heartbeat_before: datetime | None = None) -> list[RunRecord]:
309
+ r = self._t.run
310
+ stmt = select(r).where(r.c.status.in_(_ACTIVE))
311
+ if heartbeat_before is not None:
312
+ last_seen = func.coalesce(r.c.heartbeat_at, r.c.started_at, r.c.created_at)
313
+ stmt = stmt.where(last_seen < heartbeat_before)
314
+ async with self._scope() as s:
315
+ return [_run(row) for row in (await s.execute(stmt.order_by(r.c.created_at))).all()]
316
+
317
+ async def count_active_for_principal(self, principal_id: str) -> int:
318
+ r = self._t.run
319
+ stmt = (
320
+ select(func.count())
321
+ .select_from(r)
322
+ .where(r.c.principal_id == principal_id, r.c.status.in_(_ACTIVE))
323
+ )
324
+ async with self._scope() as s:
325
+ return int((await s.execute(stmt)).scalar_one())
326
+
327
+ async def lock_principal(self, principal_id: str) -> None:
328
+ # Transaction-scoped: released at commit or rollback of the caller's transaction.
329
+ async with self._scope() as s:
330
+ await s.execute(
331
+ select(func.pg_advisory_xact_lock(func.hashtextextended(f"a2d:{principal_id}", 0)))
332
+ )
333
+
334
+ async def _update(self, stmt: Any) -> bool:
335
+ async with self._scope() as s:
336
+ return (await s.execute(stmt.returning(self._t.run.c.id))).first() is not None
337
+
338
+ async def mark_running(
339
+ self,
340
+ run_id: str,
341
+ *,
342
+ owner_instance: str,
343
+ trace_id: str | None = None,
344
+ at: datetime | None = None,
345
+ ) -> bool:
346
+ r = self._t.run
347
+ values: dict[str, Any] = {
348
+ "status": RunStatus.RUNNING.value,
349
+ "owner_instance": owner_instance,
350
+ "started_at": _at(at),
351
+ "heartbeat_at": _at(at),
352
+ }
353
+ if trace_id is not None:
354
+ values["trace_id"] = trace_id
355
+ return await self._update(
356
+ update(r).where(r.c.id == run_id, r.c.status == RunStatus.QUEUED.value).values(values)
357
+ )
358
+
359
+ async def heartbeat(self, run_id: str, *, at: datetime | None = None) -> bool:
360
+ r = self._t.run
361
+ return await self._update(
362
+ update(r).where(r.c.id == run_id, r.c.status.in_(_ACTIVE)).values(heartbeat_at=_at(at))
363
+ )
364
+
365
+ async def request_cancel(self, run_id: str, *, at: datetime | None = None) -> bool:
366
+ r = self._t.run
367
+ return await self._update(
368
+ update(r)
369
+ .where(r.c.id == run_id, r.c.status.in_(_ACTIVE))
370
+ .values(cancel_requested_at=func.coalesce(r.c.cancel_requested_at, _at(at)))
371
+ )
372
+
373
+ async def set_last_event_id(self, run_id: str, event_id: str) -> None:
374
+ r = self._t.run
375
+ async with self._scope() as s:
376
+ await s.execute(update(r).where(r.c.id == run_id).values(last_event_id=event_id))
377
+
378
+ async def finish(
379
+ self,
380
+ run_id: str,
381
+ *,
382
+ status: RunStatus,
383
+ assistant_message_id: int | None = None,
384
+ error_code: str | None = None,
385
+ input_tokens: int | None = None,
386
+ output_tokens: int | None = None,
387
+ at: datetime | None = None,
388
+ ) -> bool:
389
+ status = RunStatus(status)
390
+ if status not in _TERMINAL:
391
+ raise ValueError(f"{status} is not a terminal run status")
392
+ r = self._t.run
393
+ stmt = (
394
+ update(r)
395
+ .where(r.c.id == run_id, r.c.status.in_(_ACTIVE))
396
+ .values(
397
+ status=status.value,
398
+ finished_at=_at(at),
399
+ assistant_message_id=assistant_message_id,
400
+ error_code=error_code,
401
+ input_tokens=input_tokens,
402
+ output_tokens=output_tokens,
403
+ )
404
+ .returning(r.c.id)
405
+ )
406
+ async with self._scope() as s:
407
+ try:
408
+ async with s.begin_nested():
409
+ return (await s.execute(stmt)).first() is not None
410
+ except IntegrityError: # assistant_message_id does not exist
411
+ raise NotFound(f"message {assistant_message_id}") from None
412
+
413
+
414
+ class _DashboardRepo(_Repo):
415
+ async def get(self, conversation_id: str) -> DashboardRecord | None:
416
+ d = self._t.dashboard
417
+ async with self._scope() as s:
418
+ row = (
419
+ await s.execute(select(d).where(d.c.conversation_id == conversation_id))
420
+ ).one_or_none()
421
+ return _dashboard(row) if row else None
422
+
423
+ async def put(
424
+ self,
425
+ conversation_id: str,
426
+ *,
427
+ catalog_id: str,
428
+ surface: Mapping[str, Any],
429
+ queries: Mapping[str, Mapping[str, Any]],
430
+ express: str,
431
+ source: RevisionSource = "agent",
432
+ run_id: str | None = None,
433
+ expected_revision: int | None = None,
434
+ ) -> DashboardRecord:
435
+ d = self._t.dashboard
436
+ values = {
437
+ "catalog_id": catalog_id,
438
+ "surface": dict(surface),
439
+ "queries": {k: dict(v) for k, v in queries.items()},
440
+ }
441
+ first = pg_insert(d).values(conversation_id=conversation_id, revision=1, **values)
442
+ if expected_revision is None:
443
+ stmt = first.on_conflict_do_update(
444
+ index_elements=[d.c.conversation_id],
445
+ set_={**values, "revision": d.c.revision + 1, "updated_at": func.now()},
446
+ )
447
+ elif expected_revision == 0:
448
+ stmt = first.on_conflict_do_nothing(index_elements=[d.c.conversation_id])
449
+ else:
450
+ stmt = (
451
+ update(d)
452
+ .where(d.c.conversation_id == conversation_id, d.c.revision == expected_revision)
453
+ .values(**values, revision=d.c.revision + 1, updated_at=func.now())
454
+ )
455
+ async with self._scope() as s:
456
+ try:
457
+ async with s.begin_nested():
458
+ row = (await s.execute(stmt.returning(*d.c))).one_or_none()
459
+ except IntegrityError: # the only constraint an insert can break here is the FK
460
+ raise NotFound(f"conversation {conversation_id}") from None
461
+ if row is None:
462
+ actual = (
463
+ await s.execute(
464
+ select(d.c.revision).where(d.c.conversation_id == conversation_id)
465
+ )
466
+ ).scalar_one_or_none()
467
+ raise RevisionConflict(conversation_id, expected_revision or 0, actual or 0)
468
+ # The revision's own record, in the same transaction (§4.1): it never depends on
469
+ # the turn ending well.
470
+ await s.execute(
471
+ insert(self._t.dashboard_revision).values(
472
+ conversation_id=conversation_id,
473
+ revision=row.revision,
474
+ express=express,
475
+ surface=values["surface"],
476
+ queries=values["queries"],
477
+ run_id=run_id,
478
+ source=source,
479
+ )
480
+ )
481
+ return _dashboard(row)
482
+
483
+ async def get_query(self, conversation_id: str, query_id: str) -> dict[str, Any] | None:
484
+ d = self._t.dashboard
485
+ stmt = select(d.c.queries[query_id]).where(d.c.conversation_id == conversation_id)
486
+ async with self._scope() as s:
487
+ value = (await s.execute(stmt)).scalar_one_or_none()
488
+ return dict(value) if isinstance(value, dict) else None
489
+
490
+ async def list_revisions(
491
+ self, conversation_id: str, *, run_id: str | None = None
492
+ ) -> list[RevisionRecord]:
493
+ r = self._t.dashboard_revision
494
+ stmt = select(r).where(r.c.conversation_id == conversation_id)
495
+ if run_id is not None:
496
+ stmt = stmt.where(r.c.run_id == run_id)
497
+ async with self._scope() as s:
498
+ rows = (await s.execute(stmt.order_by(r.c.revision))).all()
499
+ return [_revision(row) for row in rows]
500
+
501
+ async def get_revision(self, conversation_id: str, revision: int) -> RevisionRecord | None:
502
+ r = self._t.dashboard_revision
503
+ stmt = select(r).where(r.c.conversation_id == conversation_id, r.c.revision == revision)
504
+ async with self._scope() as s:
505
+ row = (await s.execute(stmt)).one_or_none()
506
+ return _revision(row) if row else None
507
+
508
+ async def link_message(
509
+ self,
510
+ conversation_id: str,
511
+ message_id: int,
512
+ *,
513
+ revision: int | None = None,
514
+ run_id: str | None = None,
515
+ ) -> None:
516
+ if (revision is None) == (run_id is None):
517
+ raise ValueError("pass exactly one of revision and run_id")
518
+ r = self._t.dashboard_revision
519
+ stmt = update(r).where(r.c.conversation_id == conversation_id)
520
+ if revision is not None:
521
+ stmt = stmt.where(r.c.revision == revision)
522
+ else:
523
+ stmt = stmt.where(r.c.run_id == run_id, r.c.message_id.is_(None))
524
+ async with self._scope() as s:
525
+ await s.execute(stmt.values(message_id=message_id))
526
+
527
+
528
+ class _LlmCallRepo(_Repo):
529
+ async def add(self, call: Any) -> LlmCallRecord:
530
+ lc = self._t.llm_call
531
+ new = to_new_llm_call(call)
532
+ values = {f: getattr(new, f) for f in NewLlmCall.__dataclass_fields__}
533
+ async with self._scope() as s:
534
+ row = (await s.execute(insert(lc).values(**values).returning(*lc.c))).one()
535
+ return _llm_call(row)
536
+
537
+ async def get(self, call_id: int) -> LlmCallRecord | None:
538
+ lc = self._t.llm_call
539
+ async with self._scope() as s:
540
+ row = (await s.execute(select(lc).where(lc.c.id == call_id))).one_or_none()
541
+ return _llm_call(row) if row else None
542
+
543
+ async def list_for_run(self, run_id: str) -> list[LlmCallRecord]:
544
+ lc = self._t.llm_call
545
+ stmt = select(lc).where(lc.c.run_id == run_id).order_by(lc.c.id)
546
+ async with self._scope() as s:
547
+ return [_llm_call(r) for r in (await s.execute(stmt)).all()]
548
+
549
+ async def delete_for_conversation(self, conversation_id: str) -> None:
550
+ t = self._t
551
+ run_ids = select(t.run.c.id).where(t.run.c.conversation_id == conversation_id)
552
+ async with self._scope() as s:
553
+ await s.execute(delete(t.llm_call).where(t.llm_call.c.run_id.in_(run_ids)))
554
+
555
+
556
+ class SqlAlchemyStorage:
557
+ """`Storage` over the host's `AsyncSession` factory (e.g. an `async_sessionmaker`).
558
+
559
+ `tables` is a `TableNames` (or an already built `StorageTables`); `principal` says how
560
+ `principal_id` is stored and `schema` where the tables are; both must match what
561
+ `agent2dashboard.migrations.migrate` created."""
562
+
563
+ def __init__(
564
+ self,
565
+ session_factory: SessionFactory,
566
+ tables: TableNames | StorageTables | None = None,
567
+ *,
568
+ principal: PrincipalColumn | None = None,
569
+ schema: str | None = None,
570
+ _session: AsyncSession | None = None,
571
+ ) -> None:
572
+ if isinstance(tables, StorageTables):
573
+ if principal is not None and principal != tables.principal:
574
+ raise ValueError("principal differs from the one the tables were built with")
575
+ if schema is not None and schema != tables.schema:
576
+ raise ValueError("schema differs from the one the tables were built with")
577
+ self.tables = tables
578
+ else:
579
+ self.tables = build_tables(tables, principal, schema=schema)
580
+ self._factory = session_factory
581
+ self.session_factory = session_factory
582
+ self._session = _session
583
+ scope = self._bound_scope if _session is not None else self._own_scope
584
+ self.conversations = _ConversationRepo(scope, self.tables)
585
+ self.messages = _MessageRepo(scope, self.tables)
586
+ self.runs = _RunRepo(scope, self.tables)
587
+ self.dashboards = _DashboardRepo(scope, self.tables)
588
+ self.llm_calls = _LlmCallRepo(scope, self.tables)
589
+
590
+ @asynccontextmanager
591
+ async def _own_scope(self) -> AsyncIterator[AsyncSession]:
592
+ async with self._factory() as session, session.begin():
593
+ yield session
594
+
595
+ @asynccontextmanager
596
+ async def _bound_scope(self) -> AsyncIterator[AsyncSession]:
597
+ assert self._session is not None
598
+ yield self._session
599
+
600
+ @asynccontextmanager
601
+ async def transaction(self) -> AsyncIterator[SqlAlchemyStorage]:
602
+ if self._session is not None: # already inside one: join it
603
+ yield self
604
+ return
605
+ async with self._factory() as session, session.begin():
606
+ yield SqlAlchemyStorage(self._factory, self.tables, _session=session)
607
+
608
+
609
+ # --- row → record ---------------------------------------------------------------------------
610
+
611
+
612
+ def _str_or_none(value: Any) -> str | None:
613
+ return None if value is None else str(value)
614
+
615
+
616
+ def _conversation(row: Any) -> ConversationRecord:
617
+ m = row._mapping
618
+ return ConversationRecord(
619
+ id=str(m["id"]),
620
+ principal_id=str(m["principal_id"]),
621
+ title=m["title"],
622
+ created_at=m["created_at"],
623
+ updated_at=m["updated_at"],
624
+ last_message_at=m["last_message_at"],
625
+ )
626
+
627
+
628
+ def _message(row: Any) -> MessageRecord:
629
+ m = dict(row._mapping)
630
+ m["conversation_id"] = str(m["conversation_id"])
631
+ m["run_id"] = _str_or_none(m["run_id"])
632
+ return MessageRecord(**m)
633
+
634
+
635
+ def _run(row: Any) -> RunRecord:
636
+ m = dict(row._mapping)
637
+ for key in ("id", "conversation_id", "principal_id"):
638
+ m[key] = str(m[key])
639
+ m["status"] = RunStatus(m["status"])
640
+ return RunRecord(**m)
641
+
642
+
643
+ def _dashboard(row: Any) -> DashboardRecord:
644
+ m = dict(row._mapping)
645
+ m["conversation_id"] = str(m["conversation_id"])
646
+ return DashboardRecord(**m)
647
+
648
+
649
+ def _revision(row: Any) -> RevisionRecord:
650
+ m = row._mapping
651
+ return RevisionRecord(
652
+ revision=m["revision"],
653
+ message_id=m["message_id"],
654
+ run_id=_str_or_none(m["run_id"]),
655
+ created_at=m["created_at"],
656
+ source=m["source"],
657
+ express=m["express"],
658
+ surface=dict(m["surface"]),
659
+ queries={k: dict(v) for k, v in (m["queries"] or {}).items()},
660
+ )
661
+
662
+
663
+ def _llm_call(row: Any) -> LlmCallRecord:
664
+ m = dict(row._mapping)
665
+ m["run_id"] = _str_or_none(m["run_id"])
666
+ return LlmCallRecord(**m)