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