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,349 @@
1
+ """A2UI Express for the dashboard catalog: prompt snippet, parse and compile (design §1.9, §1.10).
2
+
3
+ A thin wrapper over `a2ui-agent-sdk` 0.11.0:
4
+
5
+ - `load_catalog_json()` reads the shared catalog document
6
+ (`catalogs/dashboard/v1/catalog.json`), the single source for the prompt, server validation,
7
+ our check layer and the browser (§3.10).
8
+ - `DashboardCatalogConfig` implements the `CatalogConfig` port; `build_agent_catalog()` turns one
9
+ into the pruned agent copy the model sees.
10
+ - `ExpressProcessor` builds the Express prompt snippet for that copy and compiles the model's
11
+ Express into v1.0 wire messages, checked against a `RendererState`. Failures come back as
12
+ structured `ExpressError`s, never as exceptions, so they can go straight back to the model.
13
+
14
+ On top of the SDK's own validation, the processor refuses what the SDK allows but we never want
15
+ from the model: writing data outside `/filters` and `/ui` (rows come from `runQuery`, never from
16
+ the model), touching another surface, and deleting the surface.
17
+
18
+ Threading: the SDK parser is synchronous and `RendererState` is not thread-safe. One
19
+ `ExpressProcessor` may be shared (it holds no per-conversation state), but each `RendererState`
20
+ must be used by one call at a time: keep one per conversation behind the run lock, and parse with
21
+ `await processor.aparse(...)`, which runs `parse` through `asyncio.to_thread`.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import asyncio
27
+ import copy
28
+ import json
29
+ from collections.abc import Iterable, Mapping, Sequence
30
+ from dataclasses import dataclass, field
31
+ from functools import cache
32
+ from importlib import resources
33
+ from typing import Any
34
+
35
+ from a2ui.core import A2uiError, Catalog, CatalogApi
36
+ from a2ui.inference_formats.express import ExpressFormat, ExpressParser
37
+ from a2ui.parser import A2uiCompilationParseError, A2uiPart, to_message_dicts
38
+ from a2ui.utils import RendererState
39
+
40
+ from agent2dashboard.ports import CatalogConfig
41
+
42
+ __all__ = [
43
+ "AGENT_FUNCTIONS",
44
+ "ALLOWED_MESSAGES",
45
+ "CATALOG_ID",
46
+ "MODEL_WRITABLE_DATA_ROOTS",
47
+ "DashboardCatalogConfig",
48
+ "ExpressError",
49
+ "ExpressProcessor",
50
+ "ExpressResult",
51
+ "build_agent_catalog",
52
+ "estimate_tokens",
53
+ "load_catalog_json",
54
+ ]
55
+
56
+ CATALOG_ID = "https://techx.dev/a2ui/dashboard/v1"
57
+ _CATALOG_RESOURCE = ("catalogs", "dashboard", "v1", "catalog.json")
58
+
59
+ # Functions the model may call. They have no renderer implementation, so the renderer routes
60
+ # them to our server (`callAgentFunction`). The format functions are renderer-side and useless
61
+ # to a model that never sees data, so the agent copy leaves them out.
62
+ AGENT_FUNCTIONS: tuple[str, ...] = ("runQuery", "filterOptions")
63
+
64
+ # Message types the model may produce. `deleteSurface` and `callRendererFunction` are refused.
65
+ ALLOWED_MESSAGES: tuple[str, ...] = ("createSurface", "updateComponents", "updateDataModel")
66
+
67
+ # The only data-model roots the model may write: filter defaults and view state (§7).
68
+ MODEL_WRITABLE_DATA_ROOTS: tuple[str, ...] = ("filters", "ui")
69
+
70
+ # Components that only make sense together in a pruned copy.
71
+ _ROOT_COMPONENT = "Dashboard"
72
+ _FILTER_BAR = "FilterBar"
73
+ _PICKERS = frozenset({"PeriodPicker", "FilterSelect"})
74
+
75
+
76
+ # --- catalog -------------------------------------------------------------------------------
77
+
78
+
79
+ @cache
80
+ def _catalog_text() -> str:
81
+ path = resources.files("agent2dashboard.a2ui").joinpath(*_CATALOG_RESOURCE)
82
+ return path.read_text(encoding="utf-8")
83
+
84
+
85
+ def load_catalog_json() -> dict[str, Any]:
86
+ """The dashboard catalog v1 document, as a fresh dict the caller may change."""
87
+ return copy.deepcopy(json.loads(_catalog_text()))
88
+
89
+
90
+ @dataclass(frozen=True)
91
+ class DashboardCatalogConfig:
92
+ """The default `CatalogConfig` (§3.10): the shared document, optionally pruned for the model.
93
+
94
+ `agent_components` is the set of components offered to the model (None offers all), and
95
+ `extra_instructions` is a host addendum appended to the catalog's `instructions`.
96
+ """
97
+
98
+ catalog_json: Mapping[str, Any] = field(default_factory=load_catalog_json)
99
+ agent_components: frozenset[str] | None = None
100
+ extra_instructions: str | None = None
101
+
102
+
103
+ def _check_pruned_set(names: frozenset[str], available: Iterable[str]) -> None:
104
+ unknown = sorted(names - set(available))
105
+ if unknown:
106
+ raise ValueError(f"agent_components names unknown components: {', '.join(unknown)}")
107
+ if _ROOT_COMPONENT not in names:
108
+ raise ValueError(f"agent_components must include {_ROOT_COMPONENT}, the root component")
109
+ if names & _PICKERS and _FILTER_BAR not in names:
110
+ raise ValueError(f"PeriodPicker and FilterSelect need {_FILTER_BAR} in agent_components")
111
+ if _FILTER_BAR in names and not names & _PICKERS:
112
+ raise ValueError(f"{_FILTER_BAR} needs PeriodPicker or FilterSelect in agent_components")
113
+
114
+
115
+ def build_agent_catalog(config: CatalogConfig | None = None) -> CatalogApi:
116
+ """The agent copy of the catalog: pruned components, agent functions only, host addendum.
117
+
118
+ The copy keeps the catalog id, so the messages it validates name the same catalog the
119
+ browser renders with.
120
+
121
+ Raises:
122
+ ValueError: If `agent_components` names unknown components or an unusable subset.
123
+ """
124
+ config = config if config is not None else DashboardCatalogConfig()
125
+ full = Catalog.from_json(config.catalog_json)
126
+ if full.catalog_id != CATALOG_ID:
127
+ raise ValueError(f"expected catalog {CATALOG_ID}, got {full.catalog_id}")
128
+ components: list[str] = list(full.components)
129
+ if config.agent_components is not None:
130
+ _check_pruned_set(config.agent_components, components)
131
+ components = [name for name in components if name in config.agent_components]
132
+ instructions = full.instructions or ""
133
+ if config.extra_instructions:
134
+ instructions = f"{instructions}\n\n## Host instructions\n\n{config.extra_instructions}"
135
+ return full.derive(
136
+ catalog_id=full.catalog_id,
137
+ components=components,
138
+ functions=list(AGENT_FUNCTIONS),
139
+ instructions=instructions,
140
+ )
141
+
142
+
143
+ # --- results -------------------------------------------------------------------------------
144
+
145
+
146
+ @dataclass(frozen=True)
147
+ class ExpressError:
148
+ """One reason an Express block was refused, worded for the model to fix it.
149
+
150
+ `code` is the SDK's error code (`VALIDATION_FAILED`, `INTEGRITY_ERROR`, `UNALLOWED_PARENT`,
151
+ ...), `PARSE_ERROR` for Express the grammar can't read, or one of ours:
152
+ `FORBIDDEN_DATA_WRITE`, `FORBIDDEN_MESSAGE`, `WRONG_SURFACE`, `EMPTY`.
153
+ """
154
+
155
+ code: str
156
+ message: str
157
+ path: str | None = None
158
+ line: int | None = None
159
+ column: int | None = None
160
+ help: str | None = None
161
+
162
+ def to_dict(self) -> dict[str, Any]:
163
+ return {k: v for k, v in self.__dict__.items() if v is not None}
164
+
165
+ def for_model(self) -> str:
166
+ """One line for the tool result the model reads."""
167
+ where = f" (line {self.line}, col {self.column})" if self.line is not None else ""
168
+ at = f" at {self.path}" if self.path else ""
169
+ hint = f" Fix: {self.help}" if self.help else ""
170
+ return f"[{self.code}]{at}{where} {self.message}{hint}"
171
+
172
+
173
+ @dataclass(frozen=True)
174
+ class ExpressResult:
175
+ """What one `render_dashboard` call compiled to.
176
+
177
+ On success `messages` holds the v1.0 wire messages (dicts, ready to send) and the state has
178
+ them applied. On failure `errors` is non-empty, `messages` is empty, and the state is
179
+ exactly as it was before the call.
180
+ """
181
+
182
+ messages: tuple[dict[str, Any], ...] = ()
183
+ errors: tuple[ExpressError, ...] = ()
184
+
185
+ @property
186
+ def ok(self) -> bool:
187
+ return not self.errors
188
+
189
+ def errors_for_model(self) -> str:
190
+ return "\n".join(e.for_model() for e in self.errors)
191
+
192
+
193
+ class _Refused(Exception):
194
+ """Raised inside the state transaction to roll back a block our own rules refuse."""
195
+
196
+ def __init__(self, errors: list[ExpressError]):
197
+ super().__init__(errors)
198
+ self.errors = errors
199
+
200
+
201
+ # --- processor -----------------------------------------------------------------------------
202
+
203
+
204
+ def estimate_tokens(text: str) -> int:
205
+ """Approximate token count: characters / 3.5, rounded up.
206
+
207
+ No tokenizer ships with the SDK and Claude's isn't public, so the prompt budget (§1.10) is
208
+ tracked with this conservative heuristic (Claude averages roughly 3.5-4 characters per
209
+ token on English prose and code).
210
+ """
211
+ return -(-len(text) * 2 // 7)
212
+
213
+
214
+ class ExpressProcessor:
215
+ """Prompt snippet and Express compilation for one host's agent copy of the catalog."""
216
+
217
+ def __init__(self, config: CatalogConfig | None = None):
218
+ self._catalog = build_agent_catalog(config)
219
+ self._format = ExpressFormat([self._catalog], allowed_messages=list(ALLOWED_MESSAGES))
220
+ # Built eagerly: the SDK caches lazily, which is not safe to race from worker threads.
221
+ self._snippet = self._format.prompt_generator.generate()
222
+ _ = self._catalog.validation_schema
223
+
224
+ @property
225
+ def catalog(self) -> CatalogApi:
226
+ """The agent copy the model is shown and its output is validated against."""
227
+ return self._catalog
228
+
229
+ @property
230
+ def prompt_snippet(self) -> str:
231
+ """The fixed Express contract, signatures and catalog instructions for the system prompt."""
232
+ return self._snippet
233
+
234
+ def create_state(self) -> RendererState:
235
+ """A fresh mirror of the renderer, for one conversation."""
236
+ return RendererState([self._catalog])
237
+
238
+ def parse(self, express: str, *, surface_id: str, state: RendererState) -> ExpressResult:
239
+ """Compiles one Express program against `state`, all or nothing.
240
+
241
+ `express` is the `render_dashboard` argument, with or without `<a2ui>` tags. Statements
242
+ without a `surface(...)` line target `surface_id`. Synchronous and CPU-bound: call it
243
+ through `aparse` from async code.
244
+ """
245
+ if not express.strip():
246
+ return _failed(ExpressError("EMPTY", "The a2ui argument is empty."))
247
+ parser = ExpressParser([self._catalog], surface_id=surface_id)
248
+ wrapped = parser.has_format_content(express)
249
+ try:
250
+ with state.transaction():
251
+ parts = parser.parse_response(express, wrapped=wrapped, state=state)
252
+ messages = [
253
+ message
254
+ for part in parts
255
+ if isinstance(part, A2uiPart)
256
+ for message in to_message_dicts(part.a2ui)
257
+ ]
258
+ errors = _guard(messages, surface_id)
259
+ if not messages:
260
+ errors.append(ExpressError("EMPTY", "No A2UI Express statements found."))
261
+ if errors:
262
+ raise _Refused(errors)
263
+ except _Refused as refused:
264
+ return ExpressResult(errors=tuple(refused.errors))
265
+ except A2uiError as e:
266
+ return _failed(_from_sdk_error(e))
267
+ return ExpressResult(messages=tuple(messages))
268
+
269
+ async def aparse(self, express: str, *, surface_id: str, state: RendererState) -> ExpressResult:
270
+ """`parse` on a worker thread. The caller must not share `state` with another call."""
271
+ return await asyncio.to_thread(self.parse, express, surface_id=surface_id, state=state)
272
+
273
+
274
+ def _failed(error: ExpressError) -> ExpressResult:
275
+ return ExpressResult(errors=(error,))
276
+
277
+
278
+ def _from_sdk_error(e: A2uiError) -> ExpressError:
279
+ code = e.code or ("PARSE_ERROR" if isinstance(e, A2uiCompilationParseError) else "A2UI_ERROR")
280
+ message = getattr(e, "message", None) or str(e)
281
+ detail_paths = [d.path for d in e.details if d.path]
282
+ return ExpressError(
283
+ code=code,
284
+ message=message,
285
+ path=e.path or (detail_paths[0] if detail_paths else None),
286
+ line=getattr(e, "line", None),
287
+ column=getattr(e, "column", None),
288
+ help=_useful_help(getattr(e, "help_message", None)),
289
+ )
290
+
291
+
292
+ def _useful_help(help_message: str | None) -> str | None:
293
+ # The SDK's fallback help says nothing the message doesn't.
294
+ if not help_message or help_message.startswith("Please correct the syntax error"):
295
+ return None
296
+ return help_message
297
+
298
+
299
+ # --- our rules on top of the SDK -------------------------------------------------------------
300
+
301
+
302
+ def _guard(messages: Sequence[Mapping[str, Any]], surface_id: str) -> list[ExpressError]:
303
+ errors: list[ExpressError] = []
304
+ for message in messages:
305
+ op = next((k for k in message if k != "version"), "")
306
+ body = message.get(op)
307
+ if op not in ALLOWED_MESSAGES or not isinstance(body, Mapping):
308
+ errors.append(
309
+ ExpressError(
310
+ "FORBIDDEN_MESSAGE",
311
+ f"`{op}` is not allowed. Change the dashboard with "
312
+ f'surface("{surface_id}", update=true) instead.',
313
+ )
314
+ )
315
+ continue
316
+ target = body.get("surfaceId")
317
+ if target != surface_id:
318
+ errors.append(
319
+ ExpressError(
320
+ "WRONG_SURFACE",
321
+ f'This conversation\'s dashboard is surface "{surface_id}", not "{target}".',
322
+ )
323
+ )
324
+ if op == "createSurface":
325
+ errors.extend(_check_data_write("/", body.get("dataModel")))
326
+ elif op == "updateDataModel":
327
+ errors.extend(_check_data_write(str(body.get("path", "/")), body.get("value")))
328
+ return errors
329
+
330
+
331
+ def _check_data_write(path: str, value: Any) -> list[ExpressError]:
332
+ """Refuses model-written data outside `/filters` and `/ui` (§7: the model never writes data)."""
333
+ segments = [s for s in path.split("/") if s]
334
+ if segments:
335
+ roots = [segments[0]]
336
+ elif isinstance(value, Mapping):
337
+ roots = list(value) # a write at the root, or a createSurface dataModel
338
+ else:
339
+ roots = [] if value is None else [""]
340
+ return [
341
+ ExpressError(
342
+ "FORBIDDEN_DATA_WRITE",
343
+ f"Only filter defaults ($/filters/...) and view state ($/ui/...) may be written, "
344
+ f'not $/{root}. Rows come from runQuery("<queryId>", $/filters); never write them.',
345
+ path=path if segments else f"/{root}",
346
+ )
347
+ for root in roots
348
+ if root not in MODEL_WRITABLE_DATA_ROOTS
349
+ ]