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.
- package/CHANGELOG.md +168 -85
- package/client/qqbot-settings.js +13401 -12024
- package/config/modules.json +212 -0
- package/dist/channel-tools.js +21 -10
- package/dist/config.d.ts +14 -0
- package/dist/config.js +573 -449
- package/dist/features/contextless-store.js +247 -247
- package/dist/features/contextless-trim.js +455 -34
- package/dist/features/four-source.js +338 -336
- package/dist/features/group-join-request.js +289 -287
- package/dist/features/local-models.js +1494 -0
- package/dist/features/rotate-summarizer.js +438 -0
- package/dist/features/scenario-detect.js +321 -0
- package/dist/features/scheduler.js +8 -1
- package/dist/features/session-rotate.js +499 -0
- package/dist/features/session-title.js +199 -0
- package/dist/features/style-layer.js +501 -0
- package/dist/features/thinking-log.js +71 -69
- package/dist/gateway/bootstrap.js +1704 -1388
- package/dist/gateway/data-root.js +77 -3
- package/dist/gateway/middleware-setup.js +6 -3
- package/dist/index.js +4 -2
- package/dist/model/settings-reader.js +193 -102
- package/dist/session/session-manager.js +1730 -1587
- package/dist/shared/paths.js +128 -0
- package/dist/shared/settings-io.js +79 -0
- package/dist/transport/inbound.js +20 -1
- package/dist/transport/outbound.js +56 -4
- package/docs/RELEASE_CHECKLIST.md +24 -2
- package/dshqqbot/.qqbot-extensions/hooks/interview-panel.mjs +41 -1
- package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
- package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -689
- package/dshqqbot/.qqbot-extensions/inbound/ac-image-see.mjs +1 -1
- package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
- package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
- package/dshqqbot/.qqbot-extensions/lib/.pet-form.json +1 -1
- package/dshqqbot/.qqbot-extensions/lib/draw-core.mjs +238 -7
- package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -394
- package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
- package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
- package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
- package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
- package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
- package/dshqqbot/.qqbot-extensions/lib/plugin-dir.mjs +14 -4
- package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
- package/dshqqbot/.qqbot-extensions/lib/vision.mjs +1 -1
- package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
- package/dshqqbot/.qqbot-extensions/outbound/ac-media-fix.mjs +5 -1
- package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
- package/dshqqbot/.qqbot-extensions/outbound/split-reply.mjs +18 -2
- package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
- package/dshqqbot/.qqbot-extensions/tools/draw.mjs +22 -1
- package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
- package/dshqqbot/.qqbot-extensions/tools/pet_card.mjs +3 -2
- package/dshqqbot/.qqbot-extensions/tools/storyboard.mjs +3 -1
- package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
- package/package.json +119 -111
- package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
- package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
- package/scripts/_add_maintenance_cfg.py +20 -0
- package/scripts/_bench_keeplease.sh +10 -0
- package/scripts/_dbg_purge.py +15 -0
- package/scripts/_elev.sh +6 -0
- package/scripts/_fix_all_admin.cmd +16 -0
- package/scripts/_livecheck-image.mjs +33 -0
- package/scripts/_livecheck-llm.mjs +34 -0
- package/scripts/_livecheck-tts.mjs +37 -0
- package/scripts/_patch_curve.py +88 -0
- package/scripts/_patch_fan_thermal.py +24 -0
- package/scripts/_tag_tmp.py +13 -0
- package/scripts/adb-broker-client.mjs +87 -0
- package/scripts/adb-broker.mjs +205 -0
- package/scripts/ai-mode.cmd +6 -0
- package/scripts/ai-mode.py +387 -0
- package/scripts/ai-toolkit.py +607 -0
- package/scripts/apply-fan-gpu45.py +51 -0
- package/scripts/bench-fans.py +515 -0
- package/scripts/bench-load-direct.py +63 -0
- package/scripts/boot-tasks-hidden.vbs +20 -0
- package/scripts/boot-tasks.cmd +277 -0
- package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
- package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
- package/scripts/chat-archive/build-sft-v4.py +566 -0
- package/scripts/chat-archive/build-sft.py +390 -0
- package/scripts/chat-archive/eval-sft.py +155 -0
- package/scripts/chat-archive/extract-memory.py +143 -0
- package/scripts/chat-archive/inventory.py +182 -0
- package/scripts/chat-archive/merge-sft.py +114 -0
- package/scripts/chat-archive/qce-pull.py +217 -0
- package/scripts/chat-archive/qqheader.py +110 -0
- package/scripts/chat-archive/qqkey2.py +113 -0
- package/scripts/chat-archive/qqprobe.py +153 -0
- package/scripts/chat-archive/screen-collect.py +163 -0
- package/scripts/chat-archive/sqlcipher_probe.py +444 -0
- package/scripts/comfy_gen.py +209 -0
- package/scripts/compose-video.py +168 -0
- package/scripts/dl_models.py +45 -0
- package/scripts/draw-now.cmd +18 -0
- package/scripts/dsh-instance-guard.mjs +20 -2
- package/scripts/elev-extra.cmd +25 -0
- package/scripts/episode.py +529 -0
- package/scripts/fan-curve.py +218 -0
- package/scripts/fan-guard.cmd +8 -0
- package/scripts/fan-mode.py +380 -0
- package/scripts/fan_manual_safe.py +33 -0
- package/scripts/fan_restore_manual.py +46 -0
- package/scripts/fc_curves.py +359 -0
- package/scripts/fix-fan-and-timers.cmd +39 -0
- package/scripts/fix_admin_all.py +94 -0
- package/scripts/flows.mjs +224 -0
- package/scripts/gateway.cmd +126 -0
- package/scripts/gen-image.py +420 -0
- package/scripts/gen-video.py +186 -0
- package/scripts/git-askpass.cmd +2 -2
- package/scripts/gpu-mode.py +195 -0
- package/scripts/hw-profile.py +175 -0
- package/scripts/install-schedule.cmd +37 -0
- package/scripts/install-watch.cmd +29 -0
- package/scripts/matte-cutout.py +106 -0
- package/scripts/media-enhance.py +402 -0
- package/scripts/memory-audit.py +581 -0
- package/scripts/migrate-scope.mjs +140 -139
- package/scripts/model-registry.py +519 -0
- package/scripts/openid-audit.mjs +219 -0
- package/scripts/pull-gguf.py +127 -0
- package/scripts/purge-standby.py +151 -0
- package/scripts/qq-connect-login.py +133 -0
- package/scripts/qq-ip-sync-hidden.vbs +5 -0
- package/scripts/qq-ip-sync.py +300 -0
- package/scripts/qq-login-once.cmd +20 -0
- package/scripts/qq-login-qr.py +72 -0
- package/scripts/qq-whitelist-fix.cmd +27 -0
- package/scripts/qq-whitelist-login.cmd +26 -0
- package/scripts/qq-whitelist.cmd +12 -0
- package/scripts/qq-whitelist.py +1452 -0
- package/scripts/quality-compare.py +134 -0
- package/scripts/release-all.mjs +636 -430
- package/scripts/release-check.mjs +244 -226
- package/scripts/resume-coder.cmd +38 -0
- package/scripts/secure-room/index.html +334 -0
- package/scripts/secure-room/server.py +582 -0
- package/scripts/security-check.mjs +164 -0
- package/scripts/selftest-local-llm.mjs +20 -0
- package/scripts/selftest-local-models.mjs +754 -0
- package/scripts/selftest-rotate-style.mjs +308 -0
- package/scripts/shutdown-s5-optional.cmd +21 -0
- package/scripts/sleep-2325.cmd +75 -0
- package/scripts/start-comfyui.cmd +5 -0
- package/scripts/start-strata.cmd +17 -0
- package/scripts/start-strata.vbs +11 -0
- package/scripts/start-watch-hidden.vbs +3 -0
- package/scripts/stickers/auto-tag.mjs +161 -0
- package/scripts/storage.mjs +236 -0
- package/scripts/sync-plugin-copies.mjs +98 -23
- package/scripts/tests/test-qq-whitelist.py +192 -0
- package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
- package/scripts/train/gguf-quantize.py +92 -0
- package/scripts/train/gguf-to-hf.py +112 -0
- package/scripts/train/merge-lora.py +51 -0
- package/scripts/train/probe-mirrors.sh +12 -0
- package/scripts/train/probe-mirrors2.sh +20 -0
- package/scripts/train/setup-wsl.sh +23 -0
- package/scripts/train/setup-wsl2.sh +25 -0
- package/scripts/train/setup-wsl3.sh +22 -0
- package/scripts/train/setup-wsl4.sh +22 -0
- package/scripts/train/train-lora.py +319 -0
- package/scripts/vram-free.py +104 -0
- package/scripts/wechat-full-pull.mjs +1 -1
- package/settings-host.js +1047 -12
|
@@ -42,13 +42,31 @@
|
|
|
42
42
|
* surface 是"模型视野",不是人类 transcript(surface.js:39-46 原文注释)。
|
|
43
43
|
* 被 shadow 的原消息**仍留在会话日志**,web 上照样能翻;只多出一行可折叠的
|
|
44
44
|
* 「上下文已压缩 · 约 N tokens」标记。**不存在"把历史从记录里删掉"的机制。**
|
|
45
|
+
*
|
|
46
|
+
* ── 2026-11-25 追加(提交 A:上下文预算 + 摘要压缩)──────────────────
|
|
47
|
+
* · 新增 `trimHistoryWithSummary(agent, opts)`:与下面同一个四事件内核,
|
|
48
|
+
* 只把常量替身文本换成调用方给的 `summaryText`;node0 保护 / seq 记账原样保留。
|
|
49
|
+
* · 新增 `maybeTrimByBudget(...)`:按 `ctxBudgetTokens` 估算上下文,
|
|
50
|
+
* 超了才压、压到 `ctxKeepRecent` 条以内;由 `ctxBudgetOn`(默认 false)门控。
|
|
51
|
+
* · 摘要落盘 `.qqbot/ctx-summary/<safeKey>-<sha1前8>.jsonl`,每会话留 3 条,
|
|
52
|
+
* 更早的进 `.arch.jsonl`(不删)。
|
|
53
|
+
* · 默认行为零变化:`trimHistoryForContextless` 仍然走 FIXED_SUMMARY_TEXT、默认关。
|
|
45
54
|
*/
|
|
46
|
-
import { randomUUID } from 'node:crypto';
|
|
47
|
-
import {
|
|
55
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
56
|
+
import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
57
|
+
import { join } from 'node:path';
|
|
58
|
+
import { traceContextless, describeStorePath } from './contextless-store.js';
|
|
59
|
+
import { dataRootOf } from '../gateway/data-root.js';
|
|
48
60
|
/** 参与"保留最近 N 条"计数的消息型事件(与 dsh 的 SurfaceEventType 对齐) */
|
|
49
61
|
const MESSAGE_TYPES = new Set(['user/message', 'assistant/message', 'system/message', 'developer/message']);
|
|
50
62
|
/** 替身文本(摘要器输出;web 的「上下文已压缩」折叠块显示它) */
|
|
51
63
|
const FIXED_SUMMARY_TEXT = '(更早的对话已按「无上下文模式」省略,仅保留最近若干条)';
|
|
64
|
+
/** 摘要提示词固定前缀(主人 2026-11-25 定):给 LLM 摘要器用,本地摘录也会带上这句口径 */
|
|
65
|
+
export const SUMMARY_PROMPT_PREFIX = '保留对人设/关系/承诺/称呼的判断;保留未完成事项';
|
|
66
|
+
/** 预算压缩时至少保留多少条消息(再压下去连"刚说的话"都没了) */
|
|
67
|
+
export const CTX_SUMMARY_MIN_KEEP = 4;
|
|
68
|
+
/** 每个会话在 ctx-summary/*.jsonl 里保留几条,更早的转 .arch.jsonl */
|
|
69
|
+
const CTX_SUMMARY_KEEP = 3;
|
|
52
70
|
/**
|
|
53
71
|
* 幂等标记(2026-09-27 修):记住每个 session **已压到哪个 seq**。
|
|
54
72
|
*
|
|
@@ -79,6 +97,43 @@ function roughTokens(value) {
|
|
|
79
97
|
return 0;
|
|
80
98
|
}
|
|
81
99
|
}
|
|
100
|
+
/** 中日韩 + 全角标点(这些按字符≈1/3 token 估) */
|
|
101
|
+
const CJK_RE = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uff00-\uffef]/g;
|
|
102
|
+
/**
|
|
103
|
+
* A 件的估算函数:中文按 chars/3,其余(ASCII/空白/符号)按 chars/4。
|
|
104
|
+
* 入参可以是字符串、消息对象或它们的数组。
|
|
105
|
+
*/
|
|
106
|
+
export function estimateTokens(value) {
|
|
107
|
+
try {
|
|
108
|
+
if (value === null || value === undefined)
|
|
109
|
+
return 0;
|
|
110
|
+
const text = typeof value === 'string' ? value : JSON.stringify(value);
|
|
111
|
+
if (!text)
|
|
112
|
+
return 0;
|
|
113
|
+
const cjk = (text.match(CJK_RE) || []).length;
|
|
114
|
+
const other = Math.max(0, text.length - cjk);
|
|
115
|
+
return Math.max(1, Math.ceil(cjk / 3 + other / 4));
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
return 0;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/** 一批消息的估算总和 */
|
|
122
|
+
export function estimateMessagesTokens(msgs) {
|
|
123
|
+
if (!Array.isArray(msgs))
|
|
124
|
+
return 0;
|
|
125
|
+
let n = 0;
|
|
126
|
+
for (const m of msgs)
|
|
127
|
+
n += estimateTokens(m);
|
|
128
|
+
return n;
|
|
129
|
+
}
|
|
130
|
+
/** 数值参数收敛(配置文件可能被手改成字符串/负数) */
|
|
131
|
+
function intOf(value, fallback, min, max) {
|
|
132
|
+
const n = Math.trunc(Number(value));
|
|
133
|
+
if (!Number.isFinite(n))
|
|
134
|
+
return fallback;
|
|
135
|
+
return Math.min(max, Math.max(min, n));
|
|
136
|
+
}
|
|
82
137
|
/** tool 相关事件(回退边界用,避免切断 tool-call/tool-result 配对) */
|
|
83
138
|
function isToolish(ev) {
|
|
84
139
|
const t = String(ev?.type ?? '');
|
|
@@ -94,23 +149,204 @@ function messageOf(sess, seq) {
|
|
|
94
149
|
catch { /* ignore */ }
|
|
95
150
|
return ev;
|
|
96
151
|
}
|
|
152
|
+
/** 把消息体里的文字部分抽出来(摘要/估价都要) */
|
|
153
|
+
function textOfMessage(x) {
|
|
154
|
+
try {
|
|
155
|
+
if (x === null || x === undefined)
|
|
156
|
+
return '';
|
|
157
|
+
if (typeof x === 'string')
|
|
158
|
+
return x;
|
|
159
|
+
const content = x.content;
|
|
160
|
+
if (Array.isArray(content)) {
|
|
161
|
+
const parts = [];
|
|
162
|
+
for (const p of content) {
|
|
163
|
+
if (p && (p.type === 'text' || typeof p.text === 'string'))
|
|
164
|
+
parts.push(String(p.text ?? ''));
|
|
165
|
+
}
|
|
166
|
+
return parts.join('\n').trim();
|
|
167
|
+
}
|
|
168
|
+
if (typeof x.text === 'string')
|
|
169
|
+
return x.text;
|
|
170
|
+
return '';
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
return '';
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/** 某个 surface 节点的可读文本(先 derive 再退回事件本身) */
|
|
177
|
+
function eventText(sess, seq) {
|
|
178
|
+
const ev = sess?.eventAt?.(seq);
|
|
179
|
+
if (!ev)
|
|
180
|
+
return '';
|
|
181
|
+
let derived;
|
|
182
|
+
try {
|
|
183
|
+
if (typeof sess.deriveEventMessage === 'function')
|
|
184
|
+
derived = sess.deriveEventMessage(ev);
|
|
185
|
+
}
|
|
186
|
+
catch { /* ignore */ }
|
|
187
|
+
return textOfMessage(derived) || textOfMessage(ev.message) || textOfMessage(ev);
|
|
188
|
+
}
|
|
97
189
|
/**
|
|
98
|
-
*
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
* @param keepRecent 保留最近多少条消息(面板里的"带 @ 前 N 条";<=0 表示全清只留替身)
|
|
102
|
-
* @param logger 可选日志
|
|
103
|
-
* @param ctx 可选宿主上下文(用于拿 tokenMeter 估价)
|
|
104
|
-
* @returns 本次是否真的替换了
|
|
190
|
+
* 本地摘录式摘要(不调模型):把被丢掉的消息从后往前取,凑到 maxChars。
|
|
191
|
+
* 这是 QQ 侧默认的摘要来源 —— 这里没有微信那样的静默回合通道,
|
|
192
|
+
* 硬在 pre-step 里再唤起同一 agent 会死锁;要接模型就传 `llmSummarize`。
|
|
105
193
|
*/
|
|
106
|
-
export
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
194
|
+
export function buildExtractiveSummary(items, maxChars = 600) {
|
|
195
|
+
const limit = intOf(maxChars, 600, 80, 4000);
|
|
196
|
+
const lines = [];
|
|
197
|
+
for (const it of Array.isArray(items) ? items : []) {
|
|
198
|
+
const t = String(it?.text ?? '').replace(/\s+/g, ' ').trim();
|
|
199
|
+
if (!t)
|
|
200
|
+
continue;
|
|
201
|
+
// 注入块(历史/记忆/系统提示)不是"对话内容",别进摘要;旧占位文本也算注入块(别把占位当内容反复摘要)
|
|
202
|
+
if (/^\[(历史|记忆|系统|印象|约定|状态)/.test(t))
|
|
203
|
+
continue;
|
|
204
|
+
if (t === FIXED_SUMMARY_TEXT || /^(更早的对话/.test(t))
|
|
205
|
+
continue;
|
|
206
|
+
const tag = it?.role === 'assistant' ? '她' : '对方';
|
|
207
|
+
lines.push(tag + ':' + (t.length > 100 ? t.slice(0, 100) + '…' : t));
|
|
208
|
+
}
|
|
209
|
+
if (lines.length === 0)
|
|
210
|
+
return '';
|
|
211
|
+
const head = '(更早的对话已压缩,以下是要点)\n';
|
|
212
|
+
const room = Math.max(0, limit - head.length);
|
|
213
|
+
const picked = [];
|
|
214
|
+
let used = 0;
|
|
215
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
216
|
+
const line = lines[i];
|
|
217
|
+
if (used + line.length + 1 > room)
|
|
218
|
+
break;
|
|
219
|
+
picked.unshift(line);
|
|
220
|
+
used += line.length + 1;
|
|
221
|
+
}
|
|
222
|
+
if (picked.length === 0) {
|
|
223
|
+
// 单条就超长:至少留一条截断的
|
|
224
|
+
const one = lines[lines.length - 1].slice(0, room);
|
|
225
|
+
return one ? head + one : '';
|
|
226
|
+
}
|
|
227
|
+
return head + picked.join('\n');
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* 生成摘要文本:优先调用方注入的 LLM 摘要器,失败/没给就退回本地摘录;
|
|
231
|
+
* 本地也抽不出东西时回退 FIXED_SUMMARY_TEXT(保证四事件一定写得成)。
|
|
232
|
+
* @returns {{text:string, source:'llm'|'extractive'|'fixed'}}
|
|
233
|
+
*/
|
|
234
|
+
export async function summarizeDropped(items, opts = {}) {
|
|
235
|
+
const maxChars = intOf(opts.maxChars ?? 600, 600, 80, 4000);
|
|
236
|
+
const llm = opts.llmSummarize;
|
|
237
|
+
if (typeof llm === 'function') {
|
|
238
|
+
try {
|
|
239
|
+
const raw = await llm({
|
|
240
|
+
messages: items,
|
|
241
|
+
maxChars,
|
|
242
|
+
promptPrefix: SUMMARY_PROMPT_PREFIX,
|
|
243
|
+
});
|
|
244
|
+
const text = String(raw ?? '').trim();
|
|
245
|
+
if (text)
|
|
246
|
+
return { text: text.length > maxChars ? text.slice(0, maxChars) : text, source: 'llm' };
|
|
247
|
+
}
|
|
248
|
+
catch (err) {
|
|
249
|
+
traceContextless('摘要器失败,回退: ' + (err instanceof Error ? err.message : String(err)));
|
|
250
|
+
}
|
|
251
|
+
// 2026-11-25 修:模型摘要失败/为空时先退**抽取式**(比 FIXED 那句占位有信息量),
|
|
252
|
+
// 抽取也抽不出东西才回 FIXED(保证四事件一定写得成)。
|
|
253
|
+
const exLlm = buildExtractiveSummary(items, maxChars);
|
|
254
|
+
if (exLlm)
|
|
255
|
+
return { text: exLlm, source: 'extractive' };
|
|
256
|
+
return { text: FIXED_SUMMARY_TEXT, source: 'fixed' };
|
|
257
|
+
}
|
|
258
|
+
const ex = buildExtractiveSummary(items, maxChars);
|
|
259
|
+
if (ex)
|
|
260
|
+
return { text: ex, source: 'extractive' };
|
|
261
|
+
return { text: FIXED_SUMMARY_TEXT, source: 'fixed' };
|
|
262
|
+
}
|
|
263
|
+
/** 插件数据根:config.dataRoot → 从 contextless-store 反推 → `{cwd}/dshqqbot`
|
|
264
|
+
* 2026-12-01:最后两步统一交给 gateway/data-root.js(它带「空数据根 → 仓库真实数据根」回退),
|
|
265
|
+
* 否则 DSH 换 profile 后 cwd 变了,这里会把 ctx-summary 写到 profiles/desktop/dshqqbot 的幽灵目录。 */
|
|
266
|
+
export function resolveDataRoot(config) {
|
|
267
|
+
const direct = String(config?.dataRoot ?? '').trim();
|
|
268
|
+
if (direct)
|
|
269
|
+
return direct;
|
|
270
|
+
try {
|
|
271
|
+
const p = describeStorePath();
|
|
272
|
+
const m = /^(.*)[\\/]\.qqbot[\\/][^\\/]+$/.exec(String(p ?? ''));
|
|
273
|
+
if (m && m[1])
|
|
274
|
+
return m[1];
|
|
275
|
+
}
|
|
276
|
+
catch { /* ignore */ }
|
|
277
|
+
try {
|
|
278
|
+
return dataRootOf({ cwd: config?.cwd });
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
const cwd = String(config?.cwd ?? '').trim();
|
|
282
|
+
if (cwd)
|
|
283
|
+
return join(cwd, 'dshqqbot');
|
|
284
|
+
try {
|
|
285
|
+
return process.cwd();
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
return '.';
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
/** 会话 key → 文件名安全串 + sha1 前 8 位(同名不同群不会撞) */
|
|
293
|
+
export function ctxSummaryKeyOf(sessionKey) {
|
|
294
|
+
const raw = String(sessionKey || 'unknown');
|
|
295
|
+
const safe = raw.replace(/[^a-zA-Z0-9._-]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 48) || 'session';
|
|
296
|
+
const hash = createHash('sha1').update(raw).digest('hex').slice(0, 8);
|
|
297
|
+
return safe + '-' + hash;
|
|
298
|
+
}
|
|
299
|
+
/** 只保留最近 CTX_SUMMARY_KEEP 条,更早的追加到 *.arch.jsonl(不丢) */
|
|
300
|
+
function rotateSummaryFile(file) {
|
|
301
|
+
try {
|
|
302
|
+
const rows = readFileSync(file, 'utf8').split('\n').filter((l) => l.trim() !== '');
|
|
303
|
+
if (rows.length <= CTX_SUMMARY_KEEP)
|
|
304
|
+
return;
|
|
305
|
+
const keep = rows.slice(-CTX_SUMMARY_KEEP);
|
|
306
|
+
const older = rows.slice(0, -CTX_SUMMARY_KEEP);
|
|
307
|
+
appendFileSync(file.replace(/\.jsonl$/, '.arch.jsonl'), older.join('\n') + '\n', 'utf8');
|
|
308
|
+
writeFileSync(file, keep.join('\n') + '\n', 'utf8');
|
|
309
|
+
}
|
|
310
|
+
catch { /* 归档失败不影响主流程 */ }
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* 摘要落盘:一行一条,`{v:1,at,turnFrom,turnTo,fromSeq,toSeq,text,tokens,dropped}`。
|
|
314
|
+
* 失败一律吞掉 —— 记录摘要是为了排查,不能反过来打断聊天。
|
|
315
|
+
*/
|
|
316
|
+
export function appendCtxSummary({ dataRoot, sessionKey, at, turnFrom, turnTo, fromSeq, toSeq, text, tokens, dropped } = {}) {
|
|
317
|
+
try {
|
|
318
|
+
const root = String(dataRoot ?? '').trim() || resolveDataRoot(undefined);
|
|
319
|
+
const dir = join(root, '.qqbot', 'ctx-summary');
|
|
320
|
+
mkdirSync(dir, { recursive: true });
|
|
321
|
+
const file = join(dir, ctxSummaryKeyOf(sessionKey) + '.jsonl');
|
|
322
|
+
const row = {
|
|
323
|
+
v: 1,
|
|
324
|
+
at: String(at ?? new Date().toISOString()),
|
|
325
|
+
turnFrom: typeof turnFrom === 'number' ? turnFrom : null,
|
|
326
|
+
turnTo: typeof turnTo === 'number' ? turnTo : null,
|
|
327
|
+
fromSeq: typeof fromSeq === 'number' ? fromSeq : null,
|
|
328
|
+
toSeq: typeof toSeq === 'number' ? toSeq : null,
|
|
329
|
+
text: String(text ?? ''),
|
|
330
|
+
tokens: Number.isFinite(Number(tokens)) ? Number(tokens) : 0,
|
|
331
|
+
dropped: Array.isArray(dropped) ? dropped.filter((s) => typeof s === 'number') : [],
|
|
332
|
+
};
|
|
333
|
+
appendFileSync(file, JSON.stringify(row) + '\n', 'utf8');
|
|
334
|
+
rotateSummaryFile(file);
|
|
335
|
+
return true;
|
|
336
|
+
}
|
|
337
|
+
catch (err) {
|
|
338
|
+
traceContextless('写 ctx-summary 失败(已忽略): ' + (err instanceof Error ? err.message : String(err)));
|
|
339
|
+
return false;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* 四事件内核:把「最近 keepRecent 条消息」之前的历史整段替换成 summaryText。
|
|
344
|
+
* @returns {{ok:boolean, reason?:string, fromSeq?:number, toSeq?:number, seqs?:number[], tokens?:number}}
|
|
345
|
+
*/
|
|
346
|
+
async function trimSurface(agent, keepRecent, summaryText, logger, ctx, turn) {
|
|
112
347
|
const sess = agent?.session;
|
|
113
|
-
|
|
348
|
+
const replText = String(summaryText ?? '').trim() || FIXED_SUMMARY_TEXT;
|
|
349
|
+
traceContextless('trim 被调用: keep=' + keepRecent + ' turn=' + String(turn) + ' agent=' + (agent ? 'yes' : 'no') + ' session=' + (sess ? 'yes' : 'no') + ' summaryLen=' + replText.length);
|
|
114
350
|
let started = false; // 是否已 append compaction/start(失败时要补 end)
|
|
115
351
|
let compactionId = '';
|
|
116
352
|
const log = logger ?? ctx?.logger;
|
|
@@ -119,12 +355,12 @@ turn) {
|
|
|
119
355
|
if (!Array.isArray(nodes) || nodes.length === 0) {
|
|
120
356
|
log?.debug?.('[contextless] 跳过: 会话无 surface.nodes');
|
|
121
357
|
traceContextless('跳过: 无 surface.nodes');
|
|
122
|
-
return false;
|
|
358
|
+
return { ok: false, reason: 'no-nodes' };
|
|
123
359
|
}
|
|
124
360
|
if (typeof sess?.eventAt !== 'function' || typeof sess?.append !== 'function') {
|
|
125
361
|
log?.debug?.('[contextless] 跳过: session 缺 eventAt/append');
|
|
126
362
|
traceContextless('跳过: 缺 eventAt/append');
|
|
127
|
-
return false;
|
|
363
|
+
return { ok: false, reason: 'no-session-api' };
|
|
128
364
|
}
|
|
129
365
|
const keep = Math.max(0, Math.trunc(Number(keepRecent)) || 0);
|
|
130
366
|
// ① node0 若是 system/message 则永不纳入范围(surface.js:388 的保护)
|
|
@@ -149,7 +385,7 @@ turn) {
|
|
|
149
385
|
if (nodes.length <= firstIdx + 1) {
|
|
150
386
|
log?.debug?.('[contextless] 跳过: 节点数不足(' + nodes.length + ')');
|
|
151
387
|
traceContextless('跳过: 节点数不足 ' + nodes.length);
|
|
152
|
-
return false;
|
|
388
|
+
return { ok: false, reason: 'too-few-nodes' };
|
|
153
389
|
}
|
|
154
390
|
keepIdxInNodes = nodes.length; // 全清(只留替身)
|
|
155
391
|
}
|
|
@@ -166,11 +402,11 @@ turn) {
|
|
|
166
402
|
if (msgIdx.length <= keep + 1) {
|
|
167
403
|
log?.debug?.('[contextless] 跳过: 消息数 ' + msgIdx.length + ' <= 保留 ' + keep + '+1');
|
|
168
404
|
traceContextless('跳过: 消息数 ' + msgIdx.length + ' <= 保留 ' + keep + '+1');
|
|
169
|
-
return false;
|
|
405
|
+
return { ok: false, reason: 'too-few-messages' };
|
|
170
406
|
}
|
|
171
407
|
const keepFromRaw = msgIdx[msgIdx.length - keep];
|
|
172
408
|
if (keepFromRaw === undefined)
|
|
173
|
-
return false;
|
|
409
|
+
return { ok: false, reason: 'no-keep-index' };
|
|
174
410
|
keepIdxInNodes = keepFromRaw;
|
|
175
411
|
}
|
|
176
412
|
// ③ 回退到 tool 配对平衡的边界(surface 层不查,但 provider 会因孤立 tool 调用报错)
|
|
@@ -183,23 +419,23 @@ turn) {
|
|
|
183
419
|
if (keepIdxInNodes <= firstIdx) {
|
|
184
420
|
log?.debug?.('[contextless] 跳过: 保留段起点已到头部');
|
|
185
421
|
traceContextless('跳过: 保留段起点已到头部');
|
|
186
|
-
return false;
|
|
422
|
+
return { ok: false, reason: 'head-boundary' };
|
|
187
423
|
}
|
|
188
424
|
const startRaw = nodes[firstIdx];
|
|
189
425
|
const endRaw = nodes[keepIdxInNodes - 1];
|
|
190
426
|
if (startRaw === undefined || endRaw === undefined)
|
|
191
|
-
return false;
|
|
427
|
+
return { ok: false, reason: 'no-range' };
|
|
192
428
|
const start = startRaw;
|
|
193
429
|
const end = endRaw;
|
|
194
430
|
const shadowedSeqs = nodes.slice(firstIdx, keepIdxInNodes);
|
|
195
431
|
if (shadowedSeqs.length === 0)
|
|
196
|
-
return false;
|
|
432
|
+
return { ok: false, reason: 'empty-shadow' };
|
|
197
433
|
// ③.5 双保险:同一 turn 只压一次
|
|
198
434
|
if (typeof turn === 'number') {
|
|
199
435
|
const prevTurn = lastTrimmedTurn.get(sess);
|
|
200
436
|
if (typeof prevTurn === 'number' && prevTurn === turn) {
|
|
201
437
|
traceContextless('跳过: 同一 turn(' + turn + ') 已压缩过');
|
|
202
|
-
return false;
|
|
438
|
+
return { ok: false, reason: 'same-turn' };
|
|
203
439
|
}
|
|
204
440
|
}
|
|
205
441
|
// ④ 幂等(按 seq):本次要压到的 end 不晚于"上次压到的"→ 说明没有新历史 → 跳过。
|
|
@@ -207,11 +443,11 @@ turn) {
|
|
|
207
443
|
const trimmedTo = lastTrimmedEndSeq.get(sess);
|
|
208
444
|
if (typeof trimmedTo === 'number' && end <= trimmedTo) {
|
|
209
445
|
traceContextless('跳过: 已压到 seq ' + trimmedTo + ',本次 end=' + end + ' 没有更新的历史');
|
|
210
|
-
return false;
|
|
446
|
+
return { ok: false, reason: 'idempotent' };
|
|
211
447
|
}
|
|
212
448
|
// ⑤ shadowedTokenCount = 固定启发式价之和(契约要求;用错价会让压力账本漂移)
|
|
213
449
|
// ⚠️ 2026-09-27 修:插件的 ctx 未必 inject 了 tokenMeter,直接访问会抛
|
|
214
|
-
// "cannot get property
|
|
450
|
+
// "cannot get property \\"tokenMeter\\" without inject"(实测把整轮清理打挂)。
|
|
215
451
|
// 所以整段包 try,拿不到就退回字符估算 —— 宁可价不准,也不能不干活。
|
|
216
452
|
let estimateFn;
|
|
217
453
|
try {
|
|
@@ -248,7 +484,7 @@ turn) {
|
|
|
248
484
|
// ⑦ ② 计费事件
|
|
249
485
|
const summaryEvent = sess.append('compaction/summary', {
|
|
250
486
|
compactionId,
|
|
251
|
-
summary: [{ type: 'text', text:
|
|
487
|
+
summary: [{ type: 'text', text: replText }],
|
|
252
488
|
shadowedRange: { start, end },
|
|
253
489
|
shadowedSeqs: [...shadowedSeqs],
|
|
254
490
|
shadowedTokenCount,
|
|
@@ -261,7 +497,7 @@ turn) {
|
|
|
261
497
|
sess.append('user/message', {
|
|
262
498
|
id: newId(),
|
|
263
499
|
role: 'user',
|
|
264
|
-
content: [{ type: 'text', text:
|
|
500
|
+
content: [{ type: 'text', text: replText }],
|
|
265
501
|
source: { kind: 'compact-checkpoint', compactionId },
|
|
266
502
|
}, {
|
|
267
503
|
surfaceOp: { op: 'replace', startSeq: start, endSeq: end },
|
|
@@ -275,8 +511,9 @@ turn) {
|
|
|
275
511
|
lastTrimmedTurn.set(sess, turn);
|
|
276
512
|
traceContextless('✅ 成功: 替换 seq ' + start + '..' + end + '(' + shadowedSeqs.length + ' 节点 / ' + shadowedTokenCount + ' tokens),保留 ' + keep);
|
|
277
513
|
log?.info?.('[contextless] 已省略历史: 替换 seq ' + start + '..' + end
|
|
278
|
-
+ '(' + shadowedSeqs.length + ' 个节点 / 约 ' + shadowedTokenCount + ' tokens)→ 保留最近 ' + keep + ' 条消息'
|
|
279
|
-
|
|
514
|
+
+ '(' + shadowedSeqs.length + ' 个节点 / 约 ' + shadowedTokenCount + ' tokens)→ 保留最近 ' + keep + ' 条消息'
|
|
515
|
+
+ ';替身 ' + replText.length + ' 字');
|
|
516
|
+
return { ok: true, fromSeq: start, toSeq: end, seqs: [...shadowedSeqs], tokens: shadowedTokenCount, keep };
|
|
280
517
|
}
|
|
281
518
|
catch (err) {
|
|
282
519
|
// 失败必须补一条 compaction/end(带 error),否则该会话后续压缩会被 compaction-basic 判 busy 挡死
|
|
@@ -286,9 +523,193 @@ turn) {
|
|
|
286
523
|
}
|
|
287
524
|
catch { /* ignore */ }
|
|
288
525
|
}
|
|
289
|
-
traceContextless('❌ 失败: ' + (err instanceof Error ? (err.message + '
|
|
526
|
+
traceContextless('❌ 失败: ' + (err instanceof Error ? (err.message + '\\n' + (err.stack ?? '')) : String(err)));
|
|
290
527
|
log?.debug?.('[contextless] 省略历史失败(已忽略): ' + (err instanceof Error ? err.message : String(err)));
|
|
291
|
-
return false;
|
|
528
|
+
return { ok: false, reason: 'exception', error: err instanceof Error ? err.message : String(err) };
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* 把「最近 keepRecent 条消息」之前的历史整段替换成一句固定文本(四事件协议)。
|
|
533
|
+
*
|
|
534
|
+
* @param agent 目标 agent(取 agent.session)
|
|
535
|
+
* @param keepRecent 保留最近多少条消息(面板里的"带 @ 前 N 条";<=0 表示全清只留替身)
|
|
536
|
+
* @param logger 可选日志
|
|
537
|
+
* @param ctx 可选宿主上下文(用于拿 tokenMeter 估价)
|
|
538
|
+
* @param turn 当前打开的轮次号(来自 agent/pre-step 的 payload.turn)。
|
|
539
|
+
* ⚠️ 绝不能传 undefined/null:我们在 pre-step 里执行,回合是开着的,
|
|
540
|
+
* 而 compaction/start、compaction/end 的 turn 必须与"开着的那个 turn"一致,
|
|
541
|
+
* 否则会话日志会以 SessionFormatError 写坏(实测把两个群的会话都写崩了)。
|
|
542
|
+
* @returns 本次是否真的替换了
|
|
543
|
+
*/
|
|
544
|
+
export async function trimHistoryForContextless(agent, keepRecent, logger, ctx, turn) {
|
|
545
|
+
const r = await trimSurface(agent, keepRecent, FIXED_SUMMARY_TEXT, logger, ctx, turn);
|
|
546
|
+
return r.ok === true;
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* 【提交 A】同一条四事件内核,但替身文本由调用方给定(摘要压缩用)。
|
|
550
|
+
*
|
|
551
|
+
* opts: { keepRecent, summaryText, turn, logger, ctx, key, dataRoot, config, turnFrom, persist }
|
|
552
|
+
* · keepRecent 不给时按 ctxKeepRecent(默认 12)
|
|
553
|
+
* · summaryText 为空时退回 FIXED_SUMMARY_TEXT(默认行为不变)
|
|
554
|
+
* · persist !== false 时把摘要落盘到 .qqbot/ctx-summary/
|
|
555
|
+
* @returns {{ok:boolean, reason?:string, fromSeq?:number, toSeq?:number, seqs?:number[], tokens?:number}}
|
|
556
|
+
*/
|
|
557
|
+
export async function trimHistoryWithSummary(agent, opts = {}) {
|
|
558
|
+
const keepRecent = Number.isFinite(Number(opts.keepRecent))
|
|
559
|
+
? Math.max(0, Math.trunc(Number(opts.keepRecent)))
|
|
560
|
+
: intOf(opts.config?.ctxKeepRecent ?? 12, 12, 0, 500);
|
|
561
|
+
const summaryText = String(opts.summaryText ?? '').trim();
|
|
562
|
+
const r = await trimSurface(agent, keepRecent, summaryText || FIXED_SUMMARY_TEXT, opts.logger, opts.ctx, opts.turn);
|
|
563
|
+
if (r.ok && opts.persist !== false) {
|
|
564
|
+
appendCtxSummary({
|
|
565
|
+
dataRoot: opts.dataRoot ?? resolveDataRoot(opts.config),
|
|
566
|
+
sessionKey: opts.key ?? agent?.session?.id ?? 'unknown',
|
|
567
|
+
turnFrom: typeof opts.turnFrom === 'number' ? opts.turnFrom : opts.turn,
|
|
568
|
+
turnTo: typeof opts.turn === 'number' ? opts.turn : opts.turnTo,
|
|
569
|
+
fromSeq: r.fromSeq,
|
|
570
|
+
toSeq: r.toSeq,
|
|
571
|
+
text: summaryText || FIXED_SUMMARY_TEXT,
|
|
572
|
+
tokens: r.tokens,
|
|
573
|
+
dropped: Array.isArray(opts.droppedSeqs) ? opts.droppedSeqs : r.seqs,
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
return r;
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* 【提交 A】按预算决定要不要压:估算超 ctxBudgetTokens 才动,压到 ctxKeepRecent 条以内。
|
|
580
|
+
* 由 session-manager 的 pre-step 钩子调用,且**只在该会话没开无上下文模式时**跑
|
|
581
|
+
* (两条路都压会互相踩),外面还有 `ctxBudgetOn` 门控。
|
|
582
|
+
*/
|
|
583
|
+
export async function maybeTrimByBudget({ agent, key, config, logger, ctx, turn, dataRoot, llmSummarize } = {}) {
|
|
584
|
+
const sess = agent?.session;
|
|
585
|
+
const budget = intOf(config?.ctxBudgetTokens ?? 12000, 12000, 500, 10000000);
|
|
586
|
+
const keepWanted = intOf(config?.ctxKeepRecent ?? 12, 12, 0, 500);
|
|
587
|
+
const maxChars = intOf(config?.ctxSummaryMaxChars ?? 600, 600, 80, 4000);
|
|
588
|
+
const nodes = sess?.surface?.nodes;
|
|
589
|
+
if (!Array.isArray(nodes) || nodes.length < 3)
|
|
590
|
+
return { trimmed: false, reason: 'no-nodes' };
|
|
591
|
+
// 收集 surface 上的对话消息(跳过 node0;tool 事件不参与摘要,但仍算进 token 总量)
|
|
592
|
+
const msgs = [];
|
|
593
|
+
let total = 0;
|
|
594
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
595
|
+
const seq = nodes[i];
|
|
596
|
+
const ev = seq === undefined ? undefined : sess.eventAt?.(seq);
|
|
597
|
+
if (!ev)
|
|
598
|
+
continue;
|
|
599
|
+
const isMsg = MESSAGE_TYPES.has(String(ev.type)) && i > 0;
|
|
600
|
+
const text = isMsg ? eventText(sess, seq) : '';
|
|
601
|
+
const tokens = isMsg ? estimateTokens(text) : estimateTokens(messageOf(sess, seq));
|
|
602
|
+
total += tokens;
|
|
603
|
+
if (isMsg)
|
|
604
|
+
msgs.push({ seq, role: String(ev.type).startsWith('assistant') ? 'assistant' : 'user', text, tokens });
|
|
605
|
+
}
|
|
606
|
+
if (total <= budget) {
|
|
607
|
+
traceContextless('[ctxbudget] 未超预算: ' + total + ' <= ' + budget);
|
|
608
|
+
return { trimmed: false, reason: 'under-budget', tokens: total };
|
|
609
|
+
}
|
|
610
|
+
// 保留条数:先按 ctxKeepRecent,仍超预算就一条条减(保底 CTX_SUMMARY_MIN_KEEP)
|
|
611
|
+
let keep = Math.min(keepWanted, Math.max(0, msgs.length - 2));
|
|
612
|
+
const keptTokens = () => {
|
|
613
|
+
let n = 0;
|
|
614
|
+
for (const m of msgs.slice(msgs.length - keep))
|
|
615
|
+
n += m.tokens;
|
|
616
|
+
return n;
|
|
617
|
+
};
|
|
618
|
+
while (keep > CTX_SUMMARY_MIN_KEEP && keptTokens() > budget)
|
|
619
|
+
keep -= 1;
|
|
620
|
+
if (keep >= msgs.length - 1)
|
|
621
|
+
return { trimmed: false, reason: 'keep-too-large', tokens: total };
|
|
622
|
+
const droppedMsgs = msgs.slice(0, msgs.length - keep);
|
|
623
|
+
const summary = await summarizeDropped(droppedMsgs, { maxChars, llmSummarize });
|
|
624
|
+
const r = await trimHistoryWithSummary(agent, {
|
|
625
|
+
keepRecent: keep,
|
|
626
|
+
summaryText: summary.text,
|
|
627
|
+
turn,
|
|
628
|
+
turnFrom: turn,
|
|
629
|
+
logger,
|
|
630
|
+
ctx,
|
|
631
|
+
key,
|
|
632
|
+
config,
|
|
633
|
+
dataRoot: dataRoot ?? resolveDataRoot(config),
|
|
634
|
+
droppedSeqs: droppedMsgs.map((m) => m.seq),
|
|
635
|
+
});
|
|
636
|
+
if (!r.ok) {
|
|
637
|
+
traceContextless('[ctxbudget] 压缩未生效: ' + String(r.reason));
|
|
638
|
+
return { trimmed: false, reason: r.reason ?? 'trim-failed', tokens: total, summarySource: summary.source };
|
|
639
|
+
}
|
|
640
|
+
logger?.info?.('[ctxbudget] 已按预算压缩: ' + total + ' → 约 ' + keptTokens() + ' tokens'
|
|
641
|
+
+ '(丢 ' + droppedMsgs.length + ' 条,摘要来源=' + summary.source + ',保留 ' + keep + ' 条)');
|
|
642
|
+
return {
|
|
643
|
+
trimmed: true,
|
|
644
|
+
reason: 'trimmed',
|
|
645
|
+
tokensBefore: total,
|
|
646
|
+
tokensAfter: keptTokens(),
|
|
647
|
+
keep,
|
|
648
|
+
dropped: droppedMsgs.length,
|
|
649
|
+
summarySource: summary.source,
|
|
650
|
+
kept: r,
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* 【提交 B 用】一套骨架:把一个 agent 的 surface 摊平成 [{seq, role, text, tokens}]。
|
|
655
|
+
* 口径与 maybeTrimByBudget 完全一致(跳过 node0;tool 等非消息节点只计 token 不进文本)。
|
|
656
|
+
*/
|
|
657
|
+
function flattenSession(agent) {
|
|
658
|
+
const sess = agent?.session;
|
|
659
|
+
const nodes = sess?.surface?.nodes;
|
|
660
|
+
const out = [];
|
|
661
|
+
if (!Array.isArray(nodes))
|
|
662
|
+
return out;
|
|
663
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
664
|
+
const seq = nodes[i];
|
|
665
|
+
const ev = seq === undefined ? undefined : sess.eventAt?.(seq);
|
|
666
|
+
if (!ev)
|
|
667
|
+
continue;
|
|
668
|
+
const isMsg = MESSAGE_TYPES.has(String(ev.type)) && i > 0;
|
|
669
|
+
const role = String(ev.type).startsWith('assistant') ? 'assistant' : 'user';
|
|
670
|
+
const text = isMsg ? eventText(sess, seq) : '';
|
|
671
|
+
out.push({
|
|
672
|
+
seq,
|
|
673
|
+
role,
|
|
674
|
+
text,
|
|
675
|
+
tokens: isMsg ? estimateTokens(text) : estimateTokens(messageOf(sess, seq)),
|
|
676
|
+
isMsg,
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
return out;
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* 【提交 B 用】粗估一个会话的上下文 tokens(中文按 字/3)。会话读不到就返回 0。
|
|
683
|
+
*/
|
|
684
|
+
export function estimateAgentTokens(agent) {
|
|
685
|
+
try {
|
|
686
|
+
return flattenSession(agent).reduce((n, it) => n + it.tokens, 0);
|
|
687
|
+
}
|
|
688
|
+
catch {
|
|
689
|
+
return 0;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* 【提交 B 用】最近 limit 条真实对话(跳过 node0 与注入块),按时间正序返回。
|
|
694
|
+
* 轮换时拿它做摘要素材 / 「## 最近 N 条原文」。
|
|
695
|
+
*/
|
|
696
|
+
export function recentMessagesOf(agent, limit = 6) {
|
|
697
|
+
const max = intOf(limit, 6, 1, 60);
|
|
698
|
+
try {
|
|
699
|
+
const msgs = flattenSession(agent).filter((it) => {
|
|
700
|
+
if (!it.isMsg || !it.text)
|
|
701
|
+
return false;
|
|
702
|
+
// 注入块(历史/记忆/系统提示)不是"对话内容"
|
|
703
|
+
if (/^\[(历史|记忆|系统|印象|约定|状态)/.test(it.text))
|
|
704
|
+
return false;
|
|
705
|
+
if (it.text === FIXED_SUMMARY_TEXT || /^(更早的对话/.test(it.text))
|
|
706
|
+
return false;
|
|
707
|
+
return true;
|
|
708
|
+
});
|
|
709
|
+
return msgs.slice(-max);
|
|
710
|
+
}
|
|
711
|
+
catch {
|
|
712
|
+
return [];
|
|
292
713
|
}
|
|
293
714
|
}
|
|
294
715
|
/**
|
|
@@ -301,4 +722,4 @@ export function scheduleContextlessTrim(agent, keepRecent, logger, ctx) {
|
|
|
301
722
|
: Promise.resolve();
|
|
302
723
|
void wait.then(() => trimHistoryForContextless(agent, keepRecent, logger, ctx)).catch(() => undefined);
|
|
303
724
|
}
|
|
304
|
-
//# sourceMappingURL=contextless-trim.js.map
|
|
725
|
+
//# sourceMappingURL=contextless-trim.js.map
|