Elffuss BraidHub

kikocis/utopia public

812efb07501a · 59.9 KiBRawPermalink
1import { S, lang } from "./i18n";
2
3export class ApiError extends Error {
4 status: number;
5 /** 服务端给的稳定错误码(没有则是尚未转换的契约守卫,message 已是英文原句) */
6 code?: string;
7 constructor(status: number, message: string, code?: string) {
8 super(message);
9 this.status = status;
10 this.code = code;
11 }
12}
13
14async function request<T>(path: string, init?: RequestInit): Promise<T> {
15 const res = await fetch(path, {
16 credentials: "include",
17 headers:
18 init?.body instanceof FormData
19 ? {}
20 : { "Content-Type": "application/json" },
21 ...init,
22 });
23 if (!res.ok) {
24 // 措辞在这一个收口点定:22 个文件里的 toast.error(e.message) 一处都不用改。
25 // 有 code 就查 i18n,没有(或这一条还没进表)就退回服务端的英文原句——
26 // 服务端永远说英文,因为界面语言在客户端(docs/decisions/0004)
27 let message = res.statusText;
28 let code: string | undefined;
29 try {
30 const body = (await res.json()) as {
31 error?: string;
32 code?: string;
33 detail?: string;
34 };
35 if (body.error) message = body.error;
36 code = body.code;
37 // code 来自网络,不是字面量——这一处 cast 换来 err 表本身的全量类型检查
38 const worded = code
39 ? (S.err as Record<string, string | undefined>)[code]
40 : undefined;
41 if (worded) message = worded;
42 if (body.detail) message = S.errDetail(message, body.detail);
43 } catch {
44 // 非 JSON 响应体,保留 statusText
45 }
46 throw new ApiError(res.status, message, code);
47 }
48 return res.json() as Promise<T>;
49}
50
51export interface User {
52 id: string;
53 org_id: string;
54 email: string;
55 display_name: string;
56 is_admin: boolean;
57 created_at: string;
58}
59
60export interface Workspace {
61 id: string;
62 org_id: string;
63 name: string;
64 created_at: string;
65}
66
67/** 建库时可选的预置本体包(`GET /ontology-packs`)。 */
68export type OntologyPack = {
69 id: string;
70 name: string;
71 summary: string;
72 classes: number;
73 properties: number;
74};
75
76export interface Kb {
77 id: string;
78 workspace_id: string;
79 name: string;
80 kind: string;
81 description: string | null;
82 visibility: "open" | "restricted";
83 /** 部署的公共默认空间(第一个建的库):永远 open、不可删除 */
84 is_default: boolean;
85 /** 抽取遇到本体外的说法时,是否允许系统自动补进本体并改写等它的事实。
86 关掉不影响"留意":未匹配统计照常累积可见,只是变成你点一下的提案 */
87 auto_extend_ontology: boolean;
88 /** 把推出来的事实写进账本(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 /** 这一步发生时正文已经有多长(UTF-16 码元,与 `string.length` 同一单位)。
770 * 据此把轨迹穿回正文里,而不是全堆在最前面。
771 * **这条迁移之前的消息没有它**——缺省时整段轨迹回到顶部,即旧的样子 */
772 at?: number;
773}
774
775/** 会话行(Chat 左栏列表)。 */
776export interface ConversationRow {
777 id: string;
778 title: string;
779 created_at: string;
780 updated_at: string;
781 message_count: number;
782}
783
784/** 会话消息(含落库的行动轨迹与引用,历史回放用)。 */
785export interface ConversationMessage {
786 id: string;
787 role: "user" | "assistant";
788 content: string;
789 steps: ChatStep[];
790 sources: Source[];
791 created_at: string;
792}
793
794/** 告警中心的一组(0005):**连着的、同类的几次故障**。
795 *
796 * 存储那边仍是一次故障一行,折叠在服务端读的时候做——这样翻页数的是组,
797 * 一段连续故障不会被页边界切断。 */
798export type AlertGroup = {
799 kb_id: string | null;
800 /** 系统级告警没有库名 */
801 kb_name: string | null;
802 /** `source.sync_failed` / `llm.unreachable` —— 措辞在 i18n 里按这个查 */
803 kind: string;
804 severity: "info" | "warning" | "error";
805 /** 这一组几次 */
806 count: number;
807 /** 其中我没读过的几次 */
808 unread: number;
809 latest_at: string;
810 /** 跟 latest_at 一起圈出这一组,标已读时原样发回去 */
811 earliest_at: string;
812 /** 明细,最多几条,新的在前 */
813 lines: { name?: string; error?: string; job?: string }[];
814};
815
816export const api = {
817 health: () =>
818 request<{ status: string; name: string; version: string }>(
819 "/api/v1/health",
820 ),
821 me: () => request<User>("/api/v1/auth/me"),
822 alerts: (o: { q?: string; limit?: number; offset?: number }) => {
823 const p = new URLSearchParams();
824 if (o.q?.trim()) p.set("q", o.q.trim());
825 if (o.limit != null) p.set("limit", String(o.limit));
826 if (o.offset) p.set("offset", String(o.offset));
827 return request<{ items: AlertGroup[]; total: number }>(
828 `/api/v1/alerts?${p}`,
829 );
830 },
831 alertsUnread: () => request<{ unread: number }>("/api/v1/alerts/unread"),
832 alertReadGroup: (g: {
833 kb_id: string | null;
834 kind: string;
835 from: string;
836 to: string;
837 }) =>
838 request<{ marked: number }>("/api/v1/alerts/read-group", {
839 method: "POST",
840 body: JSON.stringify(g),
841 }),
842 alertsReadAll: () =>
843 request<{ ok: boolean }>("/api/v1/alerts/read-all", { method: "POST" }),
844 login: (email: string, password: string) =>
845 request<{ user: User }>("/api/v1/auth/login", {
846 method: "POST",
847 body: JSON.stringify({ email, password }),
848 }),
849 register: (email: string, password: string, displayName: string) =>
850 request<{ user: User; workspace: Workspace }>("/api/v1/auth/register", {
851 method: "POST",
852 body: JSON.stringify({ email, password, display_name: displayName }),
853 }),
854 logout: () =>
855 request<{ ok: boolean }>("/api/v1/auth/logout", { method: "POST" }),
856 updateMe: (displayName: string) =>
857 request<User>("/api/v1/auth/me", {
858 method: "PATCH",
859 body: JSON.stringify({ display_name: displayName }),
860 }),
861 changePassword: (currentPassword: string, newPassword: string) =>
862 request<{ ok: boolean }>("/api/v1/auth/password", {
863 method: "POST",
864 body: JSON.stringify({
865 current_password: currentPassword,
866 new_password: newPassword,
867 }),
868 }),
869 workspaces: () => request<Workspace[]>("/api/v1/workspaces"),
870
871 kbs: (workspaceId: string) =>
872 request<Kb[]>(`/api/v1/workspaces/${workspaceId}/kbs`),
873 /** 审计台账。**分页 + 筛选**——台账是合规材料,只看最近 100 条等于查不了历史。
874 * `action` 是前缀:`entity.` 捞出 entity.retyped / entity.renamed 一族。 */
875 kbAudit: (
876 kbId: string,
877 opts: {
878 action?: string;
879 actor?: string;
880 since?: string;
881 until?: string;
882 limit: number;
883 offset: number;
884 },
885 ) => {
886 const p = new URLSearchParams({
887 limit: String(opts.limit),
888 offset: String(opts.offset),
889 });
890 if (opts.action) p.set("action", opts.action);
891 if (opts.actor) p.set("actor", opts.actor);
892 if (opts.since) p.set("since", opts.since);
893 if (opts.until) p.set("until", opts.until);
894 return request<{
895 events: AuditEvent[];
896 total: number;
897 /** 这个库实际发生过的动作,筛选下拉按它填 */
898 actions: string[];
899 }>(`/api/v1/kbs/${kbId}/audit?${p}`);
900 },
901 myKbs: (workspaceId: string) =>
902 request<{ kbs: MyKb[] }>(`/api/v1/workspaces/${workspaceId}/my-kbs`),
903 createKb: (
904 workspaceId: string,
905 body: {
906 name: string;
907 description?: string | null;
908 visibility?: string;
909 /** 预置本体包 id,顺序有意义:第一个会认领同名的种子类 */
910 ontology_packs?: string[];
911 },
912 ) =>
913 request<Kb>(`/api/v1/workspaces/${workspaceId}/kbs`, {
914 method: "POST",
915 body: JSON.stringify(body),
916 }),
917
918 ontologyPacks: () =>
919 request<{ packs: OntologyPack[] }>("/api/v1/ontology-packs"),
920
921 kbDetail: (kbId: string) => request<Kb>(`/api/v1/kbs/${kbId}`),
922 updateKb: (kbId: string, body: Record<string, unknown>) =>
923 request<Kb>(`/api/v1/kbs/${kbId}`, {
924 method: "PATCH",
925 body: JSON.stringify(body),
926 }),
927 deleteKb: (kbId: string) =>
928 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}`, { method: "DELETE" }),
929 kbMembers: (kbId: string) =>
930 request<{ members: KbMember[] }>(`/api/v1/kbs/${kbId}/members`),
931 setKbMember: (kbId: string, userId: string, role: string) =>
932 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/members/${userId}`, {
933 method: "PUT",
934 body: JSON.stringify({ role }),
935 }),
936 removeKbMember: (kbId: string, userId: string) =>
937 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/members/${userId}`, {
938 method: "DELETE",
939 }),
940
941 adminDeployment: () =>
942 request<{
943 open_registration: boolean;
944 /** 外层兜底,防任务无限堆积;真正的节流是按模型的限额 */
945 worker_concurrency: number;
946 default_model_concurrency: number;
947 /** 新建知识库的本体语言默认值。**不是界面语言**——那个在客户端 */
948 default_ontology_lang: "en" | "zh";
949 model_limits: {
950 base_url: string;
951 model: string;
952 max_concurrent: number;
953 }[];
954 models_in_use: { base_url: string; model: string; kind: string }[];
955 }>("/api/v1/admin/deployment"),
956 saveAdminDeployment: (
957 openRegistration: boolean,
958 workerConcurrency?: number,
959 defaultModelConcurrency?: number,
960 modelLimit?: {
961 base_url: string;
962 model: string;
963 max_concurrent: number | null;
964 },
965 defaultOntologyLang?: "en" | "zh",
966 ) =>
967 request<{ ok: boolean }>("/api/v1/admin/deployment", {
968 method: "PUT",
969 body: JSON.stringify({
970 open_registration: openRegistration,
971 ...(workerConcurrency !== undefined
972 ? { worker_concurrency: workerConcurrency }
973 : {}),
974 ...(defaultModelConcurrency !== undefined
975 ? { default_model_concurrency: defaultModelConcurrency }
976 : {}),
977 ...(modelLimit ? { model_limit: modelLimit } : {}),
978 ...(defaultOntologyLang
979 ? { default_ontology_lang: defaultOntologyLang }
980 : {}),
981 }),
982 }),
983 adminCreateUser: (body: {
984 email: string;
985 display_name: string;
986 password: string;
987 role: string;
988 }) =>
989 request<{ user: User }>("/api/v1/admin/users", {
990 method: "POST",
991 body: JSON.stringify(body),
992 }),
993
994 /** 已停用的账号。**没有它恢复就够不着**——那个人从所有列表里消失,
995 * 而恢复接口要的正是他的 id */
996 deactivatedUsers: () => request<OrgUser[]>("/api/v1/users/deactivated"),
997 /** 恢复一个停用的账号 */
998 adminReactivateUser: (userId: string) =>
999 request<{ ok: boolean }>(`/api/v1/admin/users/${userId}`, {
1000 method: "POST",
1001 }),
1002 /** 停用一个账号(软删除)。归因照旧查得到——审计、合并日志、改类账本都靠它 */
1003 adminDeactivateUser: (userId: string) =>
1004 request<{ ok: boolean }>(`/api/v1/admin/users/${userId}`, {
1005 method: "DELETE",
1006 }),
1007 adminDataSources: () =>
1008 request<{ data_sources: DataSourceView[] }>("/api/v1/admin/data-sources"),
1009 adminCreateDataSource: (body: { name: string; conn_string: string }) =>
1010 request<{ id: string }>("/api/v1/admin/data-sources", {
1011 method: "POST",
1012 body: JSON.stringify(body),
1013 }),
1014 adminDeleteDataSource: (id: string) =>
1015 request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}`, {
1016 method: "DELETE",
1017 }),
1018 adminTestDataSource: (id: string) =>
1019 request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}/test`, {
1020 method: "POST",
1021 }),
1022 /** 这个源授权给了哪些工作区(0014)。授权与挂载是两层:
1023 * 授权由系统管理员写,挂载由 KB 管理员在授权过的集合里挑 */
1024 dataSourceGrants: (id: string) =>
1025 request<{ workspaces: { id: string; name: string }[] }>(
1026 `/api/v1/admin/data-sources/${id}/grants`,
1027 ),
1028 grantDataSource: (id: string, workspaceId: string) =>
1029 request<{ ok: boolean }>(
1030 `/api/v1/admin/data-sources/${id}/grants/${workspaceId}`,
1031 { method: "PUT" },
1032 ),
1033 /** 收回授权。**连同该工作区里已挂上的一起卸掉**,返回卸了几个 */
1034 revokeDataSource: (id: string, workspaceId: string) =>
1035 request<{ ok: boolean; unmounted: number }>(
1036 `/api/v1/admin/data-sources/${id}/grants/${workspaceId}`,
1037 { method: "DELETE" },
1038 ),
1039
1040 /** 一页口径。**Viewer 就能看**——问数的答案直接由口径决定,
1041 * 看得见答案却看不见口径,等于要人信一个不给看的算法 */
1042 mappings: (
1043 kbId: string,
1044 opts: {
1045 status?: "proposed" | "confirmed" | "rejected";
1046 q?: string;
1047 limit?: number;
1048 offset?: number;
1049 } = {},
1050 ) => {
1051 const p = new URLSearchParams();
1052 if (opts.status) p.set("status", opts.status);
1053 if (opts.q) p.set("q", opts.q);
1054 if (opts.limit != null) p.set("limit", String(opts.limit));
1055 if (opts.offset != null) p.set("offset", String(opts.offset));
1056 const qs = p.toString();
1057 return request<{
1058 items: ConceptMapping[];
1059 total: number;
1060 counts: { proposed: number; confirmed: number; rejected: number };
1061 }>(`/api/v1/kbs/${kbId}/mappings${qs ? `?${qs}` : ""}`);
1062 },
1063 /** 改一条口径。改之前那一版自动进 revisions */
1064 reviseMapping: (
1065 kbId: string,
1066 mappingId: string,
1067 body: {
1068 table_name?: string | null;
1069 expr?: string | null;
1070 sql?: string | null;
1071 unit?: string | null;
1072 summary?: string | null;
1073 derived: boolean;
1074 },
1075 ) =>
1076 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/mappings/${mappingId}`, {
1077 method: "PATCH",
1078 body: JSON.stringify(body),
1079 }),
1080 mappingRevisions: (kbId: string, mappingId: string) =>
1081 request<{ revisions: MappingRevision[] }>(
1082 `/api/v1/kbs/${kbId}/mappings/${mappingId}/revisions`,
1083 ),
1084 kbDataSources: (kbId: string) =>
1085 request<{ data_sources: DataSourceView[] }>(
1086 `/api/v1/kbs/${kbId}/data-sources`,
1087 ),
1088 kbDataSourcesAvailable: (kbId: string) =>
1089 request<{ data_sources: DataSourceView[] }>(
1090 `/api/v1/kbs/${kbId}/data-sources/available`,
1091 ),
1092 /** 挂载。**`schema_error` 非空时挂载仍然成了**——源是真挂上的,只是它的
1093 * 库表结构没摄进来,问数看不见有哪些表。同一件事会进告警中心 */
1094 mountDataSource: (kbId: string, dsId: string) =>
1095 request<{
1096 ok: boolean;
1097 schema_tables: number;
1098 schema_error?: string | null;
1099 }>(`/api/v1/kbs/${kbId}/data-sources/${dsId}`, {
1100 method: "PUT",
1101 }),
1102 unmountDataSource: (kbId: string, dsId: string) =>
1103 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/${dsId}`, {
1104 method: "DELETE",
1105 }),
1106 exploreMappings: (kbId: string) =>
1107 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/explore`, {
1108 method: "POST",
1109 }),
1110 syncDataSourceSchema: (kbId: string, dsId: string) =>
1111 request<{ ok: boolean; schema_tables: number }>(
1112 `/api/v1/kbs/${kbId}/data-sources/${dsId}/sync-schema`,
1113 { method: "POST" },
1114 ),
1115
1116 /** 文库一页。**服务端筛选与分页**——从前一次取回整库、前端切片,
1117 * 而客户端筛选只筛得到已经拿下来的那些 */
1118 documents: (
1119 kbId: string,
1120 opts: {
1121 source?: string;
1122 q?: string;
1123 graph?: string;
1124 limit: number;
1125 offset: number;
1126 },
1127 ) => {
1128 const p = new URLSearchParams({
1129 limit: String(opts.limit),
1130 offset: String(opts.offset),
1131 });
1132 if (opts.source) p.set("source", opts.source);
1133 if (opts.q) p.set("q", opts.q);
1134 if (opts.graph) p.set("graph", opts.graph);
1135 return request<{
1136 docs: Doc[];
1137 total: number;
1138 /** 下面三个**只按来源作用域算**,不受名字/状态筛选影响——
1139 * 它们是批量按钮的作用范围 */
1140 ready: number;
1141 extracting: number;
1142 failed: number;
1143 }>(`/api/v1/kbs/${kbId}/documents?${p}`);
1144 },
1145 /** 一键重试这个作用域里全部抽取失败的文档 */
1146 retryFailedDocs: (kbId: string, source?: string) =>
1147 request<{ queued: number; found: number }>(
1148 `/api/v1/kbs/${kbId}/documents/retry-failed${source ? `?source=${source}` : ""}`,
1149 { method: "POST" },
1150 ),
1151 /** 整库一次取回:行数按 (文档 × 原因 × 对象) 聚合后很小,避免逐行发请求 */
1152 extractionDrops: (kbId: string) =>
1153 request<{ drops: ExtractionDrop[] }>(
1154 `/api/v1/kbs/${kbId}/extraction-drops`,
1155 ),
1156 upload: (kbId: string, files: File[], sourceId?: string) => {
1157 const form = new FormData();
1158 for (const f of files) form.append("files", f, f.name);
1159 const qs = sourceId ? `?source=${sourceId}` : "";
1160 return request<{ created: Doc[]; skipped: unknown[] }>(
1161 `/api/v1/kbs/${kbId}/documents${qs}`,
1162 { method: "POST", body: form },
1163 );
1164 },
1165 deleteDocument: (id: string) =>
1166 request<{ ok: boolean }>(`/api/v1/documents/${id}`, { method: "DELETE" }),
1167
1168 search: (kbId: string, q: string) =>
1169 request<{ results: SearchResult[] }>(`/api/v1/kbs/${kbId}/search`, {
1170 method: "POST",
1171 body: JSON.stringify({ q }),
1172 }),
1173
1174 settings: (workspaceId: string) =>
1175 request<LlmSettingsView>(`/api/v1/workspaces/${workspaceId}/settings`),
1176 saveSettings: (workspaceId: string, body: Record<string, unknown>) =>
1177 request<{ ok: boolean }>(`/api/v1/workspaces/${workspaceId}/settings`, {
1178 method: "PUT",
1179 body: JSON.stringify(body),
1180 }),
1181 graphOverview: (kbId: string, limit?: number) =>
1182 request<{
1183 nodes: GraphNode[];
1184 edges: GraphEdge[];
1185 /** 库里一共有多少。**与 nodes.length 不是一回事**——画布只画度数最高的
1186 * 那一批,把上限当成规模显示是这个接口从前最误导人的地方 */
1187 total_nodes?: number;
1188 total_edges?: number;
1189 }>(
1190 `/api/v1/kbs/${kbId}/graph/overview${limit ? `?limit=${limit}` : ""}`,
1191 ),
1192 /** 邻域视图**没有总数**:它本来就只是一小片,说「共 325 个」没有意义。
1193 * 两个字段声明成可选,好让调用方与总览共用一个类型 */
1194 graphNeighborhood: (kbId: string, entityId: string) =>
1195 request<{
1196 nodes: GraphNode[];
1197 edges: GraphEdge[];
1198 total_nodes?: number;
1199 total_edges?: number;
1200 }>(`/api/v1/kbs/${kbId}/graph/neighborhood?entity=${entityId}&hops=2`),
1201 /** 按名字找实体。**一并回总数**——「宁分勿合」会造出一堆同名,
1202 * 固定十条时想找的那个可能根本不在这十条里 */
1203 searchEntities: (kbId: string, q: string, limit = 10) =>
1204 request<{ entities: GraphNode[]; total: number }>(
1205 `/api/v1/kbs/${kbId}/entities?q=${encodeURIComponent(q)}&limit=${limit}`,
1206 ),
1207 entityDetail: (kbId: string, entityId: string) =>
1208 request<{
1209 entity: GraphNode;
1210 facts: EntityFact[];
1211 /** 推出来的那些**单独一个键**,不掺进 facts:混在同一个列表里,
1212 * 用户看不出「文档里写的」和「引擎推的」的区别 */
1213 derived: DerivedFact[];
1214 /** 同名的其他实体。**打开面板就给**——合并入口要长在能看见同名的地方,
1215 * 而不是藏在「改一次名」之后 */
1216 same_name: GraphNode[];
1217 }>(`/api/v1/kbs/${kbId}/entities/${entityId}`),
1218 /** 认知变更历史(记录时间轴):服务端分页 */
1219 /** 人工修正实体的类型或名字。同名不拦——返回的 same_name 供界面提示是否合并。 */
1220 updateEntity: (
1221 kbId: string,
1222 entityId: string,
1223 body: { type_id?: string; canonical_name?: string },
1224 ) =>
1225 request<{ entity: GraphNode; same_name: GraphNode[] }>(
1226 `/api/v1/kbs/${kbId}/entities/${entityId}`,
1227 { method: "PATCH", body: JSON.stringify(body) },
1228 ),
1229
1230 entityHistory: (kbId: string, entityId: string, page: number, per = 30) =>
1231 request<{ events: EntityHistoryEvent[]; total: number }>(
1232 `/api/v1/kbs/${kbId}/entities/${entityId}/history?page=${page}&per=${per}`,
1233 ),
1234 factEvidence: (kbId: string, factId: string) =>
1235 request<{ evidence: Evidence[] }>(
1236 `/api/v1/kbs/${kbId}/facts/${factId}/evidence`,
1237 ),
1238 documentDetail: (id: string) =>
1239 request<{ document: Doc; chunks: ChunkFull[] }>(`/api/v1/documents/${id}`),
1240 extractDocument: (id: string) =>
1241 request<{ job_id: number }>(`/api/v1/documents/${id}/extract`, {
1242 method: "POST",
1243 }),
1244 reprocessDocument: (id: string) =>
1245 request<{ job_id: number }>(`/api/v1/documents/${id}/reprocess`, {
1246 method: "POST",
1247 }),
1248 /** 来源级全量重抽(增量语义:既有决策保留) */
1249 reExtractSource: (kbId: string, sourceId: string) =>
1250 request<{ queued: number }>(
1251 `/api/v1/kbs/${kbId}/sources/${sourceId}/re-extract`,
1252 {
1253 method: "POST",
1254 },
1255 ),
1256 /** 图谱重建(清算语义:清空图层后全量重抽;KB admin) */
1257 rebuildGraph: (kbId: string) =>
1258 request<{
1259 entities_removed: number;
1260 facts_removed: number;
1261 queued: number;
1262 }>(`/api/v1/kbs/${kbId}/graph/rebuild`, { method: "POST" }),
1263
1264 ontology: (kbId: string) =>
1265 request<{
1266 entity_types: EntityTypeView[];
1267 relation_types: RelationTypeView[];
1268 misses: OntologyMiss[];
1269 /** 已忽略的,连同它此后继续累积的计数。抑制照旧,只是看得见 */
1270 dismissed_misses: OntologyMiss[];
1271 }>(`/api/v1/kbs/${kbId}/ontology`),
1272 createEntityType: (kbId: string, body: Record<string, unknown>) =>
1273 request<{ id: string }>(`/api/v1/kbs/${kbId}/ontology/entity-types`, {
1274 method: "POST",
1275 body: JSON.stringify(body),
1276 }),
1277 updateEntityType: (kbId: string, id: string, body: Record<string, unknown>) =>
1278 request<{ ok: boolean }>(
1279 `/api/v1/kbs/${kbId}/ontology/entity-types/${id}`,
1280 {
1281 method: "PATCH",
1282 body: JSON.stringify(body),
1283 },
1284 ),
1285 deleteEntityType: (kbId: string, id: string) =>
1286 request<{ ok: boolean }>(
1287 `/api/v1/kbs/${kbId}/ontology/entity-types/${id}`,
1288 {
1289 method: "DELETE",
1290 },
1291 ),
1292 typeEntities: (kbId: string, typeId: string, page: number, per = 12) =>
1293 request<{
1294 entities: { id: string; name: string; fact_count: number }[];
1295 total: number;
1296 }>(
1297 `/api/v1/kbs/${kbId}/ontology/entity-types/${typeId}/entities?page=${page}&per=${per}`,
1298 ),
1299 createRelationType: (kbId: string, body: Record<string, unknown>) =>
1300 request<{ id: string }>(`/api/v1/kbs/${kbId}/ontology/relation-types`, {
1301 method: "POST",
1302 body: JSON.stringify(body),
1303 }),
1304 updateRelationType: (
1305 kbId: string,
1306 id: string,
1307 body: Record<string, unknown>,
1308 ) =>
1309 request<{ ok: boolean }>(
1310 `/api/v1/kbs/${kbId}/ontology/relation-types/${id}`,
1311 {
1312 method: "PATCH",
1313 body: JSON.stringify(body),
1314 },
1315 ),
1316 deleteRelationType: (kbId: string, id: string) =>
1317 request<{ ok: boolean }>(
1318 `/api/v1/kbs/${kbId}/ontology/relation-types/${id}`,
1319 {
1320 method: "DELETE",
1321 },
1322 ),
1323 /** 上次算出来、还没人表态的提案(0049)。刷新页面靠它,不必重跑模型 */
1324 storedProposals: (kbId: string) =>
1325 request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/proposals`),
1326 /** 一条提案有人表态了。改状态不删行——拒绝留痕,下一轮 Suggest 不再刷回待看 */
1327 decideProposal: (
1328 kbId: string,
1329 section: string,
1330 key: string,
1331 status: "adopted" | "rejected",
1332 ) =>
1333 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/proposals`, {
1334 method: "POST",
1335 body: JSON.stringify({ section, key, status }),
1336 }),
1337 dismissMiss: (kbId: string, kind: string, key: string) =>
1338 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/misses/dismiss`, {
1339 method: "POST",
1340 body: JSON.stringify({ kind, key }),
1341 }),
1342 restoreMiss: (kbId: string, kind: string, key: string) =>
1343 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/misses/restore`, {
1344 method: "POST",
1345 body: JSON.stringify({ kind, key }),
1346 }),
1347 /** reason 只给人看,而人就在这次请求的另一端——所以语言由调用方说,
1348 不是后端的设置(docs/decisions/0004)。description 的语言跟知识库走,服务端自己知道 */
1349 suggestOntology: (kbId: string) =>
1350 request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/suggest`, {
1351 method: "POST",
1352 body: JSON.stringify({ locale: lang }),
1353 }),
1354
1355 /** 上传本体文件只算出计划,一个字节都不写库 */
1356 previewOntologyImport: (kbId: string, file: File) => {
1357 const form = new FormData();
1358 form.append("file", file, file.name);
1359 return request<{ filename: string; plan: ImportPlan }>(
1360 `/api/v1/kbs/${kbId}/ontology/imports/preview`,
1361 { method: "POST", body: form },
1362 );
1363 },
1364 /** 执行刚看过的那个计划——服务端重新算一遍,两条路径共用同一段代码 */
1365 applyOntologyImport: (kbId: string, file: File) => {
1366 const form = new FormData();
1367 form.append("file", file, file.name);
1368 return request<{ import_id: string; plan: ImportPlan }>(
1369 `/api/v1/kbs/${kbId}/ontology/imports`,
1370 { method: "POST", body: form },
1371 );
1372 },
1373 ontologyImports: (kbId: string) =>
1374 request<{ imports: OntologyImportView[] }>(
1375 `/api/v1/kbs/${kbId}/ontology/imports`,
1376 ),
1377
1378 proposedPredicates: (kbId: string) =>
1379 request<{ forms: ProposedPredicate[] }>(
1380 `/api/v1/kbs/${kbId}/ontology/proposed-predicates`,
1381 ),
1382 /** 最近一次自动扩本体做了什么,以及还能不能撤销(撤干净了返回 null) */
1383 lastAutoExtension: (kbId: string) =>
1384 request<{
1385 run: {
1386 at: string;
1387 relations: string[] | null;
1388 classes: string[] | null;
1389 facts_remapped: number | null;
1390 batches: string[];
1391 } | null;
1392 }>(`/api/v1/kbs/${kbId}/ontology/auto-extension`),
1393 /** 建关系 **并**把等着它的无谓词事实认过去——后半句才是收益 */
1394 adoptPredicate: (
1395 kbId: string,
1396 body: {
1397 key: string;
1398 /** true = key 指的是已有的关系/属性,只改写事实,不建新类型 */
1399 existing?: boolean;
1400 /** attribute 走另一条改写路径:值要按 datatype 换算 */
1401 kind?: "relation" | "attribute";
1402 datatype?: string;
1403 unit?: string;
1404 label?: string;
1405 temporal?: string;
1406 functional?: boolean;
1407 description?: string;
1408 forms: string[];
1409 },
1410 ) =>
1411 request<{
1412 id: string;
1413 remapped: number;
1414 batch: string;
1415 /** 值换不动那个 datatype、因而没被改写的条数。改写了 3 条丢下 2 条,
1416 只报前半句就是报喜不报忧 */
1417 unconvertible?: number;
1418 }>(`/api/v1/kbs/${kbId}/ontology/adopt-predicate`, {
1419 method: "POST",
1420 body: JSON.stringify(body),
1421 }),
1422 /** 撤销一次采纳:新写的行作废、旧行复活。关系类型留着 */
1423 unadoptPredicate: (kbId: string, batchId: string) =>
1424 request<{ reverted: number }>(
1425 `/api/v1/kbs/${kbId}/ontology/adopt-predicate/${batchId}`,
1426 { method: "DELETE" },
1427 ),
1428
1429 sources: (kbId: string) =>
1430 request<{ sources: SourceView[] }>(`/api/v1/kbs/${kbId}/sources`),
1431 createSource: (kbId: string, body: Record<string, unknown>) =>
1432 request<{ source: SourceView; ingest_token?: string | null }>(
1433 `/api/v1/kbs/${kbId}/sources`,
1434 {
1435 method: "POST",
1436 body: JSON.stringify(body),
1437 },
1438 ),
1439 sourceToken: (kbId: string, sourceId: string) =>
1440 request<{ ingest_token: string | null }>(
1441 `/api/v1/kbs/${kbId}/sources/${sourceId}/token`,
1442 ),
1443 rotateSourceToken: (kbId: string, sourceId: string) =>
1444 request<{ ingest_token: string }>(
1445 `/api/v1/kbs/${kbId}/sources/${sourceId}/rotate-token`,
1446 { method: "POST" },
1447 ),
1448 updateSource: (
1449 kbId: string,
1450 sourceId: string,
1451 body: Record<string, unknown>,
1452 ) =>
1453 request<{ source: SourceView }>(`/api/v1/kbs/${kbId}/sources/${sourceId}`, {
1454 method: "PATCH",
1455 body: JSON.stringify(body),
1456 }),
1457 deleteSource: (kbId: string, sourceId: string) =>
1458 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/sources/${sourceId}`, {
1459 method: "DELETE",
1460 }),
1461 cleanupMissing: (kbId: string, sourceId: string) =>
1462 request<{ deleted: number }>(
1463 `/api/v1/kbs/${kbId}/sources/${sourceId}/missing/cleanup`,
1464 {
1465 method: "POST",
1466 },
1467 ),
1468 syncSource: (kbId: string, sourceId: string) =>
1469 request<{ queued: boolean }>(
1470 `/api/v1/kbs/${kbId}/sources/${sourceId}/sync`,
1471 {
1472 method: "POST",
1473 },
1474 ),
1475 sourceRuns: (kbId: string, sourceId: string) =>
1476 request<{ runs: SyncRun[] }>(
1477 `/api/v1/kbs/${kbId}/sources/${sourceId}/runs`,
1478 ),
1479 documentExtractions: (docId: string) =>
1480 request<{ facts: ChunkFact[] }>(`/api/v1/documents/${docId}/extractions`),
1481
1482 /** 审核队列的各档**真实条数**。与列表分开取——列表有一页的上限,数数没有。
1483 * 从前徽标读的是数组长度,而接口固定只回 100 条,于是 164 条写成 100。 */
1484 review: (kbId: string, queue: ReviewQueue, limit: number, offset: number) =>
1485 request<{
1486 counts: ReviewCounts;
1487 queue: ReviewQueue;
1488 /** 只有当前这一档的一页。类型按档不同,调用处按 queue 收窄 */
1489 items: unknown[];
1490 }>(
1491 `/api/v1/kbs/${kbId}/review?queue=${queue}&limit=${limit}&offset=${offset}`,
1492 ),
1493 closeFact: (kbId: string, factId: string, validTo: string) =>
1494 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/close`, {
1495 method: "POST",
1496 body: JSON.stringify({ valid_to: validTo }),
1497 }),
1498 resolveConflict: (
1499 kbId: string,
1500 conflictId: string,
1501 body: { action: "close" | "keep" | "reject_new"; close_at?: string },
1502 ) =>
1503 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conflicts/${conflictId}`, {
1504 method: "POST",
1505 body: JSON.stringify(body),
1506 }),
1507 decideReview: (kbId: string, reviewId: string, action: "merge" | "keep") =>
1508 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/${reviewId}`, {
1509 method: "POST",
1510 body: JSON.stringify({ action }),
1511 }),
1512 /** 对一条数据映射口径表态(0011)。改状态不删行——拒绝留痕,下一轮探索不再提议它 */
1513 decideMapping: (
1514 kbId: string,
1515 mappingId: string,
1516 status: "confirmed" | "rejected",
1517 ) =>
1518 request<{ ok: boolean }>(
1519 `/api/v1/kbs/${kbId}/review/mappings/${mappingId}`,
1520 {
1521 method: "POST",
1522 body: JSON.stringify({ status }),
1523 },
1524 ),
1525 /** 跑一遍一致性检查。同步返回——纯计算,没有模型调用也没有网络 */
1526 runConsistencyCheck: (kbId: string) =>
1527 request<{
1528 edges: number;
1529 /** **零和零不一样**:没有公理时结论是「没有判据」,不是「未发现矛盾」 */
1530 predicates_with_axioms: number;
1531 found: number;
1532 inserted: number;
1533 cleared: number;
1534 classes: number;
1535 /** 本体自己的矛盾**单独回**,不加进 found:两个数不是一类东西 */
1536 defects_found: number;
1537 defects_new: number;
1538 }>(`/api/v1/kbs/${kbId}/consistency/check`, { method: "POST" }),
1539 /** 对一处本体缺陷表态。**两个出路**——它压根没看数据,没有「数据错了」这条 */
1540 decideDefect: (
1541 kbId: string,
1542 defectId: string,
1543 resolution: "fixed" | "accepted",
1544 ) =>
1545 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/defects/${defectId}`, {
1546 method: "POST",
1547 body: JSON.stringify({ resolution }),
1548 }),
1549 /** 跑一遍推理(R1)。开关关着时后端回 inference_off */
1550 /** 类型消解:**只算不写**。回执里带着送去检索的画像——检索找不着时,
1551 * 第一个要看的就是「我们拿什么去找的」 */
1552 /** 手动合并:把 source 并进 target。**方向要紧**——source 消失,
1553 * 它的事实搬到 target 上;合并可整体回滚(entity_merges 记着快照) */
1554 mergeEntities: (kbId: string, source: string, target: string) =>
1555 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/entities/merge`, {
1556 method: "POST",
1557 body: JSON.stringify({ source, target }),
1558 }),
1559 typeResolutionPreview: (kbId: string) =>
1560 request<{ items: TypeSuggestion[] }>(
1561 `/api/v1/kbs/${kbId}/ontology/type-resolution/preview`,
1562 { method: "POST" },
1563 ),
1564 /** 跑一遍并落库。三档分开回:自动改的、留给人的、说「都不是」的 */
1565 typeResolutionApply: (kbId: string) =>
1566 request<ResolutionOutcome>(`/api/v1/kbs/${kbId}/ontology/type-resolution`, {
1567 method: "POST",
1568 }),
1569 /** 认可一个「粗类 → 细类」的配对,并把带上的实体改过去。
1570 * **认可的是类对,改的是实体**——认可一次,之后同一对不再进人工 */
1571 approveRefinement: (
1572 kbId: string,
1573 body: { from_type_id: string; to_type_id: string; entity_ids: string[] },
1574 ) =>
1575 request<{ retyped: number }>(
1576 `/api/v1/kbs/${kbId}/ontology/type-resolution/approve`,
1577 { method: "POST", body: JSON.stringify(body) },
1578 ),
1579 /** 撤销一整批:把那批实体放回原来的类 */
1580 typeResolutionUndo: (kbId: string, batchId: string) =>
1581 request<{ reverted: number }>(
1582 `/api/v1/kbs/${kbId}/ontology/type-resolution/${batchId}`,
1583 { method: "DELETE" },
1584 ),
1585 runInference: (kbId: string) =>
1586 request<{
1587 /** 编译出来的规则条数。为零时是「没有规则」而不是「推不出东西」 */
1588 rules: number;
1589 edges: number;
1590 derived: number;
1591 inserted: number;
1592 /** 前提没了、跟着作废的 */
1593 invalidated: number;
1594 /** 撞上单谓词上限、没推完的谓词个数 */
1595 capped: number;
1596 }>(`/api/v1/kbs/${kbId}/inference/run`, { method: "POST" }),
1597 /** 对一处公理违规表态。三个出路——第三个是这一档独有的:可能是定义错了 */
1598 decideViolation: (
1599 kbId: string,
1600 violationId: string,
1601 resolution: "fact_retracted" | "axiom_relaxed" | "accepted",
1602 ) =>
1603 request<{ ok: boolean }>(
1604 `/api/v1/kbs/${kbId}/review/violations/${violationId}`,
1605 { method: "POST", body: JSON.stringify({ resolution }) },
1606 ),
1607 confirmFact: (kbId: string, factId: string) =>
1608 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/confirm`, {
1609 method: "POST",
1610 }),
1611 rejectFact: (kbId: string, factId: string) =>
1612 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/reject`, {
1613 method: "POST",
1614 }),
1615 revertMerge: (kbId: string, mergeId: string) =>
1616 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/merges/${mergeId}/revert`, {
1617 method: "POST",
1618 }),
1619 reviewHistory: (kbId: string, page: number, per = 20) =>
1620 request<{ events: ReviewHistoryEvent[]; total: number }>(
1621 `/api/v1/kbs/${kbId}/review/history?page=${page}&per=${per}`,
1622 ),
1623
1624 members: (workspaceId: string) =>
1625 request<Member[]>(`/api/v1/workspaces/${workspaceId}/members`),
1626 orgUsers: () => request<OrgUser[]>("/api/v1/users"),
1627 setMemberRole: (workspaceId: string, userId: string, role: string) =>
1628 request<{ ok: boolean }>(
1629 `/api/v1/workspaces/${workspaceId}/members/${userId}`,
1630 {
1631 method: "PUT",
1632 body: JSON.stringify({ role }),
1633 },
1634 ),
1635 removeMember: (workspaceId: string, userId: string) =>
1636 request<{ ok: boolean }>(
1637 `/api/v1/workspaces/${workspaceId}/members/${userId}`,
1638 {
1639 method: "DELETE",
1640 },
1641 ),
1642
1643 testSettings: (workspaceId: string) =>
1644 request<{
1645 chat: { ok: boolean; reply?: string; error?: string };
1646 embed: { ok: boolean; dim?: number; error?: string };
1647 }>(`/api/v1/workspaces/${workspaceId}/settings/test`, { method: "POST" }),
1648};
1649
1650/** RAG 对话:SSE 流式。返回中止函数。 */
1651export const conversationsApi = {
1652 /** **可搜可翻页**:标题会重(同一个问题问两次就重了),而固定一百条之后的
1653 * 会话界面上根本不存在。搜的是标题与消息正文两处——人记得住的往往是
1654 * 问过的那句话,不是标题 */
1655 list: (kbId: string, q = "", limit = 30, offset = 0) => {
1656 const p = new URLSearchParams({
1657 limit: String(limit),
1658 offset: String(offset),
1659 });
1660 if (q.trim()) p.set("q", q.trim());
1661 return request<{ conversations: ConversationRow[]; total: number }>(
1662 `/api/v1/kbs/${kbId}/conversations?${p}`,
1663 );
1664 },
1665 /** 改标题。标题本来是从第一句话自动取的,而一段对话跑偏是常态 */
1666 rename: (kbId: string, id: string, title: string) =>
1667 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conversations/${id}`, {
1668 method: "PATCH",
1669 body: JSON.stringify({ title }),
1670 }),
1671 detail: (kbId: string, id: string) =>
1672 request<{ messages: ConversationMessage[] }>(
1673 `/api/v1/kbs/${kbId}/conversations/${id}`,
1674 ),
1675 remove: (kbId: string, id: string) =>
1676 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conversations/${id}`, {
1677 method: "DELETE",
1678 }),
1679};
1680
1681export interface ChatHandlers {
1682 onConversation: (id: string) => void;
1683 onSources: (s: Source[]) => void;
1684 onStep: (s: ChatStep) => void;
1685 onDelta: (text: string) => void;
1686 onDone: () => void;
1687 onError: (message: string) => void;
1688 /** 接上一个已经在跑的回答:这是它此刻的样子,**覆盖,不是追加** */
1689 onSnapshot?: (s: { content: string; steps: ChatStep[]; sources: Source[] }) => void;
1690 /** 这个会话没有在跑的生成——最常见的答案,不是错误 */
1691 onIdle?: () => void;
1692}
1693
1694/** 接上一个正在生成的回答(刷新页面之后走这里)。
1695 *
1696 * 与 `streamChat` 读的是同一条事件流,只是多了开头那份快照。 */
1697export function reattachChat(
1698 kbId: string,
1699 conversationId: string,
1700 handlers: ChatHandlers,
1701): () => void {
1702 return consumeChatStream(
1703 (signal) =>
1704 fetch(`/api/v1/kbs/${kbId}/conversations/${conversationId}/stream`, {
1705 credentials: "include",
1706 signal,
1707 }),
1708 handlers,
1709 );
1710}
1711
1712export function streamChat(
1713 kbId: string,
1714 body: { conversation_id?: string; message: string },
1715 handlers: ChatHandlers,
1716): () => void {
1717 return consumeChatStream(
1718 (signal) =>
1719 fetch(`/api/v1/kbs/${kbId}/chat`, {
1720 method: "POST",
1721 credentials: "include",
1722 headers: { "Content-Type": "application/json" },
1723 body: JSON.stringify(body),
1724 signal,
1725 }),
1726 handlers,
1727 );
1728}
1729
1730/** SSE 的读法只有一份:发起请求的方式不同,收下来之后的处理完全一样。 */
1731function consumeChatStream(
1732 open: (signal: AbortSignal) => Promise<Response>,
1733 handlers: ChatHandlers,
1734): () => void {
1735 const controller = new AbortController();
1736 (async () => {
1737 try {
1738 const res = await open(controller.signal);
1739 if (!res.ok || !res.body) {
1740 let message = res.statusText;
1741 try {
1742 const body = (await res.json()) as { error?: string };
1743 if (body.error) message = body.error;
1744 } catch {
1745 /* ignore */
1746 }
1747 handlers.onError(message);
1748 return;
1749 }
1750 const reader = res.body.getReader();
1751 const decoder = new TextDecoder();
1752 let buf = "";
1753 for (;;) {
1754 const { done, value } = await reader.read();
1755 if (done) break;
1756 buf += decoder.decode(value, { stream: true });
1757 let idx: number;
1758 while ((idx = buf.indexOf("\n\n")) >= 0) {
1759 const frame = buf.slice(0, idx);
1760 buf = buf.slice(idx + 2);
1761 let event = "message";
1762 let data = "";
1763 for (const line of frame.split("\n")) {
1764 if (line.startsWith("event:")) event = line.slice(6).trim();
1765 else if (line.startsWith("data:")) data += line.slice(5).trim();
1766 }
1767 if (event === "conversation")
1768 handlers.onConversation((JSON.parse(data) as { id: string }).id);
1769 else if (event === "sources")
1770 handlers.onSources(JSON.parse(data || "[]"));
1771 else if (event === "step")
1772 handlers.onStep(JSON.parse(data) as ChatStep);
1773 else if (event === "delta")
1774 handlers.onDelta((JSON.parse(data) as { text: string }).text);
1775 else if (event === "snapshot") handlers.onSnapshot?.(JSON.parse(data));
1776 else if (event === "idle") handlers.onIdle?.();
1777 else if (event === "done") handlers.onDone();
1778 else if (event === "error") handlers.onError(data);
1779 }
1780 }
1781 handlers.onDone();
1782 } catch (e) {
1783 if (!controller.signal.aborted) handlers.onError(String(e));
1784 }
1785 })();
1786 return () => controller.abort();
1787}