@wenbin_wb/dsh-bridge 2.8.7 → 2.9.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/CHANGELOG.md +295 -250
- package/README.en.md +408 -572
- package/README.md +430 -570
- package/client/client.js +3844 -3764
- package/client/index.js +140 -876
- package/client/mobile-styles.js +802 -0
- package/docs/fix-plan-202608.md +108 -0
- package/lib/auth/login-template.js +381 -381
- package/lib/auth/manager.js +531 -469
- package/lib/bridge-rpc.js +436 -511
- package/lib/cloudflared-manager.mjs +361 -345
- package/lib/compat.js +129 -0
- package/lib/feishu/index.js +225 -222
- package/lib/feishu/node.js +433 -409
- package/lib/index.js +1765 -1804
- package/lib/platform/base.js +147 -156
- package/lib/platform/commands.js +221 -0
- package/lib/platform/conversation-bridge.js +816 -1570
- package/lib/platform/dsh-storage.js +117 -0
- package/lib/platform/index.js +10 -10
- package/lib/platform/message-split.js +191 -0
- package/lib/platform/session-catalog.js +372 -0
- package/lib/platform/stream-slices.js +21 -0
- package/lib/qq/index.js +312 -309
- package/lib/qq/node.js +532 -533
- package/lib/telegram/index.js +215 -212
- package/lib/telegram/node.js +348 -350
- package/lib/tunnel-client.mjs +39 -15
- package/lib/wechat/gateway.js +973 -960
- package/lib/wechat/index.js +244 -241
- package/lib/wechat/media.js +285 -281
- package/lib/wechat/node.js +352 -350
- package/package.json +106 -102
|
@@ -1,1570 +1,816 @@
|
|
|
1
|
-
// dsh-bridge
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// -
|
|
6
|
-
// -
|
|
7
|
-
// -
|
|
8
|
-
// -
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
// -
|
|
13
|
-
// -
|
|
14
|
-
// -
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
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
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
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
|
-
|
|
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
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
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
|
-
|
|
342
|
-
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
//
|
|
346
|
-
//
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
async
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
if (
|
|
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
|
-
|
|
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
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
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
|
-
|
|
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
|
-
const
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
const
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
//
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
const
|
|
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
|
-
const timeoutMin = Math.max(1, Math.round(timeoutSec / 60))
|
|
818
|
-
const prompt = [
|
|
819
|
-
`## ⚠️ 操作权限确认 (#${number})`,
|
|
820
|
-
'',
|
|
821
|
-
'| 项目 | 详情 |',
|
|
822
|
-
'| :--- | :--- |',
|
|
823
|
-
`| **调用工具** | \`${req.toolName}\` |`,
|
|
824
|
-
...(req.reason ? [`| **申请原因** | ${String(req.reason).replace(/\|/g, '|')} |`] : []),
|
|
825
|
-
`| **等待超时** | ${timeoutMin} 分钟 (超时自动拒绝) |`,
|
|
826
|
-
'',
|
|
827
|
-
`> 回复 \`/yes\` (或 \`1\`) 批准执行`,
|
|
828
|
-
`> 回复 \`/no\` (或 \`2\`) 拒绝执行`,
|
|
829
|
-
].join('\n')
|
|
830
|
-
|
|
831
|
-
void this.sendText(prompt)
|
|
832
|
-
|
|
833
|
-
// 同时调用 downstream next(),使 Web UI 原生弹窗也能同步显示并支持直接操作
|
|
834
|
-
let nextPromise = null
|
|
835
|
-
if (typeof next === 'function') {
|
|
836
|
-
try {
|
|
837
|
-
const res = next()
|
|
838
|
-
if (res && typeof res.then === 'function') {
|
|
839
|
-
nextPromise = res
|
|
840
|
-
}
|
|
841
|
-
} catch {}
|
|
842
|
-
}
|
|
843
|
-
|
|
844
|
-
let timeoutFired = false
|
|
845
|
-
let winner = 'im'
|
|
846
|
-
const imPromise = new Promise((resolve) => {
|
|
847
|
-
const timer = setTimeout(() => {
|
|
848
|
-
timeoutFired = true
|
|
849
|
-
this.clearApproval(number)
|
|
850
|
-
resolve('rejected')
|
|
851
|
-
}, timeoutSec * 1000)
|
|
852
|
-
if (typeof timer.unref === 'function') timer.unref()
|
|
853
|
-
this.registerApproval(number, { number, request: req, resolve, timer })
|
|
854
|
-
})
|
|
855
|
-
|
|
856
|
-
const outcome = await (nextPromise
|
|
857
|
-
? Promise.race([
|
|
858
|
-
imPromise.then(res => { winner = 'im'; return res }),
|
|
859
|
-
nextPromise.then(res => { winner = 'web'; return res }),
|
|
860
|
-
])
|
|
861
|
-
: imPromise)
|
|
862
|
-
|
|
863
|
-
// 如果 Web 端先决议,清除 IM 端 pending 记录
|
|
864
|
-
if (winner === 'web') {
|
|
865
|
-
this.clearApproval(number)
|
|
866
|
-
}
|
|
867
|
-
|
|
868
|
-
// 仅在非超时路径发送确认消息(超时时 resolve 已经发生在 timer 回调)
|
|
869
|
-
if (!timeoutFired) {
|
|
870
|
-
const sourceHint = winner === 'web' ? '(Web 端操作)' : ''
|
|
871
|
-
const label = outcome === 'allowed-once' ? `✓ **已批准执行**${sourceHint}` : outcome === 'rejected' ? `❌ **已拒绝执行**${sourceHint}` : `**[${outcome}]**`
|
|
872
|
-
void this.sendText(`${label}(#${number})`)
|
|
873
|
-
}
|
|
874
|
-
return outcome
|
|
875
|
-
}
|
|
876
|
-
const disposer = this.ctx.on('approval/request', listener)
|
|
877
|
-
this.disposers.push(disposer)
|
|
878
|
-
}
|
|
879
|
-
}
|
|
880
|
-
|
|
881
|
-
// ---------------------------------------------------------------------------
|
|
882
|
-
// 辅助
|
|
883
|
-
// ---------------------------------------------------------------------------
|
|
884
|
-
|
|
885
|
-
function sessionLabel(session) {
|
|
886
|
-
for (const event of session.events ?? []) {
|
|
887
|
-
if (event.type === 'user/message') {
|
|
888
|
-
const blocks = event.data.content ?? []
|
|
889
|
-
const text = blocks
|
|
890
|
-
.filter((block) => block.type === 'text')
|
|
891
|
-
.map((block) => block.text ?? '')
|
|
892
|
-
.join(' ')
|
|
893
|
-
.trim()
|
|
894
|
-
if (text) return text.length > 28 ? `${text.slice(0, 28)}…` : text
|
|
895
|
-
}
|
|
896
|
-
}
|
|
897
|
-
return '新会话 (待输入)'
|
|
898
|
-
}
|
|
899
|
-
|
|
900
|
-
// 校验工作区路径(防止路径遍历攻击)
|
|
901
|
-
async function validateWorkspacePath(node, sel) {
|
|
902
|
-
const normalized = normalize(resolve(sel))
|
|
903
|
-
const workspaces = await listWorkspaces(node)
|
|
904
|
-
const allowedPaths = workspaces.map(w => normalize(resolve(w.path)))
|
|
905
|
-
|
|
906
|
-
if (!allowedPaths.includes(normalized)) {
|
|
907
|
-
const wsDisplay = allowedPaths.slice(0, 5).map((p, i) => `- \`[${i + 1}]\` \`${p}\``).join('\n')
|
|
908
|
-
const more = allowedPaths.length > 5 ? `\n- *…等共 ${allowedPaths.length} 个工作区*` : ''
|
|
909
|
-
return {
|
|
910
|
-
valid: false,
|
|
911
|
-
error: `❌ **路径不在已注册工作区列表中**:\`${normalized}\`\n\n**可用工作区:**\n${wsDisplay}${more}\n\n> 提示:发送 \`/workspaces\` 查看完整列表`
|
|
912
|
-
}
|
|
913
|
-
}
|
|
914
|
-
|
|
915
|
-
// 校验目录存在
|
|
916
|
-
let ok = false
|
|
917
|
-
try { ok = statSync(normalized).isDirectory() } catch { ok = false }
|
|
918
|
-
if (!ok) {
|
|
919
|
-
return {
|
|
920
|
-
valid: false,
|
|
921
|
-
error: `❌ **工作区目录不存在**:\`${normalized}\``
|
|
922
|
-
}
|
|
923
|
-
}
|
|
924
|
-
|
|
925
|
-
return { valid: true, path: normalized }
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
// 从事件日志折叠会话标题(本地实现,等价 DSH foldSessionTitle):优先取最后的
|
|
929
|
-
// session/title 事件(DSH 生成的会话名),否则回退到第一条用户消息文本。
|
|
930
|
-
function foldTitle(events) {
|
|
931
|
-
const evts = events ?? []
|
|
932
|
-
for (let i = evts.length - 1; i >= 0; i--) {
|
|
933
|
-
const e = evts[i]
|
|
934
|
-
if (e && e.type === 'session/title' && e.data?.title) return String(e.data.title)
|
|
935
|
-
}
|
|
936
|
-
return null
|
|
937
|
-
}
|
|
938
|
-
|
|
939
|
-
/** 获取所有已归档会话 ID 集合(支持 ctx.workspaceRegistry 内存服务 + workspace.json 文件存储双重兜底) */
|
|
940
|
-
function getArchivedSessionIds(ctx) {
|
|
941
|
-
const archived = new Set()
|
|
942
|
-
// 1. 尝试从 ctx.workspaceRegistry 内存服务读取
|
|
943
|
-
try {
|
|
944
|
-
const list = ctx?.workspaceRegistry?.archivedSessionIds
|
|
945
|
-
if (Array.isArray(list)) {
|
|
946
|
-
for (const id of list) {
|
|
947
|
-
if (id) archived.add(String(id))
|
|
948
|
-
}
|
|
949
|
-
return archived
|
|
950
|
-
}
|
|
951
|
-
} catch { /* ignore */ }
|
|
952
|
-
|
|
953
|
-
// 2. 尝试从 DSH workspace 存储文件($DSH_HOME/storages/workspace.json)读取兜底
|
|
954
|
-
if (!ctx?._mock) {
|
|
955
|
-
try {
|
|
956
|
-
const home = process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
957
|
-
const wsFile = join(home, 'storages', 'workspace.json')
|
|
958
|
-
if (existsSync(wsFile)) {
|
|
959
|
-
const data = JSON.parse(readFileSync(wsFile, 'utf8'))
|
|
960
|
-
const fileArchived = data?.global?.archivedSessionIds
|
|
961
|
-
if (Array.isArray(fileArchived)) {
|
|
962
|
-
for (const id of fileArchived) {
|
|
963
|
-
if (id) archived.add(String(id))
|
|
964
|
-
}
|
|
965
|
-
}
|
|
966
|
-
}
|
|
967
|
-
} catch { /* ignore */ }
|
|
968
|
-
}
|
|
969
|
-
|
|
970
|
-
return archived
|
|
971
|
-
}
|
|
972
|
-
|
|
973
|
-
/** 读取 DSH 官方持久化会话缓存元数据(标题、是否空白、创建时间等) */
|
|
974
|
-
function getSessionProjCache(ctx) {
|
|
975
|
-
if (ctx?._mock) return {}
|
|
976
|
-
try {
|
|
977
|
-
const home = process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
978
|
-
const cacheFile = join(home, 'storages', 'session_projcache.json')
|
|
979
|
-
if (existsSync(cacheFile)) {
|
|
980
|
-
const data = JSON.parse(readFileSync(cacheFile, 'utf8'))
|
|
981
|
-
return data?.tables?.sessions || {}
|
|
982
|
-
}
|
|
983
|
-
} catch { /* ignore */ }
|
|
984
|
-
return {}
|
|
985
|
-
}
|
|
986
|
-
|
|
987
|
-
/** 读取 DSH 官方注册的工作区列表及各自绑定的 sessionIds 列表 */
|
|
988
|
-
async function getRegisteredWorkspaces(ctx) {
|
|
989
|
-
const workspaces = []
|
|
990
|
-
|
|
991
|
-
// 优先从内存服务获取
|
|
992
|
-
if (ctx?.workspaceRegistry) {
|
|
993
|
-
try {
|
|
994
|
-
const list = await ctx.workspaceRegistry.list?.()
|
|
995
|
-
if (Array.isArray(list)) {
|
|
996
|
-
for (const w of list) {
|
|
997
|
-
if (w && w.path) {
|
|
998
|
-
workspaces.push({
|
|
999
|
-
id: w.id || w.path,
|
|
1000
|
-
path: w.path,
|
|
1001
|
-
title: w.title || basename(w.path),
|
|
1002
|
-
sessionIds: Array.isArray(w.sessionIds) ? [...w.sessionIds] : [],
|
|
1003
|
-
})
|
|
1004
|
-
}
|
|
1005
|
-
}
|
|
1006
|
-
return workspaces
|
|
1007
|
-
}
|
|
1008
|
-
} catch { /* ignore */ }
|
|
1009
|
-
}
|
|
1010
|
-
|
|
1011
|
-
// 兜底从 workspace.json 存储文件读取
|
|
1012
|
-
if (!ctx?._mock) {
|
|
1013
|
-
try {
|
|
1014
|
-
const home = process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
1015
|
-
const wsFile = join(home, 'storages', 'workspace.json')
|
|
1016
|
-
if (existsSync(wsFile)) {
|
|
1017
|
-
const data = JSON.parse(readFileSync(wsFile, 'utf8'))
|
|
1018
|
-
const wsIds = data?.global?.workspaceIds || Object.keys(data?.tables?.workspaces || {})
|
|
1019
|
-
const table = data?.tables?.workspaces || {}
|
|
1020
|
-
for (const wId of wsIds) {
|
|
1021
|
-
const ws = table[wId]
|
|
1022
|
-
if (ws && ws.path) {
|
|
1023
|
-
workspaces.push({
|
|
1024
|
-
id: wId,
|
|
1025
|
-
path: ws.path,
|
|
1026
|
-
title: ws.title || basename(ws.path),
|
|
1027
|
-
sessionIds: Array.isArray(ws.sessionIds) ? [...ws.sessionIds] : [],
|
|
1028
|
-
})
|
|
1029
|
-
}
|
|
1030
|
-
}
|
|
1031
|
-
}
|
|
1032
|
-
} catch { /* ignore */ }
|
|
1033
|
-
}
|
|
1034
|
-
|
|
1035
|
-
return workspaces
|
|
1036
|
-
}
|
|
1037
|
-
|
|
1038
|
-
function isSubagentSession(cacheRow, liveSession) {
|
|
1039
|
-
if (liveSession?.origin === 'subagent' || liveSession?.header?.origin === 'subagent') return true
|
|
1040
|
-
const subVal = cacheRow?.rows?.subagent?.val
|
|
1041
|
-
if (subVal && typeof subVal === 'object' && Object.keys(subVal).length > 0) return true
|
|
1042
|
-
return false
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
function formatGoalTitle(raw) {
|
|
1046
|
-
if (typeof raw === 'string' && raw) return raw
|
|
1047
|
-
if (raw && typeof raw === 'object') {
|
|
1048
|
-
const obj = raw.objective ?? raw.goal?.objective ?? raw.title
|
|
1049
|
-
if (typeof obj === 'string' && obj) return obj
|
|
1050
|
-
}
|
|
1051
|
-
return ''
|
|
1052
|
-
}
|
|
1053
|
-
|
|
1054
|
-
// 列出会话:严格对齐 DSH Web 端侧边栏会话树逻辑。
|
|
1055
|
-
// 1. 过滤已归档会话 (archivedSessionIds)
|
|
1056
|
-
// 2. 过滤未发起提问的空白会话 (blank: true)
|
|
1057
|
-
// 3. 过滤子代理内部会话 (subagent origin)
|
|
1058
|
-
// 4. 严格按工作区账本 (workspace.sessionIds) 组织
|
|
1059
|
-
async function listSessions(node) {
|
|
1060
|
-
const archived = getArchivedSessionIds(node.ctx)
|
|
1061
|
-
const projCache = getSessionProjCache(node.ctx)
|
|
1062
|
-
const workspaces = await getRegisteredWorkspaces(node.ctx)
|
|
1063
|
-
|
|
1064
|
-
// 内存活跃会话(按 id 索引)
|
|
1065
|
-
const liveList = [...(node.ctx.sessions?.list?.() ?? [])].filter(
|
|
1066
|
-
(s) => s && s.id && !archived.has(s.id) && !s.archived && !s.header?.archived
|
|
1067
|
-
)
|
|
1068
|
-
const liveById = new Map(liveList.map((s) => [s.id, s]))
|
|
1069
|
-
|
|
1070
|
-
const accounted = new Set()
|
|
1071
|
-
const result = []
|
|
1072
|
-
|
|
1073
|
-
// 1. 如果存在已注册的工作区,严格按工作区及其 sessionIds 账本组织(与 Web 端完全一致)
|
|
1074
|
-
if (workspaces.length > 0) {
|
|
1075
|
-
for (const ws of workspaces) {
|
|
1076
|
-
const normWsPath = ws.path ? normalize(ws.path).toLowerCase() : ''
|
|
1077
|
-
|
|
1078
|
-
// 优先将当前工作区下新创建但在内存里的 live 会话追加到头部
|
|
1079
|
-
for (const s of liveList) {
|
|
1080
|
-
const sCwd = s.header?.cwd || s.cwd
|
|
1081
|
-
if (sCwd && normalize(sCwd).toLowerCase() === normWsPath && !accounted.has(s.id)) {
|
|
1082
|
-
if (isSubagentSession(projCache[s.id], s)) continue
|
|
1083
|
-
accounted.add(s.id)
|
|
1084
|
-
let title = s.title || (s.events ? foldTitle(s.events) : '')
|
|
1085
|
-
if (!title) {
|
|
1086
|
-
const cache = projCache[s.id]
|
|
1087
|
-
title = cache?.rows?.title?.val || formatGoalTitle(cache?.rows?.goal?.val)
|
|
1088
|
-
}
|
|
1089
|
-
result.push({
|
|
1090
|
-
id: s.id,
|
|
1091
|
-
createdAt: s.header?.createdAt || Date.now(),
|
|
1092
|
-
cwd: ws.path,
|
|
1093
|
-
workspaceTitle: ws.title,
|
|
1094
|
-
title: title || '新会话',
|
|
1095
|
-
events: s.events,
|
|
1096
|
-
seq: s.seq ?? 0,
|
|
1097
|
-
})
|
|
1098
|
-
}
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
// 按工作区账本存储的 sessionIds 顺序追加已记录会话
|
|
1102
|
-
for (const sId of ws.sessionIds) {
|
|
1103
|
-
if (archived.has(sId) || accounted.has(sId)) continue
|
|
1104
|
-
accounted.add(sId)
|
|
1105
|
-
|
|
1106
|
-
const cache = projCache[sId]
|
|
1107
|
-
const live = liveById.get(sId)
|
|
1108
|
-
// 过滤空白草稿会话(非当前活动会话)
|
|
1109
|
-
if (cache?.rows?.sessionListMetadata?.val?.blank === true && sId !== node.activeSessionId) {
|
|
1110
|
-
continue
|
|
1111
|
-
}
|
|
1112
|
-
// 过滤子代理内部会话
|
|
1113
|
-
if (isSubagentSession(cache, live)) {
|
|
1114
|
-
continue
|
|
1115
|
-
}
|
|
1116
|
-
|
|
1117
|
-
let title = cache?.rows?.title?.val || formatGoalTitle(cache?.rows?.goal?.val)
|
|
1118
|
-
let createdAt = cache?.identity?.createdAt || 0
|
|
1119
|
-
let cwd = ws.path
|
|
1120
|
-
|
|
1121
|
-
// 如果内存有该会话,提取最新数据
|
|
1122
|
-
if (live) {
|
|
1123
|
-
title = live.title || (live.events ? foldTitle(live.events) : '') || title
|
|
1124
|
-
createdAt = live.header?.createdAt || createdAt
|
|
1125
|
-
} else if (!title && node.ctx.sessionPersistence?.load) {
|
|
1126
|
-
try {
|
|
1127
|
-
const insp = await node.ctx.sessionPersistence.load(sId)
|
|
1128
|
-
title = foldTitle(insp.events ?? []) ?? undefined
|
|
1129
|
-
} catch {}
|
|
1130
|
-
}
|
|
1131
|
-
|
|
1132
|
-
result.push({
|
|
1133
|
-
id: sId,
|
|
1134
|
-
createdAt,
|
|
1135
|
-
cwd,
|
|
1136
|
-
workspaceTitle: ws.title,
|
|
1137
|
-
title: title || '新会话',
|
|
1138
|
-
events: live?.events,
|
|
1139
|
-
seq: live?.seq ?? 0,
|
|
1140
|
-
})
|
|
1141
|
-
}
|
|
1142
|
-
}
|
|
1143
|
-
|
|
1144
|
-
// 处理当前内存中处于活动状态但未绑定任何工作区的 live 会话
|
|
1145
|
-
for (const s of liveList) {
|
|
1146
|
-
if (accounted.has(s.id)) continue
|
|
1147
|
-
if (isSubagentSession(projCache[s.id], s)) continue
|
|
1148
|
-
accounted.add(s.id)
|
|
1149
|
-
const title = s.title || (s.events ? foldTitle(s.events) : '') || '未分组会话'
|
|
1150
|
-
result.push({
|
|
1151
|
-
id: s.id,
|
|
1152
|
-
createdAt: s.header?.createdAt || Date.now(),
|
|
1153
|
-
cwd: s.header?.cwd || '(未指定)',
|
|
1154
|
-
workspaceTitle: '未指定工作区',
|
|
1155
|
-
title,
|
|
1156
|
-
events: s.events,
|
|
1157
|
-
seq: s.seq ?? 0,
|
|
1158
|
-
})
|
|
1159
|
-
}
|
|
1160
|
-
} else {
|
|
1161
|
-
// 2. 如果系统未注册任何工作区(如单目录/无工作区模式),降级读取内存及持久化会话
|
|
1162
|
-
for (const s of liveList) {
|
|
1163
|
-
accounted.add(s.id)
|
|
1164
|
-
const title = s.title || (s.events ? foldTitle(s.events) : '') || '活跃会话'
|
|
1165
|
-
result.push({
|
|
1166
|
-
id: s.id,
|
|
1167
|
-
createdAt: s.header?.createdAt || Date.now(),
|
|
1168
|
-
cwd: s.header?.cwd || '(未指定)',
|
|
1169
|
-
workspaceTitle: '未指定工作区',
|
|
1170
|
-
title,
|
|
1171
|
-
events: s.events,
|
|
1172
|
-
seq: s.seq ?? 0,
|
|
1173
|
-
})
|
|
1174
|
-
}
|
|
1175
|
-
if (node.ctx.sessionPersistence?.list) {
|
|
1176
|
-
try {
|
|
1177
|
-
const headers = await node.ctx.sessionPersistence.list()
|
|
1178
|
-
if (Array.isArray(headers)) {
|
|
1179
|
-
const coldHeaders = headers.filter((h) => h && h.id && !accounted.has(h.id) && !archived.has(h.id) && !h.archived)
|
|
1180
|
-
for (const h of coldHeaders) {
|
|
1181
|
-
accounted.add(h.id)
|
|
1182
|
-
let title
|
|
1183
|
-
try {
|
|
1184
|
-
const insp = await node.ctx.sessionPersistence.load(h.id)
|
|
1185
|
-
title = foldTitle(insp.events ?? []) ?? undefined
|
|
1186
|
-
} catch {}
|
|
1187
|
-
result.push({
|
|
1188
|
-
id: h.id,
|
|
1189
|
-
createdAt: h.createdAt ?? 0,
|
|
1190
|
-
events: undefined,
|
|
1191
|
-
seq: 0,
|
|
1192
|
-
cwd: h.cwd || '(未指定)',
|
|
1193
|
-
workspaceTitle: '未指定工作区',
|
|
1194
|
-
title: title || '新会话',
|
|
1195
|
-
})
|
|
1196
|
-
}
|
|
1197
|
-
}
|
|
1198
|
-
} catch {}
|
|
1199
|
-
}
|
|
1200
|
-
}
|
|
1201
|
-
|
|
1202
|
-
return result
|
|
1203
|
-
}
|
|
1204
|
-
|
|
1205
|
-
// 列出可用工作区:使用 DSH 官方 workspaceRegistry。返回 [{title, path}]。
|
|
1206
|
-
async function listWorkspaces(node) {
|
|
1207
|
-
try {
|
|
1208
|
-
const list = await node.ctx.workspaceRegistry?.list?.() ?? []
|
|
1209
|
-
const out = []
|
|
1210
|
-
for (const ws of list) {
|
|
1211
|
-
if (ws && ws.path) out.push({ title: ws.title ?? ws.path, path: ws.path })
|
|
1212
|
-
}
|
|
1213
|
-
return out.sort((a, b) => String(a.path).localeCompare(String(b.path)))
|
|
1214
|
-
} catch {
|
|
1215
|
-
return []
|
|
1216
|
-
}
|
|
1217
|
-
}
|
|
1218
|
-
|
|
1219
|
-
function getWorkspaceBasename(cwd) {
|
|
1220
|
-
if (!cwd || cwd === '(未指定)') return '(未指定)'
|
|
1221
|
-
const norm = normalize(cwd).replace(/[\\/]+$/, '')
|
|
1222
|
-
const parts = norm.split(/[\\/]/)
|
|
1223
|
-
return parts[parts.length - 1] || cwd
|
|
1224
|
-
}
|
|
1225
|
-
|
|
1226
|
-
async function routeCommand(node, text) {
|
|
1227
|
-
const trimmed = text.trim()
|
|
1228
|
-
|
|
1229
|
-
if (trimmed === '/yes' || trimmed === '/no' || /^[12]$/.test(trimmed)) {
|
|
1230
|
-
if (node.resolveApproval(trimmed)) return true
|
|
1231
|
-
}
|
|
1232
|
-
|
|
1233
|
-
if (!trimmed.startsWith('/')) return false
|
|
1234
|
-
|
|
1235
|
-
const [command, ...rest] = trimmed.slice(1).split(/\s+/)
|
|
1236
|
-
switch (command) {
|
|
1237
|
-
case 'help':
|
|
1238
|
-
await node.sendText(helpText())
|
|
1239
|
-
return true
|
|
1240
|
-
case 'sessions':
|
|
1241
|
-
case 'list':
|
|
1242
|
-
await node.sendText(await renderSessions(node))
|
|
1243
|
-
return true
|
|
1244
|
-
case 'use':
|
|
1245
|
-
case 'resume': {
|
|
1246
|
-
const index = Number(rest[0])
|
|
1247
|
-
const sessions = sessionsInDisplayOrder(await listSessions(node))
|
|
1248
|
-
if (!Number.isInteger(index) || index < 1 || index > sessions.length) {
|
|
1249
|
-
await node.sendText(`❌ **无效会话编号**:\`${rest[0] ?? ''}\`\n\n> 可用编号范围:\`1 – ${sessions.length}\`(发送 \`/sessions\` 查看会话列表)`)
|
|
1250
|
-
return true
|
|
1251
|
-
}
|
|
1252
|
-
const session = sessions[index - 1]
|
|
1253
|
-
node.setActiveSessionById(session.id)
|
|
1254
|
-
const title = session.title || (session.events ? sessionLabel(session) : '')
|
|
1255
|
-
const titleLine = title ? `\n- **标题**:${title}` : ''
|
|
1256
|
-
await node.sendText(`✓ **已切换到会话 #${index}**${titleLine}\n- **会话 ID**:\`${fmtSessionId(session.id)}\``)
|
|
1257
|
-
return true
|
|
1258
|
-
}
|
|
1259
|
-
case 'rename': {
|
|
1260
|
-
if (!node.activeSessionId) {
|
|
1261
|
-
await node.sendText(`❌ **当前没有活动会话**\n\n> 请先使用 \`/sessions\` 查看会话列表并通过 \`/use 编号\` 切换到目标会话,或通过 \`/new <提示词>\` 创建新会话。`)
|
|
1262
|
-
return true
|
|
1263
|
-
}
|
|
1264
|
-
const newTitle = rest.join(' ').trim()
|
|
1265
|
-
if (!newTitle) {
|
|
1266
|
-
await node.sendText(`❌ **缺少新标题参数**\n\n> 用法:\`/rename <新标题>\`\n> 示例:\`/rename 优化登录交互逻辑\``)
|
|
1267
|
-
return true
|
|
1268
|
-
}
|
|
1269
|
-
|
|
1270
|
-
try {
|
|
1271
|
-
const session = node.activeSession()
|
|
1272
|
-
if (session) {
|
|
1273
|
-
session.title = newTitle
|
|
1274
|
-
}
|
|
1275
|
-
if (node.ctx.sessionPersistence?.update) {
|
|
1276
|
-
await node.ctx.sessionPersistence.update(node.activeSessionId, { title: newTitle }).catch(() => {})
|
|
1277
|
-
}
|
|
1278
|
-
await node.sendText(`✓ **会话重命名成功**\n- **会话 ID**:\`${fmtSessionId(node.activeSessionId)}\`\n- **新标题**:${newTitle}`)
|
|
1279
|
-
} catch (err) {
|
|
1280
|
-
await node.sendText(`❌ **重命名失败**:${err instanceof Error ? err.message : String(err)}`)
|
|
1281
|
-
}
|
|
1282
|
-
return true
|
|
1283
|
-
}
|
|
1284
|
-
case 'workspaces': {
|
|
1285
|
-
const workspaces = await listWorkspaces(node)
|
|
1286
|
-
if (workspaces.length === 0) {
|
|
1287
|
-
await node.sendText(`## 🗂️ 可用工作区\n\n> 当前没有已注册的工作区。可使用 \`/new <提示词> @<路径>\` 指定项目目录。`)
|
|
1288
|
-
return true
|
|
1289
|
-
}
|
|
1290
|
-
const rows = workspaces.map((w, i) => {
|
|
1291
|
-
const titleStr = w.title && w.title !== w.path ? w.title : getWorkspaceBasename(w.path)
|
|
1292
|
-
const safeTitle = titleStr.replace(/\|/g, '|')
|
|
1293
|
-
return `| **@${i + 1}** | ${safeTitle} | \`${w.path}\` |`
|
|
1294
|
-
})
|
|
1295
|
-
await node.sendText([
|
|
1296
|
-
`## 🗂️ 可用工作区 (共 ${workspaces.length} 个)`,
|
|
1297
|
-
`> 新建会话:发送 \`/new <提示词> @序号\` 或 \`/new <提示词> @路径\``,
|
|
1298
|
-
'',
|
|
1299
|
-
'| 序号 | 工作区名称 | 目录路径 |',
|
|
1300
|
-
'| :--- | :--- | :--- |',
|
|
1301
|
-
...rows,
|
|
1302
|
-
].join('\n'))
|
|
1303
|
-
return true
|
|
1304
|
-
}
|
|
1305
|
-
case 'addworkspace': {
|
|
1306
|
-
const targetPath = rest.join(' ').trim()
|
|
1307
|
-
if (!targetPath) {
|
|
1308
|
-
await node.sendText(`❌ **缺少工作区路径**\n\n> 用法:\`/addworkspace <电脑绝对路径>\`\n> 示例:\`/addworkspace D:\\IdeaProjects\\my-app\``)
|
|
1309
|
-
return true
|
|
1310
|
-
}
|
|
1311
|
-
try {
|
|
1312
|
-
const safetyCheck = await isSafeWorkspacePath(targetPath)
|
|
1313
|
-
if (!safetyCheck.valid) {
|
|
1314
|
-
await node.sendText(`⚠️ **${safetyCheck.error || '路径安全校验未通过'}**:\`${targetPath}\`\n\n> 出于安全考虑,禁止将系统关键目录或敏感配置文件所在路径登记为工作区。`)
|
|
1315
|
-
return true
|
|
1316
|
-
}
|
|
1317
|
-
const resolved = safetyCheck.path
|
|
1318
|
-
const title = basename(resolved) || resolved
|
|
1319
|
-
if (node.ctx.workspaceRegistry?.add) {
|
|
1320
|
-
await node.ctx.workspaceRegistry.add({ path: resolved, title }).catch(() => {})
|
|
1321
|
-
} else if (node.ctx.workspaceRegistry?.register) {
|
|
1322
|
-
await node.ctx.workspaceRegistry.register({ path: resolved, title }).catch(() => {})
|
|
1323
|
-
}
|
|
1324
|
-
const workspaces = await listWorkspaces(node)
|
|
1325
|
-
const foundIndex = workspaces.findIndex(w => normalize(w.path) === normalize(resolved))
|
|
1326
|
-
const numStr = foundIndex >= 0 ? `@${foundIndex + 1}` : ''
|
|
1327
|
-
await node.sendText([
|
|
1328
|
-
`✓ **工作区添加成功**!`,
|
|
1329
|
-
`- **名称**:${title}`,
|
|
1330
|
-
`- **路径**:\`${resolved}\``,
|
|
1331
|
-
foundIndex >= 0 ? `- **快捷编号**:\`${numStr}\`` : '',
|
|
1332
|
-
'',
|
|
1333
|
-
`> 发送 \`/new <提示词> ${numStr || '@' + resolved}\` 即可直接在此工作区创建会话。`,
|
|
1334
|
-
].filter(Boolean).join('\n'))
|
|
1335
|
-
} catch (err) {
|
|
1336
|
-
await node.sendText(`❌ **添加工作区失败**:${err instanceof Error ? err.message : String(err)}`)
|
|
1337
|
-
}
|
|
1338
|
-
return true
|
|
1339
|
-
}
|
|
1340
|
-
case 'new': {
|
|
1341
|
-
// 解析尾部 @N 或 @路径 作为工作区 cwd
|
|
1342
|
-
const args = rest.join(' ').trim()
|
|
1343
|
-
let cwd
|
|
1344
|
-
let prompt = args
|
|
1345
|
-
const atMatch = args.match(/\s+@(\S+)$/)
|
|
1346
|
-
if (atMatch) {
|
|
1347
|
-
prompt = args.slice(0, atMatch.index).trim()
|
|
1348
|
-
const sel = atMatch[1]
|
|
1349
|
-
const workspaces = await listWorkspaces(node)
|
|
1350
|
-
if (/^\d+$/.test(sel)) {
|
|
1351
|
-
const idx = Number(sel)
|
|
1352
|
-
const ws = workspaces[idx - 1]
|
|
1353
|
-
if (ws) cwd = ws.path
|
|
1354
|
-
else {
|
|
1355
|
-
await node.sendText(`❌ **无效工作区编号**:\`${sel}\`\n\n> 请发送 \`/workspaces\` 查看可用工作区列表与编号。`)
|
|
1356
|
-
return true
|
|
1357
|
-
}
|
|
1358
|
-
} else {
|
|
1359
|
-
// 直接指定路径时,规范化并校验(必须完全匹配已注册工作区)
|
|
1360
|
-
const validation = await validateWorkspacePath(node, sel)
|
|
1361
|
-
if (!validation.valid) {
|
|
1362
|
-
await node.sendText(validation.error)
|
|
1363
|
-
return true
|
|
1364
|
-
}
|
|
1365
|
-
cwd = validation.path
|
|
1366
|
-
}
|
|
1367
|
-
}
|
|
1368
|
-
await node.createSession(prompt, cwd)
|
|
1369
|
-
return true
|
|
1370
|
-
}
|
|
1371
|
-
case 'stop': {
|
|
1372
|
-
node.stopAllHeartbeats()
|
|
1373
|
-
const agent = node.activeAgent()
|
|
1374
|
-
if (!agent) {
|
|
1375
|
-
await node.sendText(`ℹ️ **当前没有正在运行的 Agent 任务**`)
|
|
1376
|
-
} else {
|
|
1377
|
-
agent.cancel({ kind: 'user' })
|
|
1378
|
-
await node.sendText(`⏹ **已请求停止当前任务**`)
|
|
1379
|
-
}
|
|
1380
|
-
return true
|
|
1381
|
-
}
|
|
1382
|
-
case 'end': {
|
|
1383
|
-
node.stopAllHeartbeats()
|
|
1384
|
-
// 结束当前会话:停止 agent 并清除活动会话(进入"没有活动会话"状态)
|
|
1385
|
-
const agent = node.activeAgent()
|
|
1386
|
-
if (agent) agent.cancel({ kind: 'user' })
|
|
1387
|
-
node.activeSessionId = null
|
|
1388
|
-
await node.onActiveSessionChange?.(null)
|
|
1389
|
-
await node.sendText(`✓ **已结束当前会话**(没有活动会话)。\n\n> **后续操作**:\n> - \`/new <提示词>\` — 新建会话并开始\n> - \`/sessions\` — 查看历史会话列表\n> - \`/help\` — 查看常用指令帮助`)
|
|
1390
|
-
return true
|
|
1391
|
-
}
|
|
1392
|
-
case 'status': {
|
|
1393
|
-
const agent = node.activeAgent()
|
|
1394
|
-
const session = node.activeSession()
|
|
1395
|
-
if (!session) {
|
|
1396
|
-
await node.sendText(`## 📊 Agent 状态看板\n\n> 当前没有活动会话。\n> 发送 \`/new <提示词>\` 开始新任务,或发送 \`/sessions\` 查看已有会话。`)
|
|
1397
|
-
return true
|
|
1398
|
-
}
|
|
1399
|
-
const statusMap = {
|
|
1400
|
-
idle: '空闲 (idle)',
|
|
1401
|
-
running: '运行中 (running)',
|
|
1402
|
-
paused: '已暂停 (paused)',
|
|
1403
|
-
error: '异常 (error)',
|
|
1404
|
-
}
|
|
1405
|
-
const status = statusMap[agent?.status] || (agent?.status ?? '空闲 (idle)')
|
|
1406
|
-
const lastTurn = [...(session.events ?? [])].reverse().find((e) => e.type === 'turn/end')
|
|
1407
|
-
const reason = lastTurn ? describeTurnEnd(lastTurn.data.reason) : '尚未运行'
|
|
1408
|
-
const title = session.title || (session.events ? sessionLabel(session) : '')
|
|
1409
|
-
const shortId = fmtSessionId(session.id)
|
|
1410
|
-
const cwd = session.header?.cwd || node.config?.cwd || ''
|
|
1411
|
-
|
|
1412
|
-
const content = [
|
|
1413
|
-
`## 📊 Agent 状态看板`,
|
|
1414
|
-
'',
|
|
1415
|
-
'| 属性 | 当前状态 / 参数 |',
|
|
1416
|
-
'| :--- | :--- |',
|
|
1417
|
-
`| **会话 ID** | \`${shortId}\` |`,
|
|
1418
|
-
...(title ? [`| **会话标题** | ${title.replace(/\|/g, '|')} |`] : []),
|
|
1419
|
-
...(cwd ? [`| **工作区** | \`${cwd}\` |`] : []),
|
|
1420
|
-
`| **Agent 状态** | ${status} |`,
|
|
1421
|
-
`| **累计事件** | ${session.seq ?? 0} 条 |`,
|
|
1422
|
-
`| **最近执行** | ${reason} |`,
|
|
1423
|
-
].join('\n')
|
|
1424
|
-
|
|
1425
|
-
await node.sendText(content)
|
|
1426
|
-
return true
|
|
1427
|
-
}
|
|
1428
|
-
case 'start': // 别名:首次扫码自动开始一个会话
|
|
1429
|
-
await node.createSession('')
|
|
1430
|
-
return true
|
|
1431
|
-
default:
|
|
1432
|
-
await node.sendText(`❌ **未知指令**:\`/${command}\`\n\n${helpText()}`)
|
|
1433
|
-
return true
|
|
1434
|
-
}
|
|
1435
|
-
}
|
|
1436
|
-
|
|
1437
|
-
function describeTurnEnd(reason) {
|
|
1438
|
-
switch (reason.kind) {
|
|
1439
|
-
case 'completed': return '✓ 已完成'
|
|
1440
|
-
case 'error': return '❌ 出错'
|
|
1441
|
-
case 'aborted': return '⏹ 已停止'
|
|
1442
|
-
case 'blocked': return '⚠️ 已阻塞'
|
|
1443
|
-
case 'max-tokens': return '⚠️ 输出截断'
|
|
1444
|
-
case 'interrupted': return '⚡ 已中断'
|
|
1445
|
-
default: return `[${reason.kind}]`
|
|
1446
|
-
}
|
|
1447
|
-
}
|
|
1448
|
-
|
|
1449
|
-
async function renderSessions(node) {
|
|
1450
|
-
const all = await listSessions(node)
|
|
1451
|
-
if (all.length === 0) {
|
|
1452
|
-
return `## 📋 会话列表\n\n> 暂无历史会话。发送 \`/new <提示词>\` 开始新会话。`
|
|
1453
|
-
}
|
|
1454
|
-
// 按工作区分组(保持 listSessions 中的工作区账本顺序)
|
|
1455
|
-
const groups = new Map()
|
|
1456
|
-
for (const s of all) {
|
|
1457
|
-
const key = s.cwd || '(未指定)'
|
|
1458
|
-
if (!groups.has(key)) {
|
|
1459
|
-
groups.set(key, { title: s.workspaceTitle || getWorkspaceBasename(key), sessions: [] })
|
|
1460
|
-
}
|
|
1461
|
-
groups.get(key).sessions.push(s)
|
|
1462
|
-
}
|
|
1463
|
-
const parts = [
|
|
1464
|
-
`## 📋 会话列表 (共 ${all.length} 个)`,
|
|
1465
|
-
`> 切换会话:发送 \`/use 编号\` 或 \`/resume 编号\``,
|
|
1466
|
-
'',
|
|
1467
|
-
]
|
|
1468
|
-
let idx = 0
|
|
1469
|
-
for (const [cwd, group] of groups) {
|
|
1470
|
-
const groupName = cwd === '(未指定)' ? '📁 未指定工作区' : `📁 **${group.title || getWorkspaceBasename(cwd)}**`
|
|
1471
|
-
parts.push(groupName)
|
|
1472
|
-
parts.push('')
|
|
1473
|
-
parts.push('| 序号 | 会话标题 / 摘要 | 时间 | 状态 |')
|
|
1474
|
-
parts.push('| :--- | :--- | :--- | :--- |')
|
|
1475
|
-
for (const session of group.sessions.slice(0, 20)) {
|
|
1476
|
-
idx += 1
|
|
1477
|
-
const isActive = session.id === node.activeSessionId
|
|
1478
|
-
const statusTag = isActive ? '`[当前]`' : '-'
|
|
1479
|
-
const rawTitle = session.title || (session.events ? sessionLabel(session) : '')
|
|
1480
|
-
const titleText = formatGoalTitle(rawTitle) || (typeof rawTitle === 'string' ? rawTitle : '') || '新会话'
|
|
1481
|
-
const safeTitle = String(titleText).replace(/\|/g, '|').replace(/\r?\n/g, ' ')
|
|
1482
|
-
const when = session.createdAt ? fmtTime(session.createdAt) : '-'
|
|
1483
|
-
parts.push(`| **#${idx}** | ${safeTitle} | ${when} | ${statusTag} |`)
|
|
1484
|
-
}
|
|
1485
|
-
if (group.sessions.length > 20) {
|
|
1486
|
-
parts.push(`*…该工作区共 ${group.sessions.length} 个会话,仅显示前 20 个*`)
|
|
1487
|
-
}
|
|
1488
|
-
parts.push('')
|
|
1489
|
-
}
|
|
1490
|
-
if (all.length > 50) parts.push(`*…共 ${all.length} 个会话,仅显示前 50 个*`)
|
|
1491
|
-
return parts.join('\n').trim()
|
|
1492
|
-
}
|
|
1493
|
-
|
|
1494
|
-
// 与 renderSessions 完全一致的显示顺序:保持 listSessions 中的分组和顺序。
|
|
1495
|
-
// /use N 用这个数组索引,保证显示的编号 N 与切换的会话一一对应。
|
|
1496
|
-
function sessionsInDisplayOrder(all) {
|
|
1497
|
-
const groups = new Map()
|
|
1498
|
-
for (const s of all) {
|
|
1499
|
-
const key = s.cwd || '(未指定)'
|
|
1500
|
-
if (!groups.has(key)) groups.set(key, [])
|
|
1501
|
-
groups.get(key).push(s)
|
|
1502
|
-
}
|
|
1503
|
-
return [...groups.values()].flatMap((sessions) => sessions)
|
|
1504
|
-
}
|
|
1505
|
-
|
|
1506
|
-
// 时间戳 → 简洁可读时间 (MM-DD HH:mm 或 YYYY-MM-DD HH:mm)
|
|
1507
|
-
function fmtTime(ms) {
|
|
1508
|
-
try {
|
|
1509
|
-
const d = new Date(ms)
|
|
1510
|
-
if (isNaN(d.getTime())) return ''
|
|
1511
|
-
const p = (n) => String(n).padStart(2, '0')
|
|
1512
|
-
const now = new Date()
|
|
1513
|
-
const isSameYear = d.getFullYear() === now.getFullYear()
|
|
1514
|
-
const datePart = isSameYear ? `${p(d.getMonth() + 1)}-${p(d.getDate())}` : `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`
|
|
1515
|
-
return `${datePart} ${p(d.getHours())}:${p(d.getMinutes())}`
|
|
1516
|
-
} catch { return '' }
|
|
1517
|
-
}
|
|
1518
|
-
|
|
1519
|
-
// 提取精简会话短 ID(去除冗余 session- 前缀,保留 8 位短标识)
|
|
1520
|
-
function fmtSessionId(id) {
|
|
1521
|
-
if (!id) return ''
|
|
1522
|
-
const clean = String(id).replace(/^session-/, '')
|
|
1523
|
-
return clean.length > 8 ? clean.slice(0, 8) : clean
|
|
1524
|
-
}
|
|
1525
|
-
|
|
1526
|
-
function helpText() {
|
|
1527
|
-
return [
|
|
1528
|
-
'## 🤖 常用指令帮助',
|
|
1529
|
-
'',
|
|
1530
|
-
'### 💬 会话控制',
|
|
1531
|
-
'| 指令 | 说明 | 示例 |',
|
|
1532
|
-
'| :--- | :--- | :--- |',
|
|
1533
|
-
'| `/sessions` | 查看所有会话表格列表 | `/sessions` 或 `/list` |',
|
|
1534
|
-
'| `/use <编号>` | 切换到指定编号会话 | `/use 1` 或 `/resume 1` |',
|
|
1535
|
-
'| `/new <提示词>` | 在当前工作区新建会话 | `/new 帮我写个脚本` |',
|
|
1536
|
-
'| `/new <词> @N` | 在指定工作区新建会话 | `/new 帮我写个脚本 @1` |',
|
|
1537
|
-
'| `/rename <新标题>` | 重命名当前活动会话 | `/rename 优化登录交互` |',
|
|
1538
|
-
'| `/stop` | 中断停止当前正在执行的任务 | `/stop` |',
|
|
1539
|
-
'| `/end` | 结束当前会话(回到空闲) | `/end` |',
|
|
1540
|
-
'',
|
|
1541
|
-
'### 📁 环境与状态',
|
|
1542
|
-
'| 指令 | 说明 |',
|
|
1543
|
-
'| :--- | :--- |',
|
|
1544
|
-
'| `/workspaces` | 查看可用工作区表格列表 |',
|
|
1545
|
-
'| `/addworkspace <路径>` | 注册添加新的电脑工作区目录 |',
|
|
1546
|
-
'| `/status` | 查看 Agent 运行状态看板 |',
|
|
1547
|
-
'| `/help` | 查看此帮助菜单 |',
|
|
1548
|
-
'',
|
|
1549
|
-
'### 🔐 权限确认',
|
|
1550
|
-
'| 指令 | 快捷数字 | 说明 |',
|
|
1551
|
-
'| :--- | :--- | :--- |',
|
|
1552
|
-
'| `/yes` | `1` | 批准当前工具执行请求 |',
|
|
1553
|
-
'| `/no` | `2` | 拒绝当前工具执行请求 |',
|
|
1554
|
-
].join('\n')
|
|
1555
|
-
}
|
|
1556
|
-
|
|
1557
|
-
// 导出,便于测试与复用
|
|
1558
|
-
export const conversationBridgeHelpers = {
|
|
1559
|
-
splitForIM,
|
|
1560
|
-
digestLine,
|
|
1561
|
-
textOfAssistantMessage,
|
|
1562
|
-
resolveFilePath,
|
|
1563
|
-
extractFilePathsFromText,
|
|
1564
|
-
extractAndStripSendFileDirectives,
|
|
1565
|
-
sessionsInDisplayOrder,
|
|
1566
|
-
listSessions,
|
|
1567
|
-
renderSessions,
|
|
1568
|
-
listWorkspaces,
|
|
1569
|
-
BRIDGE_MARK,
|
|
1570
|
-
}
|
|
1
|
+
// dsh-bridge 平台无关的会话桥(核心类)
|
|
2
|
+
//
|
|
3
|
+
// 本模块只保留 ConversationBridge 类本身(白名单、会话生命周期、审批桥、
|
|
4
|
+
// 出站 digest/心跳、入站路由入口)。拆分出去的模块:
|
|
5
|
+
// - message-split.js 出站分块 + [SEND_FILE] 指令解析(纯函数)
|
|
6
|
+
// - dsh-storage.js DSH 私有存储读取兜底(workspace.json / projcache)
|
|
7
|
+
// - session-catalog.js 会话目录组织 / 渲染 / 格式化
|
|
8
|
+
// - commands.js 斜杠命令解释器(routeCommand)
|
|
9
|
+
//
|
|
10
|
+
// 平台相关的部分由子类(或组合)提供:
|
|
11
|
+
// - sendText(text, opts) / sendTyping(state):向当前 peer 发送
|
|
12
|
+
// - extractTextFrom(message):从平台消息提取文本
|
|
13
|
+
// - isGroupMessage(message):判断群消息
|
|
14
|
+
// - handlePlatformInbound(message):消息解析(返回 { senderId, text, isGroup } 或 null)
|
|
15
|
+
//
|
|
16
|
+
// 本类不直接依赖任何 IM 协议,只消费 DSH 官方服务:
|
|
17
|
+
// ctx.sessions / ctx.agents / ctx.approval / ctx.sessionPersistence / ctx.workspaceRegistry
|
|
18
|
+
|
|
19
|
+
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
20
|
+
import { randomUUID } from 'node:crypto'
|
|
21
|
+
import { stat } from 'node:fs/promises'
|
|
22
|
+
import { normalize } from 'node:path'
|
|
23
|
+
import { resolveFilePath } from './message-split.js'
|
|
24
|
+
import { splitForIM, textOfAssistantMessage, extractAndStripSendFileDirectives, extractFilePathsFromText } from './message-split.js'
|
|
25
|
+
import { routeCommand } from './commands.js'
|
|
26
|
+
import { listSessions, listWorkspaces, validateWorkspacePath, renderSessions, sessionsInDisplayOrder, describeTurnEnd, helpText, fmtTime, fmtSessionId, sessionLabel } from './session-catalog.js'
|
|
27
|
+
|
|
28
|
+
export { textOfAssistantMessage } from './message-split.js'
|
|
29
|
+
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
// 出站分块(通用:按平台 maxMessageChars 硬分块 + 保留 fenced code block)
|
|
32
|
+
// ---------------------------------------------------------------------------
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
function digestLine(session) {
|
|
36
|
+
let turn = 0
|
|
37
|
+
let tools = 0
|
|
38
|
+
let lastTool = undefined
|
|
39
|
+
let inTurn = false
|
|
40
|
+
for (const event of session.events ?? []) {
|
|
41
|
+
if (event.type === 'turn/start') {
|
|
42
|
+
turn = event.data.turn
|
|
43
|
+
inTurn = true
|
|
44
|
+
tools = 0
|
|
45
|
+
lastTool = undefined
|
|
46
|
+
} else if (event.type === 'turn/end') {
|
|
47
|
+
inTurn = false
|
|
48
|
+
} else if (event.type === 'tool/call' && inTurn) {
|
|
49
|
+
tools += 1
|
|
50
|
+
lastTool = event.data.name
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (!inTurn || turn === 0) return null
|
|
54
|
+
const steps = tools > 0 ? `${tools} 次工具调用` : '思考中'
|
|
55
|
+
const last = lastTool ? ` | 最近: ${lastTool}` : ''
|
|
56
|
+
return `[处理中] 第 ${turn} 轮 | ${steps}${last}`
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function summarizeError(error) {
|
|
60
|
+
if (error && typeof error === 'object' && 'message' in error) {
|
|
61
|
+
return String(error.message).slice(0, 200)
|
|
62
|
+
}
|
|
63
|
+
return String(error).slice(0, 200)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function sleep(ms) {
|
|
67
|
+
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ---------------------------------------------------------------------------
|
|
71
|
+
// 会话桥基类
|
|
72
|
+
// ---------------------------------------------------------------------------
|
|
73
|
+
|
|
74
|
+
export class ConversationBridge {
|
|
75
|
+
/**
|
|
76
|
+
* @param {object} opts
|
|
77
|
+
* @param {object} opts.ctx Cordis 上下文
|
|
78
|
+
* @param {object} opts.logger 日志器
|
|
79
|
+
* @param {object} [opts.config] 已持久化配置(allowFrom/间隔/活动会话等)
|
|
80
|
+
* @param {object} opts.platform 所属 Platform 实例(提供 accountId/capabilities)—— 必需
|
|
81
|
+
* @param {(senderId: string) => void} [opts.onFirstSender]
|
|
82
|
+
* @param {(sessionId: string) => void} [opts.onActiveSessionChange]
|
|
83
|
+
*/
|
|
84
|
+
constructor({ ctx, logger, config = {}, platform, onFirstSender, onActiveSessionChange } = {}) {
|
|
85
|
+
if (!platform) {
|
|
86
|
+
throw new Error('ConversationBridge requires a platform instance')
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
this.ctx = ctx
|
|
90
|
+
this.logger = logger
|
|
91
|
+
this.platform = platform
|
|
92
|
+
this.onFirstSender = onFirstSender
|
|
93
|
+
this.onActiveSessionChange = onActiveSessionChange
|
|
94
|
+
|
|
95
|
+
const maxChars = platform.capabilities?.maxMessageChars ?? 2000
|
|
96
|
+
const rawMax = Number(config.maxMessageChars)
|
|
97
|
+
const safeMaxChars = (Number.isFinite(rawMax) && rawMax > 0) ? rawMax : maxChars
|
|
98
|
+
this.config = {
|
|
99
|
+
allowFrom: Array.isArray(config.allowFrom) ? config.allowFrom : [],
|
|
100
|
+
digestIntervalSec: config.digestIntervalSec ?? 300,
|
|
101
|
+
approvalTimeoutSec: config.approvalTimeoutSec ?? 600,
|
|
102
|
+
maxMessageChars: safeMaxChars,
|
|
103
|
+
sendChunkDelayMs: config.sendChunkDelayMs ?? 1500,
|
|
104
|
+
cwd: config.cwd,
|
|
105
|
+
agentPreset: config.agentPreset,
|
|
106
|
+
agentProvider: config.agentProvider,
|
|
107
|
+
agentModel: config.agentModel,
|
|
108
|
+
// 群聊自动授权开关:默认关闭,防止任意陌生群 @机器人 即获得访问权(T2.5)
|
|
109
|
+
groupAutoApprove: config.groupAutoApprove === true,
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// 从配置恢复活动会话(v0.2.1:重启后保持会话)
|
|
113
|
+
// 注意:不在构造函数里调用 _pickDefaultSession(),由 loadConfig 回调负责恢复,避免竞态覆盖
|
|
114
|
+
this.activeSessionId = config.activeSessionId ?? null
|
|
115
|
+
this.peerId = null
|
|
116
|
+
this.pending = new Map() // number -> PendingApproval
|
|
117
|
+
this.approvalCounter = 0
|
|
118
|
+
this.disposers = []
|
|
119
|
+
|
|
120
|
+
// 配置恢复状态追踪(用于防止 handleInbound 在配置加载前处理消息)
|
|
121
|
+
this._restoringConfig = null
|
|
122
|
+
this._restoringSessionMap = new Map() // sessionId -> Promise<Agent|null>
|
|
123
|
+
|
|
124
|
+
// T2.3:sessionId -> { outboundPeer, senderId }
|
|
125
|
+
// 记录每轮对话的发起者:出站事件流(assistant/turn/end/心跳/SEND_FILE/审批)绑定到
|
|
126
|
+
// 发起轮次的 peer,而不是"最近一条入站的 peer",防止 A 任务进行中 B 来消息把回复串到 B 的窗口
|
|
127
|
+
this._turnPeers = new Map()
|
|
128
|
+
// 入站串行队列:handleInbound 内部读写 this.peerId 等共享状态,并发入站会造成串扰
|
|
129
|
+
this._inboundQueue = Promise.resolve()
|
|
130
|
+
|
|
131
|
+
this._attachOutbound()
|
|
132
|
+
this._attachApprovalBridge()
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
get gatewayAccountId() {
|
|
136
|
+
return this.platform?.accountId ?? ''
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
activeSession() {
|
|
140
|
+
if (!this.activeSessionId) return undefined
|
|
141
|
+
return this.ctx.sessions?.get(this.activeSessionId)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
activeAgent() {
|
|
145
|
+
if (!this.activeSessionId) return undefined
|
|
146
|
+
return this.ctx.agents?.get(this.activeSessionId)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
ownsAgent(agent) {
|
|
150
|
+
return this.activeSessionId !== null && agent?.session?.id === this.activeSessionId
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
isAllowed(senderId) {
|
|
154
|
+
if (!Array.isArray(this.config.allowFrom)) return false
|
|
155
|
+
if (this.config.allowFrom.length === 0) return false
|
|
156
|
+
return this.config.allowFrom.includes(senderId)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
setActiveSession(session) {
|
|
160
|
+
this.stopAllHeartbeats()
|
|
161
|
+
this._dropDigestState(this.activeSessionId)
|
|
162
|
+
this.activeSessionId = session.id
|
|
163
|
+
try { this.onActiveSessionChange?.(session.id) } catch { /* 持久化失败不致命 */ }
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// 仅按 ID 设置活动会话(持久化会话可能没有内存 session 对象),
|
|
167
|
+
// 发消息时通过 re-attach 逻辑拉起 agent。
|
|
168
|
+
setActiveSessionById(id) {
|
|
169
|
+
if (!id) return
|
|
170
|
+
this.stopAllHeartbeats()
|
|
171
|
+
this._dropDigestState(this.activeSessionId)
|
|
172
|
+
this.activeSessionId = id
|
|
173
|
+
try { this.onActiveSessionChange?.(id) } catch { /* 持久化失败不致命 */ }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// 释放指定会话的 digest 状态(活动会话切换后旧状态不再使用)
|
|
177
|
+
_dropDigestState(sessionId) {
|
|
178
|
+
if (sessionId && this._digestState) this._digestState.delete(sessionId)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async _pickDefaultSession() {
|
|
182
|
+
const sessions = await listSessions(this)
|
|
183
|
+
if (sessions.length > 0) this.setActiveSessionById(sessions[0].id)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async createSession(prompt, cwdOverride) {
|
|
187
|
+
// 使用 DSH 原生格式 session-${uuid},与 ctx.sessions 持久化系统兼容
|
|
188
|
+
const sessionId = `session-${randomUUID()}`
|
|
189
|
+
try {
|
|
190
|
+
const workspaces = await listWorkspaces(this)
|
|
191
|
+
const defaultWsPath = workspaces.length > 0 ? workspaces[0].path : process.cwd()
|
|
192
|
+
const cwd = cwdOverride || this.config.cwd || defaultWsPath
|
|
193
|
+
// 校验指定目录存在且是目录,防止路径遍历
|
|
194
|
+
if (cwdOverride) {
|
|
195
|
+
const validation = await validateWorkspacePath(this, cwdOverride)
|
|
196
|
+
if (!validation.valid) {
|
|
197
|
+
await this.sendText(validation.error)
|
|
198
|
+
return
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const meta = {
|
|
202
|
+
cwd,
|
|
203
|
+
agentPreset: this.config.agentPreset || 'routing-suite',
|
|
204
|
+
}
|
|
205
|
+
const agentOptions = {}
|
|
206
|
+
if (this.config.agentProvider) agentOptions.provider = this.config.agentProvider
|
|
207
|
+
if (this.config.agentModel) agentOptions.model = this.config.agentModel
|
|
208
|
+
if (!agentOptions.provider || !agentOptions.model) {
|
|
209
|
+
try {
|
|
210
|
+
const def = this.ctx.get?.('agentDefaultModel')?.currentSelection?.()
|
|
211
|
+
if (def) {
|
|
212
|
+
if (!agentOptions.provider && def.provider) agentOptions.provider = def.provider
|
|
213
|
+
if (!agentOptions.model && def.model) agentOptions.model = def.model
|
|
214
|
+
}
|
|
215
|
+
} catch { /* 默认模型服务不可用则忽略,交由 DSH 自行处理 */ }
|
|
216
|
+
}
|
|
217
|
+
// 注意:不预创建 ctx.sessions——agents.create 会自己 prepare+enter session
|
|
218
|
+
const handle = await this.ctx.agents.create({ sessionId, meta, agentOptions })
|
|
219
|
+
this.setActiveSession(handle.agent.session)
|
|
220
|
+
|
|
221
|
+
// 同步挂载进 DSH 工作区账本 (workspaceRegistry),使新会话在 Web 侧边栏和 /list 中精准归组
|
|
222
|
+
try {
|
|
223
|
+
const reg = this.ctx.workspaceRegistry
|
|
224
|
+
const entities = reg?.list ? (await reg.list()) : []
|
|
225
|
+
const normCwd = normalize(cwd).toLowerCase()
|
|
226
|
+
const match = (entities || []).find((ws) => ws?.path && normalize(ws.path).toLowerCase() === normCwd)
|
|
227
|
+
if (match?.attachSession) await match.attachSession(sessionId)
|
|
228
|
+
} catch { /* 账本写入失败不影响会话创建 */ }
|
|
229
|
+
|
|
230
|
+
if (prompt) {
|
|
231
|
+
const platformName = this.platform?.name || 'IM客户端'
|
|
232
|
+
const promptWithContext = `${prompt}\n\n<!-- [dsh-bridge 提示] 当前用户正通过【${platformName}】与你对话。若用户明确要求发送、导出或传送文件/图片/报表/代码脚本产物,请在本地生成/准备好文件后,在回复正文中附带明确发送指令:\n[SEND_FILE: <本地文件绝对路径>]\n例如:[SEND_FILE: C:\\path\\to\\report.xlsx]\n网关会自动解析该指令并将该文件直传至用户的聊天窗口,且在聊天文本中自动隐藏该指令。在日常编写代码、回复普通文本或未请求发送文件时,请勿输出此指令。 -->`
|
|
233
|
+
handle.agent.followup(createUserMessage({
|
|
234
|
+
content: [{ type: 'text', text: promptWithContext }],
|
|
235
|
+
source: { kind: 'user' },
|
|
236
|
+
}))
|
|
237
|
+
}
|
|
238
|
+
const wsDetail = cwd ? `\n- **工作区**:\`${cwd}\`` : ''
|
|
239
|
+
const hint = prompt ? '' : '\n\n> 💡 发送任意消息即可直接与 Agent 对话。'
|
|
240
|
+
await this.sendText(`✓ **已创建新会话**\n- **会话 ID**:\`${fmtSessionId(handle.agent.session.id)}\`${wsDetail}${hint}`)
|
|
241
|
+
} catch (error) {
|
|
242
|
+
await this.sendText(`❌ **创建会话失败**:${error instanceof Error ? error.message : String(error)}`)
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// ---- 审批 ----
|
|
247
|
+
|
|
248
|
+
nextApprovalNumber() {
|
|
249
|
+
this.approvalCounter += 1
|
|
250
|
+
return this.approvalCounter
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
registerApproval(number, approval) {
|
|
254
|
+
this.pending.set(number, approval)
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
clearApproval(number) {
|
|
258
|
+
const entry = this.pending.get(number)
|
|
259
|
+
if (entry) {
|
|
260
|
+
clearTimeout(entry.timer)
|
|
261
|
+
this.pending.delete(number)
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// 取消并拒绝审批(用于 dispose 清理)
|
|
266
|
+
cancelApproval(number) {
|
|
267
|
+
const entry = this.pending.get(number)
|
|
268
|
+
if (entry) {
|
|
269
|
+
clearTimeout(entry.timer)
|
|
270
|
+
this.pending.delete(number)
|
|
271
|
+
entry.resolve('rejected') // 触发 Promise,防止泄漏
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
resolveApproval(text, senderId = null) {
|
|
276
|
+
const entries = [...this.pending.entries()]
|
|
277
|
+
if (entries.length === 0) return false
|
|
278
|
+
let outcome
|
|
279
|
+
if (text === '/yes') outcome = 'allowed-once'
|
|
280
|
+
else if (text === '/no') outcome = 'rejected'
|
|
281
|
+
if (outcome) {
|
|
282
|
+
const [number, entry] = entries[entries.length - 1]
|
|
283
|
+
// 双重检查:确保此 number 仍在 pending 中(防止超时竞态)
|
|
284
|
+
if (!this.pending.has(number)) return false
|
|
285
|
+
if (!this._approvalAllowed(entry, senderId)) return false
|
|
286
|
+
this.clearApproval(number)
|
|
287
|
+
entry.resolve(outcome)
|
|
288
|
+
return true
|
|
289
|
+
}
|
|
290
|
+
if ((text === '1' || text === '2') && entries.length === 1) {
|
|
291
|
+
const [number, entry] = entries[0]
|
|
292
|
+
// 双重检查:确保此 number 仍在 pending 中(防止超时竞态)
|
|
293
|
+
if (!this.pending.has(number)) return false
|
|
294
|
+
if (!this._approvalAllowed(entry, senderId)) return false
|
|
295
|
+
this.clearApproval(number)
|
|
296
|
+
entry.resolve(text === '1' ? 'allowed-once' : 'rejected')
|
|
297
|
+
return true
|
|
298
|
+
}
|
|
299
|
+
return false
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// 审批发起者校验:仅允许发起审批时的 peer(handleInbound 的 sender)决议,
|
|
303
|
+
// 防止群聊/多用户场景下其他成员代批工具执行。senderId 为 null 时放行(内部路径)。
|
|
304
|
+
_approvalAllowed(entry, senderId) {
|
|
305
|
+
if (senderId == null) return true
|
|
306
|
+
if (entry.peerId && entry.peerId !== senderId) {
|
|
307
|
+
this.logger?.warn?.(`[dsh-bridge ${this.platform?.id}] approval #${entry.number} blocked: sender ${senderId} is not the initiator ${entry.peerId}`)
|
|
308
|
+
return false
|
|
309
|
+
}
|
|
310
|
+
return true
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
stopAllHeartbeats() {
|
|
314
|
+
if (this._digestState) {
|
|
315
|
+
for (const state of this._digestState.values()) {
|
|
316
|
+
if (state && state.heartbeat) {
|
|
317
|
+
clearInterval(state.heartbeat)
|
|
318
|
+
state.heartbeat = undefined
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
dispose() {
|
|
325
|
+
this.stopAllHeartbeats()
|
|
326
|
+
for (const disposer of this.disposers) {
|
|
327
|
+
try { disposer() } catch { /* 忽略 */ }
|
|
328
|
+
}
|
|
329
|
+
this.disposers = []
|
|
330
|
+
for (const number of [...this.pending.keys()]) this.cancelApproval(number)
|
|
331
|
+
// 清理所有引用,防止内存泄漏
|
|
332
|
+
this._turnPeers?.clear()
|
|
333
|
+
this._inboundQueue = Promise.resolve()
|
|
334
|
+
this.peerId = null
|
|
335
|
+
this.activeSessionId = null
|
|
336
|
+
this._restoringConfig = null
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// ---- 入站核心(平台无关)----
|
|
340
|
+
//
|
|
341
|
+
// 子类解析出平台消息后调用本方法:
|
|
342
|
+
// await bridge.handleInbound({ senderId, text, isGroup, outboundPeer })
|
|
343
|
+
// - outboundPeer(可选):该平台的"会话级发送目标"(如 QQ 群 { peerId, scope }、
|
|
344
|
+
// Telegram { peerId: chatId }),用于把本轮的出站事件流绑定回发起会话;
|
|
345
|
+
// 不传时出站回退到 this.peerId。
|
|
346
|
+
//
|
|
347
|
+
// 入站按 bridge 串行执行:处理过程会读写共享的 peer/会话状态,并发入站会互相踩踏。
|
|
348
|
+
// 消息处理本身轻量(重活是异步的 turn 事件流),串行代价可忽略。
|
|
349
|
+
//
|
|
350
|
+
// 返回:
|
|
351
|
+
// 'ignored' 消息被忽略(未授权/群消息/空消息)
|
|
352
|
+
// 'routed' 消息已路由到 agent
|
|
353
|
+
handleInbound(message) {
|
|
354
|
+
const task = this._inboundQueue.catch(() => {}).then(() => this._handleInboundSerialized(message))
|
|
355
|
+
this._inboundQueue = task.catch(() => {})
|
|
356
|
+
return task
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
async _handleInboundSerialized({ senderId, text, isGroup = false, outboundPeer }) {
|
|
360
|
+
try {
|
|
361
|
+
// 等待配置恢复完成(防止启动时竞态)
|
|
362
|
+
if (this._restoringConfig) {
|
|
363
|
+
await this._restoringConfig
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const sender = String(senderId ?? '').trim()
|
|
367
|
+
if (!sender) return 'ignored'
|
|
368
|
+
|
|
369
|
+
if (!this.isAllowed(sender)) {
|
|
370
|
+
// 自动授权:
|
|
371
|
+
// - 单聊:白名单为空时,首个发消息的真实用户自动纳入白名单
|
|
372
|
+
// - 群聊:白名单为空时随首条消息自动授权;白名单非空时仅在
|
|
373
|
+
// config.groupAutoApprove 显式开启后才授权新群(默认关闭,
|
|
374
|
+
// 防止任意陌生群 @机器人 一次即整群获得访问权)
|
|
375
|
+
const shouldAutoApprove = Boolean(text?.trim()) && (
|
|
376
|
+
this.config.allowFrom.length === 0 || // 白名单为空:单聊/群聊都自动授权
|
|
377
|
+
(isGroup && this.config.groupAutoApprove === true)
|
|
378
|
+
)
|
|
379
|
+
if (shouldAutoApprove) {
|
|
380
|
+
this.config.allowFrom = Array.from(new Set([...this.config.allowFrom, sender]))
|
|
381
|
+
this.logger?.info?.(`[dsh-bridge ${this.platform.id}] auto-approved ${isGroup ? 'group' : 'sender'} ${sender} into allowlist`)
|
|
382
|
+
try {
|
|
383
|
+
await this.onFirstSender?.(sender)
|
|
384
|
+
} catch (err) {
|
|
385
|
+
this.logger?.warn?.(`[dsh-bridge ${this.platform.id}] failed to persist first sender: ${err instanceof Error ? err.message : String(err)}`)
|
|
386
|
+
}
|
|
387
|
+
} else {
|
|
388
|
+
this.logger?.info?.(`[dsh-bridge ${this.platform.id}] media-only first message from ${sender} not auto-approved (waiting for text)`)
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// 如果仍未通过白名单,拒绝处理(防止绕过白名单)
|
|
392
|
+
if (!this.isAllowed(sender)) {
|
|
393
|
+
this.logger?.info?.(`[dsh-bridge ${this.platform.id}] ignore message from non-allowlisted sender ${sender} (never fed to model)`)
|
|
394
|
+
return 'ignored'
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// 仅在不支持群聊的平台忽略群消息(QQ 等支持群聊的平台放行)
|
|
399
|
+
if (isGroup && !this.platform?.capabilities?.supportsGroup) {
|
|
400
|
+
this.logger?.info?.(`[dsh-bridge ${this.platform.id}] ignore group message from ${sender} (no group support)`)
|
|
401
|
+
return 'ignored'
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const fullText = text?.trim() ?? ''
|
|
405
|
+
if (!fullText) {
|
|
406
|
+
this.logger?.info?.(`[dsh-bridge ${this.platform.id}] ignore empty message from ${sender}`)
|
|
407
|
+
return 'ignored'
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
this.peerId = sender
|
|
411
|
+
|
|
412
|
+
// 记录本轮发起者:出站事件流绑定回发起会话(T2.3)。outboundPeer 由平台节点传入
|
|
413
|
+
// 其"会话级发送目标"(QQ 群/Telegram chat 等),未传则不记录(出站回退 this.peerId)。
|
|
414
|
+
if (this.activeSessionId && outboundPeer) {
|
|
415
|
+
this._turnPeers.set(this.activeSessionId, { outboundPeer, senderId: sender })
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
if (await routeCommand(this, fullText, sender)) return 'routed'
|
|
419
|
+
|
|
420
|
+
let agent = this.activeAgent()
|
|
421
|
+
if (!agent && this.activeSessionId) {
|
|
422
|
+
const sessionId = this.activeSessionId
|
|
423
|
+
if (this._restoringSessionMap.has(sessionId)) {
|
|
424
|
+
try {
|
|
425
|
+
await this._restoringSessionMap.get(sessionId)
|
|
426
|
+
} catch { /* 错误已在原始 Promise 中捕获 */ }
|
|
427
|
+
agent = this.activeAgent()
|
|
428
|
+
} else {
|
|
429
|
+
const restorePromise = (async () => {
|
|
430
|
+
// agent 不在内存(DSH 重启后或切换到持久化会话)→ re-attach。
|
|
431
|
+
try {
|
|
432
|
+
const agentOptions = {}
|
|
433
|
+
if (this.config.agentProvider) agentOptions.provider = this.config.agentProvider
|
|
434
|
+
if (this.config.agentModel) agentOptions.model = this.config.agentModel
|
|
435
|
+
if (!agentOptions.provider || !agentOptions.model) {
|
|
436
|
+
try {
|
|
437
|
+
const def = this.ctx.get?.('agentDefaultModel')?.currentSelection?.()
|
|
438
|
+
if (def) {
|
|
439
|
+
if (!agentOptions.provider && def.provider) agentOptions.provider = def.provider
|
|
440
|
+
if (!agentOptions.model && def.model) agentOptions.model = def.model
|
|
441
|
+
}
|
|
442
|
+
} catch { /* ignore */ }
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// 判断该 session 是否已持久化:已持久化 → agents.resume(从持久化加载历史恢复,
|
|
446
|
+
// 避免 agents.create 用空 seed 与已持久化事件冲突);未持久化 → agents.create。
|
|
447
|
+
let persisted = false
|
|
448
|
+
try {
|
|
449
|
+
const headers = await this.ctx.sessionPersistence?.list?.()
|
|
450
|
+
persisted = Array.isArray(headers) && headers.some((h) => h?.id === sessionId)
|
|
451
|
+
} catch { /* 读取失败则按未持久化处理 */ }
|
|
452
|
+
|
|
453
|
+
let handle
|
|
454
|
+
if (persisted) {
|
|
455
|
+
handle = await this.ctx.agents.resume({
|
|
456
|
+
resumeSessionId: sessionId,
|
|
457
|
+
agentOptions,
|
|
458
|
+
})
|
|
459
|
+
} else {
|
|
460
|
+
handle = await this.ctx.agents.create({
|
|
461
|
+
sessionId,
|
|
462
|
+
meta: { cwd: this.config.cwd || process.cwd() },
|
|
463
|
+
agentOptions,
|
|
464
|
+
})
|
|
465
|
+
}
|
|
466
|
+
const resumedAgent = handle?.agent
|
|
467
|
+
this.logger?.info?.(`[dsh-bridge ${this.platform.id}] re-attached agent to session ${sessionId} (${persisted ? 'resume' : 'create'})`)
|
|
468
|
+
return resumedAgent
|
|
469
|
+
} catch (err) {
|
|
470
|
+
const reason = err instanceof Error ? err.message : String(err)
|
|
471
|
+
this.logger?.warn?.(`[dsh-bridge ${this.platform.id}] failed to re-attach agent: ${reason}`)
|
|
472
|
+
// 清除失效的 activeSessionId,避免用户误以为还在旧会话中
|
|
473
|
+
if (this.activeSessionId === sessionId) {
|
|
474
|
+
this.activeSessionId = null
|
|
475
|
+
}
|
|
476
|
+
await this.sendText(`❌ **恢复会话失败**:${reason}\n\n> 发送 \`/new <提示词>\` 可新建一个会话。`)
|
|
477
|
+
return null
|
|
478
|
+
}
|
|
479
|
+
})().finally(() => {
|
|
480
|
+
this._restoringSessionMap.delete(sessionId)
|
|
481
|
+
})
|
|
482
|
+
|
|
483
|
+
this._restoringSessionMap.set(sessionId, restorePromise)
|
|
484
|
+
agent = await restorePromise
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
if (!agent) {
|
|
488
|
+
await this.sendText(`> 💤 **当前没有活动会话**\n> 发送 \`/new <提示词>\` 开始新会话,或发送 \`/sessions\` 查看已有会话。`)
|
|
489
|
+
return 'routed'
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// 针对微信/IM客户端用户,注入上下文提示,规范 Agent 仅在需要向用户发送文件附件时输出 [SEND_FILE: <文件绝对路径>]
|
|
493
|
+
const promptWithContext = `${fullText}\n\n<!-- [dsh-bridge 提示] 当前用户正通过【${this.platform.name}】与你对话。若用户明确要求发送、导出或传送文件/图片/报表/代码脚本产物,请在本地生成/准备好文件后,在回复正文中附带明确发送指令:\n[SEND_FILE: <本地文件绝对路径>]\n例如:[SEND_FILE: C:\\path\\to\\report.xlsx]\n网关会自动解析该指令并将该文件直传至用户的聊天窗口,且在聊天文本中自动隐藏该指令。在日常编写代码、回复普通文本或未请求发送文件时,请勿输出此指令。 -->`
|
|
494
|
+
|
|
495
|
+
const messageValue = createUserMessage({
|
|
496
|
+
content: [{ type: 'text', text: promptWithContext }],
|
|
497
|
+
source: { kind: 'user' },
|
|
498
|
+
})
|
|
499
|
+
agent.followup(messageValue)
|
|
500
|
+
await this.sendTyping(1).catch(() => {})
|
|
501
|
+
return 'routed'
|
|
502
|
+
} catch (err) {
|
|
503
|
+
const errMsg = err instanceof Error ? err.message : String(err)
|
|
504
|
+
this.logger?.error?.(`[dsh-bridge ${this.platform.id}] unhandled error in handleInbound: ${errMsg}\n${err instanceof Error ? err.stack : ''}`)
|
|
505
|
+
await this.sendText(`❌ **执行出错**:${errMsg}`).catch(() => {})
|
|
506
|
+
return 'ignored'
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// ---- 发送(子类覆盖 _sendTextNow,不要覆盖 sendText)----
|
|
511
|
+
|
|
512
|
+
// 出站发送串行队列:所有 sendText 依次执行,杜绝并发分块交错乱序,
|
|
513
|
+
// 以及 QQ 流式 replace 共享 _msgSeq 的并发冲突
|
|
514
|
+
_enqueueSend(task) {
|
|
515
|
+
const queue = (this._sendQueue ??= Promise.resolve())
|
|
516
|
+
const run = queue.then(task, task)
|
|
517
|
+
this._sendQueue = run.catch(() => {})
|
|
518
|
+
return run
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** 向当前 peer 发送文本(自动分块 + typing 指示)。经串行队列执行。
|
|
522
|
+
* opts.outboundPeer(可选):覆盖发送目标(T2.3,绑定到发起轮次的会话 peer)。 */
|
|
523
|
+
sendText(text, opts = {}) {
|
|
524
|
+
return this._enqueueSend(() => this._sendTextNow(text, opts))
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
async _sendTextNow(text, opts = {}) {
|
|
528
|
+
if (this.platform?.status === 'idle' || this.platform?.status === 'offline') return
|
|
529
|
+
const peer = opts?.outboundPeer?.peerId ?? this.peerId ?? this.config.allowFrom?.[0]
|
|
530
|
+
if (!peer) return
|
|
531
|
+
const chunks = splitForIM(text, this.config.maxMessageChars)
|
|
532
|
+
if (chunks.length === 0) return
|
|
533
|
+
await this.sendTyping(1).catch(() => {})
|
|
534
|
+
try {
|
|
535
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
536
|
+
let result
|
|
537
|
+
try {
|
|
538
|
+
result = await this.platform.sendText(peer, chunks[i])
|
|
539
|
+
} catch (err) {
|
|
540
|
+
// 适配器可能直接透传 gateway 抛出的异常(telegram/feishu),统一按失败分块处理,
|
|
541
|
+
// 避免调用方 `void this.sendText(...)` 逃逸成 unhandled rejection
|
|
542
|
+
result = { success: false, error: err?.message ?? String(err) }
|
|
543
|
+
}
|
|
544
|
+
if (result && result.success === false) {
|
|
545
|
+
this.logger?.warn?.(`[dsh-bridge ${this.platform.id}] outbound chunk ${i + 1}/${chunks.length} failed: ${result.error}`)
|
|
546
|
+
break
|
|
547
|
+
}
|
|
548
|
+
if (i < chunks.length - 1 && this.config.sendChunkDelayMs > 0) {
|
|
549
|
+
await sleep(this.config.sendChunkDelayMs)
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
} finally {
|
|
553
|
+
await this.sendTyping(2).catch(() => {})
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** 发送 typing 状态(1=开始,2=停止)。子类可覆盖。 */
|
|
558
|
+
async sendTyping(state) {
|
|
559
|
+
const peer = this.peerId || this.config.allowFrom?.[0]
|
|
560
|
+
if (!this.platform?.sendTyping || peer == null) return
|
|
561
|
+
return this.platform.sendTyping(peer, state)
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// ---- 出站事件绑定 ----
|
|
565
|
+
|
|
566
|
+
_attachOutbound() {
|
|
567
|
+
this._digestState = new Map()
|
|
568
|
+
const stopHeartbeat = (state) => {
|
|
569
|
+
if (state && state.heartbeat) {
|
|
570
|
+
clearInterval(state.heartbeat)
|
|
571
|
+
state.heartbeat = undefined
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
const startHeartbeat = (session, state) => {
|
|
575
|
+
stopHeartbeat(state)
|
|
576
|
+
if (this.config.digestIntervalSec <= 0) return
|
|
577
|
+
state.heartbeat = setInterval(() => {
|
|
578
|
+
// 1. 必须依然是当前活动会话
|
|
579
|
+
if (this.activeSessionId !== session.id) {
|
|
580
|
+
stopHeartbeat(state)
|
|
581
|
+
return
|
|
582
|
+
}
|
|
583
|
+
// 2. 检查会话当前是否真正处于 inTurn 状态中
|
|
584
|
+
const line = digestLine(session)
|
|
585
|
+
if (!line) {
|
|
586
|
+
stopHeartbeat(state)
|
|
587
|
+
return
|
|
588
|
+
}
|
|
589
|
+
// 心跳时同时刷新 typing 状态(微信 typing 只维持 15 秒)
|
|
590
|
+
if (this.peerId) this.sendTyping(1).catch(() => {})
|
|
591
|
+
const heartbeatTurn = this._turnPeers.get(session.id)
|
|
592
|
+
void this.sendText(line, heartbeatTurn ? { outboundPeer: heartbeatTurn.outboundPeer } : {})
|
|
593
|
+
}, this.config.digestIntervalSec * 1000)
|
|
594
|
+
if (typeof state.heartbeat.unref === 'function') state.heartbeat.unref()
|
|
595
|
+
}
|
|
596
|
+
const onEvent = async (session, event) => {
|
|
597
|
+
// 仅为活动会话创建 digest 状态:非活动会话即使有心跳残留,也会被心跳回调里的
|
|
598
|
+
// 失活检查在下一个周期自行停止。若不过滤,任意会话事件都会在此堆积 Map entry(内存泄漏)
|
|
599
|
+
if (session.id !== this.activeSessionId) return
|
|
600
|
+
const state = this._digestState.get(session.id) ?? { startedTurns: new Set(), createdFiles: new Set() }
|
|
601
|
+
this._digestState.set(session.id, state)
|
|
602
|
+
|
|
603
|
+
if (event.type === 'turn/end') {
|
|
604
|
+
stopHeartbeat(state)
|
|
605
|
+
// 本轮已结束,清空轮次集合防止长期运行下无限累积
|
|
606
|
+
state.startedTurns.clear()
|
|
607
|
+
}
|
|
608
|
+
if (this.platform?.status === 'idle' || this.platform?.status === 'offline') return
|
|
609
|
+
|
|
610
|
+
// 出站事件绑定到发起本轮的会话 peer(T2.3)
|
|
611
|
+
const turn = this._turnPeers.get(session.id)
|
|
612
|
+
const sendOpts = turn ? { outboundPeer: turn.outboundPeer } : {}
|
|
613
|
+
|
|
614
|
+
if (event.type === 'turn/start') {
|
|
615
|
+
const turn = event.data?.turn
|
|
616
|
+
state.createdFiles = new Set()
|
|
617
|
+
if (turn != null && !state.startedTurns.has(turn)) {
|
|
618
|
+
state.startedTurns.add(turn)
|
|
619
|
+
// 不发送"[OK] 收到,开始处理…",改用 typing 指示 + 心跳进度。
|
|
620
|
+
if (this.peerId) this.sendTyping(1).catch(() => {})
|
|
621
|
+
}
|
|
622
|
+
startHeartbeat(session, state)
|
|
623
|
+
return
|
|
624
|
+
}
|
|
625
|
+
const getSessionCwd = (sess) => sess?.cwd || this.config.cwd || process.cwd()
|
|
626
|
+
|
|
627
|
+
if (event.type === 'tool/call') {
|
|
628
|
+
// 工具执行仅在终端/状态中展示,文件直发由 AI 回复中的 [SEND_FILE: ...] 指令显式驱动,杜绝误判
|
|
629
|
+
return
|
|
630
|
+
}
|
|
631
|
+
if (event.type === 'assistant/message') {
|
|
632
|
+
const rawText = textOfAssistantMessage(event.data.message)
|
|
633
|
+
if (rawText.trim()) {
|
|
634
|
+
const cwd = getSessionCwd(session)
|
|
635
|
+
const { cleanText, files } = extractAndStripSendFileDirectives(rawText, cwd)
|
|
636
|
+
for (const f of files) {
|
|
637
|
+
state.createdFiles.add(f)
|
|
638
|
+
}
|
|
639
|
+
// 仅向聊天窗口发送过滤掉 [SEND_FILE: ...] 控制指令后的纯净正文
|
|
640
|
+
if (cleanText) {
|
|
641
|
+
void this.sendText(cleanText, sendOpts)
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
return
|
|
645
|
+
}
|
|
646
|
+
if (event.type === 'turn/end') {
|
|
647
|
+
stopHeartbeat(state)
|
|
648
|
+
if (this.peerId) this.sendTyping(2).catch(() => {})
|
|
649
|
+
const reason = event.data?.reason || {}
|
|
650
|
+
if (reason.kind === 'error') {
|
|
651
|
+
void this.sendText(`❌ **处理出错**:${summarizeError(reason.error)}`, sendOpts)
|
|
652
|
+
} else if (reason.kind === 'aborted') {
|
|
653
|
+
void this.sendText(`⏹ **任务已停止**`, sendOpts)
|
|
654
|
+
} else if (reason.kind === 'max-tokens') {
|
|
655
|
+
void this.sendText(`⚠️ **达到模型单轮输出上限,本轮内容已截断**`, sendOpts)
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// 如果本轮 AI 显式指定了 [SEND_FILE: ...] 文件发送指令,直接上传并发送给用户
|
|
659
|
+
if (state.createdFiles && state.createdFiles.size > 0) {
|
|
660
|
+
const rawFiles = Array.from(state.createdFiles)
|
|
661
|
+
const cwd = getSessionCwd(session)
|
|
662
|
+
const targetPeer = sendOpts.outboundPeer?.peerId ?? this.peerId ?? this.config.allowFrom?.[0]
|
|
663
|
+
|
|
664
|
+
if (typeof this.platform?.sendMediaFile === 'function' && targetPeer) {
|
|
665
|
+
const uniqueFilesToSend = []
|
|
666
|
+
for (const f of rawFiles) {
|
|
667
|
+
const resolved = resolveFilePath(f, cwd)
|
|
668
|
+
if (resolved && !uniqueFilesToSend.includes(resolved)) {
|
|
669
|
+
uniqueFilesToSend.push(resolved)
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
for (const resolved of uniqueFilesToSend) {
|
|
673
|
+
try {
|
|
674
|
+
this.logger?.info?.(`[dsh-bridge ${this.platform.id}] auto sendMediaFile to peer: ${resolved}`)
|
|
675
|
+
const res = await this.platform.sendMediaFile(targetPeer, resolved)
|
|
676
|
+
if (res && res.success === false) {
|
|
677
|
+
this.logger?.warn?.(`[dsh-bridge ${this.platform.id}] auto sendMediaFile ${resolved} failed: %s`, res.error)
|
|
678
|
+
}
|
|
679
|
+
} catch (err) {
|
|
680
|
+
this.logger?.warn?.(`[dsh-bridge ${this.platform.id}] auto sendMediaFile ${resolved} failed: %s`, err?.message ?? err)
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
state.createdFiles.clear()
|
|
685
|
+
}
|
|
686
|
+
// 本轮结束,释放轮次绑定(审批/心跳等已不再需要)
|
|
687
|
+
this._turnPeers.delete(session.id)
|
|
688
|
+
return
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
const listener = (session, event) => { void onEvent(session, event) }
|
|
692
|
+
const disposer = this.ctx.on('session/event', listener)
|
|
693
|
+
this.disposers.push(() => {
|
|
694
|
+
for (const state of this._digestState.values()) stopHeartbeat(state)
|
|
695
|
+
disposer()
|
|
696
|
+
})
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
// ---- 审批桥 ----
|
|
700
|
+
//
|
|
701
|
+
// DSH 的审批分发是 cordis waterfall(顺序链):监听器按注册序执行,
|
|
702
|
+
// 不调用 next() 的监听器否决整条链。宿主 apiproxy 注册在先的 GUI 认领监听器
|
|
703
|
+
// 会认领 approval/asked 事件并 veto 等待网页回答——若不 prepend,本桥永远没有
|
|
704
|
+
// 机会执行,IM 端永远收不到审批卡片(工具调用最终以 unavailable 失败)。
|
|
705
|
+
// 因此以 { prepend: true } 注册到链条最外层。
|
|
706
|
+
//
|
|
707
|
+
// 归属模型:IM 发起的轮次审批**只在 IM 决议**——不调用 next(),宿主 GUI 通道
|
|
708
|
+
// 根本不打开。此前曾让 GUI 弹窗与 IM 卡片并行 race,但宿主的 pending 认领没有
|
|
709
|
+
// 插件可用的收尾接口(只有 Web /api/respond 或 signal abort),IM 决议后 Web
|
|
710
|
+
// 弹窗会永久残留(用户实测报告)。各通道只决议自己发起的轮次。
|
|
711
|
+
|
|
712
|
+
_attachApprovalBridge() {
|
|
713
|
+
const listener = async (req, next) => {
|
|
714
|
+
// 只有"本轮由本桥发起"(_turnPeers 有该会话的轮次记录)时才拦截审批。
|
|
715
|
+
// 仅凭 activeSessionId 匹配是不够的:重启恢复/默认挑选后它可能指向一个
|
|
716
|
+
// Web 端发起的会话——那会让 Web 轮次的审批被劫持发去 IM(GUI 不弹窗、
|
|
717
|
+
// 无人响应即自动拒绝)。Web 轮次必须直接放行给宿主 GUI 处理。
|
|
718
|
+
const sessionId = req.agent?.session?.id
|
|
719
|
+
const turn = sessionId ? this._turnPeers.get(sessionId) : null
|
|
720
|
+
if (!turn || !this.ownsAgent(req.agent)) {
|
|
721
|
+
// info 级别:这是用户可自诊的关键判定点(IM 没收到卡片时先看这行)
|
|
722
|
+
this.logger?.info?.('[dsh-bridge %s] approval falls through to GUI: not an IM-initiated turn (session=%s, activeSession=%s, turnTracked=%s)', this.platform?.id, sessionId ?? '(none)', this.activeSessionId ?? '(none)', Boolean(turn))
|
|
723
|
+
return next?.()
|
|
724
|
+
}
|
|
725
|
+
const peer = turn.outboundPeer?.peerId
|
|
726
|
+
const initiator = turn.senderId
|
|
727
|
+
if (!peer) {
|
|
728
|
+
this.logger?.debug?.('[dsh-bridge %s] approval/request ignored: no active peer', this.platform?.id)
|
|
729
|
+
return next?.()
|
|
730
|
+
}
|
|
731
|
+
const sendOpts = turn ? { outboundPeer: turn.outboundPeer } : {}
|
|
732
|
+
|
|
733
|
+
const number = this.nextApprovalNumber()
|
|
734
|
+
const timeoutSec = this.config.approvalTimeoutSec
|
|
735
|
+
const timeoutMin = Math.max(1, Math.round(timeoutSec / 60))
|
|
736
|
+
const prompt = [
|
|
737
|
+
`## ⚠️ 操作权限确认 (#${number})`,
|
|
738
|
+
'',
|
|
739
|
+
'| 项目 | 详情 |',
|
|
740
|
+
'| :--- | :--- |',
|
|
741
|
+
`| **调用工具** | \`${req.toolName}\` |`,
|
|
742
|
+
...(req.reason ? [`| **申请原因** | ${String(req.reason).replace(/\|/g, '|')} |`] : []),
|
|
743
|
+
`| **等待超时** | ${timeoutMin} 分钟 (超时自动拒绝) |`,
|
|
744
|
+
'',
|
|
745
|
+
`> 回复 \`/yes\` (或 \`1\`) 批准执行`,
|
|
746
|
+
`> 回复 \`/no\` (或 \`2\`) 拒绝执行`,
|
|
747
|
+
].join('\n')
|
|
748
|
+
|
|
749
|
+
void this.sendText(prompt, sendOpts)
|
|
750
|
+
|
|
751
|
+
let settled = false
|
|
752
|
+
let timeoutFired = false
|
|
753
|
+
let resolveIm
|
|
754
|
+
const imPromise = new Promise((resolve) => { resolveIm = resolve })
|
|
755
|
+
const settleIm = (outcome) => {
|
|
756
|
+
if (settled) return
|
|
757
|
+
settled = true
|
|
758
|
+
this.clearApproval(number)
|
|
759
|
+
resolveIm(outcome)
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
const timer = setTimeout(() => {
|
|
763
|
+
timeoutFired = true
|
|
764
|
+
settleIm('rejected')
|
|
765
|
+
}, timeoutSec * 1000)
|
|
766
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
767
|
+
|
|
768
|
+
// turn 被停止/工具调用中止时 DSH 会 abort req.signal:同步取消 IM 侧待决审批
|
|
769
|
+
const onSignalAbort = () => {
|
|
770
|
+
timeoutFired = true
|
|
771
|
+
settleIm('cancelled')
|
|
772
|
+
}
|
|
773
|
+
req.signal?.addEventListener('abort', onSignalAbort, { once: true })
|
|
774
|
+
|
|
775
|
+
this.registerApproval(number, { number, request: req, resolve: resolveIm, timer, peerId: initiator })
|
|
776
|
+
|
|
777
|
+
let outcome
|
|
778
|
+
try {
|
|
779
|
+
outcome = await imPromise
|
|
780
|
+
} finally {
|
|
781
|
+
req.signal?.removeEventListener('abort', onSignalAbort)
|
|
782
|
+
clearTimeout(timer)
|
|
783
|
+
settled = true
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
this.logger?.info?.('[dsh-bridge %s] approval #%d resolved: outcome=%s', this.platform?.id, number, outcome)
|
|
787
|
+
|
|
788
|
+
// 仅在非超时/非中止路径发送确认消息(那些路径 resolve 已发生在定时器/abort 回调)
|
|
789
|
+
if (!timeoutFired) {
|
|
790
|
+
const label = outcome === 'allowed-once' ? `✓ **已批准执行**` : outcome === 'rejected' ? `❌ **已拒绝执行**` : `**[${outcome}]**`
|
|
791
|
+
void this.sendText(`${label}(#${number})`, sendOpts)
|
|
792
|
+
}
|
|
793
|
+
return outcome
|
|
794
|
+
}
|
|
795
|
+
const disposer = this.ctx.on('approval/request', listener, { prepend: true })
|
|
796
|
+
this.disposers.push(disposer)
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
// ---------------------------------------------------------------------------
|
|
801
|
+
// 辅助
|
|
802
|
+
// ---------------------------------------------------------------------------
|
|
803
|
+
|
|
804
|
+
// 导出,便于测试与复用
|
|
805
|
+
export const conversationBridgeHelpers = {
|
|
806
|
+
splitForIM,
|
|
807
|
+
digestLine,
|
|
808
|
+
textOfAssistantMessage,
|
|
809
|
+
resolveFilePath,
|
|
810
|
+
extractFilePathsFromText,
|
|
811
|
+
extractAndStripSendFileDirectives,
|
|
812
|
+
sessionsInDisplayOrder,
|
|
813
|
+
listSessions,
|
|
814
|
+
renderSessions,
|
|
815
|
+
listWorkspaces,
|
|
816
|
+
}
|