Elffuss BraidHub

kikocis/utopia public

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