@dbx-tools/appkit-mastra 0.1.67 → 0.1.68

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.
package/src/chart.ts DELETED
@@ -1,716 +0,0 @@
1
- /**
2
- * Chart planner + chart cache.
3
- *
4
- * Self-contained chart subsystem with two layers:
5
- *
6
- * 1. Inner planner agent (private). Pure dataset-in /
7
- * `EChartsOption`-out brain. Driven by {@link prepareChart};
8
- * callers never instantiate it directly.
9
- * 2. {@link prepareChart}: orchestration on top of the planner.
10
- * Mints a `chartId`, caches an empty `{ chartId }` record
11
- * synchronously, then resolves the dataset and runs the
12
- * planner in the background. The terminal entry settles with
13
- * either `result` (success) or `error` (failure). Both
14
- * undefined means the entry is still processing.
15
- *
16
- * The cache surface ({@link fetchChart}) is the only state the
17
- * HTTP route and the chart-producing tools share. `prepareChart`
18
- * is dataset-agnostic - callers supply a `resolveData` callback
19
- * that fetches the rows however they like (Genie statement, inline
20
- * dataset, custom API). The module has no knowledge of Genie or
21
- * statement ids; those concerns live in the tools that wrap it.
22
- *
23
- * Wire-format schemas live in `@dbx-tools/appkit-mastra-shared` so
24
- * the demo client and any other UI consumer share the exact same
25
- * shape this module reads and writes.
26
- */
27
-
28
- import { CacheManager } from "@databricks/appkit";
29
- import {
30
- ChartSchema,
31
- ChartTypeSchema,
32
- type Chart,
33
- type ChartResult,
34
- } from "@dbx-tools/appkit-mastra-shared";
35
- import { commonUtils, logUtils, stringUtils } from "@dbx-tools/shared";
36
- import { Agent } from "@mastra/core/agent";
37
- import type { RequestContext } from "@mastra/core/request-context";
38
- import { createTool } from "@mastra/core/tools";
39
- import { z } from "zod";
40
-
41
- import type { MastraPluginConfig } from "./config.js";
42
- import { buildModel, ModelClass } from "./model.js";
43
-
44
- const log = logUtils.logger("mastra/chart");
45
-
46
- /* ------------------------------ constants ------------------------------ */
47
-
48
- /**
49
- * TTL for cached chart entries. One hour balances "long enough for
50
- * the host UI to fetch the chart well after the model finished
51
- * talking" against "short enough that abandoned chart ids don't
52
- * pin storage". Matches the typical Databricks OBO token lifetime
53
- * so any data re-resolution stays inside the original auth window.
54
- */
55
- const CHART_CACHE_TTL_SEC = 60 * 60;
56
-
57
- /** Cache namespace; keeps the chart keyspace tidy. */
58
- const CHART_CACHE_NAMESPACE = "mastra:chart";
59
-
60
- /**
61
- * `userKey` for `CacheManager.generateKey`. Chart ids are minted
62
- * via `commonUtils.id()` (v4 UUID) and are unguessable, so a
63
- * constant user key is fine. The HTTP route can re-scope to the
64
- * requesting user when policy demands it.
65
- */
66
- const CHART_CACHE_USER_KEY = "mastra-chart";
67
-
68
- /** Default server-side long-poll budget for {@link fetchChart}. */
69
- const DEFAULT_FETCH_TIMEOUT_MS = 60_000;
70
-
71
- /** Default inter-poll sleep for {@link fetchChart}. */
72
- const DEFAULT_FETCH_INTERVAL_MS = 250;
73
-
74
- /* ------------------------------- schemas ------------------------------- */
75
-
76
- /**
77
- * One series data point. Wide variant set so the planner agent can
78
- * faithfully pass through whatever the SQL row set contained
79
- * (numbers, stringified numbers, nulls for missing measurements,
80
- * `[x, y]` tuples for scatter, `{name, value}` slices for pie)
81
- * without the structured-output guard rejecting the whole plan.
82
- *
83
- * Three layers of tolerance:
84
- *
85
- * 1. {@link z.preprocess} normalizes wire shapes BEFORE union
86
- * dispatch: stringified numbers parse to numbers, finite
87
- * checks reject `NaN` / `Infinity`, 2-element arrays coerce
88
- * tuple components, and `{value}` objects with missing /
89
- * stringified `value` get coerced or rejected uniformly.
90
- * Anything not handleable becomes `null`.
91
- * 2. The union accepts `null` as a first-class variant. Echarts
92
- * renders null as a gap on bar / line / area (which is the
93
- * right visual signal for "missing reading"). Scatter and
94
- * pie filter nulls in {@link planToEchartsOption} because
95
- * Echarts crashes on null tuples / slices.
96
- * 3. {@link z.union#catch} backstops the whole thing: if
97
- * preprocess somehow produces a shape that still doesn't
98
- * match any variant, the bad item becomes `null` instead of
99
- * taking down the entire chart with a
100
- * `Structured output validation failed` error.
101
- */
102
- const chartDataPointSchema = z
103
- .preprocess(
104
- (v) => {
105
- if (v === null || v === undefined) return null;
106
- if (typeof v === "number") return Number.isFinite(v) ? v : null;
107
- if (typeof v === "string") {
108
- const n = Number(v);
109
- return Number.isFinite(n) ? n : null;
110
- }
111
- if (Array.isArray(v) && v.length === 2) {
112
- const x = typeof v[0] === "number" ? v[0] : Number(v[0]);
113
- const y = typeof v[1] === "number" ? v[1] : Number(v[1]);
114
- return Number.isFinite(x) && Number.isFinite(y) ? [x, y] : null;
115
- }
116
- if (typeof v === "object" && v !== null && "value" in v) {
117
- const obj = v as { name?: unknown; value: unknown };
118
- const val = typeof obj.value === "number" ? obj.value : Number(obj.value);
119
- if (!Number.isFinite(val)) return null;
120
- // Coerce numeric / boolean / nullish names to strings so a
121
- // pie slice keyed on a year (`2024`) or category id is
122
- // accepted without round-tripping through the catch arm.
123
- const rawName = obj.name;
124
- const name =
125
- typeof rawName === "string"
126
- ? rawName
127
- : rawName == null
128
- ? ""
129
- : String(rawName);
130
- return { name, value: val };
131
- }
132
- return null;
133
- },
134
- z.union([
135
- z.number(),
136
- z.null(),
137
- z.tuple([z.number(), z.number()]),
138
- z.object({ name: z.string(), value: z.number() }),
139
- ]),
140
- )
141
- .catch(null);
142
-
143
- /**
144
- * Compact, model-friendly representation of an Echarts spec. The
145
- * planner agent emits this; {@link planToEchartsOption} expands it
146
- * into a real `EChartsOption` JSON. Two layers because letting the
147
- * model fill in a fully-typed `EChartsOption` is brittle (hundreds
148
- * of optional fields, deep unions, version-dependent shapes). A
149
- * small "chart plan" schema is much more reliable for a fast model
150
- * and keeps animation / tooltip / styling defaults consistent
151
- * across charts.
152
- */
153
- const chartPlanSchema = z.object({
154
- chartType: ChartTypeSchema,
155
- title: z
156
- .string()
157
- .optional()
158
- .describe(
159
- stringUtils.toDescription(`
160
- Short title shown above the chart. Optional; defaults to the
161
- \`title\` argument the caller passed in.
162
- `),
163
- ),
164
- xAxisLabel: z
165
- .string()
166
- .optional()
167
- .describe(
168
- stringUtils.toDescription(`
169
- Axis label below the chart. Used for bar / line / area / scatter;
170
- ignored for pie.
171
- `),
172
- ),
173
- yAxisLabel: z
174
- .string()
175
- .optional()
176
- .describe(
177
- stringUtils.toDescription(`
178
- Axis label to the left of the chart. Used for bar / line / area /
179
- scatter; ignored for pie.
180
- `),
181
- ),
182
- categories: z
183
- .array(z.string())
184
- .optional()
185
- .describe(
186
- stringUtils.toDescription(`
187
- X-axis category labels for \`bar\` / \`line\` / \`area\` charts
188
- (one per data point in each series). Omit for \`scatter\` (uses
189
- [x, y] tuples) and \`pie\` (each slice carries its own \`name\`).
190
- `),
191
- ),
192
- series: z
193
- .array(
194
- z.object({
195
- name: z.string().describe(
196
- stringUtils.toDescription(`
197
- Legend name for this series.
198
- `),
199
- ),
200
- data: z.array(chartDataPointSchema).describe(
201
- stringUtils.toDescription(`
202
- Data points. For \`bar\` / \`line\` / \`area\`, an array of
203
- numbers aligned to \`categories\`. For \`scatter\`, an array
204
- of \`[x, y]\` numeric tuples. For \`pie\`, an array of
205
- \`{name, value}\` objects.
206
- `),
207
- ),
208
- }),
209
- )
210
- .min(1)
211
- .describe(
212
- stringUtils.toDescription(`
213
- One or more series to plot. Pie charts use exactly one series;
214
- bar/line/area can stack multiple series sharing the same
215
- \`categories\` axis.
216
- `),
217
- ),
218
- });
219
-
220
- type ChartPlan = z.infer<typeof chartPlanSchema>;
221
-
222
- /**
223
- * Canonical planner input shape. Tools that source rows from an
224
- * inline dataset (`render_data`) use it as their `inputSchema`
225
- * verbatim; tools that resolve rows from a remote (`prepare_chart`
226
- * over a Genie statement) `omit({ data })` and `extend` with their
227
- * own identifier field, so the field-level `.describe()` text
228
- * stays a single source of truth. Server-only - the UI never
229
- * sees a planner request, only the resolved {@link Chart}.
230
- */
231
- export const chartPlannerRequestSchema = z.object({
232
- title: z.string().describe(
233
- stringUtils.toDescription(`
234
- Concise title shown above the chart (e.g. "Top 10 SKUs by Revenue").
235
- `),
236
- ),
237
- description: z
238
- .string()
239
- .optional()
240
- .describe(
241
- stringUtils.toDescription(`
242
- One-line intent the chart-planner uses when picking a chart type
243
- and axis encodings (e.g. "compare quarterly revenue across
244
- regions", "highlight the steep drop after position 5"). Not shown
245
- to the user.
246
- `),
247
- ),
248
- data: z
249
- .array(z.record(z.string(), z.unknown()))
250
- .nonempty("Data must contain at least one row")
251
- .readonly()
252
- .describe(
253
- stringUtils.toDescription(`
254
- Tabular dataset to chart. One object per row, keyed by column
255
- name. Values may be strings, numbers, booleans, or null. The
256
- chart-planner decides which columns are categories vs. numeric
257
- series. Cap at a few hundred rows for legibility; sample /
258
- aggregate larger datasets first.
259
- `),
260
- ),
261
- });
262
-
263
- export type ChartPlannerRequest = z.infer<typeof chartPlannerRequestSchema>;
264
-
265
- /* --------------------------- planner instructions --------------------------- */
266
-
267
- /**
268
- * Format {@link ChartTypeSchema}'s variants as a single
269
- * human-friendly string of `` `<value>` for <description> ``
270
- * clauses joined by semicolons, drawn from each variant's own
271
- * `.describe()` so the planner prompt stays in lock-step with
272
- * the schema by construction.
273
- */
274
- function formatChartTypePicker(): string {
275
- return ChartTypeSchema.options
276
- .map((opt) => `\`${opt.value}\` for ${opt.description ?? ""}`)
277
- .join("; ");
278
- }
279
-
280
- /**
281
- * System prompt for the inner chart-planning agent. Tuned for a
282
- * fast-tier model (Haiku, GPT-5-mini, Gemini Flash Lite).
283
- */
284
- const CHART_PLANNER_INSTRUCTIONS = stringUtils.toDescription(`
285
- You design Apache Echarts visualizations. The user gives you a
286
- tabular dataset (rows of objects) plus a title and an optional
287
- description of the intent. You produce a small chart plan (chart
288
- type, axis labels, categories, series) that best conveys the data.
289
-
290
- Decision guide. Pick the chart type whose data shape matches the
291
- dataset and the user's intent: ${formatChartTypePicker()}.
292
-
293
- When in doubt between bar and line, prefer bar for unordered
294
- categories and line for ordered ones (dates, time buckets, ranks).
295
- Never pick pie for more than 7 slices.
296
-
297
- For bar / line / area: pick one column as the category axis (usually
298
- the only string-valued column) and one or more numeric columns as
299
- series. Sort categories by the primary series value descending unless
300
- the data is naturally ordered (dates, ranks).
301
-
302
- For pie: pick the category column for slice names and one numeric
303
- column for slice values. Emit a single series.
304
-
305
- For scatter: pick two numeric columns and emit \`[x, y]\` tuples in a
306
- single series.
307
-
308
- Keep series names human-readable (use the column name; title case it
309
- lightly if needed). Keep titles concise; do not repeat the user's
310
- title in xAxisLabel / yAxisLabel.
311
- `);
312
-
313
- /* ----------------------------- planner agent ----------------------------- */
314
-
315
- /**
316
- * One planner `Agent` per plugin config. Cached on config object
317
- * identity so callers can `prepareChart({ config, ... })` from a
318
- * hot path without paying the Agent-constructor cost every call.
319
- * `WeakMap` lets retired configs (e.g. test reconfigurations)
320
- * release their agent without manual eviction.
321
- */
322
- const plannerAgents = new WeakMap<MastraPluginConfig, Agent>();
323
-
324
- function getPlannerAgent(config: MastraPluginConfig): Agent {
325
- let agent = plannerAgents.get(config);
326
- if (!agent) {
327
- agent = new Agent({
328
- id: "chart_planner",
329
- name: "Chart Planner",
330
- description: "Picks chart type and axis encodings for a dataset.",
331
- instructions: CHART_PLANNER_INSTRUCTIONS,
332
- model: ({ requestContext }) =>
333
- buildModel(config, requestContext, { modelClass: ModelClass.ChatFast }),
334
- });
335
- plannerAgents.set(config, agent);
336
- }
337
- return agent;
338
- }
339
-
340
- /**
341
- * Run the planner against `request` and return the resolved
342
- * Echarts spec. Throws on planner failure - {@link prepareChart}
343
- * catches and stashes the error in the cache entry.
344
- */
345
- async function runChartPlanner(
346
- config: MastraPluginConfig,
347
- request: ChartPlannerRequest,
348
- options: { requestContext?: RequestContext; abortSignal?: AbortSignal } = {},
349
- ): Promise<ChartResult> {
350
- const { title, description, data } = request;
351
- const { requestContext, abortSignal } = options;
352
- const prompt = stringUtils.toDescription({
353
- Title: title,
354
- ...(description ? { Description: description } : {}),
355
- "Dataset (JSON, one row per object)": JSON.stringify(data, null, 2),
356
- });
357
- const result = await getPlannerAgent(config).generate(prompt, {
358
- structuredOutput: { schema: chartPlanSchema },
359
- ...(requestContext ? { requestContext } : {}),
360
- ...(abortSignal ? { abortSignal } : {}),
361
- });
362
- const plan = chartPlanSchema.parse(result.object);
363
- const option = planToEchartsOption(plan, title);
364
- return { chartType: plan.chartType, option };
365
- }
366
-
367
- /* ------------------------------ cache helpers ------------------------------ */
368
-
369
- /** Build the canonical cache key for a `chartId`. */
370
- async function chartCacheKey(chartId: string): Promise<string> {
371
- return (await CacheManager.getInstance()).generateKey(
372
- [CHART_CACHE_NAMESPACE, chartId],
373
- CHART_CACHE_USER_KEY,
374
- );
375
- }
376
-
377
- /**
378
- * Persist a {@link Chart} entry under its `chartId`. Refreshes
379
- * the TTL on every write. Cache-layer failures are logged and
380
- * swallowed so background runners never throw into the
381
- * unhandled-rejection stream.
382
- */
383
- async function writeChart(entry: Chart): Promise<void> {
384
- try {
385
- const key = await chartCacheKey(entry.chartId);
386
- await CacheManager.getInstanceSync().set(key, entry, {
387
- ttl: CHART_CACHE_TTL_SEC,
388
- });
389
- } catch (err) {
390
- log.warn("write-error", {
391
- chartId: entry.chartId,
392
- error: commonUtils.errorMessage(err),
393
- });
394
- }
395
- }
396
-
397
- /**
398
- * Look up a chart by id. Returns `undefined` on miss, on
399
- * expiry, or when the cache layer is unhealthy - never throws.
400
- */
401
- async function readChart(chartId: string): Promise<Chart | undefined> {
402
- try {
403
- const key = await chartCacheKey(chartId);
404
- const v = await CacheManager.getInstanceSync().get<Chart>(key);
405
- return v ?? undefined;
406
- } catch (err) {
407
- log.warn("read-error", {
408
- chartId,
409
- error: commonUtils.errorMessage(err),
410
- });
411
- return undefined;
412
- }
413
- }
414
-
415
- /* --------------------------- prepareChart orchestrator --------------------------- */
416
-
417
- /** Inputs to {@link prepareChart}. */
418
- export interface PrepareChartOptions {
419
- /** Plugin config; resolves the planner agent's model. */
420
- config: MastraPluginConfig;
421
- /** Display title forwarded to the planner agent. */
422
- title?: string;
423
- /** Optional intent hint forwarded to the planner agent. */
424
- description?: string;
425
- /**
426
- * Resolves the rows to chart. Called once, in the background.
427
- * Any thrown error lands in the cache as the entry's `error`
428
- * field (never propagated to the caller of {@link prepareChart}).
429
- * An empty `rows` array is rejected as `"dataset has no rows;
430
- * nothing to chart"`.
431
- */
432
- resolveData: (
433
- signal?: AbortSignal,
434
- ) => Promise<{ rows: ReadonlyArray<Record<string, unknown>> }>;
435
- /**
436
- * Per-request `RequestContext`. Forwarded to the planner agent so
437
- * user-scoped model resolution (OBO) stays in effect.
438
- */
439
- requestContext?: RequestContext;
440
- /**
441
- * Cooperative cancellation. Forwarded to `resolveData` and the
442
- * planner agent. Note: the chart task continues running in the
443
- * background after the parent request ends, so external abort
444
- * signals are best-effort; typical use is to leave this unset
445
- * and let the 1h TTL cap stale entries.
446
- */
447
- signal?: AbortSignal;
448
- }
449
-
450
- /**
451
- * Mint a `chartId`, cache an empty `{ chartId }` placeholder
452
- * synchronously, and kick off a background task that resolves the
453
- * dataset and runs the planner. Returns the `chartId` once the
454
- * placeholder lands so the first {@link fetchChart} call always
455
- * sees an entry (no spurious 404 race).
456
- *
457
- * The background task swallows its own failures and writes them
458
- * as `error` entries, so callers never see a rejected promise.
459
- * Cache state machine:
460
- *
461
- * - just after this call returns: `{ chartId }` (processing)
462
- * - on planner success: `{ chartId, result }`
463
- * - on data / planner failure: `{ chartId, error }`
464
- */
465
- export async function prepareChart(
466
- opts: PrepareChartOptions,
467
- ): Promise<{ chartId: string }> {
468
- const chartId = commonUtils.id();
469
- await writeChart({ chartId });
470
- log.debug("queued", { chartId });
471
- // Fire-and-forget. Failures land in the cache as `error` entries;
472
- // never escape into an unhandled rejection.
473
- void runPrepareChart(chartId, opts);
474
- return { chartId };
475
- }
476
-
477
- async function runPrepareChart(
478
- chartId: string,
479
- opts: PrepareChartOptions,
480
- ): Promise<void> {
481
- const startedAt = Date.now();
482
- try {
483
- const data = await opts.resolveData(opts.signal);
484
- if (data.rows.length === 0) {
485
- throw new Error("dataset has no rows; nothing to chart");
486
- }
487
- const result = await runChartPlanner(
488
- opts.config,
489
- {
490
- title: opts.title ?? "Chart",
491
- ...(opts.description ? { description: opts.description } : {}),
492
- data: data.rows as ChartPlannerRequest["data"],
493
- },
494
- {
495
- ...(opts.requestContext ? { requestContext: opts.requestContext } : {}),
496
- ...(opts.signal ? { abortSignal: opts.signal } : {}),
497
- },
498
- );
499
- await writeChart({ chartId, result });
500
- log.info("done", {
501
- chartId,
502
- chartType: result.chartType,
503
- elapsedMs: Date.now() - startedAt,
504
- });
505
- } catch (err) {
506
- const error = commonUtils.errorMessage(err);
507
- log.warn("error", { chartId, error });
508
- await writeChart({ chartId, error });
509
- }
510
- }
511
-
512
- /* ------------------------------- long-poll fetch ------------------------------- */
513
-
514
- /** Inputs to {@link fetchChart}. */
515
- export interface FetchChartOptions {
516
- /**
517
- * Server-side polling budget in ms. When the entry stays in
518
- * the processing state past this window, the helper returns the
519
- * last seen value (still processing) so the client can re-poll.
520
- * Defaults to {@link DEFAULT_FETCH_TIMEOUT_MS} (60s).
521
- */
522
- timeoutMs?: number;
523
- /**
524
- * Poll interval in ms. Defaults to
525
- * {@link DEFAULT_FETCH_INTERVAL_MS} (250ms).
526
- */
527
- intervalMs?: number;
528
- /** External cancellation handle (e.g. request `req.signal`). */
529
- signal?: AbortSignal;
530
- }
531
-
532
- /**
533
- * Long-poll the chart cache until the entry settles (`result` or
534
- * `error` set), the entry is missing, or the server-side timeout
535
- * elapses.
536
- *
537
- * Returns:
538
- * - the resolved {@link Chart} when it settled, errored, or
539
- * stayed in processing past `timeoutMs` (so the client can
540
- * re-poll);
541
- * - `undefined` when the entry is missing or expired (the
542
- * consumer should treat as 404).
543
- *
544
- * `signal` lets the caller cancel ahead of timeout (e.g. the HTTP
545
- * request closed). Cancellation propagates to the inter-poll sleep
546
- * so the helper returns immediately.
547
- */
548
- export async function fetchChart(
549
- chartId: string,
550
- options: FetchChartOptions = {},
551
- ): Promise<Chart | undefined> {
552
- const timeoutMs = options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
553
- const intervalMs = options.intervalMs ?? DEFAULT_FETCH_INTERVAL_MS;
554
- const deadline = Date.now() + timeoutMs;
555
-
556
- let last: Chart | undefined;
557
- while (true) {
558
- options.signal?.throwIfAborted();
559
- last = await readChart(chartId);
560
- if (!last) return undefined;
561
- if (last.result !== undefined || last.error !== undefined) return last;
562
- const remaining = deadline - Date.now();
563
- if (remaining <= 0) return last;
564
- await commonUtils.sleep(Math.min(intervalMs, remaining), options.signal);
565
- }
566
- }
567
-
568
- /* ----------------------------- echarts expansion ----------------------------- */
569
-
570
- /**
571
- * Expand a {@link ChartPlan} into a full Echarts `EChartsOption`
572
- * JSON. Centralized here so the planner agent only fills in the
573
- * compact plan shape; tooltip / animation / color / grid defaults
574
- * stay consistent across charts and are easy to tune without
575
- * retraining model behaviour.
576
- */
577
- function planToEchartsOption(
578
- plan: ChartPlan,
579
- fallbackTitle: string,
580
- ): Record<string, unknown> {
581
- const baseTitle = plan.title ?? fallbackTitle;
582
- const grid = { left: 48, right: 24, top: 56, bottom: 48, containLabel: true };
583
-
584
- if (plan.chartType === "pie") {
585
- // Echarts crashes on null pie slices - filter them out.
586
- // `{name, value}` slices are the only valid pie data shape,
587
- // so drop bare numbers / tuples / nulls the planner may
588
- // have leaked into a pie series.
589
- const slices = (plan.series[0]?.data ?? []).filter(
590
- (d): d is { name: string; value: number } =>
591
- d !== null && typeof d === "object" && !Array.isArray(d),
592
- );
593
- return {
594
- title: { text: baseTitle, left: "center" },
595
- tooltip: { trigger: "item" },
596
- legend: { bottom: 0 },
597
- series: [
598
- {
599
- name: plan.series[0]?.name ?? baseTitle,
600
- type: "pie",
601
- radius: ["35%", "65%"],
602
- data: slices,
603
- },
604
- ],
605
- };
606
- }
607
-
608
- if (plan.chartType === "scatter") {
609
- // Echarts crashes on null scatter points - keep only valid
610
- // `[x, y]` tuples. Bare numbers / objects / nulls from a
611
- // mismatched plan get dropped silently.
612
- return {
613
- title: { text: baseTitle, left: "center" },
614
- tooltip: { trigger: "item" },
615
- legend: { bottom: 0 },
616
- grid,
617
- xAxis: { type: "value", name: plan.xAxisLabel },
618
- yAxis: { type: "value", name: plan.yAxisLabel },
619
- series: plan.series.map((s) => ({
620
- name: s.name,
621
- type: "scatter",
622
- data: s.data.filter(
623
- (d): d is [number, number] => Array.isArray(d) && d.length === 2,
624
- ),
625
- })),
626
- };
627
- }
628
-
629
- // bar / line / area share the same axis layout.
630
- const isArea = plan.chartType === "area";
631
- const seriesType = plan.chartType === "bar" ? "bar" : "line";
632
- return {
633
- title: { text: baseTitle, left: "center" },
634
- tooltip: { trigger: "axis" },
635
- legend: { bottom: 0 },
636
- grid,
637
- xAxis: {
638
- type: "category",
639
- data: plan.categories ?? [],
640
- name: plan.xAxisLabel,
641
- },
642
- yAxis: { type: "value", name: plan.yAxisLabel },
643
- series: plan.series.map((s) => ({
644
- name: s.name,
645
- type: seriesType,
646
- data: s.data,
647
- smooth: seriesType === "line",
648
- ...(isArea ? { areaStyle: {} } : {}),
649
- })),
650
- };
651
- }
652
-
653
- /* ----------------------------- render_data tool ----------------------------- */
654
-
655
- /**
656
- * Build the `render_data` Mastra tool bound to the given plugin
657
- * config. Auto-wired as a system tool on every agent (see
658
- * `agents.ts`); per-agent tools can shadow it by registering a
659
- * same-named entry.
660
- *
661
- * Thin wrapper over {@link prepareChart} for callers that already
662
- * have a dataset in hand. Mints a `chartId` synchronously, caches
663
- * an empty placeholder, and kicks off the chart-planner in the
664
- * background. Returns just the `chartId`; the host UI resolves
665
- * `[chart:<chartId>]` markers by hitting the plugin's
666
- * `/embed/chart/:id` route.
667
- *
668
- * For Genie statement results, prefer the Genie agent's
669
- * `prepare_chart` tool, which accepts a `statement_id` and
670
- * resolves the rows lazily.
671
- */
672
- export function buildRenderDataTool(config: MastraPluginConfig) {
673
- return createTool({
674
- id: "render_data",
675
- description: stringUtils.toDescription([
676
- `
677
- Submit a tabular dataset for inline rendering as a chart in
678
- the user's view. Pass a title, the raw rows (array of objects
679
- keyed by column name), and an optional one-line description
680
- of the insight to highlight. Returns a short \`chartId\`;
681
- the chart renders inline at the position you embed the
682
- matching \`[chart:<chartId>]\` marker.
683
- `,
684
- `
685
- Placement contract: embed \`[chart:<chartId>]\` on its own
686
- line (blank lines above and below) wherever you want the
687
- chart to appear in your reply. The chart resolves
688
- asynchronously - the tool returns the id immediately and the
689
- host UI fetches the chart from the cache once the planner
690
- lands. You can call \`render_data\` multiple times in the
691
- same turn (the tool is parallel-safe) and interleave the
692
- markers with prose so each chart sits next to its
693
- commentary.
694
- `,
695
- `
696
- Use whenever a SQL row set, API response, or hand-built
697
- dataset would land better as a picture than as a list or
698
- table. Cap input at a few hundred rows; sample or aggregate
699
- larger datasets first.
700
- `,
701
- ]),
702
- inputSchema: chartPlannerRequestSchema,
703
- outputSchema: ChartSchema.pick({ chartId: true }),
704
- execute: async (input, ctxRaw) => {
705
- const { title, description, data } = input as ChartPlannerRequest;
706
- const ctx = ctxRaw as { requestContext?: RequestContext } | undefined;
707
- return prepareChart({
708
- config,
709
- title,
710
- ...(description ? { description } : {}),
711
- resolveData: () => Promise.resolve({ rows: data }),
712
- ...(ctx?.requestContext ? { requestContext: ctx.requestContext } : {}),
713
- });
714
- },
715
- });
716
- }