@mcviseron/dsh-qq-bridge 0.2.0 → 0.3.0
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/README.md +8 -0
- package/bot/.env.example +32 -0
- package/bot/bridge.py +339 -0
- package/bot/check_await.py +31 -0
- package/bot/main.py +4335 -0
- package/bot/panel.py +471 -0
- package/bot/probe_group.py +24 -0
- package/bot/requirements.txt +6 -0
- package/bot/run-bot.bat +23 -0
- package/bot/runtime_config.py +185 -0
- package/bot/stop-bot.bat +11 -0
- package/bot/test_bystander.py +48 -0
- package/bot/test_commands.py +149 -0
- package/bot/test_group_alias.py +149 -0
- package/bot/test_group_routing.py +241 -0
- package/bot/test_plan_b.py +153 -0
- package/bot/test_queue_drain.py +114 -0
- package/bot/test_quote.py +240 -0
- package/bot/test_stream_strict.py +84 -0
- package/bot/test_streaming.py +141 -0
- package/bot/test_turnid.py +80 -0
- package/bot/usage.mjs +175 -0
- package/lib/client.js +1004 -372
- package/lib/index.js +1304 -1120
- package/lib/install.js +324 -0
- package/lib/server.js +17 -5
- package/package.json +5 -2
package/lib/index.js
CHANGED
|
@@ -1,1120 +1,1304 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* dsh-qq-bridge — Host half.
|
|
3
|
-
*
|
|
4
|
-
* One QQ conversation (a group or a private chat) owns one DSH Session. This
|
|
5
|
-
* plugin keeps that mapping, turns every inbound QQ message into a Session
|
|
6
|
-
* prompt, captures the assistant text of each finished turn, keeps a rolling
|
|
7
|
-
* transcript of group chatter, and asks the bot owner before a tool needs
|
|
8
|
-
* approval.
|
|
9
|
-
*/
|
|
10
|
-
import { randomUUID } from 'node:crypto'
|
|
11
|
-
import { readFileSync } from 'node:fs'
|
|
12
|
-
import { appendFile, mkdir } from 'node:fs/promises'
|
|
13
|
-
import { dirname, join, resolve } from 'node:path'
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
const
|
|
104
|
-
/**
|
|
105
|
-
const
|
|
106
|
-
/**
|
|
107
|
-
const
|
|
108
|
-
/**
|
|
109
|
-
const
|
|
110
|
-
/**
|
|
111
|
-
const
|
|
112
|
-
/**
|
|
113
|
-
const
|
|
114
|
-
/**
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
})
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
const
|
|
167
|
-
if (
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
return
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
//
|
|
182
|
-
const
|
|
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
|
-
const
|
|
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
|
-
|
|
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
|
-
return { ok:
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
const
|
|
445
|
-
if (
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
await
|
|
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
|
-
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
const
|
|
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
|
-
const
|
|
538
|
-
const
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
const
|
|
560
|
-
const
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
if (
|
|
583
|
-
const
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
if (
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
const
|
|
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
|
-
return { ok: false, error:
|
|
669
|
-
}
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
try {
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
} catch (error) {
|
|
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
|
-
const
|
|
740
|
-
const
|
|
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
|
-
const
|
|
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
|
-
return
|
|
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
|
-
const
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
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
|
-
const
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
},
|
|
1095
|
-
async execute(args) {
|
|
1096
|
-
const convKey = String(args?.convKey || "")
|
|
1097
|
-
const
|
|
1098
|
-
|
|
1099
|
-
const
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1
|
+
/**
|
|
2
|
+
* dsh-qq-bridge — Host half.
|
|
3
|
+
*
|
|
4
|
+
* One QQ conversation (a group or a private chat) owns one DSH Session. This
|
|
5
|
+
* plugin keeps that mapping, turns every inbound QQ message into a Session
|
|
6
|
+
* prompt, captures the assistant text of each finished turn, keeps a rolling
|
|
7
|
+
* transcript of group chatter, and asks the bot owner before a tool needs
|
|
8
|
+
* approval.
|
|
9
|
+
*/
|
|
10
|
+
import { randomUUID } from 'node:crypto'
|
|
11
|
+
import { readFileSync } from 'node:fs'
|
|
12
|
+
import { appendFile, mkdir } from 'node:fs/promises'
|
|
13
|
+
import { dirname, join, resolve } from 'node:path'
|
|
14
|
+
import { fileURLToPath } from 'node:url'
|
|
15
|
+
import { Installer, readInstall, resolveSourceDir } from './install.js'
|
|
16
|
+
import { HttpBridge } from './server.js'
|
|
17
|
+
import { ConversationStore } from './store.js'
|
|
18
|
+
|
|
19
|
+
export const name = 'dsh-qq-bridge'
|
|
20
|
+
|
|
21
|
+
/** Fields a profile patch may override; everything else is fixed policy. */
|
|
22
|
+
export const DEFAULT_CONFIG = {
|
|
23
|
+
enabled: true,
|
|
24
|
+
host: '127.0.0.1',
|
|
25
|
+
port: 39061,
|
|
26
|
+
panelPort: 39062,
|
|
27
|
+
token: '',
|
|
28
|
+
cwd: '',
|
|
29
|
+
statePath: '',
|
|
30
|
+
approvalTimeoutMs: 150000,
|
|
31
|
+
approvalDefault: 'reject',
|
|
32
|
+
contextLines: 30,
|
|
33
|
+
argumentPreviewChars: 600,
|
|
34
|
+
quoteContextChars: 300,
|
|
35
|
+
historyMax: 200,
|
|
36
|
+
autoGroup: true,
|
|
37
|
+
autoGroupRoot: 'D:\\dsh-qqbot-temp',
|
|
38
|
+
streamEnabled: true,
|
|
39
|
+
streamIntervalMs: 250,
|
|
40
|
+
autoStartBot: true,
|
|
41
|
+
botDir: 'D:/Program/QQ-Bot-Class/dsh-bot/bot',
|
|
42
|
+
pythonPath: 'C:/Users/25639/.conda/envs/ChatClone-BotPy/python.exe',
|
|
43
|
+
modelProvider: '',
|
|
44
|
+
model: '',
|
|
45
|
+
reasoningEffort: '',
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
|
|
49
|
+
|
|
50
|
+
/** Profile config → absolute, defaulted runtime configuration. */
|
|
51
|
+
function resolveConfig(raw) {
|
|
52
|
+
const config = { ...DEFAULT_CONFIG, ...(raw ?? {}) }
|
|
53
|
+
const home = typeof process.env.DSH_HOME === 'string' && process.env.DSH_HOME !== ''
|
|
54
|
+
? process.env.DSH_HOME
|
|
55
|
+
: join(process.cwd(), '.dsh')
|
|
56
|
+
const dataDir = join(home, 'qq-bridge')
|
|
57
|
+
return {
|
|
58
|
+
...config,
|
|
59
|
+
port: Number(config.port ?? DEFAULT_CONFIG.port),
|
|
60
|
+
approvalTimeoutMs: Number(config.approvalTimeoutMs ?? DEFAULT_CONFIG.approvalTimeoutMs),
|
|
61
|
+
contextLines: Number(config.contextLines ?? DEFAULT_CONFIG.contextLines),
|
|
62
|
+
dataDir,
|
|
63
|
+
cwd: resolve(config.cwd !== '' ? config.cwd : join(dataDir, 'workspace')),
|
|
64
|
+
statePath: config.statePath !== '' ? resolve(config.statePath) : join(dataDir, 'state.json'),
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Text parts of one assistant message, ignoring reasoning and tool calls. */
|
|
69
|
+
function textOf(message) {
|
|
70
|
+
const content = message?.content
|
|
71
|
+
if (typeof content === 'string') return content
|
|
72
|
+
if (!Array.isArray(content)) return ''
|
|
73
|
+
const parts = []
|
|
74
|
+
for (const part of content) {
|
|
75
|
+
if (part === null || typeof part !== 'object') continue
|
|
76
|
+
if (part.type === 'text' && typeof part.text === 'string') parts.push(part.text)
|
|
77
|
+
}
|
|
78
|
+
return parts.join('')
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** One-line, length-bounded preview of a text or JSON blob. */
|
|
82
|
+
function preview(value, limit) {
|
|
83
|
+
const text = typeof value === 'string' ? value : JSON.stringify(value ?? '')
|
|
84
|
+
const flat = text.replace(/\s+/g, ' ').trim()
|
|
85
|
+
return flat.length > limit ? `${flat.slice(0, limit)}…` : flat
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function apply(ctx, rawConfig) {
|
|
89
|
+
const config = resolveConfig(rawConfig)
|
|
90
|
+
const logPath = join(dirname(config.statePath), 'bridge.log')
|
|
91
|
+
|
|
92
|
+
const log = (message) => {
|
|
93
|
+
console.log(`[dsh-qq-bridge] ${message}`)
|
|
94
|
+
void appendFile(logPath, `${new Date().toISOString()} ${message}\n`, 'utf8').catch(() => {})
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (config.enabled === false) {
|
|
98
|
+
log('disabled by config')
|
|
99
|
+
return
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const store = new ConversationStore(config.statePath)
|
|
103
|
+
const bridge = new HttpBridge({ host: config.host, port: config.port, token: config.token, log })
|
|
104
|
+
/** @type {{ sessionController?: any }} */
|
|
105
|
+
const host = {}
|
|
106
|
+
/** Live per-session turn capture: sessionId → { texts, tools }. */
|
|
107
|
+
const turns = new Map()
|
|
108
|
+
/** Recent group chatter per conversation, so a mention carries context. */
|
|
109
|
+
const contexts = new Map()
|
|
110
|
+
/** Truncated tool arguments per "sessionId:callId", shown in approvals. */
|
|
111
|
+
const callArguments = new Map()
|
|
112
|
+
/** Pending approval questions: approvalId → finish(outcome). */
|
|
113
|
+
const approvals = new Map()
|
|
114
|
+
/** Sessions this process already applied the model selection to. */
|
|
115
|
+
const selected = new Set()
|
|
116
|
+
/** Last time the bot long-polled us; approvals go to QQ only while this is fresh. */
|
|
117
|
+
let lastPullAt = 0
|
|
118
|
+
|
|
119
|
+
const ready = Promise.all([store.load(), mkdir(config.cwd, { recursive: true }), mkdir(dirname(logPath), { recursive: true })]).catch(error => {
|
|
120
|
+
log(`state init failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
// 一键装机器人环境:找 Python → 建 venv → 装依赖 → 复制随包代码 → 写配置 → 拉起
|
|
124
|
+
const pluginRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
|
125
|
+
const installer = new Installer({
|
|
126
|
+
dataDir: config.dataDir,
|
|
127
|
+
sourceDir: join(pluginRoot, 'bot'),
|
|
128
|
+
log,
|
|
129
|
+
launch: async (pythonPath, botDir) => {
|
|
130
|
+
const { spawn } = await import('node:child_process')
|
|
131
|
+
const child = spawn(pythonPath, ['-u', 'main.py', '--supervise'], {
|
|
132
|
+
cwd: botDir,
|
|
133
|
+
detached: true,
|
|
134
|
+
stdio: 'ignore',
|
|
135
|
+
windowsHide: true,
|
|
136
|
+
})
|
|
137
|
+
child.unref()
|
|
138
|
+
log(`bot supervisor spawned after install (pid ${child.pid})`)
|
|
139
|
+
return child.pid
|
|
140
|
+
},
|
|
141
|
+
})
|
|
142
|
+
void installer.load()
|
|
143
|
+
|
|
144
|
+
const stripHints = (line) => {
|
|
145
|
+
// the bot appends a sticker hint to the prompt; keep it out of the transcript
|
|
146
|
+
const at = line.indexOf('(想发个表情包时')
|
|
147
|
+
return at === -1 ? line : line.slice(0, at).trimEnd()
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Longer per-conversation history (with timestamps) the model can search.
|
|
151
|
+
const history = new Map()
|
|
152
|
+
const stamp = () => {
|
|
153
|
+
const now = new Date()
|
|
154
|
+
return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
|
|
155
|
+
}
|
|
156
|
+
const pushHistory = (convKey, line) => {
|
|
157
|
+
const list = history.get(convKey) ?? []
|
|
158
|
+
list.push(`[${stamp()}] ${stripHints(line)}`)
|
|
159
|
+
const cap = Number.isFinite(config.historyMax) ? config.historyMax : 200
|
|
160
|
+
if (list.length > cap) list.splice(0, list.length - cap)
|
|
161
|
+
history.set(convKey, list)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// One workspace per QQ conversation when auto-grouping is on; falls back to cwd.
|
|
165
|
+
const workspaceFor = async (convKey, overrides) => {
|
|
166
|
+
const enabled = overrides?.autoGroup === undefined ? config.autoGroup === true : overrides.autoGroup === true
|
|
167
|
+
if (!enabled) return config.cwd
|
|
168
|
+
const root = String(overrides?.autoGroupRoot || config.autoGroupRoot || 'D:\\dsh-qqbot-temp')
|
|
169
|
+
const name = convKey.replace(/[^A-Za-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'qq'
|
|
170
|
+
const dir = join(root, name)
|
|
171
|
+
try {
|
|
172
|
+
await mkdir(dir, { recursive: true })
|
|
173
|
+
return dir
|
|
174
|
+
} catch (error) {
|
|
175
|
+
log(`workspace mkdir failed (${dir}): ${error instanceof Error ? error.message : String(error)}`)
|
|
176
|
+
return config.cwd
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// 会话搬家:优先调用 dsh-edit-file-workspace 的 /move 路由(保留上下文),
|
|
181
|
+
// 失败才退化成"新建会话"(丢上下文)。该路由要求请求来自回环,我们的桥就在本机。
|
|
182
|
+
const moveSessionTo = async (sessionId, targetPath) => {
|
|
183
|
+
let webServer
|
|
184
|
+
try {
|
|
185
|
+
webServer = typeof ctx.get === 'function' ? ctx.get('webServer') : undefined
|
|
186
|
+
} catch (error) {
|
|
187
|
+
webServer = undefined
|
|
188
|
+
}
|
|
189
|
+
const port = webServer && typeof webServer.port === 'number' ? webServer.port : 0
|
|
190
|
+
if (port === 0) return { ok: false, reason: 'webServer 不可用' }
|
|
191
|
+
try {
|
|
192
|
+
const response = await fetch(`http://127.0.0.1:${port}/api/dsh-edit-file-workspace/move`, {
|
|
193
|
+
method: 'POST',
|
|
194
|
+
headers: { 'content-type': 'application/json' },
|
|
195
|
+
body: JSON.stringify({ sessionId, path: targetPath }),
|
|
196
|
+
})
|
|
197
|
+
const payload = await response.json().catch(() => ({}))
|
|
198
|
+
if (response.ok) return { ok: true, sandbox: payload?.sandbox }
|
|
199
|
+
return { ok: false, reason: payload?.error || ('HTTP ' + response.status) }
|
|
200
|
+
} catch (error) {
|
|
201
|
+
return { ok: false, reason: error instanceof Error ? error.message : String(error) }
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
// 提问通道:pending 表 + QQ 卡片投递(单题单选;多题/多选下一步)
|
|
205
|
+
const questionPending = new Map()
|
|
206
|
+
const sessionToConv = new Map()
|
|
207
|
+
const askOnQq = async (convKey, id, question, options) => {
|
|
208
|
+
const port = Number(config.panelPort) || 39062
|
|
209
|
+
const response = await fetch(`http://127.0.0.1:${port}/api/question`, {
|
|
210
|
+
method: 'POST',
|
|
211
|
+
headers: { 'content-type': 'application/json' },
|
|
212
|
+
body: JSON.stringify({ convKey, id, question, options }),
|
|
213
|
+
})
|
|
214
|
+
if (!response.ok) throw new Error(`bot question endpoint HTTP ${response.status}`)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const installQuestionChannel = () => {
|
|
218
|
+
if (typeof ctx.on !== 'function') return () => {}
|
|
219
|
+
const sessionToConv = new Map()
|
|
220
|
+
const refreshMap = async () => {
|
|
221
|
+
try {
|
|
222
|
+
const listed = await bridge.listConversations?.()
|
|
223
|
+
if (Array.isArray(listed?.conversations)) {
|
|
224
|
+
for (const item of listed.conversations) {
|
|
225
|
+
const convKey = String(item.convKey ?? item.key ?? "")
|
|
226
|
+
const sessionId = store.sessionOf(convKey)
|
|
227
|
+
if (sessionId !== undefined) sessionToConv.set(String(sessionId), convKey)
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
} catch (error) { /* map stays as-is */ }
|
|
231
|
+
}
|
|
232
|
+
void refreshMap()
|
|
233
|
+
// 官方契约:waterfall answerer 要 { global: true, prepend: true },
|
|
234
|
+
// 回调返回 Promise<UserQuestionResult>;不是 QQ 会话就 return next()。
|
|
235
|
+
return ctx.on('user-questions/request', (request, next) => {
|
|
236
|
+
const agentId = String(request?.agent?.id ?? "")
|
|
237
|
+
// store.convOf 是持久化的反查(sessionId → convKey),插件重启也不会丢
|
|
238
|
+
const convKey = sessionToConv.get(agentId) ?? store.convOf(agentId)
|
|
239
|
+
log(`question request: agent=${agentId} conv=${convKey ?? '-'}`)
|
|
240
|
+
const questions = Array.isArray(request?.questions) ? request.questions : []
|
|
241
|
+
const first = questions[0]
|
|
242
|
+
const options = Array.isArray(first?.options) ? first.options : []
|
|
243
|
+
if (convKey === undefined || first === undefined || options.length === 0) return next()
|
|
244
|
+
const id = randomUUID()
|
|
245
|
+
const labels = options.map((item) => String(item.label ?? item))
|
|
246
|
+
return new Promise((resolve, reject) => {
|
|
247
|
+
// 超时兜底:QQ 那边一直没人点也不能把 ask_user_question 挂死
|
|
248
|
+
const timeoutMs = Number(config.approvalTimeoutMs) || 150000
|
|
249
|
+
const deadline = setTimeout(() => {
|
|
250
|
+
if (!questionPending.has(id)) return
|
|
251
|
+
questionPending.delete(id)
|
|
252
|
+
const error = new Error("ask_user_question timed out waiting for a QQ answer")
|
|
253
|
+
error.code = "ASK_ABORTED"
|
|
254
|
+
reject(error)
|
|
255
|
+
}, timeoutMs)
|
|
256
|
+
questionPending.set(id, {
|
|
257
|
+
deadline,
|
|
258
|
+
resolve: (answer) => {
|
|
259
|
+
const index = Number(answer?.index)
|
|
260
|
+
const picked = labels[index]
|
|
261
|
+
questionPending.delete(id)
|
|
262
|
+
resolve({ answers: [{ questionIndex: 0, selected: picked === undefined ? [] : [picked] }] })
|
|
263
|
+
},
|
|
264
|
+
})
|
|
265
|
+
const signal = request?.signal
|
|
266
|
+
if (signal !== undefined && typeof signal.addEventListener === "function") {
|
|
267
|
+
signal.addEventListener("abort", () => {
|
|
268
|
+
questionPending.delete(id)
|
|
269
|
+
const error = new Error("ask_user_question was aborted before the user answered")
|
|
270
|
+
error.code = "ASK_ABORTED"
|
|
271
|
+
reject(error)
|
|
272
|
+
})
|
|
273
|
+
}
|
|
274
|
+
void askOnQq(convKey, id, String(first.question ?? ""), labels).catch((error) => {
|
|
275
|
+
questionPending.delete(id)
|
|
276
|
+
reject(error instanceof Error ? error : new Error(String(error)))
|
|
277
|
+
})
|
|
278
|
+
})
|
|
279
|
+
}, { global: true, prepend: true })
|
|
280
|
+
}
|
|
281
|
+
// 提示词形状的文本(机器人自己拼的判断/闲聊提示)不许进历史,否则会被当成群友发言回灌给模型
|
|
282
|
+
const looksLikePrompt = (value) => {
|
|
283
|
+
const text = String(value ?? '')
|
|
284
|
+
return text.includes('【闲聊模式】') || text.includes('【群聊插话判断】')
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const remember = (convKey, line) => {
|
|
288
|
+
if (looksLikePrompt(line)) return
|
|
289
|
+
const list = contexts.get(convKey) ?? []
|
|
290
|
+
const stamped = `[${stamp()}] ${stripHints(line)}`
|
|
291
|
+
list.push(stamped)
|
|
292
|
+
if (list.length > config.contextLines) list.splice(0, list.length - config.contextLines)
|
|
293
|
+
contexts.set(convKey, list)
|
|
294
|
+
pushHistory(convKey, line)
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Model-facing preamble: where the message came from and who is speaking. */
|
|
298
|
+
const composePrompt = ({ text, convKey, senderName, isOwner, chime, quote, persona }) => {
|
|
299
|
+
const isGroup = convKey.startsWith('group:')
|
|
300
|
+
const header = isGroup ? 'QQ 群聊' : 'QQ 单聊'
|
|
301
|
+
const who = isOwner
|
|
302
|
+
? `${senderName || '主人'}(机器人主人本人:可以远程办公,直接读写工作目录、执行命令、查资料,做完再回答)`
|
|
303
|
+
: `${senderName || '群友'}(普通群友:自然聊天为主;要改文件或跑命令时先说明理由,主人批准后才继续)`
|
|
304
|
+
const recent = contexts.get(convKey) ?? []
|
|
305
|
+
const parts = [`[${header}] ${who}:`]
|
|
306
|
+
if (quote !== undefined) {
|
|
307
|
+
// Structured by the bot: text / image / file / other, plus the author when known.
|
|
308
|
+
const who = quote.author || '一条更早的消息'
|
|
309
|
+
const kind = typeof quote.kind === 'string' ? quote.kind : 'text'
|
|
310
|
+
if (quote.resolved === true && kind === 'image') {
|
|
311
|
+
parts.push(`【引用了${who}发的一张图片】`, '')
|
|
312
|
+
} else if (quote.resolved === true && kind === 'file') {
|
|
313
|
+
parts.push(`【引用了${who}发的文件:${String(quote.text ?? '') || '(未命名)'}】`, '')
|
|
314
|
+
} else if (quote.resolved === true && kind === 'other') {
|
|
315
|
+
parts.push(`【引用了${who}发的一条非文本消息】`, '')
|
|
316
|
+
} else if (quote.resolved === true) {
|
|
317
|
+
const limit = Number.isFinite(config.quoteContextChars) ? config.quoteContextChars : 300
|
|
318
|
+
const full = String(quote.text ?? '')
|
|
319
|
+
const cut = full.length > limit
|
|
320
|
+
const quoted = cut ? `${full.slice(0, limit)}…` : full
|
|
321
|
+
parts.push(`【引用了${who}的消息】`, `“${quoted || '(空)'}”`, '')
|
|
322
|
+
} else {
|
|
323
|
+
const hint = quote.author ? `(可能来自${quote.author})` : ''
|
|
324
|
+
parts.push(`【对方引用了一条我这边看不到内容的消息${hint}】`, '')
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
parts.push(text)
|
|
328
|
+
if (isGroup && recent.length > 0) {
|
|
329
|
+
parts.push('', '最近的群聊记录(只作上下文,不必逐条回应):', ...recent)
|
|
330
|
+
}
|
|
331
|
+
if (chime) {
|
|
332
|
+
parts.push('', '这条不是点名问你,是你自己决定要不要插话:觉得没必要就只回 [NO_REPLY]。')
|
|
333
|
+
}
|
|
334
|
+
parts.push('', isGroup && !isOwner
|
|
335
|
+
? '(这是群聊:像真人一样回 1~3 句口语。想清楚再说完,不要复述工具过程。)'
|
|
336
|
+
: '(先直接回答,别铺垫;默认简短,需要细节时再用 Markdown 展开。)')
|
|
337
|
+
parts.push('', '(QQ 侧支持 Markdown 渲染:标题/列表/代码块/表格都能用,表情符号可以直接用。要把本地图片或文件发给对方,先把文件写到工作目录里,再在回复里单独一行写 [[send_file: 绝对路径]],机器人会把它作为文件发出。)')
|
|
338
|
+
// 人设只在会话的第一条消息里出现一次,之后靠会话历史记住
|
|
339
|
+
if (typeof persona === 'string' && persona.trim() !== '') parts.push('', '人设:', persona.trim())
|
|
340
|
+
return parts.join('\n')
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Ask the bot owner, then translate the answer into an approval outcome. */
|
|
344
|
+
const requestDecision = ({ approvalId, convKey, approvalTarget, toolName, reason, argumentPreview, signal }) => new Promise((resolveDecision) => {
|
|
345
|
+
const settle = (outcome) => {
|
|
346
|
+
clearTimeout(timer)
|
|
347
|
+
signal?.removeEventListener?.('abort', onAbort)
|
|
348
|
+
approvals.delete(approvalId)
|
|
349
|
+
resolveDecision(outcome)
|
|
350
|
+
}
|
|
351
|
+
const finish = (outcome) => {
|
|
352
|
+
if (!approvals.has(approvalId)) return
|
|
353
|
+
settle(outcome)
|
|
354
|
+
}
|
|
355
|
+
const timer = setTimeout(() => {
|
|
356
|
+
if (!approvals.has(approvalId)) return
|
|
357
|
+
bridge.push({ type: 'notice', convKey, target: approvalTarget, text: `审批超时(${toolName}),已按拒绝处理。` })
|
|
358
|
+
log(`approval timeout: ${toolName}`)
|
|
359
|
+
settle('rejected')
|
|
360
|
+
}, config.approvalTimeoutMs)
|
|
361
|
+
const onAbort = () => finish('cancelled')
|
|
362
|
+
approvals.set(approvalId, finish)
|
|
363
|
+
signal?.addEventListener?.('abort', onAbort, { once: true })
|
|
364
|
+
bridge.push({
|
|
365
|
+
type: 'approval',
|
|
366
|
+
convKey,
|
|
367
|
+
target: approvalTarget,
|
|
368
|
+
approvalId,
|
|
369
|
+
toolName,
|
|
370
|
+
reason,
|
|
371
|
+
argumentPreview,
|
|
372
|
+
expiresAt: Date.now() + config.approvalTimeoutMs,
|
|
373
|
+
})
|
|
374
|
+
log(`approval asked: ${toolName} (${convKey})`)
|
|
375
|
+
})
|
|
376
|
+
|
|
377
|
+
/** Ask the Host for its Session list, tolerating builds without a list API. */
|
|
378
|
+
const listSessions = async () => {
|
|
379
|
+
const controller = host.sessionController
|
|
380
|
+
if (controller === undefined) return { source: 'none', sessions: [] }
|
|
381
|
+
for (const method of ['list', 'listSessions', 'listAll', 'all', 'sessions', 'query']) {
|
|
382
|
+
const fn = controller[method]
|
|
383
|
+
if (typeof fn !== 'function') continue
|
|
384
|
+
try {
|
|
385
|
+
const value = await fn.call(controller, {})
|
|
386
|
+
const rows = Array.isArray(value) ? value : (Array.isArray(value?.sessions) ? value.sessions : [])
|
|
387
|
+
return {
|
|
388
|
+
source: method,
|
|
389
|
+
sessions: rows
|
|
390
|
+
.map(row => ({
|
|
391
|
+
id: String(row?.sessionId ?? row?.id ?? ''),
|
|
392
|
+
title: String(row?.title ?? row?.name ?? ''),
|
|
393
|
+
cwd: String(row?.cwd ?? ''),
|
|
394
|
+
}))
|
|
395
|
+
.filter(row => row.id !== ''),
|
|
396
|
+
}
|
|
397
|
+
} catch (error) {
|
|
398
|
+
return { source: method, sessions: [], error: error instanceof Error ? error.message : String(error) }
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
return { source: 'unavailable', sessions: [] }
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const markPull = () => { lastPullAt = Date.now() }
|
|
405
|
+
const botIsListening = () => lastPullAt !== 0 && Date.now() - lastPullAt < 45000
|
|
406
|
+
bridge.setOnPull(markPull)
|
|
407
|
+
|
|
408
|
+
bridge.setHandlers({
|
|
409
|
+
health: () => ({
|
|
410
|
+
ok: true,
|
|
411
|
+
plugin: 'dsh-qq-bridge',
|
|
412
|
+
service: host.sessionController === undefined ? 'waiting' : 'ready',
|
|
413
|
+
conversations: store.size(),
|
|
414
|
+
pendingApprovals: approvals.size,
|
|
415
|
+
}),
|
|
416
|
+
// 设置面板的「下载 / 配置机器人」:status 查进度,start 开装
|
|
417
|
+
install: async (body) => {
|
|
418
|
+
const action = typeof body?.action === 'string' && body.action !== '' ? body.action : 'status'
|
|
419
|
+
if (action === 'status') return { ok: true, ...installer.state() }
|
|
420
|
+
if (action !== 'start') return { ok: false, error: `unknown install action: ${action}` }
|
|
421
|
+
installer.sourceDir = await resolveSourceDir(pluginRoot)
|
|
422
|
+
const started = installer.start({
|
|
423
|
+
appid: typeof body.appid === 'string' ? body.appid : '',
|
|
424
|
+
appsecret: typeof body.appsecret === 'string' ? body.appsecret : '',
|
|
425
|
+
autoGroupRoot: typeof body.autoGroupRoot === 'string' ? body.autoGroupRoot : '',
|
|
426
|
+
// 新装的机器人要连的就是这个插件,地址与令牌直接给它带上
|
|
427
|
+
bridgeUrl: `http://${config.host}:${config.port}`,
|
|
428
|
+
bridgeToken: config.token,
|
|
429
|
+
})
|
|
430
|
+
log(`install started: source=${installer.sourceDir} target=${installer.botDir}`)
|
|
431
|
+
return { ok: true, ...started }
|
|
432
|
+
},
|
|
433
|
+
status: () => ({
|
|
434
|
+
ok: true,
|
|
435
|
+
cwd: config.cwd,
|
|
436
|
+
statePath: config.statePath,
|
|
437
|
+
service: host.sessionController === undefined ? 'waiting' : 'ready',
|
|
438
|
+
conversations: store.entries(),
|
|
439
|
+
bufferedContexts: [...contexts.entries()].map(([key, lines]) => [key, lines.length]),
|
|
440
|
+
pendingApprovals: [...approvals.keys()],
|
|
441
|
+
cursor: bridge.cursor,
|
|
442
|
+
}),
|
|
443
|
+
reset: async (body) => {
|
|
444
|
+
const convKey = typeof body?.convKey === 'string' ? body.convKey : ''
|
|
445
|
+
if (convKey === '') return { ok: false, error: 'convKey required' }
|
|
446
|
+
await store.unbind(convKey)
|
|
447
|
+
contexts.delete(convKey)
|
|
448
|
+
log(`conversation reset: ${convKey}`)
|
|
449
|
+
return { ok: true, convKey }
|
|
450
|
+
},
|
|
451
|
+
/** Move one QQ conversation onto another existing Session ('' = go back). */
|
|
452
|
+
switch: async (body) => {
|
|
453
|
+
await ready
|
|
454
|
+
const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
|
|
455
|
+
const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : ''
|
|
456
|
+
if (convKey === '') return { ok: false, error: 'convKey required' }
|
|
457
|
+
if (sessionId === '') {
|
|
458
|
+
const restored = await store.switchBack(convKey)
|
|
459
|
+
if (restored === undefined) return { ok: false, error: '没有可切回的会话' }
|
|
460
|
+
contexts.delete(convKey)
|
|
461
|
+
log(`switched back: ${convKey} → ${restored}`)
|
|
462
|
+
return { ok: true, convKey, sessionId: restored }
|
|
463
|
+
}
|
|
464
|
+
const previous = store.sessionOf(convKey)
|
|
465
|
+
await store.switchTo(convKey, sessionId)
|
|
466
|
+
contexts.delete(convKey)
|
|
467
|
+
log(`switched: ${convKey} → ${sessionId} (was ${previous ?? 'none'})`)
|
|
468
|
+
return { ok: true, convKey, sessionId, previous: previous ?? '' }
|
|
469
|
+
},
|
|
470
|
+
sessions: async () => {
|
|
471
|
+
await ready
|
|
472
|
+
return { ok: true, bound: store.entries(), returns: store.returnEntries(), host: await listSessions() }
|
|
473
|
+
},
|
|
474
|
+
inbound: async (body) => {
|
|
475
|
+
await ready
|
|
476
|
+
const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
|
|
477
|
+
const text = typeof body?.text === 'string' ? body.text : ''
|
|
478
|
+
const images = Array.isArray(body?.images) ? body.images : []
|
|
479
|
+
if (convKey === '') return { ok: false, error: 'convKey required' }
|
|
480
|
+
if (text.trim() === '' && images.length === 0) return { ok: false, error: 'text or images required' }
|
|
481
|
+
|
|
482
|
+
const senderName = typeof body?.senderName === 'string' ? body.senderName : ''
|
|
483
|
+
// quoted message resolved by the bot (see bot/main.py _resolve_quote)
|
|
484
|
+
const quote = body?.quote !== null && typeof body?.quote === 'object' ? body.quote : undefined
|
|
485
|
+
const quoteMark = quote !== undefined && quote.resolved === true
|
|
486
|
+
? ` ↩[${quote.author || '引用'}]`
|
|
487
|
+
: ''
|
|
488
|
+
const label = (text.trim() === '' ? '[图片]' : preview(text, 200)) + quoteMark
|
|
489
|
+
|
|
490
|
+
// Background group chatter: keep it as context, never start a turn for it.
|
|
491
|
+
if (body?.contextOnly === true) {
|
|
492
|
+
if (!looksLikePrompt(text)) remember(convKey, `${senderName || '群友'}: ${label}`)
|
|
493
|
+
return { ok: true, buffered: true }
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const sessionController = host.sessionController
|
|
497
|
+
if (sessionController === undefined) return { ok: false, error: 'sessionController unavailable' }
|
|
498
|
+
|
|
499
|
+
let sessionId = store.sessionOf(convKey)
|
|
500
|
+
let freshSession = false
|
|
501
|
+
if (sessionId === undefined) {
|
|
502
|
+
const created = await sessionController.create({ cwd: await workspaceFor(convKey, { autoGroup: body?.autoGroup, autoGroupRoot: body?.autoGroupRoot }) })
|
|
503
|
+
sessionId = String(created.sessionId)
|
|
504
|
+
freshSession = true
|
|
505
|
+
log(`session created: ${convKey} → ${sessionId}`)
|
|
506
|
+
}
|
|
507
|
+
await store.bind(convKey, sessionId, typeof body?.approvalTarget === 'string' ? body.approvalTarget : undefined)
|
|
508
|
+
sessionToConv.set(String(sessionId), convKey)
|
|
509
|
+
|
|
510
|
+
// Casual chat is latency-bound: pin the session to the configured model /
|
|
511
|
+
// reasoning effort once, without losing the Session's history.
|
|
512
|
+
if (!selected.has(sessionId) && config.modelProvider !== '' && config.model !== '') {
|
|
513
|
+
try {
|
|
514
|
+
await sessionController.selectModel({
|
|
515
|
+
sessionId,
|
|
516
|
+
provider: config.modelProvider,
|
|
517
|
+
model: config.model,
|
|
518
|
+
...(config.reasoningEffort !== '' ? { reasoningEffort: config.reasoningEffort } : {}),
|
|
519
|
+
})
|
|
520
|
+
log(`model pinned for ${sessionId}: ${config.modelProvider}/${config.model} effort=${config.reasoningEffort || 'default'}`)
|
|
521
|
+
} catch (error) {
|
|
522
|
+
log(`selectModel failed for ${sessionId}: ${error instanceof Error ? error.message : String(error)}`)
|
|
523
|
+
}
|
|
524
|
+
selected.add(sessionId)
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// 人设随请求带过来;只有刚建的新会话才塞进提示词,之后不再重复
|
|
528
|
+
const persona = freshSession && typeof body?.persona === 'string' ? body.persona : ''
|
|
529
|
+
const content = [{ type: 'text', text: composePrompt({ text, convKey, senderName, isOwner: body?.isOwner === true, chime: body?.chime === true, quote, persona }) }]
|
|
530
|
+
for (const image of images.slice(0, 4)) {
|
|
531
|
+
const mediaType = typeof image?.mediaType === 'string' ? image.mediaType : ''
|
|
532
|
+
const data = typeof image?.data === 'string' ? image.data : ''
|
|
533
|
+
if (!IMAGE_TYPES.has(mediaType) || data === '') continue
|
|
534
|
+
content.push({ type: 'image', mediaType, data })
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
const controller = new AbortController()
|
|
538
|
+
const timer = setTimeout(() => controller.abort(), 120000)
|
|
539
|
+
try {
|
|
540
|
+
await sessionController.prompt({
|
|
541
|
+
requestId: randomUUID(),
|
|
542
|
+
sessionId,
|
|
543
|
+
mode: 'queue',
|
|
544
|
+
content,
|
|
545
|
+
clientTimeZone: 'Asia/Shanghai',
|
|
546
|
+
}, controller.signal)
|
|
547
|
+
} finally {
|
|
548
|
+
clearTimeout(timer)
|
|
549
|
+
}
|
|
550
|
+
if (!looksLikePrompt(text)) remember(convKey, `${senderName || '群友'}: ${label}`)
|
|
551
|
+
return { ok: true, sessionId, accepted: true }
|
|
552
|
+
},
|
|
553
|
+
rebind: async (body) => {
|
|
554
|
+
await ready
|
|
555
|
+
const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
|
|
556
|
+
if (convKey === '') return { ok: false, error: 'convKey required' }
|
|
557
|
+
const sessionController = host.sessionController
|
|
558
|
+
if (sessionController === undefined) return { ok: false, error: 'sessionController unavailable' }
|
|
559
|
+
const dir = await workspaceFor(convKey, { autoGroup: body?.autoGroup, autoGroupRoot: body?.autoGroupRoot })
|
|
560
|
+
const existing = store.sessionOf(convKey)
|
|
561
|
+
let fallbackReason = ""
|
|
562
|
+
if (existing !== undefined) {
|
|
563
|
+
const moved = await moveSessionTo(existing, dir)
|
|
564
|
+
if (moved.ok) return { ok: true, sessionId: existing, cwd: dir, moved: true, sandbox: moved.sandbox }
|
|
565
|
+
fallbackReason = String(moved.reason || 'move failed')
|
|
566
|
+
log(`session move failed (${convKey}): ${fallbackReason}; falling back to a new session`)
|
|
567
|
+
}
|
|
568
|
+
try {
|
|
569
|
+
const created = await sessionController.create({ cwd: dir })
|
|
570
|
+
const sessionId = String(created.sessionId)
|
|
571
|
+
await store.bind(convKey, sessionId, typeof body?.approvalTarget === 'string' ? body.approvalTarget : undefined)
|
|
572
|
+
sessionToConv.set(String(sessionId), convKey)
|
|
573
|
+
return { ok: true, sessionId, cwd: dir, moved: false, fallbackReason, previous: body?.previous || null }
|
|
574
|
+
} catch (error) {
|
|
575
|
+
return { ok: false, error: 'create failed: ' + (error instanceof Error ? error.message : String(error)) }
|
|
576
|
+
}
|
|
577
|
+
},
|
|
578
|
+
|
|
579
|
+
answer: async (body) => {
|
|
580
|
+
await ready
|
|
581
|
+
const id = typeof body?.id === 'string' ? body.id : ''
|
|
582
|
+
if (id === '') return { ok: false, error: 'id required' }
|
|
583
|
+
const pending = questionPending.get(id)
|
|
584
|
+
if (pending?.deadline) clearTimeout(pending.deadline)
|
|
585
|
+
if (pending === undefined) return { ok: false, error: 'this question is no longer pending' }
|
|
586
|
+
questionPending.delete(id)
|
|
587
|
+
try { pending.resolve(body) } catch (error) { /* already settled */ }
|
|
588
|
+
return { ok: true }
|
|
589
|
+
},
|
|
590
|
+
commands: async (body) => {
|
|
591
|
+
await ready
|
|
592
|
+
const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
|
|
593
|
+
const ctxOf = (name) => { try { return typeof ctx.get === 'function' ? ctx.get(name) : undefined } catch (error) { return undefined } }
|
|
594
|
+
const agents = ctxOf('agents')
|
|
595
|
+
const runtime = ctxOf('commands')
|
|
596
|
+
if (agents === undefined || runtime === undefined) return { ok: false, error: 'agents/commands 服务不可用' }
|
|
597
|
+
const sessionId = store.sessionOf(convKey)
|
|
598
|
+
if (sessionId === undefined) return { ok: false, error: '这个会话还没有 DSH 会话' }
|
|
599
|
+
const agent = typeof agents.get === 'function' ? agents.get(sessionId) : undefined
|
|
600
|
+
if (agent === undefined) return { ok: false, error: '会话未加载(先聊一句)' }
|
|
601
|
+
let list = []
|
|
602
|
+
try {
|
|
603
|
+
list = runtime.list(agent).map((item) => ({
|
|
604
|
+
name: item.name,
|
|
605
|
+
description: item.description || item.summary || '',
|
|
606
|
+
source: item.source || '',
|
|
607
|
+
}))
|
|
608
|
+
} catch (error) {
|
|
609
|
+
return { ok: false, error: 'list failed: ' + (error instanceof Error ? error.message : String(error)) }
|
|
610
|
+
}
|
|
611
|
+
return { ok: true, count: list.length, commands: list }
|
|
612
|
+
},
|
|
613
|
+
|
|
614
|
+
command: async (body) => {
|
|
615
|
+
await ready
|
|
616
|
+
const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
|
|
617
|
+
const line = typeof body?.line === 'string' ? body.line.trim() : ''
|
|
618
|
+
if (line === '') return { ok: false, error: 'line required' }
|
|
619
|
+
const ctxOf = (name) => { try { return typeof ctx.get === 'function' ? ctx.get(name) : undefined } catch (error) { return undefined } }
|
|
620
|
+
const agents = ctxOf('agents')
|
|
621
|
+
const runtime = ctxOf('commands')
|
|
622
|
+
if (agents === undefined || runtime === undefined) return { ok: false, error: 'agents/commands 服务不可用' }
|
|
623
|
+
const sessionId = store.sessionOf(convKey)
|
|
624
|
+
if (sessionId === undefined) return { ok: false, error: '这个会话还没有 DSH 会话' }
|
|
625
|
+
const agent = typeof agents.get === 'function' ? agents.get(sessionId) : undefined
|
|
626
|
+
if (agent === undefined) return { ok: false, error: '会话未加载(先聊一句)' }
|
|
627
|
+
try {
|
|
628
|
+
const result = await runtime.execute(agent, line, [], new AbortController().signal)
|
|
629
|
+
return { ok: true, handled: result !== undefined, line }
|
|
630
|
+
} catch (error) {
|
|
631
|
+
return { ok: false, error: 'execute failed: ' + (error instanceof Error ? error.message : String(error)) }
|
|
632
|
+
}
|
|
633
|
+
},
|
|
634
|
+
permission: async (body) => {
|
|
635
|
+
await ready
|
|
636
|
+
const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
|
|
637
|
+
const preset = typeof body?.preset === 'string' ? body.preset.trim() : ''
|
|
638
|
+
let service = host.permissionPresets
|
|
639
|
+
if (service === undefined && typeof ctx.get === 'function') service = ctx.get('permissionPresets')
|
|
640
|
+
const names = service && Array.isArray(service.names) ? service.names.slice() : []
|
|
641
|
+
// 该会话"当下生效"的权限值(会话投影),读不到就退回默认值
|
|
642
|
+
const liveCurrent = () => {
|
|
643
|
+
try {
|
|
644
|
+
const sid = store.sessionOf(convKey)
|
|
645
|
+
if (sid === undefined) return ''
|
|
646
|
+
const pick = (name) => { try { return typeof ctx.get === 'function' ? ctx.get(name) : undefined } catch (error) { return undefined } }
|
|
647
|
+
const sessions = pick('sessions')
|
|
648
|
+
let session = sessions && typeof sessions.get === 'function' ? sessions.get(sid) : undefined
|
|
649
|
+
if (session === undefined) {
|
|
650
|
+
const agents = pick('agents')
|
|
651
|
+
session = agents && typeof agents.get === 'function' ? agents.get(sid) : undefined
|
|
652
|
+
}
|
|
653
|
+
if (session !== undefined && service && typeof service.current === 'function') return service.current(session)
|
|
654
|
+
} catch (error) {
|
|
655
|
+
return ''
|
|
656
|
+
}
|
|
657
|
+
return ''
|
|
658
|
+
}
|
|
659
|
+
if (preset === '') {
|
|
660
|
+
return {
|
|
661
|
+
ok: names.length > 0,
|
|
662
|
+
names,
|
|
663
|
+
current: liveCurrent() || (service && typeof service.defaultPreset === 'string' ? service.defaultPreset : ''),
|
|
664
|
+
note: names.length > 0 ? '' : 'permissionPresets 服务不可用(这条 DSH 没启用权限预设)',
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
if (names.length > 0 && !names.includes(preset)) {
|
|
668
|
+
return { ok: false, error: 'unknown preset: ' + preset, names }
|
|
669
|
+
}
|
|
670
|
+
const sessionController = host.sessionController
|
|
671
|
+
let sessionId = store.sessionOf(convKey)
|
|
672
|
+
if (sessionController === undefined && sessionId === undefined) {
|
|
673
|
+
return { ok: false, error: 'sessionController unavailable' }
|
|
674
|
+
}
|
|
675
|
+
if (sessionId === undefined) {
|
|
676
|
+
// 还没聊过:先给这个 QQ 会话建 DSH 会话(自动工作区开启时自带独立目录),
|
|
677
|
+
// 否则 /pr 没法把命令投递进去。
|
|
678
|
+
try {
|
|
679
|
+
const created = await sessionController.create({
|
|
680
|
+
cwd: await workspaceFor(convKey, { autoGroup: body?.autoGroup, autoGroupRoot: body?.autoGroupRoot }),
|
|
681
|
+
})
|
|
682
|
+
sessionId = String(created.sessionId)
|
|
683
|
+
await store.bind(convKey, sessionId, typeof body?.approvalTarget === 'string' ? body.approvalTarget : undefined)
|
|
684
|
+
sessionToConv.set(String(sessionId), convKey)
|
|
685
|
+
} catch (error) {
|
|
686
|
+
return { ok: false, error: 'create session failed: ' + (error instanceof Error ? error.message : String(error)) }
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
// 官方写入口:permissionPresets.set(session, name)(/permission 命令内部走的就是它)。
|
|
690
|
+
// 之前用 sessionController.prompt 发文本,斜杠命令不会被解释,只会变成一条用户消息。
|
|
691
|
+
let sessions = undefined
|
|
692
|
+
try { sessions = typeof ctx.get === 'function' ? ctx.get('sessions') : undefined } catch (error) { sessions = undefined }
|
|
693
|
+
const session = sessions && typeof sessions.get === 'function' ? sessions.get(sessionId) : undefined
|
|
694
|
+
if (session === undefined) return { ok: false, error: '会话还没加载,先聊一句再试' }
|
|
695
|
+
if (service === undefined || typeof service.set !== 'function') {
|
|
696
|
+
return { ok: false, error: 'permissionPresets 服务不可用' }
|
|
697
|
+
}
|
|
698
|
+
try {
|
|
699
|
+
service.set(session, preset)
|
|
700
|
+
} catch (error) {
|
|
701
|
+
return { ok: false, error: 'set failed: ' + (error instanceof Error ? error.message : String(error)) }
|
|
702
|
+
}
|
|
703
|
+
let landed = ''
|
|
704
|
+
try { landed = typeof service.current === 'function' ? service.current(session) : '' } catch (error) { landed = '' }
|
|
705
|
+
return { ok: true, switched: preset, current: landed, names }
|
|
706
|
+
},
|
|
707
|
+
|
|
708
|
+
judge: async (body) => {
|
|
709
|
+
await ready
|
|
710
|
+
const convKey = typeof body?.convKey === 'string' ? body.convKey.trim() : ''
|
|
711
|
+
const transcript = typeof body?.transcript === 'string' ? body.transcript.trim() : ''
|
|
712
|
+
if (convKey === '' || transcript === '') return { ok: false, error: 'convKey/transcript required' }
|
|
713
|
+
const sessionController = host.sessionController
|
|
714
|
+
if (sessionController === undefined) return { ok: false, error: 'sessionController unavailable' }
|
|
715
|
+
|
|
716
|
+
let sessionId = judgeSessions.get(convKey)
|
|
717
|
+
try {
|
|
718
|
+
if (sessionId === undefined) {
|
|
719
|
+
const created = await sessionController.create({ cwd: config.cwd })
|
|
720
|
+
sessionId = String(created.sessionId)
|
|
721
|
+
judgeSessions.set(convKey, sessionId)
|
|
722
|
+
log(`judge session for ${convKey}: ${sessionId}`)
|
|
723
|
+
}
|
|
724
|
+
} catch (error) {
|
|
725
|
+
return { ok: false, error: `judge session failed: ${error instanceof Error ? error.message : String(error)}` }
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
judgeTexts.set(sessionId, [])
|
|
729
|
+
const verdict = new Promise(resolve => {
|
|
730
|
+
judgeWaiters.set(sessionId, resolve)
|
|
731
|
+
setTimeout(() => {
|
|
732
|
+
if (judgeWaiters.get(sessionId) === resolve) {
|
|
733
|
+
judgeWaiters.delete(sessionId)
|
|
734
|
+
resolve('')
|
|
735
|
+
}
|
|
736
|
+
}, 90000)
|
|
737
|
+
})
|
|
738
|
+
|
|
739
|
+
const threshold = Number.isFinite(Number(body?.threshold)) ? Number(body.threshold) : 2
|
|
740
|
+
const hint = typeof body?.hint === 'string' ? body.hint.trim() : ''
|
|
741
|
+
const instruction = [
|
|
742
|
+
'【群聊插话判断器】你就是这个群里的一员,只做决定:接一句,还是不说。',
|
|
743
|
+
'默认接一句(口语、1~2 句)。只有这三种情况才不说:',
|
|
744
|
+
'① 明显是两个人一对一搭话,既没提到你也没什么可加;',
|
|
745
|
+
'② 你刚说过同类的话;',
|
|
746
|
+
'③ 这条只是表情/图片/链接/单字,没有可回应的内容。',
|
|
747
|
+
'其余情况(抛观点、吐槽、问问题、接梗)都可以接;话题不熟也可以轻接。',
|
|
748
|
+
hint,
|
|
749
|
+
'',
|
|
750
|
+
'群里的原文(每行 发言人: 内容):',
|
|
751
|
+
transcript,
|
|
752
|
+
'',
|
|
753
|
+
'输出格式(严格两行):',
|
|
754
|
+
'第一行:[[join: 0~3]](3=必须接,2=想接,1=可接可不接,0=不说)',
|
|
755
|
+
'第二行:一句话理由(不超过 40 字)',
|
|
756
|
+
].filter(line => line !== '').join('\n')
|
|
757
|
+
|
|
758
|
+
try {
|
|
759
|
+
await sessionController.prompt({
|
|
760
|
+
requestId: randomUUID(),
|
|
761
|
+
sessionId,
|
|
762
|
+
mode: 'queue',
|
|
763
|
+
content: [{ type: 'text', text: instruction }],
|
|
764
|
+
clientTimeZone: 'Asia/Shanghai',
|
|
765
|
+
}, new AbortController().signal)
|
|
766
|
+
} catch (error) {
|
|
767
|
+
judgeWaiters.delete(sessionId)
|
|
768
|
+
return { ok: false, error: `judge prompt failed: ${error instanceof Error ? error.message : String(error)}` }
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
const answer = String(await verdict)
|
|
772
|
+
const lines = answer.split('\n').map(line => line.trim()).filter(line => line !== '')
|
|
773
|
+
const head = (lines[0] ?? '').toUpperCase()
|
|
774
|
+
const joinMatch = answer.match(/\[\[\s*join\s*:\s*([0-3])\s*\]\]/i)
|
|
775
|
+
const score = joinMatch ? Number(joinMatch[1]) : null
|
|
776
|
+
const legacyReply = head.startsWith('REPLY')
|
|
777
|
+
const legacySkip = head.startsWith('SKIP')
|
|
778
|
+
const needReply = score !== null ? score >= threshold : legacyReply
|
|
779
|
+
const decisive = score !== null || legacyReply || legacySkip
|
|
780
|
+
const noteSource = score !== null ? answer.replace(joinMatch[0], '') : lines.slice(1).join(' ')
|
|
781
|
+
return {
|
|
782
|
+
ok: decisive,
|
|
783
|
+
needReply,
|
|
784
|
+
score,
|
|
785
|
+
threshold,
|
|
786
|
+
note: noteSource.trim().split('\n').map(line => line.trim()).filter(line => line !== '').join(' ').slice(0, 200),
|
|
787
|
+
raw: answer.slice(0, 200),
|
|
788
|
+
}
|
|
789
|
+
},
|
|
790
|
+
approval: async (body) => {
|
|
791
|
+
const approvalId = typeof body?.approvalId === 'string' ? body.approvalId : ''
|
|
792
|
+
const decision = body?.decision === 'allow' ? 'allowed-once' : body?.decision === 'cancel' ? 'cancelled' : 'rejected'
|
|
793
|
+
const finish = approvals.get(approvalId)
|
|
794
|
+
if (finish === undefined) return { ok: false, error: 'unknown or expired approval' }
|
|
795
|
+
finish(decision)
|
|
796
|
+
log(`approval ${approvalId} → ${decision}`)
|
|
797
|
+
return { ok: true, approvalId, decision }
|
|
798
|
+
},
|
|
799
|
+
})
|
|
800
|
+
|
|
801
|
+
// Keep the QQ bot alive across DSH restarts: DSH owns its own lifecycle, so
|
|
802
|
+
// the host half re-spawns the supervised bot whenever the panel is missing.
|
|
803
|
+
const ensureBot = async () => {
|
|
804
|
+
if (config.autoStartBot !== true) return
|
|
805
|
+
try {
|
|
806
|
+
const response = await fetch(`http://127.0.0.1:${config.panelPort ?? 39062}/health`, { signal: AbortSignal.timeout(1500) })
|
|
807
|
+
if (response.ok) return
|
|
808
|
+
} catch {
|
|
809
|
+
// panel unreachable -> the supervisor is gone, start it
|
|
810
|
+
}
|
|
811
|
+
try {
|
|
812
|
+
// 一键装过就按 install.json 里的 venv 解释器和安装目录启动
|
|
813
|
+
const installed = await readInstall(config.dataDir)
|
|
814
|
+
const pythonPath = typeof installed?.pythonPath === 'string' && installed.pythonPath !== '' ? installed.pythonPath : config.pythonPath
|
|
815
|
+
const botDir = typeof installed?.botDir === 'string' && installed.botDir !== '' ? installed.botDir : config.botDir
|
|
816
|
+
const { spawn } = await import('node:child_process')
|
|
817
|
+
const child = spawn(pythonPath, ['-u', 'main.py', '--supervise'], {
|
|
818
|
+
cwd: botDir,
|
|
819
|
+
detached: true,
|
|
820
|
+
stdio: 'ignore',
|
|
821
|
+
windowsHide: true,
|
|
822
|
+
})
|
|
823
|
+
child.unref()
|
|
824
|
+
log(`bot supervisor spawned (pid ${child.pid})`)
|
|
825
|
+
} catch (error) {
|
|
826
|
+
log(`bot autostart failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
ctx.effect(() => {
|
|
830
|
+
const first = setTimeout(() => { void ensureBot() }, 8000)
|
|
831
|
+
const ticker = setInterval(() => { void ensureBot() }, 60000)
|
|
832
|
+
return () => { clearTimeout(first); clearInterval(ticker) }
|
|
833
|
+
}, 'dsh-qq-bridge: keep the bot process alive')
|
|
834
|
+
|
|
835
|
+
// Serve the loopback port for as long as this plugin entry stays loaded.
|
|
836
|
+
ctx.effect(() => {
|
|
837
|
+
// 提问通道默认关闭:DSH 的 user-questions/request 是瀑布事件,
|
|
838
|
+
// 处理不当会让宿主 abort 并崩溃(crash-…-host.log)。稳定性验证通过后再打开。
|
|
839
|
+
if (config.questionChannel === false) return () => {}
|
|
840
|
+
const dispose = installQuestionChannel()
|
|
841
|
+
return () => { try { dispose() } catch (error) { /* already gone */ } }
|
|
842
|
+
}, 'dsh-qq-bridge: question channel')
|
|
843
|
+
|
|
844
|
+
ctx.effect(() => {
|
|
845
|
+
void bridge.start()
|
|
846
|
+
.then(() => log(`listening on http://${config.host}:${bridge.port} (cwd: ${config.cwd})`))
|
|
847
|
+
.catch(error => log(`listen failed: ${error instanceof Error ? error.message : String(error)}`))
|
|
848
|
+
return () => { void bridge.stop() }
|
|
849
|
+
}, 'dsh-qq-bridge: local http bridge')
|
|
850
|
+
|
|
851
|
+
// Live token stream: the official plugin listens to the transient
|
|
852
|
+
// 'agent/assistant-stream' event and reads frame.chunk.text, so do the same
|
|
853
|
+
// instead of sessionController.follow() (which only yields step snapshots).
|
|
854
|
+
const streams = new Map() // sessionId -> convKey
|
|
855
|
+
const agentSessions = new Map() // agentId -> sessionId
|
|
856
|
+
|
|
857
|
+
const startStream = (sessionId, convKey) => {
|
|
858
|
+
if (config.streamEnabled !== true) return
|
|
859
|
+
streams.set(sessionId, convKey)
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
const stopStream = (sessionId) => {
|
|
863
|
+
streams.delete(sessionId)
|
|
864
|
+
for (const [agentId, mapped] of agentSessions) {
|
|
865
|
+
if (mapped === sessionId) agentSessions.delete(agentId)
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
ctx.on('agent/assistant-stream', (payload) => {
|
|
870
|
+
if (config.streamEnabled !== true || streams.size === 0) return
|
|
871
|
+
const agentId = payload?.agent?.id
|
|
872
|
+
const frame = payload?.frame
|
|
873
|
+
if (typeof agentId !== 'string' || agentId === '' || frame == null) return
|
|
874
|
+
|
|
875
|
+
let sessionId = agentSessions.get(agentId)
|
|
876
|
+
if (sessionId === undefined) {
|
|
877
|
+
const newest = [...streams.keys()].pop()
|
|
878
|
+
if (newest === undefined) return
|
|
879
|
+
agentSessions.set(agentId, newest)
|
|
880
|
+
sessionId = newest
|
|
881
|
+
}
|
|
882
|
+
const convKey = streams.get(sessionId)
|
|
883
|
+
if (convKey === undefined) return
|
|
884
|
+
if (frame.type !== 'chunk') return
|
|
885
|
+
const chunk = frame.chunk
|
|
886
|
+
if (chunk?.type !== 'text-delta' || typeof chunk.text !== 'string' || chunk.text === '') return
|
|
887
|
+
bridge.push({
|
|
888
|
+
type: 'stream',
|
|
889
|
+
convKey,
|
|
890
|
+
turnId: turns.get(sessionId)?.turnId ?? '',
|
|
891
|
+
text: chunk.text,
|
|
892
|
+
final: false,
|
|
893
|
+
})
|
|
894
|
+
})
|
|
895
|
+
|
|
896
|
+
// Independent judge sessions (Plan B): one per conversation, no shared history.
|
|
897
|
+
const judgeTexts = new Map() // sessionId -> collected assistant text
|
|
898
|
+
const judgeWaiters = new Map() // sessionId -> resolve(text)
|
|
899
|
+
const judgeSessions = new Map() // convKey -> sessionId
|
|
900
|
+
|
|
901
|
+
// Capture each finished turn so the bot can answer the QQ message.
|
|
902
|
+
ctx.on('session/event', (session, event) => {
|
|
903
|
+
const sessionId = String(session?.id ?? '')
|
|
904
|
+
if (sessionId === '') return
|
|
905
|
+
const convKey = store.convOf(sessionId)
|
|
906
|
+
if (convKey === undefined) return
|
|
907
|
+
const data = event?.data ?? {}
|
|
908
|
+
if (judgeTexts.has(sessionId)) {
|
|
909
|
+
if (event.type === 'assistant/message') {
|
|
910
|
+
const t = textOf(data.message)
|
|
911
|
+
if (t.trim() !== '') judgeTexts.get(sessionId).push(t)
|
|
912
|
+
}
|
|
913
|
+
if (event.type === 'turn/end') {
|
|
914
|
+
const done = judgeWaiters.get(sessionId)
|
|
915
|
+
if (done !== undefined) {
|
|
916
|
+
judgeWaiters.delete(sessionId)
|
|
917
|
+
done(judgeTexts.get(sessionId).join('\n').trim())
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
return
|
|
921
|
+
}
|
|
922
|
+
if (event.type === 'turn/start') {
|
|
923
|
+
turns.set(sessionId, { texts: [], tools: [], turnId: `${Date.now().toString(36)}-${sessionId.slice(-6)}` })
|
|
924
|
+
startStream(sessionId, convKey)
|
|
925
|
+
return
|
|
926
|
+
}
|
|
927
|
+
if (event.type === 'assistant/message') {
|
|
928
|
+
const state = turns.get(sessionId)
|
|
929
|
+
if (state === undefined) return
|
|
930
|
+
const text = textOf(data.message)
|
|
931
|
+
if (text.trim() !== '') state.texts.push(text)
|
|
932
|
+
return
|
|
933
|
+
}
|
|
934
|
+
if (event.type === 'tool/call') {
|
|
935
|
+
const state = turns.get(sessionId)
|
|
936
|
+
if (state === undefined) return
|
|
937
|
+
if (typeof data.name === 'string') state.tools.push(data.name)
|
|
938
|
+
if (typeof data.callId === 'string') {
|
|
939
|
+
callArguments.set(`${sessionId}:${data.callId}`, preview(data.arguments, config.argumentPreviewChars))
|
|
940
|
+
if (callArguments.size > 200) callArguments.delete(callArguments.keys().next().value)
|
|
941
|
+
}
|
|
942
|
+
return
|
|
943
|
+
}
|
|
944
|
+
if (event.type === 'turn/end') {
|
|
945
|
+
const state = turns.get(sessionId) ?? { texts: [], tools: [] }
|
|
946
|
+
turns.delete(sessionId)
|
|
947
|
+
stopStream(sessionId)
|
|
948
|
+
bridge.push({ type: 'stream', convKey, turnId: state.turnId ?? '', text: state.texts.join('\n\n').trim(), final: true })
|
|
949
|
+
// data.reason is an object on this host generation; never ship "[object Object]"
|
|
950
|
+
const rawReason = data.reason
|
|
951
|
+
const reason = typeof rawReason === 'string'
|
|
952
|
+
? rawReason
|
|
953
|
+
: (rawReason && typeof rawReason === 'object' ? String(rawReason.kind ?? rawReason.type ?? '') : '')
|
|
954
|
+
bridge.push({
|
|
955
|
+
type: 'reply',
|
|
956
|
+
convKey,
|
|
957
|
+
turnId: state.turnId ?? '',
|
|
958
|
+
text: state.texts.join('\n\n').trim(),
|
|
959
|
+
tools: state.tools,
|
|
960
|
+
reason,
|
|
961
|
+
})
|
|
962
|
+
}
|
|
963
|
+
})
|
|
964
|
+
|
|
965
|
+
// Route approvals of bridged Sessions to their owner FIRST: the Web GUI also
|
|
966
|
+
// answers approvals, and only a prepended listener wins that waterfall.
|
|
967
|
+
// Sessions this plugin does not own fall through with next().
|
|
968
|
+
ctx.on('approval/request', async (request, next) => {
|
|
969
|
+
const sessionId = String(request?.agent?.session?.id ?? '')
|
|
970
|
+
const convKey = sessionId === '' ? undefined : store.convOf(sessionId)
|
|
971
|
+
if (convKey === undefined) return next()
|
|
972
|
+
if (!botIsListening()) {
|
|
973
|
+
// Nobody is polling the bridge: never swallow the approval, let the GUI ask.
|
|
974
|
+
log(`approval for ${convKey} handed to the GUI (bot not polling)`)
|
|
975
|
+
return next()
|
|
976
|
+
}
|
|
977
|
+
const approvalTarget = store.approvalTargetOf(convKey) ?? convKey
|
|
978
|
+
const callId = typeof request?.callId === 'string' ? request.callId : ''
|
|
979
|
+
try {
|
|
980
|
+
return await requestDecision({
|
|
981
|
+
approvalId: randomUUID(),
|
|
982
|
+
convKey,
|
|
983
|
+
approvalTarget,
|
|
984
|
+
toolName: String(request?.toolName ?? 'unknown'),
|
|
985
|
+
reason: String(request?.reason ?? ''),
|
|
986
|
+
argumentPreview: callId === '' ? '' : (callArguments.get(`${sessionId}:${callId}`) ?? ''),
|
|
987
|
+
signal: request?.signal,
|
|
988
|
+
})
|
|
989
|
+
} catch (error) {
|
|
990
|
+
log(`approval relay failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
991
|
+
return 'rejected'
|
|
992
|
+
}
|
|
993
|
+
}, { prepend: true })
|
|
994
|
+
|
|
995
|
+
// The Session service may arrive after this entry; wait for it instead of
|
|
996
|
+
// failing the whole profile boot when it is absent.
|
|
997
|
+
// Model-facing retrieval over the timestamped history buffer.
|
|
998
|
+
ctx.inject(['tools'], (scope) => {
|
|
999
|
+
const tools = scope.tools ?? (typeof scope.get === 'function' ? scope.get('tools') : undefined)
|
|
1000
|
+
if (tools === undefined || typeof tools.register !== 'function') {
|
|
1001
|
+
log('qq_history tool unavailable (tools service missing)')
|
|
1002
|
+
return
|
|
1003
|
+
}
|
|
1004
|
+
const definition = {
|
|
1005
|
+
name: 'qq_history',
|
|
1006
|
+
description:
|
|
1007
|
+
'搜索 QQ 群聊/私聊最近的历史消息(每行带 [HH:MM] 时间戳)。' +
|
|
1008
|
+
'当对方提到你没见过的内容、或需要确认「谁在什么时候说过什么」时调用。',
|
|
1009
|
+
parameters: {
|
|
1010
|
+
type: 'object',
|
|
1011
|
+
additionalProperties: false,
|
|
1012
|
+
properties: {
|
|
1013
|
+
convKey: { type: 'string', description: '会话键,如 group:XXXX 或 c2c:XXXX;留空表示所有会话' },
|
|
1014
|
+
query: { type: 'string', description: '关键词,留空返回最近若干条' },
|
|
1015
|
+
limit: { type: 'number', description: '返回条数上限,默认 30,最大 100' },
|
|
1016
|
+
},
|
|
1017
|
+
},
|
|
1018
|
+
output: {
|
|
1019
|
+
schema: { type: 'object' },
|
|
1020
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
|
|
1021
|
+
},
|
|
1022
|
+
async execute(args) {
|
|
1023
|
+
const limit = Math.max(1, Math.min(Number(args?.limit ?? 30) || 30, 100))
|
|
1024
|
+
const needle = typeof args?.query === 'string' ? args.query.trim() : ''
|
|
1025
|
+
const convFilter = typeof args?.convKey === 'string' ? args.convKey.trim() : ''
|
|
1026
|
+
const keys = convFilter !== '' ? [convFilter] : [...history.keys()]
|
|
1027
|
+
const lines = []
|
|
1028
|
+
for (const key of keys) {
|
|
1029
|
+
for (const line of history.get(key) ?? []) {
|
|
1030
|
+
if (needle === '' || line.includes(needle)) lines.push(`${key} ${line}`)
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
return { ok: true, count: lines.slice(-limit).length, lines: lines.slice(-limit) }
|
|
1034
|
+
},
|
|
1035
|
+
}
|
|
1036
|
+
try {
|
|
1037
|
+
tools.register(definition)
|
|
1038
|
+
log('qq_history tool registered')
|
|
1039
|
+
} catch (error) {
|
|
1040
|
+
log(`qq_history registration failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
// ── 群管理工具(禁言 / 踢人 / 成员索引) ──
|
|
1044
|
+
const adminCall = async (payload) => {
|
|
1045
|
+
const port = Number(config.panelPort) || 39062
|
|
1046
|
+
const response = await fetch(`http://127.0.0.1:${port}/api/admin`, {
|
|
1047
|
+
method: 'POST',
|
|
1048
|
+
headers: { 'content-type': 'application/json' },
|
|
1049
|
+
body: JSON.stringify(payload),
|
|
1050
|
+
})
|
|
1051
|
+
return await response.json().catch(() => ({}))
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
const readMembers = () => {
|
|
1055
|
+
try {
|
|
1056
|
+
const file = join(String(config.botDir || "."), "state", "members.json")
|
|
1057
|
+
const raw = readFileSync(file, "utf8")
|
|
1058
|
+
return JSON.parse(raw)
|
|
1059
|
+
} catch (error) {
|
|
1060
|
+
return {}
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
const resolveMember = (convKey, member) => {
|
|
1065
|
+
const known = readMembers()[convKey] || {}
|
|
1066
|
+
const raw = String(member || "").trim().replace(/^@/, "").replace(/^群友/i, "").toUpperCase()
|
|
1067
|
+
if (raw === "") return undefined
|
|
1068
|
+
for (const [tail, info] of Object.entries(known)) {
|
|
1069
|
+
if (tail.toUpperCase() === raw) return info?.openid ?? info
|
|
1070
|
+
}
|
|
1071
|
+
for (const [tail, info] of Object.entries(known)) {
|
|
1072
|
+
if (raw.length >= 4 && tail.toUpperCase().includes(raw)) return info?.openid ?? info
|
|
1073
|
+
}
|
|
1074
|
+
// 按昵称找人:群里 @ 出来的名字或自己记得的名字都能用
|
|
1075
|
+
const wanted = String(member || "").trim().replace(/^@/, "").replace(/^群友/i, "")
|
|
1076
|
+
if (wanted) {
|
|
1077
|
+
for (const [tail, info] of Object.entries(known)) {
|
|
1078
|
+
const name = String((info && typeof info === "object" && info.name) || "").trim()
|
|
1079
|
+
if (name && name.toLowerCase() === wanted.toLowerCase()) return info?.openid ?? info
|
|
1080
|
+
}
|
|
1081
|
+
for (const [tail, info] of Object.entries(known)) {
|
|
1082
|
+
const name = String((info && typeof info === "object" && info.name) || "").trim()
|
|
1083
|
+
if (name && wanted.length >= 2 && name.toLowerCase().includes(wanted.toLowerCase())) return info?.openid ?? info
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
if (/^[0-9A-F]{32}$/.test(raw)) return raw
|
|
1087
|
+
return undefined
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
const adminTools = [
|
|
1091
|
+
{
|
|
1092
|
+
name: "qq_members",
|
|
1093
|
+
description: "列出本群/本会话里发过言的成员(短号 → openid)。禁言/踢人前先查这个拿短号。",
|
|
1094
|
+
parameters: { type: "object", additionalProperties: false, properties: { convKey: { type: "string", description: "会话键,如 group:XXXX" } } },
|
|
1095
|
+
async execute(args) {
|
|
1096
|
+
const convKey = String(args?.convKey || "")
|
|
1097
|
+
const all = readMembers()
|
|
1098
|
+
const people = convKey !== "" ? { [convKey]: all[convKey] || {} } : all
|
|
1099
|
+
const lines = []
|
|
1100
|
+
for (const [key, members] of Object.entries(people)) {
|
|
1101
|
+
for (const [tail, info] of Object.entries(members || {})) {
|
|
1102
|
+
lines.push({
|
|
1103
|
+
convKey: key,
|
|
1104
|
+
tail,
|
|
1105
|
+
name: (info && typeof info === "object" && info.name) || "",
|
|
1106
|
+
openid: (info && typeof info === "object" ? info.openid : info) || "",
|
|
1107
|
+
avatar: (info && typeof info === "object" && info.avatar) || "",
|
|
1108
|
+
})
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
return { ok: true, count: lines.length, members: lines }
|
|
1112
|
+
},
|
|
1113
|
+
},
|
|
1114
|
+
{
|
|
1115
|
+
name: "qq_mute",
|
|
1116
|
+
description: "禁言群里某个成员(需要机器人是群管理员且有接口权限)。member 可以是短号(如 1B6CBB)或 @群友XXXX。",
|
|
1117
|
+
parameters: {
|
|
1118
|
+
type: "object", additionalProperties: false,
|
|
1119
|
+
required: ["convKey", "member", "minutes"],
|
|
1120
|
+
properties: {
|
|
1121
|
+
convKey: { type: "string", description: "会话键,如 group:XXXX" },
|
|
1122
|
+
member: { type: "string", description: "被禁言的成员:短号或 @群友XXXX" },
|
|
1123
|
+
minutes: { type: "number", description: "禁言分钟数(720=12 小时);传 0 表示解除禁言" },
|
|
1124
|
+
},
|
|
1125
|
+
},
|
|
1126
|
+
async execute(args) {
|
|
1127
|
+
const convKey = String(args?.convKey || "")
|
|
1128
|
+
const openid = resolveMember(convKey, args?.member)
|
|
1129
|
+
if (openid === undefined) return { ok: false, error: "找不到这个成员,先调用 qq_members 看短号" }
|
|
1130
|
+
const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
|
|
1131
|
+
// minutes <= 0 表示解除禁言(op=del);注意不能用 `|| 10`,否则 0 会被吞成 10
|
|
1132
|
+
const raw = Number(args?.minutes)
|
|
1133
|
+
const minutes = Number.isFinite(raw) ? raw : 10
|
|
1134
|
+
const seconds = minutes <= 0 ? 0 : Math.min(Math.round(minutes * 60), 60 * 60 * 24 * 30)
|
|
1135
|
+
const result = await adminCall({ action: "mute", convKey, group, member: openid, seconds })
|
|
1136
|
+
return {
|
|
1137
|
+
ok: result.ok === true,
|
|
1138
|
+
member: args?.member,
|
|
1139
|
+
op: seconds > 0 ? "add" : "del",
|
|
1140
|
+
minutes: seconds / 60,
|
|
1141
|
+
error: result.error,
|
|
1142
|
+
}
|
|
1143
|
+
},
|
|
1144
|
+
},
|
|
1145
|
+
{
|
|
1146
|
+
name: "qq_unmute",
|
|
1147
|
+
description: "解除某个成员的禁言(等价 op=del)。语义独立,避免把 0 分钟误当禁言时长。",
|
|
1148
|
+
parameters: {
|
|
1149
|
+
type: "object", additionalProperties: false,
|
|
1150
|
+
required: ["convKey", "member"],
|
|
1151
|
+
properties: {
|
|
1152
|
+
convKey: { type: "string", description: "会话键,如 group:XXXX" },
|
|
1153
|
+
member: { type: "string", description: "成员:短号或 @群友XXXX" },
|
|
1154
|
+
},
|
|
1155
|
+
},
|
|
1156
|
+
async execute(args) {
|
|
1157
|
+
const convKey = String(args?.convKey || "")
|
|
1158
|
+
const openid = resolveMember(convKey, args?.member)
|
|
1159
|
+
if (openid === undefined) return { ok: false, error: "找不到这个成员,先调用 qq_members 看短号" }
|
|
1160
|
+
const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
|
|
1161
|
+
const result = await adminCall({ action: "mute", convKey, group, member: openid, seconds: 0 })
|
|
1162
|
+
return { ok: result.ok === true, member: args?.member, op: "del", error: result.error }
|
|
1163
|
+
},
|
|
1164
|
+
},
|
|
1165
|
+
{
|
|
1166
|
+
name: "qq_mute_state",
|
|
1167
|
+
description: "查询本群当前的禁言设置(平台原样返回),用于确认禁言/解禁是否真的生效。",
|
|
1168
|
+
parameters: {
|
|
1169
|
+
type: "object", additionalProperties: false,
|
|
1170
|
+
required: ["convKey"],
|
|
1171
|
+
properties: { convKey: { type: "string", description: "会话键,如 group:XXXX" } },
|
|
1172
|
+
},
|
|
1173
|
+
async execute(args) {
|
|
1174
|
+
const convKey = String(args?.convKey || "")
|
|
1175
|
+
const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
|
|
1176
|
+
const result = await adminCall({ action: "mute_state", convKey, group })
|
|
1177
|
+
return { ok: result.ok === true, state: result.state, error: result.error }
|
|
1178
|
+
},
|
|
1179
|
+
},
|
|
1180
|
+
{
|
|
1181
|
+
name: "qq_kick",
|
|
1182
|
+
description: "把某个成员移出群(需要机器人是群管理员且有接口权限)。member 可以是短号或 @群友XXXX。",
|
|
1183
|
+
parameters: {
|
|
1184
|
+
type: "object", additionalProperties: false,
|
|
1185
|
+
required: ["convKey", "member"],
|
|
1186
|
+
properties: {
|
|
1187
|
+
convKey: { type: "string", description: "会话键,如 group:XXXX" },
|
|
1188
|
+
member: { type: "string", description: "被移出的成员:短号或 @群友XXXX" },
|
|
1189
|
+
blacklist: { type: "boolean", description: "是否同时拉黑,默认否" },
|
|
1190
|
+
},
|
|
1191
|
+
},
|
|
1192
|
+
async execute(args) {
|
|
1193
|
+
const convKey = String(args?.convKey || "")
|
|
1194
|
+
const openid = resolveMember(convKey, args?.member)
|
|
1195
|
+
if (openid === undefined) return { ok: false, error: "找不到这个成员,先调用 qq_members 看短号" }
|
|
1196
|
+
const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
|
|
1197
|
+
const result = await adminCall({ action: "kick", convKey, group, member: openid, blacklist: args?.blacklist === true })
|
|
1198
|
+
if (result.pending === true) {
|
|
1199
|
+
// 还没执行:明确告诉模型"等待确认",不要说已经踢了
|
|
1200
|
+
return {
|
|
1201
|
+
ok: false,
|
|
1202
|
+
pending: true,
|
|
1203
|
+
member: args?.member,
|
|
1204
|
+
error: null,
|
|
1205
|
+
hint: result.hint || "已发送私聊二次确认,等主人点头后才执行;现在还没有踢人",
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
return { ok: result.ok === true, member: args?.member, error: result.error }
|
|
1209
|
+
},
|
|
1210
|
+
},
|
|
1211
|
+
]
|
|
1212
|
+
|
|
1213
|
+
const infoTools = [
|
|
1214
|
+
{
|
|
1215
|
+
name: "qq_group",
|
|
1216
|
+
description: "查看当前群资料:群名、群简介、分类、标签、成员数,以及全群禁言规则。",
|
|
1217
|
+
parameters: { type: "object", properties: { convKey: { type: "string", description: "会话键,如 group:XXXX" } } },
|
|
1218
|
+
async execute(args) {
|
|
1219
|
+
const convKey = String(args?.convKey || "")
|
|
1220
|
+
const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
|
|
1221
|
+
const result = await adminCall({ action: "group", convKey, group })
|
|
1222
|
+
return { ok: result.ok === true, group: result.group, mute_rule: result.mute_rule, known_members: result.known_members, error: result.error }
|
|
1223
|
+
},
|
|
1224
|
+
},
|
|
1225
|
+
{
|
|
1226
|
+
name: "qq_muted",
|
|
1227
|
+
description: "列出本群当前被禁言的成员(名字、openid、短号、到期时间)。",
|
|
1228
|
+
parameters: { type: "object", properties: { convKey: { type: "string", description: "会话键,如 group:XXXX" } } },
|
|
1229
|
+
async execute(args) {
|
|
1230
|
+
const convKey = String(args?.convKey || "")
|
|
1231
|
+
const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
|
|
1232
|
+
const result = await adminCall({ action: "muted", convKey, group })
|
|
1233
|
+
return { ok: result.ok === true, count: result.count || 0, muted: result.muted || [], error: result.error }
|
|
1234
|
+
},
|
|
1235
|
+
},
|
|
1236
|
+
{
|
|
1237
|
+
name: "qq_member",
|
|
1238
|
+
description: "查看某个群成员的资料:昵称、头像地址、openid、短号、最后发言时间、是否被禁言。member 可传短号/昵称/openid。",
|
|
1239
|
+
parameters: {
|
|
1240
|
+
type: "object",
|
|
1241
|
+
properties: {
|
|
1242
|
+
convKey: { type: "string", description: "会话键,如 group:XXXX" },
|
|
1243
|
+
member: { type: "string", description: "短号、昵称或 openid" },
|
|
1244
|
+
},
|
|
1245
|
+
},
|
|
1246
|
+
async execute(args) {
|
|
1247
|
+
const convKey = String(args?.convKey || "")
|
|
1248
|
+
const openid = resolveMember(convKey, args?.member)
|
|
1249
|
+
if (openid === undefined) return { ok: false, error: "找不到这个成员,先调用 qq_members 看短号" }
|
|
1250
|
+
const group = convKey.startsWith("group:") ? convKey.slice(6) : convKey
|
|
1251
|
+
const result = await adminCall({ action: "member", convKey, group, member: openid })
|
|
1252
|
+
return { ok: result.ok === true, member: result.member, error: result.error }
|
|
1253
|
+
},
|
|
1254
|
+
},
|
|
1255
|
+
{
|
|
1256
|
+
name: "qq_stats",
|
|
1257
|
+
description: "查看机器人统计:私聊/群聊消息数、插话判断与开口次数、流式次数、文件发送、审批、提问、禁言踢人次数、最近事件。",
|
|
1258
|
+
parameters: { type: "object", properties: {} },
|
|
1259
|
+
async execute() {
|
|
1260
|
+
const result = await adminCall({ action: "stats" })
|
|
1261
|
+
return { ok: result.ok === true, counters: result.counters, events: result.events, error: result.error }
|
|
1262
|
+
},
|
|
1263
|
+
},
|
|
1264
|
+
]
|
|
1265
|
+
|
|
1266
|
+
// DSH 拒收非无损 JSON(undefined / NaN / Infinity),工具返回值先过一遍
|
|
1267
|
+
const jsonSafe = (value) => {
|
|
1268
|
+
if (value === null) return null
|
|
1269
|
+
const kind = typeof value
|
|
1270
|
+
if (kind === "undefined" || kind === "function" || kind === "symbol") return undefined
|
|
1271
|
+
if (kind === "number") return Number.isFinite(value) ? value : null
|
|
1272
|
+
if (kind === "bigint") return String(value)
|
|
1273
|
+
if (kind !== "object") return value
|
|
1274
|
+
if (Array.isArray(value)) return value.map((item) => {
|
|
1275
|
+
const clean = jsonSafe(item)
|
|
1276
|
+
return clean === undefined ? null : clean
|
|
1277
|
+
})
|
|
1278
|
+
const out = {}
|
|
1279
|
+
for (const [key, item] of Object.entries(value)) {
|
|
1280
|
+
const clean = jsonSafe(item)
|
|
1281
|
+
if (clean !== undefined) out[key] = clean
|
|
1282
|
+
}
|
|
1283
|
+
return out
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
for (const tool of [...infoTools, ...adminTools]) {
|
|
1287
|
+
try {
|
|
1288
|
+
tools.register({
|
|
1289
|
+
...tool,
|
|
1290
|
+
execute: async (...args) => jsonSafe(await tool.execute(...args)),
|
|
1291
|
+
output: { schema: { type: "object" }, render: (_a, value) => [{ type: "text", text: JSON.stringify(value) }] },
|
|
1292
|
+
})
|
|
1293
|
+
log(`${tool.name} tool registered`)
|
|
1294
|
+
} catch (error) {
|
|
1295
|
+
log(`${tool.name} registration failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
})
|
|
1299
|
+
|
|
1300
|
+
ctx.inject(['sessionController'], (sctx) => {
|
|
1301
|
+
host.sessionController = sctx.sessionController
|
|
1302
|
+
log('sessionController attached')
|
|
1303
|
+
})
|
|
1304
|
+
}
|