Coverage for app / services / dashboards / widgets.py: 95%
761 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""Widget type registry.
3Every dashboard widget type is one :class:`WidgetRenderer` subclass registered
4with :func:`register_widget`. The renderer owns three things: the config shape
5the type accepts, the defaults the UI should seed a new tile with, and — for
6dynamic types — how the cached result is produced.
8Adding a type therefore means adding one class here. The router serves the
9registry as a catalogue (``GET /app/dashboards/widget-types``), so a new
10renderer shows up in the frontend's widget picker without a frontend change,
11and ``validate_widget`` rejects malformed config for it automatically.
13Two families exist:
15*Static* types (``is_dynamic = False``) are drawn by the frontend from
16existing platform APIs or from their own stored config. The backend persists
17placement and config and nothing else.
19*Dynamic* types (``is_dynamic = True``) own a generated result. Their
20:meth:`WidgetRenderer.generate` invokes a model or agent through the shared
21evaluation execution targets and returns a JSON-serialisable payload that is
22cached on the widget row.
23"""
25from __future__ import annotations
27import logging
28from abc import ABC
29from dataclasses import dataclass
30from typing import Any, Iterable, Optional, Type
31from uuid import UUID, uuid4
33from pydantic import Field, OnErrorOmit, field_validator
34from sqlalchemy.orm import Session
36from app.db.postgres.enums import DashboardEnum, MessageEnum
37from app.services import appearance
38from app.services import mcp as mcp_service
39from app.util import vocab
40from app.util.model_output import ModelOutput
41from app.util.time import aware_utcnow, utc_isoformat
43from .feeds import FeedError
45logger = logging.getLogger(__name__)
47WidgetType = DashboardEnum.WidgetType
50class WidgetConfigError(ValueError):
51 """Raised when a widget's config does not satisfy its type's contract."""
54class WidgetGenerationError(RuntimeError):
55 """Raised when a dynamic widget's result could not be produced."""
58@dataclass(frozen=True)
59class ResourceRef:
60 """A resource a tile's config names, for the router to access-check.
62 ``validate_config`` has no session, so it can only shape-check an id. The
63 router resolves every ref a renderer declares against the user saving the
64 tile — a tile naming somebody else's agent or source is refused there,
65 once, for every widget type, rather than by a branch per type.
66 """
68 #: ``agent`` or ``knowledge``.
69 kind: str
70 id: str
71 #: For ``knowledge``: the source type the tile can draw, if it needs one.
72 source_type: Optional[str] = None
75# ---------------------------------------------------------------------------
76# Config coercion helpers
77#
78# Widget config arrives as free-form JSON from the client. These keep the
79# renderers declarative instead of each repeating the same isinstance dance.
80# ---------------------------------------------------------------------------
83def _as_str(
84 config: dict, key: str, *, required: bool = False, default: str = ""
85) -> str:
86 value = config.get(key, default)
87 if value is None:
88 value = default
89 if not isinstance(value, str):
90 raise WidgetConfigError(f"'{key}' must be a string.")
91 value = value.strip()
92 if required and not value:
93 raise WidgetConfigError(f"'{key}' is required.")
94 return value
97def _as_bool(config: dict, key: str, default: bool = False) -> bool:
98 value = config.get(key, default)
99 if value is None:
100 return default
101 if not isinstance(value, bool):
102 raise WidgetConfigError(f"'{key}' must be true or false.")
103 return value
106def _as_list(config: dict, key: str, *, required: bool = False) -> list:
107 value = config.get(key) or []
108 if not isinstance(value, list):
109 raise WidgetConfigError(f"'{key}' must be a list.")
110 if required and not value:
111 raise WidgetConfigError(f"'{key}' must contain at least one entry.")
112 return value
115def _one_of(config: dict, key: str, allowed: Iterable[str], default: str) -> str:
116 value = str(config.get(key) or default)
117 allowed = set(allowed)
118 if value not in allowed:
119 raise WidgetConfigError(
120 f"'{key}' must be one of: {', '.join(sorted(allowed))}."
121 )
122 return value
125def _int_between(config: dict, key: str, bounds: tuple[int, int], default: int) -> int:
126 """An integer config value within ``bounds``, or :class:`WidgetConfigError`."""
127 low, high = bounds
128 value = config.get(key, default)
129 if (
130 not isinstance(value, int)
131 or isinstance(value, bool)
132 or not low <= value <= high
133 ):
134 raise WidgetConfigError(f"'{key}' must be an integer between {low} and {high}.")
135 return value
138# A widget's ``config_schema`` is what the dashboard generator's model is shown,
139# so the values and bounds in it are rendered from the same sets and limits
140# ``validate_config`` enforces — never restated by hand.
143def _hint_one_of(values: Iterable[str], note: str = "") -> str:
144 hint = f"string — one of: {vocab.listing(values, sep=', ')}"
145 return f"{hint} — {note}" if note else hint
148def _hint_int(bounds: tuple[int, int], note: str = "") -> str:
149 hint = f"integer {bounds[0]}-{bounds[1]}"
150 return f"{hint} — {note}" if note else hint
153# ---------------------------------------------------------------------------
154# Registry
155# ---------------------------------------------------------------------------
158class WidgetRenderer(ABC):
159 """The contract for one dashboard widget type."""
161 #: Discriminator persisted on the widget row.
162 type: WidgetType
163 #: Human-facing name shown in the widget picker.
164 label: str
165 #: One line explaining what the tile shows.
166 description: str
167 #: Picker grouping — "content", "platform", "network", "feeds" or
168 #: "intelligence".
169 category: str = "content"
170 #: Where the content comes from. Boards mix exact data with model
171 #: inference, so every tile declares which it is and the UI labels it.
172 data_kind: DashboardEnum.DataKind = DashboardEnum.DataKind.stored
173 #: Whether the backend generates and caches this type's result. True for
174 #: both feed-backed and model-generated types — they share the cache and
175 #: refresh machinery; ``data_kind`` is what separates fact from inference.
176 is_dynamic: bool = False
177 #: Grid units a freshly added tile occupies.
178 default_size: dict[str, int] = {"w": 4, "h": 4}
179 #: Seed config for a freshly added tile.
180 default_config: dict[str, Any] = {}
181 #: Field-by-field description of this type's config, in the renderer that
182 #: validates it. Fed verbatim to the dashboard generator's prompt, so a
183 #: new widget type becomes generatable without touching the prompt.
184 config_schema: dict[str, str] = {}
185 #: Seed refresh cadence, for dynamic types only.
186 default_refresh_interval_seconds: Optional[int] = None
187 #: Config keys holding resource ids the user picks. A model proposing a
188 #: board never supplies these: the generator strips them, and the tile
189 #: falls back to its documented default instead of an invented id.
190 reference_fields: tuple[str, ...] = ()
191 #: Whether the tile keeps one user's content on its row — a message they
192 #: pinned or saved. Such a tile can never go on a built-in board, which is
193 #: one row shown to every user: everything else either draws the viewer's
194 #: own data when rendered or caches what belongs to nobody.
195 stores_user_content: bool = False
196 #: The shortest refresh cadence the board generator may give the type —
197 #: a vendor's quota or a model's cost sets it, not only the scheduler.
198 min_refresh_interval_seconds: int = 60
200 @property
201 def generatable(self) -> bool:
202 """Whether the board generator may propose the type. Never one that
203 keeps a user's content: what a model wrote there would read as
204 something the user saved (``stored``)."""
205 return not self.stores_user_content
207 def available(self) -> bool:
208 """Whether this deployment can draw the type at all — a tile it
209 cannot refresh is not worth proposing."""
210 return True
212 def without_model_ids(self, config: dict) -> tuple[dict, bool]:
213 """``config`` without the resource ids a model put in it, and whether
214 it had any. The model is never shown an id, so any it wrote is
215 invented: the tile keeps its documented default instead."""
216 stripped = dict(config)
217 invented = [key for key in self.reference_fields if stripped.pop(key, None)]
218 return stripped, bool(invented)
220 def document(self, widget, index: int = 0) -> dict | None:
221 """The ``index``-th downloadable document in the tile's latest result
222 (``app.services.documents``), or None — only a type whose result can
223 hold one has any."""
224 return None
226 def validate_config(self, config: dict) -> dict:
227 """Return the normalised config, or raise :class:`WidgetConfigError`."""
228 return dict(config or {})
230 def config_hints(self) -> dict[str, str]:
231 """The config hints shown in the catalogue — ``config_schema``, unless
232 a type renders them from a registry read at call time."""
233 return dict(self.config_schema)
235 def references(self, config: dict) -> list[ResourceRef]:
236 """The resources a validated config names. By default, the agent a
237 generated tile runs on, if it runs on one."""
238 target = config.get("target") or {}
239 agent_id = target.get("agent_id") if isinstance(target, dict) else None
240 return [ResourceRef("agent", str(agent_id))] if agent_id else []
242 def generate(self, db: Session, widget) -> dict:
243 """Produce this widget's cached payload. Dynamic types only."""
244 raise WidgetGenerationError(
245 f"Widget type '{self.type}' does not generate a result."
246 )
248 def spec(self) -> dict:
249 """The catalogue entry describing this type to the UI."""
250 return {
251 "type": self.type,
252 "label": self.label,
253 "description": self.description,
254 "category": self.category,
255 "data_kind": self.data_kind,
256 "is_dynamic": self.is_dynamic,
257 "default_size": dict(self.default_size),
258 "default_config": dict(self.default_config),
259 "config_schema": self.config_hints(),
260 "default_refresh_interval_seconds": (self.default_refresh_interval_seconds),
261 }
264_REGISTRY: dict[WidgetType, WidgetRenderer] = {}
267def register_widget(cls: Type[WidgetRenderer]) -> Type[WidgetRenderer]:
268 """Class decorator adding a renderer to the registry."""
269 instance = cls()
270 if instance.type in _REGISTRY:
271 raise RuntimeError(f"Widget type '{instance.type}' is already registered.")
272 _REGISTRY[instance.type] = instance
273 return cls
276def get_renderer(widget_type: WidgetType | str) -> WidgetRenderer:
277 try:
278 key = WidgetType(widget_type)
279 except ValueError as exc:
280 raise WidgetConfigError(f"Unknown widget type '{widget_type}'.") from exc
281 renderer = _REGISTRY.get(key)
282 if renderer is None:
283 raise WidgetConfigError(f"Widget type '{widget_type}' has no renderer.")
284 return renderer
287def renderers() -> list[WidgetRenderer]:
288 """Every registered renderer, in the picker's order."""
289 return [_REGISTRY[t] for t in WidgetType if t in _REGISTRY]
292def catalogue() -> list[dict]:
293 """Every registered type, ordered for display in the picker."""
294 return [renderer.spec() for renderer in renderers()]
297def dynamic_types() -> tuple[WidgetType, ...]:
298 """The types whose result the backend generates and caches — the only
299 tiles the scheduler ever has to look at."""
300 return tuple(renderer.type for renderer in renderers() if renderer.is_dynamic)
303def validate_widget(widget_type: WidgetType | str, config: dict) -> dict:
304 """Validate ``config`` against ``widget_type``'s renderer."""
305 return get_renderer(widget_type).validate_config(config or {})
308def _optional_uuid(config: dict, key: str) -> str:
309 """An id the tile may name, or "" for the tile's documented default."""
310 value = _as_str(config, key)
311 if not value:
312 return ""
313 try:
314 return str(UUID(value))
315 except ValueError as exc:
316 raise WidgetConfigError(f"'{key}' must be a resource id.") from exc
319def _uuid_list(config: dict, key: str, *, limit: int) -> list[str]:
320 ids: list[str] = []
321 for entry in _as_list(config, key):
322 if not isinstance(entry, str):
323 raise WidgetConfigError(f"Each of '{key}' must be a resource id.")
324 try:
325 value = str(UUID(entry.strip()))
326 except ValueError as exc:
327 raise WidgetConfigError(f"Each of '{key}' must be a resource id.") from exc
328 if value not in ids:
329 ids.append(value)
330 if len(ids) > limit:
331 raise WidgetConfigError(f"'{key}' may name at most {limit} resources.")
332 return ids
335# ---------------------------------------------------------------------------
336# Static widgets
337# ---------------------------------------------------------------------------
340@register_widget
341class NoteWidget(WidgetRenderer):
342 """A free-text markdown note."""
344 type = WidgetType.note
345 label = "Note"
346 description = "A markdown note — context, a checklist, or a reminder."
347 category = "content"
348 data_kind = DashboardEnum.DataKind.stored
349 default_size = {"w": 4, "h": 4}
350 default_config = {"markdown": "", "accent": appearance.DEFAULT_ACCENT}
351 config_schema = {
352 "markdown": ("string — the note body, markdown supported"),
353 "accent": _hint_one_of(appearance.ACCENTS),
354 }
356 def validate_config(self, config: dict) -> dict:
357 return {
358 "markdown": _as_str(config, "markdown"),
359 "accent": _one_of(
360 config, "accent", appearance.ACCENTS, appearance.DEFAULT_ACCENT
361 ),
362 }
365@register_widget
366class ShortcutsWidget(WidgetRenderer):
367 """A list of links into the platform."""
369 type = WidgetType.shortcuts
370 label = "Shortcuts"
371 description = "Quick links to the pages and resources you use most."
372 category = "content"
373 data_kind = DashboardEnum.DataKind.stored
374 default_size = {"w": 3, "h": 4}
375 default_config = {"links": []}
376 config_schema = {
377 "links": (
378 "array of {label: string, href: string (an in-app path like /user/inference?section=agents)}"
379 ),
380 }
382 def validate_config(self, config: dict) -> dict:
383 links = []
384 for entry in _as_list(config, "links"):
385 if not isinstance(entry, dict):
386 raise WidgetConfigError("Each shortcut must be an object.")
387 label = _as_str(entry, "label", required=True)
388 href = _as_str(entry, "href", required=True)
389 links.append(
390 {
391 "label": label,
392 "href": href,
393 "icon": _as_str(entry, "icon", default="ArrowUpRight"),
394 }
395 )
396 return {"links": links}
399@register_widget
400class StatWidget(WidgetRenderer):
401 """A single platform metric, rendered as a number tile."""
403 type = WidgetType.stat
404 label = "Stat"
405 description = "One usage or cost metric as a headline number."
406 category = "platform"
407 data_kind = DashboardEnum.DataKind.platform
408 default_size = {"w": 2, "h": 2}
409 default_config = {"metric": "total_tokens", "period": "this_month"}
411 #: Keys of ``UsagePeriod``/``TracePeriod`` the frontend can render.
412 METRICS = (
413 "total_tokens",
414 "input_tokens",
415 "output_tokens",
416 "invocation_count",
417 "error_count",
418 "avg_latency_ms",
419 "estimated_cost_usd",
420 "llm_invocation_count",
421 "tool_invocation_count",
422 )
423 PERIODS = ("this_month", "all_time")
425 config_schema = {
426 "metric": _hint_one_of(METRICS),
427 "period": _hint_one_of(PERIODS),
428 }
430 def validate_config(self, config: dict) -> dict:
431 return {
432 "metric": _one_of(config, "metric", self.METRICS, "total_tokens"),
433 "period": _one_of(config, "period", self.PERIODS, "this_month"),
434 }
437@register_widget
438class ChartWidget(WidgetRenderer):
439 """A chart over one of the platform's recorded series."""
441 type = WidgetType.chart
442 label = "Chart"
443 description = "Plot spend, tokens, latency or source trust over time."
444 category = "platform"
445 data_kind = DashboardEnum.DataKind.platform
446 default_size = {"w": 6, "h": 5}
447 default_config = {
448 "source": "llm_invocations",
449 "metric": "total_tokens",
450 "chart_type": "area",
451 "limit": 50,
452 }
453 #: Each series the chart can plot, with the metrics the frontend draws
454 #: for it.
455 METRICS: dict[str, tuple[str, ...]] = {
456 "llm_invocations": ("total_tokens", "latency_ms", "estimated_cost_usd"),
457 "web_search_domains": ("visit_count", "avg_trust_score"),
458 }
459 CHART_TYPES = ("area", "line", "bar")
460 LIMIT = (1, 500)
462 config_schema = {
463 "source": _hint_one_of(METRICS),
464 "metric": "string — "
465 + "; ".join(
466 f"for {source}: {vocab.one_of(metrics, quote='')}"
467 for source, metrics in METRICS.items()
468 ),
469 "chart_type": _hint_one_of(CHART_TYPES),
470 "limit": _hint_int(LIMIT, "how many points to plot"),
471 }
473 def validate_config(self, config: dict) -> dict:
474 source = _one_of(config, "source", self.METRICS, "llm_invocations")
475 return {
476 "source": source,
477 "metric": _one_of(
478 config, "metric", self.METRICS[source], self.METRICS[source][0]
479 ),
480 "chart_type": _one_of(config, "chart_type", self.CHART_TYPES, "area"),
481 "limit": _int_between(config, "limit", self.LIMIT, 50),
482 }
485@register_widget
486class BreakdownWidget(WidgetRenderer):
487 """One platform metric, sliced by agent, model, project or organisation.
489 The dimensioned counterpart to :class:`StatWidget`, which reports the same
490 kinds of figure for the whole account. Everything it can show comes from
491 svc-core's governance usage ledger, and everything it *offers* comes from
492 the registries in ``app.services.stats`` — so the picker's metrics,
493 dimensions and periods are the ones the query can actually honour, and a
494 metric added as a class appears here with no change to this file.
496 Deliberately not a separate "chart" and "list" and "number" type. They are
497 one question asked three ways, and splitting them would mean a user who
498 wanted the same figure as a bar instead of a row had to rebuild the tile.
499 """
501 type = WidgetType.breakdown
502 label = "Breakdown"
503 description = (
504 "One platform metric sliced by a dimension it records, as a bar chart, "
505 "a list or a single number."
506 )
507 category = "platform"
508 data_kind = DashboardEnum.DataKind.platform
509 default_size = {"w": 4, "h": 4}
510 default_config = {
511 "metric": "estimated_cost_usd",
512 "dimension": "agent",
513 "period": "this_month",
514 "display": "bar",
515 "limit": 5,
516 "filters": [],
517 }
518 DISPLAYS = ("bar", "list", "value")
519 LIMIT = (1, 20)
521 def config_hints(self) -> dict[str, str]:
522 """Rendered from the stats registries on each call, as validation reads
523 them — a metric or dimension registered as a class appears in the
524 generator's catalogue with no change here."""
525 from app.services.stats import dimensions as dimension_registry
526 from app.services.stats import metrics as metric_registry
527 from app.services.stats import periods as period_registry
528 from app.services.stats import sources as source_registry
530 sources = [spec["key"] for spec in source_registry.catalogue()]
531 by_source = "; ".join(
532 f"{source}: "
533 + vocab.inline(
534 {
535 m.key: m.description or m.key
536 for m in metric_registry.metrics_for_source(source)
537 }
538 )
539 for source in sources
540 )
541 slices = "; ".join(
542 f"{source}: "
543 + vocab.listing(
544 (d.key for d in dimension_registry.dimensions_for_source(source)),
545 sep=", ",
546 )
547 for source in sources
548 )
549 return {
550 "metric": f"string — {by_source}",
551 "dimension": (
552 "string — what to slice by, and it must be recorded on the "
553 f"metric's own source. {slices}. Omit or null for a single figure."
554 ),
555 "period": _hint_one_of(spec["key"] for spec in period_registry.catalogue()),
556 "display": _hint_one_of(self.DISPLAYS),
557 "limit": _hint_int(
558 self.LIMIT,
559 "how many slices to show before folding the rest into 'Other'",
560 ),
561 "filters": (
562 "array of strings written as '<dimension>:<value>', narrowing "
563 "to one value of a dimension that is not a resource (an "
564 "execution type, an outcome); empty for no narrowing"
565 ),
566 }
568 def without_model_ids(self, config: dict) -> tuple[dict, bool]:
569 """Also every filter naming one resource — an agent, a model, a
570 project — by id: the model is never shown one, and a filter on an id
571 nothing has would show "no data" under a caption naming it."""
572 from app.services.stats import breakdown as breakdown_service
573 from app.services.stats import dimensions as dimension_registry
575 stripped, invented = super().without_model_ids(config)
576 filters = stripped.get("filters")
577 if not isinstance(filters, list):
578 return stripped, invented
579 kept = []
580 for entry in filters:
581 try:
582 ((key, value),) = breakdown_service.parse_filters([entry])
583 except (breakdown_service.BreakdownError, ValueError):
584 kept.append(entry) # validate_config refuses it, with why
585 continue
586 dimension = dimension_registry.get_dimension(key)
587 if dimension is not None and isinstance(dimension.coerce(value), UUID):
588 invented = True
589 continue
590 kept.append(entry)
591 stripped["filters"] = kept
592 return stripped, invented
594 def validate_config(self, config: dict) -> dict:
595 # Validated against the same registries the query reads, rather than
596 # against a literal list restated here. A metric this widget would
597 # accept but the breakdown could not compute is a tile that saves
598 # cleanly and then shows an error, which is the worst of both.
599 from app.services.stats import breakdown as breakdown_service
600 from app.services.stats import dimensions as dimension_registry
601 from app.services.stats import metrics as metric_registry
602 from app.services.stats import periods as period_registry
604 metric = _one_of(
605 config, "metric", metric_registry.metric_keys(), "estimated_cost_usd"
606 )
607 source = metric_registry.get_metric(metric).source
609 raw_dimension = config.get("dimension")
610 dimension: str | None = None
611 if raw_dimension:
612 dimension = _one_of(
613 config, "dimension", dimension_registry.dimension_keys(), "agent"
614 )
615 # The same cross-source check the query makes, made here so a tile
616 # cannot be stored in a shape that errors on every refresh. The
617 # generative flow is the reason it matters: a model proposing a
618 # board will pair "blocks" with a dimension that only exists on
619 # the redaction expansion.
620 axis = dimension_registry.get_dimension(dimension)
621 if source not in axis.sources:
622 raise WidgetConfigError(
623 f"'{dimension}' cannot slice '{metric}' — they are "
624 f"recorded on different sources."
625 )
627 limit = _int_between(config, "limit", self.LIMIT, 5)
629 filters = []
630 for entry in _as_list(config, "filters"):
631 if not isinstance(entry, str):
632 raise WidgetConfigError("Each filter must be a string.")
633 filters.append(entry.strip())
634 try:
635 # Resolved now rather than at render time, through the same code
636 # the query uses. A filter the query cannot honour would otherwise
637 # be dropped silently on every refresh, widening the tile from one
638 # project to the whole account while its caption still named the
639 # project.
640 #
641 # This matters most on the generative path: a model proposing a
642 # board can invent an id, and ``value_filters`` is what refuses
643 # one that is not even shaped like a resource reference. What it
644 # cannot check is whether a well-formed id *exists* — that needs a
645 # session this method is not given. The consequence is bounded and
646 # honest rather than hidden: such a tile reports no data for a
647 # resource that has none, which is a true statement, where a
648 # dropped filter would have reported the account's total under a
649 # caption naming one agent.
650 for key, value in breakdown_service.parse_filters(filters):
651 narrowing = dimension_registry.get_dimension(key)
652 if narrowing is None:
653 raise WidgetConfigError(
654 f"'{key}' is not a dimension this platform records."
655 )
656 if source not in narrowing.sources:
657 raise WidgetConfigError(
658 f"'{key}' cannot narrow '{metric}' — they are "
659 f"recorded on different sources."
660 )
661 narrowing.value_filters(value)
662 except (breakdown_service.BreakdownError, ValueError) as exc:
663 raise WidgetConfigError(str(exc)) from exc
665 return {
666 "metric": metric,
667 "dimension": dimension,
668 "period": _one_of(
669 config,
670 "period",
671 set(period_registry.PERIODS),
672 period_registry.DEFAULT_PERIOD,
673 ),
674 "display": _one_of(config, "display", self.DISPLAYS, "bar"),
675 "limit": limit,
676 "filters": filters,
677 }
680@register_widget
681class PinnedMessageWidget(WidgetRenderer):
682 """A chat message the user pinned out of a conversation.
684 The message text is snapshotted into config on pin, so the tile keeps
685 rendering if the conversation is later deleted; ``conversation_id`` is
686 kept so the tile can still link back when it survives.
687 """
689 type = WidgetType.pinned_message
690 label = "Pinned message"
691 description = "Keep a useful answer from a chat where you can see it."
692 category = "content"
693 data_kind = DashboardEnum.DataKind.stored
694 stores_user_content = True
695 default_size = {"w": 4, "h": 4}
696 default_config = {"content": "", "role": "assistant"}
697 config_schema = {
698 "content": ("string — the message text to keep"),
699 "role": _hint_one_of(vocab.values(MessageEnum.Role)),
700 "source_label": ("string — where it came from"),
701 }
703 def validate_config(self, config: dict) -> dict:
704 out = {
705 "content": _as_str(config, "content", required=True),
706 "role": _one_of(
707 config,
708 "role",
709 vocab.values(MessageEnum.Role),
710 MessageEnum.Role.ASSISTANT,
711 ),
712 "source_label": _as_str(config, "source_label"),
713 }
714 for key in ("conversation_id", "message_id", "pinned_at"):
715 value = config.get(key)
716 if value:
717 out[key] = str(value)
718 return out
721@register_widget
722class ResourceListWidget(WidgetRenderer):
723 """A live list of one of the user's resource collections."""
725 type = WidgetType.resource_list
726 label = "Resource list"
727 description = "Your most recent agents, knowledge bases, skillsets or chats."
728 category = "platform"
729 data_kind = DashboardEnum.DataKind.platform
730 default_size = {"w": 4, "h": 5}
731 default_config = {"resource": "agents", "limit": 5}
732 LIMIT = (1, 25)
734 #: The collections a tile can list, in the order they are offered.
735 RESOURCE_ORDER = (
736 "agents",
737 "knowledge",
738 "toolkits",
739 "skillsets",
740 "conversations",
741 "projects",
742 )
743 RESOURCES = frozenset(RESOURCE_ORDER)
745 def resources(self) -> set[str]:
746 """What a new or edited tile may list.
748 A toolkit bundles MCP servers, which are not available in this
749 release, so a tile may not be set to list toolkits. One that already
750 does is left as it is: a board's saves re-validate only the tiles
751 they change.
752 """
753 if mcp_service.is_available():
754 return set(self.RESOURCES)
755 return self.RESOURCES - {"toolkits"}
757 def config_hints(self) -> dict[str, str]:
758 """What :meth:`resources` allows today — so toolkits are offered only
759 while MCP servers are available."""
760 return {
761 "resource": _hint_one_of(
762 r for r in self.RESOURCE_ORDER if r in self.resources()
763 ),
764 "limit": _hint_int(self.LIMIT),
765 }
767 def validate_config(self, config: dict) -> dict:
768 return {
769 "resource": _one_of(config, "resource", self.resources(), "agents"),
770 "limit": _int_between(config, "limit", self.LIMIT, 5),
771 }
774@register_widget
775class MessageListWidget(WidgetRenderer):
776 """A running list of chat messages the user chose to keep.
778 Distinct from ``pinned_message``, which holds exactly one: this is the
779 collection a user saves into from a conversation over time. Items are
780 appended through ``POST .../widgets/{id}/items`` rather than by rewriting
781 the whole config, so two saves from different tabs cannot clobber one
782 another's entries.
783 """
785 type = WidgetType.message_list
786 label = "Saved messages"
787 description = "A list you save chat answers into, straight from a conversation."
788 category = "content"
789 data_kind = DashboardEnum.DataKind.stored
790 stores_user_content = True
791 default_size = {"w": 4, "h": 6}
792 default_config = {"items": [], "max_items": 25}
793 #: Hard ceiling regardless of the configured ``max_items``.
794 MAX_ITEMS = 100
795 ITEMS = (1, MAX_ITEMS)
797 config_schema = {
798 "items": ("array — leave empty; the user saves into this from chat"),
799 "max_items": _hint_int(ITEMS, "how many saved messages to keep"),
800 }
802 def validate_config(self, config: dict) -> dict:
803 max_items = _int_between(config, "max_items", self.ITEMS, 25)
805 items = []
806 for entry in _as_list(config, "items"):
807 if not isinstance(entry, dict):
808 raise WidgetConfigError("Each saved message must be an object.")
809 items.append(self.normalise_item(entry))
811 return {"items": items[:max_items], "max_items": max_items}
813 def normalise_item(self, entry: dict) -> dict:
814 """One saved message, as stored. Also used by the append endpoint."""
815 item = {
816 "id": _as_str(entry, "id") or uuid4().hex,
817 "content": _as_str(entry, "content", required=True)[:10_000],
818 "role": _one_of(
819 entry,
820 "role",
821 vocab.values(MessageEnum.Role),
822 MessageEnum.Role.ASSISTANT,
823 ),
824 "note": _as_str(entry, "note")[:280],
825 "source_label": _as_str(entry, "source_label")[:140],
826 "saved_at": _as_str(entry, "saved_at") or aware_utcnow().isoformat(),
827 }
828 for key in ("conversation_id", "message_id"):
829 value = entry.get(key)
830 if value:
831 item[key] = str(value)
832 return item
835# ---------------------------------------------------------------------------
836# Network widgets
837#
838# How the platform's resources connect, drawn from stored records: which
839# agents reach which knowledge, what they remember, how a website source's
840# pages link and what a graph source holds. Static — the frontend reads the
841# graph endpoints as the viewer — and ``platform`` data, never a model's.
842#
843# A tile that draws one source or one agent may leave its id empty, and then
844# draws a documented default (the newest such source; every agent) which its
845# caption names. That is what lets a template or the dashboard generator place
846# one without inventing an id.
847# ---------------------------------------------------------------------------
849#: How many agents a network tile may be narrowed to.
850MAX_NETWORK_AGENTS = 20
853@register_widget
854class KnowledgeNetworkWidget(WidgetRenderer):
855 """Agents, the repositories granted to them, and the sources inside."""
857 type = WidgetType.knowledge_network
858 label = "Knowledge network"
859 description = (
860 "Which agents can reach which knowledge — repositories, sources and "
861 "memory — with shared and unreachable sources called out."
862 )
863 reference_fields = ("agent_ids",)
864 category = "network"
865 data_kind = DashboardEnum.DataKind.platform
866 default_size = {"w": 8, "h": 8}
867 default_config = {
868 "agent_ids": [],
869 "include_memory": True,
870 "include_unconnected": True,
871 }
872 config_schema = {
873 "agent_ids": "array of agent ids to focus on; empty for every agent",
874 "include_memory": "boolean — draw each agent's memory store beside it",
875 "include_unconnected": (
876 "boolean — also draw repositories and sources no agent reaches"
877 ),
878 }
880 def validate_config(self, config: dict) -> dict:
881 return {
882 "agent_ids": _uuid_list(config, "agent_ids", limit=MAX_NETWORK_AGENTS),
883 "include_memory": bool(config.get("include_memory", True)),
884 "include_unconnected": bool(config.get("include_unconnected", True)),
885 }
887 def references(self, config: dict) -> list[ResourceRef]:
888 return [ResourceRef("agent", a) for a in config.get("agent_ids") or []]
891@register_widget
892class AgentMemoryWidget(WidgetRenderer):
893 """What agents remember, conversation by conversation."""
895 type = WidgetType.agent_memory
896 label = "Memory graph"
897 description = (
898 "What your agents carry between chats — each conversation they "
899 "remember, and what they took from it."
900 )
901 reference_fields = ("agent_id",)
902 category = "network"
903 data_kind = DashboardEnum.DataKind.platform
904 default_size = {"w": 6, "h": 7}
905 default_config = {"agent_id": "", "recent": 20}
906 RECENT = (0, 100)
907 config_schema = {
908 "agent_id": (
909 "string — one agent's id, or empty for every agent that remembers anything"
910 ),
911 "recent": _hint_int(RECENT, "newest memory entries to draw per agent"),
912 }
914 def validate_config(self, config: dict) -> dict:
915 return {
916 "agent_id": _optional_uuid(config, "agent_id"),
917 "recent": _int_between(config, "recent", self.RECENT, 20),
918 }
920 def references(self, config: dict) -> list[ResourceRef]:
921 agent_id = config.get("agent_id")
922 return [ResourceRef("agent", agent_id)] if agent_id else []
925@register_widget
926class WebLinkGraphWidget(WidgetRenderer):
927 """A website source's pages, as the network its crawl walked."""
929 type = WidgetType.web_link_graph
930 label = "Website link graph"
931 description = (
932 "A website source's pages as the crawl walked them — starting URLs at "
933 "the centre, one ring per link, other sites dashed."
934 )
935 reference_fields = ("knowledge_id",)
936 category = "network"
937 data_kind = DashboardEnum.DataKind.platform
938 default_size = {"w": 6, "h": 8}
939 default_config = {"knowledge_id": "", "mode": "paths"}
940 MODES = {"paths": "the crawl's own tree", "all": "every link"}
941 config_schema = {
942 "knowledge_id": (
943 "string — a website source's id, or empty for the newest website source"
944 ),
945 "mode": "string — "
946 + vocab.guide(MODES, indent="", sep=" (", end=")", align=False, joiner=" or "),
947 }
949 def validate_config(self, config: dict) -> dict:
950 return {
951 "knowledge_id": _optional_uuid(config, "knowledge_id"),
952 "mode": _one_of(config, "mode", self.MODES, "paths"),
953 }
955 def references(self, config: dict) -> list[ResourceRef]:
956 kid = config.get("knowledge_id")
957 return [ResourceRef("knowledge", kid, source_type="web")] if kid else []
960@register_widget
961class KnowledgeGraphWidget(WidgetRenderer):
962 """A graph source's entities and the relationships between them."""
964 type = WidgetType.knowledge_graph
965 label = "Knowledge graph"
966 description = (
967 "The entities and relationships in a graph knowledge source, as your "
968 "agents retrieve over them."
969 )
970 reference_fields = ("knowledge_id",)
971 category = "network"
972 data_kind = DashboardEnum.DataKind.platform
973 default_size = {"w": 6, "h": 8}
974 default_config = {"knowledge_id": ""}
975 config_schema = {
976 "knowledge_id": (
977 "string — a graph source's id, or empty for the newest graph source"
978 ),
979 }
981 def validate_config(self, config: dict) -> dict:
982 return {"knowledge_id": _optional_uuid(config, "knowledge_id")}
984 def references(self, config: dict) -> list[ResourceRef]:
985 kid = config.get("knowledge_id")
986 return [ResourceRef("knowledge", kid, source_type="graph")] if kid else []
989# ---------------------------------------------------------------------------
990# Assurance
991# ---------------------------------------------------------------------------
994@register_widget
995class AssuranceWidget(WidgetRenderer):
996 """Evaluation evidence: the platform benchmark, and the viewer's agents.
998 Drawn by fe-core from ``GET /app/evaluations/benchmark`` (the same for
999 every user: CHAINR Bot and each maker's strongest model on the gold datasets) and
1000 ``GET /app/evaluations/assurance`` (the viewer's workspace), so it names
1001 no resource and keeps nothing — fit for a built-in board.
1002 """
1004 type = WidgetType.assurance
1005 label = "Assurance"
1006 description = (
1007 "How models and agents score on the gold datasets — the platform "
1008 "benchmark's rankings, risk and trend, and which of your agents have "
1009 "passing evidence behind them."
1010 )
1011 category = "platform"
1012 data_kind = DashboardEnum.DataKind.platform
1013 default_size = {"w": 6, "h": 8}
1014 default_config = {"view": "leaderboard"}
1015 #: What a tile shows. fe-core draws each (``AssuranceWidgets.tsx``
1016 #: ``VIEWS``), and a test holds the two lists equal.
1017 VIEWS = {
1018 "leaderboard": (
1019 "CHAINR Bot and each maker's strongest model ranked by their average across "
1020 "the gold datasets, with risk"
1021 ),
1022 "risk_return": (
1023 "average against risk for every benchmarked model, with the "
1024 "efficient frontier"
1025 ),
1026 "scores": (
1027 "every model's score on every gold dataset, against each dataset's "
1028 "pass mark"
1029 ),
1030 "bot_trend": "CHAINR Bot's score on each gold dataset, release by release",
1031 "fleet": (
1032 "the user's own agents: which have passing evaluation evidence for "
1033 "the version in force"
1034 ),
1035 }
1036 config_schema = {
1037 "view": "string — "
1038 + vocab.guide(VIEWS, indent="", sep=" (", end=")", align=False, joiner=" or "),
1039 }
1041 def validate_config(self, config: dict) -> dict:
1042 return {"view": _one_of(config, "view", self.VIEWS, "leaderboard")}
1044 def references(self, config: dict) -> list[ResourceRef]:
1045 return []
1048# ---------------------------------------------------------------------------
1049# Feed widgets
1050#
1051# Exact third-party data, fetched verbatim and cached on the same machinery as
1052# the generated types. They are ``is_dynamic`` but ``data_kind = feed``, so the
1053# UI can show them as sourced fact rather than model output.
1054# ---------------------------------------------------------------------------
1057@register_widget
1058class WeatherWidget(WidgetRenderer):
1059 """Current conditions and a short forecast for one location."""
1061 type = WidgetType.weather
1062 label = "Weather"
1063 description = "Current conditions and a multi-day forecast for a place you pick."
1064 category = "feeds"
1065 data_kind = DashboardEnum.DataKind.feed
1066 is_dynamic = True
1067 default_size = {"w": 4, "h": 5}
1068 default_refresh_interval_seconds = 3_600 # hourly
1069 default_config = {
1070 "latitude": 51.5072,
1071 "longitude": -0.1276,
1072 "location_name": "London",
1073 "units": "metric",
1074 "days": 5,
1075 }
1076 LATITUDE = (-90, 90)
1077 LONGITUDE = (-180, 180)
1078 UNITS = ("metric", "imperial")
1079 DAYS = (1, 7)
1080 config_schema = {
1081 "latitude": f"number {LATITUDE[0]}..{LATITUDE[1]}",
1082 "longitude": f"number {LONGITUDE[0]}..{LONGITUDE[1]}",
1083 "location_name": ("string — the place name shown on the tile"),
1084 "units": _hint_one_of(UNITS),
1085 "days": _hint_int(DAYS, "forecast length"),
1086 }
1088 def validate_config(self, config: dict) -> dict:
1089 coordinates = {}
1090 for key, (low, high) in (
1091 ("latitude", self.LATITUDE),
1092 ("longitude", self.LONGITUDE),
1093 ):
1094 value = config.get(key)
1095 if not isinstance(value, (int, float)) or not low <= value <= high:
1096 raise WidgetConfigError(
1097 f"'{key}' must be a number between {low} and {high}."
1098 )
1099 coordinates[key] = float(value)
1101 return {
1102 **coordinates,
1103 "location_name": _as_str(config, "location_name", required=True)[:120],
1104 "units": _one_of(config, "units", self.UNITS, "metric"),
1105 "days": _int_between(config, "days", self.DAYS, 5),
1106 }
1108 def generate(self, db: Session, widget) -> dict:
1109 from . import feeds
1111 config = widget.config or {}
1112 try:
1113 forecast = feeds.fetch_forecast(
1114 config["latitude"],
1115 config["longitude"],
1116 units=config.get("units", "metric"),
1117 days=config.get("days", 5),
1118 )
1119 except feeds.FeedError as exc:
1120 raise WidgetGenerationError(str(exc)) from exc
1121 return {**forecast, "location_name": config.get("location_name", "")}
1124@register_widget
1125class RSSWidget(WidgetRenderer):
1126 """Headlines from an RSS or Atom feed, verbatim.
1128 Pairs with the generated widgets by design: a user can put a publisher's
1129 own headlines next to a model's summary of them and see both, rather than
1130 having to trust the summary alone.
1131 """
1133 type = WidgetType.rss
1134 label = "RSS feed"
1135 description = "Headlines straight from a source's own feed — no model in between."
1136 category = "feeds"
1137 data_kind = DashboardEnum.DataKind.feed
1138 is_dynamic = True
1139 default_size = {"w": 4, "h": 6}
1140 default_refresh_interval_seconds = 3_600 # hourly
1141 default_config = {"url": "", "limit": 8, "show_summaries": True}
1142 LIMIT = (1, 50)
1143 config_schema = {
1144 "url": (
1145 "string — the publisher's real RSS or Atom feed URL. Use only feeds you are confident exist; a URL that does not resolve is dropped."
1146 ),
1147 "limit": _hint_int(LIMIT, "headlines to show"),
1148 "show_summaries": ("boolean"),
1149 }
1151 def validate_config(self, config: dict) -> dict:
1152 from . import feeds
1154 url = _as_str(config, "url", required=True)
1155 try:
1156 feeds.validate_feed_url(url)
1157 except feeds.FeedError as exc:
1158 raise WidgetConfigError(str(exc)) from exc
1160 limit = _int_between(config, "limit", self.LIMIT, 8)
1162 return {
1163 "url": url,
1164 "limit": limit,
1165 "show_summaries": bool(config.get("show_summaries", True)),
1166 }
1168 def generate(self, db: Session, widget) -> dict:
1169 from . import feeds
1171 config = widget.config or {}
1172 try:
1173 return feeds.fetch_feed(config["url"], config.get("limit", 8))
1174 except feeds.FeedError as exc:
1175 raise WidgetGenerationError(str(exc)) from exc
1178@register_widget
1179class MarketWidget(WidgetRenderer):
1180 """Quotes for a watchlist, plus a price chart for one of them.
1182 Exact vendor data, so it sits beside a generated market commentary rather
1183 than inside one: the numbers are sourced and labelled, the interpretation
1184 is marked as a model's.
1185 """
1187 type = WidgetType.market
1188 label = "Market"
1189 description = "Quotes for a watchlist and a price chart, from a market data vendor."
1190 category = "feeds"
1191 data_kind = DashboardEnum.DataKind.feed
1192 is_dynamic = True
1193 default_size = {"w": 5, "h": 6}
1194 # Free vendor tiers allow only a few dozen calls a day, and one refresh
1195 # spends one per symbol — so the default cadence is deliberately slow.
1196 default_refresh_interval_seconds = 21_600 # every 6 hours
1197 # The board generator may not go quicker: a model asked for "live" prices
1198 # set 60 s, which spends a free tier's day of calls in an hour.
1199 min_refresh_interval_seconds = 21_600
1200 default_config = {"symbols": [], "chart_symbol": "", "days": 30}
1201 MAX_SYMBOLS = 6
1202 DAYS = (5, 100)
1203 config_schema = {
1204 "symbols": (
1205 f"array of 1-{MAX_SYMBOLS} ticker strings as the vendor expects "
1206 "them, e.g. AAPL, MSFT, NVDA"
1207 ),
1208 "chart_symbol": ("string — which of `symbols` to draw the price chart for"),
1209 "days": _hint_int(DAYS, "how many trading days to chart"),
1210 }
1212 def validate_config(self, config: dict) -> dict:
1213 symbols = []
1214 for entry in _as_list(config, "symbols", required=True):
1215 if not isinstance(entry, str) or not entry.strip():
1216 raise WidgetConfigError("Each ticker must be a non-empty string.")
1217 symbols.append(entry.strip().upper())
1218 if len(symbols) > self.MAX_SYMBOLS:
1219 raise WidgetConfigError(
1220 f"A market widget supports at most {self.MAX_SYMBOLS} tickers "
1221 "— vendor free tiers are rate-limited per call."
1222 )
1224 days = _int_between(config, "days", self.DAYS, 30)
1226 chart_symbol = _as_str(config, "chart_symbol").upper()
1227 if chart_symbol and chart_symbol not in symbols:
1228 raise WidgetConfigError(
1229 "'chart_symbol' must be one of the configured tickers."
1230 )
1232 return {
1233 "symbols": symbols,
1234 "chart_symbol": chart_symbol or symbols[0],
1235 "days": days,
1236 }
1238 def available(self) -> bool:
1239 """Only with a market data vendor configured: there is no keyless
1240 source of equity prices (``market.py``)."""
1241 from . import market
1243 return market.is_configured()
1245 def generate(self, db: Session, widget) -> dict:
1246 from . import market
1248 config = widget.config or {}
1249 try:
1250 return market.fetch_market(
1251 config.get("symbols") or [],
1252 config.get("chart_symbol") or "",
1253 config.get("days", 30),
1254 )
1255 except market.MarketDataUnavailable as exc:
1256 # Distinct from a failure: nothing is wrong, it just needs setup.
1257 raise WidgetGenerationError(str(exc)) from exc
1258 except (market.MarketDataError, FeedError) as exc:
1259 raise WidgetGenerationError(str(exc)) from exc
1262# ---------------------------------------------------------------------------
1263# Dynamic widgets
1264#
1265# Both of these invoke a model or agent. They reuse the evaluation service's
1266# execution targets so a dashboard automation runs through exactly the same
1267# path (and the same rule enforcement) as an evaluation run — but they are not
1268# evaluations, and say so: the targets default to recording themselves as one.
1269# ---------------------------------------------------------------------------
1272#: Cap on a generated tile's prose so one runaway widget cannot bloat a row.
1273#: A document the tile keeps is stored whole beside it (``_shape_output``): a
1274#: document fence the cap cut through no longer parsed, and the tile's
1275#: document silently vanished.
1276MAX_OUTPUT_CHARS = 20_000
1278#: Documents one refresh keeps — the one the tile's PDF downloads.
1279MAX_TILE_DOCUMENTS = 1
1281#: How long one refresh's call may take. Longer than an evaluation cell's: a
1282#: tile may search the web, run its agent's skill graph and render a document
1283#: with its images, and svc-ai went on spending after svc-core had given up
1284#: at a cell's two minutes.
1285TILE_TIMEOUT_S = 300.0
1287#: How much of the previous refresh's answer the next one is shown, so a
1288#: daily tile says what changed rather than repeating itself.
1289PREVIOUS_ANSWER_CHARS = 1_500
1291#: What svc-ai records a tile's call as. fe-core's Activity feed labels it and
1292#: links it back to the board on this.
1293WIDGET_TRACE_PURPOSE = "dashboard_widget"
1294#: What the usage ledger and governance activity log record it as.
1295EXECUTION_TYPE = "dashboard"
1298@dataclass(frozen=True)
1299class TileAnswer:
1300 """What a tile's target answered, and who answered it."""
1302 text: str
1303 #: The agent's name or the model's, for the tile's PDF footer.
1304 runs_on: str
1307def _target_kind(spec: dict) -> str:
1308 return str(spec.get("type") or ("agent" if spec.get("agent_id") else "model"))
1311def _target_for(db: Session, widget, config: dict) -> tuple[Any, Any]:
1312 """The board and the target a widget's config names, attributed to it.
1314 The board is the owner: an agent target must be one the board's owner
1315 can reach, and the call is governed and ledgered under that owner like
1316 any other invocation. Resolved from the board rather than the viewer
1317 because tiles also refresh on the scheduler, with no viewer at all.
1319 A model answers as it does in chat, not as an evaluation cell (which
1320 runs at temperature 0 on 1,024 tokens: a daily fun fact repeated, and a
1321 model that reasons first spent the budget thinking and answered
1322 nothing). An agent keeps its own settings.
1323 """
1324 # Imported lazily — the targets module pulls in the agent stack, which
1325 # should not load merely because the registry was imported.
1326 from app.db.postgres.models import Dashboard
1327 from app.services import ai_client
1328 from app.services.evaluation.targets import TargetResolutionError, build_target
1330 dashboard = db.get(Dashboard, widget.dashboard_id)
1331 spec = dict(config.get("target") or {})
1332 if _target_kind(spec) == "model":
1333 spec = {
1334 "temperature": ai_client.DEFAULT_TEMPERATURE,
1335 "max_tokens": ai_client.DEFAULT_MAX_TOKENS,
1336 **spec,
1337 }
1338 try:
1339 target = build_target(spec, db, owner=dashboard)
1340 except TargetResolutionError as exc:
1341 raise WidgetGenerationError(str(exc)) from exc
1342 target.attribute(
1343 purpose=WIDGET_TRACE_PURPOSE,
1344 execution_type=EXECUTION_TYPE,
1345 reference={
1346 "dashboard_id": str(widget.dashboard_id),
1347 "widget_id": str(widget.id),
1348 },
1349 )
1350 target.timeout = TILE_TIMEOUT_S
1351 return dashboard, target
1354def _is_agent(target: Any) -> bool:
1355 return getattr(target, "type", None) == "agent"
1358def _runs_on(target: Any) -> str:
1359 """The agent's name, or the model's (never its provider's)."""
1360 label = str(getattr(target, "label", "") or "")
1361 if _is_agent(target):
1362 return label
1363 return str(getattr(target, "model_name", "") or label)
1366#: What opens a tile's instructions in an agent's task.
1367STEERING_HEADING = "How to answer — this runs unattended on a dashboard tile:"
1370def _steered(target: Any, task: str, steering: str) -> tuple[str, str]:
1371 """``(prompt, system_prompt)`` for a tile's call.
1373 An agent answers in its own instructions: a system prompt sent with it
1374 replaces the agent's (``agent_spec.Overrides``), and a tile's "You are a
1375 dashboard automation" had been doing exactly that, so an agent on a tile
1376 answered as nobody. The tile's own steering is the request's, so it goes
1377 in the task — after it, as how to answer. A model has no instructions of
1378 its own; the steering is its system prompt.
1379 """
1380 if not steering:
1381 return task, ""
1382 if _is_agent(target):
1383 return f"{task}\n\n{STEERING_HEADING}\n{steering}", ""
1384 return task, f"You write the content of a dashboard tile, unattended.\n{steering}"
1387def _tile_steering(
1388 widget,
1389 lines: Iterable[str],
1390 *,
1391 extra: str = "",
1392 previous: str = "",
1393) -> str:
1394 """The instructions every generated tile answers under, as one block:
1395 where it is shown, that nobody can be asked, the type's own ``lines``,
1396 the user's extra instructions (added to these, never in place of them)
1397 and, for a tile that refreshes, the gist of what it said last time."""
1398 title = str(getattr(widget, "title", "") or "").strip()
1399 out = [
1400 (
1401 f"- It is shown on a dashboard tile titled “{title}”."
1402 if title
1403 else "- It is shown on a dashboard tile."
1404 ),
1405 (
1406 "- Nobody can be asked anything: where the request leaves "
1407 "something open, choose sensibly and say what you assumed."
1408 ),
1409 *(f"- {line}" for line in lines if line),
1410 ]
1411 if extra.strip():
1412 out.append(f"- The tile's owner also asks: {extra.strip()}")
1413 if previous.strip():
1414 out.append(
1415 "- The previous refresh said (do not repeat it; say what has "
1416 f"changed where that matters):\n<previous>\n{previous.strip()}\n</previous>"
1417 )
1418 return "\n".join(out)
1421def _previous_prose(widget) -> str:
1422 """The prose of the tile's last answer, fences left out, capped."""
1423 from app.services.documents import split_document_fences
1425 payload = getattr(widget, "cache_payload", None) or {}
1426 markdown = payload.get("markdown") if isinstance(payload, dict) else None
1427 if not isinstance(markdown, str):
1428 return ""
1429 prose, _ = split_document_fences(markdown)
1430 return prose[:PREVIOUS_ANSWER_CHARS]
1433def _shape_output(text: str, *, keep_documents: bool) -> str:
1434 """What a tile stores of an answer: its prose capped at
1435 ``MAX_OUTPUT_CHARS``, and — only for a tile whose PDF is on and whose
1436 agent could have made one — its document, whole, after it.
1438 Every other fence goes: a tile with its PDF off never shows a document
1439 card, whatever the agent did, and a model target has no tools, so a
1440 document fence it wrote is its own text, never one ``render_document``
1441 validated (svc-ai's model engine has no artifact guard).
1442 """
1443 from app.services.documents import split_document_fences
1445 prose, fences = split_document_fences(text)
1446 prose = prose[:MAX_OUTPUT_CHARS].rstrip()
1447 kept = fences[-MAX_TILE_DOCUMENTS:] if keep_documents else []
1448 return "\n\n".join(part for part in (prose, *kept) if part)
1451#: Why a tile that asked a question failed, instead of caching the question.
1452CLARIFIED_INSTEAD = (
1453 "The agent asked a question instead of answering, and a tile runs "
1454 "unattended. Make the prompt self-contained."
1455)
1458def _invoke_target(
1459 db: Session, widget, config: dict, task: str, steering: str
1460) -> TileAnswer:
1461 """Run a widget's configured target (``_target_for``) on ``task``,
1462 steered as its kind takes it (``_steered``), and return its answer."""
1463 dashboard, target = _target_for(db, widget, config)
1464 invocation = target.invoke(*_steered(target, task, steering))
1465 _record_usage(db, dashboard, target, invocation)
1466 if not invocation.ok:
1467 raise WidgetGenerationError(invocation.shown_error or "Generation failed.")
1468 if invocation.clarification is not None:
1469 raise WidgetGenerationError(CLARIFIED_INSTEAD)
1470 return TileAnswer(invocation.output or "", _runs_on(target))
1473def _invoke_target_for(
1474 db: Session,
1475 widget,
1476 config: dict,
1477 task: str,
1478 steering: str,
1479 schema: type[ModelOutput],
1480) -> tuple[Any, str]:
1481 """Run a widget's configured target for a reply filled to ``schema``
1482 (``targets.invoke_structured``): every call ledgered, a correction's
1483 included. A call that failed, or a reply that never matched, fails the
1484 refresh. Returns the reply and who answered it."""
1485 from app.services.evaluation.targets import invoke_structured
1487 dashboard, target = _target_for(db, widget, config)
1488 result = invoke_structured(target, *_steered(target, task, steering), schema)
1489 for invocation in result.invocations:
1490 _record_usage(db, dashboard, target, invocation)
1491 if result.failed_call:
1492 raise WidgetGenerationError(result.last.shown_error or "Generation failed.")
1493 if result.value is None:
1494 logger.info("Tile %s answered out of shape: %s", widget.id, result.failure)
1495 raise WidgetGenerationError(
1496 "The answer did not come back in the tile's shape. Try refreshing."
1497 )
1498 return result.value, _runs_on(target)
1501def _record_usage(db: Session, dashboard, target, invocation) -> None:
1502 """Put a tile's call on the usage ledger, as every other invocation is.
1504 Without it a cost cap never counted a board's automations, however many
1505 ran. A blocked call is not written — it never reached the provider, and
1506 it is already on record in the governance activity log — and a failed
1507 one is written as an error, so it counts toward an error rate and no
1508 quota. Committed here: the refresh that follows commits the widget on
1509 the same session, but a failed refresh must not lose the spend.
1510 """
1511 from app.db.postgres.enums import UsageEnum
1512 from app.services import usage as usage_service
1514 # An organisation's or project's board is ledgered as the person its
1515 # tile ran as (``targets.govern``), no longer skipped.
1516 governance = getattr(target, "governance", None)
1517 owner_user_id = getattr(dashboard, "owner_user_id", None) or getattr(
1518 governance, "owner_user_id", None
1519 )
1520 if not owner_user_id or invocation.blocked:
1521 return
1522 from app.services.evaluation.targets import ledger_identity
1524 # The model that wrote the answer: an Economy profile's lighter one when
1525 # svc-ai says it did, else the target's own — as an evaluation cell's row.
1526 scope_type, scope_id, model_info = ledger_identity(target, invocation)
1527 usage_service.record_usage(
1528 db,
1529 owner_user_id=owner_user_id,
1530 execution_type=EXECUTION_TYPE,
1531 scope_type=scope_type,
1532 scope_id=scope_id,
1533 owner_project_id=getattr(dashboard, "owner_project_id", None),
1534 owner_organisation_id=getattr(dashboard, "owner_organisation_id", None),
1535 ai_model_id=model_info.get("id") if model_info else None,
1536 input_tokens=invocation.input_tokens,
1537 output_tokens=invocation.output_tokens,
1538 model_info=model_info or None,
1539 latency_ms=invocation.latency_ms,
1540 outcome=UsageEnum.Outcome.ok if invocation.ok else UsageEnum.Outcome.error,
1541 # The board is what the user built and watches; the scope is only
1542 # the agent or model the tile borrowed.
1543 source_type=UsageEnum.Source.dashboard,
1544 source_id=getattr(dashboard, "id", None),
1545 measured=invocation.usage,
1546 invocation_id=invocation.invocation_id,
1547 )
1548 try:
1549 db.commit()
1550 except Exception: # noqa: BLE001 - the ledger never fails the tile
1551 db.rollback()
1552 logger.exception("Could not commit usage for widget on %s", dashboard.id)
1555def _validate_target(config: dict) -> dict:
1556 """Shape-check a target spec without resolving it against the database."""
1557 target = config.get("target") or {}
1558 if not isinstance(target, dict):
1559 raise WidgetConfigError("'target' must be an object.")
1561 kind = str(target.get("type") or ("agent" if target.get("agent_id") else "model"))
1562 if kind not in {"agent", "model"}:
1563 raise WidgetConfigError("'target.type' must be 'agent' or 'model'.")
1565 if kind == "agent":
1566 if not target.get("agent_id"):
1567 raise WidgetConfigError("An agent target requires 'agent_id'.")
1568 return {"type": "agent", "agent_id": str(target["agent_id"])}
1570 out: dict[str, Any] = {"type": "model"}
1571 if target.get("model_id"):
1572 out["model_id"] = str(target["model_id"])
1573 elif target.get("provider") and target.get("model"):
1574 out["provider"] = str(target["provider"])
1575 out["model"] = str(target["model"])
1576 elif target.get("default") is True:
1577 # Whichever model the deployment marks as its default, resolved when
1578 # the tile runs — what a built-in board's generated tile uses, since
1579 # no model id is the same on every deployment.
1580 out["default"] = True
1581 else:
1582 raise WidgetConfigError(
1583 "A model target requires 'model_id', 'provider' and 'model', or "
1584 "'default': true."
1585 )
1586 return out
1589@register_widget
1590class AutomationWidget(WidgetRenderer):
1591 """A prompt that re-runs on a cadence and renders its answer as markdown.
1593 This is the "check the news every morning and summarise it" tile: the
1594 prompt is stored, the result is cached, and the cache is regenerated once
1595 it has aged past ``refresh_interval_seconds``.
1597 With ``pdf`` on, every refresh can be downloaded as a PDF: an agent is
1598 asked to finish with one ``render_document`` call, whose document the
1599 tile keeps, and a refresh without one (or a model's, which has no tools)
1600 is laid out from the answer (``documents.widget_document``). With it off
1601 the tile never holds a document, whatever the agent did — so a tile is
1602 the same from one refresh to the next.
1603 """
1605 type = WidgetType.automation
1606 label = "Automation"
1607 description = (
1608 "Run a prompt on a schedule — a news digest, a standup summary, "
1609 "a recurring check — and keep the latest answer on your board."
1610 )
1611 category = "intelligence"
1612 data_kind = DashboardEnum.DataKind.generated
1613 is_dynamic = True
1614 default_size = {"w": 4, "h": 6}
1615 default_refresh_interval_seconds = 86_400 # daily
1616 # Each refresh is a model's (or an agent's) whole turn.
1617 min_refresh_interval_seconds = 3_600
1618 default_config = {
1619 "prompt": "",
1620 "system_prompt": "",
1621 "style": "summary",
1622 "pdf": False,
1623 "target": {"type": "agent"},
1624 }
1625 STYLES = {
1626 "summary": "Answer as a few tight paragraphs.",
1627 "bullets": "Answer as a concise markdown bullet list, one line each.",
1628 "digest": (
1629 "Answer as a markdown digest: a one-line takeaway, then grouped "
1630 "bullets under bold headings."
1631 ),
1632 }
1633 config_schema = {
1634 "prompt": "string — the instruction to run on a schedule",
1635 "system_prompt": (
1636 "string — extra instructions added to the tile's own; may be empty"
1637 ),
1638 "style": _hint_one_of(STYLES),
1639 "pdf": (
1640 "boolean — also keep a downloadable PDF report of each refresh; "
1641 "true only when the user asks for a report or a document"
1642 ),
1643 }
1645 def validate_config(self, config: dict) -> dict:
1646 return {
1647 "prompt": _as_str(config, "prompt", required=True),
1648 "system_prompt": _as_str(config, "system_prompt"),
1649 "style": _one_of(config, "style", self.STYLES, "summary"),
1650 "pdf": _as_bool(config, "pdf"),
1651 "target": _validate_target(config),
1652 }
1654 def document(self, widget, index: int = 0) -> dict | None:
1655 from app.services.documents import widget_document
1657 return widget_document(
1658 widget, index, pdf=(widget.config or {}).get("pdf") is True
1659 )
1661 def steering(self, widget, config: dict) -> str:
1662 """How this tile's answer is asked for (``_tile_steering``)."""
1663 from app.services.documents import DOCUMENT_TOOL
1665 pdf = config.get("pdf") is True
1666 lines = [
1667 (
1668 "Write markdown read at a glance: no greeting, no restating "
1669 "of the request, no sign-off and no top-level heading."
1670 ),
1671 self.STYLES.get(config.get("style", "summary"), ""),
1672 ]
1673 if _target_kind(config.get("target") or {}) == "agent":
1674 title = str(getattr(widget, "title", "") or self.label).strip()
1675 lines.append(
1676 f"Then finish with exactly one {DOCUMENT_TOOL} call titled "
1677 f"“{title}” holding the full report, and keep the answer on "
1678 "the tile short."
1679 if pdf
1680 else f"Do not call {DOCUMENT_TOOL}: the tile shows your answer itself."
1681 )
1682 return _tile_steering(
1683 widget,
1684 lines,
1685 extra=config.get("system_prompt") or "",
1686 previous=_previous_prose(widget),
1687 )
1689 def generate(self, db: Session, widget) -> dict:
1690 config = widget.config or {}
1691 style = config.get("style", "summary")
1692 answer = _invoke_target(
1693 db, widget, config, config["prompt"], self.steering(widget, config)
1694 )
1695 keep = (
1696 config.get("pdf") is True
1697 and _target_kind(config.get("target") or {}) == "agent"
1698 )
1699 markdown = _shape_output(answer.text, keep_documents=keep)
1700 if not markdown.strip():
1701 raise WidgetGenerationError("The automation returned an empty answer.")
1702 return {
1703 "markdown": markdown,
1704 "style": style,
1705 "runs_on": answer.runs_on,
1706 "generated_at": utc_isoformat(aware_utcnow()),
1707 }
1710class AxisScore(ModelOutput):
1711 """A subject's place on one axis."""
1713 axis: str = Field(description="The axis's name, as given")
1714 score: float = Field(description="The subject's place on it, within its range")
1716 @field_validator("score", mode="before")
1717 @classmethod
1718 def _not_a_flag(cls, value: Any) -> Any:
1719 # ``true`` would read as 1.0: a placement nobody made. Refused, the
1720 # score is dropped (``OnErrorOmit``) and the tile shows the gap.
1721 if isinstance(value, bool):
1722 # A ValueError: pydantic reports it as a validation error, which
1723 # OnErrorOmit drops; a TypeError would escape it.
1724 raise ValueError("a score is a number, not true or false") # noqa: TRY004
1725 return value
1728class ComparisonRow(ModelOutput):
1729 """One subject, placed on every axis."""
1731 subject: str = Field(description="The subject, as given")
1732 scores: list[OnErrorOmit[AxisScore]] = Field(description="One score for every axis")
1733 note: str = Field(
1734 default="", description="One short sentence justifying the placement"
1735 )
1738class ComparisonReply(ModelOutput):
1739 """What a comparison tile's target is asked to fill. Scores are a list of
1740 named axes, not an object keyed by them: the schema stays the same for
1741 every tile, so a route compiles its grammar once (``structured_reply``)."""
1743 rows: list[OnErrorOmit[ComparisonRow]] = Field(
1744 description="One row for every subject"
1745 )
1746 summary: str = Field(default="", description="One sentence on the overall picture")
1749@register_widget
1750class ComparisonWidget(WidgetRenderer):
1751 """Score a set of subjects against shared axes.
1753 Built for questions of the "where do these sit relative to each other"
1754 kind — media outlets by political alignment and factual reliability,
1755 vendors by cost and lock-in, models by latency and quality. The result is
1756 a matrix the frontend can draw as a table, bars, or a scatter plot when
1757 exactly two axes are configured.
1758 """
1760 type = WidgetType.comparison
1761 label = "Comparison"
1762 description = (
1763 "Place subjects on axes you define — e.g. media outlets by political "
1764 "alignment and factual reliability — and keep the matrix current."
1765 )
1766 category = "intelligence"
1767 data_kind = DashboardEnum.DataKind.generated
1768 is_dynamic = True
1769 default_size = {"w": 6, "h": 6}
1770 default_refresh_interval_seconds = 604_800 # weekly
1771 default_config = {
1772 "subjects": [],
1773 "axes": [],
1774 "context": "",
1775 "target": {"type": "agent"},
1776 }
1777 MIN_SUBJECTS = 2
1778 MAX_SUBJECTS = 12
1779 MAX_AXES = 4
1780 config_schema = {
1781 "subjects": (
1782 f"array of {MIN_SUBJECTS}-{MAX_SUBJECTS} strings — the things being "
1783 "placed against each other"
1784 ),
1785 "axes": (
1786 f"array of 1-{MAX_AXES} {{name: string, min: number, max: number, "
1787 "min_label: string, max_label: string}. Exactly two axes renders a "
1788 "scatter plot."
1789 ),
1790 "context": ("string — optional narrowing instruction"),
1791 }
1793 def validate_config(self, config: dict) -> dict:
1794 subjects = [
1795 s.strip()
1796 for s in _as_list(config, "subjects", required=True)
1797 if isinstance(s, str) and s.strip()
1798 ]
1799 if len(subjects) < self.MIN_SUBJECTS:
1800 raise WidgetConfigError(
1801 f"A comparison needs at least {self.MIN_SUBJECTS} subjects."
1802 )
1803 if len(subjects) > self.MAX_SUBJECTS:
1804 raise WidgetConfigError(
1805 f"A comparison supports at most {self.MAX_SUBJECTS} subjects."
1806 )
1808 raw_axes = _as_list(config, "axes", required=True)
1809 if len(raw_axes) > self.MAX_AXES:
1810 raise WidgetConfigError(
1811 f"A comparison supports at most {self.MAX_AXES} axes."
1812 )
1814 axes = []
1815 for entry in raw_axes:
1816 if not isinstance(entry, dict):
1817 raise WidgetConfigError("Each axis must be an object.")
1818 minimum = entry.get("min", 0)
1819 maximum = entry.get("max", 10)
1820 if not isinstance(minimum, (int, float)) or not isinstance(
1821 maximum, (int, float)
1822 ):
1823 raise WidgetConfigError("Axis 'min' and 'max' must be numbers.")
1824 if minimum >= maximum:
1825 raise WidgetConfigError("An axis 'min' must be less than its 'max'.")
1826 axes.append(
1827 {
1828 "name": _as_str(entry, "name", required=True),
1829 "min": float(minimum),
1830 "max": float(maximum),
1831 "min_label": _as_str(entry, "min_label"),
1832 "max_label": _as_str(entry, "max_label"),
1833 }
1834 )
1836 return {
1837 "subjects": subjects,
1838 "axes": axes,
1839 "context": _as_str(config, "context"),
1840 "target": _validate_target(config),
1841 }
1843 def _prompt(self, config: dict) -> str:
1844 axes_spec = "\n".join(
1845 f'- "{a["name"]}": a number from {a["min"]} to {a["max"]}'
1846 + (
1847 f' (where {a["min"]} means "{a["min_label"]}" and '
1848 f'{a["max"]} means "{a["max_label"]}")'
1849 if a.get("min_label") and a.get("max_label")
1850 else ""
1851 )
1852 for a in config["axes"]
1853 )
1854 subjects = "\n".join(f"- {s}" for s in config["subjects"])
1855 context = config.get("context") or ""
1857 return (
1858 "Score each subject on every axis.\n\n"
1859 f"Subjects:\n{subjects}\n\n"
1860 f"Axes:\n{axes_spec}\n\n"
1861 + (f"Additional context to apply:\n{context}\n\n" if context else "")
1862 + "Include every subject exactly once and every axis for every "
1863 "subject, each by its name as given. Base scores on widely "
1864 "documented assessments rather than a single source, and keep each "
1865 "note under 20 words."
1866 )
1868 def generate(self, db: Session, widget) -> dict:
1869 config = widget.config or {}
1870 reply, runs_on = _invoke_target_for(
1871 db,
1872 widget,
1873 config,
1874 self._prompt(config),
1875 _tile_steering(
1876 widget,
1877 [
1878 (
1879 "Place the subjects as an impartial analyst: where a "
1880 "judgement is contested, place the subject at the "
1881 "consensus position and say so in its note."
1882 )
1883 ],
1884 ),
1885 ComparisonReply,
1886 )
1887 return {**self._normalise(config, reply), "runs_on": runs_on}
1889 def _normalise(self, config: dict, reply: ComparisonReply) -> dict:
1890 """Clamp scores into their axis ranges and fill in missing subjects.
1892 A model will occasionally drop a subject or return a score outside the
1893 declared range; the tile should still render, with the gap visible,
1894 rather than fail the whole refresh. Subjects and axes are matched by
1895 name, ignoring case and surrounding space.
1896 """
1897 axes = config["axes"]
1898 returned = {row.subject.strip().lower(): row for row in reply.rows}
1900 rows = []
1901 for subject in config["subjects"]:
1902 row = returned.get(subject.strip().lower())
1903 given = {
1904 score.axis.strip().lower(): score.score
1905 for score in (row.scores if row is not None else [])
1906 }
1907 scores: dict[str, Optional[float]] = {}
1908 for axis in axes:
1909 value = given.get(axis["name"].strip().lower())
1910 scores[axis["name"]] = (
1911 None
1912 if value is None
1913 else max(axis["min"], min(axis["max"], float(value)))
1914 )
1916 rows.append(
1917 {
1918 "subject": subject,
1919 "scores": scores,
1920 "note": (row.note if row is not None else "")[:280],
1921 "missing": all(v is None for v in scores.values()),
1922 }
1923 )
1925 return {"axes": axes, "rows": rows, "summary": reply.summary[:500]}