@burdenoff/microfe-botmanor 2026.1119.1 → 2026.1119.2

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.
@@ -0,0 +1,22 @@
1
+ import { FC } from 'react';
2
+ /** Most fallback models an agent may have (the service enforces the same cap). */
3
+ export declare const MAX_FALLBACK_MODELS = 3;
4
+ export interface FallbackModelOption {
5
+ id: string;
6
+ name: string;
7
+ modelId: string;
8
+ providerName?: string;
9
+ }
10
+ export interface AgentFallbackModelsPickerProps {
11
+ /** Selected fallback model ids, in the order they are tried. */
12
+ value: string[];
13
+ onChange: (next: string[]) => void;
14
+ /** Answer models the workspace has configured. */
15
+ models: FallbackModelOption[];
16
+ /** The agent's primary model, which cannot also be a fallback. */
17
+ primaryModelId: string;
18
+ disabled?: boolean;
19
+ /** Id prefix for the add-select (labels need a stable id). */
20
+ idPrefix: string;
21
+ }
22
+ export declare const AgentFallbackModelsPicker: FC<AgentFallbackModelsPickerProps>;
@@ -0,0 +1,109 @@
1
+ import { useTr as e } from "../../shared/hooks/useTr.js";
2
+ import { Button as t } from "./Button.js";
3
+ import { jsx as n, jsxs as r } from "react/jsx-runtime";
4
+ import { ArrowDown as i, ArrowUp as a, X as o } from "lucide-react";
5
+ var s = "flex h-10 w-full rounded-md border border-border-default bg-bg-surface px-3 py-2 text-sm", c = ({ value: c, onChange: l, models: u, primaryModelId: d, disabled: f, idPrefix: p }) => {
6
+ let m = e(), h = c.filter((e) => e !== d), g = u.filter((e) => e.id !== d && !h.includes(e.id)), _ = (e) => {
7
+ let t = u.find((t) => t.id === e);
8
+ return t ? t.providerName ? `${t.name} (${t.modelId}) · ${t.providerName}` : `${t.name} (${t.modelId})` : m("botlit.agentBuilder.fallback.unavailable", "Unavailable model ({{id}})", { id: e });
9
+ }, v = (e, t) => {
10
+ let n = [...h], [r] = n.splice(e, 1);
11
+ r !== void 0 && (n.splice(e + t, 0, r), l(n));
12
+ }, y = `${p}-fallback-add`;
13
+ return /* @__PURE__ */ r("section", {
14
+ "aria-labelledby": `${p}-fallback-title`,
15
+ className: "space-y-3",
16
+ children: [
17
+ /* @__PURE__ */ r("div", { children: [/* @__PURE__ */ n("h4", {
18
+ id: `${p}-fallback-title`,
19
+ className: "text-sm font-medium",
20
+ children: m("botlit.agentBuilder.fallback.title", "Fallback models")
21
+ }), /* @__PURE__ */ n("p", {
22
+ className: "text-sm text-text-secondary",
23
+ children: m("botlit.agentBuilder.fallback.help", "If the primary model’s provider fails (error, timeout, rate limit or outage), the turn is retried on these models in order. Any provider can be used; workspace model and data policies still apply. Each run records which model answered.")
24
+ })] }),
25
+ h.length > 0 ? /* @__PURE__ */ n("ol", {
26
+ className: "space-y-2",
27
+ "aria-label": m("botlit.agentBuilder.fallback.listLabel", "Fallback order"),
28
+ children: h.map((e, s) => /* @__PURE__ */ r("li", {
29
+ className: "flex items-center gap-2 rounded-md border border-border-default bg-bg-surface px-3 py-2 text-sm",
30
+ children: [
31
+ /* @__PURE__ */ r("span", {
32
+ className: "w-5 shrink-0 tabular-nums text-text-secondary",
33
+ children: [s + 1, "."]
34
+ }),
35
+ /* @__PURE__ */ n("span", {
36
+ className: "min-w-0 flex-1 truncate",
37
+ children: _(e)
38
+ }),
39
+ /* @__PURE__ */ n(t, {
40
+ type: "button",
41
+ variant: "ghost",
42
+ size: "icon",
43
+ disabled: f || s === 0,
44
+ "aria-label": m("botlit.agentBuilder.fallback.moveUp", "Move {{name}} up", { name: _(e) }),
45
+ onClick: () => v(s, -1),
46
+ children: /* @__PURE__ */ n(a, {
47
+ size: 16,
48
+ "aria-hidden": "true"
49
+ })
50
+ }),
51
+ /* @__PURE__ */ n(t, {
52
+ type: "button",
53
+ variant: "ghost",
54
+ size: "icon",
55
+ disabled: f || s === h.length - 1,
56
+ "aria-label": m("botlit.agentBuilder.fallback.moveDown", "Move {{name}} down", { name: _(e) }),
57
+ onClick: () => v(s, 1),
58
+ children: /* @__PURE__ */ n(i, {
59
+ size: 16,
60
+ "aria-hidden": "true"
61
+ })
62
+ }),
63
+ /* @__PURE__ */ n(t, {
64
+ type: "button",
65
+ variant: "ghost",
66
+ size: "icon",
67
+ disabled: f,
68
+ "aria-label": m("botlit.agentBuilder.fallback.remove", "Remove {{name}}", { name: _(e) }),
69
+ onClick: () => l(h.filter((t) => t !== e)),
70
+ children: /* @__PURE__ */ n(o, {
71
+ size: 16,
72
+ "aria-hidden": "true"
73
+ })
74
+ })
75
+ ]
76
+ }, e))
77
+ }) : /* @__PURE__ */ n("p", {
78
+ className: "text-sm text-text-secondary",
79
+ children: m("botlit.agentBuilder.fallback.none", "No fallback models. A provider failure fails the turn.")
80
+ }),
81
+ h.length < 3 && /* @__PURE__ */ r("div", {
82
+ className: "space-y-1",
83
+ children: [/* @__PURE__ */ n("label", {
84
+ htmlFor: y,
85
+ className: "text-sm text-text-secondary",
86
+ children: m("botlit.agentBuilder.fallback.add", "Add a fallback model")
87
+ }), /* @__PURE__ */ r("select", {
88
+ id: y,
89
+ className: s,
90
+ disabled: f || g.length === 0,
91
+ value: "",
92
+ onChange: (e) => {
93
+ e.target.value && l([...h, e.target.value]);
94
+ },
95
+ children: [/* @__PURE__ */ n("option", {
96
+ value: "",
97
+ children: g.length === 0 ? m("botlit.agentBuilder.fallback.noneAvailable", "No other answer model is configured") : m("botlit.agentBuilder.fallback.choose", "Choose a model…")
98
+ }), g.map((e) => /* @__PURE__ */ n("option", {
99
+ value: e.id,
100
+ children: _(e.id)
101
+ }, e.id))]
102
+ })]
103
+ })
104
+ ]
105
+ });
106
+ };
107
+ export { c as AgentFallbackModelsPicker };
108
+
109
+ //# sourceMappingURL=AgentFallbackModelsPicker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AgentFallbackModelsPicker.js","names":["SELECT_CLASS","AgentFallbackModelsPicker","tr","useTr","selected","value","id","primaryModelId","available","models","model","labelOf","entry","move","next","item","index","by","onChange","selectId","idPrefix","Button","disabled","ArrowUp","ArrowDown","X","event"],"sources":["../../../src/botlit/components/AgentFallbackModelsPicker.tsx"],"sourcesContent":["/**\n * Ordered fallback models of an agent (BOFF-15360).\n *\n * When the primary model's provider fails (an error, a timeout, a rate limit\n * or a 5xx), the turn retries on these models in order. Any provider may be\n * chosen; the workspace's model allowlist and DATA sharing/region rules still\n * apply to each one at run time.\n * @module botlit/components\n */\nimport type { FC } from 'react';\nimport { ArrowDown, ArrowUp, X } from 'lucide-react';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { Button } from './Button';\n\n/** Most fallback models an agent may have (the service enforces the same cap). */\nexport const MAX_FALLBACK_MODELS = 3;\n\nexport interface FallbackModelOption {\n id: string;\n name: string;\n modelId: string;\n providerName?: string;\n}\n\nexport interface AgentFallbackModelsPickerProps {\n /** Selected fallback model ids, in the order they are tried. */\n value: string[];\n onChange: (next: string[]) => void;\n /** Answer models the workspace has configured. */\n models: FallbackModelOption[];\n /** The agent's primary model, which cannot also be a fallback. */\n primaryModelId: string;\n disabled?: boolean;\n /** Id prefix for the add-select (labels need a stable id). */\n idPrefix: string;\n}\n\nconst SELECT_CLASS =\n 'flex h-10 w-full rounded-md border border-border-default bg-bg-surface px-3 py-2 text-sm';\n\nexport const AgentFallbackModelsPicker: FC<AgentFallbackModelsPickerProps> = ({\n value,\n onChange,\n models,\n primaryModelId,\n disabled,\n idPrefix,\n}) => {\n const tr = useTr();\n const selected = value.filter((id) => id !== primaryModelId);\n const available = models.filter(\n (model) => model.id !== primaryModelId && !selected.includes(model.id)\n );\n const labelOf = (id: string): string => {\n const model = models.find((entry) => entry.id === id);\n if (!model)\n return tr('botlit.agentBuilder.fallback.unavailable', 'Unavailable model ({{id}})', { id });\n return model.providerName\n ? `${model.name} (${model.modelId}) · ${model.providerName}`\n : `${model.name} (${model.modelId})`;\n };\n const move = (index: number, by: -1 | 1) => {\n const next = [...selected];\n const [item] = next.splice(index, 1);\n if (item === undefined) return;\n next.splice(index + by, 0, item);\n onChange(next);\n };\n const selectId = `${idPrefix}-fallback-add`;\n\n return (\n <section aria-labelledby={`${idPrefix}-fallback-title`} className=\"space-y-3\">\n <div>\n <h4 id={`${idPrefix}-fallback-title`} className=\"text-sm font-medium\">\n {tr('botlit.agentBuilder.fallback.title', 'Fallback models')}\n </h4>\n <p className=\"text-sm text-text-secondary\">\n {tr(\n 'botlit.agentBuilder.fallback.help',\n 'If the primary model’s provider fails (error, timeout, rate limit or outage), the turn is retried on these models in order. Any provider can be used; workspace model and data policies still apply. Each run records which model answered.'\n )}\n </p>\n </div>\n\n {selected.length > 0 ? (\n <ol\n className=\"space-y-2\"\n aria-label={tr('botlit.agentBuilder.fallback.listLabel', 'Fallback order')}\n >\n {selected.map((id, index) => (\n <li\n key={id}\n className=\"flex items-center gap-2 rounded-md border border-border-default bg-bg-surface px-3 py-2 text-sm\"\n >\n <span className=\"w-5 shrink-0 tabular-nums text-text-secondary\">{index + 1}.</span>\n <span className=\"min-w-0 flex-1 truncate\">{labelOf(id)}</span>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon\"\n disabled={disabled || index === 0}\n aria-label={tr('botlit.agentBuilder.fallback.moveUp', 'Move {{name}} up', {\n name: labelOf(id),\n })}\n onClick={() => move(index, -1)}\n >\n <ArrowUp size={16} aria-hidden=\"true\" />\n </Button>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon\"\n disabled={disabled || index === selected.length - 1}\n aria-label={tr('botlit.agentBuilder.fallback.moveDown', 'Move {{name}} down', {\n name: labelOf(id),\n })}\n onClick={() => move(index, 1)}\n >\n <ArrowDown size={16} aria-hidden=\"true\" />\n </Button>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon\"\n disabled={disabled}\n aria-label={tr('botlit.agentBuilder.fallback.remove', 'Remove {{name}}', {\n name: labelOf(id),\n })}\n onClick={() => onChange(selected.filter((entry) => entry !== id))}\n >\n <X size={16} aria-hidden=\"true\" />\n </Button>\n </li>\n ))}\n </ol>\n ) : (\n <p className=\"text-sm text-text-secondary\">\n {tr(\n 'botlit.agentBuilder.fallback.none',\n 'No fallback models. A provider failure fails the turn.'\n )}\n </p>\n )}\n\n {selected.length < MAX_FALLBACK_MODELS && (\n <div className=\"space-y-1\">\n <label htmlFor={selectId} className=\"text-sm text-text-secondary\">\n {tr('botlit.agentBuilder.fallback.add', 'Add a fallback model')}\n </label>\n <select\n id={selectId}\n className={SELECT_CLASS}\n disabled={disabled || available.length === 0}\n value=\"\"\n onChange={(event) => {\n if (event.target.value) onChange([...selected, event.target.value]);\n }}\n >\n <option value=\"\">\n {available.length === 0\n ? tr(\n 'botlit.agentBuilder.fallback.noneAvailable',\n 'No other answer model is configured'\n )\n : tr('botlit.agentBuilder.fallback.choose', 'Choose a model…')}\n </option>\n {available.map((model) => (\n <option key={model.id} value={model.id}>\n {labelOf(model.id)}\n </option>\n ))}\n </select>\n </div>\n )}\n </section>\n );\n};\n"],"mappings":";;;;AAqCA,IAAMA,IACJ,4FAEWC,KAAiE,EAC5E,UACA,aACA,WACA,mBACA,aACA,kBACI;CACJ,IAAMC,IAAKC,EAAM,GACXC,IAAWC,EAAM,QAAQ,MAAOC,MAAOC,CAAc,GACrDC,IAAYC,EAAO,QACtB,MAAUC,EAAM,OAAOH,KAAkB,CAACH,EAAS,SAASM,EAAM,EAAE,CACvE,GACMC,KAAW,MAAuB;EACtC,IAAMD,IAAQD,EAAO,MAAM,MAAUG,EAAM,OAAON,CAAE;EAGpD,OAFKI,IAEEA,EAAM,eACT,GAAGA,EAAM,KAAK,IAAIA,EAAM,QAAQ,MAAMA,EAAM,iBAC5C,GAAGA,EAAM,KAAK,IAAIA,EAAM,QAAQ,KAH3BR,EAAG,4CAA4C,8BAA8B,EAAE,MAAG,CAAC;CAI9F,GACMW,KAAQ,GAAe,MAAe;EAC1C,IAAMC,IAAO,CAAC,GAAGV,CAAQ,GACnB,CAACW,KAAQD,EAAK,OAAOE,GAAO,CAAC;EACnC,AAAID,MAAS,KAAA,MACbD,EAAK,OAAOE,IAAQC,GAAI,GAAGF,CAAI,GAC/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;OACR,MAAK;OACK;OACV,cAAYnB,EAAG,uCAAuC,mBAAmB,EACvE,MAAMS,EAAQL,CAAE,EAClB,CAAC;OACD,eAAeY,EAASd,EAAS,QAAQ,MAAUQ,MAAUN,CAAE,CAAC;OAEhE,UAAA,kBAACmB,GAAD;QAAG,MAAM;QAAI,eAAY;OAAQ,CAAA;MAC3B,CAAA;KACN;IAzCG,GAAAnB,CAyCH,CACL;GACC,CAAA,IAEJ,kBAAC,KAAD;IAAG,WAAU;IACV,UAAAJ,EACC,qCACA,wDACF;GACC,CAAA;GAGJE,EAAS,SAAA,KACR,kBAAC,OAAD;IAAK,WAAU;IAAf,UAAA,CACE,kBAAC,SAAD;KAAO,SAASe;KAAU,WAAU;KACjC,UAAAjB,EAAG,oCAAoC,sBAAsB;IACzD,CAAA,GACP,kBAAC,UAAD;KACE,IAAIiB;KACJ,WAAWnB;KACX,UAAUsB,KAAYd,EAAU,WAAW;KAC3C,OAAM;KACN,WAAW,MAAU;MACnB,AAAIkB,EAAM,OAAO,SAAOR,EAAS,CAAC,GAAGd,GAAUsB,EAAM,OAAO,KAAK,CAAC;KACpE;KAPF,UAAA,CASE,kBAAC,UAAD;MAAQ,OAAM;MACX,UAAAlB,EAAU,WAAW,IAClBN,EACE,8CACA,qCACF,IACAA,EAAG,uCAAuC,iBAAiB;KACzD,CAAA,GACPM,EAAU,KAAK,MACd,kBAAC,UAAD;MAAuB,OAAOE,EAAM;MACjC,UAAAC,EAAQD,EAAM,EAAE;KACX,GAFKA,EAAM,EAEX,CACT,CACK;IACL,CAAA,CAAA;;EAEA;;AAEb"}
@@ -0,0 +1,25 @@
1
+ import { FC } from 'react';
2
+ export interface ModelAttemptRecord {
3
+ llmModelId?: string;
4
+ modelId: string;
5
+ providerType: string;
6
+ outcome: 'served' | 'failed' | 'skipped';
7
+ reason?: string;
8
+ detail?: string;
9
+ durationMs?: number;
10
+ }
11
+ export interface ModelFallbackRecord {
12
+ configured: string[];
13
+ servedBy: {
14
+ llmModelId?: string;
15
+ modelId: string;
16
+ providerType: string;
17
+ } | null;
18
+ fellBack: boolean;
19
+ attempts: ModelAttemptRecord[];
20
+ }
21
+ /** The record in an execution's metadata, or null when it has none (or a malformed one). */
22
+ export declare function readModelFallback(metadata: unknown): ModelFallbackRecord | null;
23
+ export declare const ExecutionModelFallback: FC<{
24
+ metadata: unknown;
25
+ }>;
@@ -0,0 +1,114 @@
1
+ import { useTr as e } from "../../shared/hooks/useTr.js";
2
+ import { Badge as t } from "./Badge.js";
3
+ import { Card as n, CardContent as r, CardDescription as i, CardHeader as a, CardTitle as o } from "./Card.js";
4
+ import { jsx as s, jsxs as c } from "react/jsx-runtime";
5
+ import { ArrowRightLeft as l } from "lucide-react";
6
+ // src/botlit/components/ExecutionModelFallback.tsx
7
+ var u = /* @__PURE__ */ new Set([
8
+ "served",
9
+ "failed",
10
+ "skipped"
11
+ ]);
12
+ function d(e) {
13
+ if (!e || typeof e != "object") return null;
14
+ let t = e.modelFallback;
15
+ if (!t || typeof t != "object") return null;
16
+ let { attempts: n, servedBy: r, fellBack: i, configured: a } = t;
17
+ return Array.isArray(n) ? {
18
+ configured: Array.isArray(a) ? a.filter((e) => typeof e == "string") : [],
19
+ servedBy: r && typeof r == "object" && typeof r.modelId == "string" ? r : null,
20
+ fellBack: i === !0,
21
+ attempts: n.filter((e) => !!e && typeof e == "object" && typeof e.modelId == "string" && u.has(e.outcome))
22
+ } : null;
23
+ }
24
+ var f = {
25
+ served: "success",
26
+ failed: "destructive",
27
+ skipped: "secondary"
28
+ }, p = ({ metadata: u }) => {
29
+ let p = e(), m = d(u);
30
+ if (!m) return null;
31
+ let h = (e) => {
32
+ switch (e) {
33
+ case "timeout": return p("botlit.execution.fallback.reason.timeout", "Timed out");
34
+ case "rate_limited": return p("botlit.execution.fallback.reason.rateLimited", "Rate limited");
35
+ case "server_error": return p("botlit.execution.fallback.reason.serverError", "Provider error (5xx)");
36
+ case "unreachable": return p("botlit.execution.fallback.reason.unreachable", "Provider unreachable");
37
+ case "provider_rejected": return p("botlit.execution.fallback.reason.rejected", "Provider rejected the credentials or model");
38
+ case "not_retryable": return p("botlit.execution.fallback.reason.notRetryable", "Not retried (request or policy error)");
39
+ case "model_unavailable": return p("botlit.execution.fallback.reason.modelUnavailable", "Skipped: model inactive or deleted");
40
+ case "provider_unavailable": return p("botlit.execution.fallback.reason.providerUnavailable", "Skipped: provider inactive");
41
+ case "credentials_missing": return p("botlit.execution.fallback.reason.credentialsMissing", "Skipped: no credentials");
42
+ case "tool_calling_unsupported": return p("botlit.execution.fallback.reason.noTools", "Skipped: cannot call this agent’s tools");
43
+ case "model_not_allowed": return p("botlit.execution.fallback.reason.modelNotAllowed", "Skipped: not on the model allowlist");
44
+ case "data_policy": return p("botlit.execution.fallback.reason.dataPolicy", "Skipped: data policy (sharing or region)");
45
+ default: return e ?? "";
46
+ }
47
+ }, g = m.servedBy ? m.fellBack ? p("botlit.execution.fallback.fellBack", "Answered by fallback model {{model}} ({{provider}}).", {
48
+ model: m.servedBy.modelId,
49
+ provider: m.servedBy.providerType
50
+ }) : p("botlit.execution.fallback.primary", "Answered by the primary model {{model}} ({{provider}}).", {
51
+ model: m.servedBy.modelId,
52
+ provider: m.servedBy.providerType
53
+ }) : p("botlit.execution.fallback.exhausted", "No model could answer this run.");
54
+ return /* @__PURE__ */ c(n, { children: [/* @__PURE__ */ c(a, { children: [/* @__PURE__ */ c(o, {
55
+ className: "flex items-center gap-2",
56
+ children: [/* @__PURE__ */ s(l, {
57
+ size: 18,
58
+ "aria-hidden": "true"
59
+ }), p("botlit.execution.fallback.title", "Model fallback")]
60
+ }), /* @__PURE__ */ s(i, { children: g })] }), /* @__PURE__ */ s(r, { children: /* @__PURE__ */ s("ol", {
61
+ className: "space-y-2",
62
+ "aria-label": p("botlit.execution.fallback.attempts", "Model attempts"),
63
+ children: m.attempts.map((e, n) => /* @__PURE__ */ c("li", {
64
+ className: "flex flex-wrap items-start gap-2 rounded-md bg-bg-sunken p-3 text-sm",
65
+ children: [
66
+ /* @__PURE__ */ c("span", {
67
+ className: "w-5 shrink-0 tabular-nums text-text-secondary",
68
+ children: [n + 1, "."]
69
+ }),
70
+ /* @__PURE__ */ c("div", {
71
+ className: "min-w-0 flex-1",
72
+ children: [
73
+ /* @__PURE__ */ c("p", {
74
+ className: "font-medium break-all",
75
+ children: [
76
+ e.modelId || e.llmModelId,
77
+ " ",
78
+ e.providerType && /* @__PURE__ */ c("span", {
79
+ className: "text-text-secondary",
80
+ children: [
81
+ "(",
82
+ e.providerType,
83
+ ")"
84
+ ]
85
+ })
86
+ ]
87
+ }),
88
+ e.outcome !== "served" && e.reason && /* @__PURE__ */ s("p", {
89
+ className: "text-text-secondary",
90
+ children: h(e.reason)
91
+ }),
92
+ e.detail && /* @__PURE__ */ s("p", {
93
+ className: "font-mono text-xs text-text-secondary break-all",
94
+ children: e.detail
95
+ })
96
+ ]
97
+ }),
98
+ /* @__PURE__ */ c("div", {
99
+ className: "flex items-center gap-2",
100
+ children: [typeof e.durationMs == "number" && /* @__PURE__ */ c("span", {
101
+ className: "tabular-nums text-text-secondary",
102
+ children: [e.durationMs, " ms"]
103
+ }), /* @__PURE__ */ s(t, {
104
+ variant: f[e.outcome],
105
+ children: e.outcome === "served" ? p("botlit.execution.fallback.served", "Served") : e.outcome === "failed" ? p("botlit.execution.fallback.failed", "Failed") : p("botlit.execution.fallback.skipped", "Skipped")
106
+ })]
107
+ })
108
+ ]
109
+ }, `${e.llmModelId ?? e.modelId}-${n}`))
110
+ }) })] });
111
+ };
112
+ export { p as ExecutionModelFallback, d as readModelFallback };
113
+
114
+ //# sourceMappingURL=ExecutionModelFallback.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ExecutionModelFallback.js","names":["OUTCOMES","readModelFallback","metadata","record","attempts","configured","id","servedBy","fellBack","attempt","OUTCOME_VARIANT","ExecutionModelFallback","tr","useTr","reasonLabel","reason","summary","Card","CardHeader","CardTitle","ArrowRightLeft","CardDescription","CardContent","index","Badge"],"sources":["../../../src/botlit/components/ExecutionModelFallback.tsx"],"sourcesContent":["/**\n * Which model served a run, and every model it tried (BOFF-15360).\n *\n * Reads `Execution.metadata.modelFallback`, which the service records for an\n * agent with fallback models: the primary first, then each fallback that was\n * tried or skipped (and why), and the model that answered.\n * @module botlit/components\n */\nimport type { FC } from 'react';\nimport { ArrowRightLeft } from 'lucide-react';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { Badge } from './Badge';\nimport { Card, CardContent, CardDescription, CardHeader, CardTitle } from './Card';\n\nexport interface ModelAttemptRecord {\n llmModelId?: string;\n modelId: string;\n providerType: string;\n outcome: 'served' | 'failed' | 'skipped';\n reason?: string;\n detail?: string;\n durationMs?: number;\n}\n\nexport interface ModelFallbackRecord {\n configured: string[];\n servedBy: { llmModelId?: string; modelId: string; providerType: string } | null;\n fellBack: boolean;\n attempts: ModelAttemptRecord[];\n}\n\nconst OUTCOMES = new Set(['served', 'failed', 'skipped']);\n\n/** The record in an execution's metadata, or null when it has none (or a malformed one). */\nexport function readModelFallback(metadata: unknown): ModelFallbackRecord | null {\n if (!metadata || typeof metadata !== 'object') return null;\n const record = (metadata as { modelFallback?: unknown }).modelFallback;\n if (!record || typeof record !== 'object') return null;\n const { attempts, servedBy, fellBack, configured } = record as Partial<ModelFallbackRecord>;\n if (!Array.isArray(attempts)) return null;\n return {\n configured: Array.isArray(configured) ? configured.filter((id) => typeof id === 'string') : [],\n servedBy:\n servedBy && typeof servedBy === 'object' && typeof servedBy.modelId === 'string'\n ? servedBy\n : null,\n fellBack: fellBack === true,\n attempts: attempts.filter(\n (attempt): attempt is ModelAttemptRecord =>\n !!attempt &&\n typeof attempt === 'object' &&\n typeof attempt.modelId === 'string' &&\n OUTCOMES.has(attempt.outcome)\n ),\n };\n}\n\nconst OUTCOME_VARIANT = {\n served: 'success',\n failed: 'destructive',\n skipped: 'secondary',\n} as const;\n\nexport const ExecutionModelFallback: FC<{ metadata: unknown }> = ({ metadata }) => {\n const tr = useTr();\n const record = readModelFallback(metadata);\n if (!record) return null;\n\n const reasonLabel = (reason: string | undefined): string => {\n switch (reason) {\n case 'timeout':\n return tr('botlit.execution.fallback.reason.timeout', 'Timed out');\n case 'rate_limited':\n return tr('botlit.execution.fallback.reason.rateLimited', 'Rate limited');\n case 'server_error':\n return tr('botlit.execution.fallback.reason.serverError', 'Provider error (5xx)');\n case 'unreachable':\n return tr('botlit.execution.fallback.reason.unreachable', 'Provider unreachable');\n case 'provider_rejected':\n return tr(\n 'botlit.execution.fallback.reason.rejected',\n 'Provider rejected the credentials or model'\n );\n case 'not_retryable':\n return tr(\n 'botlit.execution.fallback.reason.notRetryable',\n 'Not retried (request or policy error)'\n );\n case 'model_unavailable':\n return tr(\n 'botlit.execution.fallback.reason.modelUnavailable',\n 'Skipped: model inactive or deleted'\n );\n case 'provider_unavailable':\n return tr(\n 'botlit.execution.fallback.reason.providerUnavailable',\n 'Skipped: provider inactive'\n );\n case 'credentials_missing':\n return tr('botlit.execution.fallback.reason.credentialsMissing', 'Skipped: no credentials');\n case 'tool_calling_unsupported':\n return tr(\n 'botlit.execution.fallback.reason.noTools',\n 'Skipped: cannot call this agent’s tools'\n );\n case 'model_not_allowed':\n return tr(\n 'botlit.execution.fallback.reason.modelNotAllowed',\n 'Skipped: not on the model allowlist'\n );\n case 'data_policy':\n return tr(\n 'botlit.execution.fallback.reason.dataPolicy',\n 'Skipped: data policy (sharing or region)'\n );\n default:\n return reason ?? '';\n }\n };\n\n const summary = record.servedBy\n ? record.fellBack\n ? tr(\n 'botlit.execution.fallback.fellBack',\n 'Answered by fallback model {{model}} ({{provider}}).',\n {\n model: record.servedBy.modelId,\n provider: record.servedBy.providerType,\n }\n )\n : tr(\n 'botlit.execution.fallback.primary',\n 'Answered by the primary model {{model}} ({{provider}}).',\n {\n model: record.servedBy.modelId,\n provider: record.servedBy.providerType,\n }\n )\n : tr('botlit.execution.fallback.exhausted', 'No model could answer this run.');\n\n return (\n <Card>\n <CardHeader>\n <CardTitle className=\"flex items-center gap-2\">\n <ArrowRightLeft size={18} aria-hidden=\"true\" />\n {tr('botlit.execution.fallback.title', 'Model fallback')}\n </CardTitle>\n <CardDescription>{summary}</CardDescription>\n </CardHeader>\n <CardContent>\n <ol\n className=\"space-y-2\"\n aria-label={tr('botlit.execution.fallback.attempts', 'Model attempts')}\n >\n {record.attempts.map((attempt, index) => (\n <li\n key={`${attempt.llmModelId ?? attempt.modelId}-${index}`}\n className=\"flex flex-wrap items-start gap-2 rounded-md bg-bg-sunken p-3 text-sm\"\n >\n <span className=\"w-5 shrink-0 tabular-nums text-text-secondary\">{index + 1}.</span>\n <div className=\"min-w-0 flex-1\">\n <p className=\"font-medium break-all\">\n {attempt.modelId || attempt.llmModelId}{' '}\n {attempt.providerType && (\n <span className=\"text-text-secondary\">({attempt.providerType})</span>\n )}\n </p>\n {attempt.outcome !== 'served' && attempt.reason && (\n <p className=\"text-text-secondary\">{reasonLabel(attempt.reason)}</p>\n )}\n {attempt.detail && (\n <p className=\"font-mono text-xs text-text-secondary break-all\">\n {attempt.detail}\n </p>\n )}\n </div>\n <div className=\"flex items-center gap-2\">\n {typeof attempt.durationMs === 'number' && (\n <span className=\"tabular-nums text-text-secondary\">{attempt.durationMs} ms</span>\n )}\n <Badge variant={OUTCOME_VARIANT[attempt.outcome]}>\n {attempt.outcome === 'served'\n ? tr('botlit.execution.fallback.served', 'Served')\n : attempt.outcome === 'failed'\n ? tr('botlit.execution.fallback.failed', 'Failed')\n : tr('botlit.execution.fallback.skipped', 'Skipped')}\n </Badge>\n </div>\n </li>\n ))}\n </ol>\n </CardContent>\n </Card>\n );\n};\n"],"mappings":";;;;;;AA+BA,IAAMA,oBAAW,IAAI,IAAI;CAAC;CAAU;CAAU;AAAS,CAAC;AAGxD,SAAgBC,EAAkB,GAA+C;CAC/E,IAAI,CAACC,KAAY,OAAOA,KAAa,UAAU,OAAO;CACtD,IAAMC,IAAUD,EAAyC;CACzD,IAAI,CAACC,KAAU,OAAOA,KAAW,UAAU,OAA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AhB,UAAA,CAAoDA,EAAQ,YAAW,KAAS;KAElF,CAAA,GAAA,kBAACe,GAAD;MAAO,SAASd,EAAgBD,EAAQ;MACrC,UAAAA,EAAQ,YAAY,WACjBG,EAAG,oCAAoC,QAAQ,IAC/CH,EAAQ,YAAY,WAClBG,EAAG,oCAAoC,QAAQ,IAC/CA,EAAG,qCAAqC,SAAS;KAClD,CAAA,CACJ;;GACH;EAhCG,GAAA,GAAGH,EAAQ,cAAcA,EAAQ,QAAQ,GAAGc,GAgC/C,CACL;CACC,CAAA,EACO,CAAA,CACT,EAAA,CAAA;AAEV"}
@@ -14,6 +14,8 @@ export interface AgentRecord {
14
14
  visibility?: string | null;
15
15
  capabilities?: string[] | null;
16
16
  llmModelId?: string | null;
17
+ /** BOFF-15360 — ordered fallback models. */
18
+ fallbackModelIds?: string[] | null;
17
19
  bucketId?: string | null;
18
20
  currentVersionId?: string | null;
19
21
  draftVersionId?: string | null;
@@ -67,6 +69,7 @@ interface CreateAgentInput {
67
69
  maxConcurrentExecutions?: number;
68
70
  capabilities?: string[];
69
71
  llmModelId?: string;
72
+ fallbackModelIds?: string[];
70
73
  knowledgeBaseIds?: string[];
71
74
  mcpConnectionIds?: string[];
72
75
  visibility?: string;
@@ -19,6 +19,7 @@ var f = u`
19
19
  visibility
20
20
  capabilities
21
21
  llmModelId
22
+ fallbackModelIds
22
23
  bucketId
23
24
  executionCount
24
25
  lastExecutedAt
@@ -46,6 +47,7 @@ var f = u`
46
47
  visibility
47
48
  capabilities
48
49
  llmModelId
50
+ fallbackModelIds
49
51
  bucketId
50
52
  currentVersionId
51
53
  draftVersionId
@@ -82,6 +84,7 @@ var f = u`
82
84
  visibility
83
85
  capabilities
84
86
  llmModelId
87
+ fallbackModelIds
85
88
  systemPrompt
86
89
  temperature
87
90
  maxTokens
@@ -106,6 +109,7 @@ var f = u`
106
109
  visibility
107
110
  capabilities
108
111
  llmModelId
112
+ fallbackModelIds
109
113
  systemPrompt
110
114
  temperature
111
115
  maxTokens
@@ -173,6 +177,7 @@ var f = u`
173
177
  description: !0,
174
178
  knowledgeBaseIds: !0,
175
179
  llmModelId: !0,
180
+ fallbackModelIds: !0,
176
181
  maxConcurrentExecutions: !0,
177
182
  maxTokens: !0,
178
183
  mcpConnectionIds: !0,
@@ -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","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 tags\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 tags\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 tags\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 tags\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 /** Entity-owned universal tag records (JSON). */\n tags?: unknown;\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 visibility?: string;\n}\n\ninterface UpdateAgentInput {\n agentId: string;\n input: GraphQLInput<UpdateBotmanorAgentInput>;\n}\n\nconst UPDATE_AGENT_FIELDS = fieldsOf<UpdateBotmanorAgentInput>({\n avatar: true,\n bucketId: true,\n capabilities: true,\n context: true,\n description: true,\n knowledgeBaseIds: true,\n llmModelId: true,\n maxConcurrentExecutions: true,\n maxTokens: true,\n mcpConnectionIds: true,\n metadata: true,\n name: true,\n slug: true,\n specialization: true,\n status: true,\n systemPrompt: true,\n tagIds: true,\n tags: true,\n temperature: true,\n type: true,\n visibility: true,\n workflowIds: true,\n});\n\n/**\n * Apollo v4 resolves a mutation with `result.error` set (and no data) when the\n * server answers with a GraphQL error, instead of rejecting. Throw it so the\n * caller sees the server's actionable message (\"An agent named ... already\n * exists\") and not the generic fallback.\n */\nfunction throwOperationError(result: unknown, fallback: string): void {\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw new Error(graphqlErrorMessage(operationError, fallback), { cause: operationError });\n }\n}\n\nfunction getWorkspaceClient(client: unknown): WorkspaceClient {\n return client as WorkspaceClient;\n}\n\nfunction buildAgentFilter(\n workspaceId: string | undefined,\n filter?: AgentFilter\n): Record<string, unknown> | undefined {\n if (!workspaceId && !filter) return undefined;\n\n return {\n workspaceId,\n search: filter?.search,\n status: filter?.status?.[0],\n visibility: filter?.visibility?.[0],\n bucketId: filter?.bucketId,\n };\n}\n\nexport const agentKeys = {\n all: ['agents'] as const,\n lists: () => [...agentKeys.all, 'list'] as const,\n list: (filter?: AgentFilter) => [...agentKeys.lists(), filter] as const,\n details: () => [...agentKeys.all, 'detail'] as const,\n detail: (id: string) => [...agentKeys.details(), id] as const,\n};\n\nexport function useAgents(\n filter?: AgentFilter,\n options?: { enabled?: boolean }\n): PaginatedQueryResult<AgentRecord[]> {\n const { workspaceId } = useBotlit();\n\n const variables = useMemo(\n () => ({ filters: buildAgentFilter(workspaceId, filter) }),\n [filter, workspaceId]\n );\n\n return useWorkspacePaginatedQuery<ListBotmanorAgentsData, AgentRecord, AgentRecord[]>({\n document: LIST_AGENTS_DOCUMENT,\n variables,\n pageSize: LIST_PAGE_SIZE,\n extractRows: (data) => data?.listBotmanorAgents ?? [],\n select: (rows) => rows,\n fallback: NO_AGENTS,\n enabled: Boolean(workspaceId) && options?.enabled !== false,\n errorMessage: 'Failed to load agents',\n });\n}\n\n/**\n * Exact agent counts by status for the workspace (BOFF-12426). Unlike\n * `useAgents` this is not capped at one page, so it is the source for\n * dashboard totals. `total` counts every status.\n */\nexport interface AgentCounts {\n total: number;\n draft: number;\n active: number;\n paused: number;\n training: number;\n archived: number;\n}\n\ninterface AgentCountsData {\n getBotmanorAgentCounts?: AgentCounts | null;\n}\n\nconst GET_AGENT_COUNTS_DOCUMENT = gql`\n query GetBotmanorAgentCounts {\n getBotmanorAgentCounts {\n total\n draft\n active\n paused\n training\n archived\n }\n }\n`;\n\nexport function useAgentCounts(enabled = true): QueryResult<AgentCounts | null> {\n const { workspaceId } = useBotlit();\n const variables = useMemo(() => ({}), []);\n\n return useWorkspaceQuery<AgentCountsData, AgentCounts | null>({\n document: GET_AGENT_COUNTS_DOCUMENT,\n variables,\n select: (data) => data?.getBotmanorAgentCounts ?? null,\n fallback: null,\n enabled: enabled && Boolean(workspaceId),\n errorMessage: 'Failed to load agent counts',\n });\n}\n\n/** What still uses an agent, shown in the delete confirmation (BOFF-12457). */\nexport interface AgentUsage {\n bots: Array<{ id: string; name: string; isDefault: boolean }>;\n a2aConnections: Array<{ id: string; name: string }>;\n workflowIds: string[];\n}\n\ninterface AgentUsageData {\n getBotmanorAgentUsage?: AgentUsage | null;\n}\n\nconst GET_AGENT_USAGE_DOCUMENT = gql`\n query GetBotmanorAgentUsage($id: ID!) {\n getBotmanorAgentUsage(id: $id) {\n bots {\n id\n name\n isDefault\n }\n a2aConnections {\n id\n name\n }\n workflowIds\n }\n }\n`;\n\n/** Returns a function that reads what uses an agent. Reads fresh every time, because a delete is about to rely on it. */\nexport function useLoadAgentUsage() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n\n return useCallback(\n async (agentId: string): Promise<AgentUsage> => {\n const result = await client.query<AgentUsageData>({\n query: GET_AGENT_USAGE_DOCUMENT,\n variables: { id: agentId },\n fetchPolicy: 'network-only',\n });\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw operationError instanceof Error\n ? operationError\n : new Error('Failed to load agent usage');\n }\n return (\n result.data?.getBotmanorAgentUsage ?? { bots: [], a2aConnections: [], workflowIds: [] }\n );\n },\n [client]\n );\n}\n\nexport function useAgent(agentId: string | undefined) {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [data, setData] = useState<AgentRecord | null>(null);\n // Loading from the first render when there is an id to read, so a page never\n // shows \"not found\" (or an empty form) for the frame before the read starts.\n const [loading, setLoading] = useState(Boolean(agentId));\n const [error, setError] = useState<Error | undefined>();\n\n const refetch = useCallback(async () => {\n if (!agentId) {\n setData(null);\n setLoading(false);\n return;\n }\n\n setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<GetAgentData>({\n query: GET_AGENT_DOCUMENT,\n variables: { id: agentId },\n fetchPolicy: 'network-only',\n });\n // Apollo v4 resolves (not rejects) with `result.error` set on GraphQL errors.\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw operationError instanceof Error ? operationError : new Error('Failed to load agent');\n }\n setData(result.data?.getBotmanorAgent ?? null);\n } catch (queryError) {\n setData(null);\n setError(queryError instanceof Error ? queryError : new Error('Failed to load agent'));\n } finally {\n setLoading(false);\n }\n }, [agentId, client]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nexport function useCreateAgent() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<AgentRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const createAgent = useCallback(\n async (input: CreateAgentInput) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<CreateAgentData>({\n mutation: CREATE_AGENT_DOCUMENT,\n variables: { input },\n });\n throwOperationError(result, 'Failed to create agent');\n\n const createdAgent = result.data?.createBotmanorAgent;\n if (!createdAgent) {\n throw new Error('Failed to create agent');\n }\n\n setState({ data: createdAgent, loading: false, error: undefined });\n return createdAgent;\n } catch (mutationError) {\n const error = new Error(graphqlErrorMessage(mutationError, 'Failed to create agent'), {\n cause: mutationError,\n });\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [createAgent, state] as const;\n}\n\nexport function useUpdateAgent() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<AgentRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const updateAgent = useCallback(\n async ({ agentId, input }: UpdateAgentInput) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<UpdateAgentData>({\n mutation: UPDATE_AGENT_DOCUMENT,\n variables: { id: agentId, input: buildMutationInput(input, UPDATE_AGENT_FIELDS) },\n });\n throwOperationError(result, 'Failed to update agent');\n\n const updatedAgent = result.data?.updateBotmanorAgent;\n if (!updatedAgent) {\n throw new Error('Failed to update agent');\n }\n\n setState({ data: updatedAgent, loading: false, error: undefined });\n return updatedAgent;\n } catch (mutationError) {\n const error = new Error(graphqlErrorMessage(mutationError, 'Failed to update agent'), {\n cause: mutationError,\n });\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [updateAgent, state] as const;\n}\n\nexport function useDeleteAgent() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<boolean>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const deleteAgent = useCallback(\n async (agentId: string) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<DeleteAgentData>({\n mutation: DELETE_AGENT_DOCUMENT,\n variables: { id: agentId },\n });\n throwOperationError(result, 'Failed to delete agent');\n\n const deleted = result.data?.deleteBotmanorAgent ?? false;\n setState({ data: deleted, loading: false, error: undefined });\n return deleted;\n } catch (mutationError) {\n const error = new Error(graphqlErrorMessage(mutationError, 'Failed to delete agent'), {\n cause: mutationError,\n });\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [deleteAgent, state] as const;\n}\n\n// ============================================================================\n// VERSIONING (BOFF-4381) — version history, publish, rollback\n// ============================================================================\n\nexport function useAgentVersions(agentId: string | undefined) {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [data, setData] = useState<AgentVersionRecord[]>([]);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>();\n\n const refetch = useCallback(async () => {\n if (!agentId) {\n setData([]);\n return;\n }\n\n setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<ListAgentVersionsData>({\n query: LIST_AGENT_VERSIONS_DOCUMENT,\n variables: { agentId, pagination: { limit: 50, offset: 0 } },\n fetchPolicy: 'network-only',\n });\n const versions = result.data?.listAgentVersions ?? [];\n // Newest first, regardless of what the server returned.\n setData(\n [...versions].sort((a, b) =>\n a.createdAt && b.createdAt ? b.createdAt.localeCompare(a.createdAt) : 0\n )\n );\n } catch (queryError) {\n setError(\n queryError instanceof Error ? queryError : new Error('Failed to load agent versions')\n );\n } finally {\n setLoading(false);\n }\n }, [agentId, client]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nexport function usePublishAgentVersion() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<AgentVersionRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const publishAgentVersion = useCallback(\n async ({\n agentId,\n versionId,\n changelog,\n }: {\n agentId: string;\n versionId: string;\n changelog?: string;\n }) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<PublishAgentVersionData>({\n mutation: PUBLISH_AGENT_VERSION_DOCUMENT,\n variables: { agentId, versionId, changelog: changelog?.trim() || undefined },\n });\n\n const published = result.data?.publishAgentVersion;\n if (!published) {\n throw new Error('Failed to publish agent version');\n }\n\n setState({ data: published, loading: false, error: undefined });\n return published;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error\n ? mutationError\n : new Error('Failed to publish agent version');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [publishAgentVersion, state] as const;\n}\n\nexport function useRollbackAgentVersion() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<AgentVersionRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const rollbackAgentVersion = useCallback(\n async ({ agentId, targetVersionId }: { agentId: string; targetVersionId: string }) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<RollbackAgentVersionData>({\n mutation: ROLLBACK_AGENT_VERSION_DOCUMENT,\n variables: { agentId, targetVersionId },\n });\n\n const rolledBack = result.data?.rollbackAgentVersion;\n if (!rolledBack) {\n throw new Error('Failed to roll back agent version');\n }\n\n setState({ data: rolledBack, loading: false, error: undefined });\n return rolledBack;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error\n ? mutationError\n : new Error('Failed to roll back agent version');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [rollbackAgentVersion, state] as const;\n}\n"],"mappings":";;;;;;;;AAgBA,IAAMA,IAAuB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6B1BC,IAAqB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCxBC,IAAwB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;GA0B3BC,IAAwB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+B3BC,IAAwB,CAAG;;;;GAO3BC,IAA+B,CAAG;;;;;;;;;;;;;;;GAiBlCC,IAAiC,CAAG;;;;;;;;;;;;GAcpCC,IAAkC,CAAG;;;;;;;;;;;;GAwDrCC,IAAiB,KACjBC,IAA2B,CAAC,GAwE5BC,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,IAAM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_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 fallbackModelIds\n bucketId\n executionCount\n lastExecutedAt\n specialization\n tagIds\n tags\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 fallbackModelIds\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 tags\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 fallbackModelIds\n systemPrompt\n temperature\n maxTokens\n maxConcurrentExecutions\n tagIds\n tags\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 fallbackModelIds\n systemPrompt\n temperature\n maxTokens\n maxConcurrentExecutions\n knowledgeBaseIds\n mcpConnectionIds\n workflowIds\n tagIds\n tags\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 /** BOFF-15360 — ordered fallback models. */\n fallbackModelIds?: 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 /** Entity-owned universal tag records (JSON). */\n tags?: unknown;\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 fallbackModelIds?: string[];\n knowledgeBaseIds?: string[];\n mcpConnectionIds?: string[];\n visibility?: 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 fallbackModelIds: true,\n maxConcurrentExecutions: true,\n maxTokens: true,\n mcpConnectionIds: true,\n metadata: true,\n name: true,\n slug: true,\n specialization: true,\n status: true,\n systemPrompt: true,\n tagIds: true,\n tags: true,\n temperature: true,\n type: true,\n visibility: true,\n workflowIds: true,\n});\n\n/**\n * Apollo v4 resolves a mutation with `result.error` set (and no data) when the\n * server answers with a GraphQL error, instead of rejecting. Throw it so the\n * caller sees the server's actionable message (\"An agent named ... already\n * exists\") and not the generic fallback.\n */\nfunction throwOperationError(result: unknown, fallback: string): void {\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw new Error(graphqlErrorMessage(operationError, fallback), { cause: operationError });\n }\n}\n\nfunction getWorkspaceClient(client: unknown): WorkspaceClient {\n return client as WorkspaceClient;\n}\n\nfunction buildAgentFilter(\n workspaceId: string | undefined,\n filter?: AgentFilter\n): Record<string, unknown> | undefined {\n if (!workspaceId && !filter) return undefined;\n\n return {\n workspaceId,\n search: filter?.search,\n status: filter?.status?.[0],\n visibility: filter?.visibility?.[0],\n bucketId: filter?.bucketId,\n };\n}\n\nexport const agentKeys = {\n all: ['agents'] as const,\n lists: () => [...agentKeys.all, 'list'] as const,\n list: (filter?: AgentFilter) => [...agentKeys.lists(), filter] as const,\n details: () => [...agentKeys.all, 'detail'] as const,\n detail: (id: string) => [...agentKeys.details(), id] as const,\n};\n\nexport function useAgents(\n filter?: AgentFilter,\n options?: { enabled?: boolean }\n): PaginatedQueryResult<AgentRecord[]> {\n const { workspaceId } = useBotlit();\n\n const variables = useMemo(\n () => ({ filters: buildAgentFilter(workspaceId, filter) }),\n [filter, workspaceId]\n );\n\n return useWorkspacePaginatedQuery<ListBotmanorAgentsData, AgentRecord, AgentRecord[]>({\n document: LIST_AGENTS_DOCUMENT,\n variables,\n pageSize: LIST_PAGE_SIZE,\n extractRows: (data) => data?.listBotmanorAgents ?? [],\n select: (rows) => rows,\n fallback: NO_AGENTS,\n enabled: Boolean(workspaceId) && options?.enabled !== false,\n errorMessage: 'Failed to load agents',\n });\n}\n\n/**\n * Exact agent counts by status for the workspace (BOFF-12426). Unlike\n * `useAgents` this is not capped at one page, so it is the source for\n * dashboard totals. `total` counts every status.\n */\nexport interface AgentCounts {\n total: number;\n draft: number;\n active: number;\n paused: number;\n training: number;\n archived: number;\n}\n\ninterface AgentCountsData {\n getBotmanorAgentCounts?: AgentCounts | null;\n}\n\nconst GET_AGENT_COUNTS_DOCUMENT = gql`\n query GetBotmanorAgentCounts {\n getBotmanorAgentCounts {\n total\n draft\n active\n paused\n training\n archived\n }\n }\n`;\n\nexport function useAgentCounts(enabled = true): QueryResult<AgentCounts | null> {\n const { workspaceId } = useBotlit();\n const variables = useMemo(() => ({}), []);\n\n return useWorkspaceQuery<AgentCountsData, AgentCounts | null>({\n document: GET_AGENT_COUNTS_DOCUMENT,\n variables,\n select: (data) => data?.getBotmanorAgentCounts ?? null,\n fallback: null,\n enabled: enabled && Boolean(workspaceId),\n errorMessage: 'Failed to load agent counts',\n });\n}\n\n/** What still uses an agent, shown in the delete confirmation (BOFF-12457). */\nexport interface AgentUsage {\n bots: Array<{ id: string; name: string; isDefault: boolean }>;\n a2aConnections: Array<{ id: string; name: string }>;\n workflowIds: string[];\n}\n\ninterface AgentUsageData {\n getBotmanorAgentUsage?: AgentUsage | null;\n}\n\nconst GET_AGENT_USAGE_DOCUMENT = gql`\n query GetBotmanorAgentUsage($id: ID!) {\n getBotmanorAgentUsage(id: $id) {\n bots {\n id\n name\n isDefault\n }\n a2aConnections {\n id\n name\n }\n workflowIds\n }\n }\n`;\n\n/** Returns a function that reads what uses an agent. Reads fresh every time, because a delete is about to rely on it. */\nexport function useLoadAgentUsage() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n\n return useCallback(\n async (agentId: string): Promise<AgentUsage> => {\n const result = await client.query<AgentUsageData>({\n query: GET_AGENT_USAGE_DOCUMENT,\n variables: { id: agentId },\n fetchPolicy: 'network-only',\n });\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw operationError instanceof Error\n ? operationError\n : new Error('Failed to load agent usage');\n }\n return (\n result.data?.getBotmanorAgentUsage ?? { bots: [], a2aConnections: [], workflowIds: [] }\n );\n },\n [client]\n );\n}\n\nexport function useAgent(agentId: string | undefined) {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [data, setData] = useState<AgentRecord | null>(null);\n // Loading from the first render when there is an id to read, so a page never\n // shows \"not found\" (or an empty form) for the frame before the read starts.\n const [loading, setLoading] = useState(Boolean(agentId));\n const [error, setError] = useState<Error | undefined>();\n\n const refetch = useCallback(async () => {\n if (!agentId) {\n setData(null);\n setLoading(false);\n return;\n }\n\n setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<GetAgentData>({\n query: GET_AGENT_DOCUMENT,\n variables: { id: agentId },\n fetchPolicy: 'network-only',\n });\n // Apollo v4 resolves (not rejects) with `result.error` set on GraphQL errors.\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw operationError instanceof Error ? operationError : new Error('Failed to load agent');\n }\n setData(result.data?.getBotmanorAgent ?? null);\n } catch (queryError) {\n setData(null);\n setError(queryError instanceof Error ? queryError : new Error('Failed to load agent'));\n } finally {\n setLoading(false);\n }\n }, [agentId, client]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nexport function useCreateAgent() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<AgentRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const createAgent = useCallback(\n async (input: CreateAgentInput) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<CreateAgentData>({\n mutation: CREATE_AGENT_DOCUMENT,\n variables: { input },\n });\n throwOperationError(result, 'Failed to create agent');\n\n const createdAgent = result.data?.createBotmanorAgent;\n if (!createdAgent) {\n throw new Error('Failed to create agent');\n }\n\n setState({ data: createdAgent, loading: false, error: undefined });\n return createdAgent;\n } catch (mutationError) {\n const error = new Error(graphqlErrorMessage(mutationError, 'Failed to create agent'), {\n cause: mutationError,\n });\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [createAgent, state] as const;\n}\n\nexport function useUpdateAgent() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<AgentRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const updateAgent = useCallback(\n async ({ agentId, input }: UpdateAgentInput) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<UpdateAgentData>({\n mutation: UPDATE_AGENT_DOCUMENT,\n variables: { id: agentId, input: buildMutationInput(input, UPDATE_AGENT_FIELDS) },\n });\n throwOperationError(result, 'Failed to update agent');\n\n const updatedAgent = result.data?.updateBotmanorAgent;\n if (!updatedAgent) {\n throw new Error('Failed to update agent');\n }\n\n setState({ data: updatedAgent, loading: false, error: undefined });\n return updatedAgent;\n } catch (mutationError) {\n const error = new Error(graphqlErrorMessage(mutationError, 'Failed to update agent'), {\n cause: mutationError,\n });\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [updateAgent, state] as const;\n}\n\nexport function useDeleteAgent() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<boolean>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const deleteAgent = useCallback(\n async (agentId: string) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<DeleteAgentData>({\n mutation: DELETE_AGENT_DOCUMENT,\n variables: { id: agentId },\n });\n throwOperationError(result, 'Failed to delete agent');\n\n const deleted = result.data?.deleteBotmanorAgent ?? false;\n setState({ data: deleted, loading: false, error: undefined });\n return deleted;\n } catch (mutationError) {\n const error = new Error(graphqlErrorMessage(mutationError, 'Failed to delete agent'), {\n cause: mutationError,\n });\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [deleteAgent, state] as const;\n}\n\n// ============================================================================\n// VERSIONING (BOFF-4381) — version history, publish, rollback\n// ============================================================================\n\nexport function useAgentVersions(agentId: string | undefined) {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [data, setData] = useState<AgentVersionRecord[]>([]);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>();\n\n const refetch = useCallback(async () => {\n if (!agentId) {\n setData([]);\n return;\n }\n\n setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<ListAgentVersionsData>({\n query: LIST_AGENT_VERSIONS_DOCUMENT,\n variables: { agentId, pagination: { limit: 50, offset: 0 } },\n fetchPolicy: 'network-only',\n });\n const versions = result.data?.listAgentVersions ?? [];\n // Newest first, regardless of what the server returned.\n setData(\n [...versions].sort((a, b) =>\n a.createdAt && b.createdAt ? b.createdAt.localeCompare(a.createdAt) : 0\n )\n );\n } catch (queryError) {\n setError(\n queryError instanceof Error ? queryError : new Error('Failed to load agent versions')\n );\n } finally {\n setLoading(false);\n }\n }, [agentId, client]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nexport function usePublishAgentVersion() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<AgentVersionRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const publishAgentVersion = useCallback(\n async ({\n agentId,\n versionId,\n changelog,\n }: {\n agentId: string;\n versionId: string;\n changelog?: string;\n }) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<PublishAgentVersionData>({\n mutation: PUBLISH_AGENT_VERSION_DOCUMENT,\n variables: { agentId, versionId, changelog: changelog?.trim() || undefined },\n });\n\n const published = result.data?.publishAgentVersion;\n if (!published) {\n throw new Error('Failed to publish agent version');\n }\n\n setState({ data: published, loading: false, error: undefined });\n return published;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error\n ? mutationError\n : new Error('Failed to publish agent version');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [publishAgentVersion, state] as const;\n}\n\nexport function useRollbackAgentVersion() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<AgentMutationState<AgentVersionRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const rollbackAgentVersion = useCallback(\n async ({ agentId, targetVersionId }: { agentId: string; targetVersionId: string }) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<RollbackAgentVersionData>({\n mutation: ROLLBACK_AGENT_VERSION_DOCUMENT,\n variables: { agentId, targetVersionId },\n });\n\n const rolledBack = result.data?.rollbackAgentVersion;\n if (!rolledBack) {\n throw new Error('Failed to roll back agent version');\n }\n\n setState({ data: rolledBack, loading: false, error: undefined });\n return rolledBack;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error\n ? mutationError\n : new Error('Failed to roll back agent version');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [rollbackAgentVersion, state] as const;\n}\n"],"mappings":";;;;;;;;AAgBA,IAAMA,IAAuB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8B1BC,IAAqB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCxBC,IAAwB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;GA2B3BC,IAAwB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgC3BC,IAAwB,CAAG;;;;GAO3BC,IAA+B,CAAG;;;;;;;;;;;;;;;GAiBlCC,IAAiC,CAAG;;;;;;;;;;;;GAcpCC,IAAkC,CAAG;;;;;;;;;;;;GA0DrCC,IAAiB,KACjBC,IAA2B,CAAC,GAyE5BC,IAAsBC,EAAmC;CAC7D,QAAQ;CACR,UAAU;CACV,cAAc;CACd,SAAS;CACT,aAAa;CACb,kBAAkB;CAClB,YAAY;CACZ,kBAAkB;CAClB,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,MAAME,EAAoBF,GAAgBG,CAAQ,GAAG,EAAE,OAAOH,EAAe,CAAC;AAE5F;AAEA,SAASI,EAAmB,GAAkC;CAC5D,OAAOC;AACT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