@mastra/react 1.12.0-alpha.10 → 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/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/llm/index.cjs.map +1 -1
- package/dist/hooks/logs/index.cjs.map +1 -1
- 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 +4 -4
- package/dist/hooks/traces/index.cjs.map +1 -1
- package/dist/hooks/traces/index.js +4 -4
- package/dist/hooks/traces/index.js.map +1 -1
- 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-CIutb3DO.cjs → hooks-B1i-oHae.cjs} +6 -4
- package/dist/hooks-B1i-oHae.cjs.map +1 -0
- package/dist/{hooks-FVbeHlov.js → hooks-CLfMO5cH.js} +6 -4
- package/dist/{hooks-FVbeHlov.js.map → hooks-CLfMO5cH.js.map} +1 -1
- 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-CIutb3DO.cjs.map +0 -1
- package/dist/hooks-_YevKidX.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/hooks/agents/use-agent-messages.ts","../../../src/hooks/agents/use-agent-plan.ts","../../../src/hooks/agents/use-background-tasks.ts","../../../src/hooks/agents/use-browser-session-probe.ts","../../../src/hooks/agents/is-model-not-allowed.ts","../../../src/hooks/agents/use-stored-agents.ts","../../../src/hooks/agents/use-agent-skills.ts","../../../src/hooks/agents/use-agent-versions.ts","../../../src/hooks/agents/use-agent-working-memory.ts","../../../src/hooks/agents/use-agent-workspace.ts","../../../src/hooks/agents/use-agent.ts","../../../src/hooks/agents/use-agents-model-providers.ts","../../../src/hooks/agents/use-agents.ts","../../../src/hooks/agents/use-close-browser.ts","../../../src/hooks/agents/use-preview-instructions.ts","../../../src/hooks/agents/use-stored-skills.ts","../../../src/hooks/agents/use-channels.ts","../../../src/hooks/agents/use-execute-agent-tool.ts"],"sourcesContent":["import type { MastraClient } from '@mastra/client-js';\nimport type { MastraDBMessage } from '@mastra/core/agent/message-list';\nimport { skipToken, useInfiniteQuery } from '@tanstack/react-query';\nimport type { InfiniteData, QueryKey } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraInfiniteQueryOptions } from '../shared/query-options';\n\ntype AgentMessagesPage = Awaited<ReturnType<MastraClient['listThreadMessages']>>;\n\ntype AgentMessagesData = InfiniteData<AgentMessagesPage, string> & { messages: MastraDBMessage[] };\n\nexport interface UseAgentMessagesProps<TData = AgentMessagesData> {\n threadId?: string;\n agentId: string;\n memory: boolean;\n requestContext?: Record<string, any>;\n queryOptions?: MastraInfiniteQueryOptions<AgentMessagesPage, TData, QueryKey, string>;\n}\n\nconst PER_PAGE = 40;\n\nconst NEWEST_PAGE = '';\n\nconst createdAtMs = (message: MastraDBMessage) => new Date(message.createdAt).getTime();\n\nconst byCreatedAt = (a: MastraDBMessage, b: MastraDBMessage) => createdAtMs(a) - createdAtMs(b);\n\nexport const useAgentMessages = <TData = AgentMessagesData>({\n threadId,\n agentId,\n memory,\n requestContext,\n queryOptions,\n}: UseAgentMessagesProps<TData>) => {\n const client = useMastraClient();\n\n return useInfiniteQuery({\n queryKey: ['memory', 'messages', threadId, agentId, requestContext],\n initialPageParam: NEWEST_PAGE,\n queryFn:\n memory && threadId\n ? ({ pageParam: olderThan }) =>\n client.listThreadMessages(threadId, {\n agentId,\n requestContext,\n includeSystemReminders: true,\n perPage: PER_PAGE,\n orderBy: { field: 'createdAt', direction: 'DESC' },\n // Inclusive bound: messages sharing the oldest createdAt of the previous page\n // may have been cut off by perPage, so re-ask for them and dedupe by id below.\n filter: olderThan ? { dateRange: { end: new Date(olderThan) } } : undefined,\n })\n : skipToken,\n getNextPageParam: (lastPage, _allPages, lastPageParam) => {\n if (!lastPage.hasMore || lastPage.messages.length === 0) return undefined;\n const next = new Date(Math.min(...lastPage.messages.map(createdAtMs))).toISOString();\n // A full page of same-timestamp messages would re-request itself forever.\n return next === lastPageParam ? undefined : next;\n },\n select: (data): TData => {\n const seen = new Set<string>();\n const messages = data.pages\n .flatMap(page => page.messages)\n .filter(message => {\n if (seen.has(message.id)) return false;\n seen.add(message.id);\n return true;\n })\n .sort(byCreatedAt);\n return { ...data, messages } as AgentMessagesData as TData;\n },\n staleTime: 0,\n gcTime: 0,\n retry: false,\n refetchOnWindowFocus: false,\n ...queryOptions,\n });\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\ntype AgentPlanResponse = Awaited<ReturnType<ReturnType<MastraClient['getAgent']>['readPlan']>>;\n\ninterface UseAgentPlanOptions<TData> {\n agentId: string;\n path: string;\n agentVersionId?: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<AgentPlanResponse, TData>;\n}\n\nexport function useAgentPlan<TData = AgentPlanResponse>({\n agentId,\n path,\n agentVersionId,\n requestContext,\n queryOptions,\n}: UseAgentPlanOptions<TData>): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['agent-plan', agentId, agentVersionId, path, requestContext],\n queryFn: () => {\n const agent = agentVersionId ? client.getAgent(agentId, { versionId: agentVersionId }) : client.getAgent(agentId);\n return agent.readPlan(path, requestContext);\n },\n retry: false,\n ...queryOptions,\n });\n}\n","import type { MastraClient, StreamBackgroundTasksParams } from '@mastra/client-js';\nimport type { BackgroundTaskStatus } from '@mastra/core/background-tasks';\nimport type { AgentChunkType } from '@mastra/core/stream';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\ntype BackgroundTaskStreamReader = ReturnType<Awaited<ReturnType<MastraClient['streamBackgroundTasks']>>['getReader']>;\n\nexport interface BackgroundTaskEvent {\n taskId: string;\n toolName: string;\n toolCallId: string;\n agentId: string;\n runId: string;\n result?: unknown;\n error?: { message: string; stack?: string };\n status: BackgroundTaskStatus;\n args: Record<string, unknown>;\n suspendPayload?: unknown;\n}\n\nexport interface UseBackgroundTaskStreamOptions extends StreamBackgroundTasksParams {\n /** Whether the stream is active. Default: true */\n enabled?: boolean;\n}\n\nexport interface UseBackgroundTaskStreamReturn {\n /** Map of taskId → latest event data */\n tasks: Record<string, BackgroundTaskEvent>;\n /** Whether the stream is currently connected */\n isConnected: boolean;\n /** Any connection error */\n error: Error | null;\n /** Manually disconnect the stream */\n disconnect: () => void;\n /** Manually reconnect the stream */\n reconnect: () => void;\n /** List of running tasks */\n runningTasks: BackgroundTaskEvent[];\n /** List of completed tasks */\n completedTasks: BackgroundTaskEvent[];\n /** List of failed tasks */\n failedTasks: BackgroundTaskEvent[];\n /** Clear completed and failed tasks */\n clearCompletedAndFailedTasks: () => void;\n}\n\n/**\n * Streams background task events via SSE and accumulates them in a map keyed by taskId.\n *\n * Each incoming event (task.completed / task.failed) is stored in state so the UI\n * can react to completions — e.g., show a toast, update a badge, or display results.\n *\n * @example\n * ```tsx\n * const { tasks, isConnected, completedTasks } = useBackgroundTaskStream({ agentId: 'crypto-agent' });\n *\n * // Show a badge with completed count\n * const completedCount = completedTasks.length;\n * ```\n */\n\ntype EventType = Extract<\n AgentChunkType,\n {\n type:\n | 'background-task-running'\n | 'background-task-completed'\n | 'background-task-failed'\n | 'background-task-cancelled'\n | 'background-task-output'\n | 'background-task-suspended'\n | 'background-task-resumed';\n }\n>;\n\nconst EVENT_STATUS_MAP: Record<EventType['type'], BackgroundTaskStatus> = {\n 'background-task-running': 'running',\n 'background-task-output': 'running',\n 'background-task-completed': 'completed',\n 'background-task-failed': 'failed',\n 'background-task-cancelled': 'cancelled',\n 'background-task-suspended': 'suspended',\n 'background-task-resumed': 'running',\n};\n\nexport function useBackgroundTaskStream(options: UseBackgroundTaskStreamOptions = {}): UseBackgroundTaskStreamReturn {\n const { enabled = true, agentId, runId, threadId, resourceId, taskId } = options;\n const client = useMastraClient();\n\n const [tasks, setTasks] = useState<Record<string, BackgroundTaskEvent>>({});\n const [isConnected, setIsConnected] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const abortRef = useRef<AbortController | null>(null);\n const readerRef = useRef<BackgroundTaskStreamReader | null>(null);\n const connectSeqRef = useRef(0);\n\n const runningTasks = useMemo(() => {\n return Object.values(tasks).filter(task => task.status === 'running');\n }, [tasks]);\n\n const completedTasks = useMemo(() => {\n return Object.values(tasks).filter(task => task.status === 'completed');\n }, [tasks]);\n\n const failedTasks = useMemo(() => {\n return Object.values(tasks).filter(task => task.status === 'failed');\n }, [tasks]);\n\n const cleanup = useCallback(() => {\n readerRef.current?.cancel().catch(() => {});\n readerRef.current = null;\n abortRef.current?.abort();\n abortRef.current = null;\n setIsConnected(false);\n }, []);\n\n const connect = useCallback(async () => {\n const seq = ++connectSeqRef.current;\n cleanup();\n setError(null);\n\n const controller = new AbortController();\n abortRef.current = controller;\n\n try {\n const stream = await client.streamBackgroundTasks({ agentId, runId, threadId, resourceId, taskId });\n\n if (!stream) {\n setError(new Error('Stream connection failed'));\n return;\n }\n\n if (seq === connectSeqRef.current) {\n setIsConnected(true);\n }\n\n // Get a reader from the ReadableStream and store it in ref\n const reader = stream.getReader();\n readerRef.current = reader;\n\n while (!controller.signal.aborted) {\n const { done, value } = await reader.read();\n if (done) break;\n\n const event = value as EventType;\n if (event.type !== 'background-task-output') {\n setTasks(prev => ({\n ...prev,\n [event.payload.taskId]: {\n ...prev[event.payload.taskId],\n ...event.payload,\n status: EVENT_STATUS_MAP[event.type],\n args:\n ('args' in event.payload ? event.payload.args : undefined) ?? prev[event.payload.taskId]?.args ?? {},\n },\n }));\n }\n }\n } catch (err: any) {\n if (err?.name !== 'AbortError') {\n if (seq === connectSeqRef.current) {\n setError(err instanceof Error ? err : new Error(String(err)));\n }\n }\n } finally {\n if (seq === connectSeqRef.current) {\n setIsConnected(false);\n }\n }\n }, [client, agentId, runId, threadId, resourceId, taskId, cleanup]);\n\n useEffect(() => {\n if (!enabled) {\n cleanup();\n return;\n }\n\n void connect();\n return cleanup;\n }, [enabled, connect, cleanup]);\n\n const disconnect = useCallback(() => {\n cleanup();\n }, [cleanup]);\n\n const reconnect = useCallback(() => {\n void connect();\n }, [connect]);\n\n const clearCompletedAndFailedTasks = () => {\n setTasks(prev => {\n const newTasks = { ...prev };\n Object.values(newTasks).forEach(task => {\n if (\n task.status === 'completed' ||\n task.status === 'failed' ||\n task.status === 'cancelled' ||\n task.status === 'timed_out'\n ) {\n delete newTasks[task.taskId];\n }\n });\n return newTasks;\n });\n };\n\n return {\n tasks,\n isConnected,\n error,\n disconnect,\n reconnect,\n runningTasks,\n completedTasks,\n failedTasks,\n clearCompletedAndFailedTasks,\n };\n}\n\ntype BackgroundTaskResponse = Awaited<ReturnType<MastraClient['getBackgroundTask']>>;\n\nexport const useGetBackgroundTaskById = <TData = BackgroundTaskResponse>({\n backgroundTaskId,\n queryOptions,\n}: {\n backgroundTaskId: string;\n queryOptions?: MastraQueryOptions<BackgroundTaskResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n return useQuery({\n queryKey: ['background-task', backgroundTaskId],\n queryFn: () => client.getBackgroundTask(backgroundTaskId),\n ...queryOptions,\n });\n};\n","import type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nexport interface BrowserSessionProbe {\n hasSession: boolean;\n screencastAvailable: boolean;\n}\n\ninterface UseBrowserSessionProbeOptions<TData> {\n agentId?: string;\n threadId?: string;\n /** TanStack overrides spread last, e.g. `{ enabled: false }` for agents without browser tools. */\n queryOptions?: MastraQueryOptions<BrowserSessionProbe, TData>;\n}\n\nexport const browserSessionProbeQueryKey = (agentId?: string, threadId?: string) =>\n ['browser-session-probe', agentId, threadId] as const;\n\nconst LEGACY_FALLBACK: BrowserSessionProbe = { hasSession: true, screencastAvailable: true };\n\nconst isNotFoundError = (error: unknown): boolean => {\n if (!error || typeof error !== 'object') return false;\n if ('status' in error && (error as { status: unknown }).status === 404) return true;\n if ('statusCode' in error && (error as { statusCode: unknown }).statusCode === 404) return true;\n return false;\n};\n\n/**\n * Query hook that probes the server for the agent's browser session state.\n *\n * Used by {@link BrowserSessionProvider} to decide whether to open a screencast\n * WebSocket. The probe avoids two failure modes:\n *\n * 1. `screencastAvailable: false` — the server doesn't have `ws` / `@hono/node-ws`\n * installed (or the route was never registered). Opening a WS would fail and\n * trigger a reconnect loop.\n * 2. `hasSession: false` — no active browser session for this thread yet. Opening\n * a WS would succeed but sit idle, holding resources for no reason.\n *\n * When the endpoint itself returns 404 (older server that predates this probe),\n * the hook assumes screencast is available and a session is active so behavior\n * matches the legacy unconditional connect.\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport function useBrowserSessionProbe<TData = BrowserSessionProbe>({\n agentId,\n threadId,\n queryOptions,\n}: UseBrowserSessionProbeOptions<TData>): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery<BrowserSessionProbe, Error, TData>({\n queryKey: browserSessionProbeQueryKey(agentId, threadId),\n queryFn: async () => {\n if (!agentId) {\n return { hasSession: false, screencastAvailable: false };\n }\n\n try {\n return await client.getAgent(agentId).browserSession(threadId);\n } catch (error) {\n if (isNotFoundError(error)) {\n // Older server without the probe endpoint — fall back to legacy behavior.\n return LEGACY_FALLBACK;\n }\n throw error;\n }\n },\n // No polling: the probe fires once on mount, on window focus, and is\n // updated via `setQueriesData` from `tool-fallback.tsx` when a browser\n // tool call transitions. This avoids idle 5s polls and lets the probe\n // flip to `hasSession: true` the instant a tool call is seen.\n refetchOnWindowFocus: true,\n staleTime: 0,\n retry: 1,\n ...queryOptions,\n });\n}\n","/**\n * The wire-level error code the server emits on a 422 when a model is blocked\n * by the admin's builder policy. Kept as a local literal so the browser bundle\n * never imports server-only agent-builder EE code.\n */\nconst MODEL_NOT_ALLOWED_CODE = 'MODEL_NOT_ALLOWED';\n\nexport interface ModelNotAllowedDetails {\n message: string;\n attempted?: { provider?: string; modelId?: string };\n offendingLabel?: string;\n}\n\n/**\n * Detects HTTP 422 + MODEL_NOT_ALLOWED responses thrown by `MastraClientError`\n * (or any error carrying `status` + `body.error.code`). Returns the parsed\n * details when matched, or `null` otherwise.\n */\nexport function isModelNotAllowedError(err: unknown): ModelNotAllowedDetails | null {\n if (!err || typeof err !== 'object') return null;\n const candidate = err as { status?: number; body?: unknown; message?: string };\n if (candidate.status !== 422) return null;\n const body = candidate.body as { error?: { code?: unknown } } | undefined;\n const code = body?.error?.code;\n if (code !== MODEL_NOT_ALLOWED_CODE) return null;\n const errorBody = body!.error as {\n message?: string;\n attempted?: { provider?: string; modelId?: string };\n offendingLabel?: string;\n };\n return {\n message: errorBody.message || candidate.message || 'Model not allowed by admin policy',\n attempted: errorBody.attempted,\n offendingLabel: errorBody.offendingLabel,\n };\n}\n","import type {\n CreateStoredAgentParams,\n UpdateStoredAgentParams,\n ListStoredAgentsParams,\n StoredAgentResponse,\n ListStoredAgentsResponse,\n StoredAgentDependentsResponse,\n DeleteStoredAgentResponse,\n} 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';\nimport { isModelNotAllowedError } from './is-model-not-allowed';\n\nexport const useStoredAgents = <TData = ListStoredAgentsResponse>({\n queryOptions,\n ...params\n}: ListStoredAgentsParams & {\n queryOptions?: MastraQueryOptions<ListStoredAgentsResponse, TData>;\n} = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n const listParams = Object.keys(params).length > 0 ? params : undefined;\n\n return useQuery({\n queryKey: ['stored-agents', listParams],\n queryFn: () => client.listStoredAgents(listParams),\n ...queryOptions,\n });\n};\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useStoredAgent = <TData = StoredAgentResponse | null>({\n agentId,\n status,\n requestContext,\n queryOptions,\n}: {\n agentId?: string;\n status?: 'draft' | 'published';\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<StoredAgentResponse | null, TData>;\n} = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['stored-agent', agentId, status, requestContext],\n queryFn: async () => {\n if (!agentId) return null;\n try {\n return await client.getStoredAgent(agentId).details(requestContext, { status });\n } catch (error) {\n // 404 is expected for code-only agents that haven't been stored yet\n if (error && typeof error === 'object' && 'status' in error && (error as { status: number }).status === 404) {\n return null;\n }\n throw error;\n }\n },\n retry: false,\n ...queryOptions,\n });\n};\n\nexport type StoredAgent = StoredAgentResponse;\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useStoredAgentDependents = <TData = StoredAgentDependentsResponse>({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId?: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<StoredAgentDependentsResponse, TData>;\n} = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['stored-agent-dependents', agentId, requestContext],\n queryFn: () => client.getStoredAgent(agentId!).dependents(requestContext),\n retry: false,\n ...queryOptions,\n });\n};\n\nexport const useStoredAgentMutations = ({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId?: string;\n requestContext?: Record<string, any>;\n queryOptions?: {\n createStoredAgent?: MastraMutationOptions<StoredAgentResponse, CreateStoredAgentParams>;\n updateStoredAgent?: MastraMutationOptions<StoredAgentResponse, UpdateStoredAgentParams>;\n deleteStoredAgent?: MastraMutationOptions<DeleteStoredAgentResponse, void>;\n };\n} = {}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n // If the server rejects with HTTP 422 + MODEL_NOT_ALLOWED the admin policy\n // has likely changed under us — refresh the cached settings so the UI\n // re-renders against the latest server truth.\n const invalidateBuilderSettingsOnPolicyReject = (err: unknown) => {\n if (isModelNotAllowedError(err)) {\n void queryClient.invalidateQueries({ queryKey: ['builder-settings'] });\n }\n };\n\n const createMutation = useMutation({\n mutationFn: (params: CreateStoredAgentParams) => client.createStoredAgent(params),\n onSuccess: created => {\n // Prime the per-agent details cache with the response so the next page\n // (the edit page) can render the agent on first paint without a refetch.\n // The starter relies on this to immediately mount the conversation panel\n // and dispatch the user's initial message.\n queryClient.setQueryData(['stored-agent', created.id, 'draft', requestContext], created);\n queryClient.setQueryData(['stored-agent', created.id, undefined, requestContext], created);\n // Invalidate both stored-agents list and the merged agents list\n void queryClient.invalidateQueries({ queryKey: ['stored-agents'] });\n void queryClient.invalidateQueries({ queryKey: ['agents'] });\n // Invalidate the merged agent details so the freshly-created id resolves\n // instead of staying stuck on the initial `null` from the 404 lookup.\n void queryClient.invalidateQueries({ queryKey: ['agent', created.id] });\n },\n onError: invalidateBuilderSettingsOnPolicyReject,\n ...queryOptions?.createStoredAgent,\n });\n\n const updateMutation = useMutation({\n mutationFn: (params: UpdateStoredAgentParams) => {\n if (!agentId) throw new Error('agentId is required for update');\n return client.getStoredAgent(agentId).update(params, requestContext);\n },\n onSuccess: () => {\n // Invalidate lists\n void queryClient.invalidateQueries({ queryKey: ['stored-agents'] });\n void queryClient.invalidateQueries({ queryKey: ['agents'] });\n // Invalidate specific agent details\n if (agentId) {\n void queryClient.invalidateQueries({ queryKey: ['stored-agent', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n }\n },\n onError: invalidateBuilderSettingsOnPolicyReject,\n ...queryOptions?.updateStoredAgent,\n });\n\n const deleteMutation = useMutation({\n mutationFn: () => {\n if (!agentId) throw new Error('agentId is required for delete');\n return client.getStoredAgent(agentId).delete(requestContext);\n },\n onSuccess: () => {\n // Invalidate lists so the agents list page refetches without the deleted entry\n void queryClient.invalidateQueries({ queryKey: ['stored-agents'] });\n void queryClient.invalidateQueries({ queryKey: ['agents'] });\n // Drop the deleted entity from the cache so active observers don't refetch a 404\n if (agentId) {\n queryClient.removeQueries({ queryKey: ['stored-agent', agentId] });\n queryClient.removeQueries({ queryKey: ['agent', agentId] });\n }\n },\n ...queryOptions?.deleteStoredAgent,\n });\n\n return {\n createStoredAgent: createMutation,\n updateStoredAgent: updateMutation,\n deleteStoredAgent: deleteMutation,\n };\n};\n","import type { StoredAgentResponse, StoredAgentSkillConfig, UpdateStoredAgentParams } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\nimport { useStoredAgent } from './use-stored-agents';\n\n/**\n * Hook to read and mutate the skills config for a stored agent.\n *\n * The skills field is `Record<string, StoredAgentSkillConfig>` on the agent\n * snapshot. Each key is a stored skill ID and the value holds per-skill\n * overrides (description, instructions, pin, strategy).\n */\nexport function useAgentSkills({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId?: string;\n requestContext?: Record<string, any>;\n queryOptions?: {\n updateSkills?: MastraMutationOptions<StoredAgentResponse, Record<string, StoredAgentSkillConfig> | undefined>;\n };\n} = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n const { data: agent } = useStoredAgent({ agentId, status: 'draft', queryOptions: { enabled: Boolean(agentId) } });\n\n const skills = useMemo((): Record<string, StoredAgentSkillConfig> => {\n if (!agent?.skills) return {};\n // Handle conditional field: if it's an array of variants, merge values\n if (Array.isArray(agent.skills)) {\n const merged: Record<string, StoredAgentSkillConfig> = {};\n for (const variant of agent.skills) {\n Object.assign(merged, variant.value);\n }\n return merged;\n }\n return agent.skills as Record<string, StoredAgentSkillConfig>;\n }, [agent?.skills]);\n\n const updateSkills = useMutation({\n mutationFn: (newSkills: Record<string, StoredAgentSkillConfig> | undefined) => {\n if (!agentId) throw new Error('agentId is required');\n const params: UpdateStoredAgentParams = { skills: newSkills };\n return client.getStoredAgent(agentId).update(params, requestContext);\n },\n onSuccess: () => {\n if (agentId) {\n void queryClient.invalidateQueries({ queryKey: ['stored-agent', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['agent-versions', agentId] });\n }\n },\n ...queryOptions?.updateSkills,\n });\n\n return { skills, updateSkills };\n}\n","import type {\n ListAgentVersionsParams,\n CreateAgentVersionParams,\n ListAgentVersionsResponse,\n AgentVersionResponse,\n CompareVersionsResponse,\n ActivateAgentVersionResponse,\n DeleteAgentVersionResponse,\n} from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery, useMutation, useQueryClient, skipToken } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\nexport type { ListAgentVersionsParams, CreateAgentVersionParams };\n\ntype UseAgentVersionsParams<TData = ListAgentVersionsResponse> = {\n agentId?: string;\n params?: ListAgentVersionsParams;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<ListAgentVersionsResponse, TData>;\n};\n\n/**\n * Hook to list versions of a stored agent\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useAgentVersions = <TData = ListAgentVersionsResponse>({\n agentId,\n params,\n requestContext,\n queryOptions,\n}: UseAgentVersionsParams<TData>): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<ListAgentVersionsResponse, Error, TData>({\n queryKey: ['agent-versions', agentId, params, requestContext],\n queryFn: agentId ? () => client.getStoredAgent(agentId).listVersions(params, requestContext) : skipToken,\n ...queryOptions,\n });\n};\n\n/**\n * Hook to get a single version of a stored agent\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useAgentVersion = <TData = AgentVersionResponse>({\n agentId,\n versionId,\n requestContext,\n queryOptions,\n}: {\n agentId: string;\n versionId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<AgentVersionResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<AgentVersionResponse, Error, TData>({\n queryKey: ['agent-version', agentId, versionId, requestContext],\n queryFn: () => client.getStoredAgent(agentId).getVersion(versionId, requestContext),\n ...queryOptions,\n });\n};\n\n/**\n * Hook to create a new version of a stored agent\n */\nexport const useCreateAgentVersion = ({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraMutationOptions<AgentVersionResponse, CreateAgentVersionParams | undefined>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<AgentVersionResponse, Error, CreateAgentVersionParams | undefined>({\n mutationFn: (params?: CreateAgentVersionParams) =>\n client.getStoredAgent(agentId).createVersion(params, requestContext),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['agent-versions', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n },\n ...queryOptions,\n });\n};\n\n/**\n * Hook to activate a specific version of a stored agent\n */\nexport const useActivateAgentVersion = ({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraMutationOptions<ActivateAgentVersionResponse, string>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<ActivateAgentVersionResponse, Error, string>({\n mutationFn: (versionId: string) => client.getStoredAgent(agentId).activateVersion(versionId, requestContext),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['agent-versions', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n },\n ...queryOptions,\n });\n};\n\n/**\n * Hook to restore a specific version of a stored agent (creates a new version from an old one)\n */\nexport const useRestoreAgentVersion = ({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraMutationOptions<AgentVersionResponse, string>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<AgentVersionResponse, Error, string>({\n mutationFn: (versionId: string) => client.getStoredAgent(agentId).restoreVersion(versionId, requestContext),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['agent-versions', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n },\n ...queryOptions,\n });\n};\n\n/**\n * Hook to delete a specific version of a stored agent\n */\nexport const useDeleteAgentVersion = ({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraMutationOptions<DeleteAgentVersionResponse, string>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<DeleteAgentVersionResponse, Error, string>({\n mutationFn: (versionId: string) => client.getStoredAgent(agentId).deleteVersion(versionId, requestContext),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['agent-versions', agentId] });\n },\n ...queryOptions,\n });\n};\n\n/**\n * Hook to compare two versions of a stored agent\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useCompareAgentVersions = <TData = CompareVersionsResponse>({\n agentId,\n fromVersionId,\n toVersionId,\n requestContext,\n queryOptions,\n}: {\n agentId: string;\n fromVersionId: string;\n toVersionId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<CompareVersionsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<CompareVersionsResponse, Error, TData>({\n queryKey: ['agent-versions-compare', agentId, fromVersionId, toVersionId, requestContext],\n queryFn: () => client.getStoredAgent(agentId).compareVersions(fromVersionId, toVersionId, requestContext),\n ...queryOptions,\n });\n};\n","import { useState, useEffect, useCallback, useRef } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\n\nfunction parseJsonString(jsonString: string): any {\n try {\n return JSON.stringify(JSON.parse(jsonString), null, 2);\n } catch {\n return jsonString;\n }\n}\n\nexport function useAgentWorkingMemory(\n agentId: string,\n threadId: string,\n resourceId: string,\n requestContext?: Record<string, any>,\n) {\n const client = useMastraClient();\n const [threadExists, setThreadExists] = useState(false);\n const [workingMemoryData, setWorkingMemoryData] = useState<string | null>(null);\n const [workingMemorySource, setWorkingMemorySource] = useState<'thread' | 'resource'>('thread');\n const [workingMemoryFormat, setWorkingMemoryFormat] = useState<'json' | 'markdown'>('markdown');\n const [isLoading, setIsLoading] = useState(true);\n const [isUpdating, setIsUpdating] = useState(false);\n const latestRequest = useRef(0);\n\n const refetch = useCallback(async () => {\n const requestId = ++latestRequest.current;\n setIsLoading(true);\n try {\n if (!agentId || !threadId) {\n setWorkingMemoryData(null);\n setIsLoading(false);\n return;\n }\n const res = await client.getWorkingMemory({ agentId, threadId, resourceId, requestContext });\n if (requestId !== latestRequest.current) return;\n const { workingMemory, source, workingMemoryTemplate, threadExists } = res as {\n workingMemory: string | null;\n source: 'thread' | 'resource';\n workingMemoryTemplate: { content: string; format: 'json' | 'markdown' };\n threadExists: boolean;\n };\n setThreadExists(threadExists);\n setWorkingMemoryData(workingMemory);\n setWorkingMemorySource(source);\n setWorkingMemoryFormat(workingMemoryTemplate?.format || 'markdown');\n if (workingMemoryTemplate?.format === 'json') {\n let dataToSet = '';\n if (workingMemory) {\n dataToSet = parseJsonString(workingMemory);\n } else if (workingMemoryTemplate?.content) {\n dataToSet = parseJsonString(workingMemoryTemplate.content);\n } else {\n dataToSet = '';\n }\n setWorkingMemoryData(dataToSet);\n } else {\n setWorkingMemoryData(workingMemory || workingMemoryTemplate?.content || '');\n }\n } catch (error) {\n if (requestId !== latestRequest.current) return;\n setWorkingMemoryData(null);\n console.error('Error fetching working memory', error);\n } finally {\n if (requestId === latestRequest.current) setIsLoading(false);\n }\n }, [agentId, threadId, resourceId, client, requestContext]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n const updateWorkingMemory = async (newMemory: string) => {\n setIsUpdating(true);\n try {\n if (workingMemoryFormat === 'json') {\n try {\n JSON.parse(newMemory);\n } catch {\n throw new Error('Invalid JSON working memory');\n }\n }\n await client.updateWorkingMemory({ agentId, threadId, workingMemory: newMemory, resourceId, requestContext });\n void refetch();\n } catch (error) {\n console.error('Error updating working memory', error);\n throw error;\n } finally {\n setIsUpdating(false);\n }\n };\n\n return {\n threadExists,\n workingMemoryData,\n workingMemorySource,\n workingMemoryFormat,\n isLoading,\n isUpdating,\n refetch,\n updateWorkingMemory,\n };\n}\n","import type { StoredAgentResponse, StoredWorkspaceRef, UpdateStoredAgentParams } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\nimport { useStoredAgent } from './use-stored-agents';\n\n/**\n * Hook to read and mutate the workspace reference for a stored agent.\n *\n * The workspace ref is part of the agent snapshot config and can be:\n * - `{ type: 'id', workspaceId }` — references a stored workspace by ID\n * - `{ type: 'inline', config }` — inline workspace config\n * - `undefined` — no workspace assigned\n */\nexport function useAgentWorkspace({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId?: string;\n requestContext?: Record<string, any>;\n queryOptions?: {\n updateWorkspace?: MastraMutationOptions<StoredAgentResponse, StoredWorkspaceRef | undefined>;\n };\n} = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n const { data: agent } = useStoredAgent({ agentId, status: 'draft', queryOptions: { enabled: Boolean(agentId) } });\n\n const workspace = useMemo((): StoredWorkspaceRef | undefined => {\n if (!agent?.workspace) return undefined;\n // Handle conditional field: if it's an array of variants, take the first value\n if (Array.isArray(agent.workspace)) {\n return agent.workspace[0]?.value as StoredWorkspaceRef | undefined;\n }\n return agent.workspace as StoredWorkspaceRef;\n }, [agent?.workspace]);\n\n const updateWorkspace = useMutation({\n mutationFn: (ref: StoredWorkspaceRef | undefined) => {\n if (!agentId) throw new Error('agentId is required');\n const params: UpdateStoredAgentParams = { workspace: ref };\n return client.getStoredAgent(agentId).update(params, requestContext);\n },\n onSuccess: () => {\n if (agentId) {\n void queryClient.invalidateQueries({ queryKey: ['stored-agent', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['agent-versions', agentId] });\n }\n },\n ...queryOptions?.updateWorkspace,\n });\n\n return { workspace, updateWorkspace };\n}\n","import type { GetAgentResponse } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useAgent = <TData = GetAgentResponse | null>({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId?: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<GetAgentResponse | null, TData>;\n} = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['agent', agentId, requestContext],\n queryFn: () => (agentId ? client.getAgent(agentId).details(requestContext) : null),\n retry: false,\n ...queryOptions,\n });\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\ntype AgentsModelProvidersResponse = Awaited<ReturnType<MastraClient['listAgentsModelProviders']>>;\n\nexport const useAgentsModelProviders = <TData = AgentsModelProvidersResponse>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<AgentsModelProvidersResponse, TData> } = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['agents-model-providers'],\n queryFn: () => client.listAgentsModelProviders(),\n retry: false,\n ...queryOptions,\n });\n};\n","import type {\n MastraClient,\n ReorderModelListParams,\n UpdateModelInModelListParams,\n UpdateModelParams,\n} from '@mastra/client-js';\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\nimport type { UseMutationResult, UseQueryResult } from '@tanstack/react-query';\n\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\ntype Agent = ReturnType<MastraClient['getAgent']>;\ntype ListAgentsResponse = Awaited<ReturnType<MastraClient['listAgents']>>;\nexport type ModelUpdateResponse = Awaited<ReturnType<Agent['updateModel']>>;\n\nexport const useAgents = <TData = ListAgentsResponse>({\n requestContext,\n queryOptions,\n}: {\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<ListAgentsResponse, TData>;\n} = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['agents', requestContext],\n queryFn: () => client.listAgents(requestContext),\n ...queryOptions,\n });\n};\n\nexport const useUpdateAgentModel = ({\n agentId,\n queryOptions,\n}: {\n agentId: string;\n queryOptions?: MastraMutationOptions<ModelUpdateResponse, UpdateModelParams>;\n}): UseMutationResult<ModelUpdateResponse, Error, UpdateModelParams> => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: async (payload: UpdateModelParams) => client.getAgent(agentId).updateModel(payload),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n },\n onError: err => {\n console.error('Error updating model', err);\n },\n ...queryOptions,\n });\n};\n\nexport const useReorderModelList = ({\n agentId,\n queryOptions,\n}: {\n agentId: string;\n queryOptions?: MastraMutationOptions<ModelUpdateResponse, ReorderModelListParams>;\n}): UseMutationResult<ModelUpdateResponse, Error, ReorderModelListParams> => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: async (payload: ReorderModelListParams) => client.getAgent(agentId).reorderModelList(payload),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n },\n onError: err => {\n console.error('Error reordering model list', err);\n },\n ...queryOptions,\n });\n};\n\nexport const useUpdateModelInModelList = ({\n agentId,\n queryOptions,\n}: {\n agentId: string;\n queryOptions?: MastraMutationOptions<ModelUpdateResponse, UpdateModelInModelListParams>;\n}): UseMutationResult<ModelUpdateResponse, Error, UpdateModelInModelListParams> => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: async (payload: UpdateModelInModelListParams) =>\n client.getAgent(agentId).updateModelInModelList(payload),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n },\n onError: err => {\n console.error('Error updating model in model list', err);\n },\n ...queryOptions,\n });\n};\n\nexport const useResetAgentModel = ({\n agentId,\n queryOptions,\n}: {\n agentId: string;\n queryOptions?: MastraMutationOptions<ModelUpdateResponse, void>;\n}): UseMutationResult<ModelUpdateResponse, Error, void> => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: async () => client.getAgent(agentId).resetModel(),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n },\n onError: err => {\n console.error('Error resetting model', err);\n },\n ...queryOptions,\n });\n};\n","import { useMutation } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\ninterface CloseBrowserParams {\n agentId: string;\n threadId?: string;\n}\n\n/**\n * Mutation hook for closing an agent's browser session.\n */\nexport function useCloseBrowser({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<{ success: boolean }, CloseBrowserParams> } = {}) {\n const client = useMastraClient();\n\n return useMutation<{ success: boolean }, Error, CloseBrowserParams>({\n mutationFn: ({ agentId, threadId }) => client.getAgent(agentId).closeBrowser(threadId),\n onError: err => {\n console.error('[useCloseBrowser] Error closing browser:', err);\n },\n ...queryOptions,\n });\n}\n","import type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\ninterface ApiInstructionBlock {\n type: string;\n content?: string;\n id?: string;\n /** Form-format ref blocks use `promptBlockId` instead of `id` */\n promptBlockId?: string;\n rules?: unknown;\n}\n\n/**\n * Normalize blocks to API format.\n * Form-format ref blocks have `{ type: 'prompt_block_ref', promptBlockId }`,\n * while API-format blocks have `{ type: 'prompt_block_ref', id }`.\n */\nfunction toApiBlocks(blocks: ApiInstructionBlock[]) {\n return blocks.map(block => {\n if (block.type === 'prompt_block_ref') {\n // Form-format blocks have `promptBlockId` (the storage ID) and `id` (form-internal UUID).\n // API-format blocks have `id` (the storage ID). Prefer promptBlockId when present.\n return { type: 'prompt_block_ref' as const, id: block.promptBlockId ?? block.id, rules: block.rules };\n }\n return { type: block.type, content: block.content, rules: block.rules };\n });\n}\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport function usePreviewInstructions<TData = string>({\n blocks,\n requestContext,\n queryOptions,\n}: {\n blocks: ApiInstructionBlock[] | undefined;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<string, TData>;\n}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['preview-instructions', blocks, requestContext],\n queryFn: async () => {\n if (!blocks || blocks.length === 0) return '';\n\n const response = await client.request<{ result: string }>('/stored/agents/preview-instructions', {\n method: 'POST',\n body: { blocks: toApiBlocks(blocks), context: requestContext },\n });\n\n return response.result;\n },\n ...queryOptions,\n });\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\n\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nexport type ListStoredSkillsResponse = Awaited<ReturnType<MastraClient['listStoredSkills']>>;\n\nexport function useStoredSkills<TData = ListStoredSkillsResponse>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<ListStoredSkillsResponse, TData> } = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['stored-skills'],\n queryFn: () => client.listStoredSkills(),\n ...queryOptions,\n });\n}\n","import type { ChannelPlatformInfo, ChannelInstallationInfo, ChannelConnectResult } from '@mastra/client-js';\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\nimport type { UseMutationResult, UseQueryResult } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\nexport type { ChannelPlatformInfo, ChannelInstallationInfo, ChannelConnectResult };\n\nexport const useChannelPlatforms = <TData = ChannelPlatformInfo[]>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<ChannelPlatformInfo[], TData> } = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<ChannelPlatformInfo[], Error, TData>({\n queryKey: ['channels', 'platforms'],\n queryFn: () => client.channels.listPlatforms(),\n staleTime: 60 * 1000,\n retry: false,\n ...queryOptions,\n });\n};\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useChannelInstallations = <TData = ChannelInstallationInfo[]>({\n platform,\n agentId,\n queryOptions,\n}: {\n platform: string;\n agentId: string;\n queryOptions?: MastraQueryOptions<ChannelInstallationInfo[], TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<ChannelInstallationInfo[], Error, TData>({\n queryKey: ['channels', 'installations', platform, agentId],\n queryFn: () => client.channels.listInstallations(platform, agentId),\n staleTime: 10 * 1000,\n retry: false,\n ...queryOptions,\n });\n};\n\n/**\n * Reconcile an agent's installation with platform state — activates a pending\n * installation whose connect flow completed out-of-band (e.g. a Discord bot\n * invite finished in another tab). Resolves null on platforms without\n * reconciliation. Call it deliberately (e.g. on window focus while a connect\n * is in flight) — it is a write, not a read.\n */\nexport const useReconcileChannelInstallation = ({\n platform,\n queryOptions,\n}: {\n platform: string;\n queryOptions?: MastraMutationOptions<ChannelInstallationInfo | null, string>;\n}): UseMutationResult<ChannelInstallationInfo | null, Error, string> => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<ChannelInstallationInfo | null, Error, string>({\n mutationFn: agentId => client.channels.reconcileInstallation(platform, agentId),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['channels', 'installations', platform] });\n },\n ...queryOptions,\n });\n};\n\nexport const useConnectChannel = ({\n platform,\n queryOptions,\n}: {\n platform: string;\n queryOptions?: MastraMutationOptions<ChannelConnectResult, { agentId: string; options?: Record<string, unknown> }>;\n}): UseMutationResult<ChannelConnectResult, Error, { agentId: string; options?: Record<string, unknown> }> => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<ChannelConnectResult, Error, { agentId: string; options?: Record<string, unknown> }>({\n mutationFn: ({ agentId, options }) =>\n client.channels.connect(platform, agentId, {\n ...options,\n // Tell the server to redirect back here after OAuth\n redirectUrl: window.location.href,\n }),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['channels', 'installations', platform] });\n },\n ...queryOptions,\n });\n};\n\nexport const useDisconnectChannel = ({\n platform,\n queryOptions,\n}: {\n platform: string;\n queryOptions?: MastraMutationOptions<{ success: boolean }, string>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<{ success: boolean }, Error, string>({\n mutationFn: agentId => client.channels.disconnect(platform, agentId),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['channels', 'installations', platform] });\n },\n ...queryOptions,\n });\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { RequestContext } from '@mastra/core/di';\nimport { useMutation } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\ntype ExecuteAgentToolResponse = Awaited<ReturnType<ReturnType<MastraClient['getAgent']>['executeTool']>>;\n\nexport interface ExecuteToolInput {\n agentId: string;\n toolId: string;\n input: any;\n playgroundRequestContext?: Record<string, any>;\n}\n\nexport const useExecuteAgentTool = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<ExecuteAgentToolResponse, ExecuteToolInput> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ agentId, toolId, input, playgroundRequestContext }: ExecuteToolInput) => {\n const requestContext = new RequestContext();\n Object.entries(playgroundRequestContext ?? {}).forEach(([key, value]) => {\n requestContext.set(key, value);\n });\n return client.getAgent(agentId).executeTool(toolId, { data: input, requestContext });\n },\n ...queryOptions,\n });\n};\n"],"mappings":";;;;;AAmBA,MAAM,WAAW;AAEjB,MAAM,cAAc;AAEpB,MAAM,eAAe,YAA6B,IAAI,KAAK,QAAQ,SAAS,CAAC,CAAC,QAAQ;AAEtF,MAAM,eAAe,GAAoB,MAAuB,YAAY,CAAC,IAAI,YAAY,CAAC;AAE9F,MAAa,oBAA+C,EAC1D,UACA,SACA,QACA,gBACA,mBACkC;CAClC,MAAM,SAAS,gBAAgB;CAE/B,OAAO,iBAAiB;EACtB,UAAU;GAAC;GAAU;GAAY;GAAU;GAAS;EAAc;EAClE,kBAAkB;EAClB,SACE,UAAU,YACL,EAAE,WAAW,gBACZ,OAAO,mBAAmB,UAAU;GAClC;GACA;GACA,wBAAwB;GACxB,SAAS;GACT,SAAS;IAAE,OAAO;IAAa,WAAW;GAAO;GAGjD,QAAQ,YAAY,EAAE,WAAW,EAAE,KAAK,IAAI,KAAK,SAAS,EAAE,EAAE,IAAI,KAAA;EACpE,CAAC,IACH;EACN,mBAAmB,UAAU,WAAW,kBAAkB;GACxD,IAAI,CAAC,SAAS,WAAW,SAAS,SAAS,WAAW,GAAG,OAAO,KAAA;GAChE,MAAM,OAAO,IAAI,KAAK,KAAK,IAAI,GAAG,SAAS,SAAS,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC,YAAY;GAEnF,OAAO,SAAS,gBAAgB,KAAA,IAAY;EAC9C;EACA,SAAS,SAAgB;GACvB,MAAM,uBAAO,IAAI,IAAY;GAC7B,MAAM,WAAW,KAAK,MACnB,SAAQ,SAAQ,KAAK,QAAQ,CAAC,CAC9B,Q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AiB,kBAAkB,EAAE,UAAU;IAAC;IAAY;IAAiB;GAAQ,EAAE,CAAC;EAC1F;EACA,GAAG;CACL,CAAC;AACH;AAEA,MAAa,wBAAwB,EACnC,UACA,mBAII;CACJ,MAAM,SAAS,gBAAgB;CAC/B,MAAM,cAAc,eAAe;CAEnC,OAAO,YAAiD;EACtD,aAAY,YAAW,OAAO,SAAS,WAAW,UAAU,OAAO;EACnE,iBAAiB;GACf,YAAiB,kBAAkB,EAAE,UAAU;IAAC;IAAY;IAAiB;GAAQ,EAAE,CAAC;EAC1F;EACA,GAAG;CACL,CAAC;AACH;;;ACjGA,MAAa,uBAAuB,EAClC,iBACwF,CAAC,MAAM;CAC/F,MAAM,SAAS,gBAAgB;CAC/B,OAAO,YAAY;EACjB,YAAY,OAAO,EAAE,SAAS,QAAQ,OAAO,+BAAiD;GAC5F,MAAM,iBAAiB,IAAI,eAAe;GAC1C,OAAO,QAAQ,4BAA4B,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;IACvE,eAAe,IAAI,KAAK,KAAK;GAC/B,CAAC;GACD,OAAO,OAAO,SAAS,OAAO,CAAC,CAAC,YAAY,QAAQ;IAAE,MAAM;IAAO;GAAe,CAAC;EACrF;EACA,GAAG;CACL,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/hooks/agents/use-agent-messages.ts","../../../src/hooks/agents/use-agent-plan.ts","../../../src/hooks/agents/use-background-tasks.ts","../../../src/hooks/agents/use-browser-session-probe.ts","../../../src/hooks/agents/is-model-not-allowed.ts","../../../src/hooks/agents/use-stored-agents.ts","../../../src/hooks/agents/use-agent-skills.ts","../../../src/hooks/agents/use-agent-versions.ts","../../../src/hooks/agents/use-agent-working-memory.ts","../../../src/hooks/agents/use-agent-workspace.ts","../../../src/hooks/agents/use-agent.ts","../../../src/hooks/agents/use-agents-model-providers.ts","../../../src/hooks/agents/use-agents.ts","../../../src/hooks/agents/use-close-browser.ts","../../../src/hooks/agents/use-preview-instructions.ts","../../../src/hooks/agents/use-stored-skills.ts","../../../src/hooks/agents/use-channels.ts","../../../src/hooks/agents/use-execute-agent-tool.ts"],"sourcesContent":["import type { MastraClient } from '@mastra/client-js';\nimport type { MastraDBMessage } from '@mastra/core/agent/message-list';\nimport { skipToken, useInfiniteQuery } from '@tanstack/react-query';\nimport type { InfiniteData, QueryKey } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraInfiniteQueryOptions } from '../shared/query-options';\n\ntype AgentMessagesPage = Awaited<ReturnType<MastraClient['listThreadMessages']>>;\n\ntype AgentMessagesData = InfiniteData<AgentMessagesPage, string> & { messages: MastraDBMessage[] };\n\nexport interface UseAgentMessagesProps<TData = AgentMessagesData> {\n threadId?: string;\n agentId: string;\n memory: boolean;\n requestContext?: Record<string, any>;\n queryOptions?: MastraInfiniteQueryOptions<AgentMessagesPage, TData, QueryKey, string>;\n}\n\nconst PER_PAGE = 40;\n\nconst NEWEST_PAGE = '';\n\nconst createdAtMs = (message: MastraDBMessage) => new Date(message.createdAt).getTime();\n\nconst byCreatedAt = (a: MastraDBMessage, b: MastraDBMessage) => createdAtMs(a) - createdAtMs(b);\n\nexport const useAgentMessages = <TData = AgentMessagesData>({\n threadId,\n agentId,\n memory,\n requestContext,\n queryOptions,\n}: UseAgentMessagesProps<TData>) => {\n const client = useMastraClient();\n\n return useInfiniteQuery({\n queryKey: ['memory', 'messages', threadId, agentId, requestContext],\n initialPageParam: NEWEST_PAGE,\n queryFn:\n memory && threadId\n ? ({ pageParam: olderThan }) =>\n client.listThreadMessages(threadId, {\n agentId,\n requestContext,\n includeSystemReminders: true,\n perPage: PER_PAGE,\n orderBy: { field: 'createdAt', direction: 'DESC' },\n // Inclusive bound: messages sharing the oldest createdAt of the previous page\n // may have been cut off by perPage, so re-ask for them and dedupe by id below.\n filter: olderThan ? { dateRange: { end: new Date(olderThan) } } : undefined,\n })\n : skipToken,\n getNextPageParam: (lastPage, _allPages, lastPageParam) => {\n if (!lastPage.hasMore || lastPage.messages.length === 0) return undefined;\n const next = new Date(Math.min(...lastPage.messages.map(createdAtMs))).toISOString();\n // A full page of same-timestamp messages would re-request itself forever.\n return next === lastPageParam ? undefined : next;\n },\n select: (data): TData => {\n const seen = new Set<string>();\n const messages = data.pages\n .flatMap(page => page.messages)\n .filter(message => {\n if (seen.has(message.id)) return false;\n seen.add(message.id);\n return true;\n })\n .sort(byCreatedAt);\n return { ...data, messages } as AgentMessagesData as TData;\n },\n staleTime: 0,\n gcTime: 0,\n retry: false,\n refetchOnWindowFocus: false,\n ...queryOptions,\n });\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\ntype AgentPlanResponse = Awaited<ReturnType<ReturnType<MastraClient['getAgent']>['readPlan']>>;\n\ninterface UseAgentPlanOptions<TData> {\n agentId: string;\n path: string;\n agentVersionId?: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<AgentPlanResponse, TData>;\n}\n\nexport function useAgentPlan<TData = AgentPlanResponse>({\n agentId,\n path,\n agentVersionId,\n requestContext,\n queryOptions,\n}: UseAgentPlanOptions<TData>): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['agent-plan', agentId, agentVersionId, path, requestContext],\n queryFn: () => {\n const agent = agentVersionId ? client.getAgent(agentId, { versionId: agentVersionId }) : client.getAgent(agentId);\n return agent.readPlan(path, requestContext);\n },\n retry: false,\n ...queryOptions,\n });\n}\n","import type { MastraClient, StreamBackgroundTasksParams } from '@mastra/client-js';\nimport type { BackgroundTaskStatus } from '@mastra/core/background-tasks';\nimport type { AgentChunkType } from '@mastra/core/stream';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\ntype BackgroundTaskStreamReader = ReturnType<Awaited<ReturnType<MastraClient['streamBackgroundTasks']>>['getReader']>;\n\nexport interface BackgroundTaskEvent {\n taskId: string;\n toolName: string;\n toolCallId: string;\n agentId: string;\n runId: string;\n result?: unknown;\n error?: { message: string; stack?: string };\n status: BackgroundTaskStatus;\n args: Record<string, unknown>;\n suspendPayload?: unknown;\n}\n\nexport interface UseBackgroundTaskStreamOptions extends StreamBackgroundTasksParams {\n /** Whether the stream is active. Default: true */\n enabled?: boolean;\n}\n\nexport interface UseBackgroundTaskStreamReturn {\n /** Map of taskId → latest event data */\n tasks: Record<string, BackgroundTaskEvent>;\n /** Whether the stream is currently connected */\n isConnected: boolean;\n /** Any connection error */\n error: Error | null;\n /** Manually disconnect the stream */\n disconnect: () => void;\n /** Manually reconnect the stream */\n reconnect: () => void;\n /** List of running tasks */\n runningTasks: BackgroundTaskEvent[];\n /** List of completed tasks */\n completedTasks: BackgroundTaskEvent[];\n /** List of failed tasks */\n failedTasks: BackgroundTaskEvent[];\n /** Clear completed and failed tasks */\n clearCompletedAndFailedTasks: () => void;\n}\n\n/**\n * Streams background task events via SSE and accumulates them in a map keyed by taskId.\n *\n * Each incoming event (task.completed / task.failed) is stored in state so the UI\n * can react to completions — e.g., show a toast, update a badge, or display results.\n *\n * @example\n * ```tsx\n * const { tasks, isConnected, completedTasks } = useBackgroundTaskStream({ agentId: 'crypto-agent' });\n *\n * // Show a badge with completed count\n * const completedCount = completedTasks.length;\n * ```\n */\n\ntype EventType = Extract<\n AgentChunkType,\n {\n type:\n | 'background-task-running'\n | 'background-task-completed'\n | 'background-task-failed'\n | 'background-task-cancelled'\n | 'background-task-output'\n | 'background-task-suspended'\n | 'background-task-resumed';\n }\n>;\n\nconst EVENT_STATUS_MAP: Record<EventType['type'], BackgroundTaskStatus> = {\n 'background-task-running': 'running',\n 'background-task-output': 'running',\n 'background-task-completed': 'completed',\n 'background-task-failed': 'failed',\n 'background-task-cancelled': 'cancelled',\n 'background-task-suspended': 'suspended',\n 'background-task-resumed': 'running',\n};\n\nexport function useBackgroundTaskStream(options: UseBackgroundTaskStreamOptions = {}): UseBackgroundTaskStreamReturn {\n const { enabled = true, agentId, runId, threadId, resourceId, taskId } = options;\n const client = useMastraClient();\n\n const [tasks, setTasks] = useState<Record<string, BackgroundTaskEvent>>({});\n const [isConnected, setIsConnected] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const abortRef = useRef<AbortController | null>(null);\n const readerRef = useRef<BackgroundTaskStreamReader | null>(null);\n const connectSeqRef = useRef(0);\n\n const runningTasks = useMemo(() => {\n return Object.values(tasks).filter(task => task.status === 'running');\n }, [tasks]);\n\n const completedTasks = useMemo(() => {\n return Object.values(tasks).filter(task => task.status === 'completed');\n }, [tasks]);\n\n const failedTasks = useMemo(() => {\n return Object.values(tasks).filter(task => task.status === 'failed');\n }, [tasks]);\n\n const cleanup = useCallback(() => {\n readerRef.current?.cancel().catch(() => {});\n readerRef.current = null;\n abortRef.current?.abort();\n abortRef.current = null;\n setIsConnected(false);\n }, []);\n\n const connect = useCallback(async () => {\n const seq = ++connectSeqRef.current;\n cleanup();\n setError(null);\n\n const controller = new AbortController();\n abortRef.current = controller;\n\n try {\n const stream = await client.streamBackgroundTasks({ agentId, runId, threadId, resourceId, taskId });\n\n if (!stream) {\n setError(new Error('Stream connection failed'));\n return;\n }\n\n if (seq === connectSeqRef.current) {\n setIsConnected(true);\n }\n\n // Get a reader from the ReadableStream and store it in ref\n const reader = stream.getReader();\n readerRef.current = reader;\n\n while (!controller.signal.aborted) {\n const { done, value } = await reader.read();\n if (done) break;\n\n const event = value as EventType;\n if (event.type !== 'background-task-output') {\n setTasks(prev => ({\n ...prev,\n [event.payload.taskId]: {\n ...prev[event.payload.taskId],\n ...event.payload,\n status: EVENT_STATUS_MAP[event.type],\n args:\n ('args' in event.payload ? event.payload.args : undefined) ?? prev[event.payload.taskId]?.args ?? {},\n },\n }));\n }\n }\n } catch (err: any) {\n if (err?.name !== 'AbortError') {\n if (seq === connectSeqRef.current) {\n setError(err instanceof Error ? err : new Error(String(err)));\n }\n }\n } finally {\n if (seq === connectSeqRef.current) {\n setIsConnected(false);\n }\n }\n }, [client, agentId, runId, threadId, resourceId, taskId, cleanup]);\n\n useEffect(() => {\n if (!enabled) {\n cleanup();\n return;\n }\n\n void connect();\n return cleanup;\n }, [enabled, connect, cleanup]);\n\n const disconnect = useCallback(() => {\n cleanup();\n }, [cleanup]);\n\n const reconnect = useCallback(() => {\n void connect();\n }, [connect]);\n\n const clearCompletedAndFailedTasks = () => {\n setTasks(prev => {\n const newTasks = { ...prev };\n Object.values(newTasks).forEach(task => {\n if (\n task.status === 'completed' ||\n task.status === 'failed' ||\n task.status === 'cancelled' ||\n task.status === 'timed_out'\n ) {\n delete newTasks[task.taskId];\n }\n });\n return newTasks;\n });\n };\n\n return {\n tasks,\n isConnected,\n error,\n disconnect,\n reconnect,\n runningTasks,\n completedTasks,\n failedTasks,\n clearCompletedAndFailedTasks,\n };\n}\n\ntype BackgroundTaskResponse = Awaited<ReturnType<MastraClient['getBackgroundTask']>>;\n\nexport const useGetBackgroundTaskById = <TData = BackgroundTaskResponse>({\n backgroundTaskId,\n queryOptions,\n}: {\n backgroundTaskId: string;\n queryOptions?: MastraQueryOptions<BackgroundTaskResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n return useQuery({\n queryKey: ['background-task', backgroundTaskId],\n queryFn: () => client.getBackgroundTask(backgroundTaskId),\n ...queryOptions,\n });\n};\n","import type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nexport interface BrowserSessionProbe {\n hasSession: boolean;\n screencastAvailable: boolean;\n}\n\ninterface UseBrowserSessionProbeOptions<TData> {\n agentId?: string;\n threadId?: string;\n /** TanStack overrides spread last, e.g. `{ enabled: false }` for agents without browser tools. */\n queryOptions?: MastraQueryOptions<BrowserSessionProbe, TData>;\n}\n\nexport const browserSessionProbeQueryKey = (agentId?: string, threadId?: string) =>\n ['browser-session-probe', agentId, threadId] as const;\n\nconst LEGACY_FALLBACK: BrowserSessionProbe = { hasSession: true, screencastAvailable: true };\n\nconst isNotFoundError = (error: unknown): boolean => {\n if (!error || typeof error !== 'object') return false;\n if ('status' in error && (error as { status: unknown }).status === 404) return true;\n if ('statusCode' in error && (error as { statusCode: unknown }).statusCode === 404) return true;\n return false;\n};\n\n/**\n * Query hook that probes the server for the agent's browser session state.\n *\n * Used by {@link BrowserSessionProvider} to decide whether to open a screencast\n * WebSocket. The probe avoids two failure modes:\n *\n * 1. `screencastAvailable: false` — the server doesn't have `ws` / `@hono/node-ws`\n * installed (or the route was never registered). Opening a WS would fail and\n * trigger a reconnect loop.\n * 2. `hasSession: false` — no active browser session for this thread yet. Opening\n * a WS would succeed but sit idle, holding resources for no reason.\n *\n * When the endpoint itself returns 404 (older server that predates this probe),\n * the hook assumes screencast is available and a session is active so behavior\n * matches the legacy unconditional connect.\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport function useBrowserSessionProbe<TData = BrowserSessionProbe>({\n agentId,\n threadId,\n queryOptions,\n}: UseBrowserSessionProbeOptions<TData>): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery<BrowserSessionProbe, Error, TData>({\n queryKey: browserSessionProbeQueryKey(agentId, threadId),\n queryFn: async () => {\n if (!agentId) {\n return { hasSession: false, screencastAvailable: false };\n }\n\n try {\n return await client.getAgent(agentId).browserSession(threadId);\n } catch (error) {\n if (isNotFoundError(error)) {\n // Older server without the probe endpoint — fall back to legacy behavior.\n return LEGACY_FALLBACK;\n }\n throw error;\n }\n },\n // No polling: the probe fires once on mount, on window focus, and is\n // updated via `setQueriesData` from `tool-fallback.tsx` when a browser\n // tool call transitions. This avoids idle 5s polls and lets the probe\n // flip to `hasSession: true` the instant a tool call is seen.\n refetchOnWindowFocus: true,\n staleTime: 0,\n retry: 1,\n ...queryOptions,\n });\n}\n","/**\n * The wire-level error code the server emits on a 422 when a model is blocked\n * by the admin's builder policy. Kept as a local literal so the browser bundle\n * never imports server-only agent-builder EE code.\n */\nconst MODEL_NOT_ALLOWED_CODE = 'MODEL_NOT_ALLOWED';\n\nexport interface ModelNotAllowedDetails {\n message: string;\n attempted?: { provider?: string; modelId?: string };\n offendingLabel?: string;\n}\n\n/**\n * Detects HTTP 422 + MODEL_NOT_ALLOWED responses thrown by `MastraClientError`\n * (or any error carrying `status` + `body.error.code`). Returns the parsed\n * details when matched, or `null` otherwise.\n */\nexport function isModelNotAllowedError(err: unknown): ModelNotAllowedDetails | null {\n if (!err || typeof err !== 'object') return null;\n const candidate = err as { status?: number; body?: unknown; message?: string };\n if (candidate.status !== 422) return null;\n const body = candidate.body as { error?: { code?: unknown } } | undefined;\n const code = body?.error?.code;\n if (code !== MODEL_NOT_ALLOWED_CODE) return null;\n const errorBody = body!.error as {\n message?: string;\n attempted?: { provider?: string; modelId?: string };\n offendingLabel?: string;\n };\n return {\n message: errorBody.message || candidate.message || 'Model not allowed by admin policy',\n attempted: errorBody.attempted,\n offendingLabel: errorBody.offendingLabel,\n };\n}\n","import type {\n CreateStoredAgentParams,\n UpdateStoredAgentParams,\n ListStoredAgentsParams,\n StoredAgentResponse,\n ListStoredAgentsResponse,\n StoredAgentDependentsResponse,\n DeleteStoredAgentResponse,\n} 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';\nimport { isModelNotAllowedError } from './is-model-not-allowed';\n\nexport const useStoredAgents = <TData = ListStoredAgentsResponse>({\n queryOptions,\n ...params\n}: ListStoredAgentsParams & {\n queryOptions?: MastraQueryOptions<ListStoredAgentsResponse, TData>;\n} = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n const listParams = Object.keys(params).length > 0 ? params : undefined;\n\n return useQuery({\n queryKey: ['stored-agents', listParams],\n queryFn: () => client.listStoredAgents(listParams),\n ...queryOptions,\n });\n};\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useStoredAgent = <TData = StoredAgentResponse | null>({\n agentId,\n status,\n requestContext,\n queryOptions,\n}: {\n agentId?: string;\n status?: 'draft' | 'published';\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<StoredAgentResponse | null, TData>;\n} = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['stored-agent', agentId, status, requestContext],\n queryFn: async () => {\n if (!agentId) return null;\n try {\n return await client.getStoredAgent(agentId).details(requestContext, { status });\n } catch (error) {\n // 404 is expected for code-only agents that haven't been stored yet\n if (error && typeof error === 'object' && 'status' in error && (error as { status: number }).status === 404) {\n return null;\n }\n throw error;\n }\n },\n retry: false,\n ...queryOptions,\n });\n};\n\nexport type StoredAgent = StoredAgentResponse;\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useStoredAgentDependents = <TData = StoredAgentDependentsResponse>({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId?: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<StoredAgentDependentsResponse, TData>;\n} = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['stored-agent-dependents', agentId, requestContext],\n queryFn: () => client.getStoredAgent(agentId!).dependents(requestContext),\n retry: false,\n ...queryOptions,\n });\n};\n\nexport const useStoredAgentMutations = ({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId?: string;\n requestContext?: Record<string, any>;\n queryOptions?: {\n createStoredAgent?: MastraMutationOptions<StoredAgentResponse, CreateStoredAgentParams>;\n updateStoredAgent?: MastraMutationOptions<StoredAgentResponse, UpdateStoredAgentParams>;\n deleteStoredAgent?: MastraMutationOptions<DeleteStoredAgentResponse, void>;\n };\n} = {}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n // If the server rejects with HTTP 422 + MODEL_NOT_ALLOWED the admin policy\n // has likely changed under us — refresh the cached settings so the UI\n // re-renders against the latest server truth.\n const invalidateBuilderSettingsOnPolicyReject = (err: unknown) => {\n if (isModelNotAllowedError(err)) {\n void queryClient.invalidateQueries({ queryKey: ['builder-settings'] });\n }\n };\n\n const createMutation = useMutation({\n mutationFn: (params: CreateStoredAgentParams) => client.createStoredAgent(params),\n onSuccess: created => {\n // Prime the per-agent details cache with the response so the next page\n // (the edit page) can render the agent on first paint without a refetch.\n // The starter relies on this to immediately mount the conversation panel\n // and dispatch the user's initial message.\n queryClient.setQueryData(['stored-agent', created.id, 'draft', requestContext], created);\n queryClient.setQueryData(['stored-agent', created.id, undefined, requestContext], created);\n // Invalidate both stored-agents list and the merged agents list\n void queryClient.invalidateQueries({ queryKey: ['stored-agents'] });\n void queryClient.invalidateQueries({ queryKey: ['agents'] });\n // Invalidate the merged agent details so the freshly-created id resolves\n // instead of staying stuck on the initial `null` from the 404 lookup.\n void queryClient.invalidateQueries({ queryKey: ['agent', created.id] });\n },\n onError: invalidateBuilderSettingsOnPolicyReject,\n ...queryOptions?.createStoredAgent,\n });\n\n const updateMutation = useMutation({\n mutationFn: (params: UpdateStoredAgentParams) => {\n if (!agentId) throw new Error('agentId is required for update');\n return client.getStoredAgent(agentId).update(params, requestContext);\n },\n onSuccess: () => {\n // Invalidate lists\n void queryClient.invalidateQueries({ queryKey: ['stored-agents'] });\n void queryClient.invalidateQueries({ queryKey: ['agents'] });\n // Invalidate specific agent details\n if (agentId) {\n void queryClient.invalidateQueries({ queryKey: ['stored-agent', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n }\n },\n onError: invalidateBuilderSettingsOnPolicyReject,\n ...queryOptions?.updateStoredAgent,\n });\n\n const deleteMutation = useMutation({\n mutationFn: () => {\n if (!agentId) throw new Error('agentId is required for delete');\n return client.getStoredAgent(agentId).delete(requestContext);\n },\n onSuccess: () => {\n // Invalidate lists so the agents list page refetches without the deleted entry\n void queryClient.invalidateQueries({ queryKey: ['stored-agents'] });\n void queryClient.invalidateQueries({ queryKey: ['agents'] });\n // Drop the deleted entity from the cache so active observers don't refetch a 404\n if (agentId) {\n queryClient.removeQueries({ queryKey: ['stored-agent', agentId] });\n queryClient.removeQueries({ queryKey: ['agent', agentId] });\n }\n },\n ...queryOptions?.deleteStoredAgent,\n });\n\n return {\n createStoredAgent: createMutation,\n updateStoredAgent: updateMutation,\n deleteStoredAgent: deleteMutation,\n };\n};\n","import type { StoredAgentResponse, StoredAgentSkillConfig, UpdateStoredAgentParams } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\nimport { useStoredAgent } from './use-stored-agents';\n\n/**\n * Hook to read and mutate the skills config for a stored agent.\n *\n * The skills field is `Record<string, StoredAgentSkillConfig>` on the agent\n * snapshot. Each key is a stored skill ID and the value holds per-skill\n * overrides (description, instructions, pin, strategy).\n */\nexport function useAgentSkills({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId?: string;\n requestContext?: Record<string, any>;\n queryOptions?: {\n updateSkills?: MastraMutationOptions<StoredAgentResponse, Record<string, StoredAgentSkillConfig> | undefined>;\n };\n} = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n const { data: agent } = useStoredAgent({ agentId, status: 'draft', queryOptions: { enabled: Boolean(agentId) } });\n\n const skills = useMemo((): Record<string, StoredAgentSkillConfig> => {\n if (!agent?.skills) return {};\n // Handle conditional field: if it's an array of variants, merge values\n if (Array.isArray(agent.skills)) {\n const merged: Record<string, StoredAgentSkillConfig> = {};\n for (const variant of agent.skills) {\n Object.assign(merged, variant.value);\n }\n return merged;\n }\n return agent.skills as Record<string, StoredAgentSkillConfig>;\n }, [agent?.skills]);\n\n const updateSkills = useMutation({\n mutationFn: (newSkills: Record<string, StoredAgentSkillConfig> | undefined) => {\n if (!agentId) throw new Error('agentId is required');\n const params: UpdateStoredAgentParams = { skills: newSkills };\n return client.getStoredAgent(agentId).update(params, requestContext);\n },\n onSuccess: () => {\n if (agentId) {\n void queryClient.invalidateQueries({ queryKey: ['stored-agent', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['agent-versions', agentId] });\n }\n },\n ...queryOptions?.updateSkills,\n });\n\n return { skills, updateSkills };\n}\n","import type {\n ListAgentVersionsParams,\n CreateAgentVersionParams,\n ListAgentVersionsResponse,\n AgentVersionResponse,\n CompareVersionsResponse,\n ActivateAgentVersionResponse,\n DeleteAgentVersionResponse,\n} from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery, useMutation, useQueryClient, skipToken } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\nexport type { ListAgentVersionsParams, CreateAgentVersionParams };\n\ntype UseAgentVersionsParams<TData = ListAgentVersionsResponse> = {\n agentId?: string;\n params?: ListAgentVersionsParams;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<ListAgentVersionsResponse, TData>;\n};\n\n/**\n * Hook to list versions of a stored agent\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useAgentVersions = <TData = ListAgentVersionsResponse>({\n agentId,\n params,\n requestContext,\n queryOptions,\n}: UseAgentVersionsParams<TData>): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<ListAgentVersionsResponse, Error, TData>({\n queryKey: ['agent-versions', agentId, params, requestContext],\n queryFn: agentId ? () => client.getStoredAgent(agentId).listVersions(params, requestContext) : skipToken,\n ...queryOptions,\n });\n};\n\n/**\n * Hook to get a single version of a stored agent\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useAgentVersion = <TData = AgentVersionResponse>({\n agentId,\n versionId,\n requestContext,\n queryOptions,\n}: {\n agentId: string;\n versionId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<AgentVersionResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<AgentVersionResponse, Error, TData>({\n queryKey: ['agent-version', agentId, versionId, requestContext],\n queryFn: () => client.getStoredAgent(agentId).getVersion(versionId, requestContext),\n ...queryOptions,\n });\n};\n\n/**\n * Hook to create a new version of a stored agent\n */\nexport const useCreateAgentVersion = ({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraMutationOptions<AgentVersionResponse, CreateAgentVersionParams | undefined>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<AgentVersionResponse, Error, CreateAgentVersionParams | undefined>({\n mutationFn: (params?: CreateAgentVersionParams) =>\n client.getStoredAgent(agentId).createVersion(params, requestContext),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['agent-versions', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n },\n ...queryOptions,\n });\n};\n\n/**\n * Hook to activate a specific version of a stored agent\n */\nexport const useActivateAgentVersion = ({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraMutationOptions<ActivateAgentVersionResponse, string>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<ActivateAgentVersionResponse, Error, string>({\n mutationFn: (versionId: string) => client.getStoredAgent(agentId).activateVersion(versionId, requestContext),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['agent-versions', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n },\n ...queryOptions,\n });\n};\n\n/**\n * Hook to restore a specific version of a stored agent (creates a new version from an old one)\n */\nexport const useRestoreAgentVersion = ({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraMutationOptions<AgentVersionResponse, string>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<AgentVersionResponse, Error, string>({\n mutationFn: (versionId: string) => client.getStoredAgent(agentId).restoreVersion(versionId, requestContext),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['agent-versions', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n },\n ...queryOptions,\n });\n};\n\n/**\n * Hook to delete a specific version of a stored agent\n */\nexport const useDeleteAgentVersion = ({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraMutationOptions<DeleteAgentVersionResponse, string>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<DeleteAgentVersionResponse, Error, string>({\n mutationFn: (versionId: string) => client.getStoredAgent(agentId).deleteVersion(versionId, requestContext),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['agent-versions', agentId] });\n },\n ...queryOptions,\n });\n};\n\n/**\n * Hook to compare two versions of a stored agent\n *\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useCompareAgentVersions = <TData = CompareVersionsResponse>({\n agentId,\n fromVersionId,\n toVersionId,\n requestContext,\n queryOptions,\n}: {\n agentId: string;\n fromVersionId: string;\n toVersionId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<CompareVersionsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<CompareVersionsResponse, Error, TData>({\n queryKey: ['agent-versions-compare', agentId, fromVersionId, toVersionId, requestContext],\n queryFn: () => client.getStoredAgent(agentId).compareVersions(fromVersionId, toVersionId, requestContext),\n ...queryOptions,\n });\n};\n","import { useState, useEffect, useCallback, useRef } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\n\nfunction parseJsonString(jsonString: string): any {\n try {\n return JSON.stringify(JSON.parse(jsonString), null, 2);\n } catch {\n return jsonString;\n }\n}\n\nexport function useAgentWorkingMemory(\n agentId: string,\n threadId: string,\n resourceId: string,\n requestContext?: Record<string, any>,\n) {\n const client = useMastraClient();\n const [threadExists, setThreadExists] = useState(false);\n const [workingMemoryData, setWorkingMemoryData] = useState<string | null>(null);\n const [workingMemorySource, setWorkingMemorySource] = useState<'thread' | 'resource'>('thread');\n const [workingMemoryFormat, setWorkingMemoryFormat] = useState<'json' | 'markdown'>('markdown');\n const [isLoading, setIsLoading] = useState(true);\n const [isUpdating, setIsUpdating] = useState(false);\n const latestRequest = useRef(0);\n\n const refetch = useCallback(async () => {\n const requestId = ++latestRequest.current;\n setIsLoading(true);\n try {\n if (!agentId || !threadId) {\n setWorkingMemoryData(null);\n setIsLoading(false);\n return;\n }\n const res = await client.getWorkingMemory({ agentId, threadId, resourceId, requestContext });\n if (requestId !== latestRequest.current) return;\n const { workingMemory, source, workingMemoryTemplate, threadExists } = res as {\n workingMemory: string | null;\n source: 'thread' | 'resource';\n workingMemoryTemplate: { content: string; format: 'json' | 'markdown' };\n threadExists: boolean;\n };\n setThreadExists(threadExists);\n setWorkingMemoryData(workingMemory);\n setWorkingMemorySource(source);\n setWorkingMemoryFormat(workingMemoryTemplate?.format || 'markdown');\n if (workingMemoryTemplate?.format === 'json') {\n let dataToSet = '';\n if (workingMemory) {\n dataToSet = parseJsonString(workingMemory);\n } else if (workingMemoryTemplate?.content) {\n dataToSet = parseJsonString(workingMemoryTemplate.content);\n } else {\n dataToSet = '';\n }\n setWorkingMemoryData(dataToSet);\n } else {\n setWorkingMemoryData(workingMemory || workingMemoryTemplate?.content || '');\n }\n } catch (error) {\n if (requestId !== latestRequest.current) return;\n setWorkingMemoryData(null);\n console.error('Error fetching working memory', error);\n } finally {\n if (requestId === latestRequest.current) setIsLoading(false);\n }\n }, [agentId, threadId, resourceId, client, requestContext]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n const updateWorkingMemory = async (newMemory: string) => {\n setIsUpdating(true);\n try {\n if (workingMemoryFormat === 'json') {\n try {\n JSON.parse(newMemory);\n } catch {\n throw new Error('Invalid JSON working memory');\n }\n }\n await client.updateWorkingMemory({ agentId, threadId, workingMemory: newMemory, resourceId, requestContext });\n void refetch();\n } catch (error) {\n console.error('Error updating working memory', error);\n throw error;\n } finally {\n setIsUpdating(false);\n }\n };\n\n return {\n threadExists,\n workingMemoryData,\n workingMemorySource,\n workingMemoryFormat,\n isLoading,\n isUpdating,\n refetch,\n updateWorkingMemory,\n };\n}\n","import type { StoredAgentResponse, StoredWorkspaceRef, UpdateStoredAgentParams } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\nimport { useStoredAgent } from './use-stored-agents';\n\n/**\n * Hook to read and mutate the workspace reference for a stored agent.\n *\n * The workspace ref is part of the agent snapshot config and can be:\n * - `{ type: 'id', workspaceId }` — references a stored workspace by ID\n * - `{ type: 'inline', config }` — inline workspace config\n * - `undefined` — no workspace assigned\n */\nexport function useAgentWorkspace({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId?: string;\n requestContext?: Record<string, any>;\n queryOptions?: {\n updateWorkspace?: MastraMutationOptions<StoredAgentResponse, StoredWorkspaceRef | undefined>;\n };\n} = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n const { data: agent } = useStoredAgent({ agentId, status: 'draft', queryOptions: { enabled: Boolean(agentId) } });\n\n const workspace = useMemo((): StoredWorkspaceRef | undefined => {\n if (!agent?.workspace) return undefined;\n // Handle conditional field: if it's an array of variants, take the first value\n if (Array.isArray(agent.workspace)) {\n return agent.workspace[0]?.value as StoredWorkspaceRef | undefined;\n }\n return agent.workspace as StoredWorkspaceRef;\n }, [agent?.workspace]);\n\n const updateWorkspace = useMutation({\n mutationFn: (ref: StoredWorkspaceRef | undefined) => {\n if (!agentId) throw new Error('agentId is required');\n const params: UpdateStoredAgentParams = { workspace: ref };\n return client.getStoredAgent(agentId).update(params, requestContext);\n },\n onSuccess: () => {\n if (agentId) {\n void queryClient.invalidateQueries({ queryKey: ['stored-agent', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['agent-versions', agentId] });\n }\n },\n ...queryOptions?.updateWorkspace,\n });\n\n return { workspace, updateWorkspace };\n}\n","import type { GetAgentResponse } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useAgent = <TData = GetAgentResponse | null>({\n agentId,\n requestContext,\n queryOptions,\n}: {\n agentId?: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<GetAgentResponse | null, TData>;\n} = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['agent', agentId, requestContext],\n queryFn: () => (agentId ? client.getAgent(agentId).details(requestContext) : null),\n retry: false,\n ...queryOptions,\n });\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\ntype AgentsModelProvidersResponse = Awaited<ReturnType<MastraClient['listAgentsModelProviders']>>;\n\nexport const useAgentsModelProviders = <TData = AgentsModelProvidersResponse>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<AgentsModelProvidersResponse, TData> } = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['agents-model-providers'],\n queryFn: () => client.listAgentsModelProviders(),\n retry: false,\n ...queryOptions,\n });\n};\n","import type {\n MastraClient,\n ReorderModelListParams,\n UpdateModelInModelListParams,\n UpdateModelParams,\n} from '@mastra/client-js';\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\nimport type { UseMutationResult, UseQueryResult } from '@tanstack/react-query';\n\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\ntype Agent = ReturnType<MastraClient['getAgent']>;\ntype ListAgentsResponse = Awaited<ReturnType<MastraClient['listAgents']>>;\nexport type ModelUpdateResponse = Awaited<ReturnType<Agent['updateModel']>>;\n\nexport const useAgents = <TData = ListAgentsResponse>({\n requestContext,\n queryOptions,\n}: {\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<ListAgentsResponse, TData>;\n} = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['agents', requestContext],\n queryFn: () => client.listAgents(requestContext),\n ...queryOptions,\n });\n};\n\nexport const useUpdateAgentModel = ({\n agentId,\n queryOptions,\n}: {\n agentId: string;\n queryOptions?: MastraMutationOptions<ModelUpdateResponse, UpdateModelParams>;\n}): UseMutationResult<ModelUpdateResponse, Error, UpdateModelParams> => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: async (payload: UpdateModelParams) => client.getAgent(agentId).updateModel(payload),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n },\n onError: err => {\n console.error('Error updating model', err);\n },\n ...queryOptions,\n });\n};\n\nexport const useReorderModelList = ({\n agentId,\n queryOptions,\n}: {\n agentId: string;\n queryOptions?: MastraMutationOptions<ModelUpdateResponse, ReorderModelListParams>;\n}): UseMutationResult<ModelUpdateResponse, Error, ReorderModelListParams> => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: async (payload: ReorderModelListParams) => client.getAgent(agentId).reorderModelList(payload),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n },\n onError: err => {\n console.error('Error reordering model list', err);\n },\n ...queryOptions,\n });\n};\n\nexport const useUpdateModelInModelList = ({\n agentId,\n queryOptions,\n}: {\n agentId: string;\n queryOptions?: MastraMutationOptions<ModelUpdateResponse, UpdateModelInModelListParams>;\n}): UseMutationResult<ModelUpdateResponse, Error, UpdateModelInModelListParams> => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: async (payload: UpdateModelInModelListParams) =>\n client.getAgent(agentId).updateModelInModelList(payload),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n },\n onError: err => {\n console.error('Error updating model in model list', err);\n },\n ...queryOptions,\n });\n};\n\nexport const useResetAgentModel = ({\n agentId,\n queryOptions,\n}: {\n agentId: string;\n queryOptions?: MastraMutationOptions<ModelUpdateResponse, void>;\n}): UseMutationResult<ModelUpdateResponse, Error, void> => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: async () => client.getAgent(agentId).resetModel(),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['agent', agentId] });\n },\n onError: err => {\n console.error('Error resetting model', err);\n },\n ...queryOptions,\n });\n};\n","import { useMutation } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\ninterface CloseBrowserParams {\n agentId: string;\n threadId?: string;\n}\n\n/**\n * Mutation hook for closing an agent's browser session.\n */\nexport function useCloseBrowser({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<{ success: boolean }, CloseBrowserParams> } = {}) {\n const client = useMastraClient();\n\n return useMutation<{ success: boolean }, Error, CloseBrowserParams>({\n mutationFn: ({ agentId, threadId }) => client.getAgent(agentId).closeBrowser(threadId),\n onError: err => {\n console.error('[useCloseBrowser] Error closing browser:', err);\n },\n ...queryOptions,\n });\n}\n","import type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\ninterface ApiInstructionBlock {\n type: string;\n content?: string;\n id?: string;\n /** Form-format ref blocks use `promptBlockId` instead of `id` */\n promptBlockId?: string;\n rules?: unknown;\n}\n\n/**\n * Normalize blocks to API format.\n * Form-format ref blocks have `{ type: 'prompt_block_ref', promptBlockId }`,\n * while API-format blocks have `{ type: 'prompt_block_ref', id }`.\n */\nfunction toApiBlocks(blocks: ApiInstructionBlock[]) {\n return blocks.map(block => {\n if (block.type === 'prompt_block_ref') {\n // Form-format blocks have `promptBlockId` (the storage ID) and `id` (form-internal UUID).\n // API-format blocks have `id` (the storage ID). Prefer promptBlockId when present.\n return { type: 'prompt_block_ref' as const, id: block.promptBlockId ?? block.id, rules: block.rules };\n }\n return { type: block.type, content: block.content, rules: block.rules };\n });\n}\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport function usePreviewInstructions<TData = string>({\n blocks,\n requestContext,\n queryOptions,\n}: {\n blocks: ApiInstructionBlock[] | undefined;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<string, TData>;\n}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['preview-instructions', blocks, requestContext],\n queryFn: async () => {\n if (!blocks || blocks.length === 0) return '';\n\n const response = await client.request<{ result: string }>('/stored/agents/preview-instructions', {\n method: 'POST',\n body: { blocks: toApiBlocks(blocks), context: requestContext },\n });\n\n return response.result;\n },\n ...queryOptions,\n });\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\n\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nexport type ListStoredSkillsResponse = Awaited<ReturnType<MastraClient['listStoredSkills']>>;\n\nexport function useStoredSkills<TData = ListStoredSkillsResponse>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<ListStoredSkillsResponse, TData> } = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['stored-skills'],\n queryFn: () => client.listStoredSkills(),\n ...queryOptions,\n });\n}\n","import type { ChannelPlatformInfo, ChannelInstallationInfo, ChannelConnectResult } from '@mastra/client-js';\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\nimport type { UseMutationResult, UseQueryResult } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\nexport type { ChannelPlatformInfo, ChannelInstallationInfo, ChannelConnectResult };\n\nexport const useChannelPlatforms = <TData = ChannelPlatformInfo[]>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<ChannelPlatformInfo[], TData> } = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<ChannelPlatformInfo[], Error, TData>({\n queryKey: ['channels', 'platforms'],\n queryFn: () => client.channels.listPlatforms(),\n staleTime: 60 * 1000,\n retry: false,\n ...queryOptions,\n });\n};\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useChannelInstallations = <TData = ChannelInstallationInfo[]>({\n platform,\n agentId,\n queryOptions,\n}: {\n platform: string;\n agentId: string;\n queryOptions?: MastraQueryOptions<ChannelInstallationInfo[], TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery<ChannelInstallationInfo[], Error, TData>({\n queryKey: ['channels', 'installations', platform, agentId],\n queryFn: () => client.channels.listInstallations(platform, agentId),\n staleTime: 10 * 1000,\n retry: false,\n ...queryOptions,\n });\n};\n\n/**\n * Reconcile an agent's installation with platform state — activates a pending\n * installation whose connect flow completed out-of-band (e.g. a Discord bot\n * invite finished in another tab). Resolves null on platforms without\n * reconciliation. Call it deliberately (e.g. on window focus while a connect\n * is in flight) — it is a write, not a read.\n */\nexport const useReconcileChannelInstallation = ({\n platform,\n queryOptions,\n}: {\n platform: string;\n queryOptions?: MastraMutationOptions<ChannelInstallationInfo | null, string>;\n}): UseMutationResult<ChannelInstallationInfo | null, Error, string> => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<ChannelInstallationInfo | null, Error, string>({\n mutationFn: agentId => client.channels.reconcileInstallation(platform, agentId),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['channels', 'installations', platform] });\n },\n ...queryOptions,\n });\n};\n\nexport const useConnectChannel = ({\n platform,\n queryOptions,\n}: {\n platform: string;\n queryOptions?: MastraMutationOptions<ChannelConnectResult, { agentId: string; options?: Record<string, unknown> }>;\n}): UseMutationResult<ChannelConnectResult, Error, { agentId: string; options?: Record<string, unknown> }> => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<ChannelConnectResult, Error, { agentId: string; options?: Record<string, unknown> }>({\n mutationFn: ({ agentId, options }) =>\n client.channels.connect(platform, agentId, {\n ...options,\n // Tell the server to redirect back here after OAuth\n redirectUrl: window.location.href,\n }),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['channels', 'installations', platform] });\n },\n ...queryOptions,\n });\n};\n\nexport const useDisconnectChannel = ({\n platform,\n queryOptions,\n}: {\n platform: string;\n queryOptions?: MastraMutationOptions<{ success: boolean }, string>;\n}) => {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<{ success: boolean }, Error, string>({\n mutationFn: agentId => client.channels.disconnect(platform, agentId),\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: ['channels', 'installations', platform] });\n },\n ...queryOptions,\n });\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { RequestContext } from '@mastra/core/di';\nimport { useMutation } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\ntype ExecuteAgentToolResponse = Awaited<ReturnType<ReturnType<MastraClient['getAgent']>['executeTool']>>;\n\nexport interface ExecuteToolInput {\n agentId: string;\n toolId: string;\n input: any;\n playgroundRequestContext?: Record<string, any>;\n}\n\nexport const useExecuteAgentTool = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<ExecuteAgentToolResponse, ExecuteToolInput> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ agentId, toolId, input, playgroundRequestContext }: ExecuteToolInput) => {\n const requestContext = new RequestContext();\n Object.entries(playgroundRequestContext ?? {}).forEach(([key, value]) => {\n requestContext.set(key, value);\n });\n return client.getAgent(agentId).executeTool(toolId, { data: input, requestContext });\n },\n ...queryOptions,\n });\n};\n"],"mappings":";;;;;AAmBA,MAAM,WAAW;AAEjB,MAAM,cAAc;AAEpB,MAAM,eAAe,YAA6B,IAAI,KAAK,QAAQ,SAAS,CAAC,CAAC,QAAQ;AAEtF,MAAM,eAAe,GAAoB,MAAuB,YAAY,CAAC,IAAI,YAAY,CAAC;AAE9F,MAAa,oBAA+C,EAC1D,UACA,SACA,QACA,gBACA,mBACkC;CAClC,MAAM,SAAS,gBAAgB;CAE/B,OAAO,iBAAiB;EACtB,UAAU;GAAC;GAAU;GAAY;GAAU;GAAS;EAAc;EAClE,kBAAkB;EAClB,SACE,UAAU,YACL,EAAE,WAAW,gBACZ,OAAO,mBAAmB,UAAU;GAClC;GACA;GACA,wBAAwB;GACxB,SAAS;GACT,SAAS;IAAE,OAAO;IAAa,WAAW;GAAO;GAGjD,QAAQ,YAAY,EAAE,WAAW,EAAE,KAAK,IAAI,KAAK,SAAS,EAAE,EAAE,IAAI,KAAA;EACpE,CAAC,IACH;EACN,mBAAmB,UAAU,WAAW,kBAAkB;GACxD,IAAI,CAAC,SAAS,WAAW,SAAS,SAAS,WAAW,GAAG,OAAO,KAAA;GAChE,MAAM,OAAO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A,MAAa,qBAAqB,EAChC,UACA,mBAI4G;CAC5G,MAAM,SAAS,gBAAgB;CAC/B,MAAM,cAAc,eAAe;CAEnC,OAAO,YAAiG;EACtG,aAAa,EAAE,SAAS,cACtB,OAAO,SAAS,QAAQ,UAAU,SAAS;GACzC,GAAG;GAEH,aAAa,OAAO,SAAS;EAC/B,CAAC;EACH,iBAAiB;GACf,YAAiB,kBAAkB,EAAE,UAAU;IAAC;IAAY;IAAiB;GAAQ,EAAE,CAAC;EAC1F;EACA,GAAG;CACL,CAAC;AACH;AAEA,MAAa,wBAAwB,EACnC,UACA,mBAII;CACJ,MAAM,SAAS,gBAAgB;CAC/B,MAAM,cAAc,eAAe;CAEnC,OAAO,YAAiD;EACtD,aAAY,YAAW,OAAO,SAAS,WAAW,UAAU,OAAO;EACnE,iBAAiB;GACf,YAAiB,kBAAkB,EAAE,UAAU;IAAC;IAAY;IAAiB;GAAQ,EAAE,CAAC;EAC1F;EACA,GAAG;CACL,CAAC;AACH;;;ACjGA,MAAa,uBAAuB,EAClC,iBACwF,CAAC,MAAM;CAC/F,MAAM,SAAS,gBAAgB;CAC/B,OAAO,YAAY;EACjB,YAAY,OAAO,EAAE,SAAS,QAAQ,OAAO,+BAAiD;GAC5F,MAAM,iBAAiB,IAAI,eAAe;GAC1C,OAAO,QAAQ,4BAA4B,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;IACvE,eAAe,IAAI,KAAK,KAAK;GAC/B,CAAC;GACD,OAAO,OAAO,SAAS,OAAO,CAAC,CAAC,YAAY,QAAQ;IAAE,MAAM;IAAO;GAAe,CAAC;EACrF;EACA,GAAG;CACL,CAAC;AACH"}
|
|
@@ -135,7 +135,7 @@ function useAuthCapabilities({ queryOptions } = {}) {
|
|
|
135
135
|
getClientQueryKey(client)
|
|
136
136
|
],
|
|
137
137
|
queryFn: () => makeAuthCapabilitiesRequest(client),
|
|
138
|
-
staleTime:
|
|
138
|
+
staleTime: 6e4,
|
|
139
139
|
retry: false,
|
|
140
140
|
...queryOptions
|
|
141
141
|
});
|
|
@@ -195,7 +195,7 @@ function useCurrentUser({ queryOptions } = {}) {
|
|
|
195
195
|
if (!response.ok) throw new CurrentUserError(response.status);
|
|
196
196
|
return response.json();
|
|
197
197
|
},
|
|
198
|
-
staleTime:
|
|
198
|
+
staleTime: 6e4,
|
|
199
199
|
retry: (failureCount, error) => {
|
|
200
200
|
if (!(error instanceof CurrentUserError)) return false;
|
|
201
201
|
if (error.status !== 503) return false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["useMastraClient","useMastraClient","useMastraClient","useMastraClient","useMastraClient","useMastraClient"],"sources":["../../../src/hooks/auth/types.ts","../../../src/hooks/auth/fetch-with-refresh.ts","../../../src/hooks/auth/get-client-query-key.ts","../../../src/hooks/auth/sso-login.ts","../../../src/hooks/auth/use-auth-capabilities.ts","../../../src/hooks/auth/use-current-user.ts","../../../src/hooks/auth/use-permission-patterns.ts","../../../src/hooks/auth/use-credentials-login.ts","../../../src/hooks/auth/use-credentials-signup.ts","../../../src/hooks/auth/use-auth-actions.ts"],"sourcesContent":["/**\n * Auth types for EE authentication in playground-ui.\n *\n * These types mirror the server schemas from @mastra/server.\n */\n\n/**\n * SSO configuration for login\n */\nexport type SSOConfig = {\n provider: string;\n text: string;\n icon?: string;\n description?: string;\n url: string;\n};\n\n/**\n * Login configuration\n */\nexport type LoginConfig = {\n type: 'sso' | 'credentials' | 'both';\n /** Whether sign-up is enabled (defaults to true) */\n signUpEnabled?: boolean;\n /** Optional description explaining the auth requirement and what credentials to use */\n description?: string;\n sso?: SSOConfig;\n} | null;\n\n/**\n * Public capabilities (unauthenticated)\n */\nexport type PublicAuthCapabilities = {\n enabled: boolean;\n login: LoginConfig;\n};\n\n/**\n * Authenticated user information\n */\nexport type AuthenticatedUser = {\n id: string;\n email?: string;\n name?: string;\n avatarUrl?: string;\n};\n\n/**\n * Capability flags\n */\nexport type CapabilityFlags = {\n user: boolean;\n session: boolean;\n sso: boolean;\n rbac: boolean;\n acl: boolean;\n};\n\n/**\n * User access information\n */\nexport type UserAccess = {\n roles: string[];\n permissions: string[];\n} | null;\n\n/**\n * Authenticated capabilities (extends public)\n */\nexport type AuthenticatedCapabilities = PublicAuthCapabilities & {\n user: AuthenticatedUser;\n capabilities: CapabilityFlags;\n access: UserAccess;\n /** Available roles in the system (only present for admin users) */\n availableRoles?: { id: string; name: string }[];\n};\n\n/**\n * Auth capabilities response (union of public and authenticated)\n */\nexport type AuthCapabilities = PublicAuthCapabilities | AuthenticatedCapabilities;\n\n/**\n * Current user response (may be null if not authenticated)\n */\nexport type CurrentUser = {\n id: string;\n email?: string;\n name?: string;\n avatarUrl?: string;\n roles?: string[];\n permissions?: string[];\n} | null;\n\n/**\n * SSO callback response\n */\nexport type SSOCallbackResponse = {\n success: boolean;\n user?: AuthenticatedUser;\n redirectTo?: string;\n};\n\n/**\n * Logout response\n */\nexport type LogoutResponse = {\n success: boolean;\n redirectTo?: string;\n};\n\n/**\n * Type guard to check if capabilities include authenticated user\n */\nexport function isAuthenticated(capabilities: AuthCapabilities): capabilities is AuthenticatedCapabilities {\n return 'user' in capabilities && capabilities.user !== undefined;\n}\n","/**\n * Fetch wrapper for the Mastra server API.\n *\n * ⚠️ MIRRORS: `platform/frontend/src/shared/lib/fetch-with-refresh.ts`\n *\n * Both files must stay behaviourally in lockstep — the platform dashboard and\n * the embedded playground both talk to WorkOS-backed auth and both would be\n * vulnerable to the same 429 lockout loop if either regressed. If you change\n * one, change the other in the same PR (or extract to a shared package —\n * currently blocked by the platform/mastra-ai monorepo boundary).\n *\n * ---\n *\n * The server middleware already refreshes the WorkOS session transparently\n * on every protected request. There is no scenario where the client can\n * succeed by calling /auth/refresh after a 401 — that endpoint hits the\n * same broken WorkOS with the same session and would only amplify transient\n * failures into forced logout (PLTFRM-1270).\n *\n * These are pass-throughs today. The names and signatures are preserved for\n * compatibility with existing call sites (`App.tsx`, `use-current-user.ts`).\n * Transient-failure retry belongs one level up — in React Query's `retry`\n * config on individual queries — not in a fetch wrapper that would compound\n * with the query-level retry.\n */\n\nexport async function fetchWithRefresh(\n _baseUrl: string,\n input: RequestInfo | URL,\n init?: RequestInit,\n): Promise<Response> {\n return fetch(input, init);\n}\n\nexport function createFetchWithRefresh(_baseUrl?: string, _apiPrefix?: string): typeof fetch {\n return (input, init) => fetch(input, init);\n}\n","import type { MastraClient } from '@mastra/client-js';\n\nconst clientQueryKeys = new WeakMap<MastraClient, number>();\nlet nextClientQueryKey = 0;\n\n/**\n * Returns a stable, non-sensitive query key for a Mastra client instance.\n * A new client is created whenever its connection options change.\n */\nexport function getClientQueryKey(client: MastraClient) {\n const existingKey = clientQueryKeys.get(client);\n if (existingKey !== undefined) return existingKey;\n\n const queryKey = nextClientQueryKey++;\n clientQueryKeys.set(client, queryKey);\n return queryKey;\n}\n","import type { MastraClient } from '@mastra/client-js';\n\nexport type SSOLoginResponse = {\n url: string;\n};\n\nexport async function makeSSOLoginRequest(\n client: Pick<MastraClient, 'options'>,\n { redirectUri }: { redirectUri?: string },\n): Promise<SSOLoginResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const params = new URLSearchParams();\n if (redirectUri) {\n params.set('redirect_uri', redirectUri);\n }\n\n const url = `${baseUrl}${prefix}/auth/sso/login${params.toString() ? `?${params}` : ''}`;\n\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to initiate SSO login: ${response.status}`);\n }\n\n return response.json();\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { getClientQueryKey } from './get-client-query-key';\nimport type { AuthCapabilities } from './types';\n\n/**\n * Makes a request to the auth capabilities endpoint.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeAuthCapabilitiesRequest(client: MastraClient): Promise<AuthCapabilities> {\n const { baseUrl = '', headers: clientHeaders = {}, apiPrefix } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const response = await fetch(`${baseUrl}${prefix}/auth/capabilities`, {\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch auth capabilities: ${response.status}`);\n }\n\n return response.json();\n}\n\n/**\n * Hook to fetch authentication capabilities.\n *\n * Returns server-authoritative capability detection including:\n * - Whether auth is enabled\n * - Login configuration (SSO, credentials, or both)\n * - Current user (if authenticated)\n * - Available capabilities (user awareness, session, SSO, RBAC, ACL, audit)\n * - User access (roles and permissions)\n *\n * @example\n * ```tsx\n * import { useAuthCapabilities } from '@mastra/react/hooks/auth';\n *\n * function AuthStatus() {\n * const { data: capabilities, isLoading } = useAuthCapabilities();\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (!capabilities?.enabled) return <div>Auth not enabled</div>;\n *\n * if (isAuthenticated(capabilities)) {\n * return <div>Welcome, {capabilities.user.name}</div>;\n * }\n *\n * return <LoginButton config={capabilities.login} />;\n * }\n * ```\n */\nexport function useAuthCapabilities<TData = AuthCapabilities>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<AuthCapabilities, TData> } = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery<AuthCapabilities, Error, TData>({\n queryKey: ['auth', 'capabilities', getClientQueryKey(client)],\n queryFn: () => makeAuthCapabilitiesRequest(client),\n staleTime: 60 * 1000, // Cache for 1 minute\n retry: false, // Don't retry auth requests\n ...queryOptions,\n });\n}\n","import type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { fetchWithRefresh } from './fetch-with-refresh';\nimport type { CurrentUser } from './types';\n\nconst AUTH_TRANSIENT_MAX_RETRIES = 3;\nconst AUTH_TRANSIENT_MAX_BACKOFF_MS = 8_000;\n\nexport class CurrentUserError extends Error {\n constructor(public readonly status: number) {\n super(`Failed to fetch current user: ${status}`);\n this.name = 'CurrentUserError';\n }\n}\n\nexport function isUnauthenticatedError(error: unknown): boolean {\n return error instanceof CurrentUserError && error.status === 401;\n}\n\n/**\n * Hook to fetch the current authenticated user.\n *\n * Returns the current user if authenticated, null otherwise.\n * Includes roles and permissions if RBAC is available.\n *\n * Uses fetchWithRefresh to automatically refresh the session on 401 errors,\n * preventing users from being logged out when the access token expires.\n *\n * @example\n * ```tsx\n * import { useCurrentUser } from '@mastra/react/hooks/auth';\n *\n * function UserMenu() {\n * const { data: user, isLoading } = useCurrentUser();\n *\n * if (isLoading) return <Skeleton />;\n * if (!user) return <LoginButton />;\n *\n * return (\n * <Menu>\n * <Avatar src={user.avatarUrl} />\n * <span>{user.name || user.email}</span>\n * </Menu>\n * );\n * }\n * ```\n */\nexport function useCurrentUser<TData = CurrentUser>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<CurrentUser, TData> } = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n const baseUrl = client.options?.baseUrl || '';\n\n return useQuery<CurrentUser, Error, TData>({\n queryKey: ['auth', 'me'],\n queryFn: async () => {\n const response = await fetchWithRefresh(baseUrl, `${baseUrl}/api/auth/me`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new CurrentUserError(response.status);\n }\n\n return response.json();\n },\n staleTime: 60 * 1000, // Cache for 1 minute\n // Retry the /api/auth/me query on transient auth-provider failures (HTTP 503)\n // so the UI stays in `isLoading` instead of flipping to `isError` and\n // triggering login — that redirect is what fed the WorkOS 429 lockout loop\n // (PLTFRM-1270). 401 (terminal) still fails fast.\n retry: (failureCount, error) => {\n if (!(error instanceof CurrentUserError)) return false;\n if (error.status !== 503) return false;\n return failureCount < AUTH_TRANSIENT_MAX_RETRIES;\n },\n retryDelay: attemptIndex => Math.min(AUTH_TRANSIENT_MAX_BACKOFF_MS, 500 * 2 ** attemptIndex),\n ...queryOptions,\n });\n}\n","import type { MastraClient, PermissionPattern } from '@mastra/client-js';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { getClientQueryKey } from './get-client-query-key';\nimport { isAuthenticated } from './types';\nimport { useAuthCapabilities } from './use-auth-capabilities';\n\n/**\n * Fetches the authoritative set of permission patterns from the server\n * (`GET /auth/permission-patterns`).\n *\n * The server owns the permission source of truth (generated from the route\n * registry), so the browser never imports the server-only `@mastra/core/auth/ee`\n * code just to validate hardcoded route-permission literals.\n *\n * The request only fires when RBAC is actually enabled — when auth is off or\n * RBAC isn't configured, route gating is a no-op so the pattern vocabulary is\n * not needed, and we avoid an unnecessary (and potentially 403/401) call.\n */\ntype PermissionPatternsResponse = Awaited<ReturnType<MastraClient['getPermissionPatterns']>>;\n\nexport const usePermissionPatterns = ({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<PermissionPatternsResponse> } = {}) => {\n const client = useMastraClient();\n const { data: capabilities, isLoading: capabilitiesLoading, error: capabilitiesError } = useAuthCapabilities();\n\n const rbacEnabled = !!(capabilities && isAuthenticated(capabilities) && capabilities.capabilities.rbac);\n\n const { data, isLoading, error } = useQuery({\n queryKey: ['permission-patterns', getClientQueryKey(client)],\n queryFn: () => client.getPermissionPatterns(),\n // Only fetch the pattern vocabulary when RBAC gating is in effect.\n enabled: rbacEnabled,\n // The endpoint requires auth; on 403/401 we don't want React Query to\n // thrash with retries (which toggles isLoading and re-triggers redirect\n // guards). One attempt is enough — gating falls back to the user's\n // permissions if the pattern set is empty.\n retry: false,\n staleTime: Infinity,\n ...queryOptions,\n });\n\n const patterns = useMemo(() => new Set<PermissionPattern>(data?.patterns ?? []), [data]);\n\n // While capabilities are resolving we don't yet know whether RBAC applies, so\n // report loading. Once RBAC is ruled out, this hook is never \"loading\".\n return { patterns, isLoading: capabilitiesLoading || (rbacEnabled && isLoading), error: capabilitiesError || error };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nexport type CredentialsLoginRequest = {\n email: string;\n password: string;\n};\n\nexport type CredentialsLoginResponse = {\n user?: {\n id: string;\n email: string;\n name?: string;\n };\n error?: string;\n};\n\n/**\n * Hook to login with email/password credentials.\n *\n * Uses Better Auth's email sign-in endpoint.\n *\n * @example\n * ```tsx\n * import { useCredentialsLogin } from '@mastra/react/hooks/auth';\n *\n * function LoginForm() {\n * const { mutate: login, isPending, error } = useCredentialsLogin();\n *\n * const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n * e.preventDefault();\n * const formData = new FormData(e.currentTarget);\n * login({\n * email: formData.get('email') as string,\n * password: formData.get('password') as string,\n * }, {\n * onSuccess: () => {\n * window.location.href = '/';\n * },\n * });\n * };\n *\n * return (\n * <form onSubmit={handleSubmit}>\n * <input name=\"email\" type=\"email\" required />\n * <input name=\"password\" type=\"password\" required />\n * <button type=\"submit\" disabled={isPending}>\n * Sign in\n * </button>\n * {error && <p>{error.message}</p>}\n * </form>\n * );\n * }\n * ```\n */\n/**\n * Makes a credentials sign-in request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeCredentialsLoginRequest(\n client: MastraClient,\n { email, password }: CredentialsLoginRequest,\n): Promise<CredentialsLoginResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options || {};\n const raw = (apiPrefix ?? '/api').trim();\n const normalized = raw === '' ? '' : raw.startsWith('/') ? raw : `/${raw}`;\n const prefix = normalized.replace(/\\/+$/, '');\n\n // Generic Mastra auth endpoint - works with any credentials provider\n const response = await fetch(`${baseUrl}${prefix}/auth/credentials/sign-in`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ email, password }),\n });\n\n const data = await response.json();\n\n if (!response.ok) {\n throw new Error(data.message || data.error || 'Invalid email or password');\n }\n\n return data;\n}\n\nexport function useCredentialsLogin({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<CredentialsLoginResponse, CredentialsLoginRequest> } = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<CredentialsLoginResponse, Error, CredentialsLoginRequest>({\n mutationFn: ({ email, password }) => makeCredentialsLoginRequest(client, { email, password }),\n onSuccess: () => {\n // Invalidate auth queries to refetch user state\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nexport type CredentialsSignUpRequest = {\n email: string;\n password: string;\n name?: string;\n};\n\nexport type CredentialsSignUpResponse = {\n user?: {\n id: string;\n email: string;\n name?: string;\n };\n error?: string;\n};\n\n/**\n * Hook to sign up with email/password credentials.\n *\n * Uses Better Auth's email sign-up endpoint.\n *\n * @example\n * ```tsx\n * import { useCredentialsSignUp } from '@mastra/react/hooks/auth';\n *\n * function SignUpForm() {\n * const { mutate: signUp, isPending, error } = useCredentialsSignUp();\n *\n * const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n * e.preventDefault();\n * const formData = new FormData(e.currentTarget);\n * signUp({\n * email: formData.get('email') as string,\n * password: formData.get('password') as string,\n * name: formData.get('name') as string,\n * }, {\n * onSuccess: () => {\n * window.location.href = '/';\n * },\n * });\n * };\n *\n * return (\n * <form onSubmit={handleSubmit}>\n * <input name=\"name\" type=\"text\" />\n * <input name=\"email\" type=\"email\" required />\n * <input name=\"password\" type=\"password\" required />\n * <button type=\"submit\" disabled={isPending}>\n * Sign up\n * </button>\n * {error && <p>{error.message}</p>}\n * </form>\n * );\n * }\n * ```\n */\n/**\n * Makes a credentials sign-up request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeCredentialsSignUpRequest(\n client: MastraClient,\n { email, password, name }: CredentialsSignUpRequest,\n): Promise<CredentialsSignUpResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options || {};\n const raw = (apiPrefix ?? '/api').trim();\n const normalized = raw === '' ? '' : raw.startsWith('/') ? raw : `/${raw}`;\n const prefix = normalized.replace(/\\/+$/, '');\n\n // Generic Mastra auth endpoint - works with any credentials provider\n const response = await fetch(`${baseUrl}${prefix}/auth/credentials/sign-up`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ email, password, name }),\n });\n\n const data = await response.json();\n\n if (!response.ok) {\n throw new Error(data.message || data.error || 'Failed to create account');\n }\n\n return data;\n}\n\nexport function useCredentialsSignUp({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<CredentialsSignUpResponse, CredentialsSignUpRequest> } = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<CredentialsSignUpResponse, Error, CredentialsSignUpRequest>({\n mutationFn: ({ email, password, name }) => makeCredentialsSignUpRequest(client, { email, password, name }),\n onSuccess: () => {\n // Invalidate auth queries to refetch user state\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nimport { makeSSOLoginRequest } from './sso-login';\nimport type { LogoutResponse } from './types';\n\n/**\n * Hook to initiate SSO login.\n *\n * Returns mutation to get the SSO login URL and redirect.\n *\n * @example\n * ```tsx\n * import { useSSOLogin } from '@mastra/react/hooks/auth';\n *\n * function SSOLoginButton() {\n * const { mutate: login, isPending } = useSSOLogin();\n *\n * const handleClick = () => {\n * login({ redirectUri: window.location.href }, {\n * onSuccess: (data) => {\n * window.location.href = data.url;\n * },\n * });\n * };\n *\n * return (\n * <button onClick={handleClick} disabled={isPending}>\n * Sign in with SSO\n * </button>\n * );\n * }\n * ```\n */\ntype SSOLoginResponse = Awaited<ReturnType<typeof makeSSOLoginRequest>>;\n\nexport function useSSOLogin({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<SSOLoginResponse, { redirectUri?: string }> } = {}) {\n const client = useMastraClient();\n\n return useMutation({\n mutationFn: ({ redirectUri }: { redirectUri?: string }) => makeSSOLoginRequest(client, { redirectUri }),\n ...queryOptions,\n });\n}\n\n/**\n * Hook to logout the current user.\n *\n * Destroys the current session and optionally redirects to\n * the SSO logout URL if available.\n *\n * @example\n * ```tsx\n * import { useLogout } from '@mastra/react/hooks/auth';\n *\n * function LogoutButton({ userId }: { userId: string }) {\n * const { mutate: logout, isPending } = useLogout();\n * const queryClient = useQueryClient();\n *\n * const handleLogout = () => {\n * logout({ userId }, {\n * onSuccess: (data) => {\n * queryClient.invalidateQueries({ queryKey: ['auth'] });\n * if (data.redirectTo) {\n * window.location.href = data.redirectTo;\n * } else {\n * window.location.reload();\n * }\n * },\n * });\n * };\n *\n * return (\n * <button onClick={handleLogout} disabled={isPending}>\n * Sign out\n * </button>\n * );\n * }\n * ```\n */\n/**\n * Makes a logout request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeLogoutRequest(client: Pick<MastraClient, 'options'>): Promise<LogoutResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const response = await fetch(`${baseUrl}${prefix}/auth/logout`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to logout: ${response.status}`);\n }\n\n return response.json();\n}\n\nexport interface UseLogoutOptions {\n /**\n * Runs once the server has ended the session, before the mutation resolves.\n * Failures are ignored so cleanup never turns a completed sign-out into an error.\n */\n onLoggedOut?: (variables: { userId: string }) => Promise<void>;\n queryOptions?: MastraMutationOptions<LogoutResponse, { userId: string }>;\n}\n\nexport function useLogout({ onLoggedOut, queryOptions }: UseLogoutOptions = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<LogoutResponse, Error, { userId: string }>({\n mutationFn: async variables => {\n const response = await makeLogoutRequest(client);\n await onLoggedOut?.(variables).catch(() => {});\n return response;\n },\n onSuccess: () => {\n // Invalidate all auth-related queries\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n"],"mappings":";;;;;;;;AAkHA,SAAgB,gBAAgB,cAA2E;CACzG,OAAO,UAAU,gBAAgB,aAAa,SAAS,KAAA;AACzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1FA,eAAsB,iBACpB,UACA,OACA,MACmB;CACnB,OAAO,MAAM,OAAO,IAAI;AAC1B;AAEA,SAAgB,uBAAuB,UAAmB,YAAmC;CAC3F,QAAQ,OAAO,SAAS,MAAM,OAAO,IAAI;AAC3C;;;AClCA,MAAM,kCAAkB,IAAI,QAA8B;AAC1D,IAAI,qBAAqB;;;;;AAMzB,SAAgB,kBAAkB,QAAsB;CACtD,MAAM,cAAc,gBAAgB,IAAI,MAAM;CAC9C,IAAI,gBAAgB,KAAA,GAAW,OAAO;CAEtC,MAAM,WAAW;CACjB,gBAAgB,IAAI,QAAQ,QAAQ;CACpC,OAAO;AACT;;;ACVA,eAAsB,oBACpB,QACA,EAAE,eACyB;CAC3B,MAAM,EAAE,UAAU,IAAI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mB;EACjB,aAAa,EAAE,kBAA4C,oBAAoB,QAAQ,EAAE,YAAY,CAAC;EACtG,GAAG;CACL,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,eAAsB,kBAAkB,QAAgE;CACtG,MAAM,EAAE,UAAU,IAAI,WAAW,SAAS,gBAAgB,CAAC,MAAM,OAAO;CACxE,MAAM,OAAO,aAAa,OAAA,CAAQ,KAAK;CACvC,MAAM,UAAU,IAAI,WAAW,GAAG,IAAI,MAAM,IAAI,MAAA,CAAO,QAAQ,OAAO,EAAE;CAExE,MAAM,WAAW,MAAM,MAAM,GAAG,UAAU,OAAO,eAAe;EAC9D,QAAQ;EACR,aAAa;EACb,SAAS;GACP,GAAG;GACH,gBAAgB;EAClB;CACF,CAAC;CAED,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,qBAAqB,SAAS,QAAQ;CAGxD,OAAO,SAAS,KAAK;AACvB;AAWA,SAAgB,UAAU,EAAE,aAAa,iBAAmC,CAAC,GAAG;CAC9E,MAAM,SAASA,8BAAAA,gBAAgB;CAC/B,MAAM,eAAA,GAAA,sBAAA,eAAA,CAA6B;CAEnC,QAAA,GAAA,sBAAA,YAAA,CAA8D;EAC5D,YAAY,OAAM,cAAa;GAC7B,MAAM,WAAW,MAAM,kBAAkB,MAAM;GAC/C,MAAM,cAAc,SAAS,CAAC,CAAC,YAAY,CAAC,CAAC;GAC7C,OAAO;EACT;EACA,iBAAiB;GAEf,YAAiB,kBAAkB,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;EAC3D;EACA,GAAG;CACL,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["useMastraClient","useQuery","useMastraClient","useQuery","useMastraClient","useQuery","useMemo","useMastraClient","useQueryClient","useMutation","useMastraClient","useQueryClient","useMutation","useMastraClient","useMutation","useQueryClient"],"sources":["../../../src/hooks/auth/types.ts","../../../src/hooks/auth/fetch-with-refresh.ts","../../../src/hooks/auth/get-client-query-key.ts","../../../src/hooks/auth/sso-login.ts","../../../src/hooks/auth/use-auth-capabilities.ts","../../../src/hooks/auth/use-current-user.ts","../../../src/hooks/auth/use-permission-patterns.ts","../../../src/hooks/auth/use-credentials-login.ts","../../../src/hooks/auth/use-credentials-signup.ts","../../../src/hooks/auth/use-auth-actions.ts"],"sourcesContent":["/**\n * Auth types for EE authentication in playground-ui.\n *\n * These types mirror the server schemas from @mastra/server.\n */\n\n/**\n * SSO configuration for login\n */\nexport type SSOConfig = {\n provider: string;\n text: string;\n icon?: string;\n description?: string;\n url: string;\n};\n\n/**\n * Login configuration\n */\nexport type LoginConfig = {\n type: 'sso' | 'credentials' | 'both';\n /** Whether sign-up is enabled (defaults to true) */\n signUpEnabled?: boolean;\n /** Optional description explaining the auth requirement and what credentials to use */\n description?: string;\n sso?: SSOConfig;\n} | null;\n\n/**\n * Public capabilities (unauthenticated)\n */\nexport type PublicAuthCapabilities = {\n enabled: boolean;\n login: LoginConfig;\n};\n\n/**\n * Authenticated user information\n */\nexport type AuthenticatedUser = {\n id: string;\n email?: string;\n name?: string;\n avatarUrl?: string;\n};\n\n/**\n * Capability flags\n */\nexport type CapabilityFlags = {\n user: boolean;\n session: boolean;\n sso: boolean;\n rbac: boolean;\n acl: boolean;\n};\n\n/**\n * User access information\n */\nexport type UserAccess = {\n roles: string[];\n permissions: string[];\n} | null;\n\n/**\n * Authenticated capabilities (extends public)\n */\nexport type AuthenticatedCapabilities = PublicAuthCapabilities & {\n user: AuthenticatedUser;\n capabilities: CapabilityFlags;\n access: UserAccess;\n /** Available roles in the system (only present for admin users) */\n availableRoles?: { id: string; name: string }[];\n};\n\n/**\n * Auth capabilities response (union of public and authenticated)\n */\nexport type AuthCapabilities = PublicAuthCapabilities | AuthenticatedCapabilities;\n\n/**\n * Current user response (may be null if not authenticated)\n */\nexport type CurrentUser = {\n id: string;\n email?: string;\n name?: string;\n avatarUrl?: string;\n roles?: string[];\n permissions?: string[];\n} | null;\n\n/**\n * SSO callback response\n */\nexport type SSOCallbackResponse = {\n success: boolean;\n user?: AuthenticatedUser;\n redirectTo?: string;\n};\n\n/**\n * Logout response\n */\nexport type LogoutResponse = {\n success: boolean;\n redirectTo?: string;\n};\n\n/**\n * Type guard to check if capabilities include authenticated user\n */\nexport function isAuthenticated(capabilities: AuthCapabilities): capabilities is AuthenticatedCapabilities {\n return 'user' in capabilities && capabilities.user !== undefined;\n}\n","/**\n * Fetch wrapper for the Mastra server API.\n *\n * ⚠️ MIRRORS: `platform/frontend/src/shared/lib/fetch-with-refresh.ts`\n *\n * Both files must stay behaviourally in lockstep — the platform dashboard and\n * the embedded playground both talk to WorkOS-backed auth and both would be\n * vulnerable to the same 429 lockout loop if either regressed. If you change\n * one, change the other in the same PR (or extract to a shared package —\n * currently blocked by the platform/mastra-ai monorepo boundary).\n *\n * ---\n *\n * The server middleware already refreshes the WorkOS session transparently\n * on every protected request. There is no scenario where the client can\n * succeed by calling /auth/refresh after a 401 — that endpoint hits the\n * same broken WorkOS with the same session and would only amplify transient\n * failures into forced logout (PLTFRM-1270).\n *\n * These are pass-throughs today. The names and signatures are preserved for\n * compatibility with existing call sites (`App.tsx`, `use-current-user.ts`).\n * Transient-failure retry belongs one level up — in React Query's `retry`\n * config on individual queries — not in a fetch wrapper that would compound\n * with the query-level retry.\n */\n\nexport async function fetchWithRefresh(\n _baseUrl: string,\n input: RequestInfo | URL,\n init?: RequestInit,\n): Promise<Response> {\n return fetch(input, init);\n}\n\nexport function createFetchWithRefresh(_baseUrl?: string, _apiPrefix?: string): typeof fetch {\n return (input, init) => fetch(input, init);\n}\n","import type { MastraClient } from '@mastra/client-js';\n\nconst clientQueryKeys = new WeakMap<MastraClient, number>();\nlet nextClientQueryKey = 0;\n\n/**\n * Returns a stable, non-sensitive query key for a Mastra client instance.\n * A new client is created whenever its connection options change.\n */\nexport function getClientQueryKey(client: MastraClient) {\n const existingKey = clientQueryKeys.get(client);\n if (existingKey !== undefined) return existingKey;\n\n const queryKey = nextClientQueryKey++;\n clientQueryKeys.set(client, queryKey);\n return queryKey;\n}\n","import type { MastraClient } from '@mastra/client-js';\n\nexport type SSOLoginResponse = {\n url: string;\n};\n\nexport async function makeSSOLoginRequest(\n client: Pick<MastraClient, 'options'>,\n { redirectUri }: { redirectUri?: string },\n): Promise<SSOLoginResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const params = new URLSearchParams();\n if (redirectUri) {\n params.set('redirect_uri', redirectUri);\n }\n\n const url = `${baseUrl}${prefix}/auth/sso/login${params.toString() ? `?${params}` : ''}`;\n\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to initiate SSO login: ${response.status}`);\n }\n\n return response.json();\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { getClientQueryKey } from './get-client-query-key';\nimport type { AuthCapabilities } from './types';\n\n/**\n * Makes a request to the auth capabilities endpoint.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeAuthCapabilitiesRequest(client: MastraClient): Promise<AuthCapabilities> {\n const { baseUrl = '', headers: clientHeaders = {}, apiPrefix } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const response = await fetch(`${baseUrl}${prefix}/auth/capabilities`, {\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch auth capabilities: ${response.status}`);\n }\n\n return response.json();\n}\n\n/**\n * Hook to fetch authentication capabilities.\n *\n * Returns server-authoritative capability detection including:\n * - Whether auth is enabled\n * - Login configuration (SSO, credentials, or both)\n * - Current user (if authenticated)\n * - Available capabilities (user awareness, session, SSO, RBAC, ACL, audit)\n * - User access (roles and permissions)\n *\n * @example\n * ```tsx\n * import { useAuthCapabilities } from '@mastra/react/hooks/auth';\n *\n * function AuthStatus() {\n * const { data: capabilities, isLoading } = useAuthCapabilities();\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (!capabilities?.enabled) return <div>Auth not enabled</div>;\n *\n * if (isAuthenticated(capabilities)) {\n * return <div>Welcome, {capabilities.user.name}</div>;\n * }\n *\n * return <LoginButton config={capabilities.login} />;\n * }\n * ```\n */\nexport function useAuthCapabilities<TData = AuthCapabilities>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<AuthCapabilities, TData> } = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery<AuthCapabilities, Error, TData>({\n queryKey: ['auth', 'capabilities', getClientQueryKey(client)],\n queryFn: () => makeAuthCapabilitiesRequest(client),\n staleTime: 60 * 1000, // Cache for 1 minute\n retry: false, // Don't retry auth requests\n ...queryOptions,\n });\n}\n","import type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { fetchWithRefresh } from './fetch-with-refresh';\nimport type { CurrentUser } from './types';\n\nconst AUTH_TRANSIENT_MAX_RETRIES = 3;\nconst AUTH_TRANSIENT_MAX_BACKOFF_MS = 8_000;\n\nexport class CurrentUserError extends Error {\n constructor(public readonly status: number) {\n super(`Failed to fetch current user: ${status}`);\n this.name = 'CurrentUserError';\n }\n}\n\nexport function isUnauthenticatedError(error: unknown): boolean {\n return error instanceof CurrentUserError && error.status === 401;\n}\n\n/**\n * Hook to fetch the current authenticated user.\n *\n * Returns the current user if authenticated, null otherwise.\n * Includes roles and permissions if RBAC is available.\n *\n * Uses fetchWithRefresh to automatically refresh the session on 401 errors,\n * preventing users from being logged out when the access token expires.\n *\n * @example\n * ```tsx\n * import { useCurrentUser } from '@mastra/react/hooks/auth';\n *\n * function UserMenu() {\n * const { data: user, isLoading } = useCurrentUser();\n *\n * if (isLoading) return <Skeleton />;\n * if (!user) return <LoginButton />;\n *\n * return (\n * <Menu>\n * <Avatar src={user.avatarUrl} />\n * <span>{user.name || user.email}</span>\n * </Menu>\n * );\n * }\n * ```\n */\nexport function useCurrentUser<TData = CurrentUser>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<CurrentUser, TData> } = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n const baseUrl = client.options?.baseUrl || '';\n\n return useQuery<CurrentUser, Error, TData>({\n queryKey: ['auth', 'me'],\n queryFn: async () => {\n const response = await fetchWithRefresh(baseUrl, `${baseUrl}/api/auth/me`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new CurrentUserError(response.status);\n }\n\n return response.json();\n },\n staleTime: 60 * 1000, // Cache for 1 minute\n // Retry the /api/auth/me query on transient auth-provider failures (HTTP 503)\n // so the UI stays in `isLoading` instead of flipping to `isError` and\n // triggering login — that redirect is what fed the WorkOS 429 lockout loop\n // (PLTFRM-1270). 401 (terminal) still fails fast.\n retry: (failureCount, error) => {\n if (!(error instanceof CurrentUserError)) return false;\n if (error.status !== 503) return false;\n return failureCount < AUTH_TRANSIENT_MAX_RETRIES;\n },\n retryDelay: attemptIndex => Math.min(AUTH_TRANSIENT_MAX_BACKOFF_MS, 500 * 2 ** attemptIndex),\n ...queryOptions,\n });\n}\n","import type { MastraClient, PermissionPattern } from '@mastra/client-js';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { getClientQueryKey } from './get-client-query-key';\nimport { isAuthenticated } from './types';\nimport { useAuthCapabilities } from './use-auth-capabilities';\n\n/**\n * Fetches the authoritative set of permission patterns from the server\n * (`GET /auth/permission-patterns`).\n *\n * The server owns the permission source of truth (generated from the route\n * registry), so the browser never imports the server-only `@mastra/core/auth/ee`\n * code just to validate hardcoded route-permission literals.\n *\n * The request only fires when RBAC is actually enabled — when auth is off or\n * RBAC isn't configured, route gating is a no-op so the pattern vocabulary is\n * not needed, and we avoid an unnecessary (and potentially 403/401) call.\n */\ntype PermissionPatternsResponse = Awaited<ReturnType<MastraClient['getPermissionPatterns']>>;\n\nexport const usePermissionPatterns = ({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<PermissionPatternsResponse> } = {}) => {\n const client = useMastraClient();\n const { data: capabilities, isLoading: capabilitiesLoading, error: capabilitiesError } = useAuthCapabilities();\n\n const rbacEnabled = !!(capabilities && isAuthenticated(capabilities) && capabilities.capabilities.rbac);\n\n const { data, isLoading, error } = useQuery({\n queryKey: ['permission-patterns', getClientQueryKey(client)],\n queryFn: () => client.getPermissionPatterns(),\n // Only fetch the pattern vocabulary when RBAC gating is in effect.\n enabled: rbacEnabled,\n // The endpoint requires auth; on 403/401 we don't want React Query to\n // thrash with retries (which toggles isLoading and re-triggers redirect\n // guards). One attempt is enough — gating falls back to the user's\n // permissions if the pattern set is empty.\n retry: false,\n staleTime: Infinity,\n ...queryOptions,\n });\n\n const patterns = useMemo(() => new Set<PermissionPattern>(data?.patterns ?? []), [data]);\n\n // While capabilities are resolving we don't yet know whether RBAC applies, so\n // report loading. Once RBAC is ruled out, this hook is never \"loading\".\n return { patterns, isLoading: capabilitiesLoading || (rbacEnabled && isLoading), error: capabilitiesError || error };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nexport type CredentialsLoginRequest = {\n email: string;\n password: string;\n};\n\nexport type CredentialsLoginResponse = {\n user?: {\n id: string;\n email: string;\n name?: string;\n };\n error?: string;\n};\n\n/**\n * Hook to login with email/password credentials.\n *\n * Uses Better Auth's email sign-in endpoint.\n *\n * @example\n * ```tsx\n * import { useCredentialsLogin } from '@mastra/react/hooks/auth';\n *\n * function LoginForm() {\n * const { mutate: login, isPending, error } = useCredentialsLogin();\n *\n * const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n * e.preventDefault();\n * const formData = new FormData(e.currentTarget);\n * login({\n * email: formData.get('email') as string,\n * password: formData.get('password') as string,\n * }, {\n * onSuccess: () => {\n * window.location.href = '/';\n * },\n * });\n * };\n *\n * return (\n * <form onSubmit={handleSubmit}>\n * <input name=\"email\" type=\"email\" required />\n * <input name=\"password\" type=\"password\" required />\n * <button type=\"submit\" disabled={isPending}>\n * Sign in\n * </button>\n * {error && <p>{error.message}</p>}\n * </form>\n * );\n * }\n * ```\n */\n/**\n * Makes a credentials sign-in request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeCredentialsLoginRequest(\n client: MastraClient,\n { email, password }: CredentialsLoginRequest,\n): Promise<CredentialsLoginResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options || {};\n const raw = (apiPrefix ?? '/api').trim();\n const normalized = raw === '' ? '' : raw.startsWith('/') ? raw : `/${raw}`;\n const prefix = normalized.replace(/\\/+$/, '');\n\n // Generic Mastra auth endpoint - works with any credentials provider\n const response = await fetch(`${baseUrl}${prefix}/auth/credentials/sign-in`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ email, password }),\n });\n\n const data = await response.json();\n\n if (!response.ok) {\n throw new Error(data.message || data.error || 'Invalid email or password');\n }\n\n return data;\n}\n\nexport function useCredentialsLogin({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<CredentialsLoginResponse, CredentialsLoginRequest> } = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<CredentialsLoginResponse, Error, CredentialsLoginRequest>({\n mutationFn: ({ email, password }) => makeCredentialsLoginRequest(client, { email, password }),\n onSuccess: () => {\n // Invalidate auth queries to refetch user state\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nexport type CredentialsSignUpRequest = {\n email: string;\n password: string;\n name?: string;\n};\n\nexport type CredentialsSignUpResponse = {\n user?: {\n id: string;\n email: string;\n name?: string;\n };\n error?: string;\n};\n\n/**\n * Hook to sign up with email/password credentials.\n *\n * Uses Better Auth's email sign-up endpoint.\n *\n * @example\n * ```tsx\n * import { useCredentialsSignUp } from '@mastra/react/hooks/auth';\n *\n * function SignUpForm() {\n * const { mutate: signUp, isPending, error } = useCredentialsSignUp();\n *\n * const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n * e.preventDefault();\n * const formData = new FormData(e.currentTarget);\n * signUp({\n * email: formData.get('email') as string,\n * password: formData.get('password') as string,\n * name: formData.get('name') as string,\n * }, {\n * onSuccess: () => {\n * window.location.href = '/';\n * },\n * });\n * };\n *\n * return (\n * <form onSubmit={handleSubmit}>\n * <input name=\"name\" type=\"text\" />\n * <input name=\"email\" type=\"email\" required />\n * <input name=\"password\" type=\"password\" required />\n * <button type=\"submit\" disabled={isPending}>\n * Sign up\n * </button>\n * {error && <p>{error.message}</p>}\n * </form>\n * );\n * }\n * ```\n */\n/**\n * Makes a credentials sign-up request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeCredentialsSignUpRequest(\n client: MastraClient,\n { email, password, name }: CredentialsSignUpRequest,\n): Promise<CredentialsSignUpResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options || {};\n const raw = (apiPrefix ?? '/api').trim();\n const normalized = raw === '' ? '' : raw.startsWith('/') ? raw : `/${raw}`;\n const prefix = normalized.replace(/\\/+$/, '');\n\n // Generic Mastra auth endpoint - works with any credentials provider\n const response = await fetch(`${baseUrl}${prefix}/auth/credentials/sign-up`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ email, password, name }),\n });\n\n const data = await response.json();\n\n if (!response.ok) {\n throw new Error(data.message || data.error || 'Failed to create account');\n }\n\n return data;\n}\n\nexport function useCredentialsSignUp({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<CredentialsSignUpResponse, CredentialsSignUpRequest> } = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<CredentialsSignUpResponse, Error, CredentialsSignUpRequest>({\n mutationFn: ({ email, password, name }) => makeCredentialsSignUpRequest(client, { email, password, name }),\n onSuccess: () => {\n // Invalidate auth queries to refetch user state\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nimport { makeSSOLoginRequest } from './sso-login';\nimport type { LogoutResponse } from './types';\n\n/**\n * Hook to initiate SSO login.\n *\n * Returns mutation to get the SSO login URL and redirect.\n *\n * @example\n * ```tsx\n * import { useSSOLogin } from '@mastra/react/hooks/auth';\n *\n * function SSOLoginButton() {\n * const { mutate: login, isPending } = useSSOLogin();\n *\n * const handleClick = () => {\n * login({ redirectUri: window.location.href }, {\n * onSuccess: (data) => {\n * window.location.href = data.url;\n * },\n * });\n * };\n *\n * return (\n * <button onClick={handleClick} disabled={isPending}>\n * Sign in with SSO\n * </button>\n * );\n * }\n * ```\n */\ntype SSOLoginResponse = Awaited<ReturnType<typeof makeSSOLoginRequest>>;\n\nexport function useSSOLogin({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<SSOLoginResponse, { redirectUri?: string }> } = {}) {\n const client = useMastraClient();\n\n return useMutation({\n mutationFn: ({ redirectUri }: { redirectUri?: string }) => makeSSOLoginRequest(client, { redirectUri }),\n ...queryOptions,\n });\n}\n\n/**\n * Hook to logout the current user.\n *\n * Destroys the current session and optionally redirects to\n * the SSO logout URL if available.\n *\n * @example\n * ```tsx\n * import { useLogout } from '@mastra/react/hooks/auth';\n *\n * function LogoutButton({ userId }: { userId: string }) {\n * const { mutate: logout, isPending } = useLogout();\n * const queryClient = useQueryClient();\n *\n * const handleLogout = () => {\n * logout({ userId }, {\n * onSuccess: (data) => {\n * queryClient.invalidateQueries({ queryKey: ['auth'] });\n * if (data.redirectTo) {\n * window.location.href = data.redirectTo;\n * } else {\n * window.location.reload();\n * }\n * },\n * });\n * };\n *\n * return (\n * <button onClick={handleLogout} disabled={isPending}>\n * Sign out\n * </button>\n * );\n * }\n * ```\n */\n/**\n * Makes a logout request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeLogoutRequest(client: Pick<MastraClient, 'options'>): Promise<LogoutResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const response = await fetch(`${baseUrl}${prefix}/auth/logout`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to logout: ${response.status}`);\n }\n\n return response.json();\n}\n\nexport interface UseLogoutOptions {\n /**\n * Runs once the server has ended the session, before the mutation resolves.\n * Failures are ignored so cleanup never turns a completed sign-out into an error.\n */\n onLoggedOut?: (variables: { userId: string }) => Promise<void>;\n queryOptions?: MastraMutationOptions<LogoutResponse, { userId: string }>;\n}\n\nexport function useLogout({ onLoggedOut, queryOptions }: UseLogoutOptions = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<LogoutResponse, Error, { userId: string }>({\n mutationFn: async variables => {\n const response = await makeLogoutRequest(client);\n await onLoggedOut?.(variables).catch(() => {});\n return response;\n },\n onSuccess: () => {\n // Invalidate all auth-related queries\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n"],"mappings":";;;;;;;;AAkHA,SAAgB,gBAAgB,cAA2E;CACzG,OAAO,UAAU,gBAAgB,aAAa,SAAS,KAAA;AACzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1FA,eAAsB,iBACpB,UACA,OACA,MACmB;CACnB,OAAO,MAAM,OAAO,IAAI;AAC1B;AAEA,SAAgB,uBAAuB,UAAmB,YAAmC;CAC3F,QAAQ,OAAO,SAAS,MAAM,OAAO,IAAI;AAC3C;;;AClCA,MAAM,kCAAkB,IAAI,QAA8B;AAC1D,IAAI,qBAAqB;;;;;AAMzB,SAAgB,kBAAkB,QAAsB;CACtD,MAAM,cAAc,gBAAgB,IAAI,MAAM;CAC9C,IAAI,gBAAgB,KAAA,GAAW,OAAO;CAEtC,MAAM,WAAW;CACjB,gBAAgB,IAAI,QAAQ,QAAQ;CACpC,OAAO;AACT;;;ACVA,eAAsB,oBACpB,QACA,EAAE,eACyB;CAC3B,MAAM,EAAE,UAAU,IAAI,WAAW,SAAS,gBAAgB,CAAC,MAAM,OAAO;CACxE,MAAM,OAAO,aAAa,OAAA,CAAQ,KAAK;CACvC,MAAM,UAAU,IAAI,WAAW,GAAG,IAAI,MAAM,IAAI,MAAA,CAAO,QAAQ,OAAO,EAAE;CAExE,MAAM,SAAS,IAAI,gBAAgB;CACnC,IAAI,aACF,OAAO,IAAI,gBAAgB,WAAW;CAGxC,MAAM,MAAM,GAAG,UAAU,OAAO,iBAAiB,OAAO,SAAS,IAAI,IAAI,WAAW;CAEpF,MAAM,WAAW,MAAM,MAAM,KAAK;EAChC,aAAa;EACb,SAAS;GACP,GAAG;GACH,gBAAgB;EAClB;CACF,CAAC;CAED,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,iCAAiC,SA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G;GACH,gBAAgB;EAClB;CACF,CAAC;CAED,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,qBAAqB,SAAS,QAAQ;CAGxD,OAAO,SAAS,KAAK;AACvB;AAWA,SAAgB,UAAU,EAAE,aAAa,iBAAmC,CAAC,GAAG;CAC9E,MAAM,SAASD,8BAAAA,gBAAgB;CAC/B,MAAM,eAAA,GAAcE,sBAAAA,eAAAA,CAAe;CAEnC,QAAA,GAAOD,sBAAAA,YAAAA,CAAuD;EAC5D,YAAY,OAAM,cAAa;GAC7B,MAAM,WAAW,MAAM,kBAAkB,MAAM;GAC/C,MAAM,cAAc,SAAS,CAAC,CAAC,YAAY,CAAC,CAAC;GAC7C,OAAO;EACT;EACA,iBAAiB;GAEf,YAAiB,kBAAkB,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;EAC3D;EACA,GAAG;CACL,CAAC;AACH"}
|
package/dist/hooks/auth/index.js
CHANGED
|
@@ -134,7 +134,7 @@ function useAuthCapabilities({ queryOptions } = {}) {
|
|
|
134
134
|
getClientQueryKey(client)
|
|
135
135
|
],
|
|
136
136
|
queryFn: () => makeAuthCapabilitiesRequest(client),
|
|
137
|
-
staleTime:
|
|
137
|
+
staleTime: 6e4,
|
|
138
138
|
retry: false,
|
|
139
139
|
...queryOptions
|
|
140
140
|
});
|
|
@@ -194,7 +194,7 @@ function useCurrentUser({ queryOptions } = {}) {
|
|
|
194
194
|
if (!response.ok) throw new CurrentUserError(response.status);
|
|
195
195
|
return response.json();
|
|
196
196
|
},
|
|
197
|
-
staleTime:
|
|
197
|
+
staleTime: 6e4,
|
|
198
198
|
retry: (failureCount, error) => {
|
|
199
199
|
if (!(error instanceof CurrentUserError)) return false;
|
|
200
200
|
if (error.status !== 503) return false;
|