Elffuss BraidHub

kikocis/utopia public

18eb6b0051a2 · 58.1 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 mountDataSource: (kbId: string, dsId: string) =>
1089 request<{ ok: boolean; schema_tables: number }>(
1090 `/api/v1/kbs/${kbId}/data-sources/${dsId}`,
1091 {
1092 method: "PUT",
1093 },
1094 ),
1095 unmountDataSource: (kbId: string, dsId: string) =>
1096 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/${dsId}`, {
1097 method: "DELETE",
1098 }),
1099 exploreMappings: (kbId: string) =>
1100 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/explore`, {
1101 method: "POST",
1102 }),
1103 syncDataSourceSchema: (kbId: string, dsId: string) =>
1104 request<{ ok: boolean; schema_tables: number }>(
1105 `/api/v1/kbs/${kbId}/data-sources/${dsId}/sync-schema`,
1106 { method: "POST" },
1107 ),
1108
1109 /** 文库一页。**服务端筛选与分页**——从前一次取回整库、前端切片,
1110 * 而客户端筛选只筛得到已经拿下来的那些 */
1111 documents: (
1112 kbId: string,
1113 opts: {
1114 source?: string;
1115 q?: string;
1116 graph?: string;
1117 limit: number;
1118 offset: number;
1119 },
1120 ) => {
1121 const p = new URLSearchParams({
1122 limit: String(opts.limit),
1123 offset: String(opts.offset),
1124 });
1125 if (opts.source) p.set("source", opts.source);
1126 if (opts.q) p.set("q", opts.q);
1127 if (opts.graph) p.set("graph", opts.graph);
1128 return request<{
1129 docs: Doc[];
1130 total: number;
1131 /** 下面三个**只按来源作用域算**,不受名字/状态筛选影响——
1132 * 它们是批量按钮的作用范围 */
1133 ready: number;
1134 extracting: number;
1135 failed: number;
1136 }>(`/api/v1/kbs/${kbId}/documents?${p}`);
1137 },
1138 /** 一键重试这个作用域里全部抽取失败的文档 */
1139 retryFailedDocs: (kbId: string, source?: string) =>
1140 request<{ queued: number; found: number }>(
1141 `/api/v1/kbs/${kbId}/documents/retry-failed${source ? `?source=${source}` : ""}`,
1142 { method: "POST" },
1143 ),
1144 /** 整库一次取回:行数按 (文档 × 原因 × 对象) 聚合后很小,避免逐行发请求 */
1145 extractionDrops: (kbId: string) =>
1146 request<{ drops: ExtractionDrop[] }>(
1147 `/api/v1/kbs/${kbId}/extraction-drops`,
1148 ),
1149 upload: (kbId: string, files: File[], sourceId?: string) => {
1150 const form = new FormData();
1151 for (const f of files) form.append("files", f, f.name);
1152 const qs = sourceId ? `?source=${sourceId}` : "";
1153 return request<{ created: Doc[]; skipped: unknown[] }>(
1154 `/api/v1/kbs/${kbId}/documents${qs}`,
1155 { method: "POST", body: form },
1156 );
1157 },
1158 deleteDocument: (id: string) =>
1159 request<{ ok: boolean }>(`/api/v1/documents/${id}`, { method: "DELETE" }),
1160
1161 search: (kbId: string, q: string) =>
1162 request<{ results: SearchResult[] }>(`/api/v1/kbs/${kbId}/search`, {
1163 method: "POST",
1164 body: JSON.stringify({ q }),
1165 }),
1166
1167 settings: (workspaceId: string) =>
1168 request<LlmSettingsView>(`/api/v1/workspaces/${workspaceId}/settings`),
1169 saveSettings: (workspaceId: string, body: Record<string, unknown>) =>
1170 request<{ ok: boolean }>(`/api/v1/workspaces/${workspaceId}/settings`, {
1171 method: "PUT",
1172 body: JSON.stringify(body),
1173 }),
1174 graphOverview: (kbId: string) =>
1175 request<{
1176 nodes: GraphNode[];
1177 edges: GraphEdge[];
1178 /** 库里一共有多少。**与 nodes.length 不是一回事**——画布只画度数最高的
1179 * 那一批,把上限当成规模显示是这个接口从前最误导人的地方 */
1180 total_nodes?: number;
1181 total_edges?: number;
1182 }>(`/api/v1/kbs/${kbId}/graph/overview`),
1183 /** 邻域视图**没有总数**:它本来就只是一小片,说「共 325 个」没有意义。
1184 * 两个字段声明成可选,好让调用方与总览共用一个类型 */
1185 graphNeighborhood: (kbId: string, entityId: string) =>
1186 request<{
1187 nodes: GraphNode[];
1188 edges: GraphEdge[];
1189 total_nodes?: number;
1190 total_edges?: number;
1191 }>(`/api/v1/kbs/${kbId}/graph/neighborhood?entity=${entityId}&hops=2`),
1192 /** 按名字找实体。**一并回总数**——「宁分勿合」会造出一堆同名,
1193 * 固定十条时想找的那个可能根本不在这十条里 */
1194 searchEntities: (kbId: string, q: string, limit = 10) =>
1195 request<{ entities: GraphNode[]; total: number }>(
1196 `/api/v1/kbs/${kbId}/entities?q=${encodeURIComponent(q)}&limit=${limit}`,
1197 ),
1198 entityDetail: (kbId: string, entityId: string) =>
1199 request<{
1200 entity: GraphNode;
1201 facts: EntityFact[];
1202 /** 推出来的那些**单独一个键**,不掺进 facts:混在同一个列表里,
1203 * 用户看不出「文档里写的」和「引擎推的」的区别 */
1204 derived: DerivedFact[];
1205 /** 同名的其他实体。**打开面板就给**——合并入口要长在能看见同名的地方,
1206 * 而不是藏在「改一次名」之后 */
1207 same_name: GraphNode[];
1208 }>(`/api/v1/kbs/${kbId}/entities/${entityId}`),
1209 /** 认知变更历史(记录时间轴):服务端分页 */
1210 /** 人工修正实体的类型或名字。同名不拦——返回的 same_name 供界面提示是否合并。 */
1211 updateEntity: (
1212 kbId: string,
1213 entityId: string,
1214 body: { type_id?: string; canonical_name?: string },
1215 ) =>
1216 request<{ entity: GraphNode; same_name: GraphNode[] }>(
1217 `/api/v1/kbs/${kbId}/entities/${entityId}`,
1218 { method: "PATCH", body: JSON.stringify(body) },
1219 ),
1220
1221 entityHistory: (kbId: string, entityId: string, page: number, per = 30) =>
1222 request<{ events: EntityHistoryEvent[]; total: number }>(
1223 `/api/v1/kbs/${kbId}/entities/${entityId}/history?page=${page}&per=${per}`,
1224 ),
1225 factEvidence: (kbId: string, factId: string) =>
1226 request<{ evidence: Evidence[] }>(
1227 `/api/v1/kbs/${kbId}/facts/${factId}/evidence`,
1228 ),
1229 documentDetail: (id: string) =>
1230 request<{ document: Doc; chunks: ChunkFull[] }>(`/api/v1/documents/${id}`),
1231 extractDocument: (id: string) =>
1232 request<{ job_id: number }>(`/api/v1/documents/${id}/extract`, {
1233 method: "POST",
1234 }),
1235 reprocessDocument: (id: string) =>
1236 request<{ job_id: number }>(`/api/v1/documents/${id}/reprocess`, {
1237 method: "POST",
1238 }),
1239 /** 来源级全量重抽(增量语义:既有决策保留) */
1240 reExtractSource: (kbId: string, sourceId: string) =>
1241 request<{ queued: number }>(
1242 `/api/v1/kbs/${kbId}/sources/${sourceId}/re-extract`,
1243 {
1244 method: "POST",
1245 },
1246 ),
1247 /** 图谱重建(清算语义:清空图层后全量重抽;KB admin) */
1248 rebuildGraph: (kbId: string) =>
1249 request<{
1250 entities_removed: number;
1251 facts_removed: number;
1252 queued: number;
1253 }>(`/api/v1/kbs/${kbId}/graph/rebuild`, { method: "POST" }),
1254
1255 ontology: (kbId: string) =>
1256 request<{
1257 entity_types: EntityTypeView[];
1258 relation_types: RelationTypeView[];
1259 misses: OntologyMiss[];
1260 /** 已忽略的,连同它此后继续累积的计数。抑制照旧,只是看得见 */
1261 dismissed_misses: OntologyMiss[];
1262 }>(`/api/v1/kbs/${kbId}/ontology`),
1263 createEntityType: (kbId: string, body: Record<string, unknown>) =>
1264 request<{ id: string }>(`/api/v1/kbs/${kbId}/ontology/entity-types`, {
1265 method: "POST",
1266 body: JSON.stringify(body),
1267 }),
1268 updateEntityType: (kbId: string, id: string, body: Record<string, unknown>) =>
1269 request<{ ok: boolean }>(
1270 `/api/v1/kbs/${kbId}/ontology/entity-types/${id}`,
1271 {
1272 method: "PATCH",
1273 body: JSON.stringify(body),
1274 },
1275 ),
1276 deleteEntityType: (kbId: string, id: string) =>
1277 request<{ ok: boolean }>(
1278 `/api/v1/kbs/${kbId}/ontology/entity-types/${id}`,
1279 {
1280 method: "DELETE",
1281 },
1282 ),
1283 typeEntities: (kbId: string, typeId: string, page: number, per = 12) =>
1284 request<{
1285 entities: { id: string; name: string; fact_count: number }[];
1286 total: number;
1287 }>(
1288 `/api/v1/kbs/${kbId}/ontology/entity-types/${typeId}/entities?page=${page}&per=${per}`,
1289 ),
1290 createRelationType: (kbId: string, body: Record<string, unknown>) =>
1291 request<{ id: string }>(`/api/v1/kbs/${kbId}/ontology/relation-types`, {
1292 method: "POST",
1293 body: JSON.stringify(body),
1294 }),
1295 updateRelationType: (
1296 kbId: string,
1297 id: string,
1298 body: Record<string, unknown>,
1299 ) =>
1300 request<{ ok: boolean }>(
1301 `/api/v1/kbs/${kbId}/ontology/relation-types/${id}`,
1302 {
1303 method: "PATCH",
1304 body: JSON.stringify(body),
1305 },
1306 ),
1307 deleteRelationType: (kbId: string, id: string) =>
1308 request<{ ok: boolean }>(
1309 `/api/v1/kbs/${kbId}/ontology/relation-types/${id}`,
1310 {
1311 method: "DELETE",
1312 },
1313 ),
1314 /** 上次算出来、还没人表态的提案(0049)。刷新页面靠它,不必重跑模型 */
1315 storedProposals: (kbId: string) =>
1316 request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/proposals`),
1317 /** 一条提案有人表态了。改状态不删行——拒绝留痕,下一轮 Suggest 不再刷回待看 */
1318 decideProposal: (
1319 kbId: string,
1320 section: string,
1321 key: string,
1322 status: "adopted" | "rejected",
1323 ) =>
1324 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/proposals`, {
1325 method: "POST",
1326 body: JSON.stringify({ section, key, status }),
1327 }),
1328 dismissMiss: (kbId: string, kind: string, key: string) =>
1329 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/misses/dismiss`, {
1330 method: "POST",
1331 body: JSON.stringify({ kind, key }),
1332 }),
1333 restoreMiss: (kbId: string, kind: string, key: string) =>
1334 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/misses/restore`, {
1335 method: "POST",
1336 body: JSON.stringify({ kind, key }),
1337 }),
1338 /** reason 只给人看,而人就在这次请求的另一端——所以语言由调用方说,
1339 不是后端的设置(docs/decisions/0004)。description 的语言跟知识库走,服务端自己知道 */
1340 suggestOntology: (kbId: string) =>
1341 request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/suggest`, {
1342 method: "POST",
1343 body: JSON.stringify({ locale: lang }),
1344 }),
1345
1346 /** 上传本体文件只算出计划,一个字节都不写库 */
1347 previewOntologyImport: (kbId: string, file: File) => {
1348 const form = new FormData();
1349 form.append("file", file, file.name);
1350 return request<{ filename: string; plan: ImportPlan }>(
1351 `/api/v1/kbs/${kbId}/ontology/imports/preview`,
1352 { method: "POST", body: form },
1353 );
1354 },
1355 /** 执行刚看过的那个计划——服务端重新算一遍,两条路径共用同一段代码 */
1356 applyOntologyImport: (kbId: string, file: File) => {
1357 const form = new FormData();
1358 form.append("file", file, file.name);
1359 return request<{ import_id: string; plan: ImportPlan }>(
1360 `/api/v1/kbs/${kbId}/ontology/imports`,
1361 { method: "POST", body: form },
1362 );
1363 },
1364 ontologyImports: (kbId: string) =>
1365 request<{ imports: OntologyImportView[] }>(
1366 `/api/v1/kbs/${kbId}/ontology/imports`,
1367 ),
1368
1369 proposedPredicates: (kbId: string) =>
1370 request<{ forms: ProposedPredicate[] }>(
1371 `/api/v1/kbs/${kbId}/ontology/proposed-predicates`,
1372 ),
1373 /** 最近一次自动扩本体做了什么,以及还能不能撤销(撤干净了返回 null) */
1374 lastAutoExtension: (kbId: string) =>
1375 request<{
1376 run: {
1377 at: string;
1378 relations: string[] | null;
1379 classes: string[] | null;
1380 facts_remapped: number | null;
1381 batches: string[];
1382 } | null;
1383 }>(`/api/v1/kbs/${kbId}/ontology/auto-extension`),
1384 /** 建关系 **并**把等着它的无谓词事实认过去——后半句才是收益 */
1385 adoptPredicate: (
1386 kbId: string,
1387 body: {
1388 key: string;
1389 /** true = key 指的是已有的关系/属性,只改写事实,不建新类型 */
1390 existing?: boolean;
1391 /** attribute 走另一条改写路径:值要按 datatype 换算 */
1392 kind?: "relation" | "attribute";
1393 datatype?: string;
1394 unit?: string;
1395 label?: string;
1396 temporal?: string;
1397 functional?: boolean;
1398 description?: string;
1399 forms: string[];
1400 },
1401 ) =>
1402 request<{
1403 id: string;
1404 remapped: number;
1405 batch: string;
1406 /** 值换不动那个 datatype、因而没被改写的条数。改写了 3 条丢下 2 条,
1407 只报前半句就是报喜不报忧 */
1408 unconvertible?: number;
1409 }>(`/api/v1/kbs/${kbId}/ontology/adopt-predicate`, {
1410 method: "POST",
1411 body: JSON.stringify(body),
1412 }),
1413 /** 撤销一次采纳:新写的行作废、旧行复活。关系类型留着 */
1414 unadoptPredicate: (kbId: string, batchId: string) =>
1415 request<{ reverted: number }>(
1416 `/api/v1/kbs/${kbId}/ontology/adopt-predicate/${batchId}`,
1417 { method: "DELETE" },
1418 ),
1419
1420 sources: (kbId: string) =>
1421 request<{ sources: SourceView[] }>(`/api/v1/kbs/${kbId}/sources`),
1422 createSource: (kbId: string, body: Record<string, unknown>) =>
1423 request<{ source: SourceView; ingest_token?: string | null }>(
1424 `/api/v1/kbs/${kbId}/sources`,
1425 {
1426 method: "POST",
1427 body: JSON.stringify(body),
1428 },
1429 ),
1430 sourceToken: (kbId: string, sourceId: string) =>
1431 request<{ ingest_token: string | null }>(
1432 `/api/v1/kbs/${kbId}/sources/${sourceId}/token`,
1433 ),
1434 rotateSourceToken: (kbId: string, sourceId: string) =>
1435 request<{ ingest_token: string }>(
1436 `/api/v1/kbs/${kbId}/sources/${sourceId}/rotate-token`,
1437 { method: "POST" },
1438 ),
1439 updateSource: (
1440 kbId: string,
1441 sourceId: string,
1442 body: Record<string, unknown>,
1443 ) =>
1444 request<{ source: SourceView }>(`/api/v1/kbs/${kbId}/sources/${sourceId}`, {
1445 method: "PATCH",
1446 body: JSON.stringify(body),
1447 }),
1448 deleteSource: (kbId: string, sourceId: string) =>
1449 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/sources/${sourceId}`, {
1450 method: "DELETE",
1451 }),
1452 cleanupMissing: (kbId: string, sourceId: string) =>
1453 request<{ deleted: number }>(
1454 `/api/v1/kbs/${kbId}/sources/${sourceId}/missing/cleanup`,
1455 {
1456 method: "POST",
1457 },
1458 ),
1459 syncSource: (kbId: string, sourceId: string) =>
1460 request<{ queued: boolean }>(
1461 `/api/v1/kbs/${kbId}/sources/${sourceId}/sync`,
1462 {
1463 method: "POST",
1464 },
1465 ),
1466 sourceRuns: (kbId: string, sourceId: string) =>
1467 request<{ runs: SyncRun[] }>(
1468 `/api/v1/kbs/${kbId}/sources/${sourceId}/runs`,
1469 ),
1470 documentExtractions: (docId: string) =>
1471 request<{ facts: ChunkFact[] }>(`/api/v1/documents/${docId}/extractions`),
1472
1473 /** 审核队列的各档**真实条数**。与列表分开取——列表有一页的上限,数数没有。
1474 * 从前徽标读的是数组长度,而接口固定只回 100 条,于是 164 条写成 100。 */
1475 review: (kbId: string, queue: ReviewQueue, limit: number, offset: number) =>
1476 request<{
1477 counts: ReviewCounts;
1478 queue: ReviewQueue;
1479 /** 只有当前这一档的一页。类型按档不同,调用处按 queue 收窄 */
1480 items: unknown[];
1481 }>(
1482 `/api/v1/kbs/${kbId}/review?queue=${queue}&limit=${limit}&offset=${offset}`,
1483 ),
1484 closeFact: (kbId: string, factId: string, validTo: string) =>
1485 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/close`, {
1486 method: "POST",
1487 body: JSON.stringify({ valid_to: validTo }),
1488 }),
1489 resolveConflict: (
1490 kbId: string,
1491 conflictId: string,
1492 body: { action: "close" | "keep" | "reject_new"; close_at?: string },
1493 ) =>
1494 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conflicts/${conflictId}`, {
1495 method: "POST",
1496 body: JSON.stringify(body),
1497 }),
1498 decideReview: (kbId: string, reviewId: string, action: "merge" | "keep") =>
1499 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/${reviewId}`, {
1500 method: "POST",
1501 body: JSON.stringify({ action }),
1502 }),
1503 /** 对一条数据映射口径表态(0011)。改状态不删行——拒绝留痕,下一轮探索不再提议它 */
1504 decideMapping: (
1505 kbId: string,
1506 mappingId: string,
1507 status: "confirmed" | "rejected",
1508 ) =>
1509 request<{ ok: boolean }>(
1510 `/api/v1/kbs/${kbId}/review/mappings/${mappingId}`,
1511 {
1512 method: "POST",
1513 body: JSON.stringify({ status }),
1514 },
1515 ),
1516 /** 跑一遍一致性检查。同步返回——纯计算,没有模型调用也没有网络 */
1517 runConsistencyCheck: (kbId: string) =>
1518 request<{
1519 edges: number;
1520 /** **零和零不一样**:没有公理时结论是「没有判据」,不是「未发现矛盾」 */
1521 predicates_with_axioms: number;
1522 found: number;
1523 inserted: number;
1524 cleared: number;
1525 classes: number;
1526 /** 本体自己的矛盾**单独回**,不加进 found:两个数不是一类东西 */
1527 defects_found: number;
1528 defects_new: number;
1529 }>(`/api/v1/kbs/${kbId}/consistency/check`, { method: "POST" }),
1530 /** 对一处本体缺陷表态。**两个出路**——它压根没看数据,没有「数据错了」这条 */
1531 decideDefect: (
1532 kbId: string,
1533 defectId: string,
1534 resolution: "fixed" | "accepted",
1535 ) =>
1536 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/defects/${defectId}`, {
1537 method: "POST",
1538 body: JSON.stringify({ resolution }),
1539 }),
1540 /** 跑一遍推理(R1)。开关关着时后端回 inference_off */
1541 /** 类型消解:**只算不写**。回执里带着送去检索的画像——检索找不着时,
1542 * 第一个要看的就是「我们拿什么去找的」 */
1543 /** 手动合并:把 source 并进 target。**方向要紧**——source 消失,
1544 * 它的事实搬到 target 上;合并可整体回滚(entity_merges 记着快照) */
1545 mergeEntities: (kbId: string, source: string, target: string) =>
1546 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/entities/merge`, {
1547 method: "POST",
1548 body: JSON.stringify({ source, target }),
1549 }),
1550 typeResolutionPreview: (kbId: string) =>
1551 request<{ items: TypeSuggestion[] }>(
1552 `/api/v1/kbs/${kbId}/ontology/type-resolution/preview`,
1553 { method: "POST" },
1554 ),
1555 /** 跑一遍并落库。三档分开回:自动改的、留给人的、说「都不是」的 */
1556 typeResolutionApply: (kbId: string) =>
1557 request<ResolutionOutcome>(`/api/v1/kbs/${kbId}/ontology/type-resolution`, {
1558 method: "POST",
1559 }),
1560 /** 认可一个「粗类 → 细类」的配对,并把带上的实体改过去。
1561 * **认可的是类对,改的是实体**——认可一次,之后同一对不再进人工 */
1562 approveRefinement: (
1563 kbId: string,
1564 body: { from_type_id: string; to_type_id: string; entity_ids: string[] },
1565 ) =>
1566 request<{ retyped: number }>(
1567 `/api/v1/kbs/${kbId}/ontology/type-resolution/approve`,
1568 { method: "POST", body: JSON.stringify(body) },
1569 ),
1570 /** 撤销一整批:把那批实体放回原来的类 */
1571 typeResolutionUndo: (kbId: string, batchId: string) =>
1572 request<{ reverted: number }>(
1573 `/api/v1/kbs/${kbId}/ontology/type-resolution/${batchId}`,
1574 { method: "DELETE" },
1575 ),
1576 runInference: (kbId: string) =>
1577 request<{
1578 /** 编译出来的规则条数。为零时是「没有规则」而不是「推不出东西」 */
1579 rules: number;
1580 edges: number;
1581 derived: number;
1582 inserted: number;
1583 /** 前提没了、跟着作废的 */
1584 invalidated: number;
1585 /** 撞上单谓词上限、没推完的谓词个数 */
1586 capped: number;
1587 }>(`/api/v1/kbs/${kbId}/inference/run`, { method: "POST" }),
1588 /** 对一处公理违规表态。三个出路——第三个是这一档独有的:可能是定义错了 */
1589 decideViolation: (
1590 kbId: string,
1591 violationId: string,
1592 resolution: "fact_retracted" | "axiom_relaxed" | "accepted",
1593 ) =>
1594 request<{ ok: boolean }>(
1595 `/api/v1/kbs/${kbId}/review/violations/${violationId}`,
1596 { method: "POST", body: JSON.stringify({ resolution }) },
1597 ),
1598 confirmFact: (kbId: string, factId: string) =>
1599 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/confirm`, {
1600 method: "POST",
1601 }),
1602 rejectFact: (kbId: string, factId: string) =>
1603 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/reject`, {
1604 method: "POST",
1605 }),
1606 revertMerge: (kbId: string, mergeId: string) =>
1607 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/merges/${mergeId}/revert`, {
1608 method: "POST",
1609 }),
1610 reviewHistory: (kbId: string, page: number, per = 20) =>
1611 request<{ events: ReviewHistoryEvent[]; total: number }>(
1612 `/api/v1/kbs/${kbId}/review/history?page=${page}&per=${per}`,
1613 ),
1614
1615 members: (workspaceId: string) =>
1616 request<Member[]>(`/api/v1/workspaces/${workspaceId}/members`),
1617 orgUsers: () => request<OrgUser[]>("/api/v1/users"),
1618 setMemberRole: (workspaceId: string, userId: string, role: string) =>
1619 request<{ ok: boolean }>(
1620 `/api/v1/workspaces/${workspaceId}/members/${userId}`,
1621 {
1622 method: "PUT",
1623 body: JSON.stringify({ role }),
1624 },
1625 ),
1626 removeMember: (workspaceId: string, userId: string) =>
1627 request<{ ok: boolean }>(
1628 `/api/v1/workspaces/${workspaceId}/members/${userId}`,
1629 {
1630 method: "DELETE",
1631 },
1632 ),
1633
1634 testSettings: (workspaceId: string) =>
1635 request<{
1636 chat: { ok: boolean; reply?: string; error?: string };
1637 embed: { ok: boolean; dim?: number; error?: string };
1638 }>(`/api/v1/workspaces/${workspaceId}/settings/test`, { method: "POST" }),
1639};
1640
1641/** RAG 对话:SSE 流式。返回中止函数。 */
1642export const conversationsApi = {
1643 /** **可搜可翻页**:标题会重(同一个问题问两次就重了),而固定一百条之后的
1644 * 会话界面上根本不存在。搜的是标题与消息正文两处——人记得住的往往是
1645 * 问过的那句话,不是标题 */
1646 list: (kbId: string, q = "", limit = 30, offset = 0) => {
1647 const p = new URLSearchParams({
1648 limit: String(limit),
1649 offset: String(offset),
1650 });
1651 if (q.trim()) p.set("q", q.trim());
1652 return request<{ conversations: ConversationRow[]; total: number }>(
1653 `/api/v1/kbs/${kbId}/conversations?${p}`,
1654 );
1655 },
1656 /** 改标题。标题本来是从第一句话自动取的,而一段对话跑偏是常态 */
1657 rename: (kbId: string, id: string, title: string) =>
1658 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conversations/${id}`, {
1659 method: "PATCH",
1660 body: JSON.stringify({ title }),
1661 }),
1662 detail: (kbId: string, id: string) =>
1663 request<{ messages: ConversationMessage[] }>(
1664 `/api/v1/kbs/${kbId}/conversations/${id}`,
1665 ),
1666 remove: (kbId: string, id: string) =>
1667 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conversations/${id}`, {
1668 method: "DELETE",
1669 }),
1670};
1671
1672export function streamChat(
1673 kbId: string,
1674 body: { conversation_id?: string; message: string },
1675 handlers: {
1676 onConversation: (id: string) => void;
1677 onSources: (s: Source[]) => void;
1678 onStep: (s: ChatStep) => void;
1679 onDelta: (text: string) => void;
1680 onDone: () => void;
1681 onError: (message: string) => void;
1682 },
1683): () => void {
1684 const controller = new AbortController();
1685 (async () => {
1686 try {
1687 const res = await fetch(`/api/v1/kbs/${kbId}/chat`, {
1688 method: "POST",
1689 credentials: "include",
1690 headers: { "Content-Type": "application/json" },
1691 body: JSON.stringify(body),
1692 signal: controller.signal,
1693 });
1694 if (!res.ok || !res.body) {
1695 let message = res.statusText;
1696 try {
1697 const body = (await res.json()) as { error?: string };
1698 if (body.error) message = body.error;
1699 } catch {
1700 /* ignore */
1701 }
1702 handlers.onError(message);
1703 return;
1704 }
1705 const reader = res.body.getReader();
1706 const decoder = new TextDecoder();
1707 let buf = "";
1708 for (;;) {
1709 const { done, value } = await reader.read();
1710 if (done) break;
1711 buf += decoder.decode(value, { stream: true });
1712 let idx: number;
1713 while ((idx = buf.indexOf("\n\n")) >= 0) {
1714 const frame = buf.slice(0, idx);
1715 buf = buf.slice(idx + 2);
1716 let event = "message";
1717 let data = "";
1718 for (const line of frame.split("\n")) {
1719 if (line.startsWith("event:")) event = line.slice(6).trim();
1720 else if (line.startsWith("data:")) data += line.slice(5).trim();
1721 }
1722 if (event === "conversation")
1723 handlers.onConversation((JSON.parse(data) as { id: string }).id);
1724 else if (event === "sources")
1725 handlers.onSources(JSON.parse(data || "[]"));
1726 else if (event === "step")
1727 handlers.onStep(JSON.parse(data) as ChatStep);
1728 else if (event === "delta")
1729 handlers.onDelta((JSON.parse(data) as { text: string }).text);
1730 else if (event === "done") handlers.onDone();
1731 else if (event === "error") handlers.onError(data);
1732 }
1733 }
1734 handlers.onDone();
1735 } catch (e) {
1736 if (!controller.signal.aborted) handlers.onError(String(e));
1737 }
1738 })();
1739 return () => controller.abort();
1740}