@burdenoff/microfe-botmanor 2026.1203.1 → 2026.1203.3

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.
@@ -103,13 +103,13 @@ var N = ({ label: e, value: t, icon: i, hint: a }) => /* @__PURE__ */ b("li", {
103
103
  hint: k("botlit.dashboard.usage.failed", "{{count}} failed", { count: h(R.failureCount) })
104
104
  }),
105
105
  /* @__PURE__ */ b(N, {
106
- label: k("botlit.dashboard.usage.cost", "Cost"),
106
+ label: k("botlit.dashboard.usage.byoCost", "BYO provider spend"),
107
107
  value: I.loading || R.totalCost === null ? "—" : p(R.totalCost),
108
108
  icon: /* @__PURE__ */ b(E, {
109
109
  className: "h-5 w-5",
110
110
  "aria-hidden": "true"
111
111
  }),
112
- hint: k("botlit.dashboard.usage.tokens", "{{count}} tokens", { count: g(R.totalTokens) })
112
+ hint: k("botlit.dashboard.usage.byoCostHint", "{{count}} tokens · informational (billed by your provider; platform AI credits are metered separately)", { count: g(R.totalTokens) })
113
113
  }),
114
114
  /* @__PURE__ */ b(N, {
115
115
  label: k("botlit.dashboard.usage.avgLatency", "Avg latency"),
@@ -1 +1 @@
1
- {"version":3,"file":"DashboardUsagePanel.js","names":["_Fragment","Fragment$1","TOP_AGENTS","HEALTH_WARN_RATE","healthOf","finishedRuns","successRate","topAgents","rows","row","b","a","limit","Kpi","Card","CardContent","icon","label","hint","value","DashboardUsagePanel","t","useTr","useBotlit","days","setDays","useState","daily","useDailyUsageStats","agents","DailyUsageDimension","DailyUsageInterval","totals","useMemo","sumUsage","byDay","index","windowDays","date","maxRuns","day","leaders","health","healthLabel","ErrorState","formatNumber","Activity","formatRate","CheckCircle2","formatCurrency","DollarSign","formatTokens","formatDuration","Timer","CardHeader","CardTitle","runs","failed","height","failedShare","AlertTriangle","Link","getPath","Trophy"],"sources":["../../../src/botlit/components/DashboardUsagePanel.tsx"],"sourcesContent":["/**\n * Dashboard usage panel (BOFF-15360 package E).\n * @module botlit/components\n *\n * Workspace runs, success rate, cost and latency over the last 7 or 30 days,\n * a per-day run chart, the busiest agents and a health summary. Every number\n * comes from `getDailyUsageStats`, counted by the service over the whole\n * window — never from rows the browser loaded.\n */\n\nimport { useMemo, useState, type FC, type ReactNode } from 'react';\nimport { Link } from 'react-router';\nimport { Activity, AlertTriangle, CheckCircle2, DollarSign, Timer, Trophy } from 'lucide-react';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { useBotlit } from '../providers/BotlitProvider';\nimport { Card, CardContent, CardHeader, CardTitle } from './Card';\nimport { ErrorState } from './ErrorState';\nimport {\n DailyUsageDimension,\n DailyUsageInterval,\n sumUsage,\n useDailyUsageStats,\n windowDays,\n type DailyUsageRecord,\n} from '../hooks/useUsageStats';\nimport { formatRate } from './RunStatsCard';\nimport {\n formatCurrency,\n formatDuration,\n formatNumber,\n formatTokens,\n MISSING_VALUE,\n} from '../utils/formatters';\n\nconst TOP_AGENTS = 5;\n/** Below this success rate over finished runs the workspace is flagged. */\nconst HEALTH_WARN_RATE = 0.9;\n\ntype Health = 'idle' | 'healthy' | 'degraded';\n\nexport function healthOf(successRate: number | null, finishedRuns: number): Health {\n if (finishedRuns === 0 || successRate === null) return 'idle';\n return successRate >= HEALTH_WARN_RATE ? 'healthy' : 'degraded';\n}\n\n/** Rank agents by runs over the window (the service already sums the window). */\nexport function topAgents(\n rows: readonly DailyUsageRecord[],\n limit = TOP_AGENTS\n): DailyUsageRecord[] {\n return [...rows]\n .filter((row) => row.agentId)\n .sort((a, b) => b.executionCount - a.executionCount)\n .slice(0, limit);\n}\n\nconst Kpi: FC<{ label: string; value: string; icon: ReactNode; hint?: string }> = ({\n label,\n value,\n icon,\n hint,\n}) => (\n <li>\n <Card treatment=\"metric\">\n <CardContent className=\"pt-6\">\n <div className=\"flex items-center gap-4\">\n <div className=\"rounded-lg bg-[var(--color-accent-soft)] p-3 text-text-primary\">\n {icon}\n </div>\n <div className=\"flex flex-col-reverse\">\n <p className=\"text-sm text-text-secondary\">\n {label}\n {hint ? <span className=\"block text-xs\">{hint}</span> : null}\n </p>\n <p className=\"text-2xl font-bold tabular-nums text-text-primary\">{value}</p>\n </div>\n </div>\n </CardContent>\n </Card>\n </li>\n);\n\nexport const DashboardUsagePanel: FC = () => {\n const t = useTr();\n const { getPath } = useBotlit();\n const [days, setDays] = useState(30);\n\n const daily = useDailyUsageStats({ days });\n const agents = useDailyUsageStats({\n days,\n dimension: DailyUsageDimension.Agent,\n interval: DailyUsageInterval.Window,\n });\n\n const totals = useMemo(() => sumUsage(daily.data), [daily.data]);\n const byDay = useMemo(() => {\n const index = new Map(daily.data.map((row) => [row.date, row]));\n return windowDays(days).map((date) => ({ date, row: index.get(date) }));\n }, [daily.data, days]);\n const maxRuns = Math.max(1, ...byDay.map((day) => day.row?.executionCount ?? 0));\n const leaders = useMemo(() => topAgents(agents.data), [agents.data]);\n const health = healthOf(totals.successRate, totals.successCount + totals.failureCount);\n\n const healthLabel =\n health === 'healthy'\n ? t('botlit.dashboard.usage.health.healthy', 'Healthy')\n : health === 'degraded'\n ? t('botlit.dashboard.usage.health.degraded', 'Needs attention')\n : t('botlit.dashboard.usage.health.idle', 'No finished runs');\n\n return (\n <section\n aria-labelledby=\"botmanor-usage-heading\"\n className=\"space-y-4\"\n data-testid=\"dashboard-usage-panel\"\n >\n <div className=\"flex flex-wrap items-center justify-between gap-2\">\n <h2 id=\"botmanor-usage-heading\" className=\"text-lg font-semibold text-text-primary\">\n {t('botlit.dashboard.usage.title', 'Runs and health')}\n </h2>\n <div\n role=\"group\"\n aria-label={t('botlit.runStats.rangeLabel', 'Period')}\n className=\"flex gap-1\"\n >\n {[7, 30].map((value) => (\n <button\n key={value}\n type=\"button\"\n aria-pressed={days === value}\n onClick={() => setDays(value)}\n className={`rounded-md border px-2 py-1 text-xs transition-colors ${\n days === value\n ? 'border-border-strong bg-accent text-text-primary'\n : 'border-border-seam text-text-secondary hover:border-border-strong'\n }`}\n >\n {value === 7\n ? t('botlit.runStats.range.7d', '7 days')\n : t('botlit.runStats.range.30d', '30 days')}\n </button>\n ))}\n </div>\n </div>\n\n {daily.error ? (\n <ErrorState\n resource={t('botlit.dashboard.usage.resource', 'usage statistics')}\n error={daily.error}\n onRetry={() => void daily.refetch()}\n />\n ) : (\n <>\n <ul className=\"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4\">\n <Kpi\n label={t('botlit.dashboard.usage.runs', 'Runs')}\n value={daily.loading ? MISSING_VALUE : formatNumber(totals.executionCount)}\n icon={<Activity className=\"h-5 w-5\" aria-hidden=\"true\" />}\n hint={\n totals.inProgressCount > 0\n ? t('botlit.dashboard.usage.inProgress', '{{count}} in progress', {\n count: formatNumber(totals.inProgressCount),\n })\n : undefined\n }\n />\n <Kpi\n label={t('botlit.dashboard.usage.successRate', 'Success rate')}\n value={daily.loading ? MISSING_VALUE : formatRate(totals.successRate)}\n icon={<CheckCircle2 className=\"h-5 w-5\" aria-hidden=\"true\" />}\n hint={t('botlit.dashboard.usage.failed', '{{count}} failed', {\n count: formatNumber(totals.failureCount),\n })}\n />\n <Kpi\n label={t('botlit.dashboard.usage.cost', 'Cost')}\n value={\n daily.loading || totals.totalCost === null\n ? MISSING_VALUE\n : formatCurrency(totals.totalCost)\n }\n icon={<DollarSign className=\"h-5 w-5\" aria-hidden=\"true\" />}\n hint={t('botlit.dashboard.usage.tokens', '{{count}} tokens', {\n count: formatTokens(totals.totalTokens),\n })}\n />\n <Kpi\n label={t('botlit.dashboard.usage.avgLatency', 'Avg latency')}\n value={\n daily.loading || totals.avgDurationMs === null\n ? MISSING_VALUE\n : formatDuration(Math.round(totals.avgDurationMs))\n }\n icon={<Timer className=\"h-5 w-5\" aria-hidden=\"true\" />}\n />\n </ul>\n\n <div className=\"grid grid-cols-1 gap-6 lg:grid-cols-3\">\n <Card treatment=\"insight\" className=\"lg:col-span-2\">\n <CardHeader>\n <CardTitle as=\"h3\">\n {t('botlit.dashboard.usage.perDay', 'Runs per day (UTC)')}\n </CardTitle>\n </CardHeader>\n <CardContent>\n <div\n className=\"flex h-32 items-end gap-0.5\"\n role=\"img\"\n aria-label={t(\n 'botlit.dashboard.usage.chartLabel',\n '{{count}} runs over the last {{days}} days',\n { count: formatNumber(totals.executionCount), days: String(days) }\n )}\n >\n {byDay.map(({ date, row }) => {\n const runs = row?.executionCount ?? 0;\n const failed = row?.failureCount ?? 0;\n const height = `${(runs / maxRuns) * 100}%`;\n const failedShare = runs > 0 ? `${(failed / runs) * 100}%` : '0%';\n return (\n <div\n key={date}\n className=\"flex h-full flex-1 flex-col justify-end\"\n title={t(\n 'botlit.dashboard.usage.dayTitle',\n '{{date}}: {{runs}} runs, {{failed}} failed',\n {\n date,\n runs: formatNumber(runs),\n failed: formatNumber(failed),\n }\n )}\n >\n <div\n className=\"flex w-full flex-col overflow-hidden rounded-sm bg-[var(--color-chart-1)]\"\n style={{ height }}\n >\n <div\n className=\"w-full bg-status-error-text\"\n style={{ height: failedShare }}\n />\n </div>\n </div>\n );\n })}\n </div>\n <div className=\"mt-2 flex justify-between text-xs text-text-secondary\">\n <span>{byDay[0]?.date}</span>\n <span>{byDay[byDay.length - 1]?.date}</span>\n </div>\n </CardContent>\n </Card>\n\n <Card treatment=\"insight\">\n <CardHeader>\n <CardTitle as=\"h3\" className=\"flex items-center gap-2\">\n {health === 'degraded' ? (\n <AlertTriangle className=\"h-4 w-4 text-status-error-text\" aria-hidden=\"true\" />\n ) : (\n <CheckCircle2 className=\"h-4 w-4 text-status-success-text\" aria-hidden=\"true\" />\n )}\n {t('botlit.dashboard.usage.healthTitle', 'Health')}\n </CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-2 text-sm\">\n <p className=\"font-medium text-text-primary\" data-testid=\"dashboard-health\">\n {healthLabel}\n </p>\n <p className=\"text-text-secondary\">\n {t(\n 'botlit.dashboard.usage.healthDetail',\n '{{succeeded}} succeeded, {{failed}} failed or timed out, {{open}} in progress.',\n {\n succeeded: formatNumber(totals.successCount),\n failed: formatNumber(totals.failureCount),\n open: formatNumber(totals.inProgressCount),\n }\n )}\n </p>\n <Link\n to={getPath('executions')}\n className=\"inline-block text-text-primary underline underline-offset-2\"\n >\n {t('botlit.dashboard.usage.viewExecutions', 'View executions')}\n </Link>\n </CardContent>\n </Card>\n </div>\n\n <Card treatment=\"insight\">\n <CardHeader>\n <CardTitle as=\"h3\" className=\"flex items-center gap-2\">\n <Trophy className=\"h-4 w-4\" aria-hidden=\"true\" />\n {t('botlit.dashboard.usage.topAgents', 'Top agents')}\n </CardTitle>\n </CardHeader>\n <CardContent>\n {agents.error ? (\n <ErrorState\n resource={t('botlit.dashboard.usage.resourceAgents', 'agent usage')}\n error={agents.error}\n onRetry={() => void agents.refetch()}\n />\n ) : leaders.length === 0 ? (\n <p className=\"text-sm text-text-secondary\">\n {agents.loading\n ? t('botlit.common.loading', 'Loading')\n : t('botlit.dashboard.usage.noAgentRuns', 'No agent runs in this period.')}\n </p>\n ) : (\n <table className=\"w-full text-sm\">\n <thead>\n <tr className=\"text-left text-text-secondary\">\n <th className=\"py-1 font-normal\">\n {t('botlit.dashboard.usage.agent', 'Agent')}\n </th>\n <th className=\"py-1 text-right font-normal\">\n {t('botlit.dashboard.usage.runs', 'Runs')}\n </th>\n <th className=\"py-1 text-right font-normal\">\n {t('botlit.dashboard.usage.successRate', 'Success rate')}\n </th>\n <th className=\"hidden py-1 text-right font-normal sm:table-cell\">\n {t('botlit.dashboard.usage.cost', 'Cost')}\n </th>\n <th className=\"hidden py-1 text-right font-normal sm:table-cell\">\n {t('botlit.dashboard.usage.avgLatency', 'Avg latency')}\n </th>\n </tr>\n </thead>\n <tbody>\n {leaders.map((row) => (\n <tr key={row.agentId} className=\"border-t border-border-seam\">\n <td className=\"py-2\">\n <Link\n to={getPath(`agents/${row.agentId}`)}\n className=\"font-medium text-text-primary hover:underline\"\n >\n {row.agentName ??\n t('botlit.dashboard.usage.deletedAgent', 'Deleted agent')}\n </Link>\n </td>\n <td className=\"py-2 text-right tabular-nums\">\n {formatNumber(row.executionCount)}\n </td>\n <td className=\"py-2 text-right tabular-nums\">\n {formatRate(row.successRate)}\n </td>\n <td className=\"hidden py-2 text-right tabular-nums sm:table-cell\">\n {row.totalCost === null ? MISSING_VALUE : formatCurrency(row.totalCost)}\n </td>\n <td className=\"hidden py-2 text-right tabular-nums sm:table-cell\">\n {row.avgDurationMs === null\n ? MISSING_VALUE\n : formatDuration(Math.round(row.avgDurationMs))}\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n )}\n </CardContent>\n </Card>\n </>\n )}\n </section>\n );\n};\n"],"mappings":";;;;;;;;;;;;;AAkCA,IAAME,IAAa,GAEbC,IAAmB;AAIzB,SAAgBC,EAAS,GAA4B,GAA8B;CAEjF,OADIC,MAAiB,KAAKC,MAAgB,OAAa,SAChDA,KAAeH,IAAmB,YAAY;AACvD;AAGA,SAAgBI,EACd,GACA,IAAQL,GACY;CACpB,OAAO,CAAC,GAAGM,CAAI,CAAC,CACb,QAAQ,MAAQC,EAAI,OAAO,CAAC,CAC5B,MAAM,GAAG,MAAMC,EAAE,iBAAiBC,EAAE,cAAc,CAAC,CACnD,MAAM,GAAGC,CAAK;AACnB;AAEA,IAAMC,KAA6E,EACjF,UACA,UACA,SACA,cAEA,kBAAC,MAAD,EAAA,UACE,kBAACC,GAAD;CAAM,WAAU;CACd,UAAA,kBAACC,GAAD;EAAa,WAAU;EACrB,UAAA,kBAAC,OAAD;GAAK,WAAU;GAAf,UAAA,CACE,kBAAC,OAAD;IAAK,WAAU;IACZ,UAAAC;GACE,CAAA,GACL,kBAAC,OAAD;IAAK,WAAU;IAAf,UAAA,CACE,kBAAC,KAAD;KAAG,WAAU;KAAb,UAAA,CACGC,GACAC,IAAO,kBAAC,QAAD;MAAM,WAAU;MAAiB,UAAAA;KAAW,CAAA,IAAI,IACvD;IACH,CAAA,GAAA,kBAAC,KAAD;KAAG,WAAU;KAAqD,UAAAC;IAAS,CAAA,CACxE;GACF,CAAA,CAAA;;CACM,CAAA;AACT,C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OACzB,CAAA;OACJ,kBAAC,MAAD;QAAI,WAAU;QACX,UAAAA,EAAI,cAAc,OAAA,MAAuBwC,EAAexC,EAAI,SAAS;OACpE,CAAA;OACJ,kBAAC,MAAD;QAAI,WAAU;QACX,UAAAA,EAAI,kBAAkB,OAAA,MAEnB2C,EAAe,KAAK,MAAM3C,EAAI,aAAa,CAAC;OAC9C,CAAA;MACF;KAxBK,GAAAA,EAAI,OAwBT,CACL,EACI,CAAA,CACF;IAEE,CAAA,EAAA,CAAA,CACT;;EACN,EAAA,CAAA,CAEG;;AAEb"}
1
+ {"version":3,"file":"DashboardUsagePanel.js","names":["_Fragment","Fragment$1","TOP_AGENTS","HEALTH_WARN_RATE","healthOf","finishedRuns","successRate","topAgents","rows","row","b","a","limit","Kpi","Card","CardContent","icon","label","hint","value","DashboardUsagePanel","t","useTr","useBotlit","days","setDays","useState","daily","useDailyUsageStats","agents","DailyUsageDimension","DailyUsageInterval","totals","useMemo","sumUsage","byDay","index","windowDays","date","maxRuns","day","leaders","health","healthLabel","ErrorState","formatNumber","Activity","formatRate","CheckCircle2","formatCurrency","DollarSign","formatTokens","formatDuration","Timer","CardHeader","CardTitle","runs","failed","height","failedShare","AlertTriangle","Link","getPath","Trophy"],"sources":["../../../src/botlit/components/DashboardUsagePanel.tsx"],"sourcesContent":["/**\n * Dashboard usage panel (BOFF-15360 package E).\n * @module botlit/components\n *\n * Workspace runs, success rate, cost and latency over the last 7 or 30 days,\n * a per-day run chart, the busiest agents and a health summary. Every number\n * comes from `getDailyUsageStats`, counted by the service over the whole\n * window — never from rows the browser loaded.\n */\n\nimport { useMemo, useState, type FC, type ReactNode } from 'react';\nimport { Link } from 'react-router';\nimport { Activity, AlertTriangle, CheckCircle2, DollarSign, Timer, Trophy } from 'lucide-react';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { useBotlit } from '../providers/BotlitProvider';\nimport { Card, CardContent, CardHeader, CardTitle } from './Card';\nimport { ErrorState } from './ErrorState';\nimport {\n DailyUsageDimension,\n DailyUsageInterval,\n sumUsage,\n useDailyUsageStats,\n windowDays,\n type DailyUsageRecord,\n} from '../hooks/useUsageStats';\nimport { formatRate } from './RunStatsCard';\nimport {\n formatCurrency,\n formatDuration,\n formatNumber,\n formatTokens,\n MISSING_VALUE,\n} from '../utils/formatters';\n\nconst TOP_AGENTS = 5;\n/** Below this success rate over finished runs the workspace is flagged. */\nconst HEALTH_WARN_RATE = 0.9;\n\ntype Health = 'idle' | 'healthy' | 'degraded';\n\nexport function healthOf(successRate: number | null, finishedRuns: number): Health {\n if (finishedRuns === 0 || successRate === null) return 'idle';\n return successRate >= HEALTH_WARN_RATE ? 'healthy' : 'degraded';\n}\n\n/** Rank agents by runs over the window (the service already sums the window). */\nexport function topAgents(\n rows: readonly DailyUsageRecord[],\n limit = TOP_AGENTS\n): DailyUsageRecord[] {\n return [...rows]\n .filter((row) => row.agentId)\n .sort((a, b) => b.executionCount - a.executionCount)\n .slice(0, limit);\n}\n\nconst Kpi: FC<{ label: string; value: string; icon: ReactNode; hint?: string }> = ({\n label,\n value,\n icon,\n hint,\n}) => (\n <li>\n <Card treatment=\"metric\">\n <CardContent className=\"pt-6\">\n <div className=\"flex items-center gap-4\">\n <div className=\"rounded-lg bg-[var(--color-accent-soft)] p-3 text-text-primary\">\n {icon}\n </div>\n <div className=\"flex flex-col-reverse\">\n <p className=\"text-sm text-text-secondary\">\n {label}\n {hint ? <span className=\"block text-xs\">{hint}</span> : null}\n </p>\n <p className=\"text-2xl font-bold tabular-nums text-text-primary\">{value}</p>\n </div>\n </div>\n </CardContent>\n </Card>\n </li>\n);\n\nexport const DashboardUsagePanel: FC = () => {\n const t = useTr();\n const { getPath } = useBotlit();\n const [days, setDays] = useState(30);\n\n const daily = useDailyUsageStats({ days });\n const agents = useDailyUsageStats({\n days,\n dimension: DailyUsageDimension.Agent,\n interval: DailyUsageInterval.Window,\n });\n\n const totals = useMemo(() => sumUsage(daily.data), [daily.data]);\n const byDay = useMemo(() => {\n const index = new Map(daily.data.map((row) => [row.date, row]));\n return windowDays(days).map((date) => ({ date, row: index.get(date) }));\n }, [daily.data, days]);\n const maxRuns = Math.max(1, ...byDay.map((day) => day.row?.executionCount ?? 0));\n const leaders = useMemo(() => topAgents(agents.data), [agents.data]);\n const health = healthOf(totals.successRate, totals.successCount + totals.failureCount);\n\n const healthLabel =\n health === 'healthy'\n ? t('botlit.dashboard.usage.health.healthy', 'Healthy')\n : health === 'degraded'\n ? t('botlit.dashboard.usage.health.degraded', 'Needs attention')\n : t('botlit.dashboard.usage.health.idle', 'No finished runs');\n\n return (\n <section\n aria-labelledby=\"botmanor-usage-heading\"\n className=\"space-y-4\"\n data-testid=\"dashboard-usage-panel\"\n >\n <div className=\"flex flex-wrap items-center justify-between gap-2\">\n <h2 id=\"botmanor-usage-heading\" className=\"text-lg font-semibold text-text-primary\">\n {t('botlit.dashboard.usage.title', 'Runs and health')}\n </h2>\n <div\n role=\"group\"\n aria-label={t('botlit.runStats.rangeLabel', 'Period')}\n className=\"flex gap-1\"\n >\n {[7, 30].map((value) => (\n <button\n key={value}\n type=\"button\"\n aria-pressed={days === value}\n onClick={() => setDays(value)}\n className={`rounded-md border px-2 py-1 text-xs transition-colors ${\n days === value\n ? 'border-border-strong bg-accent text-text-primary'\n : 'border-border-seam text-text-secondary hover:border-border-strong'\n }`}\n >\n {value === 7\n ? t('botlit.runStats.range.7d', '7 days')\n : t('botlit.runStats.range.30d', '30 days')}\n </button>\n ))}\n </div>\n </div>\n\n {daily.error ? (\n <ErrorState\n resource={t('botlit.dashboard.usage.resource', 'usage statistics')}\n error={daily.error}\n onRetry={() => void daily.refetch()}\n />\n ) : (\n <>\n <ul className=\"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4\">\n <Kpi\n label={t('botlit.dashboard.usage.runs', 'Runs')}\n value={daily.loading ? MISSING_VALUE : formatNumber(totals.executionCount)}\n icon={<Activity className=\"h-5 w-5\" aria-hidden=\"true\" />}\n hint={\n totals.inProgressCount > 0\n ? t('botlit.dashboard.usage.inProgress', '{{count}} in progress', {\n count: formatNumber(totals.inProgressCount),\n })\n : undefined\n }\n />\n <Kpi\n label={t('botlit.dashboard.usage.successRate', 'Success rate')}\n value={daily.loading ? MISSING_VALUE : formatRate(totals.successRate)}\n icon={<CheckCircle2 className=\"h-5 w-5\" aria-hidden=\"true\" />}\n hint={t('botlit.dashboard.usage.failed', '{{count}} failed', {\n count: formatNumber(totals.failureCount),\n })}\n />\n <Kpi\n label={t('botlit.dashboard.usage.byoCost', 'BYO provider spend')}\n value={\n daily.loading || totals.totalCost === null\n ? MISSING_VALUE\n : formatCurrency(totals.totalCost)\n }\n icon={<DollarSign className=\"h-5 w-5\" aria-hidden=\"true\" />}\n hint={t(\n 'botlit.dashboard.usage.byoCostHint',\n '{{count}} tokens · informational (billed by your provider; platform AI credits are metered separately)',\n {\n count: formatTokens(totals.totalTokens),\n }\n )}\n />\n <Kpi\n label={t('botlit.dashboard.usage.avgLatency', 'Avg latency')}\n value={\n daily.loading || totals.avgDurationMs === null\n ? MISSING_VALUE\n : formatDuration(Math.round(totals.avgDurationMs))\n }\n icon={<Timer className=\"h-5 w-5\" aria-hidden=\"true\" />}\n />\n </ul>\n\n <div className=\"grid grid-cols-1 gap-6 lg:grid-cols-3\">\n <Card treatment=\"insight\" className=\"lg:col-span-2\">\n <CardHeader>\n <CardTitle as=\"h3\">\n {t('botlit.dashboard.usage.perDay', 'Runs per day (UTC)')}\n </CardTitle>\n </CardHeader>\n <CardContent>\n <div\n className=\"flex h-32 items-end gap-0.5\"\n role=\"img\"\n aria-label={t(\n 'botlit.dashboard.usage.chartLabel',\n '{{count}} runs over the last {{days}} days',\n { count: formatNumber(totals.executionCount), days: String(days) }\n )}\n >\n {byDay.map(({ date, row }) => {\n const runs = row?.executionCount ?? 0;\n const failed = row?.failureCount ?? 0;\n const height = `${(runs / maxRuns) * 100}%`;\n const failedShare = runs > 0 ? `${(failed / runs) * 100}%` : '0%';\n return (\n <div\n key={date}\n className=\"flex h-full flex-1 flex-col justify-end\"\n title={t(\n 'botlit.dashboard.usage.dayTitle',\n '{{date}}: {{runs}} runs, {{failed}} failed',\n {\n date,\n runs: formatNumber(runs),\n failed: formatNumber(failed),\n }\n )}\n >\n <div\n className=\"flex w-full flex-col overflow-hidden rounded-sm bg-[var(--color-chart-1)]\"\n style={{ height }}\n >\n <div\n className=\"w-full bg-status-error-text\"\n style={{ height: failedShare }}\n />\n </div>\n </div>\n );\n })}\n </div>\n <div className=\"mt-2 flex justify-between text-xs text-text-secondary\">\n <span>{byDay[0]?.date}</span>\n <span>{byDay[byDay.length - 1]?.date}</span>\n </div>\n </CardContent>\n </Card>\n\n <Card treatment=\"insight\">\n <CardHeader>\n <CardTitle as=\"h3\" className=\"flex items-center gap-2\">\n {health === 'degraded' ? (\n <AlertTriangle className=\"h-4 w-4 text-status-error-text\" aria-hidden=\"true\" />\n ) : (\n <CheckCircle2 className=\"h-4 w-4 text-status-success-text\" aria-hidden=\"true\" />\n )}\n {t('botlit.dashboard.usage.healthTitle', 'Health')}\n </CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-2 text-sm\">\n <p className=\"font-medium text-text-primary\" data-testid=\"dashboard-health\">\n {healthLabel}\n </p>\n <p className=\"text-text-secondary\">\n {t(\n 'botlit.dashboard.usage.healthDetail',\n '{{succeeded}} succeeded, {{failed}} failed or timed out, {{open}} in progress.',\n {\n succeeded: formatNumber(totals.successCount),\n failed: formatNumber(totals.failureCount),\n open: formatNumber(totals.inProgressCount),\n }\n )}\n </p>\n <Link\n to={getPath('executions')}\n className=\"inline-block text-text-primary underline underline-offset-2\"\n >\n {t('botlit.dashboard.usage.viewExecutions', 'View executions')}\n </Link>\n </CardContent>\n </Card>\n </div>\n\n <Card treatment=\"insight\">\n <CardHeader>\n <CardTitle as=\"h3\" className=\"flex items-center gap-2\">\n <Trophy className=\"h-4 w-4\" aria-hidden=\"true\" />\n {t('botlit.dashboard.usage.topAgents', 'Top agents')}\n </CardTitle>\n </CardHeader>\n <CardContent>\n {agents.error ? (\n <ErrorState\n resource={t('botlit.dashboard.usage.resourceAgents', 'agent usage')}\n error={agents.error}\n onRetry={() => void agents.refetch()}\n />\n ) : leaders.length === 0 ? (\n <p className=\"text-sm text-text-secondary\">\n {agents.loading\n ? t('botlit.common.loading', 'Loading')\n : t('botlit.dashboard.usage.noAgentRuns', 'No agent runs in this period.')}\n </p>\n ) : (\n <table className=\"w-full text-sm\">\n <thead>\n <tr className=\"text-left text-text-secondary\">\n <th className=\"py-1 font-normal\">\n {t('botlit.dashboard.usage.agent', 'Agent')}\n </th>\n <th className=\"py-1 text-right font-normal\">\n {t('botlit.dashboard.usage.runs', 'Runs')}\n </th>\n <th className=\"py-1 text-right font-normal\">\n {t('botlit.dashboard.usage.successRate', 'Success rate')}\n </th>\n <th className=\"hidden py-1 text-right font-normal sm:table-cell\">\n {t('botlit.dashboard.usage.cost', 'Cost')}\n </th>\n <th className=\"hidden py-1 text-right font-normal sm:table-cell\">\n {t('botlit.dashboard.usage.avgLatency', 'Avg latency')}\n </th>\n </tr>\n </thead>\n <tbody>\n {leaders.map((row) => (\n <tr key={row.agentId} className=\"border-t border-border-seam\">\n <td className=\"py-2\">\n <Link\n to={getPath(`agents/${row.agentId}`)}\n className=\"font-medium text-text-primary hover:underline\"\n >\n {row.agentName ??\n t('botlit.dashboard.usage.deletedAgent', 'Deleted agent')}\n </Link>\n </td>\n <td className=\"py-2 text-right tabular-nums\">\n {formatNumber(row.executionCount)}\n </td>\n <td className=\"py-2 text-right tabular-nums\">\n {formatRate(row.successRate)}\n </td>\n <td className=\"hidden py-2 text-right tabular-nums sm:table-cell\">\n {row.totalCost === null ? MISSING_VALUE : formatCurrency(row.totalCost)}\n </td>\n <td className=\"hidden py-2 text-right tabular-nums sm:table-cell\">\n {row.avgDurationMs === null\n ? MISSING_VALUE\n : formatDuration(Math.round(row.avgDurationMs))}\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n )}\n </CardContent>\n </Card>\n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CAAA,CAEG;;AAEb"}
@@ -23,6 +23,9 @@ export interface AgentRecord {
23
23
  lastExecutedAt?: string | null;
24
24
  specialization?: string | null;
25
25
  systemPrompt?: string | null;
26
+ /** ISO 42001 IA-001 G1 (BOFF-10024): default-on AI disclosure on first channel reply. */
27
+ aiDisclosureEnabled?: boolean | null;
28
+ aiDisclosureText?: string | null;
26
29
  temperature?: number | null;
27
30
  maxTokens?: number | null;
28
31
  maxConcurrentExecutions?: number | null;
@@ -64,6 +67,8 @@ interface CreateAgentInput {
64
67
  avatar?: string;
65
68
  type: string;
66
69
  systemPrompt: string;
70
+ aiDisclosureEnabled?: boolean;
71
+ aiDisclosureText?: string;
67
72
  temperature?: number;
68
73
  maxTokens?: number;
69
74
  maxConcurrentExecutions?: number;
@@ -28,6 +28,8 @@ var m = f`
28
28
  lastExecutedAt
29
29
  specialization
30
30
  systemPrompt
31
+ aiDisclosureEnabled
32
+ aiDisclosureText
31
33
  temperature
32
34
  maxTokens
33
35
  maxConcurrentExecutions
@@ -59,6 +61,8 @@ var m = f`
59
61
  llmModelId
60
62
  fallbackModelIds
61
63
  systemPrompt
64
+ aiDisclosureEnabled
65
+ aiDisclosureText
62
66
  temperature
63
67
  maxTokens
64
68
  maxConcurrentExecutions
@@ -84,6 +88,8 @@ var m = f`
84
88
  llmModelId
85
89
  fallbackModelIds
86
90
  systemPrompt
91
+ aiDisclosureEnabled
92
+ aiDisclosureText
87
93
  temperature
88
94
  maxTokens
89
95
  maxConcurrentExecutions
@@ -145,6 +151,8 @@ var m = f`
145
151
  specialization: !0,
146
152
  status: !0,
147
153
  systemPrompt: !0,
154
+ aiDisclosureEnabled: !0,
155
+ aiDisclosureText: !0,
148
156
  tagIds: !0,
149
157
  tags: !0,
150
158
  temperature: !0,
@@ -1 +1 @@
1
- {"version":3,"file":"useAgents.js","names":["GET_AGENT_DOCUMENT","CREATE_AGENT_DOCUMENT","UPDATE_AGENT_DOCUMENT","DELETE_AGENT_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","ListBotmanorAgentsPageDocument","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","NO_AGENT_VERSIONS","useAgentVersions","ListBotmanorAgentVersionsPageDocument","b","a","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 {\n ListBotmanorAgentsPageDocument,\n ListBotmanorAgentVersionsPageDocument,\n type ListBotmanorAgentVersionsPageQuery,\n type ListBotmanorAgentsPageQuery,\n} from '../../generated/wspace-operations';\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 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 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\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 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<ListBotmanorAgentsPageQuery, AgentRecord, AgentRecord[]>({\n document: ListBotmanorAgentsPageDocument,\n variables,\n pageSize: LIST_PAGE_SIZE,\n extractRows: (data) => data?.listBotmanorAgentsPage.items ?? [],\n extractNextOffset: (data) => data?.listBotmanorAgentsPage.nextOffset ?? null,\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\ntype AgentVersionListItem =\n ListBotmanorAgentVersionsPageQuery['listBotmanorAgentVersionsPage']['items'][number];\nconst NO_AGENT_VERSIONS: AgentVersionRecord[] = [];\n\nexport function useAgentVersions(\n agentId: string | undefined\n): PaginatedQueryResult<AgentVersionRecord[]> {\n const variables = useMemo(() => ({ agentId }), [agentId]);\n return useWorkspacePaginatedQuery<\n ListBotmanorAgentVersionsPageQuery,\n AgentVersionListItem,\n AgentVersionRecord[]\n >({\n document: ListBotmanorAgentVersionsPageDocument,\n variables,\n pageSize: 50,\n extractRows: (data) => data?.listBotmanorAgentVersionsPage.items,\n extractNextOffset: (data) => data?.listBotmanorAgentVersionsPage.nextOffset ?? null,\n select: (rows) => [...rows].sort((a, b) => b.createdAt.localeCompare(a.createdAt)),\n fallback: NO_AGENT_VERSIONS,\n enabled: Boolean(agentId),\n errorMessage: 'Failed to load agent versions',\n });\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":";;;;;;;;;AAsBA,IAAMA,IAAqB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCxBC,IAAwB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;GA2B3BC,IAAwB,CAAG;;;;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ATE_AGENT_DOCUMENT","UPDATE_AGENT_DOCUMENT","DELETE_AGENT_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","ListBotmanorAgentsPageDocument","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","NO_AGENT_VERSIONS","useAgentVersions","ListBotmanorAgentVersionsPageDocument","b","a","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 {\n ListBotmanorAgentsPageDocument,\n ListBotmanorAgentVersionsPageDocument,\n type ListBotmanorAgentVersionsPageQuery,\n type ListBotmanorAgentsPageQuery,\n} from '../../generated/wspace-operations';\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 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 aiDisclosureEnabled\n aiDisclosureText\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 aiDisclosureEnabled\n aiDisclosureText\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 aiDisclosureEnabled\n aiDisclosureText\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 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 /** ISO 42001 IA-001 G1 (BOFF-10024): default-on AI disclosure on first channel reply. */\n aiDisclosureEnabled?: boolean | null;\n aiDisclosureText?: 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\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 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 aiDisclosureEnabled?: boolean;\n aiDisclosureText?: 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 aiDisclosureEnabled: true,\n aiDisclosureText: 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<ListBotmanorAgentsPageQuery, AgentRecord, AgentRecord[]>({\n document: ListBotmanorAgentsPageDocument,\n variables,\n pageSize: LIST_PAGE_SIZE,\n extractRows: (data) => data?.listBotmanorAgentsPage.items ?? [],\n extractNextOffset: (data) => data?.listBotmanorAgentsPage.nextOffset ?? null,\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\ntype AgentVersionListItem =\n ListBotmanorAgentVersionsPageQuery['listBotmanorAgentVersionsPage']['items'][number];\nconst NO_AGENT_VERSIONS: AgentVersionRecord[] = [];\n\nexport function useAgentVersions(\n agentId: string | undefined\n): PaginatedQueryResult<AgentVersionRecord[]> {\n const variables = useMemo(() => ({ agentId }), [agentId]);\n return useWorkspacePaginatedQuery<\n ListBotmanorAgentVersionsPageQuery,\n AgentVersionListItem,\n AgentVersionRecord[]\n >({\n document: ListBotmanorAgentVersionsPageDocument,\n variables,\n pageSize: 50,\n extractRows: (data) => data?.listBotmanorAgentVersionsPage.items,\n extractNextOffset: (data) => data?.listBotmanorAgentVersionsPage.nextOffset ?? null,\n select: (rows) => [...rows].sort((a, b) => b.createdAt.localeCompare(a.createdAt)),\n fallback: NO_AGENT_VERSIONS,\n enabled: Boolean(agentId),\n errorMessage: 'Failed to load agent versions',\n });\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":";;;;;;;;;AAsBA,IAAMA,IAAqB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCxBC,IAAwB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6B3BC,IAAwB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkC3BC,IAAwB,CAAG;;;;GAO3BC,IAAiC,CAAG;;;;;;;;;;;;GAcpCC,IAAkC,CAAG;;;;;;;;;;;;GAyDrCC,IAAiB,KACjBC,IAA2B,CAAC,GAuE5BC,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,qBAAqB;CACrB,kBAAkB;CAClB,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;AAEA,SAASC,EACP,GACA,GACqC;CACrC,IAAKC,KAAgBC,GAErB,OAAO;EACL;EACA,QAAQA,GAAQ;EAChB,QAAQA,GAAQ,SAAS;EACzB,YAAYA,GAAQ,aAAa;EACjC,UAAUA,GAAQ;CACpB;AACF;AAUA,SAAg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