lingshu-skill 5.33.0 → 5.37.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4281 -4227
- package/README.md +1584 -1577
- package/SKILL-lite.md +59 -59
- package/SKILL-tiny.md +38 -38
- package/SKILL.md +356 -331
- package/assets/panel.html +6753 -5698
- package/cordis-plugin/lingshu-cron/plugin.js +1455 -1417
- package/cordis-plugin/lingshu-startup/context-fold.js +170 -0
- package/cordis-plugin/lingshu-startup/context-pressure.js +16 -0
- package/cordis-plugin/lingshu-startup/context-snapshot.js +176 -0
- package/cordis-plugin/lingshu-startup/plugin.js +499 -467
- package/docs/audit_notes//345/276/205/345/212/236-20261201-/351/235/242/346/235/277/344/270/245/346/237/245/344/270/216/345/256/241/350/256/241.md +162 -0
- package/docs/audit_notes//345/276/205/345/212/236-20261202-/351/235/242/346/235/277/344/272/244/344/272/222/344/270/216/346/225/260/346/215/256/345/245/221/347/272/246/345/256/241/350/256/241.md +92 -0
- package/docs/audit_notes//345/276/205/345/212/236/346/250/241/346/235/277.md +140 -0
- package/docs/commands.md +278 -247
- package/docs/mechanics.md +610 -610
- package/docs//345/276/205/345/212/236-20261201-/351/235/242/346/235/277/344/270/245/346/237/245/344/270/216/345/256/241/350/256/241.md +162 -0
- package/docs//345/276/205/345/212/236-20261202-/351/235/242/346/235/277/344/272/244/344/272/222/344/270/216/346/225/260/346/215/256/345/245/221/347/272/246/345/256/241/350/256/241.md +92 -0
- package/package.json +52 -52
- package/scripts/_scratch/_tmp_backup_race.py +70 -0
- package/scripts/_scratch/_tmp_cleanup_move.py +34 -0
- package/scripts/_scratch/_tmp_count_kinds.py +25 -0
- package/scripts/_scratch/_tmp_diag_paths.py +48 -0
- package/scripts/_scratch/_tmp_facts.py +63 -0
- package/scripts/_scratch/_tmp_find_copies.py +31 -0
- package/scripts/_scratch/_tmp_find_pin.py +29 -0
- package/scripts/_scratch/_tmp_fix_pin.py +36 -0
- package/scripts/_scratch/_tmp_fold_fixture.py +55 -0
- package/scripts/_scratch/_tmp_fold_test.mjs +81 -0
- package/scripts/_scratch/_tmp_inject_secs.py +30 -0
- package/scripts/_scratch/_tmp_kb_balance.py +159 -0
- package/scripts/_scratch/_tmp_lines.py +15 -0
- package/scripts/_scratch/_tmp_market_probe.py +13 -0
- package/scripts/_scratch/_tmp_move_partial.py +16 -0
- package/scripts/_scratch/_tmp_patch_b3.py +41 -0
- package/scripts/_scratch/_tmp_patch_b5.py +62 -0
- package/scripts/_scratch/_tmp_patch_crash_excl.py +24 -0
- package/scripts/_scratch/_tmp_patch_handoff.py +21 -0
- package/scripts/_scratch/_tmp_patch_ps1.py +25 -0
- package/scripts/_scratch/_tmp_patch_stat.py +27 -0
- package/scripts/_scratch/_tmp_patch_todo.py +25 -0
- package/scripts/_scratch/_tmp_patch_todo2.py +64 -0
- package/scripts/_scratch/_tmp_probe_session.py +51 -0
- package/scripts/_scratch/_tmp_style_probe.py +40 -0
- package/scripts/_scratch/_tmp_write_note.py +139 -0
- package/scripts/_scratch/_/346/235/245/346/272/220/350/256/260/345/275/225.txt +1 -0
- package/scripts/_scratch/asar_compaction/dsh-compaction-basic__lib__index.js +1044 -0
- package/scripts/_scratch/asar_compaction/dsh-compaction-tool-result-pruner__lib__index.js +194 -0
- package/scripts/_scratch/asar_compaction/dsh-compaction__lib__index.js +175 -0
- package/scripts/_scratch/asar_compaction/dsh-compaction__lib__types__tool-pairing.js +97 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__image-offload.js +47 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__index.js +40 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__project-message.js +37 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__brand.js +9 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__checkpoint.js +36 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__types.js +10 -0
- package/scripts/_scratch/commit_msg_occ.txt +16 -0
- package/scripts/_scratch/commit_msg_struct.txt +16 -0
- package/scripts/_scratch/v5.34_changelog.txt +36 -0
- package/scripts/_sync_trae_cn.py +102 -34
- package/scripts/_tmp_add_s10.py +54 -0
- package/scripts/_tmp_add_s11.py +61 -0
- package/scripts/_tmp_add_s12.py +66 -0
- package/scripts/_tmp_add_s13.py +69 -0
- package/scripts/_tmp_add_s14.py +80 -0
- package/scripts/_tmp_add_s9.py +68 -0
- package/scripts/_tmp_cache_load.py +82 -0
- package/scripts/_tmp_clean_market.py +40 -0
- package/scripts/_tmp_clean_pruned.py +81 -0
- package/scripts/_tmp_cleanup_docs.py +39 -0
- package/scripts/_tmp_cmp_ranker.py +17 -0
- package/scripts/_tmp_dolater_note.py +35 -0
- package/scripts/_tmp_dust_why.py +27 -0
- package/scripts/_tmp_explicit_import.py +40 -0
- package/scripts/_tmp_extract_compaction.py +35 -0
- package/scripts/_tmp_extract_compaction2.py +63 -0
- package/scripts/_tmp_extract_compaction3.py +51 -0
- package/scripts/_tmp_extract_compaction4.py +54 -0
- package/scripts/_tmp_finalize_s14.py +39 -0
- package/scripts/_tmp_find_compaction.py +43 -0
- package/scripts/_tmp_fix_b4.py +22 -0
- package/scripts/_tmp_fix_cli76.py +26 -0
- package/scripts/_tmp_fix_docs.py +38 -0
- package/scripts/_tmp_fix_docs_b.py +46 -0
- package/scripts/_tmp_fix_docs_b2.py +22 -0
- package/scripts/_tmp_fix_i3.py +23 -0
- package/scripts/_tmp_fix_s10.py +83 -0
- package/scripts/_tmp_fix_s11.py +14 -0
- package/scripts/_tmp_fix_s9_status.py +19 -0
- package/scripts/_tmp_fix_shadow_sim.py +37 -0
- package/scripts/_tmp_fix_traits_value.py +41 -0
- package/scripts/_tmp_import_idem.py +106 -0
- package/scripts/_tmp_log_ack.py +45 -0
- package/scripts/_tmp_mark_batch.py +28 -0
- package/scripts/_tmp_mark_batch2.py +32 -0
- package/scripts/_tmp_mark_dolater.py +26 -0
- package/scripts/_tmp_mark_dolater2.py +31 -0
- package/scripts/_tmp_move_self.py +16 -0
- package/scripts/_tmp_occ_cli.py +22 -0
- package/scripts/_tmp_occ_link.py +108 -0
- package/scripts/_tmp_optimize_recall.py +54 -0
- package/scripts/_tmp_panel_audit.py +26 -0
- package/scripts/_tmp_patch_batch3.py +65 -0
- package/scripts/_tmp_patch_rrf.py +46 -0
- package/scripts/_tmp_patch_s2s3.py +80 -0
- package/scripts/_tmp_patch_s4.py +39 -0
- package/scripts/_tmp_patch_s7.py +43 -0
- package/scripts/_tmp_patch_s8.py +91 -0
- package/scripts/_tmp_patch_skill.py +17 -0
- package/scripts/_tmp_release_guard.py +57 -0
- package/scripts/_tmp_rerank_breaker.py +62 -0
- package/scripts/_tmp_s16.py +41 -0
- package/scripts/_tmp_scan_asar.py +41 -0
- package/scripts/_tmp_scan_asar2.py +37 -0
- package/scripts/_tmp_struct_docs.py +49 -0
- package/scripts/_tmp_sum_fallback.py +42 -0
- package/scripts/_tmp_sweep.py +81 -0
- package/scripts/_tmp_sync_check.py +69 -0
- package/scripts/_tmp_sync_tail.py +39 -0
- package/scripts/_tmp_todo_clean.py +67 -0
- package/scripts/_tmp_verify_copy.py +17 -0
- package/scripts/_tmp_wire_extras.py +93 -0
- package/scripts/_tmp_wire_hsum.py +34 -0
- package/scripts/_tmp_wire_occ_b5.py +40 -0
- package/scripts/_tmp_wire_ranker.py +13 -0
- package/scripts/_tmp_wire_shadow_timeline.py +45 -0
- package/scripts/anchor_retention.py +68 -0
- package/scripts/app_context.py +1160 -0
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +38 -22
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +4281 -4227
- package/scripts/astrbot_plugin_lingshu/engine/README.md +1584 -1577
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +59 -59
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +38 -38
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +356 -331
- package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +6753 -5698
- package/scripts/astrbot_plugin_lingshu/engine/docs/commands.md +278 -247
- package/scripts/astrbot_plugin_lingshu/engine/docs/mechanics.md +610 -610
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +102 -34
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s10.py +54 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s11.py +61 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s12.py +66 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s13.py +69 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s14.py +80 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s9.py +68 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cache_load.py +82 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_clean_market.py +40 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_clean_pruned.py +81 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cleanup_docs.py +39 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cmp_ranker.py +17 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_dolater_note.py +35 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_dust_why.py +27 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_explicit_import.py +40 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction.py +35 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction2.py +63 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction3.py +51 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction4.py +54 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_finalize_s14.py +39 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_find_compaction.py +43 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_b4.py +22 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_cli76.py +26 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs.py +38 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs_b.py +46 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs_b2.py +22 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_i3.py +23 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s10.py +83 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s11.py +14 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s9_status.py +19 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_shadow_sim.py +37 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_traits_value.py +41 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_import_idem.py +106 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_log_ack.py +45 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_batch.py +28 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_batch2.py +32 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_dolater.py +26 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_dolater2.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_move_self.py +16 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_occ_cli.py +22 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_occ_link.py +108 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_optimize_recall.py +54 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_panel_audit.py +26 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_batch3.py +65 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_rrf.py +46 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s2s3.py +80 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s4.py +39 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s7.py +43 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s8.py +91 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_skill.py +17 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_release_guard.py +57 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_rerank_breaker.py +62 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_s16.py +41 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_scan_asar.py +41 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_scan_asar2.py +37 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_struct_docs.py +49 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sum_fallback.py +42 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sweep.py +81 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sync_check.py +69 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sync_tail.py +39 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_todo_clean.py +67 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_verify_copy.py +17 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_extras.py +93 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_hsum.py +34 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_occ_b5.py +40 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_ranker.py +13 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_shadow_timeline.py +45 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/anchor_retention.py +68 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/app_context.py +1160 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/bigfive.py +90 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/brain.py +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_docs.py +191 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +921 -86
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2468 -2406
- package/scripts/astrbot_plugin_lingshu/engine/scripts/coverage_report.py +5 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/delivery.py +112 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +41 -3
- package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +202 -23
- package/scripts/astrbot_plugin_lingshu/engine/scripts/gap_memory.py +186 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +72 -8
- package/scripts/astrbot_plugin_lingshu/engine/scripts/hsum.py +206 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_score.py +92 -7
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +530 -60
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory_extras.py +200 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/occ.py +190 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +232 -142
- package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +2498 -2349
- package/scripts/astrbot_plugin_lingshu/engine/scripts/prepublish_tests.py +90 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/release.py +326 -287
- package/scripts/astrbot_plugin_lingshu/engine/scripts/rss_ingest.py +181 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +832 -764
- package/scripts/astrbot_plugin_lingshu/engine/scripts/shadow_memory.py +173 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/style_check.py +220 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/summarizer.py +343 -252
- package/scripts/astrbot_plugin_lingshu/engine/scripts/timeline.py +118 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/watchdog.py +110 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/web_research.py +125 -0
- package/scripts/bigfive.py +90 -0
- package/scripts/brain.py +1 -1
- package/scripts/check_docs.py +191 -0
- package/scripts/cli.py +921 -86
- package/scripts/core.py +2468 -2406
- package/scripts/coverage_report.py +5 -0
- package/scripts/delivery.py +112 -0
- package/scripts/dream.py +41 -3
- package/scripts/emotion.py +202 -23
- package/scripts/gap_memory.py +186 -0
- package/scripts/growth.py +72 -8
- package/scripts/hsum.py +206 -0
- package/scripts/mem_score.py +92 -7
- package/scripts/memory.py +530 -60
- package/scripts/memory_extras.py +200 -0
- package/scripts/occ.py +190 -0
- package/scripts/panel_server.py +232 -142
- package/scripts/persona.py +2498 -2349
- package/scripts/prepublish_tests.py +90 -0
- package/scripts/release.py +326 -287
- package/scripts/rss_ingest.py +181 -0
- package/scripts/run_tests.py +13 -0
- package/scripts/session_import.py +832 -764
- package/scripts/shadow_memory.py +173 -0
- package/scripts/style_check.py +220 -0
- package/scripts/summarizer.py +343 -252
- package/scripts/timeline.py +118 -0
- package/scripts/update_dsh_copy.ps1 +110 -107
- package/scripts/watchdog.py +110 -0
- package/scripts/web_research.py +125 -0
- package/docs//344/272/244/346/216/245/347/254/224/350/256/260-20261128.md +0 -128
- package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +0 -408
|
@@ -1,1417 +1,1455 @@
|
|
|
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
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
return
|
|
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
|
-
const
|
|
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
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
const
|
|
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
|
-
if (
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
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
|
-
try {
|
|
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
|
-
let
|
|
581
|
-
let
|
|
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
|
-
if (
|
|
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
|
-
const
|
|
715
|
-
|
|
716
|
-
const
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
const
|
|
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
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
if (
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
}
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
return
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
let
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
const
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
}
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
//
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
}
|
|
1267
|
-
} catch {}
|
|
1268
|
-
|
|
1269
|
-
//
|
|
1270
|
-
//
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
//
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
st.
|
|
1374
|
-
waterState.set(agent, st)
|
|
1375
|
-
return {
|
|
1376
|
-
...decision,
|
|
1377
|
-
messages: [...decision.messages, notice(
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
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
|
+
// ---- B5:宿主心跳 ----
|
|
195
|
+
// 为什么需要:灵枢的所有定时任务都跑在宿主进程里,**宿主挂掉时它们一起死**,
|
|
196
|
+
// 于是"插件装着但不动"没有任何声音(v3.53 事故:全停 6 小时 doctor 仍全绿)。
|
|
197
|
+
// 这里每个回合落一次心跳;宿主外部的 `python scripts/brain.py watchdog --check`
|
|
198
|
+
// (可挂 Windows 任务计划)读它判断存活,只告警、不尝试自启。
|
|
199
|
+
function beatHost() {
|
|
200
|
+
try {
|
|
201
|
+
const dir = memoryHome()
|
|
202
|
+
mkdirSync(dir, { recursive: true })
|
|
203
|
+
writeFileSync(
|
|
204
|
+
join(dir, '.host-heartbeat.json'),
|
|
205
|
+
JSON.stringify({ ts: Math.floor(Date.now() / 1000), pid: process.pid,
|
|
206
|
+
iso: new Date().toISOString() }) + '\n',
|
|
207
|
+
'utf8',
|
|
208
|
+
)
|
|
209
|
+
} catch { /* 心跳失败绝不影响回合 */ }
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function findPythonExe(configured) {
|
|
213
|
+
if (configured) return existsSync(configured) ? configured : null
|
|
214
|
+
for (const p of pythonCandidates()) {
|
|
215
|
+
if (existsSync(p)) return p
|
|
216
|
+
}
|
|
217
|
+
return null
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// ---------------------------------------------------------------- 状态落盘(APP profile 目录,不碰 ~/.brain-memory)
|
|
221
|
+
|
|
222
|
+
function statePath() {
|
|
223
|
+
const base = process.env.APP_DSH || join(homedir(), '.dsh')
|
|
224
|
+
return join(base, 'lingshu-cron-state.json')
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function loadState(path) {
|
|
228
|
+
try {
|
|
229
|
+
const raw = readFileSync(path, 'utf8')
|
|
230
|
+
const obj = JSON.parse(raw)
|
|
231
|
+
return obj && typeof obj === 'object' ? obj : {}
|
|
232
|
+
} catch {
|
|
233
|
+
return {}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function saveState(path, state) {
|
|
238
|
+
try {
|
|
239
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
240
|
+
const tmp = `${path}.${randomUUID()}.tmp`
|
|
241
|
+
writeFileSync(tmp, JSON.stringify(state, null, 2), 'utf8')
|
|
242
|
+
try { rmSync(path, { force: true }) } catch {}
|
|
243
|
+
renameSync(tmp, path) // 原子替换(同目录 rename)
|
|
244
|
+
} catch {}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// ⚠ 必须用**本地**日期,不能用 toISOString()(那是 UTC)。
|
|
248
|
+
// Python 侧 daily / fmt_date / doctor 的 date.today() 全是本地日期;
|
|
249
|
+
// 东八区 00:00-08:00 之间两者差一天 → days 型任务(daily/conflicts/drift/
|
|
250
|
+
// autoarchive)早上会多跑一遍,doctor 的"最落后 N 天"也算错(审计 plugin.js:229)。
|
|
251
|
+
const todayStr = () => {
|
|
252
|
+
const d = new Date()
|
|
253
|
+
const p = (n) => String(n).padStart(2, '0')
|
|
254
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** agent 的稳定标识(用于状态落盘):拿不到稳定 id 就返回 null(仅内存计数)。 */
|
|
258
|
+
function agentKey(agent) {
|
|
259
|
+
const k = agent?.id ?? agent?.agentId ?? agent?.sessionId ?? agent?.session?.id
|
|
260
|
+
return typeof k === 'string' && k ? k : null
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function dueByDays(task, state) {
|
|
264
|
+
const last = state?.days?.[task.id]
|
|
265
|
+
return last !== todayStr()
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// 按小时间隔判定(P11 #72)。备份原来用 days:1 —— 只在"当天第一次回合"跑一次,
|
|
269
|
+
// 之后十几小时的写入完全裸奔(实测缺 17%)。改小时驱动后可按 config 调。
|
|
270
|
+
function dueByHours(task, state, hours) {
|
|
271
|
+
const h = Number(hours) || 0
|
|
272
|
+
if (h <= 0) return false
|
|
273
|
+
const last = Number(state?.hours?.[task.id] || 0)
|
|
274
|
+
if (!last) return true
|
|
275
|
+
return Date.now() - last >= h * 3600 * 1000
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// ---------------------------------------------------------------- 水位自动执行(影子模式 + 显式同意)
|
|
279
|
+
//
|
|
280
|
+
// 配置在 ~/.brain-memory/config.json 的 water 段(不是本插件的 config——改完
|
|
281
|
+
// 下一个水位档位即刻生效,不用重启宿主):
|
|
282
|
+
// "water": {"autoDream": false, "autoDreamConsent": false,
|
|
283
|
+
// "autoCapture": false, "autoCaptureConsent": false, "shadow": true}
|
|
284
|
+
// 语义(缺省全关,隐私默认安全):
|
|
285
|
+
// * autoXxx 与 autoXxxConsent 都缺省 false;shadow 缺省 true;
|
|
286
|
+
// * shadow=true 时只记"本来会做什么",绝不真执行;
|
|
287
|
+
// * 真执行必须 autoXxx && autoXxxConsent 同时为真,且 shadow=false;
|
|
288
|
+
// * 配置缺 water 段/字段类型不对(非布尔)一律回退上面这套默认值——
|
|
289
|
+
// 宁可不生效,也不从脏配置里"猜"一个 true 出来。
|
|
290
|
+
// 动作:
|
|
291
|
+
// * 首次跨 75%:满足执行条件就后台跑 dream --auto(沿用 runBrain 的 fire-and-forget,
|
|
292
|
+
// 绝不 await);否则只写一行影子台账(autoDream 全关时连台账都不写);
|
|
293
|
+
// * 首次跨 90%:capture 永不自动执行——capture 要的是会话原文,插件在 pre-step
|
|
294
|
+
// 只拿得到消息与水位、拿不到"原文",绝不自己拼凑;改为记一条"待人工确认的
|
|
295
|
+
// 逃生建议"并注入提醒一次,只有用户在会话里明确要求才真 capture。
|
|
296
|
+
// 台账:~/.brain-memory/water-auto.jsonl,每行 {ts, level, action, executed, reason};
|
|
297
|
+
// 超 512KB 轮转为 water-auto.jsonl.1(只留一份旧档,思路同 failures.py)。
|
|
298
|
+
|
|
299
|
+
const WATER_AUTO_LOG = 'water-auto.jsonl'
|
|
300
|
+
const WATER_AUTO_MAX_BYTES = 512 * 1024
|
|
301
|
+
|
|
302
|
+
const DEFAULT_WATER = {
|
|
303
|
+
autoDream: false,
|
|
304
|
+
autoDreamConsent: false,
|
|
305
|
+
autoCapture: false,
|
|
306
|
+
autoCaptureConsent: false,
|
|
307
|
+
shadow: true,
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** 记忆目录:BRAIN_MEMORY_HOME > ~/.brain-memory/.home 指针 > ~/.brain-memory(与 guard 同口径)。 */
|
|
311
|
+
function memoryHome() {
|
|
312
|
+
const env = (process.env.BRAIN_MEMORY_HOME || '').trim()
|
|
313
|
+
if (env) return env
|
|
314
|
+
const base = join(homedir(), '.brain-memory')
|
|
315
|
+
try {
|
|
316
|
+
const ptr = readFileSync(join(base, '.home'), 'utf8').trim()
|
|
317
|
+
if (ptr) return ptr
|
|
318
|
+
} catch {} // 没有指针文件就用默认目录
|
|
319
|
+
return base
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** 只认真正的布尔值:字符串 "true" / 数字 1 这类手写脏值一律回退默认(隐私开关宁可不生效)。 */
|
|
323
|
+
function boolOr(value, dflt) {
|
|
324
|
+
return typeof value === 'boolean' ? value : dflt
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** 合并默认值与 config.json 的 water 段;water 缺失/非对象/字段非法都回退默认。 */
|
|
328
|
+
function resolveWaterConfig(raw) {
|
|
329
|
+
const w = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw.water : null
|
|
330
|
+
const water = w && typeof w === 'object' && !Array.isArray(w) ? w : {}
|
|
331
|
+
const out = { ...DEFAULT_WATER }
|
|
332
|
+
for (const key of Object.keys(DEFAULT_WATER)) out[key] = boolOr(water[key], DEFAULT_WATER[key])
|
|
333
|
+
return out
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// config.json 很小,但 pre-step 每步都会问一次:按 mtime 缓存,文件没变不重读。
|
|
337
|
+
// 用户改完配置、mtime 变化后下一次判定即生效(冻结配置会让撤回同意变难)。
|
|
338
|
+
let waterConfigCache = { path: '', mtime: -1, value: DEFAULT_WATER }
|
|
339
|
+
|
|
340
|
+
function loadWaterAutoConfig() {
|
|
341
|
+
try {
|
|
342
|
+
const file = join(memoryHome(), 'config.json')
|
|
343
|
+
let mtime = -1
|
|
344
|
+
try { mtime = statSync(file).mtimeMs } catch { mtime = -1 }
|
|
345
|
+
if (waterConfigCache.path === file && waterConfigCache.mtime === mtime) return waterConfigCache.value
|
|
346
|
+
let raw = null
|
|
347
|
+
if (mtime >= 0) {
|
|
348
|
+
try { raw = JSON.parse(readFileSync(file, 'utf8')) } catch { raw = null } // 坏 JSON 视作没配
|
|
349
|
+
}
|
|
350
|
+
const value = resolveWaterConfig(raw)
|
|
351
|
+
waterConfigCache = { path: file, mtime, value }
|
|
352
|
+
return value
|
|
353
|
+
} catch {
|
|
354
|
+
return { ...DEFAULT_WATER }
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** 追加一行自动执行台账;超 512KB 先轮转成 water-auto.jsonl.1。台账 IO 失败绝不抛。 */
|
|
359
|
+
function recordWaterAuto(level, action, executed, reason) {
|
|
360
|
+
try {
|
|
361
|
+
const file = join(memoryHome(), WATER_AUTO_LOG)
|
|
362
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
363
|
+
try {
|
|
364
|
+
if (existsSync(file) && statSync(file).size > WATER_AUTO_MAX_BYTES) {
|
|
365
|
+
const old = `${file}.1`
|
|
366
|
+
try { rmSync(old, { force: true }) } catch {}
|
|
367
|
+
renameSync(file, old) // 只留一份旧档:失败可见化(failures.py)同款轮转
|
|
368
|
+
}
|
|
369
|
+
} catch {} // 轮转失败不拦记账:顶多当前文件继续长大
|
|
370
|
+
appendFileSync(file, JSON.stringify({
|
|
371
|
+
ts: new Date().toISOString(),
|
|
372
|
+
level, // 75 | 90
|
|
373
|
+
action, // 'dream --auto' | 'capture'
|
|
374
|
+
executed: executed === true, // true = 已投递后台执行(fire-and-forget 不回传成败)
|
|
375
|
+
reason: String(reason || ''), // executed / busy / shadow / no-consent / no-verbatim
|
|
376
|
+
}) + '\n', 'utf8')
|
|
377
|
+
} catch {} // 台账本身不能成为故障源
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// ---------------------------------------------------------------- 上下文压力(v3.57)
|
|
381
|
+
|
|
382
|
+
/** 压力阈值:与 scripts/core.py 的 PRESSURE_DEFAULTS **保持一致**;config 的
|
|
383
|
+
* pressure 段可覆盖。两边各写一份是因为插件不 import Python,注释互指即可。 */
|
|
384
|
+
const PRESSURE_DEFAULTS = { lazy_at: 70, minimal_at: 85, hard_at: 95, force_at: 98 }
|
|
385
|
+
|
|
386
|
+
/** 读 pressure 阈值(写坏/缺项一律回退默认,宁可不生效也不猜)。 */
|
|
387
|
+
export function pressureThresholds() {
|
|
388
|
+
let seg = {}
|
|
389
|
+
try {
|
|
390
|
+
const cfg = JSON.parse(readFileSync(join(memoryHome(), 'config.json'), 'utf8'))
|
|
391
|
+
const raw = cfg?.pressure
|
|
392
|
+
if (raw && typeof raw === 'object' && !Array.isArray(raw)) seg = raw
|
|
393
|
+
} catch {}
|
|
394
|
+
const out = { ...PRESSURE_DEFAULTS }
|
|
395
|
+
for (const key of Object.keys(PRESSURE_DEFAULTS)) {
|
|
396
|
+
const v = seg[key]
|
|
397
|
+
if (typeof v === 'boolean') continue
|
|
398
|
+
if (typeof v === 'number' && Number.isFinite(v) && v >= 1 && v <= 100) out[key] = v
|
|
399
|
+
}
|
|
400
|
+
out.minimal_at = Math.max(out.minimal_at, out.lazy_at)
|
|
401
|
+
out.hard_at = Math.max(out.hard_at, out.minimal_at)
|
|
402
|
+
out.force_at = Math.max(out.force_at, out.hard_at)
|
|
403
|
+
return out
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** 上次写 Pressure 的百分比(按 agent 记,避免每步都写盘)。 */
|
|
407
|
+
const pressureWritten = new Map()
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* 把水位写进 `HOME/_pressure.json`(注入侧读它降档)。
|
|
411
|
+
* 只在"跨 5 个百分点"或"跨档"时真写,减少磁盘写;失败静默返回 false。
|
|
412
|
+
*/
|
|
413
|
+
export function writePressure(pct, source, prevMax, extra = null) {
|
|
414
|
+
try {
|
|
415
|
+
if (pct == null || !Number.isFinite(Number(pct))) return false
|
|
416
|
+
const p = Math.round(Number(pct))
|
|
417
|
+
const th = pressureThresholds()
|
|
418
|
+
const tier = p >= th.minimal_at ? 'minimal' : p >= th.lazy_at ? 'lazy' : 'full'
|
|
419
|
+
const key = `${tier}`
|
|
420
|
+
const last = pressureWritten.get('last')
|
|
421
|
+
if (last && last.tier === key && Math.abs(p - last.pct) < 5) return false
|
|
422
|
+
pressureWritten.set('last', { pct: p, tier: key })
|
|
423
|
+
const file = join(memoryHome(), '_pressure.json')
|
|
424
|
+
const tmp = `${file}.${randomUUID()}.tmp`
|
|
425
|
+
// extra 落盘估算依据(chars / tokens / limit):水位报错时能直接看出是"数漏了"
|
|
426
|
+
// 还是"系数不对",不用再猜。注入侧只读 pct,多出的字段不影响它。
|
|
427
|
+
const payload = { pct: p, at: Math.floor(Date.now() / 1000), source: String(source || '') }
|
|
428
|
+
if (extra && typeof extra === 'object') {
|
|
429
|
+
for (const k of ['chars', 'tokens', 'limit']) {
|
|
430
|
+
if (Number.isFinite(Number(extra[k]))) payload[k] = Number(extra[k])
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
writeFileSync(tmp, JSON.stringify(payload), 'utf8')
|
|
434
|
+
try { rmSync(file, { force: true }) } catch {}
|
|
435
|
+
renameSync(tmp, file)
|
|
436
|
+
return true
|
|
437
|
+
} catch { return false }
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* 98% 强制自救:只跑**没有破坏性**的两条——
|
|
442
|
+
* `auto-archive`:把审核通过的 pending 记忆按类型转正(原记忆只加 archived_at,不删)
|
|
443
|
+
* `memory diagnose`:只报告问题,不修复
|
|
444
|
+
* capture 永不自动(插件拿不到会话原文),purge 永不自动(物理删除)。
|
|
445
|
+
*/
|
|
446
|
+
export function forceActions() {
|
|
447
|
+
return [
|
|
448
|
+
{ id: 'autoarchive', argv: ['auto-archive'] },
|
|
449
|
+
{ id: 'diagnose', argv: ['memory', 'diagnose'] },
|
|
450
|
+
]
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* 90% 的"待人工确认的逃生建议":说明为什么不由插件 capture,并给出人工确认后的命令。
|
|
455
|
+
*/function escapeSuggestion(pct, source) {
|
|
456
|
+
const from = source === 'usage' ? '宿主 usage' : '消息字符估算'
|
|
457
|
+
return `【灵枢·水位 90% 逃生建议】上下文估算约 ${pct}%(来源:${from})。`
|
|
458
|
+
+ '封存 capture 需要会话原文,插件拿不到正文、也绝不替你拼凑,所以这里只提醒、不自动执行。'
|
|
459
|
+
+ '请先问用户是否现在封存;用户明确要求后,由你把原文原样贴进命令再跑:'
|
|
460
|
+
+ ' python scripts/brain.py capture "<把原文粘进来>" --tag 逃生 --kind episode'
|
|
461
|
+
+ '(每次会话只提醒这一次;autoCapture 开关只代表"允许考虑自动封存",但 capture 永不自动调用。)'
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// ---------------------------------------------------------------- 子进程(照抄 lingshu-startup 的 spawn 方案)
|
|
465
|
+
|
|
466
|
+
function runBrain(pythonExe, pythonCmdFallback, brainPy, argv, timeoutMs) {
|
|
467
|
+
return new Promise((resolve) => {
|
|
468
|
+
let settled = false
|
|
469
|
+
const done = (v) => { if (!settled) { settled = true; resolve(v) } }
|
|
470
|
+
const args = [brainPy, ...argv]
|
|
471
|
+
let child
|
|
472
|
+
try {
|
|
473
|
+
if (pythonExe) {
|
|
474
|
+
child = spawn(pythonExe, args, {
|
|
475
|
+
windowsHide: true,
|
|
476
|
+
env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
|
|
477
|
+
// 显式把工作目录挪到用户主目录:绝不继承宿主 cwd。宿主 cwd 若在插件
|
|
478
|
+
// 目录内,Windows 会因"目录被进程占用"拒绝 pnpm 的目录 rename,
|
|
479
|
+
// 导致市场更新(remove+add)报"文件被占用、请退出 DSH"。
|
|
480
|
+
cwd: homedir(),
|
|
481
|
+
})
|
|
482
|
+
} else {
|
|
483
|
+
const comspec = process.env.ComSpec ?? 'cmd.exe'
|
|
484
|
+
const pythonCmd = pythonCmdFallback || 'python'
|
|
485
|
+
const cmdline = [`"${pythonCmd}"`, ...args.map((a) => `"${a}"`)].join(' ')
|
|
486
|
+
child = spawn(comspec, ['/d', '/s', '/c', cmdline], {
|
|
487
|
+
windowsHide: true,
|
|
488
|
+
windowsVerbatimArguments: true,
|
|
489
|
+
env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
|
|
490
|
+
cwd: homedir(), // 同上:不把宿主 cwd(可能在插件目录内)占给子进程
|
|
491
|
+
})
|
|
492
|
+
}
|
|
493
|
+
} catch (e) {
|
|
494
|
+
return done({ ok: false, out: '', err: `spawn 失败:${e?.message || e}` })
|
|
495
|
+
}
|
|
496
|
+
let out = ''
|
|
497
|
+
// ★ stderr 必须收下来:brain.py 的所有错误(`[错误] 备份失败:…`)都走 stderr。
|
|
498
|
+
// 原实现只收 stdout、把 stderr 直接 resume() 丢掉 → cron 只能记「可能超时或
|
|
499
|
+
// 非零退出」,真实原因永远查不到(实测 `backup --yes` 就是 stderr 报 PermissionError)。
|
|
500
|
+
// 这里仍会 drain(避免 64KB 管道塞满阻塞),只是把尾部留 2000 字符用于定位。
|
|
501
|
+
let err = ''
|
|
502
|
+
child.stdout?.on('data', (d) => { out += d.toString('utf8') })
|
|
503
|
+
child.stderr?.on('data', (d) => { err = (err + d.toString('utf8')).slice(-2000) })
|
|
504
|
+
child.on('error', (e) => done({ ok: false, out, err: err || `spawn 异常:${e?.message || e}` }))
|
|
505
|
+
// 手动超时兜底:taskkill /T /F 杀整棵进程树(cmd 兜底分支里的 python 孙进程也要杀)
|
|
506
|
+
const killer = setTimeout(() => {
|
|
507
|
+
try {
|
|
508
|
+
if (child.pid) {
|
|
509
|
+
const tk = spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
|
|
510
|
+
tk.on('error', () => {})
|
|
511
|
+
}
|
|
512
|
+
} catch {}
|
|
513
|
+
try { child.kill() } catch {}
|
|
514
|
+
done({ ok: false, out, err: (err + `\n[超时 ${timeoutMs}ms 被杀]`).trim() })
|
|
515
|
+
}, timeoutMs)
|
|
516
|
+
killer.unref?.()
|
|
517
|
+
child.on('close', (code) => {
|
|
518
|
+
clearTimeout(killer)
|
|
519
|
+
const ok = code === 0 || code === 10
|
|
520
|
+
done({ ok, out, err })
|
|
521
|
+
})
|
|
522
|
+
})
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// ---------------------------------------------------------------- 注入消息构造(与 lingshu-startup 同格式)
|
|
526
|
+
|
|
527
|
+
function notice(text) {
|
|
528
|
+
return {
|
|
529
|
+
id: randomUUID(),
|
|
530
|
+
role: 'user',
|
|
531
|
+
content: [{ type: 'text', text }],
|
|
532
|
+
source: { kind: 'skill-invocation', name: INJECT_SOURCE, form: 'instructions' },
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// ---------------------------------------------------------------- 插件主体
|
|
537
|
+
|
|
538
|
+
export function apply(ctx, config) {
|
|
539
|
+
// 挂载探针(#55):重启后心跳不更新时,靠这行判断 cron 子插件到底有没有被加载。
|
|
540
|
+
// 只打一行,不影响任何调度逻辑。
|
|
541
|
+
try { ctx.logger?.info?.('[lingshu-cron] mounted') } catch {}
|
|
542
|
+
// v3.23:重复挂载守卫。profile 里同时启用独立包 dsh-lingshu-startup 与 lingshu-skill
|
|
543
|
+
// (根包 index.js 内部也挂 startup/cron)时,同一进程会出现两份 cron:
|
|
544
|
+
// 定时任务重复跑、水位提醒重复注入。进程级只允许一份。
|
|
545
|
+
if (globalThis.__lingshuCronApplied) {
|
|
546
|
+
try { ctx.logger?.warn?.('lingshu-cron: 已有一份灵枢 cron 在运行,跳过重复挂载') } catch {}
|
|
547
|
+
return
|
|
548
|
+
}
|
|
549
|
+
globalThis.__lingshuCronApplied = true
|
|
550
|
+
const cfg = mergeConfig(config)
|
|
551
|
+
|
|
552
|
+
const turns = new Map() // agent -> 本会话轮次
|
|
553
|
+
const running = new Set() // 防并发:同名任务进行中就不重入
|
|
554
|
+
const convo = new Map() // agent -> { text, seen }(即记即存缓冲 + 已处理消息游标,extract 成功后清空)
|
|
555
|
+
const lastReply = new Map() // agent -> 最后一条 assistant 文本(给 usage --reply 用)
|
|
556
|
+
const lastUser = new Map() // agent -> 最后一条用户文本(给 speak-up 判"是不是在提问")
|
|
557
|
+
// 主动搭话待注入队列:turn-stopping 里决定要说的话,留到下一轮 pre-step 注入
|
|
558
|
+
// (turn-stopping 阶段已经改不了本轮上下文了)。
|
|
559
|
+
const pendingNotice = new Map()
|
|
560
|
+
let _waterDebugAt = 0 // 水位诊断转储的节流时间戳(v5.32)
|
|
561
|
+
const waterState = new Map() // agent -> { max } 水位守卫已提醒的最高档(60/75/90 各提醒一次)
|
|
562
|
+
// v3.57:review 提醒已发过的 agent(每会话一次,不再每轮催)
|
|
563
|
+
const reviewNoticeAt = new Map()
|
|
564
|
+
const waterAutoState = new Map() // agent -> { max } 水位自动执行已处理到的最高档(75/90 各动作一次)
|
|
565
|
+
let state = loadState(statePath())
|
|
566
|
+
|
|
567
|
+
// 启动时清理崩溃残留的 extract 明文临时文件(超过 1 天的直接删)
|
|
568
|
+
try {
|
|
569
|
+
const base = process.env.APP_DSH || join(homedir(), '.dsh')
|
|
570
|
+
const cutoff = Date.now() - 24 * 3600 * 1000
|
|
571
|
+
for (const f of readdirSync(base)) {
|
|
572
|
+
if (!f.startsWith('lingshu-extract-') || !f.endsWith('.txt')) continue
|
|
573
|
+
const p = join(base, f)
|
|
574
|
+
try {
|
|
575
|
+
if (statSync(p).mtimeMs < cutoff) rmSync(p, { force: true })
|
|
576
|
+
} catch {}
|
|
577
|
+
}
|
|
578
|
+
} catch {}
|
|
579
|
+
let brainPyCache = null
|
|
580
|
+
let warnedOnce = false
|
|
581
|
+
let warnedNoBrain = false
|
|
582
|
+
|
|
583
|
+
// 状态节流落盘器(#69):变更只置脏,30 秒合并刷盘,避免每轮 turn-stopping 都写磁盘
|
|
584
|
+
const stateSaver = (() => {
|
|
585
|
+
let dirty = false
|
|
586
|
+
let timer = null
|
|
587
|
+
const flush = () => {
|
|
588
|
+
timer = null
|
|
589
|
+
if (!dirty) return
|
|
590
|
+
dirty = false
|
|
591
|
+
saveState(statePath(), state)
|
|
592
|
+
}
|
|
593
|
+
return {
|
|
594
|
+
markDirty() {
|
|
595
|
+
dirty = true
|
|
596
|
+
if (!timer) {
|
|
597
|
+
timer = setTimeout(flush, 30_000)
|
|
598
|
+
if (timer?.unref) timer.unref()
|
|
599
|
+
}
|
|
600
|
+
},
|
|
601
|
+
flushNow: flush,
|
|
602
|
+
}
|
|
603
|
+
})()
|
|
604
|
+
const markStateDirty = () => stateSaver.markDirty()
|
|
605
|
+
|
|
606
|
+
// review --json 缓存(pre-step 每步都问,30s 内复用)
|
|
607
|
+
let reviewCacheAt = 0
|
|
608
|
+
let reviewCacheVal = null
|
|
609
|
+
|
|
610
|
+
// 重启恢复(#77):state.turns 本身就是事实源,turn-stopping 直接读它续算,无需 seed 拷贝
|
|
611
|
+
|
|
612
|
+
const warn = (msg) => { if (!warnedOnce) { warnedOnce = true; try { ctx.logger?.warn?.(msg) } catch {} } }
|
|
613
|
+
|
|
614
|
+
async function ensureBrainPy() {
|
|
615
|
+
if (brainPyCache) return brainPyCache
|
|
616
|
+
const found = await findBrainPy(cfg.brainPy, ctx)
|
|
617
|
+
if (!found) {
|
|
618
|
+
// 静默失败必须留痕:这是 2026-11-20「记忆突然不录入了」的直接证据来源
|
|
619
|
+
if (!warnedNoBrain) {
|
|
620
|
+
warnedNoBrain = true
|
|
621
|
+
writeDiag('brainPy-not-found', {
|
|
622
|
+
tried: brainPyCandidates(),
|
|
623
|
+
packageRoot: PACKAGE_ROOT,
|
|
624
|
+
configured: cfg.brainPy || null,
|
|
625
|
+
})
|
|
626
|
+
warn('lingshu-cron: 未找到 brain.py(未安装灵枢?),调度跳过')
|
|
627
|
+
}
|
|
628
|
+
return null
|
|
629
|
+
}
|
|
630
|
+
brainPyCache = found
|
|
631
|
+
return found
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/** fire-and-forget:绝不 await、失败允许下轮补跑一次(当日仅一次,再败等明天)。
|
|
635
|
+
* 返回 false 表示同名任务正在进行、本次没有投递(供水位自动执行如实记账)。 */
|
|
636
|
+
function fire(task) {
|
|
637
|
+
if (running.has(task.id)) return false
|
|
638
|
+
running.add(task.id)
|
|
639
|
+
;(async () => {
|
|
640
|
+
try {
|
|
641
|
+
const brainPy = await ensureBrainPy()
|
|
642
|
+
if (!brainPy) {
|
|
643
|
+
// P6 #49:失败必须留痕(原来直接 return,静默)
|
|
644
|
+
logTaskFailure(task.id, '找不到 brain.py(未安装或路径配置错误)')
|
|
645
|
+
return
|
|
646
|
+
}
|
|
647
|
+
const pythonExe = findPythonExe(cfg.python)
|
|
648
|
+
const res = await runBrain(pythonExe, cfg.python, brainPy, task.argv, cfg.timeoutMs)
|
|
649
|
+
const okRun = res.ok
|
|
650
|
+
const errTail = res.err ? String(res.err).trim() : ''
|
|
651
|
+
// 退出码 0/10 才算跑成;失败不标记完成,下轮补跑一次,再失败就等明天
|
|
652
|
+
// (state.retries 记当日已补跑次数,防持续失败造成备份/做梦风暴)。
|
|
653
|
+
if (task.days) {
|
|
654
|
+
state.days = state.days || {}
|
|
655
|
+
if (okRun) {
|
|
656
|
+
state.days[task.id] = todayStr()
|
|
657
|
+
if (state.retries) delete state.retries[task.id]
|
|
658
|
+
} else {
|
|
659
|
+
state.retries = state.retries || {}
|
|
660
|
+
const r = state.retries[task.id] || { date: todayStr(), count: 0 }
|
|
661
|
+
if (r.date !== todayStr()) { r.date = todayStr(); r.count = 0 }
|
|
662
|
+
r.count += 1
|
|
663
|
+
state.retries[task.id] = r
|
|
664
|
+
// P6 #49:写 lingshu.log——doctor 报"补跑失败"时用户能查到原因
|
|
665
|
+
logTaskFailure(task.id, `brain.py 退出码非 0/10(argv: ${JSON.stringify(task.argv || []).slice(0, 160)};补跑第 ${r.count} 次)`
|
|
666
|
+
+ (errTail ? `;stderr: ${errTail}` : ''))
|
|
667
|
+
if (r.count >= 1) state.days[task.id] = todayStr() // 已补跑过一次,今天不再纠缠
|
|
668
|
+
}
|
|
669
|
+
stateSaver.flushNow() // 天级任务低频,立即落盘保证不丢标记
|
|
670
|
+
}
|
|
671
|
+
// 小时级任务(备份/自动更新)单独记时间戳:与 days 互不干扰
|
|
672
|
+
if (task.hours) {
|
|
673
|
+
state.hours = state.hours || {}
|
|
674
|
+
if (okRun) {
|
|
675
|
+
state.hours[task.id] = Date.now()
|
|
676
|
+
if (state.retries) delete state.retries[task.id]
|
|
677
|
+
} else {
|
|
678
|
+
state.retries = state.retries || {}
|
|
679
|
+
const r = state.retries[task.id] || { date: todayStr(), count: 0 }
|
|
680
|
+
if (r.date !== todayStr()) { r.date = todayStr(); r.count = 0 }
|
|
681
|
+
r.count += 1
|
|
682
|
+
state.retries[task.id] = r
|
|
683
|
+
logTaskFailure(task.id,
|
|
684
|
+
`小时级任务失败(补跑第 ${r.count} 次);`
|
|
685
|
+
+ `命令: brain.py ${(task.argv || []).join(' ')};`
|
|
686
|
+
+ '可能是超时(timeoutMs)或非零退出,先手动跑一次确认'
|
|
687
|
+
+ (errTail ? `;stderr: ${errTail}` : ''))
|
|
688
|
+
// ⚠ 必须与天级分支同样封顶(审计 plugin.js:628):
|
|
689
|
+
// 原来失败时不写 state.hours,dueByHours 因 last=0 恒为真 →
|
|
690
|
+
// 备份持续失败时**每个回合**都新拉一个子进程(最坏 120s)并刷一条
|
|
691
|
+
// 错误日志,注释承诺的"防备份风暴"根本没实现。
|
|
692
|
+
// 补跑满 1 次就先记一次时间戳,让下一个小时周期再试,别每回合重来。
|
|
693
|
+
if (r.count >= 1) state.hours[task.id] = Date.now()
|
|
694
|
+
}
|
|
695
|
+
stateSaver.flushNow()
|
|
696
|
+
}
|
|
697
|
+
} catch (err) {
|
|
698
|
+
// P6 #49:顶层异常也不能静默——写日志后照旧吞掉(守卫语义:异常不冒泡)
|
|
699
|
+
logTaskFailure(task.id, `执行异常:${err?.message || String(err)}`)
|
|
700
|
+
}
|
|
701
|
+
finally {
|
|
702
|
+
running.delete(task.id)
|
|
703
|
+
}
|
|
704
|
+
})()
|
|
705
|
+
return true
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* v3.57(保护 B 的执行端):98% 强制自救——**同步 await**(与 fire 的 fire-and-forget
|
|
710
|
+
* 不同:这里必须等结果,才能把"做了什么"如实告诉模型)。只跑无破坏性动作。
|
|
711
|
+
* 返回一行摘要(失败也返回,说明失败了几个),绝不抛异常。
|
|
712
|
+
*/
|
|
713
|
+
async function runForceActions(pythonExe, brainPy) {
|
|
714
|
+
const done = []
|
|
715
|
+
const failed = []
|
|
716
|
+
for (const task of forceActions()) {
|
|
717
|
+
try {
|
|
718
|
+
const r = await runBrain(pythonExe, cfg.python, brainPy, task.argv, cfg.timeoutMs)
|
|
719
|
+
if (!r.ok) failed.push(task.id)
|
|
720
|
+
else {
|
|
721
|
+
// 取首行当摘要,避免把整段输出灌进上下文
|
|
722
|
+
const line = String(r.out).trim().split(/\r?\n/).find((x) => x.trim()) || task.id
|
|
723
|
+
done.push(line.trim().slice(0, 60))
|
|
724
|
+
}
|
|
725
|
+
} catch { failed.push(task.id) }
|
|
726
|
+
}
|
|
727
|
+
const parts = []
|
|
728
|
+
if (done.length) parts.push(done.join(';'))
|
|
729
|
+
if (failed.length) parts.push(`失败:${failed.join('、')}(可手工重试)`)
|
|
730
|
+
return parts.join('。')
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* 水位自动执行判定(首次跨档才做一次)。纯同步返回要注入的提醒文本(null = 不注入);
|
|
735
|
+
* 真执行一律走 fire() 的后台通道,绝不 await。
|
|
736
|
+
* - 75%:autoDream && autoDreamConsent && shadow=false → fire `dream --auto`;
|
|
737
|
+
* 否则若 autoDream 开着,只记影子台账(executed=false,reason=shadow/no-consent);
|
|
738
|
+
* autoDream 关着就什么都不记(缺省全关 = 零副作用)。
|
|
739
|
+
* - 90%:capture 永不自动执行——插件拿不到会话原文,绝不自己拼;
|
|
740
|
+
* 只记 executed=false(reason=no-verbatim)并返回一次"待人工确认的逃生建议"。
|
|
741
|
+
* 两个 auto 开关都关时整段不判定、不写盘。
|
|
742
|
+
*/
|
|
743
|
+
function runWaterAuto(agent, pct, source, wcfg) {
|
|
744
|
+
if (!agent || pct == null) return null
|
|
745
|
+
const armed = wcfg.autoDream === true || wcfg.autoCapture === true
|
|
746
|
+
if (!armed) return null // 默认全关:不判定、不写盘
|
|
747
|
+
const level = pct >= 90 ? 90 : pct >= 75 ? 75 : 0
|
|
748
|
+
if (!level) return null
|
|
749
|
+
const st = waterAutoState.get(agent) || { max: 0 }
|
|
750
|
+
const prev = Number(st.max) || 0
|
|
751
|
+
if (level <= prev) return null // 档位只推进一次(首次跨 75/90 各做一次)
|
|
752
|
+
let noticeText = null
|
|
753
|
+
// 75%:该做梦了。直接从低位跳到 90% 时也补做这一档(prev < 75)。
|
|
754
|
+
// 复用 turn-stopping 那条任务名 'dream':全局同一时刻只许一份 dream 在跑
|
|
755
|
+
// (与轮次驱动的 dream 撞车时返回 busy,如实记 executed=false)。
|
|
756
|
+
if (level >= 75 && prev < 75 && wcfg.autoDream === true) {
|
|
757
|
+
const consent = wcfg.autoDreamConsent === true
|
|
758
|
+
if (consent && wcfg.shadow === false) {
|
|
759
|
+
const fired = fire({ id: 'dream', argv: ['dream', '--auto'] })
|
|
760
|
+
recordWaterAuto(75, 'dream --auto', fired, fired ? 'executed' : 'busy')
|
|
761
|
+
} else {
|
|
762
|
+
// 影子模式或没给同意:只记"本来会做什么",不动手
|
|
763
|
+
recordWaterAuto(75, 'dream --auto', false, consent ? 'shadow' : 'no-consent')
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
// 90%:该封存了,但 capture 需要原文 —— 插件永不自动拼,交人工确认。
|
|
767
|
+
if (level >= 90 && wcfg.autoCapture === true) {
|
|
768
|
+
recordWaterAuto(90, 'capture', false, 'no-verbatim')
|
|
769
|
+
noticeText = escapeSuggestion(pct, source)
|
|
770
|
+
}
|
|
771
|
+
waterAutoState.set(agent, { max: level })
|
|
772
|
+
return noticeText
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/**
|
|
776
|
+
* 即记即存:把攒的对话文本写到临时文件,静默跑 brain.py extract
|
|
777
|
+
* (惊异门控 + capture 逐段去重都在 Python 侧)。成功后清空缓冲,
|
|
778
|
+
* 失败保留缓冲下轮重试。fire-and-forget 三铁律同样适用。
|
|
779
|
+
*/
|
|
780
|
+
function fireExtract(agent) {
|
|
781
|
+
if (running.has('extract')) return
|
|
782
|
+
const buf = convo.get(agent)
|
|
783
|
+
const text = (buf?.text || '').trim()
|
|
784
|
+
if (!text || text.length < cfg.extractMinChars) return // 没攒够有信息量的内容,不跑
|
|
785
|
+
running.add('extract')
|
|
786
|
+
;(async () => {
|
|
787
|
+
let ok = false
|
|
788
|
+
try {
|
|
789
|
+
const brainPy = await ensureBrainPy()
|
|
790
|
+
if (!brainPy) return
|
|
791
|
+
// 临时文件放 APP profile 目录(与状态文件同层),用完由 brain.py 删除
|
|
792
|
+
const base = process.env.APP_DSH || join(homedir(), '.dsh')
|
|
793
|
+
mkdirSync(base, { recursive: true })
|
|
794
|
+
const tmp = join(base, `lingshu-extract-${randomUUID()}.txt`)
|
|
795
|
+
try {
|
|
796
|
+
writeFileSync(tmp, text, 'utf8')
|
|
797
|
+
const pythonExe = findPythonExe(cfg.python)
|
|
798
|
+
const r = await runBrain(pythonExe, cfg.python, brainPy,
|
|
799
|
+
['extract', '--file', tmp, '--cleanup', '--min-chars', String(cfg.extractMinChars)],
|
|
800
|
+
cfg.timeoutMs)
|
|
801
|
+
// 只有退出码 0/10(写入成功/惊异未过门)才算跑成;失败保留缓冲,
|
|
802
|
+
// 下个 extractTurns 周期重试——原逻辑把错误退出也当成功清缓冲,会丢对话。
|
|
803
|
+
ok = r.ok
|
|
804
|
+
} finally {
|
|
805
|
+
try { rmSync(tmp, { force: true }) } catch {}
|
|
806
|
+
}
|
|
807
|
+
} catch {} // 顶层兜底
|
|
808
|
+
finally {
|
|
809
|
+
if (ok) convo.set(agent, { text: '', seen: buf?.seen }) // 清空缓冲,但保留游标(防止重复攒旧消息)
|
|
810
|
+
else if (text.length > 200_000) {
|
|
811
|
+
// 兜底防爆内存:截断保留头部 100k 而非全丢,并至少告警一次(#64)
|
|
812
|
+
// ★ 必须用 ctx.logger(审计 plugin.js:766):模块作用域里没有裸 `logger`
|
|
813
|
+
// (只有 ctx.logger 和本地 warn(),而后者是 once-only——这里丢的是数据,
|
|
814
|
+
// 每次都要报,不能被 once 吞掉)。原来写裸 logger 必抛 ReferenceError,
|
|
815
|
+
// 又被同一个 catch {} 吞掉 →「截断丢了多少字符」这条唯一告警永远不出现。
|
|
816
|
+
try { ctx.logger?.warn?.(`[lingshu-cron] extract 失败且缓冲超 200k,截断保留前 100k 字符(已丢失 ${(text.length - 100_000)} 字符)`) } catch {}
|
|
817
|
+
convo.set(agent, { text: text.slice(0, 100_000), seen: buf?.seen })
|
|
818
|
+
}
|
|
819
|
+
running.delete('extract')
|
|
820
|
+
}
|
|
821
|
+
})()
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
// 主动搭话(P1-3):调 brain.py speak-up --json,命中就把那句话注入下一轮上下文。
|
|
825
|
+
// 四道闸全在 Python 侧(概率/冷却/理智/是否提问),插件不做判断、不重复实现,
|
|
826
|
+
// 避免两边规则漂移。失败一律静默——它是锦上添花,绝不能拖住回合。
|
|
827
|
+
function fireSpeakUp(agent) {
|
|
828
|
+
if (running.has('speakup')) return
|
|
829
|
+
const stmt = (lastUser.get(agent) || '').trim()
|
|
830
|
+
running.add('speakup')
|
|
831
|
+
;(async () => {
|
|
832
|
+
try {
|
|
833
|
+
const brainPy = await ensureBrainPy()
|
|
834
|
+
if (!brainPy) return
|
|
835
|
+
const pythonExe = findPythonExe(cfg.python)
|
|
836
|
+
// 任务文本走**临时文件**而不是命令行(防命令注入),与 prior 同一套做法
|
|
837
|
+
const base = process.env.APP_APP || join(homedir(), '.app')
|
|
838
|
+
mkdirSync(base, { recursive: true })
|
|
839
|
+
const tmp = join(base, `lingshu-speak-${randomUUID()}.txt`)
|
|
840
|
+
try {
|
|
841
|
+
writeFileSync(tmp, stmt, 'utf8')
|
|
842
|
+
const r = await runBrain(pythonExe, cfg.python, brainPy,
|
|
843
|
+
['speak-up', '--statement-file', tmp, '--cleanup', '--json'], cfg.timeoutMs)
|
|
844
|
+
if (!r.ok || !r.out) return
|
|
845
|
+
let r2 = null
|
|
846
|
+
try { r2 = JSON.parse(String(r.out).trim().split('\n').pop()) } catch { return }
|
|
847
|
+
if (!r2 || !r2.triggered || !r2.text) return
|
|
848
|
+
// 注入给下一轮:明确标成"灵枢自己想说的",别让宿主误以为是用户说的
|
|
849
|
+
const text = `[灵枢主动开口] ${r2.text}`
|
|
850
|
+
pendingNotice.set(agent, text)
|
|
851
|
+
} finally {
|
|
852
|
+
try { rmSync(tmp, { force: true }) } catch {}
|
|
853
|
+
}
|
|
854
|
+
} catch {} finally { running.delete('speakup') }
|
|
855
|
+
})()
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// 每轮结束:轮次驱动的静默任务(dream / usage)+ 天驱动任务(daily/backup/conflicts/selfreview)
|
|
859
|
+
ctx.on('agent/turn-stopping', (payload) => {
|
|
860
|
+
try {
|
|
861
|
+
beatHost() // B5:每回合一次心跳,给外部 watchdog 判断宿主存活
|
|
862
|
+
const agent = payload?.agent
|
|
863
|
+
if (!agent) return
|
|
864
|
+
const ak = agentKey(agent)
|
|
865
|
+
// 轮数唯一事实源是状态文件 state.turns[ak](#77):重启续算不再依赖内存 map,
|
|
866
|
+
// 内存 turns 只在拿不到稳定 ak 时兜底,避免双轨计数互相回退。
|
|
867
|
+
let prev
|
|
868
|
+
if (ak && Number.isFinite(Number(state.turns?.[ak]))) prev = Number(state.turns[ak])
|
|
869
|
+
else prev = turns.get(agent) ?? 0
|
|
870
|
+
const n = prev + 1
|
|
871
|
+
turns.set(agent, n)
|
|
872
|
+
// 轮数落盘:节流写(30s 合并刷盘,#69),重启后按状态文件续算
|
|
873
|
+
if (ak) {
|
|
874
|
+
state.turns = state.turns || {}
|
|
875
|
+
if (state.turns[ak] !== n) {
|
|
876
|
+
state.turns[ak] = n
|
|
877
|
+
markStateDirty()
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
const silentTasks = [
|
|
882
|
+
{ id: 'dream', turns: cfg.dreamTurns, argv: ['dream', '--auto'] },
|
|
883
|
+
{ id: 'daily', days: 1, argv: ['daily'] },
|
|
884
|
+
// 备份:按小时(config.backup_interval_hours,默认 6),不再是"每天一次"
|
|
885
|
+
// ⚠ 必须带 --yes:非交互环境下 `backup` 会打印"已取消"并 exit 0,
|
|
886
|
+
// 什么都不建却算成功 —— 按小时备份会永远空转(实测踩过)。
|
|
887
|
+
{ id: 'backup', hours: cfg.backupIntervalHours ?? 6, argv: ['backup', '--yes'] },
|
|
888
|
+
// APP 上下文的自动压缩(v5.34):水位过阈值时把可折叠的整轮压成摘要并记账。
|
|
889
|
+
// 只写账本;真正替换 decision.messages 由 startup 插件的 contextFold 开关控制。
|
|
890
|
+
{ id: 'autofold', hours: 1, argv: ['context', 'autofold', '--min-pct', '60'] },
|
|
891
|
+
// 自动更新:默认关(config.auto_update=false 时 auto-update 自己会跳过)
|
|
892
|
+
{ id: 'autoupdate', hours: cfg.autoUpdateIntervalHours ?? 24, argv: ['auto-update'] },
|
|
893
|
+
{ id: 'conflicts', days: 1, argv: ['detect-conflicts'] },
|
|
894
|
+
{ id: 'selfreview', days: cfg.selfReviewDays, argv: ['skill', 'self-review'] },
|
|
895
|
+
// 第④步:每日静默 persona drift —— 扫描近 1 天记忆的情感倾向,
|
|
896
|
+
// 微调 state.mood_score(0=阴郁 100=明快),真实变化才落盘并记账
|
|
897
|
+
{ id: 'drift', days: 1, argv: ['drift', '--days', '1'] },
|
|
898
|
+
// 第⑤步:每日自动归档 —— 把审核通过的 pending 记忆按"事实型→知识库 /
|
|
899
|
+
// 事件型→日记"分类转正(原记忆只加 archived_at 标记,绝不删)
|
|
900
|
+
{ id: 'autoarchive', days: 1, argv: ['auto-archive'] },
|
|
901
|
+
// 淡忘区超量自动归档(v5.34):只挪"超出 keep 的最旧那部分",
|
|
902
|
+
// 封存原文/受保护项不动;原文保真,archive restore 可回热。
|
|
903
|
+
{ id: 'dustarchive', days: 1, argv: ['archive', 'dust'] },
|
|
904
|
+
]
|
|
905
|
+
for (const t of silentTasks) {
|
|
906
|
+
if (t.turns && n % t.turns === 0) fire(t)
|
|
907
|
+
if (t.days && dueByDays(t, state)) fire(t)
|
|
908
|
+
if (t.hours && dueByHours(t, state, t.hours)) fire(t)
|
|
909
|
+
}
|
|
910
|
+
if (cfg.runUsage) {
|
|
911
|
+
// usage --reply 用"最后一条 assistant 回复"的真实文本统计记忆是否被用上;
|
|
912
|
+
// 传空串会导致关键词重叠恒 0、每条记忆都记成"没被用上",污染使用率统计。
|
|
913
|
+
// 没有真实回复文本时宁可跳过本轮,也不给假数据。
|
|
914
|
+
const reply = (lastReply.get(agent) || '').trim()
|
|
915
|
+
if (reply) fire({ id: 'usage', argv: ['usage', '--reply', reply.slice(0, 4000)] })
|
|
916
|
+
}
|
|
917
|
+
// 即记即存:每 N 轮把攒的对话文本静默封存进海马体
|
|
918
|
+
if (cfg.extractTurns > 0 && n % cfg.extractTurns === 0) fireExtract(agent)
|
|
919
|
+
// 主动搭话(P1-3):掷骰子在 brain.py 里做(概率/冷却/理智/是否提问四道闸),
|
|
920
|
+
// 这里只负责"问一句要不要说"并在命中时把话注入。**不 await**,失败静默。
|
|
921
|
+
fireSpeakUp(agent)
|
|
922
|
+
} catch {} // turn-stopping 是串行事件,任何异常都不能拖住回合关闭
|
|
923
|
+
})
|
|
924
|
+
|
|
925
|
+
// ── 盈不足标定(v5.2)──────────────────────────────────────────────
|
|
926
|
+
// 估算模型是 tokens = chars / ratio + overhead,有两个未知数。宿主偶尔会给出
|
|
927
|
+
// **真实 token 数**,那就是"盈不足"里的两次假设:拿 ≥2 组 (chars, tokens) 做
|
|
928
|
+
// 最小二乘,同时反推 ratio 与 overhead,比把 overhead 写死 18000 准得多。
|
|
929
|
+
// 只写 token-calib.jsonl / token-calib.json 两个新文件,绝不碰记忆数据。
|
|
930
|
+
const CALIB_SAMPLES = 500 // 最多留多少组样本
|
|
931
|
+
const CALIB_MIN_SPAN = 2000 // 两组样本字符差至少要这么大才有解
|
|
932
|
+
const _calibState = { lastAt: 0, lastChars: 0, cache: null }
|
|
933
|
+
|
|
934
|
+
function _calibPaths() {
|
|
935
|
+
try {
|
|
936
|
+
const home = readBrainHome()
|
|
937
|
+
if (!home) return null
|
|
938
|
+
return { samples: join(home, 'token-calib.jsonl'), fit: join(home, 'token-calib.json') }
|
|
939
|
+
} catch { return null }
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
function _fitFrom(samples) {
|
|
943
|
+
// 最小二乘拟合 y = a + b·x(等价于以字符数为自变量预测 token)
|
|
944
|
+
const n = samples.length
|
|
945
|
+
if (n < 2) return null
|
|
946
|
+
const xs = samples.map((s) => s.chars), ys = samples.map((s) => s.tokens)
|
|
947
|
+
const minX = Math.min(...xs), maxX = Math.max(...xs)
|
|
948
|
+
if (maxX - minX < CALIB_MIN_SPAN) return null // 跨度太小,解不稳定
|
|
949
|
+
const mx = xs.reduce((a, b) => a + b, 0) / n
|
|
950
|
+
const my = ys.reduce((a, b) => a + b, 0) / n
|
|
951
|
+
let sxx = 0, sxy = 0
|
|
952
|
+
for (let i = 0; i < n; i++) {
|
|
953
|
+
sxx += (xs[i] - mx) ** 2
|
|
954
|
+
sxy += (xs[i] - mx) * (ys[i] - my)
|
|
955
|
+
}
|
|
956
|
+
if (!(sxx > 0)) return null
|
|
957
|
+
const b = sxy / sxx // tokens per char
|
|
958
|
+
const a = my - b * mx // overhead
|
|
959
|
+
if (!(b > 0)) return null
|
|
960
|
+
const ratio = 1 / b
|
|
961
|
+
// 合理性闸:中文语境 1 字符大致 0.4~1 token;overhead 上万但不该离谱
|
|
962
|
+
if (!(ratio >= 0.5 && ratio <= 5)) return null
|
|
963
|
+
if (!(a >= 0 && a <= 200000)) return null
|
|
964
|
+
return { charsPerToken: Number(ratio.toFixed(3)),
|
|
965
|
+
systemOverheadTokens: Math.round(a), samples: n,
|
|
966
|
+
at: Math.floor(Date.now() / 1000) }
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
function _readCalibFit() {
|
|
970
|
+
if (_calibState.cache) return _calibState.cache
|
|
971
|
+
try {
|
|
972
|
+
const paths = _calibPaths()
|
|
973
|
+
if (!paths) return null
|
|
974
|
+
const raw = readFileSync(paths.fit, 'utf8')
|
|
975
|
+
const j = JSON.parse(raw)
|
|
976
|
+
if (!(j && j.charsPerToken > 0 && j.systemOverheadTokens >= 0)) return null
|
|
977
|
+
_calibState.cache = j
|
|
978
|
+
return j
|
|
979
|
+
} catch { return null }
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
function _recordCalib(chars, tokens) {
|
|
983
|
+
try {
|
|
984
|
+
if (!(chars > 0) || !(tokens > 0)) return
|
|
985
|
+
const now = Date.now()
|
|
986
|
+
// 限流:60 秒内且字符差不足 2000 就不记(热路径,别每轮都写盘)
|
|
987
|
+
if (now - _calibState.lastAt < 60000
|
|
988
|
+
&& Math.abs(chars - _calibState.lastChars) < CALIB_MIN_SPAN) return
|
|
989
|
+
_calibState.lastAt = now
|
|
990
|
+
_calibState.lastChars = chars
|
|
991
|
+
const paths = _calibPaths()
|
|
992
|
+
if (!paths) return
|
|
993
|
+
appendFileSync(paths.samples,
|
|
994
|
+
JSON.stringify({ chars, tokens, at: Math.floor(now / 1000) }) + '\n')
|
|
995
|
+
// 读回来拟合(顺带裁到最近 CALIB_SAMPLES 条,防无限膨胀)
|
|
996
|
+
let lines = []
|
|
997
|
+
try {
|
|
998
|
+
lines = readFileSync(paths.samples, 'utf8').split('\n').filter((x) => x.trim())
|
|
999
|
+
} catch { return }
|
|
1000
|
+
const tail = lines.slice(-CALIB_SAMPLES)
|
|
1001
|
+
if (lines.length > CALIB_SAMPLES * 2) {
|
|
1002
|
+
try { writeFileSync(paths.samples, tail.join('\n') + '\n') } catch {}
|
|
1003
|
+
}
|
|
1004
|
+
const samples = []
|
|
1005
|
+
for (const line of tail) {
|
|
1006
|
+
try {
|
|
1007
|
+
const o = JSON.parse(line)
|
|
1008
|
+
if (o && o.chars > 0 && o.tokens > 0) samples.push(o)
|
|
1009
|
+
} catch {}
|
|
1010
|
+
}
|
|
1011
|
+
const fit = _fitFrom(samples)
|
|
1012
|
+
if (fit) {
|
|
1013
|
+
try { writeFileSync(paths.fit, JSON.stringify(fit, null, 2)) } catch {}
|
|
1014
|
+
_calibState.cache = fit
|
|
1015
|
+
}
|
|
1016
|
+
} catch {}
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
// 水位估算:宿主给了 usage 就用真值(prompt 侧 = 未缓存 + 缓存读 + 缓存写);
|
|
1020
|
+
// 否则按「消息正文字符数 + system/工具固定开销」折算。
|
|
1021
|
+
// v3.23 修:旧版只数 messages 的 text 字符,system prompt 与工具 schema 完全不计,
|
|
1022
|
+
// 而本 profile 光这两项就上万 token —— 真实 65% 时估算只有 20%,阈值永远不触发。
|
|
1023
|
+
// 返回 {pct, source};拿不到任何依据返回 null。
|
|
1024
|
+
/**
|
|
1025
|
+
* 水位诊断转储(v5.32):把"插件实际看到的 messages 形态"写盘,30 秒最多一次。
|
|
1026
|
+
* 起因:递归收集修好后 chars 仍只有 915,而真实会话约需 10 万字符——
|
|
1027
|
+
* 必须确认是"拿不到历史"还是"字段名不对",不能再靠猜。
|
|
1028
|
+
*/
|
|
1029
|
+
function _dumpWaterDebug(msgs, acc) {
|
|
1030
|
+
try {
|
|
1031
|
+
const now = Date.now()
|
|
1032
|
+
if (now - _waterDebugAt < 30000) return
|
|
1033
|
+
_waterDebugAt = now
|
|
1034
|
+
const kinds = {}
|
|
1035
|
+
let withUsage = 0
|
|
1036
|
+
let sample = null
|
|
1037
|
+
for (const m of msgs) {
|
|
1038
|
+
const c = m?.content
|
|
1039
|
+
const kind = Array.isArray(c) ? 'array' : (c === undefined ? 'undefined' : typeof c)
|
|
1040
|
+
kinds[kind] = (kinds[kind] || 0) + 1
|
|
1041
|
+
const u = m?.metadata?.usage || m?.usage || m?.modelUsage
|
|
1042
|
+
if (u && typeof u === 'object') withUsage += 1
|
|
1043
|
+
if (!sample && m) {
|
|
1044
|
+
sample = {
|
|
1045
|
+
role: m.role ?? null,
|
|
1046
|
+
srcName: m?.source?.name ?? null,
|
|
1047
|
+
contentKind: kind,
|
|
1048
|
+
contentLen: Array.isArray(c) ? c.length
|
|
1049
|
+
: (typeof c === 'string' ? c.length : null),
|
|
1050
|
+
blockTypes: Array.isArray(c)
|
|
1051
|
+
? c.slice(0, 6).map((b) => b?.type ?? typeof b) : null,
|
|
1052
|
+
topKeys: Object.keys(m || {}).slice(0, 14),
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
writeFileSync(join(memoryHome(), '_pressure_debug.json'), JSON.stringify({
|
|
1057
|
+
at: Math.floor(now / 1000),
|
|
1058
|
+
msgCount: msgs.length,
|
|
1059
|
+
contentKinds: kinds,
|
|
1060
|
+
msgsWithUsage: withUsage,
|
|
1061
|
+
countedCjk: acc.cjk,
|
|
1062
|
+
countedOther: acc.other,
|
|
1063
|
+
sampleFirstMsg: sample,
|
|
1064
|
+
}, null, 2), 'utf8')
|
|
1065
|
+
} catch {
|
|
1066
|
+
/* 诊断失败绝不影响主流程 */
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
/**
|
|
1071
|
+
* 读 APP tokenMeter 的准确上下文压力快照(v3.86 起由 startup 插件写)。
|
|
1072
|
+
* 这是**唯一能拿到真实上下文用量**的来源:pre-step 的 messages 只有本轮几条,
|
|
1073
|
+
* 靠它算字符永远是猜。返回 {pct, tokens, window} 或 null(不可用/过期)。
|
|
1074
|
+
*/
|
|
1075
|
+
function _readTokenMeter(ttlSec = 300) {
|
|
1076
|
+
try {
|
|
1077
|
+
const raw = JSON.parse(
|
|
1078
|
+
readFileSync(join(memoryHome(), '.context-pressure.json'), 'utf8'))
|
|
1079
|
+
if (!raw || raw.available !== true) return null
|
|
1080
|
+
const pct = Number(raw.pct)
|
|
1081
|
+
if (!Number.isFinite(pct) || pct < 0 || pct > 100) return null
|
|
1082
|
+
const ts = Number(raw.ts)
|
|
1083
|
+
if (Number.isFinite(ts) && Date.now() / 1000 - ts > ttlSec) return null
|
|
1084
|
+
return {
|
|
1085
|
+
pct: Math.min(100, Math.round(pct)),
|
|
1086
|
+
tokens: Number(raw.pressure_tokens) || null,
|
|
1087
|
+
window: Number(raw.context_window) || null,
|
|
1088
|
+
}
|
|
1089
|
+
} catch {
|
|
1090
|
+
return null
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
function estimateWater(agent, decision) {
|
|
1095
|
+
try {
|
|
1096
|
+
// ★ 真值优先:APP tokenMeter 给的 pct 是它自己按真实 token 计量的,
|
|
1097
|
+
// 比"数本轮消息字符"准得多(实测 65.7% vs 估算 14%)。
|
|
1098
|
+
// 拿到就直接用,估算只做兜底(审计:水位长期被判低 4 倍以上)。
|
|
1099
|
+
const _tm = _readTokenMeter()
|
|
1100
|
+
if (_tm) {
|
|
1101
|
+
return { pct: _tm.pct, source: 'token-meter',
|
|
1102
|
+
chars: null, tokens: _tm.tokens,
|
|
1103
|
+
limit: _tm.window || cfg.contextLimit }
|
|
1104
|
+
}
|
|
1105
|
+
const msgs = Array.isArray(decision?.messages) ? decision.messages : []
|
|
1106
|
+
const num = (x) => (Number.isFinite(x) ? x : 0)
|
|
1107
|
+
// 先把"真实对话字符数"算出来:既给下面的 chars 分支用,也给盈不足标定
|
|
1108
|
+
// 提供自变量(宿主给真值 token 时才成对记录)。
|
|
1109
|
+
// 按语言分开统计字符:中文与英文的 token 换算率差一倍(见下方官方口径)
|
|
1110
|
+
let dialogCjk = 0, dialogOther = 0 // 纯对话
|
|
1111
|
+
let lingshuCjk = 0, lingshuOther = 0 // 灵枢注入(不算"对话",但真的占上下文)
|
|
1112
|
+
// ★ 递归收集一条消息占用的全部文本,并**按语言分开计数**(v5.32)。
|
|
1113
|
+
// 为什么必须递归:APP 的 content 块里,工具结果的正文**不在 c.text**,
|
|
1114
|
+
// 而在 c.content(可能是字符串、数组、或再嵌套一层 {type:'text',text})。
|
|
1115
|
+
// 原来只看顶层 c.text → 工具结果整块漏计。而实测这类块占上下文绝大部分
|
|
1116
|
+
// (读文件、跑命令、grep 结果),漏掉会把水位低估数倍——本会话就是
|
|
1117
|
+
// 报 14% 而实际 50%。
|
|
1118
|
+
// 为什么分语言:DeepSeek 官方口径是「1 中文字符 ≈ 0.6 token,
|
|
1119
|
+
// 1 英文字符 ≈ 0.3 token」。原来一律按「2 字符 = 1 token」折算,
|
|
1120
|
+
// 等于中文按 0.5 算(低估 17%)、英文按 0.5 算(高估 67%)。
|
|
1121
|
+
// tool_use 的 input(JSON 参数)同样占位,一并计入(按英算)。
|
|
1122
|
+
const CJK = /[\u3000-\u303f\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uffef]/
|
|
1123
|
+
const collectChars = (node, acc) => {
|
|
1124
|
+
if (node == null) return acc
|
|
1125
|
+
if (typeof node === 'string') {
|
|
1126
|
+
for (const ch of node) {
|
|
1127
|
+
if (CJK.test(ch)) acc.cjk += 1
|
|
1128
|
+
else acc.other += 1
|
|
1129
|
+
}
|
|
1130
|
+
return acc
|
|
1131
|
+
}
|
|
1132
|
+
if (Array.isArray(node)) { for (const x of node) collectChars(x, acc); return acc }
|
|
1133
|
+
if (typeof node !== 'object') return acc
|
|
1134
|
+
if (typeof node.text === 'string') collectChars(node.text, acc)
|
|
1135
|
+
if (typeof node.content === 'string') collectChars(node.content, acc)
|
|
1136
|
+
else if (node.content !== undefined) collectChars(node.content, acc)
|
|
1137
|
+
for (const k of ('parts', 'data')) {
|
|
1138
|
+
if (node[k] !== undefined) collectChars(node[k], acc)
|
|
1139
|
+
}
|
|
1140
|
+
if (node.input !== undefined) {
|
|
1141
|
+
try { collectChars(JSON.stringify(node.input), acc) } catch { /* 循环引用等,跳过 */ }
|
|
1142
|
+
}
|
|
1143
|
+
return acc
|
|
1144
|
+
}
|
|
1145
|
+
for (const m of msgs) {
|
|
1146
|
+
const isLingshu = LINGSHU_SOURCES.has(m?.source?.name)
|
|
1147
|
+
const acc = { cjk: 0, other: 0 }
|
|
1148
|
+
collectChars(m?.content, acc)
|
|
1149
|
+
const n = acc.cjk + acc.other
|
|
1150
|
+
if (n <= 0) continue
|
|
1151
|
+
if (isLingshu) { lingshuCjk += acc.cjk; lingshuOther += acc.other }
|
|
1152
|
+
else { dialogCjk += acc.cjk; dialogOther += acc.other }
|
|
1153
|
+
}
|
|
1154
|
+
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
1155
|
+
const u = msgs[i]?.metadata?.usage || msgs[i]?.usage || msgs[i]?.modelUsage
|
|
1156
|
+
|| msgs[i]?.metadata?.modelUsage
|
|
1157
|
+
if (!u || typeof u !== 'object') continue
|
|
1158
|
+
const prompt = num(u.inputTokens ?? u.promptTokens) + num(u.cacheReadTokens)
|
|
1159
|
+
+ num(u.cacheWriteTokens)
|
|
1160
|
+
const total = num(u.totalTokens)
|
|
1161
|
+
const used = total > 0 ? total : prompt
|
|
1162
|
+
if (used > 0) {
|
|
1163
|
+
// 盈不足:拿到真值时顺手记一组 (字符数, 真实 token),交给 _recordCalib 拟合。
|
|
1164
|
+
// 用纯对话字符而不是含注入的总量:灵枢注入的体积每次都变,掺进拟合会把斜率带偏。
|
|
1165
|
+
_recordCalib(dialogCjk + dialogOther, used)
|
|
1166
|
+
return { pct: Math.min(100, Math.round(used / cfg.contextLimit * 100)),
|
|
1167
|
+
source: 'usage', chars: dialogCjk + dialogOther,
|
|
1168
|
+
tokens: used, limit: cfg.contextLimit }
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
_dumpWaterDebug(msgs, { cjk: dialogCjk + lingshuCjk,
|
|
1172
|
+
other: dialogOther + lingshuOther })
|
|
1173
|
+
// 含注入的**总**字符/词元:水位分母要用它(注入真的占上下文空间)
|
|
1174
|
+
const chars = dialogCjk + dialogOther + lingshuCjk + lingshuOther
|
|
1175
|
+
if (!chars) {
|
|
1176
|
+
// v3.57(保护 C):原来这里直接 return null,守卫就此静默跳过——「以为没到水位,
|
|
1177
|
+
// 其实已经快满」正是要防的情况。现在至少按 system/工具固定开销给一个下限
|
|
1178
|
+
// (拿不到正文时它也是真实存在的成本),并标明来源,让提醒口径说实话。
|
|
1179
|
+
const floor = Number(cfg.systemOverheadTokens) || 0
|
|
1180
|
+
if (!floor) return null
|
|
1181
|
+
return { pct: Math.min(100, Math.round(floor / cfg.contextLimit * 100)),
|
|
1182
|
+
source: 'floor', chars: 0, tokens: floor, limit: cfg.contextLimit }
|
|
1183
|
+
}
|
|
1184
|
+
// 词元折算:**官方口径优先**——中文 0.6 token/字、其他 0.3 token/字。
|
|
1185
|
+
// (DeepSeek 文档:1 Chinese character ≈ 0.6 token,1 English character ≈ 0.3 token)
|
|
1186
|
+
// 拟合值(盈不足标定过)仍可用,但只作为"整体偏差修正系数"乘在官方口径上,
|
|
1187
|
+
// 不再用那个一刀切的 charsPerToken=2——它对中文低估、对英文高估。
|
|
1188
|
+
const _fit = _readCalibFit()
|
|
1189
|
+
const _over = _fit ? _fit.systemOverheadTokens : (cfg.systemOverheadTokens || 0)
|
|
1190
|
+
const cjkTokens = (dialogCjk + lingshuCjk) * 0.6
|
|
1191
|
+
const otherTokens = (dialogOther + lingshuOther) * 0.3
|
|
1192
|
+
let body = cjkTokens + otherTokens
|
|
1193
|
+
if (_fit && _fit.charsPerToken > 0) {
|
|
1194
|
+
// 标定得到的是"每 token 多少字符",换算成对官方口径的缩放比
|
|
1195
|
+
const officialRatio = chars / Math.max(1, body)
|
|
1196
|
+
body *= Math.max(0.5, Math.min(2.0, officialRatio / _fit.charsPerToken)) || 1
|
|
1197
|
+
}
|
|
1198
|
+
const tokens = body + _over
|
|
1199
|
+
return { pct: Math.min(100, Math.round(tokens / cfg.contextLimit * 100)),
|
|
1200
|
+
source: _fit ? 'chars+calib' : 'chars',
|
|
1201
|
+
chars, tokens: Math.round(tokens), limit: cfg.contextLimit }
|
|
1202
|
+
} catch { return null }
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
// 注入类:只在 enter 分支追加消息,有内容才注,缓存 review 查询
|
|
1206
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
1207
|
+
let decision
|
|
1208
|
+
try {
|
|
1209
|
+
decision = await next()
|
|
1210
|
+
if (!decision || decision.kind !== 'enter') return decision
|
|
1211
|
+
const { agent } = payload || {}
|
|
1212
|
+
if (!agent) return decision
|
|
1213
|
+
|
|
1214
|
+
// 上下文清理(v3.59 起默认关闭):只清**本插件自己**注入过的旧提醒。
|
|
1215
|
+
// 两个要点:
|
|
1216
|
+
// 1. 只认 `INJECT_SOURCE`('lingshu-cron'),绝不碰 startup 的
|
|
1217
|
+
// 'lingshu-startup' 记忆块,也不碰 im 的 'lingshu-im';
|
|
1218
|
+
// 2. 默认不执行——删历史中段的消息会改写提示词缓存前缀,后续全部无法
|
|
1219
|
+
// 复用(见 DEFAULTS 里 pruneInjected 的说明)。用户显式开启才清。
|
|
1220
|
+
try {
|
|
1221
|
+
if (cfg.pruneInjected) {
|
|
1222
|
+
const msgs = Array.isArray(decision.messages) ? decision.messages : []
|
|
1223
|
+
const kept = msgs.filter((m) => m?.source?.name !== INJECT_SOURCE)
|
|
1224
|
+
if (kept.length !== msgs.length) {
|
|
1225
|
+
decision = { ...decision, messages: kept }
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
} catch {}
|
|
1229
|
+
// 即记即存缓冲:只攒"本步新增"的文本——按消息 id 记游标,重复推送的旧消息
|
|
1230
|
+
// 不重复入缓冲(否则缓冲膨胀、extract 内容重复)。同时记录最后一条
|
|
1231
|
+
// assistant 文本给 usage --reply 用(usage 需要真实回复,不能传空串)。
|
|
1232
|
+
try {
|
|
1233
|
+
const msgs = Array.isArray(decision.messages) ? decision.messages : []
|
|
1234
|
+
if (msgs.length) {
|
|
1235
|
+
const buf = convo.get(agent) || { text: '', seen: [] }
|
|
1236
|
+
const seenIds = new Set(Array.isArray(buf.seen) ? buf.seen : [])
|
|
1237
|
+
let text = buf.text
|
|
1238
|
+
let lastAsst = lastReply.get(agent) || ''
|
|
1239
|
+
let batchIds = []
|
|
1240
|
+
for (const m of msgs) {
|
|
1241
|
+
const mid = m?.id
|
|
1242
|
+
if (mid != null) {
|
|
1243
|
+
if (seenIds.has(mid)) continue // 上一步已攒过这条,跳过(只加增量)
|
|
1244
|
+
batchIds.push(mid)
|
|
1245
|
+
}
|
|
1246
|
+
for (const c of (Array.isArray(m?.content) ? m.content : [])) {
|
|
1247
|
+
if (c?.type === 'text' && typeof c.text === 'string' && c.text.trim()) {
|
|
1248
|
+
const t = c.text.trim()
|
|
1249
|
+
if (m.role === 'assistant') lastAsst = t.slice(0, 4000)
|
|
1250
|
+
else if (m.role === 'user' && !LINGSHU_SOURCES.has(m?.source?.name)) {
|
|
1251
|
+
lastUser.set(agent, t.slice(0, 400))
|
|
1252
|
+
}
|
|
1253
|
+
text += (text ? '\n' : '') + m.role + ':' + t.slice(0, 4000) + '\n'
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
// 游标:只保留最近几批的 id(防无限增长),本批新 id 全部记入
|
|
1258
|
+
if (batchIds.length) {
|
|
1259
|
+
seenIds.add(`\0batch:${JSON.stringify(batchIds)}`)
|
|
1260
|
+
}
|
|
1261
|
+
convo.set(agent, {
|
|
1262
|
+
text,
|
|
1263
|
+
seen: [...seenIds].slice(-16), // 最近 16 个批次标记足够覆盖重推场景
|
|
1264
|
+
})
|
|
1265
|
+
if (lastAsst) lastReply.set(agent, lastAsst)
|
|
1266
|
+
}
|
|
1267
|
+
} catch {}
|
|
1268
|
+
|
|
1269
|
+
// 主动搭话(P1-3):上一轮 turn-stopping 决定要说的那句,这里注入。
|
|
1270
|
+
// 只注入一次(取走即删);明确标成"灵枢主动开口",别让模型以为是用户在说话。
|
|
1271
|
+
if (pendingNotice.has(agent)) {
|
|
1272
|
+
const _say = pendingNotice.get(agent)
|
|
1273
|
+
pendingNotice.delete(agent)
|
|
1274
|
+
if (_say) {
|
|
1275
|
+
decision = {
|
|
1276
|
+
...decision,
|
|
1277
|
+
messages: [...(decision.messages || []), notice(
|
|
1278
|
+
`${_say}\n(这句是你自己想说的,不是用户说的。自然地接着说即可;` +
|
|
1279
|
+
`若与本轮用户输入无关,可以简短带过,不必硬拗。)`)],
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
const n = (turns.get(agent) ?? 1)
|
|
1285
|
+
const brainPy = await ensureBrainPy()
|
|
1286
|
+
if (!brainPy) return decision
|
|
1287
|
+
const pythonExe = findPythonExe(cfg.python)
|
|
1288
|
+
|
|
1289
|
+
// 0) 水位估算:注入与自动执行共用同一口径(宿主 usage 优先,否则
|
|
1290
|
+
// 「消息字符 + system/工具固定开销」)。只在需要时才算:waterGuard 关闭
|
|
1291
|
+
// 且 water 自动执行全关时,默认零开销。
|
|
1292
|
+
const waterAutoCfg = loadWaterAutoConfig()
|
|
1293
|
+
const waterArmed = waterAutoCfg.autoDream === true || waterAutoCfg.autoCapture === true
|
|
1294
|
+
const est = (cfg.waterGuard || waterArmed) ? estimateWater(agent, decision) : null
|
|
1295
|
+
const pct = est && Number.isFinite(est.pct) ? est.pct : null
|
|
1296
|
+
|
|
1297
|
+
// 1) 水位自动执行(v3.44,默认全关):放在 review 之前判定——review 有待确认时
|
|
1298
|
+
// 会提前 return,不能让它挡掉「75% 该做梦 / 90% 该逃生」的自动动作。
|
|
1299
|
+
// 真执行走 fire() 的后台通道,绝不 await。
|
|
1300
|
+
try {
|
|
1301
|
+
const autoNotice = runWaterAuto(agent, pct, est?.source || '', waterAutoCfg)
|
|
1302
|
+
if (autoNotice) {
|
|
1303
|
+
decision = { ...decision, messages: [...decision.messages, notice(autoNotice)] }
|
|
1304
|
+
}
|
|
1305
|
+
} catch {} // 自动执行判定异常不能拖住 pre-step
|
|
1306
|
+
|
|
1307
|
+
// 2) review 提醒(v3.57 降级):原来是"每轮 + 命令式"——「先运行 lingshu review
|
|
1308
|
+
// 确认或丢弃,再继续当前任务」,逼模型每次都先跑一轮工具才回答(实测多一轮
|
|
1309
|
+
// 工具往返 ≈ TTFT +2~4s,且用户会感觉"开局慢")。现在:
|
|
1310
|
+
// · 文案改成非命令式("有空再看"),不再抢占回答;
|
|
1311
|
+
// · 每会话最多提醒一次(reviewNoticeOnce 默认 true);
|
|
1312
|
+
// · 待审条数达到 reviewNoticeMin(默认 5)才提,零星一两条留给用户自己看。
|
|
1313
|
+
if (cfg.injectReview) {
|
|
1314
|
+
if (Date.now() - reviewCacheAt > cfg.reviewCacheMs) {
|
|
1315
|
+
const _rv = await runBrain(pythonExe, cfg.python, brainPy, ['review', '--json'], 15000)
|
|
1316
|
+
try {
|
|
1317
|
+
const parsed = _rv.ok && _rv.out ? JSON.parse(_rv.out) : null
|
|
1318
|
+
reviewCacheVal = parsed
|
|
1319
|
+
reviewCacheAt = Date.now()
|
|
1320
|
+
} catch {
|
|
1321
|
+
reviewCacheVal = null // JSON 损坏视作无 pending,下个缓存周期再试
|
|
1322
|
+
reviewCacheAt = Date.now()
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
const memCount = (reviewCacheVal?.memories?.length ?? 0)
|
|
1326
|
+
+ (reviewCacheVal?.knowledge?.length ?? 0)
|
|
1327
|
+
+ (reviewCacheVal?.persona?.length ?? 0)
|
|
1328
|
+
// 已达下限、且没在本会话提醒过(reviewNoticeOnce=false 时每次都提)
|
|
1329
|
+
const alreadyNoticed = reviewNoticeAt.get(agent) === true
|
|
1330
|
+
const gated = cfg.reviewNoticeOnce && alreadyNoticed
|
|
1331
|
+
if (memCount >= Math.max(1, Number(cfg.reviewNoticeMin) || 1) && !gated) {
|
|
1332
|
+
reviewNoticeAt.set(agent, true)
|
|
1333
|
+
return {
|
|
1334
|
+
...decision,
|
|
1335
|
+
messages: [...decision.messages, notice(
|
|
1336
|
+
`【灵枢审核】有 ${memCount} 条 AI 整理的记忆待确认(不急,有空 \`lingshu review\` 看一眼即可,不影响当前任务)。`,
|
|
1337
|
+
)],
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
// 3) 水位守卫(v3.01 设计 / v3.23 修估算口径):用上面算好的 est/pct,
|
|
1343
|
+
// 首次跨过 60/75/90 各注入一条带真实数字的提醒。
|
|
1344
|
+
// 另加软自检:每 waterCheckTurns 轮若还没跨阈值,也戳一下,防止估算偏低时永远不响。
|
|
1345
|
+
if (cfg.waterGuard) {
|
|
1346
|
+
const st = waterState.get(agent) || { max: 0, softAt: -1, lastPct: null }
|
|
1347
|
+
if (pct != null) {
|
|
1348
|
+
// v3.57(保护 A 的写入端):把真实水位落成 HOME/_pressure.json,注入侧
|
|
1349
|
+
// (memory.build_injection 读 core.read_pressure)据此整体降档。
|
|
1350
|
+
// 每跨 5 个百分点或跨档时写一次,避免每步都写盘;失败静默(不能拖住 pre-step)。
|
|
1351
|
+
writePressure(pct, est?.source || 'unknown', st.max || 0, est)
|
|
1352
|
+
|
|
1353
|
+
// v3.57(保护 B):95 / 98 两个硬档。90 仍是"建议"(用户可能还想继续干活),
|
|
1354
|
+
// 95 改命令式,98 起自动做**无破坏性**自救(auto-archive 只打归档标记、
|
|
1355
|
+
// diagnose 只报告),绝不自动 capture(拿不到原文)也绝不 purge(物理删除)。
|
|
1356
|
+
const th = pressureThresholds()
|
|
1357
|
+
if (pct >= th.force_at) {
|
|
1358
|
+
const did = await runForceActions(pythonExe, brainPy)
|
|
1359
|
+
if (st.forceAt !== true) {
|
|
1360
|
+
st.forceAt = true
|
|
1361
|
+
waterState.set(agent, st)
|
|
1362
|
+
return {
|
|
1363
|
+
...decision,
|
|
1364
|
+
messages: [...decision.messages, notice(
|
|
1365
|
+
`【灵枢·水位 ${pct}%】已到强制自救线(${th.force_at}%),已自动执行无破坏性压缩:${did || '无可用动作'}。`
|
|
1366
|
+
+ `现在只做三件事之一:① 让用户确认封存 capture;② 结束本轮话题;③ 继续也得先说明风险。不要再开新话题。`,
|
|
1367
|
+
)],
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
return decision
|
|
1371
|
+
}
|
|
1372
|
+
if (pct >= th.hard_at && st.hardAt !== true) {
|
|
1373
|
+
st.hardAt = true
|
|
1374
|
+
waterState.set(agent, st)
|
|
1375
|
+
return {
|
|
1376
|
+
...decision,
|
|
1377
|
+
messages: [...decision.messages, notice(
|
|
1378
|
+
`【灵枢·水位 ${pct}%】已过硬线(${th.hard_at}%):立刻先跑 \`python scripts/brain.py dream --auto\``
|
|
1379
|
+
+ `(或 \`auto-archive\`),压缩完再继续。不做压缩就继续对话,后面的内容很可能被宿主截断。`,
|
|
1380
|
+
)],
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
const step = pct >= 90 ? 90 : pct >= 75 ? 75 : pct >= 60 ? 60 : 0
|
|
1385
|
+
if (step > (st.max || 0)) {
|
|
1386
|
+
st.max = step
|
|
1387
|
+
waterState.set(agent, st)
|
|
1388
|
+
const _cc = await runBrain(pythonExe, cfg.python, brainPy, ['check-context', '--used', String(pct)], 15000)
|
|
1389
|
+
const text = _cc.ok && _cc.out ? _cc.out.trim() : ''
|
|
1390
|
+
if (text) {
|
|
1391
|
+
return { ...decision, messages: [...decision.messages, notice(text)] }
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
// 软自检(v3.59 重写):原来"每 waterCheckTurns 轮无条件注入一条",实测
|
|
1395
|
+
// 水位才 14% 也照发,用户会看到"没压缩却还在注入上下文"。现在只在
|
|
1396
|
+
// **确有变化**时提醒,其余情况只记账不占上下文:
|
|
1397
|
+
// ① 从没测过水位(本会话首次拿到估算);
|
|
1398
|
+
// ② 估算比上次提醒时涨了 ≥10 个百分点(真的在变满);
|
|
1399
|
+
// ③ 距上次提醒已过 waterCheckTurns 轮,**且**确实在涨(≥2 个百分点)。
|
|
1400
|
+
// 另:文案里不再叫模型去跑 check-context——那会多一次工具往返,而这条
|
|
1401
|
+
// 提醒本身通常没到需要动作的程度。
|
|
1402
|
+
const every = Math.max(0, Number(cfg.waterCheckTurns) || 0)
|
|
1403
|
+
const lastPct = Number.isFinite(st.lastPct) ? st.lastPct : null
|
|
1404
|
+
const grew = lastPct === null ? Infinity : pct - lastPct
|
|
1405
|
+
const turnsSince = Number.isFinite(st.softAt) && st.softAt > 0 ? n - st.softAt : Infinity
|
|
1406
|
+
const worthNoticing = lastPct === null
|
|
1407
|
+
|| grew >= 10
|
|
1408
|
+
|| (every > 0 && turnsSince >= every && grew >= 2)
|
|
1409
|
+
if (worthNoticing && step === 0 && n > 0 && st.softAt !== n) {
|
|
1410
|
+
st.softAt = n
|
|
1411
|
+
st.lastPct = pct
|
|
1412
|
+
waterState.set(agent, st)
|
|
1413
|
+
return {
|
|
1414
|
+
...decision,
|
|
1415
|
+
messages: [...decision.messages, notice(
|
|
1416
|
+
`【灵枢·水位】上下文估算约 ${pct}%(来源:${est.source})。还没到清点线,正常继续即可。`
|
|
1417
|
+
)],
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
// 不提醒也要更新"上次见过的水位",下次才有得比
|
|
1421
|
+
if (lastPct !== pct) {
|
|
1422
|
+
st.lastPct = pct
|
|
1423
|
+
waterState.set(agent, st)
|
|
1424
|
+
}
|
|
1425
|
+
} else {
|
|
1426
|
+
waterState.set(agent, st)
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
return decision
|
|
1431
|
+
} catch {
|
|
1432
|
+
// next() 可能已跑过,异常只能吞掉,返回已得的 decision(可能为 undefined)
|
|
1433
|
+
return decision
|
|
1434
|
+
}
|
|
1435
|
+
})
|
|
1436
|
+
|
|
1437
|
+
// 插件卸载/进程退出前把脏状态刷盘,避免节流窗口内的轮数/任务标记丢失
|
|
1438
|
+
const flushOnExit = () => { try { stateSaver.flushNow() } catch {} }
|
|
1439
|
+
// ★ #25:agent 结束时除了刷盘,还要**清掉该 agent 的运行时表**。
|
|
1440
|
+
// 原来只 flushNow() 不清表 → 8 个以 agent 为键的 Map
|
|
1441
|
+
// (turns/convo/lastReply/lastUser/pendingNotice/waterState/
|
|
1442
|
+
// reviewNoticeAt/waterAutoState)只增不删,长驻进程里会话越开越多,
|
|
1443
|
+
// 内存只涨不落;其中 convo 单条最多留 200KB 文本(审计 plugin.js:511)。
|
|
1444
|
+
// 注意:清表不影响已落盘的 state,只丢弃"这个 agent 的进程内缓存"。
|
|
1445
|
+
ctx.on('agent/dispose', (payload) => {
|
|
1446
|
+
flushOnExit()
|
|
1447
|
+
const a = payload?.agent
|
|
1448
|
+
if (!a) return
|
|
1449
|
+
for (const m of [turns, convo, lastReply, lastUser, pendingNotice,
|
|
1450
|
+
waterState, reviewNoticeAt, waterAutoState]) {
|
|
1451
|
+
try { m.delete(a) } catch {}
|
|
1452
|
+
}
|
|
1453
|
+
})
|
|
1454
|
+
try { process.on('exit', flushOnExit) } catch {}
|
|
1455
|
+
}
|