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,219 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * openid-audit.mjs —— 「openid ↔ 记录」核对(2026-12-01)
4
+ *
5
+ * 为什么要有:
6
+ * 主人反馈「有用户记忆错乱」。查下来根源不是模型,而是**身份键对不上**:
7
+ * · 早期私聊把 QQ 号当 scope(c2c:<QQ号>),后来微信桥又用 wxid、
8
+ * QQ 现在给的是 openid(c2c:<32位openid>)—— 同一个人在库里被拆成好几份记忆;
9
+ * · 昵称兜底值(对方/群友)把不同人的画像混在一起;
10
+ * · 甚至出现 self / bot / x 这种伪 sender_id。
11
+ * 这个脚本只读地跑一遍 memory.db,把人、scope、消息数、记忆数摆在一起,
12
+ * 同一昵称跨 scope / 同一 openid 多昵称 / 纯数字 scope / 幽灵记忆 全部标出来。
13
+ *
14
+ * 用法:
15
+ * node scripts/openid-audit.mjs # 读默认数据根
16
+ * node scripts/openid-audit.mjs --json # 机器可读(设置页用)
17
+ * node scripts/openid-audit.mjs --data <root> # 指定数据根
18
+ * node scripts/openid-audit.mjs --merge-scope c2c:<QQ号>=c2c:<openid> --apply
19
+ * # 把一个人分裂出去的 scope 并回来(会先备份)
20
+ */
21
+ import { existsSync, copyFileSync } from 'node:fs'
22
+ import { join, resolve } from 'node:path'
23
+ import { createRequire } from 'node:module'
24
+
25
+ const requireSqlite = createRequire(import.meta.url)
26
+
27
+ const PRETTY_BOT = new Set(['小蓝', 'self', 'bot', '她'])
28
+ const PSEUDO_ID = new Set(['self', 'bot', 'x', '对方', '群友', '未知', ''])
29
+
30
+ export function defaultDbPath(repoRoot) {
31
+ const cands = []
32
+ const env = String(process.env.QQBOT_MEMORY_DATA_ROOT || '').trim()
33
+ if (env) cands.push(join(env, '.qqbot', 'memory.db'))
34
+ if (repoRoot) cands.push(join(repoRoot, 'dshqqbot', '.qqbot', 'memory.db'))
35
+ cands.push(join(process.cwd(), 'dshqqbot', '.qqbot', 'memory.db'))
36
+ return cands.find((p) => { try { return existsSync(p) } catch { return false } }) || cands[0]
37
+ }
38
+
39
+ function openDb(dbPath, readOnly) {
40
+ // 延迟 require:老 Node(<22.5)没有 node:sqlite,报错也只影响这一个功能
41
+ const { DatabaseSync } = requireSqlite('node:sqlite')
42
+ return new DatabaseSync(dbPath, { readOnly })
43
+ }
44
+
45
+ const isNumericId = (s) => /^\d{5,12}$/.test(String(s || ''))
46
+ const isOpenid = (s) => /^[0-9A-F]{32}$/i.test(String(s || ''))
47
+ const isWxid = (s) => /^wxid_/i.test(String(s || ''))
48
+
49
+ /** 只读核对;返回 { ok, dbPath, scopes, people, issues, stats } */
50
+ export function auditIdentity(dbPath) {
51
+ if (!existsSync(dbPath)) return { ok: false, error: `找不到 memory.db:${dbPath}` }
52
+ const db = openDb(dbPath, true)
53
+ const all = (sql) => { try { return db.prepare(sql).all() } catch { return [] } }
54
+ const people = all(`select scope, sender_id, sender, count(*) c, min(ts) f, max(ts) l
55
+ from chat where sender_id is not null and sender_id <> ''
56
+ group by scope, sender_id`)
57
+ const memByScope = new Map(all('select scope, count(*) c from mem group by scope').map((r) => [String(r.scope), r.c]))
58
+ const chatByScope = new Map(all('select scope, count(*) c from chat group by scope').map((r) => [String(r.scope), r.c]))
59
+ const scopes = [...new Set([...chatByScope.keys(), ...memByScope.keys()])].sort().map((s) => ({
60
+ scope: s,
61
+ chat: chatByScope.get(s) || 0,
62
+ mem: memByScope.get(s) || 0,
63
+ }))
64
+
65
+ // 同一个人的多份身份:按 sender_id 聚合,记录它出现在哪些 scope、用过哪些名字
66
+ const byId = new Map()
67
+ for (const p of people) {
68
+ const id = String(p.sender_id)
69
+ const e = byId.get(id) || { id, names: new Set(), scopes: new Set(), chat: 0, lastTs: 0 }
70
+ if (p.sender) e.names.add(String(p.sender))
71
+ e.scopes.add(String(p.scope))
72
+ e.chat += Number(p.c) || 0
73
+ e.lastTs = Math.max(e.lastTs, Number(p.l) || 0)
74
+ byId.set(id, e)
75
+ }
76
+ const byName = new Map()
77
+ for (const e of byId.values()) {
78
+ for (const n of e.names) {
79
+ if (PRETTY_BOT.has(n) || PSEUDO_ID.has(n)) continue
80
+ const list = byName.get(n) || []
81
+ list.push(e.id)
82
+ byName.set(n, list)
83
+ }
84
+ }
85
+
86
+ const issues = []
87
+ for (const [name, ids] of byName) {
88
+ if (ids.length > 1) {
89
+ issues.push({
90
+ level: 'warn', kind: 'name-split',
91
+ msg: `昵称「${name}」对应 ${ids.length} 个身份键,记忆可能被拆开(多半是 QQ号/openid/wxid 各存了一份)`,
92
+ ids,
93
+ })
94
+ }
95
+ }
96
+ for (const e of byId.values()) {
97
+ if (PSEUDO_ID.has(e.id)) {
98
+ issues.push({ level: 'warn', kind: 'pseudo-id', msg: `身份键是占位值「${e.id}」,这些记录没法归属到具体的人`, ids: [e.id] })
99
+ }
100
+ const real = [...e.names].filter((n) => !PSEUDO_ID.has(n))
101
+ if (real.length > 1) {
102
+ issues.push({ level: 'info', kind: 'multi-alias', msg: `身份 ${e.id.slice(0, 8)}… 有多个昵称:${real.join(' / ')}`, ids: [e.id] })
103
+ }
104
+ if (e.scopes.size > 1) {
105
+ issues.push({
106
+ level: 'warn', kind: 'multi-scope',
107
+ msg: `${[...real][0] || e.id} 同时出现在 ${e.scopes.size} 个 scope(${[...e.scopes].join(' , ')}),私聊/群聊记忆没有统一`,
108
+ ids: [e.id],
109
+ })
110
+ }
111
+ }
112
+ for (const s of scopes) {
113
+ const tail = String(s.scope).split(':').pop()
114
+ if (isNumericId(tail)) {
115
+ const same = [...byName.entries()].find(([, ids]) => ids.includes(tail))
116
+ issues.push({
117
+ level: 'warn', kind: 'numeric-scope',
118
+ msg: `scope ${s.scope} 用的是 QQ 号(不是 openid)${same ? `,同名身份还有 ${same[1].filter((x) => x !== tail).join(' , ')}` : ''} → 换号/换端后会变成"另一个人"`,
119
+ ids: same ? same[1] : [tail],
120
+ })
121
+ }
122
+ if (isWxid(tail) && String(s.scope).startsWith('c2c:')) {
123
+ issues.push({ level: 'warn', kind: 'cross-channel', msg: `微信 id ${tail} 出现在 QQ 私聊 scope 里(跨渠道合并,需确认是否有意)`, ids: [tail] })
124
+ }
125
+ if (s.mem > 0 && s.chat === 0) {
126
+ issues.push({ level: 'info', kind: 'ghost-mem', msg: `scope ${s.scope} 有 ${s.mem} 条记忆但没有任何聊天记录(孤儿记忆)`, ids: [s.scope] })
127
+ }
128
+ }
129
+
130
+ const peopleOut = [...byId.values()]
131
+ .map((e) => {
132
+ const sc = [...e.scopes]
133
+ return {
134
+ id: e.id,
135
+ names: [...e.names],
136
+ scopes: sc,
137
+ chat: e.chat,
138
+ mem: sc.reduce((a, s) => a + (memByScope.get(s) || 0), 0),
139
+ lastTs: e.lastTs,
140
+ pseudo: PSEUDO_ID.has(e.id),
141
+ }
142
+ })
143
+ .sort((a, b) => b.chat - a.chat)
144
+
145
+ return {
146
+ ok: true,
147
+ dbPath,
148
+ stats: { scopes: scopes.length, people: peopleOut.length, chat: [...chatByScope.values()].reduce((a, b) => a + b, 0), mem: [...memByScope.values()].reduce((a, b) => a + b, 0) },
149
+ scopes,
150
+ people: peopleOut,
151
+ issues,
152
+ }
153
+ }
154
+
155
+ /** 把 from 这个 scope 的所有记录并到 to(可选,需显式 --apply) */
156
+ export function mergeScope(dbPath, from, to, apply) {
157
+ if (!from || !to || from === to) throw new Error('用法:--merge-scope <旧scope>=<新scope>')
158
+ if (!apply) return { ok: true, dryRun: true, from, to }
159
+ const bak = `${dbPath}.bak-merge-${Date.now()}`
160
+ copyFileSync(dbPath, bak)
161
+ const db = openDb(dbPath, false)
162
+ const tables = ['chat', 'mem', 'mem_tag', 'mem_entity', 'mem_edge', 'mem_gist', 'mem_link', 'belief', 'persona', 'mem_channel']
163
+ const moved = {}
164
+ db.exec('BEGIN')
165
+ try {
166
+ for (const t of tables) {
167
+ try {
168
+ const r = db.prepare(`UPDATE ${t} SET scope = ? WHERE scope = ?`).run(to, from)
169
+ moved[t] = Number(r?.changes ?? 0)
170
+ } catch { moved[t] = 0 }
171
+ }
172
+ db.exec('COMMIT')
173
+ } catch (e) {
174
+ try { db.exec('ROLLBACK') } catch { /* ignore */ }
175
+ throw e
176
+ }
177
+ return { ok: true, applied: true, from, to, moved, backup: bak }
178
+ }
179
+
180
+ function fmt(ts) {
181
+ if (!ts) return '-'
182
+ const d = new Date(ts > 1e12 ? ts : ts * 1000)
183
+ return `${d.getMonth() + 1}/${d.getDate()}`
184
+ }
185
+
186
+ function main(argv) {
187
+ const args = argv.slice(2)
188
+ const has = (k) => args.includes(k)
189
+ const val = (k) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : '' }
190
+ const dataRoot = val('--data')
191
+ const dbPath = dataRoot ? join(resolve(dataRoot), '.qqbot', 'memory.db') : defaultDbPath(process.cwd())
192
+ const mergeIdx = args.indexOf('--merge-scope')
193
+ if (mergeIdx >= 0) {
194
+ const [from, to] = String(args[mergeIdx + 1] || '').split('=')
195
+ const r = mergeScope(dbPath, from, to, has('--apply'))
196
+ console.log(JSON.stringify(r, null, 2))
197
+ if (!r.applied) console.log('\n(这是预演。确认无误后加 --apply 真合并;合并前会自动备份)')
198
+ return
199
+ }
200
+ const r = auditIdentity(dbPath)
201
+ if (has('--json')) { console.log(JSON.stringify(r, null, 2)); return }
202
+ if (!r.ok) { console.error(r.error); process.exitCode = 2; return }
203
+ console.log(`数据:${r.dbPath}`)
204
+ console.log(`scope ${r.stats.scopes} 个 · 身份 ${r.stats.people} 个 · 聊天 ${r.stats.chat} 条 · 记忆 ${r.stats.mem} 条\n`)
205
+ console.log('身份'.padEnd(34) + '昵称'.padEnd(18) + 'scope'.padEnd(8) + '消息'.padStart(6) + '记忆'.padStart(6) + ' 最后')
206
+ for (const p of r.people.slice(0, 40)) {
207
+ const id = p.pseudo ? `⚠ ${p.id}` : p.id
208
+ console.log(
209
+ String(id).padEnd(34) +
210
+ (p.names.join('/').slice(0, 16) || '-').padEnd(18) +
211
+ String(p.scopes.length).padEnd(8) +
212
+ String(p.chat).padStart(6) + String(p.mem).padStart(6) + ' ' + fmt(p.lastTs),
213
+ )
214
+ }
215
+ console.log(`\n可疑项 ${r.issues.length} 条:`)
216
+ for (const it of r.issues) console.log(` [${it.level}] ${it.msg}`)
217
+ }
218
+
219
+ if (process.argv[1] && /openid-audit\.mjs$/.test(process.argv[1].replace(/\\/g, '/'))) main(process.argv)
@@ -0,0 +1,127 @@
1
+ # -*- coding: utf-8 -*-
2
+ """pull-gguf.py —— 从 hf-mirror 下载权重,支持断点续传/重试(给画质档模型用)。
3
+
4
+ 相比 huggingface_hub:hf 的 xet 通道在本机会超时,镜像又会 429;这里直接走
5
+ HTTP Range 续传(镜像支持 206),失败退避重试,进度写日志。
6
+
7
+ 用法:
8
+ python scripts/pull-gguf.py # 下清单里缺的文件
9
+ python scripts/pull-gguf.py --list
10
+ python scripts/pull-gguf.py --only krea
11
+ """
12
+ import argparse
13
+ import os
14
+ import sys
15
+ import time
16
+ import urllib.request
17
+
18
+ BASE = "https://hf-mirror.com"
19
+ DEST = r"F:\qqbot\.models"
20
+ LOG = r"F:\qqbot\logs\pull-gguf.log"
21
+
22
+ # (repo, 文件名, 完整体积, 落到哪个子目录)
23
+ # 注意:文本编码器必须落在 flux-schnell-gguf(ComfyUI 的 clip/text_encoders 搜索路径里只有它和 wan),
24
+ # unet 落在 flux-dev-gguf(unet 搜索路径包含两个目录)。
25
+ JOBS = [
26
+ ("city96/FLUX.1-dev-gguf", "flux1-dev-Q8_0.gguf", 12708281504, "flux-dev-gguf"),
27
+ ("city96/t5-v1_1-xxl-encoder-gguf", "t5-v1_1-xxl-encoder-Q8_0.gguf", 5056000000, "flux-schnell-gguf"),
28
+ ("QuantStack/FLUX.1-Krea-dev-GGUF", "flux1-krea-dev-Q8_0.gguf", 12500000000, "flux-dev-gguf"),
29
+ ]
30
+
31
+
32
+ def log(msg):
33
+ line = "%s %s" % (time.strftime("%H:%M:%S"), msg)
34
+ print(line, flush=True)
35
+ try:
36
+ os.makedirs(os.path.dirname(LOG), exist_ok=True)
37
+ with open(LOG, "a", encoding="utf-8") as f:
38
+ f.write(line + "\n")
39
+ except OSError:
40
+ pass
41
+
42
+
43
+ def fetch(url, path, retries=40):
44
+ """下载 url 到 path,已存在的部分自动续传。"""
45
+ part = path + ".part"
46
+ for attempt in range(1, retries + 1):
47
+ have = os.path.getsize(part) if os.path.exists(part) else 0
48
+ req = urllib.request.Request(url, headers={"User-Agent": "curl/8.5.0"})
49
+ if have:
50
+ req.add_header("Range", "bytes=%d-" % have)
51
+ try:
52
+ with urllib.request.urlopen(req, timeout=60) as r:
53
+ total = None
54
+ if r.status == 206:
55
+ cr = r.headers.get("Content-Range", "")
56
+ if "/" in cr:
57
+ total = int(cr.rsplit("/", 1)[1])
58
+ mode = "ab"
59
+ else:
60
+ total = int(r.headers.get("Content-Length") or 0) or None
61
+ have = 0
62
+ mode = "wb"
63
+ if os.path.exists(part):
64
+ os.remove(part)
65
+ t0 = time.time()
66
+ base = have
67
+ last = t0
68
+ with open(part, mode) as f:
69
+ while True:
70
+ chunk = r.read(1024 * 1024)
71
+ if not chunk:
72
+ break
73
+ f.write(chunk)
74
+ have += len(chunk)
75
+ if time.time() - last > 15:
76
+ speed = (have - base) / max(1e-6, time.time() - last) / 1048576
77
+ last = time.time()
78
+ pct = ("%.1f%%" % (have * 100.0 / total)) if total else "?"
79
+ log(" %s %s / %s %s %.1f MB/s" % (os.path.basename(path),
80
+ "%.2fGB" % (have / 1024 ** 3),
81
+ "%.2fGB" % (total / 1024 ** 3) if total else "?",
82
+ pct, speed))
83
+ got = os.path.getsize(part) if os.path.exists(part) else 0
84
+ if total and got >= total:
85
+ os.replace(part, path)
86
+ return got
87
+ log(" 未完整 (%d/%s),第 %d 次重试" % (got, total, attempt))
88
+ except Exception as e:
89
+ log(" 出错 %s: %s(第 %d 次,退避 5s)" % (type(e).__name__, str(e)[:120], attempt))
90
+ time.sleep(5)
91
+ return 0
92
+
93
+
94
+ def main():
95
+ ap = argparse.ArgumentParser()
96
+ ap.add_argument("--list", action="store_true")
97
+ ap.add_argument("--only", default="")
98
+ a = ap.parse_args()
99
+ if a.list:
100
+ for repo, name, min_bytes, sub in JOBS:
101
+ p = os.path.join(DEST, sub, name)
102
+ part = p + ".part"
103
+ if os.path.exists(p) and os.path.getsize(p) >= min_bytes:
104
+ state = "ok %.2fGB" % (os.path.getsize(p) / 1024 ** 3)
105
+ elif os.path.exists(part):
106
+ state = "downloading %.2fGB" % (os.path.getsize(part) / 1024 ** 3)
107
+ else:
108
+ state = "missing"
109
+ print("%-45s %-34s %-20s %s" % (repo, name, sub, state))
110
+ return 0
111
+ for repo, name, min_bytes, sub in JOBS:
112
+ if a.only and a.only not in name:
113
+ continue
114
+ os.makedirs(os.path.join(DEST, sub), exist_ok=True)
115
+ path = os.path.join(DEST, sub, name)
116
+ if os.path.exists(path) and os.path.getsize(path) >= min_bytes:
117
+ log("[skip] %s 已完整" % name)
118
+ continue
119
+ log("[start] %s" % name)
120
+ size = fetch("%s/%s/resolve/main/%s" % (BASE, repo, name), path)
121
+ log("[done] %s %.2f GB" % (name, size / 1024 ** 3) if size else "[fail] %s" % name)
122
+ log("ALL DONE")
123
+ return 0
124
+
125
+
126
+ if __name__ == "__main__":
127
+ sys.exit(main())
@@ -0,0 +1,151 @@
1
+ # -*- coding: utf-8 -*-
2
+ """purge-standby.py —— 直接调用 NtSetSystemInformation(MemoryPurgeStandbyList) 清空待机列表。
3
+
4
+ 改动(2026-11-27):
5
+ - 读待机列表改用 PDH 原生接口,不再 subprocess 调 powershell.exe
6
+ (原实现每次会在 pythonw 下弹出一个控制台窗口,两次采样就是两次闪烁)
7
+ - 增加阈值判断:待机列表低于 --min-gb 时直接退出,不做无意义的清缓存
8
+ 需管理员权限(计划任务以 Highest 运行)。日志: F:\\qqbot\\logs\\standby-purge.log
9
+ 用法: python purge-standby.py [--quiet] [--min-gb 4]
10
+ """
11
+ import ctypes
12
+ import os
13
+ import sys
14
+ import time
15
+ from ctypes import wintypes
16
+
17
+ LOG = r"F:\qqbot\logs\standby-purge.log"
18
+ STATUS_SUCCESS = 0
19
+ MB = 1048576.0
20
+
21
+ system_info = ctypes.WinDLL("ntdll").NtSetSystemInformation
22
+ pdh = ctypes.WinDLL("pdh")
23
+
24
+ PDH_FMT_DOUBLE = 0x00000200
25
+ COUNTER_PATH = "\\Memory\\Standby Cache Normal Priority Bytes"
26
+
27
+
28
+ class PDH_FMT_COUNTERVALUE(ctypes.Structure):
29
+ _fields_ = [("CStatus", wintypes.DWORD), ("doubleValue", ctypes.c_double)]
30
+
31
+
32
+ def mem_status():
33
+ class MEMORYSTATUSEX(ctypes.Structure):
34
+ _fields_ = [("dwLength", wintypes.DWORD), ("dwMemoryLoad", wintypes.DWORD),
35
+ ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong),
36
+ ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong),
37
+ ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong),
38
+ ("ullAvailExtendedVirtual", ctypes.c_ulonglong)]
39
+
40
+ ms = MEMORYSTATUSEX()
41
+ ms.dwLength = ctypes.sizeof(ms)
42
+ ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(ms))
43
+ return ms
44
+
45
+
46
+ def standby_mb() -> float:
47
+ """用 PDH 进程内读性能计数器,不产生任何子进程/窗口。"""
48
+ query = wintypes.HANDLE()
49
+ counter = wintypes.HANDLE()
50
+ try:
51
+ if pdh.PdhOpenQueryW(None, 0, ctypes.byref(query)) != 0:
52
+ raise OSError("PdhOpenQuery failed")
53
+ # AddEnglishCounter 避免中文系统上英文计数器名匹配不到
54
+ if pdh.PdhAddEnglishCounterW(query, COUNTER_PATH, 0, ctypes.byref(counter)) != 0:
55
+ raise OSError("PdhAddEnglishCounter failed")
56
+ if pdh.PdhCollectQueryData(query) != 0:
57
+ raise OSError("PdhCollectQueryData failed")
58
+ val = PDH_FMT_COUNTERVALUE()
59
+ if pdh.PdhGetFormattedCounterValue(counter, PDH_FMT_DOUBLE, None, ctypes.byref(val)) != 0:
60
+ raise OSError("PdhGetFormattedCounterValue failed")
61
+ return val.doubleValue / MB
62
+ except Exception:
63
+ ms = mem_status()
64
+ return (ms.ullTotalPhys - ms.ullAvailPhys) / MB
65
+ finally:
66
+ if query:
67
+ pdh.PdhCloseQuery(query)
68
+
69
+
70
+ def enable_privilege(name: str = "SeProfileSingleProcessPrivilege") -> bool:
71
+ adv32 = ctypes.WinDLL("advapi32", use_last_error=True)
72
+ k32 = ctypes.WinDLL("kernel32", use_last_error=True)
73
+
74
+ class LUID(ctypes.Structure):
75
+ _fields_ = [("LowPart", wintypes.DWORD), ("HighPart", wintypes.LONG)]
76
+
77
+ class LUID_AND_ATTRIBUTES(ctypes.Structure):
78
+ _fields_ = [("Luid", LUID), ("Attributes", wintypes.DWORD)]
79
+
80
+ class TOKEN_PRIVILEGES(ctypes.Structure):
81
+ _fields_ = [("PrivilegeCount", wintypes.DWORD), ("Privileges", LUID_AND_ATTRIBUTES * 1)]
82
+
83
+ adv32.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]
84
+ adv32.OpenProcessToken.restype = wintypes.BOOL
85
+ adv32.LookupPrivilegeValueW.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, ctypes.POINTER(LUID)]
86
+ adv32.LookupPrivilegeValueW.restype = wintypes.BOOL
87
+ adv32.AdjustTokenPrivileges.argtypes = [wintypes.HANDLE, wintypes.BOOL, ctypes.POINTER(TOKEN_PRIVILEGES),
88
+ wintypes.DWORD, ctypes.c_void_p, ctypes.c_void_p]
89
+ adv32.AdjustTokenPrivileges.restype = wintypes.BOOL
90
+ k32.GetCurrentProcess.restype = wintypes.HANDLE
91
+ k32.CloseHandle.argtypes = [wintypes.HANDLE]
92
+
93
+ token = wintypes.HANDLE()
94
+ if not adv32.OpenProcessToken(k32.GetCurrentProcess(), 0x0020 | 0x0008, ctypes.byref(token)):
95
+ return False
96
+ luid = LUID()
97
+ if not adv32.LookupPrivilegeValueW(None, name, ctypes.byref(luid)):
98
+ k32.CloseHandle(token)
99
+ return False
100
+ tp = TOKEN_PRIVILEGES()
101
+ tp.PrivilegeCount = 1
102
+ tp.Privileges[0].Luid = luid
103
+ tp.Privileges[0].Attributes = 0x00000002 # SE_PRIVILEGE_ENABLED
104
+ ok = bool(adv32.AdjustTokenPrivileges(token, False, ctypes.byref(tp), 0, None, None))
105
+ k32.CloseHandle(token)
106
+ return ok
107
+
108
+
109
+ def purge() -> int:
110
+ enable_privilege()
111
+ cmd = ctypes.c_uint(4) # MemoryPurgeStandbyList
112
+ system_info.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_ulong]
113
+ system_info.restype = ctypes.c_long
114
+ status = system_info(80, ctypes.byref(cmd), ctypes.sizeof(cmd)) # SystemMemoryListInformation = 80
115
+ return int(status)
116
+
117
+
118
+ def main() -> int:
119
+ quiet = "--quiet" in sys.argv
120
+ min_gb = 8.0
121
+ for i, a in enumerate(sys.argv):
122
+ if a == "--min-gb" and i + 1 < len(sys.argv):
123
+ try:
124
+ min_gb = float(sys.argv[i + 1])
125
+ except ValueError:
126
+ pass
127
+
128
+ before = standby_mb()
129
+ if before < min_gb * 1024:
130
+ if not quiet:
131
+ print("standby %.0fMB below %.1fGB, skip" % (before, min_gb))
132
+ return 0
133
+
134
+ st = purge()
135
+ time.sleep(1)
136
+ after = standby_mb()
137
+ line = "%s purge status=%d standby %.0fMB -> %.0fMB (freed %.0fMB)\n" % (
138
+ time.strftime("%Y-%m-%d %H:%M:%S"), st, before, after, before - after)
139
+ try:
140
+ os.makedirs(os.path.dirname(LOG), exist_ok=True)
141
+ with open(LOG, "a", encoding="utf-8") as f:
142
+ f.write(line)
143
+ except Exception:
144
+ pass
145
+ if not quiet:
146
+ print(line.strip())
147
+ return 0 if st == STATUS_SUCCESS else 1
148
+
149
+
150
+ if __name__ == "__main__":
151
+ sys.exit(main())
@@ -0,0 +1,133 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """qq-connect-login.py — 打开机器人的新控制台(connect.qq.com/open-platform)并等待登录
4
+
5
+ 背景(2026-12-03):旧控制台 https://q.qq.com/qqbot/dashboard/ 已经全部 302 回首页,
6
+ 脚本里"找机器人列表"的逻辑永远失败(rc=20)。机器人管理迁到了 connect.qq.com 的
7
+ 「AI 开发者管理平台」,而且这个域要单独登录一次。
8
+
9
+ 这个脚本只做两件事:
10
+ 1. 用专用 profile 打开新控制台,若未登录就点「立即登录」(扫码由本人完成,无法代劳);
11
+ 2. 登录成功后把控制台结构和截图 dump 到 logs,供下一步自动改 IP 白名单用。
12
+
13
+ 用法:python scripts/qq-connect-login.py [--wait 600]
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import json
19
+ import os
20
+ import time
21
+ from pathlib import Path
22
+
23
+ BASE = Path(os.environ.get("QQBOT_REPO_ROOT") or Path(__file__).resolve().parent.parent)
24
+ PROFILE = BASE / "data" / "edge-profile"
25
+ LOGS = BASE / "logs"
26
+ SHOTS = LOGS / "qq-connect-shots"
27
+ HOME = "https://connect.qq.com/open-platform/home"
28
+
29
+
30
+ def log(tag: str, msg: str) -> None:
31
+ line = f"{time.strftime('%Y-%m-%d %H:%M:%S')} [{tag}] {msg}"
32
+ print(line, flush=True)
33
+ try:
34
+ LOGS.mkdir(parents=True, exist_ok=True)
35
+ with open(LOGS / "qq-connect.log", "a", encoding="utf-8") as f:
36
+ f.write(line + "\n")
37
+ except Exception:
38
+ pass
39
+
40
+
41
+ def shot(page, tag: str) -> str:
42
+ SHOTS.mkdir(parents=True, exist_ok=True)
43
+ p = SHOTS / f"{time.strftime('%Y%m%d-%H%M%S')}-{tag}.png"
44
+ try:
45
+ page.screenshot(path=str(p))
46
+ except Exception:
47
+ pass
48
+ return str(p)
49
+
50
+
51
+ def main() -> int:
52
+ ap = argparse.ArgumentParser()
53
+ ap.add_argument("--wait", type=int, default=600)
54
+ a = ap.parse_args()
55
+
56
+ from playwright.sync_api import sync_playwright
57
+
58
+ with sync_playwright() as p:
59
+ ctx = p.chromium.launch_persistent_context(
60
+ str(PROFILE), channel="msedge", headless=False,
61
+ viewport={"width": 1440, "height": 900}, locale="zh-CN", timezone_id="Asia/Shanghai",
62
+ args=["--disable-blink-features=AutomationControlled", "--no-first-run", "--start-maximized"],
63
+ )
64
+ page = ctx.pages[0] if ctx.pages else ctx.new_page()
65
+ page.set_default_timeout(15000)
66
+ try:
67
+ page.goto(HOME, wait_until="domcontentloaded", timeout=45000)
68
+ page.wait_for_timeout(3000)
69
+ body = page.inner_text("body")
70
+ if "请先登录" in body or "登录后即可" in body:
71
+ log("login", "未登录,点击「立即登录」——请用手机 QQ 扫码(只需这一次)")
72
+ try:
73
+ page.locator("text=立即登录").first.click(timeout=6000)
74
+ except Exception as e:
75
+ log("login", f"点登录失败: {e}")
76
+ page.wait_for_timeout(4000)
77
+ try:
78
+ page.evaluate("window.focus()")
79
+ except Exception:
80
+ pass
81
+ shot(page, "need-scan")
82
+ deadline = time.time() + a.wait
83
+ nxt = time.time() + 20
84
+ while time.time() < deadline:
85
+ try:
86
+ if len(ctx.pages) > 1:
87
+ page = ctx.pages[-1]
88
+ txt = page.inner_text("body")
89
+ if "请先登录" not in txt and "登录后即可" not in txt and "扫码" not in txt:
90
+ log("login", f"LOGIN_OK url={page.url}")
91
+ break
92
+ except Exception:
93
+ pass
94
+ if time.time() >= nxt:
95
+ shot(page, "wait")
96
+ log("login", f"等待扫码… 还剩 {int(deadline - time.time())}s")
97
+ nxt = time.time() + 25
98
+ page.wait_for_timeout(1500)
99
+ else:
100
+ log("login", "等待超时,未登录")
101
+ return 10
102
+ else:
103
+ log("login", "已经是登录状态")
104
+
105
+ # 登录后:把控制台结构摸出来(下一步据此自动改 IP 白名单)
106
+ try:
107
+ pages = [x.url for x in ctx.pages]
108
+ log("page", "当前标签页: " + json.dumps(pages, ensure_ascii=False))
109
+ page.goto("https://connect.qq.com/open-platform/home", wait_until="domcontentloaded", timeout=40000)
110
+ page.wait_for_timeout(5000)
111
+ txt = page.inner_text("body")
112
+ log("page", f"url={page.url}")
113
+ log("page", "TEXT=" + txt[:600].replace("\n", " | "))
114
+ hrefs = page.eval_on_selector_all("a", "els => els.map(e => (e.getAttribute('href')||'') + ' :: ' + (e.innerText||'').trim().slice(0,24))")
115
+ seen, uniq = set(), []
116
+ for h in hrefs:
117
+ if h and h not in seen:
118
+ seen.add(h)
119
+ uniq.append(h)
120
+ log("page", "LINKS=" + json.dumps(uniq[:30], ensure_ascii=False))
121
+ log("shot", shot(page, "console"))
122
+ except Exception as e:
123
+ log("page", f"dump 控制台失败: {e}")
124
+ return 0
125
+ finally:
126
+ try:
127
+ ctx.close()
128
+ except Exception:
129
+ pass
130
+
131
+
132
+ if __name__ == "__main__":
133
+ raise SystemExit(main())
@@ -0,0 +1,5 @@
1
+ ' 开机静默自检:出口 IP 变了就自动改机器人白名单(不弹窗、不扫码)
2
+ ' 由 Startup 文件夹的快捷方式在登录时调用;失败只写 logs\qq-ip-sync.log
3
+ Set sh = CreateObject("WScript.Shell")
4
+ sh.CurrentDirectory = "F:\qqbot"
5
+ sh.Run """E:\Anaconda\envs\ai25\python.exe"" -u ""F:\qqbot\scripts\qq-ip-sync.py"" --sync", 0, False