@mastra/react 1.12.0-alpha.8 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/dist/{accumulator-C8kIc450.js → accumulator-BfvVnXJr.js} +1 -2
  2. package/dist/{accumulator-C8kIc450.js.map → accumulator-BfvVnXJr.js.map} +1 -1
  3. package/dist/{accumulator-BQGsraqS.cjs → accumulator-CgLQ_3q3.cjs} +1 -2
  4. package/dist/{accumulator-BQGsraqS.cjs.map → accumulator-CgLQ_3q3.cjs.map} +1 -1
  5. package/dist/chat/index.cjs +1 -1
  6. package/dist/chat/index.js +1 -2
  7. package/dist/combine-by-ids-D_lp6Dvq.cjs.map +1 -1
  8. package/dist/experiments-B7vRMK5T.js +306 -0
  9. package/dist/experiments-B7vRMK5T.js.map +1 -0
  10. package/dist/experiments-CJw1N3FB.cjs +353 -0
  11. package/dist/experiments-CJw1N3FB.cjs.map +1 -0
  12. package/dist/hooks/agents/index.cjs +2 -2
  13. package/dist/hooks/agents/index.cjs.map +1 -1
  14. package/dist/hooks/agents/index.js +2 -2
  15. package/dist/hooks/agents/index.js.map +1 -1
  16. package/dist/hooks/auth/index.cjs +2 -2
  17. package/dist/hooks/auth/index.cjs.map +1 -1
  18. package/dist/hooks/auth/index.js +2 -2
  19. package/dist/hooks/auth/index.js.map +1 -1
  20. package/dist/hooks/capabilities/index.cjs +16 -1
  21. package/dist/hooks/capabilities/index.cjs.map +1 -1
  22. package/dist/hooks/capabilities/index.d.ts +1 -0
  23. package/dist/hooks/capabilities/index.d.ts.map +1 -1
  24. package/dist/hooks/capabilities/index.js +16 -2
  25. package/dist/hooks/capabilities/index.js.map +1 -1
  26. package/dist/hooks/capabilities/use-trace-query-delta-polling-available.d.ts +10 -0
  27. package/dist/hooks/capabilities/use-trace-query-delta-polling-available.d.ts.map +1 -0
  28. package/dist/hooks/configuration/index.cjs.map +1 -1
  29. package/dist/hooks/datasets/index.cjs +25 -1
  30. package/dist/hooks/datasets/index.cjs.map +1 -1
  31. package/dist/hooks/datasets/index.js +25 -2
  32. package/dist/hooks/datasets/index.js.map +1 -1
  33. package/dist/hooks/datasets/use-datasets.d.ts +7 -0
  34. package/dist/hooks/datasets/use-datasets.d.ts.map +1 -1
  35. package/dist/hooks/embedders/index.cjs.map +1 -1
  36. package/dist/hooks/experiments/index.cjs +9 -235
  37. package/dist/hooks/experiments/index.d.ts +1 -0
  38. package/dist/hooks/experiments/index.d.ts.map +1 -1
  39. package/dist/hooks/experiments/index.js +1 -229
  40. package/dist/hooks/experiments/usage-accumulator.d.ts +25 -0
  41. package/dist/hooks/experiments/usage-accumulator.d.ts.map +1 -0
  42. package/dist/hooks/experiments/use-experiment-item-usage.d.ts +2 -7
  43. package/dist/hooks/experiments/use-experiment-item-usage.d.ts.map +1 -1
  44. package/dist/hooks/experiments/use-experiments-list-metrics.d.ts +19 -0
  45. package/dist/hooks/experiments/use-experiments-list-metrics.d.ts.map +1 -0
  46. package/dist/hooks/feedback/index.cjs.map +1 -1
  47. package/dist/hooks/llm/index.cjs.map +1 -1
  48. package/dist/hooks/logs/index.cjs.map +1 -1
  49. package/dist/hooks/mcps/index.cjs.map +1 -1
  50. package/dist/hooks/memory/index.cjs +10 -10
  51. package/dist/hooks/memory/index.cjs.map +1 -1
  52. package/dist/hooks/memory/index.js +10 -10
  53. package/dist/hooks/memory/index.js.map +1 -1
  54. package/dist/hooks/metrics/index.cjs +13 -11
  55. package/dist/hooks/metrics/index.cjs.map +1 -1
  56. package/dist/hooks/metrics/index.js +13 -11
  57. package/dist/hooks/metrics/index.js.map +1 -1
  58. package/dist/hooks/processors/index.cjs.map +1 -1
  59. package/dist/hooks/prompt-blocks/index.cjs.map +1 -1
  60. package/dist/hooks/query/index.cjs.map +1 -1
  61. package/dist/hooks/review/index.cjs +2 -2
  62. package/dist/hooks/review/index.cjs.map +1 -1
  63. package/dist/hooks/review/index.js +1 -1
  64. package/dist/hooks/schedules/index.cjs.map +1 -1
  65. package/dist/hooks/scores/index.cjs.map +1 -1
  66. package/dist/hooks/templates/index.cjs +20 -18
  67. package/dist/hooks/templates/index.cjs.map +1 -1
  68. package/dist/hooks/templates/index.js +20 -18
  69. package/dist/hooks/templates/index.js.map +1 -1
  70. package/dist/hooks/tool-providers/index.cjs +1 -1
  71. package/dist/hooks/tool-providers/index.cjs.map +1 -1
  72. package/dist/hooks/tool-providers/index.js +1 -1
  73. package/dist/hooks/tool-providers/index.js.map +1 -1
  74. package/dist/hooks/tools/index.cjs.map +1 -1
  75. package/dist/hooks/traces/index.cjs +185 -10
  76. package/dist/hooks/traces/index.cjs.map +1 -1
  77. package/dist/hooks/traces/index.js +182 -11
  78. package/dist/hooks/traces/index.js.map +1 -1
  79. package/dist/hooks/traces/use-trace-query.d.ts +50 -1
  80. package/dist/hooks/traces/use-trace-query.d.ts.map +1 -1
  81. package/dist/hooks/vectors/index.cjs.map +1 -1
  82. package/dist/hooks/voice/index.cjs.map +1 -1
  83. package/dist/hooks/workflows/index.cjs +1 -1
  84. package/dist/hooks/workflows/index.cjs.map +1 -1
  85. package/dist/hooks/workflows/index.js +1 -1
  86. package/dist/hooks/workspace/index.cjs +1 -1
  87. package/dist/hooks/workspace/index.cjs.map +1 -1
  88. package/dist/hooks/workspace/index.js +1 -1
  89. package/dist/hooks/workspace/index.js.map +1 -1
  90. package/dist/{hooks-CIutb3DO.cjs → hooks-B1i-oHae.cjs} +6 -4
  91. package/dist/hooks-B1i-oHae.cjs.map +1 -0
  92. package/dist/{hooks-FVbeHlov.js → hooks-CLfMO5cH.js} +6 -4
  93. package/dist/{hooks-FVbeHlov.js.map → hooks-CLfMO5cH.js.map} +1 -1
  94. package/dist/{hooks-_YevKidX.cjs → hooks-D8nOYPUd.cjs} +2 -2
  95. package/dist/hooks-D8nOYPUd.cjs.map +1 -0
  96. package/dist/{hooks-0L0RNfau.js → hooks-NaZLZreZ.js} +2 -2
  97. package/dist/{hooks-0L0RNfau.js.map → hooks-NaZLZreZ.js.map} +1 -1
  98. package/dist/index.cjs +3 -3
  99. package/dist/index.cjs.map +1 -1
  100. package/dist/index.js +3 -3
  101. package/dist/mastra-client-context-DzX3f0RF.cjs.map +1 -1
  102. package/dist/ui/index.cjs +4 -4
  103. package/dist/ui/index.cjs.map +1 -1
  104. package/dist/ui/index.js +3 -3
  105. package/dist/ui/index.js.map +1 -1
  106. package/dist/use-in-view-B6eJO9Zi.cjs.map +1 -1
  107. package/dist/voice-BOtUdMi8.cjs.map +1 -1
  108. package/package.json +5 -5
  109. package/dist/hooks/experiments/index.cjs.map +0 -1
  110. package/dist/hooks/experiments/index.js.map +0 -1
  111. package/dist/hooks-CIutb3DO.cjs.map +0 -1
  112. package/dist/hooks-_YevKidX.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["useMastraClient","useMastraClient","useCurrentUser","isUnauthenticatedError","useMastraClient","useMastraClient","useMastraClient","useMastraClient","useCurrentUser","isUnauthenticatedError","useMastraClient","useMastraClient","useMastraClient"],"sources":["../../../src/hooks/tool-providers/use-tool-providers.ts","../../../src/hooks/tool-providers/use-all-connections.ts","../../../src/hooks/tool-providers/use-all-provider-tools.ts","../../../src/hooks/tool-providers/use-authorize.ts","../../../src/hooks/tool-providers/use-disconnect-connection.ts","../../../src/hooks/tool-providers/use-existing-connections.ts","../../../src/hooks/tool-providers/use-provider-tools.ts","../../../src/hooks/tool-providers/use-toolkits.ts","../../../src/hooks/tool-providers/use-update-connection.ts"],"sourcesContent":["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 ToolProvidersResponse = Awaited<ReturnType<MastraClient['listToolProviders']>>;\n\nexport const useToolProviders = <TData = ToolProvidersResponse>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<ToolProvidersResponse, TData> } = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['tool-providers'],\n queryFn: () => client.listToolProviders(),\n ...queryOptions,\n });\n};\n\nexport interface IntegrationTool {\n slug: string;\n name: string;\n description?: string;\n toolkit?: string;\n providerId: string;\n providerName: string;\n}\n\nexport const useAllIntegrationTools = ({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<IntegrationTool[]> } = {}) => {\n const client = useMastraClient();\n const { data: providersData, isLoading: isLoadingProviders } = useToolProviders();\n const providers = providersData?.providers ?? [];\n\n const toolsQuery = useQuery({\n queryKey: ['integration-tools-all', providers.map(p => p.id)],\n queryFn: async () => {\n const results: IntegrationTool[] = [];\n\n for (const provider of providers) {\n const response = await client.getToolProvider(provider.id).listTools();\n for (const tool of response.data) {\n results.push({\n ...tool,\n providerId: provider.id,\n providerName: provider.name,\n });\n }\n }\n\n return results;\n },\n enabled: providers.length > 0,\n ...queryOptions,\n });\n\n return {\n data: toolsQuery.data ?? [],\n isLoading: isLoadingProviders || toolsQuery.isLoading,\n };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { useQueries } from '@tanstack/react-query';\nimport { useCallback, useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport { isUnauthenticatedError, useCurrentUser } from '../auth';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { useToolProviders } from './use-tool-providers';\n\n/**\n * Stale time long enough to avoid refetching on every picker re-render but\n * short enough that an OAuth completion in a sibling tab is reflected\n * promptly (React Query also re-fetches on window focus by default).\n */\nconst STALE_TIME_MS = 30_000;\n\nexport interface UseAllConnectionsOptions {\n /**\n * When `true`, the hook forces the server-side `authorId` filter to the\n * caller's own userId. Builder edit view passes `scopeToSelf: true` so\n * admins see only their own connections, never other authors' rows.\n *\n * Non-admin callers see the same result either way — the server already\n * scopes to the caller's bucket — but the explicit filter keeps caches\n * consistent and prevents admin cross-author leakage.\n */\n scopeToSelf?: boolean;\n /** TanStack overrides applied to every fanned-out query, spread last. `select` must keep the default shape. */\n queryOptions?: {\n toolkits?: MastraQueryOptions<Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listToolkits']>>>;\n connections?: MastraQueryOptions<\n Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listConnections']>>\n >;\n };\n}\n\n/**\n * Fans out across every registered ToolProvider and every toolkit it\n * exposes to determine whether the caller has an existing connection for a\n * given `(providerId, toolkit)` pair.\n *\n * Used by the Builder tool picker to gate integration tool rows: if the\n * pair has no connection, the card cannot be selected and surfaces an\n * inline \"Connect\" button instead.\n *\n * Distinct from `useExistingConnections` (per-pair, used by `/integrations`)\n * to keep their query caches independent.\n */\nexport const useAllConnections = ({ scopeToSelf = false, queryOptions }: UseAllConnectionsOptions = {}) => {\n const client = useMastraClient();\n const providersQuery = useToolProviders();\n const providers = useMemo(() => providersQuery.data?.providers ?? [], [providersQuery.data?.providers]);\n\n const currentUserQuery = useCurrentUser();\n const callerAuthorId = currentUserQuery.data?.id;\n const callerReady = !scopeToSelf || currentUserQuery.isSuccess || isUnauthenticatedError(currentUserQuery.error);\n\n // 1. For every provider, list its toolkits.\n const toolkitsQueries = useQueries({\n queries: providers.map(provider => ({\n queryKey: ['tool-integration-services', provider.id],\n queryFn: () => client.getToolProvider(provider.id).listToolkits(),\n ...queryOptions?.toolkits,\n })),\n });\n\n // 2. Flatten to (providerId, toolkit) pairs.\n const pairs = useMemo(() => {\n const out: Array<{ providerId: string; toolkit: string }> = [];\n providers.forEach((provider, idx) => {\n const toolkits = toolkitsQueries[idx]?.data?.data ?? [];\n for (const toolkit of toolkits) {\n out.push({ providerId: provider.id, toolkit: toolkit.slug });\n }\n });\n return out;\n }, [providers, toolkitsQueries]);\n\n // 3. One listConnections call per pair. Include `authorId` in queryKey when\n // self-scoped so the cache is distinct from any unscoped admin reads.\n const connectionsQueries = useQueries({\n queries: pairs.map(pair => ({\n queryKey: scopeToSelf\n ? ['tool-integration-connections-all', pair.providerId, pair.toolkit, callerAuthorId]\n : ['tool-integration-connections-all', pair.providerId, pair.toolkit],\n queryFn: () =>\n client.getToolProvider(pair.providerId).listConnections({\n toolkit: pair.toolkit,\n ...(scopeToSelf && callerAuthorId ? { authorId: callerAuthorId } : {}),\n }),\n enabled: callerReady,\n staleTime: STALE_TIME_MS,\n ...queryOptions?.connections,\n })),\n });\n\n const isLoading =\n providersQuery.isLoading ||\n (scopeToSelf && currentUserQuery.isLoading) ||\n toolkitsQueries.some(q => q.isLoading) ||\n connectionsQueries.some(q => q.isLoading);\n\n // Build a per-pair list of connection summaries so callers can both gate\n // (\"does this row have any connection?\") and auto-pin (\"if exactly one\n // exists, write it into the form on toggle-on\").\n const connectionsByKey = useMemo(() => {\n const map = new Map<string, Array<{ connectionId: string; label?: string | null; status?: string }>>();\n pairs.forEach((pair, idx) => {\n const items = connectionsQueries[idx]?.data?.items ?? [];\n map.set(`${pair.providerId}:${pair.toolkit}`, items);\n });\n return map;\n }, [pairs, connectionsQueries]);\n\n // A toolkit \"has a connection\" only when at least one connection is active.\n // Pending/failed rows don't count — this keeps the card hint in sync with the\n // toolkit row control, which also treats only active connections as usable.\n const hasConnection = useCallback(\n (providerId: string, toolkit: string) =>\n (connectionsByKey.get(`${providerId}:${toolkit}`) ?? []).some(connection => connection.status === 'active'),\n [connectionsByKey],\n );\n\n const getConnections = useCallback(\n (providerId: string, toolkit: string) => connectionsByKey.get(`${providerId}:${toolkit}`) ?? [],\n [connectionsByKey],\n );\n\n return { hasConnection, getConnections, isLoading };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { useQueries } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { useToolProviders } from './use-tool-providers';\n\nexport interface AvailableIntegrationTool {\n providerId: string;\n slug: string;\n toolkit: string;\n name?: string;\n description?: string;\n}\n\n/**\n * Upper bound for a single Composio-style `listTools` call. Composio's SDK has\n * no cursor — only `limit` — so we ask for a large page and fan out per\n * `toolkit` to avoid being truncated when many toolkits are allowlisted.\n */\nconst PER_SERVICE_LIMIT = 500;\n\n/**\n * Returns every tool surfaced by every registered ToolProvider, scoped to\n * the provider's `allowedToolkits`/`allowedTools` filter (enforced\n * server-side). Used to render the full available-tools list inline.\n */\nexport const useAllProviderTools = ({\n queryOptions,\n}: {\n /** TanStack overrides applied to every fanned-out query, spread last. `select` must keep the default shape. */\n queryOptions?: {\n toolkits?: MastraQueryOptions<Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listToolkits']>>>;\n tools?: MastraQueryOptions<Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listTools']>>>;\n };\n} = {}) => {\n const client = useMastraClient();\n const integrationsQuery = useToolProviders();\n const integrations = useMemo(() => integrationsQuery.data?.providers ?? [], [integrationsQuery.data?.providers]);\n\n // 1. For every integration, fetch its tool services.\n const serviceQueries = useQueries({\n queries: integrations.map(integration => ({\n queryKey: ['tool-integration-services', integration.id],\n queryFn: () => client.getToolProvider(integration.id).listToolkits(),\n ...queryOptions?.toolkits,\n })),\n });\n\n // 2. Flatten to (providerId, serviceSlug) pairs.\n const servicePairs = useMemo(() => {\n const pairs: Array<{ providerId: string; toolkit: string }> = [];\n integrations.forEach((integration, idx) => {\n const services = serviceQueries[idx]?.data?.data ?? [];\n for (const service of services) {\n pairs.push({ providerId: integration.id, toolkit: service.slug });\n }\n });\n return pairs;\n }, [integrations, serviceQueries]);\n\n // 3. Fan out one tools query per (integration, service).\n const toolsQueries = useQueries({\n queries: servicePairs.map(pair => ({\n queryKey: ['tool-integration-tools-all', pair.providerId, pair.toolkit],\n queryFn: () =>\n client.getToolProvider(pair.providerId).listTools({ toolkit: pair.toolkit, perPage: PER_SERVICE_LIMIT }),\n ...queryOptions?.tools,\n })),\n });\n\n const isLoading =\n integrationsQuery.isLoading || serviceQueries.some(q => q.isLoading) || toolsQueries.some(q => q.isLoading);\n\n const tools = useMemo<AvailableIntegrationTool[]>(() => {\n const out: AvailableIntegrationTool[] = [];\n servicePairs.forEach((pair, idx) => {\n const items = toolsQueries[idx]?.data?.data ?? [];\n for (const item of items) {\n const toolkit = (item as { toolkit?: string }).toolkit ?? pair.toolkit;\n out.push({\n providerId: pair.providerId,\n slug: item.slug,\n toolkit,\n name: (item as { name?: string }).name,\n description: (item as { description?: string }).description,\n });\n }\n });\n return out;\n }, [servicePairs, toolsQueries]);\n\n return { tools, isLoading };\n};\n","import { useMutation } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nexport interface AuthorizeArgs {\n providerId: string;\n toolkit: string;\n /**\n * Existing bucket id when re-authorizing; omit for a brand-new connection.\n * Semantics are provider-opaque; for Composio v1 this is the internal user\n * bucket the new connected account should be created under.\n */\n connectionId?: string;\n /**\n * Provider-specific connection fields collected from the picker (e.g.\n * Confluence subdomain). Forwarded to the server's `authorize` body.\n */\n config?: Record<string, unknown>;\n /**\n * Optional human label to persist on the resulting `tool_integration_connections` row.\n */\n label?: string | null;\n /**\n * Ownership scope of the OAuth bucket. `'per-author'` (default) buckets\n * under the caller's authorId.\n */\n scope?: 'per-author' | 'shared' | 'caller-supplied';\n}\n\nexport interface AuthorizeResult {\n status: 'completed' | 'failed';\n /**\n * The `authId` returned by `authorize`, exposed as `connectionId` because\n * for the v1 Composio adapter it is the `connected_account.id` that the\n * caller persists as `Connection.connectionId`.\n */\n connectionId: string;\n}\n\nconst DEFAULT_POLL_INTERVAL_MS = 2000;\nconst DEFAULT_TIMEOUT_MS = 5 * 60_000;\n\nexport interface UseAuthorizeOptions {\n pollIntervalMs?: number;\n timeoutMs?: number;\n openPopup?: (url: string) => Window | null;\n queryOptions?: MastraMutationOptions<AuthorizeResult, AuthorizeArgs>;\n}\n\n/**\n * Drives the OAuth popup + polling loop for a `ToolProvider` provider.\n */\nexport const useAuthorize = (options: UseAuthorizeOptions = {}) => {\n const client = useMastraClient();\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const openPopup = options.openPopup ?? ((url: string) => window.open(url, '_blank', 'popup,width=600,height=700'));\n\n return useMutation<AuthorizeResult, Error, AuthorizeArgs>({\n mutationFn: async ({ providerId, toolkit, connectionId, config, label, scope }) => {\n const integration = client.getToolProvider(providerId);\n const normalizedConnectionId = connectionId?.trim();\n const { url, authId } = await integration.authorize({\n toolkit,\n ...(normalizedConnectionId ? { connectionId: normalizedConnectionId } : {}),\n ...(config ? { config } : {}),\n ...(label !== undefined ? { label } : {}),\n ...(scope ? { scope } : {}),\n });\n\n const popup = openPopup(url);\n if (!popup) {\n throw new Error('Popup blocked. Please allow popups for this site.');\n }\n\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n await new Promise(resolve => setTimeout(resolve, pollIntervalMs));\n const { status } = await integration.getAuthStatus(authId);\n if (status === 'completed' || status === 'failed') {\n try {\n popup.close();\n } catch {\n // Cross-origin popups may refuse close(); ignore.\n }\n return { status, connectionId: authId };\n }\n }\n\n try {\n popup.close();\n } catch {\n // ignore\n }\n throw new Error('Authorization timed out');\n },\n ...options.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 interface DisconnectConnectionArgs {\n providerId: string;\n connectionId: string;\n /**\n * When `true`, the server skips the usage check and revokes the\n * connection at the provider before deleting the local row.\n */\n force?: boolean;\n}\n\n/**\n * Calls the provider-side revoke (best-effort) and drops the local\n * `tool_integration_connections` row. Server enforces the soft-vs-force rule.\n */\ntype DisconnectConnectionResponse = Awaited<\n ReturnType<ReturnType<MastraClient['getToolProvider']>['disconnectConnection']>\n>;\n\nexport const useDisconnectConnection = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<DisconnectConnectionResponse, DisconnectConnectionArgs> } = {}) => {\n const client = useMastraClient();\n const qc = useQueryClient();\n\n return useMutation({\n mutationFn: async ({ providerId, connectionId, force }: DisconnectConnectionArgs) => {\n const integration = client.getToolProvider(providerId);\n return integration.disconnectConnection(connectionId, force ? { force } : undefined);\n },\n onSuccess: (_data, vars) => {\n void qc.invalidateQueries({ queryKey: ['tool-integration-connections', vars.providerId] });\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';\nimport { useMastraClient } from '../../mastra-client-context';\nimport { isUnauthenticatedError, useCurrentUser } from '../auth';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nexport interface UseExistingConnectionsOptions {\n /**\n * When `true`, the hook forces the server-side `authorId` filter to the\n * caller's own userId. Builder edit view passes `scopeToSelf: true` so\n * admins see only their own connections, never other authors' rows.\n *\n * Non-admin callers see the same result either way — the server already\n * scopes to the caller's bucket — but the explicit filter keeps caches\n * consistent and prevents admin cross-author leakage in the picker.\n */\n scopeToSelf?: boolean;\n}\n\ntype ConnectionsResponse = Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listConnections']>>;\n\n/**\n * Lists existing provider connections for the caller, scoped to a tool\n * service. Powers the \"use existing connection\" path in the picker so\n * authors can pin previously-authorized accounts without re-running OAuth.\n *\n * The connection owner is resolved server-side from the request's auth\n * context. Admin callers receive cross-author rows by default; pass\n * `scopeToSelf: true` to narrow the response to the caller's own bucket\n * (used by the Builder edit view).\n */\nexport const useExistingConnections = <TData = ConnectionsResponse>({\n providerId,\n toolkit,\n scopeToSelf = false,\n queryOptions,\n}: UseExistingConnectionsOptions & {\n providerId: string | null | undefined;\n toolkit: string | null | undefined;\n queryOptions?: MastraQueryOptions<ConnectionsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n const currentUserQuery = useCurrentUser();\n const callerAuthorId = currentUserQuery.data?.id;\n\n const callerReady = !scopeToSelf || currentUserQuery.isSuccess || isUnauthenticatedError(currentUserQuery.error);\n\n const enabled = !!providerId && !!toolkit && callerReady;\n\n return useQuery({\n queryKey: scopeToSelf\n ? ['tool-integration-connections', providerId, toolkit, callerAuthorId]\n : ['tool-integration-connections', providerId, toolkit],\n queryFn: () =>\n client.getToolProvider(providerId!).listConnections({\n toolkit: toolkit!,\n ...(scopeToSelf && callerAuthorId ? { authorId: callerAuthorId } : {}),\n }),\n enabled,\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 ProviderToolsResponse = Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listTools']>>;\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useProviderTools = <TData = ProviderToolsResponse>({\n providerId,\n params,\n queryOptions,\n}: {\n providerId: string | null;\n params?: { toolkit?: string; search?: string };\n queryOptions?: MastraQueryOptions<ProviderToolsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['tool-provider-tools', providerId, params?.toolkit, params?.search],\n queryFn: () => client.getToolProvider(providerId!).listTools(params),\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 ToolkitsResponse = Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listToolkits']>>;\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useToolkits = <TData = ToolkitsResponse>({\n providerId,\n queryOptions,\n}: {\n providerId: string | null;\n queryOptions?: MastraQueryOptions<ToolkitsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['tool-provider-toolkits', providerId],\n queryFn: () => client.getToolProvider(providerId!).listToolkits(),\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 interface UpdateConnectionArgs {\n providerId: string;\n connectionId: string;\n /**\n * New display label. Pass `null` (or an empty string) to clear the label.\n */\n label: string | null;\n}\n\n/**\n * Renames a `tool_provider_connections` row in place. Server enforces\n * ownership (owner / admin / shared scope). On success, invalidates both\n * the per-toolkit and the fan-out connection lists so the picker re-fetches.\n */\ntype UpdateConnectionResponse = Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['updateConnection']>>;\n\nexport const useUpdateConnection = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<UpdateConnectionResponse, UpdateConnectionArgs> } = {}) => {\n const client = useMastraClient();\n const qc = useQueryClient();\n\n return useMutation({\n mutationFn: async ({ providerId, connectionId, label }: UpdateConnectionArgs) => {\n const integration = client.getToolProvider(providerId);\n return integration.updateConnection(connectionId, { label });\n },\n onSuccess: (_data, vars) => {\n void qc.invalidateQueries({ queryKey: ['tool-integration-connections', vars.providerId] });\n void qc.invalidateQueries({ queryKey: ['tool-integration-connections-all', vars.providerId] });\n },\n ...queryOptions,\n });\n};\n"],"mappings":";;;;;;AAQA,MAAa,oBAAmD,EAC9D,iBACuE,CAAC,MAAoC;CAC5G,MAAM,SAASA,8BAAAA,gBAAgB;CAE/B,QAAA,GAAA,sBAAA,SAAA,CAAgB;EACd,UAAU,CAAC,gBAAgB;EAC3B,eAAe,OAAO,kBAAkB;EACxC,GAAG;CACL,CAAC;AACH;AAWA,MAAa,0BAA0B,EACrC,iBAC4D,CAAC,MAAM;CACnE,MAAM,SAASA,8BAAAA,gBAAgB;CAC/B,MAAM,EAAE,MAAM,eAAe,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CAAoC,KAAK,UAAU,EAAE,CAAC;EAC/F;EACA,GAAG;CACL,CAAC;AACH"}
1
+ {"version":3,"file":"index.cjs","names":["useMastraClient","useQuery","useMastraClient","useMemo","useCurrentUser","isUnauthenticatedError","useQueries","useCallback","useMastraClient","useMemo","useQueries","useMastraClient","useMutation","useMastraClient","useQueryClient","useMutation","useMastraClient","useCurrentUser","isUnauthenticatedError","useQuery","useMastraClient","useQuery","useMastraClient","useQuery","useMastraClient","useQueryClient","useMutation"],"sources":["../../../src/hooks/tool-providers/use-tool-providers.ts","../../../src/hooks/tool-providers/use-all-connections.ts","../../../src/hooks/tool-providers/use-all-provider-tools.ts","../../../src/hooks/tool-providers/use-authorize.ts","../../../src/hooks/tool-providers/use-disconnect-connection.ts","../../../src/hooks/tool-providers/use-existing-connections.ts","../../../src/hooks/tool-providers/use-provider-tools.ts","../../../src/hooks/tool-providers/use-toolkits.ts","../../../src/hooks/tool-providers/use-update-connection.ts"],"sourcesContent":["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 ToolProvidersResponse = Awaited<ReturnType<MastraClient['listToolProviders']>>;\n\nexport const useToolProviders = <TData = ToolProvidersResponse>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<ToolProvidersResponse, TData> } = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['tool-providers'],\n queryFn: () => client.listToolProviders(),\n ...queryOptions,\n });\n};\n\nexport interface IntegrationTool {\n slug: string;\n name: string;\n description?: string;\n toolkit?: string;\n providerId: string;\n providerName: string;\n}\n\nexport const useAllIntegrationTools = ({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<IntegrationTool[]> } = {}) => {\n const client = useMastraClient();\n const { data: providersData, isLoading: isLoadingProviders } = useToolProviders();\n const providers = providersData?.providers ?? [];\n\n const toolsQuery = useQuery({\n queryKey: ['integration-tools-all', providers.map(p => p.id)],\n queryFn: async () => {\n const results: IntegrationTool[] = [];\n\n for (const provider of providers) {\n const response = await client.getToolProvider(provider.id).listTools();\n for (const tool of response.data) {\n results.push({\n ...tool,\n providerId: provider.id,\n providerName: provider.name,\n });\n }\n }\n\n return results;\n },\n enabled: providers.length > 0,\n ...queryOptions,\n });\n\n return {\n data: toolsQuery.data ?? [],\n isLoading: isLoadingProviders || toolsQuery.isLoading,\n };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { useQueries } from '@tanstack/react-query';\nimport { useCallback, useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport { isUnauthenticatedError, useCurrentUser } from '../auth';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { useToolProviders } from './use-tool-providers';\n\n/**\n * Stale time long enough to avoid refetching on every picker re-render but\n * short enough that an OAuth completion in a sibling tab is reflected\n * promptly (React Query also re-fetches on window focus by default).\n */\nconst STALE_TIME_MS = 30_000;\n\nexport interface UseAllConnectionsOptions {\n /**\n * When `true`, the hook forces the server-side `authorId` filter to the\n * caller's own userId. Builder edit view passes `scopeToSelf: true` so\n * admins see only their own connections, never other authors' rows.\n *\n * Non-admin callers see the same result either way — the server already\n * scopes to the caller's bucket — but the explicit filter keeps caches\n * consistent and prevents admin cross-author leakage.\n */\n scopeToSelf?: boolean;\n /** TanStack overrides applied to every fanned-out query, spread last. `select` must keep the default shape. */\n queryOptions?: {\n toolkits?: MastraQueryOptions<Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listToolkits']>>>;\n connections?: MastraQueryOptions<\n Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listConnections']>>\n >;\n };\n}\n\n/**\n * Fans out across every registered ToolProvider and every toolkit it\n * exposes to determine whether the caller has an existing connection for a\n * given `(providerId, toolkit)` pair.\n *\n * Used by the Builder tool picker to gate integration tool rows: if the\n * pair has no connection, the card cannot be selected and surfaces an\n * inline \"Connect\" button instead.\n *\n * Distinct from `useExistingConnections` (per-pair, used by `/integrations`)\n * to keep their query caches independent.\n */\nexport const useAllConnections = ({ scopeToSelf = false, queryOptions }: UseAllConnectionsOptions = {}) => {\n const client = useMastraClient();\n const providersQuery = useToolProviders();\n const providers = useMemo(() => providersQuery.data?.providers ?? [], [providersQuery.data?.providers]);\n\n const currentUserQuery = useCurrentUser();\n const callerAuthorId = currentUserQuery.data?.id;\n const callerReady = !scopeToSelf || currentUserQuery.isSuccess || isUnauthenticatedError(currentUserQuery.error);\n\n // 1. For every provider, list its toolkits.\n const toolkitsQueries = useQueries({\n queries: providers.map(provider => ({\n queryKey: ['tool-integration-services', provider.id],\n queryFn: () => client.getToolProvider(provider.id).listToolkits(),\n ...queryOptions?.toolkits,\n })),\n });\n\n // 2. Flatten to (providerId, toolkit) pairs.\n const pairs = useMemo(() => {\n const out: Array<{ providerId: string; toolkit: string }> = [];\n providers.forEach((provider, idx) => {\n const toolkits = toolkitsQueries[idx]?.data?.data ?? [];\n for (const toolkit of toolkits) {\n out.push({ providerId: provider.id, toolkit: toolkit.slug });\n }\n });\n return out;\n }, [providers, toolkitsQueries]);\n\n // 3. One listConnections call per pair. Include `authorId` in queryKey when\n // self-scoped so the cache is distinct from any unscoped admin reads.\n const connectionsQueries = useQueries({\n queries: pairs.map(pair => ({\n queryKey: scopeToSelf\n ? ['tool-integration-connections-all', pair.providerId, pair.toolkit, callerAuthorId]\n : ['tool-integration-connections-all', pair.providerId, pair.toolkit],\n queryFn: () =>\n client.getToolProvider(pair.providerId).listConnections({\n toolkit: pair.toolkit,\n ...(scopeToSelf && callerAuthorId ? { authorId: callerAuthorId } : {}),\n }),\n enabled: callerReady,\n staleTime: STALE_TIME_MS,\n ...queryOptions?.connections,\n })),\n });\n\n const isLoading =\n providersQuery.isLoading ||\n (scopeToSelf && currentUserQuery.isLoading) ||\n toolkitsQueries.some(q => q.isLoading) ||\n connectionsQueries.some(q => q.isLoading);\n\n // Build a per-pair list of connection summaries so callers can both gate\n // (\"does this row have any connection?\") and auto-pin (\"if exactly one\n // exists, write it into the form on toggle-on\").\n const connectionsByKey = useMemo(() => {\n const map = new Map<string, Array<{ connectionId: string; label?: string | null; status?: string }>>();\n pairs.forEach((pair, idx) => {\n const items = connectionsQueries[idx]?.data?.items ?? [];\n map.set(`${pair.providerId}:${pair.toolkit}`, items);\n });\n return map;\n }, [pairs, connectionsQueries]);\n\n // A toolkit \"has a connection\" only when at least one connection is active.\n // Pending/failed rows don't count — this keeps the card hint in sync with the\n // toolkit row control, which also treats only active connections as usable.\n const hasConnection = useCallback(\n (providerId: string, toolkit: string) =>\n (connectionsByKey.get(`${providerId}:${toolkit}`) ?? []).some(connection => connection.status === 'active'),\n [connectionsByKey],\n );\n\n const getConnections = useCallback(\n (providerId: string, toolkit: string) => connectionsByKey.get(`${providerId}:${toolkit}`) ?? [],\n [connectionsByKey],\n );\n\n return { hasConnection, getConnections, isLoading };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { useQueries } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { useToolProviders } from './use-tool-providers';\n\nexport interface AvailableIntegrationTool {\n providerId: string;\n slug: string;\n toolkit: string;\n name?: string;\n description?: string;\n}\n\n/**\n * Upper bound for a single Composio-style `listTools` call. Composio's SDK has\n * no cursor — only `limit` — so we ask for a large page and fan out per\n * `toolkit` to avoid being truncated when many toolkits are allowlisted.\n */\nconst PER_SERVICE_LIMIT = 500;\n\n/**\n * Returns every tool surfaced by every registered ToolProvider, scoped to\n * the provider's `allowedToolkits`/`allowedTools` filter (enforced\n * server-side). Used to render the full available-tools list inline.\n */\nexport const useAllProviderTools = ({\n queryOptions,\n}: {\n /** TanStack overrides applied to every fanned-out query, spread last. `select` must keep the default shape. */\n queryOptions?: {\n toolkits?: MastraQueryOptions<Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listToolkits']>>>;\n tools?: MastraQueryOptions<Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listTools']>>>;\n };\n} = {}) => {\n const client = useMastraClient();\n const integrationsQuery = useToolProviders();\n const integrations = useMemo(() => integrationsQuery.data?.providers ?? [], [integrationsQuery.data?.providers]);\n\n // 1. For every integration, fetch its tool services.\n const serviceQueries = useQueries({\n queries: integrations.map(integration => ({\n queryKey: ['tool-integration-services', integration.id],\n queryFn: () => client.getToolProvider(integration.id).listToolkits(),\n ...queryOptions?.toolkits,\n })),\n });\n\n // 2. Flatten to (providerId, serviceSlug) pairs.\n const servicePairs = useMemo(() => {\n const pairs: Array<{ providerId: string; toolkit: string }> = [];\n integrations.forEach((integration, idx) => {\n const services = serviceQueries[idx]?.data?.data ?? [];\n for (const service of services) {\n pairs.push({ providerId: integration.id, toolkit: service.slug });\n }\n });\n return pairs;\n }, [integrations, serviceQueries]);\n\n // 3. Fan out one tools query per (integration, service).\n const toolsQueries = useQueries({\n queries: servicePairs.map(pair => ({\n queryKey: ['tool-integration-tools-all', pair.providerId, pair.toolkit],\n queryFn: () =>\n client.getToolProvider(pair.providerId).listTools({ toolkit: pair.toolkit, perPage: PER_SERVICE_LIMIT }),\n ...queryOptions?.tools,\n })),\n });\n\n const isLoading =\n integrationsQuery.isLoading || serviceQueries.some(q => q.isLoading) || toolsQueries.some(q => q.isLoading);\n\n const tools = useMemo<AvailableIntegrationTool[]>(() => {\n const out: AvailableIntegrationTool[] = [];\n servicePairs.forEach((pair, idx) => {\n const items = toolsQueries[idx]?.data?.data ?? [];\n for (const item of items) {\n const toolkit = (item as { toolkit?: string }).toolkit ?? pair.toolkit;\n out.push({\n providerId: pair.providerId,\n slug: item.slug,\n toolkit,\n name: (item as { name?: string }).name,\n description: (item as { description?: string }).description,\n });\n }\n });\n return out;\n }, [servicePairs, toolsQueries]);\n\n return { tools, isLoading };\n};\n","import { useMutation } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nexport interface AuthorizeArgs {\n providerId: string;\n toolkit: string;\n /**\n * Existing bucket id when re-authorizing; omit for a brand-new connection.\n * Semantics are provider-opaque; for Composio v1 this is the internal user\n * bucket the new connected account should be created under.\n */\n connectionId?: string;\n /**\n * Provider-specific connection fields collected from the picker (e.g.\n * Confluence subdomain). Forwarded to the server's `authorize` body.\n */\n config?: Record<string, unknown>;\n /**\n * Optional human label to persist on the resulting `tool_integration_connections` row.\n */\n label?: string | null;\n /**\n * Ownership scope of the OAuth bucket. `'per-author'` (default) buckets\n * under the caller's authorId.\n */\n scope?: 'per-author' | 'shared' | 'caller-supplied';\n}\n\nexport interface AuthorizeResult {\n status: 'completed' | 'failed';\n /**\n * The `authId` returned by `authorize`, exposed as `connectionId` because\n * for the v1 Composio adapter it is the `connected_account.id` that the\n * caller persists as `Connection.connectionId`.\n */\n connectionId: string;\n}\n\nconst DEFAULT_POLL_INTERVAL_MS = 2000;\nconst DEFAULT_TIMEOUT_MS = 5 * 60_000;\n\nexport interface UseAuthorizeOptions {\n pollIntervalMs?: number;\n timeoutMs?: number;\n openPopup?: (url: string) => Window | null;\n queryOptions?: MastraMutationOptions<AuthorizeResult, AuthorizeArgs>;\n}\n\n/**\n * Drives the OAuth popup + polling loop for a `ToolProvider` provider.\n */\nexport const useAuthorize = (options: UseAuthorizeOptions = {}) => {\n const client = useMastraClient();\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const openPopup = options.openPopup ?? ((url: string) => window.open(url, '_blank', 'popup,width=600,height=700'));\n\n return useMutation<AuthorizeResult, Error, AuthorizeArgs>({\n mutationFn: async ({ providerId, toolkit, connectionId, config, label, scope }) => {\n const integration = client.getToolProvider(providerId);\n const normalizedConnectionId = connectionId?.trim();\n const { url, authId } = await integration.authorize({\n toolkit,\n ...(normalizedConnectionId ? { connectionId: normalizedConnectionId } : {}),\n ...(config ? { config } : {}),\n ...(label !== undefined ? { label } : {}),\n ...(scope ? { scope } : {}),\n });\n\n const popup = openPopup(url);\n if (!popup) {\n throw new Error('Popup blocked. Please allow popups for this site.');\n }\n\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n await new Promise(resolve => setTimeout(resolve, pollIntervalMs));\n const { status } = await integration.getAuthStatus(authId);\n if (status === 'completed' || status === 'failed') {\n try {\n popup.close();\n } catch {\n // Cross-origin popups may refuse close(); ignore.\n }\n return { status, connectionId: authId };\n }\n }\n\n try {\n popup.close();\n } catch {\n // ignore\n }\n throw new Error('Authorization timed out');\n },\n ...options.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 interface DisconnectConnectionArgs {\n providerId: string;\n connectionId: string;\n /**\n * When `true`, the server skips the usage check and revokes the\n * connection at the provider before deleting the local row.\n */\n force?: boolean;\n}\n\n/**\n * Calls the provider-side revoke (best-effort) and drops the local\n * `tool_integration_connections` row. Server enforces the soft-vs-force rule.\n */\ntype DisconnectConnectionResponse = Awaited<\n ReturnType<ReturnType<MastraClient['getToolProvider']>['disconnectConnection']>\n>;\n\nexport const useDisconnectConnection = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<DisconnectConnectionResponse, DisconnectConnectionArgs> } = {}) => {\n const client = useMastraClient();\n const qc = useQueryClient();\n\n return useMutation({\n mutationFn: async ({ providerId, connectionId, force }: DisconnectConnectionArgs) => {\n const integration = client.getToolProvider(providerId);\n return integration.disconnectConnection(connectionId, force ? { force } : undefined);\n },\n onSuccess: (_data, vars) => {\n void qc.invalidateQueries({ queryKey: ['tool-integration-connections', vars.providerId] });\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';\nimport { useMastraClient } from '../../mastra-client-context';\nimport { isUnauthenticatedError, useCurrentUser } from '../auth';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nexport interface UseExistingConnectionsOptions {\n /**\n * When `true`, the hook forces the server-side `authorId` filter to the\n * caller's own userId. Builder edit view passes `scopeToSelf: true` so\n * admins see only their own connections, never other authors' rows.\n *\n * Non-admin callers see the same result either way — the server already\n * scopes to the caller's bucket — but the explicit filter keeps caches\n * consistent and prevents admin cross-author leakage in the picker.\n */\n scopeToSelf?: boolean;\n}\n\ntype ConnectionsResponse = Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listConnections']>>;\n\n/**\n * Lists existing provider connections for the caller, scoped to a tool\n * service. Powers the \"use existing connection\" path in the picker so\n * authors can pin previously-authorized accounts without re-running OAuth.\n *\n * The connection owner is resolved server-side from the request's auth\n * context. Admin callers receive cross-author rows by default; pass\n * `scopeToSelf: true` to narrow the response to the caller's own bucket\n * (used by the Builder edit view).\n */\nexport const useExistingConnections = <TData = ConnectionsResponse>({\n providerId,\n toolkit,\n scopeToSelf = false,\n queryOptions,\n}: UseExistingConnectionsOptions & {\n providerId: string | null | undefined;\n toolkit: string | null | undefined;\n queryOptions?: MastraQueryOptions<ConnectionsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n const currentUserQuery = useCurrentUser();\n const callerAuthorId = currentUserQuery.data?.id;\n\n const callerReady = !scopeToSelf || currentUserQuery.isSuccess || isUnauthenticatedError(currentUserQuery.error);\n\n const enabled = !!providerId && !!toolkit && callerReady;\n\n return useQuery({\n queryKey: scopeToSelf\n ? ['tool-integration-connections', providerId, toolkit, callerAuthorId]\n : ['tool-integration-connections', providerId, toolkit],\n queryFn: () =>\n client.getToolProvider(providerId!).listConnections({\n toolkit: toolkit!,\n ...(scopeToSelf && callerAuthorId ? { authorId: callerAuthorId } : {}),\n }),\n enabled,\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 ProviderToolsResponse = Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listTools']>>;\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useProviderTools = <TData = ProviderToolsResponse>({\n providerId,\n params,\n queryOptions,\n}: {\n providerId: string | null;\n params?: { toolkit?: string; search?: string };\n queryOptions?: MastraQueryOptions<ProviderToolsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['tool-provider-tools', providerId, params?.toolkit, params?.search],\n queryFn: () => client.getToolProvider(providerId!).listTools(params),\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 ToolkitsResponse = Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listToolkits']>>;\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useToolkits = <TData = ToolkitsResponse>({\n providerId,\n queryOptions,\n}: {\n providerId: string | null;\n queryOptions?: MastraQueryOptions<ToolkitsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['tool-provider-toolkits', providerId],\n queryFn: () => client.getToolProvider(providerId!).listToolkits(),\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 interface UpdateConnectionArgs {\n providerId: string;\n connectionId: string;\n /**\n * New display label. Pass `null` (or an empty string) to clear the label.\n */\n label: string | null;\n}\n\n/**\n * Renames a `tool_provider_connections` row in place. Server enforces\n * ownership (owner / admin / shared scope). On success, invalidates both\n * the per-toolkit and the fan-out connection lists so the picker re-fetches.\n */\ntype UpdateConnectionResponse = Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['updateConnection']>>;\n\nexport const useUpdateConnection = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<UpdateConnectionResponse, UpdateConnectionArgs> } = {}) => {\n const client = useMastraClient();\n const qc = useQueryClient();\n\n return useMutation({\n mutationFn: async ({ providerId, connectionId, label }: UpdateConnectionArgs) => {\n const integration = client.getToolProvider(providerId);\n return integration.updateConnection(connectionId, { label });\n },\n onSuccess: (_data, vars) => {\n void qc.invalidateQueries({ queryKey: ['tool-integration-connections', vars.providerId] });\n void qc.invalidateQueries({ queryKey: ['tool-integration-connections-all', vars.providerId] });\n },\n ...queryOptions,\n });\n};\n"],"mappings":";;;;;;AAQA,MAAa,oBAAmD,EAC9D,iBACuE,CAAC,MAAoC;CAC5G,MAAM,SAASA,8BAAAA,gBAAgB;CAE/B,QAAA,GAAOC,sBAAAA,SAAAA,CAAS;EACd,UAAU,CAAC,gBAAgB;EAC3B,eAAe,OAAO,kBAAkB;EACxC,GAAG;CACL,CAAC;AACH;AAWA,MAAa,0BAA0B,EACrC,iBAC4D,CAAC,MAAM;CACnE,MAAM,SAASD,8BAAAA,gBAAgB;CAC/B,MAAM,EAAE,MAAM,eAAe,WAAW,uBAAuB,iBAAiB;CAChF,MAAM,YAAY,eAAe,aAAa,CAAC;CAE/C,MAAM,cAAA,GAAaC,sBAAAA,SAAAA,CAAS;EAC1B,UAAU,CAAC,yBAAyB,UAAU,KAAI,MAAK,EAAE,EAAE,CAAC;EAC5D,SAAS,YAAY;GACnB,MAAM,UAA6B,CAAC;GAEpC,KAAK,MAAM,YAAY,WAAW;IAChC,MAAM,WAAW,MAAM,OAAO,gBAAgB,SAAS,EAAE,CAAC,CAAC,UAAU;IACrE,KAAK,MA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AC;AACH;;;;;;ACnDA,MAAa,oBAAmD,EAC9D,YACA,QACA,mBAKkC;CAClC,MAAM,SAASC,8BAAAA,gBAAgB;CAE/B,QAAA,GAAOC,sBAAAA,SAAAA,CAAS;EACd,UAAU;GAAC;GAAuB;GAAY,QAAQ;GAAS,QAAQ;EAAM;EAC7E,eAAe,OAAO,gBAAgB,UAAW,CAAC,CAAC,UAAU,MAAM;EACnE,GAAG;CACL,CAAC;AACH;;;;;;AChBA,MAAa,eAAyC,EACpD,YACA,mBAIkC;CAClC,MAAM,SAASC,8BAAAA,gBAAgB;CAE/B,QAAA,GAAOC,sBAAAA,SAAAA,CAAS;EACd,UAAU,CAAC,0BAA0B,UAAU;EAC/C,eAAe,OAAO,gBAAgB,UAAW,CAAC,CAAC,aAAa;EAChE,GAAG;CACL,CAAC;AACH;;;ACJA,MAAa,uBAAuB,EAClC,iBAC4F,CAAC,MAAM;CACnG,MAAM,SAASC,8BAAAA,gBAAgB;CAC/B,MAAM,MAAA,GAAKC,sBAAAA,eAAAA,CAAe;CAE1B,QAAA,GAAOC,sBAAAA,YAAAA,CAAY;EACjB,YAAY,OAAO,EAAE,YAAY,cAAc,YAAkC;GAE/E,OADoB,OAAO,gBAAgB,UAC1B,CAAC,CAAC,iBAAiB,cAAc,EAAE,MAAM,CAAC;EAC7D;EACA,YAAY,OAAO,SAAS;GAC1B,GAAQ,kBAAkB,EAAE,UAAU,CAAC,gCAAgC,KAAK,UAAU,EAAE,CAAC;GACzF,GAAQ,kBAAkB,EAAE,UAAU,CAAC,oCAAoC,KAAK,UAAU,EAAE,CAAC;EAC/F;EACA,GAAG;CACL,CAAC;AACH"}
@@ -184,7 +184,7 @@ const useAllProviderTools = ({ queryOptions } = {}) => {
184
184
  //#endregion
185
185
  //#region src/hooks/tool-providers/use-authorize.ts
186
186
  const DEFAULT_POLL_INTERVAL_MS = 2e3;
187
- const DEFAULT_TIMEOUT_MS = 5 * 6e4;
187
+ const DEFAULT_TIMEOUT_MS = 3e5;
188
188
  /**
189
189
  * Drives the OAuth popup + polling loop for a `ToolProvider` provider.
190
190
  */
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/hooks/tool-providers/use-tool-providers.ts","../../../src/hooks/tool-providers/use-all-connections.ts","../../../src/hooks/tool-providers/use-all-provider-tools.ts","../../../src/hooks/tool-providers/use-authorize.ts","../../../src/hooks/tool-providers/use-disconnect-connection.ts","../../../src/hooks/tool-providers/use-existing-connections.ts","../../../src/hooks/tool-providers/use-provider-tools.ts","../../../src/hooks/tool-providers/use-toolkits.ts","../../../src/hooks/tool-providers/use-update-connection.ts"],"sourcesContent":["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 ToolProvidersResponse = Awaited<ReturnType<MastraClient['listToolProviders']>>;\n\nexport const useToolProviders = <TData = ToolProvidersResponse>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<ToolProvidersResponse, TData> } = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['tool-providers'],\n queryFn: () => client.listToolProviders(),\n ...queryOptions,\n });\n};\n\nexport interface IntegrationTool {\n slug: string;\n name: string;\n description?: string;\n toolkit?: string;\n providerId: string;\n providerName: string;\n}\n\nexport const useAllIntegrationTools = ({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<IntegrationTool[]> } = {}) => {\n const client = useMastraClient();\n const { data: providersData, isLoading: isLoadingProviders } = useToolProviders();\n const providers = providersData?.providers ?? [];\n\n const toolsQuery = useQuery({\n queryKey: ['integration-tools-all', providers.map(p => p.id)],\n queryFn: async () => {\n const results: IntegrationTool[] = [];\n\n for (const provider of providers) {\n const response = await client.getToolProvider(provider.id).listTools();\n for (const tool of response.data) {\n results.push({\n ...tool,\n providerId: provider.id,\n providerName: provider.name,\n });\n }\n }\n\n return results;\n },\n enabled: providers.length > 0,\n ...queryOptions,\n });\n\n return {\n data: toolsQuery.data ?? [],\n isLoading: isLoadingProviders || toolsQuery.isLoading,\n };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { useQueries } from '@tanstack/react-query';\nimport { useCallback, useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport { isUnauthenticatedError, useCurrentUser } from '../auth';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { useToolProviders } from './use-tool-providers';\n\n/**\n * Stale time long enough to avoid refetching on every picker re-render but\n * short enough that an OAuth completion in a sibling tab is reflected\n * promptly (React Query also re-fetches on window focus by default).\n */\nconst STALE_TIME_MS = 30_000;\n\nexport interface UseAllConnectionsOptions {\n /**\n * When `true`, the hook forces the server-side `authorId` filter to the\n * caller's own userId. Builder edit view passes `scopeToSelf: true` so\n * admins see only their own connections, never other authors' rows.\n *\n * Non-admin callers see the same result either way — the server already\n * scopes to the caller's bucket — but the explicit filter keeps caches\n * consistent and prevents admin cross-author leakage.\n */\n scopeToSelf?: boolean;\n /** TanStack overrides applied to every fanned-out query, spread last. `select` must keep the default shape. */\n queryOptions?: {\n toolkits?: MastraQueryOptions<Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listToolkits']>>>;\n connections?: MastraQueryOptions<\n Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listConnections']>>\n >;\n };\n}\n\n/**\n * Fans out across every registered ToolProvider and every toolkit it\n * exposes to determine whether the caller has an existing connection for a\n * given `(providerId, toolkit)` pair.\n *\n * Used by the Builder tool picker to gate integration tool rows: if the\n * pair has no connection, the card cannot be selected and surfaces an\n * inline \"Connect\" button instead.\n *\n * Distinct from `useExistingConnections` (per-pair, used by `/integrations`)\n * to keep their query caches independent.\n */\nexport const useAllConnections = ({ scopeToSelf = false, queryOptions }: UseAllConnectionsOptions = {}) => {\n const client = useMastraClient();\n const providersQuery = useToolProviders();\n const providers = useMemo(() => providersQuery.data?.providers ?? [], [providersQuery.data?.providers]);\n\n const currentUserQuery = useCurrentUser();\n const callerAuthorId = currentUserQuery.data?.id;\n const callerReady = !scopeToSelf || currentUserQuery.isSuccess || isUnauthenticatedError(currentUserQuery.error);\n\n // 1. For every provider, list its toolkits.\n const toolkitsQueries = useQueries({\n queries: providers.map(provider => ({\n queryKey: ['tool-integration-services', provider.id],\n queryFn: () => client.getToolProvider(provider.id).listToolkits(),\n ...queryOptions?.toolkits,\n })),\n });\n\n // 2. Flatten to (providerId, toolkit) pairs.\n const pairs = useMemo(() => {\n const out: Array<{ providerId: string; toolkit: string }> = [];\n providers.forEach((provider, idx) => {\n const toolkits = toolkitsQueries[idx]?.data?.data ?? [];\n for (const toolkit of toolkits) {\n out.push({ providerId: provider.id, toolkit: toolkit.slug });\n }\n });\n return out;\n }, [providers, toolkitsQueries]);\n\n // 3. One listConnections call per pair. Include `authorId` in queryKey when\n // self-scoped so the cache is distinct from any unscoped admin reads.\n const connectionsQueries = useQueries({\n queries: pairs.map(pair => ({\n queryKey: scopeToSelf\n ? ['tool-integration-connections-all', pair.providerId, pair.toolkit, callerAuthorId]\n : ['tool-integration-connections-all', pair.providerId, pair.toolkit],\n queryFn: () =>\n client.getToolProvider(pair.providerId).listConnections({\n toolkit: pair.toolkit,\n ...(scopeToSelf && callerAuthorId ? { authorId: callerAuthorId } : {}),\n }),\n enabled: callerReady,\n staleTime: STALE_TIME_MS,\n ...queryOptions?.connections,\n })),\n });\n\n const isLoading =\n providersQuery.isLoading ||\n (scopeToSelf && currentUserQuery.isLoading) ||\n toolkitsQueries.some(q => q.isLoading) ||\n connectionsQueries.some(q => q.isLoading);\n\n // Build a per-pair list of connection summaries so callers can both gate\n // (\"does this row have any connection?\") and auto-pin (\"if exactly one\n // exists, write it into the form on toggle-on\").\n const connectionsByKey = useMemo(() => {\n const map = new Map<string, Array<{ connectionId: string; label?: string | null; status?: string }>>();\n pairs.forEach((pair, idx) => {\n const items = connectionsQueries[idx]?.data?.items ?? [];\n map.set(`${pair.providerId}:${pair.toolkit}`, items);\n });\n return map;\n }, [pairs, connectionsQueries]);\n\n // A toolkit \"has a connection\" only when at least one connection is active.\n // Pending/failed rows don't count — this keeps the card hint in sync with the\n // toolkit row control, which also treats only active connections as usable.\n const hasConnection = useCallback(\n (providerId: string, toolkit: string) =>\n (connectionsByKey.get(`${providerId}:${toolkit}`) ?? []).some(connection => connection.status === 'active'),\n [connectionsByKey],\n );\n\n const getConnections = useCallback(\n (providerId: string, toolkit: string) => connectionsByKey.get(`${providerId}:${toolkit}`) ?? [],\n [connectionsByKey],\n );\n\n return { hasConnection, getConnections, isLoading };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { useQueries } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { useToolProviders } from './use-tool-providers';\n\nexport interface AvailableIntegrationTool {\n providerId: string;\n slug: string;\n toolkit: string;\n name?: string;\n description?: string;\n}\n\n/**\n * Upper bound for a single Composio-style `listTools` call. Composio's SDK has\n * no cursor — only `limit` — so we ask for a large page and fan out per\n * `toolkit` to avoid being truncated when many toolkits are allowlisted.\n */\nconst PER_SERVICE_LIMIT = 500;\n\n/**\n * Returns every tool surfaced by every registered ToolProvider, scoped to\n * the provider's `allowedToolkits`/`allowedTools` filter (enforced\n * server-side). Used to render the full available-tools list inline.\n */\nexport const useAllProviderTools = ({\n queryOptions,\n}: {\n /** TanStack overrides applied to every fanned-out query, spread last. `select` must keep the default shape. */\n queryOptions?: {\n toolkits?: MastraQueryOptions<Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listToolkits']>>>;\n tools?: MastraQueryOptions<Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listTools']>>>;\n };\n} = {}) => {\n const client = useMastraClient();\n const integrationsQuery = useToolProviders();\n const integrations = useMemo(() => integrationsQuery.data?.providers ?? [], [integrationsQuery.data?.providers]);\n\n // 1. For every integration, fetch its tool services.\n const serviceQueries = useQueries({\n queries: integrations.map(integration => ({\n queryKey: ['tool-integration-services', integration.id],\n queryFn: () => client.getToolProvider(integration.id).listToolkits(),\n ...queryOptions?.toolkits,\n })),\n });\n\n // 2. Flatten to (providerId, serviceSlug) pairs.\n const servicePairs = useMemo(() => {\n const pairs: Array<{ providerId: string; toolkit: string }> = [];\n integrations.forEach((integration, idx) => {\n const services = serviceQueries[idx]?.data?.data ?? [];\n for (const service of services) {\n pairs.push({ providerId: integration.id, toolkit: service.slug });\n }\n });\n return pairs;\n }, [integrations, serviceQueries]);\n\n // 3. Fan out one tools query per (integration, service).\n const toolsQueries = useQueries({\n queries: servicePairs.map(pair => ({\n queryKey: ['tool-integration-tools-all', pair.providerId, pair.toolkit],\n queryFn: () =>\n client.getToolProvider(pair.providerId).listTools({ toolkit: pair.toolkit, perPage: PER_SERVICE_LIMIT }),\n ...queryOptions?.tools,\n })),\n });\n\n const isLoading =\n integrationsQuery.isLoading || serviceQueries.some(q => q.isLoading) || toolsQueries.some(q => q.isLoading);\n\n const tools = useMemo<AvailableIntegrationTool[]>(() => {\n const out: AvailableIntegrationTool[] = [];\n servicePairs.forEach((pair, idx) => {\n const items = toolsQueries[idx]?.data?.data ?? [];\n for (const item of items) {\n const toolkit = (item as { toolkit?: string }).toolkit ?? pair.toolkit;\n out.push({\n providerId: pair.providerId,\n slug: item.slug,\n toolkit,\n name: (item as { name?: string }).name,\n description: (item as { description?: string }).description,\n });\n }\n });\n return out;\n }, [servicePairs, toolsQueries]);\n\n return { tools, isLoading };\n};\n","import { useMutation } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nexport interface AuthorizeArgs {\n providerId: string;\n toolkit: string;\n /**\n * Existing bucket id when re-authorizing; omit for a brand-new connection.\n * Semantics are provider-opaque; for Composio v1 this is the internal user\n * bucket the new connected account should be created under.\n */\n connectionId?: string;\n /**\n * Provider-specific connection fields collected from the picker (e.g.\n * Confluence subdomain). Forwarded to the server's `authorize` body.\n */\n config?: Record<string, unknown>;\n /**\n * Optional human label to persist on the resulting `tool_integration_connections` row.\n */\n label?: string | null;\n /**\n * Ownership scope of the OAuth bucket. `'per-author'` (default) buckets\n * under the caller's authorId.\n */\n scope?: 'per-author' | 'shared' | 'caller-supplied';\n}\n\nexport interface AuthorizeResult {\n status: 'completed' | 'failed';\n /**\n * The `authId` returned by `authorize`, exposed as `connectionId` because\n * for the v1 Composio adapter it is the `connected_account.id` that the\n * caller persists as `Connection.connectionId`.\n */\n connectionId: string;\n}\n\nconst DEFAULT_POLL_INTERVAL_MS = 2000;\nconst DEFAULT_TIMEOUT_MS = 5 * 60_000;\n\nexport interface UseAuthorizeOptions {\n pollIntervalMs?: number;\n timeoutMs?: number;\n openPopup?: (url: string) => Window | null;\n queryOptions?: MastraMutationOptions<AuthorizeResult, AuthorizeArgs>;\n}\n\n/**\n * Drives the OAuth popup + polling loop for a `ToolProvider` provider.\n */\nexport const useAuthorize = (options: UseAuthorizeOptions = {}) => {\n const client = useMastraClient();\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const openPopup = options.openPopup ?? ((url: string) => window.open(url, '_blank', 'popup,width=600,height=700'));\n\n return useMutation<AuthorizeResult, Error, AuthorizeArgs>({\n mutationFn: async ({ providerId, toolkit, connectionId, config, label, scope }) => {\n const integration = client.getToolProvider(providerId);\n const normalizedConnectionId = connectionId?.trim();\n const { url, authId } = await integration.authorize({\n toolkit,\n ...(normalizedConnectionId ? { connectionId: normalizedConnectionId } : {}),\n ...(config ? { config } : {}),\n ...(label !== undefined ? { label } : {}),\n ...(scope ? { scope } : {}),\n });\n\n const popup = openPopup(url);\n if (!popup) {\n throw new Error('Popup blocked. Please allow popups for this site.');\n }\n\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n await new Promise(resolve => setTimeout(resolve, pollIntervalMs));\n const { status } = await integration.getAuthStatus(authId);\n if (status === 'completed' || status === 'failed') {\n try {\n popup.close();\n } catch {\n // Cross-origin popups may refuse close(); ignore.\n }\n return { status, connectionId: authId };\n }\n }\n\n try {\n popup.close();\n } catch {\n // ignore\n }\n throw new Error('Authorization timed out');\n },\n ...options.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 interface DisconnectConnectionArgs {\n providerId: string;\n connectionId: string;\n /**\n * When `true`, the server skips the usage check and revokes the\n * connection at the provider before deleting the local row.\n */\n force?: boolean;\n}\n\n/**\n * Calls the provider-side revoke (best-effort) and drops the local\n * `tool_integration_connections` row. Server enforces the soft-vs-force rule.\n */\ntype DisconnectConnectionResponse = Awaited<\n ReturnType<ReturnType<MastraClient['getToolProvider']>['disconnectConnection']>\n>;\n\nexport const useDisconnectConnection = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<DisconnectConnectionResponse, DisconnectConnectionArgs> } = {}) => {\n const client = useMastraClient();\n const qc = useQueryClient();\n\n return useMutation({\n mutationFn: async ({ providerId, connectionId, force }: DisconnectConnectionArgs) => {\n const integration = client.getToolProvider(providerId);\n return integration.disconnectConnection(connectionId, force ? { force } : undefined);\n },\n onSuccess: (_data, vars) => {\n void qc.invalidateQueries({ queryKey: ['tool-integration-connections', vars.providerId] });\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';\nimport { useMastraClient } from '../../mastra-client-context';\nimport { isUnauthenticatedError, useCurrentUser } from '../auth';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nexport interface UseExistingConnectionsOptions {\n /**\n * When `true`, the hook forces the server-side `authorId` filter to the\n * caller's own userId. Builder edit view passes `scopeToSelf: true` so\n * admins see only their own connections, never other authors' rows.\n *\n * Non-admin callers see the same result either way — the server already\n * scopes to the caller's bucket — but the explicit filter keeps caches\n * consistent and prevents admin cross-author leakage in the picker.\n */\n scopeToSelf?: boolean;\n}\n\ntype ConnectionsResponse = Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listConnections']>>;\n\n/**\n * Lists existing provider connections for the caller, scoped to a tool\n * service. Powers the \"use existing connection\" path in the picker so\n * authors can pin previously-authorized accounts without re-running OAuth.\n *\n * The connection owner is resolved server-side from the request's auth\n * context. Admin callers receive cross-author rows by default; pass\n * `scopeToSelf: true` to narrow the response to the caller's own bucket\n * (used by the Builder edit view).\n */\nexport const useExistingConnections = <TData = ConnectionsResponse>({\n providerId,\n toolkit,\n scopeToSelf = false,\n queryOptions,\n}: UseExistingConnectionsOptions & {\n providerId: string | null | undefined;\n toolkit: string | null | undefined;\n queryOptions?: MastraQueryOptions<ConnectionsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n const currentUserQuery = useCurrentUser();\n const callerAuthorId = currentUserQuery.data?.id;\n\n const callerReady = !scopeToSelf || currentUserQuery.isSuccess || isUnauthenticatedError(currentUserQuery.error);\n\n const enabled = !!providerId && !!toolkit && callerReady;\n\n return useQuery({\n queryKey: scopeToSelf\n ? ['tool-integration-connections', providerId, toolkit, callerAuthorId]\n : ['tool-integration-connections', providerId, toolkit],\n queryFn: () =>\n client.getToolProvider(providerId!).listConnections({\n toolkit: toolkit!,\n ...(scopeToSelf && callerAuthorId ? { authorId: callerAuthorId } : {}),\n }),\n enabled,\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 ProviderToolsResponse = Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listTools']>>;\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useProviderTools = <TData = ProviderToolsResponse>({\n providerId,\n params,\n queryOptions,\n}: {\n providerId: string | null;\n params?: { toolkit?: string; search?: string };\n queryOptions?: MastraQueryOptions<ProviderToolsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['tool-provider-tools', providerId, params?.toolkit, params?.search],\n queryFn: () => client.getToolProvider(providerId!).listTools(params),\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 ToolkitsResponse = Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listToolkits']>>;\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useToolkits = <TData = ToolkitsResponse>({\n providerId,\n queryOptions,\n}: {\n providerId: string | null;\n queryOptions?: MastraQueryOptions<ToolkitsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['tool-provider-toolkits', providerId],\n queryFn: () => client.getToolProvider(providerId!).listToolkits(),\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 interface UpdateConnectionArgs {\n providerId: string;\n connectionId: string;\n /**\n * New display label. Pass `null` (or an empty string) to clear the label.\n */\n label: string | null;\n}\n\n/**\n * Renames a `tool_provider_connections` row in place. Server enforces\n * ownership (owner / admin / shared scope). On success, invalidates both\n * the per-toolkit and the fan-out connection lists so the picker re-fetches.\n */\ntype UpdateConnectionResponse = Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['updateConnection']>>;\n\nexport const useUpdateConnection = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<UpdateConnectionResponse, UpdateConnectionArgs> } = {}) => {\n const client = useMastraClient();\n const qc = useQueryClient();\n\n return useMutation({\n mutationFn: async ({ providerId, connectionId, label }: UpdateConnectionArgs) => {\n const integration = client.getToolProvider(providerId);\n return integration.updateConnection(connectionId, { label });\n },\n onSuccess: (_data, vars) => {\n void qc.invalidateQueries({ queryKey: ['tool-integration-connections', vars.providerId] });\n void qc.invalidateQueries({ queryKey: ['tool-integration-connections-all', vars.providerId] });\n },\n ...queryOptions,\n });\n};\n"],"mappings":";;;;;AAQA,MAAa,oBAAmD,EAC9D,iBACuE,CAAC,MAAoC;CAC5G,MAAM,SAAS,gBAAgB;CAE/B,OAAO,SAAS;EACd,UAAU,CAAC,gBAAgB;EAC3B,eAAe,OAAO,kBAAkB;EACxC,GAAG;CACL,CAAC;AACH;AAWA,MAAa,0BAA0B,EACrC,iBAC4D,CAAC,MAAM;CACnE,MAAM,SAAS,gBAAgB;CAC/B,MAAM,EAAE,MAAM,eAAe,WAAW,uBAAuB,iBAAiB;CAChF,MAAM,YAAY,eAAe,aAAa,CAAC;CAE/C,MAAM,aAAa,SAAS;EAC1B,UAAU,CAAC,yBAAyB,UAAU,KAAI,MAAK,EAAE,EAAE,CAAC;EAC5D,SAAS,YAAY;GACnB,MAAM,UAA6B,CAAC;GAEpC,KAAK,MAAM,YAAY,WAAW;IAChC,MAAM,WAAW,MAAM,OAAO,gBAAgB,SAAS,EAAE,CAAC,CAAC,UAAU;IACrE,KAAK,MAAM,QAAQ,SAAS,MAC1B,QAAQ,KAAK;KACX,GAAG;KACH,YAAY,SAAS;KACrB,cAAc,SAAS;IACzB,CAAC;GAEL;GAEA,OAAO;EACT;EACA,SAAS,UAAU,SAAS;EAC5B,GAAG;CACL,CAAC;CAED,OAAO;EACL,MAAM,WAAW,QAAQ,CAAC;EAC1B,WAAW,sBAAsB,WAAW;CAC9C;AACF;;;;;;;;AChDA,MAAM,gBA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,YAAY,OAAO,SAAS;GAC1B,GAAQ,kBAAkB,EAAE,UAAU,CAAC,gCAAgC,KAAK,UAAU,EAAE,CAAC;GACzF,GAAQ,kBAAkB,EAAE,UAAU,CAAC,oCAAoC,KAAK,UAAU,EAAE,CAAC;EAC/F;EACA,GAAG;CACL,CAAC;AACH"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/hooks/tool-providers/use-tool-providers.ts","../../../src/hooks/tool-providers/use-all-connections.ts","../../../src/hooks/tool-providers/use-all-provider-tools.ts","../../../src/hooks/tool-providers/use-authorize.ts","../../../src/hooks/tool-providers/use-disconnect-connection.ts","../../../src/hooks/tool-providers/use-existing-connections.ts","../../../src/hooks/tool-providers/use-provider-tools.ts","../../../src/hooks/tool-providers/use-toolkits.ts","../../../src/hooks/tool-providers/use-update-connection.ts"],"sourcesContent":["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 ToolProvidersResponse = Awaited<ReturnType<MastraClient['listToolProviders']>>;\n\nexport const useToolProviders = <TData = ToolProvidersResponse>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<ToolProvidersResponse, TData> } = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['tool-providers'],\n queryFn: () => client.listToolProviders(),\n ...queryOptions,\n });\n};\n\nexport interface IntegrationTool {\n slug: string;\n name: string;\n description?: string;\n toolkit?: string;\n providerId: string;\n providerName: string;\n}\n\nexport const useAllIntegrationTools = ({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<IntegrationTool[]> } = {}) => {\n const client = useMastraClient();\n const { data: providersData, isLoading: isLoadingProviders } = useToolProviders();\n const providers = providersData?.providers ?? [];\n\n const toolsQuery = useQuery({\n queryKey: ['integration-tools-all', providers.map(p => p.id)],\n queryFn: async () => {\n const results: IntegrationTool[] = [];\n\n for (const provider of providers) {\n const response = await client.getToolProvider(provider.id).listTools();\n for (const tool of response.data) {\n results.push({\n ...tool,\n providerId: provider.id,\n providerName: provider.name,\n });\n }\n }\n\n return results;\n },\n enabled: providers.length > 0,\n ...queryOptions,\n });\n\n return {\n data: toolsQuery.data ?? [],\n isLoading: isLoadingProviders || toolsQuery.isLoading,\n };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { useQueries } from '@tanstack/react-query';\nimport { useCallback, useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport { isUnauthenticatedError, useCurrentUser } from '../auth';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { useToolProviders } from './use-tool-providers';\n\n/**\n * Stale time long enough to avoid refetching on every picker re-render but\n * short enough that an OAuth completion in a sibling tab is reflected\n * promptly (React Query also re-fetches on window focus by default).\n */\nconst STALE_TIME_MS = 30_000;\n\nexport interface UseAllConnectionsOptions {\n /**\n * When `true`, the hook forces the server-side `authorId` filter to the\n * caller's own userId. Builder edit view passes `scopeToSelf: true` so\n * admins see only their own connections, never other authors' rows.\n *\n * Non-admin callers see the same result either way — the server already\n * scopes to the caller's bucket — but the explicit filter keeps caches\n * consistent and prevents admin cross-author leakage.\n */\n scopeToSelf?: boolean;\n /** TanStack overrides applied to every fanned-out query, spread last. `select` must keep the default shape. */\n queryOptions?: {\n toolkits?: MastraQueryOptions<Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listToolkits']>>>;\n connections?: MastraQueryOptions<\n Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listConnections']>>\n >;\n };\n}\n\n/**\n * Fans out across every registered ToolProvider and every toolkit it\n * exposes to determine whether the caller has an existing connection for a\n * given `(providerId, toolkit)` pair.\n *\n * Used by the Builder tool picker to gate integration tool rows: if the\n * pair has no connection, the card cannot be selected and surfaces an\n * inline \"Connect\" button instead.\n *\n * Distinct from `useExistingConnections` (per-pair, used by `/integrations`)\n * to keep their query caches independent.\n */\nexport const useAllConnections = ({ scopeToSelf = false, queryOptions }: UseAllConnectionsOptions = {}) => {\n const client = useMastraClient();\n const providersQuery = useToolProviders();\n const providers = useMemo(() => providersQuery.data?.providers ?? [], [providersQuery.data?.providers]);\n\n const currentUserQuery = useCurrentUser();\n const callerAuthorId = currentUserQuery.data?.id;\n const callerReady = !scopeToSelf || currentUserQuery.isSuccess || isUnauthenticatedError(currentUserQuery.error);\n\n // 1. For every provider, list its toolkits.\n const toolkitsQueries = useQueries({\n queries: providers.map(provider => ({\n queryKey: ['tool-integration-services', provider.id],\n queryFn: () => client.getToolProvider(provider.id).listToolkits(),\n ...queryOptions?.toolkits,\n })),\n });\n\n // 2. Flatten to (providerId, toolkit) pairs.\n const pairs = useMemo(() => {\n const out: Array<{ providerId: string; toolkit: string }> = [];\n providers.forEach((provider, idx) => {\n const toolkits = toolkitsQueries[idx]?.data?.data ?? [];\n for (const toolkit of toolkits) {\n out.push({ providerId: provider.id, toolkit: toolkit.slug });\n }\n });\n return out;\n }, [providers, toolkitsQueries]);\n\n // 3. One listConnections call per pair. Include `authorId` in queryKey when\n // self-scoped so the cache is distinct from any unscoped admin reads.\n const connectionsQueries = useQueries({\n queries: pairs.map(pair => ({\n queryKey: scopeToSelf\n ? ['tool-integration-connections-all', pair.providerId, pair.toolkit, callerAuthorId]\n : ['tool-integration-connections-all', pair.providerId, pair.toolkit],\n queryFn: () =>\n client.getToolProvider(pair.providerId).listConnections({\n toolkit: pair.toolkit,\n ...(scopeToSelf && callerAuthorId ? { authorId: callerAuthorId } : {}),\n }),\n enabled: callerReady,\n staleTime: STALE_TIME_MS,\n ...queryOptions?.connections,\n })),\n });\n\n const isLoading =\n providersQuery.isLoading ||\n (scopeToSelf && currentUserQuery.isLoading) ||\n toolkitsQueries.some(q => q.isLoading) ||\n connectionsQueries.some(q => q.isLoading);\n\n // Build a per-pair list of connection summaries so callers can both gate\n // (\"does this row have any connection?\") and auto-pin (\"if exactly one\n // exists, write it into the form on toggle-on\").\n const connectionsByKey = useMemo(() => {\n const map = new Map<string, Array<{ connectionId: string; label?: string | null; status?: string }>>();\n pairs.forEach((pair, idx) => {\n const items = connectionsQueries[idx]?.data?.items ?? [];\n map.set(`${pair.providerId}:${pair.toolkit}`, items);\n });\n return map;\n }, [pairs, connectionsQueries]);\n\n // A toolkit \"has a connection\" only when at least one connection is active.\n // Pending/failed rows don't count — this keeps the card hint in sync with the\n // toolkit row control, which also treats only active connections as usable.\n const hasConnection = useCallback(\n (providerId: string, toolkit: string) =>\n (connectionsByKey.get(`${providerId}:${toolkit}`) ?? []).some(connection => connection.status === 'active'),\n [connectionsByKey],\n );\n\n const getConnections = useCallback(\n (providerId: string, toolkit: string) => connectionsByKey.get(`${providerId}:${toolkit}`) ?? [],\n [connectionsByKey],\n );\n\n return { hasConnection, getConnections, isLoading };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { useQueries } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { useToolProviders } from './use-tool-providers';\n\nexport interface AvailableIntegrationTool {\n providerId: string;\n slug: string;\n toolkit: string;\n name?: string;\n description?: string;\n}\n\n/**\n * Upper bound for a single Composio-style `listTools` call. Composio's SDK has\n * no cursor — only `limit` — so we ask for a large page and fan out per\n * `toolkit` to avoid being truncated when many toolkits are allowlisted.\n */\nconst PER_SERVICE_LIMIT = 500;\n\n/**\n * Returns every tool surfaced by every registered ToolProvider, scoped to\n * the provider's `allowedToolkits`/`allowedTools` filter (enforced\n * server-side). Used to render the full available-tools list inline.\n */\nexport const useAllProviderTools = ({\n queryOptions,\n}: {\n /** TanStack overrides applied to every fanned-out query, spread last. `select` must keep the default shape. */\n queryOptions?: {\n toolkits?: MastraQueryOptions<Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listToolkits']>>>;\n tools?: MastraQueryOptions<Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listTools']>>>;\n };\n} = {}) => {\n const client = useMastraClient();\n const integrationsQuery = useToolProviders();\n const integrations = useMemo(() => integrationsQuery.data?.providers ?? [], [integrationsQuery.data?.providers]);\n\n // 1. For every integration, fetch its tool services.\n const serviceQueries = useQueries({\n queries: integrations.map(integration => ({\n queryKey: ['tool-integration-services', integration.id],\n queryFn: () => client.getToolProvider(integration.id).listToolkits(),\n ...queryOptions?.toolkits,\n })),\n });\n\n // 2. Flatten to (providerId, serviceSlug) pairs.\n const servicePairs = useMemo(() => {\n const pairs: Array<{ providerId: string; toolkit: string }> = [];\n integrations.forEach((integration, idx) => {\n const services = serviceQueries[idx]?.data?.data ?? [];\n for (const service of services) {\n pairs.push({ providerId: integration.id, toolkit: service.slug });\n }\n });\n return pairs;\n }, [integrations, serviceQueries]);\n\n // 3. Fan out one tools query per (integration, service).\n const toolsQueries = useQueries({\n queries: servicePairs.map(pair => ({\n queryKey: ['tool-integration-tools-all', pair.providerId, pair.toolkit],\n queryFn: () =>\n client.getToolProvider(pair.providerId).listTools({ toolkit: pair.toolkit, perPage: PER_SERVICE_LIMIT }),\n ...queryOptions?.tools,\n })),\n });\n\n const isLoading =\n integrationsQuery.isLoading || serviceQueries.some(q => q.isLoading) || toolsQueries.some(q => q.isLoading);\n\n const tools = useMemo<AvailableIntegrationTool[]>(() => {\n const out: AvailableIntegrationTool[] = [];\n servicePairs.forEach((pair, idx) => {\n const items = toolsQueries[idx]?.data?.data ?? [];\n for (const item of items) {\n const toolkit = (item as { toolkit?: string }).toolkit ?? pair.toolkit;\n out.push({\n providerId: pair.providerId,\n slug: item.slug,\n toolkit,\n name: (item as { name?: string }).name,\n description: (item as { description?: string }).description,\n });\n }\n });\n return out;\n }, [servicePairs, toolsQueries]);\n\n return { tools, isLoading };\n};\n","import { useMutation } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nexport interface AuthorizeArgs {\n providerId: string;\n toolkit: string;\n /**\n * Existing bucket id when re-authorizing; omit for a brand-new connection.\n * Semantics are provider-opaque; for Composio v1 this is the internal user\n * bucket the new connected account should be created under.\n */\n connectionId?: string;\n /**\n * Provider-specific connection fields collected from the picker (e.g.\n * Confluence subdomain). Forwarded to the server's `authorize` body.\n */\n config?: Record<string, unknown>;\n /**\n * Optional human label to persist on the resulting `tool_integration_connections` row.\n */\n label?: string | null;\n /**\n * Ownership scope of the OAuth bucket. `'per-author'` (default) buckets\n * under the caller's authorId.\n */\n scope?: 'per-author' | 'shared' | 'caller-supplied';\n}\n\nexport interface AuthorizeResult {\n status: 'completed' | 'failed';\n /**\n * The `authId` returned by `authorize`, exposed as `connectionId` because\n * for the v1 Composio adapter it is the `connected_account.id` that the\n * caller persists as `Connection.connectionId`.\n */\n connectionId: string;\n}\n\nconst DEFAULT_POLL_INTERVAL_MS = 2000;\nconst DEFAULT_TIMEOUT_MS = 5 * 60_000;\n\nexport interface UseAuthorizeOptions {\n pollIntervalMs?: number;\n timeoutMs?: number;\n openPopup?: (url: string) => Window | null;\n queryOptions?: MastraMutationOptions<AuthorizeResult, AuthorizeArgs>;\n}\n\n/**\n * Drives the OAuth popup + polling loop for a `ToolProvider` provider.\n */\nexport const useAuthorize = (options: UseAuthorizeOptions = {}) => {\n const client = useMastraClient();\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const openPopup = options.openPopup ?? ((url: string) => window.open(url, '_blank', 'popup,width=600,height=700'));\n\n return useMutation<AuthorizeResult, Error, AuthorizeArgs>({\n mutationFn: async ({ providerId, toolkit, connectionId, config, label, scope }) => {\n const integration = client.getToolProvider(providerId);\n const normalizedConnectionId = connectionId?.trim();\n const { url, authId } = await integration.authorize({\n toolkit,\n ...(normalizedConnectionId ? { connectionId: normalizedConnectionId } : {}),\n ...(config ? { config } : {}),\n ...(label !== undefined ? { label } : {}),\n ...(scope ? { scope } : {}),\n });\n\n const popup = openPopup(url);\n if (!popup) {\n throw new Error('Popup blocked. Please allow popups for this site.');\n }\n\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n await new Promise(resolve => setTimeout(resolve, pollIntervalMs));\n const { status } = await integration.getAuthStatus(authId);\n if (status === 'completed' || status === 'failed') {\n try {\n popup.close();\n } catch {\n // Cross-origin popups may refuse close(); ignore.\n }\n return { status, connectionId: authId };\n }\n }\n\n try {\n popup.close();\n } catch {\n // ignore\n }\n throw new Error('Authorization timed out');\n },\n ...options.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 interface DisconnectConnectionArgs {\n providerId: string;\n connectionId: string;\n /**\n * When `true`, the server skips the usage check and revokes the\n * connection at the provider before deleting the local row.\n */\n force?: boolean;\n}\n\n/**\n * Calls the provider-side revoke (best-effort) and drops the local\n * `tool_integration_connections` row. Server enforces the soft-vs-force rule.\n */\ntype DisconnectConnectionResponse = Awaited<\n ReturnType<ReturnType<MastraClient['getToolProvider']>['disconnectConnection']>\n>;\n\nexport const useDisconnectConnection = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<DisconnectConnectionResponse, DisconnectConnectionArgs> } = {}) => {\n const client = useMastraClient();\n const qc = useQueryClient();\n\n return useMutation({\n mutationFn: async ({ providerId, connectionId, force }: DisconnectConnectionArgs) => {\n const integration = client.getToolProvider(providerId);\n return integration.disconnectConnection(connectionId, force ? { force } : undefined);\n },\n onSuccess: (_data, vars) => {\n void qc.invalidateQueries({ queryKey: ['tool-integration-connections', vars.providerId] });\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';\nimport { useMastraClient } from '../../mastra-client-context';\nimport { isUnauthenticatedError, useCurrentUser } from '../auth';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nexport interface UseExistingConnectionsOptions {\n /**\n * When `true`, the hook forces the server-side `authorId` filter to the\n * caller's own userId. Builder edit view passes `scopeToSelf: true` so\n * admins see only their own connections, never other authors' rows.\n *\n * Non-admin callers see the same result either way — the server already\n * scopes to the caller's bucket — but the explicit filter keeps caches\n * consistent and prevents admin cross-author leakage in the picker.\n */\n scopeToSelf?: boolean;\n}\n\ntype ConnectionsResponse = Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listConnections']>>;\n\n/**\n * Lists existing provider connections for the caller, scoped to a tool\n * service. Powers the \"use existing connection\" path in the picker so\n * authors can pin previously-authorized accounts without re-running OAuth.\n *\n * The connection owner is resolved server-side from the request's auth\n * context. Admin callers receive cross-author rows by default; pass\n * `scopeToSelf: true` to narrow the response to the caller's own bucket\n * (used by the Builder edit view).\n */\nexport const useExistingConnections = <TData = ConnectionsResponse>({\n providerId,\n toolkit,\n scopeToSelf = false,\n queryOptions,\n}: UseExistingConnectionsOptions & {\n providerId: string | null | undefined;\n toolkit: string | null | undefined;\n queryOptions?: MastraQueryOptions<ConnectionsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n const currentUserQuery = useCurrentUser();\n const callerAuthorId = currentUserQuery.data?.id;\n\n const callerReady = !scopeToSelf || currentUserQuery.isSuccess || isUnauthenticatedError(currentUserQuery.error);\n\n const enabled = !!providerId && !!toolkit && callerReady;\n\n return useQuery({\n queryKey: scopeToSelf\n ? ['tool-integration-connections', providerId, toolkit, callerAuthorId]\n : ['tool-integration-connections', providerId, toolkit],\n queryFn: () =>\n client.getToolProvider(providerId!).listConnections({\n toolkit: toolkit!,\n ...(scopeToSelf && callerAuthorId ? { authorId: callerAuthorId } : {}),\n }),\n enabled,\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 ProviderToolsResponse = Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listTools']>>;\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useProviderTools = <TData = ProviderToolsResponse>({\n providerId,\n params,\n queryOptions,\n}: {\n providerId: string | null;\n params?: { toolkit?: string; search?: string };\n queryOptions?: MastraQueryOptions<ProviderToolsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['tool-provider-tools', providerId, params?.toolkit, params?.search],\n queryFn: () => client.getToolProvider(providerId!).listTools(params),\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 ToolkitsResponse = Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['listToolkits']>>;\n\n/**\n * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.\n */\nexport const useToolkits = <TData = ToolkitsResponse>({\n providerId,\n queryOptions,\n}: {\n providerId: string | null;\n queryOptions?: MastraQueryOptions<ToolkitsResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['tool-provider-toolkits', providerId],\n queryFn: () => client.getToolProvider(providerId!).listToolkits(),\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 interface UpdateConnectionArgs {\n providerId: string;\n connectionId: string;\n /**\n * New display label. Pass `null` (or an empty string) to clear the label.\n */\n label: string | null;\n}\n\n/**\n * Renames a `tool_provider_connections` row in place. Server enforces\n * ownership (owner / admin / shared scope). On success, invalidates both\n * the per-toolkit and the fan-out connection lists so the picker re-fetches.\n */\ntype UpdateConnectionResponse = Awaited<ReturnType<ReturnType<MastraClient['getToolProvider']>['updateConnection']>>;\n\nexport const useUpdateConnection = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<UpdateConnectionResponse, UpdateConnectionArgs> } = {}) => {\n const client = useMastraClient();\n const qc = useQueryClient();\n\n return useMutation({\n mutationFn: async ({ providerId, connectionId, label }: UpdateConnectionArgs) => {\n const integration = client.getToolProvider(providerId);\n return integration.updateConnection(connectionId, { label });\n },\n onSuccess: (_data, vars) => {\n void qc.invalidateQueries({ queryKey: ['tool-integration-connections', vars.providerId] });\n void qc.invalidateQueries({ queryKey: ['tool-integration-connections-all', vars.providerId] });\n },\n ...queryOptions,\n });\n};\n"],"mappings":";;;;;AAQA,MAAa,oBAAmD,EAC9D,iBACuE,CAAC,MAAoC;CAC5G,MAAM,SAAS,gBAAgB;CAE/B,OAAO,SAAS;EACd,UAAU,CAAC,gBAAgB;EAC3B,eAAe,OAAO,kBAAkB;EACxC,GAAG;CACL,CAAC;AACH;AAWA,MAAa,0BAA0B,EACrC,iBAC4D,CAAC,MAAM;CACnE,MAAM,SAAS,gBAAgB;CAC/B,MAAM,EAAE,MAAM,eAAe,WAAW,uBAAuB,iBAAiB;CAChF,MAAM,YAAY,eAAe,aAAa,CAAC;CAE/C,MAAM,aAAa,SAAS;EAC1B,UAAU,CAAC,yBAAyB,UAAU,KAAI,MAAK,EAAE,EAAE,CAAC;EAC5D,SAAS,YAAY;GACnB,MAAM,UAA6B,CAAC;GAEpC,KAAK,MAAM,YAAY,WAAW;IAChC,MAAM,WAAW,MAAM,OAAO,gBAAgB,SAAS,EAAE,CAAC,CAAC,UAAU;IACrE,KAAK,MAAM,QAAQ,SAAS,MAC1B,QAAQ,KAAK;KACX,GAAG;KACH,YAAY,SAAS;KACrB,cAAc,SAAS;IACzB,CAAC;GAEL;GAEA,OAAO;EACT;EACA,SAAS,UAAU,SAAS;EA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AAO,EAAE,YAAY,cAAc,YAAkC;GAE/E,OADoB,OAAO,gBAAgB,UAC1B,CAAC,CAAC,iBAAiB,cAAc,EAAE,MAAM,CAAC;EAC7D;EACA,YAAY,OAAO,SAAS;GAC1B,GAAQ,kBAAkB,EAAE,UAAU,CAAC,gCAAgC,KAAK,UAAU,EAAE,CAAC;GACzF,GAAQ,kBAAkB,EAAE,UAAU,CAAC,oCAAoC,KAAK,UAAU,EAAE,CAAC;EAC/F;EACA,GAAG;CACL,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["useMastraClient","useMastraClient","RequestContext"],"sources":["../../../src/hooks/tools/use-all-tools.ts","../../../src/hooks/tools/use-execute-tool.ts"],"sourcesContent":["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 ToolsResponse = Awaited<ReturnType<MastraClient['listTools']>>;\ntype ToolResponse = Awaited<ReturnType<ReturnType<MastraClient['getTool']>['details']>>;\n\nexport const useTools = <TData = ToolsResponse>({\n requestContext,\n queryOptions,\n}: {\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<ToolsResponse, TData>;\n} = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n return useQuery({\n queryKey: ['tools', requestContext],\n queryFn: () => client.listTools(requestContext),\n ...queryOptions,\n });\n};\n\nexport const useTool = <TData = ToolResponse>({\n toolId,\n requestContext,\n queryOptions,\n}: {\n toolId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<ToolResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['tool', toolId, requestContext],\n queryFn: () => client.getTool(toolId).details(requestContext),\n ...queryOptions,\n });\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { RequestContext } from '@mastra/core/di';\n\nimport { useMutation } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\ntype ExecuteToolResponse = Awaited<ReturnType<ReturnType<MastraClient['getTool']>['execute']>>;\ntype ExecuteToolVariables = { toolId: string; input: any; requestContext?: Record<string, any> };\n\nexport const useExecuteTool = ({\n queryOptions,\n}: {\n queryOptions?: MastraMutationOptions<ExecuteToolResponse, ExecuteToolVariables>;\n} = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ toolId, input, requestContext: playgroundRequestContext }: ExecuteToolVariables) => {\n const requestContext = new RequestContext();\n Object.entries(playgroundRequestContext ?? {}).forEach(([key, value]) => {\n requestContext.set(key, value);\n });\n\n const tool = client.getTool(toolId);\n return tool.execute({ data: input, requestContext });\n },\n ...queryOptions,\n });\n};\n"],"mappings":";;;;;AASA,MAAa,YAAmC,EAC9C,gBACA,iBAIE,CAAC,MAAoC;CACvC,MAAM,SAASA,8BAAAA,gBAAgB;CAC/B,QAAA,GAAA,sBAAA,SAAA,CAAgB;EACd,UAAU,CAAC,SAAS,cAAc;EAClC,eAAe,OAAO,UAAU,cAAc;EAC9C,GAAG;CACL,CAAC;AACH;AAEA,MAAa,WAAiC,EAC5C,QACA,gBACA,mBAKkC;CAClC,MAAM,SAASA,8BAAAA,gBAAgB;CAE/B,QAAA,GAAA,sBAAA,SAAA,CAAgB;EACd,UAAU;GAAC;GAAQ;GAAQ;EAAc;EACzC,eAAe,OAAO,QAAQ,MAAM,CAAC,CAAC,QAAQ,cAAc;EAC5D,GAAG;CACL,CAAC;AACH;;;AC9BA,MAAa,kBAAkB,EAC7B,iBAGE,CAAC,MAAM;CACT,MAAM,SAASC,8BAAAA,gBAAgB;CAC/B,QAAA,GAAA,sBAAA,YAAA,CAAmB;EACjB,YAAY,OAAO,EAAE,QAAQ,OAAO,gBAAgB,+BAAqD;GACvG,MAAM,iBAAiB,IAAIC,gBAAAA,eAAe;GAC1C,OAAO,QAAQ,4BAA4B,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;IACvE,eAAe,IAAI,KAAK,KAAK;GAC/B,CAAC;GAGD,OADa,OAAO,QAAQ,MAClB,CAAC,CAAC,QAAQ;IAAE,MAAM;IAAO;GAAe,CAAC;EACrD;EACA,GAAG;CACL,CAAC;AACH"}
1
+ {"version":3,"file":"index.cjs","names":["useMastraClient","useQuery","useMastraClient","useMutation","RequestContext"],"sources":["../../../src/hooks/tools/use-all-tools.ts","../../../src/hooks/tools/use-execute-tool.ts"],"sourcesContent":["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 ToolsResponse = Awaited<ReturnType<MastraClient['listTools']>>;\ntype ToolResponse = Awaited<ReturnType<ReturnType<MastraClient['getTool']>['details']>>;\n\nexport const useTools = <TData = ToolsResponse>({\n requestContext,\n queryOptions,\n}: {\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<ToolsResponse, TData>;\n} = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n return useQuery({\n queryKey: ['tools', requestContext],\n queryFn: () => client.listTools(requestContext),\n ...queryOptions,\n });\n};\n\nexport const useTool = <TData = ToolResponse>({\n toolId,\n requestContext,\n queryOptions,\n}: {\n toolId: string;\n requestContext?: Record<string, any>;\n queryOptions?: MastraQueryOptions<ToolResponse, TData>;\n}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['tool', toolId, requestContext],\n queryFn: () => client.getTool(toolId).details(requestContext),\n ...queryOptions,\n });\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { RequestContext } from '@mastra/core/di';\n\nimport { useMutation } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\ntype ExecuteToolResponse = Awaited<ReturnType<ReturnType<MastraClient['getTool']>['execute']>>;\ntype ExecuteToolVariables = { toolId: string; input: any; requestContext?: Record<string, any> };\n\nexport const useExecuteTool = ({\n queryOptions,\n}: {\n queryOptions?: MastraMutationOptions<ExecuteToolResponse, ExecuteToolVariables>;\n} = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ toolId, input, requestContext: playgroundRequestContext }: ExecuteToolVariables) => {\n const requestContext = new RequestContext();\n Object.entries(playgroundRequestContext ?? {}).forEach(([key, value]) => {\n requestContext.set(key, value);\n });\n\n const tool = client.getTool(toolId);\n return tool.execute({ data: input, requestContext });\n },\n ...queryOptions,\n });\n};\n"],"mappings":";;;;;AASA,MAAa,YAAmC,EAC9C,gBACA,iBAIE,CAAC,MAAoC;CACvC,MAAM,SAASA,8BAAAA,gBAAgB;CAC/B,QAAA,GAAOC,sBAAAA,SAAAA,CAAS;EACd,UAAU,CAAC,SAAS,cAAc;EAClC,eAAe,OAAO,UAAU,cAAc;EAC9C,GAAG;CACL,CAAC;AACH;AAEA,MAAa,WAAiC,EAC5C,QACA,gBACA,mBAKkC;CAClC,MAAM,SAASD,8BAAAA,gBAAgB;CAE/B,QAAA,GAAOC,sBAAAA,SAAAA,CAAS;EACd,UAAU;GAAC;GAAQ;GAAQ;EAAc;EACzC,eAAe,OAAO,QAAQ,MAAM,CAAC,CAAC,QAAQ,cAAc;EAC5D,GAAG;CACL,CAAC;AACH;;;AC9BA,MAAa,kBAAkB,EAC7B,iBAGE,CAAC,MAAM;CACT,MAAM,SAASC,8BAAAA,gBAAgB;CAC/B,QAAA,GAAOC,sBAAAA,YAAAA,CAAY;EACjB,YAAY,OAAO,EAAE,QAAQ,OAAO,gBAAgB,+BAAqD;GACvG,MAAM,iBAAiB,IAAIC,gBAAAA,eAAe;GAC1C,OAAO,QAAQ,4BAA4B,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;IACvE,eAAe,IAAI,KAAK,KAAK;GAC/B,CAAC;GAGD,OADa,OAAO,QAAQ,MAClB,CAAC,CAAC,QAAQ;IAAE,MAAM;IAAO;GAAe,CAAC;EACrD;EACA,GAAG;CACL,CAAC;AACH"}
@@ -1,9 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_mastra_client_context = require("../../mastra-client-context-DzX3f0RF.cjs");
3
3
  const require_use_in_view = require("../../use-in-view-B6eJO9Zi.cjs");
4
- const require_map = require("../../map-wjmL1y5O.cjs");
5
4
  const require_query_utils = require("../../query-utils-CcrChYgz.cjs");
6
5
  const require_feedback_refetch_interval = require("../../feedback-refetch-interval-XD5FVc2k.cjs");
6
+ const require_map = require("../../map-wjmL1y5O.cjs");
7
7
  let _mastra_client_js = require("@mastra/client-js");
8
8
  let react = require("react");
9
9
  let _tanstack_react_query = require("@tanstack/react-query");
@@ -19,7 +19,7 @@ let _mastra_core_observability = require("@mastra/core/observability");
19
19
  * through to the store's discovery refresh. Matching the server TTL keeps the
20
20
  * client from asking more often than the answer can change.
21
21
  */
22
- const DISCOVERY_STALE_TIME = 300 * 1e3;
22
+ const DISCOVERY_STALE_TIME = 3e5;
23
23
  //#endregion
24
24
  //#region src/hooks/traces/use-branch.ts
25
25
  /**
@@ -136,7 +136,7 @@ const useServiceNames = ({ queryOptions } = {}) => {
136
136
  };
137
137
  //#endregion
138
138
  //#region src/hooks/traces/use-span-detail.ts
139
- const IMMUTABLE_CACHE_TIME$1 = 1e3 * 60 * 60 * 24 * 30;
139
+ const IMMUTABLE_CACHE_TIME$1 = 2592e6;
140
140
  /**
141
141
  * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.
142
142
  */
@@ -201,7 +201,7 @@ function useThreadHasOtherTraces({ threadId, queryOptions }) {
201
201
  }
202
202
  //#endregion
203
203
  //#region src/hooks/traces/use-trace-light-spans.ts
204
- const IMMUTABLE_CACHE_TIME = 1e3 * 60 * 60 * 24 * 30;
204
+ const IMMUTABLE_CACHE_TIME = 2592e6;
205
205
  /**
206
206
  * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.
207
207
  */
@@ -320,6 +320,8 @@ function useTraceOrBranchSpans({ traceId, anchorSpanId, listMode, depth, queryOp
320
320
  //#endregion
321
321
  //#region src/hooks/traces/use-trace-query.ts
322
322
  const TRACE_QUERY_PER_PAGE = 25;
323
+ /** Max traces per delta request; the server caps `limit` at 100. */
324
+ const TRACE_QUERY_DELTA_LIMIT = 100;
323
325
  function getTraceQueryNextPageParam(lastPage) {
324
326
  return lastPage?.page.next ?? void 0;
325
327
  }
@@ -369,16 +371,101 @@ function selectLegacyTraceQueryTraces(data) {
369
371
  function getLegacyTraceQueryNextPageParam(lastPage) {
370
372
  return lastPage.pagination?.hasMore ? lastPage.pagination.page + 1 : void 0;
371
373
  }
374
+ /** Cache key of `useTraceQuery`'s trace-query list. Pass the same `query` and `limit` to share it. */
375
+ const traceQueryKey = (query, limit = 25) => [
376
+ "trace-query",
377
+ query,
378
+ limit
379
+ ];
380
+ function traceSortValue(trace, field) {
381
+ if (field === "timeToFirstChunkMs") return trace.timeToFirstChunkMs ?? null;
382
+ const value = trace[field];
383
+ return value == null ? null : Date.parse(value);
384
+ }
385
+ /** Mirrors the server's keyset order: empty values last in both directions, ties by ascending `traceId`. */
386
+ function compareTraces(orderBy) {
387
+ return (a, b) => {
388
+ const va = traceSortValue(a, orderBy.field);
389
+ const vb = traceSortValue(b, orderBy.field);
390
+ if (va !== vb) {
391
+ if (va === null) return 1;
392
+ if (vb === null) return -1;
393
+ return orderBy.direction === "asc" ? va - vb : vb - va;
394
+ }
395
+ return a.traceId < b.traceId ? -1 : a.traceId > b.traceId ? 1 : 0;
396
+ };
397
+ }
398
+ /**
399
+ * Merges delta-polled traces into the pages of a `useTraceQuery` list, without mutating `data`.
400
+ * A trace already on a page is replaced in place when its sort value is unchanged; otherwise it is
401
+ * removed and placed again like a new trace (sorting by `endedAt`, a running trace moves once it
402
+ * ends). A new trace goes into the first page whose last row sorts after it; when no loaded page does, it is
403
+ * appended to the last page if that is the end of the list, and skipped otherwise, since keyset
404
+ * pagination returns it once the user scrolls there. Page cursors are kept as they are, and `data`
405
+ * itself is returned when nothing changed.
406
+ */
407
+ function mergeTraceQueryDelta(data, traces, orderBy) {
408
+ if (traces.length === 0 || data.pages.length === 0) return data;
409
+ const incoming = new Map(traces.map((trace) => [trace.traceId, trace]));
410
+ const rows = data.pages.map((page) => page.traces);
411
+ const changed = /* @__PURE__ */ new Set();
412
+ const write = (pageIndex, next) => {
413
+ rows[pageIndex] = next;
414
+ changed.add(pageIndex);
415
+ };
416
+ const sortBy = orderBy?.[0] ?? {
417
+ field: "startedAt",
418
+ direction: "desc"
419
+ };
420
+ const compare = compareTraces(sortBy);
421
+ const replacedInPlace = /* @__PURE__ */ new Set();
422
+ rows.forEach((pageRows, pageIndex) => {
423
+ if (!pageRows.some((row) => incoming.has(row.traceId))) return;
424
+ const next = [];
425
+ for (const row of pageRows) {
426
+ const update = incoming.get(row.traceId);
427
+ if (!update) next.push(row);
428
+ else if (traceSortValue(update, sortBy.field) === traceSortValue(row, sortBy.field)) {
429
+ next.push(update);
430
+ replacedInPlace.add(row.traceId);
431
+ }
432
+ }
433
+ write(pageIndex, next);
434
+ });
435
+ for (const traceId of replacedInPlace) incoming.delete(traceId);
436
+ const lastIndex = rows.length - 1;
437
+ for (const trace of incoming.values()) {
438
+ let pageIndex = rows.findIndex((pageRows) => {
439
+ const last = pageRows[pageRows.length - 1];
440
+ return last !== void 0 && compare(trace, last) < 0;
441
+ });
442
+ if (pageIndex === -1) {
443
+ if (data.pages[lastIndex].page.next !== null) continue;
444
+ pageIndex = lastIndex;
445
+ }
446
+ const pageRows = rows[pageIndex];
447
+ const at = pageRows.findIndex((row) => compare(trace, row) < 0);
448
+ write(pageIndex, at === -1 ? [...pageRows, trace] : [
449
+ ...pageRows.slice(0, at),
450
+ trace,
451
+ ...pageRows.slice(at)
452
+ ]);
453
+ }
454
+ if (changed.size === 0) return data;
455
+ return {
456
+ ...data,
457
+ pages: data.pages.map((page, pageIndex) => changed.has(pageIndex) ? {
458
+ ...page,
459
+ traces: rows[pageIndex]
460
+ } : page)
461
+ };
462
+ }
372
463
  /** Queries traces with cursor pagination and viewport-driven loading. */
373
464
  function useTraceQuery({ query, limit = 25, enabled = true, withQueryTrace = true, legacyFilters, queryOptions }) {
374
465
  const client = require_mastra_client_context.useMastraClient();
375
466
  const { inView, setRef: setEndOfListElement } = require_use_in_view.useInView();
376
467
  const queryResult = (0, _tanstack_react_query.useInfiniteQuery)({
377
- queryKey: [
378
- "trace-query",
379
- query,
380
- limit
381
- ],
468
+ queryKey: traceQueryKey(query, limit),
382
469
  queryFn: query ? async ({ pageParam }) => {
383
470
  const response = await new _mastra_client_js.MastraClient({
384
471
  ...client.options,
@@ -456,6 +543,90 @@ function useTraceQuery({ query, limit = 25, enabled = true, withQueryTrace = tru
456
543
  setEndOfListElement
457
544
  };
458
545
  }
546
+ function omitOrderBy({ orderBy: _orderBy, ...rest }) {
547
+ return rest;
548
+ }
549
+ /** Request timeouts and rate limits clear up on their own, unlike the other 4xx refusals. */
550
+ const TRANSIENT_CLIENT_ERROR_STATUSES = /* @__PURE__ */ new Set([408, 429]);
551
+ /** The server refused the request or does not support delta polling; polling again cannot change that. */
552
+ function isRejectedDeltaRequest(error) {
553
+ if (!(error instanceof _mastra_client_js.MastraClientError) || TRANSIENT_CLIENT_ERROR_STATUSES.has(error.status)) return false;
554
+ return error.status >= 400 && error.status < 500 || error.status === 501;
555
+ }
556
+ const isCursorConflict = (error) => error instanceof _mastra_client_js.MastraClientError && error.status === 409;
557
+ /**
558
+ * Polls `queryTraces({ mode: 'delta' })` and merges new or updated traces into the list of a
559
+ * `useTraceQuery` rendered with the same `query` and `limit`. The first request only establishes
560
+ * the server cursor; each later poll drains every batch since that cursor. A cursor conflict (409)
561
+ * starts over with a new cursor. A poll that returns while the list is loading a page, or before
562
+ * the list has loaded at all, keeps its cursor and asks again on the next poll.
563
+ *
564
+ * The cursor is keyed on the query without `orderBy` (delta polls cannot sort) and on `limit`, so
565
+ * re-sorting the list keeps polling from the same cursor, and lists with different page sizes each
566
+ * get their own cursor.
567
+ *
568
+ * Requires the `deltaPolling` capability (see `useTraceQueryDeltaPollingAvailable`). The list's
569
+ * `timeRange.to` must not move between polls, so a live list needs a `to` in the future.
570
+ *
571
+ * Known limitation: the cursor is established in parallel with the list's first page, so a trace
572
+ * that completes between the first page's read and the cursor can be missed until the list is
573
+ * refetched. Traces returned by both are merged by `traceId`.
574
+ */
575
+ function useTraceQueryLatest({ query, limit = 25, enabled = true, refetchInterval = false, queryOptions }) {
576
+ const client = require_mastra_client_context.useMastraClient();
577
+ const queryClient = (0, _tanstack_react_query.useQueryClient)();
578
+ const deltaQuery = query && omitOrderBy(query);
579
+ const queryKey = [
580
+ "trace-query-latest",
581
+ deltaQuery,
582
+ limit
583
+ ];
584
+ return (0, _tanstack_react_query.useQuery)({
585
+ queryKey,
586
+ queryFn: query && deltaQuery ? async () => {
587
+ const mastra = new _mastra_client_js.MastraClient({
588
+ ...client.options,
589
+ retries: 0
590
+ });
591
+ const bootstrap = async () => {
592
+ return { deltaCursor: (await mastra.queryTraces({
593
+ ...deltaQuery,
594
+ mode: "delta"
595
+ })).deltaCursor };
596
+ };
597
+ const previous = queryClient.getQueryData(queryKey);
598
+ if (!previous) return bootstrap();
599
+ const traces = [];
600
+ let deltaCursor = previous.deltaCursor;
601
+ try {
602
+ for (let hasMore = true; hasMore;) {
603
+ const response = await mastra.queryTraces({
604
+ ...deltaQuery,
605
+ mode: "delta",
606
+ after: deltaCursor,
607
+ limit: 100
608
+ });
609
+ traces.push(...response.traces);
610
+ deltaCursor = response.deltaCursor;
611
+ hasMore = response.delta.hasMore;
612
+ }
613
+ } catch (error) {
614
+ if (isCursorConflict(error)) return bootstrap();
615
+ throw error;
616
+ }
617
+ const listKey = traceQueryKey(query, limit);
618
+ const listState = queryClient.getQueryState(listKey);
619
+ if (!listState?.data || listState.fetchStatus === "fetching") return previous;
620
+ queryClient.setQueryData(listKey, (data) => data ? mergeTraceQueryDelta(data, traces, query.orderBy) : data);
621
+ return { deltaCursor };
622
+ } : _tanstack_react_query.skipToken,
623
+ retry: false,
624
+ refetchInterval: (q) => isRejectedDeltaRequest(q.state.error) ? false : refetchInterval,
625
+ refetchIntervalInBackground: false,
626
+ enabled: enabled && !!query,
627
+ ...queryOptions
628
+ });
629
+ }
459
630
  //#endregion
460
631
  //#region src/hooks/traces/use-trace-usage.ts
461
632
  const INPUT_TOKEN_METRIC = "mastra_model_total_input_tokens";
@@ -552,7 +723,7 @@ const DEFAULT_POLLING_CONFIG = {
552
723
  deltaLimit: 100,
553
724
  pageModeRefetchIntervalMs: 1e4,
554
725
  page0StatusRefreshIntervalMs: 6e4,
555
- idleGuardThresholdMs: 15 * 6e4,
726
+ idleGuardThresholdMs: 9e5,
556
727
  minRefetchSpinMs: 400,
557
728
  deltaHighlightMs: 1e3
558
729
  };
@@ -1133,6 +1304,7 @@ function useTraceColumnPreferencesStorageKey() {
1133
1304
  exports.DISCOVERY_STALE_TIME = DISCOVERY_STALE_TIME;
1134
1305
  exports.ROOT_ENTITY_TYPES = ROOT_ENTITY_TYPES;
1135
1306
  exports.TRACES_PER_PAGE = TRACES_PER_PAGE;
1307
+ exports.TRACE_QUERY_DELTA_LIMIT = TRACE_QUERY_DELTA_LIMIT;
1136
1308
  exports.TRACE_QUERY_PER_PAGE = TRACE_QUERY_PER_PAGE;
1137
1309
  exports.createTraceQueryValuesResolver = createTraceQueryValuesResolver;
1138
1310
  exports.getLegacyTraceQueryNextPageParam = getLegacyTraceQueryNextPageParam;
@@ -1140,6 +1312,7 @@ exports.getTraceQueryNextPageParam = getTraceQueryNextPageParam;
1140
1312
  exports.getTracesNextPageParam = getTracesNextPageParam;
1141
1313
  exports.lightSpanToTraceQueryTrace = lightSpanToTraceQueryTrace;
1142
1314
  exports.mergeDeltaIntoPage0 = mergeDeltaIntoPage0;
1315
+ exports.mergeTraceQueryDelta = mergeTraceQueryDelta;
1143
1316
  exports.refreshPage0Rows = refreshPage0Rows;
1144
1317
  exports.selectLegacyTraceQueryTraces = selectLegacyTraceQueryTraces;
1145
1318
  exports.selectTraceQueryTraces = selectTraceQueryTraces;
@@ -1147,6 +1320,7 @@ exports.selectUniqueTraces = selectUniqueTraces;
1147
1320
  exports.shouldPinLightList = shouldPinLightList;
1148
1321
  exports.shouldResetAfterIdle = shouldResetAfterIdle;
1149
1322
  exports.traceQueryFieldsQueryKey = traceQueryFieldsQueryKey;
1323
+ exports.traceQueryKey = traceQueryKey;
1150
1324
  exports.traceSpansQueryOptions = traceSpansQueryOptions;
1151
1325
  exports.useBranch = useBranch;
1152
1326
  exports.useCreateFeedback = useCreateFeedback;
@@ -1165,6 +1339,7 @@ exports.useTraceLightSpans = useTraceLightSpans;
1165
1339
  exports.useTraceMetadataFilterFields = useTraceMetadataFilterFields;
1166
1340
  exports.useTraceOrBranchSpans = useTraceOrBranchSpans;
1167
1341
  exports.useTraceQuery = useTraceQuery;
1342
+ exports.useTraceQueryLatest = useTraceQueryLatest;
1168
1343
  exports.useTraceSpans = useTraceSpans;
1169
1344
  exports.useTraceSpansQueries = useTraceSpansQueries;
1170
1345
  exports.useTraceUsage = useTraceUsage;