@dbx-tools/appkit-mastra 0.1.58 → 0.1.67

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 (44) 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 -28
  5. package/src/agents.ts +7 -1
  6. package/src/config.ts +64 -0
  7. package/src/genie.ts +9 -21
  8. package/{index.ts → src/index.ts} +7 -9
  9. package/src/mcp.ts +89 -0
  10. package/src/model.ts +9 -3
  11. package/src/plugin.ts +51 -8
  12. package/src/serving.ts +5 -9
  13. package/src/statement.ts +8 -36
  14. package/dist/src/agents.d.ts +0 -316
  15. package/dist/src/agents.js +0 -470
  16. package/dist/src/chart.d.ts +0 -153
  17. package/dist/src/chart.js +0 -570
  18. package/dist/src/config.d.ts +0 -295
  19. package/dist/src/config.js +0 -55
  20. package/dist/src/genie.d.ts +0 -161
  21. package/dist/src/genie.js +0 -973
  22. package/dist/src/history.d.ts +0 -95
  23. package/dist/src/history.js +0 -278
  24. package/dist/src/memory.d.ts +0 -109
  25. package/dist/src/memory.js +0 -253
  26. package/dist/src/model.d.ts +0 -52
  27. package/dist/src/model.js +0 -198
  28. package/dist/src/observability.d.ts +0 -64
  29. package/dist/src/observability.js +0 -83
  30. package/dist/src/plugin.d.ts +0 -177
  31. package/dist/src/plugin.js +0 -554
  32. package/dist/src/processor.d.ts +0 -8
  33. package/dist/src/processor.js +0 -40
  34. package/dist/src/processors/strip-stale-charts.d.ts +0 -32
  35. package/dist/src/processors/strip-stale-charts.js +0 -98
  36. package/dist/src/server.d.ts +0 -51
  37. package/dist/src/server.js +0 -152
  38. package/dist/src/serving.d.ts +0 -65
  39. package/dist/src/serving.js +0 -79
  40. package/dist/src/statement.d.ts +0 -66
  41. package/dist/src/statement.js +0 -111
  42. package/dist/src/writer.d.ts +0 -23
  43. package/dist/src/writer.js +0 -37
  44. package/dist/tsconfig.build.tsbuildinfo +0 -1
package/dist/src/genie.js DELETED
@@ -1,973 +0,0 @@
1
- /**
2
- * Genie tools for Mastra.
3
- *
4
- * Surfaces each configured Genie space as a small set of flat Mastra
5
- * tools the calling agent drives directly - no inner orchestrator
6
- * agent. The central agent decomposes user questions, picks which
7
- * space to ask, streams the per-turn wire events (status, thinking,
8
- * sql, rows) through `ctx.writer`, and composes the final reply.
9
- * Rows are never fetched eagerly: the agent reads a statement's
10
- * values only when it needs to reason about them, otherwise it embeds
11
- * a `[data:<statement_id>]` marker in prose and lets the host UI
12
- * resolve the data. Charts are minted asynchronously and referenced
13
- * by `[chart:<chartId>]` markers so prose isn't blocked on chart
14
- * generation; the host UI fetches the cached spec by id once ready.
15
- * Space description and serialized-space lookups are available for
16
- * grounding when the agent needs schema context.
17
- *
18
- * Each tool's `execute` pulls the per-request
19
- * {@link WorkspaceClient} off `ctx.requestContext` (stamped by
20
- * `MastraServer` under {@link MASTRA_USER_KEY}) and the per-call
21
- * `writer` / `abortSignal` off `ctx`, so the tools are stateless
22
- * across requests and the central agent owns the loop.
23
- *
24
- * The tools talk to Genie directly via `@dbx-tools/genie`
25
- * (`genieEventChat`); statement-row fetching is delegated to
26
- * {@link fetchStatementData} from `./statement.js`, which wraps
27
- * the workspace `statementExecution.getStatement` API. AppKit's
28
- * stock `genie` plugin is honored only for its `spaces` config
29
- * so existing AppKit-style wiring keeps working without change.
30
- *
31
- * Suggested orchestration prompt for the central agent lives in
32
- * {@link GENIE_INSTRUCTIONS}; compose it into the agent's own
33
- * `instructions` when you want the canonical "how to drive the
34
- * Genie tools" guidance.
35
- */
36
- import { CacheManager, genie } from "@databricks/appkit";
37
- import { ApiError, HttpError, WorkspaceClient } from "@databricks/sdk-experimental";
38
- import { ChartSchema, } from "@dbx-tools/appkit-mastra-shared";
39
- import { genieEventChat, genieSampleQuestions, getGenieSpace } from "@dbx-tools/genie";
40
- import { GenieMessageSchema } from "@dbx-tools/genie-shared";
41
- import { appkitUtils, commonUtils, logUtils, stringUtils } from "@dbx-tools/shared";
42
- import { MASTRA_THREAD_ID_KEY } from "@mastra/core/request-context";
43
- import { createTool } from "@mastra/core/tools";
44
- import { z } from "zod";
45
- import { chartPlannerRequestSchema, prepareChart } from "./chart.js";
46
- import { MASTRA_USER_KEY } from "./config.js";
47
- import { fetchStatementData } from "./statement.js";
48
- import { safeWrite } from "./writer.js";
49
- const log = logUtils.logger("mastra/genie");
50
- /** Default alias used when a single unnamed Genie space is wired up. */
51
- export const DEFAULT_GENIE_ALIAS = "default";
52
- /**
53
- * Pull the per-request {@link WorkspaceClient} off the active
54
- * `RequestContext`. The Mastra plugin's server middleware stamps
55
- * a {@link User} on the context under {@link MASTRA_USER_KEY}
56
- * for every request; tools fail loudly when it's missing because
57
- * that means the Mastra plugin isn't running (e.g. a tool was
58
- * invoked outside the chat route).
59
- */
60
- function requireClient(ctx, toolId) {
61
- const requestContext = ctx?.requestContext;
62
- if (!requestContext) {
63
- throw new Error(`${toolId}: missing requestContext (MastraServer must stamp MASTRA_USER_KEY)`);
64
- }
65
- const user = requestContext.get(MASTRA_USER_KEY);
66
- if (!user) {
67
- throw new Error(`${toolId}: no user on requestContext (MASTRA_USER_KEY not set)`);
68
- }
69
- return { client: user.executionContext.client, requestContext };
70
- }
71
- /**
72
- * Lowercased placeholder strings we reject at the `ask_genie`
73
- * boundary so the LLM doesn't spend a Genie round-trip on a
74
- * non-question. Genie politely answers any of these with "Your
75
- * request '...' does not relate to..." which is pure UI noise.
76
- * Kept narrow on purpose - real questions sometimes start with
77
- * one of these tokens, so we only match the FULL trimmed string.
78
- */
79
- const PLACEHOLDER_QUESTIONS = new Set([
80
- "noop",
81
- "no-op",
82
- "skip",
83
- "none",
84
- "n/a",
85
- "na",
86
- "null",
87
- "undefined",
88
- "test",
89
- "placeholder",
90
- ]);
91
- /* ----------------------- conversation state ----------------------- */
92
- /**
93
- * Estimated Genie conversation lifetime in seconds. Databricks
94
- * publishes no official TTL on the conversation resource itself;
95
- * community projects (e.g. the open-source Databricks Genie Bot)
96
- * converge on 4 hours of inactivity as a safe operating window.
97
- * Treat this as an estimate that gets *extended on every use* by
98
- * re-setting the cache entry after each successful turn (sliding
99
- * TTL via re-`set`). When the estimate ends up wrong (conversation
100
- * deleted, expired upstream, cross-space referenced), `ask_genie`
101
- * catches the SDK's `RESOURCE_DOES_NOT_EXIST`/404 and transparently
102
- * starts a fresh conversation.
103
- */
104
- const CONVERSATION_TTL_SEC = 4 * 60 * 60;
105
- /** Cache namespace prefix so coexisting Mastra caches don't collide. */
106
- const CONVERSATION_CACHE_NAMESPACE = "mastra:genie:conversation";
107
- /**
108
- * `userKey` for `CacheManager.getOrExecute` / `generateKey`. Genie
109
- * conversations are scoped to a single user + space + thread, and
110
- * `threadId` is already user-scoped (Mastra mints threads per
111
- * `resourceId`), so a constant user key here is safe and keeps the
112
- * cache key short.
113
- */
114
- const CONVERSATION_USER_KEY = "mastra-genie";
115
- /**
116
- * Build the per-request {@link RequestContext} key the active
117
- * Genie `conversation_id` lives under for `spaceId`. Scoped by
118
- * space so an app calling two Genie spaces in one request keeps
119
- * each conversation distinct (Genie conversation ids are
120
- * space-scoped on the wire). The same `RequestContext` instance
121
- * flows from the central agent through to every `ask_genie`
122
- * invocation, so writes on one call are visible on the next
123
- * without an explicit shared ref.
124
- */
125
- const conversationContextKey = (spaceId) => `mastra__genie_conversation__${spaceId}`;
126
- /**
127
- * Read the active Genie `conversation_id` for `spaceId` off the
128
- * per-request {@link RequestContext}. Returns `undefined` when no
129
- * conversation has been started yet this request.
130
- */
131
- function readContextConversationId(requestContext, spaceId) {
132
- return requestContext.get(conversationContextKey(spaceId));
133
- }
134
- /**
135
- * Write the active Genie `conversation_id` for `spaceId` onto the
136
- * per-request {@link RequestContext}. Subsequent `ask_genie` calls
137
- * in this request will reuse it.
138
- */
139
- function writeContextConversationId(requestContext, spaceId, conversationId) {
140
- requestContext.set(conversationContextKey(spaceId), conversationId);
141
- }
142
- /**
143
- * Build the canonical cache key for a `(spaceId, threadId)` pair.
144
- * Returns `undefined` when `threadId` is missing - callers should
145
- * skip caching entirely in that case (no Mastra memory wired up).
146
- */
147
- async function conversationCacheKey(spaceId, threadId) {
148
- if (!threadId)
149
- return undefined;
150
- return (await CacheManager.getInstance()).generateKey([CONVERSATION_CACHE_NAMESPACE, spaceId, threadId], CONVERSATION_USER_KEY);
151
- }
152
- /**
153
- * Read the cached Genie conversation id for `(spaceId, threadId)`.
154
- * Returns `undefined` on miss, on expiry, or when the cache layer
155
- * is unhealthy - never throws. The TTL is renewed via re-`set`
156
- * after each successful turn (see {@link saveCachedConversationId}).
157
- */
158
- async function readCachedConversationId(cacheKey) {
159
- if (!cacheKey)
160
- return undefined;
161
- try {
162
- const v = await CacheManager.getInstanceSync().get(cacheKey);
163
- return v ?? undefined;
164
- }
165
- catch (err) {
166
- log.warn("conversation-cache:read-error", {
167
- error: commonUtils.errorMessage(err),
168
- });
169
- return undefined;
170
- }
171
- }
172
- /**
173
- * Persist the active conversation id under `cacheKey`, refreshing
174
- * its TTL. Idempotent; no-op when `cacheKey` or `conversationId`
175
- * is missing. Re-setting the same key acts as a sliding TTL: every
176
- * turn that uses the conversation extends the window by another
177
- * {@link CONVERSATION_TTL_SEC} seconds.
178
- */
179
- async function saveCachedConversationId(cacheKey, conversationId) {
180
- if (!cacheKey || !conversationId)
181
- return;
182
- try {
183
- await CacheManager.getInstanceSync().set(cacheKey, conversationId, {
184
- ttl: CONVERSATION_TTL_SEC,
185
- });
186
- }
187
- catch (err) {
188
- log.warn("conversation-cache:write-error", {
189
- error: commonUtils.errorMessage(err),
190
- });
191
- }
192
- }
193
- /** Force-evict a cached conversation id. Used on the stale-id recovery path. */
194
- async function evictCachedConversationId(cacheKey) {
195
- if (!cacheKey)
196
- return;
197
- try {
198
- await CacheManager.getInstanceSync().delete(cacheKey);
199
- }
200
- catch (err) {
201
- log.warn("conversation-cache:delete-error", {
202
- error: commonUtils.errorMessage(err),
203
- });
204
- }
205
- }
206
- /**
207
- * Lazy-seed the active Genie `conversation_id` for `spaceId` from
208
- * the cross-request cache onto the per-request `RequestContext`.
209
- * No-op when the slot is already populated (subsequent
210
- * `ask_genie` calls in the same turn) so we hit the cache at most
211
- * once per request per space.
212
- */
213
- async function ensureConversationSeeded(requestContext, spaceId, cacheKey) {
214
- if (readContextConversationId(requestContext, spaceId))
215
- return;
216
- const cached = await readCachedConversationId(cacheKey);
217
- if (cached)
218
- writeContextConversationId(requestContext, spaceId, cached);
219
- }
220
- /**
221
- * True when `err` is the SDK error Genie returns for a
222
- * conversation id that no longer exists (deleted, expired upstream,
223
- * or referenced from the wrong space). Matches the typed
224
- * {@link ApiError} 404 / `RESOURCE_DOES_NOT_EXIST` shape first, then
225
- * falls back to the lower-level {@link HttpError} 404, then to a
226
- * loose message sniff for SDK shapes we haven't catalogued.
227
- */
228
- function isConversationGoneError(err) {
229
- if (err instanceof ApiError) {
230
- if (err.statusCode === 404)
231
- return true;
232
- if (err.errorCode === "RESOURCE_DOES_NOT_EXIST")
233
- return true;
234
- }
235
- if (err instanceof HttpError && err.code === 404)
236
- return true;
237
- if (err instanceof Error && /does not exist/i.test(err.message))
238
- return true;
239
- return false;
240
- }
241
- /* ------------------------ prepare_chart input ------------------------ */
242
- /**
243
- * Agent-facing `prepare_chart` input schema. Reuses
244
- * {@link chartPlannerRequestSchema} (the dataset-driven planner
245
- * contract) but swaps the inline `data` field for a Genie
246
- * `statement_id` the tool resolves into rows server-side.
247
- * `title` is loosened to optional - the planner falls back to a
248
- * generic placeholder when the agent doesn't supply one.
249
- *
250
- * Shaped to match Genie's wire form - `statement_id` (snake)
251
- * mirrors `query_result.statement_id` and the `get_statement`
252
- * tool's input field name, so the LLM only ever sees one
253
- * spelling for the same identifier.
254
- */
255
- const prepareChartRequestSchema = chartPlannerRequestSchema
256
- .omit({ data: true, title: true })
257
- .extend({
258
- statement_id: z
259
- .string()
260
- .min(1, "statement_id is required")
261
- .describe(stringUtils.toDescription(`
262
- Genie \`statement_id\` to chart. Read from
263
- \`message.query_result.statement_id\` or
264
- \`message.attachments[*].query.statement_id\` returned by
265
- \`ask_genie\`.
266
- `)),
267
- title: chartPlannerRequestSchema.shape.title.optional(),
268
- });
269
- /* ----------------------------- tool ids ----------------------------- */
270
- /**
271
- * Suffix appended to per-space tool ids when the alias isn't the
272
- * well-known `default`. Single-space deployments get the bare
273
- * names (`ask_genie`, `get_space_description`, ...); multi-space
274
- * deployments get `ask_genie_<alias>` etc. so each space's tools
275
- * stay disambiguated in the central agent's tool registry.
276
- */
277
- function aliasSuffix(alias) {
278
- if (alias === DEFAULT_GENIE_ALIAS)
279
- return "";
280
- const slug = stringUtils.toIdentifier(alias);
281
- return slug ? `_${slug}` : "";
282
- }
283
- /* --------------------------- per-space tools --------------------------- */
284
- /**
285
- * Drop `suggested_questions` attachments from a {@link GenieMessage}
286
- * before handing it to the central LLM. Those entries already
287
- * surface in the UI as one-tap pills via the writer's
288
- * `suggested_questions` events (see `collectSuggestions` on the
289
- * client); if we let them ride back in the tool result the LLM
290
- * tends to quote them inline in its prose, double-showing the
291
- * same questions and stepping on the dedicated suggestion UI.
292
- * Query / text / row attachments are preserved so the model can
293
- * still read `statement_id`, SQL, and the answer text.
294
- */
295
- function stripSuggestedQuestions(message) {
296
- const attachments = message.attachments;
297
- if (!attachments || attachments.length === 0)
298
- return message;
299
- const filtered = attachments.filter((att) => !att.suggested_questions);
300
- if (filtered.length === attachments.length)
301
- return message;
302
- return { ...message, attachments: filtered };
303
- }
304
- function buildAskGenieTool(opts) {
305
- const { spaceId, alias, hint } = opts;
306
- const toolId = `ask_genie${aliasSuffix(alias)}`;
307
- const hintLine = hint ? ` (${hint})` : "";
308
- return createTool({
309
- id: toolId,
310
- description: stringUtils.toDescription(`
311
- Ask the Genie space "${alias}"${hintLine} ONE focused
312
- natural-language sub-question and wait for the turn to
313
- complete. Genie answers best when each call covers a
314
- single metric / dimension / time window, so expect to
315
- call this tool MULTIPLE TIMES per user turn (typically
316
- two to six) and let the results from earlier calls inform
317
- later ones - that's the normal pattern, not the exception.
318
- Do NOT try to cram a multi-part question into a single
319
- call; decompose first, then ask each piece.
320
-
321
- Returns the final \`GenieMessage\`. Rows are NOT included -
322
- the Genie wire response carries the \`statement_id\` for any
323
- SQL that ran (at \`message.query_result.statement_id\` or the
324
- first attachment's \`query.statement_id\`); call
325
- \`get_statement\` with that id only when you need to read
326
- the underlying values to reason about them. If you just
327
- want to display the rows to the user, embed a
328
- \`[data:<statement_id>]\` marker in your prose instead -
329
- the host UI fetches and renders the rows on its own. Wire
330
- events (status, thinking, sql) stream to the user
331
- automatically while the call is in flight.
332
- `),
333
- inputSchema: z.object({
334
- question: z.string().min(1, "question is required"),
335
- }),
336
- outputSchema: z.object({
337
- message: GenieMessageSchema,
338
- }),
339
- execute: async ({ question }, ctxRaw) => {
340
- const ctx = ctxRaw;
341
- const { client, requestContext } = requireClient(ctx, toolId);
342
- const writer = ctx?.writer;
343
- const signal = ctx?.abortSignal;
344
- const threadId = requestContext.get(MASTRA_THREAD_ID_KEY);
345
- // Bounce placeholder / no-op questions BEFORE spending a Genie
346
- // round-trip on them. Genie answers any of these with "Your
347
- // request 'noop' does not relate to..." - useless noise that
348
- // shows up in the UI and eats one of the workspace's 5
349
- // questions/minute. Returning a clear error here surfaces the
350
- // issue to the agent loop so the model corrects course instead
351
- // of wasting a turn.
352
- const trimmed = question.trim();
353
- if (trimmed.length === 0 || PLACEHOLDER_QUESTIONS.has(trimmed.toLowerCase())) {
354
- throw new Error(`${toolId}: refusing placeholder question "${question}" - ` +
355
- `call ${toolId} only with a real natural-language question, ` +
356
- `or skip the call entirely`);
357
- }
358
- // Seed the active Genie `conversation_id` onto `RequestContext`
359
- // from the cross-request cache when a Mastra `threadId` is
360
- // present so multi-turn chats reuse the same Genie conversation
361
- // (and Genie's accumulated context) across separate user turns.
362
- // The same `RequestContext` is reused across every `ask_genie`
363
- // call within one user turn, so `ensureConversationSeeded`
364
- // hits the cache at most once per request per space.
365
- const cacheKey = await conversationCacheKey(spaceId, threadId);
366
- await ensureConversationSeeded(requestContext, spaceId, cacheKey);
367
- // Fire the lifecycle `started` event before any LLM /
368
- // network round-trip so the host UI can pop a "Thinking..."
369
- // pill the instant the model decides to delegate.
370
- const startedEvent = {
371
- type: "started",
372
- spaceId,
373
- content: question,
374
- };
375
- await safeWrite(log, writer, startedEvent);
376
- // Single turn of `genieEventChat`. Hoisted into a closure so
377
- // we can re-run it after evicting a stale `conversation_id`
378
- // without duplicating the event-loop body.
379
- const runTurn = async () => {
380
- const seedConversationId = readContextConversationId(requestContext, spaceId);
381
- let finalMessage;
382
- for await (const event of genieEventChat(spaceId, question, {
383
- workspaceClient: client,
384
- ...(seedConversationId ? { conversationId: seedConversationId } : {}),
385
- ...(signal ? { context: signal } : {}),
386
- })) {
387
- if (event.type !== "message") {
388
- await safeWrite(log, writer, event);
389
- }
390
- const eventConversationId = event.conversation_id;
391
- if (eventConversationId) {
392
- writeContextConversationId(requestContext, spaceId, eventConversationId);
393
- }
394
- if (event.type === "result") {
395
- finalMessage = event.message;
396
- }
397
- }
398
- if (!finalMessage) {
399
- throw new Error("Genie turn ended without a result event");
400
- }
401
- return finalMessage;
402
- };
403
- let finalMessage;
404
- try {
405
- finalMessage = await runTurn();
406
- }
407
- catch (err) {
408
- // The seeded `conversation_id` was rejected by Genie - most
409
- // commonly because it was deleted upstream, expired past
410
- // Databricks' (undocumented) lifetime, or was minted in a
411
- // different space. Drop both the cached id AND the
412
- // per-request value so the retry calls `startConversation`,
413
- // and try once more. Only retry when we *had* a seeded id -
414
- // a fresh call that 404s shouldn't loop.
415
- const seeded = readContextConversationId(requestContext, spaceId);
416
- if (seeded && isConversationGoneError(err)) {
417
- log.warn("conversation-cache:stale, resetting", {
418
- spaceId,
419
- conversationId: seeded,
420
- error: commonUtils.errorMessage(err),
421
- });
422
- await evictCachedConversationId(cacheKey);
423
- writeContextConversationId(requestContext, spaceId, undefined);
424
- finalMessage = await runTurn();
425
- }
426
- else {
427
- throw err;
428
- }
429
- }
430
- // Refresh the cache entry on every successful turn. Re-setting
431
- // the same key both persists newly-minted ids (cache miss path)
432
- // and extends the TTL on active conversations (sliding window).
433
- await saveCachedConversationId(cacheKey, readContextConversationId(requestContext, spaceId));
434
- return { message: stripSuggestedQuestions(finalMessage) };
435
- },
436
- });
437
- }
438
- function buildSpaceDescriptionTool(opts) {
439
- const { spaceId, alias } = opts;
440
- const toolId = `get_space_description${aliasSuffix(alias)}`;
441
- return createTool({
442
- id: toolId,
443
- description: stringUtils.toDescription(`
444
- Return the Genie space "${alias}"'s title, description, and
445
- warehouse id. Cheap (single REST call, no LLM round-trip).
446
- Call this FIRST on any user turn that's going to touch
447
- \`ask_genie\`, unless the same description already landed
448
- earlier in this conversation - the title + description tell
449
- you what tables, metrics, and time windows the space
450
- actually covers, which is what lets you decompose the
451
- user's question into the right \`ask_genie\` sub-questions.
452
- `),
453
- inputSchema: z.object({}),
454
- outputSchema: z.object({
455
- spaceId: z.string(),
456
- title: z.string().optional(),
457
- description: z.string().optional(),
458
- warehouseId: z.string().optional(),
459
- }),
460
- execute: async (_input, ctxRaw) => {
461
- const ctx = ctxRaw;
462
- const { client } = requireClient(ctx, toolId);
463
- const signal = ctx?.abortSignal;
464
- // Route through the package's central Genie space fetch. The
465
- // description surface (title / description / warehouse id) lives
466
- // on the directory-listing shape, so skip the larger
467
- // `serialized_space` payload here.
468
- const space = await getGenieSpace(spaceId, {
469
- workspaceClient: client,
470
- serialized: false,
471
- ...(signal ? { context: signal } : {}),
472
- });
473
- return {
474
- spaceId,
475
- ...(space.title ? { title: space.title } : {}),
476
- ...(space.description ? { description: space.description } : {}),
477
- ...(space.warehouse_id ? { warehouseId: space.warehouse_id } : {}),
478
- };
479
- },
480
- });
481
- }
482
- function buildSpaceSerializedTool(opts) {
483
- const { spaceId, alias } = opts;
484
- const toolId = `get_space_serialized${aliasSuffix(alias)}`;
485
- return createTool({
486
- id: toolId,
487
- description: stringUtils.toDescription(`
488
- Return the full \`GenieSpace\` JSON for the "${alias}" space.
489
- Use only when you need exact column / table identifiers
490
- \`get_space_description\` doesn't expose. Larger payload, so
491
- prefer the description tool when it's enough.
492
- `),
493
- inputSchema: z.object({}),
494
- outputSchema: z.object({ space: z.unknown() }),
495
- execute: async (_input, ctxRaw) => {
496
- const ctx = ctxRaw;
497
- const { client } = requireClient(ctx, toolId);
498
- const signal = ctx?.abortSignal;
499
- // Central Genie space fetch with the opt-in `serialized_space`
500
- // blob (catalogs, tables, sample questions, prompts) that the
501
- // typed SDK `getSpace` omits - the whole point of this tool.
502
- const space = await getGenieSpace(spaceId, {
503
- workspaceClient: client,
504
- ...(signal ? { context: signal } : {}),
505
- });
506
- return { space };
507
- },
508
- });
509
- }
510
- /* --------------------------- shared tools --------------------------- */
511
- /**
512
- * Default row cap for {@link buildGetStatementTool} when the agent
513
- * doesn't supply a `limit`. Sized to keep result sets out of the
514
- * model context unless the agent explicitly opts into more rows -
515
- * the cheap shape (column names + a handful of representative
516
- * rows) is usually enough to reason about a query.
517
- */
518
- const DEFAULT_STATEMENT_LIMIT = 50;
519
- function buildGetStatementTool() {
520
- const toolId = "get_statement";
521
- return createTool({
522
- id: toolId,
523
- description: stringUtils.toDescription(`
524
- Fetch the rows of a Genie statement by its \`statement_id\` (the
525
- value at \`message.query_result.statement_id\` or
526
- \`message.attachments[*].query.statement_id\` returned from
527
- \`ask_genie\`). Use this ONLY when you need to read the underlying
528
- values to reason about them in your reply - e.g. naming the
529
- largest row, computing a delta the visualization wouldn't already
530
- convey, or filtering down to a specific record. If you'd just be
531
- reciting numbers the user will see anyway, skip the call and
532
- embed a \`[data:<statement_id>]\` marker in your prose instead;
533
- the host UI fetches and renders the rows on its own. \`limit\`
534
- caps the number of rows returned (defaults to
535
- ${DEFAULT_STATEMENT_LIMIT}). \`rowCount\` reflects the full
536
- upstream total - compare to \`rows.length\` to detect truncation.
537
- `),
538
- inputSchema: z.object({
539
- statement_id: z.string().min(1, "statement_id is required"),
540
- limit: z
541
- .number()
542
- .int()
543
- .nonnegative()
544
- .optional()
545
- .describe("Max rows to return. Defaults to a small sample; raise only when more rows are genuinely needed."),
546
- }),
547
- outputSchema: z.object({
548
- columns: z.array(z.string()),
549
- rows: z.array(z.record(z.string(), z.unknown())),
550
- rowCount: z.number(),
551
- truncated: z.boolean(),
552
- }),
553
- execute: async ({ statement_id, limit }, ctxRaw) => {
554
- const ctx = ctxRaw;
555
- const { client } = requireClient(ctx, toolId);
556
- const signal = ctx?.abortSignal;
557
- const effectiveLimit = limit ?? DEFAULT_STATEMENT_LIMIT;
558
- const data = await fetchStatementData(client, statement_id, {
559
- limit: effectiveLimit,
560
- ...(signal ? { signal } : {}),
561
- });
562
- return {
563
- columns: data.columns,
564
- rows: data.rows,
565
- rowCount: data.rowCount,
566
- truncated: data.rows.length < data.rowCount,
567
- };
568
- },
569
- });
570
- }
571
- /**
572
- * `prepare_chart` Mastra tool. Thin wrapper over
573
- * {@link prepareChart} that resolves the dataset by fetching the
574
- * Genie statement's rows on demand. The tool mints a `chartId`
575
- * synchronously, caches an empty placeholder, and kicks off the
576
- * planner in the background so the agent loop never blocks. The
577
- * host UI resolves `[chart:<chartId>]` markers by reading the
578
- * cached {@link Chart} entry (1h TTL).
579
- *
580
- * Space-agnostic: a Genie `statement_id` is workspace-scoped, so
581
- * one shared `prepare_chart` tool covers every wired Genie space.
582
- *
583
- * Cancellation: deliberately does NOT forward the per-call
584
- * `abortSignal` to {@link prepareChart}. The planner task is
585
- * fire-and-forget background work; the tool's own `execute`
586
- * resolves the moment the `chartId` is minted, so the per-call
587
- * signal aborts the second the tool returns. The 1h cache TTL
588
- * caps abandoned entries.
589
- */
590
- function buildPrepareChartTool(opts) {
591
- const { config } = opts;
592
- const toolId = "prepare_chart";
593
- return createTool({
594
- id: toolId,
595
- description: stringUtils.toDescription([
596
- `
597
- Queue a chart for the rows of a Genie statement. Mints a
598
- short \`chartId\` synchronously and kicks off a BACKGROUND
599
- task that fetches the statement's rows, runs the
600
- chart-planner to pick a chart type and Echarts spec, and
601
- caches the result under the \`chartId\` for one hour. The
602
- host UI fetches the cached chart on its own once it lands.
603
- `,
604
- `
605
- To display the chart in your reply, embed
606
- \`[chart:<chartId>]\` on its own line at the position you
607
- want it to appear, using the EXACT \`chartId\` string this
608
- call returned. Never construct a chart id yourself (it is
609
- not the \`statement_id\` or any variation of it) - only a
610
- value returned by this tool resolves to a real chart. The
611
- tool returns immediately - do NOT wait or call it again to
612
- "check progress"; the chart resolves asynchronously on the
613
- host UI's side.
614
- `,
615
- `
616
- Use this only when the data has a story a chart conveys
617
- better than a table (trends, rankings, distributions,
618
- parts-of-a-whole). For raw rows, embed
619
- \`[data:<statement_id>]\` instead and skip this tool.
620
- `,
621
- ]),
622
- inputSchema: prepareChartRequestSchema,
623
- outputSchema: ChartSchema.pick({ chartId: true }),
624
- execute: async (request, ctxRaw) => {
625
- const ctx = ctxRaw;
626
- const { client } = requireClient(ctx, toolId);
627
- return prepareChart({
628
- config,
629
- ...(request.title ? { title: request.title } : {}),
630
- ...(request.description ? { description: request.description } : {}),
631
- resolveData: (taskSignal) => fetchStatementData(client, request.statement_id, {
632
- ...(taskSignal ? { signal: taskSignal } : {}),
633
- }),
634
- ...(ctx?.requestContext ? { requestContext: ctx.requestContext } : {}),
635
- });
636
- },
637
- });
638
- }
639
- /* --------------------------- orchestration prompt --------------------------- */
640
- /**
641
- * Suggested orchestration prompt for the central agent that owns
642
- * the Genie tools. Compose into your agent's `instructions` to
643
- * get the canonical "decompose questions, ask Genie focused
644
- * sub-questions, place data / chart markers in prose" behavior:
645
- *
646
- * ```ts
647
- * createAgent({
648
- * instructions: `${myAgentInstructions}\n\n${GENIE_INSTRUCTIONS}`,
649
- * tools(plugins) {
650
- * return { ...plugins.genie?.toolkit() };
651
- * },
652
- * });
653
- * ```
654
- *
655
- * The prompt references the bare tool names (`ask_genie`,
656
- * `get_space_description`, `get_space_serialized`,
657
- * `get_statement`, `prepare_chart`) used for the single-space
658
- * default alias. Multi-space deployments should write their own
659
- * variant that names the suffixed per-space tools
660
- * (e.g. `ask_genie_sales`).
661
- */
662
- export const GENIE_INSTRUCTIONS = stringUtils.toDescription([
663
- "Genie orchestration. For every user question that needs SQL-backed data:",
664
- {
665
- numbered: [
666
- `
667
- Start by calling \`get_space_description\` to ground yourself
668
- in what the space covers (tables, metrics, time windows),
669
- unless you already saw the same description earlier in this
670
- conversation. Reach for \`get_space_serialized\` only when you
671
- need exact column / table identifiers the description doesn't
672
- expose - it's a much larger payload.
673
- `,
674
- `
675
- Decompose the user's question into focused sub-questions
676
- BEFORE asking Genie anything. One sub-question per distinct
677
- metric, dimension, or time window. Then call \`ask_genie\`
678
- once per sub-question - usually two to six calls per turn,
679
- and let earlier answers inform what you ask next. Cramming
680
- a multi-part question into one \`ask_genie\` call almost
681
- always produces a worse answer than asking the pieces
682
- separately. Only collapse to a single call when the question
683
- is genuinely atomic ("what was Q3 revenue?").
684
-
685
- Worked example: user asks "How did SKU 1234's revenue
686
- compare to its category average last quarter, and which
687
- regions drove the gap?" Decomposes to: (a) \`ask_genie\`
688
- for SKU 1234's Q3 revenue, (b) \`ask_genie\` for the
689
- category-average Q3 revenue, (c) \`ask_genie\` for SKU
690
- 1234's Q3 revenue split by region. Three focused calls,
691
- each grounded in the prior results.
692
- `,
693
- `
694
- Each \`ask_genie\` call returns the terminal \`GenieMessage\`.
695
- When the turn ran SQL the result has a \`statement_id\` - read
696
- it from \`message.query_result.statement_id\` (or the first
697
- attachment's \`query.statement_id\`).
698
- `,
699
- [
700
- `
701
- To DISPLAY a result set in your reply, embed a marker on its
702
- own line where the visualization should appear. Two marker
703
- shapes:
704
- `,
705
- {
706
- bullets: [
707
- `
708
- \`[data:<statement_id>]\` - render the rows as a table.
709
- Use this when there's no clear visual story (long lists,
710
- reference data, single-row results, or the user just
711
- wants to see the data). Embed the marker directly; no
712
- tool call needed.
713
- `,
714
- `
715
- \`[chart:<chartId>]\` - render the rows as a chart. To
716
- get a \`<chartId>\`, call \`prepare_chart\` with the
717
- statement's id (and an optional \`title\` / one-line
718
- \`description\` of the insight to surface). The tool
719
- returns the \`chartId\` synchronously and prepares the
720
- chart spec in the background; embed the returned id as
721
- \`[chart:<chartId>]\` on its own line wherever the
722
- chart should appear. Use a chart when the data has a
723
- story a visual conveys better than a table (trends,
724
- rankings, distributions, parts-of-a-whole).
725
-
726
- NEVER invent or hand-build a \`<chartId>\`. A valid
727
- \`<chartId>\` is the opaque token a \`prepare_chart\`
728
- call returned to you in THIS turn - nothing else. It
729
- is NOT a \`statement_id\`, and it is NOT a
730
- \`statement_id\` prefix with a label appended (e.g.
731
- \`01f1...-region-fill\`). If you have not called
732
- \`prepare_chart\` and received an id back, do not write
733
- a \`[chart:...]\` marker at all - use \`[data:...]\`
734
- instead. A fabricated chart id renders nothing and
735
- wastes a request.
736
- `,
737
- ],
738
- },
739
- `
740
- The host UI resolves both markers on its own once it sees
741
- them - you do NOT need to call \`get_statement\` just to
742
- display data, and you do NOT need to wait on
743
- \`prepare_chart\` (it returns the id immediately and the
744
- host UI fetches the cached chart later). Pick at most one
745
- marker per statement; don't chart AND table the same result
746
- side by side.
747
- `,
748
- ],
749
- `
750
- Call \`get_statement(statement_id, limit?)\` ONLY when you need
751
- to read the actual values to reason about them (e.g. naming a
752
- specific row, computing a delta the table or chart wouldn't
753
- show, or sanity-checking a result before interpreting it). If
754
- you'd just be reciting numbers the visualization already shows,
755
- skip the call and use a marker instead. \`limit\` defaults to a
756
- small sample; raise it only when you genuinely need more rows.
757
- `,
758
- `
759
- Compose your final reply as plain prose. Interleave paragraphs
760
- with \`[data:...]\` / \`[chart:...]\` markers wherever a result
761
- should render. Don't dump all markers at the end - place each
762
- one next to the prose that interprets it. Don't restate every
763
- number the visualization already shows; call out deltas,
764
- anomalies, takeaways.
765
- `,
766
- ],
767
- },
768
- ]);
769
- /* --------------------- multi-alias surface --------------------- */
770
- /**
771
- * Normalize the {@link GenieSpacesConfig} record. Bare-string
772
- * entries (`{ default: "01ef..." }`) get wrapped as
773
- * `{ spaceId: "01ef..." }`; object entries pass through unchanged.
774
- * `undefined` and empty-string values are dropped so callers can
775
- * pass `process.env.X` directly (matches AppKit `genie()`'s
776
- * defensive treatment of unset env vars).
777
- */
778
- export function normalizeGenieSpaces(spaces) {
779
- if (!spaces)
780
- return {};
781
- const out = {};
782
- for (const [alias, value] of Object.entries(spaces)) {
783
- if (value === undefined)
784
- continue;
785
- if (typeof value === "string") {
786
- if (!value)
787
- continue;
788
- out[alias] = { spaceId: value };
789
- continue;
790
- }
791
- if (!value.spaceId)
792
- continue;
793
- out[alias] = value;
794
- }
795
- return out;
796
- }
797
- /**
798
- * Discover Genie space aliases from every supported source and
799
- * merge them into a single record. Precedence (highest first):
800
- *
801
- * 1. {@link MastraPluginConfig.genieSpaces} on the `mastra(...)`
802
- * call. Explicit Mastra wiring always wins so users can
803
- * override AppKit's defaults per-agent.
804
- * 2. AppKit `genie({ spaces: { ... } })` plugin instance. Lets
805
- * users keep using the existing AppKit config format
806
- * (`genie({ spaces: { sales: "...", ops: "..." } })`)
807
- * without restating the same record on the Mastra plugin.
808
- * Read off the live plugin instance via a structural cast
809
- * since `Plugin.config` is TS-protected (not runtime-private).
810
- * 3. `DATABRICKS_GENIE_SPACE_ID` env var (registered under the
811
- * well-known `default` alias). Matches the AppKit `genie()`
812
- * plugin's fallback behavior so a bare `mastra()` + `genie()`
813
- * pair just works.
814
- *
815
- * Aliases collide cleanly: a higher-precedence source's value
816
- * replaces a lower one's wholesale. Sources that contribute zero
817
- * aliases (or contribute only `undefined` / empty entries) are
818
- * silently ignored.
819
- */
820
- export function resolveGenieSpaces(config, context) {
821
- const merged = {};
822
- // Source 3 (lowest precedence): env var.
823
- const envSpaceId = process.env["DATABRICKS_GENIE_SPACE_ID"];
824
- if (envSpaceId) {
825
- merged[DEFAULT_GENIE_ALIAS] = { spaceId: envSpaceId };
826
- }
827
- // Source 2: AppKit `genie()` plugin instance config. Use a
828
- // structural cast - `Plugin.config` is `protected` in TS only,
829
- // and the runtime layout is plain object property access.
830
- const geniePlugin = appkitUtils.instance(context, genie);
831
- if (geniePlugin) {
832
- const pluginSpaces = geniePlugin
833
- .config?.spaces;
834
- if (pluginSpaces) {
835
- Object.assign(merged, normalizeGenieSpaces(pluginSpaces));
836
- }
837
- }
838
- // Source 1 (highest precedence): explicit Mastra wiring.
839
- if (config.genieSpaces) {
840
- Object.assign(merged, normalizeGenieSpaces(config.genieSpaces));
841
- }
842
- return merged;
843
- }
844
- /**
845
- * Build the flat Mastra tools record for every configured Genie
846
- * space. Two shared, space-agnostic tools (`get_statement`,
847
- * `prepare_chart`) are registered once regardless of how many
848
- * spaces are wired; the per-space tools (`ask_genie`,
849
- * `get_space_description`, `get_space_serialized`) are suffixed
850
- * with `_<alias>` for non-default aliases so multi-space
851
- * deployments stay disambiguated.
852
- *
853
- * Returns a record keyed by tool id, ready to spread into the
854
- * central `Agent`'s `tools` map (or surfaced via the
855
- * `plugins.genie?.toolkit()` callback). Returns an empty record
856
- * when `spaces` resolves to zero entries so the caller can spread
857
- * safely.
858
- */
859
- export function buildGenieTools(opts) {
860
- const normalized = normalizeGenieSpaces(opts.spaces);
861
- const tools = {};
862
- if (Object.keys(normalized).length === 0)
863
- return tools;
864
- // Shared, space-agnostic tools.
865
- tools.get_statement = buildGetStatementTool();
866
- tools.prepare_chart = buildPrepareChartTool({ config: opts.config });
867
- for (const [alias, space] of Object.entries(normalized)) {
868
- const askTool = buildAskGenieTool({
869
- spaceId: space.spaceId,
870
- alias,
871
- ...(space.hint ? { hint: space.hint } : {}),
872
- });
873
- const descTool = buildSpaceDescriptionTool({ spaceId: space.spaceId, alias });
874
- const serTool = buildSpaceSerializedTool({ spaceId: space.spaceId, alias });
875
- tools[askTool.id] = askTool;
876
- tools[descTool.id] = descTool;
877
- tools[serTool.id] = serTool;
878
- }
879
- return tools;
880
- }
881
- /**
882
- * Plugin-toolkit adapter so the `plugins.genie?.toolkit()` lookup
883
- * inside an agent's `tools(plugins)` callback returns the
884
- * flat Genie tools record instead of throwing on missing plugin.
885
- * Mirrors AppKit's `PluginToolkitProvider` shape.
886
- */
887
- export function buildGenieToolkitProvider(opts) {
888
- return {
889
- toolkit(_opts) {
890
- return buildGenieTools(opts);
891
- },
892
- };
893
- }
894
- /* --------------------------- starter suggestions --------------------------- */
895
- /**
896
- * Default cap on starter suggestions surfaced to the chat empty
897
- * state. Sample-question lists can run long (10+ on a curated
898
- * space); a handful of one-tap prompts reads better than a wall of
899
- * buttons.
900
- */
901
- const SUGGESTION_LIMIT = 6;
902
- /**
903
- * How long a space's parsed sample questions stay cached. They're
904
- * authored config that changes rarely, and the lookup is an extra
905
- * REST round-trip per chat mount, so a few minutes of caching keeps
906
- * the empty state instant on reload without going stale for long.
907
- */
908
- const SUGGESTION_CACHE_TTL_MS = 10 * 60_000;
909
- /** Space-id -> cached sample questions with an absolute expiry. */
910
- const _suggestionCache = new Map();
911
- /** Read a space's cached questions, or `undefined` on miss / expiry. */
912
- function readSuggestionCache(spaceId) {
913
- const entry = _suggestionCache.get(spaceId);
914
- if (!entry)
915
- return undefined;
916
- if (entry.expires <= Date.now()) {
917
- _suggestionCache.delete(spaceId);
918
- return undefined;
919
- }
920
- return entry.questions;
921
- }
922
- /** Cache a space's parsed questions for {@link SUGGESTION_CACHE_TTL_MS}. */
923
- function writeSuggestionCache(spaceId, questions) {
924
- _suggestionCache.set(spaceId, {
925
- questions,
926
- expires: Date.now() + SUGGESTION_CACHE_TTL_MS,
927
- });
928
- }
929
- /**
930
- * Collect the curated starter questions across every resolved Genie
931
- * space, deduped and capped. Each space's `sample_questions` are
932
- * fetched once (cached for {@link SUGGESTION_CACHE_TTL_MS}) via
933
- * {@link getGenieSpace} + {@link genieSampleQuestions}, then merged in
934
- * alias-iteration order so a single-space app surfaces that space's
935
- * questions and a multi-space app round-trips breadth-first up to the
936
- * cap. A per-space fetch failure degrades to "no questions for that
937
- * space" (logged, not thrown) so one unreachable space never blanks
938
- * the whole list. Returns `[]` when no spaces are configured.
939
- */
940
- export async function collectSpaceSuggestions(opts) {
941
- const limit = opts.limit ?? SUGGESTION_LIMIT;
942
- const merged = [];
943
- const seen = new Set();
944
- for (const { spaceId } of Object.values(opts.spaces)) {
945
- let questions = readSuggestionCache(spaceId);
946
- if (!questions) {
947
- try {
948
- const space = await getGenieSpace(spaceId, {
949
- workspaceClient: opts.client,
950
- ...(opts.signal ? { context: opts.signal } : {}),
951
- });
952
- questions = genieSampleQuestions(space);
953
- writeSuggestionCache(spaceId, questions);
954
- }
955
- catch (err) {
956
- log.warn("suggestions:fetch-error", {
957
- spaceId,
958
- error: commonUtils.errorMessage(err),
959
- });
960
- questions = [];
961
- }
962
- }
963
- for (const question of questions) {
964
- if (seen.has(question))
965
- continue;
966
- seen.add(question);
967
- merged.push(question);
968
- if (merged.length >= limit)
969
- return merged;
970
- }
971
- }
972
- return merged;
973
- }