Elffuss BraidHub

kikocis/utopia public

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