@dbx-tools/appkit-mastra 0.1.67 → 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.
package/src/config.ts DELETED
@@ -1,384 +0,0 @@
1
- /**
2
- * Plugin configuration types and shared `RequestContext` keys.
3
- *
4
- * Kept in a leaf module so `plugin.ts`, `server.ts`, `model.ts`, and
5
- * `memory.ts` can import them without creating a cycle.
6
- */
7
-
8
- import type { BasePluginConfig } from "@databricks/appkit";
9
- import type { appkitUtils } from "@dbx-tools/shared";
10
- import type { AgentConfig } from "@mastra/core/agent";
11
- import {
12
- MASTRA_RESOURCE_ID_KEY,
13
- MASTRA_THREAD_ID_KEY,
14
- } from "@mastra/core/request-context";
15
- import type { PgVectorConfig, PostgresStoreConfig } from "@mastra/pg";
16
-
17
- import type { MastraAgentDefinition, MastraTools } from "./agents.js";
18
- import type { GenieSpacesConfig } from "./genie.js";
19
-
20
- /**
21
- * `RequestContext` key under which {@link MastraServer} stores the
22
- * resolved AppKit user. `model.ts` reads it to mint user-scoped
23
- * Databricks tokens.
24
- */
25
- export const MASTRA_USER_KEY = "mastra__user";
26
-
27
- /**
28
- * `RequestContext` keys for AppKit user metadata stamped by
29
- * {@link MastraServer}. Surfaced as trace metadata via
30
- * {@link TRACE_REQUEST_CONTEXT_KEYS} so traces are filterable by who
31
- * issued the request without leaking the full user object.
32
- */
33
- export const MASTRA_USER_NAME_KEY = "mastra__userName";
34
- export const MASTRA_USER_EMAIL_KEY = "mastra__userEmail";
35
-
36
- /**
37
- * `RequestContext` key for the per-HTTP-request id stamped by
38
- * {@link MastraServer}. Reads `X-Request-Id` from the incoming
39
- * headers when present (so an upstream load balancer / API gateway
40
- * can keep its trace correlation), falls back to a freshly minted
41
- * UUID. Echoed back on the response and surfaced on every span via
42
- * {@link TRACE_REQUEST_CONTEXT_KEYS} so logs and traces share a
43
- * join key.
44
- */
45
- export const MASTRA_REQUEST_ID_KEY = "mastra__requestId";
46
-
47
- /**
48
- * Canonical list of `RequestContext` keys we want Mastra to extract
49
- * as metadata on every observability span (agent runs, model calls,
50
- * tool invocations, workflow steps).
51
- *
52
- * Mirrors {@link https://mastra.ai/docs/observability/tracing/overview#automatic-metadata-from-requestcontext}:
53
- * passed verbatim into `Observability.configs[*].requestContextKeys`,
54
- * so any key listed here is read from `RequestContext` at trace
55
- * start and attached as scalar span metadata. Keep the set to plain
56
- * scalars - never include {@link MASTRA_USER_KEY} (it carries the
57
- * full AppKit execution context with a `WorkspaceClient` reference).
58
- *
59
- * Order is purely cosmetic; Mastra de-dupes internally.
60
- */
61
- export const TRACE_REQUEST_CONTEXT_KEYS: readonly string[] = [
62
- MASTRA_RESOURCE_ID_KEY,
63
- MASTRA_THREAD_ID_KEY,
64
- MASTRA_REQUEST_ID_KEY,
65
- MASTRA_USER_NAME_KEY,
66
- MASTRA_USER_EMAIL_KEY,
67
- // Model override key is owned by `serving.ts`; spelled inline here
68
- // so this module stays leaf-level (no cycles with `serving.ts`).
69
- "mastra__model_override",
70
- ];
71
-
72
- /** AppKit execution context plus the canonical user id. */
73
- export interface User {
74
- id: string;
75
- executionContext: appkitUtils.ExecutionContextLike;
76
- }
77
-
78
- /** PgVector config with an optional Mastra store id. */
79
- export type MastraMemoryConfig = PgVectorConfig & {
80
- id?: string;
81
- };
82
-
83
- /**
84
- * Fine-grained control for the optional MCP server exposure
85
- * ({@link MastraPluginConfig.mcp}). Every field is optional; the object
86
- * form only needs to set what differs from the defaults.
87
- */
88
- export interface MastraMcpConfig {
89
- /**
90
- * Server id used in the route path (`/mcp/<serverId>/...`) and as the
91
- * MCP registry id. Defaults to the plugin's registered name.
92
- */
93
- serverId?: string;
94
- /** Display name advertised over MCP. Defaults to `"<displayName> MCP"`. */
95
- name?: string;
96
- /** Semantic version advertised over MCP. Defaults to `"1.0.0"`. */
97
- version?: string;
98
- /** Optional human-readable description advertised over MCP. */
99
- description?: string;
100
- /**
101
- * Expose every registered agent as an `ask_<agentId>` MCP tool.
102
- * Defaults to `true` - this is the "leverage the Mastra agents over
103
- * MCP" behavior most callers want.
104
- */
105
- agents?: boolean;
106
- /**
107
- * Also expose the plugin's ambient tools (the built-in `render_data`
108
- * plus anything in `config.tools`) as MCP tools. Defaults to `false`:
109
- * the ambient tools assume an in-process chat turn (they publish
110
- * writer events the chat UI consumes), so they aren't useful to a
111
- * standalone MCP client. Turn this on only when those tools are safe
112
- * to call out-of-band.
113
- */
114
- tools?: boolean;
115
- /**
116
- * Extra tools to expose over MCP beyond the agent / ambient sets.
117
- * Use this for tools written specifically for MCP consumers.
118
- */
119
- extraTools?: MastraTools;
120
- }
121
-
122
- /** Configuration accepted by the Mastra AppKit plugin. */
123
- export interface MastraPluginConfig extends BasePluginConfig {
124
- /** Mastra OpenAI-compatible provider id. Defaults to `"databricks"`. */
125
- providerId?: string;
126
- /**
127
- * PostgresStore for Mastra threads/messages. `true` reuses the
128
- * `lakebase` plugin's pool; an object opens a dedicated store.
129
- */
130
- storage?: boolean | PostgresStoreConfig;
131
- /**
132
- * PgVector store for Mastra memory recall. `true` reuses the
133
- * `lakebase` plugin's pool; an object opens a dedicated store.
134
- */
135
- memory?: boolean | MastraMemoryConfig;
136
- /**
137
- * Code-defined agents. Accepts three shapes for convenience:
138
- *
139
- * - **Record**: `{ analyst: def, helper: def }` - keys become the
140
- * registered ids and the first key is the default.
141
- * - **Single definition**: `def` - registered under
142
- * `slugify(def.name)` (or `"default"` when `name` is omitted) and
143
- * automatically marked as the default agent.
144
- * - **Array**: `[def1, def2]` - each registered under
145
- * `slugify(def.name)` (or `agent_${i}` when `name` is omitted);
146
- * the first entry is the default.
147
- *
148
- * Each entry becomes a Mastra `Agent` reachable at
149
- * `/api/<plugin>/route/chat/<id>` (the chat route also matches
150
- * `:agentId`). When `agents` is omitted entirely, the plugin
151
- * registers a single built-in `default` analyst so the bare
152
- * `mastra()` call still mounts a working chat endpoint.
153
- *
154
- * @example Single-agent shorthand
155
- * ```ts
156
- * mastra({
157
- * agents: createAgent({ instructions: "..." }),
158
- * });
159
- * ```
160
- *
161
- * @example Array
162
- * ```ts
163
- * mastra({
164
- * agents: [
165
- * createAgent({ name: "analyst", instructions: "..." }),
166
- * createAgent({ name: "helper", instructions: "..." }),
167
- * ],
168
- * });
169
- * ```
170
- *
171
- * @example Record (explicit ids)
172
- * ```ts
173
- * mastra({
174
- * agents: {
175
- * analyst: createAgent({ instructions: "..." }),
176
- * helper: createAgent({ instructions: "..." }),
177
- * },
178
- * defaultAgent: "analyst",
179
- * });
180
- * ```
181
- */
182
- agents?:
183
- | Record<string, MastraAgentDefinition>
184
- | MastraAgentDefinition
185
- | MastraAgentDefinition[];
186
- /**
187
- * Ambient tools spread into every registered agent's tools record;
188
- * per-agent tools win on key collision. Use for a small shared
189
- * library; for per-agent tools set `agents[id].tools` instead.
190
- */
191
- tools?: MastraTools;
192
- /**
193
- * Agent id used when the client doesn't specify one (the bare,
194
- * un-suffixed history / suggestions routes resolve to it).
195
- * Defaults to the first key in `agents` (or `"default"` when
196
- * `agents` is omitted). Must match an id in `agents` when both are
197
- * set; a mismatch throws at setup with the available candidates.
198
- */
199
- defaultAgent?: string;
200
- /**
201
- * Plugin-level default model applied to every agent that omits its
202
- * own `model`. Mirrors AppKit's `agents({ defaultModel })`.
203
- *
204
- * - `string`: shorthand for "use the OBO auto-resolver but swap the
205
- * `modelId`" (e.g. `"databricks-claude-sonnet-4-6"`).
206
- * - Any other Mastra `DynamicArgument<MastraModelConfig>`: passed
207
- * through verbatim. Use this when you need full control over auth
208
- * or `providerId`.
209
- *
210
- * Resolution order per agent: `def.model` → `defaultModel` →
211
- * built-in `/serving-endpoints` resolver.
212
- */
213
- defaultModel?: AgentConfig["model"] | string;
214
- /**
215
- * Allow loose model names (`"claude sonnet"`) to be fuzzy-matched
216
- * against the workspace's Model Serving endpoints. Defaults to
217
- * `true`; set `false` to require exact endpoint names everywhere.
218
- */
219
- modelFuzzyMatch?: boolean;
220
- /**
221
- * Fuse.js score threshold for the fuzzy matcher (0 = exact match,
222
- * 1 = anything matches). Defaults to `0.4`. Lower values reject
223
- * loose matches; raise it if you have a sprawling endpoint
224
- * catalogue with similar-looking names.
225
- */
226
- modelFuzzyThreshold?: number;
227
- /**
228
- * TTL for the in-memory serving-endpoints list cache, in
229
- * milliseconds. Defaults to 5 minutes. The cache is per workspace
230
- * host and shared across users; concurrent callers coalesce on a
231
- * single in-flight fetch.
232
- */
233
- modelCacheTtlMs?: number;
234
- /**
235
- * Allow clients to override the active model per request via the
236
- * `X-Mastra-Model` header, `?model=` query string, or `model` body
237
- * field. Defaults to `true`. Disable when running multi-tenant
238
- * where untrusted clients shouldn't pick the backing endpoint.
239
- */
240
- modelOverride?: boolean;
241
- /**
242
- * Priority-ordered list of endpoint names tried *first* when no
243
- * agent / plugin / env / request-override model id is set, ahead of
244
- * the dynamic score-classified catalogue. The resolver picks the
245
- * first id that is actually present in the workspace's
246
- * `/serving-endpoints` listing.
247
- *
248
- * When unset, resolution is driven by the live Foundation Model API
249
- * `quality` / `speed` / `cost` scores: endpoints are classified into
250
- * chat classes (`classifyEndpoints`) and walked best-first
251
- * (ChatThinking -> ChatBalanced -> ChatFast), with the small built-in
252
- * `FALLBACK_MODEL_IDS` list as the floor when the catalogue can't be
253
- * read. Set this to
254
- * pin a regulated workspace to an approved subset, or to put custom
255
- * endpoints in front of the auto-classified catalogue.
256
- */
257
- defaultModelFallbacks?: readonly string[];
258
- /**
259
- * When `true` (default), every agent gets a built-in input
260
- * processor that strips `chartId` fields from prior assistant
261
- * tool-invocation results before they reach the model. This
262
- * prevents the model from reusing turn-scoped chartIds it sees
263
- * in memory recall (which would leave `[chart:<id>]` markers
264
- * pointing at writer events that no longer exist).
265
- *
266
- * Set to `false` to opt out - useful if a non-default agent
267
- * needs full visibility into prior chartIds (e.g. an audit
268
- * agent reasoning about chart lineage).
269
- */
270
- stripStaleCharts?: boolean;
271
- /**
272
- * Style guardrails appended to every agent's `instructions` to curb
273
- * common LLM-isms (em dashes, emojis, sycophantic openers, throwaway
274
- * closers, excessive hedging).
275
- *
276
- * - `undefined` (default): use the built-in
277
- * `DEFAULT_STYLE_INSTRUCTIONS` from `agents.ts`.
278
- * - `string`: replace the default with the supplied block.
279
- * - `false`: disable entirely (agents see only their bespoke
280
- * `instructions`).
281
- *
282
- * Appended (not prepended) so the agent's role and rules come first
283
- * and the style block leans on the model's recency bias.
284
- */
285
- styleInstructions?: string | false;
286
- /**
287
- * Genie spaces this plugin's agents can delegate to. One Mastra
288
- * tool is registered per alias (`genie` for the well-known
289
- * `default` alias, `genie_<alias>` otherwise). Each tool spins
290
- * up a per-question Genie sub-agent that runs Databricks
291
- * "agent mode" against the space, broadcasts wire events to the
292
- * UI, fetches statement rows for non-empty results, and returns
293
- * a `(string | data | chart)[]` summary the host UI renders
294
- * inline.
295
- *
296
- * Entries accept either a full {@link GenieSpaceConfig} object
297
- * or a bare `space_id` string when no extras are needed:
298
- *
299
- * ```ts
300
- * mastra({
301
- * genieSpaces: {
302
- * default: "01ef0d3c0e1b1f4a8d2c3e4f5a6b7c8d",
303
- * forecasts: { spaceId: "01ef...", hint: "weekly demand forecasts" },
304
- * },
305
- * });
306
- * ```
307
- *
308
- * Reach the spaces from an agent's `tools(plugins)` callback via
309
- * `plugins.genie?.toolkit()`; the resulting tools accept
310
- * `{ content, conversationId? }` and return a hydrated summary.
311
- *
312
- * **Fallback discovery** (highest precedence first): if this
313
- * field is omitted, the Genie agent also picks up spaces from
314
- * (1) the AppKit `genie({ spaces: { ... } })` plugin instance
315
- * when registered, and (2) the `DATABRICKS_GENIE_SPACE_ID`
316
- * env var (registered under the `default` alias). This keeps
317
- * existing AppKit deployments working without restating the
318
- * spaces config in two places.
319
- */
320
- genieSpaces?: GenieSpacesConfig;
321
- /**
322
- * TTL for the in-memory Genie space metadata cache, in
323
- * milliseconds. Defaults to 5 minutes. The Genie agent calls
324
- * `client.genie.getSpace(...)` on every cold-start to get the
325
- * title / description / warehouse id; cached responses skip the
326
- * round-trip and concurrent callers coalesce on a single
327
- * in-flight fetch. Drop to a smaller value when analysts are
328
- * actively editing space metadata and you want changes visible
329
- * within seconds; raise it to amortise the round-trip when
330
- * space metadata is effectively frozen.
331
- *
332
- * Backed by AppKit's `CacheManager`, so the cache participates
333
- * in telemetry spans (`cache.getOrExecute`) and benefits from
334
- * Lakebase persistence when the `lakebase` plugin is wired up.
335
- */
336
- genieSpaceCacheTtlMs?: number;
337
- /**
338
- * Maximum LLM steps each agent gets per turn. One step = one
339
- * round-trip to the underlying model (a tool call consumes a
340
- * step, the final-text reply consumes one too). Applies to
341
- * every agent registered through {@link MastraPluginConfig.agents}
342
- * - per-agent overrides aren't surfaced yet because the same
343
- * ceiling has been sufficient across every workload we've run.
344
- *
345
- * Defaults to {@link DEFAULT_AGENT_MAX_STEPS} (25), sized to fit
346
- * a decomposed Genie turn (grounding + several `ask_genie` calls
347
- * + `prepare_chart` per dataset + the final-text reply) with
348
- * headroom for the model to chain a couple of follow-ups before
349
- * answering. Mastra's own `agent.generate` default of 5 would
350
- * cut multi-step orchestration off after 2-3 tool calls, so
351
- * explicitly raising the ceiling here is what lets the
352
- * agent-mode loop play out.
353
- *
354
- * Lower when an unusually slow or expensive model makes long
355
- * turns unaffordable; raise for exploratory workloads that need
356
- * to drill deep into a dataset within a single turn.
357
- */
358
- agentMaxSteps?: number;
359
- /**
360
- * Expose the plugin's agents (and optionally tools) as a Mastra MCP
361
- * server so external MCP clients - Claude Desktop, Cursor, the Mastra
362
- * playground, or another agent - can call them over the standard MCP
363
- * transports. Disabled by default.
364
- *
365
- * - `undefined` / `false`: no MCP endpoints.
366
- * - `true`: expose every registered agent as an `ask_<agentId>` MCP
367
- * tool under a server whose id is the plugin name.
368
- * - {@link MastraMcpConfig}: fine-grained control over the server id,
369
- * advertised metadata, and which agents / tools are exposed.
370
- *
371
- * When enabled, the stock Mastra MCP routes mount under the plugin's
372
- * base path (no bespoke route is added - the server is handed to the
373
- * `Mastra` instance via `mcpServers`, which `@mastra/express` serves):
374
- *
375
- * - Streamable HTTP: `POST /api/<plugin>/mcp/<serverId>/mcp`
376
- * - SSE (legacy): `GET /api/<plugin>/mcp/<serverId>/sse`
377
- * `POST /api/<plugin>/mcp/<serverId>/messages`
378
- *
379
- * Requests run under the same AppKit OBO scope as the chat routes, so
380
- * an agent invoked over MCP resolves its model and tools as the
381
- * calling user.
382
- */
383
- mcp?: boolean | MastraMcpConfig;
384
- }