@dbx-tools/ui-mastra 0.9.189 → 0.9.193

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.
@@ -0,0 +1,257 @@
1
+ import { Tooltip, TooltipContent, TooltipTrigger, cn } from "@databricks/appkit-ui/react";
2
+ import {
3
+ MODEL_ROUTE_PART_TYPE,
4
+ MODEL_USAGE_PART_TYPE,
5
+ ModelRoutePartDataSchema,
6
+ ModelUsagePartDataSchema,
7
+ type ModelRoutePartData,
8
+ type ModelUsagePartData,
9
+ } from "@dbx-tools/shared-mastra";
10
+ import { toModelDisplayName } from "@dbx-tools/shared-model";
11
+ import type { UIMessage } from "ai";
12
+ import { RouteIcon } from "lucide-react";
13
+ import { type ReactNode, useEffect, useState } from "react";
14
+
15
+ import type { ChatMetric, ChatMetrics } from "./types.ts";
16
+ import { readBrowserMessageTimestamps } from "../support/browser-transcript.ts";
17
+
18
+ const ALL_METRICS = ["tokens", "time", "dbu", "usd"] as const satisfies readonly ChatMetric[];
19
+
20
+ /** Model route and latest cumulative usage stored on one assistant turn. */
21
+ export interface SelectedModelActivity {
22
+ route: ModelRoutePartData;
23
+ usage?: ModelUsagePartData;
24
+ }
25
+
26
+ /** Minimal assistant message shape needed for route and metric rendering. */
27
+ export interface SelectedModelMessage {
28
+ metadata?: unknown;
29
+ parts: readonly { type: string; data?: unknown }[];
30
+ }
31
+
32
+ /** Read the model route and latest usage stored on one assistant turn. */
33
+ export function selectedModelActivity(
34
+ message: SelectedModelMessage,
35
+ ): SelectedModelActivity | undefined {
36
+ let route: ModelRoutePartData | undefined;
37
+ let usage: ModelUsagePartData | undefined;
38
+ for (const part of message.parts) {
39
+ if (part.type === MODEL_ROUTE_PART_TYPE) {
40
+ const parsed = ModelRoutePartDataSchema.safeParse((part as { data?: unknown }).data);
41
+ if (parsed.success) route ??= parsed.data;
42
+ }
43
+ if (part.type === MODEL_USAGE_PART_TYPE) {
44
+ const parsed = ModelUsagePartDataSchema.safeParse((part as { data?: unknown }).data);
45
+ if (parsed.success) {
46
+ route ??= parsed.data;
47
+ usage = parsed.data;
48
+ }
49
+ }
50
+ }
51
+ return route ? { route, ...(usage ? { usage } : {}) } : undefined;
52
+ }
53
+
54
+ /** Read the earliest available model route stored on one assistant turn. */
55
+ export const selectedModelRoute = (message: SelectedModelMessage): ModelRoutePartData | undefined =>
56
+ selectedModelActivity(message)?.route;
57
+
58
+ /** Normalize the public one-or-many metric option while preserving caller order. */
59
+ export function normalizeChatMetrics(metrics: ChatMetrics | undefined): ChatMetric[] {
60
+ if (metrics === undefined) return [];
61
+ return [...new Set(Array.isArray(metrics) ? metrics : [metrics])];
62
+ }
63
+
64
+ type MetricValues = Record<ChatMetric, string>;
65
+
66
+ /** Numeric per-turn metrics derived from persisted route, usage, and timestamps. */
67
+ export interface SelectedModelTurnMetrics {
68
+ tokens?: number;
69
+ timeMs?: number;
70
+ dbu?: number;
71
+ usd?: number;
72
+ }
73
+
74
+ function averageUsdPerDbu(route: ModelRoutePartData): number | undefined {
75
+ const values = Object.values(route.pricing?.usdPerDbu ?? {});
76
+ if (values.length === 0) return undefined;
77
+ return values.reduce((sum, value) => sum + value, 0) / values.length;
78
+ }
79
+
80
+ function elapsedMs(
81
+ message: Pick<UIMessage, "metadata">,
82
+ active: boolean,
83
+ now: number,
84
+ fallbackStartedAt: number,
85
+ ): number | undefined {
86
+ const timestamps = readBrowserMessageTimestamps(message);
87
+ if (!timestamps) return active ? Math.max(0, now - fallbackStartedAt) : undefined;
88
+ const startedAt = Date.parse(timestamps.createdAt);
89
+ const completedAt = timestamps.completedAt
90
+ ? Date.parse(timestamps.completedAt)
91
+ : active
92
+ ? now
93
+ : NaN;
94
+ if (!Number.isFinite(startedAt) || !Number.isFinite(completedAt)) return undefined;
95
+ return Math.max(0, completedAt - startedAt);
96
+ }
97
+
98
+ function formatDuration(value: number | undefined): string {
99
+ if (value === undefined) return "—";
100
+ return value < 1_000 ? `${Math.round(value)}ms` : `${(value / 1_000).toFixed(1)}s`;
101
+ }
102
+
103
+ function formatTokens(value: number | undefined): string {
104
+ if (value === undefined) return "—";
105
+ if (value < 1_000) return value.toLocaleString();
106
+ return `${(value / 1_000).toFixed(value < 10_000 ? 1 : 0)}k`;
107
+ }
108
+
109
+ function formatDbu(value: number | undefined): string {
110
+ if (value === undefined) return "—";
111
+ return `${value < 0.001 ? value.toFixed(6) : value.toFixed(4)} DBU`;
112
+ }
113
+
114
+ function formatUsd(value: number | undefined): string {
115
+ if (value === undefined) return "—";
116
+ return `$${value < 0.01 ? value.toFixed(6) : value.toFixed(4)}`;
117
+ }
118
+
119
+ function activityTurnMetrics(
120
+ activity: SelectedModelActivity,
121
+ message: Pick<UIMessage, "metadata">,
122
+ active: boolean,
123
+ now: number,
124
+ fallbackStartedAt: number,
125
+ ): SelectedModelTurnMetrics {
126
+ const dbu = activity.usage?.estimatedCostDbu;
127
+ const usdPerDbu = averageUsdPerDbu(activity.route);
128
+ const timeMs = elapsedMs(message, active, now, fallbackStartedAt);
129
+ return {
130
+ ...(activity.usage ? { tokens: activity.usage.usage.totalTokens } : {}),
131
+ ...(timeMs !== undefined ? { timeMs } : {}),
132
+ ...(dbu !== undefined ? { dbu } : {}),
133
+ ...(dbu !== undefined && usdPerDbu !== undefined ? { usd: dbu * usdPerDbu } : {}),
134
+ };
135
+ }
136
+
137
+ /** Read completed per-turn metrics from one assistant message. */
138
+ export function selectedModelTurnMetrics(
139
+ message: SelectedModelMessage,
140
+ ): SelectedModelTurnMetrics | undefined {
141
+ const activity = selectedModelActivity(message);
142
+ if (!activity) return undefined;
143
+ return activityTurnMetrics(activity, message, false, 0, 0);
144
+ }
145
+
146
+ function metricValues(
147
+ activity: SelectedModelActivity,
148
+ message: Pick<UIMessage, "metadata">,
149
+ active: boolean,
150
+ now: number,
151
+ fallbackStartedAt: number,
152
+ ): MetricValues {
153
+ const values = activityTurnMetrics(activity, message, active, now, fallbackStartedAt);
154
+ return {
155
+ tokens: formatTokens(values.tokens),
156
+ time: formatDuration(values.timeMs),
157
+ dbu: formatDbu(values.dbu),
158
+ usd: formatUsd(values.usd),
159
+ };
160
+ }
161
+
162
+ const metricLabel = (metric: ChatMetric): string =>
163
+ ({ tokens: "Tokens", time: "Time", dbu: "DBU", usd: "USD" })[metric];
164
+
165
+ const MetricsTooltip = ({ values }: { values: MetricValues }) => (
166
+ <TooltipContent>
167
+ <dl className="grid grid-cols-[auto_auto] gap-x-4 gap-y-1 text-xs">
168
+ {ALL_METRICS.map((metric) => (
169
+ <div key={metric} className="contents">
170
+ <dt className="text-muted-foreground">{metricLabel(metric)}</dt>
171
+ <dd className="text-right font-mono tabular-nums">{values[metric]}</dd>
172
+ </div>
173
+ ))}
174
+ </dl>
175
+ </TooltipContent>
176
+ );
177
+
178
+ /** Compact per-turn row for the model selected before generation begins. */
179
+ export const SelectedModelPill = ({
180
+ activity,
181
+ message,
182
+ showModel = true,
183
+ metrics,
184
+ active = false,
185
+ children,
186
+ }: {
187
+ activity: SelectedModelActivity;
188
+ message: Pick<UIMessage, "metadata">;
189
+ showModel?: boolean;
190
+ metrics?: ChatMetrics;
191
+ active?: boolean;
192
+ children?: ReactNode;
193
+ }) => {
194
+ const selectedMetrics = normalizeChatMetrics(metrics);
195
+ const [fallbackStartedAt] = useState(() => Date.now());
196
+ const [now, setNow] = useState(() => Date.now());
197
+ const updateTime = active && selectedMetrics.includes("time");
198
+ useEffect(() => {
199
+ if (!updateTime) return;
200
+ setNow(Date.now());
201
+ const interval = window.setInterval(() => setNow(Date.now()), 100);
202
+ return () => window.clearInterval(interval);
203
+ }, [updateTime]);
204
+ if (!showModel && selectedMetrics.length === 0) return null;
205
+
206
+ const route = activity.route;
207
+ const values = metricValues(activity, message, active, now, fallbackStartedAt);
208
+ const friendlyName = toModelDisplayName(route.model);
209
+ return (
210
+ <div
211
+ data-slot="selected-model-pill"
212
+ className="flex min-h-7 min-w-0 max-w-full flex-1 items-center gap-1 overflow-hidden text-xs text-muted-foreground"
213
+ >
214
+ {showModel ? (
215
+ <Tooltip>
216
+ <TooltipTrigger asChild>
217
+ <span
218
+ tabIndex={0}
219
+ className="mr-1 flex min-w-0 items-center gap-1.5 truncate rounded-sm px-1 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
220
+ aria-label={`${friendlyName}: ${route.model}`}
221
+ >
222
+ <RouteIcon className="size-3 shrink-0" aria-hidden />
223
+ <span className="truncate">{friendlyName}</span>
224
+ </span>
225
+ </TooltipTrigger>
226
+ <TooltipContent>
227
+ <span className="font-mono text-xs">{route.model}</span>
228
+ </TooltipContent>
229
+ </Tooltip>
230
+ ) : null}
231
+ {children}
232
+ {selectedMetrics.length > 0 ? (
233
+ <Tooltip>
234
+ <TooltipTrigger asChild>
235
+ <span
236
+ tabIndex={0}
237
+ className={cn(
238
+ "ml-auto flex min-w-0 shrink-0 items-center justify-end gap-2 rounded-sm px-1 font-mono text-[10px] tabular-nums focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
239
+ !showModel && "w-full",
240
+ )}
241
+ aria-label={ALL_METRICS.map(
242
+ (metric) => `${metricLabel(metric)} ${values[metric]}`,
243
+ ).join(", ")}
244
+ >
245
+ {selectedMetrics.map((metric) => (
246
+ <span key={metric} className="whitespace-nowrap">
247
+ {values[metric]}
248
+ </span>
249
+ ))}
250
+ </span>
251
+ </TooltipTrigger>
252
+ <MetricsTooltip values={values} />
253
+ </Tooltip>
254
+ ) : null}
255
+ </div>
256
+ );
257
+ };
@@ -34,6 +34,7 @@ export const SuggestionPills = ({
34
34
  if (questions.length === 0) return null;
35
35
  return (
36
36
  <div
37
+ data-slot="aui_suggestion-pills"
37
38
  aria-label="Suggested questions"
38
39
  className={cn(
39
40
  "flex gap-1.5",
@@ -185,7 +185,10 @@ export const ThreadTabs = ({
185
185
  return (
186
186
  // The divider spans the whole chat width while the strip's contents stay
187
187
  // in the same centered column as the transcript and composer.
188
- <div className={cn("w-full border-b border-border text-xs", className)}>
188
+ <div
189
+ data-slot="aui_thread-tabs"
190
+ className={cn("w-full border-b border-border text-xs", className)}
191
+ >
189
192
  <div className="mx-auto flex w-full max-w-4xl items-center gap-1 px-2 py-1 md:px-4">
190
193
  <div ref={tabStripRef} className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto">
191
194
  {openThreadIds.map((id) => {
@@ -16,6 +16,12 @@ import type { ExportFormat } from "../support/export.ts";
16
16
  /** User-visible lifecycle state of the active chat turn. */
17
17
  export type ChatStatus = "submitted" | "streaming" | "finishing" | "ready" | "error";
18
18
 
19
+ /** Per-turn metric available in the compact assistant activity row. */
20
+ export type ChatMetric = "tokens" | "time" | "dbu" | "usd";
21
+
22
+ /** One or more per-turn metrics shown beside the selected model. */
23
+ export type ChatMetrics = ChatMetric | readonly ChatMetric[];
24
+
19
25
  /** Whether a turn still owns its session and queues new messages. */
20
26
  export const isActiveChatStatus = (status: ChatStatus): boolean =>
21
27
  status === "submitted" || status === "streaming" || status === "finishing";
@@ -58,7 +64,7 @@ export type ToolProgress = ToolProgressEvent;
58
64
  */
59
65
  export type ChatModelOption = Pick<
60
66
  ServingEndpointSummary,
61
- "name" | "displayName" | "family" | "reasoningEfforts"
67
+ "name" | "displayName" | "family" | "profile" | "reasoningEfforts"
62
68
  >;
63
69
 
64
70
  /**
@@ -174,6 +180,8 @@ export type ChatViewProps = {
174
180
  onStop?: (threadId?: string) => void;
175
181
  /** Extra classes merged onto the root layout container. */
176
182
  className?: string;
183
+ /** Render the built-in composer. Defaults to true for standalone chat surfaces. */
184
+ showComposer?: boolean;
177
185
  /**
178
186
  * Starter questions shown as one-tap buttons on the empty state.
179
187
  * Defaults to none - nothing renders when omitted or empty, so the
@@ -186,6 +194,18 @@ export type ChatViewProps = {
186
194
  followUpSuggestions?: FollowUpSuggestionMode;
187
195
  /** Maximum post-turn follow-up questions shown under one response. */
188
196
  followUpSuggestionLimit?: number;
197
+ /**
198
+ * Show the friendly name of the model selected for each assistant turn. Off by default.
199
+ * The compact assistant footer appears as soon as the streamed model-route part
200
+ * arrives; the concrete endpoint id is available on hover or keyboard focus.
201
+ */
202
+ showSelectedModel?: boolean;
203
+ /**
204
+ * Per-turn metrics shown at the right edge of the assistant footer.
205
+ * Pass one metric or an array containing `tokens`, `time`, `dbu`, and/or
206
+ * `usd`. Omit to hide metrics. Hovering or focusing the group shows all four.
207
+ */
208
+ metrics?: ChatMetrics;
189
209
  toolEventsByMessage?: Record<string, ToolEvent[]>;
190
210
  /** Available model endpoints. Pass an empty array (or omit) to hide the picker. */
191
211
  models?: ChatModelOption[];
@@ -0,0 +1,132 @@
1
+ import type { UIMessage } from "ai";
2
+ import { z } from "zod";
3
+
4
+ const DEFAULT_MAX_MESSAGES = 100;
5
+
6
+ /** Client-observed lifecycle timestamps stored with one browser-held message. */
7
+ export const BrowserMessageTimestampsSchema = z
8
+ .object({
9
+ createdAt: z.iso.datetime().describe("ISO-8601 time when the message turn started."),
10
+ completedAt: z.iso
11
+ .datetime()
12
+ .optional()
13
+ .describe("ISO-8601 time when the assistant response completed."),
14
+ })
15
+ .passthrough()
16
+ .describe("Browser-persisted message lifecycle timestamps.");
17
+
18
+ /** Client-observed lifecycle timestamps stored with one browser-held message. */
19
+ export type BrowserMessageTimestamps = z.infer<typeof BrowserMessageTimestampsSchema>;
20
+
21
+ const StoredBrowserMessageSchema = z
22
+ .object({
23
+ id: z.string().min(1).describe("AI SDK UI message identifier."),
24
+ role: z.enum(["system", "user", "assistant"]).describe("AI SDK UI message author role."),
25
+ metadata: z
26
+ .unknown()
27
+ .optional()
28
+ .describe("Message lifecycle timestamps plus any transport-owned metadata."),
29
+ parts: z.array(z.unknown()).describe("AI SDK UI message content parts."),
30
+ })
31
+ .passthrough()
32
+ .describe("Browser-persisted AI SDK UI message.");
33
+
34
+ const StoredBrowserTranscriptSchema = z
35
+ .object({
36
+ version: z
37
+ .union([z.literal(1), z.literal(2)])
38
+ .describe("Browser transcript storage format version."),
39
+ messages: z
40
+ .array(StoredBrowserMessageSchema)
41
+ .describe("Chronological AI SDK UI messages for one thread."),
42
+ })
43
+ .strict()
44
+ .describe("Browser-persisted Mastra conversation transcript.");
45
+
46
+ type StorageLike = Pick<Storage, "getItem" | "setItem" | "removeItem">;
47
+
48
+ function browserStorage(): StorageLike | undefined {
49
+ try {
50
+ return typeof window === "undefined" ? undefined : window.localStorage;
51
+ } catch {
52
+ return undefined;
53
+ }
54
+ }
55
+
56
+ /** Build the browser storage key for one resource-scoped Mastra thread. */
57
+ export function browserTranscriptStorageKey(
58
+ basePath: string,
59
+ agentId: string,
60
+ threadId: string,
61
+ resourceScope?: string,
62
+ ): string {
63
+ const prefix = `dbx-mastra-transcript:${basePath}:${agentId}:${encodeURIComponent(threadId)}`;
64
+ return resourceScope ? `${prefix}:${encodeURIComponent(resourceScope)}` : prefix;
65
+ }
66
+
67
+ /** Restore a browser transcript, removing malformed data without failing the chat. */
68
+ export function readStoredBrowserTranscript(
69
+ key: string,
70
+ storage: StorageLike | undefined = browserStorage(),
71
+ ): UIMessage[] {
72
+ if (!storage) return [];
73
+ try {
74
+ const serialized = storage.getItem(key);
75
+ if (!serialized) return [];
76
+ const parsed = StoredBrowserTranscriptSchema.parse(JSON.parse(serialized));
77
+ return parsed.messages as UIMessage[];
78
+ } catch {
79
+ try {
80
+ storage.removeItem(key);
81
+ } catch {}
82
+ return [];
83
+ }
84
+ }
85
+
86
+ /** Read validated lifecycle timestamps from one UI message. */
87
+ export function readBrowserMessageTimestamps(
88
+ message: Pick<UIMessage, "metadata">,
89
+ ): BrowserMessageTimestamps | undefined {
90
+ const parsed = BrowserMessageTimestampsSchema.safeParse(message.metadata);
91
+ return parsed.success ? parsed.data : undefined;
92
+ }
93
+
94
+ /** Add lifecycle timestamps without discarding transport-owned message metadata. */
95
+ export function withBrowserMessageTimestamps(
96
+ message: UIMessage,
97
+ timestamps: BrowserMessageTimestamps,
98
+ ): UIMessage {
99
+ const existing =
100
+ message.metadata && typeof message.metadata === "object" && !Array.isArray(message.metadata)
101
+ ? message.metadata
102
+ : {};
103
+ const current = readBrowserMessageTimestamps(message);
104
+ const next = BrowserMessageTimestampsSchema.parse({
105
+ ...existing,
106
+ ...timestamps,
107
+ createdAt: current?.createdAt ?? timestamps.createdAt,
108
+ });
109
+ return { ...message, metadata: next };
110
+ }
111
+
112
+ /** Persist the newest browser-held messages for one thread on a best-effort basis. */
113
+ export function storeBrowserTranscript(
114
+ key: string,
115
+ messages: readonly UIMessage[],
116
+ maxMessages = DEFAULT_MAX_MESSAGES,
117
+ storage: StorageLike | undefined = browserStorage(),
118
+ ): void {
119
+ if (!storage) return;
120
+ try {
121
+ if (messages.length === 0) {
122
+ storage.removeItem(key);
123
+ return;
124
+ }
125
+ const limit = Number.isFinite(maxMessages)
126
+ ? Math.max(1, Math.floor(maxMessages))
127
+ : DEFAULT_MAX_MESSAGES;
128
+ storage.setItem(key, JSON.stringify({ version: 2, messages: messages.slice(-limit) }));
129
+ } catch {
130
+ // Storage can be blocked or full; the live in-memory transcript remains valid.
131
+ }
132
+ }
@@ -7,6 +7,7 @@ import {
7
7
  type MastraFeedbackRequest,
8
8
  type MastraFeedbackResponse,
9
9
  type MastraMlflowExperimentResponse,
10
+ type MastraSuggestionGenerationRequest,
10
11
  type StatementData,
11
12
  type FeedbackDestination,
12
13
  MastraFeedbackResponseSchema,
@@ -18,12 +19,14 @@ import {
18
19
  ServingEndpointsResponseSchema,
19
20
  DefaultModelResponseSchema,
20
21
  MastraSuggestionsResponseSchema,
22
+ MastraSuggestionGenerationRequestSchema,
21
23
  ChartSchema,
22
24
  StatementDataSchema,
23
25
  type GenieVisualizationEmbed,
24
26
  genieVisualizationImagePath,
25
27
  } from "@dbx-tools/shared-mastra";
26
- import type { ReasoningEffort, ServingEndpointSummary } from "@dbx-tools/shared-model";
28
+ import type { ModelSource, ReasoningEffort, ServingEndpointSummary } from "@dbx-tools/shared-model";
29
+ import { AI_DECIDE_STRATEGY_HEADER, type AiDecideStrategy } from "@dbx-tools/shared-model-gateway";
27
30
  import {
28
31
  MastraClient,
29
32
  type ListAgentSuspendedRunsResponse,
@@ -138,10 +141,17 @@ export class MastraPluginClient extends MastraClient {
138
141
  * cookie thread); `model` is a concrete endpoint name (fuzzy-matched
139
142
  * server-side) or a model-class slug (`"chat-fast"` / `"chat-thinking"`).
140
143
  */
141
- #routingHeaders(routing: { threadId?: string; model?: string }): Record<string, string> {
144
+ #routingHeaders(routing: {
145
+ threadId?: string;
146
+ model?: string;
147
+ aiDecideStrategy?: AiDecideStrategy;
148
+ }): Record<string, string> {
142
149
  const headers: Record<string, string> = {};
143
150
  if (routing.threadId) headers[THREAD_ID_HEADER] = routing.threadId;
144
151
  if (routing.model) headers[MODEL_OVERRIDE_HEADER] = routing.model;
152
+ if (routing.aiDecideStrategy) {
153
+ headers[AI_DECIDE_STRATEGY_HEADER] = routing.aiDecideStrategy;
154
+ }
145
155
  return headers;
146
156
  }
147
157
 
@@ -150,7 +160,7 @@ export class MastraPluginClient extends MastraClient {
150
160
  chatId: string;
151
161
  messages: UIMessage[];
152
162
  body?: object;
153
- routing: { threadId?: string; model?: string };
163
+ routing: { threadId?: string; model?: string; aiDecideStrategy?: AiDecideStrategy };
154
164
  signal?: AbortSignal;
155
165
  }): Promise<MastraStreamResponse> {
156
166
  let headers = new Headers();
@@ -236,6 +246,7 @@ export class MastraPluginClient extends MastraClient {
236
246
  runId: string;
237
247
  threadId?: string;
238
248
  model?: string;
249
+ aiDecideStrategy?: AiDecideStrategy;
239
250
  reasoningEffort?: ReasoningEffort;
240
251
  requestContext?: RequestContext;
241
252
  signal?: AbortSignal;
@@ -365,15 +376,34 @@ export class MastraPluginClient extends MastraClient {
365
376
  * publishes (server-cached for ~5 minutes); callers filter to
366
377
  * chat-capable models for a picker.
367
378
  */
368
- async models(signal?: AbortSignal): Promise<ServingEndpointSummary[]> {
379
+ async models(
380
+ signal?: AbortSignal,
381
+ modelSource: ModelSource | "all" = "foundation",
382
+ ): Promise<ServingEndpointSummary[]> {
383
+ const query = new URLSearchParams({ modelSource });
369
384
  const payload = await this.getJson(
370
- `${this.basePath}${MASTRA_ROUTES.models}`,
385
+ `${this.basePath}${MASTRA_ROUTES.models}?${query.toString()}`,
371
386
  ServingEndpointsResponseSchema,
372
387
  signal,
373
388
  );
374
389
  return payload.endpoints;
375
390
  }
376
391
 
392
+ /** Resolve the highest-ranked live endpoint matching a model family or search term. */
393
+ async resolveModel(
394
+ search: string,
395
+ signal?: AbortSignal,
396
+ modelSource: ModelSource | "all" = "foundation",
397
+ ): Promise<ServingEndpointSummary | undefined> {
398
+ const query = new URLSearchParams({ search, limit: "1", modelSource });
399
+ const payload = await this.getJson(
400
+ `${this.basePath}${MASTRA_ROUTES.models}?${query.toString()}`,
401
+ ServingEndpointsResponseSchema,
402
+ signal,
403
+ );
404
+ return payload.endpoints[0];
405
+ }
406
+
377
407
  /**
378
408
  * Fetch the humanized name of the static default model `agentId` falls back
379
409
  * to when no model is pinned, from `GET ${basePath}/default-model`. Returns
@@ -412,6 +442,21 @@ export class MastraPluginClient extends MastraClient {
412
442
  return payload.questions;
413
443
  }
414
444
 
445
+ /** Generate context-aware next questions through the plugin's shared suggestion service. */
446
+ async generateSuggestions(
447
+ request: MastraSuggestionGenerationRequest,
448
+ signal?: AbortSignal,
449
+ ): Promise<string[]> {
450
+ const body = MastraSuggestionGenerationRequestSchema.parse(request);
451
+ const payload = await this.#mutateJson(
452
+ `${this.basePath}${MASTRA_ROUTES.suggestionGeneration}`,
453
+ "POST",
454
+ MastraSuggestionsResponseSchema,
455
+ { body, ...(signal ? { signal } : {}) },
456
+ );
457
+ return payload.questions;
458
+ }
459
+
415
460
  /** Fetch one page from Mastra's native resource-scoped memory route. */
416
461
  async history(options: {
417
462
  agentId?: string;
@@ -19,6 +19,9 @@ export type SessionRun = {
19
19
  requestContext?: RequestContext;
20
20
  };
21
21
 
22
+ /** Source of prior messages supplied to Mastra for a new turn. */
23
+ export type ConversationHistorySource = "memory" | "browser";
24
+
22
25
  /** Session-scoped transcript + stream state for one conversation thread. */
23
26
  export type ThreadSession = {
24
27
  messages: UIMessage[];
@@ -90,6 +93,24 @@ export function interruptedTurnMessages(
90
93
  return [interrupted, nextMessage];
91
94
  }
92
95
 
96
+ /**
97
+ * Build the message payload Mastra recommends for the configured history source.
98
+ * Stored memory remains authoritative when enabled; otherwise the browser sends
99
+ * its full visible transcript and omits an interrupted partial assistant reply.
100
+ */
101
+ export function conversationRequestMessages(
102
+ source: ConversationHistorySource,
103
+ messages: readonly UIMessage[],
104
+ latest: UIMessage,
105
+ activeAssistantId?: string | null,
106
+ ): UIMessage | UIMessage[] {
107
+ if (source === "memory") return latest;
108
+ const retained = activeAssistantId
109
+ ? messages.filter((message) => message.id !== activeAssistantId)
110
+ : [...messages];
111
+ return retained.some((message) => message.id === latest.id) ? retained : [...retained, latest];
112
+ }
113
+
93
114
  /** Append a steer to the queue (oldest first). Returns a new array. */
94
115
  export function enqueueSteer<T extends QueuedSteer>(queue: T[], steer: T): T[] {
95
116
  return [...queue, steer];