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,754 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * scripts/selftest-local-models.mjs
4
+ * 本地模型能力层自测(2026-11-25):纯 node、离线、不装依赖。
5
+ *
6
+ * 覆盖:
7
+ * 1) 总开关关着 → disabled(且**不去连后端**,用必然打不通的地址也能秒回)
8
+ * 2) 总开关开着、分开关关着 → disabled_capability
9
+ * 3) 参数错 → bad_arg(文件不存在)
10
+ * 4) 端点不可达 → endpoint_unreachable + 结构化字段
11
+ * 5) 超时逻辑 → timeout(本地起一个只回话不干活的假服务,socket 挂住)
12
+ * 6) /tts 还没上线(HTTP 404)→ tts_unavailable
13
+ * 7) LLM auto 全链失败 → all_backends_failed + attempts[]
14
+ * 8) 出图后端全不在 → image_backend_unavailable + tried[](绝不返回假图)
15
+ * 9) 成功路径:假 localai 返回真 WAV 字节 → localTts 落盘 + 字节数对得上
16
+ * 10) localStatus() 形状 + 开关全 false
17
+ *
18
+ * 跑法:node scripts/selftest-local-models.mjs
19
+ * 退出码 0 = 全过;1 = 有失败(会列出失败项)。
20
+ */
21
+ import http from 'node:http';
22
+ import { existsSync, statSync, readFileSync, rmSync } from 'node:fs';
23
+ import { mkdtempSync } from 'node:fs';
24
+ import { tmpdir } from 'node:os';
25
+ import { join } from 'node:path';
26
+ import zlib from 'node:zlib';
27
+
28
+ const mod = await import('../dist/features/local-models.js');
29
+ const {
30
+ configureLocalModels, getLocalModelsConfig, localCapabilityState,
31
+ localAsr, localOcr, localTts, localLlm, localImage, localStatus, listImagePorts,
32
+ DEFAULT_CONFIG, SETTINGS_HINT, buildLocalModelTools, resolveGatewayKey,
33
+ parseVramFreeMb, readFreeVramMb, computeBackendAction, unloadTtsWorker, ensureVram,
34
+ probeSdServer, waitSdServer, spawnSdServer, pngSize,
35
+ } = mod;
36
+
37
+ // 造一张结构合法的真 PNG(8-bit RGB,全零像素;用于「不伪造、真读 IHDR」的自测)
38
+ function makePng(w, h) {
39
+ const crcTable = [];
40
+ for (let n = 0; n < 256; n++) {
41
+ let c = n;
42
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
43
+ crcTable[n] = c >>> 0;
44
+ }
45
+ const crc32 = (buf) => {
46
+ let c = 0xffffffff;
47
+ for (const b of buf) c = crcTable[(c ^ b) & 0xff] ^ (c >>> 8);
48
+ return (c ^ 0xffffffff) >>> 0;
49
+ };
50
+ const chunk = (type, data) => {
51
+ const len = Buffer.alloc(4);
52
+ len.writeUInt32BE(data.length, 0);
53
+ const t = Buffer.from(type, 'ascii');
54
+ const crc = Buffer.alloc(4);
55
+ crc.writeUInt32BE(crc32(Buffer.concat([t, data])), 0);
56
+ return Buffer.concat([len, t, data, crc]);
57
+ };
58
+ const ihdr = Buffer.alloc(13);
59
+ ihdr.writeUInt32BE(w, 0);
60
+ ihdr.writeUInt32BE(h, 4);
61
+ ihdr[8] = 8; // bit depth
62
+ ihdr[9] = 2; // RGB
63
+ const raw = Buffer.alloc((w * 3 + 1) * h); // 每行一个 filter 字节(0) + RGB
64
+ const idat = zlib.deflateSync(raw, { level: 9 });
65
+ return Buffer.concat([
66
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
67
+ chunk('IHDR', ihdr),
68
+ chunk('IDAT', idat),
69
+ chunk('IEND', Buffer.alloc(0)),
70
+ ]);
71
+ }
72
+
73
+ let pass = 0;
74
+ let fail = 0;
75
+ const failures = [];
76
+
77
+ function ok(name, cond, extra) {
78
+ if (cond) {
79
+ pass++;
80
+ console.log(` ✅ ${name}`);
81
+ } else {
82
+ fail++;
83
+ failures.push(name);
84
+ console.log(` ❌ ${name}${extra ? ` — ${extra}` : ''}`);
85
+ }
86
+ }
87
+
88
+ // configureLocalModels 是「整份替换」,测试里改单个键要先带上当前快照
89
+ const reconf = (changes) => configureLocalModels({ ...getLocalModelsConfig(), ...changes });
90
+
91
+ function eq(name, actual, expected) {
92
+ ok(name, actual === expected, `期望 ${JSON.stringify(expected)},实际 ${JSON.stringify(actual)}`);
93
+ }
94
+
95
+ // ── 假后端:一个 http server 用不同路径模拟各种情况 ──────────────────
96
+ // URL 用 127.0.0.1 随机端口,避免和真后端(localai 8188)串味。
97
+ const requests = [];
98
+ const srv = http.createServer((req, res) => {
99
+ requests.push({ url: req.url, method: req.method });
100
+ if (req.url === '/health') {
101
+ res.writeHead(200, { 'content-type': 'application/json' });
102
+ res.end(JSON.stringify({ ok: true, asr: true, ocr: true, tts: false, llm: true, embed: true }));
103
+ return;
104
+ }
105
+ if (req.url === '/tts') {
106
+ // 404 = /tts 还没上线(别人正在加)
107
+ res.writeHead(404, { 'content-type': 'application/json' });
108
+ res.end(JSON.stringify({ detail: 'Not Found' }));
109
+ return;
110
+ }
111
+ if (req.url === '/tts-ok') {
112
+ // 成功路径:返回一段最小合法 RIFF/WAVE 头(44 字节)
113
+ const wav = Buffer.alloc(44);
114
+ wav.write('RIFF', 0, 'ascii');
115
+ wav.writeUInt32LE(36, 4);
116
+ wav.write('WAVE', 8, 'ascii');
117
+ wav.write('fmt ', 12, 'ascii');
118
+ wav.writeUInt32LE(16, 16);
119
+ wav.writeUInt16LE(1, 20);
120
+ wav.writeUInt16LE(1, 22);
121
+ wav.writeUInt32LE(16000, 24);
122
+ wav.writeUInt32LE(32000, 28);
123
+ wav.writeUInt16LE(2, 32);
124
+ wav.writeUInt16LE(16, 34);
125
+ wav.write('data', 36, 'ascii');
126
+ wav.writeUInt32LE(0, 40);
127
+ res.writeHead(200, { 'content-type': 'audio/wav' });
128
+ res.end(wav);
129
+ return;
130
+ }
131
+ if (req.url === '/asr') {
132
+ res.writeHead(200, { 'content-type': 'application/json' });
133
+ res.end(JSON.stringify({ text: '你好,本鲸听得见', lang: 'zh', duration: 1.2 }));
134
+ return;
135
+ }
136
+ if (req.url === '/ocr') {
137
+ res.writeHead(200, { 'content-type': 'application/json' });
138
+ res.end(JSON.stringify({ lines: [{ text: '第一行' }, { text: '第二行' }] }));
139
+ return;
140
+ }
141
+ if (req.url === '/llm') {
142
+ res.writeHead(200, { 'content-type': 'application/json' });
143
+ res.end(JSON.stringify({ text: '本地模型补的一句', model: 'fake', tok_per_s: 12 }));
144
+ return;
145
+ }
146
+ // 其它一律挂住不回(用来测超时):故意不 end
147
+ // 但 node 里挂住的 socket 会让进程退出变慢,所以最多挂 10s 再断
148
+ setTimeout(() => {
149
+ try {
150
+ res.destroy();
151
+ }
152
+ catch { /* ignore */ }
153
+ }, 10000);
154
+ });
155
+ await new Promise((resolve) => srv.listen(0, '127.0.0.1', resolve));
156
+ const PORT = srv.address().port;
157
+ const BASE = `http://127.0.0.1:${PORT}`;
158
+ console.log(`假后端: ${BASE}`);
159
+
160
+ // 临时目录放输出
161
+ const tmp = mkdtempSync(join(tmpdir(), 'lm-selftest-'));
162
+ // 造一个 100 字节假音频/假图(只测路径校验,不真解析)
163
+ const fakeAudio = join(tmp, 'fake.wav');
164
+ const { writeFileSync } = await import('node:fs');
165
+ writeFileSync(fakeAudio, Buffer.alloc(100));
166
+
167
+ // ══════════════════════════════════════════════════════════════════
168
+ console.log('\n[1] 默认值:全关');
169
+ eq('DEFAULT_CONFIG.enabled', DEFAULT_CONFIG.enabled, false);
170
+ for (const cap of ['asr', 'ocr', 'tts', 'llm', 'image']) eq(`DEFAULT_CONFIG.${cap}`, DEFAULT_CONFIG[cap], false);
171
+
172
+ // ══════════════════════════════════════════════════════════════════
173
+ console.log('\n[2] 总开关关着 → disabled(且不连后端)');
174
+ configureLocalModels({ enabled: false, asr: true, ocr: true, tts: true, llm: true, image: true, localaiUrl: 'http://127.0.0.1:1' });
175
+ {
176
+ const before = requests.length;
177
+ const r = await localAsr(fakeAudio);
178
+ eq('localAsr code', r.code, 'disabled');
179
+ ok('localAsr ok=false', r.ok === false);
180
+ ok('disabled 错误里带指路(map)', String(r.error).includes(SETTINGS_HINT.slice(0, 8)), r.error);
181
+ const r2 = await localLlm('hi');
182
+ eq('localLlm code', r2.code, 'disabled');
183
+ const r3 = await localImage('a cat');
184
+ eq('localImage code', r3.code, 'disabled');
185
+ const r4 = await localTts('你好');
186
+ eq('localTts code', r4.code, 'disabled');
187
+ const r5 = await localOcr(fakeAudio);
188
+ eq('localOcr code', r5.code, 'disabled');
189
+ eq('打到后端的请求数(应为 0)', requests.length - before, 0);
190
+ }
191
+
192
+ // ══════════════════════════════════════════════════════════════════
193
+ console.log('\n[3] 总开关开、分开关关 → disabled_capability');
194
+ configureLocalModels({ enabled: true, asr: true, ocr: false, tts: false, llm: false, image: false, localaiUrl: BASE });
195
+ {
196
+ const a = await localAsr(fakeAudio);
197
+ ok('asr 开着 → ok=true', a.ok === true, JSON.stringify(a));
198
+ eq('asr 文本', a.text, '你好,本鲸听得见');
199
+ const o = await localOcr(fakeAudio);
200
+ eq('ocr 关着 → disabled_capability', o.code, 'disabled_capability');
201
+ ok('disabled_capability 提到分开关名', String(o.error).includes('localModels.ocr'), o.error);
202
+ const t = await localTts('你好');
203
+ eq('tts 关着 → disabled_capability', t.code, 'disabled_capability');
204
+ const l = await localLlm('hi');
205
+ eq('llm 关着 → disabled_capability', l.code, 'disabled_capability');
206
+ const i = await localImage('cat');
207
+ eq('image 关着 → disabled_capability', i.code, 'disabled_capability');
208
+ }
209
+
210
+ // ══════════════════════════════════════════════════════════════════
211
+ console.log('\n[4] 参数错 → bad_arg');
212
+ configureLocalModels({ enabled: true, asr: true, ocr: true, tts: true, llm: true, image: true, localaiUrl: BASE });
213
+ {
214
+ const r = await localAsr(join(tmp, 'nope-does-not-exist.wav'));
215
+ eq('不存在的文件 → bad_arg', r.code, 'bad_arg');
216
+ ok('bad_arg 有 error 文本', typeof r.error === 'string' && r.error.length > 0);
217
+ const r2 = await localTts(' ');
218
+ eq('空文本 TTS → bad_arg', r2.code, 'bad_arg');
219
+ const r3 = await localLlm('');
220
+ eq('空 prompt LLM → bad_arg', r3.code, 'bad_arg');
221
+ const r4 = await localLlm('hi', { backend: 'nonsense' });
222
+ eq('未知 backend → bad_arg', r4.code, 'bad_arg');
223
+ }
224
+
225
+ // ══════════════════════════════════════════════════════════════════
226
+ console.log('\n[5] 端点不可达 → endpoint_unreachable');
227
+ configureLocalModels({ enabled: true, asr: true, tts: true, llm: true, localaiUrl: 'http://127.0.0.1:9', timeoutMs: 3000 });
228
+ {
229
+ const r = await localAsr(fakeAudio);
230
+ eq('unreachable code', r.code, 'endpoint_unreachable');
231
+ ok('带 url 字段', typeof r.url === 'string' && r.url.includes('/asr'), r.url);
232
+ ok('带 ms 字段', typeof r.ms === 'number');
233
+ ok('带 backend 字段', r.backend === 'localai', String(r.backend));
234
+ ok('error 是字符串', typeof r.error === 'string');
235
+ }
236
+
237
+ // ══════════════════════════════════════════════════════════════════
238
+ console.log('\n[6] 超时 → timeout');
239
+ configureLocalModels({ enabled: true, asr: true, tts: true, llm: true, localaiUrl: BASE, timeoutMs: 400 });
240
+ // 主假后端各路径都秒回,测不出超时 → 单起一个「收请求但永不回包」的服务器
241
+ const hangSrv = http.createServer(() => { /* 故意不 end,让 fetch 挂住 */ });
242
+ await new Promise((r2) => hangSrv.listen(0, '127.0.0.1', r2));
243
+ const hangPort = hangSrv.address().port;
244
+ configureLocalModels({ enabled: true, asr: true, tts: true, llm: true, localaiUrl: `http://127.0.0.1:${hangPort}`, timeoutMs: 400 });
245
+ {
246
+ const r = await localAsr(fakeAudio);
247
+ eq('挂住的端点 → timeout', r.code, 'timeout');
248
+ ok('timeout 里带 timeoutMs', r.timeoutMs === 400, String(r.timeoutMs));
249
+ ok('timeout 用时接近 400ms 而不是傻等', r.ms < 2500, `${r.ms}ms`);
250
+ hangSrv.closeAllConnections?.();
251
+ hangSrv.close();
252
+ }
253
+
254
+ // ══════════════════════════════════════════════════════════════════
255
+ console.log('\n[7] /tts 没上线(404)→ tts_unavailable');
256
+ configureLocalModels({ enabled: true, tts: true, localaiUrl: BASE, timeoutMs: 3000 });
257
+ {
258
+ const r = await localTts('你好', { outDir: tmp });
259
+ eq('404 → tts_unavailable', r.code, 'tts_unavailable');
260
+ ok('tts_unavailable 提到 /tts', String(r.error).includes('/tts'), r.error);
261
+ ok('tts_unavailable 带 status=404', r.status === 404, String(r.status));
262
+ }
263
+
264
+ // ══════════════════════════════════════════════════════════════════
265
+ console.log('\n[8] TTS 成功路径(真字节落盘)');
266
+ {
267
+ // 借 /system_stats 之类的成功分支不行,直接让假后端把 /tts 变成成功:
268
+ // 用单独的服务器太难,这里改用 outPath 指定 + 把 localaiUrl 指向假服务的别处
269
+ // → 换一个只回 wav 的 server
270
+ const wavSrv = http.createServer((req, res) => {
271
+ if (req.url === '/tts') {
272
+ const wav = Buffer.alloc(44);
273
+ wav.write('RIFF', 0, 'ascii');
274
+ wav.writeUInt32LE(36, 4);
275
+ wav.write('WAVE', 8, 'ascii');
276
+ res.writeHead(200, { 'content-type': 'audio/wav' });
277
+ res.end(wav);
278
+ return;
279
+ }
280
+ res.writeHead(404);
281
+ res.end();
282
+ });
283
+ await new Promise((r2) => wavSrv.listen(0, '127.0.0.1', r2));
284
+ const wp = wavSrv.address().port;
285
+ configureLocalModels({ enabled: true, tts: true, localaiUrl: `http://127.0.0.1:${wp}`, timeoutMs: 3000 });
286
+ const outPath = join(tmp, 'tts-ok.wav');
287
+ const r = await localTts('你好', { outPath });
288
+ ok('localTts ok', r.ok === true, JSON.stringify(r));
289
+ eq('落盘字节数', r.bytes, 44);
290
+ ok('文件真的存在', existsSync(outPath));
291
+ if (existsSync(outPath)) eq('磁盘上的字节数', statSync(outPath).size, 44);
292
+ ok('RIFF 头存在', existsSync(outPath) && readFileSync(outPath).subarray(0, 4).toString('ascii') === 'RIFF');
293
+ wavSrv.close();
294
+ }
295
+
296
+ // ══════════════════════════════════════════════════════════════════
297
+ console.log('\n[9] LLM auto 全链失败 → all_backends_failed + attempts[]');
298
+ configureLocalModels({
299
+ enabled: true, llm: true,
300
+ localaiUrl: 'http://127.0.0.1:9',
301
+ strataUrl: 'http://127.0.0.1:9/v1',
302
+ gatewayUrl: 'http://127.0.0.1:9/v1',
303
+ ollamaUrl: 'http://127.0.0.1:9',
304
+ llmBackend: 'auto',
305
+ timeoutMs: 1500,
306
+ });
307
+ {
308
+ const r = await localLlm('hi');
309
+ eq('全链失败 code', r.code, 'all_backends_failed');
310
+ ok('attempts 是数组且 4 条', Array.isArray(r.attempts) && r.attempts.length === 4, JSON.stringify(r.attempts));
311
+ ok('attempts 顺序 localai/strata/gateway/ollama',
312
+ (r.attempts || []).map((a) => a.backend).join(',') === 'localai,strata,gateway,ollama',
313
+ JSON.stringify((r.attempts || []).map((a) => a.backend)));
314
+ ok('每条都有 code', (r.attempts || []).every((a) => typeof a.code === 'string'));
315
+ ok('all_backends_failed 里带 lastCode', typeof r.lastCode === 'string', String(r.lastCode));
316
+ }
317
+
318
+ // ══════════════════════════════════════════════════════════════════
319
+ console.log('\n[10] LLM 成功(假 localai /llm)');
320
+ configureLocalModels({ enabled: true, llm: true, localaiUrl: BASE, llmBackend: 'auto', timeoutMs: 3000 });
321
+ {
322
+ const r = await localLlm('说一句');
323
+ ok('LLM ok', r.ok === true, JSON.stringify(r));
324
+ eq('LLM backend', r.backend, 'localai');
325
+ eq('LLM text', r.text, '本地模型补的一句');
326
+ }
327
+
328
+ // ══════════════════════════════════════════════════════════════════
329
+ console.log('\n[11] 出图后端全不在 → image_backend_unavailable + tried[]');
330
+ configureLocalModels({ enabled: true, image: true, imageBackend: 'sdwebui', imagePorts: '9,10', heavyTimeoutMs: 2000 });
331
+ {
332
+ const r = await localImage('a cat');
333
+ eq('无出图后端 code', r.code, 'image_backend_unavailable');
334
+ ok('tried 数组长度 2', Array.isArray(r.tried) && r.tried.length === 2, JSON.stringify(r.tried));
335
+ ok('tried 里都 up=false', (r.tried || []).every((t) => t.up === false));
336
+ ok('**没有**返回任何图片路径(不伪造)', r.path === undefined && r.bytes === undefined, JSON.stringify(r));
337
+ }
338
+
339
+ // ══════════════════════════════════════════════════════════════════
340
+ console.log('\n[12] localStatus() 形状');
341
+ configureLocalModels({
342
+ enabled: true, asr: true, ocr: false, tts: false, llm: false, image: false,
343
+ localaiUrl: BASE, ollamaUrl: 'http://127.0.0.1:9', strataUrl: 'http://127.0.0.1:9/v1', imagePorts: '9',
344
+ });
345
+ {
346
+ const s = await localStatus();
347
+ eq('status ok', s.ok, true);
348
+ eq('switches.enabled', s.switches.enabled, true);
349
+ eq('switches.asr', s.switches.asr, true);
350
+ eq('switches.ocr', s.switches.ocr, false);
351
+ eq('localai up', s.backends.localai.up, true);
352
+ eq('ollama down', s.backends.ollama.up, false);
353
+ eq('strata down', s.backends.strata.up, false);
354
+ ok('image 端口数组 1 条', Array.isArray(s.backends.image) && s.backends.image.length === 1);
355
+ ok('notes 是数组且提到关着的分开关', Array.isArray(s.notes) && s.notes.some((n) => n.includes('localModels.ocr')), JSON.stringify(s.notes));
356
+ ok('notes 里带显存守卫', s.notes.some((n) => n.includes('20.5G')));
357
+ }
358
+
359
+ // ══════════════════════════════════════════════════════════════════
360
+ console.log('\n[13] 工具装配(用假 defineTool,不需要宿主包)');
361
+ {
362
+ const seen = [];
363
+ const fakeDefine = (def) => {
364
+ seen.push(def.name);
365
+ return def;
366
+ };
367
+ const tools = buildLocalModelTools(fakeDefine);
368
+ eq('工具数 7', tools.length, 7);
369
+ eq('工具名', seen.join(','), 'local_asr,local_ocr,local_tts,local_llm,local_image,local_status,local_models');
370
+ // 关掉总开关,跑一次 execute,确认回 {ok:false} 且文本带 disabled
371
+ configureLocalModels({ enabled: false });
372
+ const asr = tools.find((t) => t.tool.name === 'local_asr').tool;
373
+ const out = await asr.execute({ file: fakeAudio });
374
+ eq('工具层 ok=false', out.ok, false);
375
+ ok('工具层文本带 disabled', String(out.msg).includes('disabled'), out.msg);
376
+ // local_status 不受开关限制
377
+ configureLocalModels({ enabled: false, localaiUrl: 'http://127.0.0.1:9', ollamaUrl: 'http://127.0.0.1:9', strataUrl: 'http://127.0.0.1:9/v1', imagePorts: '9' });
378
+ const st = tools.find((t) => t.tool.name === 'local_status').tool;
379
+ const sOut = await st.execute({});
380
+ eq('local_status 关着也能调', sOut.ok, true);
381
+ ok('local_status 文本有大写开关汇总', String(sOut.msg).includes('总关'), String(sOut.msg).slice(0, 80));
382
+ }
383
+
384
+ // ══════════════════════════════════════════════════════════════════
385
+ console.log('\n[14] 配置规范化');
386
+ {
387
+ const c = configureLocalModels({ localaiUrl: 'http://127.0.0.1:8188/', strataUrl: 'http://127.0.0.1:8080' });
388
+ eq('URL 去尾斜杠', c.localaiUrl, 'http://127.0.0.1:8188');
389
+ eq('strataUrl 自动补 /v1', c.strataUrl, 'http://127.0.0.1:8080/v1');
390
+ const c2 = configureLocalModels({ enabled: 'true', asr: 1 });
391
+ eq('字符串 "true" → true', c2.enabled, true);
392
+ eq('数字 1 → true', c2.asr, true);
393
+ eq('listImagePorts 默认解析', listImagePorts().length >= 1, true);
394
+ configureLocalModels({ timeoutMs: -5 });
395
+ eq('非法超时被忽略(仍 60000)', getLocalModelsConfig().timeoutMs, 60000);
396
+ eq('配置快照可读', typeof getLocalModelsConfig().localaiUrl, 'string');
397
+ configureLocalModels({ enabled: true, asr: true });
398
+ eq('localCapabilityState 开着 → ok', localCapabilityState('asr').ok, true);
399
+ eq('localCapabilityState 关着的分开关 → disabled_capability', localCapabilityState('ocr').code, 'disabled_capability');
400
+ }
401
+
402
+ // ══════════════════════════════════════════════════════════════════
403
+ console.log('\n[15] Strata 分支:必须自动关思考,空 content 报错');
404
+ {
405
+ const bodies = [];
406
+ let mode = 'ok';
407
+ const strataSrv = http.createServer((req, res) => {
408
+ let raw = '';
409
+ req.on('data', (c) => { raw += c; });
410
+ req.on('end', () => {
411
+ bodies.push({ url: req.url, body: raw ? JSON.parse(raw) : null });
412
+ res.writeHead(200, { 'content-type': 'application/json' });
413
+ if (mode === 'empty') {
414
+ res.end(JSON.stringify({ model: 'qwen3.6-35b-a3b-ud-q4_k_xl', choices: [{ message: { content: '', reasoning_content: '我在想……' } }] }));
415
+ } else {
416
+ res.end(JSON.stringify({ model: 'qwen3.6-35b-a3b-ud-q4_k_xl', choices: [{ message: { content: 'Strata 真回了一句' } }], usage: { prompt_tokens: 5, completion_tokens: 6 } }));
417
+ }
418
+ });
419
+ });
420
+ await new Promise((r2) => strataSrv.listen(0, '127.0.0.1', r2));
421
+ const sPort = strataSrv.address().port;
422
+ configureLocalModels({ enabled: true, llm: true, strataUrl: `http://127.0.0.1:${sPort}/v1`, strataModel: 'qwen3.6-35b-a3b-ud-q4_k_xl', llmTimeoutMs: 3000 });
423
+ const r = await localLlm('说一句', { backend: 'strata', maxTokens: 32 });
424
+ ok('strata ok', r.ok === true, JSON.stringify(r));
425
+ eq('strata backend', r.backend, 'strata');
426
+ eq('strata text', r.text, 'Strata 真回了一句');
427
+ eq('strata usage 透传', r.usage?.completion_tokens, 6);
428
+ const b0 = bodies[0]?.body || {};
429
+ eq('strata 打到 /v1/chat/completions', bodies[0]?.url, '/v1/chat/completions');
430
+ eq('strata body.enable_thinking', b0.enable_thinking, false);
431
+ eq('strata body.chat_template_kwargs.enable_thinking', b0?.chat_template_kwargs?.enable_thinking, false);
432
+ eq('strata body.stream', b0.stream, false);
433
+ eq('strata body.model', b0.model, 'qwen3.6-35b-a3b-ud-q4_k_xl');
434
+ eq('strata max_tokens 透传', b0.max_tokens, 32);
435
+ mode = 'empty';
436
+ const r2 = await localLlm('说一句', { backend: 'strata' });
437
+ eq('strata 空 content → all_backends_failed', r2.code, 'all_backends_failed');
438
+ eq('strata 空 content 的底层 code', r2.attempts?.[0]?.code, 'empty_content');
439
+ ok('empty_content 提示带 reasoning_content', String(r2.attempts?.[0]?.error).includes('我在想'), r2.attempts?.[0]?.error);
440
+ strataSrv.closeAllConnections?.();
441
+ strataSrv.close();
442
+ }
443
+
444
+ // ══════════════════════════════════════════════════════════════════
445
+ console.log('\n[16] Gateway 分支:Bearer key + local-auto + content 解析');
446
+ {
447
+ const got = [];
448
+ let mode = 'ok';
449
+ const gwSrv = http.createServer((req, res) => {
450
+ let raw = '';
451
+ req.on('data', (c) => { raw += c; });
452
+ req.on('end', () => {
453
+ got.push({ url: req.url, auth: req.headers.authorization || '', body: raw ? JSON.parse(raw) : null });
454
+ res.writeHead(200, { 'content-type': 'application/json' });
455
+ if (mode === 'empty') {
456
+ res.end(JSON.stringify({ model: 'local-auto', choices: [{ message: { content: '' } }] }));
457
+ return;
458
+ }
459
+ res.end(JSON.stringify({ model: 'qwen2.5:7b', choices: [{ message: { content: '网关回了一句' } }], usage: { prompt_tokens: 9, completion_tokens: 4 } }));
460
+ });
461
+ });
462
+ await new Promise((r2) => gwSrv.listen(0, '127.0.0.1', r2));
463
+ const gPort = gwSrv.address().port;
464
+ configureLocalModels({ enabled: true, llm: true, gatewayUrl: `http://127.0.0.1:${gPort}`, gatewayKey: 'sk-test-123', gatewayModel: '', llmTimeoutMs: 3000 });
465
+ const r = await localLlm('说一句', { backend: 'gateway' });
466
+ ok('gateway ok', r.ok === true, JSON.stringify(r));
467
+ eq('gateway text', r.text, '网关回了一句');
468
+ eq('gateway upstream=响应里的 model', r.upstream, 'qwen2.5:7b');
469
+ eq('gateway 默认模型 local-auto', got[0]?.body?.model, 'local-auto');
470
+ eq('gateway Authorization Bearer', got[0]?.auth, 'Bearer sk-test-123');
471
+ eq('gateway 打到 /v1/chat/completions', got[0]?.url, '/v1/chat/completions');
472
+ const r2 = await localLlm('说一句', { backend: 'gateway', model: 'qwen3:8b' });
473
+ eq('gateway 可指定 model', got[1]?.body?.model, 'qwen3:8b');
474
+ ok('gateway 指定 model 仍 ok', r2.ok === true, JSON.stringify(r2));
475
+ mode = 'empty';
476
+ const r3 = await localLlm('说一句', { backend: 'gateway' });
477
+ eq('gateway 空 content → all_backends_failed', r3.code, 'all_backends_failed');
478
+ eq('gateway 空 content 的底层 code', r3.attempts?.[0]?.code, 'empty_content');
479
+ gwSrv.closeAllConnections?.();
480
+ gwSrv.close();
481
+ }
482
+
483
+ // ══════════════════════════════════════════════════════════════════
484
+ console.log('\n[17] 纯函数:parseVramFreeMb / pngSize / computeBackendAction / unloadTtsWorker');
485
+ {
486
+ eq('parseVramFreeMb("21965 MiB")', parseVramFreeMb('21965 MiB'), 21965);
487
+ eq('parseVramFreeMb("21382")', parseVramFreeMb('21382'), 21382);
488
+ eq('parseVramFreeMb("N/A")', parseVramFreeMb('N/A'), null);
489
+ eq('parseVramFreeMb("")', parseVramFreeMb(''), null);
490
+ ok('pngSize(随机字节) → null', pngSize(Buffer.alloc(40, 1)) === null);
491
+ ok('pngSize(空) → null', pngSize(null) === null);
492
+ const tiny = makePng(640, 480);
493
+ const dim = pngSize(tiny);
494
+ eq('pngSize 宽', dim?.width, 640);
495
+ eq('pngSize 高', dim?.height, 480);
496
+ ok('pngSize 认 PNG 签名', tiny.subarray(0, 8).toString('hex') === '89504e470d0a1a0a');
497
+ }
498
+
499
+ // ══════════════════════════════════════════════════════════════════
500
+ console.log('\n[18] TTS 显存策略:先 unload → 必要时停 strata → note/policy');
501
+ {
502
+ process.env.QQBOT_FAKE_VRAM_FREE_MB = '12000';
503
+ const calls = [];
504
+ const polSrv = http.createServer((req, res) => {
505
+ let raw = '';
506
+ req.on('data', (c) => { raw += c; });
507
+ req.on('end', () => {
508
+ calls.push(req.url);
509
+ if (req.url.startsWith('/api/backend/strata/stop')) {
510
+ res.writeHead(200, { 'content-type': 'application/json' });
511
+ res.end(JSON.stringify({ ok: true }));
512
+ return;
513
+ }
514
+ if (req.url.startsWith('/tts/unload')) {
515
+ res.writeHead(200, { 'content-type': 'application/json' });
516
+ res.end(JSON.stringify({ ok: true, running: false }));
517
+ return;
518
+ }
519
+ if (req.url === '/tts') {
520
+ const wav = Buffer.alloc(44);
521
+ wav.write('RIFF', 0, 'ascii');
522
+ wav.writeUInt32LE(36, 4);
523
+ wav.write('WAVE', 8, 'ascii');
524
+ res.writeHead(200, { 'content-type': 'audio/wav', 'x-tts-vram-peak-mb': '5457.9', 'x-tts-duration-ms': '4160', 'x-tts-elapsed-ms': '7845' });
525
+ res.end(wav);
526
+ return;
527
+ }
528
+ res.writeHead(200, { 'content-type': 'application/json' });
529
+ res.end('{}');
530
+ });
531
+ });
532
+ await new Promise((r2) => polSrv.listen(0, '127.0.0.1', r2));
533
+ const pPort = polSrv.address().port;
534
+ configureLocalModels({
535
+ enabled: true, tts: true, ttsIdleUnload: false,
536
+ localaiUrl: `http://127.0.0.1:${pPort}`,
537
+ computeUrl: `http://127.0.0.1:${pPort}`,
538
+ ttsNeedVramMb: 7000, heavyTimeoutMs: 5000,
539
+ });
540
+ const outPath = join(tmp, 'tts-policy.wav');
541
+ const r = await localTts('策略测试', { outPath });
542
+ ok('策略 TTS ok', r.ok === true, JSON.stringify(r));
543
+ eq('策略 TTS 字节', r.bytes, 44);
544
+ ok('先调了 /tts/unload', calls.some((u) => u.startsWith('/tts/unload')), calls.join('|'));
545
+ ok('unload 在 /tts 之前', calls.indexOf('/tts/unload?kill=1') > -1 && calls.indexOf('/tts/unload?kill=1') < calls.indexOf('/tts'), calls.join('|'));
546
+ ok('显存够时不调 compute stop', !calls.some((u) => u.includes('/api/backend/')), calls.join('|'));
547
+ ok('policy 是数组且提到 unload', Array.isArray(r.policy) && r.policy.join(';').includes('unload'), JSON.stringify(r.policy));
548
+ ok('note 以「显存策略:」开头', String(r.note || '').startsWith('显存策略:'), r.note);
549
+ eq('note 里带 unload 策略', String(r.note).includes('/tts/unload?kill=1'), true);
550
+ eq('响应头 vramPeakMb 解析', r.vramPeakMb, 5457.9);
551
+ eq('响应头 durationMs 解析', r.durationMs, 4160);
552
+ eq('响应头 elapsedMs 解析', r.elapsedMs, 7845);
553
+ eq('TTS 返回 freeVramMb(伪造 12000)', r.freeVramMb, 12000);
554
+ ok('ttsIdleUnload=false 时不再 unload', calls.filter((u) => u.startsWith('/tts/unload')).length === 1, calls.join('|'));
555
+
556
+ // 显存不够:stop strata 后仍不够 → vram_insufficient(等 12s 轮询结束)
557
+ process.env.QQBOT_FAKE_VRAM_FREE_MB = '100';
558
+ calls.length = 0;
559
+ reconf({ ttsNeedVramMb: 7000 });
560
+ const r2 = await localTts('策略测试2', { outPath: join(tmp, 'tts-policy2.wav') });
561
+ eq('显存不足 code', r2.code, 'vram_insufficient');
562
+ ok('不足时确实停了 strata', calls.some((u) => u.startsWith('/api/backend/strata/stop')), calls.join('|'));
563
+ ok('不足时 policy 里带停 strata 记录或被吞', Array.isArray(r2.policy), JSON.stringify(r2.policy));
564
+ ok('不足时不写文件', !existsSync(join(tmp, 'tts-policy2.wav')));
565
+
566
+ // ttsIdleUnload=true:合成后卸载
567
+ process.env.QQBOT_FAKE_VRAM_FREE_MB = '12000';
568
+ calls.length = 0;
569
+ reconf({ ttsIdleUnload: true });
570
+ const r3 = await localTts('策略测试3', { outPath: join(tmp, 'tts-policy3.wav') });
571
+ ok('idleUnload 仍 ok', r3.ok === true, JSON.stringify(r3));
572
+ eq('idleUnload 调了两次 unload', calls.filter((u) => u.startsWith('/tts/unload')).length, 2);
573
+ ok('policy 提到合成后卸载', r3.policy.join(';').includes('ttsIdleUnload=true'), JSON.stringify(r3.policy));
574
+ reconf({ ttsIdleUnload: false });
575
+ delete process.env.QQBOT_FAKE_VRAM_FREE_MB;
576
+ polSrv.closeAllConnections?.();
577
+ polSrv.close();
578
+ }
579
+
580
+ // ══════════════════════════════════════════════════════════════════
581
+ console.log('\n[19] sd_server 出图:/health + /draw → 真 PNG(宽高从 IHDR 读)');
582
+ {
583
+ process.env.QQBOT_FAKE_VRAM_FREE_MB = '16000';
584
+ const draws = [];
585
+ const sdSrv = http.createServer((req, res) => {
586
+ if (req.url === '/health') {
587
+ res.writeHead(200, { 'content-type': 'application/json' });
588
+ res.end(JSON.stringify({ ok: true, model: 'fake-sd15', loaded: true, device: 'cuda', steps: 24, cfg: 7 }));
589
+ return;
590
+ }
591
+ if (req.url === '/draw') {
592
+ let raw = '';
593
+ req.on('data', (c) => { raw += c; });
594
+ req.on('end', () => {
595
+ const body = raw ? JSON.parse(raw) : {};
596
+ draws.push(body);
597
+ const png = makePng(Number(body.width) || 512, Number(body.height) || 512);
598
+ writeFileSync(body.out, png);
599
+ res.writeHead(200, { 'content-type': 'application/json' });
600
+ res.end(JSON.stringify({ ok: true, path: body.out, ms: 1234, seed: 42, steps: body.steps }));
601
+ });
602
+ return;
603
+ }
604
+ res.writeHead(404);
605
+ res.end();
606
+ });
607
+ await new Promise((r2) => sdSrv.listen(0, '127.0.0.1', r2));
608
+ const sdPort = sdSrv.address().port;
609
+ configureLocalModels({
610
+ enabled: true, image: true, imageBackend: 'sdserver',
611
+ sdServerUrl: `http://127.0.0.1:${sdPort}`, sdWidth: 512, sdHeight: 512, sdSteps: 20,
612
+ heavyTimeoutMs: 5000, imageNeedVramMb: 7000,
613
+ });
614
+ const out = join(tmp, 'sd-ok.png');
615
+ const r = await localImage('a whale girl', { outPath: out });
616
+ ok('sdserver ok', r.ok === true, JSON.stringify(r));
617
+ eq('sdserver backend', r.backend, 'sdserver');
618
+ eq('sdserver 宽', r.width, 512);
619
+ eq('sdserver 高', r.height, 512);
620
+ eq('sdserver seed', r.seed, 42);
621
+ eq('sdserver drawMs', r.drawMs, 1234);
622
+ ok('sdserver bytes>0', typeof r.bytes === 'number' && r.bytes > 0, String(r.bytes));
623
+ ok('sdserver 文件真的落盘', existsSync(out));
624
+ eq('sdserver note 带显存守卫', String(r.note).includes('显存守卫'), true);
625
+ ok('sdserver tried 空(服务已在)', Array.isArray(r.tried) && r.tried.length === 0, JSON.stringify(r.tried));
626
+ eq('sdserver 传了 out 路径', typeof draws[0]?.out, 'string');
627
+ eq('sdserver 传了 steps', draws[0]?.steps, 20);
628
+ eq('sdserver 传了 prompt', draws[0]?.prompt, 'a whale girl');
629
+ eq('sdserver 传了 negative', typeof draws[0]?.negative, 'string');
630
+
631
+ // 太小 → bad_size
632
+ const smallSrv = http.createServer((req, res) => {
633
+ if (req.url === '/health') {
634
+ res.writeHead(200, { 'content-type': 'application/json' });
635
+ res.end(JSON.stringify({ ok: true, loaded: true }));
636
+ return;
637
+ }
638
+ let raw = '';
639
+ req.on('data', (c) => { raw += c; });
640
+ req.on('end', () => {
641
+ const body = JSON.parse(raw);
642
+ writeFileSync(body.out, makePng(256, 256));
643
+ res.writeHead(200, { 'content-type': 'application/json' });
644
+ res.end(JSON.stringify({ ok: true, path: body.out, ms: 10 }));
645
+ });
646
+ });
647
+ await new Promise((r2) => smallSrv.listen(0, '127.0.0.1', r2));
648
+ reconf({ sdServerUrl: `http://127.0.0.1:${smallSrv.address().port}` });
649
+ const r2 = await localImage('x', { width: 256, height: 256, outPath: join(tmp, 'sd-small.png') });
650
+ eq('产物 <512 → bad_size', r2.code, 'bad_size');
651
+ ok('bad_size 不带 path', r2.path === undefined, String(r2.path));
652
+
653
+ // /health 报错 → sd_load_failed
654
+ const badSrv = http.createServer((req, res) => {
655
+ res.writeHead(200, { 'content-type': 'application/json' });
656
+ res.end(JSON.stringify({ ok: false, loaded: false, error: 'CUDA out of memory' }));
657
+ });
658
+ await new Promise((r2) => badSrv.listen(0, '127.0.0.1', r2));
659
+ reconf({ sdServerUrl: `http://127.0.0.1:${badSrv.address().port}`, sdBootWaitMs: 1500 });
660
+ const r3 = await localImage('x');
661
+ eq('加载失败 → sd_load_failed', r3.code, 'sd_load_failed');
662
+ ok('sd_load_failed 带原始 error', String(r3.error).includes('CUDA out of memory'), r3.error);
663
+
664
+ // python 不存在 → sd_python_missing
665
+ reconf({ sdServerUrl: 'http://127.0.0.1:9', sdPython: join(tmp, 'no-python.exe'), sdBootWaitMs: 1200 });
666
+ const r4 = await localImage('x');
667
+ eq('python 缺失 → sd_python_missing', r4.code, 'sd_python_missing');
668
+ delete process.env.QQBOT_FAKE_VRAM_FREE_MB;
669
+ sdSrv.closeAllConnections?.(); sdSrv.close();
670
+ smallSrv.closeAllConnections?.(); smallSrv.close();
671
+ badSrv.closeAllConnections?.(); badSrv.close();
672
+ }
673
+
674
+ // ══════════════════════════════════════════════════════════════════
675
+ console.log('\n[20] 工具 schema:新参数/枚举都要在');
676
+ {
677
+ const seen = new Map();
678
+ buildLocalModelTools((def) => { seen.set(def.name, def); return def; });
679
+ const llmDef = seen.get('local_llm');
680
+ ok('local_llm 有 backend 枚举', Array.isArray(llmDef?.parameters?.backend?.enum), JSON.stringify(llmDef?.parameters?.backend));
681
+ ok('local_llm 枚举含 gateway', (llmDef?.parameters?.backend?.enum || []).includes('gateway'));
682
+ ok('local_llm 枚举含 strata/auto', (llmDef?.parameters?.backend?.enum || []).includes('strata') && (llmDef?.parameters?.backend?.enum || []).includes('auto'));
683
+ ok('local_llm 描述提到 8090', String(llmDef?.description).includes('8090'));
684
+ ok('local_llm 描述提到 enable_thinking', String(llmDef?.description).includes('enable_thinking'));
685
+ const ttsDef = seen.get('local_tts');
686
+ ok('local_tts 有 unloadFirst', ttsDef?.parameters?.unloadFirst?.type === 'boolean');
687
+ ok('local_tts 描述提到 unload', String(ttsDef?.description).includes('unload'));
688
+ const imgDef = seen.get('local_image');
689
+ ok('local_image 有 backend 枚举', Array.isArray(imgDef?.parameters?.backend?.enum));
690
+ ok('local_image 枚举含 sdserver', (imgDef?.parameters?.backend?.enum || []).includes('sdserver'));
691
+ ok('local_image 有 seed', imgDef?.parameters?.seed?.type === 'number');
692
+ ok('local_image 描述提到 7861', String(imgDef?.description).includes('7861'));
693
+ ok('local_image 描述提到不伪造', String(imgDef?.description).includes('绝不返回假图'));
694
+ const stDef = seen.get('local_status');
695
+ ok('local_status 描述提到 8090', String(stDef?.description).includes('8090'));
696
+ ok('local_status 描述提到 sd_server', String(stDef?.description).includes('sd_server'));
697
+ }
698
+
699
+ // ══════════════════════════════════════════════════════════════════
700
+ console.log('\n[21] 新配置键规范化');
701
+ {
702
+ const c = configureLocalModels({
703
+ gatewayUrl: 'http://127.0.0.1:8090/',
704
+ sdServerUrl: 'http://127.0.0.1:7861/',
705
+ computeUrl: 'http://127.0.0.1:8199/',
706
+ gatewayKey: 'k', gatewayModel: '',
707
+ sdWidth: '640', sdHeight: '640', sdSteps: '18', sdBootWaitMs: '90000',
708
+ imageNeedVramMb: '6500', ttsNeedVramMb: '6000', llmTimeoutMs: '150000',
709
+ imageBackend: 'nonsense', llmBackend: 'nonsense',
710
+ });
711
+ eq('gatewayUrl 去尾斜杠并补 /v1', c.gatewayUrl, 'http://127.0.0.1:8090/v1');
712
+ eq('sdServerUrl 去尾斜杠', c.sdServerUrl, 'http://127.0.0.1:7861');
713
+ eq('computeUrl 去尾斜杠', c.computeUrl, 'http://127.0.0.1:8199');
714
+ eq('sdWidth 字符串→数字', c.sdWidth, 640);
715
+ eq('sdHeight 字符串→数字', c.sdHeight, 640);
716
+ eq('sdSteps 字符串→数字', c.sdSteps, 18);
717
+ eq('sdBootWaitMs 字符串→数字', c.sdBootWaitMs, 90000);
718
+ eq('imageNeedVramMb 字符串→数字', c.imageNeedVramMb, 6500);
719
+ eq('ttsNeedVramMb 字符串→数字', c.ttsNeedVramMb, 6000);
720
+ eq('llmTimeoutMs 字符串→数字', c.llmTimeoutMs, 150000);
721
+ eq('非法 imageBackend 回 auto', c.imageBackend, 'auto');
722
+ eq('非法 llmBackend 回 auto', c.llmBackend, 'auto');
723
+ eq('默认 llmTimeoutMs', 120000, 120000);
724
+ eq('DEFAULT gatewayUrl', DEFAULT_CONFIG.gatewayUrl, 'http://127.0.0.1:8090/v1');
725
+ // 2026-11-29:默认不再内嵌 key(包里不携带凭证),留空由 resolveGatewayKey 从本机 clients.json 取
726
+ eq('DEFAULT gatewayKey 不内嵌凭证', DEFAULT_CONFIG.gatewayKey, '');
727
+ eq('resolveGatewayKey 本机取到 key', !!resolveGatewayKey({ gatewayKey: '' }), true);
728
+ eq('DEFAULT imageBackend', DEFAULT_CONFIG.imageBackend, 'auto');
729
+ eq('DEFAULT sdPort', DEFAULT_CONFIG.sdPort, 7861);
730
+ eq('DEFAULT sdWidth', DEFAULT_CONFIG.sdWidth, 768);
731
+ eq('DEFAULT ttsNeedVramMb', DEFAULT_CONFIG.ttsNeedVramMb, 7000);
732
+ eq('DEFAULT ttsIdleUnload', DEFAULT_CONFIG.ttsIdleUnload, false);
733
+ eq('DEFAULT computeUrl', DEFAULT_CONFIG.computeUrl, 'http://127.0.0.1:8199');
734
+ configureLocalModels({ enabled: false });
735
+ }
736
+
737
+ // ── 收尾 ──────────────────────────────────────────────────────────
738
+ srv.closeAllConnections?.();
739
+ srv.close();
740
+ try {
741
+ rmSync(tmp, { recursive: true, force: true });
742
+ }
743
+ catch { /* ignore */ }
744
+
745
+ console.log('\n' + '─'.repeat(56));
746
+ console.log(`通过 ${pass} 项,失败 ${fail} 项(共 ${pass + fail})`);
747
+ if (fail > 0) {
748
+ console.log('失败项:');
749
+ for (const f of failures) console.log(` - ${f}`);
750
+ process.exitCode = 1;
751
+ }
752
+ else {
753
+ console.log('本地模型能力层自测全过 ✅');
754
+ }