@mastra/react 1.11.1-alpha.6 → 1.12.0-alpha.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{accumulator-C8kIc450.js → accumulator-BfvVnXJr.js} +1 -2
- package/dist/{accumulator-C8kIc450.js.map → accumulator-BfvVnXJr.js.map} +1 -1
- package/dist/{accumulator-BQGsraqS.cjs → accumulator-CgLQ_3q3.cjs} +1 -2
- package/dist/{accumulator-BQGsraqS.cjs.map → accumulator-CgLQ_3q3.cjs.map} +1 -1
- package/dist/agent/hooks.d.ts +9 -0
- package/dist/agent/hooks.d.ts.map +1 -1
- package/dist/chat/index.cjs +1 -1
- package/dist/chat/index.js +1 -2
- package/dist/combine-by-ids-D_lp6Dvq.cjs.map +1 -1
- package/dist/hooks/agents/index.cjs +2 -2
- package/dist/hooks/agents/index.cjs.map +1 -1
- package/dist/hooks/agents/index.js +2 -2
- package/dist/hooks/agents/index.js.map +1 -1
- package/dist/hooks/auth/index.cjs +2 -2
- package/dist/hooks/auth/index.cjs.map +1 -1
- package/dist/hooks/auth/index.js +2 -2
- package/dist/hooks/auth/index.js.map +1 -1
- package/dist/hooks/capabilities/index.cjs +1 -1
- package/dist/hooks/capabilities/index.cjs.map +1 -1
- package/dist/hooks/capabilities/index.js +1 -1
- package/dist/hooks/capabilities/index.js.map +1 -1
- package/dist/hooks/configuration/index.cjs.map +1 -1
- package/dist/hooks/datasets/index.cjs +1 -1
- package/dist/hooks/datasets/index.cjs.map +1 -1
- package/dist/hooks/datasets/index.js +1 -1
- package/dist/hooks/datasets/index.js.map +1 -1
- package/dist/hooks/embedders/index.cjs.map +1 -1
- package/dist/hooks/experiments/index.cjs.map +1 -1
- package/dist/hooks/feedback/index.cjs.map +1 -1
- package/dist/hooks/feedback/use-feedback.d.ts +3 -3
- package/dist/hooks/llm/index.cjs.map +1 -1
- package/dist/hooks/logs/index.cjs.map +1 -1
- package/dist/hooks/logs/use-logs.d.ts +3 -3
- package/dist/hooks/mcps/index.cjs.map +1 -1
- package/dist/hooks/memory/index.cjs +10 -10
- package/dist/hooks/memory/index.cjs.map +1 -1
- package/dist/hooks/memory/index.js +10 -10
- package/dist/hooks/memory/index.js.map +1 -1
- package/dist/hooks/metrics/index.cjs +13 -11
- package/dist/hooks/metrics/index.cjs.map +1 -1
- package/dist/hooks/metrics/index.js +13 -11
- package/dist/hooks/metrics/index.js.map +1 -1
- package/dist/hooks/processors/index.cjs.map +1 -1
- package/dist/hooks/prompt-blocks/index.cjs.map +1 -1
- package/dist/hooks/query/index.cjs.map +1 -1
- package/dist/hooks/review/index.cjs.map +1 -1
- package/dist/hooks/schedules/index.cjs.map +1 -1
- package/dist/hooks/scores/index.cjs.map +1 -1
- package/dist/hooks/templates/index.cjs +20 -18
- package/dist/hooks/templates/index.cjs.map +1 -1
- package/dist/hooks/templates/index.js +20 -18
- package/dist/hooks/templates/index.js.map +1 -1
- package/dist/hooks/tool-providers/index.cjs +1 -1
- package/dist/hooks/tool-providers/index.cjs.map +1 -1
- package/dist/hooks/tool-providers/index.js +1 -1
- package/dist/hooks/tool-providers/index.js.map +1 -1
- package/dist/hooks/tools/index.cjs.map +1 -1
- package/dist/hooks/traces/index.cjs +6 -5
- package/dist/hooks/traces/index.cjs.map +1 -1
- package/dist/hooks/traces/index.js +6 -5
- package/dist/hooks/traces/index.js.map +1 -1
- package/dist/hooks/traces/types.d.ts +1 -0
- package/dist/hooks/traces/types.d.ts.map +1 -1
- package/dist/hooks/traces/use-traces.d.ts +4 -4
- package/dist/hooks/vectors/index.cjs.map +1 -1
- package/dist/hooks/voice/index.cjs.map +1 -1
- package/dist/hooks/workflows/index.cjs +1 -1
- package/dist/hooks/workflows/index.cjs.map +1 -1
- package/dist/hooks/workflows/index.js +1 -1
- package/dist/hooks/workspace/index.cjs +1 -1
- package/dist/hooks/workspace/index.cjs.map +1 -1
- package/dist/hooks/workspace/index.js +1 -1
- package/dist/hooks/workspace/index.js.map +1 -1
- package/dist/{hooks-CIwCEruG.cjs → hooks-B1i-oHae.cjs} +27 -5
- package/dist/hooks-B1i-oHae.cjs.map +1 -0
- package/dist/{hooks-CbX7Q4A3.js → hooks-CLfMO5cH.js} +27 -5
- package/dist/hooks-CLfMO5cH.js.map +1 -0
- package/dist/{hooks-_YevKidX.cjs → hooks-D8nOYPUd.cjs} +2 -2
- package/dist/hooks-D8nOYPUd.cjs.map +1 -0
- package/dist/{hooks-0L0RNfau.js → hooks-NaZLZreZ.js} +2 -2
- package/dist/{hooks-0L0RNfau.js.map → hooks-NaZLZreZ.js.map} +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +3 -3
- package/dist/mastra-client-context-DzX3f0RF.cjs.map +1 -1
- package/dist/ui/index.cjs +4 -4
- package/dist/ui/index.cjs.map +1 -1
- package/dist/ui/index.js +3 -3
- package/dist/ui/index.js.map +1 -1
- package/dist/use-in-view-B6eJO9Zi.cjs.map +1 -1
- package/dist/voice-BOtUdMi8.cjs.map +1 -1
- package/package.json +4 -4
- package/dist/hooks-CIwCEruG.cjs.map +0 -1
- package/dist/hooks-CbX7Q4A3.js.map +0 -1
- package/dist/hooks-_YevKidX.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["isUnsupportedObservabilityOperationError","isObservabilityUnavailableError","useMastraClient","useInView","isUnsupportedObservabilityOperationError","isObservabilityUnavailableError","useMastraClient","useMastraClient","useMastraClient","useMastraClient"],"sources":["../../../src/hooks/scores/use-scorers.ts","../../../src/hooks/scores/use-trace-span-scores.ts","../../../src/hooks/scores/use-trigger-scorer.ts","../../../src/hooks/scores/use-stored-scorers.ts","../../../src/hooks/scores/use-scorer-versions.ts"],"sourcesContent":["import type { MastraClient, GetScorerResponse, ListScoresResponse } from '@mastra/client-js';\nimport type { UseInfiniteQueryResult, UseQueryResult } from '@tanstack/react-query';\nimport { useInfiniteQuery, useQuery } from '@tanstack/react-query';\nimport { useEffect, useState } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport { isObservabilityUnavailableError, isUnsupportedObservabilityOperationError } from '../query/query-utils';\nimport type { MastraInfiniteQueryOptions, MastraQueryOptions } from '../shared/query-options';\nimport { useInView } from '../shared/use-in-view';\n\nconst SCORES_PER_PAGE = 25;\nconst SCORES_REFETCH_INTERVAL_MS = 15_000;\n\nexport function getScoresRefetchInterval(query: { state: { error: unknown } }) {\n if (\n isUnsupportedObservabilityOperationError(query.state.error, 'scores') ||\n isObservabilityUnavailableError(query.state.error)\n ) {\n return false;\n }\n return SCORES_REFETCH_INTERVAL_MS;\n}\n\ntype UseScoresByScorerIdProps<TData> = {\n scorerId: string;\n entityId?: string;\n entityType?: string;\n /** TanStack overrides spread last; `select` defaults to the flattened, de-duplicated score list. */\n queryOptions?: MastraInfiniteQueryOptions<ListScoresResponse, TData, readonly unknown[], number>;\n};\n\nfunction getScoresNextPageParam(lastPage: ListScoresResponse | undefined, _allPages: unknown, lastPageParam: number) {\n if (lastPage?.pagination?.hasMore) {\n return lastPageParam + 1;\n }\n return undefined;\n}\n\nfunction selectFlatScores(data: { pages: ListScoresResponse[] }) {\n const seen = new Set<string>();\n const scores = data.pages\n .flatMap(page => page.scores ?? [])\n .filter(score => {\n if (seen.has(score.id)) return false;\n seen.add(score.id);\n return true;\n });\n return scores;\n}\n\nexport const useScoresByScorerId = <TData = ReturnType<typeof selectFlatScores>>({\n scorerId,\n entityId,\n entityType,\n queryOptions,\n}: UseScoresByScorerIdProps<TData>): UseInfiniteQueryResult<TData, Error> & {\n setEndOfListElement: ReturnType<typeof useInView>['setRef'];\n} => {\n const client = useMastraClient();\n const { inView: isEndOfListInView, setRef: setEndOfListElement } = useInView();\n\n const query = useInfiniteQuery<ListScoresResponse, Error, TData, readonly unknown[], number>({\n queryKey: ['scores', scorerId, entityId, entityType],\n queryFn: ({ pageParam }) =>\n client.listScoresByScorerId({ scorerId, page: pageParam, perPage: SCORES_PER_PAGE, entityId, entityType }),\n initialPageParam: 0,\n getNextPageParam: getScoresNextPageParam,\n select: data => selectFlatScores(data) as TData,\n refetchInterval: getScoresRefetchInterval,\n ...queryOptions,\n });\n\n const { hasNextPage, isFetchingNextPage, fetchNextPage } = query;\n\n useEffect(() => {\n if (isEndOfListInView && hasNextPage && !isFetchingNextPage) {\n void fetchNextPage();\n }\n }, [isEndOfListInView, hasNextPage, isFetchingNextPage, fetchNextPage]);\n\n return { ...query, setEndOfListElement };\n};\n\nexport const useScorer = (scorerId: string) => {\n const client = useMastraClient();\n const [scorer, setScorer] = useState<GetScorerResponse | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n useEffect(() => {\n const fetchScorer = async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await client.getScorer(scorerId);\n setScorer(res);\n } catch (error) {\n setScorer(null);\n const errorObj = error instanceof Error ? error : new Error('Error fetching scorer');\n setError(errorObj);\n console.error('Error fetching scorer', error);\n } finally {\n setIsLoading(false);\n }\n };\n\n void fetchScorer();\n }, [scorerId, client]);\n\n return { scorer, isLoading, error };\n};\n\ntype ListScorersResponse = Awaited<ReturnType<MastraClient['listScorers']>>;\n\nexport const useScorers = <TData = ListScorersResponse>({\n requestContext,\n queryOptions,\n}: {\n requestContext?: Record<string, unknown>;\n queryOptions?: MastraQueryOptions<ListScorersResponse, TData>;\n} = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<ListScorersResponse, Error, TData>({\n queryKey: ['scorers', requestContext],\n queryFn: () => client.listScorers(requestContext),\n staleTime: 0,\n gcTime: 0,\n ...queryOptions,\n });\n};\n","import type { ListScoresResponse } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport { isObservabilityUnavailableError, isUnsupportedObservabilityOperationError } from '../query/query-utils';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nconst TRACE_SPAN_SCORES_REFETCH_INTERVAL_MS = 15_000;\n\nexport function getTraceSpanScoresRefetchInterval(query: { state: { error: unknown } }) {\n if (\n isUnsupportedObservabilityOperationError(query.state.error, 'scores') ||\n isObservabilityUnavailableError(query.state.error)\n ) {\n return false;\n }\n return TRACE_SPAN_SCORES_REFETCH_INTERVAL_MS;\n}\n\ntype useTraceSpanScoresProps<TData> = {\n traceId?: string;\n spanId?: string;\n page?: number;\n queryOptions?: MastraQueryOptions<ListScoresResponse, TData>;\n};\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useTraceSpanScores = <TData = ListScoresResponse>({\n traceId = '',\n spanId = '',\n page,\n queryOptions,\n}: useTraceSpanScoresProps<TData>): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n return useQuery<ListScoresResponse, Error, TData>({\n queryKey: ['trace-span-scores', traceId, spanId, page],\n queryFn: () => client.listScoresBySpan({ traceId, spanId, page: page || 0, perPage: 10 }),\n refetchInterval: getTraceSpanScoresRefetchInterval,\n gcTime: 0,\n staleTime: 0,\n ...queryOptions,\n });\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\ninterface TriggerScoreArgs {\n scorerName: string;\n traceId: string;\n spanId?: string;\n}\n\ntype TriggerScorerResponse = Awaited<ReturnType<MastraClient['score']>>;\n\nexport const useTriggerScorer = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TriggerScorerResponse, TriggerScoreArgs> } = {}) => {\n const client = useMastraClient();\n\n return useMutation({\n mutationFn: async ({ scorerName, traceId, spanId }: TriggerScoreArgs) => {\n const response = await client.score({\n scorerName,\n targets: [{ traceId, spanId }],\n });\n\n return response;\n },\n ...queryOptions,\n });\n};\n","import type { MastraClient, CreateStoredScorerParams, UpdateStoredScorerParams } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\ntype StoredScorerResponse = Awaited<ReturnType<ReturnType<MastraClient['getStoredScorer']>['details']>>;\ntype DeleteStoredScorerResponse = Awaited<ReturnType<ReturnType<MastraClient['getStoredScorer']>['delete']>>;\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useStoredScorer = <TData = StoredScorerResponse | null>({\n scorerId,\n status,\n requestContext,\n queryOptions,\n}: {\n scorerId?: string;\n status?: 'draft' | 'published';\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<StoredScorerResponse | null, TData>;\n} = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<StoredScorerResponse | null, Error, TData>({\n queryKey: ['stored-scorer', scorerId, status, requestContext],\n queryFn: () => (scorerId ? client.getStoredScorer(scorerId).details(requestContext, { status }) : null),\n ...queryOptions,\n });\n};\n\nexport const useStoredScorerMutations = ({\n scorerId,\n requestContext,\n queryOptions,\n}: {\n scorerId?: string;\n requestContext?: Record<string, any>;\n queryOptions?: {\n createStoredScorer?: MastraMutationOptions<StoredScorerResponse, CreateStoredScorerParams>;\n updateStoredScorer?: MastraMutationOptions<StoredScorerResponse, UpdateStoredScorerParams>;\n deleteStoredScorer?: MastraMutationOptions<DeleteStoredScorerResponse, void>;\n };\n} = {}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n const createMutation = useMutation({\n mutationFn: (params: CreateStoredScorerParams) => client.createStoredScorer(params),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['stored-scorers'] });\n void queryClient.invalidateQueries({ queryKey: ['scorers'] });\n },\n ...queryOptions?.createStoredScorer,\n });\n\n const updateMutation = useMutation({\n mutationFn: (params: UpdateStoredScorerParams) => {\n if (!scorerId) throw new Error('scorerId is required for update');\n return client.getStoredScorer(scorerId).update(params, requestContext);\n },\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['stored-scorers'] });\n void queryClient.invalidateQueries({ queryKey: ['scorers'] });\n if (scorerId) {\n void queryClient.invalidateQueries({ queryKey: ['stored-scorer', scorerId] });\n }\n },\n ...queryOptions?.updateStoredScorer,\n });\n\n const deleteMutation = useMutation({\n mutationFn: () => {\n if (!scorerId) throw new Error('scorerId is required for delete');\n return client.getStoredScorer(scorerId).delete(requestContext);\n },\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['stored-scorers'] });\n void queryClient.invalidateQueries({ queryKey: ['scorers'] });\n if (scorerId) {\n void queryClient.invalidateQueries({ queryKey: ['stored-scorer', scorerId] });\n }\n },\n ...queryOptions?.deleteStoredScorer,\n });\n\n return {\n createStoredScorer: createMutation,\n updateStoredScorer: updateMutation,\n deleteStoredScorer: deleteMutation,\n };\n};\n","import type {\n ListScorerVersionsParams,\n CreateScorerVersionParams,\n ListScorerVersionsResponse,\n ScorerVersionResponse,\n CompareScorerVersionsResponse,\n ActivateScorerVersionResponse,\n DeleteScorerVersionResponse,\n} from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\nexport type { ListScorerVersionsParams, CreateScorerVersionParams };\n\n/**\n * Hook to list versions of a stored scorer\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useScorerVersions = <TData = ListScorerVersionsResponse>({\n scorerId,\n params,\n requestContext,\n queryOptions,\n}: {\n scorerId: string;\n params?: ListScorerVersionsParams;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<ListScorerVersionsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<ListScorerVersionsResponse, Error, TData>({\n queryKey: ['scorer-versions', scorerId, params, requestContext],\n queryFn: () => client.getStoredScorer(scorerId).listVersions(params, requestContext),\n ...queryOptions,\n });\n};\n\n/**\n * Hook to get a single version of a stored scorer\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useScorerVersion = <TData = ScorerVersionResponse>({\n scorerId,\n versionId,\n requestContext,\n queryOptions,\n}: {\n scorerId: string;\n versionId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<ScorerVersionResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<ScorerVersionResponse, Error, TData>({\n queryKey: ['scorer-version', scorerId, versionId, requestContext],\n queryFn: () => client.getStoredScorer(scorerId).getVersion(versionId, requestContext),\n ...queryOptions,\n });\n};\n\n/**\n * Hook to create a new version of a stored scorer\n */\nexport const useCreateScorerVersion = ({\n scorerId,\n requestContext,\n queryOptions,\n}: {\n scorerId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraMutationOptions<ScorerVersionResponse, CreateScorerVersionParams | undefined>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<ScorerVersionResponse, Error, CreateScorerVersionParams | undefined>({\n mutationFn: (params?: CreateScorerVersionParams) =>\n client.getStoredScorer(scorerId).createVersion(params, requestContext),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['scorer-versions', scorerId] });\n void queryClient.invalidateQueries({ queryKey: ['stored-scorer', scorerId] });\n },\n ...queryOptions,\n });\n};\n\n/**\n * Hook to activate a specific version of a stored scorer\n */\nexport const useActivateScorerVersion = ({\n scorerId,\n requestContext,\n queryOptions,\n}: {\n scorerId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraMutationOptions<ActivateScorerVersionResponse, string>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<ActivateScorerVersionResponse, Error, string>({\n mutationFn: (versionId: string) => client.getStoredScorer(scorerId).activateVersion(versionId, requestContext),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['scorer-versions', scorerId] });\n void queryClient.invalidateQueries({ queryKey: ['stored-scorer', scorerId] });\n },\n ...queryOptions,\n });\n};\n\n/**\n * Hook to restore a specific version of a stored scorer (creates a new version from an old one)\n */\nexport const useRestoreScorerVersion = ({\n scorerId,\n requestContext,\n queryOptions,\n}: {\n scorerId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraMutationOptions<ScorerVersionResponse, string>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<ScorerVersionResponse, Error, string>({\n mutationFn: (versionId: string) => client.getStoredScorer(scorerId).restoreVersion(versionId, requestContext),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['scorer-versions', scorerId] });\n void queryClient.invalidateQueries({ queryKey: ['stored-scorer', scorerId] });\n },\n ...queryOptions,\n });\n};\n\n/**\n * Hook to delete a specific version of a stored scorer\n */\nexport const useDeleteScorerVersion = ({\n scorerId,\n requestContext,\n queryOptions,\n}: {\n scorerId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraMutationOptions<DeleteScorerVersionResponse, string>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<DeleteScorerVersionResponse, Error, string>({\n mutationFn: (versionId: string) => client.getStoredScorer(scorerId).deleteVersion(versionId, requestContext),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['scorer-versions', scorerId] });\n },\n ...queryOptions,\n });\n};\n\n/**\n * Hook to compare two versions of a stored scorer\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useCompareScorerVersions = <TData = CompareScorerVersionsResponse>({\n scorerId,\n fromVersionId,\n toVersionId,\n requestContext,\n queryOptions,\n}: {\n scorerId: string;\n fromVersionId: string;\n toVersionId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<CompareScorerVersionsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<CompareScorerVersionsResponse, Error, TData>({\n queryKey: ['scorer-versions-compare', scorerId, fromVersionId, toVersionId, requestContext],\n queryFn: () => client.getStoredScorer(scorerId).compareVersions(fromVersionId, toVersionId, requestContext),\n ...queryOptions,\n });\n};\n"],"mappings":";;;;;;;AASA,MAAM,kBAAkB;AACxB,MAAM,6BAA6B;AAEnC,SAAgB,yBAAyB,OAAsC;CAC7E,IACEA,oBAAAA,yCAAyC,MAAM,MAAM,OAAO,QAAQ,KACpEC,oBAAAA,gCAAgC,MAAM,MAAM,KAAK,GAEjD,OAAO;CAET,OAAO;AACT;AAUA,SAAS,uBAAuB,UAA0C,WAAoB,eAAuB;CACnH,IAAI,UAAU,YAAY,SACxB,OAAO,gBAAgB;AAG3B;AAEA,SAAS,iBAAiB,MAAuC;CAC/D,MAAM,uBAAO,IAAI,IAAY;CAQ7B,OAPe,KAAK,MACjB,SAAQ,SAAQ,KAAK,UAAU,CAAC,CAAC,CAAC,CAClC,QAAO,UAAS;EACf,IAAI,KAAK,IAAI,MAAM,EAAE,GAAG,OAAO;EAC/B,KAAK,IAAI,MAAM,EAAE;EACjB,OAAO;CACT,CACU;AACd;AAEA,MAAa,uBAAoE,EAC/E,UACA,UACA,YACA,mBAGG;CACH,MAAM,SAASC,8BAAAA,gBAAgB;CAC/B,MAAM,EAAE,QAAQ,mBAAmB,QAAQ,wBAAwBC,oBAAAA,UAAU;CAE7E,MAAM,SAAA,GAAA,sBAAA,iBAAA,CAAuF;EAC3F,UAAU;GAAC;GAAU;GAAU;GAAU;EAAU;EACnD,UAAU,EAAE,gBACV,OAAO,qBAAqB;GAAE;GAAU,MAAM;GAAW,SAAS;GAAiB;GAAU;EAAW,CAAC;EAC3G,kBAAkB;EAClB,kBAAkB;EAClB,SAAQ,SAAQ,iBAAiB,IAAI;EACrC,iBAAiB;EACjB,GAAG;CACL,CAAC;CAED,MAAM,EAAE,aAAa,oBAAoB,kBAAkB;CAE3D,CA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SAASA,8BAAAA,gBAAgB;CAC/B,MAAM,eAAA,GAAA,sBAAA,eAAA,CAA6B;CAEnC,QAAA,GAAA,sBAAA,YAAA,CAAyD;EACvD,aAAa,cAAsB,OAAO,gBAAgB,QAAQ,CAAC,CAAC,eAAe,WAAW,cAAc;EAC5G,iBAAiB;GACf,YAAiB,kBAAkB,EAAE,UAAU,CAAC,mBAAmB,QAAQ,EAAE,CAAC;GAC9E,YAAiB,kBAAkB,EAAE,UAAU,CAAC,iBAAiB,QAAQ,EAAE,CAAC;EAC9E;EACA,GAAG;CACL,CAAC;AACH;;;;AAKA,MAAa,0BAA0B,EACrC,UACA,gBACA,mBAKI;CACJ,MAAM,SAASA,8BAAAA,gBAAgB;CAC/B,MAAM,eAAA,GAAA,sBAAA,eAAA,CAA6B;CAEnC,QAAA,GAAA,sBAAA,YAAA,CAA+D;EAC7D,aAAa,cAAsB,OAAO,gBAAgB,QAAQ,CAAC,CAAC,cAAc,WAAW,cAAc;EAC3G,iBAAiB;GACf,YAAiB,kBAAkB,EAAE,UAAU,CAAC,mBAAmB,QAAQ,EAAE,CAAC;EAChF;EACA,GAAG;CACL,CAAC;AACH;;;;;;AAOA,MAAa,4BAAmE,EAC9E,UACA,eACA,aACA,gBACA,mBAOkC;CAClC,MAAM,SAASA,8BAAAA,gBAAgB;CAE/B,QAAA,GAAA,sBAAA,SAAA,CAA6D;EAC3D,UAAU;GAAC;GAA2B;GAAU;GAAe;GAAa;EAAc;EAC1F,eAAe,OAAO,gBAAgB,QAAQ,CAAC,CAAC,gBAAgB,eAAe,aAAa,cAAc;EAC1G,GAAG;CACL,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["isUnsupportedObservabilityOperationError","isObservabilityUnavailableError","useMastraClient","useInView","useInfiniteQuery","useState","useQuery","isUnsupportedObservabilityOperationError","isObservabilityUnavailableError","useMastraClient","useQuery","useMastraClient","useMutation","useMastraClient","useQuery","useQueryClient","useMutation","useMastraClient","useQuery","useQueryClient","useMutation"],"sources":["../../../src/hooks/scores/use-scorers.ts","../../../src/hooks/scores/use-trace-span-scores.ts","../../../src/hooks/scores/use-trigger-scorer.ts","../../../src/hooks/scores/use-stored-scorers.ts","../../../src/hooks/scores/use-scorer-versions.ts"],"sourcesContent":["import type { MastraClient, GetScorerResponse, ListScoresResponse } from '@mastra/client-js';\nimport type { UseInfiniteQueryResult, UseQueryResult } from '@tanstack/react-query';\nimport { useInfiniteQuery, useQuery } from '@tanstack/react-query';\nimport { useEffect, useState } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport { isObservabilityUnavailableError, isUnsupportedObservabilityOperationError } from '../query/query-utils';\nimport type { MastraInfiniteQueryOptions, MastraQueryOptions } from '../shared/query-options';\nimport { useInView } from '../shared/use-in-view';\n\nconst SCORES_PER_PAGE = 25;\nconst SCORES_REFETCH_INTERVAL_MS = 15_000;\n\nexport function getScoresRefetchInterval(query: { state: { error: unknown } }) {\n if (\n isUnsupportedObservabilityOperationError(query.state.error, 'scores') ||\n isObservabilityUnavailableError(query.state.error)\n ) {\n return false;\n }\n return SCORES_REFETCH_INTERVAL_MS;\n}\n\ntype UseScoresByScorerIdProps<TData> = {\n scorerId: string;\n entityId?: string;\n entityType?: string;\n /** TanStack overrides spread last; `select` defaults to the flattened, de-duplicated score list. */\n queryOptions?: MastraInfiniteQueryOptions<ListScoresResponse, TData, readonly unknown[], number>;\n};\n\nfunction getScoresNextPageParam(lastPage: ListScoresResponse | undefined, _allPages: unknown, lastPageParam: number) {\n if (lastPage?.pagination?.hasMore) {\n return lastPageParam + 1;\n }\n return undefined;\n}\n\nfunction selectFlatScores(data: { pages: ListScoresResponse[] }) {\n const seen = new Set<string>();\n const scores = data.pages\n .flatMap(page => page.scores ?? [])\n .filter(score => {\n if (seen.has(score.id)) return false;\n seen.add(score.id);\n return true;\n });\n return scores;\n}\n\nexport const useScoresByScorerId = <TData = ReturnType<typeof selectFlatScores>>({\n scorerId,\n entityId,\n entityType,\n queryOptions,\n}: UseScoresByScorerIdProps<TData>): UseInfiniteQueryResult<TData, Error> & {\n setEndOfListElement: ReturnType<typeof useInView>['setRef'];\n} => {\n const client = useMastraClient();\n const { inView: isEndOfListInView, setRef: setEndOfListElement } = useInView();\n\n const query = useInfiniteQuery<ListScoresResponse, Error, TData, readonly unknown[], number>({\n queryKey: ['scores', scorerId, entityId, entityType],\n queryFn: ({ pageParam }) =>\n client.listScoresByScorerId({ scorerId, page: pageParam, perPage: SCORES_PER_PAGE, entityId, entityType }),\n initialPageParam: 0,\n getNextPageParam: getScoresNextPageParam,\n select: data => selectFlatScores(data) as TData,\n refetchInterval: getScoresRefetchInterval,\n ...queryOptions,\n });\n\n const { hasNextPage, isFetchingNextPage, fetchNextPage } = query;\n\n useEffect(() => {\n if (isEndOfListInView && hasNextPage && !isFetchingNextPage) {\n void fetchNextPage();\n }\n }, [isEndOfListInView, hasNextPage, isFetchingNextPage, fetchNextPage]);\n\n return { ...query, setEndOfListElement };\n};\n\nexport const useScorer = (scorerId: string) => {\n const client = useMastraClient();\n const [scorer, setScorer] = useState<GetScorerResponse | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n useEffect(() => {\n const fetchScorer = async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await client.getScorer(scorerId);\n setScorer(res);\n } catch (error) {\n setScorer(null);\n const errorObj = error instanceof Error ? error : new Error('Error fetching scorer');\n setError(errorObj);\n console.error('Error fetching scorer', error);\n } finally {\n setIsLoading(false);\n }\n };\n\n void fetchScorer();\n }, [scorerId, client]);\n\n return { scorer, isLoading, error };\n};\n\ntype ListScorersResponse = Awaited<ReturnType<MastraClient['listScorers']>>;\n\nexport const useScorers = <TData = ListScorersResponse>({\n requestContext,\n queryOptions,\n}: {\n requestContext?: Record<string, unknown>;\n queryOptions?: MastraQueryOptions<ListScorersResponse, TData>;\n} = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<ListScorersResponse, Error, TData>({\n queryKey: ['scorers', requestContext],\n queryFn: () => client.listScorers(requestContext),\n staleTime: 0,\n gcTime: 0,\n ...queryOptions,\n });\n};\n","import type { ListScoresResponse } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport { isObservabilityUnavailableError, isUnsupportedObservabilityOperationError } from '../query/query-utils';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nconst TRACE_SPAN_SCORES_REFETCH_INTERVAL_MS = 15_000;\n\nexport function getTraceSpanScoresRefetchInterval(query: { state: { error: unknown } }) {\n if (\n isUnsupportedObservabilityOperationError(query.state.error, 'scores') ||\n isObservabilityUnavailableError(query.state.error)\n ) {\n return false;\n }\n return TRACE_SPAN_SCORES_REFETCH_INTERVAL_MS;\n}\n\ntype useTraceSpanScoresProps<TData> = {\n traceId?: string;\n spanId?: string;\n page?: number;\n queryOptions?: MastraQueryOptions<ListScoresResponse, TData>;\n};\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useTraceSpanScores = <TData = ListScoresResponse>({\n traceId = '',\n spanId = '',\n page,\n queryOptions,\n}: useTraceSpanScoresProps<TData>): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n return useQuery<ListScoresResponse, Error, TData>({\n queryKey: ['trace-span-scores', traceId, spanId, page],\n queryFn: () => client.listScoresBySpan({ traceId, spanId, page: page || 0, perPage: 10 }),\n refetchInterval: getTraceSpanScoresRefetchInterval,\n gcTime: 0,\n staleTime: 0,\n ...queryOptions,\n });\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\ninterface TriggerScoreArgs {\n scorerName: string;\n traceId: string;\n spanId?: string;\n}\n\ntype TriggerScorerResponse = Awaited<ReturnType<MastraClient['score']>>;\n\nexport const useTriggerScorer = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TriggerScorerResponse, TriggerScoreArgs> } = {}) => {\n const client = useMastraClient();\n\n return useMutation({\n mutationFn: async ({ scorerName, traceId, spanId }: TriggerScoreArgs) => {\n const response = await client.score({\n scorerName,\n targets: [{ traceId, spanId }],\n });\n\n return response;\n },\n ...queryOptions,\n });\n};\n","import type { MastraClient, CreateStoredScorerParams, UpdateStoredScorerParams } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\ntype StoredScorerResponse = Awaited<ReturnType<ReturnType<MastraClient['getStoredScorer']>['details']>>;\ntype DeleteStoredScorerResponse = Awaited<ReturnType<ReturnType<MastraClient['getStoredScorer']>['delete']>>;\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useStoredScorer = <TData = StoredScorerResponse | null>({\n scorerId,\n status,\n requestContext,\n queryOptions,\n}: {\n scorerId?: string;\n status?: 'draft' | 'published';\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<StoredScorerResponse | null, TData>;\n} = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<StoredScorerResponse | null, Error, TData>({\n queryKey: ['stored-scorer', scorerId, status, requestContext],\n queryFn: () => (scorerId ? client.getStoredScorer(scorerId).details(requestContext, { status }) : null),\n ...queryOptions,\n });\n};\n\nexport const useStoredScorerMutations = ({\n scorerId,\n requestContext,\n queryOptions,\n}: {\n scorerId?: string;\n requestContext?: Record<string, any>;\n queryOptions?: {\n createStoredScorer?: MastraMutationOptions<StoredScorerResponse, CreateStoredScorerParams>;\n updateStoredScorer?: MastraMutationOptions<StoredScorerResponse, UpdateStoredScorerParams>;\n deleteStoredScorer?: MastraMutationOptions<DeleteStoredScorerResponse, void>;\n };\n} = {}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n const createMutation = useMutation({\n mutationFn: (params: CreateStoredScorerParams) => client.createStoredScorer(params),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['stored-scorers'] });\n void queryClient.invalidateQueries({ queryKey: ['scorers'] });\n },\n ...queryOptions?.createStoredScorer,\n });\n\n const updateMutation = useMutation({\n mutationFn: (params: UpdateStoredScorerParams) => {\n if (!scorerId) throw new Error('scorerId is required for update');\n return client.getStoredScorer(scorerId).update(params, requestContext);\n },\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['stored-scorers'] });\n void queryClient.invalidateQueries({ queryKey: ['scorers'] });\n if (scorerId) {\n void queryClient.invalidateQueries({ queryKey: ['stored-scorer', scorerId] });\n }\n },\n ...queryOptions?.updateStoredScorer,\n });\n\n const deleteMutation = useMutation({\n mutationFn: () => {\n if (!scorerId) throw new Error('scorerId is required for delete');\n return client.getStoredScorer(scorerId).delete(requestContext);\n },\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['stored-scorers'] });\n void queryClient.invalidateQueries({ queryKey: ['scorers'] });\n if (scorerId) {\n void queryClient.invalidateQueries({ queryKey: ['stored-scorer', scorerId] });\n }\n },\n ...queryOptions?.deleteStoredScorer,\n });\n\n return {\n createStoredScorer: createMutation,\n updateStoredScorer: updateMutation,\n deleteStoredScorer: deleteMutation,\n };\n};\n","import type {\n ListScorerVersionsParams,\n CreateScorerVersionParams,\n ListScorerVersionsResponse,\n ScorerVersionResponse,\n CompareScorerVersionsResponse,\n ActivateScorerVersionResponse,\n DeleteScorerVersionResponse,\n} from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\nexport type { ListScorerVersionsParams, CreateScorerVersionParams };\n\n/**\n * Hook to list versions of a stored scorer\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useScorerVersions = <TData = ListScorerVersionsResponse>({\n scorerId,\n params,\n requestContext,\n queryOptions,\n}: {\n scorerId: string;\n params?: ListScorerVersionsParams;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<ListScorerVersionsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<ListScorerVersionsResponse, Error, TData>({\n queryKey: ['scorer-versions', scorerId, params, requestContext],\n queryFn: () => client.getStoredScorer(scorerId).listVersions(params, requestContext),\n ...queryOptions,\n });\n};\n\n/**\n * Hook to get a single version of a stored scorer\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useScorerVersion = <TData = ScorerVersionResponse>({\n scorerId,\n versionId,\n requestContext,\n queryOptions,\n}: {\n scorerId: string;\n versionId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<ScorerVersionResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<ScorerVersionResponse, Error, TData>({\n queryKey: ['scorer-version', scorerId, versionId, requestContext],\n queryFn: () => client.getStoredScorer(scorerId).getVersion(versionId, requestContext),\n ...queryOptions,\n });\n};\n\n/**\n * Hook to create a new version of a stored scorer\n */\nexport const useCreateScorerVersion = ({\n scorerId,\n requestContext,\n queryOptions,\n}: {\n scorerId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraMutationOptions<ScorerVersionResponse, CreateScorerVersionParams | undefined>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<ScorerVersionResponse, Error, CreateScorerVersionParams | undefined>({\n mutationFn: (params?: CreateScorerVersionParams) =>\n client.getStoredScorer(scorerId).createVersion(params, requestContext),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['scorer-versions', scorerId] });\n void queryClient.invalidateQueries({ queryKey: ['stored-scorer', scorerId] });\n },\n ...queryOptions,\n });\n};\n\n/**\n * Hook to activate a specific version of a stored scorer\n */\nexport const useActivateScorerVersion = ({\n scorerId,\n requestContext,\n queryOptions,\n}: {\n scorerId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraMutationOptions<ActivateScorerVersionResponse, string>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<ActivateScorerVersionResponse, Error, string>({\n mutationFn: (versionId: string) => client.getStoredScorer(scorerId).activateVersion(versionId, requestContext),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['scorer-versions', scorerId] });\n void queryClient.invalidateQueries({ queryKey: ['stored-scorer', scorerId] });\n },\n ...queryOptions,\n });\n};\n\n/**\n * Hook to restore a specific version of a stored scorer (creates a new version from an old one)\n */\nexport const useRestoreScorerVersion = ({\n scorerId,\n requestContext,\n queryOptions,\n}: {\n scorerId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraMutationOptions<ScorerVersionResponse, string>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<ScorerVersionResponse, Error, string>({\n mutationFn: (versionId: string) => client.getStoredScorer(scorerId).restoreVersion(versionId, requestContext),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['scorer-versions', scorerId] });\n void queryClient.invalidateQueries({ queryKey: ['stored-scorer', scorerId] });\n },\n ...queryOptions,\n });\n};\n\n/**\n * Hook to delete a specific version of a stored scorer\n */\nexport const useDeleteScorerVersion = ({\n scorerId,\n requestContext,\n queryOptions,\n}: {\n scorerId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraMutationOptions<DeleteScorerVersionResponse, string>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<DeleteScorerVersionResponse, Error, string>({\n mutationFn: (versionId: string) => client.getStoredScorer(scorerId).deleteVersion(versionId, requestContext),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['scorer-versions', scorerId] });\n },\n ...queryOptions,\n });\n};\n\n/**\n * Hook to compare two versions of a stored scorer\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useCompareScorerVersions = <TData = CompareScorerVersionsResponse>({\n scorerId,\n fromVersionId,\n toVersionId,\n requestContext,\n queryOptions,\n}: {\n scorerId: string;\n fromVersionId: string;\n toVersionId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<CompareScorerVersionsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<CompareScorerVersionsResponse, Error, TData>({\n queryKey: ['scorer-versions-compare', scorerId, fromVersionId, toVersionId, requestContext],\n queryFn: () => client.getStoredScorer(scorerId).compareVersions(fromVersionId, toVersionId, requestContext),\n ...queryOptions,\n });\n};\n"],"mappings":";;;;;;;AASA,MAAM,kBAAkB;AACxB,MAAM,6BAA6B;AAEnC,SAAgB,yBAAyB,OAAsC;CAC7E,IACEA,oBAAAA,yCAAyC,MAAM,MAAM,OAAO,QAAQ,KACpEC,oBAAAA,gCAAgC,MAAM,MAAM,KAAK,GAEjD,OAAO;CAET,OAAO;AACT;AAUA,SAAS,uBAAuB,UAA0C,WAAoB,eAAuB;CACnH,IAAI,UAAU,YAAY,SACxB,OAAO,gBAAgB;AAG3B;AAEA,SAAS,iBAAiB,MAAuC;CAC/D,MAAM,uBAAO,IAAI,IAAY;CAQ7B,OAPe,KAAK,MACjB,SAAQ,SAAQ,KAAK,UAAU,CAAC,CAAC,CAAC,CAClC,QAAO,UAAS;EACf,IAAI,KAAK,IAAI,MAAM,EAAE,GAAG,OAAO;EAC/B,KAAK,IAAI,MAAM,EAAE;EACjB,OAAO;CACT,CACU;AACd;AAEA,MAAa,uBAAoE,EAC/E,UACA,UACA,YACA,mBAGG;CACH,MAAM,SAASC,8BAAAA,gBAAgB;CAC/B,MAAM,EAAE,QAAQ,mBAAmB,QAAQ,wBAAwBC,oBAAAA,UAAU;CAE7E,MAAM,SAAA,GAAQC,sBA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AsD;EAC3D,UAAU;GAAC;GAA2B;GAAU;GAAe;GAAa;EAAc;EAC1F,eAAe,OAAO,gBAAgB,QAAQ,CAAC,CAAC,gBAAgB,eAAe,aAAa,cAAc;EAC1G,GAAG;CACL,CAAC;AACH"}
|
|
@@ -286,24 +286,26 @@ const processTemplateInstallRecord = (record, currentState, workflowInfo) => {
|
|
|
286
286
|
currentStep: null
|
|
287
287
|
}
|
|
288
288
|
};
|
|
289
|
-
if (record.type === "finish" || record.type === "workflow-finish")
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
289
|
+
if (record.type === "finish" || record.type === "workflow-finish") {
|
|
290
|
+
if (newState.phase === "error" || newState.status === "failed") newState = {
|
|
291
|
+
...newState,
|
|
292
|
+
completedAt: /* @__PURE__ */ new Date()
|
|
293
|
+
};
|
|
294
|
+
else newState = {
|
|
295
|
+
...newState,
|
|
296
|
+
status: record.payload.status || "completed",
|
|
297
|
+
phase: "completed",
|
|
298
|
+
payload: {
|
|
299
|
+
...newState.payload,
|
|
300
|
+
currentStep: null,
|
|
301
|
+
workflowState: {
|
|
302
|
+
...newState.payload.workflowState,
|
|
303
|
+
status: record.payload.status || "completed"
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
completedAt: /* @__PURE__ */ new Date()
|
|
307
|
+
};
|
|
308
|
+
}
|
|
307
309
|
if (record.type === "error") {
|
|
308
310
|
const errorStr = normalizeError(record.payload.error);
|
|
309
311
|
newState = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["useMastraClient","RequestContext"],"sources":["../../../src/hooks/templates/use-templates.ts"],"sourcesContent":["import type { MastraClient, TemplateInstallationRequest } from '@mastra/client-js';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery, useMutation } from '@tanstack/react-query';\nimport { useState } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\nexport interface Template {\n slug: string;\n title: string;\n description: string;\n longDescription: string;\n githubUrl: string;\n tags: string[];\n imageURL?: string;\n codeExample?: string;\n agents?: string[];\n tools?: string[];\n workflows?: string[];\n mcp?: string[];\n networks?: string[];\n videoURL?: string;\n useCase: string;\n supportedProviders: string[];\n}\n\nasync function getMastraTemplateRepos(): Promise<{ templates: Template[]; tags: string[]; providers: string[] }> {\n const response = await fetch('https://mastra.ai/api/templates.json');\n if (!response.ok) {\n throw new Error(`Failed to fetch templates: ${response.statusText}`);\n }\n const templates = await response.json();\n const allTemplates = [\n {\n title: 'Weather Agent',\n slug: 'weather-agent',\n githubUrl: 'https://github.com/mastra-ai/weather-agent',\n description: 'Get weather information of any city.',\n longDescription: 'One Agent, one Workflow and one Tool to bring you the weather in your city.',\n imageURL: '',\n tags: ['Agent', 'Workflow', 'Tool'],\n useCase: '',\n supportedProviders: ['openai', 'anthropic', 'google', 'groq'],\n agents: ['weatherAgent'],\n tools: ['weatherTool'],\n workflows: ['weatherWorkflow'],\n },\n ...templates,\n ];\n\n const allTags = Array.from(new Set(allTemplates.flatMap(t => t.tags)));\n const allProviders = Array.from(new Set(allTemplates.flatMap(t => t.supportedProviders)));\n\n return {\n templates: allTemplates,\n tags: allTags,\n providers: allProviders,\n };\n}\n\nasync function getTemplateRepoByRepoName({ repo, owner }: { repo: string; owner: string }): Promise<Template> {\n const response = await fetch(`https://api.github.com/repos/${owner}/${repo}`);\n if (!response.ok) {\n throw new Error(`Failed to fetch template: ${response.statusText}`);\n }\n const repoInfo = await response.json();\n if (!repoInfo.is_template) {\n throw new Error('Repo is not a template, please update the repo settings to make it a template');\n }\n\n return {\n title: repoInfo.name,\n slug: repoInfo.name,\n description: repoInfo.description ?? '',\n imageURL: '',\n tags: [],\n useCase: '',\n longDescription: repoInfo.description ?? '',\n githubUrl: repoInfo.html_url,\n supportedProviders: [],\n };\n}\n\nasync function getTemplateRepo({ repoOrSlug, owner }: { repoOrSlug: string; owner: string }): Promise<Template> {\n const { templates } = await getMastraTemplateRepos();\n const template = templates.find(t => t.slug === repoOrSlug);\n\n if (!template) {\n if (owner === 'mastra-ai' && repoOrSlug.startsWith('template-')) {\n const templateRepo = templates.find(template => `template-${template.slug}` === repoOrSlug);\n if (templateRepo) {\n return templateRepo;\n }\n }\n\n const templateRepo = await getTemplateRepoByRepoName({ repo: repoOrSlug, owner });\n\n if (templateRepo) {\n return templateRepo;\n }\n\n throw new Error(`Template ${repoOrSlug} not found`);\n }\n\n return template;\n}\n\nasync function getTemplateRepoEnvVars({\n repo,\n owner,\n branch,\n}: {\n repo: string;\n owner: string;\n branch: string;\n}): Promise<Record<string, string>> {\n const envUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/.env.example`;\n const envResponse = await fetch(envUrl);\n\n if (envResponse.ok) {\n const envContent = await envResponse.text();\n const envVars = envContent.split('\\n').reduce(\n (acc, line) => {\n if (!line || line.startsWith('#')) return acc; // Skip empty lines and comments\n\n const [key, value] = line.split('=');\n\n if (key) {\n acc[key] = value?.split('')?.every(item => item === '*') ? '' : value?.replaceAll('\"', '');\n }\n return acc;\n },\n {} as Record<string, string>,\n );\n\n return envVars;\n }\n\n return {};\n}\n\ntype MastraTemplateRepos = Awaited<ReturnType<typeof getMastraTemplateRepos>>;\ntype TemplateRepo = Awaited<ReturnType<typeof getTemplateRepo>>;\ntype TemplateRepoEnvVars = Awaited<ReturnType<typeof getTemplateRepoEnvVars>>;\ntype AgentBuilderWorkflowDetails = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['details']>>;\ntype TemplateInstallRun = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['createRun']>>;\ntype TemplateInstallRunById = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['runById']>>;\ntype StreamTemplateInstallVariables = {\n inputData: TemplateInstallationRequest;\n selectedModel: { provider: string; modelId: string };\n runId: string;\n};\n\nexport const useMastraTemplates = <TData = MastraTemplateRepos>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<MastraTemplateRepos, TData> } = {}): UseQueryResult<TData, Error> => {\n return useQuery<MastraTemplateRepos, Error, TData>({\n queryKey: ['mastra-templates'],\n queryFn: getMastraTemplateRepos,\n ...queryOptions,\n });\n};\n\nexport const useTemplateRepo = <TData = TemplateRepo>({\n repoOrSlug,\n owner,\n queryOptions,\n}: {\n repoOrSlug: string;\n owner: string;\n queryOptions?: MastraQueryOptions<TemplateRepo, TData>;\n}): UseQueryResult<TData, Error> => {\n return useQuery<TemplateRepo, Error, TData>({\n queryKey: ['template-repo', repoOrSlug, owner],\n queryFn: () => getTemplateRepo({ repoOrSlug, owner }),\n ...queryOptions,\n });\n};\n\nexport const useTemplateRepoEnvVars = <TData = TemplateRepoEnvVars>({\n repo,\n owner,\n branch,\n queryOptions,\n}: {\n repo: string;\n owner: string;\n branch: string;\n queryOptions?: MastraQueryOptions<TemplateRepoEnvVars, TData>;\n}): UseQueryResult<TData, Error> => {\n return useQuery<TemplateRepoEnvVars, Error, TData>({\n queryKey: ['template-repo-env-vars', repo, owner, branch],\n queryFn: () => getTemplateRepoEnvVars({ repo, owner, branch }),\n ...queryOptions,\n });\n};\n\nexport const useAgentBuilderWorkflow = <TData = AgentBuilderWorkflowDetails>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<AgentBuilderWorkflowDetails, TData> } = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n return useQuery<AgentBuilderWorkflowDetails, Error, TData>({\n queryKey: ['agent-builder-workflow'],\n queryFn: async () => {\n return await client.getAgentBuilderAction('merge-template').details();\n },\n ...queryOptions,\n });\n};\n\nexport const useCreateTemplateInstallRun = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TemplateInstallRun, { runId?: string }> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ runId }: { runId?: string }) => {\n return await client.getAgentBuilderAction('merge-template').createRun({ runId });\n },\n ...queryOptions,\n });\n};\n\nexport const useGetTemplateInstallRun = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TemplateInstallRunById, { runId: string }> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ runId }: { runId: string }) => {\n return await client.getAgentBuilderAction('merge-template').runById(runId);\n },\n ...queryOptions,\n });\n};\n\nconst normalizeError = (error: unknown): string => {\n if (typeof error === 'string') return error;\n if (error == null) return 'Unknown error';\n if (error instanceof Error)\n return typeof error.message === 'string' && error.message.length > 0 ? error.message : 'Unknown error';\n if (typeof error === 'object') {\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n }\n return String(error);\n};\n\n// Helper function to process template installation records (like workflows' sanitizeWorkflowWatchResult)\nconst processTemplateInstallRecord = (\n record: { type: string; payload: any; runId?: string; eventTimestamp?: string },\n currentState: any,\n workflowInfo?: any,\n): { newState: any } => {\n let newState = { ...currentState };\n\n // Initialize steps if not present or empty\n const hasSteps =\n newState.payload?.workflowState?.steps && Object.keys(newState.payload.workflowState.steps).length > 0;\n if (!hasSteps && workflowInfo?.allSteps) {\n newState.payload = {\n ...newState.payload,\n workflowState: {\n ...newState.payload?.workflowState,\n steps: Object.keys(workflowInfo.allSteps).reduce((acc, stepId) => {\n acc[stepId] = {\n id: stepId,\n description: workflowInfo.allSteps[stepId].description,\n status: 'pending',\n };\n return acc;\n }, {} as any),\n },\n };\n }\n\n // Handle different event types\n // Support both legacy ('start') and VNext ('workflow-start') formats\n if (record.type === 'start' || record.type === 'workflow-start') {\n // Pre-populate all workflow steps from workflowInfo if available\n const initialSteps: any = {};\n if (workflowInfo?.allSteps) {\n Object.entries(workflowInfo.allSteps).forEach(([stepId, stepData]: [string, any]) => {\n initialSteps[stepId] = {\n id: stepData.id,\n description: stepData.description,\n status: 'pending',\n };\n });\n }\n\n const runId = record.runId || record.payload?.runId;\n\n newState = {\n ...newState,\n runId,\n eventTimestamp: new Date().toISOString(),\n status: 'running',\n phase: 'initializing',\n payload: {\n workflowState: {\n status: 'running',\n steps: initialSteps,\n },\n currentStep: null,\n },\n };\n }\n\n // Support both legacy ('step-start') and VNext ('workflow-step-start') formats\n if (record.type === 'step-start' || record.type === 'workflow-step-start') {\n const stepId = record.payload.id;\n newState = {\n ...newState,\n phase: 'processing',\n payload: {\n ...newState.payload,\n currentStep: {\n id: stepId,\n status: 'running',\n startTime: new Date(),\n ...record.payload,\n },\n workflowState: {\n ...newState.payload.workflowState,\n steps: {\n ...newState.payload.workflowState.steps,\n [stepId]: {\n ...newState.payload.workflowState.steps[stepId],\n status: 'running',\n startTime: new Date(),\n ...record.payload,\n },\n },\n },\n },\n };\n }\n\n // Support both legacy ('step-result') and VNext ('workflow-step-result') formats\n if (record.type === 'step-result' || record.type === 'workflow-step-result') {\n const stepId = record.payload.id;\n const status = record.payload.status;\n const hasError = record.payload.error;\n newState = {\n ...newState,\n payload: {\n ...newState.payload,\n currentStep: {\n ...newState.payload.currentStep,\n status: record.payload.status,\n output: record.payload.output,\n error: record.payload.error,\n endTime: new Date(),\n },\n workflowState: {\n ...newState.payload.workflowState,\n steps: {\n ...newState.payload.workflowState.steps,\n [stepId]: {\n ...newState.payload.workflowState.steps[stepId],\n status: record.payload.status,\n output: record.payload.output,\n error: record.payload.error,\n endTime: new Date(),\n },\n },\n },\n },\n };\n\n // If this step failed, also set workflow-level error state\n if (status === 'failed' && hasError) {\n const errorString = normalizeError(hasError);\n newState = {\n ...newState,\n status: 'failed',\n error: errorString,\n phase: 'error',\n failedStep: {\n id: stepId,\n error: errorString,\n description: record.payload.description || stepId,\n },\n payload: {\n ...newState.payload,\n workflowState: {\n ...newState.payload.workflowState,\n status: 'failed',\n },\n },\n errorTimestamp: new Date(),\n };\n }\n }\n\n // Support both legacy ('step-finish') and VNext ('workflow-step-finish') formats\n if (record.type === 'step-finish' || record.type === 'workflow-step-finish') {\n newState = {\n ...newState,\n payload: {\n ...newState.payload,\n currentStep: null,\n },\n };\n }\n\n // Support both legacy ('finish') and VNext ('workflow-finish') formats\n if (record.type === 'finish' || record.type === 'workflow-finish') {\n // Don't override error states - if we're already in error phase, stay there\n if (newState.phase === 'error' || newState.status === 'failed') {\n newState = {\n ...newState,\n // Keep existing status, phase, error, failedStep\n completedAt: new Date(),\n };\n } else {\n // Normal completion flow\n newState = {\n ...newState,\n status: record.payload.status || 'completed',\n phase: 'completed',\n payload: {\n ...newState.payload,\n currentStep: null,\n workflowState: {\n ...newState.payload.workflowState,\n status: record.payload.status || 'completed',\n },\n },\n completedAt: new Date(),\n };\n }\n }\n\n if (record.type === 'error') {\n const errorStr = normalizeError(record.payload.error);\n newState = {\n ...newState,\n status: 'failed',\n error: errorStr,\n phase: 'error',\n payload: {\n ...newState.payload,\n workflowState: {\n ...newState.payload.workflowState,\n status: 'failed',\n },\n },\n errorTimestamp: new Date(),\n };\n }\n\n return { newState };\n};\n\n// Shared localStorage helpers for template installation state\nconst saveTemplateStateToLocalStorage = (runId: string, state: any) => {\n try {\n localStorage.setItem(\n `template-install-${runId}`,\n JSON.stringify({\n state,\n timestamp: Date.now(),\n }),\n );\n } catch (error) {\n console.warn('Failed to save template state to localStorage:', error);\n }\n};\n\n// Shared helper for processing template installation streams (streamlined)\nconst useTemplateStreamProcessor = (workflowInfo?: any, runId?: string) => {\n const [streamResult, setStreamResult] = useState<any>({});\n const [isStreaming, setIsStreaming] = useState(false);\n\n const processStream = async (stream: any, initialRunId?: string) => {\n setIsStreaming(true);\n setStreamResult({});\n\n if (!stream) throw new Error('No stream returned');\n\n const reader = stream.getReader();\n\n // Initialize minimal state - don't set immediately, let events drive the state\n let currentState: any = {\n runId: initialRunId || runId,\n eventTimestamp: new Date().toISOString(),\n phase: 'running',\n payload: {\n workflowState: {\n steps: {},\n },\n currentStep: null,\n },\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n const { newState } = processTemplateInstallRecord(value, currentState, workflowInfo);\n\n currentState = newState;\n setStreamResult(newState);\n\n // Save to localStorage for refresh recovery (same as watch)\n if (value.runId || initialRunId || runId) {\n const effectiveRunId = value.runId || initialRunId || runId;\n saveTemplateStateToLocalStorage(effectiveRunId, newState);\n }\n }\n } catch (error) {\n console.error('💥 [processStream] Error processing template installation stream:', error);\n\n // Use the helper for error handling too\n const { newState } = processTemplateInstallRecord(\n { type: 'error', payload: { error: error instanceof Error ? error.message : 'Unknown error' } },\n currentState,\n workflowInfo,\n );\n\n setStreamResult(newState);\n } finally {\n setIsStreaming(false);\n reader.releaseLock();\n }\n };\n\n return {\n streamResult,\n isStreaming,\n processStream,\n };\n};\n\nexport const useStreamTemplateInstall = ({\n workflowInfo,\n queryOptions,\n}: {\n workflowInfo?: any;\n queryOptions?: { streamInstall?: MastraMutationOptions<void, StreamTemplateInstallVariables> };\n} = {}) => {\n const client = useMastraClient();\n const { streamResult, isStreaming, processStream } = useTemplateStreamProcessor(workflowInfo);\n\n const streamInstall = useMutation({\n mutationFn: async ({ inputData, selectedModel, runId }: StreamTemplateInstallVariables) => {\n const maxRetries = 3;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n const template = client.getAgentBuilderAction('merge-template');\n const requestContext = new RequestContext();\n requestContext.set('selectedModel', selectedModel);\n const stream = await template.stream({ inputData, requestContext }, runId);\n await processStream(stream, runId);\n\n // If we get here, the stream completed successfully\n return;\n } catch (error: any) {\n console.error(`💥 [streamInstall] Attempt ${attempt} failed:`, error);\n const isNetworkError =\n error?.message?.includes('Failed to fetch') ||\n error?.message?.includes('NetworkError') ||\n error?.message?.includes('network error') ||\n error?.message?.includes('fetch') ||\n error?.code === 'NETWORK_ERROR' ||\n error?.name === 'TypeError';\n\n console.warn(`Stream attempt ${attempt}/${maxRetries} failed:`, error);\n\n if (isNetworkError) {\n // For stream network errors, provide helpful message since switching context is complex\n const errorMessage = runId\n ? `Network error during template installation (likely hot reload). Please refresh the page to resume from where you left off using runId: ${runId}`\n : 'Network error during template installation (likely hot reload). Please try again.';\n\n console.error('🔌 Stream network error:', errorMessage);\n throw new Error(errorMessage);\n }\n\n // If it's not a network error or we've exhausted retries, throw\n console.error('❌ [streamInstall] Non-network error or max retries reached, throwing:', error);\n throw error;\n }\n }\n },\n ...queryOptions?.streamInstall,\n });\n\n return {\n streamInstall,\n streamResult,\n isStreaming,\n };\n};\n\n/**\n * Hook for observing template installation with full replay capability.\n * Uses observeStream() which replays cached execution from beginning, then continues live.\n */\nexport const useObserveStreamTemplateInstall = ({\n workflowInfo,\n queryOptions,\n}: {\n workflowInfo?: any;\n queryOptions?: { observeInstall?: MastraMutationOptions<void, { runId: string }> };\n} = {}) => {\n const client = useMastraClient();\n const { streamResult, isStreaming, processStream } = useTemplateStreamProcessor(workflowInfo);\n\n const observeInstall = useMutation({\n mutationFn: async ({ runId }: { runId: string }) => {\n const maxRetries = 3;\n const retryDelay = 2000; // 2 seconds\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n // Initialize state - but observeStream will replay full history\n // so we don't need to rely on localStorage as fallback\n const template = client.getAgentBuilderAction('merge-template');\n\n // Use observeStream to get full replay + live updates\n const stream = await template.observeStream({ runId });\n await processStream(stream, runId);\n\n // If we get here, the observe stream completed successfully\n return;\n } catch (error: any) {\n console.error(`💥 [observeInstall] Attempt ${attempt} failed:`, error);\n const isNetworkError =\n error?.message?.includes('Failed to fetch') ||\n error?.message?.includes('NetworkError') ||\n error?.message?.includes('network error') ||\n error?.message?.includes('fetch') ||\n error?.code === 'NETWORK_ERROR' ||\n error?.name === 'TypeError';\n\n console.warn(`ObserveStream attempt ${attempt}/${maxRetries} failed:`, error);\n\n if (isNetworkError && attempt < maxRetries) {\n console.info(\n `🔄 ObserveStream network error detected (likely hot reload), retrying in ${retryDelay}ms... (attempt ${attempt + 1}/${maxRetries})`,\n );\n await new Promise(resolve => setTimeout(resolve, retryDelay));\n continue; // Retry\n }\n\n // If it's not a network error or we've exhausted retries, throw\n console.error('❌ [observeInstall] Non-network error or max retries reached, throwing:', error);\n throw error;\n }\n }\n },\n ...queryOptions?.observeInstall,\n });\n\n return {\n observeInstall,\n streamResult,\n isStreaming,\n };\n};\n"],"mappings":";;;;;;AA2BA,eAAe,yBAAkG;CAC/G,MAAM,WAAW,MAAM,MAAM,sCAAsC;CACnE,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,8BAA8B,SAAS,YAAY;CAGrE,MAAM,eAAe,CACnB;EACE,OAAO;EACP,MAAM;EACN,WAAW;EACX,aAAa;EACb,iBAAiB;EACjB,UAAU;EACV,MAAM;GAAC;GAAS;GAAY;EAAM;EAClC,SAAS;EACT,oBAAoB;GAAC;GAAU;GAAa;GAAU;EAAM;EAC5D,QAAQ,CAAC,cAAc;EACvB,OAAO,CAAC,aAAa;EACrB,WAAW,CAAC,iBAAiB;CAC/B,GACA,GAAG,MAhBmB,SAAS,KAAK,CAiBtC;CAKA,OAAO;EACL,WAAW;EACX,MALc,MAAM,KAAK,IAAI,IAAI,aAAa,SAAQ,MAAK,EAAE,IAAI,CAAC,CAKtD;EACZ,WALmB,MAAM,KAAK,IAAI,IAAI,aAAa,SAAQ,MAAK,EAAE,kBAAkB,CAAC,CAK/D;CACxB;AACF;AAEA,eAAe,0BAA0B,EAAE,MAAM,SAA6D;CAC5G,MAAM,WAAW,MAAM,MAAM,gCAAgC,MAAM,GAAG,MAAM;CAC5E,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,6BAA6B,SAAS,YAAY;CAEpE,MAAM,WAAW,MAAM,SAAS,KAAK;CACrC,IAAI,CAAC,SAAS,aACZ,MAAM,IAAI,MAAM,+EAA+E;CAGjG,OAAO;EACL,OAAO,SAAS;EAChB,MAAM,SAAS;EACf,aAAa,SAAS,eAAe;EACrC,UAAU;EACV,MAAM,CAAC;EACP,SAAS;EACT,iBAAiB,SAAS,e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BAAiB,KAC1C,OAAO,SAAS,SAAS,cAAc,KACvC,OAAO,SAAS,SAAS,eAAe,KACxC,OAAO,SAAS,SAAS,OAAO,KAChC,OAAO,SAAS,mBAChB,OAAO,SAAS;KAElB,QAAQ,KAAK,yBAAyB,QAAQ,GAAG,WAAW,WAAW,KAAK;KAE5E,IAAI,kBAAkB,UAAU,YAAY;MAC1C,QAAQ,KACN,4EAA4E,WAAW,iBAAiB,UAAU,EAAE,GAAG,WAAW,EACpI;MACA,MAAM,IAAI,SAAQ,YAAW,WAAW,SAAS,UAAU,CAAC;MAC5D;KACF;KAGA,QAAQ,MAAM,0EAA0E,KAAK;KAC7F,MAAM;IACR;GAEJ;GACA,GAAG,cAAc;EACnB,CAGe;EACb;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["useQuery","useMastraClient","useMutation","useState","RequestContext"],"sources":["../../../src/hooks/templates/use-templates.ts"],"sourcesContent":["import type { MastraClient, TemplateInstallationRequest } from '@mastra/client-js';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery, useMutation } from '@tanstack/react-query';\nimport { useState } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\nexport interface Template {\n slug: string;\n title: string;\n description: string;\n longDescription: string;\n githubUrl: string;\n tags: string[];\n imageURL?: string;\n codeExample?: string;\n agents?: string[];\n tools?: string[];\n workflows?: string[];\n mcp?: string[];\n networks?: string[];\n videoURL?: string;\n useCase: string;\n supportedProviders: string[];\n}\n\nasync function getMastraTemplateRepos(): Promise<{ templates: Template[]; tags: string[]; providers: string[] }> {\n const response = await fetch('https://mastra.ai/api/templates.json');\n if (!response.ok) {\n throw new Error(`Failed to fetch templates: ${response.statusText}`);\n }\n const templates = await response.json();\n const allTemplates = [\n {\n title: 'Weather Agent',\n slug: 'weather-agent',\n githubUrl: 'https://github.com/mastra-ai/weather-agent',\n description: 'Get weather information of any city.',\n longDescription: 'One Agent, one Workflow and one Tool to bring you the weather in your city.',\n imageURL: '',\n tags: ['Agent', 'Workflow', 'Tool'],\n useCase: '',\n supportedProviders: ['openai', 'anthropic', 'google', 'groq'],\n agents: ['weatherAgent'],\n tools: ['weatherTool'],\n workflows: ['weatherWorkflow'],\n },\n ...templates,\n ];\n\n const allTags = Array.from(new Set(allTemplates.flatMap(t => t.tags)));\n const allProviders = Array.from(new Set(allTemplates.flatMap(t => t.supportedProviders)));\n\n return {\n templates: allTemplates,\n tags: allTags,\n providers: allProviders,\n };\n}\n\nasync function getTemplateRepoByRepoName({ repo, owner }: { repo: string; owner: string }): Promise<Template> {\n const response = await fetch(`https://api.github.com/repos/${owner}/${repo}`);\n if (!response.ok) {\n throw new Error(`Failed to fetch template: ${response.statusText}`);\n }\n const repoInfo = await response.json();\n if (!repoInfo.is_template) {\n throw new Error('Repo is not a template, please update the repo settings to make it a template');\n }\n\n return {\n title: repoInfo.name,\n slug: repoInfo.name,\n description: repoInfo.description ?? '',\n imageURL: '',\n tags: [],\n useCase: '',\n longDescription: repoInfo.description ?? '',\n githubUrl: repoInfo.html_url,\n supportedProviders: [],\n };\n}\n\nasync function getTemplateRepo({ repoOrSlug, owner }: { repoOrSlug: string; owner: string }): Promise<Template> {\n const { templates } = await getMastraTemplateRepos();\n const template = templates.find(t => t.slug === repoOrSlug);\n\n if (!template) {\n if (owner === 'mastra-ai' && repoOrSlug.startsWith('template-')) {\n const templateRepo = templates.find(template => `template-${template.slug}` === repoOrSlug);\n if (templateRepo) {\n return templateRepo;\n }\n }\n\n const templateRepo = await getTemplateRepoByRepoName({ repo: repoOrSlug, owner });\n\n if (templateRepo) {\n return templateRepo;\n }\n\n throw new Error(`Template ${repoOrSlug} not found`);\n }\n\n return template;\n}\n\nasync function getTemplateRepoEnvVars({\n repo,\n owner,\n branch,\n}: {\n repo: string;\n owner: string;\n branch: string;\n}): Promise<Record<string, string>> {\n const envUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/.env.example`;\n const envResponse = await fetch(envUrl);\n\n if (envResponse.ok) {\n const envContent = await envResponse.text();\n const envVars = envContent.split('\\n').reduce(\n (acc, line) => {\n if (!line || line.startsWith('#')) return acc; // Skip empty lines and comments\n\n const [key, value] = line.split('=');\n\n if (key) {\n acc[key] = value?.split('')?.every(item => item === '*') ? '' : value?.replaceAll('\"', '');\n }\n return acc;\n },\n {} as Record<string, string>,\n );\n\n return envVars;\n }\n\n return {};\n}\n\ntype MastraTemplateRepos = Awaited<ReturnType<typeof getMastraTemplateRepos>>;\ntype TemplateRepo = Awaited<ReturnType<typeof getTemplateRepo>>;\ntype TemplateRepoEnvVars = Awaited<ReturnType<typeof getTemplateRepoEnvVars>>;\ntype AgentBuilderWorkflowDetails = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['details']>>;\ntype TemplateInstallRun = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['createRun']>>;\ntype TemplateInstallRunById = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['runById']>>;\ntype StreamTemplateInstallVariables = {\n inputData: TemplateInstallationRequest;\n selectedModel: { provider: string; modelId: string };\n runId: string;\n};\n\nexport const useMastraTemplates = <TData = MastraTemplateRepos>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<MastraTemplateRepos, TData> } = {}): UseQueryResult<TData, Error> => {\n return useQuery<MastraTemplateRepos, Error, TData>({\n queryKey: ['mastra-templates'],\n queryFn: getMastraTemplateRepos,\n ...queryOptions,\n });\n};\n\nexport const useTemplateRepo = <TData = TemplateRepo>({\n repoOrSlug,\n owner,\n queryOptions,\n}: {\n repoOrSlug: string;\n owner: string;\n queryOptions?: MastraQueryOptions<TemplateRepo, TData>;\n}): UseQueryResult<TData, Error> => {\n return useQuery<TemplateRepo, Error, TData>({\n queryKey: ['template-repo', repoOrSlug, owner],\n queryFn: () => getTemplateRepo({ repoOrSlug, owner }),\n ...queryOptions,\n });\n};\n\nexport const useTemplateRepoEnvVars = <TData = TemplateRepoEnvVars>({\n repo,\n owner,\n branch,\n queryOptions,\n}: {\n repo: string;\n owner: string;\n branch: string;\n queryOptions?: MastraQueryOptions<TemplateRepoEnvVars, TData>;\n}): UseQueryResult<TData, Error> => {\n return useQuery<TemplateRepoEnvVars, Error, TData>({\n queryKey: ['template-repo-env-vars', repo, owner, branch],\n queryFn: () => getTemplateRepoEnvVars({ repo, owner, branch }),\n ...queryOptions,\n });\n};\n\nexport const useAgentBuilderWorkflow = <TData = AgentBuilderWorkflowDetails>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<AgentBuilderWorkflowDetails, TData> } = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n return useQuery<AgentBuilderWorkflowDetails, Error, TData>({\n queryKey: ['agent-builder-workflow'],\n queryFn: async () => {\n return await client.getAgentBuilderAction('merge-template').details();\n },\n ...queryOptions,\n });\n};\n\nexport const useCreateTemplateInstallRun = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TemplateInstallRun, { runId?: string }> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ runId }: { runId?: string }) => {\n return await client.getAgentBuilderAction('merge-template').createRun({ runId });\n },\n ...queryOptions,\n });\n};\n\nexport const useGetTemplateInstallRun = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TemplateInstallRunById, { runId: string }> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ runId }: { runId: string }) => {\n return await client.getAgentBuilderAction('merge-template').runById(runId);\n },\n ...queryOptions,\n });\n};\n\nconst normalizeError = (error: unknown): string => {\n if (typeof error === 'string') return error;\n if (error == null) return 'Unknown error';\n if (error instanceof Error)\n return typeof error.message === 'string' && error.message.length > 0 ? error.message : 'Unknown error';\n if (typeof error === 'object') {\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n }\n return String(error);\n};\n\n// Helper function to process template installation records (like workflows' sanitizeWorkflowWatchResult)\nconst processTemplateInstallRecord = (\n record: { type: string; payload: any; runId?: string; eventTimestamp?: string },\n currentState: any,\n workflowInfo?: any,\n): { newState: any } => {\n let newState = { ...currentState };\n\n // Initialize steps if not present or empty\n const hasSteps =\n newState.payload?.workflowState?.steps && Object.keys(newState.payload.workflowState.steps).length > 0;\n if (!hasSteps && workflowInfo?.allSteps) {\n newState.payload = {\n ...newState.payload,\n workflowState: {\n ...newState.payload?.workflowState,\n steps: Object.keys(workflowInfo.allSteps).reduce((acc, stepId) => {\n acc[stepId] = {\n id: stepId,\n description: workflowInfo.allSteps[stepId].description,\n status: 'pending',\n };\n return acc;\n }, {} as any),\n },\n };\n }\n\n // Handle different event types\n // Support both legacy ('start') and VNext ('workflow-start') formats\n if (record.type === 'start' || record.type === 'workflow-start') {\n // Pre-populate all workflow steps from workflowInfo if available\n const initialSteps: any = {};\n if (workflowInfo?.allSteps) {\n Object.entries(workflowInfo.allSteps).forEach(([stepId, stepData]: [string, any]) => {\n initialSteps[stepId] = {\n id: stepData.id,\n description: stepData.description,\n status: 'pending',\n };\n });\n }\n\n const runId = record.runId || record.payload?.runId;\n\n newState = {\n ...newState,\n runId,\n eventTimestamp: new Date().toISOString(),\n status: 'running',\n phase: 'initializing',\n payload: {\n workflowState: {\n status: 'running',\n steps: initialSteps,\n },\n currentStep: null,\n },\n };\n }\n\n // Support both legacy ('step-start') and VNext ('workflow-step-start') formats\n if (record.type === 'step-start' || record.type === 'workflow-step-start') {\n const stepId = record.payload.id;\n newState = {\n ...newState,\n phase: 'processing',\n payload: {\n ...newState.payload,\n currentStep: {\n id: stepId,\n status: 'running',\n startTime: new Date(),\n ...record.payload,\n },\n workflowState: {\n ...newState.payload.workflowState,\n steps: {\n ...newState.payload.workflowState.steps,\n [stepId]: {\n ...newState.payload.workflowState.steps[stepId],\n status: 'running',\n startTime: new Date(),\n ...record.payload,\n },\n },\n },\n },\n };\n }\n\n // Support both legacy ('step-result') and VNext ('workflow-step-result') formats\n if (record.type === 'step-result' || record.type === 'workflow-step-result') {\n const stepId = record.payload.id;\n const status = record.payload.status;\n const hasError = record.payload.error;\n newState = {\n ...newState,\n payload: {\n ...newState.payload,\n currentStep: {\n ...newState.payload.currentStep,\n status: record.payload.status,\n output: record.payload.output,\n error: record.payload.error,\n endTime: new Date(),\n },\n workflowState: {\n ...newState.payload.workflowState,\n steps: {\n ...newState.payload.workflowState.steps,\n [stepId]: {\n ...newState.payload.workflowState.steps[stepId],\n status: record.payload.status,\n output: record.payload.output,\n error: record.payload.error,\n endTime: new Date(),\n },\n },\n },\n },\n };\n\n // If this step failed, also set workflow-level error state\n if (status === 'failed' && hasError) {\n const errorString = normalizeError(hasError);\n newState = {\n ...newState,\n status: 'failed',\n error: errorString,\n phase: 'error',\n failedStep: {\n id: stepId,\n error: errorString,\n description: record.payload.description || stepId,\n },\n payload: {\n ...newState.payload,\n workflowState: {\n ...newState.payload.workflowState,\n status: 'failed',\n },\n },\n errorTimestamp: new Date(),\n };\n }\n }\n\n // Support both legacy ('step-finish') and VNext ('workflow-step-finish') formats\n if (record.type === 'step-finish' || record.type === 'workflow-step-finish') {\n newState = {\n ...newState,\n payload: {\n ...newState.payload,\n currentStep: null,\n },\n };\n }\n\n // Support both legacy ('finish') and VNext ('workflow-finish') formats\n if (record.type === 'finish' || record.type === 'workflow-finish') {\n // Don't override error states - if we're already in error phase, stay there\n if (newState.phase === 'error' || newState.status === 'failed') {\n newState = {\n ...newState,\n // Keep existing status, phase, error, failedStep\n completedAt: new Date(),\n };\n } else {\n // Normal completion flow\n newState = {\n ...newState,\n status: record.payload.status || 'completed',\n phase: 'completed',\n payload: {\n ...newState.payload,\n currentStep: null,\n workflowState: {\n ...newState.payload.workflowState,\n status: record.payload.status || 'completed',\n },\n },\n completedAt: new Date(),\n };\n }\n }\n\n if (record.type === 'error') {\n const errorStr = normalizeError(record.payload.error);\n newState = {\n ...newState,\n status: 'failed',\n error: errorStr,\n phase: 'error',\n payload: {\n ...newState.payload,\n workflowState: {\n ...newState.payload.workflowState,\n status: 'failed',\n },\n },\n errorTimestamp: new Date(),\n };\n }\n\n return { newState };\n};\n\n// Shared localStorage helpers for template installation state\nconst saveTemplateStateToLocalStorage = (runId: string, state: any) => {\n try {\n localStorage.setItem(\n `template-install-${runId}`,\n JSON.stringify({\n state,\n timestamp: Date.now(),\n }),\n );\n } catch (error) {\n console.warn('Failed to save template state to localStorage:', error);\n }\n};\n\n// Shared helper for processing template installation streams (streamlined)\nconst useTemplateStreamProcessor = (workflowInfo?: any, runId?: string) => {\n const [streamResult, setStreamResult] = useState<any>({});\n const [isStreaming, setIsStreaming] = useState(false);\n\n const processStream = async (stream: any, initialRunId?: string) => {\n setIsStreaming(true);\n setStreamResult({});\n\n if (!stream) throw new Error('No stream returned');\n\n const reader = stream.getReader();\n\n // Initialize minimal state - don't set immediately, let events drive the state\n let currentState: any = {\n runId: initialRunId || runId,\n eventTimestamp: new Date().toISOString(),\n phase: 'running',\n payload: {\n workflowState: {\n steps: {},\n },\n currentStep: null,\n },\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n const { newState } = processTemplateInstallRecord(value, currentState, workflowInfo);\n\n currentState = newState;\n setStreamResult(newState);\n\n // Save to localStorage for refresh recovery (same as watch)\n if (value.runId || initialRunId || runId) {\n const effectiveRunId = value.runId || initialRunId || runId;\n saveTemplateStateToLocalStorage(effectiveRunId, newState);\n }\n }\n } catch (error) {\n console.error('💥 [processStream] Error processing template installation stream:', error);\n\n // Use the helper for error handling too\n const { newState } = processTemplateInstallRecord(\n { type: 'error', payload: { error: error instanceof Error ? error.message : 'Unknown error' } },\n currentState,\n workflowInfo,\n );\n\n setStreamResult(newState);\n } finally {\n setIsStreaming(false);\n reader.releaseLock();\n }\n };\n\n return {\n streamResult,\n isStreaming,\n processStream,\n };\n};\n\nexport const useStreamTemplateInstall = ({\n workflowInfo,\n queryOptions,\n}: {\n workflowInfo?: any;\n queryOptions?: { streamInstall?: MastraMutationOptions<void, StreamTemplateInstallVariables> };\n} = {}) => {\n const client = useMastraClient();\n const { streamResult, isStreaming, processStream } = useTemplateStreamProcessor(workflowInfo);\n\n const streamInstall = useMutation({\n mutationFn: async ({ inputData, selectedModel, runId }: StreamTemplateInstallVariables) => {\n const maxRetries = 3;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n const template = client.getAgentBuilderAction('merge-template');\n const requestContext = new RequestContext();\n requestContext.set('selectedModel', selectedModel);\n const stream = await template.stream({ inputData, requestContext }, runId);\n await processStream(stream, runId);\n\n // If we get here, the stream completed successfully\n return;\n } catch (error: any) {\n console.error(`💥 [streamInstall] Attempt ${attempt} failed:`, error);\n const isNetworkError =\n error?.message?.includes('Failed to fetch') ||\n error?.message?.includes('NetworkError') ||\n error?.message?.includes('network error') ||\n error?.message?.includes('fetch') ||\n error?.code === 'NETWORK_ERROR' ||\n error?.name === 'TypeError';\n\n console.warn(`Stream attempt ${attempt}/${maxRetries} failed:`, error);\n\n if (isNetworkError) {\n // For stream network errors, provide helpful message since switching context is complex\n const errorMessage = runId\n ? `Network error during template installation (likely hot reload). Please refresh the page to resume from where you left off using runId: ${runId}`\n : 'Network error during template installation (likely hot reload). Please try again.';\n\n console.error('🔌 Stream network error:', errorMessage);\n throw new Error(errorMessage);\n }\n\n // If it's not a network error or we've exhausted retries, throw\n console.error('❌ [streamInstall] Non-network error or max retries reached, throwing:', error);\n throw error;\n }\n }\n },\n ...queryOptions?.streamInstall,\n });\n\n return {\n streamInstall,\n streamResult,\n isStreaming,\n };\n};\n\n/**\n * Hook for observing template installation with full replay capability.\n * Uses observeStream() which replays cached execution from beginning, then continues live.\n */\nexport const useObserveStreamTemplateInstall = ({\n workflowInfo,\n queryOptions,\n}: {\n workflowInfo?: any;\n queryOptions?: { observeInstall?: MastraMutationOptions<void, { runId: string }> };\n} = {}) => {\n const client = useMastraClient();\n const { streamResult, isStreaming, processStream } = useTemplateStreamProcessor(workflowInfo);\n\n const observeInstall = useMutation({\n mutationFn: async ({ runId }: { runId: string }) => {\n const maxRetries = 3;\n const retryDelay = 2000; // 2 seconds\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n // Initialize state - but observeStream will replay full history\n // so we don't need to rely on localStorage as fallback\n const template = client.getAgentBuilderAction('merge-template');\n\n // Use observeStream to get full replay + live updates\n const stream = await template.observeStream({ runId });\n await processStream(stream, runId);\n\n // If we get here, the observe stream completed successfully\n return;\n } catch (error: any) {\n console.error(`💥 [observeInstall] Attempt ${attempt} failed:`, error);\n const isNetworkError =\n error?.message?.includes('Failed to fetch') ||\n error?.message?.includes('NetworkError') ||\n error?.message?.includes('network error') ||\n error?.message?.includes('fetch') ||\n error?.code === 'NETWORK_ERROR' ||\n error?.name === 'TypeError';\n\n console.warn(`ObserveStream attempt ${attempt}/${maxRetries} failed:`, error);\n\n if (isNetworkError && attempt < maxRetries) {\n console.info(\n `🔄 ObserveStream network error detected (likely hot reload), retrying in ${retryDelay}ms... (attempt ${attempt + 1}/${maxRetries})`,\n );\n await new Promise(resolve => setTimeout(resolve, retryDelay));\n continue; // Retry\n }\n\n // If it's not a network error or we've exhausted retries, throw\n console.error('❌ [observeInstall] Non-network error or max retries reached, throwing:', error);\n throw error;\n }\n }\n },\n ...queryOptions?.observeInstall,\n });\n\n return {\n observeInstall,\n streamResult,\n isStreaming,\n };\n};\n"],"mappings":";;;;;;AA2BA,eAAe,yBAAkG;CAC/G,MAAM,WAAW,MAAM,MAAM,sCAAsC;CACnE,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,8BAA8B,SAAS,YAAY;CAGrE,MAAM,eAAe,CACnB;EACE,OAAO;EACP,MAAM;EACN,WAAW;EACX,aAAa;EACb,iBAAiB;EACjB,UAAU;EACV,MAAM;GAAC;GAAS;GAAY;EAAM;EAClC,SAAS;EACT,oBAAoB;GAAC;GAAU;GAAa;GAAU;EAAM;EAC5D,QAAQ,CAAC,cAAc;EACvB,OAAO,CAAC,aAAa;EACrB,WAAW,CAAC,iBAAiB;CAC/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: null
|
|
286
286
|
}
|
|
287
287
|
};
|
|
288
|
-
if (record.type === "finish" || record.type === "workflow-finish")
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
288
|
+
if (record.type === "finish" || record.type === "workflow-finish") {
|
|
289
|
+
if (newState.phase === "error" || newState.status === "failed") newState = {
|
|
290
|
+
...newState,
|
|
291
|
+
completedAt: /* @__PURE__ */ new Date()
|
|
292
|
+
};
|
|
293
|
+
else newState = {
|
|
294
|
+
...newState,
|
|
295
|
+
status: record.payload.status || "completed",
|
|
296
|
+
phase: "completed",
|
|
297
|
+
payload: {
|
|
298
|
+
...newState.payload,
|
|
299
|
+
currentStep: null,
|
|
300
|
+
workflowState: {
|
|
301
|
+
...newState.payload.workflowState,
|
|
302
|
+
status: record.payload.status || "completed"
|
|
303
|
+
}
|
|
304
|
+
},
|
|
305
|
+
completedAt: /* @__PURE__ */ new Date()
|
|
306
|
+
};
|
|
307
|
+
}
|
|
306
308
|
if (record.type === "error") {
|
|
307
309
|
const errorStr = normalizeError(record.payload.error);
|
|
308
310
|
newState = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/hooks/templates/use-templates.ts"],"sourcesContent":["import type { MastraClient, TemplateInstallationRequest } from '@mastra/client-js';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery, useMutation } from '@tanstack/react-query';\nimport { useState } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\nexport interface Template {\n slug: string;\n title: string;\n description: string;\n longDescription: string;\n githubUrl: string;\n tags: string[];\n imageURL?: string;\n codeExample?: string;\n agents?: string[];\n tools?: string[];\n workflows?: string[];\n mcp?: string[];\n networks?: string[];\n videoURL?: string;\n useCase: string;\n supportedProviders: string[];\n}\n\nasync function getMastraTemplateRepos(): Promise<{ templates: Template[]; tags: string[]; providers: string[] }> {\n const response = await fetch('https://mastra.ai/api/templates.json');\n if (!response.ok) {\n throw new Error(`Failed to fetch templates: ${response.statusText}`);\n }\n const templates = await response.json();\n const allTemplates = [\n {\n title: 'Weather Agent',\n slug: 'weather-agent',\n githubUrl: 'https://github.com/mastra-ai/weather-agent',\n description: 'Get weather information of any city.',\n longDescription: 'One Agent, one Workflow and one Tool to bring you the weather in your city.',\n imageURL: '',\n tags: ['Agent', 'Workflow', 'Tool'],\n useCase: '',\n supportedProviders: ['openai', 'anthropic', 'google', 'groq'],\n agents: ['weatherAgent'],\n tools: ['weatherTool'],\n workflows: ['weatherWorkflow'],\n },\n ...templates,\n ];\n\n const allTags = Array.from(new Set(allTemplates.flatMap(t => t.tags)));\n const allProviders = Array.from(new Set(allTemplates.flatMap(t => t.supportedProviders)));\n\n return {\n templates: allTemplates,\n tags: allTags,\n providers: allProviders,\n };\n}\n\nasync function getTemplateRepoByRepoName({ repo, owner }: { repo: string; owner: string }): Promise<Template> {\n const response = await fetch(`https://api.github.com/repos/${owner}/${repo}`);\n if (!response.ok) {\n throw new Error(`Failed to fetch template: ${response.statusText}`);\n }\n const repoInfo = await response.json();\n if (!repoInfo.is_template) {\n throw new Error('Repo is not a template, please update the repo settings to make it a template');\n }\n\n return {\n title: repoInfo.name,\n slug: repoInfo.name,\n description: repoInfo.description ?? '',\n imageURL: '',\n tags: [],\n useCase: '',\n longDescription: repoInfo.description ?? '',\n githubUrl: repoInfo.html_url,\n supportedProviders: [],\n };\n}\n\nasync function getTemplateRepo({ repoOrSlug, owner }: { repoOrSlug: string; owner: string }): Promise<Template> {\n const { templates } = await getMastraTemplateRepos();\n const template = templates.find(t => t.slug === repoOrSlug);\n\n if (!template) {\n if (owner === 'mastra-ai' && repoOrSlug.startsWith('template-')) {\n const templateRepo = templates.find(template => `template-${template.slug}` === repoOrSlug);\n if (templateRepo) {\n return templateRepo;\n }\n }\n\n const templateRepo = await getTemplateRepoByRepoName({ repo: repoOrSlug, owner });\n\n if (templateRepo) {\n return templateRepo;\n }\n\n throw new Error(`Template ${repoOrSlug} not found`);\n }\n\n return template;\n}\n\nasync function getTemplateRepoEnvVars({\n repo,\n owner,\n branch,\n}: {\n repo: string;\n owner: string;\n branch: string;\n}): Promise<Record<string, string>> {\n const envUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/.env.example`;\n const envResponse = await fetch(envUrl);\n\n if (envResponse.ok) {\n const envContent = await envResponse.text();\n const envVars = envContent.split('\\n').reduce(\n (acc, line) => {\n if (!line || line.startsWith('#')) return acc; // Skip empty lines and comments\n\n const [key, value] = line.split('=');\n\n if (key) {\n acc[key] = value?.split('')?.every(item => item === '*') ? '' : value?.replaceAll('\"', '');\n }\n return acc;\n },\n {} as Record<string, string>,\n );\n\n return envVars;\n }\n\n return {};\n}\n\ntype MastraTemplateRepos = Awaited<ReturnType<typeof getMastraTemplateRepos>>;\ntype TemplateRepo = Awaited<ReturnType<typeof getTemplateRepo>>;\ntype TemplateRepoEnvVars = Awaited<ReturnType<typeof getTemplateRepoEnvVars>>;\ntype AgentBuilderWorkflowDetails = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['details']>>;\ntype TemplateInstallRun = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['createRun']>>;\ntype TemplateInstallRunById = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['runById']>>;\ntype StreamTemplateInstallVariables = {\n inputData: TemplateInstallationRequest;\n selectedModel: { provider: string; modelId: string };\n runId: string;\n};\n\nexport const useMastraTemplates = <TData = MastraTemplateRepos>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<MastraTemplateRepos, TData> } = {}): UseQueryResult<TData, Error> => {\n return useQuery<MastraTemplateRepos, Error, TData>({\n queryKey: ['mastra-templates'],\n queryFn: getMastraTemplateRepos,\n ...queryOptions,\n });\n};\n\nexport const useTemplateRepo = <TData = TemplateRepo>({\n repoOrSlug,\n owner,\n queryOptions,\n}: {\n repoOrSlug: string;\n owner: string;\n queryOptions?: MastraQueryOptions<TemplateRepo, TData>;\n}): UseQueryResult<TData, Error> => {\n return useQuery<TemplateRepo, Error, TData>({\n queryKey: ['template-repo', repoOrSlug, owner],\n queryFn: () => getTemplateRepo({ repoOrSlug, owner }),\n ...queryOptions,\n });\n};\n\nexport const useTemplateRepoEnvVars = <TData = TemplateRepoEnvVars>({\n repo,\n owner,\n branch,\n queryOptions,\n}: {\n repo: string;\n owner: string;\n branch: string;\n queryOptions?: MastraQueryOptions<TemplateRepoEnvVars, TData>;\n}): UseQueryResult<TData, Error> => {\n return useQuery<TemplateRepoEnvVars, Error, TData>({\n queryKey: ['template-repo-env-vars', repo, owner, branch],\n queryFn: () => getTemplateRepoEnvVars({ repo, owner, branch }),\n ...queryOptions,\n });\n};\n\nexport const useAgentBuilderWorkflow = <TData = AgentBuilderWorkflowDetails>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<AgentBuilderWorkflowDetails, TData> } = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n return useQuery<AgentBuilderWorkflowDetails, Error, TData>({\n queryKey: ['agent-builder-workflow'],\n queryFn: async () => {\n return await client.getAgentBuilderAction('merge-template').details();\n },\n ...queryOptions,\n });\n};\n\nexport const useCreateTemplateInstallRun = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TemplateInstallRun, { runId?: string }> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ runId }: { runId?: string }) => {\n return await client.getAgentBuilderAction('merge-template').createRun({ runId });\n },\n ...queryOptions,\n });\n};\n\nexport const useGetTemplateInstallRun = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TemplateInstallRunById, { runId: string }> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ runId }: { runId: string }) => {\n return await client.getAgentBuilderAction('merge-template').runById(runId);\n },\n ...queryOptions,\n });\n};\n\nconst normalizeError = (error: unknown): string => {\n if (typeof error === 'string') return error;\n if (error == null) return 'Unknown error';\n if (error instanceof Error)\n return typeof error.message === 'string' && error.message.length > 0 ? error.message : 'Unknown error';\n if (typeof error === 'object') {\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n }\n return String(error);\n};\n\n// Helper function to process template installation records (like workflows' sanitizeWorkflowWatchResult)\nconst processTemplateInstallRecord = (\n record: { type: string; payload: any; runId?: string; eventTimestamp?: string },\n currentState: any,\n workflowInfo?: any,\n): { newState: any } => {\n let newState = { ...currentState };\n\n // Initialize steps if not present or empty\n const hasSteps =\n newState.payload?.workflowState?.steps && Object.keys(newState.payload.workflowState.steps).length > 0;\n if (!hasSteps && workflowInfo?.allSteps) {\n newState.payload = {\n ...newState.payload,\n workflowState: {\n ...newState.payload?.workflowState,\n steps: Object.keys(workflowInfo.allSteps).reduce((acc, stepId) => {\n acc[stepId] = {\n id: stepId,\n description: workflowInfo.allSteps[stepId].description,\n status: 'pending',\n };\n return acc;\n }, {} as any),\n },\n };\n }\n\n // Handle different event types\n // Support both legacy ('start') and VNext ('workflow-start') formats\n if (record.type === 'start' || record.type === 'workflow-start') {\n // Pre-populate all workflow steps from workflowInfo if available\n const initialSteps: any = {};\n if (workflowInfo?.allSteps) {\n Object.entries(workflowInfo.allSteps).forEach(([stepId, stepData]: [string, any]) => {\n initialSteps[stepId] = {\n id: stepData.id,\n description: stepData.description,\n status: 'pending',\n };\n });\n }\n\n const runId = record.runId || record.payload?.runId;\n\n newState = {\n ...newState,\n runId,\n eventTimestamp: new Date().toISOString(),\n status: 'running',\n phase: 'initializing',\n payload: {\n workflowState: {\n status: 'running',\n steps: initialSteps,\n },\n currentStep: null,\n },\n };\n }\n\n // Support both legacy ('step-start') and VNext ('workflow-step-start') formats\n if (record.type === 'step-start' || record.type === 'workflow-step-start') {\n const stepId = record.payload.id;\n newState = {\n ...newState,\n phase: 'processing',\n payload: {\n ...newState.payload,\n currentStep: {\n id: stepId,\n status: 'running',\n startTime: new Date(),\n ...record.payload,\n },\n workflowState: {\n ...newState.payload.workflowState,\n steps: {\n ...newState.payload.workflowState.steps,\n [stepId]: {\n ...newState.payload.workflowState.steps[stepId],\n status: 'running',\n startTime: new Date(),\n ...record.payload,\n },\n },\n },\n },\n };\n }\n\n // Support both legacy ('step-result') and VNext ('workflow-step-result') formats\n if (record.type === 'step-result' || record.type === 'workflow-step-result') {\n const stepId = record.payload.id;\n const status = record.payload.status;\n const hasError = record.payload.error;\n newState = {\n ...newState,\n payload: {\n ...newState.payload,\n currentStep: {\n ...newState.payload.currentStep,\n status: record.payload.status,\n output: record.payload.output,\n error: record.payload.error,\n endTime: new Date(),\n },\n workflowState: {\n ...newState.payload.workflowState,\n steps: {\n ...newState.payload.workflowState.steps,\n [stepId]: {\n ...newState.payload.workflowState.steps[stepId],\n status: record.payload.status,\n output: record.payload.output,\n error: record.payload.error,\n endTime: new Date(),\n },\n },\n },\n },\n };\n\n // If this step failed, also set workflow-level error state\n if (status === 'failed' && hasError) {\n const errorString = normalizeError(hasError);\n newState = {\n ...newState,\n status: 'failed',\n error: errorString,\n phase: 'error',\n failedStep: {\n id: stepId,\n error: errorString,\n description: record.payload.description || stepId,\n },\n payload: {\n ...newState.payload,\n workflowState: {\n ...newState.payload.workflowState,\n status: 'failed',\n },\n },\n errorTimestamp: new Date(),\n };\n }\n }\n\n // Support both legacy ('step-finish') and VNext ('workflow-step-finish') formats\n if (record.type === 'step-finish' || record.type === 'workflow-step-finish') {\n newState = {\n ...newState,\n payload: {\n ...newState.payload,\n currentStep: null,\n },\n };\n }\n\n // Support both legacy ('finish') and VNext ('workflow-finish') formats\n if (record.type === 'finish' || record.type === 'workflow-finish') {\n // Don't override error states - if we're already in error phase, stay there\n if (newState.phase === 'error' || newState.status === 'failed') {\n newState = {\n ...newState,\n // Keep existing status, phase, error, failedStep\n completedAt: new Date(),\n };\n } else {\n // Normal completion flow\n newState = {\n ...newState,\n status: record.payload.status || 'completed',\n phase: 'completed',\n payload: {\n ...newState.payload,\n currentStep: null,\n workflowState: {\n ...newState.payload.workflowState,\n status: record.payload.status || 'completed',\n },\n },\n completedAt: new Date(),\n };\n }\n }\n\n if (record.type === 'error') {\n const errorStr = normalizeError(record.payload.error);\n newState = {\n ...newState,\n status: 'failed',\n error: errorStr,\n phase: 'error',\n payload: {\n ...newState.payload,\n workflowState: {\n ...newState.payload.workflowState,\n status: 'failed',\n },\n },\n errorTimestamp: new Date(),\n };\n }\n\n return { newState };\n};\n\n// Shared localStorage helpers for template installation state\nconst saveTemplateStateToLocalStorage = (runId: string, state: any) => {\n try {\n localStorage.setItem(\n `template-install-${runId}`,\n JSON.stringify({\n state,\n timestamp: Date.now(),\n }),\n );\n } catch (error) {\n console.warn('Failed to save template state to localStorage:', error);\n }\n};\n\n// Shared helper for processing template installation streams (streamlined)\nconst useTemplateStreamProcessor = (workflowInfo?: any, runId?: string) => {\n const [streamResult, setStreamResult] = useState<any>({});\n const [isStreaming, setIsStreaming] = useState(false);\n\n const processStream = async (stream: any, initialRunId?: string) => {\n setIsStreaming(true);\n setStreamResult({});\n\n if (!stream) throw new Error('No stream returned');\n\n const reader = stream.getReader();\n\n // Initialize minimal state - don't set immediately, let events drive the state\n let currentState: any = {\n runId: initialRunId || runId,\n eventTimestamp: new Date().toISOString(),\n phase: 'running',\n payload: {\n workflowState: {\n steps: {},\n },\n currentStep: null,\n },\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n const { newState } = processTemplateInstallRecord(value, currentState, workflowInfo);\n\n currentState = newState;\n setStreamResult(newState);\n\n // Save to localStorage for refresh recovery (same as watch)\n if (value.runId || initialRunId || runId) {\n const effectiveRunId = value.runId || initialRunId || runId;\n saveTemplateStateToLocalStorage(effectiveRunId, newState);\n }\n }\n } catch (error) {\n console.error('💥 [processStream] Error processing template installation stream:', error);\n\n // Use the helper for error handling too\n const { newState } = processTemplateInstallRecord(\n { type: 'error', payload: { error: error instanceof Error ? error.message : 'Unknown error' } },\n currentState,\n workflowInfo,\n );\n\n setStreamResult(newState);\n } finally {\n setIsStreaming(false);\n reader.releaseLock();\n }\n };\n\n return {\n streamResult,\n isStreaming,\n processStream,\n };\n};\n\nexport const useStreamTemplateInstall = ({\n workflowInfo,\n queryOptions,\n}: {\n workflowInfo?: any;\n queryOptions?: { streamInstall?: MastraMutationOptions<void, StreamTemplateInstallVariables> };\n} = {}) => {\n const client = useMastraClient();\n const { streamResult, isStreaming, processStream } = useTemplateStreamProcessor(workflowInfo);\n\n const streamInstall = useMutation({\n mutationFn: async ({ inputData, selectedModel, runId }: StreamTemplateInstallVariables) => {\n const maxRetries = 3;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n const template = client.getAgentBuilderAction('merge-template');\n const requestContext = new RequestContext();\n requestContext.set('selectedModel', selectedModel);\n const stream = await template.stream({ inputData, requestContext }, runId);\n await processStream(stream, runId);\n\n // If we get here, the stream completed successfully\n return;\n } catch (error: any) {\n console.error(`💥 [streamInstall] Attempt ${attempt} failed:`, error);\n const isNetworkError =\n error?.message?.includes('Failed to fetch') ||\n error?.message?.includes('NetworkError') ||\n error?.message?.includes('network error') ||\n error?.message?.includes('fetch') ||\n error?.code === 'NETWORK_ERROR' ||\n error?.name === 'TypeError';\n\n console.warn(`Stream attempt ${attempt}/${maxRetries} failed:`, error);\n\n if (isNetworkError) {\n // For stream network errors, provide helpful message since switching context is complex\n const errorMessage = runId\n ? `Network error during template installation (likely hot reload). Please refresh the page to resume from where you left off using runId: ${runId}`\n : 'Network error during template installation (likely hot reload). Please try again.';\n\n console.error('🔌 Stream network error:', errorMessage);\n throw new Error(errorMessage);\n }\n\n // If it's not a network error or we've exhausted retries, throw\n console.error('❌ [streamInstall] Non-network error or max retries reached, throwing:', error);\n throw error;\n }\n }\n },\n ...queryOptions?.streamInstall,\n });\n\n return {\n streamInstall,\n streamResult,\n isStreaming,\n };\n};\n\n/**\n * Hook for observing template installation with full replay capability.\n * Uses observeStream() which replays cached execution from beginning, then continues live.\n */\nexport const useObserveStreamTemplateInstall = ({\n workflowInfo,\n queryOptions,\n}: {\n workflowInfo?: any;\n queryOptions?: { observeInstall?: MastraMutationOptions<void, { runId: string }> };\n} = {}) => {\n const client = useMastraClient();\n const { streamResult, isStreaming, processStream } = useTemplateStreamProcessor(workflowInfo);\n\n const observeInstall = useMutation({\n mutationFn: async ({ runId }: { runId: string }) => {\n const maxRetries = 3;\n const retryDelay = 2000; // 2 seconds\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n // Initialize state - but observeStream will replay full history\n // so we don't need to rely on localStorage as fallback\n const template = client.getAgentBuilderAction('merge-template');\n\n // Use observeStream to get full replay + live updates\n const stream = await template.observeStream({ runId });\n await processStream(stream, runId);\n\n // If we get here, the observe stream completed successfully\n return;\n } catch (error: any) {\n console.error(`💥 [observeInstall] Attempt ${attempt} failed:`, error);\n const isNetworkError =\n error?.message?.includes('Failed to fetch') ||\n error?.message?.includes('NetworkError') ||\n error?.message?.includes('network error') ||\n error?.message?.includes('fetch') ||\n error?.code === 'NETWORK_ERROR' ||\n error?.name === 'TypeError';\n\n console.warn(`ObserveStream attempt ${attempt}/${maxRetries} failed:`, error);\n\n if (isNetworkError && attempt < maxRetries) {\n console.info(\n `🔄 ObserveStream network error detected (likely hot reload), retrying in ${retryDelay}ms... (attempt ${attempt + 1}/${maxRetries})`,\n );\n await new Promise(resolve => setTimeout(resolve, retryDelay));\n continue; // Retry\n }\n\n // If it's not a network error or we've exhausted retries, throw\n console.error('❌ [observeInstall] Non-network error or max retries reached, throwing:', error);\n throw error;\n }\n }\n },\n ...queryOptions?.observeInstall,\n });\n\n return {\n observeInstall,\n streamResult,\n isStreaming,\n };\n};\n"],"mappings":";;;;;AA2BA,eAAe,yBAAkG;CAC/G,MAAM,WAAW,MAAM,MAAM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","names":[],"sources":["../../../src/hooks/templates/use-templates.ts"],"sourcesContent":["import type { MastraClient, TemplateInstallationRequest } from '@mastra/client-js';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery, useMutation } from '@tanstack/react-query';\nimport { useState } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\nexport interface Template {\n slug: string;\n title: string;\n description: string;\n longDescription: string;\n githubUrl: string;\n tags: string[];\n imageURL?: string;\n codeExample?: string;\n agents?: string[];\n tools?: string[];\n workflows?: string[];\n mcp?: string[];\n networks?: string[];\n videoURL?: string;\n useCase: string;\n supportedProviders: string[];\n}\n\nasync function getMastraTemplateRepos(): Promise<{ templates: Template[]; tags: string[]; providers: string[] }> {\n const response = await fetch('https://mastra.ai/api/templates.json');\n if (!response.ok) {\n throw new Error(`Failed to fetch templates: ${response.statusText}`);\n }\n const templates = await response.json();\n const allTemplates = [\n {\n title: 'Weather Agent',\n slug: 'weather-agent',\n githubUrl: 'https://github.com/mastra-ai/weather-agent',\n description: 'Get weather information of any city.',\n longDescription: 'One Agent, one Workflow and one Tool to bring you the weather in your city.',\n imageURL: '',\n tags: ['Agent', 'Workflow', 'Tool'],\n useCase: '',\n supportedProviders: ['openai', 'anthropic', 'google', 'groq'],\n agents: ['weatherAgent'],\n tools: ['weatherTool'],\n workflows: ['weatherWorkflow'],\n },\n ...templates,\n ];\n\n const allTags = Array.from(new Set(allTemplates.flatMap(t => t.tags)));\n const allProviders = Array.from(new Set(allTemplates.flatMap(t => t.supportedProviders)));\n\n return {\n templates: allTemplates,\n tags: allTags,\n providers: allProviders,\n };\n}\n\nasync function getTemplateRepoByRepoName({ repo, owner }: { repo: string; owner: string }): Promise<Template> {\n const response = await fetch(`https://api.github.com/repos/${owner}/${repo}`);\n if (!response.ok) {\n throw new Error(`Failed to fetch template: ${response.statusText}`);\n }\n const repoInfo = await response.json();\n if (!repoInfo.is_template) {\n throw new Error('Repo is not a template, please update the repo settings to make it a template');\n }\n\n return {\n title: repoInfo.name,\n slug: repoInfo.name,\n description: repoInfo.description ?? '',\n imageURL: '',\n tags: [],\n useCase: '',\n longDescription: repoInfo.description ?? '',\n githubUrl: repoInfo.html_url,\n supportedProviders: [],\n };\n}\n\nasync function getTemplateRepo({ repoOrSlug, owner }: { repoOrSlug: string; owner: string }): Promise<Template> {\n const { templates } = await getMastraTemplateRepos();\n const template = templates.find(t => t.slug === repoOrSlug);\n\n if (!template) {\n if (owner === 'mastra-ai' && repoOrSlug.startsWith('template-')) {\n const templateRepo = templates.find(template => `template-${template.slug}` === repoOrSlug);\n if (templateRepo) {\n return templateRepo;\n }\n }\n\n const templateRepo = await getTemplateRepoByRepoName({ repo: repoOrSlug, owner });\n\n if (templateRepo) {\n return templateRepo;\n }\n\n throw new Error(`Template ${repoOrSlug} not found`);\n }\n\n return template;\n}\n\nasync function getTemplateRepoEnvVars({\n repo,\n owner,\n branch,\n}: {\n repo: string;\n owner: string;\n branch: string;\n}): Promise<Record<string, string>> {\n const envUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/.env.example`;\n const envResponse = await fetch(envUrl);\n\n if (envResponse.ok) {\n const envContent = await envResponse.text();\n const envVars = envContent.split('\\n').reduce(\n (acc, line) => {\n if (!line || line.startsWith('#')) return acc; // Skip empty lines and comments\n\n const [key, value] = line.split('=');\n\n if (key) {\n acc[key] = value?.split('')?.every(item => item === '*') ? '' : value?.replaceAll('\"', '');\n }\n return acc;\n },\n {} as Record<string, string>,\n );\n\n return envVars;\n }\n\n return {};\n}\n\ntype MastraTemplateRepos = Awaited<ReturnType<typeof getMastraTemplateRepos>>;\ntype TemplateRepo = Awaited<ReturnType<typeof getTemplateRepo>>;\ntype TemplateRepoEnvVars = Awaited<ReturnType<typeof getTemplateRepoEnvVars>>;\ntype AgentBuilderWorkflowDetails = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['details']>>;\ntype TemplateInstallRun = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['createRun']>>;\ntype TemplateInstallRunById = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['runById']>>;\ntype StreamTemplateInstallVariables = {\n inputData: TemplateInstallationRequest;\n selectedModel: { provider: string; modelId: string };\n runId: string;\n};\n\nexport const useMastraTemplates = <TData = MastraTemplateRepos>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<MastraTemplateRepos, TData> } = {}): UseQueryResult<TData, Error> => {\n return useQuery<MastraTemplateRepos, Error, TData>({\n queryKey: ['mastra-templates'],\n queryFn: getMastraTemplateRepos,\n ...queryOptions,\n });\n};\n\nexport const useTemplateRepo = <TData = TemplateRepo>({\n repoOrSlug,\n owner,\n queryOptions,\n}: {\n repoOrSlug: string;\n owner: string;\n queryOptions?: MastraQueryOptions<TemplateRepo, TData>;\n}): UseQueryResult<TData, Error> => {\n return useQuery<TemplateRepo, Error, TData>({\n queryKey: ['template-repo', repoOrSlug, owner],\n queryFn: () => getTemplateRepo({ repoOrSlug, owner }),\n ...queryOptions,\n });\n};\n\nexport const useTemplateRepoEnvVars = <TData = TemplateRepoEnvVars>({\n repo,\n owner,\n branch,\n queryOptions,\n}: {\n repo: string;\n owner: string;\n branch: string;\n queryOptions?: MastraQueryOptions<TemplateRepoEnvVars, TData>;\n}): UseQueryResult<TData, Error> => {\n return useQuery<TemplateRepoEnvVars, Error, TData>({\n queryKey: ['template-repo-env-vars', repo, owner, branch],\n queryFn: () => getTemplateRepoEnvVars({ repo, owner, branch }),\n ...queryOptions,\n });\n};\n\nexport const useAgentBuilderWorkflow = <TData = AgentBuilderWorkflowDetails>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<AgentBuilderWorkflowDetails, TData> } = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n return useQuery<AgentBuilderWorkflowDetails, Error, TData>({\n queryKey: ['agent-builder-workflow'],\n queryFn: async () => {\n return await client.getAgentBuilderAction('merge-template').details();\n },\n ...queryOptions,\n });\n};\n\nexport const useCreateTemplateInstallRun = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TemplateInstallRun, { runId?: string }> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ runId }: { runId?: string }) => {\n return await client.getAgentBuilderAction('merge-template').createRun({ runId });\n },\n ...queryOptions,\n });\n};\n\nexport const useGetTemplateInstallRun = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TemplateInstallRunById, { runId: string }> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ runId }: { runId: string }) => {\n return await client.getAgentBuilderAction('merge-template').runById(runId);\n },\n ...queryOptions,\n });\n};\n\nconst normalizeError = (error: unknown): string => {\n if (typeof error === 'string') return error;\n if (error == null) return 'Unknown error';\n if (error instanceof Error)\n return typeof error.message === 'string' && error.message.length > 0 ? error.message : 'Unknown error';\n if (typeof error === 'object') {\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n }\n return String(error);\n};\n\n// Helper function to process template installation records (like workflows' sanitizeWorkflowWatchResult)\nconst processTemplateInstallRecord = (\n record: { type: string; payload: any; runId?: string; eventTimestamp?: string },\n currentState: any,\n workflowInfo?: any,\n): { newState: any } => {\n let newState = { ...currentState };\n\n // Initialize steps if not present or empty\n const hasSteps =\n newState.payload?.workflowState?.steps && Object.keys(newState.payload.workflowState.steps).length > 0;\n if (!hasSteps && workflowInfo?.allSteps) {\n newState.payload = {\n ...newState.payload,\n workflowState: {\n ...newState.payload?.workflowState,\n steps: Object.keys(workflowInfo.allSteps).reduce((acc, stepId) => {\n acc[stepId] = {\n id: stepId,\n description: workflowInfo.allSteps[stepId].description,\n status: 'pending',\n };\n return acc;\n }, {} as any),\n },\n };\n }\n\n // Handle different event types\n // Support both legacy ('start') and VNext ('workflow-start') formats\n if (record.type === 'start' || record.type === 'workflow-start') {\n // Pre-populate all workflow steps from workflowInfo if available\n const initialSteps: any = {};\n if (workflowInfo?.allSteps) {\n Object.entries(workflowInfo.allSteps).forEach(([stepId, stepData]: [string, any]) => {\n initialSteps[stepId] = {\n id: stepData.id,\n description: stepData.description,\n status: 'pending',\n };\n });\n }\n\n const runId = record.runId || record.payload?.runId;\n\n newState = {\n ...newState,\n runId,\n eventTimestamp: new Date().toISOString(),\n status: 'running',\n phase: 'initializing',\n payload: {\n workflowState: {\n status: 'running',\n steps: initialSteps,\n },\n currentStep: null,\n },\n };\n }\n\n // Support both legacy ('step-start') and VNext ('workflow-step-start') formats\n if (record.type === 'step-start' || record.type === 'workflow-step-start') {\n const stepId = record.payload.id;\n newState = {\n ...newState,\n phase: 'processing',\n payload: {\n ...newState.payload,\n currentStep: {\n id: stepId,\n status: 'running',\n startTime: new Date(),\n ...record.payload,\n },\n workflowState: {\n ...newState.payload.workflowState,\n steps: {\n ...newState.payload.workflowState.steps,\n [stepId]: {\n ...newState.payload.workflowState.steps[stepId],\n status: 'running',\n startTime: new Date(),\n ...record.payload,\n },\n },\n },\n },\n };\n }\n\n // Support both legacy ('step-result') and VNext ('workflow-step-result') formats\n if (record.type === 'step-result' || record.type === 'workflow-step-result') {\n const stepId = record.payload.id;\n const status = record.payload.status;\n const hasError = record.payload.error;\n newState = {\n ...newState,\n payload: {\n ...newState.payload,\n currentStep: {\n ...newState.payload.currentStep,\n status: record.payload.status,\n output: record.payload.output,\n error: record.payload.error,\n endTime: new Date(),\n },\n workflowState: {\n ...newState.payload.workflowState,\n steps: {\n ...newState.payload.workflowState.steps,\n [stepId]: {\n ...newState.payload.workflowState.steps[stepId],\n status: record.payload.status,\n output: record.payload.output,\n error: record.payload.error,\n endTime: new Date(),\n },\n },\n },\n },\n };\n\n // If this step failed, also set workflow-level error state\n if (status === 'failed' && hasError) {\n const errorString = normalizeError(hasError);\n newState = {\n ...newState,\n status: 'failed',\n error: errorString,\n phase: 'error',\n failedStep: {\n id: stepId,\n error: errorString,\n description: record.payload.description || stepId,\n },\n payload: {\n ...newState.payload,\n workflowState: {\n ...newState.payload.workflowState,\n status: 'failed',\n },\n },\n errorTimestamp: new Date(),\n };\n }\n }\n\n // Support both legacy ('step-finish') and VNext ('workflow-step-finish') formats\n if (record.type === 'step-finish' || record.type === 'workflow-step-finish') {\n newState = {\n ...newState,\n payload: {\n ...newState.payload,\n currentStep: null,\n },\n };\n }\n\n // Support both legacy ('finish') and VNext ('workflow-finish') formats\n if (record.type === 'finish' || record.type === 'workflow-finish') {\n // Don't override error states - if we're already in error phase, stay there\n if (newState.phase === 'error' || newState.status === 'failed') {\n newState = {\n ...newState,\n // Keep existing status, phase, error, failedStep\n completedAt: new Date(),\n };\n } else {\n // Normal completion flow\n newState = {\n ...newState,\n status: record.payload.status || 'completed',\n phase: 'completed',\n payload: {\n ...newState.payload,\n currentStep: null,\n workflowState: {\n ...newState.payload.workflowState,\n status: record.payload.status || 'completed',\n },\n },\n completedAt: new Date(),\n };\n }\n }\n\n if (record.type === 'error') {\n const errorStr = normalizeError(record.payload.error);\n newState = {\n ...newState,\n status: 'failed',\n error: errorStr,\n phase: 'error',\n payload: {\n ...newState.payload,\n workflowState: {\n ...newState.payload.workflowState,\n status: 'failed',\n },\n },\n errorTimestamp: new Date(),\n };\n }\n\n return { newState };\n};\n\n// Shared localStorage helpers for template installation state\nconst saveTemplateStateToLocalStorage = (runId: string, state: any) => {\n try {\n localStorage.setItem(\n `template-install-${runId}`,\n JSON.stringify({\n state,\n timestamp: Date.now(),\n }),\n );\n } catch (error) {\n console.warn('Failed to save template state to localStorage:', error);\n }\n};\n\n// Shared helper for processing template installation streams (streamlined)\nconst useTemplateStreamProcessor = (workflowInfo?: any, runId?: string) => {\n const [streamResult, setStreamResult] = useState<any>({});\n const [isStreaming, setIsStreaming] = useState(false);\n\n const processStream = async (stream: any, initialRunId?: string) => {\n setIsStreaming(true);\n setStreamResult({});\n\n if (!stream) throw new Error('No stream returned');\n\n const reader = stream.getReader();\n\n // Initialize minimal state - don't set immediately, let events drive the state\n let currentState: any = {\n runId: initialRunId || runId,\n eventTimestamp: new Date().toISOString(),\n phase: 'running',\n payload: {\n workflowState: {\n steps: {},\n },\n currentStep: null,\n },\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n const { newState } = processTemplateInstallRecord(value, currentState, workflowInfo);\n\n currentState = newState;\n setStreamResult(newState);\n\n // Save to localStorage for refresh recovery (same as watch)\n if (value.runId || initialRunId || runId) {\n const effectiveRunId = value.runId || initialRunId || runId;\n saveTemplateStateToLocalStorage(effectiveRunId, newState);\n }\n }\n } catch (error) {\n console.error('💥 [processStream] Error processing template installation stream:', error);\n\n // Use the helper for error handling too\n const { newState } = processTemplateInstallRecord(\n { type: 'error', payload: { error: error instanceof Error ? error.message : 'Unknown error' } },\n currentState,\n workflowInfo,\n );\n\n setStreamResult(newState);\n } finally {\n setIsStreaming(false);\n reader.releaseLock();\n }\n };\n\n return {\n streamResult,\n isStreaming,\n processStream,\n };\n};\n\nexport const useStreamTemplateInstall = ({\n workflowInfo,\n queryOptions,\n}: {\n workflowInfo?: any;\n queryOptions?: { streamInstall?: MastraMutationOptions<void, StreamTemplateInstallVariables> };\n} = {}) => {\n const client = useMastraClient();\n const { streamResult, isStreaming, processStream } = useTemplateStreamProcessor(workflowInfo);\n\n const streamInstall = useMutation({\n mutationFn: async ({ inputData, selectedModel, runId }: StreamTemplateInstallVariables) => {\n const maxRetries = 3;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n const template = client.getAgentBuilderAction('merge-template');\n const requestContext = new RequestContext();\n requestContext.set('selectedModel', selectedModel);\n const stream = await template.stream({ inputData, requestContext }, runId);\n await processStream(stream, runId);\n\n // If we get here, the stream completed successfully\n return;\n } catch (error: any) {\n console.error(`💥 [streamInstall] Attempt ${attempt} failed:`, error);\n const isNetworkError =\n error?.message?.includes('Failed to fetch') ||\n error?.message?.includes('NetworkError') ||\n error?.message?.includes('network error') ||\n error?.message?.includes('fetch') ||\n error?.code === 'NETWORK_ERROR' ||\n error?.name === 'TypeError';\n\n console.warn(`Stream attempt ${attempt}/${maxRetries} failed:`, error);\n\n if (isNetworkError) {\n // For stream network errors, provide helpful message since switching context is complex\n const errorMessage = runId\n ? `Network error during template installation (likely hot reload). Please refresh the page to resume from where you left off using runId: ${runId}`\n : 'Network error during template installation (likely hot reload). Please try again.';\n\n console.error('🔌 Stream network error:', errorMessage);\n throw new Error(errorMessage);\n }\n\n // If it's not a network error or we've exhausted retries, throw\n console.error('❌ [streamInstall] Non-network error or max retries reached, throwing:', error);\n throw error;\n }\n }\n },\n ...queryOptions?.streamInstall,\n });\n\n return {\n streamInstall,\n streamResult,\n isStreaming,\n };\n};\n\n/**\n * Hook for observing template installation with full replay capability.\n * Uses observeStream() which replays cached execution from beginning, then continues live.\n */\nexport const useObserveStreamTemplateInstall = ({\n workflowInfo,\n queryOptions,\n}: {\n workflowInfo?: any;\n queryOptions?: { observeInstall?: MastraMutationOptions<void, { runId: string }> };\n} = {}) => {\n const client = useMastraClient();\n const { streamResult, isStreaming, processStream } = useTemplateStreamProcessor(workflowInfo);\n\n const observeInstall = useMutation({\n mutationFn: async ({ runId }: { runId: string }) => {\n const maxRetries = 3;\n const retryDelay = 2000; // 2 seconds\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n // Initialize state - but observeStream will replay full history\n // so we don't need to rely on localStorage as fallback\n const template = client.getAgentBuilderAction('merge-template');\n\n // Use observeStream to get full replay + live updates\n const stream = await template.observeStream({ runId });\n await processStream(stream, runId);\n\n // If we get here, the observe stream completed successfully\n return;\n } catch (error: any) {\n console.error(`💥 [observeInstall] Attempt ${attempt} failed:`, error);\n const isNetworkError =\n error?.message?.includes('Failed to fetch') ||\n error?.message?.includes('NetworkError') ||\n error?.message?.includes('network error') ||\n error?.message?.includes('fetch') ||\n error?.code === 'NETWORK_ERROR' ||\n error?.name === 'TypeError';\n\n console.warn(`ObserveStream attempt ${attempt}/${maxRetries} failed:`, error);\n\n if (isNetworkError && attempt < maxRetries) {\n console.info(\n `🔄 ObserveStream network error detected (likely hot reload), retrying in ${retryDelay}ms... (attempt ${attempt + 1}/${maxRetries})`,\n );\n await new Promise(resolve => setTimeout(resolve, retryDelay));\n continue; // Retry\n }\n\n // If it's not a network error or we've exhausted retries, throw\n console.error('❌ [observeInstall] Non-network error or max retries reached, throwing:', error);\n throw error;\n }\n }\n },\n ...queryOptions?.observeInstall,\n });\n\n return {\n observeInstall,\n streamResult,\n isStreaming,\n };\n};\n"],"mappings":";;;;;AA2BA,eAAe,yBAAkG;CAC/G,MAAM,WAAW,MAAM,MAAM,sCAAsC;CACnE,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,8BAA8B,SAAS,YAAY;CAGrE,MAAM,eAAe,CACnB;EACE,OAAO;EACP,MAAM;EACN,WAAW;EACX,aAAa;EACb,iBAAiB;EACjB,UAAU;EACV,MAAM;GAAC;GAAS;GAAY;EAAM;EAClC,SAAS;EACT,oBAAoB;GAAC;GAAU;GAAa;GAAU;EAAM;EAC5D,QAAQ,CAAC,cAAc;EACvB,OAAO,CAAC,aAAa;EACrB,WAAW,CAAC,iBAAiB;CAC/B,GACA,GAAG,MAhBmB,SAAS,KAAK,CAiBtC;CAKA,OAAO;EACL,WAAW;EACX,MALc,MAAM,KAAK,IAAI,IAAI,aAAa,SAAQ,MAAK,EAAE,IAAI,CAAC,CAKtD;EACZ,WALmB,MAAM,KAAK,IAAI,IAAI,aAAa,SAAQ,MAAK,EAAE,kBAAkB,CAAC,CAK/D;CACxB;AACF;AAEA,eAAe,0BAA0B,EAAE,MAAM,SAA6D;CAC5G,MAAM,WAAW,MAAM,MAAM,gCAAgC,MAAM,GAAG,MAAM;CAC5E,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,6BAA6B,SAAS,YAAY;CAEpE,MAAM,WAAW,MAAM,SAAS,KAAK;CACrC,IAAI,CAAC,SAAS,aACZ,MAAM,IAAI,MAAM,+EAA+E;CAGjG,OAAO;EACL,OAAO,SAAS;EAChB,MAAM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QAAQ,KAAK,yBAAyB,QAAQ,GAAG,WAAW,WAAW,KAAK;KAE5E,IAAI,kBAAkB,UAAU,YAAY;MAC1C,QAAQ,KACN,4EAA4E,WAAW,iBAAiB,UAAU,EAAE,GAAG,WAAW,EACpI;MACA,MAAM,IAAI,SAAQ,YAAW,WAAW,SAAS,UAAU,CAAC;MAC5D;KACF;KAGA,QAAQ,MAAM,0EAA0E,KAAK;KAC7F,MAAM;IACR;GAEJ;GACA,GAAG,cAAc;EACnB,CAGe;EACb;EACA;CACF;AACF"}
|
|
@@ -185,7 +185,7 @@ const useAllProviderTools = ({ queryOptions } = {}) => {
|
|
|
185
185
|
//#endregion
|
|
186
186
|
//#region src/hooks/tool-providers/use-authorize.ts
|
|
187
187
|
const DEFAULT_POLL_INTERVAL_MS = 2e3;
|
|
188
|
-
const DEFAULT_TIMEOUT_MS =
|
|
188
|
+
const DEFAULT_TIMEOUT_MS = 3e5;
|
|
189
189
|
/**
|
|
190
190
|
* Drives the OAuth popup + polling loop for a `ToolProvider` provider.
|
|
191
191
|
*/
|