Elffuss BraidHub

kikocis/utopia public

f9f23e10e2c2 · 40.9 KiBRawPermalink
1import { S, lang } from "./i18n";
2
3export class ApiError extends Error {
4 status: number;
5 /** 服务端给的稳定错误码(没有则是尚未转换的契约守卫,message 已是英文原句) */
6 code?: string;
7 constructor(status: number, message: string, code?: string) {
8 super(message);
9 this.status = status;
10 this.code = code;
11 }
12}
13
14async function request<T>(path: string, init?: RequestInit): Promise<T> {
15 const res = await fetch(path, {
16 credentials: "include",
17 headers:
18 init?.body instanceof FormData
19 ? {}
20 : { "Content-Type": "application/json" },
21 ...init,
22 });
23 if (!res.ok) {
24 // 措辞在这一个收口点定:22 个文件里的 toast.error(e.message) 一处都不用改。
25 // 有 code 就查 i18n,没有(或这一条还没进表)就退回服务端的英文原句——
26 // 服务端永远说英文,因为界面语言在客户端(docs/decisions/0004)
27 let message = res.statusText;
28 let code: string | undefined;
29 try {
30 const body = (await res.json()) as {
31 error?: string;
32 code?: string;
33 detail?: string;
34 };
35 if (body.error) message = body.error;
36 code = body.code;
37 // code 来自网络,不是字面量——这一处 cast 换来 err 表本身的全量类型检查
38 const worded = code
39 ? (S.err as Record<string, string | undefined>)[code]
40 : undefined;
41 if (worded) message = worded;
42 if (body.detail) message = S.errDetail(message, body.detail);
43 } catch {
44 // 非 JSON 响应体,保留 statusText
45 }
46 throw new ApiError(res.status, message, code);
47 }
48 return res.json() as Promise<T>;
49}
50
51export interface User {
52 id: string;
53 org_id: string;
54 email: string;
55 display_name: string;
56 is_admin: boolean;
57 created_at: string;
58}
59
60export interface Workspace {
61 id: string;
62 org_id: string;
63 name: string;
64 created_at: string;
65}
66
67/** 建库时可选的预置本体包(`GET /ontology-packs`)。 */
68export type OntologyPack = {
69 id: string;
70 name: string;
71 summary: string;
72 classes: number;
73 properties: number;
74};
75
76export interface Kb {
77 id: string;
78 workspace_id: string;
79 name: string;
80 kind: string;
81 description: string | null;
82 visibility: "open" | "restricted";
83 /** 部署的公共默认空间(第一个建的库):永远 open、不可删除 */
84 is_default: boolean;
85 /** 抽取遇到本体外的说法时,是否允许系统自动补进本体并改写等它的事实。
86 关掉不影响"留意":未匹配统计照常累积可见,只是变成你点一下的提案 */
87 auto_extend_ontology: boolean;
88 /** 内置本体按哪种语言播种、新描述写哪种语言。**跟语料走,不跟界面走**
89 (界面语言在客户端,见 docs/decisions/0004) */
90 ontology_lang: "en" | "zh";
91 /** 调用者在本库的角色(仅详情接口返回):前端据此门控破坏性入口 */
92 my_role?: "viewer" | "editor" | "admin" | "owner" | null;
93}
94
95/** 账户层"我的知识库"行:库 + 我的角色 + 加入信息 + 概览统计。 */
96export interface MyKb {
97 kb: Kb;
98 my_role: "viewer" | "editor" | "admin" | "owner" | null;
99 joined_at: string | null;
100 added_by_name: string | null;
101 doc_count: number;
102 member_count: number;
103}
104
105/** 审计事件(纯审计展示)。 */
106export interface AuditEvent {
107 id: string;
108 action: string;
109 target_kind: string;
110 target_id: string | null;
111 detail: Record<string, unknown>;
112 actor_name: string | null;
113 created_at: string;
114}
115
116export interface KbMember {
117 user_id: string;
118 email: string;
119 display_name: string;
120 role: "viewer" | "editor" | "admin";
121}
122
123export interface Doc {
124 id: string;
125 kb_id: string;
126 source_id: string | null;
127 filename: string;
128 mime: string;
129 size_bytes: number;
130 status: string;
131 graph_status: string;
132 /** 摄入管道的失败原因 */
133 error: string | null;
134 /** 图谱抽取管道的失败原因(与 error 分列:两条管道各存各的) */
135 graph_error: string | null;
136 chunk_count: number;
137 tags: string[];
138 missing_since: string | null;
139 created_at: string;
140}
141
142/** 一类抽取丢弃在一篇文档里的聚合:事实抽出来了,却没能落地。 */
143export interface ExtractionDrop {
144 document_id: string;
145 /** 稳定的原因码,前端按它查文案(attr_domain_mismatch / low_confidence / ...) */
146 reason: string;
147 /** 该原因下的具体对象(属性 key、谓词名、"salary@organization") */
148 detail: string;
149 count: number;
150 example: string | null;
151}
152
153export interface SourceView {
154 id: string;
155 kind: "folder" | "url" | "rss" | "api" | "custom" | "memory" | "upload";
156 name: string;
157 config: { urls?: string[]; feed_url?: string; endpoint?: string } | null;
158 icon: string | null;
159 sync_interval_minutes: number | null;
160 sync_cron: string | null;
161 last_sync_at: string | null;
162 last_sync_status: "never" | "queued" | "running" | "ok" | "failed";
163 last_sync_error: string | null;
164 last_sync_added: number;
165 doc_count: number;
166 missing_count: number;
167}
168
169export interface SearchResult {
170 id: string;
171 document_id: string;
172 seq: number;
173 text: string;
174 filename: string;
175}
176
177export interface LlmSettingsView {
178 chat_base_url?: string | null;
179 chat_model?: string | null;
180 has_chat_key?: boolean;
181 embed_base_url?: string | null;
182 embed_model?: string | null;
183 embed_dim?: number | null;
184 has_embed_key?: boolean;
185}
186
187export interface Member {
188 user_id: string;
189 email: string;
190 display_name: string;
191 role: string;
192 is_admin: boolean;
193}
194
195export interface OrgUser {
196 id: string;
197 email: string;
198 display_name: string;
199 is_admin: boolean;
200}
201
202/** 问数数据源(凭据不下发,只有 host:port/db 摘要)。 */
203export interface DataSourceView {
204 id: string;
205 name: string;
206 engine: string;
207 summary: string;
208 created_at: string;
209 last_test_at: string | null;
210 last_test_ok: boolean | null;
211}
212
213export interface GraphNode {
214 id: string;
215 name: string;
216 // 没判出类型时为 null(0009)
217 type_key: string | null;
218 type_label: string | null;
219 color: string;
220 shape: "circle" | "square";
221 degree: number;
222 disambiguator: string | null;
223}
224
225export interface SyncRun {
226 id: string;
227 started_at: string;
228 finished_at: string | null;
229 status: "running" | "ok" | "failed";
230 created_docs: number;
231 updated_docs: number;
232 error: string | null;
233}
234
235/** 分块的抽取产物(文档查看器右栏)。 */
236export interface ChunkFact {
237 chunk_id: string;
238 fact_id: string;
239 subject_id: string;
240 subject: string;
241 /** 本体没认下这条关系时是原文说法;两者都拿不出时为 null */
242 predicate: string | null;
243 /** true = 名字来自原文,不是本体认下的关系 */
244 inferred: boolean;
245 object_id: string | null;
246 object: string | null;
247 valid_from: string | null;
248 valid_to: string | null;
249 confidence: number;
250}
251
252export interface ReviewSide {
253 id: string;
254 name: string;
255 // 没判出类型时为 null(0009)
256 type_label: string | null;
257 color: string;
258 disambiguator: string | null;
259 degree: number;
260 top_facts: string[];
261}
262
263export interface ReviewItem {
264 id: string;
265 score: number;
266 reason: string | null;
267 stage: "adjudicating" | "human";
268 created_at: string;
269 left: ReviewSide;
270 right: ReviewSide;
271}
272
273export interface FactReviewItem {
274 id: string;
275 subject_name: string;
276 predicate_label: string | null;
277 object_name: string | null;
278 valid_from: string | null;
279 valid_to: string | null;
280 confidence: number;
281 evidence_count: number;
282 quote: string | null;
283}
284
285/** 时态冲突(自动闭合拿不准的那些):旧事实 vs 新事实。 */
286export interface ConflictItem {
287 id: string;
288 reason: "no_time" | "simultaneous" | "low_confidence";
289 created_at: string;
290 predicate_label: string;
291 old_fact_id: string;
292 old_subject: string;
293 old_object: string | null;
294 old_valid_from: string | null;
295 new_fact_id: string;
296 new_subject: string;
297 new_object: string | null;
298 new_valid_from: string | null;
299 new_confidence: number;
300}
301
302/** 决策台账事件(audit_events 的 review 域切片):detail 是决策时的自包含快照。 */
303export interface ReviewHistoryEvent {
304 id: string;
305 action: string;
306 target_kind: string;
307 target_id: string | null;
308 detail: Record<string, unknown>;
309 /** null = 系统(AI 裁决器) */
310 actor_name: string | null;
311 created_at: string;
312}
313
314export interface MergeLog {
315 id: string;
316 source_name: string;
317 target_name: string;
318 merged_by_name: string | null;
319 reason: string | null;
320 created_at: string;
321 reverted_at: string | null;
322}
323
324export interface GraphEdge {
325 id: string;
326 source: string;
327 target: string;
328 /** 本体没认下这条关系时是原文说法;两者都拿不出时为 null(0052 之前的老数据) */
329 predicate: string | null;
330 label: string | null;
331 /** true = 这条边的名字来自原文,不是本体认下的关系 */
332 inferred: boolean;
333 valid_from: string | null;
334 valid_to: string | null;
335 confidence: number;
336}
337
338export interface EntityFact {
339 id: string;
340 direction: "out" | "in";
341 /** 同 GraphEdge:本体外的关系回落到原文说法,两者都没有时为 null */
342 predicate_key: string | null;
343 predicate_label: string | null;
344 /** true = 名字来自原文,不是本体认下的关系 */
345 inferred: boolean;
346 /** 关系的时态类别。没有谓词就无从谈起,为 null */
347 temporal: string | null;
348 other_id: string | null;
349 other_name: string | null;
350 /** 字面值宾语(属性事实/问数映射):{"value":…} 或 {"summary":…} */
351 object_value: Record<string, unknown> | null;
352 valid_from: string | null;
353 valid_to: string | null;
354 valid_from_precision: string | null;
355 /** year | month | day,外加 unknown = 原文说它结束了但没说哪天 */
356 valid_to_precision: string | null;
357 confidence: number;
358 evidence_count: number;
359 /** 证据全部停留在来源文档的旧版(未被现行内容确认;不代表事实失效) */
360 stale: boolean;
361 /** 修正行:区间闭合来自引擎对账/人工裁决而非抽取原文 */
362 corrected: boolean;
363 /** 证据集合里最新的文档时间(开放事实的"最后确认时间") */
364 last_evidence_time: string | null;
365}
366
367/** 实体的一次认知变更(记录时间轴上的事件,与 EntityFact 的有效时间轴正交)。
368 *
369 * 不是每个事件都来自一条事实:retyped / retype_reverted 来自改类账本,
370 * 没有谓词、没有对方、没有方向。 */
371export interface EntityHistoryEvent {
372 /** 事实事件才有;改类事件为 null */
373 fact_id: string | null;
374 /** 记录时刻:写入 = recorded_at,作废 = invalidated_at,改类 = 改类那一刻 */
375 at: string;
376 kind:
377 | "asserted"
378 | "corrected"
379 | "rejected"
380 | "merged"
381 | "retyped"
382 | "retype_reverted";
383 direction: "out" | "in" | null;
384 predicate_label: string | null;
385 other_name: string | null;
386 object_value: Record<string, unknown> | null;
387 valid_from: string | null;
388 valid_to: string | null;
389 valid_from_precision: string | null;
390 /** year | month | day,外加 unknown = 原文说它结束了但没说哪天 */
391 valid_to_precision: string | null;
392 confidence: number | null;
393 /** null = 引擎自动(抽取写入 / 时态对账闭合 / 高置信自动改类) */
394 actor_name: string | null;
395 action: string | null;
396 document_id: string | null;
397 filename: string | null;
398 quote: string | null;
399 /** 改类事件的两端。起点为 null = 从「未分类」改过来(0009 之后最常见的一种) */
400 from_type_label: string | null;
401 to_type_label: string | null;
402}
403
404export interface Evidence {
405 /** 模型在这一块里实际用的谓词说法。本体外的谓词不落到关系上,界面显示的就是这里 */
406 proposed_predicate: string | null;
407 quote: string | null;
408 chunk_id: string;
409 document_id: string;
410 filename: string;
411 seq: number;
412 /** 证据出自文档的第几版 */
413 doc_version: number;
414 /** 文档已有更新版本(证据停留在旧版;不代表事实失效) */
415 stale: boolean;
416}
417
418export interface ChunkFull {
419 id: string;
420 seq: number;
421 text: string;
422}
423
424export interface EntityTypeView {
425 id: string;
426 key: string;
427 label: string;
428 color: string;
429 shape: "circle" | "square";
430 builtin: boolean;
431 /** 全部父类(subClassOf 可以有多个) */
432 parents: string[];
433 /** 左栏画树时挂在哪一支下。不参与语义,只管展示 */
434 primary_parent: string | null;
435 description: string;
436 usage: number;
437}
438
439export interface RelationTypeView {
440 id: string;
441 key: string;
442 label: string;
443 temporal: string;
444 functional: boolean;
445 inverse_functional: boolean;
446 builtin: boolean;
447 description: string;
448 /** relation(宾语是实体)| attribute(宾语是字面值) */
449 kind: "relation" | "attribute";
450 /** 可以当主语的类。attribute 至少一个;relation 留空 = 不限 */
451 domains: string[];
452 /** 可以当宾语的类。只对 relation 有意义——attribute 的值域是 datatype */
453 ranges: string[];
454 datatype: "text" | "number" | "date" | "bool" | null;
455 unit: string | null;
456 usage: number;
457}
458
459export interface OntologyMiss {
460 kind: "entity_type" | "relation_type";
461 key: string;
462 example: string | null;
463 count: number;
464}
465
466/** `description` 与 `reason` 不是一回事:description 逐字进抽取提示词,是模型判断
467 "什么算这个类"的唯一依据;reason 只是给人看的"为什么该加"。喂错了这个类会成为
468 下一个倾倒场——实测 technology 就是这么来的。 */
469export interface OntologyProposals {
470 entity_types: {
471 key: string;
472 label: string;
473 description?: string;
474 reason?: string;
475 }[];
476 relation_types: {
477 key: string;
478 label: string;
479 temporal?: string;
480 functional?: boolean;
481 description?: string;
482 reason?: string;
483 /** 这条关系归并了哪些表层说法。有它才谈得上把等待的事实改写过去 */
484 forms?: string[];
485 }[];
486 /**
487 * 宾语是字面值的说法("成立日期 = 2015")。
488 *
489 * 跟 relation_types 分开是因为它们要的东西不一样:属性有 datatype,
490 * 而把它当关系建出来,那个值就会变成一个假实体。domain 不在这里——
491 * 服务端从事实的主语类型里取,猜错会让整条被丢弃
492 */
493 attribute_types?: {
494 key: string;
495 label: string;
496 datatype?: string;
497 unit?: string;
498 description?: string;
499 reason?: string;
500 forms?: string[];
501 }[];
502 /**
503 * 本体里**已经有**这个意思,只需把说法挂过去。
504 *
505 * 跟 relation_types 的区别是不建东西:同一个意思长出第二个 key,
506 * 这批事实就永久分在两处,谁也认不出它们本是一回事。
507 */
508 map_to?: {
509 key: string;
510 /** 服务端标的:目标落在关系还是属性上。两条改写路径不一样,
511 而模型只答得出一个 key,看不出它在哪一档 */
512 kind?: string;
513 forms?: string[];
514 reason?: string;
515 }[];
516}
517
518/** 原文说过、本体里没有、因而事实没有谓词的说法。 */
519export interface ProposedPredicate {
520 form: string;
521 fact_count: number;
522 example: string | null;
523}
524
525/** 一个类/属性在这次导入里的去向。key_taken = key 被另一个 IRI 占着,报告但不动 */
526export interface PlannedItem {
527 iri: string;
528 key: string;
529 label: string;
530 has_description: boolean;
531 disposition: "create" | "update" | "key_taken";
532 functional?: boolean;
533 conflict_with?: string | null;
534}
535
536/** 预览与落库返回同一个计划:点确认之后发生的事就是刚看过的事 */
537export interface ImportPlan {
538 format: string;
539 triples: number;
540 classes: PlannedItem[];
541 relations: PlannedItem[];
542 attributes: PlannedItem[];
543 /** 出现过但今天不消费的公理 → 次数。不是已跳过,是暂未投影 */
544 unprojected: [string, number][];
545 classes_without_description: number;
546 functional_relations: number;
547}
548
549export interface OntologyImportView {
550 id: string;
551 filename: string;
552 format: string;
553 byte_size: number;
554 summary: Record<string, unknown>;
555 imported_by_name: string | null;
556 imported_at: string;
557}
558
559export interface Source {
560 n: number;
561 /** 缺省 = 文档 chunk 引用;charter = 内置手册(跳 /docs/{slug}#{anchor}) */
562 kind?: "charter";
563 chunk_id?: string;
564 document_id?: string;
565 slug?: string;
566 anchor?: string;
567 heading?: string;
568 filename: string;
569 excerpt: string;
570}
571
572/** Agentic 对话的行动轨迹(工具调用一步一条)。 */
573export interface ChatStep {
574 kind: "search" | "docs" | "entity" | "facts" | "changes" | "query" | "tool";
575 label: string;
576 detail: string;
577}
578
579/** 会话行(Chat 左栏列表)。 */
580export interface ConversationRow {
581 id: string;
582 title: string;
583 created_at: string;
584 updated_at: string;
585 message_count: number;
586}
587
588/** 会话消息(含落库的行动轨迹与引用,历史回放用)。 */
589export interface ConversationMessage {
590 id: string;
591 role: "user" | "assistant";
592 content: string;
593 steps: ChatStep[];
594 sources: Source[];
595 created_at: string;
596}
597
598/** 告警中心的一组(0005):**连着的、同类的几次故障**。
599 *
600 * 存储那边仍是一次故障一行,折叠在服务端读的时候做——这样翻页数的是组,
601 * 一段连续故障不会被页边界切断。 */
602export type AlertGroup = {
603 kb_id: string | null;
604 /** 系统级告警没有库名 */
605 kb_name: string | null;
606 /** `source.sync_failed` / `llm.unreachable` —— 措辞在 i18n 里按这个查 */
607 kind: string;
608 severity: "info" | "warning" | "error";
609 /** 这一组几次 */
610 count: number;
611 /** 其中我没读过的几次 */
612 unread: number;
613 latest_at: string;
614 /** 跟 latest_at 一起圈出这一组,标已读时原样发回去 */
615 earliest_at: string;
616 /** 明细,最多几条,新的在前 */
617 lines: { name?: string; error?: string; job?: string }[];
618};
619
620export const api = {
621 health: () =>
622 request<{ status: string; name: string; version: string }>(
623 "/api/v1/health",
624 ),
625 me: () => request<User>("/api/v1/auth/me"),
626 alerts: (o: { q?: string; limit?: number; offset?: number }) => {
627 const p = new URLSearchParams();
628 if (o.q?.trim()) p.set("q", o.q.trim());
629 if (o.limit != null) p.set("limit", String(o.limit));
630 if (o.offset) p.set("offset", String(o.offset));
631 return request<{ items: AlertGroup[]; total: number }>(
632 `/api/v1/alerts?${p}`,
633 );
634 },
635 alertsUnread: () => request<{ unread: number }>("/api/v1/alerts/unread"),
636 alertReadGroup: (g: {
637 kb_id: string | null;
638 kind: string;
639 from: string;
640 to: string;
641 }) =>
642 request<{ marked: number }>("/api/v1/alerts/read-group", {
643 method: "POST",
644 body: JSON.stringify(g),
645 }),
646 alertsReadAll: () =>
647 request<{ ok: boolean }>("/api/v1/alerts/read-all", { method: "POST" }),
648 login: (email: string, password: string) =>
649 request<{ user: User }>("/api/v1/auth/login", {
650 method: "POST",
651 body: JSON.stringify({ email, password }),
652 }),
653 register: (email: string, password: string, displayName: string) =>
654 request<{ user: User; workspace: Workspace }>("/api/v1/auth/register", {
655 method: "POST",
656 body: JSON.stringify({ email, password, display_name: displayName }),
657 }),
658 logout: () =>
659 request<{ ok: boolean }>("/api/v1/auth/logout", { method: "POST" }),
660 updateMe: (displayName: string) =>
661 request<User>("/api/v1/auth/me", {
662 method: "PATCH",
663 body: JSON.stringify({ display_name: displayName }),
664 }),
665 changePassword: (currentPassword: string, newPassword: string) =>
666 request<{ ok: boolean }>("/api/v1/auth/password", {
667 method: "POST",
668 body: JSON.stringify({
669 current_password: currentPassword,
670 new_password: newPassword,
671 }),
672 }),
673 workspaces: () => request<Workspace[]>("/api/v1/workspaces"),
674
675 kbs: (workspaceId: string) =>
676 request<Kb[]>(`/api/v1/workspaces/${workspaceId}/kbs`),
677 kbAudit: (kbId: string) =>
678 request<{ events: AuditEvent[] }>(`/api/v1/kbs/${kbId}/audit`),
679 myKbs: (workspaceId: string) =>
680 request<{ kbs: MyKb[] }>(`/api/v1/workspaces/${workspaceId}/my-kbs`),
681 createKb: (
682 workspaceId: string,
683 body: {
684 name: string;
685 description?: string | null;
686 visibility?: string;
687 /** 预置本体包 id,顺序有意义:第一个会认领同名的种子类 */
688 ontology_packs?: string[];
689 },
690 ) =>
691 request<Kb>(`/api/v1/workspaces/${workspaceId}/kbs`, {
692 method: "POST",
693 body: JSON.stringify(body),
694 }),
695
696 ontologyPacks: () =>
697 request<{ packs: OntologyPack[] }>("/api/v1/ontology-packs"),
698
699 kbDetail: (kbId: string) => request<Kb>(`/api/v1/kbs/${kbId}`),
700 updateKb: (kbId: string, body: Record<string, unknown>) =>
701 request<Kb>(`/api/v1/kbs/${kbId}`, {
702 method: "PATCH",
703 body: JSON.stringify(body),
704 }),
705 deleteKb: (kbId: string) =>
706 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}`, { method: "DELETE" }),
707 kbMembers: (kbId: string) =>
708 request<{ members: KbMember[] }>(`/api/v1/kbs/${kbId}/members`),
709 setKbMember: (kbId: string, userId: string, role: string) =>
710 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/members/${userId}`, {
711 method: "PUT",
712 body: JSON.stringify({ role }),
713 }),
714 removeKbMember: (kbId: string, userId: string) =>
715 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/members/${userId}`, {
716 method: "DELETE",
717 }),
718
719 adminDeployment: () =>
720 request<{
721 open_registration: boolean;
722 /** 外层兜底,防任务无限堆积;真正的节流是按模型的限额 */
723 worker_concurrency: number;
724 default_model_concurrency: number;
725 /** 新建知识库的本体语言默认值。**不是界面语言**——那个在客户端 */
726 default_ontology_lang: "en" | "zh";
727 model_limits: {
728 base_url: string;
729 model: string;
730 max_concurrent: number;
731 }[];
732 models_in_use: { base_url: string; model: string; kind: string }[];
733 }>("/api/v1/admin/deployment"),
734 saveAdminDeployment: (
735 openRegistration: boolean,
736 workerConcurrency?: number,
737 defaultModelConcurrency?: number,
738 modelLimit?: {
739 base_url: string;
740 model: string;
741 max_concurrent: number | null;
742 },
743 defaultOntologyLang?: "en" | "zh",
744 ) =>
745 request<{ ok: boolean }>("/api/v1/admin/deployment", {
746 method: "PUT",
747 body: JSON.stringify({
748 open_registration: openRegistration,
749 ...(workerConcurrency !== undefined
750 ? { worker_concurrency: workerConcurrency }
751 : {}),
752 ...(defaultModelConcurrency !== undefined
753 ? { default_model_concurrency: defaultModelConcurrency }
754 : {}),
755 ...(modelLimit ? { model_limit: modelLimit } : {}),
756 ...(defaultOntologyLang
757 ? { default_ontology_lang: defaultOntologyLang }
758 : {}),
759 }),
760 }),
761 adminCreateUser: (body: {
762 email: string;
763 display_name: string;
764 password: string;
765 role: string;
766 }) =>
767 request<{ user: User }>("/api/v1/admin/users", {
768 method: "POST",
769 body: JSON.stringify(body),
770 }),
771
772 adminDataSources: () =>
773 request<{ data_sources: DataSourceView[] }>("/api/v1/admin/data-sources"),
774 adminCreateDataSource: (body: { name: string; conn_string: string }) =>
775 request<{ id: string }>("/api/v1/admin/data-sources", {
776 method: "POST",
777 body: JSON.stringify(body),
778 }),
779 adminDeleteDataSource: (id: string) =>
780 request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}`, {
781 method: "DELETE",
782 }),
783 adminTestDataSource: (id: string) =>
784 request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}/test`, {
785 method: "POST",
786 }),
787 kbDataSources: (kbId: string) =>
788 request<{ data_sources: DataSourceView[] }>(
789 `/api/v1/kbs/${kbId}/data-sources`,
790 ),
791 kbDataSourcesAvailable: (kbId: string) =>
792 request<{ data_sources: DataSourceView[] }>(
793 `/api/v1/kbs/${kbId}/data-sources/available`,
794 ),
795 mountDataSource: (kbId: string, dsId: string) =>
796 request<{ ok: boolean; schema_tables: number }>(
797 `/api/v1/kbs/${kbId}/data-sources/${dsId}`,
798 {
799 method: "PUT",
800 },
801 ),
802 unmountDataSource: (kbId: string, dsId: string) =>
803 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/${dsId}`, {
804 method: "DELETE",
805 }),
806 exploreMappings: (kbId: string) =>
807 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/explore`, {
808 method: "POST",
809 }),
810 syncDataSourceSchema: (kbId: string, dsId: string) =>
811 request<{ ok: boolean; schema_tables: number }>(
812 `/api/v1/kbs/${kbId}/data-sources/${dsId}/sync-schema`,
813 { method: "POST" },
814 ),
815
816 documents: (kbId: string) => request<Doc[]>(`/api/v1/kbs/${kbId}/documents`),
817 /** 整库一次取回:行数按 (文档 × 原因 × 对象) 聚合后很小,避免逐行发请求 */
818 extractionDrops: (kbId: string) =>
819 request<{ drops: ExtractionDrop[] }>(
820 `/api/v1/kbs/${kbId}/extraction-drops`,
821 ),
822 upload: (kbId: string, files: File[], sourceId?: string) => {
823 const form = new FormData();
824 for (const f of files) form.append("files", f, f.name);
825 const qs = sourceId ? `?source=${sourceId}` : "";
826 return request<{ created: Doc[]; skipped: unknown[] }>(
827 `/api/v1/kbs/${kbId}/documents${qs}`,
828 { method: "POST", body: form },
829 );
830 },
831 deleteDocument: (id: string) =>
832 request<{ ok: boolean }>(`/api/v1/documents/${id}`, { method: "DELETE" }),
833
834 search: (kbId: string, q: string) =>
835 request<{ results: SearchResult[] }>(`/api/v1/kbs/${kbId}/search`, {
836 method: "POST",
837 body: JSON.stringify({ q }),
838 }),
839
840 settings: (workspaceId: string) =>
841 request<LlmSettingsView>(`/api/v1/workspaces/${workspaceId}/settings`),
842 saveSettings: (workspaceId: string, body: Record<string, unknown>) =>
843 request<{ ok: boolean }>(`/api/v1/workspaces/${workspaceId}/settings`, {
844 method: "PUT",
845 body: JSON.stringify(body),
846 }),
847 graphOverview: (kbId: string) =>
848 request<{ nodes: GraphNode[]; edges: GraphEdge[] }>(
849 `/api/v1/kbs/${kbId}/graph/overview`,
850 ),
851 graphNeighborhood: (kbId: string, entityId: string) =>
852 request<{ nodes: GraphNode[]; edges: GraphEdge[] }>(
853 `/api/v1/kbs/${kbId}/graph/neighborhood?entity=${entityId}&hops=2`,
854 ),
855 searchEntities: (kbId: string, q: string) =>
856 request<{ entities: GraphNode[] }>(
857 `/api/v1/kbs/${kbId}/entities?q=${encodeURIComponent(q)}`,
858 ),
859 entityDetail: (kbId: string, entityId: string) =>
860 request<{ entity: GraphNode; facts: EntityFact[] }>(
861 `/api/v1/kbs/${kbId}/entities/${entityId}`,
862 ),
863 /** 认知变更历史(记录时间轴):服务端分页 */
864 /** 人工修正实体的类型或名字。同名不拦——返回的 same_name 供界面提示是否合并。 */
865 updateEntity: (
866 kbId: string,
867 entityId: string,
868 body: { type_id?: string; canonical_name?: string },
869 ) =>
870 request<{ entity: GraphNode; same_name: GraphNode[] }>(
871 `/api/v1/kbs/${kbId}/entities/${entityId}`,
872 { method: "PATCH", body: JSON.stringify(body) },
873 ),
874
875 entityHistory: (kbId: string, entityId: string, page: number, per = 30) =>
876 request<{ events: EntityHistoryEvent[]; total: number }>(
877 `/api/v1/kbs/${kbId}/entities/${entityId}/history?page=${page}&per=${per}`,
878 ),
879 factEvidence: (kbId: string, factId: string) =>
880 request<{ evidence: Evidence[] }>(
881 `/api/v1/kbs/${kbId}/facts/${factId}/evidence`,
882 ),
883 documentDetail: (id: string) =>
884 request<{ document: Doc; chunks: ChunkFull[] }>(`/api/v1/documents/${id}`),
885 extractDocument: (id: string) =>
886 request<{ job_id: number }>(`/api/v1/documents/${id}/extract`, {
887 method: "POST",
888 }),
889 reprocessDocument: (id: string) =>
890 request<{ job_id: number }>(`/api/v1/documents/${id}/reprocess`, {
891 method: "POST",
892 }),
893 /** 来源级全量重抽(增量语义:既有决策保留) */
894 reExtractSource: (kbId: string, sourceId: string) =>
895 request<{ queued: number }>(
896 `/api/v1/kbs/${kbId}/sources/${sourceId}/re-extract`,
897 {
898 method: "POST",
899 },
900 ),
901 /** 图谱重建(清算语义:清空图层后全量重抽;KB admin) */
902 rebuildGraph: (kbId: string) =>
903 request<{
904 entities_removed: number;
905 facts_removed: number;
906 queued: number;
907 }>(`/api/v1/kbs/${kbId}/graph/rebuild`, { method: "POST" }),
908
909 ontology: (kbId: string) =>
910 request<{
911 entity_types: EntityTypeView[];
912 relation_types: RelationTypeView[];
913 misses: OntologyMiss[];
914 /** 已忽略的,连同它此后继续累积的计数。抑制照旧,只是看得见 */
915 dismissed_misses: OntologyMiss[];
916 }>(`/api/v1/kbs/${kbId}/ontology`),
917 createEntityType: (kbId: string, body: Record<string, unknown>) =>
918 request<{ id: string }>(`/api/v1/kbs/${kbId}/ontology/entity-types`, {
919 method: "POST",
920 body: JSON.stringify(body),
921 }),
922 updateEntityType: (kbId: string, id: string, body: Record<string, unknown>) =>
923 request<{ ok: boolean }>(
924 `/api/v1/kbs/${kbId}/ontology/entity-types/${id}`,
925 {
926 method: "PATCH",
927 body: JSON.stringify(body),
928 },
929 ),
930 deleteEntityType: (kbId: string, id: string) =>
931 request<{ ok: boolean }>(
932 `/api/v1/kbs/${kbId}/ontology/entity-types/${id}`,
933 {
934 method: "DELETE",
935 },
936 ),
937 typeEntities: (kbId: string, typeId: string, page: number, per = 12) =>
938 request<{
939 entities: { id: string; name: string; fact_count: number }[];
940 total: number;
941 }>(
942 `/api/v1/kbs/${kbId}/ontology/entity-types/${typeId}/entities?page=${page}&per=${per}`,
943 ),
944 createRelationType: (kbId: string, body: Record<string, unknown>) =>
945 request<{ id: string }>(`/api/v1/kbs/${kbId}/ontology/relation-types`, {
946 method: "POST",
947 body: JSON.stringify(body),
948 }),
949 updateRelationType: (
950 kbId: string,
951 id: string,
952 body: Record<string, unknown>,
953 ) =>
954 request<{ ok: boolean }>(
955 `/api/v1/kbs/${kbId}/ontology/relation-types/${id}`,
956 {
957 method: "PATCH",
958 body: JSON.stringify(body),
959 },
960 ),
961 deleteRelationType: (kbId: string, id: string) =>
962 request<{ ok: boolean }>(
963 `/api/v1/kbs/${kbId}/ontology/relation-types/${id}`,
964 {
965 method: "DELETE",
966 },
967 ),
968 /** 上次算出来、还没人表态的提案(0049)。刷新页面靠它,不必重跑模型 */
969 storedProposals: (kbId: string) =>
970 request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/proposals`),
971 /** 一条提案有人表态了。改状态不删行——拒绝留痕,下一轮 Suggest 不再刷回待看 */
972 decideProposal: (
973 kbId: string,
974 section: string,
975 key: string,
976 status: "adopted" | "rejected",
977 ) =>
978 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/proposals`, {
979 method: "POST",
980 body: JSON.stringify({ section, key, status }),
981 }),
982 dismissMiss: (kbId: string, kind: string, key: string) =>
983 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/misses/dismiss`, {
984 method: "POST",
985 body: JSON.stringify({ kind, key }),
986 }),
987 restoreMiss: (kbId: string, kind: string, key: string) =>
988 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/misses/restore`, {
989 method: "POST",
990 body: JSON.stringify({ kind, key }),
991 }),
992 /** reason 只给人看,而人就在这次请求的另一端——所以语言由调用方说,
993 不是后端的设置(docs/decisions/0004)。description 的语言跟知识库走,服务端自己知道 */
994 suggestOntology: (kbId: string) =>
995 request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/suggest`, {
996 method: "POST",
997 body: JSON.stringify({ locale: lang }),
998 }),
999
1000 /** 上传本体文件只算出计划,一个字节都不写库 */
1001 previewOntologyImport: (kbId: string, file: File) => {
1002 const form = new FormData();
1003 form.append("file", file, file.name);
1004 return request<{ filename: string; plan: ImportPlan }>(
1005 `/api/v1/kbs/${kbId}/ontology/imports/preview`,
1006 { method: "POST", body: form },
1007 );
1008 },
1009 /** 执行刚看过的那个计划——服务端重新算一遍,两条路径共用同一段代码 */
1010 applyOntologyImport: (kbId: string, file: File) => {
1011 const form = new FormData();
1012 form.append("file", file, file.name);
1013 return request<{ import_id: string; plan: ImportPlan }>(
1014 `/api/v1/kbs/${kbId}/ontology/imports`,
1015 { method: "POST", body: form },
1016 );
1017 },
1018 ontologyImports: (kbId: string) =>
1019 request<{ imports: OntologyImportView[] }>(
1020 `/api/v1/kbs/${kbId}/ontology/imports`,
1021 ),
1022
1023 proposedPredicates: (kbId: string) =>
1024 request<{ forms: ProposedPredicate[] }>(
1025 `/api/v1/kbs/${kbId}/ontology/proposed-predicates`,
1026 ),
1027 /** 最近一次自动扩本体做了什么,以及还能不能撤销(撤干净了返回 null) */
1028 lastAutoExtension: (kbId: string) =>
1029 request<{
1030 run: {
1031 at: string;
1032 relations: string[] | null;
1033 classes: string[] | null;
1034 facts_remapped: number | null;
1035 batches: string[];
1036 } | null;
1037 }>(`/api/v1/kbs/${kbId}/ontology/auto-extension`),
1038 /** 建关系 **并**把等着它的无谓词事实认过去——后半句才是收益 */
1039 adoptPredicate: (
1040 kbId: string,
1041 body: {
1042 key: string;
1043 /** true = key 指的是已有的关系/属性,只改写事实,不建新类型 */
1044 existing?: boolean;
1045 /** attribute 走另一条改写路径:值要按 datatype 换算 */
1046 kind?: "relation" | "attribute";
1047 datatype?: string;
1048 unit?: string;
1049 label?: string;
1050 temporal?: string;
1051 functional?: boolean;
1052 description?: string;
1053 forms: string[];
1054 },
1055 ) =>
1056 request<{
1057 id: string;
1058 remapped: number;
1059 batch: string;
1060 /** 值换不动那个 datatype、因而没被改写的条数。改写了 3 条丢下 2 条,
1061 只报前半句就是报喜不报忧 */
1062 unconvertible?: number;
1063 }>(`/api/v1/kbs/${kbId}/ontology/adopt-predicate`,
1064 { method: "POST", body: JSON.stringify(body) },
1065 ),
1066 /** 撤销一次采纳:新写的行作废、旧行复活。关系类型留着 */
1067 unadoptPredicate: (kbId: string, batchId: string) =>
1068 request<{ reverted: number }>(
1069 `/api/v1/kbs/${kbId}/ontology/adopt-predicate/${batchId}`,
1070 { method: "DELETE" },
1071 ),
1072
1073 sources: (kbId: string) =>
1074 request<{ sources: SourceView[] }>(`/api/v1/kbs/${kbId}/sources`),
1075 createSource: (kbId: string, body: Record<string, unknown>) =>
1076 request<{ source: SourceView; ingest_token?: string | null }>(
1077 `/api/v1/kbs/${kbId}/sources`,
1078 {
1079 method: "POST",
1080 body: JSON.stringify(body),
1081 },
1082 ),
1083 sourceToken: (kbId: string, sourceId: string) =>
1084 request<{ ingest_token: string | null }>(
1085 `/api/v1/kbs/${kbId}/sources/${sourceId}/token`,
1086 ),
1087 rotateSourceToken: (kbId: string, sourceId: string) =>
1088 request<{ ingest_token: string }>(
1089 `/api/v1/kbs/${kbId}/sources/${sourceId}/rotate-token`,
1090 { method: "POST" },
1091 ),
1092 updateSource: (
1093 kbId: string,
1094 sourceId: string,
1095 body: Record<string, unknown>,
1096 ) =>
1097 request<{ source: SourceView }>(`/api/v1/kbs/${kbId}/sources/${sourceId}`, {
1098 method: "PATCH",
1099 body: JSON.stringify(body),
1100 }),
1101 deleteSource: (kbId: string, sourceId: string) =>
1102 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/sources/${sourceId}`, {
1103 method: "DELETE",
1104 }),
1105 cleanupMissing: (kbId: string, sourceId: string) =>
1106 request<{ deleted: number }>(
1107 `/api/v1/kbs/${kbId}/sources/${sourceId}/missing/cleanup`,
1108 {
1109 method: "POST",
1110 },
1111 ),
1112 syncSource: (kbId: string, sourceId: string) =>
1113 request<{ queued: boolean }>(
1114 `/api/v1/kbs/${kbId}/sources/${sourceId}/sync`,
1115 {
1116 method: "POST",
1117 },
1118 ),
1119 sourceRuns: (kbId: string, sourceId: string) =>
1120 request<{ runs: SyncRun[] }>(
1121 `/api/v1/kbs/${kbId}/sources/${sourceId}/runs`,
1122 ),
1123 documentExtractions: (docId: string) =>
1124 request<{ facts: ChunkFact[] }>(`/api/v1/documents/${docId}/extractions`),
1125
1126 review: (kbId: string) =>
1127 request<{
1128 reviews: ReviewItem[];
1129 facts: FactReviewItem[];
1130 merges: MergeLog[];
1131 conflicts: ConflictItem[];
1132 unconfirmed: FactReviewItem[];
1133 }>(`/api/v1/kbs/${kbId}/review`),
1134 closeFact: (kbId: string, factId: string, validTo: string) =>
1135 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/close`, {
1136 method: "POST",
1137 body: JSON.stringify({ valid_to: validTo }),
1138 }),
1139 resolveConflict: (
1140 kbId: string,
1141 conflictId: string,
1142 body: { action: "close" | "keep" | "reject_new"; close_at?: string },
1143 ) =>
1144 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conflicts/${conflictId}`, {
1145 method: "POST",
1146 body: JSON.stringify(body),
1147 }),
1148 decideReview: (kbId: string, reviewId: string, action: "merge" | "keep") =>
1149 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/${reviewId}`, {
1150 method: "POST",
1151 body: JSON.stringify({ action }),
1152 }),
1153 confirmFact: (kbId: string, factId: string) =>
1154 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/confirm`, {
1155 method: "POST",
1156 }),
1157 rejectFact: (kbId: string, factId: string) =>
1158 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/reject`, {
1159 method: "POST",
1160 }),
1161 revertMerge: (kbId: string, mergeId: string) =>
1162 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/merges/${mergeId}/revert`, {
1163 method: "POST",
1164 }),
1165 reviewHistory: (kbId: string, page: number, per = 20) =>
1166 request<{ events: ReviewHistoryEvent[]; total: number }>(
1167 `/api/v1/kbs/${kbId}/review/history?page=${page}&per=${per}`,
1168 ),
1169
1170 members: (workspaceId: string) =>
1171 request<Member[]>(`/api/v1/workspaces/${workspaceId}/members`),
1172 orgUsers: () => request<OrgUser[]>("/api/v1/users"),
1173 setMemberRole: (workspaceId: string, userId: string, role: string) =>
1174 request<{ ok: boolean }>(
1175 `/api/v1/workspaces/${workspaceId}/members/${userId}`,
1176 {
1177 method: "PUT",
1178 body: JSON.stringify({ role }),
1179 },
1180 ),
1181 removeMember: (workspaceId: string, userId: string) =>
1182 request<{ ok: boolean }>(
1183 `/api/v1/workspaces/${workspaceId}/members/${userId}`,
1184 {
1185 method: "DELETE",
1186 },
1187 ),
1188
1189 testSettings: (workspaceId: string) =>
1190 request<{
1191 chat: { ok: boolean; reply?: string; error?: string };
1192 embed: { ok: boolean; dim?: number; error?: string };
1193 }>(`/api/v1/workspaces/${workspaceId}/settings/test`, { method: "POST" }),
1194};
1195
1196/** RAG 对话:SSE 流式。返回中止函数。 */
1197export const conversationsApi = {
1198 list: (kbId: string) =>
1199 request<{ conversations: ConversationRow[] }>(
1200 `/api/v1/kbs/${kbId}/conversations`,
1201 ),
1202 detail: (kbId: string, id: string) =>
1203 request<{ messages: ConversationMessage[] }>(
1204 `/api/v1/kbs/${kbId}/conversations/${id}`,
1205 ),
1206 remove: (kbId: string, id: string) =>
1207 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conversations/${id}`, {
1208 method: "DELETE",
1209 }),
1210};
1211
1212export function streamChat(
1213 kbId: string,
1214 body: { conversation_id?: string; message: string },
1215 handlers: {
1216 onConversation: (id: string) => void;
1217 onSources: (s: Source[]) => void;
1218 onStep: (s: ChatStep) => void;
1219 onDelta: (text: string) => void;
1220 onDone: () => void;
1221 onError: (message: string) => void;
1222 },
1223): () => void {
1224 const controller = new AbortController();
1225 (async () => {
1226 try {
1227 const res = await fetch(`/api/v1/kbs/${kbId}/chat`, {
1228 method: "POST",
1229 credentials: "include",
1230 headers: { "Content-Type": "application/json" },
1231 body: JSON.stringify(body),
1232 signal: controller.signal,
1233 });
1234 if (!res.ok || !res.body) {
1235 let message = res.statusText;
1236 try {
1237 const body = (await res.json()) as { error?: string };
1238 if (body.error) message = body.error;
1239 } catch {
1240 /* ignore */
1241 }
1242 handlers.onError(message);
1243 return;
1244 }
1245 const reader = res.body.getReader();
1246 const decoder = new TextDecoder();
1247 let buf = "";
1248 for (;;) {
1249 const { done, value } = await reader.read();
1250 if (done) break;
1251 buf += decoder.decode(value, { stream: true });
1252 let idx: number;
1253 while ((idx = buf.indexOf("\n\n")) >= 0) {
1254 const frame = buf.slice(0, idx);
1255 buf = buf.slice(idx + 2);
1256 let event = "message";
1257 let data = "";
1258 for (const line of frame.split("\n")) {
1259 if (line.startsWith("event:")) event = line.slice(6).trim();
1260 else if (line.startsWith("data:")) data += line.slice(5).trim();
1261 }
1262 if (event === "conversation")
1263 handlers.onConversation((JSON.parse(data) as { id: string }).id);
1264 else if (event === "sources")
1265 handlers.onSources(JSON.parse(data || "[]"));
1266 else if (event === "step")
1267 handlers.onStep(JSON.parse(data) as ChatStep);
1268 else if (event === "delta")
1269 handlers.onDelta((JSON.parse(data) as { text: string }).text);
1270 else if (event === "done") handlers.onDone();
1271 else if (event === "error") handlers.onError(data);
1272 }
1273 }
1274 handlers.onDone();
1275 } catch (e) {
1276 if (!controller.signal.aborted) handlers.onError(String(e));
1277 }
1278 })();
1279 return () => controller.abort();
1280}