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