@mastra/react 1.15.0-alpha.9 → 1.15.1-alpha.0

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 (36) hide show
  1. package/dist/{experiments-B2PEqGwi.js → experiments-BUTZk3Fu.js} +2 -2
  2. package/dist/{experiments-B2PEqGwi.js.map → experiments-BUTZk3Fu.js.map} +1 -1
  3. package/dist/{experiments-beUCWMr-.cjs → experiments-CDqRm-1r.cjs} +2 -2
  4. package/dist/{experiments-beUCWMr-.cjs.map → experiments-CDqRm-1r.cjs.map} +1 -1
  5. package/dist/hooks/auth/index.cjs +2 -0
  6. package/dist/hooks/auth/index.cjs.map +1 -1
  7. package/dist/hooks/auth/index.js +3 -1
  8. package/dist/hooks/auth/index.js.map +1 -1
  9. package/dist/hooks/auth/use-auth-capabilities.d.ts.map +1 -1
  10. package/dist/hooks/auth/use-permission-patterns.d.ts.map +1 -1
  11. package/dist/hooks/datasets/index.cjs +1 -1
  12. package/dist/hooks/datasets/index.js +1 -1
  13. package/dist/hooks/experiments/index.cjs +1 -1
  14. package/dist/hooks/experiments/index.js +1 -1
  15. package/dist/hooks/logs/index.cjs +1 -1
  16. package/dist/hooks/logs/index.js +1 -1
  17. package/dist/hooks/review/index.cjs +115 -1
  18. package/dist/hooks/review/index.cjs.map +1 -1
  19. package/dist/hooks/review/index.js +115 -3
  20. package/dist/hooks/review/index.js.map +1 -1
  21. package/dist/hooks/review/use-dataset-review-items.d.ts +26 -2
  22. package/dist/hooks/review/use-dataset-review-items.d.ts.map +1 -1
  23. package/dist/hooks/schedules/index.cjs +1 -1
  24. package/dist/hooks/schedules/index.js +1 -1
  25. package/dist/hooks/scores/index.cjs +1 -1
  26. package/dist/hooks/scores/index.js +1 -1
  27. package/dist/hooks/shared/use-in-view.d.ts.map +1 -1
  28. package/dist/hooks/traces/index.cjs +1 -1
  29. package/dist/hooks/traces/index.js +1 -1
  30. package/dist/hooks/workflows/index.cjs +1 -1
  31. package/dist/hooks/workflows/index.js +1 -1
  32. package/dist/{use-in-view-CyjKdplM.js → use-in-view-ChEDWwE1.js} +5 -2
  33. package/dist/{use-in-view-CyjKdplM.js.map → use-in-view-ChEDWwE1.js.map} +1 -1
  34. package/dist/{use-in-view-BxdrrnCw.cjs → use-in-view-u7xWhAjL.cjs} +5 -2
  35. package/dist/{use-in-view-BxdrrnCw.cjs.map → use-in-view-u7xWhAjL.cjs.map} +1 -1
  36. package/package.json +5 -5
@@ -1,7 +1,7 @@
1
1
  import { n as useMastraClient } from "./mastra-client-context-DQ5z_ze9.js";
2
2
  import { t as useCombineByIds } from "./combine-by-ids-C-0oe4eH.js";
3
3
  import { t as getOrCreate } from "./map-5-4U5rwA.js";
4
- import { t as useInView } from "./use-in-view-CyjKdplM.js";
4
+ import { t as useInView } from "./use-in-view-ChEDWwE1.js";
5
5
  import { useEffect } from "react";
6
6
  import { keepPreviousData, useInfiniteQuery, useQueries, useQuery } from "@tanstack/react-query";
7
7
  // src/hooks/experiments/usage-accumulator.ts
@@ -296,4 +296,4 @@ function useInfiniteExperiments({ datasetId, target, orderBy, queryOptions }) {
296
296
  }
297
297
  export { useExperimentsForDatasetFilter as a, useExperimentsItemUsage as c, EXPERIMENTS_PAGE_SIZE as i, useInfiniteExperiments as n, useExperimentTrace as o, useExperimentsListMetrics as r, useExperimentMetrics as s, EXPERIMENTS_PER_PAGE as t };
298
298
 
299
- //# sourceMappingURL=experiments-B2PEqGwi.js.map
299
+ //# sourceMappingURL=experiments-BUTZk3Fu.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"experiments-B2PEqGwi.js","names":["POLL_INTERVAL_MS"],"sources":["../src/hooks/experiments/usage-accumulator.ts","../src/hooks/experiments/use-experiment-item-usage.ts","../src/hooks/experiments/use-experiment-metrics.ts","../src/hooks/experiments/use-experiment-trace.ts","../src/hooks/experiments/use-experiments-for-dataset-filter.ts","../src/hooks/experiments/use-experiments-list-metrics.ts","../src/hooks/experiments/use-infinite-experiments.ts"],"sourcesContent":["import type { GetMetricBreakdownResponse } from '@mastra/core/storage';\n\nexport const INPUT_TOKEN_METRIC = 'mastra_model_total_input_tokens';\nexport const OUTPUT_TOKEN_METRIC = 'mastra_model_total_output_tokens';\n\nexport interface ExperimentItemUsage {\n inputTokens?: number;\n outputTokens?: number;\n /** Undefined when no group is priced or when groups use different cost units. */\n estimatedCost?: number;\n costUnit?: string;\n}\n\nexport type UsageAccumulator = {\n inputTokens?: number;\n outputTokens?: number;\n estimatedCost: number;\n costUnits: Set<string>;\n hasUnknownCostUnit: boolean;\n};\n\nexport const createAccumulator = (): UsageAccumulator => ({\n estimatedCost: 0,\n costUnits: new Set(),\n hasUnknownCostUnit: false,\n});\n\ntype BreakdownGroup = GetMetricBreakdownResponse['groups'][number];\n\n/** The token field a breakdown group feeds, or undefined when the group is not a token metric. */\nexport function tokenFieldOf(group: BreakdownGroup): 'inputTokens' | 'outputTokens' | undefined {\n const metricName = group.dimensions.name;\n if (metricName === INPUT_TOKEN_METRIC) return 'inputTokens';\n if (metricName === OUTPUT_TOKEN_METRIC) return 'outputTokens';\n return undefined;\n}\n\nexport function accumulate(\n accumulator: UsageAccumulator,\n tokenField: 'inputTokens' | 'outputTokens',\n group: BreakdownGroup,\n) {\n accumulator[tokenField] = (accumulator[tokenField] ?? 0) + group.value;\n\n if (group.estimatedCost == null) return;\n accumulator.estimatedCost += group.estimatedCost;\n if (group.costUnit) {\n accumulator.costUnits.add(group.costUnit.toLowerCase());\n } else {\n accumulator.hasUnknownCostUnit = true;\n }\n}\n\nexport function toUsage(accumulator: UsageAccumulator): ExperimentItemUsage {\n // A single known unit implies at least one priced group.\n const isPriced = !accumulator.hasUnknownCostUnit && accumulator.costUnits.size === 1;\n return {\n inputTokens: accumulator.inputTokens,\n outputTokens: accumulator.outputTokens,\n estimatedCost: isPriced ? accumulator.estimatedCost : undefined,\n costUnit: isPriced ? [...accumulator.costUnits][0] : undefined,\n };\n}\n","import type { GetMetricBreakdownResponse } from '@mastra/core/storage';\nimport { useQueries } from '@tanstack/react-query';\nimport type { Query } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { ExperimentRef } from '../datasets/use-dataset-experiments';\nimport { useCombineByIds } from '../shared/combine-by-ids';\nimport type { ExperimentQueriesResult } from '../shared/combine-by-ids';\nimport { getOrCreate } from '../shared/map';\nimport {\n INPUT_TOKEN_METRIC,\n OUTPUT_TOKEN_METRIC,\n accumulate,\n createAccumulator,\n tokenFieldOf,\n toUsage,\n} from './usage-accumulator';\nimport type { ExperimentItemUsage, UsageAccumulator } from './usage-accumulator';\n\nexport type { ExperimentItemUsage } from './usage-accumulator';\n\nconst POLL_INTERVAL_MS = 2000;\n\n/** Usage of one experiment: its totals, and each item's usage keyed by the trace id of its run. */\nexport interface ExperimentUsage {\n /** Totals across every item. The cost sums priced groups only. */\n summary: ExperimentItemUsage;\n traces: Record<string, ExperimentItemUsage>;\n}\n\n/** Builds the experiment totals and the per-trace usage in a single pass over the groups. */\nfunction toExperimentUsage(response: GetMetricBreakdownResponse): ExperimentUsage {\n const summary = createAccumulator();\n const accumulators = new Map<string, UsageAccumulator>();\n\n for (const group of response.groups) {\n const tokenField = tokenFieldOf(group);\n if (!tokenField) continue;\n\n accumulate(summary, tokenField, group);\n\n const traceId = group.dimensions.traceId;\n if (traceId) accumulate(getOrCreate(accumulators, traceId, createAccumulator), tokenField, group);\n }\n\n const traces: Record<string, ExperimentItemUsage> = {};\n for (const [traceId, accumulator] of accumulators) {\n traces[traceId] = toUsage(accumulator);\n }\n return { summary: toUsage(summary), traces };\n}\n\n/** How many breakdowns to fetch after completion while the exporter may still be flushing metrics. */\nconst MAX_EMPTY_ATTEMPTS = 5;\n\nconst isEmptyUsage = (usage: ExperimentUsage | undefined) =>\n !usage ||\n (Object.keys(usage.traces).length === 0 &&\n usage.summary.inputTokens === undefined &&\n usage.summary.outputTokens === undefined);\n\n/**\n * Token and cost usage of several experiments, keyed by experiment id: each entry holds the\n * experiment totals (`summary`) and every item's usage keyed by trace id (`traces`).\n * Sends one metric breakdown request per experiment, filtered by its id rather than by trace ids,\n * so it does not wait for the experiment results. Usage is only fetched once an experiment has\n * finished; while the breakdown is still empty (metrics flushing), it retries every 2 seconds up to\n * 5 attempts. No request is made when the observability store cannot serve metrics.\n */\nexport const useExperimentsItemUsage = ({\n experiments,\n supportsMetrics,\n}: {\n experiments: ExperimentRef[];\n supportsMetrics: boolean;\n}): ExperimentQueriesResult<ExperimentUsage> => {\n const client = useMastraClient();\n const combine = useCombineByIds<ExperimentUsage>(experiments.map(experiment => experiment.id));\n\n return useQueries({\n queries: experiments.map(({ id, status }) => {\n const finished = status !== 'running' && status !== 'pending';\n return {\n queryKey: ['experiment-item-usage', id, finished],\n queryFn: async () =>\n toExperimentUsage(\n await client.getMetricBreakdown({\n name: [INPUT_TOKEN_METRIC, OUTPUT_TOKEN_METRIC],\n aggregation: 'sum',\n groupBy: ['traceId', 'name'],\n filters: { experimentId: id },\n }),\n ),\n enabled: supportsMetrics && finished,\n refetchInterval: (query: Query<ExperimentUsage>) =>\n isEmptyUsage(query.state.data) && query.state.dataUpdateCount < MAX_EMPTY_ATTEMPTS ? POLL_INTERVAL_MS : false,\n };\n }),\n combine,\n });\n};\n","import type { DatasetExperiment } from '@mastra/client-js';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nexport interface ExperimentMetrics {\n totalTokens: number | null;\n estimatedCost: number | null;\n costUnit: string | null;\n avgAgentDurationMs: number | null;\n agentRuns: number | null;\n}\n\ninterface UseExperimentMetricsArgs {\n experimentId: string | undefined;\n experimentStatus: DatasetExperiment['status'] | undefined;\n /** Whether the observability store can serve metrics; no requests are made when false. */\n supportsMetrics: boolean;\n queryOptions?: MastraQueryOptions<ExperimentMetrics>;\n}\n\n/**\n * Experiment-scoped metrics (tokens, cost, avg agent latency).\n * Filters only by experimentId — no time window, since the experiment already bounds the row set.\n * Polls every 2 seconds while the experiment is running or pending.\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useExperimentMetrics = ({\n experimentId,\n experimentStatus,\n supportsMetrics,\n queryOptions,\n}: UseExperimentMetricsArgs) => {\n const client = useMastraClient();\n const isEnabled = Boolean(experimentId) && supportsMetrics;\n const isActive = experimentStatus === 'running' || experimentStatus === 'pending';\n\n const query = useQuery({\n queryKey: ['experiment-metrics', experimentId],\n refetchInterval: isActive ? 2000 : false,\n queryFn: async (): Promise<ExperimentMetrics> => {\n // `enabled` already guards this; the check exists to narrow the type.\n if (!experimentId) throw new Error('experimentId is required');\n const filters = { experimentId };\n\n const [tokens, avgDuration, runs] = await Promise.all([\n client.getMetricAggregate({\n name: ['mastra_model_total_input_tokens', 'mastra_model_total_output_tokens'],\n aggregation: 'sum',\n filters,\n }),\n client.getMetricAggregate({ name: ['mastra_agent_duration_ms'], aggregation: 'avg', filters }),\n client.getMetricAggregate({ name: ['mastra_agent_duration_ms'], aggregation: 'count', filters }),\n ]);\n\n return {\n totalTokens: tokens.value ?? null,\n estimatedCost: tokens.estimatedCost ?? null,\n costUnit: tokens.costUnit ?? null,\n avgAgentDurationMs: avgDuration.value ?? null,\n agentRuns: runs.value ?? null,\n };\n },\n ...queryOptions,\n });\n\n return { data: query.data, isLoading: query.isLoading, isEnabled };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\ntype TraceLightResponse = Awaited<ReturnType<MastraClient['getTraceLight']>>;\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useExperimentTrace = <TData = TraceLightResponse>({\n traceId,\n queryOptions,\n}: {\n traceId: string | null | undefined;\n queryOptions?: MastraQueryOptions<TraceLightResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['experiment-trace-light', traceId],\n queryFn: async () => {\n if (!traceId) {\n throw new Error('Trace ID is required');\n }\n return client.getTraceLight(traceId);\n },\n ...queryOptions,\n });\n};\n","import type { ExperimentTargetType, ListExperimentsParams, MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\n/** Explicit page size: server defaults are 20 (global) / 10 (per dataset), which is too small for the list. */\nexport const EXPERIMENTS_PAGE_SIZE = 100;\n\nexport interface ExperimentTargetFilter {\n targetType?: ExperimentTargetType | '';\n targetId?: string;\n}\n\n/**\n * Experiments for the list page: the global list, or the dataset-scoped list when a dataset filter is active.\n * A dataset's runs may not be in the first page of the global list, so filtering client-side is not enough.\n * The optional target filter is applied server-side for the same reason.\n */\ntype ListExperimentsResponse = Awaited<ReturnType<MastraClient['listExperiments']>>;\n\nexport function useExperimentsForDatasetFilter<TData = ListExperimentsResponse>({\n datasetId,\n target,\n queryOptions,\n}: {\n datasetId: string | undefined;\n target?: ExperimentTargetFilter;\n queryOptions?: MastraQueryOptions<ListExperimentsResponse, TData>;\n}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n const params: ListExperimentsParams = { perPage: EXPERIMENTS_PAGE_SIZE };\n if (target?.targetType) params.targetType = target.targetType;\n if (target?.targetId) params.targetId = target.targetId;\n\n return useQuery({\n // Prefixes match the keys invalidated by dataset/experiment mutations.\n queryKey: datasetId ? ['dataset-experiments', datasetId, params] : ['experiments', params],\n queryFn: () => (datasetId ? client.listDatasetExperiments(datasetId, params) : client.listExperiments(params)),\n ...queryOptions,\n });\n}\n","import type { GetMetricBreakdownResponse } from '@mastra/core/storage';\nimport { keepPreviousData, useQuery } from '@tanstack/react-query';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { ExperimentRef } from '../datasets/use-dataset-experiments';\nimport { getOrCreate } from '../shared/map';\nimport {\n INPUT_TOKEN_METRIC,\n OUTPUT_TOKEN_METRIC,\n accumulate,\n createAccumulator,\n tokenFieldOf,\n toUsage,\n} from './usage-accumulator';\nimport type { ExperimentItemUsage, UsageAccumulator } from './usage-accumulator';\n\nconst AGENT_DURATION_METRIC = 'mastra_agent_duration_ms';\n// Each experiment can return two token groups, while the breakdown endpoint allows at most 1,000.\nconst EXPERIMENT_IDS_PER_REQUEST = 500;\nconst POLL_INTERVAL_MS = 5000;\n\n/** Totals of one experiment: token usage, its estimated cost, and the average agent run duration. */\nexport interface ExperimentListMetrics extends ExperimentItemUsage {\n avgDurationMs?: number;\n}\n\nfunction chunk(ids: readonly string[]): string[][] {\n const chunks: string[][] = [];\n for (let index = 0; index < ids.length; index += EXPERIMENT_IDS_PER_REQUEST) {\n chunks.push(ids.slice(index, index + EXPERIMENT_IDS_PER_REQUEST));\n }\n return chunks;\n}\n\nfunction settledValues<T>(results: PromiseSettledResult<T>[]): T[] {\n return results.flatMap(result => (result.status === 'fulfilled' ? [result.value] : []));\n}\n\n/**\n * Builds each requested experiment's metrics. Groups for other experiments are skipped,\n * in case a store ignores the `experimentIds` filter.\n */\nfunction toListMetrics(\n experimentIds: readonly string[],\n tokenResponses: GetMetricBreakdownResponse[],\n durationResponses: GetMetricBreakdownResponse[],\n): Map<string, ExperimentListMetrics> {\n const requested = new Set(experimentIds);\n const accumulators = new Map<string, UsageAccumulator>();\n for (const group of tokenResponses.flatMap(response => response.groups)) {\n const experimentId = group.dimensions.experimentId;\n const tokenField = tokenFieldOf(group);\n if (!experimentId || !requested.has(experimentId) || !tokenField) continue;\n accumulate(getOrCreate(accumulators, experimentId, createAccumulator), tokenField, group);\n }\n\n const metrics = new Map<string, ExperimentListMetrics>();\n for (const [experimentId, accumulator] of accumulators) {\n metrics.set(experimentId, toUsage(accumulator));\n }\n for (const group of durationResponses.flatMap(response => response.groups)) {\n const experimentId = group.dimensions.experimentId;\n if (!experimentId || !requested.has(experimentId)) continue;\n getOrCreate(metrics, experimentId, (): ExperimentListMetrics => ({})).avgDurationMs = group.value;\n }\n return metrics;\n}\n\n/**\n * Token usage, estimated cost and average agent duration of many experiments, keyed by experiment id.\n * Sends two metric breakdowns per 500 experiments (tokens grouped by experiment and metric name,\n * durations grouped by experiment) instead of one request per experiment.\n * Experiments without any metric are absent from the map. Polls while an experiment is running\n * or pending. No request is made when the observability store cannot serve metrics.\n */\nexport const useExperimentsListMetrics = ({\n experiments,\n supportsMetrics,\n}: {\n experiments: ExperimentRef[];\n supportsMetrics: boolean;\n}): UseQueryResult<Map<string, ExperimentListMetrics>, Error> => {\n const client = useMastraClient();\n const experimentIds = [...new Set(experiments.map(experiment => experiment.id))].toSorted();\n const hasActiveExperiment = experiments.some(({ status }) => status === 'running' || status === 'pending');\n\n return useQuery({\n queryKey: ['experiments-list-metrics', experimentIds],\n enabled: supportsMetrics && experimentIds.length > 0,\n queryFn: async () => {\n const batches = chunk(experimentIds);\n const [tokenResults, durationResults] = await Promise.all([\n Promise.allSettled(\n batches.map(batch =>\n client.getMetricBreakdown({\n name: [INPUT_TOKEN_METRIC, OUTPUT_TOKEN_METRIC],\n aggregation: 'sum',\n groupBy: ['experimentId', 'name'],\n filters: { experimentIds: batch },\n limit: batch.length * 2,\n }),\n ),\n ),\n Promise.allSettled(\n batches.map(batch =>\n client.getMetricBreakdown({\n name: [AGENT_DURATION_METRIC],\n aggregation: 'avg',\n groupBy: ['experimentId'],\n filters: { experimentIds: batch },\n limit: batch.length,\n }),\n ),\n ),\n ]);\n return toListMetrics(experimentIds, settledValues(tokenResults), settledValues(durationResults));\n },\n // Loading another page changes the ids; keep the rows already shown filled meanwhile.\n placeholderData: keepPreviousData,\n refetchInterval: hasActiveExperiment ? POLL_INTERVAL_MS : false,\n });\n};\n","import type { DatasetExperiment, ListExperimentsParams, MastraClient } from '@mastra/client-js';\nimport { useInfiniteQuery } from '@tanstack/react-query';\nimport type { InfiniteData, QueryKey, UseInfiniteQueryResult } from '@tanstack/react-query';\nimport { useEffect } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraInfiniteQueryOptions } from '../shared/query-options';\nimport { useInView } from '../shared/use-in-view';\nimport type { ExperimentTargetFilter } from './use-experiments-for-dataset-filter';\n\nexport const EXPERIMENTS_PER_PAGE = 100;\n\n/**\n * Infinite-scroll experiments for the list page: the global list, or the dataset-scoped list when a\n * dataset filter is active (a dataset's runs may not be in the first pages of the global list). The\n * optional target filter is applied server-side for the same reason.\n */\nexport type ExperimentsOrderBy = NonNullable<ListExperimentsParams['orderBy']>;\n\ntype ListExperimentsResponse = Awaited<ReturnType<MastraClient['listExperiments']>>;\n\nexport function useInfiniteExperiments<TData = DatasetExperiment[]>({\n datasetId,\n target,\n orderBy,\n queryOptions,\n}: {\n datasetId: string | undefined;\n target?: ExperimentTargetFilter;\n orderBy?: ExperimentsOrderBy;\n queryOptions?: MastraInfiniteQueryOptions<ListExperimentsResponse, TData, QueryKey, number>;\n}): UseInfiniteQueryResult<TData, Error> & {\n setEndOfListElement: (element: HTMLDivElement | null) => void;\n} {\n const client = useMastraClient();\n const { inView: isEndOfListInView, setRef: setEndOfListElement } = useInView();\n const targetType = target?.targetType || undefined;\n const targetId = target?.targetId || undefined;\n\n const query = useInfiniteQuery({\n // Prefixes match the keys invalidated by dataset/experiment mutations.\n queryKey: datasetId\n ? ['dataset-experiments', datasetId, 'infinite', { targetType, targetId, orderBy }]\n : ['experiments', 'infinite', { targetType, targetId, orderBy }],\n queryFn: ({ pageParam }) => {\n const params: ListExperimentsParams = { page: pageParam, perPage: EXPERIMENTS_PER_PAGE };\n if (targetType) params.targetType = targetType;\n if (targetId) params.targetId = targetId;\n if (orderBy) params.orderBy = orderBy;\n return datasetId ? client.listDatasetExperiments(datasetId, params) : client.listExperiments(params);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage, _, lastPageParam) => {\n if (!lastPage?.experiments?.length || !lastPage.pagination?.hasMore) {\n return undefined;\n }\n return lastPageParam + 1;\n },\n select: (data: InfiniteData<ListExperimentsResponse, number>) =>\n data.pages.flatMap(page => page?.experiments ?? []) as TData,\n ...queryOptions,\n });\n\n useEffect(() => {\n if (isEndOfListInView && query.hasNextPage && !query.isFetchingNextPage) {\n void query.fetchNextPage();\n }\n }, [isEndOfListInView, query]);\n\n return { ...query, setEndOfListElement };\n}\n"],"mappings":";;;;;;;AAEA,MAAa,qBAAqB;AAClC,MAAa,sBAAsB;AAkBnC,MAAa,2BAA6C;CACxD,eAAe;CACf,2BAAW,IAAI,IAAI;CACnB,oBAAoB;AACtB;;AAKA,SAAgB,aAAa,OAAmE;CAC9F,MAAM,aAAa,MAAM,WAAW;CACpC,IAAI,eAAA,mCAAmC,OAAO;CAC9C,IAAI,eAAA,oCAAoC,OAAO;AAEjD;AAEA,SAAgB,WACd,aACA,YACA,OACA;CACA,YAAY,eAAe,YAAY,eAAe,KAAK,MAAM;CAEjE,IAAI,MAAM,iBAAiB,MAAM;CACjC,YAAY,iBAAiB,MAAM;CACnC,IAAI,MAAM,UACR,YAAY,UAAU,IAAI,MAAM,SAAS,YAAY,CAAC;MAEtD,YAAY,qBAAqB;AAErC;AAEA,SAAgB,QAAQ,aAAoD;CAE1E,MAAM,WAAW,CAAC,YAAY,sBAAsB,YAAY,UAAU,SAAS;CACnF,OAAO;EACL,aAAa,YAAY;EACzB,cAAc,YAAY;EAC1B,eAAe,WAAW,YAAY,gBAAgB,KAAA;EACtD,UAAU,WAAW,CAAC,GAAG,YAAY,SAAS,CAAC,CAAC,KAAK,KAAA;CACvD;AACF;;AC1CA,MAAMA,qBAAmB;;AAUzB,SAAS,kBAAkB,UAAuD;CAChF,MAAM,UAAU,kBAAkB;CAClC,MAAM,+BAAe,IAAI,IAA8B;CAEvD,KAAK,MAAM,SAAS,SAAS,QAAQ;EACnC,MAAM,aAAa,aAAa,KAAK;EACrC,IAAI,CAAC,YAAY;EAEjB,WAAW,SAAS,YAAY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AC;GAAuB;GAAW;GAAY;IAAE;IAAY;IAAU;GAAQ;EAAC,IAChF;GAAC;GAAe;GAAY;IAAE;IAAY;IAAU;GAAQ;EAAC;EACjE,UAAU,EAAE,gBAAgB;GAC1B,MAAM,SAAgC;IAAE,MAAM;IAAW,SAAA;GAA8B;GACvF,IAAI,YAAY,OAAO,aAAa;GACpC,IAAI,UAAU,OAAO,WAAW;GAChC,IAAI,SAAS,OAAO,UAAU;GAC9B,OAAO,YAAY,OAAO,uBAAuB,WAAW,MAAM,IAAI,OAAO,gBAAgB,MAAM;EACrG;EACA,kBAAkB;EAClB,mBAAmB,UAAU,GAAG,kBAAkB;GAChD,IAAI,CAAC,UAAU,aAAa,UAAU,CAAC,SAAS,YAAY,SAC1D;GAEF,OAAO,gBAAgB;EACzB;EACA,SAAS,SACP,KAAK,MAAM,SAAQ,SAAQ,MAAM,eAAe,CAAC,CAAC;EACpD,GAAG;CACL,CAAC;CAED,gBAAgB;EACd,IAAI,qBAAqB,MAAM,eAAe,CAAC,MAAM,oBACnD,MAAW,cAAc;CAE7B,GAAG,CAAC,mBAAmB,KAAK,CAAC;CAE7B,OAAO;EAAE,GAAG;EAAO;CAAoB;AACzC"}
1
+ {"version":3,"file":"experiments-BUTZk3Fu.js","names":["POLL_INTERVAL_MS"],"sources":["../src/hooks/experiments/usage-accumulator.ts","../src/hooks/experiments/use-experiment-item-usage.ts","../src/hooks/experiments/use-experiment-metrics.ts","../src/hooks/experiments/use-experiment-trace.ts","../src/hooks/experiments/use-experiments-for-dataset-filter.ts","../src/hooks/experiments/use-experiments-list-metrics.ts","../src/hooks/experiments/use-infinite-experiments.ts"],"sourcesContent":["import type { GetMetricBreakdownResponse } from '@mastra/core/storage';\n\nexport const INPUT_TOKEN_METRIC = 'mastra_model_total_input_tokens';\nexport const OUTPUT_TOKEN_METRIC = 'mastra_model_total_output_tokens';\n\nexport interface ExperimentItemUsage {\n inputTokens?: number;\n outputTokens?: number;\n /** Undefined when no group is priced or when groups use different cost units. */\n estimatedCost?: number;\n costUnit?: string;\n}\n\nexport type UsageAccumulator = {\n inputTokens?: number;\n outputTokens?: number;\n estimatedCost: number;\n costUnits: Set<string>;\n hasUnknownCostUnit: boolean;\n};\n\nexport const createAccumulator = (): UsageAccumulator => ({\n estimatedCost: 0,\n costUnits: new Set(),\n hasUnknownCostUnit: false,\n});\n\ntype BreakdownGroup = GetMetricBreakdownResponse['groups'][number];\n\n/** The token field a breakdown group feeds, or undefined when the group is not a token metric. */\nexport function tokenFieldOf(group: BreakdownGroup): 'inputTokens' | 'outputTokens' | undefined {\n const metricName = group.dimensions.name;\n if (metricName === INPUT_TOKEN_METRIC) return 'inputTokens';\n if (metricName === OUTPUT_TOKEN_METRIC) return 'outputTokens';\n return undefined;\n}\n\nexport function accumulate(\n accumulator: UsageAccumulator,\n tokenField: 'inputTokens' | 'outputTokens',\n group: BreakdownGroup,\n) {\n accumulator[tokenField] = (accumulator[tokenField] ?? 0) + group.value;\n\n if (group.estimatedCost == null) return;\n accumulator.estimatedCost += group.estimatedCost;\n if (group.costUnit) {\n accumulator.costUnits.add(group.costUnit.toLowerCase());\n } else {\n accumulator.hasUnknownCostUnit = true;\n }\n}\n\nexport function toUsage(accumulator: UsageAccumulator): ExperimentItemUsage {\n // A single known unit implies at least one priced group.\n const isPriced = !accumulator.hasUnknownCostUnit && accumulator.costUnits.size === 1;\n return {\n inputTokens: accumulator.inputTokens,\n outputTokens: accumulator.outputTokens,\n estimatedCost: isPriced ? accumulator.estimatedCost : undefined,\n costUnit: isPriced ? [...accumulator.costUnits][0] : undefined,\n };\n}\n","import type { GetMetricBreakdownResponse } from '@mastra/core/storage';\nimport { useQueries } from '@tanstack/react-query';\nimport type { Query } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { ExperimentRef } from '../datasets/use-dataset-experiments';\nimport { useCombineByIds } from '../shared/combine-by-ids';\nimport type { ExperimentQueriesResult } from '../shared/combine-by-ids';\nimport { getOrCreate } from '../shared/map';\nimport {\n INPUT_TOKEN_METRIC,\n OUTPUT_TOKEN_METRIC,\n accumulate,\n createAccumulator,\n tokenFieldOf,\n toUsage,\n} from './usage-accumulator';\nimport type { ExperimentItemUsage, UsageAccumulator } from './usage-accumulator';\n\nexport type { ExperimentItemUsage } from './usage-accumulator';\n\nconst POLL_INTERVAL_MS = 2000;\n\n/** Usage of one experiment: its totals, and each item's usage keyed by the trace id of its run. */\nexport interface ExperimentUsage {\n /** Totals across every item. The cost sums priced groups only. */\n summary: ExperimentItemUsage;\n traces: Record<string, ExperimentItemUsage>;\n}\n\n/** Builds the experiment totals and the per-trace usage in a single pass over the groups. */\nfunction toExperimentUsage(response: GetMetricBreakdownResponse): ExperimentUsage {\n const summary = createAccumulator();\n const accumulators = new Map<string, UsageAccumulator>();\n\n for (const group of response.groups) {\n const tokenField = tokenFieldOf(group);\n if (!tokenField) continue;\n\n accumulate(summary, tokenField, group);\n\n const traceId = group.dimensions.traceId;\n if (traceId) accumulate(getOrCreate(accumulators, traceId, createAccumulator), tokenField, group);\n }\n\n const traces: Record<string, ExperimentItemUsage> = {};\n for (const [traceId, accumulator] of accumulators) {\n traces[traceId] = toUsage(accumulator);\n }\n return { summary: toUsage(summary), traces };\n}\n\n/** How many breakdowns to fetch after completion while the exporter may still be flushing metrics. */\nconst MAX_EMPTY_ATTEMPTS = 5;\n\nconst isEmptyUsage = (usage: ExperimentUsage | undefined) =>\n !usage ||\n (Object.keys(usage.traces).length === 0 &&\n usage.summary.inputTokens === undefined &&\n usage.summary.outputTokens === undefined);\n\n/**\n * Token and cost usage of several experiments, keyed by experiment id: each entry holds the\n * experiment totals (`summary`) and every item's usage keyed by trace id (`traces`).\n * Sends one metric breakdown request per experiment, filtered by its id rather than by trace ids,\n * so it does not wait for the experiment results. Usage is only fetched once an experiment has\n * finished; while the breakdown is still empty (metrics flushing), it retries every 2 seconds up to\n * 5 attempts. No request is made when the observability store cannot serve metrics.\n */\nexport const useExperimentsItemUsage = ({\n experiments,\n supportsMetrics,\n}: {\n experiments: ExperimentRef[];\n supportsMetrics: boolean;\n}): ExperimentQueriesResult<ExperimentUsage> => {\n const client = useMastraClient();\n const combine = useCombineByIds<ExperimentUsage>(experiments.map(experiment => experiment.id));\n\n return useQueries({\n queries: experiments.map(({ id, status }) => {\n const finished = status !== 'running' && status !== 'pending';\n return {\n queryKey: ['experiment-item-usage', id, finished],\n queryFn: async () =>\n toExperimentUsage(\n await client.getMetricBreakdown({\n name: [INPUT_TOKEN_METRIC, OUTPUT_TOKEN_METRIC],\n aggregation: 'sum',\n groupBy: ['traceId', 'name'],\n filters: { experimentId: id },\n }),\n ),\n enabled: supportsMetrics && finished,\n refetchInterval: (query: Query<ExperimentUsage>) =>\n isEmptyUsage(query.state.data) && query.state.dataUpdateCount < MAX_EMPTY_ATTEMPTS ? POLL_INTERVAL_MS : false,\n };\n }),\n combine,\n });\n};\n","import type { DatasetExperiment } from '@mastra/client-js';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nexport interface ExperimentMetrics {\n totalTokens: number | null;\n estimatedCost: number | null;\n costUnit: string | null;\n avgAgentDurationMs: number | null;\n agentRuns: number | null;\n}\n\ninterface UseExperimentMetricsArgs {\n experimentId: string | undefined;\n experimentStatus: DatasetExperiment['status'] | undefined;\n /** Whether the observability store can serve metrics; no requests are made when false. */\n supportsMetrics: boolean;\n queryOptions?: MastraQueryOptions<ExperimentMetrics>;\n}\n\n/**\n * Experiment-scoped metrics (tokens, cost, avg agent latency).\n * Filters only by experimentId — no time window, since the experiment already bounds the row set.\n * Polls every 2 seconds while the experiment is running or pending.\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useExperimentMetrics = ({\n experimentId,\n experimentStatus,\n supportsMetrics,\n queryOptions,\n}: UseExperimentMetricsArgs) => {\n const client = useMastraClient();\n const isEnabled = Boolean(experimentId) && supportsMetrics;\n const isActive = experimentStatus === 'running' || experimentStatus === 'pending';\n\n const query = useQuery({\n queryKey: ['experiment-metrics', experimentId],\n refetchInterval: isActive ? 2000 : false,\n queryFn: async (): Promise<ExperimentMetrics> => {\n // `enabled` already guards this; the check exists to narrow the type.\n if (!experimentId) throw new Error('experimentId is required');\n const filters = { experimentId };\n\n const [tokens, avgDuration, runs] = await Promise.all([\n client.getMetricAggregate({\n name: ['mastra_model_total_input_tokens', 'mastra_model_total_output_tokens'],\n aggregation: 'sum',\n filters,\n }),\n client.getMetricAggregate({ name: ['mastra_agent_duration_ms'], aggregation: 'avg', filters }),\n client.getMetricAggregate({ name: ['mastra_agent_duration_ms'], aggregation: 'count', filters }),\n ]);\n\n return {\n totalTokens: tokens.value ?? null,\n estimatedCost: tokens.estimatedCost ?? null,\n costUnit: tokens.costUnit ?? null,\n avgAgentDurationMs: avgDuration.value ?? null,\n agentRuns: runs.value ?? null,\n };\n },\n ...queryOptions,\n });\n\n return { data: query.data, isLoading: query.isLoading, isEnabled };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\ntype TraceLightResponse = Awaited<ReturnType<MastraClient['getTraceLight']>>;\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useExperimentTrace = <TData = TraceLightResponse>({\n traceId,\n queryOptions,\n}: {\n traceId: string | null | undefined;\n queryOptions?: MastraQueryOptions<TraceLightResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['experiment-trace-light', traceId],\n queryFn: async () => {\n if (!traceId) {\n throw new Error('Trace ID is required');\n }\n return client.getTraceLight(traceId);\n },\n ...queryOptions,\n });\n};\n","import type { ExperimentTargetType, ListExperimentsParams, MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\n/** Explicit page size: server defaults are 20 (global) / 10 (per dataset), which is too small for the list. */\nexport const EXPERIMENTS_PAGE_SIZE = 100;\n\nexport interface ExperimentTargetFilter {\n targetType?: ExperimentTargetType | '';\n targetId?: string;\n}\n\n/**\n * Experiments for the list page: the global list, or the dataset-scoped list when a dataset filter is active.\n * A dataset's runs may not be in the first page of the global list, so filtering client-side is not enough.\n * The optional target filter is applied server-side for the same reason.\n */\ntype ListExperimentsResponse = Awaited<ReturnType<MastraClient['listExperiments']>>;\n\nexport function useExperimentsForDatasetFilter<TData = ListExperimentsResponse>({\n datasetId,\n target,\n queryOptions,\n}: {\n datasetId: string | undefined;\n target?: ExperimentTargetFilter;\n queryOptions?: MastraQueryOptions<ListExperimentsResponse, TData>;\n}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n const params: ListExperimentsParams = { perPage: EXPERIMENTS_PAGE_SIZE };\n if (target?.targetType) params.targetType = target.targetType;\n if (target?.targetId) params.targetId = target.targetId;\n\n return useQuery({\n // Prefixes match the keys invalidated by dataset/experiment mutations.\n queryKey: datasetId ? ['dataset-experiments', datasetId, params] : ['experiments', params],\n queryFn: () => (datasetId ? client.listDatasetExperiments(datasetId, params) : client.listExperiments(params)),\n ...queryOptions,\n });\n}\n","import type { GetMetricBreakdownResponse } from '@mastra/core/storage';\nimport { keepPreviousData, useQuery } from '@tanstack/react-query';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { ExperimentRef } from '../datasets/use-dataset-experiments';\nimport { getOrCreate } from '../shared/map';\nimport {\n INPUT_TOKEN_METRIC,\n OUTPUT_TOKEN_METRIC,\n accumulate,\n createAccumulator,\n tokenFieldOf,\n toUsage,\n} from './usage-accumulator';\nimport type { ExperimentItemUsage, UsageAccumulator } from './usage-accumulator';\n\nconst AGENT_DURATION_METRIC = 'mastra_agent_duration_ms';\n// Each experiment can return two token groups, while the breakdown endpoint allows at most 1,000.\nconst EXPERIMENT_IDS_PER_REQUEST = 500;\nconst POLL_INTERVAL_MS = 5000;\n\n/** Totals of one experiment: token usage, its estimated cost, and the average agent run duration. */\nexport interface ExperimentListMetrics extends ExperimentItemUsage {\n avgDurationMs?: number;\n}\n\nfunction chunk(ids: readonly string[]): string[][] {\n const chunks: string[][] = [];\n for (let index = 0; index < ids.length; index += EXPERIMENT_IDS_PER_REQUEST) {\n chunks.push(ids.slice(index, index + EXPERIMENT_IDS_PER_REQUEST));\n }\n return chunks;\n}\n\nfunction settledValues<T>(results: PromiseSettledResult<T>[]): T[] {\n return results.flatMap(result => (result.status === 'fulfilled' ? [result.value] : []));\n}\n\n/**\n * Builds each requested experiment's metrics. Groups for other experiments are skipped,\n * in case a store ignores the `experimentIds` filter.\n */\nfunction toListMetrics(\n experimentIds: readonly string[],\n tokenResponses: GetMetricBreakdownResponse[],\n durationResponses: GetMetricBreakdownResponse[],\n): Map<string, ExperimentListMetrics> {\n const requested = new Set(experimentIds);\n const accumulators = new Map<string, UsageAccumulator>();\n for (const group of tokenResponses.flatMap(response => response.groups)) {\n const experimentId = group.dimensions.experimentId;\n const tokenField = tokenFieldOf(group);\n if (!experimentId || !requested.has(experimentId) || !tokenField) continue;\n accumulate(getOrCreate(accumulators, experimentId, createAccumulator), tokenField, group);\n }\n\n const metrics = new Map<string, ExperimentListMetrics>();\n for (const [experimentId, accumulator] of accumulators) {\n metrics.set(experimentId, toUsage(accumulator));\n }\n for (const group of durationResponses.flatMap(response => response.groups)) {\n const experimentId = group.dimensions.experimentId;\n if (!experimentId || !requested.has(experimentId)) continue;\n getOrCreate(metrics, experimentId, (): ExperimentListMetrics => ({})).avgDurationMs = group.value;\n }\n return metrics;\n}\n\n/**\n * Token usage, estimated cost and average agent duration of many experiments, keyed by experiment id.\n * Sends two metric breakdowns per 500 experiments (tokens grouped by experiment and metric name,\n * durations grouped by experiment) instead of one request per experiment.\n * Experiments without any metric are absent from the map. Polls while an experiment is running\n * or pending. No request is made when the observability store cannot serve metrics.\n */\nexport const useExperimentsListMetrics = ({\n experiments,\n supportsMetrics,\n}: {\n experiments: ExperimentRef[];\n supportsMetrics: boolean;\n}): UseQueryResult<Map<string, ExperimentListMetrics>, Error> => {\n const client = useMastraClient();\n const experimentIds = [...new Set(experiments.map(experiment => experiment.id))].toSorted();\n const hasActiveExperiment = experiments.some(({ status }) => status === 'running' || status === 'pending');\n\n return useQuery({\n queryKey: ['experiments-list-metrics', experimentIds],\n enabled: supportsMetrics && experimentIds.length > 0,\n queryFn: async () => {\n const batches = chunk(experimentIds);\n const [tokenResults, durationResults] = await Promise.all([\n Promise.allSettled(\n batches.map(batch =>\n client.getMetricBreakdown({\n name: [INPUT_TOKEN_METRIC, OUTPUT_TOKEN_METRIC],\n aggregation: 'sum',\n groupBy: ['experimentId', 'name'],\n filters: { experimentIds: batch },\n limit: batch.length * 2,\n }),\n ),\n ),\n Promise.allSettled(\n batches.map(batch =>\n client.getMetricBreakdown({\n name: [AGENT_DURATION_METRIC],\n aggregation: 'avg',\n groupBy: ['experimentId'],\n filters: { experimentIds: batch },\n limit: batch.length,\n }),\n ),\n ),\n ]);\n return toListMetrics(experimentIds, settledValues(tokenResults), settledValues(durationResults));\n },\n // Loading another page changes the ids; keep the rows already shown filled meanwhile.\n placeholderData: keepPreviousData,\n refetchInterval: hasActiveExperiment ? POLL_INTERVAL_MS : false,\n });\n};\n","import type { DatasetExperiment, ListExperimentsParams, MastraClient } from '@mastra/client-js';\nimport { useInfiniteQuery } from '@tanstack/react-query';\nimport type { InfiniteData, QueryKey, UseInfiniteQueryResult } from '@tanstack/react-query';\nimport { useEffect } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraInfiniteQueryOptions } from '../shared/query-options';\nimport { useInView } from '../shared/use-in-view';\nimport type { ExperimentTargetFilter } from './use-experiments-for-dataset-filter';\n\nexport const EXPERIMENTS_PER_PAGE = 100;\n\n/**\n * Infinite-scroll experiments for the list page: the global list, or the dataset-scoped list when a\n * dataset filter is active (a dataset's runs may not be in the first pages of the global list). The\n * optional target filter is applied server-side for the same reason.\n */\nexport type ExperimentsOrderBy = NonNullable<ListExperimentsParams['orderBy']>;\n\ntype ListExperimentsResponse = Awaited<ReturnType<MastraClient['listExperiments']>>;\n\nexport function useInfiniteExperiments<TData = DatasetExperiment[]>({\n datasetId,\n target,\n orderBy,\n queryOptions,\n}: {\n datasetId: string | undefined;\n target?: ExperimentTargetFilter;\n orderBy?: ExperimentsOrderBy;\n queryOptions?: MastraInfiniteQueryOptions<ListExperimentsResponse, TData, QueryKey, number>;\n}): UseInfiniteQueryResult<TData, Error> & {\n setEndOfListElement: (element: HTMLDivElement | null) => void;\n} {\n const client = useMastraClient();\n const { inView: isEndOfListInView, setRef: setEndOfListElement } = useInView();\n const targetType = target?.targetType || undefined;\n const targetId = target?.targetId || undefined;\n\n const query = useInfiniteQuery({\n // Prefixes match the keys invalidated by dataset/experiment mutations.\n queryKey: datasetId\n ? ['dataset-experiments', datasetId, 'infinite', { targetType, targetId, orderBy }]\n : ['experiments', 'infinite', { targetType, targetId, orderBy }],\n queryFn: ({ pageParam }) => {\n const params: ListExperimentsParams = { page: pageParam, perPage: EXPERIMENTS_PER_PAGE };\n if (targetType) params.targetType = targetType;\n if (targetId) params.targetId = targetId;\n if (orderBy) params.orderBy = orderBy;\n return datasetId ? client.listDatasetExperiments(datasetId, params) : client.listExperiments(params);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage, _, lastPageParam) => {\n if (!lastPage?.experiments?.length || !lastPage.pagination?.hasMore) {\n return undefined;\n }\n return lastPageParam + 1;\n },\n select: (data: InfiniteData<ListExperimentsResponse, number>) =>\n data.pages.flatMap(page => page?.experiments ?? []) as TData,\n ...queryOptions,\n });\n\n useEffect(() => {\n if (isEndOfListInView && query.hasNextPage && !query.isFetchingNextPage) {\n void query.fetchNextPage();\n }\n }, [isEndO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ACpC,IAAI,UAAU,OAAO,WAAW;GAChC,IAAI,SAAS,OAAO,UAAU;GAC9B,OAAO,YAAY,OAAO,uBAAuB,WAAW,MAAM,IAAI,OAAO,gBAAgB,MAAM;EACrG;EACA,kBAAkB;EAClB,mBAAmB,UAAU,GAAG,kBAAkB;GAChD,IAAI,CAAC,UAAU,aAAa,UAAU,CAAC,SAAS,YAAY,SAC1D;GAEF,OAAO,gBAAgB;EACzB;EACA,SAAS,SACP,KAAK,MAAM,SAAQ,SAAQ,MAAM,eAAe,CAAC,CAAC;EACpD,GAAG;CACL,CAAC;CAED,gBAAgB;EACd,IAAI,qBAAqB,MAAM,eAAe,CAAC,MAAM,oBACnD,MAAW,cAAc;CAE7B,GAAG,CAAC,mBAAmB,KAAK,CAAC;CAE7B,OAAO;EAAE,GAAG;EAAO;CAAoB;AACzC"}
@@ -1,7 +1,7 @@
1
1
  const require_mastra_client_context = require("./mastra-client-context-DX8wJM9p.cjs");
2
2
  const require_combine_by_ids = require("./combine-by-ids-ERVPXXBi.cjs");
3
3
  const require_map = require("./map-BGoWBTGy.cjs");
4
- const require_use_in_view = require("./use-in-view-BxdrrnCw.cjs");
4
+ const require_use_in_view = require("./use-in-view-u7xWhAjL.cjs");
5
5
  let react = require("react");
6
6
  let _tanstack_react_query = require("@tanstack/react-query");
7
7
  // src/hooks/experiments/usage-accumulator.ts
@@ -343,4 +343,4 @@ Object.defineProperty(exports, "useInfiniteExperiments", {
343
343
  }
344
344
  });
345
345
 
346
- //# sourceMappingURL=experiments-beUCWMr-.cjs.map
346
+ //# sourceMappingURL=experiments-CDqRm-1r.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"experiments-beUCWMr-.cjs","names":["POLL_INTERVAL_MS","getOrCreate","useMastraClient","useCombineByIds","useQueries","useMastraClient","useQuery","useMastraClient","useQuery","useMastraClient","useQuery","getOrCreate","useMastraClient","useQuery","keepPreviousData","useMastraClient","useInView","useInfiniteQuery"],"sources":["../src/hooks/experiments/usage-accumulator.ts","../src/hooks/experiments/use-experiment-item-usage.ts","../src/hooks/experiments/use-experiment-metrics.ts","../src/hooks/experiments/use-experiment-trace.ts","../src/hooks/experiments/use-experiments-for-dataset-filter.ts","../src/hooks/experiments/use-experiments-list-metrics.ts","../src/hooks/experiments/use-infinite-experiments.ts"],"sourcesContent":["import type { GetMetricBreakdownResponse } from '@mastra/core/storage';\n\nexport const INPUT_TOKEN_METRIC = 'mastra_model_total_input_tokens';\nexport const OUTPUT_TOKEN_METRIC = 'mastra_model_total_output_tokens';\n\nexport interface ExperimentItemUsage {\n inputTokens?: number;\n outputTokens?: number;\n /** Undefined when no group is priced or when groups use different cost units. */\n estimatedCost?: number;\n costUnit?: string;\n}\n\nexport type UsageAccumulator = {\n inputTokens?: number;\n outputTokens?: number;\n estimatedCost: number;\n costUnits: Set<string>;\n hasUnknownCostUnit: boolean;\n};\n\nexport const createAccumulator = (): UsageAccumulator => ({\n estimatedCost: 0,\n costUnits: new Set(),\n hasUnknownCostUnit: false,\n});\n\ntype BreakdownGroup = GetMetricBreakdownResponse['groups'][number];\n\n/** The token field a breakdown group feeds, or undefined when the group is not a token metric. */\nexport function tokenFieldOf(group: BreakdownGroup): 'inputTokens' | 'outputTokens' | undefined {\n const metricName = group.dimensions.name;\n if (metricName === INPUT_TOKEN_METRIC) return 'inputTokens';\n if (metricName === OUTPUT_TOKEN_METRIC) return 'outputTokens';\n return undefined;\n}\n\nexport function accumulate(\n accumulator: UsageAccumulator,\n tokenField: 'inputTokens' | 'outputTokens',\n group: BreakdownGroup,\n) {\n accumulator[tokenField] = (accumulator[tokenField] ?? 0) + group.value;\n\n if (group.estimatedCost == null) return;\n accumulator.estimatedCost += group.estimatedCost;\n if (group.costUnit) {\n accumulator.costUnits.add(group.costUnit.toLowerCase());\n } else {\n accumulator.hasUnknownCostUnit = true;\n }\n}\n\nexport function toUsage(accumulator: UsageAccumulator): ExperimentItemUsage {\n // A single known unit implies at least one priced group.\n const isPriced = !accumulator.hasUnknownCostUnit && accumulator.costUnits.size === 1;\n return {\n inputTokens: accumulator.inputTokens,\n outputTokens: accumulator.outputTokens,\n estimatedCost: isPriced ? accumulator.estimatedCost : undefined,\n costUnit: isPriced ? [...accumulator.costUnits][0] : undefined,\n };\n}\n","import type { GetMetricBreakdownResponse } from '@mastra/core/storage';\nimport { useQueries } from '@tanstack/react-query';\nimport type { Query } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { ExperimentRef } from '../datasets/use-dataset-experiments';\nimport { useCombineByIds } from '../shared/combine-by-ids';\nimport type { ExperimentQueriesResult } from '../shared/combine-by-ids';\nimport { getOrCreate } from '../shared/map';\nimport {\n INPUT_TOKEN_METRIC,\n OUTPUT_TOKEN_METRIC,\n accumulate,\n createAccumulator,\n tokenFieldOf,\n toUsage,\n} from './usage-accumulator';\nimport type { ExperimentItemUsage, UsageAccumulator } from './usage-accumulator';\n\nexport type { ExperimentItemUsage } from './usage-accumulator';\n\nconst POLL_INTERVAL_MS = 2000;\n\n/** Usage of one experiment: its totals, and each item's usage keyed by the trace id of its run. */\nexport interface ExperimentUsage {\n /** Totals across every item. The cost sums priced groups only. */\n summary: ExperimentItemUsage;\n traces: Record<string, ExperimentItemUsage>;\n}\n\n/** Builds the experiment totals and the per-trace usage in a single pass over the groups. */\nfunction toExperimentUsage(response: GetMetricBreakdownResponse): ExperimentUsage {\n const summary = createAccumulator();\n const accumulators = new Map<string, UsageAccumulator>();\n\n for (const group of response.groups) {\n const tokenField = tokenFieldOf(group);\n if (!tokenField) continue;\n\n accumulate(summary, tokenField, group);\n\n const traceId = group.dimensions.traceId;\n if (traceId) accumulate(getOrCreate(accumulators, traceId, createAccumulator), tokenField, group);\n }\n\n const traces: Record<string, ExperimentItemUsage> = {};\n for (const [traceId, accumulator] of accumulators) {\n traces[traceId] = toUsage(accumulator);\n }\n return { summary: toUsage(summary), traces };\n}\n\n/** How many breakdowns to fetch after completion while the exporter may still be flushing metrics. */\nconst MAX_EMPTY_ATTEMPTS = 5;\n\nconst isEmptyUsage = (usage: ExperimentUsage | undefined) =>\n !usage ||\n (Object.keys(usage.traces).length === 0 &&\n usage.summary.inputTokens === undefined &&\n usage.summary.outputTokens === undefined);\n\n/**\n * Token and cost usage of several experiments, keyed by experiment id: each entry holds the\n * experiment totals (`summary`) and every item's usage keyed by trace id (`traces`).\n * Sends one metric breakdown request per experiment, filtered by its id rather than by trace ids,\n * so it does not wait for the experiment results. Usage is only fetched once an experiment has\n * finished; while the breakdown is still empty (metrics flushing), it retries every 2 seconds up to\n * 5 attempts. No request is made when the observability store cannot serve metrics.\n */\nexport const useExperimentsItemUsage = ({\n experiments,\n supportsMetrics,\n}: {\n experiments: ExperimentRef[];\n supportsMetrics: boolean;\n}): ExperimentQueriesResult<ExperimentUsage> => {\n const client = useMastraClient();\n const combine = useCombineByIds<ExperimentUsage>(experiments.map(experiment => experiment.id));\n\n return useQueries({\n queries: experiments.map(({ id, status }) => {\n const finished = status !== 'running' && status !== 'pending';\n return {\n queryKey: ['experiment-item-usage', id, finished],\n queryFn: async () =>\n toExperimentUsage(\n await client.getMetricBreakdown({\n name: [INPUT_TOKEN_METRIC, OUTPUT_TOKEN_METRIC],\n aggregation: 'sum',\n groupBy: ['traceId', 'name'],\n filters: { experimentId: id },\n }),\n ),\n enabled: supportsMetrics && finished,\n refetchInterval: (query: Query<ExperimentUsage>) =>\n isEmptyUsage(query.state.data) && query.state.dataUpdateCount < MAX_EMPTY_ATTEMPTS ? POLL_INTERVAL_MS : false,\n };\n }),\n combine,\n });\n};\n","import type { DatasetExperiment } from '@mastra/client-js';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nexport interface ExperimentMetrics {\n totalTokens: number | null;\n estimatedCost: number | null;\n costUnit: string | null;\n avgAgentDurationMs: number | null;\n agentRuns: number | null;\n}\n\ninterface UseExperimentMetricsArgs {\n experimentId: string | undefined;\n experimentStatus: DatasetExperiment['status'] | undefined;\n /** Whether the observability store can serve metrics; no requests are made when false. */\n supportsMetrics: boolean;\n queryOptions?: MastraQueryOptions<ExperimentMetrics>;\n}\n\n/**\n * Experiment-scoped metrics (tokens, cost, avg agent latency).\n * Filters only by experimentId — no time window, since the experiment already bounds the row set.\n * Polls every 2 seconds while the experiment is running or pending.\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useExperimentMetrics = ({\n experimentId,\n experimentStatus,\n supportsMetrics,\n queryOptions,\n}: UseExperimentMetricsArgs) => {\n const client = useMastraClient();\n const isEnabled = Boolean(experimentId) && supportsMetrics;\n const isActive = experimentStatus === 'running' || experimentStatus === 'pending';\n\n const query = useQuery({\n queryKey: ['experiment-metrics', experimentId],\n refetchInterval: isActive ? 2000 : false,\n queryFn: async (): Promise<ExperimentMetrics> => {\n // `enabled` already guards this; the check exists to narrow the type.\n if (!experimentId) throw new Error('experimentId is required');\n const filters = { experimentId };\n\n const [tokens, avgDuration, runs] = await Promise.all([\n client.getMetricAggregate({\n name: ['mastra_model_total_input_tokens', 'mastra_model_total_output_tokens'],\n aggregation: 'sum',\n filters,\n }),\n client.getMetricAggregate({ name: ['mastra_agent_duration_ms'], aggregation: 'avg', filters }),\n client.getMetricAggregate({ name: ['mastra_agent_duration_ms'], aggregation: 'count', filters }),\n ]);\n\n return {\n totalTokens: tokens.value ?? null,\n estimatedCost: tokens.estimatedCost ?? null,\n costUnit: tokens.costUnit ?? null,\n avgAgentDurationMs: avgDuration.value ?? null,\n agentRuns: runs.value ?? null,\n };\n },\n ...queryOptions,\n });\n\n return { data: query.data, isLoading: query.isLoading, isEnabled };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\ntype TraceLightResponse = Awaited<ReturnType<MastraClient['getTraceLight']>>;\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useExperimentTrace = <TData = TraceLightResponse>({\n traceId,\n queryOptions,\n}: {\n traceId: string | null | undefined;\n queryOptions?: MastraQueryOptions<TraceLightResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['experiment-trace-light', traceId],\n queryFn: async () => {\n if (!traceId) {\n throw new Error('Trace ID is required');\n }\n return client.getTraceLight(traceId);\n },\n ...queryOptions,\n });\n};\n","import type { ExperimentTargetType, ListExperimentsParams, MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\n/** Explicit page size: server defaults are 20 (global) / 10 (per dataset), which is too small for the list. */\nexport const EXPERIMENTS_PAGE_SIZE = 100;\n\nexport interface ExperimentTargetFilter {\n targetType?: ExperimentTargetType | '';\n targetId?: string;\n}\n\n/**\n * Experiments for the list page: the global list, or the dataset-scoped list when a dataset filter is active.\n * A dataset's runs may not be in the first page of the global list, so filtering client-side is not enough.\n * The optional target filter is applied server-side for the same reason.\n */\ntype ListExperimentsResponse = Awaited<ReturnType<MastraClient['listExperiments']>>;\n\nexport function useExperimentsForDatasetFilter<TData = ListExperimentsResponse>({\n datasetId,\n target,\n queryOptions,\n}: {\n datasetId: string | undefined;\n target?: ExperimentTargetFilter;\n queryOptions?: MastraQueryOptions<ListExperimentsResponse, TData>;\n}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n const params: ListExperimentsParams = { perPage: EXPERIMENTS_PAGE_SIZE };\n if (target?.targetType) params.targetType = target.targetType;\n if (target?.targetId) params.targetId = target.targetId;\n\n return useQuery({\n // Prefixes match the keys invalidated by dataset/experiment mutations.\n queryKey: datasetId ? ['dataset-experiments', datasetId, params] : ['experiments', params],\n queryFn: () => (datasetId ? client.listDatasetExperiments(datasetId, params) : client.listExperiments(params)),\n ...queryOptions,\n });\n}\n","import type { GetMetricBreakdownResponse } from '@mastra/core/storage';\nimport { keepPreviousData, useQuery } from '@tanstack/react-query';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { ExperimentRef } from '../datasets/use-dataset-experiments';\nimport { getOrCreate } from '../shared/map';\nimport {\n INPUT_TOKEN_METRIC,\n OUTPUT_TOKEN_METRIC,\n accumulate,\n createAccumulator,\n tokenFieldOf,\n toUsage,\n} from './usage-accumulator';\nimport type { ExperimentItemUsage, UsageAccumulator } from './usage-accumulator';\n\nconst AGENT_DURATION_METRIC = 'mastra_agent_duration_ms';\n// Each experiment can return two token groups, while the breakdown endpoint allows at most 1,000.\nconst EXPERIMENT_IDS_PER_REQUEST = 500;\nconst POLL_INTERVAL_MS = 5000;\n\n/** Totals of one experiment: token usage, its estimated cost, and the average agent run duration. */\nexport interface ExperimentListMetrics extends ExperimentItemUsage {\n avgDurationMs?: number;\n}\n\nfunction chunk(ids: readonly string[]): string[][] {\n const chunks: string[][] = [];\n for (let index = 0; index < ids.length; index += EXPERIMENT_IDS_PER_REQUEST) {\n chunks.push(ids.slice(index, index + EXPERIMENT_IDS_PER_REQUEST));\n }\n return chunks;\n}\n\nfunction settledValues<T>(results: PromiseSettledResult<T>[]): T[] {\n return results.flatMap(result => (result.status === 'fulfilled' ? [result.value] : []));\n}\n\n/**\n * Builds each requested experiment's metrics. Groups for other experiments are skipped,\n * in case a store ignores the `experimentIds` filter.\n */\nfunction toListMetrics(\n experimentIds: readonly string[],\n tokenResponses: GetMetricBreakdownResponse[],\n durationResponses: GetMetricBreakdownResponse[],\n): Map<string, ExperimentListMetrics> {\n const requested = new Set(experimentIds);\n const accumulators = new Map<string, UsageAccumulator>();\n for (const group of tokenResponses.flatMap(response => response.groups)) {\n const experimentId = group.dimensions.experimentId;\n const tokenField = tokenFieldOf(group);\n if (!experimentId || !requested.has(experimentId) || !tokenField) continue;\n accumulate(getOrCreate(accumulators, experimentId, createAccumulator), tokenField, group);\n }\n\n const metrics = new Map<string, ExperimentListMetrics>();\n for (const [experimentId, accumulator] of accumulators) {\n metrics.set(experimentId, toUsage(accumulator));\n }\n for (const group of durationResponses.flatMap(response => response.groups)) {\n const experimentId = group.dimensions.experimentId;\n if (!experimentId || !requested.has(experimentId)) continue;\n getOrCreate(metrics, experimentId, (): ExperimentListMetrics => ({})).avgDurationMs = group.value;\n }\n return metrics;\n}\n\n/**\n * Token usage, estimated cost and average agent duration of many experiments, keyed by experiment id.\n * Sends two metric breakdowns per 500 experiments (tokens grouped by experiment and metric name,\n * durations grouped by experiment) instead of one request per experiment.\n * Experiments without any metric are absent from the map. Polls while an experiment is running\n * or pending. No request is made when the observability store cannot serve metrics.\n */\nexport const useExperimentsListMetrics = ({\n experiments,\n supportsMetrics,\n}: {\n experiments: ExperimentRef[];\n supportsMetrics: boolean;\n}): UseQueryResult<Map<string, ExperimentListMetrics>, Error> => {\n const client = useMastraClient();\n const experimentIds = [...new Set(experiments.map(experiment => experiment.id))].toSorted();\n const hasActiveExperiment = experiments.some(({ status }) => status === 'running' || status === 'pending');\n\n return useQuery({\n queryKey: ['experiments-list-metrics', experimentIds],\n enabled: supportsMetrics && experimentIds.length > 0,\n queryFn: async () => {\n const batches = chunk(experimentIds);\n const [tokenResults, durationResults] = await Promise.all([\n Promise.allSettled(\n batches.map(batch =>\n client.getMetricBreakdown({\n name: [INPUT_TOKEN_METRIC, OUTPUT_TOKEN_METRIC],\n aggregation: 'sum',\n groupBy: ['experimentId', 'name'],\n filters: { experimentIds: batch },\n limit: batch.length * 2,\n }),\n ),\n ),\n Promise.allSettled(\n batches.map(batch =>\n client.getMetricBreakdown({\n name: [AGENT_DURATION_METRIC],\n aggregation: 'avg',\n groupBy: ['experimentId'],\n filters: { experimentIds: batch },\n limit: batch.length,\n }),\n ),\n ),\n ]);\n return toListMetrics(experimentIds, settledValues(tokenResults), settledValues(durationResults));\n },\n // Loading another page changes the ids; keep the rows already shown filled meanwhile.\n placeholderData: keepPreviousData,\n refetchInterval: hasActiveExperiment ? POLL_INTERVAL_MS : false,\n });\n};\n","import type { DatasetExperiment, ListExperimentsParams, MastraClient } from '@mastra/client-js';\nimport { useInfiniteQuery } from '@tanstack/react-query';\nimport type { InfiniteData, QueryKey, UseInfiniteQueryResult } from '@tanstack/react-query';\nimport { useEffect } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraInfiniteQueryOptions } from '../shared/query-options';\nimport { useInView } from '../shared/use-in-view';\nimport type { ExperimentTargetFilter } from './use-experiments-for-dataset-filter';\n\nexport const EXPERIMENTS_PER_PAGE = 100;\n\n/**\n * Infinite-scroll experiments for the list page: the global list, or the dataset-scoped list when a\n * dataset filter is active (a dataset's runs may not be in the first pages of the global list). The\n * optional target filter is applied server-side for the same reason.\n */\nexport type ExperimentsOrderBy = NonNullable<ListExperimentsParams['orderBy']>;\n\ntype ListExperimentsResponse = Awaited<ReturnType<MastraClient['listExperiments']>>;\n\nexport function useInfiniteExperiments<TData = DatasetExperiment[]>({\n datasetId,\n target,\n orderBy,\n queryOptions,\n}: {\n datasetId: string | undefined;\n target?: ExperimentTargetFilter;\n orderBy?: ExperimentsOrderBy;\n queryOptions?: MastraInfiniteQueryOptions<ListExperimentsResponse, TData, QueryKey, number>;\n}): UseInfiniteQueryResult<TData, Error> & {\n setEndOfListElement: (element: HTMLDivElement | null) => void;\n} {\n const client = useMastraClient();\n const { inView: isEndOfListInView, setRef: setEndOfListElement } = useInView();\n const targetType = target?.targetType || undefined;\n const targetId = target?.targetId || undefined;\n\n const query = useInfiniteQuery({\n // Prefixes match the keys invalidated by dataset/experiment mutations.\n queryKey: datasetId\n ? ['dataset-experiments', datasetId, 'infinite', { targetType, targetId, orderBy }]\n : ['experiments', 'infinite', { targetType, targetId, orderBy }],\n queryFn: ({ pageParam }) => {\n const params: ListExperimentsParams = { page: pageParam, perPage: EXPERIMENTS_PER_PAGE };\n if (targetType) params.targetType = targetType;\n if (targetId) params.targetId = targetId;\n if (orderBy) params.orderBy = orderBy;\n return datasetId ? client.listDatasetExperiments(datasetId, params) : client.listExperiments(params);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage, _, lastPageParam) => {\n if (!lastPage?.experiments?.length || !lastPage.pagination?.hasMore) {\n return undefined;\n }\n return lastPageParam + 1;\n },\n select: (data: InfiniteData<ListExperimentsResponse, number>) =>\n data.pages.flatMap(page => page?.experiments ?? []) as TData,\n ...queryOptions,\n });\n\n useEffect(() => {\n if (isEndOfListInView && query.hasNextPage && !query.isFetchingNextPage) {\n void query.fetchNextPage();\n }\n }, [isEndOfListInView, query]);\n\n return { ...query, setEndOfListElement };\n}\n"],"mappings":";;;;;;;AAEA,MAAa,qBAAqB;AAClC,MAAa,sBAAsB;AAkBnC,MAAa,2BAA6C;CACxD,eAAe;CACf,2BAAW,IAAI,IAAI;CACnB,oBAAoB;AACtB;;AAKA,SAAgB,aAAa,OAAmE;CAC9F,MAAM,aAAa,MAAM,WAAW;CACpC,IAAI,eAAA,mCAAmC,OAAO;CAC9C,IAAI,eAAA,oCAAoC,OAAO;AAEjD;AAEA,SAAgB,WACd,aACA,YACA,OACA;CACA,YAAY,eAAe,YAAY,eAAe,KAAK,MAAM;CAEjE,IAAI,MAAM,iBAAiB,MAAM;CACjC,YAAY,iBAAiB,MAAM;CACnC,IAAI,MAAM,UACR,YAAY,UAAU,IAAI,MAAM,SAAS,YAAY,CAAC;MAEtD,YAAY,qBAAqB;AAErC;AAEA,SAAgB,QAAQ,aAAoD;CAE1E,MAAM,WAAW,CAAC,YAAY,sBAAsB,YAAY,UAAU,SAAS;CACnF,OAAO;EACL,aAAa,YAAY;EACzB,cAAc,YAAY;EAC1B,eAAe,WAAW,YAAY,gBAAgB,KAAA;EACtD,UAAU,WAAW,CAAC,GAAG,YAAY,SAAS,CAAC,CAAC,KAAK,KAAA;CACvD;AACF;;AC1CA,MAAMA,qBAAmB;;AAUzB,SAAS,kBAAkB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L_INTERVAL_MS","getOrCreate","useMastraClient","useCombineByIds","useQueries","useMastraClient","useQuery","useMastraClient","useQuery","useMastraClient","useQuery","getOrCreate","useMastraClient","useQuery","keepPreviousData","useMastraClient","useInView","useInfiniteQuery"],"sources":["../src/hooks/experiments/usage-accumulator.ts","../src/hooks/experiments/use-experiment-item-usage.ts","../src/hooks/experiments/use-experiment-metrics.ts","../src/hooks/experiments/use-experiment-trace.ts","../src/hooks/experiments/use-experiments-for-dataset-filter.ts","../src/hooks/experiments/use-experiments-list-metrics.ts","../src/hooks/experiments/use-infinite-experiments.ts"],"sourcesContent":["import type { GetMetricBreakdownResponse } from '@mastra/core/storage';\n\nexport const INPUT_TOKEN_METRIC = 'mastra_model_total_input_tokens';\nexport const OUTPUT_TOKEN_METRIC = 'mastra_model_total_output_tokens';\n\nexport interface ExperimentItemUsage {\n inputTokens?: number;\n outputTokens?: number;\n /** Undefined when no group is priced or when groups use different cost units. */\n estimatedCost?: number;\n costUnit?: string;\n}\n\nexport type UsageAccumulator = {\n inputTokens?: number;\n outputTokens?: number;\n estimatedCost: number;\n costUnits: Set<string>;\n hasUnknownCostUnit: boolean;\n};\n\nexport const createAccumulator = (): UsageAccumulator => ({\n estimatedCost: 0,\n costUnits: new Set(),\n hasUnknownCostUnit: false,\n});\n\ntype BreakdownGroup = GetMetricBreakdownResponse['groups'][number];\n\n/** The token field a breakdown group feeds, or undefined when the group is not a token metric. */\nexport function tokenFieldOf(group: BreakdownGroup): 'inputTokens' | 'outputTokens' | undefined {\n const metricName = group.dimensions.name;\n if (metricName === INPUT_TOKEN_METRIC) return 'inputTokens';\n if (metricName === OUTPUT_TOKEN_METRIC) return 'outputTokens';\n return undefined;\n}\n\nexport function accumulate(\n accumulator: UsageAccumulator,\n tokenField: 'inputTokens' | 'outputTokens',\n group: BreakdownGroup,\n) {\n accumulator[tokenField] = (accumulator[tokenField] ?? 0) + group.value;\n\n if (group.estimatedCost == null) return;\n accumulator.estimatedCost += group.estimatedCost;\n if (group.costUnit) {\n accumulator.costUnits.add(group.costUnit.toLowerCase());\n } else {\n accumulator.hasUnknownCostUnit = true;\n }\n}\n\nexport function toUsage(accumulator: UsageAccumulator): ExperimentItemUsage {\n // A single known unit implies at least one priced group.\n const isPriced = !accumulator.hasUnknownCostUnit && accumulator.costUnits.size === 1;\n return {\n inputTokens: accumulator.inputTokens,\n outputTokens: accumulator.outputTokens,\n estimatedCost: isPriced ? accumulator.estimatedCost : undefined,\n costUnit: isPriced ? [...accumulator.costUnits][0] : undefined,\n };\n}\n","import type { GetMetricBreakdownResponse } from '@mastra/core/storage';\nimport { useQueries } from '@tanstack/react-query';\nimport type { Query } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { ExperimentRef } from '../datasets/use-dataset-experiments';\nimport { useCombineByIds } from '../shared/combine-by-ids';\nimport type { ExperimentQueriesResult } from '../shared/combine-by-ids';\nimport { getOrCreate } from '../shared/map';\nimport {\n INPUT_TOKEN_METRIC,\n OUTPUT_TOKEN_METRIC,\n accumulate,\n createAccumulator,\n tokenFieldOf,\n toUsage,\n} from './usage-accumulator';\nimport type { ExperimentItemUsage, UsageAccumulator } from './usage-accumulator';\n\nexport type { ExperimentItemUsage } from './usage-accumulator';\n\nconst POLL_INTERVAL_MS = 2000;\n\n/** Usage of one experiment: its totals, and each item's usage keyed by the trace id of its run. */\nexport interface ExperimentUsage {\n /** Totals across every item. The cost sums priced groups only. */\n summary: ExperimentItemUsage;\n traces: Record<string, ExperimentItemUsage>;\n}\n\n/** Builds the experiment totals and the per-trace usage in a single pass over the groups. */\nfunction toExperimentUsage(response: GetMetricBreakdownResponse): ExperimentUsage {\n const summary = createAccumulator();\n const accumulators = new Map<string, UsageAccumulator>();\n\n for (const group of response.groups) {\n const tokenField = tokenFieldOf(group);\n if (!tokenField) continue;\n\n accumulate(summary, tokenField, group);\n\n const traceId = group.dimensions.traceId;\n if (traceId) accumulate(getOrCreate(accumulators, traceId, createAccumulator), tokenField, group);\n }\n\n const traces: Record<string, ExperimentItemUsage> = {};\n for (const [traceId, accumulator] of accumulators) {\n traces[traceId] = toUsage(accumulator);\n }\n return { summary: toUsage(summary), traces };\n}\n\n/** How many breakdowns to fetch after completion while the exporter may still be flushing metrics. */\nconst MAX_EMPTY_ATTEMPTS = 5;\n\nconst isEmptyUsage = (usage: ExperimentUsage | undefined) =>\n !usage ||\n (Object.keys(usage.traces).length === 0 &&\n usage.summary.inputTokens === undefined &&\n usage.summary.outputTokens === undefined);\n\n/**\n * Token and cost usage of several experiments, keyed by experiment id: each entry holds the\n * experiment totals (`summary`) and every item's usage keyed by trace id (`traces`).\n * Sends one metric breakdown request per experiment, filtered by its id rather than by trace ids,\n * so it does not wait for the experiment results. Usage is only fetched once an experiment has\n * finished; while the breakdown is still empty (metrics flushing), it retries every 2 seconds up to\n * 5 attempts. No request is made when the observability store cannot serve metrics.\n */\nexport const useExperimentsItemUsage = ({\n experiments,\n supportsMetrics,\n}: {\n experiments: ExperimentRef[];\n supportsMetrics: boolean;\n}): ExperimentQueriesResult<ExperimentUsage> => {\n const client = useMastraClient();\n const combine = useCombineByIds<ExperimentUsage>(experiments.map(experiment => experiment.id));\n\n return useQueries({\n queries: experiments.map(({ id, status }) => {\n const finished = status !== 'running' && status !== 'pending';\n return {\n queryKey: ['experiment-item-usage', id, finished],\n queryFn: async () =>\n toExperimentUsage(\n await client.getMetricBreakdown({\n name: [INPUT_TOKEN_METRIC, OUTPUT_TOKEN_METRIC],\n aggregation: 'sum',\n groupBy: ['traceId', 'name'],\n filters: { experimentId: id },\n }),\n ),\n enabled: supportsMetrics && finished,\n refetchInterval: (query: Query<ExperimentUsage>) =>\n isEmptyUsage(query.state.data) && query.state.dataUpdateCount < MAX_EMPTY_ATTEMPTS ? POLL_INTERVAL_MS : false,\n };\n }),\n combine,\n });\n};\n","import type { DatasetExperiment } from '@mastra/client-js';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nexport interface ExperimentMetrics {\n totalTokens: number | null;\n estimatedCost: number | null;\n costUnit: string | null;\n avgAgentDurationMs: number | null;\n agentRuns: number | null;\n}\n\ninterface UseExperimentMetricsArgs {\n experimentId: string | undefined;\n experimentStatus: DatasetExperiment['status'] | undefined;\n /** Whether the observability store can serve metrics; no requests are made when false. */\n supportsMetrics: boolean;\n queryOptions?: MastraQueryOptions<ExperimentMetrics>;\n}\n\n/**\n * Experiment-scoped metrics (tokens, cost, avg agent latency).\n * Filters only by experimentId — no time window, since the experiment already bounds the row set.\n * Polls every 2 seconds while the experiment is running or pending.\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useExperimentMetrics = ({\n experimentId,\n experimentStatus,\n supportsMetrics,\n queryOptions,\n}: UseExperimentMetricsArgs) => {\n const client = useMastraClient();\n const isEnabled = Boolean(experimentId) && supportsMetrics;\n const isActive = experimentStatus === 'running' || experimentStatus === 'pending';\n\n const query = useQuery({\n queryKey: ['experiment-metrics', experimentId],\n refetchInterval: isActive ? 2000 : false,\n queryFn: async (): Promise<ExperimentMetrics> => {\n // `enabled` already guards this; the check exists to narrow the type.\n if (!experimentId) throw new Error('experimentId is required');\n const filters = { experimentId };\n\n const [tokens, avgDuration, runs] = await Promise.all([\n client.getMetricAggregate({\n name: ['mastra_model_total_input_tokens', 'mastra_model_total_output_tokens'],\n aggregation: 'sum',\n filters,\n }),\n client.getMetricAggregate({ name: ['mastra_agent_duration_ms'], aggregation: 'avg', filters }),\n client.getMetricAggregate({ name: ['mastra_agent_duration_ms'], aggregation: 'count', filters }),\n ]);\n\n return {\n totalTokens: tokens.value ?? null,\n estimatedCost: tokens.estimatedCost ?? null,\n costUnit: tokens.costUnit ?? null,\n avgAgentDurationMs: avgDuration.value ?? null,\n agentRuns: runs.value ?? null,\n };\n },\n ...queryOptions,\n });\n\n return { data: query.data, isLoading: query.isLoading, isEnabled };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\ntype TraceLightResponse = Awaited<ReturnType<MastraClient['getTraceLight']>>;\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useExperimentTrace = <TData = TraceLightResponse>({\n traceId,\n queryOptions,\n}: {\n traceId: string | null | undefined;\n queryOptions?: MastraQueryOptions<TraceLightResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['experiment-trace-light', traceId],\n queryFn: async () => {\n if (!traceId) {\n throw new Error('Trace ID is required');\n }\n return client.getTraceLight(traceId);\n },\n ...queryOptions,\n });\n};\n","import type { ExperimentTargetType, ListExperimentsParams, MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\n/** Explicit page size: server defaults are 20 (global) / 10 (per dataset), which is too small for the list. */\nexport const EXPERIMENTS_PAGE_SIZE = 100;\n\nexport interface ExperimentTargetFilter {\n targetType?: ExperimentTargetType | '';\n targetId?: string;\n}\n\n/**\n * Experiments for the list page: the global list, or the dataset-scoped list when a dataset filter is active.\n * A dataset's runs may not be in the first page of the global list, so filtering client-side is not enough.\n * The optional target filter is applied server-side for the same reason.\n */\ntype ListExperimentsResponse = Awaited<ReturnType<MastraClient['listExperiments']>>;\n\nexport function useExperimentsForDatasetFilter<TData = ListExperimentsResponse>({\n datasetId,\n target,\n queryOptions,\n}: {\n datasetId: string | undefined;\n target?: ExperimentTargetFilter;\n queryOptions?: MastraQueryOptions<ListExperimentsResponse, TData>;\n}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n const params: ListExperimentsParams = { perPage: EXPERIMENTS_PAGE_SIZE };\n if (target?.targetType) params.targetType = target.targetType;\n if (target?.targetId) params.targetId = target.targetId;\n\n return useQuery({\n // Prefixes match the keys invalidated by dataset/experiment mutations.\n queryKey: datasetId ? ['dataset-experiments', datasetId, params] : ['experiments', params],\n queryFn: () => (datasetId ? client.listDatasetExperiments(datasetId, params) : client.listExperiments(params)),\n ...queryOptions,\n });\n}\n","import type { GetMetricBreakdownResponse } from '@mastra/core/storage';\nimport { keepPreviousData, useQuery } from '@tanstack/react-query';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { ExperimentRef } from '../datasets/use-dataset-experiments';\nimport { getOrCreate } from '../shared/map';\nimport {\n INPUT_TOKEN_METRIC,\n OUTPUT_TOKEN_METRIC,\n accumulate,\n createAccumulator,\n tokenFieldOf,\n toUsage,\n} from './usage-accumulator';\nimport type { ExperimentItemUsage, UsageAccumulator } from './usage-accumulator';\n\nconst AGENT_DURATION_METRIC = 'mastra_agent_duration_ms';\n// Each experiment can return two token groups, while the breakdown endpoint allows at most 1,000.\nconst EXPERIMENT_IDS_PER_REQUEST = 500;\nconst POLL_INTERVAL_MS = 5000;\n\n/** Totals of one experiment: token usage, its estimated cost, and the average agent run duration. */\nexport interface ExperimentListMetrics extends ExperimentItemUsage {\n avgDurationMs?: number;\n}\n\nfunction chunk(ids: readonly string[]): string[][] {\n const chunks: string[][] = [];\n for (let index = 0; index < ids.length; index += EXPERIMENT_IDS_PER_REQUEST) {\n chunks.push(ids.slice(index, index + EXPERIMENT_IDS_PER_REQUEST));\n }\n return chunks;\n}\n\nfunction settledValues<T>(results: PromiseSettledResult<T>[]): T[] {\n return results.flatMap(result => (result.status === 'fulfilled' ? [result.value] : []));\n}\n\n/**\n * Builds each requested experiment's metrics. Groups for other experiments are skipped,\n * in case a store ignores the `experimentIds` filter.\n */\nfunction toListMetrics(\n experimentIds: readonly string[],\n tokenResponses: GetMetricBreakdownResponse[],\n durationResponses: GetMetricBreakdownResponse[],\n): Map<string, ExperimentListMetrics> {\n const requested = new Set(experimentIds);\n const accumulators = new Map<string, UsageAccumulator>();\n for (const group of tokenResponses.flatMap(response => response.groups)) {\n const experimentId = group.dimensions.experimentId;\n const tokenField = tokenFieldOf(group);\n if (!experimentId || !requested.has(experimentId) || !tokenField) continue;\n accumulate(getOrCreate(accumulators, experimentId, createAccumulator), tokenField, group);\n }\n\n const metrics = new Map<string, ExperimentListMetrics>();\n for (const [experimentId, accumulator] of accumulators) {\n metrics.set(experimentId, toUsage(accumulator));\n }\n for (const group of durationResponses.flatMap(response => response.groups)) {\n const experimentId = group.dimensions.experimentId;\n if (!experimentId || !requested.has(experimentId)) continue;\n getOrCreate(metrics, experimentId, (): ExperimentListMetrics => ({})).avgDurationMs = group.value;\n }\n return metrics;\n}\n\n/**\n * Token usage, estimated cost and average agent duration of many experiments, keyed by experiment id.\n * Sends two metric breakdowns per 500 experiments (tokens grouped by experiment and metric name,\n * durations grouped by experiment) instead of one request per experiment.\n * Experiments without any metric are absent from the map. Polls while an experiment is running\n * or pending. No request is made when the observability store cannot serve metrics.\n */\nexport const useExperimentsListMetrics = ({\n experiments,\n supportsMetrics,\n}: {\n experiments: ExperimentRef[];\n supportsMetrics: boolean;\n}): UseQueryResult<Map<string, ExperimentListMetrics>, Error> => {\n const client = useMastraClient();\n const experimentIds = [...new Set(experiments.map(experiment => experiment.id))].toSorted();\n const hasActiveExperiment = experiments.some(({ status }) => status === 'running' || status === 'pending');\n\n return useQuery({\n queryKey: ['experiments-list-metrics', experimentIds],\n enabled: supportsMetrics && experimentIds.length > 0,\n queryFn: async () => {\n const batches = chunk(experimentIds);\n const [tokenResults, durationResults] = await Promise.all([\n Promise.allSettled(\n batches.map(batch =>\n client.getMetricBreakdown({\n name: [INPUT_TOKEN_METRIC, OUTPUT_TOKEN_METRIC],\n aggregation: 'sum',\n groupBy: ['experimentId', 'name'],\n filters: { experimentIds: batch },\n limit: batch.length * 2,\n }),\n ),\n ),\n Promise.allSettled(\n batches.map(batch =>\n client.getMetricBreakdown({\n name: [AGENT_DURATION_METRIC],\n aggregation: 'avg',\n groupBy: ['experimentId'],\n filters: { experimentIds: batch },\n limit: batch.length,\n }),\n ),\n ),\n ]);\n return toListMetrics(experimentIds, settledValues(tokenResults), settledValues(durationResults));\n },\n // Loading another page changes the ids; keep the rows already shown filled meanwhile.\n placeholderData: keepPreviousData,\n refetchInterval: hasActiveExperiment ? POLL_INTERVAL_MS : false,\n });\n};\n","import type { DatasetExperiment, ListExperimentsParams, MastraClient } from '@mastra/client-js';\nimport { useInfiniteQuery } from '@tanstack/react-query';\nimport type { InfiniteData, QueryKey, UseInfiniteQueryResult } from '@tanstack/react-query';\nimport { useEffect } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraInfiniteQueryOptions } from '../shared/query-options';\nimport { useInView } from '../shared/use-in-view';\nimport type { ExperimentTargetFilter } from './use-experiments-for-dataset-filter';\n\nexport const EXPERIMENTS_PER_PAGE = 100;\n\n/**\n * Infinite-scroll experiments for the list page: the global list, or the dataset-scoped list when a\n * dataset filter is active (a dataset's runs may not be in the first pages of the global list). The\n * optional target filter is applied server-side for the same reason.\n */\nexport type ExperimentsOrderBy = NonNullable<ListExperimentsParams['orderBy']>;\n\ntype ListExperimentsResponse = Awaited<ReturnType<MastraClient['listExperiments']>>;\n\nexport function useInfiniteExperiments<TData = DatasetExperiment[]>({\n datasetId,\n target,\n orderBy,\n queryOptions,\n}: {\n datasetId: string | undefined;\n target?: ExperimentTargetFilter;\n orderBy?: ExperimentsOrderBy;\n queryOptions?: MastraInfiniteQueryOptions<ListExperimentsResponse, TData, QueryKey, number>;\n}): UseInfiniteQueryResult<TData, Error> & {\n setEndOfListElement: (element: HTMLDivElement | null) => void;\n} {\n const client = useMastraClient();\n const { inView: isEndOfListInView, setRef: setEndOfListElement } = useInView();\n const targetType = target?.targetType || undefined;\n const targetId = target?.targetId || undefined;\n\n const query = useInfiniteQuery({\n // Prefixes match the keys invalidated by dataset/experiment mutations.\n queryKey: datasetId\n ? ['dataset-experiments', datasetId, 'infinite', { targetType, targetId, orderBy }]\n : ['experiments', 'infinite', { targetType, targetId, orderBy }],\n queryFn: ({ pageParam }) => {\n const params: ListExperimentsParams = { page: pageParam, perPage: EXPERIMENTS_PER_PAGE };\n if (targetType) params.targetType = targetType;\n if (targetId) params.targetId = targetId;\n if (orderBy) params.orderBy = orderBy;\n return datasetId ? client.listDatasetExperiments(datasetId, params) : client.listExperiments(params);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage, _, lastPageParam) => {\n if (!lastPage?.experiments?.length || !lastPage.pagination?.hasMore) {\n return undefined;\n }\n return lastPageParam + 1;\n },\n select: (data: InfiniteData<ListExperimentsResponse, number>) =>\n data.pages.flatMap(page => page?.experiments ?? []) as TData,\n ...queryOptions,\n });\n\n useEffect(() => {\n if (isEndOfListInView && query.hasNextPage && !query.isFetchingNextPage) {\n void query.fetchNextPage();\n }\n }, [isEndOfListInView, query]);\n\n return { ...query, setEndOfListElement };\n}\n"],"mappings":";;;;;;;AAEA,MAAa,qBAAqB;AAClC,MAAa,sBAAsB;AAkBnC,MAAa,2BAA6C;CACxD,eAAe;CACf,2BAAW,IAAI,IAAI;CACnB,oBAAoB;AACtB;;AAKA,SAAgB,aAAa,OAAmE;CAC9F,MAAM,aAAa,MAAM,WAAW;CACpC,IAAI,eAAA,mCAAmC,OAAO;CAC9C,IAAI,eAAA,oCAAoC,OAAO;AAEjD;AAEA,SAAgB,WACd,aACA,YACA,OACA;CACA,YAAY,eAAe,YAAY,eAAe,KAAK,MAAM;CAEjE,IAAI,MAAM,iBAAiB,MAAM;CACjC,YAAY,iBAAiB,MAAM;CACnC,IAAI,MAAM,UACR,YAAY,UAAU,IAAI,MAAM,SAAS,YAAY,CAAC;MAEtD,YAAY,qBAAqB;AAErC;AAEA,SAAgB,QAAQ,aAAoD;CAE1E,MAAM,WAAW,CAAC,YAAY,sBAAsB,YAAY,UAAU,SAAS;CACnF,OAAO;EACL,aAAa,YAAY;EACz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qB,MAAM,eAAe,CAAC,MAAM,oBACnD,MAAW,cAAc;CAE7B,GAAG,CAAC,mBAAmB,KAAK,CAAC;CAE7B,OAAO;EAAE,GAAG;EAAO;CAAoB;AACzC"}
@@ -133,6 +133,7 @@ function useAuthCapabilities({ queryOptions } = {}) {
133
133
  queryFn: () => makeAuthCapabilitiesRequest(client),
134
134
  staleTime: 6e4,
135
135
  retry: false,
136
+ placeholderData: _tanstack_react_query.keepPreviousData,
136
137
  ...queryOptions
137
138
  });
138
139
  }
@@ -211,6 +212,7 @@ const usePermissionPatterns = ({ queryOptions } = {}) => {
211
212
  enabled: rbacEnabled,
212
213
  retry: false,
213
214
  staleTime: Infinity,
215
+ placeholderData: _tanstack_react_query.keepPreviousData,
214
216
  ...queryOptions
215
217
  });
216
218
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["useMastraClient","useQuery","useMastraClient","useQuery","useMastraClient","useQuery","useMemo","useMastraClient","useQueryClient","useMutation","useMastraClient","useQueryClient","useMutation","useMastraClient","useMutation","useQueryClient"],"sources":["../../../src/hooks/auth/types.ts","../../../src/hooks/auth/fetch-with-refresh.ts","../../../src/hooks/auth/get-client-query-key.ts","../../../src/hooks/auth/sso-login.ts","../../../src/hooks/auth/use-auth-capabilities.ts","../../../src/hooks/auth/use-current-user.ts","../../../src/hooks/auth/use-permission-patterns.ts","../../../src/hooks/auth/use-credentials-login.ts","../../../src/hooks/auth/use-credentials-signup.ts","../../../src/hooks/auth/use-auth-actions.ts"],"sourcesContent":["/**\n * Auth types for EE authentication in playground-ui.\n *\n * These types mirror the server schemas from @mastra/server.\n */\n\n/**\n * SSO configuration for login\n */\nexport type SSOConfig = {\n provider: string;\n text: string;\n icon?: string;\n description?: string;\n url: string;\n};\n\n/**\n * Login configuration\n */\nexport type LoginConfig = {\n type: 'sso' | 'credentials' | 'both';\n /** Whether sign-up is enabled (defaults to true) */\n signUpEnabled?: boolean;\n /** Optional description explaining the auth requirement and what credentials to use */\n description?: string;\n sso?: SSOConfig;\n} | null;\n\n/**\n * Public capabilities (unauthenticated)\n */\nexport type PublicAuthCapabilities = {\n enabled: boolean;\n login: LoginConfig;\n};\n\n/**\n * Authenticated user information\n */\nexport type AuthenticatedUser = {\n id: string;\n email?: string;\n name?: string;\n avatarUrl?: string;\n};\n\n/**\n * Capability flags\n */\nexport type CapabilityFlags = {\n user: boolean;\n session: boolean;\n sso: boolean;\n rbac: boolean;\n acl: boolean;\n};\n\n/**\n * User access information\n */\nexport type UserAccess = {\n roles: string[];\n permissions: string[];\n} | null;\n\n/**\n * Authenticated capabilities (extends public)\n */\nexport type AuthenticatedCapabilities = PublicAuthCapabilities & {\n user: AuthenticatedUser;\n capabilities: CapabilityFlags;\n access: UserAccess;\n /** Available roles in the system (only present for admin users) */\n availableRoles?: { id: string; name: string }[];\n};\n\n/**\n * Auth capabilities response (union of public and authenticated)\n */\nexport type AuthCapabilities = PublicAuthCapabilities | AuthenticatedCapabilities;\n\n/**\n * Current user response (may be null if not authenticated)\n */\nexport type CurrentUser = {\n id: string;\n email?: string;\n name?: string;\n avatarUrl?: string;\n roles?: string[];\n permissions?: string[];\n} | null;\n\n/**\n * SSO callback response\n */\nexport type SSOCallbackResponse = {\n success: boolean;\n user?: AuthenticatedUser;\n redirectTo?: string;\n};\n\n/**\n * Logout response\n */\nexport type LogoutResponse = {\n success: boolean;\n redirectTo?: string;\n};\n\n/**\n * Type guard to check if capabilities include authenticated user\n */\nexport function isAuthenticated(capabilities: AuthCapabilities): capabilities is AuthenticatedCapabilities {\n return 'user' in capabilities && capabilities.user !== undefined;\n}\n","/**\n * Fetch wrapper for the Mastra server API.\n *\n * ⚠️ MIRRORS: `platform/frontend/src/shared/lib/fetch-with-refresh.ts`\n *\n * Both files must stay behaviourally in lockstep — the platform dashboard and\n * the embedded playground both talk to WorkOS-backed auth and both would be\n * vulnerable to the same 429 lockout loop if either regressed. If you change\n * one, change the other in the same PR (or extract to a shared package —\n * currently blocked by the platform/mastra-ai monorepo boundary).\n *\n * ---\n *\n * The server middleware already refreshes the WorkOS session transparently\n * on every protected request. There is no scenario where the client can\n * succeed by calling /auth/refresh after a 401 — that endpoint hits the\n * same broken WorkOS with the same session and would only amplify transient\n * failures into forced logout (PLTFRM-1270).\n *\n * These are pass-throughs today. The names and signatures are preserved for\n * compatibility with existing call sites (`App.tsx`, `use-current-user.ts`).\n * Transient-failure retry belongs one level up — in React Query's `retry`\n * config on individual queries — not in a fetch wrapper that would compound\n * with the query-level retry.\n */\n\nexport async function fetchWithRefresh(\n _baseUrl: string,\n input: RequestInfo | URL,\n init?: RequestInit,\n): Promise<Response> {\n return fetch(input, init);\n}\n\nexport function createFetchWithRefresh(_baseUrl?: string, _apiPrefix?: string): typeof fetch {\n return (input, init) => fetch(input, init);\n}\n","import type { MastraClient } from '@mastra/client-js';\n\nconst clientQueryKeys = new WeakMap<MastraClient, number>();\nlet nextClientQueryKey = 0;\n\n/**\n * Returns a stable, non-sensitive query key for a Mastra client instance.\n * A new client is created whenever its connection options change.\n */\nexport function getClientQueryKey(client: MastraClient) {\n const existingKey = clientQueryKeys.get(client);\n if (existingKey !== undefined) return existingKey;\n\n const queryKey = nextClientQueryKey++;\n clientQueryKeys.set(client, queryKey);\n return queryKey;\n}\n","import type { MastraClient } from '@mastra/client-js';\n\nexport type SSOLoginResponse = {\n url: string;\n};\n\nexport async function makeSSOLoginRequest(\n client: Pick<MastraClient, 'options'>,\n { redirectUri }: { redirectUri?: string },\n): Promise<SSOLoginResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const params = new URLSearchParams();\n if (redirectUri) {\n params.set('redirect_uri', redirectUri);\n }\n\n const url = `${baseUrl}${prefix}/auth/sso/login${params.toString() ? `?${params}` : ''}`;\n\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to initiate SSO login: ${response.status}`);\n }\n\n return response.json();\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { getClientQueryKey } from './get-client-query-key';\nimport type { AuthCapabilities } from './types';\n\n/**\n * Makes a request to the auth capabilities endpoint.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeAuthCapabilitiesRequest(client: MastraClient): Promise<AuthCapabilities> {\n const { baseUrl = '', headers: clientHeaders = {}, apiPrefix } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const response = await fetch(`${baseUrl}${prefix}/auth/capabilities`, {\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch auth capabilities: ${response.status}`);\n }\n\n return response.json();\n}\n\n/**\n * Hook to fetch authentication capabilities.\n *\n * Returns server-authoritative capability detection including:\n * - Whether auth is enabled\n * - Login configuration (SSO, credentials, or both)\n * - Current user (if authenticated)\n * - Available capabilities (user awareness, session, SSO, RBAC, ACL, audit)\n * - User access (roles and permissions)\n *\n * @example\n * ```tsx\n * import { useAuthCapabilities } from '@mastra/react/hooks/auth';\n *\n * function AuthStatus() {\n * const { data: capabilities, isLoading } = useAuthCapabilities();\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (!capabilities?.enabled) return <div>Auth not enabled</div>;\n *\n * if (isAuthenticated(capabilities)) {\n * return <div>Welcome, {capabilities.user.name}</div>;\n * }\n *\n * return <LoginButton config={capabilities.login} />;\n * }\n * ```\n */\nexport function useAuthCapabilities<TData = AuthCapabilities>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<AuthCapabilities, TData> } = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery<AuthCapabilities, Error, TData>({\n queryKey: ['auth', 'capabilities', getClientQueryKey(client)],\n queryFn: () => makeAuthCapabilitiesRequest(client),\n staleTime: 60 * 1000, // Cache for 1 minute\n retry: false, // Don't retry auth requests\n ...queryOptions,\n });\n}\n","import type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { fetchWithRefresh } from './fetch-with-refresh';\nimport type { CurrentUser } from './types';\n\nconst AUTH_TRANSIENT_MAX_RETRIES = 3;\nconst AUTH_TRANSIENT_MAX_BACKOFF_MS = 8_000;\n\nexport class CurrentUserError extends Error {\n constructor(public readonly status: number) {\n super(`Failed to fetch current user: ${status}`);\n this.name = 'CurrentUserError';\n }\n}\n\nexport function isUnauthenticatedError(error: unknown): boolean {\n return error instanceof CurrentUserError && error.status === 401;\n}\n\n/**\n * Hook to fetch the current authenticated user.\n *\n * Returns the current user if authenticated, null otherwise.\n * Includes roles and permissions if RBAC is available.\n *\n * Uses fetchWithRefresh to automatically refresh the session on 401 errors,\n * preventing users from being logged out when the access token expires.\n *\n * @example\n * ```tsx\n * import { useCurrentUser } from '@mastra/react/hooks/auth';\n *\n * function UserMenu() {\n * const { data: user, isLoading } = useCurrentUser();\n *\n * if (isLoading) return <Skeleton />;\n * if (!user) return <LoginButton />;\n *\n * return (\n * <Menu>\n * <Avatar src={user.avatarUrl} />\n * <span>{user.name || user.email}</span>\n * </Menu>\n * );\n * }\n * ```\n */\nexport function useCurrentUser<TData = CurrentUser>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<CurrentUser, TData> } = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n const baseUrl = client.options?.baseUrl || '';\n\n return useQuery<CurrentUser, Error, TData>({\n queryKey: ['auth', 'me'],\n queryFn: async () => {\n const response = await fetchWithRefresh(baseUrl, `${baseUrl}/api/auth/me`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new CurrentUserError(response.status);\n }\n\n return response.json();\n },\n staleTime: 60 * 1000, // Cache for 1 minute\n // Retry the /api/auth/me query on transient auth-provider failures (HTTP 503)\n // so the UI stays in `isLoading` instead of flipping to `isError` and\n // triggering login — that redirect is what fed the WorkOS 429 lockout loop\n // (PLTFRM-1270). 401 (terminal) still fails fast.\n retry: (failureCount, error) => {\n if (!(error instanceof CurrentUserError)) return false;\n if (error.status !== 503) return false;\n return failureCount < AUTH_TRANSIENT_MAX_RETRIES;\n },\n retryDelay: attemptIndex => Math.min(AUTH_TRANSIENT_MAX_BACKOFF_MS, 500 * 2 ** attemptIndex),\n ...queryOptions,\n });\n}\n","import type { MastraClient, PermissionPattern } from '@mastra/client-js';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { getClientQueryKey } from './get-client-query-key';\nimport { isAuthenticated } from './types';\nimport { useAuthCapabilities } from './use-auth-capabilities';\n\n/**\n * Fetches the authoritative set of permission patterns from the server\n * (`GET /auth/permission-patterns`).\n *\n * The server owns the permission source of truth (generated from the route\n * registry), so the browser never imports the server-only `@mastra/core/auth/ee`\n * code just to validate hardcoded route-permission literals.\n *\n * The request only fires when RBAC is actually enabled — when auth is off or\n * RBAC isn't configured, route gating is a no-op so the pattern vocabulary is\n * not needed, and we avoid an unnecessary (and potentially 403/401) call.\n */\ntype PermissionPatternsResponse = Awaited<ReturnType<MastraClient['getPermissionPatterns']>>;\n\nexport const usePermissionPatterns = ({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<PermissionPatternsResponse> } = {}) => {\n const client = useMastraClient();\n const { data: capabilities, isLoading: capabilitiesLoading, error: capabilitiesError } = useAuthCapabilities();\n\n const rbacEnabled = !!(capabilities && isAuthenticated(capabilities) && capabilities.capabilities.rbac);\n\n const { data, isLoading, error } = useQuery({\n queryKey: ['permission-patterns', getClientQueryKey(client)],\n queryFn: () => client.getPermissionPatterns(),\n // Only fetch the pattern vocabulary when RBAC gating is in effect.\n enabled: rbacEnabled,\n // The endpoint requires auth; on 403/401 we don't want React Query to\n // thrash with retries (which toggles isLoading and re-triggers redirect\n // guards). One attempt is enough — gating falls back to the user's\n // permissions if the pattern set is empty.\n retry: false,\n staleTime: Infinity,\n ...queryOptions,\n });\n\n const patterns = useMemo(() => new Set<PermissionPattern>(data?.patterns ?? []), [data]);\n\n // While capabilities are resolving we don't yet know whether RBAC applies, so\n // report loading. Once RBAC is ruled out, this hook is never \"loading\".\n return { patterns, isLoading: capabilitiesLoading || (rbacEnabled && isLoading), error: capabilitiesError || error };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nexport type CredentialsLoginRequest = {\n email: string;\n password: string;\n};\n\nexport type CredentialsLoginResponse = {\n user?: {\n id: string;\n email: string;\n name?: string;\n };\n error?: string;\n};\n\n/**\n * Hook to login with email/password credentials.\n *\n * Uses Better Auth's email sign-in endpoint.\n *\n * @example\n * ```tsx\n * import { useCredentialsLogin } from '@mastra/react/hooks/auth';\n *\n * function LoginForm() {\n * const { mutate: login, isPending, error } = useCredentialsLogin();\n *\n * const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n * e.preventDefault();\n * const formData = new FormData(e.currentTarget);\n * login({\n * email: formData.get('email') as string,\n * password: formData.get('password') as string,\n * }, {\n * onSuccess: () => {\n * window.location.href = '/';\n * },\n * });\n * };\n *\n * return (\n * <form onSubmit={handleSubmit}>\n * <input name=\"email\" type=\"email\" required />\n * <input name=\"password\" type=\"password\" required />\n * <button type=\"submit\" disabled={isPending}>\n * Sign in\n * </button>\n * {error && <p>{error.message}</p>}\n * </form>\n * );\n * }\n * ```\n */\n/**\n * Makes a credentials sign-in request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeCredentialsLoginRequest(\n client: MastraClient,\n { email, password }: CredentialsLoginRequest,\n): Promise<CredentialsLoginResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options || {};\n const raw = (apiPrefix ?? '/api').trim();\n const normalized = raw === '' ? '' : raw.startsWith('/') ? raw : `/${raw}`;\n const prefix = normalized.replace(/\\/+$/, '');\n\n // Generic Mastra auth endpoint - works with any credentials provider\n const response = await fetch(`${baseUrl}${prefix}/auth/credentials/sign-in`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ email, password }),\n });\n\n const data = await response.json();\n\n if (!response.ok) {\n throw new Error(data.message || data.error || 'Invalid email or password');\n }\n\n return data;\n}\n\nexport function useCredentialsLogin({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<CredentialsLoginResponse, CredentialsLoginRequest> } = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<CredentialsLoginResponse, Error, CredentialsLoginRequest>({\n mutationFn: ({ email, password }) => makeCredentialsLoginRequest(client, { email, password }),\n onSuccess: () => {\n // Invalidate auth queries to refetch user state\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nexport type CredentialsSignUpRequest = {\n email: string;\n password: string;\n name?: string;\n};\n\nexport type CredentialsSignUpResponse = {\n user?: {\n id: string;\n email: string;\n name?: string;\n };\n error?: string;\n};\n\n/**\n * Hook to sign up with email/password credentials.\n *\n * Uses Better Auth's email sign-up endpoint.\n *\n * @example\n * ```tsx\n * import { useCredentialsSignUp } from '@mastra/react/hooks/auth';\n *\n * function SignUpForm() {\n * const { mutate: signUp, isPending, error } = useCredentialsSignUp();\n *\n * const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n * e.preventDefault();\n * const formData = new FormData(e.currentTarget);\n * signUp({\n * email: formData.get('email') as string,\n * password: formData.get('password') as string,\n * name: formData.get('name') as string,\n * }, {\n * onSuccess: () => {\n * window.location.href = '/';\n * },\n * });\n * };\n *\n * return (\n * <form onSubmit={handleSubmit}>\n * <input name=\"name\" type=\"text\" />\n * <input name=\"email\" type=\"email\" required />\n * <input name=\"password\" type=\"password\" required />\n * <button type=\"submit\" disabled={isPending}>\n * Sign up\n * </button>\n * {error && <p>{error.message}</p>}\n * </form>\n * );\n * }\n * ```\n */\n/**\n * Makes a credentials sign-up request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeCredentialsSignUpRequest(\n client: MastraClient,\n { email, password, name }: CredentialsSignUpRequest,\n): Promise<CredentialsSignUpResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options || {};\n const raw = (apiPrefix ?? '/api').trim();\n const normalized = raw === '' ? '' : raw.startsWith('/') ? raw : `/${raw}`;\n const prefix = normalized.replace(/\\/+$/, '');\n\n // Generic Mastra auth endpoint - works with any credentials provider\n const response = await fetch(`${baseUrl}${prefix}/auth/credentials/sign-up`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ email, password, name }),\n });\n\n const data = await response.json();\n\n if (!response.ok) {\n throw new Error(data.message || data.error || 'Failed to create account');\n }\n\n return data;\n}\n\nexport function useCredentialsSignUp({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<CredentialsSignUpResponse, CredentialsSignUpRequest> } = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<CredentialsSignUpResponse, Error, CredentialsSignUpRequest>({\n mutationFn: ({ email, password, name }) => makeCredentialsSignUpRequest(client, { email, password, name }),\n onSuccess: () => {\n // Invalidate auth queries to refetch user state\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nimport { makeSSOLoginRequest } from './sso-login';\nimport type { LogoutResponse } from './types';\n\n/**\n * Hook to initiate SSO login.\n *\n * Returns mutation to get the SSO login URL and redirect.\n *\n * @example\n * ```tsx\n * import { useSSOLogin } from '@mastra/react/hooks/auth';\n *\n * function SSOLoginButton() {\n * const { mutate: login, isPending } = useSSOLogin();\n *\n * const handleClick = () => {\n * login({ redirectUri: window.location.href }, {\n * onSuccess: (data) => {\n * window.location.href = data.url;\n * },\n * });\n * };\n *\n * return (\n * <button onClick={handleClick} disabled={isPending}>\n * Sign in with SSO\n * </button>\n * );\n * }\n * ```\n */\ntype SSOLoginResponse = Awaited<ReturnType<typeof makeSSOLoginRequest>>;\n\nexport function useSSOLogin({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<SSOLoginResponse, { redirectUri?: string }> } = {}) {\n const client = useMastraClient();\n\n return useMutation({\n mutationFn: ({ redirectUri }: { redirectUri?: string }) => makeSSOLoginRequest(client, { redirectUri }),\n ...queryOptions,\n });\n}\n\n/**\n * Hook to logout the current user.\n *\n * Destroys the current session and optionally redirects to\n * the SSO logout URL if available.\n *\n * @example\n * ```tsx\n * import { useLogout } from '@mastra/react/hooks/auth';\n *\n * function LogoutButton({ userId }: { userId: string }) {\n * const { mutate: logout, isPending } = useLogout();\n * const queryClient = useQueryClient();\n *\n * const handleLogout = () => {\n * logout({ userId }, {\n * onSuccess: (data) => {\n * queryClient.invalidateQueries({ queryKey: ['auth'] });\n * if (data.redirectTo) {\n * window.location.href = data.redirectTo;\n * } else {\n * window.location.reload();\n * }\n * },\n * });\n * };\n *\n * return (\n * <button onClick={handleLogout} disabled={isPending}>\n * Sign out\n * </button>\n * );\n * }\n * ```\n */\n/**\n * Makes a logout request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeLogoutRequest(client: Pick<MastraClient, 'options'>): Promise<LogoutResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const response = await fetch(`${baseUrl}${prefix}/auth/logout`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to logout: ${response.status}`);\n }\n\n return response.json();\n}\n\nexport interface UseLogoutOptions {\n /**\n * Runs once the server has ended the session, before the mutation resolves.\n * Failures are ignored so cleanup never turns a completed sign-out into an error.\n */\n onLoggedOut?: (variables: { userId: string }) => Promise<void>;\n queryOptions?: MastraMutationOptions<LogoutResponse, { userId: string }>;\n}\n\nexport function useLogout({ onLoggedOut, queryOptions }: UseLogoutOptions = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<LogoutResponse, Error, { userId: string }>({\n mutationFn: async variables => {\n const response = await makeLogoutRequest(client);\n await onLoggedOut?.(variables).catch(() => {});\n return response;\n },\n onSuccess: () => {\n // Invalidate all auth-related queries\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n"],"mappings":";;;;;;;;AAkHA,SAAgB,gBAAgB,cAA2E;CACzG,OAAO,UAAU,gBAAgB,aAAa,SAAS,KAAA;AACzD;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1FA,eAAsB,iBACpB,UACA,OACA,MACmB;CACnB,OAAO,MAAM,OAAO,IAAI;AAC1B;AAEA,SAAgB,uBAAuB,UAAmB,YAAmC;CAC3F,QAAQ,OAAO,SAAS,MAAM,OAAO,IAAI;AAC3C;;AClCA,MAAM,kCAAkB,IAAI,QAA8B;AAC1D,IAAI,qBAAqB;;;;;AAMzB,SAAgB,kB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ACA,GAAG;CACL,CAAC;AACH"}
1
+ {"version":3,"file":"index.cjs","names":["useMastraClient","useQuery","keepPreviousData","useMastraClient","useQuery","useMastraClient","useQuery","keepPreviousData","useMemo","useMastraClient","useQueryClient","useMutation","useMastraClient","useQueryClient","useMutation","useMastraClient","useMutation","useQueryClient"],"sources":["../../../src/hooks/auth/types.ts","../../../src/hooks/auth/fetch-with-refresh.ts","../../../src/hooks/auth/get-client-query-key.ts","../../../src/hooks/auth/sso-login.ts","../../../src/hooks/auth/use-auth-capabilities.ts","../../../src/hooks/auth/use-current-user.ts","../../../src/hooks/auth/use-permission-patterns.ts","../../../src/hooks/auth/use-credentials-login.ts","../../../src/hooks/auth/use-credentials-signup.ts","../../../src/hooks/auth/use-auth-actions.ts"],"sourcesContent":["/**\n * Auth types for EE authentication in playground-ui.\n *\n * These types mirror the server schemas from @mastra/server.\n */\n\n/**\n * SSO configuration for login\n */\nexport type SSOConfig = {\n provider: string;\n text: string;\n icon?: string;\n description?: string;\n url: string;\n};\n\n/**\n * Login configuration\n */\nexport type LoginConfig = {\n type: 'sso' | 'credentials' | 'both';\n /** Whether sign-up is enabled (defaults to true) */\n signUpEnabled?: boolean;\n /** Optional description explaining the auth requirement and what credentials to use */\n description?: string;\n sso?: SSOConfig;\n} | null;\n\n/**\n * Public capabilities (unauthenticated)\n */\nexport type PublicAuthCapabilities = {\n enabled: boolean;\n login: LoginConfig;\n};\n\n/**\n * Authenticated user information\n */\nexport type AuthenticatedUser = {\n id: string;\n email?: string;\n name?: string;\n avatarUrl?: string;\n};\n\n/**\n * Capability flags\n */\nexport type CapabilityFlags = {\n user: boolean;\n session: boolean;\n sso: boolean;\n rbac: boolean;\n acl: boolean;\n};\n\n/**\n * User access information\n */\nexport type UserAccess = {\n roles: string[];\n permissions: string[];\n} | null;\n\n/**\n * Authenticated capabilities (extends public)\n */\nexport type AuthenticatedCapabilities = PublicAuthCapabilities & {\n user: AuthenticatedUser;\n capabilities: CapabilityFlags;\n access: UserAccess;\n /** Available roles in the system (only present for admin users) */\n availableRoles?: { id: string; name: string }[];\n};\n\n/**\n * Auth capabilities response (union of public and authenticated)\n */\nexport type AuthCapabilities = PublicAuthCapabilities | AuthenticatedCapabilities;\n\n/**\n * Current user response (may be null if not authenticated)\n */\nexport type CurrentUser = {\n id: string;\n email?: string;\n name?: string;\n avatarUrl?: string;\n roles?: string[];\n permissions?: string[];\n} | null;\n\n/**\n * SSO callback response\n */\nexport type SSOCallbackResponse = {\n success: boolean;\n user?: AuthenticatedUser;\n redirectTo?: string;\n};\n\n/**\n * Logout response\n */\nexport type LogoutResponse = {\n success: boolean;\n redirectTo?: string;\n};\n\n/**\n * Type guard to check if capabilities include authenticated user\n */\nexport function isAuthenticated(capabilities: AuthCapabilities): capabilities is AuthenticatedCapabilities {\n return 'user' in capabilities && capabilities.user !== undefined;\n}\n","/**\n * Fetch wrapper for the Mastra server API.\n *\n * ⚠️ MIRRORS: `platform/frontend/src/shared/lib/fetch-with-refresh.ts`\n *\n * Both files must stay behaviourally in lockstep — the platform dashboard and\n * the embedded playground both talk to WorkOS-backed auth and both would be\n * vulnerable to the same 429 lockout loop if either regressed. If you change\n * one, change the other in the same PR (or extract to a shared package —\n * currently blocked by the platform/mastra-ai monorepo boundary).\n *\n * ---\n *\n * The server middleware already refreshes the WorkOS session transparently\n * on every protected request. There is no scenario where the client can\n * succeed by calling /auth/refresh after a 401 — that endpoint hits the\n * same broken WorkOS with the same session and would only amplify transient\n * failures into forced logout (PLTFRM-1270).\n *\n * These are pass-throughs today. The names and signatures are preserved for\n * compatibility with existing call sites (`App.tsx`, `use-current-user.ts`).\n * Transient-failure retry belongs one level up — in React Query's `retry`\n * config on individual queries — not in a fetch wrapper that would compound\n * with the query-level retry.\n */\n\nexport async function fetchWithRefresh(\n _baseUrl: string,\n input: RequestInfo | URL,\n init?: RequestInit,\n): Promise<Response> {\n return fetch(input, init);\n}\n\nexport function createFetchWithRefresh(_baseUrl?: string, _apiPrefix?: string): typeof fetch {\n return (input, init) => fetch(input, init);\n}\n","import type { MastraClient } from '@mastra/client-js';\n\nconst clientQueryKeys = new WeakMap<MastraClient, number>();\nlet nextClientQueryKey = 0;\n\n/**\n * Returns a stable, non-sensitive query key for a Mastra client instance.\n * A new client is created whenever its connection options change.\n */\nexport function getClientQueryKey(client: MastraClient) {\n const existingKey = clientQueryKeys.get(client);\n if (existingKey !== undefined) return existingKey;\n\n const queryKey = nextClientQueryKey++;\n clientQueryKeys.set(client, queryKey);\n return queryKey;\n}\n","import type { MastraClient } from '@mastra/client-js';\n\nexport type SSOLoginResponse = {\n url: string;\n};\n\nexport async function makeSSOLoginRequest(\n client: Pick<MastraClient, 'options'>,\n { redirectUri }: { redirectUri?: string },\n): Promise<SSOLoginResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const params = new URLSearchParams();\n if (redirectUri) {\n params.set('redirect_uri', redirectUri);\n }\n\n const url = `${baseUrl}${prefix}/auth/sso/login${params.toString() ? `?${params}` : ''}`;\n\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to initiate SSO login: ${response.status}`);\n }\n\n return response.json();\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { keepPreviousData, useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { getClientQueryKey } from './get-client-query-key';\nimport type { AuthCapabilities } from './types';\n\n/**\n * Makes a request to the auth capabilities endpoint.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeAuthCapabilitiesRequest(client: MastraClient): Promise<AuthCapabilities> {\n const { baseUrl = '', headers: clientHeaders = {}, apiPrefix } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const response = await fetch(`${baseUrl}${prefix}/auth/capabilities`, {\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch auth capabilities: ${response.status}`);\n }\n\n return response.json();\n}\n\n/**\n * Hook to fetch authentication capabilities.\n *\n * Returns server-authoritative capability detection including:\n * - Whether auth is enabled\n * - Login configuration (SSO, credentials, or both)\n * - Current user (if authenticated)\n * - Available capabilities (user awareness, session, SSO, RBAC, ACL, audit)\n * - User access (roles and permissions)\n *\n * @example\n * ```tsx\n * import { useAuthCapabilities } from '@mastra/react/hooks/auth';\n *\n * function AuthStatus() {\n * const { data: capabilities, isLoading } = useAuthCapabilities();\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (!capabilities?.enabled) return <div>Auth not enabled</div>;\n *\n * if (isAuthenticated(capabilities)) {\n * return <div>Welcome, {capabilities.user.name}</div>;\n * }\n *\n * return <LoginButton config={capabilities.login} />;\n * }\n * ```\n */\nexport function useAuthCapabilities<TData = AuthCapabilities>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<AuthCapabilities, TData> } = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery<AuthCapabilities, Error, TData>({\n queryKey: ['auth', 'capabilities', getClientQueryKey(client)],\n queryFn: () => makeAuthCapabilitiesRequest(client),\n staleTime: 60 * 1000, // Cache for 1 minute\n retry: false, // Don't retry auth requests\n // A changed connection (Settings) makes a new client and so a new key. Keep the last answer while the\n // new one loads, so guards keep the page up instead of blanking it on every save.\n placeholderData: keepPreviousData,\n ...queryOptions,\n });\n}\n","import type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { fetchWithRefresh } from './fetch-with-refresh';\nimport type { CurrentUser } from './types';\n\nconst AUTH_TRANSIENT_MAX_RETRIES = 3;\nconst AUTH_TRANSIENT_MAX_BACKOFF_MS = 8_000;\n\nexport class CurrentUserError extends Error {\n constructor(public readonly status: number) {\n super(`Failed to fetch current user: ${status}`);\n this.name = 'CurrentUserError';\n }\n}\n\nexport function isUnauthenticatedError(error: unknown): boolean {\n return error instanceof CurrentUserError && error.status === 401;\n}\n\n/**\n * Hook to fetch the current authenticated user.\n *\n * Returns the current user if authenticated, null otherwise.\n * Includes roles and permissions if RBAC is available.\n *\n * Uses fetchWithRefresh to automatically refresh the session on 401 errors,\n * preventing users from being logged out when the access token expires.\n *\n * @example\n * ```tsx\n * import { useCurrentUser } from '@mastra/react/hooks/auth';\n *\n * function UserMenu() {\n * const { data: user, isLoading } = useCurrentUser();\n *\n * if (isLoading) return <Skeleton />;\n * if (!user) return <LoginButton />;\n *\n * return (\n * <Menu>\n * <Avatar src={user.avatarUrl} />\n * <span>{user.name || user.email}</span>\n * </Menu>\n * );\n * }\n * ```\n */\nexport function useCurrentUser<TData = CurrentUser>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<CurrentUser, TData> } = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n const baseUrl = client.options?.baseUrl || '';\n\n return useQuery<CurrentUser, Error, TData>({\n queryKey: ['auth', 'me'],\n queryFn: async () => {\n const response = await fetchWithRefresh(baseUrl, `${baseUrl}/api/auth/me`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new CurrentUserError(response.status);\n }\n\n return response.json();\n },\n staleTime: 60 * 1000, // Cache for 1 minute\n // Retry the /api/auth/me query on transient auth-provider failures (HTTP 503)\n // so the UI stays in `isLoading` instead of flipping to `isError` and\n // triggering login — that redirect is what fed the WorkOS 429 lockout loop\n // (PLTFRM-1270). 401 (terminal) still fails fast.\n retry: (failureCount, error) => {\n if (!(error instanceof CurrentUserError)) return false;\n if (error.status !== 503) return false;\n return failureCount < AUTH_TRANSIENT_MAX_RETRIES;\n },\n retryDelay: attemptIndex => Math.min(AUTH_TRANSIENT_MAX_BACKOFF_MS, 500 * 2 ** attemptIndex),\n ...queryOptions,\n });\n}\n","import type { MastraClient, PermissionPattern } from '@mastra/client-js';\nimport { keepPreviousData, useQuery } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { getClientQueryKey } from './get-client-query-key';\nimport { isAuthenticated } from './types';\nimport { useAuthCapabilities } from './use-auth-capabilities';\n\n/**\n * Fetches the authoritative set of permission patterns from the server\n * (`GET /auth/permission-patterns`).\n *\n * The server owns the permission source of truth (generated from the route\n * registry), so the browser never imports the server-only `@mastra/core/auth/ee`\n * code just to validate hardcoded route-permission literals.\n *\n * The request only fires when RBAC is actually enabled — when auth is off or\n * RBAC isn't configured, route gating is a no-op so the pattern vocabulary is\n * not needed, and we avoid an unnecessary (and potentially 403/401) call.\n */\ntype PermissionPatternsResponse = Awaited<ReturnType<MastraClient['getPermissionPatterns']>>;\n\nexport const usePermissionPatterns = ({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<PermissionPatternsResponse> } = {}) => {\n const client = useMastraClient();\n const { data: capabilities, isLoading: capabilitiesLoading, error: capabilitiesError } = useAuthCapabilities();\n\n const rbacEnabled = !!(capabilities && isAuthenticated(capabilities) && capabilities.capabilities.rbac);\n\n const { data, isLoading, error } = useQuery({\n queryKey: ['permission-patterns', getClientQueryKey(client)],\n queryFn: () => client.getPermissionPatterns(),\n // Only fetch the pattern vocabulary when RBAC gating is in effect.\n enabled: rbacEnabled,\n // The endpoint requires auth; on 403/401 we don't want React Query to\n // thrash with retries (which toggles isLoading and re-triggers redirect\n // guards). One attempt is enough — gating falls back to the user's\n // permissions if the pattern set is empty.\n retry: false,\n staleTime: Infinity,\n // A changed connection (Settings) makes a new client and so a new key. Keep the last answer while the\n // new one loads, so guards keep the page up instead of blanking it on every save.\n placeholderData: keepPreviousData,\n ...queryOptions,\n });\n\n const patterns = useMemo(() => new Set<PermissionPattern>(data?.patterns ?? []), [data]);\n\n // While capabilities are resolving we don't yet know whether RBAC applies, so\n // report loading. Once RBAC is ruled out, this hook is never \"loading\".\n return { patterns, isLoading: capabilitiesLoading || (rbacEnabled && isLoading), error: capabilitiesError || error };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nexport type CredentialsLoginRequest = {\n email: string;\n password: string;\n};\n\nexport type CredentialsLoginResponse = {\n user?: {\n id: string;\n email: string;\n name?: string;\n };\n error?: string;\n};\n\n/**\n * Hook to login with email/password credentials.\n *\n * Uses Better Auth's email sign-in endpoint.\n *\n * @example\n * ```tsx\n * import { useCredentialsLogin } from '@mastra/react/hooks/auth';\n *\n * function LoginForm() {\n * const { mutate: login, isPending, error } = useCredentialsLogin();\n *\n * const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n * e.preventDefault();\n * const formData = new FormData(e.currentTarget);\n * login({\n * email: formData.get('email') as string,\n * password: formData.get('password') as string,\n * }, {\n * onSuccess: () => {\n * window.location.href = '/';\n * },\n * });\n * };\n *\n * return (\n * <form onSubmit={handleSubmit}>\n * <input name=\"email\" type=\"email\" required />\n * <input name=\"password\" type=\"password\" required />\n * <button type=\"submit\" disabled={isPending}>\n * Sign in\n * </button>\n * {error && <p>{error.message}</p>}\n * </form>\n * );\n * }\n * ```\n */\n/**\n * Makes a credentials sign-in request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeCredentialsLoginRequest(\n client: MastraClient,\n { email, password }: CredentialsLoginRequest,\n): Promise<CredentialsLoginResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options || {};\n const raw = (apiPrefix ?? '/api').trim();\n const normalized = raw === '' ? '' : raw.startsWith('/') ? raw : `/${raw}`;\n const prefix = normalized.replace(/\\/+$/, '');\n\n // Generic Mastra auth endpoint - works with any credentials provider\n const response = await fetch(`${baseUrl}${prefix}/auth/credentials/sign-in`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ email, password }),\n });\n\n const data = await response.json();\n\n if (!response.ok) {\n throw new Error(data.message || data.error || 'Invalid email or password');\n }\n\n return data;\n}\n\nexport function useCredentialsLogin({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<CredentialsLoginResponse, CredentialsLoginRequest> } = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<CredentialsLoginResponse, Error, CredentialsLoginRequest>({\n mutationFn: ({ email, password }) => makeCredentialsLoginRequest(client, { email, password }),\n onSuccess: () => {\n // Invalidate auth queries to refetch user state\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nexport type CredentialsSignUpRequest = {\n email: string;\n password: string;\n name?: string;\n};\n\nexport type CredentialsSignUpResponse = {\n user?: {\n id: string;\n email: string;\n name?: string;\n };\n error?: string;\n};\n\n/**\n * Hook to sign up with email/password credentials.\n *\n * Uses Better Auth's email sign-up endpoint.\n *\n * @example\n * ```tsx\n * import { useCredentialsSignUp } from '@mastra/react/hooks/auth';\n *\n * function SignUpForm() {\n * const { mutate: signUp, isPending, error } = useCredentialsSignUp();\n *\n * const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n * e.preventDefault();\n * const formData = new FormData(e.currentTarget);\n * signUp({\n * email: formData.get('email') as string,\n * password: formData.get('password') as string,\n * name: formData.get('name') as string,\n * }, {\n * onSuccess: () => {\n * window.location.href = '/';\n * },\n * });\n * };\n *\n * return (\n * <form onSubmit={handleSubmit}>\n * <input name=\"name\" type=\"text\" />\n * <input name=\"email\" type=\"email\" required />\n * <input name=\"password\" type=\"password\" required />\n * <button type=\"submit\" disabled={isPending}>\n * Sign up\n * </button>\n * {error && <p>{error.message}</p>}\n * </form>\n * );\n * }\n * ```\n */\n/**\n * Makes a credentials sign-up request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeCredentialsSignUpRequest(\n client: MastraClient,\n { email, password, name }: CredentialsSignUpRequest,\n): Promise<CredentialsSignUpResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options || {};\n const raw = (apiPrefix ?? '/api').trim();\n const normalized = raw === '' ? '' : raw.startsWith('/') ? raw : `/${raw}`;\n const prefix = normalized.replace(/\\/+$/, '');\n\n // Generic Mastra auth endpoint - works with any credentials provider\n const response = await fetch(`${baseUrl}${prefix}/auth/credentials/sign-up`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ email, password, name }),\n });\n\n const data = await response.json();\n\n if (!response.ok) {\n throw new Error(data.message || data.error || 'Failed to create account');\n }\n\n return data;\n}\n\nexport function useCredentialsSignUp({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<CredentialsSignUpResponse, CredentialsSignUpRequest> } = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<CredentialsSignUpResponse, Error, CredentialsSignUpRequest>({\n mutationFn: ({ email, password, name }) => makeCredentialsSignUpRequest(client, { email, password, name }),\n onSuccess: () => {\n // Invalidate auth queries to refetch user state\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nimport { makeSSOLoginRequest } from './sso-login';\nimport type { LogoutResponse } from './types';\n\n/**\n * Hook to initiate SSO login.\n *\n * Returns mutation to get the SSO login URL and redirect.\n *\n * @example\n * ```tsx\n * import { useSSOLogin } from '@mastra/react/hooks/auth';\n *\n * function SSOLoginButton() {\n * const { mutate: login, isPending } = useSSOLogin();\n *\n * const handleClick = () => {\n * login({ redirectUri: window.location.href }, {\n * onSuccess: (data) => {\n * window.location.href = data.url;\n * },\n * });\n * };\n *\n * return (\n * <button onClick={handleClick} disabled={isPending}>\n * Sign in with SSO\n * </button>\n * );\n * }\n * ```\n */\ntype SSOLoginResponse = Awaited<ReturnType<typeof makeSSOLoginRequest>>;\n\nexport function useSSOLogin({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<SSOLoginResponse, { redirectUri?: string }> } = {}) {\n const client = useMastraClient();\n\n return useMutation({\n mutationFn: ({ redirectUri }: { redirectUri?: string }) => makeSSOLoginRequest(client, { redirectUri }),\n ...queryOptions,\n });\n}\n\n/**\n * Hook to logout the current user.\n *\n * Destroys the current session and optionally redirects to\n * the SSO logout URL if available.\n *\n * @example\n * ```tsx\n * import { useLogout } from '@mastra/react/hooks/auth';\n *\n * function LogoutButton({ userId }: { userId: string }) {\n * const { mutate: logout, isPending } = useLogout();\n * const queryClient = useQueryClient();\n *\n * const handleLogout = () => {\n * logout({ userId }, {\n * onSuccess: (data) => {\n * queryClient.invalidateQueries({ queryKey: ['auth'] });\n * if (data.redirectTo) {\n * window.location.href = data.redirectTo;\n * } else {\n * window.location.reload();\n * }\n * },\n * });\n * };\n *\n * return (\n * <button onClick={handleLogout} disabled={isPending}>\n * Sign out\n * </button>\n * );\n * }\n * ```\n */\n/**\n * Makes a logout request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeLogoutRequest(client: Pick<MastraClient, 'options'>): Promise<LogoutResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const response = await fetch(`${baseUrl}${prefix}/auth/logout`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to logout: ${response.status}`);\n }\n\n return response.json();\n}\n\nexport interface UseLogoutOptions {\n /**\n * Runs once the server has ended the session, before the mutation resolves.\n * Failures are ignored so cleanup never turns a completed sign-out into an error.\n */\n onLoggedOut?: (variables: { userId: string }) => Promise<void>;\n queryOptions?: MastraMutationOptions<LogoutResponse, { userId: string }>;\n}\n\nexport function useLogout({ onLoggedOut, queryOptions }: UseLogoutOptions = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<LogoutResponse, Error, { userId: string }>({\n mutationFn: async variables => {\n const response = await makeLogoutRequest(client);\n await onLoggedOut?.(variables).catch(() => {});\n return response;\n },\n onSuccess: () => {\n // Invalidate all auth-related queries\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n"],"mappings":";;;;;;;;AAkHA,SAAgB,gBAAgB,cAA2E;CACzG,OAAO,UAAU,gBAAgB,aAAa,SAAS,KAAA;AACzD;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1FA,eAAsB,iBACpB,UACA,OACA,MACmB;CACnB,OAAO,MAAM,OAAO,IAAI;AAC1B;AAEA,SAAgB,uBAAuB,UAAmB,YAAmC;CAC3F,QAAQ,OAAO,SAAS,MAAM,OAAO,IAAI;AAC3C;;AClCA,MAAM,kCAAkB,IAAI,QAA8B;AAC1D,IAAI,qBAAqB;;;;;AAMzB,SAAgB,kBAAkB,QAAsB;CACtD,MAAM,cAAc,gBAAgB,IAAI,MAAM;CAC9C,IAAI,gBAAgB,KAAA,GAAW,OAAO;CAEtC,MAAM,WAAW;CACjB,gBAAgB,IAAI,QAAQ,QAAQ;CACpC,OAAO;AACT;;ACVA,eAAsB,oBACpB,QACA,EAAE,eACyB;CAC3B,MAAM,EAAE,UAAU,IAAI,WAAW,SAAS,gBAAgB,CAAC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AA,GAAOC,sBAAAA,YAAAA,CAAY;EACjB,aAAa,EAAE,kBAA4C,oBAAoB,QAAQ,EAAE,YAAY,CAAC;EACtG,GAAG;CACL,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,eAAsB,kBAAkB,QAAgE;CACtG,MAAM,EAAE,UAAU,IAAI,WAAW,SAAS,gBAAgB,CAAC,MAAM,OAAO;CACxE,MAAM,OAAO,aAAa,OAAA,CAAQ,KAAK;CACvC,MAAM,UAAU,IAAI,WAAW,GAAG,IAAI,MAAM,IAAI,MAAA,CAAO,QAAQ,OAAO,EAAE;CAExE,MAAM,WAAW,MAAM,MAAM,GAAG,UAAU,OAAO,eAAe;EAC9D,QAAQ;EACR,aAAa;EACb,SAAS;GACP,GAAG;GACH,gBAAgB;EAClB;CACF,CAAC;CAED,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,qBAAqB,SAAS,QAAQ;CAGxD,OAAO,SAAS,KAAK;AACvB;AAWA,SAAgB,UAAU,EAAE,aAAa,iBAAmC,CAAC,GAAG;CAC9E,MAAM,SAASD,8BAAAA,gBAAgB;CAC/B,MAAM,eAAA,GAAcE,sBAAAA,eAAAA,CAAe;CAEnC,QAAA,GAAOD,sBAAAA,YAAAA,CAAuD;EAC5D,YAAY,OAAM,cAAa;GAC7B,MAAM,WAAW,MAAM,kBAAkB,MAAM;GAC/C,MAAM,cAAc,SAAS,CAAC,CAAC,YAAY,CAAC,CAAC;GAC7C,OAAO;EACT;EACA,iBAAiB;GAEf,YAAiB,kBAAkB,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;EAC3D;EACA,GAAG;CACL,CAAC;AACH"}
@@ -1,6 +1,6 @@
1
1
  import { n as useMastraClient } from "../../mastra-client-context-DQ5z_ze9.js";
2
2
  import { useMemo } from "react";
3
- import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
3
+ import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
4
4
  // src/hooks/auth/types.ts
5
5
  /**
6
6
  * Type guard to check if capabilities include authenticated user
@@ -132,6 +132,7 @@ function useAuthCapabilities({ queryOptions } = {}) {
132
132
  queryFn: () => makeAuthCapabilitiesRequest(client),
133
133
  staleTime: 6e4,
134
134
  retry: false,
135
+ placeholderData: keepPreviousData,
135
136
  ...queryOptions
136
137
  });
137
138
  }
@@ -210,6 +211,7 @@ const usePermissionPatterns = ({ queryOptions } = {}) => {
210
211
  enabled: rbacEnabled,
211
212
  retry: false,
212
213
  staleTime: Infinity,
214
+ placeholderData: keepPreviousData,
213
215
  ...queryOptions
214
216
  });
215
217
  return {