ai-helper-agent 2.7.0 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/assets/{agent-store-B3YTug9u.js → agent-store-CrkBz4jI.js} +1 -1
  2. package/dist/assets/background.js +88 -71
  3. package/dist/assets/chat-export-BZ5KC0qd.js +37 -0
  4. package/dist/assets/content.js +30 -30
  5. package/dist/assets/{i18n-3Yjz1yjD.js → i18n-DU8C0Dir.js} +4 -4
  6. package/dist/assets/{markdown-render-gukxI2k-.js → markdown-render-BVLp_kOz.js} +3 -3
  7. package/dist/assets/model-profiles-Czl5eTZY.js +24 -0
  8. package/dist/assets/{options-DMfGHPSS.css → options-d_q5bb5y.css} +1 -1
  9. package/dist/assets/options.js +113 -92
  10. package/dist/assets/{page-snapshot-renderer-CNpsnBGY.js → page-snapshot-renderer-hjJdKBBL.js} +1 -1
  11. package/dist/assets/session-store-D93MJNgp.js +84 -0
  12. package/dist/assets/side_panel.css +1 -1
  13. package/dist/assets/side_panel.js +350 -313
  14. package/dist/assets/{utils-CbVJXFy8.js → utils-CbwqBtBF.js} +1 -1
  15. package/dist/assets/{version-Dn5x2y3p.js → version-B5_tcFNU.js} +1 -1
  16. package/dist/assets/{workspace-manager-iSLqL-5b.js → workspace-manager-Dq1z6ENd.js} +1 -1
  17. package/dist/manifest.json +1 -1
  18. package/dist/offscreen/offscreen.js +4 -4
  19. package/dist/options.html +37 -4
  20. package/dist/side_panel.html +34 -8
  21. package/package.json +1 -1
  22. package/src/config.js +3 -0
  23. package/src/locales/en.json +3 -0
  24. package/src/locales/zh.json +3 -0
  25. package/src/rag/config.js +19 -0
  26. package/src/rag/manager.js +351 -43
  27. package/src/rag/routes.js +83 -2
  28. package/dist/assets/chat-export-D23FaEWE.js +0 -37
  29. package/dist/assets/model-profiles-brq461y3.js +0 -24
  30. package/dist/assets/session-store-QkSYgz0Z.js +0 -81
@@ -7,12 +7,13 @@
7
7
  // - 检索(以知识库注册表中的 embedding 配置为准,保证链路一致性)
8
8
  // 存储布局见 config.js / 设计文档 5.2
9
9
 
10
- import { join, extname } from 'path';
10
+ import { join, extname, basename } from 'path';
11
11
  import { tmpdir } from 'os';
12
12
  import { mkdir, readFile, writeFile, rm, unlink, readdir, rename, stat, chmod } from 'fs/promises';
13
- import { randomBytes } from 'crypto';
13
+ import { randomBytes, createHash } from 'crypto';
14
14
  import {
15
- RAG_ROOT, COLLECTIONS_REGISTRY, COLLECTION_ID_PREFIX,
15
+ RAG_ROOT, COLLECTIONS_REGISTRY, COLLECTION_ID_PREFIX, ORIGINALS_ROOT, PARSER_ROUTES,
16
+ DEFAULT_ORIGINALS_CONFIG, DOC_TEXT_VIEW_MAX_CHARS,
16
17
  DEFAULT_EMBEDDING_CONFIG, DEFAULT_CHUNK_CONFIG, EMBED_BATCH_SIZE,
17
18
  } from './config.js';
18
19
  import { createEmbeddingProvider } from './embedding/index.js';
@@ -55,6 +56,54 @@ function formatBytes(bytes) {
55
56
  : `${Math.round(bytes / 1024)}KB`;
56
57
  }
57
58
 
59
+ // 原件扩展名白名单形态:只接受 .pdf 这类安全后缀(防拼出越界路径),其余落 .bin
60
+ const ORIGINAL_EXT_RE = /^\.[a-z0-9]{1,8}$/;
61
+ const ORIGINAL_FALLBACK_EXT = '.bin';
62
+
63
+ // 原件下载响应用的 MIME 映射(只覆盖解析器支持的格式;未命中的按二进制流下载)
64
+ const MIME_BY_EXT = {
65
+ '.pdf': 'application/pdf',
66
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
67
+ '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
68
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
69
+ '.xls': 'application/vnd.ms-excel',
70
+ '.html': 'text/html; charset=utf-8',
71
+ '.htm': 'text/html; charset=utf-8',
72
+ '.txt': 'text/plain; charset=utf-8',
73
+ '.md': 'text/markdown; charset=utf-8',
74
+ '.json': 'application/json; charset=utf-8',
75
+ '.csv': 'text/csv; charset=utf-8',
76
+ '.rtf': 'application/rtf',
77
+ '.odt': 'application/vnd.oasis.opendocument.text',
78
+ };
79
+
80
+ /**
81
+ * 规范化原件扩展名(不合白名单形态的一律落 .bin)
82
+ * @param {string} ext
83
+ * @returns {string}
84
+ */
85
+ function safeOriginalExt(ext) {
86
+ const value = String(ext || '').toLowerCase();
87
+ return ORIGINAL_EXT_RE.test(value) ? value : ORIGINAL_FALLBACK_EXT;
88
+ }
89
+
90
+ /**
91
+ * 按扩展名推断原件 MIME(下载响应头用)
92
+ * @param {string} ext
93
+ * @returns {string}
94
+ */
95
+ function guessMime(ext) {
96
+ return MIME_BY_EXT[String(ext || '').toLowerCase()] || 'application/octet-stream';
97
+ }
98
+
99
+ /**
100
+ * 生成文档 ID(doc_ 前缀 + 时间 36 进制 + 随机后缀)
101
+ * @returns {string}
102
+ */
103
+ function newDocumentId() {
104
+ return `doc_${Date.now().toString(36)}${randomBytes(4).toString('hex')}`;
105
+ }
106
+
58
107
  // 远端(OpenAI 兼容)模式的字段默认值(与 embedding/index.js 的运行时兜底保持一致)
59
108
  // dimensions: 0 表示未显式指定 → 不向服务端透传 dimensions,使用平台默认维度
60
109
  const REMOTE_EMBEDDING_DEFAULTS = {
@@ -181,6 +230,8 @@ export class RagManager {
181
230
  this._activeOps = new Set();
182
231
  // URL 导入内网放行策略覆盖(仅测试注入;缺省 null 时读取 config.ragUrlIngest)
183
232
  this._urlIngestPolicyOverride = options.urlIngestPolicy || null;
233
+ // 原件留存策略覆盖(仅测试注入;缺省 null 时读取 config.ragOriginals)
234
+ this._originalsPolicyOverride = options.originalsPolicy || null;
184
235
  }
185
236
 
186
237
  // ==================== 注册表 ====================
@@ -308,6 +359,8 @@ export class RagManager {
308
359
  this._assertIdle(collectionId); // 导入/重建进行中时禁止删除(防索引写坏)
309
360
  // 防路径穿越:ID 已通过正则校验,目录路径安全
310
361
  await rm(join(RAG_ROOT, collectionId), { recursive: true, force: true });
362
+ // 原件在独立目录:删库时一并清理(失败仅残留,不影响库可用性)
363
+ await rm(this._originalsDir(collectionId), { recursive: true, force: true }).catch(() => {});
311
364
  this._providers.delete(collectionId);
312
365
  await this._updateRegistry(reg => {
313
366
  reg.collections = reg.collections.filter(c => c.id !== collectionId);
@@ -679,6 +732,122 @@ export class RagManager {
679
732
  return this._providers.get(collection.id);
680
733
  }
681
734
 
735
+ // ==================== 原件留存 ====================
736
+
737
+ /**
738
+ * 原件留存策略(config.ragOriginals;字段缺失/非法时回退默认值)
739
+ */
740
+ _originalsPolicy() {
741
+ if (this._originalsPolicyOverride) return this._originalsPolicyOverride;
742
+ const cfg = loadConfig().ragOriginals || {};
743
+ const max = Number(cfg.maxBytesPerCollection);
744
+ return {
745
+ enabled: cfg.enabled !== false,
746
+ maxBytesPerCollection: Number.isFinite(max) && max > 0
747
+ ? max
748
+ : DEFAULT_ORIGINALS_CONFIG.maxBytesPerCollection,
749
+ };
750
+ }
751
+
752
+ /**
753
+ * 知识库原件目录(与索引目录分离,避免重建换入时连带替换)
754
+ */
755
+ _originalsDir(collectionId) {
756
+ return join(ORIGINALS_ROOT, collectionId);
757
+ }
758
+
759
+ /**
760
+ * 该库原件已占用字节数(配额判定用;统计失败按 0 处理,不阻断导入)
761
+ */
762
+ async _originalsUsage(collectionId) {
763
+ const dir = this._originalsDir(collectionId);
764
+ let names = [];
765
+ try {
766
+ names = await readdir(dir);
767
+ } catch {
768
+ return 0;
769
+ }
770
+ let total = 0;
771
+ for (const name of names) {
772
+ try {
773
+ total += (await stat(join(dir, name))).size;
774
+ } catch {
775
+ // 单个文件统计失败不影响配额汇总
776
+ }
777
+ }
778
+ return total;
779
+ }
780
+
781
+ /**
782
+ * 归档原件(开关关闭/空内容/超配额/写盘失败时仅跳过,绝不阻断导入)
783
+ * @param {string} collectionId
784
+ * @param {string} documentId
785
+ * @param {Buffer} bytes - 原始字节(与交给解析器的字节同一份)
786
+ * @param {{name?: string, ext?: string, mime?: string}} meta
787
+ * @returns {Promise<{original?: object, skipped?: string}>}
788
+ */
789
+ async _persistOriginal(collectionId, documentId, bytes, meta = {}) {
790
+ const policy = this._originalsPolicy();
791
+ if (!policy.enabled) return { skipped: 'disabled' };
792
+ if (!bytes || !bytes.length) return { skipped: 'empty' };
793
+
794
+ const ext = safeOriginalExt(meta.ext);
795
+ const usage = await this._originalsUsage(collectionId);
796
+ if (usage + bytes.length > policy.maxBytesPerCollection) {
797
+ console.warn(`[RAG] original skipped (quota): ${collectionId}/${documentId} ${bytes.length}B (used ${usage}B)`);
798
+ return { skipped: 'quotaExceeded' };
799
+ }
800
+
801
+ try {
802
+ const dir = this._originalsDir(collectionId);
803
+ await mkdir(dir, { recursive: true });
804
+ await writeFile(join(dir, `${documentId}${ext}`), bytes);
805
+ return {
806
+ original: {
807
+ name: meta.name || `${documentId}${ext}`,
808
+ ext,
809
+ size: bytes.length,
810
+ mime: meta.mime || guessMime(ext),
811
+ sha256: createHash('sha256').update(bytes).digest('hex'),
812
+ storedAt: new Date().toISOString(),
813
+ },
814
+ };
815
+ } catch (err) {
816
+ // 归档失败不影响知识库可用性(文本与向量仍会写入)
817
+ console.warn(`[RAG] original write failed: ${collectionId}/${documentId}: ${err.message}`);
818
+ return { skipped: 'writeFailed' };
819
+ }
820
+ }
821
+
822
+ /**
823
+ * 删除文档对应的原件(不存在时静默)
824
+ */
825
+ async _removeOriginal(collectionId, documentId, ext) {
826
+ const safeExt = safeOriginalExt(ext);
827
+ await unlink(join(this._originalsDir(collectionId), `${documentId}${safeExt}`)).catch(() => {});
828
+ }
829
+
830
+ /**
831
+ * 解析内存字节:解析器按扩展名路由、需要真实文件 → 落临时文件解析后立即删除
832
+ * (归档与原解析共用同一份内存字节,因此「归档字节 == 被索引字节」)
833
+ * @param {Buffer} bytes
834
+ * @param {string} fileName - 决定解析器路由与错误文本的原始文件名
835
+ * @returns {Promise<string>} 抽取出的纯文本
836
+ */
837
+ async _parseBytes(bytes, fileName) {
838
+ const ext = extname(String(fileName || '')).toLowerCase();
839
+ if (!PARSER_ROUTES[ext]) throw new RagError('unsupportedFormat', { ext: ext || String(fileName || '') });
840
+ const tmpFile = join(tmpdir(), `rag-parse-${randomBytes(6).toString('hex')}${ext}`);
841
+ try {
842
+ await writeFile(tmpFile, bytes);
843
+ const { text } = await loadDocument(tmpFile);
844
+ return text;
845
+ } finally {
846
+ // 临时文件清理(Windows 上文件句柄未释放时忽略错误)
847
+ await unlink(tmpFile).catch(() => {});
848
+ }
849
+ }
850
+
682
851
  // ==================== 文档导入 ====================
683
852
 
684
853
  /**
@@ -741,16 +910,20 @@ export class RagManager {
741
910
  /**
742
911
  * 导入文件
743
912
  * 支持两种来源:
744
- * - path:agent 本地文件路径(沙箱校验后解析,受 allowedPaths 白名单与硬阻止清单约束)
745
- * - contentBase64 + fileName:前端上传内容(落临时文件解析后清理)
913
+ * - path:agent 本地文件路径(沙箱校验后归档并解析,受 allowedPaths 白名单与硬阻止清单约束)
914
+ * - contentBase64 + fileName:前端上传内容(直接落原件目录并解析,不经中转临时文件)
915
+ * 原始字节归档到 originals/<collectionId>/<documentId>.<ext>(超配额只跳过原件)
746
916
  * @param {string} collectionId
747
917
  * @param {{path?: string, fileName?: string, contentBase64?: string, metadata?: object, chunkConfig?: object}} input
748
918
  * @param {{ sessionId?: string, workdir?: string }} [ctx] - 请求级会话上下文(会话级工作目录)
749
919
  */
750
920
  async ingestFile(collectionId, input = {}, ctx = {}) {
751
921
  return this._runIngest(collectionId, async () => {
752
- // 来源 1:agent 本地文件
922
+ let bytes;
923
+ let fileName;
924
+
753
925
  if (input.path) {
926
+ // 来源 1:agent 本地文件
754
927
  // 文件沙箱:与 /api/fs/read 同一套规则(allowedPaths 白名单 + 硬阻止清单),
755
928
  // 防止经 RAG 导入绕过沙箱读取宿主任意文件(如代理自身敏感文件)
756
929
  // ctx = 请求级会话上下文:会话绑定不写 allowedPaths,
@@ -759,36 +932,41 @@ export class RagManager {
759
932
  if (!check.allowed) {
760
933
  throw new RagError('pathNotAllowed', { reason: check.reason });
761
934
  }
762
- this._reportProgress(collectionId, { phase: 'parsing', current: 0, total: 0, done: false, error: null });
763
- const { text, fileName } = await loadDocument(check.resolved || input.path);
764
- return this._ingestText(collectionId, {
765
- text, name: fileName, source: 'file', metadata: input.metadata, chunkConfig: input.chunkConfig,
766
- });
767
- }
768
-
769
- // 来源 2:上传内容(base64)
770
- if (input.contentBase64) {
935
+ const resolved = check.resolved || input.path;
936
+ // 体积校验:path 分支此前缺这道关,超大文件会整块读入内存
937
+ const info = await stat(resolved).catch(() => null);
938
+ if (!info || !info.isFile()) throw new RagError('pathNotAllowed', { reason: 'notFile' });
939
+ if (info.size > INGEST_MAX_FILE_BYTES) {
940
+ throw new RagError('fileTooLarge', { limit: formatBytes(INGEST_MAX_FILE_BYTES) });
941
+ }
942
+ bytes = await readFile(resolved);
943
+ fileName = basename(input.path);
944
+ } else if (input.contentBase64) {
945
+ // 来源 2:上传内容(base64)
771
946
  if (!input.fileName) throw new RagError('missingFileName');
772
947
  // 体积预检(P3):按 base64 长度换算近似解码尺寸,避免先分配超大 Buffer 再拒绝
773
948
  if (Math.floor(input.contentBase64.length * 3 / 4) > INGEST_MAX_FILE_BYTES) {
774
949
  throw new RagError('fileTooLarge', { limit: formatBytes(INGEST_MAX_FILE_BYTES) });
775
950
  }
776
- const ext = extname(input.fileName).toLowerCase();
777
- const tmpFile = join(tmpdir(), `rag-upload-${randomBytes(6).toString('hex')}${ext}`);
778
- this._reportProgress(collectionId, { phase: 'parsing', current: 0, total: 0, done: false, error: null });
779
- try {
780
- await writeFile(tmpFile, Buffer.from(input.contentBase64, 'base64'));
781
- const { text, fileName } = await loadDocument(tmpFile);
782
- return await this._ingestText(collectionId, {
783
- text, name: input.fileName || fileName, source: 'file', metadata: input.metadata, chunkConfig: input.chunkConfig,
784
- });
785
- } finally {
786
- // 临时文件清理(Windows 上文件句柄未释放时忽略错误)
787
- await unlink(tmpFile).catch(() => {});
788
- }
951
+ bytes = Buffer.from(input.contentBase64, 'base64');
952
+ fileName = basename(input.fileName);
953
+ } else {
954
+ throw new RagError('missingFileSource');
789
955
  }
790
956
 
791
- throw new RagError('missingFileSource');
957
+ this._reportProgress(collectionId, { phase: 'parsing', current: 0, total: 0, done: false, error: null });
958
+ // 先解析(不支持的格式在这里快速失败,不会留下孤儿原件),再归档
959
+ const text = await this._parseBytes(bytes, fileName);
960
+ const documentId = newDocumentId();
961
+ const ext = extname(fileName).toLowerCase();
962
+ const persisted = await this._persistOriginal(collectionId, documentId, bytes, {
963
+ name: fileName, ext, mime: guessMime(ext),
964
+ });
965
+
966
+ return this._ingestText(collectionId, {
967
+ text, name: fileName, source: 'file', metadata: input.metadata, chunkConfig: input.chunkConfig,
968
+ documentId, original: persisted.original, originalSkipped: persisted.skipped,
969
+ });
792
970
  });
793
971
  }
794
972
 
@@ -814,17 +992,12 @@ export class RagManager {
814
992
  this._reportProgress(collectionId, { phase: 'parsing', current: 0, total: 0, done: false, error: null });
815
993
  const { bytes, contentType } = await fetchUrlGuarded(url, this._urlIngestPolicy());
816
994
 
995
+ const isPdf = contentType.includes('application/pdf');
817
996
  let text;
818
997
  if (contentType.includes('text/html') || contentType.includes('application/xhtml')) {
819
998
  text = await htmlToText(decodeBytes(bytes, contentType));
820
- } else if (contentType.includes('application/pdf')) {
821
- const tmpFile = join(tmpdir(), `rag-url-${randomBytes(6).toString('hex')}.pdf`);
822
- try {
823
- await writeFile(tmpFile, bytes);
824
- ({ text } = await loadDocument(tmpFile));
825
- } finally {
826
- await unlink(tmpFile).catch(() => {});
827
- }
999
+ } else if (isPdf) {
1000
+ text = await this._parseBytes(bytes, 'page.pdf');
828
1001
  } else {
829
1002
  // text/*、application/json 等按文本处理(按 charset 解码,兼容 GBK 站点)
830
1003
  text = decodeBytes(bytes, contentType);
@@ -839,8 +1012,19 @@ export class RagManager {
839
1012
  const tail = u.pathname.split('/').filter(Boolean).pop() || '';
840
1013
  const name = `${u.hostname}${tail ? '/' + tail : ''}`.slice(0, 100);
841
1014
 
1015
+ // 原件:把抓到的响应体原样归档(HTML 快照 / PDF 原文件),mime 保留远端 Content-Type
1016
+ const ext = isPdf ? '.pdf' : '.html';
1017
+ const documentId = newDocumentId();
1018
+ const originalName = `${u.hostname}${tail ? '-' + tail : ''}${ext}`
1019
+ .replace(/[/\\:*?"<>|]/g, '_')
1020
+ .slice(-120);
1021
+ const persisted = await this._persistOriginal(collectionId, documentId, bytes, {
1022
+ name: originalName, ext, mime: contentType,
1023
+ });
1024
+
842
1025
  return this._ingestText(collectionId, {
843
1026
  text, name, source: 'url', metadata: { ...(input.metadata || {}), url }, chunkConfig: input.chunkConfig,
1027
+ documentId, original: persisted.original, originalSkipped: persisted.skipped, originUrl: url,
844
1028
  });
845
1029
  });
846
1030
  }
@@ -848,8 +1032,14 @@ export class RagManager {
848
1032
  /**
849
1033
  * 内部统一导入流程:分块 → 批量向量化 → 事务写入 → 原文备份 → 更新计数
850
1034
  * 全程上报进度快照(parsing/chunking/embedding/storing/done/error),供前端轮询展示
1035
+ * @param {object} params
1036
+ * @param {string} [params.documentId] - 调用方已归档原件时会预先分配(保证原件与文档同名)
1037
+ * @param {object} [params.original] - 已归档原件的元数据(name/ext/size/mime/sha256/storedAt)
1038
+ * @param {string} [params.originalSkipped] - 原件未留存原因(quotaExceeded/disabled/empty/writeFailed)
1039
+ * @param {string} [params.originUrl] - URL 导入的来源地址
851
1040
  */
852
- async _ingestText(collectionId, { text, name, source, metadata, chunkConfig }) {
1041
+ async _ingestText(collectionId, { text, name, source, metadata, chunkConfig, documentId, original, originalSkipped, originUrl }) {
1042
+ const docId = documentId || newDocumentId();
853
1043
  try {
854
1044
  const collection = await this.getCollection(collectionId);
855
1045
  this._reportProgress(collectionId, { phase: 'chunking', current: 0, total: 0, done: false, error: null });
@@ -863,13 +1053,12 @@ export class RagManager {
863
1053
  console.log(`[RAG] embed ${name}: ${embedded}/${chunks.length}`);
864
1054
  });
865
1055
 
866
- const documentId = `doc_${Date.now().toString(36)}${randomBytes(4).toString('hex')}`;
867
1056
  const createdAt = new Date().toISOString();
868
1057
 
869
1058
  this._reportProgress(collectionId, { phase: 'storing', current: chunks.length, total: chunks.length });
870
1059
  const store = new VectraStore(collectionId);
871
1060
  // 用户 metadata 先展开、系统业务键最后(S4b):documentName/source/createdAt 不可被覆盖
872
- await store.upsertChunks(documentId, chunks, embeddings, {
1061
+ await store.upsertChunks(docId, chunks, embeddings, {
873
1062
  ...(metadata || {}),
874
1063
  documentName: name,
875
1064
  source,
@@ -878,7 +1067,10 @@ export class RagManager {
878
1067
 
879
1068
  // 原文备份(BM25 docReader 依赖,见设计文档 5.8)
880
1069
  await this._saveDocumentBackup(collectionId, {
881
- id: documentId, name, text, source, metadata: metadata || {}, chunkCount: chunks.length, createdAt,
1070
+ id: docId, name, text, source, metadata: metadata || {}, chunkCount: chunks.length, createdAt,
1071
+ ...(original ? { original } : {}),
1072
+ ...(originalSkipped ? { originalSkipped } : {}),
1073
+ ...(originUrl ? { originUrl } : {}),
882
1074
  });
883
1075
 
884
1076
  // 更新注册表计数
@@ -892,8 +1084,14 @@ export class RagManager {
892
1084
  });
893
1085
 
894
1086
  this._reportProgress(collectionId, { phase: 'done', current: chunks.length, total: chunks.length, done: true });
895
- return { documentId, name, chunkCount: chunks.length };
1087
+ return {
1088
+ documentId: docId, name, chunkCount: chunks.length,
1089
+ ...(original ? { original } : {}),
1090
+ ...(originalSkipped ? { originalSkipped } : {}),
1091
+ };
896
1092
  } catch (err) {
1093
+ // 原件在解析之后、备份之前归档:失败时备份未写入,只需回滚原件,避免孤儿文件
1094
+ if (original) await this._removeOriginal(collectionId, docId, original.ext);
897
1095
  this._reportProgress(collectionId, { phase: 'error', done: true, error: err.message });
898
1096
  throw err;
899
1097
  }
@@ -937,10 +1135,43 @@ export class RagManager {
937
1135
  // ==================== 文档管理 ====================
938
1136
 
939
1137
  /**
940
- * 列出知识库中的所有文档(从分块元数据聚合)
1138
+ * 列出知识库中的所有文档(以 documents/*.json 备份为准:带来原件信息,且不必扫全量分块)
1139
+ * 备份目录缺失/为空时回退到分块元数据聚合(兼容无备份的老数据)
941
1140
  */
942
1141
  async listDocuments(collectionId) {
943
1142
  await this.getCollection(collectionId); // 校验存在性
1143
+
1144
+ const docsDir = join(RAG_ROOT, collectionId, 'documents');
1145
+ let backups = [];
1146
+ try {
1147
+ const files = await readdir(docsDir);
1148
+ for (const file of files) {
1149
+ if (!file.endsWith('.json')) continue;
1150
+ try {
1151
+ backups.push(JSON.parse(await readFile(join(docsDir, file), 'utf-8')));
1152
+ } catch {
1153
+ console.warn(`[RAG] listDocuments: skip corrupted backup ${file}`);
1154
+ }
1155
+ }
1156
+ } catch {
1157
+ backups = [];
1158
+ }
1159
+
1160
+ if (backups.length > 0) {
1161
+ return backups
1162
+ .map((b) => ({
1163
+ id: b.id,
1164
+ name: b.name || b.id,
1165
+ source: b.source || 'unknown',
1166
+ createdAt: b.createdAt || null,
1167
+ chunkCount: b.chunkCount || 0,
1168
+ original: b.original || null,
1169
+ originalSkipped: b.originalSkipped || null,
1170
+ originUrl: b.originUrl || b.metadata?.url || null,
1171
+ }))
1172
+ .sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
1173
+ }
1174
+
944
1175
  const store = new VectraStore(collectionId);
945
1176
  const items = await store.listAllItems();
946
1177
 
@@ -956,12 +1187,86 @@ export class RagManager {
956
1187
  source: m.source || 'unknown',
957
1188
  createdAt: m.createdAt || null,
958
1189
  chunkCount: m.totalChunks || 0,
1190
+ original: null,
1191
+ originalSkipped: null,
1192
+ originUrl: null,
959
1193
  });
960
1194
  }
961
1195
  }
962
1196
  return [...docs.values()].sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
963
1197
  }
964
1198
 
1199
+ /**
1200
+ * 读取文档备份(文本真源)
1201
+ * @returns {Promise<object>}
1202
+ */
1203
+ async _readBackup(collectionId, documentId) {
1204
+ if (!DOCUMENT_ID_RE.test(documentId)) throw new RagError('invalidDocumentId', { id: documentId });
1205
+ try {
1206
+ return JSON.parse(await readFile(join(RAG_ROOT, collectionId, 'documents', `${documentId}.json`), 'utf-8'));
1207
+ } catch {
1208
+ throw new RagError('documentNotFound', { id: documentId });
1209
+ }
1210
+ }
1211
+
1212
+ /**
1213
+ * 文档详情(供设置页查看原文):超长文本截断,避免数 MB JSON 卡住弹窗
1214
+ */
1215
+ async getDocument(collectionId, documentId) {
1216
+ await this.getCollection(collectionId);
1217
+ const backup = await this._readBackup(collectionId, documentId);
1218
+ const full = String(backup.text || '');
1219
+ const truncated = full.length > DOC_TEXT_VIEW_MAX_CHARS;
1220
+ return {
1221
+ id: backup.id || documentId,
1222
+ name: backup.name || documentId,
1223
+ source: backup.source || 'unknown',
1224
+ createdAt: backup.createdAt || null,
1225
+ chunkCount: backup.chunkCount || 0,
1226
+ original: backup.original || null,
1227
+ originalSkipped: backup.originalSkipped || null,
1228
+ originUrl: backup.originUrl || backup.metadata?.url || null,
1229
+ text: truncated ? full.slice(0, DOC_TEXT_VIEW_MAX_CHARS) : full,
1230
+ totalChars: full.length,
1231
+ viewLimit: DOC_TEXT_VIEW_MAX_CHARS,
1232
+ truncated,
1233
+ };
1234
+ }
1235
+
1236
+ /**
1237
+ * 解析下载目标
1238
+ * - kind=original:原件存档必须实际存在,否则 originalMissing
1239
+ * - kind=text:现场从备份生成纯文本(不落盘,避免第二份文本)
1240
+ * @param {string} collectionId
1241
+ * @param {string} documentId
1242
+ * @param {string} kind - 'original' | 'text'
1243
+ * @returns {Promise<{kind: string, fileName: string, mime: string, path?: string, text?: string}>}
1244
+ */
1245
+ async resolveDocumentDownload(collectionId, documentId, kind) {
1246
+ await this.getCollection(collectionId);
1247
+ const backup = await this._readBackup(collectionId, documentId);
1248
+ const name = backup.name || documentId;
1249
+
1250
+ if (kind === 'text') {
1251
+ return { kind, fileName: `${name}.txt`, mime: 'text/plain; charset=utf-8', text: String(backup.text || '') };
1252
+ }
1253
+ if (kind !== 'original') throw new RagError('unsupportedDownloadKind', { kind: String(kind) });
1254
+ if (!backup.original) throw new RagError('originalMissing', { name });
1255
+
1256
+ // 扩展名只取存量记录(不信客户端参数),拼路径前再收一道白名单
1257
+ const ext = safeOriginalExt(backup.original.ext);
1258
+ const path = join(this._originalsDir(collectionId), `${documentId}${ext}`);
1259
+ const info = await stat(path).catch(() => null);
1260
+ if (!info || !info.isFile()) throw new RagError('originalMissing', { name });
1261
+ return {
1262
+ kind,
1263
+ fileName: backup.original.name || `${name}${ext}`,
1264
+ mime: backup.original.mime || guessMime(ext),
1265
+ size: info.size,
1266
+ path,
1267
+ };
1268
+ }
1269
+
965
1270
  /**
966
1271
  * 删除文档(分块 + 原文备份)
967
1272
  */
@@ -972,9 +1277,12 @@ export class RagManager {
972
1277
  // 删除同样是索引写操作:占位防与导入/重建并发交错写坏索引
973
1278
  this._activeOps.add(collectionId);
974
1279
  try {
1280
+ // 先读备份拿到原件扩展名(备份缺失时按无原件处理,不阻断删除)
1281
+ const backup = await this._readBackup(collectionId, documentId).catch(() => null);
975
1282
  const store = new VectraStore(collectionId);
976
1283
  const removed = await store.removeDocument(documentId);
977
1284
 
1285
+ if (backup?.original) await this._removeOriginal(collectionId, documentId, backup.original.ext);
978
1286
  await unlink(join(RAG_ROOT, collectionId, 'documents', `${documentId}.json`)).catch(() => {});
979
1287
 
980
1288
  await this._updateRegistry(reg => {
package/src/rag/routes.js CHANGED
@@ -15,10 +15,13 @@
15
15
  // POST /api/rag/collections/{id}/ingest 导入文档(text/file/url;同步执行)
16
16
  // GET /api/rag/collections/{id}/ingest/status 导入进度快照(供导入弹窗轮询)
17
17
  // GET /api/rag/collections/{id}/documents 文档列表
18
+ // GET /api/rag/collections/{id}/documents/{docId} 文档详情(查看原文,超长截断)
19
+ // GET /api/rag/collections/{id}/documents/{docId}/download?kind=original|text 下载原件/文本
18
20
  // DELETE /api/rag/collections/{id}/documents/{docId} 删除文档
19
21
  // POST /api/rag/collections/{id}/search 检索
20
22
  // POST /api/rag/search 跨知识库检索
21
23
 
24
+ import { createReadStream } from 'fs';
22
25
  import { isRagAvailable } from './detect.js';
23
26
  import { getRagInstallStatus } from './install.js';
24
27
  import { RagManager, resolveEmbeddingConfig, validateEmbeddingConfig } from './manager.js';
@@ -62,6 +65,63 @@ function jsonResponse(res, status, data) {
62
65
  res.end(JSON.stringify(data));
63
66
  }
64
67
 
68
+ /**
69
+ * 跨域响应头(与 jsonResponse 同源):仅放行扩展页面来源
70
+ */
71
+ function corsHeaders(res) {
72
+ const headers = {
73
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
74
+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
75
+ };
76
+ const allowedOrigin = getAllowedOrigin(res.req);
77
+ if (allowedOrigin) {
78
+ headers['Access-Control-Allow-Origin'] = allowedOrigin;
79
+ headers['Vary'] = 'Origin';
80
+ }
81
+ return headers;
82
+ }
83
+
84
+ /**
85
+ * RFC 5987 编码(中文文件名在 Content-Disposition 中不乱码;encodeURIComponent 不转义 '()*)
86
+ */
87
+ function encodeRFC5987(value) {
88
+ return encodeURIComponent(value).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
89
+ }
90
+
91
+ /**
92
+ * 下载响应:同时给 ASCII 回退名与 UTF-8 编码名,保留原文件名
93
+ */
94
+ function attachmentHeaders(mime, fileName, size) {
95
+ const ascii = String(fileName || 'download')
96
+ .replace(/[^\x20-\x7e]/g, '_')
97
+ .replace(/["\\]/g, '_');
98
+ const headers = {
99
+ 'Content-Type': mime || 'application/octet-stream',
100
+ 'Content-Disposition': `attachment; filename="${ascii}"; filename*=UTF-8''${encodeRFC5987(String(fileName || 'download'))}`,
101
+ };
102
+ if (typeof size === 'number' && size >= 0) headers['Content-Length'] = String(size);
103
+ return headers;
104
+ }
105
+
106
+ /**
107
+ * 输出下载体:文本直接写缓冲,原件走流(大文件不整块进内存)
108
+ */
109
+ function sendDownload(res, target) {
110
+ if (target.kind === 'text') {
111
+ const body = Buffer.from(String(target.text || ''), 'utf-8');
112
+ res.writeHead(200, { ...corsHeaders(res), ...attachmentHeaders(target.mime, target.fileName, body.length) });
113
+ res.end(body);
114
+ return;
115
+ }
116
+ res.writeHead(200, { ...corsHeaders(res), ...attachmentHeaders(target.mime, target.fileName, target.size) });
117
+ const stream = createReadStream(target.path);
118
+ stream.on('error', (err) => {
119
+ console.error('[RAG] original stream failed:', err);
120
+ res.destroy(); // 头部已发出,无法改状态码
121
+ });
122
+ stream.pipe(res);
123
+ }
124
+
65
125
  /**
66
126
  * 业务处理包装:统一错误响应(RagError 按当前请求语言翻译,其余 400 原样返回)
67
127
  */
@@ -186,9 +246,9 @@ export async function ragRouter(req, res, pathname, url, t, body = {}, ctx = {})
186
246
  });
187
247
  }
188
248
 
189
- // /api/rag/collections/{id}[/{sub}[/{docId}]]
249
+ // /api/rag/collections/{id}[/{sub}[/{docId}[/download]]]
190
250
  const collectionMatch = pathname.match(
191
- /^\/api\/rag\/collections\/([^/]+)(?:\/(stats|ingest|documents|search|toggle)(?:\/([^/]+))?)?$/
251
+ /^\/api\/rag\/collections\/([^/]+)(?:\/(stats|ingest|documents|search|toggle)(?:\/([^/]+)(?:\/(download))?)?)?$/
192
252
  );
193
253
 
194
254
  if (collectionMatch) {
@@ -202,6 +262,7 @@ export async function ragRouter(req, res, pathname, url, t, body = {}, ctx = {})
202
262
  }
203
263
  const sub = collectionMatch[2];
204
264
  const docId = collectionMatch[3] ? safeDecodePathSegment(collectionMatch[3]) : undefined;
265
+ const action = collectionMatch[4];
205
266
  if (docId === null) {
206
267
  return jsonResponse(res, 400, {
207
268
  success: false,
@@ -265,6 +326,26 @@ export async function ragRouter(req, res, pathname, url, t, body = {}, ctx = {})
265
326
  return handle(res, async () => ({ documents: await manager.listDocuments(collectionId) }));
266
327
  }
267
328
 
329
+ // GET /api/rag/collections/{id}/documents/{docId} - 文档详情(查看原文;超长截断)
330
+ if (method === 'GET' && sub === 'documents' && docId && !action) {
331
+ return handle(res, async () => ({ document: await manager.getDocument(collectionId, docId) }));
332
+ }
333
+
334
+ // GET /api/rag/collections/{id}/documents/{docId}/download?kind=original|text
335
+ // 下载失败仍返回 JSON 错误体(便于前端 toast),成功才发附件头
336
+ if (method === 'GET' && sub === 'documents' && docId && action === 'download') {
337
+ const kind = String(url.searchParams.get('kind') || 'text');
338
+ let target;
339
+ try {
340
+ target = await manager.resolveDocumentDownload(collectionId, docId, kind);
341
+ } catch (err) {
342
+ if (!(err instanceof RagError)) console.error('[RAG] download error:', err);
343
+ const { error, code } = translateRagError(err, t);
344
+ return jsonResponse(res, 400, { success: false, error, code });
345
+ }
346
+ return sendDownload(res, target);
347
+ }
348
+
268
349
  // DELETE /api/rag/collections/{id}/documents/{docId} - 删除文档
269
350
  if (method === 'DELETE' && sub === 'documents' && docId) {
270
351
  return handle(res, async () => manager.deleteDocument(collectionId, docId));