lingshu-skill 4.1.0 → 4.2.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 +32 -1
- package/README.md +697 -697
- package/SKILL.md +380 -380
- package/assets/panel.html +1 -1
- package/cordis-plugin/lingshu-cron/plugin.js +1074 -1040
- package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +32 -1
- package/package.json +52 -52
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +11 -9
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +32 -1
- package/scripts/astrbot_plugin_lingshu/engine/README.md +697 -697
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +380 -380
- package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +131 -8
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +16 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/desktop_shortcut.py +136 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_data.py +75 -4
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_settings.py +23 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_update.py +81 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/release.py +10 -0
- package/scripts/cli.py +131 -8
- package/scripts/core.py +16 -0
- package/scripts/desktop_shortcut.py +136 -0
- package/scripts/panel_data.py +75 -4
- package/scripts/panel_settings.py +23 -0
- package/scripts/panel_update.py +81 -0
- package/scripts/release.py +10 -0
- package/scripts/run_tests.py +36 -0
|
@@ -1,1040 +1,1074 @@
|
|
|
1
|
-
// 灵枢 · 例行维护调度插件(lingshu-cron)
|
|
2
|
-
//
|
|
3
|
-
// 设计思想:灵枢的例行维护(做梦、每日整理、备份、冲突检测、用量上报、技能自检)
|
|
4
|
-
// 原本压在"模型自觉"上——模型记不住就不做。本插件把调度搬进 APP:
|
|
5
|
-
// 模型只负责内容(记什么、想什么),维护归插件。
|
|
6
|
-
//
|
|
7
|
-
// 三条铁律(对齐 turn-stopping / pre-step 的真实语义):
|
|
8
|
-
// 1. 绝不 await:agent/turn-stopping 是串行事件,await 长任务会拖住回合关闭。
|
|
9
|
-
// 所有任务 fire-and-forget,失败静默吞掉。
|
|
10
|
-
// 2. 防并发:running Set 挡住同一任务重入(用户连发消息时事件密集触发)。
|
|
11
|
-
// 3. 状态落盘:状态文件放 APP profile 目录(不碰 ~/.brain-memory),
|
|
12
|
-
// 否则每次重启 daily/backup 都会重跑。临时文件 + rename 原子写。
|
|
13
|
-
//
|
|
14
|
-
// 数据安全:本插件只调用灵枢 CLI 的只读/自维护命令,不改任何会话上下文;
|
|
15
|
-
// 注入类(review / check-context)默认也开启,但只在有内容时注入一次,
|
|
16
|
-
// 且可整体关闭(injectReview / waterGuard = false)——
|
|
17
|
-
// 保证不影响"人格/记忆/灵魂 + AI 自主自动化"的主功能。
|
|
18
|
-
//
|
|
19
|
-
// 水位自动执行(v3.44,影子模式 + 显式同意,隐私默认安全):
|
|
20
|
-
// 75% 做梦 / 90% 封存过去靠"模型自觉",现在可由 config.json 的 water 段自动执行,
|
|
21
|
-
// 但默认全关:autoDream/autoCapture 及其 consent 都缺省 false,shadow 缺省 true;
|
|
22
|
-
// shadow=true 只记"本来会做什么",真执行必须 autoXxx && autoXxxConsent 同真且
|
|
23
|
-
// shadow=false。90% 的 capture 永不自动执行(插件拿不到会话原文,绝不自己拼),
|
|
24
|
-
// 只记一条待人工确认的逃生建议并在会话里提醒一次。详见下方 WATER 段注释。
|
|
25
|
-
|
|
26
|
-
import { spawn } from 'node:child_process'
|
|
27
|
-
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync, rmSync } from 'node:fs'
|
|
28
|
-
import { homedir } from 'node:os'
|
|
29
|
-
import { delimiter, dirname, join } from 'node:path'
|
|
30
|
-
import { randomUUID } from 'node:crypto'
|
|
31
|
-
import { fileURLToPath } from 'node:url'
|
|
32
|
-
|
|
33
|
-
export const name = 'dsh-lingshu-cron'
|
|
34
|
-
|
|
35
|
-
// 本插件文件在 <包根>/cordis-plugin/lingshu-cron/plugin.js → 上两级是包根
|
|
36
|
-
const PLUGIN_DIR = dirname(fileURLToPath(import.meta.url))
|
|
37
|
-
const PACKAGE_ROOT = join(PLUGIN_DIR, '..', '..')
|
|
38
|
-
|
|
39
|
-
const DEFAULTS = {
|
|
40
|
-
brainPy: '', // brain.py 绝对路径;留空自动探测(与 lingshu-startup 同一套逻辑)
|
|
41
|
-
python: '', // python.exe 绝对路径;留空自动探测(spawn 不解析 PATHEXT)
|
|
42
|
-
timeoutMs: 120000, // 后台任务子进程超时(做梦/备份可能慢,2 分钟兜底)
|
|
43
|
-
dreamTurns: 8, // 每 N 轮触发 dream --auto
|
|
44
|
-
extractTurns: 4, // 每 N 轮把攒下的对话文本静默 extract(即记即存)
|
|
45
|
-
extractMinChars: 80, // 攒的文本短于该值不触发(惊异门控在 brain.py extract 里有第二道)
|
|
46
|
-
selfReviewDays: 3, // 每 N 天触发 skill self-review
|
|
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
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
out.
|
|
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
|
-
return null
|
|
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
|
-
|
|
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
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
return
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
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
|
-
child.
|
|
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
|
-
let
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
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
|
-
function
|
|
653
|
-
|
|
654
|
-
const
|
|
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
|
-
if (
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
const
|
|
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
|
-
if (
|
|
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
|
-
}
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
|
|
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
|
-
if (
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1
|
+
// 灵枢 · 例行维护调度插件(lingshu-cron)
|
|
2
|
+
//
|
|
3
|
+
// 设计思想:灵枢的例行维护(做梦、每日整理、备份、冲突检测、用量上报、技能自检)
|
|
4
|
+
// 原本压在"模型自觉"上——模型记不住就不做。本插件把调度搬进 APP:
|
|
5
|
+
// 模型只负责内容(记什么、想什么),维护归插件。
|
|
6
|
+
//
|
|
7
|
+
// 三条铁律(对齐 turn-stopping / pre-step 的真实语义):
|
|
8
|
+
// 1. 绝不 await:agent/turn-stopping 是串行事件,await 长任务会拖住回合关闭。
|
|
9
|
+
// 所有任务 fire-and-forget,失败静默吞掉。
|
|
10
|
+
// 2. 防并发:running Set 挡住同一任务重入(用户连发消息时事件密集触发)。
|
|
11
|
+
// 3. 状态落盘:状态文件放 APP profile 目录(不碰 ~/.brain-memory),
|
|
12
|
+
// 否则每次重启 daily/backup 都会重跑。临时文件 + rename 原子写。
|
|
13
|
+
//
|
|
14
|
+
// 数据安全:本插件只调用灵枢 CLI 的只读/自维护命令,不改任何会话上下文;
|
|
15
|
+
// 注入类(review / check-context)默认也开启,但只在有内容时注入一次,
|
|
16
|
+
// 且可整体关闭(injectReview / waterGuard = false)——
|
|
17
|
+
// 保证不影响"人格/记忆/灵魂 + AI 自主自动化"的主功能。
|
|
18
|
+
//
|
|
19
|
+
// 水位自动执行(v3.44,影子模式 + 显式同意,隐私默认安全):
|
|
20
|
+
// 75% 做梦 / 90% 封存过去靠"模型自觉",现在可由 config.json 的 water 段自动执行,
|
|
21
|
+
// 但默认全关:autoDream/autoCapture 及其 consent 都缺省 false,shadow 缺省 true;
|
|
22
|
+
// shadow=true 只记"本来会做什么",真执行必须 autoXxx && autoXxxConsent 同真且
|
|
23
|
+
// shadow=false。90% 的 capture 永不自动执行(插件拿不到会话原文,绝不自己拼),
|
|
24
|
+
// 只记一条待人工确认的逃生建议并在会话里提醒一次。详见下方 WATER 段注释。
|
|
25
|
+
|
|
26
|
+
import { spawn } from 'node:child_process'
|
|
27
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync, rmSync } from 'node:fs'
|
|
28
|
+
import { homedir } from 'node:os'
|
|
29
|
+
import { delimiter, dirname, join } from 'node:path'
|
|
30
|
+
import { randomUUID } from 'node:crypto'
|
|
31
|
+
import { fileURLToPath } from 'node:url'
|
|
32
|
+
|
|
33
|
+
export const name = 'dsh-lingshu-cron'
|
|
34
|
+
|
|
35
|
+
// 本插件文件在 <包根>/cordis-plugin/lingshu-cron/plugin.js → 上两级是包根
|
|
36
|
+
const PLUGIN_DIR = dirname(fileURLToPath(import.meta.url))
|
|
37
|
+
const PACKAGE_ROOT = join(PLUGIN_DIR, '..', '..')
|
|
38
|
+
|
|
39
|
+
const DEFAULTS = {
|
|
40
|
+
brainPy: '', // brain.py 绝对路径;留空自动探测(与 lingshu-startup 同一套逻辑)
|
|
41
|
+
python: '', // python.exe 绝对路径;留空自动探测(spawn 不解析 PATHEXT)
|
|
42
|
+
timeoutMs: 120000, // 后台任务子进程超时(做梦/备份可能慢,2 分钟兜底)
|
|
43
|
+
dreamTurns: 8, // 每 N 轮触发 dream --auto
|
|
44
|
+
extractTurns: 4, // 每 N 轮把攒下的对话文本静默 extract(即记即存)
|
|
45
|
+
extractMinChars: 80, // 攒的文本短于该值不触发(惊异门控在 brain.py extract 里有第二道)
|
|
46
|
+
selfReviewDays: 3, // 每 N 天触发 skill self-review
|
|
47
|
+
// P11:备份改按小时(原来 days:1 只在当天第一次回合跑,之后十几小时裸奔)
|
|
48
|
+
backupIntervalHours: 6,
|
|
49
|
+
// P11:自动更新检查间隔(真正的开关在 ~/.brain-memory/config.json 的 auto_update)
|
|
50
|
+
autoUpdateIntervalHours: 24,
|
|
51
|
+
runUsage: true, // 每轮 turn-stopping 静默跑 usage --reply
|
|
52
|
+
injectReview: true, // review 有 pending 时注入提醒(每会话一次,见 reviewNotice*)
|
|
53
|
+
reviewNoticeMin: 5, // v3.57:待审条数达到这个数才提醒(零星一两条不打扰)
|
|
54
|
+
reviewNoticeOnce: true, // v3.57:每会话最多提醒一次(false = 每次都提,旧行为)
|
|
55
|
+
waterGuard: true, // 水位守卫:pre-step 估真实水位,首次跨 60/75/90 各注一条提醒(v3.01)
|
|
56
|
+
charsPerToken: 2, // 中文语境 token 估算:约 2 字符 ≈ 1 token(v3.23 从 3 下调,避免低估)
|
|
57
|
+
systemOverheadTokens: 18000, // system prompt + 工具 schema 的固定开销(不进 messages,v3.23)
|
|
58
|
+
contextLimit: 131072, // 模型上下文窗口 token 数(估算分母;宿主给 usage 时用宿主值)
|
|
59
|
+
waterCheckTurns: 10, // 每 N 轮做一次「软自检」:估算没到阈值也提醒 AI 自查(v3.23)
|
|
60
|
+
reviewCacheMs: 30000, // review --json 结果缓存时长(pre-step 每步都跑,别真跑)
|
|
61
|
+
pruneInjected: false, // v3.59:默认**不清理**已注入的旧消息。
|
|
62
|
+
// 为什么反过来了:提示词缓存从请求开头逐项匹配,删掉历史中段的
|
|
63
|
+
// 一条消息等于**改写前缀**——从该处往后全部无法复用缓存,新模型还会
|
|
64
|
+
// 丢弃变更点之后的推理项(OpenAI《保持前缀不变》)。所以"删旧消息省
|
|
65
|
+
// token"是净亏。只在压缩/上下文重建后由宿主清一次才划算。
|
|
66
|
+
// 想恢复旧行为:config 里设 pruneInjected: true。
|
|
67
|
+
// (原文已被 extract 封存海马体,清掉 = 归档后遗忘,不丢信息)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// 本插件注入消息的 source.name:**故意与 startup 的 'lingshu-startup' 区分开**。
|
|
71
|
+
// 原来两个子插件都用 'lingshu',于是 cron 的 pruneInjected 会把 startup 注入的
|
|
72
|
+
// 人格/记忆块一起删掉(谁先跑谁赢)。lingshu-im 早就因为同一个坑改用了
|
|
73
|
+
// 'lingshu-im'(见其 plugin.js 注释),这里补齐。
|
|
74
|
+
const INJECT_SOURCE = 'lingshu-cron'
|
|
75
|
+
|
|
76
|
+
/** 灵枢家族所有注入消息的 source.name——水位估算要排除它们,只看真实对话。 */
|
|
77
|
+
const LINGSHU_SOURCES = new Set(['lingshu', 'lingshu-cron', 'lingshu-startup', 'lingshu-im'])
|
|
78
|
+
|
|
79
|
+
/** 合并用户配置与默认值 */
|
|
80
|
+
function mergeConfig(user) {
|
|
81
|
+
const merged = { ...DEFAULTS }
|
|
82
|
+
if (user && typeof user === 'object') {
|
|
83
|
+
for (const k of Object.keys(DEFAULTS)) {
|
|
84
|
+
const v = user[k]
|
|
85
|
+
if (v !== undefined && v !== null && v !== '') merged[k] = v
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return merged
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ---------------------------------------------------------------- 探测(照抄 lingshu-startup 已验证方案)
|
|
92
|
+
|
|
93
|
+
async function findBrainPy(configured, ctx) {
|
|
94
|
+
if (configured) return existsSync(configured) ? configured : null
|
|
95
|
+
// ① 本包自带优先:../../scripts/brain.py 与插件同包发布,不依赖宿主状态
|
|
96
|
+
// (v3.53 之前缺这一条 → 注册 runtime 技能时没给 resourceBase/path,
|
|
97
|
+
// 注册表查不到路径,即记即存与天级任务就静默停摆、days 永远不推进)
|
|
98
|
+
for (const p of brainPyCandidates()) {
|
|
99
|
+
if (existsSync(p)) return p
|
|
100
|
+
}
|
|
101
|
+
// ② 技能注册表(装了全局技能副本时更准;字段名跨版本不同,逐个试)
|
|
102
|
+
try {
|
|
103
|
+
const registry = ctx?.get?.('skills') ?? ctx?.skills
|
|
104
|
+
let items = registry?.list?.()
|
|
105
|
+
if (items?.then) items = await items
|
|
106
|
+
const hit = Array.isArray(items) ? items.find((s) => s?.name === 'lingshu') : null
|
|
107
|
+
if (hit) {
|
|
108
|
+
const bases = [
|
|
109
|
+
[hit.path, true], [hit.location, true],
|
|
110
|
+
[hit?.resourceBase?.path, false],
|
|
111
|
+
[hit.dir, false], [hit.baseDir, false], [hit.directory, false],
|
|
112
|
+
]
|
|
113
|
+
for (const [raw, isFile] of bases) {
|
|
114
|
+
if (typeof raw !== 'string' || !raw) continue
|
|
115
|
+
const root = isFile ? dirname(raw) : raw
|
|
116
|
+
const p = join(root, 'scripts', 'brain.py')
|
|
117
|
+
if (existsSync(p)) return p
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
} catch {}
|
|
121
|
+
return null
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** 有可能藏着 brain.py 的绝对路径清单(纯函数,测试与排障共用) */
|
|
125
|
+
export function brainPyCandidates() {
|
|
126
|
+
const out = [join(PACKAGE_ROOT, 'scripts', 'brain.py')]
|
|
127
|
+
const envDir = (process.env.LINGSHU_SKILL_DIR || '').trim()
|
|
128
|
+
if (envDir) out.push(join(envDir, 'scripts', 'brain.py'))
|
|
129
|
+
const home = homedir()
|
|
130
|
+
out.push(
|
|
131
|
+
join(home, '.dsh', 'skills', 'lingshu', 'scripts', 'brain.py'),
|
|
132
|
+
join(home, '.trae-cn', 'skills', 'lingshu', 'scripts', 'brain.py'),
|
|
133
|
+
)
|
|
134
|
+
return out
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** 有可能可用的 python 可执行文件清单(纯函数,测试与排障共用) */
|
|
138
|
+
export function pythonCandidates() {
|
|
139
|
+
const home = homedir()
|
|
140
|
+
const out = []
|
|
141
|
+
for (const app of [process.env.APP_DSH, join(home, '.dsh')].filter(Boolean)) {
|
|
142
|
+
out.push(join(app, 'app-runtimes', 'app-primary-runtime', 'dependencies', 'python', 'python.exe'))
|
|
143
|
+
out.push(join(app, 'runtimes', 'app-primary-runtime', 'dependencies', 'python', 'python.exe'))
|
|
144
|
+
}
|
|
145
|
+
// PATH 上的 python.exe / python3.exe(ServBay、Store、conda 等都能命中)。
|
|
146
|
+
// 不选 .cmd shim:spawn 走 CreateProcess,不解析 PATHEXT。
|
|
147
|
+
for (const dir of (process.env.PATH || '').split(delimiter)) {
|
|
148
|
+
if (!dir) continue
|
|
149
|
+
out.push(join(dir, 'python.exe'), join(dir, 'python3.exe'))
|
|
150
|
+
}
|
|
151
|
+
out.push(
|
|
152
|
+
join(home, 'AppData', 'Local', 'Programs', 'Python', 'python.exe'),
|
|
153
|
+
'C:\\Python313\\python.exe',
|
|
154
|
+
'C:\\Python312\\python.exe',
|
|
155
|
+
'C:\\Program Files\\Python313\\python.exe',
|
|
156
|
+
)
|
|
157
|
+
return out
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 静默失败留痕:写 ~/.dsh/lingshu-diag.json(doctor / 排障读它) */
|
|
161
|
+
export function writeDiag(kind, detail) {
|
|
162
|
+
try {
|
|
163
|
+
const base = process.env.APP_DSH || join(homedir(), '.dsh')
|
|
164
|
+
const payload = {
|
|
165
|
+
ts: new Date().toISOString(),
|
|
166
|
+
plugin: 'lingshu-cron',
|
|
167
|
+
kind,
|
|
168
|
+
detail: detail && typeof detail === 'object' ? detail : { message: String(detail ?? '') },
|
|
169
|
+
}
|
|
170
|
+
writeFileSync(join(base, 'lingshu-diag.json'), JSON.stringify(payload, null, 2), 'utf8')
|
|
171
|
+
} catch {}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* 天级任务失败留痕(P6 #49):写数据目录 lingshu.log,格式与 Python 的
|
|
176
|
+
* core.log_event 一致(JSONL: {ts秒, kind, level, msg, ...})。
|
|
177
|
+
* 原来 fire() 失败只记 state.retries、不写日志——doctor 报"补跑失败:backup"
|
|
178
|
+
* 时日志里 grep 不到任何线索,用户无法排查。失败必须可追溯。
|
|
179
|
+
*/
|
|
180
|
+
function logTaskFailure(taskId, detail) {
|
|
181
|
+
try {
|
|
182
|
+
const dir = memoryHome()
|
|
183
|
+
mkdirSync(dir, { recursive: true })
|
|
184
|
+
const row = {
|
|
185
|
+
ts: Math.floor(Date.now() / 1000),
|
|
186
|
+
kind: 'cron-task',
|
|
187
|
+
level: 'error',
|
|
188
|
+
msg: `天级任务 ${taskId} 执行失败:${String(detail || '未知原因').slice(0, 400)}`,
|
|
189
|
+
}
|
|
190
|
+
appendFileSync(join(dir, 'lingshu.log'), JSON.stringify(row) + '\n', 'utf8')
|
|
191
|
+
} catch {}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function findPythonExe(configured) {
|
|
195
|
+
if (configured) return existsSync(configured) ? configured : null
|
|
196
|
+
for (const p of pythonCandidates()) {
|
|
197
|
+
if (existsSync(p)) return p
|
|
198
|
+
}
|
|
199
|
+
return null
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ---------------------------------------------------------------- 状态落盘(APP profile 目录,不碰 ~/.brain-memory)
|
|
203
|
+
|
|
204
|
+
function statePath() {
|
|
205
|
+
const base = process.env.APP_DSH || join(homedir(), '.dsh')
|
|
206
|
+
return join(base, 'lingshu-cron-state.json')
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function loadState(path) {
|
|
210
|
+
try {
|
|
211
|
+
const raw = readFileSync(path, 'utf8')
|
|
212
|
+
const obj = JSON.parse(raw)
|
|
213
|
+
return obj && typeof obj === 'object' ? obj : {}
|
|
214
|
+
} catch {
|
|
215
|
+
return {}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function saveState(path, state) {
|
|
220
|
+
try {
|
|
221
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
222
|
+
const tmp = `${path}.${randomUUID()}.tmp`
|
|
223
|
+
writeFileSync(tmp, JSON.stringify(state, null, 2), 'utf8')
|
|
224
|
+
try { rmSync(path, { force: true }) } catch {}
|
|
225
|
+
renameSync(tmp, path) // 原子替换(同目录 rename)
|
|
226
|
+
} catch {}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const todayStr = () => new Date().toISOString().slice(0, 10)
|
|
230
|
+
|
|
231
|
+
/** agent 的稳定标识(用于状态落盘):拿不到稳定 id 就返回 null(仅内存计数)。 */
|
|
232
|
+
function agentKey(agent) {
|
|
233
|
+
const k = agent?.id ?? agent?.agentId ?? agent?.sessionId ?? agent?.session?.id
|
|
234
|
+
return typeof k === 'string' && k ? k : null
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function dueByDays(task, state) {
|
|
238
|
+
const last = state?.days?.[task.id]
|
|
239
|
+
return last !== todayStr()
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// 按小时间隔判定(P11 #72)。备份原来用 days:1 —— 只在"当天第一次回合"跑一次,
|
|
243
|
+
// 之后十几小时的写入完全裸奔(实测缺 17%)。改小时驱动后可按 config 调。
|
|
244
|
+
function dueByHours(task, state, hours) {
|
|
245
|
+
const h = Number(hours) || 0
|
|
246
|
+
if (h <= 0) return false
|
|
247
|
+
const last = Number(state?.hours?.[task.id] || 0)
|
|
248
|
+
if (!last) return true
|
|
249
|
+
return Date.now() - last >= h * 3600 * 1000
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// ---------------------------------------------------------------- 水位自动执行(影子模式 + 显式同意)
|
|
253
|
+
//
|
|
254
|
+
// 配置在 ~/.brain-memory/config.json 的 water 段(不是本插件的 config——改完
|
|
255
|
+
// 下一个水位档位即刻生效,不用重启宿主):
|
|
256
|
+
// "water": {"autoDream": false, "autoDreamConsent": false,
|
|
257
|
+
// "autoCapture": false, "autoCaptureConsent": false, "shadow": true}
|
|
258
|
+
// 语义(缺省全关,隐私默认安全):
|
|
259
|
+
// * autoXxx 与 autoXxxConsent 都缺省 false;shadow 缺省 true;
|
|
260
|
+
// * shadow=true 时只记"本来会做什么",绝不真执行;
|
|
261
|
+
// * 真执行必须 autoXxx && autoXxxConsent 同时为真,且 shadow=false;
|
|
262
|
+
// * 配置缺 water 段/字段类型不对(非布尔)一律回退上面这套默认值——
|
|
263
|
+
// 宁可不生效,也不从脏配置里"猜"一个 true 出来。
|
|
264
|
+
// 动作:
|
|
265
|
+
// * 首次跨 75%:满足执行条件就后台跑 dream --auto(沿用 runBrain 的 fire-and-forget,
|
|
266
|
+
// 绝不 await);否则只写一行影子台账(autoDream 全关时连台账都不写);
|
|
267
|
+
// * 首次跨 90%:capture 永不自动执行——capture 要的是会话原文,插件在 pre-step
|
|
268
|
+
// 只拿得到消息与水位、拿不到"原文",绝不自己拼凑;改为记一条"待人工确认的
|
|
269
|
+
// 逃生建议"并注入提醒一次,只有用户在会话里明确要求才真 capture。
|
|
270
|
+
// 台账:~/.brain-memory/water-auto.jsonl,每行 {ts, level, action, executed, reason};
|
|
271
|
+
// 超 512KB 轮转为 water-auto.jsonl.1(只留一份旧档,思路同 failures.py)。
|
|
272
|
+
|
|
273
|
+
const WATER_AUTO_LOG = 'water-auto.jsonl'
|
|
274
|
+
const WATER_AUTO_MAX_BYTES = 512 * 1024
|
|
275
|
+
|
|
276
|
+
const DEFAULT_WATER = {
|
|
277
|
+
autoDream: false,
|
|
278
|
+
autoDreamConsent: false,
|
|
279
|
+
autoCapture: false,
|
|
280
|
+
autoCaptureConsent: false,
|
|
281
|
+
shadow: true,
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** 记忆目录:BRAIN_MEMORY_HOME > ~/.brain-memory/.home 指针 > ~/.brain-memory(与 guard 同口径)。 */
|
|
285
|
+
function memoryHome() {
|
|
286
|
+
const env = (process.env.BRAIN_MEMORY_HOME || '').trim()
|
|
287
|
+
if (env) return env
|
|
288
|
+
const base = join(homedir(), '.brain-memory')
|
|
289
|
+
try {
|
|
290
|
+
const ptr = readFileSync(join(base, '.home'), 'utf8').trim()
|
|
291
|
+
if (ptr) return ptr
|
|
292
|
+
} catch {} // 没有指针文件就用默认目录
|
|
293
|
+
return base
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** 只认真正的布尔值:字符串 "true" / 数字 1 这类手写脏值一律回退默认(隐私开关宁可不生效)。 */
|
|
297
|
+
function boolOr(value, dflt) {
|
|
298
|
+
return typeof value === 'boolean' ? value : dflt
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** 合并默认值与 config.json 的 water 段;water 缺失/非对象/字段非法都回退默认。 */
|
|
302
|
+
function resolveWaterConfig(raw) {
|
|
303
|
+
const w = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw.water : null
|
|
304
|
+
const water = w && typeof w === 'object' && !Array.isArray(w) ? w : {}
|
|
305
|
+
const out = { ...DEFAULT_WATER }
|
|
306
|
+
for (const key of Object.keys(DEFAULT_WATER)) out[key] = boolOr(water[key], DEFAULT_WATER[key])
|
|
307
|
+
return out
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// config.json 很小,但 pre-step 每步都会问一次:按 mtime 缓存,文件没变不重读。
|
|
311
|
+
// 用户改完配置、mtime 变化后下一次判定即生效(冻结配置会让撤回同意变难)。
|
|
312
|
+
let waterConfigCache = { path: '', mtime: -1, value: DEFAULT_WATER }
|
|
313
|
+
|
|
314
|
+
function loadWaterAutoConfig() {
|
|
315
|
+
try {
|
|
316
|
+
const file = join(memoryHome(), 'config.json')
|
|
317
|
+
let mtime = -1
|
|
318
|
+
try { mtime = statSync(file).mtimeMs } catch { mtime = -1 }
|
|
319
|
+
if (waterConfigCache.path === file && waterConfigCache.mtime === mtime) return waterConfigCache.value
|
|
320
|
+
let raw = null
|
|
321
|
+
if (mtime >= 0) {
|
|
322
|
+
try { raw = JSON.parse(readFileSync(file, 'utf8')) } catch { raw = null } // 坏 JSON 视作没配
|
|
323
|
+
}
|
|
324
|
+
const value = resolveWaterConfig(raw)
|
|
325
|
+
waterConfigCache = { path: file, mtime, value }
|
|
326
|
+
return value
|
|
327
|
+
} catch {
|
|
328
|
+
return { ...DEFAULT_WATER }
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** 追加一行自动执行台账;超 512KB 先轮转成 water-auto.jsonl.1。台账 IO 失败绝不抛。 */
|
|
333
|
+
function recordWaterAuto(level, action, executed, reason) {
|
|
334
|
+
try {
|
|
335
|
+
const file = join(memoryHome(), WATER_AUTO_LOG)
|
|
336
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
337
|
+
try {
|
|
338
|
+
if (existsSync(file) && statSync(file).size > WATER_AUTO_MAX_BYTES) {
|
|
339
|
+
const old = `${file}.1`
|
|
340
|
+
try { rmSync(old, { force: true }) } catch {}
|
|
341
|
+
renameSync(file, old) // 只留一份旧档:失败可见化(failures.py)同款轮转
|
|
342
|
+
}
|
|
343
|
+
} catch {} // 轮转失败不拦记账:顶多当前文件继续长大
|
|
344
|
+
appendFileSync(file, JSON.stringify({
|
|
345
|
+
ts: new Date().toISOString(),
|
|
346
|
+
level, // 75 | 90
|
|
347
|
+
action, // 'dream --auto' | 'capture'
|
|
348
|
+
executed: executed === true, // true = 已投递后台执行(fire-and-forget 不回传成败)
|
|
349
|
+
reason: String(reason || ''), // executed / busy / shadow / no-consent / no-verbatim
|
|
350
|
+
}) + '\n', 'utf8')
|
|
351
|
+
} catch {} // 台账本身不能成为故障源
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// ---------------------------------------------------------------- 上下文压力(v3.57)
|
|
355
|
+
|
|
356
|
+
/** 压力阈值:与 scripts/core.py 的 PRESSURE_DEFAULTS **保持一致**;config 的
|
|
357
|
+
* pressure 段可覆盖。两边各写一份是因为插件不 import Python,注释互指即可。 */
|
|
358
|
+
const PRESSURE_DEFAULTS = { lazy_at: 70, minimal_at: 85, hard_at: 95, force_at: 98 }
|
|
359
|
+
|
|
360
|
+
/** 读 pressure 阈值(写坏/缺项一律回退默认,宁可不生效也不猜)。 */
|
|
361
|
+
export function pressureThresholds() {
|
|
362
|
+
let seg = {}
|
|
363
|
+
try {
|
|
364
|
+
const cfg = JSON.parse(readFileSync(join(memoryHome(), 'config.json'), 'utf8'))
|
|
365
|
+
const raw = cfg?.pressure
|
|
366
|
+
if (raw && typeof raw === 'object' && !Array.isArray(raw)) seg = raw
|
|
367
|
+
} catch {}
|
|
368
|
+
const out = { ...PRESSURE_DEFAULTS }
|
|
369
|
+
for (const key of Object.keys(PRESSURE_DEFAULTS)) {
|
|
370
|
+
const v = seg[key]
|
|
371
|
+
if (typeof v === 'boolean') continue
|
|
372
|
+
if (typeof v === 'number' && Number.isFinite(v) && v >= 1 && v <= 100) out[key] = v
|
|
373
|
+
}
|
|
374
|
+
out.minimal_at = Math.max(out.minimal_at, out.lazy_at)
|
|
375
|
+
out.hard_at = Math.max(out.hard_at, out.minimal_at)
|
|
376
|
+
out.force_at = Math.max(out.force_at, out.hard_at)
|
|
377
|
+
return out
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** 上次写 Pressure 的百分比(按 agent 记,避免每步都写盘)。 */
|
|
381
|
+
const pressureWritten = new Map()
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* 把水位写进 `HOME/_pressure.json`(注入侧读它降档)。
|
|
385
|
+
* 只在"跨 5 个百分点"或"跨档"时真写,减少磁盘写;失败静默返回 false。
|
|
386
|
+
*/
|
|
387
|
+
export function writePressure(pct, source, prevMax) {
|
|
388
|
+
try {
|
|
389
|
+
if (pct == null || !Number.isFinite(Number(pct))) return false
|
|
390
|
+
const p = Math.round(Number(pct))
|
|
391
|
+
const th = pressureThresholds()
|
|
392
|
+
const tier = p >= th.minimal_at ? 'minimal' : p >= th.lazy_at ? 'lazy' : 'full'
|
|
393
|
+
const key = `${tier}`
|
|
394
|
+
const last = pressureWritten.get('last')
|
|
395
|
+
if (last && last.tier === key && Math.abs(p - last.pct) < 5) return false
|
|
396
|
+
pressureWritten.set('last', { pct: p, tier: key })
|
|
397
|
+
const file = join(memoryHome(), '_pressure.json')
|
|
398
|
+
const tmp = `${file}.${randomUUID()}.tmp`
|
|
399
|
+
writeFileSync(tmp, JSON.stringify({ pct: p, at: Math.floor(Date.now() / 1000), source: String(source || '') }), 'utf8')
|
|
400
|
+
try { rmSync(file, { force: true }) } catch {}
|
|
401
|
+
renameSync(tmp, file)
|
|
402
|
+
return true
|
|
403
|
+
} catch { return false }
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* 98% 强制自救:只跑**没有破坏性**的两条——
|
|
408
|
+
* `auto-archive`:把审核通过的 pending 记忆按类型转正(原记忆只加 archived_at,不删)
|
|
409
|
+
* `memory diagnose`:只报告问题,不修复
|
|
410
|
+
* capture 永不自动(插件拿不到会话原文),purge 永不自动(物理删除)。
|
|
411
|
+
*/
|
|
412
|
+
export function forceActions() {
|
|
413
|
+
return [
|
|
414
|
+
{ id: 'autoarchive', argv: ['auto-archive'] },
|
|
415
|
+
{ id: 'diagnose', argv: ['memory', 'diagnose'] },
|
|
416
|
+
]
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* 90% 的"待人工确认的逃生建议":说明为什么不由插件 capture,并给出人工确认后的命令。
|
|
421
|
+
*/function escapeSuggestion(pct, source) {
|
|
422
|
+
const from = source === 'usage' ? '宿主 usage' : '消息字符估算'
|
|
423
|
+
return `【灵枢·水位 90% 逃生建议】上下文估算约 ${pct}%(来源:${from})。`
|
|
424
|
+
+ '封存 capture 需要会话原文,插件拿不到正文、也绝不替你拼凑,所以这里只提醒、不自动执行。'
|
|
425
|
+
+ '请先问用户是否现在封存;用户明确要求后,由你把原文原样贴进命令再跑:'
|
|
426
|
+
+ ' python scripts/brain.py capture "<把原文粘进来>" --tag 逃生 --kind episode'
|
|
427
|
+
+ '(每次会话只提醒这一次;autoCapture 开关只代表"允许考虑自动封存",但 capture 永不自动调用。)'
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// ---------------------------------------------------------------- 子进程(照抄 lingshu-startup 的 spawn 方案)
|
|
431
|
+
|
|
432
|
+
function runBrain(pythonExe, pythonCmdFallback, brainPy, argv, timeoutMs) {
|
|
433
|
+
return new Promise((resolve) => {
|
|
434
|
+
let settled = false
|
|
435
|
+
const done = (v) => { if (!settled) { settled = true; resolve(v) } }
|
|
436
|
+
const args = [brainPy, ...argv]
|
|
437
|
+
let child
|
|
438
|
+
try {
|
|
439
|
+
if (pythonExe) {
|
|
440
|
+
child = spawn(pythonExe, args, {
|
|
441
|
+
windowsHide: true,
|
|
442
|
+
env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
|
|
443
|
+
// 显式把工作目录挪到用户主目录:绝不继承宿主 cwd。宿主 cwd 若在插件
|
|
444
|
+
// 目录内,Windows 会因"目录被进程占用"拒绝 pnpm 的目录 rename,
|
|
445
|
+
// 导致市场更新(remove+add)报"文件被占用、请退出 DSH"。
|
|
446
|
+
cwd: homedir(),
|
|
447
|
+
})
|
|
448
|
+
} else {
|
|
449
|
+
const comspec = process.env.ComSpec ?? 'cmd.exe'
|
|
450
|
+
const pythonCmd = pythonCmdFallback || 'python'
|
|
451
|
+
const cmdline = [`"${pythonCmd}"`, ...args.map((a) => `"${a}"`)].join(' ')
|
|
452
|
+
child = spawn(comspec, ['/d', '/s', '/c', cmdline], {
|
|
453
|
+
windowsHide: true,
|
|
454
|
+
windowsVerbatimArguments: true,
|
|
455
|
+
env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
|
|
456
|
+
cwd: homedir(), // 同上:不把宿主 cwd(可能在插件目录内)占给子进程
|
|
457
|
+
})
|
|
458
|
+
}
|
|
459
|
+
} catch {
|
|
460
|
+
return done(null)
|
|
461
|
+
}
|
|
462
|
+
let out = ''
|
|
463
|
+
child.stdout?.on('data', (d) => { out += d.toString('utf8') })
|
|
464
|
+
child.stderr?.resume() // 必须 drain:塞满 64KB 管道子进程会写阻塞永不退出
|
|
465
|
+
child.on('error', () => done(null))
|
|
466
|
+
// 手动超时兜底:taskkill /T /F 杀整棵进程树(cmd 兜底分支里的 python 孙进程也要杀)
|
|
467
|
+
const killer = setTimeout(() => {
|
|
468
|
+
try {
|
|
469
|
+
if (child.pid) {
|
|
470
|
+
const tk = spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
|
|
471
|
+
tk.on('error', () => {})
|
|
472
|
+
}
|
|
473
|
+
} catch {}
|
|
474
|
+
try { child.kill() } catch {}
|
|
475
|
+
done(null)
|
|
476
|
+
}, timeoutMs)
|
|
477
|
+
killer.unref?.()
|
|
478
|
+
child.on('close', (code) => {
|
|
479
|
+
clearTimeout(killer)
|
|
480
|
+
done(code === 0 || code === 10 ? out : null)
|
|
481
|
+
})
|
|
482
|
+
})
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// ---------------------------------------------------------------- 注入消息构造(与 lingshu-startup 同格式)
|
|
486
|
+
|
|
487
|
+
function notice(text) {
|
|
488
|
+
return {
|
|
489
|
+
id: randomUUID(),
|
|
490
|
+
role: 'user',
|
|
491
|
+
content: [{ type: 'text', text }],
|
|
492
|
+
source: { kind: 'skill-invocation', name: INJECT_SOURCE, form: 'instructions' },
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// ---------------------------------------------------------------- 插件主体
|
|
497
|
+
|
|
498
|
+
export function apply(ctx, config) {
|
|
499
|
+
// v3.23:重复挂载守卫。profile 里同时启用独立包 dsh-lingshu-startup 与 lingshu-skill
|
|
500
|
+
// (根包 index.js 内部也挂 startup/cron)时,同一进程会出现两份 cron:
|
|
501
|
+
// 定时任务重复跑、水位提醒重复注入。进程级只允许一份。
|
|
502
|
+
if (globalThis.__lingshuCronApplied) {
|
|
503
|
+
try { ctx.logger?.warn?.('lingshu-cron: 已有一份灵枢 cron 在运行,跳过重复挂载') } catch {}
|
|
504
|
+
return
|
|
505
|
+
}
|
|
506
|
+
globalThis.__lingshuCronApplied = true
|
|
507
|
+
const cfg = mergeConfig(config)
|
|
508
|
+
|
|
509
|
+
const turns = new Map() // agent -> 本会话轮次
|
|
510
|
+
const running = new Set() // 防并发:同名任务进行中就不重入
|
|
511
|
+
const convo = new Map() // agent -> { text, seen }(即记即存缓冲 + 已处理消息游标,extract 成功后清空)
|
|
512
|
+
const lastReply = new Map() // agent -> 最后一条 assistant 文本(给 usage --reply 用)
|
|
513
|
+
const waterState = new Map() // agent -> { max } 水位守卫已提醒的最高档(60/75/90 各提醒一次)
|
|
514
|
+
// v3.57:review 提醒已发过的 agent(每会话一次,不再每轮催)
|
|
515
|
+
const reviewNoticeAt = new Map()
|
|
516
|
+
const waterAutoState = new Map() // agent -> { max } 水位自动执行已处理到的最高档(75/90 各动作一次)
|
|
517
|
+
let state = loadState(statePath())
|
|
518
|
+
|
|
519
|
+
// 启动时清理崩溃残留的 extract 明文临时文件(超过 1 天的直接删)
|
|
520
|
+
try {
|
|
521
|
+
const base = process.env.APP_DSH || join(homedir(), '.dsh')
|
|
522
|
+
const cutoff = Date.now() - 24 * 3600 * 1000
|
|
523
|
+
for (const f of readdirSync(base)) {
|
|
524
|
+
if (!f.startsWith('lingshu-extract-') || !f.endsWith('.txt')) continue
|
|
525
|
+
const p = join(base, f)
|
|
526
|
+
try {
|
|
527
|
+
if (statSync(p).mtimeMs < cutoff) rmSync(p, { force: true })
|
|
528
|
+
} catch {}
|
|
529
|
+
}
|
|
530
|
+
} catch {}
|
|
531
|
+
let brainPyCache = null
|
|
532
|
+
let warnedOnce = false
|
|
533
|
+
let warnedNoBrain = false
|
|
534
|
+
|
|
535
|
+
// 状态节流落盘器(#69):变更只置脏,30 秒合并刷盘,避免每轮 turn-stopping 都写磁盘
|
|
536
|
+
const stateSaver = (() => {
|
|
537
|
+
let dirty = false
|
|
538
|
+
let timer = null
|
|
539
|
+
const flush = () => {
|
|
540
|
+
timer = null
|
|
541
|
+
if (!dirty) return
|
|
542
|
+
dirty = false
|
|
543
|
+
saveState(statePath(), state)
|
|
544
|
+
}
|
|
545
|
+
return {
|
|
546
|
+
markDirty() {
|
|
547
|
+
dirty = true
|
|
548
|
+
if (!timer) {
|
|
549
|
+
timer = setTimeout(flush, 30_000)
|
|
550
|
+
if (timer?.unref) timer.unref()
|
|
551
|
+
}
|
|
552
|
+
},
|
|
553
|
+
flushNow: flush,
|
|
554
|
+
}
|
|
555
|
+
})()
|
|
556
|
+
const markStateDirty = () => stateSaver.markDirty()
|
|
557
|
+
|
|
558
|
+
// review --json 缓存(pre-step 每步都问,30s 内复用)
|
|
559
|
+
let reviewCacheAt = 0
|
|
560
|
+
let reviewCacheVal = null
|
|
561
|
+
|
|
562
|
+
// 重启恢复(#77):state.turns 本身就是事实源,turn-stopping 直接读它续算,无需 seed 拷贝
|
|
563
|
+
|
|
564
|
+
const warn = (msg) => { if (!warnedOnce) { warnedOnce = true; try { ctx.logger?.warn?.(msg) } catch {} } }
|
|
565
|
+
|
|
566
|
+
async function ensureBrainPy() {
|
|
567
|
+
if (brainPyCache) return brainPyCache
|
|
568
|
+
const found = await findBrainPy(cfg.brainPy, ctx)
|
|
569
|
+
if (!found) {
|
|
570
|
+
// 静默失败必须留痕:这是 2026-11-20「记忆突然不录入了」的直接证据来源
|
|
571
|
+
if (!warnedNoBrain) {
|
|
572
|
+
warnedNoBrain = true
|
|
573
|
+
writeDiag('brainPy-not-found', {
|
|
574
|
+
tried: brainPyCandidates(),
|
|
575
|
+
packageRoot: PACKAGE_ROOT,
|
|
576
|
+
configured: cfg.brainPy || null,
|
|
577
|
+
})
|
|
578
|
+
warn('lingshu-cron: 未找到 brain.py(未安装灵枢?),调度跳过')
|
|
579
|
+
}
|
|
580
|
+
return null
|
|
581
|
+
}
|
|
582
|
+
brainPyCache = found
|
|
583
|
+
return found
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/** fire-and-forget:绝不 await、失败允许下轮补跑一次(当日仅一次,再败等明天)。
|
|
587
|
+
* 返回 false 表示同名任务正在进行、本次没有投递(供水位自动执行如实记账)。 */
|
|
588
|
+
function fire(task) {
|
|
589
|
+
if (running.has(task.id)) return false
|
|
590
|
+
running.add(task.id)
|
|
591
|
+
;(async () => {
|
|
592
|
+
try {
|
|
593
|
+
const brainPy = await ensureBrainPy()
|
|
594
|
+
if (!brainPy) {
|
|
595
|
+
// P6 #49:失败必须留痕(原来直接 return,静默)
|
|
596
|
+
logTaskFailure(task.id, '找不到 brain.py(未安装或路径配置错误)')
|
|
597
|
+
return
|
|
598
|
+
}
|
|
599
|
+
const pythonExe = findPythonExe(cfg.python)
|
|
600
|
+
const out = await runBrain(pythonExe, cfg.python, brainPy, task.argv, cfg.timeoutMs)
|
|
601
|
+
// 退出码 0/10 才算跑成;失败不标记完成,下轮补跑一次,再失败就等明天
|
|
602
|
+
// (state.retries 记当日已补跑次数,防持续失败造成备份/做梦风暴)。
|
|
603
|
+
if (task.days) {
|
|
604
|
+
state.days = state.days || {}
|
|
605
|
+
if (out !== null) {
|
|
606
|
+
state.days[task.id] = todayStr()
|
|
607
|
+
if (state.retries) delete state.retries[task.id]
|
|
608
|
+
} else {
|
|
609
|
+
state.retries = state.retries || {}
|
|
610
|
+
const r = state.retries[task.id] || { date: todayStr(), count: 0 }
|
|
611
|
+
if (r.date !== todayStr()) { r.date = todayStr(); r.count = 0 }
|
|
612
|
+
r.count += 1
|
|
613
|
+
state.retries[task.id] = r
|
|
614
|
+
// P6 #49:写 lingshu.log——doctor 报"补跑失败"时用户能查到原因
|
|
615
|
+
logTaskFailure(task.id, `brain.py 退出码非 0/10(argv: ${JSON.stringify(task.argv || []).slice(0, 160)};补跑第 ${r.count} 次)`)
|
|
616
|
+
if (r.count >= 1) state.days[task.id] = todayStr() // 已补跑过一次,今天不再纠缠
|
|
617
|
+
}
|
|
618
|
+
stateSaver.flushNow() // 天级任务低频,立即落盘保证不丢标记
|
|
619
|
+
}
|
|
620
|
+
// 小时级任务(备份/自动更新)单独记时间戳:与 days 互不干扰
|
|
621
|
+
if (task.hours) {
|
|
622
|
+
state.hours = state.hours || {}
|
|
623
|
+
if (out !== null) {
|
|
624
|
+
state.hours[task.id] = Date.now()
|
|
625
|
+
if (state.retries) delete state.retries[task.id]
|
|
626
|
+
} else {
|
|
627
|
+
state.retries = state.retries || {}
|
|
628
|
+
const r = state.retries[task.id] || { date: todayStr(), count: 0 }
|
|
629
|
+
if (r.date !== todayStr()) { r.date = todayStr(); r.count = 0 }
|
|
630
|
+
r.count += 1
|
|
631
|
+
state.retries[task.id] = r
|
|
632
|
+
logTaskFailure(task.id, `小时级任务失败(补跑第 ${r.count} 次)`)
|
|
633
|
+
}
|
|
634
|
+
stateSaver.flushNow()
|
|
635
|
+
}
|
|
636
|
+
} catch (err) {
|
|
637
|
+
// P6 #49:顶层异常也不能静默——写日志后照旧吞掉(守卫语义:异常不冒泡)
|
|
638
|
+
logTaskFailure(task.id, `执行异常:${err?.message || String(err)}`)
|
|
639
|
+
}
|
|
640
|
+
finally {
|
|
641
|
+
running.delete(task.id)
|
|
642
|
+
}
|
|
643
|
+
})()
|
|
644
|
+
return true
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* v3.57(保护 B 的执行端):98% 强制自救——**同步 await**(与 fire 的 fire-and-forget
|
|
649
|
+
* 不同:这里必须等结果,才能把"做了什么"如实告诉模型)。只跑无破坏性动作。
|
|
650
|
+
* 返回一行摘要(失败也返回,说明失败了几个),绝不抛异常。
|
|
651
|
+
*/
|
|
652
|
+
async function runForceActions(pythonExe, brainPy) {
|
|
653
|
+
const done = []
|
|
654
|
+
const failed = []
|
|
655
|
+
for (const task of forceActions()) {
|
|
656
|
+
try {
|
|
657
|
+
const out = await runBrain(pythonExe, cfg.python, brainPy, task.argv, cfg.timeoutMs)
|
|
658
|
+
if (out === null) failed.push(task.id)
|
|
659
|
+
else {
|
|
660
|
+
// 取首行当摘要,避免把整段输出灌进上下文
|
|
661
|
+
const line = String(out).trim().split(/\r?\n/).find((x) => x.trim()) || task.id
|
|
662
|
+
done.push(line.trim().slice(0, 60))
|
|
663
|
+
}
|
|
664
|
+
} catch { failed.push(task.id) }
|
|
665
|
+
}
|
|
666
|
+
const parts = []
|
|
667
|
+
if (done.length) parts.push(done.join(';'))
|
|
668
|
+
if (failed.length) parts.push(`失败:${failed.join('、')}(可手工重试)`)
|
|
669
|
+
return parts.join('。')
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* 水位自动执行判定(首次跨档才做一次)。纯同步返回要注入的提醒文本(null = 不注入);
|
|
674
|
+
* 真执行一律走 fire() 的后台通道,绝不 await。
|
|
675
|
+
* - 75%:autoDream && autoDreamConsent && shadow=false → fire `dream --auto`;
|
|
676
|
+
* 否则若 autoDream 开着,只记影子台账(executed=false,reason=shadow/no-consent);
|
|
677
|
+
* autoDream 关着就什么都不记(缺省全关 = 零副作用)。
|
|
678
|
+
* - 90%:capture 永不自动执行——插件拿不到会话原文,绝不自己拼;
|
|
679
|
+
* 只记 executed=false(reason=no-verbatim)并返回一次"待人工确认的逃生建议"。
|
|
680
|
+
* 两个 auto 开关都关时整段不判定、不写盘。
|
|
681
|
+
*/
|
|
682
|
+
function runWaterAuto(agent, pct, source, wcfg) {
|
|
683
|
+
if (!agent || pct == null) return null
|
|
684
|
+
const armed = wcfg.autoDream === true || wcfg.autoCapture === true
|
|
685
|
+
if (!armed) return null // 默认全关:不判定、不写盘
|
|
686
|
+
const level = pct >= 90 ? 90 : pct >= 75 ? 75 : 0
|
|
687
|
+
if (!level) return null
|
|
688
|
+
const st = waterAutoState.get(agent) || { max: 0 }
|
|
689
|
+
const prev = Number(st.max) || 0
|
|
690
|
+
if (level <= prev) return null // 档位只推进一次(首次跨 75/90 各做一次)
|
|
691
|
+
let noticeText = null
|
|
692
|
+
// 75%:该做梦了。直接从低位跳到 90% 时也补做这一档(prev < 75)。
|
|
693
|
+
// 复用 turn-stopping 那条任务名 'dream':全局同一时刻只许一份 dream 在跑
|
|
694
|
+
// (与轮次驱动的 dream 撞车时返回 busy,如实记 executed=false)。
|
|
695
|
+
if (level >= 75 && prev < 75 && wcfg.autoDream === true) {
|
|
696
|
+
const consent = wcfg.autoDreamConsent === true
|
|
697
|
+
if (consent && wcfg.shadow === false) {
|
|
698
|
+
const fired = fire({ id: 'dream', argv: ['dream', '--auto'] })
|
|
699
|
+
recordWaterAuto(75, 'dream --auto', fired, fired ? 'executed' : 'busy')
|
|
700
|
+
} else {
|
|
701
|
+
// 影子模式或没给同意:只记"本来会做什么",不动手
|
|
702
|
+
recordWaterAuto(75, 'dream --auto', false, consent ? 'shadow' : 'no-consent')
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
// 90%:该封存了,但 capture 需要原文 —— 插件永不自动拼,交人工确认。
|
|
706
|
+
if (level >= 90 && wcfg.autoCapture === true) {
|
|
707
|
+
recordWaterAuto(90, 'capture', false, 'no-verbatim')
|
|
708
|
+
noticeText = escapeSuggestion(pct, source)
|
|
709
|
+
}
|
|
710
|
+
waterAutoState.set(agent, { max: level })
|
|
711
|
+
return noticeText
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/**
|
|
715
|
+
* 即记即存:把攒的对话文本写到临时文件,静默跑 brain.py extract
|
|
716
|
+
* (惊异门控 + capture 逐段去重都在 Python 侧)。成功后清空缓冲,
|
|
717
|
+
* 失败保留缓冲下轮重试。fire-and-forget 三铁律同样适用。
|
|
718
|
+
*/
|
|
719
|
+
function fireExtract(agent) {
|
|
720
|
+
if (running.has('extract')) return
|
|
721
|
+
const buf = convo.get(agent)
|
|
722
|
+
const text = (buf?.text || '').trim()
|
|
723
|
+
if (!text || text.length < cfg.extractMinChars) return // 没攒够有信息量的内容,不跑
|
|
724
|
+
running.add('extract')
|
|
725
|
+
;(async () => {
|
|
726
|
+
let ok = false
|
|
727
|
+
try {
|
|
728
|
+
const brainPy = await ensureBrainPy()
|
|
729
|
+
if (!brainPy) return
|
|
730
|
+
// 临时文件放 APP profile 目录(与状态文件同层),用完由 brain.py 删除
|
|
731
|
+
const base = process.env.APP_DSH || join(homedir(), '.dsh')
|
|
732
|
+
mkdirSync(base, { recursive: true })
|
|
733
|
+
const tmp = join(base, `lingshu-extract-${randomUUID()}.txt`)
|
|
734
|
+
try {
|
|
735
|
+
writeFileSync(tmp, text, 'utf8')
|
|
736
|
+
const pythonExe = findPythonExe(cfg.python)
|
|
737
|
+
const out = await runBrain(pythonExe, cfg.python, brainPy,
|
|
738
|
+
['extract', '--file', tmp, '--min-chars', String(cfg.extractMinChars)],
|
|
739
|
+
cfg.timeoutMs)
|
|
740
|
+
// 只有退出码 0/10(写入成功/惊异未过门)才算跑成;失败保留缓冲,
|
|
741
|
+
// 下个 extractTurns 周期重试——原逻辑把错误退出也当成功清缓冲,会丢对话。
|
|
742
|
+
ok = out !== null
|
|
743
|
+
} finally {
|
|
744
|
+
try { rmSync(tmp, { force: true }) } catch {}
|
|
745
|
+
}
|
|
746
|
+
} catch {} // 顶层兜底
|
|
747
|
+
finally {
|
|
748
|
+
if (ok) convo.set(agent, { text: '', seen: buf?.seen }) // 清空缓冲,但保留游标(防止重复攒旧消息)
|
|
749
|
+
else if (text.length > 200_000) {
|
|
750
|
+
// 兜底防爆内存:截断保留头部 100k 而非全丢,并至少告警一次(#64)
|
|
751
|
+
try { logger.warn(`[lingshu-cron] extract 失败且缓冲超 200k,截断保留前 100k 字符(已丢失 ${(text.length - 100_000)} 字符)`) } catch {}
|
|
752
|
+
convo.set(agent, { text: text.slice(0, 100_000), seen: buf?.seen })
|
|
753
|
+
}
|
|
754
|
+
running.delete('extract')
|
|
755
|
+
}
|
|
756
|
+
})()
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
// 每轮结束:轮次驱动的静默任务(dream / usage)+ 天驱动任务(daily/backup/conflicts/selfreview)
|
|
760
|
+
ctx.on('agent/turn-stopping', (payload) => {
|
|
761
|
+
try {
|
|
762
|
+
const agent = payload?.agent
|
|
763
|
+
if (!agent) return
|
|
764
|
+
const ak = agentKey(agent)
|
|
765
|
+
// 轮数唯一事实源是状态文件 state.turns[ak](#77):重启续算不再依赖内存 map,
|
|
766
|
+
// 内存 turns 只在拿不到稳定 ak 时兜底,避免双轨计数互相回退。
|
|
767
|
+
let prev
|
|
768
|
+
if (ak && Number.isFinite(Number(state.turns?.[ak]))) prev = Number(state.turns[ak])
|
|
769
|
+
else prev = turns.get(agent) ?? 0
|
|
770
|
+
const n = prev + 1
|
|
771
|
+
turns.set(agent, n)
|
|
772
|
+
// 轮数落盘:节流写(30s 合并刷盘,#69),重启后按状态文件续算
|
|
773
|
+
if (ak) {
|
|
774
|
+
state.turns = state.turns || {}
|
|
775
|
+
if (state.turns[ak] !== n) {
|
|
776
|
+
state.turns[ak] = n
|
|
777
|
+
markStateDirty()
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
const silentTasks = [
|
|
782
|
+
{ id: 'dream', turns: cfg.dreamTurns, argv: ['dream', '--auto'] },
|
|
783
|
+
{ id: 'daily', days: 1, argv: ['daily'] },
|
|
784
|
+
// 备份:按小时(config.backup_interval_hours,默认 6),不再是"每天一次"
|
|
785
|
+
{ id: 'backup', hours: cfg.backupIntervalHours ?? 6, argv: ['backup'] },
|
|
786
|
+
// 自动更新:默认关(config.auto_update=false 时 auto-update 自己会跳过)
|
|
787
|
+
{ id: 'autoupdate', hours: cfg.autoUpdateIntervalHours ?? 24, argv: ['auto-update'] },
|
|
788
|
+
{ id: 'conflicts', days: 1, argv: ['detect-conflicts'] },
|
|
789
|
+
{ id: 'selfreview', days: cfg.selfReviewDays, argv: ['skill', 'self-review'] },
|
|
790
|
+
// 第④步:每日静默 persona drift —— 扫描近 1 天记忆的情感倾向,
|
|
791
|
+
// 微调 state.mood_score(0=阴郁 100=明快),真实变化才落盘并记账
|
|
792
|
+
{ id: 'drift', days: 1, argv: ['drift', '--days', '1'] },
|
|
793
|
+
// 第⑤步:每日自动归档 —— 把审核通过的 pending 记忆按"事实型→知识库 /
|
|
794
|
+
// 事件型→日记"分类转正(原记忆只加 archived_at 标记,绝不删)
|
|
795
|
+
{ id: 'autoarchive', days: 1, argv: ['auto-archive'] },
|
|
796
|
+
]
|
|
797
|
+
for (const t of silentTasks) {
|
|
798
|
+
if (t.turns && n % t.turns === 0) fire(t)
|
|
799
|
+
if (t.days && dueByDays(t, state)) fire(t)
|
|
800
|
+
if (t.hours && dueByHours(t, state, t.hours)) fire(t)
|
|
801
|
+
}
|
|
802
|
+
if (cfg.runUsage) {
|
|
803
|
+
// usage --reply 用"最后一条 assistant 回复"的真实文本统计记忆是否被用上;
|
|
804
|
+
// 传空串会导致关键词重叠恒 0、每条记忆都记成"没被用上",污染使用率统计。
|
|
805
|
+
// 没有真实回复文本时宁可跳过本轮,也不给假数据。
|
|
806
|
+
const reply = (lastReply.get(agent) || '').trim()
|
|
807
|
+
if (reply) fire({ id: 'usage', argv: ['usage', '--reply', reply.slice(0, 4000)] })
|
|
808
|
+
}
|
|
809
|
+
// 即记即存:每 N 轮把攒的对话文本静默封存进海马体
|
|
810
|
+
if (cfg.extractTurns > 0 && n % cfg.extractTurns === 0) fireExtract(agent)
|
|
811
|
+
} catch {} // turn-stopping 是串行事件,任何异常都不能拖住回合关闭
|
|
812
|
+
})
|
|
813
|
+
|
|
814
|
+
// 水位估算:宿主给了 usage 就用真值(prompt 侧 = 未缓存 + 缓存读 + 缓存写);
|
|
815
|
+
// 否则按「消息正文字符数 + system/工具固定开销」折算。
|
|
816
|
+
// v3.23 修:旧版只数 messages 的 text 字符,system prompt 与工具 schema 完全不计,
|
|
817
|
+
// 而本 profile 光这两项就上万 token —— 真实 65% 时估算只有 20%,阈值永远不触发。
|
|
818
|
+
// 返回 {pct, source};拿不到任何依据返回 null。
|
|
819
|
+
function estimateWater(agent, decision) {
|
|
820
|
+
try {
|
|
821
|
+
const msgs = Array.isArray(decision?.messages) ? decision.messages : []
|
|
822
|
+
const num = (x) => (Number.isFinite(x) ? x : 0)
|
|
823
|
+
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
824
|
+
const u = msgs[i]?.metadata?.usage || msgs[i]?.usage || msgs[i]?.modelUsage
|
|
825
|
+
|| msgs[i]?.metadata?.modelUsage
|
|
826
|
+
if (!u || typeof u !== 'object') continue
|
|
827
|
+
const prompt = num(u.inputTokens ?? u.promptTokens) + num(u.cacheReadTokens)
|
|
828
|
+
+ num(u.cacheWriteTokens)
|
|
829
|
+
const total = num(u.totalTokens)
|
|
830
|
+
const used = total > 0 ? total : prompt
|
|
831
|
+
if (used > 0) {
|
|
832
|
+
return { pct: Math.min(100, Math.round(used / cfg.contextLimit * 100)), source: 'usage' }
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
let chars = 0
|
|
836
|
+
for (const m of msgs) {
|
|
837
|
+
// 估算只看"真实对话":灵枢自己注入的消息不算(v3.59:三个子插件各有名字)
|
|
838
|
+
if (LINGSHU_SOURCES.has(m?.source?.name)) continue
|
|
839
|
+
for (const c of (Array.isArray(m?.content) ? m.content : [])) {
|
|
840
|
+
if (c?.type === 'text' && typeof c.text === 'string') chars += c.text.length
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
if (!chars) {
|
|
844
|
+
// v3.57(保护 C):原来这里直接 return null,守卫就此静默跳过——「以为没到水位,
|
|
845
|
+
// 其实已经快满」正是要防的情况。现在至少按 system/工具固定开销给一个下限
|
|
846
|
+
// (拿不到正文时它也是真实存在的成本),并标明来源,让提醒口径说实话。
|
|
847
|
+
const floor = Number(cfg.systemOverheadTokens) || 0
|
|
848
|
+
if (!floor) return null
|
|
849
|
+
return { pct: Math.min(100, Math.round(floor / cfg.contextLimit * 100)), source: 'floor' }
|
|
850
|
+
}
|
|
851
|
+
const tokens = chars / cfg.charsPerToken + (cfg.systemOverheadTokens || 0)
|
|
852
|
+
return { pct: Math.min(100, Math.round(tokens / cfg.contextLimit * 100)), source: 'chars' }
|
|
853
|
+
} catch { return null }
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
// 注入类:只在 enter 分支追加消息,有内容才注,缓存 review 查询
|
|
857
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
858
|
+
let decision
|
|
859
|
+
try {
|
|
860
|
+
decision = await next()
|
|
861
|
+
if (!decision || decision.kind !== 'enter') return decision
|
|
862
|
+
const { agent } = payload || {}
|
|
863
|
+
if (!agent) return decision
|
|
864
|
+
|
|
865
|
+
// 上下文清理(v3.59 起默认关闭):只清**本插件自己**注入过的旧提醒。
|
|
866
|
+
// 两个要点:
|
|
867
|
+
// 1. 只认 `INJECT_SOURCE`('lingshu-cron'),绝不碰 startup 的
|
|
868
|
+
// 'lingshu-startup' 记忆块,也不碰 im 的 'lingshu-im';
|
|
869
|
+
// 2. 默认不执行——删历史中段的消息会改写提示词缓存前缀,后续全部无法
|
|
870
|
+
// 复用(见 DEFAULTS 里 pruneInjected 的说明)。用户显式开启才清。
|
|
871
|
+
try {
|
|
872
|
+
if (cfg.pruneInjected) {
|
|
873
|
+
const msgs = Array.isArray(decision.messages) ? decision.messages : []
|
|
874
|
+
const kept = msgs.filter((m) => m?.source?.name !== INJECT_SOURCE)
|
|
875
|
+
if (kept.length !== msgs.length) {
|
|
876
|
+
decision = { ...decision, messages: kept }
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
} catch {}
|
|
880
|
+
// 即记即存缓冲:只攒"本步新增"的文本——按消息 id 记游标,重复推送的旧消息
|
|
881
|
+
// 不重复入缓冲(否则缓冲膨胀、extract 内容重复)。同时记录最后一条
|
|
882
|
+
// assistant 文本给 usage --reply 用(usage 需要真实回复,不能传空串)。
|
|
883
|
+
try {
|
|
884
|
+
const msgs = Array.isArray(decision.messages) ? decision.messages : []
|
|
885
|
+
if (msgs.length) {
|
|
886
|
+
const buf = convo.get(agent) || { text: '', seen: [] }
|
|
887
|
+
const seenIds = new Set(Array.isArray(buf.seen) ? buf.seen : [])
|
|
888
|
+
let text = buf.text
|
|
889
|
+
let lastAsst = lastReply.get(agent) || ''
|
|
890
|
+
let batchIds = []
|
|
891
|
+
for (const m of msgs) {
|
|
892
|
+
const mid = m?.id
|
|
893
|
+
if (mid != null) {
|
|
894
|
+
if (seenIds.has(mid)) continue // 上一步已攒过这条,跳过(只加增量)
|
|
895
|
+
batchIds.push(mid)
|
|
896
|
+
}
|
|
897
|
+
for (const c of (Array.isArray(m?.content) ? m.content : [])) {
|
|
898
|
+
if (c?.type === 'text' && typeof c.text === 'string' && c.text.trim()) {
|
|
899
|
+
const t = c.text.trim()
|
|
900
|
+
if (m.role === 'assistant') lastAsst = t.slice(0, 4000)
|
|
901
|
+
text += (text ? '\n' : '') + m.role + ':' + t.slice(0, 4000) + '\n'
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
// 游标:只保留最近几批的 id(防无限增长),本批新 id 全部记入
|
|
906
|
+
if (batchIds.length) {
|
|
907
|
+
seenIds.add(`\0batch:${JSON.stringify(batchIds)}`)
|
|
908
|
+
}
|
|
909
|
+
convo.set(agent, {
|
|
910
|
+
text,
|
|
911
|
+
seen: [...seenIds].slice(-16), // 最近 16 个批次标记足够覆盖重推场景
|
|
912
|
+
})
|
|
913
|
+
if (lastAsst) lastReply.set(agent, lastAsst)
|
|
914
|
+
}
|
|
915
|
+
} catch {}
|
|
916
|
+
|
|
917
|
+
const n = (turns.get(agent) ?? 1)
|
|
918
|
+
const brainPy = await ensureBrainPy()
|
|
919
|
+
if (!brainPy) return decision
|
|
920
|
+
const pythonExe = findPythonExe(cfg.python)
|
|
921
|
+
|
|
922
|
+
// 0) 水位估算:注入与自动执行共用同一口径(宿主 usage 优先,否则
|
|
923
|
+
// 「消息字符 + system/工具固定开销」)。只在需要时才算:waterGuard 关闭
|
|
924
|
+
// 且 water 自动执行全关时,默认零开销。
|
|
925
|
+
const waterAutoCfg = loadWaterAutoConfig()
|
|
926
|
+
const waterArmed = waterAutoCfg.autoDream === true || waterAutoCfg.autoCapture === true
|
|
927
|
+
const est = (cfg.waterGuard || waterArmed) ? estimateWater(agent, decision) : null
|
|
928
|
+
const pct = est && Number.isFinite(est.pct) ? est.pct : null
|
|
929
|
+
|
|
930
|
+
// 1) 水位自动执行(v3.44,默认全关):放在 review 之前判定——review 有待确认时
|
|
931
|
+
// 会提前 return,不能让它挡掉「75% 该做梦 / 90% 该逃生」的自动动作。
|
|
932
|
+
// 真执行走 fire() 的后台通道,绝不 await。
|
|
933
|
+
try {
|
|
934
|
+
const autoNotice = runWaterAuto(agent, pct, est?.source || '', waterAutoCfg)
|
|
935
|
+
if (autoNotice) {
|
|
936
|
+
decision = { ...decision, messages: [...decision.messages, notice(autoNotice)] }
|
|
937
|
+
}
|
|
938
|
+
} catch {} // 自动执行判定异常不能拖住 pre-step
|
|
939
|
+
|
|
940
|
+
// 2) review 提醒(v3.57 降级):原来是"每轮 + 命令式"——「先运行 lingshu review
|
|
941
|
+
// 确认或丢弃,再继续当前任务」,逼模型每次都先跑一轮工具才回答(实测多一轮
|
|
942
|
+
// 工具往返 ≈ TTFT +2~4s,且用户会感觉"开局慢")。现在:
|
|
943
|
+
// · 文案改成非命令式("有空再看"),不再抢占回答;
|
|
944
|
+
// · 每会话最多提醒一次(reviewNoticeOnce 默认 true);
|
|
945
|
+
// · 待审条数达到 reviewNoticeMin(默认 5)才提,零星一两条留给用户自己看。
|
|
946
|
+
if (cfg.injectReview) {
|
|
947
|
+
if (Date.now() - reviewCacheAt > cfg.reviewCacheMs) {
|
|
948
|
+
const raw = await runBrain(pythonExe, cfg.python, brainPy, ['review', '--json'], 15000)
|
|
949
|
+
try {
|
|
950
|
+
const parsed = raw ? JSON.parse(raw) : null
|
|
951
|
+
reviewCacheVal = parsed
|
|
952
|
+
reviewCacheAt = Date.now()
|
|
953
|
+
} catch {
|
|
954
|
+
reviewCacheVal = null // JSON 损坏视作无 pending,下个缓存周期再试
|
|
955
|
+
reviewCacheAt = Date.now()
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
const memCount = (reviewCacheVal?.memories?.length ?? 0)
|
|
959
|
+
+ (reviewCacheVal?.knowledge?.length ?? 0)
|
|
960
|
+
+ (reviewCacheVal?.persona?.length ?? 0)
|
|
961
|
+
// 已达下限、且没在本会话提醒过(reviewNoticeOnce=false 时每次都提)
|
|
962
|
+
const alreadyNoticed = reviewNoticeAt.get(agent) === true
|
|
963
|
+
const gated = cfg.reviewNoticeOnce && alreadyNoticed
|
|
964
|
+
if (memCount >= Math.max(1, Number(cfg.reviewNoticeMin) || 1) && !gated) {
|
|
965
|
+
reviewNoticeAt.set(agent, true)
|
|
966
|
+
return {
|
|
967
|
+
...decision,
|
|
968
|
+
messages: [...decision.messages, notice(
|
|
969
|
+
`【灵枢审核】有 ${memCount} 条 AI 整理的记忆待确认(不急,有空 \`lingshu review\` 看一眼即可,不影响当前任务)。`,
|
|
970
|
+
)],
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
// 3) 水位守卫(v3.01 设计 / v3.23 修估算口径):用上面算好的 est/pct,
|
|
976
|
+
// 首次跨过 60/75/90 各注入一条带真实数字的提醒。
|
|
977
|
+
// 另加软自检:每 waterCheckTurns 轮若还没跨阈值,也戳一下,防止估算偏低时永远不响。
|
|
978
|
+
if (cfg.waterGuard) {
|
|
979
|
+
const st = waterState.get(agent) || { max: 0, softAt: -1, lastPct: null }
|
|
980
|
+
if (pct != null) {
|
|
981
|
+
// v3.57(保护 A 的写入端):把真实水位落成 HOME/_pressure.json,注入侧
|
|
982
|
+
// (memory.build_injection 读 core.read_pressure)据此整体降档。
|
|
983
|
+
// 每跨 5 个百分点或跨档时写一次,避免每步都写盘;失败静默(不能拖住 pre-step)。
|
|
984
|
+
writePressure(pct, est?.source || 'unknown', st.max || 0)
|
|
985
|
+
|
|
986
|
+
// v3.57(保护 B):95 / 98 两个硬档。90 仍是"建议"(用户可能还想继续干活),
|
|
987
|
+
// 95 改命令式,98 起自动做**无破坏性**自救(auto-archive 只打归档标记、
|
|
988
|
+
// diagnose 只报告),绝不自动 capture(拿不到原文)也绝不 purge(物理删除)。
|
|
989
|
+
const th = pressureThresholds()
|
|
990
|
+
if (pct >= th.force_at) {
|
|
991
|
+
const did = await runForceActions(pythonExe, brainPy)
|
|
992
|
+
if (st.forceAt !== true) {
|
|
993
|
+
st.forceAt = true
|
|
994
|
+
waterState.set(agent, st)
|
|
995
|
+
return {
|
|
996
|
+
...decision,
|
|
997
|
+
messages: [...decision.messages, notice(
|
|
998
|
+
`【灵枢·水位 ${pct}%】已到强制自救线(${th.force_at}%),已自动执行无破坏性压缩:${did || '无可用动作'}。`
|
|
999
|
+
+ `现在只做三件事之一:① 让用户确认封存 capture;② 结束本轮话题;③ 继续也得先说明风险。不要再开新话题。`,
|
|
1000
|
+
)],
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
return decision
|
|
1004
|
+
}
|
|
1005
|
+
if (pct >= th.hard_at && st.hardAt !== true) {
|
|
1006
|
+
st.hardAt = true
|
|
1007
|
+
waterState.set(agent, st)
|
|
1008
|
+
return {
|
|
1009
|
+
...decision,
|
|
1010
|
+
messages: [...decision.messages, notice(
|
|
1011
|
+
`【灵枢·水位 ${pct}%】已过硬线(${th.hard_at}%):立刻先跑 \`python scripts/brain.py dream --auto\``
|
|
1012
|
+
+ `(或 \`auto-archive\`),压缩完再继续。不做压缩就继续对话,后面的内容很可能被宿主截断。`,
|
|
1013
|
+
)],
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
const step = pct >= 90 ? 90 : pct >= 75 ? 75 : pct >= 60 ? 60 : 0
|
|
1018
|
+
if (step > (st.max || 0)) {
|
|
1019
|
+
st.max = step
|
|
1020
|
+
waterState.set(agent, st)
|
|
1021
|
+
const raw = await runBrain(pythonExe, cfg.python, brainPy, ['check-context', '--used', String(pct)], 15000)
|
|
1022
|
+
const text = raw ? raw.trim() : ''
|
|
1023
|
+
if (text) {
|
|
1024
|
+
return { ...decision, messages: [...decision.messages, notice(text)] }
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
// 软自检(v3.59 重写):原来"每 waterCheckTurns 轮无条件注入一条",实测
|
|
1028
|
+
// 水位才 14% 也照发,用户会看到"没压缩却还在注入上下文"。现在只在
|
|
1029
|
+
// **确有变化**时提醒,其余情况只记账不占上下文:
|
|
1030
|
+
// ① 从没测过水位(本会话首次拿到估算);
|
|
1031
|
+
// ② 估算比上次提醒时涨了 ≥10 个百分点(真的在变满);
|
|
1032
|
+
// ③ 距上次提醒已过 waterCheckTurns 轮,**且**确实在涨(≥2 个百分点)。
|
|
1033
|
+
// 另:文案里不再叫模型去跑 check-context——那会多一次工具往返,而这条
|
|
1034
|
+
// 提醒本身通常没到需要动作的程度。
|
|
1035
|
+
const every = Math.max(0, Number(cfg.waterCheckTurns) || 0)
|
|
1036
|
+
const lastPct = Number.isFinite(st.lastPct) ? st.lastPct : null
|
|
1037
|
+
const grew = lastPct === null ? Infinity : pct - lastPct
|
|
1038
|
+
const turnsSince = Number.isFinite(st.softAt) && st.softAt > 0 ? n - st.softAt : Infinity
|
|
1039
|
+
const worthNoticing = lastPct === null
|
|
1040
|
+
|| grew >= 10
|
|
1041
|
+
|| (every > 0 && turnsSince >= every && grew >= 2)
|
|
1042
|
+
if (worthNoticing && step === 0 && n > 0 && st.softAt !== n) {
|
|
1043
|
+
st.softAt = n
|
|
1044
|
+
st.lastPct = pct
|
|
1045
|
+
waterState.set(agent, st)
|
|
1046
|
+
return {
|
|
1047
|
+
...decision,
|
|
1048
|
+
messages: [...decision.messages, notice(
|
|
1049
|
+
`【灵枢·水位】上下文估算约 ${pct}%(来源:${est.source})。还没到清点线,正常继续即可。`
|
|
1050
|
+
)],
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
// 不提醒也要更新"上次见过的水位",下次才有得比
|
|
1054
|
+
if (lastPct !== pct) {
|
|
1055
|
+
st.lastPct = pct
|
|
1056
|
+
waterState.set(agent, st)
|
|
1057
|
+
}
|
|
1058
|
+
} else {
|
|
1059
|
+
waterState.set(agent, st)
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
return decision
|
|
1064
|
+
} catch {
|
|
1065
|
+
// next() 可能已跑过,异常只能吞掉,返回已得的 decision(可能为 undefined)
|
|
1066
|
+
return decision
|
|
1067
|
+
}
|
|
1068
|
+
})
|
|
1069
|
+
|
|
1070
|
+
// 插件卸载/进程退出前把脏状态刷盘,避免节流窗口内的轮数/任务标记丢失
|
|
1071
|
+
const flushOnExit = () => { try { stateSaver.flushNow() } catch {} }
|
|
1072
|
+
ctx.on('agent/dispose', flushOnExit)
|
|
1073
|
+
try { process.on('exit', flushOnExit) } catch {}
|
|
1074
|
+
}
|