dsh-qqbot-muu 0.1.15 → 0.1.21

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 (171) hide show
  1. package/CHANGELOG.md +168 -85
  2. package/client/qqbot-settings.js +13401 -12024
  3. package/config/modules.json +212 -0
  4. package/dist/channel-tools.js +21 -10
  5. package/dist/config.d.ts +14 -0
  6. package/dist/config.js +573 -449
  7. package/dist/features/contextless-store.js +247 -247
  8. package/dist/features/contextless-trim.js +455 -34
  9. package/dist/features/four-source.js +338 -336
  10. package/dist/features/group-join-request.js +289 -287
  11. package/dist/features/local-models.js +1494 -0
  12. package/dist/features/rotate-summarizer.js +438 -0
  13. package/dist/features/scenario-detect.js +321 -0
  14. package/dist/features/scheduler.js +8 -1
  15. package/dist/features/session-rotate.js +499 -0
  16. package/dist/features/session-title.js +199 -0
  17. package/dist/features/style-layer.js +501 -0
  18. package/dist/features/thinking-log.js +71 -69
  19. package/dist/gateway/bootstrap.js +1704 -1388
  20. package/dist/gateway/data-root.js +77 -3
  21. package/dist/gateway/middleware-setup.js +6 -3
  22. package/dist/index.js +4 -2
  23. package/dist/model/settings-reader.js +193 -102
  24. package/dist/session/session-manager.js +1730 -1587
  25. package/dist/shared/paths.js +128 -0
  26. package/dist/shared/settings-io.js +79 -0
  27. package/dist/transport/inbound.js +20 -1
  28. package/dist/transport/outbound.js +56 -4
  29. package/docs/RELEASE_CHECKLIST.md +24 -2
  30. package/dshqqbot/.qqbot-extensions/hooks/interview-panel.mjs +41 -1
  31. package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
  32. package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -689
  33. package/dshqqbot/.qqbot-extensions/inbound/ac-image-see.mjs +1 -1
  34. package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
  35. package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
  36. package/dshqqbot/.qqbot-extensions/lib/.pet-form.json +1 -1
  37. package/dshqqbot/.qqbot-extensions/lib/draw-core.mjs +238 -7
  38. package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -394
  39. package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
  40. package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
  41. package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
  42. package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
  43. package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
  44. package/dshqqbot/.qqbot-extensions/lib/plugin-dir.mjs +14 -4
  45. package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
  46. package/dshqqbot/.qqbot-extensions/lib/vision.mjs +1 -1
  47. package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
  48. package/dshqqbot/.qqbot-extensions/outbound/ac-media-fix.mjs +5 -1
  49. package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
  50. package/dshqqbot/.qqbot-extensions/outbound/split-reply.mjs +18 -2
  51. package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
  52. package/dshqqbot/.qqbot-extensions/tools/draw.mjs +22 -1
  53. package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
  54. package/dshqqbot/.qqbot-extensions/tools/pet_card.mjs +3 -2
  55. package/dshqqbot/.qqbot-extensions/tools/storyboard.mjs +3 -1
  56. package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
  57. package/package.json +119 -111
  58. package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
  59. package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
  60. package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
  61. package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
  62. package/scripts/_add_maintenance_cfg.py +20 -0
  63. package/scripts/_bench_keeplease.sh +10 -0
  64. package/scripts/_dbg_purge.py +15 -0
  65. package/scripts/_elev.sh +6 -0
  66. package/scripts/_fix_all_admin.cmd +16 -0
  67. package/scripts/_livecheck-image.mjs +33 -0
  68. package/scripts/_livecheck-llm.mjs +34 -0
  69. package/scripts/_livecheck-tts.mjs +37 -0
  70. package/scripts/_patch_curve.py +88 -0
  71. package/scripts/_patch_fan_thermal.py +24 -0
  72. package/scripts/_tag_tmp.py +13 -0
  73. package/scripts/adb-broker-client.mjs +87 -0
  74. package/scripts/adb-broker.mjs +205 -0
  75. package/scripts/ai-mode.cmd +6 -0
  76. package/scripts/ai-mode.py +387 -0
  77. package/scripts/ai-toolkit.py +607 -0
  78. package/scripts/apply-fan-gpu45.py +51 -0
  79. package/scripts/bench-fans.py +515 -0
  80. package/scripts/bench-load-direct.py +63 -0
  81. package/scripts/boot-tasks-hidden.vbs +20 -0
  82. package/scripts/boot-tasks.cmd +277 -0
  83. package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
  84. package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
  85. package/scripts/chat-archive/build-sft-v4.py +566 -0
  86. package/scripts/chat-archive/build-sft.py +390 -0
  87. package/scripts/chat-archive/eval-sft.py +155 -0
  88. package/scripts/chat-archive/extract-memory.py +143 -0
  89. package/scripts/chat-archive/inventory.py +182 -0
  90. package/scripts/chat-archive/merge-sft.py +114 -0
  91. package/scripts/chat-archive/qce-pull.py +217 -0
  92. package/scripts/chat-archive/qqheader.py +110 -0
  93. package/scripts/chat-archive/qqkey2.py +113 -0
  94. package/scripts/chat-archive/qqprobe.py +153 -0
  95. package/scripts/chat-archive/screen-collect.py +163 -0
  96. package/scripts/chat-archive/sqlcipher_probe.py +444 -0
  97. package/scripts/comfy_gen.py +209 -0
  98. package/scripts/compose-video.py +168 -0
  99. package/scripts/dl_models.py +45 -0
  100. package/scripts/draw-now.cmd +18 -0
  101. package/scripts/dsh-instance-guard.mjs +20 -2
  102. package/scripts/elev-extra.cmd +25 -0
  103. package/scripts/episode.py +529 -0
  104. package/scripts/fan-curve.py +218 -0
  105. package/scripts/fan-guard.cmd +8 -0
  106. package/scripts/fan-mode.py +380 -0
  107. package/scripts/fan_manual_safe.py +33 -0
  108. package/scripts/fan_restore_manual.py +46 -0
  109. package/scripts/fc_curves.py +359 -0
  110. package/scripts/fix-fan-and-timers.cmd +39 -0
  111. package/scripts/fix_admin_all.py +94 -0
  112. package/scripts/flows.mjs +224 -0
  113. package/scripts/gateway.cmd +126 -0
  114. package/scripts/gen-image.py +420 -0
  115. package/scripts/gen-video.py +186 -0
  116. package/scripts/git-askpass.cmd +2 -2
  117. package/scripts/gpu-mode.py +195 -0
  118. package/scripts/hw-profile.py +175 -0
  119. package/scripts/install-schedule.cmd +37 -0
  120. package/scripts/install-watch.cmd +29 -0
  121. package/scripts/matte-cutout.py +106 -0
  122. package/scripts/media-enhance.py +402 -0
  123. package/scripts/memory-audit.py +581 -0
  124. package/scripts/migrate-scope.mjs +140 -139
  125. package/scripts/model-registry.py +519 -0
  126. package/scripts/openid-audit.mjs +219 -0
  127. package/scripts/pull-gguf.py +127 -0
  128. package/scripts/purge-standby.py +151 -0
  129. package/scripts/qq-connect-login.py +133 -0
  130. package/scripts/qq-ip-sync-hidden.vbs +5 -0
  131. package/scripts/qq-ip-sync.py +300 -0
  132. package/scripts/qq-login-once.cmd +20 -0
  133. package/scripts/qq-login-qr.py +72 -0
  134. package/scripts/qq-whitelist-fix.cmd +27 -0
  135. package/scripts/qq-whitelist-login.cmd +26 -0
  136. package/scripts/qq-whitelist.cmd +12 -0
  137. package/scripts/qq-whitelist.py +1452 -0
  138. package/scripts/quality-compare.py +134 -0
  139. package/scripts/release-all.mjs +636 -430
  140. package/scripts/release-check.mjs +244 -226
  141. package/scripts/resume-coder.cmd +38 -0
  142. package/scripts/secure-room/index.html +334 -0
  143. package/scripts/secure-room/server.py +582 -0
  144. package/scripts/security-check.mjs +164 -0
  145. package/scripts/selftest-local-llm.mjs +20 -0
  146. package/scripts/selftest-local-models.mjs +754 -0
  147. package/scripts/selftest-rotate-style.mjs +308 -0
  148. package/scripts/shutdown-s5-optional.cmd +21 -0
  149. package/scripts/sleep-2325.cmd +75 -0
  150. package/scripts/start-comfyui.cmd +5 -0
  151. package/scripts/start-strata.cmd +17 -0
  152. package/scripts/start-strata.vbs +11 -0
  153. package/scripts/start-watch-hidden.vbs +3 -0
  154. package/scripts/stickers/auto-tag.mjs +161 -0
  155. package/scripts/storage.mjs +236 -0
  156. package/scripts/sync-plugin-copies.mjs +98 -23
  157. package/scripts/tests/test-qq-whitelist.py +192 -0
  158. package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
  159. package/scripts/train/gguf-quantize.py +92 -0
  160. package/scripts/train/gguf-to-hf.py +112 -0
  161. package/scripts/train/merge-lora.py +51 -0
  162. package/scripts/train/probe-mirrors.sh +12 -0
  163. package/scripts/train/probe-mirrors2.sh +20 -0
  164. package/scripts/train/setup-wsl.sh +23 -0
  165. package/scripts/train/setup-wsl2.sh +25 -0
  166. package/scripts/train/setup-wsl3.sh +22 -0
  167. package/scripts/train/setup-wsl4.sh +22 -0
  168. package/scripts/train/train-lora.py +319 -0
  169. package/scripts/vram-free.py +104 -0
  170. package/scripts/wechat-full-pull.mjs +1 -1
  171. package/settings-host.js +1047 -12
@@ -0,0 +1,499 @@
1
+ /**
2
+ * session-rotate.js — QQ 侧会话轮换(提交 B,2026-11-25,**默认关**)
3
+ *
4
+ * 背景:QQ 侧每轮全量发上下文、没有轮数上限,会话越聊越大(最大的单会话 17MB)。
5
+ * 微信侧早就有「聊够 N 轮 + 中途空闲 ≥5 分钟 → 出摘要 → 换新会话」,QQ 侧没有。
6
+ * 这里补上同一套,但**只在 config.sessionRotate === true 时**生效:
7
+ * · 判断:轮数 >= maxTurnsPerSession(默认 60)或上下文估算 > 30000 tokens,
8
+ * 且距上一次交互 >= 5 分钟(不打断正在聊的人);
9
+ * · 动作:旧会话出 ≤160 字摘要 → ①写 ctx-summary 留档 ②抽 ≤3 条事实进记忆库
10
+ * ③upsert 一条 persona ④新会话首条消息前置「上一段要点/相关记忆/最近原文」。
11
+ *
12
+ * 为什么摘要不在这里直接调模型:dist 里没有 silentTurn 通道,硬塞 followup 会让 AI
13
+ * 漏出可见回复。所以这里留 `summarize` 注入口(宿主/扩展可以给一个真正调模型的实现),
14
+ * 没注入时用本地抽取式摘要,保证"一定有东西可写、绝不阻塞入站"。
15
+ */
16
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
17
+ import { join, resolve } from 'node:path';
18
+ import { pathToFileURL } from 'node:url';
19
+ import { traceContextless } from './contextless-store.js';
20
+ import {
21
+ SUMMARY_PROMPT_PREFIX,
22
+ appendCtxSummary,
23
+ buildExtractiveSummary,
24
+ ctxSummaryKeyOf,
25
+ estimateAgentTokens,
26
+ estimateTokens,
27
+ recentMessagesOf,
28
+ } from './contextless-trim.js';
29
+ import {
30
+ DEFAULT_SIGNAL_WINDOW,
31
+ DEFAULT_TASK_THRESHOLD,
32
+ MODE_CHAT,
33
+ MODE_TASK,
34
+ classifyScenario,
35
+ collectSessionSignals,
36
+ explainScenario,
37
+ extractTaskAnchors,
38
+ formatTaskAnchors,
39
+ } from './scenario-detect.js';
40
+
41
+ /** 轮换阈值(默认值;可用 config 覆盖)
42
+ * 2026-11-25 任务 A:从「固定 60 轮」改成**按场景自适应** ——
43
+ * · 任务型(有工具/代码/长需求/路径/反复追同一目标)默认 250 轮、60k tokens;
44
+ * · 闲聊型(短句、表情、无工具)默认 1000 轮、100k tokens;
45
+ * · sessionRotateMode = auto|task|chat 可强制模式;
46
+ * · 旧配置 maxTurnsPerSession / sessionRotateTokens 仍生效:只在**判定不可用**时兜底。
47
+ * 2026-11-30 按主人要求把默认值从 150/600 提到 250/1000(仍可在设置页微调)。 */
48
+ export const DEFAULT_MAX_TURNS_PER_SESSION = 60;
49
+ export const DEFAULT_ROTATE_TOKEN_LIMIT = 30000;
50
+ export const DEFAULT_MAX_TURNS_TASK = 250;
51
+ export const DEFAULT_MAX_TURNS_CHAT = 1000;
52
+ export const DEFAULT_ROTATE_TOKENS_TASK = 60000;
53
+ export const DEFAULT_ROTATE_TOKENS_CHAT = 100000;
54
+ export const DEFAULT_ROTATE_MODE = 'auto';
55
+ /** 距上次交互至少多久才允许轮换(5 分钟) */
56
+ export const ROTATE_IDLE_MIN_MS = 5 * 60 * 1000;
57
+ /** 旧会话摘要最大字数(闲聊型:寒暄几句话够用) */
58
+ export const ROTATE_SUMMARY_MAX_CHARS = 160;
59
+ /** 任务型摘要预算:要装下「在做什么 + 待办 + 文件路径 + 报错原文」,160 字放不下三类锚点 */
60
+ export const ROTATE_SUMMARY_MAX_CHARS_TASK = 420;
61
+ /** 新会话首条消息带多少条原文 */
62
+ export const ROTATE_RECENT_RAW = 6;
63
+ /** 摘要拆成事实进记忆库的上限 */
64
+ export const ROTATE_MAX_FACTS = 3;
65
+
66
+ const TURNS_VERSION = 1;
67
+
68
+ function intOf(v, dflt, min, max) {
69
+ const n = Number(v);
70
+ if (!Number.isFinite(n))
71
+ return dflt;
72
+ return Math.min(max, Math.max(min, Math.round(n)));
73
+ }
74
+
75
+ /** 会话键 → 文件名安全键(与 ctx-summary 同一套规则,便于对同一会话对账) */
76
+ export function turnsKeyOf(sessionKey) {
77
+ return ctxSummaryKeyOf(sessionKey);
78
+ }
79
+
80
+ /** session-turns 目录:<dataRoot>/.qqbot/session-turns */
81
+ export function turnsDirOf(dataRoot) {
82
+ const root = String(dataRoot ?? '').trim() || resolve(process.cwd(), 'dshqqbot');
83
+ return join(root, '.qqbot', 'session-turns');
84
+ }
85
+
86
+ export function turnsPathOf(dataRoot, sessionKey) {
87
+ return join(turnsDirOf(dataRoot), turnsKeyOf(sessionKey) + '.json');
88
+ }
89
+
90
+ function emptyState() {
91
+ return {
92
+ v: TURNS_VERSION,
93
+ sid: '',
94
+ turns: 0,
95
+ rotating: false,
96
+ summary: '',
97
+ rotatedFrom: '',
98
+ at: 0,
99
+ estTokens: 0,
100
+ pendingIntro: '',
101
+ // 2026-11-25 任务 A:最近一次场景判定的结果(诊断/设置页展示用,不参与计数)
102
+ scenario: '',
103
+ scenarioScore: 0,
104
+ scenarioWhy: '',
105
+ };
106
+ }
107
+
108
+ /** 读轮换状态(文件不存在/坏了都给默认值,绝不抛) */
109
+ export function loadTurns(dataRoot, sessionKey) {
110
+ try {
111
+ const p = turnsPathOf(dataRoot, sessionKey);
112
+ if (!existsSync(p))
113
+ return emptyState();
114
+ const raw = JSON.parse(readFileSync(p, 'utf8'));
115
+ const st = emptyState();
116
+ if (raw && typeof raw === 'object') {
117
+ st.sid = String(raw.sid ?? '');
118
+ st.turns = intOf(raw.turns ?? 0, 0, 0, 1000000);
119
+ st.rotating = raw.rotating === true;
120
+ st.summary = String(raw.summary ?? '');
121
+ st.rotatedFrom = String(raw.rotatedFrom ?? '');
122
+ st.at = Number(raw.at) || 0;
123
+ st.estTokens = intOf(raw.estTokens ?? 0, 0, 0, 100000000);
124
+ st.pendingIntro = String(raw.pendingIntro ?? '');
125
+ st.scenario = (raw.scenario === MODE_TASK || raw.scenario === MODE_CHAT) ? String(raw.scenario) : '';
126
+ st.scenarioScore = Number(raw.scenarioScore) || 0;
127
+ st.scenarioWhy = String(raw.scenarioWhy ?? '');
128
+ }
129
+ return st;
130
+ }
131
+ catch (err) {
132
+ traceContextless('[rotate] 读状态失败(按新会话算): ' + (err instanceof Error ? err.message : String(err)));
133
+ return emptyState();
134
+ }
135
+ }
136
+
137
+ /** 写轮换状态(原子替换;失败只记日志) */
138
+ export function saveTurns(dataRoot, sessionKey, state) {
139
+ try {
140
+ const dir = turnsDirOf(dataRoot);
141
+ mkdirSync(dir, { recursive: true });
142
+ const p = turnsPathOf(dataRoot, sessionKey);
143
+ const body = JSON.stringify({ v: TURNS_VERSION, ...state });
144
+ const tmp = p + '.tmp';
145
+ writeFileSync(tmp, body, 'utf8');
146
+ try {
147
+ // 先写临时文件再改名,避免半截 json 被读到
148
+ renameSync(tmp, p);
149
+ }
150
+ catch {
151
+ writeFileSync(p, body, 'utf8');
152
+ }
153
+ return true;
154
+ }
155
+ catch (err) {
156
+ traceContextless('[rotate] 写状态失败: ' + (err instanceof Error ? err.message : String(err)));
157
+ return false;
158
+ }
159
+ }
160
+
161
+ function clip(text, max) {
162
+ const t = String(text ?? '').replace(/[ \t]+/g, ' ').trim();
163
+ if (!t)
164
+ return '';
165
+ return t.length > max ? t.slice(0, Math.max(1, max - 1)) + '…' : t;
166
+ }
167
+
168
+ /**
169
+ * 给旧会话出一段摘要(≤maxChars 字)。
170
+ * 有 summarize 注入就用它(收到 {messages,promptPrefix,maxChars,mode},返回字符串),
171
+ * 没有/失败就用本地抽取式,最后兜底一句人话。
172
+ *
173
+ * 2026-11-25 任务 A:任务型会话额外把「待办 / 文件路径 / 报错原文」原样拼到摘要尾部 ——
174
+ * 模型摘要漏写、或直接退回抽取式时,这三类硬信息也不会丢(聊到一半的需求不能因为换档消失)。
175
+ */
176
+ export async function summarizeInto({ agent, maxChars, summarize, logger, mode } = {}) {
177
+ // 任务型给更大预算(420),闲聊型沿用 160;显式传 maxChars 时以调用方为准。
178
+ const budget = maxChars ?? (mode === MODE_TASK ? ROTATE_SUMMARY_MAX_CHARS_TASK : ROTATE_SUMMARY_MAX_CHARS);
179
+ const limit = intOf(budget, ROTATE_SUMMARY_MAX_CHARS, 40, 2000);
180
+ const msgs = recentMessagesOf(agent, 60);
181
+ const isTask = mode === MODE_TASK;
182
+ let base = '';
183
+ if (typeof summarize === 'function' && msgs.length > 0) {
184
+ try {
185
+ const raw = await summarize({ messages: msgs, promptPrefix: SUMMARY_PROMPT_PREFIX, maxChars: limit, mode: isTask ? MODE_TASK : MODE_CHAT });
186
+ const t = clip(raw, limit);
187
+ if (t)
188
+ base = t;
189
+ }
190
+ catch (err) {
191
+ traceContextless('[rotate] 摘要器失败(回退本地抽取): ' + (err instanceof Error ? err.message : String(err)));
192
+ logger?.debug?.('[rotate] 摘要器失败: ' + (err instanceof Error ? err.message : String(err)));
193
+ }
194
+ }
195
+ if (!base) {
196
+ const ex = buildExtractiveSummary(msgs, limit);
197
+ if (ex) {
198
+ // 去掉抽取式摘要自带的标题行,轮换摘要要的是"要点本身"
199
+ base = clip(ex.replace(/^(更早的对话已压缩,以下是要点)\n?/, '').replace(/\n/g, ';'), limit);
200
+ }
201
+ }
202
+ if (!base)
203
+ base = '(这一段聊得比较久,之前的细节没留全,接着聊就行)';
204
+ if (!isTask)
205
+ return base;
206
+ // ── 任务型:补锚点(待办/报错/文件)──
207
+ // 预算怎么分:主体至少留 40%(不然只剩一堆路径,看不出在干嘛),锚点吃剩下的额度。
208
+ // 锚点之间按「待办 → 报错 → 文件」顺序裁,前两类被裁掉时才丢路径 —— 待办和报错优先。
209
+ const anchors = extractTaskAnchors(msgs);
210
+ const anchorLine = formatTaskAnchors(anchors);
211
+ if (!anchorLine)
212
+ return base;
213
+ const reserve = Math.max(24, Math.floor(limit * 0.4));
214
+ const head = clip(base, Math.max(16, limit - reserve - 1));
215
+ const remain = Math.max(12, limit - head.length - 1);
216
+ return head + '|' + clip(anchorLine, remain);
217
+ }
218
+
219
+ /** 摘要 → ≤3 条事实(去重交给记忆库自己的 cos 阈值 0.92) */
220
+ export function factsOf(summary) {
221
+ const parts = String(summary ?? '')
222
+ .split(/[。!?;\n]+/)
223
+ .map((s) => s.replace(/^(她|对方|我|你)[::]\s*/, '').trim())
224
+ .filter((s) => s.length >= 6 && s.length <= 120);
225
+ return parts.slice(0, ROTATE_MAX_FACTS);
226
+ }
227
+
228
+ /** 记忆库是扩展侧的实现,按数据根动态加载;没有就静默跳过 */
229
+ async function loadMemoryDb(dataRoot) {
230
+ try {
231
+ const root = String(dataRoot ?? '').trim();
232
+ if (!root)
233
+ return null;
234
+ const p = join(root, '.qqbot-extensions', 'lib', 'memory-db.mjs');
235
+ if (!existsSync(p))
236
+ return null;
237
+ return await import(pathToFileURL(p).href);
238
+ }
239
+ catch (err) {
240
+ traceContextless('[rotate] 记忆库加载失败(跳过记忆写入): ' + (err instanceof Error ? err.message : String(err)));
241
+ return null;
242
+ }
243
+ }
244
+
245
+ /**
246
+ * 组装新会话首条消息前缀。
247
+ * 结构固定三节:## 上一段要点 / ## 相关记忆 / ## 最近 N 条原文(空节直接省掉)。
248
+ */
249
+ export function buildIntro({ summary, recallText, recent } = {}) {
250
+ const parts = [];
251
+ const s = String(summary ?? '').trim();
252
+ if (s)
253
+ parts.push('## 上一段要点\n' + s);
254
+ const r = String(recallText ?? '').trim();
255
+ if (r)
256
+ parts.push('## 相关记忆\n' + r);
257
+ const list = Array.isArray(recent) ? recent.slice(-ROTATE_RECENT_RAW) : [];
258
+ if (list.length > 0) {
259
+ const lines = list.map((m) => (m.role === 'assistant' ? '她:' : '对方:') + clip(m.text, 120)).filter(Boolean);
260
+ if (lines.length > 0)
261
+ parts.push('## 最近 ' + lines.length + ' 条原文\n' + lines.join('\n'));
262
+ }
263
+ return parts.join('\n\n');
264
+ }
265
+
266
+ /** 取走并清空"待注入的上一段要点"(新会话第一条消息前用) */
267
+ export function takePendingIntro({ dataRoot, sessionKey } = {}) {
268
+ try {
269
+ if (!dataRoot || !sessionKey)
270
+ return '';
271
+ const st = loadTurns(dataRoot, sessionKey);
272
+ if (!st.pendingIntro)
273
+ return '';
274
+ const intro = st.pendingIntro;
275
+ st.pendingIntro = '';
276
+ saveTurns(dataRoot, sessionKey, st);
277
+ return intro;
278
+ }
279
+ catch {
280
+ return '';
281
+ }
282
+ }
283
+
284
+ /**
285
+ * 记一轮:**轮数的唯一写入点**(2026-11-25 统一计数)。
286
+ * 由 outbound 的 turn/end 调一次(一轮结束才 +1),原来 outbound 里的 `record.turns` 内存计数已停用。
287
+ * 这样「轮数」只有一处真相:`.qqbot/session-turns/<key>.json`,重启不归零、GUI/QQ 两边读同一个数。
288
+ * @returns {{turns:number, state:object}}
289
+ */
290
+ export function bumpTurns({ dataRoot, sessionKey, sid, at = Date.now() } = {}) {
291
+ if (!dataRoot || !sessionKey)
292
+ return { turns: 0, state: emptyState() };
293
+ const state = loadTurns(dataRoot, sessionKey);
294
+ const nowSid = String(sid ?? '');
295
+ if (state.sid && nowSid && state.sid !== nowSid) {
296
+ // 档被换过(forceRotate / cwd 迁移)→ 新档从头数
297
+ state.turns = 0;
298
+ state.pendingIntro = '';
299
+ state.sid = nowSid;
300
+ }
301
+ else if (nowSid && !state.sid) {
302
+ state.sid = nowSid;
303
+ }
304
+ state.turns = (Number(state.turns) || 0) + 1;
305
+ state.at = Number(at) || Date.now();
306
+ state.rotating = false;
307
+ saveTurns(dataRoot, sessionKey, state);
308
+ return { turns: state.turns, state };
309
+ }
310
+
311
+ /**
312
+ * 每轮入口调用一次:**只读**轮数(不再自增,见 bumpTurns),够阈值 + 够空闲才真轮换。
313
+ * 由 session-manager.getOrCreate 在 `config.sessionRotate === true` 时调用。
314
+ * @returns {Promise<{rotated:boolean, reason?:string, turns?:number, estTokens?:number,
315
+ * oldSid?:string, newSessionId?:string, summary?:string}>}
316
+ */
317
+ export async function maybeRotate({ manager, key, scope, peerId, config, logger, dataRoot, now = Date.now(), summarize } = {}) {
318
+ if (!manager || !key)
319
+ return { rotated: false, reason: 'bad-args' };
320
+ const root = dataRoot;
321
+ if (!root)
322
+ return { rotated: false, reason: 'no-data-root' };
323
+ const live = manager.sessions?.get?.(key);
324
+ const state = loadTurns(root, key);
325
+ const nowSid = live?.sessionId ? String(live.sessionId) : '';
326
+ let dirty = false;
327
+ // 会话档被换过(外部 forceRotate / cwd 迁移 / 重启后重建)→ 计数归零,不立刻轮换
328
+ if (state.sid && nowSid && state.sid !== nowSid) {
329
+ traceContextless('[rotate] 会话档已变,计数归零: key=' + key);
330
+ state.turns = 0;
331
+ state.pendingIntro = '';
332
+ state.sid = nowSid;
333
+ dirty = true;
334
+ }
335
+ if (state.rotating) {
336
+ // 上一轮如果中途挂了,这里清掉挂起标记(真在跑的话下一轮也会重算)
337
+ state.rotating = false;
338
+ dirty = true;
339
+ }
340
+ const prevAt = Number(state.at) || 0;
341
+ const turns = Number(state.turns) || 0;
342
+ if (!live) {
343
+ if (dirty)
344
+ saveTurns(root, key, state);
345
+ return { rotated: false, reason: 'no-live-session', turns };
346
+ }
347
+ // ── 2026-11-25 任务 A:先判「任务型 / 闲聊型」,再按场景取阈值 ──
348
+ // 强制模式(sessionRotateMode=task|chat)跳过判定;auto 时用最近 N 条可观测信号打分。
349
+ // 判定失败/没素材 → scenario 为空 → 退回旧的固定阈值(maxTurnsPerSession / sessionRotateTokens)。
350
+ let scenario = '';
351
+ let verdict = null;
352
+ const forced = String(config?.sessionRotateMode ?? DEFAULT_ROTATE_MODE).trim().toLowerCase();
353
+ if (forced === MODE_TASK || forced === MODE_CHAT) {
354
+ scenario = forced;
355
+ }
356
+ else {
357
+ try {
358
+ const win = intOf(config?.sessionRotateWindow ?? DEFAULT_SIGNAL_WINDOW, DEFAULT_SIGNAL_WINDOW, 4, 60);
359
+ const th = Number(config?.sessionRotateTaskScore ?? DEFAULT_TASK_THRESHOLD);
360
+ const sig = collectSessionSignals(live.agent, { msgLimit: win });
361
+ verdict = classifyScenario({
362
+ messages: sig.messages,
363
+ toolCalls: sig.toolCalls,
364
+ threshold: Number.isFinite(th) ? th : DEFAULT_TASK_THRESHOLD,
365
+ });
366
+ if (verdict.stats.messages > 0)
367
+ scenario = verdict.mode;
368
+ }
369
+ catch (e) {
370
+ traceContextless('[rotate] 场景判定失败(退回固定阈值): ' + (e instanceof Error ? e.message : String(e)));
371
+ }
372
+ }
373
+ const why = verdict ? explainScenario(verdict) : ('mode=' + (scenario || 'fallback') + ' (强制或无法判定)');
374
+ if (state.scenario !== scenario || state.scenarioScore !== (verdict?.score ?? 0) || state.scenarioWhy !== why) {
375
+ state.scenario = scenario;
376
+ state.scenarioScore = verdict?.score ?? 0;
377
+ state.scenarioWhy = why;
378
+ dirty = true;
379
+ }
380
+ const taskMode = scenario === MODE_TASK;
381
+ const chatMode = scenario === MODE_CHAT;
382
+ const maxTurns = taskMode
383
+ ? intOf(config?.sessionRotateTaskTurns ?? config?.maxTurnsTask ?? DEFAULT_MAX_TURNS_TASK, DEFAULT_MAX_TURNS_TASK, 4, 10000)
384
+ : chatMode
385
+ ? intOf(config?.sessionRotateChatTurns ?? config?.maxTurnsChat ?? DEFAULT_MAX_TURNS_CHAT, DEFAULT_MAX_TURNS_CHAT, 4, 10000)
386
+ : intOf(config?.maxTurnsPerSession ?? DEFAULT_MAX_TURNS_PER_SESSION, DEFAULT_MAX_TURNS_PER_SESSION, 4, 10000);
387
+ const tokenLimit = taskMode
388
+ ? intOf(config?.sessionRotateTaskTokens ?? config?.sessionRotateTokensTask ?? DEFAULT_ROTATE_TOKENS_TASK, DEFAULT_ROTATE_TOKENS_TASK, 1000, 10000000)
389
+ : chatMode
390
+ ? intOf(config?.sessionRotateChatTokens ?? config?.sessionRotateTokensChat ?? DEFAULT_ROTATE_TOKENS_CHAT, DEFAULT_ROTATE_TOKENS_CHAT, 1000, 10000000)
391
+ : intOf(config?.sessionRotateTokens ?? DEFAULT_ROTATE_TOKEN_LIMIT, DEFAULT_ROTATE_TOKEN_LIMIT, 1000, 10000000);
392
+ const estTokens = estimateAgentTokens(live.agent);
393
+ logger?.debug?.('[rotate] ' + why + ' key=' + key + ' turns=' + turns + '/' + maxTurns + ' est=' + estTokens + '/' + tokenLimit);
394
+ const overTurns = turns >= maxTurns;
395
+ const overTokens = estTokens > tokenLimit;
396
+ if (!overTurns && !overTokens) {
397
+ if (dirty)
398
+ saveTurns(root, key, state);
399
+ return { rotated: false, reason: 'below-threshold', turns, estTokens, scenario, maxTurns, tokenLimit, score: verdict?.score ?? 0 };
400
+ }
401
+ const idleMs = prevAt > 0 ? now - prevAt : 0;
402
+ if (idleMs < ROTATE_IDLE_MIN_MS) {
403
+ if (dirty)
404
+ saveTurns(root, key, state);
405
+ return { rotated: false, reason: 'not-idle', turns, estTokens, idleMs };
406
+ }
407
+ // ── 到这里才真动 ──
408
+ state.rotating = true;
409
+ saveTurns(root, key, state);
410
+ const oldSid = nowSid || String(state.sid || '');
411
+ const memScope = String(scope ?? '') + ':' + String(peerId ?? '');
412
+ const recent = recentMessagesOf(live.agent, ROTATE_RECENT_RAW);
413
+ const summary = await summarizeInto({
414
+ agent: live.agent,
415
+ maxChars: scenario === MODE_TASK ? ROTATE_SUMMARY_MAX_CHARS_TASK : ROTATE_SUMMARY_MAX_CHARS,
416
+ summarize,
417
+ logger,
418
+ mode: scenario,
419
+ });
420
+ // ① 留档:同一份摘要进 ctx-summary(与预算压缩共用一套账,每会话留 3 条)
421
+ try {
422
+ await appendCtxSummary({
423
+ dataRoot: root,
424
+ sessionKey: key,
425
+ at: now,
426
+ turnFrom: Math.max(1, turns - 1),
427
+ turnTo: turns,
428
+ fromSeq: null,
429
+ toSeq: null,
430
+ text: summary,
431
+ tokens: estimateTokens(summary),
432
+ dropped: [],
433
+ });
434
+ }
435
+ catch (err) {
436
+ traceContextless('[rotate] 写 ctx-summary 失败(不影响轮换): ' + (err instanceof Error ? err.message : String(err)));
437
+ }
438
+ // ② 事实 + ③ persona:记忆库不在(未装扩展)就跳过,绝不拖垮轮换
439
+ const db = await loadMemoryDb(root);
440
+ if (db) {
441
+ for (const text of factsOf(summary)) {
442
+ try {
443
+ await db.remember(root, memScope, { text, kind: 'fact' });
444
+ }
445
+ catch (err) {
446
+ traceContextless('[rotate] 记忆写入失败: ' + (err instanceof Error ? err.message : String(err)));
447
+ }
448
+ }
449
+ try {
450
+ db.setPersona(root, memScope, { ckey: '上一段要点', cvalue: clip(summary, 160), weight: 3 });
451
+ }
452
+ catch (err) {
453
+ traceContextless('[rotate] persona 写入失败: ' + (err instanceof Error ? err.message : String(err)));
454
+ }
455
+ }
456
+ // ④ 换新会话(旧档文件保留在宿主 sessions 目录里,可回看)
457
+ let rotated = null;
458
+ try {
459
+ rotated = await manager.forceRotate(scope, peerId, 'rotate-summary');
460
+ }
461
+ catch (err) {
462
+ traceContextless('[rotate] forceRotate 失败: ' + (err instanceof Error ? err.message : String(err)));
463
+ state.rotating = false;
464
+ saveTurns(root, key, state);
465
+ return { rotated: false, reason: 'rotate-failed', turns, estTokens };
466
+ }
467
+ const newSid = String(rotated?.sessionId ?? '');
468
+ // 相关记忆:拿旧摘要去记忆库捞 4 条,拼进首条消息
469
+ let recallText = '';
470
+ if (db) {
471
+ try {
472
+ const hits = await db.recall(root, memScope, summary, undefined);
473
+ if (Array.isArray(hits) && hits.length > 0) {
474
+ const block = db.formatRecallBlock(hits.slice(0, 4), undefined) || '';
475
+ recallText = String(block).replace(/^\s*\[记忆\]\s*/, '').replace(/\[\/记忆\]\s*$/, '').trim();
476
+ }
477
+ }
478
+ catch (err) {
479
+ traceContextless('[rotate] 召回失败(首条消息少一节): ' + (err instanceof Error ? err.message : String(err)));
480
+ }
481
+ }
482
+ const intro = buildIntro({ summary, recallText, recent });
483
+ const next = emptyState();
484
+ next.sid = newSid;
485
+ next.turns = 0;
486
+ next.summary = summary;
487
+ next.rotatedFrom = oldSid;
488
+ next.at = now;
489
+ next.pendingIntro = intro;
490
+ // 新档继承「本次是按什么场景换的」——诊断页看得到,下一轮起重新判定
491
+ next.scenario = scenario;
492
+ next.scenarioScore = verdict?.score ?? 0;
493
+ next.scenarioWhy = why;
494
+ saveTurns(root, key, next);
495
+ logger?.info?.('[rotate] 已轮换会话: key=' + key + ' scenario=' + (scenario || 'fallback') + ' turns=' + turns + '/' + maxTurns
496
+ + ' est=' + estTokens + ' old=' + String(oldSid).slice(0, 8) + '… new=' + String(newSid).slice(0, 8) + '…');
497
+ traceContextless('[rotate] ok key=' + key + ' turns=' + turns + ' est=' + estTokens + ' mode=' + (scenario || 'fallback'));
498
+ return { rotated: true, reason: 'rotated', turns, estTokens, oldSid, newSessionId: newSid, summary, scenario, maxTurns, tokenLimit };
499
+ }