@mastra/mcp-apps-components 0.0.0-agent-session-20261112221706

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