Elffuss BraidHub

kikocis/utopia public

056185cb340e · 60.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 /** 推它出来的那条规则;断言的边为 null。
519 * 界面靠它认出 `inverse`——那种边与来源边是同一件事的两种说法,
520 * 画两条只是把冗余画了两遍(见 Graph 的 `layOutParallelEdges`) */
521 rule: string | null;
522 /** 推它出来用到的前提事实 id(按证明顺序);断言的边为空。
523 * 并边要靠它认准来源——只按节点对匹配会把说法挂到错的边上 */
524 premises: string[];
525 valid_from: string | null;
526 valid_to: string | null;
527 confidence: number;
528}
529
530export interface EntityFact {
531 id: string;
532 direction: "out" | "in";
533 /** 同 GraphEdge:本体外的关系回落到原文说法,两者都没有时为 null */
534 predicate_key: string | null;
535 predicate_label: string | null;
536 /** true = 名字来自原文,不是本体认下的关系 */
537 inferred: boolean;
538 /** 关系的时态类别。没有谓词就无从谈起,为 null */
539 temporal: string | null;
540 other_id: string | null;
541 other_name: string | null;
542 /** 字面值宾语(属性事实/问数映射):{"value":…} 或 {"summary":…} */
543 object_value: Record<string, unknown> | null;
544 valid_from: string | null;
545 valid_to: string | null;
546 valid_from_precision: string | null;
547 /** year | month | day,外加 unknown = 原文说它结束了但没说哪天 */
548 valid_to_precision: string | null;
549 confidence: number;
550 evidence_count: number;
551 /** 证据全部停留在来源文档的旧版(未被现行内容确认;不代表事实失效) */
552 stale: boolean;
553 /** 修正行:区间闭合来自引擎对账/人工裁决而非抽取原文 */
554 corrected: boolean;
555 /** 证据集合里最新的文档时间(开放事实的"最后确认时间") */
556 last_evidence_time: string | null;
557}
558
559/** 实体的一次认知变更(记录时间轴上的事件,与 EntityFact 的有效时间轴正交)。
560 *
561 * 不是每个事件都来自一条事实:retyped / retype_reverted 来自改类账本,
562 * 没有谓词、没有对方、没有方向。 */
563export interface EntityHistoryEvent {
564 /** 事实事件才有;改类事件为 null */
565 fact_id: string | null;
566 /** 记录时刻:写入 = recorded_at,作废 = invalidated_at,改类 = 改类那一刻 */
567 at: string;
568 kind:
569 | "asserted"
570 | "corrected"
571 | "rejected"
572 | "merged"
573 | "retyped"
574 | "retype_reverted";
575 direction: "out" | "in" | null;
576 predicate_label: string | null;
577 other_name: string | null;
578 object_value: Record<string, unknown> | null;
579 valid_from: string | null;
580 valid_to: string | null;
581 valid_from_precision: string | null;
582 /** year | month | day,外加 unknown = 原文说它结束了但没说哪天 */
583 valid_to_precision: string | null;
584 confidence: number | null;
585 /** null = 引擎自动(抽取写入 / 时态对账闭合 / 高置信自动改类) */
586 actor_name: string | null;
587 action: string | null;
588 document_id: string | null;
589 filename: string | null;
590 quote: string | null;
591 /** 改类事件的两端。起点为 null = 从「未分类」改过来(0009 之后最常见的一种) */
592 from_type_label: string | null;
593 to_type_label: string | null;
594}
595
596export interface Evidence {
597 /** 模型在这一块里实际用的谓词说法。本体外的谓词不落到关系上,界面显示的就是这里 */
598 proposed_predicate: string | null;
599 quote: string | null;
600 chunk_id: string;
601 document_id: string;
602 filename: string;
603 seq: number;
604 /** 证据出自文档的第几版 */
605 doc_version: number;
606 /** 文档已有更新版本(证据停留在旧版;不代表事实失效) */
607 stale: boolean;
608}
609
610export interface ChunkFull {
611 id: string;
612 seq: number;
613 text: string;
614}
615
616export interface EntityTypeView {
617 id: string;
618 key: string;
619 label: string;
620 color: string;
621 shape: "circle" | "square";
622 builtin: boolean;
623 /** 全部父类(subClassOf 可以有多个) */
624 parents: string[];
625 /** 与它互斥的类:**声明「不可能同时是」** */
626 disjoint: string[];
627 /** 左栏画树时挂在哪一支下。不参与语义,只管展示 */
628 primary_parent: string | null;
629 description: string;
630 usage: number;
631}
632
633export interface RelationTypeView {
634 id: string;
635 key: string;
636 label: string;
637 temporal: string;
638 functional: boolean;
639 inverse_functional: boolean;
640 /** 其余四条 OWL 公理。**推理机的判据全在这里** */
641 is_transitive: boolean;
642 is_symmetric: boolean;
643 is_asymmetric: boolean;
644 is_irreflexive: boolean;
645 builtin: boolean;
646 description: string;
647 /** relation(宾语是实体)| attribute(宾语是字面值) */
648 kind: "relation" | "attribute";
649 /** 可以当主语的类。attribute 至少一个;relation 留空 = 不限 */
650 domains: string[];
651 /** 可以当宾语的类。只对 relation 有意义——attribute 的值域是 datatype */
652 ranges: string[];
653 datatype: "text" | "number" | "date" | "bool" | null;
654 unit: string | null;
655 usage: number;
656}
657
658export interface OntologyMiss {
659 kind: "entity_type" | "relation_type";
660 key: string;
661 example: string | null;
662 count: number;
663}
664
665/** `description` 与 `reason` 不是一回事:description 逐字进抽取提示词,是模型判断
666 "什么算这个类"的唯一依据;reason 只是给人看的"为什么该加"。喂错了这个类会成为
667 下一个倾倒场——实测 technology 就是这么来的。 */
668export interface OntologyProposals {
669 entity_types: {
670 key: string;
671 label: string;
672 description?: string;
673 reason?: string;
674 }[];
675 relation_types: {
676 key: string;
677 label: string;
678 temporal?: string;
679 functional?: boolean;
680 description?: string;
681 reason?: string;
682 /** 这条关系归并了哪些表层说法。有它才谈得上把等待的事实改写过去 */
683 forms?: string[];
684 }[];
685 /**
686 * 宾语是字面值的说法("成立日期 = 2015")。
687 *
688 * 跟 relation_types 分开是因为它们要的东西不一样:属性有 datatype,
689 * 而把它当关系建出来,那个值就会变成一个假实体。domain 不在这里——
690 * 服务端从事实的主语类型里取,猜错会让整条被丢弃
691 */
692 attribute_types?: {
693 key: string;
694 label: string;
695 datatype?: string;
696 unit?: string;
697 description?: string;
698 reason?: string;
699 forms?: string[];
700 }[];
701 /**
702 * 本体里**已经有**这个意思,只需把说法挂过去。
703 *
704 * 跟 relation_types 的区别是不建东西:同一个意思长出第二个 key,
705 * 这批事实就永久分在两处,谁也认不出它们本是一回事。
706 */
707 map_to?: {
708 key: string;
709 /** 服务端标的:目标落在关系还是属性上。两条改写路径不一样,
710 而模型只答得出一个 key,看不出它在哪一档 */
711 kind?: string;
712 forms?: string[];
713 reason?: string;
714 }[];
715}
716
717/** 原文说过、本体里没有、因而事实没有谓词的说法。 */
718export interface ProposedPredicate {
719 form: string;
720 fact_count: number;
721 example: string | null;
722}
723
724/** 一个类/属性在这次导入里的去向。key_taken = key 被另一个 IRI 占着,报告但不动 */
725export interface PlannedItem {
726 iri: string;
727 key: string;
728 label: string;
729 has_description: boolean;
730 disposition: "create" | "update" | "key_taken";
731 functional?: boolean;
732 conflict_with?: string | null;
733}
734
735/** 预览与落库返回同一个计划:点确认之后发生的事就是刚看过的事 */
736export interface ImportPlan {
737 format: string;
738 triples: number;
739 classes: PlannedItem[];
740 relations: PlannedItem[];
741 attributes: PlannedItem[];
742 /** 出现过但今天不消费的公理 → 次数。不是已跳过,是暂未投影 */
743 unprojected: [string, number][];
744 classes_without_description: number;
745 functional_relations: number;
746}
747
748export interface OntologyImportView {
749 id: string;
750 filename: string;
751 format: string;
752 byte_size: number;
753 summary: Record<string, unknown>;
754 imported_by_name: string | null;
755 imported_at: string;
756}
757
758export interface Source {
759 n: number;
760 /** 缺省 = 文档 chunk 引用;charter = 内置手册(跳 /docs/{slug}#{anchor}) */
761 kind?: "charter";
762 chunk_id?: string;
763 document_id?: string;
764 slug?: string;
765 anchor?: string;
766 heading?: string;
767 filename: string;
768 excerpt: string;
769}
770
771/** Agentic 对话的行动轨迹(工具调用一步一条)。 */
772export interface ChatStep {
773 kind: "search" | "docs" | "entity" | "facts" | "changes" | "query" | "tool";
774 label: string;
775 detail: string;
776 /** 这一步发生时正文已经有多长(UTF-16 码元,与 `string.length` 同一单位)。
777 * 据此把轨迹穿回正文里,而不是全堆在最前面。
778 * **这条迁移之前的消息没有它**——缺省时整段轨迹回到顶部,即旧的样子 */
779 at?: number;
780}
781
782/** 会话行(Chat 左栏列表)。 */
783export interface ConversationRow {
784 id: string;
785 title: string;
786 created_at: string;
787 updated_at: string;
788 message_count: number;
789}
790
791/** 会话消息(含落库的行动轨迹与引用,历史回放用)。 */
792export interface ConversationMessage {
793 id: string;
794 role: "user" | "assistant";
795 content: string;
796 steps: ChatStep[];
797 sources: Source[];
798 created_at: string;
799}
800
801/** 告警中心的一组(0005):**连着的、同类的几次故障**。
802 *
803 * 存储那边仍是一次故障一行,折叠在服务端读的时候做——这样翻页数的是组,
804 * 一段连续故障不会被页边界切断。 */
805export type AlertGroup = {
806 kb_id: string | null;
807 /** 系统级告警没有库名 */
808 kb_name: string | null;
809 /** `source.sync_failed` / `llm.unreachable` —— 措辞在 i18n 里按这个查 */
810 kind: string;
811 severity: "info" | "warning" | "error";
812 /** 这一组几次 */
813 count: number;
814 /** 其中我没读过的几次 */
815 unread: number;
816 latest_at: string;
817 /** 跟 latest_at 一起圈出这一组,标已读时原样发回去 */
818 earliest_at: string;
819 /** 明细,最多几条,新的在前 */
820 lines: { name?: string; error?: string; job?: string }[];
821};
822
823export const api = {
824 health: () =>
825 request<{ status: string; name: string; version: string }>(
826 "/api/v1/health",
827 ),
828 me: () => request<User>("/api/v1/auth/me"),
829 alerts: (o: { q?: string; limit?: number; offset?: number }) => {
830 const p = new URLSearchParams();
831 if (o.q?.trim()) p.set("q", o.q.trim());
832 if (o.limit != null) p.set("limit", String(o.limit));
833 if (o.offset) p.set("offset", String(o.offset));
834 return request<{ items: AlertGroup[]; total: number }>(
835 `/api/v1/alerts?${p}`,
836 );
837 },
838 alertsUnread: () => request<{ unread: number }>("/api/v1/alerts/unread"),
839 alertReadGroup: (g: {
840 kb_id: string | null;
841 kind: string;
842 from: string;
843 to: string;
844 }) =>
845 request<{ marked: number }>("/api/v1/alerts/read-group", {
846 method: "POST",
847 body: JSON.stringify(g),
848 }),
849 alertsReadAll: () =>
850 request<{ ok: boolean }>("/api/v1/alerts/read-all", { method: "POST" }),
851 login: (email: string, password: string) =>
852 request<{ user: User }>("/api/v1/auth/login", {
853 method: "POST",
854 body: JSON.stringify({ email, password }),
855 }),
856 register: (email: string, password: string, displayName: string) =>
857 request<{ user: User; workspace: Workspace }>("/api/v1/auth/register", {
858 method: "POST",
859 body: JSON.stringify({ email, password, display_name: displayName }),
860 }),
861 logout: () =>
862 request<{ ok: boolean }>("/api/v1/auth/logout", { method: "POST" }),
863 updateMe: (displayName: string) =>
864 request<User>("/api/v1/auth/me", {
865 method: "PATCH",
866 body: JSON.stringify({ display_name: displayName }),
867 }),
868 changePassword: (currentPassword: string, newPassword: string) =>
869 request<{ ok: boolean }>("/api/v1/auth/password", {
870 method: "POST",
871 body: JSON.stringify({
872 current_password: currentPassword,
873 new_password: newPassword,
874 }),
875 }),
876 workspaces: () => request<Workspace[]>("/api/v1/workspaces"),
877
878 kbs: (workspaceId: string) =>
879 request<Kb[]>(`/api/v1/workspaces/${workspaceId}/kbs`),
880 /** 审计台账。**分页 + 筛选**——台账是合规材料,只看最近 100 条等于查不了历史。
881 * `action` 是前缀:`entity.` 捞出 entity.retyped / entity.renamed 一族。 */
882 kbAudit: (
883 kbId: string,
884 opts: {
885 action?: string;
886 actor?: string;
887 since?: string;
888 until?: string;
889 limit: number;
890 offset: number;
891 },
892 ) => {
893 const p = new URLSearchParams({
894 limit: String(opts.limit),
895 offset: String(opts.offset),
896 });
897 if (opts.action) p.set("action", opts.action);
898 if (opts.actor) p.set("actor", opts.actor);
899 if (opts.since) p.set("since", opts.since);
900 if (opts.until) p.set("until", opts.until);
901 return request<{
902 events: AuditEvent[];
903 total: number;
904 /** 这个库实际发生过的动作,筛选下拉按它填 */
905 actions: string[];
906 }>(`/api/v1/kbs/${kbId}/audit?${p}`);
907 },
908 myKbs: (workspaceId: string) =>
909 request<{ kbs: MyKb[] }>(`/api/v1/workspaces/${workspaceId}/my-kbs`),
910 createKb: (
911 workspaceId: string,
912 body: {
913 name: string;
914 description?: string | null;
915 visibility?: string;
916 /** 预置本体包 id,顺序有意义:第一个会认领同名的种子类 */
917 ontology_packs?: string[];
918 },
919 ) =>
920 request<Kb>(`/api/v1/workspaces/${workspaceId}/kbs`, {
921 method: "POST",
922 body: JSON.stringify(body),
923 }),
924
925 ontologyPacks: () =>
926 request<{ packs: OntologyPack[] }>("/api/v1/ontology-packs"),
927
928 kbDetail: (kbId: string) => request<Kb>(`/api/v1/kbs/${kbId}`),
929 updateKb: (kbId: string, body: Record<string, unknown>) =>
930 request<Kb>(`/api/v1/kbs/${kbId}`, {
931 method: "PATCH",
932 body: JSON.stringify(body),
933 }),
934 deleteKb: (kbId: string) =>
935 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}`, { method: "DELETE" }),
936 kbMembers: (kbId: string) =>
937 request<{ members: KbMember[] }>(`/api/v1/kbs/${kbId}/members`),
938 setKbMember: (kbId: string, userId: string, role: string) =>
939 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/members/${userId}`, {
940 method: "PUT",
941 body: JSON.stringify({ role }),
942 }),
943 removeKbMember: (kbId: string, userId: string) =>
944 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/members/${userId}`, {
945 method: "DELETE",
946 }),
947
948 adminDeployment: () =>
949 request<{
950 open_registration: boolean;
951 /** 外层兜底,防任务无限堆积;真正的节流是按模型的限额 */
952 worker_concurrency: number;
953 default_model_concurrency: number;
954 /** 新建知识库的本体语言默认值。**不是界面语言**——那个在客户端 */
955 default_ontology_lang: "en" | "zh";
956 model_limits: {
957 base_url: string;
958 model: string;
959 max_concurrent: number;
960 }[];
961 models_in_use: { base_url: string; model: string; kind: string }[];
962 }>("/api/v1/admin/deployment"),
963 saveAdminDeployment: (
964 openRegistration: boolean,
965 workerConcurrency?: number,
966 defaultModelConcurrency?: number,
967 modelLimit?: {
968 base_url: string;
969 model: string;
970 max_concurrent: number | null;
971 },
972 defaultOntologyLang?: "en" | "zh",
973 ) =>
974 request<{ ok: boolean }>("/api/v1/admin/deployment", {
975 method: "PUT",
976 body: JSON.stringify({
977 open_registration: openRegistration,
978 ...(workerConcurrency !== undefined
979 ? { worker_concurrency: workerConcurrency }
980 : {}),
981 ...(defaultModelConcurrency !== undefined
982 ? { default_model_concurrency: defaultModelConcurrency }
983 : {}),
984 ...(modelLimit ? { model_limit: modelLimit } : {}),
985 ...(defaultOntologyLang
986 ? { default_ontology_lang: defaultOntologyLang }
987 : {}),
988 }),
989 }),
990 adminCreateUser: (body: {
991 email: string;
992 display_name: string;
993 password: string;
994 role: string;
995 }) =>
996 request<{ user: User }>("/api/v1/admin/users", {
997 method: "POST",
998 body: JSON.stringify(body),
999 }),
1000
1001 /** 已停用的账号。**没有它恢复就够不着**——那个人从所有列表里消失,
1002 * 而恢复接口要的正是他的 id */
1003 deactivatedUsers: () => request<OrgUser[]>("/api/v1/users/deactivated"),
1004 /** 恢复一个停用的账号 */
1005 adminReactivateUser: (userId: string) =>
1006 request<{ ok: boolean }>(`/api/v1/admin/users/${userId}`, {
1007 method: "POST",
1008 }),
1009 /** 停用一个账号(软删除)。归因照旧查得到——审计、合并日志、改类账本都靠它 */
1010 adminDeactivateUser: (userId: string) =>
1011 request<{ ok: boolean }>(`/api/v1/admin/users/${userId}`, {
1012 method: "DELETE",
1013 }),
1014 adminDataSources: () =>
1015 request<{ data_sources: DataSourceView[] }>("/api/v1/admin/data-sources"),
1016 adminCreateDataSource: (body: { name: string; conn_string: string }) =>
1017 request<{ id: string }>("/api/v1/admin/data-sources", {
1018 method: "POST",
1019 body: JSON.stringify(body),
1020 }),
1021 adminDeleteDataSource: (id: string) =>
1022 request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}`, {
1023 method: "DELETE",
1024 }),
1025 adminTestDataSource: (id: string) =>
1026 request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}/test`, {
1027 method: "POST",
1028 }),
1029 /** 这个源授权给了哪些工作区(0014)。授权与挂载是两层:
1030 * 授权由系统管理员写,挂载由 KB 管理员在授权过的集合里挑 */
1031 dataSourceGrants: (id: string) =>
1032 request<{ workspaces: { id: string; name: string }[] }>(
1033 `/api/v1/admin/data-sources/${id}/grants`,
1034 ),
1035 grantDataSource: (id: string, workspaceId: string) =>
1036 request<{ ok: boolean }>(
1037 `/api/v1/admin/data-sources/${id}/grants/${workspaceId}`,
1038 { method: "PUT" },
1039 ),
1040 /** 收回授权。**连同该工作区里已挂上的一起卸掉**,返回卸了几个 */
1041 revokeDataSource: (id: string, workspaceId: string) =>
1042 request<{ ok: boolean; unmounted: number }>(
1043 `/api/v1/admin/data-sources/${id}/grants/${workspaceId}`,
1044 { method: "DELETE" },
1045 ),
1046
1047 /** 一页口径。**Viewer 就能看**——问数的答案直接由口径决定,
1048 * 看得见答案却看不见口径,等于要人信一个不给看的算法 */
1049 mappings: (
1050 kbId: string,
1051 opts: {
1052 status?: "proposed" | "confirmed" | "rejected";
1053 q?: string;
1054 limit?: number;
1055 offset?: number;
1056 } = {},
1057 ) => {
1058 const p = new URLSearchParams();
1059 if (opts.status) p.set("status", opts.status);
1060 if (opts.q) p.set("q", opts.q);
1061 if (opts.limit != null) p.set("limit", String(opts.limit));
1062 if (opts.offset != null) p.set("offset", String(opts.offset));
1063 const qs = p.toString();
1064 return request<{
1065 items: ConceptMapping[];
1066 total: number;
1067 counts: { proposed: number; confirmed: number; rejected: number };
1068 }>(`/api/v1/kbs/${kbId}/mappings${qs ? `?${qs}` : ""}`);
1069 },
1070 /** 改一条口径。改之前那一版自动进 revisions */
1071 reviseMapping: (
1072 kbId: string,
1073 mappingId: string,
1074 body: {
1075 table_name?: string | null;
1076 expr?: string | null;
1077 sql?: string | null;
1078 unit?: string | null;
1079 summary?: string | null;
1080 derived: boolean;
1081 },
1082 ) =>
1083 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/mappings/${mappingId}`, {
1084 method: "PATCH",
1085 body: JSON.stringify(body),
1086 }),
1087 mappingRevisions: (kbId: string, mappingId: string) =>
1088 request<{ revisions: MappingRevision[] }>(
1089 `/api/v1/kbs/${kbId}/mappings/${mappingId}/revisions`,
1090 ),
1091 kbDataSources: (kbId: string) =>
1092 request<{ data_sources: DataSourceView[] }>(
1093 `/api/v1/kbs/${kbId}/data-sources`,
1094 ),
1095 kbDataSourcesAvailable: (kbId: string) =>
1096 request<{ data_sources: DataSourceView[] }>(
1097 `/api/v1/kbs/${kbId}/data-sources/available`,
1098 ),
1099 /** 挂载。**`schema_error` 非空时挂载仍然成了**——源是真挂上的,只是它的
1100 * 库表结构没摄进来,问数看不见有哪些表。同一件事会进告警中心 */
1101 mountDataSource: (kbId: string, dsId: string) =>
1102 request<{
1103 ok: boolean;
1104 schema_tables: number;
1105 schema_error?: string | null;
1106 }>(`/api/v1/kbs/${kbId}/data-sources/${dsId}`, {
1107 method: "PUT",
1108 }),
1109 unmountDataSource: (kbId: string, dsId: string) =>
1110 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/${dsId}`, {
1111 method: "DELETE",
1112 }),
1113 exploreMappings: (kbId: string) =>
1114 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/explore`, {
1115 method: "POST",
1116 }),
1117 syncDataSourceSchema: (kbId: string, dsId: string) =>
1118 request<{ ok: boolean; schema_tables: number }>(
1119 `/api/v1/kbs/${kbId}/data-sources/${dsId}/sync-schema`,
1120 { method: "POST" },
1121 ),
1122
1123 /** 文库一页。**服务端筛选与分页**——从前一次取回整库、前端切片,
1124 * 而客户端筛选只筛得到已经拿下来的那些 */
1125 documents: (
1126 kbId: string,
1127 opts: {
1128 source?: string;
1129 q?: string;
1130 graph?: string;
1131 limit: number;
1132 offset: number;
1133 },
1134 ) => {
1135 const p = new URLSearchParams({
1136 limit: String(opts.limit),
1137 offset: String(opts.offset),
1138 });
1139 if (opts.source) p.set("source", opts.source);
1140 if (opts.q) p.set("q", opts.q);
1141 if (opts.graph) p.set("graph", opts.graph);
1142 return request<{
1143 docs: Doc[];
1144 total: number;
1145 /** 下面三个**只按来源作用域算**,不受名字/状态筛选影响——
1146 * 它们是批量按钮的作用范围 */
1147 ready: number;
1148 extracting: number;
1149 failed: number;
1150 }>(`/api/v1/kbs/${kbId}/documents?${p}`);
1151 },
1152 /** 一键重试这个作用域里全部抽取失败的文档 */
1153 retryFailedDocs: (kbId: string, source?: string) =>
1154 request<{ queued: number; found: number }>(
1155 `/api/v1/kbs/${kbId}/documents/retry-failed${source ? `?source=${source}` : ""}`,
1156 { method: "POST" },
1157 ),
1158 /** 整库一次取回:行数按 (文档 × 原因 × 对象) 聚合后很小,避免逐行发请求 */
1159 extractionDrops: (kbId: string) =>
1160 request<{ drops: ExtractionDrop[] }>(
1161 `/api/v1/kbs/${kbId}/extraction-drops`,
1162 ),
1163 upload: (kbId: string, files: File[], sourceId?: string) => {
1164 const form = new FormData();
1165 for (const f of files) form.append("files", f, f.name);
1166 const qs = sourceId ? `?source=${sourceId}` : "";
1167 return request<{ created: Doc[]; skipped: unknown[] }>(
1168 `/api/v1/kbs/${kbId}/documents${qs}`,
1169 { method: "POST", body: form },
1170 );
1171 },
1172 deleteDocument: (id: string) =>
1173 request<{ ok: boolean }>(`/api/v1/documents/${id}`, { method: "DELETE" }),
1174
1175 search: (kbId: string, q: string) =>
1176 request<{ results: SearchResult[] }>(`/api/v1/kbs/${kbId}/search`, {
1177 method: "POST",
1178 body: JSON.stringify({ q }),
1179 }),
1180
1181 settings: (workspaceId: string) =>
1182 request<LlmSettingsView>(`/api/v1/workspaces/${workspaceId}/settings`),
1183 saveSettings: (workspaceId: string, body: Record<string, unknown>) =>
1184 request<{ ok: boolean }>(`/api/v1/workspaces/${workspaceId}/settings`, {
1185 method: "PUT",
1186 body: JSON.stringify(body),
1187 }),
1188 graphOverview: (kbId: string, limit?: number) =>
1189 request<{
1190 nodes: GraphNode[];
1191 edges: GraphEdge[];
1192 /** 库里一共有多少。**与 nodes.length 不是一回事**——画布只画度数最高的
1193 * 那一批,把上限当成规模显示是这个接口从前最误导人的地方 */
1194 total_nodes?: number;
1195 total_edges?: number;
1196 }>(
1197 `/api/v1/kbs/${kbId}/graph/overview${limit ? `?limit=${limit}` : ""}`,
1198 ),
1199 /** 邻域视图**没有总数**:它本来就只是一小片,说「共 325 个」没有意义。
1200 * 两个字段声明成可选,好让调用方与总览共用一个类型 */
1201 graphNeighborhood: (kbId: string, entityId: string) =>
1202 request<{
1203 nodes: GraphNode[];
1204 edges: GraphEdge[];
1205 total_nodes?: number;
1206 total_edges?: number;
1207 }>(`/api/v1/kbs/${kbId}/graph/neighborhood?entity=${entityId}&hops=2`),
1208 /** 按名字找实体。**一并回总数**——「宁分勿合」会造出一堆同名,
1209 * 固定十条时想找的那个可能根本不在这十条里 */
1210 searchEntities: (kbId: string, q: string, limit = 10) =>
1211 request<{ entities: GraphNode[]; total: number }>(
1212 `/api/v1/kbs/${kbId}/entities?q=${encodeURIComponent(q)}&limit=${limit}`,
1213 ),
1214 entityDetail: (kbId: string, entityId: string) =>
1215 request<{
1216 entity: GraphNode;
1217 facts: EntityFact[];
1218 /** 推出来的那些**单独一个键**,不掺进 facts:混在同一个列表里,
1219 * 用户看不出「文档里写的」和「引擎推的」的区别 */
1220 derived: DerivedFact[];
1221 /** 同名的其他实体。**打开面板就给**——合并入口要长在能看见同名的地方,
1222 * 而不是藏在「改一次名」之后 */
1223 same_name: GraphNode[];
1224 }>(`/api/v1/kbs/${kbId}/entities/${entityId}`),
1225 /** 认知变更历史(记录时间轴):服务端分页 */
1226 /** 人工修正实体的类型或名字。同名不拦——返回的 same_name 供界面提示是否合并。 */
1227 updateEntity: (
1228 kbId: string,
1229 entityId: string,
1230 body: { type_id?: string; canonical_name?: string },
1231 ) =>
1232 request<{ entity: GraphNode; same_name: GraphNode[] }>(
1233 `/api/v1/kbs/${kbId}/entities/${entityId}`,
1234 { method: "PATCH", body: JSON.stringify(body) },
1235 ),
1236
1237 entityHistory: (kbId: string, entityId: string, page: number, per = 30) =>
1238 request<{ events: EntityHistoryEvent[]; total: number }>(
1239 `/api/v1/kbs/${kbId}/entities/${entityId}/history?page=${page}&per=${per}`,
1240 ),
1241 factEvidence: (kbId: string, factId: string) =>
1242 request<{ evidence: Evidence[] }>(
1243 `/api/v1/kbs/${kbId}/facts/${factId}/evidence`,
1244 ),
1245 documentDetail: (id: string) =>
1246 request<{ document: Doc; chunks: ChunkFull[] }>(`/api/v1/documents/${id}`),
1247 extractDocument: (id: string) =>
1248 request<{ job_id: number }>(`/api/v1/documents/${id}/extract`, {
1249 method: "POST",
1250 }),
1251 reprocessDocument: (id: string) =>
1252 request<{ job_id: number }>(`/api/v1/documents/${id}/reprocess`, {
1253 method: "POST",
1254 }),
1255 /** 来源级全量重抽(增量语义:既有决策保留) */
1256 reExtractSource: (kbId: string, sourceId: string) =>
1257 request<{ queued: number }>(
1258 `/api/v1/kbs/${kbId}/sources/${sourceId}/re-extract`,
1259 {
1260 method: "POST",
1261 },
1262 ),
1263 /** 图谱重建(清算语义:清空图层后全量重抽;KB admin) */
1264 rebuildGraph: (kbId: string) =>
1265 request<{
1266 entities_removed: number;
1267 facts_removed: number;
1268 queued: number;
1269 }>(`/api/v1/kbs/${kbId}/graph/rebuild`, { method: "POST" }),
1270
1271 ontology: (kbId: string) =>
1272 request<{
1273 entity_types: EntityTypeView[];
1274 relation_types: RelationTypeView[];
1275 misses: OntologyMiss[];
1276 /** 已忽略的,连同它此后继续累积的计数。抑制照旧,只是看得见 */
1277 dismissed_misses: OntologyMiss[];
1278 }>(`/api/v1/kbs/${kbId}/ontology`),
1279 createEntityType: (kbId: string, body: Record<string, unknown>) =>
1280 request<{ id: string }>(`/api/v1/kbs/${kbId}/ontology/entity-types`, {
1281 method: "POST",
1282 body: JSON.stringify(body),
1283 }),
1284 updateEntityType: (kbId: string, id: string, body: Record<string, unknown>) =>
1285 request<{ ok: boolean }>(
1286 `/api/v1/kbs/${kbId}/ontology/entity-types/${id}`,
1287 {
1288 method: "PATCH",
1289 body: JSON.stringify(body),
1290 },
1291 ),
1292 deleteEntityType: (kbId: string, id: string) =>
1293 request<{ ok: boolean }>(
1294 `/api/v1/kbs/${kbId}/ontology/entity-types/${id}`,
1295 {
1296 method: "DELETE",
1297 },
1298 ),
1299 typeEntities: (kbId: string, typeId: string, page: number, per = 12) =>
1300 request<{
1301 entities: { id: string; name: string; fact_count: number }[];
1302 total: number;
1303 }>(
1304 `/api/v1/kbs/${kbId}/ontology/entity-types/${typeId}/entities?page=${page}&per=${per}`,
1305 ),
1306 createRelationType: (kbId: string, body: Record<string, unknown>) =>
1307 request<{ id: string }>(`/api/v1/kbs/${kbId}/ontology/relation-types`, {
1308 method: "POST",
1309 body: JSON.stringify(body),
1310 }),
1311 updateRelationType: (
1312 kbId: string,
1313 id: string,
1314 body: Record<string, unknown>,
1315 ) =>
1316 request<{ ok: boolean }>(
1317 `/api/v1/kbs/${kbId}/ontology/relation-types/${id}`,
1318 {
1319 method: "PATCH",
1320 body: JSON.stringify(body),
1321 },
1322 ),
1323 deleteRelationType: (kbId: string, id: string) =>
1324 request<{ ok: boolean }>(
1325 `/api/v1/kbs/${kbId}/ontology/relation-types/${id}`,
1326 {
1327 method: "DELETE",
1328 },
1329 ),
1330 /** 上次算出来、还没人表态的提案(0049)。刷新页面靠它,不必重跑模型 */
1331 storedProposals: (kbId: string) =>
1332 request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/proposals`),
1333 /** 一条提案有人表态了。改状态不删行——拒绝留痕,下一轮 Suggest 不再刷回待看 */
1334 decideProposal: (
1335 kbId: string,
1336 section: string,
1337 key: string,
1338 status: "adopted" | "rejected",
1339 ) =>
1340 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/proposals`, {
1341 method: "POST",
1342 body: JSON.stringify({ section, key, status }),
1343 }),
1344 dismissMiss: (kbId: string, kind: string, key: string) =>
1345 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/misses/dismiss`, {
1346 method: "POST",
1347 body: JSON.stringify({ kind, key }),
1348 }),
1349 restoreMiss: (kbId: string, kind: string, key: string) =>
1350 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/misses/restore`, {
1351 method: "POST",
1352 body: JSON.stringify({ kind, key }),
1353 }),
1354 /** reason 只给人看,而人就在这次请求的另一端——所以语言由调用方说,
1355 不是后端的设置(docs/decisions/0004)。description 的语言跟知识库走,服务端自己知道 */
1356 suggestOntology: (kbId: string) =>
1357 request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/suggest`, {
1358 method: "POST",
1359 body: JSON.stringify({ locale: lang }),
1360 }),
1361
1362 /** 上传本体文件只算出计划,一个字节都不写库 */
1363 previewOntologyImport: (kbId: string, file: File) => {
1364 const form = new FormData();
1365 form.append("file", file, file.name);
1366 return request<{ filename: string; plan: ImportPlan }>(
1367 `/api/v1/kbs/${kbId}/ontology/imports/preview`,
1368 { method: "POST", body: form },
1369 );
1370 },
1371 /** 执行刚看过的那个计划——服务端重新算一遍,两条路径共用同一段代码 */
1372 applyOntologyImport: (kbId: string, file: File) => {
1373 const form = new FormData();
1374 form.append("file", file, file.name);
1375 return request<{ import_id: string; plan: ImportPlan }>(
1376 `/api/v1/kbs/${kbId}/ontology/imports`,
1377 { method: "POST", body: form },
1378 );
1379 },
1380 ontologyImports: (kbId: string) =>
1381 request<{ imports: OntologyImportView[] }>(
1382 `/api/v1/kbs/${kbId}/ontology/imports`,
1383 ),
1384
1385 proposedPredicates: (kbId: string) =>
1386 request<{ forms: ProposedPredicate[] }>(
1387 `/api/v1/kbs/${kbId}/ontology/proposed-predicates`,
1388 ),
1389 /** 最近一次自动扩本体做了什么,以及还能不能撤销(撤干净了返回 null) */
1390 lastAutoExtension: (kbId: string) =>
1391 request<{
1392 run: {
1393 at: string;
1394 relations: string[] | null;
1395 classes: string[] | null;
1396 facts_remapped: number | null;
1397 batches: string[];
1398 } | null;
1399 }>(`/api/v1/kbs/${kbId}/ontology/auto-extension`),
1400 /** 建关系 **并**把等着它的无谓词事实认过去——后半句才是收益 */
1401 adoptPredicate: (
1402 kbId: string,
1403 body: {
1404 key: string;
1405 /** true = key 指的是已有的关系/属性,只改写事实,不建新类型 */
1406 existing?: boolean;
1407 /** attribute 走另一条改写路径:值要按 datatype 换算 */
1408 kind?: "relation" | "attribute";
1409 datatype?: string;
1410 unit?: string;
1411 label?: string;
1412 temporal?: string;
1413 functional?: boolean;
1414 description?: string;
1415 forms: string[];
1416 },
1417 ) =>
1418 request<{
1419 id: string;
1420 remapped: number;
1421 batch: string;
1422 /** 值换不动那个 datatype、因而没被改写的条数。改写了 3 条丢下 2 条,
1423 只报前半句就是报喜不报忧 */
1424 unconvertible?: number;
1425 }>(`/api/v1/kbs/${kbId}/ontology/adopt-predicate`, {
1426 method: "POST",
1427 body: JSON.stringify(body),
1428 }),
1429 /** 撤销一次采纳:新写的行作废、旧行复活。关系类型留着 */
1430 unadoptPredicate: (kbId: string, batchId: string) =>
1431 request<{ reverted: number }>(
1432 `/api/v1/kbs/${kbId}/ontology/adopt-predicate/${batchId}`,
1433 { method: "DELETE" },
1434 ),
1435
1436 sources: (kbId: string) =>
1437 request<{ sources: SourceView[] }>(`/api/v1/kbs/${kbId}/sources`),
1438 createSource: (kbId: string, body: Record<string, unknown>) =>
1439 request<{ source: SourceView; ingest_token?: string | null }>(
1440 `/api/v1/kbs/${kbId}/sources`,
1441 {
1442 method: "POST",
1443 body: JSON.stringify(body),
1444 },
1445 ),
1446 sourceToken: (kbId: string, sourceId: string) =>
1447 request<{ ingest_token: string | null }>(
1448 `/api/v1/kbs/${kbId}/sources/${sourceId}/token`,
1449 ),
1450 rotateSourceToken: (kbId: string, sourceId: string) =>
1451 request<{ ingest_token: string }>(
1452 `/api/v1/kbs/${kbId}/sources/${sourceId}/rotate-token`,
1453 { method: "POST" },
1454 ),
1455 updateSource: (
1456 kbId: string,
1457 sourceId: string,
1458 body: Record<string, unknown>,
1459 ) =>
1460 request<{ source: SourceView }>(`/api/v1/kbs/${kbId}/sources/${sourceId}`, {
1461 method: "PATCH",
1462 body: JSON.stringify(body),
1463 }),
1464 deleteSource: (kbId: string, sourceId: string) =>
1465 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/sources/${sourceId}`, {
1466 method: "DELETE",
1467 }),
1468 cleanupMissing: (kbId: string, sourceId: string) =>
1469 request<{ deleted: number }>(
1470 `/api/v1/kbs/${kbId}/sources/${sourceId}/missing/cleanup`,
1471 {
1472 method: "POST",
1473 },
1474 ),
1475 syncSource: (kbId: string, sourceId: string) =>
1476 request<{ queued: boolean }>(
1477 `/api/v1/kbs/${kbId}/sources/${sourceId}/sync`,
1478 {
1479 method: "POST",
1480 },
1481 ),
1482 sourceRuns: (kbId: string, sourceId: string) =>
1483 request<{ runs: SyncRun[] }>(
1484 `/api/v1/kbs/${kbId}/sources/${sourceId}/runs`,
1485 ),
1486 documentExtractions: (docId: string) =>
1487 request<{ facts: ChunkFact[] }>(`/api/v1/documents/${docId}/extractions`),
1488
1489 /** 审核队列的各档**真实条数**。与列表分开取——列表有一页的上限,数数没有。
1490 * 从前徽标读的是数组长度,而接口固定只回 100 条,于是 164 条写成 100。 */
1491 review: (kbId: string, queue: ReviewQueue, limit: number, offset: number) =>
1492 request<{
1493 counts: ReviewCounts;
1494 queue: ReviewQueue;
1495 /** 只有当前这一档的一页。类型按档不同,调用处按 queue 收窄 */
1496 items: unknown[];
1497 }>(
1498 `/api/v1/kbs/${kbId}/review?queue=${queue}&limit=${limit}&offset=${offset}`,
1499 ),
1500 closeFact: (kbId: string, factId: string, validTo: string) =>
1501 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/close`, {
1502 method: "POST",
1503 body: JSON.stringify({ valid_to: validTo }),
1504 }),
1505 resolveConflict: (
1506 kbId: string,
1507 conflictId: string,
1508 body: { action: "close" | "keep" | "reject_new"; close_at?: string },
1509 ) =>
1510 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conflicts/${conflictId}`, {
1511 method: "POST",
1512 body: JSON.stringify(body),
1513 }),
1514 decideReview: (kbId: string, reviewId: string, action: "merge" | "keep") =>
1515 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/${reviewId}`, {
1516 method: "POST",
1517 body: JSON.stringify({ action }),
1518 }),
1519 /** 对一条数据映射口径表态(0011)。改状态不删行——拒绝留痕,下一轮探索不再提议它 */
1520 decideMapping: (
1521 kbId: string,
1522 mappingId: string,
1523 status: "confirmed" | "rejected",
1524 ) =>
1525 request<{ ok: boolean }>(
1526 `/api/v1/kbs/${kbId}/review/mappings/${mappingId}`,
1527 {
1528 method: "POST",
1529 body: JSON.stringify({ status }),
1530 },
1531 ),
1532 /** 跑一遍一致性检查。同步返回——纯计算,没有模型调用也没有网络 */
1533 runConsistencyCheck: (kbId: string) =>
1534 request<{
1535 edges: number;
1536 /** **零和零不一样**:没有公理时结论是「没有判据」,不是「未发现矛盾」 */
1537 predicates_with_axioms: number;
1538 found: number;
1539 inserted: number;
1540 cleared: number;
1541 classes: number;
1542 /** 本体自己的矛盾**单独回**,不加进 found:两个数不是一类东西 */
1543 defects_found: number;
1544 defects_new: number;
1545 }>(`/api/v1/kbs/${kbId}/consistency/check`, { method: "POST" }),
1546 /** 对一处本体缺陷表态。**两个出路**——它压根没看数据,没有「数据错了」这条 */
1547 decideDefect: (
1548 kbId: string,
1549 defectId: string,
1550 resolution: "fixed" | "accepted",
1551 ) =>
1552 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/defects/${defectId}`, {
1553 method: "POST",
1554 body: JSON.stringify({ resolution }),
1555 }),
1556 /** 跑一遍推理(R1)。开关关着时后端回 inference_off */
1557 /** 类型消解:**只算不写**。回执里带着送去检索的画像——检索找不着时,
1558 * 第一个要看的就是「我们拿什么去找的」 */
1559 /** 手动合并:把 source 并进 target。**方向要紧**——source 消失,
1560 * 它的事实搬到 target 上;合并可整体回滚(entity_merges 记着快照) */
1561 mergeEntities: (kbId: string, source: string, target: string) =>
1562 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/entities/merge`, {
1563 method: "POST",
1564 body: JSON.stringify({ source, target }),
1565 }),
1566 typeResolutionPreview: (kbId: string) =>
1567 request<{ items: TypeSuggestion[] }>(
1568 `/api/v1/kbs/${kbId}/ontology/type-resolution/preview`,
1569 { method: "POST" },
1570 ),
1571 /** 跑一遍并落库。三档分开回:自动改的、留给人的、说「都不是」的 */
1572 typeResolutionApply: (kbId: string) =>
1573 request<ResolutionOutcome>(`/api/v1/kbs/${kbId}/ontology/type-resolution`, {
1574 method: "POST",
1575 }),
1576 /** 认可一个「粗类 → 细类」的配对,并把带上的实体改过去。
1577 * **认可的是类对,改的是实体**——认可一次,之后同一对不再进人工 */
1578 approveRefinement: (
1579 kbId: string,
1580 body: { from_type_id: string; to_type_id: string; entity_ids: string[] },
1581 ) =>
1582 request<{ retyped: number }>(
1583 `/api/v1/kbs/${kbId}/ontology/type-resolution/approve`,
1584 { method: "POST", body: JSON.stringify(body) },
1585 ),
1586 /** 撤销一整批:把那批实体放回原来的类 */
1587 typeResolutionUndo: (kbId: string, batchId: string) =>
1588 request<{ reverted: number }>(
1589 `/api/v1/kbs/${kbId}/ontology/type-resolution/${batchId}`,
1590 { method: "DELETE" },
1591 ),
1592 runInference: (kbId: string) =>
1593 request<{
1594 /** 编译出来的规则条数。为零时是「没有规则」而不是「推不出东西」 */
1595 rules: number;
1596 edges: number;
1597 derived: number;
1598 inserted: number;
1599 /** 前提没了、跟着作废的 */
1600 invalidated: number;
1601 /** 撞上单谓词上限、没推完的谓词个数 */
1602 capped: number;
1603 }>(`/api/v1/kbs/${kbId}/inference/run`, { method: "POST" }),
1604 /** 对一处公理违规表态。三个出路——第三个是这一档独有的:可能是定义错了 */
1605 decideViolation: (
1606 kbId: string,
1607 violationId: string,
1608 resolution: "fact_retracted" | "axiom_relaxed" | "accepted",
1609 ) =>
1610 request<{ ok: boolean }>(
1611 `/api/v1/kbs/${kbId}/review/violations/${violationId}`,
1612 { method: "POST", body: JSON.stringify({ resolution }) },
1613 ),
1614 confirmFact: (kbId: string, factId: string) =>
1615 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/confirm`, {
1616 method: "POST",
1617 }),
1618 rejectFact: (kbId: string, factId: string) =>
1619 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/reject`, {
1620 method: "POST",
1621 }),
1622 revertMerge: (kbId: string, mergeId: string) =>
1623 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/merges/${mergeId}/revert`, {
1624 method: "POST",
1625 }),
1626 reviewHistory: (kbId: string, page: number, per = 20) =>
1627 request<{ events: ReviewHistoryEvent[]; total: number }>(
1628 `/api/v1/kbs/${kbId}/review/history?page=${page}&per=${per}`,
1629 ),
1630
1631 members: (workspaceId: string) =>
1632 request<Member[]>(`/api/v1/workspaces/${workspaceId}/members`),
1633 orgUsers: () => request<OrgUser[]>("/api/v1/users"),
1634 setMemberRole: (workspaceId: string, userId: string, role: string) =>
1635 request<{ ok: boolean }>(
1636 `/api/v1/workspaces/${workspaceId}/members/${userId}`,
1637 {
1638 method: "PUT",
1639 body: JSON.stringify({ role }),
1640 },
1641 ),
1642 removeMember: (workspaceId: string, userId: string) =>
1643 request<{ ok: boolean }>(
1644 `/api/v1/workspaces/${workspaceId}/members/${userId}`,
1645 {
1646 method: "DELETE",
1647 },
1648 ),
1649
1650 testSettings: (workspaceId: string) =>
1651 request<{
1652 chat: { ok: boolean; reply?: string; error?: string };
1653 embed: { ok: boolean; dim?: number; error?: string };
1654 }>(`/api/v1/workspaces/${workspaceId}/settings/test`, { method: "POST" }),
1655};
1656
1657/** RAG 对话:SSE 流式。返回中止函数。 */
1658export const conversationsApi = {
1659 /** **可搜可翻页**:标题会重(同一个问题问两次就重了),而固定一百条之后的
1660 * 会话界面上根本不存在。搜的是标题与消息正文两处——人记得住的往往是
1661 * 问过的那句话,不是标题 */
1662 list: (kbId: string, q = "", limit = 30, offset = 0) => {
1663 const p = new URLSearchParams({
1664 limit: String(limit),
1665 offset: String(offset),
1666 });
1667 if (q.trim()) p.set("q", q.trim());
1668 return request<{ conversations: ConversationRow[]; total: number }>(
1669 `/api/v1/kbs/${kbId}/conversations?${p}`,
1670 );
1671 },
1672 /** 改标题。标题本来是从第一句话自动取的,而一段对话跑偏是常态 */
1673 rename: (kbId: string, id: string, title: string) =>
1674 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conversations/${id}`, {
1675 method: "PATCH",
1676 body: JSON.stringify({ title }),
1677 }),
1678 detail: (kbId: string, id: string) =>
1679 request<{ messages: ConversationMessage[] }>(
1680 `/api/v1/kbs/${kbId}/conversations/${id}`,
1681 ),
1682 remove: (kbId: string, id: string) =>
1683 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conversations/${id}`, {
1684 method: "DELETE",
1685 }),
1686};
1687
1688export interface ChatHandlers {
1689 onConversation: (id: string) => void;
1690 onSources: (s: Source[]) => void;
1691 onStep: (s: ChatStep) => void;
1692 onDelta: (text: string) => void;
1693 onDone: () => void;
1694 onError: (message: string) => void;
1695 /** 接上一个已经在跑的回答:这是它此刻的样子,**覆盖,不是追加** */
1696 onSnapshot?: (s: { content: string; steps: ChatStep[]; sources: Source[] }) => void;
1697 /** 这个会话没有在跑的生成——最常见的答案,不是错误 */
1698 onIdle?: () => void;
1699}
1700
1701/** 接上一个正在生成的回答(刷新页面之后走这里)。
1702 *
1703 * 与 `streamChat` 读的是同一条事件流,只是多了开头那份快照。 */
1704export function reattachChat(
1705 kbId: string,
1706 conversationId: string,
1707 handlers: ChatHandlers,
1708): () => void {
1709 return consumeChatStream(
1710 (signal) =>
1711 fetch(`/api/v1/kbs/${kbId}/conversations/${conversationId}/stream`, {
1712 credentials: "include",
1713 signal,
1714 }),
1715 handlers,
1716 );
1717}
1718
1719export function streamChat(
1720 kbId: string,
1721 body: { conversation_id?: string; message: string },
1722 handlers: ChatHandlers,
1723): () => void {
1724 return consumeChatStream(
1725 (signal) =>
1726 fetch(`/api/v1/kbs/${kbId}/chat`, {
1727 method: "POST",
1728 credentials: "include",
1729 headers: { "Content-Type": "application/json" },
1730 body: JSON.stringify(body),
1731 signal,
1732 }),
1733 handlers,
1734 );
1735}
1736
1737/** SSE 的读法只有一份:发起请求的方式不同,收下来之后的处理完全一样。 */
1738function consumeChatStream(
1739 open: (signal: AbortSignal) => Promise<Response>,
1740 handlers: ChatHandlers,
1741): () => void {
1742 const controller = new AbortController();
1743 (async () => {
1744 try {
1745 const res = await open(controller.signal);
1746 if (!res.ok || !res.body) {
1747 let message = res.statusText;
1748 try {
1749 const body = (await res.json()) as { error?: string };
1750 if (body.error) message = body.error;
1751 } catch {
1752 /* ignore */
1753 }
1754 handlers.onError(message);
1755 return;
1756 }
1757 const reader = res.body.getReader();
1758 const decoder = new TextDecoder();
1759 let buf = "";
1760 for (;;) {
1761 const { done, value } = await reader.read();
1762 if (done) break;
1763 buf += decoder.decode(value, { stream: true });
1764 let idx: number;
1765 while ((idx = buf.indexOf("\n\n")) >= 0) {
1766 const frame = buf.slice(0, idx);
1767 buf = buf.slice(idx + 2);
1768 let event = "message";
1769 let data = "";
1770 for (const line of frame.split("\n")) {
1771 if (line.startsWith("event:")) event = line.slice(6).trim();
1772 else if (line.startsWith("data:")) data += line.slice(5).trim();
1773 }
1774 if (event === "conversation")
1775 handlers.onConversation((JSON.parse(data) as { id: string }).id);
1776 else if (event === "sources")
1777 handlers.onSources(JSON.parse(data || "[]"));
1778 else if (event === "step")
1779 handlers.onStep(JSON.parse(data) as ChatStep);
1780 else if (event === "delta")
1781 handlers.onDelta((JSON.parse(data) as { text: string }).text);
1782 else if (event === "snapshot") handlers.onSnapshot?.(JSON.parse(data));
1783 else if (event === "idle") handlers.onIdle?.();
1784 else if (event === "done") handlers.onDone();
1785 else if (event === "error") handlers.onError(data);
1786 }
1787 }
1788 handlers.onDone();
1789 } catch (e) {
1790 if (!controller.signal.aborted) handlers.onError(String(e));
1791 }
1792 })();
1793 return () => controller.abort();
1794}