chore: ARTEX 初始化
ARTEX — AI 自主渗透测试系统(Go 后端 + Next.js 前端,单二进制内嵌)。 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
commit
0ef8561411
287 files changed
+70178
No files matched your search
@@ -0,0 +1,47 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
|
||||
import { ArrowLeftIcon } from "lucide-react";
|
||||
|
||||
import { AgentEditor } from "@/components/agent-editor";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
// Deep-link editor page for one agent. The primary flow is the drawer on
|
||||
// /system/agents; this page reuses the same AgentEditor component full-width so a
|
||||
// direct URL (or an external link) still opens the editor.
|
||||
function AgentDetailInner() {
|
||||
const searchParams = useSearchParams();
|
||||
const key = searchParams.get("key") ?? "";
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button asChild variant="ghost" size="icon-sm">
|
||||
<Link href="/system/agents">
|
||||
<ArrowLeftIcon className="size-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">Agent</h1>
|
||||
<p className="text-muted-foreground font-mono text-xs">{key}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-1 flex-col rounded-lg border">
|
||||
<AgentEditor agentKey={key} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// useSearchParams must sit under a Suspense boundary for static export.
|
||||
export default function AgentDetailPage() {
|
||||
return (
|
||||
<React.Suspense fallback={null}>
|
||||
<AgentDetailInner />
|
||||
</React.Suspense>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Bot, PlusIcon, Trash2Icon } from "lucide-react";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
|
||||
import { AgentEditor } from "@/components/agent-editor";
|
||||
import { api } from "@/lib/api";
|
||||
import type { Agent } from "@/lib/types";
|
||||
|
||||
// AgentGridCard is one clickable tile opening the agent's editor drawer. Custom
|
||||
// (non-builtin) agents get a delete button.
|
||||
function AgentGridCard({
|
||||
agent,
|
||||
onOpen,
|
||||
onDeleted,
|
||||
}: {
|
||||
agent: Agent;
|
||||
onOpen: () => void;
|
||||
onDeleted: () => void;
|
||||
}) {
|
||||
async function del() {
|
||||
try {
|
||||
await api.deleteAgent(agent.key);
|
||||
toast.success(`已删除 Agent「${agent.name}」`);
|
||||
onDeleted();
|
||||
} catch (e) {
|
||||
toast.error("删除失败:" + (e as Error).message);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div className="hover:border-primary/50 group relative flex flex-col gap-2 rounded-lg border p-4 transition-colors">
|
||||
<button type="button" onClick={onOpen} className="flex flex-col gap-2 text-left">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Bot className="text-muted-foreground size-4" />
|
||||
<span className="text-sm font-medium">{agent.name}</span>
|
||||
<span className="text-muted-foreground font-mono text-xs">{agent.key}</span>
|
||||
{agent.builtin ? (
|
||||
<Badge variant="secondary" className="px-1.5 py-0 text-[10px]">
|
||||
内置
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
|
||||
自定义
|
||||
</Badge>
|
||||
)}
|
||||
{!agent.enabled && (
|
||||
<Badge variant="outline" className="text-destructive px-1.5 py-0 text-[10px]">
|
||||
已停用
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-muted-foreground line-clamp-2 min-h-8 text-xs">
|
||||
{agent.description || "(无描述)"}
|
||||
</p>
|
||||
<div className="text-muted-foreground flex flex-wrap gap-1.5 text-[10px]">
|
||||
<span className="rounded border px-1.5 py-0.5">MCP {agent.mcp_count ?? 0}</span>
|
||||
<span className="rounded border px-1.5 py-0.5">Skill {agent.skill_count ?? 0}</span>
|
||||
<span className="rounded border px-1.5 py-0.5">工具 {agent.tool_count ?? 0}</span>
|
||||
</div>
|
||||
</button>
|
||||
{!agent.builtin && (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="text-muted-foreground hover:text-destructive absolute top-2 right-2 opacity-0 transition-opacity group-hover:opacity-100"
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>删除 Agent「{agent.name}」?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
将一并删除它的提示词、变量、可见性与工具绑定。此操作不可撤销。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={del}>删除</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateAgentDialog({ onCreated }: { onCreated: (key: string) => void }) {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [key, setKey] = React.useState("");
|
||||
const [name, setName] = React.useState("");
|
||||
const [description, setDescription] = React.useState("");
|
||||
const [busy, setBusy] = React.useState(false);
|
||||
|
||||
async function create() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const a = await api.createAgent(key.trim(), name.trim(), description.trim());
|
||||
toast.success(`已创建 Agent「${a.name}」`);
|
||||
setOpen(false);
|
||||
setKey("");
|
||||
setName("");
|
||||
setDescription("");
|
||||
onCreated(a.key);
|
||||
} catch (e) {
|
||||
toast.error("创建失败:" + (e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const keyOk = /^[a-z][a-z0-9_]*$/.test(key.trim());
|
||||
const canCreate = keyOk && name.trim().length > 0 && !busy;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button size="sm">
|
||||
<PlusIcon /> 新建 Agent
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>新建自定义 Agent</DialogTitle>
|
||||
<DialogDescription>
|
||||
创建一个会话型助手。key 用于内部标识,创建后不可更改;名称与描述用于识别。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-2">
|
||||
<div className="grid gap-1.5">
|
||||
<Label htmlFor="agent-key">Key</Label>
|
||||
<Input
|
||||
id="agent-key"
|
||||
placeholder="如 research_helper"
|
||||
value={key}
|
||||
onChange={(e) => setKey(e.target.value)}
|
||||
className="font-mono"
|
||||
/>
|
||||
{key.length > 0 && !keyOk && (
|
||||
<span className="text-destructive text-xs">小写字母开头,仅含小写字母/数字/下划线</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="grid gap-1.5">
|
||||
<Label htmlFor="agent-name">名称</Label>
|
||||
<Input
|
||||
id="agent-name"
|
||||
placeholder="如 研究助手"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-1.5">
|
||||
<Label htmlFor="agent-desc">描述</Label>
|
||||
<Textarea
|
||||
id="agent-desc"
|
||||
placeholder="一句话说明这个 Agent 是干什么的"
|
||||
rows={2}
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button onClick={create} disabled={!canCreate}>
|
||||
创建
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AgentsPage() {
|
||||
const [agents, setAgents] = React.useState<Agent[]>([]);
|
||||
const [editKey, setEditKey] = React.useState<string | null>(null);
|
||||
|
||||
const reload = React.useCallback(() => {
|
||||
api.agents().then(setAgents).catch(() => setAgents([]));
|
||||
}, []);
|
||||
React.useEffect(() => {
|
||||
reload();
|
||||
}, [reload]);
|
||||
|
||||
const editing = agents.find((a) => a.key === editKey) ?? null;
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col gap-4 md:gap-6">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">Agent</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
内置 Agent 的提示词/配置,以及自定义会话 Agent 的创建与管理
|
||||
</p>
|
||||
</div>
|
||||
<CreateAgentDialog
|
||||
onCreated={(key) => {
|
||||
reload();
|
||||
setEditKey(key);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Agent 清单</CardTitle>
|
||||
<CardDescription>共 {agents.length} 个</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{agents.length === 0 ? (
|
||||
<p className="text-muted-foreground py-6 text-center text-sm">(暂无 Agent)</p>
|
||||
) : (
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{agents.map((a) => (
|
||||
<AgentGridCard key={a.key} agent={a} onOpen={() => setEditKey(a.key)} onDeleted={reload} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Sheet open={!!editing} onOpenChange={(o) => !o && setEditKey(null)}>
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="flex flex-col gap-0 p-0 data-[side=right]:w-[45vw] data-[side=right]:sm:max-w-[45vw]"
|
||||
>
|
||||
{editing && (
|
||||
<>
|
||||
<SheetHeader className="px-4">
|
||||
<SheetTitle className="flex items-center gap-2">
|
||||
{editing.name}
|
||||
<span className="text-muted-foreground font-mono text-xs">{editing.key}</span>
|
||||
{!editing.builtin && (
|
||||
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
|
||||
自定义
|
||||
</Badge>
|
||||
)}
|
||||
</SheetTitle>
|
||||
<SheetDescription>{editing.description || "提示词、配置、可见资源与工具绑定"}</SheetDescription>
|
||||
</SheetHeader>
|
||||
<AgentEditor agentKey={editing.key} onSaved={reload} />
|
||||
</>
|
||||
)}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { CheckIcon, ClipboardListIcon, RefreshCwIcon, ShieldAlertIcon, XIcon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { api } from "@/lib/api";
|
||||
import type { InterceptApprovalRow } from "@/lib/types";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
|
||||
// ---- helpers ----------------------------------------------------------------
|
||||
|
||||
function fmtTime(s: string) {
|
||||
if (!s) return "—";
|
||||
const d = new Date(s);
|
||||
return d.toLocaleString("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" });
|
||||
}
|
||||
|
||||
function SourceCell({ row }: { row: InterceptApprovalRow }) {
|
||||
if (row.task_id) {
|
||||
return (
|
||||
<div className="space-y-0.5">
|
||||
<div className="font-mono text-xs font-medium">{row.task_id}</div>
|
||||
<div className="text-[11px] text-muted-foreground">{row.agent_name || "—"}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (row.conversation_id) {
|
||||
const agent = row.conv_agent_key || "—";
|
||||
const title = row.conv_title || `对话 #${row.conversation_id}`;
|
||||
return (
|
||||
<div className="space-y-0.5">
|
||||
<div className="font-medium">{title}</div>
|
||||
<div className="text-[11px] text-muted-foreground">Agent: {agent}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <span className="text-muted-foreground">—</span>;
|
||||
}
|
||||
|
||||
function StatusBadge({ status }: { status: string }) {
|
||||
if (status === "pending") return <Badge variant="outline" className="border-amber-400 text-amber-600">待审批</Badge>;
|
||||
if (status === "allowed") return <Badge variant="outline" className="border-emerald-500 text-emerald-600">已允许</Badge>;
|
||||
if (status === "denied") return <Badge variant="outline" className="border-red-500 text-red-600">已拒绝</Badge>;
|
||||
return <Badge variant="outline" className="text-muted-foreground">已超时</Badge>;
|
||||
}
|
||||
|
||||
function InputPreview({ input }: { input: Record<string, unknown> }) {
|
||||
const full = JSON.stringify(input, null, 2);
|
||||
const s = JSON.stringify(input);
|
||||
const short = s.length > 120 ? s.slice(0, 120) + "…" : s;
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<code className="block w-full cursor-default truncate font-mono text-[11px] text-muted-foreground">
|
||||
{short}
|
||||
</code>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="start" className="max-w-sm">
|
||||
<pre className="whitespace-pre-wrap break-all font-mono text-xs">{full}</pre>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- main component ---------------------------------------------------------
|
||||
|
||||
export default function ApprovalsPage() {
|
||||
const [rows, setRows] = React.useState<InterceptApprovalRow[]>([]);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [deciding, setDeciding] = React.useState<number | null>(null);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const items = await api.interceptHistory();
|
||||
setRows(items);
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
React.useEffect(() => {
|
||||
load();
|
||||
const t = setInterval(load, 5000);
|
||||
return () => clearInterval(t);
|
||||
}, []);
|
||||
|
||||
async function decide(id: number, decision: "allowed" | "denied") {
|
||||
if (deciding !== null) return;
|
||||
setDeciding(id);
|
||||
try {
|
||||
await api.interceptDecide(id, decision);
|
||||
toast.success(decision === "allowed" ? "已允许执行" : "已拒绝执行");
|
||||
setRows((prev) =>
|
||||
prev.map((r) =>
|
||||
r.id === id ? { ...r, status: decision, decided_at: new Date().toISOString() } : r,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
} finally {
|
||||
setDeciding(null);
|
||||
}
|
||||
}
|
||||
|
||||
const pending = rows.filter((r) => r.status === "pending");
|
||||
const decided = rows.filter((r) => r.status !== "pending");
|
||||
|
||||
return (
|
||||
<TooltipProvider delayDuration={300}>
|
||||
<div className="flex flex-1 flex-col gap-6 p-6">
|
||||
{/* header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<ClipboardListIcon className="h-5 w-5 text-muted-foreground" />
|
||||
<h1 className="text-xl font-semibold">审批记录</h1>
|
||||
{pending.length > 0 && (
|
||||
<Badge className="rounded-full bg-destructive text-destructive-foreground">{pending.length} 待审批</Badge>
|
||||
)}
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={load} disabled={loading}>
|
||||
<RefreshCwIcon className="mr-1.5 h-3.5 w-3.5" />
|
||||
刷新
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* pending section */}
|
||||
{pending.length > 0 && (
|
||||
<section className="rounded-lg border border-amber-400/40 bg-amber-50/30 dark:bg-amber-950/10">
|
||||
<div className="flex items-center gap-2 border-b border-amber-400/30 px-4 py-3 text-sm font-medium text-amber-700 dark:text-amber-400">
|
||||
<ShieldAlertIcon className="h-4 w-4" />
|
||||
待处理 ({pending.length})
|
||||
</div>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-12">#</TableHead>
|
||||
<TableHead>工具</TableHead>
|
||||
<TableHead>来源</TableHead>
|
||||
<TableHead>匹配规则</TableHead>
|
||||
<TableHead className="w-48">参数</TableHead>
|
||||
<TableHead>时间</TableHead>
|
||||
<TableHead className="w-28 text-right">操作</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{pending.map((row) => (
|
||||
<TableRow key={row.id}>
|
||||
<TableCell className="text-muted-foreground">{row.id}</TableCell>
|
||||
<TableCell>
|
||||
<code className="rounded bg-muted px-1.5 py-0.5 text-xs font-mono">{row.tool_name}</code>
|
||||
</TableCell>
|
||||
<TableCell><SourceCell row={row} /></TableCell>
|
||||
<TableCell>
|
||||
{row.rule_name
|
||||
? <span className="text-sm">{row.rule_name}</span>
|
||||
: <span className="text-muted-foreground">—</span>}
|
||||
</TableCell>
|
||||
<TableCell className="w-48 max-w-[12rem]"><InputPreview input={row.tool_input} /></TableCell>
|
||||
<TableCell className="whitespace-nowrap text-xs text-muted-foreground">{fmtTime(row.created_at)}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end gap-1.5">
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-7 px-2 text-xs"
|
||||
disabled={deciding === row.id}
|
||||
onClick={() => decide(row.id, "allowed")}
|
||||
>
|
||||
<CheckIcon className="mr-1 h-3 w-3" />
|
||||
允许
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
className="h-7 px-2 text-xs"
|
||||
disabled={deciding === row.id}
|
||||
onClick={() => decide(row.id, "denied")}
|
||||
>
|
||||
<XIcon className="mr-1 h-3 w-3" />
|
||||
拒绝
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* history section */}
|
||||
<section className="rounded-lg border">
|
||||
<div className="border-b px-4 py-3 text-sm font-medium text-muted-foreground">
|
||||
全部记录 ({rows.length})
|
||||
</div>
|
||||
{rows.length === 0 && !loading ? (
|
||||
<div className="py-16 text-center text-sm text-muted-foreground">暂无审批记录</div>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-12">#</TableHead>
|
||||
<TableHead>工具</TableHead>
|
||||
<TableHead>来源</TableHead>
|
||||
<TableHead>匹配规则</TableHead>
|
||||
<TableHead className="w-48">参数</TableHead>
|
||||
<TableHead>状态</TableHead>
|
||||
<TableHead>申请时间</TableHead>
|
||||
<TableHead>决定时间</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{rows.map((row) => (
|
||||
<TableRow key={row.id} className={row.status === "pending" ? "opacity-40" : ""}>
|
||||
<TableCell className="text-muted-foreground">{row.id}</TableCell>
|
||||
<TableCell>
|
||||
<code className="rounded bg-muted px-1.5 py-0.5 text-xs font-mono">{row.tool_name}</code>
|
||||
</TableCell>
|
||||
<TableCell><SourceCell row={row} /></TableCell>
|
||||
<TableCell>
|
||||
{row.rule_name
|
||||
? <span className="text-sm">{row.rule_name}</span>
|
||||
: <span className="text-muted-foreground">—</span>}
|
||||
</TableCell>
|
||||
<TableCell className="w-48 max-w-[12rem]"><InputPreview input={row.tool_input} /></TableCell>
|
||||
<TableCell><StatusBadge status={row.status} /></TableCell>
|
||||
<TableCell className="whitespace-nowrap text-xs text-muted-foreground">{fmtTime(row.created_at)}</TableCell>
|
||||
<TableCell className="whitespace-nowrap text-xs text-muted-foreground">
|
||||
{row.decided_at ? fmtTime(row.decided_at) : "—"}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,633 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
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 { api } from "@/lib/api";
|
||||
import type { InterceptRule, InterceptAction, Tool } from "@/lib/types";
|
||||
|
||||
// ---- 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 <Badge variant="secondary">允许</Badge>;
|
||||
if (action === "deny") return <Badge variant="destructive">禁止</Badge>;
|
||||
return <Badge variant="outline" className="border-amber-400 text-amber-600">申请</Badge>;
|
||||
}
|
||||
|
||||
function Field({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
|
||||
{label}
|
||||
</Label>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- page ----
|
||||
|
||||
export default function InterceptPage() {
|
||||
const [rules, setRules] = React.useState<InterceptRule[]>([]);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [editing, setEditing] = React.useState<InterceptRule | null>(null);
|
||||
const [form, setForm] = React.useState<RuleForm>(defaultForm());
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
const [regexErr, setRegexErr] = React.useState("");
|
||||
const [regexWarn, setRegexWarn] = React.useState(false); // true = JS 无法解析但可能是合法 Go 语法
|
||||
|
||||
// ---- tool scope dialog ----
|
||||
const [scopeOpen, setScopeOpen] = React.useState(false);
|
||||
const [allTools, setAllTools] = React.useState<Tool[]>([]);
|
||||
const [enabledTools, setEnabledTools] = React.useState<Set<string>>(new Set());
|
||||
const [scopeLoading, setScopeLoading] = React.useState(false);
|
||||
const [scopeSaving, setScopeSaving] = React.useState(false);
|
||||
|
||||
// ---- data ----
|
||||
|
||||
const load = React.useCallback(async () => {
|
||||
try {
|
||||
const r = await api.interceptRules();
|
||||
setRules(r);
|
||||
} catch {
|
||||
toast.error("加载拦截规则失败");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => { load(); }, [load]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (form.match_type !== "regex" || !form.pattern) { setRegexErr(""); setRegexWarn(false); return; }
|
||||
try {
|
||||
new RegExp(form.pattern);
|
||||
setRegexErr("");
|
||||
setRegexWarn(false);
|
||||
} catch {
|
||||
// JS RegExp 不支持 Go RE2 扩展语法(如 (?i) 内联 flag)。
|
||||
// 这里只是预览校验失败,不代表 Go 端无效;交给服务端最终验证。
|
||||
setRegexErr("");
|
||||
setRegexWarn(true);
|
||||
}
|
||||
}, [form.pattern, form.match_type]);
|
||||
|
||||
// ---- rule handlers ----
|
||||
|
||||
function set(patch: Partial<RuleForm>) { setForm(f => ({ ...f, ...patch })); }
|
||||
|
||||
function openNew() {
|
||||
setEditing(null);
|
||||
setForm(defaultForm());
|
||||
setRegexErr("");
|
||||
setOpen(true);
|
||||
}
|
||||
|
||||
function openEdit(rule: InterceptRule) {
|
||||
setEditing(rule);
|
||||
setForm({
|
||||
name: rule.name, enabled: rule.enabled, priority: rule.priority,
|
||||
match_target: rule.match_target, match_type: rule.match_type,
|
||||
pattern: rule.pattern, action: rule.action, message: rule.message,
|
||||
timeout_enabled: rule.timeout_enabled, timeout_seconds: rule.timeout_seconds,
|
||||
timeout_action: rule.timeout_action,
|
||||
});
|
||||
setRegexErr("");
|
||||
setOpen(true);
|
||||
}
|
||||
|
||||
async function handleSave() {
|
||||
if (!form.name.trim()) { toast.error("名称不能为空"); return; }
|
||||
if (!form.pattern.trim()) { toast.error("模式不能为空"); return; }
|
||||
if (regexErr) { toast.error("正则表达式语法无效"); return; }
|
||||
setSaving(true);
|
||||
try {
|
||||
if (editing) {
|
||||
await api.updateInterceptRule(editing.id, form);
|
||||
toast.success("规则已更新");
|
||||
} else {
|
||||
await api.createInterceptRule(form);
|
||||
toast.success("规则已创建");
|
||||
}
|
||||
setOpen(false);
|
||||
load();
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(id: number) {
|
||||
try {
|
||||
await api.deleteInterceptRule(id);
|
||||
toast.success("规则已删除");
|
||||
load();
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleToggle(rule: InterceptRule) {
|
||||
try {
|
||||
await api.toggleInterceptRule(rule.id, !rule.enabled);
|
||||
load();
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- scope handlers ----
|
||||
|
||||
async function openScope() {
|
||||
setScopeOpen(true);
|
||||
setScopeLoading(true);
|
||||
try {
|
||||
const [tools, cfg] = await Promise.all([api.tools(), api.interceptGetToolConfig()]);
|
||||
setAllTools(tools);
|
||||
setEnabledTools(new Set(cfg.enabled_tools));
|
||||
} catch (e) {
|
||||
toast.error("加载失败: " + (e as Error).message);
|
||||
} finally {
|
||||
setScopeLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTool(key: string, val: boolean) {
|
||||
setEnabledTools(prev => {
|
||||
const next = new Set(prev);
|
||||
if (val) next.add(key); else next.delete(key);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
async function saveScope() {
|
||||
setScopeSaving(true);
|
||||
try {
|
||||
await api.interceptSetToolConfig([...enabledTools]);
|
||||
toast.success("拦截范围已保存");
|
||||
setScopeOpen(false);
|
||||
} catch (e) {
|
||||
toast.error("保存失败: " + (e as Error).message);
|
||||
} finally {
|
||||
setScopeSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
const toolGroups = React.useMemo(() => groupTools(allTools), [allTools]);
|
||||
|
||||
// ---- render ----
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col gap-6 p-6">
|
||||
|
||||
{/* ---- header ---- */}
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<ShieldAlertIcon className="h-5 w-5 mt-0.5 shrink-0" />
|
||||
<div>
|
||||
<h1 className="text-lg font-semibold leading-tight">拦截规则</h1>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">
|
||||
工具执行前按优先级(数字越大越先)逐条匹配,首条命中的规则生效
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<Button variant="outline" size="sm" onClick={openScope}>
|
||||
<ListFilterIcon className="h-4 w-4" />
|
||||
拦截范围
|
||||
</Button>
|
||||
<Button onClick={openNew} size="sm">
|
||||
<PlusIcon className="h-4 w-4" />
|
||||
新建规则
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ---- rules table ---- */}
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
{loading ? (
|
||||
<p className="p-6 text-sm text-muted-foreground">加载中…</p>
|
||||
) : rules.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 py-16 text-center">
|
||||
<ShieldAlertIcon className="h-8 w-8 text-muted-foreground/40" />
|
||||
<p className="text-sm text-muted-foreground">暂无规则</p>
|
||||
<Button size="sm" variant="outline" onClick={openNew}>
|
||||
<PlusIcon className="h-4 w-4" />
|
||||
新建第一条规则
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="hover:bg-transparent">
|
||||
<TableHead className="w-[72px]">优先级</TableHead>
|
||||
<TableHead>名称</TableHead>
|
||||
<TableHead className="w-[90px]">目标</TableHead>
|
||||
<TableHead className="w-[80px]">类型</TableHead>
|
||||
<TableHead>模式</TableHead>
|
||||
<TableHead className="w-[72px]">策略</TableHead>
|
||||
<TableHead className="w-[64px] text-center">启用</TableHead>
|
||||
<TableHead className="w-[80px]" />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{rules.map((rule) => (
|
||||
<TableRow key={rule.id} className={!rule.enabled ? "opacity-40" : ""}>
|
||||
<TableCell>
|
||||
<span className="font-mono text-xs tabular-nums">{rule.priority}</span>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium text-sm">{rule.name}</TableCell>
|
||||
<TableCell>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{rule.match_target === "tool_name" ? "工具名" : "输入内容"}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{rule.match_type === "regex" ? "正则" : "字符串"}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell className="max-w-[220px]">
|
||||
<code className="block truncate rounded bg-muted px-1.5 py-0.5 text-xs font-mono">
|
||||
{rule.pattern}
|
||||
</code>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<ActionBadge action={rule.action} />
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<Switch
|
||||
checked={rule.enabled}
|
||||
onCheckedChange={() => handleToggle(rule)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center justify-end gap-0.5">
|
||||
<Button
|
||||
size="icon" variant="ghost" className="h-7 w-7"
|
||||
onClick={() => openEdit(rule)}
|
||||
>
|
||||
<PencilIcon className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
size="icon" variant="ghost"
|
||||
className="h-7 w-7 text-destructive hover:text-destructive"
|
||||
onClick={() => handleDelete(rule.id)}
|
||||
>
|
||||
<Trash2Icon className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* ---- editor sheet ---- */}
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetContent side="right" className="flex flex-col gap-0 p-0 sm:max-w-md">
|
||||
<SheetHeader className="border-b px-6 py-4">
|
||||
<SheetTitle>{editing ? "编辑规则" : "新建规则"}</SheetTitle>
|
||||
<SheetDescription className="text-xs">
|
||||
优先级越大越先匹配;首条命中规则生效,后续跳过
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto px-6 py-5 space-y-5">
|
||||
<Field label="名称">
|
||||
<Input
|
||||
placeholder="给规则起个名字"
|
||||
value={form.name}
|
||||
onChange={(e) => set({ name: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field label="优先级(数字越大越先匹配)">
|
||||
<Input
|
||||
type="number"
|
||||
value={form.priority}
|
||||
onChange={(e) => set({ priority: parseInt(e.target.value) || 0 })}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Separator />
|
||||
|
||||
<Field label="匹配目标">
|
||||
<Select
|
||||
value={form.match_target}
|
||||
onValueChange={(v) => set({ match_target: v as RuleForm["match_target"] })}
|
||||
>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="tool_name">工具名(tool_name)</SelectItem>
|
||||
<SelectItem value="tool_input">输入内容(tool_input JSON)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
|
||||
<Field label="匹配类型">
|
||||
<Select
|
||||
value={form.match_type}
|
||||
onValueChange={(v) => set({ match_type: v as RuleForm["match_type"] })}
|
||||
>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="string">字符串包含</SelectItem>
|
||||
<SelectItem value="regex">正则表达式</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
|
||||
<Field label="模式">
|
||||
<Input
|
||||
placeholder={form.match_type === "regex" ? "^Bash$" : "rm -rf"}
|
||||
value={form.pattern}
|
||||
onChange={(e) => set({ pattern: e.target.value })}
|
||||
className={regexErr ? "border-destructive focus-visible:ring-destructive" : ""}
|
||||
/>
|
||||
{regexErr && (
|
||||
<p className="text-xs text-destructive mt-1">{regexErr}</p>
|
||||
)}
|
||||
{regexWarn && (
|
||||
<p className="text-xs text-amber-600 mt-1">包含 Go RE2 扩展语法(如 <code className="font-mono">(?i)</code>),浏览器无法预览,提交后由服务端验证</p>
|
||||
)}
|
||||
</Field>
|
||||
|
||||
<Separator />
|
||||
|
||||
<Field label="拦截策略">
|
||||
<Select
|
||||
value={form.action}
|
||||
onValueChange={(v) => set({ action: v as InterceptAction })}
|
||||
>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="allow">允许 — 直接放行,跳过后续规则</SelectItem>
|
||||
<SelectItem value="deny">禁止 — 阻断,返回拒绝消息给模型</SelectItem>
|
||||
<SelectItem value="ask">向用户申请 — 等待审批</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
|
||||
{form.action !== "allow" && (
|
||||
<Field label={form.action === "deny" ? "拒绝消息(返回给模型)" : "审批说明(可选)"}>
|
||||
<Textarea
|
||||
placeholder={form.action === "deny" ? "操作被安全策略阻止" : ""}
|
||||
value={form.message}
|
||||
onChange={(e) => set({ message: e.target.value })}
|
||||
rows={2}
|
||||
className="resize-none"
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
|
||||
{form.action === "ask" && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium">启用审批超时</p>
|
||||
<p className="text-xs text-muted-foreground">超时后自动处置,不再等待</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={form.timeout_enabled}
|
||||
onCheckedChange={(v) => set({ timeout_enabled: v })}
|
||||
/>
|
||||
</div>
|
||||
{form.timeout_enabled && (
|
||||
<div className="flex items-end gap-3">
|
||||
<Field label="超时时间(秒)">
|
||||
<Input
|
||||
type="number"
|
||||
min={5}
|
||||
className="w-28"
|
||||
value={form.timeout_seconds}
|
||||
onChange={(e) => {
|
||||
const n = parseInt(e.target.value, 10);
|
||||
if (n > 0) set({ timeout_seconds: n });
|
||||
}}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="超时动作">
|
||||
<Select
|
||||
value={form.timeout_action}
|
||||
onValueChange={(v) => set({ timeout_action: v as "deny" | "allow" })}
|
||||
>
|
||||
<SelectTrigger className="w-32"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="deny">自动拒绝</SelectItem>
|
||||
<SelectItem value="allow">自动允许</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Switch
|
||||
id="rule-enabled"
|
||||
checked={form.enabled}
|
||||
onCheckedChange={(v) => set({ enabled: v })}
|
||||
/>
|
||||
<Label htmlFor="rule-enabled" className="cursor-pointer">启用此规则</Label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SheetFooter className="border-t px-6 py-4 flex-row justify-end gap-2">
|
||||
<Button variant="outline" onClick={() => setOpen(false)}>取消</Button>
|
||||
<Button onClick={handleSave} disabled={saving || !!regexErr}>
|
||||
{saving ? "保存中…" : "保存"}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
{/* ---- scope dialog ---- */}
|
||||
<Dialog open={scopeOpen} onOpenChange={setScopeOpen}>
|
||||
<DialogContent className="sm:max-w-lg flex flex-col overflow-hidden p-0 gap-0" style={{ maxHeight: "min(80vh, 560px)" }}>
|
||||
<DialogHeader className="shrink-0 border-b px-6 py-4">
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<ListFilterIcon className="h-4 w-4" />
|
||||
拦截范围
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-xs">
|
||||
只有启用拦截的工具才会进入规则匹配;其余工具直接放行
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto px-6 py-4 space-y-5">
|
||||
{scopeLoading ? (
|
||||
<p className="text-sm text-muted-foreground py-4">加载中…</p>
|
||||
) : (
|
||||
toolGroups.map((group, gi) => (
|
||||
<div key={group.label}>
|
||||
{gi > 0 && <Separator className="mb-5" />}
|
||||
<p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-2">
|
||||
{group.label}
|
||||
</p>
|
||||
<div className="space-y-0.5">
|
||||
{group.tools.map((t) => (
|
||||
<div key={t.key} className="flex items-center gap-3 rounded-md px-2 py-1.5 hover:bg-muted/50">
|
||||
<Switch
|
||||
id={`scope-${t.key}`}
|
||||
checked={enabledTools.has(t.key)}
|
||||
onCheckedChange={(v) => toggleTool(t.key, v)}
|
||||
/>
|
||||
<label htmlFor={`scope-${t.key}`} className="flex-1 min-w-0 cursor-pointer">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="font-mono text-sm">{t.key}</span>
|
||||
{(t.kind && t.kind !== "builtin") && (
|
||||
<Badge variant="outline" className="px-1 py-0 text-[10px]">{t.kind}</Badge>
|
||||
)}
|
||||
</div>
|
||||
{t.description && (
|
||||
<p className="text-[11px] text-muted-foreground line-clamp-1">{t.description}</p>
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="shrink-0 border-t px-6 py-3 flex justify-end gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => setScopeOpen(false)}>取消</Button>
|
||||
<Button size="sm" onClick={saveScope} disabled={scopeSaving || scopeLoading}>
|
||||
{scopeSaving ? "保存中…" : "保存"}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,692 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import { Loader2Icon, PlugZapIcon, PlusIcon, SaveIcon, StarIcon, Trash2Icon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { api } from "@/lib/api";
|
||||
import type { LLMProfile } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// 思考强度档位(仅在开关打开时生效)。
|
||||
const EFFORT_LEVELS: { value: string; label: string }[] = [
|
||||
{ value: "low", label: "低" },
|
||||
{ value: "medium", label: "中" },
|
||||
{ value: "high", label: "高" },
|
||||
{ value: "max", label: "最大" },
|
||||
];
|
||||
// 思考模式三态 ↔ 存库字符串 reasoning_effort:
|
||||
// none→""(thinking / reasoning_effort 两个字段都【不发送】,兼容不支持该字段的模型,如 MiniMax)
|
||||
// off →"off"(发送 thinking:{type:disabled},用于默认开启思考、需要显式关闭的模型)
|
||||
// on →强度值(发送 thinking:{enabled} + reasoning_effort)
|
||||
type ThinkMode = "none" | "off" | "on";
|
||||
const THINK_MODES: { value: ThinkMode; label: string }[] = [
|
||||
{ value: "none", label: "不发送(默认)" },
|
||||
{ value: "off", label: "显式关闭" },
|
||||
{ value: "on", label: "开启" },
|
||||
];
|
||||
const toStore = (mode: ThinkMode, effort: string) => (mode === "on" ? effort : mode === "off" ? "off" : "");
|
||||
const modeFromStore = (v?: string): ThinkMode => (!v ? "none" : v === "off" ? "off" : "on");
|
||||
const effortFromStore = (v?: string) => (v && v !== "off" ? v : "high");
|
||||
|
||||
function NewProfileDialog({ onCreated }: { onCreated: (id: string) => void }) {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [name, setName] = React.useState("");
|
||||
const [format, setFormat] = React.useState<"anthropic" | "openai">("anthropic");
|
||||
const [model, setModel] = React.useState("");
|
||||
const [baseUrl, setBaseUrl] = React.useState("");
|
||||
const [proxy, setProxy] = React.useState("");
|
||||
const [apiKey, setApiKey] = React.useState("");
|
||||
const [rps, setRps] = React.useState("0");
|
||||
const [rpm, setRpm] = React.useState("0");
|
||||
const [cw, setCw] = React.useState("0");
|
||||
const [thinkMode, setThinkMode] = React.useState<ThinkMode>("none");
|
||||
const [effort, setEffort] = React.useState("high");
|
||||
|
||||
function reset() {
|
||||
setName("");
|
||||
setFormat("anthropic");
|
||||
setModel("");
|
||||
setBaseUrl("");
|
||||
setProxy("");
|
||||
setApiKey("");
|
||||
setRps("0");
|
||||
setRpm("0");
|
||||
setCw("0");
|
||||
setThinkMode("none");
|
||||
setEffort("high");
|
||||
}
|
||||
|
||||
async function create() {
|
||||
if (!name.trim() || !model.trim()) {
|
||||
toast.error("请填写名称与模型");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { id } = await api.saveLLMProfile({
|
||||
name: name.trim(),
|
||||
format,
|
||||
model: model.trim(),
|
||||
base_url: baseUrl.trim(),
|
||||
proxy: proxy.trim(),
|
||||
api_key: apiKey,
|
||||
rate_per_second: Number(rps) || 0,
|
||||
rate_per_minute: Number(rpm) || 0,
|
||||
context_window_k: Number(cw) || 0,
|
||||
reasoning_effort: toStore(thinkMode, effort),
|
||||
});
|
||||
toast.success(`已新建 Profile:${name.trim()}(在列表中「设为激活」以启用)`);
|
||||
reset();
|
||||
setOpen(false);
|
||||
onCreated(String(id));
|
||||
} catch (e) {
|
||||
toast.error(`新建失败:${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(o) => {
|
||||
setOpen(o);
|
||||
if (!o) reset();
|
||||
}}
|
||||
>
|
||||
<DialogTrigger asChild>
|
||||
<Button size="sm" variant="outline">
|
||||
<PlusIcon /> 新建
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>新建 Profile</DialogTitle>
|
||||
<DialogDescription>新建后不会自动激活,请在列表中「设为激活」以启用。</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-2">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="np-name">名称</Label>
|
||||
<Input
|
||||
id="np-name"
|
||||
placeholder="例如:OpenAI 生产"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="grid gap-2">
|
||||
<Label>格式</Label>
|
||||
<Select value={format} onValueChange={(v) => setFormat(v as "anthropic" | "openai")}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="选择格式" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="anthropic">Anthropic</SelectItem>
|
||||
<SelectItem value="openai">OpenAI</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="np-model">模型</Label>
|
||||
<Input
|
||||
id="np-model"
|
||||
className="font-mono"
|
||||
placeholder="claude-opus-4-8"
|
||||
value={model}
|
||||
onChange={(e) => setModel(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="np-base-url">Base URL(可选)</Label>
|
||||
<Input
|
||||
id="np-base-url"
|
||||
className="font-mono"
|
||||
placeholder="https://api.openai.com/v1"
|
||||
value={baseUrl}
|
||||
onChange={(e) => setBaseUrl(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="np-proxy">代理(可选)</Label>
|
||||
<Input
|
||||
id="np-proxy"
|
||||
className="font-mono"
|
||||
placeholder="http://127.0.0.1:8080 · socks5://127.0.0.1:1080"
|
||||
value={proxy}
|
||||
onChange={(e) => setProxy(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="np-api-key">API Key</Label>
|
||||
<Input
|
||||
id="np-api-key"
|
||||
type="password"
|
||||
placeholder="sk-…"
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="np-rps">每秒限速</Label>
|
||||
<Input id="np-rps" type="number" min={0} value={rps} onChange={(e) => setRps(e.target.value)} />
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="np-rpm">每分钟限速</Label>
|
||||
<Input id="np-rpm" type="number" min={0} value={rpm} onChange={(e) => setRpm(e.target.value)} />
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="np-cw">上下文窗口(K)</Label>
|
||||
<Input
|
||||
id="np-cw"
|
||||
type="number"
|
||||
min={0}
|
||||
max={1000}
|
||||
value={cw}
|
||||
onChange={(e) => setCw(e.target.value)}
|
||||
placeholder="200"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-3 rounded-lg border p-3">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="grid gap-0.5">
|
||||
<Label className="text-sm">思考模式 · Extended Thinking</Label>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
不发送=不带思考字段(兼容 MiniMax 等不支持该字段的模型);显式关闭=发 disabled(默认开思考的模型才需要);开启=先推理再作答。
|
||||
</p>
|
||||
</div>
|
||||
<Select value={thinkMode} onValueChange={(v) => setThinkMode(v as ThinkMode)}>
|
||||
<SelectTrigger className="w-32 shrink-0">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{THINK_MODES.map((o) => (
|
||||
<SelectItem key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{thinkMode === "on" && (
|
||||
<div className="flex items-center justify-between gap-4 border-t pt-3">
|
||||
<div className="grid gap-0.5">
|
||||
<Label className="text-sm">思考强度</Label>
|
||||
<p className="text-muted-foreground text-xs">推理投入档位,越高越深入。</p>
|
||||
</div>
|
||||
<Select value={effort} onValueChange={setEffort}>
|
||||
<SelectTrigger className="w-28 shrink-0">
|
||||
<SelectValue placeholder="强度" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{EFFORT_LEVELS.map((o) => (
|
||||
<SelectItem key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button variant="outline">取消</Button>
|
||||
</DialogClose>
|
||||
<Button onClick={create}>新建</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export default function LLMPage() {
|
||||
const [profiles, setProfiles] = React.useState<LLMProfile[]>([]);
|
||||
const [selectedId, setSelectedId] = React.useState<string | null>(null);
|
||||
const [format, setFormat] = React.useState<"anthropic" | "openai">("anthropic");
|
||||
const [name, setName] = React.useState("");
|
||||
const [model, setModel] = React.useState("");
|
||||
const [baseUrl, setBaseUrl] = React.useState("");
|
||||
const [proxy, setProxy] = React.useState("");
|
||||
const [apiKey, setApiKey] = React.useState("");
|
||||
const [keyHint, setKeyHint] = React.useState("");
|
||||
const [rps, setRps] = React.useState("0");
|
||||
const [rpm, setRpm] = React.useState("0");
|
||||
const [cw, setCw] = React.useState("0"); // 上下文窗口(K tokens);0=默认200K
|
||||
const [thinkMode, setThinkMode] = React.useState<ThinkMode>("none");
|
||||
const [effort, setEffort] = React.useState("high");
|
||||
const [testing, setTesting] = React.useState(false);
|
||||
|
||||
const load = React.useCallback(async () => {
|
||||
try {
|
||||
const ps = await api.llmProfiles();
|
||||
setProfiles(ps);
|
||||
setSelectedId((prev) => {
|
||||
if (prev && ps.some((p) => p.id === prev)) return prev;
|
||||
return ps.find((p) => p.is_default)?.id ?? ps[0]?.id ?? null;
|
||||
});
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}, []);
|
||||
React.useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
// Fill the editor from the selected profile. Runs only on explicit reloads /
|
||||
// selection changes (this page does not poll), so it never clobbers edits.
|
||||
const selected = React.useMemo(() => profiles.find((p) => p.id === selectedId) ?? null, [profiles, selectedId]);
|
||||
React.useEffect(() => {
|
||||
if (!selected) return;
|
||||
setName(selected.name);
|
||||
setFormat(selected.format === "anthropic" ? "anthropic" : "openai");
|
||||
setModel(selected.model);
|
||||
setBaseUrl(selected.base_url ?? "");
|
||||
setProxy(selected.proxy ?? "");
|
||||
setRps(String(selected.rate_per_second ?? 0));
|
||||
setRpm(String(selected.rate_per_minute ?? 0));
|
||||
setCw(String(selected.context_window_k ?? 0));
|
||||
setThinkMode(modeFromStore(selected.reasoning_effort));
|
||||
setEffort(effortFromStore(selected.reasoning_effort));
|
||||
setApiKey("");
|
||||
setKeyHint(selected.api_key_hint ?? "");
|
||||
}, [selected]);
|
||||
|
||||
async function testConnection() {
|
||||
if (testing) return;
|
||||
setTesting(true);
|
||||
try {
|
||||
// test with the SAME thinking params the profile will run with, so an
|
||||
// unsupported reasoning field fails here instead of only at run time.
|
||||
// 传当前选中 profile 的 id:输入框留空时,后端用该 profile 已存的 key 测试。
|
||||
const r = await api.testLLM(
|
||||
format,
|
||||
model,
|
||||
baseUrl,
|
||||
apiKey,
|
||||
proxy,
|
||||
toStore(thinkMode, effort),
|
||||
selectedId ? Number(selectedId) : undefined,
|
||||
);
|
||||
if (r.ok) toast.success(`连接成功 · ${r.latency_ms ?? "?"}ms · ${r.model ?? model}`);
|
||||
else toast.error(`连接失败:${r.error ?? "未知"}`);
|
||||
} catch (e) {
|
||||
toast.error(`测试出错:${(e as Error).message}`);
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!selectedId) {
|
||||
toast.error("请先在左侧选择或新建一个 Profile");
|
||||
return;
|
||||
}
|
||||
if (!name.trim() || !model.trim()) {
|
||||
toast.error("请填写名称与模型");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await api.saveLLMProfile({
|
||||
id: Number(selectedId),
|
||||
name: name.trim(),
|
||||
format,
|
||||
model: model.trim(),
|
||||
base_url: baseUrl.trim(),
|
||||
proxy: proxy.trim(),
|
||||
api_key: apiKey,
|
||||
rate_per_second: Number(rps) || 0,
|
||||
rate_per_minute: Number(rpm) || 0,
|
||||
context_window_k: Number(cw) || 0,
|
||||
reasoning_effort: toStore(thinkMode, effort),
|
||||
});
|
||||
toast.success(selected?.is_default ? "已保存,激活配置即时生效,无需重启" : "已保存");
|
||||
setApiKey("");
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.error(`保存失败:${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function activate(id: string) {
|
||||
try {
|
||||
await api.activateLLMProfile(id);
|
||||
const p = profiles.find((x) => x.id === id);
|
||||
toast.success(`已激活 Profile:${p?.name ?? id}`);
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.error(`激活失败:${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(p: LLMProfile) {
|
||||
if (p.is_default) {
|
||||
toast.error("无法删除当前激活的 Profile");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await api.deleteLLMProfile(p.id);
|
||||
toast.success(`已删除 Profile:${p.name}`);
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.error(`删除失败:${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col gap-4 md:gap-6">
|
||||
<div>
|
||||
<h1 className="font-semibold text-xl tracking-tight">LLM</h1>
|
||||
<p className="text-muted-foreground text-sm">全 Agent 共享的格式 / 模型 / 限速配置</p>
|
||||
</div>
|
||||
<div className="flex flex-1 flex-col gap-4 md:gap-6">
|
||||
<div className="grid grid-cols-1 gap-4 md:gap-6 lg:grid-cols-3">
|
||||
<Card className="lg:order-2 lg:col-span-2">
|
||||
<CardHeader>
|
||||
<CardTitle>
|
||||
{selected ? (
|
||||
<span className="flex items-center gap-2">
|
||||
编辑 Profile:{selected.name}
|
||||
{selected.is_default && (
|
||||
<Badge variant="outline" className="border-amber-400/50 text-amber-500">
|
||||
激活中
|
||||
</Badge>
|
||||
)}
|
||||
</span>
|
||||
) : (
|
||||
"格式配置"
|
||||
)}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{selected
|
||||
? "修改后点击「保存」。若为激活 Profile,保存后对全部 Agent 立即生效。"
|
||||
: "从左侧选择一个 Profile 进行编辑,或点击「新建」。"}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
{selected ? (
|
||||
<CardContent className="grid gap-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="name">名称</Label>
|
||||
<Input
|
||||
id="name"
|
||||
placeholder="Profile 名称"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label>格式</Label>
|
||||
<Select value={format} onValueChange={(v) => setFormat(v as "anthropic" | "openai")}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="选择格式" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="anthropic">Anthropic</SelectItem>
|
||||
<SelectItem value="openai">OpenAI</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="model">模型</Label>
|
||||
<Input
|
||||
id="model"
|
||||
className="font-mono"
|
||||
placeholder="claude-opus-4-8"
|
||||
value={model}
|
||||
onChange={(e) => setModel(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="base-url">Base URL(可选)</Label>
|
||||
<Input
|
||||
id="base-url"
|
||||
className="font-mono"
|
||||
placeholder="https://api.openai.com/v1"
|
||||
value={baseUrl}
|
||||
onChange={(e) => setBaseUrl(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="proxy">代理(可选)</Label>
|
||||
<Input
|
||||
id="proxy"
|
||||
className="font-mono"
|
||||
placeholder="http://127.0.0.1:8080 · socks5://127.0.0.1:1080"
|
||||
value={proxy}
|
||||
onChange={(e) => setProxy(e.target.value)}
|
||||
/>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
仅 LLM 出站请求走此代理,支持 http/https/socks5;留空则用环境变量(HTTP_PROXY/HTTPS_PROXY)。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="api-key">API Key</Label>
|
||||
<Input
|
||||
id="api-key"
|
||||
type="password"
|
||||
placeholder={keyHint ? `已设置(${keyHint}),留空保持不变` : "sk-…"}
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="rps">每秒限速</Label>
|
||||
<Input id="rps" type="number" min={0} value={rps} onChange={(e) => setRps(e.target.value)} />
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="rpm">每分钟限速</Label>
|
||||
<Input id="rpm" type="number" min={0} value={rpm} onChange={(e) => setRpm(e.target.value)} />
|
||||
<p className="text-muted-foreground text-xs">0 = 不限</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cw">上下文窗口(K tokens)</Label>
|
||||
<Input
|
||||
id="cw"
|
||||
type="number"
|
||||
min={0}
|
||||
max={1000}
|
||||
value={cw}
|
||||
onChange={(e) => setCw(e.target.value)}
|
||||
placeholder="200"
|
||||
/>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
模型上下文窗口,用于压缩阈值。单位 K(千 token);0/留空 = 默认 200K;上限 1000(即
|
||||
1M)。设太高会导致压缩不触发。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 rounded-lg border p-3">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="grid gap-0.5">
|
||||
<Label className="text-sm">思考模式 · Extended Thinking</Label>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
不发送=不带思考字段(兼容 MiniMax 等不支持该字段的模型);显式关闭=发 disabled(默认开思考的模型才需要);开启=先推理再作答。
|
||||
</p>
|
||||
</div>
|
||||
<Select value={thinkMode} onValueChange={(v) => setThinkMode(v as ThinkMode)}>
|
||||
<SelectTrigger className="w-32 shrink-0">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{THINK_MODES.map((o) => (
|
||||
<SelectItem key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{thinkMode === "on" && (
|
||||
<div className="flex items-center justify-between gap-4 border-t pt-3">
|
||||
<div className="grid gap-0.5">
|
||||
<Label className="text-sm">思考强度</Label>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
推理投入档位,越高越深入(OpenAI reasoning_effort / Anthropic output_config.effort)。
|
||||
</p>
|
||||
</div>
|
||||
<Select value={effort} onValueChange={setEffort}>
|
||||
<SelectTrigger className="w-28 shrink-0">
|
||||
<SelectValue placeholder="强度" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{EFFORT_LEVELS.map((o) => (
|
||||
<SelectItem key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button variant="outline" onClick={testConnection} disabled={testing}>
|
||||
{testing ? <Loader2Icon className="animate-spin" /> : <PlugZapIcon />}
|
||||
{testing ? "测试中…" : "测试连接"}
|
||||
</Button>
|
||||
<Button onClick={save}>
|
||||
<SaveIcon /> 保存
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
) : (
|
||||
<CardContent>
|
||||
<div className="flex items-center justify-center rounded-lg border border-dashed py-16 text-muted-foreground text-sm">
|
||||
还没有 Profile,点击左侧「新建」创建第一个。
|
||||
</div>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card className="lg:order-1">
|
||||
<CardHeader className="has-data-[slot=card-action]:grid-cols-[1fr_auto]">
|
||||
<CardTitle>Profiles</CardTitle>
|
||||
<CardDescription>点击选中以编辑;全 Agent 用同一激活 Profile,限速全局共享。</CardDescription>
|
||||
<CardAction className="self-center">
|
||||
<NewProfileDialog
|
||||
onCreated={(id) => {
|
||||
setSelectedId(id);
|
||||
void load();
|
||||
}}
|
||||
/>
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-3">
|
||||
{profiles.map((p) => (
|
||||
// biome-ignore lint/a11y/useSemanticElements: row wraps its own action buttons, so a native <button> would nest buttons (invalid HTML)
|
||||
<div
|
||||
key={p.id}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => setSelectedId(p.id)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
setSelectedId(p.id);
|
||||
}
|
||||
}}
|
||||
aria-pressed={p.id === selectedId}
|
||||
className={cn(
|
||||
"cursor-pointer rounded-lg border p-3 text-left outline-none transition-colors",
|
||||
p.is_default && "border-amber-400/50 bg-amber-400/5",
|
||||
p.id === selectedId ? "ring-2 ring-primary" : "hover:border-foreground/30",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<StarIcon
|
||||
className={cn(
|
||||
"mt-0.5 size-4 shrink-0",
|
||||
p.is_default ? "fill-amber-400 text-amber-400" : "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate font-medium text-sm">{p.name}</span>
|
||||
<Badge variant="outline" className="uppercase">
|
||||
{p.format}
|
||||
</Badge>
|
||||
</div>
|
||||
<code className="mt-1 block truncate font-mono text-muted-foreground text-xs">{p.model}</code>
|
||||
<div className="mt-1 flex flex-wrap gap-x-3 gap-y-0.5 text-muted-foreground text-xs">
|
||||
<span>{p.api_key_hint}</span>
|
||||
<span>
|
||||
{p.rate_per_second}/s · {p.rate_per_minute}/min
|
||||
</span>
|
||||
{p.proxy && <span className="truncate">代理 {p.proxy}</span>}
|
||||
{p.reasoning_effort && (
|
||||
<span>思考 {p.reasoning_effort === "off" ? "关" : p.reasoning_effort}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="flex-1"
|
||||
disabled={p.is_default}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
void activate(p.id);
|
||||
}}
|
||||
>
|
||||
{p.is_default ? "已激活" : "设为激活"}
|
||||
</Button>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="outline"
|
||||
aria-label="删除 Profile"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
void remove(p);
|
||||
}}
|
||||
>
|
||||
<Trash2Icon className="text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{profiles.length === 0 && (
|
||||
<div className="rounded-lg border border-dashed p-6 text-center text-muted-foreground text-sm">
|
||||
暂无 Profile
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { sseUrl } from "@/lib/api";
|
||||
import { MOCK } from "@/lib/mock/enabled";
|
||||
import type { LogLine } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// Mock demo:无后端 SSE,塞几行示例日志。
|
||||
const MOCK_LOGS: LogLine[] = [
|
||||
{ seq: 1, ts: "2026-07-26T03:55:00Z", level: "info", tag: "engine", text: "ARTEX v0.1.0 backend listening on :8787 (workers=3)" },
|
||||
{ seq: 2, ts: "2026-07-26T03:55:01Z", level: "info", tag: "config", text: "LLM configured from DB: anthropic / claude-opus-4-8" },
|
||||
{ seq: 3, ts: "2026-07-26T03:56:10Z", level: "info", tag: "planner", text: "task t-acme-web: 第 3 轮规划,生成意图 i-4" },
|
||||
{ seq: 4, ts: "2026-07-26T03:57:00Z", level: "warn", tag: "guard", text: "block bash: 目标越界 out.evil.example 不在 scope 内" },
|
||||
{ seq: 5, ts: "2026-07-26T03:57:30Z", level: "info", tag: "work#1", text: "report_finding: Default Credentials (high) 已落库" },
|
||||
{ seq: 6, ts: "2026-07-26T03:58:20Z", level: "error", tag: "work#3", text: "intercept: mysqldump 命中破坏性规则,等待人工审批" },
|
||||
];
|
||||
|
||||
const levelTone: Record<LogLine["level"], string> = {
|
||||
info: "text-foreground/80",
|
||||
warn: "text-amber-600 dark:text-amber-400",
|
||||
error: "text-red-600 dark:text-red-400",
|
||||
};
|
||||
const levelDot: Record<LogLine["level"], string> = {
|
||||
info: "bg-muted-foreground/40",
|
||||
warn: "bg-amber-500",
|
||||
error: "bg-red-500",
|
||||
};
|
||||
|
||||
function fmtTime(ts: string) {
|
||||
const d = new Date(ts);
|
||||
return isNaN(d.getTime()) ? "" : d.toLocaleTimeString("zh-CN", { hour12: false });
|
||||
}
|
||||
|
||||
export default function LogsPage() {
|
||||
const [lines, setLines] = React.useState<LogLine[]>([]);
|
||||
const [q, setQ] = React.useState("");
|
||||
const [level, setLevel] = React.useState<"all" | LogLine["level"]>("all");
|
||||
const [paused, setPaused] = React.useState(false);
|
||||
const [loadingHistory, setLoadingHistory] = React.useState(false);
|
||||
const [hasMore, setHasMore] = React.useState(false);
|
||||
const bottom = React.useRef<HTMLDivElement>(null);
|
||||
const stick = React.useRef(true);
|
||||
const pausedRef = React.useRef(false);
|
||||
pausedRef.current = paused;
|
||||
|
||||
// Minimum db_id seen — used as the cursor for loading older history.
|
||||
const minDbId = React.useMemo(() => {
|
||||
let min = 0;
|
||||
for (const l of lines) {
|
||||
if (l.db_id && (min === 0 || l.db_id < min)) min = l.db_id;
|
||||
}
|
||||
return min;
|
||||
}, [lines]);
|
||||
|
||||
// Live tail via SSE. on connect, replays whatever is in the ring (includes
|
||||
// DB-restored history from the last 100 rows written before restart).
|
||||
React.useEffect(() => {
|
||||
if (MOCK) {
|
||||
setLines(MOCK_LOGS);
|
||||
return;
|
||||
}
|
||||
const es = new EventSource(sseUrl("/api/logs/stream?since=0"));
|
||||
es.onmessage = (e) => {
|
||||
if (pausedRef.current) return;
|
||||
try {
|
||||
const l = JSON.parse(e.data) as LogLine;
|
||||
setLines((prev) => (prev.some((x) => x.seq === l.seq) ? prev : [...prev, l].slice(-3000)));
|
||||
} catch {
|
||||
/* ignore malformed frame */
|
||||
}
|
||||
};
|
||||
return () => es.close();
|
||||
}, []);
|
||||
|
||||
// Mark "has more" once we have any db_id in view.
|
||||
React.useEffect(() => {
|
||||
if (minDbId > 1) setHasMore(true);
|
||||
}, [minDbId]);
|
||||
|
||||
async function loadOlderHistory() {
|
||||
if (loadingHistory) return;
|
||||
setLoadingHistory(true);
|
||||
try {
|
||||
const params = minDbId > 0 ? `?before=${minDbId}&limit=200` : `?limit=200`;
|
||||
const res = await fetch(`/api/logs/history${params}`);
|
||||
if (!res.ok) return;
|
||||
const data = await res.json() as { items: LogLine[]; has_more: boolean };
|
||||
if (data.items?.length) {
|
||||
// Assign synthetic seq numbers below current minimum to keep dedup working.
|
||||
setLines((prev) => {
|
||||
const minSeq = prev.reduce((m, l) => Math.min(m, l.seq ?? 0), 0);
|
||||
const older = data.items.map((l, i) => ({
|
||||
...l,
|
||||
seq: minSeq - data.items.length + i,
|
||||
}));
|
||||
// Prepend, dedup by db_id, cap at 5000.
|
||||
const merged = [...older, ...prev];
|
||||
const seen = new Set<number>();
|
||||
const deduped = merged.filter((l) => {
|
||||
if (!l.db_id) return true;
|
||||
if (seen.has(l.db_id)) return false;
|
||||
seen.add(l.db_id);
|
||||
return true;
|
||||
});
|
||||
return deduped.slice(-5000);
|
||||
});
|
||||
}
|
||||
setHasMore(data.has_more ?? false);
|
||||
} finally {
|
||||
setLoadingHistory(false);
|
||||
}
|
||||
}
|
||||
|
||||
const filtered = React.useMemo(() => {
|
||||
const needle = q.trim().toLowerCase();
|
||||
return lines.filter(
|
||||
(l) =>
|
||||
(level === "all" || l.level === level) &&
|
||||
(!needle || l.text.toLowerCase().includes(needle) || l.tag.toLowerCase().includes(needle)),
|
||||
);
|
||||
}, [lines, q, level]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (stick.current && !paused) bottom.current?.scrollIntoView();
|
||||
}, [filtered, paused]);
|
||||
|
||||
const counts = React.useMemo(() => {
|
||||
let warn = 0,
|
||||
error = 0;
|
||||
for (const l of lines) {
|
||||
if (l.level === "warn") warn++;
|
||||
else if (l.level === "error") error++;
|
||||
}
|
||||
return { warn, error, total: lines.length };
|
||||
}, [lines]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col gap-3">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">系统日志</h1>
|
||||
<p className="text-muted-foreground text-sm">后端实时日志流(planner / worker / 数据库 / 流量 …)</p>
|
||||
</div>
|
||||
<div className="flex flex-1 flex-col gap-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Input
|
||||
placeholder="过滤(文本 / tag)…"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
className="h-8 max-w-xs"
|
||||
/>
|
||||
<div className="flex gap-1">
|
||||
{(["all", "info", "warn", "error"] as const).map((lv) => (
|
||||
<Button
|
||||
key={lv}
|
||||
size="sm"
|
||||
variant={level === lv ? "default" : "outline"}
|
||||
className="h-8"
|
||||
onClick={() => setLevel(lv)}
|
||||
>
|
||||
{lv === "all" ? "全部" : lv}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant={paused ? "default" : "outline"}
|
||||
className="h-8"
|
||||
onClick={() => setPaused((p) => !p)}
|
||||
>
|
||||
{paused ? "已暂停" : "暂停"}
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" className="h-8" onClick={() => setLines([])}>
|
||||
清空
|
||||
</Button>
|
||||
<span className="ml-auto text-xs text-muted-foreground">
|
||||
{counts.total} 行 ·{" "}
|
||||
<span className="text-amber-600 dark:text-amber-400">{counts.warn} 警告</span> ·{" "}
|
||||
<span className="text-red-600 dark:text-red-400">{counts.error} 错误</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
onScroll={(e) => {
|
||||
const el = e.currentTarget;
|
||||
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
|
||||
}}
|
||||
className="h-[calc(100vh-14rem)] overflow-auto rounded-lg border bg-card p-2 font-mono text-xs leading-relaxed"
|
||||
>
|
||||
{hasMore && (
|
||||
<div className="flex justify-center py-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 text-xs"
|
||||
disabled={loadingHistory}
|
||||
onClick={loadOlderHistory}
|
||||
>
|
||||
{loadingHistory ? "加载中…" : "加载更早日志"}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{filtered.length === 0 ? (
|
||||
<p className="py-10 text-center text-muted-foreground">暂无日志。</p>
|
||||
) : (
|
||||
filtered.map((l) => {
|
||||
const body =
|
||||
l.tag && l.text.startsWith("[" + l.tag + "]")
|
||||
? l.text.slice(l.tag.length + 2).trimStart()
|
||||
: l.text;
|
||||
return (
|
||||
<div key={l.seq} className="flex items-start gap-2 px-1 py-0.5 hover:bg-muted/40">
|
||||
<span className={cn("mt-1.5 size-1.5 shrink-0 rounded-full", levelDot[l.level])} />
|
||||
<span className="shrink-0 tabular-nums text-muted-foreground">{fmtTime(l.ts)}</span>
|
||||
{l.tag && (
|
||||
<span className="shrink-0 rounded bg-muted px-1 text-[10px] text-foreground/70">{l.tag}</span>
|
||||
)}
|
||||
<span className={cn("min-w-0 whitespace-pre-wrap break-words", levelTone[l.level])}>{body}</span>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
<div ref={bottom} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { toast } from "sonner";
|
||||
import { PlusIcon, RefreshCwIcon, ServerIcon, Trash2Icon } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
} from "@/components/ui/sheet";
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
|
||||
import { api } from "@/lib/api";
|
||||
import type { MCPServer, MCPTool, Agent } from "@/lib/types";
|
||||
|
||||
type Transport = "stdio" | "http";
|
||||
type FormState = {
|
||||
name: string;
|
||||
transport: Transport;
|
||||
command: string;
|
||||
args: string;
|
||||
url: string;
|
||||
env: string;
|
||||
};
|
||||
const emptyForm: FormState = {
|
||||
name: "",
|
||||
transport: "stdio",
|
||||
command: "",
|
||||
args: "",
|
||||
url: "",
|
||||
env: "",
|
||||
};
|
||||
|
||||
export default function MCPPage() {
|
||||
const [servers, setServers] = React.useState<MCPServer[]>([]);
|
||||
const [agents, setAgents] = React.useState<Agent[]>([]);
|
||||
const [visibility, setVisibility] = React.useState<Record<number, string[]>>({});
|
||||
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [editing, setEditing] = React.useState<MCPServer | null>(null); // null = add mode
|
||||
const [tab, setTab] = React.useState<"config" | "tools">("config");
|
||||
const [form, setForm] = React.useState<FormState>(emptyForm);
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
const [tools, setTools] = React.useState<MCPTool[]>([]);
|
||||
const [toolsLoading, setToolsLoading] = React.useState(false);
|
||||
const [refreshing, setRefreshing] = React.useState(false);
|
||||
|
||||
const load = React.useCallback(() => {
|
||||
api.agents().then(setAgents).catch(() => {});
|
||||
api
|
||||
.mcpServers()
|
||||
.then((ss) => {
|
||||
setServers(ss);
|
||||
ss.forEach((s) =>
|
||||
api
|
||||
.resourceVisibility("mcp", s.id)
|
||||
.then((ids) => setVisibility((v) => ({ ...v, [s.id]: ids })))
|
||||
.catch(() => {}),
|
||||
);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
React.useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
function setF(patch: Partial<FormState>) {
|
||||
setForm((f) => ({ ...f, ...patch }));
|
||||
}
|
||||
|
||||
function parseEnv(text: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const line of text.split("\n")) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
const idx = trimmed.indexOf("=");
|
||||
if (idx > 0) out[trimmed.slice(0, idx)] = trimmed.slice(idx + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function envToText(env: Record<string, string> | undefined): string {
|
||||
return Object.entries(env ?? {})
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
function openAdd() {
|
||||
setEditing(null);
|
||||
setForm(emptyForm);
|
||||
setTools([]);
|
||||
setTab("config");
|
||||
setOpen(true);
|
||||
}
|
||||
|
||||
function openEdit(s: MCPServer) {
|
||||
setEditing(s);
|
||||
setForm({
|
||||
name: s.name,
|
||||
transport: s.transport,
|
||||
command: s.command ?? "",
|
||||
args: (s.args ?? []).join(" "),
|
||||
url: s.url ?? "",
|
||||
env: envToText(s.env),
|
||||
});
|
||||
setTab("config");
|
||||
setOpen(true);
|
||||
loadTools(s.id);
|
||||
}
|
||||
|
||||
async function loadTools(id: number) {
|
||||
setToolsLoading(true);
|
||||
try {
|
||||
setTools(await api.mcpTools(id));
|
||||
} catch {
|
||||
setTools([]);
|
||||
} finally {
|
||||
setToolsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveForm() {
|
||||
if (!form.name.trim()) {
|
||||
toast.error("请填写名称");
|
||||
return;
|
||||
}
|
||||
if (form.transport === "stdio" && !form.command.trim()) {
|
||||
toast.error("请填写命令");
|
||||
return;
|
||||
}
|
||||
if (form.transport === "http" && !form.url.trim()) {
|
||||
toast.error("请填写远程 URL");
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const base =
|
||||
form.transport === "http"
|
||||
? {
|
||||
transport: "http" as const,
|
||||
url: form.url.trim(),
|
||||
command: "",
|
||||
args: [] as string[],
|
||||
env: parseEnv(form.env), // 远程模式下 env 即请求头
|
||||
}
|
||||
: {
|
||||
transport: "stdio" as const,
|
||||
command: form.command.trim(),
|
||||
args: form.args.trim() ? form.args.trim().split(/\s+/) : [],
|
||||
env: parseEnv(form.env),
|
||||
};
|
||||
await api.saveMcpServer({
|
||||
...(editing ? { id: editing.id } : {}),
|
||||
name: form.name.trim(),
|
||||
enabled: editing ? editing.enabled : true,
|
||||
...base,
|
||||
});
|
||||
toast.success(editing ? "已保存" : "已添加 MCP 服务器");
|
||||
if (!editing) setOpen(false);
|
||||
load();
|
||||
} catch (e) {
|
||||
toast.error("保存失败:" + (e as Error).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshTools() {
|
||||
if (!editing) return;
|
||||
setRefreshing(true);
|
||||
try {
|
||||
const t = await api.refreshMcpServer(editing.id);
|
||||
setTools(t);
|
||||
toast.success(`发现 ${t.length} 个工具`);
|
||||
load();
|
||||
} catch (e) {
|
||||
toast.error("刷新失败:" + (e as Error).message);
|
||||
} finally {
|
||||
setRefreshing(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeServer(s: MCPServer) {
|
||||
try {
|
||||
await api.deleteMcpServer(s.id);
|
||||
toast.success(`已删除:${s.name}`);
|
||||
setOpen(false);
|
||||
load();
|
||||
} catch (e) {
|
||||
toast.error("删除失败:" + (e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleEnabled(s: MCPServer) {
|
||||
try {
|
||||
await api.saveMcpServer({ ...s, enabled: !s.enabled });
|
||||
load();
|
||||
} catch (e) {
|
||||
toast.error("操作失败:" + (e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleVisibility(serverId: number, agentId: string, agentName: string) {
|
||||
const on = (visibility[serverId] ?? []).includes(agentId);
|
||||
try {
|
||||
await api.toggleVisibility(agentId, "mcp", serverId, !on);
|
||||
toast.success(`${on ? "取消" : "授予"}「${agentName}」可见`);
|
||||
load();
|
||||
} catch (e) {
|
||||
toast.error("操作失败:" + (e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
function renderForm() {
|
||||
return (
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label>传输方式</Label>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant={form.transport === "stdio" ? "default" : "outline"}
|
||||
onClick={() => setF({ transport: "stdio" })}
|
||||
>
|
||||
stdio(本地)
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={form.transport === "http" ? "default" : "outline"}
|
||||
onClick={() => setF({ transport: "http" })}
|
||||
>
|
||||
http(远程)
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="m-name">名称</Label>
|
||||
<Input
|
||||
id="m-name"
|
||||
placeholder="filesystem"
|
||||
value={form.name}
|
||||
onChange={(e) => setF({ name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
{form.transport === "stdio" ? (
|
||||
<>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="m-cmd">命令</Label>
|
||||
<Input
|
||||
id="m-cmd"
|
||||
className="font-mono"
|
||||
placeholder="npx"
|
||||
value={form.command}
|
||||
onChange={(e) => setF({ command: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="m-args">参数(空格分隔)</Label>
|
||||
<Input
|
||||
id="m-args"
|
||||
className="font-mono"
|
||||
placeholder="-y @modelcontextprotocol/server-filesystem /data"
|
||||
value={form.args}
|
||||
onChange={(e) => setF({ args: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="m-url">远程 URL</Label>
|
||||
<Input
|
||||
id="m-url"
|
||||
className="font-mono"
|
||||
placeholder="https://mcp.example.com/mcp"
|
||||
value={form.url}
|
||||
onChange={(e) => setF({ url: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="m-env">
|
||||
{form.transport === "http"
|
||||
? "请求头(每行 KEY=VALUE,如 Authorization=Bearer xxx)"
|
||||
: "环境变量(每行 KEY=VALUE)"}
|
||||
</Label>
|
||||
<Textarea
|
||||
id="m-env"
|
||||
className="font-mono"
|
||||
placeholder={
|
||||
form.transport === "http" ? "Authorization=Bearer xxxx" : "API_KEY=xxxx\nFOO=bar"
|
||||
}
|
||||
value={form.env}
|
||||
onChange={(e) => setF({ env: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function renderTools() {
|
||||
return (
|
||||
<div className="flex flex-col gap-3 py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground text-sm">{tools.length} 个工具</span>
|
||||
<Button size="sm" variant="outline" disabled={refreshing} onClick={refreshTools}>
|
||||
<RefreshCwIcon className={refreshing ? "animate-spin" : ""} /> 刷新
|
||||
</Button>
|
||||
</div>
|
||||
{toolsLoading ? (
|
||||
<p className="text-muted-foreground text-sm">加载中…</p>
|
||||
) : tools.length === 0 ? (
|
||||
<p className="text-muted-foreground text-sm">尚未发现工具,点击刷新重新获取。</p>
|
||||
) : (
|
||||
<div className="flex flex-col divide-y">
|
||||
{tools.map((t) => (
|
||||
<div key={t.name} className="py-2.5">
|
||||
<code className="font-mono text-sm">{t.name}</code>
|
||||
{t.description && (
|
||||
<p className="text-muted-foreground mt-0.5 text-xs leading-relaxed">
|
||||
{t.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col gap-4 md:gap-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">MCP</h1>
|
||||
<p className="text-muted-foreground text-sm">外部 MCP 工具服务器 · 按 Agent 授权可见</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={openAdd}
|
||||
className="text-foreground/70 border-foreground/70 hover:bg-muted/60 hover:shadow-sm flex min-h-[116px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed transition"
|
||||
>
|
||||
<PlusIcon className="size-6" />
|
||||
<span className="text-sm">添加 MCP</span>
|
||||
</button>
|
||||
|
||||
{servers.map((s) => (
|
||||
<Card
|
||||
key={s.id}
|
||||
onClick={() => openEdit(s)}
|
||||
className="hover:border-primary/60 cursor-pointer gap-3 transition hover:shadow-sm"
|
||||
>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<ServerIcon className="text-muted-foreground size-4 shrink-0" />
|
||||
<CardTitle className="truncate text-base">{s.name}</CardTitle>
|
||||
<Badge variant="outline" className="uppercase">
|
||||
{s.transport}
|
||||
</Badge>
|
||||
<div className="ml-auto flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
|
||||
<Switch
|
||||
checked={s.enabled}
|
||||
onCheckedChange={() => toggleEnabled(s)}
|
||||
aria-label="启用"
|
||||
/>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="outline"
|
||||
aria-label="删除"
|
||||
onClick={() => removeServer(s)}
|
||||
>
|
||||
<Trash2Icon className="text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-3">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{s.tools && s.tools.length > 0 ? `${s.tools.length} 个工具` : "尚未发现工具"}
|
||||
</p>
|
||||
<div className="grid gap-2" onClick={(e) => e.stopPropagation()}>
|
||||
<span className="text-muted-foreground text-xs">可见性(按 Agent 授权)</span>
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-2">
|
||||
{agents.map((a) => (
|
||||
<label key={a.key} className="flex items-center gap-2 text-sm">
|
||||
<Checkbox
|
||||
checked={(visibility[s.id] ?? []).includes(a.id)}
|
||||
onCheckedChange={() => toggleVisibility(s.id, a.id, a.name)}
|
||||
/>
|
||||
{a.name}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="w-full data-[side=right]:sm:max-w-lg"
|
||||
>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{editing ? editing.name : "添加 MCP 服务器"}</SheetTitle>
|
||||
<SheetDescription>
|
||||
stdio(本地起进程)或 http(远程 Streamable HTTP)
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
{editing ? (
|
||||
<Tabs
|
||||
value={tab}
|
||||
onValueChange={(v) => setTab(v as "config" | "tools")}
|
||||
className="flex min-h-0 flex-1 flex-col px-4"
|
||||
>
|
||||
<TabsList>
|
||||
<TabsTrigger value="config">配置</TabsTrigger>
|
||||
<TabsTrigger value="tools">
|
||||
工具列表{tools.length ? `(${tools.length})` : ""}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="config" className="min-h-0 flex-1 overflow-y-auto">
|
||||
{renderForm()}
|
||||
<div className="flex gap-2 pt-2 pb-6">
|
||||
<Button onClick={saveForm} disabled={saving}>
|
||||
保存
|
||||
</Button>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="tools" className="min-h-0 flex-1 overflow-y-auto">
|
||||
{renderTools()}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
) : (
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-4">
|
||||
{renderForm()}
|
||||
<div className="pt-2 pb-6">
|
||||
<Button onClick={saveForm} disabled={saving}>
|
||||
<PlusIcon /> 添加
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import { CpuIcon, RadioTowerIcon, SearchIcon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { api } from "@/lib/api";
|
||||
import type { Settings } from "@/lib/types";
|
||||
|
||||
export default function SystemSettingsPage() {
|
||||
const [trafficCapture, setTrafficCapture] = React.useState(false);
|
||||
const [webSearch, setWebSearch] = React.useState(false);
|
||||
const [backend, setBackend] = React.useState("ddgs");
|
||||
const [braveKeySet, setBraveKeySet] = React.useState(false);
|
||||
const [braveKeyInput, setBraveKeyInput] = React.useState("");
|
||||
const [tavilyKeySet, setTavilyKeySet] = React.useState(false);
|
||||
const [tavilyKeyInput, setTavilyKeyInput] = React.useState("");
|
||||
const [savingTavilyKey, setSavingTavilyKey] = React.useState(false);
|
||||
const [proxyInput, setProxyInput] = React.useState("");
|
||||
const [savingProxy, setSavingProxy] = React.useState(false);
|
||||
const [testing, setTesting] = React.useState(false);
|
||||
const [loaded, setLoaded] = React.useState(false);
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
const [savingKey, setSavingKey] = React.useState(false);
|
||||
const [pyInterp, setPyInterp] = React.useState("");
|
||||
const [workers, setWorkers] = React.useState("3");
|
||||
const [savingWorkers, setSavingWorkers] = React.useState(false);
|
||||
|
||||
const apply = React.useCallback((s: Settings) => {
|
||||
setTrafficCapture(!!s.traffic_capture);
|
||||
setWebSearch(!!s.web_search_enabled);
|
||||
setBackend(s.web_search_backend || "ddgs");
|
||||
setBraveKeySet(!!s.brave_key_set);
|
||||
setTavilyKeySet(!!s.tavily_key_set);
|
||||
setProxyInput(s.web_search_proxy || "");
|
||||
setPyInterp(s.python_interpreter || "");
|
||||
setWorkers(String(s.workers ?? 3));
|
||||
}, []);
|
||||
|
||||
const saveWorkers = () => {
|
||||
const n = Number(workers);
|
||||
if (!Number.isInteger(n) || n <= 0) {
|
||||
toast.error("并发数必须是大于 0 的整数");
|
||||
return;
|
||||
}
|
||||
setSavingWorkers(true);
|
||||
api
|
||||
.setSettings({ workers: n })
|
||||
.then((s) => {
|
||||
apply(s);
|
||||
toast.success("已保存并发工作 agent 数(对之后启动的任务生效)");
|
||||
})
|
||||
.catch((e) => toast.error("保存失败:" + (e as Error).message))
|
||||
.finally(() => setSavingWorkers(false));
|
||||
};
|
||||
|
||||
const savePython = () => {
|
||||
setSaving(true);
|
||||
api
|
||||
.setSettings({ python_interpreter: pyInterp.trim() })
|
||||
.then((s) => {
|
||||
apply(s);
|
||||
toast.success("已保存 Python 解释器配置");
|
||||
})
|
||||
.catch((e) => toast.error("保存失败:" + (e as Error).message))
|
||||
.finally(() => setSaving(false));
|
||||
};
|
||||
const detectPython = () => {
|
||||
setSaving(true);
|
||||
api.detectPython().then((r) => setPyInterp(r.python_interpreter)).catch(() => undefined).finally(() => setSaving(false));
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
api
|
||||
.settings()
|
||||
.then(apply)
|
||||
.catch(() => undefined)
|
||||
.finally(() => setLoaded(true));
|
||||
}, [apply]);
|
||||
|
||||
const toggleTraffic = (v: boolean) => {
|
||||
setTrafficCapture(v); // optimistic
|
||||
setSaving(true);
|
||||
api
|
||||
.setSettings({ traffic_capture: v })
|
||||
.then(apply)
|
||||
.catch(() => setTrafficCapture(!v)) // revert on failure
|
||||
.finally(() => setSaving(false));
|
||||
};
|
||||
|
||||
// Persist a web-search patch (enable and/or backend). Optimistic with refetch.
|
||||
const saveWebSearch = (patch: Partial<Settings>) => {
|
||||
setSaving(true);
|
||||
api
|
||||
.setSettings(patch)
|
||||
.then((s) => {
|
||||
apply(s);
|
||||
toast.success("已保存网络搜索配置");
|
||||
})
|
||||
.catch((e) => {
|
||||
toast.error("保存失败:" + (e as Error).message);
|
||||
api
|
||||
.settings()
|
||||
.then(apply)
|
||||
.catch(() => undefined);
|
||||
})
|
||||
.finally(() => setSaving(false));
|
||||
};
|
||||
|
||||
const saveBraveKey = () => {
|
||||
setSavingKey(true);
|
||||
api
|
||||
.setSettings({ brave_search_api_key: braveKeyInput })
|
||||
.then((s) => {
|
||||
apply(s);
|
||||
setBraveKeyInput("");
|
||||
toast.success("已保存 Brave API Key");
|
||||
})
|
||||
.catch((e) => toast.error("保存失败:" + (e as Error).message))
|
||||
.finally(() => setSavingKey(false));
|
||||
};
|
||||
|
||||
const saveTavilyKey = () => {
|
||||
setSavingTavilyKey(true);
|
||||
api
|
||||
.setSettings({ tavily_search_api_key: tavilyKeyInput })
|
||||
.then((s) => {
|
||||
apply(s);
|
||||
setTavilyKeyInput("");
|
||||
toast.success("已保存 Tavily API Key");
|
||||
})
|
||||
.catch((e) => toast.error("保存失败:" + (e as Error).message))
|
||||
.finally(() => setSavingTavilyKey(false));
|
||||
};
|
||||
|
||||
const saveProxy = () => {
|
||||
setSavingProxy(true);
|
||||
api
|
||||
.setSettings({ web_search_proxy: proxyInput.trim() })
|
||||
.then((s) => {
|
||||
apply(s);
|
||||
toast.success(proxyInput.trim() ? "已保存出口代理" : "已清除出口代理(改为直连)");
|
||||
})
|
||||
.catch((e) => toast.error("保存失败:" + (e as Error).message))
|
||||
.finally(() => setSavingProxy(false));
|
||||
};
|
||||
|
||||
// Run a real "test" search ("test") against the CURRENT form values (backend +
|
||||
// proxy + entered key), falling back to saved values server-side. Toasts result.
|
||||
const runTest = () => {
|
||||
setTesting(true);
|
||||
api
|
||||
.testWebSearch({
|
||||
web_search_backend: backend,
|
||||
web_search_proxy: proxyInput.trim(),
|
||||
brave_search_api_key: braveKeyInput,
|
||||
tavily_search_api_key: tavilyKeyInput,
|
||||
})
|
||||
.then((r) => {
|
||||
if (r.ok) toast.success(`搜索测试成功 · ${r.backend} 返回 ${r.count} 条结果`);
|
||||
else toast.error("搜索测试失败:" + (r.error || "未知错误"));
|
||||
})
|
||||
.catch((e) => toast.error("搜索测试失败:" + (e as Error).message))
|
||||
.finally(() => setTesting(false));
|
||||
};
|
||||
|
||||
// brave-free selected but no key stored and none being entered → tool stays off.
|
||||
const braveNeedsKey = webSearch && backend === "brave-free" && !braveKeySet;
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col gap-4 md:gap-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">系统配置</h1>
|
||||
<p className="text-muted-foreground text-sm">全局运行时开关</p>
|
||||
</div>
|
||||
|
||||
<Card className="max-w-2xl">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<RadioTowerIcon className="size-4" />
|
||||
流量捕获
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
开启后,所有 Agent 的 HTTP 流量经记录代理全量落库,并向 Agent 注入 traffic_search / traffic_get
|
||||
工具与代理配置(提示词含代理说明)。
|
||||
<br />
|
||||
关闭(默认)时不记录任何流量:Agent
|
||||
<b>不会</b>拿到代理配置与流量工具,提示词也<b>不含</b>代理相关内容。切换后会即时重建 Agent 生效。
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex items-center justify-between gap-4">
|
||||
<Label htmlFor="traffic-capture" className="text-sm font-normal text-muted-foreground">
|
||||
{trafficCapture ? "已开启 · 正在记录流量并注入代理" : "已关闭 · 不记录、不注入代理"}
|
||||
</Label>
|
||||
<Switch
|
||||
id="traffic-capture"
|
||||
checked={trafficCapture}
|
||||
disabled={!loaded || saving}
|
||||
onCheckedChange={toggleTraffic}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="max-w-2xl">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<SearchIcon className="size-4" />
|
||||
网络搜索
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
这是网络搜索的<b>总开关 + 来源配置</b>。开启后,才能在<b>每个 Agent 的配置</b>里单独选择是否启用
|
||||
<b>web_search</b>(仅返回标题/链接/摘要,不抓取正文;抓取由 WebFetch 负责)。网络搜索<b>不走</b>记录代理,独立于流量捕获。
|
||||
<br />
|
||||
来源可选 <b>DuckDuckGo(ddgs)</b>(无需 Key)、<b>Brave(免费版)</b>(需填写 Brave API Key)或 <b>Tavily</b>(需填写 Tavily API Key)。总开关关闭时,各 Agent 的网络搜索开关不可用。
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<Label htmlFor="web-search" className="text-sm font-normal text-muted-foreground">
|
||||
{webSearch ? "总开关已开启 · 可在各 Agent 配置里单独启用" : "已关闭 · 各 Agent 无法启用网络搜索"}
|
||||
</Label>
|
||||
<Switch
|
||||
id="web-search"
|
||||
checked={webSearch}
|
||||
disabled={!loaded || saving}
|
||||
onCheckedChange={(v) => {
|
||||
setWebSearch(v); // optimistic
|
||||
saveWebSearch({ web_search_enabled: v });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{webSearch && (
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<Label className="text-sm font-normal text-muted-foreground">搜索来源</Label>
|
||||
<Select
|
||||
value={backend}
|
||||
disabled={!loaded || saving}
|
||||
onValueChange={(v) => {
|
||||
setBackend(v); // optimistic
|
||||
saveWebSearch({ web_search_backend: v });
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-48 shrink-0">
|
||||
<SelectValue placeholder="选择来源" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="ddgs">DuckDuckGo(ddgs · 免费无 Key)</SelectItem>
|
||||
<SelectItem value="brave-free">Brave(免费版 · 需 Key)</SelectItem>
|
||||
<SelectItem value="tavily">Tavily(需 Key)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{webSearch && backend === "brave-free" && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="brave-key" className="text-sm font-normal text-muted-foreground">
|
||||
Brave Search API Key
|
||||
{braveKeySet && <span className="ml-2 text-xs text-emerald-500">已配置</span>}
|
||||
</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
id="brave-key"
|
||||
type="password"
|
||||
autoComplete="off"
|
||||
placeholder={braveKeySet ? "已配置(留空则不变)" : "输入 Brave API Key"}
|
||||
value={braveKeyInput}
|
||||
disabled={!loaded || savingKey}
|
||||
onChange={(e) => setBraveKeyInput(e.target.value)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={saveBraveKey}
|
||||
disabled={!loaded || savingKey || braveKeyInput.trim() === ""}
|
||||
>
|
||||
保存
|
||||
</Button>
|
||||
</div>
|
||||
{braveNeedsKey && (
|
||||
<p className="text-xs text-amber-500">
|
||||
已选择 Brave 但尚未配置 Key —— 在保存 Key 之前,搜索工具不会启用。
|
||||
</p>
|
||||
)}
|
||||
<p className="text-muted-foreground text-xs">
|
||||
免费版额度约 2,000 次/月。前往 https://brave.com/search/api/ 获取 Key。
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{webSearch && backend === "tavily" && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="tavily-key" className="text-sm font-normal text-muted-foreground">
|
||||
Tavily Search API Key
|
||||
{tavilyKeySet && <span className="ml-2 text-xs text-emerald-500">已配置</span>}
|
||||
</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
id="tavily-key"
|
||||
type="password"
|
||||
autoComplete="off"
|
||||
placeholder={tavilyKeySet ? "已配置(留空则不变)" : "输入 Tavily API Key(tvly-…)"}
|
||||
value={tavilyKeyInput}
|
||||
disabled={!loaded || savingTavilyKey}
|
||||
onChange={(e) => setTavilyKeyInput(e.target.value)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={saveTavilyKey}
|
||||
disabled={!loaded || savingTavilyKey || tavilyKeyInput.trim() === ""}
|
||||
>
|
||||
保存
|
||||
</Button>
|
||||
</div>
|
||||
{webSearch && backend === "tavily" && !tavilyKeySet && (
|
||||
<p className="text-xs text-amber-500">
|
||||
已选择 Tavily 但尚未配置 Key —— 在保存 Key 之前,搜索工具不会启用。
|
||||
</p>
|
||||
)}
|
||||
<p className="text-muted-foreground text-xs">
|
||||
前往 https://tavily.com 注册并获取 API Key。
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{webSearch && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="ws-proxy" className="text-sm font-normal text-muted-foreground">
|
||||
出口代理(可选)
|
||||
</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
id="ws-proxy"
|
||||
autoComplete="off"
|
||||
placeholder="http://host:port 或 socks5://host:port(留空=直连)"
|
||||
value={proxyInput}
|
||||
disabled={!loaded || savingProxy}
|
||||
onChange={(e) => setProxyInput(e.target.value)}
|
||||
/>
|
||||
<Button type="button" onClick={saveProxy} disabled={!loaded || savingProxy}>
|
||||
保存
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
独立出口代理,仅用于访问搜索端点(VPN/SOCKS 等)。与记录流量的 MITM 代理无关;网络不通时经此代理访问。
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{webSearch && (
|
||||
<div className="flex items-center justify-between gap-4 border-t pt-4">
|
||||
<p className="text-muted-foreground text-xs">
|
||||
用当前配置(来源 + 代理 + Key)实际搜索一次「test」,验证是否可用。
|
||||
</p>
|
||||
<Button type="button" variant="outline" onClick={runTest} disabled={!loaded || testing} className="shrink-0">
|
||||
{testing ? "测试中…" : "测试搜索"}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="max-w-2xl">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<RadioTowerIcon className="size-4" />
|
||||
自定义脚本 · Python 解释器
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
自定义 <b>script</b> 类型工具用它跑 Python。开机会自动检测(python3 优先);此处可手填 venv /
|
||||
特定版本的绝对路径,留空则运行时自动检测。
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
className="font-mono text-sm"
|
||||
placeholder="/usr/bin/python3(留空=自动检测)"
|
||||
value={pyInterp}
|
||||
disabled={!loaded || saving}
|
||||
onChange={(e) => setPyInterp(e.target.value)}
|
||||
/>
|
||||
<Button variant="outline" onClick={detectPython} disabled={!loaded || saving}>
|
||||
重新检测
|
||||
</Button>
|
||||
<Button onClick={savePython} disabled={!loaded || saving}>
|
||||
保存
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="max-w-2xl">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<CpuIcon className="size-4" />
|
||||
工作并发 · Work Agent 数
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
每个任务并发运行的工作 agent 数量(默认 3)。数值越大并发探测越多、消耗也越高。修改后<b>对之后启动的任务生效</b>,正在运行的任务不受影响。
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
className="w-32 font-mono text-sm"
|
||||
placeholder="3"
|
||||
value={workers}
|
||||
disabled={!loaded || savingWorkers}
|
||||
onChange={(e) => setWorkers(e.target.value)}
|
||||
/>
|
||||
<Button onClick={saveWorkers} disabled={!loaded || savingWorkers}>
|
||||
保存
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,764 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
ChevronRightIcon,
|
||||
FolderIcon,
|
||||
FolderOpenIcon,
|
||||
FolderPlusIcon,
|
||||
FileTextIcon,
|
||||
FilePlusIcon,
|
||||
PlusIcon,
|
||||
Trash2Icon,
|
||||
UploadIcon,
|
||||
} from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { api } from "@/lib/api";
|
||||
import type { Agent, SkillItem, MCPServer } from "@/lib/types";
|
||||
|
||||
// ── Tree node ──────────────────────────────────────────────────────────────
|
||||
interface TreeNode {
|
||||
name: string;
|
||||
path: string; // relative to skill root, dirs WITHOUT trailing slash
|
||||
type: "file" | "dir";
|
||||
children: TreeNode[];
|
||||
}
|
||||
|
||||
// Backend returns dirs as "scripts/" (trailing slash) and files as "scripts/a.py".
|
||||
function buildTree(entries: string[]): TreeNode[] {
|
||||
const root: TreeNode[] = [];
|
||||
const dirMap = new Map<string, TreeNode>();
|
||||
|
||||
function ensureDir(dirPath: string, parentNodes: TreeNode[]): TreeNode[] {
|
||||
if (dirMap.has(dirPath)) return dirMap.get(dirPath)!.children;
|
||||
const parts = dirPath.split("/");
|
||||
let nodes = root;
|
||||
let cur = "";
|
||||
for (const part of parts) {
|
||||
cur = cur ? `${cur}/${part}` : part;
|
||||
if (!dirMap.has(cur)) {
|
||||
const d: TreeNode = { name: part, path: cur, type: "dir", children: [] };
|
||||
nodes.push(d);
|
||||
dirMap.set(cur, d);
|
||||
}
|
||||
nodes = dirMap.get(cur)!.children;
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
for (const entry of [...entries].sort()) {
|
||||
if (entry.endsWith("/")) {
|
||||
// Explicit directory entry — ensure the node exists (may already be created)
|
||||
ensureDir(entry.slice(0, -1), root);
|
||||
} else {
|
||||
// File — ensure parent dirs exist, then push file node
|
||||
const parts = entry.split("/");
|
||||
let nodes = root;
|
||||
let cur = "";
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
cur = cur ? `${cur}/${parts[i]}` : parts[i];
|
||||
if (!dirMap.has(cur)) {
|
||||
const d: TreeNode = { name: parts[i], path: cur, type: "dir", children: [] };
|
||||
nodes.push(d);
|
||||
dirMap.set(cur, d);
|
||||
}
|
||||
nodes = dirMap.get(cur)!.children;
|
||||
}
|
||||
const fname = parts[parts.length - 1];
|
||||
if (fname) nodes.push({ name: fname, path: entry, type: "file", children: [] });
|
||||
}
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
// ── State types ───────────────────────────────────────────────────────────
|
||||
type Selected =
|
||||
| { skill: string; path: null }
|
||||
| { skill: string; path: string };
|
||||
|
||||
type Creating = {
|
||||
skill: string;
|
||||
inDir: string;
|
||||
kind: "file" | "dir";
|
||||
} | null;
|
||||
|
||||
// ── Page ──────────────────────────────────────────────────────────────────
|
||||
export default function SkillsPage() {
|
||||
const [skills, setSkills] = React.useState<SkillItem[]>([]);
|
||||
const [agents, setAgents] = React.useState<Agent[]>([]);
|
||||
const [selected, setSelected] = React.useState<Selected | null>(null);
|
||||
const [visibility, setVisibility] = React.useState<Record<string, string[]>>({});
|
||||
const [expanded, setExpanded] = React.useState<Set<string>>(new Set());
|
||||
|
||||
// file editor
|
||||
const [fileContent, setFileContent] = React.useState("");
|
||||
const [fileLoading, setFileLoading] = React.useState(false);
|
||||
const [dirty, setDirty] = React.useState(false);
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
|
||||
// inline create — using a ref to avoid stale closure in onBlur
|
||||
const [creating, setCreating] = React.useState<Creating>(null);
|
||||
const [newEntryName, setNewEntryName] = React.useState("");
|
||||
const inlineRef = React.useRef<HTMLInputElement>(null);
|
||||
// cancelRef prevents onBlur from committing when Escape was pressed
|
||||
const cancelRef = React.useRef(false);
|
||||
|
||||
// new skill dialog
|
||||
const [newOpen, setNewOpen] = React.useState(false);
|
||||
const [newName, setNewName] = React.useState("");
|
||||
const [newDesc, setNewDesc] = React.useState("");
|
||||
const [newLicense, setNewLicense] = React.useState("");
|
||||
const [newCompat, setNewCompat] = React.useState("");
|
||||
const [newInst, setNewInst] = React.useState("");
|
||||
const [newMcps, setNewMcps] = React.useState<string[]>([]);
|
||||
const [newVisibility, setNewVisibility] = React.useState<string[]>([]);
|
||||
const [mcpOptions, setMcpOptions] = React.useState<MCPServer[]>([]);
|
||||
const [creatingSkill, setCreatingSkill] = React.useState(false);
|
||||
const [uploading, setUploading] = React.useState(false);
|
||||
const uploadRef = React.useRef<HTMLInputElement>(null);
|
||||
|
||||
// skill detail — MCP edit state (optimistic, rolls back on error)
|
||||
const [detailMcps, setDetailMcps] = React.useState<string[]>([]);
|
||||
|
||||
// ── Data ──────────────────────────────────────────────────────────────────
|
||||
const load = React.useCallback(() => {
|
||||
api.agents().then(setAgents).catch(() => {});
|
||||
api.mcpServers().then(setMcpOptions).catch(() => {});
|
||||
api.skills().then((ss) => {
|
||||
setSkills(ss);
|
||||
ss.forEach((s) =>
|
||||
api.skillVisibility(s.name)
|
||||
.then((ids) => setVisibility((v) => ({ ...v, [s.name]: ids })))
|
||||
.catch(() => {}),
|
||||
);
|
||||
}).catch(() => {});
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => { load(); }, [load]);
|
||||
|
||||
// ── Upload a .zip skill ───────────────────────────────────────────────────
|
||||
async function uploadZip(file: File, overwrite = false) {
|
||||
setUploading(true);
|
||||
try {
|
||||
const r = await api.uploadSkill(file, overwrite);
|
||||
toast.success(`已安装 Skill:${r.name}(${r.files} 个文件)`);
|
||||
load();
|
||||
} catch (e) {
|
||||
const msg = (e as Error).message;
|
||||
// offer overwrite when the skill already exists
|
||||
if (!overwrite && msg.includes("已存在")) {
|
||||
if (window.confirm(`${msg}\n\n是否覆盖同名 Skill?`)) {
|
||||
await uploadZip(file, true);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
toast.error("上传失败:" + msg);
|
||||
}
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
function onUploadPick(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const f = e.target.files?.[0];
|
||||
e.target.value = ""; // reset so picking the same file again re-fires
|
||||
if (f) uploadZip(f);
|
||||
}
|
||||
|
||||
React.useEffect(() => {
|
||||
if (creating) {
|
||||
// Small timeout so the element is actually in the DOM before focusing
|
||||
setTimeout(() => inlineRef.current?.focus(), 20);
|
||||
}
|
||||
}, [creating]);
|
||||
|
||||
// Sync detail-panel MCP state when the selected skill changes.
|
||||
React.useEffect(() => {
|
||||
if (!selected || selected.path !== null) return;
|
||||
const sk = skills.find((s) => s.name === selected.skill);
|
||||
setDetailMcps(sk?.mcps ?? []);
|
||||
}, [selected, skills]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!selected || selected.path === null) { setFileContent(""); setDirty(false); return; }
|
||||
setFileLoading(true);
|
||||
api.readSkillFile(selected.skill, selected.path)
|
||||
.then((c) => { setFileContent(c); setDirty(false); })
|
||||
.catch(() => toast.error("读取文件失败"))
|
||||
.finally(() => setFileLoading(false));
|
||||
}, [selected]);
|
||||
|
||||
// ── Expand helpers ────────────────────────────────────────────────────────
|
||||
function toggleExpanded(key: string) {
|
||||
setExpanded((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(key)) next.delete(key); else next.add(key);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
function ensureExpanded(skill: string, dirPath: string) {
|
||||
setExpanded((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.add(skill);
|
||||
if (dirPath) {
|
||||
let cur = "";
|
||||
for (const part of dirPath.split("/")) {
|
||||
cur = cur ? `${cur}/${part}` : part;
|
||||
next.add(`${skill}:${cur}`);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
// ── Inline create ─────────────────────────────────────────────────────────
|
||||
function startCreate(skill: string, inDir: string, kind: "file" | "dir") {
|
||||
cancelRef.current = false;
|
||||
ensureExpanded(skill, inDir);
|
||||
setCreating({ skill, inDir, kind });
|
||||
setNewEntryName("");
|
||||
}
|
||||
|
||||
// Use a ref snapshot so commitCreate reads the latest creating value
|
||||
// without depending on potentially stale closure state.
|
||||
const creatingRef = React.useRef<Creating>(null);
|
||||
React.useEffect(() => { creatingRef.current = creating; }, [creating]);
|
||||
const newEntryRef = React.useRef("");
|
||||
React.useEffect(() => { newEntryRef.current = newEntryName; }, [newEntryName]);
|
||||
|
||||
async function commitCreate() {
|
||||
if (cancelRef.current) { cancelRef.current = false; return; }
|
||||
const c = creatingRef.current;
|
||||
const name = newEntryRef.current.trim();
|
||||
setCreating(null);
|
||||
setNewEntryName("");
|
||||
if (!c || !name) return;
|
||||
|
||||
const fullPath = c.inDir ? `${c.inDir}/${name}` : name;
|
||||
try {
|
||||
if (c.kind === "dir") {
|
||||
await api.createSkillDir(c.skill, fullPath);
|
||||
toast.success(`已创建文件夹:${fullPath}`);
|
||||
ensureExpanded(c.skill, fullPath);
|
||||
} else {
|
||||
await api.writeSkillFile(c.skill, fullPath, "");
|
||||
toast.success(`已创建文件:${fullPath}`);
|
||||
setSelected({ skill: c.skill, path: fullPath });
|
||||
ensureExpanded(c.skill, c.inDir);
|
||||
}
|
||||
load();
|
||||
} catch (e) {
|
||||
toast.error("创建失败:" + (e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
function cancelCreate() {
|
||||
cancelRef.current = true;
|
||||
setCreating(null);
|
||||
setNewEntryName("");
|
||||
}
|
||||
|
||||
async function deletePath(skill: string, path: string) {
|
||||
try {
|
||||
await api.deleteSkillPath(skill, path);
|
||||
toast.success(`已删除:${path}`);
|
||||
if (selected?.skill === skill && selected.path === path) setSelected(null);
|
||||
load();
|
||||
} catch (e) {
|
||||
toast.error("删除失败:" + (e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSkill(name: string) {
|
||||
try {
|
||||
await api.deleteSkill(name);
|
||||
toast.success(`已删除 Skill:${name}`);
|
||||
if (selected?.skill === name) setSelected(null);
|
||||
load();
|
||||
} catch (e) {
|
||||
toast.error("删除失败:" + (e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveFile() {
|
||||
if (!selected || selected.path === null) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
await api.writeSkillFile(selected.skill, selected.path, fileContent);
|
||||
toast.success("已保存");
|
||||
setDirty(false);
|
||||
} catch (e) {
|
||||
toast.error("保存失败:" + (e as Error).message);
|
||||
} finally { setSaving(false); }
|
||||
}
|
||||
|
||||
async function toggleSkillMcp(skillName: string, mcpName: string, mcpOn: boolean) {
|
||||
const next = mcpOn
|
||||
? [...detailMcps, mcpName]
|
||||
: detailMcps.filter((n) => n !== mcpName);
|
||||
setDetailMcps(next);
|
||||
try {
|
||||
await api.updateSkillMeta(skillName, { mcps: next });
|
||||
toast.success(`${mcpOn ? "关联" : "取消关联"}「${mcpName}」`);
|
||||
load();
|
||||
} catch (e) {
|
||||
// roll back on error
|
||||
setDetailMcps(detailMcps);
|
||||
toast.error("操作失败:" + (e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleVisibility(skillName: string, agentId: string, agentName: string) {
|
||||
const on = (visibility[skillName] ?? []).includes(agentId);
|
||||
try {
|
||||
await api.toggleSkillVisibility(agentId, skillName, !on);
|
||||
toast.success(`${on ? "取消" : "授予"}「${agentName}」可见`);
|
||||
const ids = await api.skillVisibility(skillName);
|
||||
setVisibility((v) => ({ ...v, [skillName]: ids }));
|
||||
} catch (e) {
|
||||
toast.error("操作失败:" + (e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
async function createNewSkill() {
|
||||
if (!newName.trim()) { toast.error("请填写 name"); return; }
|
||||
if (!newDesc.trim()) { toast.error("description 为必填项"); return; }
|
||||
setCreatingSkill(true);
|
||||
try {
|
||||
const name = newName.trim();
|
||||
await api.createSkill({
|
||||
name, description: newDesc.trim(),
|
||||
license: newLicense.trim() || undefined,
|
||||
compatibility: newCompat.trim() || undefined,
|
||||
mcps: newMcps.length ? newMcps : undefined,
|
||||
instructions: newInst.trim() || undefined,
|
||||
});
|
||||
// apply initial visibility (fire-and-forget per agent; best-effort)
|
||||
await Promise.all(newVisibility.map((id) => api.toggleSkillVisibility(id, name, true)));
|
||||
toast.success("已创建 Skill");
|
||||
setNewOpen(false);
|
||||
setNewName(""); setNewDesc(""); setNewLicense(""); setNewCompat(""); setNewInst("");
|
||||
setNewMcps([]); setNewVisibility([]);
|
||||
load();
|
||||
} catch (e) {
|
||||
toast.error("创建失败:" + (e as Error).message);
|
||||
} finally { setCreatingSkill(false); }
|
||||
}
|
||||
|
||||
// ── Inline input JSX helper (NOT a React component — avoids remount on re-render) ──
|
||||
// Defined as a plain function returning JSX so React never sees a new component type.
|
||||
function inlineInputJSX(indent: number) {
|
||||
return (
|
||||
<div
|
||||
key="__inline_create__"
|
||||
className="flex items-center gap-1 py-0.5 pr-2"
|
||||
style={{ paddingLeft: indent }}
|
||||
>
|
||||
{creating?.kind === "dir"
|
||||
? <FolderIcon className="size-3.5 shrink-0 text-amber-500" />
|
||||
: <FileTextIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
}
|
||||
<Input
|
||||
ref={inlineRef}
|
||||
className="h-6 flex-1 px-1 py-0 font-mono text-xs"
|
||||
placeholder={creating?.kind === "dir" ? "folder-name" : "filename.py"}
|
||||
value={newEntryName}
|
||||
onChange={(e) => setNewEntryName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") { cancelRef.current = false; void commitCreate(); }
|
||||
if (e.key === "Escape") cancelCreate();
|
||||
}}
|
||||
onBlur={() => { void commitCreate(); }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Recursive tree renderer ───────────────────────────────────────────────
|
||||
function renderTree(nodes: TreeNode[], skill: string, depth: number): React.ReactNode {
|
||||
const baseIndent = 8 + depth * 14;
|
||||
return nodes.map((node) => {
|
||||
if (node.type === "dir") {
|
||||
const key = `${skill}:${node.path}`;
|
||||
const open = expanded.has(key);
|
||||
return (
|
||||
<div key={node.path}>
|
||||
<div
|
||||
className="group flex cursor-pointer select-none items-center gap-1 rounded py-0.5 pr-1 text-sm hover:bg-muted"
|
||||
style={{ paddingLeft: baseIndent }}
|
||||
onClick={() => toggleExpanded(key)}
|
||||
>
|
||||
<ChevronRightIcon className={cn("size-3.5 shrink-0 transition-transform", open && "rotate-90")} />
|
||||
{open
|
||||
? <FolderOpenIcon className="size-3.5 shrink-0 text-amber-500" />
|
||||
: <FolderIcon className="size-3.5 shrink-0 text-amber-500" />
|
||||
}
|
||||
<span className="flex-1 truncate">{node.name}</span>
|
||||
<span className="ml-auto hidden shrink-0 items-center gap-0.5 group-hover:flex">
|
||||
<Button size="icon" variant="ghost" className="size-5" title="新建文件"
|
||||
onClick={(e) => { e.stopPropagation(); startCreate(skill, node.path, "file"); }}>
|
||||
<FilePlusIcon className="size-3 text-muted-foreground" />
|
||||
</Button>
|
||||
<Button size="icon" variant="ghost" className="size-5" title="新建文件夹"
|
||||
onClick={(e) => { e.stopPropagation(); startCreate(skill, node.path, "dir"); }}>
|
||||
<FolderPlusIcon className="size-3 text-muted-foreground" />
|
||||
</Button>
|
||||
<Button size="icon" variant="ghost" className="size-5" title="删除文件夹"
|
||||
onClick={(e) => { e.stopPropagation(); deletePath(skill, node.path); }}>
|
||||
<Trash2Icon className="size-3 text-destructive" />
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
{open && (
|
||||
<>
|
||||
{renderTree(node.children, skill, depth + 1)}
|
||||
{creating?.skill === skill && creating.inDir === node.path &&
|
||||
inlineInputJSX(baseIndent + 14)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// file node
|
||||
const isSelected = selected?.skill === skill && selected.path === node.path;
|
||||
return (
|
||||
<div
|
||||
key={node.path}
|
||||
className={cn(
|
||||
"group flex cursor-pointer select-none items-center gap-1 rounded py-0.5 pr-1 text-sm",
|
||||
isSelected ? "bg-accent text-accent-foreground" : "hover:bg-muted",
|
||||
)}
|
||||
style={{ paddingLeft: baseIndent + 16 }}
|
||||
onClick={() => setSelected({ skill, path: node.path })}
|
||||
>
|
||||
<FileTextIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span className="flex-1 truncate font-mono text-xs">{node.name}</span>
|
||||
<Button size="icon" variant="ghost" className="ml-auto hidden size-5 group-hover:flex"
|
||||
title="删除文件"
|
||||
onClick={(e) => { e.stopPropagation(); deletePath(skill, node.path); }}>
|
||||
<Trash2Icon className="size-3 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const selectedSkill = selected
|
||||
? skills.find((s) => s.name === selected.skill) ?? null
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div data-content-padding="false" className="flex flex-1 flex-col overflow-hidden">
|
||||
<div className="flex flex-col gap-0.5 border-b px-4 py-2.5 lg:px-6">
|
||||
<h1 className="text-sm font-semibold leading-tight">Skill</h1>
|
||||
<p className="text-muted-foreground text-xs">技能库 · agentskills.io 规范 · 按 Agent 授权可见</p>
|
||||
</div>
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
{/* ── 左侧文件树 ── */}
|
||||
<div className="flex w-64 shrink-0 flex-col border-r">
|
||||
<div className="flex flex-col gap-2 border-b p-2">
|
||||
<Button size="sm" variant="outline" className="w-full" onClick={() => setNewOpen(true)}>
|
||||
<PlusIcon className="size-3.5" />新建 Skill
|
||||
</Button>
|
||||
<input
|
||||
ref={uploadRef}
|
||||
type="file"
|
||||
accept=".zip,application/zip"
|
||||
className="hidden"
|
||||
onChange={onUploadPick}
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
disabled={uploading}
|
||||
onClick={() => uploadRef.current?.click()}
|
||||
title="上传包含 SKILL.md 的 .zip 压缩包"
|
||||
>
|
||||
<UploadIcon className="size-3.5" />
|
||||
{uploading ? "上传中…" : "上传压缩包"}
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-1">
|
||||
{skills.map((s) => {
|
||||
const isOpen = expanded.has(s.name);
|
||||
const tree = buildTree(s.files);
|
||||
const isSkillSelected = selected?.skill === s.name && selected.path === null;
|
||||
return (
|
||||
<div key={s.name}>
|
||||
{/* skill 根节点 */}
|
||||
<div
|
||||
className={cn(
|
||||
"group flex cursor-pointer select-none items-center gap-1 rounded px-2 py-1 text-sm",
|
||||
isSkillSelected ? "bg-accent text-accent-foreground" : "hover:bg-muted",
|
||||
)}
|
||||
onClick={() => {
|
||||
toggleExpanded(s.name);
|
||||
setSelected({ skill: s.name, path: null });
|
||||
}}
|
||||
>
|
||||
<ChevronRightIcon className={cn("size-3.5 shrink-0 transition-transform", isOpen && "rotate-90")} />
|
||||
{isOpen
|
||||
? <FolderOpenIcon className="size-3.5 shrink-0 text-blue-500" />
|
||||
: <FolderIcon className="size-3.5 shrink-0 text-blue-500" />
|
||||
}
|
||||
<span className="flex-1 truncate font-semibold">{s.name}</span>
|
||||
<span className="ml-auto hidden shrink-0 items-center gap-0.5 group-hover:flex">
|
||||
<Button size="icon" variant="ghost" className="size-5" title="新建文件"
|
||||
onClick={(e) => { e.stopPropagation(); startCreate(s.name, "", "file"); }}>
|
||||
<FilePlusIcon className="size-3 text-muted-foreground" />
|
||||
</Button>
|
||||
<Button size="icon" variant="ghost" className="size-5" title="新建文件夹"
|
||||
onClick={(e) => { e.stopPropagation(); startCreate(s.name, "", "dir"); }}>
|
||||
<FolderPlusIcon className="size-3 text-muted-foreground" />
|
||||
</Button>
|
||||
<Button size="icon" variant="ghost" className="size-5" title="删除 Skill"
|
||||
onClick={(e) => { e.stopPropagation(); deleteSkill(s.name); }}>
|
||||
<Trash2Icon className="size-3 text-destructive" />
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* 展开:递归文件树 */}
|
||||
{isOpen && (
|
||||
<>
|
||||
{renderTree(tree, s.name, 0)}
|
||||
{creating?.skill === s.name && creating.inDir === "" &&
|
||||
inlineInputJSX(22)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{skills.length === 0 && (
|
||||
<p className="p-3 text-xs text-muted-foreground">暂无 Skill,点击「新建」开始</p>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
{/* ── 右侧面板 ── */}
|
||||
<div className="flex flex-1 flex-col overflow-auto p-4">
|
||||
{!selected && (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-sm text-muted-foreground">选择左侧 Skill 或文件</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selected && selected.path === null && selectedSkill && (
|
||||
<div className="max-w-xl space-y-5">
|
||||
<div>
|
||||
<h2 className="font-mono text-base font-semibold">{selectedSkill.name}</h2>
|
||||
{selectedSkill.description && (
|
||||
<p className="mt-1 text-sm text-muted-foreground">{selectedSkill.description}</p>
|
||||
)}
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{selectedSkill.license && (
|
||||
<Badge variant="outline" className="text-xs font-normal">License: {selectedSkill.license}</Badge>
|
||||
)}
|
||||
{selectedSkill.compatibility && (
|
||||
<Badge variant="secondary" className="text-xs font-normal">{selectedSkill.compatibility}</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── 关联 MCP ── */}
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs text-muted-foreground">
|
||||
关联 MCP
|
||||
<span className="ml-1 font-normal">(加载 Skill 时才披露/解锁其工具)</span>
|
||||
</Label>
|
||||
{mcpOptions.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">暂无 MCP,可在「MCP」页添加。</p>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-2">
|
||||
{mcpOptions.map((m) => (
|
||||
<label key={m.id} className="flex cursor-pointer items-center gap-2 text-sm">
|
||||
<Checkbox
|
||||
checked={detailMcps.includes(m.name)}
|
||||
onCheckedChange={(on) => toggleSkillMcp(selectedSkill.name, m.name, !!on)}
|
||||
/>
|
||||
{m.name}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── 可见性 ── */}
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs text-muted-foreground">可见性(按 Agent 授权)</Label>
|
||||
<div className="space-y-2">
|
||||
{agents.map((a) => (
|
||||
<label key={a.key} className="flex cursor-pointer items-center gap-2 text-sm">
|
||||
<Checkbox
|
||||
checked={(visibility[selectedSkill.name] ?? []).includes(a.id)}
|
||||
onCheckedChange={() => toggleVisibility(selectedSkill.name, a.id, a.name)}
|
||||
/>
|
||||
{a.name}
|
||||
</label>
|
||||
))}
|
||||
{agents.length === 0 && (
|
||||
<span className="text-xs text-muted-foreground">(暂无 Agent)</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selected && selected.path !== null && (
|
||||
<div className="flex h-full flex-col gap-2">
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<span className="font-medium text-foreground">{selected.skill}</span>
|
||||
<span>/</span>
|
||||
<span className="font-mono">{selected.path}</span>
|
||||
<Button size="sm" className="ml-auto" onClick={saveFile} disabled={!dirty || saving}>
|
||||
{saving ? "保存中…" : "保存"}
|
||||
</Button>
|
||||
</div>
|
||||
{fileLoading ? (
|
||||
<p className="text-xs text-muted-foreground">加载中…</p>
|
||||
) : (
|
||||
<Textarea
|
||||
className="flex-1 resize-none font-mono text-xs"
|
||||
value={fileContent}
|
||||
onChange={(e) => { setFileContent(e.target.value); setDirty(true); }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── 新建 Skill 对话框 ── */}
|
||||
<Sheet open={newOpen} onOpenChange={setNewOpen}>
|
||||
<SheetContent side="right" className="flex w-full flex-col gap-0 data-[side=right]:sm:max-w-xl">
|
||||
<SheetHeader className="px-4 pt-4">
|
||||
<SheetTitle>新建 Skill</SheetTitle>
|
||||
</SheetHeader>
|
||||
<Tabs defaultValue="basic" className="flex min-h-0 flex-1 flex-col">
|
||||
<TabsList className="mx-4 mt-3 shrink-0 justify-start">
|
||||
<TabsTrigger value="basic">基本信息</TabsTrigger>
|
||||
<TabsTrigger value="mcp">
|
||||
关联 MCP
|
||||
{newMcps.length > 0 && (
|
||||
<span className="ml-1.5 rounded-full bg-primary px-1.5 py-0.5 text-[10px] leading-none text-primary-foreground">
|
||||
{newMcps.length}
|
||||
</span>
|
||||
)}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="visibility">
|
||||
可见性
|
||||
{newVisibility.length > 0 && (
|
||||
<span className="ml-1.5 rounded-full bg-primary px-1.5 py-0.5 text-[10px] leading-none text-primary-foreground">
|
||||
{newVisibility.length}
|
||||
</span>
|
||||
)}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* 基本信息 */}
|
||||
<TabsContent value="basic" className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4 pb-4 pt-4 data-[state=inactive]:hidden">
|
||||
<div className="grid gap-1.5">
|
||||
<Label htmlFor="sk-name">名称 <span className="text-destructive">*</span></Label>
|
||||
<Input id="sk-name" placeholder="sqli-deepdive" value={newName} onChange={(e) => setNewName(e.target.value)} />
|
||||
<p className="text-muted-foreground text-xs">小写字母 / 数字 / 连字符,1–64 字符</p>
|
||||
</div>
|
||||
<div className="grid gap-1.5">
|
||||
<Label htmlFor="sk-desc">描述 <span className="text-destructive">*</span></Label>
|
||||
<Textarea id="sk-desc" rows={2} className="resize-none"
|
||||
placeholder="这个 skill 做什么、何时使用。"
|
||||
value={newDesc} onChange={(e) => setNewDesc(e.target.value)} />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="grid gap-1.5">
|
||||
<Label className="text-muted-foreground text-xs">license</Label>
|
||||
<Input placeholder="MIT / Proprietary" value={newLicense} onChange={(e) => setNewLicense(e.target.value)} />
|
||||
</div>
|
||||
<div className="grid gap-1.5">
|
||||
<Label className="text-muted-foreground text-xs">compatibility</Label>
|
||||
<Input placeholder="需要 sqlmap、python3" value={newCompat} onChange={(e) => setNewCompat(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-1.5">
|
||||
<Label htmlFor="sk-inst">正文 <span className="text-muted-foreground text-xs font-normal">(留空自动生成骨架)</span></Label>
|
||||
<Textarea id="sk-inst"
|
||||
className="min-h-40 flex-1 resize-none font-mono text-sm leading-relaxed"
|
||||
placeholder={"## 执行方法\n\n1. 先探测错误\n2. 区分盲注类型\n\n脚本放 scripts/ 目录。"}
|
||||
value={newInst} onChange={(e) => setNewInst(e.target.value)} />
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
{/* 关联 MCP */}
|
||||
<TabsContent value="mcp" className="overflow-y-auto px-4 pb-4 pt-4 data-[state=inactive]:hidden">
|
||||
<p className="mb-3 text-xs text-muted-foreground">加载 Skill 时才披露并解锁所选 MCP 的工具。</p>
|
||||
{mcpOptions.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">暂无 MCP,可在「MCP」页添加。</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{mcpOptions.map((m) => (
|
||||
<label key={m.id} className="flex cursor-pointer items-center gap-2 text-sm">
|
||||
<Checkbox
|
||||
checked={newMcps.includes(m.name)}
|
||||
onCheckedChange={(on) =>
|
||||
setNewMcps((cur) => on ? [...cur, m.name] : cur.filter((n) => n !== m.name))
|
||||
}
|
||||
/>
|
||||
{m.name}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
{/* 可见性 */}
|
||||
<TabsContent value="visibility" className="overflow-y-auto px-4 pb-4 pt-4 data-[state=inactive]:hidden">
|
||||
<p className="mb-3 text-xs text-muted-foreground">选中的 Agent 创建后即可见此 Skill。</p>
|
||||
{agents.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">(暂无 Agent)</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{agents.map((a) => (
|
||||
<label key={a.key} className="flex cursor-pointer items-center gap-2 text-sm">
|
||||
<Checkbox
|
||||
checked={newVisibility.includes(a.id)}
|
||||
onCheckedChange={(on) =>
|
||||
setNewVisibility((cur) => on ? [...cur, a.id] : cur.filter((id) => id !== a.id))
|
||||
}
|
||||
/>
|
||||
{a.name}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<SheetFooter className="flex-row justify-end gap-2 border-t px-4 py-3">
|
||||
<Button variant="outline" onClick={() => setNewOpen(false)}>取消</Button>
|
||||
<Button onClick={createNewSkill} disabled={creatingSkill}>{creatingSkill ? "创建中…" : "创建"}</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,835 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { toast } from "sonner";
|
||||
import { PlayIcon, PlusIcon, RotateCcwIcon, SaveIcon, SearchIcon, Trash2Icon } from "lucide-react";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import { api } from "@/lib/api";
|
||||
import type { Agent, Tool } from "@/lib/types";
|
||||
|
||||
// Traffic tools are host tools gated by the global 流量捕获 switch: bindable, but
|
||||
// only usable when capture is on. Keep in sync with traffic.SeedToolMetas.
|
||||
const TRAFFIC_TOOL_KEYS = new Set(["traffic_search", "traffic_get"]);
|
||||
|
||||
// paramRows flattens schema.properties into an ordered row list for editing.
|
||||
// name/type/required are read-only (welded to the Go handler); description/default
|
||||
// are editable. Non-scalar params (array/object) can't carry an editable default.
|
||||
// parentKey is set for rows that live inside an array param's items.properties.
|
||||
type ParamRow = {
|
||||
name: string;
|
||||
type: string;
|
||||
required: boolean;
|
||||
description: string;
|
||||
defaultStr: string; // "" = no default declared
|
||||
scalar: boolean;
|
||||
parentKey?: string; // set when this is a sub-field of an array param's items
|
||||
};
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function toRows(schema: Record<string, any>): ParamRow[] {
|
||||
const props = (schema?.properties ?? {}) as Record<string, Record<string, unknown>>;
|
||||
const required = new Set<string>((schema?.required as string[]) ?? []);
|
||||
const rows: ParamRow[] = [];
|
||||
for (const [name, p] of Object.entries(props)) {
|
||||
const type = String(p?.type ?? "");
|
||||
const hasDefault = p != null && "default" in p && (p as Record<string, unknown>).default != null;
|
||||
rows.push({
|
||||
name, type,
|
||||
required: required.has(name),
|
||||
description: String(p?.description ?? ""),
|
||||
defaultStr: hasDefault ? String((p as Record<string, unknown>).default) : "",
|
||||
scalar: ["string", "integer", "number", "boolean"].includes(type),
|
||||
});
|
||||
// Expand items.properties for array params so sub-fields are editable.
|
||||
if (type === "array") {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const itemProps = (p as any)?.items?.properties as Record<string, Record<string, unknown>> | undefined;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const itemRequired = new Set<string>(((p as any)?.items?.required as string[]) ?? []);
|
||||
if (itemProps) {
|
||||
for (const [subName, subP] of Object.entries(itemProps)) {
|
||||
const subType = String((subP as Record<string, unknown>)?.type ?? "");
|
||||
const subHasDefault = subP != null && "default" in subP && subP.default != null;
|
||||
rows.push({
|
||||
name: subName, type: subType,
|
||||
required: itemRequired.has(subName),
|
||||
description: String(subP?.description ?? ""),
|
||||
defaultStr: subHasDefault ? String(subP.default) : "",
|
||||
scalar: ["string", "integer", "number", "boolean"].includes(subType),
|
||||
parentKey: name,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
// coerceDefault turns the edited default string back into a typed JSON value, or
|
||||
// undefined to drop the "default" key entirely.
|
||||
function coerceDefault(type: string, raw: string): unknown {
|
||||
const s = raw.trim();
|
||||
if (s === "") return undefined;
|
||||
if (type === "integer" || type === "number") {
|
||||
const n = Number(s);
|
||||
return Number.isNaN(n) ? undefined : n;
|
||||
}
|
||||
if (type === "boolean") return s === "true";
|
||||
return raw;
|
||||
}
|
||||
|
||||
// applyRows writes edited rows back into a deep-copied schema (structure untouched).
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function applyRows(schema: Record<string, any>, rows: ParamRow[]): Record<string, any> {
|
||||
const next = structuredClone(schema ?? {});
|
||||
const props = (next.properties ?? {}) as Record<string, Record<string, unknown>>;
|
||||
for (const r of rows) {
|
||||
if (r.parentKey) {
|
||||
// Sub-field of an array param's items.properties
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const parent = props[r.parentKey] as any;
|
||||
const subP = parent?.items?.properties?.[r.name] as Record<string, unknown> | undefined;
|
||||
if (!subP) continue;
|
||||
subP.description = r.description;
|
||||
if (r.scalar) {
|
||||
const dv = coerceDefault(r.type, r.defaultStr);
|
||||
if (dv === undefined) delete subP.default;
|
||||
else subP.default = dv;
|
||||
}
|
||||
} else {
|
||||
const p = props[r.name];
|
||||
if (!p) continue;
|
||||
p.description = r.description;
|
||||
if (r.scalar) {
|
||||
const dv = coerceDefault(r.type, r.defaultStr);
|
||||
if (dv === undefined) delete p.default;
|
||||
else p.default = dv;
|
||||
}
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
// ToolEditor is the full edit form for one tool, rendered inside the drawer.
|
||||
function ToolEditor({
|
||||
tool,
|
||||
agents,
|
||||
captureOn,
|
||||
onSaved,
|
||||
onClose,
|
||||
}: {
|
||||
tool: Tool;
|
||||
agents: Agent[];
|
||||
captureOn: boolean;
|
||||
onSaved: () => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
// traffic tools can't be bound/enabled until the global 流量捕获 switch is on.
|
||||
const trafficGated = TRAFFIC_TOOL_KEYS.has(tool.key) && !captureOn;
|
||||
const [description, setDescription] = React.useState(tool.description);
|
||||
const [bound, setBound] = React.useState<string[]>(tool.agents);
|
||||
const [enabled, setEnabled] = React.useState(tool.enabled);
|
||||
const [rows, setRows] = React.useState<ParamRow[]>(() => toRows(tool.schema));
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
|
||||
const setRow = (i: number, patch: Partial<ParamRow>) =>
|
||||
setRows((rs) => rs.map((r, j) => (j === i ? { ...r, ...patch } : r)));
|
||||
const toggleAgent = (k: string) =>
|
||||
setBound((b) => (b.includes(k) ? b.filter((x) => x !== k) : [...b, k]));
|
||||
|
||||
async function save() {
|
||||
setSaving(true);
|
||||
try {
|
||||
await api.saveTool(tool.key, {
|
||||
description,
|
||||
schema: applyRows(tool.schema, rows),
|
||||
agents: bound,
|
||||
enabled,
|
||||
});
|
||||
toast.success(`已保存工具「${tool.key}」`);
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toast.error("保存失败:" + (e as Error).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
async function reset() {
|
||||
try {
|
||||
await api.resetTool(tool.key);
|
||||
toast.success(`已恢复「${tool.key}」为代码默认`);
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toast.error("恢复失败:" + (e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4">
|
||||
{trafficGated && (
|
||||
<div className="border-amber-500/40 bg-amber-500/10 text-muted-foreground rounded-md border px-3 py-2 text-xs">
|
||||
该工具依赖<b>流量捕获</b>。请先在「系统配置」开启流量捕获,才能绑定给 Agent 并启用。
|
||||
</div>
|
||||
)}
|
||||
{/* binding + switch */}
|
||||
<div className="flex flex-wrap items-center gap-x-6 gap-y-3">
|
||||
<div className="grid gap-1.5">
|
||||
<Label className="text-muted-foreground text-xs">绑定 Agent(决定该工具给哪些 Agent)</Label>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{agents.map((ag) => (
|
||||
<label key={ag.key} className="flex items-center gap-2 text-sm">
|
||||
<Checkbox
|
||||
checked={bound.includes(ag.key)}
|
||||
disabled={trafficGated}
|
||||
onCheckedChange={() => toggleAgent(ag.key)}
|
||||
/>
|
||||
{ag.name}
|
||||
<span className="text-muted-foreground font-mono text-xs">{ag.key}</span>
|
||||
</label>
|
||||
))}
|
||||
{agents.length === 0 && <span className="text-muted-foreground text-xs">(无 Agent)</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch checked={enabled} onCheckedChange={setEnabled} id={`en-${tool.key}`} />
|
||||
<Label htmlFor={`en-${tool.key}`} className="text-sm">
|
||||
启用
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* description */}
|
||||
<div className="grid gap-1.5">
|
||||
<Label className="text-muted-foreground text-xs">工具描述(发送给模型)</Label>
|
||||
<Textarea
|
||||
className="font-mono text-xs"
|
||||
rows={6}
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* params */}
|
||||
<div className="grid gap-2">
|
||||
<Label className="text-muted-foreground text-xs">
|
||||
参数(名称 / 类型 / 必填只读;描述与默认值可改)
|
||||
</Label>
|
||||
{rows.length === 0 && <span className="text-muted-foreground text-xs">(无参数)</span>}
|
||||
{rows.map((r, i) => (
|
||||
<div
|
||||
key={(r.parentKey ?? "") + "." + r.name}
|
||||
className={r.parentKey
|
||||
? "border-l-2 border-muted ml-3 pl-3 grid gap-2 py-2"
|
||||
: "grid gap-2 rounded-md border p-3"
|
||||
}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{r.parentKey && <span className="text-muted-foreground font-mono text-[10px]">↳</span>}
|
||||
<span className="font-mono text-sm">{r.name}</span>
|
||||
<Badge variant="secondary" className="px-1.5 py-0 text-[10px]">
|
||||
{r.type || "?"}
|
||||
</Badge>
|
||||
{r.required && (
|
||||
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
|
||||
必填
|
||||
</Badge>
|
||||
)}
|
||||
{r.parentKey && (
|
||||
<span className="text-muted-foreground text-[10px]">items 子字段</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<div className="grid gap-1">
|
||||
<Label className="text-muted-foreground text-[11px]">描述</Label>
|
||||
<Input
|
||||
className="text-xs"
|
||||
value={r.description}
|
||||
onChange={(e) => setRow(i, { description: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-1">
|
||||
<Label className="text-muted-foreground text-[11px]">默认值</Label>
|
||||
<Input
|
||||
className="text-xs"
|
||||
placeholder={r.scalar ? "(空=无默认)" : "仅标量支持"}
|
||||
disabled={!r.scalar}
|
||||
value={r.defaultStr}
|
||||
onChange={(e) => setRow(i, { defaultStr: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator className="mt-4" />
|
||||
<div className="flex flex-wrap gap-2 p-4">
|
||||
<Button size="sm" onClick={save} disabled={saving}>
|
||||
<SaveIcon /> 保存
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={reset}>
|
||||
<RotateCcwIcon /> 恢复默认
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ToolGridCard is one clickable tile in the catalog grid.
|
||||
function ToolGridCard({ tool, onClick }: { tool: Tool; onClick: () => void }) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className="hover:border-primary/50 hover:bg-muted/40 focus-visible:ring-ring flex flex-col gap-2 rounded-lg border p-4 text-left transition-colors focus-visible:ring-2 focus-visible:outline-none"
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-mono text-sm font-medium">{tool.key}</span>
|
||||
{tool.system ? (
|
||||
<Badge variant="secondary" className="px-1.5 py-0 text-[10px]">
|
||||
系统
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
|
||||
自定义·{tool.kind}
|
||||
</Badge>
|
||||
)}
|
||||
{tool.deferred && (
|
||||
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
|
||||
deferred
|
||||
</Badge>
|
||||
)}
|
||||
{!tool.enabled && (
|
||||
<Badge variant="outline" className="text-destructive px-1.5 py-0 text-[10px]">
|
||||
已停用
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-muted-foreground line-clamp-1 h-4 text-xs">
|
||||
{tool.description || "(无描述)"}
|
||||
</p>
|
||||
<div className="mt-auto flex flex-wrap gap-1 pt-1">
|
||||
{tool.agents.length === 0 && (
|
||||
<span className="text-muted-foreground text-[10px]">(未绑定 Agent)</span>
|
||||
)}
|
||||
{tool.agents.map((a) => (
|
||||
<Badge key={a} variant="outline" className="px-1.5 py-0 text-[10px]">
|
||||
{a}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ToolsPage() {
|
||||
const [tools, setTools] = React.useState<Tool[]>([]);
|
||||
const [agents, setAgents] = React.useState<Agent[]>([]);
|
||||
const [captureOn, setCaptureOn] = React.useState(false);
|
||||
const [selectedKey, setSelectedKey] = React.useState<string | null>(null);
|
||||
const [customEdit, setCustomEdit] = React.useState<Tool | "new" | null>(null);
|
||||
|
||||
const reload = React.useCallback(() => {
|
||||
api.tools().then(setTools).catch(() => setTools([]));
|
||||
}, []);
|
||||
React.useEffect(() => {
|
||||
reload();
|
||||
api.agents().then(setAgents).catch(() => {});
|
||||
api.settings().then((s) => setCaptureOn(!!s.traffic_capture)).catch(() => {});
|
||||
}, [reload]);
|
||||
|
||||
const [query, setQuery] = React.useState("");
|
||||
|
||||
const selected = tools.find((t) => t.key === selectedKey) ?? null;
|
||||
const matchTool = React.useCallback((t: Tool) => {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (!q) return true;
|
||||
return (
|
||||
t.key.toLowerCase().includes(q) ||
|
||||
t.description.toLowerCase().includes(q) ||
|
||||
t.agents.some((a) => a.toLowerCase().includes(q))
|
||||
);
|
||||
}, [query]);
|
||||
const systemTools = tools.filter((t) => t.system && matchTool(t));
|
||||
const customTools = tools.filter((t) => !t.system && matchTool(t));
|
||||
const allSystemCount = tools.filter((t) => t.system).length;
|
||||
const allCustomCount = tools.filter((t) => !t.system).length;
|
||||
// clicking a built-in tool opens the binding drawer; a custom tool opens its full editor.
|
||||
const openTool = (t: Tool) => (t.system ? setSelectedKey(t.key) : setCustomEdit(t));
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col gap-4 md:gap-6">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">工具</h1>
|
||||
<p className="text-muted-foreground text-sm">系统工具的描述/绑定,以及自定义工具(command/script/http)</p>
|
||||
</div>
|
||||
<div className="relative w-64">
|
||||
<SearchIcon className="text-muted-foreground absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2" />
|
||||
<Input
|
||||
className="h-8 pl-8 text-sm"
|
||||
placeholder="搜索工具名、描述、Agent…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="system">
|
||||
<TabsList>
|
||||
<TabsTrigger value="system">系统工具</TabsTrigger>
|
||||
<TabsTrigger value="custom">自定义工具</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="system">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>系统工具</CardTitle>
|
||||
<CardDescription>
|
||||
{query.trim()
|
||||
? `${systemTools.length} / ${allSystemCount} 个匹配,点击卡片编辑描述、参数默认值与 Agent 绑定`
|
||||
: `共 ${allSystemCount} 个,点击卡片编辑描述、参数默认值与 Agent 绑定`}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{systemTools.length === 0 ? (
|
||||
<p className="text-muted-foreground py-6 text-center text-sm">
|
||||
{query.trim() ? "没有匹配的系统工具" : "(暂无系统工具,等待后端 seed)"}
|
||||
</p>
|
||||
) : (
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{systemTools.map((t) => (
|
||||
<ToolGridCard key={t.key} tool={t} onClick={() => openTool(t)} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="custom">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<CardTitle>自定义工具</CardTitle>
|
||||
<CardDescription>
|
||||
{query.trim()
|
||||
? `shell/command/script/http,${customTools.length} / ${allCustomCount} 个匹配,点击卡片编辑`
|
||||
: `shell(bash 声明) / command(命令) / script(Python) / http(API),共 ${allCustomCount} 个,点击卡片编辑`}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Button size="sm" onClick={() => setCustomEdit("new")}>
|
||||
<PlusIcon /> 新建自定义工具
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{customTools.length === 0 ? (
|
||||
<p className="text-muted-foreground py-6 text-center text-sm">
|
||||
{query.trim() ? "没有匹配的自定义工具" : "(暂无自定义工具,点击右上角「新建自定义工具」)"}
|
||||
</p>
|
||||
) : (
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{customTools.map((t) => (
|
||||
<ToolGridCard key={t.key} tool={t} onClick={() => openTool(t)} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<Sheet open={!!selected} onOpenChange={(o) => !o && setSelectedKey(null)}>
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="gap-0 p-0 data-[side=right]:w-[30vw] data-[side=right]:sm:max-w-[30vw]"
|
||||
>
|
||||
{selected && (
|
||||
<>
|
||||
<SheetHeader className="px-4">
|
||||
<SheetTitle className="font-mono">{selected.key}</SheetTitle>
|
||||
<SheetDescription>编辑描述、参数默认值与 Agent 绑定</SheetDescription>
|
||||
</SheetHeader>
|
||||
<ToolEditor
|
||||
key={selected.key}
|
||||
tool={selected}
|
||||
agents={agents}
|
||||
captureOn={captureOn}
|
||||
onSaved={reload}
|
||||
onClose={() => setSelectedKey(null)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
<CustomToolDialog
|
||||
edit={customEdit}
|
||||
agents={agents}
|
||||
onClose={() => setCustomEdit(null)}
|
||||
onSaved={() => {
|
||||
setCustomEdit(null);
|
||||
reload();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- 自定义工具编辑器 ----
|
||||
|
||||
type ExecState = {
|
||||
command: string;
|
||||
code: string;
|
||||
method: string;
|
||||
url: string;
|
||||
headers: string;
|
||||
body: string;
|
||||
timeout_ms: string;
|
||||
proxy: string;
|
||||
use_recording_proxy: boolean;
|
||||
};
|
||||
|
||||
function CustomToolDialog({
|
||||
edit,
|
||||
agents,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: {
|
||||
edit: Tool | "new" | null;
|
||||
agents: Agent[];
|
||||
onClose: () => void;
|
||||
onSaved: () => void;
|
||||
}) {
|
||||
const isNew = edit === "new";
|
||||
const tool = edit && edit !== "new" ? edit : null;
|
||||
const [key, setKey] = React.useState("");
|
||||
const [description, setDescription] = React.useState("");
|
||||
const [kind, setKind] = React.useState<"shell" | "command" | "script" | "http">("shell");
|
||||
const [ex, setEx] = React.useState<ExecState>({
|
||||
command: "", code: "", method: "GET", url: "", headers: "", body: "", timeout_ms: "", proxy: "", use_recording_proxy: false,
|
||||
});
|
||||
const [schemaText, setSchemaText] = React.useState("");
|
||||
const [bound, setBound] = React.useState<string[]>([]);
|
||||
const [deferred, setDeferred] = React.useState(false);
|
||||
const [enabled, setEnabled] = React.useState(true);
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
const [paramsText, setParamsText] = React.useState("");
|
||||
const [testing, setTesting] = React.useState(false);
|
||||
const [testResult, setTestResult] = React.useState<{ output: string; is_error: boolean } | null>(null);
|
||||
|
||||
// (re)load form state when opening.
|
||||
React.useEffect(() => {
|
||||
if (!edit) return;
|
||||
setParamsText(""); setTestResult(null);
|
||||
if (edit === "new") {
|
||||
setKey(""); setDescription(""); setKind("shell");
|
||||
setEx({ command: "", code: "", method: "GET", url: "", headers: "", body: "", timeout_ms: "", proxy: "", use_recording_proxy: false });
|
||||
setSchemaText(""); setBound([]); setDeferred(false); setEnabled(true);
|
||||
return;
|
||||
}
|
||||
const t = edit;
|
||||
const e = (t.exec ?? {}) as Record<string, unknown>;
|
||||
setKey(t.key);
|
||||
setDescription(t.description);
|
||||
setKind((t.kind as "shell" | "command" | "script" | "http") ?? "shell");
|
||||
setEx({
|
||||
command: String(e.command ?? ""),
|
||||
code: String(e.code ?? ""),
|
||||
method: String(e.method ?? "GET"),
|
||||
url: String(e.url ?? ""),
|
||||
headers: e.headers ? JSON.stringify(e.headers, null, 2) : "",
|
||||
body: String(e.body ?? ""),
|
||||
timeout_ms: e.timeout_ms ? String(e.timeout_ms) : "",
|
||||
proxy: String(e.proxy ?? ""),
|
||||
use_recording_proxy: !!e.use_recording_proxy,
|
||||
});
|
||||
setSchemaText(t.schema && Object.keys(t.schema).length ? JSON.stringify(t.schema, null, 2) : "");
|
||||
setBound(t.agents ?? []);
|
||||
setDeferred(!!t.deferred);
|
||||
setEnabled(t.enabled);
|
||||
}, [edit]);
|
||||
|
||||
const toggleAgent = (k: string) => setBound((b) => (b.includes(k) ? b.filter((x) => x !== k) : [...b, k]));
|
||||
|
||||
function buildExec(): Record<string, unknown> {
|
||||
if (kind === "shell") return {};
|
||||
const t = ex.timeout_ms ? Number(ex.timeout_ms) : undefined;
|
||||
if (kind === "command") return { command: ex.command, timeout_ms: t };
|
||||
if (kind === "script") return { code: ex.code, timeout_ms: t };
|
||||
let headers: Record<string, string> = {};
|
||||
if (ex.headers.trim()) {
|
||||
try { headers = JSON.parse(ex.headers); } catch { /* validated on save */ }
|
||||
}
|
||||
return { method: ex.method, url: ex.url, headers, body: ex.body, timeout_ms: t, proxy: ex.proxy, use_recording_proxy: ex.use_recording_proxy };
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (isNew && !/^[a-z][a-z0-9_]*$/.test(key.trim())) {
|
||||
toast.error("key 需小写字母开头,仅含小写字母/数字/下划线");
|
||||
return;
|
||||
}
|
||||
let schema: Record<string, unknown> = {};
|
||||
if (schemaText.trim()) {
|
||||
try { schema = JSON.parse(schemaText); } catch { toast.error("参数 JSON Schema 格式错误"); return; }
|
||||
}
|
||||
if (kind === "http" && ex.headers.trim()) {
|
||||
try { JSON.parse(ex.headers); } catch { toast.error("headers JSON 格式错误"); return; }
|
||||
}
|
||||
if (kind === "http") {
|
||||
const props = (schema as { properties?: Record<string, unknown> }).properties;
|
||||
if (!props || Object.keys(props).length === 0) {
|
||||
toast.error("http 工具必须提供参数 JSON Schema(含 properties,不能留空)");
|
||||
return;
|
||||
}
|
||||
}
|
||||
setSaving(true);
|
||||
const payload = { description, schema: kind === "shell" ? {} : schema, agents: bound, enabled, kind, exec: buildExec(), deferred: kind === "shell" ? false : deferred };
|
||||
try {
|
||||
if (isNew) await api.createCustomTool({ key: key.trim(), ...payload });
|
||||
else await api.updateCustomTool(tool!.key, payload);
|
||||
toast.success(isNew ? "已创建自定义工具" : "已保存");
|
||||
onSaved();
|
||||
} catch (e) {
|
||||
toast.error("保存失败:" + (e as Error).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
async function del() {
|
||||
if (!tool) return;
|
||||
try {
|
||||
await api.deleteCustomTool(tool.key);
|
||||
toast.success("已删除");
|
||||
onSaved();
|
||||
} catch (e) {
|
||||
toast.error("删除失败:" + (e as Error).message);
|
||||
}
|
||||
}
|
||||
// runTest dry-runs the CURRENT form (unsaved) with the sample params, so a
|
||||
// template/script/request can be debugged before saving.
|
||||
async function runTest() {
|
||||
let params: Record<string, unknown> = {};
|
||||
if (paramsText.trim()) {
|
||||
try { params = JSON.parse(paramsText); } catch { toast.error("测试参数 JSON 格式错误"); return; }
|
||||
}
|
||||
if (kind === "http" && ex.headers.trim()) {
|
||||
try { JSON.parse(ex.headers); } catch { toast.error("headers JSON 格式错误"); return; }
|
||||
}
|
||||
setTesting(true);
|
||||
setTestResult(null);
|
||||
try {
|
||||
const r = await api.testCustomTool({ kind, exec: buildExec(), params });
|
||||
setTestResult(r);
|
||||
} catch (e) {
|
||||
setTestResult({ output: (e as Error).message, is_error: true });
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={!!edit} onOpenChange={(o) => !o && onClose()}>
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="flex flex-col gap-0 p-0 data-[side=right]:w-[45vw] data-[side=right]:sm:max-w-[45vw] data-[side=right]:min-w-[480px]"
|
||||
>
|
||||
<SheetHeader className="px-4">
|
||||
<SheetTitle>{isNew ? "新建自定义工具" : `编辑 ${tool?.key}`}</SheetTitle>
|
||||
<SheetDescription>shell=bash 环境声明(只需名称+描述,告知模型可用 bash 调用);command/script/http 需写执行规格。</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4 pb-4">
|
||||
<div className="grid gap-1.5">
|
||||
<Label className="text-xs">Key</Label>
|
||||
<Input className="font-mono" placeholder="如 nmap_scan" value={key} disabled={!isNew}
|
||||
onChange={(e) => setKey(e.target.value)} />
|
||||
</div>
|
||||
<div className="grid gap-1.5">
|
||||
<Label className="text-xs">描述(发给模型)</Label>
|
||||
<Textarea rows={2} value={description} onChange={(e) => setDescription(e.target.value)} />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-1.5">
|
||||
<Label className="text-xs">类型</Label>
|
||||
<Select value={kind} onValueChange={(v) => setKind(v as "shell" | "command" | "script" | "http")}>
|
||||
<SelectTrigger className="w-56"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="shell">shell(bash 环境声明)</SelectItem>
|
||||
<SelectItem value="command">command(shell 命令模板)</SelectItem>
|
||||
<SelectItem value="script">script(Python 脚本)</SelectItem>
|
||||
<SelectItem value="http">http(API 请求)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{kind === "shell" && (
|
||||
<p className="text-muted-foreground text-xs">适合 nmap、sqlmap、ffuf 等出名工具——模型已知用法,只需声明"可在 bash 中调用"即可。名称+描述会追加到 Bash 工具描述里。</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{kind === "command" && (
|
||||
<div className="grid gap-1.5">
|
||||
<Label className="text-xs">命令模板(占位符 {"{param}"},如 nmap -p {"{ports}"} {"{target}"})</Label>
|
||||
<Textarea className="font-mono text-xs" rows={2} value={ex.command}
|
||||
onChange={(e) => setEx({ ...ex, command: e.target.value })} />
|
||||
</div>
|
||||
)}
|
||||
{kind === "script" && (
|
||||
<div className="grid gap-1.5">
|
||||
<Label className="text-xs">Python 正文(参数走 stdin JSON / os.environ["TOOL_X"])</Label>
|
||||
<Textarea className="font-mono text-xs" rows={10} value={ex.code}
|
||||
placeholder={'import json,sys\nargs=json.load(sys.stdin)\nprint(...)'}
|
||||
onChange={(e) => setEx({ ...ex, code: e.target.value })} />
|
||||
</div>
|
||||
)}
|
||||
{kind === "http" && (
|
||||
<div className="grid gap-2">
|
||||
<div className="flex gap-2">
|
||||
<div className="grid gap-1.5">
|
||||
<Label className="text-xs">Method</Label>
|
||||
<Input className="w-24" value={ex.method} onChange={(e) => setEx({ ...ex, method: e.target.value })} />
|
||||
</div>
|
||||
<div className="grid flex-1 gap-1.5">
|
||||
<Label className="text-xs">URL(可含 {"{param}"})</Label>
|
||||
<Input className="font-mono text-xs" value={ex.url} onChange={(e) => setEx({ ...ex, url: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-1.5">
|
||||
<Label className="text-xs">Headers(JSON,可含 {"{param}"})</Label>
|
||||
<Textarea className="font-mono text-xs" rows={2} value={ex.headers}
|
||||
placeholder={'{"Authorization": "Bearer {token}"}'} onChange={(e) => setEx({ ...ex, headers: e.target.value })} />
|
||||
</div>
|
||||
<div className="grid gap-1.5">
|
||||
<Label className="text-xs">Body(可含 {"{param}"})</Label>
|
||||
<Textarea className="font-mono text-xs" rows={2} value={ex.body} onChange={(e) => setEx({ ...ex, body: e.target.value })} />
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="grid gap-1.5">
|
||||
<Label className="text-xs">代理 URL(空=直连)</Label>
|
||||
<Input className="font-mono text-xs w-56" value={ex.proxy} onChange={(e) => setEx({ ...ex, proxy: e.target.value })} />
|
||||
</div>
|
||||
<label className="mt-4 flex items-center gap-2 text-sm">
|
||||
<Checkbox checked={ex.use_recording_proxy} onCheckedChange={(v) => setEx({ ...ex, use_recording_proxy: !!v })} />
|
||||
走记录代理
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{kind !== "shell" && (
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="grid gap-1.5">
|
||||
<Label className="text-xs">超时(ms,空=默认)</Label>
|
||||
<Input type="number" className="w-32" value={ex.timeout_ms} onChange={(e) => setEx({ ...ex, timeout_ms: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{kind !== "shell" && (
|
||||
<div className="grid gap-1.5">
|
||||
<Label className="text-xs">
|
||||
参数 JSON Schema{kind === "http" ? "(http 工具必填,需含 properties)" : "(留空 = 自动给 {args} 薄壳)"}
|
||||
</Label>
|
||||
<Textarea className="font-mono text-xs" rows={4} value={schemaText}
|
||||
placeholder={'{"type":"object","properties":{"target":{"type":"string"}},"required":["target"]}'}
|
||||
onChange={(e) => setSchemaText(e.target.value)} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid gap-1.5">
|
||||
<Label className="text-muted-foreground text-xs">绑定 Agent</Label>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{agents.map((a) => (
|
||||
<label key={a.key} className="flex items-center gap-2 text-sm">
|
||||
<Checkbox checked={bound.includes(a.key)} onCheckedChange={() => toggleAgent(a.key)} />
|
||||
{a.name}<span className="text-muted-foreground font-mono text-xs">{a.key}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-6">
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<Switch checked={enabled} onCheckedChange={setEnabled} /> 启用
|
||||
</label>
|
||||
{kind !== "shell" && (
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<Switch checked={deferred} onCheckedChange={setDeferred} /> deferred(大量不常用工具才开)
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{kind !== "shell" && (
|
||||
<div className="grid gap-1.5 rounded-md border p-3">
|
||||
<Label className="text-xs font-medium">测试运行(用当前表单,不会保存)</Label>
|
||||
<Textarea className="font-mono text-xs" rows={2} value={paramsText}
|
||||
placeholder={'示例参数 JSON,如 {"target":"example.com"}'}
|
||||
onChange={(e) => setParamsText(e.target.value)} />
|
||||
<div>
|
||||
<Button size="sm" variant="outline" onClick={runTest} disabled={testing}>
|
||||
<PlayIcon /> {testing ? "运行中…" : "测试运行"}
|
||||
</Button>
|
||||
</div>
|
||||
{testResult && (
|
||||
<pre
|
||||
className={
|
||||
"max-h-64 overflow-auto whitespace-pre-wrap break-words rounded bg-muted p-2 font-mono text-xs " +
|
||||
(testResult.is_error ? "text-destructive" : "")
|
||||
}
|
||||
>
|
||||
{testResult.output || "(无输出)"}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
<div className="flex items-center gap-2 p-4">
|
||||
<Button size="sm" onClick={save} disabled={saving}>
|
||||
<SaveIcon /> {isNew ? "创建" : "保存"}
|
||||
</Button>
|
||||
{!isNew && (
|
||||
<Button size="sm" variant="outline" className="text-destructive" onClick={del}>
|
||||
<Trash2Icon /> 删除
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user