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
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rotate-summarizer.js — 真调模型写「会话换档/预算压缩摘要」(2026-11-25 重写,任务 B)
|
|
3
|
+
*
|
|
4
|
+
* 两种协议都支持:
|
|
5
|
+
* · ollama 原生:POST {base}/api/generate
|
|
6
|
+
* · OpenAI 兼容:POST {base}/v1/chat/completions(本地 Strata / vLLM / llama.cpp / 云端都对)
|
|
7
|
+
* 协议判定:rotateSummaryProtocol = auto|ollama|openai;auto 时按 URL 猜
|
|
8
|
+
* (含 /v1 或 /chat/completions → openai;含 /api → ollama;127.0.0.1/localhost → ollama;其余 → openai)。
|
|
9
|
+
*
|
|
10
|
+
* 降级链(任务要求:云端 → 本地大模型 → 抽取式):
|
|
11
|
+
* ① 主端点(rotateSummaryUrl,云端/任意兼容端点,带 rotateSummaryApiKey)
|
|
12
|
+
* ② 本地 ollama(rotateSummaryLocalUrl,默认 127.0.0.1:11434),模型按**可用最大**自动挑
|
|
13
|
+
* ③ 返回 null → 调用方(session-rotate / contextless-trim)退回抽取式
|
|
14
|
+
* 每次尝试都打日志(logger.debug + traceContextless),成功时 info 一行 `[summarize] path=cloud model=… ms=… 字数=…`,
|
|
15
|
+
* 出问题能直接看出走了哪条路、卡在哪。
|
|
16
|
+
*
|
|
17
|
+
* 模型默认值:**不写死小模型名**。rotateSummaryModel 留空时,读 /api/tags(或 /v1/models),
|
|
18
|
+
* 按参数规模从大到小挑第一个能用的(跳过 embedding 模型);本地显存不够 ollama 会自己报错,再降级。
|
|
19
|
+
*/
|
|
20
|
+
import { traceContextless } from './contextless-store.js';
|
|
21
|
+
|
|
22
|
+
export const DEFAULT_OLLAMA_HOST = 'http://127.0.0.1:11434';
|
|
23
|
+
export const DEFAULT_SUMMARY_TIMEOUT_MS = 20000;
|
|
24
|
+
/** 本地兜底那次调用的最小预算(云端超时通常配得很短,本地 8B 冷启动就要好几秒) */
|
|
25
|
+
export const LOCAL_FALLBACK_TIMEOUT_MS = 90000;
|
|
26
|
+
/** 协议:auto 按 URL 猜 */
|
|
27
|
+
export const PROTOCOLS = ['auto', 'ollama', 'openai'];
|
|
28
|
+
/** 送进模型的原文上限(字),太长的会话只看最近这一段 */
|
|
29
|
+
const TRANSCRIPT_MAX_CHARS = 5000;
|
|
30
|
+
const PER_MSG_MAX_CHARS = 300;
|
|
31
|
+
/** 不该被选成摘要模型的(向量/重排模型不能生成) */
|
|
32
|
+
const NON_CHAT_RE = /(embed|embedding|bge-|gte-|e5-|rerank|clip|whisper|tts|stable-diffusion|sdxl)/i;
|
|
33
|
+
|
|
34
|
+
export const SUMMARY_SYSTEM_PROMPT = [
|
|
35
|
+
'你是一个聊天记录整理员。读下面这段聊天,写一段给对方(不是给模型)看的接续摘要。',
|
|
36
|
+
'必须包含三件事,能确定的才写,不确定的不许编:',
|
|
37
|
+
'1) 在聊什么:这几轮的具体话题/事件(带具体对象、时间、数字);',
|
|
38
|
+
'2) 用户稳定偏好:称呼、口味、作息、雷点这类会长期有效的;',
|
|
39
|
+
'3) 未完成的事:答应了要做但还没做的、约好但还没到的、对方还在等问题。',
|
|
40
|
+
'要求:一段话,不要标题、不要分点、不要「总结:」开头、不要复述整段对话;简洁、口语、可执行。',
|
|
41
|
+
].join('\n');
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 任务型会话专用(2026-11-25 任务 A.3):换档不能把「正在做的事」弄丢。
|
|
45
|
+
* 明确点名四类硬信息必须**原样**保留 —— 待办、文件路径、命令、报错原文。
|
|
46
|
+
*/
|
|
47
|
+
export const SUMMARY_SYSTEM_PROMPT_TASK = [
|
|
48
|
+
'你是一个工程任务的交接记录员。这段聊天是「正在做的事」,下一段会话要接着干,不能失忆。',
|
|
49
|
+
'按下面的顺序写,能确定的才写,不确定的不许编:',
|
|
50
|
+
'1) 目标:这几轮到底要达成什么(一句话,别写成流程);',
|
|
51
|
+
'2) 待办:谁要做什么、做到哪一步、还差什么 —— 逐条列,用「·」开头;',
|
|
52
|
+
'3) 文件与命令:涉及的文件路径、函数/配置名、跑过的命令,**原样抄**,不要改写或概括;',
|
|
53
|
+
'4) 报错原文:报错/异常/失败的关键行**逐字保留**(可以只留最关键的 1~2 行),别翻译成「有个错误」;',
|
|
54
|
+
'5) 未答复的问题 / 已答应但没做的事。',
|
|
55
|
+
'要求:宁可条目化,不要写成一段泛泛的总结;不要「总结:」开头;不要复述无关闲聊。',
|
|
56
|
+
].join('\n');
|
|
57
|
+
|
|
58
|
+
function clip(text, max) {
|
|
59
|
+
const t = String(text ?? '').replace(/\s+/g, ' ').trim();
|
|
60
|
+
if (!t)
|
|
61
|
+
return '';
|
|
62
|
+
return t.length > max ? t.slice(0, Math.max(1, max - 1)) + '…' : t;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function intOf(v, dflt, min, max) {
|
|
66
|
+
const n = Number(v);
|
|
67
|
+
if (!Number.isFinite(n))
|
|
68
|
+
return dflt;
|
|
69
|
+
return Math.min(max, Math.max(min, Math.round(n)));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function trimSlash(u) {
|
|
73
|
+
return String(u ?? '').trim().replace(/\/+$/, '');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** URL 里有没有「这条是本地」的特征 */
|
|
77
|
+
export function isLocalUrl(url) {
|
|
78
|
+
const u = String(url ?? '').toLowerCase();
|
|
79
|
+
return /(127\.0\.0\.1|localhost|0\.0\.0\.0|\[::1\]|192\.168\.|10\.\d+\.|172\.(1[6-9]|2\d|3[01])\.)/.test(u);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 判协议:显式配置优先,否则按 URL 猜(猜错也能靠降级链兜住) */
|
|
83
|
+
export function protocolOf(url, forced = 'auto') {
|
|
84
|
+
const f = String(forced ?? 'auto').trim().toLowerCase();
|
|
85
|
+
if (f === 'ollama' || f === 'openai')
|
|
86
|
+
return f;
|
|
87
|
+
const u = String(url ?? '').toLowerCase();
|
|
88
|
+
if (/\/chat\/completions/.test(u))
|
|
89
|
+
return 'openai';
|
|
90
|
+
if (/\/v1(\/|$)/.test(u))
|
|
91
|
+
return 'openai';
|
|
92
|
+
if (/\/api\//.test(u))
|
|
93
|
+
return 'ollama';
|
|
94
|
+
if (isLocalUrl(u))
|
|
95
|
+
return 'ollama';
|
|
96
|
+
return 'openai';
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 拼真实请求地址(允许用户直接把完整路径填进 rotateSummaryUrl) */
|
|
100
|
+
export function endpointOf(url, protocol) {
|
|
101
|
+
const base = trimSlash(url);
|
|
102
|
+
if (protocol === 'openai') {
|
|
103
|
+
if (/\/chat\/completions$/.test(base))
|
|
104
|
+
return base;
|
|
105
|
+
if (/\/v1$/.test(base))
|
|
106
|
+
return base + '/chat/completions';
|
|
107
|
+
return base + '/v1/chat/completions';
|
|
108
|
+
}
|
|
109
|
+
if (/\/api\/generate$/.test(base))
|
|
110
|
+
return base;
|
|
111
|
+
return base + '/api/generate';
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** 从模型名/参数字段里读参数规模(单位 B);读不到给 0 */
|
|
115
|
+
export function paramSizeOf(name, parameterSize) {
|
|
116
|
+
const d = String(parameterSize ?? '').trim();
|
|
117
|
+
const m0 = d.match(/(\d+(?:\.\d+)?)\s*[bB]/);
|
|
118
|
+
if (m0)
|
|
119
|
+
return Number(m0[1]);
|
|
120
|
+
const s = String(name ?? '');
|
|
121
|
+
const m = s.match(/(?:^|[:_\-.])(\d+(?:\.\d+)?)\s*[bB](?![a-zA-Z])/);
|
|
122
|
+
if (m)
|
|
123
|
+
return Number(m[1]);
|
|
124
|
+
if (/(^|[:_\-.])(tiny|small|mini)(?![a-z])/i.test(s))
|
|
125
|
+
return 1;
|
|
126
|
+
return 0;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 挑「能用的最大模型」。
|
|
131
|
+
* @param {Array<string|{name:string, params?:number, size?:number}>} models
|
|
132
|
+
* @returns {string} 模型名(没有可用返回空串)
|
|
133
|
+
*/
|
|
134
|
+
export function pickSummaryModel(models) {
|
|
135
|
+
const list = (Array.isArray(models) ? models : []).map((m) => {
|
|
136
|
+
if (typeof m === 'string')
|
|
137
|
+
return { name: m.trim(), params: paramSizeOf(m), size: 0 };
|
|
138
|
+
return {
|
|
139
|
+
name: String(m?.name ?? '').trim(),
|
|
140
|
+
params: Number.isFinite(Number(m?.params)) && Number(m?.params) > 0 ? Number(m.params) : paramSizeOf(m?.name),
|
|
141
|
+
size: Number(m?.size) || 0,
|
|
142
|
+
};
|
|
143
|
+
}).filter((m) => m.name && !NON_CHAT_RE.test(m.name));
|
|
144
|
+
if (list.length === 0)
|
|
145
|
+
return '';
|
|
146
|
+
list.sort((a, b) => (b.params - a.params) || (b.size - a.size) || a.name.localeCompare(b.name));
|
|
147
|
+
return list[0].name;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** 老接口保留:探 ollama 装了哪些模型名(带 30s 缓存) */
|
|
151
|
+
let _tagsCache = { at: 0, host: '', models: [] };
|
|
152
|
+
export async function listModelsDetailed(host = DEFAULT_OLLAMA_HOST, timeoutMs = 2000) {
|
|
153
|
+
const h = trimSlash(host || DEFAULT_OLLAMA_HOST);
|
|
154
|
+
const now = Date.now();
|
|
155
|
+
if (_tagsCache.host === h && now - _tagsCache.at < 30000)
|
|
156
|
+
return _tagsCache.models;
|
|
157
|
+
const ac = new AbortController();
|
|
158
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
159
|
+
try {
|
|
160
|
+
const res = await fetch(h + '/api/tags', { signal: ac.signal });
|
|
161
|
+
if (!res.ok)
|
|
162
|
+
throw new Error('HTTP ' + res.status);
|
|
163
|
+
const j = await res.json();
|
|
164
|
+
const models = (Array.isArray(j?.models) ? j.models : [])
|
|
165
|
+
.map((m) => ({
|
|
166
|
+
name: String(m?.name ?? '').trim(),
|
|
167
|
+
params: paramSizeOf(m?.name, m?.details?.parameter_size),
|
|
168
|
+
size: Number(m?.size) || 0,
|
|
169
|
+
}))
|
|
170
|
+
.filter((m) => m.name);
|
|
171
|
+
_tagsCache = { at: now, host: h, models };
|
|
172
|
+
return models;
|
|
173
|
+
}
|
|
174
|
+
catch (err) {
|
|
175
|
+
_tagsCache = { at: now, host: h, models: [] };
|
|
176
|
+
traceContextless('[summarize] ollama /api/tags 失败: ' + (err instanceof Error ? err.message : String(err)));
|
|
177
|
+
return [];
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
clearTimeout(timer);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** 兼容旧调用:只要名字数组 */
|
|
185
|
+
export async function availableModels(host = DEFAULT_OLLAMA_HOST, timeoutMs = 2000) {
|
|
186
|
+
const models = await listModelsDetailed(host, timeoutMs);
|
|
187
|
+
return models.map((m) => m.name);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** OpenAI 兼容端点列模型(有些服务没实现,失败就当没有) */
|
|
191
|
+
export async function listOpenAIModels(baseUrl, apiKey, timeoutMs = 2000) {
|
|
192
|
+
const base = trimSlash(baseUrl);
|
|
193
|
+
const ac = new AbortController();
|
|
194
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
195
|
+
try {
|
|
196
|
+
const headers = {};
|
|
197
|
+
if (apiKey)
|
|
198
|
+
headers.authorization = 'Bearer ' + apiKey;
|
|
199
|
+
const res = await fetch((/\/v1$/.test(base) ? base : base + '/v1') + '/models', { headers, signal: ac.signal });
|
|
200
|
+
if (!res.ok)
|
|
201
|
+
return [];
|
|
202
|
+
const j = await res.json();
|
|
203
|
+
const arr = Array.isArray(j?.data) ? j.data : (Array.isArray(j?.models) ? j.models : []);
|
|
204
|
+
return arr.map((m) => String(m?.id ?? m?.name ?? '').trim()).filter(Boolean);
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
return [];
|
|
208
|
+
}
|
|
209
|
+
finally {
|
|
210
|
+
clearTimeout(timer);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** 把消息数组拼成「对方:… / 她:…」的稿子,只留最近 TRANSCRIPT_MAX_CHARS 字 */
|
|
215
|
+
export function transcriptOf(messages) {
|
|
216
|
+
const list = Array.isArray(messages) ? messages : [];
|
|
217
|
+
const lines = [];
|
|
218
|
+
for (const m of list) {
|
|
219
|
+
const text = clip(m?.text ?? m?.content ?? '', PER_MSG_MAX_CHARS);
|
|
220
|
+
if (!text)
|
|
221
|
+
continue;
|
|
222
|
+
const who = String(m?.role ?? '') === 'assistant' ? '她' : '对方';
|
|
223
|
+
lines.push(who + ':' + text);
|
|
224
|
+
}
|
|
225
|
+
let body = lines.join('\n');
|
|
226
|
+
if (body.length > TRANSCRIPT_MAX_CHARS)
|
|
227
|
+
body = '…(更早的省略)\n' + body.slice(body.length - TRANSCRIPT_MAX_CHARS);
|
|
228
|
+
return body;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** 清洗模型输出:去 think 块、去「总结:」前缀、去包裹引号、压成一段 */
|
|
232
|
+
export function cleanSummary(raw) {
|
|
233
|
+
let t = String(raw ?? '');
|
|
234
|
+
// qwen3 的思考块(有的版本从 response 里吐,有的从 thinking 字段吐,这里两边都防)
|
|
235
|
+
t = t.replace(/<think[\s\S]*?<\/think>/gi, ' ');
|
|
236
|
+
t = t.replace(/<\/think>/gi, ' ');
|
|
237
|
+
t = t.replace(/^\s*(摘要|总结|要点|outline|summary)\s*[::]\s*/i, '');
|
|
238
|
+
t = t.replace(/^["'“”‘’]+|["'“”‘’]+$/g, '');
|
|
239
|
+
t = t.replace(/\r/g, '').replace(/\n+/g, ' ').replace(/[ \t]{2,}/g, ' ').trim();
|
|
240
|
+
// 小模型(qwen2.5 系)爱在汉字之间吐空格:「对 方 在 催 促」→「对方在催促」
|
|
241
|
+
t = t.replace(/([\u4e00-\u9fff])\s+(?=[\u4e00-\u9fff])/g, '$1');
|
|
242
|
+
t = t.replace(/([\u4e00-\u9fff])\s+(?=[,。、;:!?)」』”])/g, '$1');
|
|
243
|
+
t = t.replace(/([,。、;:!?(「『“])\s+/g, '$1');
|
|
244
|
+
t = t.replace(/\s+(?=[(「『“])/g, '');
|
|
245
|
+
t = t.replace(/(?<=[)」,。;:”’』])[ \t]+/g, '');
|
|
246
|
+
return t;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** 一次 ollama 原生调用 */
|
|
250
|
+
async function callOllama({ base, model, prompt, system, timeoutMs, keepAlive, numPredict }) {
|
|
251
|
+
const ac = new AbortController();
|
|
252
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
253
|
+
try {
|
|
254
|
+
const res = await fetch(endpointOf(base, 'ollama'), {
|
|
255
|
+
method: 'POST',
|
|
256
|
+
headers: { 'content-type': 'application/json' },
|
|
257
|
+
signal: ac.signal,
|
|
258
|
+
body: JSON.stringify({
|
|
259
|
+
model,
|
|
260
|
+
prompt,
|
|
261
|
+
system,
|
|
262
|
+
stream: false,
|
|
263
|
+
// qwen3 系默认会先吐一大段思考,思考 token 既算时间又可能把 num_predict 吃光 → 关掉
|
|
264
|
+
think: false,
|
|
265
|
+
keep_alive: keepAlive,
|
|
266
|
+
options: {
|
|
267
|
+
temperature: 0.2,
|
|
268
|
+
top_p: 0.8,
|
|
269
|
+
repeat_penalty: 1.05,
|
|
270
|
+
num_predict: numPredict,
|
|
271
|
+
num_ctx: 8192,
|
|
272
|
+
},
|
|
273
|
+
}),
|
|
274
|
+
});
|
|
275
|
+
if (!res.ok) {
|
|
276
|
+
const hint = res.status === 404 ? '模型不存在(需要 ollama pull ' + model + ')' : 'HTTP ' + res.status;
|
|
277
|
+
throw new Error(hint);
|
|
278
|
+
}
|
|
279
|
+
const j = await res.json();
|
|
280
|
+
return cleanSummary(j?.response ?? '');
|
|
281
|
+
}
|
|
282
|
+
finally {
|
|
283
|
+
clearTimeout(timer);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** 一次 OpenAI 兼容调用 */
|
|
288
|
+
async function callOpenAI({ base, model, prompt, system, timeoutMs, apiKey, numPredict }) {
|
|
289
|
+
const ac = new AbortController();
|
|
290
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
291
|
+
try {
|
|
292
|
+
const headers = { 'content-type': 'application/json' };
|
|
293
|
+
if (apiKey)
|
|
294
|
+
headers.authorization = 'Bearer ' + apiKey;
|
|
295
|
+
const res = await fetch(endpointOf(base, 'openai'), {
|
|
296
|
+
method: 'POST',
|
|
297
|
+
headers,
|
|
298
|
+
signal: ac.signal,
|
|
299
|
+
body: JSON.stringify({
|
|
300
|
+
model,
|
|
301
|
+
messages: [
|
|
302
|
+
{ role: 'system', content: system },
|
|
303
|
+
{ role: 'user', content: prompt },
|
|
304
|
+
],
|
|
305
|
+
temperature: 0.2,
|
|
306
|
+
top_p: 0.8,
|
|
307
|
+
max_tokens: numPredict,
|
|
308
|
+
stream: false,
|
|
309
|
+
// 部分推理端点认这个;不认的会忽略(不影响)
|
|
310
|
+
chat_template_kwargs: { enable_thinking: false },
|
|
311
|
+
}),
|
|
312
|
+
});
|
|
313
|
+
if (!res.ok) {
|
|
314
|
+
const hint = res.status === 404 ? '端点/模型不存在(HTTP 404)' : 'HTTP ' + res.status;
|
|
315
|
+
throw new Error(hint);
|
|
316
|
+
}
|
|
317
|
+
const j = await res.json();
|
|
318
|
+
const choice = Array.isArray(j?.choices) ? j.choices[0] : undefined;
|
|
319
|
+
const content = choice?.message?.content;
|
|
320
|
+
const text = Array.isArray(content)
|
|
321
|
+
? content.map((c) => (typeof c === 'string' ? c : c?.text ?? '')).join('')
|
|
322
|
+
: content;
|
|
323
|
+
return cleanSummary(text ?? j?.response ?? '');
|
|
324
|
+
}
|
|
325
|
+
finally {
|
|
326
|
+
clearTimeout(timer);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* 造一个摘要器:`async ({messages, promptPrefix, maxChars, mode}) => string|null`
|
|
332
|
+
* 成功返回一段(≤maxChars 附近,不强切,调用方自己会 clip);失败/超时返回 null(调用方退回抽取式)。
|
|
333
|
+
*/
|
|
334
|
+
export function makeSummarizer({ config, logger, host, model, timeoutMs, apiKey, protocol, localUrl } = {}) {
|
|
335
|
+
const cfg = config || {};
|
|
336
|
+
const primaryUrl = trimSlash(host ?? cfg.rotateSummaryUrl ?? '') || DEFAULT_OLLAMA_HOST;
|
|
337
|
+
const localHost = trimSlash(localUrl ?? cfg.rotateSummaryLocalUrl ?? '') || DEFAULT_OLLAMA_HOST;
|
|
338
|
+
const pinned = String(model ?? cfg.rotateSummaryModel ?? '').trim();
|
|
339
|
+
const key = String(apiKey ?? cfg.rotateSummaryApiKey ?? '').trim();
|
|
340
|
+
const proto = String(protocol ?? cfg.rotateSummaryProtocol ?? 'auto').trim().toLowerCase();
|
|
341
|
+
const budgetMs = intOf(timeoutMs ?? cfg.rotateSummaryTimeoutMs ?? DEFAULT_SUMMARY_TIMEOUT_MS, DEFAULT_SUMMARY_TIMEOUT_MS, 1000, 180000);
|
|
342
|
+
const keepAlive = String(cfg.rotateSummaryKeepAlive ?? '10m') || '10m';
|
|
343
|
+
let warned = '';
|
|
344
|
+
|
|
345
|
+
function attemptLog(msg) {
|
|
346
|
+
logger?.debug?.('[summarize] ' + msg);
|
|
347
|
+
traceContextless('[summarize] ' + msg);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** 跑一条路径:返回 {ok,text,model,ms,path,err} */
|
|
351
|
+
async function tryPath({ path, url, modelName, system, prompt, numPredict, useKey, budgetMs }) {
|
|
352
|
+
const p = protocolOf(url, proto);
|
|
353
|
+
const started = Date.now();
|
|
354
|
+
try {
|
|
355
|
+
let text = '';
|
|
356
|
+
if (p === 'openai') {
|
|
357
|
+
let m = modelName;
|
|
358
|
+
if (!m) {
|
|
359
|
+
const names = await listOpenAIModels(url, useKey);
|
|
360
|
+
m = pickSummaryModel(names);
|
|
361
|
+
}
|
|
362
|
+
if (!m)
|
|
363
|
+
throw new Error('没有可用模型(/v1/models 为空)');
|
|
364
|
+
text = await callOpenAI({ base: url, model: m, prompt, system, timeoutMs: budgetMs, apiKey: useKey, numPredict });
|
|
365
|
+
return finish(path, m, text, started);
|
|
366
|
+
}
|
|
367
|
+
let m = modelName;
|
|
368
|
+
if (!m) {
|
|
369
|
+
const models = await listModelsDetailed(url, 2000);
|
|
370
|
+
m = pickSummaryModel(models);
|
|
371
|
+
}
|
|
372
|
+
if (!m)
|
|
373
|
+
throw new Error('没有可用模型(/api/tags 为空)');
|
|
374
|
+
text = await callOllama({ base: url, model: m, prompt, system, timeoutMs: budgetMs, keepAlive, numPredict });
|
|
375
|
+
return finish(path, m, text, started);
|
|
376
|
+
}
|
|
377
|
+
catch (err) {
|
|
378
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
379
|
+
const friendly = /abort/i.test(msg) ? 'timeout(' + budgetMs + 'ms)' : msg;
|
|
380
|
+
return { ok: false, err: friendly, path, model: modelName, ms: Date.now() - started };
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function finish(path, m, text, started) {
|
|
385
|
+
const t = clip(text, 2000);
|
|
386
|
+
if (!t)
|
|
387
|
+
return { ok: false, err: '模型返回空', path, model: m, ms: Date.now() - started };
|
|
388
|
+
return { ok: true, text: t, path, model: m, ms: Date.now() - started };
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
return async function summarize({ messages, promptPrefix, maxChars, mode } = {}) {
|
|
392
|
+
const transcript = transcriptOf(messages);
|
|
393
|
+
if (!transcript)
|
|
394
|
+
return null;
|
|
395
|
+
const limit = intOf(maxChars ?? 160, 160, 40, 2000);
|
|
396
|
+
// 180 字的摘要在中文里 ≈ 180~260 token;给到 2 倍 + 余量
|
|
397
|
+
const numPredict = Math.min(1200, Math.max(160, Math.round(limit * 2)));
|
|
398
|
+
const isTask = String(mode ?? '') === 'task';
|
|
399
|
+
const system = isTask ? SUMMARY_SYSTEM_PROMPT_TASK : SUMMARY_SYSTEM_PROMPT;
|
|
400
|
+
const prompt = [
|
|
401
|
+
String(promptPrefix ?? '').trim(),
|
|
402
|
+
'字数上限:' + limit + ' 字。',
|
|
403
|
+
'',
|
|
404
|
+
'【聊天记录】',
|
|
405
|
+
transcript,
|
|
406
|
+
'',
|
|
407
|
+
'【摘要】',
|
|
408
|
+
].filter((s) => s !== undefined && s !== '').join('\n');
|
|
409
|
+
|
|
410
|
+
// ① 主端点(云端/自定义兼容端点)。本地 ollama 也走这里,模型留空=自动挑最大
|
|
411
|
+
const primaryIsLocal = isLocalUrl(primaryUrl);
|
|
412
|
+
const tryOrder = [{ path: primaryIsLocal ? 'local' : 'cloud', url: primaryUrl, modelName: pinned || '' }];
|
|
413
|
+
// ② 本地大模型兜底(主端点不是本地时才有意义)
|
|
414
|
+
if (trimSlash(primaryUrl) !== localHost)
|
|
415
|
+
tryOrder.push({ path: 'local', url: localHost, modelName: String(cfg.rotateSummaryLocalModel ?? '').trim() });
|
|
416
|
+
|
|
417
|
+
for (const t of tryOrder) {
|
|
418
|
+
// 本地兜底给独立预算:云端那 20s 的预算套到本地 8B 上经常直接超时
|
|
419
|
+
const isFallbackLocal = t.path === 'local' && trimSlash(t.url) !== trimSlash(primaryUrl);
|
|
420
|
+
const r = await tryPath({ ...t, system, prompt, numPredict, useKey: key, budgetMs: isFallbackLocal ? Math.max(budgetMs, LOCAL_FALLBACK_TIMEOUT_MS) : budgetMs });
|
|
421
|
+
if (r.ok) {
|
|
422
|
+
logger?.info?.('[summarize] path=' + r.path + ' model=' + r.model + ' ' + r.ms + 'ms ' + r.text.length + '字'
|
|
423
|
+
+ (isTask ? ' (task)' : ''));
|
|
424
|
+
traceContextless('[summarize] ok path=' + r.path + ' model=' + r.model + ' ms=' + r.ms + ' chars=' + r.text.length);
|
|
425
|
+
return clip(r.text, limit);
|
|
426
|
+
}
|
|
427
|
+
const line = r.path + ' 失败(' + (r.model || 'auto') + '): ' + r.err;
|
|
428
|
+
if (warned !== line) {
|
|
429
|
+
warned = line;
|
|
430
|
+
attemptLog(line + ' → 继续降级');
|
|
431
|
+
logger?.debug?.('[summarize] ' + line + ' → 继续降级');
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
attemptLog('全部路径失败 → 退回抽取式');
|
|
435
|
+
logger?.warn?.('[summarize] 全部路径失败(主端点=' + primaryUrl + ') → 本次改用抽取式摘要');
|
|
436
|
+
return null;
|
|
437
|
+
};
|
|
438
|
+
}
|