@dbx-tools/appkit-mastra 0.3.43 → 0.4.0

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 (56) hide show
  1. package/lib/index.d.ts +71 -0
  2. package/lib/index.js +56 -0
  3. package/lib/src/agents.d.ts +347 -0
  4. package/lib/src/agents.js +554 -0
  5. package/lib/src/chart.d.ts +192 -0
  6. package/lib/src/chart.js +638 -0
  7. package/lib/src/config.d.ts +479 -0
  8. package/lib/src/config.js +190 -0
  9. package/lib/src/defaults.d.ts +68 -0
  10. package/lib/src/defaults.js +107 -0
  11. package/lib/src/filesystems.d.ts +208 -0
  12. package/lib/src/filesystems.js +958 -0
  13. package/lib/src/genie.d.ts +166 -0
  14. package/lib/src/genie.js +969 -0
  15. package/lib/src/history.d.ts +97 -0
  16. package/lib/src/history.js +264 -0
  17. package/lib/src/mcp.d.ts +66 -0
  18. package/lib/src/mcp.js +65 -0
  19. package/lib/src/memory.d.ts +111 -0
  20. package/lib/src/memory.js +275 -0
  21. package/lib/src/mlflow.d.ts +63 -0
  22. package/lib/src/mlflow.js +117 -0
  23. package/lib/src/model.d.ts +62 -0
  24. package/lib/src/model.js +168 -0
  25. package/lib/src/observability.d.ts +81 -0
  26. package/lib/src/observability.js +98 -0
  27. package/lib/src/pagination.d.ts +23 -0
  28. package/lib/src/pagination.js +31 -0
  29. package/lib/src/plugin.d.ts +352 -0
  30. package/lib/src/plugin.js +1015 -0
  31. package/lib/src/processors.d.ts +62 -0
  32. package/lib/src/processors.js +162 -0
  33. package/lib/src/rest.d.ts +36 -0
  34. package/lib/src/rest.js +46 -0
  35. package/lib/src/server.d.ts +155 -0
  36. package/lib/src/server.js +336 -0
  37. package/lib/src/serving-sanitize.d.ts +104 -0
  38. package/lib/src/serving-sanitize.js +228 -0
  39. package/lib/src/serving.d.ts +61 -0
  40. package/lib/src/serving.js +78 -0
  41. package/lib/src/statement.d.ts +51 -0
  42. package/lib/src/statement.js +83 -0
  43. package/lib/src/storage-schema.d.ts +14 -0
  44. package/lib/src/storage-schema.js +34 -0
  45. package/lib/src/summarize.d.ts +70 -0
  46. package/lib/src/summarize.js +142 -0
  47. package/lib/src/threads.d.ts +109 -0
  48. package/lib/src/threads.js +301 -0
  49. package/lib/src/validation.d.ts +19 -0
  50. package/lib/src/validation.js +17 -0
  51. package/lib/src/workspaces.d.ts +68 -0
  52. package/lib/src/workspaces.js +246 -0
  53. package/lib/src/writer.d.ts +25 -0
  54. package/lib/src/writer.js +40 -0
  55. package/lib/tsconfig.tsbuildinfo +1 -0
  56. package/package.json +17 -13
@@ -0,0 +1,352 @@
1
+ /**
2
+ * AppKit plugin that builds one or more Mastra `Agent` instances and
3
+ * mounts the `@mastra/express` server. Clients drive the conversation
4
+ * over the standard Mastra agent stream (`@mastra/client-js`'s
5
+ * `getAgent(id).stream()`), so there's no bespoke chat transport to
6
+ * keep in sync.
7
+ *
8
+ * - Agents: registered through `config.agents` at plugin creation
9
+ * ({@link MastraAgentDefinition}). Each entry's `tools` field accepts
10
+ * either a plain record or a `(plugins) => tools` callback that gets
11
+ * a typed sibling-plugin index ({@link MastraPlugins}). Omit
12
+ * `config.agents` to get a single built-in `default` analyst.
13
+ * - Model: each agent call resolves a `MastraModelConfig` via
14
+ * {@link buildModel} from `./model.js`. Per-agent `model` overrides
15
+ * (`AgentConfig["model"]` or a `modelId` string) flow through
16
+ * {@link buildAgents}.
17
+ * - Memory / storage: per-agent, built by {@link createMemoryBuilder}
18
+ * from `./memory.js`. Both auto-default to `true` when the
19
+ * `lakebase` plugin is registered (unless the caller passed
20
+ * `false` or a custom config). Storage namespaces per agent via
21
+ * {@link agentStorageSchemaName} per agent; the vector store is a single
22
+ * shared singleton across every agent.
23
+ * - Server: the Express subapp wiring lives in `./server.js`.
24
+ * - HTTP: AppKit mounts this plugin under `/api/mastra`. Alongside the
25
+ * Mastra agent routes, the plugin registers `/route/history`
26
+ * (load + clear a thread's messages), `/route/threads` (list the
27
+ * caller's conversations + delete one), `/models`, `/default-model`,
28
+ * `/suggestions`, `/route/feedback` (log a thumbs / comment to MLflow
29
+ * when feedback is enabled), and the generic `/embed/:type/:id`
30
+ * resolver for inline chart / data markers. Each is registered through
31
+ * AppKit's `route()` so it lands in the plugin's endpoint map, and
32
+ * every outbound call one makes runs through `execute()` (see
33
+ * `./defaults.js`). The stock `@mastra/express` surface is gated
34
+ * by `config.apiAccess` (default `"scoped"`): only agent inference,
35
+ * read-only agent metadata, the `/route/*` routes, and (when enabled)
36
+ * MCP are dispatched to Mastra; admin / mutating / bulk-export routes
37
+ * are refused with `403`. See {@link isMastraRequestAllowed}.
38
+ * - MCP: opt in with `config.mcp` to expose the agents (and optionally
39
+ * tools) as a Mastra `MCPServer`. It is registered on the `Mastra`
40
+ * instance via `mcpServers`, so `@mastra/express` serves the stock
41
+ * MCP transport routes (`/mcp/<serverId>/...`) under the mount. See
42
+ * `./mcp.js`.
43
+ *
44
+ * @module
45
+ */
46
+ import { Plugin, type IAppRouter, type PluginManifest, type ResourceRequirement } from "@databricks/appkit";
47
+ import { type ServingEndpointSummary } from "@dbx-tools/shared-model";
48
+ import type { Agent } from "@mastra/core/agent";
49
+ import { Mastra } from "@mastra/core/mastra";
50
+ import type { RequestContext } from "@mastra/core/request-context";
51
+ import { type MastraPluginConfig } from "./config.js";
52
+ import { MastraServer } from "./server.js";
53
+ /**
54
+ * AppKit plugin (registered name: `mastra`) that hosts Mastra agents
55
+ * with optional Lakebase-backed memory and AI SDK chat routes under
56
+ * the plugin mount (typically `/api/mastra`).
57
+ *
58
+ * @example Register the plugin
59
+ * ```ts
60
+ * import { createApp, lakebase } from "@databricks/appkit";
61
+ * import { createAgent, mastra } from "@dbx-tools/appkit-mastra";
62
+ *
63
+ * // `lakebase` first: registering it auto-enables Mastra storage + memory.
64
+ * const app = await createApp({
65
+ * plugins: [
66
+ * lakebase(),
67
+ * mastra({
68
+ * genieSpaces: { default: process.env.DATABRICKS_GENIE_SPACE_ID! },
69
+ * agents: createAgent({
70
+ * name: "analyst",
71
+ * instructions: "You answer questions about revenue and returns.",
72
+ * tools(plugins) {
73
+ * return { ...plugins.genie?.toolkit() };
74
+ * },
75
+ * }),
76
+ * }),
77
+ * ],
78
+ * });
79
+ * ```
80
+ *
81
+ * @example Read the agents back off the AppKit instance
82
+ * ```ts
83
+ * const agentIds = app.mastra.list();
84
+ * const endpoints = await app.mastra.listModels();
85
+ * ```
86
+ */
87
+ export declare class MastraPlugin extends Plugin<MastraPluginConfig> {
88
+ static manifest: PluginManifest<"mastra">;
89
+ /**
90
+ * Tighten resource requirements based on which features are enabled.
91
+ * AppKit calls this at registration time (config-aware) so disabled
92
+ * features don't surface their resource asks to the host app.
93
+ */
94
+ static getResourceRequirements(config: MastraPluginConfig): ResourceRequirement[];
95
+ private logger;
96
+ private built;
97
+ private mastra;
98
+ private mastraApp;
99
+ private mastraServer;
100
+ /**
101
+ * The optional MCP server exposing this plugin's agents / tools, or
102
+ * `null` when `config.mcp` is disabled (the default). Built in
103
+ * {@link buildAgentAndServer} and registered on the Mastra instance.
104
+ */
105
+ private mcp;
106
+ /**
107
+ * Dedicated service-principal Lakebase pool backing Mastra memory /
108
+ * storage. Built once in {@link buildAgentAndServer} (outside any
109
+ * `asUser` scope, so it never inherits a request's OBO identity) and
110
+ * drained in {@link shutdown}. `null` until setup runs or when
111
+ * Lakebase isn't needed.
112
+ */
113
+ private servicePrincipalPool;
114
+ setup(): Promise<void>;
115
+ /**
116
+ * When the `lakebase` plugin is registered, auto-enable `storage`
117
+ * and `memory` unless the caller opted out explicitly (`false` or a
118
+ * custom config object). Run after `setup:complete` so the lookup
119
+ * is reliable: any plugin that registers itself synchronously is
120
+ * already in the registry by the time this fires.
121
+ */
122
+ private applyLakebaseAutoDefaults;
123
+ /**
124
+ * Drain the memory service-principal pool. Idempotent: the handle is
125
+ * cleared before the drain starts, so a second call is a no-op and a
126
+ * later `setup()` rebuilds the pool. Bounded by
127
+ * {@link POOL_DRAIN_TIMEOUT_MS} to stay well inside the 15s graceful
128
+ * shutdown budget.
129
+ */
130
+ shutdown(): Promise<void>;
131
+ /**
132
+ * Abort in-flight work. AppKit's graceful shutdown calls this hook
133
+ * synchronously and never awaits {@link shutdown}, so the pool drain is
134
+ * started here too; it cannot be awaited from a `void` hook, and
135
+ * {@link shutdown} is idempotent so the duplicate call is free.
136
+ */
137
+ abortActiveOperations(): void;
138
+ exports(): {
139
+ /**
140
+ * Ids of every registered agent in registration order. Matches
141
+ * AppKit `agents.list()` so callers can iterate the registry the
142
+ * same way under both plugins.
143
+ */
144
+ list: () => string[];
145
+ /**
146
+ * Look up a registered agent by id. Returns `null` (not
147
+ * undefined) when unknown so call sites can early-return without
148
+ * a separate `in` check.
149
+ */
150
+ get: (id: string) => Agent | null;
151
+ /**
152
+ * The agent the client converses with when it doesn't name one.
153
+ * Resolves to `config.defaultAgent`, the first registered id, or
154
+ * the built-in `default` fallback.
155
+ */
156
+ getDefault: () => Agent | null;
157
+ /** Underlying Mastra instance for advanced use (custom routes etc.). */
158
+ getMastra: () => Mastra<Record<string, Agent<any, import("@mastra/core/agent").ToolsInput, undefined, unknown, import("@mastra/core/agent").AgentEditorConfig | undefined>>, Record<string, import("@mastra/core/workflows").AnyWorkflow>, Record<string, import("@mastra/core/vector").MastraVector<any>>, Record<string, import("@mastra/core/tts").MastraTTS>, import("@mastra/core/logger").IMastraLogger, Record<string, import("@mastra/core/mcp").MCPServerBase<any>>, Record<string, import("@mastra/core/evals").MastraScorer<any, any, any, any>>, Record<string, import("@mastra/core/tools").ToolAction<any, any, any, any, any, any, unknown>>, Record<string, import("@mastra/core/processors").Processor<any, unknown>>, Record<string, import("@mastra/core/memory").MastraMemory>, Record<string, import("@mastra/core/channels").ChannelProvider>> | null;
159
+ /**
160
+ * Build the `RequestContext` an agent turn driven from OUTSIDE this
161
+ * plugin's routes needs (a Teams activity on another plugin's endpoint, a
162
+ * scheduled job).
163
+ *
164
+ * Mastra's user-scoped tools - `ask_genie` most visibly - read the AppKit
165
+ * user off the request context, which only the HTTP middleware stamps.
166
+ * Calling `agent.generate` with a raw prompt therefore answers "the data
167
+ * source is unreachable" where the chat routes answer with real data.
168
+ * Passing this as `requestContext` closes that gap, so an out-of-band turn
169
+ * has exactly the capabilities a chat turn has.
170
+ *
171
+ * Must be called INSIDE an `asUser(req)` scope to inherit the caller's
172
+ * OBO identity; outside one it resolves to the service principal.
173
+ */
174
+ createRequestContext: (options?: {
175
+ threadId?: string;
176
+ resourceId?: string;
177
+ requestId?: string;
178
+ }) => Promise<RequestContext>;
179
+ /**
180
+ * MCP endpoint info when `config.mcp` is enabled, else `null`.
181
+ * Streamable HTTP is `http`; the SSE pair is the legacy transport.
182
+ *
183
+ * Each path is given twice: mount-relative (`httpPath`, `ssePath`,
184
+ * `messagePath`) for anything that already knows where the plugin is
185
+ * mounted, and absolute (`http`, `sse`, `messages`) for MCP clients,
186
+ * which take a single URL and cannot compose one. The absolute form is
187
+ * built from {@link basePath}, so it honors a `config.name` override but
188
+ * still assumes AppKit's default `/api/<name>` mount.
189
+ */
190
+ getMcp: () => {
191
+ serverId: string;
192
+ httpPath: string;
193
+ ssePath: string;
194
+ messagePath: string;
195
+ http: string;
196
+ sse: string;
197
+ messages: string;
198
+ } | null;
199
+ /** Express subapp Mastra is mounted on; mostly for tests. */
200
+ getMastraServer: () => MastraServer | null;
201
+ /**
202
+ * Fetch the workspace's Model Serving endpoints (cached). Same
203
+ * payload the `GET /models` route returns; surfaced here so
204
+ * other plugins / scripts can introspect the catalogue without
205
+ * an HTTP round-trip. AppKit wraps this with `asUser(req)` for
206
+ * OBO scoping automatically. Throws when the listing fails, since
207
+ * there is no status code to hand back on this surface.
208
+ */
209
+ listModels: () => Promise<ServingEndpointSummary[]>;
210
+ /**
211
+ * Force-evict cached endpoint listings via AppKit's
212
+ * `CacheManager`. Useful in tests or right after an admin
213
+ * deploys a new endpoint and doesn't want to wait for the TTL.
214
+ * Returns the underlying `CacheManager.delete`/`clear` promise.
215
+ */
216
+ clearModelsCache: (host?: string) => Promise<void>;
217
+ };
218
+ /**
219
+ * Absolute mount this plugin's routes answer on. AppKit mounts every plugin
220
+ * at `/api/<plugin.name>` and `this.name` honors a `config.name` override,
221
+ * so the per-route segments (`routes.MASTRA_ROUTES`) hang off this.
222
+ */
223
+ private get basePath();
224
+ clientConfig(): Record<string, unknown>;
225
+ /**
226
+ * Whether user feedback can be logged to MLflow. Delegates to
227
+ * {@link resolveFeedbackEnabled} so the client-config flag and the
228
+ * feedback route share the same gate as the server's trace-id header.
229
+ */
230
+ private feedbackEnabled;
231
+ injectRoutes(router: IAppRouter): void;
232
+ /**
233
+ * Map a failed {@link ExecutionResult} onto the response: the status the
234
+ * execution pipeline resolved, paired with `clientMessage` rather than the
235
+ * result's own text, which can carry upstream detail. The full message is
236
+ * logged under `<operation>:error`.
237
+ */
238
+ private sendFailure;
239
+ /** 404 body for a request naming an agent that isn't registered. */
240
+ private unknownAgentMessage;
241
+ /**
242
+ * Invoke the Mastra express sub-app. Exists as a method (instead of reading
243
+ * `this.mastraApp` through the `asUser(req)` proxy at the call site) so the
244
+ * proxy binds this plain method - whose `.bind` is `Function.prototype.bind`
245
+ * - rather than the express app, whose `.bind` is the HTTP BIND route
246
+ * registrar (see the note in `injectRoutes`). Runs inside the user scope so
247
+ * `getExecutionContext()` returns the OBO client for the agent/model
248
+ * resolvers.
249
+ */
250
+ private dispatchMastra;
251
+ /**
252
+ * Map a clean, mount-relative MCP alias path to the underlying
253
+ * `@mastra/express` route. Returns `null` when MCP is off or the path
254
+ * isn't an alias. Collapses the stock `/mcp/<serverId>/<transport>`
255
+ * layout (serverId defaults to the plugin name) down to `/mcp`,
256
+ * `/sse`, and `/messages`.
257
+ */
258
+ private mcpRouteAlias;
259
+ /**
260
+ * Implementation backing the `/suggestions` route. Runs inside the
261
+ * AppKit user-context proxy so `getExecutionContext()` returns the
262
+ * OBO-scoped client. Resolves the plugin's Genie spaces and merges
263
+ * their curated `sample_questions` (see {@link collectSpaceSuggestions}).
264
+ * Returns `[]` when no Genie space is configured so the client
265
+ * shows a bare empty state instead of built-in example prompts.
266
+ */
267
+ private fetchSuggestions;
268
+ /**
269
+ * Implementation backing the `/route/feedback` route. Runs inside the
270
+ * AppKit user-context proxy so `getExecutionContext()` returns the
271
+ * OBO-scoped client and the assessment is attributed to the signed-in
272
+ * user (their email / id as the assessment source). Returns the
273
+ * created assessment id on success, or `undefined` on a soft failure
274
+ * (see {@link logFeedback} in `./mlflow.js`).
275
+ */
276
+ private logFeedback;
277
+ /**
278
+ * Implementation backing the `data` embed resolver
279
+ * (`GET /embed/data/:id`). Runs inside the AppKit user-context proxy so
280
+ * `getExecutionContext()` returns the OBO-scoped workspace
281
+ * client, then reuses the same `fetchStatementData` pipeline
282
+ * the `get_statement` tool runs so the LLM and the UI see the
283
+ * exact same shape for the same statement.
284
+ *
285
+ * Resolves to `undefined` data for upstream 404s so the route can map them
286
+ * to a clean HTTP 404; any other failure comes back as a non-`ok` result
287
+ * carrying the status to answer with.
288
+ */
289
+ private fetchStatement;
290
+ /**
291
+ * Implementation backing the `chart` embed resolver
292
+ * (`GET /embed/chart/:id`). Runs inside the AppKit user-context proxy so the
293
+ * lookup is namespaced to the calling identity: a chart minted for another
294
+ * user is indistinguishable from an unknown id, and the route answers 404.
295
+ */
296
+ private fetchChartEntry;
297
+ /**
298
+ * Implementation backing the `/models` route. Runs inside the AppKit
299
+ * user-context proxy so `getExecutionContext()` returns the OBO-scoped
300
+ * client and the catalogue reflects what the caller can invoke.
301
+ */
302
+ private listModelsResult;
303
+ /**
304
+ * Implementation backing the `listModels` export. The programmatic surface
305
+ * carries no status code, so a failed execution becomes a throw with a
306
+ * stable message; the routes branch on the {@link ExecutionResult} instead.
307
+ */
308
+ private listModels;
309
+ private buildAgentAndServer;
310
+ }
311
+ /**
312
+ * Register the Mastra plugin on an AppKit app. Mounts the agents, the
313
+ * `/route/*` chat surface, and (unless disabled) the MCP transport under
314
+ * `/api/mastra`.
315
+ *
316
+ * @example Minimal app
317
+ * ```ts
318
+ * import { createApp } from "@databricks/appkit";
319
+ * import { mastra } from "@dbx-tools/appkit-mastra";
320
+ *
321
+ * // No `agents`: a single built-in `default` analyst is registered, so the
322
+ * // chat endpoint works out of the box.
323
+ * const app = await createApp({ plugins: [mastra()] });
324
+ * ```
325
+ *
326
+ * @example Two agents, a pinned model, and Genie
327
+ * ```ts
328
+ * import { createApp, lakebase } from "@databricks/appkit";
329
+ * import { createAgent, mastra } from "@dbx-tools/appkit-mastra";
330
+ *
331
+ * const app = await createApp({
332
+ * plugins: [
333
+ * lakebase(),
334
+ * mastra({
335
+ * defaultModel: "databricks-claude-sonnet-4-6",
336
+ * defaultAgent: "analyst",
337
+ * genieSpaces: { sales: { spaceId: "01ef...", hint: "orders, returns" } },
338
+ * agents: {
339
+ * analyst: createAgent({
340
+ * instructions: "You answer questions about sales.",
341
+ * tools(plugins) {
342
+ * return { ...plugins.genie?.toolkit() };
343
+ * },
344
+ * }),
345
+ * helper: createAgent({ instructions: "You explain the analyst's answers." }),
346
+ * },
347
+ * }),
348
+ * ],
349
+ * });
350
+ * ```
351
+ */
352
+ export declare const mastra: import("@databricks/appkit").ToPlugin<typeof MastraPlugin, MastraPluginConfig, "mastra">;