@dbx-tools/appkit-mastra 0.1.58 → 0.1.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +41 -1
  2. package/dist/index.d.ts +1229 -17
  3. package/dist/index.js +3348 -19
  4. package/package.json +17 -30
  5. package/dist/src/agents.d.ts +0 -316
  6. package/dist/src/agents.js +0 -470
  7. package/dist/src/chart.d.ts +0 -153
  8. package/dist/src/chart.js +0 -570
  9. package/dist/src/config.d.ts +0 -295
  10. package/dist/src/config.js +0 -55
  11. package/dist/src/genie.d.ts +0 -161
  12. package/dist/src/genie.js +0 -973
  13. package/dist/src/history.d.ts +0 -95
  14. package/dist/src/history.js +0 -278
  15. package/dist/src/memory.d.ts +0 -109
  16. package/dist/src/memory.js +0 -253
  17. package/dist/src/model.d.ts +0 -52
  18. package/dist/src/model.js +0 -198
  19. package/dist/src/observability.d.ts +0 -64
  20. package/dist/src/observability.js +0 -83
  21. package/dist/src/plugin.d.ts +0 -177
  22. package/dist/src/plugin.js +0 -554
  23. package/dist/src/processor.d.ts +0 -8
  24. package/dist/src/processor.js +0 -40
  25. package/dist/src/processors/strip-stale-charts.d.ts +0 -32
  26. package/dist/src/processors/strip-stale-charts.js +0 -98
  27. package/dist/src/server.d.ts +0 -51
  28. package/dist/src/server.js +0 -152
  29. package/dist/src/serving.d.ts +0 -65
  30. package/dist/src/serving.js +0 -79
  31. package/dist/src/statement.d.ts +0 -66
  32. package/dist/src/statement.js +0 -111
  33. package/dist/src/writer.d.ts +0 -23
  34. package/dist/src/writer.js +0 -37
  35. package/dist/tsconfig.build.tsbuildinfo +0 -1
  36. package/index.ts +0 -27
  37. package/src/agents.ts +0 -772
  38. package/src/chart.ts +0 -716
  39. package/src/config.ts +0 -320
  40. package/src/genie.ts +0 -1123
  41. package/src/history.ts +0 -322
  42. package/src/memory.ts +0 -293
  43. package/src/model.ts +0 -257
  44. package/src/observability.ts +0 -114
  45. package/src/plugin.ts +0 -623
  46. package/src/processor.ts +0 -46
  47. package/src/processors/strip-stale-charts.ts +0 -102
  48. package/src/server.ts +0 -195
  49. package/src/serving.ts +0 -104
  50. package/src/statement.ts +0 -120
  51. package/src/writer.ts +0 -44
package/src/agents.ts DELETED
@@ -1,772 +0,0 @@
1
- /**
2
- * Agent registration for the Mastra AppKit plugin.
3
- *
4
- * Mirrors the shape of the AppKit `agents` plugin (`config.agents` map
5
- * of {@link MastraAgentDefinition}, dual-form `tools` accepting a plain
6
- * record or a `(plugins) => tools` callback). Resolves each definition
7
- * into a Mastra `Agent` instance during plugin setup; user-supplied
8
- * tool callbacks are invoked exactly once with a typed
9
- * {@link MastraPlugins} map built from registered sibling plugins.
10
- *
11
- * When no agents are registered the plugin falls back to a single
12
- * built-in analyst so the bare `mastra()` call still mounts a working
13
- * streamable agent for demos.
14
- */
15
-
16
- import { appkitUtils, logUtils, stringUtils } from "@dbx-tools/shared";
17
- import type { AgentConfig, ToolsInput } from "@mastra/core/agent";
18
- import { Agent } from "@mastra/core/agent";
19
- import type { Tool } from "@mastra/core/tools";
20
- import { createTool } from "@mastra/core/tools";
21
- import type { PgVectorConfig, PostgresStoreConfig } from "@mastra/pg";
22
-
23
- import { buildRenderDataTool } from "./chart.js";
24
- import type { MastraPluginConfig } from "./config.js";
25
- import { buildGenieToolkitProvider, resolveGenieSpaces } from "./genie.js";
26
- import type { MemoryBuilder } from "./memory.js";
27
- import { buildModel, FALLBACK_MODEL_IDS } from "./model.js";
28
- import { ResultProcessor } from "./processor.js";
29
- import { stripStaleChartsProcessor } from "./processors/strip-stale-charts.js";
30
-
31
- /**
32
- * Tool record accepted by every Mastra `Agent.tools` field and by the
33
- * `tools(plugins)` callback on {@link MastraAgentDefinition}.
34
- *
35
- * Alias of Mastra's `ToolsInput`, so it already accepts:
36
- *
37
- * - Mastra tools built with {@link createTool} (or `new Tool(...)`)
38
- * - Mastra tools built with the AppKit-shaped {@link tool} wrapper
39
- * below
40
- * - Vercel AI SDK tools (`tool({ ... })` from `ai`)
41
- * - Provider-defined tools (e.g. `openai.tools.webSearch(...)`)
42
- *
43
- * Existing tool libraries drop in as-is - nothing in this package
44
- * forces a rebuild.
45
- */
46
- export type MastraTools = ToolsInput;
47
-
48
- /** Re-export of Mastra's native `createTool` for full-feature access. */
49
- export { createTool } from "@mastra/core/tools";
50
-
51
- /**
52
- * AppKit-shaped tool factory. Lets users mix-and-match tools across
53
- * AppKit's `agents` plugin and `mastra` with a single import:
54
- *
55
- * ```ts
56
- * import { tool } from "@dbx-tools/appkit-mastra";
57
- * import { z } from "zod";
58
- *
59
- * get_weather: tool({
60
- * description: "Weather",
61
- * schema: z.object({ city: z.string() }),
62
- * execute: async ({ city }) => `Sunny in ${city}`,
63
- * }),
64
- * ```
65
- *
66
- * Maps onto Mastra's `createTool`:
67
- *
68
- * - `description` -> `description` (required)
69
- * - `schema` -> `inputSchema` (optional)
70
- * - `execute(input)` -> `execute(input, ctx)` - Mastra already calls
71
- * the first arg with the parsed inputs, so the body shape is
72
- * identical. The Mastra `context` arg is forwarded as the second
73
- * parameter when the caller declares it.
74
- * - `id`: optional. Defaults to a stable identifier derived from
75
- * `description` (slugified, with a short hash suffix for
76
- * uniqueness). Pass an explicit `id` when you need a stable string
77
- * for tracing or MCP exposure.
78
- *
79
- * Reach for {@link createTool} when you need Mastra-only fields
80
- * (`outputSchema`, `suspendSchema`, `requireApproval`, `mcp`, etc.).
81
- */
82
- export function tool(opts: AppKitToolOptions): Tool {
83
- const id = opts.id ?? deriveToolId(opts.description);
84
- return createTool({
85
- id,
86
- description: opts.description,
87
- ...(opts.schema ? { inputSchema: opts.schema as never } : {}),
88
- execute: opts.execute as never,
89
- });
90
- }
91
-
92
- /**
93
- * Input shape for the AppKit-style {@link tool} factory. A trimmed
94
- * subset of Mastra's `createTool` options that mirrors the
95
- * `@databricks/appkit/beta` `tool({ description, schema, execute })`
96
- * signature.
97
- *
98
- * Generics are intentionally absent - inference flows through the
99
- * caller's `schema` (typically a Zod object), and the `execute` body
100
- * destructures naturally from that. Reach for {@link createTool} when
101
- * you need the fully-typed input/output schemas wired explicitly.
102
- */
103
- export interface AppKitToolOptions {
104
- /** Optional stable identifier; auto-derived from `description` when omitted. */
105
- id?: string;
106
- /** Human-readable description shown to the model. Required. */
107
- description: string;
108
- /**
109
- * Optional input schema (any Standard Schema instance, e.g. Zod).
110
- * Maps to Mastra's `inputSchema`; passed through to the model
111
- * verbatim.
112
- */
113
- schema?: unknown;
114
- /**
115
- * Execute body. First arg is the parsed input (typed off `schema`
116
- * when supplied), second arg is the full Mastra execution context
117
- * (request context, abort signal, mastra instance) if you need it.
118
- */
119
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
120
- execute: (input: any, context?: unknown) => unknown;
121
- }
122
-
123
- /**
124
- * Build a deterministic Mastra tool id from a description.
125
- * Delegates to {@link stringUtils.toUniqueSlug}: slug + always-on
126
- * 6-char FNV-1a base-32 suffix so two tools with the same leading
127
- * words don't collide in traces. Stable across runs.
128
- */
129
- function deriveToolId(description: string): string {
130
- return stringUtils.toUniqueSlug(description, { fallbackPrefix: "tool" });
131
- }
132
-
133
- /**
134
- * Identity helper that brands a definition as a Mastra agent. Mirrors
135
- * AppKit's `createAgent(def)` so the registration shape matches:
136
- *
137
- * ```ts
138
- * const support = createAgent({
139
- * instructions: "...",
140
- * model: "databricks-claude-sonnet-4-6",
141
- * tools(plugins) { return { ... }; },
142
- * });
143
- * ```
144
- *
145
- * Returns the definition unchanged - the wrapper exists only to anchor
146
- * type inference and to match the AppKit API surface.
147
- */
148
- export function createAgent<T extends MastraAgentDefinition>(def: T): T {
149
- return def;
150
- }
151
-
152
- /**
153
- * Filter / rename options accepted by every plugin's `.toolkit()`
154
- * method. Mirrors AppKit's `ToolkitOptions` verbatim so options pass
155
- * through unchanged - the underlying AppKit plugin does the filtering
156
- * and we just adapt the resulting entries into Mastra tools.
157
- */
158
- export interface ToolkitOptions {
159
- /**
160
- * Key prefix prepended to every tool name. AppKit's default is
161
- * `${pluginName}.` when omitted; pass an explicit `""` to drop it.
162
- */
163
- prefix?: string;
164
- /** Allowlist of local tool names. */
165
- only?: string[];
166
- /** Denylist of local tool names. */
167
- except?: string[];
168
- /** Remap specific local names to different keys. */
169
- rename?: Record<string, string>;
170
- }
171
-
172
- /**
173
- * Toolkit provider shape every entry in the {@link MastraPlugins} map
174
- * exposes. Identical to AppKit's `PluginToolkitProvider` - any AppKit
175
- * plugin that implements the standard `ToolProvider` interface
176
- * (`getAgentTools` + `executeAgentTool` + `toolkit`) is reachable
177
- * through this surface automatically.
178
- */
179
- export interface MastraPluginToolkitProvider {
180
- /**
181
- * Returns a Mastra-shaped tools record adapted from the plugin's
182
- * agent tools. Each tool dispatches back through the plugin's
183
- * `executeAgentTool` so OBO auth and telemetry spans stay intact.
184
- */
185
- toolkit(opts?: ToolkitOptions): MastraTools;
186
- }
187
-
188
- /**
189
- * Plugin map handed to the function form of
190
- * {@link MastraAgentDefinition.tools}. Mirrors AppKit's `Plugins`
191
- * type exactly: a string-keyed record where every value exposes
192
- * `.toolkit(opts)`.
193
- *
194
- * Implemented as a runtime Proxy that auto-discovers any registered
195
- * AppKit plugin implementing the standard `ToolProvider` interface
196
- * (`analytics`, `files`, `lakebase`, `genie`, plus any third-party
197
- * plugin that does the same). Unknown names resolve to `undefined`
198
- * at runtime, so guard with `?.` and `?? {}` when spreading from a
199
- * plugin that may not be registered in every environment.
200
- *
201
- * @example
202
- * ```ts
203
- * createAgent({
204
- * instructions: "...",
205
- * tools(plugins) {
206
- * return {
207
- * ...plugins.analytics.toolkit(),
208
- * ...plugins.files.toolkit({ only: ["uploads.read"] }),
209
- * get_weather: tool({
210
- * description: "Weather",
211
- * schema: z.object({ city: z.string() }),
212
- * execute: async ({ city }) => `Sunny in ${city}`,
213
- * }),
214
- * };
215
- * },
216
- * });
217
- * ```
218
- */
219
- export type MastraPlugins = Record<string, MastraPluginToolkitProvider>;
220
-
221
- /** Function form of {@link MastraAgentDefinition.tools}. */
222
- export type MastraToolsFn = (
223
- plugins: MastraPlugins,
224
- ) => MastraTools | Promise<MastraTools>;
225
-
226
- /**
227
- * A code-defined Mastra agent. Mirrors the shape AppKit's `agents`
228
- * plugin uses for `AgentDefinition`. The registry key under
229
- * `config.agents` is the `agentId` the client streams against; `name`
230
- * is purely informational (defaults to the key).
231
- */
232
- export interface MastraAgentDefinition {
233
- /** Display name used as `Agent.name`. Defaults to the registry key. */
234
- name?: string;
235
- /** Optional long-form description; surfaced as `Agent.description`. */
236
- description?: string;
237
- /** System prompt body. */
238
- instructions: string;
239
- /**
240
- * Per-agent model override.
241
- *
242
- * - `undefined` (default): falls back to the workspace
243
- * `/serving-endpoints` resolver that {@link buildModel} configures
244
- * from the per-request `WorkspaceClient`.
245
- * - `string`: shorthand for "use the default resolver but swap the
246
- * `modelId`" (e.g. `"databricks-meta-llama-3-3-70b-instruct"`).
247
- * - Any other Mastra `DynamicArgument<MastraModelConfig>`: passed
248
- * straight through to `Agent.model`. Use this when you need full
249
- * control over auth or providerId.
250
- */
251
- model?: AgentConfig["model"] | string;
252
- /**
253
- * Per-agent tool record. Either a plain map or a callback that
254
- * receives the typed {@link MastraPlugins} sibling-plugin index and
255
- * returns a map. The callback runs exactly once at agent setup; the
256
- * result is cached for the agent's lifetime.
257
- */
258
- tools?: MastraTools | MastraToolsFn;
259
- /**
260
- * Per-agent semantic recall (PgVector) override. Cascades from
261
- * `config.memory`; the agent value wins when set.
262
- *
263
- * - `undefined` (default): inherit `config.memory`. When that's
264
- * enabled, the agent **shares the plugin-level singleton `PgVector`
265
- * instance** (cross-agent semantic recall across the same index).
266
- * - `false`: disable semantic recall for this agent only.
267
- * - `true`: enable using the shared singleton (same as default when
268
- * plugin memory is enabled; useful to opt in when plugin disabled).
269
- * - {@link MastraMemoryConfig} object: dedicated `PgVector` for this
270
- * agent (private recall index). Bypasses the shared singleton.
271
- */
272
- memory?: boolean | MastraMemoryConfigOverride;
273
- /**
274
- * Per-agent thread/message storage (`PostgresStore`) override.
275
- * Cascades from `config.storage`; the agent value wins when set.
276
- *
277
- * - `undefined` (default): inherit `config.storage`. When that's
278
- * enabled, the agent gets its **own per-agent `PostgresStore`**
279
- * keyed by `schemaName: "mastra_<agentId>"` so threads and
280
- * messages stay isolated between agents in the same database.
281
- * - `false`: disable storage for this agent only (purely in-memory).
282
- * - `true`: enable with the per-agent default schema.
283
- * - {@link MastraStorageConfigOverride} object: dedicated
284
- * `PostgresStore` config (custom schema, connection, etc.).
285
- */
286
- storage?: boolean | MastraStorageConfigOverride;
287
- }
288
-
289
- /**
290
- * Distributive `Omit` so unions in `PostgresStoreConfig` /
291
- * `PgVectorConfig` keep their discriminants after the override types
292
- * strip `id`. The built-in `Omit` collapses unions to one shape with
293
- * common fields only, which loses the connection-style discriminants.
294
- */
295
- type DistributiveOmit<T, K extends keyof never> = T extends unknown
296
- ? Omit<T, K>
297
- : never;
298
-
299
- /**
300
- * `PostgresStoreConfig` minus `id` - per-agent overrides accept any
301
- * Mastra-supported storage shape. `id` is filled in automatically
302
- * from the agent registry key so traces stay stable.
303
- */
304
- export type MastraStorageConfigOverride = DistributiveOmit<
305
- PostgresStoreConfig,
306
- "id"
307
- > & { id?: string };
308
-
309
- /**
310
- * `PgVectorConfig` minus `id` - per-agent overrides accept any
311
- * Mastra-supported vector shape. `id` is filled in automatically
312
- * from the agent registry key.
313
- */
314
- export type MastraMemoryConfigOverride = DistributiveOmit<PgVectorConfig, "id"> & {
315
- id?: string;
316
- };
317
-
318
- /** Output of {@link buildAgents}: resolved agents plus the default id. */
319
- export interface BuiltAgents {
320
- agents: Record<string, Agent>;
321
- defaultAgentId: string;
322
- }
323
-
324
- /** Fallback agent id used when `config.agents` is omitted entirely. */
325
- export const FALLBACK_AGENT_ID = "default";
326
-
327
- /**
328
- * Default per-turn step ceiling applied to every registered agent
329
- * when {@link MastraPluginConfig.agentMaxSteps} is unset. Sized to
330
- * fit a decomposed Genie turn (grounding + several `ask_genie`
331
- * calls + `prepare_chart` per dataset + the final-text reply) with
332
- * headroom for the model to chain a couple of follow-ups before
333
- * answering - well above Mastra's own `agent.generate` default of
334
- * 5, which would cut multi-step orchestration off mid-loop.
335
- */
336
- export const DEFAULT_AGENT_MAX_STEPS = 25;
337
-
338
- const FALLBACK_AGENT_INSTRUCTIONS = `You are a data analyst. The user will ask questions about
339
- business metrics and may share personal preferences you should remember across turns.
340
-
341
- Rules:
342
-
343
- 1. Quote numbers exactly. Never invent data.
344
- 2. When the user states a preference or durable fact about themselves
345
- ("I'm in EU so use EUR", "always show me the SQL"), acknowledge that
346
- you will remember it.
347
- 3. If you don't have enough information to answer, ask a clarifying
348
- question instead of guessing.`;
349
-
350
- /**
351
- * Style guardrails appended to every agent's `instructions` to curb
352
- * common LLM-isms (em dashes, emojis, sycophantic openers, excessive
353
- * hedging, throwaway closers). Appended rather than prepended so the
354
- * agent's role/context comes first; the model's recency bias then
355
- * helps the style rules dominate the response surface.
356
- *
357
- * Override globally via {@link MastraPluginConfig.styleInstructions}
358
- * (pass `false` to disable entirely, or a string to replace).
359
- */
360
- export const DEFAULT_STYLE_INSTRUCTIONS = [
361
- "Output style:",
362
- "",
363
- "Use markdown formatting, including headings, lists, and code blocks.",
364
- "Avoid lists and headers for short replies.",
365
- "Plain prose.",
366
- "Use hyphens (-) only. Never use em dashes or en dashes.",
367
- "Never use emojis.",
368
- "Skip openers like 'Great question', 'Absolutely', and 'I'd be happy to help'.",
369
- "Skip closers like 'Let me know if you have any questions'.",
370
- "Skip self-disclaimers like 'I should mention' and 'It's important to note'.",
371
- "Answer directly.",
372
- "Do not include a preamble before the actual answer.",
373
- "Use lists and headers only when they clarify a multi-part answer.",
374
- ].join("\n");
375
-
376
- /**
377
- * Resolve the style block to append to every agent's instructions.
378
- * Returns `null` when the caller opted out (`styleInstructions: false`).
379
- */
380
- function resolveStyleInstructions(config: MastraPluginConfig): string | null {
381
- if (config.styleInstructions === false) return null;
382
- if (typeof config.styleInstructions === "string") {
383
- return config.styleInstructions;
384
- }
385
-
386
- return DEFAULT_STYLE_INSTRUCTIONS;
387
- }
388
-
389
- /**
390
- * Join an agent's bespoke instructions with the resolved style block.
391
- * Returns the bespoke text unchanged when the style block is disabled.
392
- */
393
- function composeInstructions(agentInstructions: string, style: string | null): string {
394
- if (!style) return agentInstructions;
395
- return `${agentInstructions.trimEnd()}\n\n${style}`;
396
- }
397
-
398
- /**
399
- * Resolve every entry in `config.agents` into a Mastra `Agent`
400
- * instance. When `config.agents` is omitted the plugin registers a
401
- * single built-in `default` analyst so the bare `mastra()` call still
402
- * yields a working agent.
403
- *
404
- * Per-agent tool callbacks are invoked once with a typed
405
- * {@link MastraPlugins} index built from registered sibling plugins
406
- * (currently `genie`; extend `MastraPlugins` to surface more).
407
- *
408
- * @throws when `config.defaultAgent` is set to an id that isn't in the
409
- * resolved registry; this is a wiring bug, not a runtime condition.
410
- */
411
- export async function buildAgents(opts: {
412
- config: MastraPluginConfig;
413
- context: appkitUtils.PluginContextLike | undefined;
414
- memoryBuilder?: MemoryBuilder;
415
- log: logUtils.Logger;
416
- }): Promise<BuiltAgents> {
417
- const { config, context, memoryBuilder, log } = opts;
418
- const definitions = resolveDefinitions(config);
419
- const ids = Object.keys(definitions);
420
- const defaultAgentId = config.defaultAgent ?? ids[0] ?? FALLBACK_AGENT_ID;
421
-
422
- const plugins = buildPluginsMap(config, context);
423
- // System-default ambient tools every agent gets out of the box.
424
- // Currently just `render_data` for inline visualizations; the
425
- // user can shadow it by including a same-named tool in their own
426
- // `config.tools` or per-agent `tools`. Order in {@link resolveTools}
427
- // is `system -> user-ambient -> per-agent`, last write wins.
428
- const systemTools: MastraTools = {
429
- render_data: buildRenderDataTool(config),
430
- };
431
- const ambientTools = { ...systemTools, ...(config.tools ?? {}) };
432
- const style = resolveStyleInstructions(config);
433
- // Default-on protection against the model copying turn-scoped
434
- // chartIds from prior assistant tool results into the new
435
- // turn's `[chart:<id>]` markers. Opt out per-plugin via
436
- // `config.stripStaleCharts: false`.
437
- const outputProcessors = [new ResultProcessor()];
438
- const inputProcessors =
439
- config.stripStaleCharts === false ? [] : [stripStaleChartsProcessor];
440
- const agents: Record<string, Agent> = {};
441
-
442
- for (const [id, def] of Object.entries(definitions)) {
443
- const tools = await resolveTools(def.tools, plugins, ambientTools);
444
- const memory = memoryBuilder?.forAgent(id, def);
445
- agents[id] = new Agent({
446
- id,
447
- name: def.name ?? id,
448
- ...(def.description !== undefined ? { description: def.description } : {}),
449
- instructions: composeInstructions(def.instructions, style),
450
- model: resolveModel(config, def.model),
451
- defaultOptions: {
452
- maxSteps: config.agentMaxSteps ?? DEFAULT_AGENT_MAX_STEPS,
453
- },
454
- tools,
455
- ...(memory ? { memory } : {}),
456
- inputProcessors,
457
- outputProcessors,
458
- });
459
- // Surface the effective default model per agent so operators can
460
- // see at a glance which endpoint each agent points at without
461
- // having to fire a request and inspect a trace. The value is the
462
- // *static* default; per-request overrides (header / query /
463
- // body) and the workspace-catalogue fuzzy match still apply at
464
- // call time.
465
- log.info("agent registered", {
466
- id,
467
- name: def.name ?? id,
468
- defaultModel: describeAgentDefaultModel(config, def),
469
- tools: Object.keys(tools),
470
- });
471
- }
472
-
473
- if (!agents[defaultAgentId]) {
474
- throw new Error(
475
- `mastra: defaultAgent "${defaultAgentId}" not found in registered agents (${ids.join(", ") || "none"})`,
476
- );
477
- }
478
-
479
- log.info("agents ready", { ids, defaultAgentId });
480
- return { agents, defaultAgentId };
481
- }
482
-
483
- /**
484
- * Best-effort description of the *static* default model an agent will
485
- * resolve to at call time. Walks the same precedence ladder as
486
- * {@link resolveModel} / {@link buildModel}:
487
- *
488
- * 1. Per-agent `def.model` (string sugar -> the literal id;
489
- * function / `DynamicArgument` -> `"<dynamic>"` because the
490
- * resolver decides at call time).
491
- * 2. Plugin-level `config.defaultModel` (same rules).
492
- * 3. `DATABRICKS_SERVING_ENDPOINT_NAME` env var.
493
- * 4. First entry of `config.defaultModelFallbacks ?? FALLBACK_MODEL_IDS`.
494
- *
495
- * Used for the startup `agent registered` log so operators can see
496
- * which endpoint each agent points at by default. Per-request
497
- * overrides (`X-Mastra-Model` etc.) and the workspace-catalogue
498
- * fuzzy match are still applied at runtime.
499
- */
500
- function describeAgentDefaultModel(
501
- config: MastraPluginConfig,
502
- def: MastraAgentDefinition,
503
- ): string {
504
- const effective = def.model ?? config.defaultModel;
505
- if (typeof effective === "string") return effective;
506
- if (effective !== undefined) return "<dynamic>";
507
- return (
508
- process.env.DATABRICKS_SERVING_ENDPOINT_NAME ??
509
- config.defaultModelFallbacks?.[0] ??
510
- FALLBACK_MODEL_IDS[0]!
511
- );
512
- }
513
-
514
- /**
515
- * Normalize `config.agents` into a `Record<id, definition>`. Accepts
516
- * any of the three shapes documented on
517
- * {@link MastraPluginConfig.agents}:
518
- *
519
- * - Record - returned as-is when non-empty.
520
- * - Single definition (detected via the required `instructions`
521
- * field) - keyed by `slugify(def.name)` or `FALLBACK_AGENT_ID`.
522
- * - Array - keyed by `slugify(def.name)` or `agent_${i}`; duplicate
523
- * slugs fail loudly so users know to set explicit names.
524
- *
525
- * Omitted or empty inputs fall back to a single built-in analyst so
526
- * the bare `mastra()` call still mounts a working chat route.
527
- */
528
- function resolveDefinitions(
529
- config: MastraPluginConfig,
530
- ): Record<string, MastraAgentDefinition> {
531
- const input = config.agents;
532
- if (!input) return fallbackDefinitions();
533
-
534
- if (Array.isArray(input)) {
535
- if (input.length === 0) return fallbackDefinitions();
536
- const out: Record<string, MastraAgentDefinition> = {};
537
- input.forEach((def, i) => {
538
- const key = deriveAgentKey(def, i);
539
- if (out[key]) {
540
- throw new Error(
541
- `mastra: duplicate agent id "${key}" derived from name "${def.name ?? ""}"; ` +
542
- `set unique \`name\`s on each definition`,
543
- );
544
- }
545
- out[key] = def;
546
- });
547
- return out;
548
- }
549
-
550
- // Single-definition shorthand: an agent always has `instructions: string`,
551
- // a record-of-agents never has that field directly.
552
- if (typeof (input as MastraAgentDefinition).instructions === "string") {
553
- const def = input as MastraAgentDefinition;
554
- const key = deriveAgentKey(def);
555
- return { [key]: def };
556
- }
557
-
558
- const record = input as Record<string, MastraAgentDefinition>;
559
- if (Object.keys(record).length === 0) return fallbackDefinitions();
560
- return record;
561
- }
562
-
563
- /** Derive a registry id from a definition's `name`, with a fallback. */
564
- function deriveAgentKey(def: MastraAgentDefinition, index?: number): string {
565
- if (def.name) {
566
- const slug = stringUtils.toIdentifier(def.name);
567
- if (slug) return slug;
568
- }
569
- return index === undefined ? FALLBACK_AGENT_ID : `agent_${index}`;
570
- }
571
-
572
- /** Built-in fallback registry used when `agents` is omitted / empty. */
573
- function fallbackDefinitions(): Record<string, MastraAgentDefinition> {
574
- return {
575
- [FALLBACK_AGENT_ID]: {
576
- name: "Default Agent",
577
- instructions: FALLBACK_AGENT_INSTRUCTIONS,
578
- },
579
- };
580
- }
581
-
582
- /**
583
- * Pick the effective model spec for an agent. Fallback ladder, in
584
- * order:
585
- *
586
- * 1. Per-agent `def.model` (string sugar or `DynamicArgument`).
587
- * 2. Plugin-level `config.defaultModel` (string sugar or
588
- * `DynamicArgument`) - mirrors AppKit's `agents({ defaultModel })`.
589
- * 3. The auto-resolver that mints user-scoped tokens against
590
- * `/serving-endpoints` via {@link buildModel}.
591
- *
592
- * String values are treated as `modelId` sugar and threaded through
593
- * `buildModel`'s override hook so the runtime fuzzy matcher and the
594
- * per-request `X-Mastra-Model` override layer on top of the static
595
- * choice. Non-string `DynamicArgument`s are passed through verbatim;
596
- * callers that need full control over `providerId` / `headers` /
597
- * `modelId` bypass the resolver pipeline entirely.
598
- */
599
- function resolveModel(
600
- config: MastraPluginConfig,
601
- override: MastraAgentDefinition["model"],
602
- ): AgentConfig["model"] {
603
- const effective = override ?? config.defaultModel;
604
- if (effective === undefined) {
605
- return ({ requestContext }) => buildModel(config, requestContext);
606
- }
607
- if (typeof effective === "string") {
608
- const modelId = effective;
609
- return ({ requestContext }) => buildModel(config, requestContext, { modelId });
610
- }
611
- return effective;
612
- }
613
-
614
- /**
615
- * Resolve a definition's `tools` field to a flat `MastraTools` record,
616
- * merging in plugin-level ambient tools (per-agent tools win on key
617
- * collision). Callback errors propagate verbatim so the original stack
618
- * survives - the caller already knows which agent was registering.
619
- */
620
- async function resolveTools(
621
- defTools: MastraAgentDefinition["tools"],
622
- plugins: MastraPlugins,
623
- ambientTools: MastraTools,
624
- ): Promise<MastraTools> {
625
- if (!defTools) return { ...ambientTools };
626
- const resolved = typeof defTools === "function" ? await defTools(plugins) : defTools;
627
- return { ...ambientTools, ...resolved };
628
- }
629
-
630
- /**
631
- * Build the {@link MastraPlugins} runtime proxy handed to
632
- * `tools(plugins)` callbacks.
633
- *
634
- * Implemented as a `Proxy` over the AppKit plugin context so
635
- * `plugins.<name>` resolves at first access. Any sibling plugin that
636
- * implements AppKit's standard `ToolProvider` interface
637
- * (`toolkit(opts?)` + `executeAgentTool(name, args, signal?)`) is
638
- * auto-adapted into Mastra tools. Unknown names return `undefined`,
639
- * matching AppKit's `Plugins` semantics so `plugins.foo?.toolkit()`
640
- * remains safe in environments where `foo` isn't registered.
641
- *
642
- * `genie` is special-cased to swap the generic AppKit toolkit (which
643
- * runs `executeAgentTool` and only emits a single final `tool-result`
644
- * chunk per call) for the streaming-aware tools built by
645
- * {@link buildGenieProvider}. The streaming variant forwards each
646
- * Genie wire event (status, SQL, row counts, errors) out through the
647
- * Mastra `ctx.writer`, so the UI gets `tool-output` chunks in real
648
- * time instead of staring at a spinner for the full Genie round-trip.
649
- */
650
- function buildPluginsMap(
651
- config: MastraPluginConfig,
652
- context: appkitUtils.PluginContextLike | undefined,
653
- ): MastraPlugins {
654
- const cache = new Map<string, MastraPluginToolkitProvider | null>();
655
- return new Proxy({} as MastraPlugins, {
656
- get(_target, propName) {
657
- if (typeof propName !== "string") return undefined;
658
- if (cache.has(propName)) return cache.get(propName) ?? undefined;
659
- const provider = resolveProvider(config, context, propName);
660
- cache.set(propName, provider);
661
- return provider ?? undefined;
662
- },
663
- });
664
- }
665
-
666
- /**
667
- * Pick the right {@link MastraPluginToolkitProvider} for a sibling
668
- * plugin lookup. Returns the Genie agent-backed adapter when
669
- * the caller asks for `genie` AND at least one space is reachable
670
- * via {@link resolveGenieSpaces} (the explicit
671
- * `config.genieSpaces`, the registered AppKit `genie()` plugin's
672
- * `spaces` config, or the `DATABRICKS_GENIE_SPACE_ID` env var).
673
- * Falls back to the generic AppKit `ToolProvider` adapter for
674
- * every other plugin name. `config` is threaded through so the
675
- * Genie agent inherits the same model resolver / fallback
676
- * ladder the calling agents use.
677
- *
678
- * The Genie agent talks to Genie directly via `@dbx-tools/genie`
679
- * (`genieEventChat`) and the workspace
680
- * `statementExecution.getStatement` API. AppKit's stock `genie`
681
- * plugin is honored only for its resource manifest and `spaces`
682
- * config so existing `app.yaml` configs and `genie({ spaces })`
683
- * wiring keep working without change.
684
- */
685
- function resolveProvider(
686
- config: MastraPluginConfig,
687
- context: appkitUtils.PluginContextLike | undefined,
688
- propName: string,
689
- ): MastraPluginToolkitProvider | null {
690
- if (propName === "genie") {
691
- const spaces = resolveGenieSpaces(config, context);
692
- if (Object.keys(spaces).length === 0) return null;
693
- return buildGenieToolkitProvider({
694
- spaces,
695
- config,
696
- }) as MastraPluginToolkitProvider;
697
- }
698
- const plugin = context?.getPlugins().get(propName);
699
- return adaptPluginToolkit(plugin);
700
- }
701
-
702
- /**
703
- * AppKit `ToolProvider` shape we duck-type against any registered
704
- * plugin. Defined structurally to avoid coupling to AppKit's internal
705
- * type module layout.
706
- */
707
- interface AppKitToolkitProvider {
708
- toolkit?: (opts?: ToolkitOptions) => Record<string, AppKitToolkitEntry>;
709
- executeAgentTool?: (
710
- name: string,
711
- args: unknown,
712
- signal?: AbortSignal,
713
- ) => Promise<unknown>;
714
- }
715
-
716
- /** Single entry returned by an AppKit plugin's `.toolkit(opts)` call. */
717
- interface AppKitToolkitEntry {
718
- pluginName: string;
719
- localName: string;
720
- def: {
721
- name: string;
722
- description: string;
723
- parameters: unknown;
724
- };
725
- }
726
-
727
- /**
728
- * Adapt an AppKit `ToolProvider` plugin instance into a
729
- * {@link MastraPluginToolkitProvider}. Returns `null` for any plugin
730
- * that doesn't implement both `toolkit` and `executeAgentTool` (e.g.
731
- * `server`, `lakebase` when used only as a Postgres pool, etc.).
732
- */
733
- function adaptPluginToolkit(plugin: unknown): MastraPluginToolkitProvider | null {
734
- if (!plugin || typeof plugin !== "object") return null;
735
- const p = plugin as AppKitToolkitProvider;
736
- if (typeof p.toolkit !== "function" || typeof p.executeAgentTool !== "function") {
737
- return null;
738
- }
739
- return {
740
- toolkit(opts?: ToolkitOptions): MastraTools {
741
- const entries = p.toolkit!(opts);
742
- const tools: MastraTools = {};
743
- for (const [key, entry] of Object.entries(entries)) {
744
- tools[key] = toolkitEntryToMastraTool(entry, p);
745
- }
746
- return tools;
747
- },
748
- };
749
- }
750
-
751
- /**
752
- * Wrap a single {@link AppKitToolkitEntry} as a Mastra tool whose
753
- * `execute` dispatches back through `plugin.executeAgentTool(...)` so
754
- * AppKit's OBO auth (`asUser`) and telemetry spans stay intact. JSON
755
- * Schema parameters pass through unchanged - Mastra's `PublicSchema`
756
- * accepts `JSONSchema7` directly via `@mastra/schema-compat`.
757
- */
758
- function toolkitEntryToMastraTool(
759
- entry: AppKitToolkitEntry,
760
- plugin: AppKitToolkitProvider,
761
- ): Tool {
762
- return createTool({
763
- id: `${entry.pluginName}__${entry.localName}`,
764
- description: entry.def.description,
765
- ...(entry.def.parameters ? { inputSchema: entry.def.parameters as never } : {}),
766
- execute: async (input: unknown, context: unknown) => {
767
- const signal = (context as { abortSignal?: AbortSignal } | undefined)
768
- ?.abortSignal;
769
- return plugin.executeAgentTool!(entry.localName, input, signal);
770
- },
771
- });
772
- }