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,236 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * storage.mjs —— 统一管理 qqbot 的「过程性文件」(2026-11-30)
4
+ *
5
+ * 问题:截图 → OCR(微信 / 小天才 / qqbot 换 IP)、ffmpeg 转码、TTS 临时 wav、自检沙箱……
6
+ * 各自往仓库根 / %TEMP% 丢文件,越积越多,和模型文件一样散。
7
+ * 做法:所有目录在 config/storage.json 里声明(谁、放哪、留几天、能不能自动删),
8
+ * 这里只做三件事:list(分区表)、stats(占多大)、clean(按 TTL 删过期文件)。
9
+ *
10
+ * node scripts/storage.mjs list
11
+ * node scripts/storage.mjs stats [--json]
12
+ * node scripts/storage.mjs clean [--area vision,tmp] [--older-than 3] [--dry-run]
13
+ *
14
+ * 安全:只删 ttlDays>0 且 autoClean=true 的区域;模型 / 产出 / 凭证 / 归档永不自动删。
15
+ * 删之前把清单写到 out/reports/storage-clean-<时间>.json,可追溯。
16
+ */
17
+ import { existsSync, readFileSync, readdirSync, statSync, unlinkSync, mkdirSync, writeFileSync, rmdirSync } from 'node:fs'
18
+ import { dirname, join, relative, isAbsolute } from 'node:path'
19
+ import { tmpdir } from 'node:os'
20
+ import { fileURLToPath } from 'node:url'
21
+
22
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')
23
+ const CFG = (() => {
24
+ try { return JSON.parse(readFileSync(join(ROOT, 'config', 'storage.json'), 'utf8')) } catch { return { areas: [] } }
25
+ })()
26
+ /**
27
+ * 数据根(2026-12-01):过程性文件大部分不在仓库根,而在 `{dataRoot}/.qqbot/...`
28
+ * (截图 OCR 缓存、引用图、视频卡封面、记忆库每日备份…)。分区表里用 `@data/xxx`
29
+ * 表示"相对数据根",这里统一解析:
30
+ * 环境变量 QQBOT_DATA_ROOT > {仓库根}/dshqqbot(有就用) > 仓库根。
31
+ */
32
+ const DATA_ROOT = (() => {
33
+ const env = String(process.env.QQBOT_DATA_ROOT || '').trim()
34
+ if (env) return env
35
+ const guess = join(ROOT, 'dshqqbot')
36
+ try { if (statSync(guess).isDirectory()) return guess } catch { /* 没有就用仓库根 */ }
37
+ return ROOT
38
+ })()
39
+
40
+ const argv = process.argv.slice(2)
41
+ const cmd = argv[0] || 'list'
42
+ const arg = (k, d) => { const i = argv.indexOf('--' + k); return i >= 0 ? argv[i + 1] : d }
43
+ const flag = (k) => argv.includes('--' + k)
44
+
45
+ /** glob → RegExp(只支持 ** 和 *,够用且不引第三方依赖) */
46
+ function globToRe(g) {
47
+ const norm = String(g).replace(/\\/g, '/')
48
+ let re = ''
49
+ for (let i = 0; i < norm.length; i += 1) {
50
+ const ch = norm[i]
51
+ if (ch === '*' && norm[i + 1] === '*') { re += '.*'; i += 1 }
52
+ else if (ch === '*') re += '[^/]*'
53
+ else if ('\\^$.|?+()[]{}'.includes(ch)) re += '\\' + ch
54
+ else re += ch
55
+ }
56
+ return new RegExp('^' + re + '$')
57
+ }
58
+
59
+ function walk(base, depth = 0, out = []) {
60
+ if (depth > 8) return out
61
+ let ents = []
62
+ try { ents = readdirSync(base, { withFileTypes: true }) } catch { return out }
63
+ for (const e of ents) {
64
+ const p = join(base, e.name)
65
+ if (e.isDirectory()) { out.push({ p, dir: true }); walk(p, depth + 1, out) }
66
+ else if (e.isFile()) { try { out.push({ p, dir: false, size: statSync(p).size, mtime: statSync(p).mtimeMs }) } catch { /* 跳过 */ } }
67
+ }
68
+ return out
69
+ }
70
+
71
+ const toPosix = (p) => String(p).replace(/\\/g, '/')
72
+
73
+ /** 展开一个分区 → 文件列表 */
74
+ function collect(area) {
75
+ const rows = []
76
+ // fromRegistry:不遍历磁盘(.models 有几十万个分片,走一遍要几分钟),直接读注册表汇总
77
+ if (area.fromRegistry) {
78
+ try {
79
+ const reg = JSON.parse(readFileSync(join(ROOT, 'config', 'models.registry.json'), 'utf8'))
80
+ const list = Array.isArray(reg.models) ? reg.models : []
81
+ const bytes = Math.round(Number(reg.total_gb || 0) * 1024 ** 3)
82
+ return [{ p: '.models', size: bytes, mtime: 0, area: area.id, synthetic: list.length }]
83
+ } catch { return [] }
84
+ }
85
+ if (area.globs) {
86
+ // `@data/…` → 数据根;其余 → 仓库根。同一个 top 目录只 walk 一次。
87
+ const bases = new Map() // `${base}|${top}` → { base, top, pats:[] }
88
+ for (const g of area.globs) {
89
+ const isData = String(g).startsWith('@data/')
90
+ const base = isData ? DATA_ROOT : ROOT
91
+ const pat = isData ? String(g).slice(6) : String(g)
92
+ const top = pat.split('/')[0]
93
+ const k = base + '|' + top
94
+ const cur = bases.get(k) || { base, top, pats: [] }
95
+ cur.pats.push(globToRe(pat))
96
+ bases.set(k, cur)
97
+ }
98
+ for (const { base, top, pats } of bases.values()) {
99
+ const abs = join(base, top)
100
+ if (!existsSync(abs)) continue
101
+ const files = walk(abs)
102
+ for (const f of files) {
103
+ if (f.dir) continue
104
+ const rel = toPosix(relative(base, f.p))
105
+ if (pats.some((re) => re.test(rel))) rows.push({ ...f, area: area.id })
106
+ if (rows.length > 50000) return rows
107
+ }
108
+ }
109
+ }
110
+ for (const pat of area.osTemp || []) {
111
+ const abs = join(tmpdir())
112
+ let ents = []
113
+ try { ents = readdirSync(abs, { withFileTypes: true }) } catch { /* ignore */ }
114
+ const re = new RegExp('^' + String(pat).replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$')
115
+ for (const e of ents) {
116
+ if (!re.test(e.name)) continue
117
+ const p = join(abs, e.name)
118
+ const files = e.isDirectory() ? walk(p) : [{ p, dir: false }]
119
+ for (const f of files) {
120
+ if (f.dir) continue
121
+ try { const st = statSync(f.p); rows.push({ p: f.p, size: st.size, mtime: st.mtimeMs, area: area.id }) } catch { /* ignore */ }
122
+ }
123
+ }
124
+ }
125
+ return rows
126
+ }
127
+
128
+ function human(n) {
129
+ const b = Number(n || 0)
130
+ if (b > 1024 ** 3) return (b / 1024 ** 3).toFixed(2) + 'GB'
131
+ if (b > 1024 ** 2) return (b / 1024 ** 2).toFixed(1) + 'MB'
132
+ return Math.max(0, Math.round(b / 1024)) + 'KB'
133
+ }
134
+
135
+ function allStats() {
136
+ const out = []
137
+ for (const area of CFG.areas || []) {
138
+ const files = collect(area)
139
+ const bytes = files.reduce((s, f) => s + (f.size || 0), 0)
140
+ const count = files.length && files[0].synthetic ? files[0].synthetic : files.length
141
+ out.push({ id: area.id, name: area.name, files: count, bytes, ttlDays: area.ttlDays, autoClean: !!area.autoClean, desc: area.desc, items: files })
142
+ }
143
+ return out
144
+ }
145
+
146
+ if (cmd === 'list') {
147
+ console.log('\n=== 存储分区(config/storage.json)===\n')
148
+ for (const a of CFG.areas || []) {
149
+ console.log(`${String(a.ttlDays || 0).padStart(3)}天 ${a.autoClean ? '可清理' : '只统计'} ${a.id.padEnd(12)} ${a.name}`)
150
+ console.log(` ${a.globs ? a.globs.join(' , ') : (a.osTemp || []).map((x) => '%TEMP%/' + x).join(' , ')}`)
151
+ if (a.desc) console.log(` ${a.desc}`)
152
+ }
153
+ console.log('')
154
+ process.exit(0)
155
+ }
156
+
157
+ if (cmd === 'stats') {
158
+ const rows = allStats()
159
+ if (flag('json')) { console.log(JSON.stringify(rows.map(({ items, ...r }) => r), null, 2)); process.exit(0) }
160
+ console.log('\n=== 占用 ===\n')
161
+ let total = 0
162
+ for (const r of rows) {
163
+ total += r.bytes
164
+ console.log(`${r.files.toString().padStart(5)} 个 ${human(r.bytes).padStart(9)} ${r.id.padEnd(12)} ${r.name}${r.autoClean ? '' : '(只统计)'}`)
165
+ }
166
+ console.log(`\n合计 ${human(total)};可自动清理: ${human(rows.filter((r) => r.autoClean).reduce((s, r) => s + r.bytes, 0))}\n`)
167
+ process.exit(0)
168
+ }
169
+
170
+ if (cmd === 'clean') {
171
+ const dry = flag('dry-run')
172
+ const jsonMode = flag('json')
173
+ const only = String(arg('area', '')).split(',').map((x) => x.trim()).filter(Boolean)
174
+ const olderThan = Number(arg('older-than', '0')) || 0
175
+ const now = Date.now()
176
+ const rows = allStats().filter((r) => (only.length ? only.includes(r.id) : r.autoClean))
177
+ const deleted = []
178
+ let freed = 0
179
+ for (const r of rows) {
180
+ const area = (CFG.areas || []).find((a) => a.id === r.id)
181
+ if (!area || !area.autoClean) { if (!jsonMode) console.log(`- 跳过 ${r.id}(只统计,不自动删)`); continue }
182
+ const ttl = olderThan || Number(area.ttlDays || 0)
183
+ if (!ttl) { if (!jsonMode) console.log(`- 跳过 ${r.id}(没设 TTL)`); continue }
184
+ const cutoff = now - ttl * 86400 * 1000
185
+ // keepNewest:不管多旧都至少保留最新 N 份(记忆库每日备份这类"宁可多留"的分区)
186
+ const keep = Number(area.keepNewest) || 0
187
+ let items = r.items
188
+ if (keep > 0 && items.length > keep) {
189
+ items = items.slice().sort((a, b) => (Number(b.mtime) || 0) - (Number(a.mtime) || 0)).slice(keep)
190
+ }
191
+ else if (keep > 0) {
192
+ items = []
193
+ }
194
+ for (const f of items) {
195
+ if (!f.mtime || f.mtime > cutoff) continue
196
+ try {
197
+ if (!dry) unlinkSync(f.p)
198
+ deleted.push({ area: r.id, path: toPosix(isAbsolute(f.p) ? f.p : join(ROOT, f.p)), size: f.size || 0 })
199
+ freed += f.size || 0
200
+ } catch { /* 被占用就下次再删 */ }
201
+ }
202
+ }
203
+ // 清理空目录(只碰可自动清理的分区,别去遍历 .models)
204
+ if (!dry) {
205
+ for (const area of CFG.areas || []) {
206
+ if (!area.autoClean) continue
207
+ for (const g of area.globs || []) {
208
+ const isData = String(g).startsWith('@data/')
209
+ const base = isData ? DATA_ROOT : ROOT
210
+ const top = join(base, (isData ? String(g).slice(6) : String(g)).split('/')[0])
211
+ if (!existsSync(top)) continue
212
+ for (const f of walk(top).sort((a, b) => b.p.length - a.p.length)) {
213
+ if (!f.dir) continue
214
+ try { if (readdirSync(f.p).length === 0) rmdirSync(f.p) } catch { /* ignore */ }
215
+ }
216
+ }
217
+ }
218
+ }
219
+ const reportDir = join(ROOT, 'out', 'reports')
220
+ if (!dry && deleted.length) {
221
+ mkdirSync(reportDir, { recursive: true })
222
+ const p = join(reportDir, 'storage-clean-' + new Date().toISOString().replace(/[:.]/g, '-') + '.json')
223
+ writeFileSync(p, JSON.stringify({ at: new Date().toISOString(), freed, count: deleted.length, items: deleted }, null, 1), 'utf8')
224
+ if (!flag('json')) console.log(`\n清单已写入 ${toPosix(relative(ROOT, p))}`)
225
+ }
226
+ if (flag('json')) {
227
+ // 2026-11-30:给设置页「缓存清理」按钮用(host 直接 parse)
228
+ console.log(JSON.stringify({ ok: true, dry, freed, count: deleted.length, deleted }))
229
+ process.exit(0)
230
+ }
231
+ console.log(`\n${dry ? '(演练,没删)' : ''}清理 ${deleted.length} 个文件,释放 ${human(freed)}`)
232
+ process.exit(0)
233
+ }
234
+
235
+ console.error('用法: node scripts/storage.mjs list | stats [--json] | clean [--area vision,tmp] [--older-than 3] [--dry-run]')
236
+ process.exit(1)
@@ -44,14 +44,37 @@ const __repoRoot = (() => {
44
44
  // 2026-11-14 起:profile 依赖改成相对路径 + local-plugins 软链,
45
45
  // 见 scripts/dsh-profile-links.mjs 的头注释(那次绝对路径 file: 直接触发过安全模式)。
46
46
 
47
- import { readdirSync, cpSync, existsSync, statSync } from 'node:fs'
48
- import { join, basename } from 'node:path'
47
+ import { readdirSync, cpSync, existsSync, statSync, mkdirSync, writeFileSync, realpathSync } from 'node:fs'
48
+ import { join, basename, dirname } from 'node:path'
49
49
 
50
50
  const profileArg = process.argv.indexOf('--profile')
51
- const PROF = profileArg >= 0 && process.argv[profileArg + 1]
51
+ const EXPLICIT_PROF = profileArg >= 0 && process.argv[profileArg + 1]
52
52
  ? process.argv[profileArg + 1]
53
- : join(process.env.APPDATA ?? '', 'dsh-desktop', 'harness', 'profiles', 'web')
54
- const PNPM = join(PROF, 'node_modules', '.pnpm')
53
+ : ''
54
+ const HARNESS = join(process.env.APPDATA ?? '', 'dsh-desktop', 'harness')
55
+ const PROFILES_ROOT = join(HARNESS, 'profiles')
56
+
57
+ /**
58
+ * 2026-12-01:DSH 0.14 起默认 profile 从 `web` 换成了 `desktop`(升级后依然保留旧 web 目录)。
59
+ * 以前这里写死 profiles/web → 同步全打到旧副本,实际运行的 desktop 副本还是旧代码,
60
+ * 表现出来就是「升级后插件功能缺失 / 新功能不生效」。
61
+ * 现在:显式 --profile 优先;否则把**所有装了 dsh-qqbot-muu 的 profile** 都同步一遍(desktop/web/…)。
62
+ */
63
+ function profileDirs() {
64
+ if (EXPLICIT_PROF) return [join(PROFILES_ROOT, EXPLICIT_PROF)]
65
+ const out = []
66
+ try {
67
+ for (const name of readdirSync(PROFILES_ROOT)) {
68
+ const p = join(PROFILES_ROOT, name)
69
+ const pnpm = join(p, 'node_modules', '.pnpm')
70
+ if (!existsSync(pnpm)) continue
71
+ const has = readdirSync(pnpm).some((x) => x.startsWith('dsh-qqbot-muu@'))
72
+ if (has) out.push(p)
73
+ }
74
+ } catch { /* 没有 profiles 就退回旧路径 */ }
75
+ if (!out.length) out.push(join(PROFILES_ROOT, 'web'))
76
+ return out
77
+ }
55
78
 
56
79
  /** [源路径, .pnpm 目录名前缀, 副本内相对路径(文件可省略,默认同名)] */
57
80
  const PAIRS = [
@@ -64,35 +87,87 @@ const PAIRS = [
64
87
  [__repoRoot() + "/dist", 'dsh-qqbot-muu@', 'dsh-qqbot-muu/dist'],
65
88
  [__repoRoot() + "/client", 'dsh-qqbot-muu@', 'dsh-qqbot-muu/client'],
66
89
  [__repoRoot() + "/settings-host.js", 'dsh-qqbot-muu@', 'dsh-qqbot-muu/settings-host.js'],
90
+ // 模块注册表(2026-11-28):host 的 /modules 路由读它;副本里没有会自动回落到内置兜底清单
91
+ [__repoRoot() + "/config/modules.json", 'dsh-qqbot-muu@', 'dsh-qqbot-muu/config/modules.json'],
92
+ // 模型注册表(2026-11-29):之前漏了这一份 —— 副本里的那份被一次空扫描写成了 1507 字节,
93
+ // host 读副本时"一个模型都没有",设置页只能看到 ollama 现查的 8b / 0.5b(主人反馈的那个 bug)。
94
+ [__repoRoot() + "/config/models.registry.json", 'dsh-qqbot-muu@', 'dsh-qqbot-muu/config/models.registry.json'],
95
+ // 存储分区表(2026-11-30):过程性文件(截图/OCR/转码/临时)的唯一目录地图,随包一起走
96
+ [__repoRoot() + "/config/storage.json", 'dsh-qqbot-muu@', 'dsh-qqbot-muu/config/storage.json'],
67
97
  // 两个子插件:整目录同步(2026-11-14 补上 dsh-xtc-muu,之前漏了,改小天才通道不生效)
68
98
  [__repoRoot() + "/dsh-wechat-muu", 'dsh-wechat-muu@', 'dsh-wechat-muu'],
69
99
  [__repoRoot() + "/dsh-xtc-muu", 'dsh-xtc-muu@', 'dsh-xtc-muu'],
70
100
  ]
71
101
 
72
- if (!existsSync(PNPM)) {
73
- console.error(`✗ 没有找到 pnpm 安装目录:${PNPM}`)
74
- console.error(' profile 还没装好?先跑:node scripts/dsh-profile-preflight.mjs --repair --install')
75
- process.exit(1)
102
+ /**
103
+ * 2026-12-01:desktop profile 的 `node_modules/dsh-qqbot-muu` 是个 Junction,实际指向
104
+ * web/.pnpm/... 那份副本。只同步本 profile 的 .pnpm 会出现「同步成功但运行没变」。
105
+ * 所以优先按软链真实指向定位目标;拿不到再退回 .pnpm 目录。
106
+ */
107
+ function packageTargets(PROF, prefix) {
108
+ if (prefix === 'dsh-qqbot-muu@') {
109
+ const link = join(PROF, 'node_modules', 'dsh-qqbot-muu')
110
+ try {
111
+ const real = realpathSync(link)
112
+ return [dirname(real)]
113
+ } catch { /* 不是软链/不存在 */ }
114
+ }
115
+ const pnpm = join(PROF, 'node_modules', '.pnpm')
116
+ if (!existsSync(pnpm)) return []
117
+ const hit = readdirSync(pnpm).filter((x) => x.startsWith(prefix)).sort().pop()
118
+ if (!hit) return []
119
+ return [join(pnpm, hit, 'node_modules')]
76
120
  }
77
121
 
78
122
  let bad = 0
79
- for (const [src, prefix, rel] of PAIRS) {
80
- if (!existsSync(src)) { console.log(`✗ 源不存在:${src}`); bad += 1; continue }
81
- const hit = readdirSync(PNPM).filter((x) => x.startsWith(prefix)).sort().pop()
82
- if (!hit) { console.log(`✗ 没找到安装副本:${prefix}`); bad += 1; continue }
83
- const root = join(PNPM, hit, 'node_modules')
84
- const dst = rel ? join(root, rel) : join(root, basename(src))
123
+ const profiles = profileDirs()
124
+ for (const PROF of profiles) {
125
+ const PNPM = join(PROF, 'node_modules', '.pnpm')
126
+ console.log(`\n── profile: ${PROF}`)
127
+ if (!existsSync(PNPM)) {
128
+ console.error(`✗ 没有找到 pnpm 安装目录:${PNPM}`)
129
+ console.error(' profile 还没装好?先跑:node scripts/dsh-profile-preflight.mjs --repair --install')
130
+ bad += 1
131
+ continue
132
+ }
133
+ for (const [src, prefix, rel] of PAIRS) {
134
+ if (!existsSync(src)) { console.log(`✗ 源不存在:${src}`); bad += 1; continue }
135
+ const targets = packageTargets(PROF, prefix)
136
+ if (!targets.length) { console.log(`✗ 没找到安装副本:${prefix}`); bad += 1; continue }
137
+ for (const root of targets) {
138
+ const dst = rel ? join(root, rel) : join(root, basename(src))
139
+ try {
140
+ if (statSync(src).isDirectory()) {
141
+ if (!existsSync(dst)) mkdirSync(dst, { recursive: true })
142
+ cpSync(src, dst, { recursive: true, force: true })
143
+ } else {
144
+ // 2026-11-28:新增的 config/modules.json 在副本里还没有父目录(旧副本不会自动出现),
145
+ // 这里补建父目录再拷,避免"第一次同步必失败"。
146
+ mkdirSync(join(dst, '..'), { recursive: true })
147
+ cpSync(src, dst, { force: true })
148
+ }
149
+ console.log(`✓ 已同步 ${rel || basename(src)} -> ${root}`)
150
+ } catch (e) {
151
+ console.log(`✗ 同步失败 ${rel || basename(src)}:${e?.message ?? e}`)
152
+ bad += 1
153
+ }
154
+ }
155
+ }
156
+ // 2026-11-30:给每个副本写一份「真实仓库根」指针。
157
+ // 副本里既没有 .models 也没有 services/,host 无论怎么猜都会落到副本自己身上,
158
+ // 于是读到副本那份被旧进程写空的注册表 → 面板只剩 1 个模型。
159
+ // host 里 resolveModelsRoot()/resolveServiceRoot()/data-root 会优先读这个文件并校验有效性。
85
160
  try {
86
- if (statSync(src).isDirectory()) {
87
- if (!existsSync(dst)) { console.log(`✗ 副本内路径不存在:${dst}`); bad += 1; continue }
88
- cpSync(src, dst, { recursive: true, force: true })
89
- } else {
90
- if (!existsSync(dst)) { console.log(`✗ 副本内文件不存在:${dst}`); bad += 1; continue }
91
- cpSync(src, dst, { force: true })
161
+ const hits = readdirSync(PNPM).filter((x) => x.startsWith('dsh-qqbot-muu@'))
162
+ for (const hit of hits) {
163
+ const cfgDir = join(PNPM, hit, 'node_modules', 'dsh-qqbot-muu', 'config')
164
+ mkdirSync(cfgDir, { recursive: true })
165
+ writeFileSync(join(cfgDir, 'repo-root.json'),
166
+ JSON.stringify({ root: __repoRoot(), updated: new Date().toISOString() }, null, 1), 'utf8')
92
167
  }
93
- console.log(`✓ 已同步 ${rel || basename(src)}`)
168
+ console.log(`✓ 已写仓库根指针(${hits.length} 个副本 → ${__repoRoot()})`)
94
169
  } catch (e) {
95
- console.log(`✗ 同步失败 ${rel || basename(src)}:${e?.message ?? e}`)
170
+ console.log(`✗ 写仓库根指针失败:${e?.message ?? e}`)
96
171
  bad += 1
97
172
  }
98
173
  }
@@ -0,0 +1,192 @@
1
+ # -*- coding: utf-8 -*-
2
+ """qq-whitelist 的离线单测:不启动浏览器。
3
+ 覆盖 1) ipconfig 解析/校园网优先 2) 幂等:同一 IP 连跑两次第二次必须 up-to-date
4
+ 3) 旧 IP 清理 4) _usable 过滤
5
+ 运行:E:\Anaconda\envs\ai25\python.exe F:\qqbot\scripts\tests\test-qq-whitelist.py
6
+ """
7
+ import importlib.util
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ MOD_PATH = Path(r"F:\qqbot\scripts\qq-whitelist.py")
12
+ spec = importlib.util.spec_from_file_location("qq_whitelist", str(MOD_PATH))
13
+ mod = importlib.util.module_from_spec(spec)
14
+ spec.loader.exec_module(mod)
15
+
16
+ fails = []
17
+
18
+
19
+ def check(name, cond, extra=""):
20
+ print(("PASS " if cond else "FAIL ") + name + ((" " + str(extra)) if extra else ""))
21
+ if not cond:
22
+ fails.append(name)
23
+
24
+
25
+ SAMPLE = """
26
+ Windows IP 配置
27
+
28
+ 以太网适配器 以太网 4:
29
+
30
+ 媒体状态 . . . . . . . . . . . . : 媒体已断开连接
31
+ IPv4 地址 . . . . . . . . . . . . : 169.254.61.110
32
+
33
+ 无线局域网适配器 WLAN 2:
34
+
35
+ IPv4 地址 . . . . . . . . . . . . : 10.198.183.69
36
+ 默认网关. . . . . . . . . . . . . : 10.198.255.254
37
+
38
+ 未知适配器 Tailscale:
39
+
40
+ IPv4 地址 . . . . . . . . . . . . : 100.126.113.49
41
+ 默认网关. . . . . . . . . . . . . :
42
+ """
43
+
44
+ adapters = mod.parse_ipconfig(SAMPLE)
45
+ names = [a["name"] for a in adapters]
46
+ check("parse_ipconfig 识别 3 个适配器", len(adapters) == 3, names)
47
+ wlan = [a for a in adapters if "WLAN 2" in a["name"]][0]
48
+ check("WLAN 2 解析出 10.198.183.69", wlan["ips"] == ["10.198.183.69"], wlan)
49
+ check("WLAN 2 识别默认网关", wlan["default_gw"] is True)
50
+ check("Tailscale 不当作可用地址", mod._usable("100.126.113.49") is False)
51
+ check("169.254 不当作可用地址", mod._usable("169.254.61.110") is False)
52
+ check("10.x 可用", mod._usable("10.198.183.69") is True)
53
+
54
+ # ---- 幂等:把取 IP 函数 mock 成固定值,连续跑两次
55
+ FAKE_IP = "10.198.183.69"
56
+ orig_get_ip = mod.get_current_ip
57
+ mod.get_current_ip = lambda verbose=False: FAKE_IP
58
+ try:
59
+ whitelist = ["1.2.3.4", "5.6.7.8"] # 机器上残留的旧 IP
60
+ plan1 = mod.plan_update(mod.get_current_ip(), whitelist)
61
+ check("第一次:判定需要更新", plan1["action"] == "update", plan1)
62
+ check("第一次:删除两条旧 IP", sorted(plan1["delete"]) == ["1.2.3.4", "5.6.7.8"], plan1)
63
+ check("第一次:添加当前 IP", plan1["add"] == [FAKE_IP], plan1)
64
+
65
+ whitelist = mod.apply_plan(whitelist, plan1) # 模拟页面保存成功
66
+ plan2 = mod.plan_update(mod.get_current_ip(), whitelist)
67
+ check("第二次:up-to-date(幂等)", plan2["action"] == "up-to-date", plan2)
68
+ check("第二次:无删除无添加", plan2["delete"] == [] and plan2["add"] == [], plan2)
69
+ check("第二次:保存后列表只剩当前 IP", whitelist == [FAKE_IP], whitelist)
70
+ finally:
71
+ mod.get_current_ip = orig_get_ip
72
+
73
+ # ---- 2026-11-27 起 prune 默认开:当前 IP 已在名单但还有历史 IP -> cleanup(只留最新真实 IP)
74
+ plan3 = mod.plan_update("10.0.0.9", ["10.0.0.9", "8.8.8.8"])
75
+ check("当前 IP 已存在但有历史残留 -> cleanup", plan3["action"] == "cleanup", plan3)
76
+ check("cleanup 删掉历史残留、不重复加当前 IP", plan3["delete"] == ["8.8.8.8"] and plan3["add"] == [], plan3)
77
+
78
+ # ---- 去重
79
+ plan4 = mod.plan_update("10.0.0.9", ["1.1.1.1", "1.1.1.1"])
80
+ check("重复旧 IP 去重", plan4["delete"] == ["1.1.1.1"], plan4)
81
+
82
+ # ================================================================ 登录态判定
83
+ # 2026-11-26 复盘:旧版日志打印「登录状态判断: login」,字面量 login 被误读成「已登录」,
84
+ # 实际含义是「需要登录」。下面这些用例锁住新语义:logged_in / need_login / unknown。
85
+ BODY_NEED = ("QQ登录 邮箱登录 密码登录 注册账号 意见反馈 系统公告 "
86
+ "机器人 QQ功能Skill库 游戏社区服务 QQ互联 QQ小程序小游戏 立即使用")
87
+ BODY_LOGGED = "我的机器人 管理机器人 开发设置 退出登录 MuUAstra 服务器 IP 白名单"
88
+ BODY_BLANK = "正在加载…"
89
+
90
+ cases = [
91
+ ("有鉴权 cookie + 已登录痕迹", BODY_LOGGED, "https://q.qq.com/#/", ["uin", "skey"], mod.LOGIN_LOGGED),
92
+ ("有鉴权 cookie + 页面无标记", BODY_BLANK, "https://q.qq.com/#/", ["skey"], mod.LOGIN_LOGGED),
93
+ ("有 cookie 但显示登录卡(cookie 失效)", BODY_NEED, "https://q.qq.com/#/", ["skey"], mod.LOGIN_NEED),
94
+ ("无 cookie + 登录卡(真实复现场景)", BODY_NEED, "https://q.qq.com/#/", [], mod.LOGIN_NEED),
95
+ # 2026-12-01:只剩 pt2gguin 这种弱 cookie 时,页面可能像后台,但实际已掉登录 → 要求扫码
96
+ ("无强 cookie + 已登录痕迹 -> need_login", BODY_LOGGED, "https://q.qq.com/#/", [], mod.LOGIN_NEED),
97
+ ("两样都没有 -> need_login(保守)", BODY_BLANK, "https://q.qq.com/#/", [], mod.LOGIN_NEED),
98
+ ("URL 停在 ptlogin -> need_login", BODY_BLANK, "https://xui.ptlogin2.qq.com/cgi-bin/xlogin", [], mod.LOGIN_NEED),
99
+ ("空 body 不崩 -> need_login", "", "", None, mod.LOGIN_NEED),
100
+ ]
101
+ for name, body, url, ck, want in cases:
102
+ got, detail = mod.detect_login_state(body, url, ck)
103
+ check("detect_login_state: " + name, got == want, "got=%s want=%s why=%s" % (got, want, detail.get("why")))
104
+
105
+ # qlogin_uid 在完全未登录时也存在,绝不能当登录依据
106
+ state_no_auth, d_no_auth = mod.detect_login_state(BODY_NEED, "", [])
107
+ check("detect_login_state: 无鉴权 cookie 不能判已登录", state_no_auth == mod.LOGIN_NEED, d_no_auth["why"])
108
+ check("AUTH_COOKIE_NAMES 不含 qlogin_uid", "qlogin_uid" not in mod.AUTH_COOKIE_NAMES, mod.AUTH_COOKIE_NAMES)
109
+ # 2026-12-01:pt2gguin 过期后仍存在,降级为弱 cookie,不能再单独当登录依据
110
+ check("AUTH_COOKIE_NAMES 不含 pt2gguin", "pt2gguin" not in mod.AUTH_COOKIE_NAMES, mod.AUTH_COOKIE_NAMES)
111
+ check("AUTH_COOKIE_NAMES 含 skey/uin", ("skey" in mod.AUTH_COOKIE_NAMES) and ("uin" in mod.AUTH_COOKIE_NAMES))
112
+
113
+
114
+ # ---- _frame_text / inspect_login 用假 page(不启动浏览器)
115
+ class FakeFrame:
116
+ def __init__(self, text):
117
+ self._t = text
118
+
119
+ def evaluate(self, js):
120
+ return self._t
121
+
122
+
123
+ class FakePage:
124
+ def __init__(self, body, url="https://q.qq.com/#/", frames=()):
125
+ self.body = body
126
+ self.url = url
127
+ self.main_frame = FakeFrame(body)
128
+ self.frames = [self.main_frame] + [FakeFrame(t) for t in frames]
129
+
130
+ def evaluate(self, js):
131
+ return self.body
132
+
133
+
134
+ fp = FakePage(BODY_BLANK, frames=[BODY_NEED])
135
+ check("_frame_text 合并 iframe 文本", "QQ登录" in mod._frame_text(fp))
136
+
137
+ _orig_probe = mod.probe_profile_cookies
138
+ mod.probe_profile_cookies = lambda profile_dir=None, use_cache=True: {
139
+ "ok": True, "db": "fake", "exists": True, "size": 32768,
140
+ "mtime": "2026-11-26 08:31:00", "total": 20, "qq_total": 10, "auth": [], "error": "",
141
+ }
142
+ try:
143
+ st, det = mod.inspect_login(FakePage(BODY_NEED))
144
+ check("inspect_login: 登录卡 + 空 auth -> need_login", st == mod.LOGIN_NEED, det.get("summary"))
145
+ check("inspect_login: detail 带 cookie 摘要", det["cookie"]["total"] == 20, det.get("cookie"))
146
+ st2, _ = mod.inspect_login(FakePage(BODY_LOGGED))
147
+ check("inspect_login: 只有弱 cookie 的已登录痕迹 -> need_login", st2 == mod.LOGIN_NEED, st2)
148
+ check("read_login_state 兼容包装仍可用", mod.read_login_state(FakePage(BODY_LOGGED)) == mod.LOGIN_NEED)
149
+ finally:
150
+ mod.probe_profile_cookies = _orig_probe
151
+
152
+ # ================================================================ cookie 库探测
153
+ import shutil
154
+ import sqlite3
155
+ import tempfile
156
+
157
+ tmp = Path(tempfile.mkdtemp(prefix="qqwl-test-cookies-"))
158
+ try:
159
+ net = tmp / "Default" / "Network"
160
+ net.mkdir(parents=True)
161
+ db = net / "Cookies"
162
+ con = sqlite3.connect(str(db))
163
+ con.execute("CREATE TABLE cookies (host_key TEXT, name TEXT, value TEXT)")
164
+ con.executemany("INSERT INTO cookies VALUES (?,?,?)", [
165
+ (".ptlogin2.qq.com", "qrsig", "x"),
166
+ (".ptlogin2.qq.com", "pt_local_token", "x"),
167
+ (".qq.com", "qlogin_uid", "x"), # 未登录也有,不能算鉴权
168
+ (".qq.com", "skey", "x"),
169
+ (".qq.com", "p_skey", "x"),
170
+ (".example.com", "uin", "x"), # 非 qq.com 域不算
171
+ ])
172
+ con.commit()
173
+ con.close()
174
+
175
+ info = mod.probe_profile_cookies(profile_dir=tmp, use_cache=False)
176
+ check("probe_profile_cookies: ok", info["ok"] is True, info.get("error"))
177
+ check("probe_profile_cookies: total=6", info["total"] == 6, info["total"])
178
+ check("probe_profile_cookies: qq_total=5", info["qq_total"] == 5, info["qq_total"])
179
+ check("probe_profile_cookies: auth 只有 skey/p_skey",
180
+ sorted(info["auth"]) == ["p_skey", "skey"], info["auth"])
181
+ check("probe_profile_cookies: 读出 mtime", bool(info["mtime"]))
182
+ finally:
183
+ shutil.rmtree(str(tmp), ignore_errors=True)
184
+
185
+ missing = mod.probe_profile_cookies(profile_dir=Path(tempfile.gettempdir()) / "not-exist-qqwl", use_cache=False)
186
+ check("probe_profile_cookies: 库不存在 -> ok=False 且不抛", missing["ok"] is False and bool(missing["error"]), missing)
187
+
188
+ print()
189
+ if fails:
190
+ print("FAILED:", len(fails), fails)
191
+ sys.exit(1)
192
+ print("ALL TESTS PASSED")