CapabilityPage.tsx
21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import { Bot, Globe, Play, Plus, Save, ShieldCheck, Trash2, Wrench, Zap } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { Badge, Card, CardHeader, Empty, Field, Segmented, Spinner } from "@/components/ui";
import { useHashParams } from "@/lib/nav";
import {
errText, onto, STATUS_LABEL, STATUS_TONE, type CapDef, type ConceptBrief, type FunctionBrief, type Me, type ToolBrief,
} from "@/lib/onto";
import { cn } from "@/lib/utils";
import { confirmDialog } from "@/lib/dialog";
import { toast } from "@/store/useAppStore";
type Tab = "builtin" | "skill" | "action" | "endpoint";
const RISK_TONE: Record<string, string> = { low: "bg-ok/10 text-ok", medium: "bg-warn/10 text-warn", high: "bg-bad/10 text-bad" };
/**
* 能力库:系统里「AI 与流程能做什么」的唯一清单。
* 函数只读、随便调;工具有副作用,只能被审批过的动作调用;技能是 AI 分析包;动作是业务操作。
*/
export function CapabilityPage({ me }: { me: Me | null }) {
const params = useHashParams();
const canEdit = !!me?.permissions.includes("build");
const [tab, setTab] = useState<Tab>("action");
const [cat, setCat] = useState<{ functions: FunctionBrief[]; tools: ToolBrief[]; defs: CapDef[] } | null>(null);
const [sel, setSel] = useState<string>(params.get("id") || "");
const load = useCallback(() => { void onto.catalog().then(setCat).catch((e) => toast("error", errText(e))); }, []);
useEffect(load, [load]);
useEffect(() => {
const id = params.get("id");
if (id && cat) { const d = cat.defs.find((x) => x.id === id); if (d) { setTab(d.kind); setSel(id); } }
}, [params, cat]);
if (!cat) return <Spinner />;
const defs = cat.defs.filter((d) => d.kind === tab);
return (
<div className="space-y-4">
<Segmented value={tab} onChange={(t) => { setTab(t); setSel(""); }} options={[
{ key: "action", label: "动作" }, { key: "skill", label: "技能" },
{ key: "builtin", label: "函数与工具" }, { key: "endpoint", label: "外部端点" }]} />
{tab === "builtin" ? <Builtins cat={cat} /> : (
<div className="grid gap-4 lg:grid-cols-[280px_minmax(0,1fr)]">
<Card className="self-start">
<CardHeader title={{ action: "动作", skill: "技能", endpoint: "外部端点" }[tab]}
right={canEdit && <button className="btn btn-sm" onClick={() => setSel("new")}><Plus className="h-3.5 w-3.5" />新建</button>} />
<div className="divide-y divide-line">
{!defs.length && <Empty title="还没有" desc={tab === "action" ? "动作是经人工审批后才会执行的业务操作。" : ""} />}
{defs.map((d) => (
<button key={d.id} onClick={() => setSel(d.id)}
className={cn("block w-full px-3 py-2 text-left hover:bg-ink/[0.03]", sel === d.id && "bg-brand/5")}>
<div className="flex items-center gap-2">
<span className="min-w-0 flex-1 truncate text-[13px] font-medium">{d.display_name || d.name}</span>
<Badge tone={STATUS_TONE[d.status]}>{STATUS_LABEL[d.status]}</Badge>
</div>
<p className="truncate text-[11px] text-muted">{d.name} · v{d.version}{tab === "action" ? ` · ${d.risk_level}` : ""}</p>
</button>
))}
</div>
</Card>
<div className="min-w-0">
{sel ? <DefEditor key={sel + tab} kind={tab} def={sel === "new" ? null : cat.defs.find((d) => d.id === sel) || null}
cat={cat} canEdit={canEdit} onSaved={(id) => { load(); setSel(id); }} onDeleted={() => { load(); setSel(""); }} />
: <Card><Empty icon={tab === "action" ? <ShieldCheck className="h-10 w-10" /> : tab === "skill" ? <Bot className="h-10 w-10" /> : <Globe className="h-10 w-10" />}
title="选择或新建" /></Card>}
</div>
</div>
)}
</div>
);
}
function Builtins({ cat }: { cat: { functions: FunctionBrief[]; tools: ToolBrief[] } }) {
const [open, setOpen] = useState("");
const [args, setArgs] = useState("{}");
const [out, setOut] = useState<any>(null);
return (
<div className="grid gap-4 xl:grid-cols-2">
<Card>
<CardHeader title={<span className="flex items-center gap-1.5"><Wrench className="h-4 w-4" />函数(只读)</span>}
desc="AI、SOP、技能都能直接调用。没有副作用。" />
<div className="divide-y divide-line">
{cat.functions.map((f) => (
<div key={f.name} className="px-4 py-2.5">
<button className="w-full text-left" onClick={() => { setOpen(open === f.name ? "" : f.name); setOut(null); setArgs("{}"); }}>
<p className="text-[13px] font-medium">{f.title} <code className="ml-1 text-[11px] text-muted">{f.name}</code></p>
<p className="text-[12px] text-muted">{f.description}</p>
</button>
{open === f.name && (
<div className="mt-2 space-y-2">
<p className="text-[11px] text-muted">参数:{Object.entries(f.input_schema.properties || {}).map(([k, v]: any) =>
`${k}${(f.input_schema.required || []).includes(k) ? "*" : ""}(${v.description || v.type})`).join(";")}</p>
<textarea className="input min-h-[60px] font-mono text-[12px]" value={args} onChange={(e) => setArgs(e.target.value)} />
<button className="btn btn-sm" onClick={async () => {
try { setOut(await onto.callFunction(f.name, JSON.parse(args || "{}"))); } catch (e) { setOut({ error: errText(e) }); }
}}><Play className="h-3.5 w-3.5" />试调用</button>
{out && <pre className="max-h-64 overflow-auto rounded bg-ink/5 p-2 text-[11px]">{JSON.stringify(out, null, 2)}</pre>}
</div>
)}
</div>
))}
</div>
</Card>
<Card className="self-start">
<CardHeader title={<span className="flex items-center gap-1.5"><Zap className="h-4 w-4" />工具(有副作用)</span>}
desc="只能被经过人工审批的动作调用,AI 与 SOP 不能直接用。" />
<div className="divide-y divide-line">
{cat.tools.map((t) => (
<div key={t.name} className="px-4 py-2.5">
<p className="flex items-center gap-2 text-[13px] font-medium">{t.title} <code className="text-[11px] text-muted">{t.name}</code>
<Badge tone={RISK_TONE[t.risk_level]}>{t.risk_level}</Badge>
{t.reversible && <Badge>可撤销</Badge>}{t.external && <Badge tone="bg-bad/10 text-bad">外部</Badge>}</p>
<p className="text-[12px] text-muted">{t.description}</p>
</div>
))}
</div>
</Card>
</div>
);
}
const EMPTY_SPEC: Record<string, any> = {
action: { target_type: "", params: [], criteria: [], effects: [], approval: { mode: "manual", approver_roles: [] }, reversible: true },
skill: { instructions: "", functions: ["metric.query", "knowledge.search"], inputs: [], output_schema: { conclusion: "结论", details: [] }, max_steps: 4 },
endpoint: { url: "https://", method: "POST", timeout: 15 },
};
function DefEditor({ kind, def, cat, canEdit, onSaved, onDeleted }: {
kind: "skill" | "action" | "endpoint"; def: CapDef | null; cat: { functions: FunctionBrief[]; tools: ToolBrief[] };
canEdit: boolean; onSaved: (id: string) => void; onDeleted: () => void;
}) {
const [name, setName] = useState(def?.name || "");
const [display, setDisplay] = useState(def?.display_name || "");
const [desc, setDesc] = useState(def?.description || "");
const [spec, setSpec] = useState<any>(structuredClone(def?.spec || EMPTY_SPEC[kind]));
const [secret, setSecret] = useState("");
const [types, setTypes] = useState<ConceptBrief[]>([]);
const [roles, setRoles] = useState<ConceptBrief[]>([]);
const [busy, setBusy] = useState(false);
const [test, setTest] = useState("{}");
const [testOut, setTestOut] = useState<any>(null);
useEffect(() => {
void onto.concepts({ kind: "object_type" }).then(setTypes);
void onto.concepts({ kind: "role" }).then(setRoles);
}, []);
const set = (k: string, v: any) => setSpec({ ...spec, [k]: v });
const save = async () => {
setBusy(true);
try {
const body: any = { kind, name, display_name: display, description: desc, spec };
if (kind === "endpoint" && secret.trim()) body.secret = JSON.parse(secret);
const d = await onto.saveCapDef(body, def?.id);
toast("ok", "已保存", d.status === "draft" ? "修改后需要重新发布,运行时才会用新定义" : undefined);
onSaved(d.id);
} catch (e) { toast("error", "保存失败", errText(e)); } finally { setBusy(false); }
};
const status = async (s: string) => {
try { await onto.setCapStatus(def!.id, s); toast("ok", STATUS_LABEL[s]); onSaved(def!.id); }
catch (e) { toast("error", errText(e)); }
};
return (
<Card>
<CardHeader title={def ? (def.display_name || def.name) : "新建"}
desc={def ? `${def.kind_label} · v${def.version} · 风险 ${def.risk_level}` : undefined}
right={canEdit && <>
{def && def.status !== "published" && <button className="btn btn-sm" onClick={() => void status("published")}>发布</button>}
{def && def.status === "published" && <button className="btn btn-sm" onClick={() => void status("disabled")}>停用</button>}
{def && <button className="btn btn-sm" onClick={async () => {
if (!(await confirmDialog("删除这个能力?", { desc: "有运行记录的动作不能删除,只能停用", danger: true }))) return;
try { await onto.deleteCapDef(def.id); onDeleted(); } catch (e) { toast("error", errText(e)); }
}}><Trash2 className="h-3.5 w-3.5" /></button>}
<button className="btn btn-primary btn-sm" disabled={busy} onClick={() => void save()}><Save className="h-3.5 w-3.5" />保存</button>
</>} />
<div className="space-y-4 p-4">
<div className="grid gap-3 sm:grid-cols-3">
<Field label="标识名" required hint="英文或中文,唯一"><input className="input" value={name} disabled={!canEdit} onChange={(e) => setName(e.target.value)} /></Field>
<Field label="显示名"><input className="input" value={display} disabled={!canEdit} onChange={(e) => setDisplay(e.target.value)} /></Field>
<Field label="说明(AI 靠它判断何时用)"><input className="input" value={desc} disabled={!canEdit} onChange={(e) => setDesc(e.target.value)} /></Field>
</div>
{kind === "skill" && (
<>
<Field label="指令" required><textarea className="input min-h-[100px]" value={spec.instructions} disabled={!canEdit} onChange={(e) => set("instructions", e.target.value)} /></Field>
<Field label="允许使用的函数(只读)">
<div className="flex flex-wrap gap-1.5">
{cat.functions.map((f) => (
<label key={f.name} className={cn("chip cursor-pointer", spec.functions.includes(f.name) && "border-brand text-brand")}>
<input type="checkbox" className="hidden" disabled={!canEdit} checked={spec.functions.includes(f.name)}
onChange={(e) => set("functions", e.target.checked ? [...spec.functions, f.name] : spec.functions.filter((x: string) => x !== f.name))} />
{f.title}
</label>
))}
</div>
</Field>
<div className="grid gap-3 sm:grid-cols-2">
<Field label="输入(每行:名称:说明)">
<textarea className="input min-h-[60px] font-mono text-[12px]" disabled={!canEdit}
value={(spec.inputs || []).map((i: any) => `${i.name}:${i.description}`).join("\n")}
onChange={(e) => set("inputs", e.target.value.split("\n").filter(Boolean).map((l) => {
const [n, ...r] = l.split(":"); return { name: n.trim(), description: r.join(":").trim() };
}))} />
</Field>
<Field label="输出格式(JSON 示例)">
<JsonBox value={spec.output_schema} disabled={!canEdit} onChange={(v) => set("output_schema", v)} />
</Field>
</div>
<Field label="最多调用函数次数" className="w-40"><input className="input" type="number" value={spec.max_steps} disabled={!canEdit} onChange={(e) => set("max_steps", Number(e.target.value))} /></Field>
{def && (
<div className="space-y-2 rounded-lg border border-line p-3">
<p className="text-[12px] font-medium">试运行</p>
<textarea className="input min-h-[50px] font-mono text-[12px]" value={test} onChange={(e) => setTest(e.target.value)} />
<button className="btn btn-sm" onClick={async () => {
setTestOut({ running: true });
try { setTestOut(await onto.runSkill(def.id, JSON.parse(test || "{}"))); } catch (e) { setTestOut({ error: errText(e) }); }
}}><Play className="h-3.5 w-3.5" />运行</button>
{testOut && (testOut.running ? <Spinner /> : <pre className="max-h-72 overflow-auto rounded bg-ink/5 p-2 text-[11px]">{JSON.stringify(testOut, null, 2)}</pre>)}
</div>
)}
</>
)}
{kind === "action" && (
<>
<div className="grid gap-3 sm:grid-cols-2">
<Field label="作用对象类型" hint="设置后,提议时要指定对象;表达式里可用 obj.属性、obj_key">
<select className="input" value={spec.target_type} disabled={!canEdit} onChange={(e) => set("target_type", e.target.value)}>
<option value="">(不作用于具体对象)</option>
{types.map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
</select>
</Field>
<Field label="审批角色" hint="当前阶段所有动作都需要人工审批;不设角色则任何有审批权限的人可批">
<div className="flex flex-wrap gap-1.5">
{roles.map((r) => (
<label key={r.id} className={cn("chip cursor-pointer", spec.approval.approver_roles.includes(r.name) && "border-brand text-brand")}>
<input type="checkbox" className="hidden" disabled={!canEdit} checked={spec.approval.approver_roles.includes(r.name)}
onChange={(e) => set("approval", { mode: "manual", approver_roles: e.target.checked
? [...spec.approval.approver_roles, r.name] : spec.approval.approver_roles.filter((x: string) => x !== r.name) })} />
{r.name}
</label>
))}
{!roles.length && <span className="text-[12px] text-muted">本体里还没有角色</span>}
</div>
</Field>
</div>
<Field label="参数">
<Rows items={spec.params} disabled={!canEdit} onChange={(v) => set("params", v)}
empty={{ name: "", label: "", type: "string", required: false, enum: [] as string[] } as any}
render={(p, up) => (<>
<input className="input h-8 w-28" placeholder="name" value={p.name} onChange={(e) => up({ ...p, name: e.target.value })} />
<input className="input h-8 w-28" placeholder="中文名" value={p.label} onChange={(e) => up({ ...p, label: e.target.value })} />
<select className="input h-8 w-24" value={p.type} onChange={(e) => up({ ...p, type: e.target.value })}>
{["string", "text", "number", "integer", "boolean", "enum", "date"].map((t) => <option key={t}>{t}</option>)}
</select>
{p.type === "enum" && <input className="input h-8 w-36" placeholder="可选值,逗号分隔" value={(p.enum || []).join(",")}
onChange={(e) => up({ ...p, enum: e.target.value.split(/[,,]/).map((s) => s.trim()).filter(Boolean) })} />}
<label className="flex items-center gap-1 text-[12px]"><input type="checkbox" checked={p.required} onChange={(e) => up({ ...p, required: e.target.checked })} />必填</label>
</>)} />
</Field>
<Field label="前置条件" hint="规则表达式,不满足时拒绝提议,如 obj.状态 != '已关闭'">
<Rows items={spec.criteria} disabled={!canEdit} onChange={(v) => set("criteria", v)} empty={{ expression: "", message: "" }}
render={(c, up) => (<>
<input className="input h-8 flex-1 font-mono text-[12px]" placeholder="表达式" value={c.expression} onChange={(e) => up({ ...c, expression: e.target.value })} />
<input className="input h-8 w-48" placeholder="不满足时的提示" value={c.message} onChange={(e) => up({ ...c, message: e.target.value })} />
</>)} />
</Field>
<Field label="效果(按顺序调用工具)" hint="参数里用 $参数名、$obj.属性、$obj_key 引用;预览与审批都基于这份渲染结果">
<Rows items={spec.effects} disabled={!canEdit} onChange={(v) => set("effects", v)} empty={{ tool: cat.tools[0]?.name || "", args: {} }}
render={(e, up) => (
<div className="flex w-full flex-col gap-1.5">
<select className="input h-8 w-56" value={e.tool} onChange={(ev) => up({ ...e, tool: ev.target.value })}>
{cat.tools.map((t) => <option key={t.name} value={t.name}>{t.title}({t.name})</option>)}
</select>
<JsonBox value={e.args} onChange={(v) => up({ ...e, args: v })}
placeholder={JSON.stringify(Object.fromEntries(Object.keys(cat.tools.find((t) => t.name === e.tool)?.input_schema.properties || {}).map((k) => [k, ""])))} />
</div>
)} />
</Field>
<label className="flex items-center gap-2 text-[12.5px]">
<input type="checkbox" checked={spec.reversible} disabled={!canEdit} onChange={(e) => set("reversible", e.target.checked)} />
允许撤销(所有效果的工具都支持撤销时才生效)
</label>
</>
)}
{kind === "endpoint" && (
<>
<div className="grid gap-3 sm:grid-cols-3">
<Field label="地址" className="sm:col-span-2"><input className="input" value={spec.url} disabled={!canEdit} onChange={(e) => set("url", e.target.value)} /></Field>
<Field label="方法"><select className="input" value={spec.method} disabled={!canEdit} onChange={(e) => set("method", e.target.value)}>
{["POST", "PUT", "PATCH"].map((m) => <option key={m}>{m}</option>)}</select></Field>
</div>
<Field label="凭据请求头(JSON)" hint="加密保存、永不回显、AI 看不到。留空表示不修改">
<textarea className="input min-h-[60px] font-mono text-[12px]" value={secret} disabled={!canEdit} placeholder='{"Authorization": "Bearer ..."}'
onChange={(e) => setSecret(e.target.value)} />
</Field>
<p className="text-[12px] text-muted">外部端点只能通过动作里的 webhook.call 工具调用,同样需要审批。</p>
</>
)}
</div>
</Card>
);
}
function Rows<T>({ items, onChange, render, empty, disabled }: {
items: T[]; onChange: (v: T[]) => void; render: (it: T, update: (v: T) => void) => React.ReactNode; empty: T; disabled?: boolean;
}) {
return (
<div className="space-y-1.5">
{(items || []).map((it, i) => (
<div key={i} className="flex flex-wrap items-center gap-2 rounded-md border border-line/70 p-1.5">
<fieldset disabled={disabled} className="contents">{render(it, (v) => { const n = [...items]; n[i] = v; onChange(n); })}</fieldset>
{!disabled && <button className="btn btn-ghost btn-sm ml-auto" onClick={() => onChange(items.filter((_, j) => j !== i))}><Trash2 className="h-3.5 w-3.5" /></button>}
</div>
))}
{!disabled && <button className="btn btn-sm" onClick={() => onChange([...(items || []), structuredClone(empty)])}><Plus className="h-3.5 w-3.5" />添加</button>}
</div>
);
}
export function JsonBox({ value, onChange, disabled, placeholder }: { value: any; onChange: (v: any) => void; disabled?: boolean; placeholder?: string }) {
const [text, setText] = useState(() => JSON.stringify(value ?? {}, null, 2));
const [bad, setBad] = useState(false);
return (
<textarea className={cn("input min-h-[64px] font-mono text-[12px]", bad && "border-bad")} value={text} disabled={disabled} placeholder={placeholder}
onChange={(e) => {
setText(e.target.value);
try { onChange(JSON.parse(e.target.value || "{}")); setBad(false); } catch { setBad(true); }
}} />
);
}