ai-helper-agent 2.8.2 → 2.8.4
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.
- package/dist/assets/{agent-store-CDvWEPZE.js → agent-store-CvwCM_vy.js} +1 -1
- package/dist/assets/background.js +27 -22
- package/dist/assets/{chat-export-Dk9SHnz5.js → chat-export-DJw6x2Sw.js} +1 -1
- package/dist/assets/content.js +18 -18
- package/dist/assets/{i18n-XJTStlKO.js → i18n-B1Q34rTV.js} +6 -6
- package/dist/assets/{markdown-render-AIT2waF5.js → markdown-render-C-euDKUV.js} +9 -9
- package/dist/assets/{model-profiles-B-8HB7uC.js → model-profiles-CxoB9idD.js} +1 -1
- package/dist/assets/options-DamSLmKe.css +1 -0
- package/dist/assets/options.js +72 -57
- package/dist/assets/{page-snapshot-renderer-BF9z-5DA.js → page-snapshot-renderer-I5Z-2PsZ.js} +1 -1
- package/dist/assets/{session-store-vZsITypR.js → session-store-BP9eCHvz.js} +4 -4
- package/dist/assets/side_panel.js +317 -317
- package/dist/assets/{utils-UyExxTOM.js → utils-B3cdluuq.js} +2 -2
- package/dist/assets/{version-CN20Ise-.js → version-BwkwMVG0.js} +1 -1
- package/dist/assets/{workspace-manager-BqgbuzqN.js → workspace-manager-C9F8S32K.js} +1 -1
- package/dist/manifest.json +1 -1
- package/dist/offscreen/offscreen.js +6 -6
- package/dist/options.html +9 -5
- package/dist/side_panel.html +8 -8
- package/package.json +1 -1
- package/src/locales/en.json +2 -1
- package/src/locales/zh.json +2 -1
- package/src/memory/archive.js +169 -0
- package/src/memory/service.js +46 -18
- package/src/rag/export.js +202 -0
- package/src/rag/manager.js +63 -0
- package/src/rag/routes.js +44 -1
- package/src/search.js +134 -50
- package/src/server.js +60 -6
- package/src/skill/markdown-loader.js +20 -0
- package/dist/assets/options-CM9dPi9P.css +0 -1
package/dist/options.html
CHANGED
|
@@ -5,14 +5,14 @@
|
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
6
6
|
<title data-i18n="settings.docTitle">AI Helper - 配置</title>
|
|
7
7
|
<script type="module" crossorigin src="/assets/theme-Cp7RrL45.js"></script>
|
|
8
|
-
<script type="module" crossorigin src="/assets/version-
|
|
9
|
-
<script type="module" crossorigin src="/assets/i18n-
|
|
10
|
-
<script type="module" crossorigin src="/assets/model-profiles-
|
|
8
|
+
<script type="module" crossorigin src="/assets/version-BwkwMVG0.js"></script>
|
|
9
|
+
<script type="module" crossorigin src="/assets/i18n-B1Q34rTV.js"></script>
|
|
10
|
+
<script type="module" crossorigin src="/assets/model-profiles-CxoB9idD.js"></script>
|
|
11
11
|
<script type="module" crossorigin src="/assets/network-scope-0d6MoKgI.js"></script>
|
|
12
12
|
<script type="module" crossorigin src="/assets/voice-shortcut-Dtt3nhkz.js"></script>
|
|
13
13
|
<script type="module" crossorigin src="/assets/options.js"></script>
|
|
14
14
|
<link rel="stylesheet" crossorigin href="/assets/theme-ChzggwXz.css">
|
|
15
|
-
<link rel="stylesheet" crossorigin href="/assets/options-
|
|
15
|
+
<link rel="stylesheet" crossorigin href="/assets/options-DamSLmKe.css">
|
|
16
16
|
</head>
|
|
17
17
|
<body>
|
|
18
18
|
<div class="container">
|
|
@@ -1050,7 +1050,11 @@
|
|
|
1050
1050
|
<div class="memory-entries-head">
|
|
1051
1051
|
<label data-i18n="memoryEntries.title">记忆条目</label>
|
|
1052
1052
|
<span id="memoryEntriesCount" class="memory-entries-count"></span>
|
|
1053
|
-
<
|
|
1053
|
+
<div class="memory-entries-actions">
|
|
1054
|
+
<button class="toolbox-add-btn" type="button" id="memoryEntriesRefreshBtn" style="width:auto; margin:0; padding:6px 14px; border-style:solid;" data-i18n="memoryEntries.refreshBtn">刷新</button>
|
|
1055
|
+
<button class="toolbox-add-btn" type="button" id="memoryEntriesExportBtn" style="width:auto; margin:0; padding:6px 14px; border-style:solid;" data-i18n="memoryEntries.exportBtn">导出</button>
|
|
1056
|
+
<button class="toolbox-add-btn" type="button" id="memoryEntriesImportBtn" style="width:auto; margin:0; padding:6px 14px; border-style:solid;" data-i18n="memoryEntries.importBtn">导入</button>
|
|
1057
|
+
</div>
|
|
1054
1058
|
</div>
|
|
1055
1059
|
<div class="memory-entries-filter">
|
|
1056
1060
|
<input type="text" id="memoryEntriesSearch" data-i18n-placeholder="memoryEntries.searchPlaceholder" placeholder="">
|
package/dist/side_panel.html
CHANGED
|
@@ -6,15 +6,15 @@
|
|
|
6
6
|
<title data-i18n="header.docTitle">AI Helper - 模型问答</title>
|
|
7
7
|
<script type="module" crossorigin src="/assets/theme-Cp7RrL45.js"></script>
|
|
8
8
|
<script type="module" crossorigin src="/assets/chunk-CMxvf4Kt.js"></script>
|
|
9
|
-
<script type="module" crossorigin src="/assets/i18n-
|
|
10
|
-
<script type="module" crossorigin src="/assets/model-profiles-
|
|
11
|
-
<script type="module" crossorigin src="/assets/session-store-
|
|
12
|
-
<script type="module" crossorigin src="/assets/version-
|
|
9
|
+
<script type="module" crossorigin src="/assets/i18n-B1Q34rTV.js"></script>
|
|
10
|
+
<script type="module" crossorigin src="/assets/model-profiles-CxoB9idD.js"></script>
|
|
11
|
+
<script type="module" crossorigin src="/assets/session-store-BP9eCHvz.js"></script>
|
|
12
|
+
<script type="module" crossorigin src="/assets/version-BwkwMVG0.js"></script>
|
|
13
13
|
<script type="module" crossorigin src="/assets/voice-shortcut-Dtt3nhkz.js"></script>
|
|
14
|
-
<script type="module" crossorigin src="/assets/agent-store-
|
|
15
|
-
<script type="module" crossorigin src="/assets/utils-
|
|
16
|
-
<script type="module" crossorigin src="/assets/markdown-render-
|
|
17
|
-
<script type="module" crossorigin src="/assets/workspace-manager-
|
|
14
|
+
<script type="module" crossorigin src="/assets/agent-store-CvwCM_vy.js"></script>
|
|
15
|
+
<script type="module" crossorigin src="/assets/utils-B3cdluuq.js"></script>
|
|
16
|
+
<script type="module" crossorigin src="/assets/markdown-render-C-euDKUV.js"></script>
|
|
17
|
+
<script type="module" crossorigin src="/assets/workspace-manager-C9F8S32K.js"></script>
|
|
18
18
|
<script type="module" crossorigin src="/assets/side_panel.js"></script>
|
|
19
19
|
<link rel="stylesheet" crossorigin href="/assets/theme-ChzggwXz.css">
|
|
20
20
|
<link rel="stylesheet" crossorigin href="/assets/side_panel.css">
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ai-helper-agent",
|
|
3
|
-
"version": "2.8.
|
|
3
|
+
"version": "2.8.4",
|
|
4
4
|
"description": "AI Helper Agent - Local file access and system command execution proxy for Chrome extension / AI Helper 代理服务,为 Chrome 扩展提供本地文件读写和系统命令执行",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/server.js",
|
package/src/locales/en.json
CHANGED
|
@@ -376,7 +376,8 @@
|
|
|
376
376
|
"foundResults": "Found {count} relevant memories:{note}",
|
|
377
377
|
"recallNoteAllOld": "(Note: The above memories have already been retrieved in this conversation, returned again)",
|
|
378
378
|
"recallNoteMixed": "(Note: {oldCount} memories already retrieved in this conversation, only returning {newCount} new ones)",
|
|
379
|
-
"compactDone": "Memory compaction complete.
|
|
379
|
+
"compactDone": "Memory compaction complete. Archived {facts} fact memories and {summaries} summary memories to {archiveDir} (value below {threshold}); you can restore them from the archive files there. Current: facts {totalFacts}, summaries {totalSummaries}",
|
|
380
|
+
"archiveFailed": "Memory archiving failed, compaction aborted (no memories were removed): {error}",
|
|
380
381
|
"reviewTitle": "## Memory Review Report",
|
|
381
382
|
"reviewOverview": "**Overview**: Facts {facts}/{maxFacts}, Summaries {summaries}/{maxSummaries}",
|
|
382
383
|
"reviewLastReview": "**Last review**: {date}",
|
package/src/locales/zh.json
CHANGED
|
@@ -376,7 +376,8 @@
|
|
|
376
376
|
"foundResults": "找到 {count} 条相关记忆:{note}",
|
|
377
377
|
"recallNoteAllOld": "(注:以上记忆在本对话中已检索过,此处为重复返回)",
|
|
378
378
|
"recallNoteMixed": "(注:{oldCount} 条记忆在本对话中已检索过,仅返回新的 {newCount} 条)",
|
|
379
|
-
"compactDone": "
|
|
379
|
+
"compactDone": "记忆压缩完成。已归档 {facts} 条事实记忆和 {summaries} 条摘要记忆到 {archiveDir}(价值低于 {threshold}),需要时可按该目录下的归档文件找回。当前: 事实 {totalFacts}, 摘要 {totalSummaries}",
|
|
380
|
+
"archiveFailed": "记忆归档失败,本轮压缩已中止(未删除任何记忆): {error}",
|
|
380
381
|
"reviewTitle": "## 记忆审查报告",
|
|
381
382
|
"reviewOverview": "**概况**: 事实 {facts}/{maxFacts}, 摘要 {summaries}/{maxSummaries}",
|
|
382
383
|
"reviewLastReview": "**上次审查**: {date}",
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// agent/src/memory/archive.js - 淘汰记忆归档(append-only JSONL)
|
|
2
|
+
//
|
|
3
|
+
// 为什么不用「一个 backup 文件」:淘汰是长期行为,单文件会无限增长,越到后面越难打开、
|
|
4
|
+
// 越难备份,一次写坏就是全量丢失。这里按月切片:memory-archive-YYYY-MM.jsonl。
|
|
5
|
+
//
|
|
6
|
+
// 为什么用 JSONL 而不是 JSON 数组:
|
|
7
|
+
// 1. 追加只改文件尾部,不需要「读全量-改-写回」,单次淘汰的写入量与归档总量无关;
|
|
8
|
+
// 2. 崩溃最多损坏最后一行,前面的历史记录仍然可读(导入侧按行解析、坏行跳过);
|
|
9
|
+
// 3. 一行一条记忆,用户可以直接用编辑器/文本工具查看某个月的淘汰项。
|
|
10
|
+
//
|
|
11
|
+
// 单文件上限之外还要管总量:按月切片只约束文件名,不约束单文件大小(一个月内也可能
|
|
12
|
+
// 反复淘汰)。这里再做两层限制:
|
|
13
|
+
// 1. 单文件超过 ARCHIVE_MAX_FILE_BYTES 时,月内继续切片为 memory-archive-YYYY-MM-2.jsonl;
|
|
14
|
+
// 2. 最多保留 ARCHIVE_MAX_FILES 个文件且总量不超过 ARCHIVE_MAX_BYTES,
|
|
15
|
+
// 超出后从最旧的文件开始删——归档是兜底,不是无限期冷存储。
|
|
16
|
+
//
|
|
17
|
+
// 失败语义由调用方决定:append 失败必须中止淘汰(fail-closed,宁可这轮不压缩),
|
|
18
|
+
// prune 失败只告警(数据已经归档,删不掉旧文件不影响正确性)。
|
|
19
|
+
|
|
20
|
+
import { appendFile, mkdir, open, readdir, rm, stat } from 'fs/promises';
|
|
21
|
+
import { basename, join } from 'path';
|
|
22
|
+
|
|
23
|
+
export const ARCHIVE_MAX_FILES = 12; // 最多 12 个归档文件(月份或月内分段)
|
|
24
|
+
export const ARCHIVE_MAX_BYTES = 10 * 1024 * 1024; // 总量上限 10 MB
|
|
25
|
+
export const ARCHIVE_MAX_FILE_BYTES = 2 * 1024 * 1024; // 单文件上限 2 MB,超出后月内再切片
|
|
26
|
+
export const ARCHIVE_FILE_RE = /^memory-archive-(\d{4})-(\d{2})(?:-(\d+))?\.jsonl$/;
|
|
27
|
+
|
|
28
|
+
function pad2(n) {
|
|
29
|
+
return String(n).padStart(2, '0');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 归档基础文件按月命名;月内分段为 -2、-3……,文件名本身即时间范围 */
|
|
33
|
+
export function archiveFilePath(dir, now = Date.now()) {
|
|
34
|
+
const d = new Date(now);
|
|
35
|
+
return join(dir, `memory-archive-${d.getFullYear()}-${pad2(d.getMonth() + 1)}.jsonl`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 排序键:先月份、再分段号(无后缀视为第 1 段),保证裁剪永远从最旧开始 */
|
|
39
|
+
function archiveSortKey(name) {
|
|
40
|
+
const m = ARCHIVE_FILE_RE.exec(name);
|
|
41
|
+
if (!m) return '';
|
|
42
|
+
const seg = m[3] ? Number(m[3]) : 1;
|
|
43
|
+
return `${m[1]}-${m[2]}-${String(seg).padStart(6, '0')}`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 选追加目标:优先写进当月已有分段中「再加这条不会超单文件上限」的最早一个,
|
|
48
|
+
* 都放不下就新开一个分段。这样单文件大小有硬上限,而恢复时按文件名排序仍然天然有序。
|
|
49
|
+
*/
|
|
50
|
+
async function pickArchiveTarget(dir, now, payloadBytes, maxFileBytes) {
|
|
51
|
+
const month = basename(archiveFilePath(dir, now), '.jsonl');
|
|
52
|
+
const segRe = new RegExp(`^${month}(?:-(\\d+))?\\.jsonl$`);
|
|
53
|
+
|
|
54
|
+
let names = [];
|
|
55
|
+
try {
|
|
56
|
+
names = await readdir(dir);
|
|
57
|
+
} catch (err) {
|
|
58
|
+
if (err.code !== 'ENOENT') throw err;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const segs = names
|
|
62
|
+
.map((name) => {
|
|
63
|
+
const m = segRe.exec(name);
|
|
64
|
+
return m ? { name, seg: m[1] ? Number(m[1]) : 1 } : null;
|
|
65
|
+
})
|
|
66
|
+
.filter(Boolean)
|
|
67
|
+
.sort((a, b) => a.seg - b.seg);
|
|
68
|
+
|
|
69
|
+
for (const item of segs) {
|
|
70
|
+
const path = join(dir, item.name);
|
|
71
|
+
const st = await stat(path);
|
|
72
|
+
if (st.size + payloadBytes <= maxFileBytes) return path;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const nextSeg = segs.length ? segs[segs.length - 1].seg + 1 : 1;
|
|
76
|
+
return join(dir, nextSeg === 1 ? `${month}.jsonl` : `${month}-${nextSeg}.jsonl`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 上次追加若在写一半时崩掉,文件末尾可能缺换行;此时直接追加会把新记录拼到残行上,
|
|
81
|
+
* 连上一条历史记录一起毁掉。追加前检查最后一个字节,缺就补一个换行。
|
|
82
|
+
*/
|
|
83
|
+
async function endsWithNewline(filePath) {
|
|
84
|
+
let st;
|
|
85
|
+
try {
|
|
86
|
+
st = await stat(filePath);
|
|
87
|
+
} catch (err) {
|
|
88
|
+
if (err.code === 'ENOENT') return true;
|
|
89
|
+
throw err;
|
|
90
|
+
}
|
|
91
|
+
if (st.size === 0) return true;
|
|
92
|
+
const fh = await open(filePath, 'r');
|
|
93
|
+
try {
|
|
94
|
+
const buf = Buffer.alloc(1);
|
|
95
|
+
await fh.read(buf, 0, 1, st.size - 1);
|
|
96
|
+
return buf[0] === 0x0a;
|
|
97
|
+
} finally {
|
|
98
|
+
await fh.close();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 把淘汰项追加进当月归档文件(一次写入,减少半行风险);
|
|
104
|
+
* 当月文件超过单文件上限时自动切到下一个分段。
|
|
105
|
+
* @param {Array<{memory: Object, value: number}>} records - 被淘汰条目及其淘汰时的价值分
|
|
106
|
+
* @param {{dir: string, reason?: string, now?: number, maxFileBytes?: number}} opts
|
|
107
|
+
* @returns {Promise<{archived: number, filePath: string}>}
|
|
108
|
+
*/
|
|
109
|
+
export async function appendArchive(records, {
|
|
110
|
+
dir, reason = 'compact', now = Date.now(), maxFileBytes = ARCHIVE_MAX_FILE_BYTES,
|
|
111
|
+
}) {
|
|
112
|
+
const list = Array.isArray(records) ? records.filter((r) => r && r.memory) : [];
|
|
113
|
+
if (!list.length) return { archived: 0, filePath: null };
|
|
114
|
+
|
|
115
|
+
await mkdir(dir, { recursive: true });
|
|
116
|
+
const archivedAt = new Date(now).toISOString();
|
|
117
|
+
const body = list.map(({ memory, value }) => JSON.stringify({
|
|
118
|
+
...memory,
|
|
119
|
+
archivedAt,
|
|
120
|
+
archiveReason: reason,
|
|
121
|
+
archiveValue: Number.isFinite(value) ? Number(value.toFixed(2)) : null,
|
|
122
|
+
})).join('\n') + '\n';
|
|
123
|
+
|
|
124
|
+
const filePath = await pickArchiveTarget(dir, now, Buffer.byteLength(body), maxFileBytes);
|
|
125
|
+
const prefix = await endsWithNewline(filePath) ? '' : '\n';
|
|
126
|
+
await appendFile(filePath, prefix + body, 'utf8');
|
|
127
|
+
return { archived: list.length, filePath };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* 总量控制:按「月份 + 分段号」从旧到新,删到「文件数 ≤ maxFiles 且总字节 ≤ maxBytes」。
|
|
132
|
+
* 永远保留最新的一个文件:即使它单独就超过 maxBytes(极端情况下单次归档量过大),
|
|
133
|
+
* 删掉它等于删掉刚归档的数据,宁可让上限短暂失效。
|
|
134
|
+
* @param {{dir: string, maxFiles?: number, maxBytes?: number}} opts
|
|
135
|
+
* @returns {Promise<{removed: string[]}>}
|
|
136
|
+
*/
|
|
137
|
+
export async function pruneArchive({
|
|
138
|
+
dir,
|
|
139
|
+
maxFiles = ARCHIVE_MAX_FILES,
|
|
140
|
+
maxBytes = ARCHIVE_MAX_BYTES,
|
|
141
|
+
} = {}) {
|
|
142
|
+
let names;
|
|
143
|
+
try {
|
|
144
|
+
names = await readdir(dir);
|
|
145
|
+
} catch (err) {
|
|
146
|
+
if (err.code === 'ENOENT') return { removed: [] };
|
|
147
|
+
throw err;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const files = [];
|
|
151
|
+
let total = 0;
|
|
152
|
+
for (const name of names
|
|
153
|
+
.filter((n) => ARCHIVE_FILE_RE.test(n))
|
|
154
|
+
.sort((a, b) => archiveSortKey(a).localeCompare(archiveSortKey(b)))) {
|
|
155
|
+
const path = join(dir, name);
|
|
156
|
+
const st = await stat(path);
|
|
157
|
+
files.push({ name, path, size: st.size });
|
|
158
|
+
total += st.size;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const removed = [];
|
|
162
|
+
while (files.length > 1 && (files.length > maxFiles || total > maxBytes)) {
|
|
163
|
+
const oldest = files.shift();
|
|
164
|
+
await rm(oldest.path, { force: true });
|
|
165
|
+
total -= oldest.size;
|
|
166
|
+
removed.push(oldest.name);
|
|
167
|
+
}
|
|
168
|
+
return { removed };
|
|
169
|
+
}
|
package/src/memory/service.js
CHANGED
|
@@ -5,8 +5,9 @@
|
|
|
5
5
|
// store/recall/manage 按 action 分发;文案经调用方传入的请求语言 t 闭包渲染。
|
|
6
6
|
|
|
7
7
|
import { readFile, writeFile } from 'fs/promises';
|
|
8
|
-
import { join } from 'path';
|
|
8
|
+
import { dirname, join } from 'path';
|
|
9
9
|
import { MEMORY_DIR } from '../config.js';
|
|
10
|
+
import { appendArchive, pruneArchive } from './archive.js';
|
|
10
11
|
import { calcMemoryValue, selectMemoriesForInjection } from './injection.js';
|
|
11
12
|
import { extractMemoryTerms, keywordScore, buildDocFreqFilter, memorySearchText, KEYWORD_MIN_UNITS } from './tokens.js';
|
|
12
13
|
import { getMemoryEmbeddingConfig, toEmbeddingProviderConfig } from './embedding-config.js';
|
|
@@ -142,6 +143,9 @@ function byKeywordRank(a, b) {
|
|
|
142
143
|
*/
|
|
143
144
|
export function createMemoryService({
|
|
144
145
|
filePath = join(MEMORY_DIR, 'global-memory.json'),
|
|
146
|
+
// 归档目录默认与真源文件同级的 archive/:测试只要注入 filePath 就自动隔离,
|
|
147
|
+
// 不会有人忘了传 archiveDir 就把淘汰记录写进用户真实目录
|
|
148
|
+
archiveDir = join(dirname(filePath), 'archive'),
|
|
145
149
|
vectorsFilePath,
|
|
146
150
|
embeddingConfigProvider = getMemoryEmbeddingConfig,
|
|
147
151
|
embedderFactory = (cfg) => createEmbeddingProvider(cfg),
|
|
@@ -815,48 +819,72 @@ export function createMemoryService({
|
|
|
815
819
|
}
|
|
816
820
|
|
|
817
821
|
if (action === 'compact') {
|
|
818
|
-
//
|
|
822
|
+
// 压缩:先归档低价值记忆,再从真源移除。淘汰不等于物理删除——
|
|
823
|
+
// 归档写不进去就整轮中止(fail-closed),宁可这轮不压缩,也不能让用户失去找回的可能。
|
|
819
824
|
const threshold = 10;
|
|
825
|
+
const keptFacts = [];
|
|
826
|
+
const keptSummaries = [];
|
|
827
|
+
const removed = [];
|
|
820
828
|
let removedFacts = 0;
|
|
821
829
|
let removedSummaries = 0;
|
|
822
830
|
|
|
823
|
-
const
|
|
824
|
-
memoryData.facts = memoryData.facts.filter(m => {
|
|
831
|
+
for (const m of memoryData.facts) {
|
|
825
832
|
const value = calcMemoryValue(m, now);
|
|
826
833
|
if (value < threshold) {
|
|
834
|
+
removed.push({ memory: m, value });
|
|
827
835
|
removedFacts++;
|
|
828
|
-
|
|
829
|
-
|
|
836
|
+
} else {
|
|
837
|
+
keptFacts.push(m);
|
|
830
838
|
}
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
memoryData.summaries = memoryData.summaries.filter(m => {
|
|
839
|
+
}
|
|
840
|
+
for (const m of memoryData.summaries) {
|
|
835
841
|
const value = calcMemoryValue(m, now);
|
|
836
842
|
if (value < threshold) {
|
|
843
|
+
removed.push({ memory: m, value });
|
|
837
844
|
removedSummaries++;
|
|
838
|
-
|
|
839
|
-
|
|
845
|
+
} else {
|
|
846
|
+
keptSummaries.push(m);
|
|
840
847
|
}
|
|
841
|
-
|
|
842
|
-
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
if (removed.length) {
|
|
851
|
+
try {
|
|
852
|
+
await appendArchive(removed, { dir: archiveDir, reason: 'compact', now });
|
|
853
|
+
} catch (err) {
|
|
854
|
+
return { success: false, error: t('memory.archiveFailed', { error: err.message }) };
|
|
855
|
+
}
|
|
856
|
+
memoryData.facts = keptFacts;
|
|
857
|
+
memoryData.summaries = keptSummaries;
|
|
858
|
+
}
|
|
843
859
|
|
|
844
|
-
memoryData.stats.lastReviewAt = new Date().toISOString();
|
|
860
|
+
memoryData.stats.lastReviewAt = new Date(now).toISOString();
|
|
845
861
|
|
|
846
862
|
const writeResult = await writeMemoryFile(memoryData);
|
|
847
863
|
if (!writeResult.success) return { success: false, error: t('memory.writeFailed', { error: writeResult.error }) };
|
|
848
864
|
|
|
849
865
|
// 已淘汰记忆从会话召回缓存中移除,避免后续会话永久占位
|
|
850
|
-
|
|
866
|
+
const removedIds = removed.map(r => r.memory.id);
|
|
867
|
+
for (const id of removedIds) removeFromRecalledCache(id);
|
|
851
868
|
|
|
852
869
|
// 淘汰项的向量一并摘除:派生缓存可以整删重建,但不能指向已被压缩掉的条目
|
|
853
|
-
if (
|
|
870
|
+
if (removedIds.length) await vectors.dropVectors(removedIds);
|
|
871
|
+
|
|
872
|
+
// 归档总量控制放在数据安全落盘之后;清旧文件失败只告警,不影响本轮结果
|
|
873
|
+
if (removed.length) {
|
|
874
|
+
try {
|
|
875
|
+
await pruneArchive({ dir: archiveDir });
|
|
876
|
+
} catch (err) {
|
|
877
|
+
console.warn('[Memory] archive prune failed:', err.message);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
854
880
|
|
|
855
881
|
return {
|
|
856
882
|
success: true,
|
|
857
|
-
message: t('memory.compactDone', { facts: removedFacts, summaries: removedSummaries, threshold, totalFacts: memoryData.stats.totalFacts, totalSummaries: memoryData.stats.totalSummaries }),
|
|
883
|
+
message: t('memory.compactDone', { facts: removedFacts, summaries: removedSummaries, threshold, totalFacts: memoryData.stats.totalFacts, totalSummaries: memoryData.stats.totalSummaries, archiveDir }),
|
|
858
884
|
removedFacts,
|
|
859
885
|
removedSummaries,
|
|
886
|
+
archived: removed.length,
|
|
887
|
+
archiveDir,
|
|
860
888
|
stats: memoryData.stats
|
|
861
889
|
};
|
|
862
890
|
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// 知识库可恢复备份:保留原件与完整文本,向量索引在恢复时重新生成
|
|
2
|
+
import { extname, join } from 'path';
|
|
3
|
+
import { stat } from 'fs/promises';
|
|
4
|
+
import { ZipArchive } from 'archiver';
|
|
5
|
+
import { ORIGINALS_ROOT } from './config.js';
|
|
6
|
+
|
|
7
|
+
const BACKUP_FORMAT = 'ai-helper-knowledge-base-backup';
|
|
8
|
+
const ORIGINAL_EXT_RE = /^\.[a-z0-9]{1,8}$/;
|
|
9
|
+
const MAX_ENTRY_NAME = 160;
|
|
10
|
+
|
|
11
|
+
function safeOriginalExt(ext) {
|
|
12
|
+
const value = String(ext || '').toLowerCase();
|
|
13
|
+
return ORIGINAL_EXT_RE.test(value) ? value : '.bin';
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* ZIP 内文件名只保留单段,清理控制字符与各平台保留字符。
|
|
18
|
+
* 超长名按「主干裁剪 + 保留扩展名」截断:直接切尾会把 .pdf/.docx 切掉,
|
|
19
|
+
* 恢复时无法识别文件类型。
|
|
20
|
+
*/
|
|
21
|
+
function safeFileName(value, fallback) {
|
|
22
|
+
const cleaned = String(value || '')
|
|
23
|
+
.replace(/[\u0000-\u001f<>:"/\\|?*]/g, '_')
|
|
24
|
+
.replace(/[. ]+$/g, '')
|
|
25
|
+
.trim();
|
|
26
|
+
if (!cleaned) return fallback;
|
|
27
|
+
if (cleaned.length <= MAX_ENTRY_NAME) return cleaned;
|
|
28
|
+
|
|
29
|
+
const rawExt = extname(cleaned);
|
|
30
|
+
const ext = rawExt.length > 1 && rawExt.length <= 10 ? rawExt : '';
|
|
31
|
+
const stem = ext ? cleaned.slice(0, -ext.length) : cleaned;
|
|
32
|
+
return `${stem.slice(0, MAX_ENTRY_NAME - ext.length)}${ext}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 保留可读原名;重名时追加文档 ID,避免覆盖(按大小写不敏感判断,兼容 Windows/macOS) */
|
|
36
|
+
function allocateEntryName(directory, preferredName, documentId, usedNames) {
|
|
37
|
+
const safeName = safeFileName(preferredName, documentId);
|
|
38
|
+
const ext = extname(safeName);
|
|
39
|
+
const stem = ext ? safeName.slice(0, -ext.length) : safeName;
|
|
40
|
+
let candidate = `${directory}/${safeName}`;
|
|
41
|
+
let suffix = 0;
|
|
42
|
+
while (usedNames.has(candidate.toLowerCase())) {
|
|
43
|
+
suffix += 1;
|
|
44
|
+
const disambiguator = suffix === 1 ? documentId : `${documentId}-${suffix}`;
|
|
45
|
+
candidate = `${directory}/${stem}-${disambiguator}${ext}`;
|
|
46
|
+
}
|
|
47
|
+
usedNames.add(candidate.toLowerCase());
|
|
48
|
+
return candidate;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** ZIP 文件名用本地日期(toISOString 是 UTC,东八区凌晨导出会差一天) */
|
|
52
|
+
export function formatLocalDate(date) {
|
|
53
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
54
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function collectionForExport(collection) {
|
|
58
|
+
const { apiKey, ...embeddingConfig } = collection.embeddingConfig || {};
|
|
59
|
+
return {
|
|
60
|
+
...collection,
|
|
61
|
+
embeddingConfig: {
|
|
62
|
+
...embeddingConfig,
|
|
63
|
+
apiKey: '',
|
|
64
|
+
hasApiKey: Boolean(apiKey),
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function restoreReadme(collection) {
|
|
70
|
+
return `AI Helper 知识库备份 / Knowledge Base Backup
|
|
71
|
+
=========================================
|
|
72
|
+
|
|
73
|
+
知识库:${collection.name}
|
|
74
|
+
知识库 ID:${collection.id}
|
|
75
|
+
|
|
76
|
+
备份内容
|
|
77
|
+
- manifest.json:知识库配置、文档索引、文件路径、SHA-256 和缺失项警告。
|
|
78
|
+
- documents/*.json:每篇文档的完整内部备份(含全文与元数据),文件名与内部存储一致。
|
|
79
|
+
- originals/*:导入时保留的原始文件。
|
|
80
|
+
- texts/*:仅对「没有原件」的文档提供完整 UTF-8 提取文本,避免与 documents/ 重复存一份全文。
|
|
81
|
+
|
|
82
|
+
恢复方法
|
|
83
|
+
1. 在 AI Helper 中新建知识库,按 manifest.json 的 collection 配置名称、向量模型和分块参数。
|
|
84
|
+
2. 远端向量服务的 API Key 不会写入备份,请在恢复时重新填写。
|
|
85
|
+
3. 最直接的方式:把 documents/*.json 拷回 <RAG 数据目录>/<知识库 ID>/documents/,
|
|
86
|
+
把 originals/* 拷回 <RAG 数据目录>/originals/<知识库 ID>/(文件名需改回文档 ID),
|
|
87
|
+
即可复用原始文档记录。
|
|
88
|
+
4. 更稳妥的方式:重新导入 originals/ 中的文件;没有原件时导入 texts/ 中的文本。
|
|
89
|
+
5. 重新导入会重新分块并生成向量索引,因此备份不包含旧向量、缓存或索引文件。
|
|
90
|
+
6. 如 manifest.json 的 warnings 非空,请先查看缺失项:
|
|
91
|
+
- backupUnreadable:内部文档备份无法解析,该文档未进入备份(需从其他来源补齐)。
|
|
92
|
+
- originalMissing:原件已丢失,仅保留了全文(见 documents/ 或 texts/)。
|
|
93
|
+
- documentExportFailed:该文档导出时出错,备份不完整。
|
|
94
|
+
|
|
95
|
+
Backup contents
|
|
96
|
+
- manifest.json: sanitized collection settings, document metadata, entry paths, hashes and warnings.
|
|
97
|
+
- documents/: complete internal document backups, byte-compatible with the agent's storage layout.
|
|
98
|
+
- originals/: retained original bytes.
|
|
99
|
+
- texts/: full UTF-8 text only for documents without an exported original (avoids duplicating
|
|
100
|
+
the same text that documents/ already contains).
|
|
101
|
+
|
|
102
|
+
To restore, create a knowledge base using the collection settings in manifest.json,
|
|
103
|
+
re-enter the remote embedding API key, then import originals/ (or texts/ when no original exists).
|
|
104
|
+
The vector index is intentionally excluded and is rebuilt on import.
|
|
105
|
+
Check manifest.json warnings for any incomplete entries.
|
|
106
|
+
`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 准备单库 ZIP 流。原件由 archiver 逐文件读取,不把整个知识库一次性载入内存。
|
|
111
|
+
* 调用方负责 archive.pipe(destination) 与 archive.finalize()。
|
|
112
|
+
*/
|
|
113
|
+
export async function buildCollectionExport(manager, collection) {
|
|
114
|
+
const collectionId = collection.id;
|
|
115
|
+
const { documents, unreadable } = await manager.scanDocumentBackups(collectionId);
|
|
116
|
+
const now = new Date();
|
|
117
|
+
const exportedAt = now.toISOString();
|
|
118
|
+
const archive = new ZipArchive({ zlib: { level: 6 } });
|
|
119
|
+
const usedNames = new Set(['manifest.json', 'readme.txt']);
|
|
120
|
+
const manifestDocuments = [];
|
|
121
|
+
// 损坏的内部备份不能静默丢弃:写进 warnings,恢复时才不会"少文件却不知道"
|
|
122
|
+
const warnings = unreadable.map((item) => ({
|
|
123
|
+
documentId: item.documentId,
|
|
124
|
+
code: 'backupUnreadable',
|
|
125
|
+
name: item.file,
|
|
126
|
+
}));
|
|
127
|
+
const pendingOriginals = [];
|
|
128
|
+
|
|
129
|
+
for (const { id: documentId, backup } of documents) {
|
|
130
|
+
try {
|
|
131
|
+
const backupPath = `documents/${documentId}.json`;
|
|
132
|
+
const { text, ...metadata } = backup;
|
|
133
|
+
const entry = {
|
|
134
|
+
...metadata,
|
|
135
|
+
id: documentId,
|
|
136
|
+
backupPath,
|
|
137
|
+
textPath: null,
|
|
138
|
+
original: null,
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
if (backup.original) {
|
|
142
|
+
const ext = safeOriginalExt(backup.original.ext);
|
|
143
|
+
const originalPath = join(ORIGINALS_ROOT, collectionId, `${documentId}${ext}`);
|
|
144
|
+
const info = await stat(originalPath).catch(() => null);
|
|
145
|
+
if (info?.isFile()) {
|
|
146
|
+
const zipPath = allocateEntryName(
|
|
147
|
+
'originals',
|
|
148
|
+
backup.original.name || `${backup.name || documentId}${ext}`,
|
|
149
|
+
documentId,
|
|
150
|
+
usedNames,
|
|
151
|
+
);
|
|
152
|
+
entry.original = { ...backup.original, exported: true, path: zipPath };
|
|
153
|
+
pendingOriginals.push({ path: originalPath, name: zipPath });
|
|
154
|
+
} else {
|
|
155
|
+
entry.original = { ...backup.original, exported: false, path: null };
|
|
156
|
+
warnings.push({ documentId, code: 'originalMissing', name: backup.name || documentId });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// 有原件时正文已可由原件重建,不再重复写一份;无原件时文本是唯一的恢复来源
|
|
161
|
+
if (!entry.original?.exported) {
|
|
162
|
+
entry.textPath = allocateEntryName(
|
|
163
|
+
'texts',
|
|
164
|
+
`${backup.name || documentId}.txt`,
|
|
165
|
+
documentId,
|
|
166
|
+
usedNames,
|
|
167
|
+
);
|
|
168
|
+
archive.append(String(text || ''), { name: entry.textPath });
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
manifestDocuments.push(entry);
|
|
172
|
+
archive.append(JSON.stringify(backup, null, 2), { name: backupPath });
|
|
173
|
+
} catch (err) {
|
|
174
|
+
warnings.push({ documentId, code: 'documentExportFailed', message: String(err?.message || err) });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
for (const original of pendingOriginals) {
|
|
179
|
+
archive.file(original.path, { name: original.name });
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const manifest = {
|
|
183
|
+
format: BACKUP_FORMAT,
|
|
184
|
+
version: 1,
|
|
185
|
+
exportedAt,
|
|
186
|
+
collection: collectionForExport(collection),
|
|
187
|
+
stats: {
|
|
188
|
+
documents: manifestDocuments.length,
|
|
189
|
+
originals: manifestDocuments.filter((doc) => doc.original?.exported).length,
|
|
190
|
+
missingOriginals: warnings.filter((item) => item.code === 'originalMissing').length,
|
|
191
|
+
unreadableBackups: unreadable.length,
|
|
192
|
+
},
|
|
193
|
+
documents: manifestDocuments,
|
|
194
|
+
warnings,
|
|
195
|
+
};
|
|
196
|
+
const safeCollectionName = safeFileName(collection.name, collectionId);
|
|
197
|
+
const fileName = `${safeCollectionName}-backup-${formatLocalDate(now)}.zip`;
|
|
198
|
+
|
|
199
|
+
archive.append(restoreReadme(collection), { name: 'README.txt' });
|
|
200
|
+
archive.append(JSON.stringify(manifest, null, 2), { name: 'manifest.json' });
|
|
201
|
+
return { archive, fileName, warningCount: warnings.length };
|
|
202
|
+
}
|
package/src/rag/manager.js
CHANGED
|
@@ -27,6 +27,7 @@ import { checkPath } from '../security.js';
|
|
|
27
27
|
import { fetchUrlGuarded, decodeBytes } from './url-guard.js';
|
|
28
28
|
import { loadConfig } from '../config.js';
|
|
29
29
|
import { encodeSecret, decodeSecret } from '../crypto-lite.js';
|
|
30
|
+
import { buildCollectionExport } from './export.js';
|
|
30
31
|
|
|
31
32
|
// 知识库 ID 格式校验(防路径穿越)
|
|
32
33
|
const COLLECTION_ID_RE = /^kb_[a-z0-9]+$/;
|
|
@@ -1134,6 +1135,36 @@ export class RagManager {
|
|
|
1134
1135
|
|
|
1135
1136
|
// ==================== 文档管理 ====================
|
|
1136
1137
|
|
|
1138
|
+
/**
|
|
1139
|
+
* 创建可恢复 ZIP 备份。导出期间与导入/重建/删除互斥,避免读到半完成状态。
|
|
1140
|
+
* 流结束、关闭或出错时释放锁;调用方必须消费并 finalize 返回的 archive,
|
|
1141
|
+
* 若在消费前失败,必须调用返回的 release() 兜底,避免知识库被长期锁住。
|
|
1142
|
+
*/
|
|
1143
|
+
async createCollectionExport(collectionId) {
|
|
1144
|
+
const collection = await this.getCollection(collectionId);
|
|
1145
|
+
this._assertIdle(collectionId);
|
|
1146
|
+
this._activeOps.add(collectionId);
|
|
1147
|
+
|
|
1148
|
+
let exported;
|
|
1149
|
+
try {
|
|
1150
|
+
exported = await buildCollectionExport(this, collection);
|
|
1151
|
+
} catch (err) {
|
|
1152
|
+
this._activeOps.delete(collectionId);
|
|
1153
|
+
throw err;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
let released = false;
|
|
1157
|
+
const release = () => {
|
|
1158
|
+
if (released) return;
|
|
1159
|
+
released = true;
|
|
1160
|
+
this._activeOps.delete(collectionId);
|
|
1161
|
+
};
|
|
1162
|
+
exported.archive.once('end', release);
|
|
1163
|
+
exported.archive.once('close', release);
|
|
1164
|
+
exported.archive.once('error', release);
|
|
1165
|
+
return { ...exported, release };
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1137
1168
|
/**
|
|
1138
1169
|
* 列出知识库中的所有文档(以 documents/*.json 备份为准:带来原件信息,且不必扫全量分块)
|
|
1139
1170
|
* 备份目录缺失/为空时回退到分块元数据聚合(兼容无备份的老数据)
|
|
@@ -1196,6 +1227,38 @@ export class RagManager {
|
|
|
1196
1227
|
return [...docs.values()].sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
|
|
1197
1228
|
}
|
|
1198
1229
|
|
|
1230
|
+
/**
|
|
1231
|
+
* 枚举文档备份文件(导出用)
|
|
1232
|
+
* 与 listDocuments 的区别:无法解析的备份不被静默忽略,而是作为 unreadable 返回,
|
|
1233
|
+
* 由灾备包记录缺失项——导出链路最忌讳"看起来成功但少了数据"。
|
|
1234
|
+
* @returns {Promise<{documents: Array<{id: string, backup: object}>, unreadable: Array<{documentId: string, file: string}>}>}
|
|
1235
|
+
*/
|
|
1236
|
+
async scanDocumentBackups(collectionId) {
|
|
1237
|
+
await this.getCollection(collectionId); // 校验存在性
|
|
1238
|
+
|
|
1239
|
+
const docsDir = join(RAG_ROOT, collectionId, 'documents');
|
|
1240
|
+
let files;
|
|
1241
|
+
try {
|
|
1242
|
+
files = await readdir(docsDir);
|
|
1243
|
+
} catch {
|
|
1244
|
+
return { documents: [], unreadable: [] };
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
const documents = [];
|
|
1248
|
+
const unreadable = [];
|
|
1249
|
+
for (const file of files.sort()) {
|
|
1250
|
+
if (!file.endsWith('.json')) continue;
|
|
1251
|
+
const fallbackId = file.slice(0, -'.json'.length);
|
|
1252
|
+
try {
|
|
1253
|
+
const backup = JSON.parse(await readFile(join(docsDir, file), 'utf-8'));
|
|
1254
|
+
documents.push({ id: backup.id || fallbackId, backup });
|
|
1255
|
+
} catch {
|
|
1256
|
+
unreadable.push({ documentId: fallbackId, file });
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
return { documents, unreadable };
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1199
1262
|
/**
|
|
1200
1263
|
* 读取文档备份(文本真源)
|
|
1201
1264
|
* @returns {Promise<object>}
|