dsh-weknora-recall 0.1.0 → 0.1.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.
- package/README.md +33 -0
- package/lib/index.js +141 -40
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -46,3 +46,36 @@ pnpm add dsh-weknora-recall
|
|
|
46
46
|
## 许可
|
|
47
47
|
|
|
48
48
|
MIT © chenge
|
|
49
|
+
|
|
50
|
+
## 配置
|
|
51
|
+
|
|
52
|
+
> **日常不建议改这里。** 这些项都有默认值,要改就改统一配置文件 `~/.mnemon/state/weknora-suite.json` 里 `packages.<包名>.values` —— 那份文件带中文说明、带出厂值可回滚,AI 也能直接改。写在 `cordis.patch.yml` 里会盖住它,只在「这个 profile 要跟别人不一样」时才用。
|
|
53
|
+
|
|
54
|
+
全部可在 profile 的 `cordis.patch.yml` 里按行覆盖,不配就用默认值。
|
|
55
|
+
|
|
56
|
+
```yaml
|
|
57
|
+
- id: weknora-recall
|
|
58
|
+
name: "dsh-weknora-recall"
|
|
59
|
+
config:
|
|
60
|
+
knowledgeBodyName: "知识" # 只查这个名字的空间;"" = 全部空间都查
|
|
61
|
+
maxChars: 900 # 本轮注入块总字数上限
|
|
62
|
+
perSpaceItems: 2 # 每个空间取几条
|
|
63
|
+
perItemChars: 220 # 每条保留多少字
|
|
64
|
+
timeoutMs: 1500 # 整轮召回硬超时,超了就不注入
|
|
65
|
+
providerTimeoutMs: 1200 # 单次检索请求超时
|
|
66
|
+
minQueryChars: 4 # 短于这个字数不查
|
|
67
|
+
fetchFactor: 2 # 先多取再截断的倍数
|
|
68
|
+
preamble: "" # 注入块抬头,留空用内置
|
|
69
|
+
archiveHeading: "" # 「自动归档」那一节的标题
|
|
70
|
+
archive:
|
|
71
|
+
enabled: true # 是否连带本地自动归档文档
|
|
72
|
+
maxDocs: 2
|
|
73
|
+
itemChars: 320
|
|
74
|
+
matchWindow: 900
|
|
75
|
+
minScore: 2
|
|
76
|
+
stateCacheMs: 5000 # 状态文件缓存;0 = 每轮重读
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
两个路径 `statePath` / `documentIndexPath` 默认跟随 mnemon,装到别处才需要改。
|
|
80
|
+
|
|
81
|
+
源码里这份默认值是 `lib/index.js` 顶部的 `DEFAULTS`,`resolveConfig()` 负责合并与类型兜底——配置写错不会让插件崩。
|
package/lib/index.js
CHANGED
|
@@ -11,6 +11,9 @@
|
|
|
11
11
|
*
|
|
12
12
|
* Nothing here writes. Writes stay with mnemon_remember, so the only untrusted direction
|
|
13
13
|
* is "read more than needed", never "store something wrong".
|
|
14
|
+
*
|
|
15
|
+
* Every number and every piece of wording below is overridable from the row's `config`
|
|
16
|
+
* block. Defaults reproduce the behaviour this package shipped with.
|
|
14
17
|
*/
|
|
15
18
|
import { readFileSync } from "node:fs";
|
|
16
19
|
import { homedir } from "node:os";
|
|
@@ -18,26 +21,119 @@ import { join } from "node:path";
|
|
|
18
21
|
import { randomUUID } from "node:crypto";
|
|
19
22
|
import { WeKnoraProvider } from "dsh-mnemon-provider-weknora";
|
|
20
23
|
|
|
24
|
+
/** 统一配置文件 ~/.mnemon/state/weknora-suite.json 里本包那一段;没有或读坏就返回空对象。 */
|
|
25
|
+
function suiteSection(pkgName) {
|
|
26
|
+
try {
|
|
27
|
+
const raw = readFileSync(join(homedir(), ".mnemon", "state", "weknora-suite.json"), "utf8");
|
|
28
|
+
const values = JSON.parse(raw)?.packages?.[pkgName]?.values;
|
|
29
|
+
return values && typeof values === "object" ? values : {};
|
|
30
|
+
} catch {
|
|
31
|
+
return {};
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
21
35
|
export const name = "dsh-weknora-recall";
|
|
22
36
|
|
|
23
|
-
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
37
|
+
/** 默认值:每一项都可以被 config 覆盖,默认值等于本包原本的行为。 */
|
|
38
|
+
const DEFAULTS = {
|
|
39
|
+
enabled: true,
|
|
40
|
+
/** 本轮注入块的总字数上限(含抬头与标题)。越小越省钱,越大越可能带上无关内容。 */
|
|
41
|
+
maxChars: 900,
|
|
42
|
+
/** 每个记忆空间取几条。 */
|
|
43
|
+
perSpaceItems: 2,
|
|
44
|
+
/** 检索时先从服务端多取几条,再在本地截断,用来提高命中率。 */
|
|
45
|
+
fetchFactor: 2,
|
|
46
|
+
/** 每条结果保留多少字。 */
|
|
47
|
+
perItemChars: 220,
|
|
48
|
+
/** 整轮召回的硬超时。超时就不注入,绝不拖慢这一轮。 */
|
|
49
|
+
timeoutMs: 1500,
|
|
50
|
+
/** 单次检索请求到维克纳的超时。 */
|
|
51
|
+
providerTimeoutMs: 1200,
|
|
52
|
+
/** 少于这个字数的问题不查(「好」「继续」这种问了也没用)。 */
|
|
53
|
+
minQueryChars: 4,
|
|
54
|
+
/**
|
|
55
|
+
* 只查名字等于它的记忆空间。留空字符串表示所有空间都查。
|
|
56
|
+
* 改成别的名字,或改成 "" 全查,都是这一行。
|
|
57
|
+
*/
|
|
58
|
+
knowledgeBodyName: "知识",
|
|
59
|
+
/** 注入块抬头。留空用内置文案。 */
|
|
60
|
+
preamble: "",
|
|
61
|
+
/** 自动归档那一节的标题,留空则用内置标题。 */
|
|
62
|
+
archiveHeading: "",
|
|
63
|
+
/** 状态文件缓存毫秒;0 表示每轮都重新读(改配置立刻生效)。 */
|
|
64
|
+
stateCacheMs: 5000,
|
|
65
|
+
/** 注入消息的 source.kind,一般不用改。 */
|
|
66
|
+
sourceKind: "plugin:weknora-recall",
|
|
67
|
+
/** 附带的本地自动归档文档检索(mnemon 空闲审查写的那批 Markdown)。 */
|
|
68
|
+
archive: {
|
|
69
|
+
enabled: true,
|
|
70
|
+
/** 最多带几篇。 */
|
|
71
|
+
maxDocs: 2,
|
|
72
|
+
/** 每篇保留多少字。 */
|
|
73
|
+
itemChars: 320,
|
|
74
|
+
/** 只拿正文前多少字参与匹配。 */
|
|
75
|
+
matchWindow: 900,
|
|
76
|
+
/** 命中分低于它就不算相关。 */
|
|
77
|
+
minScore: 2,
|
|
78
|
+
},
|
|
79
|
+
/** 这两个路径跟着 mnemon 的装机位置走,一般不用改。 */
|
|
80
|
+
statePath: "",
|
|
81
|
+
documentIndexPath: "",
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const BUILTIN_PREAMBLE =
|
|
85
|
+
"<weknora_recall>\n" +
|
|
86
|
+
"下面是从长期记忆里按本轮问题捞出来的。仍是过去记录,引用数值前与现状核对;与本轮原话冲突时以原话为准。";
|
|
87
|
+
|
|
88
|
+
const BUILTIN_ARCHIVE_HEADING = "自动归档(mnemon 空闲审查自己写的)";
|
|
89
|
+
|
|
90
|
+
const num = (value, fallback) => {
|
|
91
|
+
const parsed = typeof value === "string" ? Number(value.trim()) : value;
|
|
92
|
+
return typeof parsed === "number" && Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
|
|
93
|
+
};
|
|
94
|
+
const str = (value, fallback) => (typeof value === "string" ? value : fallback);
|
|
95
|
+
const bool = (value, fallback) => (typeof value === "boolean" ? value : fallback);
|
|
96
|
+
|
|
97
|
+
/** 把用户 config 合并到默认值上,并对每个字段做类型兜底。配置写错不该让插件崩。 */
|
|
98
|
+
export function resolveConfig(config = {}) {
|
|
99
|
+
const source = { ...suiteSection("dsh-weknora-recall"), ...(config ?? {}) };
|
|
100
|
+
const archive = source.archive ?? {};
|
|
101
|
+
return {
|
|
102
|
+
enabled: bool(source.enabled, DEFAULTS.enabled),
|
|
103
|
+
maxChars: num(source.maxChars, DEFAULTS.maxChars),
|
|
104
|
+
perSpaceItems: num(source.perSpaceItems, DEFAULTS.perSpaceItems),
|
|
105
|
+
fetchFactor: num(source.fetchFactor, DEFAULTS.fetchFactor),
|
|
106
|
+
perItemChars: num(source.perItemChars, DEFAULTS.perItemChars),
|
|
107
|
+
timeoutMs: num(source.timeoutMs, DEFAULTS.timeoutMs),
|
|
108
|
+
providerTimeoutMs: num(source.providerTimeoutMs, DEFAULTS.providerTimeoutMs),
|
|
109
|
+
minQueryChars: num(source.minQueryChars, DEFAULTS.minQueryChars),
|
|
110
|
+
knowledgeBodyName: str(source.knowledgeBodyName, DEFAULTS.knowledgeBodyName),
|
|
111
|
+
preamble: str(source.preamble, DEFAULTS.preamble),
|
|
112
|
+
archiveHeading: str(source.archiveHeading, DEFAULTS.archiveHeading),
|
|
113
|
+
stateCacheMs: num(source.stateCacheMs, DEFAULTS.stateCacheMs),
|
|
114
|
+
sourceKind: str(source.sourceKind, DEFAULTS.sourceKind),
|
|
115
|
+
archive: {
|
|
116
|
+
enabled: bool(archive.enabled, DEFAULTS.archive.enabled),
|
|
117
|
+
maxDocs: num(archive.maxDocs, DEFAULTS.archive.maxDocs),
|
|
118
|
+
itemChars: num(archive.itemChars, DEFAULTS.archive.itemChars),
|
|
119
|
+
matchWindow: num(archive.matchWindow, DEFAULTS.archive.matchWindow),
|
|
120
|
+
minScore: num(archive.minScore, DEFAULTS.archive.minScore),
|
|
121
|
+
},
|
|
122
|
+
statePath: str(source.statePath, "") || join(homedir(), ".mnemon", "state", "memory-providers.json"),
|
|
123
|
+
documentIndexPath: str(source.documentIndexPath, "") || join(homedir(), ".mnemon", "documents", "index.json"),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
let cfg = resolveConfig({});
|
|
32
128
|
|
|
33
129
|
/** 每轮都读一次状态文件:用户在页面上改配置不该等到重启。失败就用上一次的。 */
|
|
34
130
|
let cache = { at: 0, value: null };
|
|
35
131
|
|
|
36
132
|
function loadState() {
|
|
37
133
|
const now = Date.now();
|
|
38
|
-
if (cache.value && now - cache.at <
|
|
134
|
+
if (cfg.stateCacheMs > 0 && cache.value && now - cache.at < cfg.stateCacheMs) return cache.value;
|
|
39
135
|
try {
|
|
40
|
-
const raw = JSON.parse(readFileSync(
|
|
136
|
+
const raw = JSON.parse(readFileSync(cfg.statePath, "utf8"));
|
|
41
137
|
const service = raw?.services?.weknora;
|
|
42
138
|
const bodies = (Array.isArray(raw?.bodies) ? raw.bodies : []).filter(
|
|
43
139
|
(body) => body && body.active === true && body.providerId === "weknora" && body.connection?.knowledgeBaseId,
|
|
@@ -87,20 +183,17 @@ function clip(text, limit) {
|
|
|
87
183
|
|
|
88
184
|
function render(sections) {
|
|
89
185
|
const lines = [];
|
|
90
|
-
const preamble =
|
|
91
|
-
"<weknora_recall>\n" +
|
|
92
|
-
"下面是从长期记忆里按本轮问题捞出来的(WeKnora 三个空间:知识=结论,会话记忆=过程原文,资料=素材;末节是 mnemon 空闲审查自动归档的文档)。" +
|
|
93
|
-
"仍是过去记录,引用数值前与现状核对;与本轮原话冲突时以原话为准。";
|
|
186
|
+
const preamble = cfg.preamble !== "" ? cfg.preamble : BUILTIN_PREAMBLE;
|
|
94
187
|
let size = preamble.length;
|
|
95
188
|
for (const section of sections) {
|
|
96
189
|
if (section.items.length === 0) continue;
|
|
97
190
|
const head = "\n### " + section.name;
|
|
98
|
-
if (size + head.length >
|
|
191
|
+
if (size + head.length > cfg.maxChars) break;
|
|
99
192
|
lines.push(head);
|
|
100
193
|
size += head.length;
|
|
101
194
|
for (const item of section.items) {
|
|
102
|
-
const line = "\n- " + clip(item,
|
|
103
|
-
if (size + line.length >
|
|
195
|
+
const line = "\n- " + clip(item, cfg.perItemChars);
|
|
196
|
+
if (size + line.length > cfg.maxChars) break;
|
|
104
197
|
lines.push(line);
|
|
105
198
|
size += line.length;
|
|
106
199
|
}
|
|
@@ -123,9 +216,9 @@ let docCache = { at: 0, docs: [] };
|
|
|
123
216
|
|
|
124
217
|
function loadDocumentIndex() {
|
|
125
218
|
const now = Date.now();
|
|
126
|
-
if (now - docCache.at <
|
|
219
|
+
if (cfg.stateCacheMs > 0 && now - docCache.at < cfg.stateCacheMs) return docCache.docs;
|
|
127
220
|
try {
|
|
128
|
-
const raw = JSON.parse(readFileSync(
|
|
221
|
+
const raw = JSON.parse(readFileSync(cfg.documentIndexPath, "utf8"));
|
|
129
222
|
const rows = Array.isArray(raw?.documents) ? raw.documents : [];
|
|
130
223
|
const docs = rows
|
|
131
224
|
.filter((row) => row && row.status === "active" && typeof row.relativePath === "string")
|
|
@@ -166,16 +259,16 @@ export function searchDocuments(query, limit) {
|
|
|
166
259
|
const scored = [];
|
|
167
260
|
for (const doc of loadDocumentIndex()) {
|
|
168
261
|
// 标题与摘要权重最高,但 idle review 写的标题常是英文短语,提问却是中文,
|
|
169
|
-
//
|
|
170
|
-
const hay = (doc.title + "\n" + doc.description + "\n" + doc.body.slice(0,
|
|
262
|
+
// 所以要给正文也留一票(取前 matchWindow 字,够覆盖结论段)。
|
|
263
|
+
const hay = (doc.title + "\n" + doc.description + "\n" + doc.body.slice(0, cfg.archive.matchWindow)).toLowerCase();
|
|
171
264
|
let score = 0;
|
|
172
265
|
for (const term of terms) if (hay.includes(term)) score += term.length >= 3 ? 2 : 1;
|
|
173
|
-
if (score >=
|
|
266
|
+
if (score >= cfg.archive.minScore) scored.push({ doc, score });
|
|
174
267
|
}
|
|
175
268
|
scored.sort((a, b) => b.score - a.score || b.doc.updatedAt.localeCompare(a.doc.updatedAt));
|
|
176
269
|
const items = [];
|
|
177
270
|
for (const { doc } of scored.slice(0, limit)) {
|
|
178
|
-
if (doc.body.length > 0) items.push("【自动归档】" + doc.title + ":" + clip(doc.body,
|
|
271
|
+
if (doc.body.length > 0) items.push("【自动归档】" + doc.title + ":" + clip(doc.body, cfg.archive.itemChars));
|
|
179
272
|
}
|
|
180
273
|
return items;
|
|
181
274
|
}
|
|
@@ -183,27 +276,34 @@ export function searchDocuments(query, limit) {
|
|
|
183
276
|
async function recall(query, state) {
|
|
184
277
|
const provider = new WeKnoraProvider(
|
|
185
278
|
{ providerConnection: () => state.service },
|
|
186
|
-
{ requestTimeoutMs:
|
|
279
|
+
{ requestTimeoutMs: cfg.providerTimeoutMs },
|
|
187
280
|
);
|
|
188
|
-
// 只做一次:provider
|
|
281
|
+
// 只做一次:provider 靠它知道哪一个空间是「结论库」,否则三个空间都会回答记忆条目。
|
|
189
282
|
try {
|
|
190
283
|
await provider.discover(state.service);
|
|
191
284
|
} catch {}
|
|
192
|
-
//
|
|
193
|
-
//
|
|
194
|
-
const
|
|
195
|
-
|
|
285
|
+
// 只查指定的那个空间(默认「知识」):会话记忆(原文)与资料库不参与每轮自动检索,
|
|
286
|
+
// 需要原话或原始材料时由模型主动去查。找不到该名字的空间才退回全部。
|
|
287
|
+
const wanted =
|
|
288
|
+
cfg.knowledgeBodyName === ""
|
|
289
|
+
? state.bodies
|
|
290
|
+
: state.bodies.filter((body) => body.name === cfg.knowledgeBodyName);
|
|
291
|
+
const bodies = wanted.length > 0 ? wanted : state.bodies;
|
|
292
|
+
const docsPromise =
|
|
293
|
+
cfg.archive.enabled && cfg.archive.maxDocs > 0
|
|
294
|
+
? Promise.resolve(searchDocuments(query, cfg.archive.maxDocs))
|
|
295
|
+
: Promise.resolve([]);
|
|
196
296
|
const [sections, docs] = await Promise.all([
|
|
197
297
|
Promise.all(
|
|
198
298
|
bodies.map(async (body) => {
|
|
199
299
|
try {
|
|
200
300
|
const result = await provider.search(
|
|
201
301
|
{ id: body.id, provider: { typeId: "weknora" }, connection: body.connection },
|
|
202
|
-
{ query, limit:
|
|
302
|
+
{ query, limit: Math.max(1, Math.round(cfg.perSpaceItems * cfg.fetchFactor)) },
|
|
203
303
|
);
|
|
204
304
|
const items = (result?.results ?? [])
|
|
205
|
-
.slice(0,
|
|
206
|
-
.map((hit) => clip(hit.content,
|
|
305
|
+
.slice(0, cfg.perSpaceItems)
|
|
306
|
+
.map((hit) => clip(hit.content, cfg.perItemChars))
|
|
207
307
|
.filter((text) => text.length > 0);
|
|
208
308
|
return { name: body.name, items };
|
|
209
309
|
} catch {
|
|
@@ -211,15 +311,16 @@ async function recall(query, state) {
|
|
|
211
311
|
}
|
|
212
312
|
}),
|
|
213
313
|
),
|
|
214
|
-
|
|
314
|
+
docsPromise,
|
|
215
315
|
]);
|
|
216
|
-
const
|
|
316
|
+
const heading = cfg.archiveHeading !== "" ? cfg.archiveHeading : BUILTIN_ARCHIVE_HEADING;
|
|
317
|
+
const all = docs.length > 0 ? [...sections, { name: heading, items: docs }] : sections;
|
|
217
318
|
return render(all);
|
|
218
319
|
}
|
|
219
320
|
|
|
220
321
|
export function apply(ctx, config = {}) {
|
|
221
|
-
|
|
222
|
-
if (!enabled) return;
|
|
322
|
+
cfg = resolveConfig(config);
|
|
323
|
+
if (!cfg.enabled) return;
|
|
223
324
|
|
|
224
325
|
ctx.on(
|
|
225
326
|
"agent/pre-step",
|
|
@@ -230,8 +331,8 @@ export function apply(ctx, config = {}) {
|
|
|
230
331
|
const state = loadState();
|
|
231
332
|
if (!state) return decision;
|
|
232
333
|
const query = lastUserText(decision.messages ?? input?.agent?.session?.messages);
|
|
233
|
-
if (query.length <
|
|
234
|
-
const block = await withTimeout(recall(query, state),
|
|
334
|
+
if (query.length < cfg.minQueryChars) return decision;
|
|
335
|
+
const block = await withTimeout(recall(query, state), cfg.timeoutMs);
|
|
235
336
|
if (!block) return decision;
|
|
236
337
|
return {
|
|
237
338
|
...decision,
|
|
@@ -241,7 +342,7 @@ export function apply(ctx, config = {}) {
|
|
|
241
342
|
id: randomUUID(),
|
|
242
343
|
role: "user",
|
|
243
344
|
content: [{ type: "text", text: block }],
|
|
244
|
-
source: { kind:
|
|
345
|
+
source: { kind: cfg.sourceKind, form: "context" },
|
|
245
346
|
},
|
|
246
347
|
],
|
|
247
348
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-weknora-recall",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "Recalls relevant WeKnora knowledge before every turn and appends it as a context message, so the assistant remembers instead of guessing.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./lib/index.js",
|