@wagq/dsh-obsidian 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/index.js ADDED
@@ -0,0 +1,931 @@
1
+ /**
2
+ * @wagq/dsh-obsidian — Host 半端
3
+ *
4
+ * 面向「知识库」工作区:索引整个 Obsidian vault,提供
5
+ * - 文件库树(文件夹 / 笔记 / PDF / 图片 / 其它文件,按类型筛选)
6
+ * - 笔记详情(正文、frontmatter、标签、大纲、字数、链接与反链)
7
+ * - 全文检索、标签聚合、关联笔记
8
+ * - 写入 / 新建 / 重命名 / 删除(.trash)/ 建文件夹
9
+ * - 与左侧栏同一套能力的 kb_* 对话工具
10
+ *
11
+ * 纯 node:fs 实现,零外部依赖;路径越界防护;不触碰 .obsidian/
12
+ */
13
+ import { readFile, readdir, writeFile, mkdir, rename, stat, copyFile, rm } from 'node:fs/promises'
14
+ import { readFileSync } from 'node:fs'
15
+ import path from 'node:path'
16
+ import { homedir } from 'node:os'
17
+ import z from '@deepseek-ai/schemastery'
18
+
19
+ export const name = '@wagq/dsh-obsidian'
20
+ export const inject = ['webServer', 'tools']
21
+
22
+ export const Config = z.object({
23
+ vaultPath: z.string().default('').description('Obsidian vault 绝对路径;留空则自动检测 obsidian.json 中打开的 vault'),
24
+ })
25
+
26
+ const PREFIX = '/kb'
27
+ const API = `${PREFIX}/api`
28
+ const EXCLUDE = new Set(['.obsidian', '.git', '.trash', 'node_modules', '.DS_Store'])
29
+ /** 隐藏目录一律不索引(.obsidian / .trash / .git / .claudian 等) */
30
+ const isIgnoredDir = name => EXCLUDE.has(name) || name.startsWith('.')
31
+ const MAX_FILE = 4 * 1024 * 1024
32
+
33
+ const IMAGE_EXT = new Set(['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'bmp', 'avif'])
34
+ const NOTE_EXT = new Set(['md', 'markdown'])
35
+
36
+ let config = { vaultPath: '' }
37
+ let vaultRoot = null
38
+ let vaultError = ''
39
+
40
+ function detectFromObsidianConfig() {
41
+ const home = homedir()
42
+ const candidates = [
43
+ process.env.APPDATA ? path.join(process.env.APPDATA, 'obsidian', 'obsidian.json') : '',
44
+ path.join(home, 'Library', 'Application Support', 'obsidian', 'obsidian.json'),
45
+ path.join(home, '.config', 'obsidian', 'obsidian.json'),
46
+ ].filter(Boolean)
47
+ for (const file of candidates) {
48
+ try {
49
+ const cfg = JSON.parse(readFileSync(file, 'utf8'))
50
+ const vaults = Object.values(cfg.vaults ?? {})
51
+ const found = vaults.find(v => v.open) || vaults[0]
52
+ if (found?.path) return path.resolve(found.path)
53
+ } catch { /* ignore */ }
54
+ }
55
+ return null
56
+ }
57
+
58
+ /** 列出 obsidian.json 里登记的所有 vault,供面板切换 */
59
+ function listVaults() {
60
+ const home = homedir()
61
+ const candidates = [
62
+ process.env.APPDATA ? path.join(process.env.APPDATA, 'obsidian', 'obsidian.json') : '',
63
+ path.join(home, 'Library', 'Application Support', 'obsidian', 'obsidian.json'),
64
+ path.join(home, '.config', 'obsidian', 'obsidian.json'),
65
+ ].filter(Boolean)
66
+ for (const file of candidates) {
67
+ try {
68
+ const cfg = JSON.parse(readFileSync(file, 'utf8'))
69
+ const out = []
70
+ for (const v of Object.values(cfg.vaults ?? {})) {
71
+ if (!v?.path) continue
72
+ const abs = path.resolve(v.path)
73
+ out.push({ path: abs, name: path.basename(abs), open: !!v.open })
74
+ }
75
+ if (out.length) return out.sort((a, b) => Number(b.open) - Number(a.open))
76
+ } catch { /* ignore */ }
77
+ }
78
+ return []
79
+ }
80
+
81
+ function resolveVault() {
82
+ vaultError = ''
83
+ const explicit = config.vaultPath && String(config.vaultPath).trim()
84
+ vaultRoot = explicit ? path.resolve(String(config.vaultPath).trim()) : detectFromObsidianConfig()
85
+ if (!vaultRoot) vaultError = '未找到本地 Obsidian 知识库。请在插件配置里设置 vaultPath,或先在 Obsidian 中打开一个 vault。'
86
+ }
87
+
88
+ function guard(rel) {
89
+ if (!vaultRoot) throw new Error(vaultError || '知识库未配置')
90
+ if (typeof rel !== 'string') throw new Error('path must be a string')
91
+ const normalized = rel.trim() === '' ? '.' : rel.replace(/\\/g, '/')
92
+ if (normalized.startsWith('/') || /^[A-Za-z]:/.test(normalized)) throw new Error(`path escapes vault root: ${rel}`)
93
+ const root = path.resolve(vaultRoot)
94
+ const abs = path.resolve(root, normalized)
95
+ const out = path.relative(root, abs)
96
+ if (out === '..' || out.startsWith(`..${path.sep}`) || path.isAbsolute(out)) throw new Error(`path escapes vault root: ${rel}`)
97
+ return { root, abs, rel: out.replace(/\\/g, '/') }
98
+ }
99
+
100
+ const toRel = abs => path.relative(path.resolve(vaultRoot), abs).replace(/\\/g, '/')
101
+
102
+ function classify(name) {
103
+ const ext = (name.split('.').pop() || '').toLowerCase()
104
+ if (NOTE_EXT.has(ext)) return { type: 'note', ext }
105
+ if (ext === 'pdf') return { type: 'pdf', ext }
106
+ if (IMAGE_EXT.has(ext)) return { type: 'image', ext }
107
+ return { type: 'file', ext }
108
+ }
109
+
110
+ /** 遍历 vault,返回文件清单(不读正文,快);空文件夹也作为条目返回 */
111
+ async function walkVault(dir = '') {
112
+ const { abs } = guard(dir)
113
+ const out = []
114
+ async function walk(d) {
115
+ let entries
116
+ try { entries = await readdir(d, { withFileTypes: true }) } catch { return }
117
+ for (const e of entries) {
118
+ if (e.isDirectory() ? isIgnoredDir(e.name) : EXCLUDE.has(e.name)) continue
119
+ const full = path.join(d, e.name)
120
+ if (e.isDirectory()) {
121
+ // 记录文件夹本身,这样新建的空文件夹也能出现在树里
122
+ out.push({
123
+ path: toRel(full), title: e.name, type: 'folder', ext: '',
124
+ size: 0, mtime: 0,
125
+ })
126
+ await walk(full)
127
+ continue
128
+ }
129
+ if (!e.isFile()) continue
130
+ let st
131
+ try { st = await stat(full) } catch { continue }
132
+ const kind = classify(e.name)
133
+ out.push({
134
+ path: toRel(full),
135
+ title: kind.type === 'note' ? e.name.replace(/\.(md|markdown)$/i, '') : e.name,
136
+ type: kind.type,
137
+ ext: kind.ext,
138
+ size: st.size,
139
+ mtime: st.mtimeMs,
140
+ })
141
+ }
142
+ }
143
+ await walk(abs)
144
+ return out.sort((a, b) => a.path.localeCompare(b.path))
145
+ }
146
+
147
+ /** 从 Markdown 提取标题大纲 */
148
+ function extractHeadings(body) {
149
+ const lines = String(body || '').replace(/\r/g, '').split('\n')
150
+ const out = []
151
+ let inFence = false
152
+ for (const line of lines) {
153
+ if (/^\s*```/.test(line)) { inFence = !inFence; continue }
154
+ if (inFence) continue
155
+ const m = line.match(/^(#{1,6})\s+(.+?)\s*$/)
156
+ if (m) out.push({ level: m[1].length, text: m[2].replace(/[*_`]/g, ''), index: out.length })
157
+ }
158
+ return out
159
+ }
160
+
161
+ /** 标签:frontmatter + 行内 #tag */
162
+ function extractTags(body, fm) {
163
+ const set = new Set()
164
+ const fmTags = fm?.tags
165
+ if (typeof fmTags === 'string') fmTags.split(/[,\s]+/).filter(Boolean).forEach(x => set.add(x.replace(/^#/, '')))
166
+ if (Array.isArray(fmTags)) fmTags.forEach(x => set.add(String(x).replace(/^#/, '')))
167
+ const text = String(body || '').replace(/```[\s\S]*?```/g, ' ')
168
+ const re = /(^|[\s((])#([\p{L}\p{N}_\-/]+)/gu
169
+ let m
170
+ while ((m = re.exec(text))) set.add(m[2])
171
+ return [...set].filter(Boolean)
172
+ }
173
+
174
+ function parseFrontmatter(body) {
175
+ const fm = {}
176
+ const m = body.match(/^---\r?\n([\s\S]*?)\r?\n---/)
177
+ if (!m) return { fm, body }
178
+ for (const line of m[1].split(/\r?\n/)) {
179
+ const kv = line.match(/^([^:#\s][^:]*):\s*(.*)$/)
180
+ if (!kv) continue
181
+ const key = kv[1].trim()
182
+ let val = kv[2].trim()
183
+ if (/^\[.*\]$/.test(val)) val = val.slice(1, -1).split(',').map(s => s.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean)
184
+ else val = val.replace(/^['"]|['"]$/g, '')
185
+ fm[key] = val
186
+ }
187
+ return { fm, body: body.slice(m[0].length).replace(/^\r?\n/, '') }
188
+ }
189
+
190
+ function extractLinks(body) {
191
+ const out = []
192
+ const re = /\[\[([^\]|#]+)(?:[|#][^\]]*)?\]\]/g
193
+ let m
194
+ while ((m = re.exec(String(body || '')))) out.push(m[1].trim())
195
+ return [...new Set(out)].filter(Boolean)
196
+ }
197
+
198
+ function countWords(body) {
199
+ const text = String(body || '').replace(/```[\s\S]*?```/g, ' ').replace(/[#>*_`\-|]/g, ' ')
200
+ const cjk = (text.match(/[\p{Script=Han}]/gu) || []).length
201
+ const latin = (text.match(/[A-Za-z0-9_]+/g) || []).length
202
+ return cjk + latin
203
+ }
204
+
205
+ function excerptOf(body) {
206
+ const plain = String(body || '')
207
+ .replace(/^---[\s\S]*?---/, '')
208
+ .replace(/```[\s\S]*?```/g, ' ')
209
+ .replace(/!\[[^\]]*\]\([^)]*\)/g, ' ')
210
+ .replace(/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g, '$1')
211
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
212
+ .replace(/[#>*_`|\-]{1,}/g, ' ')
213
+ .replace(/\s+/g, ' ')
214
+ .trim()
215
+ return plain.slice(0, 160)
216
+ }
217
+
218
+ async function readNote(rel) {
219
+ const { abs } = guard(rel)
220
+ const st = await stat(abs)
221
+ if (!st.isFile()) throw new Error('not a file')
222
+ if (st.size > MAX_FILE) throw new Error('note too large (>4MB)')
223
+ const kind = classify(path.basename(abs))
224
+ const isNote = kind.type === 'note'
225
+
226
+ if (!isNote) {
227
+ // 非笔记:返回元信息,供面板展示图片/PDF 预览
228
+ return {
229
+ path: toRel(abs),
230
+ title: path.basename(abs),
231
+ body: '',
232
+ raw: '',
233
+ frontmatter: {},
234
+ tags: [],
235
+ headings: [],
236
+ links: [],
237
+ words: 0,
238
+ chars: 0,
239
+ lines: 0,
240
+ size: st.size,
241
+ mtime: st.mtimeMs,
242
+ ctime: st.birthtimeMs,
243
+ excerpt: '',
244
+ kind: kind.type,
245
+ ext: kind.ext,
246
+ }
247
+ }
248
+
249
+ const raw = await readFile(abs, 'utf8')
250
+ const { fm, body } = parseFrontmatter(raw)
251
+ const headings = extractHeadings(body)
252
+ return {
253
+ path: toRel(abs),
254
+ title: path.basename(abs).replace(/\.(md|markdown)$/i, ''),
255
+ body,
256
+ raw,
257
+ frontmatter: fm,
258
+ tags: extractTags(body, fm),
259
+ headings,
260
+ links: extractLinks(body),
261
+ words: countWords(body),
262
+ chars: body.length,
263
+ lines: body.split('\n').length,
264
+ size: st.size,
265
+ mtime: st.mtimeMs,
266
+ ctime: st.birthtimeMs,
267
+ excerpt: excerptOf(body),
268
+ kind: 'note',
269
+ ext: kind.ext,
270
+ }
271
+ }
272
+
273
+ /** 反链:扫描所有笔记中指向 target 的 [[链接]] */
274
+ async function backlinks(rel) {
275
+ const files = await walkVault('')
276
+ const target = rel.replace(/\.(md|markdown)$/i, '')
277
+ const base = path.basename(target)
278
+ const hits = []
279
+ for (const f of files) {
280
+ if (f.type !== 'note' || f.path === rel) continue
281
+ let raw
282
+ try { raw = await readFile(path.resolve(vaultRoot, f.path), 'utf8') } catch { continue }
283
+ const links = extractLinks(raw)
284
+ if (links.some(l => l === base || l === target || l === f.path.replace(/\.md$/i, ''))) {
285
+ hits.push({ path: f.path, title: f.title })
286
+ }
287
+ }
288
+ return hits
289
+ }
290
+
291
+ /** 把一条 [[链接]] 解析为 vault 内真实笔记 */
292
+ async function resolveLink(name, files) {
293
+ const clean = String(name).replace(/\.md$/i, '').trim()
294
+ const exact = files.find(f => f.type === 'note' && f.path.replace(/\.md$/i, '') === clean)
295
+ if (exact) return exact
296
+ const byBase = files.filter(f => f.type === 'note' && path.posix.basename(f.path).replace(/\.md$/i, '') === clean)
297
+ return byBase[0] || null
298
+ }
299
+
300
+ async function relatedNotes(rel) {
301
+ const files = await walkVault('')
302
+ const note = await readNote(rel)
303
+ const outgoing = []
304
+ for (const link of note.links) {
305
+ const hit = await resolveLink(link, files)
306
+ if (hit && hit.path !== rel) outgoing.push({ path: hit.path, title: hit.title, kind: 'out' })
307
+ }
308
+ const incoming = (await backlinks(rel)).map(x => ({ ...x, kind: 'in' }))
309
+ const seen = new Set()
310
+ return [...incoming, ...outgoing].filter(x => (seen.has(x.path) ? false : seen.add(x.path)))
311
+ }
312
+
313
+ // ─────────── 全库问答:检索 + 证据 ───────────
314
+
315
+ /** 把问题切成检索词:拉丁词 + 中文单字/双字 */
316
+ function tokenize(text) {
317
+ const s = String(text || '').toLowerCase()
318
+ const out = new Set()
319
+ for (const w of s.match(/[a-z0-9_]{2,}/g) || []) out.add(w)
320
+ const cjk = s.match(/[\p{Script=Han}]+/gu) || []
321
+ for (const run of cjk) {
322
+ for (const ch of run) out.add(ch)
323
+ for (let i = 0; i < run.length - 1; i++) out.add(run.slice(i, i + 2))
324
+ }
325
+ return [...out]
326
+ }
327
+
328
+ /** 按标题把正文切成块,便于精确引用 */
329
+ function splitChunks(body, headings) {
330
+ const lines = String(body || '').replace(/\r/g, '').split('\n')
331
+ const chunks = []
332
+ let cur = { heading: '正文', lines: [] }
333
+ let inFence = false
334
+ for (const line of lines) {
335
+ if (/^\s*```/.test(line)) inFence = !inFence
336
+ const hm = !inFence && line.match(/^(#{1,6})\s+(.+?)\s*$/)
337
+ if (hm) {
338
+ if (cur.lines.join('').trim()) chunks.push(cur)
339
+ cur = { heading: hm[2].replace(/[*_`]/g, ''), lines: [] }
340
+ continue
341
+ }
342
+ cur.lines.push(line)
343
+ }
344
+ if (cur.lines.join('').trim()) chunks.push(cur)
345
+ return chunks.map(c => ({ heading: c.heading, text: c.lines.join('\n').trim() })).filter(c => c.text)
346
+ }
347
+
348
+ function scoreChunk(text, heading, title, terms) {
349
+ const hay = `${title}\n${heading}\n${text}`.toLowerCase()
350
+ let score = 0
351
+ for (const term of terms) {
352
+ if (!term) continue
353
+ let idx = hay.indexOf(term)
354
+ if (idx < 0) continue
355
+ const weight = term.length > 1 ? 3 : 1
356
+ let hits = 0
357
+ while (idx >= 0 && hits < 12) { hits++; score += weight; idx = hay.indexOf(term, idx + term.length) }
358
+ if (heading.toLowerCase().includes(term)) score += weight * 4
359
+ if (title.toLowerCase().includes(term)) score += weight * 3
360
+ }
361
+ return score
362
+ }
363
+
364
+ /** 全库检索:返回最相关的证据块 */
365
+ async function retrieve(question, limit = 8) {
366
+ const terms = tokenize(question)
367
+ if (!terms.length) return []
368
+ const files = await walkVault('')
369
+ const hits = []
370
+ for (const f of files) {
371
+ if (f.type !== 'note') continue
372
+ let raw
373
+ try { raw = await readFile(path.resolve(vaultRoot, f.path), 'utf8') } catch { continue }
374
+ const { body } = parseFrontmatter(raw)
375
+ for (const ch of splitChunks(body, extractHeadings(body))) {
376
+ const score = scoreChunk(ch.text, ch.heading, f.title, terms)
377
+ if (score > 0) hits.push({ path: f.path, title: f.title, heading: ch.heading, text: ch.text, score })
378
+ }
379
+ }
380
+ hits.sort((a, b) => b.score - a.score)
381
+ return hits.slice(0, limit)
382
+ }
383
+
384
+ /** 尝试用当前默认模型综合回答;不可用时退回证据 */
385
+ async function synthesize(ctx, question, hits) {
386
+ if (!hits.length) return { answer: '', synthesized: false, reason: 'no-evidence' }
387
+ let provider, model
388
+ try {
389
+ const sel = ctx.get('agentDefaultModel')?.currentSelection?.()
390
+ provider = sel?.provider
391
+ model = sel?.model
392
+ } catch { /* ignore */ }
393
+ let llm
394
+ try { llm = ctx.get('llm') } catch { /* ignore */ }
395
+ if (!llm || !provider || !model) return { answer: '', synthesized: false, reason: 'no-model' }
396
+
397
+ const evidence = hits.map((h, i) =>
398
+ `[${i + 1}] ${h.path}${h.heading ? ` › ${h.heading}` : ''}\n${h.text.slice(0, 1600)}`).join('\n\n')
399
+ const prompt = [
400
+ '你是检索问答系统。读完片段后,只输出一行最终答案,不要输出任何思考或复述。',
401
+ '',
402
+ `片段:`,
403
+ evidence,
404
+ '',
405
+ `问题:${question}`,
406
+ '',
407
+ '答案(一行):',
408
+ ].join('\n')
409
+
410
+ const ac = new AbortController()
411
+ const timer = setTimeout(() => ac.abort(), 60000)
412
+ try {
413
+ const stream = llm.stream({
414
+ provider,
415
+ model,
416
+ messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
417
+ signal: ac.signal,
418
+ })
419
+ let text = ''
420
+ for await (const chunk of stream) {
421
+ if (ac.signal.aborted) break
422
+ const piece = chunk?.delta ?? chunk?.text ?? chunk?.content ?? ''
423
+ if (typeof piece === 'string') text += piece
424
+ else if (Array.isArray(piece)) {
425
+ for (const part of piece) if (part?.type === 'text' && part.text) text += part.text
426
+ } else if (piece && typeof piece === 'object' && typeof piece.text === 'string') text += piece.text
427
+ }
428
+ if (text.trim()) return { answer: cleanAnswer(text), synthesized: true, provider, model, reason: '' }
429
+ return { answer: '', synthesized: false, reason: 'empty' }
430
+ } catch (e) {
431
+ return { answer: '', synthesized: false, reason: String(e?.message || e).slice(0, 200) }
432
+ } finally {
433
+ clearTimeout(timer)
434
+ }
435
+ }
436
+
437
+ /** 去掉模型泄漏的思考:优先取带引号的完整答案,否则取最后一个干净句 */
438
+ function cleanAnswer(text) {
439
+ let s = String(text || '')
440
+ s = s.replace(/<think(?:ing)?>[\s\S]*?<\/think(?:ing)?>/gi, '').trim()
441
+ if (!s) return ''
442
+
443
+ // 优先:引号内的完整答案(模型常把答案写在引号里)
444
+ const quoted = [...s.matchAll(/["“]([^"”]{6,400})["”]/g)]
445
+ .map(m => m[1].trim())
446
+ .filter(x => x && !/^(We need|Need |Only |No explanation)/i.test(x))
447
+ if (quoted.length) return quoted[quoted.length - 1]
448
+
449
+ // 其次:最后一个以句末标点结尾、且不含思考词的句子
450
+ const BAD = /(We need|Need answer|Only final|No explanation|我们需要|我们应该|答案式|不要输出|仅依据|片段\[?\d*\]?|问题[::]|需要简洁|可以标注|按格式|最后给出|用户问|用户想|注意严格|只能最终|需要输出|应该回答|可以答|问有什么|最终只输出|按检索问答|没有具体内容|一行)/
451
+ // 只按中文句末与 !? 切分;不按英文句点切(避免把 IP/版本号切碎)
452
+ const sentences = s.split(/(?<=[。!?!?\n])/).map(x => x.trim()).filter(Boolean)
453
+ for (let i = sentences.length - 1; i >= 0; i--) {
454
+ const c = sentences[i].replace(/^["“]|["”]$/g, '').trim()
455
+ if (c.length >= 4 && !BAD.test(c)) return c
456
+ }
457
+ // 兜底:整段(可能是短答案本身)
458
+ return s.length <= 200 && !BAD.test(s) ? s.trim() : ''
459
+ }
460
+
461
+ async function askVault(ctx, question, limit = 8) {
462
+ const q = String(question || '').trim()
463
+ if (!q) throw new Error('question is required')
464
+ const hits = await retrieve(q, limit)
465
+ const { answer, synthesized, reason, provider, model } = await synthesize(ctx, q, hits)
466
+ const citations = []
467
+ const seen = new Set()
468
+ for (const h of hits) {
469
+ if (seen.has(h.path)) continue
470
+ seen.add(h.path)
471
+ citations.push({ path: h.path, title: h.title, heading: h.heading })
472
+ }
473
+ return { question: q, answer, synthesized, reason, provider, model, hits, citations }
474
+ }
475
+
476
+ async function tagsIndex() {
477
+ const files = await walkVault('')
478
+ const counts = new Map()
479
+ for (const f of files) {
480
+ if (f.type !== 'note') continue
481
+ let raw
482
+ try { raw = await readFile(path.resolve(vaultRoot, f.path), 'utf8') } catch { continue }
483
+ const { fm, body } = parseFrontmatter(raw)
484
+ for (const tag of extractTags(body, fm)) counts.set(tag, (counts.get(tag) || 0) + 1)
485
+ }
486
+ return [...counts.entries()].map(([tag, count]) => ({ tag, count })).sort((a, b) => b.count - a.count || a.tag.localeCompare(b.tag))
487
+ }
488
+
489
+ async function searchVault(query, opts = {}) {
490
+ const q = String(query || '').trim().toLowerCase()
491
+ if (!q) return []
492
+ const files = await walkVault('')
493
+ const limit = opts.limit || 60
494
+ const out = []
495
+ for (const f of files) {
496
+ if (out.length >= limit) break
497
+ if (f.type !== 'note') continue
498
+ let raw
499
+ try { raw = await readFile(path.resolve(vaultRoot, f.path), 'utf8') } catch { continue }
500
+ const titleHit = f.title.toLowerCase().includes(q)
501
+ const lines = raw.replace(/\r/g, '').split('\n')
502
+ let lineHit = null
503
+ for (let i = 0; i < lines.length; i++) {
504
+ if (lines[i].toLowerCase().includes(q)) { lineHit = { line: i + 1, text: lines[i].trim().slice(0, 180) }; break }
505
+ }
506
+ if (titleHit || lineHit) {
507
+ out.push({ path: f.path, title: f.title, mtime: f.mtime, line: lineHit?.line, text: lineHit?.text, inTitle: titleHit })
508
+ }
509
+ }
510
+ return out
511
+ }
512
+
513
+ async function status() {
514
+ if (!vaultRoot || vaultError) {
515
+ return {
516
+ ok: false, connected: false, vaultPath: vaultRoot || null, error: vaultError,
517
+ vaults: listVaults(), counts: { note: 0, pdf: 0, image: 0, file: 0, folders: 0 },
518
+ }
519
+ }
520
+ const files = await walkVault('')
521
+ const counts = { note: 0, pdf: 0, image: 0, file: 0, folders: 0 }
522
+ const folders = new Set()
523
+ for (const f of files) {
524
+ if (f.type === 'folder') { folders.add(f.path); continue }
525
+ counts[f.type] = (counts[f.type] || 0) + 1
526
+ const dir = f.path.includes('/') ? f.path.slice(0, f.path.lastIndexOf('/')) : ''
527
+ if (dir) { let acc = ''; for (const seg of dir.split('/')) { acc = acc ? `${acc}/${seg}` : seg; folders.add(acc) } }
528
+ }
529
+ counts.folders = folders.size
530
+ return {
531
+ ok: true, connected: true, vaultPath: vaultRoot, name: path.basename(vaultRoot), error: '',
532
+ vaults: listVaults(), counts,
533
+ }
534
+ }
535
+
536
+ async function writeNote(rel, content) {
537
+ const { abs } = guard(rel)
538
+ if (typeof content !== 'string') throw new Error('content must be a string')
539
+ await mkdir(path.dirname(abs), { recursive: true })
540
+ await writeFile(abs, content, 'utf8')
541
+ return { path: toRel(abs), bytes: Buffer.byteLength(content, 'utf8') }
542
+ }
543
+
544
+ async function appendNote(rel, content) {
545
+ const existing = await readNote(rel).catch(() => ({ raw: '' }))
546
+ const sep = existing.raw && !existing.raw.endsWith('\n') ? '\n' : ''
547
+ return writeNote(rel, existing.raw + sep + String(content ?? ''))
548
+ }
549
+
550
+ async function moveNote(from, to) {
551
+ const a = guard(from)
552
+ const b = guard(to)
553
+ await mkdir(path.dirname(b.abs), { recursive: true })
554
+ await rename(a.abs, b.abs)
555
+ return { from: a.rel, to: b.rel }
556
+ }
557
+
558
+ async function deleteNote(rel) {
559
+ const { abs } = guard(rel)
560
+ const trash = path.join(path.resolve(vaultRoot), '.trash')
561
+ await mkdir(trash, { recursive: true })
562
+ const dest = path.join(trash, `${Date.now()}-${path.basename(abs)}`)
563
+ await copyFile(abs, dest)
564
+ await rm(abs)
565
+ return { path: toRel(abs), trashed: toRel(dest) }
566
+ }
567
+
568
+ async function makeFolder(rel) {
569
+ const { abs, rel: clean } = guard(rel)
570
+ await mkdir(abs, { recursive: true })
571
+ return { path: clean }
572
+ }
573
+
574
+ /** 删除文件夹:整棵子树移入 .trash(可逆),并返回受影响文件数 */
575
+ async function deleteFolder(rel) {
576
+ const { abs, rel: clean } = guard(rel)
577
+ if (!clean) throw new Error('不能删除 vault 根目录')
578
+ const st = await stat(abs)
579
+ if (!st.isDirectory()) throw new Error('not a directory')
580
+
581
+ // 统计将被移除的内容
582
+ let files = 0
583
+ async function count(d) {
584
+ let entries
585
+ try { entries = await readdir(d, { withFileTypes: true }) } catch { return }
586
+ for (const e of entries) {
587
+ const full = path.join(d, e.name)
588
+ if (e.isDirectory()) await count(full)
589
+ else files++
590
+ }
591
+ }
592
+ await count(abs)
593
+
594
+ const trash = path.join(path.resolve(vaultRoot), '.trash', `${Date.now()}-${path.basename(abs)}`)
595
+ await mkdir(path.dirname(trash), { recursive: true })
596
+ // 优先整目录搬移(同盘原子),失败则递归复制后删除
597
+ try {
598
+ await rename(abs, trash)
599
+ } catch {
600
+ await copyFile(abs, trash).catch(() => {})
601
+ try {
602
+ await rm(abs, { recursive: true, force: true })
603
+ } catch (e) {
604
+ throw new Error(`删除失败:${e?.message ?? e}`)
605
+ }
606
+ }
607
+ return { path: clean, trashed: toRel(trash), files }
608
+ }
609
+
610
+ /** 在磁盘上创建一个新的 Obsidian vault(含最小 .obsidian 配置) */
611
+ async function createVault(parentDir, name) {
612
+ const parent = String(parentDir || '').trim()
613
+ const rawName = String(name || '').trim()
614
+ if (!parent) throw new Error('请填写父目录,例如 D:\\知识库')
615
+ if (!rawName) throw new Error('请填写项目(vault)名称')
616
+ if (/[\\/:*?"<>|]/.test(rawName)) throw new Error('名称不能包含 \\ / : * ? " < > |')
617
+
618
+ const parentAbs = path.resolve(parent)
619
+ try {
620
+ const st = await stat(parentAbs)
621
+ if (!st.isDirectory()) throw new Error('父目录不是文件夹')
622
+ } catch (e) {
623
+ if (e?.code === 'ENOENT') throw new Error(`父目录不存在:${parentAbs}`)
624
+ throw e
625
+ }
626
+
627
+ const target = path.join(parentAbs, rawName)
628
+ try {
629
+ const st = await stat(target)
630
+ if (st.isDirectory()) throw new Error(`目标已存在:${target}`)
631
+ } catch (e) {
632
+ if (e?.code !== 'ENOENT') throw e
633
+ }
634
+
635
+ await mkdir(target, { recursive: true })
636
+ // 写一个最小 .obsidian 目录,让 Obsidian 能识别为 vault
637
+ const obsidianDir = path.join(target, '.obsidian')
638
+ await mkdir(obsidianDir, { recursive: true })
639
+ await writeFile(path.join(obsidianDir, 'app.json'), '{}\n', 'utf8').catch(() => {})
640
+ await writeFile(
641
+ path.join(obsidianDir, 'core-plugins.json'),
642
+ JSON.stringify({ 'file-explorer': true, 'global-search': true, switcher: true, graph: false }, null, 2),
643
+ 'utf8',
644
+ ).catch(() => {})
645
+ await writeFile(path.join(target, '欢迎.md'), `# ${rawName}\n\n这是新建知识库的首页。\n`, 'utf8').catch(() => {})
646
+
647
+ return { path: target, name: rawName }
648
+ }
649
+
650
+ function readJsonBody(req, limit = 16 * 1024 * 1024) {
651
+ return new Promise((resolve, reject) => {
652
+ let size = 0, settled = false
653
+ const chunks = []
654
+ const fail = e => { if (!settled) { settled = true; reject(e) } }
655
+ req.on('data', c => {
656
+ if (settled) return
657
+ size += c.length
658
+ if (size > limit) { fail(new Error('body too large')); return }
659
+ chunks.push(c)
660
+ })
661
+ req.on('end', () => {
662
+ if (settled) return
663
+ settled = true
664
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')) }
665
+ catch { reject(new Error('invalid JSON')) }
666
+ })
667
+ req.on('error', fail)
668
+ })
669
+ }
670
+
671
+ function sendJson(res, code, body) {
672
+ const data = Buffer.from(JSON.stringify(body), 'utf8')
673
+ res.writeHead(code, {
674
+ 'content-type': 'application/json; charset=utf-8',
675
+ 'content-length': data.length,
676
+ 'cache-control': 'no-store',
677
+ 'x-content-type-options': 'nosniff',
678
+ })
679
+ res.end(data)
680
+ }
681
+
682
+ function isTrusted(req) {
683
+ const origin = req.headers.origin
684
+ if (!origin) return true
685
+ const host = req.headers.host
686
+ if (!host) return false
687
+ return origin === `http://${host}` || origin === `https://${host}`
688
+ }
689
+
690
+ /** 对话侧工具:与左侧栏共用同一套实现 */
691
+ function registerTools(ctx) {
692
+ const off = []
693
+ const OUT = { type: 'object', properties: { message: { type: 'string' } }, required: ['message'] }
694
+ const P = (props, required = []) => ({ type: 'object', properties: props, ...(required.length ? { required } : {}) })
695
+ const S = description => ({ type: 'string', description })
696
+ const I = description => ({ type: 'integer', description })
697
+
698
+ const tool = (name, description, parameters, execute) => {
699
+ off.push(ctx.tools.register({
700
+ name,
701
+ description,
702
+ parameters,
703
+ output: { schema: OUT, render: (_a, v) => [{ type: 'text', text: String(v?.message ?? '') }] },
704
+ execute: async (args) => {
705
+ const result = await execute(args)
706
+ return { message: typeof result === 'string' ? result : JSON.stringify(result, null, 2) }
707
+ },
708
+ }))
709
+ }
710
+
711
+ tool('kb_status', '查看本地 Obsidian 知识库连接状态、vault 路径与各类文件数量。', P({}), () => status())
712
+ tool('kb_list', '列出知识库中的笔记(可按子目录与类型过滤)。', P({
713
+ dir: S('vault 内的相对子目录,留空为根目录。'),
714
+ type: S('类型过滤:note / pdf / image / file。'),
715
+ limit: I('最多返回条数,默认 300。'),
716
+ }), async args => {
717
+ const files = await walkVault(args.dir || '')
718
+ const filtered = args.type ? files.filter(f => f.type === args.type) : files
719
+ return filtered.slice(0, args.limit || 300).map(f => ({ path: f.path, title: f.title, type: f.type, size: f.size }))
720
+ })
721
+ tool('kb_search', '在知识库中全文检索笔记标题与正文,返回匹配行。', P({
722
+ query: S('要检索的文字(大小写不敏感)。'),
723
+ limit: I('最多返回条数,默认 60。'),
724
+ }, ['query']), args => searchVault(args.query, { limit: args.limit || 60 }))
725
+ tool('kb_read', '读取一篇笔记:正文、frontmatter、标签、大纲、字数、链接与反链。', P({
726
+ path: S('相对 vault 的笔记路径,如 Folder/Note.md。'),
727
+ }, ['path']), async args => {
728
+ const note = await readNote(args.path)
729
+ return {
730
+ path: note.path, title: note.title, tags: note.tags, words: note.words,
731
+ headings: note.headings.map(x => `${'#'.repeat(x.level)} ${x.text}`), links: note.links, body: note.body,
732
+ }
733
+ })
734
+ tool('kb_outline', '取出一篇笔记的标题大纲,用于定位章节。', P({
735
+ path: S('相对 vault 的笔记路径。'),
736
+ }, ['path']), async args => (await readNote(args.path)).headings)
737
+ tool('kb_write', '新建或覆盖一篇笔记。', P({
738
+ path: S('相对 vault 的笔记路径。'),
739
+ content: S('笔记完整内容(Markdown)。'),
740
+ }, ['path', 'content']), args => writeNote(args.path, args.content))
741
+ tool('kb_append', '向一篇笔记末尾追加内容。', P({
742
+ path: S('相对 vault 的笔记路径。'),
743
+ content: S('要追加的内容。'),
744
+ }, ['path', 'content']), args => appendNote(args.path, args.content))
745
+ tool('kb_move', '移动或重命名笔记。', P({
746
+ from: S('原相对路径。'),
747
+ to: S('目标相对路径。'),
748
+ }, ['from', 'to']), args => moveNote(args.from, args.to))
749
+ tool('kb_delete', '把笔记移入 .trash(可逆删除)。', P({
750
+ path: S('相对 vault 的笔记路径。'),
751
+ }, ['path']), args => deleteNote(args.path))
752
+ tool('kb_backlinks', '查找链接到某篇笔记的其它笔记。', P({
753
+ path: S('相对 vault 的笔记路径。'),
754
+ }, ['path']), args => backlinks(args.path))
755
+ tool('kb_related', '查找与某篇笔记相关的笔记(反链 + 出链)。', P({
756
+ path: S('相对 vault 的笔记路径。'),
757
+ }, ['path']), args => relatedNotes(args.path))
758
+ tool('kb_ask', '全库问答:在整个知识库里检索与问题相关的片段,并据此回答,返回答案与出处。', P({
759
+ question: S('要问的问题,自然语言即可。'),
760
+ limit: S('最多取多少条证据片段,默认 8。'),
761
+ }, ['question']), args => askVault(ctx, args.question, Number(args.limit) || 8))
762
+ tool('kb_tags', '列出知识库内所有标签及使用次数。', P({}), () => tagsIndex())
763
+ tool('kb_mkdir', '在知识库内创建文件夹。', P({
764
+ path: S('相对 vault 的文件夹路径。'),
765
+ }, ['path']), args => makeFolder(args.path))
766
+ tool('kb_rmdir', '删除知识库内的文件夹(整棵子树移入 .trash,可逆)。', P({
767
+ path: S('相对 vault 的文件夹路径。'),
768
+ }, ['path']), args => deleteFolder(args.path))
769
+ tool('kb_create_vault', '在磁盘上新建一个 Obsidian vault(知识库项目),并切换过去。', P({
770
+ parent: S('父目录绝对路径,例如 D:\\知识库。'),
771
+ name: S('新 vault 名称。'),
772
+ }, ['parent', 'name']), async args => {
773
+ const created = await createVault(args.parent, args.name)
774
+ config = { ...config, vaultPath: created.path }
775
+ resolveVault()
776
+ return created
777
+ })
778
+
779
+ return () => { for (const f of off.reverse()) { try { f() } catch {} } }
780
+ }
781
+
782
+ export function apply(ctx, source) {
783
+ if (source && typeof source === 'object') {
784
+ const live = 'get' in source
785
+ config = { ...config, ...(live ? source.get() : source) }
786
+ }
787
+ resolveVault()
788
+
789
+ const unregisterTools = registerTools(ctx)
790
+
791
+ const disposeRoute = ctx.webServer.register({
792
+ kind: 'prefix',
793
+ path: PREFIX,
794
+ handler: async (req, res) => {
795
+ if (!isTrusted(req)) { sendJson(res, 403, { ok: false, error: 'forbidden' }); return }
796
+ const url = new URL(req.url || '/', 'http://127.0.0.1')
797
+
798
+ // 原始文件(图片 / PDF 预览)
799
+ if (url.pathname === `${PREFIX}/raw`) {
800
+ try {
801
+ const { abs } = guard(url.searchParams.get('path') || '')
802
+ const st = await stat(abs)
803
+ if (!st.isFile()) { sendJson(res, 404, { ok: false, error: 'not a file' }); return }
804
+ if (st.size > 32 * 1024 * 1024) { sendJson(res, 413, { ok: false, error: 'file too large' }); return }
805
+ const ext = (abs.split('.').pop() || '').toLowerCase()
806
+ const MIME = {
807
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif',
808
+ svg: 'image/svg+xml', webp: 'image/webp', bmp: 'image/bmp', avif: 'image/avif',
809
+ pdf: 'application/pdf',
810
+ }
811
+ const buf = await readFile(abs)
812
+ res.writeHead(200, {
813
+ 'content-type': MIME[ext] || 'application/octet-stream',
814
+ 'content-length': buf.length,
815
+ 'cache-control': 'no-store',
816
+ 'x-content-type-options': 'nosniff',
817
+ })
818
+ res.end(buf)
819
+ } catch (e) {
820
+ sendJson(res, 404, { ok: false, error: e?.message ?? String(e) })
821
+ }
822
+ return
823
+ }
824
+
825
+ const p = url.pathname.slice(API.length)
826
+
827
+ try {
828
+ if (p === '/status' && req.method === 'GET') { sendJson(res, 200, await status()); return }
829
+ if (p === '/reload' && req.method === 'POST') { resolveVault(); sendJson(res, 200, await status()); return }
830
+ if (p === '/vaults' && req.method === 'GET') {
831
+ sendJson(res, 200, { ok: true, current: vaultRoot, vaults: listVaults() })
832
+ return
833
+ }
834
+ if (p === '/switch' && req.method === 'POST') {
835
+ const b = await readJsonBody(req)
836
+ const target = String(b.path || '').trim()
837
+ if (!target) { sendJson(res, 200, { ok: false, error: 'path is required' }); return }
838
+ const abs = path.resolve(target)
839
+ try {
840
+ const st = await stat(abs)
841
+ if (!st.isDirectory()) { sendJson(res, 200, { ok: false, error: '不是文件夹' }); return }
842
+ } catch {
843
+ sendJson(res, 200, { ok: false, error: '路径不存在' }); return
844
+ }
845
+ config = { ...config, vaultPath: abs }
846
+ resolveVault()
847
+ sendJson(res, 200, { ok: true, ...(await status()) })
848
+ return
849
+ }
850
+ if (p === '/tree' && req.method === 'GET') {
851
+ const files = await walkVault(url.searchParams.get('dir') || '')
852
+ sendJson(res, 200, { ok: true, files })
853
+ return
854
+ }
855
+ if (p === '/note' && req.method === 'GET') {
856
+ const note = await readNote(url.searchParams.get('path') || '')
857
+ sendJson(res, 200, { ok: true, note })
858
+ return
859
+ }
860
+ if (p === '/related' && req.method === 'GET') {
861
+ sendJson(res, 200, { ok: true, related: await relatedNotes(url.searchParams.get('path') || '') })
862
+ return
863
+ }
864
+ if (p === '/tags' && req.method === 'GET') {
865
+ sendJson(res, 200, { ok: true, tags: await tagsIndex() })
866
+ return
867
+ }
868
+ if (p === '/search' && req.method === 'GET') {
869
+ sendJson(res, 200, { ok: true, results: await searchVault(url.searchParams.get('query') || '', { limit: Number(url.searchParams.get('limit')) || 60 }) })
870
+ return
871
+ }
872
+ if (p === '/ask' && req.method === 'POST') {
873
+ const b = await readJsonBody(req)
874
+ sendJson(res, 200, { ok: true, ...(await askVault(ctx, b.question, Number(b.limit) || 8)) })
875
+ return
876
+ }
877
+ if (p === '/save' && req.method === 'POST') {
878
+ const b = await readJsonBody(req)
879
+ sendJson(res, 200, { ok: true, result: await writeNote(b.path, b.content) })
880
+ return
881
+ }
882
+ if (p === '/create' && req.method === 'POST') {
883
+ const b = await readJsonBody(req)
884
+ const rel = /\.(md|markdown)$/i.test(b.path) ? b.path : `${b.path}.md`
885
+ const content = typeof b.content === 'string' ? b.content : `# ${path.basename(rel).replace(/\.md$/i, '')}\n\n`
886
+ sendJson(res, 200, { ok: true, result: await writeNote(rel, content) })
887
+ return
888
+ }
889
+ if (p === '/move' && req.method === 'POST') {
890
+ const b = await readJsonBody(req)
891
+ sendJson(res, 200, { ok: true, result: await moveNote(b.from, b.to) })
892
+ return
893
+ }
894
+ if (p === '/delete' && req.method === 'POST') {
895
+ const b = await readJsonBody(req)
896
+ sendJson(res, 200, { ok: true, result: await deleteNote(b.path) })
897
+ return
898
+ }
899
+ if (p === '/mkdir' && req.method === 'POST') {
900
+ const b = await readJsonBody(req)
901
+ sendJson(res, 200, { ok: true, result: await makeFolder(b.path) })
902
+ return
903
+ }
904
+ if (p === '/rmdir' && req.method === 'POST') {
905
+ const b = await readJsonBody(req)
906
+ sendJson(res, 200, { ok: true, result: await deleteFolder(b.path) })
907
+ return
908
+ }
909
+ if (p === '/create-vault' && req.method === 'POST') {
910
+ const b = await readJsonBody(req)
911
+ const created = await createVault(b.parent, b.name)
912
+ // 新建后直接切过去
913
+ config = { ...config, vaultPath: created.path }
914
+ resolveVault()
915
+ sendJson(res, 200, { ok: true, result: created, ...(await status()) })
916
+ return
917
+ }
918
+ sendJson(res, 404, { ok: false, error: 'not found' })
919
+ } catch (e) {
920
+ sendJson(res, 200, { ok: false, error: e?.message ?? String(e) })
921
+ }
922
+ },
923
+ })
924
+
925
+ ctx.effect(() => () => {
926
+ try { disposeRoute() } catch {}
927
+ try { unregisterTools?.() } catch {}
928
+ }, '@wagq/dsh-obsidian:cleanup')
929
+
930
+ ctx.logger?.info?.(`[kb] vault=${vaultRoot || 'UNCONFIGURED'} api=${API} tools=registered`)
931
+ }