Elffuss BraidHub

kikocis/utopia public

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