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.
- agent2dashboard/__init__.py +593 -0
- agent2dashboard/__main__.py +3 -0
- agent2dashboard/_env.py +79 -0
- agent2dashboard/a2ui/__init__.py +1 -0
- agent2dashboard/a2ui/catalogs/dashboard/v1/catalog.json +496 -0
- agent2dashboard/a2ui/checks.py +656 -0
- agent2dashboard/a2ui/express.py +349 -0
- agent2dashboard/a2ui/layout_actions.py +409 -0
- agent2dashboard/a2ui/render.py +252 -0
- agent2dashboard/a2ui/state.py +600 -0
- agent2dashboard/a2ui/surfaces.py +23 -0
- agent2dashboard/agent/__init__.py +83 -0
- agent2dashboard/agent/builtin_tools.py +258 -0
- agent2dashboard/agent/history.py +218 -0
- agent2dashboard/agent/loop.py +341 -0
- agent2dashboard/agent/prompt.py +66 -0
- agent2dashboard/agent/tools.py +162 -0
- agent2dashboard/agent/turn.py +201 -0
- agent2dashboard/auth.py +350 -0
- agent2dashboard/cli/__init__.py +50 -0
- agent2dashboard/errors.py +18 -0
- agent2dashboard/http/__init__.py +40 -0
- agent2dashboard/http/dashboards.py +100 -0
- agent2dashboard/http/functions.py +462 -0
- agent2dashboard/http/queries.py +168 -0
- agent2dashboard/http/revisions.py +126 -0
- agent2dashboard/http/router.py +353 -0
- agent2dashboard/http/schemas.py +102 -0
- agent2dashboard/llm/__init__.py +7 -0
- agent2dashboard/llm/_messages_api.py +123 -0
- agent2dashboard/llm/bedrock.py +96 -0
- agent2dashboard/llm/direct.py +40 -0
- agent2dashboard/llm/messages.py +45 -0
- agent2dashboard/migrations/__init__.py +383 -0
- agent2dashboard/migrations/versions/0001_initial.py +228 -0
- agent2dashboard/ports.py +538 -0
- agent2dashboard/py.typed +0 -0
- agent2dashboard/query/__init__.py +65 -0
- agent2dashboard/query/errors.py +39 -0
- agent2dashboard/query/executor.py +203 -0
- agent2dashboard/query/filters.py +446 -0
- agent2dashboard/query/governed.py +155 -0
- agent2dashboard/query/readonly.py +166 -0
- agent2dashboard/query/registry.py +213 -0
- agent2dashboard/query/row_filter.py +135 -0
- agent2dashboard/query/service.py +93 -0
- agent2dashboard/query/sql_guard.py +219 -0
- agent2dashboard/runs/__init__.py +87 -0
- agent2dashboard/runs/errors.py +65 -0
- agent2dashboard/runs/events.py +147 -0
- agent2dashboard/runs/hooks.py +135 -0
- agent2dashboard/runs/http.py +169 -0
- agent2dashboard/runs/memory.py +148 -0
- agent2dashboard/runs/redis_bus.py +219 -0
- agent2dashboard/runs/service.py +728 -0
- agent2dashboard/runs/writer.py +95 -0
- agent2dashboard/semantic/__init__.py +6 -0
- agent2dashboard/semantic/cube.py +39 -0
- agent2dashboard/semantic/static.py +81 -0
- agent2dashboard/storage/__init__.py +60 -0
- agent2dashboard/storage/lifecycle.py +105 -0
- agent2dashboard/storage/memory.py +488 -0
- agent2dashboard/storage/records.py +219 -0
- agent2dashboard/storage/sql.py +666 -0
- agent2dashboard/storage/tables.py +387 -0
- agent2dashboard/testing/__init__.py +20 -0
- agent2dashboard/testing/event_bus.py +10 -0
- agent2dashboard/testing/fake_llm.py +129 -0
- agent2dashboard/testing/host.py +191 -0
- agent2dashboard/tracing/__init__.py +36 -0
- agent2dashboard/tracing/db.py +143 -0
- agent2dashboard/tracing/fanout.py +153 -0
- agent2dashboard/tracing/langfuse.py +339 -0
- agent2dashboard/tracing/masking.py +26 -0
- agent2dashboard-0.2.0.dist-info/METADATA +81 -0
- agent2dashboard-0.2.0.dist-info/RECORD +79 -0
- agent2dashboard-0.2.0.dist-info/WHEEL +4 -0
- agent2dashboard-0.2.0.dist-info/entry_points.txt +3 -0
- agent2dashboard-0.2.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,600 @@
|
|
|
1
|
+
"""The conversation's dashboard: its live `RendererState`, revisions, replay and restore
|
|
2
|
+
(design §1.10 decisions 5-6, §4.1, §5.1, §6.4).
|
|
3
|
+
|
|
4
|
+
- **Surface document.** The `dashboard.surface` column holds `{"components": [...],
|
|
5
|
+
"dataModel": {...}}`: the components reachable from `root` (compacted), and the data model
|
|
6
|
+
the model wrote (filter defaults, view state). One `createSurface` message rebuilds it.
|
|
7
|
+
- **Run start.** `DashboardSession.load` rebuilds the conversation's `RendererState` and query
|
|
8
|
+
registry from the stored dashboard. The session lives for one run, behind the run lock, and
|
|
9
|
+
goes to the tools in `ToolContext.extras[DASHBOARD_SESSION]`; `define_query` registers into
|
|
10
|
+
`session.registry`, `render_dashboard` parses against `session.state`.
|
|
11
|
+
- **Revisions.** Each accepted change (a `render_dashboard`, a layout action, a restore)
|
|
12
|
+
stores a new `dashboard` revision and, in the same transaction, one `dashboard_revision`
|
|
13
|
+
row: its Express, surface document and query registry. That row is the revision's durable
|
|
14
|
+
record; a turn that fails after rendering, or a run the reaper closes, keeps it.
|
|
15
|
+
- **Message fields.** The run writes the assistant message at the end of the turn with
|
|
16
|
+
`session.message_fields()`: `a2ui` (the accepted Express blocks of the turn) and `revision`
|
|
17
|
+
(the last one), and links the turn's revision rows to it.
|
|
18
|
+
- **Revision snapshots.** A revision's surface and queries are read from its row
|
|
19
|
+
(`snapshot_at`, `revision_snapshots`); nothing is rebuilt from tool trails.
|
|
20
|
+
- **Restore.** `restore_revision` makes an older revision the newest: it writes the snapshot
|
|
21
|
+
back as one generated `update=true` Express block, checks the result, stores it as a new
|
|
22
|
+
revision with a note message, and returns the `canvas.a2ui` payload.
|
|
23
|
+
- **On screen.** `on_screen_section` is the host-prompt part that tells the model the surface id
|
|
24
|
+
and what is on screen (id, type, queryId, title), refreshed after each change.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import asyncio
|
|
30
|
+
import copy
|
|
31
|
+
import json
|
|
32
|
+
import re
|
|
33
|
+
import uuid
|
|
34
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
35
|
+
from dataclasses import dataclass, field
|
|
36
|
+
from typing import Any
|
|
37
|
+
|
|
38
|
+
from a2ui.constants import A2UI_INFERENCE_CLOSE_TAG, A2UI_INFERENCE_OPEN_TAG
|
|
39
|
+
from a2ui.inference_formats.express.decompiler import ExpressDecompiler
|
|
40
|
+
from a2ui.utils import RendererState
|
|
41
|
+
|
|
42
|
+
from agent2dashboard.a2ui import checks
|
|
43
|
+
from agent2dashboard.a2ui.express import CATALOG_ID, ExpressError, ExpressProcessor
|
|
44
|
+
from agent2dashboard.a2ui.surfaces import surface_id_for
|
|
45
|
+
from agent2dashboard.errors import AgentDashboardError
|
|
46
|
+
from agent2dashboard.query.registry import QueryRegistry
|
|
47
|
+
from agent2dashboard.storage.records import (
|
|
48
|
+
DashboardRecord,
|
|
49
|
+
MessageRecord,
|
|
50
|
+
NotFound,
|
|
51
|
+
RevisionRecord,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
__all__ = [
|
|
55
|
+
"CANVAS_EVENT",
|
|
56
|
+
"DASHBOARD_SESSION",
|
|
57
|
+
"RESTORED_NOTE",
|
|
58
|
+
"RESTORE_TOOL",
|
|
59
|
+
"Compiled",
|
|
60
|
+
"DashboardSession",
|
|
61
|
+
"ReplayError",
|
|
62
|
+
"RestoreResult",
|
|
63
|
+
"Snapshot",
|
|
64
|
+
"canvas_payload",
|
|
65
|
+
"commit",
|
|
66
|
+
"compile_express",
|
|
67
|
+
"create_surface_message",
|
|
68
|
+
"inner_express",
|
|
69
|
+
"join_express",
|
|
70
|
+
"on_screen_section",
|
|
71
|
+
"rebuild_state",
|
|
72
|
+
"restore_revision",
|
|
73
|
+
"revision_snapshots",
|
|
74
|
+
"snapshot_at",
|
|
75
|
+
"split_express",
|
|
76
|
+
"surface_id_of",
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
# The run event that carries compiled A2UI messages to the browser (§5.2).
|
|
80
|
+
CANVAS_EVENT = "canvas.a2ui"
|
|
81
|
+
# `ToolContext.extras` key of the run's `DashboardSession`.
|
|
82
|
+
DASHBOARD_SESSION = "dashboard_session"
|
|
83
|
+
# Tool-trail name of a restore, on the note message it writes.
|
|
84
|
+
RESTORE_TOOL = "restore_revision"
|
|
85
|
+
# `message.note` code of a restore's note message (params: revision, from_revision).
|
|
86
|
+
RESTORED_NOTE = "revision.restored"
|
|
87
|
+
VERSION = "1.0"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class ReplayError(AgentDashboardError):
|
|
91
|
+
"""Stored Express no longer replays (e.g. the catalog changed incompatibly)."""
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def surface_id_of(conversation_id: str | uuid.UUID) -> str:
|
|
95
|
+
cid = conversation_id if isinstance(conversation_id, uuid.UUID) else uuid.UUID(conversation_id)
|
|
96
|
+
return surface_id_for(cid)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# --- Express stored on a message ------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
_TAGGED = re.compile(
|
|
102
|
+
re.escape(A2UI_INFERENCE_OPEN_TAG) + r"(.*?)" + re.escape(A2UI_INFERENCE_CLOSE_TAG), re.S
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _inner(express: str) -> str:
|
|
107
|
+
"""The Express inside `<a2ui>` tags (all tagged blocks, in order), or the whole text."""
|
|
108
|
+
blocks = _TAGGED.findall(express)
|
|
109
|
+
return "\n".join(b.strip() for b in blocks) if blocks else express.strip()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
inner_express = _inner
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def join_express(blocks: Sequence[str]) -> str | None:
|
|
116
|
+
"""The accepted Express blocks of one turn, as stored in `message.a2ui`: each in its own
|
|
117
|
+
`<a2ui>` tags, so replay applies them one by one."""
|
|
118
|
+
if not blocks:
|
|
119
|
+
return None
|
|
120
|
+
return "\n".join(
|
|
121
|
+
f"{A2UI_INFERENCE_OPEN_TAG}\n{_inner(b)}\n{A2UI_INFERENCE_CLOSE_TAG}" for b in blocks
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def split_express(stored: str | None) -> list[str]:
|
|
126
|
+
if not stored or not stored.strip():
|
|
127
|
+
return []
|
|
128
|
+
blocks = _TAGGED.findall(stored)
|
|
129
|
+
return [b.strip() for b in blocks] if blocks else [stored.strip()]
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# --- the surface document -------------------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _components_of(state: RendererState, surface_id: str) -> list[dict[str, Any]]:
|
|
136
|
+
surface = state.get_surface(surface_id)
|
|
137
|
+
if surface is None:
|
|
138
|
+
return []
|
|
139
|
+
return [
|
|
140
|
+
{"id": cid, "component": model.type, **copy.deepcopy(model.properties)}
|
|
141
|
+
for cid, model in surface.components_model.components_map.items()
|
|
142
|
+
]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _data_model_of(state: RendererState, surface_id: str) -> dict[str, Any]:
|
|
146
|
+
surface = state.get_surface(surface_id)
|
|
147
|
+
value = surface.data_model.get("/") if surface is not None else None
|
|
148
|
+
return copy.deepcopy(value) if isinstance(value, Mapping) else {}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _surface_doc(components: Iterable[Mapping[str, Any]], data_model: Mapping[str, Any]) -> dict:
|
|
152
|
+
return {
|
|
153
|
+
"components": checks.compact_components(components),
|
|
154
|
+
"dataModel": copy.deepcopy(dict(data_model)),
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def create_surface_message(
|
|
159
|
+
surface_id: str, surface: Mapping[str, Any], *, catalog_id: str = CATALOG_ID
|
|
160
|
+
) -> dict[str, Any]:
|
|
161
|
+
"""The one v1.0 message that recreates a stored surface (for a reopened conversation and
|
|
162
|
+
for rebuilding the `RendererState`)."""
|
|
163
|
+
body: dict[str, Any] = {
|
|
164
|
+
"surfaceId": surface_id,
|
|
165
|
+
"catalogId": catalog_id,
|
|
166
|
+
"components": copy.deepcopy(list(surface.get("components") or [])),
|
|
167
|
+
}
|
|
168
|
+
if surface.get("dataModel"):
|
|
169
|
+
body["dataModel"] = copy.deepcopy(dict(surface["dataModel"]))
|
|
170
|
+
return {"version": VERSION, "createSurface": body}
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def rebuild_state(
|
|
174
|
+
processor: ExpressProcessor,
|
|
175
|
+
surface_id: str,
|
|
176
|
+
surface: Mapping[str, Any] | None,
|
|
177
|
+
*,
|
|
178
|
+
catalog_id: str = CATALOG_ID,
|
|
179
|
+
) -> RendererState:
|
|
180
|
+
"""A fresh `RendererState` holding the stored surface, or empty when there is none."""
|
|
181
|
+
state = processor.create_state()
|
|
182
|
+
if surface and surface.get("components"):
|
|
183
|
+
state.apply([create_surface_message(surface_id, surface, catalog_id=catalog_id)])
|
|
184
|
+
state.check_topology([surface_id])
|
|
185
|
+
state.mark_checked([surface_id])
|
|
186
|
+
return state
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
# --- compile: parse, fill grids, candidate surface ------------------------------------------
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@dataclass(frozen=True)
|
|
193
|
+
class Compiled:
|
|
194
|
+
"""One Express block compiled against a state, not yet applied. `surface` is what the
|
|
195
|
+
stored surface document would be after it; `changed` the component ids it writes."""
|
|
196
|
+
|
|
197
|
+
messages: tuple[dict[str, Any], ...] = ()
|
|
198
|
+
surface: dict[str, Any] = field(default_factory=dict)
|
|
199
|
+
changed: tuple[str, ...] = ()
|
|
200
|
+
errors: tuple[ExpressError, ...] = ()
|
|
201
|
+
|
|
202
|
+
@property
|
|
203
|
+
def ok(self) -> bool:
|
|
204
|
+
return not self.errors
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
class _Rollback(Exception):
|
|
208
|
+
pass
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _fill_grids(messages: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
|
|
212
|
+
out = copy.deepcopy([dict(m) for m in messages])
|
|
213
|
+
for message in out:
|
|
214
|
+
for op in ("createSurface", "updateComponents"):
|
|
215
|
+
body = message.get(op)
|
|
216
|
+
for component in (body or {}).get("components") or []:
|
|
217
|
+
if component.get("component") == "DashboardGrid" and isinstance(
|
|
218
|
+
component.get("items"), list
|
|
219
|
+
):
|
|
220
|
+
items = [i for i in component["items"] if isinstance(i, Mapping)]
|
|
221
|
+
if not checks.grid_problems(str(component.get("id")), items):
|
|
222
|
+
component["items"] = checks.fill_grid(items)
|
|
223
|
+
return out
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _written_ids(messages: Iterable[Mapping[str, Any]]) -> list[str]:
|
|
227
|
+
ids: list[str] = []
|
|
228
|
+
for message in messages:
|
|
229
|
+
for op in ("createSurface", "updateComponents"):
|
|
230
|
+
for component in (message.get(op) or {}).get("components") or []:
|
|
231
|
+
if isinstance(component.get("id"), str):
|
|
232
|
+
ids.append(component["id"])
|
|
233
|
+
return ids
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def compile_express(
|
|
237
|
+
processor: ExpressProcessor, state: RendererState, express: str, surface_id: str
|
|
238
|
+
) -> Compiled:
|
|
239
|
+
"""Parses `express` against `state` and works out the surface it would leave, then rolls
|
|
240
|
+
the state back: nothing is applied until `commit`. DashboardGrid items without x/y are
|
|
241
|
+
placed here (§1.10 *Layout*). Synchronous; call it through `asyncio.to_thread`."""
|
|
242
|
+
try:
|
|
243
|
+
with state.transaction():
|
|
244
|
+
result = processor.parse(express, surface_id=surface_id, state=state)
|
|
245
|
+
if not result.ok:
|
|
246
|
+
return Compiled(errors=result.errors)
|
|
247
|
+
messages = _fill_grids(result.messages)
|
|
248
|
+
changed = _written_ids(messages)
|
|
249
|
+
filled = {
|
|
250
|
+
c["id"]: c
|
|
251
|
+
for m in messages
|
|
252
|
+
for op in ("createSurface", "updateComponents")
|
|
253
|
+
for c in (m.get(op) or {}).get("components") or []
|
|
254
|
+
}
|
|
255
|
+
components = [filled.get(c["id"], c) for c in _components_of(state, surface_id)]
|
|
256
|
+
surface = _surface_doc(components, _data_model_of(state, surface_id))
|
|
257
|
+
raise _Rollback
|
|
258
|
+
except _Rollback:
|
|
259
|
+
pass
|
|
260
|
+
return Compiled(messages=tuple(messages), surface=surface, changed=tuple(changed))
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def commit(state: RendererState, messages: Sequence[Mapping[str, Any]]) -> None:
|
|
264
|
+
"""Applies compiled messages for real (all or nothing)."""
|
|
265
|
+
surface_ids = state.apply(list(messages))
|
|
266
|
+
state.check_topology(surface_ids)
|
|
267
|
+
state.mark_checked(surface_ids)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def canvas_payload(
|
|
271
|
+
surface_id: str, revision: int, messages: Sequence[Mapping[str, Any]]
|
|
272
|
+
) -> dict[str, Any]:
|
|
273
|
+
"""The data of a `canvas.a2ui` run event (§5.2)."""
|
|
274
|
+
return {"surface_id": surface_id, "revision": revision, "messages": [dict(m) for m in messages]}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
# --- the run's session ----------------------------------------------------------------------
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _registry_json(registry: QueryRegistry, ids: Iterable[str] | None = None) -> dict[str, Any]:
|
|
281
|
+
wanted = set(ids) if ids is not None else None
|
|
282
|
+
return {
|
|
283
|
+
q.query_id: q.model_dump(mode="json")
|
|
284
|
+
for q in registry
|
|
285
|
+
if wanted is None or q.query_id in wanted
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def referenced_queries(surface: Mapping[str, Any]) -> list[str]:
|
|
290
|
+
seen: list[str] = []
|
|
291
|
+
for component in surface.get("components") or []:
|
|
292
|
+
data = component.get("data")
|
|
293
|
+
if isinstance(data, Mapping) and data.get("@call") == "runQuery":
|
|
294
|
+
query_id = (data.get("args") or {}).get("queryId")
|
|
295
|
+
if isinstance(query_id, str) and query_id not in seen:
|
|
296
|
+
seen.append(query_id)
|
|
297
|
+
return seen
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
@dataclass
|
|
301
|
+
class DashboardSession:
|
|
302
|
+
"""A conversation's dashboard for the length of one run."""
|
|
303
|
+
|
|
304
|
+
conversation_id: str
|
|
305
|
+
surface_id: str
|
|
306
|
+
processor: ExpressProcessor
|
|
307
|
+
state: RendererState
|
|
308
|
+
registry: QueryRegistry
|
|
309
|
+
revision: int = 0
|
|
310
|
+
surface: dict[str, Any] | None = None
|
|
311
|
+
catalog_id: str = CATALOG_ID
|
|
312
|
+
accepted: list[str] = field(default_factory=list)
|
|
313
|
+
"""Express blocks accepted this turn, in order."""
|
|
314
|
+
turn_revision: int | None = None
|
|
315
|
+
"""The revision the turn's last accepted render stored."""
|
|
316
|
+
run_id: str | None = None
|
|
317
|
+
"""The run this session belongs to; stored with each revision it renders."""
|
|
318
|
+
lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
|
|
319
|
+
|
|
320
|
+
@classmethod
|
|
321
|
+
async def load(
|
|
322
|
+
cls,
|
|
323
|
+
storage: Any,
|
|
324
|
+
conversation_id: str,
|
|
325
|
+
processor: ExpressProcessor,
|
|
326
|
+
*,
|
|
327
|
+
run_id: str | None = None,
|
|
328
|
+
) -> DashboardSession:
|
|
329
|
+
"""Rebuilds the session from the stored dashboard (run start, §5.1)."""
|
|
330
|
+
record: DashboardRecord | None = await storage.dashboards.get(conversation_id)
|
|
331
|
+
surface_id = surface_id_of(conversation_id)
|
|
332
|
+
if record is None:
|
|
333
|
+
return cls(
|
|
334
|
+
conversation_id=conversation_id,
|
|
335
|
+
surface_id=surface_id,
|
|
336
|
+
processor=processor,
|
|
337
|
+
state=processor.create_state(),
|
|
338
|
+
registry=QueryRegistry(),
|
|
339
|
+
run_id=run_id,
|
|
340
|
+
)
|
|
341
|
+
state = await asyncio.to_thread(
|
|
342
|
+
rebuild_state, processor, surface_id, record.surface, catalog_id=record.catalog_id
|
|
343
|
+
)
|
|
344
|
+
return cls(
|
|
345
|
+
conversation_id=conversation_id,
|
|
346
|
+
surface_id=surface_id,
|
|
347
|
+
processor=processor,
|
|
348
|
+
state=state,
|
|
349
|
+
registry=QueryRegistry.from_json(list(record.queries.values())),
|
|
350
|
+
revision=record.revision,
|
|
351
|
+
surface=copy.deepcopy(record.surface),
|
|
352
|
+
catalog_id=record.catalog_id,
|
|
353
|
+
run_id=run_id,
|
|
354
|
+
)
|
|
355
|
+
|
|
356
|
+
def accept(self, express: str, record: DashboardRecord) -> None:
|
|
357
|
+
self.accepted.append(_inner(express))
|
|
358
|
+
self.revision = record.revision
|
|
359
|
+
self.surface = copy.deepcopy(record.surface)
|
|
360
|
+
self.turn_revision = record.revision
|
|
361
|
+
|
|
362
|
+
def message_fields(self) -> dict[str, Any]:
|
|
363
|
+
"""`a2ui` and `revision` for the turn's assistant message (§4.1)."""
|
|
364
|
+
return {"a2ui": join_express(self.accepted), "revision": self.turn_revision}
|
|
365
|
+
|
|
366
|
+
def on_screen(self) -> str:
|
|
367
|
+
return on_screen_section(self.surface_id, self.surface, self.registry, self.revision)
|
|
368
|
+
|
|
369
|
+
def reset_state(self) -> None:
|
|
370
|
+
"""Back to the last stored surface (after a failed store)."""
|
|
371
|
+
self.state = rebuild_state(
|
|
372
|
+
self.processor, self.surface_id, self.surface, catalog_id=self.catalog_id
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
# --- the host prompt's "on screen" section ---------------------------------------------------
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def on_screen_section(
|
|
380
|
+
surface_id: str,
|
|
381
|
+
surface: Mapping[str, Any] | None,
|
|
382
|
+
registry: QueryRegistry | None = None,
|
|
383
|
+
revision: int = 0,
|
|
384
|
+
) -> str:
|
|
385
|
+
"""What the model is told about the dashboard: its surface id and the components on
|
|
386
|
+
screen (id, type, queryId, title), as a tree (§1.10 decision 6, §6.4 step 1)."""
|
|
387
|
+
registry = registry or QueryRegistry()
|
|
388
|
+
queries = _queries_text(registry)
|
|
389
|
+
if not surface or not surface.get("components"):
|
|
390
|
+
return (
|
|
391
|
+
"[Host] This conversation has no dashboard yet. Its surface id is "
|
|
392
|
+
f'"{surface_id}": create it with surface("{surface_id}") and root = Dashboard(...).'
|
|
393
|
+
+ (f"\nRegistered queries:\n{queries}" if queries else "")
|
|
394
|
+
)
|
|
395
|
+
components = {str(c["id"]): c for c in surface["components"]}
|
|
396
|
+
lines = [
|
|
397
|
+
f'[Host] On screen: dashboard surface "{surface_id}", revision {revision}. Change it '
|
|
398
|
+
f'with surface("{surface_id}", update=true) and only the components that change; '
|
|
399
|
+
"refer to these ids without redefining them:"
|
|
400
|
+
]
|
|
401
|
+
for cid, depth, _ in checks.walk(components):
|
|
402
|
+
component = components[cid]
|
|
403
|
+
parts = [f"{' ' * depth}- {cid}: {component.get('component')}"]
|
|
404
|
+
title = component.get("title") or component.get("label")
|
|
405
|
+
if isinstance(title, str):
|
|
406
|
+
parts.append(json.dumps(title, ensure_ascii=False))
|
|
407
|
+
data = component.get("data")
|
|
408
|
+
if isinstance(data, Mapping) and data.get("@call") == "runQuery":
|
|
409
|
+
parts.append(f"(query {(data.get('args') or {}).get('queryId')})")
|
|
410
|
+
lines.append(" ".join(parts))
|
|
411
|
+
filters = (surface.get("dataModel") or {}).get("filters")
|
|
412
|
+
if isinstance(filters, Mapping) and filters:
|
|
413
|
+
defaults = ", ".join(f"{k}={json.dumps(v, ensure_ascii=False)}" for k, v in filters.items())
|
|
414
|
+
lines.append(f"Filter defaults: {defaults}")
|
|
415
|
+
if queries:
|
|
416
|
+
lines.append(f"Registered queries:\n{queries}")
|
|
417
|
+
return "\n".join(lines)
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _queries_text(registry: QueryRegistry) -> str:
|
|
421
|
+
return "\n".join(
|
|
422
|
+
f"- {q.query_id}: "
|
|
423
|
+
+ (", ".join(f"{c.name} ({c.kind})" for c in q.columns) or "columns unknown")
|
|
424
|
+
+ (f"; filters {', '.join(q.filters_used)}" if q.filters_used else "")
|
|
425
|
+
for q in registry
|
|
426
|
+
)
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
# --- revision snapshots --------------------------------------------------------------------
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
@dataclass(frozen=True)
|
|
433
|
+
class Snapshot:
|
|
434
|
+
"""A revision as it was stored: its surface document and the queries it references."""
|
|
435
|
+
|
|
436
|
+
revision: int
|
|
437
|
+
message_id: int | None
|
|
438
|
+
surface: dict[str, Any]
|
|
439
|
+
queries: QueryRegistry
|
|
440
|
+
|
|
441
|
+
def create_messages(self, surface_id: str) -> list[dict[str, Any]]:
|
|
442
|
+
return [create_surface_message(surface_id, self.surface)]
|
|
443
|
+
|
|
444
|
+
@classmethod
|
|
445
|
+
def of(cls, record: RevisionRecord) -> Snapshot:
|
|
446
|
+
return cls(
|
|
447
|
+
revision=record.revision,
|
|
448
|
+
message_id=record.message_id,
|
|
449
|
+
surface=copy.deepcopy(record.surface),
|
|
450
|
+
queries=QueryRegistry.from_json(list(record.queries.values())),
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
async def revision_snapshots(storage: Any, conversation_id: str) -> list[Snapshot]:
|
|
455
|
+
"""Every stored revision of the conversation's dashboard, oldest first."""
|
|
456
|
+
return [Snapshot.of(r) for r in await storage.dashboards.list_revisions(conversation_id)]
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
async def snapshot_at(storage: Any, conversation_id: str, revision: int) -> Snapshot:
|
|
460
|
+
"""The surface and queries of one revision, as stored with it (a revision chip).
|
|
461
|
+
|
|
462
|
+
Raises:
|
|
463
|
+
NotFound: No such revision.
|
|
464
|
+
"""
|
|
465
|
+
record = await storage.dashboards.get_revision(conversation_id, revision)
|
|
466
|
+
if record is None:
|
|
467
|
+
raise NotFound(f"revision {revision} of conversation {conversation_id}")
|
|
468
|
+
return Snapshot.of(record)
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
# --- restore --------------------------------------------------------------------------------
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
@dataclass(frozen=True)
|
|
475
|
+
class RestoreResult:
|
|
476
|
+
record: DashboardRecord
|
|
477
|
+
message: MessageRecord
|
|
478
|
+
payload: dict[str, Any]
|
|
479
|
+
"""The `canvas.a2ui` event data to send."""
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _restore_express(
|
|
483
|
+
processor: ExpressProcessor,
|
|
484
|
+
surface_id: str,
|
|
485
|
+
snapshot: Snapshot,
|
|
486
|
+
current_filters: Mapping[str, Any],
|
|
487
|
+
) -> str:
|
|
488
|
+
"""One `update=true` block that turns the current surface into the snapshot."""
|
|
489
|
+
decompiler = ExpressDecompiler([processor.catalog])
|
|
490
|
+
messages: list[dict[str, Any]] = [
|
|
491
|
+
{
|
|
492
|
+
"version": VERSION,
|
|
493
|
+
"updateComponents": {
|
|
494
|
+
"surfaceId": surface_id,
|
|
495
|
+
"components": copy.deepcopy(snapshot.surface["components"]),
|
|
496
|
+
},
|
|
497
|
+
}
|
|
498
|
+
]
|
|
499
|
+
filters = (snapshot.surface.get("dataModel") or {}).get("filters") or {}
|
|
500
|
+
for key in current_filters:
|
|
501
|
+
if key not in filters:
|
|
502
|
+
messages.append(_data_write(surface_id, key, None))
|
|
503
|
+
for key, value in filters.items():
|
|
504
|
+
messages.append(_data_write(surface_id, key, value))
|
|
505
|
+
body: list[str] = []
|
|
506
|
+
for message in messages:
|
|
507
|
+
lines = decompiler.decompile([message], use_keyword_args=True).split("\n")
|
|
508
|
+
body.extend(lines[1:]) # drop each block's own surface(...) header
|
|
509
|
+
return "\n".join([f'surface("{surface_id}", update=true)', *body])
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def _data_write(surface_id: str, key: str, value: Any) -> dict[str, Any]:
|
|
513
|
+
return {
|
|
514
|
+
"version": VERSION,
|
|
515
|
+
"updateDataModel": {"surfaceId": surface_id, "path": f"/filters/{key}", "value": value},
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
async def restore_revision(
|
|
520
|
+
storage: Any,
|
|
521
|
+
processor: ExpressProcessor,
|
|
522
|
+
conversation_id: str,
|
|
523
|
+
revision: int,
|
|
524
|
+
*,
|
|
525
|
+
note: str | None = None,
|
|
526
|
+
run_id: str | None = None,
|
|
527
|
+
) -> RestoreResult:
|
|
528
|
+
"""Makes an older revision the newest (§9 acceptance 10): a new revision with the
|
|
529
|
+
snapshot's surface and queries (as stored with that revision, so a query id redefined
|
|
530
|
+
since binds to the SQL it had then), recorded on an assistant note message. The result
|
|
531
|
+
goes through `check_surface` before it is stored. The caller makes sure no run is active
|
|
532
|
+
on the conversation.
|
|
533
|
+
|
|
534
|
+
Raises:
|
|
535
|
+
NotFound: The conversation has no dashboard or no such revision.
|
|
536
|
+
ReplayError: The snapshot no longer compiles or no longer passes the checks.
|
|
537
|
+
"""
|
|
538
|
+
record = await storage.dashboards.get(conversation_id)
|
|
539
|
+
if record is None:
|
|
540
|
+
raise NotFound(f"dashboard of conversation {conversation_id}")
|
|
541
|
+
snapshot = await snapshot_at(storage, conversation_id, revision)
|
|
542
|
+
surface_id = surface_id_of(conversation_id)
|
|
543
|
+
current_filters = (record.surface.get("dataModel") or {}).get("filters") or {}
|
|
544
|
+
express = _restore_express(processor, surface_id, snapshot, current_filters)
|
|
545
|
+
|
|
546
|
+
def compile_on_current() -> Compiled:
|
|
547
|
+
state = rebuild_state(processor, surface_id, record.surface, catalog_id=record.catalog_id)
|
|
548
|
+
return compile_express(processor, state, express, surface_id)
|
|
549
|
+
|
|
550
|
+
compiled = await asyncio.to_thread(compile_on_current)
|
|
551
|
+
if not compiled.ok:
|
|
552
|
+
raise ReplayError(
|
|
553
|
+
f"revision {revision} can't be restored: "
|
|
554
|
+
+ "; ".join(e.for_model() for e in compiled.errors)
|
|
555
|
+
)
|
|
556
|
+
registry = snapshot.queries
|
|
557
|
+
problems = checks.check_surface(compiled.surface, registry, changed=compiled.changed)
|
|
558
|
+
if problems:
|
|
559
|
+
raise ReplayError(
|
|
560
|
+
f"revision {revision} can't be restored: " + "; ".join(p.for_model() for p in problems)
|
|
561
|
+
)
|
|
562
|
+
ids = referenced_queries(compiled.surface)
|
|
563
|
+
async with storage.transaction() as tx:
|
|
564
|
+
new = await tx.dashboards.put(
|
|
565
|
+
conversation_id,
|
|
566
|
+
catalog_id=record.catalog_id,
|
|
567
|
+
surface=compiled.surface,
|
|
568
|
+
queries=_registry_json(registry, ids),
|
|
569
|
+
express=express,
|
|
570
|
+
source="restore",
|
|
571
|
+
run_id=run_id,
|
|
572
|
+
expected_revision=record.revision,
|
|
573
|
+
)
|
|
574
|
+
text = note or f"Restored revision {revision} as revision {new.revision}."
|
|
575
|
+
message = await tx.messages.add(
|
|
576
|
+
conversation_id=conversation_id,
|
|
577
|
+
role="assistant",
|
|
578
|
+
content=text,
|
|
579
|
+
run_id=run_id,
|
|
580
|
+
a2ui=join_express([express]),
|
|
581
|
+
revision=new.revision,
|
|
582
|
+
note={
|
|
583
|
+
"code": RESTORED_NOTE,
|
|
584
|
+
"params": {"revision": new.revision, "from_revision": revision},
|
|
585
|
+
},
|
|
586
|
+
tool_trace=[
|
|
587
|
+
{
|
|
588
|
+
"name": RESTORE_TOOL,
|
|
589
|
+
"input": {"revision": revision},
|
|
590
|
+
"result": text,
|
|
591
|
+
"is_error": False,
|
|
592
|
+
}
|
|
593
|
+
],
|
|
594
|
+
)
|
|
595
|
+
await tx.dashboards.link_message(conversation_id, message.id, revision=new.revision)
|
|
596
|
+
return RestoreResult(
|
|
597
|
+
record=new,
|
|
598
|
+
message=message,
|
|
599
|
+
payload=canvas_payload(surface_id, new.revision, compiled.messages),
|
|
600
|
+
)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""A conversation's one dashboard surface id: `dash_` + the conversation UUID as 32 hex chars."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import uuid
|
|
7
|
+
|
|
8
|
+
__all__ = ["SURFACE_PREFIX", "conversation_id_for", "surface_id_for"]
|
|
9
|
+
|
|
10
|
+
SURFACE_PREFIX = "dash_"
|
|
11
|
+
_SURFACE_ID = re.compile(r"^dash_([0-9a-f]{32})$")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def surface_id_for(conversation_id: uuid.UUID) -> str:
|
|
15
|
+
return SURFACE_PREFIX + conversation_id.hex
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def conversation_id_for(surface_id: str) -> uuid.UUID:
|
|
19
|
+
"""Raises ValueError for anything that isn't `dash_` + 32 lowercase hex."""
|
|
20
|
+
match = _SURFACE_ID.fullmatch(surface_id) if isinstance(surface_id, str) else None
|
|
21
|
+
if match is None:
|
|
22
|
+
raise ValueError(f"not a dashboard surface id: {surface_id!r}")
|
|
23
|
+
return uuid.UUID(hex=match.group(1))
|