@dbx-tools/appkit-mastra 0.1.67 → 0.1.68

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