Elffuss BraidHub

kikocis/utopia public

2be3085b044a · 58.4 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 /** 把推出来的事实写进账本(R1)。**缺省关**——推理往图里加东西,
89 * 而声明可能是错的,不该在用户没表态时就按它改图 */
90 materialize_inferences: boolean;
91 /** 多久重推一次(分钟)。事实持续在变,只靠手点会让派生一直是缺的 */
92 inference_interval_minutes: number;
93 /** 上次推完的时间 */
94 last_inference_at: string | null;
95 /** 内置本体按哪种语言播种、新描述写哪种语言。**跟语料走,不跟界面走**
96 (界面语言在客户端,见 docs/decisions/0004) */
97 ontology_lang: "en" | "zh";
98 /** 调用者在本库的角色(仅详情接口返回):前端据此门控破坏性入口 */
99 my_role?: "viewer" | "editor" | "admin" | "owner" | null;
100}
101
102/** 账户层"我的知识库"行:库 + 我的角色 + 加入信息 + 概览统计。 */
103export interface MyKb {
104 kb: Kb;
105 my_role: "viewer" | "editor" | "admin" | "owner" | null;
106 joined_at: string | null;
107 added_by_name: string | null;
108 doc_count: number;
109 member_count: number;
110}
111
112/** 审计事件(纯审计展示)。 */
113export interface AuditEvent {
114 id: string;
115 action: string;
116 target_kind: string;
117 target_id: string | null;
118 detail: Record<string, unknown>;
119 actor_name: string | null;
120 created_at: string;
121}
122
123export interface KbMember {
124 user_id: string;
125 email: string;
126 display_name: string;
127 role: "viewer" | "editor" | "admin";
128}
129
130export interface Doc {
131 id: string;
132 kb_id: string;
133 source_id: string | null;
134 filename: string;
135 mime: string;
136 size_bytes: number;
137 status: string;
138 graph_status: string;
139 /** 摄入管道的失败原因 */
140 error: string | null;
141 /** 图谱抽取管道的失败原因(与 error 分列:两条管道各存各的) */
142 graph_error: string | null;
143 chunk_count: number;
144 /** 文档标签。**今天没有任何界面用它**——故意留着,理由写在
145 * `migrations/0002_ingest.sql` 的 `tags` 列上 */
146 tags: string[];
147 missing_since: string | null;
148 created_at: string;
149}
150
151/** 一类抽取丢弃在一篇文档里的聚合:事实抽出来了,却没能落地。 */
152export interface ExtractionDrop {
153 document_id: string;
154 /** 稳定的原因码,前端按它查文案(attr_domain_mismatch / low_confidence / ...) */
155 reason: string;
156 /** 该原因下的具体对象(属性 key、谓词名、"salary@organization") */
157 detail: string;
158 count: number;
159 example: string | null;
160}
161
162export interface SourceView {
163 id: string;
164 kind:
165 | "folder"
166 | "url"
167 | "rss"
168 | "api"
169 | "custom"
170 | "github_issues"
171 | "jira_issues"
172 | "memory"
173 | "upload";
174 name: string;
175 config: {
176 urls?: string[];
177 feed_url?: string;
178 endpoint?: string;
179 /** github_issues:owner/name */
180 repo?: string;
181 /** github_issues:PR 在 GitHub 模型里也是工单,默认不收 */
182 include_pull_requests?: boolean;
183 /** jira_issues:站点地址,如 https://issues.apache.org/jira */
184 base_url?: string;
185 /** jira_issues:项目 key,如 KAFKA */
186 project?: string;
187 } | null;
188 icon: string | null;
189 sync_interval_minutes: number | null;
190 sync_cron: string | null;
191 last_sync_at: string | null;
192 last_sync_status: "never" | "queued" | "running" | "ok" | "failed";
193 last_sync_error: string | null;
194 last_sync_added: number;
195 doc_count: number;
196 missing_count: number;
197}
198
199export interface SearchResult {
200 id: string;
201 document_id: string;
202 seq: number;
203 text: string;
204 filename: string;
205}
206
207export interface LlmSettingsView {
208 chat_base_url?: string | null;
209 chat_model?: string | null;
210 has_chat_key?: boolean;
211 embed_base_url?: string | null;
212 embed_model?: string | null;
213 embed_dim?: number | null;
214 has_embed_key?: boolean;
215}
216
217export interface Member {
218 user_id: string;
219 email: string;
220 display_name: string;
221 role: string;
222 is_admin: boolean;
223}
224
225export interface OrgUser {
226 id: string;
227 email: string;
228 display_name: string;
229 is_admin: boolean;
230}
231
232/** 问数数据源(凭据不下发,只有 host:port/db 摘要)。 */
233export interface DataSourceView {
234 id: string;
235 name: string;
236 engine: string;
237 summary: string;
238 created_at: string;
239 last_test_at: string | null;
240 last_test_ok: boolean | null;
241}
242
243export interface GraphNode {
244 id: string;
245 name: string;
246 // 没判出类型时为 null(0009)
247 type_key: string | null;
248 type_label: string | null;
249 color: string;
250 shape: "circle" | "square";
251 degree: number;
252 disambiguator: string | null;
253}
254
255export interface SyncRun {
256 id: string;
257 started_at: string;
258 finished_at: string | null;
259 status: "running" | "ok" | "failed";
260 created_docs: number;
261 updated_docs: number;
262 error: string | null;
263}
264
265/** 分块的抽取产物(文档查看器右栏)。 */
266export interface ChunkFact {
267 chunk_id: string;
268 fact_id: string;
269 subject_id: string;
270 subject: string;
271 /** 本体没认下这条关系时是原文说法;两者都拿不出时为 null */
272 predicate: string | null;
273 /** true = 名字来自原文,不是本体认下的关系 */
274 inferred: boolean;
275 object_id: string | null;
276 object: string | null;
277 valid_from: string | null;
278 valid_to: string | null;
279 confidence: number;
280}
281
282/** 一条推出来的事实,连同它的证明(实体面板的「推出来的」那一档)。
283 *
284 * `premises` 是这一档存在的理由:不给出前提的话,一条派生边跟一条普通的边
285 * 在界面上看不出区别,而那正是「推理污染知识」的样子。 */
286export interface DerivedFact {
287 id: string;
288 subject_id: string;
289 subject: string;
290 object_id: string;
291 object: string;
292 predicate: string;
293 /** 靠哪条规则推的 */
294 rule: "transitive" | "symmetric";
295 valid_from: string | null;
296 valid_to: string | null;
297 confidence: number;
298 derived_at: string;
299 /** 直接前提,按推导顺序 */
300 premises: string[];
301}
302
303/** 审核页的分档。**与服务端的 queue 参数是同一组字面量**——拼错会拿到
304 * 一个明确的 unknown_queue 错误,而不是悄悄的空列表。 */
305export type ReviewQueue =
306 | "duplicates"
307 | "conflicts"
308 | "unconfirmed"
309 | "lowconf"
310 | "mappings"
311 | "violations"
312 | "defects"
313 | "merges";
314
315/** 各档的真实条数。左栏的徽标读它,不读列表长度 */
316export interface ReviewCounts {
317 duplicates: number;
318 conflicts: number;
319 unconfirmed: number;
320 lowconf: number;
321 mappings: number;
322 violations: number;
323 defects: number;
324 merges: number;
325}
326
327/** 类型消解的一条建议:一个待精化的实体、送去检索的画像、以及候选类。
328 *
329 * `profile` 回给调用方是有意的——检索找不着的时候,第一个要看的就是
330 * 「我们拿什么去找的」,而不是猜是画像不对还是类的描述不对。 */
331export interface TypeSuggestion {
332 entity_id: string;
333 name: string;
334 /** 现在挂着的类,可能没有(0009) */
335 coarse: string | null;
336 coarse_description: string | null;
337 proposed_type: string | null;
338 specific_type: string | null;
339 fact_count: number;
340 profile: string;
341 candidates: {
342 id: string;
343 key: string;
344 label: string;
345 description: string;
346 distance: number;
347 }[];
348}
349
350/** 跑完一轮的结果。**三档分开报**:自动改了的、留给人的、裁决说「都不是」的。
351 * 最后那一档带着理由——这一步押在「选择都不是是个体面答案」上,
352 * 不记理由,最大的那一档就是不透明的。 */
353export interface ResolutionOutcome {
354 batch: string | null;
355 retyped: number;
356 for_review: {
357 entity_id: string;
358 name: string;
359 coarse: string | null;
360 from_type_id: string | null;
361 to_type_id: string;
362 choice: string;
363 confidence: number;
364 reason: string | null;
365 /** 选中的类不在粗类的子树里——换的是分类轴,不是往下走一格 */
366 crosses_axis: boolean;
367 }[];
368 left_alone: {
369 name: string;
370 coarse: string | null;
371 specific_type: string | null;
372 reason: string | null;
373 top_candidate: string | null;
374 }[];
375}
376export interface ReviewSide {
377 id: string;
378 name: string;
379 // 没判出类型时为 null(0009)
380 type_label: string | null;
381 color: string;
382 disambiguator: string | null;
383 degree: number;
384 top_facts: string[];
385}
386
387export interface ReviewItem {
388 id: string;
389 score: number;
390 reason: string | null;
391 stage: "adjudicating" | "human";
392 created_at: string;
393 left: ReviewSide;
394 right: ReviewSide;
395}
396
397/** 数据映射的一条口径:业务概念 → 数据资产定义(见 docs/decisions/0011)。
398 *
399 * 字段是列而不是 JSON 里的键——从前它是一条 `mapped_to` 事实,
400 * 这几样全塞在 `object_value` 里。 */
401export interface ConceptMapping {
402 id: string;
403 concept_id: string;
404 concept_name: string;
405 /** 挂载的数据源。同一概念在不同源上可以有不同定义 */
406 source: string;
407 table_name: string | null;
408 expr: string | null;
409 sql: string | null;
410 unit: string | null;
411 summary: string | null;
412 /** 派生指标:算出来的,不是表里的列 */
413 derived: boolean;
414 status: "proposed" | "confirmed" | "rejected";
415}
416/** 一条口径改动之前的样子。**整版快照而不是差异**(0006):
417 * 读的时候要回答的是「当时是什么」,差异得从头重放才答得出来 */
418export interface MappingRevision {
419 id: string;
420 before: Record<string, unknown>;
421 /** 改的人;用户是软删除的,所以归因不会因为人离职而丢 */
422 changed_by_name: string | null;
423 changed_at: string;
424}
425/** 一处公理违规(0002 R0)。判据来自本体自己声明的公理,没声明就不报 */
426export interface AxiomViolation {
427 id: string;
428 kind: "self_loop" | "asymmetry" | "cycle" | "functional";
429 /** 判据来自哪条关系。判「公理写错了」时从这里进本体去改 */
430 predicate: string | null;
431 left_fact: string;
432 left_text: string;
433 /** 自反那一类与 left 相同——一条事实跟自己矛盾 */
434 right_fact: string;
435 right_text: string;
436 /** 环的长度;其余三类为 0 */
437 path_len: number;
438 detected_at: string;
439}
440/** 本体自己的一处自相矛盾。**与 AxiomViolation 不是一回事**:那个说
441 * 「事实与定义抵触」,这个说「定义自己站不住」,后者更根本 */
442export interface OntologyDefect {
443 id: string;
444 kind:
445 | "symmetric_and_asymmetric"
446 | "transitive_and_functional"
447 | "subclass_cycle"
448 | "disjoint_with_ancestor"
449 | "inherits_disjoint";
450 subject_label: string | null;
451 other_label: string | null;
452 path_labels: string[];
453 detected_at: string;
454}
455export interface FactReviewItem {
456 id: string;
457 subject_name: string;
458 predicate_label: string | null;
459 object_name: string | null;
460 valid_from: string | null;
461 valid_to: string | null;
462 confidence: number;
463 evidence_count: number;
464 quote: string | null;
465}
466
467/** 时态冲突(自动闭合拿不准的那些):旧事实 vs 新事实。 */
468export interface ConflictItem {
469 id: string;
470 reason: "no_time" | "simultaneous" | "low_confidence";
471 created_at: string;
472 predicate_label: string;
473 old_fact_id: string;
474 old_subject: string;
475 old_object: string | null;
476 old_valid_from: string | null;
477 new_fact_id: string;
478 new_subject: string;
479 new_object: string | null;
480 new_valid_from: string | null;
481 new_confidence: number;
482}
483
484/** 决策台账事件(audit_events 的 review 域切片):detail 是决策时的自包含快照。 */
485export interface ReviewHistoryEvent {
486 id: string;
487 action: string;
488 target_kind: string;
489 target_id: string | null;
490 detail: Record<string, unknown>;
491 /** null = 系统(AI 裁决器) */
492 actor_name: string | null;
493 created_at: string;
494}
495
496export interface MergeLog {
497 id: string;
498 source_name: string;
499 target_name: string;
500 merged_by_name: string | null;
501 reason: string | null;
502 created_at: string;
503 reverted_at: string | null;
504}
505
506export interface GraphEdge {
507 id: string;
508 source: string;
509 target: string;
510 /** 本体没认下这条关系时是原文说法;两者都拿不出时为 null(0052 之前的老数据) */
511 predicate: string | null;
512 label: string | null;
513 /** true = 这条边的名字来自原文,不是本体认下的关系 */
514 inferred: boolean;
515 /** true = 这条边是**推出来的**,不是任何人断言的(R1)。
516 * 与 `inferred` 不是一回事:那个说「名字来自原文」,这个说「不是谁说的」 */
517 derived: boolean;
518 valid_from: string | null;
519 valid_to: string | null;
520 confidence: number;
521}
522
523export interface EntityFact {
524 id: string;
525 direction: "out" | "in";
526 /** 同 GraphEdge:本体外的关系回落到原文说法,两者都没有时为 null */
527 predicate_key: string | null;
528 predicate_label: string | null;
529 /** true = 名字来自原文,不是本体认下的关系 */
530 inferred: boolean;
531 /** 关系的时态类别。没有谓词就无从谈起,为 null */
532 temporal: string | null;
533 other_id: string | null;
534 other_name: string | null;
535 /** 字面值宾语(属性事实/问数映射):{"value":…} 或 {"summary":…} */
536 object_value: Record<string, unknown> | null;
537 valid_from: string | null;
538 valid_to: string | null;
539 valid_from_precision: string | null;
540 /** year | month | day,外加 unknown = 原文说它结束了但没说哪天 */
541 valid_to_precision: string | null;
542 confidence: number;
543 evidence_count: number;
544 /** 证据全部停留在来源文档的旧版(未被现行内容确认;不代表事实失效) */
545 stale: boolean;
546 /** 修正行:区间闭合来自引擎对账/人工裁决而非抽取原文 */
547 corrected: boolean;
548 /** 证据集合里最新的文档时间(开放事实的"最后确认时间") */
549 last_evidence_time: string | null;
550}
551
552/** 实体的一次认知变更(记录时间轴上的事件,与 EntityFact 的有效时间轴正交)。
553 *
554 * 不是每个事件都来自一条事实:retyped / retype_reverted 来自改类账本,
555 * 没有谓词、没有对方、没有方向。 */
556export interface EntityHistoryEvent {
557 /** 事实事件才有;改类事件为 null */
558 fact_id: string | null;
559 /** 记录时刻:写入 = recorded_at,作废 = invalidated_at,改类 = 改类那一刻 */
560 at: string;
561 kind:
562 | "asserted"
563 | "corrected"
564 | "rejected"
565 | "merged"
566 | "retyped"
567 | "retype_reverted";
568 direction: "out" | "in" | null;
569 predicate_label: string | null;
570 other_name: string | null;
571 object_value: Record<string, unknown> | null;
572 valid_from: string | null;
573 valid_to: string | null;
574 valid_from_precision: string | null;
575 /** year | month | day,外加 unknown = 原文说它结束了但没说哪天 */
576 valid_to_precision: string | null;
577 confidence: number | null;
578 /** null = 引擎自动(抽取写入 / 时态对账闭合 / 高置信自动改类) */
579 actor_name: string | null;
580 action: string | null;
581 document_id: string | null;
582 filename: string | null;
583 quote: string | null;
584 /** 改类事件的两端。起点为 null = 从「未分类」改过来(0009 之后最常见的一种) */
585 from_type_label: string | null;
586 to_type_label: string | null;
587}
588
589export interface Evidence {
590 /** 模型在这一块里实际用的谓词说法。本体外的谓词不落到关系上,界面显示的就是这里 */
591 proposed_predicate: string | null;
592 quote: string | null;
593 chunk_id: string;
594 document_id: string;
595 filename: string;
596 seq: number;
597 /** 证据出自文档的第几版 */
598 doc_version: number;
599 /** 文档已有更新版本(证据停留在旧版;不代表事实失效) */
600 stale: boolean;
601}
602
603export interface ChunkFull {
604 id: string;
605 seq: number;
606 text: string;
607}
608
609export interface EntityTypeView {
610 id: string;
611 key: string;
612 label: string;
613 color: string;
614 shape: "circle" | "square";
615 builtin: boolean;
616 /** 全部父类(subClassOf 可以有多个) */
617 parents: string[];
618 /** 与它互斥的类:**声明「不可能同时是」** */
619 disjoint: string[];
620 /** 左栏画树时挂在哪一支下。不参与语义,只管展示 */
621 primary_parent: string | null;
622 description: string;
623 usage: number;
624}
625
626export interface RelationTypeView {
627 id: string;
628 key: string;
629 label: string;
630 temporal: string;
631 functional: boolean;
632 inverse_functional: boolean;
633 /** 其余四条 OWL 公理。**推理机的判据全在这里** */
634 is_transitive: boolean;
635 is_symmetric: boolean;
636 is_asymmetric: boolean;
637 is_irreflexive: boolean;
638 builtin: boolean;
639 description: string;
640 /** relation(宾语是实体)| attribute(宾语是字面值) */
641 kind: "relation" | "attribute";
642 /** 可以当主语的类。attribute 至少一个;relation 留空 = 不限 */
643 domains: string[];
644 /** 可以当宾语的类。只对 relation 有意义——attribute 的值域是 datatype */
645 ranges: string[];
646 datatype: "text" | "number" | "date" | "bool" | null;
647 unit: string | null;
648 usage: number;
649}
650
651export interface OntologyMiss {
652 kind: "entity_type" | "relation_type";
653 key: string;
654 example: string | null;
655 count: number;
656}
657
658/** `description` 与 `reason` 不是一回事:description 逐字进抽取提示词,是模型判断
659 "什么算这个类"的唯一依据;reason 只是给人看的"为什么该加"。喂错了这个类会成为
660 下一个倾倒场——实测 technology 就是这么来的。 */
661export interface OntologyProposals {
662 entity_types: {
663 key: string;
664 label: string;
665 description?: string;
666 reason?: string;
667 }[];
668 relation_types: {
669 key: string;
670 label: string;
671 temporal?: string;
672 functional?: boolean;
673 description?: string;
674 reason?: string;
675 /** 这条关系归并了哪些表层说法。有它才谈得上把等待的事实改写过去 */
676 forms?: string[];
677 }[];
678 /**
679 * 宾语是字面值的说法("成立日期 = 2015")。
680 *
681 * 跟 relation_types 分开是因为它们要的东西不一样:属性有 datatype,
682 * 而把它当关系建出来,那个值就会变成一个假实体。domain 不在这里——
683 * 服务端从事实的主语类型里取,猜错会让整条被丢弃
684 */
685 attribute_types?: {
686 key: string;
687 label: string;
688 datatype?: string;
689 unit?: string;
690 description?: string;
691 reason?: string;
692 forms?: string[];
693 }[];
694 /**
695 * 本体里**已经有**这个意思,只需把说法挂过去。
696 *
697 * 跟 relation_types 的区别是不建东西:同一个意思长出第二个 key,
698 * 这批事实就永久分在两处,谁也认不出它们本是一回事。
699 */
700 map_to?: {
701 key: string;
702 /** 服务端标的:目标落在关系还是属性上。两条改写路径不一样,
703 而模型只答得出一个 key,看不出它在哪一档 */
704 kind?: string;
705 forms?: string[];
706 reason?: string;
707 }[];
708}
709
710/** 原文说过、本体里没有、因而事实没有谓词的说法。 */
711export interface ProposedPredicate {
712 form: string;
713 fact_count: number;
714 example: string | null;
715}
716
717/** 一个类/属性在这次导入里的去向。key_taken = key 被另一个 IRI 占着,报告但不动 */
718export interface PlannedItem {
719 iri: string;
720 key: string;
721 label: string;
722 has_description: boolean;
723 disposition: "create" | "update" | "key_taken";
724 functional?: boolean;
725 conflict_with?: string | null;
726}
727
728/** 预览与落库返回同一个计划:点确认之后发生的事就是刚看过的事 */
729export interface ImportPlan {
730 format: string;
731 triples: number;
732 classes: PlannedItem[];
733 relations: PlannedItem[];
734 attributes: PlannedItem[];
735 /** 出现过但今天不消费的公理 → 次数。不是已跳过,是暂未投影 */
736 unprojected: [string, number][];
737 classes_without_description: number;
738 functional_relations: number;
739}
740
741export interface OntologyImportView {
742 id: string;
743 filename: string;
744 format: string;
745 byte_size: number;
746 summary: Record<string, unknown>;
747 imported_by_name: string | null;
748 imported_at: string;
749}
750
751export interface Source {
752 n: number;
753 /** 缺省 = 文档 chunk 引用;charter = 内置手册(跳 /docs/{slug}#{anchor}) */
754 kind?: "charter";
755 chunk_id?: string;
756 document_id?: string;
757 slug?: string;
758 anchor?: string;
759 heading?: string;
760 filename: string;
761 excerpt: string;
762}
763
764/** Agentic 对话的行动轨迹(工具调用一步一条)。 */
765export interface ChatStep {
766 kind: "search" | "docs" | "entity" | "facts" | "changes" | "query" | "tool";
767 label: string;
768 detail: string;
769}
770
771/** 会话行(Chat 左栏列表)。 */
772export interface ConversationRow {
773 id: string;
774 title: string;
775 created_at: string;
776 updated_at: string;
777 message_count: number;
778}
779
780/** 会话消息(含落库的行动轨迹与引用,历史回放用)。 */
781export interface ConversationMessage {
782 id: string;
783 role: "user" | "assistant";
784 content: string;
785 steps: ChatStep[];
786 sources: Source[];
787 created_at: string;
788}
789
790/** 告警中心的一组(0005):**连着的、同类的几次故障**。
791 *
792 * 存储那边仍是一次故障一行,折叠在服务端读的时候做——这样翻页数的是组,
793 * 一段连续故障不会被页边界切断。 */
794export type AlertGroup = {
795 kb_id: string | null;
796 /** 系统级告警没有库名 */
797 kb_name: string | null;
798 /** `source.sync_failed` / `llm.unreachable` —— 措辞在 i18n 里按这个查 */
799 kind: string;
800 severity: "info" | "warning" | "error";
801 /** 这一组几次 */
802 count: number;
803 /** 其中我没读过的几次 */
804 unread: number;
805 latest_at: string;
806 /** 跟 latest_at 一起圈出这一组,标已读时原样发回去 */
807 earliest_at: string;
808 /** 明细,最多几条,新的在前 */
809 lines: { name?: string; error?: string; job?: string }[];
810};
811
812export const api = {
813 health: () =>
814 request<{ status: string; name: string; version: string }>(
815 "/api/v1/health",
816 ),
817 me: () => request<User>("/api/v1/auth/me"),
818 alerts: (o: { q?: string; limit?: number; offset?: number }) => {
819 const p = new URLSearchParams();
820 if (o.q?.trim()) p.set("q", o.q.trim());
821 if (o.limit != null) p.set("limit", String(o.limit));
822 if (o.offset) p.set("offset", String(o.offset));
823 return request<{ items: AlertGroup[]; total: number }>(
824 `/api/v1/alerts?${p}`,
825 );
826 },
827 alertsUnread: () => request<{ unread: number }>("/api/v1/alerts/unread"),
828 alertReadGroup: (g: {
829 kb_id: string | null;
830 kind: string;
831 from: string;
832 to: string;
833 }) =>
834 request<{ marked: number }>("/api/v1/alerts/read-group", {
835 method: "POST",
836 body: JSON.stringify(g),
837 }),
838 alertsReadAll: () =>
839 request<{ ok: boolean }>("/api/v1/alerts/read-all", { method: "POST" }),
840 login: (email: string, password: string) =>
841 request<{ user: User }>("/api/v1/auth/login", {
842 method: "POST",
843 body: JSON.stringify({ email, password }),
844 }),
845 register: (email: string, password: string, displayName: string) =>
846 request<{ user: User; workspace: Workspace }>("/api/v1/auth/register", {
847 method: "POST",
848 body: JSON.stringify({ email, password, display_name: displayName }),
849 }),
850 logout: () =>
851 request<{ ok: boolean }>("/api/v1/auth/logout", { method: "POST" }),
852 updateMe: (displayName: string) =>
853 request<User>("/api/v1/auth/me", {
854 method: "PATCH",
855 body: JSON.stringify({ display_name: displayName }),
856 }),
857 changePassword: (currentPassword: string, newPassword: string) =>
858 request<{ ok: boolean }>("/api/v1/auth/password", {
859 method: "POST",
860 body: JSON.stringify({
861 current_password: currentPassword,
862 new_password: newPassword,
863 }),
864 }),
865 workspaces: () => request<Workspace[]>("/api/v1/workspaces"),
866
867 kbs: (workspaceId: string) =>
868 request<Kb[]>(`/api/v1/workspaces/${workspaceId}/kbs`),
869 /** 审计台账。**分页 + 筛选**——台账是合规材料,只看最近 100 条等于查不了历史。
870 * `action` 是前缀:`entity.` 捞出 entity.retyped / entity.renamed 一族。 */
871 kbAudit: (
872 kbId: string,
873 opts: {
874 action?: string;
875 actor?: string;
876 since?: string;
877 until?: string;
878 limit: number;
879 offset: number;
880 },
881 ) => {
882 const p = new URLSearchParams({
883 limit: String(opts.limit),
884 offset: String(opts.offset),
885 });
886 if (opts.action) p.set("action", opts.action);
887 if (opts.actor) p.set("actor", opts.actor);
888 if (opts.since) p.set("since", opts.since);
889 if (opts.until) p.set("until", opts.until);
890 return request<{
891 events: AuditEvent[];
892 total: number;
893 /** 这个库实际发生过的动作,筛选下拉按它填 */
894 actions: string[];
895 }>(`/api/v1/kbs/${kbId}/audit?${p}`);
896 },
897 myKbs: (workspaceId: string) =>
898 request<{ kbs: MyKb[] }>(`/api/v1/workspaces/${workspaceId}/my-kbs`),
899 createKb: (
900 workspaceId: string,
901 body: {
902 name: string;
903 description?: string | null;
904 visibility?: string;
905 /** 预置本体包 id,顺序有意义:第一个会认领同名的种子类 */
906 ontology_packs?: string[];
907 },
908 ) =>
909 request<Kb>(`/api/v1/workspaces/${workspaceId}/kbs`, {
910 method: "POST",
911 body: JSON.stringify(body),
912 }),
913
914 ontologyPacks: () =>
915 request<{ packs: OntologyPack[] }>("/api/v1/ontology-packs"),
916
917 kbDetail: (kbId: string) => request<Kb>(`/api/v1/kbs/${kbId}`),
918 updateKb: (kbId: string, body: Record<string, unknown>) =>
919 request<Kb>(`/api/v1/kbs/${kbId}`, {
920 method: "PATCH",
921 body: JSON.stringify(body),
922 }),
923 deleteKb: (kbId: string) =>
924 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}`, { method: "DELETE" }),
925 kbMembers: (kbId: string) =>
926 request<{ members: KbMember[] }>(`/api/v1/kbs/${kbId}/members`),
927 setKbMember: (kbId: string, userId: string, role: string) =>
928 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/members/${userId}`, {
929 method: "PUT",
930 body: JSON.stringify({ role }),
931 }),
932 removeKbMember: (kbId: string, userId: string) =>
933 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/members/${userId}`, {
934 method: "DELETE",
935 }),
936
937 adminDeployment: () =>
938 request<{
939 open_registration: boolean;
940 /** 外层兜底,防任务无限堆积;真正的节流是按模型的限额 */
941 worker_concurrency: number;
942 default_model_concurrency: number;
943 /** 新建知识库的本体语言默认值。**不是界面语言**——那个在客户端 */
944 default_ontology_lang: "en" | "zh";
945 model_limits: {
946 base_url: string;
947 model: string;
948 max_concurrent: number;
949 }[];
950 models_in_use: { base_url: string; model: string; kind: string }[];
951 }>("/api/v1/admin/deployment"),
952 saveAdminDeployment: (
953 openRegistration: boolean,
954 workerConcurrency?: number,
955 defaultModelConcurrency?: number,
956 modelLimit?: {
957 base_url: string;
958 model: string;
959 max_concurrent: number | null;
960 },
961 defaultOntologyLang?: "en" | "zh",
962 ) =>
963 request<{ ok: boolean }>("/api/v1/admin/deployment", {
964 method: "PUT",
965 body: JSON.stringify({
966 open_registration: openRegistration,
967 ...(workerConcurrency !== undefined
968 ? { worker_concurrency: workerConcurrency }
969 : {}),
970 ...(defaultModelConcurrency !== undefined
971 ? { default_model_concurrency: defaultModelConcurrency }
972 : {}),
973 ...(modelLimit ? { model_limit: modelLimit } : {}),
974 ...(defaultOntologyLang
975 ? { default_ontology_lang: defaultOntologyLang }
976 : {}),
977 }),
978 }),
979 adminCreateUser: (body: {
980 email: string;
981 display_name: string;
982 password: string;
983 role: string;
984 }) =>
985 request<{ user: User }>("/api/v1/admin/users", {
986 method: "POST",
987 body: JSON.stringify(body),
988 }),
989
990 /** 已停用的账号。**没有它恢复就够不着**——那个人从所有列表里消失,
991 * 而恢复接口要的正是他的 id */
992 deactivatedUsers: () => request<OrgUser[]>("/api/v1/users/deactivated"),
993 /** 恢复一个停用的账号 */
994 adminReactivateUser: (userId: string) =>
995 request<{ ok: boolean }>(`/api/v1/admin/users/${userId}`, {
996 method: "POST",
997 }),
998 /** 停用一个账号(软删除)。归因照旧查得到——审计、合并日志、改类账本都靠它 */
999 adminDeactivateUser: (userId: string) =>
1000 request<{ ok: boolean }>(`/api/v1/admin/users/${userId}`, {
1001 method: "DELETE",
1002 }),
1003 adminDataSources: () =>
1004 request<{ data_sources: DataSourceView[] }>("/api/v1/admin/data-sources"),
1005 adminCreateDataSource: (body: { name: string; conn_string: string }) =>
1006 request<{ id: string }>("/api/v1/admin/data-sources", {
1007 method: "POST",
1008 body: JSON.stringify(body),
1009 }),
1010 adminDeleteDataSource: (id: string) =>
1011 request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}`, {
1012 method: "DELETE",
1013 }),
1014 adminTestDataSource: (id: string) =>
1015 request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}/test`, {
1016 method: "POST",
1017 }),
1018 /** 这个源授权给了哪些工作区(0014)。授权与挂载是两层:
1019 * 授权由系统管理员写,挂载由 KB 管理员在授权过的集合里挑 */
1020 dataSourceGrants: (id: string) =>
1021 request<{ workspaces: { id: string; name: string }[] }>(
1022 `/api/v1/admin/data-sources/${id}/grants`,
1023 ),
1024 grantDataSource: (id: string, workspaceId: string) =>
1025 request<{ ok: boolean }>(
1026 `/api/v1/admin/data-sources/${id}/grants/${workspaceId}`,
1027 { method: "PUT" },
1028 ),
1029 /** 收回授权。**连同该工作区里已挂上的一起卸掉**,返回卸了几个 */
1030 revokeDataSource: (id: string, workspaceId: string) =>
1031 request<{ ok: boolean; unmounted: number }>(
1032 `/api/v1/admin/data-sources/${id}/grants/${workspaceId}`,
1033 { method: "DELETE" },
1034 ),
1035
1036 /** 一页口径。**Viewer 就能看**——问数的答案直接由口径决定,
1037 * 看得见答案却看不见口径,等于要人信一个不给看的算法 */
1038 mappings: (
1039 kbId: string,
1040 opts: {
1041 status?: "proposed" | "confirmed" | "rejected";
1042 q?: string;
1043 limit?: number;
1044 offset?: number;
1045 } = {},
1046 ) => {
1047 const p = new URLSearchParams();
1048 if (opts.status) p.set("status", opts.status);
1049 if (opts.q) p.set("q", opts.q);
1050 if (opts.limit != null) p.set("limit", String(opts.limit));
1051 if (opts.offset != null) p.set("offset", String(opts.offset));
1052 const qs = p.toString();
1053 return request<{
1054 items: ConceptMapping[];
1055 total: number;
1056 counts: { proposed: number; confirmed: number; rejected: number };
1057 }>(`/api/v1/kbs/${kbId}/mappings${qs ? `?${qs}` : ""}`);
1058 },
1059 /** 改一条口径。改之前那一版自动进 revisions */
1060 reviseMapping: (
1061 kbId: string,
1062 mappingId: string,
1063 body: {
1064 table_name?: string | null;
1065 expr?: string | null;
1066 sql?: string | null;
1067 unit?: string | null;
1068 summary?: string | null;
1069 derived: boolean;
1070 },
1071 ) =>
1072 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/mappings/${mappingId}`, {
1073 method: "PATCH",
1074 body: JSON.stringify(body),
1075 }),
1076 mappingRevisions: (kbId: string, mappingId: string) =>
1077 request<{ revisions: MappingRevision[] }>(
1078 `/api/v1/kbs/${kbId}/mappings/${mappingId}/revisions`,
1079 ),
1080 kbDataSources: (kbId: string) =>
1081 request<{ data_sources: DataSourceView[] }>(
1082 `/api/v1/kbs/${kbId}/data-sources`,
1083 ),
1084 kbDataSourcesAvailable: (kbId: string) =>
1085 request<{ data_sources: DataSourceView[] }>(
1086 `/api/v1/kbs/${kbId}/data-sources/available`,
1087 ),
1088 /** 挂载。**`schema_error` 非空时挂载仍然成了**——源是真挂上的,只是它的
1089 * 库表结构没摄进来,问数看不见有哪些表。同一件事会进告警中心 */
1090 mountDataSource: (kbId: string, dsId: string) =>
1091 request<{
1092 ok: boolean;
1093 schema_tables: number;
1094 schema_error?: string | null;
1095 }>(`/api/v1/kbs/${kbId}/data-sources/${dsId}`, {
1096 method: "PUT",
1097 }),
1098 unmountDataSource: (kbId: string, dsId: string) =>
1099 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/${dsId}`, {
1100 method: "DELETE",
1101 }),
1102 exploreMappings: (kbId: string) =>
1103 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/explore`, {
1104 method: "POST",
1105 }),
1106 syncDataSourceSchema: (kbId: string, dsId: string) =>
1107 request<{ ok: boolean; schema_tables: number }>(
1108 `/api/v1/kbs/${kbId}/data-sources/${dsId}/sync-schema`,
1109 { method: "POST" },
1110 ),
1111
1112 /** 文库一页。**服务端筛选与分页**——从前一次取回整库、前端切片,
1113 * 而客户端筛选只筛得到已经拿下来的那些 */
1114 documents: (
1115 kbId: string,
1116 opts: {
1117 source?: string;
1118 q?: string;
1119 graph?: string;
1120 limit: number;
1121 offset: number;
1122 },
1123 ) => {
1124 const p = new URLSearchParams({
1125 limit: String(opts.limit),
1126 offset: String(opts.offset),
1127 });
1128 if (opts.source) p.set("source", opts.source);
1129 if (opts.q) p.set("q", opts.q);
1130 if (opts.graph) p.set("graph", opts.graph);
1131 return request<{
1132 docs: Doc[];
1133 total: number;
1134 /** 下面三个**只按来源作用域算**,不受名字/状态筛选影响——
1135 * 它们是批量按钮的作用范围 */
1136 ready: number;
1137 extracting: number;
1138 failed: number;
1139 }>(`/api/v1/kbs/${kbId}/documents?${p}`);
1140 },
1141 /** 一键重试这个作用域里全部抽取失败的文档 */
1142 retryFailedDocs: (kbId: string, source?: string) =>
1143 request<{ queued: number; found: number }>(
1144 `/api/v1/kbs/${kbId}/documents/retry-failed${source ? `?source=${source}` : ""}`,
1145 { method: "POST" },
1146 ),
1147 /** 整库一次取回:行数按 (文档 × 原因 × 对象) 聚合后很小,避免逐行发请求 */
1148 extractionDrops: (kbId: string) =>
1149 request<{ drops: ExtractionDrop[] }>(
1150 `/api/v1/kbs/${kbId}/extraction-drops`,
1151 ),
1152 upload: (kbId: string, files: File[], sourceId?: string) => {
1153 const form = new FormData();
1154 for (const f of files) form.append("files", f, f.name);
1155 const qs = sourceId ? `?source=${sourceId}` : "";
1156 return request<{ created: Doc[]; skipped: unknown[] }>(
1157 `/api/v1/kbs/${kbId}/documents${qs}`,
1158 { method: "POST", body: form },
1159 );
1160 },
1161 deleteDocument: (id: string) =>
1162 request<{ ok: boolean }>(`/api/v1/documents/${id}`, { method: "DELETE" }),
1163
1164 search: (kbId: string, q: string) =>
1165 request<{ results: SearchResult[] }>(`/api/v1/kbs/${kbId}/search`, {
1166 method: "POST",
1167 body: JSON.stringify({ q }),
1168 }),
1169
1170 settings: (workspaceId: string) =>
1171 request<LlmSettingsView>(`/api/v1/workspaces/${workspaceId}/settings`),
1172 saveSettings: (workspaceId: string, body: Record<string, unknown>) =>
1173 request<{ ok: boolean }>(`/api/v1/workspaces/${workspaceId}/settings`, {
1174 method: "PUT",
1175 body: JSON.stringify(body),
1176 }),
1177 graphOverview: (kbId: string, limit?: number) =>
1178 request<{
1179 nodes: GraphNode[];
1180 edges: GraphEdge[];
1181 /** 库里一共有多少。**与 nodes.length 不是一回事**——画布只画度数最高的
1182 * 那一批,把上限当成规模显示是这个接口从前最误导人的地方 */
1183 total_nodes?: number;
1184 total_edges?: number;
1185 }>(
1186 `/api/v1/kbs/${kbId}/graph/overview${limit ? `?limit=${limit}` : ""}`,
1187 ),
1188 /** 邻域视图**没有总数**:它本来就只是一小片,说「共 325 个」没有意义。
1189 * 两个字段声明成可选,好让调用方与总览共用一个类型 */
1190 graphNeighborhood: (kbId: string, entityId: string) =>
1191 request<{
1192 nodes: GraphNode[];
1193 edges: GraphEdge[];
1194 total_nodes?: number;
1195 total_edges?: number;
1196 }>(`/api/v1/kbs/${kbId}/graph/neighborhood?entity=${entityId}&hops=2`),
1197 /** 按名字找实体。**一并回总数**——「宁分勿合」会造出一堆同名,
1198 * 固定十条时想找的那个可能根本不在这十条里 */
1199 searchEntities: (kbId: string, q: string, limit = 10) =>
1200 request<{ entities: GraphNode[]; total: number }>(
1201 `/api/v1/kbs/${kbId}/entities?q=${encodeURIComponent(q)}&limit=${limit}`,
1202 ),
1203 entityDetail: (kbId: string, entityId: string) =>
1204 request<{
1205 entity: GraphNode;
1206 facts: EntityFact[];
1207 /** 推出来的那些**单独一个键**,不掺进 facts:混在同一个列表里,
1208 * 用户看不出「文档里写的」和「引擎推的」的区别 */
1209 derived: DerivedFact[];
1210 /** 同名的其他实体。**打开面板就给**——合并入口要长在能看见同名的地方,
1211 * 而不是藏在「改一次名」之后 */
1212 same_name: GraphNode[];
1213 }>(`/api/v1/kbs/${kbId}/entities/${entityId}`),
1214 /** 认知变更历史(记录时间轴):服务端分页 */
1215 /** 人工修正实体的类型或名字。同名不拦——返回的 same_name 供界面提示是否合并。 */
1216 updateEntity: (
1217 kbId: string,
1218 entityId: string,
1219 body: { type_id?: string; canonical_name?: string },
1220 ) =>
1221 request<{ entity: GraphNode; same_name: GraphNode[] }>(
1222 `/api/v1/kbs/${kbId}/entities/${entityId}`,
1223 { method: "PATCH", body: JSON.stringify(body) },
1224 ),
1225
1226 entityHistory: (kbId: string, entityId: string, page: number, per = 30) =>
1227 request<{ events: EntityHistoryEvent[]; total: number }>(
1228 `/api/v1/kbs/${kbId}/entities/${entityId}/history?page=${page}&per=${per}`,
1229 ),
1230 factEvidence: (kbId: string, factId: string) =>
1231 request<{ evidence: Evidence[] }>(
1232 `/api/v1/kbs/${kbId}/facts/${factId}/evidence`,
1233 ),
1234 documentDetail: (id: string) =>
1235 request<{ document: Doc; chunks: ChunkFull[] }>(`/api/v1/documents/${id}`),
1236 extractDocument: (id: string) =>
1237 request<{ job_id: number }>(`/api/v1/documents/${id}/extract`, {
1238 method: "POST",
1239 }),
1240 reprocessDocument: (id: string) =>
1241 request<{ job_id: number }>(`/api/v1/documents/${id}/reprocess`, {
1242 method: "POST",
1243 }),
1244 /** 来源级全量重抽(增量语义:既有决策保留) */
1245 reExtractSource: (kbId: string, sourceId: string) =>
1246 request<{ queued: number }>(
1247 `/api/v1/kbs/${kbId}/sources/${sourceId}/re-extract`,
1248 {
1249 method: "POST",
1250 },
1251 ),
1252 /** 图谱重建(清算语义:清空图层后全量重抽;KB admin) */
1253 rebuildGraph: (kbId: string) =>
1254 request<{
1255 entities_removed: number;
1256 facts_removed: number;
1257 queued: number;
1258 }>(`/api/v1/kbs/${kbId}/graph/rebuild`, { method: "POST" }),
1259
1260 ontology: (kbId: string) =>
1261 request<{
1262 entity_types: EntityTypeView[];
1263 relation_types: RelationTypeView[];
1264 misses: OntologyMiss[];
1265 /** 已忽略的,连同它此后继续累积的计数。抑制照旧,只是看得见 */
1266 dismissed_misses: OntologyMiss[];
1267 }>(`/api/v1/kbs/${kbId}/ontology`),
1268 createEntityType: (kbId: string, body: Record<string, unknown>) =>
1269 request<{ id: string }>(`/api/v1/kbs/${kbId}/ontology/entity-types`, {
1270 method: "POST",
1271 body: JSON.stringify(body),
1272 }),
1273 updateEntityType: (kbId: string, id: string, body: Record<string, unknown>) =>
1274 request<{ ok: boolean }>(
1275 `/api/v1/kbs/${kbId}/ontology/entity-types/${id}`,
1276 {
1277 method: "PATCH",
1278 body: JSON.stringify(body),
1279 },
1280 ),
1281 deleteEntityType: (kbId: string, id: string) =>
1282 request<{ ok: boolean }>(
1283 `/api/v1/kbs/${kbId}/ontology/entity-types/${id}`,
1284 {
1285 method: "DELETE",
1286 },
1287 ),
1288 typeEntities: (kbId: string, typeId: string, page: number, per = 12) =>
1289 request<{
1290 entities: { id: string; name: string; fact_count: number }[];
1291 total: number;
1292 }>(
1293 `/api/v1/kbs/${kbId}/ontology/entity-types/${typeId}/entities?page=${page}&per=${per}`,
1294 ),
1295 createRelationType: (kbId: string, body: Record<string, unknown>) =>
1296 request<{ id: string }>(`/api/v1/kbs/${kbId}/ontology/relation-types`, {
1297 method: "POST",
1298 body: JSON.stringify(body),
1299 }),
1300 updateRelationType: (
1301 kbId: string,
1302 id: string,
1303 body: Record<string, unknown>,
1304 ) =>
1305 request<{ ok: boolean }>(
1306 `/api/v1/kbs/${kbId}/ontology/relation-types/${id}`,
1307 {
1308 method: "PATCH",
1309 body: JSON.stringify(body),
1310 },
1311 ),
1312 deleteRelationType: (kbId: string, id: string) =>
1313 request<{ ok: boolean }>(
1314 `/api/v1/kbs/${kbId}/ontology/relation-types/${id}`,
1315 {
1316 method: "DELETE",
1317 },
1318 ),
1319 /** 上次算出来、还没人表态的提案(0049)。刷新页面靠它,不必重跑模型 */
1320 storedProposals: (kbId: string) =>
1321 request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/proposals`),
1322 /** 一条提案有人表态了。改状态不删行——拒绝留痕,下一轮 Suggest 不再刷回待看 */
1323 decideProposal: (
1324 kbId: string,
1325 section: string,
1326 key: string,
1327 status: "adopted" | "rejected",
1328 ) =>
1329 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/proposals`, {
1330 method: "POST",
1331 body: JSON.stringify({ section, key, status }),
1332 }),
1333 dismissMiss: (kbId: string, kind: string, key: string) =>
1334 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/misses/dismiss`, {
1335 method: "POST",
1336 body: JSON.stringify({ kind, key }),
1337 }),
1338 restoreMiss: (kbId: string, kind: string, key: string) =>
1339 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/misses/restore`, {
1340 method: "POST",
1341 body: JSON.stringify({ kind, key }),
1342 }),
1343 /** reason 只给人看,而人就在这次请求的另一端——所以语言由调用方说,
1344 不是后端的设置(docs/decisions/0004)。description 的语言跟知识库走,服务端自己知道 */
1345 suggestOntology: (kbId: string) =>
1346 request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/suggest`, {
1347 method: "POST",
1348 body: JSON.stringify({ locale: lang }),
1349 }),
1350
1351 /** 上传本体文件只算出计划,一个字节都不写库 */
1352 previewOntologyImport: (kbId: string, file: File) => {
1353 const form = new FormData();
1354 form.append("file", file, file.name);
1355 return request<{ filename: string; plan: ImportPlan }>(
1356 `/api/v1/kbs/${kbId}/ontology/imports/preview`,
1357 { method: "POST", body: form },
1358 );
1359 },
1360 /** 执行刚看过的那个计划——服务端重新算一遍,两条路径共用同一段代码 */
1361 applyOntologyImport: (kbId: string, file: File) => {
1362 const form = new FormData();
1363 form.append("file", file, file.name);
1364 return request<{ import_id: string; plan: ImportPlan }>(
1365 `/api/v1/kbs/${kbId}/ontology/imports`,
1366 { method: "POST", body: form },
1367 );
1368 },
1369 ontologyImports: (kbId: string) =>
1370 request<{ imports: OntologyImportView[] }>(
1371 `/api/v1/kbs/${kbId}/ontology/imports`,
1372 ),
1373
1374 proposedPredicates: (kbId: string) =>
1375 request<{ forms: ProposedPredicate[] }>(
1376 `/api/v1/kbs/${kbId}/ontology/proposed-predicates`,
1377 ),
1378 /** 最近一次自动扩本体做了什么,以及还能不能撤销(撤干净了返回 null) */
1379 lastAutoExtension: (kbId: string) =>
1380 request<{
1381 run: {
1382 at: string;
1383 relations: string[] | null;
1384 classes: string[] | null;
1385 facts_remapped: number | null;
1386 batches: string[];
1387 } | null;
1388 }>(`/api/v1/kbs/${kbId}/ontology/auto-extension`),
1389 /** 建关系 **并**把等着它的无谓词事实认过去——后半句才是收益 */
1390 adoptPredicate: (
1391 kbId: string,
1392 body: {
1393 key: string;
1394 /** true = key 指的是已有的关系/属性,只改写事实,不建新类型 */
1395 existing?: boolean;
1396 /** attribute 走另一条改写路径:值要按 datatype 换算 */
1397 kind?: "relation" | "attribute";
1398 datatype?: string;
1399 unit?: string;
1400 label?: string;
1401 temporal?: string;
1402 functional?: boolean;
1403 description?: string;
1404 forms: string[];
1405 },
1406 ) =>
1407 request<{
1408 id: string;
1409 remapped: number;
1410 batch: string;
1411 /** 值换不动那个 datatype、因而没被改写的条数。改写了 3 条丢下 2 条,
1412 只报前半句就是报喜不报忧 */
1413 unconvertible?: number;
1414 }>(`/api/v1/kbs/${kbId}/ontology/adopt-predicate`, {
1415 method: "POST",
1416 body: JSON.stringify(body),
1417 }),
1418 /** 撤销一次采纳:新写的行作废、旧行复活。关系类型留着 */
1419 unadoptPredicate: (kbId: string, batchId: string) =>
1420 request<{ reverted: number }>(
1421 `/api/v1/kbs/${kbId}/ontology/adopt-predicate/${batchId}`,
1422 { method: "DELETE" },
1423 ),
1424
1425 sources: (kbId: string) =>
1426 request<{ sources: SourceView[] }>(`/api/v1/kbs/${kbId}/sources`),
1427 createSource: (kbId: string, body: Record<string, unknown>) =>
1428 request<{ source: SourceView; ingest_token?: string | null }>(
1429 `/api/v1/kbs/${kbId}/sources`,
1430 {
1431 method: "POST",
1432 body: JSON.stringify(body),
1433 },
1434 ),
1435 sourceToken: (kbId: string, sourceId: string) =>
1436 request<{ ingest_token: string | null }>(
1437 `/api/v1/kbs/${kbId}/sources/${sourceId}/token`,
1438 ),
1439 rotateSourceToken: (kbId: string, sourceId: string) =>
1440 request<{ ingest_token: string }>(
1441 `/api/v1/kbs/${kbId}/sources/${sourceId}/rotate-token`,
1442 { method: "POST" },
1443 ),
1444 updateSource: (
1445 kbId: string,
1446 sourceId: string,
1447 body: Record<string, unknown>,
1448 ) =>
1449 request<{ source: SourceView }>(`/api/v1/kbs/${kbId}/sources/${sourceId}`, {
1450 method: "PATCH",
1451 body: JSON.stringify(body),
1452 }),
1453 deleteSource: (kbId: string, sourceId: string) =>
1454 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/sources/${sourceId}`, {
1455 method: "DELETE",
1456 }),
1457 cleanupMissing: (kbId: string, sourceId: string) =>
1458 request<{ deleted: number }>(
1459 `/api/v1/kbs/${kbId}/sources/${sourceId}/missing/cleanup`,
1460 {
1461 method: "POST",
1462 },
1463 ),
1464 syncSource: (kbId: string, sourceId: string) =>
1465 request<{ queued: boolean }>(
1466 `/api/v1/kbs/${kbId}/sources/${sourceId}/sync`,
1467 {
1468 method: "POST",
1469 },
1470 ),
1471 sourceRuns: (kbId: string, sourceId: string) =>
1472 request<{ runs: SyncRun[] }>(
1473 `/api/v1/kbs/${kbId}/sources/${sourceId}/runs`,
1474 ),
1475 documentExtractions: (docId: string) =>
1476 request<{ facts: ChunkFact[] }>(`/api/v1/documents/${docId}/extractions`),
1477
1478 /** 审核队列的各档**真实条数**。与列表分开取——列表有一页的上限,数数没有。
1479 * 从前徽标读的是数组长度,而接口固定只回 100 条,于是 164 条写成 100。 */
1480 review: (kbId: string, queue: ReviewQueue, limit: number, offset: number) =>
1481 request<{
1482 counts: ReviewCounts;
1483 queue: ReviewQueue;
1484 /** 只有当前这一档的一页。类型按档不同,调用处按 queue 收窄 */
1485 items: unknown[];
1486 }>(
1487 `/api/v1/kbs/${kbId}/review?queue=${queue}&limit=${limit}&offset=${offset}`,
1488 ),
1489 closeFact: (kbId: string, factId: string, validTo: string) =>
1490 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/close`, {
1491 method: "POST",
1492 body: JSON.stringify({ valid_to: validTo }),
1493 }),
1494 resolveConflict: (
1495 kbId: string,
1496 conflictId: string,
1497 body: { action: "close" | "keep" | "reject_new"; close_at?: string },
1498 ) =>
1499 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conflicts/${conflictId}`, {
1500 method: "POST",
1501 body: JSON.stringify(body),
1502 }),
1503 decideReview: (kbId: string, reviewId: string, action: "merge" | "keep") =>
1504 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/${reviewId}`, {
1505 method: "POST",
1506 body: JSON.stringify({ action }),
1507 }),
1508 /** 对一条数据映射口径表态(0011)。改状态不删行——拒绝留痕,下一轮探索不再提议它 */
1509 decideMapping: (
1510 kbId: string,
1511 mappingId: string,
1512 status: "confirmed" | "rejected",
1513 ) =>
1514 request<{ ok: boolean }>(
1515 `/api/v1/kbs/${kbId}/review/mappings/${mappingId}`,
1516 {
1517 method: "POST",
1518 body: JSON.stringify({ status }),
1519 },
1520 ),
1521 /** 跑一遍一致性检查。同步返回——纯计算,没有模型调用也没有网络 */
1522 runConsistencyCheck: (kbId: string) =>
1523 request<{
1524 edges: number;
1525 /** **零和零不一样**:没有公理时结论是「没有判据」,不是「未发现矛盾」 */
1526 predicates_with_axioms: number;
1527 found: number;
1528 inserted: number;
1529 cleared: number;
1530 classes: number;
1531 /** 本体自己的矛盾**单独回**,不加进 found:两个数不是一类东西 */
1532 defects_found: number;
1533 defects_new: number;
1534 }>(`/api/v1/kbs/${kbId}/consistency/check`, { method: "POST" }),
1535 /** 对一处本体缺陷表态。**两个出路**——它压根没看数据,没有「数据错了」这条 */
1536 decideDefect: (
1537 kbId: string,
1538 defectId: string,
1539 resolution: "fixed" | "accepted",
1540 ) =>
1541 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/defects/${defectId}`, {
1542 method: "POST",
1543 body: JSON.stringify({ resolution }),
1544 }),
1545 /** 跑一遍推理(R1)。开关关着时后端回 inference_off */
1546 /** 类型消解:**只算不写**。回执里带着送去检索的画像——检索找不着时,
1547 * 第一个要看的就是「我们拿什么去找的」 */
1548 /** 手动合并:把 source 并进 target。**方向要紧**——source 消失,
1549 * 它的事实搬到 target 上;合并可整体回滚(entity_merges 记着快照) */
1550 mergeEntities: (kbId: string, source: string, target: string) =>
1551 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/entities/merge`, {
1552 method: "POST",
1553 body: JSON.stringify({ source, target }),
1554 }),
1555 typeResolutionPreview: (kbId: string) =>
1556 request<{ items: TypeSuggestion[] }>(
1557 `/api/v1/kbs/${kbId}/ontology/type-resolution/preview`,
1558 { method: "POST" },
1559 ),
1560 /** 跑一遍并落库。三档分开回:自动改的、留给人的、说「都不是」的 */
1561 typeResolutionApply: (kbId: string) =>
1562 request<ResolutionOutcome>(`/api/v1/kbs/${kbId}/ontology/type-resolution`, {
1563 method: "POST",
1564 }),
1565 /** 认可一个「粗类 → 细类」的配对,并把带上的实体改过去。
1566 * **认可的是类对,改的是实体**——认可一次,之后同一对不再进人工 */
1567 approveRefinement: (
1568 kbId: string,
1569 body: { from_type_id: string; to_type_id: string; entity_ids: string[] },
1570 ) =>
1571 request<{ retyped: number }>(
1572 `/api/v1/kbs/${kbId}/ontology/type-resolution/approve`,
1573 { method: "POST", body: JSON.stringify(body) },
1574 ),
1575 /** 撤销一整批:把那批实体放回原来的类 */
1576 typeResolutionUndo: (kbId: string, batchId: string) =>
1577 request<{ reverted: number }>(
1578 `/api/v1/kbs/${kbId}/ontology/type-resolution/${batchId}`,
1579 { method: "DELETE" },
1580 ),
1581 runInference: (kbId: string) =>
1582 request<{
1583 /** 编译出来的规则条数。为零时是「没有规则」而不是「推不出东西」 */
1584 rules: number;
1585 edges: number;
1586 derived: number;
1587 inserted: number;
1588 /** 前提没了、跟着作废的 */
1589 invalidated: number;
1590 /** 撞上单谓词上限、没推完的谓词个数 */
1591 capped: number;
1592 }>(`/api/v1/kbs/${kbId}/inference/run`, { method: "POST" }),
1593 /** 对一处公理违规表态。三个出路——第三个是这一档独有的:可能是定义错了 */
1594 decideViolation: (
1595 kbId: string,
1596 violationId: string,
1597 resolution: "fact_retracted" | "axiom_relaxed" | "accepted",
1598 ) =>
1599 request<{ ok: boolean }>(
1600 `/api/v1/kbs/${kbId}/review/violations/${violationId}`,
1601 { method: "POST", body: JSON.stringify({ resolution }) },
1602 ),
1603 confirmFact: (kbId: string, factId: string) =>
1604 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/confirm`, {
1605 method: "POST",
1606 }),
1607 rejectFact: (kbId: string, factId: string) =>
1608 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/reject`, {
1609 method: "POST",
1610 }),
1611 revertMerge: (kbId: string, mergeId: string) =>
1612 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/merges/${mergeId}/revert`, {
1613 method: "POST",
1614 }),
1615 reviewHistory: (kbId: string, page: number, per = 20) =>
1616 request<{ events: ReviewHistoryEvent[]; total: number }>(
1617 `/api/v1/kbs/${kbId}/review/history?page=${page}&per=${per}`,
1618 ),
1619
1620 members: (workspaceId: string) =>
1621 request<Member[]>(`/api/v1/workspaces/${workspaceId}/members`),
1622 orgUsers: () => request<OrgUser[]>("/api/v1/users"),
1623 setMemberRole: (workspaceId: string, userId: string, role: string) =>
1624 request<{ ok: boolean }>(
1625 `/api/v1/workspaces/${workspaceId}/members/${userId}`,
1626 {
1627 method: "PUT",
1628 body: JSON.stringify({ role }),
1629 },
1630 ),
1631 removeMember: (workspaceId: string, userId: string) =>
1632 request<{ ok: boolean }>(
1633 `/api/v1/workspaces/${workspaceId}/members/${userId}`,
1634 {
1635 method: "DELETE",
1636 },
1637 ),
1638
1639 testSettings: (workspaceId: string) =>
1640 request<{
1641 chat: { ok: boolean; reply?: string; error?: string };
1642 embed: { ok: boolean; dim?: number; error?: string };
1643 }>(`/api/v1/workspaces/${workspaceId}/settings/test`, { method: "POST" }),
1644};
1645
1646/** RAG 对话:SSE 流式。返回中止函数。 */
1647export const conversationsApi = {
1648 /** **可搜可翻页**:标题会重(同一个问题问两次就重了),而固定一百条之后的
1649 * 会话界面上根本不存在。搜的是标题与消息正文两处——人记得住的往往是
1650 * 问过的那句话,不是标题 */
1651 list: (kbId: string, q = "", limit = 30, offset = 0) => {
1652 const p = new URLSearchParams({
1653 limit: String(limit),
1654 offset: String(offset),
1655 });
1656 if (q.trim()) p.set("q", q.trim());
1657 return request<{ conversations: ConversationRow[]; total: number }>(
1658 `/api/v1/kbs/${kbId}/conversations?${p}`,
1659 );
1660 },
1661 /** 改标题。标题本来是从第一句话自动取的,而一段对话跑偏是常态 */
1662 rename: (kbId: string, id: string, title: string) =>
1663 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conversations/${id}`, {
1664 method: "PATCH",
1665 body: JSON.stringify({ title }),
1666 }),
1667 detail: (kbId: string, id: string) =>
1668 request<{ messages: ConversationMessage[] }>(
1669 `/api/v1/kbs/${kbId}/conversations/${id}`,
1670 ),
1671 remove: (kbId: string, id: string) =>
1672 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conversations/${id}`, {
1673 method: "DELETE",
1674 }),
1675};
1676
1677export function streamChat(
1678 kbId: string,
1679 body: { conversation_id?: string; message: string },
1680 handlers: {
1681 onConversation: (id: string) => void;
1682 onSources: (s: Source[]) => void;
1683 onStep: (s: ChatStep) => void;
1684 onDelta: (text: string) => void;
1685 onDone: () => void;
1686 onError: (message: string) => void;
1687 },
1688): () => void {
1689 const controller = new AbortController();
1690 (async () => {
1691 try {
1692 const res = await fetch(`/api/v1/kbs/${kbId}/chat`, {
1693 method: "POST",
1694 credentials: "include",
1695 headers: { "Content-Type": "application/json" },
1696 body: JSON.stringify(body),
1697 signal: controller.signal,
1698 });
1699 if (!res.ok || !res.body) {
1700 let message = res.statusText;
1701 try {
1702 const body = (await res.json()) as { error?: string };
1703 if (body.error) message = body.error;
1704 } catch {
1705 /* ignore */
1706 }
1707 handlers.onError(message);
1708 return;
1709 }
1710 const reader = res.body.getReader();
1711 const decoder = new TextDecoder();
1712 let buf = "";
1713 for (;;) {
1714 const { done, value } = await reader.read();
1715 if (done) break;
1716 buf += decoder.decode(value, { stream: true });
1717 let idx: number;
1718 while ((idx = buf.indexOf("\n\n")) >= 0) {
1719 const frame = buf.slice(0, idx);
1720 buf = buf.slice(idx + 2);
1721 let event = "message";
1722 let data = "";
1723 for (const line of frame.split("\n")) {
1724 if (line.startsWith("event:")) event = line.slice(6).trim();
1725 else if (line.startsWith("data:")) data += line.slice(5).trim();
1726 }
1727 if (event === "conversation")
1728 handlers.onConversation((JSON.parse(data) as { id: string }).id);
1729 else if (event === "sources")
1730 handlers.onSources(JSON.parse(data || "[]"));
1731 else if (event === "step")
1732 handlers.onStep(JSON.parse(data) as ChatStep);
1733 else if (event === "delta")
1734 handlers.onDelta((JSON.parse(data) as { text: string }).text);
1735 else if (event === "done") handlers.onDone();
1736 else if (event === "error") handlers.onError(data);
1737 }
1738 }
1739 handlers.onDone();
1740 } catch (e) {
1741 if (!controller.signal.aborted) handlers.onError(String(e));
1742 }
1743 })();
1744 return () => controller.abort();
1745}