dsh-agent-soul 0.5.0 → 0.5.2
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/README.md +605 -495
- package/lib/api.js +1232 -902
- package/lib/archive.js +87 -0
- package/lib/attest.js +173 -0
- package/lib/client/app.js +2 -0
- package/lib/client/diary-tab.js +132 -21
- package/lib/client/memory-tab.js +239 -173
- package/lib/client/mood-tab.js +276 -256
- package/lib/client/notes-tab.js +172 -0
- package/lib/client/overview-tab.js +10 -1
- package/lib/client/settings-tab.js +11 -0
- package/lib/client.js +844 -451
- package/lib/diary-pick.js +157 -0
- package/lib/diary-tool.js +192 -0
- package/lib/diary.js +1749 -1377
- package/lib/env.js +77 -1
- package/lib/extract.js +152 -12
- package/lib/index.js +1220 -869
- package/lib/memory.js +165 -37
- package/lib/mood.js +992 -981
- package/lib/notes.js +549 -0
- package/lib/paths.js +47 -5
- package/lib/refine.js +18 -3
- package/lib/session-title.js +189 -0
- package/lib/store.js +78 -15
- package/lib/tone.js +179 -160
- package/lib/tool.js +157 -0
- package/package.json +10 -3
- package/tools/build-client.mjs +1 -0
- package/tools/eval-recall.mjs +89 -0
- package/tools/sync.mjs +27 -8
package/lib/api.js
CHANGED
|
@@ -1,902 +1,1232 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* api.js —— 设置页用的同源 HTTP 接口。
|
|
3
|
-
*
|
|
4
|
-
* 为什么走同源 HTTP 而不是 RPC:
|
|
5
|
-
* 浏览器半侧只要能 fetch 就能用,不需要理解宿主的 RPC 协议;
|
|
6
|
-
* 而且插件被卸载/重装时,页面顶多拿到 404,不会把宿主会话搞坏。
|
|
7
|
-
*
|
|
8
|
-
* 路由(前缀 /api/soul):
|
|
9
|
-
* GET /state 配置 + 人格来源 + 记忆统计 + 目的摘要 + 心情摘要(页面首屏一次拿全)
|
|
10
|
-
* POST /config 保存配置
|
|
11
|
-
* GET /persona 读人格文件
|
|
12
|
-
* POST /persona 写人格文件
|
|
13
|
-
* GET /memory 列记忆(?scope=global|project&cwd=...&query=...)
|
|
14
|
-
* POST /memory 增 / 改 / 删一条记忆
|
|
15
|
-
* POST /maintain 手动跑一次衰减与压缩
|
|
16
|
-
* GET /mood 心情全量(值 + 七情 + 时间线)
|
|
17
|
-
* POST /mood/reset 重置心情
|
|
18
|
-
* POST /mood/decay 手动跑一次时间衰减
|
|
19
|
-
* POST /diary 手动触发日记({ date?: "YYYY-MM-DD", note?: "备注" })
|
|
20
|
-
* GET /diary/list 日记列表(最近 N 天,公开日记带预览,私密只报存在性)
|
|
21
|
-
* GET /diary/read 读某一天的日记(公开全文,私密只报存在性)
|
|
22
|
-
* GET /diary/private 读私密正文(2026-10-31;仅回环 + diaryPrivateVisible=true)
|
|
23
|
-
*
|
|
24
|
-
* POST /diary/
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
30
|
-
import {
|
|
31
|
-
import {
|
|
32
|
-
import {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
import {
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
import {
|
|
68
|
-
import {
|
|
69
|
-
import {
|
|
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
|
-
|
|
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
|
-
if (
|
|
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
|
-
function
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
if (
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
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
|
-
const
|
|
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
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
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
|
-
const
|
|
343
|
-
const
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
return json(res,
|
|
553
|
-
}
|
|
554
|
-
const
|
|
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
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
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
|
-
if (route === '/
|
|
807
|
-
const
|
|
808
|
-
|
|
809
|
-
const
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
return json(res, 200, {
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
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
|
-
|
|
875
|
-
|
|
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
|
-
|
|
1
|
+
/**
|
|
2
|
+
* api.js —— 设置页用的同源 HTTP 接口。
|
|
3
|
+
*
|
|
4
|
+
* 为什么走同源 HTTP 而不是 RPC:
|
|
5
|
+
* 浏览器半侧只要能 fetch 就能用,不需要理解宿主的 RPC 协议;
|
|
6
|
+
* 而且插件被卸载/重装时,页面顶多拿到 404,不会把宿主会话搞坏。
|
|
7
|
+
*
|
|
8
|
+
* 路由(前缀 /api/soul):
|
|
9
|
+
* GET /state 配置 + 人格来源 + 记忆统计 + 目的摘要 + 心情摘要(页面首屏一次拿全)
|
|
10
|
+
* POST /config 保存配置
|
|
11
|
+
* GET /persona 读人格文件
|
|
12
|
+
* POST /persona 写人格文件
|
|
13
|
+
* GET /memory 列记忆(?scope=global|project&cwd=...&query=...)
|
|
14
|
+
* POST /memory 增 / 改 / 删一条记忆
|
|
15
|
+
* POST /maintain 手动跑一次衰减与压缩
|
|
16
|
+
* GET /mood 心情全量(值 + 七情 + 时间线)
|
|
17
|
+
* POST /mood/reset 重置心情
|
|
18
|
+
* POST /mood/decay 手动跑一次时间衰减
|
|
19
|
+
* POST /diary 手动触发日记({ date?: "YYYY-MM-DD", note?: "备注" })
|
|
20
|
+
* GET /diary/list 日记列表(最近 N 天,公开日记带预览,私密只报存在性)
|
|
21
|
+
* GET /diary/read 读某一天的日记(公开全文,私密只报存在性)
|
|
22
|
+
* GET /diary/private 读私密正文(2026-10-31;仅回环 + diaryPrivateVisible=true)
|
|
23
|
+
* GET /diary/sessions 可选会话列表(设置页的日记会话下拉用,最多 50 条)
|
|
24
|
+
* POST /diary/bind 把会话绑定成日记会话({ sessionId? },缺省取当前会话)
|
|
25
|
+
* POST /diary/unbind 清除日记会话绑定
|
|
26
|
+
*/
|
|
27
|
+
import { spawn } from 'node:child_process'
|
|
28
|
+
import { readdirSync, readFileSync, statSync } from 'node:fs'
|
|
29
|
+
import { dirname, join } from 'node:path'
|
|
30
|
+
import { fileURLToPath } from 'node:url'
|
|
31
|
+
import { archivedSessionIds } from './archive.js'
|
|
32
|
+
import { note, serviceOf } from './env.js'
|
|
33
|
+
import { composePersona, localPersonaPath, MAX_INJECT_CHARS, resolveSources, storedProjectPersonaPath } from './persona.js'
|
|
34
|
+
import {
|
|
35
|
+
archivePath,
|
|
36
|
+
atomicWrite,
|
|
37
|
+
exists,
|
|
38
|
+
globalPersonaPath,
|
|
39
|
+
normalizePathKey,
|
|
40
|
+
readText,
|
|
41
|
+
slugFor,
|
|
42
|
+
diaryPublicDir,
|
|
43
|
+
diaryPrivateDir,
|
|
44
|
+
diaryPublicPath,
|
|
45
|
+
diaryPrivatePath
|
|
46
|
+
} from './paths.js'
|
|
47
|
+
import { hostProbeState } from './host.js'
|
|
48
|
+
import { deleteSecret, saveSecret, secretInfo } from './secrets.js'
|
|
49
|
+
import {
|
|
50
|
+
// 2026-11-04:/config 的键白名单要用它(只允许写入声明过的配置项)
|
|
51
|
+
DEFAULT_CONFIG,
|
|
52
|
+
globalCard,
|
|
53
|
+
projectCard,
|
|
54
|
+
loadConfig,
|
|
55
|
+
maintain,
|
|
56
|
+
memoryHealth,
|
|
57
|
+
memoryStats,
|
|
58
|
+
saveConfig,
|
|
59
|
+
purposeState,
|
|
60
|
+
savePurposeState,
|
|
61
|
+
saveGlobalCard,
|
|
62
|
+
saveProjectCard,
|
|
63
|
+
moodState,
|
|
64
|
+
resetMood,
|
|
65
|
+
decayMoodFor
|
|
66
|
+
} from './store.js'
|
|
67
|
+
import { todayKey, yesterdayKey, runDiaryOnce } from './diary.js'
|
|
68
|
+
import { displayDimPercents, displayDims, moodFace, moodLabel, topDims, TIMELINE_CAP } from './mood.js'
|
|
69
|
+
import { forgetRecord, makeArchiver, setPinned, addRecord } from './memory.js'
|
|
70
|
+
import { closeGoal, openGoals, summarize } from './purpose.js'
|
|
71
|
+
import { MEMORY_FACTS } from './facts.js'
|
|
72
|
+
import { decodeSessionDirName, listWorkspaces, registerProject, sessionsRoot } from './registry.js'
|
|
73
|
+
import { EMPTY_SESSION_TITLE, titleForSession } from './session-title.js'
|
|
74
|
+
import { deleteNote, listNotes, readNote, renameNote, writeNote } from './notes.js'
|
|
75
|
+
import { getFallbackCwd } from './tool.js'
|
|
76
|
+
import { attestationState } from './attest.js'
|
|
77
|
+
|
|
78
|
+
export const API_PREFIX = '/api/soul'
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 静态资源前缀:心情那五张表情图从这里出去(/dsh-agent-soul/face-ok.png)。
|
|
82
|
+
* 跟 dsh-feiyu-mood 的老习惯一致,也避开宿主自己的路径。
|
|
83
|
+
*/
|
|
84
|
+
export const ASSET_PREFIX = '/dsh-agent-soul'
|
|
85
|
+
|
|
86
|
+
/** 只认这五张图 —— 白名单挡住 ../ 之类的路径穿越,别让外面翻目录。 */
|
|
87
|
+
const FACE_ASSETS = new Set([
|
|
88
|
+
'face-great.png',
|
|
89
|
+
'face-good.png',
|
|
90
|
+
'face-ok.png',
|
|
91
|
+
'face-worry.png',
|
|
92
|
+
'face-sad.png'
|
|
93
|
+
])
|
|
94
|
+
|
|
95
|
+
/** 插件自己的 assets 目录(跟 lib/ 平级;npm 装完也在那儿)。 */
|
|
96
|
+
const ASSETS_DIR = fileURLToPath(new URL('../assets/', import.meta.url))
|
|
97
|
+
|
|
98
|
+
/** 请求体上限:设置页只传配置和短文本,1MB 足够,挡住手滑。 */
|
|
99
|
+
const MAX_BODY = 1024 * 1024
|
|
100
|
+
|
|
101
|
+
function readBody(req, limit = MAX_BODY) {
|
|
102
|
+
return new Promise((resolve, reject) => {
|
|
103
|
+
const chunks = []
|
|
104
|
+
let size = 0
|
|
105
|
+
req.on('data', (chunk) => {
|
|
106
|
+
size += chunk.length
|
|
107
|
+
if (size > limit) {
|
|
108
|
+
reject(new Error('请求体太大'))
|
|
109
|
+
req.destroy()
|
|
110
|
+
return
|
|
111
|
+
}
|
|
112
|
+
chunks.push(chunk)
|
|
113
|
+
})
|
|
114
|
+
req.on('end', () => {
|
|
115
|
+
try {
|
|
116
|
+
const text = Buffer.concat(chunks).toString('utf8')
|
|
117
|
+
resolve(text === '' ? {} : JSON.parse(text))
|
|
118
|
+
} catch (error) {
|
|
119
|
+
reject(new Error(`JSON 解析失败:${error instanceof Error ? error.message : error}`))
|
|
120
|
+
}
|
|
121
|
+
})
|
|
122
|
+
req.on('error', reject)
|
|
123
|
+
})
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const json = (res, code, payload) => {
|
|
127
|
+
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' })
|
|
128
|
+
res.end(JSON.stringify(payload))
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 请求是不是从本机回环地址发来的(2026-10-31)。
|
|
133
|
+
*
|
|
134
|
+
* 为什么单独判一次:私密日记正文默认永不出服务器。开了 diaryPrivateVisible
|
|
135
|
+
* 也只给「这台机器上的自己」看 —— 远程访问(局域网 / 反代)拿到的应当仍是 403。
|
|
136
|
+
* remoteAddress 的三种写法都要认:IPv4 直连、IPv6 回环、IPv4-mapped IPv6。
|
|
137
|
+
*/
|
|
138
|
+
export function isLoopbackRequest(req) {
|
|
139
|
+
const remote = String(req?.socket?.remoteAddress ?? '')
|
|
140
|
+
return remote === '127.0.0.1' || remote === '::1' || remote === '::ffff:127.0.0.1'
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* 是否放行这次接口请求(2026-11-04 修 ⑤,纯函数便于测试)。
|
|
145
|
+
*
|
|
146
|
+
* 原来的权限模型是**反的**:最敏感的私密日记(/diary/private)做了回环校验,
|
|
147
|
+
* 而「改写注入内容的人格」「覆盖笔记」「弹系统文件对话框」这些更危险的动作,
|
|
148
|
+
* 只要请求不带 Origin 就一律放行 —— 本机任何进程(脚本、别的应用、浏览器扩展)
|
|
149
|
+
* 都能直接 POST 过来。
|
|
150
|
+
*
|
|
151
|
+
* 现在统一:只认本机回环。设置页本来就是从 127.0.0.1 访问的,不受影响。
|
|
152
|
+
*
|
|
153
|
+
* 留 `apiLoopbackOnly: false` 这一个逃生口:万一某些宿主的 webServer 走的是
|
|
154
|
+
* 转发/代理、remoteAddress 不是回环地址,用户能改配置自救,而不是被锁在门外
|
|
155
|
+
* 又找不到原因(被拒的请求会打日志,含真实 remoteAddress)。
|
|
156
|
+
*/
|
|
157
|
+
export function shouldAllowApiRequest(req, config) {
|
|
158
|
+
if (config !== null && config !== undefined && config.apiLoopbackOnly === false) return true
|
|
159
|
+
return isLoopbackRequest(req)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* 私密日记的访问闸门 + 读取(2026-10-31,纯函数便于测试)。
|
|
164
|
+
*
|
|
165
|
+
* 顺序不能换:先判回环,再判开关,最后才读文件 —— 开关关着时连「文件在不在」
|
|
166
|
+
* 之外的任何内容都不回。鉴权沿用 /api/soul 全局那道 Origin 跨源检查(POST /diary
|
|
167
|
+
* 用的也是它),这里再加一层回环限制,是私密内容的第二道锁。
|
|
168
|
+
*
|
|
169
|
+
* @returns {{ status: number, payload: object }}
|
|
170
|
+
*/
|
|
171
|
+
export function privateDiaryView(req, config) {
|
|
172
|
+
if (!isLoopbackRequest(req)) {
|
|
173
|
+
return { status: 403, payload: { ok: false, error: '私密日记只允许本机回环请求' } }
|
|
174
|
+
}
|
|
175
|
+
if (config === null || config === undefined || config.diaryPrivateVisible !== true) {
|
|
176
|
+
return { status: 403, payload: { ok: false, error: '私密日记查看未开启(diaryPrivateVisible=false)' } }
|
|
177
|
+
}
|
|
178
|
+
let dateStr = ''
|
|
179
|
+
try {
|
|
180
|
+
dateStr = String(new URL(req?.url ?? '/', 'http://127.0.0.1').searchParams.get('date') ?? '').trim()
|
|
181
|
+
} catch {
|
|
182
|
+
dateStr = ''
|
|
183
|
+
}
|
|
184
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
|
|
185
|
+
return { status: 400, payload: { ok: false, error: '缺少或非法的 date 参数(YYYY-MM-DD)' } }
|
|
186
|
+
}
|
|
187
|
+
const file = diaryPrivatePath(dateStr)
|
|
188
|
+
const hasPrivate = exists(file)
|
|
189
|
+
return {
|
|
190
|
+
status: 200,
|
|
191
|
+
payload: { ok: true, date: dateStr, hasPrivate, content: hasPrivate ? readText(file) : '' }
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* 会话服务里最近更新的会话 id(拿不到返回空串)。
|
|
197
|
+
*
|
|
198
|
+
* 2026-10-31:这台 DSH 的设置页 renderSlot('settings.section') 只传 { close },
|
|
199
|
+
* 前端拿不到当前会话 id。点「把当前会话指定为日记会话」时请求里就没 id,
|
|
200
|
+
* 这里按 updatedAt 取「最近动过的那个」当当前会话 —— 只用于【手动绑定这一步】;
|
|
201
|
+
* 投递侧只认配置里的 id,绝不回退到这里。
|
|
202
|
+
*/
|
|
203
|
+
function currentSessionIdOf(ctx) {
|
|
204
|
+
const sessions = serviceOf(ctx, 'sessions')
|
|
205
|
+
if (sessions === undefined || sessions === null || typeof sessions.list !== 'function') return ''
|
|
206
|
+
try {
|
|
207
|
+
const list = sessions.list()
|
|
208
|
+
if (!Array.isArray(list)) return ''
|
|
209
|
+
let best = null
|
|
210
|
+
for (const session of list) {
|
|
211
|
+
const id = String(session?.header?.id ?? session?.id ?? '')
|
|
212
|
+
if (id === '') continue
|
|
213
|
+
const stamp = String(session?.header?.updatedAt ?? session?.header?.createdAt ?? session?.updatedAt ?? session?.createdAt ?? '')
|
|
214
|
+
if (best === null || stamp > best.stamp) best = { id, stamp }
|
|
215
|
+
}
|
|
216
|
+
return best === null ? '' : best.id
|
|
217
|
+
} catch {
|
|
218
|
+
return ''
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* 日记设置页的会话候选(2026-11-04)。
|
|
224
|
+
*
|
|
225
|
+
* 主来源是 sessions 服务(只含活着的会话,但标题最准);拿不到或一条都没有时,
|
|
226
|
+
* 扫 sessionsRoot() 兜底 —— 至少让下拉里有 id 可选。任何一步失败都只记日志,
|
|
227
|
+
* 绝不把异常抛给路由(接口约定:失败也返回 200 + 空数组)。
|
|
228
|
+
*
|
|
229
|
+
* 2026-11-04:两个来源都要滤掉归档会话。扫盘只认目录、完全不认归档;sessions
|
|
230
|
+
* 服务也可能把归档的列出来。归档集合读不到时 archivedSessionIds() 返回空集合
|
|
231
|
+
* (等于不过滤)并记一行日志,绝不因此让下拉变成空的。
|
|
232
|
+
*
|
|
233
|
+
* 2026-11-04(第二次改):标题不再直接信 header —— 会话标题落在日志的
|
|
234
|
+
* `session/title` 事件里(header.title 常常是 id 或空)。优先级改为:
|
|
235
|
+
* sessionTitle 服务 → 日志里的标题(见 lib/session-title.js)→ header.title
|
|
236
|
+
* → (空会话,没有消息)
|
|
237
|
+
* 读日志有磁盘 IO,只对最终入选的 ≤50 条做;每条单独 try/catch,一条坏日志
|
|
238
|
+
* 只丢它自己的标题,不拖垮整个列表。
|
|
239
|
+
*
|
|
240
|
+
* @returns {Array<{id:string,title:string,cwd:string,updatedAt:string}>}
|
|
241
|
+
*/
|
|
242
|
+
function listDiarySessions(ctx) {
|
|
243
|
+
const byId = new Map()
|
|
244
|
+
// 只取一次,两个来源共用;取不到时是空集合,put 里的判断自然全部放行
|
|
245
|
+
const archived = archivedSessionIds()
|
|
246
|
+
|
|
247
|
+
const put = (raw) => {
|
|
248
|
+
const id = String(raw?.id ?? '').trim()
|
|
249
|
+
if (id === '') return
|
|
250
|
+
// 归档会话不进下拉(用户收起来的,不该被绑成日记会话)
|
|
251
|
+
if (archived.has(id)) return
|
|
252
|
+
const title = String(raw?.title ?? '').trim()
|
|
253
|
+
const headerTitle = String(raw?.headerTitle ?? '').trim()
|
|
254
|
+
const cwd = String(raw?.cwd ?? '')
|
|
255
|
+
const updatedAt = String(raw?.updatedAt ?? '')
|
|
256
|
+
const old = byId.get(id)
|
|
257
|
+
if (old === undefined) {
|
|
258
|
+
byId.set(id, { id, title, headerTitle, cwd, updatedAt })
|
|
259
|
+
return
|
|
260
|
+
}
|
|
261
|
+
// 同一个会话可能来自多个来源:标题留非空的,cwd 留非空的,时间留新的
|
|
262
|
+
if (old.title === '' && title !== '') old.title = title
|
|
263
|
+
if (old.headerTitle === '' && headerTitle !== '') old.headerTitle = headerTitle
|
|
264
|
+
if (old.cwd === '' && cwd !== '') old.cwd = cwd
|
|
265
|
+
if (updatedAt > old.updatedAt) old.updatedAt = updatedAt
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
try {
|
|
269
|
+
const sessions = serviceOf(ctx, 'sessions')
|
|
270
|
+
if (sessions !== undefined && sessions !== null && typeof sessions.list === 'function') {
|
|
271
|
+
// 标题在 sessionTitle 服务里;它不一定会出现在 inject 里,每次访问都兜住
|
|
272
|
+
let titleSvc
|
|
273
|
+
try {
|
|
274
|
+
titleSvc = serviceOf(ctx, 'sessionTitle')
|
|
275
|
+
} catch (error) {
|
|
276
|
+
note('api', `日记会话列表:sessionTitle 不可用(${error instanceof Error ? error.message : error})`)
|
|
277
|
+
titleSvc = undefined
|
|
278
|
+
}
|
|
279
|
+
for (const session of sessions.list() ?? []) {
|
|
280
|
+
const header = session?.header ?? {}
|
|
281
|
+
const id = String(header.id ?? session?.id ?? '').trim()
|
|
282
|
+
if (id === '') continue
|
|
283
|
+
let title = ''
|
|
284
|
+
if (titleSvc !== undefined && titleSvc !== null && typeof titleSvc.get === 'function') {
|
|
285
|
+
try {
|
|
286
|
+
const folded = titleSvc.get(session)
|
|
287
|
+
if (typeof folded === 'string') title = folded
|
|
288
|
+
} catch (error) {
|
|
289
|
+
note('api', `日记会话列表:读标题失败 ${id}(${error instanceof Error ? error.message : error})`)
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
put({
|
|
293
|
+
id,
|
|
294
|
+
title,
|
|
295
|
+
headerTitle: String(session?.displayTitle ?? header.displayTitle ?? session?.title ?? header.title ?? ''),
|
|
296
|
+
cwd: String(header.cwd ?? session?.cwd ?? ''),
|
|
297
|
+
updatedAt: String(header.updatedAt ?? header.createdAt ?? session?.updatedAt ?? session?.createdAt ?? '')
|
|
298
|
+
})
|
|
299
|
+
}
|
|
300
|
+
} else {
|
|
301
|
+
note('api', '日记会话列表:sessions 服务不可用,改用扫盘兜底')
|
|
302
|
+
}
|
|
303
|
+
} catch (error) {
|
|
304
|
+
note('api', `日记会话列表:sessions.list 失败(${error instanceof Error ? error.message : error})`)
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// 服务挂了 / 一个活会话都没有时扫盘。只扫两层:<sessions>/<编码后的 cwd>/<会话 id>/
|
|
308
|
+
if (byId.size === 0) {
|
|
309
|
+
let cwdDirs = []
|
|
310
|
+
try {
|
|
311
|
+
cwdDirs = readdirSync(sessionsRoot(), { withFileTypes: true })
|
|
312
|
+
} catch (error) {
|
|
313
|
+
note('api', `日记会话列表:扫盘失败 ${sessionsRoot()}(${error instanceof Error ? error.message : error})`)
|
|
314
|
+
}
|
|
315
|
+
for (const cwdDir of cwdDirs) {
|
|
316
|
+
if (cwdDir.isDirectory() !== true) continue
|
|
317
|
+
const cwd = decodeSessionDirName(cwdDir.name)
|
|
318
|
+
let sessionDirs = []
|
|
319
|
+
try {
|
|
320
|
+
sessionDirs = readdirSync(join(sessionsRoot(), cwdDir.name), { withFileTypes: true })
|
|
321
|
+
} catch (error) {
|
|
322
|
+
note('api', `日记会话列表:跳过 ${cwdDir.name}(${error instanceof Error ? error.message : error})`)
|
|
323
|
+
continue
|
|
324
|
+
}
|
|
325
|
+
for (const sessionDir of sessionDirs) {
|
|
326
|
+
if (sessionDir.isDirectory() !== true) continue
|
|
327
|
+
let updatedAt = ''
|
|
328
|
+
try {
|
|
329
|
+
updatedAt = statSync(join(sessionsRoot(), cwdDir.name, sessionDir.name)).mtime.toISOString()
|
|
330
|
+
} catch {
|
|
331
|
+
/* 读不到时间就留空 */
|
|
332
|
+
}
|
|
333
|
+
put({ id: sessionDir.name, title: '', cwd, updatedAt })
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const picked = [...byId.values()]
|
|
339
|
+
.sort((a, b) => {
|
|
340
|
+
const ta = Date.parse(a.updatedAt)
|
|
341
|
+
const tb = Date.parse(b.updatedAt)
|
|
342
|
+
const va = Number.isFinite(ta) ? ta : 0
|
|
343
|
+
const vb = Number.isFinite(tb) ? tb : 0
|
|
344
|
+
if (va !== vb) return vb - va
|
|
345
|
+
return a.id.localeCompare(b.id)
|
|
346
|
+
})
|
|
347
|
+
.slice(0, 50)
|
|
348
|
+
|
|
349
|
+
// 只有这里开始读磁盘,而且只读最终入选的这 ≤50 条。
|
|
350
|
+
// 每条独立 try/catch:一条日志坏掉只丢它自己的标题,列表照常返回。
|
|
351
|
+
for (const item of picked) {
|
|
352
|
+
if (item.title === '') {
|
|
353
|
+
try {
|
|
354
|
+
const fromLog = titleForSession(item.id)
|
|
355
|
+
if (typeof fromLog === 'string' && fromLog !== '') item.title = fromLog
|
|
356
|
+
} catch (error) {
|
|
357
|
+
note('api', `日记会话列表:读日志标题失败 ${item.id}(${error instanceof Error ? error.message : error})`)
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
if (item.title === '') item.title = item.headerTitle
|
|
361
|
+
if (item.title === '') item.title = EMPTY_SESSION_TITLE
|
|
362
|
+
// headerTitle 只是中间产物,不往外带
|
|
363
|
+
delete item.headerTitle
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
return picked
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* 日记本用了几天(绑定当天算第 1 天;绑定时间缺失时返回 0,页面据此不显示)。
|
|
371
|
+
* 按 24 小时向上取整:用了 1 小时算 1 天,满 15×24 小时显示 15 天。
|
|
372
|
+
*/
|
|
373
|
+
function diarySessionDays(bornAt, now = Date.now()) {
|
|
374
|
+
const born = Number(bornAt)
|
|
375
|
+
if (!Number.isFinite(born) || born <= 0) return 0
|
|
376
|
+
const elapsed = Math.max(0, Number(now) - born)
|
|
377
|
+
return Math.max(1, Math.ceil(elapsed / (24 * 60 * 60 * 1000)))
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* 弹一个系统「选择文件夹」对话框,返回选中的目录(取消返回空串)。
|
|
382
|
+
*
|
|
383
|
+
* 为什么要它:设置页里「项目人格」原本只能依赖宿主传 cwd,拿不到就整块灰死。
|
|
384
|
+
* 浏览器拿不到原生目录选择器,所以这一步由宿主(Node 侧)代劳。
|
|
385
|
+
* 三条平台分支各用系统自带工具,没有额外依赖。
|
|
386
|
+
*/
|
|
387
|
+
function pickFolder() {
|
|
388
|
+
return new Promise((resolve, reject) => {
|
|
389
|
+
const plat = process.platform
|
|
390
|
+
let cmd
|
|
391
|
+
let args
|
|
392
|
+
if (plat === 'win32') {
|
|
393
|
+
cmd = 'powershell'
|
|
394
|
+
args = [
|
|
395
|
+
'-NoProfile',
|
|
396
|
+
'-STA',
|
|
397
|
+
'-Command',
|
|
398
|
+
// ① [Console]::OutputEncoding 必须先设成 UTF-8:否则中文路径(例 D:\某个中文目录)会以
|
|
399
|
+
// 控制台代码页(CP936)吐出来,Node 侧按 UTF-8 解码就变成乱码。
|
|
400
|
+
// ② -STA 是 WinForms 对话框的要求,缺了会直接抛。
|
|
401
|
+
"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Add-Type -AssemblyName System.Windows.Forms | Out-Null; $d = New-Object System.Windows.Forms.FolderBrowserDialog; $d.Description = '选择要用项目人格的工作目录'; $d.ShowNewFolderButton = $true; if ($d.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Out.Write($d.SelectedPath) }",
|
|
402
|
+
]
|
|
403
|
+
} else if (plat === 'darwin') {
|
|
404
|
+
cmd = 'osascript'
|
|
405
|
+
args = ['-e', 'POSIX path of (choose folder with prompt "选择要用项目人格的工作目录")']
|
|
406
|
+
} else {
|
|
407
|
+
cmd = 'zenity'
|
|
408
|
+
args = ['--file-selection', '--directory', '--title=选择要用项目人格的工作目录']
|
|
409
|
+
}
|
|
410
|
+
let child
|
|
411
|
+
try {
|
|
412
|
+
child = spawn(cmd, args, { windowsHide: true })
|
|
413
|
+
} catch (error) {
|
|
414
|
+
reject(error)
|
|
415
|
+
return
|
|
416
|
+
}
|
|
417
|
+
let out = ''
|
|
418
|
+
child.stdout?.on('data', (chunk) => {
|
|
419
|
+
out += String(chunk)
|
|
420
|
+
})
|
|
421
|
+
child.on('error', reject)
|
|
422
|
+
child.on('exit', () => {
|
|
423
|
+
resolve(out.trim())
|
|
424
|
+
})
|
|
425
|
+
})
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* 会话服务里「最近活跃的那个会话」的工作目录(拿不到返回空串)。
|
|
430
|
+
*
|
|
431
|
+
* 设置页弹层是全局的,某些 DSH 版本不给 settings.section 传 sessionId,
|
|
432
|
+
* 于是「当前工作目录」解析成空、面板直接死路。这里退一步:从会话服务里挑一个
|
|
433
|
+
* 最近活跃且有 cwd 的会话兜底(页面会标明这是兜底值)。
|
|
434
|
+
*/
|
|
435
|
+
function recentSessionOf(ctx) {
|
|
436
|
+
const sessions = serviceOf(ctx, 'sessions')
|
|
437
|
+
if (sessions === undefined || sessions === null || typeof sessions.list !== 'function') return ''
|
|
438
|
+
try {
|
|
439
|
+
const list = sessions.list()
|
|
440
|
+
if (!Array.isArray(list)) return ''
|
|
441
|
+
let best = null
|
|
442
|
+
for (const session of list) {
|
|
443
|
+
const cwd = session?.header?.cwd
|
|
444
|
+
if (typeof cwd !== 'string' || cwd === '') continue
|
|
445
|
+
const stamp = String(session?.header?.updatedAt ?? session?.header?.createdAt ?? session?.updatedAt ?? session?.createdAt ?? '')
|
|
446
|
+
if (best === null || stamp > best.stamp) best = { stamp, cwd }
|
|
447
|
+
}
|
|
448
|
+
return best === null ? '' : best.cwd
|
|
449
|
+
} catch {
|
|
450
|
+
return ''
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* 接口取 cwd 的唯一入口:三级兜底。
|
|
456
|
+
*
|
|
457
|
+
* 2026-10-29 真事故:这套兜底原来**只写在 /state 里**,其它路由各自
|
|
458
|
+
* `query.get('cwd') ?? ''` 就直接用。于是设置页拿不到会话 cwd 时:
|
|
459
|
+
*
|
|
460
|
+
* 概览 /state → 兜底到最近活跃会话 → 心情 80
|
|
461
|
+
* 详情 /mood → 拿到空串 → 落到 mood/global.json → 文件不存在 → 空白 70、七情全 0
|
|
462
|
+
*
|
|
463
|
+
* 同一个页面左边 80 右边 70,而且右边还显示「还没聊出变化」——
|
|
464
|
+
* 看起来像心情功能整个坏了,其实是读了两份不同的文件。
|
|
465
|
+
* 更糟的是 /mood/reset:用空 cwd 会把心情重置到一个从没用过的作用域上,
|
|
466
|
+
* 页面还看不见自己刚才重置的那份。
|
|
467
|
+
*
|
|
468
|
+
* 三级的顺序不能改:页面手选 > 最近活跃会话 > 最近一次注入记下的。
|
|
469
|
+
*/
|
|
470
|
+
function resolveCwd(ctx, query) {
|
|
471
|
+
const direct = String(query?.get?.('cwd') ?? '').trim()
|
|
472
|
+
if (direct !== '') return { cwd: direct, source: 'path' }
|
|
473
|
+
const recent = recentSessionOf(ctx)
|
|
474
|
+
if (recent !== '') return { cwd: recent, source: 'recent' }
|
|
475
|
+
const fallback = getFallbackCwd()
|
|
476
|
+
// 标 fallback 而不是 recent:这两条来源不同(一个是会话服务里捞的,一个是注入时记下的),
|
|
477
|
+
// 排查「设置页到底认了哪个目录」时混在一起会看不出走的哪条
|
|
478
|
+
if (fallback !== '') return { cwd: fallback, source: 'fallback' }
|
|
479
|
+
return { cwd: '', source: 'none' }
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
export function registerApi(ctx) {
|
|
483
|
+
const webServer = serviceOf(ctx, 'webServer')
|
|
484
|
+
if (webServer === undefined || webServer === null || typeof webServer.register !== 'function') {
|
|
485
|
+
note('api', '宿主没有 webServer 服务,设置页接口未注册')
|
|
486
|
+
return undefined
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
const dispose = webServer.register({
|
|
490
|
+
kind: 'prefix',
|
|
491
|
+
path: API_PREFIX,
|
|
492
|
+
handler: async (req, res) => {
|
|
493
|
+
// ---- 跨源防护(CSRF) ----
|
|
494
|
+
// 这套接口没有任何鉴权:POST /persona 能改写人格注入内容,POST /open 能弹 explorer,
|
|
495
|
+
// POST /pick 能弹系统文件选择框。也就是说,你浏览器里随便一个恶意页面
|
|
496
|
+
// fetch('http://127.0.0.1:PORT/api/soul/persona', {method:'POST',...}) 就能改写她的魂。
|
|
497
|
+
//
|
|
498
|
+
// 判据只认「明确是外站」这一种:
|
|
499
|
+
// · 没带 Origin(同源导航、非浏览器客户端)→ 放行
|
|
500
|
+
// · Origin 是 'null'(sandboxed iframe / file:// 宿主)→ 放行,拒了会误伤本地 webview
|
|
501
|
+
// · Origin 是 http(s) 且 host 与本次请求的 Host 对不上 → 拒绝
|
|
502
|
+
// 这样挡掉网页端发起的跨站请求,又不至于把宿主自己锁在门外。
|
|
503
|
+
const origin = req.headers.origin
|
|
504
|
+
if (typeof origin === 'string' && origin !== '' && origin !== 'null') {
|
|
505
|
+
let crossed = false
|
|
506
|
+
try {
|
|
507
|
+
const parsed = new URL(origin)
|
|
508
|
+
const isHttp = parsed.protocol === 'http:' || parsed.protocol === 'https:'
|
|
509
|
+
// 非 http(s) 的来源(file://、app://、chrome-extension:// 等)都是本地宿主自己,
|
|
510
|
+
// 一律放行 —— 拒掉它们会把设置页锁在门外,那是比 CSRF 更糟的故障。
|
|
511
|
+
if (isHttp) {
|
|
512
|
+
const host = String(req.headers.host ?? '')
|
|
513
|
+
const isLocal = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1' || parsed.hostname === '[::1]'
|
|
514
|
+
const samePort = parsed.port === String(host).split(':')[1]
|
|
515
|
+
crossed = !(host !== '' && (parsed.host === host || (isLocal && samePort)))
|
|
516
|
+
}
|
|
517
|
+
} catch {
|
|
518
|
+
crossed = true // Origin 都解析不了,不认
|
|
519
|
+
}
|
|
520
|
+
if (crossed) {
|
|
521
|
+
note('api', `拒绝跨源请求:Origin=${origin} Host=${String(req.headers.host ?? '')}`)
|
|
522
|
+
return json(res, 403, { ok: false, error: '跨源请求被拒绝' })
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
const url = (req.url ?? '').split('?')[0]
|
|
527
|
+
const route = url.slice(API_PREFIX.length) || '/'
|
|
528
|
+
const query = new URLSearchParams((req.url ?? '').split('?')[1] ?? '')
|
|
529
|
+
|
|
530
|
+
// ---- 本机回环校验(2026-11-04 修 ⑤)----
|
|
531
|
+
// 放在 Origin 检查之后、路由分发之前:Origin 那道只挡「网页跨站」,
|
|
532
|
+
// 对「本机另一个进程」完全无效(那种请求通常根本不带 Origin)。
|
|
533
|
+
// 这里补上真正的权限边界 —— 私密日记的闸门也是同一个判据,两处对齐。
|
|
534
|
+
if (!shouldAllowApiRequest(req, loadConfig())) {
|
|
535
|
+
note('api', `拒绝非回环请求:${req.method} ${route} 来自 ${String(req?.socket?.remoteAddress ?? '未知')}`)
|
|
536
|
+
return json(res, 403, { ok: false, error: '只允许本机访问(apiLoopbackOnly=false 可关闭此限制)' })
|
|
537
|
+
}
|
|
538
|
+
try {
|
|
539
|
+
// ---- 装配证词:这一次装配到底带上了 soul 的哪几段(2026-11-02) ----
|
|
540
|
+
// 只读。`observed:false` 的含义很确切:一次装配都没观测到,也就是
|
|
541
|
+
// **观测器自己没跑起来**,而不是「没注入」。这两件事必须分开报,
|
|
542
|
+
// 否则看门狗死了还会显示「一切正常」。
|
|
543
|
+
if (route === '/attestation' && req.method === 'GET') {
|
|
544
|
+
return json(res, 200, { ok: true, ...attestationState() })
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// ---- 人格文件:读 ----
|
|
548
|
+
if (route === '/persona' && req.method === 'GET') {
|
|
549
|
+
const kind = query.get('kind') === 'project' ? 'project' : 'global'
|
|
550
|
+
const cwd = query.get('cwd') ?? ''
|
|
551
|
+
if (kind === 'project' && cwd === '') {
|
|
552
|
+
return json(res, 400, { ok: false, error: '读项目人格要给 cwd' })
|
|
553
|
+
}
|
|
554
|
+
const file = kind === 'project' ? storedProjectPersonaPath(cwd) : globalPersonaPath()
|
|
555
|
+
let updatedAt = null
|
|
556
|
+
try {
|
|
557
|
+
if (exists(file)) updatedAt = statSync(file).mtime.toISOString()
|
|
558
|
+
} catch {
|
|
559
|
+
/* 读不到时间就留空 */
|
|
560
|
+
}
|
|
561
|
+
return json(res, 200, {
|
|
562
|
+
ok: true,
|
|
563
|
+
kind,
|
|
564
|
+
path: file,
|
|
565
|
+
exists: exists(file),
|
|
566
|
+
updatedAt,
|
|
567
|
+
text: readText(file)
|
|
568
|
+
})
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
// ---- 人格文件:写 ----
|
|
572
|
+
if (route === '/persona' && req.method === 'POST') {
|
|
573
|
+
const body = await readBody(req)
|
|
574
|
+
const kind = body?.kind === 'project' ? 'project' : 'global'
|
|
575
|
+
const cwd = String(body?.cwd ?? '')
|
|
576
|
+
const text = String(body?.text ?? '')
|
|
577
|
+
if (kind === 'project' && cwd === '') {
|
|
578
|
+
return json(res, 400, { ok: false, error: '写项目人格要给 cwd' })
|
|
579
|
+
}
|
|
580
|
+
if (text.length > MAX_INJECT_CHARS) {
|
|
581
|
+
return json(res, 400, { ok: false, error: `太长(超过 ${MAX_INJECT_CHARS} 字),后面的内容不会生效` })
|
|
582
|
+
}
|
|
583
|
+
const file = kind === 'project' ? storedProjectPersonaPath(cwd) : globalPersonaPath()
|
|
584
|
+
// 2026-11-04 修 ②:写盘失败必须如实回非 200。
|
|
585
|
+
//
|
|
586
|
+
// 原来的写法是 `atomicWrite(file, text)` 然后无条件 200 { ok: true }:
|
|
587
|
+
// 磁盘满、文件被别的程序占着、目录权限没了的时候,界面照样显示「已保存」,
|
|
588
|
+
// 而下次装配读到的还是旧人格 —— 用户以为改好了,其实一个字都没写进去。
|
|
589
|
+
// 这比报错更糟:报错他会重试,静默成功他不会。
|
|
590
|
+
//
|
|
591
|
+
// atomicWrite 有两种失败:返回 { ok:false },或第一步写 .tmp 就抛。
|
|
592
|
+
// 两种都收成同一条失败路径,回 500(带原因),并留一行 api 日志。
|
|
593
|
+
let written
|
|
594
|
+
try {
|
|
595
|
+
written = atomicWrite(file, text)
|
|
596
|
+
} catch (error) {
|
|
597
|
+
written = { ok: false, error: error instanceof Error ? error.message : String(error) }
|
|
598
|
+
}
|
|
599
|
+
if (written?.ok !== true) {
|
|
600
|
+
const reason = String(written?.error ?? '未知原因')
|
|
601
|
+
note('api', `人格保存失败(${kind}):${reason} → ${file}`)
|
|
602
|
+
// 文案写成「写盘失败:…」而不是「保存失败:…」:设置页那边已经统一加了
|
|
603
|
+
// 「保存失败:」前缀(lib/client/persona-tab.js 的 catch),再带一遍就重复了。
|
|
604
|
+
return json(res, 500, { ok: false, error: `写盘失败:${reason}` })
|
|
605
|
+
}
|
|
606
|
+
note('api', `人格已保存(${kind},${text.length} 字)→ ${file}`)
|
|
607
|
+
return json(res, 200, { ok: true, path: file, chars: text.length })
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
// ---- 在系统文件管理器里选中人格文件 ----
|
|
611
|
+
// 有些人就是想用 VS Code 改,别逼他在浏览器的 textarea 里写 Markdown。
|
|
612
|
+
if (route === '/open' && req.method === 'POST') {
|
|
613
|
+
const body = await readBody(req)
|
|
614
|
+
const kind = body?.kind === 'project' ? 'project' : 'global'
|
|
615
|
+
const cwd = String(body?.cwd ?? '')
|
|
616
|
+
if (kind === 'project' && cwd === '') {
|
|
617
|
+
return json(res, 400, { ok: false, error: '没有工作目录,不知道要打开哪一份' })
|
|
618
|
+
}
|
|
619
|
+
const file = kind === 'project' ? storedProjectPersonaPath(cwd) : globalPersonaPath()
|
|
620
|
+
if (!exists(file)) {
|
|
621
|
+
return json(res, 404, { ok: false, error: '这个文件还不存在 —— 先在编辑器里写点内容并保存,再打开' })
|
|
622
|
+
}
|
|
623
|
+
const platform = process.platform
|
|
624
|
+
const cmd = platform === 'win32' ? 'explorer' : platform === 'darwin' ? 'open' : 'xdg-open'
|
|
625
|
+
// Windows 的 explorer 用 `/select,` 选中文件;其它平台只能打开所在目录
|
|
626
|
+
const args = platform === 'win32' ? ['/select,', file] : [dirname(file)]
|
|
627
|
+
try {
|
|
628
|
+
// detached + stdio ignore:explorer 不会自己退出,不能让它拖住进程
|
|
629
|
+
spawn(cmd, args, { detached: true, stdio: 'ignore' }).unref()
|
|
630
|
+
note('api', `已在文件管理器中打开:${file}`)
|
|
631
|
+
return json(res, 200, { ok: true, path: file })
|
|
632
|
+
} catch (error) {
|
|
633
|
+
return json(res, 500, { ok: false, error: `打开失败:${error instanceof Error ? error.message : error}` })
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// ---- 首屏:一次拿全 ----
|
|
638
|
+
if (route === '/state' && req.method === 'GET') {
|
|
639
|
+
// cwd 三级兜底(学 dsh-agent-md):设置页是全局弹层,某些 DSH 版本
|
|
640
|
+
// 不给 settings.section 传会话 cwd,光靠 query 会整块灰死。
|
|
641
|
+
// ① 页面显式传的(宿主 props 或用户手选) ② 最近活跃的会话 ③ 最近一次注入记下的
|
|
642
|
+
// 三级兜底抽到 resolveCwd 里了 —— 这套逻辑以前只属于本路由,
|
|
643
|
+
// /mood 那边没有,于是概览和详情读到了两份不同的心情文件
|
|
644
|
+
const cwdPick = resolveCwd(ctx, query)
|
|
645
|
+
const cwd = cwdPick.cwd
|
|
646
|
+
const cwdSource = cwdPick.source
|
|
647
|
+
// 设置页每 20 秒轮询一次 /state —— 不能每次都往 projects.json 写一遍:
|
|
648
|
+
// 那会不停刷 lastSeen、改 active、重排顺序,纯属无谓写盘。
|
|
649
|
+
// 只有「这个工作区还没登记过」才补登;切换 active 走 POST /register。
|
|
650
|
+
if (cwd !== '') {
|
|
651
|
+
const key = normalizePathKey(cwd)
|
|
652
|
+
const known = listWorkspaces().some((item) => normalizePathKey(item?.cwd) === key)
|
|
653
|
+
if (!known) registerProject(cwd, { active: true })
|
|
654
|
+
}
|
|
655
|
+
const config = loadConfig()
|
|
656
|
+
const persona = composePersona({ cwd, config })
|
|
657
|
+
const stats = memoryStats(cwd, config)
|
|
658
|
+
const purpose = summarize(purposeState())
|
|
659
|
+
|
|
660
|
+
// 位置标注(2026-10-28):用户要看得见「这一份人格到底对哪个目录生效」。
|
|
661
|
+
// 三层来源各自可能有、可能没有,光给一个路径说不清优先级 ——
|
|
662
|
+
// 尤其是「cwd 里有 AGENT.md」时,它会**盖掉**设置页编辑的这份,
|
|
663
|
+
// 不标出来就会出现「我在设置页改了却没生效」。
|
|
664
|
+
const resolved = resolveSources({ cwd, config })
|
|
665
|
+
const localFile = String(cwd).trim() !== '' ? localPersonaPath(cwd, config.localNames) : null
|
|
666
|
+
const storedFile = String(cwd).trim() !== '' ? storedProjectPersonaPath(cwd) : ''
|
|
667
|
+
const globalFile = globalPersonaPath()
|
|
668
|
+
|
|
669
|
+
return json(res, 200, {
|
|
670
|
+
ok: true,
|
|
671
|
+
config,
|
|
672
|
+
persona: {
|
|
673
|
+
mode: persona.mode,
|
|
674
|
+
sources: persona.sources,
|
|
675
|
+
chars: persona.text.length,
|
|
676
|
+
truncated: persona.truncated,
|
|
677
|
+
preview: persona.text.slice(0, 400)
|
|
678
|
+
},
|
|
679
|
+
workspace: {
|
|
680
|
+
cwd,
|
|
681
|
+
cwdSource,
|
|
682
|
+
slug: String(cwd).trim() !== '' ? slugFor(cwd).slug : '',
|
|
683
|
+
// 三层来源,逐层标出存在与否 —— 页面按这个画优先级
|
|
684
|
+
layers: [
|
|
685
|
+
{
|
|
686
|
+
level: 1,
|
|
687
|
+
name: '项目内 AGENT.md',
|
|
688
|
+
scope: '跟着仓库走,可提交进 git',
|
|
689
|
+
path: localFile === null ? (String(cwd).trim() === '' ? '' : `${cwd}\\AGENT.md`) : localFile,
|
|
690
|
+
exists: localFile !== null,
|
|
691
|
+
editable: false
|
|
692
|
+
},
|
|
693
|
+
{
|
|
694
|
+
level: 2,
|
|
695
|
+
name: '项目人格(本机)',
|
|
696
|
+
scope: '这个工作区专用,设置页编辑的就是它',
|
|
697
|
+
path: storedFile,
|
|
698
|
+
exists: storedFile !== '' ? exists(storedFile) : false,
|
|
699
|
+
editable: storedFile !== ''
|
|
700
|
+
},
|
|
701
|
+
{
|
|
702
|
+
level: 3,
|
|
703
|
+
name: '全局人格',
|
|
704
|
+
scope: '所有会话的底座',
|
|
705
|
+
path: globalFile,
|
|
706
|
+
exists: exists(globalFile),
|
|
707
|
+
editable: true
|
|
708
|
+
}
|
|
709
|
+
],
|
|
710
|
+
// 项目层实际生效的是哪一份(1 优先于 2)
|
|
711
|
+
projectEffective: resolved.project === null ? null : resolved.project.kind,
|
|
712
|
+
projectEffectivePath: resolved.project === null ? '' : resolved.project.path,
|
|
713
|
+
// cwd 里有 AGENT.md 时,设置页编辑的那份会被盖住 —— 必须提示
|
|
714
|
+
localOverridesStored: localFile !== null && storedFile !== '' && exists(storedFile)
|
|
715
|
+
},
|
|
716
|
+
// health:上次读取记忆卡有没有出事(损坏备份 / 只读)。
|
|
717
|
+
// 数据出了问题是**必须看得见**的 —— 只在 soul.log 里留一行等于没留。
|
|
718
|
+
memory: { ...stats, health: memoryHealth() },
|
|
719
|
+
// 宿主形状自检:宿主升级把事件形状改了的话,这里会留下现场
|
|
720
|
+
host: hostProbeState(),
|
|
721
|
+
// 心情摘要:值 + 七情 + 最近理由(时间线走 /mood 拉全量)
|
|
722
|
+
mood: (() => {
|
|
723
|
+
const s = moodState(cwd)
|
|
724
|
+
return {
|
|
725
|
+
mood: Math.round(s.mood),
|
|
726
|
+
label: moodLabel(s.mood),
|
|
727
|
+
face: moodFace(s.mood),
|
|
728
|
+
dims: displayDims(s),
|
|
729
|
+
dimsPercent: displayDimPercents(s),
|
|
730
|
+
top: topDims(s),
|
|
731
|
+
lastReason: s.lastReason,
|
|
732
|
+
updatedAt: s.updatedAt,
|
|
733
|
+
timelineCount: s.timeline.length
|
|
734
|
+
}
|
|
735
|
+
})(),
|
|
736
|
+
// 本机所有工作区(DSH 工作区表 + 登记表 + 会话目录):设置页的下拉用它
|
|
737
|
+
workspaces: listWorkspaces(),
|
|
738
|
+
purpose: { ...purpose, goals: openGoals(purposeState(), { limit: 10 }) },
|
|
739
|
+
facts: MEMORY_FACTS,
|
|
740
|
+
dirs: { log: 'agents/soul.log' },
|
|
741
|
+
// 2026-10-31:概览页「最近」那张卡要看昨天那篇写没写。
|
|
742
|
+
// 只报状态,不读正文 —— 私密那篇的正文不该出现在概览里。
|
|
743
|
+
diary: (() => {
|
|
744
|
+
const y = yesterdayKey(Date.now())
|
|
745
|
+
const t = todayKey(Date.now())
|
|
746
|
+
// 没绑定会话时即使旧配置里留着 bornAt,也不该在概览上显示「日记本 N 天」
|
|
747
|
+
const bound = String(config.diarySessionId ?? '').trim() !== ''
|
|
748
|
+
const bornAt = bound ? Number(config.diarySessionBornAt) || 0 : 0
|
|
749
|
+
return {
|
|
750
|
+
today: t,
|
|
751
|
+
yesterday: y,
|
|
752
|
+
yesterdayPublic: exists(diaryPublicPath(y)),
|
|
753
|
+
yesterdayPrivate: exists(diaryPrivatePath(y)),
|
|
754
|
+
// 两篇都算写完才算「已写」
|
|
755
|
+
yesterdayDone: exists(diaryPublicPath(y)) && exists(diaryPrivatePath(y)),
|
|
756
|
+
// 日记本用了几天:概览页「最近」那张卡的小药丸用它
|
|
757
|
+
sessionBornAt: bornAt,
|
|
758
|
+
sessionDays: diarySessionDays(bornAt)
|
|
759
|
+
}
|
|
760
|
+
})()
|
|
761
|
+
})
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// ---- 保存配置 ----
|
|
765
|
+
if (route === '/config' && req.method === 'POST') {
|
|
766
|
+
const body = await readBody(req)
|
|
767
|
+
// 2026-11-04 修 B8:加键白名单。
|
|
768
|
+
//
|
|
769
|
+
// 原来是 saveConfig(body.config ?? body) 全量合并 —— 一次请求就能写
|
|
770
|
+
// `apiLoopbackOnly: false`(关掉唯一的权限边界)或者 `enabled: false`(整个插件停摆),
|
|
771
|
+
// 而这些键在设置页上根本没有控件,属于"只有写进去才会生效"的隐藏开关。
|
|
772
|
+
// 现在只接受 DEFAULT_CONFIG 里声明过的键:设置页能改什么,接口就只能写什么。
|
|
773
|
+
const incoming = body?.config ?? body ?? {}
|
|
774
|
+
const allowed = new Set(Object.keys(DEFAULT_CONFIG))
|
|
775
|
+
const filtered = {}
|
|
776
|
+
const rejected = []
|
|
777
|
+
for (const [key, value] of Object.entries(incoming ?? {})) {
|
|
778
|
+
if (allowed.has(key)) filtered[key] = value
|
|
779
|
+
else rejected.push(key)
|
|
780
|
+
}
|
|
781
|
+
if (rejected.length > 0) {
|
|
782
|
+
note('api', `配置写入了未知键,已忽略:${rejected.join('、')}`)
|
|
783
|
+
}
|
|
784
|
+
const next = saveConfig(filtered)
|
|
785
|
+
note('api', `配置已保存:mode=${next.mode} 记忆预算=${next.injectMaxChars} 相关区=${next.memoryRecall !== false ? `开(${next.memoryRecallTopK ?? 6})` : '关'}`)
|
|
786
|
+
return json(res, 200, { ok: true, config: next })
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
// ---- 存密钥(只进不出:返回的永远只是状态,不回显明文)----
|
|
790
|
+
if (route === '/secret' && req.method === 'POST') {
|
|
791
|
+
const body = await readBody(req)
|
|
792
|
+
const name = String(body?.name ?? '').trim()
|
|
793
|
+
const value = String(body?.value ?? '')
|
|
794
|
+
if (body?.remove === true) {
|
|
795
|
+
const removed = deleteSecret(name)
|
|
796
|
+
note('api', `密钥 ${name} 已删除`)
|
|
797
|
+
return json(res, 200, { ok: true, removed, status: secretInfo(name) })
|
|
798
|
+
}
|
|
799
|
+
const saved = saveSecret(name, value)
|
|
800
|
+
if (saved.ok !== true) return json(res, 400, { ok: false, error: saved.error })
|
|
801
|
+
note('api', `密钥 ${name} 已保存(${saved.encrypted ? 'DPAPI 加密' : '明文+0600'})`)
|
|
802
|
+
return json(res, 200, { ok: true, encrypted: saved.encrypted, status: secretInfo(name) })
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// ---- 列记忆 ----
|
|
806
|
+
if (route === '/memory' && req.method === 'GET') {
|
|
807
|
+
const scope = query.get('scope') === 'project' ? 'project' : 'global'
|
|
808
|
+
// 列记忆也要跟着当前工作区走,否则「项目记忆」会永远显示空
|
|
809
|
+
const { cwd } = resolveCwd(ctx, query)
|
|
810
|
+
const keyword = (query.get('query') ?? '').trim().toLowerCase()
|
|
811
|
+
const card = scope === 'project' && cwd !== '' ? projectCard(cwd) : globalCard()
|
|
812
|
+
let records = [...card.records].sort((a, b) => (b.importance ?? 0) - (a.importance ?? 0))
|
|
813
|
+
if (keyword !== '') {
|
|
814
|
+
records = records.filter((record) => `${record.text} ${record.title}`.toLowerCase().includes(keyword))
|
|
815
|
+
}
|
|
816
|
+
return json(res, 200, {
|
|
817
|
+
ok: true,
|
|
818
|
+
scope,
|
|
819
|
+
total: card.records.length,
|
|
820
|
+
lastDecayDate: card.lastDecayDate,
|
|
821
|
+
records: records.slice(0, 300).map((record) => ({
|
|
822
|
+
id: record.id,
|
|
823
|
+
text: record.text,
|
|
824
|
+
title: record.title,
|
|
825
|
+
importance: record.importance,
|
|
826
|
+
clarity: record.clarity,
|
|
827
|
+
tags: record.tags,
|
|
828
|
+
pinned: record.pinned,
|
|
829
|
+
createdAt: record.createdAt,
|
|
830
|
+
lastSeenAt: record.lastSeenAt,
|
|
831
|
+
recallCount: record.recallCount,
|
|
832
|
+
source: record.source
|
|
833
|
+
}))
|
|
834
|
+
})
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
// ---- 增 / 改 / 删一条记忆 ----
|
|
838
|
+
if (route === '/memory' && req.method === 'POST') {
|
|
839
|
+
const body = await readBody(req)
|
|
840
|
+
const scope = body?.scope === 'project' ? 'project' : 'global'
|
|
841
|
+
// 必须和 GET /memory 用同一套兜底。
|
|
842
|
+
// 原来这里直接 String(body?.cwd ?? ''):设置页拿不到会话 cwd 时,
|
|
843
|
+
// 列表走兜底读到项目卡、显示得出来,删除却按空 cwd 去查全局卡 ——
|
|
844
|
+
// 全局卡是空的,于是永远「没找到这条记忆」。删 / 固定 / 编辑都一样。
|
|
845
|
+
const given = String(body?.cwd ?? '').trim()
|
|
846
|
+
const cwd = given !== '' ? given : resolveCwd(ctx, query).cwd
|
|
847
|
+
const card = scope === 'project' && cwd !== '' ? projectCard(cwd) : globalCard()
|
|
848
|
+
const action = String(body?.action ?? '')
|
|
849
|
+
const id = String(body?.id ?? '')
|
|
850
|
+
|
|
851
|
+
if (action === 'delete') {
|
|
852
|
+
// 传 archive:设置页点删除也算「遗忘」,要能在 archive.jsonl 里查回来
|
|
853
|
+
const removed = forgetRecord(card, id, makeArchiver(archivePath()))
|
|
854
|
+
if (removed === null) {
|
|
855
|
+
note('api', `删除落空:scope=${scope} cwd=「${cwd}」卡里 ${card.records.length} 条,找不到 id=${id}`)
|
|
856
|
+
return json(res, 404, { ok: false, error: '没找到这条记忆' })
|
|
857
|
+
}
|
|
858
|
+
} else if (action === 'pin') {
|
|
859
|
+
if (!setPinned(card, id, body?.pinned !== false)) {
|
|
860
|
+
note('api', `固定落空:scope=${scope} cwd=「${cwd}」卡里 ${card.records.length} 条,找不到 id=${id}`)
|
|
861
|
+
return json(res, 404, { ok: false, error: '没找到这条记忆' })
|
|
862
|
+
}
|
|
863
|
+
} else if (action === 'write') {
|
|
864
|
+
// 设置页手动新增。走 addRecord 才能拿到打分、去重、脱敏那一套。
|
|
865
|
+
const text = String(body?.text ?? '').trim()
|
|
866
|
+
if (text === '') return json(res, 400, { ok: false, error: '内容不能为空' })
|
|
867
|
+
const result = addRecord(card, { text, source: 'manual', isOwner: true, isPrivate: true }, loadConfig(), Date.now())
|
|
868
|
+
if (result.ok !== true) return json(res, 400, { ok: false, error: result.reason ?? '写入失败' })
|
|
869
|
+
} else if (action === 'edit') {
|
|
870
|
+
const record = card.records.find((item) => item.id === id)
|
|
871
|
+
if (record === undefined) return json(res, 404, { ok: false, error: '没找到这条记忆' })
|
|
872
|
+
if (typeof body?.text === 'string' && body.text.trim() !== '') record.text = body.text.trim().slice(0, 600)
|
|
873
|
+
if (typeof body?.title === 'string') record.title = body.title.trim().slice(0, 60)
|
|
874
|
+
} else {
|
|
875
|
+
return json(res, 400, { ok: false, error: `不认识的 action:${action}` })
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
if (scope === 'project' && cwd !== '') saveProjectCard(cwd, card)
|
|
879
|
+
else saveGlobalCard(card)
|
|
880
|
+
return json(res, 200, { ok: true, total: card.records.length })
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
// ---- 手动维护 ----
|
|
884
|
+
if (route === '/maintain' && req.method === 'POST') {
|
|
885
|
+
const body = await readBody(req)
|
|
886
|
+
const given = String(body?.cwd ?? '').trim()
|
|
887
|
+
const cwd = given !== '' ? given : resolveCwd(ctx, query).cwd
|
|
888
|
+
const report = maintain(cwd, loadConfig())
|
|
889
|
+
return json(res, 200, { ok: true, report })
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
// ---- 心情:读全量(值 + 七情 + 时间线) ----
|
|
893
|
+
if (route === '/mood' && req.method === 'GET') {
|
|
894
|
+
// 必须和 /state 用同一套兜底,否则详情页和概览页读的是两份文件
|
|
895
|
+
const { cwd } = resolveCwd(ctx, query)
|
|
896
|
+
const cfg = loadConfig()
|
|
897
|
+
const s = moodState(cwd)
|
|
898
|
+
return json(res, 200, {
|
|
899
|
+
ok: true,
|
|
900
|
+
cwd,
|
|
901
|
+
config: cfg,
|
|
902
|
+
// 密钥只报状态,绝不回显明文(2026-11-01)
|
|
903
|
+
secrets: { siliconflow: secretInfo('siliconflow') },
|
|
904
|
+
state: {
|
|
905
|
+
mood: Math.round(s.mood),
|
|
906
|
+
rawMood: s.mood,
|
|
907
|
+
label: moodLabel(s.mood),
|
|
908
|
+
face: moodFace(s.mood),
|
|
909
|
+
dims: displayDims(s),
|
|
910
|
+
dimsPercent: displayDimPercents(s),
|
|
911
|
+
top: topDims(s),
|
|
912
|
+
lastReason: s.lastReason,
|
|
913
|
+
lastConfidence: s.lastConfidence,
|
|
914
|
+
minor: s.minor,
|
|
915
|
+
kind: s.kind,
|
|
916
|
+
updatedAt: s.updatedAt,
|
|
917
|
+
timelineCount: s.timeline.length,
|
|
918
|
+
// 时间线倒序 60 条(页面再截 40);t.dims 也一并给,方便 tooltip
|
|
919
|
+
timeline: s.timeline.slice(-60).reverse().map((t) => ({
|
|
920
|
+
at: t.at,
|
|
921
|
+
mood: t.mood,
|
|
922
|
+
delta: t.delta,
|
|
923
|
+
reason: t.reason,
|
|
924
|
+
conf: t.conf,
|
|
925
|
+
minor: t.minor === true,
|
|
926
|
+
kind: t.kind || '',
|
|
927
|
+
dims: t.dims || null
|
|
928
|
+
}))
|
|
929
|
+
}
|
|
930
|
+
})
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
// ---- 心情:重置 ----
|
|
934
|
+
if (route === '/mood/reset' && req.method === 'POST') {
|
|
935
|
+
const body = await readBody(req)
|
|
936
|
+
const given = String(body?.cwd ?? '').trim()
|
|
937
|
+
// 页面没给 cwd 就按当前工作区兜底:不然会把心情重置到一个从没用过的作用域上,
|
|
938
|
+
// 页面还看不见自己刚重置的那份(表现为「点了重置却没反应」)
|
|
939
|
+
const cwd = given !== '' ? given : resolveCwd(ctx, query).cwd
|
|
940
|
+
const s = resetMood(cwd)
|
|
941
|
+
note('api', `心情已重置(cwd=${cwd || '全局'})→ ${Math.round(s.mood)}`)
|
|
942
|
+
return json(res, 200, { ok: true, mood: Math.round(s.mood) })
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
// ---- 心情:手动跑一次时间衰减(页面刷新时用,幂等) ----
|
|
946
|
+
if (route === '/mood/decay' && req.method === 'POST') {
|
|
947
|
+
const body = await readBody(req)
|
|
948
|
+
const given = String(body?.cwd ?? '').trim()
|
|
949
|
+
const cwd = given !== '' ? given : resolveCwd(ctx, query).cwd
|
|
950
|
+
const s = decayMoodFor(cwd)
|
|
951
|
+
return json(res, 200, {
|
|
952
|
+
ok: true,
|
|
953
|
+
mood: Math.round(s.mood),
|
|
954
|
+
dims: displayDims(s),
|
|
955
|
+
dimsPercent: displayDimPercents(s),
|
|
956
|
+
lastReason: s.lastReason,
|
|
957
|
+
updatedAt: s.updatedAt
|
|
958
|
+
})
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
// ---- 目标:关掉一条 ----
|
|
962
|
+
if (route === '/goal' && req.method === 'POST') {
|
|
963
|
+
const body = await readBody(req)
|
|
964
|
+
const state = purposeState()
|
|
965
|
+
const id = String(body?.id ?? '')
|
|
966
|
+
const ok = closeGoal(state, id)
|
|
967
|
+
if (ok) savePurposeState(state)
|
|
968
|
+
return json(res, ok ? 200 : 404, { ok, goals: openGoals(state, { limit: 20 }) })
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
// ---- 登记工作区(设置页「使用」按钮:手填/选中的目录切过去) ----
|
|
972
|
+
if (route === '/register' && req.method === 'POST') {
|
|
973
|
+
const body = await readBody(req)
|
|
974
|
+
const cwd = String(body?.cwd ?? '').trim()
|
|
975
|
+
if (cwd === '') return json(res, 400, { ok: false, error: '缺少 cwd' })
|
|
976
|
+
const registry = registerProject(cwd, { active: body.active === true })
|
|
977
|
+
return json(res, 200, { ok: true, registry, slug: slugFor(cwd).slug })
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
// ---- 系统「选择文件夹」:让任意目录都能成为项目人格的归属 ----
|
|
981
|
+
if (route === '/pick' && req.method === 'POST') {
|
|
982
|
+
try {
|
|
983
|
+
const picked = await pickFolder()
|
|
984
|
+
if (picked === '') return json(res, 200, { picked: '', cancelled: true })
|
|
985
|
+
registerProject(picked, { active: false })
|
|
986
|
+
return json(res, 200, { picked, cancelled: false, slug: slugFor(picked).slug })
|
|
987
|
+
} catch (error) {
|
|
988
|
+
return json(res, 500, {
|
|
989
|
+
ok: false,
|
|
990
|
+
error: `打不开系统文件夹选择器:${error instanceof Error ? error.message : error};可以直接把路径粘到输入框里。`
|
|
991
|
+
})
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
// ---- 日记:列表(只列公开日记的预览;私密内容不出服务器) ----
|
|
996
|
+
if (route === '/diary/list' && req.method === 'GET') {
|
|
997
|
+
const days = Math.min(30, Math.max(1, Math.round(Number(query.get('days')) || 14)))
|
|
998
|
+
const today = new Date()
|
|
999
|
+
today.setHours(0, 0, 0, 0)
|
|
1000
|
+
const list = []
|
|
1001
|
+
for (let i = 0; i < days; i++) {
|
|
1002
|
+
const day = new Date(today.getTime() - i * 24 * 60 * 60 * 1000)
|
|
1003
|
+
const pad = (n) => String(n).padStart(2, '0')
|
|
1004
|
+
const dateStr = `${day.getFullYear()}-${pad(day.getMonth() + 1)}-${pad(day.getDate())}`
|
|
1005
|
+
const publicFile = diaryPublicPath(dateStr)
|
|
1006
|
+
const privateFile = diaryPrivatePath(dateStr)
|
|
1007
|
+
const hasPublic = exists(publicFile)
|
|
1008
|
+
const hasPrivate = exists(privateFile)
|
|
1009
|
+
if (!hasPublic && !hasPrivate) continue
|
|
1010
|
+
list.push({
|
|
1011
|
+
date: dateStr,
|
|
1012
|
+
hasPublic,
|
|
1013
|
+
hasPrivate,
|
|
1014
|
+
preview: hasPublic ? readText(publicFile).slice(0, 400) : '',
|
|
1015
|
+
updatedAt: hasPublic ? statSync(publicFile).mtime.toISOString() : null
|
|
1016
|
+
})
|
|
1017
|
+
}
|
|
1018
|
+
return json(res, 200, { ok: true, list })
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
// ---- 日记:读取某一天(私密不出服务器,只返回存在性) ----
|
|
1022
|
+
if (route === '/diary/read' && req.method === 'GET') {
|
|
1023
|
+
const dateStr = String(query.get('date') ?? '').trim()
|
|
1024
|
+
if (dateStr === '') return json(res, 400, { ok: false, error: '缺少 date 参数' })
|
|
1025
|
+
const publicFile = diaryPublicPath(dateStr)
|
|
1026
|
+
const privateFile = diaryPrivatePath(dateStr)
|
|
1027
|
+
const hasPublic = exists(publicFile)
|
|
1028
|
+
const hasPrivate = exists(privateFile)
|
|
1029
|
+
return json(res, 200, {
|
|
1030
|
+
ok: true,
|
|
1031
|
+
date: dateStr,
|
|
1032
|
+
hasPublic,
|
|
1033
|
+
hasPrivate,
|
|
1034
|
+
publicContent: hasPublic ? readText(publicFile) : '',
|
|
1035
|
+
// 私密日记不出服务器,只告诉有没有
|
|
1036
|
+
})
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
// ---- 日记:读私密正文(2026-10-31;仅回环 + 显式开启) ----
|
|
1040
|
+
// 默认 diaryPrivateVisible=false 时这里一律 403,行为和以前一样:
|
|
1041
|
+
// 私密只报存在性,正文永不出服务器。开关打开也只对本机回环放行。
|
|
1042
|
+
if (route === '/diary/private' && req.method === 'GET') {
|
|
1043
|
+
const view = privateDiaryView(req, loadConfig())
|
|
1044
|
+
return json(res, view.status, view.payload)
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
// ---- 日记:可选会话(2026-11-04) ----
|
|
1048
|
+
// 设置页的下拉要能看到「任意会话」,不只是当前这个。列表失败不报 500:
|
|
1049
|
+
// 返回空数组,页面仍有「刷新列表」按钮可以重试。
|
|
1050
|
+
if (route === '/diary/sessions' && req.method === 'GET') {
|
|
1051
|
+
let sessions = []
|
|
1052
|
+
try {
|
|
1053
|
+
sessions = listDiarySessions(ctx)
|
|
1054
|
+
} catch (error) {
|
|
1055
|
+
note('api', `日记会话列表生成失败:${error instanceof Error ? error.message : error}`)
|
|
1056
|
+
}
|
|
1057
|
+
return json(res, 200, { ok: true, sessions })
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
// ---- 日记:绑定当前会话 / 清除绑定(2026-10-31) ----
|
|
1061
|
+
// 为什么绑:agents.create 造出来的日记会话没有宿主的标准工具集,写不出文件。
|
|
1062
|
+
// 只接受明确的会话 id;请求没带就取「最近更新的会话」(这台 DSH 的设置页
|
|
1063
|
+
// 拿不到 sessionId,见 currentSessionIdOf 的注释)。
|
|
1064
|
+
if (route === '/diary/bind' && req.method === 'POST') {
|
|
1065
|
+
const body = await readBody(req)
|
|
1066
|
+
let sessionId = String(body?.sessionId ?? '').trim()
|
|
1067
|
+
const source = sessionId === '' ? 'recent' : 'client'
|
|
1068
|
+
if (sessionId === '') sessionId = currentSessionIdOf(ctx)
|
|
1069
|
+
if (sessionId === '') {
|
|
1070
|
+
return json(res, 400, { ok: false, error: '拿不到当前会话 id:请求没带,会话服务里也没有可用会话' })
|
|
1071
|
+
}
|
|
1072
|
+
// 2026-11-04:绑定前探测一次(只 get,**绝不 resume** —— resume 有副作用,
|
|
1073
|
+
// 会在用户只是选下拉的时候就真把会话冷启动起来)。
|
|
1074
|
+
// get 拿不到 ≠ id 错了:休眠的会话 get 不到,但写日记时 resume 能冷启动,
|
|
1075
|
+
// 这是现有设计里的合法路径。所以这里只加 warning,不返回 400。
|
|
1076
|
+
// agents 服务不可用 / 探测抛错时一律跳过,照常绑定。
|
|
1077
|
+
let probeWarning = ''
|
|
1078
|
+
try {
|
|
1079
|
+
const agents = serviceOf(ctx, 'agents')
|
|
1080
|
+
if (agents === undefined || agents === null || typeof agents.get !== 'function') {
|
|
1081
|
+
note('api', `日记会话绑定:agents 服务不可用,跳过存在性探测(${sessionId})`)
|
|
1082
|
+
} else {
|
|
1083
|
+
const live = agents.get(sessionId)
|
|
1084
|
+
if (live === undefined || live === null) {
|
|
1085
|
+
probeWarning = '这个会话现在不活跃,写日记时会尝试冷启动它'
|
|
1086
|
+
note('api', `日记会话绑定:${sessionId} 当前不活跃(agents.get 为空),照常绑定,写日记时会冷启动`)
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
} catch (error) {
|
|
1090
|
+
note('api', `日记会话绑定:探测 ${sessionId} 失败,跳过(${error instanceof Error ? error.message : error})`)
|
|
1091
|
+
}
|
|
1092
|
+
const bornAt = Date.now()
|
|
1093
|
+
const next = saveConfig({ diarySessionId: sessionId, diarySessionBornAt: bornAt })
|
|
1094
|
+
note('api', `日记会话已绑定:${sessionId}(来源 ${source},起算 ${bornAt})`)
|
|
1095
|
+
return json(res, 200, {
|
|
1096
|
+
ok: true,
|
|
1097
|
+
sessionId,
|
|
1098
|
+
source,
|
|
1099
|
+
bornAt,
|
|
1100
|
+
...(probeWarning === '' ? {} : { warning: probeWarning }),
|
|
1101
|
+
config: next
|
|
1102
|
+
})
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
if (route === '/diary/unbind' && req.method === 'POST') {
|
|
1106
|
+
// bornAt 一起清掉:否则概览还会按旧时间显示「日记本 N 天」
|
|
1107
|
+
const next = saveConfig({ diarySessionId: '', diarySessionBornAt: 0 })
|
|
1108
|
+
note('api', '日记会话绑定已清除')
|
|
1109
|
+
return json(res, 200, { ok: true, sessionId: '', config: next })
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
// ---- 手动触发日记 ----
|
|
1113
|
+
if (route === '/diary' && req.method === 'POST') {
|
|
1114
|
+
const body = await readBody(req)
|
|
1115
|
+
const dateStr = String(body?.date ?? '').trim() || todayKey(Date.now())
|
|
1116
|
+
const noteText = String(body?.note ?? '').trim()
|
|
1117
|
+
const config = loadConfig()
|
|
1118
|
+
if (config.diaryEnabled === false) {
|
|
1119
|
+
return json(res, 403, { ok: false, error: '日记功能已关闭' })
|
|
1120
|
+
}
|
|
1121
|
+
const ok2 = await runDiaryOnce(ctx, dateStr, noteText || undefined)
|
|
1122
|
+
return json(res, ok2 ? 200 : 500, {
|
|
1123
|
+
ok: ok2,
|
|
1124
|
+
date: dateStr,
|
|
1125
|
+
message: ok2 ? '已触发日记写作' : '日记触发失败(无可用会话或 LLM 异常)'
|
|
1126
|
+
})
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
// ---- 笔记(2026-11-04):她自己写的 md ----
|
|
1130
|
+
//
|
|
1131
|
+
// 跟私密日记的处理不一样:日记是「写给自己看的」,所以正文不出服务器;
|
|
1132
|
+
// 笔记是「她自己整理的东西」,没有那一层私密约定,设置页该能看、能改、能删。
|
|
1133
|
+
// 她写了什么你都能在这里看到 —— 这也是这个功能有意思的地方。
|
|
1134
|
+
if (route === '/notes/list' && req.method === 'GET') {
|
|
1135
|
+
return json(res, 200, { ok: true, notes: listNotes() })
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
if (route === '/notes/read' && req.method === 'GET') {
|
|
1139
|
+
const got = readNote(String(query.get('title') ?? '').trim())
|
|
1140
|
+
if (got.ok !== true) return json(res, 404, { ok: false, error: got.reason })
|
|
1141
|
+
return json(res, 200, { ok: true, note: got.note, text: got.text })
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
if (route === '/notes/save' && req.method === 'POST') {
|
|
1145
|
+
const body = await readBody(req)
|
|
1146
|
+
const result = writeNote({
|
|
1147
|
+
title: String(body?.title ?? '').trim(),
|
|
1148
|
+
content: body?.content,
|
|
1149
|
+
// 2026-11-04 修 B8:默认**不覆盖**,跟 soul_note 工具口径一致。
|
|
1150
|
+
// 原来写的是 `body.overwrite !== false`(缺省 true),设置页点保存就把同名笔记整篇替换掉,
|
|
1151
|
+
// 而工具那边同一个动作是必须显式 overwrite 的 —— 同一个概念两个默认值,早晚出事。
|
|
1152
|
+
overwrite: body?.overwrite === true
|
|
1153
|
+
})
|
|
1154
|
+
if (result.ok !== true) return json(res, 400, { ok: false, error: result.reason })
|
|
1155
|
+
return json(res, 200, { ok: true, slug: result.slug, created: result.created })
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
if (route === '/notes/rename' && req.method === 'POST') {
|
|
1159
|
+
const body = await readBody(req)
|
|
1160
|
+
const result = renameNote(String(body?.title ?? '').trim(), String(body?.newTitle ?? '').trim())
|
|
1161
|
+
if (result.ok !== true) return json(res, 400, { ok: false, error: result.reason })
|
|
1162
|
+
return json(res, 200, { ok: true, slug: result.slug })
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
if (route === '/notes/delete' && req.method === 'POST') {
|
|
1166
|
+
const body = await readBody(req)
|
|
1167
|
+
const result = deleteNote(String(body?.title ?? '').trim())
|
|
1168
|
+
if (result.ok !== true) return json(res, 400, { ok: false, error: result.reason })
|
|
1169
|
+
return json(res, 200, { ok: true, slug: result.slug })
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
return json(res, 404, { ok: false, error: `不认识的路由:${route}` })
|
|
1173
|
+
} catch (error) {
|
|
1174
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
1175
|
+
note('api', `${route} 出错:${message}`)
|
|
1176
|
+
return json(res, 500, { ok: false, error: message })
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
})
|
|
1180
|
+
|
|
1181
|
+
if (typeof dispose === 'function' && typeof ctx.effect === 'function') {
|
|
1182
|
+
ctx.effect(() => dispose, 'dsh-agent-soul: http api')
|
|
1183
|
+
}
|
|
1184
|
+
note('api', `设置页接口已注册 ${API_PREFIX}`)
|
|
1185
|
+
return dispose
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
/**
|
|
1189
|
+
* 表情图那五张 PNG 走这儿出去。
|
|
1190
|
+
* 之前用的是系统 emoji(😊🙂那种),跟原插件那套画不一致 —— 现在直接给图。
|
|
1191
|
+
* 只此五张、只读,顺永远不会变,所以缓存直接拉到最长。
|
|
1192
|
+
*/
|
|
1193
|
+
export function registerAssets(ctx) {
|
|
1194
|
+
const webServer = serviceOf(ctx, 'webServer')
|
|
1195
|
+
if (webServer === undefined || webServer === null || typeof webServer.register !== 'function') {
|
|
1196
|
+
note('api', '宿主没有 webServer 服务,表情图未注册')
|
|
1197
|
+
return undefined
|
|
1198
|
+
}
|
|
1199
|
+
const dispose = webServer.register({
|
|
1200
|
+
kind: 'prefix',
|
|
1201
|
+
path: ASSET_PREFIX,
|
|
1202
|
+
handler: (req, res) => {
|
|
1203
|
+
const url = (req.url ?? '').split('?')[0]
|
|
1204
|
+
const raw = url.slice(ASSET_PREFIX.length).replace(/^\/+/, '')
|
|
1205
|
+
const name = decodeURIComponent(raw)
|
|
1206
|
+
if (!FACE_ASSETS.has(name)) {
|
|
1207
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' })
|
|
1208
|
+
res.end('not found')
|
|
1209
|
+
return
|
|
1210
|
+
}
|
|
1211
|
+
try {
|
|
1212
|
+
const bytes = readFileSync(join(ASSETS_DIR, name))
|
|
1213
|
+
res.writeHead(200, {
|
|
1214
|
+
'Content-Type': 'image/png',
|
|
1215
|
+
'Content-Length': bytes.length,
|
|
1216
|
+
// 文件名不带版本号,但内容从不改 → 让浏览器只取一次
|
|
1217
|
+
'Cache-Control': 'public, max-age=31536000, immutable'
|
|
1218
|
+
})
|
|
1219
|
+
res.end(bytes)
|
|
1220
|
+
} catch {
|
|
1221
|
+
note('api', `表情图读不出来:${name}(assets 目录丢了?${ASSETS_DIR})`)
|
|
1222
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' })
|
|
1223
|
+
res.end('not found')
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
})
|
|
1227
|
+
if (typeof dispose === 'function' && typeof ctx.effect === 'function') {
|
|
1228
|
+
ctx.effect(() => dispose, 'dsh-agent-soul: assets')
|
|
1229
|
+
}
|
|
1230
|
+
note('api', `表情图已注册 ${ASSET_PREFIX}(${FACE_ASSETS.size} 张)`)
|
|
1231
|
+
return dispose
|
|
1232
|
+
}
|