Elffuss BraidHub

kikocis/utopia public

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