@mastra/mcp-apps-components 0.1.0-alpha.4 → 0.1.0-alpha.6

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.
@@ -0,0 +1,1286 @@
1
+ import { t as OBSERVABILITY_DATE_PRESETS } from "./tool-CKJgZfHk.js";
2
+ import { DASHBOARD_MAX_QUERIES_PER_VIEW, DASHBOARD_MAX_WIDGETS, DASHBOARD_SCHEMA_VERSION, DASHBOARD_SCOPES, DASHBOARD_WIDGET_KINDS, dashboardDefaultsSchema, dashboardDefinitionSchema, dashboardQuerySchema, dashboardWidgetSchema, dashboardWidgetViewSchema } from "@mastra/core/storage/dashboards";
3
+ import { z } from "zod/v4";
4
+ // ../playground-ui/dist/domains/dashboards/lib/values.es.js
5
+ /**
6
+ * The options vocabulary widget kinds share. Values reference a view's query results and
7
+ * combine them with a few fixed operations; there are no free-form expressions.
8
+ */
9
+ /** Names one of the view's queries by its `id`, never its position, so reordering queries keeps refs. */
10
+ var queryRefSchema = z.string().min(1);
11
+ /** A number read from one query's result. */
12
+ var valueRefSchema = z.object({
13
+ /** The `id` of one of the view's queries. */
14
+ query: queryRefSchema,
15
+ /** Metrics and scores read `value` (or the price, `estimatedCost`); trace and span aggregates read a measure. */
16
+ field: z.enum(["value", "estimatedCost"]).optional(),
17
+ /** A trace or span aggregate measure, e.g. `countDistinct.threadId`. */
18
+ measure: z.string().min(1).optional(),
19
+ /** A percentile of a percentiles request, e.g. `0.95`. */
20
+ percentile: z.number().min(0).max(1).optional(),
21
+ /** Only the series whose group key is exactly one of these... */
22
+ groups: z.array(z.string()).min(1).optional(),
23
+ /** ...or is none of these. */
24
+ notGroups: z.array(z.string()).min(1).optional()
25
+ }).strict();
26
+ var constSchema = z.strictObject({ const: z.number() });
27
+ var sumSchema = z.strictObject({ get sum() {
28
+ return z.array(valueExprSchema).min(1);
29
+ } });
30
+ var minusSchema = z.strictObject({ get minus() {
31
+ return z.tuple([valueExprSchema, valueExprSchema]);
32
+ } });
33
+ var ratioSchema = z.strictObject({ get ratio() {
34
+ return z.strictObject({
35
+ of: valueExprSchema,
36
+ over: valueExprSchema
37
+ });
38
+ } });
39
+ var maxSchema = z.strictObject({ get max() {
40
+ return z.array(valueExprSchema).min(1);
41
+ } });
42
+ var coalesceSchema = z.strictObject({ get coalesce() {
43
+ return z.array(valueExprSchema).min(1);
44
+ } });
45
+ var valueExprSchema = z.union([
46
+ valueRefSchema,
47
+ constSchema,
48
+ sumSchema,
49
+ minusSchema,
50
+ ratioSchema,
51
+ maxSchema,
52
+ coalesceSchema
53
+ ]);
54
+ var formatSchema = z.enum([
55
+ "count",
56
+ "usd",
57
+ "duration",
58
+ "percent",
59
+ "score"
60
+ ]);
61
+ var colorSchema = z.enum([
62
+ "green",
63
+ "sky",
64
+ "violet",
65
+ "teal",
66
+ "indigo",
67
+ "warning",
68
+ "error",
69
+ "neutral"
70
+ ]);
71
+ /** Every ref an expression reads, in order. */
72
+ function exprRefs(expr) {
73
+ if ("const" in expr) return [];
74
+ if ("sum" in expr) return expr.sum.flatMap(exprRefs);
75
+ if ("minus" in expr) return expr.minus.flatMap(exprRefs);
76
+ if ("ratio" in expr) return [...exprRefs(expr.ratio.of), ...exprRefs(expr.ratio.over)];
77
+ if ("max" in expr) return expr.max.flatMap(exprRefs);
78
+ if ("coalesce" in expr) return expr.coalesce.flatMap(exprRefs);
79
+ return [expr];
80
+ }
81
+ /** An issue for each referenced query id the view doesn't have. */
82
+ function unknownQueryIssues(ids, queries, where = "options") {
83
+ const known = new Set(queries.flatMap((q) => q.id === void 0 ? [] : [q.id]));
84
+ return [...new Set(ids)].filter((id) => !known.has(id)).map((id) => `${where}: reads query '${id}', which the view doesn't have`);
85
+ }
86
+ // ../playground-ui/dist/domains/dashboards/kinds/kpis/options.es.js
87
+ var kpiItemSchema = z.object({
88
+ label: z.string().min(1),
89
+ icon: z.enum([
90
+ "bot",
91
+ "coins",
92
+ "hash",
93
+ "threads"
94
+ ]),
95
+ format: z.enum(["count", "usd"]),
96
+ /** A metrics or scores aggregate value, or the sum of several. Comparing needs `compare` on the queries. */
97
+ value: valueExprSchema,
98
+ detail: z.string(),
99
+ lowerIsBetter: z.boolean().optional()
100
+ }).strict();
101
+ var kpisOptionsSchema = z.object({ items: z.array(kpiItemSchema).min(1) }).strict();
102
+ var readsAggregates = (expr) => "query" in expr || "sum" in expr && expr.sum.every(readsAggregates);
103
+ var isAggregate = (query) => (query?.source === "metrics" || query?.source === "scores") && query.request === "aggregate";
104
+ /** What the schema can't say: query ids the view has, and only metrics or scores aggregates (scores naming a scorer), or sums of them. */
105
+ var kpisIssues = (view) => {
106
+ const byId = new Map(view.queries.map((q) => [q.id, q]));
107
+ return [
108
+ ...unknownQueryIssues(view.options.items.flatMap((i) => exprRefs(i.value).map((r) => r.query)), view.queries),
109
+ ...view.options.items.filter((i) => !readsAggregates(i.value)).map((i) => `KPI '${i.label}' can only read an aggregate or sum several`),
110
+ ...view.options.items.flatMap((i) => exprRefs(i.value).filter((r) => byId.has(r.query) && !isAggregate(byId.get(r.query))).map((r) => `KPI '${i.label}' reads query '${r.query}', which is not a metrics or scores aggregate`)),
111
+ ...view.options.items.flatMap((i) => exprRefs(i.value).filter((r) => {
112
+ const query = byId.get(r.query);
113
+ return query?.source === "scores" && query.scorerId === void 0;
114
+ }).map((r) => `KPI '${i.label}' reads scores query '${r.query}', which must name a scorer`))
115
+ ];
116
+ };
117
+ // ../playground-ui/dist/domains/dashboards/kinds/scores/options.es.js
118
+ var scoresOptionsSchema = z.object({
119
+ /** Id of the scores aggregate giving each scorer's mean over the range, sent as the Scores card sends it. */
120
+ average: queryRefSchema,
121
+ /** Id of the scores time series giving each scorer's line. */
122
+ series: queryRefSchema,
123
+ /** @deprecated Accepted so saved definitions still parse; every empty chart shows the same message. */
124
+ emptyMessage: z.string().optional()
125
+ }).strict();
126
+ /**
127
+ * Both ids must name scores queries of the right request, and when both name a scorer it must be the
128
+ * same one, since each scorer's mean and line are drawn together.
129
+ */
130
+ var scoresIssues = (view) => {
131
+ const issues = [];
132
+ const average = view.queries.find((q) => q.id === view.options.average);
133
+ const series = view.queries.find((q) => q.id === view.options.series);
134
+ if (average?.source !== "scores" || average.request !== "aggregate") issues.push(`options.average must name a scores aggregate query`);
135
+ if (series?.source !== "scores" || series.request !== "timeSeries") issues.push(`options.series must name a scores timeSeries query`);
136
+ const averageScorer = average?.source === "scores" ? average.scorerId : void 0;
137
+ const seriesScorer = series?.source === "scores" ? series.scorerId : void 0;
138
+ if (averageScorer && seriesScorer && averageScorer !== seriesScorer) issues.push(`options.average names scorer '${averageScorer}' but options.series names '${seriesScorer}'; they must match`);
139
+ return issues;
140
+ };
141
+ // ../playground-ui/dist/domains/dashboards/lib/table.es.js
142
+ /**
143
+ * The `table` kind: one row per group, joined across the view's queries on `groupBy`. Each column
144
+ * shows the row's name, a dimension, a value read from the row's answers, or a value's change
145
+ * against the previous window.
146
+ */
147
+ var TRACK = String.raw`(?:auto|max-content|\d+(?:\.\d+)?(?:rem|fr))`;
148
+ /** A CSS grid track: `auto`, `max-content`, `12rem`, `3fr`, or `minmax()` of two of those. */
149
+ var widthSchema = z.string().regex(new RegExp(String.raw`^(?:${TRACK}|minmax\(\s*${TRACK}\s*,\s*${TRACK}\s*\))$`), "Expected auto, max-content, Nrem, Nfr or minmax(a, b) of those");
150
+ var shared = {
151
+ /** The header's tooltip. */
152
+ description: z.string().optional(),
153
+ width: widthSchema.optional(),
154
+ sortable: z.boolean().optional()
155
+ };
156
+ var nameColumnSchema = z.strictObject({
157
+ type: z.literal("name"),
158
+ /** `project` shows the host's name for a project id. */
159
+ as: z.literal("project").optional(),
160
+ /** What a row without a name reads as. Defaults to "Unnamed". */
161
+ unnamed: z.string().optional(),
162
+ /** Before the name: an entity's icon, or the provider logo with the name read as `provider › model`. */
163
+ mark: z.union([z.strictObject({ icon: z.enum([
164
+ "agent",
165
+ "workflow",
166
+ "tool"
167
+ ]) }), z.strictObject({ providerDimension: z.string().min(1) })]).optional(),
168
+ ...shared
169
+ });
170
+ var dimensionColumnSchema = z.strictObject({
171
+ type: z.literal("dimension"),
172
+ dimension: z.string().min(1),
173
+ as: z.literal("project").optional(),
174
+ /** A lookup: that query's `dimension`, matched on the row's `joinOn` dimension. */
175
+ query: queryRefSchema.optional(),
176
+ joinOn: z.string().min(1).optional(),
177
+ ...shared
178
+ });
179
+ var valueColumnSchema = z.strictObject({
180
+ type: z.literal("value"),
181
+ /** Refs read this row's entry in the query: a `measure` of an aggregate, or a group's `field`. */
182
+ value: valueExprSchema,
183
+ format: z.enum([
184
+ "count",
185
+ "usd",
186
+ "duration",
187
+ "percent"
188
+ ]),
189
+ /** The figure the table ranks by, in full tone; the others are muted. */
190
+ emphasis: z.boolean().optional(),
191
+ /** Shown when the row has no value, e.g. 0 for a count. */
192
+ missing: z.number().optional(),
193
+ /** A total: a dropped row shows 0, and a value with none before is "New". */
194
+ additive: z.boolean().optional(),
195
+ /** Which way % Change is good news. */
196
+ better: z.enum(["higher", "lower"]).optional(),
197
+ /** `usd` only: "Not priced" when the row has no value but this column's is above 0. */
198
+ unpricedWhen: z.string().min(1).optional(),
199
+ ...shared
200
+ });
201
+ var changeColumnSchema = z.strictObject({
202
+ type: z.literal("change"),
203
+ description: z.string().optional()
204
+ });
205
+ var tableColumnOptionsSchema = z.discriminatedUnion("type", [
206
+ nameColumnSchema,
207
+ dimensionColumnSchema,
208
+ valueColumnSchema,
209
+ changeColumnSchema
210
+ ]);
211
+ function columnOf(id, label, options) {
212
+ switch (options.type) {
213
+ case "name": return {
214
+ id,
215
+ label,
216
+ options
217
+ };
218
+ case "dimension": return {
219
+ id,
220
+ label,
221
+ options
222
+ };
223
+ case "value": return {
224
+ id,
225
+ label,
226
+ options
227
+ };
228
+ case "change": return {
229
+ id,
230
+ label,
231
+ options
232
+ };
233
+ }
234
+ }
235
+ var tableOptionsSchema = z.strictObject({
236
+ /** The dimensions a row is keyed on; the last one names the row. */
237
+ groupBy: z.array(z.string().min(1)).min(1),
238
+ /** The starting sort, and where a third click on a header returns. */
239
+ defaultSort: z.strictObject({
240
+ column: z.string().min(1),
241
+ direction: z.enum(["asc", "desc"])
242
+ }),
243
+ /** Rows per page. Without it every row shows. */
244
+ pageSize: z.number().int().min(1).optional(),
245
+ emptyMessage: z.string(),
246
+ ariaLabel: z.string().optional(),
247
+ /** Leaves out rows without a name. */
248
+ hideUnnamed: z.boolean().optional(),
249
+ /** Lists groups active in the previous window but absent now, at zero. Defaults to on. */
250
+ dropped: z.boolean().optional(),
251
+ /** Opens on this view only once it has this many rows; otherwise on the next. */
252
+ openWhen: z.strictObject({ minRows: z.number().int().min(1) }).optional(),
253
+ /** What a row click adds to the view's `click` drilldown. */
254
+ rowDrilldown: z.strictObject({
255
+ /** Row dimension → drilldown field. Empty values are left out. */
256
+ fields: z.record(z.string(), z.enum([
257
+ "projectId",
258
+ "entityName",
259
+ "threadId",
260
+ "resourceId",
261
+ "environment",
262
+ "sessionId",
263
+ "userId",
264
+ "model",
265
+ "provider"
266
+ ])),
267
+ /** Set: `entityName` goes in as a filter on spans of these types. */
268
+ spanTypes: z.array(z.string().min(1)).min(1).optional(),
269
+ /** The row's name goes in even when empty. */
270
+ keepEmpty: z.boolean().optional()
271
+ }).optional()
272
+ });
273
+ /** The view's columns with their options parsed; `issues` reports what doesn't parse. */
274
+ function parseColumns(columns) {
275
+ const parsed = [];
276
+ const issues = [];
277
+ for (const [i, column] of (columns ?? []).entries()) {
278
+ const options = tableColumnOptionsSchema.safeParse(column.options ?? {});
279
+ if (!options.success) {
280
+ const issue = options.error.issues[0];
281
+ const path = issue?.path.length ? `.${issue.path.join(".")}` : "";
282
+ issues.push(`columns.${i}.options${path}: ${issue?.message ?? "invalid"}`);
283
+ continue;
284
+ }
285
+ parsed.push(columnOf(column.id, column.label ?? "", options.data));
286
+ }
287
+ return {
288
+ columns: parsed,
289
+ issues
290
+ };
291
+ }
292
+ var isValueColumn = (column) => column.options.type === "value";
293
+ /** What the schema can't say: columns that name each other and queries the view has. */
294
+ function tableIssues(columns, options, queries) {
295
+ const parsed = parseColumns(columns);
296
+ const issues = [...parsed.issues];
297
+ const byId = new Map(parsed.columns.map((c) => [c.id, c]));
298
+ if (!parsed.columns.filter(isValueColumn).length) issues.push("columns: a table needs a value column");
299
+ if (columns && !columns.some((c) => c.id === options.defaultSort.column)) issues.push(`options.defaultSort: no column '${options.defaultSort.column}'`);
300
+ const read = [];
301
+ for (const column of parsed.columns) {
302
+ const o = column.options;
303
+ if (o.type === "value") {
304
+ read.push(...exprRefs(o.value).map((r) => r.query));
305
+ if (o.unpricedWhen !== void 0 && !(byId.get(o.unpricedWhen)?.options.type === "value")) issues.push(`columns: '${column.id}' is unpriced by '${o.unpricedWhen}', which isn't a value column`);
306
+ }
307
+ if (o.type === "dimension") {
308
+ if (o.query === void 0 !== (o.joinOn === void 0)) issues.push(`columns: '${column.id}' needs both 'query' and 'joinOn', or neither`);
309
+ if (o.query !== void 0) read.push(o.query);
310
+ const own = o.joinOn ?? o.dimension;
311
+ if (!options.groupBy.includes(own)) issues.push(`columns: '${column.id}' reads '${own}', which rows aren't keyed on`);
312
+ }
313
+ }
314
+ issues.push(...unknownQueryIssues(read, queries, "columns"));
315
+ return issues;
316
+ }
317
+ // ../playground-ui/dist/domains/dashboards/lib/timeseries.es.js
318
+ var timeseriesSeriesSchema = z.object({
319
+ dataKey: z.string().min(1),
320
+ label: z.string().min(1),
321
+ color: colorSchema,
322
+ emphasis: z.boolean().optional(),
323
+ /** The series' value per bucket. */
324
+ value: valueExprSchema,
325
+ /** The series' value over the whole range, shown beside the card's title marked with the series' color. */
326
+ rangeTotal: valueExprSchema.optional(),
327
+ /** Rounds each bucket's value to a whole number. */
328
+ round: z.boolean().optional()
329
+ }).strict();
330
+ var timeseriesOptionsSchema = z.object({
331
+ chart: z.enum(["stackedBar", "line"]),
332
+ format: formatSchema,
333
+ /** `false` leaves the y-axis to the chart's default labels. */
334
+ axis: z.boolean().optional(),
335
+ series: z.array(timeseriesSeriesSchema).min(1),
336
+ /**
337
+ * `chart` re-buckets metrics onto the bar charts' grid (sums merge); `api` keeps the API's 1h or 1d
338
+ * buckets (percentiles and averages can't merge). Trace and span aggregates always keep the API's.
339
+ */
340
+ buckets: z.enum(["chart", "api"]).optional(),
341
+ /** Ids of queries sent over the whole range, without an interval (e.g. distinct counts, which can't be summed). */
342
+ totals: z.array(queryRefSchema).optional(),
343
+ /** Hides a series whose range total (or, without one, sum of buckets) is zero. */
344
+ hideEmpty: z.boolean().optional(),
345
+ /** Emphasizes the first series shown. */
346
+ emphasizeFirst: z.boolean().optional(),
347
+ xLabels: z.literal("edges").optional(),
348
+ /** The y-axis range when every plotted value is zero. */
349
+ flatYDomain: z.tuple([z.number(), z.number()]).optional(),
350
+ yDomain: z.tuple([z.number(), z.number()]).optional(),
351
+ /** The card's total, beside its title. Ignored when a series has a `rangeTotal`. */
352
+ total: z.object({
353
+ /** `total`: every series summed over the range; `peak`: one series' highest bucket; or an expression over range totals. */
354
+ value: z.union([
355
+ z.literal("total"),
356
+ z.object({ peak: z.string().min(1) }).strict(),
357
+ valueExprSchema
358
+ ]),
359
+ format: formatSchema.optional()
360
+ }).strict().optional(),
361
+ /** @deprecated Accepted so saved definitions still parse; every empty chart shows the same message. */
362
+ emptyMessage: z.string().optional(),
363
+ /** Empty when this is zero over the range; by default, when every plotted value is zero. */
364
+ emptyWhenZero: valueExprSchema.optional()
365
+ }).strict();
366
+ /** Aggregations whose values for several groups add up to the value for all of them. */
367
+ var ADDITIVE = /* @__PURE__ */ new Set(["sum", "count"]);
368
+ /**
369
+ * What the schema can't say: query ids the view has, bucketed queries that leave their interval to the
370
+ * chart's grid, refs that pick one of the percentiles their query asks for, and refs that pick one group
371
+ * of a grouped aggregation that can't be added up.
372
+ */
373
+ function timeseriesIssues(options, queries) {
374
+ const exprs = options.series.flatMap((s) => s.rangeTotal ? [s.value, s.rangeTotal] : [s.value]);
375
+ const total = options.total?.value;
376
+ if (total && total !== "total" && !("peak" in total)) exprs.push(total);
377
+ if (options.emptyWhenZero) exprs.push(options.emptyWhenZero);
378
+ const refs = exprs.flatMap(exprRefs);
379
+ const totals = new Set(options.totals ?? []);
380
+ const byId = new Map(queries.map((q) => [q.id, q]));
381
+ const ownIntervals = queries.filter((q) => q.id !== void 0 && !totals.has(q.id) && "interval" in q && q.interval !== void 0).map((q) => `query '${q.id}' sets its own interval; the chart's buckets follow the page's range`);
382
+ const ambiguousPercentiles = refs.filter((r) => {
383
+ const query = byId.get(r.query);
384
+ return r.percentile === void 0 && query !== void 0 && "request" in query && query.request === "percentiles" && query.percentiles.length > 1;
385
+ }).map((r) => `a value reading query '${r.query}' must pick one of its percentiles`);
386
+ const missingPercentiles = refs.filter((r) => {
387
+ const query = byId.get(r.query);
388
+ return r.percentile !== void 0 && query !== void 0 && "request" in query && query.request === "percentiles" && !query.percentiles.includes(r.percentile);
389
+ }).map((r) => `a value reading query '${r.query}' picks percentile ${r.percentile}, which the query doesn't ask for`);
390
+ const mixedGroups = refs.filter((r) => {
391
+ const query = byId.get(r.query);
392
+ return r.groups?.length !== 1 && query !== void 0 && "request" in query && query.request === "timeSeries" && (query.groupBy?.length ?? 0) > 0 && !ADDITIVE.has(query.aggregation);
393
+ }).map((r) => `a value reading query '${r.query}' must pick one group, since its groups' values can't be added up`);
394
+ return [
395
+ ...unknownQueryIssues(refs.map((r) => r.query), queries),
396
+ ...unknownQueryIssues(options.totals ?? [], queries, "options.totals"),
397
+ ...ownIntervals,
398
+ ...new Set(ambiguousPercentiles),
399
+ ...new Set(missingPercentiles),
400
+ ...new Set(mixedGroups)
401
+ ];
402
+ }
403
+ // ../playground-ui/dist/domains/dashboards/lib/chrome.es.js
404
+ /** A view's value in the card's menu: its label in kebab case (`Token usage` → `token-usage`), or its position when unlabelled or blank. */
405
+ var viewValue = (label, index) => {
406
+ const trimmed = label?.trim();
407
+ return trimmed ? trimmed.toLowerCase().replace(/\s+/g, "-") : String(index);
408
+ };
409
+ // src/dashboard-views.ts
410
+ /** How each built-in kind checks a view: the options it accepts, then what it checks beyond them. */
411
+ const KIND_CHECKS = {
412
+ kpis: {
413
+ optionsSchema: kpisOptionsSchema,
414
+ issues: kpisIssues
415
+ },
416
+ table: {
417
+ optionsSchema: tableOptionsSchema,
418
+ issues: (view) => tableIssues(view.columns, view.options, view.queries)
419
+ },
420
+ timeseries: {
421
+ optionsSchema: timeseriesOptionsSchema,
422
+ issues: (view) => timeseriesIssues(view.options, view.queries)
423
+ },
424
+ scores: {
425
+ optionsSchema: scoresOptionsSchema,
426
+ issues: scoresIssues
427
+ }
428
+ };
429
+ /** Whether a widget, view or column tagged with `scope` shows at the page's scope. */
430
+ const inScope = (item, scope) => item.scope === void 0 || item.scope === scope;
431
+ /**
432
+ * What the renderer rejects in the widget's views at `scope`, in the order it finds them: options
433
+ * parsed, then the kind's own issues, then labels unique. Takes a widget core's schema accepts.
434
+ * Views in `skipKindChecks` skip the kind's own issues, for callers that already report them.
435
+ */
436
+ function viewIssues(widget, check, scope, skipKindChecks = /* @__PURE__ */ new Set()) {
437
+ const issues = [];
438
+ const values = /* @__PURE__ */ new Set();
439
+ let shown = 0;
440
+ for (const [index, view] of widget.views.entries()) {
441
+ if (!inScope(view, scope)) continue;
442
+ const value = viewValue(view.label, shown++);
443
+ const repeated = values.has(value);
444
+ values.add(value);
445
+ const options = check.optionsSchema.safeParse(view.options ?? {});
446
+ if (!options.success) {
447
+ const found = options.error.issues.length ? options.error.issues : [{
448
+ path: [],
449
+ message: "Invalid options"
450
+ }];
451
+ issues.push(...found.map((issue) => ({
452
+ path: [
453
+ "views",
454
+ index,
455
+ "options",
456
+ ...issue.path
457
+ ],
458
+ message: issue.message
459
+ })));
460
+ continue;
461
+ }
462
+ const resolved = {
463
+ ...view,
464
+ columns: view.columns?.filter((c) => inScope(c, scope)),
465
+ options: options.data
466
+ };
467
+ if (!skipKindChecks.has(index)) issues.push(...(check.issues?.(resolved) ?? []).map((message) => ({
468
+ path: ["views", index],
469
+ message
470
+ })));
471
+ if (repeated) issues.push({
472
+ path: ["views", index],
473
+ message: `another view is already labelled '${view.label ?? value}'`
474
+ });
475
+ }
476
+ return issues;
477
+ }
478
+ const isBuiltInKind = (kind) => Object.hasOwn(KIND_CHECKS, kind);
479
+ const zodIssues = (error, prefix) => error.issues.map((issue) => ({
480
+ path: [...prefix, ...issue.path],
481
+ message: issue.message
482
+ }));
483
+ /**
484
+ * What the renderer would reject in a widget core accepts, paths relative to the widget. Every
485
+ * view's options and columns are parsed; the kind's own checks then run at each scope the widget
486
+ * shows at, as the renderer runs them there, skipping views whose options or columns don't parse.
487
+ * All problems come back together. It also rejects columns on views that aren't tables, which the
488
+ * renderer ignores.
489
+ */
490
+ function widgetIssues(widget) {
491
+ if (!isBuiltInKind(widget.kind)) return [{
492
+ path: ["kind"],
493
+ message: `Unknown widget kind '${widget.kind}'; expected one of ${DASHBOARD_WIDGET_KINDS.join(", ")}`
494
+ }];
495
+ const check = KIND_CHECKS[widget.kind];
496
+ const issues = /* @__PURE__ */ new Map();
497
+ const add = (found) => {
498
+ for (const issue of found) issues.set(`${JSON.stringify(issue.path)} ${issue.message}`, issue);
499
+ };
500
+ const badColumns = /* @__PURE__ */ new Set();
501
+ for (const [i, view] of widget.views.entries()) {
502
+ const options = check.optionsSchema.safeParse(view.options ?? {});
503
+ if (!options.success) add(zodIssues(options.error, [
504
+ "views",
505
+ i,
506
+ "options"
507
+ ]));
508
+ if (!view.columns) continue;
509
+ if (widget.kind !== "table") {
510
+ add([{
511
+ path: [
512
+ "views",
513
+ i,
514
+ "columns"
515
+ ],
516
+ message: "Only table widgets have columns"
517
+ }]);
518
+ continue;
519
+ }
520
+ for (const [m, column] of view.columns.entries()) {
521
+ const columnOptions = tableColumnOptionsSchema.safeParse(column.options ?? {});
522
+ if (!columnOptions.success) {
523
+ add(zodIssues(columnOptions.error, [
524
+ "views",
525
+ i,
526
+ "columns",
527
+ m,
528
+ "options"
529
+ ]));
530
+ badColumns.add(i);
531
+ }
532
+ }
533
+ }
534
+ for (const scope of DASHBOARD_SCOPES) if (inScope(widget, scope)) add(viewIssues(widget, check, scope, badColumns));
535
+ return [...issues.values()];
536
+ }
537
+ // src/observability-dashboard.ts
538
+ const report = (context, issues, path = []) => {
539
+ for (const message of issues) context.addIssue({
540
+ code: "custom",
541
+ path,
542
+ message
543
+ });
544
+ };
545
+ const keysList = (keys) => keys.map((key) => `\`${key}\``).join(", ");
546
+ /** The keys of `value` among `keys` that hold something. */
547
+ const keysIn = (value, keys) => keys.filter((key) => value[key] !== void 0);
548
+ /**
549
+ * Whether exactly one of `keys` holds the case's fields, reporting it when not. Checked before the
550
+ * cases are parsed, so a missing or extra case is reported as such rather than as each case's
551
+ * errors. The keys named are the cases given, or, with none, the keys `fields` doesn't have: a
552
+ * read written where it isn't allowed.
553
+ */
554
+ const hasOneKey = (input, keys, fields, what, context) => {
555
+ const given = keysIn(input, keys);
556
+ if (given.length === 1) return true;
557
+ const wrong = given.length ? given : Object.keys(input).filter((key) => !fields.includes(key));
558
+ context.addIssue({
559
+ code: "custom",
560
+ path: given.slice(1),
561
+ message: `${what} takes exactly one of ${keysList(keys)}${wrong.length ? `, not ${keysList(wrong)}` : ""}`
562
+ });
563
+ return false;
564
+ };
565
+ /**
566
+ * `schema`, an object with one optional key per case, parsed only once exactly one of `keys` holds
567
+ * the case's fields. Typed as `T`, the union of one-key objects that check leaves.
568
+ */
569
+ const oneKeyOf = (keys, what, schema) => {
570
+ const fields = Object.keys(schema.shape);
571
+ return z.preprocess((input, context) => {
572
+ if (!input || typeof input !== "object" || hasOneKey(input, keys, fields, what, context)) return input;
573
+ return z.NEVER;
574
+ }, schema);
575
+ };
576
+ /** The fields of an object schema, without `omit`. */
577
+ const fieldsOf = (schema, omit) => Object.fromEntries(Object.entries(schema.shape).filter(([key]) => !omit.includes(key)));
578
+ /** Canonical JSON: the same for objects that differ only in key order. */
579
+ const canonical = (value) => JSON.stringify(value, (_, v) => v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a.localeCompare(b))) : v);
580
+ /** Past this many, metric names stay free strings: a longer list costs more than it guides. */
581
+ const OBSERVABILITY_CATALOG_MAX_METRIC_NAMES = 200;
582
+ const METRIC_NAME_DESCRIPTION = [
583
+ "A metric name. Mastra emits `mastra_agent_duration_ms`, `mastra_workflow_duration_ms`, `mastra_tool_duration_ms`,",
584
+ "`mastra_model_duration_ms` and `mastra_processor_duration_ms` (one row per run or call, labelled `status` `ok` or",
585
+ "`error`: `count` them for runs, take percentiles for latency); `mastra_model_total_input_tokens` and",
586
+ "`mastra_model_total_output_tokens` (`sum` them for tokens; read `field: \"estimatedCost\"` for the price), plus",
587
+ "per-type token metrics such as `mastra_model_input_cache_read_tokens` and `mastra_model_output_reasoning_tokens`.",
588
+ "Projects can emit their own metrics too."
589
+ ].join(" ");
590
+ const READS = {
591
+ traceAggregate: { source: "traceAggregate" },
592
+ spanAggregate: { source: "spanAggregate" },
593
+ metricAggregate: {
594
+ source: "metrics",
595
+ request: "aggregate"
596
+ },
597
+ metricBreakdown: {
598
+ source: "metrics",
599
+ request: "breakdown"
600
+ },
601
+ metricTimeSeries: {
602
+ source: "metrics",
603
+ request: "timeSeries"
604
+ },
605
+ metricPercentiles: {
606
+ source: "metrics",
607
+ request: "percentiles"
608
+ }
609
+ };
610
+ /** What each place a value sits can read. */
611
+ const CHART_READS = [
612
+ "metricTimeSeries",
613
+ "metricPercentiles",
614
+ "traceAggregate",
615
+ "spanAggregate"
616
+ ];
617
+ const RANGE_READS = [...CHART_READS, "metricAggregate"];
618
+ const TABLE_READS = [
619
+ "traceAggregate",
620
+ "spanAggregate",
621
+ "metricBreakdown"
622
+ ];
623
+ const KPI_READS = ["metricAggregate"];
624
+ /** The fields of a read that pick a number out of its answer rather than change the request. */
625
+ const PICKS = [
626
+ "measure",
627
+ "percentile",
628
+ "field",
629
+ "groups",
630
+ "notGroups"
631
+ ];
632
+ const isTraceRead = (key) => key === "traceAggregate" || key === "spanAggregate";
633
+ /**
634
+ * `query`'s `filters`, named, so JSON Schema lists them once rather than at every read. Every
635
+ * metrics query takes the same filters, as does every scores query. The name goes on the optional
636
+ * field rather than the object inside it: provider compatibility layers (`@mastra/schema-compat`)
637
+ * empty a `$ref` they find wrapped in an optional.
638
+ */
639
+ const namedFilters = (query, id) => ({ filters: query.shape.filters.meta({ id }) });
640
+ /** Each read's arguments, with metric names limited to `metricNames` when given. */
641
+ const readSchemas = (metricNames) => {
642
+ const [traceAggregate, spanAggregate, metrics] = dashboardQuerySchema.out.options;
643
+ const [metricAggregate, metricBreakdown, metricTimeSeries, metricPercentiles] = metrics.options;
644
+ const metricName = (metricNames ? z.enum(metricNames) : z.string().min(1)).meta({
645
+ id: "MastraMetricName",
646
+ description: METRIC_NAME_DESCRIPTION
647
+ });
648
+ const names = { name: z.array(metricName).nonempty() };
649
+ const filters = namedFilters(metricAggregate, "MastraMetricFilters");
650
+ const { field, groups, notGroups, percentile } = valueRefSchema.shape;
651
+ const picks = {
652
+ field: field.describe("`value`, or `estimatedCost` for the price. Defaults to `value`."),
653
+ groups: groups.describe("Only the groups whose key is exactly one of these."),
654
+ notGroups: notGroups.describe("Only the groups whose key is none of these."),
655
+ percentile: percentile.unwrap().describe("The percentile to read, e.g. `0.95`.")
656
+ };
657
+ const omit = [
658
+ "source",
659
+ "request",
660
+ "id",
661
+ "interval"
662
+ ];
663
+ const measures = traceAggregate.shape.measures;
664
+ const traceRead = (source, query) => guardPredicates(source, z.strictObject({
665
+ ...fieldsOf(query, [
666
+ ...omit,
667
+ "measures",
668
+ "having",
669
+ "orderBy"
670
+ ]),
671
+ measure: measures.element.optional().describe("The measure this value reads. Defaults to `count`."),
672
+ groups: picks.groups,
673
+ notGroups: picks.notGroups
674
+ }));
675
+ const grouped = (query) => query.shape.groupBy.optional().describe("The dimensions to group by. In a table, defaults to the table's `groupBy`.");
676
+ return named({
677
+ traceAggregate: traceRead("traceAggregate", traceAggregate),
678
+ spanAggregate: traceRead("spanAggregate", spanAggregate),
679
+ metricAggregate: z.strictObject({
680
+ ...fieldsOf(metricAggregate, omit),
681
+ ...names,
682
+ ...filters,
683
+ field: picks.field
684
+ }),
685
+ metricBreakdown: z.strictObject({
686
+ ...fieldsOf(metricBreakdown, omit),
687
+ ...names,
688
+ ...filters,
689
+ groupBy: grouped(metricBreakdown),
690
+ field: picks.field
691
+ }),
692
+ metricTimeSeries: z.strictObject({
693
+ ...fieldsOf(metricTimeSeries, omit),
694
+ ...names,
695
+ ...filters,
696
+ field: picks.field,
697
+ groups: picks.groups,
698
+ notGroups: picks.notGroups
699
+ }),
700
+ metricPercentiles: z.strictObject({
701
+ ...fieldsOf(metricPercentiles, [...omit, "percentiles"]),
702
+ ...filters,
703
+ name: metricName,
704
+ percentile: picks.percentile
705
+ })
706
+ });
707
+ };
708
+ /** `schemas`, each named, so JSON Schema lists a read's arguments once rather than at every value. */
709
+ const named = (schemas) => Object.fromEntries(Object.entries(schemas).map(([key, schema]) => [key, schema.meta({ id: `Mastra${key[0].toUpperCase()}${key.slice(1)}Read` })]));
710
+ /** `schema`, with an oversized `where` rejected before zod recurses into it, as the definition does. */
711
+ const guardPredicates = (source, schema) => z.preprocess((input, context) => {
712
+ if (!input || typeof input !== "object") return input;
713
+ const guarded = z.safeParse(dashboardQuerySchema.in, {
714
+ source,
715
+ ...input
716
+ });
717
+ if (guarded.success) return input;
718
+ for (const issue of guarded.error.issues) context.addIssue({
719
+ ...issue,
720
+ code: "custom"
721
+ });
722
+ return z.NEVER;
723
+ }, schema);
724
+ const OPERATORS = [
725
+ "const",
726
+ "sum",
727
+ "minus",
728
+ "ratio",
729
+ "max",
730
+ "coalesce"
731
+ ];
732
+ /** The keys of a value column that hold its number rather than its options. */
733
+ const TABLE_VALUE_KEYS = [...TABLE_READS, ...OPERATORS];
734
+ /**
735
+ * The keys a value takes, one of which it sets: each read among `reads` holding its arguments, and
736
+ * each operator over `self`, the value nested inside it. `sumOnly` leaves `sum` as the one operator.
737
+ */
738
+ const valueCases = (schemas, reads, self, sumOnly = false) => {
739
+ const operators = sumOnly ? ["sum"] : OPERATORS;
740
+ const parts = (description) => z.array(self).min(1).optional().describe(description);
741
+ return {
742
+ keys: [...reads, ...operators],
743
+ summary: `a read (${keysList(reads)}) holding its arguments, or ${sumOnly ? "`sum`" : `an operator (${keysList(operators)})`} over values. Reads that differ only in ${keysList(PICKS)} share one request.`,
744
+ shape: {
745
+ ...Object.fromEntries(reads.map((key) => [key, schemas[key].optional()])),
746
+ sum: parts("The parts added up; a missing part counts as 0."),
747
+ ...sumOnly ? {} : {
748
+ const: z.number().optional(),
749
+ minus: z.tuple([self, self]).optional().describe("The first minus the second."),
750
+ ratio: z.strictObject({
751
+ of: self,
752
+ over: self
753
+ }).optional().describe("`of / over`; no value when `over` is 0."),
754
+ max: parts("The largest part that has a value."),
755
+ coalesce: parts("The first part that has a value.")
756
+ }
757
+ }
758
+ };
759
+ };
760
+ /** A value: exactly one key, a read among `reads` or an operator over values. */
761
+ const valueSchema = (schemas, reads, id, description, sumOnly = false) => {
762
+ const cases = valueCases(schemas, reads, z.lazy(() => value), sumOnly);
763
+ const value = oneKeyOf(cases.keys, "A value", z.strictObject(cases.shape)).meta({
764
+ id,
765
+ description: `${description} Exactly one key: ${cases.summary}`
766
+ });
767
+ return value;
768
+ };
769
+ /** The view's reads, gathered into one query each, so identical reads are sent once. */
770
+ var Reads = class {
771
+ constructor() {
772
+ this.queries = [];
773
+ this.wholeRange = [];
774
+ this.#byIdentity = /* @__PURE__ */ new Map();
775
+ }
776
+ #byIdentity;
777
+ /**
778
+ * The ref reading `read` placed in `place`: `range` sends a trace or span aggregate over the whole
779
+ * range; `table` groups it by `groupBy` unless it sets its own.
780
+ */
781
+ ref(read, place, groupBy) {
782
+ const [key] = keysIn(read, Object.keys(READS));
783
+ const { measure, percentile, field, groups, notGroups, ...args } = read[key];
784
+ const trace = isTraceRead(key);
785
+ if (groupBy && (trace || key === "metricBreakdown") && args.groupBy === void 0) args.groupBy = groupBy;
786
+ const whole = trace && place === "range";
787
+ const identity = canonical([
788
+ key,
789
+ whole,
790
+ args
791
+ ]);
792
+ let query = this.#byIdentity.get(identity);
793
+ if (!query) {
794
+ query = {
795
+ ...READS[key],
796
+ id: `q${this.queries.length + 1}`,
797
+ ...args,
798
+ ...trace ? { measures: [] } : {},
799
+ ...percentile === void 0 ? {} : { percentiles: [] }
800
+ };
801
+ this.#byIdentity.set(identity, query);
802
+ this.queries.push(query);
803
+ if (whole) this.wholeRange.push(query.id);
804
+ }
805
+ const ref = { query: query.id };
806
+ if (trace) {
807
+ ref.measure = measure ?? "count";
808
+ if (!query.measures.includes(ref.measure)) query.measures.push(ref.measure);
809
+ }
810
+ if (percentile !== void 0) {
811
+ ref.percentile = percentile;
812
+ if (!query.percentiles.includes(percentile)) query.percentiles.push(percentile);
813
+ }
814
+ if (field !== void 0) ref.field = field;
815
+ if (groups !== void 0) ref.groups = groups;
816
+ if (notGroups !== void 0) ref.notGroups = notGroups;
817
+ return ref;
818
+ }
819
+ /** `value` with each read turned into a ref. */
820
+ expr(value, place, groupBy) {
821
+ const recurse = (v) => this.expr(v, place, groupBy);
822
+ if ("const" in value) return { const: value.const };
823
+ if ("sum" in value) return { sum: value.sum.map(recurse) };
824
+ if ("minus" in value) return { minus: [recurse(value.minus[0]), recurse(value.minus[1])] };
825
+ if ("ratio" in value) return { ratio: {
826
+ of: recurse(value.ratio.of),
827
+ over: recurse(value.ratio.over)
828
+ } };
829
+ if ("max" in value) return { max: value.max.map(recurse) };
830
+ if ("coalesce" in value) return { coalesce: value.coalesce.map(recurse) };
831
+ return this.ref(value, place, groupBy);
832
+ }
833
+ /** The queries, a trace or span aggregate no value reads a measure of counting rows. */
834
+ done() {
835
+ for (const query of this.queries) if ("measures" in query && query.measures?.length === 0) query.measures = ["count"];
836
+ return this.queries;
837
+ }
838
+ };
839
+ const WIDGET_KINDS = [
840
+ "kpis",
841
+ "timeseries",
842
+ "table",
843
+ "scores"
844
+ ];
845
+ const COLUMN_TYPES = tableColumnOptionsSchema.options.map((option) => option.shape.type.value);
846
+ const viewBase = ({ label, description }) => ({
847
+ ...label === void 0 ? {} : { label },
848
+ ...description === void 0 ? {} : { description }
849
+ });
850
+ const toKpisView = (draft) => {
851
+ const { label: _l, description: _d, tabs: _t, items, ...options } = draft;
852
+ const reads = new Reads();
853
+ const converted = items.map(({ value, ...item }) => ({
854
+ ...item,
855
+ value: reads.expr(value, "range")
856
+ }));
857
+ return {
858
+ ...viewBase(draft),
859
+ queries: reads.done(),
860
+ options: {
861
+ ...options,
862
+ items: converted
863
+ }
864
+ };
865
+ };
866
+ const toTimeseriesView = (draft) => {
867
+ const { label: _l, description: _d, tabs: _t, series, total, emptyWhenZero, ...options } = draft;
868
+ const reads = new Reads();
869
+ const converted = series.map(({ value, rangeTotal, ...line }, i) => ({
870
+ ...line,
871
+ dataKey: `series${i + 1}`,
872
+ value: reads.expr(value, "bucket"),
873
+ ...rangeTotal === void 0 ? {} : { rangeTotal: reads.expr(rangeTotal, "range") }
874
+ }));
875
+ const peaked = converted.find((line) => line.emphasis) ?? converted[0];
876
+ const totalValue = total === void 0 ? void 0 : total.value === "total" ? "total" : total.value === "peak" ? { peak: peaked.dataKey } : reads.expr(total.value, "range");
877
+ return {
878
+ ...viewBase(draft),
879
+ queries: reads.done(),
880
+ options: {
881
+ ...options,
882
+ series: converted,
883
+ ...total === void 0 ? {} : { total: {
884
+ ...total,
885
+ value: totalValue
886
+ } },
887
+ ...emptyWhenZero === void 0 ? {} : { emptyWhenZero: reads.expr(emptyWhenZero, "range") },
888
+ ...reads.wholeRange.length ? { totals: reads.wholeRange } : {}
889
+ }
890
+ };
891
+ };
892
+ const columnIds = (columns) => columns.map((column, i) => column.id ?? `column${i + 1}`);
893
+ const columnType = (column) => keysIn(column, COLUMN_TYPES)[0];
894
+ const toTableView = (draft) => {
895
+ const { label: _l, description: _d, tabs: _t, columns, ...options } = draft;
896
+ const reads = new Reads();
897
+ const ids = columnIds(columns);
898
+ const converted = columns.map((column, i) => {
899
+ const type = columnType(column);
900
+ const body = column[type];
901
+ let typed = body;
902
+ if (type === "value") {
903
+ const entries = Object.entries(body);
904
+ const isValueKey = ([key]) => TABLE_VALUE_KEYS.includes(key);
905
+ typed = {
906
+ ...Object.fromEntries(entries.filter((entry) => !isValueKey(entry))),
907
+ value: reads.expr(Object.fromEntries(entries.filter(isValueKey)), "table", options.groupBy)
908
+ };
909
+ }
910
+ return {
911
+ id: ids[i],
912
+ ...column.label === void 0 ? {} : { label: column.label },
913
+ options: {
914
+ type,
915
+ ...typed
916
+ }
917
+ };
918
+ });
919
+ const sorted = columns.findIndex((column) => column.sort !== void 0);
920
+ const values = columns.flatMap((column, i) => columnType(column) === "value" ? [i] : []);
921
+ const sortBy = sorted >= 0 ? sorted : values.find((i) => columns[i].value.emphasis) ?? values[0];
922
+ return {
923
+ ...viewBase(draft),
924
+ queries: reads.done(),
925
+ columns: converted,
926
+ options: {
927
+ ...options,
928
+ defaultSort: {
929
+ column: ids[sortBy],
930
+ direction: columns[sorted]?.sort ?? "desc"
931
+ }
932
+ }
933
+ };
934
+ };
935
+ const toScoresView = (draft) => {
936
+ const { label: _l, description: _d, tabs: _t, scorerId, scoreSource, average, series, ...options } = draft;
937
+ const scorer = {
938
+ ...scorerId === void 0 ? {} : { scorerId },
939
+ ...scoreSource === void 0 ? {} : { scoreSource }
940
+ };
941
+ return {
942
+ ...viewBase(draft),
943
+ queries: [{
944
+ id: "average",
945
+ source: "scores",
946
+ request: "aggregate",
947
+ ...scorer,
948
+ ...average
949
+ }, {
950
+ id: "series",
951
+ source: "scores",
952
+ request: "timeSeries",
953
+ ...scorer,
954
+ ...series
955
+ }],
956
+ options: {
957
+ ...options,
958
+ average: "average",
959
+ series: "series"
960
+ }
961
+ };
962
+ };
963
+ const TO_VIEW = {
964
+ kpis: toKpisView,
965
+ timeseries: toTimeseriesView,
966
+ table: toTableView,
967
+ scores: toScoresView
968
+ };
969
+ const toWidget = (draft) => {
970
+ const { kpis, timeseries, table, scores, ...widget } = draft;
971
+ const kind = keysIn({
972
+ kpis,
973
+ timeseries,
974
+ table,
975
+ scores
976
+ }, WIDGET_KINDS)[0];
977
+ const first = {
978
+ kpis,
979
+ timeseries,
980
+ table,
981
+ scores
982
+ }[kind];
983
+ const views = [first, ...first.tabs ?? []].map((view) => TO_VIEW[kind](view));
984
+ return {
985
+ ...widget,
986
+ id: widget.id ?? crypto.randomUUID(),
987
+ span: widget.span ?? FULL_WIDTH,
988
+ kind,
989
+ views
990
+ };
991
+ };
992
+ /** What the draft can say wrong that its schema can't: a table's sort and its `unpricedWhen` column. */
993
+ const tableDraftIssues = (draft, context) => {
994
+ const before = context.issues.length;
995
+ const { columns } = draft;
996
+ const ids = columnIds(columns);
997
+ const valueIds = columns.flatMap((column, i) => columnType(column) === "value" ? [ids[i]] : []);
998
+ if (!valueIds.length) report(context, ["A table needs at least one `value` column"], ["columns"]);
999
+ const sorted = columns.flatMap((column, i) => column.sort === void 0 ? [] : [i]);
1000
+ if (sorted.length > 1) report(context, ["At most one column sets `sort`; without one, the table sorts by its emphasized value column"], [
1001
+ "columns",
1002
+ sorted[1],
1003
+ "sort"
1004
+ ]);
1005
+ const seen = /* @__PURE__ */ new Set();
1006
+ ids.forEach((id, i) => {
1007
+ if (seen.has(id)) report(context, [`Duplicate column id '${id}'`], [
1008
+ "columns",
1009
+ i,
1010
+ "id"
1011
+ ]);
1012
+ seen.add(id);
1013
+ });
1014
+ columns.forEach((column, i) => {
1015
+ const unpricedWhen = column.value?.unpricedWhen;
1016
+ if (unpricedWhen === void 0 || valueIds.includes(unpricedWhen) && unpricedWhen !== ids[i]) return;
1017
+ report(context, [`unpricedWhen names column '${unpricedWhen}', which is not another value column; value column ids are ${keysList(valueIds.filter((id) => id !== ids[i]))}`], [
1018
+ "columns",
1019
+ i,
1020
+ "value",
1021
+ "unpricedWhen"
1022
+ ]);
1023
+ });
1024
+ return context.issues.length === before;
1025
+ };
1026
+ const FULL_WIDTH = 12;
1027
+ const SPAN_DESCRIPTION = "Columns of a 12-column row, one of 1, 2, 3, 4, 6 or 12: 12 is the full width, 6 half, 4 a third, 3 a quarter. Left out, the full width.";
1028
+ /**
1029
+ * What the renderer rejects across a widget's views, such as two tabs with one label, reported at
1030
+ * the view in the draft. Checked once the draft's own fields pass, on the widget they convert to.
1031
+ */
1032
+ const widgetDraftIssues = (draft, context) => {
1033
+ if (context.issues.length) return;
1034
+ const widget = toWidget(draft);
1035
+ for (const { path, message } of widgetIssues(widget)) {
1036
+ const [, view, ...rest] = path[0] === "views" ? path : [
1037
+ void 0,
1038
+ void 0,
1039
+ ...path
1040
+ ];
1041
+ const at = view === void 0 ? [] : view === 0 ? [widget.kind] : [
1042
+ widget.kind,
1043
+ "tabs",
1044
+ view - 1
1045
+ ];
1046
+ context.addIssue({
1047
+ code: "custom",
1048
+ path: at,
1049
+ message: rest.length ? `${rest.join(".")}: ${message}` : message
1050
+ });
1051
+ }
1052
+ };
1053
+ /**
1054
+ * The schemas a model writes a widget (`widget`) or a dashboard (`dashboard`) with, metric names
1055
+ * limited to `catalog.metricNames` as `createObservabilityDashboardInputSchema` limits them, and
1056
+ * only the choices `options` allows: a kind or `defaults.filters` left out is missing from their
1057
+ * JSON schema too. Both share their named parts, so build them once per catalog and use both from
1058
+ * the result, for example as the input of a tool that saves a widget and one that saves a dashboard.
1059
+ * Convert a draft with `toObservabilityWidget` or `toObservabilityDashboard`.
1060
+ */
1061
+ function createObservabilityDraftSchemas(catalog = {}, options = {}) {
1062
+ const kinds = options.kinds ? WIDGET_KINDS.filter((kind) => options.kinds.includes(kind)) : WIDGET_KINDS;
1063
+ if (!kinds.length) throw new Error("`kinds` must name at least one widget kind");
1064
+ const metricNames = [...new Set(catalog.metricNames)].sort();
1065
+ const listed = metricNames.length > 0 && metricNames.length <= 200;
1066
+ const reads = readSchemas(listed ? metricNames : void 0);
1067
+ const chartValue = valueSchema(reads, CHART_READS, "MastraChartValue", "A series' number per bucket of the chart.");
1068
+ const rangeValue = valueSchema(reads, RANGE_READS, "MastraRangeValue", "A number over the whole range.");
1069
+ const tableValue = valueSchema(reads, TABLE_READS, "MastraTableValue", "A row's number: its reads are grouped by the table's `groupBy` unless they set their own.");
1070
+ const tableCases = valueCases(reads, TABLE_READS, tableValue);
1071
+ const kpiValue = valueSchema(reads, KPI_READS, "MastraKpiValue", "A KPI figure: one aggregate or the sum of several.", true);
1072
+ const { label, description } = dashboardWidgetViewSchema.shape;
1073
+ const viewOf = (kind, shape, draftIssues, kindIssues) => z.strictObject({
1074
+ label,
1075
+ description,
1076
+ ...shape
1077
+ }).superRefine((draft, context) => {
1078
+ if (!draftIssues(draft, context)) return;
1079
+ const view = TO_VIEW[kind](draft);
1080
+ if (view.queries.length > DASHBOARD_MAX_QUERIES_PER_VIEW) return report(context, [`This view sends ${view.queries.length} requests, past the ${DASHBOARD_MAX_QUERIES_PER_VIEW} a view can send. Reads that differ only in ${keysList(PICKS)} share one.`]);
1081
+ const checked = dashboardWidgetViewSchema.safeParse(view);
1082
+ if (!checked.success) return report(context, checked.error.issues.map((issue) => issue.message));
1083
+ report(context, [...new Set(kindIssues(view))]);
1084
+ });
1085
+ const kpiItem = kpisOptionsSchema.shape.items.element;
1086
+ const kpis = viewOf("kpis", { items: z.array(z.strictObject({
1087
+ ...fieldsOf(kpiItem, ["value"]),
1088
+ value: kpiValue
1089
+ })).min(1).describe("One figure each, compared with the window before when its reads set `compare`.") }, () => true, (view) => kpisIssues(view));
1090
+ const { total: storedTotal } = timeseriesOptionsSchema.shape;
1091
+ const timeseries = viewOf("timeseries", {
1092
+ ...fieldsOf(timeseriesOptionsSchema, [
1093
+ "series",
1094
+ "totals",
1095
+ "total",
1096
+ "emptyWhenZero"
1097
+ ]),
1098
+ series: z.array(z.strictObject({
1099
+ ...fieldsOf(timeseriesSeriesSchema, [
1100
+ "dataKey",
1101
+ "value",
1102
+ "rangeTotal"
1103
+ ]),
1104
+ value: chartValue,
1105
+ rangeTotal: rangeValue.optional().describe("The series' number over the whole range, shown beside the card's title.")
1106
+ })).min(1),
1107
+ total: z.strictObject({
1108
+ value: z.union([z.enum(["total", "peak"]), rangeValue]).describe("`total`: every series summed over the range; `peak`: the highest bucket of the emphasized series (the first, when none is); or a number over the range."),
1109
+ format: storedTotal.unwrap().shape.format
1110
+ }).optional().describe("The card's total, beside its title. Ignored when a series has a `rangeTotal`."),
1111
+ emptyWhenZero: rangeValue.optional().describe("Empty when this is zero over the range; by default, when every plotted value is zero.")
1112
+ }, () => true, (view) => timeseriesIssues(view.options, view.queries));
1113
+ const columnOptions = Object.fromEntries(tableColumnOptionsSchema.options.map((option) => [option.shape.type.value, option]));
1114
+ const column = oneKeyOf(COLUMN_TYPES, "A column", z.strictObject({
1115
+ id: z.string().min(1).optional().describe("Needed only for another column's `unpricedWhen` to name it."),
1116
+ label: z.string().optional(),
1117
+ sort: z.enum(["asc", "desc"]).optional().describe("Sorts the table by this column. Without one, it sorts by its emphasized value column, descending."),
1118
+ name: z.strictObject(fieldsOf(columnOptions.name, ["type"])).optional(),
1119
+ dimension: z.strictObject(fieldsOf(columnOptions.dimension, [
1120
+ "type",
1121
+ "query",
1122
+ "joinOn"
1123
+ ])).optional(),
1124
+ value: oneKeyOf(tableCases.keys, "A value column", z.strictObject({
1125
+ ...fieldsOf(columnOptions.value, ["type", "value"]),
1126
+ unpricedWhen: columnOptions.value.shape.unpricedWhen.describe("`usd` only: the `id` of the column whose value above 0 makes a missing price read \"Not priced\"."),
1127
+ ...tableCases.shape
1128
+ })).optional().describe(`The column's options beside the row's number, written as one key: ${tableCases.summary} Its reads are grouped by the table's \`groupBy\` unless they set their own.`),
1129
+ change: z.strictObject(fieldsOf(columnOptions.change, ["type"])).optional().describe("The emphasized value's % change against the window before; its reads set `compare`.")
1130
+ })).describe(`Exactly one of ${keysList(COLUMN_TYPES)} names the column's type and holds its options.`);
1131
+ const table = viewOf("table", {
1132
+ ...fieldsOf(tableOptionsSchema, ["defaultSort", "rowDrilldown"]),
1133
+ columns: z.array(column).min(1)
1134
+ }, tableDraftIssues, (view) => tableIssues(view.columns, view.options, view.queries));
1135
+ const [scoreAggregate, , scoreTimeSeries] = dashboardQuerySchema.out.options[3].options;
1136
+ const { scorerId, scoreSource } = scoreAggregate.shape;
1137
+ const scoreFilters = namedFilters(scoreAggregate, "MastraScoreFilters");
1138
+ const views = {
1139
+ kpis,
1140
+ timeseries,
1141
+ table,
1142
+ scores: viewOf("scores", {
1143
+ ...fieldsOf(scoresOptionsSchema, ["average", "series"]),
1144
+ scorerId,
1145
+ scoreSource,
1146
+ average: z.strictObject({
1147
+ ...fieldsOf(scoreAggregate, [
1148
+ "source",
1149
+ "request",
1150
+ "id",
1151
+ "interval",
1152
+ "scorerId",
1153
+ "scoreSource"
1154
+ ]),
1155
+ ...scoreFilters
1156
+ }).describe("Each scorer's mean over the range."),
1157
+ series: z.strictObject({
1158
+ ...fieldsOf(scoreTimeSeries, [
1159
+ "source",
1160
+ "request",
1161
+ "id",
1162
+ "interval",
1163
+ "scorerId",
1164
+ "scoreSource"
1165
+ ]),
1166
+ ...scoreFilters
1167
+ }).describe("Each scorer's line over time.")
1168
+ }, () => true, (view) => scoresIssues(view))
1169
+ };
1170
+ const { span, title, description: widgetDescription } = dashboardWidgetSchema.shape;
1171
+ const widget = oneKeyOf(kinds, "A widget", z.strictObject({
1172
+ id: dashboardWidgetSchema.shape.id.optional().describe("Left out, the server assigns one."),
1173
+ span: span.optional().describe(SPAN_DESCRIPTION),
1174
+ title,
1175
+ description: widgetDescription,
1176
+ ...Object.fromEntries(kinds.map((kind) => [kind, views[kind].safeExtend({ tabs: z.array(views[kind]).optional().describe("Further views of this kind, drawn as tabs after this one. Leave out for one view.") }).optional()]))
1177
+ }).superRefine((draft, context) => widgetDraftIssues(draft, context))).describe(`Exactly one of ${keysList(kinds)} names the widget's kind and holds its view.`);
1178
+ const { datePreset } = dashboardDefaultsSchema.shape;
1179
+ const defaults = options.dashboardFilters === false ? z.strictObject({ datePreset }) : dashboardDefaultsSchema;
1180
+ return {
1181
+ widget,
1182
+ dashboard: z.strictObject({
1183
+ schemaVersion: z.literal(DASHBOARD_SCHEMA_VERSION).optional(),
1184
+ defaults: defaults.optional(),
1185
+ rows: z.array(z.strictObject({ widgets: z.array(widget).min(1) })).min(1)
1186
+ }).superRefine((dashboard, context) => {
1187
+ const widgets = dashboard.rows.flatMap((row) => row.widgets);
1188
+ if (widgets.length > DASHBOARD_MAX_WIDGETS) context.addIssue({
1189
+ code: "custom",
1190
+ path: ["rows"],
1191
+ message: `At most ${DASHBOARD_MAX_WIDGETS} widgets`
1192
+ });
1193
+ const seen = /* @__PURE__ */ new Set();
1194
+ for (const { id } of widgets) {
1195
+ if (id === void 0) continue;
1196
+ if (seen.has(id)) context.addIssue({
1197
+ code: "custom",
1198
+ path: ["rows"],
1199
+ message: `Duplicate widget id '${id}'`
1200
+ });
1201
+ seen.add(id);
1202
+ }
1203
+ })
1204
+ };
1205
+ }
1206
+ /**
1207
+ * The input schema of one widget, as written in a dashboard's `rows[].widgets[]`, for a tool that
1208
+ * adds a single widget. Metric names are limited to `catalog.metricNames` as in
1209
+ * `createObservabilityDashboardInputSchema`. Build it again when the catalog changes: the schema is a
1210
+ * snapshot.
1211
+ */
1212
+ function createObservabilityWidgetInputSchema(catalog = {}) {
1213
+ return createObservabilityDraftSchemas(catalog).widget;
1214
+ }
1215
+ const dashboardInputSchemaOf = (dashboard) => z.object({
1216
+ dashboard,
1217
+ datePreset: z.enum(OBSERVABILITY_DATE_PRESETS).optional().describe("The range drawn. Left out, the dashboard's `defaults.datePreset` when it is one of these, else `24h`.")
1218
+ });
1219
+ /**
1220
+ * The opening tool's input schema, with metric names limited to `catalog.metricNames`, so the
1221
+ * model can only name metrics that have data. With no names, or more than
1222
+ * `OBSERVABILITY_CATALOG_MAX_METRIC_NAMES`, metric names stay free strings. Build it again when the
1223
+ * catalog changes: the schema is a snapshot.
1224
+ */
1225
+ function createObservabilityDashboardInputSchema(catalog = {}) {
1226
+ return dashboardInputSchemaOf(createObservabilityDraftSchemas(catalog).dashboard);
1227
+ }
1228
+ const draftSchemas = createObservabilityDraftSchemas();
1229
+ /** One widget's input schema, with free metric names; `createObservabilityWidgetInputSchema` lists the project's. */
1230
+ const observabilityWidgetInputSchema = draftSchemas.widget;
1231
+ /**
1232
+ * The opening tool's input schema. It spells out each built-in kind's options and checks them as
1233
+ * the widget's renderer does, so a model writing the dashboard sees them and gets actionable errors.
1234
+ * Metric names are free strings; `createObservabilityDashboardInputSchema` lists the project's.
1235
+ */
1236
+ const observabilityDashboardInputSchema = dashboardInputSchemaOf(draftSchemas.dashboard);
1237
+ /** The opening tool's output schema, which the app reads as `structuredContent`. */
1238
+ const observabilityDashboardOutputSchema = z.object({
1239
+ dashboard: dashboardDefinitionSchema,
1240
+ datePreset: z.enum(OBSERVABILITY_DATE_PRESETS).optional()
1241
+ });
1242
+ /**
1243
+ * The stored definition for `input`: each value's reads gathered into the view's queries, and every
1244
+ * widget without an id given a fresh UUID, so the host can pin each widget by an id that stays the
1245
+ * same whenever the result is shown. Throws when `input` doesn't pass
1246
+ * `observabilityDashboardInputSchema`, or the definition doesn't validate (e.g. over the size limit).
1247
+ * Like `toObservabilityWidget`, it checks against the default schemas, not a catalog or options.
1248
+ */
1249
+ function toObservabilityDashboard(input) {
1250
+ const checked = observabilityDashboardInputSchema.safeParse(input);
1251
+ if (!checked.success) throw new Error(`The dashboard is invalid: ${z.prettifyError(checked.error)}`);
1252
+ const { dashboard, datePreset } = input;
1253
+ const definition = {
1254
+ ...dashboard,
1255
+ schemaVersion: DASHBOARD_SCHEMA_VERSION,
1256
+ rows: dashboard.rows.map((row) => ({ widgets: row.widgets.map(toWidget) }))
1257
+ };
1258
+ const parsed = dashboardDefinitionSchema.safeParse(definition);
1259
+ if (!parsed.success) throw new Error(`The dashboard is invalid: ${z.prettifyError(parsed.error)}`);
1260
+ return {
1261
+ dashboard: definition,
1262
+ ...datePreset ? { datePreset } : {}
1263
+ };
1264
+ }
1265
+ /**
1266
+ * The stored widget for `draft`, converted as in `toObservabilityDashboard`: its reads gathered into
1267
+ * each view's queries, its `id` kept or a fresh UUID when it has none, and the full width when it has
1268
+ * no span. Throws when `draft` doesn't pass `observabilityWidgetInputSchema`; the error's `cause` is
1269
+ * the `ZodError`, whose issue paths point into the draft (e.g. `timeseries.series.1.value`). The
1270
+ * converted widget is checked against core's schema too, as a backstop the draft's checks should
1271
+ * make unreachable; that error's `cause` has paths into the stored widget. It checks against the default schemas, so it allows every kind and
1272
+ * metric name: a tool whose input schema came from `createObservabilityDraftSchemas` with a catalog
1273
+ * or `kinds` has already applied them, but elsewhere check `draft` against your own schemas first.
1274
+ * Check the widget's place in a dashboard (unique ids, the widget count) with the whole definition.
1275
+ */
1276
+ function toObservabilityWidget(draft) {
1277
+ const checked = observabilityWidgetInputSchema.safeParse(draft);
1278
+ if (!checked.success) throw new Error(`The widget is invalid: ${z.prettifyError(checked.error)}`, { cause: checked.error });
1279
+ const widget = toWidget(draft);
1280
+ const parsed = dashboardWidgetSchema.safeParse(widget);
1281
+ if (!parsed.success) throw new Error(`The widget is invalid: ${z.prettifyError(parsed.error)}`, { cause: parsed.error });
1282
+ return widget;
1283
+ }
1284
+ export { observabilityDashboardInputSchema as a, toObservabilityDashboard as c, zodIssues as d, createObservabilityWidgetInputSchema as i, toObservabilityWidget as l, createObservabilityDashboardInputSchema as n, observabilityDashboardOutputSchema as o, createObservabilityDraftSchemas as r, observabilityWidgetInputSchema as s, OBSERVABILITY_CATALOG_MAX_METRIC_NAMES as t, widgetIssues as u };
1285
+
1286
+ //# sourceMappingURL=observability-dashboard-BH7Qi5Nh.js.map