dsh-qqbot-muu 0.1.20 → 0.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +168 -154
- package/client/qqbot-settings.js +13401 -13380
- package/dist/config.js +573 -581
- package/dist/features/contextless-store.js +247 -247
- package/dist/features/four-source.js +338 -336
- package/dist/features/group-join-request.js +289 -287
- package/dist/features/local-models.js +1494 -1467
- package/dist/features/style-layer.js +501 -498
- package/dist/features/thinking-log.js +71 -69
- package/dist/gateway/bootstrap.js +1704 -1652
- package/dist/model/settings-reader.js +193 -102
- package/dist/shared/paths.js +128 -0
- package/dist/shared/settings-io.js +79 -83
- package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
- package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -794
- package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
- package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
- package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -444
- package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
- package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
- package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
- package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
- package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
- package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
- package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
- package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
- package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
- package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
- package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
- package/package.json +119 -118
- package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
- package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
- package/scripts/ai-toolkit.py +607 -478
- package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
- package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
- package/scripts/chat-archive/build-sft-v4.py +566 -0
- package/scripts/chat-archive/build-sft.py +390 -0
- package/scripts/chat-archive/eval-sft.py +155 -0
- package/scripts/chat-archive/extract-memory.py +143 -0
- package/scripts/chat-archive/inventory.py +182 -0
- package/scripts/chat-archive/merge-sft.py +114 -0
- package/scripts/chat-archive/qce-pull.py +217 -0
- package/scripts/chat-archive/qqheader.py +110 -0
- package/scripts/chat-archive/qqkey2.py +113 -0
- package/scripts/chat-archive/qqprobe.py +153 -0
- package/scripts/chat-archive/screen-collect.py +163 -0
- package/scripts/chat-archive/sqlcipher_probe.py +444 -0
- package/scripts/episode.py +529 -0
- package/scripts/fan-curve.py +218 -0
- package/scripts/fan-guard.cmd +8 -0
- package/scripts/fan-mode.py +380 -263
- package/scripts/gen-image.py +420 -413
- package/scripts/gen-video.py +186 -178
- package/scripts/hw-profile.py +175 -0
- package/scripts/media-enhance.py +402 -0
- package/scripts/memory-audit.py +581 -0
- package/scripts/migrate-scope.mjs +140 -139
- package/scripts/qq-connect-login.py +133 -0
- package/scripts/qq-ip-sync-hidden.vbs +5 -0
- package/scripts/qq-ip-sync.py +300 -0
- package/scripts/qq-whitelist.py +71 -0
- package/scripts/release-all.mjs +636 -509
- package/scripts/release-check.mjs +244 -226
- package/scripts/secure-room/index.html +334 -0
- package/scripts/secure-room/server.py +582 -0
- package/scripts/stickers/auto-tag.mjs +161 -0
- package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
- package/scripts/train/gguf-quantize.py +92 -0
- package/scripts/train/gguf-to-hf.py +112 -0
- package/scripts/train/merge-lora.py +51 -0
- package/scripts/train/probe-mirrors.sh +12 -0
- package/scripts/train/probe-mirrors2.sh +20 -0
- package/scripts/train/setup-wsl.sh +23 -0
- package/scripts/train/setup-wsl2.sh +25 -0
- package/scripts/train/setup-wsl3.sh +22 -0
- package/scripts/train/setup-wsl4.sh +22 -0
- package/scripts/train/train-lora.py +319 -0
- package/dist/_backup_ctx_20261125_183653/dist/config.d.ts +0 -473
- package/dist/_backup_ctx_20261125_183653/dist/config.js +0 -450
- package/dist/_backup_ctx_20261125_183653/dist/features/contextless-trim.js +0 -304
- package/dist/_backup_ctx_20261125_183653/dist/session/session-manager.js +0 -1588
- package/dist/_backup_ctx_20261125_183653/dist/transport/inbound.js +0 -1567
- package/dist/_backup_ctx_20261125_183653/dist/transport/outbound.js +0 -647
- package/scripts/__pycache__/ai-mode.cpython-311.pyc +0 -0
- package/scripts/__pycache__/ai-toolkit.cpython-311.pyc +0 -0
- package/scripts/__pycache__/comfy_gen.cpython-311.pyc +0 -0
- package/scripts/__pycache__/gen-image.cpython-311.pyc +0 -0
- package/scripts/__pycache__/gen-video.cpython-311.pyc +0 -0
- package/scripts/__pycache__/model-registry.cpython-311.pyc +0 -0
- package/scripts/__pycache__/purge-standby.cpython-311.pyc +0 -0
|
@@ -1,1653 +1,1705 @@
|
|
|
1
|
-
import { existsSync as __existsSync } from 'node:fs'
|
|
2
|
-
const __repoRoot = (() => {
|
|
3
|
-
let cached = ''
|
|
4
|
-
const norm = (p) => String(p || '').split(String.fromCharCode(92)).join('/')
|
|
5
|
-
return () => {
|
|
6
|
-
if (cached) return cached
|
|
7
|
-
const cands = []
|
|
8
|
-
const env = String(process.env.QQBOT_ROOT || process.env.QQBOT_REPO_ROOT || '').trim()
|
|
9
|
-
if (env) cands.push(norm(env))
|
|
10
|
-
try {
|
|
11
|
-
let here = decodeURIComponent(new URL('.', import.meta.url).pathname)
|
|
12
|
-
if (here[0] === '/' && here[2] === ':') here = here.slice(1)
|
|
13
|
-
here = norm(here).replace(/\/+$/, '')
|
|
14
|
-
let d = here
|
|
15
|
-
for (let i = 0; i < 6; i += 1) {
|
|
16
|
-
if (!d) break
|
|
17
|
-
cands.push(d)
|
|
18
|
-
const k = d.lastIndexOf('/')
|
|
19
|
-
d = k > 0 ? d.slice(0, k) : ''
|
|
20
|
-
}
|
|
21
|
-
} catch { /* noop */ }
|
|
22
|
-
try { cands.push(norm(process.cwd())) } catch { /* noop */ }
|
|
23
|
-
for (const c of cands) {
|
|
24
|
-
try {
|
|
25
|
-
if (c && (__existsSync(c + '/qqbot-mod/muu-shared.mjs') || __existsSync(c + '/dshqqbot'))) { cached = c; return cached }
|
|
26
|
-
} catch { /* noop */ }
|
|
27
|
-
}
|
|
28
|
-
cached = norm(cands.find(Boolean) || '.')
|
|
29
|
-
return cached
|
|
30
|
-
}
|
|
31
|
-
})()
|
|
32
|
-
import { join, resolve, relative, isAbsolute, basename, extname } from 'node:path';
|
|
33
|
-
import { readFileSync as qqReadFileSync, writeFileSync as qqWriteFileSync, appendFileSync as qqAppendFileSync, mkdirSync as qqMkdirSync, realpathSync as qqRealpathSync, existsSync as qqExistsSync, statSync as qqStatSync, unlinkSync as qqUnlinkSync } from 'node:fs';
|
|
34
|
-
import { fileURLToPath } from 'node:url';
|
|
35
|
-
import { spawn as qqSpawn } from 'node:child_process';
|
|
36
|
-
|
|
37
|
-
/** 项目根:dist/gateway → 上两级。
|
|
38
|
-
* 2026-11-14:插件被 pnpm 复制进 profiles/web/node_modules/.pnpm/… 之后,上两级成了**包目录**而不是
|
|
39
|
-
* 仓库根,媒体白名单(assets/media/tmp/render/voices)会整体指错。这里优先认「上两级里真有
|
|
40
|
-
* wechat-bridge/util.mjs」的那个,其次 QQBOT_REPO_ROOT,最后回落老部署 <仓库根>。 */
|
|
41
|
-
const QQBOT_ROOT = (() => {
|
|
42
|
-
const up = resolve(fileURLToPath(new URL('.', import.meta.url)), '..', '..');
|
|
43
|
-
const cands = [up, String(process.env.QQBOT_REPO_ROOT || '').trim(), __repoRoot() + ""].filter(Boolean);
|
|
44
|
-
return cands.find((p) => { try { return qqExistsSync(join(p, 'wechat-bridge', 'util.mjs')) } catch { return false } }) || up;
|
|
45
|
-
})();
|
|
46
|
-
/** scripts/ + data/net 所在的「真实仓库根」。
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
const
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
try {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
write
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
//
|
|
135
|
-
//
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
//
|
|
149
|
-
//
|
|
150
|
-
//
|
|
151
|
-
//
|
|
152
|
-
//
|
|
153
|
-
//
|
|
154
|
-
//
|
|
155
|
-
//
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
if (/
|
|
172
|
-
return '
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
return
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
//
|
|
328
|
-
//
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
try {
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
//
|
|
438
|
-
//
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
//
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
//
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
//
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
const
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
//
|
|
494
|
-
|
|
495
|
-
//
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
const
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
if (
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
}
|
|
596
|
-
}
|
|
597
|
-
if (
|
|
598
|
-
logger.debug(
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
//
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
//
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
}
|
|
743
|
-
}
|
|
744
|
-
//
|
|
745
|
-
{
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
}
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
//
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
//
|
|
911
|
-
//
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
//
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
//
|
|
943
|
-
//
|
|
944
|
-
//
|
|
945
|
-
//
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
//
|
|
961
|
-
//
|
|
962
|
-
//
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
try {
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
}
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
() =>
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
}));
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
//
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
//
|
|
1070
|
-
// (
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
//
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
}
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
}
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
}
|
|
1293
|
-
};
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
if (
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
})
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
const
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
try {
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
}
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1
|
+
import { existsSync as __existsSync } from 'node:fs'
|
|
2
|
+
const __repoRoot = (() => {
|
|
3
|
+
let cached = ''
|
|
4
|
+
const norm = (p) => String(p || '').split(String.fromCharCode(92)).join('/')
|
|
5
|
+
return () => {
|
|
6
|
+
if (cached) return cached
|
|
7
|
+
const cands = []
|
|
8
|
+
const env = String(process.env.QQBOT_ROOT || process.env.QQBOT_REPO_ROOT || '').trim()
|
|
9
|
+
if (env) cands.push(norm(env))
|
|
10
|
+
try {
|
|
11
|
+
let here = decodeURIComponent(new URL('.', import.meta.url).pathname)
|
|
12
|
+
if (here[0] === '/' && here[2] === ':') here = here.slice(1)
|
|
13
|
+
here = norm(here).replace(/\/+$/, '')
|
|
14
|
+
let d = here
|
|
15
|
+
for (let i = 0; i < 6; i += 1) {
|
|
16
|
+
if (!d) break
|
|
17
|
+
cands.push(d)
|
|
18
|
+
const k = d.lastIndexOf('/')
|
|
19
|
+
d = k > 0 ? d.slice(0, k) : ''
|
|
20
|
+
}
|
|
21
|
+
} catch { /* noop */ }
|
|
22
|
+
try { cands.push(norm(process.cwd())) } catch { /* noop */ }
|
|
23
|
+
for (const c of cands) {
|
|
24
|
+
try {
|
|
25
|
+
if (c && (__existsSync(c + '/qqbot-mod/muu-shared.mjs') || __existsSync(c + '/dshqqbot'))) { cached = c; return cached }
|
|
26
|
+
} catch { /* noop */ }
|
|
27
|
+
}
|
|
28
|
+
cached = norm(cands.find(Boolean) || '.')
|
|
29
|
+
return cached
|
|
30
|
+
}
|
|
31
|
+
})()
|
|
32
|
+
import { join, resolve, relative, isAbsolute, basename, extname } from 'node:path';
|
|
33
|
+
import { readFileSync as qqReadFileSync, writeFileSync as qqWriteFileSync, appendFileSync as qqAppendFileSync, mkdirSync as qqMkdirSync, realpathSync as qqRealpathSync, existsSync as qqExistsSync, statSync as qqStatSync, unlinkSync as qqUnlinkSync, renameSync as qqRenameSync } from 'node:fs';
|
|
34
|
+
import { fileURLToPath } from 'node:url';
|
|
35
|
+
import { spawn as qqSpawn } from 'node:child_process';
|
|
36
|
+
|
|
37
|
+
/** 项目根:dist/gateway → 上两级。
|
|
38
|
+
* 2026-11-14:插件被 pnpm 复制进 profiles/web/node_modules/.pnpm/… 之后,上两级成了**包目录**而不是
|
|
39
|
+
* 仓库根,媒体白名单(assets/media/tmp/render/voices)会整体指错。这里优先认「上两级里真有
|
|
40
|
+
* wechat-bridge/util.mjs」的那个,其次 QQBOT_REPO_ROOT,最后回落老部署 <仓库根>。 */
|
|
41
|
+
const QQBOT_ROOT = (() => {
|
|
42
|
+
const up = resolve(fileURLToPath(new URL('.', import.meta.url)), '..', '..');
|
|
43
|
+
const cands = [up, String(process.env.QQBOT_REPO_ROOT || '').trim(), __repoRoot() + ""].filter(Boolean);
|
|
44
|
+
return cands.find((p) => { try { return qqExistsSync(join(p, 'wechat-bridge', 'util.mjs')) } catch { return false } }) || up;
|
|
45
|
+
})();
|
|
46
|
+
/** scripts/ + data/net 所在的「真实仓库根」。
|
|
47
|
+
* 2026-12-04:这一段推导已上移到 shared/paths.js(SCRIPTS_ROOT),
|
|
48
|
+
* 与 config.js / features/local-models.js 共用同一套语义,避免三处各算一遍。 */
|
|
49
|
+
const QQBOT_SCRIPTS_ROOT = SCRIPTS_ROOT;
|
|
50
|
+
import { SCRIPTS_ROOT } from '../shared/paths.js';
|
|
51
|
+
|
|
52
|
+
/** 允许出站的本地媒体根目录(P0-4):[MEDIA]/send_media 只能引用这些目录内的文件
|
|
53
|
+
* 2026-11-28 加 'out':统一产出目录(图/视频/音频/文本)在 out/ 下,不再走 media/。
|
|
54
|
+
* 2026-12-02 加 'tmp':搜索/下载下来的图常临时落在 tmp/ 与 tmp_xxx/(主人实测
|
|
55
|
+
* "查到了图却发不出"——白名单把 tmp_liang 拒了,正文里 [MEDIA] 被静默丢弃)。 */
|
|
56
|
+
const MEDIA_ALLOW_DIRS = ['out', 'assets', 'media', 'tmp', 'voices'];
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 本地媒体路径闸门(唯一咽喉,[MEDIA]标记 / send_media 工具 / ext 能力 / botplay 都汇于 sender.sendMedia)。
|
|
60
|
+
* 规则:realpath 后必须落在允许根(含表情包库)内;显式拒绝 secrets/secret/.git 与凭证 json。
|
|
61
|
+
* 越界抛错,由上层转 ok:false,不静默放行。
|
|
62
|
+
*/
|
|
63
|
+
function assertMediaPath(localPath, config) {
|
|
64
|
+
const raw = String(localPath || '');
|
|
65
|
+
if (!raw) throw new Error('媒体路径为空');
|
|
66
|
+
let real;
|
|
67
|
+
try { real = qqRealpathSync(resolve(raw)); }
|
|
68
|
+
catch { throw new Error(`媒体文件不存在或不可读:${basename(raw)}`); }
|
|
69
|
+
let stickerRoot = '';
|
|
70
|
+
try { stickerRoot = resolve(stickerDirOf(config)); } catch { /* 配置不全时忽略 */ }
|
|
71
|
+
let dataRoot = '';
|
|
72
|
+
try { dataRoot = resolve(dataRootOf(config)); } catch { /* 配置不全时忽略 */ }
|
|
73
|
+
const roots = [
|
|
74
|
+
// 工作区根整体放行:模型把图放在 tmp_xxx/、downloads/ 这类临时目录是常态,
|
|
75
|
+
// 逐个加白名单永远跟不上(2026-12-02 主人实测:tmp_liang 被拒 → 图静默丢失)。
|
|
76
|
+
// 敏感目录/凭证在下面显式拒绝,不放行。
|
|
77
|
+
//
|
|
78
|
+
// ⚠️ 2026-12-02 修「查到了图却发不出」的根因:
|
|
79
|
+
// 插件被 pnpm 复制进 profiles/desktop/node_modules/dsh-qqbot-muu 后,上面 QQBOT_ROOT
|
|
80
|
+
// 的启发式会落在这个**安装副本**上(副本里既没有 wechat-bridge/ 也没有 out|media|tmp),
|
|
81
|
+
// 于是老白名单的每个根都指向不存在的目录 ⇒ 任何本地图都被判「不在允许目录内」。
|
|
82
|
+
// QQBOT_SCRIPTS_ROOT 认 config/repo-root.json 指针(sync-plugin-copies 写的 F:/qqbot),
|
|
83
|
+
// 是安装副本里唯一可靠的仓库根,媒体根必须两套都算上。
|
|
84
|
+
resolve(QQBOT_ROOT),
|
|
85
|
+
resolve(QQBOT_SCRIPTS_ROOT),
|
|
86
|
+
...MEDIA_ALLOW_DIRS.map((d) => resolve(QQBOT_SCRIPTS_ROOT, d)),
|
|
87
|
+
...MEDIA_ALLOW_DIRS.map((d) => resolve(QQBOT_ROOT, d)),
|
|
88
|
+
stickerRoot,
|
|
89
|
+
// 登录二维码与扩展自身产出的媒体(面板/桌宠/视频流水线的正常出口)
|
|
90
|
+
dataRoot ? join(dataRoot, 'qun-login-qr.png') : '',
|
|
91
|
+
dataRoot ? join(dataRoot, '.qqbot-extensions') : '',
|
|
92
|
+
].filter(Boolean);
|
|
93
|
+
const rel = roots.map((r) => relative(r, real)).find((x) => !isAbsolute(x) && !x.startsWith('..'));
|
|
94
|
+
if (rel === undefined) throw new Error(`媒体路径不在允许目录内:${basename(raw)}`);
|
|
95
|
+
const low = real.toLowerCase().replace(/\\/g, '/');
|
|
96
|
+
if (/\/secrets?\//.test(low) || /\/\.git\//.test(low) || /(bili|douyin)-cookie\.json$/.test(low)) {
|
|
97
|
+
throw new Error('媒体路径命中敏感目录/凭证文件,已拒绝');
|
|
98
|
+
}
|
|
99
|
+
try { if (!qqStatSync(real).isFile()) throw new Error('not file'); }
|
|
100
|
+
catch { throw new Error(`媒体路径不是文件:${basename(raw)}`); }
|
|
101
|
+
return real;
|
|
102
|
+
}
|
|
103
|
+
// [qqbot-mod] host-lock —— 同一机器人只许一个 DSH 实例连 QQ(防双答案/会话两开)
|
|
104
|
+
function qqbotHostLock(dataRoot, logger) {
|
|
105
|
+
const dir = join(dataRoot, '.qqbot')
|
|
106
|
+
const file = join(dir, 'bot-host.lock')
|
|
107
|
+
const mine = process.pid
|
|
108
|
+
const now = Date.now()
|
|
109
|
+
try { qqMkdirSync(dir, { recursive: true }) } catch { }
|
|
110
|
+
let prev = null
|
|
111
|
+
try { prev = JSON.parse(qqReadFileSync(file, 'utf8')) } catch { prev = null }
|
|
112
|
+
const fresh = !!(prev && typeof prev.at === "number" && now - prev.at < 90000)
|
|
113
|
+
if (fresh && prev.pid && prev.pid !== mine) {
|
|
114
|
+
let alive = false
|
|
115
|
+
try { process.kill(prev.pid, 0); alive = true } catch { alive = false }
|
|
116
|
+
if (alive) return { ok: false, holder: prev }
|
|
117
|
+
}
|
|
118
|
+
// 原子写锁:心跳每 30 秒一次,另一个实例恰好在这时读到半截 JSON 会 parse 失败
|
|
119
|
+
// → 被当成"没有锁" → 两个 bot 同时上线抢同一账号(重复回复/互相顶号)。
|
|
120
|
+
const write = () => {
|
|
121
|
+
try {
|
|
122
|
+
const tmp = `${file}.${mine}.tmp`
|
|
123
|
+
qqWriteFileSync(tmp, JSON.stringify({ pid: mine, at: Date.now(), startedAt: new Date().toISOString() }), 'utf8')
|
|
124
|
+
qqRenameSync(tmp, file)
|
|
125
|
+
}
|
|
126
|
+
catch { }
|
|
127
|
+
}
|
|
128
|
+
write()
|
|
129
|
+
const timer = setInterval(write, 30000)
|
|
130
|
+
if (timer.unref) timer.unref()
|
|
131
|
+
return { ok: true, holder: null, release: () => { clearInterval(timer); try { qqWriteFileSync(file, JSON.stringify({ pid: mine, at: 0 }), 'utf8') } catch { } } }
|
|
132
|
+
}
|
|
133
|
+
// [qqbot-mod] bot-status —— bot ws 在线状态**事件驱动落盘**(2026-10-31 主人反馈"🟢 QQ 在线无效"):
|
|
134
|
+
// ready/resumed/error/start-failed 每次都写 {dataRoot}/.qqbot/bot-status.json,
|
|
135
|
+
// 浮窗扩展页与桌宠 /pet 页读这份文件,替代扫日志猜状态(旧法会把几天前的 ready 当在线)。
|
|
136
|
+
function writeBotStatus(dataRoot, online, why, detail) {
|
|
137
|
+
try {
|
|
138
|
+
const dir = join(dataRoot, '.qqbot')
|
|
139
|
+
try { qqMkdirSync(dir, { recursive: true }) } catch { }
|
|
140
|
+
const target = join(dir, 'bot-status.json')
|
|
141
|
+
// 原子写:面板/桌宠随时在读这个文件,直接覆盖会有概率读到半个 JSON,
|
|
142
|
+
// 于是"在线"被解析失败当成"离线"(别的用户看到状态乱跳就是这个)。
|
|
143
|
+
const tmp = `${target}.${process.pid}.tmp`
|
|
144
|
+
qqWriteFileSync(tmp, JSON.stringify({ online: !!online, why: String(why || ''), detail: String(detail || ''), at: new Date().toISOString(), pid: process.pid }), 'utf8')
|
|
145
|
+
qqRenameSync(tmp, target)
|
|
146
|
+
} catch { }
|
|
147
|
+
}
|
|
148
|
+
// ── [qqbot-mod] conn-recover 2026-12-01 ─────────────────────────────────────
|
|
149
|
+
// 背景(主人报「明明能连上却一直离线 / 私聊发消息没反应」):
|
|
150
|
+
// DSH 0.14 把 profile 从 web 换成 desktop 之后,desktop 那份设置里的 appSecret
|
|
151
|
+
// 是错的 → /token 直接回 "invalid appid or secret" → bot.start() 立刻 reject,
|
|
152
|
+
// 而旧代码只写一个 start-failed 状态就不管了 ⇒ 一路离线到下次重启,且日志里
|
|
153
|
+
// 连原因都没有(失败信息只进了 logger,harness.log 里看不到插件 info 级日志)。
|
|
154
|
+
// 这里补三件事:
|
|
155
|
+
// ① 每次启动/失败都写 {dataRoot}/.qqbot/qqbot-startup.log(原因 + 堆栈 + 重试计划);
|
|
156
|
+
// ② 失败后退避重试(凭据类 5 分钟一档,网络类 5s→300s 递增);
|
|
157
|
+
// ③ 命中「源IP不在白名单」时自动跑 scripts/qq-whitelist.py --headless,成功后重连;
|
|
158
|
+
// 另外每 30 分钟比对一次当前出口 IP 与 whitelist-applied.txt,变了就先修白名单。
|
|
159
|
+
// 面板/桌宠读 bot-status.json 的 why/detail 就能直接告诉人「为什么离线」。
|
|
160
|
+
function qqStartupLog(dataRoot, text) {
|
|
161
|
+
try {
|
|
162
|
+
const dir = join(dataRoot, '.qqbot')
|
|
163
|
+
try { qqMkdirSync(dir, { recursive: true }) } catch { }
|
|
164
|
+
qqAppendFileSync(join(dir, 'qqbot-startup.log'), `[${new Date().toISOString()}] ${text}\n`, 'utf8')
|
|
165
|
+
}
|
|
166
|
+
catch { /* 日志写不进去不影响连接 */ }
|
|
167
|
+
}
|
|
168
|
+
/** 把 SDK 的报错归类,决定后续自愈动作 */
|
|
169
|
+
function connectionErrorKind(msg) {
|
|
170
|
+
const s = String(msg || '');
|
|
171
|
+
if (/白名单|whitelist|源IP/i.test(s))
|
|
172
|
+
return 'whitelist';
|
|
173
|
+
if (/invalid appid or secret|appid invalid|invalid appid|access_token|app_?secret/i.test(s))
|
|
174
|
+
return 'credential';
|
|
175
|
+
if (/ENOTFOUND|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|socket hang up|fetch failed|network/i.test(s))
|
|
176
|
+
return 'network';
|
|
177
|
+
return 'other';
|
|
178
|
+
}
|
|
179
|
+
/** 跑 scripts/ 下的 python 脚本(统一解释器探测,避免每处各写一套 spawn) */
|
|
180
|
+
function runPyScript(scriptName, args, timeoutMs) {
|
|
181
|
+
return new Promise((resolvePromise) => {
|
|
182
|
+
// 脚本可能只存在于「真仓库」或「包目录」的其中一处:逐根找,找不到就明确报错。
|
|
183
|
+
// 2026-12-04:旧代码直接 join(QQBOT_SCRIPTS_ROOT, ...) 去 spawn,路径不存在时
|
|
184
|
+
// 只会得到 rc=2 + 一段 python traceback,启动自检日志里完全看不出是「脚本缺了」。
|
|
185
|
+
const roots = [];
|
|
186
|
+
for (const r of [QQBOT_SCRIPTS_ROOT, QQBOT_ROOT, String(process.env.QQBOT_REPO_ROOT || '').trim()]) {
|
|
187
|
+
if (r && !roots.includes(r))
|
|
188
|
+
roots.push(r);
|
|
189
|
+
}
|
|
190
|
+
let script = '';
|
|
191
|
+
for (const r of roots) {
|
|
192
|
+
try {
|
|
193
|
+
const p = join(r, 'scripts', scriptName);
|
|
194
|
+
if (qqExistsSync(p)) {
|
|
195
|
+
script = p;
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
catch { /* ignore */ }
|
|
200
|
+
}
|
|
201
|
+
if (!script) {
|
|
202
|
+
resolvePromise({ code: -2, out: `找不到 scripts/${scriptName}(已查:${roots.join(' | ') || '无候选根'})` });
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
// 解释器:环境变量 → python3 → python。
|
|
206
|
+
// 不再写死作者机器的 E:/Anaconda/envs/ai25/python.exe(别的用户机器上必不存在)。
|
|
207
|
+
const py = [String(process.env.QQBOT_PYTHON || '').trim(), 'python3', 'python'].filter(Boolean);
|
|
208
|
+
const tryOne = (idx) => {
|
|
209
|
+
if (idx >= py.length) {
|
|
210
|
+
resolvePromise({ code: -1, out: 'no python interpreter' });
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
let out = '';
|
|
214
|
+
let child;
|
|
215
|
+
try {
|
|
216
|
+
// PYTHONIOENCODING:脚本里的中文输出在 GBK 控制台会被写坏,
|
|
217
|
+
// 启动日志里就变成乱码(用户反馈排查困难)。
|
|
218
|
+
child = qqSpawn(py[idx], [script, ...args], {
|
|
219
|
+
windowsHide: true,
|
|
220
|
+
env: { ...process.env, PYTHONIOENCODING: 'utf-8', PYTHONUTF8: '1' },
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
catch (err) {
|
|
224
|
+
if (idx + 1 < py.length)
|
|
225
|
+
tryOne(idx + 1);
|
|
226
|
+
else
|
|
227
|
+
resolvePromise({ code: -3, out: err instanceof Error ? err.message : String(err) });
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
const killTimer = setTimeout(() => { try { child.kill(); } catch { /* ignore */ } }, timeoutMs);
|
|
231
|
+
if (killTimer.unref) killTimer.unref();
|
|
232
|
+
child.stdout?.on('data', (b) => { out += String(b); });
|
|
233
|
+
child.stderr?.on('data', (b) => { out += String(b); });
|
|
234
|
+
child.on('error', (err) => {
|
|
235
|
+
clearTimeout(killTimer);
|
|
236
|
+
// 解释器不存在(ENOENT)→ 换下一个候选
|
|
237
|
+
if (String(err && err.code) === 'ENOENT' && idx + 1 < py.length)
|
|
238
|
+
tryOne(idx + 1);
|
|
239
|
+
else
|
|
240
|
+
resolvePromise({ code: -4, out: out + (err instanceof Error ? err.message : String(err)) });
|
|
241
|
+
});
|
|
242
|
+
child.on('close', (code) => {
|
|
243
|
+
clearTimeout(killTimer);
|
|
244
|
+
resolvePromise({ code: typeof code === 'number' ? code : -5, out });
|
|
245
|
+
});
|
|
246
|
+
};
|
|
247
|
+
tryOne(0);
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// 2026-12-04:runWhitelistScript() 已删除 —— 全项目没有任何调用点,
|
|
252
|
+
// 而它指向的 qq-whitelist.py 早就因为后台改版永远 rc=20,留着只会让后来的人接错线。
|
|
253
|
+
import { QQBot } from '@tencent-connect/qqbot-nodejs';
|
|
254
|
+
import { FULL_INTENTS } from '@tencent-connect/qqbot-nodejs/protocol';
|
|
255
|
+
import { SessionManager } from '../session/index.js';
|
|
256
|
+
import { handleInbound, createOutboundHandler } from '../transport/index.js';
|
|
257
|
+
import { parseStreamFrame } from '../transport/events.js';
|
|
258
|
+
import { setMaterialTargetFactory, rewriteLocalMarkdownImages, lastMediaRewrite } from '../features/md-media-rewrite.js';
|
|
259
|
+
import { rollFire, matchEventJobs, bumpActivation } from '../features/schedule-events.js';
|
|
260
|
+
import { buildUserAgent } from '../shared/index.js';
|
|
261
|
+
import { setupMiddlewares } from './middleware-setup.js';
|
|
262
|
+
import { configureDiag, diagWrite } from '../shared/diag.js';
|
|
263
|
+
import { dataRootOf, migrateLegacyData, stickerDirOf } from './data-root.js';
|
|
264
|
+
import { configureStickerStore } from '../features/sticker-store.js';
|
|
265
|
+
import { initStickerGate, bindStickerGates, flushStickerGate, getStickerGate, StickerGateDenied } from '../features/sticker-gate.js';
|
|
266
|
+
import { startScheduler } from '../features/scheduler.js';
|
|
267
|
+
import { startJoinRequestPolling } from '../features/poll-join-requests.js';
|
|
268
|
+
import { configureScheduleStore, getScheduleStore } from '../features/schedule-store.js';
|
|
269
|
+
import { initContextlessStore, traceContextless, describeStorePath } from '../features/contextless-store.js';
|
|
270
|
+
import { rememberInbound, rememberSelf } from '../features/msg-recent.js';
|
|
271
|
+
import { initMsgHistory, appendMsgHistory } from '../features/msg-history.js';
|
|
272
|
+
import { setChannelBridge } from '../channel-tools.js';
|
|
273
|
+
import { QqApprovalController, setApprovalDispatch, makeApprovalListener, registerApprovalController } from '../features/qq-approval.js';
|
|
274
|
+
import { QqUserQuestionsController, registerQuestionController } from '../features/qq-user-questions.js';
|
|
275
|
+
import { handleGroupJoinRequestEvent } from '../features/group-join-request.js';
|
|
276
|
+
import { handleGroupMemberAddEvent, handleGroupAddRobotEvent } from '../features/group-hub.js';
|
|
277
|
+
import { registerSessionManager, setBotOnline } from '../features/session-registry.js';
|
|
278
|
+
import { BotplayController, registerBotplayController, setBotplayTriggerImpl, setBotplayCatalogImpl } from '../features/botplay.js';
|
|
279
|
+
import { createCardCallbackController } from '../features/card-callback.js';
|
|
280
|
+
import { createExtToolInteractionController } from '../features/ext-tool-interaction.js';
|
|
281
|
+
import { makeExtCaps } from '../features/ext-capabilities.js';
|
|
282
|
+
import { readBotplayEvents } from '../features/botplay-store.js';
|
|
283
|
+
import { PresetSwitcherController, setPresetCardImpl } from '../features/preset-switcher.js';
|
|
284
|
+
import { buildCommandList } from '../commands/index.js';
|
|
285
|
+
import { SettingsReader } from '../model/settings-reader.js';
|
|
286
|
+
/** 从 interaction 事件推出"回复目标"(回执发到按钮所在群/私聊)。scope 由事件 chat_type/scene 推断 */
|
|
287
|
+
function replyTargetOfInteraction(event, _ctx, _manager) {
|
|
288
|
+
const e = event;
|
|
289
|
+
if (e?.group_openid)
|
|
290
|
+
return { scope: 'group', targetId: e.group_openid };
|
|
291
|
+
if (e?.user_openid)
|
|
292
|
+
return { scope: 'c2c', targetId: e.user_openid };
|
|
293
|
+
// 兜底: 群聊 member_openid 只能推群, 但没有 group_openid 无法构造 → 空 target(上层会忽略)
|
|
294
|
+
return { scope: (e?.chat_type === 1 || e?.scene === 'group') ? 'group' : 'c2c', targetId: e?.group_member_openid ?? '' };
|
|
295
|
+
}
|
|
296
|
+
export async function bootstrapGateway(ctx, agents, config, logger, hooks) {
|
|
297
|
+
const manager = new SessionManager(ctx, agents, config, logger);
|
|
298
|
+
// 2026-10-22: 账号包要用机器人 token 通道(素材上传),这里把凭据放全局供 pack 读取
|
|
299
|
+
try {
|
|
300
|
+
globalThis.__qqbotAppCred = {
|
|
301
|
+
appId: String(config.appId ?? ''),
|
|
302
|
+
appSecret: String(config.appSecret ?? ''),
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
catch { /* ignore */ }
|
|
306
|
+
// 2026-10-21: 出站自动传图用 —— 给 md-media-rewrite 一个拿得到 token 的句柄
|
|
307
|
+
try {
|
|
308
|
+
setMaterialTargetFactory(() => {
|
|
309
|
+
const c = manager.groupAdmin;
|
|
310
|
+
return c ? { apiCall: c.apiCall.bind(c) } : undefined;
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
catch { /* ignore */ }
|
|
314
|
+
// 实例标识(settingsNs), 全 bootstrap 共用: 注册表按 ns 隔离(B类修复 2026-09-11)
|
|
315
|
+
const myNs = config.settingsNs?.trim() || 'im-qqbot';
|
|
316
|
+
// ★★ 0.1.6 首装补丁(只缺省才写 + 只补缺失文件,绝不覆盖用户改动)★★
|
|
317
|
+
// 为什么放在这里:settings 服务此时可用,且早于 bot 连接 —— 扩展必须在网关起链之前就位,
|
|
318
|
+
// 否则新装用户第一条消息就落在"没有扩展"的链上(分句/卡片/记忆都没有)。
|
|
319
|
+
// 两步都 fail-soft:任何异常只 warn,绝不影响登录。
|
|
320
|
+
try {
|
|
321
|
+
const { configureRuntimeTuning } = await import('../features/runtime-tuning.js');
|
|
322
|
+
configureRuntimeTuning(config.runtime ?? {});
|
|
323
|
+
}
|
|
324
|
+
catch (err) {
|
|
325
|
+
logger.warn(`im-qqbot: 运行时调优未生效(用内置默认): ${err instanceof Error ? err.message : String(err)}`);
|
|
326
|
+
}
|
|
327
|
+
// 本地模型能力层(2026-11-25):把 config.localModels 灌进能力层单例。
|
|
328
|
+
// 默认全关 —— 这里只是搬配置,不做任何网络探测,启动零开销。
|
|
329
|
+
try {
|
|
330
|
+
const { configureLocalModels } = await import('../features/local-models.js');
|
|
331
|
+
const _lm = configureLocalModels(config.localModels ?? {});
|
|
332
|
+
logger.info(`im-qqbot: 本地模型开关 总=${_lm.enabled ? '开' : '关'} asr=${_lm.asr ? 1 : 0} ocr=${_lm.ocr ? 1 : 0} tts=${_lm.tts ? 1 : 0} llm=${_lm.llm ? 1 : 0} image=${_lm.image ? 1 : 0}`);
|
|
333
|
+
}
|
|
334
|
+
catch (err) {
|
|
335
|
+
logger.warn(`im-qqbot: 本地模型能力层未生效(用内置默认全关): ${err instanceof Error ? err.message : String(err)}`);
|
|
336
|
+
}
|
|
337
|
+
try {
|
|
338
|
+
const { applyDefaultsPatch, seedExtensions } = await import('../features/firstrun.js');
|
|
339
|
+
const _seedDataRoot = dataRootOf(config);
|
|
340
|
+
let _svc;
|
|
341
|
+
try {
|
|
342
|
+
_svc = ctx?.get?.('settings');
|
|
343
|
+
}
|
|
344
|
+
catch { /* 拿不到就走自有存储 */ }
|
|
345
|
+
const _patch = await applyDefaultsPatch({ ns: myNs, dataRoot: _seedDataRoot, logger, settingsService: _svc });
|
|
346
|
+
// settings 服务写成功时把新值并回内存 config,保证本次启动就按新默认值跑
|
|
347
|
+
if (_patch.written && Object.keys(_patch.written).length > 0) {
|
|
348
|
+
try {
|
|
349
|
+
const { setPath } = await import('../features/firstrun.js');
|
|
350
|
+
for (const [k, v] of Object.entries(_patch.written))
|
|
351
|
+
setPath(config, k, v);
|
|
352
|
+
}
|
|
353
|
+
catch { /* ignore */ }
|
|
354
|
+
}
|
|
355
|
+
if (_seedDataRoot)
|
|
356
|
+
seedExtensions({ pkgRoot: QQBOT_ROOT, dataRoot: _seedDataRoot, logger });
|
|
357
|
+
}
|
|
358
|
+
catch (err) {
|
|
359
|
+
logger.warn(`im-qqbot: 首装补丁失败(不影响启动): ${err instanceof Error ? err.message : String(err)}`);
|
|
360
|
+
}
|
|
361
|
+
// [qqbot-mod 2026-10-31] appSecret 自愈 + secrets 镜像刷新(在 new QQBot 之前,时序保证)。
|
|
362
|
+
// 事故背景:设置页保存曾把掩码 '********' 写进自有存储 → bot 全天 100016 掉线。
|
|
363
|
+
// 三件事:
|
|
364
|
+
// ① config.appSecret 是掩码/空 → 从 <cwd>/secrets/runtime/qqbot-account-<ns>.json 取回真身,
|
|
365
|
+
// 并顺手把自有存储文件里的掩码修掉(下次 /read 就是对的);
|
|
366
|
+
// ② 真 secret 在手 → 刷新 secrets 镜像(savedAt 滚动,永远有一份可恢复);
|
|
367
|
+
// ③ 两者都没有 → 打一行明确的 error(不带任何 secret 内容),别再让人猜一整天。
|
|
368
|
+
// 纪律:绝不打日志泄露 secret 内容;任何失败静默,不影响启动。
|
|
369
|
+
try {
|
|
370
|
+
const _sec = String(config.appSecret ?? '');
|
|
371
|
+
const _cwd = String(config.cwd ?? '').trim() || __repoRoot() + "";
|
|
372
|
+
const _nsSafe = myNs.replace(/[^\w.-]/g, '_');
|
|
373
|
+
const _mirrorPath = join(_cwd, 'secrets', 'runtime', `qqbot-account-${_nsSafe}.json`);
|
|
374
|
+
// 自有存储路径(与 settings-host ns-guard 同规则):<DSH_HOME>/qqbot-settings/<profile>/<ns>.json
|
|
375
|
+
// profile 名进程内可能拿不到(DSH_PROFILE 只在 shell 注入)→ 扫一层子目录 + 老布局兜底。
|
|
376
|
+
const _ownCandidates = [];
|
|
377
|
+
try {
|
|
378
|
+
const _qsRoot = join(process.env.DSH_HOME || '', 'qqbot-settings');
|
|
379
|
+
const { readdirSync: _rd } = await import('node:fs');
|
|
380
|
+
for (const e of _rd(_qsRoot, { withFileTypes: true })) {
|
|
381
|
+
if (e.isDirectory())
|
|
382
|
+
_ownCandidates.push(join(_qsRoot, e.name, `${myNs}.json`));
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
catch { /* 目录扫不了就只试老布局 */ }
|
|
386
|
+
_ownCandidates.push(join(process.env.DSH_HOME || '', 'qqbot-settings', `${myNs}.json`));
|
|
387
|
+
const _isMask = (s) => !s || /^[*]+$/.test(s);
|
|
388
|
+
if (_isMask(_sec)) {
|
|
389
|
+
let healed = '';
|
|
390
|
+
try {
|
|
391
|
+
const m = JSON.parse(qqReadFileSync(_mirrorPath, 'utf8'));
|
|
392
|
+
const ms = String(m?.appSecret ?? '');
|
|
393
|
+
if (ms && !/^[*]+$/.test(ms) && ms.length >= 16)
|
|
394
|
+
healed = ms;
|
|
395
|
+
}
|
|
396
|
+
catch { /* 无镜像/读失败 → 走告警 */ }
|
|
397
|
+
if (healed) {
|
|
398
|
+
config.appSecret = healed;
|
|
399
|
+
logger.warn(`[im-qqbot] appSecret 自愈: 自有存储里的值是掩码,已从 secrets 镜像恢复 (len=${healed.length}, ns=${myNs})`);
|
|
400
|
+
try {
|
|
401
|
+
for (const _op of _ownCandidates) {
|
|
402
|
+
try {
|
|
403
|
+
const o = JSON.parse(qqReadFileSync(_op, 'utf8'));
|
|
404
|
+
if (o && typeof o === 'object' && _isMask(String(o.appSecret ?? ''))) {
|
|
405
|
+
o.appSecret = healed;
|
|
406
|
+
qqWriteFileSync(_op, JSON.stringify(o, null, 2), 'utf8');
|
|
407
|
+
logger.warn(`[im-qqbot] appSecret 自愈: 自有存储已同步修复 (${_op.slice(-60)})`);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
catch { /* 单个候选失败继续下一个 */ }
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
catch { /* 自有存储修不动不阻塞(config 内存里已是对的) */ }
|
|
414
|
+
}
|
|
415
|
+
else {
|
|
416
|
+
logger.error(`[im-qqbot] appSecret 是掩码/空且 secrets 镜像缺失(${_mirrorPath}),Bot 将连不上(100016)。请在账号页重新保存真 secret。`);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
else if (_sec.length >= 16) {
|
|
420
|
+
// 真 secret 在手 → 刷新镜像(幂等;失败不影响启动)
|
|
421
|
+
try {
|
|
422
|
+
const { mkdirSync: _md, writeFileSync: _wf } = await import('node:fs');
|
|
423
|
+
_md(join(_cwd, 'secrets', 'runtime'), { recursive: true });
|
|
424
|
+
_wf(_mirrorPath, JSON.stringify({ appId: String(config.appId ?? ''), appSecret: _sec, savedAt: new Date().toISOString() }, null, 2), 'utf8');
|
|
425
|
+
}
|
|
426
|
+
catch { /* 镜像写失败静默 */ }
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
catch { /* 自愈整体失败不阻塞启动 */ }
|
|
430
|
+
// ★ 2026-10-06 诊断日志总开关(默认关):开了才写 {DSH_HOME|~/.dsh}/*.log。
|
|
431
|
+
// 以前各功能各写各的、零上限(contextless-trace 涨到 25MB),现在统一走 shared/diag.ts。
|
|
432
|
+
// 也可用环境变量 DSH_QQBOT_DIAG=1 临时打开。
|
|
433
|
+
try {
|
|
434
|
+
configureDiag({ enabled: config.diagLog === true });
|
|
435
|
+
}
|
|
436
|
+
catch { /* ignore */ }
|
|
437
|
+
// ── dataRoot 启动迁移: 若配置了 dataRoot(如 cwd/dshqqbot), 先把 cwd 下的旧数据目录
|
|
438
|
+
// 搬进去(幂等, 不覆盖); 必须在任何数据目录初始化/写入之前执行。──
|
|
439
|
+
migrateLegacyData(config, logger);
|
|
440
|
+
// QQ 远程审批控制器(enableApprovals 时创建; 定义在 sender 就绪后, 此处先声明供入站回调引用)
|
|
441
|
+
let approvalController;
|
|
442
|
+
let questionController;
|
|
443
|
+
// botplay 互动事件控制器(事件配置 live 现读 config.botplayEvents; 定义在 sender 就绪后)
|
|
444
|
+
let botplayController;
|
|
445
|
+
/** 自定义卡片(📝 卡片编辑器)按钮回调兜底处理器; 见 features/card-callback.ts */
|
|
446
|
+
let cardCallbackController;
|
|
447
|
+
// 扩展工具按钮回调(2026-10-08): data 前缀 `ext:` → 派发给该工具的 onInteraction
|
|
448
|
+
let extToolInteractionController;
|
|
449
|
+
// ── 表情包图库单例预初始化(防目录分裂) ──
|
|
450
|
+
// ⚠️ 单例时序坑:谁先 getStickerStore 谁定路径。必须在启动早期按数据根
|
|
451
|
+
// 初始化,否则 list_stickers(无参)会以 process.cwd 建错目录(线上踩坑:C盘幽灵库)。
|
|
452
|
+
const stickerDataDir = stickerDirOf(config);
|
|
453
|
+
const stickerStore = configureStickerStore(stickerDataDir, logger, myNs);
|
|
454
|
+
// 启动维护: 清理损坏/空文件 + 物理清除超30天回收站条目
|
|
455
|
+
try {
|
|
456
|
+
const broken = stickerStore.cleanupBroken();
|
|
457
|
+
// 回收站上限(2026-10-05):启动时顺手清一次,把历史堆积的旧 trash 收口
|
|
458
|
+
try {
|
|
459
|
+
const trashed = stickerStore.cleanupTrash(800);
|
|
460
|
+
if (trashed > 0)
|
|
461
|
+
logger.info?.(`[sticker] 回收站超限,已物理清理 ${trashed} 张旧图`);
|
|
462
|
+
}
|
|
463
|
+
catch { /* ignore */ }
|
|
464
|
+
const purged = stickerStore.purgeTrashed();
|
|
465
|
+
if (broken > 0 || purged > 0)
|
|
466
|
+
logger.info(`[sticker] 启动维护: 清损坏${broken} 清回收站${purged}`);
|
|
467
|
+
}
|
|
468
|
+
catch { /* ignore */ }
|
|
469
|
+
logger.info(`[sticker] 图库目录: ${stickerDataDir}`);
|
|
470
|
+
// ⚠️ 2026-09-13 **撤下**「启动后台回填 dHash」: 它会在**启动路径上**调 sharp/libvips ——
|
|
471
|
+
// 实测宿主启动时刷 GLib-GObject-CRITICAL("...property 'space' of type 'VipsInterpretation'"),
|
|
472
|
+
// 并把 dsh 拖到启动不了。改为: dHash **只在真正需要判重时(图片消息预检)惰性计算**,
|
|
473
|
+
// 任何失败都只算"判不了", 绝不进入启动路径; 老库回填改由独立脚本按需跑。
|
|
474
|
+
// ── 表情包发送闸门单例预初始化(P1): 与图库同 dataDir, 绑定 live config getter ──
|
|
475
|
+
// 配置现读(getter 每次判定取 config.sticker.gates), Web 设置热更新即时生效。
|
|
476
|
+
initStickerGate(stickerDataDir, logger, myNs);
|
|
477
|
+
bindStickerGates(() => config.sticker.gates);
|
|
478
|
+
const stickerGate = getStickerGate(stickerDataDir, logger, myNs);
|
|
479
|
+
// ── 会话自设定时任务单例预初始化(schedule_timer 工具用) ──
|
|
480
|
+
// 落盘 {cwd}/.qqbot/timers.json; 与图库同策略: 启动早期按 config.cwd 定路径防分裂。
|
|
481
|
+
const scheduleDataDir = join(dataRootOf(config), '.qqbot');
|
|
482
|
+
configureScheduleStore(scheduleDataDir, logger, myNs);
|
|
483
|
+
// ── 无上下文模式(2026-09-27): 会话级开关存 {dataRoot}/.qqbot/contextless.json ──
|
|
484
|
+
// 开启后该会话每轮丢掉历史(只带 @ 前 N 条 + 系统规则), 大幅省 token。
|
|
485
|
+
try {
|
|
486
|
+
const _dr = dataRootOf(config);
|
|
487
|
+
initContextlessStore(_dr);
|
|
488
|
+
traceContextless('bootstrap 初始化: dataRoot=' + _dr + ' → store文件=' + describeStorePath());
|
|
489
|
+
}
|
|
490
|
+
catch (e) {
|
|
491
|
+
traceContextless('bootstrap 初始化失败: ' + (e instanceof Error ? e.message : String(e)));
|
|
492
|
+
}
|
|
493
|
+
// ── 初始化 QQ Bot SDK ──
|
|
494
|
+
const userAgent = buildUserAgent();
|
|
495
|
+
// 启动期合并 settings.yaml 的 groupAdmin(Web 可视化设置那份):
|
|
496
|
+
// QQBot 构造时 intents 一次性读取 config.groupAdmin; 而 settings 服务注入是异步的,
|
|
497
|
+
// 晚于 gateway 构造 → 仅靠 settings 同步拿不到值, 曾导致 watchJoinRequests 改完不生效
|
|
498
|
+
// (2026-09-09 复盘: 只能改 cordis.patch.yml 绕坑)。这里启动时直接读文件, 让
|
|
499
|
+
// Web 设置(存 settings.yaml)重启即生效, 无需手改 yml —— 通用且时序安全。
|
|
500
|
+
try {
|
|
501
|
+
const reader = new SettingsReader();
|
|
502
|
+
const ga = reader.readGroupAdmin(config.settingsNs?.trim() || 'im-qqbot');
|
|
503
|
+
if (ga) {
|
|
504
|
+
config.groupAdmin = { ...(config.groupAdmin ?? {}), ...ga };
|
|
505
|
+
logger.info(`[im-qqbot] 启动合并 groupAdmin(settings.yaml / .imported 兜底): ${JSON.stringify(config.groupAdmin)}`);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
catch (err) {
|
|
509
|
+
logger.warn?.(`[im-qqbot] settings.yaml groupAdmin 合并跳过: ${err instanceof Error ? err.message : String(err)}`);
|
|
510
|
+
}
|
|
511
|
+
// 入群申请事件(GROUP_JOIN_REQUEST)订阅: intent GROUP_MEMBER_EVENT = 1<<24, SDK 默认 FULL_INTENTS 不含它。
|
|
512
|
+
// ⚠️ 只在"群管理开启 + watchJoinRequests"时扩展 intents(Identify 携带未授权 intent 可能被拒连 4914/4915);
|
|
513
|
+
// 该值在 gateway 连接建立时确定 → 修改 config 后需重启才生效(非 live)。
|
|
514
|
+
const watchJoinRequests = !!config.groupAdmin?.enabled && !!config.groupAdmin?.watchJoinRequests;
|
|
515
|
+
const bot = new QQBot({
|
|
516
|
+
appId: config.appId,
|
|
517
|
+
appSecret: config.appSecret,
|
|
518
|
+
transport: 'websocket',
|
|
519
|
+
baseUrl: process.env.QQBOT_BASE_URL?.replace(/\/+$/, '') || 'https://api.bot.qq.com',
|
|
520
|
+
tokenBaseUrl: process.env.QQBOT_TOKEN_BASE_URL?.replace(/\/+$/, '') || 'https://api.bot.qq.com',
|
|
521
|
+
userAgent,
|
|
522
|
+
...(watchJoinRequests ? { intents: FULL_INTENTS | (1 << 24) } : {}),
|
|
523
|
+
// 调试隔离时可用 QQBOT_DEBUG_CONSOLE=1 让 QQBot 日志直出 stdout,便于定位
|
|
524
|
+
logger: process.env.QQBOT_DEBUG_CONSOLE ? console : logger,
|
|
525
|
+
});
|
|
526
|
+
logger.info(`QQBot SDK initialized (UA: ${userAgent})${watchJoinRequests ? ' [watchJoinRequests: GROUP_MEMBER_EVENT 已订阅]' : ''}`);
|
|
527
|
+
// ── 中间件链 ──
|
|
528
|
+
await setupMiddlewares(bot, config, manager, logger, ctx);
|
|
529
|
+
// 2026-10-20: 消息历史台账(落盘、按会话一个文件)
|
|
530
|
+
initMsgHistory(dataRootOf(config));
|
|
531
|
+
// ── 入站:经过中间件链后的消息交给 dsh agent ──
|
|
532
|
+
bot.on('message', async (mCtx) => {
|
|
533
|
+
const msg = mCtx.message;
|
|
534
|
+
// 2026-10-20 主人需求: 先判消息类型 + 记进「最近 2 分钟」内存缓冲(不落盘)
|
|
535
|
+
let inKind = 'text';
|
|
536
|
+
let inText = '';
|
|
537
|
+
try {
|
|
538
|
+
const anyMsg = msg;
|
|
539
|
+
const atts = anyMsg.attachments ?? [];
|
|
540
|
+
const ct = (a) => String(a.content_type ?? a.type ?? '');
|
|
541
|
+
inKind = atts.length === 0
|
|
542
|
+
? 'text'
|
|
543
|
+
: atts.some((a) => /image/i.test(ct(a))) ? 'image'
|
|
544
|
+
: atts.some((a) => /audio|voice|silk/i.test(ct(a))) ? 'voice'
|
|
545
|
+
: atts.some((a) => /video/i.test(ct(a))) ? 'video'
|
|
546
|
+
: 'file';
|
|
547
|
+
inText = inKind === 'text' ? String(anyMsg.content ?? '') : `[${inKind}]`;
|
|
548
|
+
const rScope = String(msg.groupOpenid ?? '') !== '' ? 'group' : 'c2c';
|
|
549
|
+
const rPeer = rScope === 'group' ? (msg.groupOpenid ?? msg.senderId ?? '') : (msg.senderId ?? '');
|
|
550
|
+
rememberInbound(rScope, String(rPeer ?? ''), {
|
|
551
|
+
msgId: String(msg.messageId ?? ''),
|
|
552
|
+
senderId: String(msg.senderId ?? ''),
|
|
553
|
+
senderName: String(msg.senderName ?? msg.senderId ?? ''),
|
|
554
|
+
at: Date.now(),
|
|
555
|
+
text: inText,
|
|
556
|
+
kind: inKind,
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
catch { /* 缓冲失败不影响主流程 */ }
|
|
560
|
+
// 自动撤回(2026-10-20 主人定): 命中关键词/附件类型 → **立刻撤回**(不等 AI)。
|
|
561
|
+
// ★ 位置说明: 这里已经是**中间件链 + 入站扩展全部跑完之后**,所以 mode='drop' 只决定
|
|
562
|
+
// "这条消息要不要进 agent",不改变扩展收到的 ctx、也不改扩展执行顺序 —— 不破坏扩展契约。
|
|
563
|
+
let autoDropped = false;
|
|
564
|
+
try {
|
|
565
|
+
const ar = config.autoRecall;
|
|
566
|
+
const msgId = String(msg.messageId ?? '');
|
|
567
|
+
if (ar?.enabled === true && String(msg.groupOpenid ?? '') !== '' && msgId !== '') {
|
|
568
|
+
const kws = (ar.keywords ?? []).map((k) => String(k).trim()).filter(Boolean);
|
|
569
|
+
const kinds = (ar.kinds ?? []).map(String);
|
|
570
|
+
const textLower = String(msg.content ?? '').toLowerCase();
|
|
571
|
+
const hitKw = kws.find((k) => textLower.includes(k.toLowerCase()));
|
|
572
|
+
const hitKind = kinds.includes(inKind);
|
|
573
|
+
if (hitKw !== undefined || hitKind) {
|
|
574
|
+
const gid = String(msg.groupOpenid ?? '');
|
|
575
|
+
const ga = manager.groupAdmin;
|
|
576
|
+
const dry = ar.dryRun === true;
|
|
577
|
+
logger.info(`auto-recall hit: gid=…${gid.slice(-4)} kind=${inKind} kw=${hitKw ?? '-'} dry=${dry} mode=${ar.mode ?? 'keep'}`);
|
|
578
|
+
if (!dry && ga && gid) {
|
|
579
|
+
void ga.recallMessage(gid, msgId, 'group').catch(() => undefined);
|
|
580
|
+
const secs = Math.max(0, Math.round(Number(ar.muteSeconds) || 0));
|
|
581
|
+
const sid = String(msg.senderId ?? '');
|
|
582
|
+
if (secs > 0 && /^[0-9A-Za-z]{32}$/u.test(sid)) {
|
|
583
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
584
|
+
const ex = new Date(Date.now() + secs * 1000);
|
|
585
|
+
const rfc = `${ex.getFullYear()}-${pad(ex.getMonth() + 1)}-${pad(ex.getDate())}T${pad(ex.getHours())}:${pad(ex.getMinutes())}:${pad(ex.getSeconds())}+08:00`;
|
|
586
|
+
void ga.setMemberMute(gid, sid, rfc).catch(() => undefined);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
if ((ar.mode ?? 'keep') === 'drop')
|
|
590
|
+
autoDropped = true;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
catch (err) {
|
|
595
|
+
logger.warn(`auto-recall error: ${err instanceof Error ? err.message : String(err)}`);
|
|
596
|
+
}
|
|
597
|
+
if (autoDropped) {
|
|
598
|
+
logger.debug('auto-recall drop: 该消息不进 agent(扩展已执行完)');
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
// QQ 远程审批: /approve|/deny CODE 最先拦截(消费后不再进 agent/普通聊天)
|
|
602
|
+
if (approvalController) {
|
|
603
|
+
const scope = msg.kind === 'group' ? 'group' : 'c2c';
|
|
604
|
+
const peerId = scope === 'group' ? (msg.groupOpenid ?? msg.senderId) : msg.senderId;
|
|
605
|
+
try {
|
|
606
|
+
const consumed = await approvalController.handleInbound(msg, {
|
|
607
|
+
scope, targetId: peerId, msgId: msg.messageId,
|
|
608
|
+
});
|
|
609
|
+
if (consumed)
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
catch (err) {
|
|
613
|
+
logger.warn(`approval inbound error: ${err instanceof Error ? err.message : String(err)}`);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
// QQ 远程提问的**文字兜底**(2026-09-11 主人定): 有待答提问时, 发起者发来的文字也算回答 ——
|
|
617
|
+
// 字母/序号/选项原文 → 选中选项(支持多选); 其它文字 → 作为自由回答(custom)透传给 AI。
|
|
618
|
+
// 没有待答提问时该方法立即返回 false, 零副作用(消息照常进 agent)。
|
|
619
|
+
if (questionController) {
|
|
620
|
+
const qScope = msg.kind === 'group' ? 'group' : 'c2c';
|
|
621
|
+
const qPeerId = qScope === 'group' ? (msg.groupOpenid ?? msg.senderId) : msg.senderId;
|
|
622
|
+
try {
|
|
623
|
+
const consumed = await questionController.handleInbound(msg, {
|
|
624
|
+
scope: qScope, targetId: qPeerId, msgId: msg.messageId,
|
|
625
|
+
});
|
|
626
|
+
if (consumed)
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
catch (err) {
|
|
630
|
+
logger.warn(`question inbound error: ${err instanceof Error ? err.message : String(err)}`);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
if (config.debug) {
|
|
634
|
+
logger.debug(`← message (post-middleware): ${JSON.stringify(msg, null, 2).slice(0, 500)}`);
|
|
635
|
+
}
|
|
636
|
+
await handleInbound(msg, manager, config, logger, mCtx.state);
|
|
637
|
+
});
|
|
638
|
+
// ── 出站:dsh session/event → QQ 消息 ──
|
|
639
|
+
// 获取 tools 服务(工具结果结构化展示,参考 dsh-TUI presentResult),可选
|
|
640
|
+
let toolsRegistry;
|
|
641
|
+
try {
|
|
642
|
+
toolsRegistry = ctx.get('tools');
|
|
643
|
+
}
|
|
644
|
+
catch {
|
|
645
|
+
toolsRegistry = undefined;
|
|
646
|
+
}
|
|
647
|
+
// 发送适配器:将 QQBot 实例适配为 QQBotSender(openStream 参数形态不同)
|
|
648
|
+
// 记录 bot 发给每个 peer 的最近消息历史,供 agent [RECALL(:N)] 按序号撤回自身消息。
|
|
649
|
+
const HISTORY_LIMIT = 10;
|
|
650
|
+
const sentByPeer = new Map();
|
|
651
|
+
const keyOf = (t) => `${t.scope}:${t.targetId}`;
|
|
652
|
+
const pushSent = (target, id, text, kind) => {
|
|
653
|
+
if (!id)
|
|
654
|
+
return;
|
|
655
|
+
const k = keyOf(target);
|
|
656
|
+
let arr = sentByPeer.get(k);
|
|
657
|
+
if (!arr) {
|
|
658
|
+
arr = [];
|
|
659
|
+
sentByPeer.set(k, arr);
|
|
660
|
+
}
|
|
661
|
+
arr.unshift({ target, id }); // 最新在前
|
|
662
|
+
if (arr.length > HISTORY_LIMIT)
|
|
663
|
+
arr.length = HISTORY_LIMIT;
|
|
664
|
+
// 2026-10-20 主人需求: 机器人自己发的消息也进 msg-recent 缓冲,
|
|
665
|
+
// 这样「自动撤回/按关键词搜索消息」也能覆盖自己发的。
|
|
666
|
+
try {
|
|
667
|
+
const sc = String(target.scope ?? 'group') === 'c2c' ? 'c2c' : 'group';
|
|
668
|
+
rememberSelf(sc, String(target.targetId ?? ''), { msgId: id, text, kind: kind ?? 'text' });
|
|
669
|
+
appendMsgHistory(sc, String(target.targetId ?? ''), { id, s: 'self', n: '机器人', t: Date.now(), k: kind ?? 'text', x: text ?? '', me: true });
|
|
670
|
+
}
|
|
671
|
+
catch { /* 记不了不影响发送 */ }
|
|
672
|
+
};
|
|
673
|
+
const doRecall = async (target, index) => {
|
|
674
|
+
const arr = sentByPeer.get(keyOf(target));
|
|
675
|
+
if (!arr)
|
|
676
|
+
return false;
|
|
677
|
+
const item = arr[index - 1];
|
|
678
|
+
if (!item)
|
|
679
|
+
return false;
|
|
680
|
+
try {
|
|
681
|
+
await bot.recallMessage(item.target, item.id);
|
|
682
|
+
arr.splice(index - 1, 1);
|
|
683
|
+
if (!arr.length)
|
|
684
|
+
sentByPeer.delete(keyOf(target));
|
|
685
|
+
return true;
|
|
686
|
+
}
|
|
687
|
+
catch (err) {
|
|
688
|
+
logger.error(`recall(${index}) failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
689
|
+
return false;
|
|
690
|
+
}
|
|
691
|
+
};
|
|
692
|
+
// 出站富媒体降级判定: 内容无 markdown 语法(且无 @提及/qqbot 标签)→ 走纯文本通道(msg_type:0),
|
|
693
|
+
// 避开 QQ 对 markdown 富媒体的严格频控(实测连发 5 条 markdown 后静默被拦)。
|
|
694
|
+
const hasMarkdownSyntax = (text) => {
|
|
695
|
+
const t = String(text || '');
|
|
696
|
+
return (/<@[A-Za-z0-9]+>|<qqbot-at-user|<qqbot-at-everyone|<emoji:|<#/.test(t) ||
|
|
697
|
+
t.includes('```') || t.includes('`') ||
|
|
698
|
+
/(^|\n)\s*(#{1,6}\s|>\s?|[-*+]\s|\d+\.\s)/.test(t) ||
|
|
699
|
+
/\*\*[^*]+\*\*/.test(t) ||
|
|
700
|
+
/\[([^\]\n]+)\]\(https?:[^)\n]+\)/.test(t) ||
|
|
701
|
+
/~~[^~\n]+~~/.test(t));
|
|
702
|
+
};
|
|
703
|
+
const sender = {
|
|
704
|
+
sendMarkdown: async (target, content) => {
|
|
705
|
+
try {
|
|
706
|
+
let rawText = String(content || '');
|
|
707
|
+
// 2026-10-21: markdown 通道也要自动传本地图 ——
|
|
708
|
+
// 扩展工具 send_md / 卡片 / sendText 都直接走这个 sender.sendMarkdown,
|
|
709
|
+
// 绕过了 OutboundRouter.send() 里的那次重写,所以这里必须再来一次。
|
|
710
|
+
if (rawText.indexOf('![') >= 0) {
|
|
711
|
+
try {
|
|
712
|
+
const ga = manager.groupAdmin;
|
|
713
|
+
if (ga)
|
|
714
|
+
rawText = await rewriteLocalMarkdownImages(rawText, { apiCall: ga.apiCall.bind(ga) });
|
|
715
|
+
// 2026-10-21(主人定):markdown 卡片通道里,本地图没传成功就**不发送**这条(正文不受影响,正文走 send())
|
|
716
|
+
{
|
|
717
|
+
const rw = lastMediaRewrite();
|
|
718
|
+
if (rw && Number(rw.failed || 0) > 0) {
|
|
719
|
+
throw new Error('图上传失败 ' + rw.failed + '/' + rw.matched + ',本条未发送');
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
catch { /* 失败保留原样 */ }
|
|
724
|
+
}
|
|
725
|
+
// 引用消息(2026-09-13 主人定): AI 写 [rf:短号] → 台账查表还原 msg_id, 出站带 message_reference 以"引用"形式发出
|
|
726
|
+
const refId = target.referenceMessageId;
|
|
727
|
+
if (refId) {
|
|
728
|
+
// 保留 target(含 msgId 被动回复)+ 加引用 —— SDK send(): body.msg_id 与 body.message_reference 并存,
|
|
729
|
+
// 2026-09-13 修: 之前用 tgtNoMsg 去 msgId 变纯主动, 主动消息易被 QQ 静默拦, 主人测试看不到引用
|
|
730
|
+
const hasMd = hasMarkdownSyntax(rawText);
|
|
731
|
+
const refBody = hasMd
|
|
732
|
+
? { target, msgType: 2, markdown: { content: rawText }, messageReference: { message_id: refId } }
|
|
733
|
+
: { target, msgType: 0, content: rawText, messageReference: { message_id: refId } };
|
|
734
|
+
try {
|
|
735
|
+
const resp = (await bot.send(refBody));
|
|
736
|
+
pushSent(target, resp?.id, rawText);
|
|
737
|
+
return resp;
|
|
738
|
+
}
|
|
739
|
+
catch (refErr) {
|
|
740
|
+
logger.warn(`引用消息发送失败, 降级为普通发送: ${refErr instanceof Error ? refErr.message : String(refErr)}`);
|
|
741
|
+
// fallthrough: 去掉引用, 走原有发送路径
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
// 纯文本降级: 无 markdown 语法/@标签 → 直接纯文本通道, 省富媒体额度与频控
|
|
745
|
+
if (!hasMarkdownSyntax(rawText)) {
|
|
746
|
+
const respT = (await bot.sendText(target, rawText));
|
|
747
|
+
pushSent(target, respT?.id, rawText);
|
|
748
|
+
return respT;
|
|
749
|
+
}
|
|
750
|
+
const resp = (await bot.sendMarkdown(target, content));
|
|
751
|
+
pushSent(target, resp?.id, rawText);
|
|
752
|
+
return resp;
|
|
753
|
+
}
|
|
754
|
+
catch (err) {
|
|
755
|
+
const firstErr = err instanceof Error ? err.message : String(err);
|
|
756
|
+
// 出站失败落盘(2026-10-08 加):以后"某个会话发不出消息"能直接查这条日志,不用靠猜。
|
|
757
|
+
diagWrite('qqbot-send-diag', `[${new Date().toISOString()}] sendMarkdown 失败: scope=${target.scope} target=${String(target.targetId ?? '').slice(0, 12)}… msgId=${target.msgId ? `…${String(target.msgId).slice(-8)}` : '(无)'} err=${firstErr}`);
|
|
758
|
+
// ── ① 被动回复(msgId) 被拒 → **去掉 msgId 转主动重试一次** ──────────────────
|
|
759
|
+
// ⚠️ 2026-10-08 修(主人实测:崩溃重启后"那个会话再也发不出消息,得新开会话才行"):
|
|
760
|
+
// passive 模式下**所有**出站都带 msgId(见 outbound.ts 的 effectiveTarget),
|
|
761
|
+
// msgId 一旦失效(过期 / 被动回复配额用尽 / 崩溃重启残留的陈旧 id),
|
|
762
|
+
// 原来这里**直接 throw** ⇒ outbound 只记一行日志 ⇒ 消息静默丢失 ⇒ 整个会话像哑了。
|
|
763
|
+
// 转主动只多花一点主动额度,远好过彻底发不出去;成败都落盘,便于事后溯源。
|
|
764
|
+
if (target.msgId) {
|
|
765
|
+
try {
|
|
766
|
+
const act = { scope: target.scope, targetId: target.targetId };
|
|
767
|
+
const r0 = (await bot.sendMarkdown(act, content));
|
|
768
|
+
pushSent(act, r0?.id);
|
|
769
|
+
logger.warn(`被动回复被拒(msgId 失效) → 已去掉 msgId 转主动发送成功: ${firstErr}`);
|
|
770
|
+
diagWrite('qqbot-send-diag', `[${new Date().toISOString()}] 已降级为主动发送成功 target=${String(target.targetId ?? '').slice(0, 12)}…`);
|
|
771
|
+
return r0;
|
|
772
|
+
}
|
|
773
|
+
catch (errA) {
|
|
774
|
+
const secondErr = errA instanceof Error ? errA.message : String(errA);
|
|
775
|
+
logger.error(`被动回复被拒且转主动也失败: 被动轮=${firstErr} / 主动轮=${secondErr}`);
|
|
776
|
+
diagWrite('qqbot-send-diag', `[${new Date().toISOString()}] 转主动仍失败 target=${String(target.targetId ?? '').slice(0, 12)}… err=${secondErr}`);
|
|
777
|
+
throw errA;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
// ── ② 纯主动(无 msgId) → 原有降级链: markdown → 纯文本 → c2c is_wakeup ──
|
|
781
|
+
{
|
|
782
|
+
// ⚠️ 清洗仅针对 markdown 语法字符; QQ at 标签必须原样保留——
|
|
783
|
+
// 实测(2026-09-06): 高亮 @ 用 `<@openid>`(无斜杠)或 `<qqbot-at-user id="openid" />`;
|
|
784
|
+
// 剥掉 '>' 会把标签弄残 → QQ 不渲染。这里先把两类 at 标签暂存, 清洗完再恢复。
|
|
785
|
+
const plain = String(content || '')
|
|
786
|
+
.replace(/<qqbot-at-user\s+id="([A-Za-z0-9]+)"\s*\/>/g, '\u0001ATQ:$1\u0001')
|
|
787
|
+
.replace(/<@([A-Za-z0-9]+)>/g, '\u0001ATA:$1\u0001')
|
|
788
|
+
.replace(/[#*`_~>]/g, '')
|
|
789
|
+
.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
|
|
790
|
+
.replace(/\u0001ATQ:([A-Za-z0-9]+)\u0001/g, '<qqbot-at-user id="$1" />')
|
|
791
|
+
.replace(/\u0001ATA:([A-Za-z0-9]+)\u0001/g, '<@$1>')
|
|
792
|
+
.trim();
|
|
793
|
+
if (plain) {
|
|
794
|
+
try {
|
|
795
|
+
const r2 = (await bot.sendText(target, plain));
|
|
796
|
+
pushSent(target, r2?.id);
|
|
797
|
+
logger.warn(`主动推送 markdown 被拒, 已降级纯文本发送: ${firstErr}`);
|
|
798
|
+
return r2;
|
|
799
|
+
}
|
|
800
|
+
catch (err2) {
|
|
801
|
+
if (target.scope === 'c2c') {
|
|
802
|
+
try {
|
|
803
|
+
const r3 = (await bot.sendWakeup(target, plain));
|
|
804
|
+
pushSent(target, r3?.id);
|
|
805
|
+
logger.warn(`主动纯文本被拒, 已降级 is_wakeup 召回通道: ${err2 instanceof Error ? err2.message : String(err2)}`);
|
|
806
|
+
return r3;
|
|
807
|
+
}
|
|
808
|
+
catch (err3) {
|
|
809
|
+
logger.error(`主动推送三通道全拒: md=${firstErr} / text=${err2 instanceof Error ? err2.message : String(err2)} / wakeup=${err3 instanceof Error ? err3.message : String(err3)}`);
|
|
810
|
+
throw err3;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
logger.error(`主动推送两通道被拒: md=${firstErr} / text=${err2 instanceof Error ? err2.message : String(err2)}`);
|
|
814
|
+
throw err2;
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
throw err;
|
|
819
|
+
}
|
|
820
|
+
},
|
|
821
|
+
sendMarkdownWithKeyboard: async (target, content, keyboard) => {
|
|
822
|
+
// 卡片按钮(审批/提问): bot.send 显式 msg_type=2 + keyboard。
|
|
823
|
+
// 失败直接抛(不静默降级)——由调用方决定文本兜底, 避免"卡片+文本码"双发。
|
|
824
|
+
const resp = (await bot.send({ target, msgType: 2, markdown: { content }, keyboard: keyboard }));
|
|
825
|
+
pushSent(target, resp?.id);
|
|
826
|
+
return resp;
|
|
827
|
+
},
|
|
828
|
+
openStream: (target) => bot.openStream({
|
|
829
|
+
target: {
|
|
830
|
+
scope: target.scope,
|
|
831
|
+
targetId: target.targetId,
|
|
832
|
+
msgId: target.msgId,
|
|
833
|
+
},
|
|
834
|
+
}),
|
|
835
|
+
sendMedia: async (target, kind, source) => {
|
|
836
|
+
// ── P0-4 本地媒体路径闸门:任意绝对路径 → 只允许项目内媒体/表情包目录 ──
|
|
837
|
+
if (source?.localPath) source = { ...source, localPath: assertMediaPath(source.localPath, config) };
|
|
838
|
+
// ── P1 表情包闸门(唯一咽喉, [MEDIA]标记 与 send_media 工具都汇于此) ──
|
|
839
|
+
// 只对"库内图片的主动发送"生效; URL/非库路径/语音视频文件放行。
|
|
840
|
+
let gateHit = false;
|
|
841
|
+
if (kind === 'image' && source.localPath) {
|
|
842
|
+
const groupId = target.scope === 'group' ? target.targetId : undefined;
|
|
843
|
+
const verdict = stickerGate.checkMedia({ groupId, kind, localPath: source.localPath });
|
|
844
|
+
if (!verdict.allowed) {
|
|
845
|
+
throw new StickerGateDenied(verdict.reason ?? '被闸门拦截');
|
|
846
|
+
}
|
|
847
|
+
gateHit = verdict.isSticker && !!groupId;
|
|
848
|
+
}
|
|
849
|
+
const srcOpt = source.url
|
|
850
|
+
? { url: source.url }
|
|
851
|
+
: source.localPath
|
|
852
|
+
? { localPath: source.localPath }
|
|
853
|
+
: {};
|
|
854
|
+
let out;
|
|
855
|
+
if (kind === 'image')
|
|
856
|
+
out = await bot.sendImage(target, srcOpt);
|
|
857
|
+
else if (kind === 'video')
|
|
858
|
+
out = await bot.sendVideo(target, srcOpt);
|
|
859
|
+
else if (kind === 'voice')
|
|
860
|
+
out = await bot.sendVoice(target, srcOpt);
|
|
861
|
+
else
|
|
862
|
+
out = await bot.sendFile(target, srcOpt);
|
|
863
|
+
const id = out?.message?.id;
|
|
864
|
+
pushSent(target, id);
|
|
865
|
+
// 发送成功后才记录(失败不占预算/去重); 库内图且群内才算表情包发送
|
|
866
|
+
if (gateHit && id !== undefined && source.localPath) {
|
|
867
|
+
try {
|
|
868
|
+
stickerGate.noteSent(target.scope === 'group' ? target.targetId : undefined, source.localPath);
|
|
869
|
+
}
|
|
870
|
+
catch { /* 记录失败不影响发送 */ }
|
|
871
|
+
}
|
|
872
|
+
return { id };
|
|
873
|
+
},
|
|
874
|
+
recallLast: (target) => doRecall(target, 1),
|
|
875
|
+
recallByIndex: (target, index) => doRecall(target, index),
|
|
876
|
+
// c2c 主动召回(官方 is_wakeup:true; 群聊调用会抛, 由调用方保证只用于 c2c)
|
|
877
|
+
sendC2cWakeup: (target, content) => bot.sendWakeup(target, content),
|
|
878
|
+
};
|
|
879
|
+
// 把发送能力注入 SessionManager,供 QQ 会话 provide qqChannel 服务给通道工具
|
|
880
|
+
manager.installChannelSender(sender);
|
|
881
|
+
// 全局桥: 通道工具 execute 的兜底解析(不依赖 setup/provide, 防重启后 setup 未跑)
|
|
882
|
+
setChannelBridge({ manager, sender });
|
|
883
|
+
// ── 群事件(M2 群组管理器 + P2.5): rawEvent 分发 ──
|
|
884
|
+
// · GROUP_JOIN_REQUEST / GROUP_MEMBER_ADD: intent GROUP_MEMBER_EVENT(1<<24), 需 watchJoinRequests 已扩 intents;
|
|
885
|
+
// · GROUP_ADD_ROBOT: intent GROUP_AND_C2C_EVENT(1<<25, SDK FULL_INTENTS 基础订阅即收)。
|
|
886
|
+
// 同一 bot 仅一个群管理实例; 事件带 group_openid, 天然按群路由。
|
|
887
|
+
bot.on('rawEvent', (rawCtx) => {
|
|
888
|
+
const et = rawCtx.eventType;
|
|
889
|
+
if (et === 'GROUP_JOIN_REQUEST') {
|
|
890
|
+
logger.info(`[group-join] rawEvent GROUP_JOIN_REQUEST 到达`);
|
|
891
|
+
void handleGroupJoinRequestEvent(rawCtx.data, { sender, config, logger, manager }).catch((err) => {
|
|
892
|
+
logger.error(`[group-join] 事件处理异常: ${err instanceof Error ? err.message : String(err)}`);
|
|
893
|
+
});
|
|
894
|
+
return;
|
|
895
|
+
}
|
|
896
|
+
if (et === 'GROUP_MEMBER_ADD') {
|
|
897
|
+
logger.info(`[group-hub] rawEvent GROUP_MEMBER_ADD 到达`);
|
|
898
|
+
void handleGroupMemberAddEvent(rawCtx.data, { config, logger, manager }).catch((err) => {
|
|
899
|
+
logger.error(`[group-hub] member_add 处理异常: ${err instanceof Error ? err.message : String(err)}`);
|
|
900
|
+
});
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
903
|
+
if (et === 'GROUP_ADD_ROBOT') {
|
|
904
|
+
logger.info(`[group-hub] rawEvent GROUP_ADD_ROBOT 到达`);
|
|
905
|
+
void handleGroupAddRobotEvent(rawCtx.data, { config, logger, manager }).catch((err) => {
|
|
906
|
+
logger.error(`[group-hub] add_robot 处理异常: ${err instanceof Error ? err.message : String(err)}`);
|
|
907
|
+
});
|
|
908
|
+
}
|
|
909
|
+
});
|
|
910
|
+
// ── QQ 远程审批: ACP 模式接入(专家考古实证, 见 qq-approval.ts 头注) ──
|
|
911
|
+
// ①dispatch: ownership(只处理本 bot 的 agent)+ enableApprovals 闸门;
|
|
912
|
+
// ②监听: 注册在插件 apply ctx, 用 {prepend:true} 插到链首(抢在宿主 GUI 转发器 dsh-api-remotes 之前)。
|
|
913
|
+
approvalController = new QqApprovalController(manager, sender, logger, () => config.approvalTimeoutMs);
|
|
914
|
+
// 注册进 ns 注册表(Web 审批浮层经 settings-host 同源路由读写); ns 取 settingsNs 与 index.ts 一致(myNs 见顶部)
|
|
915
|
+
registerApprovalController(myNs, approvalController);
|
|
916
|
+
registerSessionManager(myNs, manager);
|
|
917
|
+
// ⚠️ 2026-09-11 多实例修复: dispatch 不再走模块级单例(会被多实例覆盖) —— 直接把本实例的
|
|
918
|
+
// 处理逻辑作为 handler 传入 makeApprovalListener(闭包捕获本实例 manager/controller)。
|
|
919
|
+
const myApprovalHandler = ((request, next) => {
|
|
920
|
+
const diagA = (line) => { try {
|
|
921
|
+
globalThis.qqApprovalDiag = (globalThis.qqApprovalDiag || []);
|
|
922
|
+
globalThis.qqApprovalDiag.push('[' + new Date().toISOString() + '] ' + line);
|
|
923
|
+
}
|
|
924
|
+
catch { /* 忽略 */ } };
|
|
925
|
+
diagA('dispatch enter enable=' + config.enableApprovals);
|
|
926
|
+
if (!config.enableApprovals) {
|
|
927
|
+
diagA('dispatch next: disabled');
|
|
928
|
+
return next();
|
|
929
|
+
}
|
|
930
|
+
const reqAgent = request.agent;
|
|
931
|
+
const rec = reqAgent ? manager.findByAgent(reqAgent) : undefined;
|
|
932
|
+
diagA('dispatch find=' + (rec ? 'hit(' + rec.scope + ')' : 'miss'));
|
|
933
|
+
if (!reqAgent || !rec)
|
|
934
|
+
return next(); // 非本 bot agent → 放行给 GUI/ACP
|
|
935
|
+
diagA('dispatch -> request()');
|
|
936
|
+
return approvalController.request(request, next);
|
|
937
|
+
});
|
|
938
|
+
setApprovalDispatch(myNs, myApprovalHandler);
|
|
939
|
+
// 挂到宿主根 ctx(与 Web GUI 审批转发器同层)并 prepend 插链首 —— 保证本 bot 的审批先被 QQ 通道接管
|
|
940
|
+
const approvalCtx = ((ctx.root) || ctx);
|
|
941
|
+
approvalCtx.on('approval/request', makeApprovalListener(myApprovalHandler), { prepend: true });
|
|
942
|
+
// ── expose:'all' 的扩展工具:**启动即注册**(2026-10-10 主人定)────────────
|
|
943
|
+
// ⚠️ 之前它只挂在 agent/pre-step 上(那是"每个 QQ 会话每步"才触发)⇒
|
|
944
|
+
// QQ 不活跃时永远注册不上(主人原话:"不能 qq 不活跃也注册吗" —— 对)。
|
|
945
|
+
// 现在:插件启动就注册一次,并每 5 秒重试(最多 12 次,约 1 分钟)兜住"实例/扩展目录稍后才就绪"。
|
|
946
|
+
// 用动态 import 避免与 channel-tools 的循环依赖;函数内部自己 `ctx.root ?? ctx`,幂等 + 节流。
|
|
947
|
+
// 工具名 = `<name>__<人设id>`(分隔符只能是 [a-zA-Z0-9_-],`@` 会被 LLM API 拒 —— 见 channel-tools 注释)。
|
|
948
|
+
void (async () => {
|
|
949
|
+
for (let i = 0; i < 12; i++) {
|
|
950
|
+
try {
|
|
951
|
+
const ct = await import('../channel-tools.js');
|
|
952
|
+
ct.ensureExtToolsGlobal(ctx);
|
|
953
|
+
}
|
|
954
|
+
catch { /* 单次失败继续重试 */ }
|
|
955
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
956
|
+
}
|
|
957
|
+
})();
|
|
958
|
+
logger.info('[im-qqbot] expose:all 扩展工具:启动即注册(含重试)已启动');
|
|
959
|
+
// ── 首次运行"见面礼":把本包自带的扩展示例铺到用户的扩展目录(2026-10-10 主人定)──
|
|
960
|
+
// 用户的工作目录里生成 `dshqqbot/` 之后,不用自己手动搬示例 ——
|
|
961
|
+
// 插件启动就把 examples/ext-tools/*.mjs 补进 `{dataRoot}/.qqbot-extensions/tools/`。
|
|
962
|
+
// ⚠️ 只补不覆盖(用户改过的同名文件一律不动),失败静默,绝不影响启动。
|
|
963
|
+
void (async () => {
|
|
964
|
+
try {
|
|
965
|
+
const es = await import('../features/extension-store.js');
|
|
966
|
+
const n = es.seedExampleTools(dataRootOf(config), logger);
|
|
967
|
+
if (n > 0)
|
|
968
|
+
logger.info(`[im-qqbot] 已自动铺设 ${n} 个扩展示例`);
|
|
969
|
+
}
|
|
970
|
+
catch { /* 静默 */ }
|
|
971
|
+
})();
|
|
972
|
+
// ── 启动钩子(ext-hooks,第四套扩展;2026-10-12)────────────────────────────
|
|
973
|
+
// `{dataRoot}/.qqbot-extensions/hooks/*.mjs` 里的模块在**插件启动时自动跑一次**
|
|
974
|
+
// (不需要任何调用方触发)—— 用途:恢复上次没跑完的长期任务、注册监听、起定时器、预取数据。
|
|
975
|
+
//
|
|
976
|
+
// ⚠️ 三条硬纪律(实现都在 features/ext-hooks.ts,这里只负责接线):
|
|
977
|
+
// ① 单钩子独立 try/catch ⇒ 抛错绝不影响插件启动、也不影响其它钩子;
|
|
978
|
+
// ② 单钩子 30s 超时 ⇒ 异步钩子不会把启动拖死(超时只告警并放行);
|
|
979
|
+
// ③ 目录缺失/为空完全安静 ⇒ 不报错、不打日志。
|
|
980
|
+
// 放在 seedExampleTools 之后 ⇒ **首次安装当次启动**就能跑到刚铺进去的示例钩子(不用重启宿主)。
|
|
981
|
+
// 与 seed 同为 fire-and-forget:不阻塞启动、永不抛出。
|
|
982
|
+
void (async () => {
|
|
983
|
+
try {
|
|
984
|
+
const hooks = await import('../features/ext-hooks.js');
|
|
985
|
+
const r = await hooks.runStartupHooks({ dataRoot: dataRootOf(config), logger, ctx, config });
|
|
986
|
+
if (r.total > 0) {
|
|
987
|
+
logger.info(`[im-qqbot] 启动钩子: ${r.total} 个(成功 ${r.ok} / 失败 ${r.failed} / 超时 ${r.timedOut})`);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
catch (err) {
|
|
991
|
+
// 引擎内部已经永不抛出;真走到这里说明连 import 都失败了 —— 仍只告警
|
|
992
|
+
logger.warn?.(`[im-qqbot] 启动钩子装载异常(已忽略, 不影响插件启动): ${err instanceof Error ? err.message : String(err)}`);
|
|
993
|
+
}
|
|
994
|
+
})();
|
|
995
|
+
logger.info(`[im-qqbot] QQ 远程审批接线就绪(${config.enableApprovals ? '已启用' : '默认关闭, Web 设置可热开'})`);
|
|
996
|
+
// ── QQ 远程提问(按钮卡片版): ask_user_question → QQ 卡片按钮 ──
|
|
997
|
+
// 宿主 user-questions/request 是 Agent 作用域 waterfall(同 approval), Web UI 答案器
|
|
998
|
+
// 在宿主引导期注册 → 本监听同样 {prepend:true} 抢链首。enableQuestions 默认开(与审批独立开关)。
|
|
999
|
+
const enableUserQuestions = config.enableUserQuestions !== false;
|
|
1000
|
+
questionController = new QqUserQuestionsController(manager, sender, logger, () => config.approvalTimeoutMs || 120000,
|
|
1001
|
+
// 提问工作方式(现读/live 热更): 'async'=后台(默认, 卡片发出即返回, 不卡回合) / 'blocking'=旧行为
|
|
1002
|
+
() => (config.questionsMode === 'blocking' ? 'blocking' : 'async'),
|
|
1003
|
+
// openid → 昵称:延迟求值(botplayController 在本段之后才创建)
|
|
1004
|
+
(target, openid) => {
|
|
1005
|
+
try {
|
|
1006
|
+
return botplayController?.memberName(target, openid) || '';
|
|
1007
|
+
}
|
|
1008
|
+
catch {
|
|
1009
|
+
return '';
|
|
1010
|
+
}
|
|
1011
|
+
});
|
|
1012
|
+
registerQuestionController(myNs, questionController);
|
|
1013
|
+
ctx.on('user-questions/request', (async (request, next) => {
|
|
1014
|
+
if (!enableUserQuestions)
|
|
1015
|
+
return next();
|
|
1016
|
+
const reqAgent = request.agent;
|
|
1017
|
+
if (!reqAgent || !manager.findByAgent(reqAgent))
|
|
1018
|
+
return next(); // 非本 bot agent → GUI 兜底
|
|
1019
|
+
try {
|
|
1020
|
+
return await questionController.request(request, next);
|
|
1021
|
+
}
|
|
1022
|
+
catch (err) {
|
|
1023
|
+
logger.warn(`[qq-questions] request 异常: ${err instanceof Error ? err.message : String(err)}`);
|
|
1024
|
+
return next();
|
|
1025
|
+
}
|
|
1026
|
+
}), { prepend: true });
|
|
1027
|
+
logger.info(`[im-qqbot] QQ 远程提问接线就绪(${enableUserQuestions ? '启用' : '关闭'})`);
|
|
1028
|
+
// ── botplay 互动事件装配器(2026-09-08, Phase1 MVP) ──
|
|
1029
|
+
// 事件配置真相源 = {dataRoot}/botplay-events.json (2026-09-10 M4.3 起, 控制器现读支持热更)。
|
|
1030
|
+
// ⚠️ 修复: 启动时把文件内容回填 config.botplayEvents —— 命令层/其他消费者仍读该字段,
|
|
1031
|
+
// 而 settings 层自迁移后已被清空(空数组), 若不回填会导致 /botplay 查不到任何事件。
|
|
1032
|
+
try {
|
|
1033
|
+
const seeded = readBotplayEvents(dataRootOf(config), () => (Array.isArray(config.botplayEvents) ? config.botplayEvents : []));
|
|
1034
|
+
if (Array.isArray(seeded) && seeded.length > 0) {
|
|
1035
|
+
config.botplayEvents = seeded;
|
|
1036
|
+
logger.info(`[im-qqbot] botplay 事件已从文件装载: ${seeded.length} 个`);
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
catch (err) {
|
|
1040
|
+
logger.warn?.(`[im-qqbot] botplay 事件文件装载失败: ${err instanceof Error ? err.message : String(err)}`);
|
|
1041
|
+
}
|
|
1042
|
+
// /botplay 命令 → triggerBotplay 模块级注册表 → 这里实现(带 sender/manager)发卡。
|
|
1043
|
+
botplayController = new BotplayController(manager, sender, logger,
|
|
1044
|
+
// 事件配置从 {dataRoot}/.qqbot/botplay-events.json 现读(2026-09-10 M4.3 独立存储,
|
|
1045
|
+
// 自动迁移 settings 旧数据; 文件缺失回退 settings 现值)
|
|
1046
|
+
() => readBotplayEvents(dataRootOf(config), () => (Array.isArray(config.botplayEvents) ? config.botplayEvents : [])), () => (Array.isArray(config.groupAdmin?.owners) ? config.groupAdmin.owners : []), () => stickerDataDir,
|
|
1047
|
+
// 数据根(2026-10-05): botplay 自定义事件模块放 {dataRoot}/.qqbot-extensions/botplay/
|
|
1048
|
+
// ⚠️ 必须与事件文件同源(dataRootOf), 否则面板报的路径与实际加载的不是一处, 主人改错文件还找不到原因
|
|
1049
|
+
() => dataRootOf(config));
|
|
1050
|
+
registerBotplayController(myNs, botplayController);
|
|
1051
|
+
// ★ 内核句柄:把插件 ctx 交给 botplay(卡片 ctx.kernel / 与扩展工具·命令对齐)
|
|
1052
|
+
botplayController.setKernel(ctx);
|
|
1053
|
+
// 昵称兜底(2026-10-05 主人定: "兜底的时候用 api,其余的时候用台账"):
|
|
1054
|
+
// 台账/会话壳都查不到时, 后台调官方「获取群成员信息」接口拿 username。
|
|
1055
|
+
// ⚠️ 该接口官方标注「内邀接入中」(11253=无权限) ⇒ 失败静默、只记一行日志。
|
|
1056
|
+
// 借 manager.groupAdmin(懒建; groupAdmin.enabled=false 时为 undefined ⇒ 自动跳过)。
|
|
1057
|
+
botplayController.setGroupAdminGetter(() => manager.groupAdmin);
|
|
1058
|
+
// 卡片(= .mjs 代码)需要"钥匙"而不是"被包好的能力": 直接把 appId/appSecret 给它,
|
|
1059
|
+
// 它就能自己换 access_token 调任意官方 API(查成员/发消息/上传媒体/禁言…)。
|
|
1060
|
+
botplayController.setCredentialsGetter(() => ({
|
|
1061
|
+
appId: String(config.appId ?? ''),
|
|
1062
|
+
appSecret: String(config.appSecret ?? ''),
|
|
1063
|
+
}));
|
|
1064
|
+
setBotplayTriggerImpl(myNs, (target, eventId, triggererId) => botplayController.trigger(target, eventId, triggererId));
|
|
1065
|
+
setBotplayCatalogImpl(myNs, (target, page) => botplayController.sendCatalog(target, page));
|
|
1066
|
+
// 预设切换卡片(2026-09-10): /preset 无参发按钮卡, 点击热切人格(仿 botplay 翻页)
|
|
1067
|
+
const presetSwitcher = new PresetSwitcherController(manager, sender, logger);
|
|
1068
|
+
setPresetCardImpl(myNs, (target, scope, peerId, page) => presetSwitcher.sendCard(target, scope, peerId, page ?? 0));
|
|
1069
|
+
// 指令型按钮(Phase2): 点击后执行斜杠命令(不经 AI)。复用 buildCommandList 的 handler,
|
|
1070
|
+
// 模拟一个最小命令 ctx(command 名称/空参 + 消息壳), 返回 handler 结果文本。
|
|
1071
|
+
// 指令型按钮(Phase2): 点击后执行斜杠命令(不经 AI)。复用 buildCommandList 的 handler,
|
|
1072
|
+
// 模拟一个最小命令 ctx(command 名称/空参 + 消息壳), 返回 handler 结果文本。
|
|
1073
|
+
// ⚠️ 2026-09-10: 抽成具名函数 —— botplay 卡片(bp:) 与「📝 卡片」编辑器发的自定义卡(bpk:)
|
|
1074
|
+
// 共用同一条命令执行链路(见 features/card-callback.ts)。
|
|
1075
|
+
// ⚠️ 2026-10-08 修:`senderId` 原为**写死空串** ⇒ 指令型按钮执行时拿不到"谁点的"
|
|
1076
|
+
// (签到、按人统计这类场景全部做不了)。交互事件里本来就有点击者 openid
|
|
1077
|
+
// (`group_member_openid` / `user_openid`),这里补成可选第三参 `actorOpenid`。
|
|
1078
|
+
const runButtonCommand = async (cmdName, target, actorOpenid) => {
|
|
1079
|
+
const cmdList = buildCommandList({ manager, config });
|
|
1080
|
+
const cmd = cmdList.find((c) => (Array.isArray(c.name) ? c.name : [c.name]).map(String).includes(cmdName));
|
|
1081
|
+
if (!cmd)
|
|
1082
|
+
return `未知指令「${cmdName}」(指令型按钮可用的: ${cmdList.filter((c) => !c.hidden).map((c) => (Array.isArray(c.name) ? c.name[0] : c.name)).join(', ')})`;
|
|
1083
|
+
const fakeCtx = {
|
|
1084
|
+
message: { kind: target.scope === 'group' ? 'group' : 'c2c', senderId: String(actorOpenid ?? ''), groupOpenid: target.scope === 'group' ? target.targetId : undefined },
|
|
1085
|
+
replyTarget: target,
|
|
1086
|
+
command: { name: cmdName, args: [], raw: '' },
|
|
1087
|
+
// 2026-10-25 兼容别名:与 middleware-setup 保持一致(按钮触发的命令没有参数)
|
|
1088
|
+
args: '',
|
|
1089
|
+
rawArgs: '',
|
|
1090
|
+
// 部分命令(如 /bot-help)直接经 cmdCtx.bot.sendMarkdown 分段发消息 → 桥到真实 sender
|
|
1091
|
+
bot: { sendMarkdown: async (t, c) => sender.sendMarkdown(t || target, c) },
|
|
1092
|
+
};
|
|
1093
|
+
const result = await cmd.handler(fakeCtx);
|
|
1094
|
+
if (typeof result === 'string')
|
|
1095
|
+
return result;
|
|
1096
|
+
if (result && typeof result === 'object') {
|
|
1097
|
+
const r = result;
|
|
1098
|
+
if (r.kind === 'text' && r.content)
|
|
1099
|
+
return r.content;
|
|
1100
|
+
}
|
|
1101
|
+
return '';
|
|
1102
|
+
};
|
|
1103
|
+
botplayController.setCommandExecutor(runButtonCommand);
|
|
1104
|
+
// 自定义卡片按钮回调(2026-09-10 主人要求: 卡片按钮支持「回文本 / 跳链接 / 执行命令」)。
|
|
1105
|
+
// 「📝 卡片」编辑器发的卡是裸卡、没有 botplay 事件挂靠 → 由本控制器兜底处理点击
|
|
1106
|
+
// (host 发卡时把按钮动作写进 {dataRoot}/.qqbot/card-callbacks.json, data 前缀 bpk:)。
|
|
1107
|
+
cardCallbackController = createCardCallbackController({
|
|
1108
|
+
dataRoot: dataRootOf(config),
|
|
1109
|
+
sendText: async (target, text) => { await sender.sendMarkdown(target || target, text); },
|
|
1110
|
+
commandExecutor: (cmdName, target, actorOpenid) => runButtonCommand(cmdName, target, actorOpenid),
|
|
1111
|
+
logger,
|
|
1112
|
+
});
|
|
1113
|
+
// ── 扩展工具按钮回调(2026-10-08 新增)──────────────────────────────
|
|
1114
|
+
// 让 `{dataRoot}/.qqbot-extensions/tools/*.mjs` 发出的
|
|
1115
|
+
// `ext:<工具名>:<卡id>:<按钮id>` 回调按钮,能被派发给该工具的 `onInteraction(ctx, info)`
|
|
1116
|
+
// (卡片注册表 features/ext-tool-cards.ts;工具契约 extension-store.ts 的 ExtensionToolDef)。
|
|
1117
|
+
// ctx 用 makeExtCaps **现场组装** —— 保证"点按钮时拿到的能力"与"run() 时拿到的能力"同一套。
|
|
1118
|
+
extToolInteractionController = createExtToolInteractionController({
|
|
1119
|
+
dataRoot: dataRootOf(config),
|
|
1120
|
+
logger,
|
|
1121
|
+
makeCtx: ({ toolName, replyTarget, actor, scope, peerId, clickedBefore }) => {
|
|
1122
|
+
const owners = Array.isArray(config.groupAdmin?.owners) ? config.groupAdmin.owners.map(String) : [];
|
|
1123
|
+
const caps = makeExtCaps({
|
|
1124
|
+
dataRoot: dataRootOf(config),
|
|
1125
|
+
logger,
|
|
1126
|
+
appId: String(config.appId ?? ''),
|
|
1127
|
+
appSecret: String(config.appSecret ?? ''),
|
|
1128
|
+
sender: sender,
|
|
1129
|
+
replyTarget,
|
|
1130
|
+
scope,
|
|
1131
|
+
peerId,
|
|
1132
|
+
actorOpenid: actor.openid,
|
|
1133
|
+
selfName: toolName,
|
|
1134
|
+
owners,
|
|
1135
|
+
kind: 'tools',
|
|
1136
|
+
// ⚠️ 2026-10-08 补(主人实测:回执说"已通知 AI",AI 那边什么都没收到):
|
|
1137
|
+
// caps.appendWake 靠 **该会话的 agent.followup** 才能唤醒;漏传时它会静默 return false
|
|
1138
|
+
// (fail-soft 恰好把失败吞掉)⇒ 症状就是"嘴上说通知了、上下文里啥也没有"。
|
|
1139
|
+
// 与 channel-tools 里给扩展工具 run() 的 env 保持一致(那边本来就传了 agent)。
|
|
1140
|
+
agent: (manager.findByPeer(scope === 'group' ? 'group' : 'c2c', peerId)?.agent ?? undefined),
|
|
1141
|
+
});
|
|
1142
|
+
// 点击者身份(与 botplay 同口径:owners 白名单判 isOwner)
|
|
1143
|
+
// name 暂留空(事件里只有 openid);需要昵称的模块可自行查群成员台账
|
|
1144
|
+
caps['performer'] = { openid: actor.openid, name: '', isOwner: !!actor.openid && owners.includes(actor.openid) };
|
|
1145
|
+
caps['clickedBefore'] = clickedBefore; // 内存态提示;权威判重请用 caps.store 落盘
|
|
1146
|
+
return caps;
|
|
1147
|
+
},
|
|
1148
|
+
sendReceipt: async (target, text) => {
|
|
1149
|
+
try {
|
|
1150
|
+
await sender.sendMarkdown(target || target, text);
|
|
1151
|
+
}
|
|
1152
|
+
catch { /* ignore */ }
|
|
1153
|
+
},
|
|
1154
|
+
});
|
|
1155
|
+
logger.info('[im-qqbot] botplay 互动事件接线就绪(/botplay 触发发卡, dock🎮装配, 保存即热更; 指令型按钮已接命令层)');
|
|
1156
|
+
// ── 按钮回调(INTERACTION_CREATE, type=11): 审批/提问卡片共用分发 ──
|
|
1157
|
+
// SDK 事件: bot.on('interaction', (ctx, event) => …); 需 PUT /interactions/{id} 回应防 loading。
|
|
1158
|
+
if (typeof bot.on === 'function') {
|
|
1159
|
+
bot.on('interaction', (async (ctx, event) => {
|
|
1160
|
+
const ev = event;
|
|
1161
|
+
// 诊断落盘(排查按钮回调是否到达; ~/.dsh/botplay-diag.log)
|
|
1162
|
+
try {
|
|
1163
|
+
const line = `[${new Date().toISOString()}] interaction id=${ev?.id ?? '?'} type=${ev?.data?.type ?? '?'} btn=${ev?.data?.resolved?.button_data ?? '(none)'} group_member=${event.group_member_openid ?? ''} user=${event.user_openid ?? ''}`;
|
|
1164
|
+
diagWrite('botplay-diag', line);
|
|
1165
|
+
}
|
|
1166
|
+
catch { /* 诊断失败忽略 */ }
|
|
1167
|
+
if (ev?.data?.type !== 11)
|
|
1168
|
+
return; // 只处理消息按钮回调
|
|
1169
|
+
const target = replyTargetOfInteraction(ev, ctx, manager);
|
|
1170
|
+
let consumed = false;
|
|
1171
|
+
try {
|
|
1172
|
+
if (presetSwitcher) {
|
|
1173
|
+
const scope = target.scope === 'group' ? 'group' : 'c2c';
|
|
1174
|
+
consumed = await presetSwitcher.handleInteraction(ev, target, scope, target.targetId);
|
|
1175
|
+
}
|
|
1176
|
+
if (!consumed && approvalController)
|
|
1177
|
+
consumed = await approvalController.handleInteraction(ev, target);
|
|
1178
|
+
if (!consumed && questionController)
|
|
1179
|
+
consumed = await questionController.handleInteraction(ev, target);
|
|
1180
|
+
if (!consumed && botplayController)
|
|
1181
|
+
consumed = await botplayController.handleInteraction(ev, target);
|
|
1182
|
+
// 扩展工具按钮(2026-10-08): data=ext:<工具名>:<卡id>:<按钮id> → 派发给该工具的 onInteraction
|
|
1183
|
+
if (!consumed && extToolInteractionController)
|
|
1184
|
+
consumed = await extToolInteractionController.handleInteraction(ev, target);
|
|
1185
|
+
// 自定义卡片(📝 卡片编辑器发的裸卡, data=bpk:<cardId>:<btnId>)兜底:
|
|
1186
|
+
// 查 {dataRoot}/.qqbot/card-callbacks.json → 回文本 / 执行命令 / 跳转提示
|
|
1187
|
+
if (!consumed && cardCallbackController)
|
|
1188
|
+
consumed = await cardCallbackController.handleInteraction(ev, target);
|
|
1189
|
+
}
|
|
1190
|
+
catch (err) {
|
|
1191
|
+
logger.warn(`[qq-interaction] 处理异常: ${err instanceof Error ? err.message : String(err)}`);
|
|
1192
|
+
}
|
|
1193
|
+
// 回应 loading(无论是否消费都要 ack; 防客户端一直转圈)
|
|
1194
|
+
try {
|
|
1195
|
+
await bot.acknowledgeInteraction(ev.id ?? '');
|
|
1196
|
+
}
|
|
1197
|
+
catch { /* ack 失败不致命 */ }
|
|
1198
|
+
}));
|
|
1199
|
+
logger.info('[im-qqbot] interaction(按钮回调)分发就绪');
|
|
1200
|
+
}
|
|
1201
|
+
const outboundHandler = createOutboundHandler(manager, sender, config, logger, toolsRegistry);
|
|
1202
|
+
ctx
|
|
1203
|
+
.on('session/event', outboundHandler);
|
|
1204
|
+
// ── 出站流式:agent/assistant-stream(瞬态帧,不落 session log) ──
|
|
1205
|
+
// 2026-10-20 对齐上游 c8b9158:老的 durable `assistant/chunk` 宿主早就不发了,
|
|
1206
|
+
// 只监听它 = 流式永远收不到帧。该事件按 agent 作用域派发,根作用域必须 { global: true }。
|
|
1207
|
+
ctx.on('agent/assistant-stream', (payload) => {
|
|
1208
|
+
const parsed = parseStreamFrame(payload);
|
|
1209
|
+
if (parsed !== undefined)
|
|
1210
|
+
outboundHandler.routeStreamFrame(parsed.agentId, parsed.delta);
|
|
1211
|
+
}, { global: true });
|
|
1212
|
+
bot.on('error', (err) => {
|
|
1213
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1214
|
+
const kind = connectionErrorKind(msg);
|
|
1215
|
+
logger.error(`bot error: ${msg}`);
|
|
1216
|
+
setBotOnline(myNs, false);
|
|
1217
|
+
writeBotStatus(dataRootOf(config), false, kind === 'whitelist' ? 'ip-whitelist' : 'bot-error', msg);
|
|
1218
|
+
qqStartupLog(dataRootOf(config), `BOT ERROR kind=${kind} msg=${msg}`);
|
|
1219
|
+
// 「源IP不在白名单」可以运行期自愈:IP 换了就自动改白名单再重连,
|
|
1220
|
+
// 否则 SDK 会每 60 秒撞一次同样的错、永远连不上(2026-12-01 主人实测一整晚都这样)。
|
|
1221
|
+
if (kind === 'whitelist') void selfHeal('whitelist');
|
|
1222
|
+
});
|
|
1223
|
+
bot.on('resumed', () => {
|
|
1224
|
+
retryStep = 0;
|
|
1225
|
+
setBotOnline(myNs, true);
|
|
1226
|
+
writeBotStatus(dataRootOf(config), true, 'resumed');
|
|
1227
|
+
qqStartupLog(dataRootOf(config), 'RESUMED(连接恢复)');
|
|
1228
|
+
});
|
|
1229
|
+
bot.on('ready', () => {
|
|
1230
|
+
retryStep = 0;
|
|
1231
|
+
setBotOnline(myNs, true);
|
|
1232
|
+
writeBotStatus(dataRootOf(config), true, 'ready');
|
|
1233
|
+
qqStartupLog(dataRootOf(config), `READY appId=${config.appId}`);
|
|
1234
|
+
console.log(`[im-qqbot] Bot ready! appId=${config.appId}`);
|
|
1235
|
+
});
|
|
1236
|
+
// ── 生命周期 ──
|
|
1237
|
+
let stopScheduler;
|
|
1238
|
+
let stopJoinPoll;
|
|
1239
|
+
// 会话自设定时任务(schedule-store 系, schedule_timer 工具创建)
|
|
1240
|
+
let scheduleTicker;
|
|
1241
|
+
const scheduleInFlight = new Set();
|
|
1242
|
+
const scheduleMissed = new Map();
|
|
1243
|
+
// ── 连接自愈状态(说明见文件头部 conn-recover 2026-12-01)──
|
|
1244
|
+
const connDataRoot = dataRootOf(config);
|
|
1245
|
+
let botStopped = false;
|
|
1246
|
+
let botStarting = false;
|
|
1247
|
+
let retryTimer;
|
|
1248
|
+
let retryStep = 0;
|
|
1249
|
+
let healBusy = false;
|
|
1250
|
+
let ipWatchTimer;
|
|
1251
|
+
let requestTimer;
|
|
1252
|
+
const RETRY_DELAYS = [5000, 15000, 60000, 180000, 300000];
|
|
1253
|
+
const scheduleRetry = (delayMs, why) => {
|
|
1254
|
+
if (botStopped)
|
|
1255
|
+
return;
|
|
1256
|
+
clearTimeout(retryTimer);
|
|
1257
|
+
retryTimer = setTimeout(() => { void startBotWithRecovery('retry(' + why + ')'); }, delayMs);
|
|
1258
|
+
if (retryTimer.unref)
|
|
1259
|
+
retryTimer.unref();
|
|
1260
|
+
qqStartupLog(connDataRoot, `计划 ${Math.round(delayMs / 1000)}s 后重连(${why})`);
|
|
1261
|
+
};
|
|
1262
|
+
const startBotWithRecovery = async (why) => {
|
|
1263
|
+
if (botStopped || botStarting)
|
|
1264
|
+
return;
|
|
1265
|
+
botStarting = true;
|
|
1266
|
+
qqStartupLog(connDataRoot, `START (${why}) appId=${config.appId}`);
|
|
1267
|
+
try {
|
|
1268
|
+
await bot.start();
|
|
1269
|
+
botStarting = false;
|
|
1270
|
+
}
|
|
1271
|
+
catch (err) {
|
|
1272
|
+
botStarting = false;
|
|
1273
|
+
if (botStopped)
|
|
1274
|
+
return;
|
|
1275
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1276
|
+
const kind = connectionErrorKind(msg);
|
|
1277
|
+
const statusWhy = kind === 'whitelist' ? 'ip-whitelist' : kind === 'credential' ? 'credential-invalid' : 'start-failed';
|
|
1278
|
+
logger.error(`Bot start failed(${kind}): ${msg}`);
|
|
1279
|
+
qqStartupLog(connDataRoot, `START FAILED kind=${kind} msg=${msg}\n${err instanceof Error && err.stack ? err.stack : ''}`);
|
|
1280
|
+
writeBotStatus(connDataRoot, false, statusWhy, msg);
|
|
1281
|
+
setBotOnline(myNs, false);
|
|
1282
|
+
if (kind === 'whitelist')
|
|
1283
|
+
void selfHeal('whitelist');
|
|
1284
|
+
if (kind === 'credential') {
|
|
1285
|
+
// 凭据错着重试再快也没用;但面板里可能刚被改好 —— 5 分钟再看一眼
|
|
1286
|
+
scheduleRetry(300000, 'credential');
|
|
1287
|
+
return;
|
|
1288
|
+
}
|
|
1289
|
+
const delay = RETRY_DELAYS[Math.min(retryStep, RETRY_DELAYS.length - 1)];
|
|
1290
|
+
retryStep += 1;
|
|
1291
|
+
scheduleRetry(delay, kind);
|
|
1292
|
+
}
|
|
1293
|
+
};
|
|
1294
|
+
const forceReconnect = async (why) => {
|
|
1295
|
+
if (botStopped)
|
|
1296
|
+
return;
|
|
1297
|
+
try {
|
|
1298
|
+
bot.stop();
|
|
1299
|
+
}
|
|
1300
|
+
catch { /* ignore */ }
|
|
1301
|
+
// 等 SDK 释放连接再起(stop 是同步释放,但旧 start() 的 promise 结算需要一拍)
|
|
1302
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
1303
|
+
if (botStopped || botStarting)
|
|
1304
|
+
return;
|
|
1305
|
+
await startBotWithRecovery(why);
|
|
1306
|
+
};
|
|
1307
|
+
const selfHeal = async (kind) => {
|
|
1308
|
+
if (botStopped || healBusy)
|
|
1309
|
+
return;
|
|
1310
|
+
healBusy = true;
|
|
1311
|
+
try {
|
|
1312
|
+
if (kind === 'whitelist') {
|
|
1313
|
+
// 2026-12-03:旧 qq-whitelist.py 走的是已下线的 /qqbot/dashboard/(302 回首页,
|
|
1314
|
+
// 永远 rc=20)。换成 qq-ip-sync.py:先探 gateway,通了就什么都不做;
|
|
1315
|
+
// 不通才开控制台(新地址 manage/<appId>?sec=dev-settings)加 IP,再复核。
|
|
1316
|
+
qqStartupLog(connDataRoot, '检测到 IP 白名单问题 -> 运行 scripts/qq-ip-sync.py --sync');
|
|
1317
|
+
const r = await runPyScript('qq-ip-sync.py', ['--sync'], 420000);
|
|
1318
|
+
qqStartupLog(connDataRoot, `白名单自愈 rc=${r.code} ${String(r.out || '').replace(/\s+/g, ' ').slice(-400)}`);
|
|
1319
|
+
if (r.code === 0) {
|
|
1320
|
+
retryStep = 0;
|
|
1321
|
+
await forceReconnect('whitelist-fixed');
|
|
1322
|
+
}
|
|
1323
|
+
else if (r.code === 3) {
|
|
1324
|
+
// 控制台要登录(一次即可);别每 5 分钟刷一次浏览器
|
|
1325
|
+
scheduleRetry(900000, 'whitelist-need-manual');
|
|
1326
|
+
}
|
|
1327
|
+
else {
|
|
1328
|
+
scheduleRetry(300000, 'whitelist-sync-failed');
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
finally {
|
|
1333
|
+
healBusy = false;
|
|
1334
|
+
}
|
|
1335
|
+
};
|
|
1336
|
+
/** 每 30 分钟比对「当前出口 IP」和「已确认写进白名单的 IP」,变了就先修再连 */
|
|
1337
|
+
const checkIpDrift = async () => {
|
|
1338
|
+
if (botStopped || healBusy)
|
|
1339
|
+
return;
|
|
1340
|
+
const r = await runPyScript('qq-ip-sync.py', ['--print-ip'], 30000);
|
|
1341
|
+
const ip = String(r.out || '').split(/\r?\n/).map((x) => x.trim()).filter((x) => /^\d+\.\d+\.\d+\.\d+$/.test(x)).pop() || '';
|
|
1342
|
+
if (!ip) {
|
|
1343
|
+
qqStartupLog(connDataRoot, `出口 IP 探测失败 rc=${r.code} ${String(r.out || '').slice(0, 120)}`);
|
|
1344
|
+
return;
|
|
1345
|
+
}
|
|
1346
|
+
let applied = '';
|
|
1347
|
+
try {
|
|
1348
|
+
applied = qqReadFileSync(join(QQBOT_SCRIPTS_ROOT, 'data', 'net', 'whitelist-applied.txt'), 'utf8').trim();
|
|
1349
|
+
}
|
|
1350
|
+
catch { applied = ''; }
|
|
1351
|
+
if (applied && applied !== ip) {
|
|
1352
|
+
qqStartupLog(connDataRoot, `出口 IP 变化 ${applied} -> ${ip},自动更新白名单`);
|
|
1353
|
+
await selfHeal('whitelist');
|
|
1354
|
+
}
|
|
1355
|
+
};
|
|
1356
|
+
// 启动即自检(2026-12-03):宽带重播后出口 IP 会变,先静默跑一次白名单自愈,
|
|
1357
|
+
// 免得第一条消息就撞「源IP不在白名单」再退避重试。通了就是两次 HTTP,几乎无感。
|
|
1358
|
+
void (async () => {
|
|
1359
|
+
try {
|
|
1360
|
+
const r = await runPyScript('qq-ip-sync.py', ['--sync'], 420000);
|
|
1361
|
+
if (r.code !== 0)
|
|
1362
|
+
qqStartupLog(connDataRoot, `启动自检:白名单自愈 rc=${r.code} ${String(r.out || '').replace(/\s+/g, ' ').slice(-300)}`);
|
|
1363
|
+
}
|
|
1364
|
+
catch { /* 自检失败不影响正常启动流程 */ }
|
|
1365
|
+
})();
|
|
1366
|
+
const _qqHostLock = qqbotHostLock(dataRootOf(config), logger);
|
|
1367
|
+
if (_qqHostLock && _qqHostLock.ok === false) {
|
|
1368
|
+
logger.error(`[im-qqbot] 双实例保护:另一个 DSH 实例(pid=${(_qqHostLock.holder && _qqHostLock.holder.pid) ?? "?"}) 正在运行同一个机器人 -> 本实例暂不连接 QQ,等它让出锁后自动接管。`);
|
|
1369
|
+
}
|
|
1370
|
+
ctx
|
|
1371
|
+
.effect(() => {
|
|
1372
|
+
logger.info(`Starting bot (appId=${config.appId})`);
|
|
1373
|
+
if (_qqHostLock && _qqHostLock.ok === false) {
|
|
1374
|
+
// 锁被别人活着持有:不连接 QQ(否则同一条消息会被两个宿主各答一次)。
|
|
1375
|
+
// 每 20 秒重试一次抢锁;对方心跳停了(死掉/关窗口)就自动接管。
|
|
1376
|
+
const _qqRetry = setInterval(() => {
|
|
1377
|
+
const again = qqbotHostLock(dataRootOf(config), logger);
|
|
1378
|
+
if (!again || again.ok !== true)
|
|
1379
|
+
return;
|
|
1380
|
+
clearInterval(_qqRetry);
|
|
1381
|
+
logger.warn(`[im-qqbot] 双实例保护:锁已释放 -> 本实例现在接管并连接 QQ`);
|
|
1382
|
+
void startBotWithRecovery('host-lock-released');
|
|
1383
|
+
}, 20000);
|
|
1384
|
+
if (_qqRetry.unref)
|
|
1385
|
+
_qqRetry.unref();
|
|
1386
|
+
logger.warn(`[im-qqbot] 已暂缓 bot.start()(双实例保护,20 秒后重试抢锁)`);
|
|
1387
|
+
return () => clearInterval(_qqRetry);
|
|
1388
|
+
}
|
|
1389
|
+
void startBotWithRecovery('boot');
|
|
1390
|
+
// 面板「立即重连 / 修白名单后重连」:settings-host 只写一个请求文件,这里消费
|
|
1391
|
+
requestTimer = setInterval(() => {
|
|
1392
|
+
const f = join(connDataRoot, '.qqbot', 'reconnect-request.json');
|
|
1393
|
+
try {
|
|
1394
|
+
if (!qqExistsSync(f))
|
|
1395
|
+
return;
|
|
1396
|
+
qqUnlinkSync(f);
|
|
1397
|
+
}
|
|
1398
|
+
catch { return; }
|
|
1399
|
+
qqStartupLog(connDataRoot, '收到面板「立即重连」请求');
|
|
1400
|
+
retryStep = 0;
|
|
1401
|
+
void forceReconnect('panel-request');
|
|
1402
|
+
}, 5000);
|
|
1403
|
+
if (requestTimer.unref)
|
|
1404
|
+
requestTimer.unref();
|
|
1405
|
+
// 校园网出口 IP 会漂 —— 30 分钟核一次,别等断了 60 秒一轮才发现
|
|
1406
|
+
ipWatchTimer = setInterval(() => { void checkIpDrift(); }, 30 * 60 * 1000);
|
|
1407
|
+
if (ipWatchTimer.unref)
|
|
1408
|
+
ipWatchTimer.unref();
|
|
1409
|
+
// M3 定时唤醒调度器(与 bot 同生命周期; 任务到点 followup → 回复经出站链路主动推送)
|
|
1410
|
+
stopScheduler = startScheduler(manager, config, logger);
|
|
1411
|
+
void (async () => {
|
|
1412
|
+
// 2026-11-15:单实例守护。DSH 每次重启都会换 cookie 和 GUI 端口,旧进程没退干净时
|
|
1413
|
+
// 会有两套 DSH 同时加载 qqbot、各自往 QQ/微信发消息 → 同一条回复发两遍。
|
|
1414
|
+
// 启动后立刻清掉「比我早启动」的实例,并抢固定协调端口、把 cookie 记进锁文件。
|
|
1415
|
+
try {
|
|
1416
|
+
const guardUrl = new URL('file:///' + join(QQBOT_ROOT, 'scripts', 'dsh-instance-guard.mjs').replace(/\\/g, '/'));
|
|
1417
|
+
const guard = await import(guardUrl.href);
|
|
1418
|
+
const r = await guard.ensureSingleInstance({ keepServer: true });
|
|
1419
|
+
if (r?.killed?.length) logger.warn(`[instance] 已结束 ${r.killed.length} 个残留 DSH 实例:${r.killed.join(',')}`);
|
|
1420
|
+
logger.info(`[instance] 单实例守护就绪 cookie=${String(r?.cookie ?? '').slice(0, 8)}… port=${r?.port} guiPort=${r?.guiPort || '?'}`);
|
|
1421
|
+
} catch (e) {
|
|
1422
|
+
logger.warn(`[instance] 单实例守护失败(忽略):${e instanceof Error ? e.message : String(e)}`);
|
|
1423
|
+
}
|
|
1424
|
+
})();
|
|
1425
|
+
// 2026-11-18(v0.1.7):profile 依赖自检 —— 老用户升级后如果 profile 里还是
|
|
1426
|
+
// "file:<仓库根>" 这种绝对盘符写法,pnpm 会把它当相对路径拼到 profile 目录下、
|
|
1427
|
+
// 直接 ENOENT → dshmarket 基线立不起来 → 整机进安全模式(2026-11-13 事故一)。
|
|
1428
|
+
// 这里只在运行期【检测 + 记日志 + 落标记】,不擅自改 profile(改配置会让市场重装,
|
|
1429
|
+
// 正在跑的实例更危险);真正的修复交给 scripts/dsh-profile-links.mjs。
|
|
1430
|
+
void (async () => {
|
|
1431
|
+
try {
|
|
1432
|
+
const { readFileSync: _rf, writeFileSync: _wf, existsSync: _ex } = await import('node:fs');
|
|
1433
|
+
const { join: _join } = await import('node:path');
|
|
1434
|
+
const home = process.env.APPDATA || '';
|
|
1435
|
+
if (!home) return;
|
|
1436
|
+
// 2026-12-01:0.14 起活动 profile 可能是 desktop(web 仍在),这里扫全部 profile
|
|
1437
|
+
const fsMod = await import('node:fs');
|
|
1438
|
+
const base = _join(home, 'dsh-desktop', 'harness', 'profiles');
|
|
1439
|
+
if (!_ex(base)) return;
|
|
1440
|
+
let names = [];
|
|
1441
|
+
try { names = fsMod.readdirSync(base).filter((n) => !n.startsWith('.')); } catch { return; }
|
|
1442
|
+
let bad = [];
|
|
1443
|
+
let firstProf = '';
|
|
1444
|
+
for (const name of names) {
|
|
1445
|
+
const prof = _join(base, name, 'package.json');
|
|
1446
|
+
if (!_ex(prof)) continue;
|
|
1447
|
+
let man;
|
|
1448
|
+
try { man = JSON.parse(_rf(prof, 'utf8')); } catch { continue; }
|
|
1449
|
+
const deps = { ...(man.dependencies || {}), ...(man.devDependencies || {}) };
|
|
1450
|
+
const rows = Object.entries(deps).filter(([, v]) => typeof v === 'string' && /^file:[A-Za-z]:[\/]/.test(v));
|
|
1451
|
+
if (rows.length) { bad = bad.concat(rows); if (!firstProf) firstProf = prof; }
|
|
1452
|
+
}
|
|
1453
|
+
if (!bad.length) return;
|
|
1454
|
+
logger.warn(`[profile] 检测到 ${bad.length} 个绝对盘符 file: 依赖(升级后可能进安全模式):${bad.map(([k]) => k).join(',')}`);
|
|
1455
|
+
logger.warn('[profile] 修复:node scripts/dsh-profile-links.mjs(详见 docs/运维-DSH安全模式与profile依赖.md)');
|
|
1456
|
+
try {
|
|
1457
|
+
const dir = _join(dataRootOf(config), '.qqbot');
|
|
1458
|
+
const mark = _join(dir, 'profile-fix-needed.json');
|
|
1459
|
+
_wf(mark, JSON.stringify({ at: Date.now(), profile: firstProf, bad: bad.map(([k, v]) => ({ name: k, spec: v })) }, null, 2));
|
|
1460
|
+
} catch { }
|
|
1461
|
+
} catch (e) {
|
|
1462
|
+
logger.warn(`[profile] 依赖自检失败(忽略):${e instanceof Error ? e.message : String(e)}`);
|
|
1463
|
+
}
|
|
1464
|
+
})();
|
|
1465
|
+
// 积压消息补回(2026-11-13): 重启/掉线期间没人回的消息,合成一条注入会话让 agent 自己接话。
|
|
1466
|
+
// 只处理 QQ 的 c2c:/group: scope;微信/小天才由各自插件负责。全流程 fail-soft。
|
|
1467
|
+
// 2026-11-14 改:不只启动时补一次 —— 每 10 分钟巡检一次,中途积压/上次注入失败也能补上。
|
|
1468
|
+
let _catchupBusy = false;
|
|
1469
|
+
const runQqCatchup = async () => {
|
|
1470
|
+
if (_catchupBusy) return;
|
|
1471
|
+
_catchupBusy = true;
|
|
1472
|
+
try {
|
|
1473
|
+
const { catchupUnrepliedMessages } = await import('../features/catchup.js');
|
|
1474
|
+
await catchupUnrepliedMessages({
|
|
1475
|
+
dataRoot: dataRootOf(config),
|
|
1476
|
+
manager,
|
|
1477
|
+
logger,
|
|
1478
|
+
maxAgeMs: Number(config?.catchup?.maxAgeHours || 24) * 3600_000,
|
|
1479
|
+
});
|
|
1480
|
+
} catch (e) {
|
|
1481
|
+
logger.warn(`[catchup] 积压补回失败(忽略): ${e instanceof Error ? e.message : String(e)}`);
|
|
1482
|
+
} finally {
|
|
1483
|
+
_catchupBusy = false;
|
|
1484
|
+
}
|
|
1485
|
+
};
|
|
1486
|
+
// 重启后尽快补一次(10s 内),之后每 2 分钟巡检:积压必须自己冒出来,不能等人催。
|
|
1487
|
+
setTimeout(() => { void runQqCatchup(); }, 10_000);
|
|
1488
|
+
setInterval(() => { void runQqCatchup(); }, 2 * 60_000);
|
|
1489
|
+
// 入群申请轮询(2026-09-09 主人定, 事件驱动兜底): 定时拉各群审批列表,
|
|
1490
|
+
// 有新增就唤醒 LLM 提醒主人; live config 控制(Web 设置热更, 无需重启)。
|
|
1491
|
+
stopJoinPoll = startJoinRequestPolling(manager, config, logger);
|
|
1492
|
+
// 会话自设定时任务 ticker(30s): due → injectToPeer 注入原会话 → 成功 markDone;
|
|
1493
|
+
// 失败(会话不在)连续≥3次自动停用; once 到期滞留 >24h 清理防堆积。
|
|
1494
|
+
const tickSchedule = () => {
|
|
1495
|
+
try {
|
|
1496
|
+
const store = getScheduleStore(scheduleDataDir);
|
|
1497
|
+
const now = Date.now();
|
|
1498
|
+
for (const job of store.list()) {
|
|
1499
|
+
if (job.kind === 'once' && job.dueAt !== undefined && now - job.dueAt > 24 * 3600_000) {
|
|
1500
|
+
store.remove(job.id);
|
|
1501
|
+
scheduleInFlight.delete(job.id);
|
|
1502
|
+
scheduleMissed.delete(job.id);
|
|
1503
|
+
logger.warn(`[schedule] 一次性任务过期清理 id=${job.id}`);
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
for (const job of store.due(now)) {
|
|
1507
|
+
if (scheduleInFlight.has(job.id))
|
|
1508
|
+
continue;
|
|
1509
|
+
scheduleInFlight.add(job.id);
|
|
1510
|
+
void (async () => {
|
|
1511
|
+
try {
|
|
1512
|
+
// 窗口/天气任务:到点先判断该不该开口(不合适就顺延,不打扰)
|
|
1513
|
+
const { passesGuard } = await import('../features/schedule-guard.js');
|
|
1514
|
+
if (!(await passesGuard(job, { logger }))) {
|
|
1515
|
+
store.markDone(job.id);
|
|
1516
|
+
logger.info(`[schedule] guard 判定不开口 job=${job.id}(已顺延下一个点)`);
|
|
1517
|
+
return;
|
|
1518
|
+
}
|
|
1519
|
+
// 窗口任务按权重摇一次:不是每个点都非说不可,说多了自然淡(weight 由入站回涨)
|
|
1520
|
+
if (job.kind === 'window' && !rollFire(job)) {
|
|
1521
|
+
store.markDone(job.id);
|
|
1522
|
+
logger.info(`[schedule] 窗口任务这次不说 job=${job.id} weight=${Number(job.weight).toFixed(2)}(已顺延)`);
|
|
1523
|
+
return;
|
|
1524
|
+
}
|
|
1525
|
+
// 2026-11-14:注入失败不再 3 次就静默停用(人看到的是「任务没发就没了」)。
|
|
1526
|
+
// 先补一次会话(重启后会话表可能是空的),再重试;给 4 分钟窗口,
|
|
1527
|
+
// 真失败也把原因写在 job 上,面板显示 + 可点「重试」。
|
|
1528
|
+
let ok = await manager.injectToPeer(job.scope, job.peerId, `[定时任务] ${job.prompt}`, 'subagent-settled');
|
|
1529
|
+
if (!ok) {
|
|
1530
|
+
try {
|
|
1531
|
+
manager.getOrCreate?.(job.scope, job.peerId, 'schedule', { scope: job.scope, targetId: job.peerId });
|
|
1532
|
+
ok = await manager.injectToPeer(job.scope, job.peerId, `[定时任务] ${job.prompt}`, 'subagent-settled');
|
|
1533
|
+
}
|
|
1534
|
+
catch { /* 建会话失败按失败处理 */ }
|
|
1535
|
+
}
|
|
1536
|
+
if (ok) {
|
|
1537
|
+
scheduleMissed.delete(job.id);
|
|
1538
|
+
store.reportFire(job.id);
|
|
1539
|
+
store.markDone(job.id);
|
|
1540
|
+
logger.info(`[schedule] 触发 ok job=${job.id} kind=${job.kind} → ${job.scope}:${job.peerId}`);
|
|
1541
|
+
}
|
|
1542
|
+
else {
|
|
1543
|
+
const n = (scheduleMissed.get(job.id) ?? 0) + 1;
|
|
1544
|
+
store.reportFail(job.id, `会话不在/注入失败(第 ${n} 次)`);
|
|
1545
|
+
if (n >= 8) {
|
|
1546
|
+
scheduleMissed.delete(job.id);
|
|
1547
|
+
store.setEnabled(job.id, false);
|
|
1548
|
+
store.reportFail(job.id, '连续 8 次投递失败,已暂停;可点「重试」补发');
|
|
1549
|
+
logger.warn(`[schedule] job=${job.id} 连续${n}次会话不在/注入失败, 已自动停用(可在设置点重试)`);
|
|
1550
|
+
}
|
|
1551
|
+
else {
|
|
1552
|
+
scheduleMissed.set(job.id, n);
|
|
1553
|
+
logger.warn(`[schedule] job=${job.id} 会话不在/注入失败 第${n}次, 下轮重试`);
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
catch (err) {
|
|
1558
|
+
logger.warn?.(`[schedule] 触发异常 job=${job.id}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1559
|
+
}
|
|
1560
|
+
finally {
|
|
1561
|
+
scheduleInFlight.delete(job.id);
|
|
1562
|
+
}
|
|
1563
|
+
})();
|
|
1564
|
+
}
|
|
1565
|
+
// 事件型任务 + 权重激活(2026-11-13):不看点到没到,看聊天里有没有那件事。
|
|
1566
|
+
// 说了就进冷却、权重往下淡;对方真回话(同 scope 有入站)权重往上回涨。
|
|
1567
|
+
try {
|
|
1568
|
+
bumpActivation(store, { dataRoot: dataRootOf(config), now });
|
|
1569
|
+
for (const { job, hits, samples } of matchEventJobs(store, { dataRoot: dataRootOf(config), now })) {
|
|
1570
|
+
if (scheduleInFlight.has(job.id))
|
|
1571
|
+
continue;
|
|
1572
|
+
if (!rollFire(job)) {
|
|
1573
|
+
store.markDone(job.id);
|
|
1574
|
+
logger.info(`[schedule] 事件任务这次不说 job=${job.id} weight=${Number(job.weight).toFixed(2)}(进冷却)`);
|
|
1575
|
+
continue;
|
|
1576
|
+
}
|
|
1577
|
+
scheduleInFlight.add(job.id);
|
|
1578
|
+
void (async () => {
|
|
1579
|
+
try {
|
|
1580
|
+
const hint = `刚才聊天里出现了「${hits.join('/')}」:${samples.join(' / ')}`;
|
|
1581
|
+
let ok = await manager.injectToPeer(job.scope, job.peerId, `[事件任务] ${hint}。${job.prompt}`, 'subagent-settled');
|
|
1582
|
+
if (!ok) {
|
|
1583
|
+
try {
|
|
1584
|
+
manager.getOrCreate?.(job.scope, job.peerId, 'schedule', { scope: job.scope, targetId: job.peerId });
|
|
1585
|
+
ok = await manager.injectToPeer(job.scope, job.peerId, `[事件任务] ${hint}。${job.prompt}`, 'subagent-settled');
|
|
1586
|
+
}
|
|
1587
|
+
catch { /* 建会话失败按失败处理 */ }
|
|
1588
|
+
}
|
|
1589
|
+
if (ok) {
|
|
1590
|
+
scheduleMissed.delete(job.id);
|
|
1591
|
+
store.reportFire(job.id);
|
|
1592
|
+
store.markDone(job.id);
|
|
1593
|
+
logger.info(`[schedule] 事件触发 ok job=${job.id} hits=${hits.join(',')} → ${job.scope}:${job.peerId}`);
|
|
1594
|
+
}
|
|
1595
|
+
else {
|
|
1596
|
+
const n = (scheduleMissed.get(job.id) ?? 0) + 1;
|
|
1597
|
+
store.reportFail(job.id, `事件注入失败(第 ${n} 次)`);
|
|
1598
|
+
if (n >= 8) {
|
|
1599
|
+
scheduleMissed.delete(job.id);
|
|
1600
|
+
store.setEnabled(job.id, false);
|
|
1601
|
+
store.reportFail(job.id, '连续 8 次注入失败,已暂停;可点「重试」补发');
|
|
1602
|
+
logger.warn(`[schedule] 事件任务 job=${job.id} 连续${n}次注入失败, 已自动停用`);
|
|
1603
|
+
}
|
|
1604
|
+
else {
|
|
1605
|
+
scheduleMissed.set(job.id, n);
|
|
1606
|
+
logger.warn(`[schedule] 事件任务 job=${job.id} 注入失败 第${n}次, 下轮重试`);
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
catch (err) {
|
|
1611
|
+
logger.warn?.(`[schedule] 事件任务触发异常 job=${job.id}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1612
|
+
}
|
|
1613
|
+
finally {
|
|
1614
|
+
scheduleInFlight.delete(job.id);
|
|
1615
|
+
}
|
|
1616
|
+
})();
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
catch (err) {
|
|
1620
|
+
logger.warn?.(`[schedule] 事件任务评估异常: ${err instanceof Error ? err.message : String(err)}`);
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
catch (err) {
|
|
1624
|
+
logger.warn?.(`[schedule] tick 异常: ${err instanceof Error ? err.message : String(err)}`);
|
|
1625
|
+
}
|
|
1626
|
+
};
|
|
1627
|
+
// 会话自设定时 ticker: 5s 粒度(原 30s → 一次性任务延迟上限 30s 太大, 主人实测 11:35 任务 11:36 才发;
|
|
1628
|
+
// 任务量小 store 内存读, 5s 开销可忽略) → 延迟压到 ≤5s。
|
|
1629
|
+
scheduleTicker = setInterval(tickSchedule, 5_000);
|
|
1630
|
+
scheduleTicker.unref?.();
|
|
1631
|
+
logger.info(`[schedule] ticker 启动 (30s, dataDir=${scheduleDataDir})`);
|
|
1632
|
+
// botplay 过期卡定期清理(Phase2): 60s 扫一次, 防内存积压(卡默认最长 600s 存活)
|
|
1633
|
+
const botplaySweeper = setInterval(() => {
|
|
1634
|
+
try {
|
|
1635
|
+
botplayController?.sweepExpired();
|
|
1636
|
+
}
|
|
1637
|
+
catch { /* ignore */ }
|
|
1638
|
+
}, 60_000);
|
|
1639
|
+
botplaySweeper.unref?.();
|
|
1640
|
+
// 2026-10-12:拆成**幂等的 dispose**。它现在有两条调用路径:
|
|
1641
|
+
// ① cordis 作用域销毁(把返回值交给 'im-qqbot.lifecycle')
|
|
1642
|
+
// ② 保存了「连接相关设置」后的"先拆后建"(index.ts 通过 hooks.onDisposer 拿到它)
|
|
1643
|
+
// 幂等守卫是必需的:两条路都可能触发,重复 dispose 会把 manager/bot 拆两次。
|
|
1644
|
+
let disposed = false;
|
|
1645
|
+
const dispose = async () => {
|
|
1646
|
+
if (disposed)
|
|
1647
|
+
return;
|
|
1648
|
+
disposed = true;
|
|
1649
|
+
// 先停自愈定时器,否则拆卸过程中还可能触发一次 start()
|
|
1650
|
+
botStopped = true;
|
|
1651
|
+
clearTimeout(retryTimer);
|
|
1652
|
+
clearInterval(ipWatchTimer);
|
|
1653
|
+
clearInterval(requestTimer);
|
|
1654
|
+
logger.info('Shutting down');
|
|
1655
|
+
registerApprovalController(myNs, undefined);
|
|
1656
|
+
registerQuestionController(myNs, undefined);
|
|
1657
|
+
registerBotplayController(myNs, undefined);
|
|
1658
|
+
setBotplayTriggerImpl(myNs, undefined);
|
|
1659
|
+
setBotplayCatalogImpl(myNs, undefined);
|
|
1660
|
+
registerSessionManager(myNs, undefined);
|
|
1661
|
+
approvalController?.dispose();
|
|
1662
|
+
questionController?.dispose();
|
|
1663
|
+
botplayController?.clear();
|
|
1664
|
+
stopScheduler?.();
|
|
1665
|
+
stopJoinPoll?.();
|
|
1666
|
+
if (scheduleTicker) {
|
|
1667
|
+
clearInterval(scheduleTicker);
|
|
1668
|
+
scheduleTicker = undefined;
|
|
1669
|
+
}
|
|
1670
|
+
clearInterval(botplaySweeper);
|
|
1671
|
+
flushStickerGate();
|
|
1672
|
+
// ── 启动钩子(ext-hooks):卸载 / 宿主退出 / 保存连接设置后重建网关时清理本实例登记项 ──
|
|
1673
|
+
// 钩子可能在启动时注册了监听、定时器、订阅 —— 不清理就会在重建网关时不断累积(历史上踩过这个坑)。
|
|
1674
|
+
// 引擎内部逐个 try/catch + 逆序执行,单个清理失败只告警,绝不阻断其余拆卸步骤。
|
|
1675
|
+
try {
|
|
1676
|
+
const hooks = await import('../features/ext-hooks.js');
|
|
1677
|
+
await hooks.disposeStartupHooks(logger);
|
|
1678
|
+
}
|
|
1679
|
+
catch (err) {
|
|
1680
|
+
logger.warn?.(`[ext-hook] 清理启动钩子异常(已忽略): ${err instanceof Error ? err.message : String(err)}`);
|
|
1681
|
+
}
|
|
1682
|
+
// ── 入站中间件扩展(ext-inbound,第五套扩展;2026-10-12)──────────────────────
|
|
1683
|
+
// 与启动钩子同一时机:卸载 / 宿主退出 / 保存连接设置后重建网关时,
|
|
1684
|
+
// 调各扩展可选导出的 dispose(),并把热重载入口摘掉(否则它会指向已经死掉的实例)。
|
|
1685
|
+
// 引擎内部逆序 + 逐个 try/catch,单个失败只告警,绝不阻断其余拆卸步骤。
|
|
1686
|
+
try {
|
|
1687
|
+
const inbound = await import('../features/ext-inbound.js');
|
|
1688
|
+
await inbound.disposeInboundExtensions(logger);
|
|
1689
|
+
}
|
|
1690
|
+
catch (err) {
|
|
1691
|
+
logger.warn?.(`[ext-inbound] 清理入站扩展异常(已忽略): ${err instanceof Error ? err.message : String(err)}`);
|
|
1692
|
+
}
|
|
1693
|
+
await manager.disposeAll();
|
|
1694
|
+
bot.stop();
|
|
1695
|
+
};
|
|
1696
|
+
try {
|
|
1697
|
+
hooks?.onDisposer?.(dispose);
|
|
1698
|
+
}
|
|
1699
|
+
catch (e) {
|
|
1700
|
+
logger.warn?.(`bootstrap hooks.onDisposer 失败: ${e instanceof Error ? e.message : String(e)}`);
|
|
1701
|
+
}
|
|
1702
|
+
return dispose;
|
|
1703
|
+
}, 'im-qqbot.lifecycle');
|
|
1704
|
+
}
|
|
1653
1705
|
//# sourceMappingURL=bootstrap.js.map
|