@dbx-tools/appkit-mastra 0.1.12 → 0.1.14

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 (57) hide show
  1. package/README.md +303 -637
  2. package/index.ts +46 -38
  3. package/package.json +58 -43
  4. package/src/agents.ts +224 -66
  5. package/src/chart.ts +531 -429
  6. package/src/config.ts +270 -19
  7. package/src/filesystems.ts +1090 -0
  8. package/src/genie.ts +1000 -660
  9. package/src/history.ts +166 -79
  10. package/src/mcp.ts +105 -0
  11. package/src/memory.ts +119 -81
  12. package/src/mlflow.ts +149 -0
  13. package/src/model.ts +75 -408
  14. package/src/observability.ts +144 -0
  15. package/src/pagination.ts +34 -0
  16. package/src/plugin.ts +566 -59
  17. package/src/processors.ts +168 -0
  18. package/src/rest.ts +67 -0
  19. package/src/server.ts +232 -45
  20. package/src/serving-sanitize.ts +167 -0
  21. package/src/serving.ts +27 -243
  22. package/src/statement.ts +89 -0
  23. package/src/storage-schema.ts +41 -0
  24. package/src/summarize.ts +176 -0
  25. package/src/threads.ts +338 -0
  26. package/src/workspaces.ts +346 -0
  27. package/src/writer.ts +44 -0
  28. package/tsconfig.json +41 -0
  29. package/dist/index.d.ts +0 -20
  30. package/dist/index.js +0 -20
  31. package/dist/src/agents.d.ts +0 -306
  32. package/dist/src/agents.js +0 -403
  33. package/dist/src/chart.d.ts +0 -170
  34. package/dist/src/chart.js +0 -491
  35. package/dist/src/config.d.ts +0 -183
  36. package/dist/src/config.js +0 -12
  37. package/dist/src/genie.d.ts +0 -131
  38. package/dist/src/genie.js +0 -630
  39. package/dist/src/history.d.ts +0 -67
  40. package/dist/src/history.js +0 -172
  41. package/dist/src/memory.d.ts +0 -79
  42. package/dist/src/memory.js +0 -210
  43. package/dist/src/model.d.ts +0 -159
  44. package/dist/src/model.js +0 -427
  45. package/dist/src/plugin.d.ts +0 -130
  46. package/dist/src/plugin.js +0 -261
  47. package/dist/src/processors/strip-stale-charts.d.ts +0 -29
  48. package/dist/src/processors/strip-stale-charts.js +0 -96
  49. package/dist/src/server.d.ts +0 -46
  50. package/dist/src/server.js +0 -123
  51. package/dist/src/serving.d.ts +0 -156
  52. package/dist/src/serving.js +0 -231
  53. package/dist/src/tools/email.d.ts +0 -74
  54. package/dist/src/tools/email.js +0 -122
  55. package/dist/tsconfig.build.tsbuildinfo +0 -1
  56. package/src/processors/strip-stale-charts.ts +0 -105
  57. package/src/tools/email.ts +0 -147
@@ -0,0 +1,346 @@
1
+ /**
2
+ * Mastra workspace factory for Databricks Apps.
3
+ *
4
+ * Builds a per-request {@link Workspace} whose filesystem is a
5
+ * {@link CompositeFilesystem} over Databricks paths resolved from the
6
+ * OBO client on {@link MASTRA_USER_KEY}. Optional mount resolver
7
+ * contributions merge extra filesystems and skill scan roots; built-in
8
+ * Assistant skill trees are toggled with `assistantSkills` (on by default).
9
+ */
10
+
11
+ import type { WorkspaceClient } from "@databricks/sdk-experimental";
12
+ import type { RequestContext } from "@mastra/core/request-context";
13
+ import {
14
+ CompositeFilesystem,
15
+ Workspace,
16
+ type SkillsContext,
17
+ type SkillsResolver,
18
+ type WorkspaceFilesystem,
19
+ } from "@mastra/core/workspace";
20
+
21
+ import { MASTRA_SCOPES_KEY, MASTRA_USER_EMAIL_KEY, MASTRA_USER_KEY, type User } from "./config";
22
+ import { DatabricksWorkspaceFilesystem, emptyFilesystem } from "./filesystems";
23
+ import { log, string, token } from "@dbx-tools/shared-core";
24
+
25
+ /* ------------------------------ constants ------------------------------ */
26
+
27
+ /** Shared Assistant skills tree in the workspace namespace. */
28
+ const ASSISTANT_SHARED_SKILLS_PATH = "/Workspace/.assistant/skills";
29
+
30
+ /** Composite mount for {@link ASSISTANT_SHARED_SKILLS_PATH}. */
31
+ const ASSISTANT_WORKSPACE_SKILLS_MOUNT = "/workspace_skills";
32
+
33
+ /** Composite mount for the caller's `/.assistant/skills` tree. */
34
+ const ASSISTANT_USER_SKILLS_MOUNT = "/workspace_user_skills";
35
+
36
+ /** OAuth scopes that gate Databricks workspace file mounts. */
37
+ const WORKSPACE_FILE_SCOPES = ["workspace", "workspace.workspace", "all-apis"] as const;
38
+
39
+ const logger = log.logger("mastra/workspaces");
40
+
41
+ /* -------------------------------- types -------------------------------- */
42
+
43
+ /** Per-request context for mount resolvers. */
44
+ interface WorkspaceMountContext {
45
+ requestContext?: RequestContext;
46
+ }
47
+
48
+ /** Mount map plus optional Mastra skill scan roots for one resolver. */
49
+ interface WorkspaceMountContribution {
50
+ mounts: Record<string, WorkspaceFilesystem>;
51
+ /** Paths within the composite namespace where `SKILL.md` files are scanned. */
52
+ skillPaths?: string[];
53
+ }
54
+
55
+ /** Contributes filesystem mounts (and optional skill paths) for one request. */
56
+ type WorkspaceMountResolver = (
57
+ context: WorkspaceMountContext,
58
+ ) => WorkspaceMountContribution | Promise<WorkspaceMountContribution>;
59
+
60
+ /** Options for {@link createWorkspace}. */
61
+ export interface CreateWorkspaceOptions {
62
+ /** Workspace id; derived from `name` or `"workspace"` when omitted. */
63
+ id?: string;
64
+ /** Display name; derived from `id` when omitted. */
65
+ name?: string;
66
+ /**
67
+ * Mount read-only Assistant skill trees from `/Workspace/.assistant/skills`
68
+ * and `/Users/<email>/.assistant/skills`. Defaults to `true`.
69
+ */
70
+ assistantSkills?: boolean;
71
+ /** Extra per-request mount resolvers (run after built-in options). */
72
+ mounts?: WorkspaceMountResolver[];
73
+ /** Replace the auto-built dynamic skills resolver. */
74
+ skills?: SkillsResolver;
75
+ /** Forwarded to Mastra when skill discovery is enabled. */
76
+ checkSkillFileMtime?: boolean;
77
+ /** Enable BM25 keyword search over indexed workspace content. */
78
+ bm25?: boolean;
79
+ }
80
+
81
+ /**
82
+ * Create a Mastra {@link Workspace} with per-request Databricks mounts.
83
+ *
84
+ * @example Assistant skills only (default for agents in this plugin)
85
+ * ```ts
86
+ * createWorkspace()
87
+ * ```
88
+ *
89
+ * @example Assistant skills plus a custom mount resolver
90
+ * ```ts
91
+ * createWorkspace({
92
+ * assistantSkills: true,
93
+ * mounts: [
94
+ * async ({ requestContext }) => ({
95
+ * mounts: { "/data": myFilesystem },
96
+ * skillPaths: [],
97
+ * }),
98
+ * ],
99
+ * })
100
+ * ```
101
+ */
102
+ export function createWorkspace(options: CreateWorkspaceOptions = {}): Workspace {
103
+ const { id, name } = resolveWorkspaceIdentity(options);
104
+ const resolvers = buildMountResolvers(options);
105
+ const skills =
106
+ options.skills ?? (resolvers.length > 0 ? buildWorkspaceSkillsResolver(resolvers) : undefined);
107
+ const checkSkillFileMtime = options.checkSkillFileMtime ?? options.assistantSkills !== false;
108
+ const bm25 = options.bm25 !== false;
109
+ logger.debug("workspace:create", {
110
+ id,
111
+ name,
112
+ resolverCount: resolvers.length,
113
+ assistantSkills: options.assistantSkills !== false,
114
+ customMountResolvers: options.mounts?.length ?? 0,
115
+ customSkillsResolver: Boolean(options.skills),
116
+ checkSkillFileMtime,
117
+ bm25,
118
+ });
119
+
120
+ return new Workspace({
121
+ id,
122
+ name,
123
+ filesystem: (context) => resolveWorkspaceFilesystem(resolvers, context),
124
+ ...(skills
125
+ ? {
126
+ skills,
127
+ checkSkillFileMtime,
128
+ }
129
+ : {}),
130
+ bm25,
131
+ });
132
+ }
133
+
134
+ /* ---------------------------- private helpers ---------------------------- */
135
+
136
+ /**
137
+ * Map an OBO user email to their Assistant skills directory in the
138
+ * workspace namespace.
139
+ */
140
+ function userAssistantSkillsPath(userEmail: string): string {
141
+ return `/Users/${userEmail.trim()}/.assistant/skills`;
142
+ }
143
+
144
+ /**
145
+ * Return whether the request token carries a scope that allows workspace
146
+ * file API access (`workspace` or `all-apis` on {@link MASTRA_SCOPES_KEY}).
147
+ */
148
+ function hasWorkspaceFileScope(requestContext: RequestContext | undefined): boolean {
149
+ return token.includesAccessTokenScope(
150
+ requestContext?.get(MASTRA_SCOPES_KEY),
151
+ WORKSPACE_FILE_SCOPES,
152
+ );
153
+ }
154
+
155
+ /**
156
+ * Built-in mount resolver for Assistant `SKILL.md` trees.
157
+ *
158
+ * Mounts {@link ASSISTANT_SHARED_SKILLS_PATH} when scope checks pass and
159
+ * `/Users/<email>/.assistant/skills` when {@link MASTRA_USER_EMAIL_KEY} is
160
+ * set. Returns empty mounts when the OBO user or client is missing.
161
+ * Mastra owns filesystem initialization.
162
+ */
163
+ function resolveAssistantSkillsMounts(context: WorkspaceMountContext): WorkspaceMountContribution {
164
+ const mounts: Record<string, DatabricksWorkspaceFilesystem> = {};
165
+ const requestContext = context.requestContext;
166
+
167
+ if (!shouldMountAssistantSkills(requestContext)) {
168
+ logger.debug("assistant-skills:skipped", {
169
+ reason: !requestContext ? "no-request-context" : "missing-workspace-scope",
170
+ nodeEnv: process.env.NODE_ENV,
171
+ scopes: context.requestContext?.get(MASTRA_SCOPES_KEY),
172
+ });
173
+ return { mounts, skillPaths: [] };
174
+ }
175
+
176
+ const user = requestContext!.get(MASTRA_USER_KEY) as User | undefined;
177
+ const client = user?.executionContext.client;
178
+ if (!client) {
179
+ logger.debug("assistant-skills:skipped", {
180
+ reason: "missing-obo-client",
181
+ userId: user?.id,
182
+ });
183
+ return { mounts, skillPaths: [] };
184
+ }
185
+
186
+ mounts[ASSISTANT_WORKSPACE_SKILLS_MOUNT] = databricksFilesystem(
187
+ client,
188
+ ASSISTANT_SHARED_SKILLS_PATH,
189
+ );
190
+
191
+ const email = resolveScopedEmail(requestContext);
192
+ if (email) {
193
+ mounts[ASSISTANT_USER_SKILLS_MOUNT] = databricksFilesystem(
194
+ client,
195
+ userAssistantSkillsPath(email),
196
+ false,
197
+ );
198
+ }
199
+
200
+ logger.debug("assistant-skills:mounted", {
201
+ sharedPath: ASSISTANT_SHARED_SKILLS_PATH,
202
+ sharedMount: ASSISTANT_WORKSPACE_SKILLS_MOUNT,
203
+ userMount: email ? ASSISTANT_USER_SKILLS_MOUNT : undefined,
204
+ userPath: email ? userAssistantSkillsPath(email) : undefined,
205
+ mountKeys: Object.keys(mounts),
206
+ });
207
+
208
+ return { mounts, skillPaths: Object.keys(mounts) };
209
+ }
210
+
211
+ /**
212
+ * Fill in `id` and `name` when either is omitted on {@link CreateWorkspaceOptions}.
213
+ * Slugifies `name` into `id`; tokenizes `id` into a display `name`.
214
+ */
215
+ function resolveWorkspaceIdentity(options: CreateWorkspaceOptions): {
216
+ id: string;
217
+ name: string;
218
+ } {
219
+ let id = options.id;
220
+ let name = options.name;
221
+ if (!id) {
222
+ id = name ? string.toSlug(name) : "workspace";
223
+ }
224
+ if (!name) {
225
+ name = Array.from(string.tokenize(id)).join(" ");
226
+ }
227
+ return { id, name };
228
+ }
229
+
230
+ /** Collect built-in and caller-supplied mount resolvers for one workspace. */
231
+ function buildMountResolvers(options: CreateWorkspaceOptions): WorkspaceMountResolver[] {
232
+ const resolvers: WorkspaceMountResolver[] = [];
233
+ const { assistantSkills = true, mounts } = options;
234
+ if (assistantSkills) {
235
+ resolvers.push(resolveAssistantSkillsMounts);
236
+ }
237
+ if (mounts?.length) {
238
+ resolvers.push(...mounts);
239
+ }
240
+ logger.debug("mounts:resolvers", {
241
+ assistantSkills,
242
+ builtInResolver: assistantSkills,
243
+ customResolverCount: mounts?.length ?? 0,
244
+ totalResolverCount: resolvers.length,
245
+ });
246
+ return resolvers;
247
+ }
248
+
249
+ /**
250
+ * Gate Assistant skill mounts on request context.
251
+ *
252
+ * Always allows mounts in development; in other environments requires
253
+ * {@link hasWorkspaceFileScope}.
254
+ */
255
+ function shouldMountAssistantSkills(
256
+ requestContext: RequestContext | undefined,
257
+ ): requestContext is RequestContext {
258
+ if (!requestContext) return false;
259
+ if (process.env.NODE_ENV === "development") return true;
260
+ return hasWorkspaceFileScope(requestContext);
261
+ }
262
+
263
+ /** Read the trimmed OBO user email stamped on {@link MASTRA_USER_EMAIL_KEY}. */
264
+ function resolveScopedEmail(requestContext: RequestContext | undefined): string | undefined {
265
+ const email = requestContext?.get(MASTRA_USER_EMAIL_KEY) as string | undefined;
266
+ return email?.trim() || undefined;
267
+ }
268
+
269
+ /** Construct a read-only {@link DatabricksWorkspaceFilesystem} for `basePath`. */
270
+ function databricksFilesystem(
271
+ client: WorkspaceClient,
272
+ basePath: string,
273
+ readOnly: boolean = true,
274
+ ): DatabricksWorkspaceFilesystem {
275
+ return new DatabricksWorkspaceFilesystem({
276
+ client,
277
+ basePath,
278
+ readOnly,
279
+ });
280
+ }
281
+
282
+ /**
283
+ * Run every mount resolver for one request and merge mounts plus skill paths.
284
+ * Later resolvers overwrite mount keys from earlier ones.
285
+ */
286
+ async function resolveWorkspaceContribution(
287
+ resolvers: WorkspaceMountResolver[],
288
+ context: WorkspaceMountContext,
289
+ ): Promise<WorkspaceMountContribution> {
290
+ const mounts: Record<string, WorkspaceFilesystem> = {};
291
+ const skillPaths: string[] = [];
292
+
293
+ for (const [index, resolver] of resolvers.entries()) {
294
+ const contribution = await resolver(context);
295
+ logger.debug("mounts:resolver", {
296
+ index,
297
+ mountKeys: Object.keys(contribution.mounts),
298
+ skillPaths: contribution.skillPaths ?? [],
299
+ });
300
+ Object.assign(mounts, contribution.mounts);
301
+ if (contribution.skillPaths?.length) {
302
+ skillPaths.push(...contribution.skillPaths);
303
+ }
304
+ }
305
+
306
+ logger.debug("mounts:merged", {
307
+ mountKeys: Object.keys(mounts),
308
+ skillPaths,
309
+ });
310
+
311
+ return { mounts, skillPaths };
312
+ }
313
+
314
+ /**
315
+ * Dynamic filesystem resolver passed to Mastra {@link Workspace}.
316
+ *
317
+ * Returns a {@link CompositeFilesystem} when any mount resolved; otherwise
318
+ * {@link emptyFilesystem}.
319
+ */
320
+ async function resolveWorkspaceFilesystem(
321
+ resolvers: WorkspaceMountResolver[],
322
+ context: WorkspaceMountContext,
323
+ ): Promise<WorkspaceFilesystem> {
324
+ const { mounts } = await resolveWorkspaceContribution(resolvers, context);
325
+ const mountKeys = Object.keys(mounts);
326
+ if (mountKeys.length === 0) {
327
+ logger.debug("filesystem:empty", {
328
+ hasRequestContext: Boolean(context.requestContext),
329
+ });
330
+ return emptyFilesystem();
331
+ }
332
+ logger.debug("filesystem:composite", { mountKeys });
333
+ return new CompositeFilesystem({ mounts });
334
+ }
335
+
336
+ /**
337
+ * Build the dynamic {@link SkillsResolver} that collects `skillPaths` from
338
+ * every mount resolver on each request.
339
+ */
340
+ function buildWorkspaceSkillsResolver(resolvers: WorkspaceMountResolver[]): SkillsResolver {
341
+ return async (context: SkillsContext) => {
342
+ const { skillPaths } = await resolveWorkspaceContribution(resolvers, context);
343
+ logger.debug("skills:resolved", { skillPaths });
344
+ return skillPaths ?? [];
345
+ };
346
+ }
package/src/writer.ts ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Shared helper for publishing events through Mastra's
3
+ * `ctx.writer`. Centralizes the "the downstream stream may already
4
+ * be closed, don't take the whole tool down" pattern that the
5
+ * Genie agent and chart tool both need.
6
+ *
7
+ * Failures are logged at `warn` (a persistently-closed writer is
8
+ * the most likely culprit when events go missing client-side) but
9
+ * swallowed so a cancelled request or a client that navigated
10
+ * away can't crash a tool mid-flight.
11
+ */
12
+
13
+ import type { MastraWriter } from "@dbx-tools/shared-mastra";
14
+ import { error, log } from "@dbx-tools/shared-core";
15
+
16
+ /**
17
+ * Best-effort `writer.write`. No-op when `writer` is undefined;
18
+ * caught errors are logged via `log.warn("writer:error", ...)`
19
+ * along with any caller-supplied `context` fields (e.g. a
20
+ * `chartId` or `messageId`) so the warning is greppable per
21
+ * resource.
22
+ *
23
+ * Returns when the write resolves or rejects; never throws.
24
+ */
25
+ export async function safeWrite(
26
+ log: log.Logger,
27
+ writer: MastraWriter | undefined,
28
+ chunk: unknown,
29
+ context: Record<string, unknown> = {},
30
+ ): Promise<void> {
31
+ if (!writer) {
32
+ log.debug("writer:no-writer", context);
33
+ return;
34
+ }
35
+ try {
36
+ await writer.write(chunk);
37
+ log.debug("writer:ok", context);
38
+ } catch (err) {
39
+ log.warn("writer:error", {
40
+ ...context,
41
+ error: error.errorMessage(err),
42
+ });
43
+ }
44
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,41 @@
1
+ // ~~ Generated by projen. To modify, edit .projenrc.js and run "pnpm exec projen".
2
+ {
3
+ "compilerOptions": {
4
+ "rootDir": "src",
5
+ "outDir": "lib",
6
+ "alwaysStrict": true,
7
+ "declaration": true,
8
+ "esModuleInterop": true,
9
+ "experimentalDecorators": true,
10
+ "inlineSourceMap": true,
11
+ "inlineSources": true,
12
+ "lib": [
13
+ "ES2022"
14
+ ],
15
+ "module": "ESNext",
16
+ "noEmitOnError": false,
17
+ "noFallthroughCasesInSwitch": true,
18
+ "noImplicitAny": true,
19
+ "noImplicitReturns": true,
20
+ "noImplicitThis": true,
21
+ "noUnusedLocals": true,
22
+ "noUnusedParameters": true,
23
+ "resolveJsonModule": true,
24
+ "strict": true,
25
+ "strictNullChecks": true,
26
+ "strictPropertyInitialization": true,
27
+ "stripInternal": true,
28
+ "target": "ES2022",
29
+ "types": [
30
+ "node"
31
+ ],
32
+ "moduleResolution": "bundler",
33
+ "skipLibCheck": true
34
+ },
35
+ "include": [
36
+ "src/**/*.ts"
37
+ ],
38
+ "exclude": [
39
+ "node_modules"
40
+ ]
41
+ }
package/dist/index.d.ts DELETED
@@ -1,20 +0,0 @@
1
- /**
2
- * AppKit Mastra integration: {@link MastraPlugin} / {@link mastra},
3
- * plugin config types, agent registration helpers, Genie tool
4
- * builders, and dynamic Model Serving endpoint resolution.
5
- *
6
- * Client-side consumers should import URL helpers and the
7
- * {@link MastraClientConfig} type from `@dbx-tools/appkit-mastra-shared`
8
- * instead - that package is pure (no pg / fastembed / Mastra deps) and
9
- * is the right surface for browser bundles and `usePluginClientConfig`
10
- * consumers.
11
- */
12
- export * from "./src/plugin.js";
13
- export * from "@dbx-tools/appkit-mastra-shared";
14
- export * from "./src/config.js";
15
- export * from "./src/agents.js";
16
- export * from "./src/chart.js";
17
- export * from "./src/genie.js";
18
- export * from "./src/tools/email.js";
19
- export { clearServingEndpointsCache, extractModelOverride, listServingEndpoints, MASTRA_MODEL_OVERRIDE_KEY, MODEL_OVERRIDE_BODY_FIELDS, MODEL_OVERRIDE_HEADER, MODEL_OVERRIDE_QUERY, resolveModelId, type ResolvedModel, type ResolveModelOptions, type ServingEndpointSummary, } from "./src/serving.js";
20
- export { FALLBACK_MODEL_IDS, MODEL_CATALOG, modelForTier, modelsForTier, ModelTier, } from "./src/model.js";
package/dist/index.js DELETED
@@ -1,20 +0,0 @@
1
- /**
2
- * AppKit Mastra integration: {@link MastraPlugin} / {@link mastra},
3
- * plugin config types, agent registration helpers, Genie tool
4
- * builders, and dynamic Model Serving endpoint resolution.
5
- *
6
- * Client-side consumers should import URL helpers and the
7
- * {@link MastraClientConfig} type from `@dbx-tools/appkit-mastra-shared`
8
- * instead - that package is pure (no pg / fastembed / Mastra deps) and
9
- * is the right surface for browser bundles and `usePluginClientConfig`
10
- * consumers.
11
- */
12
- export * from "./src/plugin.js";
13
- export * from "@dbx-tools/appkit-mastra-shared";
14
- export * from "./src/config.js";
15
- export * from "./src/agents.js";
16
- export * from "./src/chart.js";
17
- export * from "./src/genie.js";
18
- export * from "./src/tools/email.js";
19
- export { clearServingEndpointsCache, extractModelOverride, listServingEndpoints, MASTRA_MODEL_OVERRIDE_KEY, MODEL_OVERRIDE_BODY_FIELDS, MODEL_OVERRIDE_HEADER, MODEL_OVERRIDE_QUERY, resolveModelId, } from "./src/serving.js";
20
- export { FALLBACK_MODEL_IDS, MODEL_CATALOG, modelForTier, modelsForTier, ModelTier, } from "./src/model.js";