Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-ui): add guardrails hooks dashboard + per-agent tab (bucket b slice c)
Andy Pavia72c7a217f10d
diff --git a/control-ui/app/constants/hostDetails.ts b/control-ui/app/constants/hostDetails.tsindex c0d042ddc..beb6e6c85 100644--- a/control-ui/app/constants/hostDetails.ts+++ b/control-ui/app/constants/hostDetails.ts@@ -8,6 +8,7 @@ export const HOST_TABS = ['users','teams','approvals',+ 'guardrails','env',] as constdiff --git a/control-ui/app/constants/routes.ts b/control-ui/app/constants/routes.tsindex 333dff0a9..fe268c24a 100644--- a/control-ui/app/constants/routes.ts+++ b/control-ui/app/constants/routes.ts@@ -61,6 +61,9 @@ export const CONTROL_ROUTES = {edit: (name: string) => `/external-channels/${segment(name)}/edit`,},globalFileSystem: '/global-file-system',+ guardrails: {+ root: '/guardrails',+ },llmModels: {root: '/llm-models',discovery: '/llm-models/discovery',diff --git a/control-ui/app/globals.css b/control-ui/app/globals.cssindex 013e7dda3..b45f99376 100644--- a/control-ui/app/globals.css+++ b/control-ui/app/globals.css@@ -1898,6 +1898,66 @@ textarea.cu-input {justify-content: flex-end;}+.cu-guardrails-table-wrap {+ container-type: inline-size;+}++.cu-guardrails-table {+ min-width: 52rem;+ --cu-expandable-inset-left: calc(3rem + 0.85rem);+ --cu-expandable-inset-right: 6rem;+}++.cu-guardrails-table th:nth-child(1),+.cu-guardrails-table td:nth-child(1) {+ width: 3rem;+}++.cu-guardrails-table th:nth-child(2),+.cu-guardrails-table td:nth-child(2) {+ width: 30%;+ max-width: 30%;+}++.cu-guardrails-table th:nth-child(4),+.cu-guardrails-table td:nth-child(4) {+ width: 5rem;+}++.cu-guardrails-table th:nth-child(5),+.cu-guardrails-table td:nth-child(5) {+ width: 8rem;+}++.cu-guardrails-table th:nth-child(6),+.cu-guardrails-table td:nth-child(6) {+ width: 9rem;+}++.cu-guardrails-table th:nth-child(7),+.cu-guardrails-table td:nth-child(7) {+ width: 6rem;+ text-align: right;+}++.cu-guardrails-table td:nth-child(7) .cu-table-actions {+ justify-content: flex-end;+}++/* Per-agent Guardrails tab: add-built-in control row + removable hook chip. */+.cu-guardrails-add-row {+ display: flex;+ flex-wrap: wrap;+ gap: var(--cu-space-2);+ align-items: center;+}++.cu-guardrails-ref-chip {+ display: inline-flex;+ align-items: center;+ gap: var(--cu-space-1);+}+.cu-expandable-row__name,.cu-installed-plugin__name {color: var(--cu-text);diff --git a/control-ui/app/guardrails/page.tsx b/control-ui/app/guardrails/page.tsxnew file mode 100644index 000000000..c5e9fcabf--- /dev/null+++ b/control-ui/app/guardrails/page.tsx@@ -0,0 +1,74 @@+'use client'++import React, { useEffect, useState } from 'react'+import { useConfirmDialog } from '../../components/ConfirmDialog'+import { DashboardLayout } from '../../components/DashboardLayout'+import { GuardrailHooksTable } from '../../components/GuardrailHooksTable'+import type { LlmHookRef } from '../../components/GuardrailHooksTable.types'+import { useToast } from '../../components/Toast'+import { deleteLlmHook, getLlmHooks, isSilentApiError } from '../../lib/api'+import type { LlmHookResource } from '../../lib/api'++export default function GuardrailsPage() {+ const { showToast } = useToast()+ const [loading, setLoading] = useState(true)+ const [error, setError] = useState('')+ const [hooks, setHooks] = useState<LlmHookResource[]>([])+ const [uninstallingKey, setUninstallingKey] = useState<string | null>(null)+ const { confirm, confirmDialog } = useConfirmDialog()++ async function loadAll() {+ setLoading(true)+ setError('')+ try {+ const result = await getLlmHooks()+ setHooks((result.items || []) as LlmHookResource[])+ } catch (e) {+ if (isSilentApiError(e)) return+ setError(e instanceof Error ? e.message : 'Failed to load guardrail hooks')+ } finally {+ setLoading(false)+ }+ }++ async function handleUninstall(hook: LlmHookRef) {+ const shouldDelete = await confirm({+ title: 'Uninstall Guardrail Hook',+ message: `Uninstall guardrail hook ${hook.name}? This removes the LlmHook and its deployment.`,+ confirmLabel: 'Uninstall',+ tone: 'danger',+ })+ if (!shouldDelete) return+ setUninstallingKey(hook.name)+ setError('')+ try {+ await deleteLlmHook(hook.name)+ await loadAll()+ showToast(`Guardrail hook ${hook.name} uninstalled.`, { tone: 'success' })+ } catch (e) {+ if (isSilentApiError(e)) return+ setError(e instanceof Error ? e.message : `Failed to uninstall ${hook.name}`)+ } finally {+ setUninstallingKey(null)+ }+ }++ useEffect(() => {+ void loadAll()+ }, [])++ return (+ <DashboardLayout>+ {error ? <div className="cu-banner cu-banner--error">{error}</div> : null}+ <GuardrailHooksTable+ items={hooks}+ onUninstall={handleUninstall}+ uninstallingKey={uninstallingKey}+ onRefresh={loadAll}+ refreshing={loading}+ loading={loading && hooks.length === 0}+ />+ {confirmDialog}+ </DashboardLayout>+ )+}diff --git a/control-ui/app/hosts/[name]/[tab]/page.tsx b/control-ui/app/hosts/[name]/[tab]/page.tsxindex 52b04221d..d8d648a23 100644--- a/control-ui/app/hosts/[name]/[tab]/page.tsx+++ b/control-ui/app/hosts/[name]/[tab]/page.tsx@@ -16,6 +16,7 @@ export default async function HostTabPage({ params }: HostTabPageProps) {'env-vars','member-access','team-access',+ 'guardrails',]if (!tabs.includes(tab)) notFound()diff --git a/control-ui/app/hosts/[name]/page.tsx b/control-ui/app/hosts/[name]/page.tsxindex 6729e08c6..1efc4d042 100644--- a/control-ui/app/hosts/[name]/page.tsx+++ b/control-ui/app/hosts/[name]/page.tsx@@ -10,6 +10,8 @@ import { HOST_DEFAULT_TAB, HOST_TABS } from '@constants/hostDetails'import { CONTROL_ROUTES } from '@constants/routes'import { HostApprovalSection } from '../../../components/HostApprovalSection'import { HostEnvTable } from '../../../components/HostEnvTable'+import { HostGuardrailsSection } from '../../../components/HostGuardrailsSection'+import type { HostGuardrails } from '../../../components/HostGuardrailsSection/types'import { HostIdentityTab } from '../../../components/HostIdentityTab'import { LlmProviderConfig } from '../../../components/LlmProviderConfig'import { IconRobot } from '../../../components/Sidebar/icons'@@ -52,6 +54,7 @@ const TAB_LABELS: Record<HostTab, string> = {details: 'Overview',model: 'Models & creds',approvals: 'Per-tool approval',+ guardrails: 'Guardrails',contexts: 'Context',env: 'Env vars',users: 'Member access',@@ -63,6 +66,7 @@ const TAB_SLUGS: Record<HostTab, string> = {details: 'overview',model: 'model',approvals: 'approvals',+ guardrails: 'guardrails',contexts: 'contexts',env: 'env-vars',users: 'member-access',@@ -149,6 +153,7 @@ export default function HostDetailsPage() {const [approvalToolsData, setApprovalToolsData] = useState<Record<string, boolean> | undefined>(undefined)+ const [guardrailsData, setGuardrailsData] = useState<HostGuardrails | undefined>(undefined)const [statelessDraft, setStatelessDraft] = useState(false)const [savedStateless, setSavedStateless] = useState(false)const [lifecycleState, setLifecycleState] = useState('')@@ -318,6 +323,10 @@ export default function HostDetailsPage() {}const rawTools = (spec.approval as { tools?: Record<string, boolean> } | undefined)?.toolssetApprovalToolsData(rawTools && typeof rawTools === 'object' ? rawTools : undefined)+ const rawGuardrails = spec.guardrails as HostGuardrails | undefined+ setGuardrailsData(+ rawGuardrails && typeof rawGuardrails === 'object' ? rawGuardrails : undefined+ )const specStateless = spec.lifecycle?.stateless === truesetSavedStateless(specStateless)setLifecycleState(String(host.status?.lifecycle?.state ?? ''))@@ -775,6 +784,51 @@ export default function HostDetailsPage() {[routeName])+ // Persist Host.spec.guardrails (hook references + built-ins). Owns only the+ // guardrails object — every other spec field is preserved via the+ // `...currentHost.spec` spread (full-replace semantics). Carries the+ // form-load resourceVersion so a concurrent change 409s instead of being+ // overwritten (AP-6), surfacing the same reload guidance as the other saves.+ const persistGuardrails = useCallback(+ async (next: HostGuardrails) => {+ setBusy(true)+ setError('')+ try {+ const currentHost = await getHost(routeName)+ const nextSpec = {+ ...currentHost.spec,+ guardrails: next,+ }+ const formResourceVersion = formResourceVersionRef.current+ await apiSend('PUT', `/api/v1/admin/hosts/${encodeURIComponent(routeName)}`, {+ ...(formResourceVersion ? { metadata: { resourceVersion: formResourceVersion } } : {}),+ spec: nextSpec,+ })+ // Reload guardrails/server state while preserving any drafts left open+ // in the Overview or Model tabs.+ await loadData('none')+ showToast('Guardrails saved.', { tone: 'success' })+ } catch (e) {+ const status = (e as { status?: number } | null)?.status+ const code = (e as { code?: string } | null)?.code+ if (status === 409 && code === 'conflict') {+ setError(+ "This agent changed since you opened the form (another edit, or the agent's own lifecycle state updated). Reload to see the latest, then re-apply your change."+ )+ } else {+ setError(e instanceof Error ? e.message : 'Failed to save guardrails')+ }+ // Re-throw so HostGuardrailsSection stays in edit mode and keeps the+ // operator's draft alongside the error/conflict banner.+ throw e+ } finally {+ setBusy(false)+ }+ },+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [routeName]+ )+async function grantUserAccess() {if (selectedUserIdsToGrant.length === 0 || hasPendingRename) returnsetBusy(true)@@ -941,7 +995,9 @@ export default function HostDetailsPage() {tabAriaLabel="Agent sections"tabClassName="cu-tabs--compact"contentClassName={- activeTab === 'approvals' || (activeTab === 'model' && editingModel)+ activeTab === 'approvals' ||+ activeTab === 'guardrails' ||+ (activeTab === 'model' && editingModel)? 'cu-agent-detail-card': undefined}@@ -1258,6 +1314,15 @@ export default function HostDetailsPage() {/>)}+ {activeTab === 'guardrails' && !initialLoading && (+ <HostGuardrailsSection+ initialGuardrails={guardrailsData}+ onSave={persistGuardrails}+ busy={busy}+ canWrite={true /* TODO: wire to actual host:write check if/when per-field RBAC lands */}+ />+ )}+{activeTab === 'contexts' && (<><p className="cu-muted" style={{ fontSize: '0.875rem', marginBottom: '1rem' }}>diff --git a/control-ui/components/DashboardLayout.tsx b/control-ui/components/DashboardLayout.tsxindex 6528ccb71..89fa9335c 100644--- a/control-ui/components/DashboardLayout.tsx+++ b/control-ui/components/DashboardLayout.tsx@@ -84,6 +84,9 @@ function PersistentDashboardFrame({ children }: Pick<DashboardLayoutProps, 'chilif (isControlRouteSection(pathname, CONTROL_ROUTES.connectors.root)) {return 'mcp-servers'}+ if (isControlRouteSection(pathname, CONTROL_ROUTES.guardrails.root)) {+ return 'guardrails'+ }if (isControlRouteSection(pathname, CONTROL_ROUTES.agentFiles.root)) {return 'directories'}diff --git a/control-ui/components/GuardrailHooksTable.tsx b/control-ui/components/GuardrailHooksTable.tsxnew file mode 100644index 000000000..7208ab3ba--- /dev/null+++ b/control-ui/components/GuardrailHooksTable.tsx@@ -0,0 +1,328 @@+'use client'++import React, { Fragment, useMemo, useState } from 'react'+import type { LlmHookStatus } from '../lib/api'+import type {+ GuardrailHooksTableProps,+ LlmHookSpecView,+ LlmHookTarget,+} from './GuardrailHooksTable.types'+import { SectionSearchInput } from './SectionSearchInput'+import { IconShield } from './Sidebar/icons'+import { SkeletonTableRows } from './SkeletonTableRows'+import { TableHeaderRow } from './TableHeaderRow'+import type { TableHeaderColumn } from './TableHeaderRow/types'+import { TablePanelHeader } from './TablePanelHeader'+import { IconChevronRight, IconRefresh, IconX } from './icons'++const HOOK_COLUMNS: TableHeaderColumn[] = [+ { key: 'expand', ariaLabel: 'Expand hook' },+ { key: 'name', label: 'Name' },+ { key: 'lifecycle', label: 'Lifecycle' },+ { key: 'order', label: 'Order' },+ { key: 'failMode', label: 'Fail mode' },+ { key: 'status', label: 'Status' },+ { key: 'actions', align: 'right', ariaLabel: 'Actions' },+]++function StatusBadge({ status }: { status?: LlmHookStatus }) {+ const conditions = status?.conditions+ const ready = conditions?.find(c => c.type === 'Ready' && c.status === 'True')+ const failing = conditions?.find(c => c.status === 'False')+ const state = ready ? 'ready' : failing ? 'error' : conditions?.length ? 'pending' : 'unknown'+ const label =+ state === 'ready'+ ? 'Ready'+ : state === 'error'+ ? 'Error'+ : state === 'pending'+ ? 'Pending'+ : 'Unknown'+ return (+ <span+ className={`cu-connector-badge cu-connector-badge--status-${state}`}+ title={failing?.message}+ >+ {label}+ </span>+ )+}++function FailModeBadge({ failMode }: { failMode?: 'open' | 'closed' }) {+ if (!failMode) return <span className="cu-muted">—</span>+ return (+ <span+ className={`cu-connector-badge cu-connector-badge--${failMode === 'open' ? 'yes' : 'no'}`}+ >+ {failMode}+ </span>+ )+}++function describeTarget(target?: LlmHookTarget): string {+ if (target?.image?.ref) return target.image.ref+ if (target?.service?.name) {+ const namespace = target.service.namespace ? `${target.service.namespace}/` : ''+ const port = target.service.port ? `:${target.service.port}` : ''+ return `${namespace}${target.service.name}${port}`+ }+ if (target?.remote?.baseUrl) return target.remote.baseUrl+ return ''+}++export function GuardrailHooksTable({+ items,+ onUninstall,+ uninstallingKey,+ onRefresh,+ refreshing,+ loading,+}: GuardrailHooksTableProps) {+ const [searchQuery, setSearchQuery] = useState('')+ const [expandedKeys, setExpandedKeys] = useState<Set<string>>(new Set())++ const rows = useMemo(+ () =>+ items.map(item => {+ const name = item.metadata?.name || 'unknown'+ return { key: name, name, item }+ }),+ [items]+ )+ const normalizedSearch = searchQuery.trim().toLowerCase()+ const filteredRows = useMemo(() => {+ if (!normalizedSearch) return rows+ return rows.filter(({ name, item }) => {+ const spec = (item.spec || {}) as LlmHookSpecView+ const conditionText = (item.status?.conditions || [])+ .map(condition =>+ [condition.type, condition.status, condition.reason, condition.message].join(' ')+ )+ .join(' ')+ return [+ name,+ (spec.lifecyclePoints || []).join(' '),+ spec.failMode,+ describeTarget(spec.target),+ (spec.capabilities || []).join(' '),+ conditionText,+ ]+ .join(' ')+ .toLowerCase()+ .includes(normalizedSearch)+ })+ }, [normalizedSearch, rows])++ React.useEffect(() => {+ if (!onRefresh) return+ const id = setInterval(() => void onRefresh(), 10_000)+ return () => clearInterval(id)+ }, [onRefresh])++ function toggleExpanded(key: string) {+ setExpandedKeys(current => {+ const next = new Set(current)+ if (next.has(key)) next.delete(key)+ else next.add(key)+ return next+ })+ }++ const isInitialLoad = loading && items.length === 0++ return (+ <div className="cu-card cu-card--viewport-fill cu-section-card">+ <TablePanelHeader+ title={+ <>+ <IconShield />+ {isInitialLoad ? 'Guardrail Hooks' : `Guardrail Hooks (${filteredRows.length})`}+ </>+ }+ subtitle="Installed LLM guardrail hooks across the cluster."+ actions={+ <>+ <SectionSearchInput+ value={searchQuery}+ onChange={setSearchQuery}+ placeholder="Search hooks"+ ariaLabel="Search guardrail hooks"+ disabled={isInitialLoad}+ />+ {onRefresh ? (+ <button+ type="button"+ className="cu-btn cu-btn--icon cu-btn--toolbar"+ onClick={() => void onRefresh()}+ disabled={refreshing || isInitialLoad}+ aria-label={refreshing ? 'Refreshing...' : 'Reload guardrail hooks'}+ >+ <IconRefresh+ className={refreshing ? 'cu-spin' : undefined}+ width={18}+ height={18}+ />+ </button>+ ) : null}+ </>+ }+ />+ {isInitialLoad ? (+ <div className="cu-table-wrap cu-guardrails-table-wrap">+ <table className="cu-table cu-table--header-band cu-expandable-table cu-guardrails-table">+ <thead>+ <TableHeaderRow columns={HOOK_COLUMNS} />+ </thead>+ <tbody>+ <SkeletonTableRows columns={HOOK_COLUMNS.length} rows={5} />+ </tbody>+ </table>+ </div>+ ) : filteredRows.length === 0 ? (+ <div className="cu-empty">+ {normalizedSearch ? 'No hooks match this search.' : 'No guardrail hooks installed.'}+ </div>+ ) : (+ <div className="cu-table-wrap cu-guardrails-table-wrap">+ <table className="cu-table cu-table--header-band cu-expandable-table cu-guardrails-table">+ <thead>+ <TableHeaderRow columns={HOOK_COLUMNS} />+ </thead>+ <tbody>+ {filteredRows.map(({ key, name, item }) => {+ const spec = (item.spec || {}) as LlmHookSpecView+ const expanded = expandedKeys.has(key)+ const lifecycle = (spec.lifecyclePoints || []).join(', ')+ const target = describeTarget(spec.target)+ return (+ <Fragment key={key}>+ <tr+ className="cu-table__row cu-table__row--clickable cu-expandable-row"+ role="button"+ onClick={() => toggleExpanded(key)}+ onKeyDown={event => {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault()+ toggleExpanded(key)+ }+ }}+ tabIndex={0}+ aria-expanded={expanded}+ aria-controls={`hook-details-${key}`}+ aria-label={`${expanded ? 'Collapse' : 'Expand'} hook ${name}`}+ >+ <td className="cu-expandable-row__chevron" aria-hidden="true">+ <IconChevronRight+ className={expanded ? 'is-expanded' : undefined}+ width={18}+ height={18}+ />+ </td>+ <td>+ <span className="cu-expandable-row__name">{name}</span>+ </td>+ <td>{lifecycle ? lifecycle : <span className="cu-muted">—</span>}</td>+ <td>+ {typeof spec.order === 'number' ? (+ spec.order+ ) : (+ <span className="cu-muted">—</span>+ )}+ </td>+ <td>+ <FailModeBadge failMode={spec.failMode} />+ </td>+ <td>+ <StatusBadge status={item.status} />+ </td>+ <td+ className="cu-table__cell-actions"+ onClick={event => event.stopPropagation()}+ onKeyDown={event => event.stopPropagation()}+ >+ <div className="cu-table-actions">+ {onUninstall ? (+ <button+ type="button"+ className="cu-btn cu-btn--icon cu-btn--danger-icon"+ onClick={() => void onUninstall({ name })}+ disabled={uninstallingKey === key}+ aria-label={+ uninstallingKey === key+ ? 'Uninstalling...'+ : `Uninstall hook ${name}`+ }+ title={+ uninstallingKey === key+ ? 'Uninstalling...'+ : `Uninstall hook ${name}`+ }+ >+ <IconX width={16} height={16} />+ </button>+ ) : null}+ </div>+ </td>+ </tr>+ {expanded ? (+ <tr id={`hook-details-${key}`} className="cu-expandable-detail-row">+ <td colSpan={HOOK_COLUMNS.length}>+ <div className="cu-expandable-detail cu-connector-detail">+ <div className="cu-expandable-detail__fields">+ <div className="cu-expandable-field cu-expandable-field--wide">+ <span className="cu-expandable-field__label">Target</span>+ <span className="cu-expandable-field__code">{target || '—'}</span>+ </div>+ <div className="cu-expandable-field">+ <span className="cu-expandable-field__label">Path</span>+ <span className="cu-expandable-field__code">+ {spec.path || '/'}+ </span>+ </div>+ <div className="cu-expandable-field cu-expandable-field--wide">+ <span className="cu-expandable-field__label">Capabilities</span>+ {spec.capabilities && spec.capabilities.length > 0 ? (+ <div className="cu-expandable-tags">+ {spec.capabilities.map(capability => (+ <span key={capability} className="cu-registry-tag">+ {capability}+ </span>+ ))}+ </div>+ ) : (+ <span className="cu-muted">None declared</span>+ )}+ </div>+ <div className="cu-expandable-field">+ <span className="cu-expandable-field__label">Observed digest</span>+ <span className="cu-expandable-field__code">+ {item.status?.observedDigest || '—'}+ </span>+ </div>+ <div className="cu-expandable-field">+ <span className="cu-expandable-field__label">Ready replicas</span>+ <span>+ {typeof item.status?.readyReplicas === 'number'+ ? item.status.readyReplicas+ : '—'}+ </span>+ </div>+ <div className="cu-expandable-field">+ <span className="cu-expandable-field__label">Last reconciled</span>+ <span>{item.status?.lastReconciled || '—'}</span>+ </div>+ </div>+ </div>+ </td>+ </tr>+ ) : null}+ </Fragment>+ )+ })}+ </tbody>+ </table>+ </div>+ )}+ </div>+ )+}diff --git a/control-ui/components/GuardrailHooksTable.types.ts b/control-ui/components/GuardrailHooksTable.types.tsnew file mode 100644index 000000000..934db4675--- /dev/null+++ b/control-ui/components/GuardrailHooksTable.types.ts@@ -0,0 +1,37 @@+import type { LlmHookResource } from '../lib/api'++// Structured view over the LlmHook CR `spec` (typed `AnyRecord` in lib/api).+// The reconciler writes the oneOf target shape; only one branch is populated.+export type LlmHookTarget = {+ image?: { ref?: string; port?: number }+ service?: { name?: string; namespace?: string; port?: number }+ remote?: { baseUrl?: string }+}++export type LlmHookLifecyclePoint = 'preCall' | 'moderate' | 'postCallSuccess' | 'onError'++export type LlmHookCapability =+ | 'may_deny'+ | 'may_rewrite'+ | 'may_substitute_result'+ | 'may_add_context'++export type LlmHookSpecView = {+ target?: LlmHookTarget+ path?: string+ lifecyclePoints?: LlmHookLifecyclePoint[]+ order?: number+ failMode?: 'open' | 'closed'+ capabilities?: LlmHookCapability[]+}++export type LlmHookRef = { name: string }++export type GuardrailHooksTableProps = {+ items: LlmHookResource[]+ onUninstall?: (hook: LlmHookRef) => Promise<void>+ uninstallingKey?: string | null+ onRefresh?: () => void+ refreshing?: boolean+ loading?: boolean+}diff --git a/control-ui/components/HostGuardrailsSection/constants.ts b/control-ui/components/HostGuardrailsSection/constants.tsnew file mode 100644index 000000000..2b2e611ab--- /dev/null+++ b/control-ui/components/HostGuardrailsSection/constants.ts@@ -0,0 +1,29 @@+import type { GuardrailBuiltinType, GuardrailPhase } from './types'++// Render/iteration order for the hook phases.+export const GUARDRAIL_PHASES: readonly GuardrailPhase[] = [+ 'preToolUse',+ 'preCall',+ 'moderate',+ 'postCallSuccess',+ 'postToolUse',+ 'onError',+] as const++export const GUARDRAIL_PHASE_LABELS: Record<GuardrailPhase, string> = {+ preToolUse: 'Pre-tool use',+ postToolUse: 'Post-tool use',+ preCall: 'Pre-call',+ moderate: 'Moderate',+ postCallSuccess: 'Post-call success',+ onError: 'On error',+}++// Curated built-in types offered by the minimal add UI.+export const GUARDRAIL_BUILTIN_OPTIONS: ReadonlyArray<{+ value: GuardrailBuiltinType+ label: string+}> = [+ { value: 'prompt-shaping', label: 'Prompt shaping' },+ { value: 'token-trim', label: 'Token trim' },+] as constdiff --git a/control-ui/components/HostGuardrailsSection/index.tsx b/control-ui/components/HostGuardrailsSection/index.tsxnew file mode 100644index 000000000..dce71281a--- /dev/null+++ b/control-ui/components/HostGuardrailsSection/index.tsx@@ -0,0 +1,323 @@+'use client'++import React, { useMemo, useState } from 'react'+import { IconX } from '../icons'+import { Button, SelectInput, TextInput } from '../ui'+import { GUARDRAIL_BUILTIN_OPTIONS, GUARDRAIL_PHASES, GUARDRAIL_PHASE_LABELS } from './constants'+import type {+ GuardrailBuiltin,+ GuardrailBuiltinType,+ GuardrailHookRef,+ GuardrailPhase,+ HostGuardrails,+ HostGuardrailsSectionProps,+} from './types'++function cloneGuardrails(source: HostGuardrails | undefined): HostGuardrails {+ return {+ ...source,+ hooks: source?.hooks ? { ...source.hooks } : {},+ builtins: source?.builtins ? source.builtins.map(builtin => ({ ...builtin })) : [],+ }+}++export function HostGuardrailsSection({+ initialGuardrails,+ onSave,+ busy,+ canWrite,+ defaultEditing = false,+}: HostGuardrailsSectionProps) {+ const [editing, setEditing] = useState(defaultEditing)+ const [draft, setDraft] = useState<HostGuardrails>(() => cloneGuardrails(initialGuardrails))++ // Re-seed the draft whenever the saved guardrails change (reload after save).+ const initialKey = JSON.stringify(initialGuardrails ?? {})+ React.useEffect(() => {+ setDraft(cloneGuardrails(initialGuardrails))+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [initialKey])++ const isDirty = useMemo(+ () => JSON.stringify(draft) !== JSON.stringify(cloneGuardrails(initialGuardrails)),+ [draft, initialGuardrails]+ )++ const hookPhases = useMemo(+ () =>+ GUARDRAIL_PHASES.map(phase => ({+ phase,+ refs: draft.hooks?.[phase] ?? [],+ })).filter(entry => entry.refs.length > 0),+ [draft.hooks]+ )+ const builtins = draft.builtins ?? []+ const hasAny = hookPhases.length > 0 || builtins.length > 0++ function removeHookRef(phase: GuardrailPhase, id: string) {+ setDraft(current => {+ const currentRefs = current.hooks?.[phase] ?? []+ const nextRefs = currentRefs.filter(ref => ref.id !== id)+ const nextHooks: HostGuardrails['hooks'] = { ...current.hooks }+ if (nextRefs.length > 0) nextHooks[phase] = nextRefs+ else delete nextHooks[phase]+ return { ...current, hooks: nextHooks }+ })+ }++ function addBuiltin(builtin: GuardrailBuiltin) {+ setDraft(current => ({+ ...current,+ builtins: [...(current.builtins ?? []), builtin],+ }))+ }++ function removeBuiltin(index: number) {+ setDraft(current => ({+ ...current,+ builtins: (current.builtins ?? []).filter((_, i) => i !== index),+ }))+ }++ function handleCancel() {+ setDraft(cloneGuardrails(initialGuardrails))+ setEditing(defaultEditing)+ }++ async function handleSave() {+ try {+ await onSave(draft)+ setEditing(defaultEditing)+ } catch {+ // Parent surfaced an error/conflict banner. Stay in edit mode so the+ // operator's draft survives the failure.+ }+ }++ return (+ <div className="cu-host-approval-section">+ <p className="cu-muted cu-host-approval-section__description">+ Installed guardrail hooks referenced by this agent, plus built-in guardrails. Remove a hook+ reference or add a built-in. Manage installed hooks cluster-wide from the Guardrails+ section.+ </p>++ <div className="cu-host-approval-section__content">+ {!editing ? (+ !hasAny ? (+ <div className="cu-empty">+ No guardrail hooks or built-ins configured for this agent.+ </div>+ ) : (+ <div>+ {hookPhases.map(({ phase, refs }) => (+ <div key={phase} className="cu-access-row">+ <span>{GUARDRAIL_PHASE_LABELS[phase]}</span>+ <div className="cu-expandable-tags">+ {refs.map(ref => (+ <span+ key={ref.id}+ className="cu-registry-tag"+ title={ref.digest ? `digest ${ref.digest}` : undefined}+ >+ {ref.id}+ </span>+ ))}+ </div>+ </div>+ ))}+ {builtins.map((builtin, index) => (+ <div key={`${builtin.type}-${index}`} className="cu-access-row">+ <span>Built-in · {builtin.type}</span>+ <span>+ order {typeof builtin.order === 'number' ? builtin.order : '—'} · fail{' '}+ {builtin.failMode ?? 'open'}+ </span>+ </div>+ ))}+ </div>+ )+ ) : (+ <EditMode+ hookPhases={hookPhases}+ builtins={builtins}+ busy={busy}+ onRemoveHookRef={removeHookRef}+ onAddBuiltin={addBuiltin}+ onRemoveBuiltin={removeBuiltin}+ />+ )}+ </div>++ <div className="cu-host-approval-section__actions">+ {editing ? (+ <>+ <button+ type="button"+ className="cu-btn cu-btn--ghost cu-btn--sm"+ onClick={handleCancel}+ disabled={busy}+ >+ Cancel+ </button>+ <button+ type="button"+ className="cu-btn cu-btn--primary"+ onClick={handleSave}+ disabled={busy || !isDirty}+ >+ {busy ? 'Saving…' : 'Save'}+ </button>+ </>+ ) : canWrite ? (+ <button+ type="button"+ className="cu-btn cu-btn--ghost cu-btn--sm"+ onClick={() => setEditing(true)}+ disabled={busy}+ >+ Edit+ </button>+ ) : null}+ </div>+ </div>+ )+}++interface EditModeProps {+ hookPhases: Array<{ phase: GuardrailPhase; refs: GuardrailHookRef[] }>+ builtins: GuardrailBuiltin[]+ busy: boolean+ onRemoveHookRef: (phase: GuardrailPhase, id: string) => void+ onAddBuiltin: (builtin: GuardrailBuiltin) => void+ onRemoveBuiltin: (index: number) => void+}++function EditMode({+ hookPhases,+ builtins,+ busy,+ onRemoveHookRef,+ onAddBuiltin,+ onRemoveBuiltin,+}: EditModeProps) {+ const [builtinType, setBuiltinType] = useState<GuardrailBuiltinType>('prompt-shaping')+ const [orderValue, setOrderValue] = useState('0')+ const [failMode, setFailMode] = useState<'open' | 'closed'>('open')++ function handleAdd() {+ const parsedOrder = Number.parseInt(orderValue, 10)+ onAddBuiltin({+ type: builtinType,+ order: Number.isFinite(parsedOrder) ? parsedOrder : 0,+ failMode,+ })+ setOrderValue('0')+ setFailMode('open')+ setBuiltinType('prompt-shaping')+ }++ return (+ <>+ <div className="cu-field">+ <label>Referenced hooks</label>+ {hookPhases.length === 0 ? (+ <div className="cu-empty">No installed hooks are referenced by this agent.</div>+ ) : (+ hookPhases.map(({ phase, refs }) => (+ <div key={phase} className="cu-access-row">+ <span>{GUARDRAIL_PHASE_LABELS[phase]}</span>+ <div className="cu-expandable-tags">+ {refs.map(ref => (+ <span key={ref.id} className="cu-guardrails-ref-chip">+ <span+ className="cu-registry-tag"+ title={ref.digest ? `digest ${ref.digest}` : undefined}+ >+ {ref.id}+ </span>+ <button+ type="button"+ className="cu-btn cu-btn--icon cu-btn--danger-icon"+ aria-label={`Remove hook ${ref.id} from ${GUARDRAIL_PHASE_LABELS[phase]}`}+ onClick={() => onRemoveHookRef(phase, ref.id)}+ disabled={busy}+ >+ <IconX />+ </button>+ </span>+ ))}+ </div>+ </div>+ ))+ )}+ </div>++ <div className="cu-field">+ <label>Built-in guardrails</label>+ {builtins.length === 0 ? (+ <div className="cu-empty">No built-in guardrails configured.</div>+ ) : (+ builtins.map((builtin, index) => (+ <div key={`${builtin.type}-${index}`} className="cu-access-row">+ <span>+ {builtin.type} · order {typeof builtin.order === 'number' ? builtin.order : '—'} ·+ fail {builtin.failMode ?? 'open'}+ </span>+ <button+ type="button"+ className="cu-btn cu-btn--icon cu-btn--danger-icon"+ aria-label={`Remove built-in ${builtin.type}`}+ onClick={() => onRemoveBuiltin(index)}+ disabled={busy}+ >+ <IconX />+ </button>+ </div>+ ))+ )}+ </div>++ <div className="cu-field">+ <label htmlFor="guardrail-builtin-type">Add built-in</label>+ <div className="cu-guardrails-add-row">+ <SelectInput+ id="guardrail-builtin-type"+ compact+ value={builtinType}+ onChange={e => setBuiltinType(e.target.value as GuardrailBuiltinType)}+ disabled={busy}+ >+ {GUARDRAIL_BUILTIN_OPTIONS.map(option => (+ <option key={option.value} value={option.value}>+ {option.label}+ </option>+ ))}+ </SelectInput>+ <TextInput+ type="number"+ compact+ narrow+ value={orderValue}+ onChange={e => setOrderValue(e.target.value)}+ disabled={busy}+ aria-label="Built-in order"+ />+ <SelectInput+ compact+ value={failMode}+ onChange={e => setFailMode(e.target.value as 'open' | 'closed')}+ disabled={busy}+ aria-label="Built-in fail mode"+ >+ <option value="open">Fail open</option>+ <option value="closed">Fail closed</option>+ </SelectInput>+ <Button variant="ghost" size="sm" onClick={handleAdd} disabled={busy}>+ Add+ </Button>+ </div>+ </div>+ </>+ )+}diff --git a/control-ui/components/HostGuardrailsSection/types.ts b/control-ui/components/HostGuardrailsSection/types.tsnew file mode 100644index 000000000..32033c992--- /dev/null+++ b/control-ui/components/HostGuardrailsSection/types.ts@@ -0,0 +1,47 @@+// Phases keying `Host.spec.guardrails.hooks`. Each maps to an ordered list of+// installed-hook references (id + pinned digest).+export type GuardrailPhase =+ | 'preToolUse'+ | 'postToolUse'+ | 'preCall'+ | 'moderate'+ | 'postCallSuccess'+ | 'onError'++export type GuardrailHookRef = { id: string; digest?: string }++// Built-in guardrails supported by the minimal add UI. The stored `type` is a+// free string on the CR; the picker offers this curated subset.+export type GuardrailBuiltinType = 'prompt-shaping' | 'token-trim'++export type GuardrailBuiltin = {+ type: string+ order?: number+ failMode?: 'open' | 'closed'+ timeoutMs?: number+ config?: Record<string, unknown>+}++// Structured view over `Host.spec.guardrails` (typed `AnyRecord` in lib/api).+// Fields this section does not edit (rules, trust level, ceiling, limits) are+// carried through untouched so a save never drops them.+export type HostGuardrails = {+ rules?: unknown[]+ hooks?: Partial<Record<GuardrailPhase, GuardrailHookRef[]>>+ builtins?: GuardrailBuiltin[]+ minInstalledHookTrustLevel?: string+ capabilityCeiling?: string[]+ limits?: Record<string, unknown>+}++export interface HostGuardrailsSectionProps {+ initialGuardrails: HostGuardrails | undefined+ // Persist the full guardrails object (parent merges it into the Host spec+ // under the resourceVersion precondition). Rejects on failure so the section+ // keeps the operator's draft.+ onSave: (next: HostGuardrails) => Promise<void>+ busy: boolean+ canWrite: boolean+ // Render the editable list immediately instead of the read-only summary.+ defaultEditing?: boolean+}diff --git a/control-ui/components/Sidebar/constants.tsx b/control-ui/components/Sidebar/constants.tsxindex 7c2fcfa19..7a5aca3b8 100644--- a/control-ui/components/Sidebar/constants.tsx+++ b/control-ui/components/Sidebar/constants.tsx@@ -14,6 +14,7 @@ import {IconRobot,IconRunReplay,IconSettings,+ IconShield,IconStore,IconTokenBudgets,IconTraceDashboard,@@ -32,6 +33,11 @@ export const SIDEBAR_TABS: Record<SidebarTab, SidebarItem> = {icon: <IconCable />,},contexts: { label: 'Contexts', href: CONTROL_ROUTES.contexts.root, icon: <IconGroupWork /> },+ guardrails: {+ label: 'Guardrails',+ href: CONTROL_ROUTES.guardrails.root,+ icon: <IconShield />,+ },cost: {label: 'Cost & Usage',href: CONTROL_ROUTES.costAndUsage.root,diff --git a/control-ui/components/Sidebar/icons.tsx b/control-ui/components/Sidebar/icons.tsxindex f758a6510..e0233b34c 100644--- a/control-ui/components/Sidebar/icons.tsx+++ b/control-ui/components/Sidebar/icons.tsx@@ -23,6 +23,25 @@ export function IconWorkflow() {)}+export function IconShield() {+ return (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="18"+ height="18"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M12 3l7 3v5c0 4.5 -3 7.5 -7 9c-4 -1.5 -7 -4.5 -7 -9V6l7 -3z" />+ <path d="M9 12l2 2l4 -4" />+ </svg>+ )+}+export function IconOutputs() {return (<svgdiff --git a/control-ui/components/Sidebar/types.ts b/control-ui/components/Sidebar/types.tsindex a50716fe5..1bbae3048 100644--- a/control-ui/components/Sidebar/types.ts+++ b/control-ui/components/Sidebar/types.ts@@ -3,6 +3,7 @@ import type { ReactNode } from 'react'export type SidebarTab =| 'hosts'| 'contexts'+ | 'guardrails'| 'mcp-servers'| 'directories'| 'communication-channels'diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.tsindex cc61cf0da..720b01de0 100644--- a/control-ui/lib/api.ts+++ b/control-ui/lib/api.ts@@ -832,6 +832,27 @@ export type McpServerResource = {spec?: AnyRecordstatus?: { conditions?: McpServerCondition[] }}++// Installed guardrail hook CRs (LlmHook). Reconciler-written status follows the+// same conditions[] convention as McpServer, plus hook-specific fields.+export type LlmHookCondition = {+ type: string+ status: 'True' | 'False' | 'Unknown'+ reason?: string+ message?: string+ lastTransitionTime?: string+}+export type LlmHookStatus = {+ conditions?: LlmHookCondition[]+ observedDigest?: string+ readyReplicas?: number+ lastReconciled?: string+}+export type LlmHookResource = {+ metadata?: Metadata+ spec?: AnyRecord+ status?: LlmHookStatus+}export type ContextUser = {id: stringemail: string@@ -1034,6 +1055,20 @@ export async function getMcpServers() {return apiGet('/api/v1/admin/mcp-servers') as Promise<{ items?: McpServerResource[] }>}+// ── Installed guardrail hooks (LlmHook CRDs) — read + uninstall ─────────────+// Creation is via the org-scoped registry install-hook saga, not a raw write.+export async function getLlmHooks() {+ return apiGet('/api/v1/admin/llm-hooks') as Promise<{ items?: LlmHookResource[] }>+}++export async function getLlmHook(name: string) {+ return apiGet(`/api/v1/admin/llm-hooks/${encodeURIComponent(name)}`) as Promise<LlmHookResource>+}++export async function deleteLlmHook(name: string) {+ return apiSend('DELETE', `/api/v1/admin/llm-hooks/${encodeURIComponent(name)}`)+}+// ── SharedFileSystem CRD admin + per-SFS file browsing ──────────────────export async function getSharedFileSystems() {diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex dcca8f277..4d312c178 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.389",+ "version": "0.1.390","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.389",+ "version": "0.1.390","dependencies": {"@clerum/llm-providers": "file:../packages/llm-providers","@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",diff --git a/control-ui/package.json b/control-ui/package.jsonindex d71b5a910..7467c2e7c 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.389",+ "version": "0.1.390","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",