onto.ts
21.8 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
329
330
331
332
333
334
335
336
337
338
/**
* 本体平台(v3)的类型与接口:内核、能力、SOP、统一提问、治理、评测。
* 老的文档 / 图谱 / 数据连接接口仍在 api.ts。
*/
import { ApiError } from "./api";
async function req<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(path, init);
if (!res.ok) {
let detail = `HTTP ${res.status}`;
try {
const body = await res.json();
detail = typeof body.detail === "string" ? body.detail : JSON.stringify(body.detail ?? body);
} catch { /* 非 JSON */ }
throw new ApiError(detail, res.status);
}
const ct = res.headers.get("content-type") ?? "";
return (ct.includes("json") ? res.json() : res.text()) as Promise<T>;
}
const post = (body?: unknown): RequestInit => ({
method: "POST", headers: { "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
const put = (body: unknown): RequestInit => ({ ...post(body), method: "PUT" });
const del: RequestInit = { method: "DELETE" };
const enc = encodeURIComponent;
const qs = (p: Record<string, unknown>) => {
const q = new URLSearchParams();
Object.entries(p).forEach(([k, v]) => { if (v !== undefined && v !== null && v !== "") q.set(k, String(v)); });
const s = q.toString();
return s ? `?${s}` : "";
};
// ============================== 类型 ==============================
export type ConceptKind = "object_type" | "link_type" | "metric" | "dimension" | "rule" | "calendar"
| "role" | "process" | "term";
export interface Me {
id: string; name: string; kind: string; roles: string[]; biz_roles: string[];
scope: Record<string, Record<string, string[]>>; workspace: string; permissions: string[];
}
export interface UserRec {
id: string; name: string; roles: string[]; biz_roles: string[];
scope: Record<string, Record<string, string[]>>; enabled: boolean;
}
export interface Binding { id: string; concept_id: string; ds_id: number; target_kind: string; ref: any; updated_at?: string }
export interface Evidence { id?: number; doc_id: number; chunk_id: string; heading: string; snippet: string }
export interface ConceptBrief {
id: string; kind: ConceptKind; kind_label: string; name: string; display_name: string;
description: string; synonyms: string[]; status: "draft" | "published" | "deprecated";
dirty: boolean; version: number; origin: string; published: boolean; updated_at: string | null;
}
export interface Concept extends ConceptBrief {
spec: any; bindings: Binding[]; evidence: Evidence[]; published_copy: any;
graph_entities?: { id: string; label: string; type: string; degree: number }[];
}
export interface KernelMeta {
kinds: { kind: ConceptKind; label: string; desc: string }[];
data_types: string[]; rule_kinds: string[]; directions: string[]; cardinality: string[];
binding_kinds: Record<string, string>; functions: string[];
}
export interface KernelStats {
by_kind: Record<string, { total: number; draft?: number; published?: number; deprecated?: number }>;
dirty: number; revision: number;
}
export interface Diff {
added: { id: string; name: string; kind: string }[];
removed: { id: string; name: string; kind: string }[];
changed: { id: string; name: string; kind: string; fields: string[] }[];
}
export interface RevisionRec { revision: number; note: string; diff: Diff; published_by: string; created_at: string; concepts: number }
export interface LinkResult {
concepts: { id: string; kind: string; name: string; matched: string[] }[];
instances: { concept_id: string; type_name: string; key: string; label: string; matched: string }[];
time: any;
}
export interface ObjectRec { type_id: string; type_name: string; key: string; label: string; properties: Record<string, any>; overridden?: string[] }
export interface FunctionBrief { kind: "function"; name: string; title: string; description: string; input_schema: any; category: string; output: string }
export interface ToolBrief { kind: "tool"; name: string; title: string; description: string; input_schema: any; risk_level: string; reversible: boolean; external: boolean }
export interface CapDef {
id: string; kind: "skill" | "action" | "endpoint"; kind_label: string; name: string;
display_name: string; description: string; spec: any; status: "draft" | "published" | "disabled";
version: number; risk_level: string; updated_at: string;
}
export interface ActionPreview {
action: { id: string; name: string; display_name: string; version: number; reversible: boolean; risk_level: string; approver_roles: string[] };
params: Record<string, any>; target_ref: string; summary: string;
effects: { tool: string; label: string; args: any; preview: { summary: string; changes?: any[]; external?: boolean }; risk_level: string; external: boolean }[];
}
export interface ActionRun {
id: string; action_id: string; action_name: string; kind: "normal" | "revert"; revert_of: string;
params: Record<string, any>; target_ref: string; initiator_kind: "user" | "ai" | "sop";
initiator_id: string; submitted_by: string; source_ref: string; reason: string;
status: string; preview: ActionPreview; result: any; error: string;
created_at: string; decided_at: string | null; finished_at: string | null;
approvals: { id: string; status: string; decided_by: string; comment: string; decided_at: string | null; approver_roles: string[] }[];
can_approve?: boolean; cannot_reason?: string;
}
export interface TaskRec {
id: string; title: string; description: string; role: string; assignee: string;
form: { name: string; label: string; type: string; required: boolean; options?: string[] }[];
checklist: string[]; context: any; object_ref: string; status: "open" | "done" | "cancelled";
result: any; source_type: string; source_id: string; due_at: string | null; overdue: boolean;
created_at: string; completed_by: string; completed_at: string | null;
}
export interface ReviewItem {
id: string; kind: string; kind_label: string; title: string; payload: any; target_ref: string;
source: string; confidence: number; status: string; assignee_role: string; created_by: string;
decided_by: string; comment: string; created_at: string; decided_at: string | null;
}
export interface NotificationRec { id: number; title: string; body: string; link: string; read: boolean; created_at: string }
export interface InboxCounts { approvals: number; tasks: number; reviews: number; review_counts: Record<string, number>; notifications: number }
export interface AuditRec {
id: number; ts: string; actor_kind: string; actor_id: string; actor_name: string; event: string;
target_type: string; target_id: string; summary: string; before?: any; after?: any;
}
export interface SopStep {
id: string; type: "function" | "skill" | "decision" | "human_task" | "action" | "subprocess" | "end";
title: string; description: string; lane: string; next: string; output: string;
function?: string; args?: Record<string, any>;
skill?: string; inputs?: Record<string, any>;
branches?: { when: string; next: string; label: string }[]; default?: string;
role?: string; instructions?: string; form?: { name: string; label: string; type?: string; required?: boolean }[];
checklist?: string[]; sla_hours?: number;
action?: string; params?: Record<string, any>; object_key?: string; on_reject?: string;
sop?: string; outcome?: string;
}
export interface SopParam { name: string; label: string; type: string; object_type: string; calendar: string; required: boolean; default?: any }
export interface SopSpec {
params: SopParam[]; roles: string[]; trigger: any; start: string; steps: SopStep[]; evidence: any[];
}
export interface SopBrief {
id: string; title: string; description: string; status: string; current_version: number;
step_count: number; trigger_kind: string; dry_run_ok: boolean; ai_generated: boolean;
run_count?: number; updated_at: string; owner_role: string; process_concept_id: string;
}
export interface SopDef extends SopBrief {
spec: SopSpec; validation: { errors: string[]; warnings: string[] }; draft_hash: string;
last_dry_run: any; versions: { id: string; version: number; note: string; published_by: string; created_at: string }[];
}
export interface SopStepRun {
id: string; seq: number; step_id: string; step_type: string; title: string; status: string;
inputs: any; output: any; note: string; error: string; task_id: string; action_run_id: string;
child_run_id: string; started_at: string; finished_at: string | null;
}
export interface SopRun {
id: string; def_id: string; version: number; title: string; mode: string; params: any; vars: any;
status: string; current_step: string; trigger: string; outcome: string; error: string;
started_by: string; created_at: string; finished_at: string | null;
steps: SopStepRun[] | null; spec?: SopSpec;
}
export interface AskCard {
action: string; action_id?: string; display_name: string; params: Record<string, any>;
object_key: string; reason: string; preview?: ActionPreview; error?: string;
}
export interface DataRef {
run_id: number; sql: string; columns: string[]; rows: any[][]; metric?: any; period?: any;
calibre?: any; cited?: boolean; step_id: string;
}
export interface Citation { chunk_id: string; heading: string; doc_id: number; text: string }
export interface Turn {
id: string; conversation_id: string; seq: number; question: string; status: string;
links: LinkResult; plan: any; steps: any[]; answer: string; citations: Citation[];
data_refs: DataRef[]; actions: AskCard[]; sops: any[]; rating: number; feedback: string;
duration_ms: number; created_at: string;
}
export interface EvalCase {
id: string; suite: string; kind: string; question: string; expected: string;
must_include: string[]; expected_calls: string[]; expected_action: string; source: string; enabled: boolean;
}
export interface EvalRun {
id: string; suite: string; target: string; status: string; total: number; passed: number;
pass_rate: number; summary: any; job_id: number; created_at: string; finished_at: string | null;
results?: any[];
}
// ============================== 接口 ==============================
export const onto = {
// 治理
me: () => req<Me>("/api/gov/me"),
users: () => req<{ users: UserRec[]; system_roles: string[] }>("/api/gov/users"),
saveUser: (id: string, body: Partial<UserRec>) => req<UserRec>(`/api/gov/users/${enc(id)}`, put(body)),
audit: (p: Record<string, unknown>) => req<{ total: number; items: AuditRec[] }>(`/api/gov/audit${qs(p)}`),
auditOne: (id: number) => req<AuditRec>(`/api/gov/audit/${id}`),
auditExportUrl: (p: Record<string, unknown>) => `/api/gov/audit/export${qs(p)}`,
reviews: (p: Record<string, unknown>) => req<{ total: number; items: ReviewItem[] }>(`/api/gov/review${qs(p)}`),
reviewCounts: () => req<Record<string, number>>("/api/gov/review/counts"),
decideReview: (id: string, body: { accept: boolean; comment?: string; payload?: any }) =>
req<ReviewItem & { result: any }>(`/api/gov/review/${enc(id)}/decide`, post(body)),
batchReview: (ids: string[], accept: boolean, comment = "") =>
req<{ ok: string[]; failed: { id: string; error: string }[] }>("/api/gov/review/batch", post({ ids, accept, comment })),
notifications: (unread = false) => req<{ items: NotificationRec[]; unread: number }>(`/api/gov/notifications${qs({ unread })}`),
readNotifications: (ids?: number[]) => req<{ ok: boolean }>("/api/gov/notifications/read", post({ ids })),
llmStats: (days = 7) => req<any>(`/api/gov/llm-stats?days=${days}`),
// 内核
kernelMeta: () => req<KernelMeta>("/api/kernel/meta"),
kernelStats: () => req<KernelStats>("/api/kernel/stats"),
concepts: (p: { kind?: string; status?: string; q?: string } = {}) => req<ConceptBrief[]>(`/api/kernel/concepts${qs(p)}`),
concept: (id: string) => req<Concept>(`/api/kernel/concepts/${enc(id)}`),
createConcept: (body: any) => req<Concept>("/api/kernel/concepts", post(body)),
updateConcept: (id: string, body: any) => req<Concept>(`/api/kernel/concepts/${enc(id)}`, put(body)),
deleteConcept: (id: string) => req<{ ok: boolean }>(`/api/kernel/concepts/${enc(id)}`, del),
deprecateConcept: (id: string, reason = "") => req<Concept>(`/api/kernel/concepts/${enc(id)}/deprecate`, post({ reason })),
usage: (id: string) => req<{ type: string; id: string; name: string; kind: string }[]>(`/api/kernel/concepts/${enc(id)}/usage`),
impact: (id: string) => req<any>(`/api/kernel/concepts/${enc(id)}/impact`),
lineage: (id: string) => req<{ nodes: { id: string; label: string; kind: string }[]; edges: { from: string; to: string; label: string }[] }>(
`/api/kernel/concepts/${enc(id)}/lineage`),
setBinding: (id: string, body: { ds_id: number; target_kind: string; ref: any }) =>
req<Binding>(`/api/kernel/concepts/${enc(id)}/bindings`, put(body)),
deleteBinding: (bid: string) => req<{ ok: boolean }>(`/api/kernel/bindings/${enc(bid)}`, del),
pendingDiff: () => req<Diff>("/api/kernel/diff"),
publish: (note: string, force = false) => req<{ revision: number; diff: Diff }>("/api/kernel/publish", post({ note, force })),
revisions: () => req<RevisionRec[]>("/api/kernel/revisions"),
rollback: (rev: number) => req<{ revision: number }>(`/api/kernel/revisions/${rev}/rollback`, post()),
link: (q: string) => req<LinkResult>(`/api/kernel/link?q=${enc(q)}`),
evalRule: (body: { rule?: string; expression?: string; vars: any }) =>
req<{ result: any; params: string[]; expression: string }>("/api/kernel/rules/eval", post(body)),
resolveCalendar: (body: { calendar?: string; spec?: any; ref: string }) =>
req<{ period: string; start: string; end: string }>("/api/kernel/calendar/resolve", post(body)),
metricQuery: (body: any) => req<any>("/api/kernel/metrics/query", post(body)),
metricCompile: (body: any) => req<{ sql: string; ds_id: number; period: any }>("/api/kernel/metrics/compile", post(body)),
proposeFromDocs: (doc_ids?: number[]) => req<{ job_id: number; chunks: number }>("/api/kernel/propose/documents", post({ doc_ids })),
proposeFromDatasource: (dsId: number) => req<{ proposed: number; conflicts: number; enriched: number }>(
`/api/kernel/propose/datasource/${dsId}`, post()),
graphLink: () => req<{ linked: number; concepts_with_evidence: number }>("/api/kernel/graph-link", post()),
exportYamlUrl: "/api/kernel/export",
importYaml: (yaml: string, overwrite = false) => req<any>("/api/kernel/import", post({ yaml, overwrite })),
templates: () => req<{ id: string; name: string; description: string; concepts: number; capabilities: number; sops: number }[]>(
"/api/kernel/templates"),
applyTemplate: (id: string, overwrite = false) => req<any>(`/api/kernel/templates/${enc(id)}/apply`, post({ overwrite })),
objects: (type: string, q = "", limit = 20) =>
req<{ object_type: { id: string; name: string; spec: any }; items: ObjectRec[] }>(
`/api/kernel/objects/${enc(type)}${qs({ q, limit })}`),
object360: (type: string, key: string) => req<any>(`/api/kernel/objects/${enc(type)}/${enc(key)}`),
syncObjects: (type: string) => req<{ synced: number }>(`/api/kernel/objects/${enc(type)}/sync`, post()),
// 能力
catalog: () => req<{ functions: FunctionBrief[]; tools: ToolBrief[]; defs: CapDef[] }>("/api/cap/catalog"),
callFunction: (name: string, args: any) => req<any>(`/api/cap/functions/${enc(name)}/call`, post({ args })),
capDefs: (kind = "") => req<CapDef[]>(`/api/cap/defs${qs({ kind })}`),
saveCapDef: (body: any, id?: string) => id
? req<CapDef>(`/api/cap/defs/${enc(id)}`, put(body)) : req<CapDef>("/api/cap/defs", post(body)),
setCapStatus: (id: string, status: string) => req<CapDef>(`/api/cap/defs/${enc(id)}/status`, post({ status })),
deleteCapDef: (id: string) => req<{ ok: boolean }>(`/api/cap/defs/${enc(id)}`, del),
runSkill: (ref: string, args: any) => req<any>(`/api/cap/skills/${enc(ref)}/run`, post({ args })),
prepareAction: (ref: string, params: any, object_key = "") =>
req<ActionPreview>(`/api/cap/actions/${enc(ref)}/prepare`, post({ params, object_key })),
proposeAction: (ref: string, body: { params: any; object_key?: string; reason?: string; initiator_kind?: string; source_ref?: string }) =>
req<ActionRun>(`/api/cap/actions/${enc(ref)}/propose`, post(body)),
actionRuns: (p: Record<string, unknown> = {}) => req<ActionRun[]>(`/api/cap/runs${qs(p)}`),
actionRun: (id: string) => req<ActionRun>(`/api/cap/runs/${enc(id)}`),
decideAction: (id: string, approve: boolean, comment = "") => req<ActionRun>(`/api/cap/runs/${enc(id)}/decide`, post({ approve, comment })),
cancelAction: (id: string, reason = "") => req<ActionRun>(`/api/cap/runs/${enc(id)}/cancel`, post({ reason })),
revertAction: (id: string, reason = "") => req<ActionRun>(`/api/cap/runs/${enc(id)}/revert`, post({ reason })),
approvals: () => req<ActionRun[]>("/api/cap/approvals"),
tasks: (p: Record<string, unknown> = {}) => req<TaskRec[]>(`/api/cap/tasks${qs(p)}`),
task: (id: string) => req<TaskRec>(`/api/cap/tasks/${enc(id)}`),
completeTask: (id: string, result: any, comment = "") => req<TaskRec>(`/api/cap/tasks/${enc(id)}/complete`, post({ result, comment })),
claimTask: (id: string) => req<TaskRec>(`/api/cap/tasks/${enc(id)}/claim`, post()),
inbox: () => req<InboxCounts>("/api/cap/inbox"),
// SOP
sopMeta: () => req<{ step_types: { type: string; label: string }[]; param_types: string[] }>("/api/sop/meta"),
sops: (p: Record<string, unknown> = {}) => req<SopBrief[]>(`/api/sop/defs${qs(p)}`),
sop: (id: string) => req<SopDef>(`/api/sop/defs/${enc(id)}`),
createSop: (body: any) => req<SopDef>("/api/sop/defs", post(body)),
draftSop: (topic: string, process_concept_id = "") => req<SopDef>("/api/sop/defs/draft", post({ topic, process_concept_id })),
saveSop: (id: string, body: any) => req<SopDef>(`/api/sop/defs/${enc(id)}`, put(body)),
archiveSop: (id: string) => req<SopDef>(`/api/sop/defs/${enc(id)}/archive`, post()),
validateSop: (spec: any) => req<{ spec: SopSpec; errors: string[]; warnings: string[] }>("/api/sop/validate", post({ spec })),
dryRunSop: (id: string, params: any) => req<SopRun>(`/api/sop/defs/${enc(id)}/dry-run`, post({ params })),
submitSop: (id: string, note: string) => req<ReviewItem>(`/api/sop/defs/${enc(id)}/submit`, post({ note })),
runSop: (id: string, params: any, mode = "live") => req<SopRun>(`/api/sop/defs/${enc(id)}/run`, post({ params, mode })),
sopVersion: (id: string, v: number) => req<{ spec: SopSpec; version: number }>(`/api/sop/defs/${enc(id)}/versions/${v}`),
triggerScan: (id: string, dry = true) => req<any>(`/api/sop/defs/${enc(id)}/trigger-scan`, post({ dry })),
sopRuns: (p: Record<string, unknown> = {}) => req<SopRun[]>(`/api/sop/runs${qs(p)}`),
sopRun: (id: string) => req<SopRun>(`/api/sop/runs/${enc(id)}`),
cancelSopRun: (id: string, reason = "") => req<SopRun>(`/api/sop/runs/${enc(id)}/cancel`, post({ reason })),
// 统一提问
conversations: () => req<{ id: string; title: string; turns: number; updated_at: string }[]>("/api/ask/conversations"),
conversation: (id: string) => req<{ id: string; title: string; turns: Turn[] }>(`/api/ask/conversations/${enc(id)}`),
deleteConversation: (id: string) => req<{ ok: boolean }>(`/api/ask/conversations/${enc(id)}`, del),
feedback: (turnId: string, rating: number, comment = "", correction = "") =>
req<{ ok: boolean; review_item: ReviewItem | null }>(`/api/ask/turns/${enc(turnId)}/feedback`, post({ rating, comment, correction })),
// 评测
evalSuites: () => req<{ suites: { suite: string; cases: number; by_kind: Record<string, number> }[]; gold_sets: string[] }>("/api/eval/suites"),
evalCases: (suite = "") => req<EvalCase[]>(`/api/eval/cases${qs({ suite })}`),
saveEvalCase: (body: any, id?: string) => id
? req<EvalCase>(`/api/eval/cases/${enc(id)}`, put(body)) : req<EvalCase>("/api/eval/cases", post(body)),
deleteEvalCase: (id: string) => req<{ ok: boolean }>(`/api/eval/cases/${enc(id)}`, del),
importGold: (gold_set: string) => req<{ imported: number }>("/api/eval/cases/import", post({ gold_set })),
startEval: (suite: string, target: string, judge = true) => req<EvalRun>("/api/eval/runs", post({ suite, target, judge })),
evalRuns: () => req<EvalRun[]>("/api/eval/runs"),
evalRun: (id: string) => req<EvalRun>(`/api/eval/runs/${enc(id)}`),
ontologyEval: (gold_set: string) => req<any>("/api/eval/ontology", post({ gold_set })),
};
export const STATUS_LABEL: Record<string, string> = {
draft: "草稿", published: "已发布", deprecated: "已废弃", disabled: "已停用",
pending_approval: "待审批", executing: "执行中", done: "已完成", failed: "失败",
rejected: "已驳回", cancelled: "已撤回", reverted: "已撤销", pending: "待处理",
accepted: "已采纳", open: "待办", running: "运行中", waiting: "等待中", paused: "已暂停",
waiting_human: "等人工", waiting_approval: "等审批", waiting_child: "等子流程",
suggested: "建议", skipped: "跳过", archived: "已归档",
};
export const STATUS_TONE: Record<string, string> = {
draft: "bg-ink/5 text-muted", published: "bg-ok/10 text-ok", deprecated: "bg-bad/10 text-bad",
pending_approval: "bg-warn/10 text-warn", executing: "bg-brand2/10 text-brand2",
done: "bg-ok/10 text-ok", failed: "bg-bad/10 text-bad", rejected: "bg-bad/10 text-bad",
cancelled: "bg-ink/5 text-muted", reverted: "bg-ink/5 text-muted", pending: "bg-warn/10 text-warn",
accepted: "bg-ok/10 text-ok", open: "bg-warn/10 text-warn", running: "bg-brand2/10 text-brand2",
waiting: "bg-warn/10 text-warn", paused: "bg-brand/10 text-brand", waiting_human: "bg-warn/10 text-warn",
waiting_approval: "bg-warn/10 text-warn", suggested: "bg-brand/10 text-brand", disabled: "bg-ink/5 text-muted",
archived: "bg-ink/5 text-muted",
};
export const KIND_COLOR: Record<string, string> = {
object_type: "#6366f1", link_type: "#8b5cf6", metric: "#0ea5e9", dimension: "#14b8a6",
rule: "#f59e0b", calendar: "#10b981", role: "#ec4899", process: "#ef4444", term: "#64748b",
};
export function fmtTime(s?: string | null): string {
if (!s) return "-";
return s.replace("T", " ").slice(0, 16);
}
export function errText(e: unknown): string {
return e instanceof Error ? e.message : String(e);
}