Elffuss BraidHub

kikocis/utopia public

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