@restregular/dsh-memory 0.28.0 → 0.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +13 -3
- package/lib/client.js +130 -26
- package/lib/inject/policy.js +2 -0
- package/lib/panel.js +1345 -1284
- package/lib/provider/apply.js +81 -1
- package/lib/provider/authorize.js +13 -0
- package/lib/provider/index.js +170 -26
- package/lib/provider/store.js +12 -3
- package/lib/tools/index.js +114 -7
- package/lib/tools/render.js +20 -2
- package/package.json +1 -6
package/lib/panel.js
CHANGED
|
@@ -1,1287 +1,1348 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* dsh-memory-panel — 服务端(entry)。
|
|
3
|
-
*
|
|
4
|
-
* 架构照抄 dsh-meme 的铁律(2026-10-10 crash 的教训):
|
|
5
|
-
* - 不导出 inject:一切服务 ctx.get() 被动获取,缺谁就降级跳过,
|
|
6
|
-
* 绝不让 fiber 进入 FAILED(desktop fail-loud,一个 entry 失败=整个应用起不来);
|
|
7
|
-
* - 路由注册 try/catch:冲突则复用/记日志,不抛;
|
|
8
|
-
* - apply 整体兜底 catch:任何意外都不允许向外抛。
|
|
9
|
-
*
|
|
10
|
-
* 提供管理员 API(前缀路由 /memory/api):
|
|
11
|
-
* GET /status 各 scope 记录数 + 待嵌入数 + 展示标签 + 用途描述(0.28.0)
|
|
12
|
-
*
|
|
13
|
-
* GET /
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
//
|
|
29
|
-
//
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
res.
|
|
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
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
if (
|
|
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
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
const
|
|
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
|
-
|
|
279
|
-
|
|
280
|
-
...(text('
|
|
281
|
-
...(
|
|
282
|
-
...(text('
|
|
283
|
-
...(
|
|
284
|
-
...(
|
|
285
|
-
...(
|
|
286
|
-
...(
|
|
287
|
-
...(
|
|
288
|
-
...(
|
|
289
|
-
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
...(query.
|
|
298
|
-
...(query.
|
|
299
|
-
...(query.
|
|
300
|
-
...(query.
|
|
301
|
-
...(query.
|
|
302
|
-
...(query.
|
|
303
|
-
...(query.
|
|
304
|
-
|
|
305
|
-
...(query.
|
|
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
|
-
const
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
if (
|
|
337
|
-
if (query.
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
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
|
-
if (
|
|
383
|
-
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
const
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
if (
|
|
395
|
-
const
|
|
396
|
-
if (
|
|
397
|
-
if (
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
if (
|
|
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
|
-
if (
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
*
|
|
483
|
-
*
|
|
484
|
-
*
|
|
485
|
-
*
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
let
|
|
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
|
-
defaultScopes =
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
const
|
|
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
|
-
*
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
if (
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
if (normalized.
|
|
619
|
-
throw new ApiError(400, 'SCOPE_INVALID',
|
|
620
|
-
}
|
|
621
|
-
if (
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
*
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
}
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
const
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
const
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
//
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
const
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
if (normalized.
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
const
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
const
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
const
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
const
|
|
844
|
-
if (
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
const
|
|
875
|
-
if (
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
}
|
|
911
|
-
}
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
if (typeof memory.
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
const
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
writeJson(res, { ok: true, value:
|
|
1033
|
-
return
|
|
1034
|
-
}
|
|
1035
|
-
if (method === 'POST' && path === '/
|
|
1036
|
-
if (typeof memory.
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
if (typeof memory.
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
//
|
|
1075
|
-
const
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
if (
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
}
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
const
|
|
1175
|
-
|
|
1176
|
-
if (
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
const
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
s
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
if (
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
}
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1
|
+
/**
|
|
2
|
+
* dsh-memory-panel — 服务端(entry)。
|
|
3
|
+
*
|
|
4
|
+
* 架构照抄 dsh-meme 的铁律(2026-10-10 crash 的教训):
|
|
5
|
+
* - 不导出 inject:一切服务 ctx.get() 被动获取,缺谁就降级跳过,
|
|
6
|
+
* 绝不让 fiber 进入 FAILED(desktop fail-loud,一个 entry 失败=整个应用起不来);
|
|
7
|
+
* - 路由注册 try/catch:冲突则复用/记日志,不抛;
|
|
8
|
+
* - apply 整体兜底 catch:任何意外都不允许向外抛。
|
|
9
|
+
*
|
|
10
|
+
* 提供管理员 API(前缀路由 /memory/api):
|
|
11
|
+
* GET /status 各 scope 记录数 + 待嵌入数 + 展示标签 + 用途描述(0.28.0)
|
|
12
|
+
* POST /scope-meta {scope, description?, name?} 编辑作用域用途 / 别名(0.29.0)
|
|
13
|
+
* GET /records ?scope=&q= 枚举/过滤记录
|
|
14
|
+
* GET /search ?scope=&q=&topK= 语义检索(向量 + 词法,provider 排序)
|
|
15
|
+
* POST /update {id, content?, kind?, importance?, tags?, triggers?, expiresAt?/ttlMs?}
|
|
16
|
+
* → 新建一条修正版(supersedes=id),旧记录保留(0.23.0)
|
|
17
|
+
* POST /delete {id}
|
|
18
|
+
* scope 惰性加载是同步的(store.peek(),**读路径不创建**),无需 ready 门。内容编辑会作废旧
|
|
19
|
+
* 向量并加入 embedPending,由 provider 的回填队列重新嵌入。
|
|
20
|
+
*
|
|
21
|
+
* 安全(每个路由都过 refuseRequest,见下):
|
|
22
|
+
* 注册在裸 webServer 上的路由**既不在宿主的 /api 围栏之后,也不在浏览器登录
|
|
23
|
+
* 之后** —— 宿主的围栏是一个给别的路由主动调用的服务方法(connection.requestRejection),
|
|
24
|
+
* 不是自动套上的中间件(dsh-market #603 的结论:裸 webServer 路由在登录开启时
|
|
25
|
+
* 可被无 session 调用 = 任意代码执行)。这里的读接口能读出全部记忆,写接口能改写、
|
|
26
|
+
* 删除、清空,还能拉起/卸载向量服务,所以必须自己问一次。
|
|
27
|
+
*/
|
|
28
|
+
// scope 规范化与 provider 共用同一份实现。路径按**源码树位置**写:构建脚本的改写表
|
|
29
|
+
// 会把它落成产物里的 `../provider/scope.js`(`lib/panel.js` → `lib/provider/scope.js`),
|
|
30
|
+
// 在源码树里同一路径直接命中 source/memory-local/src —— 测试与真实加载都能解析。
|
|
31
|
+
import { normalizeScopeInput, resolveCurrentScopes, scopeDisplayName, sessionShortId } from './provider/scope.js'
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
function writeJson(res, body, status = 200) {
|
|
35
|
+
try {
|
|
36
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
|
|
37
|
+
res.end(JSON.stringify(body))
|
|
38
|
+
} catch { /* 客户端已断开 */ }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** provider 侧的"调用方输入有问题"错误码 → 400;其余未标注的仍算 500。 */
|
|
42
|
+
const CLIENT_ERROR_CODES = new Set([
|
|
43
|
+
'SCOPE_INVALID', 'SCOPE_DISABLED', 'CONTENT_EMPTY', 'CONTENT_TOO_LONG',
|
|
44
|
+
'SECRET_DETECTED', 'IMPORT_INVALID', 'IMPORT_TOO_LARGE', 'KIND_INVALID',
|
|
45
|
+
'QUERY_EMPTY', 'QUERY_INVALID', 'SESSION_REQUIRED', 'SCOPE_EMPTY', 'SCOPE_NOT_VISIBLE',
|
|
46
|
+
// 0.29.0:作用域用途 / 别名的编辑错误(名字非法 / 重名 / 不支持 / 用途过长)
|
|
47
|
+
'SCOPE_NAME_INVALID', 'SCOPE_NAME_TAKEN', 'SCOPE_NAME_UNSUPPORTED', 'SCOPE_DESCRIPTION_TOO_LONG',
|
|
48
|
+
])
|
|
49
|
+
|
|
50
|
+
function writeError(res, error) {
|
|
51
|
+
const code = typeof error?.code === 'string' ? error.code : 'internal'
|
|
52
|
+
const status = Number(error?.status) || (CLIENT_ERROR_CODES.has(code) ? 400 : code === 'SCOPE_LIMIT' ? 409 : 500)
|
|
53
|
+
writeJson(res, { ok: false, error: { code, message: error?.message || String(error) } }, status)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
class ApiError extends Error {
|
|
57
|
+
constructor(status, code, message) {
|
|
58
|
+
super(message)
|
|
59
|
+
this.status = status
|
|
60
|
+
this.code = code
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 只认本机权威(loopback),没有宿主围栏时的兜底。 */
|
|
65
|
+
const LOOPBACK_AUTHORITY = /^(?:127(?:\.\d{1,3}){3}|\[::1\]|::1|localhost)(?::\d+)?$/i
|
|
66
|
+
|
|
67
|
+
/** 请求头里的 Host,小写归一;缺失返回空串。 */
|
|
68
|
+
function hostHeader(req) {
|
|
69
|
+
const value = req?.headers?.host
|
|
70
|
+
return typeof value === 'string' ? value.trim().toLowerCase() : ''
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 部署自己声明的权威(宿主 connection 的 trustedHosts);拿不到就空数组。 */
|
|
74
|
+
function trustedAuthorities(ctx) {
|
|
75
|
+
try {
|
|
76
|
+
const connection = ctx?.get?.('connection')
|
|
77
|
+
return Array.isArray(connection?.trustedHosts)
|
|
78
|
+
? connection.trustedHosts.filter((entry) => typeof entry === 'string').map((entry) => entry.toLowerCase())
|
|
79
|
+
: []
|
|
80
|
+
} catch {
|
|
81
|
+
return []
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 该不该拒绝这个请求。
|
|
87
|
+
*
|
|
88
|
+
* 两层,顺序有讲究:
|
|
89
|
+
* 1. 宿主发布了 connection.requestRejection 时**以它为准** —— 它同时含 Host/Origin
|
|
90
|
+
* 围栏(防 DNS rebinding 与跨站调用)与浏览器登录(login-token cookie)。
|
|
91
|
+
* 围栏自己抛错时返回 403:抛错意味着"什么都没放行",此处失败关闭,不能放行。
|
|
92
|
+
* 2. 旧宿主没有这个服务时自己来:Host 必须是 loopback 或宿主声明的权威,
|
|
93
|
+
* sec-fetch-site 不得是 cross-site,带 Origin 就必须与 Host 相等。
|
|
94
|
+
* (注意 content-type: text/plain 也能携带合法 JSON 体且不触发预检,
|
|
95
|
+
* 所以"要求 JSON 体"挡不住跨站 —— 承重的是 Host/Origin 这一层。)
|
|
96
|
+
*
|
|
97
|
+
* @returns 需要拒绝时返回状态码(401 未登录 / 403 不受信任),否则 undefined。
|
|
98
|
+
*/
|
|
99
|
+
export function refuseRequest(ctx, req) {
|
|
100
|
+
let connection
|
|
101
|
+
try { connection = ctx?.get?.('connection') } catch { connection = undefined }
|
|
102
|
+
const gate = connection?.requestRejection
|
|
103
|
+
if (typeof gate === 'function') {
|
|
104
|
+
try {
|
|
105
|
+
const status = gate.call(connection, req)
|
|
106
|
+
return typeof status === 'number' ? status : undefined
|
|
107
|
+
} catch {
|
|
108
|
+
return 403
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const host = hostHeader(req)
|
|
112
|
+
if (host === '') return 403
|
|
113
|
+
if (!LOOPBACK_AUTHORITY.test(host) && !trustedAuthorities(ctx).includes(host)) return 403
|
|
114
|
+
if (String(req?.headers?.['sec-fetch-site'] ?? '').toLowerCase() === 'cross-site') return 403
|
|
115
|
+
const origin = req?.headers?.origin
|
|
116
|
+
if (origin !== undefined) {
|
|
117
|
+
try {
|
|
118
|
+
if (new URL(String(origin)).host.toLowerCase() !== host) return 403
|
|
119
|
+
} catch {
|
|
120
|
+
return 403
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return undefined
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** 拒绝时的响应体:给人话,不说内部概念。 */
|
|
127
|
+
function writeRefusal(res, status) {
|
|
128
|
+
writeJson(res, {
|
|
129
|
+
ok: false,
|
|
130
|
+
error: {
|
|
131
|
+
code: status === 401 ? 'LOGIN_REQUIRED' : 'UNTRUSTED_REQUEST',
|
|
132
|
+
message: status === 401
|
|
133
|
+
? '需要先登录 DSH:请重新打开启动时打印的那个网址。'
|
|
134
|
+
: '这个请求来自不受信任的来源,已拒绝。',
|
|
135
|
+
},
|
|
136
|
+
}, status)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function readJsonBody(req) {
|
|
140
|
+
const chunks = []
|
|
141
|
+
for await (const chunk of req) chunks.push(chunk)
|
|
142
|
+
const raw = Buffer.concat(chunks).toString('utf8')
|
|
143
|
+
return raw.length > 0 ? JSON.parse(raw) : {}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* scope 键 → **不需要查宿主服务**的展示名(带类型前缀)。
|
|
148
|
+
* global → `global:全局`
|
|
149
|
+
* project:<cwd> → `project:<cwd>`
|
|
150
|
+
* session:<id> → `session:session-1a2b3c4d`(会话 id 前 16 位)
|
|
151
|
+
* 自定义 → `custom:<名字>`(自定义 scope 的键本身没有前缀,靠类型补)
|
|
152
|
+
*
|
|
153
|
+
* 细节都有两处坑:①会话 id 以 `session-` 开头(正好 8 个字符),取 8 位会让所有会话
|
|
154
|
+
* 作用域都显示成同一个名字,所以取 16 位;②自定义作用域与 global 的键天然不带前缀,
|
|
155
|
+
* 必须按类型补 —— 规则集中在 provider 的 scopeDisplayName。
|
|
156
|
+
*/
|
|
157
|
+
function fallbackScopeLabel(scope) {
|
|
158
|
+
return scopeDisplayName(scope)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* scope 键 → 展示名。在 fallback 之上多一步:会话 scope 尽力取会话标题
|
|
163
|
+
* (宿主 `sessionTitle` 服务的 `get(session)` → `{ title }`,见 @deepseek-ai/dsh-session-title)。
|
|
164
|
+
* 所有宿主服务访问都在 try/catch 里:面板绝不能因为拿不到标题而失败。
|
|
165
|
+
*
|
|
166
|
+
* 带标题时形如 `session:修层级(1a2b3c4d)` —— 类型前缀仍在最前面,名字部分换成标题。
|
|
167
|
+
*/
|
|
168
|
+
function scopeLabel(ctx, scope) {
|
|
169
|
+
if (!scope.startsWith('session:')) return scopeDisplayName(scope)
|
|
170
|
+
const id = scope.slice('session:'.length)
|
|
171
|
+
const short = sessionShortId(id)
|
|
172
|
+
try {
|
|
173
|
+
const session = ctx?.get?.('sessions')?.get?.(id)
|
|
174
|
+
if (session !== undefined) {
|
|
175
|
+
const title = ctx.get('sessionTitle')?.get?.(session)?.title
|
|
176
|
+
if (typeof title === 'string' && title.length > 0) return scopeDisplayName(scope, `${title}(${short})`)
|
|
177
|
+
}
|
|
178
|
+
} catch { /* 标题是尽力而为 */ }
|
|
179
|
+
return scopeDisplayName(scope)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** 会话 scope 查标题的上限:标题要读会话事件日志,scope 多了它就成了 /status 的大头。 */
|
|
183
|
+
const TITLE_LOOKUP_LIMIT = 50
|
|
184
|
+
/** discovery(读每个 scope 文件的第一条记录)结果的缓存时长。 */
|
|
185
|
+
const DISCOVER_CACHE_MS = 3000
|
|
186
|
+
/** 每个 memory 服务的发现缓存。面板看不到进程数,所以按服务实例各存一份。 */
|
|
187
|
+
const discoveryCache = new WeakMap()
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* 发现磁盘上的 scope,3 秒内只做一次。
|
|
191
|
+
* 面板每个请求都想要一份完整清单(别的进程写下的 scope 也要看得见),而 discovery 要
|
|
192
|
+
* 读每个文件的第一条记录 —— 没有缓存的话刷新一下就是一次全目录扫描。
|
|
193
|
+
*/
|
|
194
|
+
function discoverScopes(memory, store) {
|
|
195
|
+
const now = Date.now()
|
|
196
|
+
const cached = discoveryCache.get(memory)
|
|
197
|
+
if (cached !== undefined && now - cached.at < DISCOVER_CACHE_MS) return
|
|
198
|
+
discoveryCache.set(memory, { at: now })
|
|
199
|
+
try {
|
|
200
|
+
if (typeof memory.discoverScopes === 'function') memory.discoverScopes()
|
|
201
|
+
else store.loadDiscovered?.()
|
|
202
|
+
} catch { /* discovery is best-effort */ }
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function wireRecord(rec, scopeStore, supersededBy = null) {
|
|
206
|
+
return {
|
|
207
|
+
id: rec.id,
|
|
208
|
+
scope: rec.scope,
|
|
209
|
+
kind: rec.kind,
|
|
210
|
+
content: rec.content,
|
|
211
|
+
tags: rec.tags ?? [],
|
|
212
|
+
importance: rec.importance,
|
|
213
|
+
createdAt: rec.createdAt,
|
|
214
|
+
updatedAt: rec.updatedAt,
|
|
215
|
+
accessCount: rec.accessCount ?? 0,
|
|
216
|
+
supersededBy,
|
|
217
|
+
supersedes: rec.supersedes ?? null,
|
|
218
|
+
triggers: rec.triggers ?? [],
|
|
219
|
+
expiredAt: rec.expiredAt ?? null,
|
|
220
|
+
expired: rec.expiredAt !== undefined && rec.expiredAt < Date.now(),
|
|
221
|
+
embedded: !scopeStore.embedPending.has(rec.id) && scopeStore.vectors.has(rec.id),
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function collectScope(scopeStore) {
|
|
226
|
+
// supersedes 是"新记录 → 旧记录"的指向;反查一次,给旧记录标上"已被修正"。
|
|
227
|
+
const correctedBy = new Map()
|
|
228
|
+
for (const rec of scopeStore.records.values()) {
|
|
229
|
+
if (rec.supersedes) correctedBy.set(rec.supersedes, rec.id)
|
|
230
|
+
}
|
|
231
|
+
const out = []
|
|
232
|
+
for (const rec of scopeStore.records.values()) out.push(wireRecord(rec, scopeStore, correctedBy.get(rec.id) ?? null))
|
|
233
|
+
return out.sort((a, b) => b.updatedAt - a.updatedAt)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** 审计时间参数:Unix ms 或可解析的 ISO 字符串。 */
|
|
237
|
+
function parseAuditTime(value, name) {
|
|
238
|
+
if (value === null || value === undefined || value === '') return undefined
|
|
239
|
+
const numeric = Number(value)
|
|
240
|
+
if (Number.isFinite(numeric)) return numeric
|
|
241
|
+
const parsed = Date.parse(value)
|
|
242
|
+
if (Number.isFinite(parsed)) return parsed
|
|
243
|
+
throw new ApiError(400, 'AUDIT_QUERY_INVALID', `${name} 必须是毫秒时间戳或 ISO 时间`)
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** 面板查询参数 → audit sink 的 AuditListQuery。 */
|
|
247
|
+
const AUDIT_CHANNELS = new Set(['digest', 'recall', 'rules', 'rules_delta', 'policy', 'nudge', 'signal', 'lifecycle'])
|
|
248
|
+
const AUDIT_OUTCOMES = new Set(['success', 'failed', 'skipped', 'partial', 'unknown'])
|
|
249
|
+
function parseAuditQuery(url) {
|
|
250
|
+
const text = (name) => {
|
|
251
|
+
const value = url.searchParams.get(name)
|
|
252
|
+
const trimmed = value === null ? '' : value.trim()
|
|
253
|
+
return trimmed === '' ? undefined : trimmed
|
|
254
|
+
}
|
|
255
|
+
const limitRaw = text('limit')
|
|
256
|
+
let limit
|
|
257
|
+
if (limitRaw !== undefined) {
|
|
258
|
+
if (!/^\d+$/.test(limitRaw)) throw new ApiError(400, 'AUDIT_QUERY_INVALID', 'limit 必须是 1..200 的整数')
|
|
259
|
+
limit = Number(limitRaw)
|
|
260
|
+
if (limit < 1 || limit > 200) throw new ApiError(400, 'AUDIT_QUERY_INVALID', 'limit 必须在 1..200 之间')
|
|
261
|
+
}
|
|
262
|
+
const cursor = text('cursor')
|
|
263
|
+
if (cursor !== undefined && !/^\d+$/.test(cursor)) {
|
|
264
|
+
throw new ApiError(400, 'AUDIT_CURSOR_INVALID', 'cursor 必须是 seq 数字')
|
|
265
|
+
}
|
|
266
|
+
const channel = text('channel')
|
|
267
|
+
if (channel !== undefined && !AUDIT_CHANNELS.has(channel)) {
|
|
268
|
+
throw new ApiError(400, 'AUDIT_QUERY_INVALID', `未知 channel: ${channel}`)
|
|
269
|
+
}
|
|
270
|
+
const outcome = text('outcome')
|
|
271
|
+
if (outcome !== undefined && !AUDIT_OUTCOMES.has(outcome)) {
|
|
272
|
+
throw new ApiError(400, 'AUDIT_QUERY_INVALID', `未知 outcome: ${outcome}`)
|
|
273
|
+
}
|
|
274
|
+
const since = parseAuditTime(text('since'), 'since')
|
|
275
|
+
const until = parseAuditTime(text('until'), 'until')
|
|
276
|
+
if (since !== undefined && until !== undefined && since > until) {
|
|
277
|
+
throw new ApiError(400, 'AUDIT_QUERY_INVALID', 'since 不能晚于 until')
|
|
278
|
+
}
|
|
279
|
+
return {
|
|
280
|
+
...(text('session') !== undefined ? { sessionId: text('session') } : {}),
|
|
281
|
+
...(text('trace') !== undefined ? { traceId: text('trace') } : {}),
|
|
282
|
+
...(text('operation') !== undefined ? { operationId: text('operation') } : {}),
|
|
283
|
+
...(text('memory') !== undefined ? { memoryId: text('memory') } : {}),
|
|
284
|
+
...(channel !== undefined ? { channel } : {}),
|
|
285
|
+
...(text('trigger') !== undefined ? { trigger: text('trigger') } : {}),
|
|
286
|
+
...(outcome !== undefined ? { outcome } : {}),
|
|
287
|
+
...(url.searchParams.get('problem') === '1' ? { problem: true } : {}),
|
|
288
|
+
...(since !== undefined ? { since } : {}),
|
|
289
|
+
...(until !== undefined ? { until } : {}),
|
|
290
|
+
...(limit !== undefined ? { limit } : {}),
|
|
291
|
+
...(cursor !== undefined ? { cursor } : {}),
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function publicAuditQuery(query) {
|
|
296
|
+
return {
|
|
297
|
+
...(query.sessionId !== undefined ? { sessionId: query.sessionId } : {}),
|
|
298
|
+
...(query.traceId !== undefined ? { traceId: query.traceId } : {}),
|
|
299
|
+
...(query.operationId !== undefined ? { operationId: query.operationId } : {}),
|
|
300
|
+
...(query.memoryId !== undefined ? { memoryId: query.memoryId } : {}),
|
|
301
|
+
...(query.channel !== undefined ? { channel: query.channel } : {}),
|
|
302
|
+
...(query.trigger !== undefined ? { trigger: query.trigger } : {}),
|
|
303
|
+
...(query.outcome !== undefined ? { outcome: query.outcome } : {}),
|
|
304
|
+
...(query.problem === true ? { problem: true } : {}),
|
|
305
|
+
...(query.since !== undefined ? { since: query.since } : {}),
|
|
306
|
+
...(query.until !== undefined ? { until: query.until } : {}),
|
|
307
|
+
limit: query.limit ?? 50,
|
|
308
|
+
...(query.cursor !== undefined ? { cursor: query.cursor } : {}),
|
|
309
|
+
scope: query.sessionId !== undefined ? 'session' : 'all',
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function emptyAuditStats() {
|
|
314
|
+
return {
|
|
315
|
+
entries: 0, capacity: 0, perSessionCapacity: 0, dropped: 0,
|
|
316
|
+
writeErrors: 0, persistence: 'memory',
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function auditStats(memory) {
|
|
321
|
+
try {
|
|
322
|
+
const stats = typeof memory?.injectAuditStats === 'function' ? memory.injectAuditStats() : undefined
|
|
323
|
+
return stats && typeof stats === 'object' ? stats : emptyAuditStats()
|
|
324
|
+
} catch {
|
|
325
|
+
return { ...emptyAuditStats(), persistence: 'degraded' }
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** 旧 provider 只有 injectAudit(list) 时,在面板侧补最小过滤/分页。 */
|
|
330
|
+
function legacyAuditPage(memory, query) {
|
|
331
|
+
const all = (() => {
|
|
332
|
+
try { return typeof memory?.injectAudit === 'function' ? memory.injectAudit(query.sessionId) : [] } catch { return [] }
|
|
333
|
+
})()
|
|
334
|
+
const entries = Array.isArray(all) ? all : []
|
|
335
|
+
const filtered = entries.filter((entry) => {
|
|
336
|
+
if (!entry || typeof entry !== 'object') return false
|
|
337
|
+
if (query.channel !== undefined && entry.channel !== query.channel) return false
|
|
338
|
+
if (query.trigger !== undefined && entry.trigger !== query.trigger) return false
|
|
339
|
+
if (query.outcome !== undefined && entry.outcome !== query.outcome) return false
|
|
340
|
+
if (query.problem === true) {
|
|
341
|
+
const delivery = entry.delivery
|
|
342
|
+
const omitted = Array.isArray(entry.omitted) ? entry.omitted.length : 0
|
|
343
|
+
if (!(entry.outcome === 'failed' || entry.outcome === 'partial' || omitted > 0 || (delivery && delivery.status !== 'appended' && delivery.status !== 'unknown'))) return false
|
|
344
|
+
}
|
|
345
|
+
if (query.memoryId !== undefined) {
|
|
346
|
+
const ids = [
|
|
347
|
+
...(entry.contentIds ?? []), ...(entry.hintIds ?? []),
|
|
348
|
+
...((entry.selected && entry.selected.contentIds) ?? []),
|
|
349
|
+
...((entry.omitted ?? []).map((item) => item.id)),
|
|
350
|
+
]
|
|
351
|
+
if (!ids.includes(query.memoryId)) return false
|
|
352
|
+
}
|
|
353
|
+
if (query.since !== undefined && !(entry.at >= query.since)) return false
|
|
354
|
+
if (query.until !== undefined && !(entry.at <= query.until)) return false
|
|
355
|
+
return true
|
|
356
|
+
})
|
|
357
|
+
const limit = query.limit ?? 50
|
|
358
|
+
const start = query.cursor === undefined ? 0 : Number(query.cursor)
|
|
359
|
+
const page = filtered.slice(start, start + limit)
|
|
360
|
+
return {
|
|
361
|
+
entries: page,
|
|
362
|
+
total: filtered.length,
|
|
363
|
+
...(start + limit < filtered.length ? { nextCursor: String(start + limit) } : {}),
|
|
364
|
+
stats: emptyAuditStats(),
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* 把一个审计条目的 turn/step 锚点解析成轨迹可直接聚焦的 tool call id。
|
|
370
|
+
*
|
|
371
|
+
* Trajectory 的深链只接受 callId(它的 `toolCallFocus` 就是同一性映射),所以
|
|
372
|
+
* 没有 operationId 的审计事件(摘要/规则等按步注入)需要回到会话事件里找该步
|
|
373
|
+
* 的第一个 `tool/call`。找不到工具调用时不伪造:返回 null,由客户端退化成
|
|
374
|
+
* “只切到轨迹页”。
|
|
375
|
+
*
|
|
376
|
+
* @param ctx - Host 插件上下文。
|
|
377
|
+
* @param query - `{ sessionId, turn?, step?, callId? }`。
|
|
378
|
+
* @returns 锚点结果(永不抛错)。
|
|
379
|
+
*/
|
|
380
|
+
export function findTrajectoryAnchor(ctx, query) {
|
|
381
|
+
const sessionId = typeof query?.sessionId === 'string' ? query.sessionId.trim() : ''
|
|
382
|
+
if (sessionId === '') return { callId: null, reason: 'session_required' }
|
|
383
|
+
let session
|
|
384
|
+
try { session = ctx?.get?.('sessions')?.get?.(sessionId) } catch { session = undefined }
|
|
385
|
+
if (session === undefined || typeof session?.ownEvents !== 'function') {
|
|
386
|
+
return { callId: null, reason: 'session_unavailable' }
|
|
387
|
+
}
|
|
388
|
+
const turn = typeof query.turn === 'number' ? query.turn : undefined
|
|
389
|
+
const step = typeof query.step === 'number' ? query.step : undefined
|
|
390
|
+
// 已有 callId 时校验它确实属于这个会话,避免把跨会话/伪造 id 送进轨迹。
|
|
391
|
+
const wanted = typeof query.callId === 'string' && query.callId !== '' ? query.callId : undefined
|
|
392
|
+
try {
|
|
393
|
+
for (const event of session.ownEvents()) {
|
|
394
|
+
if (event?.type !== 'tool/call') continue
|
|
395
|
+
const data = event.data ?? {}
|
|
396
|
+
if (turn !== undefined && data.turn !== turn) continue
|
|
397
|
+
if (step !== undefined && data.step !== step) continue
|
|
398
|
+
const callId = typeof data.callId === 'string' ? data.callId : undefined
|
|
399
|
+
if (callId === undefined) continue
|
|
400
|
+
if (wanted !== undefined && callId !== wanted) continue
|
|
401
|
+
return {
|
|
402
|
+
callId,
|
|
403
|
+
tool: typeof data.name === 'string' ? data.name : undefined,
|
|
404
|
+
turn: typeof data.turn === 'number' ? data.turn : undefined,
|
|
405
|
+
step: typeof data.step === 'number' ? data.step : undefined,
|
|
406
|
+
reason: wanted !== undefined ? 'operation' : 'step_tool',
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
} catch { /* 事件窗口读取失败:按找不到处理 */ }
|
|
410
|
+
return { callId: null, reason: wanted !== undefined ? 'operation_not_found' : 'no_tool_in_step' }
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
function auditPage(memory, query) { if (memory === undefined || memory === null) {
|
|
414
|
+
throw new ApiError(503, 'AUDIT_UNAVAILABLE', 'memory provider 未加载')
|
|
415
|
+
}
|
|
416
|
+
try {
|
|
417
|
+
if (typeof memory.injectAuditPage === 'function') {
|
|
418
|
+
const page = memory.injectAuditPage(query)
|
|
419
|
+
if (page && typeof page === 'object' && Array.isArray(page.entries)) {
|
|
420
|
+
return {
|
|
421
|
+
entries: page.entries,
|
|
422
|
+
total: typeof page.total === 'number' ? page.total : page.entries.length,
|
|
423
|
+
...(typeof page.nextCursor === 'string' ? { nextCursor: page.nextCursor } : {}),
|
|
424
|
+
stats: page.stats && typeof page.stats === 'object' ? page.stats : emptyAuditStats(),
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
if (typeof memory.injectAudit === 'function') return legacyAuditPage(memory, query)
|
|
429
|
+
throw new ApiError(503, 'AUDIT_UNAVAILABLE', 'provider 未提供注入审计接口(请升级 @restregular/dsh-memory)')
|
|
430
|
+
} catch (error) {
|
|
431
|
+
if (error instanceof ApiError) throw error
|
|
432
|
+
if (error && typeof error.code === 'string' && error.code.startsWith('AUDIT_')) {
|
|
433
|
+
throw new ApiError(400, error.code, error.message || '审计查询参数无效')
|
|
434
|
+
}
|
|
435
|
+
throw error
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/** 导出:按当前筛选循环取页(上限 200/页,最多 50 页 = 10000 条)。 */
|
|
440
|
+
function collectAuditEntries(memory, query) {
|
|
441
|
+
const out = []
|
|
442
|
+
let cursor
|
|
443
|
+
for (let i = 0; i < 50; i++) {
|
|
444
|
+
const page = auditPage(memory, { ...query, ...(cursor !== undefined ? { cursor } : {}), limit: 200 })
|
|
445
|
+
out.push(...page.entries)
|
|
446
|
+
if (page.nextCursor === undefined) break
|
|
447
|
+
cursor = page.nextCursor
|
|
448
|
+
}
|
|
449
|
+
return out
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** scope 选择 → 实际存在的 ScopeStore(读路径只用 peek,绝不通过 store.scope() 创建)。 */
|
|
453
|
+
function selectedStores(store, selection) {
|
|
454
|
+
if (selection === null) return store.allScopes()
|
|
455
|
+
return (Array.isArray(selection) ? selection : [selection])
|
|
456
|
+
.map((s) => store.peek(s))
|
|
457
|
+
.filter((s) => s !== undefined)
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* 面板的 scope 参数 → 要看的 scope 集合。
|
|
462
|
+
* null = 全部作用域
|
|
463
|
+
* string[] = 规范化后的 scope 键(current-session / current-project 由 provider 解析)
|
|
464
|
+
* 非法输入抛 400,合法但不存在的 scope 由 selectedStores 自然过滤成空集合。
|
|
465
|
+
*/
|
|
466
|
+
function resolveScopeSelection(memory, rawScope) {
|
|
467
|
+
if (rawScope === null || rawScope === undefined || rawScope.trim() === '') return null
|
|
468
|
+
const normalized = normalizeScopeInput(rawScope)
|
|
469
|
+
if (!normalized.ok) throw new ApiError(400, normalized.code, normalized.message)
|
|
470
|
+
if (normalized.kind === 'all') return null
|
|
471
|
+
if (normalized.kind === 'current-session' || normalized.kind === 'current-project') {
|
|
472
|
+
// 面板不在某个 agent 里:按 provider 的读取集合解析('project' → 当前项目键);
|
|
473
|
+
// 解析不出会话时就退化为全部,而不是报错。
|
|
474
|
+
const refs = typeof memory.resolveReadScopes === 'function' ? memory.resolveReadScopes(undefined) : []
|
|
475
|
+
return refs.length > 0 ? refs : null
|
|
476
|
+
}
|
|
477
|
+
return normalized.scope ?? null
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** 面板已知的记忆类型(与工具的 kind enum 一致)。 */
|
|
481
|
+
/**
|
|
482
|
+
* 会话「记忆可见域」的完整快照:自己的覆盖 + 生效策略 + 可选范围目录。
|
|
483
|
+
*
|
|
484
|
+
* 自己的覆盖(null = 没设置)用于面板上的"恢复默认";effective 用于预选(子 Agent
|
|
485
|
+
* 会话会继承父会话的覆盖);defaults 是"没有显式覆盖时 Agent 实际会读的集合",
|
|
486
|
+
* 首次打开面板时按它预选,而不是显示成什么都没选。
|
|
487
|
+
*
|
|
488
|
+
* 0.19.1 起不再支持按记忆类型收窄:目录只返回 scope,不再返回 kinds。
|
|
489
|
+
*/
|
|
490
|
+
function visibilityPayload(ctx, memory, sessionId) {
|
|
491
|
+
let session
|
|
492
|
+
try { session = ctx.get('sessions')?.get?.(sessionId) } catch { session = undefined }
|
|
493
|
+
const agentLike = { session: session !== undefined ? session : { id: sessionId } }
|
|
494
|
+
const own = typeof memory.sessionVisibility === 'function' ? memory.sessionVisibility(sessionId) : null
|
|
495
|
+
let effective = null
|
|
496
|
+
let inherited = false
|
|
497
|
+
// 0.20.0 起 provider 永远给一份生效策略(没有显式覆盖时是默认策略)。
|
|
498
|
+
// source 告诉面板这份策略是"自己的 / 继承的 / 默认的"。
|
|
499
|
+
let source = own === null ? 'default' : 'explicit'
|
|
500
|
+
try {
|
|
501
|
+
if (typeof memory.visibilityPolicy === 'function') {
|
|
502
|
+
const policy = memory.visibilityPolicy(agentLike)
|
|
503
|
+
if (policy !== undefined && policy !== null) {
|
|
504
|
+
effective = policy
|
|
505
|
+
source = policy.source === 'explicit' || policy.source === 'inherited' || policy.source === 'default'
|
|
506
|
+
? policy.source
|
|
507
|
+
: (own === null ? 'default' : 'explicit')
|
|
508
|
+
inherited = source === 'inherited'
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
} catch { /* 可见域是增强;拿不到就只返回自己的覆盖 */ }
|
|
512
|
+
|
|
513
|
+
let refs
|
|
514
|
+
try { if (session !== undefined) refs = resolveCurrentScopes({ session }) } catch { refs = undefined }
|
|
515
|
+
// 没有显式覆盖时,面板仍预选"当前默认读取集合"(会话 + 项目 + global + 工作区绑定),
|
|
516
|
+
// 让用户看到 Agent 现在实际能看到什么;保存后才变成显式覆盖。
|
|
517
|
+
let defaults = []
|
|
518
|
+
try {
|
|
519
|
+
const resolved = memory.resolveReadScopes?.(agentLike)
|
|
520
|
+
if (Array.isArray(resolved)) defaults = resolved
|
|
521
|
+
} catch { /* 降级为空 */ }
|
|
522
|
+
|
|
523
|
+
// 0.23.0:工作区级绑定 + 每个作用域的 read / write 状态。
|
|
524
|
+
let workspace = null
|
|
525
|
+
let bindings = []
|
|
526
|
+
try {
|
|
527
|
+
if (typeof memory.projectKeyFor === 'function') workspace = memory.projectKeyFor(agentLike)
|
|
528
|
+
if (typeof memory.workspaceBindings === 'function') {
|
|
529
|
+
const list = memory.workspaceBindings(agentLike)
|
|
530
|
+
if (Array.isArray(list)) bindings = list
|
|
531
|
+
}
|
|
532
|
+
} catch { /* 绑定是增强;拿不到就按"没有绑定"处理 */ }
|
|
533
|
+
const bound = new Set(bindings)
|
|
534
|
+
const rules = new Map()
|
|
535
|
+
for (const rule of (Array.isArray(effective?.scopes) ? effective.scopes : [])) {
|
|
536
|
+
if (rule && typeof rule.scope === 'string' && !rules.has(rule.scope)) rules.set(rule.scope, rule)
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const stats = typeof memory.scopeStats === 'function' ? memory.scopeStats() : []
|
|
540
|
+
const byScope = new Map()
|
|
541
|
+
for (const item of Array.isArray(stats) ? stats : []) {
|
|
542
|
+
if (item && typeof item.scope === 'string') byScope.set(item.scope, { ...item })
|
|
543
|
+
}
|
|
544
|
+
// 即使还没有任何记录 / 宿主没给 sessions,也要能把默认集合里的 scope 勾出来。
|
|
545
|
+
const ensure = (scope) => {
|
|
546
|
+
if (typeof scope === 'string' && scope !== '' && !byScope.has(scope)) {
|
|
547
|
+
byScope.set(scope, { scope, records: 0, pendingEmbeds: 0 })
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
const sessionScope = refs?.session ?? defaults.find((scope) => scope.startsWith('session:'))
|
|
551
|
+
const projectScope = refs?.project ?? defaults.find((scope) => scope.startsWith('project:'))
|
|
552
|
+
// 默认范围的**基础集合** = 会话 + 项目 + global。它们天然包含在默认范围里,
|
|
553
|
+
// 面板按「已绑定」展示且不可取消;工作区绑定只负责额外并入其它作用域。
|
|
554
|
+
let defaultScopes = []
|
|
555
|
+
try {
|
|
556
|
+
const list = typeof memory.defaultScopes === 'function' ? memory.defaultScopes(agentLike) : undefined
|
|
557
|
+
if (Array.isArray(list)) defaultScopes = list.filter((scope) => typeof scope === 'string' && scope !== '')
|
|
558
|
+
} catch { /* 旧 provider:退回下面的本地面包 */ }
|
|
559
|
+
if (defaultScopes.length === 0) {
|
|
560
|
+
defaultScopes = [sessionScope, projectScope, 'global'].filter((scope) => typeof scope === 'string' && scope !== '')
|
|
561
|
+
}
|
|
562
|
+
const defaultBound = new Set(defaultScopes)
|
|
563
|
+
ensure(sessionScope)
|
|
564
|
+
ensure(projectScope)
|
|
565
|
+
ensure('global')
|
|
566
|
+
for (const scope of defaults) ensure(scope)
|
|
567
|
+
for (const scope of bindings) ensure(scope)
|
|
568
|
+
const rank = (scope) => scope === sessionScope ? 0 : scope === projectScope ? 1 : scope === 'global' ? 2 : 3
|
|
569
|
+
const scopes = [...byScope.values()]
|
|
570
|
+
.sort((a, b) => rank(a.scope) - rank(b.scope) || String(a.scope).localeCompare(String(b.scope)))
|
|
571
|
+
.map((item) => {
|
|
572
|
+
const rule = rules.get(item.scope)
|
|
573
|
+
return {
|
|
574
|
+
...item,
|
|
575
|
+
// 别名也带类型前缀:项目别名 → `project:<别名>`,自定义 → `custom:<别名>`。
|
|
576
|
+
label: typeof item.name === 'string' && item.name !== ''
|
|
577
|
+
? scopeDisplayName(item.scope, item.name)
|
|
578
|
+
: scopeLabel(ctx, item.scope),
|
|
579
|
+
read: rule === undefined ? true : rule.read !== false,
|
|
580
|
+
write: rule === undefined ? true : rule.write !== false,
|
|
581
|
+
// bound = 显式绑定或默认范围自带;defaultBound 告诉客户端这一项不能取消。
|
|
582
|
+
bound: bound.has(item.scope) || defaultBound.has(item.scope),
|
|
583
|
+
defaultBound: defaultBound.has(item.scope),
|
|
584
|
+
bindable: !String(item.scope).startsWith('session:') && !defaultBound.has(item.scope),
|
|
585
|
+
}
|
|
586
|
+
})
|
|
587
|
+
return {
|
|
588
|
+
sessionId,
|
|
589
|
+
override: own,
|
|
590
|
+
effective,
|
|
591
|
+
inherited,
|
|
592
|
+
source,
|
|
593
|
+
defaults,
|
|
594
|
+
defaultScopes,
|
|
595
|
+
workspace,
|
|
596
|
+
bindings: [...bound],
|
|
597
|
+
scopes,
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* 校验并规范化「工作区绑定」提交(0.25.13)。
|
|
603
|
+
*
|
|
604
|
+
* `/visibility` 与 `/bindings` 共用同一套规则:只接受**具体作用域键**
|
|
605
|
+
* (不接受 `all` / 当前项目 / 当前会话这类别名),会话作用域不能绑定到工作区
|
|
606
|
+
* (它只属于某一次会话),重复项去重保序。
|
|
607
|
+
*
|
|
608
|
+
* @param rawBindings - 客户端提交的绑定数组(任意值都按非法处理)。
|
|
609
|
+
* @returns 规范化后的作用域键数组。
|
|
610
|
+
*/
|
|
611
|
+
function normalizeBindings(rawBindings) {
|
|
612
|
+
if (!Array.isArray(rawBindings)) throw new ApiError(400, 'SCOPE_INVALID', 'bindings 必须是字符串数组')
|
|
613
|
+
const bindings = []
|
|
614
|
+
for (const raw of rawBindings) {
|
|
615
|
+
if (typeof raw !== 'string' || raw.trim() === '') throw new ApiError(400, 'SCOPE_INVALID', '绑定项必须是非空字符串')
|
|
616
|
+
const normalized = normalizeScopeInput(raw)
|
|
617
|
+
if (!normalized.ok) throw new ApiError(400, normalized.code, normalized.message)
|
|
618
|
+
if (normalized.kind === 'all' || normalized.kind === 'current-project' || normalized.kind === 'current-session' || normalized.scope === undefined) {
|
|
619
|
+
throw new ApiError(400, 'SCOPE_INVALID', `绑定必须是具体作用域键: ${JSON.stringify(raw)}`)
|
|
620
|
+
}
|
|
621
|
+
if (normalized.scope.startsWith('session:')) {
|
|
622
|
+
throw new ApiError(400, 'SCOPE_INVALID', '会话作用域不能绑定到工作区')
|
|
623
|
+
}
|
|
624
|
+
if (!bindings.includes(normalized.scope)) bindings.push(normalized.scope)
|
|
625
|
+
}
|
|
626
|
+
return bindings
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* 面板「记忆权限」的授权快照(0.25.0)。
|
|
631
|
+
*
|
|
632
|
+
* grants 由 Agent 通过 memory_scopes request 申请、用户批准产生;这里只暴露
|
|
633
|
+
* scope / 权限 / 授予时间,不返回任何记忆正文。`inherited` 表示这条授权属于父会话。
|
|
634
|
+
*/
|
|
635
|
+
function grantsPayload(ctx, memory, sessionId) {
|
|
636
|
+
const list = []
|
|
637
|
+
let grants = []
|
|
638
|
+
try {
|
|
639
|
+
grants = typeof memory.sessionGrants === 'function' ? memory.sessionGrants(sessionId) : []
|
|
640
|
+
} catch { grants = [] }
|
|
641
|
+
for (const grant of Array.isArray(grants) ? grants : []) {
|
|
642
|
+
if (!grant || typeof grant.scope !== 'string' || grant.scope === '') continue
|
|
643
|
+
const permissions = Array.isArray(grant.permissions)
|
|
644
|
+
? grant.permissions.filter((permission) => permission === 'read' || permission === 'write')
|
|
645
|
+
: []
|
|
646
|
+
if (permissions.length === 0) continue
|
|
647
|
+
const ownerSession = typeof grant.sessionId === 'string' && grant.sessionId !== '' ? grant.sessionId : sessionId
|
|
648
|
+
list.push({
|
|
649
|
+
id: typeof grant.id === 'string' ? grant.id : '',
|
|
650
|
+
scope: grant.scope,
|
|
651
|
+
label: scopeLabel(ctx, grant.scope),
|
|
652
|
+
permissions,
|
|
653
|
+
grantedAt: typeof grant.grantedAt === 'number' ? grant.grantedAt : 0,
|
|
654
|
+
ownerSession,
|
|
655
|
+
inherited: ownerSession !== sessionId,
|
|
656
|
+
})
|
|
657
|
+
}
|
|
658
|
+
list.sort((a, b) => a.grantedAt - b.grantedAt || a.scope.localeCompare(b.scope))
|
|
659
|
+
return { sessionId, grants: list }
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
async function handle(ctx, routePath, req, res) {
|
|
663
|
+
const url = new URL(req.url ?? '/', 'http://dsh.local')
|
|
664
|
+
const path = url.pathname.slice(routePath.length) || '/'
|
|
665
|
+
const method = req.method ?? 'GET'
|
|
666
|
+
// 围栏在最前面:任何路由(读也一样)都先过宿主,再谈记忆。
|
|
667
|
+
const refused = refuseRequest(ctx, req)
|
|
668
|
+
if (refused !== undefined) {
|
|
669
|
+
writeRefusal(res, refused)
|
|
670
|
+
return
|
|
671
|
+
}
|
|
672
|
+
try {
|
|
673
|
+
const memory = ctx.get('memory')
|
|
674
|
+
// 审计路由只依赖注入半边挂载的 sink,不依赖记忆 store;先于 store 检查。
|
|
675
|
+
if (method === 'GET' && path === '/audit') {
|
|
676
|
+
const query = parseAuditQuery(url)
|
|
677
|
+
const value = auditPage(memory, query)
|
|
678
|
+
writeJson(res, { ok: true, value: { ...value, query: publicAuditQuery(query) } })
|
|
679
|
+
return
|
|
680
|
+
}
|
|
681
|
+
if (method === 'GET' && path === '/audit/stats') {
|
|
682
|
+
writeJson(res, { ok: true, value: auditStats(memory) })
|
|
683
|
+
return
|
|
684
|
+
}
|
|
685
|
+
if (method === 'GET' && path === '/anchor') {
|
|
686
|
+
const numeric = (name) => {
|
|
687
|
+
const raw = url.searchParams.get(name)
|
|
688
|
+
if (raw === null || raw.trim() === '') return undefined
|
|
689
|
+
if (!/^-?\d+$/.test(raw.trim())) throw new ApiError(400, 'ANCHOR_QUERY_INVALID', `${name} 必须是整数`)
|
|
690
|
+
return Number(raw)
|
|
691
|
+
}
|
|
692
|
+
const query = {
|
|
693
|
+
sessionId: url.searchParams.get('session') ?? '',
|
|
694
|
+
turn: numeric('turn'),
|
|
695
|
+
step: numeric('step'),
|
|
696
|
+
callId: url.searchParams.get('callId') ?? undefined,
|
|
697
|
+
}
|
|
698
|
+
writeJson(res, { ok: true, value: findTrajectoryAnchor(ctx, query) })
|
|
699
|
+
return
|
|
700
|
+
}
|
|
701
|
+
if (method === 'GET' && path === '/audit/export') {
|
|
702
|
+
const query = parseAuditQuery(url)
|
|
703
|
+
const format = url.searchParams.get('format') === 'jsonl' ? 'jsonl' : 'json'
|
|
704
|
+
const entries = collectAuditEntries(memory, query)
|
|
705
|
+
const body = format === 'jsonl'
|
|
706
|
+
? entries.map((entry) => JSON.stringify(entry)).join('\n') + (entries.length > 0 ? '\n' : '')
|
|
707
|
+
: JSON.stringify({
|
|
708
|
+
schemaVersion: 2,
|
|
709
|
+
exportedAt: Date.now(),
|
|
710
|
+
query: publicAuditQuery(query),
|
|
711
|
+
count: entries.length,
|
|
712
|
+
entries,
|
|
713
|
+
}, null, 2) + '\n'
|
|
714
|
+
try {
|
|
715
|
+
res.writeHead(200, {
|
|
716
|
+
'content-type': format === 'jsonl' ? 'application/x-ndjson; charset=utf-8' : 'application/json; charset=utf-8',
|
|
717
|
+
'content-disposition': `attachment; filename="dsh-memory-audit.${format === 'jsonl' ? 'jsonl' : 'json'}"`,
|
|
718
|
+
'cache-control': 'no-store',
|
|
719
|
+
})
|
|
720
|
+
res.end(body)
|
|
721
|
+
} catch { /* client disconnected */ }
|
|
722
|
+
return
|
|
723
|
+
}
|
|
724
|
+
if (!memory?.store) throw new ApiError(503, 'MEMORY_UNAVAILABLE', 'memory provider 未加载')
|
|
725
|
+
const store = memory.store
|
|
726
|
+
// Scopes are created lazily, so a fresh process only knows the ones it has
|
|
727
|
+
// touched. A management view must see everything written on disk (project
|
|
728
|
+
// memories from earlier sessions included) — best-effort discovery, cached.
|
|
729
|
+
discoverScopes(memory, store)
|
|
730
|
+
|
|
731
|
+
// 会话级「记忆可见范围」:输入框旁的按钮读写这一对接口。
|
|
732
|
+
if (method === 'GET' && path === '/visibility') {
|
|
733
|
+
if (typeof memory.sessionVisibility !== 'function') {
|
|
734
|
+
throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供会话可见范围接口(请升级 @restregular/dsh-memory)')
|
|
735
|
+
}
|
|
736
|
+
const sessionId = (url.searchParams.get('session') ?? '').trim()
|
|
737
|
+
if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 参数不能为空')
|
|
738
|
+
writeJson(res, { ok: true, value: visibilityPayload(ctx, memory, sessionId) })
|
|
739
|
+
return
|
|
740
|
+
}
|
|
741
|
+
if (method === 'POST' && path === '/visibility') {
|
|
742
|
+
if (typeof memory.setSessionVisibility !== 'function') {
|
|
743
|
+
throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供会话可见范围接口(请升级 @restregular/dsh-memory)')
|
|
744
|
+
}
|
|
745
|
+
const body = await readJsonBody(req)
|
|
746
|
+
const sessionId = typeof body?.session === 'string' ? body.session.trim() : ''
|
|
747
|
+
if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 不能为空')
|
|
748
|
+
let next = null
|
|
749
|
+
const rawConfig = body?.visibility
|
|
750
|
+
// 新协议:{ visibility: { scopes: [{ scope, read?, write? }], level } } | null
|
|
751
|
+
// 兼容 0.19.0 的 { scopes: [{ scope, kinds? }] } 与 0.18 的 { scopes: string[] }:
|
|
752
|
+
// 0.19.1 起不再限制记忆类型,提交里的 kinds 一律忽略。
|
|
753
|
+
const rawScopes = rawConfig !== null && rawConfig !== undefined && typeof rawConfig === 'object'
|
|
754
|
+
? rawConfig.scopes
|
|
755
|
+
: body?.scopes
|
|
756
|
+
if (rawScopes !== null && rawScopes !== undefined) {
|
|
757
|
+
if (!Array.isArray(rawScopes)) throw new ApiError(400, 'SCOPE_INVALID', 'scopes 必须是数组或 null')
|
|
758
|
+
if (rawScopes.length === 0) throw new ApiError(400, 'SCOPE_EMPTY', '至少选择一个可见范围')
|
|
759
|
+
const scopes = []
|
|
760
|
+
for (const raw of rawScopes) {
|
|
761
|
+
const scopeRaw = typeof raw === 'string' ? raw : raw?.scope
|
|
762
|
+
if (typeof scopeRaw !== 'string' || scopeRaw.trim() === '') {
|
|
763
|
+
throw new ApiError(400, 'SCOPE_INVALID', 'scope 必须是非空字符串')
|
|
764
|
+
}
|
|
765
|
+
const normalized = normalizeScopeInput(scopeRaw)
|
|
766
|
+
if (!normalized.ok) throw new ApiError(400, normalized.code, normalized.message)
|
|
767
|
+
if (normalized.kind === 'all' || normalized.kind === 'current-project' || normalized.kind === 'current-session') {
|
|
768
|
+
throw new ApiError(400, 'SCOPE_INVALID', `可见范围必须是具体作用域键: ${JSON.stringify(scopeRaw)}`)
|
|
769
|
+
}
|
|
770
|
+
if (normalized.scope === undefined || scopes.some((item) => item.scope === normalized.scope)) continue
|
|
771
|
+
// 0.23.0:read / write 状态。省略 = 可读可写;只有显式 false 才落盘。
|
|
772
|
+
const read = typeof raw === 'object' && raw !== null && raw.read === false
|
|
773
|
+
const write = typeof raw === 'object' && raw !== null && raw.write === false
|
|
774
|
+
scopes.push({
|
|
775
|
+
scope: normalized.scope,
|
|
776
|
+
...(read ? { read: false } : {}),
|
|
777
|
+
...(write ? { write: false } : {}),
|
|
778
|
+
})
|
|
779
|
+
}
|
|
780
|
+
const levelRaw = rawConfig !== null && rawConfig !== undefined && typeof rawConfig === 'object' ? rawConfig.level : 'absolute'
|
|
781
|
+
const level = levelRaw === 'normal' || levelRaw === 'none' ? levelRaw : 'absolute'
|
|
782
|
+
next = { scopes, level }
|
|
783
|
+
}
|
|
784
|
+
// 工作区级绑定:省略 = 不改;数组 = 整体替换。与可见范围同一个保存动作提交。
|
|
785
|
+
const rawBindings = body?.bindings
|
|
786
|
+
if (rawBindings !== undefined) {
|
|
787
|
+
if (typeof memory.setWorkspaceBindings !== 'function') {
|
|
788
|
+
throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供工作区绑定接口(请升级 @restregular/dsh-memory)')
|
|
789
|
+
}
|
|
790
|
+
const bindings = normalizeBindings(rawBindings)
|
|
791
|
+
let session
|
|
792
|
+
try { session = ctx.get('sessions')?.get?.(sessionId) } catch { session = undefined }
|
|
793
|
+
memory.setWorkspaceBindings({ session: session !== undefined ? session : { id: sessionId } }, bindings)
|
|
794
|
+
}
|
|
795
|
+
memory.setSessionVisibility(sessionId, next)
|
|
796
|
+
writeJson(res, { ok: true, value: visibilityPayload(ctx, memory, sessionId) })
|
|
797
|
+
return
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
// 记忆权限浮窗的「绑定」按钮**单独保存**(0.25.13):绑定是工作区级设置
|
|
801
|
+
// (本工作区新会话的默认可见范围),和「勾选范围 / 可读可写」的草稿无关,
|
|
802
|
+
// 所以点一下立即落盘,不需要用户再点「保存」;也不注入上下文提示。
|
|
803
|
+
if (method === 'POST' && path === '/bindings') {
|
|
804
|
+
if (typeof memory.setWorkspaceBindings !== 'function') {
|
|
805
|
+
throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供工作区绑定接口(请升级 @restregular/dsh-memory)')
|
|
806
|
+
}
|
|
807
|
+
const body = await readJsonBody(req)
|
|
808
|
+
const sessionId = typeof body?.session === 'string' ? body.session.trim() : ''
|
|
809
|
+
if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 不能为空')
|
|
810
|
+
const bindings = normalizeBindings(body?.bindings)
|
|
811
|
+
let session
|
|
812
|
+
try { session = ctx.get('sessions')?.get?.(sessionId) } catch { session = undefined }
|
|
813
|
+
const written = memory.setWorkspaceBindings({ session: session !== undefined ? session : { id: sessionId } }, bindings)
|
|
814
|
+
writeJson(res, {
|
|
815
|
+
ok: true,
|
|
816
|
+
value: { sessionId, bindings: Array.isArray(written) ? written : bindings },
|
|
817
|
+
})
|
|
818
|
+
return
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
// 普通限制下的范围外访问审批:客户端浮层轮询待审批,用户点「拒绝 / 允许一次」后回写。
|
|
822
|
+
// `summary=1` 是 0.25.14 新增的轻量口径:侧边栏阻塞提醒只需要 id + sessionId,
|
|
823
|
+
// 不带条目正文,避免全局 1.5s 轮询把审批内容一遍遍传一遍。
|
|
824
|
+
if (method === 'GET' && path === '/approvals') {
|
|
825
|
+
if (typeof memory.pendingVisibilityApprovals !== 'function') {
|
|
826
|
+
throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供可见域审批接口(请升级 @restregular/dsh-memory)')
|
|
827
|
+
}
|
|
828
|
+
const sessionId = (url.searchParams.get('session') ?? '').trim()
|
|
829
|
+
const summary = url.searchParams.get('summary') === '1'
|
|
830
|
+
const approvals = summary && typeof memory.pendingVisibilityApprovalPresence === 'function'
|
|
831
|
+
? memory.pendingVisibilityApprovalPresence(sessionId === '' ? undefined : sessionId)
|
|
832
|
+
: memory.pendingVisibilityApprovals(sessionId === '' ? undefined : sessionId)
|
|
833
|
+
writeJson(res, { ok: true, value: { approvals } })
|
|
834
|
+
return
|
|
835
|
+
}
|
|
836
|
+
if (method === 'POST' && path === '/approvals') {
|
|
837
|
+
if (typeof memory.answerVisibilityApproval !== 'function') {
|
|
838
|
+
throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供可见域审批接口(请升级 @restregular/dsh-memory)')
|
|
839
|
+
}
|
|
840
|
+
const body = await readJsonBody(req)
|
|
841
|
+
const id = typeof body?.id === 'string' ? body.id.trim() : ''
|
|
842
|
+
if (id === '') throw new ApiError(400, 'APPROVAL_ID_REQUIRED', 'id 不能为空')
|
|
843
|
+
const outcome = body?.outcome === 'allowed-once' ? 'allowed-once' : body?.outcome === 'rejected' ? 'rejected' : ''
|
|
844
|
+
if (outcome === '') throw new ApiError(400, 'APPROVAL_OUTCOME_INVALID', 'outcome 必须是 allowed-once 或 rejected')
|
|
845
|
+
// 0.21.0:逐条允许。省略 = 全部允许;空数组 = 一条都不允许(按拒绝处理)。
|
|
846
|
+
const rawIds = body?.allowedIds
|
|
847
|
+
if (rawIds !== undefined && rawIds !== null && !Array.isArray(rawIds)) {
|
|
848
|
+
throw new ApiError(400, 'APPROVAL_IDS_INVALID', 'allowedIds 必须是字符串数组')
|
|
849
|
+
}
|
|
850
|
+
const allowedIds = Array.isArray(rawIds) ? rawIds.filter((value) => typeof value === 'string' && value !== '') : undefined
|
|
851
|
+
const answered = allowedIds === undefined
|
|
852
|
+
? memory.answerVisibilityApproval(id, outcome)
|
|
853
|
+
: memory.answerVisibilityApproval(id, outcome, allowedIds)
|
|
854
|
+
writeJson(res, { ok: true, value: { answered } })
|
|
855
|
+
return
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// 面板「记忆权限」:Agent 申请到的会话授权 + 撤销(0.25.0)。
|
|
859
|
+
if (method === 'GET' && path === '/grants') {
|
|
860
|
+
if (typeof memory.sessionGrants !== 'function') {
|
|
861
|
+
throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供会话授权接口(请升级 @restregular/dsh-memory)')
|
|
862
|
+
}
|
|
863
|
+
const sessionId = (url.searchParams.get('session') ?? '').trim()
|
|
864
|
+
if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 参数不能为空')
|
|
865
|
+
writeJson(res, { ok: true, value: grantsPayload(ctx, memory, sessionId) })
|
|
866
|
+
return
|
|
867
|
+
}
|
|
868
|
+
if (method === 'POST' && path === '/grants') {
|
|
869
|
+
if (typeof memory.revokeGrant !== 'function') {
|
|
870
|
+
throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供授权撤销接口(请升级 @restregular/dsh-memory)')
|
|
871
|
+
}
|
|
872
|
+
const body = await readJsonBody(req)
|
|
873
|
+
const sessionId = typeof body?.session === 'string' ? body.session.trim() : ''
|
|
874
|
+
const id = typeof body?.id === 'string' ? body.id.trim() : ''
|
|
875
|
+
if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 不能为空')
|
|
876
|
+
if (id === '') throw new ApiError(400, 'GRANT_ID_REQUIRED', 'id 不能为空')
|
|
877
|
+
const revoked = memory.revokeGrant(sessionId, id)
|
|
878
|
+
if (!revoked) throw new ApiError(404, 'GRANT_NOT_FOUND', '没有找到这条授权(可能已撤销或已过期)')
|
|
879
|
+
const view = typeof body?.view === 'string' && body.view.trim() !== '' ? body.view.trim() : sessionId
|
|
880
|
+
writeJson(res, { ok: true, value: grantsPayload(ctx, memory, view) })
|
|
881
|
+
return
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
if (method === 'GET' && path === '/status') {
|
|
885
|
+
const stats = typeof memory.scopeStats === 'function'
|
|
886
|
+
? memory.scopeStats()
|
|
887
|
+
: store.allScopes().map((s) => ({ scope: s.scope, records: s.records.size, pendingEmbeds: s.embedPending.size }))
|
|
888
|
+
// 作用域用途(0.28.0):面板「记录 → 作用域」子标签页要展示的「这个域是干什么的」。
|
|
889
|
+
// 与 memory_scopes 目录 / memory_search 的范围外清单同源(scope-meta 手写优先,
|
|
890
|
+
// 没写过按类型给默认描述),所以三处看到的用途永远一致。
|
|
891
|
+
const catalog = new Map()
|
|
892
|
+
try {
|
|
893
|
+
if (typeof memory.scopeCatalog === 'function') {
|
|
894
|
+
for (const entry of memory.scopeCatalog(undefined) ?? []) {
|
|
895
|
+
if (entry && typeof entry.scope === 'string') catalog.set(entry.scope, entry)
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
} catch { /* 目录是增强:拿不到就只有名称与条数 */ }
|
|
899
|
+
// 会话标题是尽力而为的增强,而且要读会话事件日志:只给最近活跃的前 N 个查,
|
|
900
|
+
// 其余直接用「会话 <id 前 16 位>」。列表本身**始终**完整(不受这个上限影响)。
|
|
901
|
+
// 手写用途与默认描述的区分(0.29.0):面板要能编辑「用途」,就得知道现在显示的是
|
|
902
|
+
// 自己写的那句,还是按类型补的默认描述 —— 编辑框只预填手写的,否则一保存就把
|
|
903
|
+
// 默认文案固化成手写内容。`descriptionSource` 就是给这个用的。
|
|
904
|
+
const customDescriptionOf = (scope) => {
|
|
905
|
+
try {
|
|
906
|
+
const meta = typeof memory.scopeMeta === 'function' ? memory.scopeMeta(scope) : undefined
|
|
907
|
+
return typeof meta?.description === 'string' ? meta.description.trim() : ''
|
|
908
|
+
} catch {
|
|
909
|
+
return ''
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
const scopes = stats.map((s, index) => {
|
|
913
|
+
const entry = catalog.get(s.scope)
|
|
914
|
+
const custom = customDescriptionOf(s.scope)
|
|
915
|
+
return {
|
|
916
|
+
...s,
|
|
917
|
+
// 别名(项目 / 自定义作用域)也要带类型前缀;没有别名时退回按类型算的展示名。
|
|
918
|
+
label: typeof s.name === 'string' && s.name !== ''
|
|
919
|
+
? scopeDisplayName(s.scope, s.name)
|
|
920
|
+
: (index < TITLE_LOOKUP_LIMIT ? scopeLabel(ctx, s.scope) : fallbackScopeLabel(s.scope)),
|
|
921
|
+
...(custom !== ''
|
|
922
|
+
? { description: custom, descriptionSource: 'custom' }
|
|
923
|
+
: entry !== undefined && typeof entry.description === 'string' && entry.description.trim() !== ''
|
|
924
|
+
? { description: entry.description.trim(), descriptionSource: 'default' }
|
|
925
|
+
: {}),
|
|
926
|
+
...(entry !== undefined && typeof entry.origin === 'string' ? { origin: entry.origin } : {}),
|
|
927
|
+
}
|
|
928
|
+
})
|
|
929
|
+
// 删光记录不等于作用域消失:目录里有用途、却没有记录的作用域也列出来。
|
|
930
|
+
// 只收**有元数据**的(updatedAt 来自 scope-meta):默认三路里的 global / 当前项目
|
|
931
|
+
// 也会出现在目录里,但它们未必真的落过盘,全塞进列表就是凭空多出两个作用域。
|
|
932
|
+
// 别的会话的 session scope 不列 —— 它们的用途是空的,只会把清单变长。
|
|
933
|
+
const seen = new Set(scopes.map((s) => s.scope))
|
|
934
|
+
for (const [key, entry] of catalog) {
|
|
935
|
+
if (seen.has(key) || key.startsWith('session:')) continue
|
|
936
|
+
if (typeof entry.description !== 'string' || entry.description.trim() === '') continue
|
|
937
|
+
if (!(typeof entry.updatedAt === 'number' && entry.updatedAt > 0)) continue
|
|
938
|
+
scopes.push({
|
|
939
|
+
scope: key,
|
|
940
|
+
records: 0,
|
|
941
|
+
pendingEmbeds: 0,
|
|
942
|
+
updatedAt: entry.updatedAt,
|
|
943
|
+
...(typeof entry.name === 'string' && entry.name !== '' ? { name: entry.name } : {}),
|
|
944
|
+
label: typeof entry.name === 'string' && entry.name !== ''
|
|
945
|
+
? scopeDisplayName(key, entry.name)
|
|
946
|
+
: fallbackScopeLabel(key),
|
|
947
|
+
description: entry.description.trim(),
|
|
948
|
+
descriptionSource: customDescriptionOf(key) !== '' ? 'custom' : 'default',
|
|
949
|
+
...(typeof entry.origin === 'string' ? { origin: entry.origin } : {}),
|
|
950
|
+
...(entry.archived === true ? { archived: true } : {}),
|
|
951
|
+
})
|
|
952
|
+
}
|
|
953
|
+
let embedServer = null
|
|
954
|
+
// older providers have no lifecycle API — the panel simply omits the card
|
|
955
|
+
try { embedServer = (await memory.embedServerStatus?.()) ?? null } catch { embedServer = null }
|
|
956
|
+
let rules = null
|
|
957
|
+
try { rules = typeof memory.ruleStats === 'function' ? memory.ruleStats() : null } catch { rules = null }
|
|
958
|
+
writeJson(res, { ok: true, value: { scopes, embedServer, rules } })
|
|
959
|
+
return
|
|
960
|
+
}
|
|
961
|
+
if (method === 'POST' && path === '/scope-meta') {
|
|
962
|
+
// 用户编辑作用域的描述 / 别名(0.29.0)。面板是用户本人的操作,不带会话可见域;
|
|
963
|
+
// 但只允许改**目录里看得见**的作用域,免得手滑把用途写到一条永远读不到的元数据上。
|
|
964
|
+
if (typeof memory.describeScope !== 'function' && typeof memory.renameScope !== 'function') {
|
|
965
|
+
throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供作用域编辑接口(请升级 @restregular/dsh-memory)')
|
|
966
|
+
}
|
|
967
|
+
const body = await readJsonBody(req)
|
|
968
|
+
const scope = typeof body?.scope === 'string' ? body.scope.trim() : ''
|
|
969
|
+
if (scope === '') throw new ApiError(400, 'SCOPE_INVALID', 'scope 不能为空')
|
|
970
|
+
const wantDescription = typeof body?.description === 'string'
|
|
971
|
+
const wantName = typeof body?.name === 'string'
|
|
972
|
+
if (!wantDescription && !wantName) {
|
|
973
|
+
throw new ApiError(400, 'SCOPE_NOTHING_TO_UPDATE', '至少提供 description(用途)或 name(别名)之一')
|
|
974
|
+
}
|
|
975
|
+
if (typeof memory.scopeCatalog === 'function') {
|
|
976
|
+
let known = false
|
|
977
|
+
try {
|
|
978
|
+
known = (memory.scopeCatalog(undefined) ?? []).some((item) => item?.scope === scope)
|
|
979
|
+
} catch { known = true /* 目录不可用时不拦:让 provider 自己校验 */ }
|
|
980
|
+
if (!known) throw new ApiError(404, 'SCOPE_UNKNOWN', `目录里没有作用域 ${scope}(可能刚被删除或改名)`)
|
|
981
|
+
}
|
|
982
|
+
let description
|
|
983
|
+
if (wantDescription) {
|
|
984
|
+
if (typeof memory.describeScope !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供作用域用途编辑接口')
|
|
985
|
+
description = memory.describeScope(scope, String(body.description), 'user').description
|
|
986
|
+
}
|
|
987
|
+
let name
|
|
988
|
+
if (wantName) {
|
|
989
|
+
if (typeof memory.renameScope !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供作用域别名编辑接口')
|
|
990
|
+
name = memory.renameScope(scope, String(body.name)).name ?? ''
|
|
991
|
+
}
|
|
992
|
+
writeJson(res, {
|
|
993
|
+
ok: true,
|
|
994
|
+
value: {
|
|
995
|
+
scope,
|
|
996
|
+
...(wantDescription ? { description } : {}),
|
|
997
|
+
...(wantName ? { name } : {}),
|
|
998
|
+
},
|
|
999
|
+
})
|
|
1000
|
+
return
|
|
1001
|
+
}
|
|
1002
|
+
if (method === 'GET' && path === '/settings') {
|
|
1003
|
+
if (typeof memory.injectSettings !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供注入设置接口(请升级 @restregular/dsh-memory)')
|
|
1004
|
+
writeJson(res, { ok: true, value: memory.injectSettings() })
|
|
1005
|
+
return
|
|
1006
|
+
}
|
|
1007
|
+
if (method === 'POST' && path === '/settings') {
|
|
1008
|
+
if (typeof memory.updateInjectSettings !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供注入设置接口(请升级 @restregular/dsh-memory)')
|
|
1009
|
+
const body = await readJsonBody(req)
|
|
1010
|
+
writeJson(res, { ok: true, value: memory.updateInjectSettings(body) })
|
|
1011
|
+
return
|
|
1012
|
+
}
|
|
1013
|
+
if (method === 'POST' && path === '/create') {
|
|
1014
|
+
if (typeof memory.createRecord !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供新建接口(请升级 @restregular/dsh-memory)')
|
|
1015
|
+
const body = await readJsonBody(req)
|
|
1016
|
+
const record = await memory.createRecord({
|
|
1017
|
+
...(typeof body.scope === 'string' ? { scope: body.scope } : {}),
|
|
1018
|
+
...(typeof body.kind === 'string' ? { kind: body.kind } : {}),
|
|
1019
|
+
...(typeof body.content === 'string' ? { content: body.content } : {}),
|
|
1020
|
+
...(Array.isArray(body.tags) ? { tags: body.tags.map(String) } : {}),
|
|
1021
|
+
...(typeof body.importance === 'number' ? { importance: body.importance } : {}),
|
|
1022
|
+
...(typeof body.ttlMs === 'number' ? { ttlMs: body.ttlMs } : {}),
|
|
1023
|
+
...(typeof body.expiresAt === 'number' ? { expiresAt: body.expiresAt } : {}),
|
|
1024
|
+
...(Array.isArray(body.triggers) ? { triggers: body.triggers.map(String) } : {}),
|
|
1025
|
+
})
|
|
1026
|
+
console.log(`[dsh-memory-panel] 新建 ${record.kind} @ ${record.scope}: ${record.id}`)
|
|
1027
|
+
writeJson(res, { ok: true, value: { record } })
|
|
1028
|
+
return
|
|
1029
|
+
}
|
|
1030
|
+
if (method === 'GET' && path === '/export') {
|
|
1031
|
+
if (typeof memory.exportAll !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供导出接口(请升级 @restregular/dsh-memory)')
|
|
1032
|
+
writeJson(res, { ok: true, value: memory.exportAll() })
|
|
1033
|
+
return
|
|
1034
|
+
}
|
|
1035
|
+
if (method === 'POST' && path === '/import') {
|
|
1036
|
+
if (typeof memory.importRecords !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供导入接口(请升级 @restregular/dsh-memory)')
|
|
1037
|
+
const body = await readJsonBody(req)
|
|
1038
|
+
const result = await memory.importRecords(body)
|
|
1039
|
+
console.log(`[dsh-memory-panel] 导入完成: 新增 ${result.imported} / 跳过 ${result.skipped} / 失败 ${result.rejected}`)
|
|
1040
|
+
writeJson(res, { ok: true, value: result })
|
|
1041
|
+
return
|
|
1042
|
+
}
|
|
1043
|
+
if (method === 'GET' && path === '/embed/status') { if (typeof memory.embedServerStatus !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量服务管理接口')
|
|
1044
|
+
writeJson(res, { ok: true, value: await memory.embedServerStatus() })
|
|
1045
|
+
return
|
|
1046
|
+
}
|
|
1047
|
+
if (method === 'POST' && path === '/embed/start') {
|
|
1048
|
+
if (typeof memory.startEmbedServerManually !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量服务管理接口')
|
|
1049
|
+
const state = await memory.startEmbedServerManually()
|
|
1050
|
+
console.log(`[dsh-memory-panel] 手动启动向量服务 -> ${state}`)
|
|
1051
|
+
writeJson(res, { ok: true, value: { state, ...(await memory.embedServerStatus()) } })
|
|
1052
|
+
return
|
|
1053
|
+
}
|
|
1054
|
+
if (method === 'POST' && path === '/embed/stop') {
|
|
1055
|
+
if (typeof memory.stopEmbedServerManually !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量服务管理接口')
|
|
1056
|
+
const out = memory.stopEmbedServerManually()
|
|
1057
|
+
console.log(`[dsh-memory-panel] 手动停止向量服务 -> ${out.reason}`)
|
|
1058
|
+
writeJson(res, { ok: true, value: { ...out, ...(await memory.embedServerStatus()) } })
|
|
1059
|
+
return
|
|
1060
|
+
}
|
|
1061
|
+
if (method === 'GET' && path === '/embed/model') {
|
|
1062
|
+
if (typeof memory.modelsReport !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供模型清单接口(请升级 @restregular/dsh-memory)')
|
|
1063
|
+
writeJson(res, { ok: true, value: await memory.modelsReport(false) })
|
|
1064
|
+
return
|
|
1065
|
+
}
|
|
1066
|
+
if (method === 'POST' && path === '/embed/model/refresh') {
|
|
1067
|
+
if (typeof memory.modelsReport !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供模型清单接口(请升级 @restregular/dsh-memory)')
|
|
1068
|
+
// 强制重探硬件:用户点了「重新检测」,缓存必须让路。
|
|
1069
|
+
writeJson(res, { ok: true, value: await memory.modelsReport(true) })
|
|
1070
|
+
return
|
|
1071
|
+
}
|
|
1072
|
+
if (method === 'POST' && path === '/embed/install') {
|
|
1073
|
+
if (typeof memory.installVectorBackend !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供自动安装接口(请升级 @restregular/dsh-memory)')
|
|
1074
|
+
// 面板可以带选择:预设 / 档位 / 风味,或者一个完全自定义的 GGUF。
|
|
1075
|
+
const body = await readJsonBody(req)
|
|
1076
|
+
const override = {}
|
|
1077
|
+
if (typeof body.preset === 'string' && body.preset !== '') override.preset = body.preset
|
|
1078
|
+
if (typeof body.variant === 'string' && body.variant !== '') override.variant = body.variant
|
|
1079
|
+
if (typeof body.flavor === 'string' && body.flavor !== '') override.flavor = body.flavor
|
|
1080
|
+
if (body.custom !== undefined && typeof body.custom === 'object' && body.custom !== null) {
|
|
1081
|
+
const url = String(body.custom.url ?? '')
|
|
1082
|
+
const dims = Number(body.custom.dims)
|
|
1083
|
+
if (url === '' || !Number.isFinite(dims) || dims <= 0) throw new ApiError(400, 'CUSTOM_MODEL_INVALID', '自定义模型需要 url 与 dims')
|
|
1084
|
+
override.custom = {
|
|
1085
|
+
url,
|
|
1086
|
+
dims,
|
|
1087
|
+
...(body.custom.file ? { file: String(body.custom.file) } : {}),
|
|
1088
|
+
...(body.custom.pooling ? { pooling: String(body.custom.pooling) } : {}),
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
memory.installVectorBackend(override)
|
|
1092
|
+
console.log(`[dsh-memory-panel] 开始下载向量服务 ${JSON.stringify(override)}`)
|
|
1093
|
+
writeJson(res, { ok: true, value: { ...(await memory.embedServerStatus()) } })
|
|
1094
|
+
return
|
|
1095
|
+
}
|
|
1096
|
+
if (method === 'POST' && path === '/embed/install/cancel') {
|
|
1097
|
+
if (typeof memory.cancelVectorInstall !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供自动安装接口(请升级 @restregular/dsh-memory)')
|
|
1098
|
+
memory.cancelVectorInstall()
|
|
1099
|
+
console.log('[dsh-memory-panel] 取消下载本地向量服务')
|
|
1100
|
+
writeJson(res, { ok: true, value: { ...(await memory.embedServerStatus()) } })
|
|
1101
|
+
return
|
|
1102
|
+
}
|
|
1103
|
+
if (method === 'POST' && path === '/embed/uninstall') {
|
|
1104
|
+
if (typeof memory.uninstallVectorBackend !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供卸载接口(请升级 @restregular/dsh-memory)')
|
|
1105
|
+
const out = memory.uninstallVectorBackend()
|
|
1106
|
+
console.log(`[dsh-memory-panel] 卸载向量服务 -> ${out.reason},释放 ${(out.freedBytes / 1048576).toFixed(1)} MB`)
|
|
1107
|
+
writeJson(res, { ok: true, value: { ...out, ...(await memory.embedServerStatus()) } })
|
|
1108
|
+
return
|
|
1109
|
+
}
|
|
1110
|
+
if (method === 'POST' && path === '/embed/reindex') {
|
|
1111
|
+
if (typeof memory.reindexAll !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量重建接口(请升级 @restregular/dsh-memory)')
|
|
1112
|
+
// 同步部分只作废旧向量 + 排队,真正的重嵌在后台跑,不阻塞请求;进度看 /status 的待嵌入计数。
|
|
1113
|
+
const result = memory.reindexAll() ?? {}
|
|
1114
|
+
const total = typeof result.total === 'number' ? result.total : 0
|
|
1115
|
+
console.log(`[dsh-memory-panel] 开始重建全部向量:${total} 条`)
|
|
1116
|
+
writeJson(res, { ok: true, value: { scheduled: true, records: total } })
|
|
1117
|
+
return
|
|
1118
|
+
}
|
|
1119
|
+
if (method === 'POST' && path === '/data/wipe') {
|
|
1120
|
+
if (typeof memory.wipeAllRecords !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供数据清理接口(请升级 @restregular/dsh-memory)')
|
|
1121
|
+
const body = await readJsonBody(req)
|
|
1122
|
+
// Deleting everything is irreversible: require the caller to say so out
|
|
1123
|
+
// loud, not just to click a button.
|
|
1124
|
+
if (String(body.confirm ?? '') !== 'delete') throw new ApiError(400, 'CONFIRM_REQUIRED', '需要 confirm: "delete" 才执行删除')
|
|
1125
|
+
const out = memory.wipeAllRecords()
|
|
1126
|
+
console.log(`[dsh-memory-panel] 清空记忆数据 -> ${out.removed} 条 / ${out.scopes.length} 个作用域`)
|
|
1127
|
+
writeJson(res, { ok: true, value: { ...out, ...(await memory.embedServerStatus()) } })
|
|
1128
|
+
return
|
|
1129
|
+
}
|
|
1130
|
+
if (method === 'GET' && path === '/records') {
|
|
1131
|
+
const rawScope = url.searchParams.get('scope')
|
|
1132
|
+
const query = (url.searchParams.get('q') ?? '').trim().toLowerCase()
|
|
1133
|
+
const idQuery = (url.searchParams.get('id') ?? '').trim()
|
|
1134
|
+
// scope 先过同一套规范化:非法 → 400(而不是当成一个陌生 scope 去建文件);
|
|
1135
|
+
// 合法但不存在的 scope → 空列表。`peek`/`peekScope`,**绝不通过 store.scope() 创建**。
|
|
1136
|
+
const stores = selectedStores(store, resolveScopeSelection(memory, rawScope))
|
|
1137
|
+
let records = []
|
|
1138
|
+
for (const s of stores) records.push(...collectScope(s))
|
|
1139
|
+
if (query) {
|
|
1140
|
+
records = records.filter((r) =>
|
|
1141
|
+
r.content.toLowerCase().includes(query)
|
|
1142
|
+
|| r.kind.toLowerCase().includes(query)
|
|
1143
|
+
|| r.tags.some((t) => t.toLowerCase().includes(query)))
|
|
1144
|
+
}
|
|
1145
|
+
if (idQuery) {
|
|
1146
|
+
records = records.filter((r) => r.id === idQuery || r.id.startsWith(idQuery))
|
|
1147
|
+
}
|
|
1148
|
+
writeJson(res, { ok: true, value: { records } })
|
|
1149
|
+
return
|
|
1150
|
+
}
|
|
1151
|
+
// 记录页的「语义检索」:和 memory_search 同一套召回排序(向量 + 词法 + 可选重排),
|
|
1152
|
+
// 由 provider 的 searchForPanel 执行 —— 只读、不写访问计数,并报告向量通道是否
|
|
1153
|
+
// 真的参与,面板据此如实标注「语义排序」还是「退回关键词」。
|
|
1154
|
+
if (method === 'GET' && path === '/search') {
|
|
1155
|
+
const text = (url.searchParams.get('q') ?? '').trim()
|
|
1156
|
+
if (text === '') throw new ApiError(400, 'QUERY_EMPTY', '搜索内容不能为空')
|
|
1157
|
+
let topK = 20
|
|
1158
|
+
const rawTopK = (url.searchParams.get('topK') ?? '').trim()
|
|
1159
|
+
if (rawTopK !== '') {
|
|
1160
|
+
if (!/^\d+$/.test(rawTopK)) throw new ApiError(400, 'QUERY_INVALID', 'topK 必须是 1..50 的整数')
|
|
1161
|
+
topK = Number(rawTopK)
|
|
1162
|
+
if (topK < 1 || topK > 50) throw new ApiError(400, 'QUERY_INVALID', 'topK 必须在 1..50 之间')
|
|
1163
|
+
}
|
|
1164
|
+
const scopes = selectedStores(store, resolveScopeSelection(memory, url.searchParams.get('scope')))
|
|
1165
|
+
const keys = scopes.map((s) => s.scope)
|
|
1166
|
+
// 空集合不能交给旧 provider 的 search():它会退回"默认项目 + global",
|
|
1167
|
+
// 等于点了一个不存在的 scope 却搜出别的 scope 的记录。
|
|
1168
|
+
if (keys.length === 0) {
|
|
1169
|
+
writeJson(res, { ok: true, value: { hits: [], mode: 'lexical', reason: 'no-records', embedded: 0, total: 0 } })
|
|
1170
|
+
return
|
|
1171
|
+
}
|
|
1172
|
+
const totalRecords = scopes.reduce((n, s) => n + s.records.size, 0)
|
|
1173
|
+
const wireHit = (hit) => {
|
|
1174
|
+
const scopeStore = store.peek(hit.record.scope)
|
|
1175
|
+
let supersededBy = null
|
|
1176
|
+
if (scopeStore !== undefined) {
|
|
1177
|
+
for (const other of scopeStore.records.values()) {
|
|
1178
|
+
if (other.supersedes === hit.record.id) { supersededBy = other.id; break }
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
const record = wireRecord(
|
|
1182
|
+
hit.record,
|
|
1183
|
+
scopeStore ?? { embedPending: new Map(), vectors: new Map() },
|
|
1184
|
+
supersededBy,
|
|
1185
|
+
)
|
|
1186
|
+
return typeof hit.score === 'number' ? { ...record, score: hit.score } : record
|
|
1187
|
+
}
|
|
1188
|
+
let result
|
|
1189
|
+
if (typeof memory.searchForPanel === 'function') {
|
|
1190
|
+
result = await memory.searchForPanel({ text, scopes: keys, topK })
|
|
1191
|
+
} else if (typeof memory.search === 'function') {
|
|
1192
|
+
// 旧 provider 没有面板专用入口:退回通用检索(会写访问计数),向量是否参与
|
|
1193
|
+
// 只能按"有没有向量"来推断。
|
|
1194
|
+
let embedded = 0
|
|
1195
|
+
for (const s of scopes) embedded += s.vectors.size
|
|
1196
|
+
const hits = await memory.search({ text, scopes: keys, topK })
|
|
1197
|
+
result = {
|
|
1198
|
+
hits,
|
|
1199
|
+
mode: embedded > 0 ? 'vector' : 'lexical',
|
|
1200
|
+
...(embedded > 0 ? {} : { reason: 'no-vectors' }),
|
|
1201
|
+
embedded,
|
|
1202
|
+
total: totalRecords,
|
|
1203
|
+
}
|
|
1204
|
+
} else {
|
|
1205
|
+
// 连检索接口都没有:退回 /records?q= 同口径的关键词过滤,面板不至于空转。
|
|
1206
|
+
const lowercase = text.toLowerCase()
|
|
1207
|
+
const hits = []
|
|
1208
|
+
for (const s of scopes) {
|
|
1209
|
+
for (const r of collectScope(s)) {
|
|
1210
|
+
if (r.content.toLowerCase().includes(lowercase)
|
|
1211
|
+
|| r.kind.toLowerCase().includes(lowercase)
|
|
1212
|
+
|| r.tags.some((t) => t.toLowerCase().includes(lowercase))) hits.push({ record: r })
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
result = { hits: hits.slice(0, topK), mode: 'lexical', reason: 'provider-lexical', embedded: 0, total: totalRecords }
|
|
1216
|
+
}
|
|
1217
|
+
writeJson(res, {
|
|
1218
|
+
ok: true,
|
|
1219
|
+
value: {
|
|
1220
|
+
hits: result.hits.slice(0, topK).map(wireHit),
|
|
1221
|
+
mode: result.mode,
|
|
1222
|
+
...(result.reason !== undefined ? { reason: result.reason } : {}),
|
|
1223
|
+
embedded: result.embedded ?? 0,
|
|
1224
|
+
total: result.total ?? totalRecords,
|
|
1225
|
+
},
|
|
1226
|
+
})
|
|
1227
|
+
return
|
|
1228
|
+
}
|
|
1229
|
+
if (method === 'POST' && path === '/update') {
|
|
1230
|
+
const body = await readJsonBody(req)
|
|
1231
|
+
const id = String(body.id ?? '')
|
|
1232
|
+
// 0.23.0:编辑 = 新建一条修正版,旧记录不原地修改。旧 provider 没有
|
|
1233
|
+
// reviseRecord 时才退回原来的原地编辑,避免版本错配直接报错。
|
|
1234
|
+
if (typeof memory.reviseRecord === 'function') {
|
|
1235
|
+
const input = { id }
|
|
1236
|
+
if (body.content !== undefined) input.content = String(body.content)
|
|
1237
|
+
if (body.kind !== undefined) input.kind = String(body.kind)
|
|
1238
|
+
if (body.importance !== undefined) input.importance = Number(body.importance)
|
|
1239
|
+
if (body.tags !== undefined) input.tags = Array.isArray(body.tags) ? body.tags.map(String) : []
|
|
1240
|
+
if (body.triggers !== undefined) input.triggers = Array.isArray(body.triggers) ? body.triggers.map(String) : []
|
|
1241
|
+
if (body.expiredAt === null) input.expiresAt = null
|
|
1242
|
+
else if (typeof body.expiresAt === 'number') input.expiresAt = body.expiresAt
|
|
1243
|
+
else if (typeof body.ttlMs === 'number' && body.ttlMs > 0) input.ttlMs = body.ttlMs
|
|
1244
|
+
const { record, superseded } = await memory.reviseRecord(input)
|
|
1245
|
+
const scopeStore = store.peek(record.scope) ?? { embedPending: new Map(), vectors: new Map() }
|
|
1246
|
+
let supersededBy = null
|
|
1247
|
+
for (const other of scopeStore.records.values()) {
|
|
1248
|
+
if (other.supersedes === record.id) { supersededBy = other.id; break }
|
|
1249
|
+
}
|
|
1250
|
+
console.log(`[dsh-memory-panel] 修正记忆 ${superseded} -> ${record.id}`)
|
|
1251
|
+
writeJson(res, { ok: true, value: { record: wireRecord(record, scopeStore, supersededBy), superseded } })
|
|
1252
|
+
return
|
|
1253
|
+
}
|
|
1254
|
+
let target = null
|
|
1255
|
+
for (const s of store.allScopes()) {
|
|
1256
|
+
const rec = s.records.get(id)
|
|
1257
|
+
if (rec) { target = { s, rec }; break }
|
|
1258
|
+
}
|
|
1259
|
+
if (!target) throw new ApiError(404, 'RECORD_NOT_FOUND', `no record ${id}`)
|
|
1260
|
+
const { s, rec } = target
|
|
1261
|
+
let reindex = false
|
|
1262
|
+
if (body.content !== undefined) {
|
|
1263
|
+
const content = String(body.content)
|
|
1264
|
+
if (!content.trim()) throw new ApiError(400, 'CONTENT_EMPTY', 'content 不能为空')
|
|
1265
|
+
if (content !== rec.content) {
|
|
1266
|
+
rec.content = content
|
|
1267
|
+
// 旧向量作废:内存 + 磁盘一起丢掉(vectorsDirty),再排队重建。
|
|
1268
|
+
// 只删内存不标 dirty 的话,重启后 load 会看到旧向量、把它当成"已嵌入"。
|
|
1269
|
+
s.vectors.delete(id)
|
|
1270
|
+
s.vectorsDirty = true
|
|
1271
|
+
s.embedPending.add(id)
|
|
1272
|
+
reindex = true
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
if (body.kind !== undefined) rec.kind = String(body.kind)
|
|
1276
|
+
if (body.importance !== undefined) rec.importance = Math.min(1, Math.max(0, Number(body.importance) || 0))
|
|
1277
|
+
if (body.tags !== undefined) rec.tags = Array.isArray(body.tags) ? body.tags.map(String) : []
|
|
1278
|
+
if (body.triggers !== undefined) rec.triggers = Array.isArray(body.triggers) ? body.triggers.map(String) : []
|
|
1279
|
+
if (body.supersededBy !== undefined) rec.supersedes = body.supersededBy === null ? undefined : String(body.supersededBy)
|
|
1280
|
+
// 过期时间:null 清除;expiresAt 绝对时间优先;ttlMs 相对当前时间。
|
|
1281
|
+
if (body.expiredAt === null) delete rec.expiredAt
|
|
1282
|
+
else if (typeof body.expiresAt === 'number') rec.expiredAt = body.expiresAt
|
|
1283
|
+
else if (typeof body.ttlMs === 'number' && body.ttlMs > 0) rec.expiredAt = Date.now() + body.ttlMs
|
|
1284
|
+
rec.updatedAt = Date.now()
|
|
1285
|
+
// 改动本身要进增量(flush 只落增量,不再整份快照覆盖);向量作废靠 vectorsDirty。
|
|
1286
|
+
s.insert(rec)
|
|
1287
|
+
store.scheduleFlush()
|
|
1288
|
+
// 立即重建向量(不等 60s 的定时回填);失败就留在 pending 里由重试兜底。
|
|
1289
|
+
if (reindex && typeof memory.reindexRecord === 'function') {
|
|
1290
|
+
void memory.reindexRecord(rec.scope, id).catch(() => {})
|
|
1291
|
+
}
|
|
1292
|
+
writeJson(res, { ok: true, value: { record: wireRecord(rec, s) } })
|
|
1293
|
+
return
|
|
1294
|
+
}
|
|
1295
|
+
if (method === 'POST' && path === '/delete') {
|
|
1296
|
+
const body = await readJsonBody(req)
|
|
1297
|
+
let removed = false
|
|
1298
|
+
for (const s of store.allScopes()) {
|
|
1299
|
+
if (s.records.has(String(body.id))) { removed = s.remove(String(body.id)); break }
|
|
1300
|
+
}
|
|
1301
|
+
if (!removed) throw new ApiError(404, 'RECORD_NOT_FOUND', `no record ${body.id}`)
|
|
1302
|
+
store.scheduleFlush()
|
|
1303
|
+
writeJson(res, { ok: true, value: { removed: 1 } })
|
|
1304
|
+
return
|
|
1305
|
+
}
|
|
1306
|
+
throw new ApiError(404, 'not_found', `unknown endpoint ${method} ${path}`)
|
|
1307
|
+
} catch (error) {
|
|
1308
|
+
ctx?.logger?.warn?.(error instanceof Error ? error : new Error(String(error)))
|
|
1309
|
+
writeError(res, error)
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
export const name = 'dsh-memory-panel'
|
|
1314
|
+
/** 路由处理器(导出供测试直接调用:围栏、规范化、peek 行为都在这里)。 */
|
|
1315
|
+
export { handle as handleRequest }
|
|
1316
|
+
export function apply(ctx, config = {}) {
|
|
1317
|
+
const routePath = String(config.route || '/memory/api').replace(/\/$/, '')
|
|
1318
|
+
try {
|
|
1319
|
+
// 动态注入(cordis ctx.inject):webServer 已就绪则立即回调,否则等它出现,
|
|
1320
|
+
// 不阻塞 entry 激活,也绝不让缺服务变成 fiber FAILED(dsh-client-modules 同款)。
|
|
1321
|
+
ctx.inject(['webServer'], (svcCtx) => {
|
|
1322
|
+
try {
|
|
1323
|
+
const webServer = svcCtx.get('webServer')
|
|
1324
|
+
if (!webServer || typeof webServer.register !== 'function') {
|
|
1325
|
+
console.log('[dsh-memory-panel] webServer 不可用,面板 API 不注册(记忆工具不受影响)')
|
|
1326
|
+
return
|
|
1327
|
+
}
|
|
1328
|
+
webServer.register({
|
|
1329
|
+
kind: 'prefix',
|
|
1330
|
+
path: routePath,
|
|
1331
|
+
// returning the promise is ignored by the http server but makes the
|
|
1332
|
+
// handler awaitable in tests/host-sim
|
|
1333
|
+
handler: (req, res) => Promise.resolve(handle(ctx, routePath, req, res))
|
|
1334
|
+
.catch((error) => writeError(res, error)),
|
|
1335
|
+
})
|
|
1336
|
+
console.log(`[dsh-memory-panel] 路由已注册 ${routePath}`)
|
|
1337
|
+
} catch (error) {
|
|
1338
|
+
console.log('[dsh-memory-panel] 路由注册失败(可能已存在,复用):', error?.message)
|
|
1339
|
+
}
|
|
1340
|
+
})
|
|
1341
|
+
} catch (error) {
|
|
1342
|
+
// 铁律:面板绝不允许把异常抛回 cordis(desktop fail-loud 会拖垮整个启动)
|
|
1343
|
+
console.error('[dsh-memory-panel] apply 意外失败(已吞掉,不影响启动):', error?.message)
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1285
1346
|
|
|
1286
1347
|
|
|
1287
1348
|
//# sourceURL=source/memory-panel/lib/index.js
|