@burdenoff/microfe-botmanor 2026.1120.9 → 2026.1120.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/botlit/components/ChannelSetupPanels.d.ts +5 -0
  2. package/dist/botlit/components/ChannelSetupPanels.js +19 -15
  3. package/dist/botlit/components/ChannelSetupPanels.js.map +1 -1
  4. package/dist/botlit/components/ExecutionFeedback.d.ts +5 -0
  5. package/dist/botlit/components/ExecutionFeedback.js +55 -0
  6. package/dist/botlit/components/ExecutionFeedback.js.map +1 -0
  7. package/dist/botlit/components/KnowledgeReviewSchedule.d.ts +7 -0
  8. package/dist/botlit/components/KnowledgeReviewSchedule.js +92 -0
  9. package/dist/botlit/components/KnowledgeReviewSchedule.js.map +1 -0
  10. package/dist/botlit/components/SuggestionsPanel.d.ts +12 -0
  11. package/dist/botlit/components/SuggestionsPanel.js +219 -0
  12. package/dist/botlit/components/SuggestionsPanel.js.map +1 -0
  13. package/dist/botlit/hooks/useAgentTuning.d.ts +87 -0
  14. package/dist/botlit/hooks/useAgentTuning.js +170 -0
  15. package/dist/botlit/hooks/useAgentTuning.js.map +1 -0
  16. package/dist/botlit/hooks/useAiOperations.js +1 -1
  17. package/dist/botlit/hooks/useAiOperations.js.map +1 -1
  18. package/dist/botlit/hooks/useChannelSetup.d.ts +21 -4
  19. package/dist/botlit/hooks/useChannelSetup.js +128 -32
  20. package/dist/botlit/hooks/useChannelSetup.js.map +1 -1
  21. package/dist/botlit/pages/AgentDetailPage.js +75 -70
  22. package/dist/botlit/pages/AgentDetailPage.js.map +1 -1
  23. package/dist/botlit/pages/BotChannelsTab.js +1 -0
  24. package/dist/botlit/pages/BotChannelsTab.js.map +1 -1
  25. package/dist/botlit/pages/ChannelDetailPage.js +381 -380
  26. package/dist/botlit/pages/ChannelDetailPage.js.map +1 -1
  27. package/dist/botlit/pages/ExecutionDetailPage.js +141 -136
  28. package/dist/botlit/pages/ExecutionDetailPage.js.map +1 -1
  29. package/dist/botlit/pages/KnowledgeBaseDetailPage.js +356 -354
  30. package/dist/botlit/pages/KnowledgeBaseDetailPage.js.map +1 -1
  31. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SuggestionsPanel.js","names":["SEVERITY_VARIANT","evidenceExecutionIds","groups","evidence","ids","value","id","changesDraft","suggestion","SuggestionCard","t","useTr","useBotlit","showChange","setShowChange","useState","executionIds","runs","change","Card","CardContent","Badge","formatRelativeTime","topic","Button","open","Link","getPath","index","Check","busy","onAccept","X","onDismiss","SuggestionsPanel","suggestions","useAgentSuggestions","agentId","suggest","suggestState","useSuggestAgentImprovements","accept","acceptState","useAcceptAgentSuggestion","dismiss","dismissState","useDismissAgentSuggestion","pending","setPending","runSuggest","run","refetch","toast","err","confirmAccept","target","result","onDraftChanged","runDismiss","CardHeader","CardTitle","Lightbulb","CardDescription","RefreshCw","error","loading","EmptyState","AlertDialog","AlertDialogContent","AlertDialogHeader","AlertDialogTitle","AlertDialogDescription","AlertDialogFooter","AlertDialogCancel","AlertDialogAction"],"sources":["../../../src/botlit/components/SuggestionsPanel.tsx"],"sourcesContent":["/**\n * Evidence-based tuning suggestions for an agent (BOFF-15360, ABOUT §9).\n *\n * Cards drawn from the agent's own recent runs (policy blocks, poor ratings,\n * model fallbacks, answers that found no knowledge) and from the freshness of\n * the knowledge it uses. Accepting a prompt or model suggestion edits the\n * agent's DRAFT, never what is live: the person publishes the draft when ready.\n * Accepting an overdue-knowledge card marks the knowledge base reviewed;\n * knowledge gap and conflict cards are acknowledgements with a link to act.\n * @module botlit/components\n */\nimport type { FC } from 'react';\nimport { useState } from 'react';\nimport { Link } from 'react-router';\nimport { toast } from 'sonner';\nimport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from '@burdenoff/fe-libs/ui';\nimport { Check, Lightbulb, RefreshCw, X } from 'lucide-react';\nimport { useTr } from '../../shared/hooks/useTr';\nimport {\n type AgentSuggestion,\n useAcceptAgentSuggestion,\n useAgentSuggestions,\n useDismissAgentSuggestion,\n useSuggestAgentImprovements,\n} from '../hooks/useAgentTuning';\nimport { useBotlit } from '../providers/BotlitProvider';\nimport { formatRelativeTime } from '../utils/formatters';\nimport { Badge } from './Badge';\nimport { Button } from './Button';\nimport { Card, CardContent, CardDescription, CardHeader, CardTitle } from './Card';\nimport { EmptyState } from './EmptyState';\n\nconst SEVERITY_VARIANT = {\n CRITICAL: 'destructive',\n WARNING: 'warning',\n INFO: 'secondary',\n} as const;\n\n/** Execution ids the card's evidence links to, by signal. */\nexport function evidenceExecutionIds(evidence: Record<string, unknown>): string[] {\n const groups = evidence.executionIds;\n if (!groups || typeof groups !== 'object') return [];\n const ids = Object.values(groups as Record<string, unknown>).flatMap((value) =>\n Array.isArray(value) ? value.filter((id): id is string => typeof id === 'string') : []\n );\n return [...new Set(ids)];\n}\n\n/** Whether accepting the suggestion changes the agent draft. */\nexport function changesDraft(suggestion: AgentSuggestion): boolean {\n return suggestion.change?.type === 'SYSTEM_PROMPT' || suggestion.change?.type === 'MODEL';\n}\n\nconst SuggestionCard: FC<{\n suggestion: AgentSuggestion;\n busy: boolean;\n onAccept: (suggestion: AgentSuggestion) => void;\n onDismiss: (suggestion: AgentSuggestion) => void;\n}> = ({ suggestion, busy, onAccept, onDismiss }) => {\n const t = useTr();\n const { getPath } = useBotlit();\n const [showChange, setShowChange] = useState(false);\n const executionIds = evidenceExecutionIds(suggestion.evidence);\n const runs = typeof suggestion.evidence.runs === 'number' ? suggestion.evidence.runs : null;\n const change = suggestion.change;\n\n return (\n <Card data-testid=\"agent-suggestion-card\">\n <CardContent className=\"space-y-3 pt-5\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <h3 className=\"font-semibold text-text-primary\">{suggestion.title}</h3>\n <Badge\n variant={\n SEVERITY_VARIANT[suggestion.severity as keyof typeof SEVERITY_VARIANT] ?? 'secondary'\n }\n >\n {suggestion.severity}\n </Badge>\n <Badge variant=\"outline\">\n {suggestion.draftedBy === 'MODEL'\n ? t('botlit.suggestions.draftedByModel', 'Drafted by the agent model')\n : t('botlit.suggestions.draftedByRules', 'Drafted from rules')}\n </Badge>\n <span className=\"text-xs text-text-tertiary\">\n {formatRelativeTime(suggestion.generatedAt)}\n </span>\n </div>\n <p className=\"text-sm text-text-secondary\">{suggestion.recommendation}</p>\n\n {suggestion.topics.length > 0 && (\n <div\n className=\"flex flex-wrap gap-2\"\n aria-label={t('botlit.suggestions.topics', 'Topics')}\n >\n {suggestion.topics.map((topic) => (\n <Badge key={topic} variant=\"secondary\">\n {topic}\n </Badge>\n ))}\n </div>\n )}\n\n {change?.type === 'MODEL' && (\n <p className=\"text-sm text-text-secondary\">\n {t('botlit.suggestions.modelChange', 'Primary model: {{before}} → {{after}}', {\n before: change.before ?? t('botlit.suggestions.none', 'none'),\n after: change.after ?? '',\n })}\n </p>\n )}\n\n {change?.type === 'SYSTEM_PROMPT' && (\n <div>\n <Button variant=\"ghost\" size=\"sm\" onClick={() => setShowChange((open) => !open)}>\n {showChange\n ? t('botlit.suggestions.hidePrompt', 'Hide proposed prompt')\n : t('botlit.suggestions.showPrompt', 'Show proposed prompt')}\n </Button>\n {showChange && (\n <div className=\"mt-2 grid gap-3 md:grid-cols-2\">\n <div>\n <p className=\"mb-1 text-xs font-medium text-text-secondary\">\n {t('botlit.suggestions.currentPrompt', 'Current draft')}\n </p>\n <pre className=\"max-h-64 overflow-auto whitespace-pre-wrap rounded-lg bg-bg-sunken p-3 font-mono text-xs\">\n {change.before ?? ''}\n </pre>\n </div>\n <div>\n <p className=\"mb-1 text-xs font-medium text-text-secondary\">\n {t('botlit.suggestions.proposedPrompt', 'Proposed')}\n </p>\n <pre\n className=\"max-h-64 overflow-auto whitespace-pre-wrap rounded-lg bg-bg-sunken p-3 font-mono text-xs\"\n data-testid=\"agent-suggestion-proposed-prompt\"\n >\n {change.after ?? ''}\n </pre>\n </div>\n </div>\n )}\n </div>\n )}\n\n {(runs !== null || executionIds.length > 0) && (\n <div className=\"flex flex-wrap items-center gap-2 text-xs text-text-secondary\">\n {runs !== null && (\n <span>\n {t('botlit.suggestions.runsAnalyzed', 'From {{runs}} recent runs', { runs })}\n </span>\n )}\n {executionIds.map((id, index) => (\n <Link key={id} to={getPath(`executions/${id}`)} className=\"text-text-link underline\">\n {t('botlit.suggestions.runLink', 'Run {{n}}', { n: index + 1 })}\n </Link>\n ))}\n {change?.type === 'KNOWLEDGE_REVIEW' && change.knowledgeBaseId && (\n <Link\n to={getPath(`knowledge/${change.knowledgeBaseId}`)}\n className=\"text-text-link underline\"\n >\n {t('botlit.suggestions.openKnowledgeBase', 'Open knowledge base')}\n </Link>\n )}\n </div>\n )}\n\n <div className=\"flex gap-2\">\n <Button\n size=\"sm\"\n leftIcon={<Check size={14} />}\n disabled={busy}\n onClick={() => onAccept(suggestion)}\n >\n {changesDraft(suggestion)\n ? t('botlit.suggestions.applyToDraft', 'Apply to draft')\n : change?.type === 'KNOWLEDGE_REVIEW'\n ? t('botlit.suggestions.markReviewed', 'Mark reviewed')\n : t('botlit.suggestions.acknowledge', 'Accept')}\n </Button>\n <Button\n size=\"sm\"\n variant=\"outline\"\n leftIcon={<X size={14} />}\n disabled={busy}\n onClick={() => onDismiss(suggestion)}\n >\n {t('botlit.suggestions.dismiss', 'Dismiss')}\n </Button>\n </div>\n </CardContent>\n </Card>\n );\n};\n\nexport interface SuggestionsPanelProps {\n agentId: string;\n /** Called after an accepted suggestion changed the agent draft, so the page can refresh it. */\n onDraftChanged?: () => void;\n}\n\nexport const SuggestionsPanel: FC<SuggestionsPanelProps> = ({ agentId, onDraftChanged }) => {\n const t = useTr();\n const { data: suggestions, loading, error, refetch } = useAgentSuggestions(agentId);\n const [suggest, suggestState] = useSuggestAgentImprovements();\n const [accept, acceptState] = useAcceptAgentSuggestion();\n const [dismiss, dismissState] = useDismissAgentSuggestion();\n const [pending, setPending] = useState<AgentSuggestion | null>(null);\n const busy = suggestState.loading || acceptState.loading || dismissState.loading;\n\n const runSuggest = async () => {\n try {\n const run = await suggest(agentId);\n await refetch();\n toast.success(\n run.suggestions.length > 0\n ? t('botlit.suggestions.generated', '{{count}} suggestions from {{runs}} runs', {\n count: run.suggestions.length,\n runs: run.runsAnalyzed,\n })\n : t(\n 'botlit.suggestions.noneFound',\n 'No suggestions: {{runs}} runs in the last {{days}} days do not show a pattern to act on.',\n { runs: run.runsAnalyzed, days: run.windowDays }\n )\n );\n } catch (err) {\n toast.error(err instanceof Error ? err.message : String(err));\n }\n };\n\n const confirmAccept = async () => {\n const target = pending;\n setPending(null);\n if (!target) return;\n try {\n const result = await accept(target.id);\n await refetch();\n if (result.draftChanged) {\n onDraftChanged?.();\n toast.success(\n t(\n 'botlit.suggestions.appliedToDraft',\n 'Applied to the draft. Publish the agent to put the change live.'\n )\n );\n } else {\n toast.success(t('botlit.suggestions.accepted', 'Suggestion accepted.'));\n }\n } catch (err) {\n toast.error(err instanceof Error ? err.message : String(err));\n }\n };\n\n const runDismiss = async (target: AgentSuggestion) => {\n try {\n await dismiss(target.id);\n await refetch();\n toast.success(t('botlit.suggestions.dismissed', 'Suggestion dismissed.'));\n } catch (err) {\n toast.error(err instanceof Error ? err.message : String(err));\n }\n };\n\n return (\n <Card data-testid=\"suggestions-panel\">\n <CardHeader className=\"flex flex-row items-start justify-between gap-4\">\n <div>\n <CardTitle className=\"flex items-center gap-2\">\n <Lightbulb size={18} aria-hidden=\"true\" />\n {t('botlit.suggestions.title', 'Suggestions')}\n </CardTitle>\n <CardDescription>\n {t(\n 'botlit.suggestions.description',\n 'Improvements drawn from this agent’s recent runs and the knowledge it uses. Accepting edits the draft; nothing goes live until you publish.'\n )}\n </CardDescription>\n </div>\n <Button\n variant=\"outline\"\n size=\"sm\"\n leftIcon={<RefreshCw size={14} />}\n isLoading={suggestState.loading}\n disabled={busy}\n onClick={() => void runSuggest()}\n >\n {t('botlit.suggestions.generate', 'Suggest improvements')}\n </Button>\n </CardHeader>\n <CardContent className=\"space-y-3\">\n {error ? (\n <p className=\"text-sm text-status-error-text\" role=\"alert\">\n {error.message}\n </p>\n ) : loading && suggestions.length === 0 ? (\n <p className=\"text-sm text-text-secondary\" aria-busy=\"true\">\n {t('botlit.suggestions.loading', 'Loading suggestions…')}\n </p>\n ) : suggestions.length === 0 ? (\n <EmptyState\n icon={<Lightbulb className=\"h-8 w-8\" />}\n title={t('botlit.suggestions.emptyTitle', 'No open suggestions')}\n description={t(\n 'botlit.suggestions.emptyDescription',\n 'Run “Suggest improvements” to analyse the last 14 days of runs.'\n )}\n />\n ) : (\n suggestions.map((suggestion) => (\n <SuggestionCard\n key={suggestion.id}\n suggestion={suggestion}\n busy={busy}\n onAccept={setPending}\n onDismiss={(target) => void runDismiss(target)}\n />\n ))\n )}\n </CardContent>\n\n <AlertDialog open={pending != null} onOpenChange={(open) => !open && setPending(null)}>\n <AlertDialogContent>\n <AlertDialogHeader>\n <AlertDialogTitle>\n {pending && changesDraft(pending)\n ? t('botlit.suggestions.confirmApplyTitle', 'Apply this change to the draft?')\n : t('botlit.suggestions.confirmAcceptTitle', 'Accept this suggestion?')}\n </AlertDialogTitle>\n <AlertDialogDescription>\n {pending && changesDraft(pending)\n ? t(\n 'botlit.suggestions.confirmApplyBody',\n 'The agent draft is updated. Production keeps running the published version until you publish the draft.'\n )\n : pending?.change?.type === 'KNOWLEDGE_REVIEW'\n ? t(\n 'botlit.suggestions.confirmReviewBody',\n 'The knowledge base is marked reviewed today. Do this after updating its outdated documents.'\n )\n : t(\n 'botlit.suggestions.confirmAcknowledgeBody',\n 'Nothing on the agent changes. The suggestion is recorded as accepted.'\n )}\n </AlertDialogDescription>\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel>{t('botlit.suggestions.cancel', 'Cancel')}</AlertDialogCancel>\n <AlertDialogAction onClick={() => void confirmAccept()}>\n {t('botlit.suggestions.confirm', 'Confirm')}\n </A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AwC,iCAAiC,IAC3EA,EAAE,yCAAyC,yBAAyB,EACxD,CAAA,GAClB,kBAAC6D,GAAD,EAAA,UACGxB,KAAWxC,EAAawC,CAAO,IAC5BrC,EACE,uCACA,yGACF,IACAqC,GAAS,QAAQ,SAAS,qBACxBrC,EACE,wCACA,6FACF,IACAA,EACE,6CACA,uEACF,EACgB,CAAA,CACP,EAAA,CAAA,GACnB,kBAAC8D,GAAD,EAAA,UAAA,CACE,kBAACC,GAAD,EAAA,UAAoB/D,EAAE,6BAA6B,QAAQ,EAAqB,CAAA,GAChF,kBAACgE,GAAD;KAAmB,eAAe,KAAKpB,EAAc;KAClD,UAAA5C,EAAE,8BAA8B,SAAS;IACzB,CAAA,CACF,EAAA,CAAA,CACD,EAAA,CAAA;GACT,CAAA;EACT;;AAEV"}
@@ -0,0 +1,87 @@
1
+ import { MutationState, QueryResult } from './internal/workspaceGateway';
2
+ export type AgentSuggestionKind = 'PROMPT_EDIT' | 'KNOWLEDGE_GAP' | 'MODEL_CHANGE' | 'KNOWLEDGE_OVERDUE' | 'KNOWLEDGE_CONFLICT';
3
+ export interface AgentSuggestionChange {
4
+ type: 'SYSTEM_PROMPT' | 'MODEL' | 'KNOWLEDGE_REVIEW';
5
+ before: string | null;
6
+ after: string | null;
7
+ fallbackBefore: string[] | null;
8
+ fallbackAfter: string[] | null;
9
+ knowledgeBaseId: string | null;
10
+ }
11
+ export interface AgentSuggestion {
12
+ id: string;
13
+ agentId: string;
14
+ kind: AgentSuggestionKind;
15
+ status: string;
16
+ title: string;
17
+ recommendation: string;
18
+ severity: string;
19
+ score: number;
20
+ confidence: number;
21
+ change: AgentSuggestionChange | null;
22
+ topics: string[];
23
+ evidence: Record<string, unknown>;
24
+ draftedBy: 'MODEL' | 'RULES';
25
+ modelVersion: string;
26
+ generatedAt: string;
27
+ appliedAt: string | null;
28
+ }
29
+ export interface AgentSuggestionRun {
30
+ suggestions: AgentSuggestion[];
31
+ runsAnalyzed: number;
32
+ windowDays: number;
33
+ suppressed: number;
34
+ modelDrafted: boolean;
35
+ }
36
+ /** The agent's open suggestions. */
37
+ export declare function useAgentSuggestions(agentId: string | undefined): QueryResult<AgentSuggestion[]>;
38
+ export declare function useSuggestAgentImprovements(): readonly [
39
+ (agentId: string) => Promise<AgentSuggestionRun>,
40
+ MutationState<AgentSuggestionRun>
41
+ ];
42
+ export declare function useAcceptAgentSuggestion(): readonly [
43
+ (id: string) => Promise<{
44
+ draftChanged: boolean;
45
+ suggestion: AgentSuggestion;
46
+ }>,
47
+ MutationState<{
48
+ draftChanged: boolean;
49
+ suggestion: AgentSuggestion;
50
+ }>
51
+ ];
52
+ export declare function useDismissAgentSuggestion(): readonly [
53
+ (id: string) => Promise<AgentSuggestion>,
54
+ MutationState<AgentSuggestion>
55
+ ];
56
+ export type ExecutionFeedbackRating = 'GOOD' | 'POOR' | 'CLEAR';
57
+ export interface ExecutionFeedback {
58
+ id: string;
59
+ feedbackRating: number | null;
60
+ feedbackAt: string | null;
61
+ }
62
+ export declare function useRateExecution(): readonly [
63
+ (input: {
64
+ id: string;
65
+ rating: ExecutionFeedbackRating;
66
+ }) => Promise<ExecutionFeedback>,
67
+ MutationState<ExecutionFeedback>
68
+ ];
69
+ export interface KnowledgeReviewSchedule {
70
+ id: string;
71
+ refreshIntervalDays: number | null;
72
+ lastReviewedAt: string | null;
73
+ }
74
+ export declare function useKnowledgeReviewSchedule(knowledgeBaseId: string | undefined): QueryResult<KnowledgeReviewSchedule | undefined>;
75
+ export declare function useSetKnowledgeRefreshInterval(): readonly [
76
+ (input: {
77
+ id: string;
78
+ days: number | null;
79
+ }) => Promise<KnowledgeReviewSchedule>,
80
+ MutationState<KnowledgeReviewSchedule>
81
+ ];
82
+ export declare function useMarkKnowledgeReviewed(): readonly [
83
+ (id: string) => Promise<KnowledgeReviewSchedule>,
84
+ MutationState<KnowledgeReviewSchedule>
85
+ ];
86
+ /** The reviewer rating recorded on a run. */
87
+ export declare function useExecutionFeedback(executionId: string | undefined): QueryResult<ExecutionFeedback | undefined>;
@@ -0,0 +1,170 @@
1
+ import { useWorkspaceId as e, useWorkspaceMutation as t, useWorkspaceQuery as n } from "./internal/workspaceGateway.js";
2
+ import { useMemo as r } from "react";
3
+ import { gql as i } from "@apollo/client";
4
+ // src/botlit/hooks/useAgentTuning.ts
5
+ var a = "\n id\n agentId\n kind\n status\n title\n recommendation\n severity\n score\n confidence\n change {\n type\n before\n after\n fallbackBefore\n fallbackAfter\n knowledgeBaseId\n }\n topics\n evidence\n draftedBy\n modelVersion\n generatedAt\n appliedAt\n", o = i`
6
+ query BotmanorAgentSuggestions($agentId: ID!) {
7
+ agentSuggestions(agentId: $agentId) {
8
+ ${a}
9
+ }
10
+ }
11
+ `, s = i`
12
+ mutation BotmanorSuggestAgentImprovements($agentId: ID!) {
13
+ suggestAgentImprovements(agentId: $agentId) {
14
+ agentId
15
+ runsAnalyzed
16
+ windowDays
17
+ suppressed
18
+ modelDrafted
19
+ suggestions {
20
+ ${a}
21
+ }
22
+ }
23
+ }
24
+ `, c = i`
25
+ mutation BotmanorAcceptAgentSuggestion($id: ID!) {
26
+ acceptAgentSuggestion(id: $id) {
27
+ draftChanged
28
+ suggestion {
29
+ ${a}
30
+ }
31
+ }
32
+ }
33
+ `, l = i`
34
+ mutation BotmanorDismissAgentSuggestion($id: ID!) {
35
+ dismissAgentSuggestion(id: $id) {
36
+ ${a}
37
+ }
38
+ }
39
+ `, u = i`
40
+ mutation BotmanorRateExecution($id: ID!, $rating: ExecutionFeedbackRating!) {
41
+ rateExecution(id: $id, rating: $rating) {
42
+ id
43
+ feedbackRating
44
+ feedbackAt
45
+ }
46
+ }
47
+ `, d = i`
48
+ mutation BotmanorSetKnowledgeBaseRefreshInterval($id: ID!, $days: Int) {
49
+ setKnowledgeBaseRefreshInterval(id: $id, days: $days) {
50
+ id
51
+ refreshIntervalDays
52
+ lastReviewedAt
53
+ }
54
+ }
55
+ `, f = i`
56
+ mutation BotmanorMarkKnowledgeBaseReviewed($id: ID!) {
57
+ markKnowledgeBaseReviewed(id: $id) {
58
+ id
59
+ refreshIntervalDays
60
+ lastReviewedAt
61
+ }
62
+ }
63
+ `, p = i`
64
+ query BotmanorKnowledgeBaseReviewSchedule($id: ID!) {
65
+ getKnowledgeBase(id: $id) {
66
+ id
67
+ refreshIntervalDays
68
+ lastReviewedAt
69
+ }
70
+ }
71
+ `, m = [];
72
+ function h(t) {
73
+ let i = e(), a = r(() => t ? { agentId: t } : void 0, [t]);
74
+ return n({
75
+ document: o,
76
+ variables: a,
77
+ enabled: !!i && !!t,
78
+ errorMessage: "Failed to load suggestions.",
79
+ fallback: m,
80
+ select: (e) => e?.agentSuggestions ?? m
81
+ });
82
+ }
83
+ function g() {
84
+ return t({
85
+ document: s,
86
+ variables: (e) => ({ agentId: e }),
87
+ select: (e) => e?.suggestAgentImprovements,
88
+ errorMessage: "Failed to generate suggestions."
89
+ });
90
+ }
91
+ function _() {
92
+ return t({
93
+ document: c,
94
+ variables: (e) => ({ id: e }),
95
+ select: (e) => e?.acceptAgentSuggestion,
96
+ errorMessage: "Failed to accept the suggestion."
97
+ });
98
+ }
99
+ function v() {
100
+ return t({
101
+ document: l,
102
+ variables: (e) => ({ id: e }),
103
+ select: (e) => e?.dismissAgentSuggestion,
104
+ errorMessage: "Failed to dismiss the suggestion."
105
+ });
106
+ }
107
+ function y() {
108
+ return t({
109
+ document: u,
110
+ variables: (e) => ({
111
+ id: e.id,
112
+ rating: e.rating
113
+ }),
114
+ select: (e) => e?.rateExecution,
115
+ errorMessage: "Failed to save the rating."
116
+ });
117
+ }
118
+ function b(t) {
119
+ let i = e(), a = r(() => t ? { id: t } : void 0, [t]);
120
+ return n({
121
+ document: p,
122
+ variables: a,
123
+ enabled: !!i && !!t,
124
+ errorMessage: "Failed to load the review schedule.",
125
+ fallback: void 0,
126
+ select: (e) => e?.getKnowledgeBase ?? void 0
127
+ });
128
+ }
129
+ function x() {
130
+ return t({
131
+ document: d,
132
+ variables: (e) => ({
133
+ id: e.id,
134
+ days: e.days
135
+ }),
136
+ select: (e) => e?.setKnowledgeBaseRefreshInterval,
137
+ errorMessage: "Failed to save the review interval."
138
+ });
139
+ }
140
+ function S() {
141
+ return t({
142
+ document: f,
143
+ variables: (e) => ({ id: e }),
144
+ select: (e) => e?.markKnowledgeBaseReviewed,
145
+ errorMessage: "Failed to mark the knowledge base reviewed."
146
+ });
147
+ }
148
+ var C = i`
149
+ query BotmanorExecutionFeedback($id: ID!) {
150
+ getExecution(id: $id) {
151
+ id
152
+ feedbackRating
153
+ feedbackAt
154
+ }
155
+ }
156
+ `;
157
+ function w(t) {
158
+ let i = e(), a = r(() => t ? { id: t } : void 0, [t]);
159
+ return n({
160
+ document: C,
161
+ variables: a,
162
+ enabled: !!i && !!t,
163
+ errorMessage: "Failed to load the rating.",
164
+ fallback: void 0,
165
+ select: (e) => e?.getExecution ?? void 0
166
+ });
167
+ }
168
+ export { _ as useAcceptAgentSuggestion, h as useAgentSuggestions, v as useDismissAgentSuggestion, w as useExecutionFeedback, b as useKnowledgeReviewSchedule, S as useMarkKnowledgeReviewed, y as useRateExecution, x as useSetKnowledgeRefreshInterval, g as useSuggestAgentImprovements };
169
+
170
+ //# sourceMappingURL=useAgentTuning.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAgentTuning.js","names":["SUGGESTION_FIELDS","LIST_DOCUMENT","SUGGEST_DOCUMENT","ACCEPT_DOCUMENT","DISMISS_DOCUMENT","RATE_DOCUMENT","REFRESH_INTERVAL_DOCUMENT","MARK_REVIEWED_DOCUMENT","REVIEW_SCHEDULE_DOCUMENT","NO_SUGGESTIONS","useAgentSuggestions","workspaceId","useWorkspaceId","variables","useMemo","agentId","useWorkspaceQuery","data","useSuggestAgentImprovements","useWorkspaceMutation","useAcceptAgentSuggestion","useDismissAgentSuggestion","useRateExecution","input","useKnowledgeReviewSchedule","knowledgeBaseId","useSetKnowledgeRefreshInterval","useMarkKnowledgeReviewed","EXECUTION_FEEDBACK_DOCUMENT","useExecutionFeedback","executionId"],"sources":["../../../src/botlit/hooks/useAgentTuning.ts"],"sourcesContent":["/**\n * Evidence-based agent tuning and knowledge review hooks (BOFF-15360).\n *\n * Wrap the `agent-tuning` fields of wspace-botmanor-svc:\n * - `agentSuggestions` / `suggestAgentImprovements` / `acceptAgentSuggestion`\n * / `dismissAgentSuggestion` — the accept-or-dismiss cards on an agent;\n * - `rateExecution` — a reviewer's good/poor rating of a run's answer;\n * - `setKnowledgeBaseRefreshInterval` / `markKnowledgeBaseReviewed` — a\n * knowledge base's review schedule.\n */\nimport { gql } from '@apollo/client';\nimport { useMemo } from 'react';\n\nimport {\n type MutationState,\n type QueryResult,\n useWorkspaceId,\n useWorkspaceMutation,\n useWorkspaceQuery,\n} from './internal/workspaceGateway';\n\nexport type AgentSuggestionKind =\n 'PROMPT_EDIT' | 'KNOWLEDGE_GAP' | 'MODEL_CHANGE' | 'KNOWLEDGE_OVERDUE' | 'KNOWLEDGE_CONFLICT';\n\nexport interface AgentSuggestionChange {\n type: 'SYSTEM_PROMPT' | 'MODEL' | 'KNOWLEDGE_REVIEW';\n before: string | null;\n after: string | null;\n fallbackBefore: string[] | null;\n fallbackAfter: string[] | null;\n knowledgeBaseId: string | null;\n}\n\nexport interface AgentSuggestion {\n id: string;\n agentId: string;\n kind: AgentSuggestionKind;\n status: string;\n title: string;\n recommendation: string;\n severity: string;\n score: number;\n confidence: number;\n change: AgentSuggestionChange | null;\n topics: string[];\n evidence: Record<string, unknown>;\n draftedBy: 'MODEL' | 'RULES';\n modelVersion: string;\n generatedAt: string;\n appliedAt: string | null;\n}\n\nexport interface AgentSuggestionRun {\n suggestions: AgentSuggestion[];\n runsAnalyzed: number;\n windowDays: number;\n suppressed: number;\n modelDrafted: boolean;\n}\n\nconst SUGGESTION_FIELDS = `\n id\n agentId\n kind\n status\n title\n recommendation\n severity\n score\n confidence\n change {\n type\n before\n after\n fallbackBefore\n fallbackAfter\n knowledgeBaseId\n }\n topics\n evidence\n draftedBy\n modelVersion\n generatedAt\n appliedAt\n`;\n\nconst LIST_DOCUMENT = gql`\n query BotmanorAgentSuggestions($agentId: ID!) {\n agentSuggestions(agentId: $agentId) {\n ${SUGGESTION_FIELDS}\n }\n }\n`;\n\nconst SUGGEST_DOCUMENT = gql`\n mutation BotmanorSuggestAgentImprovements($agentId: ID!) {\n suggestAgentImprovements(agentId: $agentId) {\n agentId\n runsAnalyzed\n windowDays\n suppressed\n modelDrafted\n suggestions {\n ${SUGGESTION_FIELDS}\n }\n }\n }\n`;\n\nconst ACCEPT_DOCUMENT = gql`\n mutation BotmanorAcceptAgentSuggestion($id: ID!) {\n acceptAgentSuggestion(id: $id) {\n draftChanged\n suggestion {\n ${SUGGESTION_FIELDS}\n }\n }\n }\n`;\n\nconst DISMISS_DOCUMENT = gql`\n mutation BotmanorDismissAgentSuggestion($id: ID!) {\n dismissAgentSuggestion(id: $id) {\n ${SUGGESTION_FIELDS}\n }\n }\n`;\n\nconst RATE_DOCUMENT = gql`\n mutation BotmanorRateExecution($id: ID!, $rating: ExecutionFeedbackRating!) {\n rateExecution(id: $id, rating: $rating) {\n id\n feedbackRating\n feedbackAt\n }\n }\n`;\n\nconst REFRESH_INTERVAL_DOCUMENT = gql`\n mutation BotmanorSetKnowledgeBaseRefreshInterval($id: ID!, $days: Int) {\n setKnowledgeBaseRefreshInterval(id: $id, days: $days) {\n id\n refreshIntervalDays\n lastReviewedAt\n }\n }\n`;\n\nconst MARK_REVIEWED_DOCUMENT = gql`\n mutation BotmanorMarkKnowledgeBaseReviewed($id: ID!) {\n markKnowledgeBaseReviewed(id: $id) {\n id\n refreshIntervalDays\n lastReviewedAt\n }\n }\n`;\n\nconst REVIEW_SCHEDULE_DOCUMENT = gql`\n query BotmanorKnowledgeBaseReviewSchedule($id: ID!) {\n getKnowledgeBase(id: $id) {\n id\n refreshIntervalDays\n lastReviewedAt\n }\n }\n`;\n\nconst NO_SUGGESTIONS: AgentSuggestion[] = [];\n\n/** The agent's open suggestions. */\nexport function useAgentSuggestions(agentId: string | undefined): QueryResult<AgentSuggestion[]> {\n const workspaceId = useWorkspaceId();\n const variables = useMemo(() => (agentId ? { agentId } : undefined), [agentId]);\n return useWorkspaceQuery<{ agentSuggestions?: AgentSuggestion[] }, AgentSuggestion[]>({\n document: LIST_DOCUMENT,\n variables,\n enabled: !!workspaceId && !!agentId,\n errorMessage: 'Failed to load suggestions.',\n fallback: NO_SUGGESTIONS,\n select: (data) => data?.agentSuggestions ?? NO_SUGGESTIONS,\n });\n}\n\nexport function useSuggestAgentImprovements(): readonly [\n (agentId: string) => Promise<AgentSuggestionRun>,\n MutationState<AgentSuggestionRun>,\n] {\n return useWorkspaceMutation<\n { suggestAgentImprovements?: AgentSuggestionRun },\n string,\n AgentSuggestionRun\n >({\n document: SUGGEST_DOCUMENT,\n variables: (agentId) => ({ agentId }),\n select: (data) => data?.suggestAgentImprovements,\n errorMessage: 'Failed to generate suggestions.',\n });\n}\n\nexport function useAcceptAgentSuggestion(): readonly [\n (id: string) => Promise<{ draftChanged: boolean; suggestion: AgentSuggestion }>,\n MutationState<{ draftChanged: boolean; suggestion: AgentSuggestion }>,\n] {\n return useWorkspaceMutation<\n { acceptAgentSuggestion?: { draftChanged: boolean; suggestion: AgentSuggestion } },\n string,\n { draftChanged: boolean; suggestion: AgentSuggestion }\n >({\n document: ACCEPT_DOCUMENT,\n variables: (id) => ({ id }),\n select: (data) => data?.acceptAgentSuggestion,\n errorMessage: 'Failed to accept the suggestion.',\n });\n}\n\nexport function useDismissAgentSuggestion(): readonly [\n (id: string) => Promise<AgentSuggestion>,\n MutationState<AgentSuggestion>,\n] {\n return useWorkspaceMutation<\n { dismissAgentSuggestion?: AgentSuggestion },\n string,\n AgentSuggestion\n >({\n document: DISMISS_DOCUMENT,\n variables: (id) => ({ id }),\n select: (data) => data?.dismissAgentSuggestion,\n errorMessage: 'Failed to dismiss the suggestion.',\n });\n}\n\nexport type ExecutionFeedbackRating = 'GOOD' | 'POOR' | 'CLEAR';\n\nexport interface ExecutionFeedback {\n id: string;\n feedbackRating: number | null;\n feedbackAt: string | null;\n}\n\nexport function useRateExecution(): readonly [\n (input: { id: string; rating: ExecutionFeedbackRating }) => Promise<ExecutionFeedback>,\n MutationState<ExecutionFeedback>,\n] {\n return useWorkspaceMutation<\n { rateExecution?: ExecutionFeedback },\n { id: string; rating: ExecutionFeedbackRating },\n ExecutionFeedback\n >({\n document: RATE_DOCUMENT,\n variables: (input) => ({ id: input.id, rating: input.rating }),\n select: (data) => data?.rateExecution,\n errorMessage: 'Failed to save the rating.',\n });\n}\n\nexport interface KnowledgeReviewSchedule {\n id: string;\n refreshIntervalDays: number | null;\n lastReviewedAt: string | null;\n}\n\nexport function useKnowledgeReviewSchedule(\n knowledgeBaseId: string | undefined\n): QueryResult<KnowledgeReviewSchedule | undefined> {\n const workspaceId = useWorkspaceId();\n const variables = useMemo(\n () => (knowledgeBaseId ? { id: knowledgeBaseId } : undefined),\n [knowledgeBaseId]\n );\n return useWorkspaceQuery<\n { getKnowledgeBase?: KnowledgeReviewSchedule | null },\n KnowledgeReviewSchedule | undefined\n >({\n document: REVIEW_SCHEDULE_DOCUMENT,\n variables,\n enabled: !!workspaceId && !!knowledgeBaseId,\n errorMessage: 'Failed to load the review schedule.',\n fallback: undefined,\n select: (data) => data?.getKnowledgeBase ?? undefined,\n });\n}\n\nexport function useSetKnowledgeRefreshInterval(): readonly [\n (input: { id: string; days: number | null }) => Promise<KnowledgeReviewSchedule>,\n MutationState<KnowledgeReviewSchedule>,\n] {\n return useWorkspaceMutation<\n { setKnowledgeBaseRefreshInterval?: KnowledgeReviewSchedule },\n { id: string; days: number | null },\n KnowledgeReviewSchedule\n >({\n document: REFRESH_INTERVAL_DOCUMENT,\n variables: (input) => ({ id: input.id, days: input.days }),\n select: (data) => data?.setKnowledgeBaseRefreshInterval,\n errorMessage: 'Failed to save the review interval.',\n });\n}\n\nexport function useMarkKnowledgeReviewed(): readonly [\n (id: string) => Promise<KnowledgeReviewSchedule>,\n MutationState<KnowledgeReviewSchedule>,\n] {\n return useWorkspaceMutation<\n { markKnowledgeBaseReviewed?: KnowledgeReviewSchedule },\n string,\n KnowledgeReviewSchedule\n >({\n document: MARK_REVIEWED_DOCUMENT,\n variables: (id) => ({ id }),\n select: (data) => data?.markKnowledgeBaseReviewed,\n errorMessage: 'Failed to mark the knowledge base reviewed.',\n });\n}\n\nconst EXECUTION_FEEDBACK_DOCUMENT = gql`\n query BotmanorExecutionFeedback($id: ID!) {\n getExecution(id: $id) {\n id\n feedbackRating\n feedbackAt\n }\n }\n`;\n\n/** The reviewer rating recorded on a run. */\nexport function useExecutionFeedback(\n executionId: string | undefined\n): QueryResult<ExecutionFeedback | undefined> {\n const workspaceId = useWorkspaceId();\n const variables = useMemo(() => (executionId ? { id: executionId } : undefined), [executionId]);\n return useWorkspaceQuery<\n { getExecution?: ExecutionFeedback | null },\n ExecutionFeedback | undefined\n >({\n document: EXECUTION_FEEDBACK_DOCUMENT,\n variables,\n enabled: !!workspaceId && !!executionId,\n errorMessage: 'Failed to load the rating.',\n fallback: undefined,\n select: (data) => data?.getExecution ?? undefined,\n });\n}\n"],"mappings":";;;;AA4DA,IAAMA,IAAoB,oSA0BpBC,IAAgB,CAAG;;;QAGjBD,EAAkB;;;GAKpBE,IAAmB,CAAG;;;;;;;;;UASlBF,EAAkB;;;;GAMtBG,IAAkB,CAAG;;;;;UAKjBH,EAAkB;;;;GAMtBI,IAAmB,CAAG;;;QAGpBJ,EAAkB;;;GAKpBK,IAAgB,CAAG;;;;;;;;GAUnBC,IAA4B,CAAG;;;;;;;;GAU/BC,IAAyB,CAAG;;;;;;;;GAU5BC,IAA2B,CAAG;;;;;;;;GAU9BC,IAAoC,CAAC;AAG3C,SAAgBC,EAAoB,GAA6D;CAC/F,IAAMC,IAAcC,EAAe,GAC7BC,IAAYC,QAAeC,IAAU,EAAE,WAAQ,IAAI,KAAA,GAAY,CAACA,CAAO,CAAC;CAC9E,OAAOC,EAA+E;EACpF,UAAUf;EACV;EAC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EACzB,SAAS,MAASU,GAAM;EACxB,cAAc;CAChB,CAAC;AACH;AAEA,IAAMW,IAA8B,CAAG;;;;;;;;;AAWvC,SAAgBC,EACd,GAC4C;CAC5C,IAAMlB,IAAcC,EAAe,GAC7BC,IAAYC,QAAegB,IAAc,EAAE,IAAIA,EAAY,IAAI,KAAA,GAAY,CAACA,CAAW,CAAC;CAC9F,OAAOd,EAGL;EACA,UAAUY;EACV;EACA,SAAS,CAAC,CAACjB,KAAe,CAAC,CAACmB;EAC5B,cAAc;EACd,UAAU,KAAA;EACV,SAAS,MAASb,GAAM,gBAAgB,KAAA;CAC1C,CAAC;AACH"}
@@ -24,7 +24,7 @@ function p(e) {
24
24
  enabled: !!t,
25
25
  errorMessage: "Failed to load AI operations findings.",
26
26
  fallback: d,
27
- select: (e) => (e?.aiPredictions.items ?? []).map((e) => ({
27
+ select: (e) => (e?.aiPredictions.items ?? []).filter((e) => !e.predictionType.startsWith("agent_tuning.")).map((e) => ({
28
28
  id: e.id,
29
29
  predictionType: e.predictionType,
30
30
  subjectType: e.subjectType ?? null,
@@ -1 +1 @@
1
- {"version":3,"file":"useAiOperations.js","names":["LIST_LIMIT","NO_PREDICTIONS","NO_RUNS","useAiPredictions","workspaceId","useWorkspaceId","filter","variables","useMemo","gqlFilter","subjectType","subjectId","status","useWorkspaceQuery","ListAiPredictionsDocument","data","item","useSetAiPredictionStatus","useWorkspaceMutation","SetAiPredictionStatusDocument","input","row","useSupervisorConfig","GetSupervisorConfigDocument","config","useConfigureSupervisor","ConfigureSupervisorDocument","useRunSupervisorNow","RunSupervisorNowDocument","result","run","useSupervisorRuns","ListSupervisorRunsDocument","predictionSeverity","severity","record","\"severity\"","predictionSubjectName","name","\"subjectName\""],"sources":["../../../src/botlit/hooks/useAiOperations.ts"],"sourcesContent":["/**\n * AI Operations hooks (BOFF-3839)\n * @module botlit/hooks\n *\n * Backed by the supervisor surface on wspace-botmanor-svc: the AiPrediction\n * feed (findings as decision cards), the supervisor configuration, run-now\n * and the run history. Read conventions come from `useExecutions`\n * (network-only, explicit error state, caller-driven refetch).\n */\n\nimport { useMemo } from 'react';\nimport {\n ConfigureSupervisorDocument,\n GetSupervisorConfigDocument,\n ListAiPredictionsDocument,\n ListSupervisorRunsDocument,\n RunSupervisorNowDocument,\n SetAiPredictionStatusDocument,\n type ConfigureSupervisorMutation,\n type ConfigureSupervisorMutationVariables,\n type GetSupervisorConfigQuery,\n type ListAiPredictionsQuery,\n type ListSupervisorRunsQuery,\n type RunSupervisorNowMutation,\n type SetAiPredictionStatusMutation,\n type SetAiPredictionStatusMutationVariables,\n} from '../../generated/wspace-operations';\nimport type {\n AiPredictionFilterInput,\n AiPredictionStatus,\n ConfigureSupervisorInput,\n} from '../../generated/wspace-types';\nimport {\n useWorkspaceId,\n useWorkspaceMutation,\n useWorkspaceQuery,\n type QueryResult,\n} from './internal/workspaceGateway';\n\nconst LIST_LIMIT = 50;\n\nexport interface AiPredictionRecord {\n id: string;\n predictionType: string;\n subjectType: string | null;\n subjectId: string | null;\n score: number;\n confidence: number;\n recommendation: string;\n status: string;\n features: Record<string, unknown> | null;\n /** Supervisor metadata: fingerprint, severity, subjectName, runId. */\n metadata: Record<string, unknown> | null;\n generatedAt: string;\n}\n\nexport interface AiPredictionsFilter {\n subjectType?: string;\n subjectId?: string;\n status?: string;\n}\n\nexport interface SupervisorConfigRecord {\n enabled: boolean;\n cron: string;\n timezone: string;\n lastRunAt: string | null;\n updatedAt: string;\n}\n\nexport interface SupervisorRunRecord {\n id: string;\n trigger: string;\n status: string;\n findings: number;\n notified: number;\n error: string | null;\n startedAt: string;\n completedAt: string | null;\n}\n\nconst NO_PREDICTIONS: AiPredictionRecord[] = [];\nconst NO_RUNS: SupervisorRunRecord[] = [];\n\nexport const aiOperationsKeys = {\n all: ['ai-operations'] as const,\n predictions: (filter?: AiPredictionsFilter) =>\n [...aiOperationsKeys.all, 'predictions', filter] as const,\n config: () => [...aiOperationsKeys.all, 'config'] as const,\n runs: () => [...aiOperationsKeys.all, 'runs'] as const,\n};\n\n/** Decision-card feed, optionally narrowed to one subject (agent/app/KB). */\nexport function useAiPredictions(filter?: AiPredictionsFilter): QueryResult<AiPredictionRecord[]> {\n const workspaceId = useWorkspaceId();\n const { subjectType, subjectId, status } = filter ?? {};\n\n const variables = useMemo(() => {\n const gqlFilter: AiPredictionFilterInput = { sourceProduct: 'botmanor' };\n if (subjectType) gqlFilter.subjectType = subjectType;\n if (subjectId) gqlFilter.subjectId = subjectId;\n if (status) gqlFilter.status = status as AiPredictionStatus;\n return { filter: gqlFilter, pagination: { limit: LIST_LIMIT, offset: 0 } };\n }, [subjectType, subjectId, status]);\n\n return useWorkspaceQuery<ListAiPredictionsQuery, AiPredictionRecord[]>({\n document: ListAiPredictionsDocument,\n variables,\n enabled: !!workspaceId,\n errorMessage: 'Failed to load AI operations findings.',\n fallback: NO_PREDICTIONS,\n select: (data) =>\n (data?.aiPredictions.items ?? []).map((item) => ({\n id: item.id,\n predictionType: item.predictionType,\n subjectType: item.subjectType ?? null,\n subjectId: item.subjectId ?? null,\n score: item.score,\n confidence: item.confidence,\n recommendation: item.recommendation,\n status: item.status,\n features: (item.features ?? null) as Record<string, unknown> | null,\n metadata: (item.metadata ?? null) as Record<string, unknown> | null,\n generatedAt: item.generatedAt,\n })),\n });\n}\n\n/** Accept / dismiss one finding. Callers refetch the feed afterwards. */\nexport function useSetAiPredictionStatus(): readonly [\n (input: { id: string; status: AiPredictionStatus }) => Promise<{ id: string; status: string }>,\n { data: { id: string; status: string } | undefined; loading: boolean; error: Error | undefined },\n] {\n return useWorkspaceMutation<\n SetAiPredictionStatusMutation,\n { id: string; status: AiPredictionStatus },\n { id: string; status: string }\n >({\n document: SetAiPredictionStatusDocument,\n variables: (input) =>\n ({ id: input.id, status: input.status }) as SetAiPredictionStatusMutationVariables,\n select: (data) => {\n const row = data?.setAiPredictionStatus;\n return row ? { id: row.id, status: row.status } : undefined;\n },\n errorMessage: 'Failed to update the finding.',\n });\n}\n\nexport function useSupervisorConfig(): QueryResult<SupervisorConfigRecord | undefined> {\n const workspaceId = useWorkspaceId();\n return useWorkspaceQuery<GetSupervisorConfigQuery, SupervisorConfigRecord | undefined>({\n document: GetSupervisorConfigDocument,\n variables: {},\n enabled: !!workspaceId,\n errorMessage: 'Failed to load the supervisor configuration.',\n fallback: undefined,\n select: (data) => {\n const config = data?.supervisorConfig;\n if (!config) return undefined;\n return {\n enabled: config.enabled,\n cron: config.cron,\n timezone: config.timezone,\n lastRunAt: config.lastRunAt ?? null,\n updatedAt: config.updatedAt,\n };\n },\n });\n}\n\nexport function useConfigureSupervisor(): readonly [\n (input: {\n enabled?: boolean;\n cron?: string;\n timezone?: string;\n }) => Promise<SupervisorConfigRecord>,\n { data: SupervisorConfigRecord | undefined; loading: boolean; error: Error | undefined },\n] {\n return useWorkspaceMutation<\n ConfigureSupervisorMutation,\n ConfigureSupervisorInput,\n SupervisorConfigRecord\n >({\n document: ConfigureSupervisorDocument,\n variables: (input) => ({ input }) as ConfigureSupervisorMutationVariables,\n select: (data) => {\n const config = data?.configureSupervisor;\n if (!config) return undefined;\n return {\n enabled: config.enabled,\n cron: config.cron,\n timezone: config.timezone,\n lastRunAt: config.lastRunAt ?? null,\n updatedAt: config.updatedAt,\n };\n },\n errorMessage: 'Failed to save the supervisor configuration.',\n });\n}\n\nexport interface RunSupervisorNowResult {\n run: SupervisorRunRecord | null;\n findings: number;\n}\n\n/** Manual fleet review (the scheduled path is the FluidGrids cron tick). */\nexport function useRunSupervisorNow(): readonly [\n () => Promise<RunSupervisorNowResult>,\n { data: RunSupervisorNowResult | undefined; loading: boolean; error: Error | undefined },\n] {\n return useWorkspaceMutation<RunSupervisorNowMutation, void, RunSupervisorNowResult>({\n document: RunSupervisorNowDocument,\n variables: () => ({}),\n select: (data) => {\n const result = data?.runSupervisorNow;\n if (!result) return undefined;\n const run = result.run;\n return {\n findings: result.findings,\n run: run\n ? {\n id: run.id,\n trigger: run.trigger,\n status: run.status,\n findings: run.findings,\n notified: run.notified,\n error: run.error ?? null,\n startedAt: run.startedAt,\n completedAt: run.completedAt ?? null,\n }\n : null,\n };\n },\n errorMessage: 'Failed to run the supervisor review.',\n });\n}\n\nexport function useSupervisorRuns(): QueryResult<SupervisorRunRecord[]> {\n const workspaceId = useWorkspaceId();\n return useWorkspaceQuery<ListSupervisorRunsQuery, SupervisorRunRecord[]>({\n document: ListSupervisorRunsDocument,\n variables: { pagination: { limit: 20, offset: 0 } },\n enabled: !!workspaceId,\n errorMessage: 'Failed to load the supervisor run history.',\n fallback: NO_RUNS,\n select: (data) =>\n (data?.supervisorRuns.items ?? []).map((run) => ({\n id: run.id,\n trigger: run.trigger,\n status: run.status,\n findings: run.findings,\n notified: run.notified,\n error: run.error ?? null,\n startedAt: run.startedAt,\n completedAt: run.completedAt ?? null,\n })),\n });\n}\n\n/** Severity from supervisor metadata (WARNING/CRITICAL/INFO), defaulting to INFO. */\nexport function predictionSeverity(record: AiPredictionRecord): string {\n const severity = record.metadata?.['severity'];\n return typeof severity === 'string' ? severity : 'INFO';\n}\n\n/** Human name the supervisor recorded for the subject, when present. */\nexport function predictionSubjectName(record: AiPredictionRecord): string {\n const name = record.metadata?.['subjectName'];\n if (typeof name === 'string' && name.length > 0) return name;\n return record.subjectId ?? record.predictionType;\n}\n"],"mappings":";;;;AAuCA,IAAMA,IAAa,IA0CbC,IAAuC,CAAC,GACxCC,IAAiC,CAAC;AAWxC,SAAgBC,EAAiB,GAAiE;CAChG,IAAMC,IAAcC,EAAe,GAC7B,EAAE,gBAAa,cAAW,cAAWC,KAAU,CAAC,GAEhDC,IAAYC,QAAc;EAC9B,IAAMC,IAAqC,EAAE,eAAe,WAAW;EAIvE,OAHIC,MAAa,EAAU,cAAcA,IACrCC,MAAW,EAAU,YAAYA,IACjCC,MAAQ,EAAU,SAASA,IACxB;GAAE,QAAQH;GAAW,YAAY;IAAE,OAAOT;IAAY,QAAQ;GAAE;EAAE;CAC3E,GAAG;EAACU;EAAaC;EAAWC;CA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3,"file":"useAiOperations.js","names":["LIST_LIMIT","NO_PREDICTIONS","NO_RUNS","useAiPredictions","workspaceId","useWorkspaceId","filter","variables","useMemo","gqlFilter","subjectType","subjectId","status","useWorkspaceQuery","ListAiPredictionsDocument","data","item","useSetAiPredictionStatus","useWorkspaceMutation","SetAiPredictionStatusDocument","input","row","useSupervisorConfig","GetSupervisorConfigDocument","config","useConfigureSupervisor","ConfigureSupervisorDocument","useRunSupervisorNow","RunSupervisorNowDocument","result","run","useSupervisorRuns","ListSupervisorRunsDocument","predictionSeverity","severity","record","\"severity\"","predictionSubjectName","name","\"subjectName\""],"sources":["../../../src/botlit/hooks/useAiOperations.ts"],"sourcesContent":["/**\n * AI Operations hooks (BOFF-3839)\n * @module botlit/hooks\n *\n * Backed by the supervisor surface on wspace-botmanor-svc: the AiPrediction\n * feed (findings as decision cards), the supervisor configuration, run-now\n * and the run history. Read conventions come from `useExecutions`\n * (network-only, explicit error state, caller-driven refetch).\n */\n\nimport { useMemo } from 'react';\nimport {\n ConfigureSupervisorDocument,\n GetSupervisorConfigDocument,\n ListAiPredictionsDocument,\n ListSupervisorRunsDocument,\n RunSupervisorNowDocument,\n SetAiPredictionStatusDocument,\n type ConfigureSupervisorMutation,\n type ConfigureSupervisorMutationVariables,\n type GetSupervisorConfigQuery,\n type ListAiPredictionsQuery,\n type ListSupervisorRunsQuery,\n type RunSupervisorNowMutation,\n type SetAiPredictionStatusMutation,\n type SetAiPredictionStatusMutationVariables,\n} from '../../generated/wspace-operations';\nimport type {\n AiPredictionFilterInput,\n AiPredictionStatus,\n ConfigureSupervisorInput,\n} from '../../generated/wspace-types';\nimport {\n useWorkspaceId,\n useWorkspaceMutation,\n useWorkspaceQuery,\n type QueryResult,\n} from './internal/workspaceGateway';\n\nconst LIST_LIMIT = 50;\n\nexport interface AiPredictionRecord {\n id: string;\n predictionType: string;\n subjectType: string | null;\n subjectId: string | null;\n score: number;\n confidence: number;\n recommendation: string;\n status: string;\n features: Record<string, unknown> | null;\n /** Supervisor metadata: fingerprint, severity, subjectName, runId. */\n metadata: Record<string, unknown> | null;\n generatedAt: string;\n}\n\nexport interface AiPredictionsFilter {\n subjectType?: string;\n subjectId?: string;\n status?: string;\n}\n\nexport interface SupervisorConfigRecord {\n enabled: boolean;\n cron: string;\n timezone: string;\n lastRunAt: string | null;\n updatedAt: string;\n}\n\nexport interface SupervisorRunRecord {\n id: string;\n trigger: string;\n status: string;\n findings: number;\n notified: number;\n error: string | null;\n startedAt: string;\n completedAt: string | null;\n}\n\nconst NO_PREDICTIONS: AiPredictionRecord[] = [];\nconst NO_RUNS: SupervisorRunRecord[] = [];\n\nexport const aiOperationsKeys = {\n all: ['ai-operations'] as const,\n predictions: (filter?: AiPredictionsFilter) =>\n [...aiOperationsKeys.all, 'predictions', filter] as const,\n config: () => [...aiOperationsKeys.all, 'config'] as const,\n runs: () => [...aiOperationsKeys.all, 'runs'] as const,\n};\n\n/** Decision-card feed, optionally narrowed to one subject (agent/app/KB). */\nexport function useAiPredictions(filter?: AiPredictionsFilter): QueryResult<AiPredictionRecord[]> {\n const workspaceId = useWorkspaceId();\n const { subjectType, subjectId, status } = filter ?? {};\n\n const variables = useMemo(() => {\n const gqlFilter: AiPredictionFilterInput = { sourceProduct: 'botmanor' };\n if (subjectType) gqlFilter.subjectType = subjectType;\n if (subjectId) gqlFilter.subjectId = subjectId;\n if (status) gqlFilter.status = status as AiPredictionStatus;\n return { filter: gqlFilter, pagination: { limit: LIST_LIMIT, offset: 0 } };\n }, [subjectType, subjectId, status]);\n\n return useWorkspaceQuery<ListAiPredictionsQuery, AiPredictionRecord[]>({\n document: ListAiPredictionsDocument,\n variables,\n enabled: !!workspaceId,\n errorMessage: 'Failed to load AI operations findings.',\n fallback: NO_PREDICTIONS,\n select: (data) =>\n (data?.aiPredictions.items ?? [])\n // BOFF-15360: agent tuning suggestions have their own panel and accept\n // path (acceptAgentSuggestion); they are not supervisor findings.\n .filter((item) => !item.predictionType.startsWith('agent_tuning.'))\n .map((item) => ({\n id: item.id,\n predictionType: item.predictionType,\n subjectType: item.subjectType ?? null,\n subjectId: item.subjectId ?? null,\n score: item.score,\n confidence: item.confidence,\n recommendation: item.recommendation,\n status: item.status,\n features: (item.features ?? null) as Record<string, unknown> | null,\n metadata: (item.metadata ?? null) as Record<string, unknown> | null,\n generatedAt: item.generatedAt,\n })),\n });\n}\n\n/** Accept / dismiss one finding. Callers refetch the feed afterwards. */\nexport function useSetAiPredictionStatus(): readonly [\n (input: { id: string; status: AiPredictionStatus }) => Promise<{ id: string; status: string }>,\n { data: { id: string; status: string } | undefined; loading: boolean; error: Error | undefined },\n] {\n return useWorkspaceMutation<\n SetAiPredictionStatusMutation,\n { id: string; status: AiPredictionStatus },\n { id: string; status: string }\n >({\n document: SetAiPredictionStatusDocument,\n variables: (input) =>\n ({ id: input.id, status: input.status }) as SetAiPredictionStatusMutationVariables,\n select: (data) => {\n const row = data?.setAiPredictionStatus;\n return row ? { id: row.id, status: row.status } : undefined;\n },\n errorMessage: 'Failed to update the finding.',\n });\n}\n\nexport function useSupervisorConfig(): QueryResult<SupervisorConfigRecord | undefined> {\n const workspaceId = useWorkspaceId();\n return useWorkspaceQuery<GetSupervisorConfigQuery, SupervisorConfigRecord | undefined>({\n document: GetSupervisorConfigDocument,\n variables: {},\n enabled: !!workspaceId,\n errorMessage: 'Failed to load the supervisor configuration.',\n fallback: undefined,\n select: (data) => {\n const config = data?.supervisorConfig;\n if (!config) return undefined;\n return {\n enabled: config.enabled,\n cron: config.cron,\n timezone: config.timezone,\n lastRunAt: config.lastRunAt ?? null,\n updatedAt: config.updatedAt,\n };\n },\n });\n}\n\nexport function useConfigureSupervisor(): readonly [\n (input: {\n enabled?: boolean;\n cron?: string;\n timezone?: string;\n }) => Promise<SupervisorConfigRecord>,\n { data: SupervisorConfigRecord | undefined; loading: boolean; error: Error | undefined },\n] {\n return useWorkspaceMutation<\n ConfigureSupervisorMutation,\n ConfigureSupervisorInput,\n SupervisorConfigRecord\n >({\n document: ConfigureSupervisorDocument,\n variables: (input) => ({ input }) as ConfigureSupervisorMutationVariables,\n select: (data) => {\n const config = data?.configureSupervisor;\n if (!config) return undefined;\n return {\n enabled: config.enabled,\n cron: config.cron,\n timezone: config.timezone,\n lastRunAt: config.lastRunAt ?? null,\n updatedAt: config.updatedAt,\n };\n },\n errorMessage: 'Failed to save the supervisor configuration.',\n });\n}\n\nexport interface RunSupervisorNowResult {\n run: SupervisorRunRecord | null;\n findings: number;\n}\n\n/** Manual fleet review (the scheduled path is the FluidGrids cron tick). */\nexport function useRunSupervisorNow(): readonly [\n () => Promise<RunSupervisorNowResult>,\n { data: RunSupervisorNowResult | undefined; loading: boolean; error: Error | undefined },\n] {\n return useWorkspaceMutation<RunSupervisorNowMutation, void, RunSupervisorNowResult>({\n document: RunSupervisorNowDocument,\n variables: () => ({}),\n select: (data) => {\n const result = data?.runSupervisorNow;\n if (!result) return undefined;\n const run = result.run;\n return {\n findings: result.findings,\n run: run\n ? {\n id: run.id,\n trigger: run.trigger,\n status: run.status,\n findings: run.findings,\n notified: run.notified,\n error: run.error ?? null,\n startedAt: run.startedAt,\n completedAt: run.completedAt ?? null,\n }\n : null,\n };\n },\n errorMessage: 'Failed to run the supervisor review.',\n });\n}\n\nexport function useSupervisorRuns(): QueryResult<SupervisorRunRecord[]> {\n const workspaceId = useWorkspaceId();\n return useWorkspaceQuery<ListSupervisorRunsQuery, SupervisorRunRecord[]>({\n document: ListSupervisorRunsDocument,\n variables: { pagination: { limit: 20, offset: 0 } },\n enabled: !!workspaceId,\n errorMessage: 'Failed to load the supervisor run history.',\n fallback: NO_RUNS,\n select: (data) =>\n (data?.supervisorRuns.items ?? []).map((run) => ({\n id: run.id,\n trigger: run.trigger,\n status: run.status,\n findings: run.findings,\n notified: run.notified,\n error: run.error ?? null,\n startedAt: run.startedAt,\n completedAt: run.completedAt ?? null,\n })),\n });\n}\n\n/** Severity from supervisor metadata (WARNING/CRITICAL/INFO), defaulting to INFO. */\nexport function predictionSeverity(record: AiPredictionRecord): string {\n const severity = record.metadata?.['severity'];\n return typeof severity === 'string' ? severity : 'INFO';\n}\n\n/** Human name the supervisor recorded for the subject, when present. */\nexport function predictionSubjectName(record: AiPredictionRecord): string {\n const name = record.metadata?.['subjectName'];\n if (typeof name === 'string' && name.length > 0) return name;\n return record.subjectId ?? record.predictionType;\n}\n"],"mappings":";;;;AAuCA,IAAMA,IAAa,IA0CbC,IAAuC,CAAC,GACxCC,IAAiC,CAAC;AAWxC,SAAgBC,EAAiB,GAAiE;CAChG,IAAMC,IAAcC,EAAe,GAC7B,EAAE,gBAAa,cAAW,cAAWC,KAAU,CAAC,GAEhDC,IAAYC,QAAc;EAC9B,IAAMC,IAAqC,EAAE,eAAe,WAAW;EAIvE,OAHIC,MAAa,EAAU,cAAcA,IACrCC,MAAW,EAAU,YAAYA,IACjCC,MAAQ,EAAU,SAASA,IACxB;GAAE,QAAQH;GAAW,YAAY;IAAE,OAAOT;IAAY,QAAQ;GAAE;EAAE;CAC3E,GAAG;EAACU;EAAaC;EAAWC;CAAM,CAAC;CAEnC,OAAOC,EAAgE;EACrE,UAAUC;EACV;EACA,SAAS,CAAC,CAACV;EACX,cAAc;EACd,UAAUH;EACV,SAAS,OACNc,GAAM,cAAc,SAAS,CAAC,EAAA,CAG5B,QAAQ,MAAS,CAACC,EAAK,eAAe,WAAW,eAAe,CAAC,CAAC,CAClE,KAAK,OAAU;GACd,IAAIA,EAAK;GACT,gBAAgBA,EAAK;GACrB,aAAaA,EAAK,eAAe;GACjC,WAAWA,EAAK,aAAa;GAC7B,OAAOA,EAAK;GACZ,YAAYA,EAAK;GACjB,gBAAgBA,EAAK;GACrB,QAAQA,EAAK;GACb,UAAWA,EAAK,YAAY;GAC5B,UAAWA,EAAK,YAAY;GAC5B,aAAaA,EAAK;EACpB,EAAE;CACR,CAAC;AACH;AAGA,SAAgBC,IAGd;CACA,OAAOC,EAIL;EACA,UAAUC;EACV,YAAY,OACT;GAAE,IAAIC,EAAM;GAAI,Q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,SAAgBC,IAAwD;CACtE,IAAM3B,IAAcC,EAAe;CACnC,OAAOQ,EAAkE;EACvE,UAAUmB;EACV,WAAW,EAAE,YAAY;GAAE,OAAO;GAAI,QAAQ;EAAE,EAAE;EAClD,SAAS,CAAC,CAAC5B;EACX,cAAc;EACd,UAAUF;EACV,SAAS,OACNa,GAAM,eAAe,SAAS,CAAC,EAAA,CAAG,KAAK,OAAS;GAC/C,IAAIe,EAAI;GACR,SAASA,EAAI;GACb,QAAQA,EAAI;GACZ,UAAUA,EAAI;GACd,UAAUA,EAAI;GACd,OAAOA,EAAI,SAAS;GACpB,WAAWA,EAAI;GACf,aAAaA,EAAI,eAAe;EAClC,EAAE;CACN,CAAC;AACH;AAGA,SAAgBG,EAAmB,GAAoC;CACrE,IAAMC,IAAWC,EAAO,UAAWC;CACnC,OAAO,OAAOF,KAAa,WAAWA,IAAW;AACnD;AAGA,SAAgBG,EAAsB,GAAoC;CACxE,IAAMC,IAAOH,EAAO,UAAWI;CAE/B,OADI,OAAOD,KAAS,YAAYA,EAAK,SAAS,IAAUA,IACjDH,EAAO,aAAaA,EAAO;AACpC"}
@@ -33,6 +33,9 @@ export interface CredentialFieldDefinition {
33
33
  generatable?: boolean;
34
34
  /** Must be an absolute https URL. */
35
35
  url?: boolean;
36
+ /** The value must match this pattern (whole value), else `patternMessage`. */
37
+ pattern?: RegExp;
38
+ patternMessage?: string;
36
39
  }
37
40
  export interface PlatformCredentialDefinition {
38
41
  platform: ChannelSetupPlatform;
@@ -40,13 +43,27 @@ export interface PlatformCredentialDefinition {
40
43
  fields: CredentialFieldDefinition[];
41
44
  /** Where to paste the inbound webhook URL on the platform side. */
42
45
  inboundHint: string;
46
+ /**
47
+ * False when the platform does not call a URL (Discord: messages arrive
48
+ * over the bot's Gateway connection); the card then shows only the hint.
49
+ */
50
+ usesInboundUrl: boolean;
43
51
  }
44
52
  /**
45
53
  * Connector types whose credentials the form can collect directly. The keys
46
- * are the ones global-channel-svc reads: Slack sends with `botToken` and
47
- * verifies inbound requests with `signingSecret`; a generic webhook verifies
48
- * with `webhookSecret` (HMAC-SHA256 hex in `X-Signature`) and POSTs replies
49
- * to `targetUrl`.
54
+ * are the ones global-channel-svc reads:
55
+ * - Slack sends with `botToken` and verifies inbound requests with
56
+ * `signingSecret`.
57
+ * - Microsoft Teams (an Azure Bot): `appId` is the audience inbound Bot
58
+ * Framework tokens must carry; `appId` + `appPassword` + `tenantId` get the
59
+ * token replies are posted with.
60
+ * - WhatsApp (Cloud API): inbound requests are verified with `appSecret`
61
+ * (X-Hub-Signature-256) and the subscription check with `verifyToken`;
62
+ * replies are sent from `phoneNumberId` with `accessToken`.
63
+ * - Discord: the bot (`botToken`) receives messages over its Gateway
64
+ * connection; `guildId` names the server whose messages this channel takes.
65
+ * - A generic webhook verifies with `webhookSecret` (HMAC-SHA256 hex in
66
+ * `X-Signature`) and POSTs replies to `targetUrl`.
50
67
  */
51
68
  export declare const PLATFORM_CREDENTIALS: Readonly<Record<string, PlatformCredentialDefinition>>;
52
69
  export declare function connectorPlatform(connectorType: string): ChannelSetupPlatform | undefined;