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,409 @@
|
|
|
1
|
+
"""Grid layout actions: direct revisions of the dashboard, with no model turn (design §1.10
|
|
2
|
+
*Layout* → *Editing*, §6.2).
|
|
3
|
+
|
|
4
|
+
The chat UI sends two A2UI `action`s to `POST /surfaces/{sid}/actions` that only move
|
|
5
|
+
widgets around, so the server applies them itself:
|
|
6
|
+
|
|
7
|
+
- `gridLayoutChange` (a drag or resize in the expanded dashboard): `sourceComponentId` is the
|
|
8
|
+
`DashboardGrid`, `context.items` its new `[{child, x, y, w, h}]`. Every child stays; only
|
|
9
|
+
coordinates and sizes change.
|
|
10
|
+
- `arrangeOnGrid` (the block header's "Arrange on grid"): the free Row/Column layout under the
|
|
11
|
+
Dashboard's `body` becomes one `DashboardGrid`, flattened in reading order. A Row splits its
|
|
12
|
+
width among its children by `weight`; a Column stacks them. Card, Tabs and leaf widgets
|
|
13
|
+
become grid items as they are.
|
|
14
|
+
|
|
15
|
+
Each accepted action is stored exactly like `restore_revision` stores a restore: one
|
|
16
|
+
generated `update=true` Express block is compiled against the current surface, checked by the
|
|
17
|
+
check layer (only problems the action introduces refuse it), written as a new `dashboard`
|
|
18
|
+
revision (with its `dashboard_revision` row, source `layout`) and recorded on an assistant
|
|
19
|
+
note message carrying that Express and a structured `note` (`layout.changed` /
|
|
20
|
+
`layout.arranged`) the UI translates. The agent sees the note on its next turn.
|
|
21
|
+
|
|
22
|
+
The caller (the HTTP route) checks ownership, the `QUERY` capability and that no run is active.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import asyncio
|
|
28
|
+
import copy
|
|
29
|
+
from collections.abc import Mapping, Sequence
|
|
30
|
+
from dataclasses import dataclass
|
|
31
|
+
from typing import Any
|
|
32
|
+
|
|
33
|
+
from a2ui.inference_formats.express.decompiler import ExpressDecompiler
|
|
34
|
+
|
|
35
|
+
from agent2dashboard.a2ui import checks
|
|
36
|
+
from agent2dashboard.a2ui.express import ExpressProcessor
|
|
37
|
+
from agent2dashboard.a2ui.state import (
|
|
38
|
+
VERSION,
|
|
39
|
+
Compiled,
|
|
40
|
+
canvas_payload,
|
|
41
|
+
compile_express,
|
|
42
|
+
join_express,
|
|
43
|
+
rebuild_state,
|
|
44
|
+
surface_id_of,
|
|
45
|
+
)
|
|
46
|
+
from agent2dashboard.errors import AgentDashboardError
|
|
47
|
+
from agent2dashboard.query.registry import QueryRegistry
|
|
48
|
+
from agent2dashboard.storage.records import DashboardRecord, MessageRecord
|
|
49
|
+
|
|
50
|
+
__all__ = [
|
|
51
|
+
"ARRANGE_ON_GRID",
|
|
52
|
+
"GRID_LAYOUT_CHANGE",
|
|
53
|
+
"LAYOUT_ACTIONS",
|
|
54
|
+
"LAYOUT_TOOL",
|
|
55
|
+
"LayoutActionError",
|
|
56
|
+
"LayoutResult",
|
|
57
|
+
"NOTE_CODES",
|
|
58
|
+
"apply_layout_action",
|
|
59
|
+
"arrange_items",
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
GRID_LAYOUT_CHANGE = "gridLayoutChange"
|
|
63
|
+
ARRANGE_ON_GRID = "arrangeOnGrid"
|
|
64
|
+
LAYOUT_ACTIONS = frozenset({GRID_LAYOUT_CHANGE, ARRANGE_ON_GRID})
|
|
65
|
+
# Tool-trail name on the note message a layout action writes.
|
|
66
|
+
LAYOUT_TOOL = "layout_action"
|
|
67
|
+
|
|
68
|
+
# Catalog bounds of a DashboardGrid item (catalog.json `DashboardGrid.items`).
|
|
69
|
+
MAX_ITEMS = 24
|
|
70
|
+
MAX_H = 40
|
|
71
|
+
MAX_Y = 1000
|
|
72
|
+
# Grid rows per height token (one grid row is 40 px in the renderer; a KPI is 2, a chart 6).
|
|
73
|
+
HEIGHT_ROWS = {"xs": 2, "sm": 4, "md": 6, "lg": 8, "xl": 10}
|
|
74
|
+
DEFAULT_ROWS = {
|
|
75
|
+
"KpiCard": 2,
|
|
76
|
+
"BarChart": 6,
|
|
77
|
+
"LineChart": 6,
|
|
78
|
+
"AreaChart": 6,
|
|
79
|
+
"PieChart": 6,
|
|
80
|
+
"DataTable": 8,
|
|
81
|
+
"Text": 1,
|
|
82
|
+
"Notice": 1,
|
|
83
|
+
"Divider": 1,
|
|
84
|
+
}
|
|
85
|
+
_FLOWING = frozenset({"Row", "Column"})
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class LayoutActionError(AgentDashboardError):
|
|
89
|
+
"""A layout action that can't be applied. `status` is the HTTP answer: 404 (no dashboard),
|
|
90
|
+
409 (not applicable to the current layout) or 422 (invalid layout)."""
|
|
91
|
+
|
|
92
|
+
def __init__(self, status: int, code: str, message: str, problems: Sequence[str] = ()) -> None:
|
|
93
|
+
super().__init__(message)
|
|
94
|
+
self.status = status
|
|
95
|
+
self.code = code
|
|
96
|
+
self.message = message
|
|
97
|
+
self.problems = tuple(problems)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@dataclass(frozen=True)
|
|
101
|
+
class LayoutResult:
|
|
102
|
+
record: DashboardRecord
|
|
103
|
+
message: MessageRecord | None
|
|
104
|
+
"""The note message, or None when the action changed nothing (no new revision)."""
|
|
105
|
+
payload: dict[str, Any] | None
|
|
106
|
+
"""The `canvas.a2ui` data of the change, or None when nothing changed."""
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _invalid(message: str, problems: Sequence[str] = ()) -> LayoutActionError:
|
|
110
|
+
return LayoutActionError(422, "invalid_layout", message, problems)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# --- gridLayoutChange -------------------------------------------------------------------------
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _int(value: Any) -> int | None:
|
|
117
|
+
return value if isinstance(value, int) and not isinstance(value, bool) else None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _parse_items(raw: Any) -> list[dict[str, Any]]:
|
|
121
|
+
if not isinstance(raw, list) or not 1 <= len(raw) <= MAX_ITEMS:
|
|
122
|
+
raise _invalid(f"`context.items` must be a list of 1 to {MAX_ITEMS} grid items.")
|
|
123
|
+
items: list[dict[str, Any]] = []
|
|
124
|
+
for index, entry in enumerate(raw):
|
|
125
|
+
if not isinstance(entry, Mapping) or set(entry) != {"child", "x", "y", "w", "h"}:
|
|
126
|
+
raise _invalid(f"Item {index} must have exactly child, x, y, w and h.")
|
|
127
|
+
child = entry["child"]
|
|
128
|
+
x, y, w, h = (_int(entry[k]) for k in ("x", "y", "w", "h"))
|
|
129
|
+
if not isinstance(child, str) or None in (x, y, w, h):
|
|
130
|
+
raise _invalid(f"Item {index}: child is an id and x, y, w, h are integers.")
|
|
131
|
+
assert x is not None and y is not None and w is not None and h is not None
|
|
132
|
+
if not (
|
|
133
|
+
0 <= x < checks.GRID_COLUMNS
|
|
134
|
+
and 0 <= y <= MAX_Y
|
|
135
|
+
and 1 <= w <= checks.GRID_COLUMNS
|
|
136
|
+
and 1 <= h <= MAX_H
|
|
137
|
+
):
|
|
138
|
+
raise _invalid(
|
|
139
|
+
f"Item {index} ({child}) is out of bounds: x 0..11, y 0..{MAX_Y}, w 1..12, "
|
|
140
|
+
f"h 1..{MAX_H}."
|
|
141
|
+
)
|
|
142
|
+
items.append({"child": child, "x": x, "y": y, "w": w, "h": h})
|
|
143
|
+
return items
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _reading_order(items: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
|
|
147
|
+
"""Top to bottom, then left to right: the order the grid stacks in on a phone."""
|
|
148
|
+
return sorted((dict(i) for i in items), key=lambda i: (i["y"], i["x"]))
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _grid_change(
|
|
152
|
+
components: Mapping[str, dict[str, Any]], action: Mapping[str, Any]
|
|
153
|
+
) -> list[dict[str, Any]]:
|
|
154
|
+
grid_id = action.get("sourceComponentId")
|
|
155
|
+
grid = components.get(grid_id) if isinstance(grid_id, str) else None
|
|
156
|
+
if grid is None or grid.get("component") != "DashboardGrid":
|
|
157
|
+
raise _invalid("`sourceComponentId` must be a DashboardGrid on this dashboard.")
|
|
158
|
+
context = action.get("context")
|
|
159
|
+
items = _parse_items(context.get("items") if isinstance(context, Mapping) else None)
|
|
160
|
+
problems = checks.grid_problems(str(grid_id), items)
|
|
161
|
+
if problems:
|
|
162
|
+
raise _invalid("The grid doesn't fit.", [p.for_model() for p in problems])
|
|
163
|
+
current = [i.get("child") for i in grid.get("items") or [] if isinstance(i, Mapping)]
|
|
164
|
+
if sorted(map(str, current)) != sorted(i["child"] for i in items):
|
|
165
|
+
raise _invalid("A layout change can move and resize widgets, not add or remove them.")
|
|
166
|
+
return [{**grid, "items": _reading_order(items)}]
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# --- arrangeOnGrid ----------------------------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _leaf_rows(components: Mapping[str, Mapping[str, Any]], cid: str, width: int) -> int:
|
|
173
|
+
component = components.get(cid) or {}
|
|
174
|
+
kind = component.get("component")
|
|
175
|
+
token = component.get("height")
|
|
176
|
+
if isinstance(token, str) and token in HEIGHT_ROWS:
|
|
177
|
+
rows = HEIGHT_ROWS[token]
|
|
178
|
+
elif kind == "Card":
|
|
179
|
+
child = component.get("child")
|
|
180
|
+
inner = _place(components, child, 0, width, 0)[1] if isinstance(child, str) else 1
|
|
181
|
+
rows = inner + 1
|
|
182
|
+
elif kind == "Tabs":
|
|
183
|
+
tabs = [t for t in component.get("tabs") or [] if isinstance(t, Mapping)]
|
|
184
|
+
rows = 1 + max(
|
|
185
|
+
(
|
|
186
|
+
_place(components, t["child"], 0, width, 0)[1]
|
|
187
|
+
for t in tabs
|
|
188
|
+
if isinstance(t.get("child"), str)
|
|
189
|
+
),
|
|
190
|
+
default=1,
|
|
191
|
+
)
|
|
192
|
+
elif kind == "DashboardGrid":
|
|
193
|
+
items = [i for i in component.get("items") or [] if isinstance(i, Mapping)]
|
|
194
|
+
rows = max((int(i.get("y", 0)) + int(i.get("h", 1)) for i in items), default=1)
|
|
195
|
+
else:
|
|
196
|
+
rows = DEFAULT_ROWS.get(str(kind), 4)
|
|
197
|
+
return min(max(rows, 1), MAX_H)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _split(width: int, weights: Sequence[float]) -> list[int]:
|
|
201
|
+
"""`width` columns shared by `weights` (largest remainder), each at least 1."""
|
|
202
|
+
total = sum(weights)
|
|
203
|
+
spare = width - len(weights)
|
|
204
|
+
exact = [spare * w / total for w in weights]
|
|
205
|
+
shares = [int(e) for e in exact]
|
|
206
|
+
order = sorted(range(len(weights)), key=lambda i: exact[i] - shares[i], reverse=True)
|
|
207
|
+
for i in order[: spare - sum(shares)]:
|
|
208
|
+
shares[i] += 1
|
|
209
|
+
return [s + 1 for s in shares]
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _weight(component: Mapping[str, Any] | None) -> float:
|
|
213
|
+
value = (component or {}).get("weight")
|
|
214
|
+
return float(value) if isinstance(value, int | float) and value > 0 else 1.0
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _place(
|
|
218
|
+
components: Mapping[str, Mapping[str, Any]], cid: str, x: int, width: int, y: int
|
|
219
|
+
) -> tuple[list[dict[str, Any]], int]:
|
|
220
|
+
"""Grid items for the subtree at `cid` in the box (x, y, width), and its height in rows."""
|
|
221
|
+
component = components.get(cid)
|
|
222
|
+
if component is None:
|
|
223
|
+
return [], 0
|
|
224
|
+
kind = component.get("component")
|
|
225
|
+
children = [c for c in checks.child_ids(component) if c in components]
|
|
226
|
+
if kind == "Column" or (kind == "Row" and len(children) > width):
|
|
227
|
+
items: list[dict[str, Any]] = []
|
|
228
|
+
top = y
|
|
229
|
+
for child in children:
|
|
230
|
+
placed, rows = _place(components, child, x, width, top)
|
|
231
|
+
items.extend(placed)
|
|
232
|
+
top += rows
|
|
233
|
+
return items, top - y
|
|
234
|
+
if kind == "Row":
|
|
235
|
+
if not children:
|
|
236
|
+
return [], 0
|
|
237
|
+
widths = _split(width, [_weight(components.get(c)) for c in children])
|
|
238
|
+
items, rows, left = [], 0, x
|
|
239
|
+
leaves: list[dict[str, Any]] = []
|
|
240
|
+
for child, w in zip(children, widths, strict=True):
|
|
241
|
+
placed, height = _place(components, child, left, w, y)
|
|
242
|
+
if components[child].get("component") not in _FLOWING:
|
|
243
|
+
leaves.extend(placed)
|
|
244
|
+
items.extend(placed)
|
|
245
|
+
rows = max(rows, height)
|
|
246
|
+
left += w
|
|
247
|
+
for leaf in leaves: # widgets in one Row share one height
|
|
248
|
+
leaf["h"] = rows
|
|
249
|
+
return items, rows
|
|
250
|
+
rows = _leaf_rows(components, cid, width)
|
|
251
|
+
return [{"child": cid, "x": x, "y": y, "w": width, "h": rows}], rows
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def arrange_items(components: Mapping[str, Mapping[str, Any]], body: str) -> list[dict[str, Any]]:
|
|
255
|
+
"""The `DashboardGrid` items that reproduce the free layout under `body`, in reading
|
|
256
|
+
order, on 12 columns."""
|
|
257
|
+
items, _ = _place(components, body, 0, checks.GRID_COLUMNS, 0)
|
|
258
|
+
return _reading_order(items)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _free_id(components: Mapping[str, Any], base: str = "grid") -> str:
|
|
262
|
+
if base not in components:
|
|
263
|
+
return base
|
|
264
|
+
n = 2
|
|
265
|
+
while f"{base}_{n}" in components:
|
|
266
|
+
n += 1
|
|
267
|
+
return f"{base}_{n}"
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _arrange(components: Mapping[str, dict[str, Any]]) -> list[dict[str, Any]]:
|
|
271
|
+
root = components.get(checks.ROOT_ID)
|
|
272
|
+
body = root.get("body") if root else None
|
|
273
|
+
if root is None or not isinstance(body, str) or body not in components:
|
|
274
|
+
raise LayoutActionError(409, "no_layout", "This dashboard has no body to arrange.")
|
|
275
|
+
kind = components[body].get("component")
|
|
276
|
+
if kind == "DashboardGrid":
|
|
277
|
+
raise LayoutActionError(409, "already_on_grid", "This dashboard is already on a grid.")
|
|
278
|
+
items = arrange_items(components, body)
|
|
279
|
+
if not items:
|
|
280
|
+
raise LayoutActionError(409, "no_layout", "This dashboard has nothing to arrange.")
|
|
281
|
+
if len(items) > MAX_ITEMS:
|
|
282
|
+
raise _invalid(f"A grid holds at most {MAX_ITEMS} items; this layout has {len(items)}.")
|
|
283
|
+
problems = checks.grid_problems(body, items)
|
|
284
|
+
if problems: # a bug in the flattening, not the user's doing
|
|
285
|
+
raise _invalid("The layout can't be put on a grid.", [p.for_model() for p in problems])
|
|
286
|
+
if kind in _FLOWING: # the body keeps its id and becomes the grid
|
|
287
|
+
return [{"id": body, "component": "DashboardGrid", "items": items}]
|
|
288
|
+
grid_id = _free_id(components)
|
|
289
|
+
return [
|
|
290
|
+
{"id": grid_id, "component": "DashboardGrid", "items": items},
|
|
291
|
+
{**root, "body": grid_id},
|
|
292
|
+
]
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
# --- storing the revision ---------------------------------------------------------------------
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _layout_express(
|
|
299
|
+
processor: ExpressProcessor, surface_id: str, components: Sequence[Mapping[str, Any]]
|
|
300
|
+
) -> str:
|
|
301
|
+
"""One `update=true` block writing `components` (as `_restore_express` does)."""
|
|
302
|
+
decompiler = ExpressDecompiler([processor.catalog])
|
|
303
|
+
message = {
|
|
304
|
+
"version": VERSION,
|
|
305
|
+
"updateComponents": {"surfaceId": surface_id, "components": copy.deepcopy(components)},
|
|
306
|
+
}
|
|
307
|
+
lines = decompiler.decompile([message], use_keyword_args=True).split("\n")
|
|
308
|
+
return "\n".join([f'surface("{surface_id}", update=true)', *lines[1:]])
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _problem_key(problem: checks.CheckProblem) -> tuple[str, str | None, str]:
|
|
312
|
+
return problem.code, problem.component_id, problem.message
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
# `message.note` codes of the note messages (params: revision); `content` is the English text.
|
|
316
|
+
NOTE_CODES = {GRID_LAYOUT_CHANGE: "layout.changed", ARRANGE_ON_GRID: "layout.arranged"}
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _note(name: str, revision: int) -> str:
|
|
320
|
+
if name == ARRANGE_ON_GRID:
|
|
321
|
+
return f"Arranged the dashboard on a grid as revision {revision}."
|
|
322
|
+
return f"Moved and resized widgets on the grid as revision {revision}."
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
async def apply_layout_action(
|
|
326
|
+
storage: Any,
|
|
327
|
+
processor: ExpressProcessor,
|
|
328
|
+
conversation_id: str,
|
|
329
|
+
action: Mapping[str, Any],
|
|
330
|
+
) -> LayoutResult:
|
|
331
|
+
"""Applies a `gridLayoutChange` or `arrangeOnGrid` action as a new dashboard revision.
|
|
332
|
+
|
|
333
|
+
Raises:
|
|
334
|
+
LayoutActionError: No dashboard (404), the action doesn't apply to the current layout
|
|
335
|
+
(409), or the layout is invalid (422).
|
|
336
|
+
RevisionConflict: The dashboard changed while this was applied.
|
|
337
|
+
"""
|
|
338
|
+
name = action.get("name")
|
|
339
|
+
if name not in LAYOUT_ACTIONS:
|
|
340
|
+
raise ValueError(f"not a layout action: {name!r}")
|
|
341
|
+
record: DashboardRecord | None = await storage.dashboards.get(conversation_id)
|
|
342
|
+
if record is None or not (record.surface or {}).get("components"):
|
|
343
|
+
raise LayoutActionError(404, "not_found", "This conversation has no dashboard yet.")
|
|
344
|
+
components = {
|
|
345
|
+
str(c["id"]): dict(c) for c in record.surface["components"] if isinstance(c, Mapping)
|
|
346
|
+
}
|
|
347
|
+
written = (
|
|
348
|
+
_grid_change(components, action) if name == GRID_LAYOUT_CHANGE else _arrange(components)
|
|
349
|
+
)
|
|
350
|
+
if all(components.get(c["id"]) == c for c in written):
|
|
351
|
+
return LayoutResult(record=record, message=None, payload=None)
|
|
352
|
+
|
|
353
|
+
surface_id = surface_id_of(conversation_id)
|
|
354
|
+
express = _layout_express(processor, surface_id, written)
|
|
355
|
+
registry = QueryRegistry.from_json(list(record.queries.values()))
|
|
356
|
+
|
|
357
|
+
def compile_and_check() -> tuple[Compiled, list[checks.CheckProblem]]:
|
|
358
|
+
state = rebuild_state(processor, surface_id, record.surface, catalog_id=record.catalog_id)
|
|
359
|
+
compiled = compile_express(processor, state, express, surface_id)
|
|
360
|
+
if not compiled.ok:
|
|
361
|
+
return compiled, []
|
|
362
|
+
before = {_problem_key(p) for p in checks.check_surface(record.surface, registry)}
|
|
363
|
+
after = checks.check_surface(compiled.surface, registry, changed=compiled.changed)
|
|
364
|
+
return compiled, [p for p in after if _problem_key(p) not in before]
|
|
365
|
+
|
|
366
|
+
compiled, problems = await asyncio.to_thread(compile_and_check)
|
|
367
|
+
if not compiled.ok:
|
|
368
|
+
raise _invalid(
|
|
369
|
+
"The layout change doesn't compile.", [e.for_model() for e in compiled.errors]
|
|
370
|
+
)
|
|
371
|
+
if problems:
|
|
372
|
+
raise _invalid("The layout change was refused.", [p.for_model() for p in problems])
|
|
373
|
+
|
|
374
|
+
async with storage.transaction() as tx:
|
|
375
|
+
new = await tx.dashboards.put(
|
|
376
|
+
conversation_id,
|
|
377
|
+
catalog_id=record.catalog_id,
|
|
378
|
+
surface=compiled.surface,
|
|
379
|
+
queries=copy.deepcopy(dict(record.queries)),
|
|
380
|
+
express=express,
|
|
381
|
+
source="layout",
|
|
382
|
+
expected_revision=record.revision,
|
|
383
|
+
)
|
|
384
|
+
text = _note(str(name), new.revision)
|
|
385
|
+
message = await tx.messages.add(
|
|
386
|
+
conversation_id=conversation_id,
|
|
387
|
+
role="assistant",
|
|
388
|
+
content=text,
|
|
389
|
+
a2ui=join_express([express]),
|
|
390
|
+
revision=new.revision,
|
|
391
|
+
note={"code": NOTE_CODES[str(name)], "params": {"revision": new.revision}},
|
|
392
|
+
tool_trace=[
|
|
393
|
+
{
|
|
394
|
+
"name": LAYOUT_TOOL,
|
|
395
|
+
"input": {
|
|
396
|
+
"action": name,
|
|
397
|
+
"sourceComponentId": action.get("sourceComponentId"),
|
|
398
|
+
},
|
|
399
|
+
"result": text,
|
|
400
|
+
"is_error": False,
|
|
401
|
+
}
|
|
402
|
+
],
|
|
403
|
+
)
|
|
404
|
+
await tx.dashboards.link_message(conversation_id, message.id, revision=new.revision)
|
|
405
|
+
return LayoutResult(
|
|
406
|
+
record=new,
|
|
407
|
+
message=message,
|
|
408
|
+
payload=canvas_payload(surface_id, new.revision, compiled.messages),
|
|
409
|
+
)
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
"""The `render_dashboard(a2ui)` tool (design §1.10 *Agent tools*, §6.4).
|
|
2
|
+
|
|
3
|
+
Express -> the SDK's parser against the conversation's `RendererState` (on a worker thread) ->
|
|
4
|
+
our check layer -> a new revision of the conversation's `dashboard` row, recorded in
|
|
5
|
+
`dashboard_revision` in the same transaction (so a turn that fails later keeps it) -> a
|
|
6
|
+
`canvas.a2ui` emit with the compiled v1.0 messages. Every refusal goes back to the model as
|
|
7
|
+
one error list (`ToolResult(is_error=True)`), and the state is left exactly as it was, so the
|
|
8
|
+
model's retry is parsed against the same surface.
|
|
9
|
+
|
|
10
|
+
Wiring (the run service): build one `ExpressProcessor` per host, load a `DashboardSession` at
|
|
11
|
+
run start and pass it in `ToolContext.extras[DASHBOARD_SESSION]`, register
|
|
12
|
+
`render_dashboard_tool(...)`, map its `ToolEmit` to the `canvas.a2ui` event, and write the
|
|
13
|
+
assistant message with `session.message_fields()`.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import asyncio
|
|
19
|
+
from collections.abc import Mapping, Sequence
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from agent2dashboard.a2ui import checks
|
|
24
|
+
from agent2dashboard.a2ui.express import ExpressProcessor
|
|
25
|
+
from agent2dashboard.a2ui.state import (
|
|
26
|
+
DASHBOARD_SESSION,
|
|
27
|
+
DashboardSession,
|
|
28
|
+
canvas_payload,
|
|
29
|
+
commit,
|
|
30
|
+
compile_express,
|
|
31
|
+
inner_express,
|
|
32
|
+
referenced_queries,
|
|
33
|
+
)
|
|
34
|
+
from agent2dashboard.agent.tools import RENDER_DASHBOARD, Tool, ToolContext, ToolResult
|
|
35
|
+
from agent2dashboard.errors import AgentDashboardError, RowFilterDenied
|
|
36
|
+
from agent2dashboard.ports import Capability, Principal, ToolDef
|
|
37
|
+
from agent2dashboard.query.errors import QueryError
|
|
38
|
+
from agent2dashboard.query.service import QueryService
|
|
39
|
+
from agent2dashboard.storage.records import RevisionConflict
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"RENDER_DASHBOARD_TOOL",
|
|
43
|
+
"RenderOutcome",
|
|
44
|
+
"render_dashboard",
|
|
45
|
+
"render_dashboard_tool",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
RENDER_DASHBOARD_TOOL = ToolDef(
|
|
49
|
+
name=RENDER_DASHBOARD,
|
|
50
|
+
description=(
|
|
51
|
+
"Create or change this conversation's dashboard. `a2ui` is A2UI Express for the "
|
|
52
|
+
'dashboard catalog: the first time `surface("<surface id>")` and the whole dashboard, '
|
|
53
|
+
'afterwards `surface("<surface id>", update=true)` and only the components that '
|
|
54
|
+
"change. The host prompt gives the surface id and lists what is on screen. Every data "
|
|
55
|
+
'widget\'s data is runQuery("<queryId>", $/filters) on a query registered with '
|
|
56
|
+
"define_query. On errors, nothing changed: fix every listed problem and call again."
|
|
57
|
+
),
|
|
58
|
+
input_schema={
|
|
59
|
+
"type": "object",
|
|
60
|
+
"properties": {"a2ui": {"type": "string", "minLength": 1, "description": "A2UI Express."}},
|
|
61
|
+
"required": ["a2ui"],
|
|
62
|
+
"additionalProperties": False,
|
|
63
|
+
},
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
ERROR_HEADER = (
|
|
67
|
+
"The dashboard was not changed. Fix every problem below and call render_dashboard again:"
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True)
|
|
72
|
+
class RenderOutcome:
|
|
73
|
+
"""What one call did. On success `payload` is the `canvas.a2ui` event data."""
|
|
74
|
+
|
|
75
|
+
errors: tuple[str, ...] = ()
|
|
76
|
+
revision: int | None = None
|
|
77
|
+
payload: Mapping[str, Any] | None = None
|
|
78
|
+
changed: tuple[str, ...] = ()
|
|
79
|
+
removed: tuple[str, ...] = ()
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def ok(self) -> bool:
|
|
83
|
+
return not self.errors
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
async def _pie_slices(
|
|
87
|
+
surface: Mapping[str, Any],
|
|
88
|
+
session: DashboardSession,
|
|
89
|
+
service: QueryService | None,
|
|
90
|
+
principal: Principal,
|
|
91
|
+
) -> tuple[dict[str, int], list[str]]:
|
|
92
|
+
"""Rows each pie's query returns at the dashboard's default filters (check_spec ran every
|
|
93
|
+
widget's query once; only the slice count needs rows here)."""
|
|
94
|
+
if service is None:
|
|
95
|
+
return {}, []
|
|
96
|
+
on_screen = set(checks.reachable({c["id"]: c for c in surface["components"]}))
|
|
97
|
+
pies = {
|
|
98
|
+
query_id
|
|
99
|
+
for cid, query_id in checks.pie_queries(surface["components"]).items()
|
|
100
|
+
if cid in on_screen
|
|
101
|
+
}
|
|
102
|
+
defaults = (surface.get("dataModel") or {}).get("filters") or {}
|
|
103
|
+
counts: dict[str, int] = {}
|
|
104
|
+
problems: list[str] = []
|
|
105
|
+
for query_id in sorted(pies):
|
|
106
|
+
query = session.registry.get(query_id)
|
|
107
|
+
if query is None:
|
|
108
|
+
continue # reported by the checks
|
|
109
|
+
try:
|
|
110
|
+
context = query.context(defaults, service.data.governed)
|
|
111
|
+
outcome = await service.run(
|
|
112
|
+
query.sql,
|
|
113
|
+
principal=principal,
|
|
114
|
+
context=context,
|
|
115
|
+
max_rows=checks.MAX_PIE_SLICES + 1,
|
|
116
|
+
)
|
|
117
|
+
except (QueryError, RowFilterDenied) as exc:
|
|
118
|
+
problems.append(f"[QUERY] {query_id}: {exc}")
|
|
119
|
+
continue
|
|
120
|
+
counts[query_id] = len(outcome.result.rows) + (1 if outcome.result.truncated else 0)
|
|
121
|
+
return counts, problems
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
async def render_dashboard(
|
|
125
|
+
session: DashboardSession,
|
|
126
|
+
express: Any,
|
|
127
|
+
*,
|
|
128
|
+
storage: Any,
|
|
129
|
+
principal: Principal,
|
|
130
|
+
query_service: QueryService | None = None,
|
|
131
|
+
) -> RenderOutcome:
|
|
132
|
+
"""Compiles, checks and stores one Express block as the dashboard's next revision."""
|
|
133
|
+
if not isinstance(express, str) or not express.strip():
|
|
134
|
+
return RenderOutcome(errors=("[EMPTY] The a2ui argument must be A2UI Express text.",))
|
|
135
|
+
async with session.lock:
|
|
136
|
+
compiled = await asyncio.to_thread(
|
|
137
|
+
compile_express, session.processor, session.state, express, session.surface_id
|
|
138
|
+
)
|
|
139
|
+
if not compiled.ok:
|
|
140
|
+
return RenderOutcome(errors=tuple(e.for_model() for e in compiled.errors))
|
|
141
|
+
|
|
142
|
+
slices, problems = await _pie_slices(compiled.surface, session, query_service, principal)
|
|
143
|
+
problems += [
|
|
144
|
+
p.for_model()
|
|
145
|
+
for p in checks.check_surface(
|
|
146
|
+
compiled.surface,
|
|
147
|
+
session.registry,
|
|
148
|
+
changed=compiled.changed,
|
|
149
|
+
pie_slices=slices,
|
|
150
|
+
)
|
|
151
|
+
]
|
|
152
|
+
if problems:
|
|
153
|
+
return RenderOutcome(errors=tuple(problems))
|
|
154
|
+
|
|
155
|
+
await asyncio.to_thread(commit, session.state, compiled.messages)
|
|
156
|
+
ids = referenced_queries(compiled.surface)
|
|
157
|
+
try:
|
|
158
|
+
async with storage.transaction() as tx:
|
|
159
|
+
record = await tx.dashboards.put(
|
|
160
|
+
session.conversation_id,
|
|
161
|
+
catalog_id=session.catalog_id,
|
|
162
|
+
surface=compiled.surface,
|
|
163
|
+
queries={
|
|
164
|
+
q.query_id: q.model_dump(mode="json")
|
|
165
|
+
for q in session.registry
|
|
166
|
+
if q.query_id in ids
|
|
167
|
+
},
|
|
168
|
+
express=inner_express(express),
|
|
169
|
+
source="agent",
|
|
170
|
+
run_id=session.run_id,
|
|
171
|
+
expected_revision=session.revision,
|
|
172
|
+
)
|
|
173
|
+
except RevisionConflict:
|
|
174
|
+
await asyncio.to_thread(session.reset_state)
|
|
175
|
+
return RenderOutcome(
|
|
176
|
+
errors=(
|
|
177
|
+
"[CONFLICT] The dashboard changed outside this reply; nothing was stored. "
|
|
178
|
+
"Tell the user to send the request again.",
|
|
179
|
+
)
|
|
180
|
+
)
|
|
181
|
+
except BaseException:
|
|
182
|
+
await asyncio.to_thread(session.reset_state)
|
|
183
|
+
raise
|
|
184
|
+
before = {c["id"] for c in (session.surface or {}).get("components") or []}
|
|
185
|
+
after = {c["id"] for c in compiled.surface["components"]}
|
|
186
|
+
session.accept(express, record)
|
|
187
|
+
return RenderOutcome(
|
|
188
|
+
revision=record.revision,
|
|
189
|
+
payload=canvas_payload(session.surface_id, record.revision, compiled.messages),
|
|
190
|
+
changed=compiled.changed,
|
|
191
|
+
removed=tuple(sorted(before - after)),
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _success_text(outcome: RenderOutcome, session: DashboardSession) -> str:
|
|
196
|
+
lines = [f"Rendered revision {outcome.revision} of {session.surface_id}."]
|
|
197
|
+
if outcome.changed:
|
|
198
|
+
lines.append(f"Written: {', '.join(outcome.changed)}.")
|
|
199
|
+
if outcome.removed:
|
|
200
|
+
lines.append(f"Removed: {', '.join(outcome.removed)}.")
|
|
201
|
+
lines.append("")
|
|
202
|
+
lines.append(session.on_screen())
|
|
203
|
+
return "\n".join(lines)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def error_text(errors: Sequence[str]) -> str:
|
|
207
|
+
return "\n".join([ERROR_HEADER, *(f"- {e}" for e in errors)])
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def render_dashboard_tool(
|
|
211
|
+
*,
|
|
212
|
+
storage: Any,
|
|
213
|
+
processor: ExpressProcessor,
|
|
214
|
+
query_service: QueryService | None = None,
|
|
215
|
+
) -> Tool:
|
|
216
|
+
"""The tool for a `ToolRegistry`. It uses the run's `DashboardSession` from
|
|
217
|
+
`context.extras[DASHBOARD_SESSION]`, or loads one from storage when the run gave none
|
|
218
|
+
(then nothing is reported back for the message; the dashboard row is still updated)."""
|
|
219
|
+
|
|
220
|
+
async def handler(tool_input: Mapping[str, Any], context: ToolContext) -> ToolResult:
|
|
221
|
+
session = context.extras.get(DASHBOARD_SESSION)
|
|
222
|
+
if not isinstance(session, DashboardSession):
|
|
223
|
+
session = await DashboardSession.load(
|
|
224
|
+
storage, context.conversation_id, processor, run_id=context.run_id
|
|
225
|
+
)
|
|
226
|
+
try:
|
|
227
|
+
outcome = await render_dashboard(
|
|
228
|
+
session,
|
|
229
|
+
tool_input.get("a2ui"),
|
|
230
|
+
storage=storage,
|
|
231
|
+
principal=context.principal,
|
|
232
|
+
query_service=query_service,
|
|
233
|
+
)
|
|
234
|
+
except AgentDashboardError as exc:
|
|
235
|
+
return ToolResult(f"render_dashboard failed: {exc}", is_error=True)
|
|
236
|
+
if not outcome.ok:
|
|
237
|
+
return ToolResult(
|
|
238
|
+
error_text(outcome.errors),
|
|
239
|
+
is_error=True,
|
|
240
|
+
trace_metadata={"errors": len(outcome.errors)},
|
|
241
|
+
)
|
|
242
|
+
return ToolResult(
|
|
243
|
+
_success_text(outcome, session),
|
|
244
|
+
emit=outcome.payload,
|
|
245
|
+
trace_metadata={
|
|
246
|
+
"revision": outcome.revision,
|
|
247
|
+
"surface_id": session.surface_id,
|
|
248
|
+
"changed": list(outcome.changed),
|
|
249
|
+
},
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
return Tool(RENDER_DASHBOARD_TOOL, handler, Capability.QUERY)
|