@xiaofanzhao/dsh-plugin-knowledge-base 0.0.0-stage → 0.1.0

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/routes.mjs ADDED
@@ -0,0 +1,546 @@
1
+ // ============================================================================
2
+ // Host HTTP 路由(浏览器端只用这一条通道)
3
+ //
4
+ // 约定:
5
+ // · 所有接口都要求自定义头 x-kb-client: 1(跨站简单请求过不了预检,防 CSRF)
6
+ // · 带 Origin 的请求必须同源
7
+ // · 落盘文件名永远是 <docId>.<ext>,用户文件名只存数据库
8
+ // ============================================================================
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { createWriteStream } from 'node:fs';
12
+ import { pipeline as streamPipeline } from 'node:stream/promises';
13
+ import { createHash } from 'node:crypto';
14
+ import {
15
+ API_BASE, extOf, filenameFromHeader, guard, newId, nowMs, readBody, sanitizeName,
16
+ sendBytes, sendJson, sendText, clampInt,
17
+ } from './util.mjs';
18
+ import { MIME_BY_EXT, SUPPORTED_EXTENSIONS, isIndexable } from './extract.mjs';
19
+ import { IMAGE_EXTENSIONS } from './preview.mjs';
20
+ import { createEmbedder } from './index.mjs';
21
+
22
+ function fail(res, status, error) {
23
+ return sendJson(res, status, { ok: false, error });
24
+ }
25
+
26
+ function safeOrigin(webServer) {
27
+ try {
28
+ return webServer?.getOrigin?.() ?? '';
29
+ } catch {
30
+ return '';
31
+ }
32
+ }
33
+
34
+ export function createRoutes({ store, index, pipeline, embedder, settings, config, logger, webServer, token, previewer }) {
35
+ const origin = safeOrigin(webServer);
36
+ const maxFileBytes = Number(config?.maxFileBytes) || 64 * 1024 * 1024;
37
+
38
+ const capabilities = () => ({
39
+ embedding: embedder?.describe?.() ?? { configured: false, enabled: false, model: '' },
40
+ officePreview: previewer?.available?.() ?? false,
41
+ maxFileBytes,
42
+ formats: [...SUPPORTED_EXTENSIONS],
43
+ });
44
+
45
+ /** 把一个文件直接写给浏览器。 */
46
+ function serveFile(res, filePath, type, { download = false, name = '', cache = 'private, max-age=60' } = {}) {
47
+ let stat;
48
+ try {
49
+ stat = fs.statSync(filePath);
50
+ } catch {
51
+ return fail(res, 404, '文件不见了');
52
+ }
53
+ const headers = {
54
+ 'content-type': type,
55
+ 'content-length': stat.size,
56
+ 'cache-control': cache,
57
+ 'content-disposition': download
58
+ ? `attachment; filename*=UTF-8''${encodeURIComponent(name || 'file')}`
59
+ : 'inline',
60
+ };
61
+ res.writeHead(200, headers);
62
+ fs.createReadStream(filePath).pipe(res);
63
+ return undefined;
64
+ }
65
+
66
+ /** 全库解析进度(重建索引时界面靠它显示进度条)。 */
67
+ function progressOf() {
68
+ const rows = store.raw.q(`SELECT status, COUNT(*) AS n FROM nodes WHERE kind = 'doc' GROUP BY status`).all();
69
+ const counts = { pending: 0, parsing: 0, ready: 0, failed: 0 };
70
+ for (const row of rows) {
71
+ if (row.status in counts) counts[row.status] = Number(row.n);
72
+ else counts.pending += Number(row.n);
73
+ }
74
+ const total = counts.pending + counts.parsing + counts.ready + counts.failed;
75
+ const info = pipeline?.pendingInfo?.() ?? { queued: 0, active: 0, concurrency: 1 };
76
+ return { ...counts, total, done: counts.ready + counts.failed, queued: info.queued, active: info.active };
77
+ }
78
+
79
+ function stateBody(kbId) {
80
+ const kbs = store.listKbs();
81
+ const active = kbId || kbs[0]?.id || '';
82
+ return {
83
+ ok: true,
84
+ root: store.root,
85
+ token,
86
+ kbs,
87
+ kbId: active,
88
+ nodes: active ? store.listNodes(active) : [],
89
+ stats: store.stats(),
90
+ progress: progressOf(),
91
+ capabilities: capabilities(),
92
+ };
93
+ }
94
+
95
+ async function handleUpload(req, res) {
96
+ const url = new URL(req.url ?? '/', 'http://local');
97
+ const kbId = url.searchParams.get('kb') || '';
98
+ const parentId = url.searchParams.get('parent') || '';
99
+ const kb = kbId ? store.getKb(kbId) : null;
100
+ if (!kb) return fail(res, 400, '知识库不存在');
101
+ const filename = filenameFromHeader(req) || 'file';
102
+ const ext = extOf(filename);
103
+ if (!SUPPORTED_EXTENSIONS.has(ext)) return fail(res, 415, `不支持的文件类型:.${ext || '?'}`);
104
+
105
+ const declared = Number(req.headers['content-length']);
106
+ if (Number.isFinite(declared) && declared > maxFileBytes) {
107
+ return fail(res, 413, `文件超过上限(${Math.round(maxFileBytes / 1048576)} MB)`);
108
+ }
109
+
110
+ const docId = newId('d');
111
+ const tmpPath = path.join(store.tmpDir, `${docId}.part`);
112
+ const hash = createHash('sha256');
113
+ let size = 0;
114
+ let aborted = false;
115
+ req.on('data', (chunk) => {
116
+ size += chunk.length;
117
+ if (size > maxFileBytes) aborted = true;
118
+ hash.update(chunk);
119
+ });
120
+ try {
121
+ await streamPipeline(req, createWriteStream(tmpPath));
122
+ } catch (error) {
123
+ try { fs.rmSync(tmpPath, { force: true }); } catch { /* ignore */ }
124
+ return fail(res, 400, `上传中断:${error instanceof Error ? error.message : String(error)}`);
125
+ }
126
+ if (aborted) {
127
+ try { fs.rmSync(tmpPath, { force: true }); } catch { /* ignore */ }
128
+ return fail(res, 413, `文件超过上限(${Math.round(maxFileBytes / 1048576)} MB)`);
129
+ }
130
+ if (size === 0) {
131
+ try { fs.rmSync(tmpPath, { force: true }); } catch { /* ignore */ }
132
+ return fail(res, 400, '文件是空的');
133
+ }
134
+
135
+ const finalPath = path.join(store.filesDir, `${docId}.${ext}`);
136
+ fs.renameSync(tmpPath, finalPath);
137
+ const indexable = isIndexable(ext);
138
+ const node = store.createNode({
139
+ id: docId,
140
+ kbId,
141
+ parentId: parentId || null,
142
+ kind: 'doc',
143
+ name: sanitizeName(filename, `未命名.${ext}`),
144
+ now: nowMs(),
145
+ ext,
146
+ mime: MIME_BY_EXT[ext] ?? 'application/octet-stream',
147
+ bytes: size,
148
+ filePath: finalPath,
149
+ status: indexable ? 'pending' : 'ready',
150
+ });
151
+ store.raw.q(`UPDATE nodes SET sha256 = ? WHERE id = ?`).run(hash.digest('hex'), docId);
152
+ if (indexable && pipeline) pipeline.enqueue(docId);
153
+ // Office 文件先把原版式预览排在后台(失败不影响上传本身)
154
+ if (previewer?.supports?.(ext) && previewer.available?.()) {
155
+ previewer.ensure(node, { priority: 'background' })
156
+ .catch((error) => logger?.warn?.(`[knowledge-base] preview prewarm failed for ${filename}: ${error?.message || error}`));
157
+ }
158
+ return sendJson(res, 200, {
159
+ ok: true,
160
+ node: store.getNode(docId),
161
+ indexable,
162
+ notice: indexable ? '' : '这是一张图片,只做预览,不进正文索引。',
163
+ });
164
+ }
165
+
166
+ const routes = [];
167
+
168
+ routes.push({
169
+ kind: 'exact',
170
+ path: `${API_BASE}/state`,
171
+ handler: (req, res) => {
172
+ if (!guard(origin, req).ok) return fail(res, 403, 'forbidden');
173
+ const url = new URL(req.url ?? '/', 'http://local');
174
+ return sendJson(res, 200, stateBody(url.searchParams.get('kb') || ''));
175
+ },
176
+ });
177
+
178
+ routes.push({
179
+ kind: 'exact',
180
+ path: `${API_BASE}/node`,
181
+ handler: async (req, res) => {
182
+ if (req.method !== 'POST') return fail(res, 405, '只接受 POST');
183
+ if (!guard(origin, req).ok) return fail(res, 403, 'forbidden');
184
+ const body = await readBody(req);
185
+ if (!body.ok) return fail(res, 400, '请求体不是合法 JSON');
186
+ const { action } = body.value;
187
+ const now = nowMs();
188
+ try {
189
+ if (action === 'create-kb') {
190
+ const kb = store.createKb({ id: newId('k'), name: sanitizeName(body.value.name, '新知识库'), now });
191
+ return sendJson(res, 200, { ...stateBody(kb.id), created: kb });
192
+ }
193
+ if (action === 'rename-kb') {
194
+ store.renameKb(String(body.value.id), sanitizeName(body.value.name, '知识库'), now);
195
+ return sendJson(res, 200, stateBody(String(body.value.id)));
196
+ }
197
+ if (action === 'delete-kb') {
198
+ store.deleteKb(String(body.value.id));
199
+ return sendJson(res, 200, stateBody(''));
200
+ }
201
+ if (action === 'create') {
202
+ const kbId = String(body.value.kbId ?? '');
203
+ const parentId = body.value.parentId ? String(body.value.parentId) : null;
204
+ const kind = body.value.kind === 'folder' ? 'folder' : 'doc';
205
+ const node = store.createNode({
206
+ id: newId(kind === 'folder' ? 'f' : 'd'),
207
+ kbId,
208
+ parentId,
209
+ kind,
210
+ name: sanitizeName(body.value.name, kind === 'folder' ? '新建文件夹' : '新建文档'),
211
+ now,
212
+ status: 'ready',
213
+ });
214
+ return sendJson(res, 200, { ok: true, node, nodes: store.listNodes(kbId) });
215
+ }
216
+ if (action === 'rename') {
217
+ const node = store.getNode(String(body.value.id));
218
+ if (!node) return fail(res, 404, '节点不存在');
219
+ store.renameNode(node.id, sanitizeName(body.value.name, node.name), now);
220
+ return sendJson(res, 200, { ok: true, nodes: store.listNodes(node.kbId) });
221
+ }
222
+ if (action === 'move') {
223
+ const node = store.getNode(String(body.value.id));
224
+ if (!node) return fail(res, 404, '节点不存在');
225
+ store.moveNode(node.id, body.value.parentId ? String(body.value.parentId) : null,
226
+ Number(body.value.index), now);
227
+ return sendJson(res, 200, { ok: true, nodes: store.listNodes(node.kbId) });
228
+ }
229
+ if (action === 'delete') {
230
+ const node = store.getNode(String(body.value.id));
231
+ if (!node) return fail(res, 404, '节点不存在');
232
+ const result = store.deleteNode(node.id);
233
+ return sendJson(res, 200, { ok: true, removed: result.removed, nodes: store.listNodes(node.kbId) });
234
+ }
235
+ return fail(res, 400, `未知操作 ${action}`);
236
+ } catch (error) {
237
+ logger?.warn?.(`[knowledge-base] node action ${action} failed: ${error instanceof Error ? error.message : String(error)}`);
238
+ return fail(res, 400, error instanceof Error ? error.message : '操作失败');
239
+ }
240
+ },
241
+ });
242
+
243
+ routes.push({
244
+ kind: 'exact',
245
+ path: `${API_BASE}/upload`,
246
+ handler: (req, res) => {
247
+ if (req.method !== 'POST') return fail(res, 405, '只接受 POST');
248
+ if (!guard(origin, req).ok) return fail(res, 403, 'forbidden');
249
+ return handleUpload(req, res).catch((error) => {
250
+ logger?.error?.('[knowledge-base] upload failed', error);
251
+ if (!res.headersSent) fail(res, 500, '上传失败');
252
+ });
253
+ },
254
+ });
255
+
256
+ routes.push({
257
+ kind: 'exact',
258
+ path: `${API_BASE}/search`,
259
+ handler: async (req, res) => {
260
+ if (!guard(origin, req).ok) return fail(res, 403, 'forbidden');
261
+ const url = new URL(req.url ?? '/', 'http://local');
262
+ const query = (url.searchParams.get('q') ?? '').trim();
263
+ const kb = url.searchParams.get('kb') ?? '';
264
+ const mode = url.searchParams.get('mode') === 'hybrid' ? 'hybrid' : 'keyword';
265
+ const limit = clampInt(url.searchParams.get('limit'), 1, 50, 20);
266
+ if (!query) return sendJson(res, 200, { ok: true, hits: [], mode, total: 0 });
267
+ try {
268
+ const result = await index.search({ query, kbIds: kb ? [kb] : [], limit, mode });
269
+ return sendJson(res, 200, { ok: true, ...result });
270
+ } catch (error) {
271
+ return fail(res, 500, `检索失败:${error instanceof Error ? error.message : String(error)}`);
272
+ }
273
+ },
274
+ });
275
+
276
+ routes.push({
277
+ kind: 'exact',
278
+ path: `${API_BASE}/dashboard`,
279
+ handler: (req, res) => {
280
+ if (!guard(origin, req).ok) return fail(res, 403, 'forbidden');
281
+ try {
282
+ const data = store.dashboard(nowMs());
283
+ return sendJson(res, 200, { ok: true, ...data, capabilities: capabilities() });
284
+ } catch (error) {
285
+ return fail(res, 500, `读取统计失败:${error instanceof Error ? error.message : String(error)}`);
286
+ }
287
+ },
288
+ });
289
+
290
+ routes.push({
291
+ kind: 'exact',
292
+ path: `${API_BASE}/settings`,
293
+ handler: async (req, res) => {
294
+ if (!guard(origin, req).ok) return fail(res, 403, 'forbidden');
295
+ if (req.method === 'GET') {
296
+ return sendJson(res, 200, {
297
+ ok: true,
298
+ embedding: settings.publicEmbedding(config?.embedding),
299
+ status: embedder.describe(),
300
+ stats: store.stats(),
301
+ });
302
+ }
303
+ if (req.method !== 'POST') return fail(res, 405, '只接受 GET / POST');
304
+ const body = await readBody(req);
305
+ if (!body.ok) return fail(res, 400, '请求体不是合法 JSON');
306
+ const patch = body.value.embedding && typeof body.value.embedding === 'object' ? body.value.embedding : body.value;
307
+ // 启用时必须能拼出请求地址
308
+ if (patch.enabled) {
309
+ const baseUrl = String(patch.baseUrl ?? '').trim();
310
+ if (!/^https?:\/\//i.test(baseUrl)) return fail(res, 400, '接口地址要以 http:// 或 https:// 开头');
311
+ if (!String(patch.model ?? '').trim()) return fail(res, 400, '要填模型名');
312
+ }
313
+ const saved = settings.saveEmbedding(patch);
314
+ if (!saved.ok) return fail(res, 500, '写入设置失败,检查一下磁盘权限');
315
+ return sendJson(res, 200, {
316
+ ok: true,
317
+ embedding: settings.publicEmbedding(config?.embedding),
318
+ status: embedder.describe(),
319
+ });
320
+ },
321
+ });
322
+
323
+ routes.push({
324
+ kind: 'exact',
325
+ path: `${API_BASE}/embedding-test`,
326
+ handler: async (req, res) => {
327
+ if (req.method !== 'POST') return fail(res, 405, '只接受 POST');
328
+ if (!guard(origin, req).ok) return fail(res, 403, 'forbidden');
329
+ const body = await readBody(req);
330
+ if (!body.ok) return fail(res, 400, '请求体不是合法 JSON');
331
+ const form = body.value && typeof body.value === 'object' ? body.value : {};
332
+ // 用「表单里正在填的值」测,不必先保存;key 没填就沿用已保存的
333
+ const saved = settings.embedding();
334
+ const probe = createEmbedder({
335
+ config: {
336
+ enabled: true,
337
+ baseUrl: typeof form.baseUrl === 'string' ? form.baseUrl : saved.baseUrl,
338
+ model: typeof form.model === 'string' ? form.model : saved.model,
339
+ apiKey: (typeof form.apiKey === 'string' && form.apiKey.trim()) ? form.apiKey.trim() : saved.apiKey,
340
+ },
341
+ logger,
342
+ });
343
+ try {
344
+ const result = await probe.probe();
345
+ // 探测失败也走 200:外层 ok 表示"请求处理成功",probe.ok 表示"接口通不通"
346
+ return sendJson(res, 200, { ok: true, probe: result });
347
+ } catch (error) {
348
+ return sendJson(res, 200, { ok: true, probe: { ok: false, error: error instanceof Error ? error.message : String(error) } });
349
+ }
350
+ },
351
+ });
352
+
353
+ routes.push({
354
+ kind: 'exact',
355
+ path: `${API_BASE}/purge-previews`,
356
+ handler: (req, res) => {
357
+ if (req.method !== 'POST') return fail(res, 405, '只接受 POST');
358
+ if (!guard(origin, req).ok) return fail(res, 403, 'forbidden');
359
+ let cleared = 0;
360
+ for (const row of store.raw.q(`SELECT id FROM nodes WHERE kind = 'doc'`).all()) {
361
+ const node = store.getNode(row.id);
362
+ if (node && previewer?.supports?.(node.ext)) {
363
+ previewer.invalidate(node);
364
+ cleared += 1;
365
+ }
366
+ }
367
+ return sendJson(res, 200, { ok: true, cleared });
368
+ },
369
+ });
370
+
371
+ routes.push({
372
+ kind: 'exact',
373
+ path: `${API_BASE}/reindex-all`,
374
+ handler: (req, res) => {
375
+ if (req.method !== 'POST') return fail(res, 405, '只接受 POST');
376
+ if (!guard(origin, req).ok) return fail(res, 403, 'forbidden');
377
+ const count = pipeline.reindexAll();
378
+ return sendJson(res, 200, { ok: true, queued: count });
379
+ },
380
+ });
381
+
382
+ routes.push({
383
+ kind: 'exact',
384
+ path: `${API_BASE}/ask`,
385
+ handler: async (req, res) => {
386
+ if (req.method !== 'POST') return fail(res, 405, '只接受 POST');
387
+ if (!guard(origin, req).ok) return fail(res, 403, 'forbidden');
388
+ const body = await readBody(req);
389
+ if (!body.ok) return fail(res, 400, '请求体不是合法 JSON');
390
+ const nodeId = String(body.value.docId ?? '');
391
+ const question = typeof body.value.question === 'string' ? body.value.question.trim() : '';
392
+ const node = nodeId ? store.getNode(nodeId) : null;
393
+ if (node && node.kind === 'doc') {
394
+ const crumb = store.breadcrumb(node.id);
395
+ const prompt = [
396
+ '请基于我的个人知识库回答。',
397
+ `文档:《${node.name}》(${crumb})`,
398
+ `docId: ${node.id}`,
399
+ '先用 kb_read 读这篇文档里相关的部分(必要时用 kb_search 定位),再回答;',
400
+ '回答里标注出处(文件名 + 章节或页码),不要编造文档里没有的内容。',
401
+ question ? `\n我的问题:${question}` : '\n我的问题:',
402
+ ].join('\n');
403
+ return sendJson(res, 200, { ok: true, prompt });
404
+ }
405
+ const kbId = String(body.value.kbId ?? '');
406
+ const kb = kbId ? store.getKb(kbId) : null;
407
+ const prompt = [
408
+ kb ? `请基于我的个人知识库「${kb.name}」回答。` : '请基于我的个人知识库回答。',
409
+ kb ? `kbId: ${kb.id}(在 kb_search 的 kbIds 里传它)` : '先用 kb_list 看看有哪些知识库。',
410
+ '先用 kb_search 检索,再用 kb_read 读片段周围的正文,然后回答;标注出处,不要编造。',
411
+ question ? `\n我的问题:${question}` : '\n我的问题:',
412
+ ].join('\n');
413
+ return sendJson(res, 200, { ok: true, prompt });
414
+ },
415
+ });
416
+
417
+ // ── /doc?id=<id>&action=meta|text|raw|preview|reindex ─────────────────
418
+ // 说明:这一版 webServer 的前缀路由没有接管 /api 下的自定义前缀(会落到 API
419
+ // 网关并拿到 401),所以文档相关操作统一走一条 exact 路由 + 查询参数。
420
+ routes.push({
421
+ kind: 'exact',
422
+ path: `${API_BASE}/doc`,
423
+ handler: async (req, res) => {
424
+ const url = new URL(req.url ?? '/', 'http://local');
425
+ const action = url.searchParams.get('action') ?? '';
426
+ const id = url.searchParams.get('id') ?? '';
427
+ // 二进制预览要能被 <img>/<iframe> 直接取,而它们带不了自定义头:
428
+ // 这时改用一次性启动令牌(令牌只通过需要自定义头的 /state 下发)。
429
+ const byToken = (action === 'raw' || action === 'preview' || action === 'page' || action === 'thumb')
430
+ && Boolean(token) && url.searchParams.get('t') === token;
431
+ if (!byToken && !guard(origin, req).ok) return fail(res, 403, 'forbidden');
432
+ const node = id ? store.getNode(id) : null;
433
+ if (!node || node.kind !== 'doc') return fail(res, 404, '文档不存在');
434
+
435
+ if (action === 'text') {
436
+ const offset = clampInt(url.searchParams.get('offset'), 0, 100 * 1024 * 1024, 0);
437
+ const limit = clampInt(url.searchParams.get('limit'), 200, 40000, 8000);
438
+ const full = store.getText(node.id);
439
+ const end = Math.min(full.length, offset + limit);
440
+ return sendJson(res, 200, {
441
+ ok: true,
442
+ node,
443
+ breadcrumb: store.breadcrumb(node.id),
444
+ totalChars: full.length,
445
+ offset,
446
+ end,
447
+ text: full.slice(offset, end),
448
+ hasMore: end < full.length,
449
+ });
450
+ }
451
+
452
+ if (action === 'raw') {
453
+ const filePath = store.raw.q(`SELECT file_path AS filePath FROM nodes WHERE id = ?`).get(node.id)?.filePath;
454
+ if (!filePath || !fs.existsSync(filePath)) return fail(res, 404, '原始文件不见了');
455
+ const download = url.searchParams.get('download') === '1';
456
+ return serveFile(res, filePath, node.mime || 'application/octet-stream', {
457
+ download,
458
+ name: node.name,
459
+ cache: 'private, max-age=60',
460
+ });
461
+ }
462
+
463
+ // 逐页图片:界面自己画阅读器(不起浏览器 PDF 阅读器)
464
+ if (action === 'previewinfo') {
465
+ if (!previewer?.supports?.(node.ext)) return fail(res, 400, '这类文件没有逐页预览');
466
+ try {
467
+ const manifest = await previewer.ensurePages(node);
468
+ // 缩略图栏要用的低分辨率版本,顺手在后台准备好
469
+ previewer.ensureThumbs(node).catch(() => { /* 缩略图失败不影响正文 */ });
470
+ return sendJson(res, 200, {
471
+ ok: true,
472
+ pages: manifest.pages,
473
+ pageCount: manifest.pageCount,
474
+ truncated: Boolean(manifest.truncated),
475
+ dpi: manifest.dpi,
476
+ width: manifest.width,
477
+ height: manifest.height,
478
+ });
479
+ } catch (error) {
480
+ const code = error?.code === 'unavailable' ? 503 : 500;
481
+ const reason = error instanceof Error ? error.message : String(error);
482
+ logger?.warn?.(`[knowledge-base] page render failed for ${node.name}: ${reason}`);
483
+ return fail(res, code, reason);
484
+ }
485
+ }
486
+
487
+ if (action === 'page' || action === 'thumb') {
488
+ if (!previewer?.supports?.(node.ext)) return fail(res, 400, '这类文件没有逐页预览');
489
+ const page = clampInt(url.searchParams.get('n'), 1, 2000, 1);
490
+ const isThumb = action === 'thumb';
491
+ try {
492
+ let file = isThumb ? previewer.thumbFile(node, page) : previewer.pageFile(node, page);
493
+ if (!fs.existsSync(file)) {
494
+ await (isThumb ? previewer.ensureThumbs(node) : previewer.ensurePages(node));
495
+ file = isThumb ? previewer.thumbFile(node, page) : previewer.pageFile(node, page);
496
+ }
497
+ if (!fs.existsSync(file)) return fail(res, 404, `没有第 ${page} 页`);
498
+ return serveFile(res, file, 'image/png', { cache: 'private, max-age=3600' });
499
+ } catch (error) {
500
+ return fail(res, 500, error instanceof Error ? error.message : '渲染失败');
501
+ }
502
+ }
503
+
504
+ // 原版式预览:PDF/图片直接给原文件;Office 用宿主的 officeKit 转成 PDF 再看
505
+ if (action === 'preview') {
506
+ if (node.ext === 'pdf' || IMAGE_EXTENSIONS.has(node.ext)) {
507
+ const filePath = store.raw.q(`SELECT file_path AS filePath FROM nodes WHERE id = ?`).get(node.id)?.filePath;
508
+ if (!filePath || !fs.existsSync(filePath)) return fail(res, 404, '原始文件不见了');
509
+ return serveFile(res, filePath, node.mime || 'application/octet-stream', { cache: 'private, max-age=60' });
510
+ }
511
+ if (!previewer?.supports?.(node.ext)) {
512
+ return fail(res, 400, '这类文件没有原版式预览,请用文字阅读');
513
+ }
514
+ try {
515
+ const pdfPath = await previewer.ensure(node, { priority: 'foreground' });
516
+ return serveFile(res, pdfPath, 'application/pdf', { cache: 'no-store' });
517
+ } catch (error) {
518
+ const code = error?.code === 'unavailable' ? 503 : 500;
519
+ const reason = error instanceof Error ? error.message : String(error);
520
+ logger?.warn?.(`[knowledge-base] preview failed for ${node.name}: ${reason}`);
521
+ return fail(res, code, reason);
522
+ }
523
+ }
524
+
525
+ if (action === 'reindex' && req.method === 'POST') { if (!isIndexable(node.ext)) return fail(res, 400, '图片没有正文索引');
526
+ store.setDocStatus(node.id, 'pending', { error: null, updatedAt: nowMs() });
527
+ pipeline.enqueue(node.id);
528
+ return sendJson(res, 200, { ok: true, node: store.getNode(node.id) });
529
+ }
530
+
531
+ if (!action || action === 'meta') {
532
+ return sendJson(res, 200, {
533
+ ok: true,
534
+ node,
535
+ breadcrumb: store.breadcrumb(node.id),
536
+ stats: store.stats(),
537
+ });
538
+ }
539
+ return fail(res, 404, '未知的文档操作');
540
+ },
541
+ });
542
+
543
+ return { routes, origin };
544
+ }
545
+
546
+ export { API_BASE, sendText, sendBytes, safeOrigin };
@@ -0,0 +1,107 @@
1
+ // ============================================================================
2
+ // 插件自己的设置文件:$DSH_HOME/kb/settings.json(0600)
3
+ //
4
+ // 目前只放向量检索的配置,理由:改 YAML 要重载插件才生效,而这个东西用户会反复
5
+ // 试(换服务、换模型、填错 key)。放这里可以即改即用,且 KEY 不落到 patch 里。
6
+ // 优先级:settings.json > 插件 config.embedding。
7
+ // ============================================================================
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ /**
12
+ * 出厂的默认 embeddings 端点(只有地址和模型名,**没有任何密钥**)。
13
+ * 用户装上后在设置里只需要填 API Key + 勾选启用。
14
+ */
15
+ export const DEFAULT_EMBEDDING = {
16
+ baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
17
+ model: 'text-embedding-v4',
18
+ };
19
+
20
+ function clean(value) {
21
+ return typeof value === 'string' ? value.trim() : '';
22
+ }
23
+
24
+ function normalizeEmbedding(input) {
25
+ const raw = input && typeof input === 'object' ? input : {};
26
+ return {
27
+ enabled: Boolean(raw.enabled),
28
+ baseUrl: clean(raw.baseUrl).replace(/\/+$/, ''),
29
+ model: clean(raw.model),
30
+ apiKey: clean(raw.apiKey),
31
+ };
32
+ }
33
+
34
+ export function createSettingsStore({ root, logger }) {
35
+ const file = path.join(root, 'settings.json');
36
+
37
+ function readAll() {
38
+ try {
39
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
40
+ return raw && typeof raw === 'object' ? raw : {};
41
+ } catch {
42
+ return {};
43
+ }
44
+ }
45
+
46
+ function writeAll(next) {
47
+ try {
48
+ fs.writeFileSync(file, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
49
+ try { fs.chmodSync(file, 0o600); } catch { /* Windows 上可能不支持,忽略 */ }
50
+ return true;
51
+ } catch (error) {
52
+ logger?.warn?.(`[knowledge-base] 写设置失败:${error instanceof Error ? error.message : String(error)}`);
53
+ return false;
54
+ }
55
+ }
56
+
57
+ /** 读当前向量配置(未填过就是空值)。 */
58
+ function embedding() {
59
+ return normalizeEmbedding(readAll().embedding);
60
+ }
61
+
62
+ /** settings.json 里有没有存过 embedding(没存过就回落到插件 YAML 的配置)。 */
63
+ function hasSaved() {
64
+ const raw = readAll().embedding;
65
+ return Boolean(raw && typeof raw === 'object');
66
+ }
67
+
68
+ /**
69
+ * 保存向量配置。
70
+ * @param {object} patch - { enabled?, baseUrl?, model?, apiKey?, clearKey? }
71
+ */
72
+ function saveEmbedding(patch) {
73
+ const current = embedding();
74
+ const next = { ...current };
75
+ if (patch && typeof patch === 'object') {
76
+ if ('enabled' in patch) next.enabled = Boolean(patch.enabled);
77
+ if ('baseUrl' in patch) next.baseUrl = clean(patch.baseUrl).replace(/\/+$/, '');
78
+ if ('model' in patch) next.model = clean(patch.model);
79
+ if (patch.clearKey === true) next.apiKey = '';
80
+ else if (typeof patch.apiKey === 'string' && patch.apiKey.trim()) next.apiKey = patch.apiKey.trim();
81
+ }
82
+ const all = readAll();
83
+ all.embedding = next;
84
+ const ok = writeAll(all);
85
+ return { ok, embedding: next };
86
+ }
87
+
88
+ /** 给界面看的版本:key 只留尾号。 */
89
+ function publicEmbedding(fallback = {}) {
90
+ const saved = readAll().embedding;
91
+ const effective = saved && typeof saved === 'object' ? normalizeEmbedding(saved) : normalizeEmbedding(fallback);
92
+ const key = effective.apiKey || process.env.DSH_KB_EMBEDDING_KEY || '';
93
+ return {
94
+ enabled: effective.enabled,
95
+ // 没填过地址/模型就回落到出厂默认,用户只需要补 Key
96
+ baseUrl: effective.baseUrl || DEFAULT_EMBEDDING.baseUrl,
97
+ model: effective.model || DEFAULT_EMBEDDING.model,
98
+ defaultBaseUrl: DEFAULT_EMBEDDING.baseUrl,
99
+ defaultModel: DEFAULT_EMBEDDING.model,
100
+ hasKey: Boolean(key),
101
+ keyTail: key ? key.slice(-4) : '',
102
+ fromFile: Boolean(saved && typeof saved === 'object'),
103
+ };
104
+ }
105
+
106
+ return { file, embedding, hasSaved, saveEmbedding, publicEmbedding };
107
+ }