Elffuss BraidHub

kikocis/utopia public

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