dsh-wiki-notes 0.0.0-stage → 1.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/lib/index.js ADDED
@@ -0,0 +1,886 @@
1
+ /**
2
+ * index.js —— dsh-wiki-notes 的宿主半:注册一个只读工具 wiki_recall。
3
+ *
4
+ * 为什么只有一个工具:profile 里已经装了 26 个插件,模型每回合都要在工具表里选,
5
+ * 多一个工具就是多一份选择成本。四种查询压在同一个工具里用 mode 区分。
6
+ *
7
+ * 为什么用 node:fs 而不是 ctx.fs:库在 D:\笔记(会话工作区之外),抽象 fs 会先被
8
+ * 沙箱策略拦一道;这里只需要「读一个用户明确授权的目录」,用 node:fs 更直接,
9
+ * 而且这一步只在扫描时发生,不涉及任何写操作。
10
+ *
11
+ * 只读承诺:除了插件目录旁那一个 wiki-notes.config.json(设置页保存库路径用),
12
+ * 这里不写任何文件,更不写知识库本体。
13
+ */
14
+
15
+ import path from 'node:path'
16
+ import { statSync, watch } from 'node:fs'
17
+ import { fileURLToPath } from 'node:url'
18
+
19
+ import { asList, loadCorpus } from './corpus.js'
20
+ import { normalizeTopicConfig, readTopicConfig, writeTopicConfig } from './config.js'
21
+ import { run } from './engine.js'
22
+ import { configPath, DEFAULT_WIKI_ROOT, NOT_CONFIGURED_HINT, readConfigFile, normalizePromptConfig, readPromptConfig, resolveWikiRootInfo, writeConfigFile, writePromptConfig } from './config.js'
23
+
24
+ export const name = 'wiki-notes'
25
+
26
+ /** 工具是主职;webServer 只给设置页用,缺了也还能检索(只是设置页读不到状态)。 */
27
+ export const inject = ['tools', 'webServer', 'systemPrompt']
28
+
29
+ /** 库扫描结果缓存时长:扫描 70 页约 40ms,但同一回合常连着问好几遍。 */
30
+ const CACHE_TTL_MS = 30_000
31
+
32
+ /** 设置页的同源 API 前缀(浏览器半侧 lib/client.js 里写的是同一个值)。 */
33
+ const API_PREFIX = '/api/wiki-notes'
34
+
35
+ /**
36
+ * 工具泛词:它们能出现在任何一页上,对「这个库在研究什么」没有信息量。
37
+ * 命中就跳过,不进主题词候选(打标签不受影响,检索打分照旧用它们)。
38
+ */
39
+ const TOPIC_STOPWORDS = new Set([
40
+ 'meta', 'data', 'tool', 'tools', 'note', 'notes', 'todo', 'other',
41
+ '数据', '工具', '人物', '政策', '方法', '理论', '笔记', '总结', '其他', '杂项',
42
+ '待整理', '待补充', '通用', '综合', '知识', '资料', '内容',
43
+ ])
44
+
45
+ /** 结构页:总览类页面不参与主题词统计。 */
46
+ const STRUCTURAL_PAGE_NAMES = new Set(['overview', '总览', '总览-overview', 'index', 'log'])
47
+ function isStructuralPage(page) {
48
+ if (STRUCTURAL_PAGE_NAMES.has(page.name)) return true
49
+ return String(page.fields['类型'] ?? '') === '总览'
50
+ }
51
+
52
+ function sendJson(res, status, payload) {
53
+ const body = JSON.stringify(payload)
54
+ res.statusCode = status
55
+ res.setHeader('content-type', 'application/json; charset=utf-8')
56
+ res.setHeader('cache-control', 'no-store')
57
+ res.end(body)
58
+ }
59
+
60
+ /** 请求体很小(一个路径字符串),限量读,别让谁塞一个大 body 进来。 */
61
+ function readBody(req, limit = 64 * 1024) {
62
+ return new Promise((resolve, reject) => {
63
+ let size = 0
64
+ const chunks = []
65
+ req.on('data', (chunk) => {
66
+ size += chunk.length
67
+ if (size > limit) {
68
+ reject(new Error('请求体过大'))
69
+ req.destroy()
70
+ return
71
+ }
72
+ chunks.push(chunk)
73
+ })
74
+ req.on('end', () => {
75
+ const text = Buffer.concat(chunks).toString('utf8').trim()
76
+ if (text === '') return resolve(null)
77
+ try {
78
+ resolve(JSON.parse(text))
79
+ } catch {
80
+ resolve(null)
81
+ }
82
+ })
83
+ req.on('error', reject)
84
+ })
85
+ }
86
+
87
+ const PARAMETERS = {
88
+ type: 'object',
89
+ properties: {
90
+ mode: {
91
+ type: 'string',
92
+ enum: ['search', 'page', 'list', 'overview', 'lint', 'draft'],
93
+ description: 'search=关键词检索(默认);page=按页名取整页;list=按类型/标签列目录;overview=库总览与健康状态;lint=全库健康检查(孤儿页/断链/缺字段/别名冲突/久未更新);draft=生成「把好答案回写成新页」的落盘骨架(不写文件)',
94
+ },
95
+ query: {
96
+ type: 'string',
97
+ description: 'mode=search 时的检索词:1-4 个核心名词,空格分隔即 AND。不要传整句问话——先自己把问话拆成名词(「什么是逻辑填空」应传「逻辑填空」)。',
98
+ },
99
+ name: {
100
+ type: 'string',
101
+ description: 'mode=page 时的页面名,例如「上下文工程」。没精确命中会返回候选。',
102
+ },
103
+ type: {
104
+ type: 'string',
105
+ description: '按页面类型筛:概念 / 实体 / 对比 / 综合 / 资料',
106
+ },
107
+ tags: {
108
+ type: 'array',
109
+ items: { type: 'string' },
110
+ description: '按标签筛,任一命中即算;例如 ["AI","方法"]',
111
+ },
112
+ status: {
113
+ type: 'string',
114
+ description: '按状态筛:草稿 / 演进中 / 已提纯',
115
+ },
116
+ limit: {
117
+ type: 'number',
118
+ description: 'search 返回几页,默认 5,最多 12;lint 时表示每组列几条,默认 8。',
119
+ },
120
+ staleDays: {
121
+ type: 'number',
122
+ description: 'mode=lint 时判定「久未更新」的天数,默认 120。',
123
+ },
124
+ title: {
125
+ type: 'string',
126
+ description: 'mode=draft 时新页的名字(不含 .md),例如「上下文预算怎么算」。',
127
+ },
128
+ sources: {
129
+ type: 'number',
130
+ description: 'mode=draft 时写进 frontmatter 的「来源数量」,默认 0。',
131
+ },
132
+ summary: {
133
+ type: 'string',
134
+ description: 'mode=draft 时的一句话摘要,会同时写进正文引言与 index.md 那一行。',
135
+ },
136
+ sectionChars: {
137
+ type: 'number',
138
+ description: 'search 时每页返回的正文上限字符数,默认 900(约 600 token)。答案需要完整段落时调到 1500-2000。',
139
+ },
140
+ pageChars: {
141
+ type: 'number',
142
+ description: 'page 的正文上限字符数,默认 6000;overview 引用总览正文时默认 4000。',
143
+ },
144
+ logLimit: {
145
+ type: 'number',
146
+ description: 'mode=overview 时列最近几条日志,默认 5,最多 20。',
147
+ },
148
+ },
149
+ required: ['mode'],
150
+ }
151
+
152
+ const DESCRIPTION = `本地 LLM-Wiki 知识库检索(只读,不会改动任何文件)。
153
+
154
+ 何时必须调用(命中任一):
155
+ - 问题涉及库内已知线索:页名、别名、标签,或系统提示里注入的主题词;
156
+ - 问个人记录(「我之前怎么记的」「笔记里写了什么」);
157
+ - 考公、行测、申论、政治理论相关;
158
+ - 点名具体工具、框架、模型、项目、论文;
159
+ - 要求引用、转述、核对笔记原文。
160
+
161
+ 何时可以不查:纯通用常识,且根据库索引线索能确认没有对应内容(如「水」「三角形」)。
162
+ 只是没看到线索,不等于库里没有;拿不准先查,别靠自信跳过。
163
+
164
+ mode 用法:
165
+ - search(默认):传 1-4 个关键词,空格分隔做 AND。返回每页的元数据 + index.md 一句话摘要 + **命中小节完整正文** + citation。通常一次调用就够作答,不用再去读文件。
166
+ - page:传页名取整页。没精确命中会返回 5 个候选,挑一个再查。
167
+ - list:按 type / tags / status 列目录,比读 index.md 更省 token。
168
+ - overview:总览正文 + 规模行 + 最近 5 条日志 + 断链统计。
169
+ - lint:全库健康检查(只读)——孤儿页、断链名字、缺 frontmatter 字段、别名冲突、久未更新、无出链、草稿、index.md 与磁盘不一致。用户在整理/维护笔记、或问「库里有什么问题」时用。
170
+ - draft:把本次的好答案回写成新页时,先要一份落盘骨架(目录、frontmatter 七字段、index.md 那一行、log.md 那一条)。本工具只返回文本,写文件要用你自己的写文件工具。
171
+
172
+ 怎么读结果:
173
+ - kind=note 是消化过的笔记(最可信);raw-summary 是原始资料的压缩稿;source 是资料页。
174
+ - sources 是「来源数量」,判断证据强度用:1 份和 12 份不是一回事。
175
+ - status=草稿 的页可能只是骨架。
176
+ - brokenLinks 非空 = 这一节引用了库里不存在的页(红链),说明该处判断缺少页级支撑,转述时要标明。
177
+ - 一条都没命中不代表话题不存在,换同义词(中文/英文/缩写)或先用 list 看目录再搜。`
178
+
179
+ /** 知识层的候选目录名:路径指到上一层时,自动下钻到这些名字。 */
180
+ const DRILL_DIRS = ['知识层-wiki', '知识层', 'wiki', 'Wiki']
181
+
182
+ /**
183
+ * 库路径指错层时的自动纠正。
184
+ *
185
+ * 判据是 index.md:karpathy 原文的架构里,知识层是「LLM 拥有的 markdown 目录」,
186
+ * 它自己带 index.md;而 LLM-Wiki 根只有 AGENTS.md + 原始资料-raw + 这个知识层目录。
187
+ * 所以「自己有 index.md」= 已经是知识层,不再往下找;否则看有没有带 index.md 的子目录。
188
+ */
189
+ function drillTarget(dir) {
190
+ const hasIndex = (target) => {
191
+ try {
192
+ return statSync(path.join(target, 'index.md')).isFile()
193
+ } catch {
194
+ return false
195
+ }
196
+ }
197
+ if (hasIndex(dir)) return ''
198
+ for (const name of DRILL_DIRS) {
199
+ const candidate = path.join(dir, name)
200
+ if (hasIndex(candidate)) return candidate
201
+ }
202
+ return ''
203
+ }
204
+
205
+ export function apply(ctx, config = {}) {
206
+ const pluginRoot = path.dirname(path.dirname(fileURLToPath(import.meta.url)))
207
+ const inlineRoot = typeof config?.root === 'string' ? config.root : ''
208
+
209
+ /** 当前生效的库路径。设置页保存后原地换掉,不用重启插件。 */
210
+ let rootInfo = resolveWikiRootInfo(pluginRoot, inlineRoot)
211
+ let root = rootInfo.root
212
+ /** 提示词那一行:可关、可整段替换、可在末尾追加。存配置文件,改完立即生效。 */
213
+ let promptCfg = normalizePromptConfig(config?.prompt) ?? readPromptConfig(pluginRoot)
214
+ let topicCfg = normalizeTopicConfig(config?.topics) ?? readTopicConfig(pluginRoot)
215
+
216
+ let cache = null
217
+ let cachedAt = 0
218
+ let inflight = null
219
+
220
+ /** 换库 / 重扫时把缓存一起作废,否则设置页说「已切换」,模型那边还在看旧库。 */
221
+ function invalidate() {
222
+ cache = null
223
+ cachedAt = 0
224
+ inflight = null
225
+ }
226
+
227
+ /* ---------------------- 目录监听:库是活的 ---------------------- */
228
+ // 有 30 秒缓存兜底就够了,但「刚改完笔记,模型还在念旧版本」很容易让人以为插件坏了。
229
+ // 监听只做一件事:发现 .md 变了就作废缓存,下次查询重扫(70 页约 40ms,重扫不心疼)。
230
+
231
+ let watcher = null
232
+ let watchTimer = null
233
+ /** 'on' 实时同步生效;'off' 退回 30 秒缓存。设置页要显示这个 —— 否则实时同步悄悄失效了没人知道。 */
234
+ let watchState = 'off'
235
+
236
+ function stopWatch() {
237
+ watchState = 'off'
238
+ if (watchTimer !== null) {
239
+ clearTimeout(watchTimer)
240
+ watchTimer = null
241
+ }
242
+ if (watcher !== null) {
243
+ try {
244
+ watcher.close()
245
+ } catch {
246
+ // 关不掉就算了,进程退出时会一起没
247
+ }
248
+ watcher = null
249
+ }
250
+ }
251
+
252
+ function startWatch() {
253
+ stopWatch()
254
+ // 还没配置库路径时没什么可监听的,等用户在设置页存了再说
255
+ if (root === '') return
256
+ // 监听的必须是真正在读的那一层:路径指错层时 getCorpus 会下钻,监听上层等于永远收不到事件
257
+ const watchRoot = drillTarget(root) || root
258
+ let handle
259
+ try {
260
+ handle = watch(watchRoot, { recursive: true }, (_event, filename) => {
261
+ const name = String(filename ?? '')
262
+ // 只认笔记:编辑器保存时会带出 .swp/.tmp/xxx.md~ 之类的临时文件,别为它们重扫整库
263
+ if (name !== '' && !/\.md$/i.test(name)) return
264
+ if (/[~#]$|\.(swp|tmp|bak)$/i.test(name)) return
265
+ // 一次保存常常触发多个事件,攒 400ms 再作废
266
+ if (watchTimer !== null) clearTimeout(watchTimer)
267
+ watchTimer = setTimeout(() => {
268
+ watchTimer = null
269
+ invalidate()
270
+ }, 400)
271
+ })
272
+ } catch (error) {
273
+ ctx.logger?.warn?.(`LLM-Wiki 检索:监听不了 ${root}(${String(error?.message ?? error)}),退回 30 秒缓存`)
274
+ return
275
+ }
276
+ handle.on?.('error', () => {
277
+ // 被监听目录消失(比如换了 D 盘盘符)时不炸,让缓存策略继续兜底
278
+ stopWatch()
279
+ })
280
+ // 别让监听句柄把进程钉住:CLI 与测试脚本跑完要能正常退出,DSH 进程本身就常驻。
281
+ handle.unref?.()
282
+ watcher = handle
283
+ watchState = 'on'
284
+ }
285
+
286
+ startWatch()
287
+
288
+
289
+ /** 库路径指错层时的自动纠正(详见 drillTarget)。 */
290
+ let scannedRoot = ''
291
+
292
+ /* --------- 主题词:让模型自己判断「这问题该不该查库」 --------- */
293
+ // 工具描述里写「任何主题」等于没有触发条件。这里从库里现有标签算出主题,
294
+ // 注入一行(约 60 token),换库自动变 —— 不用把某一批领域词写死进公开仓库。
295
+
296
+ let topicLine = ''
297
+ /** 设置页要显示的那份(主题词 + 出现次数),与 topicLine 同源。 */
298
+ let topicTags = []
299
+ /** 阈值这次没生效(所有标签都低于阈值)时为 true,设置页据此提示。 */
300
+ let topicFilterFallback = false
301
+
302
+ /**
303
+ * 主题词:从标签频次算「这个库在研究什么」,注入给模型当触发器。
304
+ *
305
+ * 三道过滤,都是为了「代表性」而不是「覆盖全部」:
306
+ * 1. 结构页(总览/overview)不参与 —— 它们的 meta 之类标签没有主题含义
307
+ * 2. 只留出现 ≥ minCount 次的标签 —— 一次性专有名词进不了前五
308
+ * 3. 跳过工具泛词 —— 「数据」「工具」这种哪篇都能打,进前五等于噪音
309
+ * 全部被滤掉时退回未过滤的前五(小库不至于一条提示都没有)。
310
+ */
311
+ function refreshTopics(corpus) {
312
+ // 按小写归并:`RAG` 和 `rag` 是同一个主题,分开数会让两边都掉到阈值以下。
313
+ // 展示时用出现次数最多的那种写法(一样多就取码点靠前的),保证稳定的可读形式。
314
+ const counts = new Map()
315
+ for (const page of corpus.pages) {
316
+ if (isStructuralPage(page)) continue
317
+ for (const tag of asList(page.fields['标签'])) {
318
+ const form = tag.trim()
319
+ if (form === '') continue
320
+ const key = form.toLowerCase()
321
+ if (topicCfg.stopwords && TOPIC_STOPWORDS.has(key)) continue
322
+ let entry = counts.get(key)
323
+ if (entry === undefined) {
324
+ entry = { key, count: 0, forms: new Map() }
325
+ counts.set(key, entry)
326
+ }
327
+ entry.count += 1
328
+ entry.forms.set(form, (entry.forms.get(form) ?? 0) + 1)
329
+ }
330
+ }
331
+ const label = (entry) => {
332
+ let best = entry.key
333
+ let bestCount = -1
334
+ for (const [form, n] of entry.forms) {
335
+ if (n > bestCount || (n === bestCount && form < best)) {
336
+ best = form
337
+ bestCount = n
338
+ }
339
+ }
340
+ return best
341
+ }
342
+ const ranked = [...counts.values()]
343
+ .map((entry) => ({ tag: label(entry), count: entry.count, key: entry.key }))
344
+ .sort((a, b) => b.count - a.count || (a.key < b.key ? -1 : 1))
345
+ const kept = ranked.filter((item) => item.count >= topicCfg.minCount)
346
+ // 保底:过滤太狠(比如整个库只有一两页)就退回不过滤,别让模型完全失去线索。
347
+ // 这时阈值其实没生效,要如实告诉设置页,别让人以为勾选框失灵了。
348
+ topicFilterFallback = kept.length === 0 && ranked.length > 0
349
+ const pool = kept.length > 0 ? kept : ranked
350
+ const top = pool.slice(0, 5).map((item) => item.tag)
351
+ topicTags = pool.slice(0, 8).map((item) => ({ tag: item.tag, count: item.count }))
352
+ // 不写页数:它对「该不该查库」这个判断没有贡献,页数一变还会打掉 systemPrompt 的前缀缓存。
353
+ // 触发靠的是主题词那半句,页数只给人看 —— 给人看的地方是设置页,不是这里。
354
+ topicLine = top.length === 0
355
+ ? ''
356
+ : `本地知识库主题:${top.join('、')}。问题沾这些主题、或要引用笔记原文时,先调用 wiki_recall 查库再作答。`
357
+ }
358
+
359
+ /** 最终注入的那段文本:关掉 → 空;有 override → 用它;否则用自动算的主题词;最后追加 extra。 */
360
+ function buildTopicText() {
361
+ if (promptCfg.enabled !== true) return ''
362
+ const body = promptCfg.override !== '' ? promptCfg.override : topicLine
363
+ if (body === '') return promptCfg.extra
364
+ return promptCfg.extra === '' ? body : `${body}\n${promptCfg.extra}`
365
+ }
366
+
367
+ async function getCorpus() {
368
+ // 没配库路径就直接说清楚。别让它扫出一个空库 —— 模型会把「0 页」当成
369
+ // 「你笔记里没有这条」,然后自信地给你编答案。
370
+ if (root === '') throw new Error(NOT_CONFIGURED_HINT)
371
+ const now = Date.now()
372
+ if (cache !== null && now - cachedAt < CACHE_TTL_MS) return cache
373
+ if (inflight !== null) return inflight
374
+ inflight = (async () => {
375
+ // 用户很容易把路径指到 LLM-Wiki 根(那里有 AGENTS.md、raw 与模板),
376
+ // 扫出来数字虚高、还混进不该读的原始资料。这里自动下钻到真正的知识层。
377
+ const drilled = drillTarget(root)
378
+ const target = drilled === '' ? root : drilled
379
+ const corpus = await loadCorpus(target)
380
+ if (target !== root) corpus.drilledFrom = root
381
+ scannedRoot = target
382
+ refreshTopics(corpus)
383
+ cache = corpus
384
+ cachedAt = Date.now()
385
+ return corpus
386
+ })().finally(() => {
387
+ inflight = null
388
+ })
389
+ return inflight
390
+ }
391
+
392
+ // 启动时探一次库:路径写错的话,日志里会立刻出现,而不是等模型调用时才失败。
393
+ getCorpus()
394
+ .then((corpus) => {
395
+ ctx.logger?.info?.(
396
+ `LLM-Wiki 检索就绪:${corpus.stats.pages} 页 / ${corpus.stats.resources} 份资料 / ${corpus.stats.brokenPages} 页存在红链(${root})`,
397
+ )
398
+ })
399
+ .catch((error) => {
400
+ ctx.logger?.warn?.(`LLM-Wiki 检索:打不开知识库 ${root} —— ${String(error && error.message || error)}`)
401
+ })
402
+
403
+ /* --------------------------- 设置页 API --------------------------- */
404
+ // 与浏览器半侧只走同源 HTTP:不碰 RPC,就没有「connection 服务缺失」这类降级分支。
405
+
406
+ function statsOf(corpus) {
407
+ const stats = corpus?.stats ?? {}
408
+ return {
409
+ pages: stats.pages ?? 0,
410
+ resources: stats.resources ?? 0,
411
+ brokenPages: stats.brokenPages ?? 0,
412
+ brokenTotal: stats.brokenTotal ?? 0,
413
+ scannedMs: stats.scannedMs ?? 0,
414
+ }
415
+ }
416
+
417
+ function baseState() {
418
+ return {
419
+ root,
420
+ source: rootInfo.source,
421
+ sourceLabel: rootInfo.label,
422
+ defaultRoot: DEFAULT_WIKI_ROOT,
423
+ envRoot: typeof process.env.DSH_WIKI_ROOT === 'string' ? process.env.DSH_WIKI_ROOT : '',
424
+ configFile: configPath(pluginRoot),
425
+ savedRoot: readConfigFile(pluginRoot),
426
+ // 与 root 不同时说明路径指错层、被自动下钻了 —— 设置页要能显示这一点
427
+ scannedRoot,
428
+ watch: watchState,
429
+ topics: topicTags,
430
+ prompt: promptCfg,
431
+ // fallback = 阈值这次没生效(所有标签都低于阈值,退回不过滤),设置页要提示
432
+ topicFilter: { ...topicCfg, fallback: topicFilterFallback },
433
+ topicPreview: buildTopicText(),
434
+ }
435
+ }
436
+
437
+ async function buildState() {
438
+ try {
439
+ const corpus = await getCorpus()
440
+ return { ...baseState(), ok: true, stats: statsOf(corpus), scale: corpus.scaleLine ?? '' }
441
+ } catch (error) {
442
+ return { ...baseState(), ok: false, error: String(error?.message ?? error) }
443
+ }
444
+ }
445
+
446
+ /** 试扫一个候选路径但不改配置:让用户在按「保存」之前就知道这条路通不通。 */
447
+ async function probeRoot(candidate) {
448
+ const started = Date.now()
449
+ const target = String(candidate ?? '').trim() || root
450
+ if (target === '') return { ok: false, root: '', ms: Date.now() - started, error: NOT_CONFIGURED_HINT }
451
+ try {
452
+ const corpus = await loadCorpus(target)
453
+ const stats = statsOf(corpus)
454
+ if (stats.pages === 0) {
455
+ return { ok: false, root: target, ms: Date.now() - started, error: '这个目录里没有任何页面(可能是路径写错了,或指到了上一层的 LLM-Wiki 根)' }
456
+ }
457
+ // 指到上一层时也能扫出东西(把 raw 与模板一起数进来),但数字会失真:给个明确提示。
458
+ let hint = ''
459
+ try {
460
+ if (path.basename(target) !== '知识层-wiki' && statSync(path.join(target, '知识层-wiki')).isDirectory()) {
461
+ hint = `这个目录下面还有「知识层-wiki」,那才是知识库本体(这里扫到的是 ${stats.pages} 页,含原始资料与模板)`
462
+ }
463
+ } catch {
464
+ // 没有子目录就算了,不是错误
465
+ }
466
+ return { ok: true, root: target, ms: Date.now() - started, stats, scale: corpus.scaleLine ?? '', hint }
467
+ } catch (error) {
468
+ return { ok: false, root: target, ms: Date.now() - started, error: String(error?.message ?? error) }
469
+ }
470
+ }
471
+
472
+ // 路由是「组合级契约」:同名前缀第二次注册会抛 duplicate。所以必须自己保存 disposer,
473
+ // 卸载时释放 —— 否则热重载一次(关掉再打开插件)就会永久占着这个前缀。
474
+ let disposeApi = null
475
+ try {
476
+ disposeApi = ctx.webServer?.register?.({
477
+ kind: 'prefix',
478
+ path: API_PREFIX,
479
+ handler: async (req, res) => {
480
+ const route = (req.url ?? '').split('?')[0].slice(API_PREFIX.length) || '/'
481
+ try {
482
+ if (route === '/state' && req.method === 'GET') {
483
+ return sendJson(res, 200, await buildState())
484
+ }
485
+ if (route === '/check' && req.method === 'POST') {
486
+ const body = await readBody(req)
487
+ return sendJson(res, 200, await probeRoot(body?.root))
488
+ }
489
+ if (route === '/save' && req.method === 'POST') {
490
+ const body = await readBody(req)
491
+ const typed = typeof body?.root === 'string' ? body.root.trim() : ''
492
+ // 统一存成绝对路径(用户可能写成正斜杠或相对路径),空串 = 清配置回到上一层
493
+ const next = typed === '' ? '' : path.resolve(typed)
494
+ // 先试扫再落盘:打错一个字符就把坏路径写进配置文件,等于让整个插件查不到库,
495
+ // 用户还得再存一次才能救回来。扫不出页面就拒绝保存,配置保持原样。
496
+ if (next !== '') {
497
+ const probe = await probeRoot(next)
498
+ if (probe.ok !== true) {
499
+ return sendJson(res, 200, { ok: false, saved: false, error: probe.error || '这个路径扫不出页面' })
500
+ }
501
+ }
502
+ writeConfigFile(pluginRoot, next)
503
+ rootInfo = resolveWikiRootInfo(pluginRoot, inlineRoot)
504
+ root = rootInfo.root
505
+ invalidate()
506
+ startWatch()
507
+ return sendJson(res, 200, await buildState())
508
+ }
509
+ if (route === '/topics' && req.method === 'POST') {
510
+ const body = await readBody(req)
511
+ topicCfg = writeTopicConfig(pluginRoot, body).config
512
+ invalidate()
513
+ sendJson(res, 200, await buildState())
514
+ return
515
+ }
516
+ if (route === '/prompt' && req.method === 'POST') {
517
+ const body = await readBody(req)
518
+ promptCfg = writePromptConfig(pluginRoot, {
519
+ enabled: body?.enabled !== false,
520
+ override: typeof body?.override === 'string' ? body.override : '',
521
+ extra: typeof body?.extra === 'string' ? body.extra : '',
522
+ }).config
523
+ // 不用 invalidate():提示词和语料无关,下一回合读 text() 就是新值
524
+ return sendJson(res, 200, await buildState())
525
+ }
526
+ if (route === '/rescan' && req.method === 'POST') {
527
+ invalidate()
528
+ return sendJson(res, 200, await buildState())
529
+ }
530
+ return sendJson(res, 404, { error: `未知路由 ${route}` })
531
+ } catch (error) {
532
+ return sendJson(res, 500, { error: String(error?.message ?? error) })
533
+ }
534
+ },
535
+ })
536
+ } catch (error) {
537
+ const message = String(error?.message ?? error)
538
+ // 幂等保护:loader 重放装配时同名 route 会撞 duplicate,跳过 API 而不是让整个插件不激活。
539
+ if (!message.includes('duplicate')) throw error
540
+ ctx.logger?.warn?.(`[wiki-notes] ${API_PREFIX} 已被注册过,跳过重复注册`)
541
+ }
542
+
543
+ // 主题词注入:一行、同步、读完即用。库没配好时返回空串,不占上下文。
544
+ try {
545
+ ctx.systemPrompt?.context?.({
546
+ name: 'wiki-notes:topics',
547
+ order: 240,
548
+ text: () => buildTopicText(),
549
+ })
550
+ } catch (error) {
551
+ ctx.logger?.warn?.(`[wiki-notes] 主题提示注册失败:${String(error?.message ?? error)}`)
552
+ }
553
+
554
+ const register = () => ctx.tools.register({
555
+ name: 'wiki_recall',
556
+ description: DESCRIPTION,
557
+ parameters: PARAMETERS,
558
+ output: {
559
+ schema: { type: 'object', additionalProperties: true },
560
+ render: (args, value) => [{ type: 'text', text: renderValue(args, value) }],
561
+ },
562
+ async execute(args) {
563
+ const started = Date.now()
564
+ try {
565
+ const corpus = await getCorpus()
566
+ const result = run(corpus, args ?? {})
567
+ if (result !== null && typeof result === 'object') {
568
+ result.scanned = corpus.stats.pages
569
+ result.root = root
570
+ if (typeof corpus.drilledFrom === 'string') result.drilledFrom = corpus.drilledFrom
571
+ result.ms = Date.now() - started
572
+ }
573
+ return result ?? { mode: 'error', error: '查询没有返回结果(mode 可能传错了)' }
574
+ } catch (error) {
575
+ // 工具层不往上抛:把「库读不出来」变成一条模型看得懂、能转告用户的错误,
576
+ // 而不是一次工具调用失败。库里 0 页和库里没有这个词,是两回事。
577
+ // 这里只剩两类:没配路径(用户该去设置页),以及真正的程序异常(该转告)。
578
+ // 文件系统层面的「能扫但不全」已经在 corpus.stats 里记过,不会走到这儿。
579
+ return {
580
+ mode: 'error',
581
+ status: root === '' ? 'unconfigured' : 'error',
582
+ error: String((error && error.message) || error),
583
+ }
584
+ }
585
+ },
586
+ })
587
+
588
+ let dispose
589
+ try {
590
+ dispose = register()
591
+ } catch (error) {
592
+ ctx.logger?.warn?.(`LLM-Wiki 检索:注册工具失败 —— ${String(error && error.message || error)}`)
593
+ stopWatch()
594
+ return
595
+ }
596
+
597
+ ctx.on?.('dispose', () => {
598
+ stopWatch()
599
+ try {
600
+ disposeApi?.()
601
+ } catch {
602
+ // 卸载时失败无所谓
603
+ }
604
+ try {
605
+ dispose?.()
606
+ } catch {
607
+ // 同上
608
+ }
609
+ })
610
+ }
611
+
612
+ /* ------------------------------- 渲染 ------------------------------- */
613
+
614
+ function renderValue(args, value) {
615
+ if (value === null || typeof value !== 'object') return String(value)
616
+ if (typeof value.error === 'string') {
617
+ // 三种「没查成」要说成三件事:参数写错了、库没配、程序出错。
618
+ // 前两种都不该让模型怀疑「你笔记里没有这条」。
619
+ if (value.status === 'invalid_input') {
620
+ return `参数不对:${value.error}\n(这次没有读取知识库,改好参数再调一次。)`
621
+ }
622
+ if (value.status === 'unconfigured') return `知识库还没配置:${value.error}`
623
+ return `查询失败:${value.error}`
624
+ }
625
+ let body
626
+ switch (value.mode) {
627
+ case 'search':
628
+ body = renderSearch(value)
629
+ break
630
+ case 'page':
631
+ body = renderPage(value)
632
+ break
633
+ case 'list':
634
+ body = renderList(value)
635
+ break
636
+ case 'overview':
637
+ body = renderOverview(value)
638
+ break
639
+ case 'lint':
640
+ body = renderLint(value)
641
+ break
642
+ case 'draft':
643
+ body = renderDraft(value)
644
+ break
645
+ default:
646
+ body = JSON.stringify(value, null, 2)
647
+ }
648
+ // 路径指错层被自动纠正时,必须让模型知道它看的不是配置里那个目录
649
+ // 顺手把连续空行压成一行:模型读的是这段文本,连着的空行纯属白付 token
650
+ const tidy = body.replace(/\n{3,}/g, '\n\n')
651
+ // 覆盖缺口放最前面:先说「你看到的不是全部」,再给结果。
652
+ // 唯一例外是 search 扫到 0 页 —— 正文里已经把那句话讲清楚了,不必重复。
653
+ const duplicated = value.status === 'unavailable' && value.mode === 'search'
654
+ const warned = Array.isArray(value.warnings) && value.warnings.length > 0 && !duplicated
655
+ ? `⚠ 本次结果有缺口:\n${value.warnings.map((line) => `· ${line}`).join('\n')}\n\n`
656
+ : ''
657
+ const withWarnings = `${warned}${tidy}`
658
+ return value.drilledFrom
659
+ ? `(库路径已自动下钻到知识层:${value.drilledFrom})\n${withWarnings}`
660
+ : withWarnings
661
+ }
662
+
663
+ /** lint 的渲染:按「该修的地方」分组,每组只说名字,不贴正文。 */
664
+ function renderLint(value) {
665
+ const stats = value.stats || {}
666
+ const counts = value.counts || {}
667
+ const lines = [
668
+ `库健康检查(只读)· ${stats.pages ?? 0} 页 · ${stats.resources ?? 0} 份资料 · 扫描 ${stats.scannedMs ?? 0} ms`,
669
+ ]
670
+
671
+ const block = (title, total, rows, format) => {
672
+ if (!total) return
673
+ lines.push('')
674
+ lines.push(`${title}(${total})`)
675
+ for (const row of rows ?? []) lines.push(' · ' + format(row))
676
+ if (total > (rows ?? []).length) lines.push(` …还有 ${total - rows.length} 个`)
677
+ }
678
+
679
+ block('🕳 孤儿页 —— 没有任何页链到它', counts.orphans, value.orphans, (name) => name)
680
+ block('🔗 断链 —— 被提到、但库里没有这页', counts.broken, value.brokenTargets, (row) => `${row.name} × ${row.pages} 页`)
681
+ block('🧩 缺 frontmatter 字段', counts.missingFields, value.missingFields, (row) => `${row.name}:缺 ${row.missing.join('、')}`)
682
+ block('🏷 别名冲突 —— 同一别名挂在多页,检索排序会漂', counts.aliasConflicts, value.aliasConflicts, (row) => `${row.alias} → ${row.pages.join(' / ')}`)
683
+ block(`⏳ 久未更新(> ${value.staleDays} 天)`, counts.stale, value.stale, (row) => `${row.name}(${row.updated},${row.days} 天前)`)
684
+ block('🚪 无出链 —— 正文里没有任何 [[双链]]', counts.noLinks, value.noLinks, (name) => name)
685
+ block('📝 草稿状态', counts.drafts, value.drafts, (name) => name)
686
+ block('📇 index.md 登记了、磁盘上没有', counts.indexOnly, value.consistency?.indexOnly, (name) => name)
687
+ block('📥 磁盘上有、index.md 没登记', counts.diskOnly, value.consistency?.diskOnly, (name) => name)
688
+ block('📦 未读入的大文件(> 512KB,只记了名字)', counts.oversized, value.oversized, (name) => name)
689
+
690
+ if (Object.values(counts).every((n) => !n)) lines.push('', '没有发现问题。')
691
+ lines.push('', '(页面间矛盾、被新资料推翻的旧结论要读内容才能判断,不在这里报。)')
692
+ return lines.join('\n')
693
+ }
694
+
695
+ /** draft 的渲染:要能整段复制去落盘,所以顺序是「未落盘声明 → 文件 → 内容 → 三件收尾」。 */
696
+ function renderDraft(value) {
697
+ const out = []
698
+ // 最重要的事实放第一行:模型会截断、摘要或转述,末尾的说明最先被省掉
699
+ out.push('⚠ 以下内容仅为待审阅草稿,尚未写入任何文件。')
700
+ out.push('')
701
+ const warn = value.exists === null
702
+ ? ''
703
+ : `(⚠ 已有同名页 ${value.exists.file},直接写会覆盖它 —— 换个名字,或确认就是要改那一页)`
704
+ out.push(`回写骨架:${value.file}${warn}`)
705
+ out.push('')
706
+ out.push(value.frontmatter)
707
+ out.push('')
708
+ out.push(value.body)
709
+ out.push('')
710
+ out.push('落盘后还有三件事,少一件这页就等于没进库:')
711
+ out.push(`1. index.md 里与其它「${value.type}」页同一节,加一行:`)
712
+ out.push(` ${value.indexLine}`)
713
+ out.push('2. log.md 末尾追加一条:')
714
+ out.push(` ${value.logLine}`)
715
+ out.push('3. 再跑一次 mode:"lint" 复查(这页还挂着红链会被报出来)')
716
+ return out.join('\n')
717
+ }
718
+
719
+ const KIND_LABEL = { note: '笔记', 'raw-summary': '资料摘要', source: '资料页' }
720
+
721
+ function metaLine(hit) {
722
+ const parts = []
723
+ if (hit.type) parts.push(hit.type)
724
+ if (hit.status) parts.push(hit.status)
725
+ if (hit.sources !== null && hit.sources !== undefined) parts.push(`${hit.sources} 源`)
726
+ if (hit.updated) parts.push(hit.updated)
727
+ if (hit.kind && KIND_LABEL[hit.kind]) parts.push(KIND_LABEL[hit.kind])
728
+ return parts.join(' · ')
729
+ }
730
+
731
+ /** 去掉正文开头与页名重复的 `# 页名`,省一行 token。 */
732
+ function stripLeadingH1(text, name) {
733
+ // 正文常以空行开头(frontmatter 之后),先吃掉空行,首行才轮得到标题
734
+ const value = String(text ?? '').replace(/^\s*\n+/, '')
735
+ const lines = value.split('\n')
736
+ if (lines.length === 0) return value
737
+ const first = lines[0].trim()
738
+ if (first === `# ${name}` || first === `# ${name.replace(/\.md$/, '')}`) {
739
+ return lines.slice(1).join('\n').replace(/^\s*\n/, '')
740
+ }
741
+ return value
742
+ }
743
+
744
+ function renderSearch(value) {
745
+ const out = []
746
+ const tokens = Array.isArray(value.tokens) ? value.tokens.join(' + ') : ''
747
+ const scanned = value.scanned ?? 0
748
+ // 分母要摊开写:扫描了多少、过滤后真正参与打分的多少、命中多少、最后返回几条。
749
+ // 只写「扫描 341 页,5 命中」会让人以为 341 页正文都比过了。
750
+ const numbers = Number.isFinite(value.considered)
751
+ ? `扫描 ${scanned} · 参与 ${value.considered} · 命中 ${value.matched ?? value.total}` +
752
+ `${Number.isFinite(value.allTerms) ? `(全词 ${value.allTerms})` : ''}· 返回 ${value.returned ?? 0}`
753
+ : `扫描 ${scanned} 页,${value.total} 命中`
754
+ out.push(`【检索】${tokens} ${numbers}`)
755
+ // 降级说明已由 warnings 承载(degraded 时必有一条);只有老调用方(结果里没有 status 字段)
756
+ // 才需要这里的 note —— 否则同一句话模型会读两遍。
757
+ if (value.note && value.status === undefined) out.push(`⚠️ ${value.note}`)
758
+
759
+ const hits = Array.isArray(value.hits) ? value.hits : []
760
+ if (hits.length === 0) {
761
+ out.push('')
762
+ if (scanned === 0) {
763
+ // 扫到 0 页几乎一定是路径问题,别让模型得出「你笔记里没有这条」的结论
764
+ out.push(`库路径可能不对:这次扫描到 0 个页面(${value.root ?? '路径未配置'})。`)
765
+ out.push('请确认「设置 → 知识库」指向的是放着 .md 笔记的目录,而不是它的上级。')
766
+ } else {
767
+ const gap = Number.isFinite(value.oversizedRelevant) && value.oversizedRelevant > 0
768
+ ? `,另有 ${value.oversizedRelevant} 个超大页只比了标题与 index 摘要`
769
+ : ''
770
+ // no_match 只说「当前可检索范围未命中」,不说「全库没有」——
771
+ // 超大页的正文从来没读过,标题和摘要不沾边也推不出正文不沾边。
772
+ out.push(`当前可检索范围内没有命中:已比对 ${value.considered ?? scanned} 页的内容${gap}。`)
773
+ out.push('这只说明参与比对的页面里没有,不能反推全库没有。')
774
+ out.push('换同义词(中文/英文/缩写)再试,或用 mode:"list" 看有哪些页。')
775
+ }
776
+ return out.join('\n')
777
+ }
778
+
779
+ hits.forEach((hit, index) => {
780
+ out.push('')
781
+ out.push(`${index + 1}. ${hit.name} ⟨${metaLine(hit)}⟩ ${hit.score} 分`)
782
+ if (hit.summary) out.push(` 摘要:${hit.summary}`)
783
+ else if (hit.gist) out.push(` 要点:${hit.gist}`)
784
+ if (hit.section && hit.section.text) {
785
+ const body = stripLeadingH1(hit.section.text, hit.name)
786
+ if (hit.section.title) out.push(` §${hit.section.title}`)
787
+ out.push(body)
788
+ }
789
+ if (Array.isArray(hit.brokenLinks) && hit.brokenLinks.length > 0) {
790
+ out.push(` ⚠️ 红链:${hit.brokenLinks.slice(0, 6).join('、')}(库里没有这些页)`)
791
+ }
792
+ out.push(` 引用:${hit.citation}`)
793
+ })
794
+ return out.join('\n')
795
+ }
796
+
797
+ function renderPage(value) {
798
+ const out = []
799
+ if (value.found === null || value.found === undefined) {
800
+ out.push(`没有精确命中「${value.wanted ?? ''}」。${value.note ?? ''}`)
801
+ const candidates = Array.isArray(value.candidates) ? value.candidates : []
802
+ if (candidates.length > 0) {
803
+ out.push('')
804
+ for (const item of candidates) {
805
+ out.push(`- ${item.name} ⟨${item.type || '?'} · ${item.updated || '?'}⟩${item.summary ? ` ${item.summary}` : ''}`)
806
+ }
807
+ out.push('')
808
+ out.push('把上面某个名字当 name 再查一次。')
809
+ }
810
+ return out.join('\n')
811
+ }
812
+ const page = value.found
813
+ out.push(`【${page.name}】⟨${metaLine(page)}⟩`)
814
+ if (page.summary) out.push(`摘要:${page.summary}`)
815
+ if (Array.isArray(page.aliases) && page.aliases.length > 0) out.push(`别名:${page.aliases.join(' / ')}`)
816
+ if (Array.isArray(page.sections) && page.sections.length > 0) out.push(`小节:${page.sections.join(' / ')}`)
817
+ out.push('')
818
+ // 正文首尾的空行由 render 自己掌握:不然「正文 + 截断提示」之间会挤出两个空行
819
+ out.push(stripLeadingH1(page.body, page.name).replace(/\s+$/, ''))
820
+ if (page.truncated) out.push('', `…(正文已截断,全文 ${page.file})`)
821
+ out.push('', `引用:${page.citation}`)
822
+ return out.join('\n')
823
+ }
824
+
825
+ function renderList(value) {
826
+ const out = []
827
+ const byType = value.byType && typeof value.byType === 'object'
828
+ ? Object.entries(value.byType).map(([type, count]) => `${type} ${count}`).join(' / ')
829
+ : ''
830
+ out.push(`【目录】${value.total} 页${byType ? ` (${byType})` : ''}`)
831
+ if (value.scale) out.push(`规模:${value.scale}`)
832
+ const rows = Array.isArray(value.rows) ? value.rows : []
833
+ for (const row of rows) {
834
+ const meta = [row.type, row.status, row.sources === null ? '' : `${row.sources} 源`, row.updated]
835
+ .filter((part) => part !== '' && part !== null && part !== undefined)
836
+ .join(' · ')
837
+ out.push(`- ${row.name} ⟨${meta}⟩${row.summary ? ` ${row.summary}` : ''}`)
838
+ }
839
+ if (value.truncated === true) {
840
+ out.push(`…(只显示前 ${value.shown} 条,加 limit 或按 type/tags 收窄)`)
841
+ }
842
+ return out.join('\n')
843
+ }
844
+
845
+ function renderOverview(value) {
846
+ const out = []
847
+ out.push('【库总览】')
848
+ if (value.scale) out.push(`规模:${value.scale}`)
849
+ const stats = value.stats ?? {}
850
+ const oversizedCount = Number(stats.oversized ?? 0)
851
+ out.push(`扫描:${stats.pages ?? '?'} 页 / ${stats.resources ?? '?'} 份资料 / ${stats.brokenPages ?? 0} 页有红链(共 ${stats.brokenTotal ?? 0} 处)${oversizedCount > 0 ? ` / ${oversizedCount} 页超大未读正文` : ''}`)
852
+
853
+ const consistency = value.consistency ?? {}
854
+ if ((consistency.indexOnlyTotal ?? 0) > 0) {
855
+ out.push(`⚠️ index.md 登记了但磁盘上没有:${consistency.indexOnly.join('、')}${consistency.indexOnlyTotal > consistency.indexOnly.length ? ` …共 ${consistency.indexOnlyTotal} 条` : ''}`)
856
+ }
857
+ if ((consistency.diskOnlyTotal ?? 0) > 0) {
858
+ out.push(`⚠️ 磁盘上有但没进 index.md:${consistency.diskOnly.join('、')}${consistency.diskOnlyTotal > consistency.diskOnly.length ? ` …共 ${consistency.diskOnlyTotal} 条` : ''}`)
859
+ }
860
+ const dupNames = Array.isArray(stats.duplicateNames) ? stats.duplicateNames : []
861
+ if (dupNames.length > 0) {
862
+ out.push(`⚠️ 重名页(只保留最后一个,其余查不到):${dupNames.slice(0, 6).map((item) => `${item.name}(${item.file})`).join('、')}`)
863
+ }
864
+
865
+ if (value.overview !== null && value.overview !== undefined) {
866
+ out.push('')
867
+ out.push(`━━ ${value.overview.name} ━━`)
868
+ out.push(stripLeadingH1(value.overview.body, value.overview.name).replace(/\s+$/, ''))
869
+ out.push('', `引用:${value.overview.citation}`)
870
+ }
871
+
872
+ const log = Array.isArray(value.recentLog) ? value.recentLog : []
873
+ if (log.length > 0) {
874
+ out.push('')
875
+ out.push('最近日志:')
876
+ for (const entry of log) out.push(`- [${entry.date}] ${entry.type} | ${entry.title}`)
877
+ }
878
+
879
+ const broken = Array.isArray(value.broken) ? value.broken : []
880
+ if (broken.length > 0) {
881
+ out.push('')
882
+ out.push('红链(正文指向不存在的页):')
883
+ for (const item of broken) out.push(`- ${item.name} → ${item.missing.slice(0, 5).join('、')}`)
884
+ }
885
+ return out.join('\n')
886
+ }