@dbx-tools/appkit-mastra 0.1.58 → 0.1.68

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