@burdenoff/microfe-botmanor 2026.1116.1 → 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.
- package/dist/botlit/hooks/internal/workspaceGateway.js +33 -32
- package/dist/botlit/hooks/internal/workspaceGateway.js.map +1 -1
- package/dist/botlit/hooks/useAgents.d.ts +3 -1
- package/dist/botlit/hooks/useAgents.js +5 -4
- package/dist/botlit/hooks/useAgents.js.map +1 -1
- package/dist/botlit/hooks/useBotAgents.d.ts +12 -0
- package/dist/botlit/hooks/useBotAgents.js +54 -28
- package/dist/botlit/hooks/useBotAgents.js.map +1 -1
- package/dist/botlit/hooks/useKnowledgeBases.d.ts +13 -0
- package/dist/botlit/hooks/useKnowledgeBases.js +76 -53
- package/dist/botlit/hooks/useKnowledgeBases.js.map +1 -1
- package/dist/botlit/pages/AgentBuilderPage.js +229 -213
- package/dist/botlit/pages/AgentBuilderPage.js.map +1 -1
- package/dist/botlit/pages/AgentDetailPage.js +408 -379
- package/dist/botlit/pages/AgentDetailPage.js.map +1 -1
- package/dist/botlit/pages/KnowledgeBaseDetailPage.js +519 -265
- package/dist/botlit/pages/KnowledgeBaseDetailPage.js.map +1 -1
- package/dist/botlit/pages/KnowledgeBasesPage.js +269 -130
- package/dist/botlit/pages/KnowledgeBasesPage.js.map +1 -1
- package/dist/botlit/utils/kbDelete.d.ts +5 -0
- package/dist/botlit/utils/kbDelete.js +11 -0
- package/dist/botlit/utils/kbDelete.js.map +1 -0
- package/dist/botlit/utils/kbSettings.d.ts +41 -0
- package/dist/botlit/utils/kbSettings.js +60 -0
- package/dist/botlit/utils/kbSettings.js.map +1 -0
- package/dist/generated/wspace-operations.d.ts +71 -0
- package/dist/generated/wspace-operations.js +60 -48
- package/dist/generated/wspace-operations.js.map +1 -1
- package/dist/generated/wspace-types.d.ts +23 -0
- package/dist/generated/wspace-types.js.map +1 -1
- package/package.json +1 -1
|
@@ -56,13 +56,14 @@ function f(e) {
|
|
|
56
56
|
refetch: b
|
|
57
57
|
};
|
|
58
58
|
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
59
|
+
var p = [];
|
|
60
|
+
function m(e) {
|
|
61
|
+
let { document: t, variables: i, pageSize: s, enabled: l, errorMessage: f } = e, m = c(), h = d(e.select), g = d(e.extractRows), [_, v] = o([]), y = a([]), [b, x] = o(e.fallback), [S, C] = o(!1), [w, T] = o(!1), [E, D] = o(!0), [O, k] = o(), A = n((e) => {
|
|
62
|
+
y.current = e, v(e), x(h.current(e));
|
|
63
|
+
}, [h]), j = n(async (e, n) => {
|
|
64
|
+
n ? T(!0) : C(!0), k(void 0);
|
|
64
65
|
try {
|
|
65
|
-
let r = await
|
|
66
|
+
let r = await m.query({
|
|
66
67
|
query: t,
|
|
67
68
|
variables: {
|
|
68
69
|
...i,
|
|
@@ -74,47 +75,47 @@ function p(e) {
|
|
|
74
75
|
fetchPolicy: "network-only"
|
|
75
76
|
}), a = r.error;
|
|
76
77
|
if (a != null) throw u(a, f);
|
|
77
|
-
let o =
|
|
78
|
-
|
|
78
|
+
let o = g.current(r.data ?? void 0) ?? [];
|
|
79
|
+
A(n ? [...y.current, ...o] : o), D(o.length < s);
|
|
79
80
|
} catch (e) {
|
|
80
|
-
|
|
81
|
+
k(u(e, f));
|
|
81
82
|
} finally {
|
|
82
|
-
n ?
|
|
83
|
+
n ? T(!1) : C(!1);
|
|
83
84
|
}
|
|
84
85
|
}, [
|
|
85
|
-
|
|
86
|
+
m,
|
|
86
87
|
t,
|
|
87
88
|
i,
|
|
88
89
|
s,
|
|
89
90
|
f,
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
]), j = n(async () => {
|
|
93
|
-
l ? await A(0, !1) : (k([]), E(!0), O(void 0));
|
|
94
|
-
}, [
|
|
95
|
-
l,
|
|
96
|
-
A,
|
|
97
|
-
k
|
|
91
|
+
g,
|
|
92
|
+
A
|
|
98
93
|
]), M = n(async () => {
|
|
99
|
-
l
|
|
94
|
+
l ? await j(0, !1) : (A(p), D(!0), k(void 0));
|
|
100
95
|
}, [
|
|
101
96
|
l,
|
|
102
|
-
|
|
97
|
+
j,
|
|
103
98
|
A
|
|
99
|
+
]), N = n(async () => {
|
|
100
|
+
l && !E && await j(y.current.length, !0);
|
|
101
|
+
}, [
|
|
102
|
+
l,
|
|
103
|
+
E,
|
|
104
|
+
j
|
|
104
105
|
]);
|
|
105
106
|
return r(() => {
|
|
106
|
-
|
|
107
|
-
}, [
|
|
108
|
-
data:
|
|
109
|
-
loading:
|
|
110
|
-
loadingMore:
|
|
111
|
-
hasMore: !
|
|
112
|
-
error:
|
|
113
|
-
refetch:
|
|
114
|
-
loadMore:
|
|
107
|
+
M();
|
|
108
|
+
}, [M]), {
|
|
109
|
+
data: b,
|
|
110
|
+
loading: S,
|
|
111
|
+
loadingMore: w,
|
|
112
|
+
hasMore: !E,
|
|
113
|
+
error: O,
|
|
114
|
+
refetch: M,
|
|
115
|
+
loadMore: N
|
|
115
116
|
};
|
|
116
117
|
}
|
|
117
|
-
function
|
|
118
|
+
function h(e) {
|
|
118
119
|
let { document: t, errorMessage: r } = e, i = c(), a = d(e.variables), s = d(e.select), [l, f] = o({
|
|
119
120
|
data: void 0,
|
|
120
121
|
loading: !1,
|
|
@@ -155,6 +156,6 @@ function m(e) {
|
|
|
155
156
|
a
|
|
156
157
|
]), l];
|
|
157
158
|
}
|
|
158
|
-
export { c as useWorkspaceClient, l as useWorkspaceId,
|
|
159
|
+
export { c as useWorkspaceClient, l as useWorkspaceId, h as useWorkspaceMutation, m as useWorkspacePaginatedQuery, f as useWorkspaceQuery };
|
|
159
160
|
|
|
160
161
|
//# sourceMappingURL=workspaceGateway.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspaceGateway.js","names":["useWorkspaceClient","useGatewayClient","useWorkspaceId","useBotlit","toError","message","extractGraphqlFailureMessage","cause","fallbackMessage","useLatest","ref","useRef","value","useLayoutEffect","useWorkspaceQuery","options","client","selectRef","fallbackRef","data","setData","useState","loading","setLoading","error","setError","refetch","useCallback","enabled","result","document","operationError","errorMessage","queryError","variables","useEffect","useWorkspacePaginatedQuery","extractRowsRef","rows","setRows","rowsRef","loadingMore","setLoadingMore","exhausted","setExhausted","replaceRows","next","fetchPage","append","pageSize","pageRows","loadMore","useWorkspaceMutation","variablesRef","state","setState","input","selected","mutationError","failure"],"sources":["../../../../src/botlit/hooks/internal/workspaceGateway.ts"],"sourcesContent":["/**\n * Workspace gateway hook primitives\n * @module botlit/hooks/internal\n *\n * Every BotManor hook talks to the workspace public gateway through the Apollo\n * client the shell installs (`useGatewayClient('workspace')`) — never through a\n * client of its own. These primitives capture the exact shape used by the\n * reference hooks (`useAgents`, `useBots`): `network-only` reads, an explicit\n * `Error` in state rather than a thrown promise, and a `refetch` the caller can\n * run after a mutation.\n */\n\nimport type { ApolloClient, DocumentNode } from '@apollo/client';\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\n\nimport { useBotlit } from '../../providers/BotlitProvider';\nimport { extractGraphqlFailureMessage } from '../../utils/errors';\n\nexport type WorkspaceClient = ApolloClient;\n\n/** Apollo client for the workspace gateway, provided by the host shell. */\nexport function useWorkspaceClient(): WorkspaceClient {\n return useGatewayClient('workspace');\n}\n\n/** Current workspace id from the BotManor context (undefined until the shell resolves it). */\nexport function useWorkspaceId(): string | undefined {\n return useBotlit().workspaceId;\n}\n\nexport interface QueryResult<T> {\n data: T;\n loading: boolean;\n /** Set only when the request FAILED. An empty `data` with no `error` means \"no records yet\". */\n error: Error | undefined;\n refetch: () => Promise<void>;\n}\n\nexport interface PaginatedQueryResult<T> extends QueryResult<T> {\n /** True while the next page is being appended. */\n loadingMore: boolean;\n /**\n * True when the most recent page came back full, i.e. another page may\n * exist. False before the first page resolves and once a short page\n * (or an empty one) marks the end of the list.\n */\n hasMore: boolean;\n /**\n * Fetches the next page (current row count as offset) and appends it.\n * No-op while a fetch is in flight or when `hasMore` is false.\n */\n loadMore: () => Promise<void>;\n}\n\nexport interface MutationState<T> {\n data: T | undefined;\n loading: boolean;\n error: Error | undefined;\n}\n\n/**\n * Normalises any mutation failure to an Error with the server's\n * user-actionable message where one exists.\n *\n * Apollo Client v4 does not reject with a plain Error: failures arrive as\n * `{ networkError }` / `{ graphQLErrors }` objects, and the batched fetch\n * layer attaches the structured GraphQL errors as `.errors` on the\n * networkError. `extractGraphqlFailureMessage` unwraps all of those; only\n * when nothing user-actionable is present do we fall back to the hook's\n * generic `errorMessage`.\n */\nfunction toError(cause: unknown, fallbackMessage: string): Error {\n const message = extractGraphqlFailureMessage(cause);\n if (message) {\n // Preserve the original rejection on the chain so error monitoring can\n // still reach the structured GraphQL errors (extensions.code, requestId…).\n return new Error(message, { cause });\n }\n if (cause instanceof Error) return cause;\n return new Error(fallbackMessage, { cause });\n}\n\n/** Keeps a mutable ref pointing at the latest value without re-running effects. */\nfunction useLatest<T>(value: T): { readonly current: T } {\n const ref = useRef(value);\n useLayoutEffect(() => {\n ref.current = value;\n }, [value]);\n return ref;\n}\n\nexport interface WorkspaceQueryOptions<TData, TResult> {\n /** Generated GraphQL document (see `src/generated/wspace-operations.ts`). */\n document: DocumentNode;\n /** Must be referentially stable — memoize at the call site. */\n variables: Record<string, unknown> | undefined;\n /** Projects the raw payload onto the record shape the UI consumes. */\n select: (data: TData | undefined) => TResult;\n /** Value held while disabled or before the first successful read. */\n fallback: TResult;\n /** When false the request is skipped (e.g. no workspace id / no entity id yet). */\n enabled: boolean;\n /** Used when the thrown value is not an Error. */\n errorMessage: string;\n}\n\n/**\n * Reads from the workspace gateway and keeps `{ data, loading, error, refetch }`\n * in sync. `error` is reserved for real failures so callers can tell an empty\n * collection apart from a failed request.\n */\nexport function useWorkspaceQuery<TData, TResult>(\n options: WorkspaceQueryOptions<TData, TResult>\n): QueryResult<TResult> {\n const { document, variables, enabled, errorMessage } = options;\n const client = useWorkspaceClient();\n const selectRef = useLatest(options.select);\n const fallbackRef = useLatest(options.fallback);\n\n const [data, setData] = useState<TResult>(options.fallback);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>();\n\n const refetch = useCallback(async () => {\n if (!enabled) {\n setData(fallbackRef.current);\n setError(undefined);\n return;\n }\n\n setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<TData>({\n query: document,\n variables,\n fetchPolicy: 'network-only',\n });\n // Apollo v4 resolves (not rejects) with `result.error` set on GraphQL\n // errors — same handling as useWorkspaceMutation.\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw toError(operationError, errorMessage);\n }\n setData(selectRef.current(result.data ?? undefined));\n } catch (queryError) {\n setData(fallbackRef.current);\n setError(toError(queryError, errorMessage));\n } finally {\n setLoading(false);\n }\n // fallbackRef/selectRef are stable refs by construction\n }, [client, document, variables, enabled, errorMessage, fallbackRef, selectRef]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nexport interface WorkspacePaginatedQueryOptions<TData, TRow, TResult> {\n /** Generated GraphQL document (see `src/generated/wspace-operations.ts`). */\n document: DocumentNode;\n /**\n * Base variables (filters, ids, …) WITHOUT `pagination` — the hook adds\n * `{ limit: pageSize, offset }` per fetch. Must be referentially stable;\n * a new identity resets the accumulation back to page one.\n */\n variables: Record<string, unknown> | undefined;\n /** Page size for each fetch. */\n pageSize: number;\n /** Extracts the raw row list from a page payload; missing data yields []. */\n extractRows: (data: TData | undefined) => TRow[] | undefined;\n /** Projects the ACCUMULATED raw rows onto the record shape the UI consumes. */\n select: (rows: TRow[]) => TResult;\n /** Value held while disabled or before the first successful read. */\n fallback: TResult;\n /** When false the request is skipped (e.g. no workspace id yet). */\n enabled: boolean;\n /** Used when the thrown value is not an Error. */\n errorMessage: string;\n}\n\n/**\n * Offset-paginated variant of `useWorkspaceQuery` for unbounded lists.\n *\n * `refetch()` restarts at offset 0 and REPLACES the accumulated rows;\n * `loadMore()` fetches the next page and appends it. A page that returns\n * fewer rows than `pageSize` marks the list exhausted (`hasMore` false).\n * `select` runs over the accumulated raw rows, so client-side narrowing\n * (e.g. executions search) sees every loaded page, not just the last one.\n */\nexport function useWorkspacePaginatedQuery<TData, TRow, TResult>(\n options: WorkspacePaginatedQueryOptions<TData, TRow, TResult>\n): PaginatedQueryResult<TResult> {\n const { document, variables, pageSize, enabled, errorMessage } = options;\n const client = useWorkspaceClient();\n const selectRef = useLatest(options.select);\n const extractRowsRef = useLatest(options.extractRows);\n\n const [rows, setRows] = useState<TRow[]>([]);\n const rowsRef = useRef<TRow[]>([]);\n const [data, setData] = useState<TResult>(options.fallback);\n const [loading, setLoading] = useState(false);\n const [loadingMore, setLoadingMore] = useState(false);\n const [exhausted, setExhausted] = useState(true);\n const [error, setError] = useState<Error | undefined>();\n\n const replaceRows = useCallback(\n (next: TRow[]) => {\n rowsRef.current = next;\n setRows(next);\n setData(selectRef.current(next));\n },\n [selectRef]\n );\n\n const fetchPage = useCallback(\n async (offset: number, append: boolean) => {\n if (append) setLoadingMore(true);\n else setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<TData>({\n query: document,\n variables: { ...variables, pagination: { limit: pageSize, offset } },\n fetchPolicy: 'network-only',\n });\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw toError(operationError, errorMessage);\n }\n const pageRows = extractRowsRef.current(result.data ?? undefined) ?? [];\n replaceRows(append ? [...rowsRef.current, ...pageRows] : pageRows);\n setExhausted(pageRows.length < pageSize);\n } catch (queryError) {\n setError(toError(queryError, errorMessage));\n } finally {\n if (append) setLoadingMore(false);\n else setLoading(false);\n }\n },\n [client, document, variables, pageSize, errorMessage, extractRowsRef, replaceRows]\n );\n\n const refetch = useCallback(async () => {\n if (!enabled) {\n replaceRows([]);\n setExhausted(true);\n setError(undefined);\n return;\n }\n await fetchPage(0, false);\n }, [enabled, fetchPage, replaceRows]);\n\n const loadMore = useCallback(async () => {\n if (!enabled || exhausted) return;\n await fetchPage(rowsRef.current.length, true);\n }, [enabled, exhausted, fetchPage]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, loadingMore, hasMore: !exhausted, error, refetch, loadMore };\n}\n\nexport interface WorkspaceMutationOptions<TData, TInput, TResult> {\n /** Generated GraphQL document (see `src/generated/wspace-operations.ts`). */\n document: DocumentNode;\n /** Maps the caller's input onto GraphQL variables. */\n variables: (input: TInput) => Record<string, unknown>;\n /** Projects the raw payload onto the record shape the UI consumes. */\n select: (data: TData | undefined) => TResult | undefined;\n /** Thrown (and stored) when the payload is missing or the request fails. */\n errorMessage: string;\n}\n\n/**\n * Writes to the workspace gateway. Returns the `[mutate, state]` tuple used by\n * the reference hooks. `mutate` REJECTS on failure so callers cannot mistake a\n * failed write for a successful one.\n */\nexport function useWorkspaceMutation<TData, TInput, TResult>(\n options: WorkspaceMutationOptions<TData, TInput, TResult>\n): readonly [(input: TInput) => Promise<TResult>, MutationState<TResult>] {\n const { document, errorMessage } = options;\n const client = useWorkspaceClient();\n const variablesRef = useLatest(options.variables);\n const selectRef = useLatest(options.select);\n\n const [state, setState] = useState<MutationState<TResult>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const mutate = useCallback(\n async (input: TInput): Promise<TResult> => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<TData>({\n mutation: document,\n variables: variablesRef.current(input),\n });\n // Apollo v4 does not reject on GraphQL errors by default: the mutation\n // RESOLVES with `data` undefined and the failure on `result.error`\n // (CombinedGraphQLErrors / networkError). Surface it like a rejection\n // so callers see the server's field-level message, not the fallback.\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw toError(operationError, errorMessage);\n }\n const selected = selectRef.current(result.data ?? undefined);\n if (selected === undefined) {\n throw new Error(errorMessage);\n }\n setState({ data: selected, loading: false, error: undefined });\n return selected;\n } catch (mutationError) {\n const failure = toError(mutationError, errorMessage);\n setState({ data: undefined, loading: false, error: failure });\n throw failure;\n }\n },\n [client, document, errorMessage, selectRef, variablesRef]\n );\n\n return [mutate, state] as const;\n}\n"],"mappings":";;;;;AAsBA,SAAgBA,IAAsC;CACpD,OAAOC,EAAiB,WAAW;AACrC;AAGA,SAAgBC,IAAqC;CACnD,OAAOC,EAAU,CAAC,CAAC;AACrB;AA2CA,SAASC,EAAQ,GAAgB,GAAgC;CAC/D,IAAMC,IAAUC,EAA6BC,CAAK;CAOlD,OANIF,IAGS,MAAMA,GAAS,EAAE,SAAM,CAAC,IAEjCE,aAAiB,QAAcA,IACxB,MAAMC,GAAiB,EAAE,SAAM,CAAC;AAC7C;AAGA,SAASC,EAAa,GAAmC;CACvD,IAAMC,IAAMC,EAAOC,CAAK;CAIxB,OAHAC,QAAsB;EACpB,EAAI,UAAUD;CAChB,GAAG,CAACA,CAAK,CAAC,GACHF;AACT;AAsBA,SAAgBI,EACd,GACsB;CACtB,IAAM,EAAE,aAAU,cAAW,YAAS,oBAAiBC,GACjDC,IAAShB,EAAmB,GAC5BiB,IAAYR,EAAUM,EAAQ,MAAM,GACpCG,IAAcT,EAAUM,EAAQ,QAAQ,GAExC,CAACI,GAAMC,KAAWC,EAAkBN,EAAQ,QAAQ,GACpD,CAACO,GAASC,KAAcF,EAAS,EAAK,GACtC,CAACG,GAAOC,KAAYJ,EAA4B,GAEhDK,IAAUC,EAAY,YAAY;EACtC,IAAI,CAACC,GAEH,AADAR,EAAQF,EAAY,OAAO,GAC3BO,EAAS,KAAA,CAAS;OAIpB;GACA,AADAF,EAAW,EAAI,GACfE,EAAS,KAAA,CAAS;GAClB,IAAI;IACF,IAAMI,IAAS,MAAMb,EAAO,MAAa;KACvC,OAAOc;KACP;KACA,aAAa;IACf,CAAC,GAGKC,IAAkBF,EAA+B;IACvD,IAAIE,KAAkB,MACpB,MAAM3B,EAAQ2B,GAAgBC,CAAY;IAE5C,EAAQf,EAAU,QAAQY,EAAO,QAAQ,KAAA,CAAS,CAAC;GACrD,SAASI,GAAY;IAE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AM,KAAA;GAAW,SAAS;GAAM,OAAO,KAAA;EAAU,CAAC;EAC7D,IAAI;GACF,IAAME,IAAS,MAAMb,EAAO,OAAc;IACxC,UAAUc;IACV,WAAWuB,EAAa,QAAQG,CAAK;GACvC,CAAC,GAKKzB,IAAkBF,EAA+B;GACvD,IAAIE,KAAkB,MACpB,MAAM3B,EAAQ2B,GAAgBC,CAAY;GAE5C,IAAMyB,IAAWxC,EAAU,QAAQY,EAAO,QAAQ,KAAA,CAAS;GAC3D,IAAI4B,MAAa,KAAA,GACf,MAAU,MAAMzB,CAAY;GAG9B,OADAuB,EAAS;IAAE,MAAME;IAAU,SAAS;IAAO,OAAO,KAAA;GAAU,CAAC,GACtDA;EACT,SAASC,GAAe;GACtB,IAAMC,IAAUvD,EAAQsD,GAAe1B,CAAY;GAEnD,MADAuB,EAAS;IAAE,MAAM,KAAA;IAAW,SAAS;IAAO,OAAOI;GAAQ,CAAC,GACtDA;EACR;CACF,GACA;EAAC3C;EAAQc;EAAUE;EAAcf;EAAWoC;CAAY,CAGlD,GAAQC,CAAK;AACvB"}
|
|
1
|
+
{"version":3,"file":"workspaceGateway.js","names":["useWorkspaceClient","useGatewayClient","useWorkspaceId","useBotlit","toError","message","extractGraphqlFailureMessage","cause","fallbackMessage","useLatest","ref","useRef","value","useLayoutEffect","useWorkspaceQuery","options","client","selectRef","fallbackRef","data","setData","useState","loading","setLoading","error","setError","refetch","useCallback","enabled","result","document","operationError","errorMessage","queryError","variables","useEffect","NO_ROWS","useWorkspacePaginatedQuery","extractRowsRef","rows","setRows","rowsRef","loadingMore","setLoadingMore","exhausted","setExhausted","replaceRows","next","fetchPage","append","pageSize","pageRows","loadMore","useWorkspaceMutation","variablesRef","state","setState","input","selected","mutationError","failure"],"sources":["../../../../src/botlit/hooks/internal/workspaceGateway.ts"],"sourcesContent":["/**\n * Workspace gateway hook primitives\n * @module botlit/hooks/internal\n *\n * Every BotManor hook talks to the workspace public gateway through the Apollo\n * client the shell installs (`useGatewayClient('workspace')`) — never through a\n * client of its own. These primitives capture the exact shape used by the\n * reference hooks (`useAgents`, `useBots`): `network-only` reads, an explicit\n * `Error` in state rather than a thrown promise, and a `refetch` the caller can\n * run after a mutation.\n */\n\nimport type { ApolloClient, DocumentNode } from '@apollo/client';\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\n\nimport { useBotlit } from '../../providers/BotlitProvider';\nimport { extractGraphqlFailureMessage } from '../../utils/errors';\n\nexport type WorkspaceClient = ApolloClient;\n\n/** Apollo client for the workspace gateway, provided by the host shell. */\nexport function useWorkspaceClient(): WorkspaceClient {\n return useGatewayClient('workspace');\n}\n\n/** Current workspace id from the BotManor context (undefined until the shell resolves it). */\nexport function useWorkspaceId(): string | undefined {\n return useBotlit().workspaceId;\n}\n\nexport interface QueryResult<T> {\n data: T;\n loading: boolean;\n /** Set only when the request FAILED. An empty `data` with no `error` means \"no records yet\". */\n error: Error | undefined;\n refetch: () => Promise<void>;\n}\n\nexport interface PaginatedQueryResult<T> extends QueryResult<T> {\n /** True while the next page is being appended. */\n loadingMore: boolean;\n /**\n * True when the most recent page came back full, i.e. another page may\n * exist. False before the first page resolves and once a short page\n * (or an empty one) marks the end of the list.\n */\n hasMore: boolean;\n /**\n * Fetches the next page (current row count as offset) and appends it.\n * No-op while a fetch is in flight or when `hasMore` is false.\n */\n loadMore: () => Promise<void>;\n}\n\nexport interface MutationState<T> {\n data: T | undefined;\n loading: boolean;\n error: Error | undefined;\n}\n\n/**\n * Normalises any mutation failure to an Error with the server's\n * user-actionable message where one exists.\n *\n * Apollo Client v4 does not reject with a plain Error: failures arrive as\n * `{ networkError }` / `{ graphQLErrors }` objects, and the batched fetch\n * layer attaches the structured GraphQL errors as `.errors` on the\n * networkError. `extractGraphqlFailureMessage` unwraps all of those; only\n * when nothing user-actionable is present do we fall back to the hook's\n * generic `errorMessage`.\n */\nfunction toError(cause: unknown, fallbackMessage: string): Error {\n const message = extractGraphqlFailureMessage(cause);\n if (message) {\n // Preserve the original rejection on the chain so error monitoring can\n // still reach the structured GraphQL errors (extensions.code, requestId…).\n return new Error(message, { cause });\n }\n if (cause instanceof Error) return cause;\n return new Error(fallbackMessage, { cause });\n}\n\n/** Keeps a mutable ref pointing at the latest value without re-running effects. */\nfunction useLatest<T>(value: T): { readonly current: T } {\n const ref = useRef(value);\n useLayoutEffect(() => {\n ref.current = value;\n }, [value]);\n return ref;\n}\n\nexport interface WorkspaceQueryOptions<TData, TResult> {\n /** Generated GraphQL document (see `src/generated/wspace-operations.ts`). */\n document: DocumentNode;\n /** Must be referentially stable — memoize at the call site. */\n variables: Record<string, unknown> | undefined;\n /** Projects the raw payload onto the record shape the UI consumes. */\n select: (data: TData | undefined) => TResult;\n /** Value held while disabled or before the first successful read. */\n fallback: TResult;\n /** When false the request is skipped (e.g. no workspace id / no entity id yet). */\n enabled: boolean;\n /** Used when the thrown value is not an Error. */\n errorMessage: string;\n}\n\n/**\n * Reads from the workspace gateway and keeps `{ data, loading, error, refetch }`\n * in sync. `error` is reserved for real failures so callers can tell an empty\n * collection apart from a failed request.\n */\nexport function useWorkspaceQuery<TData, TResult>(\n options: WorkspaceQueryOptions<TData, TResult>\n): QueryResult<TResult> {\n const { document, variables, enabled, errorMessage } = options;\n const client = useWorkspaceClient();\n const selectRef = useLatest(options.select);\n const fallbackRef = useLatest(options.fallback);\n\n const [data, setData] = useState<TResult>(options.fallback);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>();\n\n const refetch = useCallback(async () => {\n if (!enabled) {\n setData(fallbackRef.current);\n setError(undefined);\n return;\n }\n\n setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<TData>({\n query: document,\n variables,\n fetchPolicy: 'network-only',\n });\n // Apollo v4 resolves (not rejects) with `result.error` set on GraphQL\n // errors — same handling as useWorkspaceMutation.\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw toError(operationError, errorMessage);\n }\n setData(selectRef.current(result.data ?? undefined));\n } catch (queryError) {\n setData(fallbackRef.current);\n setError(toError(queryError, errorMessage));\n } finally {\n setLoading(false);\n }\n // fallbackRef/selectRef are stable refs by construction\n }, [client, document, variables, enabled, errorMessage, fallbackRef, selectRef]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\n/** Shared empty page, so a disabled paginated query keeps one stable value. */\nconst NO_ROWS: never[] = [];\n\nexport interface WorkspacePaginatedQueryOptions<TData, TRow, TResult> {\n /** Generated GraphQL document (see `src/generated/wspace-operations.ts`). */\n document: DocumentNode;\n /**\n * Base variables (filters, ids, …) WITHOUT `pagination` — the hook adds\n * `{ limit: pageSize, offset }` per fetch. Must be referentially stable;\n * a new identity resets the accumulation back to page one.\n */\n variables: Record<string, unknown> | undefined;\n /** Page size for each fetch. */\n pageSize: number;\n /** Extracts the raw row list from a page payload; missing data yields []. */\n extractRows: (data: TData | undefined) => TRow[] | undefined;\n /** Projects the ACCUMULATED raw rows onto the record shape the UI consumes. */\n select: (rows: TRow[]) => TResult;\n /** Value held while disabled or before the first successful read. */\n fallback: TResult;\n /** When false the request is skipped (e.g. no workspace id yet). */\n enabled: boolean;\n /** Used when the thrown value is not an Error. */\n errorMessage: string;\n}\n\n/**\n * Offset-paginated variant of `useWorkspaceQuery` for unbounded lists.\n *\n * `refetch()` restarts at offset 0 and REPLACES the accumulated rows;\n * `loadMore()` fetches the next page and appends it. A page that returns\n * fewer rows than `pageSize` marks the list exhausted (`hasMore` false).\n * `select` runs over the accumulated raw rows, so client-side narrowing\n * (e.g. executions search) sees every loaded page, not just the last one.\n */\nexport function useWorkspacePaginatedQuery<TData, TRow, TResult>(\n options: WorkspacePaginatedQueryOptions<TData, TRow, TResult>\n): PaginatedQueryResult<TResult> {\n const { document, variables, pageSize, enabled, errorMessage } = options;\n const client = useWorkspaceClient();\n const selectRef = useLatest(options.select);\n const extractRowsRef = useLatest(options.extractRows);\n\n const [rows, setRows] = useState<TRow[]>([]);\n const rowsRef = useRef<TRow[]>([]);\n const [data, setData] = useState<TResult>(options.fallback);\n const [loading, setLoading] = useState(false);\n const [loadingMore, setLoadingMore] = useState(false);\n const [exhausted, setExhausted] = useState(true);\n const [error, setError] = useState<Error | undefined>();\n\n const replaceRows = useCallback(\n (next: TRow[]) => {\n rowsRef.current = next;\n setRows(next);\n setData(selectRef.current(next));\n },\n [selectRef]\n );\n\n const fetchPage = useCallback(\n async (offset: number, append: boolean) => {\n if (append) setLoadingMore(true);\n else setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<TData>({\n query: document,\n variables: { ...variables, pagination: { limit: pageSize, offset } },\n fetchPolicy: 'network-only',\n });\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw toError(operationError, errorMessage);\n }\n const pageRows = extractRowsRef.current(result.data ?? undefined) ?? [];\n replaceRows(append ? [...rowsRef.current, ...pageRows] : pageRows);\n setExhausted(pageRows.length < pageSize);\n } catch (queryError) {\n setError(toError(queryError, errorMessage));\n } finally {\n if (append) setLoadingMore(false);\n else setLoading(false);\n }\n },\n [client, document, variables, pageSize, errorMessage, extractRowsRef, replaceRows]\n );\n\n const refetch = useCallback(async () => {\n if (!enabled) {\n // The same empty list every time: a disabled query must not change state, or a\n // caller whose client identity changes per render would refetch forever.\n replaceRows(NO_ROWS);\n setExhausted(true);\n setError(undefined);\n return;\n }\n await fetchPage(0, false);\n }, [enabled, fetchPage, replaceRows]);\n\n const loadMore = useCallback(async () => {\n if (!enabled || exhausted) return;\n await fetchPage(rowsRef.current.length, true);\n }, [enabled, exhausted, fetchPage]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, loadingMore, hasMore: !exhausted, error, refetch, loadMore };\n}\n\nexport interface WorkspaceMutationOptions<TData, TInput, TResult> {\n /** Generated GraphQL document (see `src/generated/wspace-operations.ts`). */\n document: DocumentNode;\n /** Maps the caller's input onto GraphQL variables. */\n variables: (input: TInput) => Record<string, unknown>;\n /** Projects the raw payload onto the record shape the UI consumes. */\n select: (data: TData | undefined) => TResult | undefined;\n /** Thrown (and stored) when the payload is missing or the request fails. */\n errorMessage: string;\n}\n\n/**\n * Writes to the workspace gateway. Returns the `[mutate, state]` tuple used by\n * the reference hooks. `mutate` REJECTS on failure so callers cannot mistake a\n * failed write for a successful one.\n */\nexport function useWorkspaceMutation<TData, TInput, TResult>(\n options: WorkspaceMutationOptions<TData, TInput, TResult>\n): readonly [(input: TInput) => Promise<TResult>, MutationState<TResult>] {\n const { document, errorMessage } = options;\n const client = useWorkspaceClient();\n const variablesRef = useLatest(options.variables);\n const selectRef = useLatest(options.select);\n\n const [state, setState] = useState<MutationState<TResult>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const mutate = useCallback(\n async (input: TInput): Promise<TResult> => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<TData>({\n mutation: document,\n variables: variablesRef.current(input),\n });\n // Apollo v4 does not reject on GraphQL errors by default: the mutation\n // RESOLVES with `data` undefined and the failure on `result.error`\n // (CombinedGraphQLErrors / networkError). Surface it like a rejection\n // so callers see the server's field-level message, not the fallback.\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw toError(operationError, errorMessage);\n }\n const selected = selectRef.current(result.data ?? undefined);\n if (selected === undefined) {\n throw new Error(errorMessage);\n }\n setState({ data: selected, loading: false, error: undefined });\n return selected;\n } catch (mutationError) {\n const failure = toError(mutationError, errorMessage);\n setState({ data: undefined, loading: false, error: failure });\n throw failure;\n }\n },\n [client, document, errorMessage, selectRef, variablesRef]\n );\n\n return [mutate, state] as const;\n}\n"],"mappings":";;;;;AAsBA,SAAgBA,IAAsC;CACpD,OAAOC,EAAiB,WAAW;AACrC;AAGA,SAAgBC,IAAqC;CACnD,OAAOC,EAAU,CAAC,CAAC;AACrB;AA2CA,SAASC,EAAQ,GAAgB,GAAgC;CAC/D,IAAMC,IAAUC,EAA6BC,CAAK;CAOlD,OANIF,IAGS,MAAM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,QAAQY,EAAO,QAAQ,KAAA,CAAS;GAC3D,IAAI6B,MAAa,KAAA,GACf,MAAU,MAAM1B,CAAY;GAG9B,OADAwB,EAAS;IAAE,MAAME;IAAU,SAAS;IAAO,OAAO,KAAA;GAAU,CAAC,GACtDA;EACT,SAASC,GAAe;GACtB,IAAMC,IAAUxD,EAAQuD,GAAe3B,CAAY;GAEnD,MADAwB,EAAS;IAAE,MAAM,KAAA;IAAW,SAAS;IAAO,OAAOI;GAAQ,CAAC,GACtDA;EACR;CACF,GACA;EAAC5C;EAAQc;EAAUE;EAAcf;EAAWqC;CAAY,CAGlD,GAAQC,CAAK;AACvB"}
|
|
@@ -79,7 +79,9 @@ export declare const agentKeys: {
|
|
|
79
79
|
details: () => readonly ["agents", "detail"];
|
|
80
80
|
detail: (id: string) => readonly ["agents", "detail", string];
|
|
81
81
|
};
|
|
82
|
-
export declare function useAgents(filter?: AgentFilter
|
|
82
|
+
export declare function useAgents(filter?: AgentFilter, options?: {
|
|
83
|
+
enabled?: boolean;
|
|
84
|
+
}): PaginatedQueryResult<AgentRecord[]>;
|
|
83
85
|
/**
|
|
84
86
|
* Exact agent counts by status for the workspace (BOFF-12426). Unlike
|
|
85
87
|
* `useAgents` this is not capped at one page, so it is the source for
|
|
@@ -24,6 +24,7 @@ var f = u`
|
|
|
24
24
|
lastExecutedAt
|
|
25
25
|
specialization
|
|
26
26
|
tagIds
|
|
27
|
+
knowledgeBaseIds
|
|
27
28
|
createdAt
|
|
28
29
|
updatedAt
|
|
29
30
|
createdById
|
|
@@ -200,16 +201,16 @@ function T(e, t) {
|
|
|
200
201
|
bucketId: t?.bucketId
|
|
201
202
|
};
|
|
202
203
|
}
|
|
203
|
-
function E(t) {
|
|
204
|
-
let { workspaceId:
|
|
204
|
+
function E(t, n) {
|
|
205
|
+
let { workspaceId: r } = e(), a = c(() => ({ filters: T(r, t) }), [t, r]);
|
|
205
206
|
return i({
|
|
206
207
|
document: f,
|
|
207
|
-
variables:
|
|
208
|
+
variables: a,
|
|
208
209
|
pageSize: b,
|
|
209
210
|
extractRows: (e) => e?.listBotmanorAgents ?? [],
|
|
210
211
|
select: (e) => e,
|
|
211
212
|
fallback: x,
|
|
212
|
-
enabled: !!n,
|
|
213
|
+
enabled: !!r && n?.enabled !== !1,
|
|
213
214
|
errorMessage: "Failed to load agents"
|
|
214
215
|
});
|
|
215
216
|
}
|
|
@@ -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","throwOperationError","operationError","result","graphqlErrorMessage","fallback","getWorkspaceClient","client","buildAgentFilter","workspaceId","filter","useAgents","useBotlit","variables","useMemo","useWorkspacePaginatedQuery","data","rows","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 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(filter?: AgentFilter): 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\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;;;;;;;;;;;;;;;;;;;;;;;;;GA2B1BC,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+B;CACvD,IAAID,KAAkB,MACpB,MAAU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;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,CAACzB,CAAM,CAGD,GAAqB+B,CAAK;AACpC;AAEA,SAAgBiB,IAA0B;CACxC,IAAMhD,IAASD,EAAmBkB,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,MALEjD,EAAO,OAAiC;IAC3D,UAAUX;IACV,WAAW;KAAE;KAAS;IAAgB;GACxC,CAAC,EAAA,CAEyB,MAAM;GAChC,IAAI,CAAC4D,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,CAACzB,CAAM,CAGD,GAAsB+B,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 [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D;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"}
|
|
@@ -21,3 +21,15 @@ export interface LinkAgentInput {
|
|
|
21
21
|
export declare function useLinkAgentToBot(): readonly [(input: LinkAgentInput) => Promise<BotAgentLink>, import('./internal/workspaceGateway').MutationState<BotAgentLink>];
|
|
22
22
|
/** Removes a link (the agent itself is untouched). */
|
|
23
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
|
+
};
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
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";
|
|
5
7
|
// src/botlit/hooks/useBotAgents.ts
|
|
6
|
-
var
|
|
8
|
+
var c = s`
|
|
7
9
|
query ListBotAgentLinks($filters: AppAgentFilterInput, $pagination: PaginationInput) {
|
|
8
10
|
listAppAgents(filters: $filters, pagination: $pagination) {
|
|
9
11
|
id
|
|
@@ -13,7 +15,7 @@ var a = i`
|
|
|
13
15
|
priority
|
|
14
16
|
}
|
|
15
17
|
}
|
|
16
|
-
`,
|
|
18
|
+
`, l = s`
|
|
17
19
|
mutation LinkAgentToBot($input: CreateAppAgentInput!) {
|
|
18
20
|
createAppAgent(input: $input) {
|
|
19
21
|
id
|
|
@@ -23,30 +25,30 @@ var a = i`
|
|
|
23
25
|
priority
|
|
24
26
|
}
|
|
25
27
|
}
|
|
26
|
-
`,
|
|
28
|
+
`, u = s`
|
|
27
29
|
mutation UnlinkAgentFromBot($id: ID!) {
|
|
28
30
|
deleteAppAgent(id: $id)
|
|
29
31
|
}
|
|
30
|
-
`,
|
|
31
|
-
function
|
|
32
|
-
let
|
|
33
|
-
appId:
|
|
34
|
-
workspaceId:
|
|
35
|
-
} }), [
|
|
36
|
-
return
|
|
37
|
-
document:
|
|
38
|
-
variables:
|
|
39
|
-
pageSize:
|
|
40
|
-
extractRows: (e) => e?.listAppAgents ??
|
|
41
|
-
fallback:
|
|
42
|
-
enabled: !!(
|
|
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),
|
|
43
45
|
errorMessage: "Failed to load the agents linked to this bot"
|
|
44
46
|
});
|
|
45
47
|
}
|
|
46
|
-
function
|
|
47
|
-
let e =
|
|
48
|
-
return
|
|
49
|
-
document:
|
|
48
|
+
function m() {
|
|
49
|
+
let e = r();
|
|
50
|
+
return i({
|
|
51
|
+
document: l,
|
|
50
52
|
variables: ({ botId: t, agentId: n }) => ({ input: {
|
|
51
53
|
appId: t,
|
|
52
54
|
agentId: n,
|
|
@@ -56,14 +58,38 @@ function d() {
|
|
|
56
58
|
errorMessage: "Failed to link the agent to the bot"
|
|
57
59
|
});
|
|
58
60
|
}
|
|
59
|
-
function
|
|
60
|
-
return
|
|
61
|
-
document:
|
|
61
|
+
function h() {
|
|
62
|
+
return i({
|
|
63
|
+
document: u,
|
|
62
64
|
variables: (e) => ({ id: e }),
|
|
63
65
|
select: (e) => e?.deleteAppAgent ?? void 0,
|
|
64
66
|
errorMessage: "Failed to remove the agent from the bot"
|
|
65
67
|
});
|
|
66
68
|
}
|
|
67
|
-
|
|
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 };
|
|
68
94
|
|
|
69
95
|
//# sourceMappingURL=useBotAgents.js.map
|
|
@@ -1 +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"],"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 { useMemo } from 'react';\n\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"],"mappings":"
|
|
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;CACv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MC,KAAST,EAAO,MACzB,IAAIM,EAAO,IAAIG,EAAM,EAAE,GAAG,KAAK,IAAMC,KAAQD,EAAM,oBAAoB,CAAC,GAAG,EAAI,IAAIC,CAAI;CAGzF,OAAO;EACL;EACA,SAASb,EAAM,WAAWC,EAAI,WAAWE,EAAO,WAAWA,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"}
|
|
@@ -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;
|