Elffuss BraidHub

kikocis/utopia public

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