@dbx-tools/appkit-mastra 0.1.57 → 0.1.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +41 -1
  2. package/dist/index.d.ts +1229 -17
  3. package/dist/index.js +3348 -19
  4. package/package.json +17 -27
  5. package/src/agents.ts +7 -1
  6. package/src/config.ts +64 -0
  7. package/src/genie.ts +9 -21
  8. package/{index.ts → src/index.ts} +7 -9
  9. package/src/mcp.ts +89 -0
  10. package/src/model.ts +9 -3
  11. package/src/plugin.ts +51 -8
  12. package/src/serving.ts +5 -9
  13. package/src/statement.ts +8 -36
  14. package/dist/src/agents.d.ts +0 -316
  15. package/dist/src/agents.js +0 -470
  16. package/dist/src/chart.d.ts +0 -153
  17. package/dist/src/chart.js +0 -570
  18. package/dist/src/config.d.ts +0 -295
  19. package/dist/src/config.js +0 -55
  20. package/dist/src/genie.d.ts +0 -161
  21. package/dist/src/genie.js +0 -973
  22. package/dist/src/history.d.ts +0 -95
  23. package/dist/src/history.js +0 -278
  24. package/dist/src/memory.d.ts +0 -109
  25. package/dist/src/memory.js +0 -253
  26. package/dist/src/model.d.ts +0 -52
  27. package/dist/src/model.js +0 -198
  28. package/dist/src/observability.d.ts +0 -64
  29. package/dist/src/observability.js +0 -83
  30. package/dist/src/plugin.d.ts +0 -177
  31. package/dist/src/plugin.js +0 -554
  32. package/dist/src/processor.d.ts +0 -8
  33. package/dist/src/processor.js +0 -40
  34. package/dist/src/processors/strip-stale-charts.d.ts +0 -32
  35. package/dist/src/processors/strip-stale-charts.js +0 -98
  36. package/dist/src/server.d.ts +0 -51
  37. package/dist/src/server.js +0 -152
  38. package/dist/src/serving.d.ts +0 -65
  39. package/dist/src/serving.js +0 -79
  40. package/dist/src/statement.d.ts +0 -66
  41. package/dist/src/statement.js +0 -111
  42. package/dist/src/writer.d.ts +0 -23
  43. package/dist/src/writer.js +0 -37
  44. package/dist/tsconfig.build.tsbuildinfo +0 -1
package/dist/index.d.ts CHANGED
@@ -1,20 +1,1232 @@
1
+ import { Chart } from "@dbx-tools/appkit-mastra-shared";
2
+ import { ServingEndpointSummary } from "@dbx-tools/model";
3
+ import { appkitUtils, logUtils } from "@dbx-tools/shared";
4
+ import * as _mastra_core_agent0 from "@mastra/core/agent";
5
+ import { Agent, AgentConfig, ToolsInput } from "@mastra/core/agent";
6
+ import * as _mastra_core_tools0 from "@mastra/core/tools";
7
+ import { Tool, createTool } from "@mastra/core/tools";
8
+ import * as _databricks_appkit0 from "@databricks/appkit";
9
+ import { BasePluginConfig, IAppRouter, Plugin, ResourceRequirement } from "@databricks/appkit";
10
+ import { z } from "zod";
11
+ import { RequestContext } from "@mastra/core/request-context";
12
+ import { WorkspaceClient } from "@databricks/sdk-experimental";
13
+ import { MCPServer } from "@mastra/mcp";
14
+ import { Mastra } from "@mastra/core/mastra";
15
+ import express from "express";
16
+ import { Memory } from "@mastra/memory";
17
+ import { PgVectorConfig, PostgresStore, PostgresStoreConfig } from "@mastra/pg";
18
+ import { Pool } from "pg";
19
+ import { MastraServer } from "@mastra/express";
20
+ import * as _mastra_core_workflows0 from "@mastra/core/workflows";
21
+ import * as _mastra_core_vector0 from "@mastra/core/vector";
22
+ import * as _mastra_core_tts0 from "@mastra/core/tts";
23
+ import * as _mastra_core_logger0 from "@mastra/core/logger";
24
+ import * as _mastra_core_mcp0 from "@mastra/core/mcp";
25
+ import * as _mastra_core_evals0 from "@mastra/core/evals";
26
+ import * as _mastra_core_processors0 from "@mastra/core/processors";
27
+ import * as _mastra_core_memory0 from "@mastra/core/memory";
28
+ import * as _mastra_core_channels0 from "@mastra/core/channels";
29
+ export * from "@dbx-tools/appkit-mastra-shared";
30
+ export * from "@dbx-tools/model";
31
+
32
+ //#region packages/appkit-mastra/src/genie.d.ts
33
+ /** Default alias used when a single unnamed Genie space is wired up. */
34
+ declare const DEFAULT_GENIE_ALIAS = "default";
35
+ /** Per-space Genie agent configuration. */
36
+ interface GenieSpaceConfig {
37
+ /** Genie `space_id`. Required; resolves via `client.genie.getSpace`. */
38
+ spaceId: string;
39
+ /**
40
+ * Optional human-readable description appended to the per-space
41
+ * tool descriptions so the calling LLM has hints about *what
42
+ * data* this space covers (e.g. "orders, returns,
43
+ * fulfillment"). When omitted, only the space's own
44
+ * `description` (fetched on first use of `get_space_description`)
45
+ * is shown.
46
+ */
47
+ hint?: string;
48
+ }
49
+ /** Map of alias -> space config. Accepts either explicit objects or bare space ids. */
50
+ type GenieSpacesConfig = Record<string, GenieSpaceConfig | string>;
1
51
  /**
2
- * Server-side entry point for the AppKit Mastra integration. Mounts
3
- * the plugin via {@link mastra} and re-exports the full server surface
4
- * (config, agent wiring, Genie and chart tooling, and dynamic Model
5
- * Serving resolution) so apps build agent backends from one import.
52
+ * Suggested orchestration prompt for the central agent that owns
53
+ * the Genie tools. Compose into your agent's `instructions` to
54
+ * get the canonical "decompose questions, ask Genie focused
55
+ * sub-questions, place data / chart markers in prose" behavior:
6
56
  *
7
- * Client-side consumers should import URL helpers and the
8
- * {@link MastraClientConfig} type from `@dbx-tools/appkit-mastra-shared`
9
- * instead - that package is pure (no pg / fastembed / Mastra deps) and
10
- * is the right surface for browser bundles and `usePluginClientConfig`
11
- * consumers.
57
+ * ```ts
58
+ * createAgent({
59
+ * instructions: `${myAgentInstructions}\n\n${GENIE_INSTRUCTIONS}`,
60
+ * tools(plugins) {
61
+ * return { ...plugins.genie?.toolkit() };
62
+ * },
63
+ * });
64
+ * ```
65
+ *
66
+ * The prompt references the bare tool names (`ask_genie`,
67
+ * `get_space_description`, `get_space_serialized`,
68
+ * `get_statement`, `prepare_chart`) used for the single-space
69
+ * default alias. Multi-space deployments should write their own
70
+ * variant that names the suffixed per-space tools
71
+ * (e.g. `ask_genie_sales`).
12
72
  */
13
- export * from "@dbx-tools/appkit-mastra-shared";
14
- export * from "@dbx-tools/model";
15
- export * from "./src/agents.js";
16
- export * from "./src/chart.js";
17
- export * from "./src/config.js";
18
- export * from "./src/genie.js";
19
- export * from "./src/plugin.js";
20
- export { MASTRA_MODEL_OVERRIDE_KEY, MODEL_OVERRIDE_BODY_FIELDS, MODEL_OVERRIDE_HEADER, MODEL_OVERRIDE_QUERY, extractModelOverride, type ModelOverrideRequest, } from "./src/serving.js";
73
+ declare const GENIE_INSTRUCTIONS: string;
74
+ /**
75
+ * Normalize the {@link GenieSpacesConfig} record. Bare-string
76
+ * entries (`{ default: "01ef..." }`) get wrapped as
77
+ * `{ spaceId: "01ef..." }`; object entries pass through unchanged.
78
+ * `undefined` and empty-string values are dropped so callers can
79
+ * pass `process.env.X` directly (matches AppKit `genie()`'s
80
+ * defensive treatment of unset env vars).
81
+ */
82
+ declare function normalizeGenieSpaces(spaces: GenieSpacesConfig | Record<string, string | GenieSpaceConfig | undefined> | undefined): Record<string, GenieSpaceConfig>;
83
+ /**
84
+ * Discover Genie space aliases from every supported source and
85
+ * merge them into a single record. Precedence (highest first):
86
+ *
87
+ * 1. {@link MastraPluginConfig.genieSpaces} on the `mastra(...)`
88
+ * call. Explicit Mastra wiring always wins so users can
89
+ * override AppKit's defaults per-agent.
90
+ * 2. AppKit `genie({ spaces: { ... } })` plugin instance. Lets
91
+ * users keep using the existing AppKit config format
92
+ * (`genie({ spaces: { sales: "...", ops: "..." } })`)
93
+ * without restating the same record on the Mastra plugin.
94
+ * Read off the live plugin instance via a structural cast
95
+ * since `Plugin.config` is TS-protected (not runtime-private).
96
+ * 3. `DATABRICKS_GENIE_SPACE_ID` env var (registered under the
97
+ * well-known `default` alias). Matches the AppKit `genie()`
98
+ * plugin's fallback behavior so a bare `mastra()` + `genie()`
99
+ * pair just works.
100
+ *
101
+ * Aliases collide cleanly: a higher-precedence source's value
102
+ * replaces a lower one's wholesale. Sources that contribute zero
103
+ * aliases (or contribute only `undefined` / empty entries) are
104
+ * silently ignored.
105
+ */
106
+ declare function resolveGenieSpaces(config: MastraPluginConfig, context: appkitUtils.PluginContextLike | undefined): Record<string, GenieSpaceConfig>;
107
+ /**
108
+ * Build the flat Mastra tools record for every configured Genie
109
+ * space. Two shared, space-agnostic tools (`get_statement`,
110
+ * `prepare_chart`) are registered once regardless of how many
111
+ * spaces are wired; the per-space tools (`ask_genie`,
112
+ * `get_space_description`, `get_space_serialized`) are suffixed
113
+ * with `_<alias>` for non-default aliases so multi-space
114
+ * deployments stay disambiguated.
115
+ *
116
+ * Returns a record keyed by tool id, ready to spread into the
117
+ * central `Agent`'s `tools` map (or surfaced via the
118
+ * `plugins.genie?.toolkit()` callback). Returns an empty record
119
+ * when `spaces` resolves to zero entries so the caller can spread
120
+ * safely.
121
+ */
122
+ declare function buildGenieTools(opts: {
123
+ spaces: GenieSpacesConfig | Record<string, GenieSpaceConfig>;
124
+ config: MastraPluginConfig;
125
+ }): MastraTools;
126
+ /**
127
+ * Plugin-toolkit adapter so the `plugins.genie?.toolkit()` lookup
128
+ * inside an agent's `tools(plugins)` callback returns the
129
+ * flat Genie tools record instead of throwing on missing plugin.
130
+ * Mirrors AppKit's `PluginToolkitProvider` shape.
131
+ */
132
+ declare function buildGenieToolkitProvider(opts: {
133
+ spaces: GenieSpacesConfig | Record<string, GenieSpaceConfig>;
134
+ config: MastraPluginConfig;
135
+ }): {
136
+ toolkit(opts?: unknown): MastraTools;
137
+ };
138
+ /**
139
+ * Collect the curated starter questions across every resolved Genie
140
+ * space, deduped and capped. Each space's `sample_questions` are
141
+ * fetched once (cached for {@link SUGGESTION_CACHE_TTL_MS}) via
142
+ * {@link getGenieSpace} + {@link genieSampleQuestions}, then merged in
143
+ * alias-iteration order so a single-space app surfaces that space's
144
+ * questions and a multi-space app round-trips breadth-first up to the
145
+ * cap. A per-space fetch failure degrades to "no questions for that
146
+ * space" (logged, not thrown) so one unreachable space never blanks
147
+ * the whole list. Returns `[]` when no spaces are configured.
148
+ */
149
+ declare function collectSpaceSuggestions(opts: {
150
+ spaces: Record<string, GenieSpaceConfig>;
151
+ client: WorkspaceClient;
152
+ signal?: AbortSignal;
153
+ limit?: number;
154
+ }): Promise<string[]>;
155
+ //#endregion
156
+ //#region packages/appkit-mastra/src/config.d.ts
157
+ /**
158
+ * `RequestContext` key under which {@link MastraServer} stores the
159
+ * resolved AppKit user. `model.ts` reads it to mint user-scoped
160
+ * Databricks tokens.
161
+ */
162
+ declare const MASTRA_USER_KEY = "mastra__user";
163
+ /**
164
+ * `RequestContext` keys for AppKit user metadata stamped by
165
+ * {@link MastraServer}. Surfaced as trace metadata via
166
+ * {@link TRACE_REQUEST_CONTEXT_KEYS} so traces are filterable by who
167
+ * issued the request without leaking the full user object.
168
+ */
169
+ declare const MASTRA_USER_NAME_KEY = "mastra__userName";
170
+ declare const MASTRA_USER_EMAIL_KEY = "mastra__userEmail";
171
+ /**
172
+ * `RequestContext` key for the per-HTTP-request id stamped by
173
+ * {@link MastraServer}. Reads `X-Request-Id` from the incoming
174
+ * headers when present (so an upstream load balancer / API gateway
175
+ * can keep its trace correlation), falls back to a freshly minted
176
+ * UUID. Echoed back on the response and surfaced on every span via
177
+ * {@link TRACE_REQUEST_CONTEXT_KEYS} so logs and traces share a
178
+ * join key.
179
+ */
180
+ declare const MASTRA_REQUEST_ID_KEY = "mastra__requestId";
181
+ /**
182
+ * Canonical list of `RequestContext` keys we want Mastra to extract
183
+ * as metadata on every observability span (agent runs, model calls,
184
+ * tool invocations, workflow steps).
185
+ *
186
+ * Mirrors {@link https://mastra.ai/docs/observability/tracing/overview#automatic-metadata-from-requestcontext}:
187
+ * passed verbatim into `Observability.configs[*].requestContextKeys`,
188
+ * so any key listed here is read from `RequestContext` at trace
189
+ * start and attached as scalar span metadata. Keep the set to plain
190
+ * scalars - never include {@link MASTRA_USER_KEY} (it carries the
191
+ * full AppKit execution context with a `WorkspaceClient` reference).
192
+ *
193
+ * Order is purely cosmetic; Mastra de-dupes internally.
194
+ */
195
+ declare const TRACE_REQUEST_CONTEXT_KEYS: readonly string[];
196
+ /** AppKit execution context plus the canonical user id. */
197
+ interface User {
198
+ id: string;
199
+ executionContext: appkitUtils.ExecutionContextLike;
200
+ }
201
+ /** PgVector config with an optional Mastra store id. */
202
+ type MastraMemoryConfig = PgVectorConfig & {
203
+ id?: string;
204
+ };
205
+ /**
206
+ * Fine-grained control for the optional MCP server exposure
207
+ * ({@link MastraPluginConfig.mcp}). Every field is optional; the object
208
+ * form only needs to set what differs from the defaults.
209
+ */
210
+ interface MastraMcpConfig {
211
+ /**
212
+ * Server id used in the route path (`/mcp/<serverId>/...`) and as the
213
+ * MCP registry id. Defaults to the plugin's registered name.
214
+ */
215
+ serverId?: string;
216
+ /** Display name advertised over MCP. Defaults to `"<displayName> MCP"`. */
217
+ name?: string;
218
+ /** Semantic version advertised over MCP. Defaults to `"1.0.0"`. */
219
+ version?: string;
220
+ /** Optional human-readable description advertised over MCP. */
221
+ description?: string;
222
+ /**
223
+ * Expose every registered agent as an `ask_<agentId>` MCP tool.
224
+ * Defaults to `true` - this is the "leverage the Mastra agents over
225
+ * MCP" behavior most callers want.
226
+ */
227
+ agents?: boolean;
228
+ /**
229
+ * Also expose the plugin's ambient tools (the built-in `render_data`
230
+ * plus anything in `config.tools`) as MCP tools. Defaults to `false`:
231
+ * the ambient tools assume an in-process chat turn (they publish
232
+ * writer events the chat UI consumes), so they aren't useful to a
233
+ * standalone MCP client. Turn this on only when those tools are safe
234
+ * to call out-of-band.
235
+ */
236
+ tools?: boolean;
237
+ /**
238
+ * Extra tools to expose over MCP beyond the agent / ambient sets.
239
+ * Use this for tools written specifically for MCP consumers.
240
+ */
241
+ extraTools?: MastraTools;
242
+ }
243
+ /** Configuration accepted by the Mastra AppKit plugin. */
244
+ interface MastraPluginConfig extends BasePluginConfig {
245
+ /** Mastra OpenAI-compatible provider id. Defaults to `"databricks"`. */
246
+ providerId?: string;
247
+ /**
248
+ * PostgresStore for Mastra threads/messages. `true` reuses the
249
+ * `lakebase` plugin's pool; an object opens a dedicated store.
250
+ */
251
+ storage?: boolean | PostgresStoreConfig;
252
+ /**
253
+ * PgVector store for Mastra memory recall. `true` reuses the
254
+ * `lakebase` plugin's pool; an object opens a dedicated store.
255
+ */
256
+ memory?: boolean | MastraMemoryConfig;
257
+ /**
258
+ * Code-defined agents. Accepts three shapes for convenience:
259
+ *
260
+ * - **Record**: `{ analyst: def, helper: def }` - keys become the
261
+ * registered ids and the first key is the default.
262
+ * - **Single definition**: `def` - registered under
263
+ * `slugify(def.name)` (or `"default"` when `name` is omitted) and
264
+ * automatically marked as the default agent.
265
+ * - **Array**: `[def1, def2]` - each registered under
266
+ * `slugify(def.name)` (or `agent_${i}` when `name` is omitted);
267
+ * the first entry is the default.
268
+ *
269
+ * Each entry becomes a Mastra `Agent` reachable at
270
+ * `/api/<plugin>/route/chat/<id>` (the chat route also matches
271
+ * `:agentId`). When `agents` is omitted entirely, the plugin
272
+ * registers a single built-in `default` analyst so the bare
273
+ * `mastra()` call still mounts a working chat endpoint.
274
+ *
275
+ * @example Single-agent shorthand
276
+ * ```ts
277
+ * mastra({
278
+ * agents: createAgent({ instructions: "..." }),
279
+ * });
280
+ * ```
281
+ *
282
+ * @example Array
283
+ * ```ts
284
+ * mastra({
285
+ * agents: [
286
+ * createAgent({ name: "analyst", instructions: "..." }),
287
+ * createAgent({ name: "helper", instructions: "..." }),
288
+ * ],
289
+ * });
290
+ * ```
291
+ *
292
+ * @example Record (explicit ids)
293
+ * ```ts
294
+ * mastra({
295
+ * agents: {
296
+ * analyst: createAgent({ instructions: "..." }),
297
+ * helper: createAgent({ instructions: "..." }),
298
+ * },
299
+ * defaultAgent: "analyst",
300
+ * });
301
+ * ```
302
+ */
303
+ agents?: Record<string, MastraAgentDefinition> | MastraAgentDefinition | MastraAgentDefinition[];
304
+ /**
305
+ * Ambient tools spread into every registered agent's tools record;
306
+ * per-agent tools win on key collision. Use for a small shared
307
+ * library; for per-agent tools set `agents[id].tools` instead.
308
+ */
309
+ tools?: MastraTools;
310
+ /**
311
+ * Agent id used when the client doesn't specify one (the bare,
312
+ * un-suffixed history / suggestions routes resolve to it).
313
+ * Defaults to the first key in `agents` (or `"default"` when
314
+ * `agents` is omitted). Must match an id in `agents` when both are
315
+ * set; a mismatch throws at setup with the available candidates.
316
+ */
317
+ defaultAgent?: string;
318
+ /**
319
+ * Plugin-level default model applied to every agent that omits its
320
+ * own `model`. Mirrors AppKit's `agents({ defaultModel })`.
321
+ *
322
+ * - `string`: shorthand for "use the OBO auto-resolver but swap the
323
+ * `modelId`" (e.g. `"databricks-claude-sonnet-4-6"`).
324
+ * - Any other Mastra `DynamicArgument<MastraModelConfig>`: passed
325
+ * through verbatim. Use this when you need full control over auth
326
+ * or `providerId`.
327
+ *
328
+ * Resolution order per agent: `def.model` → `defaultModel` →
329
+ * built-in `/serving-endpoints` resolver.
330
+ */
331
+ defaultModel?: AgentConfig["model"] | string;
332
+ /**
333
+ * Allow loose model names (`"claude sonnet"`) to be fuzzy-matched
334
+ * against the workspace's Model Serving endpoints. Defaults to
335
+ * `true`; set `false` to require exact endpoint names everywhere.
336
+ */
337
+ modelFuzzyMatch?: boolean;
338
+ /**
339
+ * Fuse.js score threshold for the fuzzy matcher (0 = exact match,
340
+ * 1 = anything matches). Defaults to `0.4`. Lower values reject
341
+ * loose matches; raise it if you have a sprawling endpoint
342
+ * catalogue with similar-looking names.
343
+ */
344
+ modelFuzzyThreshold?: number;
345
+ /**
346
+ * TTL for the in-memory serving-endpoints list cache, in
347
+ * milliseconds. Defaults to 5 minutes. The cache is per workspace
348
+ * host and shared across users; concurrent callers coalesce on a
349
+ * single in-flight fetch.
350
+ */
351
+ modelCacheTtlMs?: number;
352
+ /**
353
+ * Allow clients to override the active model per request via the
354
+ * `X-Mastra-Model` header, `?model=` query string, or `model` body
355
+ * field. Defaults to `true`. Disable when running multi-tenant
356
+ * where untrusted clients shouldn't pick the backing endpoint.
357
+ */
358
+ modelOverride?: boolean;
359
+ /**
360
+ * Priority-ordered list of endpoint names tried *first* when no
361
+ * agent / plugin / env / request-override model id is set, ahead of
362
+ * the dynamic score-classified catalogue. The resolver picks the
363
+ * first id that is actually present in the workspace's
364
+ * `/serving-endpoints` listing.
365
+ *
366
+ * When unset, resolution is driven by the live Foundation Model API
367
+ * `quality` / `speed` / `cost` scores: endpoints are classified into
368
+ * chat classes (`classifyEndpoints`) and walked best-first
369
+ * (ChatThinking -> ChatBalanced -> ChatFast), with the small built-in
370
+ * `FALLBACK_MODEL_IDS` list as the floor when the catalogue can't be
371
+ * read. Set this to
372
+ * pin a regulated workspace to an approved subset, or to put custom
373
+ * endpoints in front of the auto-classified catalogue.
374
+ */
375
+ defaultModelFallbacks?: readonly string[];
376
+ /**
377
+ * When `true` (default), every agent gets a built-in input
378
+ * processor that strips `chartId` fields from prior assistant
379
+ * tool-invocation results before they reach the model. This
380
+ * prevents the model from reusing turn-scoped chartIds it sees
381
+ * in memory recall (which would leave `[chart:<id>]` markers
382
+ * pointing at writer events that no longer exist).
383
+ *
384
+ * Set to `false` to opt out - useful if a non-default agent
385
+ * needs full visibility into prior chartIds (e.g. an audit
386
+ * agent reasoning about chart lineage).
387
+ */
388
+ stripStaleCharts?: boolean;
389
+ /**
390
+ * Style guardrails appended to every agent's `instructions` to curb
391
+ * common LLM-isms (em dashes, emojis, sycophantic openers, throwaway
392
+ * closers, excessive hedging).
393
+ *
394
+ * - `undefined` (default): use the built-in
395
+ * `DEFAULT_STYLE_INSTRUCTIONS` from `agents.ts`.
396
+ * - `string`: replace the default with the supplied block.
397
+ * - `false`: disable entirely (agents see only their bespoke
398
+ * `instructions`).
399
+ *
400
+ * Appended (not prepended) so the agent's role and rules come first
401
+ * and the style block leans on the model's recency bias.
402
+ */
403
+ styleInstructions?: string | false;
404
+ /**
405
+ * Genie spaces this plugin's agents can delegate to. One Mastra
406
+ * tool is registered per alias (`genie` for the well-known
407
+ * `default` alias, `genie_<alias>` otherwise). Each tool spins
408
+ * up a per-question Genie sub-agent that runs Databricks
409
+ * "agent mode" against the space, broadcasts wire events to the
410
+ * UI, fetches statement rows for non-empty results, and returns
411
+ * a `(string | data | chart)[]` summary the host UI renders
412
+ * inline.
413
+ *
414
+ * Entries accept either a full {@link GenieSpaceConfig} object
415
+ * or a bare `space_id` string when no extras are needed:
416
+ *
417
+ * ```ts
418
+ * mastra({
419
+ * genieSpaces: {
420
+ * default: "01ef0d3c0e1b1f4a8d2c3e4f5a6b7c8d",
421
+ * forecasts: { spaceId: "01ef...", hint: "weekly demand forecasts" },
422
+ * },
423
+ * });
424
+ * ```
425
+ *
426
+ * Reach the spaces from an agent's `tools(plugins)` callback via
427
+ * `plugins.genie?.toolkit()`; the resulting tools accept
428
+ * `{ content, conversationId? }` and return a hydrated summary.
429
+ *
430
+ * **Fallback discovery** (highest precedence first): if this
431
+ * field is omitted, the Genie agent also picks up spaces from
432
+ * (1) the AppKit `genie({ spaces: { ... } })` plugin instance
433
+ * when registered, and (2) the `DATABRICKS_GENIE_SPACE_ID`
434
+ * env var (registered under the `default` alias). This keeps
435
+ * existing AppKit deployments working without restating the
436
+ * spaces config in two places.
437
+ */
438
+ genieSpaces?: GenieSpacesConfig;
439
+ /**
440
+ * TTL for the in-memory Genie space metadata cache, in
441
+ * milliseconds. Defaults to 5 minutes. The Genie agent calls
442
+ * `client.genie.getSpace(...)` on every cold-start to get the
443
+ * title / description / warehouse id; cached responses skip the
444
+ * round-trip and concurrent callers coalesce on a single
445
+ * in-flight fetch. Drop to a smaller value when analysts are
446
+ * actively editing space metadata and you want changes visible
447
+ * within seconds; raise it to amortise the round-trip when
448
+ * space metadata is effectively frozen.
449
+ *
450
+ * Backed by AppKit's `CacheManager`, so the cache participates
451
+ * in telemetry spans (`cache.getOrExecute`) and benefits from
452
+ * Lakebase persistence when the `lakebase` plugin is wired up.
453
+ */
454
+ genieSpaceCacheTtlMs?: number;
455
+ /**
456
+ * Maximum LLM steps each agent gets per turn. One step = one
457
+ * round-trip to the underlying model (a tool call consumes a
458
+ * step, the final-text reply consumes one too). Applies to
459
+ * every agent registered through {@link MastraPluginConfig.agents}
460
+ * - per-agent overrides aren't surfaced yet because the same
461
+ * ceiling has been sufficient across every workload we've run.
462
+ *
463
+ * Defaults to {@link DEFAULT_AGENT_MAX_STEPS} (25), sized to fit
464
+ * a decomposed Genie turn (grounding + several `ask_genie` calls
465
+ * + `prepare_chart` per dataset + the final-text reply) with
466
+ * headroom for the model to chain a couple of follow-ups before
467
+ * answering. Mastra's own `agent.generate` default of 5 would
468
+ * cut multi-step orchestration off after 2-3 tool calls, so
469
+ * explicitly raising the ceiling here is what lets the
470
+ * agent-mode loop play out.
471
+ *
472
+ * Lower when an unusually slow or expensive model makes long
473
+ * turns unaffordable; raise for exploratory workloads that need
474
+ * to drill deep into a dataset within a single turn.
475
+ */
476
+ agentMaxSteps?: number;
477
+ /**
478
+ * Expose the plugin's agents (and optionally tools) as a Mastra MCP
479
+ * server so external MCP clients - Claude Desktop, Cursor, the Mastra
480
+ * playground, or another agent - can call them over the standard MCP
481
+ * transports. Disabled by default.
482
+ *
483
+ * - `undefined` / `false`: no MCP endpoints.
484
+ * - `true`: expose every registered agent as an `ask_<agentId>` MCP
485
+ * tool under a server whose id is the plugin name.
486
+ * - {@link MastraMcpConfig}: fine-grained control over the server id,
487
+ * advertised metadata, and which agents / tools are exposed.
488
+ *
489
+ * When enabled, the stock Mastra MCP routes mount under the plugin's
490
+ * base path (no bespoke route is added - the server is handed to the
491
+ * `Mastra` instance via `mcpServers`, which `@mastra/express` serves):
492
+ *
493
+ * - Streamable HTTP: `POST /api/<plugin>/mcp/<serverId>/mcp`
494
+ * - SSE (legacy): `GET /api/<plugin>/mcp/<serverId>/sse`
495
+ * `POST /api/<plugin>/mcp/<serverId>/messages`
496
+ *
497
+ * Requests run under the same AppKit OBO scope as the chat routes, so
498
+ * an agent invoked over MCP resolves its model and tools as the
499
+ * calling user.
500
+ */
501
+ mcp?: boolean | MastraMcpConfig;
502
+ }
503
+ //#endregion
504
+ //#region packages/appkit-mastra/src/memory.d.ts
505
+ /**
506
+ * Builds one `Memory` per agent against a shared service-principal
507
+ * Lakebase pool. Per-instance state keeps the shared `PgVector` alive
508
+ * across calls so registering N agents stays cheap.
509
+ */
510
+ declare class MemoryBuilder {
511
+ private readonly config;
512
+ private readonly servicePrincipalPool;
513
+ private sharedVector;
514
+ constructor(config: MastraPluginConfig, servicePrincipalPool: Pool);
515
+ /**
516
+ * Build a `Memory` for `agentId` after the plugin/agent cascade.
517
+ * Returns `undefined` when the agent has neither storage nor a
518
+ * vector store enabled - Mastra accepts a missing `memory` field
519
+ * and treats the agent as stateless.
520
+ */
521
+ /**
522
+ * Build the Mastra-instance-level storage used for workflow
523
+ * snapshots. Returns `undefined` when plugin-level `storage` is
524
+ * disabled, in which case `agent.resumeStream()` (and therefore
525
+ * the `requireApproval` flow) will not be available.
526
+ *
527
+ * The store lives in a dedicated `mastra_instance` schema so it
528
+ * never collides with per-agent `mastra_<agentId>` namespaces.
529
+ * Workflow snapshots are not per-agent state; they belong to the
530
+ * `Mastra` instance that owns the workflow execution.
531
+ */
532
+ instanceStorage(): PostgresStore | undefined;
533
+ forAgent(agentId: string, def: MastraAgentDefinition): Memory | undefined;
534
+ private buildStorage;
535
+ /**
536
+ * Resolve the agent's vector store. Cascade:
537
+ *
538
+ * - falsy: no vector.
539
+ * - `boolean` / `undefined-inheriting-true`: return the shared
540
+ * singleton (built lazily on first call). All agents that
541
+ * default-enable memory write into and recall from one index.
542
+ * - object: build a dedicated `PgVector` for this agent.
543
+ */
544
+ private buildVector;
545
+ private getSharedVector;
546
+ }
547
+ //#endregion
548
+ //#region packages/appkit-mastra/src/agents.d.ts
549
+ /**
550
+ * Tool record accepted by every Mastra `Agent.tools` field and by the
551
+ * `tools(plugins)` callback on {@link MastraAgentDefinition}.
552
+ *
553
+ * Alias of Mastra's `ToolsInput`, so it already accepts:
554
+ *
555
+ * - Mastra tools built with {@link createTool} (or `new Tool(...)`)
556
+ * - Mastra tools built with the AppKit-shaped {@link tool} wrapper
557
+ * below
558
+ * - Vercel AI SDK tools (`tool({ ... })` from `ai`)
559
+ * - Provider-defined tools (e.g. `openai.tools.webSearch(...)`)
560
+ *
561
+ * Existing tool libraries drop in as-is - nothing in this package
562
+ * forces a rebuild.
563
+ */
564
+ type MastraTools = ToolsInput;
565
+ /**
566
+ * AppKit-shaped tool factory. Lets users mix-and-match tools across
567
+ * AppKit's `agents` plugin and `mastra` with a single import:
568
+ *
569
+ * ```ts
570
+ * import { tool } from "@dbx-tools/appkit-mastra";
571
+ * import { z } from "zod";
572
+ *
573
+ * get_weather: tool({
574
+ * description: "Weather",
575
+ * schema: z.object({ city: z.string() }),
576
+ * execute: async ({ city }) => `Sunny in ${city}`,
577
+ * }),
578
+ * ```
579
+ *
580
+ * Maps onto Mastra's `createTool`:
581
+ *
582
+ * - `description` -> `description` (required)
583
+ * - `schema` -> `inputSchema` (optional)
584
+ * - `execute(input)` -> `execute(input, ctx)` - Mastra already calls
585
+ * the first arg with the parsed inputs, so the body shape is
586
+ * identical. The Mastra `context` arg is forwarded as the second
587
+ * parameter when the caller declares it.
588
+ * - `id`: optional. Defaults to a stable identifier derived from
589
+ * `description` (slugified, with a short hash suffix for
590
+ * uniqueness). Pass an explicit `id` when you need a stable string
591
+ * for tracing or MCP exposure.
592
+ *
593
+ * Reach for {@link createTool} when you need Mastra-only fields
594
+ * (`outputSchema`, `suspendSchema`, `requireApproval`, `mcp`, etc.).
595
+ */
596
+ declare function tool(opts: AppKitToolOptions): Tool;
597
+ /**
598
+ * Input shape for the AppKit-style {@link tool} factory. A trimmed
599
+ * subset of Mastra's `createTool` options that mirrors the
600
+ * `@databricks/appkit/beta` `tool({ description, schema, execute })`
601
+ * signature.
602
+ *
603
+ * Generics are intentionally absent - inference flows through the
604
+ * caller's `schema` (typically a Zod object), and the `execute` body
605
+ * destructures naturally from that. Reach for {@link createTool} when
606
+ * you need the fully-typed input/output schemas wired explicitly.
607
+ */
608
+ interface AppKitToolOptions {
609
+ /** Optional stable identifier; auto-derived from `description` when omitted. */
610
+ id?: string;
611
+ /** Human-readable description shown to the model. Required. */
612
+ description: string;
613
+ /**
614
+ * Optional input schema (any Standard Schema instance, e.g. Zod).
615
+ * Maps to Mastra's `inputSchema`; passed through to the model
616
+ * verbatim.
617
+ */
618
+ schema?: unknown;
619
+ /**
620
+ * Execute body. First arg is the parsed input (typed off `schema`
621
+ * when supplied), second arg is the full Mastra execution context
622
+ * (request context, abort signal, mastra instance) if you need it.
623
+ */
624
+ execute: (input: any, context?: unknown) => unknown;
625
+ }
626
+ /**
627
+ * Identity helper that brands a definition as a Mastra agent. Mirrors
628
+ * AppKit's `createAgent(def)` so the registration shape matches:
629
+ *
630
+ * ```ts
631
+ * const support = createAgent({
632
+ * instructions: "...",
633
+ * model: "databricks-claude-sonnet-4-6",
634
+ * tools(plugins) { return { ... }; },
635
+ * });
636
+ * ```
637
+ *
638
+ * Returns the definition unchanged - the wrapper exists only to anchor
639
+ * type inference and to match the AppKit API surface.
640
+ */
641
+ declare function createAgent<T extends MastraAgentDefinition>(def: T): T;
642
+ /**
643
+ * Filter / rename options accepted by every plugin's `.toolkit()`
644
+ * method. Mirrors AppKit's `ToolkitOptions` verbatim so options pass
645
+ * through unchanged - the underlying AppKit plugin does the filtering
646
+ * and we just adapt the resulting entries into Mastra tools.
647
+ */
648
+ interface ToolkitOptions {
649
+ /**
650
+ * Key prefix prepended to every tool name. AppKit's default is
651
+ * `${pluginName}.` when omitted; pass an explicit `""` to drop it.
652
+ */
653
+ prefix?: string;
654
+ /** Allowlist of local tool names. */
655
+ only?: string[];
656
+ /** Denylist of local tool names. */
657
+ except?: string[];
658
+ /** Remap specific local names to different keys. */
659
+ rename?: Record<string, string>;
660
+ }
661
+ /**
662
+ * Toolkit provider shape every entry in the {@link MastraPlugins} map
663
+ * exposes. Identical to AppKit's `PluginToolkitProvider` - any AppKit
664
+ * plugin that implements the standard `ToolProvider` interface
665
+ * (`getAgentTools` + `executeAgentTool` + `toolkit`) is reachable
666
+ * through this surface automatically.
667
+ */
668
+ interface MastraPluginToolkitProvider {
669
+ /**
670
+ * Returns a Mastra-shaped tools record adapted from the plugin's
671
+ * agent tools. Each tool dispatches back through the plugin's
672
+ * `executeAgentTool` so OBO auth and telemetry spans stay intact.
673
+ */
674
+ toolkit(opts?: ToolkitOptions): MastraTools;
675
+ }
676
+ /**
677
+ * Plugin map handed to the function form of
678
+ * {@link MastraAgentDefinition.tools}. Mirrors AppKit's `Plugins`
679
+ * type exactly: a string-keyed record where every value exposes
680
+ * `.toolkit(opts)`.
681
+ *
682
+ * Implemented as a runtime Proxy that auto-discovers any registered
683
+ * AppKit plugin implementing the standard `ToolProvider` interface
684
+ * (`analytics`, `files`, `lakebase`, `genie`, plus any third-party
685
+ * plugin that does the same). Unknown names resolve to `undefined`
686
+ * at runtime, so guard with `?.` and `?? {}` when spreading from a
687
+ * plugin that may not be registered in every environment.
688
+ *
689
+ * @example
690
+ * ```ts
691
+ * createAgent({
692
+ * instructions: "...",
693
+ * tools(plugins) {
694
+ * return {
695
+ * ...plugins.analytics.toolkit(),
696
+ * ...plugins.files.toolkit({ only: ["uploads.read"] }),
697
+ * get_weather: tool({
698
+ * description: "Weather",
699
+ * schema: z.object({ city: z.string() }),
700
+ * execute: async ({ city }) => `Sunny in ${city}`,
701
+ * }),
702
+ * };
703
+ * },
704
+ * });
705
+ * ```
706
+ */
707
+ type MastraPlugins = Record<string, MastraPluginToolkitProvider>;
708
+ /** Function form of {@link MastraAgentDefinition.tools}. */
709
+ type MastraToolsFn = (plugins: MastraPlugins) => MastraTools | Promise<MastraTools>;
710
+ /**
711
+ * A code-defined Mastra agent. Mirrors the shape AppKit's `agents`
712
+ * plugin uses for `AgentDefinition`. The registry key under
713
+ * `config.agents` is the `agentId` the client streams against; `name`
714
+ * is purely informational (defaults to the key).
715
+ */
716
+ interface MastraAgentDefinition {
717
+ /** Display name used as `Agent.name`. Defaults to the registry key. */
718
+ name?: string;
719
+ /** Optional long-form description; surfaced as `Agent.description`. */
720
+ description?: string;
721
+ /** System prompt body. */
722
+ instructions: string;
723
+ /**
724
+ * Per-agent model override.
725
+ *
726
+ * - `undefined` (default): falls back to the workspace
727
+ * `/serving-endpoints` resolver that {@link buildModel} configures
728
+ * from the per-request `WorkspaceClient`.
729
+ * - `string`: shorthand for "use the default resolver but swap the
730
+ * `modelId`" (e.g. `"databricks-meta-llama-3-3-70b-instruct"`).
731
+ * - Any other Mastra `DynamicArgument<MastraModelConfig>`: passed
732
+ * straight through to `Agent.model`. Use this when you need full
733
+ * control over auth or providerId.
734
+ */
735
+ model?: AgentConfig["model"] | string;
736
+ /**
737
+ * Per-agent tool record. Either a plain map or a callback that
738
+ * receives the typed {@link MastraPlugins} sibling-plugin index and
739
+ * returns a map. The callback runs exactly once at agent setup; the
740
+ * result is cached for the agent's lifetime.
741
+ */
742
+ tools?: MastraTools | MastraToolsFn;
743
+ /**
744
+ * Per-agent semantic recall (PgVector) override. Cascades from
745
+ * `config.memory`; the agent value wins when set.
746
+ *
747
+ * - `undefined` (default): inherit `config.memory`. When that's
748
+ * enabled, the agent **shares the plugin-level singleton `PgVector`
749
+ * instance** (cross-agent semantic recall across the same index).
750
+ * - `false`: disable semantic recall for this agent only.
751
+ * - `true`: enable using the shared singleton (same as default when
752
+ * plugin memory is enabled; useful to opt in when plugin disabled).
753
+ * - {@link MastraMemoryConfig} object: dedicated `PgVector` for this
754
+ * agent (private recall index). Bypasses the shared singleton.
755
+ */
756
+ memory?: boolean | MastraMemoryConfigOverride;
757
+ /**
758
+ * Per-agent thread/message storage (`PostgresStore`) override.
759
+ * Cascades from `config.storage`; the agent value wins when set.
760
+ *
761
+ * - `undefined` (default): inherit `config.storage`. When that's
762
+ * enabled, the agent gets its **own per-agent `PostgresStore`**
763
+ * keyed by `schemaName: "mastra_<agentId>"` so threads and
764
+ * messages stay isolated between agents in the same database.
765
+ * - `false`: disable storage for this agent only (purely in-memory).
766
+ * - `true`: enable with the per-agent default schema.
767
+ * - {@link MastraStorageConfigOverride} object: dedicated
768
+ * `PostgresStore` config (custom schema, connection, etc.).
769
+ */
770
+ storage?: boolean | MastraStorageConfigOverride;
771
+ }
772
+ /**
773
+ * Distributive `Omit` so unions in `PostgresStoreConfig` /
774
+ * `PgVectorConfig` keep their discriminants after the override types
775
+ * strip `id`. The built-in `Omit` collapses unions to one shape with
776
+ * common fields only, which loses the connection-style discriminants.
777
+ */
778
+ type DistributiveOmit<T, K extends keyof never> = T extends unknown ? Omit<T, K> : never;
779
+ /**
780
+ * `PostgresStoreConfig` minus `id` - per-agent overrides accept any
781
+ * Mastra-supported storage shape. `id` is filled in automatically
782
+ * from the agent registry key so traces stay stable.
783
+ */
784
+ type MastraStorageConfigOverride = DistributiveOmit<PostgresStoreConfig, "id"> & {
785
+ id?: string;
786
+ };
787
+ /**
788
+ * `PgVectorConfig` minus `id` - per-agent overrides accept any
789
+ * Mastra-supported vector shape. `id` is filled in automatically
790
+ * from the agent registry key.
791
+ */
792
+ type MastraMemoryConfigOverride = DistributiveOmit<PgVectorConfig, "id"> & {
793
+ id?: string;
794
+ };
795
+ /** Output of {@link buildAgents}: resolved agents plus the default id. */
796
+ interface BuiltAgents {
797
+ agents: Record<string, Agent>;
798
+ defaultAgentId: string;
799
+ /**
800
+ * Ambient tools shared across every agent (the built-in system tools
801
+ * spread with `config.tools`). Surfaced so the optional MCP server
802
+ * can re-expose them when {@link MastraMcpConfig.tools} is enabled.
803
+ */
804
+ ambientTools: MastraTools;
805
+ }
806
+ /** Fallback agent id used when `config.agents` is omitted entirely. */
807
+ declare const FALLBACK_AGENT_ID = "default";
808
+ /**
809
+ * Default per-turn step ceiling applied to every registered agent
810
+ * when {@link MastraPluginConfig.agentMaxSteps} is unset. Sized to
811
+ * fit a decomposed Genie turn (grounding + several `ask_genie`
812
+ * calls + `prepare_chart` per dataset + the final-text reply) with
813
+ * headroom for the model to chain a couple of follow-ups before
814
+ * answering - well above Mastra's own `agent.generate` default of
815
+ * 5, which would cut multi-step orchestration off mid-loop.
816
+ */
817
+ declare const DEFAULT_AGENT_MAX_STEPS = 25;
818
+ /**
819
+ * Style guardrails appended to every agent's `instructions` to curb
820
+ * common LLM-isms (em dashes, emojis, sycophantic openers, excessive
821
+ * hedging, throwaway closers). Appended rather than prepended so the
822
+ * agent's role/context comes first; the model's recency bias then
823
+ * helps the style rules dominate the response surface.
824
+ *
825
+ * Override globally via {@link MastraPluginConfig.styleInstructions}
826
+ * (pass `false` to disable entirely, or a string to replace).
827
+ */
828
+ declare const DEFAULT_STYLE_INSTRUCTIONS: string;
829
+ /**
830
+ * Resolve every entry in `config.agents` into a Mastra `Agent`
831
+ * instance. When `config.agents` is omitted the plugin registers a
832
+ * single built-in `default` analyst so the bare `mastra()` call still
833
+ * yields a working agent.
834
+ *
835
+ * Per-agent tool callbacks are invoked once with a typed
836
+ * {@link MastraPlugins} index built from registered sibling plugins
837
+ * (currently `genie`; extend `MastraPlugins` to surface more).
838
+ *
839
+ * @throws when `config.defaultAgent` is set to an id that isn't in the
840
+ * resolved registry; this is a wiring bug, not a runtime condition.
841
+ */
842
+ declare function buildAgents(opts: {
843
+ config: MastraPluginConfig;
844
+ context: appkitUtils.PluginContextLike | undefined;
845
+ memoryBuilder?: MemoryBuilder;
846
+ log: logUtils.Logger;
847
+ }): Promise<BuiltAgents>;
848
+ //#endregion
849
+ //#region packages/appkit-mastra/src/chart.d.ts
850
+ /**
851
+ * Canonical planner input shape. Tools that source rows from an
852
+ * inline dataset (`render_data`) use it as their `inputSchema`
853
+ * verbatim; tools that resolve rows from a remote (`prepare_chart`
854
+ * over a Genie statement) `omit({ data })` and `extend` with their
855
+ * own identifier field, so the field-level `.describe()` text
856
+ * stays a single source of truth. Server-only - the UI never
857
+ * sees a planner request, only the resolved {@link Chart}.
858
+ */
859
+ declare const chartPlannerRequestSchema: z.ZodObject<{
860
+ title: z.ZodString;
861
+ description: z.ZodOptional<z.ZodString>;
862
+ data: z.ZodReadonly<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
863
+ }, z.core.$strip>;
864
+ type ChartPlannerRequest = z.infer<typeof chartPlannerRequestSchema>;
865
+ /** Inputs to {@link prepareChart}. */
866
+ interface PrepareChartOptions {
867
+ /** Plugin config; resolves the planner agent's model. */
868
+ config: MastraPluginConfig;
869
+ /** Display title forwarded to the planner agent. */
870
+ title?: string;
871
+ /** Optional intent hint forwarded to the planner agent. */
872
+ description?: string;
873
+ /**
874
+ * Resolves the rows to chart. Called once, in the background.
875
+ * Any thrown error lands in the cache as the entry's `error`
876
+ * field (never propagated to the caller of {@link prepareChart}).
877
+ * An empty `rows` array is rejected as `"dataset has no rows;
878
+ * nothing to chart"`.
879
+ */
880
+ resolveData: (signal?: AbortSignal) => Promise<{
881
+ rows: ReadonlyArray<Record<string, unknown>>;
882
+ }>;
883
+ /**
884
+ * Per-request `RequestContext`. Forwarded to the planner agent so
885
+ * user-scoped model resolution (OBO) stays in effect.
886
+ */
887
+ requestContext?: RequestContext;
888
+ /**
889
+ * Cooperative cancellation. Forwarded to `resolveData` and the
890
+ * planner agent. Note: the chart task continues running in the
891
+ * background after the parent request ends, so external abort
892
+ * signals are best-effort; typical use is to leave this unset
893
+ * and let the 1h TTL cap stale entries.
894
+ */
895
+ signal?: AbortSignal;
896
+ }
897
+ /**
898
+ * Mint a `chartId`, cache an empty `{ chartId }` placeholder
899
+ * synchronously, and kick off a background task that resolves the
900
+ * dataset and runs the planner. Returns the `chartId` once the
901
+ * placeholder lands so the first {@link fetchChart} call always
902
+ * sees an entry (no spurious 404 race).
903
+ *
904
+ * The background task swallows its own failures and writes them
905
+ * as `error` entries, so callers never see a rejected promise.
906
+ * Cache state machine:
907
+ *
908
+ * - just after this call returns: `{ chartId }` (processing)
909
+ * - on planner success: `{ chartId, result }`
910
+ * - on data / planner failure: `{ chartId, error }`
911
+ */
912
+ declare function prepareChart(opts: PrepareChartOptions): Promise<{
913
+ chartId: string;
914
+ }>;
915
+ /** Inputs to {@link fetchChart}. */
916
+ interface FetchChartOptions {
917
+ /**
918
+ * Server-side polling budget in ms. When the entry stays in
919
+ * the processing state past this window, the helper returns the
920
+ * last seen value (still processing) so the client can re-poll.
921
+ * Defaults to {@link DEFAULT_FETCH_TIMEOUT_MS} (60s).
922
+ */
923
+ timeoutMs?: number;
924
+ /**
925
+ * Poll interval in ms. Defaults to
926
+ * {@link DEFAULT_FETCH_INTERVAL_MS} (250ms).
927
+ */
928
+ intervalMs?: number;
929
+ /** External cancellation handle (e.g. request `req.signal`). */
930
+ signal?: AbortSignal;
931
+ }
932
+ /**
933
+ * Long-poll the chart cache until the entry settles (`result` or
934
+ * `error` set), the entry is missing, or the server-side timeout
935
+ * elapses.
936
+ *
937
+ * Returns:
938
+ * - the resolved {@link Chart} when it settled, errored, or
939
+ * stayed in processing past `timeoutMs` (so the client can
940
+ * re-poll);
941
+ * - `undefined` when the entry is missing or expired (the
942
+ * consumer should treat as 404).
943
+ *
944
+ * `signal` lets the caller cancel ahead of timeout (e.g. the HTTP
945
+ * request closed). Cancellation propagates to the inter-poll sleep
946
+ * so the helper returns immediately.
947
+ */
948
+ declare function fetchChart(chartId: string, options?: FetchChartOptions): Promise<Chart | undefined>;
949
+ /**
950
+ * Build the `render_data` Mastra tool bound to the given plugin
951
+ * config. Auto-wired as a system tool on every agent (see
952
+ * `agents.ts`); per-agent tools can shadow it by registering a
953
+ * same-named entry.
954
+ *
955
+ * Thin wrapper over {@link prepareChart} for callers that already
956
+ * have a dataset in hand. Mints a `chartId` synchronously, caches
957
+ * an empty placeholder, and kicks off the chart-planner in the
958
+ * background. Returns just the `chartId`; the host UI resolves
959
+ * `[chart:<chartId>]` markers by hitting the plugin's
960
+ * `/embed/chart/:id` route.
961
+ *
962
+ * For Genie statement results, prefer the Genie agent's
963
+ * `prepare_chart` tool, which accepts a `statement_id` and
964
+ * resolves the rows lazily.
965
+ */
966
+ declare function buildRenderDataTool(config: MastraPluginConfig): _mastra_core_tools0.Tool<{
967
+ title: string;
968
+ data: readonly Record<string, unknown>[];
969
+ description?: string | undefined;
970
+ }, {
971
+ chartId: string;
972
+ }, unknown, unknown, _mastra_core_tools0.ToolExecutionContext<unknown, unknown, unknown>, "render_data", unknown>;
973
+ //#endregion
974
+ //#region packages/appkit-mastra/src/mcp.d.ts
975
+ /**
976
+ * A built MCP server plus the request paths it answers on, relative to
977
+ * the plugin's base path (`/api/<plugin>`). The paths are informational
978
+ * (logging / `exports().getMcp()`); the routes themselves are mounted
979
+ * by `@mastra/express` off the `Mastra` instance's `mcpServers`.
980
+ */
981
+ interface ResolvedMcp {
982
+ /** Registry id, used in the route path (`/mcp/<serverId>/...`). */
983
+ serverId: string;
984
+ /** The Mastra MCP server to hand to `new Mastra({ mcpServers })`. */
985
+ server: MCPServer;
986
+ /** Streamable-HTTP transport path, relative to the plugin base path. */
987
+ httpPath: string;
988
+ /** SSE transport path, relative to the plugin base path. */
989
+ ssePath: string;
990
+ /** SSE message path, relative to the plugin base path. */
991
+ messagePath: string;
992
+ }
993
+ /**
994
+ * Build the plugin's MCP server, or `null` when `config.mcp` is falsy
995
+ * (the default - no MCP endpoints).
996
+ *
997
+ * `true` exposes every registered agent as an `ask_<agentId>` MCP tool
998
+ * under a server id equal to the plugin name. The object form
999
+ * ({@link MastraMcpConfig}) tunes the id / advertised metadata and can
1000
+ * additionally expose the plugin's ambient tools or a set of extra
1001
+ * MCP-only tools.
1002
+ */
1003
+ declare function buildMcpServer(opts: {
1004
+ config: MastraPluginConfig;
1005
+ pluginName: string;
1006
+ displayName: string;
1007
+ agents: Record<string, Agent>;
1008
+ ambientTools: MastraTools;
1009
+ }): ResolvedMcp | null;
1010
+ //#endregion
1011
+ //#region packages/appkit-mastra/src/server.d.ts
1012
+ /**
1013
+ * `@mastra/express` subclass that stamps `RequestContext` with the
1014
+ * AppKit user, resource id, and a thread id backed by an HTTP-only
1015
+ * session cookie (`appkit_<plugin-name>_session_id`).
1016
+ */
1017
+ declare class MastraServer$1 extends MastraServer {
1018
+ private config;
1019
+ private log;
1020
+ constructor(config: MastraPluginConfig, ...args: ConstructorParameters<typeof MastraServer>);
1021
+ registerAuthMiddleware(): void;
1022
+ configureRequestContextUser(requestContext: RequestContext): void;
1023
+ /**
1024
+ * Stamp a per-request id and echo it on the response so an upstream
1025
+ * proxy / curl client / browser-side log line can pair its view of
1026
+ * the request with the matching trace span. Reuses `X-Request-Id`
1027
+ * when the upstream already supplies one so multi-hop traces stay
1028
+ * joined; otherwise mints a UUIDv4.
1029
+ *
1030
+ * The id is surfaced as `mastra__requestId` span metadata via
1031
+ * {@link TRACE_REQUEST_CONTEXT_KEYS} and as the `X-Request-Id`
1032
+ * response header so dev tools can copy it from either side.
1033
+ */
1034
+ configureRequestContextRequestId(req: express.Request, res: express.Response, requestContext: RequestContext): void;
1035
+ configureRequestContextThreadId(req: express.Request, res: express.Response, requestContext: RequestContext): void;
1036
+ configureRequestContextModelOverride(req: express.Request, requestContext: RequestContext): void;
1037
+ }
1038
+ //#endregion
1039
+ //#region packages/appkit-mastra/src/plugin.d.ts
1040
+ /**
1041
+ * AppKit plugin (registered name: `mastra`) that hosts Mastra agents
1042
+ * with optional Lakebase-backed memory and AI SDK chat routes under
1043
+ * the plugin mount (typically `/api/mastra`).
1044
+ */
1045
+ declare class MastraPlugin extends Plugin<MastraPluginConfig> {
1046
+ static manifest: {
1047
+ name: "mastra";
1048
+ displayName: string;
1049
+ description: string;
1050
+ stability: "beta";
1051
+ resources: {
1052
+ required: never[];
1053
+ optional: Omit<ResourceRequirement, "required">[];
1054
+ };
1055
+ };
1056
+ /**
1057
+ * Tighten resource requirements based on which features are enabled.
1058
+ * AppKit calls this at registration time (config-aware) so disabled
1059
+ * features don't surface their resource asks to the host app.
1060
+ */
1061
+ static getResourceRequirements(config: MastraPluginConfig): ResourceRequirement[];
1062
+ private log;
1063
+ private built;
1064
+ private mastra;
1065
+ private mastraApp;
1066
+ private mastraServer;
1067
+ /**
1068
+ * The optional MCP server exposing this plugin's agents / tools, or
1069
+ * `null` when `config.mcp` is disabled (the default). Built in
1070
+ * {@link buildAgentAndServer} and registered on the Mastra instance.
1071
+ */
1072
+ private mcp;
1073
+ /**
1074
+ * Dedicated service-principal Lakebase pool backing Mastra memory /
1075
+ * storage. Built once in {@link buildAgentAndServer} (outside any
1076
+ * `asUser` scope, so it never inherits a request's OBO identity) and
1077
+ * drained in {@link abortActiveOperations}. `null` until setup runs
1078
+ * or when Lakebase isn't needed.
1079
+ */
1080
+ private servicePrincipalPool;
1081
+ setup(): Promise<void>;
1082
+ /**
1083
+ * When the `lakebase` plugin is registered, auto-enable `storage`
1084
+ * and `memory` unless the caller opted out explicitly (`false` or a
1085
+ * custom config object). Run after `setup:complete` so the lookup
1086
+ * is reliable: any plugin that registers itself synchronously is
1087
+ * already in the registry by the time this fires.
1088
+ */
1089
+ private applyLakebaseAutoDefaults;
1090
+ /**
1091
+ * Drain the memory service-principal pool on shutdown. AppKit calls
1092
+ * this during teardown; the lakebase plugin closes its own SP / OBO
1093
+ * pools the same way. Fire-and-forget so shutdown isn't blocked on a
1094
+ * slow drain, and clear the handle so a re-`setup()` rebuilds it.
1095
+ */
1096
+ abortActiveOperations(): void;
1097
+ exports(): {
1098
+ /**
1099
+ * Ids of every registered agent in registration order. Matches
1100
+ * AppKit `agents.list()` so callers can iterate the registry the
1101
+ * same way under both plugins.
1102
+ */
1103
+ list: () => string[];
1104
+ /**
1105
+ * Look up a registered agent by id. Returns `null` (not
1106
+ * undefined) when unknown so call sites can early-return without
1107
+ * a separate `in` check.
1108
+ */
1109
+ get: (id: string) => Agent | null;
1110
+ /**
1111
+ * The agent the client converses with when it doesn't name one.
1112
+ * Resolves to `config.defaultAgent`, the first registered id, or
1113
+ * the built-in `default` fallback.
1114
+ */
1115
+ getDefault: () => Agent | null; /** Underlying Mastra instance for advanced use (custom routes etc.). */
1116
+ getMastra: () => Mastra<Record<string, Agent<any, _mastra_core_agent0.ToolsInput, undefined, unknown, _mastra_core_agent0.AgentEditorConfig | undefined>>, Record<string, _mastra_core_workflows0.AnyWorkflow>, Record<string, _mastra_core_vector0.MastraVector<any>>, Record<string, _mastra_core_tts0.MastraTTS>, _mastra_core_logger0.IMastraLogger, Record<string, _mastra_core_mcp0.MCPServerBase<any>>, Record<string, _mastra_core_evals0.MastraScorer<any, any, any, any>>, Record<string, _mastra_core_tools0.ToolAction<any, any, any, any, any, any, unknown>>, Record<string, _mastra_core_processors0.Processor<any, unknown>>, Record<string, _mastra_core_memory0.MastraMemory>, Record<string, _mastra_core_channels0.ChannelProvider>> | null;
1117
+ /**
1118
+ * MCP endpoint info when `config.mcp` is enabled, else `null`.
1119
+ * Paths are absolute (under the plugin mount), ready to hand to an
1120
+ * MCP client. Streamable HTTP is `http`; the SSE pair is the
1121
+ * legacy transport.
1122
+ */
1123
+ getMcp: () => {
1124
+ serverId: string;
1125
+ http: string;
1126
+ sse: string;
1127
+ messages: string;
1128
+ } | null; /** Express subapp Mastra is mounted on; mostly for tests. */
1129
+ getMastraServer: () => MastraServer$1 | null;
1130
+ /**
1131
+ * Fetch the workspace's Model Serving endpoints (cached). Same
1132
+ * payload the `GET /models` route returns; surfaced here so
1133
+ * other plugins / scripts can introspect the catalogue without
1134
+ * an HTTP round-trip. AppKit wraps this with `asUser(req)` for
1135
+ * OBO scoping automatically.
1136
+ */
1137
+ listModels: () => Promise<ServingEndpointSummary[]>;
1138
+ /**
1139
+ * Force-evict cached endpoint listings via AppKit's
1140
+ * `CacheManager`. Useful in tests or right after an admin
1141
+ * deploys a new endpoint and doesn't want to wait for the TTL.
1142
+ * Returns the underlying `CacheManager.delete`/`clear` promise.
1143
+ */
1144
+ clearModelsCache: (host?: string) => Promise<void>;
1145
+ };
1146
+ clientConfig(): Record<string, unknown>;
1147
+ injectRoutes(router: IAppRouter): void;
1148
+ /**
1149
+ * Invoke the Mastra express sub-app. Exists as a method (instead of reading
1150
+ * `this.mastraApp` through the `asUser(req)` proxy at the call site) so the
1151
+ * proxy binds this plain method - whose `.bind` is `Function.prototype.bind`
1152
+ * - rather than the express app, whose `.bind` is the HTTP BIND route
1153
+ * registrar (see the note in `injectRoutes`). Runs inside the user scope so
1154
+ * `getExecutionContext()` returns the OBO client for the agent/model
1155
+ * resolvers.
1156
+ */
1157
+ private dispatchMastra;
1158
+ /**
1159
+ * Implementation backing the `/suggestions` route. Runs inside the
1160
+ * AppKit user-context proxy so `getExecutionContext()` returns the
1161
+ * OBO-scoped client. Resolves the plugin's Genie spaces and merges
1162
+ * their curated `sample_questions` (see {@link collectSpaceSuggestions}).
1163
+ * Returns `[]` when no Genie space is configured so the client
1164
+ * shows a bare empty state instead of built-in example prompts.
1165
+ */
1166
+ private fetchSuggestions;
1167
+ /**
1168
+ * Implementation backing the `data` embed resolver
1169
+ * (`GET /embed/data/:id`). Runs inside the AppKit user-context proxy so
1170
+ * `getExecutionContext()` returns the OBO-scoped workspace
1171
+ * client, then reuses the same `fetchStatementData` pipeline
1172
+ * the `get_statement` tool runs so the LLM and the UI see the
1173
+ * exact same shape for the same statement.
1174
+ *
1175
+ * Returns `undefined` for upstream 404s so the route can map
1176
+ * them to a clean HTTP 404; any other failure bubbles up.
1177
+ */
1178
+ private fetchStatement;
1179
+ /**
1180
+ * Return `this.asUser(req)` when the request carries an OBO token,
1181
+ * otherwise return `this` directly. Prevents the noisy AppKit warn
1182
+ * (`asUser() called without user token in development mode. Skipping
1183
+ * user impersonation.`) on every request in local dev where the
1184
+ * browser never sends `x-forwarded-access-token`. Behavior is
1185
+ * unchanged in production: a missing token always means a real OBO
1186
+ * proxy call (and AppKit will throw upstream if that's wrong).
1187
+ */
1188
+ private userScopedSelf;
1189
+ /**
1190
+ * Implementation backing both the `/models` route and the
1191
+ * `listModels` export. Runs inside the AppKit user-context proxy so
1192
+ * `getExecutionContext()` returns the OBO-scoped client.
1193
+ */
1194
+ private listModels;
1195
+ private buildAgentAndServer;
1196
+ }
1197
+ declare const mastra: _databricks_appkit0.ToPlugin<typeof MastraPlugin, MastraPluginConfig, "mastra">;
1198
+ //#endregion
1199
+ //#region packages/appkit-mastra/src/serving.d.ts
1200
+ /**
1201
+ * `RequestContext` key under which {@link MastraServer} stores the
1202
+ * per-request model override (header / query / body). `model.ts`
1203
+ * reads it before falling back to the agent / plugin default.
1204
+ */
1205
+ declare const MASTRA_MODEL_OVERRIDE_KEY = "mastra__model_override";
1206
+ /**
1207
+ * Minimal Express-ish request shape used by {@link extractModelOverride}.
1208
+ * Keeps this module independent of `express` so the helper can be
1209
+ * reused from non-Express adapters.
1210
+ */
1211
+ interface ModelOverrideRequest {
1212
+ headers?: Record<string, string | string[] | undefined>;
1213
+ query?: Record<string, unknown> | undefined;
1214
+ body?: unknown;
1215
+ }
1216
+ /**
1217
+ * Pull a model override out of a single HTTP request, checking
1218
+ * sources in priority order:
1219
+ *
1220
+ * 1. `X-Mastra-Model` header
1221
+ * 2. `?model=` query string parameter
1222
+ * 3. Body field (`model` or `modelId`, in that order)
1223
+ *
1224
+ * Returns `null` when nothing is set, so callers can wrap with
1225
+ * `if (override) ...` without juggling empty strings. Body inspection
1226
+ * is lenient - any plain object with one of the configured keys
1227
+ * counts, mirroring how AI SDK chat clients pass arbitrary metadata
1228
+ * alongside `messages`.
1229
+ */
1230
+ declare function extractModelOverride(req: ModelOverrideRequest): string | null;
1231
+ //#endregion
1232
+ export { AppKitToolOptions, BuiltAgents, ChartPlannerRequest, DEFAULT_AGENT_MAX_STEPS, DEFAULT_GENIE_ALIAS, DEFAULT_STYLE_INSTRUCTIONS, FALLBACK_AGENT_ID, FetchChartOptions, GENIE_INSTRUCTIONS, GenieSpaceConfig, GenieSpacesConfig, MASTRA_MODEL_OVERRIDE_KEY, MASTRA_REQUEST_ID_KEY, MASTRA_USER_EMAIL_KEY, MASTRA_USER_KEY, MASTRA_USER_NAME_KEY, MastraAgentDefinition, MastraMcpConfig, MastraMemoryConfig, MastraMemoryConfigOverride, MastraPlugin, MastraPluginConfig, MastraPluginToolkitProvider, MastraPlugins, MastraStorageConfigOverride, MastraTools, MastraToolsFn, type ModelOverrideRequest, PrepareChartOptions, ResolvedMcp, TRACE_REQUEST_CONTEXT_KEYS, ToolkitOptions, User, buildAgents, buildGenieToolkitProvider, buildGenieTools, buildMcpServer, buildRenderDataTool, chartPlannerRequestSchema, collectSpaceSuggestions, createAgent, createTool, extractModelOverride, fetchChart, mastra, normalizeGenieSpaces, prepareChart, resolveGenieSpaces, tool };