@dbx-tools/appkit-mastra 0.1.26 → 0.1.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -10
- package/dist/index.d.ts +4 -3
- package/dist/index.js +4 -3
- package/dist/src/agents.js +1 -1
- package/dist/src/chart.d.ts +4 -13
- package/dist/src/chart.js +5 -16
- package/dist/src/config.d.ts +1 -1
- package/dist/src/genie.d.ts +13 -35
- package/dist/src/genie.js +31 -38
- package/dist/src/intercept.d.ts +48 -0
- package/dist/src/intercept.js +167 -0
- package/dist/src/plugin.d.ts +2 -2
- package/dist/src/plugin.js +105 -89
- package/dist/src/serving.d.ts +10 -17
- package/dist/src/serving.js +10 -17
- package/dist/src/statement.d.ts +14 -21
- package/dist/src/statement.js +14 -21
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/index.ts +4 -3
- package/package.json +5 -5
- package/src/agents.ts +1 -1
- package/src/chart.ts +7 -18
- package/src/config.ts +1 -1
- package/src/genie.ts +31 -38
- package/src/intercept.ts +206 -0
- package/src/plugin.ts +121 -90
- package/src/serving.ts +10 -17
- package/src/statement.ts +14 -21
package/src/plugin.ts
CHANGED
|
@@ -37,7 +37,7 @@ import {
|
|
|
37
37
|
type PluginManifest,
|
|
38
38
|
type ResourceRequirement,
|
|
39
39
|
} from "@databricks/appkit";
|
|
40
|
-
import { appkitUtils, logUtils } from "@dbx-tools/shared";
|
|
40
|
+
import { appkitUtils, commonUtils, logUtils } from "@dbx-tools/shared";
|
|
41
41
|
import { chatRoute } from "@mastra/ai-sdk";
|
|
42
42
|
import type { Agent } from "@mastra/core/agent";
|
|
43
43
|
import { Mastra } from "@mastra/core/mastra";
|
|
@@ -54,6 +54,10 @@ import { historyRoute } from "./history.js";
|
|
|
54
54
|
import { createMemoryBuilder, needsLakebase } from "./memory.js";
|
|
55
55
|
import { buildObservability } from "./observability.js";
|
|
56
56
|
import { attachRoutePatchMiddleware, MastraServer } from "./server.js";
|
|
57
|
+
import {
|
|
58
|
+
installStreamEventInterceptor,
|
|
59
|
+
type StreamFrameInterceptor,
|
|
60
|
+
} from "./intercept.js";
|
|
57
61
|
import {
|
|
58
62
|
clearServingEndpointsCache,
|
|
59
63
|
listServingEndpoints,
|
|
@@ -208,8 +212,7 @@ export class MastraPlugin extends Plugin<MastraPluginConfig> {
|
|
|
208
212
|
modelsPath: `${basePath}/models`,
|
|
209
213
|
historyPath: `${basePath}/route/history`,
|
|
210
214
|
historyPathTemplate: `${basePath}/route/history/:agentId`,
|
|
211
|
-
|
|
212
|
-
statementsPathTemplate: `${basePath}/statements/:statementId`,
|
|
215
|
+
embedPathTemplate: `${basePath}/embed/:type/:id`,
|
|
213
216
|
defaultAgent: this.built?.defaultAgentId ?? FALLBACK_AGENT_ID,
|
|
214
217
|
agents: Object.keys(this.built?.agents ?? {}),
|
|
215
218
|
};
|
|
@@ -229,114 +232,97 @@ export class MastraPlugin extends Plugin<MastraPluginConfig> {
|
|
|
229
232
|
.catch(next);
|
|
230
233
|
});
|
|
231
234
|
|
|
232
|
-
// `GET /
|
|
233
|
-
//
|
|
234
|
-
//
|
|
235
|
-
//
|
|
236
|
-
//
|
|
237
|
-
//
|
|
238
|
-
//
|
|
239
|
-
// set) or the server-side budget elapses (then returns the
|
|
240
|
-
// last seen still-processing entry so the client can poll
|
|
241
|
-
// again).
|
|
235
|
+
// `GET /embed/:type/:id` is the single resolver for every embed
|
|
236
|
+
// marker the agent emits in prose (`[chart:<id>]`,
|
|
237
|
+
// `[data:<id>]`, ...). `:type` selects a resolver from the
|
|
238
|
+
// registry below; `:id` is that resolver's lookup key. The
|
|
239
|
+
// grammar (see `marker.ts`) is type-agnostic on purpose - new
|
|
240
|
+
// embed kinds are added by registering a resolver here, with no
|
|
241
|
+
// client or grammar change.
|
|
242
242
|
//
|
|
243
243
|
// Status codes:
|
|
244
|
-
// - 200 with JSON body when the
|
|
245
|
-
// - 404 when
|
|
244
|
+
// - 200 with the resolver's JSON body when the id resolves.
|
|
245
|
+
// - 404 when `:type` isn't registered (unsupported embed
|
|
246
|
+
// type) OR a registered resolver can't find `:id` (unknown
|
|
247
|
+
// / expired - e.g. a chart past its 1h TTL or a fabricated
|
|
248
|
+
// id the model never minted).
|
|
249
|
+
// - 400 when `:id` is empty.
|
|
246
250
|
//
|
|
247
|
-
//
|
|
248
|
-
// - `
|
|
249
|
-
//
|
|
251
|
+
// Per-type query knobs and behavior:
|
|
252
|
+
// - `chart`: long-polls the chart cache until the entry
|
|
253
|
+
// settles (`result` / `error`) or the budget elapses (then
|
|
254
|
+
// returns the still-processing entry to poll again).
|
|
255
|
+
// `?timeoutMs=<n>` (default 60s, capped 5min) tunes it.
|
|
256
|
+
// - `data`: one OBO-scoped Statement Execution fetch.
|
|
257
|
+
// `?limit=<n>` caps rows (clamped to STATEMENT_ROW_CAP).
|
|
250
258
|
//
|
|
251
|
-
//
|
|
252
|
-
//
|
|
253
|
-
//
|
|
254
|
-
//
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
+
// Built once (this handler is registered once) and keyed by the
|
|
260
|
+
// raw `:type` token. Each resolver gets the request (for query
|
|
261
|
+
// parsing + OBO scoping) and an `AbortSignal` bridged off the
|
|
262
|
+
// connection `close` event so a long-poll unblocks the instant
|
|
263
|
+
// the client disconnects. `undefined` from a resolver maps to a
|
|
264
|
+
// clean 404; thrown errors bubble through `next(err)`.
|
|
265
|
+
const embedResolvers: Record<string, EmbedResolver> = {
|
|
266
|
+
chart: (req, id, signal) => {
|
|
267
|
+
const timeoutMs = parseTimeoutMs(req.query["timeoutMs"]);
|
|
268
|
+
return fetchChart(id, {
|
|
269
|
+
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
270
|
+
signal,
|
|
271
|
+
});
|
|
272
|
+
},
|
|
273
|
+
data: (req, id, signal) => {
|
|
274
|
+
const limit = parseStatementLimit(req.query["limit"]);
|
|
275
|
+
return this.userScopedSelf(req).fetchStatement(id, {
|
|
276
|
+
...(limit !== undefined ? { limit } : {}),
|
|
277
|
+
signal,
|
|
278
|
+
});
|
|
279
|
+
},
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
router.get("/embed/:type/:id", (req, res, next) => {
|
|
283
|
+
const type = req.params["type"] ?? "";
|
|
284
|
+
const id = req.params["id"];
|
|
285
|
+
const resolve = embedResolvers[type];
|
|
286
|
+
if (!resolve) {
|
|
287
|
+
res.status(404).json({ error: `unsupported embed type: ${type}` });
|
|
259
288
|
return;
|
|
260
289
|
}
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
// `close` event onto an `AbortController` so a closed
|
|
264
|
-
// connection unblocks the long-poll immediately and frees
|
|
265
|
-
// the request thread. The `close` listener also fires on
|
|
266
|
-
// a normal completion, but at that point we no longer
|
|
267
|
-
// care about the abort and the listener is GC'd with the
|
|
268
|
-
// request.
|
|
269
|
-
const controller = new AbortController();
|
|
270
|
-
req.on("close", () => controller.abort());
|
|
271
|
-
fetchChart(chartId, {
|
|
272
|
-
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
273
|
-
signal: controller.signal,
|
|
274
|
-
})
|
|
275
|
-
.then((entry) => {
|
|
276
|
-
if (!entry) {
|
|
277
|
-
res.status(404).json({ error: "chart not found" });
|
|
278
|
-
return;
|
|
279
|
-
}
|
|
280
|
-
res.json(entry);
|
|
281
|
-
})
|
|
282
|
-
.catch(next);
|
|
283
|
-
});
|
|
284
|
-
|
|
285
|
-
// `GET /statements/:statementId` resolves a Genie / Statement
|
|
286
|
-
// Execution result for inline rendering as a table.
|
|
287
|
-
//
|
|
288
|
-
// The agent embeds `[data:<statement_id>]` markers in prose
|
|
289
|
-
// (see `GENIE_INSTRUCTIONS`) whenever it wants the host UI to
|
|
290
|
-
// display a result set without the model re-spelling every
|
|
291
|
-
// row in markdown. This route is what those markers resolve
|
|
292
|
-
// against - one OBO-scoped fetch returns the columns + rows
|
|
293
|
-
// so the client renders an AppKit Table inline.
|
|
294
|
-
//
|
|
295
|
-
// Status codes:
|
|
296
|
-
// - 200 with `StatementData` body when the statement is found.
|
|
297
|
-
// - 404 when the workspace can't find / read the statement.
|
|
298
|
-
//
|
|
299
|
-
// Query params:
|
|
300
|
-
// - `limit` (optional): row cap. Clamped to
|
|
301
|
-
// {@link STATEMENT_ROW_CAP} so a runaway result set
|
|
302
|
-
// can't hose the response.
|
|
303
|
-
//
|
|
304
|
-
// OBO-scoped via {@link userScopedSelf} so the caller's
|
|
305
|
-
// workspace permissions apply; SDK errors propagate through
|
|
306
|
-
// `next(err)` to Express's default error handler.
|
|
307
|
-
router.get("/statements/:statementId", (req, res, next) => {
|
|
308
|
-
const statementId = req.params["statementId"];
|
|
309
|
-
if (!statementId) {
|
|
310
|
-
res.status(400).json({ error: "statementId is required" });
|
|
290
|
+
if (!id) {
|
|
291
|
+
res.status(400).json({ error: "id is required" });
|
|
311
292
|
return;
|
|
312
293
|
}
|
|
313
|
-
|
|
294
|
+
// Express's `req` predates `AbortSignal`; bridge the `close`
|
|
295
|
+
// event onto an `AbortController` so a closed connection
|
|
296
|
+
// unblocks any long-poll immediately and frees the request
|
|
297
|
+
// thread. The listener is GC'd with the request on normal
|
|
298
|
+
// completion.
|
|
314
299
|
const controller = new AbortController();
|
|
315
300
|
req.on("close", () => controller.abort());
|
|
316
|
-
|
|
317
|
-
.
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
})
|
|
321
|
-
.then((data) => {
|
|
322
|
-
if (!data) {
|
|
323
|
-
res.status(404).json({ error: "statement not found" });
|
|
301
|
+
resolve(req, id, controller.signal)
|
|
302
|
+
.then((entry) => {
|
|
303
|
+
if (entry === undefined) {
|
|
304
|
+
res.status(404).json({ error: `${type} not found` });
|
|
324
305
|
return;
|
|
325
306
|
}
|
|
326
|
-
res.json(
|
|
307
|
+
res.json(entry);
|
|
327
308
|
})
|
|
328
309
|
.catch(next);
|
|
329
310
|
});
|
|
330
311
|
|
|
331
312
|
router.use("", (req, res, next) => {
|
|
332
313
|
if (!this.mastraApp) return res.status(503).end();
|
|
314
|
+
// Run each Mastra `/stream` SSE frame through the interceptor
|
|
315
|
+
// (keep / rewrite / drop). Only engages on a
|
|
316
|
+
// `200 text/event-stream` body, so the JSON routes above and any
|
|
317
|
+
// error response are untouched.
|
|
318
|
+
installStreamEventInterceptor(res, interceptStreamFrame);
|
|
333
319
|
return this.userScopedSelf(req).mastraApp!(req, res, next);
|
|
334
320
|
});
|
|
335
321
|
}
|
|
336
322
|
|
|
337
323
|
/**
|
|
338
|
-
* Implementation backing the
|
|
339
|
-
* Runs inside the AppKit user-context proxy so
|
|
324
|
+
* Implementation backing the `data` embed resolver
|
|
325
|
+
* (`GET /embed/data/:id`). Runs inside the AppKit user-context proxy so
|
|
340
326
|
* `getExecutionContext()` returns the OBO-scoped workspace
|
|
341
327
|
* client, then reuses the same `fetchStatementData` pipeline
|
|
342
328
|
* the `get_statement` tool runs so the LLM and the UI see the
|
|
@@ -472,9 +458,22 @@ export class MastraPlugin extends Plugin<MastraPluginConfig> {
|
|
|
472
458
|
}
|
|
473
459
|
}
|
|
474
460
|
|
|
461
|
+
/**
|
|
462
|
+
* Resolver for one embed `<type>` behind the generic
|
|
463
|
+
* `GET /embed/:type/:id` route. Returns the JSON body to send on
|
|
464
|
+
* success, or `undefined` to signal a 404 (unknown / expired id).
|
|
465
|
+
* `signal` aborts when the client disconnects so long-polling
|
|
466
|
+
* resolvers (e.g. `chart`) unblock immediately.
|
|
467
|
+
*/
|
|
468
|
+
type EmbedResolver = (
|
|
469
|
+
req: express.Request,
|
|
470
|
+
id: string,
|
|
471
|
+
signal: AbortSignal,
|
|
472
|
+
) => Promise<unknown | undefined>;
|
|
473
|
+
|
|
475
474
|
/**
|
|
476
475
|
* Parse the optional `?timeoutMs=<n>` query parameter from a
|
|
477
|
-
* `GET /
|
|
476
|
+
* `GET /embed/chart/:id` request. Accepts a positive integer up
|
|
478
477
|
* to 5 minutes (clamped) and rejects everything else as
|
|
479
478
|
* `undefined` so {@link fetchChart} falls back to its default.
|
|
480
479
|
* Express produces `string | string[] | undefined`; we normalize
|
|
@@ -490,7 +489,7 @@ function parseTimeoutMs(raw: unknown): number | undefined {
|
|
|
490
489
|
|
|
491
490
|
/**
|
|
492
491
|
* Parse the optional `?limit=<n>` query parameter from a
|
|
493
|
-
* `GET /
|
|
492
|
+
* `GET /embed/data/:id` request. Accepts a non-negative
|
|
494
493
|
* integer and lets the route clamp to `STATEMENT_ROW_CAP`;
|
|
495
494
|
* rejects anything else as `undefined` so the route falls back
|
|
496
495
|
* to the server-side cap.
|
|
@@ -503,4 +502,36 @@ function parseStatementLimit(raw: unknown): number | undefined {
|
|
|
503
502
|
return Math.floor(n);
|
|
504
503
|
}
|
|
505
504
|
|
|
505
|
+
/**
|
|
506
|
+
* {@link StreamFrameInterceptor} for Mastra `/stream` responses.
|
|
507
|
+
*
|
|
508
|
+
* Removes large, redundant payloads from terminal `step-finish`,
|
|
509
|
+
* `finish`, and `tool-result` frames before they reach the browser.
|
|
510
|
+
* These frames often repeat information already delivered incrementally
|
|
511
|
+
* via streamed text and tool events, including full tool outputs,
|
|
512
|
+
* accumulated responses, message history, SQL results, chart data, and
|
|
513
|
+
* other large result payloads.
|
|
514
|
+
*
|
|
515
|
+
* The interceptor deletes heavyweight payload properties
|
|
516
|
+
* (`output`, `messages`, `response`, and `result`) while preserving the
|
|
517
|
+
* event envelope and lifecycle metadata required by the client.
|
|
518
|
+
*
|
|
519
|
+
* Deletion is key based, so streams that do not contain these
|
|
520
|
+
* fields are passed through unchanged.
|
|
521
|
+
*/
|
|
522
|
+
const interceptStreamFrame: StreamFrameInterceptor = (chunk) => {
|
|
523
|
+
if (!commonUtils.isRecord(chunk)) return true;
|
|
524
|
+
if (!["step-finish", "finish", "tool-result"].find((type) => type === chunk.type))
|
|
525
|
+
return true;
|
|
526
|
+
const payload = chunk.payload;
|
|
527
|
+
if (!commonUtils.isRecord(payload)) return true;
|
|
528
|
+
const trimmedPayload = commonUtils.deleteKeys(payload, [
|
|
529
|
+
"output",
|
|
530
|
+
"messages",
|
|
531
|
+
"response",
|
|
532
|
+
"result",
|
|
533
|
+
]);
|
|
534
|
+
return trimmedPayload ? { replace: chunk } : true;
|
|
535
|
+
};
|
|
536
|
+
|
|
506
537
|
export const mastra = toPlugin(MastraPlugin);
|
package/src/serving.ts
CHANGED
|
@@ -1,23 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Dynamic model resolution against Databricks Model Serving.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* 3. **Per-request override** - {@link extractModelOverride} pulls a
|
|
15
|
-
* model name from the `X-Mastra-Model` header, `?model=` query
|
|
16
|
-
* string, or `model` body field so the same agent can be exercised
|
|
17
|
-
* against different endpoints without redeploying.
|
|
18
|
-
*
|
|
19
|
-
* `model.ts` glues these together inside the per-step model resolver;
|
|
20
|
-
* `plugin.ts` exposes the cached list at `GET /models`.
|
|
4
|
+
* Turns loose, human-typed model names into real serving-endpoint ids
|
|
5
|
+
* so the same agent can target different endpoints without code
|
|
6
|
+
* changes. The workspace's `/serving-endpoints` list is fetched once
|
|
7
|
+
* per host and cached with a TTL, with concurrent callers sharing one
|
|
8
|
+
* in-flight promise (the coalescing pattern of Python's
|
|
9
|
+
* `cachetools-async`). Names are matched through `fuse.js` extended
|
|
10
|
+
* search so tokens like `"claude sonnet"` snap to
|
|
11
|
+
* `databricks-claude-sonnet-4-6`, and a per-request override can be
|
|
12
|
+
* pulled from the request header, query string, or body so a model
|
|
13
|
+
* can be swapped per call without redeploying.
|
|
21
14
|
*/
|
|
22
15
|
|
|
23
16
|
import { CacheManager, type getExecutionContext } from "@databricks/appkit";
|
package/src/statement.ts
CHANGED
|
@@ -1,24 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Databricks Statement Execution helpers for the Mastra plugin.
|
|
3
3
|
*
|
|
4
|
-
* Wraps `client.statementExecution.getStatement` with the shape
|
|
5
|
-
*
|
|
6
|
-
* `/
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* `/statements/:statementId` route) clamp `limit` to so a
|
|
16
|
-
* runaway result set can't hose a response.
|
|
17
|
-
* - {@link isStatementNotFoundError}: structural detector that
|
|
18
|
-
* normalizes the SDK's two error classes plus the loose
|
|
19
|
-
* `does not exist` / `not found` message shapes into a single
|
|
20
|
-
* boolean - lets the route map upstream 404s to a clean
|
|
21
|
-
* HTTP 404 without coupling to SDK error-class identity.
|
|
4
|
+
* Wraps `client.statementExecution.getStatement` with the shape,
|
|
5
|
+
* size, and error handling the plugin's tools and the
|
|
6
|
+
* `/embed/data/:id` route both need: a low-level fetch that returns a
|
|
7
|
+
* raw `{columns, rows, rowCount}` shape and coerces numeric strings
|
|
8
|
+
* to numbers so downstream charts and aggregations don't have to, a
|
|
9
|
+
* hard row cap callers clamp `limit` to so a runaway result set can't
|
|
10
|
+
* hose a response, and a structural not-found detector that
|
|
11
|
+
* normalizes the SDK's error classes and loose `does not exist` /
|
|
12
|
+
* `not found` message shapes into one boolean so the route can map
|
|
13
|
+
* upstream 404s to a clean HTTP 404 without coupling to SDK
|
|
14
|
+
* error-class identity.
|
|
22
15
|
*
|
|
23
16
|
* Not Genie-specific: a Databricks `statement_id` is workspace
|
|
24
17
|
* scoped and lives in the Statement Execution API regardless of
|
|
@@ -33,7 +26,7 @@ import { apiUtils } from "@dbx-tools/shared";
|
|
|
33
26
|
|
|
34
27
|
/**
|
|
35
28
|
* Hard server-side cap on rows returned by the
|
|
36
|
-
* `/
|
|
29
|
+
* `/embed/data/:id` route. Sized to keep responses small
|
|
37
30
|
* enough for inline tables to render snappily; the route surfaces
|
|
38
31
|
* a `truncated` flag whenever the upstream `rowCount` exceeds
|
|
39
32
|
* this so end users know they're seeing a sample.
|
|
@@ -66,7 +59,7 @@ function coerceCell(cell: string | null): unknown {
|
|
|
66
59
|
*
|
|
67
60
|
* Exported because every consumer in the plugin (the
|
|
68
61
|
* `get_statement` tool, the `prepare_chart` dataset resolver, and
|
|
69
|
-
* the `/
|
|
62
|
+
* the `/embed/data/:id` route) needs the exact same
|
|
70
63
|
* fetch + coercion pipeline so LLM-side `get_statement` output
|
|
71
64
|
* and UI-side `[data:<id>]` rendering stay shape-identical for
|
|
72
65
|
* the same `statement_id`.
|
|
@@ -110,7 +103,7 @@ export async function fetchStatementData(
|
|
|
110
103
|
* catalogued.
|
|
111
104
|
*
|
|
112
105
|
* Pulled into its own helper so callers (notably the
|
|
113
|
-
* `/
|
|
106
|
+
* `/embed/data/:id` route) stay decoupled from SDK
|
|
114
107
|
* error-class identity, and the conversion logic stays testable
|
|
115
108
|
* in isolation.
|
|
116
109
|
*/
|