"use client"; import * as React from "react"; import { toast } from "sonner"; import { BotIcon, ListFilterIcon, PencilIcon, PlusIcon, ShieldAlertIcon, Trash2Icon, } from "lucide-react"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Separator } from "@/components/ui/separator"; import { Switch } from "@/components/ui/switch"; import { Textarea } from "@/components/ui/textarea"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle, } from "@/components/ui/sheet"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { Card, CardContent } from "@/components/ui/card"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { api } from "@/lib/api"; import type { InterceptAction, InterceptRule, JudgeConfig, JudgeDayUsage, JudgeUsage, LLMProfile, Tool, } from "@/lib/types"; // fmtTokens 把 token 数压成紧凑写法(1.2k / 3.4M),用于审批用量统计。 function fmtTokens(n: number): string { if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + "M"; if (n >= 1000) return (n / 1000).toFixed(1) + "k"; return String(n); } // JudgeStat 是一块统计数字(标签 + 数值)。 function JudgeStat({ label, value }: { label: string; value: string }) { return (
{label}
{value}
); } // JudgeSparkbars 用纯 div 画近 N 天每日消耗(输入+输出)的迷你柱图,免图表库依赖。 function JudgeSparkbars({ daily }: { daily: JudgeDayUsage[] }) { const max = Math.max(1, ...daily.map((d) => d.input_tokens + d.output_tokens)); return (
{daily.map((d) => { const total = d.input_tokens + d.output_tokens; const h = Math.max(2, Math.round((total / max) * 100)); return (
); })}
); } // ---- tool scope ---- // SDK tools are intentionally not seeded into the DB (they apply to every agent // and have no per-agent binding). We hardcode them here so they still appear in // the scope dialog. function sdkTool(key: string, description: string): Tool { return { key, system: true, description, schema: {}, agents: [], enabled: true, kind: "builtin" }; } const SDK_EXEC: Tool[] = [ sdkTool("Bash", "在 shell 中执行命令"), sdkTool("WebFetch", "发起 HTTP/HTTPS 请求(含代理支持)"), sdkTool("web_search", "网络搜索"), sdkTool("shell_open", "开启持久 PTY 交互会话"), sdkTool("shell_send", "向交互会话发送输入"), sdkTool("shell_read", "读取交互会话输出"), sdkTool("shell_close", "关闭交互会话"), sdkTool("shell_list", "列出所有交互会话"), ]; const SDK_WRITE: Tool[] = [ sdkTool("Write", "写入文件"), sdkTool("Edit", "编辑文件(精确替换)"), sdkTool("MultiEdit", "批量编辑文件"), ]; const SDK_KEYS = new Set([...SDK_EXEC, ...SDK_WRITE].map((t) => t.key)); function groupTools(dbTools: Tool[]) { const sys: Tool[] = [], custom: Tool[] = []; for (const t of dbTools) { if (SDK_KEYS.has(t.key)) continue; // already covered by hardcoded groups if (t.system) sys.push(t); else custom.push(t); } return [ { label: "执行类", tools: SDK_EXEC }, { label: "写入/编辑类", tools: SDK_WRITE }, { label: "系统工具", tools: sys }, { label: "自定义工具", tools: custom }, ].filter((g) => g.tools.length > 0); } // ---- form state ---- type RuleForm = { name: string; enabled: boolean; priority: number; match_target: "tool_name" | "tool_input"; match_type: "string" | "regex"; pattern: string; action: InterceptAction; message: string; timeout_enabled: boolean; timeout_seconds: number; timeout_action: "deny" | "allow"; }; const defaultForm = (): RuleForm => ({ name: "", enabled: true, priority: 0, match_target: "tool_name", match_type: "string", pattern: "", action: "deny", message: "", timeout_enabled: true, timeout_seconds: 60, timeout_action: "deny", }); // ---- small components ---- function ActionBadge({ action }: { action: InterceptAction }) { if (action === "allow") return 允许; if (action === "deny") return 禁止; return 申请; } function Field({ label, children }: { label: string; children: React.ReactNode }) { return (
{children}
); } // ---- LLM fallback judge card ---- const FOLLOW_ACTIVE = "0"; // profile_id 0 = 跟随激活/默认配置 const defaultJudge = (): JudgeConfig => ({ enabled: false, profile_id: 0, prompt: "", timeout_seconds: 15, fail_action: "allow", ask_timeout_seconds: 300, ask_timeout_action: "deny", }); function JudgeCard() { const [cfg, setCfg] = React.useState(defaultJudge()); const [profiles, setProfiles] = React.useState([]); const [loading, setLoading] = React.useState(true); const [saving, setSaving] = React.useState(false); const [usage, setUsage] = React.useState(null); // 审批用量统计:失败不打断配置页,仅在开启时拉取。 const loadUsage = React.useCallback(async () => { try { setUsage(await api.interceptJudgeUsage(30)); } catch { // 忽略:统计不可用不应影响配置编辑 } }, []); const load = React.useCallback(async () => { setLoading(true); try { const [j, ps] = await Promise.all([api.interceptGetJudgeConfig(), api.llmProfiles()]); setCfg(j); setProfiles(ps); } catch (e) { toast.error("加载模型兜底配置失败: " + (e as Error).message); } finally { setLoading(false); } }, []); React.useEffect(() => { load(); }, [load]); // 开启后(含初次加载把开关读为 true 时)拉取审批用量统计。 React.useEffect(() => { if (cfg.enabled) loadUsage(); }, [cfg.enabled, loadUsage]); function patch(p: Partial) { setCfg((c) => ({ ...c, ...p })); } async function save() { setSaving(true); try { await api.interceptSetJudgeConfig(cfg); toast.success("模型兜底配置已保存"); await load(); // 回读:提示词若清空则回填内置模板 } catch (e) { toast.error("保存失败: " + (e as Error).message); } finally { setSaving(false); } } async function restorePrompt() { // 清空提示词并保存 → 服务端下次返回内置模板全文,回填到输入框。 setSaving(true); try { await api.interceptSetJudgeConfig({ ...cfg, prompt: "" }); const j = await api.interceptGetJudgeConfig(); setCfg(j); toast.success("已恢复内置默认模板"); } catch (e) { toast.error("恢复失败: " + (e as Error).message); } finally { setSaving(false); } } return (
{/* 启用开关 —— 独立高亮条 */}

模型兜底审批

在拦截范围内、且没有任何拦截规则命中的命令,才由模型做语义判断(放行 / 转人工 / 拦截)

{cfg.enabled ? "已启用" : "未启用"} patch({ enabled: v })} />
{/* 审批 Token 用量统计(全局累计,独立于各模型配置) */} {cfg.enabled && usage && (

审批 Token 消耗

模型兜底审批累计用量,单独计量(worker=judge),不与各模型配置的统计混在一起

{usage.daily.length > 0 && (

近 30 天每日消耗(输入 + 输出)

)}
)} {cfg.enabled && (
{/* 左:提示词编辑器(直接展开,主区域) */}

审批提示词

模型据此判定 ALLOW / ASK / DENY,可直接编辑