dsh-verbatim 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/LICENSE +1 -1
- package/README.en.md +24 -22
- package/README.md +24 -22
- package/bin/cli.mjs +2 -1
- package/bin/mcp-memory.mjs +130 -62
- package/client.js +8880 -8857
- package/cordis.patch.yml +1 -1
- package/docs/ARCHITECTURE.md +1 -1
- package/icon.svg +1 -1
- package/index.js +613 -2558
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +2 -3
- package/src/config/exclude-range.js +1 -1
- package/src/config/global-config.js +3 -1
- package/src/config/session-config.js +12 -10
- package/src/config/session-config.test.js +375 -375
- package/src/derive/fact.js +6 -6
- package/src/derive/gist.js +2 -1
- package/src/host/config-views.js +2 -0
- package/src/host/db-admin.js +78 -15
- package/src/host/panel-api.js +1109 -0
- package/src/host/panel-http.js +322 -0
- package/src/host/panel-search.js +236 -0
- package/src/host/panel-session-store.js +411 -0
- package/src/host/rebuild.js +11 -3
- package/src/host/scene-ops.js +75 -6
- package/src/host/session-sync.js +91 -0
- package/src/index.js +2 -1
- package/src/ingest/cli.js +8 -7
- package/src/ingest/export.js +28 -18
- package/src/ingest/package.json +1 -1
- package/src/ingest/reader.js +181 -7
- package/src/model/embedding.js +3 -2
- package/src/model/llm.js +3 -2
- package/src/model/rerank.js +7 -4
- package/src/pipeline.js +159 -763
- package/src/scene/link.js +4 -4
- package/src/scene/package.json +1 -1
- package/src/scene/split.js +11 -11
- package/src/search/_fixtures.js +1 -0
- package/src/search/bench.js +4 -2
- package/src/search/chunk.js +6 -4
- package/src/search/dedupe.js +8 -8
- package/src/search/indexer.js +889 -879
- package/src/search/note-rank.js +64 -12
- package/src/search/regression.test.js +2 -1
- package/src/search/rrf.js +11 -11
- package/src/search/session-shape.js +3 -1
- package/src/search/thread.js +8 -8
- package/src/search/vector-fallback.js +509 -0
- package/src/search/vector-hydrate.js +309 -0
- package/src/search/vector-math.js +125 -0
- package/src/search/vector-store.js +1065 -1598
- package/src/search/vector-store.test.js +30 -0
- package/src/search/window.js +8 -8
- package/src/store/db.js +803 -715
- package/src/store/repo-extras-meta.js +430 -0
- package/src/store/repo-extras-search.js +580 -0
- package/src/store/repo.js +1024 -2133
- package/src/store/repo.test.js +39 -1
- package/src/store/schema.sql +15 -1
- package/src/tools/format.js +594 -503
- package/src/tools/index.js +7 -15
- package/src/tools/memory-forget.js +43 -32
- package/src/tools/memory-remember.js +11 -7
- package/src/tools/memory-search.js +721 -2206
- package/src/tools/remember-forget.test.js +19 -0
- package/src/tools/scope.js +7 -6
- package/src/tools/search-render.js +502 -0
- package/src/tools/time-route.js +71 -66
- package/src/tools/vector-route.js +655 -0
- package/sessions/qqb-p-0000000000-00000000000000000000000000000000.json +0 -12
package/index.js
CHANGED
|
@@ -1,2558 +1,613 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
'
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
]);
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
const
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
const
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
if (
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
const
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
return
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
const
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
};
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
try {
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
const key = hasEmbeddingKey();
|
|
615
|
-
const vecLoaded = handle.hasVec === true;
|
|
616
|
-
|
|
617
|
-
// ③ 一致性判定
|
|
618
|
-
const consistent = models.length <= 1; // 库里没混模型
|
|
619
|
-
const top = models[0] ?? null;
|
|
620
|
-
const modelMatch = configured === null ? null
|
|
621
|
-
: (top !== null && top.model === configured.model && top.dim === configured.dim);
|
|
622
|
-
|
|
623
|
-
const coverage = totalMsgs > 0 ? indexed / totalMsgs : 0;
|
|
624
|
-
const MIN_COVERAGE = 0.5;
|
|
625
|
-
|
|
626
|
-
let state;
|
|
627
|
-
let reason;
|
|
628
|
-
if (!key) {
|
|
629
|
-
state = 'disabled';
|
|
630
|
-
reason = '语义搜索未启用:没有配 embedding 的 API Key(去设置页填,或把服务类型改成「本地」)。时间轴与关键词检索照常可用。';
|
|
631
|
-
} else if (models.length > 1) {
|
|
632
|
-
// **混用**:两种模型的向量空间不可比,混算不报错但结果无意义 —— 必须先重建
|
|
633
|
-
state = 'mixed';
|
|
634
|
-
reason = `库里有 ${models.length} 套向量(${models.map((m) => `${m.model} ${m.count} 条`).join(' / ')})。`
|
|
635
|
-
+ '不同模型的向量不可比,语义搜索现在不可用;重建一次就好(原文不会动)。';
|
|
636
|
-
} else if (indexed === 0) {
|
|
637
|
-
state = 'empty';
|
|
638
|
-
reason = `语义搜索还没建索引(0 / ${totalMsgs} 条)。点 [重建] 建一次就能用;在那之前检索只走关键词和时间轴,不会白跑 embedding。`;
|
|
639
|
-
} else if (modelMatch === false) {
|
|
640
|
-
// **模型换了但没重建**:这之前显示「正常」,实际每次查询都抛 vec:err
|
|
641
|
-
state = 'mismatch';
|
|
642
|
-
reason = `索引是用 ${top.model} 建的,现在配置的是 ${configured?.model ?? '(未配置)'}。`
|
|
643
|
-
+ '两者不是同一个模型,语义搜索用不了 —— 用新模型重建一次就行(原文不会动)。';
|
|
644
|
-
} else if (coverage < MIN_COVERAGE) {
|
|
645
|
-
state = 'partial';
|
|
646
|
-
reason = `语义搜索的索引只覆盖了 ${indexed} / ${totalMsgs} 条(${(coverage * 100).toFixed(1)}%)。`
|
|
647
|
-
+ '覆盖率太低时语义召回会系统性偏向已索引的部分,所以这时不跑语义路;点 [重建] 可以补全。';
|
|
648
|
-
} else if (!vecLoaded) {
|
|
649
|
-
state = 'degraded';
|
|
650
|
-
reason = 'sqlite-vec 加载失败,已降级为暴力余弦(功能等价、结果一致,只是稍慢)。';
|
|
651
|
-
} else {
|
|
652
|
-
state = 'ok';
|
|
653
|
-
reason = '语义检索可用。';
|
|
654
|
-
}
|
|
655
|
-
|
|
656
|
-
let pending = 0;
|
|
657
|
-
try {
|
|
658
|
-
pending = typeof extras?.vecMeta?.countPending === 'function'
|
|
659
|
-
? extras.vecMeta.countPending({ sessionId })
|
|
660
|
-
: Math.max(0, totalMsgs - indexed);
|
|
661
|
-
} catch {
|
|
662
|
-
pending = Math.max(0, totalMsgs - indexed);
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
let windowTotal = 0;
|
|
666
|
-
let windowPending = 0;
|
|
667
|
-
const windowKinds = { window: 0, exchange: 0, thread: 0 };
|
|
668
|
-
try {
|
|
669
|
-
windowTotal = typeof extras?.window?.count === 'function' ? extras.window.count({ sessionId }) : 0;
|
|
670
|
-
windowPending = typeof extras?.window?.countPending === 'function' ? extras.window.countPending({ sessionId }) : 0;
|
|
671
|
-
if (windowTotal > 0) {
|
|
672
|
-
const kRows = db.prepare(
|
|
673
|
-
"SELECT COALESCE(kind, 'window') AS kind, COUNT(*) AS n FROM window WHERE session_id = ? GROUP BY COALESCE(kind, 'window')",
|
|
674
|
-
).all(sessionId);
|
|
675
|
-
for (const r of kRows) {
|
|
676
|
-
const k = r.kind === 'exchange' || r.kind === 'thread' ? r.kind : 'window';
|
|
677
|
-
windowKinds[k] += Number(r.n ?? 0);
|
|
678
|
-
}
|
|
679
|
-
}
|
|
680
|
-
} catch {
|
|
681
|
-
windowTotal = 0;
|
|
682
|
-
windowPending = 0;
|
|
683
|
-
}
|
|
684
|
-
const windowIndexed = Math.max(0, windowTotal - windowPending);
|
|
685
|
-
|
|
686
|
-
return {
|
|
687
|
-
// 兼容旧字段(面板和测试都读 model/dim)
|
|
688
|
-
model: top?.model ?? null,
|
|
689
|
-
dim: top?.dim ?? null,
|
|
690
|
-
models, // 全部模型分组
|
|
691
|
-
configured, // 当前配置
|
|
692
|
-
consistent, // 库里没混模型
|
|
693
|
-
modelMatch, // 库里 == 当前配置(null = 不知道)
|
|
694
|
-
indexed,
|
|
695
|
-
total: totalMsgs,
|
|
696
|
-
pending,
|
|
697
|
-
coverage,
|
|
698
|
-
state,
|
|
699
|
-
reason,
|
|
700
|
-
hasVec: vecLoaded,
|
|
701
|
-
hasKey: key,
|
|
702
|
-
windows: {
|
|
703
|
-
total: windowTotal,
|
|
704
|
-
indexed: windowIndexed,
|
|
705
|
-
pending: windowPending,
|
|
706
|
-
kinds: windowKinds,
|
|
707
|
-
},
|
|
708
|
-
};
|
|
709
|
-
}
|
|
710
|
-
|
|
711
|
-
/* ───────────────────────── 空态/限制说明(B7 的诚实原则) ───────────────────────── */
|
|
712
|
-
|
|
713
|
-
/** note 表有没有 session_id 列(v6 起已加;保留探测以兼容未迁移的 v5 老库) */
|
|
714
|
-
let noteColsCache = null;
|
|
715
|
-
function noteHasSessionColumn() {
|
|
716
|
-
if (noteColsCache !== null) return noteColsCache;
|
|
717
|
-
try {
|
|
718
|
-
noteColsCache = db
|
|
719
|
-
.prepare('PRAGMA table_info(note)')
|
|
720
|
-
.all()
|
|
721
|
-
.some((c) => c.name === 'session_id');
|
|
722
|
-
} catch {
|
|
723
|
-
noteColsCache = false;
|
|
724
|
-
}
|
|
725
|
-
return noteColsCache;
|
|
726
|
-
}
|
|
727
|
-
|
|
728
|
-
function buildWarnings() {
|
|
729
|
-
const warnings = [];
|
|
730
|
-
if (!noteHasSessionColumn()) {
|
|
731
|
-
warnings.push(
|
|
732
|
-
'note 表没有 session_id 列(老库还没迁移到 v6),「TA的笔记」只能显示全库笔记,暂时无法按会话过滤。'
|
|
733
|
-
+ '其余统计(条数/字数/场景/压缩/撤回)都只算当前会话。',
|
|
734
|
-
);
|
|
735
|
-
} else {
|
|
736
|
-
// 遗留笔记(v6 之前写的,没有会话归属)不属于任何对话,面板按会话过滤时看不到。
|
|
737
|
-
// 这个数字要说出来,否则用户会以为"我记的笔记没了"。
|
|
738
|
-
try {
|
|
739
|
-
const orphan = Number(
|
|
740
|
-
stmt('SELECT COUNT(*) AS c FROM note WHERE deleted_at IS NULL AND session_id IS NULL').get().c ?? 0,
|
|
741
|
-
);
|
|
742
|
-
if (orphan > 0) {
|
|
743
|
-
warnings.push(
|
|
744
|
-
`有 ${orphan} 条 v6 之前写下的遗留笔记没有会话归属(session_id 为空),`
|
|
745
|
-
+ '它们不属于任何一个对话,所以不在这个面板里显示 —— 不是丢了。',
|
|
746
|
-
);
|
|
747
|
-
}
|
|
748
|
-
} catch {
|
|
749
|
-
// 查询失败就不提,不影响主统计
|
|
750
|
-
}
|
|
751
|
-
}
|
|
752
|
-
if (!hasEmbeddingKey()) {
|
|
753
|
-
warnings.push(
|
|
754
|
-
`语义搜索未启用(缺 embedding API Key)。时间轴与关键词检索不受影响。`,
|
|
755
|
-
);
|
|
756
|
-
} else if (handle.hasVec !== true) {
|
|
757
|
-
warnings.push('sqlite-vec 未加载,向量检索降级为暴力余弦(结果一致、稍慢)。');
|
|
758
|
-
}
|
|
759
|
-
return warnings;
|
|
760
|
-
}
|
|
761
|
-
|
|
762
|
-
const {
|
|
763
|
-
recentTasks,
|
|
764
|
-
assertSafeToReset,
|
|
765
|
-
makeEmbeddingProvider,
|
|
766
|
-
findRunningTask,
|
|
767
|
-
startRebuildTask,
|
|
768
|
-
getTask,
|
|
769
|
-
} = createRebuildManager({
|
|
770
|
-
handle,
|
|
771
|
-
repo,
|
|
772
|
-
extras,
|
|
773
|
-
dbPath,
|
|
774
|
-
embCfg,
|
|
775
|
-
llmCfg,
|
|
776
|
-
hasEmbeddingKey,
|
|
777
|
-
hasLlmReady,
|
|
778
|
-
getHostLlm,
|
|
779
|
-
noteHasSessionColumn,
|
|
780
|
-
syncSession,
|
|
781
|
-
logger,
|
|
782
|
-
PanelError,
|
|
783
|
-
});
|
|
784
|
-
|
|
785
|
-
/* ══════════════════════════════ 20 个 RPC ══════════════════════════════ */
|
|
786
|
-
|
|
787
|
-
/**
|
|
788
|
-
* E1:需要会话范围的方法必须带 sessionId,缺了报错 —— **绝不默认全库**。
|
|
789
|
-
* @param {string} method
|
|
790
|
-
* @param {object} params
|
|
791
|
-
* @returns {string}
|
|
792
|
-
*/
|
|
793
|
-
function requireSession(method, params) {
|
|
794
|
-
const raw = params?.sessionId;
|
|
795
|
-
if (typeof raw !== 'string' || !raw.trim()) {
|
|
796
|
-
throw new PanelError(
|
|
797
|
-
'SESSION_ID_REQUIRED',
|
|
798
|
-
`panel.${method} 必须带 sessionId(D-014:一个对话一个面板)。`
|
|
799
|
-
+ '不带 sessionId 会把别的会话的数据混进来 —— 这正是旧 /verbatim-api/stats 的 bug,不再允许。',
|
|
800
|
-
400,
|
|
801
|
-
);
|
|
802
|
-
}
|
|
803
|
-
try {
|
|
804
|
-
return assertSessionId(raw);
|
|
805
|
-
} catch (error) {
|
|
806
|
-
throw new PanelError('BAD_SESSION_ID', error?.message ?? String(error), 400);
|
|
807
|
-
}
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
/** 可选 sessionId(按 id 定位的方法用它做跨会话保护;不传 = 全库管理视角) */
|
|
811
|
-
function optionalSession(method, params) {
|
|
812
|
-
const raw = params?.sessionId;
|
|
813
|
-
if (raw === undefined || raw === null || raw === '') return null;
|
|
814
|
-
if (typeof raw !== 'string') {
|
|
815
|
-
throw new PanelError('BAD_SESSION_ID', `panel.${method} 的 sessionId 必须是非空字符串`, 400);
|
|
816
|
-
}
|
|
817
|
-
try {
|
|
818
|
-
return assertSessionId(raw);
|
|
819
|
-
} catch (error) {
|
|
820
|
-
throw new PanelError('BAD_SESSION_ID', error?.message ?? String(error), 400);
|
|
821
|
-
}
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
/**
|
|
825
|
-
* `panel.status({ sessionId })` → { enabled, stats, vector }(B3~B7)
|
|
826
|
-
*
|
|
827
|
-
* - enabled 只有 record / tools 两个开关(D-166:autoRecall 不进面板)
|
|
828
|
-
* - stats 只算**这个会话**(A2),compactedMsgs 是面板最核心的数字(B4)
|
|
829
|
-
* - rewindedMsgs 从原始日志重新数(库里是物理删除的,查不到,B5)
|
|
830
|
-
* - vector.state 明确区分 ok / degraded / disabled(B6/B7)
|
|
831
|
-
*/
|
|
832
|
-
function status(params) {
|
|
833
|
-
const sessionId = requireSession('status', params);
|
|
834
|
-
const cfg = readSessionConfig(sessionId);
|
|
835
|
-
const agg = sessionAggregate(sessionId);
|
|
836
|
-
const log = safeLoadLog(sessionId);
|
|
837
|
-
const rewindedMsgs = log ? Number(log.stats.rewoundCount ?? 0) : null;
|
|
838
|
-
const rewindedChars = log ? Number(log.stats.rewoundChars ?? 0) : null;
|
|
839
|
-
let excludedMsgs = 0;
|
|
840
|
-
for (const m of agg.msgs) {
|
|
841
|
-
if (m.excluded === 1) excludedMsgs += 1;
|
|
842
|
-
}
|
|
843
|
-
const deletedNotesCount = noteHasSessionColumn()
|
|
844
|
-
? extras.note.count({ sessionId, deletedOnly: true })
|
|
845
|
-
: extras.note.count({ deletedOnly: true });
|
|
846
|
-
let scenesWithGist = 0;
|
|
847
|
-
let llmGistScenes = 0;
|
|
848
|
-
try {
|
|
849
|
-
scenesWithGist = Number(
|
|
850
|
-
stmt("SELECT COUNT(*) AS c FROM scene WHERE session_id = ? AND gist IS NOT NULL AND TRIM(gist) != ''").get(sessionId)?.c ?? 0,
|
|
851
|
-
);
|
|
852
|
-
llmGistScenes = Number(
|
|
853
|
-
stmt("SELECT COUNT(*) AS c FROM scene WHERE session_id = ? AND gist_source = 'llm'").get(sessionId)?.c ?? 0,
|
|
854
|
-
);
|
|
855
|
-
} catch {
|
|
856
|
-
scenesWithGist = 0;
|
|
857
|
-
llmGistScenes = 0;
|
|
858
|
-
}
|
|
859
|
-
const llmGistRatio = agg.sceneCount > 0 ? Math.round((llmGistScenes / agg.sceneCount) * 100) : 0;
|
|
860
|
-
const llmConf = llmCfg();
|
|
861
|
-
|
|
862
|
-
return {
|
|
863
|
-
enabled: { record: cfg.record === true, tools: cfg.tools === true },
|
|
864
|
-
excludeRanges: cfg.excludeRanges,
|
|
865
|
-
stats: {
|
|
866
|
-
totalMsgs: agg.totalMsgs,
|
|
867
|
-
totalChars: agg.totalChars,
|
|
868
|
-
startAt: agg.startAt,
|
|
869
|
-
compactedMsgs: agg.compactedMsgs,
|
|
870
|
-
compactedChars: agg.compactedChars,
|
|
871
|
-
rewindedMsgs,
|
|
872
|
-
rewindedChars,
|
|
873
|
-
excludedMsgs,
|
|
874
|
-
deletedNotesCount,
|
|
875
|
-
sceneCount: agg.sceneCount,
|
|
876
|
-
scenesWithGist,
|
|
877
|
-
llmGistScenes,
|
|
878
|
-
llmGistRatio,
|
|
879
|
-
dayCount: agg.dayCount,
|
|
880
|
-
},
|
|
881
|
-
vector: vectorStatus(sessionId, agg.totalMsgs),
|
|
882
|
-
llm: {
|
|
883
|
-
ready: hasLlmReady(),
|
|
884
|
-
enabled: llmConf.enabled,
|
|
885
|
-
mode: llmConf.mode,
|
|
886
|
-
model: llmConf.model,
|
|
887
|
-
},
|
|
888
|
-
sessionId,
|
|
889
|
-
dbPath,
|
|
890
|
-
hasVec: handle.hasVec === true,
|
|
891
|
-
warnings: buildWarnings(),
|
|
892
|
-
tasks: recentTasks(),
|
|
893
|
-
};
|
|
894
|
-
}
|
|
895
|
-
|
|
896
|
-
/**
|
|
897
|
-
* `panel.timeline({ sessionId, from?, to?, limit? })`
|
|
898
|
-
* → [{ date, msgCount, sceneCount, chars, scenes: [{ id, startAt, endAt, msgCount, compacted }] }]
|
|
899
|
-
*
|
|
900
|
-
* 按天分组,默认最近 7 天(PANEL §3.4「默认展开最近 7 天」)。
|
|
901
|
-
* `limit` 是**天数**,不是消息数。
|
|
902
|
-
*/
|
|
903
|
-
function timeline(params) {
|
|
904
|
-
const sessionId = requireSession('timeline', params);
|
|
905
|
-
const limit = intParam(params.limit, 'limit', { def: 7, min: 1, max: 100 });
|
|
906
|
-
const from = instantParam(params.from, 'from', 0);
|
|
907
|
-
const to = instantParam(params.to, 'to', TIME_MAX);
|
|
908
|
-
if (to <= from) throw new PanelError('BAD_RANGE', `to(${to})必须大于 from(${from})`, 400);
|
|
909
|
-
|
|
910
|
-
const msgs = repo.msgsByTimeRange(sessionId, from, to, ALL_ROWS, true);
|
|
911
|
-
const scenes = repo.scenesByTimeRange(sessionId, from, to, ALL_ROWS);
|
|
912
|
-
|
|
913
|
-
/** @type {Map<string, {date:string, msgCount:number, sceneCount:number, chars:number, scenes:object[]}>} */
|
|
914
|
-
const byDay = new Map();
|
|
915
|
-
const ensure = (date) => {
|
|
916
|
-
let d = byDay.get(date);
|
|
917
|
-
if (!d) {
|
|
918
|
-
d = { date, msgCount: 0, sceneCount: 0, pendingMsgs: 0, chars: 0, scenes: [] };
|
|
919
|
-
byDay.set(date, d);
|
|
920
|
-
}
|
|
921
|
-
return d;
|
|
922
|
-
};
|
|
923
|
-
|
|
924
|
-
for (const m of msgs) {
|
|
925
|
-
const d = ensure(dayKeyInZone(m.at));
|
|
926
|
-
d.msgCount += 1;
|
|
927
|
-
d.chars += m.text.length;
|
|
928
|
-
if (m.sceneId === null || m.sceneId === undefined) {
|
|
929
|
-
d.pendingMsgs += 1;
|
|
930
|
-
}
|
|
931
|
-
}
|
|
932
|
-
for (const s of scenes) {
|
|
933
|
-
// 场景归到「它在查询区间内的第一天」(不是 startAt 那天):
|
|
934
|
-
// 一场可能跨午夜(11-15 18:25 → 11-16 04:35),如果按 startAt 归组,
|
|
935
|
-
// from=11-16 时会在 11-15 凭空造出一个 msgCount=0 的天,看起来像 bug。
|
|
936
|
-
const day = dayKeyInZone(Math.max(s.startAt, from));
|
|
937
|
-
const d = ensure(day);
|
|
938
|
-
d.scenes.push({
|
|
939
|
-
id: s.id,
|
|
940
|
-
startAt: s.startAt,
|
|
941
|
-
endAt: s.endAt,
|
|
942
|
-
msgCount: s.msgCount,
|
|
943
|
-
gist: gistHeadline(s.gist, 42),
|
|
944
|
-
gistSource: s.gistSource ?? null,
|
|
945
|
-
locked: s.locked === 1,
|
|
946
|
-
// 这一场里有没有被压缩掉的(D-141:压缩的内容必须还在库里)
|
|
947
|
-
compacted: s.crossesCompaction === 1 || s.outOfSurfaceCount > 0,
|
|
948
|
-
});
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
const days = [...byDay.values()]
|
|
952
|
-
.sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0))
|
|
953
|
-
.slice(0, limit);
|
|
954
|
-
for (const d of days) {
|
|
955
|
-
d.scenes.sort((a, b) => a.startAt - b.startAt);
|
|
956
|
-
d.sceneCount = d.scenes.length;
|
|
957
|
-
}
|
|
958
|
-
return days;
|
|
959
|
-
}
|
|
960
|
-
|
|
961
|
-
/**
|
|
962
|
-
* `panel.sceneDetail({ sceneId })`
|
|
963
|
-
* → { startAt, endAt, msgs: [{ id, at, speaker, text, inSurface }], leadIn }
|
|
964
|
-
*
|
|
965
|
-
* 按 id 定位,不需要 sessionId(E1 豁免)。
|
|
966
|
-
*/
|
|
967
|
-
function sceneDetail(params) {
|
|
968
|
-
const sceneId = intParam(params.sceneId, 'sceneId', { min: 1 });
|
|
969
|
-
const scene = repo.sceneById(sceneId);
|
|
970
|
-
if (!scene) throw new PanelError('SCENE_NOT_FOUND', `没有 id=${sceneId} 的场景`, 404);
|
|
971
|
-
|
|
972
|
-
// includeExcluded=true:核对时被排除的那段也要看得见(不然会以为"没记")
|
|
973
|
-
const rawMsgs = repo.msgsByScene(sceneId, true);
|
|
974
|
-
const mediaByMsg = extras?.media?.byMsgIds ? extras.media.byMsgIds(rawMsgs.map((m) => m.id)) : new Map();
|
|
975
|
-
const msgs = rawMsgs.map((m) => ({
|
|
976
|
-
id: m.id,
|
|
977
|
-
at: m.at,
|
|
978
|
-
speaker: m.speaker,
|
|
979
|
-
text: m.text,
|
|
980
|
-
inSurface: m.inSurface,
|
|
981
|
-
excluded: m.excluded ?? 0,
|
|
982
|
-
media: mediaByMsg.get(Number(m.id)) ?? [],
|
|
983
|
-
}));
|
|
984
|
-
|
|
985
|
-
let leadIn = null;
|
|
986
|
-
if (scene.leadIn !== null && scene.leadIn !== undefined) {
|
|
987
|
-
try {
|
|
988
|
-
leadIn = JSON.parse(scene.leadIn);
|
|
989
|
-
} catch {
|
|
990
|
-
leadIn = scene.leadIn; // 老数据可能不是 JSON,原样给出,别让面板崩
|
|
991
|
-
}
|
|
992
|
-
}
|
|
993
|
-
|
|
994
|
-
return {
|
|
995
|
-
sceneId: scene.id,
|
|
996
|
-
sessionId: scene.sessionId,
|
|
997
|
-
startAt: scene.startAt,
|
|
998
|
-
endAt: scene.endAt,
|
|
999
|
-
msgCount: scene.msgCount,
|
|
1000
|
-
precededBy: scene.precededBy ?? null,
|
|
1001
|
-
followedBy: scene.followedBy ?? null,
|
|
1002
|
-
locked: scene.locked === 1,
|
|
1003
|
-
gist: gistHeadline(scene.gist, 60),
|
|
1004
|
-
gistSource: scene.gistSource ?? null,
|
|
1005
|
-
compacted: scene.crossesCompaction === 1 || scene.outOfSurfaceCount > 0,
|
|
1006
|
-
msgs,
|
|
1007
|
-
leadIn,
|
|
1008
|
-
};
|
|
1009
|
-
}
|
|
1010
|
-
|
|
1011
|
-
/**
|
|
1012
|
-
* `panel.notes({ sessionId, limit?, offset? })` → [{ id, content, about, at }]
|
|
1013
|
-
*
|
|
1014
|
-
* A2 会话隔离:`note` 表从 v6 起有 `session_id` 列,按会话过滤(TA记的是
|
|
1015
|
-
* 「在这个对话里记的」,面板也是「一个对话一个面板」)。
|
|
1016
|
-
* 老库(v5 及更早、还没迁移完)没有这一列时才退回全库,并在 warnings 里明说。
|
|
1017
|
-
*/
|
|
1018
|
-
function notes(params) {
|
|
1019
|
-
const sessionId = requireSession('notes', params);
|
|
1020
|
-
const limit = intParam(params.limit, 'limit', { def: 100, min: 1, max: 500 });
|
|
1021
|
-
const offset = intParam(params.offset, 'offset', { def: 0, min: 0, max: 1_000_000 });
|
|
1022
|
-
|
|
1023
|
-
const rows = noteHasSessionColumn()
|
|
1024
|
-
? extras.note.list({ sessionId, limit, offset })
|
|
1025
|
-
: extras.note.list({ limit, offset });
|
|
1026
|
-
return rows.map((r) => ({
|
|
1027
|
-
id: r.id,
|
|
1028
|
-
content: r.content,
|
|
1029
|
-
about: r.about ?? null,
|
|
1030
|
-
at: r.at,
|
|
1031
|
-
}));
|
|
1032
|
-
}
|
|
1033
|
-
|
|
1034
|
-
/**
|
|
1035
|
-
* `panel.deletedNotes({ sessionId, limit?, offset? })` → { items, total }
|
|
1036
|
-
* 回收站:仅列该会话已被软删、仍在 30 天保留期内的笔记,并在读取前顺手清理过期条目。
|
|
1037
|
-
*/
|
|
1038
|
-
function deletedNotes(params) {
|
|
1039
|
-
const NOTE_RETENTION_MS = 30 * 86_400_000;
|
|
1040
|
-
const sessionId = requireSession('deletedNotes', params);
|
|
1041
|
-
const limit = intParam(params.limit, 'limit', { def: 50, min: 1, max: 500 });
|
|
1042
|
-
const offset = intParam(params.offset, 'offset', { def: 0, min: 0, max: 1_000_000 });
|
|
1043
|
-
const hasSessionCol = noteHasSessionColumn();
|
|
1044
|
-
|
|
1045
|
-
try {
|
|
1046
|
-
if (hasSessionCol) extras.note.purgeExpired(NOTE_RETENTION_MS, Date.now(), { sessionId });
|
|
1047
|
-
else extras.note.purgeExpired(NOTE_RETENTION_MS, Date.now());
|
|
1048
|
-
} catch {
|
|
1049
|
-
// best-effort:清理失败不影响列回收站
|
|
1050
|
-
}
|
|
1051
|
-
|
|
1052
|
-
const filter = hasSessionCol ? { sessionId, deletedOnly: true } : { deletedOnly: true };
|
|
1053
|
-
const rows = extras.note.list({ ...filter, limit, offset });
|
|
1054
|
-
const total = extras.note.count(filter);
|
|
1055
|
-
return {
|
|
1056
|
-
items: rows.map((r) => ({
|
|
1057
|
-
id: r.id,
|
|
1058
|
-
content: r.content,
|
|
1059
|
-
about: r.about ?? null,
|
|
1060
|
-
at: r.at,
|
|
1061
|
-
deletedAt: r.deletedAt,
|
|
1062
|
-
expiresAt: r.deletedAt ? r.deletedAt + NOTE_RETENTION_MS : null,
|
|
1063
|
-
})),
|
|
1064
|
-
total,
|
|
1065
|
-
};
|
|
1066
|
-
}
|
|
1067
|
-
|
|
1068
|
-
/**
|
|
1069
|
-
* `panel.search({ sessionId, query, when?, limit?, includeExcluded? })`
|
|
1070
|
-
* 面板搜索:关键词路优先;命中 < 5 条且本会话向量可用时按需补语义路(RRF 融合)。
|
|
1071
|
-
*/
|
|
1072
|
-
async function search(params) {
|
|
1073
|
-
const sessionId = requireSession('search', params);
|
|
1074
|
-
const query = String(params.query ?? '').trim();
|
|
1075
|
-
if (!query) throw new PanelError('BAD_ARG', '缺少搜索关键词 query', 400);
|
|
1076
|
-
const limit = intParam(params.limit, 'limit', { def: 20, min: 1, max: 50 });
|
|
1077
|
-
const includeExcluded =
|
|
1078
|
-
params.includeExcluded === 'false' || params.includeExcluded === '0'
|
|
1079
|
-
? false
|
|
1080
|
-
: Boolean(params.includeExcluded);
|
|
1081
|
-
|
|
1082
|
-
const whenRaw = params.when === undefined || params.when === null ? '' : String(params.when).trim();
|
|
1083
|
-
let from;
|
|
1084
|
-
let to;
|
|
1085
|
-
if (whenRaw) {
|
|
1086
|
-
const win = resolveTimeWindow({ when: whenRaw });
|
|
1087
|
-
if (win.kind === 'unknown') {
|
|
1088
|
-
throw new PanelError(
|
|
1089
|
-
'BAD_WHEN',
|
|
1090
|
-
`看不懂的时间范围:${JSON.stringify(whenRaw)}(支持如 2026-11-09、11-09、2026-11、2026-11-09..2026-11-12 或 7d)`,
|
|
1091
|
-
400,
|
|
1092
|
-
);
|
|
1093
|
-
}
|
|
1094
|
-
if (Number.isFinite(win.from)) from = Number(win.from);
|
|
1095
|
-
if (Number.isFinite(win.to)) to = Number(win.to);
|
|
1096
|
-
}
|
|
1097
|
-
|
|
1098
|
-
const kwOpts = { sessionId, includeExcluded };
|
|
1099
|
-
if (from !== undefined) kwOpts.from = from;
|
|
1100
|
-
if (to !== undefined) kwOpts.to = to;
|
|
1101
|
-
const kwTotal = extras.search.countKeyword(query, kwOpts);
|
|
1102
|
-
|
|
1103
|
-
// (跨句多词关键词检索已移除:与 vec_window 语义召回重叠且易引入噪声)
|
|
1104
|
-
|
|
1105
|
-
// 场景摘要(scene.gist)同样参与检索:关键词匹配 + 语义路 vec_scene 匹配
|
|
1106
|
-
const sceneMatchMap = new Map();
|
|
1107
|
-
try {
|
|
1108
|
-
const likePat = `%${query.replace(/[\\%_]/g, '\\$&')}%`;
|
|
1109
|
-
const conds = ['session_id = ?', "gist IS NOT NULL AND gist LIKE ? ESCAPE '\\'"];
|
|
1110
|
-
const binds = [sessionId, likePat];
|
|
1111
|
-
if (!includeExcluded) conds.push('NOT (has_excluded = 1 AND excluded_count >= msg_count)');
|
|
1112
|
-
if (from !== undefined) { conds.push('end_at >= ?'); binds.push(from); }
|
|
1113
|
-
if (to !== undefined) { conds.push('start_at < ?'); binds.push(to); }
|
|
1114
|
-
const scKw = db.prepare(
|
|
1115
|
-
`SELECT id, start_at, end_at, msg_count, gist
|
|
1116
|
-
FROM scene
|
|
1117
|
-
WHERE ${conds.join(' AND ')}
|
|
1118
|
-
ORDER BY end_at DESC
|
|
1119
|
-
LIMIT 4`,
|
|
1120
|
-
).all(...binds);
|
|
1121
|
-
for (const s of scKw) {
|
|
1122
|
-
sceneMatchMap.set(Number(s.id), {
|
|
1123
|
-
id: Number(s.id),
|
|
1124
|
-
startAt: Number(s.start_at),
|
|
1125
|
-
endAt: Number(s.end_at),
|
|
1126
|
-
msgCount: Number(s.msg_count ?? 0),
|
|
1127
|
-
gist: String(s.gist ?? ''),
|
|
1128
|
-
sources: ['keyword'],
|
|
1129
|
-
score: null,
|
|
1130
|
-
});
|
|
1131
|
-
}
|
|
1132
|
-
} catch { /* best-effort */ }
|
|
1133
|
-
|
|
1134
|
-
const totalMsgs = extras.stats.get({ sessionId }).msgs;
|
|
1135
|
-
const vecStat = vectorStatus(sessionId, totalMsgs);
|
|
1136
|
-
let shown = [];
|
|
1137
|
-
let total = kwTotal;
|
|
1138
|
-
let used = false;
|
|
1139
|
-
let semanticNote = null;
|
|
1140
|
-
let semProvider = null;
|
|
1141
|
-
let semStore = null;
|
|
1142
|
-
let reranked = false;
|
|
1143
|
-
let rerankModel = null;
|
|
1144
|
-
let rerankError = null;
|
|
1145
|
-
|
|
1146
|
-
const canSemantic = hasEmbeddingKey() && (vecStat.state === 'ok' || vecStat.state === 'degraded');
|
|
1147
|
-
if (!canSemantic) {
|
|
1148
|
-
semanticNote = vecStat.reason;
|
|
1149
|
-
} else {
|
|
1150
|
-
if (vecStat.state === 'degraded') semanticNote = vecStat.reason;
|
|
1151
|
-
try {
|
|
1152
|
-
semProvider = await makeEmbeddingProvider();
|
|
1153
|
-
} catch (err) {
|
|
1154
|
-
semanticNote = `语义搜索失败,已降级为仅关键词:${err?.message ?? err}`;
|
|
1155
|
-
}
|
|
1156
|
-
}
|
|
1157
|
-
|
|
1158
|
-
let rerankerObj = null;
|
|
1159
|
-
const rr = rerankCfg();
|
|
1160
|
-
const rrApiKey = rr.apiKey || (rr.apiKeyEnv ? process.env[rr.apiKeyEnv] : '') || '';
|
|
1161
|
-
if (rr.enabled && rr.model && rr.baseUrl && (rr.mode === 'local' || rrApiKey)) {
|
|
1162
|
-
rerankerObj = createReranker({
|
|
1163
|
-
model: rr.model,
|
|
1164
|
-
baseURL: rr.baseUrl,
|
|
1165
|
-
apiKey: rrApiKey,
|
|
1166
|
-
local: rr.mode === 'local',
|
|
1167
|
-
});
|
|
1168
|
-
}
|
|
1169
|
-
|
|
1170
|
-
// 与 Agent 工具共用同一套 v15 检索内核(避免双套代码漂移)
|
|
1171
|
-
let trace = null;
|
|
1172
|
-
const { createSearchTool } = await import('./src/tools/memory-search.js');
|
|
1173
|
-
const searchTool = createSearchTool({
|
|
1174
|
-
handle,
|
|
1175
|
-
repo,
|
|
1176
|
-
extras,
|
|
1177
|
-
dshHome,
|
|
1178
|
-
sessionId,
|
|
1179
|
-
...(semProvider ? { provider: semProvider, semantic: true } : { semantic: false }),
|
|
1180
|
-
...(rerankerObj ? { reranker: rerankerObj, rerankTopN: rr.topN || 50 } : { rerank: false }),
|
|
1181
|
-
logger: { warn: (m) => logger.warn?.(m) },
|
|
1182
|
-
onResult: (tr) => { trace = tr; },
|
|
1183
|
-
});
|
|
1184
|
-
await searchTool.handler({
|
|
1185
|
-
query,
|
|
1186
|
-
...(whenRaw ? { when: whenRaw } : {}),
|
|
1187
|
-
limit,
|
|
1188
|
-
includeExcluded,
|
|
1189
|
-
scope: 'msg',
|
|
1190
|
-
}, { allowExcluded: true });
|
|
1191
|
-
|
|
1192
|
-
shown = Array.isArray(trace?.shownHits) ? trace.shownHits : [];
|
|
1193
|
-
total = Math.max(kwTotal, Array.isArray(trace?.hits) ? trace.hits.length : shown.length);
|
|
1194
|
-
if (trace?.meta) {
|
|
1195
|
-
used = canSemantic && Boolean(semProvider) && !trace.meta.vectorSkipped && !trace.meta.vectorError;
|
|
1196
|
-
if (trace.meta.vectorError) {
|
|
1197
|
-
used = false;
|
|
1198
|
-
semanticNote = `语义搜索失败,已降级为仅关键词:${trace.meta.vectorError}`;
|
|
1199
|
-
}
|
|
1200
|
-
reranked = Boolean(trace.meta.reranked);
|
|
1201
|
-
rerankModel = trace.meta.rerankModel ?? null;
|
|
1202
|
-
rerankError = trace.meta.rerankError ?? null;
|
|
1203
|
-
}
|
|
1204
|
-
|
|
1205
|
-
const matchedScenes = [...sceneMatchMap.values()]
|
|
1206
|
-
.sort((a, b) => (b.score ?? 0) - (a.score ?? 0) || (b.endAt - a.endAt))
|
|
1207
|
-
.slice(0, 4);
|
|
1208
|
-
|
|
1209
|
-
// 笔记高权重置顶召回(关键词 + vec_note 语义融合 + 分数门槛 >= 0.58)
|
|
1210
|
-
let matchedNotes = [];
|
|
1211
|
-
try {
|
|
1212
|
-
const noteCount = noteHasSessionColumn()
|
|
1213
|
-
? extras.note.count({ sessionId })
|
|
1214
|
-
: extras.note.count({});
|
|
1215
|
-
if (noteCount > 0) {
|
|
1216
|
-
if (!semStore && hasEmbeddingKey()) {
|
|
1217
|
-
try {
|
|
1218
|
-
if (!semProvider) semProvider = await makeEmbeddingProvider();
|
|
1219
|
-
const { createVectorStore } = await import('./src/search/vector-store.js');
|
|
1220
|
-
semStore = createVectorStore(handle, {
|
|
1221
|
-
dim: semProvider.dim,
|
|
1222
|
-
logger: { warn: (m) => logger.warn?.(`[verbatim] ${m}`) },
|
|
1223
|
-
});
|
|
1224
|
-
} catch { /* 装配失败则只走笔记关键词路 */ }
|
|
1225
|
-
}
|
|
1226
|
-
const nr = await searchRankedNotes({
|
|
1227
|
-
extras,
|
|
1228
|
-
sessionId: noteHasSessionColumn() ? sessionId : null,
|
|
1229
|
-
query,
|
|
1230
|
-
from: from ?? null,
|
|
1231
|
-
to: to ?? null,
|
|
1232
|
-
provider: semProvider,
|
|
1233
|
-
store: semStore,
|
|
1234
|
-
minScore: NOTE_MIN_SCORE_DEFAULT,
|
|
1235
|
-
limit: PINNED_NOTE_MAX_DEFAULT,
|
|
1236
|
-
});
|
|
1237
|
-
matchedNotes = nr.hits.map((n) => ({
|
|
1238
|
-
id: Number(n.id),
|
|
1239
|
-
content: String(n.content ?? ''),
|
|
1240
|
-
about: n.about ?? null,
|
|
1241
|
-
at: Number(n.at),
|
|
1242
|
-
score: typeof n.score === 'number' ? n.score : null,
|
|
1243
|
-
sources: Array.isArray(n.sources) ? n.sources : ['keyword'],
|
|
1244
|
-
}));
|
|
1245
|
-
}
|
|
1246
|
-
} catch { /* 笔记检索失败不影响主流程 */ }
|
|
1247
|
-
|
|
1248
|
-
return {
|
|
1249
|
-
query,
|
|
1250
|
-
total,
|
|
1251
|
-
matchedNotes,
|
|
1252
|
-
matchedScenes,
|
|
1253
|
-
hits: shown.map((r) => ({
|
|
1254
|
-
id: Number(r.id),
|
|
1255
|
-
seq: r.seq,
|
|
1256
|
-
at: r.at,
|
|
1257
|
-
speaker: r.speaker,
|
|
1258
|
-
text: r.text,
|
|
1259
|
-
inSurface: r.inSurface ?? 1,
|
|
1260
|
-
excluded: r.excluded ?? 0,
|
|
1261
|
-
sceneId: r.sceneId ?? null,
|
|
1262
|
-
sceneStartAt: r.sceneStartAt ?? null,
|
|
1263
|
-
sceneEndAt: r.sceneEndAt ?? null,
|
|
1264
|
-
sceneMsgCount: r.sceneMsgCount ?? null,
|
|
1265
|
-
sources: Array.isArray(r.sources) ? r.sources : ['keyword'],
|
|
1266
|
-
score: typeof r.score === 'number' ? r.score : null,
|
|
1267
|
-
chunk: r.chunk ?? null,
|
|
1268
|
-
window: r.window ?? null,
|
|
1269
|
-
...(r.focusExchange ? { focusExchange: r.focusExchange } : {}),
|
|
1270
|
-
...(Array.isArray(r.relatedTimeline) && r.relatedTimeline.length > 0
|
|
1271
|
-
? {
|
|
1272
|
-
relatedTimeline: r.relatedTimeline.map((rt) => ({
|
|
1273
|
-
at: rt.at ?? rt.sceneStartAt ?? null,
|
|
1274
|
-
sceneId: rt.sceneId ?? null,
|
|
1275
|
-
})),
|
|
1276
|
-
}
|
|
1277
|
-
: {}),
|
|
1278
|
-
})),
|
|
1279
|
-
semantic: { used, state: vecStat.state, note: semanticNote, reranked, rerankModel, rerankError },
|
|
1280
|
-
};
|
|
1281
|
-
}
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
/**
|
|
1285
|
-
* `panel.sample({ sessionId })` → { id, at, speaker, text, scene }
|
|
1286
|
-
*
|
|
1287
|
-
* 「抽一条」用于核对(C4)。该会话没有任何消息时返回 null(面板显示空态)。
|
|
1288
|
-
*/
|
|
1289
|
-
function sample(params) {
|
|
1290
|
-
const sessionId = requireSession('sample', params);
|
|
1291
|
-
const msgs = repo.msgsByTimeRange(sessionId, 0, TIME_MAX, ALL_ROWS, true);
|
|
1292
|
-
if (msgs.length === 0) return null;
|
|
1293
|
-
|
|
1294
|
-
// 均匀随机:每次「抽一条」都可能是不同的,人才能靠抽查建立信任
|
|
1295
|
-
const m = msgs[Math.floor(Math.random() * msgs.length)];
|
|
1296
|
-
const scene = m.sceneId ? repo.sceneById(m.sceneId) : null;
|
|
1297
|
-
return {
|
|
1298
|
-
id: m.id,
|
|
1299
|
-
seq: m.seq,
|
|
1300
|
-
sessionId,
|
|
1301
|
-
at: m.at,
|
|
1302
|
-
speaker: m.speaker,
|
|
1303
|
-
text: m.text,
|
|
1304
|
-
inSurface: m.inSurface,
|
|
1305
|
-
scene: scene
|
|
1306
|
-
? { id: scene.id, startAt: scene.startAt, endAt: scene.endAt, msgCount: scene.msgCount }
|
|
1307
|
-
: null,
|
|
1308
|
-
};
|
|
1309
|
-
}
|
|
1310
|
-
|
|
1311
|
-
/**
|
|
1312
|
-
* `panel.verify({ msgId })` → { dbText, logText, identical }(C4 / E2,P0)
|
|
1313
|
-
*
|
|
1314
|
-
* 这是整个面板最重要的功能:让你亲眼确认「库里存的字」和「日志里的字」一模一样。
|
|
1315
|
-
*
|
|
1316
|
-
* dbText —— 库里存的(已经清洗过桥接元数据,D-216)
|
|
1317
|
-
* logText —— 从原始会话日志重导出并**再清洗一次**(stripBridgeMetadata)后的正文
|
|
1318
|
-
* identical —— 两者是否逐字相同
|
|
1319
|
-
*/
|
|
1320
|
-
function verify(params) {
|
|
1321
|
-
const msgId = intParam(params.msgId, 'msgId', { min: 1 });
|
|
1322
|
-
const row = repo.msgsByIds([msgId])[0];
|
|
1323
|
-
if (!row) {
|
|
1324
|
-
throw new PanelError(
|
|
1325
|
-
'MSG_NOT_FOUND',
|
|
1326
|
-
`没有 id=${msgId} 的消息。原文是唯一事实来源,查不到就是真的不在库里(可能已撤回,或 id 不属于这个库)。`,
|
|
1327
|
-
404,
|
|
1328
|
-
);
|
|
1329
|
-
}
|
|
1330
|
-
|
|
1331
|
-
const log = safeLoadLog(row.sessionId);
|
|
1332
|
-
let logText = null;
|
|
1333
|
-
let source = 'no-log';
|
|
1334
|
-
let reason = null;
|
|
1335
|
-
|
|
1336
|
-
if (log) {
|
|
1337
|
-
const entry = log.raw.get(row.seq);
|
|
1338
|
-
if (entry) {
|
|
1339
|
-
// 库里存的是清洗后的正文(D-216);比对必须用同一条清洗路径,
|
|
1340
|
-
// 否则每条带 `【当前时间】…` 的消息都会假失败。
|
|
1341
|
-
logText = stripBridgeMetadata(entry.raw);
|
|
1342
|
-
source = 'log';
|
|
1343
|
-
} else {
|
|
1344
|
-
source = 'log-missing-seq';
|
|
1345
|
-
reason = `日志里没有 seq=${row.seq}(可能已被撤回、或日志已轮转)`;
|
|
1346
|
-
}
|
|
1347
|
-
} else {
|
|
1348
|
-
reason = '找不到这个会话的原始日志文件,无法比对';
|
|
1349
|
-
}
|
|
1350
|
-
|
|
1351
|
-
const identical = typeof logText === 'string' && logText === row.text;
|
|
1352
|
-
return {
|
|
1353
|
-
dbText: row.text,
|
|
1354
|
-
logText,
|
|
1355
|
-
identical,
|
|
1356
|
-
msgId: row.id,
|
|
1357
|
-
sessionId: row.sessionId,
|
|
1358
|
-
seq: row.seq,
|
|
1359
|
-
at: row.at,
|
|
1360
|
-
speaker: row.speaker,
|
|
1361
|
-
source,
|
|
1362
|
-
reason,
|
|
1363
|
-
};
|
|
1364
|
-
}
|
|
1365
|
-
|
|
1366
|
-
/**
|
|
1367
|
-
* `panel.set({ sessionId, key, value })` → 落盘后的开关状态(E4:写操作必须明确返回)
|
|
1368
|
-
*
|
|
1369
|
-
* key: 'record' | 'tools' | 'autoRecall'
|
|
1370
|
-
* 走 `setSessionFlag`(T9 的配置层),**不自己写文件**。
|
|
1371
|
-
*/
|
|
1372
|
-
function set(params) {
|
|
1373
|
-
const sessionId = requireSession('set', params);
|
|
1374
|
-
const key = String(params.key ?? '');
|
|
1375
|
-
if (!['record', 'tools', 'autoRecall'].includes(key)) {
|
|
1376
|
-
throw new PanelError(
|
|
1377
|
-
'BAD_KEY',
|
|
1378
|
-
`开关名只能是 "record" / "tools" / "autoRecall",收到 ${JSON.stringify(params.key)}`,
|
|
1379
|
-
400,
|
|
1380
|
-
);
|
|
1381
|
-
}
|
|
1382
|
-
const value = boolParam(params.value, 'value');
|
|
1383
|
-
|
|
1384
|
-
let cfg;
|
|
1385
|
-
try {
|
|
1386
|
-
cfg = setSessionFlag(sessionId, key, value, { dbRoot });
|
|
1387
|
-
} catch (error) {
|
|
1388
|
-
throw new PanelError('CONFIG_WRITE_FAILED', `开关没保存上:${error?.message ?? error}`, 500);
|
|
1389
|
-
}
|
|
1390
|
-
|
|
1391
|
-
const applies = key === 'record'
|
|
1392
|
-
? '已保存。下一次同步开始按新开关执行(关掉后新消息不再入库,已有数据一条不删)。'
|
|
1393
|
-
: key === 'tools'
|
|
1394
|
-
? '已保存。已尝试热更新当前会话的工具注入;若对话未加载,将在下次打开时生效。'
|
|
1395
|
-
: '已保存(autoRecall 是预留配置项,面板不显示开关,D-166)。';
|
|
1396
|
-
|
|
1397
|
-
return {
|
|
1398
|
-
ok: true,
|
|
1399
|
-
sessionId,
|
|
1400
|
-
key,
|
|
1401
|
-
value,
|
|
1402
|
-
// 面板只渲染两个开关(D-166);autoRecall 保留在协议里但前端不显示
|
|
1403
|
-
enabled: { record: cfg.record === true, tools: cfg.tools === true },
|
|
1404
|
-
config: {
|
|
1405
|
-
record: cfg.record === true,
|
|
1406
|
-
tools: cfg.tools === true,
|
|
1407
|
-
autoRecall: cfg.autoRecall === true,
|
|
1408
|
-
excludeRanges: cfg.excludeRanges,
|
|
1409
|
-
},
|
|
1410
|
-
applies,
|
|
1411
|
-
};
|
|
1412
|
-
}
|
|
1413
|
-
|
|
1414
|
-
/**
|
|
1415
|
-
* `panel.setExcludeRanges({ sessionId, ranges })` → { ok: true, sessionId, excludeRanges, synced }
|
|
1416
|
-
* 写回排除区间配置,并立刻同步更新数据库里的 `msg.excluded` 与 `scene.excluded_count/has_excluded`。
|
|
1417
|
-
*/
|
|
1418
|
-
function setExcludeRanges(params) {
|
|
1419
|
-
const sessionId = requireSession('setExcludeRanges', params);
|
|
1420
|
-
const rawRanges = params.ranges !== undefined ? params.ranges : params.excludeRanges;
|
|
1421
|
-
if (!Array.isArray(rawRanges)) {
|
|
1422
|
-
throw new PanelError('BAD_EXCLUDE_RANGE', 'ranges 必须是数组', 400);
|
|
1423
|
-
}
|
|
1424
|
-
|
|
1425
|
-
let cfg;
|
|
1426
|
-
let normalized;
|
|
1427
|
-
try {
|
|
1428
|
-
cfg = setSessionExcludeRanges(sessionId, rawRanges, { dbRoot });
|
|
1429
|
-
normalized = normalizeRanges(cfg.excludeRanges);
|
|
1430
|
-
} catch (err) {
|
|
1431
|
-
if (err instanceof ConfigError || err?.name === 'ConfigError') {
|
|
1432
|
-
throw new PanelError('BAD_EXCLUDE_RANGE', err.message, 400);
|
|
1433
|
-
}
|
|
1434
|
-
throw new PanelError('CONFIG_WRITE_FAILED', `排除区间没保存上:${err?.message ?? err}`, 500);
|
|
1435
|
-
}
|
|
1436
|
-
|
|
1437
|
-
const synced = extras.sceneAssign.syncExcludedForSession(sessionId, normalized);
|
|
1438
|
-
return {
|
|
1439
|
-
ok: true,
|
|
1440
|
-
sessionId,
|
|
1441
|
-
excludeRanges: cfg.excludeRanges,
|
|
1442
|
-
synced,
|
|
1443
|
-
};
|
|
1444
|
-
}
|
|
1445
|
-
|
|
1446
|
-
/**
|
|
1447
|
-
* `panel.rebuild({ sessionId, scope })` → { taskId }(然后轮询 panel.task)
|
|
1448
|
-
*
|
|
1449
|
-
* scope:
|
|
1450
|
-
* 'scene' —— 从 msg 重建场景(切分 + 邻接),原文一条不动
|
|
1451
|
-
* 'vector' —— 重建向量索引(需要 embedding key)
|
|
1452
|
-
* 'derive' —— 场景 + gist(要 llm)+ 向量(要 embedding),缺什么就明确说跳过
|
|
1453
|
-
*
|
|
1454
|
-
* 安全闸门(E3):任何 `reset: true` 的清库意图先过 assertSafeToReset(),
|
|
1455
|
-
* 真实记忆库直接 403;即使临时库也只重建派生数据,**永不删 msg**。
|
|
1456
|
-
*/
|
|
1457
|
-
function rebuild(params) {
|
|
1458
|
-
const sessionId = requireSession('rebuild', params);
|
|
1459
|
-
const scope = params.scope === undefined || params.scope === null || params.scope === ''
|
|
1460
|
-
? 'derive'
|
|
1461
|
-
: String(params.scope);
|
|
1462
|
-
if (!['scene', 'vector', 'derive', 'incremental', 'gist'].includes(scope)) {
|
|
1463
|
-
throw new PanelError(
|
|
1464
|
-
'BAD_SCOPE',
|
|
1465
|
-
`scope 只能是 "scene" / "vector" / "derive" / "incremental" / "gist",收到 ${JSON.stringify(params.scope)}`,
|
|
1466
|
-
400,
|
|
1467
|
-
);
|
|
1468
|
-
}
|
|
1469
|
-
|
|
1470
|
-
if (params.reset === true) {
|
|
1471
|
-
// 真实库会在这里被 403 拒绝(可复现的闸门)
|
|
1472
|
-
assertSafeToReset(dbPath);
|
|
1473
|
-
// 临时库也不清原文:重建只重建派生数据
|
|
1474
|
-
logger.warn?.(`[verbatim] panel.rebuild reset 请求:库在临时目录下,仍只重建派生数据(不删 msg)`);
|
|
1475
|
-
}
|
|
1476
|
-
|
|
1477
|
-
// 向量重建依赖 embedding key:没有就**当场明确拒绝**(E4 / B7),
|
|
1478
|
-
// 不要先返回 taskId 再在后台失败 —— 前端会一直以为"还在跑"。
|
|
1479
|
-
if (scope === 'vector' && !hasEmbeddingKey()) {
|
|
1480
|
-
throw new PanelError(
|
|
1481
|
-
'NO_EMBEDDING',
|
|
1482
|
-
'没有配置 embedding 的 API Key,向量索引无法重建。去设置页填一个,或把服务类型改成「本地」。'
|
|
1483
|
-
+ '时间轴与关键词检索不受影响 —— 这不是失败,是「语义搜索未启用」(B7)。',
|
|
1484
|
-
503,
|
|
1485
|
-
);
|
|
1486
|
-
}
|
|
1487
|
-
|
|
1488
|
-
if (scope === 'gist' && !hasLlmReady()) {
|
|
1489
|
-
throw new PanelError(
|
|
1490
|
-
'NO_LLM',
|
|
1491
|
-
'尚未启用或未配好场景摘要 LLM。请先在「设置 → 逐字记忆 → 场景摘要 LLM」启用并完成配置(未启用时已自动使用零成本抽取式摘要)。',
|
|
1492
|
-
503,
|
|
1493
|
-
);
|
|
1494
|
-
}
|
|
1495
|
-
|
|
1496
|
-
// 同会话已有同类(或全量)向量任务在跑时直接复用,避免连点造成并发重算
|
|
1497
|
-
const active = findRunningTask(sessionId, scope);
|
|
1498
|
-
if (active) {
|
|
1499
|
-
return {
|
|
1500
|
-
taskId: active.id,
|
|
1501
|
-
scope: active.scope,
|
|
1502
|
-
sessionId,
|
|
1503
|
-
state: active.state,
|
|
1504
|
-
progress: active.progress ?? null,
|
|
1505
|
-
reused: true,
|
|
1506
|
-
};
|
|
1507
|
-
}
|
|
1508
|
-
|
|
1509
|
-
const useLlm = params.useLlm === false ? false : undefined;
|
|
1510
|
-
const onlyUnrefined = params.onlyUnrefined === true;
|
|
1511
|
-
const concurrency = Number.isFinite(Number(params.concurrency)) ? Number(params.concurrency) : undefined;
|
|
1512
|
-
const task = startRebuildTask({ sessionId, scope, useLlm, onlyUnrefined, concurrency });
|
|
1513
|
-
return { taskId: task.id, scope, sessionId, state: task.state, progress: task.progress ?? null };
|
|
1514
|
-
}
|
|
1515
|
-
|
|
1516
|
-
/** `panel.task({ taskId })` → 重建任务进度(PANEL §5「然后轮询进度」的落点) */
|
|
1517
|
-
function taskInfo(params) {
|
|
1518
|
-
const taskId = String(params.taskId ?? '');
|
|
1519
|
-
if (!taskId) throw new PanelError('BAD_ARG', '缺少 taskId', 400);
|
|
1520
|
-
const t = getTask(taskId);
|
|
1521
|
-
if (!t) throw new PanelError('TASK_NOT_FOUND', `没有 taskId=${taskId} 的重建任务(任务只保留最近 20 个)`, 404);
|
|
1522
|
-
return {
|
|
1523
|
-
taskId: t.id,
|
|
1524
|
-
scope: t.scope,
|
|
1525
|
-
sessionId: t.sessionId,
|
|
1526
|
-
state: t.state,
|
|
1527
|
-
progress: t.progress ?? null,
|
|
1528
|
-
startedAt: t.startedAt,
|
|
1529
|
-
finishedAt: t.finishedAt,
|
|
1530
|
-
result: t.result,
|
|
1531
|
-
error: t.error,
|
|
1532
|
-
};
|
|
1533
|
-
}
|
|
1534
|
-
|
|
1535
|
-
/**
|
|
1536
|
-
* `panel.flag({ msgId, reason? })` → { id }
|
|
1537
|
-
*
|
|
1538
|
-
* 只记一笔,不删任何东西(C5 / D-167)。标记后检索照常返回该条。
|
|
1539
|
-
*/
|
|
1540
|
-
function flag(params) {
|
|
1541
|
-
const msgId = intParam(params.msgId, 'msgId', { min: 1 });
|
|
1542
|
-
const row = repo.msgsByIds([msgId])[0];
|
|
1543
|
-
if (!row) throw new PanelError('MSG_NOT_FOUND', `没有 id=${msgId} 的消息,标不了`, 404);
|
|
1544
|
-
const reason = params.reason === undefined || params.reason === null || params.reason === ''
|
|
1545
|
-
? null
|
|
1546
|
-
: String(params.reason);
|
|
1547
|
-
|
|
1548
|
-
let id;
|
|
1549
|
-
try {
|
|
1550
|
-
id = extras.flag.insert({ msgId, reason });
|
|
1551
|
-
} catch (error) {
|
|
1552
|
-
throw new PanelError('FLAG_FAILED', `标记没记上:${error?.message ?? error}`, 500);
|
|
1553
|
-
}
|
|
1554
|
-
return { id, msgId, reason, at: Date.now(), sessionId: row.sessionId };
|
|
1555
|
-
}
|
|
1556
|
-
|
|
1557
|
-
/**
|
|
1558
|
-
* `panel.flags({ sessionId, limit? })` → [{ id, msgId, reason, at, snippet }]
|
|
1559
|
-
*
|
|
1560
|
-
* 只要未取消的标记(resolved_at IS NULL)。snippet 供核对页直接显示原文开头。
|
|
1561
|
-
*/
|
|
1562
|
-
function flags(params) {
|
|
1563
|
-
const sessionId = requireSession('flags', params);
|
|
1564
|
-
const limit = intParam(params.limit, 'limit', { def: 50, min: 1, max: 500 });
|
|
1565
|
-
|
|
1566
|
-
const rows = extras.flag.list({ sessionId, openOnly: true, limit });
|
|
1567
|
-
const ids = rows.map((r) => r.msgId);
|
|
1568
|
-
const byId = new Map(repo.msgsByIds(ids).map((m) => [m.id, m]));
|
|
1569
|
-
|
|
1570
|
-
return rows.map((r) => {
|
|
1571
|
-
const msg = byId.get(r.msgId);
|
|
1572
|
-
const text = msg?.text ?? '';
|
|
1573
|
-
return {
|
|
1574
|
-
id: r.id,
|
|
1575
|
-
msgId: r.msgId,
|
|
1576
|
-
reason: r.reason ?? null,
|
|
1577
|
-
at: r.at,
|
|
1578
|
-
snippet: text.length > 80 ? `${text.slice(0, 80)}…` : text,
|
|
1579
|
-
};
|
|
1580
|
-
});
|
|
1581
|
-
}
|
|
1582
|
-
|
|
1583
|
-
/** `panel.unflag({ id })` → { ok }(只撤销标记,不碰原文) */
|
|
1584
|
-
function unflag(params) {
|
|
1585
|
-
const id = intParam(params.id, 'id', { min: 1 });
|
|
1586
|
-
const changed = extras.flag.resolve(id);
|
|
1587
|
-
return {
|
|
1588
|
-
ok: changed,
|
|
1589
|
-
id,
|
|
1590
|
-
message: changed ? '已取消标记(这条原文没有任何变化)' : '没有可取消的标记(不存在,或已经取消过了)',
|
|
1591
|
-
};
|
|
1592
|
-
}
|
|
1593
|
-
|
|
1594
|
-
/**
|
|
1595
|
-
* `panel.deleteNote({ id, sessionId?, reason? })` → { ok }(软删,30 天内可恢复)
|
|
1596
|
-
*
|
|
1597
|
-
* 带 sessionId 时只删该会话的笔记(A1:B 会话不能凭编号删掉 A 的);
|
|
1598
|
-
* 不带 = 全库管理视角(PANEL §5 的契约只写了 id,这里向后兼容)。
|
|
1599
|
-
*/
|
|
1600
|
-
function deleteNote(params) {
|
|
1601
|
-
const id = intParam(params.id, 'id', { min: 1 });
|
|
1602
|
-
const sessionId = optionalSession('deleteNote', params);
|
|
1603
|
-
const reason = params.reason === undefined || params.reason === null || params.reason === ''
|
|
1604
|
-
? null
|
|
1605
|
-
: String(params.reason);
|
|
1606
|
-
|
|
1607
|
-
const row = extras.note.byId(id, sessionId ? { sessionId } : {});
|
|
1608
|
-
if (!row) {
|
|
1609
|
-
throw new PanelError(
|
|
1610
|
-
'NOTE_NOT_FOUND',
|
|
1611
|
-
`没有 id=${id} 的笔记${sessionId ? `(会话 ${sessionId} 里没有这条)` : ''}`,
|
|
1612
|
-
404,
|
|
1613
|
-
);
|
|
1614
|
-
}
|
|
1615
|
-
if (row.deletedAt !== null) {
|
|
1616
|
-
return { ok: false, id, deletedAt: row.deletedAt, message: '这条笔记之前已经删过了(30 天内可以在回收站恢复)' };
|
|
1617
|
-
}
|
|
1618
|
-
|
|
1619
|
-
const deletedAt = Date.now();
|
|
1620
|
-
const changed = extras.note.softDelete(id, deletedAt, sessionId ? { sessionId } : {});
|
|
1621
|
-
if (changed) {
|
|
1622
|
-
try {
|
|
1623
|
-
if (handle.hasVec) db.prepare('DELETE FROM vec_note WHERE note_id = ?').run(BigInt(id));
|
|
1624
|
-
} catch { /* ignore */ }
|
|
1625
|
-
try {
|
|
1626
|
-
extras.audit.insert({
|
|
1627
|
-
action: 'forget',
|
|
1628
|
-
target: `note:${id}`,
|
|
1629
|
-
detail: { via: 'panel', reason, sessionId },
|
|
1630
|
-
});
|
|
1631
|
-
} catch {
|
|
1632
|
-
// 审计失败不该让删除回滚:笔记已经标记删除了
|
|
1633
|
-
}
|
|
1634
|
-
}
|
|
1635
|
-
return {
|
|
1636
|
-
ok: changed,
|
|
1637
|
-
id,
|
|
1638
|
-
deletedAt: changed ? deletedAt : null,
|
|
1639
|
-
message: changed ? '已删除(软删,30 天内可在回收站恢复)' : '删除没生效(可能刚刚被删过)',
|
|
1640
|
-
};
|
|
1641
|
-
}
|
|
1642
|
-
|
|
1643
|
-
/**
|
|
1644
|
-
* `panel.restoreNote({ id, sessionId? })` → { ok }
|
|
1645
|
-
*
|
|
1646
|
-
* 带 sessionId 时只恢复该会话的笔记(和 deleteNote 同一套归属判断)。
|
|
1647
|
-
*/
|
|
1648
|
-
function restoreNote(params) {
|
|
1649
|
-
const id = intParam(params.id, 'id', { min: 1 });
|
|
1650
|
-
const sessionId = optionalSession('restoreNote', params);
|
|
1651
|
-
const row = extras.note.byId(id, sessionId ? { sessionId } : {});
|
|
1652
|
-
if (!row) {
|
|
1653
|
-
throw new PanelError(
|
|
1654
|
-
'NOTE_NOT_FOUND',
|
|
1655
|
-
`没有 id=${id} 的笔记${sessionId ? `(会话 ${sessionId} 里没有这条)` : ''}`,
|
|
1656
|
-
404,
|
|
1657
|
-
);
|
|
1658
|
-
}
|
|
1659
|
-
if (row.deletedAt === null) {
|
|
1660
|
-
return { ok: false, id, message: '这条笔记没有被删过,不需要恢复' };
|
|
1661
|
-
}
|
|
1662
|
-
const changed = extras.note.restore(id, sessionId ? { sessionId } : {});
|
|
1663
|
-
if (changed) {
|
|
1664
|
-
try {
|
|
1665
|
-
extras.audit.insert({ action: 'restore', target: `note:${id}`, detail: { via: 'panel', sessionId } });
|
|
1666
|
-
} catch {
|
|
1667
|
-
// 同上
|
|
1668
|
-
}
|
|
1669
|
-
}
|
|
1670
|
-
return { ok: changed, id, message: changed ? '已恢复' : '恢复没生效' };
|
|
1671
|
-
}
|
|
1672
|
-
|
|
1673
|
-
/**
|
|
1674
|
-
* `panel.addNote({ sessionId, content, about? })` → { ok, id, note }
|
|
1675
|
-
* 允许用户在面板里主动补记一条笔记(与 Agent 的 memory_remember 共用 note 表,严格按会话隔离)。
|
|
1676
|
-
*/
|
|
1677
|
-
function addNote(params) {
|
|
1678
|
-
const sessionId = requireSession('addNote', params);
|
|
1679
|
-
const content = typeof params.content === 'string' ? params.content.trim() : '';
|
|
1680
|
-
if (!content) throw new PanelError('BAD_ARG', '笔记内容不能为空', 400);
|
|
1681
|
-
if (content.length > 2000) throw new PanelError('BAD_ARG', '单条笔记最多 2000 字', 400);
|
|
1682
|
-
const rawAbout = params.about === undefined || params.about === null || params.about === ''
|
|
1683
|
-
? null
|
|
1684
|
-
: String(params.about).trim();
|
|
1685
|
-
if (rawAbout !== null && !['me', 'him', 'us'].includes(rawAbout)) {
|
|
1686
|
-
throw new PanelError('BAD_ARG', `about 只能是 me / him / us 或留空,收到 ${JSON.stringify(params.about)}`, 400);
|
|
1687
|
-
}
|
|
1688
|
-
const at = Date.now();
|
|
1689
|
-
const id = extras.note.insert({ sessionId, content, about: rawAbout, at });
|
|
1690
|
-
try {
|
|
1691
|
-
extras.audit.insert({ action: 'remember', target: `note:${id}`, detail: { via: 'panel', sessionId, about: rawAbout } });
|
|
1692
|
-
} catch { /* 审计失败不影响写入 */ }
|
|
1693
|
-
const note = extras.note.byId(id, { sessionId }) ?? { id, sessionId, content, about: rawAbout, at, deletedAt: null };
|
|
1694
|
-
return { ok: true, id, note };
|
|
1695
|
-
}
|
|
1696
|
-
|
|
1697
|
-
function globalConfig(params) {
|
|
1698
|
-
optionalSession('globalConfig', params);
|
|
1699
|
-
const { config: loadedCfg, exists, warnings } = loadGlobalConfig({ dshHome });
|
|
1700
|
-
return {
|
|
1701
|
-
config: sanitizeGlobalConfig(loadedCfg),
|
|
1702
|
-
path: globalConfigPath({ dshHome }),
|
|
1703
|
-
exists,
|
|
1704
|
-
warnings,
|
|
1705
|
-
embedding: buildEmbeddingView(loadedCfg),
|
|
1706
|
-
llm: buildLlmView(loadedCfg, Boolean(getHostLlm())),
|
|
1707
|
-
rerank: buildRerankView(loadedCfg),
|
|
1708
|
-
vecExt: buildVecExtView(handle),
|
|
1709
|
-
};
|
|
1710
|
-
}
|
|
1711
|
-
|
|
1712
|
-
const probeLocal = createModelProber({ embCfg, llmCfg, rerankCfg, getHostLlm });
|
|
1713
|
-
|
|
1714
|
-
/** 写全局配置(深合并)。白名单字段,避免前端乱写把配置搞坏。 */
|
|
1715
|
-
function setGlobalConfig(params) {
|
|
1716
|
-
optionalSession('setGlobalConfig', params);
|
|
1717
|
-
const patch = params.patch ?? params.config;
|
|
1718
|
-
if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) {
|
|
1719
|
-
throw new PanelError('BAD_ARG', 'patch 必须是一个对象', 400);
|
|
1720
|
-
}
|
|
1721
|
-
const allowed = new Set(['defaults', 'embedding', 'llm', 'rerank', 'search', 'index']);
|
|
1722
|
-
const unknown = Object.keys(patch).filter((k) => !allowed.has(k));
|
|
1723
|
-
if (unknown.length) {
|
|
1724
|
-
throw new PanelError(
|
|
1725
|
-
'BAD_KEY',
|
|
1726
|
-
`不认识的配置块:${unknown.join(', ')}。可写:${[...allowed].join(' / ')}`,
|
|
1727
|
-
400,
|
|
1728
|
-
);
|
|
1729
|
-
}
|
|
1730
|
-
// Key 直接存(作者 2026-11-18:不绕环境变量)。只是提醒一下会明文落盘。
|
|
1731
|
-
const patchKey = patch?.embedding?.apiKey;
|
|
1732
|
-
if (typeof patchKey === 'string' && patchKey.length > 500) {
|
|
1733
|
-
throw new PanelError('BAD_ARG', 'embedding.apiKey 太长了(上限 500 字符)', 400);
|
|
1734
|
-
}
|
|
1735
|
-
const patchLlmKey = patch?.llm?.apiKey;
|
|
1736
|
-
if (typeof patchLlmKey === 'string' && patchLlmKey.length > 500) {
|
|
1737
|
-
throw new PanelError('BAD_ARG', 'llm.apiKey 太长了(上限 500 字符)', 400);
|
|
1738
|
-
}
|
|
1739
|
-
const patchRerankKey = patch?.rerank?.apiKey;
|
|
1740
|
-
if (typeof patchRerankKey === 'string' && patchRerankKey.length > 500) {
|
|
1741
|
-
throw new PanelError('BAD_ARG', 'rerank.apiKey 太长了(上限 500 字符)', 400);
|
|
1742
|
-
}
|
|
1743
|
-
const checkInt = (val, label, min, max) => {
|
|
1744
|
-
if (val === undefined) return;
|
|
1745
|
-
if (typeof val !== 'number' || !Number.isInteger(val) || val < min || val > max) {
|
|
1746
|
-
throw new PanelError('BAD_ARG', `${label} 必须是 ${min}~${max} 的整数`, 400);
|
|
1747
|
-
}
|
|
1748
|
-
};
|
|
1749
|
-
if (patch.embedding) checkInt(patch.embedding.dim, 'embedding.dim', 16, 16384);
|
|
1750
|
-
if (patch.rerank) {
|
|
1751
|
-
checkInt(patch.rerank.topN, 'rerank.topN', 1, 100);
|
|
1752
|
-
checkInt(patch.rerank.timeoutMs, 'rerank.timeoutMs', 500, 60000);
|
|
1753
|
-
}
|
|
1754
|
-
if (patch.search) {
|
|
1755
|
-
checkInt(patch.search.defaultLimit, 'search.defaultLimit', 1, 100);
|
|
1756
|
-
checkInt(patch.search.maxLimit, 'search.maxLimit', 1, 500);
|
|
1757
|
-
}
|
|
1758
|
-
|
|
1759
|
-
const next = saveGlobalConfig(patch, { dshHome });
|
|
1760
|
-
invalidateGlobal(); // 设置页改完立即生效,不用重启插件
|
|
1761
|
-
return {
|
|
1762
|
-
ok: true,
|
|
1763
|
-
config: sanitizeGlobalConfig(next),
|
|
1764
|
-
path: globalConfigPath({ dshHome }),
|
|
1765
|
-
embedding: buildEmbeddingView(next),
|
|
1766
|
-
llm: buildLlmView(next, Boolean(getHostLlm())),
|
|
1767
|
-
rerank: buildRerankView(next),
|
|
1768
|
-
vecExt: buildVecExtView(handle),
|
|
1769
|
-
applies: '已保存,立即生效。新会话按新默认值走;已有会话各自的开关不受影响(对话级优先)。',
|
|
1770
|
-
};
|
|
1771
|
-
}
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
/* ───────────────────────── 数据库管理台(全局 + 跨会话切换视图) ───────────────────────── */
|
|
1775
|
-
|
|
1776
|
-
const { dbOverview, dbRows, dbQuery, dbMaintain } = createDbAdmin({
|
|
1777
|
-
handle,
|
|
1778
|
-
db,
|
|
1779
|
-
repo,
|
|
1780
|
-
extras,
|
|
1781
|
-
dbPath,
|
|
1782
|
-
dbRoot,
|
|
1783
|
-
stmt,
|
|
1784
|
-
noteHasSessionColumn,
|
|
1785
|
-
requireSession,
|
|
1786
|
-
optionalSession,
|
|
1787
|
-
readSessionConfig,
|
|
1788
|
-
intParam,
|
|
1789
|
-
PanelError,
|
|
1790
|
-
logger,
|
|
1791
|
-
});
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
const {
|
|
1795
|
-
mergeScene,
|
|
1796
|
-
splitScene,
|
|
1797
|
-
refineOneScene,
|
|
1798
|
-
setSceneGist,
|
|
1799
|
-
setMsgExcluded,
|
|
1800
|
-
updateNote,
|
|
1801
|
-
mediaPreview,
|
|
1802
|
-
setMediaCaption,
|
|
1803
|
-
findDuplicateNotes,
|
|
1804
|
-
mergeNotes,
|
|
1805
|
-
} = createSceneOps({
|
|
1806
|
-
handle,
|
|
1807
|
-
db,
|
|
1808
|
-
repo,
|
|
1809
|
-
extras,
|
|
1810
|
-
stmt,
|
|
1811
|
-
requireSession,
|
|
1812
|
-
intParam,
|
|
1813
|
-
PanelError,
|
|
1814
|
-
llmCfg,
|
|
1815
|
-
getHostLlm,
|
|
1816
|
-
hasEmbeddingKey,
|
|
1817
|
-
makeEmbeddingProvider,
|
|
1818
|
-
noteHasSessionColumn,
|
|
1819
|
-
dshHome,
|
|
1820
|
-
logger,
|
|
1821
|
-
});
|
|
1822
|
-
|
|
1823
|
-
const recallEntries = Array.isArray(opts.recallLog) ? opts.recallLog : [];
|
|
1824
|
-
function recallLog(params) {
|
|
1825
|
-
const sid = optionalSession('recallLog', params);
|
|
1826
|
-
const limit = intParam(params.limit, 'limit', { def: 20, min: 1, max: 50 });
|
|
1827
|
-
const list = sid ? recallEntries.filter((e) => e.sessionId === sid) : recallEntries;
|
|
1828
|
-
return { items: list.slice(0, limit), total: list.length };
|
|
1829
|
-
}
|
|
1830
|
-
|
|
1831
|
-
const sessionLock = opts.sessionLock ?? createSessionLock();
|
|
1832
|
-
const lockWrite = (key, fn) => sessionLock.withLock(key, fn);
|
|
1833
|
-
|
|
1834
|
-
const methods = {
|
|
1835
|
-
status,
|
|
1836
|
-
timeline,
|
|
1837
|
-
sceneDetail,
|
|
1838
|
-
notes,
|
|
1839
|
-
deletedNotes,
|
|
1840
|
-
sample,
|
|
1841
|
-
verify,
|
|
1842
|
-
search,
|
|
1843
|
-
set,
|
|
1844
|
-
setExcludeRanges,
|
|
1845
|
-
rebuild,
|
|
1846
|
-
flag,
|
|
1847
|
-
flags,
|
|
1848
|
-
unflag,
|
|
1849
|
-
deleteNote,
|
|
1850
|
-
restoreNote,
|
|
1851
|
-
addNote,
|
|
1852
|
-
globalConfig,
|
|
1853
|
-
setGlobalConfig,
|
|
1854
|
-
probeLocal,
|
|
1855
|
-
dbOverview,
|
|
1856
|
-
dbRows,
|
|
1857
|
-
dbQuery,
|
|
1858
|
-
dbMaintain: (p) => (
|
|
1859
|
-
['clearSession', 'importSession', 'vacuum'].includes(p?.action)
|
|
1860
|
-
? lockWrite(p?.sessionId || p?.payload?.sessionId || '__global__', () => dbMaintain(p))
|
|
1861
|
-
: dbMaintain(p)
|
|
1862
|
-
),
|
|
1863
|
-
recallLog,
|
|
1864
|
-
mergeScene: (p) => lockWrite(p?.sessionId, () => mergeScene(p)),
|
|
1865
|
-
splitScene: (p) => lockWrite(p?.sessionId, () => splitScene(p)),
|
|
1866
|
-
refineOneScene: (p) => lockWrite(p?.sessionId, () => refineOneScene(p)),
|
|
1867
|
-
mediaPreview,
|
|
1868
|
-
setMediaCaption,
|
|
1869
|
-
findDuplicateNotes,
|
|
1870
|
-
mergeNotes,
|
|
1871
|
-
setSceneGist: (p) => lockWrite(p?.sessionId, () => setSceneGist(p)),
|
|
1872
|
-
setMsgExcluded: (p) => lockWrite(p?.sessionId, () => setMsgExcluded(p)),
|
|
1873
|
-
updateNote,
|
|
1874
|
-
// 补充方法:PANEL §5 的 rebuild 说「→ { taskId } 然后轮询进度」,
|
|
1875
|
-
// 没有它前端无法轮询(详见报告)。
|
|
1876
|
-
task: taskInfo,
|
|
1877
|
-
};
|
|
1878
|
-
|
|
1879
|
-
return {
|
|
1880
|
-
methods,
|
|
1881
|
-
/** 统一入口:未知方法 404,业务错误统一成 PanelError */
|
|
1882
|
-
async call(method, params) {
|
|
1883
|
-
const name = String(method ?? '');
|
|
1884
|
-
const fn = methods[name];
|
|
1885
|
-
if (typeof fn !== 'function') {
|
|
1886
|
-
throw new PanelError(
|
|
1887
|
-
'METHOD_NOT_FOUND',
|
|
1888
|
-
`没有 panel.${name} 这个方法。可用:${Object.keys(methods).map((k) => `panel.${k}`).join(', ')}`,
|
|
1889
|
-
404,
|
|
1890
|
-
);
|
|
1891
|
-
}
|
|
1892
|
-
return await fn(params ?? {});
|
|
1893
|
-
},
|
|
1894
|
-
/** 测试/诊断用:当前日志缓存状态 */
|
|
1895
|
-
debug() {
|
|
1896
|
-
return {
|
|
1897
|
-
methodNames: Object.keys(methods),
|
|
1898
|
-
cachedLogs: [...logCache.keys()],
|
|
1899
|
-
tasks: recentTasks(),
|
|
1900
|
-
dbRoot,
|
|
1901
|
-
dbPath,
|
|
1902
|
-
};
|
|
1903
|
-
},
|
|
1904
|
-
};
|
|
1905
|
-
}
|
|
1906
|
-
|
|
1907
|
-
/* ══════════════════════════════════════════════════════════════════════
|
|
1908
|
-
* 面板 RPC:HTTP 适配层
|
|
1909
|
-
* ══════════════════════════════════════════════════════════════════════ */
|
|
1910
|
-
|
|
1911
|
-
/** 统一的 JSON 响应(永远带 no-store:面板看的是实时状态) */
|
|
1912
|
-
function sendJson(res, body, status = 200) {
|
|
1913
|
-
const text = JSON.stringify(body);
|
|
1914
|
-
res.writeHead(status, {
|
|
1915
|
-
'content-type': 'application/json; charset=utf-8',
|
|
1916
|
-
'cache-control': 'no-store',
|
|
1917
|
-
'content-length': Buffer.byteLength(text),
|
|
1918
|
-
});
|
|
1919
|
-
res.end(text);
|
|
1920
|
-
}
|
|
1921
|
-
|
|
1922
|
-
/** 不依赖会话日志的面板 RPC:跳过同步,保证设置页/探测/轮询/写开关/异步任务发起/库管理即时响应 */
|
|
1923
|
-
const SKIP_SYNC_METHODS = new Set([
|
|
1924
|
-
'globalConfig',
|
|
1925
|
-
'setGlobalConfig',
|
|
1926
|
-
'probeLocal',
|
|
1927
|
-
'task',
|
|
1928
|
-
'rebuild',
|
|
1929
|
-
'set',
|
|
1930
|
-
'setExcludeRanges',
|
|
1931
|
-
'addNote',
|
|
1932
|
-
'dbOverview',
|
|
1933
|
-
'dbRows',
|
|
1934
|
-
'dbQuery',
|
|
1935
|
-
'dbMaintain',
|
|
1936
|
-
'recallLog',
|
|
1937
|
-
'mergeScene',
|
|
1938
|
-
'splitScene',
|
|
1939
|
-
'refineOneScene',
|
|
1940
|
-
'mediaPreview',
|
|
1941
|
-
'setMediaCaption',
|
|
1942
|
-
'findDuplicateNotes',
|
|
1943
|
-
'mergeNotes',
|
|
1944
|
-
'setSceneGist',
|
|
1945
|
-
'setMsgExcluded',
|
|
1946
|
-
'updateNote',
|
|
1947
|
-
]);
|
|
1948
|
-
|
|
1949
|
-
/**
|
|
1950
|
-
* 把 createPanelApi() 适配成 DSH webServer 的 handler。
|
|
1951
|
-
*
|
|
1952
|
-
* 路径约定:`${API_PREFIX}/panel.<method>`(PANEL.md §5)。
|
|
1953
|
-
* 参数同时接受 query(GET)和 JSON body(POST)。
|
|
1954
|
-
*
|
|
1955
|
-
* @param {object} api createPanelApi() 的返回值
|
|
1956
|
-
* @param {{beforeRequest?: (ctx: {method: string, sessionId: string|null}) => Promise<void>|void}} [opts]
|
|
1957
|
-
*/
|
|
1958
|
-
export function createPanelHandler(api, opts = {}) {
|
|
1959
|
-
const beforeRequest = typeof opts.beforeRequest === 'function' ? opts.beforeRequest : null;
|
|
1960
|
-
const afterCall = typeof opts.afterCall === 'function' ? opts.afterCall : null;
|
|
1961
|
-
|
|
1962
|
-
return async function handler(req, res) {
|
|
1963
|
-
let url;
|
|
1964
|
-
try {
|
|
1965
|
-
url = new URL(req.url ?? '/', 'http://localhost');
|
|
1966
|
-
} catch {
|
|
1967
|
-
return sendJson(res, { ok: false, code: 'BAD_URL', error: '请求地址解析不了' }, 400);
|
|
1968
|
-
}
|
|
1969
|
-
|
|
1970
|
-
const rawPath = url.pathname;
|
|
1971
|
-
const p = rawPath.startsWith(API_PREFIX) ? rawPath.slice(API_PREFIX.length) || '/' : rawPath;
|
|
1972
|
-
|
|
1973
|
-
if (!p.startsWith('/panel.')) {
|
|
1974
|
-
const legacy = LEGACY_PANEL_PATHS.has(p);
|
|
1975
|
-
return sendJson(
|
|
1976
|
-
res,
|
|
1977
|
-
{
|
|
1978
|
-
ok: false,
|
|
1979
|
-
code: legacy ? 'LEGACY_ENDPOINT' : 'NOT_FOUND',
|
|
1980
|
-
error: legacy
|
|
1981
|
-
? `旧端点 ${p} 已废弃:它不按会话过滤,会把别的对话的数据混进来(A2 的 bug)。`
|
|
1982
|
-
+ `请改用 ${API_PREFIX}/panel.status 等 RPC(见 PANEL.md §5)。`
|
|
1983
|
-
: `没有这个端点:${p}。RPC 路径形如 ${API_PREFIX}/panel.status`,
|
|
1984
|
-
methods: [...PANEL_METHODS],
|
|
1985
|
-
},
|
|
1986
|
-
legacy ? 410 : 404,
|
|
1987
|
-
);
|
|
1988
|
-
}
|
|
1989
|
-
|
|
1990
|
-
const method = p.slice('/panel.'.length);
|
|
1991
|
-
const body = await readRequestBody(req);
|
|
1992
|
-
if (body === null) {
|
|
1993
|
-
return sendJson(res, { ok: false, code: 'BAD_JSON', error: '请求体不是合法 JSON 对象' }, 400);
|
|
1994
|
-
}
|
|
1995
|
-
|
|
1996
|
-
const query = {};
|
|
1997
|
-
for (const [k, v] of url.searchParams) query[k] = v;
|
|
1998
|
-
const params = coerceParams({ ...query, ...body });
|
|
1999
|
-
|
|
2000
|
-
// 先把目标会话数据同步到最新,否则面板看到的是旧数字(失败就用现有数据)
|
|
2001
|
-
if (beforeRequest && !SKIP_SYNC_METHODS.has(method)) {
|
|
2002
|
-
const sessionId = typeof params.sessionId === 'string' && params.sessionId.trim()
|
|
2003
|
-
? params.sessionId.trim()
|
|
2004
|
-
: null;
|
|
2005
|
-
try {
|
|
2006
|
-
await beforeRequest({ method, sessionId });
|
|
2007
|
-
} catch { /* 同步失败不影响读取 */ }
|
|
2008
|
-
}
|
|
2009
|
-
|
|
2010
|
-
try {
|
|
2011
|
-
const result = await api.call(method, params);
|
|
2012
|
-
if (afterCall) {
|
|
2013
|
-
try { await afterCall({ method, params, result }); } catch { /* 后置钩子失败不影响响应 */ }
|
|
2014
|
-
}
|
|
2015
|
-
return sendJson(res, result, 200);
|
|
2016
|
-
} catch (error) {
|
|
2017
|
-
const status = error instanceof PanelError ? error.status : 500;
|
|
2018
|
-
return sendJson(
|
|
2019
|
-
res,
|
|
2020
|
-
{
|
|
2021
|
-
ok: false,
|
|
2022
|
-
method: `panel.${method}`,
|
|
2023
|
-
code: error?.code ?? 'INTERNAL_ERROR',
|
|
2024
|
-
error: error?.message ?? String(error),
|
|
2025
|
-
},
|
|
2026
|
-
status,
|
|
2027
|
-
);
|
|
2028
|
-
}
|
|
2029
|
-
};
|
|
2030
|
-
}
|
|
2031
|
-
|
|
2032
|
-
/* ══════════════════════════════════════════════════════════════════════
|
|
2033
|
-
* 插件入口
|
|
2034
|
-
* ══════════════════════════════════════════════════════════════════════ */
|
|
2035
|
-
|
|
2036
|
-
export function apply(ctx, config = {}) {
|
|
2037
|
-
const dshHome = config.dshHome ?? process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh');
|
|
2038
|
-
const dbPath = config.dbPath ?? defaultDbPath(dshHome);
|
|
2039
|
-
|
|
2040
|
-
// 运行时配置根 = 库所在目录(D-175:`$DSH_HOME/verbatim/sessions/<id>.json`)。
|
|
2041
|
-
// 注意不是 dshHome:`<dshHome>/verbatim/sessions` 才是对的,传错就永远读不到会话开关。
|
|
2042
|
-
const dbRoot = dbPath === ':memory:'
|
|
2043
|
-
? path.join(dshHome, 'verbatim')
|
|
2044
|
-
: path.dirname(path.resolve(dbPath));
|
|
2045
|
-
|
|
2046
|
-
let handle;
|
|
2047
|
-
try {
|
|
2048
|
-
handle = openDb({ dbPath, logger: { warn: (m) => ctx.logger?.warn?.(`[verbatim] ${m}`) } });
|
|
2049
|
-
} catch (e) {
|
|
2050
|
-
// 库打不开是致命问题,但不能拖垮整个 Harness
|
|
2051
|
-
ctx.logger?.error?.(`[verbatim] 记忆库打不开:${e.message}`);
|
|
2052
|
-
return () => {};
|
|
2053
|
-
}
|
|
2054
|
-
|
|
2055
|
-
// 诊断状态文件:DSH 主进程日志不好取,把关键状态写到库目录旁边,方便外部确认
|
|
2056
|
-
// (这不是功能,只是让我能验证"插件到底加载了没、给哪个会话注册了工具")
|
|
2057
|
-
const statusFile = path.join(dbPath === ':memory:' ? dbRoot : path.dirname(dbPath), 'plugin-status.json');
|
|
2058
|
-
const writeStatus = (patch) => {
|
|
2059
|
-
try {
|
|
2060
|
-
const prev = fs.existsSync(statusFile) ? JSON.parse(fs.readFileSync(statusFile, 'utf8')) : {};
|
|
2061
|
-
fs.writeFileSync(statusFile, JSON.stringify({ ...prev, ...patch, at: new Date().toISOString() }, null, 2));
|
|
2062
|
-
} catch { /* 写不进去就算了,不能因为诊断影响插件 */ }
|
|
2063
|
-
};
|
|
2064
|
-
const instanceId = Date.now() + '-' + Math.random().toString(36).slice(2, 7);
|
|
2065
|
-
writeStatus({ loaded: true, instanceId, dbPath, hasVec: handle.hasVec === true });
|
|
2066
|
-
|
|
2067
|
-
const repo = createRepo(handle);
|
|
2068
|
-
const extras = createExtras(handle);
|
|
2069
|
-
ctx.logger?.info?.(`[verbatim] 记忆库已打开:${dbPath}(${handle.hasVec ? '向量可用' : '降级为暴力余弦'})`);
|
|
2070
|
-
|
|
2071
|
-
/* ───────── 增量同步与轻量自动补索引 ───────── */
|
|
2072
|
-
|
|
2073
|
-
/** 按会话日志文件独立记录 mtime 与并发同步 Promise(多会话切换互不覆盖) */
|
|
2074
|
-
const lastMtimes = new Map();
|
|
2075
|
-
const syncingFiles = new Map();
|
|
2076
|
-
let disposed = false;
|
|
2077
|
-
let autoIndexing = null;
|
|
2078
|
-
|
|
2079
|
-
/**
|
|
2080
|
-
* 后台轻量增量补索引(仅当全局配置 index.autoIndex === true 时启用)。
|
|
2081
|
-
* 不阻塞工具返回和面板读取;单次最多补 64 条,出错或模型不一致只告警,不破坏已有向量。
|
|
2082
|
-
*/
|
|
2083
|
-
const scheduleAutoIndex = () => {
|
|
2084
|
-
if (disposed || autoIndexing) return;
|
|
2085
|
-
let globalCfg;
|
|
2086
|
-
try {
|
|
2087
|
-
globalCfg = loadGlobalConfig({ dshHome }).config;
|
|
2088
|
-
} catch {
|
|
2089
|
-
return;
|
|
2090
|
-
}
|
|
2091
|
-
if (globalCfg?.index?.autoIndex !== true) return;
|
|
2092
|
-
|
|
2093
|
-
const gEmb = globalCfg.embedding ?? {};
|
|
2094
|
-
const pEmb = config.embedding ?? {};
|
|
2095
|
-
const pick = (k) => (pEmb[k] !== undefined && pEmb[k] !== null && pEmb[k] !== '' ? pEmb[k] : gEmb[k]);
|
|
2096
|
-
const emb = {
|
|
2097
|
-
mode: pick('mode') === 'local' ? 'local' : 'remote',
|
|
2098
|
-
model: pick('model') || 'Qwen/Qwen3-Embedding-4B',
|
|
2099
|
-
dim: Number(pick('dim')) || 1024,
|
|
2100
|
-
baseUrl: pick('baseUrl') || pick('baseURL') || 'https://api.siliconflow.cn/v1',
|
|
2101
|
-
apiKey: typeof pick('apiKey') === 'string' ? pick('apiKey') : '',
|
|
2102
|
-
apiKeyEnv: pick('apiKeyEnv') ?? config.embeddingKeyEnv ?? '',
|
|
2103
|
-
maxBatch: Number(pick('maxBatch')) || 32,
|
|
2104
|
-
fetchImpl: pEmb.fetchImpl,
|
|
2105
|
-
};
|
|
2106
|
-
const local = emb.mode === 'local';
|
|
2107
|
-
const hasEnvKey = Boolean(emb.apiKeyEnv && process.env[emb.apiKeyEnv]);
|
|
2108
|
-
if (!emb.model || (!local && !emb.apiKey.trim() && !hasEnvKey)) return;
|
|
2109
|
-
|
|
2110
|
-
try {
|
|
2111
|
-
if (extras.vecMeta.pending({ limit: 1 }).length === 0) return;
|
|
2112
|
-
} catch {
|
|
2113
|
-
return;
|
|
2114
|
-
}
|
|
2115
|
-
|
|
2116
|
-
autoIndexing = (async () => {
|
|
2117
|
-
try {
|
|
2118
|
-
const { createSiliconFlowEmbedding } = await import('./src/model/embedding.js');
|
|
2119
|
-
const { createVectorStore } = await import('./src/search/vector-store.js');
|
|
2120
|
-
const { createIndexer } = await import('./src/search/indexer.js');
|
|
2121
|
-
if (disposed) return;
|
|
2122
|
-
|
|
2123
|
-
const provider = createSiliconFlowEmbedding({
|
|
2124
|
-
model: emb.model,
|
|
2125
|
-
dim: emb.dim,
|
|
2126
|
-
maxBatch: emb.maxBatch,
|
|
2127
|
-
baseURL: emb.baseUrl,
|
|
2128
|
-
apiKey: emb.apiKey.trim() || undefined,
|
|
2129
|
-
apiKeyEnv: emb.apiKeyEnv,
|
|
2130
|
-
local,
|
|
2131
|
-
fetchImpl: emb.fetchImpl,
|
|
2132
|
-
});
|
|
2133
|
-
const store = createVectorStore(handle, {
|
|
2134
|
-
dim: provider.dim,
|
|
2135
|
-
logger: { warn: (m) => ctx.logger?.warn?.(`[verbatim] ${m}`) },
|
|
2136
|
-
});
|
|
2137
|
-
const indexer = createIndexer({
|
|
2138
|
-
handle,
|
|
2139
|
-
provider,
|
|
2140
|
-
extras,
|
|
2141
|
-
store,
|
|
2142
|
-
logger: { warn: (m) => ctx.logger?.warn?.(`[verbatim] ${m}`) },
|
|
2143
|
-
});
|
|
2144
|
-
const r = await indexer.indexPending({ limit: 64 });
|
|
2145
|
-
if (!disposed && r.indexed > 0) {
|
|
2146
|
-
ctx.logger?.info?.(`[verbatim] 自动增量补索引 ${r.indexed} 条(${r.elapsedMs}ms)`);
|
|
2147
|
-
}
|
|
2148
|
-
} catch (e) {
|
|
2149
|
-
if (!disposed) ctx.logger?.warn?.(`[verbatim] 自动补索引跳过:${e?.message ?? e}`);
|
|
2150
|
-
} finally {
|
|
2151
|
-
autoIndexing = null;
|
|
2152
|
-
}
|
|
2153
|
-
})();
|
|
2154
|
-
};
|
|
2155
|
-
|
|
2156
|
-
/** 开关被改写(如打开 record)后失效该会话日志的 mtime 缓存,确保下次读取立即重同步 */
|
|
2157
|
-
const invalidateFresh = (sessionId) => {
|
|
2158
|
-
if (!sessionId) {
|
|
2159
|
-
lastMtimes.clear();
|
|
2160
|
-
return;
|
|
2161
|
-
}
|
|
2162
|
-
const file = config.sessionFile ?? findSessionFile(dshHome, sessionId);
|
|
2163
|
-
if (file) lastMtimes.delete(file);
|
|
2164
|
-
};
|
|
2165
|
-
|
|
2166
|
-
/**
|
|
2167
|
-
* 增量同步指定会话(或最新会话)的日志到记忆库。
|
|
2168
|
-
* @param {string|{sessionId?: string|null}|null} [target]
|
|
2169
|
-
* @param {{skipAutoIndex?: boolean}} [syncOpts]
|
|
2170
|
-
*/
|
|
2171
|
-
const ensureFresh = async (target = null, syncOpts = {}) => {
|
|
2172
|
-
if (disposed) return { skipped: true, inserted: 0 };
|
|
2173
|
-
const sessionId = typeof target === 'string'
|
|
2174
|
-
? target
|
|
2175
|
-
: (typeof target?.sessionId === 'string' ? target.sessionId : null);
|
|
2176
|
-
|
|
2177
|
-
const file = config.sessionFile
|
|
2178
|
-
?? (sessionId ? findSessionFile(dshHome, sessionId) : null)
|
|
2179
|
-
?? findLatestSession(dshHome);
|
|
2180
|
-
if (!file) return { skipped: true, inserted: 0 };
|
|
2181
|
-
|
|
2182
|
-
let stat;
|
|
2183
|
-
try { stat = fs.statSync(file); } catch { return { skipped: true, inserted: 0 }; }
|
|
2184
|
-
if (stat.mtimeMs === lastMtimes.get(file)) return { skipped: true, inserted: 0 };
|
|
2185
|
-
if (syncingFiles.has(file)) return syncingFiles.get(file);
|
|
2186
|
-
|
|
2187
|
-
const job = (async () => {
|
|
2188
|
-
const t0 = Date.now();
|
|
2189
|
-
try {
|
|
2190
|
-
const lockKey = sessionId || file;
|
|
2191
|
-
const r = await hostSessionLock.withLock(lockKey, () => importSession(file, { handle, dbRoot }));
|
|
2192
|
-
lastMtimes.set(file, stat.mtimeMs);
|
|
2193
|
-
const inserted = Number(r?.ingest?.inserted ?? 0);
|
|
2194
|
-
ctx.logger?.info?.(`[verbatim] 同步 ${Date.now() - t0}ms:${r?.ingest?.inserted ?? '?'} 条`);
|
|
2195
|
-
if (!syncOpts.skipAutoIndex && inserted > 0) {
|
|
2196
|
-
scheduleAutoIndex();
|
|
2197
|
-
if (sessionId) scheduleAutoRefine(sessionId);
|
|
2198
|
-
}
|
|
2199
|
-
return { skipped: false, inserted };
|
|
2200
|
-
} catch (e) {
|
|
2201
|
-
ctx.logger?.warn?.(`[verbatim] 同步失败(继续用现有数据):${e.message}`);
|
|
2202
|
-
return { skipped: false, inserted: 0, error: e.message };
|
|
2203
|
-
} finally {
|
|
2204
|
-
syncingFiles.delete(file);
|
|
2205
|
-
}
|
|
2206
|
-
})();
|
|
2207
|
-
syncingFiles.set(file, job);
|
|
2208
|
-
return job;
|
|
2209
|
-
};
|
|
2210
|
-
|
|
2211
|
-
/* ───────── 工具定义 ───────── */
|
|
2212
|
-
|
|
2213
|
-
// 插件 config 里如果显式给了 `session`(测试/排障用手动覆盖),就用它当所有会话的配置;
|
|
2214
|
-
// 平时不传 —— 开关必须按会话读 `$DSH_HOME/verbatim/sessions/<id>.json`(A3)。
|
|
2215
|
-
const explicitToolConfig = config.session && Object.keys(config.session).length
|
|
2216
|
-
? { ...defaultSessionConfig(), ...config.session }
|
|
2217
|
-
: undefined;
|
|
2218
|
-
|
|
2219
|
-
const hostSessionLock = createSessionLock();
|
|
2220
|
-
const recallLogEntries = [];
|
|
2221
|
-
const pushRecallEntry = (entry) => {
|
|
2222
|
-
recallLogEntries.unshift(entry);
|
|
2223
|
-
if (recallLogEntries.length > 50) recallLogEntries.length = 50;
|
|
2224
|
-
};
|
|
2225
|
-
|
|
2226
|
-
let autoRefining = null;
|
|
2227
|
-
const dailyRefineBudget = { day: '', used: 0 };
|
|
2228
|
-
const scheduleAutoRefine = (sessionId) => {
|
|
2229
|
-
if (disposed || autoRefining || !sessionId) return;
|
|
2230
|
-
let g;
|
|
2231
|
-
try { g = loadGlobalConfig({ dshHome }).config; } catch { return; }
|
|
2232
|
-
const llm = g.llm ?? {};
|
|
2233
|
-
if (llm.enabled !== true || llm.autoRefine !== true || !llm.model) return;
|
|
2234
|
-
const today = dayKeyInZone(Date.now());
|
|
2235
|
-
if (dailyRefineBudget.day !== today) {
|
|
2236
|
-
dailyRefineBudget.day = today;
|
|
2237
|
-
dailyRefineBudget.used = 0;
|
|
2238
|
-
}
|
|
2239
|
-
const limit = Number.isFinite(Number(llm.dailyLimit)) ? Math.max(0, Math.trunc(Number(llm.dailyLimit))) : 50;
|
|
2240
|
-
if (limit <= 0 || dailyRefineBudget.used >= limit) return;
|
|
2241
|
-
|
|
2242
|
-
let hostLlm = null;
|
|
2243
|
-
try { hostLlm = (typeof ctx.get === 'function' ? ctx.get('llm') : ctx.llm) ?? null; } catch { return; }
|
|
2244
|
-
if (!hostLlm) return;
|
|
2245
|
-
|
|
2246
|
-
autoRefining = (async () => {
|
|
2247
|
-
try {
|
|
2248
|
-
const unrefined = repo.scenesByTimeRange(sessionId, 0, Number.MAX_SAFE_INTEGER, 5000)
|
|
2249
|
-
.filter((s) => s.gistSource !== 'llm');
|
|
2250
|
-
const remain = Math.max(0, limit - dailyRefineBudget.used);
|
|
2251
|
-
const batch = unrefined.slice(0, Math.min(remain, 8));
|
|
2252
|
-
if (batch.length === 0) return;
|
|
2253
|
-
const { createHostLlmAdapter } = await import('./src/host/dsh-llm.js');
|
|
2254
|
-
const { generateGist } = await import('./src/derive/gist.js');
|
|
2255
|
-
const llmAdapter = createHostLlmAdapter(hostLlm, { provider: llm.provider || '', model: llm.model });
|
|
2256
|
-
let cursor = 0;
|
|
2257
|
-
let done = 0;
|
|
2258
|
-
const worker = async () => {
|
|
2259
|
-
while (!disposed && cursor < batch.length) {
|
|
2260
|
-
const sc = batch[cursor++];
|
|
2261
|
-
try {
|
|
2262
|
-
const msgs = repo.msgsByScene(sc.id, false);
|
|
2263
|
-
if (msgs.length === 0) continue;
|
|
2264
|
-
const gr = await generateGist({ llm: llmAdapter, msgs, startAt: sc.startAt, endAt: sc.endAt });
|
|
2265
|
-
if (gr.ok && gr.gist) {
|
|
2266
|
-
repo.setSceneGist(sc.id, gr.gist, { source: 'llm' });
|
|
2267
|
-
dailyRefineBudget.used += 1;
|
|
2268
|
-
done += 1;
|
|
2269
|
-
}
|
|
2270
|
-
} catch { /* 单场失败静默跳过 */ }
|
|
2271
|
-
}
|
|
2272
|
-
};
|
|
2273
|
-
await Promise.all([worker(), worker()]);
|
|
2274
|
-
if (!disposed && done > 0) {
|
|
2275
|
-
ctx.logger?.info?.(`[verbatim] 后台空闲自动补齐 LLM 摘要 ${done} 场(今日已用 ${dailyRefineBudget.used}/${limit})`);
|
|
2276
|
-
}
|
|
2277
|
-
} catch (e) {
|
|
2278
|
-
if (!disposed) ctx.logger?.warn?.(`[verbatim] 后台自动补齐摘要跳过:${e?.message ?? e}`);
|
|
2279
|
-
} finally {
|
|
2280
|
-
autoRefining = null;
|
|
2281
|
-
}
|
|
2282
|
-
})();
|
|
2283
|
-
};
|
|
2284
|
-
|
|
2285
|
-
/** 把库里的 handler 包成 DSH 工具定义(绑定所属 sessionId 以精确同步该会话) */
|
|
2286
|
-
const toDshTool = (t, sessionId) => ({
|
|
2287
|
-
name: t.name,
|
|
2288
|
-
description: t.description,
|
|
2289
|
-
parameters: t.parameters,
|
|
2290
|
-
output: textOutput(),
|
|
2291
|
-
async execute(args) {
|
|
2292
|
-
const t0 = Date.now();
|
|
2293
|
-
await ensureFresh(sessionId);
|
|
2294
|
-
let trace = null;
|
|
2295
|
-
const onResult = t.name === 'memory_search'
|
|
2296
|
-
? (info) => { trace = info; }
|
|
2297
|
-
: undefined;
|
|
2298
|
-
// 工具实例本身已经闭包了 sessionId(createSessionToolSet),这里传 handle 不会丢会话
|
|
2299
|
-
const text = await t.handler(args ?? {}, { handle, repo, extras, onResult });
|
|
2300
|
-
if (t.name === 'memory_search') {
|
|
2301
|
-
const hits = Array.isArray(trace?.hits) ? trace.hits : [];
|
|
2302
|
-
const sceneMap = new Map();
|
|
2303
|
-
for (const h of hits) {
|
|
2304
|
-
if (h.sceneId !== null && h.sceneId !== undefined) {
|
|
2305
|
-
const sid = Number(h.sceneId);
|
|
2306
|
-
const prev = sceneMap.get(sid);
|
|
2307
|
-
if (prev) prev.count += 1;
|
|
2308
|
-
else sceneMap.set(sid, { sceneId: sid, startAt: h.sceneStartAt ?? h.at, endAt: h.sceneEndAt ?? h.at, count: 1 });
|
|
2309
|
-
}
|
|
2310
|
-
}
|
|
2311
|
-
pushRecallEntry({
|
|
2312
|
-
id: `rc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`,
|
|
2313
|
-
at: Date.now(),
|
|
2314
|
-
sessionId,
|
|
2315
|
-
query: String(args?.query ?? '').trim(),
|
|
2316
|
-
when: args?.when ? String(args.when) : null,
|
|
2317
|
-
scope: String(args?.scope ?? 'msg'),
|
|
2318
|
-
elapsedMs: Date.now() - t0,
|
|
2319
|
-
resultChars: String(text ?? '').length,
|
|
2320
|
-
hitCount: hits.length,
|
|
2321
|
-
counts: trace?.meta?.counts ?? { keyword: (trace?.keywordRows ?? []).length, vector: 0 },
|
|
2322
|
-
usedRoutes: trace?.meta?.usedRoutes ?? ((trace?.keywordRows ?? []).length > 0 ? ['keyword'] : []),
|
|
2323
|
-
reranked: trace?.meta?.reranked === true,
|
|
2324
|
-
rerankModel: trace?.meta?.rerankModel ?? null,
|
|
2325
|
-
hitScenes: [...sceneMap.values()].slice(0, 6),
|
|
2326
|
-
});
|
|
2327
|
-
}
|
|
2328
|
-
return { text: String(text) };
|
|
2329
|
-
},
|
|
2330
|
-
});
|
|
2331
|
-
|
|
2332
|
-
/* ───────── 注册:给每个 Agent 的 session 上下文装一份 ───────── */
|
|
2333
|
-
|
|
2334
|
-
const cleanups = new Map(); // sessionId -> cleanup[]
|
|
2335
|
-
const liveAgents = new Map(); // sessionId -> agent
|
|
2336
|
-
|
|
2337
|
-
function registerFor(agent) {
|
|
2338
|
-
const sessionId = agent?.session?.id;
|
|
2339
|
-
if (typeof sessionId !== 'string') return;
|
|
2340
|
-
liveAgents.set(sessionId, agent);
|
|
2341
|
-
if (cleanups.has(sessionId)) return;
|
|
2342
|
-
|
|
2343
|
-
const sessionCtx = agent.ctx;
|
|
2344
|
-
if (!sessionCtx?.tools?.register) return;
|
|
2345
|
-
|
|
2346
|
-
// **工具必须按会话建**(A1):createSessionToolSet 把 sessionId 闭包进每个 handler,
|
|
2347
|
-
// TA在 A 会话里查不到 B 会话的 msg / scene / note;开关也按
|
|
2348
|
-
// `$DSH_HOME/verbatim/sessions/<id>.json` 读(A3),A 关掉不影响 B。
|
|
2349
|
-
let set;
|
|
2350
|
-
try {
|
|
2351
|
-
set = createSessionToolSet({
|
|
2352
|
-
handle,
|
|
2353
|
-
repo,
|
|
2354
|
-
extras,
|
|
2355
|
-
sessionId,
|
|
2356
|
-
dshHome,
|
|
2357
|
-
config: explicitToolConfig,
|
|
2358
|
-
logger: { warn: (m) => ctx.logger?.warn?.(m) },
|
|
2359
|
-
});
|
|
2360
|
-
} catch (e) {
|
|
2361
|
-
ctx.logger?.warn?.(`[verbatim] 会话 ${sessionId} 建工具集失败:${e.message}`);
|
|
2362
|
-
return;
|
|
2363
|
-
}
|
|
2364
|
-
|
|
2365
|
-
const dshTools = set.tools.map((t) => toDshTool(t, sessionId));
|
|
2366
|
-
const undos = [];
|
|
2367
|
-
try {
|
|
2368
|
-
for (const def of dshTools) {
|
|
2369
|
-
undos.push(sessionCtx.tools.register(def));
|
|
2370
|
-
}
|
|
2371
|
-
// 注销时一并收尾:set.close() 是引用计数,不会关掉别的会话共用的那条连接
|
|
2372
|
-
undos.push(() => set.close());
|
|
2373
|
-
cleanups.set(sessionId, undos);
|
|
2374
|
-
writeStatus({ registeredFor: [...cleanups.keys()], toolCount: dshTools.length });
|
|
2375
|
-
ctx.logger?.info?.(
|
|
2376
|
-
`[verbatim] 已为会话 ${sessionId} 注册 ${dshTools.length} 个记忆工具`
|
|
2377
|
-
+ (dshTools.length === 0 ? '(配置里两个开关都关着,不注册是对的)' : ''),
|
|
2378
|
-
);
|
|
2379
|
-
} catch (e) {
|
|
2380
|
-
// 注册失败要回滚已经注册的那几个,不留半截状态
|
|
2381
|
-
for (const undo of undos) {
|
|
2382
|
-
try { undo?.(); } catch { /* 回滚失败也没别的办法 */ }
|
|
2383
|
-
}
|
|
2384
|
-
try { set.close(); } catch { /* 同上 */ }
|
|
2385
|
-
ctx.logger?.warn?.(`[verbatim] 注册工具失败:${e.message}`);
|
|
2386
|
-
}
|
|
2387
|
-
}
|
|
2388
|
-
|
|
2389
|
-
function unregisterFor(sessionId) {
|
|
2390
|
-
const undos = cleanups.get(sessionId);
|
|
2391
|
-
if (!undos) return;
|
|
2392
|
-
for (const undo of undos) {
|
|
2393
|
-
try { undo?.(); } catch { /* 已经没了就算了 */ }
|
|
2394
|
-
}
|
|
2395
|
-
cleanups.delete(sessionId);
|
|
2396
|
-
}
|
|
2397
|
-
|
|
2398
|
-
function refreshToolsFor(sessionId) {
|
|
2399
|
-
if (typeof sessionId !== 'string' || !sessionId) return false;
|
|
2400
|
-
unregisterFor(sessionId);
|
|
2401
|
-
let agent = liveAgents.get(sessionId);
|
|
2402
|
-
if (!agent) {
|
|
2403
|
-
try {
|
|
2404
|
-
const agents = ctx.get('agents');
|
|
2405
|
-
if (typeof agents?.get === 'function') agent = agents.get(sessionId);
|
|
2406
|
-
} catch { /* ignore */ }
|
|
2407
|
-
}
|
|
2408
|
-
if (agent) {
|
|
2409
|
-
registerFor(agent);
|
|
2410
|
-
return true;
|
|
2411
|
-
}
|
|
2412
|
-
return false;
|
|
2413
|
-
}
|
|
2414
|
-
|
|
2415
|
-
// 已经在跑的 Agent(插件热装/重载时会走到这里)
|
|
2416
|
-
try {
|
|
2417
|
-
const agents = ctx.get('agents');
|
|
2418
|
-
// 诊断:agents 服务到底暴露了什么(一次性,用来确定怎么列出当前 Agent)
|
|
2419
|
-
const proto = agents ? Object.getPrototypeOf(agents) : null;
|
|
2420
|
-
const keys = !agents ? '(服务不存在)' : proto ? Object.getOwnPropertyNames(proto).join(',') : '(无原型)';
|
|
2421
|
-
ctx.logger?.info?.(`[verbatim] agents 服务原型方法: ${keys}`);
|
|
2422
|
-
const list = typeof agents?.list === 'function' ? agents.list()
|
|
2423
|
-
: typeof agents?.all === 'function' ? agents.all()
|
|
2424
|
-
: typeof agents?.values === 'function' ? [...agents.values()]
|
|
2425
|
-
: [];
|
|
2426
|
-
ctx.logger?.info?.(`[verbatim] 现有 Agent 数量: ${Array.isArray(list) ? list.length : '(不是数组)'}`);
|
|
2427
|
-
for (const agent of list) registerFor(agent);
|
|
2428
|
-
|
|
2429
|
-
// ── 诊断:agents 服务到底覆盖哪些会话 ──
|
|
2430
|
-
// 实测踩到:Web GUI 里正在跑的这个 agent 不在 list() 里,
|
|
2431
|
-
// 结果是"插件装好了、库在同步、但TA在当前会话看不到工具"。
|
|
2432
|
-
try {
|
|
2433
|
-
const listIds = (Array.isArray(list) ? list : []).map((a) => a?.session?.id).filter(Boolean);
|
|
2434
|
-
const dirRoot = path.join(dshHome, 'sessions');
|
|
2435
|
-
const diskIds = [];
|
|
2436
|
-
if (fs.existsSync(dirRoot)) {
|
|
2437
|
-
for (const ws of fs.readdirSync(dirRoot, { withFileTypes: true })) {
|
|
2438
|
-
if (!ws.isDirectory()) continue;
|
|
2439
|
-
const wsd = path.join(dirRoot, ws.name);
|
|
2440
|
-
let subs = [];
|
|
2441
|
-
try { subs = fs.readdirSync(wsd, { withFileTypes: true }); } catch { continue; }
|
|
2442
|
-
for (const s of subs) {
|
|
2443
|
-
if (s.isDirectory() && fs.existsSync(path.join(wsd, s.name, 'session.v4.jsonl.zstd'))) {
|
|
2444
|
-
diskIds.push(s.name);
|
|
2445
|
-
}
|
|
2446
|
-
}
|
|
2447
|
-
}
|
|
2448
|
-
}
|
|
2449
|
-
const gettable = diskIds.filter((id) => {
|
|
2450
|
-
if (listIds.includes(id)) return true;
|
|
2451
|
-
try { return agents?.get?.(id) !== undefined; } catch { return false; }
|
|
2452
|
-
});
|
|
2453
|
-
writeStatus({
|
|
2454
|
-
diag: {
|
|
2455
|
-
agentsListCount: listIds.length,
|
|
2456
|
-
agentsListIds: listIds.slice(0, 8),
|
|
2457
|
-
diskSessionCount: diskIds.length,
|
|
2458
|
-
gettableCount: gettable.length,
|
|
2459
|
-
gettableSample: gettable.slice(0, 8),
|
|
2460
|
-
hasGet: typeof agents?.get === 'function',
|
|
2461
|
-
},
|
|
2462
|
-
});
|
|
2463
|
-
ctx.logger?.info?.(
|
|
2464
|
-
`[verbatim] agents.list=${listIds.length} / 磁盘会话=${diskIds.length} / 能拿到 Agent 的=${gettable.length}`,
|
|
2465
|
-
);
|
|
2466
|
-
} catch (e) { ctx.logger?.warn?.(`[verbatim] 诊断失败:${e.message}`); }
|
|
2467
|
-
|
|
2468
|
-
// **补注册当前会话**(实测踩到:list() 里往往没有"正在跑的这一轮"的 Agent)。
|
|
2469
|
-
// 办法是从最近修改的会话日志反推 sessionId,再 agents.get(id) 拿 Agent。
|
|
2470
|
-
// 不这么做的话:插件装好了、库里数据也在同步,但TA在这个会话里根本看不到工具。
|
|
2471
|
-
const latestLog = config.sessionFile ?? findLatestSession(dshHome);
|
|
2472
|
-
if (latestLog) {
|
|
2473
|
-
const sid = path.basename(path.dirname(latestLog));
|
|
2474
|
-
if (!cleanups.has(sid)) {
|
|
2475
|
-
const agent = typeof agents?.get === 'function' ? agents.get(sid) : undefined;
|
|
2476
|
-
if (agent) {
|
|
2477
|
-
registerFor(agent);
|
|
2478
|
-
ctx.logger?.info?.(`[verbatim] 已补注册当前会话 ${sid}`);
|
|
2479
|
-
} else {
|
|
2480
|
-
writeStatus({ missedSession: sid, note: 'agents.get 拿不到这个会话的 Agent,等 agent/created' });
|
|
2481
|
-
ctx.logger?.warn?.(`[verbatim] agents.get(${sid}) 拿不到 Agent —— 当前会话暂时没有工具,等下一次 agent/created`);
|
|
2482
|
-
}
|
|
2483
|
-
}
|
|
2484
|
-
}
|
|
2485
|
-
} catch (e) { ctx.logger?.warn?.(`[verbatim] 遍历 Agent 失败:${e.message}`); }
|
|
2486
|
-
|
|
2487
|
-
const unsubCreated = ctx.on('agent/created', ({ agent }) => registerFor(agent));
|
|
2488
|
-
const unsubDisposed = ctx.on('agent/disposed', ({ agent }) => {
|
|
2489
|
-
const sessionId = agent?.session?.id;
|
|
2490
|
-
if (typeof sessionId === 'string') {
|
|
2491
|
-
unregisterFor(sessionId);
|
|
2492
|
-
liveAgents.delete(sessionId);
|
|
2493
|
-
}
|
|
2494
|
-
});
|
|
2495
|
-
|
|
2496
|
-
/* ───────── 面板 RPC(PANEL.md §5,共 17 个方法) ───────── */
|
|
2497
|
-
|
|
2498
|
-
const panelApi = createPanelApi({
|
|
2499
|
-
handle,
|
|
2500
|
-
repo,
|
|
2501
|
-
extras,
|
|
2502
|
-
dbPath,
|
|
2503
|
-
dshHome,
|
|
2504
|
-
config,
|
|
2505
|
-
sessionLock: hostSessionLock,
|
|
2506
|
-
recallLog: recallLogEntries,
|
|
2507
|
-
logger: ctx.logger,
|
|
2508
|
-
getHostLlm: () => {
|
|
2509
|
-
try {
|
|
2510
|
-
return (typeof ctx.get === 'function' ? ctx.get('llm') : ctx.llm) ?? null;
|
|
2511
|
-
} catch {
|
|
2512
|
-
return null;
|
|
2513
|
-
}
|
|
2514
|
-
},
|
|
2515
|
-
syncSession: async (sid) => {
|
|
2516
|
-
invalidateFresh(sid);
|
|
2517
|
-
return await ensureFresh(sid, { skipAutoIndex: true });
|
|
2518
|
-
},
|
|
2519
|
-
});
|
|
2520
|
-
|
|
2521
|
-
ctx.effect(
|
|
2522
|
-
() => ctx.webServer.register({
|
|
2523
|
-
kind: 'prefix',
|
|
2524
|
-
path: API_PREFIX,
|
|
2525
|
-
handler: createPanelHandler(panelApi, {
|
|
2526
|
-
beforeRequest: ensureFresh,
|
|
2527
|
-
afterCall: ({ method, params }) => {
|
|
2528
|
-
// 打开 record 时清除该会话 mtime 缓存,下一次刷新面板/调工具立即补同步历史日志
|
|
2529
|
-
if (method === 'set' && params?.key === 'record' && params?.value === true) {
|
|
2530
|
-
invalidateFresh(params.sessionId);
|
|
2531
|
-
}
|
|
2532
|
-
// 切换 tools 或 record 时热更新当前活跃 Agent 的工具注入(memory_remember 依赖两者)
|
|
2533
|
-
if (method === 'set' && (params?.key === 'tools' || params?.key === 'record') && typeof params?.sessionId === 'string') {
|
|
2534
|
-
refreshToolsFor(params.sessionId);
|
|
2535
|
-
}
|
|
2536
|
-
if (method === 'batchSetSessionFlags' && (params?.key === 'tools' || params?.key === 'record' || params?.tools !== undefined || params?.record !== undefined)) {
|
|
2537
|
-
for (const sid of [...liveAgents.keys()]) refreshToolsFor(sid);
|
|
2538
|
-
}
|
|
2539
|
-
},
|
|
2540
|
-
}),
|
|
2541
|
-
}),
|
|
2542
|
-
'dsh-verbatim: panel api',
|
|
2543
|
-
);
|
|
2544
|
-
|
|
2545
|
-
ctx.logger?.info?.(
|
|
2546
|
-
`[verbatim] 面板 RPC 已挂载:${API_PREFIX}/panel.{${PANEL_METHODS.join(',')}}`,
|
|
2547
|
-
);
|
|
2548
|
-
|
|
2549
|
-
/* ───────── 清理 ───────── */
|
|
2550
|
-
|
|
2551
|
-
return () => {
|
|
2552
|
-
disposed = true;
|
|
2553
|
-
try { if (typeof unsubCreated === 'function') unsubCreated(); } catch { /* ignore */ }
|
|
2554
|
-
try { if (typeof unsubDisposed === 'function') unsubDisposed(); } catch { /* ignore */ }
|
|
2555
|
-
for (const sessionId of [...cleanups.keys()]) unregisterFor(sessionId);
|
|
2556
|
-
try { handle.close(); } catch { /* 关不上也不影响退出 */ }
|
|
2557
|
-
};
|
|
2558
|
-
}
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* dsh-verbatim —— DSH Host 插件入口。
|
|
4
|
+
*
|
|
5
|
+
* 这是插件形态的入口(`package.json` 的 `.`);库形态在 `./src/index.js`;
|
|
6
|
+
* 面板 RPC 业务层与 HTTP 适配层在 `./src/host/panel-api.js`。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
|
|
13
|
+
import { openDb, defaultDbPath } from './src/store/db.js';
|
|
14
|
+
import { createRepo, createExtras } from './src/store/repo.js';
|
|
15
|
+
import { createSessionToolSet } from './src/tools/index.js';
|
|
16
|
+
import { defaultSessionConfig } from './src/config/session-config.js';
|
|
17
|
+
import { importSession } from './src/pipeline.js';
|
|
18
|
+
import { shanghaiParts } from './src/tools/format.js';
|
|
19
|
+
import { loadGlobalConfig } from './src/config/global-config.js';
|
|
20
|
+
import { createSessionLock } from './src/host/session-lock.js';
|
|
21
|
+
import {
|
|
22
|
+
API_PREFIX,
|
|
23
|
+
PANEL_METHODS,
|
|
24
|
+
PanelError,
|
|
25
|
+
createPanelApi,
|
|
26
|
+
createPanelHandler,
|
|
27
|
+
findLatestSession,
|
|
28
|
+
findSessionFile,
|
|
29
|
+
} from './src/host/panel-api.js';
|
|
30
|
+
|
|
31
|
+
export {
|
|
32
|
+
API_PREFIX,
|
|
33
|
+
PANEL_METHODS,
|
|
34
|
+
PanelError,
|
|
35
|
+
createPanelApi,
|
|
36
|
+
createPanelHandler,
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** 依赖 DSH 的工具注册表与 HTTP 载体 */
|
|
40
|
+
export const inject = ['tools', 'webServer'];
|
|
41
|
+
|
|
42
|
+
function textOutput() {
|
|
43
|
+
return {
|
|
44
|
+
schema: {
|
|
45
|
+
type: 'object',
|
|
46
|
+
properties: { text: { type: 'string' } },
|
|
47
|
+
required: ['text'],
|
|
48
|
+
additionalProperties: false,
|
|
49
|
+
},
|
|
50
|
+
render(_args, value) {
|
|
51
|
+
return [{ type: 'text', text: String(value?.text ?? '') }];
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function apply(ctx, config = {}) {
|
|
57
|
+
const dshHome = config.dshHome ?? process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh');
|
|
58
|
+
const dbPath = config.dbPath ?? defaultDbPath(dshHome);
|
|
59
|
+
|
|
60
|
+
const dbRoot = dbPath === ':memory:'
|
|
61
|
+
? path.join(dshHome, 'verbatim')
|
|
62
|
+
: path.dirname(path.resolve(dbPath));
|
|
63
|
+
|
|
64
|
+
let configuredVecDim;
|
|
65
|
+
try {
|
|
66
|
+
const gCfg = loadGlobalConfig({ dshHome }).config;
|
|
67
|
+
const rawDim = Number(config?.embedding?.dim ?? gCfg?.embedding?.dim);
|
|
68
|
+
if (Number.isInteger(rawDim) && rawDim > 0) configuredVecDim = rawDim;
|
|
69
|
+
} catch { /* ignore */ }
|
|
70
|
+
|
|
71
|
+
let handle;
|
|
72
|
+
try {
|
|
73
|
+
handle = openDb({
|
|
74
|
+
dbPath,
|
|
75
|
+
vecDim: configuredVecDim,
|
|
76
|
+
logger: { warn: (m) => ctx.logger?.warn?.(`[verbatim] ${m}`) },
|
|
77
|
+
});
|
|
78
|
+
} catch (e) {
|
|
79
|
+
ctx.logger?.error?.(`[verbatim] 记忆库打不开:${e.message}`);
|
|
80
|
+
return () => {};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const writeJsonAtomic = (filePath, data) => {
|
|
84
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
85
|
+
const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
|
|
86
|
+
try {
|
|
87
|
+
fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8');
|
|
88
|
+
fs.renameSync(tmp, filePath);
|
|
89
|
+
} catch (e) {
|
|
90
|
+
try { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); } catch { /* ignore */ }
|
|
91
|
+
throw e;
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const statusFile = path.join(dbPath === ':memory:' ? dbRoot : path.dirname(dbPath), 'plugin-status.json');
|
|
96
|
+
const writeStatus = (patch) => {
|
|
97
|
+
try {
|
|
98
|
+
const prev = fs.existsSync(statusFile) ? JSON.parse(fs.readFileSync(statusFile, 'utf8')) : {};
|
|
99
|
+
writeJsonAtomic(statusFile, { ...prev, ...patch, at: new Date().toISOString() });
|
|
100
|
+
} catch { /* ignore */ }
|
|
101
|
+
};
|
|
102
|
+
const instanceId = Date.now() + '-' + Math.random().toString(36).slice(2, 7);
|
|
103
|
+
writeStatus({ loaded: true, instanceId, dbPath, hasVec: handle.hasVec === true });
|
|
104
|
+
|
|
105
|
+
const repo = createRepo(handle);
|
|
106
|
+
const extras = createExtras(handle);
|
|
107
|
+
ctx.logger?.info?.(`[verbatim] 记忆库已打开:${dbPath}(${handle.hasVec ? '向量可用' : '降级为暴力余弦'})`);
|
|
108
|
+
|
|
109
|
+
/* ───────── 增量同步与轻量自动补索引 ───────── */
|
|
110
|
+
|
|
111
|
+
const hostSessionLock = createSessionLock();
|
|
112
|
+
const lastMtimes = new Map();
|
|
113
|
+
const readerCache = new Map();
|
|
114
|
+
const syncingFiles = new Map();
|
|
115
|
+
let disposed = false;
|
|
116
|
+
let autoIndexing = null;
|
|
117
|
+
let dbMutationEpoch = 0;
|
|
118
|
+
|
|
119
|
+
const scheduleAutoIndex = () => {
|
|
120
|
+
if (disposed || autoIndexing) return;
|
|
121
|
+
let globalCfg;
|
|
122
|
+
try {
|
|
123
|
+
globalCfg = loadGlobalConfig({ dshHome }).config;
|
|
124
|
+
} catch {
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
if (globalCfg?.index?.autoIndex !== true) return;
|
|
128
|
+
|
|
129
|
+
const gEmb = globalCfg.embedding ?? {};
|
|
130
|
+
const pEmb = config.embedding ?? {};
|
|
131
|
+
const pick = (k) => (pEmb[k] !== undefined && pEmb[k] !== null && pEmb[k] !== '' ? pEmb[k] : gEmb[k]);
|
|
132
|
+
const emb = {
|
|
133
|
+
mode: pick('mode') === 'local' ? 'local' : 'remote',
|
|
134
|
+
model: pick('model') || 'Qwen/Qwen3-Embedding-4B',
|
|
135
|
+
dim: Number(pick('dim')) || 1024,
|
|
136
|
+
baseUrl: pick('baseUrl') || pick('baseURL') || 'https://api.siliconflow.cn/v1',
|
|
137
|
+
apiKey: typeof pick('apiKey') === 'string' ? pick('apiKey') : '',
|
|
138
|
+
apiKeyEnv: pick('apiKeyEnv') ?? config.embeddingKeyEnv ?? '',
|
|
139
|
+
maxBatch: Number(pick('maxBatch')) || 32,
|
|
140
|
+
fetchImpl: pEmb.fetchImpl,
|
|
141
|
+
};
|
|
142
|
+
const local = emb.mode === 'local';
|
|
143
|
+
const hasEnvKey = Boolean(emb.apiKeyEnv && process.env[emb.apiKeyEnv]);
|
|
144
|
+
if (!emb.model || (!local && !emb.apiKey.trim() && !hasEnvKey)) return;
|
|
145
|
+
|
|
146
|
+
try {
|
|
147
|
+
if (extras.vecMeta.pending({ limit: 1 }).length === 0) return;
|
|
148
|
+
} catch {
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const startEpoch = dbMutationEpoch;
|
|
153
|
+
autoIndexing = (async () => {
|
|
154
|
+
try {
|
|
155
|
+
const { createSiliconFlowEmbedding } = await import('./src/model/embedding.js');
|
|
156
|
+
const { createVectorStore } = await import('./src/search/vector-store.js');
|
|
157
|
+
const { createIndexer } = await import('./src/search/indexer.js');
|
|
158
|
+
if (disposed) return;
|
|
159
|
+
|
|
160
|
+
const provider = createSiliconFlowEmbedding({
|
|
161
|
+
model: emb.model,
|
|
162
|
+
dim: emb.dim,
|
|
163
|
+
maxBatch: emb.maxBatch,
|
|
164
|
+
baseURL: emb.baseUrl,
|
|
165
|
+
apiKey: emb.apiKey.trim() || undefined,
|
|
166
|
+
apiKeyEnv: emb.apiKeyEnv,
|
|
167
|
+
local,
|
|
168
|
+
fetchImpl: emb.fetchImpl,
|
|
169
|
+
});
|
|
170
|
+
const store = createVectorStore(handle, {
|
|
171
|
+
dim: provider.dim,
|
|
172
|
+
logger: { warn: (m) => ctx.logger?.warn?.(`[verbatim] ${m}`) },
|
|
173
|
+
});
|
|
174
|
+
const indexer = createIndexer({
|
|
175
|
+
handle,
|
|
176
|
+
provider,
|
|
177
|
+
extras,
|
|
178
|
+
store,
|
|
179
|
+
logger: { warn: (m) => ctx.logger?.warn?.(`[verbatim] ${m}`) },
|
|
180
|
+
});
|
|
181
|
+
const r = await hostSessionLock.withLock('__auto_index__', () => indexer.indexPending({ limit: 64 }));
|
|
182
|
+
// 若补索引期间发生过 clearSession / rebuild 等变更,顺手清理可能残留的孤儿向量
|
|
183
|
+
if (!disposed && dbMutationEpoch !== startEpoch) {
|
|
184
|
+
try { store.pruneOrphans(); } catch { /* ignore */ }
|
|
185
|
+
}
|
|
186
|
+
if (!disposed && r.indexed > 0) {
|
|
187
|
+
ctx.logger?.info?.(`[verbatim] 自动增量补索引 ${r.indexed} 条(${r.elapsedMs}ms)`);
|
|
188
|
+
}
|
|
189
|
+
} catch (e) {
|
|
190
|
+
if (!disposed) ctx.logger?.warn?.(`[verbatim] 自动补索引跳过:${e?.message ?? e}`);
|
|
191
|
+
} finally {
|
|
192
|
+
autoIndexing = null;
|
|
193
|
+
}
|
|
194
|
+
})();
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
const invalidateFresh = (sessionId) => {
|
|
198
|
+
if (!sessionId) {
|
|
199
|
+
lastMtimes.clear();
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
const file = config.sessionFile ?? findSessionFile(dshHome, sessionId);
|
|
203
|
+
if (file) lastMtimes.delete(file);
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
const ensureFresh = async (target = null, syncOpts = {}) => {
|
|
207
|
+
if (disposed) return { skipped: true, inserted: 0 };
|
|
208
|
+
const sessionId = typeof target === 'string'
|
|
209
|
+
? target
|
|
210
|
+
: (typeof target?.sessionId === 'string' ? target.sessionId : null);
|
|
211
|
+
|
|
212
|
+
const file = config.sessionFile
|
|
213
|
+
?? (sessionId ? findSessionFile(dshHome, sessionId) : null)
|
|
214
|
+
?? findLatestSession(dshHome);
|
|
215
|
+
if (!file) return { skipped: true, inserted: 0 };
|
|
216
|
+
|
|
217
|
+
let stat;
|
|
218
|
+
try { stat = fs.statSync(file); } catch { return { skipped: true, inserted: 0 }; }
|
|
219
|
+
if (stat.mtimeMs === lastMtimes.get(file)) return { skipped: true, inserted: 0 };
|
|
220
|
+
if (syncingFiles.has(file)) return syncingFiles.get(file);
|
|
221
|
+
|
|
222
|
+
const job = (async () => {
|
|
223
|
+
const t0 = Date.now();
|
|
224
|
+
try {
|
|
225
|
+
const lockKey = sessionId || file;
|
|
226
|
+
const r = await hostSessionLock.withLock(lockKey, () => importSession(file, { handle, dbRoot, readerCache }));
|
|
227
|
+
lastMtimes.set(file, stat.mtimeMs);
|
|
228
|
+
const inserted = Number(r?.ingest?.inserted ?? 0);
|
|
229
|
+
ctx.logger?.info?.(`[verbatim] 同步 ${Date.now() - t0}ms:${r?.ingest?.inserted ?? '?'} 条`);
|
|
230
|
+
if (!syncOpts.skipAutoIndex && inserted > 0) {
|
|
231
|
+
scheduleAutoIndex();
|
|
232
|
+
if (sessionId) scheduleAutoRefine(sessionId);
|
|
233
|
+
}
|
|
234
|
+
return { skipped: false, inserted };
|
|
235
|
+
} catch (e) {
|
|
236
|
+
ctx.logger?.warn?.(`[verbatim] 同步失败(继续用现有数据):${e.message}`);
|
|
237
|
+
return { skipped: false, inserted: 0, error: e.message };
|
|
238
|
+
} finally {
|
|
239
|
+
syncingFiles.delete(file);
|
|
240
|
+
}
|
|
241
|
+
})();
|
|
242
|
+
syncingFiles.set(file, job);
|
|
243
|
+
return job;
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
/* ───────── 后台自动 LLM 场景摘要精炼(按会话并发 + 持久化日预算) ───────── */
|
|
247
|
+
|
|
248
|
+
const explicitToolConfig = config.session && Object.keys(config.session).length
|
|
249
|
+
? { ...defaultSessionConfig(), ...config.session }
|
|
250
|
+
: undefined;
|
|
251
|
+
|
|
252
|
+
const recallLogEntries = [];
|
|
253
|
+
const pushRecallEntry = (entry) => {
|
|
254
|
+
recallLogEntries.unshift(entry);
|
|
255
|
+
if (recallLogEntries.length > 50) recallLogEntries.length = 50;
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
const refiningSessions = new Set();
|
|
259
|
+
const budgetFile = dbPath !== ':memory:' ? path.join(dbRoot, 'refine-budget.json') : null;
|
|
260
|
+
const readRefineBudget = (today) => {
|
|
261
|
+
if (budgetFile) {
|
|
262
|
+
try {
|
|
263
|
+
if (fs.existsSync(budgetFile)) {
|
|
264
|
+
const parsed = JSON.parse(fs.readFileSync(budgetFile, 'utf8'));
|
|
265
|
+
if (parsed && parsed.day === today && Number.isFinite(Number(parsed.used))) {
|
|
266
|
+
return { day: today, used: Math.max(0, Math.trunc(Number(parsed.used))) };
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
} catch { /* ignore */ }
|
|
270
|
+
}
|
|
271
|
+
return { day: today, used: 0 };
|
|
272
|
+
};
|
|
273
|
+
const budgetDayKey = (at = Date.now()) => {
|
|
274
|
+
const p = shanghaiParts(at, undefined);
|
|
275
|
+
return `${p.y}-${String(p.mo).padStart(2, '0')}-${String(p.d).padStart(2, '0')}`;
|
|
276
|
+
};
|
|
277
|
+
let dailyRefineBudget = readRefineBudget(budgetDayKey(Date.now()));
|
|
278
|
+
const saveRefineBudget = () => {
|
|
279
|
+
if (!budgetFile) return;
|
|
280
|
+
try {
|
|
281
|
+
writeJsonAtomic(budgetFile, dailyRefineBudget);
|
|
282
|
+
} catch { /* ignore */ }
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
const scheduleAutoRefine = (sessionId) => {
|
|
286
|
+
if (disposed || !sessionId || refiningSessions.has(sessionId)) return;
|
|
287
|
+
let g;
|
|
288
|
+
try { g = loadGlobalConfig({ dshHome }).config; } catch { return; }
|
|
289
|
+
const llm = g.llm ?? {};
|
|
290
|
+
if (llm.enabled !== true || llm.autoRefine !== true || !llm.model) return;
|
|
291
|
+
const today = budgetDayKey(Date.now());
|
|
292
|
+
if (dailyRefineBudget.day !== today) {
|
|
293
|
+
dailyRefineBudget = readRefineBudget(today);
|
|
294
|
+
}
|
|
295
|
+
const limit = Number.isFinite(Number(llm.dailyLimit)) ? Math.max(0, Math.trunc(Number(llm.dailyLimit))) : 50;
|
|
296
|
+
if (limit <= 0 || dailyRefineBudget.used >= limit) return;
|
|
297
|
+
|
|
298
|
+
let hostLlm = null;
|
|
299
|
+
try { hostLlm = (typeof ctx.get === 'function' ? ctx.get('llm') : ctx.llm) ?? null; } catch { return; }
|
|
300
|
+
if (!hostLlm) return;
|
|
301
|
+
|
|
302
|
+
refiningSessions.add(sessionId);
|
|
303
|
+
(async () => {
|
|
304
|
+
try {
|
|
305
|
+
const unrefined = await hostSessionLock.withLock(sessionId, () => (
|
|
306
|
+
repo.scenesByTimeRange(sessionId, 0, Number.MAX_SAFE_INTEGER, 5000)
|
|
307
|
+
.filter((s) => s.gistSource !== 'llm' && s.gistSource !== 'manual')
|
|
308
|
+
));
|
|
309
|
+
const remain = Math.max(0, limit - dailyRefineBudget.used);
|
|
310
|
+
const batch = unrefined.slice(0, Math.min(remain, 8));
|
|
311
|
+
if (batch.length === 0) return;
|
|
312
|
+
const { createHostLlmAdapter } = await import('./src/host/dsh-llm.js');
|
|
313
|
+
const { generateGist } = await import('./src/derive/gist.js');
|
|
314
|
+
const llmAdapter = createHostLlmAdapter(hostLlm, { provider: llm.provider || '', model: llm.model });
|
|
315
|
+
let cursor = 0;
|
|
316
|
+
let done = 0;
|
|
317
|
+
const worker = async () => {
|
|
318
|
+
while (!disposed && cursor < batch.length) {
|
|
319
|
+
if (dailyRefineBudget.used >= limit) break;
|
|
320
|
+
const sc = batch[cursor++];
|
|
321
|
+
try {
|
|
322
|
+
const msgs = await hostSessionLock.withLock(sessionId, () => repo.msgsByScene(sc.id, false));
|
|
323
|
+
if (msgs.length === 0) continue;
|
|
324
|
+
const gr = await generateGist({ llm: llmAdapter, msgs, startAt: sc.startAt, endAt: sc.endAt });
|
|
325
|
+
if (disposed || !gr.ok || !gr.gist) continue;
|
|
326
|
+
await hostSessionLock.withLock(sessionId, () => {
|
|
327
|
+
if (dailyRefineBudget.used >= limit) return;
|
|
328
|
+
// 写入前在会话锁内复核:避免覆盖人工摘要或已重建/合并的旧场景
|
|
329
|
+
const latest = repo.sceneById(sc.id);
|
|
330
|
+
if (!latest || latest.sessionId !== sessionId) return;
|
|
331
|
+
if (latest.gistSource === 'llm' || latest.gistSource === 'manual') return;
|
|
332
|
+
repo.setSceneGist(sc.id, gr.gist, { source: 'llm' });
|
|
333
|
+
dailyRefineBudget.used += 1;
|
|
334
|
+
done += 1;
|
|
335
|
+
saveRefineBudget();
|
|
336
|
+
});
|
|
337
|
+
} catch { /* ignore */ }
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
await Promise.all([worker(), worker()]);
|
|
341
|
+
if (!disposed && done > 0) {
|
|
342
|
+
ctx.logger?.info?.(`[verbatim] 后台空闲自动补齐 LLM 摘要 ${done} 场(今日已用 ${dailyRefineBudget.used}/${limit})`);
|
|
343
|
+
}
|
|
344
|
+
} catch (e) {
|
|
345
|
+
if (!disposed) ctx.logger?.warn?.(`[verbatim] 后台自动补齐摘要跳过:${e?.message ?? e}`);
|
|
346
|
+
} finally {
|
|
347
|
+
refiningSessions.delete(sessionId);
|
|
348
|
+
}
|
|
349
|
+
})();
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
/* ───────── 工具定义与生命周期 ───────── */
|
|
353
|
+
|
|
354
|
+
const toDshTool = (t, sessionId) => ({
|
|
355
|
+
name: t.name,
|
|
356
|
+
description: t.description,
|
|
357
|
+
parameters: t.parameters,
|
|
358
|
+
output: textOutput(),
|
|
359
|
+
async execute(args) {
|
|
360
|
+
const t0 = Date.now();
|
|
361
|
+
await ensureFresh(sessionId);
|
|
362
|
+
let trace = null;
|
|
363
|
+
const onResult = t.name === 'memory_search'
|
|
364
|
+
? (info) => { trace = info; }
|
|
365
|
+
: undefined;
|
|
366
|
+
const text = await t.handler(args ?? {}, { handle, repo, extras, onResult });
|
|
367
|
+
if (t.name === 'memory_search') {
|
|
368
|
+
const hits = Array.isArray(trace?.hits) ? trace.hits : [];
|
|
369
|
+
const sceneMap = new Map();
|
|
370
|
+
for (const h of hits) {
|
|
371
|
+
if (h.sceneId !== null && h.sceneId !== undefined) {
|
|
372
|
+
const sid = Number(h.sceneId);
|
|
373
|
+
const prev = sceneMap.get(sid);
|
|
374
|
+
if (prev) prev.count += 1;
|
|
375
|
+
else sceneMap.set(sid, { sceneId: sid, startAt: h.sceneStartAt ?? h.at, endAt: h.sceneEndAt ?? h.at, count: 1 });
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
pushRecallEntry({
|
|
379
|
+
id: `rc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`,
|
|
380
|
+
at: Date.now(),
|
|
381
|
+
sessionId,
|
|
382
|
+
query: String(args?.query ?? '').trim(),
|
|
383
|
+
when: args?.when ? String(args.when) : null,
|
|
384
|
+
scope: String(args?.scope ?? 'msg'),
|
|
385
|
+
elapsedMs: Date.now() - t0,
|
|
386
|
+
resultChars: String(text ?? '').length,
|
|
387
|
+
hitCount: hits.length,
|
|
388
|
+
counts: trace?.meta?.counts ?? { keyword: (trace?.keywordRows ?? []).length, vector: 0 },
|
|
389
|
+
usedRoutes: trace?.meta?.usedRoutes ?? ((trace?.keywordRows ?? []).length > 0 ? ['keyword'] : []),
|
|
390
|
+
reranked: trace?.meta?.reranked === true,
|
|
391
|
+
rerankModel: trace?.meta?.rerankModel ?? null,
|
|
392
|
+
hitScenes: [...sceneMap.values()].slice(0, 6),
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
return { text: String(text) };
|
|
396
|
+
},
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
const cleanups = new Map();
|
|
400
|
+
const liveAgents = new Map();
|
|
401
|
+
|
|
402
|
+
function registerFor(agent) {
|
|
403
|
+
const sessionId = agent?.session?.id;
|
|
404
|
+
if (typeof sessionId !== 'string') return;
|
|
405
|
+
liveAgents.set(sessionId, agent);
|
|
406
|
+
if (cleanups.has(sessionId)) return;
|
|
407
|
+
|
|
408
|
+
const sessionCtx = agent.ctx;
|
|
409
|
+
if (!sessionCtx?.tools?.register) return;
|
|
410
|
+
|
|
411
|
+
let set;
|
|
412
|
+
try {
|
|
413
|
+
set = createSessionToolSet({
|
|
414
|
+
handle,
|
|
415
|
+
repo,
|
|
416
|
+
extras,
|
|
417
|
+
sessionId,
|
|
418
|
+
dshHome,
|
|
419
|
+
config: explicitToolConfig,
|
|
420
|
+
logger: { warn: (m) => ctx.logger?.warn?.(m) },
|
|
421
|
+
});
|
|
422
|
+
} catch (e) {
|
|
423
|
+
ctx.logger?.warn?.(`[verbatim] 会话 ${sessionId} 建工具集失败:${e.message}`);
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
const dshTools = set.tools.map((t) => toDshTool(t, sessionId));
|
|
428
|
+
const undos = [];
|
|
429
|
+
try {
|
|
430
|
+
for (const def of dshTools) {
|
|
431
|
+
undos.push(sessionCtx.tools.register(def));
|
|
432
|
+
}
|
|
433
|
+
undos.push(() => set.close());
|
|
434
|
+
cleanups.set(sessionId, undos);
|
|
435
|
+
writeStatus({ registeredFor: [...cleanups.keys()], toolCount: dshTools.length });
|
|
436
|
+
ctx.logger?.info?.(
|
|
437
|
+
`[verbatim] 已为会话 ${sessionId} 注册 ${dshTools.length} 个记忆工具`
|
|
438
|
+
+ (dshTools.length === 0 ? '(配置里两个开关都关着,不注册是对的)' : ''),
|
|
439
|
+
);
|
|
440
|
+
} catch (e) {
|
|
441
|
+
for (const undo of undos) {
|
|
442
|
+
try { undo?.(); } catch { /* ignore */ }
|
|
443
|
+
}
|
|
444
|
+
try { set.close(); } catch { /* ignore */ }
|
|
445
|
+
ctx.logger?.warn?.(`[verbatim] 注册工具失败:${e.message}`);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function unregisterFor(sessionId) {
|
|
450
|
+
const undos = cleanups.get(sessionId);
|
|
451
|
+
if (!undos) return;
|
|
452
|
+
for (const undo of undos) {
|
|
453
|
+
try { undo?.(); } catch { /* ignore */ }
|
|
454
|
+
}
|
|
455
|
+
cleanups.delete(sessionId);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function refreshToolsFor(sessionId) {
|
|
459
|
+
if (typeof sessionId !== 'string' || !sessionId) return false;
|
|
460
|
+
unregisterFor(sessionId);
|
|
461
|
+
let agent = liveAgents.get(sessionId);
|
|
462
|
+
if (!agent) {
|
|
463
|
+
try {
|
|
464
|
+
const agents = ctx.get('agents');
|
|
465
|
+
if (typeof agents?.get === 'function') agent = agents.get(sessionId);
|
|
466
|
+
} catch { /* ignore */ }
|
|
467
|
+
}
|
|
468
|
+
if (agent) {
|
|
469
|
+
registerFor(agent);
|
|
470
|
+
return true;
|
|
471
|
+
}
|
|
472
|
+
return false;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
try {
|
|
476
|
+
const agents = ctx.get('agents');
|
|
477
|
+
const proto = agents ? Object.getPrototypeOf(agents) : null;
|
|
478
|
+
const keys = !agents ? '(服务不存在)' : proto ? Object.getOwnPropertyNames(proto).join(',') : '(无原型)';
|
|
479
|
+
ctx.logger?.info?.(`[verbatim] agents 服务原型方法: ${keys}`);
|
|
480
|
+
const list = typeof agents?.list === 'function' ? agents.list()
|
|
481
|
+
: typeof agents?.all === 'function' ? agents.all()
|
|
482
|
+
: typeof agents?.values === 'function' ? [...agents.values()]
|
|
483
|
+
: [];
|
|
484
|
+
ctx.logger?.info?.(`[verbatim] 现有 Agent 数量: ${Array.isArray(list) ? list.length : '(不是数组)'}`);
|
|
485
|
+
for (const agent of list) registerFor(agent);
|
|
486
|
+
|
|
487
|
+
try {
|
|
488
|
+
const listIds = (Array.isArray(list) ? list : []).map((a) => a?.session?.id).filter(Boolean);
|
|
489
|
+
const dirRoot = path.join(dshHome, 'sessions');
|
|
490
|
+
const diskIds = [];
|
|
491
|
+
if (fs.existsSync(dirRoot)) {
|
|
492
|
+
for (const ws of fs.readdirSync(dirRoot, { withFileTypes: true })) {
|
|
493
|
+
if (!ws.isDirectory()) continue;
|
|
494
|
+
const wsd = path.join(dirRoot, ws.name);
|
|
495
|
+
let subs = [];
|
|
496
|
+
try { subs = fs.readdirSync(wsd, { withFileTypes: true }); } catch { continue; }
|
|
497
|
+
for (const s of subs) {
|
|
498
|
+
if (s.isDirectory() && fs.existsSync(path.join(wsd, s.name, 'session.v4.jsonl.zstd'))) {
|
|
499
|
+
diskIds.push(s.name);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
const gettable = diskIds.filter((id) => {
|
|
505
|
+
if (listIds.includes(id)) return true;
|
|
506
|
+
try { return agents?.get?.(id) !== undefined; } catch { return false; }
|
|
507
|
+
});
|
|
508
|
+
writeStatus({
|
|
509
|
+
diag: {
|
|
510
|
+
agentsListCount: listIds.length,
|
|
511
|
+
agentsListIds: listIds.slice(0, 8),
|
|
512
|
+
diskSessionCount: diskIds.length,
|
|
513
|
+
gettableCount: gettable.length,
|
|
514
|
+
gettableSample: gettable.slice(0, 8),
|
|
515
|
+
hasGet: typeof agents?.get === 'function',
|
|
516
|
+
},
|
|
517
|
+
});
|
|
518
|
+
ctx.logger?.info?.(
|
|
519
|
+
`[verbatim] agents.list=${listIds.length} / 磁盘会话=${diskIds.length} / 能拿到 Agent 的=${gettable.length}`,
|
|
520
|
+
);
|
|
521
|
+
} catch (e) { ctx.logger?.warn?.(`[verbatim] 诊断失败:${e.message}`); }
|
|
522
|
+
|
|
523
|
+
const latestLog = config.sessionFile ?? findLatestSession(dshHome);
|
|
524
|
+
if (latestLog) {
|
|
525
|
+
const sid = path.basename(path.dirname(latestLog));
|
|
526
|
+
if (!cleanups.has(sid)) {
|
|
527
|
+
const agent = typeof agents?.get === 'function' ? agents.get(sid) : undefined;
|
|
528
|
+
if (agent) {
|
|
529
|
+
registerFor(agent);
|
|
530
|
+
ctx.logger?.info?.(`[verbatim] 已补注册当前会话 ${sid}`);
|
|
531
|
+
} else {
|
|
532
|
+
writeStatus({ missedSession: sid, note: 'agents.get 拿不到这个会话的 Agent,等 agent/created' });
|
|
533
|
+
ctx.logger?.warn?.(`[verbatim] agents.get(${sid}) 拿不到 Agent —— 当前会话暂时没有工具,等下一次 agent/created`);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
} catch (e) { ctx.logger?.warn?.(`[verbatim] 遍历 Agent 失败:${e.message}`); }
|
|
538
|
+
|
|
539
|
+
const unsubCreated = ctx.on('agent/created', ({ agent }) => registerFor(agent));
|
|
540
|
+
const unsubDisposed = ctx.on('agent/disposed', ({ agent }) => {
|
|
541
|
+
const sessionId = agent?.session?.id;
|
|
542
|
+
if (typeof sessionId === 'string') {
|
|
543
|
+
unregisterFor(sessionId);
|
|
544
|
+
liveAgents.delete(sessionId);
|
|
545
|
+
}
|
|
546
|
+
});
|
|
547
|
+
|
|
548
|
+
const panelApi = createPanelApi({
|
|
549
|
+
handle,
|
|
550
|
+
repo,
|
|
551
|
+
extras,
|
|
552
|
+
dbPath,
|
|
553
|
+
dshHome,
|
|
554
|
+
config,
|
|
555
|
+
sessionLock: hostSessionLock,
|
|
556
|
+
recallLog: recallLogEntries,
|
|
557
|
+
logger: ctx.logger,
|
|
558
|
+
getHostLlm: () => {
|
|
559
|
+
try {
|
|
560
|
+
return (typeof ctx.get === 'function' ? ctx.get('llm') : ctx.llm) ?? null;
|
|
561
|
+
} catch {
|
|
562
|
+
return null;
|
|
563
|
+
}
|
|
564
|
+
},
|
|
565
|
+
syncSession: async (sid) => {
|
|
566
|
+
invalidateFresh(sid);
|
|
567
|
+
return await ensureFresh(sid, { skipAutoIndex: true });
|
|
568
|
+
},
|
|
569
|
+
});
|
|
570
|
+
|
|
571
|
+
ctx.effect(
|
|
572
|
+
() => ctx.webServer.register({
|
|
573
|
+
kind: 'prefix',
|
|
574
|
+
path: API_PREFIX,
|
|
575
|
+
handler: createPanelHandler(panelApi, {
|
|
576
|
+
beforeRequest: ensureFresh,
|
|
577
|
+
afterCall: ({ method, params }) => {
|
|
578
|
+
if (method === 'dbMaintain' && params?.action === 'clearSession') {
|
|
579
|
+
dbMutationEpoch += 1;
|
|
580
|
+
invalidateFresh(params.sessionId);
|
|
581
|
+
}
|
|
582
|
+
if (method === 'rebuild') {
|
|
583
|
+
dbMutationEpoch += 1;
|
|
584
|
+
}
|
|
585
|
+
if (method === 'set' && params?.key === 'record' && params?.value === true) {
|
|
586
|
+
invalidateFresh(params.sessionId);
|
|
587
|
+
}
|
|
588
|
+
if (method === 'set' && (params?.key === 'tools' || params?.key === 'record') && typeof params?.sessionId === 'string') {
|
|
589
|
+
refreshToolsFor(params.sessionId);
|
|
590
|
+
}
|
|
591
|
+
if (method === 'batchSetSessionFlags' && (params?.key === 'tools' || params?.key === 'record' || params?.tools !== undefined || params?.record !== undefined)) {
|
|
592
|
+
for (const sid of [...liveAgents.keys()]) refreshToolsFor(sid);
|
|
593
|
+
}
|
|
594
|
+
},
|
|
595
|
+
}),
|
|
596
|
+
}),
|
|
597
|
+
'dsh-verbatim: panel api',
|
|
598
|
+
);
|
|
599
|
+
|
|
600
|
+
ctx.logger?.info?.(
|
|
601
|
+
`[verbatim] 面板 RPC 已挂载:${API_PREFIX}/panel.{${PANEL_METHODS.join(',')}}`,
|
|
602
|
+
);
|
|
603
|
+
|
|
604
|
+
return () => {
|
|
605
|
+
disposed = true;
|
|
606
|
+
try { if (typeof unsubCreated === 'function') unsubCreated(); } catch { /* ignore */ }
|
|
607
|
+
try { if (typeof unsubDisposed === 'function') unsubDisposed(); } catch { /* ignore */ }
|
|
608
|
+
for (const sessionId of [...cleanups.keys()]) unregisterFor(sessionId);
|
|
609
|
+
try { handle.close(); } catch { /* ignore */ }
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
export default { inject, apply };
|