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,252 +1,343 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
- """会话摘要层(附录 C · P2)——五段式摘要 + 校验 + fail-open。
4
-
5
- 设计要点(照附录 C 与 billion-context 的教训):
6
- 1. **五段固定结构**:目标 / 已做 / 未决 / 约束 / 原话引用。其中「原话引用」必须逐字保留,
7
- 它是摘要漂移时的纠错锚。
8
- 2. **外部便宜模型可选**:配 `config.summary`(OpenAI 兼容 /chat/completions)就走模型;
9
- 没配、超时、报错、输出不合格 → 一律**回退到离线抽取式摘要**,绝不阻塞主流程(fail-open)。
10
- 3. **提交前校验**:长度上限 + 五个小标题齐全 + 不许整段回显 prompt / 代码块。
11
- 4. 纯标准库;模型调用用 urllib,可注入 `call` 便于测试(不联网也能测全部分支)。
12
-
13
- CLI(在 cli.py 里挂 `summarize`):
14
- brain.py summarize --input turns.jsonl [--json] [--max-chars 1500]
15
- """
16
- from __future__ import annotations
17
-
18
- import json
19
- import math
20
- import os
21
- import re
22
- import urllib.request
23
-
24
- HEADERS = ("目标", "已做", "未决", "约束", "原话引用")
25
- DEFAULT_MAX_CHARS = 1500
26
-
27
- TEMPLATE = """你是会话摘要器。把下面的对话压成固定五段,供下一轮上下文使用。
28
-
29
- 必须严格输出这五个小标题(顺序不变),每段 1-3 行:
30
- ## 目标
31
- (用户想要什么;可引用一句原话)
32
- ## 已做
33
- (已经完成/确认的事实,带路径或命令)
34
- ## 未决
35
- (还没定的问题、待办、阻塞)
36
- ## 约束
37
- (用户明确说过的限制:风格、技术栈、不要做什么)
38
- ## 原话引用
39
- (最多 3 句必须逐字保留的用户原话:纠正、承诺、关键数字)
40
-
41
- 规则:
42
- - 总长不超过 {max_chars} 字;不要复述本提示,不要输出代码块。
43
- - 上一版摘要只作参考,发现冲突以最新对话为准。
44
-
45
- {prev}
46
- ---- 对话 ----
47
- {turns}
48
- """
49
-
50
-
51
- # ---------------------------------------------------------------- 输入归一
52
-
53
- def normalize_turns(raw) -> list[dict]:
54
- """接受 [{role,content}] / [{role,text}] / {"messages":[...]} / JSONL 行列表。"""
55
- if isinstance(raw, dict):
56
- raw = raw.get("messages") or raw.get("turns") or []
57
- out = []
58
- for item in raw or []:
59
- if not isinstance(item, dict):
60
- continue
61
- role = str(item.get("role") or item.get("sender") or "other").lower()
62
- if role in ("human", "me", "用户"):
63
- role = "user"
64
- elif role in ("ai", "bot", "model", "助手"):
65
- role = "assistant"
66
- text = item.get("content", item.get("text", item.get("message", "")))
67
- if isinstance(text, list): # OpenAI content parts
68
- text = " ".join(str(x.get("text") if isinstance(x, dict) else x) for x in text)
69
- text = str(text or "").strip()
70
- if text:
71
- out.append({"role": role, "text": text})
72
- return out
73
-
74
-
75
- def load_turns(path) -> list[dict]:
76
- """读 .jsonl(每行一条)或 .json(数组 / {messages:[...]})。
77
-
78
- 上限保护:导出文件可能几百 MB(整个账号的聊天记录),全量读进内存会炸。
79
- 这里只读前 64MB / 20 万行,超出截断并继续——摘要本来也不需要全量。
80
- """
81
- from pathlib import Path
82
- p = Path(path)
83
- MAX_BYTES = 64 * 1024 * 1024
84
- MAX_LINES = 200_000
85
- raw = p.read_bytes()
86
- if len(raw) > MAX_BYTES:
87
- raw = raw[:MAX_BYTES]
88
- text = raw.decode("utf-8-sig", errors="replace")
89
- if p.suffix.lower() == ".jsonl":
90
- rows = []
91
- for line in text.splitlines()[:MAX_LINES]:
92
- line = line.strip()
93
- if not line:
94
- continue
95
- try:
96
- rows.append(json.loads(line))
97
- except ValueError:
98
- continue
99
- return normalize_turns(rows)
100
- return normalize_turns(json.loads(text))
101
-
102
-
103
- # ---------------------------------------------------------------- 五段校验
104
-
105
- def validate(text: str, max_chars: int = DEFAULT_MAX_CHARS) -> tuple[bool, str]:
106
- """提交前校验:长度、五个小标题、拒绝回显提示/代码块。"""
107
- t = str(text or "").strip()
108
- if not t:
109
- return False, "空摘要"
110
- if len(t) > max_chars:
111
- return False, f"超长:{len(t)} > {max_chars}"
112
- missing = [h for h in HEADERS if f"## {h}" not in t]
113
- if missing:
114
- return False, "缺小标题:" + "、".join(missing)
115
- if "```" in t:
116
- return False, "包含代码块"
117
- if "规则:" in t and "上一版摘要" in t:
118
- return False, "疑似回显提示词"
119
- return True, ""
120
-
121
-
122
- # ---------------------------------------------------------------- 离线抽取式(fail-open 兜底)
123
-
124
- _KEY = re.compile(r"不对|不是|改成|记住|务必|不要|必须|只能|预算|注意|风险|TODO|待办|未决|下次|明天")
125
- _QUOTE = re.compile(r"不对|不是|改成|记住|务必|别|不要|必须")
126
-
127
-
128
- def _clip(s: str, n: int = 120) -> str:
129
- s = re.sub(r"\s+", " ", str(s or "")).strip()
130
- return s if len(s) <= n else s[: n - 1] + "…"
131
-
132
-
133
- def extractive_fallback(turns: list[dict], max_chars: int = DEFAULT_MAX_CHARS) -> str:
134
- """不调模型的确定性摘要:只挑明确信号,不编造。"""
135
- users = [t["text"] for t in turns if t["role"] == "user"]
136
- bots = [t["text"] for t in turns if t["role"] == "assistant"]
137
- goal = _clip(users[0], 160) if users else "(没读到用户消息)"
138
- done = [f"- {_clip(b)}" for b in bots[-3:] if len(b) >= 8]
139
- pending = [f"- {_clip(u)}" for u in users[-3:] if _KEY.search(u)]
140
- constraints = [f"- {_clip(u)}" for u in users
141
- if re.search(r"不要|必须|只能|务必|别", u)][-3:]
142
- quotes = [f"- {_clip(u, 80)}" for u in users if _QUOTE.search(u)][-3:]
143
-
144
- def block(title: str, lines: list[str], empty: str) -> str:
145
- body = "\n".join(lines) if lines else empty
146
- return f"## {title}\n{body}"
147
-
148
- text = "\n".join([
149
- block("目标", ([f"- {goal}"] if goal else []), "- (未提取到)"),
150
- block("已做", done, "- (未提取到)"),
151
- block("未决", pending, "- (未提取到)"),
152
- block("约束", constraints, "- (未提取到)"),
153
- block("原话引用", quotes, "- (未提取到)"),
154
- ])
155
- if len(text) > max_chars:
156
- text = text[: max_chars - 1].rstrip() + "…"
157
- return text
158
-
159
-
160
- # ---------------------------------------------------------------- 模型调用(可选)
161
-
162
- def _cfg_section(cfg: dict | None) -> dict:
163
- if cfg is not None:
164
- return dict(cfg.get("summary") or {})
165
- try:
166
- import core
167
- return dict((core.load_config() or {}).get("summary") or {})
168
- except Exception:
169
- return {}
170
-
171
-
172
- def openai_chat(prompt: str, cfg: dict, timeout: float | None = None) -> str | None:
173
- """OpenAI 兼容 /chat/completions;任何失败返回 None(由上层 fail-open)。"""
174
- base = str(cfg.get("base_url") or "").rstrip("/")
175
- model = str(cfg.get("model") or "")
176
- if not base or not model:
177
- return None
178
- key_env = str(cfg.get("api_key_env") or "")
179
- api_key = os.environ.get(key_env, "") if key_env else ""
180
- body = json.dumps({
181
- "model": model,
182
- "temperature": 0.2,
183
- "messages": [{"role": "user", "content": prompt}],
184
- }).encode("utf-8")
185
- url = base if base.endswith("/chat/completions") else base + "/chat/completions"
186
- req = urllib.request.Request(url, data=body, method="POST",
187
- headers={"Content-Type": "application/json",
188
- **({"Authorization": f"Bearer {api_key}"} if api_key else {})})
189
- try:
190
- with urllib.request.urlopen(req, timeout=timeout or float(cfg.get("timeout") or 30)) as r:
191
- data = json.loads(r.read().decode("utf-8", "replace"))
192
- content = (((data.get("choices") or [{}])[0]).get("message") or {}).get("content")
193
- return str(content or "").strip() or None
194
- except Exception as exc: # noqa: BLE001
195
- try:
196
- import failures
197
- failures.record("summary.model", f"{type(exc).__name__}: {exc}",
198
- ctx={"base_url": base, "model": model})
199
- except Exception:
200
- pass
201
- return None
202
-
203
-
204
- # ---------------------------------------------------------------- 主入口
205
-
206
- def build_prompt(turns: list[dict], prev_summary: str = "", max_chars: int = DEFAULT_MAX_CHARS) -> str:
207
- lines = []
208
- for t in turns:
209
- who = "用户" if t["role"] == "user" else ("我" if t["role"] == "assistant" else "其他")
210
- lines.append(f"{who}: {t['text']}")
211
- prev = f"上一版摘要:\n{prev_summary.strip()}\n" if prev_summary and prev_summary.strip() else ""
212
- return TEMPLATE.format(max_chars=max_chars, prev=prev, turns="\n".join(lines))
213
-
214
-
215
- def summarize(turns: list[dict], *, cfg: dict | None = None, prev_summary: str = "",
216
- max_chars: int = DEFAULT_MAX_CHARS, call=None) -> dict:
217
- """生成五段摘要:模型优先,失败/不合格一律回退抽取式。
218
-
219
- 返回 {text, source: 'model'|'fallback', actions:[...], warnings:[...], chars}
220
- """
221
- turns = normalize_turns(turns)
222
- actions: list[str] = []
223
- warnings: list[str] = []
224
- sec = _cfg_section(cfg)
225
- if not sec.get("enabled"):
226
- actions.append("summary.enabled=false:走离线抽取式")
227
- text = extractive_fallback(turns, max_chars)
228
- return {"text": text, "source": "fallback", "actions": actions,
229
- "warnings": warnings, "chars": len(text)}
230
-
231
- prompt = build_prompt(turns, prev_summary, max_chars)
232
- caller = call or (lambda p: openai_chat(p, sec))
233
- try:
234
- text = caller(prompt)
235
- except Exception as exc: # noqa: BLE001
236
- text = None
237
- warnings.append(f"模型调用异常:{exc!r}")
238
- if text:
239
- ok, why = validate(text, max_chars)
240
- if ok:
241
- return {"text": text, "source": "model", "actions": actions,
242
- "warnings": warnings, "chars": len(text)}
243
- warnings.append(f"模型输出不合格({why}),回退离线摘要")
244
- else:
245
- warnings.append("模型调用失败,回退离线摘要")
246
- text = extractive_fallback(turns, max_chars)
247
- return {"text": text, "source": "fallback", "actions": actions,
248
- "warnings": warnings, "chars": len(text)}
249
-
250
-
251
- def estimate_tokens(text: str, chars_per_token: int = 2) -> int:
252
- return int(math.ceil(len(text or "") / max(1, chars_per_token)))
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """会话摘要层(附录 C · P2)——五段式摘要 + 校验 + fail-open。
4
+
5
+ 设计要点(照附录 C 与 billion-context 的教训):
6
+ 1. **五段固定结构**:目标 / 已做 / 未决 / 约束 / 原话引用。其中「原话引用」必须逐字保留,
7
+ 它是摘要漂移时的纠错锚。
8
+ 2. **外部便宜模型可选**:配 `config.summary`(OpenAI 兼容 /chat/completions)就走模型;
9
+ 没配、超时、报错、输出不合格 → 一律**回退到离线抽取式摘要**,绝不阻塞主流程(fail-open)。
10
+ 3. **提交前校验**:长度上限 + 五个小标题齐全 + 不许整段回显 prompt / 代码块。
11
+ 4. 纯标准库;模型调用用 urllib,可注入 `call` 便于测试(不联网也能测全部分支)。
12
+
13
+ CLI(在 cli.py 里挂 `summarize`):
14
+ brain.py summarize --input turns.jsonl [--json] [--max-chars 1500]
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import math
20
+ import os
21
+ import re
22
+ import urllib.request
23
+
24
+ HEADERS = ("目标", "已做", "未决", "约束", "原话引用")
25
+ DEFAULT_MAX_CHARS = 1500
26
+
27
+ TEMPLATE = """你是会话摘要器。把下面的对话压成固定五段,供下一轮上下文使用。
28
+
29
+ 必须严格输出这五个小标题(顺序不变),每段 1-3 行:
30
+ ## 目标
31
+ (用户想要什么;可引用一句原话)
32
+ ## 已做
33
+ (已经完成/确认的事实,带路径或命令)
34
+ ## 未决
35
+ (还没定的问题、待办、阻塞)
36
+ ## 约束
37
+ (用户明确说过的限制:风格、技术栈、不要做什么)
38
+ ## 原话引用
39
+ (最多 3 句必须逐字保留的用户原话:纠正、承诺、关键数字)
40
+
41
+ 规则:
42
+ - 总长不超过 {max_chars} 字;不要复述本提示,不要输出代码块。
43
+ - 上一版摘要只作参考,发现冲突以最新对话为准。
44
+
45
+ {prev}
46
+ ---- 对话 ----
47
+ {turns}
48
+ """
49
+
50
+
51
+ # ---------------------------------------------------------------- 输入归一
52
+
53
+ def normalize_turns(raw) -> list[dict]:
54
+ """接受 [{role,content}] / [{role,text}] / {"messages":[...]} / JSONL 行列表。"""
55
+ if isinstance(raw, dict):
56
+ raw = raw.get("messages") or raw.get("turns") or []
57
+ out = []
58
+ for item in raw or []:
59
+ if not isinstance(item, dict):
60
+ continue
61
+ role = str(item.get("role") or item.get("sender") or "other").lower()
62
+ if role in ("human", "me", "用户"):
63
+ role = "user"
64
+ elif role in ("ai", "bot", "model", "助手"):
65
+ role = "assistant"
66
+ text = item.get("content", item.get("text", item.get("message", "")))
67
+ if isinstance(text, list): # OpenAI content parts
68
+ text = " ".join(str(x.get("text") if isinstance(x, dict) else x) for x in text)
69
+ text = str(text or "").strip()
70
+ if text:
71
+ out.append({"role": role, "text": text})
72
+ return out
73
+
74
+
75
+ def load_turns(path) -> list[dict]:
76
+ """读 .jsonl(每行一条)或 .json(数组 / {messages:[...]})。
77
+
78
+ 上限保护:导出文件可能几百 MB(整个账号的聊天记录),全量读进内存会炸。
79
+ 这里只读前 64MB / 20 万行,超出截断并继续——摘要本来也不需要全量。
80
+ """
81
+ from pathlib import Path
82
+ p = Path(path)
83
+ MAX_BYTES = 64 * 1024 * 1024
84
+ MAX_LINES = 200_000
85
+ raw = p.read_bytes()
86
+ if len(raw) > MAX_BYTES:
87
+ raw = raw[:MAX_BYTES]
88
+ text = raw.decode("utf-8-sig", errors="replace")
89
+ if p.suffix.lower() == ".jsonl":
90
+ rows = []
91
+ for line in text.splitlines()[:MAX_LINES]:
92
+ line = line.strip()
93
+ if not line:
94
+ continue
95
+ try:
96
+ rows.append(json.loads(line))
97
+ except ValueError:
98
+ continue
99
+ return normalize_turns(rows)
100
+ return normalize_turns(json.loads(text))
101
+
102
+
103
+ # ---------------------------------------------------------------- 五段校验
104
+
105
+ def validate(text: str, max_chars: int = DEFAULT_MAX_CHARS) -> tuple[bool, str]:
106
+ """提交前校验:长度、五个小标题、拒绝回显提示/代码块。"""
107
+ t = str(text or "").strip()
108
+ if not t:
109
+ return False, "空摘要"
110
+ if len(t) > max_chars:
111
+ return False, f"超长:{len(t)} > {max_chars}"
112
+ missing = [h for h in HEADERS if f"## {h}" not in t]
113
+ if missing:
114
+ return False, "缺小标题:" + "、".join(missing)
115
+ if "```" in t:
116
+ return False, "包含代码块"
117
+ if "规则:" in t and "上一版摘要" in t:
118
+ return False, "疑似回显提示词"
119
+ return True, ""
120
+
121
+
122
+ # ---------------------------------------------------------------- 离线抽取式(fail-open 兜底)
123
+
124
+ _KEY = re.compile(r"不对|不是|改成|记住|务必|不要|必须|只能|预算|注意|风险|TODO|待办|未决|下次|明天")
125
+ _QUOTE = re.compile(r"不对|不是|改成|记住|务必|别|不要|必须")
126
+
127
+
128
+ def _clip(s: str, n: int = 120) -> str:
129
+ s = re.sub(r"\s+", " ", str(s or "")).strip()
130
+ return s if len(s) <= n else s[: n - 1] + "…"
131
+
132
+
133
+ def textrank_top(texts: list, n: int = 3, iters: int = 20, d: float = 0.85) -> list:
134
+ """TextRank 选"最中心"的句子(§2 do-later)。
135
+
136
+ 为什么需要:位置启发式只看"最后 3 条"——一句"预算只有 3 天"如果不在末尾就丢了。
137
+ TextRank 按句子间的词重叠建图、迭代算中心性,**位置无关**,更能捞出全篇要点。
138
+
139
+ 只用标准库;相似度取 term 的 jaccard;PageRank 迭代 20 次。
140
+ 任何异常都退回"原顺序前 n 条",绝不抛。
141
+ """
142
+ try:
143
+ from mem_score import jaccard as _jac, terms as _terms
144
+ sents = []
145
+ for t in texts or []:
146
+ for s in re.split(r"[。!?!?\n]+", str(t or "")):
147
+ s = s.strip()
148
+ if len(s) >= 8:
149
+ sents.append(s)
150
+ if not sents:
151
+ return []
152
+ if len(sents) <= n:
153
+ return sents
154
+ ts = [_terms(s) for s in sents]
155
+ m = len(sents)
156
+ score = [1.0 / m] * m
157
+ for _ in range(iters):
158
+ new = [0.0] * m
159
+ for i in range(m):
160
+ acc = 0.0
161
+ for j in range(m):
162
+ if i == j:
163
+ continue
164
+ sim = _jac(ts[i], ts[j])
165
+ if sim > 0:
166
+ out_sum = sum(_jac(ts[k], ts[j]) for k in range(m) if k != j) or 1.0
167
+ acc += sim / out_sum * score[j]
168
+ new[i] = (1 - d) / m + d * acc
169
+ score = new
170
+ order = sorted(range(m), key=lambda i: -score[i])
171
+ return [sents[i] for i in order[:n]]
172
+ except Exception:
173
+ out = [s.strip() for t in (texts or [])
174
+ for s in re.split(r"[。!?!?\n]+", str(t or "")) if s.strip()]
175
+ return out[:n]
176
+
177
+
178
+ def extractive_fallback(turns: list[dict], max_chars: int = DEFAULT_MAX_CHARS,
179
+ ranker: str = "position") -> str:
180
+ """不调模型的确定性摘要:只挑明确信号,不编造。
181
+
182
+ `ranker="textrank"` 时,"已做"段不再取最后 3 条,而是用 TextRank 挑全篇最中心的句子
183
+ (避免"预算只有 3 天"这类关键句因为不在末尾而被丢掉)。默认仍走位置启发式。
184
+ """
185
+ users = [t["text"] for t in turns if t["role"] == "user"]
186
+ bots = [t["text"] for t in turns if t["role"] == "assistant"]
187
+ goal = _clip(users[0], 160) if users else "(没读到用户消息)"
188
+ # v5.34:同一句不允许在多个小节里重复出现。
189
+ # 实测症状:一段含"必须/不要"的大块会被 未决/约束/原话 三节同时抽中,
190
+ # 整份注入原样复制三遍,摘要等于没压。
191
+ used = {goal} if users else set()
192
+
193
+ def pick(cands, clip_n: int = 120) -> list[str]:
194
+ lines = []
195
+ for x in cands:
196
+ c = _clip(x, clip_n)
197
+ if not c or c in used:
198
+ continue
199
+ used.add(c)
200
+ lines.append(f"- {c}")
201
+ return lines
202
+
203
+ if ranker == "textrank":
204
+ _tops = textrank_top(bots, 3)
205
+ done = []
206
+ for s in _tops:
207
+ c = _clip(s, 120)
208
+ if c and c not in used:
209
+ used.add(c)
210
+ done.append(f"- {c}")
211
+ else:
212
+ done = pick([b for b in bots[-3:] if len(b) >= 8])
213
+ pending = pick([u for u in users[-3:] if _KEY.search(u)])[-3:]
214
+ constraints = pick([u for u in users
215
+ if re.search(r"不要|必须|只能|务必|别", u)])[-3:]
216
+ quotes = pick([u for u in users if _QUOTE.search(u)], 80)[-3:]
217
+
218
+ # 兜底补段(v5.34 残余风险):离线抽取只认明确信号,实测"未决/约束/原话"经常空着。
219
+ # 空着比缺信息更糟——读摘要的人会以为"这轮确实没有未决"。这里用保守规则兜一层:
220
+ # 只把**已经存在的内容**换个角度呈现,不编造。
221
+ if not pending:
222
+ _rest_u = [u for u in users if _clip(u, 120) not in used]
223
+ if _rest_u:
224
+ pending = [f"- 待确认:{_clip(_rest_u[-1], 120)}"]
225
+ if not constraints:
226
+ _cue = re.compile(r"不要|必须|只能|务必|别|预算|期限|deadline|时间只|最多|最少", re.I)
227
+ _c = [x for x in (users + bots) if _cue.search(x) and _clip(x, 120) not in used]
228
+ if _c:
229
+ constraints = [f"- {_clip(_c[-1], 120)}"]
230
+ if not quotes:
231
+ _rest_q = [u for u in users if _clip(u, 80) not in used]
232
+ if _rest_q:
233
+ quotes = [f"- 「{_clip(_rest_q[-1], 80)}」"]
234
+
235
+ def block(title: str, lines: list[str], empty: str) -> str:
236
+ body = "\n".join(lines) if lines else empty
237
+ return f"## {title}\n{body}"
238
+
239
+ text = "\n".join([
240
+ block("目标", ([f"- {goal}"] if goal else []), "- (未提取到)"),
241
+ block("已做", done, "- (本轮没有助手产出)"),
242
+ block("未决", pending, "- (本轮没有明显未决)"),
243
+ block("约束", constraints, "- (本轮没有明显约束)"),
244
+ block("原话引用", quotes, "- (本轮没有引号原话)"),
245
+ ])
246
+ if len(text) > max_chars:
247
+ text = text[: max_chars - 1].rstrip() + "…"
248
+ return text
249
+
250
+
251
+ # ---------------------------------------------------------------- 模型调用(可选)
252
+
253
+ def _cfg_section(cfg: dict | None) -> dict:
254
+ if cfg is not None:
255
+ return dict(cfg.get("summary") or {})
256
+ try:
257
+ import core
258
+ return dict((core.load_config() or {}).get("summary") or {})
259
+ except Exception:
260
+ return {}
261
+
262
+
263
+ def openai_chat(prompt: str, cfg: dict, timeout: float | None = None) -> str | None:
264
+ """OpenAI 兼容 /chat/completions;任何失败返回 None(由上层 fail-open)。"""
265
+ base = str(cfg.get("base_url") or "").rstrip("/")
266
+ model = str(cfg.get("model") or "")
267
+ if not base or not model:
268
+ return None
269
+ key_env = str(cfg.get("api_key_env") or "")
270
+ api_key = os.environ.get(key_env, "") if key_env else ""
271
+ body = json.dumps({
272
+ "model": model,
273
+ "temperature": 0.2,
274
+ "messages": [{"role": "user", "content": prompt}],
275
+ }).encode("utf-8")
276
+ url = base if base.endswith("/chat/completions") else base + "/chat/completions"
277
+ req = urllib.request.Request(url, data=body, method="POST",
278
+ headers={"Content-Type": "application/json",
279
+ **({"Authorization": f"Bearer {api_key}"} if api_key else {})})
280
+ try:
281
+ with urllib.request.urlopen(req, timeout=timeout or float(cfg.get("timeout") or 30)) as r:
282
+ data = json.loads(r.read().decode("utf-8", "replace"))
283
+ content = (((data.get("choices") or [{}])[0]).get("message") or {}).get("content")
284
+ return str(content or "").strip() or None
285
+ except Exception as exc: # noqa: BLE001
286
+ try:
287
+ import failures
288
+ failures.record("summary.model", f"{type(exc).__name__}: {exc}",
289
+ ctx={"base_url": base, "model": model})
290
+ except Exception:
291
+ pass
292
+ return None
293
+
294
+
295
+ # ---------------------------------------------------------------- 主入口
296
+
297
+ def build_prompt(turns: list[dict], prev_summary: str = "", max_chars: int = DEFAULT_MAX_CHARS) -> str:
298
+ lines = []
299
+ for t in turns:
300
+ who = "用户" if t["role"] == "user" else ("我" if t["role"] == "assistant" else "其他")
301
+ lines.append(f"{who}: {t['text']}")
302
+ prev = f"上一版摘要:\n{prev_summary.strip()}\n" if prev_summary and prev_summary.strip() else ""
303
+ return TEMPLATE.format(max_chars=max_chars, prev=prev, turns="\n".join(lines))
304
+
305
+
306
+ def summarize(turns: list[dict], *, cfg: dict | None = None, prev_summary: str = "",
307
+ max_chars: int = DEFAULT_MAX_CHARS, call=None) -> dict:
308
+ """生成五段摘要:模型优先,失败/不合格一律回退抽取式。
309
+
310
+ 返回 {text, source: 'model'|'fallback', actions:[...], warnings:[...], chars}
311
+ """
312
+ turns = normalize_turns(turns)
313
+ actions: list[str] = []
314
+ warnings: list[str] = []
315
+ sec = _cfg_section(cfg)
316
+ if not sec.get("enabled"):
317
+ actions.append("summary.enabled=false:走离线抽取式")
318
+ text = extractive_fallback(turns, max_chars, ranker=str(sec.get("ranker") or "position"))
319
+ return {"text": text, "source": "fallback", "actions": actions,
320
+ "warnings": warnings, "chars": len(text)}
321
+
322
+ prompt = build_prompt(turns, prev_summary, max_chars)
323
+ caller = call or (lambda p: openai_chat(p, sec))
324
+ try:
325
+ text = caller(prompt)
326
+ except Exception as exc: # noqa: BLE001
327
+ text = None
328
+ warnings.append(f"模型调用异常:{exc!r}")
329
+ if text:
330
+ ok, why = validate(text, max_chars)
331
+ if ok:
332
+ return {"text": text, "source": "model", "actions": actions,
333
+ "warnings": warnings, "chars": len(text)}
334
+ warnings.append(f"模型输出不合格({why}),回退离线摘要")
335
+ else:
336
+ warnings.append("模型调用失败,回退离线摘要")
337
+ text = extractive_fallback(turns, max_chars, ranker=str(sec.get("ranker") or "position"))
338
+ return {"text": text, "source": "fallback", "actions": actions,
339
+ "warnings": warnings, "chars": len(text)}
340
+
341
+
342
+ def estimate_tokens(text: str, chars_per_token: int = 2) -> int:
343
+ return int(math.ceil(len(text or "") / max(1, chars_per_token)))