@dbx-tools/appkit-mastra 0.1.5 → 0.1.10

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