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.
Files changed (266) hide show
  1. package/CHANGELOG.md +4281 -4227
  2. package/README.md +1584 -1577
  3. package/SKILL-lite.md +59 -59
  4. package/SKILL-tiny.md +38 -38
  5. package/SKILL.md +356 -331
  6. package/assets/panel.html +6753 -5698
  7. package/cordis-plugin/lingshu-cron/plugin.js +1455 -1417
  8. package/cordis-plugin/lingshu-startup/context-fold.js +170 -0
  9. package/cordis-plugin/lingshu-startup/context-pressure.js +16 -0
  10. package/cordis-plugin/lingshu-startup/context-snapshot.js +176 -0
  11. package/cordis-plugin/lingshu-startup/plugin.js +499 -467
  12. 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
  13. 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
  14. package/docs/audit_notes//345/276/205/345/212/236/346/250/241/346/235/277.md +140 -0
  15. package/docs/commands.md +278 -247
  16. package/docs/mechanics.md +610 -610
  17. 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
  18. 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
  19. package/package.json +52 -52
  20. package/scripts/_scratch/_tmp_backup_race.py +70 -0
  21. package/scripts/_scratch/_tmp_cleanup_move.py +34 -0
  22. package/scripts/_scratch/_tmp_count_kinds.py +25 -0
  23. package/scripts/_scratch/_tmp_diag_paths.py +48 -0
  24. package/scripts/_scratch/_tmp_facts.py +63 -0
  25. package/scripts/_scratch/_tmp_find_copies.py +31 -0
  26. package/scripts/_scratch/_tmp_find_pin.py +29 -0
  27. package/scripts/_scratch/_tmp_fix_pin.py +36 -0
  28. package/scripts/_scratch/_tmp_fold_fixture.py +55 -0
  29. package/scripts/_scratch/_tmp_fold_test.mjs +81 -0
  30. package/scripts/_scratch/_tmp_inject_secs.py +30 -0
  31. package/scripts/_scratch/_tmp_kb_balance.py +159 -0
  32. package/scripts/_scratch/_tmp_lines.py +15 -0
  33. package/scripts/_scratch/_tmp_market_probe.py +13 -0
  34. package/scripts/_scratch/_tmp_move_partial.py +16 -0
  35. package/scripts/_scratch/_tmp_patch_b3.py +41 -0
  36. package/scripts/_scratch/_tmp_patch_b5.py +62 -0
  37. package/scripts/_scratch/_tmp_patch_crash_excl.py +24 -0
  38. package/scripts/_scratch/_tmp_patch_handoff.py +21 -0
  39. package/scripts/_scratch/_tmp_patch_ps1.py +25 -0
  40. package/scripts/_scratch/_tmp_patch_stat.py +27 -0
  41. package/scripts/_scratch/_tmp_patch_todo.py +25 -0
  42. package/scripts/_scratch/_tmp_patch_todo2.py +64 -0
  43. package/scripts/_scratch/_tmp_probe_session.py +51 -0
  44. package/scripts/_scratch/_tmp_style_probe.py +40 -0
  45. package/scripts/_scratch/_tmp_write_note.py +139 -0
  46. package/scripts/_scratch/_/346/235/245/346/272/220/350/256/260/345/275/225.txt +1 -0
  47. package/scripts/_scratch/asar_compaction/dsh-compaction-basic__lib__index.js +1044 -0
  48. package/scripts/_scratch/asar_compaction/dsh-compaction-tool-result-pruner__lib__index.js +194 -0
  49. package/scripts/_scratch/asar_compaction/dsh-compaction__lib__index.js +175 -0
  50. package/scripts/_scratch/asar_compaction/dsh-compaction__lib__types__tool-pairing.js +97 -0
  51. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__image-offload.js +47 -0
  52. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__index.js +40 -0
  53. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__project-message.js +37 -0
  54. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__brand.js +9 -0
  55. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__checkpoint.js +36 -0
  56. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__types.js +10 -0
  57. package/scripts/_scratch/commit_msg_occ.txt +16 -0
  58. package/scripts/_scratch/commit_msg_struct.txt +16 -0
  59. package/scripts/_scratch/v5.34_changelog.txt +36 -0
  60. package/scripts/_sync_trae_cn.py +102 -34
  61. package/scripts/_tmp_add_s10.py +54 -0
  62. package/scripts/_tmp_add_s11.py +61 -0
  63. package/scripts/_tmp_add_s12.py +66 -0
  64. package/scripts/_tmp_add_s13.py +69 -0
  65. package/scripts/_tmp_add_s14.py +80 -0
  66. package/scripts/_tmp_add_s9.py +68 -0
  67. package/scripts/_tmp_cache_load.py +82 -0
  68. package/scripts/_tmp_clean_market.py +40 -0
  69. package/scripts/_tmp_clean_pruned.py +81 -0
  70. package/scripts/_tmp_cleanup_docs.py +39 -0
  71. package/scripts/_tmp_cmp_ranker.py +17 -0
  72. package/scripts/_tmp_dolater_note.py +35 -0
  73. package/scripts/_tmp_dust_why.py +27 -0
  74. package/scripts/_tmp_explicit_import.py +40 -0
  75. package/scripts/_tmp_extract_compaction.py +35 -0
  76. package/scripts/_tmp_extract_compaction2.py +63 -0
  77. package/scripts/_tmp_extract_compaction3.py +51 -0
  78. package/scripts/_tmp_extract_compaction4.py +54 -0
  79. package/scripts/_tmp_finalize_s14.py +39 -0
  80. package/scripts/_tmp_find_compaction.py +43 -0
  81. package/scripts/_tmp_fix_b4.py +22 -0
  82. package/scripts/_tmp_fix_cli76.py +26 -0
  83. package/scripts/_tmp_fix_docs.py +38 -0
  84. package/scripts/_tmp_fix_docs_b.py +46 -0
  85. package/scripts/_tmp_fix_docs_b2.py +22 -0
  86. package/scripts/_tmp_fix_i3.py +23 -0
  87. package/scripts/_tmp_fix_s10.py +83 -0
  88. package/scripts/_tmp_fix_s11.py +14 -0
  89. package/scripts/_tmp_fix_s9_status.py +19 -0
  90. package/scripts/_tmp_fix_shadow_sim.py +37 -0
  91. package/scripts/_tmp_fix_traits_value.py +41 -0
  92. package/scripts/_tmp_import_idem.py +106 -0
  93. package/scripts/_tmp_log_ack.py +45 -0
  94. package/scripts/_tmp_mark_batch.py +28 -0
  95. package/scripts/_tmp_mark_batch2.py +32 -0
  96. package/scripts/_tmp_mark_dolater.py +26 -0
  97. package/scripts/_tmp_mark_dolater2.py +31 -0
  98. package/scripts/_tmp_move_self.py +16 -0
  99. package/scripts/_tmp_occ_cli.py +22 -0
  100. package/scripts/_tmp_occ_link.py +108 -0
  101. package/scripts/_tmp_optimize_recall.py +54 -0
  102. package/scripts/_tmp_panel_audit.py +26 -0
  103. package/scripts/_tmp_patch_batch3.py +65 -0
  104. package/scripts/_tmp_patch_rrf.py +46 -0
  105. package/scripts/_tmp_patch_s2s3.py +80 -0
  106. package/scripts/_tmp_patch_s4.py +39 -0
  107. package/scripts/_tmp_patch_s7.py +43 -0
  108. package/scripts/_tmp_patch_s8.py +91 -0
  109. package/scripts/_tmp_patch_skill.py +17 -0
  110. package/scripts/_tmp_release_guard.py +57 -0
  111. package/scripts/_tmp_rerank_breaker.py +62 -0
  112. package/scripts/_tmp_s16.py +41 -0
  113. package/scripts/_tmp_scan_asar.py +41 -0
  114. package/scripts/_tmp_scan_asar2.py +37 -0
  115. package/scripts/_tmp_struct_docs.py +49 -0
  116. package/scripts/_tmp_sum_fallback.py +42 -0
  117. package/scripts/_tmp_sweep.py +81 -0
  118. package/scripts/_tmp_sync_check.py +69 -0
  119. package/scripts/_tmp_sync_tail.py +39 -0
  120. package/scripts/_tmp_todo_clean.py +67 -0
  121. package/scripts/_tmp_verify_copy.py +17 -0
  122. package/scripts/_tmp_wire_extras.py +93 -0
  123. package/scripts/_tmp_wire_hsum.py +34 -0
  124. package/scripts/_tmp_wire_occ_b5.py +40 -0
  125. package/scripts/_tmp_wire_ranker.py +13 -0
  126. package/scripts/_tmp_wire_shadow_timeline.py +45 -0
  127. package/scripts/anchor_retention.py +68 -0
  128. package/scripts/app_context.py +1160 -0
  129. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +38 -22
  130. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +4281 -4227
  131. package/scripts/astrbot_plugin_lingshu/engine/README.md +1584 -1577
  132. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +59 -59
  133. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +38 -38
  134. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +356 -331
  135. package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +6753 -5698
  136. package/scripts/astrbot_plugin_lingshu/engine/docs/commands.md +278 -247
  137. package/scripts/astrbot_plugin_lingshu/engine/docs/mechanics.md +610 -610
  138. package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +102 -34
  139. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s10.py +54 -0
  140. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s11.py +61 -0
  141. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s12.py +66 -0
  142. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s13.py +69 -0
  143. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s14.py +80 -0
  144. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s9.py +68 -0
  145. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cache_load.py +82 -0
  146. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_clean_market.py +40 -0
  147. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_clean_pruned.py +81 -0
  148. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cleanup_docs.py +39 -0
  149. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cmp_ranker.py +17 -0
  150. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_dolater_note.py +35 -0
  151. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_dust_why.py +27 -0
  152. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_explicit_import.py +40 -0
  153. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction.py +35 -0
  154. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction2.py +63 -0
  155. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction3.py +51 -0
  156. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction4.py +54 -0
  157. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_finalize_s14.py +39 -0
  158. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_find_compaction.py +43 -0
  159. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_b4.py +22 -0
  160. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_cli76.py +26 -0
  161. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs.py +38 -0
  162. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs_b.py +46 -0
  163. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs_b2.py +22 -0
  164. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_i3.py +23 -0
  165. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s10.py +83 -0
  166. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s11.py +14 -0
  167. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s9_status.py +19 -0
  168. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_shadow_sim.py +37 -0
  169. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_traits_value.py +41 -0
  170. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_import_idem.py +106 -0
  171. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_log_ack.py +45 -0
  172. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_batch.py +28 -0
  173. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_batch2.py +32 -0
  174. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_dolater.py +26 -0
  175. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_dolater2.py +31 -0
  176. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_move_self.py +16 -0
  177. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_occ_cli.py +22 -0
  178. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_occ_link.py +108 -0
  179. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_optimize_recall.py +54 -0
  180. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_panel_audit.py +26 -0
  181. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_batch3.py +65 -0
  182. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_rrf.py +46 -0
  183. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s2s3.py +80 -0
  184. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s4.py +39 -0
  185. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s7.py +43 -0
  186. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s8.py +91 -0
  187. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_skill.py +17 -0
  188. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_release_guard.py +57 -0
  189. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_rerank_breaker.py +62 -0
  190. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_s16.py +41 -0
  191. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_scan_asar.py +41 -0
  192. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_scan_asar2.py +37 -0
  193. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_struct_docs.py +49 -0
  194. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sum_fallback.py +42 -0
  195. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sweep.py +81 -0
  196. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sync_check.py +69 -0
  197. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sync_tail.py +39 -0
  198. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_todo_clean.py +67 -0
  199. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_verify_copy.py +17 -0
  200. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_extras.py +93 -0
  201. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_hsum.py +34 -0
  202. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_occ_b5.py +40 -0
  203. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_ranker.py +13 -0
  204. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_shadow_timeline.py +45 -0
  205. package/scripts/astrbot_plugin_lingshu/engine/scripts/anchor_retention.py +68 -0
  206. package/scripts/astrbot_plugin_lingshu/engine/scripts/app_context.py +1160 -0
  207. package/scripts/astrbot_plugin_lingshu/engine/scripts/bigfive.py +90 -0
  208. package/scripts/astrbot_plugin_lingshu/engine/scripts/brain.py +1 -1
  209. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_docs.py +191 -0
  210. package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +921 -86
  211. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2468 -2406
  212. package/scripts/astrbot_plugin_lingshu/engine/scripts/coverage_report.py +5 -0
  213. package/scripts/astrbot_plugin_lingshu/engine/scripts/delivery.py +112 -0
  214. package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +41 -3
  215. package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +202 -23
  216. package/scripts/astrbot_plugin_lingshu/engine/scripts/gap_memory.py +186 -0
  217. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +72 -8
  218. package/scripts/astrbot_plugin_lingshu/engine/scripts/hsum.py +206 -0
  219. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_score.py +92 -7
  220. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +530 -60
  221. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory_extras.py +200 -0
  222. package/scripts/astrbot_plugin_lingshu/engine/scripts/occ.py +190 -0
  223. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +232 -142
  224. package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +2498 -2349
  225. package/scripts/astrbot_plugin_lingshu/engine/scripts/prepublish_tests.py +90 -0
  226. package/scripts/astrbot_plugin_lingshu/engine/scripts/release.py +326 -287
  227. package/scripts/astrbot_plugin_lingshu/engine/scripts/rss_ingest.py +181 -0
  228. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +832 -764
  229. package/scripts/astrbot_plugin_lingshu/engine/scripts/shadow_memory.py +173 -0
  230. package/scripts/astrbot_plugin_lingshu/engine/scripts/style_check.py +220 -0
  231. package/scripts/astrbot_plugin_lingshu/engine/scripts/summarizer.py +343 -252
  232. package/scripts/astrbot_plugin_lingshu/engine/scripts/timeline.py +118 -0
  233. package/scripts/astrbot_plugin_lingshu/engine/scripts/watchdog.py +110 -0
  234. package/scripts/astrbot_plugin_lingshu/engine/scripts/web_research.py +125 -0
  235. package/scripts/bigfive.py +90 -0
  236. package/scripts/brain.py +1 -1
  237. package/scripts/check_docs.py +191 -0
  238. package/scripts/cli.py +921 -86
  239. package/scripts/core.py +2468 -2406
  240. package/scripts/coverage_report.py +5 -0
  241. package/scripts/delivery.py +112 -0
  242. package/scripts/dream.py +41 -3
  243. package/scripts/emotion.py +202 -23
  244. package/scripts/gap_memory.py +186 -0
  245. package/scripts/growth.py +72 -8
  246. package/scripts/hsum.py +206 -0
  247. package/scripts/mem_score.py +92 -7
  248. package/scripts/memory.py +530 -60
  249. package/scripts/memory_extras.py +200 -0
  250. package/scripts/occ.py +190 -0
  251. package/scripts/panel_server.py +232 -142
  252. package/scripts/persona.py +2498 -2349
  253. package/scripts/prepublish_tests.py +90 -0
  254. package/scripts/release.py +326 -287
  255. package/scripts/rss_ingest.py +181 -0
  256. package/scripts/run_tests.py +13 -0
  257. package/scripts/session_import.py +832 -764
  258. package/scripts/shadow_memory.py +173 -0
  259. package/scripts/style_check.py +220 -0
  260. package/scripts/summarizer.py +343 -252
  261. package/scripts/timeline.py +118 -0
  262. package/scripts/update_dsh_copy.ps1 +110 -107
  263. package/scripts/watchdog.py +110 -0
  264. package/scripts/web_research.py +125 -0
  265. package/docs//344/272/244/346/216/245/347/254/224/350/256/260-20261128.md +0 -128
  266. package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +0 -408
@@ -1,467 +1,499 @@
1
- // 灵枢 · DSH/Cordis 启动注入插件
2
- //
3
- // 为什么需要它:DSH 的技能 catalog 只把 name+description 给模型,正文要不要读
4
- // 全凭模型自觉。本插件把"自觉"变成"机制"——每个新会话(agent/created,
5
- // source ∈ startup/resume)时自动跑灵枢的 `brain.py startup`,把人格、记忆、
6
- // 待办、行为指引注入会话上下文,模型想忘都忘不掉。
7
- //
8
- // 事件与注入(对齐 DSH 真实 API):
9
- // - 监听 `agent/created`(serial 事件,监听器会被 await,失败会回滚会话创建——
10
- // 所以本插件任何路径都不允许抛异常),payload 为
11
- // { agent, source: 'startup'|'resume'|'clear'|'compact', signal? }。
12
- // 只对 startup/resume 注入;clear/compact 是同会话重建上下文,不重复注入。
13
- // - 投递用 agent/pre-step 钩子:agent/created 里只跑 startup 并把文本存进
14
- // pending Map;pre-step(构建 messages 之后、请求之前)await next() 后把文本
15
- // 追加进 enter 分支的 messages——不排队、不经过 inbox 消费逻辑,必然进模型
16
- // 上下文。此前试过 inject(写 next-step,turn/start 清空丢注入)与
17
- // send('next-turn')(进待发送队列,模型看不到),都实测失败。
18
- //
19
- // 数据安全:本插件只读记忆库(startup 内部只读+写 last_startup),不碰
20
- // 技能目录;brain.py 自身保证只读降级(HOME 不可写时照样注入)。
21
-
22
- import { spawn } from 'node:child_process'
23
- import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
24
- import { homedir, tmpdir } from 'node:os'
25
- import { delimiter, dirname, join } from 'node:path'
26
- import { createHash, randomUUID } from 'node:crypto'
27
- import { fileURLToPath } from 'node:url'
28
- import { clearContextPressure, sampleContextPressure } from './context-pressure.js'
29
-
30
- // 刻意零外部依赖:不 import @deepseek-ai/schemastery。原因——link: 安装时模块
31
- // 真实路径留在技能目录,Node 从那里向上找 node_modules 一路到盘符根都找不到
32
- // DSH 内置包,import 失败 → cordis 静默跳过整个插件(UI 里装了却不动)。
33
- // 去掉依赖后 link 安装也能工作,改 plugin.js 即时生效,不必每次重打包。
34
-
35
- export const name = 'dsh-lingshu-startup'
36
-
37
- /** 注入消息的 source.name:与 cron 的 'lingshu-cron'、im 的 'lingshu-im' 区分开。 */
38
- const INJECT_SOURCE = 'lingshu-startup'
39
-
40
- // 本插件文件在 <包根>/cordis-plugin/lingshu-startup/plugin.js,
41
- // 往上一级是 cordis-plugin/,再上一级就是包根(含 scripts/brain.py 与 SKILL.md)。
42
- const PLUGIN_DIR = dirname(fileURLToPath(import.meta.url))
43
- const PACKAGE_ROOT = join(PLUGIN_DIR, '..', '..')
44
-
45
- /**
46
- * 把"找不到 brain.py / python"这类静默失败写进 ~/.dsh/lingshu-diag.json。
47
- * 为什么需要:插件里所有失败都必须吞掉(事件串行、抛异常会回滚会话),
48
- * 结果就是"记忆不录入了"却没有任何痕迹可查——2026-11-20 那次排障就卡在这。
49
- */
50
- export function writeDiag(kind, detail) {
51
- try {
52
- const base = process.env.APP_DSH || join(homedir(), '.dsh')
53
- const payload = {
54
- ts: new Date().toISOString(),
55
- plugin: 'lingshu-startup',
56
- kind,
57
- detail: detail && typeof detail === 'object' ? detail : { message: String(detail ?? '') },
58
- }
59
- writeFileSync(join(base, 'lingshu-diag.json'), JSON.stringify(payload, null, 2), 'utf8')
60
- } catch {}
61
- }
62
-
63
- // 默认配置(纯普通对象,零依赖)。DSH 对导出 Config 的插件会喂用户配置,
64
- // 不导出 Config 时喂默认空对象——两种情况本插件都能工作。
65
- const DEFAULTS = {
66
- brainPy: '', // brain.py 绝对路径;留空自动探测 ~/.dsh/skills/lingshu、~/.trae-cn/skills/lingshu
67
- python: '', // python.exe 绝对路径;留空自动探测 DSH 自带运行时等位置(spawn 不解析 PATHEXT)
68
- budget: 1400, // startup 注入 token 预算
69
- timeoutMs: 3000, // startup 子进程超时;agent/created 是串行事件,超时太久拖慢新会话
70
- resumeBudget: 400, // v3.59:resume 用极简版预算(人格+待办+水位,约 640 字符)。
71
- // 为什么:会话历史里已有一份完整记忆块,resume 再注入一整份
72
- // 就是同一段上下文出现两遍(实测 1214 tokens x 2)。
73
- injectResume: true, // resume 来源(续聊)是否也注入
74
- // —— P9 #61 开工前查(借鉴 ShellBrain CBR / mem0 proactive memory)——
75
- // 每轮首个 pre-step 抽取用户消息,自动跑 `brain.py prior`,命中就注入
76
- // "这件事以前做过吗"块,避免模型把已经做过/调研过的事重新来一遍。
77
- priorAuto: true, // 关掉则只在模型主动调 `prior` 时生效
78
- priorBudget: 1200, // prior 注入块字符上限(比 startup 小,它是每轮附加)
79
- priorTimeoutMs: 6000, // prior 子进程超时(在请求关键路径上,宁可放弃也不拖住)
80
- priorMinChars: 12, // 用户消息少于这个长度不查("继续""好"之类没有检索价值)
81
- }
82
-
83
- /** 合并用户配置与默认值(用户值非空/存在才覆盖) */
84
- function mergeConfig(user) {
85
- const merged = { ...DEFAULTS }
86
- if (user && typeof user === 'object') {
87
- for (const k of Object.keys(DEFAULTS)) {
88
- const v = user[k]
89
- if (v !== undefined && v !== null && v !== '') merged[k] = v
90
- }
91
- }
92
- return merged
93
- }
94
-
95
- /** 依次探测常见安装位置的 brain.py */
96
- async function findBrainPy(configured, ctx) {
97
- if (configured) return existsSync(configured) ? configured : null
98
- // ① 先看本包自带:插件就在 <包根>/cordis-plugin/lingshu-startup/ 里,
99
- // ../../scripts/brain.py 一定和它同包发布。这一条不依赖任何宿主状态,
100
- // 也不依赖"技能注册表带路径"(v3.53 之前正是缺了这一条:注册 runtime 技能
101
- // 时没给 resourceBase/path,子插件就永远找不到 brain.py,整条自动注入/
102
- // 即记即存/天级任务全部静默停摆)。
103
- for (const p of brainPyCandidates()) {
104
- if (existsSync(p)) return p
105
- }
106
- // ② 再问技能注册表(装了全局技能副本时更准;字段名跨版本不同,逐个试)
107
- try {
108
- const registry = ctx?.get?.('skills') ?? ctx?.skills
109
- let items = registry?.list?.()
110
- if (items?.then) items = await items
111
- const hit = Array.isArray(items) ? items.find((s) => s?.name === 'lingshu') : null
112
- if (hit) {
113
- const bases = [
114
- [hit.path, true], [hit.location, true],
115
- [hit?.resourceBase?.path, false], // DSH 的 runtime 技能可带资源根目录
116
- [hit.dir, false], [hit.baseDir, false], [hit.directory, false],
117
- ]
118
- for (const [raw, isFile] of bases) {
119
- if (typeof raw !== 'string' || !raw) continue
120
- const root = isFile ? dirname(raw) : raw
121
- const p = join(root, 'scripts', 'brain.py')
122
- if (existsSync(p)) return p
123
- }
124
- }
125
- } catch (e) {
126
- // 技能注册表探测失败不该静默——留一条日志方便排障(但不在群/会话里打扰)
127
- try { ctx?.logger?.warn?.('lingshu-startup: 技能注册表探测异常,走环境变量/默认路径兜底', e) } catch {}
128
- }
129
- return null
130
- }
131
-
132
- /** 有可能藏着 brain.py 的绝对路径清单(纯函数,便于测试与排障打印) */
133
- export function brainPyCandidates() {
134
- const out = [join(PACKAGE_ROOT, 'scripts', 'brain.py')]
135
- const envDir = (process.env.LINGSHU_SKILL_DIR || '').trim()
136
- if (envDir) out.push(join(envDir, 'scripts', 'brain.py'))
137
- const home = homedir()
138
- out.push(
139
- join(home, '.dsh', 'skills', 'lingshu', 'scripts', 'brain.py'),
140
- join(home, '.trae-cn', 'skills', 'lingshu', 'scripts', 'brain.py'),
141
- )
142
- return out
143
- }
144
-
145
- /** 有可能可用的 python 可执行文件清单(纯函数,便于测试与排障打印) */
146
- export function pythonCandidates() {
147
- const home = homedir()
148
- const out = []
149
- for (const app of [process.env.APP_DSH, join(home, '.dsh')].filter(Boolean)) {
150
- out.push(join(app, 'app-runtimes', 'app-primary-runtime', 'dependencies', 'python', 'python.exe'))
151
- out.push(join(app, 'runtimes', 'app-primary-runtime', 'dependencies', 'python', 'python.exe'))
152
- }
153
- // PATH 里的 python.exe / python3.exe(ServBay、Store、conda 等布局都能命中)。
154
- // 刻意不选 .cmd shim:spawn 走 CreateProcess 不解析 PATHEXT。
155
- for (const dir of (process.env.PATH || '').split(delimiter)) {
156
- if (!dir) continue
157
- out.push(join(dir, 'python.exe'), join(dir, 'python3.exe'))
158
- }
159
- out.push(
160
- join(home, 'AppData', 'Local', 'Programs', 'Python', 'python.exe'),
161
- 'C:\\Python313\\python.exe',
162
- 'C:\\Python312\\python.exe',
163
- 'C:\\Program Files\\Python313\\python.exe',
164
- )
165
- return out
166
- }
167
-
168
- /**
169
- * 探测可用的 python.exe。spawn 走 CreateProcess,不解析 PATHEXT——
170
- * PATH 里只有 python.cmd 的机器上 spawn('python') 直接 ENOENT。
171
- * 优先级:用户配置 > DSH 自带运行时(确定的 exe)> 常见安装位置 > 系统常见位置。
172
- * 都没命中返回 null(由调用方走 cmd 兜底)。
173
- */
174
- function findPythonExe(configured) {
175
- if (configured) return existsSync(configured) ? configured : null
176
- for (const p of pythonCandidates()) {
177
- if (existsSync(p)) return p
178
- }
179
- return null
180
- }
181
-
182
- /**
183
- * 跑 brain.py startup,返回注入文本;失败返回 null(绝不抛异常、绝不阻塞会话)。
184
- * 找不到 python.exe 时退回 ComSpec 让 cmd 解析 PATHEXT(python.cmd 也能跑)。
185
- */
186
- function runBrainText(pythonExe, pythonCmdFallback, brainPy, extraArgs, timeoutMs) {
187
- return new Promise((resolve) => {
188
- let settled = false
189
- const done = (v) => { if (!settled) { settled = true; resolve(v) } }
190
- const args = [brainPy, ...(extraArgs || [])]
191
- let child
192
- try {
193
- if (pythonExe) {
194
- child = spawn(pythonExe, args, {
195
- windowsHide: true,
196
- env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
197
- // 显式把工作目录挪到用户主目录:绝不继承宿主 cwd。宿主 cwd 若在插件
198
- // 目录内,Windows 会因"目录被进程占用"拒绝 pnpm 的目录 rename,
199
- // 导致市场更新(remove+add)报"文件被占用、请退出 DSH"。
200
- cwd: homedir(),
201
- // 不用 spawn 的 timeout 选项:它只杀直接子进程,见下方手动兜底说明
202
- })
203
- } else {
204
- // 兜底:让 cmd 去解析 .cmd(/d 关 autorun,/s 规范引号解析,/c 执行后退出)。
205
- // 注意命令行必须带上 python 命令本身(pythonExe 没找到时用裸 'python',
206
- // 由 cmd 按 PATHEXT 解析成 python.cmd)——只拼 brain.py 会依赖 .py 文件关联。
207
- const comspec = process.env.ComSpec ?? 'cmd.exe'
208
- const pythonCmd = pythonCmdFallback || 'python'
209
- const cmdline = [`"${pythonCmd}"`, ...args.map((a) => `"${a}"`)].join(' ')
210
- child = spawn(comspec, ['/d', '/s', '/c', cmdline], {
211
- windowsHide: true,
212
- windowsVerbatimArguments: true, // 命令行已手工加引号,阻止 Node 再转义一层
213
- env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
214
- cwd: homedir(), // 同上:不把宿主 cwd(可能在插件目录内)占给子进程
215
- })
216
- }
217
- } catch {
218
- return done(null)
219
- }
220
- let out = ''
221
- child.stdout?.on('data', (d) => { out += d.toString('utf8') })
222
- child.stderr?.resume() // 必须 drain:traceback 超 64KB 会塞满管道缓冲,子进程写阻塞永不退出
223
- child.on('error', () => done(null))
224
- // 手动超时兜底(不靠 spawn 的 timeout 选项,它只杀直接子进程):
225
- // taskkill /T /F 杀整棵进程树——cmd 兜底分支里直接子进程是 cmd.exe,
226
- // 只杀它会留下 python.exe 孙进程残留。
227
- const killer = setTimeout(() => {
228
- try {
229
- if (child.pid) {
230
- const tk = spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
231
- tk.on('error', () => {}) // 无 taskkill(非 Windows)时静默,下面还有 child.kill() 托底
232
- }
233
- } catch {}
234
- try { child.kill() } catch {}
235
- done(null)
236
- }, timeoutMs + 500)
237
- killer.unref?.()
238
- child.on('close', (code) => {
239
- clearTimeout(killer) // 正常退出清掉兜底定时器,别留着空转
240
- // 返回码 0=正常注入;10=只读降级注入(照样有效);2=未初始化(跳过)
241
- done(code === 0 || code === 10 ? out.trim() : null)
242
- })
243
- })
244
- }
245
-
246
- /** 启动注入:brain.py startup --budget N */
247
- function runStartup(pythonExe, pythonCmdFallback, brainPy, budget, timeoutMs) {
248
- return runBrainText(pythonExe, pythonCmdFallback, brainPy,
249
- ['startup', '--budget', String(budget)], timeoutMs)
250
- }
251
-
252
- /**
253
- * 开工前查:brain.py prior --task-file <tmp> --render --budget N
254
- *
255
- * 任务文本来自**用户消息**,绝不拼进命令行——用户一句话里带引号/`&`/`|`
256
- * 在 cmd 兜底分支就是命令注入(lingshu-im 那边踩过同款坑)。这里写临时文件、
257
- * 只传路径,python 侧读完即删。
258
- */
259
- function runPrior(pythonExe, pythonCmdFallback, brainPy, taskText, budget, timeoutMs) {
260
- let taskFile = ''
261
- try {
262
- const dir = join(tmpdir(), 'lingshu-prior')
263
- mkdirSync(dir, { recursive: true })
264
- taskFile = join(dir, `t-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.txt`)
265
- writeFileSync(taskFile, String(taskText || '').slice(0, 2000), 'utf8')
266
- } catch {
267
- return Promise.resolve(null)
268
- }
269
- return runBrainText(pythonExe, pythonCmdFallback, brainPy,
270
- ['prior', '--task-file', taskFile, '--render', '--budget', String(budget)],
271
- timeoutMs).finally(() => {
272
- // python 侧正常会删;异常/超时时这里兜底清理,避免临时文件堆积
273
- try { rmSync(taskFile, { force: true }) } catch {}
274
- })
275
- }
276
-
277
- /** 从 pre-step 决策的 messages 里抽出最后一条用户文本(含多模态里的 text 段) */
278
- export function lastUserText(messages) {
279
- if (!Array.isArray(messages)) return ''
280
- for (let i = messages.length - 1; i >= 0; i--) {
281
- const m = messages[i]
282
- if (!m || m.role !== 'user') continue
283
- const c = m.content
284
- if (typeof c === 'string') return c.trim()
285
- if (Array.isArray(c)) {
286
- const t = c.filter((x) => x && x.type === 'text' && x.text).map((x) => x.text).join('\n')
287
- if (t.trim()) return t.trim()
288
- }
289
- }
290
- return ''
291
- }
292
-
293
- /** 像"要做的事"吗:够长、不是纯问候/确认。避免每轮都白跑一次 python。 */
294
- export function looksLikeTask(text, minChars) {
295
- const t = String(text || '').trim()
296
- if (t.length < Math.max(4, Number(minChars) || 12)) return false
297
- // 纯确认/寒暄短句("继续""好的""嗯"…)没有检索价值
298
- if (/^(继续|好的?|嗯+|行|可以|收到|谢谢|ok|okay|yes|no|继续吧|接着来)[。!!.\s]*$/i.test(t)) return false
299
- return true
300
- }
301
-
302
- export function apply(ctx, config) {
303
- // v3.23:重复挂载守卫。profile 同时启用独立包与根包时,同一进程会出现两份 startup,
304
- // 每会话注入两遍人格/记忆(白烧 ~3k token,且两份可能来自不同版本引擎)。
305
- if (globalThis.__lingshuStartupApplied) {
306
- try { ctx.logger?.warn?.('lingshu-startup: 已有一份灵枢 startup 在运行,跳过重复挂载') } catch {}
307
- return
308
- }
309
- globalThis.__lingshuStartupApplied = true
310
- const cfg = mergeConfig(config)
311
- // pending:agent -> 注入文本。agent/created 只负责把文本存进来,
312
- // 真正投递在 agent/pre-step 里做(见下)。
313
- const pending = new Map()
314
- // v3.59:每个 agent 已注入过的内容指纹(sha256 前 16 位)。
315
- // 解决同一对话里注入第二份一模一样内容——resume、agent 重建、
316
- // 宿主重复派发 agent/created 都可能触发重注入。同一份内容只进一次上下文,
317
- // 这也正是提示词缓存友好的做法(只在末尾追加、不重复历史)。
318
- const injectedDigests = new Map()
319
- // P9 #61:每个 agent 已查过「开工前」的用户消息指纹(sha256 前 16 位)。
320
- // 同一条消息只查一次,避免模型多步工具调用时反复触发 python 子进程。
321
- const priorDigests = new Map()
322
- // 配置类失败只告警一次:静默吞掉配置错误会让插件"看似在工作、实际没注入"
323
- let warnedOnce = false
324
-
325
- ctx.on('agent/created', async (payload) => {
326
- try { // 顶层兜底:serial 监听器 reject 会回滚会话创建,这里绝不允许冒泡
327
- const { agent, source } = payload || {}
328
- if (!agent) return
329
- // 白名单:只有新开会话(startup)与续聊(resume)注入;
330
- // clear / compact 是同会话上下文重建,重复注入只会浪费 token。
331
- if (source !== 'startup' && source !== 'resume') return
332
- if (source === 'resume' && !cfg.injectResume) return
333
- if (pending.has(agent)) return
334
- // P9 #57:全新会话先清掉上个会话留下的水位样本——否则首轮注入会把
335
- // 上个会话的"水位 90%"标成"本会话实测",误导 AI 在空会话里做梦/封存。
336
- // resume 不清:同一会话续聊,样本仍属本会话,清掉反而丢有效值。
337
- if (source === 'startup') clearContextPressure()
338
-
339
- const brainPy = await findBrainPy(cfg.brainPy, ctx)
340
- if (!brainPy) {
341
- // 静默失败必须有痕迹:doctor / 面板 / 手工排障都读这个文件
342
- writeDiag('brainPy-not-found', {
343
- tried: brainPyCandidates(),
344
- packageRoot: PACKAGE_ROOT,
345
- configured: cfg.brainPy || null,
346
- })
347
- if (!warnedOnce) { warnedOnce = true; try { ctx.logger?.warn?.('lingshu-startup: 未找到 brain.py(未安装灵枢?),跳过注入') } catch {} }
348
- return
349
- }
350
- const pythonExe = findPythonExe(cfg.python)
351
- // v3.59:resume 走极简版预算——历史里已有完整记忆块,不必再来一份
352
- const budget = source === 'resume'
353
- ? (Number(cfg.resumeBudget) > 0 ? Number(cfg.resumeBudget) : cfg.budget)
354
- : cfg.budget
355
- const text = await runStartup(pythonExe, cfg.python, brainPy, budget, cfg.timeoutMs)
356
- if (!text) {
357
- writeDiag('startup-no-output', {
358
- brainPy,
359
- pythonExe: pythonExe || null,
360
- pythonConfigured: cfg.python || null,
361
- pythonTried: pythonCandidates().slice(0, 12),
362
- })
363
- if (!warnedOnce) { warnedOnce = true; try { ctx.logger?.warn?.('lingshu-startup: brain.py startup 未产出注入文本(python 不在/超时/未初始化),跳过注入') } catch {} }
364
- return
365
- }
366
- // 成功时清掉上一次的失败痕迹,避免旧 diag 一直误导排障
367
- try {
368
- const base = process.env.APP_DSH || join(homedir(), '.dsh')
369
- rmSync(join(base, 'lingshu-diag.json'), { force: true })
370
- } catch {}
371
- // v3.59:内容指纹去重——同一份文本在同一 agent 只注入一次。
372
- // 场景:resume、agent 重建、宿主重复派发 agent/created。不加这道闸,
373
- // 同一个对话里会出现两份一样的记忆块(实测 1214 tokens x 2),
374
- // 既费 token 又让提示词缓存从重复处开始失效。
375
- const digest = createHash('sha256').update(text).digest('hex').slice(0, 16)
376
- let seen = injectedDigests.get(agent)
377
- if (seen === undefined) {
378
- seen = new Set()
379
- injectedDigests.set(agent, seen)
380
- }
381
- if (seen.has(digest)) {
382
- // 已经注入过一模一样的内容:直接跳过,不占上下文(也算成功,清掉旧 diag)
383
- return
384
- }
385
- seen.add(digest)
386
- // 只存不投递:send/inject 走 inbox 都有生命周期坑(实测坐实),真正进模型
387
- // 上下文要在 agent/pre-step 里追加 messages(见下)。
388
- pending.set(agent, text)
389
- } catch (e) {
390
- // 任何意外都不能让监听器 reject(agent/created 失败会回滚会话创建)
391
- try { ctx.logger?.warn?.('lingshu-startup: 未捕获异常', e) } catch {}
392
- }
393
- })
394
-
395
- // 每步构建 messages 之后、发起请求之前:把注入文本追加进这批 messages。
396
- // 这条通道不排队、不经过 inbox 消费逻辑——enter 分支的 messages 就是模型看到的。
397
- ctx.on('agent/pre-step', async (payload, next) => {
398
- try {
399
- // 先 await next():让其他(wrapping)监听器先改完,保住它们的
400
- // startsRequestSeries / batch 语义,再在结果上追加。
401
- const decision = await next()
402
- // v3.86:每轮请求前采一次 DSH 的准确 token 压力(ctx.tokenMeter),
403
- // 写 HOME/.context-pressure.json 给 brain.py 读。必须在决策之后也不影响
404
- // 注入语义;采集器自身吞掉所有异常,绝不让 pre-step 冒泡。
405
- try {
406
- const { agent: pa } = payload || {}
407
- if (pa) sampleContextPressure(ctx, pa)
408
- } catch { /* 采集失败不影响请求/注入 */ }
409
- if (!decision || decision.kind !== 'enter') return decision
410
- const { agent } = payload || {}
411
- const extra = []
412
- // ① 启动注入(每次会话一次)
413
- const text = agent && pending.get(agent)
414
- if (text) {
415
- pending.delete(agent) // 只注入一次:不删的话每条 pre-step 都会重复塞
416
- extra.push(text)
417
- }
418
- // ② 开工前查(P9 #61):每轮首个 pre-step 抽用户消息 → prior → 命中才注入。
419
- // 同一条消息只查一次(digest 去重);查不到就不注入,避免白占上下文。
420
- if (cfg.priorAuto && agent) {
421
- try {
422
- const userText = lastUserText(decision.messages)
423
- if (looksLikeTask(userText, cfg.priorMinChars)) {
424
- const dig = createHash('sha256').update(userText).digest('hex').slice(0, 16)
425
- let seen = priorDigests.get(agent)
426
- if (seen === undefined) {
427
- seen = new Set()
428
- priorDigests.set(agent, seen)
429
- }
430
- if (!seen.has(dig)) {
431
- seen.add(dig)
432
- if (seen.size > 200) { // 防长会话无限增长
433
- const keep = [...seen].slice(-100)
434
- priorDigests.set(agent, new Set(keep))
435
- }
436
- const brainPy = await findBrainPy(cfg.brainPy, ctx)
437
- const pythonExe = findPythonExe(cfg.python)
438
- const block = brainPy
439
- ? await runPrior(pythonExe, cfg.python, brainPy, userText,
440
- cfg.priorBudget, cfg.priorTimeoutMs)
441
- : null
442
- if (block) extra.push(block)
443
- }
444
- }
445
- } catch { /* 查不到/失败都不影响本轮请求 */ }
446
- }
447
- if (!extra.length) return decision
448
- return {
449
- ...decision,
450
- messages: [
451
- ...decision.messages,
452
- ...extra.map((t) => ({
453
- id: randomUUID(),
454
- role: 'user',
455
- content: [{ type: 'text', text: t }],
456
- // v3.59:用自己的 source.name,别和 cron 的 'lingshu-cron' 撞。
457
- // 撞了会被 cron 的 pruneInjected 当成本插件自己的旧提醒删掉。
458
- source: { kind: 'skill-invocation', name: INJECT_SOURCE, form: 'instructions' },
459
- })),
460
- ],
461
- }
462
- } catch (e) {
463
- try { ctx.logger?.warn?.('lingshu-startup: pre-step 注入失败', e) } catch {}
464
- // next() 可能已经跑过,无法安全重放;异常只能吞掉,不能冒泡
465
- }
466
- })
467
- }
1
+ // 灵枢 · DSH/Cordis 启动注入插件
2
+ //
3
+ // 为什么需要它:DSH 的技能 catalog 只把 name+description 给模型,正文要不要读
4
+ // 全凭模型自觉。本插件把"自觉"变成"机制"——每个新会话(agent/created,
5
+ // source ∈ startup/resume)时自动跑灵枢的 `brain.py startup`,把人格、记忆、
6
+ // 待办、行为指引注入会话上下文,模型想忘都忘不掉。
7
+ //
8
+ // 事件与注入(对齐 DSH 真实 API):
9
+ // - 监听 `agent/created`(serial 事件,监听器会被 await,失败会回滚会话创建——
10
+ // 所以本插件任何路径都不允许抛异常),payload 为
11
+ // { agent, source: 'startup'|'resume'|'clear'|'compact', signal? }。
12
+ // 只对 startup/resume 注入;clear/compact 是同会话重建上下文,不重复注入。
13
+ // - 投递用 agent/pre-step 钩子:agent/created 里只跑 startup 并把文本存进
14
+ // pending Map;pre-step(构建 messages 之后、请求之前)await next() 后把文本
15
+ // 追加进 enter 分支的 messages——不排队、不经过 inbox 消费逻辑,必然进模型
16
+ // 上下文。此前试过 inject(写 next-step,turn/start 清空丢注入)与
17
+ // send('next-turn')(进待发送队列,模型看不到),都实测失败。
18
+ //
19
+ // 数据安全:本插件只读记忆库(startup 内部只读+写 last_startup),不碰
20
+ // 技能目录;brain.py 自身保证只读降级(HOME 不可写时照样注入)。
21
+
22
+ import { spawn } from 'node:child_process'
23
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
24
+ import { homedir, tmpdir } from 'node:os'
25
+ import { delimiter, dirname, join } from 'node:path'
26
+ import { createHash, randomUUID } from 'node:crypto'
27
+ import { fileURLToPath } from 'node:url'
28
+ import { sampleContextPressure } from './context-pressure.js'
29
+ import { applyFolds } from './context-fold.js'
30
+
31
+ // 刻意零外部依赖:不 import @deepseek-ai/schemastery。原因——link: 安装时模块
32
+ // 真实路径留在技能目录,Node 从那里向上找 node_modules 一路到盘符根都找不到
33
+ // DSH 内置包,import 失败 → cordis 静默跳过整个插件(UI 里装了却不动)。
34
+ // 去掉依赖后 link 安装也能工作,改 plugin.js 即时生效,不必每次重打包。
35
+
36
+ export const name = 'dsh-lingshu-startup'
37
+
38
+ /** 注入消息的 source.name:与 cron 的 'lingshu-cron'、im 的 'lingshu-im' 区分开。 */
39
+ const INJECT_SOURCE = 'lingshu-startup'
40
+
41
+ // 本插件文件在 <包根>/cordis-plugin/lingshu-startup/plugin.js,
42
+ // 往上一级是 cordis-plugin/,再上一级就是包根(含 scripts/brain.py 与 SKILL.md)。
43
+ const PLUGIN_DIR = dirname(fileURLToPath(import.meta.url))
44
+ const PACKAGE_ROOT = join(PLUGIN_DIR, '..', '..')
45
+
46
+ /**
47
+ * 把"找不到 brain.py / python"这类静默失败写进 ~/.dsh/lingshu-diag.json。
48
+ * 为什么需要:插件里所有失败都必须吞掉(事件串行、抛异常会回滚会话),
49
+ * 结果就是"记忆不录入了"却没有任何痕迹可查——2026-11-20 那次排障就卡在这。
50
+ */
51
+ export function writeDiag(kind, detail) {
52
+ try {
53
+ const base = process.env.APP_DSH || join(homedir(), '.dsh')
54
+ const payload = {
55
+ ts: new Date().toISOString(),
56
+ plugin: 'lingshu-startup',
57
+ kind,
58
+ detail: detail && typeof detail === 'object' ? detail : { message: String(detail ?? '') },
59
+ }
60
+ writeFileSync(join(base, 'lingshu-diag.json'), JSON.stringify(payload, null, 2), 'utf8')
61
+ } catch {}
62
+ }
63
+
64
+ // 默认配置(纯普通对象,零依赖)。DSH 对导出 Config 的插件会喂用户配置,
65
+ // 不导出 Config 时喂默认空对象——两种情况本插件都能工作。
66
+ const DEFAULTS = {
67
+ brainPy: '', // brain.py 绝对路径;留空自动探测 ~/.dsh/skills/lingshu、~/.trae-cn/skills/lingshu
68
+ python: '', // python.exe 绝对路径;留空自动探测 DSH 自带运行时等位置(spawn 不解析 PATHEXT)
69
+ budget: 1400, // startup 注入 token 预算
70
+ timeoutMs: 3000, // startup 子进程超时;agent/created 是串行事件,超时太久拖慢新会话
71
+ resumeBudget: 400, // v3.59:resume 用极简版预算(人格+待办+水位,约 640 字符)。
72
+ // 为什么:会话历史里已有一份完整记忆块,resume 再注入一整份
73
+ // 就是同一段上下文出现两遍(实测 1214 tokens x 2)。
74
+ injectResume: true, // resume 来源(续聊)是否也注入
75
+ // —— P9 #61 开工前查(借鉴 ShellBrain CBR / mem0 proactive memory)——
76
+ // 每轮首个 pre-step 抽取用户消息,自动跑 `brain.py prior`,命中就注入
77
+ // "这件事以前做过吗"块,避免模型把已经做过/调研过的事重新来一遍。
78
+ priorAuto: true, // 关掉则只在模型主动调 `prior` 时生效
79
+ priorBudget: 1200, // prior 注入块字符上限(比 startup 小,它是每轮附加)
80
+ priorTimeoutMs: 6000, // prior 子进程超时(在请求关键路径上,宁可放弃也不拖住)
81
+ priorMinChars: 12, // 用户消息长度少于这个不查("继续""好"之类没有检索价值)
82
+ // —— v5.34 上下文折叠(默认关闭)——
83
+ // 账本由 `brain.py context fold --turn N` 生成;这里只负责把「生效中」的
84
+ // 整轮替换成摘要。默认关闭:它改的是每条请求的消息列表,先让人确认再开。
85
+ contextFold: false,
86
+ contextFoldMaxChars: 1600, // 单条折叠摘要落进上下文的字符上限
87
+ }
88
+
89
+ /** 合并用户配置与默认值(用户值非空/存在才覆盖) */
90
+ function mergeConfig(user) {
91
+ const merged = { ...DEFAULTS }
92
+ if (user && typeof user === 'object') {
93
+ for (const k of Object.keys(DEFAULTS)) {
94
+ const v = user[k]
95
+ if (v !== undefined && v !== null && v !== '') merged[k] = v
96
+ }
97
+ }
98
+ return merged
99
+ }
100
+
101
+ /** 依次探测常见安装位置的 brain.py */
102
+ async function findBrainPy(configured, ctx) {
103
+ if (configured) return existsSync(configured) ? configured : null
104
+ // ① 先看本包自带:插件就在 <包根>/cordis-plugin/lingshu-startup/ 里,
105
+ // ../../scripts/brain.py 一定和它同包发布。这一条不依赖任何宿主状态,
106
+ // 也不依赖"技能注册表带路径"(v3.53 之前正是缺了这一条:注册 runtime 技能
107
+ // 时没给 resourceBase/path,子插件就永远找不到 brain.py,整条自动注入/
108
+ // 即记即存/天级任务全部静默停摆)。
109
+ for (const p of brainPyCandidates()) {
110
+ if (existsSync(p)) return p
111
+ }
112
+ // ② 再问技能注册表(装了全局技能副本时更准;字段名跨版本不同,逐个试)
113
+ try {
114
+ const registry = ctx?.get?.('skills') ?? ctx?.skills
115
+ let items = registry?.list?.()
116
+ if (items?.then) items = await items
117
+ const hit = Array.isArray(items) ? items.find((s) => s?.name === 'lingshu') : null
118
+ if (hit) {
119
+ const bases = [
120
+ [hit.path, true], [hit.location, true],
121
+ [hit?.resourceBase?.path, false], // DSH 的 runtime 技能可带资源根目录
122
+ [hit.dir, false], [hit.baseDir, false], [hit.directory, false],
123
+ ]
124
+ for (const [raw, isFile] of bases) {
125
+ if (typeof raw !== 'string' || !raw) continue
126
+ const root = isFile ? dirname(raw) : raw
127
+ const p = join(root, 'scripts', 'brain.py')
128
+ if (existsSync(p)) return p
129
+ }
130
+ }
131
+ } catch (e) {
132
+ // 技能注册表探测失败不该静默——留一条日志方便排障(但不在群/会话里打扰)
133
+ try { ctx?.logger?.warn?.('lingshu-startup: 技能注册表探测异常,走环境变量/默认路径兜底', e) } catch {}
134
+ }
135
+ return null
136
+ }
137
+
138
+ /** 有可能藏着 brain.py 的绝对路径清单(纯函数,便于测试与排障打印) */
139
+ export function brainPyCandidates() {
140
+ const out = [join(PACKAGE_ROOT, 'scripts', 'brain.py')]
141
+ const envDir = (process.env.LINGSHU_SKILL_DIR || '').trim()
142
+ if (envDir) out.push(join(envDir, 'scripts', 'brain.py'))
143
+ const home = homedir()
144
+ out.push(
145
+ join(home, '.dsh', 'skills', 'lingshu', 'scripts', 'brain.py'),
146
+ join(home, '.trae-cn', 'skills', 'lingshu', 'scripts', 'brain.py'),
147
+ )
148
+ return out
149
+ }
150
+
151
+ /** 有可能可用的 python 可执行文件清单(纯函数,便于测试与排障打印) */
152
+ export function pythonCandidates() {
153
+ const home = homedir()
154
+ const out = []
155
+ for (const app of [process.env.APP_DSH, join(home, '.dsh')].filter(Boolean)) {
156
+ out.push(join(app, 'app-runtimes', 'app-primary-runtime', 'dependencies', 'python', 'python.exe'))
157
+ out.push(join(app, 'runtimes', 'app-primary-runtime', 'dependencies', 'python', 'python.exe'))
158
+ }
159
+ // PATH 里的 python.exe / python3.exe(ServBay、Store、conda 等布局都能命中)。
160
+ // 刻意不选 .cmd shim:spawn 走 CreateProcess 不解析 PATHEXT。
161
+ for (const dir of (process.env.PATH || '').split(delimiter)) {
162
+ if (!dir) continue
163
+ out.push(join(dir, 'python.exe'), join(dir, 'python3.exe'))
164
+ }
165
+ out.push(
166
+ join(home, 'AppData', 'Local', 'Programs', 'Python', 'python.exe'),
167
+ 'C:\\Python313\\python.exe',
168
+ 'C:\\Python312\\python.exe',
169
+ 'C:\\Program Files\\Python313\\python.exe',
170
+ )
171
+ return out
172
+ }
173
+
174
+ /**
175
+ * 探测可用的 python.exe。spawn 走 CreateProcess,不解析 PATHEXT——
176
+ * PATH 里只有 python.cmd 的机器上 spawn('python') 直接 ENOENT。
177
+ * 优先级:用户配置 > DSH 自带运行时(确定的 exe)> 常见安装位置 > 系统常见位置。
178
+ * 都没命中返回 null(由调用方走 cmd 兜底)。
179
+ */
180
+ function findPythonExe(configured) {
181
+ if (configured) return existsSync(configured) ? configured : null
182
+ for (const p of pythonCandidates()) {
183
+ if (existsSync(p)) return p
184
+ }
185
+ return null
186
+ }
187
+
188
+ /**
189
+ * 跑 brain.py startup,返回注入文本;失败返回 null(绝不抛异常、绝不阻塞会话)。
190
+ * 找不到 python.exe 时退回 ComSpec 让 cmd 解析 PATHEXT(python.cmd 也能跑)。
191
+ */
192
+ function runBrainText(pythonExe, pythonCmdFallback, brainPy, extraArgs, timeoutMs) {
193
+ return new Promise((resolve) => {
194
+ let settled = false
195
+ const done = (v) => { if (!settled) { settled = true; resolve(v) } }
196
+ const args = [brainPy, ...(extraArgs || [])]
197
+ let child
198
+ try {
199
+ if (pythonExe) {
200
+ child = spawn(pythonExe, args, {
201
+ windowsHide: true,
202
+ env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
203
+ // 显式把工作目录挪到用户主目录:绝不继承宿主 cwd。宿主 cwd 若在插件
204
+ // 目录内,Windows 会因"目录被进程占用"拒绝 pnpm 的目录 rename,
205
+ // 导致市场更新(remove+add)报"文件被占用、请退出 DSH"。
206
+ cwd: homedir(),
207
+ // 不用 spawn 的 timeout 选项:它只杀直接子进程,见下方手动兜底说明
208
+ })
209
+ } else {
210
+ // 兜底:让 cmd 去解析 .cmd(/d 关 autorun,/s 规范引号解析,/c 执行后退出)。
211
+ // 注意命令行必须带上 python 命令本身(pythonExe 没找到时用裸 'python',
212
+ // 由 cmd 按 PATHEXT 解析成 python.cmd)——只拼 brain.py 会依赖 .py 文件关联。
213
+ const comspec = process.env.ComSpec ?? 'cmd.exe'
214
+ const pythonCmd = pythonCmdFallback || 'python'
215
+ const cmdline = [`"${pythonCmd}"`, ...args.map((a) => `"${a}"`)].join(' ')
216
+ child = spawn(comspec, ['/d', '/s', '/c', cmdline], {
217
+ windowsHide: true,
218
+ windowsVerbatimArguments: true, // 命令行已手工加引号,阻止 Node 再转义一层
219
+ env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
220
+ cwd: homedir(), // 同上:不把宿主 cwd(可能在插件目录内)占给子进程
221
+ })
222
+ }
223
+ } catch {
224
+ return done(null)
225
+ }
226
+ let out = ''
227
+ child.stdout?.on('data', (d) => { out += d.toString('utf8') })
228
+ child.stderr?.resume() // 必须 drain:traceback 超 64KB 会塞满管道缓冲,子进程写阻塞永不退出
229
+ child.on('error', () => done(null))
230
+ // 手动超时兜底(不靠 spawn 的 timeout 选项,它只杀直接子进程):
231
+ // taskkill /T /F 杀整棵进程树——cmd 兜底分支里直接子进程是 cmd.exe,
232
+ // 只杀它会留下 python.exe 孙进程残留。
233
+ const killer = setTimeout(() => {
234
+ try {
235
+ if (child.pid) {
236
+ const tk = spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
237
+ tk.on('error', () => {}) // 无 taskkill(非 Windows)时静默,下面还有 child.kill() 托底
238
+ }
239
+ } catch {}
240
+ try { child.kill() } catch {}
241
+ done(null)
242
+ }, timeoutMs + 500)
243
+ killer.unref?.()
244
+ child.on('close', (code) => {
245
+ clearTimeout(killer) // 正常退出清掉兜底定时器,别留着空转
246
+ // 返回码 0=正常注入;10=只读降级注入(照样有效);2=未初始化(跳过)
247
+ done(code === 0 || code === 10 ? out.trim() : null)
248
+ })
249
+ })
250
+ }
251
+
252
+ /** 启动注入:brain.py startup --budget N */
253
+ function runStartup(pythonExe, pythonCmdFallback, brainPy, budget, timeoutMs) {
254
+ return runBrainText(pythonExe, pythonCmdFallback, brainPy,
255
+ ['startup', '--budget', String(budget)], timeoutMs)
256
+ }
257
+
258
+ /**
259
+ * 开工前查:brain.py prior --task-file <tmp> --render --budget N
260
+ *
261
+ * 任务文本来自**用户消息**,绝不拼进命令行——用户一句话里带引号/`&`/`|`
262
+ * 在 cmd 兜底分支就是命令注入(lingshu-im 那边踩过同款坑)。这里写临时文件、
263
+ * 只传路径,python 侧读完即删。
264
+ */
265
+ function runPrior(pythonExe, pythonCmdFallback, brainPy, taskText, budget, timeoutMs) {
266
+ let taskFile = ''
267
+ try {
268
+ const dir = join(tmpdir(), 'lingshu-prior')
269
+ mkdirSync(dir, { recursive: true })
270
+ taskFile = join(dir, `t-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.txt`)
271
+ writeFileSync(taskFile, String(taskText || '').slice(0, 2000), 'utf8')
272
+ } catch {
273
+ return Promise.resolve(null)
274
+ }
275
+ return runBrainText(pythonExe, pythonCmdFallback, brainPy,
276
+ ['prior', '--task-file', taskFile, '--render', '--budget', String(budget)],
277
+ timeoutMs).finally(() => {
278
+ // python 侧正常会删;异常/超时时这里兜底清理,避免临时文件堆积
279
+ try { rmSync(taskFile, { force: true }) } catch {}
280
+ })
281
+ }
282
+
283
+ /** 从 pre-step 决策的 messages 里抽出最后一条用户文本(含多模态里的 text 段) */
284
+ export function lastUserText(messages) {
285
+ if (!Array.isArray(messages)) return ''
286
+ for (let i = messages.length - 1; i >= 0; i--) {
287
+ const m = messages[i]
288
+ if (!m || m.role !== 'user') continue
289
+ const c = m.content
290
+ if (typeof c === 'string') return c.trim()
291
+ if (Array.isArray(c)) {
292
+ const t = c.filter((x) => x && x.type === 'text' && x.text).map((x) => x.text).join('\n')
293
+ if (t.trim()) return t.trim()
294
+ }
295
+ }
296
+ return ''
297
+ }
298
+
299
+ /** 像"要做的事"吗:够长、不是纯问候/确认。避免每轮都白跑一次 python。 */
300
+ export function looksLikeTask(text, minChars) {
301
+ const t = String(text || '').trim()
302
+ if (t.length < Math.max(4, Number(minChars) || 12)) return false
303
+ // 纯确认/寒暄短句("继续""好的""嗯"…)没有检索价值
304
+ if (/^(继续|好的?|嗯+|行|可以|收到|谢谢|ok|okay|yes|no|继续吧|接着来)[。!!.\s]*$/i.test(t)) return false
305
+ return true
306
+ }
307
+
308
+ export function apply(ctx, config) {
309
+ // v3.23:重复挂载守卫。profile 同时启用独立包与根包时,同一进程会出现两份 startup,
310
+ // 每会话注入两遍人格/记忆(白烧 ~3k token,且两份可能来自不同版本引擎)。
311
+ if (globalThis.__lingshuStartupApplied) {
312
+ try { ctx.logger?.warn?.('lingshu-startup: 已有一份灵枢 startup 在运行,跳过重复挂载') } catch {}
313
+ return
314
+ }
315
+ globalThis.__lingshuStartupApplied = true
316
+ const cfg = mergeConfig(config)
317
+ // pending:agent -> 注入文本。agent/created 只负责把文本存进来,
318
+ // 真正投递在 agent/pre-step 里做(见下)。
319
+ const pending = new Map()
320
+ // v3.59:每个 agent 已注入过的内容指纹(sha256 前 16 位)。
321
+ // 解决同一对话里注入第二份一模一样内容——resume、agent 重建、
322
+ // 宿主重复派发 agent/created 都可能触发重注入。同一份内容只进一次上下文,
323
+ // 这也正是提示词缓存友好的做法(只在末尾追加、不重复历史)。
324
+ const injectedDigests = new Map()
325
+ // P9 #61:每个 agent 已查过「开工前」的用户消息指纹(sha256 前 16 位)。
326
+ // 同一条消息只查一次,避免模型多步工具调用时反复触发 python 子进程。
327
+ const priorDigests = new Map()
328
+ // #45:digest -> 上次查询时间(毫秒)
329
+ let priorCooldown = new Map()
330
+ // 配置类失败只告警一次:静默吞掉配置错误会让插件"看似在工作、实际没注入"
331
+ let warnedOnce = false
332
+
333
+ ctx.on('agent/created', async (payload) => {
334
+ try { // 顶层兜底:serial 监听器 reject 会回滚会话创建,这里绝不允许冒泡
335
+ const { agent, source } = payload || {}
336
+ if (!agent) return
337
+ // 白名单:只有新开会话(startup)与续聊(resume)注入;
338
+ // clear / compact 是同会话上下文重建,重复注入只会浪费 token。
339
+ if (source !== 'startup' && source !== 'resume') return
340
+ if (source === 'resume' && !cfg.injectResume) return
341
+ if (pending.has(agent)) return
342
+ // P9 #57 + v5.36:startup 时先试采一次 tokenMeter。
343
+ // v5.37 改:不再清空旧样本。原因:新会话首轮 tokenMeter 往往还没 usage(还没发 API),
344
+ // 之前清空导致 Python 只能显示"未知 + 上次 47%(17.5h 前)"——用户看不到任何有用数字。
345
+ // 现在改成:采到了新数据就覆盖,采不到就保留旧样本;Python 侧 `_water_level()` 会按
346
+ // ts 判定 stale(超 4h 标"上次会话"),所以不会误报为"本会话实测"。
347
+
348
+ const brainPy = await findBrainPy(cfg.brainPy, ctx)
349
+ if (!brainPy) {
350
+ // 静默失败必须有痕迹:doctor / 面板 / 手工排障都读这个文件
351
+ writeDiag('brainPy-not-found', {
352
+ tried: brainPyCandidates(),
353
+ packageRoot: PACKAGE_ROOT,
354
+ configured: cfg.brainPy || null,
355
+ })
356
+ if (!warnedOnce) { warnedOnce = true; try { ctx.logger?.warn?.('lingshu-startup: 未找到 brain.py(未安装灵枢?),跳过注入') } catch {} }
357
+ return
358
+ }
359
+ const pythonExe = findPythonExe(cfg.python)
360
+ // v3.59:resume 走极简版预算——历史里已有完整记忆块,不必再来一份
361
+ const budget = source === 'resume'
362
+ ? (Number(cfg.resumeBudget) > 0 ? Number(cfg.resumeBudget) : cfg.budget)
363
+ : cfg.budget
364
+ const text = await runStartup(pythonExe, cfg.python, brainPy, budget, cfg.timeoutMs)
365
+ if (!text) {
366
+ writeDiag('startup-no-output', {
367
+ brainPy,
368
+ pythonExe: pythonExe || null,
369
+ pythonConfigured: cfg.python || null,
370
+ pythonTried: pythonCandidates().slice(0, 12),
371
+ })
372
+ if (!warnedOnce) { warnedOnce = true; try { ctx.logger?.warn?.('lingshu-startup: brain.py startup 未产出注入文本(python 不在/超时/未初始化),跳过注入') } catch {} }
373
+ return
374
+ }
375
+ // 成功时清掉上一次的失败痕迹,避免旧 diag 一直误导排障
376
+ try {
377
+ const base = process.env.APP_DSH || join(homedir(), '.dsh')
378
+ rmSync(join(base, 'lingshu-diag.json'), { force: true })
379
+ } catch {}
380
+ // v3.59:内容指纹去重——同一份文本在同一 agent 只注入一次。
381
+ // 场景:resume、agent 重建、宿主重复派发 agent/created。不加这道闸,
382
+ // 同一个对话里会出现两份一样的记忆块(实测 1214 tokens x 2),
383
+ // 既费 token 又让提示词缓存从重复处开始失效。
384
+ const digest = createHash('sha256').update(text).digest('hex').slice(0, 16)
385
+ let seen = injectedDigests.get(agent)
386
+ if (seen === undefined) {
387
+ seen = new Set()
388
+ injectedDigests.set(agent, seen)
389
+ }
390
+ if (seen.has(digest)) {
391
+ // 已经注入过一模一样的内容:直接跳过,不占上下文(也算成功,清掉旧 diag)
392
+ return
393
+ }
394
+ seen.add(digest)
395
+ // 只存不投递:send/inject 走 inbox 都有生命周期坑(实测坐实),真正进模型
396
+ // 上下文要在 agent/pre-step 里追加 messages(见下)。
397
+ pending.set(agent, text)
398
+ } catch (e) {
399
+ // 任何意外都不能让监听器 reject(agent/created 失败会回滚会话创建)
400
+ try { ctx.logger?.warn?.('lingshu-startup: 未捕获异常', e) } catch {}
401
+ }
402
+ })
403
+
404
+ // 每步构建 messages 之后、发起请求之前:把注入文本追加进这批 messages。
405
+ // 这条通道不排队、不经过 inbox 消费逻辑——enter 分支的 messages 就是模型看到的。
406
+ ctx.on('agent/pre-step', async (payload, next) => {
407
+ try {
408
+ // 先 await next():让其他(wrapping)监听器先改完,保住它们的
409
+ // startsRequestSeries / batch 语义,再在结果上追加。
410
+ const decision = await next()
411
+ // v3.86:每轮请求前采一次 DSH 的准确 token 压力(ctx.tokenMeter),
412
+ // 写 HOME/.context-pressure.json 给 brain.py 读。必须在决策之后也不影响
413
+ // 注入语义;采集器自身吞掉所有异常,绝不让 pre-step 冒泡。
414
+ try {
415
+ const { agent: pa } = payload || {}
416
+ if (pa) sampleContextPressure(ctx, pa)
417
+ } catch { /* 采集失败不影响请求/注入 */ }
418
+ if (!decision || decision.kind !== 'enter') return decision
419
+ const { agent } = payload || {}
420
+ // v5.34:上下文折叠(默认关闭)。把账本里生效中的整轮换成摘要。
421
+ // 只按消息 id 匹配、只改 decision.messages;任何异常吞掉,不影响本轮。
422
+ if (cfg.contextFold) {
423
+ try {
424
+ const r = applyFolds(decision, Number(cfg.contextFoldMaxChars) || 1600)
425
+ if (r && r.changed) {
426
+ try { ctx.logger?.debug?.(`[lingshu-startup] 折叠 ${r.folded} 轮`) } catch {}
427
+ }
428
+ } catch { /* 折叠失败照常发请求 */ }
429
+ }
430
+ const extra = []
431
+ // ① 启动注入(每次会话一次)
432
+ const text = agent && pending.get(agent)
433
+ if (text) {
434
+ pending.delete(agent) // 只注入一次:不删的话每条 pre-step 都会重复塞
435
+ extra.push(text)
436
+ }
437
+ // ② 开工前查(P9 #61):每轮首个 pre-step 抽用户消息 → prior → 命中才注入。
438
+ // 同一条消息只查一次(digest 去重);查不到就不注入,避免白占上下文。
439
+ if (cfg.priorAuto && agent) {
440
+ try {
441
+ const userText = lastUserText(decision.messages)
442
+ if (looksLikeTask(userText, cfg.priorMinChars)) {
443
+ const dig = createHash('sha256').update(userText).digest('hex').slice(0, 16)
444
+ let seen = priorDigests.get(agent)
445
+ if (seen === undefined) {
446
+ seen = new Set()
447
+ priorDigests.set(agent, seen)
448
+ }
449
+ if (!seen.has(dig)) {
450
+ // #45:同一 digest 的 prior 查询冷却(缓存守卫代理)。
451
+ // 为什么:每轮都查 prior 会让'稳定前缀'反复变化,宿主缓存命中率下降;
452
+ // 而我们拿不到命中率信号,只能用'刚查过就别再查'来降频。
453
+ const _cd = Number(cfg.priorCooldownSec || 0) * 1000
454
+ if (_cd > 0) {
455
+ const _last = priorCooldown.get(dig) || 0
456
+ if (Date.now() - _last < _cd) return decision
457
+ priorCooldown.set(dig, Date.now())
458
+ if (priorCooldown.size > 200) {
459
+ const _keep = [...priorCooldown.entries()].slice(-100)
460
+ priorCooldown = new Map(_keep)
461
+ }
462
+ }
463
+ seen.add(dig)
464
+ if (seen.size > 200) { // 防长会话无限增长
465
+ const keep = [...seen].slice(-100)
466
+ priorDigests.set(agent, new Set(keep))
467
+ }
468
+ const brainPy = await findBrainPy(cfg.brainPy, ctx)
469
+ const pythonExe = findPythonExe(cfg.python)
470
+ const block = brainPy
471
+ ? await runPrior(pythonExe, cfg.python, brainPy, userText,
472
+ cfg.priorBudget, cfg.priorTimeoutMs)
473
+ : null
474
+ if (block) extra.push(block)
475
+ }
476
+ }
477
+ } catch { /* 查不到/失败都不影响本轮请求 */ }
478
+ }
479
+ if (!extra.length) return decision
480
+ return {
481
+ ...decision,
482
+ messages: [
483
+ ...decision.messages,
484
+ ...extra.map((t) => ({
485
+ id: randomUUID(),
486
+ role: 'user',
487
+ content: [{ type: 'text', text: t }],
488
+ // v3.59:用自己的 source.name,别和 cron 的 'lingshu-cron' 撞。
489
+ // 撞了会被 cron 的 pruneInjected 当成本插件自己的旧提醒删掉。
490
+ source: { kind: 'skill-invocation', name: INJECT_SOURCE, form: 'instructions' },
491
+ })),
492
+ ],
493
+ }
494
+ } catch (e) {
495
+ try { ctx.logger?.warn?.('lingshu-startup: pre-step 注入失败', e) } catch {}
496
+ // next() 可能已经跑过,无法安全重放;异常只能吞掉,不能冒泡
497
+ }
498
+ })
499
+ }