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,488 @@
1
+ """`InMemoryStorage`: the same contract as `SqlAlchemyStorage`, for tests (§3.7).
2
+
3
+ Single process only. Constraints the database enforces (one active run per conversation,
4
+ `client_message_id` per conversation, foreign keys) are enforced here too, and
5
+ `transaction()` rolls everything back on an exception.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import copy
11
+ import uuid
12
+ from collections.abc import AsyncIterator, Mapping, Sequence
13
+ from contextlib import asynccontextmanager
14
+ from dataclasses import dataclass, field, replace
15
+ from datetime import UTC, datetime
16
+ from typing import Any, Literal
17
+
18
+ from agent2dashboard.ports import RunStatus
19
+ from agent2dashboard.storage.records import (
20
+ ActiveRunExists,
21
+ ConversationRecord,
22
+ DashboardRecord,
23
+ DuplicateClientMessage,
24
+ LlmCallRecord,
25
+ MessageRecord,
26
+ NewLlmCall,
27
+ NotFound,
28
+ RevisionConflict,
29
+ RevisionRecord,
30
+ RevisionSource,
31
+ RunRecord,
32
+ to_new_llm_call,
33
+ )
34
+ from agent2dashboard.storage.tables import ACTIVE_RUN_STATUSES
35
+
36
+ __all__ = ["InMemoryStorage"]
37
+
38
+ _TERMINAL = {RunStatus.SUCCEEDED, RunStatus.FAILED, RunStatus.CANCELLED, RunStatus.INTERRUPTED}
39
+
40
+
41
+ def _now() -> datetime:
42
+ return datetime.now(UTC)
43
+
44
+
45
+ @dataclass
46
+ class _State:
47
+ conversations: dict[str, ConversationRecord] = field(default_factory=dict)
48
+ messages: dict[int, MessageRecord] = field(default_factory=dict)
49
+ runs: dict[str, RunRecord] = field(default_factory=dict)
50
+ dashboards: dict[str, DashboardRecord] = field(default_factory=dict)
51
+ revisions: dict[tuple[str, int], RevisionRecord] = field(default_factory=dict)
52
+ llm_calls: dict[int, LlmCallRecord] = field(default_factory=dict)
53
+ next_message_id: int = 1
54
+ next_llm_call_id: int = 1
55
+
56
+
57
+ class _Repo:
58
+ def __init__(self, owner: InMemoryStorage) -> None:
59
+ self._owner = owner
60
+
61
+ @property
62
+ def _s(self) -> _State:
63
+ return self._owner._state
64
+
65
+
66
+ class _ConversationRepo(_Repo):
67
+ async def create(
68
+ self, *, principal_id: str, title: str | None = None, conversation_id: str | None = None
69
+ ) -> ConversationRecord:
70
+ cid = conversation_id or str(uuid.uuid4())
71
+ if cid in self._s.conversations:
72
+ raise ValueError(f"conversation {cid} already exists")
73
+ now = _now()
74
+ record = ConversationRecord(
75
+ id=cid,
76
+ principal_id=principal_id,
77
+ title=title,
78
+ created_at=now,
79
+ updated_at=now,
80
+ last_message_at=now,
81
+ )
82
+ self._s.conversations[cid] = record
83
+ return record
84
+
85
+ async def get(
86
+ self, conversation_id: str, *, principal_id: str | None = None
87
+ ) -> ConversationRecord | None:
88
+ record = self._s.conversations.get(conversation_id)
89
+ if record is None or (principal_id is not None and record.principal_id != principal_id):
90
+ return None
91
+ return record
92
+
93
+ async def list_for_principal(
94
+ self, principal_id: str, *, limit: int = 50, before: datetime | None = None
95
+ ) -> list[ConversationRecord]:
96
+ rows = [
97
+ c
98
+ for c in self._s.conversations.values()
99
+ if c.principal_id == principal_id and (before is None or c.last_message_at < before)
100
+ ]
101
+ rows.sort(key=lambda c: c.id)
102
+ rows.sort(key=lambda c: c.last_message_at, reverse=True)
103
+ return rows[:limit]
104
+
105
+ async def rename(self, conversation_id: str, title: str | None) -> bool:
106
+ record = self._s.conversations.get(conversation_id)
107
+ if record is None:
108
+ return False
109
+ self._s.conversations[conversation_id] = replace(record, title=title, updated_at=_now())
110
+ return True
111
+
112
+ async def touch(self, conversation_id: str, *, at: datetime | None = None) -> None:
113
+ record = self._s.conversations.get(conversation_id)
114
+ if record is not None:
115
+ at = at or _now()
116
+ self._s.conversations[conversation_id] = replace(
117
+ record, last_message_at=at, updated_at=at
118
+ )
119
+
120
+ async def delete(self, conversation_id: str) -> bool:
121
+ s = self._s
122
+ run_ids = {r.id for r in s.runs.values() if r.conversation_id == conversation_id}
123
+ s.llm_calls = {k: v for k, v in s.llm_calls.items() if v.run_id not in run_ids}
124
+ s.dashboards.pop(conversation_id, None)
125
+ s.revisions = {k: v for k, v in s.revisions.items() if k[0] != conversation_id}
126
+ s.runs = {k: v for k, v in s.runs.items() if k not in run_ids}
127
+ s.messages = {k: v for k, v in s.messages.items() if v.conversation_id != conversation_id}
128
+ return s.conversations.pop(conversation_id, None) is not None
129
+
130
+ async def list_inactive(self, *, before: datetime, limit: int = 100) -> list[str]:
131
+ rows = [c for c in self._s.conversations.values() if c.last_message_at < before]
132
+ rows.sort(key=lambda c: (c.last_message_at, c.id))
133
+ return [c.id for c in rows[:limit]]
134
+
135
+
136
+ class _MessageRepo(_Repo):
137
+ async def add(
138
+ self,
139
+ *,
140
+ conversation_id: str,
141
+ role: Literal["user", "assistant"],
142
+ content: str,
143
+ stop_reason: str | None = None,
144
+ input_tokens: int | None = None,
145
+ output_tokens: int | None = None,
146
+ run_id: str | None = None,
147
+ a2ui: str | None = None,
148
+ revision: int | None = None,
149
+ tool_trace: Sequence[Mapping[str, Any]] | None = None,
150
+ client_message_id: str | None = None,
151
+ note: Mapping[str, Any] | None = None,
152
+ ) -> MessageRecord:
153
+ s = self._s
154
+ if conversation_id not in s.conversations:
155
+ raise NotFound(f"conversation {conversation_id}")
156
+ if client_message_id is not None and any(
157
+ m.conversation_id == conversation_id and m.client_message_id == client_message_id
158
+ for m in s.messages.values()
159
+ ):
160
+ raise DuplicateClientMessage(conversation_id, client_message_id)
161
+ now = _now()
162
+ record = MessageRecord(
163
+ id=s.next_message_id,
164
+ conversation_id=conversation_id,
165
+ role=role,
166
+ content=content,
167
+ stop_reason=stop_reason,
168
+ input_tokens=input_tokens,
169
+ output_tokens=output_tokens,
170
+ run_id=run_id,
171
+ a2ui=a2ui,
172
+ revision=revision,
173
+ tool_trace=(
174
+ copy.deepcopy([dict(x) for x in tool_trace]) if tool_trace is not None else None
175
+ ),
176
+ client_message_id=client_message_id,
177
+ created_at=now,
178
+ note=copy.deepcopy(dict(note)) if note is not None else None,
179
+ )
180
+ s.next_message_id += 1
181
+ s.messages[record.id] = record
182
+ await self._owner.conversations.touch(conversation_id, at=now)
183
+ return record
184
+
185
+ async def get(self, message_id: int) -> MessageRecord | None:
186
+ return self._s.messages.get(message_id)
187
+
188
+ async def get_by_client_message_id(
189
+ self, conversation_id: str, client_message_id: str
190
+ ) -> MessageRecord | None:
191
+ for m in self._s.messages.values():
192
+ if m.conversation_id == conversation_id and m.client_message_id == client_message_id:
193
+ return m
194
+ return None
195
+
196
+ async def list(
197
+ self, conversation_id: str, *, up_to_message_id: int | None = None
198
+ ) -> list[MessageRecord]:
199
+ return sorted(
200
+ (
201
+ m
202
+ for m in self._s.messages.values()
203
+ if m.conversation_id == conversation_id
204
+ and (up_to_message_id is None or m.id <= up_to_message_id)
205
+ ),
206
+ key=lambda m: m.id,
207
+ )
208
+
209
+
210
+ class _RunRepo(_Repo):
211
+ async def create(
212
+ self,
213
+ *,
214
+ conversation_id: str,
215
+ principal_id: str,
216
+ user_message_id: int,
217
+ model_id: str | None = None,
218
+ run_id: str | None = None,
219
+ ) -> RunRecord:
220
+ s = self._s
221
+ if conversation_id not in s.conversations:
222
+ raise NotFound(f"conversation {conversation_id}")
223
+ if user_message_id not in s.messages:
224
+ raise NotFound(f"message {user_message_id}")
225
+ if any(r.conversation_id == conversation_id and r.active for r in s.runs.values()):
226
+ raise ActiveRunExists(conversation_id)
227
+ rid = run_id or str(uuid.uuid4())
228
+ if rid in s.runs:
229
+ raise ValueError(f"run {rid} already exists")
230
+ record = RunRecord(
231
+ id=rid,
232
+ conversation_id=conversation_id,
233
+ principal_id=principal_id,
234
+ user_message_id=user_message_id,
235
+ assistant_message_id=None,
236
+ status=RunStatus.QUEUED,
237
+ cancel_requested_at=None,
238
+ owner_instance=None,
239
+ heartbeat_at=None,
240
+ started_at=None,
241
+ finished_at=None,
242
+ error_code=None,
243
+ trace_id=None,
244
+ model_id=model_id,
245
+ input_tokens=None,
246
+ output_tokens=None,
247
+ last_event_id=None,
248
+ created_at=_now(),
249
+ )
250
+ s.runs[rid] = record
251
+ return record
252
+
253
+ async def get(self, run_id: str) -> RunRecord | None:
254
+ return self._s.runs.get(run_id)
255
+
256
+ async def get_active(self, conversation_id: str) -> RunRecord | None:
257
+ for r in self._s.runs.values():
258
+ if r.conversation_id == conversation_id and r.active:
259
+ return r
260
+ return None
261
+
262
+ async def get_by_user_message(self, user_message_id: int) -> RunRecord | None:
263
+ runs = [r for r in self._s.runs.values() if r.user_message_id == user_message_id]
264
+ return max(runs, key=lambda r: r.created_at) if runs else None
265
+
266
+ async def list_for_conversation(self, conversation_id: str) -> list[RunRecord]:
267
+ return sorted(
268
+ (r for r in self._s.runs.values() if r.conversation_id == conversation_id),
269
+ key=lambda r: r.created_at,
270
+ )
271
+
272
+ async def list_active(self, *, heartbeat_before: datetime | None = None) -> list[RunRecord]:
273
+ def stale(r: RunRecord) -> bool:
274
+ last_seen = r.heartbeat_at or r.started_at or r.created_at
275
+ return heartbeat_before is None or last_seen < heartbeat_before
276
+
277
+ return sorted(
278
+ (r for r in self._s.runs.values() if r.active and stale(r)),
279
+ key=lambda r: r.created_at,
280
+ )
281
+
282
+ async def count_active_for_principal(self, principal_id: str) -> int:
283
+ return sum(1 for r in self._s.runs.values() if r.principal_id == principal_id and r.active)
284
+
285
+ async def lock_principal(self, principal_id: str) -> None:
286
+ return None # one process, and nothing awaits between the count and the insert
287
+
288
+ def _change(self, run_id: str, when: Any, **changes: Any) -> bool:
289
+ record = self._s.runs.get(run_id)
290
+ if record is None or not when(record):
291
+ return False
292
+ self._s.runs[run_id] = replace(record, **changes)
293
+ return True
294
+
295
+ async def mark_running(
296
+ self,
297
+ run_id: str,
298
+ *,
299
+ owner_instance: str,
300
+ trace_id: str | None = None,
301
+ at: datetime | None = None,
302
+ ) -> bool:
303
+ at = at or _now()
304
+ record = self._s.runs.get(run_id)
305
+ changes: dict[str, Any] = {
306
+ "status": RunStatus.RUNNING,
307
+ "owner_instance": owner_instance,
308
+ "started_at": at,
309
+ "heartbeat_at": at,
310
+ "trace_id": trace_id if trace_id is not None else (record and record.trace_id),
311
+ }
312
+ return self._change(run_id, lambda r: r.status == RunStatus.QUEUED, **changes)
313
+
314
+ async def heartbeat(self, run_id: str, *, at: datetime | None = None) -> bool:
315
+ return self._change(run_id, lambda r: r.active, heartbeat_at=at or _now())
316
+
317
+ async def request_cancel(self, run_id: str, *, at: datetime | None = None) -> bool:
318
+ record = self._s.runs.get(run_id)
319
+ if record is None or not record.active:
320
+ return False
321
+ if record.cancel_requested_at is None:
322
+ self._s.runs[run_id] = replace(record, cancel_requested_at=at or _now())
323
+ return True
324
+
325
+ async def set_last_event_id(self, run_id: str, event_id: str) -> None:
326
+ self._change(run_id, lambda r: True, last_event_id=event_id)
327
+
328
+ async def finish(
329
+ self,
330
+ run_id: str,
331
+ *,
332
+ status: RunStatus,
333
+ assistant_message_id: int | None = None,
334
+ error_code: str | None = None,
335
+ input_tokens: int | None = None,
336
+ output_tokens: int | None = None,
337
+ at: datetime | None = None,
338
+ ) -> bool:
339
+ status = RunStatus(status)
340
+ if status not in _TERMINAL:
341
+ raise ValueError(f"{status} is not a terminal run status")
342
+ if assistant_message_id is not None and assistant_message_id not in self._s.messages:
343
+ raise NotFound(f"message {assistant_message_id}")
344
+ return self._change(
345
+ run_id,
346
+ lambda r: r.status in ACTIVE_RUN_STATUSES,
347
+ status=status,
348
+ finished_at=at or _now(),
349
+ assistant_message_id=assistant_message_id,
350
+ error_code=error_code,
351
+ input_tokens=input_tokens,
352
+ output_tokens=output_tokens,
353
+ )
354
+
355
+
356
+ class _DashboardRepo(_Repo):
357
+ async def get(self, conversation_id: str) -> DashboardRecord | None:
358
+ record = self._s.dashboards.get(conversation_id)
359
+ return copy.deepcopy(record) if record else None
360
+
361
+ async def put(
362
+ self,
363
+ conversation_id: str,
364
+ *,
365
+ catalog_id: str,
366
+ surface: Mapping[str, Any],
367
+ queries: Mapping[str, Mapping[str, Any]],
368
+ express: str,
369
+ source: RevisionSource = "agent",
370
+ run_id: str | None = None,
371
+ expected_revision: int | None = None,
372
+ ) -> DashboardRecord:
373
+ if conversation_id not in self._s.conversations:
374
+ if expected_revision:
375
+ raise RevisionConflict(conversation_id, expected_revision, 0)
376
+ raise NotFound(f"conversation {conversation_id}")
377
+ current = self._s.dashboards.get(conversation_id)
378
+ actual = current.revision if current else 0
379
+ if expected_revision is not None and expected_revision != actual:
380
+ raise RevisionConflict(conversation_id, expected_revision, actual)
381
+ record = DashboardRecord(
382
+ conversation_id=conversation_id,
383
+ catalog_id=catalog_id,
384
+ surface=copy.deepcopy(dict(surface)),
385
+ queries={k: copy.deepcopy(dict(v)) for k, v in queries.items()},
386
+ revision=actual + 1,
387
+ updated_at=_now(),
388
+ )
389
+ self._s.dashboards[conversation_id] = record
390
+ self._s.revisions[(conversation_id, record.revision)] = RevisionRecord(
391
+ revision=record.revision,
392
+ message_id=None,
393
+ run_id=run_id,
394
+ created_at=record.updated_at,
395
+ source=source,
396
+ express=express,
397
+ surface=copy.deepcopy(record.surface),
398
+ queries=copy.deepcopy(record.queries),
399
+ )
400
+ return copy.deepcopy(record)
401
+
402
+ async def get_query(self, conversation_id: str, query_id: str) -> dict[str, Any] | None:
403
+ record = self._s.dashboards.get(conversation_id)
404
+ entry = record.queries.get(query_id) if record else None
405
+ return copy.deepcopy(entry) if isinstance(entry, dict) else None
406
+
407
+ async def list_revisions(
408
+ self, conversation_id: str, *, run_id: str | None = None
409
+ ) -> list[RevisionRecord]:
410
+ return [
411
+ copy.deepcopy(r)
412
+ for (cid, _), r in sorted(self._s.revisions.items(), key=lambda kv: kv[0][1])
413
+ if cid == conversation_id and (run_id is None or r.run_id == run_id)
414
+ ]
415
+
416
+ async def get_revision(self, conversation_id: str, revision: int) -> RevisionRecord | None:
417
+ record = self._s.revisions.get((conversation_id, revision))
418
+ return copy.deepcopy(record) if record else None
419
+
420
+ async def link_message(
421
+ self,
422
+ conversation_id: str,
423
+ message_id: int,
424
+ *,
425
+ revision: int | None = None,
426
+ run_id: str | None = None,
427
+ ) -> None:
428
+ if (revision is None) == (run_id is None):
429
+ raise ValueError("pass exactly one of revision and run_id")
430
+ for key, record in list(self._s.revisions.items()):
431
+ if key[0] != conversation_id:
432
+ continue
433
+ if revision is not None and key[1] == revision:
434
+ self._s.revisions[key] = replace(record, message_id=message_id)
435
+ elif run_id is not None and record.run_id == run_id and record.message_id is None:
436
+ self._s.revisions[key] = replace(record, message_id=message_id)
437
+
438
+
439
+ class _LlmCallRepo(_Repo):
440
+ async def add(self, call: Any) -> LlmCallRecord:
441
+ s = self._s
442
+ new = to_new_llm_call(call)
443
+ if new.run_id is not None and new.run_id not in s.runs:
444
+ raise NotFound(f"run {new.run_id}")
445
+ values = {f: getattr(new, f) for f in NewLlmCall.__dataclass_fields__}
446
+ record = LlmCallRecord(id=s.next_llm_call_id, created_at=_now(), **values)
447
+ s.next_llm_call_id += 1
448
+ s.llm_calls[record.id] = record
449
+ return record
450
+
451
+ async def get(self, call_id: int) -> LlmCallRecord | None:
452
+ return self._s.llm_calls.get(call_id)
453
+
454
+ async def list_for_run(self, run_id: str) -> list[LlmCallRecord]:
455
+ return sorted(
456
+ (c for c in self._s.llm_calls.values() if c.run_id == run_id), key=lambda c: c.id
457
+ )
458
+
459
+ async def delete_for_conversation(self, conversation_id: str) -> None:
460
+ s = self._s
461
+ run_ids = {r.id for r in s.runs.values() if r.conversation_id == conversation_id}
462
+ s.llm_calls = {k: v for k, v in s.llm_calls.items() if v.run_id not in run_ids}
463
+
464
+
465
+ class InMemoryStorage:
466
+ def __init__(self) -> None:
467
+ self._state = _State()
468
+ self._in_transaction = False
469
+ self.conversations = _ConversationRepo(self)
470
+ self.messages = _MessageRepo(self)
471
+ self.runs = _RunRepo(self)
472
+ self.dashboards = _DashboardRepo(self)
473
+ self.llm_calls = _LlmCallRepo(self)
474
+
475
+ @asynccontextmanager
476
+ async def transaction(self) -> AsyncIterator[InMemoryStorage]:
477
+ if self._in_transaction: # already inside one: join it
478
+ yield self
479
+ return
480
+ snapshot = copy.deepcopy(self._state)
481
+ self._in_transaction = True
482
+ try:
483
+ yield self
484
+ except BaseException:
485
+ self._state = snapshot
486
+ raise
487
+ finally:
488
+ self._in_transaction = False
@@ -0,0 +1,219 @@
1
+ """What the repositories return: plain frozen dataclasses, never ORM objects or rows."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass, field
7
+ from datetime import datetime
8
+ from typing import Any, Literal
9
+
10
+ from agent2dashboard.errors import AgentDashboardError
11
+ from agent2dashboard.ports import RunStatus
12
+
13
+ __all__ = [
14
+ "ActiveRunExists",
15
+ "ConversationRecord",
16
+ "DashboardRecord",
17
+ "DuplicateClientMessage",
18
+ "LlmCallRecord",
19
+ "MessageRecord",
20
+ "NewLlmCall",
21
+ "NotFound",
22
+ "RevisionConflict",
23
+ "RevisionRecord",
24
+ "RevisionSource",
25
+ "RunRecord",
26
+ "StorageError",
27
+ "to_new_llm_call",
28
+ ]
29
+
30
+ Role = Literal["user", "assistant"]
31
+
32
+
33
+ class StorageError(AgentDashboardError):
34
+ """Base class for storage errors."""
35
+
36
+
37
+ class NotFound(StorageError):
38
+ """The referenced conversation, message or run does not exist."""
39
+
40
+
41
+ class ActiveRunExists(StorageError):
42
+ """The conversation already has a queued or running run (the HTTP layer answers 409)."""
43
+
44
+ def __init__(self, conversation_id: str) -> None:
45
+ super().__init__(f"conversation {conversation_id} already has an active run")
46
+ self.conversation_id = conversation_id
47
+
48
+
49
+ class DuplicateClientMessage(StorageError):
50
+ """A user message with this `client_message_id` already exists in the conversation; the
51
+ caller looks it up and returns the run it started (idempotent retry, §5.3)."""
52
+
53
+ def __init__(self, conversation_id: str, client_message_id: str) -> None:
54
+ super().__init__(f"client_message_id {client_message_id} already used")
55
+ self.conversation_id = conversation_id
56
+ self.client_message_id = client_message_id
57
+
58
+
59
+ class RevisionConflict(StorageError):
60
+ """`DashboardRepo.put` was given an `expected_revision` that is no longer current."""
61
+
62
+ def __init__(self, conversation_id: str, expected: int, actual: int) -> None:
63
+ super().__init__(
64
+ f"dashboard of {conversation_id} is at revision {actual}, expected {expected}"
65
+ )
66
+ self.expected = expected
67
+ self.actual = actual
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class ConversationRecord:
72
+ id: str
73
+ principal_id: str
74
+ title: str | None
75
+ created_at: datetime
76
+ updated_at: datetime
77
+ last_message_at: datetime
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class MessageRecord:
82
+ id: int
83
+ conversation_id: str
84
+ role: Role
85
+ content: str
86
+ stop_reason: str | None
87
+ input_tokens: int | None
88
+ output_tokens: int | None
89
+ run_id: str | None
90
+ a2ui: str | None
91
+ revision: int | None
92
+ tool_trace: list[dict[str, Any]] | None
93
+ client_message_id: str | None
94
+ created_at: datetime
95
+ note: dict[str, Any] | None = None
96
+ """A layout action's or restore's note, `{code, params}`; `content` is its English text."""
97
+
98
+
99
+ @dataclass(frozen=True)
100
+ class RunRecord:
101
+ id: str
102
+ conversation_id: str
103
+ principal_id: str
104
+ user_message_id: int
105
+ assistant_message_id: int | None
106
+ status: RunStatus
107
+ cancel_requested_at: datetime | None
108
+ owner_instance: str | None
109
+ heartbeat_at: datetime | None
110
+ started_at: datetime | None
111
+ finished_at: datetime | None
112
+ error_code: str | None
113
+ trace_id: str | None
114
+ model_id: str | None
115
+ input_tokens: int | None
116
+ output_tokens: int | None
117
+ last_event_id: str | None
118
+ created_at: datetime
119
+
120
+ @property
121
+ def active(self) -> bool:
122
+ return self.status in (RunStatus.QUEUED, RunStatus.RUNNING)
123
+
124
+
125
+ @dataclass(frozen=True)
126
+ class DashboardRecord:
127
+ """The conversation's one dashboard at its current revision. `queries` is the query
128
+ registry keyed by `query_id` (each entry holds `sql`, `filters_used`, `columns`, ...)."""
129
+
130
+ conversation_id: str
131
+ catalog_id: str
132
+ surface: dict[str, Any]
133
+ queries: dict[str, dict[str, Any]]
134
+ revision: int
135
+ updated_at: datetime
136
+
137
+
138
+ RevisionSource = Literal["agent", "layout", "restore"]
139
+
140
+
141
+ @dataclass(frozen=True)
142
+ class RevisionRecord:
143
+ """One accepted dashboard change (a `render_dashboard`, a layout action or a restore), as
144
+ stored with it in the same transaction: its Express, surface document and query registry.
145
+ `message_id` is the message that records it, once that message is written (an agent
146
+ render's message is written at the end of the turn; a reaped run may have none)."""
147
+
148
+ revision: int
149
+ message_id: int | None
150
+ run_id: str | None
151
+ created_at: datetime
152
+ source: RevisionSource = "agent"
153
+ express: str = ""
154
+ surface: dict[str, Any] = field(default_factory=dict)
155
+ queries: dict[str, dict[str, Any]] = field(default_factory=dict)
156
+
157
+
158
+ @dataclass(frozen=True)
159
+ class NewLlmCall:
160
+ purpose: str
161
+ model: str
162
+ status: str
163
+ max_tokens: int | None
164
+ input: str
165
+ latency_ms: int
166
+ run_id: str | None = None
167
+ system_sha256: str | None = None
168
+ output: str | None = None
169
+ stop_reason: str | None = None
170
+ input_tokens: int | None = None
171
+ output_tokens: int | None = None
172
+ error: str | None = None
173
+
174
+
175
+ @dataclass(frozen=True)
176
+ class LlmCallRecord:
177
+ id: int
178
+ run_id: str | None
179
+ purpose: str
180
+ model: str
181
+ status: str
182
+ max_tokens: int | None
183
+ system_sha256: str | None
184
+ input: str
185
+ output: str | None
186
+ stop_reason: str | None
187
+ input_tokens: int | None
188
+ output_tokens: int | None
189
+ latency_ms: int
190
+ error: str | None
191
+ created_at: datetime
192
+
193
+
194
+ def to_new_llm_call(call: Any) -> NewLlmCall:
195
+ """A `NewLlmCall`, or anything shaped like `agent2dashboard.tracing.LlmCallRecord` (what
196
+ `DbTraceSink` writes through `LlmCallWriter`): non-text input/output is stored as JSON."""
197
+ if isinstance(call, NewLlmCall):
198
+ return call
199
+ return NewLlmCall(
200
+ purpose=call.purpose,
201
+ model=call.model,
202
+ status=call.status,
203
+ max_tokens=call.max_tokens,
204
+ input=_text(call.input) or "",
205
+ latency_ms=call.latency_ms,
206
+ run_id=call.run_id,
207
+ system_sha256=call.system_sha256,
208
+ output=_text(call.output),
209
+ stop_reason=call.stop_reason,
210
+ input_tokens=call.input_tokens,
211
+ output_tokens=call.output_tokens,
212
+ error=call.error,
213
+ )
214
+
215
+
216
+ def _text(value: Any) -> str | None:
217
+ if value is None or isinstance(value, str):
218
+ return value
219
+ return json.dumps(value, ensure_ascii=False, default=str)