@burdenoff/microfe-botmanor 2026.1115.2 → 2026.1117.1

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 (53) hide show
  1. package/dist/botlit/components/BotFormFields.js +66 -87
  2. package/dist/botlit/components/BotFormFields.js.map +1 -1
  3. package/dist/botlit/components/EmojiPicker.d.ts +20 -0
  4. package/dist/botlit/components/EmojiPicker.js +42 -0
  5. package/dist/botlit/components/EmojiPicker.js.map +1 -0
  6. package/dist/botlit/components/index.d.ts +1 -0
  7. package/dist/botlit/hooks/internal/allPages.d.ts +2 -0
  8. package/dist/botlit/hooks/internal/allPages.js +25 -0
  9. package/dist/botlit/hooks/internal/allPages.js.map +1 -0
  10. package/dist/botlit/hooks/internal/workspaceGateway.js +33 -32
  11. package/dist/botlit/hooks/internal/workspaceGateway.js.map +1 -1
  12. package/dist/botlit/hooks/useAgents.d.ts +26 -3
  13. package/dist/botlit/hooks/useAgents.js +160 -110
  14. package/dist/botlit/hooks/useAgents.js.map +1 -1
  15. package/dist/botlit/hooks/useBotAgents.d.ts +35 -0
  16. package/dist/botlit/hooks/useBotAgents.js +95 -0
  17. package/dist/botlit/hooks/useBotAgents.js.map +1 -0
  18. package/dist/botlit/hooks/useBots.js +2 -2
  19. package/dist/botlit/hooks/useBots.js.map +1 -1
  20. package/dist/botlit/hooks/useKnowledgeBases.d.ts +13 -0
  21. package/dist/botlit/hooks/useKnowledgeBases.js +77 -58
  22. package/dist/botlit/hooks/useKnowledgeBases.js.map +1 -1
  23. package/dist/botlit/hooks/useMCPServers.js +53 -57
  24. package/dist/botlit/hooks/useMCPServers.js.map +1 -1
  25. package/dist/botlit/pages/AgentBuilderPage.js +848 -425
  26. package/dist/botlit/pages/AgentBuilderPage.js.map +1 -1
  27. package/dist/botlit/pages/AgentDetailPage.js +629 -518
  28. package/dist/botlit/pages/AgentDetailPage.js.map +1 -1
  29. package/dist/botlit/pages/AgentsListPage.js +487 -291
  30. package/dist/botlit/pages/AgentsListPage.js.map +1 -1
  31. package/dist/botlit/pages/KnowledgeBaseDetailPage.js +519 -265
  32. package/dist/botlit/pages/KnowledgeBaseDetailPage.js.map +1 -1
  33. package/dist/botlit/pages/KnowledgeBasesPage.js +269 -130
  34. package/dist/botlit/pages/KnowledgeBasesPage.js.map +1 -1
  35. package/dist/botlit/types/index.d.ts +4 -1
  36. package/dist/botlit/utils/agentDelete.d.ts +5 -0
  37. package/dist/botlit/utils/agentDelete.js +15 -0
  38. package/dist/botlit/utils/agentDelete.js.map +1 -0
  39. package/dist/botlit/utils/agentSettings.d.ts +77 -0
  40. package/dist/botlit/utils/agentSettings.js +78 -0
  41. package/dist/botlit/utils/agentSettings.js.map +1 -0
  42. package/dist/botlit/utils/kbDelete.d.ts +5 -0
  43. package/dist/botlit/utils/kbDelete.js +11 -0
  44. package/dist/botlit/utils/kbDelete.js.map +1 -0
  45. package/dist/botlit/utils/kbSettings.d.ts +41 -0
  46. package/dist/botlit/utils/kbSettings.js +60 -0
  47. package/dist/botlit/utils/kbSettings.js.map +1 -0
  48. package/dist/generated/wspace-operations.d.ts +75 -0
  49. package/dist/generated/wspace-operations.js +60 -48
  50. package/dist/generated/wspace-operations.js.map +1 -1
  51. package/dist/generated/wspace-types.d.ts +66 -0
  52. package/dist/generated/wspace-types.js.map +1 -1
  53. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"useAgents.js","names":["LIST_AGENTS_DOCUMENT","GET_AGENT_DOCUMENT","CREATE_AGENT_DOCUMENT","UPDATE_AGENT_DOCUMENT","DELETE_AGENT_DOCUMENT","LIST_AGENT_VERSIONS_DOCUMENT","PUBLISH_AGENT_VERSION_DOCUMENT","ROLLBACK_AGENT_VERSION_DOCUMENT","LIST_PAGE_SIZE","NO_AGENTS","UPDATE_AGENT_FIELDS","fieldsOf","getWorkspaceClient","client","buildAgentFilter","workspaceId","filter","useAgents","useBotlit","variables","useMemo","useWorkspacePaginatedQuery","data","rows","GET_AGENT_COUNTS_DOCUMENT","useAgentCounts","useWorkspaceQuery","enabled","useAgent","useGatewayClient","setData","useState","loading","setLoading","error","setError","refetch","useCallback","agentId","result","queryError","useEffect","useCreateAgent","state","setState","createdAgent","mutationError","useUpdateAgent","updatedAgent","buildMutationInput","input","useDeleteAgent","deleted","useAgentVersions","versions","a","b","usePublishAgentVersion","published","changelog","useRollbackAgentVersion","rolledBack"],"sources":["../../../src/botlit/hooks/useAgents.ts"],"sourcesContent":["import { gql, type ApolloClient } from '@apollo/client';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\n\nimport type { UpdateBotmanorAgentInput } from '../../generated/wspace-types';\nimport { useBotlit } from '../providers/BotlitProvider';\nimport type { BaseFilter } from '../types';\nimport { buildMutationInput, fieldsOf, type GraphQLInput } from './internal/mutationInput';\nimport {\n useWorkspacePaginatedQuery,\n useWorkspaceQuery,\n type PaginatedQueryResult,\n type QueryResult,\n} from './internal/workspaceGateway';\n\nconst LIST_AGENTS_DOCUMENT = gql`\n query ListBotmanorAgents($filters: BotmanorAgentFilterInput, $pagination: PaginationInput) {\n listBotmanorAgents(filters: $filters, pagination: $pagination) {\n id\n name\n slug\n description\n type\n status\n visibility\n capabilities\n llmModelId\n bucketId\n executionCount\n lastExecutedAt\n specialization\n tagIds\n createdAt\n updatedAt\n createdById\n updatedById\n workspaceId\n }\n }\n`;\n\nconst GET_AGENT_DOCUMENT = gql`\n query GetBotmanorAgent($id: ID!) {\n getBotmanorAgent(id: $id) {\n id\n name\n slug\n description\n type\n status\n visibility\n capabilities\n llmModelId\n bucketId\n currentVersionId\n draftVersionId\n executionCount\n lastExecutedAt\n specialization\n systemPrompt\n temperature\n maxTokens\n maxConcurrentExecutions\n knowledgeBaseIds\n mcpConnectionIds\n workflowIds\n tagIds\n metadata\n createdAt\n updatedAt\n createdById\n updatedById\n workspaceId\n }\n }\n`;\n\nconst CREATE_AGENT_DOCUMENT = gql`\n mutation CreateBotmanorAgent($input: CreateBotmanorAgentInput!) {\n createBotmanorAgent(input: $input) {\n id\n name\n slug\n description\n type\n status\n visibility\n capabilities\n llmModelId\n systemPrompt\n temperature\n maxTokens\n maxConcurrentExecutions\n tagIds\n createdAt\n updatedAt\n workspaceId\n }\n }\n`;\n\nconst UPDATE_AGENT_DOCUMENT = gql`\n mutation UpdateBotmanorAgent($id: ID!, $input: UpdateBotmanorAgentInput!) {\n updateBotmanorAgent(id: $id, input: $input) {\n id\n name\n slug\n description\n type\n status\n visibility\n capabilities\n llmModelId\n systemPrompt\n temperature\n maxTokens\n maxConcurrentExecutions\n knowledgeBaseIds\n mcpConnectionIds\n workflowIds\n tagIds\n metadata\n createdAt\n updatedAt\n updatedById\n workspaceId\n }\n }\n`;\n\nconst DELETE_AGENT_DOCUMENT = gql`\n mutation DeleteBotmanorAgent($id: ID!) {\n deleteBotmanorAgent(id: $id)\n }\n`;\n\n// BOFF-4381: agent version history, publish, and rollback.\nconst LIST_AGENT_VERSIONS_DOCUMENT = gql`\n query ListAgentVersions($agentId: ID!, $pagination: PaginationInput) {\n listAgentVersions(agentId: $agentId, pagination: $pagination) {\n id\n agentId\n version\n status\n changelog\n config\n createdById\n createdAt\n publishedById\n publishedAt\n }\n }\n`;\n\nconst PUBLISH_AGENT_VERSION_DOCUMENT = gql`\n mutation PublishAgentVersion($agentId: ID!, $versionId: ID!, $changelog: String) {\n publishAgentVersion(agentId: $agentId, versionId: $versionId, changelog: $changelog) {\n id\n agentId\n version\n status\n changelog\n publishedById\n publishedAt\n }\n }\n`;\n\nconst ROLLBACK_AGENT_VERSION_DOCUMENT = gql`\n mutation RollbackAgentVersion($agentId: ID!, $targetVersionId: ID!) {\n rollbackAgentVersion(agentId: $agentId, targetVersionId: $targetVersionId) {\n id\n agentId\n version\n status\n changelog\n publishedById\n publishedAt\n }\n }\n`;\n\ntype WorkspaceClient = ApolloClient;\n\nexport interface AgentRecord {\n id: string;\n name: string;\n slug: string;\n description?: string | null;\n type: string;\n status: string;\n visibility?: string | null;\n capabilities?: string[] | null;\n llmModelId?: string | null;\n bucketId?: string | null;\n currentVersionId?: string | null;\n draftVersionId?: string | null;\n executionCount?: number | null;\n lastExecutedAt?: string | null;\n specialization?: string | null;\n systemPrompt?: string | null;\n temperature?: number | null;\n maxTokens?: number | null;\n maxConcurrentExecutions?: number | null;\n knowledgeBaseIds?: string[] | null;\n mcpConnectionIds?: string[] | null;\n workflowIds?: string[] | null;\n tagIds?: string[] | null;\n metadata?: Record<string, unknown> | null;\n createdAt?: string | null;\n updatedAt?: string | null;\n createdById?: string | null;\n updatedById?: string | null;\n workspaceId?: string | null;\n}\n\ninterface ListBotmanorAgentsData {\n listBotmanorAgents: AgentRecord[];\n}\n\nconst LIST_PAGE_SIZE = 100;\nconst NO_AGENTS: AgentRecord[] = [];\n\ninterface GetAgentData {\n getBotmanorAgent: AgentRecord | null;\n}\n\ninterface CreateAgentData {\n createBotmanorAgent: AgentRecord;\n}\n\ninterface UpdateAgentData {\n updateBotmanorAgent: AgentRecord;\n}\n\ninterface DeleteAgentData {\n deleteBotmanorAgent: boolean;\n}\n\nexport interface AgentVersionRecord {\n id: string;\n agentId: string;\n version: string;\n status: 'DRAFT' | 'PUBLISHED' | 'HISTORICAL';\n changelog?: string | null;\n config?: Record<string, unknown> | null;\n createdById?: string | null;\n createdAt?: string | null;\n publishedById?: string | null;\n publishedAt?: string | null;\n}\n\ninterface ListAgentVersionsData {\n listAgentVersions: AgentVersionRecord[];\n}\n\ninterface PublishAgentVersionData {\n publishAgentVersion: AgentVersionRecord;\n}\n\ninterface RollbackAgentVersionData {\n rollbackAgentVersion: AgentVersionRecord;\n}\n\ninterface AgentMutationState<T> {\n data: T | undefined;\n loading: boolean;\n error: Error | undefined;\n}\n\ninterface CreateAgentInput {\n workspaceId: string;\n name: string;\n slug?: string;\n description?: string;\n type: string;\n systemPrompt: string;\n temperature?: number;\n maxTokens?: number;\n capabilities?: string[];\n llmModelId?: string;\n}\n\ninterface UpdateAgentInput {\n agentId: string;\n input: GraphQLInput<UpdateBotmanorAgentInput>;\n}\n\nconst UPDATE_AGENT_FIELDS = fieldsOf<UpdateBotmanorAgentInput>({\n bucketId: true,\n capabilities: true,\n context: true,\n description: true,\n knowledgeBaseIds: true,\n llmModelId: true,\n maxConcurrentExecutions: true,\n maxTokens: true,\n mcpConnectionIds: true,\n metadata: true,\n name: true,\n slug: true,\n specialization: true,\n status: true,\n systemPrompt: true,\n tagIds: true,\n tags: true,\n temperature: true,\n type: true,\n visibility: true,\n workflowIds: true,\n});\n\nfunction getWorkspaceClient(client: unknown): WorkspaceClient {\n return client as WorkspaceClient;\n}\n\nfunction buildAgentFilter(\n workspaceId: string | undefined,\n filter?: BaseFilter\n): Record<string, unknown> | undefined {\n if (!workspaceId && !filter) return undefined;\n\n return {\n workspaceId,\n search: filter?.search,\n status: filter?.status?.[0],\n visibility: filter?.visibility?.[0],\n bucketId: filter?.bucketId,\n };\n}\n\nexport const agentKeys = {\n all: ['agents'] as const,\n lists: () => [...agentKeys.all, 'list'] as const,\n list: (filter?: BaseFilter) => [...agentKeys.lists(), filter] as const,\n details: () => [...agentKeys.all, 'detail'] as const,\n detail: (id: string) => [...agentKeys.details(), id] as const,\n};\n\nexport function useAgents(filter?: BaseFilter): PaginatedQueryResult<AgentRecord[]> {\n const { workspaceId } = useBotlit();\n\n const variables = useMemo(\n () => ({ filters: buildAgentFilter(workspaceId, filter) }),\n [filter, workspaceId]\n );\n\n return useWorkspacePaginatedQuery<ListBotmanorAgentsData, AgentRecord, AgentRecord[]>({\n document: LIST_AGENTS_DOCUMENT,\n variables,\n pageSize: LIST_PAGE_SIZE,\n extractRows: (data) => data?.listBotmanorAgents ?? [],\n select: (rows) => rows,\n fallback: NO_AGENTS,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load agents',\n });\n}\n\n/**\n * Exact agent counts by status for the workspace (BOFF-12426). Unlike\n * `useAgents` this is not capped at one page, so it is the source for\n * dashboard totals. `total` counts every status.\n */\nexport interface AgentCounts {\n total: number;\n draft: number;\n active: number;\n paused: number;\n training: number;\n archived: number;\n}\n\ninterface AgentCountsData {\n getBotmanorAgentCounts?: AgentCounts | null;\n}\n\nconst GET_AGENT_COUNTS_DOCUMENT = gql`\n query GetBotmanorAgentCounts {\n getBotmanorAgentCounts {\n total\n draft\n active\n paused\n training\n archived\n }\n }\n`;\n\nexport function useAgentCounts(enabled = true): QueryResult<AgentCounts | null> {\n const { workspaceId } = useBotlit();\n const variables = useMemo(() => ({}), []);\n\n return useWorkspaceQuery<AgentCountsData, AgentCounts | null>({\n document: GET_AGENT_COUNTS_DOCUMENT,\n variables,\n select: (data) => data?.getBotmanorAgentCounts ?? null,\n fallback: null,\n enabled: enabled && Boolean(workspaceId),\n errorMessage: 'Failed to load agent counts',\n });\n}\n\nexport function useAgent(agentId: string | undefined) {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [data, setData] = useState<AgentRecord | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>();\n\n const refetch = useCallback(async () => {\n if (!agentId) {\n setData(null);\n return;\n }\n\n setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<GetAgentData>({\n query: GET_AGENT_DOCUMENT,\n variables: { id: agentId },\n fetchPolicy: 'network-only',\n });\n setData(result.data?.getBotmanorAgent ?? null);\n } catch (queryError) {\n setError(queryError instanceof Error ? queryError : new Error('Failed to load agent'));\n } finally {\n setLoading(false);\n }\n }, [agentId, client]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nexport function useCreateAgent() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<AgentRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const createAgent = useCallback(\n async (input: CreateAgentInput) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<CreateAgentData>({\n mutation: CREATE_AGENT_DOCUMENT,\n variables: { input },\n });\n\n const createdAgent = result.data?.createBotmanorAgent;\n if (!createdAgent) {\n throw new Error('Failed to create agent');\n }\n\n setState({ data: createdAgent, loading: false, error: undefined });\n return createdAgent;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error ? mutationError : new Error('Failed to create agent');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [createAgent, state] as const;\n}\n\nexport function useUpdateAgent() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<AgentRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const updateAgent = useCallback(\n async ({ agentId, input }: UpdateAgentInput) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<UpdateAgentData>({\n mutation: UPDATE_AGENT_DOCUMENT,\n variables: { id: agentId, input: buildMutationInput(input, UPDATE_AGENT_FIELDS) },\n });\n\n const updatedAgent = result.data?.updateBotmanorAgent;\n if (!updatedAgent) {\n throw new Error('Failed to update agent');\n }\n\n setState({ data: updatedAgent, loading: false, error: undefined });\n return updatedAgent;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error ? mutationError : new Error('Failed to update agent');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [updateAgent, state] as const;\n}\n\nexport function useDeleteAgent() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<boolean>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const deleteAgent = useCallback(\n async (agentId: string) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<DeleteAgentData>({\n mutation: DELETE_AGENT_DOCUMENT,\n variables: { id: agentId },\n });\n\n const deleted = result.data?.deleteBotmanorAgent ?? false;\n setState({ data: deleted, loading: false, error: undefined });\n return deleted;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error ? mutationError : new Error('Failed to delete agent');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [deleteAgent, state] as const;\n}\n\n// ============================================================================\n// VERSIONING (BOFF-4381) — version history, publish, rollback\n// ============================================================================\n\nexport function useAgentVersions(agentId: string | undefined) {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [data, setData] = useState<AgentVersionRecord[]>([]);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>();\n\n const refetch = useCallback(async () => {\n if (!agentId) {\n setData([]);\n return;\n }\n\n setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<ListAgentVersionsData>({\n query: LIST_AGENT_VERSIONS_DOCUMENT,\n variables: { agentId, pagination: { limit: 50, offset: 0 } },\n fetchPolicy: 'network-only',\n });\n const versions = result.data?.listAgentVersions ?? [];\n // Newest first, regardless of what the server returned.\n setData(\n [...versions].sort((a, b) =>\n a.createdAt && b.createdAt ? b.createdAt.localeCompare(a.createdAt) : 0\n )\n );\n } catch (queryError) {\n setError(\n queryError instanceof Error ? queryError : new Error('Failed to load agent versions')\n );\n } finally {\n setLoading(false);\n }\n }, [agentId, client]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nexport function usePublishAgentVersion() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<AgentVersionRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const publishAgentVersion = useCallback(\n async ({\n agentId,\n versionId,\n changelog,\n }: {\n agentId: string;\n versionId: string;\n changelog?: string;\n }) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<PublishAgentVersionData>({\n mutation: PUBLISH_AGENT_VERSION_DOCUMENT,\n variables: { agentId, versionId, changelog: changelog?.trim() || undefined },\n });\n\n const published = result.data?.publishAgentVersion;\n if (!published) {\n throw new Error('Failed to publish agent version');\n }\n\n setState({ data: published, loading: false, error: undefined });\n return published;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error\n ? mutationError\n : new Error('Failed to publish agent version');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [publishAgentVersion, state] as const;\n}\n\nexport function useRollbackAgentVersion() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<AgentVersionRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const rollbackAgentVersion = useCallback(\n async ({ agentId, targetVersionId }: { agentId: string; targetVersionId: string }) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<RollbackAgentVersionData>({\n mutation: ROLLBACK_AGENT_VERSION_DOCUMENT,\n variables: { agentId, targetVersionId },\n });\n\n const rolledBack = result.data?.rollbackAgentVersion;\n if (!rolledBack) {\n throw new Error('Failed to roll back agent version');\n }\n\n setState({ data: rolledBack, loading: false, error: undefined });\n return rolledBack;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error\n ? mutationError\n : new Error('Failed to roll back agent version');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [rollbackAgentVersion, state] as const;\n}\n"],"mappings":";;;;;;;AAeA,IAAMA,IAAuB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;GA0B1BC,IAAqB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCxBC,IAAwB,CAAG;;;;;;;;;;;;;;;;;;;;;;GAwB3BC,IAAwB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6B3BC,IAAwB,CAAG;;;;GAO3BC,IAA+B,CAAG;;;;;;;;;;;;;;;GAiBlCC,IAAiC,CAAG;;;;;;;;;;;;GAcpCC,IAAkC,CAAG;;;;;;;;;;;;GAoDrCC,IAAiB,KACjBC,IAA2B,CAAC,GAmE5BC,IAAsBC,EAAmC;CAC7D,UAAU;CACV,cAAc;CACd,SAAS;CACT,aAAa;CACb,kBAAkB;CAClB,YAAY;CACZ,yBAAyB;CACzB,WAAW;CACX,kBAAkB;CAClB,UAAU;CAC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,OAAO,KAAA;GAAU,CAAC,GACxDA;EACT,SAASf,GAAe;GACtB,IAAMZ,IACJY,aAAyB,QACrBA,IACA,gBAAI,MAAM,mCAAmC;GAEnD,MADAF,EAAS;IAAE,MAAM,KAAA;IAAW,SAAS;IAAO;GAAM,CAAC,GAC7CV;EACR;CACF,GACA,CAACrB,CAAM,CAGD,GAAsB8B,CAAK;AACrC"}
1
+ {"version":3,"file":"useAgents.js","names":["LIST_AGENTS_DOCUMENT","GET_AGENT_DOCUMENT","CREATE_AGENT_DOCUMENT","UPDATE_AGENT_DOCUMENT","DELETE_AGENT_DOCUMENT","LIST_AGENT_VERSIONS_DOCUMENT","PUBLISH_AGENT_VERSION_DOCUMENT","ROLLBACK_AGENT_VERSION_DOCUMENT","LIST_PAGE_SIZE","NO_AGENTS","UPDATE_AGENT_FIELDS","fieldsOf","throwOperationError","operationError","result","graphqlErrorMessage","fallback","getWorkspaceClient","client","buildAgentFilter","workspaceId","filter","useAgents","useBotlit","variables","useMemo","useWorkspacePaginatedQuery","data","rows","options","GET_AGENT_COUNTS_DOCUMENT","useAgentCounts","useWorkspaceQuery","enabled","GET_AGENT_USAGE_DOCUMENT","useLoadAgentUsage","useGatewayClient","useCallback","agentId","useAgent","setData","useState","loading","setLoading","error","setError","refetch","queryError","useEffect","useCreateAgent","state","setState","createdAgent","mutationError","useUpdateAgent","buildMutationInput","input","updatedAgent","useDeleteAgent","deleted","useAgentVersions","versions","a","b","usePublishAgentVersion","published","changelog","useRollbackAgentVersion","rolledBack"],"sources":["../../../src/botlit/hooks/useAgents.ts"],"sourcesContent":["import { gql, type ApolloClient } from '@apollo/client';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\n\nimport type { UpdateBotmanorAgentInput } from '../../generated/wspace-types';\nimport { useBotlit } from '../providers/BotlitProvider';\nimport type { AgentFilter } from '../types';\nimport { graphqlErrorMessage } from '../utils/errors';\nimport { buildMutationInput, fieldsOf, type GraphQLInput } from './internal/mutationInput';\nimport {\n useWorkspacePaginatedQuery,\n useWorkspaceQuery,\n type PaginatedQueryResult,\n type QueryResult,\n} from './internal/workspaceGateway';\n\nconst LIST_AGENTS_DOCUMENT = gql`\n query ListBotmanorAgents($filters: BotmanorAgentFilterInput, $pagination: PaginationInput) {\n listBotmanorAgents(filters: $filters, pagination: $pagination) {\n id\n name\n slug\n description\n avatar\n type\n status\n visibility\n capabilities\n llmModelId\n bucketId\n executionCount\n lastExecutedAt\n specialization\n tagIds\n knowledgeBaseIds\n createdAt\n updatedAt\n createdById\n updatedById\n workspaceId\n }\n }\n`;\n\nconst GET_AGENT_DOCUMENT = gql`\n query GetBotmanorAgent($id: ID!) {\n getBotmanorAgent(id: $id) {\n id\n name\n slug\n description\n avatar\n type\n status\n visibility\n capabilities\n llmModelId\n bucketId\n currentVersionId\n draftVersionId\n executionCount\n lastExecutedAt\n specialization\n systemPrompt\n temperature\n maxTokens\n maxConcurrentExecutions\n knowledgeBaseIds\n mcpConnectionIds\n workflowIds\n tagIds\n metadata\n createdAt\n updatedAt\n createdById\n updatedById\n workspaceId\n }\n }\n`;\n\nconst CREATE_AGENT_DOCUMENT = gql`\n mutation CreateBotmanorAgent($input: CreateBotmanorAgentInput!) {\n createBotmanorAgent(input: $input) {\n id\n name\n slug\n description\n avatar\n type\n status\n visibility\n capabilities\n llmModelId\n systemPrompt\n temperature\n maxTokens\n maxConcurrentExecutions\n tagIds\n createdAt\n updatedAt\n workspaceId\n }\n }\n`;\n\nconst UPDATE_AGENT_DOCUMENT = gql`\n mutation UpdateBotmanorAgent($id: ID!, $input: UpdateBotmanorAgentInput!) {\n updateBotmanorAgent(id: $id, input: $input) {\n id\n name\n slug\n description\n avatar\n type\n status\n visibility\n capabilities\n llmModelId\n systemPrompt\n temperature\n maxTokens\n maxConcurrentExecutions\n knowledgeBaseIds\n mcpConnectionIds\n workflowIds\n tagIds\n metadata\n createdAt\n updatedAt\n updatedById\n workspaceId\n }\n }\n`;\n\nconst DELETE_AGENT_DOCUMENT = gql`\n mutation DeleteBotmanorAgent($id: ID!) {\n deleteBotmanorAgent(id: $id)\n }\n`;\n\n// BOFF-4381: agent version history, publish, and rollback.\nconst LIST_AGENT_VERSIONS_DOCUMENT = gql`\n query ListAgentVersions($agentId: ID!, $pagination: PaginationInput) {\n listAgentVersions(agentId: $agentId, pagination: $pagination) {\n id\n agentId\n version\n status\n changelog\n config\n createdById\n createdAt\n publishedById\n publishedAt\n }\n }\n`;\n\nconst PUBLISH_AGENT_VERSION_DOCUMENT = gql`\n mutation PublishAgentVersion($agentId: ID!, $versionId: ID!, $changelog: String) {\n publishAgentVersion(agentId: $agentId, versionId: $versionId, changelog: $changelog) {\n id\n agentId\n version\n status\n changelog\n publishedById\n publishedAt\n }\n }\n`;\n\nconst ROLLBACK_AGENT_VERSION_DOCUMENT = gql`\n mutation RollbackAgentVersion($agentId: ID!, $targetVersionId: ID!) {\n rollbackAgentVersion(agentId: $agentId, targetVersionId: $targetVersionId) {\n id\n agentId\n version\n status\n changelog\n publishedById\n publishedAt\n }\n }\n`;\n\ntype WorkspaceClient = ApolloClient;\n\nexport interface AgentRecord {\n id: string;\n name: string;\n slug: string;\n description?: string | null;\n /** Emoji chosen for the agent; null means the default. */\n avatar?: string | null;\n type: string;\n status: string;\n visibility?: string | null;\n capabilities?: string[] | null;\n llmModelId?: string | null;\n bucketId?: string | null;\n currentVersionId?: string | null;\n draftVersionId?: string | null;\n executionCount?: number | null;\n lastExecutedAt?: string | null;\n specialization?: string | null;\n systemPrompt?: string | null;\n temperature?: number | null;\n maxTokens?: number | null;\n maxConcurrentExecutions?: number | null;\n knowledgeBaseIds?: string[] | null;\n mcpConnectionIds?: string[] | null;\n workflowIds?: string[] | null;\n tagIds?: string[] | null;\n metadata?: Record<string, unknown> | null;\n createdAt?: string | null;\n updatedAt?: string | null;\n createdById?: string | null;\n updatedById?: string | null;\n workspaceId?: string | null;\n}\n\ninterface ListBotmanorAgentsData {\n listBotmanorAgents: AgentRecord[];\n}\n\nconst LIST_PAGE_SIZE = 100;\nconst NO_AGENTS: AgentRecord[] = [];\n\ninterface GetAgentData {\n getBotmanorAgent: AgentRecord | null;\n}\n\ninterface CreateAgentData {\n createBotmanorAgent: AgentRecord;\n}\n\ninterface UpdateAgentData {\n updateBotmanorAgent: AgentRecord;\n}\n\ninterface DeleteAgentData {\n deleteBotmanorAgent: boolean;\n}\n\nexport interface AgentVersionRecord {\n id: string;\n agentId: string;\n version: string;\n status: 'DRAFT' | 'PUBLISHED' | 'HISTORICAL';\n changelog?: string | null;\n config?: Record<string, unknown> | null;\n createdById?: string | null;\n createdAt?: string | null;\n publishedById?: string | null;\n publishedAt?: string | null;\n}\n\ninterface ListAgentVersionsData {\n listAgentVersions: AgentVersionRecord[];\n}\n\ninterface PublishAgentVersionData {\n publishAgentVersion: AgentVersionRecord;\n}\n\ninterface RollbackAgentVersionData {\n rollbackAgentVersion: AgentVersionRecord;\n}\n\ninterface AgentMutationState<T> {\n data: T | undefined;\n loading: boolean;\n error: Error | undefined;\n}\n\ninterface CreateAgentInput {\n workspaceId: string;\n name: string;\n slug?: string;\n description?: string;\n avatar?: string;\n type: string;\n systemPrompt: string;\n temperature?: number;\n maxTokens?: number;\n maxConcurrentExecutions?: number;\n capabilities?: string[];\n llmModelId?: string;\n knowledgeBaseIds?: string[];\n mcpConnectionIds?: string[];\n}\n\ninterface UpdateAgentInput {\n agentId: string;\n input: GraphQLInput<UpdateBotmanorAgentInput>;\n}\n\nconst UPDATE_AGENT_FIELDS = fieldsOf<UpdateBotmanorAgentInput>({\n avatar: true,\n bucketId: true,\n capabilities: true,\n context: true,\n description: true,\n knowledgeBaseIds: true,\n llmModelId: true,\n maxConcurrentExecutions: true,\n maxTokens: true,\n mcpConnectionIds: true,\n metadata: true,\n name: true,\n slug: true,\n specialization: true,\n status: true,\n systemPrompt: true,\n tagIds: true,\n tags: true,\n temperature: true,\n type: true,\n visibility: true,\n workflowIds: true,\n});\n\n/**\n * Apollo v4 resolves a mutation with `result.error` set (and no data) when the\n * server answers with a GraphQL error, instead of rejecting. Throw it so the\n * caller sees the server's actionable message (\"An agent named ... already\n * exists\") and not the generic fallback.\n */\nfunction throwOperationError(result: unknown, fallback: string): void {\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw new Error(graphqlErrorMessage(operationError, fallback), { cause: operationError });\n }\n}\n\nfunction getWorkspaceClient(client: unknown): WorkspaceClient {\n return client as WorkspaceClient;\n}\n\nfunction buildAgentFilter(\n workspaceId: string | undefined,\n filter?: AgentFilter\n): Record<string, unknown> | undefined {\n if (!workspaceId && !filter) return undefined;\n\n return {\n workspaceId,\n search: filter?.search,\n status: filter?.status?.[0],\n visibility: filter?.visibility?.[0],\n bucketId: filter?.bucketId,\n };\n}\n\nexport const agentKeys = {\n all: ['agents'] as const,\n lists: () => [...agentKeys.all, 'list'] as const,\n list: (filter?: AgentFilter) => [...agentKeys.lists(), filter] as const,\n details: () => [...agentKeys.all, 'detail'] as const,\n detail: (id: string) => [...agentKeys.details(), id] as const,\n};\n\nexport function useAgents(\n filter?: AgentFilter,\n options?: { enabled?: boolean }\n): PaginatedQueryResult<AgentRecord[]> {\n const { workspaceId } = useBotlit();\n\n const variables = useMemo(\n () => ({ filters: buildAgentFilter(workspaceId, filter) }),\n [filter, workspaceId]\n );\n\n return useWorkspacePaginatedQuery<ListBotmanorAgentsData, AgentRecord, AgentRecord[]>({\n document: LIST_AGENTS_DOCUMENT,\n variables,\n pageSize: LIST_PAGE_SIZE,\n extractRows: (data) => data?.listBotmanorAgents ?? [],\n select: (rows) => rows,\n fallback: NO_AGENTS,\n enabled: Boolean(workspaceId) && options?.enabled !== false,\n errorMessage: 'Failed to load agents',\n });\n}\n\n/**\n * Exact agent counts by status for the workspace (BOFF-12426). Unlike\n * `useAgents` this is not capped at one page, so it is the source for\n * dashboard totals. `total` counts every status.\n */\nexport interface AgentCounts {\n total: number;\n draft: number;\n active: number;\n paused: number;\n training: number;\n archived: number;\n}\n\ninterface AgentCountsData {\n getBotmanorAgentCounts?: AgentCounts | null;\n}\n\nconst GET_AGENT_COUNTS_DOCUMENT = gql`\n query GetBotmanorAgentCounts {\n getBotmanorAgentCounts {\n total\n draft\n active\n paused\n training\n archived\n }\n }\n`;\n\nexport function useAgentCounts(enabled = true): QueryResult<AgentCounts | null> {\n const { workspaceId } = useBotlit();\n const variables = useMemo(() => ({}), []);\n\n return useWorkspaceQuery<AgentCountsData, AgentCounts | null>({\n document: GET_AGENT_COUNTS_DOCUMENT,\n variables,\n select: (data) => data?.getBotmanorAgentCounts ?? null,\n fallback: null,\n enabled: enabled && Boolean(workspaceId),\n errorMessage: 'Failed to load agent counts',\n });\n}\n\n/** What still uses an agent, shown in the delete confirmation (BOFF-12457). */\nexport interface AgentUsage {\n bots: Array<{ id: string; name: string; isDefault: boolean }>;\n a2aConnections: Array<{ id: string; name: string }>;\n workflowIds: string[];\n}\n\ninterface AgentUsageData {\n getBotmanorAgentUsage?: AgentUsage | null;\n}\n\nconst GET_AGENT_USAGE_DOCUMENT = gql`\n query GetBotmanorAgentUsage($id: ID!) {\n getBotmanorAgentUsage(id: $id) {\n bots {\n id\n name\n isDefault\n }\n a2aConnections {\n id\n name\n }\n workflowIds\n }\n }\n`;\n\n/** Returns a function that reads what uses an agent. Reads fresh every time, because a delete is about to rely on it. */\nexport function useLoadAgentUsage() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n\n return useCallback(\n async (agentId: string): Promise<AgentUsage> => {\n const result = await client.query<AgentUsageData>({\n query: GET_AGENT_USAGE_DOCUMENT,\n variables: { id: agentId },\n fetchPolicy: 'network-only',\n });\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw operationError instanceof Error\n ? operationError\n : new Error('Failed to load agent usage');\n }\n return (\n result.data?.getBotmanorAgentUsage ?? { bots: [], a2aConnections: [], workflowIds: [] }\n );\n },\n [client]\n );\n}\n\nexport function useAgent(agentId: string | undefined) {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [data, setData] = useState<AgentRecord | null>(null);\n // Loading from the first render when there is an id to read, so a page never\n // shows \"not found\" (or an empty form) for the frame before the read starts.\n const [loading, setLoading] = useState(Boolean(agentId));\n const [error, setError] = useState<Error | undefined>();\n\n const refetch = useCallback(async () => {\n if (!agentId) {\n setData(null);\n setLoading(false);\n return;\n }\n\n setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<GetAgentData>({\n query: GET_AGENT_DOCUMENT,\n variables: { id: agentId },\n fetchPolicy: 'network-only',\n });\n // Apollo v4 resolves (not rejects) with `result.error` set on GraphQL errors.\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw operationError instanceof Error ? operationError : new Error('Failed to load agent');\n }\n setData(result.data?.getBotmanorAgent ?? null);\n } catch (queryError) {\n setData(null);\n setError(queryError instanceof Error ? queryError : new Error('Failed to load agent'));\n } finally {\n setLoading(false);\n }\n }, [agentId, client]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nexport function useCreateAgent() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<AgentRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const createAgent = useCallback(\n async (input: CreateAgentInput) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<CreateAgentData>({\n mutation: CREATE_AGENT_DOCUMENT,\n variables: { input },\n });\n throwOperationError(result, 'Failed to create agent');\n\n const createdAgent = result.data?.createBotmanorAgent;\n if (!createdAgent) {\n throw new Error('Failed to create agent');\n }\n\n setState({ data: createdAgent, loading: false, error: undefined });\n return createdAgent;\n } catch (mutationError) {\n const error = new Error(graphqlErrorMessage(mutationError, 'Failed to create agent'), {\n cause: mutationError,\n });\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [createAgent, state] as const;\n}\n\nexport function useUpdateAgent() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<AgentRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const updateAgent = useCallback(\n async ({ agentId, input }: UpdateAgentInput) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<UpdateAgentData>({\n mutation: UPDATE_AGENT_DOCUMENT,\n variables: { id: agentId, input: buildMutationInput(input, UPDATE_AGENT_FIELDS) },\n });\n throwOperationError(result, 'Failed to update agent');\n\n const updatedAgent = result.data?.updateBotmanorAgent;\n if (!updatedAgent) {\n throw new Error('Failed to update agent');\n }\n\n setState({ data: updatedAgent, loading: false, error: undefined });\n return updatedAgent;\n } catch (mutationError) {\n const error = new Error(graphqlErrorMessage(mutationError, 'Failed to update agent'), {\n cause: mutationError,\n });\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [updateAgent, state] as const;\n}\n\nexport function useDeleteAgent() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<boolean>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const deleteAgent = useCallback(\n async (agentId: string) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<DeleteAgentData>({\n mutation: DELETE_AGENT_DOCUMENT,\n variables: { id: agentId },\n });\n throwOperationError(result, 'Failed to delete agent');\n\n const deleted = result.data?.deleteBotmanorAgent ?? false;\n setState({ data: deleted, loading: false, error: undefined });\n return deleted;\n } catch (mutationError) {\n const error = new Error(graphqlErrorMessage(mutationError, 'Failed to delete agent'), {\n cause: mutationError,\n });\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [deleteAgent, state] as const;\n}\n\n// ============================================================================\n// VERSIONING (BOFF-4381) — version history, publish, rollback\n// ============================================================================\n\nexport function useAgentVersions(agentId: string | undefined) {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [data, setData] = useState<AgentVersionRecord[]>([]);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>();\n\n const refetch = useCallback(async () => {\n if (!agentId) {\n setData([]);\n return;\n }\n\n setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<ListAgentVersionsData>({\n query: LIST_AGENT_VERSIONS_DOCUMENT,\n variables: { agentId, pagination: { limit: 50, offset: 0 } },\n fetchPolicy: 'network-only',\n });\n const versions = result.data?.listAgentVersions ?? [];\n // Newest first, regardless of what the server returned.\n setData(\n [...versions].sort((a, b) =>\n a.createdAt && b.createdAt ? b.createdAt.localeCompare(a.createdAt) : 0\n )\n );\n } catch (queryError) {\n setError(\n queryError instanceof Error ? queryError : new Error('Failed to load agent versions')\n );\n } finally {\n setLoading(false);\n }\n }, [agentId, client]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nexport function usePublishAgentVersion() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<AgentVersionRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const publishAgentVersion = useCallback(\n async ({\n agentId,\n versionId,\n changelog,\n }: {\n agentId: string;\n versionId: string;\n changelog?: string;\n }) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<PublishAgentVersionData>({\n mutation: PUBLISH_AGENT_VERSION_DOCUMENT,\n variables: { agentId, versionId, changelog: changelog?.trim() || undefined },\n });\n\n const published = result.data?.publishAgentVersion;\n if (!published) {\n throw new Error('Failed to publish agent version');\n }\n\n setState({ data: published, loading: false, error: undefined });\n return published;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error\n ? mutationError\n : new Error('Failed to publish agent version');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [publishAgentVersion, state] as const;\n}\n\nexport function useRollbackAgentVersion() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<AgentVersionRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const rollbackAgentVersion = useCallback(\n async ({ agentId, targetVersionId }: { agentId: string; targetVersionId: string }) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<RollbackAgentVersionData>({\n mutation: ROLLBACK_AGENT_VERSION_DOCUMENT,\n variables: { agentId, targetVersionId },\n });\n\n const rolledBack = result.data?.rollbackAgentVersion;\n if (!rolledBack) {\n throw new Error('Failed to roll back agent version');\n }\n\n setState({ data: rolledBack, loading: false, error: undefined });\n return rolledBack;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error\n ? mutationError\n : new Error('Failed to roll back agent version');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [rollbackAgentVersion, state] as const;\n}\n"],"mappings":";;;;;;;;AAgBA,IAAMA,IAAuB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;GA4B1BC,IAAqB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCxBC,IAAwB,CAAG;;;;;;;;;;;;;;;;;;;;;;;GAyB3BC,IAAwB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8B3BC,IAAwB,CAAG;;;;GAO3BC,IAA+B,CAAG;;;;;;;;;;;;;;;GAiBlCC,IAAiC,CAAG;;;;;;;;;;;;GAcpCC,IAAkC,CAAG;;;;;;;;;;;;GAsDrCC,IAAiB,KACjBC,IAA2B,CAAC,GAuE5BC,IAAsBC,EAAmC;CAC7D,QAAQ;CACR,UAAU;CACV,cAAc;CACd,SAAS;CACT,aAAa;CACb,kBAAkB;CAClB,YAAY;CACZ,yBAAyB;CACzB,WAAW;CACX,kBAAkB;CAClB,UAAU;CACV,MAAM;CACN,MAAM;CACN,gBAAgB;CAChB,QAAQ;CACR,cAAc;CACd,QAAQ;CACR,MAAM;CACN,aAAa;CACb,MAAM;CACN,YAAY;CACZ,aAAa;AACf,CAAC;AAQD,SAASC,EAAoB,GAAiB,GAAwB;CACpE,IAAMC,IAAkBC,EAA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,IAAI,CAACD,GACH,MAAU,MAAM,iCAAiC;GAInD,OADAd,EAAS;IAAE,MAAMc;IAAW,SAAS;IAAO,OAAO,KAAA;GAAU,CAAC,GACvDA;EACT,SAASZ,GAAe;GACtB,IAAMT,IACJS,aAAyB,QACrBA,IACA,gBAAI,MAAM,iCAAiC;GAEjD,MADAF,EAAS;IAAE,MAAM,KAAA;IAAW,SAAS;IAAO;GAAM,CAAC,GAC7CP;EACR;CACF,GACA,CAAC1B,CAAM,CAGD,GAAqBgC,CAAK;AACpC;AAEA,SAAgBiB,IAA0B;CACxC,IAAMjD,IAASD,EAAmBmB,EAAiB,WAAW,CAAC,GACzD,CAACc,GAAOC,KAAYV,EAAiD;EACzE,MAAM,KAAA;EACN,SAAS;EACT,OAAO,KAAA;CACT,CAAC;CA8BD,OAAO,CA5BsBJ,EAC3B,OAAO,EAAE,YAAS,yBAAoE;EACpF,EAAS;GAAE,MAAM,KAAA;GAAW,SAAS;GAAM,OAAO,KAAA;EAAU,CAAC;EAC7D,IAAI;GAMF,IAAM+B,KAAa,MALElD,EAAO,OAAiC;IAC3D,UAAUX;IACV,WAAW;KAAE;KAAS;IAAgB;GACxC,CAAC,EAAA,CAEyB,MAAM;GAChC,IAAI,CAAC6D,GACH,MAAU,MAAM,mCAAmC;GAIrD,OADAjB,EAAS;IAAE,MAAMiB;IAAY,SAAS;IAAO,OAAO,KAAA;GAAU,CAAC,GACxDA;EACT,SAASf,GAAe;GACtB,IAAMT,IACJS,aAAyB,QACrBA,IACA,gBAAI,MAAM,mCAAmC;GAEnD,MADAF,EAAS;IAAE,MAAM,KAAA;IAAW,SAAS;IAAO;GAAM,CAAC,GAC7CP;EACR;CACF,GACA,CAAC1B,CAAM,CAGD,GAAsBgC,CAAK;AACrC"}
@@ -0,0 +1,35 @@
1
+ import { QueryResult } from './internal/workspaceGateway';
2
+ export interface BotAgentLink {
3
+ id: string;
4
+ appId: string;
5
+ agentId: string;
6
+ isActive: boolean;
7
+ priority: number;
8
+ }
9
+ /**
10
+ * Every agent linked to one bot. Disabled until there is a bot and a workspace.
11
+ * It reads all pages (a bot can have more links than one page holds), and stays
12
+ * `loading` until the last one is in, so a page never derives its list from a
13
+ * partial set of links.
14
+ */
15
+ export declare function useBotAgentLinks(botId: string | undefined): QueryResult<BotAgentLink[]>;
16
+ export interface LinkAgentInput {
17
+ botId: string;
18
+ agentId: string;
19
+ }
20
+ /** Links an agent to a bot. */
21
+ export declare function useLinkAgentToBot(): readonly [(input: LinkAgentInput) => Promise<BotAgentLink>, import('./internal/workspaceGateway').MutationState<BotAgentLink>];
22
+ /** Removes a link (the agent itself is untouched). */
23
+ export declare function useUnlinkAgentFromBot(): readonly [(input: string) => Promise<boolean>, import('./internal/workspaceGateway').MutationState<boolean>];
24
+ /**
25
+ * The knowledge bases a bot uses: the ones attached to the agents linked to it
26
+ * (and to its default agent). A bot reaches knowledge only through its agents, so
27
+ * this is what its knowledge page lists. Reads every page of agents, and is
28
+ * `loading` until the links, the bot and every page are in.
29
+ */
30
+ export declare function useBotKnowledgeBaseIds(botId: string | undefined): {
31
+ ids: Set<string>;
32
+ loading: boolean;
33
+ error: Error | undefined;
34
+ refetch: () => void;
35
+ };
@@ -0,0 +1,95 @@
1
+ import { useAgents as e } from "./useAgents.js";
2
+ import { useBot as t } from "./useBots.js";
3
+ import { useAllPagesQuery as n } from "./internal/allPages.js";
4
+ import { useWorkspaceId as r, useWorkspaceMutation as i } from "./internal/workspaceGateway.js";
5
+ import { useEffect as a, useMemo as o } from "react";
6
+ import { gql as s } from "@apollo/client";
7
+ // src/botlit/hooks/useBotAgents.ts
8
+ var c = s`
9
+ query ListBotAgentLinks($filters: AppAgentFilterInput, $pagination: PaginationInput) {
10
+ listAppAgents(filters: $filters, pagination: $pagination) {
11
+ id
12
+ appId
13
+ agentId
14
+ isActive
15
+ priority
16
+ }
17
+ }
18
+ `, l = s`
19
+ mutation LinkAgentToBot($input: CreateAppAgentInput!) {
20
+ createAppAgent(input: $input) {
21
+ id
22
+ appId
23
+ agentId
24
+ isActive
25
+ priority
26
+ }
27
+ }
28
+ `, u = s`
29
+ mutation UnlinkAgentFromBot($id: ID!) {
30
+ deleteAppAgent(id: $id)
31
+ }
32
+ `, d = 100, f = [];
33
+ function p(e) {
34
+ let t = r(), i = o(() => ({ filters: {
35
+ appId: e,
36
+ workspaceId: t
37
+ } }), [e, t]);
38
+ return n({
39
+ document: c,
40
+ variables: i,
41
+ pageSize: d,
42
+ extractRows: (e) => e?.listAppAgents ?? f,
43
+ fallback: f,
44
+ enabled: !!(e && t),
45
+ errorMessage: "Failed to load the agents linked to this bot"
46
+ });
47
+ }
48
+ function m() {
49
+ let e = r();
50
+ return i({
51
+ document: l,
52
+ variables: ({ botId: t, agentId: n }) => ({ input: {
53
+ appId: t,
54
+ agentId: n,
55
+ workspaceId: e
56
+ } }),
57
+ select: (e) => e?.createAppAgent ?? void 0,
58
+ errorMessage: "Failed to link the agent to the bot"
59
+ });
60
+ }
61
+ function h() {
62
+ return i({
63
+ document: u,
64
+ variables: (e) => ({ id: e }),
65
+ select: (e) => e?.deleteAppAgent ?? void 0,
66
+ errorMessage: "Failed to remove the agent from the bot"
67
+ });
68
+ }
69
+ function g(n) {
70
+ let r = p(n), i = t(n), o = e(void 0, { enabled: !!n }), { hasMore: s, loadingMore: c, loadMore: l, error: u } = o;
71
+ a(() => {
72
+ n && s && !c && !u && l();
73
+ }, [
74
+ n,
75
+ s,
76
+ c,
77
+ u,
78
+ l
79
+ ]);
80
+ let d = new Set(r.data.filter((e) => e.isActive).map((e) => e.agentId));
81
+ i.data?.defaultAgentId && d.add(i.data.defaultAgentId);
82
+ let f = /* @__PURE__ */ new Set();
83
+ for (let e of o.data) if (d.has(e.id)) for (let t of e.knowledgeBaseIds ?? []) f.add(t);
84
+ return {
85
+ ids: f,
86
+ loading: r.loading || i.loading || o.loading || o.loadingMore || o.hasMore,
87
+ error: r.error ?? i.error ?? o.error,
88
+ refetch: () => {
89
+ r.refetch(), i.refetch(), o.refetch();
90
+ }
91
+ };
92
+ }
93
+ export { p as useBotAgentLinks, g as useBotKnowledgeBaseIds, m as useLinkAgentToBot, h as useUnlinkAgentFromBot };
94
+
95
+ //# sourceMappingURL=useBotAgents.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useBotAgents.js","names":["LIST_APP_AGENTS_DOCUMENT","CREATE_APP_AGENT_DOCUMENT","DELETE_APP_AGENT_DOCUMENT","LINK_PAGE_SIZE","NO_LINKS","useBotAgentLinks","workspaceId","useWorkspaceId","variables","useMemo","botId","useAllPagesQuery","data","useLinkAgentToBot","useWorkspaceMutation","useUnlinkAgentFromBot","linkId","useBotKnowledgeBaseIds","links","bot","useBot","agents","useAgents","agentsError","hasMore","loadingMore","loadMore","linked","link","ids","agent","kbId"],"sources":["../../../src/botlit/hooks/useBotAgents.ts"],"sourcesContent":["/**\n * Bot-agent links (BOFF-12452)\n * @module botlit/hooks\n *\n * A bot reaches its agents through `AppAgent` links plus an optional default\n * agent. These hooks list a bot's links and add or remove one, so the bot's\n * Agents page can show only that bot's agents and a create-from-bot flow can\n * link what it creates. Setting the default agent is `useUpdateBot`.\n */\n\nimport { gql } from '@apollo/client';\nimport { useEffect, useMemo } from 'react';\n\nimport { useAgents } from './useAgents';\nimport { useBot } from './useBots';\nimport { useAllPagesQuery } from './internal/allPages';\nimport {\n useWorkspaceId,\n useWorkspaceMutation,\n type QueryResult,\n} from './internal/workspaceGateway';\n\nexport interface BotAgentLink {\n id: string;\n appId: string;\n agentId: string;\n isActive: boolean;\n priority: number;\n}\n\ninterface ListAppAgentsData {\n listAppAgents?: BotAgentLink[] | null;\n}\n\ninterface CreateAppAgentData {\n createAppAgent?: BotAgentLink | null;\n}\n\ninterface DeleteAppAgentData {\n deleteAppAgent?: boolean | null;\n}\n\nconst LIST_APP_AGENTS_DOCUMENT = gql`\n query ListBotAgentLinks($filters: AppAgentFilterInput, $pagination: PaginationInput) {\n listAppAgents(filters: $filters, pagination: $pagination) {\n id\n appId\n agentId\n isActive\n priority\n }\n }\n`;\n\nconst CREATE_APP_AGENT_DOCUMENT = gql`\n mutation LinkAgentToBot($input: CreateAppAgentInput!) {\n createAppAgent(input: $input) {\n id\n appId\n agentId\n isActive\n priority\n }\n }\n`;\n\nconst DELETE_APP_AGENT_DOCUMENT = gql`\n mutation UnlinkAgentFromBot($id: ID!) {\n deleteAppAgent(id: $id)\n }\n`;\n\nconst LINK_PAGE_SIZE = 100;\nconst NO_LINKS: BotAgentLink[] = [];\n\n/**\n * Every agent linked to one bot. Disabled until there is a bot and a workspace.\n * It reads all pages (a bot can have more links than one page holds), and stays\n * `loading` until the last one is in, so a page never derives its list from a\n * partial set of links.\n */\nexport function useBotAgentLinks(botId: string | undefined): QueryResult<BotAgentLink[]> {\n const workspaceId = useWorkspaceId();\n const variables = useMemo(\n () => ({ filters: { appId: botId, workspaceId } }),\n [botId, workspaceId]\n );\n\n return useAllPagesQuery<ListAppAgentsData, BotAgentLink>({\n document: LIST_APP_AGENTS_DOCUMENT,\n variables,\n pageSize: LINK_PAGE_SIZE,\n extractRows: (data) => data?.listAppAgents ?? NO_LINKS,\n fallback: NO_LINKS,\n enabled: Boolean(botId && workspaceId),\n errorMessage: 'Failed to load the agents linked to this bot',\n });\n}\n\nexport interface LinkAgentInput {\n botId: string;\n agentId: string;\n}\n\n/** Links an agent to a bot. */\nexport function useLinkAgentToBot() {\n const workspaceId = useWorkspaceId();\n return useWorkspaceMutation<CreateAppAgentData, LinkAgentInput, BotAgentLink>({\n document: CREATE_APP_AGENT_DOCUMENT,\n variables: ({ botId, agentId }) => ({ input: { appId: botId, agentId, workspaceId } }),\n select: (data) => data?.createAppAgent ?? undefined,\n errorMessage: 'Failed to link the agent to the bot',\n });\n}\n\n/** Removes a link (the agent itself is untouched). */\nexport function useUnlinkAgentFromBot() {\n return useWorkspaceMutation<DeleteAppAgentData, string, boolean>({\n document: DELETE_APP_AGENT_DOCUMENT,\n variables: (linkId) => ({ id: linkId }),\n select: (data) => data?.deleteAppAgent ?? undefined,\n errorMessage: 'Failed to remove the agent from the bot',\n });\n}\n\n/**\n * The knowledge bases a bot uses: the ones attached to the agents linked to it\n * (and to its default agent). A bot reaches knowledge only through its agents, so\n * this is what its knowledge page lists. Reads every page of agents, and is\n * `loading` until the links, the bot and every page are in.\n */\nexport function useBotKnowledgeBaseIds(botId: string | undefined): {\n ids: Set<string>;\n loading: boolean;\n error: Error | undefined;\n refetch: () => void;\n} {\n const links = useBotAgentLinks(botId);\n const bot = useBot(botId);\n // Only bot-scoped pages need the agents; the global list must not fetch them.\n const agents = useAgents(undefined, { enabled: Boolean(botId) });\n\n const { hasMore, loadingMore, loadMore, error: agentsError } = agents;\n useEffect(() => {\n if (botId && hasMore && !loadingMore && !agentsError) void loadMore();\n }, [botId, hasMore, loadingMore, agentsError, loadMore]);\n\n // Deactivated links are not used when the bot routes requests.\n const linked = new Set(links.data.filter((link) => link.isActive).map((link) => link.agentId));\n if (bot.data?.defaultAgentId) linked.add(bot.data.defaultAgentId);\n const ids = new Set<string>();\n for (const agent of agents.data) {\n if (linked.has(agent.id)) for (const kbId of agent.knowledgeBaseIds ?? []) ids.add(kbId);\n }\n\n return {\n ids,\n loading: links.loading || bot.loading || agents.loading || agents.loadingMore || agents.hasMore,\n error: links.error ?? bot.error ?? agents.error,\n refetch: () => {\n void links.refetch();\n void bot.refetch();\n void agents.refetch();\n },\n };\n}\n"],"mappings":";;;;;;;AA0CA,IAAMA,IAA2B,CAAG;;;;;;;;;;GAY9BC,IAA4B,CAAG;;;;;;;;;;GAY/BC,IAA4B,CAAG;;;;GAM/BC,IAAiB,KACjBC,IAA2B,CAAC;AAQlC,SAAgBC,EAAiB,GAAwD;CACvF,IAAMC,IAAcC,EAAe,GAC7BC,IAAYC,SACT,EAAE,SAAS;EAAE,OAAOC;EAAO;CAAY,EAAE,IAChD,CAACA,GAAOJ,CAAW,CACrB;CAEA,OAAOK,EAAkD;EACvD,UAAUX;EACV;EACA,UAAUG;EACV,cAAc,MAASS,GAAM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WA,EAAO,eAAeA,EAAO;EACxF,OAAOH,EAAM,SAASC,EAAI,SAASE,EAAO;EAC1C,eAAe;GAGb,AAFAH,EAAW,QAAQ,GACnBC,EAAS,QAAQ,GACjBE,EAAY,QAAQ;EACtB;CACF;AACF"}
@@ -170,8 +170,8 @@ function C(t = !0) {
170
170
  });
171
171
  }
172
172
  function w(e) {
173
- let t = y(u("workspace")), [n, r] = c(null), [i, s] = c(!1), [l, d] = c(), p = a(async () => {
174
- if (!e) r(null);
173
+ let t = y(u("workspace")), [n, r] = c(null), [i, s] = c(!!e), [l, d] = c(), p = a(async () => {
174
+ if (!e) r(null), s(!1);
175
175
  else {
176
176
  s(!0), d(void 0);
177
177
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"useBots.js","names":["LIST_BOT_APPS_DOCUMENT","GET_BOT_APP_DOCUMENT","CREATE_BOT_APP_DOCUMENT","UPDATE_BOT_APP_DOCUMENT","DELETE_BOT_APP_DOCUMENT","LIST_PAGE_SIZE","NO_BOTS","UPDATE_BOT_APP_FIELDS","fieldsOf","getWorkspaceClient","client","buildBotFilter","workspaceId","filter","useBots","useBotlit","variables","useMemo","useWorkspacePaginatedQuery","data","rows","GET_BOT_APP_COUNTS_DOCUMENT","useBotAppCounts","useWorkspaceQuery","enabled","useBot","useGatewayClient","setData","useState","loading","setLoading","error","setError","refetch","useCallback","botId","result","operationError","queryError","useEffect","useCreateBot","state","setState","createdBot","mutationError","useUpdateBot","updatedBot","buildMutationInput","input","useDeleteBot","deleted"],"sources":["../../../src/botlit/hooks/useBots.ts"],"sourcesContent":["import { gql, type ApolloClient } from '@apollo/client';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\n\nimport type { UpdateBotAppInput } from '../../generated/wspace-types';\nimport { useBotlit } from '../providers/BotlitProvider';\nimport type { BaseFilter } from '../types';\nimport { buildMutationInput, fieldsOf, type GraphQLInput } from './internal/mutationInput';\nimport {\n useWorkspacePaginatedQuery,\n useWorkspaceQuery,\n type PaginatedQueryResult,\n type QueryResult,\n} from './internal/workspaceGateway';\n\nconst LIST_BOT_APPS_DOCUMENT = gql`\n query ListBotApps($filters: BotAppFilterInput, $pagination: PaginationInput) {\n listBotApps(filters: $filters, pagination: $pagination) {\n id\n name\n slug\n description\n icon\n type\n status\n visibility\n routingStrategy\n defaultAgentId\n welcomeMessage\n fallbackMessage\n workflowId\n executionCount\n lastExecutedAt\n tagIds\n createdAt\n updatedAt\n createdById\n updatedById\n workspaceId\n }\n }\n`;\n\nconst GET_BOT_APP_DOCUMENT = gql`\n query GetBotApp($id: ID!) {\n getBotApp(id: $id) {\n id\n name\n slug\n description\n icon\n type\n status\n visibility\n routingStrategy\n defaultAgentId\n welcomeMessage\n fallbackMessage\n workflowId\n executionCount\n lastExecutedAt\n tagIds\n createdAt\n updatedAt\n createdById\n updatedById\n workspaceId\n }\n }\n`;\n\nconst CREATE_BOT_APP_DOCUMENT = gql`\n mutation CreateBotApp($input: CreateBotAppInput!) {\n createBotApp(input: $input) {\n id\n name\n slug\n description\n icon\n type\n status\n visibility\n routingStrategy\n defaultAgentId\n workflowId\n tagIds\n createdAt\n updatedAt\n workspaceId\n }\n }\n`;\n\nconst UPDATE_BOT_APP_DOCUMENT = gql`\n mutation UpdateBotApp($id: ID!, $input: UpdateBotAppInput!) {\n updateBotApp(id: $id, input: $input) {\n id\n name\n slug\n description\n icon\n type\n status\n visibility\n routingStrategy\n defaultAgentId\n welcomeMessage\n fallbackMessage\n workflowId\n tagIds\n updatedAt\n updatedById\n workspaceId\n }\n }\n`;\n\nconst DELETE_BOT_APP_DOCUMENT = gql`\n mutation DeleteBotApp($id: ID!) {\n deleteBotApp(id: $id)\n }\n`;\n\ntype WorkspaceClient = ApolloClient;\n\nexport interface BotAppRecord {\n id: string;\n name: string;\n slug: string;\n description?: string | null;\n icon?: string | null;\n type: string;\n status: string;\n visibility?: string | null;\n routingStrategy?: string | null;\n defaultAgentId?: string | null;\n welcomeMessage?: string | null;\n fallbackMessage?: string | null;\n /** Bound FluidGrids workflow definition id — the bot's designed behaviour. */\n workflowId?: string | null;\n executionCount?: number | null;\n lastExecutedAt?: string | null;\n tagIds?: string[] | null;\n createdAt?: string | null;\n updatedAt?: string | null;\n createdById?: string | null;\n updatedById?: string | null;\n workspaceId?: string | null;\n}\n\ninterface ListBotAppsData {\n listBotApps: BotAppRecord[];\n}\n\nconst LIST_PAGE_SIZE = 100;\nconst NO_BOTS: BotAppRecord[] = [];\n\ninterface GetBotAppData {\n getBotApp: BotAppRecord | null;\n}\n\ninterface CreateBotAppData {\n createBotApp: BotAppRecord;\n}\n\ninterface UpdateBotAppData {\n updateBotApp: BotAppRecord;\n}\n\ninterface DeleteBotAppData {\n deleteBotApp: boolean;\n}\n\ninterface BotMutationState<T> {\n data: T | undefined;\n loading: boolean;\n error: Error | undefined;\n}\n\ninterface CreateBotInput {\n workspaceId: string;\n name: string;\n slug?: string;\n type: string;\n routingStrategy?: string;\n description?: string;\n icon?: string;\n}\n\ninterface UpdateBotInput {\n botId: string;\n input: GraphQLInput<UpdateBotAppInput>;\n}\n\nconst UPDATE_BOT_APP_FIELDS = fieldsOf<UpdateBotAppInput>({\n bucketId: true,\n context: true,\n defaultAgentId: true,\n description: true,\n fallbackMessage: true,\n icon: true,\n metadata: true,\n name: true,\n routingStrategy: true,\n slug: true,\n status: true,\n tagIds: true,\n tags: true,\n type: true,\n visibility: true,\n welcomeMessage: true,\n workflowId: true,\n});\n\nfunction getWorkspaceClient(client: unknown): WorkspaceClient {\n return client as WorkspaceClient;\n}\n\nfunction buildBotFilter(\n workspaceId: string | undefined,\n filter?: BaseFilter\n): Record<string, unknown> | undefined {\n if (!workspaceId && !filter) return undefined;\n\n return {\n workspaceId,\n search: filter?.search,\n status: filter?.status?.[0],\n visibility: filter?.visibility?.[0],\n bucketId: filter?.bucketId,\n };\n}\n\nexport const botKeys = {\n all: ['bots'] as const,\n lists: () => [...botKeys.all, 'list'] as const,\n list: (filter?: BaseFilter) => [...botKeys.lists(), filter] as const,\n details: () => [...botKeys.all, 'detail'] as const,\n detail: (id: string) => [...botKeys.details(), id] as const,\n};\n\nexport function useBots(filter?: BaseFilter): PaginatedQueryResult<BotAppRecord[]> {\n const { workspaceId } = useBotlit();\n\n const variables = useMemo(\n () => ({ filters: buildBotFilter(workspaceId, filter) }),\n [filter, workspaceId]\n );\n\n return useWorkspacePaginatedQuery<ListBotAppsData, BotAppRecord, BotAppRecord[]>({\n document: LIST_BOT_APPS_DOCUMENT,\n variables,\n pageSize: LIST_PAGE_SIZE,\n extractRows: (data) => data?.listBotApps ?? [],\n select: (rows) => rows,\n fallback: NO_BOTS,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load bots',\n });\n}\n\n/**\n * Exact bot counts by status for the workspace (BOFF-12426). Unlike `useBots`\n * this is not capped at one page, so it is the source for dashboard totals.\n * `total` counts every status; the dashboard shows `total - archived`.\n */\nexport interface BotAppCounts {\n total: number;\n draft: number;\n active: number;\n paused: number;\n archived: number;\n}\n\ninterface BotAppCountsData {\n getBotAppCounts?: BotAppCounts | null;\n}\n\nconst GET_BOT_APP_COUNTS_DOCUMENT = gql`\n query GetBotAppCounts {\n getBotAppCounts {\n total\n draft\n active\n paused\n archived\n }\n }\n`;\n\nexport function useBotAppCounts(enabled = true): QueryResult<BotAppCounts | null> {\n const { workspaceId } = useBotlit();\n const variables = useMemo(() => ({}), []);\n\n return useWorkspaceQuery<BotAppCountsData, BotAppCounts | null>({\n document: GET_BOT_APP_COUNTS_DOCUMENT,\n variables,\n select: (data) => data?.getBotAppCounts ?? null,\n fallback: null,\n enabled: enabled && Boolean(workspaceId),\n errorMessage: 'Failed to load bot counts',\n });\n}\n\nexport function useBot(botId: string | undefined) {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [data, setData] = useState<BotAppRecord | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>();\n\n const refetch = useCallback(async () => {\n if (!botId) {\n setData(null);\n return;\n }\n\n setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<GetBotAppData>({\n query: GET_BOT_APP_DOCUMENT,\n variables: { id: botId },\n fetchPolicy: 'network-only',\n });\n // Apollo v4 resolves (not rejects) with `result.error` set on GraphQL errors.\n // Without this a FORBIDDEN read looked like \"bot not found\" (BOFF-12436).\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw operationError instanceof Error ? operationError : new Error('Failed to load bot');\n }\n setData(result.data?.getBotApp ?? null);\n } catch (queryError) {\n setData(null);\n setError(queryError instanceof Error ? queryError : new Error('Failed to load bot'));\n } finally {\n setLoading(false);\n }\n }, [botId, client]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nexport function useCreateBot() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<BotMutationState<BotAppRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const createBot = useCallback(\n async (input: CreateBotInput) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<CreateBotAppData>({\n mutation: CREATE_BOT_APP_DOCUMENT,\n variables: { input },\n });\n\n const createdBot = result.data?.createBotApp;\n if (!createdBot) {\n throw new Error('Failed to create bot');\n }\n\n setState({ data: createdBot, loading: false, error: undefined });\n return createdBot;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error ? mutationError : new Error('Failed to create bot');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [createBot, state] as const;\n}\n\nexport function useUpdateBot() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<BotMutationState<BotAppRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const updateBot = useCallback(\n async ({ botId, input }: UpdateBotInput) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<UpdateBotAppData>({\n mutation: UPDATE_BOT_APP_DOCUMENT,\n variables: { id: botId, input: buildMutationInput(input, UPDATE_BOT_APP_FIELDS) },\n });\n\n const updatedBot = result.data?.updateBotApp;\n if (!updatedBot) {\n throw new Error('Failed to update bot');\n }\n\n setState({ data: updatedBot, loading: false, error: undefined });\n return updatedBot;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error ? mutationError : new Error('Failed to update bot');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [updateBot, state] as const;\n}\n\nexport function useDeleteBot() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<BotMutationState<boolean>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const deleteBot = useCallback(\n async (botId: string) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<DeleteBotAppData>({\n mutation: DELETE_BOT_APP_DOCUMENT,\n variables: { id: botId },\n });\n\n const deleted = result.data?.deleteBotApp ?? false;\n setState({ data: deleted, loading: false, error: undefined });\n return deleted;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error ? mutationError : new Error('Failed to delete bot');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [deleteBot, state] as const;\n}\n"],"mappings":";;;;;;;AAeA,IAAMA,IAAyB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;GA4B5BC,IAAuB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;GA4B1BC,IAA0B,CAAG;;;;;;;;;;;;;;;;;;;;GAsB7BC,IAA0B,CAAG;;;;;;;;;;;;;;;;;;;;;;GAwB7BC,IAA0B,CAAG;;;;GAqC7BC,IAAiB,KACjBC,IAA0B,CAAC,GAuC3BC,IAAwBC,EAA4B;CACxD,UAAU;CACV,SAAS;CACT,gBAAgB;CAChB,aAAa;CACb,iBAAiB;CACjB,MAAM;CACN,UAAU;CACV,MAAM;CACN,iBAAiB;CACjB,MAAM;CACN,QAAQ;CACR,QAAQ;CACR,MAAM;CACN,MAAM;CACN,YAAY;CACZ,gB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S;IAAO,OAAO,KAAA;GAAU,CAAC,GACrDA;EACT,SAASN,GAAe;GACtB,IAAMb,IACJa,aAAyB,QAAQA,IAAgB,gBAAI,MAAM,sBAAsB;GAEnF,MADAF,EAAS;IAAE,MAAM,KAAA;IAAW,SAAS;IAAO;GAAM,CAAC,GAC7CX;EACR;CACF,GACA,CAACrB,CAAM,CAGD,GAAW+B,CAAK;AAC1B"}
1
+ {"version":3,"file":"useBots.js","names":["LIST_BOT_APPS_DOCUMENT","GET_BOT_APP_DOCUMENT","CREATE_BOT_APP_DOCUMENT","UPDATE_BOT_APP_DOCUMENT","DELETE_BOT_APP_DOCUMENT","LIST_PAGE_SIZE","NO_BOTS","UPDATE_BOT_APP_FIELDS","fieldsOf","getWorkspaceClient","client","buildBotFilter","workspaceId","filter","useBots","useBotlit","variables","useMemo","useWorkspacePaginatedQuery","data","rows","GET_BOT_APP_COUNTS_DOCUMENT","useBotAppCounts","useWorkspaceQuery","enabled","useBot","useGatewayClient","setData","useState","loading","setLoading","botId","error","setError","refetch","useCallback","result","operationError","queryError","useEffect","useCreateBot","state","setState","createdBot","mutationError","useUpdateBot","updatedBot","buildMutationInput","input","useDeleteBot","deleted"],"sources":["../../../src/botlit/hooks/useBots.ts"],"sourcesContent":["import { gql, type ApolloClient } from '@apollo/client';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\n\nimport type { UpdateBotAppInput } from '../../generated/wspace-types';\nimport { useBotlit } from '../providers/BotlitProvider';\nimport type { BaseFilter } from '../types';\nimport { buildMutationInput, fieldsOf, type GraphQLInput } from './internal/mutationInput';\nimport {\n useWorkspacePaginatedQuery,\n useWorkspaceQuery,\n type PaginatedQueryResult,\n type QueryResult,\n} from './internal/workspaceGateway';\n\nconst LIST_BOT_APPS_DOCUMENT = gql`\n query ListBotApps($filters: BotAppFilterInput, $pagination: PaginationInput) {\n listBotApps(filters: $filters, pagination: $pagination) {\n id\n name\n slug\n description\n icon\n type\n status\n visibility\n routingStrategy\n defaultAgentId\n welcomeMessage\n fallbackMessage\n workflowId\n executionCount\n lastExecutedAt\n tagIds\n createdAt\n updatedAt\n createdById\n updatedById\n workspaceId\n }\n }\n`;\n\nconst GET_BOT_APP_DOCUMENT = gql`\n query GetBotApp($id: ID!) {\n getBotApp(id: $id) {\n id\n name\n slug\n description\n icon\n type\n status\n visibility\n routingStrategy\n defaultAgentId\n welcomeMessage\n fallbackMessage\n workflowId\n executionCount\n lastExecutedAt\n tagIds\n createdAt\n updatedAt\n createdById\n updatedById\n workspaceId\n }\n }\n`;\n\nconst CREATE_BOT_APP_DOCUMENT = gql`\n mutation CreateBotApp($input: CreateBotAppInput!) {\n createBotApp(input: $input) {\n id\n name\n slug\n description\n icon\n type\n status\n visibility\n routingStrategy\n defaultAgentId\n workflowId\n tagIds\n createdAt\n updatedAt\n workspaceId\n }\n }\n`;\n\nconst UPDATE_BOT_APP_DOCUMENT = gql`\n mutation UpdateBotApp($id: ID!, $input: UpdateBotAppInput!) {\n updateBotApp(id: $id, input: $input) {\n id\n name\n slug\n description\n icon\n type\n status\n visibility\n routingStrategy\n defaultAgentId\n welcomeMessage\n fallbackMessage\n workflowId\n tagIds\n updatedAt\n updatedById\n workspaceId\n }\n }\n`;\n\nconst DELETE_BOT_APP_DOCUMENT = gql`\n mutation DeleteBotApp($id: ID!) {\n deleteBotApp(id: $id)\n }\n`;\n\ntype WorkspaceClient = ApolloClient;\n\nexport interface BotAppRecord {\n id: string;\n name: string;\n slug: string;\n description?: string | null;\n icon?: string | null;\n type: string;\n status: string;\n visibility?: string | null;\n routingStrategy?: string | null;\n defaultAgentId?: string | null;\n welcomeMessage?: string | null;\n fallbackMessage?: string | null;\n /** Bound FluidGrids workflow definition id — the bot's designed behaviour. */\n workflowId?: string | null;\n executionCount?: number | null;\n lastExecutedAt?: string | null;\n tagIds?: string[] | null;\n createdAt?: string | null;\n updatedAt?: string | null;\n createdById?: string | null;\n updatedById?: string | null;\n workspaceId?: string | null;\n}\n\ninterface ListBotAppsData {\n listBotApps: BotAppRecord[];\n}\n\nconst LIST_PAGE_SIZE = 100;\nconst NO_BOTS: BotAppRecord[] = [];\n\ninterface GetBotAppData {\n getBotApp: BotAppRecord | null;\n}\n\ninterface CreateBotAppData {\n createBotApp: BotAppRecord;\n}\n\ninterface UpdateBotAppData {\n updateBotApp: BotAppRecord;\n}\n\ninterface DeleteBotAppData {\n deleteBotApp: boolean;\n}\n\ninterface BotMutationState<T> {\n data: T | undefined;\n loading: boolean;\n error: Error | undefined;\n}\n\ninterface CreateBotInput {\n workspaceId: string;\n name: string;\n slug?: string;\n type: string;\n routingStrategy?: string;\n description?: string;\n icon?: string;\n}\n\ninterface UpdateBotInput {\n botId: string;\n input: GraphQLInput<UpdateBotAppInput>;\n}\n\nconst UPDATE_BOT_APP_FIELDS = fieldsOf<UpdateBotAppInput>({\n bucketId: true,\n context: true,\n defaultAgentId: true,\n description: true,\n fallbackMessage: true,\n icon: true,\n metadata: true,\n name: true,\n routingStrategy: true,\n slug: true,\n status: true,\n tagIds: true,\n tags: true,\n type: true,\n visibility: true,\n welcomeMessage: true,\n workflowId: true,\n});\n\nfunction getWorkspaceClient(client: unknown): WorkspaceClient {\n return client as WorkspaceClient;\n}\n\nfunction buildBotFilter(\n workspaceId: string | undefined,\n filter?: BaseFilter\n): Record<string, unknown> | undefined {\n if (!workspaceId && !filter) return undefined;\n\n return {\n workspaceId,\n search: filter?.search,\n status: filter?.status?.[0],\n visibility: filter?.visibility?.[0],\n bucketId: filter?.bucketId,\n };\n}\n\nexport const botKeys = {\n all: ['bots'] as const,\n lists: () => [...botKeys.all, 'list'] as const,\n list: (filter?: BaseFilter) => [...botKeys.lists(), filter] as const,\n details: () => [...botKeys.all, 'detail'] as const,\n detail: (id: string) => [...botKeys.details(), id] as const,\n};\n\nexport function useBots(filter?: BaseFilter): PaginatedQueryResult<BotAppRecord[]> {\n const { workspaceId } = useBotlit();\n\n const variables = useMemo(\n () => ({ filters: buildBotFilter(workspaceId, filter) }),\n [filter, workspaceId]\n );\n\n return useWorkspacePaginatedQuery<ListBotAppsData, BotAppRecord, BotAppRecord[]>({\n document: LIST_BOT_APPS_DOCUMENT,\n variables,\n pageSize: LIST_PAGE_SIZE,\n extractRows: (data) => data?.listBotApps ?? [],\n select: (rows) => rows,\n fallback: NO_BOTS,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load bots',\n });\n}\n\n/**\n * Exact bot counts by status for the workspace (BOFF-12426). Unlike `useBots`\n * this is not capped at one page, so it is the source for dashboard totals.\n * `total` counts every status; the dashboard shows `total - archived`.\n */\nexport interface BotAppCounts {\n total: number;\n draft: number;\n active: number;\n paused: number;\n archived: number;\n}\n\ninterface BotAppCountsData {\n getBotAppCounts?: BotAppCounts | null;\n}\n\nconst GET_BOT_APP_COUNTS_DOCUMENT = gql`\n query GetBotAppCounts {\n getBotAppCounts {\n total\n draft\n active\n paused\n archived\n }\n }\n`;\n\nexport function useBotAppCounts(enabled = true): QueryResult<BotAppCounts | null> {\n const { workspaceId } = useBotlit();\n const variables = useMemo(() => ({}), []);\n\n return useWorkspaceQuery<BotAppCountsData, BotAppCounts | null>({\n document: GET_BOT_APP_COUNTS_DOCUMENT,\n variables,\n select: (data) => data?.getBotAppCounts ?? null,\n fallback: null,\n enabled: enabled && Boolean(workspaceId),\n errorMessage: 'Failed to load bot counts',\n });\n}\n\nexport function useBot(botId: string | undefined) {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [data, setData] = useState<BotAppRecord | null>(null);\n // Loading from the first render when there is a bot to read, so a page that\n // depends on the bot never acts on \"no bot yet\" for the frame before the read.\n const [loading, setLoading] = useState(Boolean(botId));\n const [error, setError] = useState<Error | undefined>();\n\n const refetch = useCallback(async () => {\n if (!botId) {\n setData(null);\n setLoading(false);\n return;\n }\n\n setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<GetBotAppData>({\n query: GET_BOT_APP_DOCUMENT,\n variables: { id: botId },\n fetchPolicy: 'network-only',\n });\n // Apollo v4 resolves (not rejects) with `result.error` set on GraphQL errors.\n // Without this a FORBIDDEN read looked like \"bot not found\" (BOFF-12436).\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw operationError instanceof Error ? operationError : new Error('Failed to load bot');\n }\n setData(result.data?.getBotApp ?? null);\n } catch (queryError) {\n setData(null);\n setError(queryError instanceof Error ? queryError : new Error('Failed to load bot'));\n } finally {\n setLoading(false);\n }\n }, [botId, client]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nexport function useCreateBot() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<BotMutationState<BotAppRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const createBot = useCallback(\n async (input: CreateBotInput) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<CreateBotAppData>({\n mutation: CREATE_BOT_APP_DOCUMENT,\n variables: { input },\n });\n\n const createdBot = result.data?.createBotApp;\n if (!createdBot) {\n throw new Error('Failed to create bot');\n }\n\n setState({ data: createdBot, loading: false, error: undefined });\n return createdBot;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error ? mutationError : new Error('Failed to create bot');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [createBot, state] as const;\n}\n\nexport function useUpdateBot() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<BotMutationState<BotAppRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const updateBot = useCallback(\n async ({ botId, input }: UpdateBotInput) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<UpdateBotAppData>({\n mutation: UPDATE_BOT_APP_DOCUMENT,\n variables: { id: botId, input: buildMutationInput(input, UPDATE_BOT_APP_FIELDS) },\n });\n\n const updatedBot = result.data?.updateBotApp;\n if (!updatedBot) {\n throw new Error('Failed to update bot');\n }\n\n setState({ data: updatedBot, loading: false, error: undefined });\n return updatedBot;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error ? mutationError : new Error('Failed to update bot');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [updateBot, state] as const;\n}\n\nexport function useDeleteBot() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<BotMutationState<boolean>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const deleteBot = useCallback(\n async (botId: string) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<DeleteBotAppData>({\n mutation: DELETE_BOT_APP_DOCUMENT,\n variables: { id: botId },\n });\n\n const deleted = result.data?.deleteBotApp ?? false;\n setState({ data: deleted, loading: false, error: undefined });\n return deleted;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error ? mutationError : new Error('Failed to delete bot');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [deleteBot, state] as const;\n}\n"],"mappings":";;;;;;;AAeA,IAAMA,IAAyB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;GA4B5BC,IAAuB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;GA4B1BC,IAA0B,CAAG;;;;;;;;;;;;;;;;;;;;GAsB7BC,IAA0B,CAAG;;;;;;;;;;;;;;;;;;;;;;GAwB7BC,IAA0B,CAAG;;;;GAqC7BC,IAAiB,KACjBC,IAA0B,CAAC,GAuC3BC,IAAwBC,EAA4B;CACxD,UAAU;CACV,SAAS;CACT,gBAAgB;CAChB,aAAa;CACb,iBAAiB;CACjB,MAAM;CACN,UAAU;CACV,MAAM;CACN,iBAAiB;CACjB,MAAM;CACN,QAAQ;CACR,QAAQ;CACR,MAAM;CACN,MAAM;CACN,YAAY;CACZ,gBAAgB;CAChB,YAAY;AACd,CAAC;AAED,SAASC,EAAmB,GAAkC;CAC5D,OAAOC;AACT;AAEA,SAASC,EACP,GACA,GACqC;CACrC,IAAKC,KA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Y,aAAyB,QAAQA,IAAgB,gBAAI,MAAM,sBAAsB;GAEnF,MADAF,EAAS;IAAE,MAAM,KAAA;IAAW,SAAS;IAAO;GAAM,CAAC,GAC7CV;EACR;CACF,GACA,CAACtB,CAAM,CAGD,GAAW+B,CAAK;AAC1B"}
@@ -55,7 +55,20 @@ export declare const knowledgeBaseKeys: {
55
55
  };
56
56
  export declare function useKnowledgeBases(filter?: BaseFilter): QueryResult<KnowledgeBaseRecord[]>;
57
57
  export declare function useKnowledgeBase(kbId: string | undefined): QueryResult<KnowledgeBaseRecord | null>;
58
+ /** Every document of a knowledge base: all pages, `loading` until the last one is in. */
58
59
  export declare function useKnowledgeDocuments(kbId: string | undefined): QueryResult<KnowledgeDocumentRecord[]>;
60
+ /** What still uses a knowledge base: the live agents that have it attached (BOFF-12472). */
61
+ export interface KnowledgeBaseUsage {
62
+ agents: Array<{
63
+ id: string;
64
+ name: string;
65
+ status: string;
66
+ }>;
67
+ }
68
+ /** Returns a function that reads what uses a knowledge base, fresh each time: a delete is about to rely on it. */
69
+ export declare function useLoadKnowledgeBaseUsage(): (kbId: string) => Promise<KnowledgeBaseUsage>;
70
+ /** Removes one document and its vectors (`removeKnowledgeDocument`). */
71
+ export declare function useRemoveKnowledgeDocument(): readonly [(input: string) => Promise<boolean>, import('./internal/workspaceGateway').MutationState<boolean>];
59
72
  export declare function useCreateKnowledgeBase(): readonly [(input: CreateKnowledgeBaseVariables) => Promise<{
60
73
  id: string;
61
74
  name: string;
@@ -1,9 +1,10 @@
1
- import { CreateKnowledgeBaseDocument as e, GetKnowledgeBaseDocument as t, ListKnowledgeBasesDocument as n, ListKnowledgeDocumentsDocument as r, RebuildKnowledgeBaseIndexDocument as i, UpdateKnowledgeBaseDocument as a } from "../../generated/wspace-operations.js";
2
- import { buildMutationInput as o, fieldsOf as s } from "./internal/mutationInput.js";
3
- import { useWorkspaceId as c, useWorkspaceMutation as l, useWorkspaceQuery as u } from "./internal/workspaceGateway.js";
4
- import { useCallback as d, useMemo as f } from "react";
1
+ import { CreateKnowledgeBaseDocument as e, DeleteKnowledgeBaseDocument as t, GetKnowledgeBaseDocument as n, GetKnowledgeBaseUsageDocument as r, ListKnowledgeBasesDocument as i, ListKnowledgeDocumentsDocument as a, RebuildKnowledgeBaseIndexDocument as o, RemoveKnowledgeDocumentDocument as s, UpdateKnowledgeBaseDocument as c } from "../../generated/wspace-operations.js";
2
+ import { useAllPagesQuery as l } from "./internal/allPages.js";
3
+ import { buildMutationInput as u, fieldsOf as d } from "./internal/mutationInput.js";
4
+ import { useWorkspaceClient as f, useWorkspaceId as p, useWorkspaceMutation as m, useWorkspaceQuery as h } from "./internal/workspaceGateway.js";
5
+ import { useCallback as g, useMemo as _ } from "react";
5
6
  // src/botlit/hooks/useKnowledgeBases.ts
6
- var p = 100, m = s({
7
+ var v = 100, y = d({
7
8
  chunkOverlap: !0,
8
9
  chunkSize: !0,
9
10
  chunkingStrategy: !0,
@@ -14,102 +15,120 @@ var p = 100, m = s({
14
15
  name: !0,
15
16
  vectorStoreDriver: !0,
16
17
  workspaceId: !0
17
- }), h = s({
18
+ }), b = d({
18
19
  chunkOverlap: !0,
19
20
  chunkSize: !0,
20
21
  chunkingStrategy: !0,
21
22
  description: !0,
22
23
  metadata: !0,
23
24
  name: !0
24
- }), g = [], _ = [];
25
- function v(e) {
26
- return e?.listKnowledgeBases ?? g;
25
+ }), x = [], S = [];
26
+ function C(e) {
27
+ return e?.listKnowledgeBases ?? x;
27
28
  }
28
- function y(e) {
29
+ function w(e) {
29
30
  return e?.getKnowledgeBase ?? null;
30
31
  }
31
- function b(e) {
32
- return e?.listKnowledgeDocuments ?? _;
32
+ function T(e) {
33
+ return e?.listKnowledgeDocuments ?? S;
33
34
  }
34
- function x(e) {
35
- let t = c(), r = e?.search, i = f(() => ({
36
- filters: {
37
- workspaceId: t,
38
- search: r || void 0
39
- },
40
- pagination: {
41
- limit: p,
42
- offset: 0
43
- }
44
- }), [t, r]);
45
- return u({
46
- document: n,
47
- variables: i,
48
- select: v,
49
- fallback: g,
35
+ function E(e) {
36
+ let t = p(), n = e?.search, r = _(() => ({ filters: {
37
+ workspaceId: t,
38
+ search: n || void 0
39
+ } }), [t, n]);
40
+ return l({
41
+ document: i,
42
+ variables: r,
43
+ pageSize: v,
44
+ extractRows: C,
45
+ fallback: x,
50
46
  enabled: !!t,
51
47
  errorMessage: "Failed to load knowledge bases"
52
48
  });
53
49
  }
54
- function S(e) {
55
- let n = f(() => ({ id: e ?? "" }), [e]);
56
- return u({
57
- document: t,
58
- variables: n,
59
- select: y,
50
+ function D(e) {
51
+ let t = _(() => ({ id: e ?? "" }), [e]);
52
+ return h({
53
+ document: n,
54
+ variables: t,
55
+ select: w,
60
56
  fallback: null,
61
57
  enabled: !!e,
62
58
  errorMessage: "Failed to load knowledge base"
63
59
  });
64
60
  }
65
- function C(e) {
66
- let t = f(() => ({
67
- knowledgeBaseId: e ?? "",
68
- pagination: {
69
- limit: p,
70
- offset: 0
71
- }
72
- }), [e]);
73
- return u({
74
- document: r,
61
+ function O(e) {
62
+ let t = _(() => ({ knowledgeBaseId: e ?? "" }), [e]);
63
+ return l({
64
+ document: a,
75
65
  variables: t,
76
- select: b,
77
- fallback: _,
66
+ pageSize: v,
67
+ extractRows: T,
68
+ fallback: S,
78
69
  enabled: !!e,
79
70
  errorMessage: "Failed to load knowledge documents"
80
71
  });
81
72
  }
82
- function w() {
83
- let t = c(), n = d((e) => ({ input: o({
73
+ function k() {
74
+ let e = f();
75
+ return g(async (t) => {
76
+ let n = await e.query({
77
+ query: r,
78
+ variables: { id: t },
79
+ fetchPolicy: "network-only"
80
+ }), i = n.error;
81
+ if (i != null) throw i instanceof Error ? i : /* @__PURE__ */ Error("Failed to load what uses this knowledge base");
82
+ return n.data?.getKnowledgeBaseUsage ?? { agents: [] };
83
+ }, [e]);
84
+ }
85
+ function A() {
86
+ return m({
87
+ document: s,
88
+ variables: (e) => ({ id: e }),
89
+ select: (e) => e?.removeKnowledgeDocument,
90
+ errorMessage: "Failed to remove the document"
91
+ });
92
+ }
93
+ function j() {
94
+ let t = p(), n = g((e) => ({ input: u({
84
95
  ...e,
85
96
  workspaceId: t
86
- }, m) }), [t]);
87
- return l({
97
+ }, y) }), [t]);
98
+ return m({
88
99
  document: e,
89
100
  variables: n,
90
101
  select: (e) => e?.createKnowledgeBase,
91
102
  errorMessage: "Failed to create knowledge base"
92
103
  });
93
104
  }
94
- function T() {
95
- return l({
96
- document: a,
105
+ function M() {
106
+ return m({
107
+ document: c,
97
108
  variables: ({ kbId: e, input: t }) => ({
98
109
  id: e,
99
- input: o(t, h)
110
+ input: u(t, b)
100
111
  }),
101
112
  select: (e) => e?.updateKnowledgeBase,
102
113
  errorMessage: "Failed to update knowledge base"
103
114
  });
104
115
  }
105
- function E() {
106
- return l({
107
- document: i,
116
+ function N() {
117
+ return m({
118
+ document: o,
108
119
  variables: (e) => ({ knowledgeBaseId: e }),
109
120
  select: (e) => e?.rebuildKnowledgeBaseIndex,
110
121
  errorMessage: "Failed to rebuild the knowledge base index"
111
122
  });
112
123
  }
113
- export { w as useCreateKnowledgeBase, S as useKnowledgeBase, x as useKnowledgeBases, C as useKnowledgeDocuments, E as useRebuildKnowledgeBaseIndex, T as useUpdateKnowledgeBase };
124
+ function P() {
125
+ return m({
126
+ document: t,
127
+ variables: (e) => ({ id: e }),
128
+ select: (e) => e?.deleteKnowledgeBase,
129
+ errorMessage: "Failed to delete knowledge base"
130
+ });
131
+ }
132
+ export { j as useCreateKnowledgeBase, P as useDeleteKnowledgeBase, D as useKnowledgeBase, E as useKnowledgeBases, O as useKnowledgeDocuments, k as useLoadKnowledgeBaseUsage, N as useRebuildKnowledgeBaseIndex, A as useRemoveKnowledgeDocument, M as useUpdateKnowledgeBase };
114
133
 
115
134
  //# sourceMappingURL=useKnowledgeBases.js.map