@chenacc/dsh-agentbridge 0.1.1 → 0.2.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 +16 -6
- package/lib/index.js +970 -862
- package/package.json +61 -58
package/lib/index.js
CHANGED
|
@@ -1,862 +1,970 @@
|
|
|
1
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
//
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
const
|
|
24
|
-
//
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
const
|
|
28
|
-
//
|
|
29
|
-
//
|
|
30
|
-
|
|
31
|
-
const
|
|
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
|
-
const
|
|
199
|
-
if (
|
|
200
|
-
const
|
|
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
|
-
const
|
|
228
|
-
if (!
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
const
|
|
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
|
-
const
|
|
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
|
-
return
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
async
|
|
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
|
-
const
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
}
|
|
751
|
-
if (
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
}
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
} catch (error) {
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
}
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
|
|
7
|
+
const name = "agentbridge-dsh-phone";
|
|
8
|
+
// `agents` is not optional: creating a conversation from the phone asks the agent
|
|
9
|
+
// service to open one, and touching a service that was not injected throws
|
|
10
|
+
// `cannot get property "agents" without inject` — which is what the phone showed
|
|
11
|
+
// as a failed "新建对话" instead of the friendly message below.
|
|
12
|
+
const inject = ["commands", "apiProxy", "llm", "agents"];
|
|
13
|
+
const DEFAULT_ORIGIN = "http://127.0.0.1:8787";
|
|
14
|
+
const POLL_DELAY_MS = 800;
|
|
15
|
+
const EVENT_BATCH_DELAY_MS = 120;
|
|
16
|
+
const APPROVAL_PREFIX = "approval:";
|
|
17
|
+
// The bridge accepts at most 1 MB per /events POST (readJson limit), and this batch
|
|
18
|
+
// carries a JSON wrapper on top of the events. 448 KB leaves headroom, and it is also
|
|
19
|
+
// the cap for a single shrunken event, so one giant tool output can never wedge the
|
|
20
|
+
// queue behind a batch the bridge would refuse.
|
|
21
|
+
const EVENT_POST_BUDGET_BYTES = 448 * 1024;
|
|
22
|
+
const EVENT_MAX_ITEMS = 200;
|
|
23
|
+
const EVENT_EVENT_BUDGET_BYTES = 384 * 1024;
|
|
24
|
+
// A string longer than this in one event is clipped before it crosses the wire: the
|
|
25
|
+
// phone renders a summary of tool output, not a faithful copy, and a clipped giant is
|
|
26
|
+
// better than a batch that the bridge rejects.
|
|
27
|
+
const EVENT_STRING_CLIP = 2_048;
|
|
28
|
+
// Bumped whenever the integration gains something the phone relies on. The bridge
|
|
29
|
+
// compares it with the version it needs, because this file is *copied* into the DSH
|
|
30
|
+
// profile: changing the repository does nothing until install:dsh-phone runs again.
|
|
31
|
+
const INTEGRATION_VERSION = 6;
|
|
32
|
+
// Reconnect pacing. The first attempt is immediate (a bridge restart is usually already
|
|
33
|
+
// over by the time the next poll fails), then it backs off to `RECONNECT_MAX_MS`.
|
|
34
|
+
const RECONNECT_MIN_MS = 1_000;
|
|
35
|
+
const RECONNECT_MAX_MS = 30_000;
|
|
36
|
+
|
|
37
|
+
function sleep(ms, signal) {
|
|
38
|
+
return new Promise((resolve) => {
|
|
39
|
+
if (signal.aborted) return resolve();
|
|
40
|
+
const timer = setTimeout(resolve, ms);
|
|
41
|
+
signal.addEventListener("abort", () => {
|
|
42
|
+
clearTimeout(timer);
|
|
43
|
+
resolve();
|
|
44
|
+
}, { once: true });
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function textFromError(error) {
|
|
49
|
+
return error instanceof Error ? error.message : String(error);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Whether the bridge was simply not there.
|
|
54
|
+
*
|
|
55
|
+
* The distinction matters for the message the user sees: a refused connection
|
|
56
|
+
* means the plugin loaded fine and only the local bridge is missing, which is a
|
|
57
|
+
* setup step — while a 401 from a live bridge is a different problem entirely.
|
|
58
|
+
*/
|
|
59
|
+
function isBridgeAbsent(error) {
|
|
60
|
+
const cause = error && typeof error === "object" ? error.cause?.code ?? "" : "";
|
|
61
|
+
return /ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|UND_ERR_CONNECT|fetch failed|socket hang up/i
|
|
62
|
+
.test(`${textFromError(error)} ${cause}`);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The setup steps a user needs when /phone finds nothing listening. */
|
|
66
|
+
function bridgeSetupText(origin) {
|
|
67
|
+
return [
|
|
68
|
+
`无法连接 AgentBridge 桥(${origin})。插件本身已经加载,缺的是电脑上这个本地服务。`,
|
|
69
|
+
"",
|
|
70
|
+
"手动起桥只要一条命令:",
|
|
71
|
+
"npx @chenacc/agentbridge",
|
|
72
|
+
"",
|
|
73
|
+
"想长期使用就装成全局命令:",
|
|
74
|
+
"npm install -g @chenacc/agentbridge",
|
|
75
|
+
"agentbridge phone --agent claude",
|
|
76
|
+
"",
|
|
77
|
+
`桥启动后再敲一次 /phone。桥不在默认端口的话,先设置环境变量 AGENTBRIDGE_ORIGIN,再重启 DSH Desktop。`,
|
|
78
|
+
].join("\n");
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const BRIDGE_PACKAGE = "@chenacc/agentbridge";
|
|
82
|
+
// Long enough for a detached server to bind its port on a slow disk, short
|
|
83
|
+
// enough that /phone still reads as a command rather than a hang.
|
|
84
|
+
const AUTOSTART_TIMEOUT_MS = 8_000;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Where the bridge's server entry lives on this machine, if it is installed.
|
|
88
|
+
*
|
|
89
|
+
* The plugin ships `@chenacc/agentbridge` as a dependency, so the normal answer
|
|
90
|
+
* comes from module resolution next to this file. `AGENTBRIDGE_BRIDGE_ENTRY`
|
|
91
|
+
* exists for tests and for unusual installs.
|
|
92
|
+
*
|
|
93
|
+
* The resolved manifest must live under a `node_modules` directory: without that
|
|
94
|
+
* check, Node's package self-reference resolves this repository's own root
|
|
95
|
+
* package as `@chenacc/agentbridge`, so a development checkout would start a
|
|
96
|
+
* second bridge from the source tree and steal port 8787 from the developer.
|
|
97
|
+
*/
|
|
98
|
+
function bridgeServerEntry() {
|
|
99
|
+
if (process.env.AGENTBRIDGE_BRIDGE_ENTRY) return process.env.AGENTBRIDGE_BRIDGE_ENTRY;
|
|
100
|
+
try {
|
|
101
|
+
const resolved = fileURLToPath(import.meta.resolve(`${BRIDGE_PACKAGE}/package.json`));
|
|
102
|
+
if (!resolved.split(path.sep).includes("node_modules")) return null;
|
|
103
|
+
return path.join(path.dirname(resolved), "src", "server.js");
|
|
104
|
+
} catch {
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function bridgeIsReady(origin) {
|
|
110
|
+
try {
|
|
111
|
+
const response = await fetch(`${origin}/api/health`, { signal: AbortSignal.timeout(700) });
|
|
112
|
+
if (!response.ok) return false;
|
|
113
|
+
const body = await response.json().catch(() => null);
|
|
114
|
+
return body?.ok === true;
|
|
115
|
+
} catch {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Whether this process may start a bridge at all.
|
|
122
|
+
*
|
|
123
|
+
* A unit test must never spawn a server: node:test sets NODE_TEST_CONTEXT, and a
|
|
124
|
+
* bridge started there would bind a real port and outlive the run. An explicit
|
|
125
|
+
* AGENTBRIDGE_BRIDGE_ENTRY is the single way to opt back in, which is what the
|
|
126
|
+
* autostart test relies on.
|
|
127
|
+
*/
|
|
128
|
+
function autoStartAllowed() {
|
|
129
|
+
if (process.env.AGENTBRIDGE_NO_AUTOSTART === "1") return false;
|
|
130
|
+
if (process.env.AGENTBRIDGE_BRIDGE_ENTRY) return true;
|
|
131
|
+
return process.env.NODE_TEST_CONTEXT === undefined;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Start the local bridge and wait until it answers.
|
|
136
|
+
*
|
|
137
|
+
* Returns true only once the health check passes, so the caller retries the real
|
|
138
|
+
* registration instead of trusting that a spawn means a working server. Every
|
|
139
|
+
* failure path is silent: the caller falls back to the manual setup text.
|
|
140
|
+
*/
|
|
141
|
+
async function startBridge(origin) {
|
|
142
|
+
if (await bridgeIsReady(origin)) return true;
|
|
143
|
+
if (!autoStartAllowed()) return false;
|
|
144
|
+
const entry = bridgeServerEntry();
|
|
145
|
+
if (!entry || !existsSync(entry)) return false;
|
|
146
|
+
|
|
147
|
+
let port;
|
|
148
|
+
try {
|
|
149
|
+
port = new URL(origin).port || "8787";
|
|
150
|
+
} catch {
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
try {
|
|
155
|
+
// Loaded lazily: the plugin normally runs with a bridge already up, so the
|
|
156
|
+
// child-process machinery is dead weight on the common path.
|
|
157
|
+
const { spawn } = await import("node:child_process");
|
|
158
|
+
const child = spawn(process.execPath, [entry], {
|
|
159
|
+
// State belongs next to the user's DSH data, not in whatever directory the
|
|
160
|
+
// desktop happened to launch from.
|
|
161
|
+
cwd: process.env.DSH_HOME || homedir(),
|
|
162
|
+
detached: true,
|
|
163
|
+
stdio: "ignore",
|
|
164
|
+
windowsHide: true,
|
|
165
|
+
env: { ...process.env, AGENTBRIDGE_PORT: process.env.AGENTBRIDGE_PORT || port },
|
|
166
|
+
});
|
|
167
|
+
child.unref();
|
|
168
|
+
} catch {
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const deadline = Date.now() + AUTOSTART_TIMEOUT_MS;
|
|
173
|
+
while (Date.now() < deadline) {
|
|
174
|
+
await new Promise((resolve) => setTimeout(resolve, 150));
|
|
175
|
+
if (await bridgeIsReady(origin)) return true;
|
|
176
|
+
}
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function clipped(value, limit) {
|
|
181
|
+
return typeof value === "string" ? value.slice(0, limit) : "";
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Bound one event's wire size.
|
|
186
|
+
*
|
|
187
|
+
* The bridge rejects a batch over its limit, and a rejected batch is replayed whole
|
|
188
|
+
* on the next flush — so an event that is too big by itself wedges the channel: the
|
|
189
|
+
* same batch fails again and again, nothing ever advances, and the phone goes blind.
|
|
190
|
+
* That loop is what used to fill the desktop log with `Request body is too large`.
|
|
191
|
+
*
|
|
192
|
+
* Clipping long strings keeps the event useful (the phone only ever shows a summary
|
|
193
|
+
* of tool output); the last resort is a stub carrying just the type, because a queued
|
|
194
|
+
* stub is progress while a queued giant is not.
|
|
195
|
+
*/
|
|
196
|
+
function shrinkEventForWire(event) {
|
|
197
|
+
if (JSON.stringify(event).length <= EVENT_EVENT_BUDGET_BYTES) return event;
|
|
198
|
+
const copy = { ...event };
|
|
199
|
+
if (copy.data !== undefined && typeof copy.data === "object") copy.data = { ...copy.data };
|
|
200
|
+
const clipStrings = (value, limit) => {
|
|
201
|
+
if (typeof value === "string") return value.length > limit ? `${value.slice(0, limit)}…[clipped]` : value;
|
|
202
|
+
if (Array.isArray(value)) return value.map((item) => clipStrings(item, limit));
|
|
203
|
+
if (value && typeof value === "object") {
|
|
204
|
+
const result = {};
|
|
205
|
+
for (const [key, child] of Object.entries(value)) result[key] = clipStrings(child, limit);
|
|
206
|
+
return result;
|
|
207
|
+
}
|
|
208
|
+
return value;
|
|
209
|
+
};
|
|
210
|
+
copy.data = clipStrings(copy.data, EVENT_STRING_CLIP);
|
|
211
|
+
if (JSON.stringify(copy).length <= EVENT_EVENT_BUDGET_BYTES) return copy;
|
|
212
|
+
// Pathological: still over the budget after clipping. The phone only needs the
|
|
213
|
+
// event's type to keep the transcript consistent; the payload is display-only.
|
|
214
|
+
return { type: copy.type, time: copy.time, data: { note: "事件过大,手机侧省略了内容" } };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Project one DSH mux frame onto the interaction record the bridge ingests.
|
|
219
|
+
*
|
|
220
|
+
* Only this session's frames matter, and only the four interaction payloads:
|
|
221
|
+
* everything else on the stream is ordinary conversation traffic that already
|
|
222
|
+
* travels on the event channel. Fields are copied out one by one because the
|
|
223
|
+
* frame carries live DSH objects that must not be handed to another process.
|
|
224
|
+
*/
|
|
225
|
+
export function interactionRecord(envelope, sessionId) {
|
|
226
|
+
const payload = envelope?.payload;
|
|
227
|
+
const rpcId = typeof envelope?.rpcId === "string" ? envelope.rpcId : "";
|
|
228
|
+
if (!payload || !rpcId || payload.sessionId !== sessionId) return null;
|
|
229
|
+
if (payload.type === "question/requested") {
|
|
230
|
+
const questions = Array.isArray(payload.questions) ? payload.questions : [];
|
|
231
|
+
const projected = questions.slice(0, 10).flatMap((question, index) => {
|
|
232
|
+
if (!question || typeof question !== "object") return [];
|
|
233
|
+
const questionText = clipped(question.question, 4_000);
|
|
234
|
+
if (!questionText) return [];
|
|
235
|
+
const options = Array.isArray(question.options) ? question.options.slice(0, 25).flatMap((option) => {
|
|
236
|
+
const label = clipped(option?.label, 200);
|
|
237
|
+
if (!label) return [];
|
|
238
|
+
const description = clipped(option?.description, 500);
|
|
239
|
+
return [{ label, ...(description ? { description } : {}) }];
|
|
240
|
+
}) : [];
|
|
241
|
+
const header = clipped(question.header, 200);
|
|
242
|
+
return [{
|
|
243
|
+
id: clipped(question.id, 100) || `q${index + 1}`,
|
|
244
|
+
question: questionText,
|
|
245
|
+
...(header ? { header } : {}),
|
|
246
|
+
...(options.length ? { options } : {}),
|
|
247
|
+
...(question.multiSelect === true ? { multiSelect: true } : {}),
|
|
248
|
+
}];
|
|
249
|
+
});
|
|
250
|
+
if (!projected.length) return null;
|
|
251
|
+
return { kind: "question-requested", requestId: rpcId, questions: projected };
|
|
252
|
+
}
|
|
253
|
+
if (payload.type === "approval/requested") {
|
|
254
|
+
return {
|
|
255
|
+
kind: "approval-requested",
|
|
256
|
+
requestId: rpcId,
|
|
257
|
+
dshApprovalId: clipped(payload.approvalId, 200),
|
|
258
|
+
toolName: clipped(payload.toolName, 200) || "tool",
|
|
259
|
+
...(payload.reason ? { reason: clipped(payload.reason, 2_000) } : {}),
|
|
260
|
+
...(payload.callId ? { callId: clipped(payload.callId, 200) } : {}),
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
if (payload.type === "question/resolved") {
|
|
264
|
+
return { kind: "question-resolved", requestId: clipped(payload.questionRpcId, 200), outcome: clipped(payload.outcome, 40) };
|
|
265
|
+
}
|
|
266
|
+
if (payload.type === "approval/resolved") {
|
|
267
|
+
return {
|
|
268
|
+
kind: "approval-resolved",
|
|
269
|
+
requestId: "",
|
|
270
|
+
dshApprovalId: clipped(payload.approvalId, 200),
|
|
271
|
+
outcome: clipped(payload.outcome, 40),
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function deepFreeze(value) {
|
|
278
|
+
if (!value || typeof value !== "object" || Object.isFrozen(value)) return value;
|
|
279
|
+
for (const child of Object.values(value)) deepFreeze(child);
|
|
280
|
+
return Object.freeze(value);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function createUserMessage(text) {
|
|
284
|
+
return deepFreeze({
|
|
285
|
+
id: randomUUID(),
|
|
286
|
+
role: "user",
|
|
287
|
+
content: [{ type: "text", text }],
|
|
288
|
+
source: { kind: "user" },
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function selectionFromAgent(agent) {
|
|
293
|
+
let logged;
|
|
294
|
+
try {
|
|
295
|
+
logged = agent.session.requestHeader?.()?.config;
|
|
296
|
+
} catch {
|
|
297
|
+
logged = undefined;
|
|
298
|
+
}
|
|
299
|
+
const provider = agent.options?.provider || logged?.provider;
|
|
300
|
+
const model = agent.options?.model || logged?.model;
|
|
301
|
+
if (!provider || !model) return null;
|
|
302
|
+
const reasoningEffort = agent.options?.reasoningEffort || logged?.reasoningEffort;
|
|
303
|
+
return { provider, model, ...(reasoningEffort ? { reasoningEffort } : {}) };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function compactModelDirectory(value, current, extraFailures = []) {
|
|
307
|
+
const groups = Array.isArray(value?.groups) ? value.groups.slice(0, 30).map((group) => ({
|
|
308
|
+
id: group.id,
|
|
309
|
+
name: group.name,
|
|
310
|
+
models: Array.isArray(group.models) ? group.models.slice(0, 200).map((model) => ({
|
|
311
|
+
id: model.id,
|
|
312
|
+
name: model.name,
|
|
313
|
+
...(model.reasoning ? { reasoning: {
|
|
314
|
+
efforts: Array.isArray(model.reasoning.efforts) ? model.reasoning.efforts.slice(0, 20) : [],
|
|
315
|
+
...(model.reasoning.defaultEffort ? { defaultEffort: model.reasoning.defaultEffort } : {}),
|
|
316
|
+
} } : {}),
|
|
317
|
+
})) : [],
|
|
318
|
+
})) : [];
|
|
319
|
+
const failures = [...extraFailures, ...(Array.isArray(value?.failures) ? value.failures : [])].slice(0, 30);
|
|
320
|
+
return {
|
|
321
|
+
current,
|
|
322
|
+
routable: current ? groups.some((group) => group.id === current.provider) : false,
|
|
323
|
+
groups,
|
|
324
|
+
failures,
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
async function readResponse(response) {
|
|
329
|
+
const body = await response.json().catch(() => ({}));
|
|
330
|
+
if (!response.ok) {
|
|
331
|
+
// The status matters to the caller: 401/403/404/409 mean "this channel no
|
|
332
|
+
// longer exists", which is the signal to re-register instead of retrying.
|
|
333
|
+
const error = new Error(body.error || `AgentBridge request failed (${response.status})`);
|
|
334
|
+
error.status = response.status;
|
|
335
|
+
throw error;
|
|
336
|
+
}
|
|
337
|
+
return body;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function isStaleChannel(error) {
|
|
341
|
+
return [401, 403, 404, 409, 410].includes(Number(error?.status));
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export class PhoneConnections {
|
|
345
|
+
constructor(ctx, options = {}) {
|
|
346
|
+
this.ctx = ctx;
|
|
347
|
+
this.bySession = new Map();
|
|
348
|
+
// One lifetime per conversation, independent of any single channel connection.
|
|
349
|
+
// A reconnect tears the connection down (aborting its controller) *before* it knows
|
|
350
|
+
// whether the bridge is back, so a retry loop tied to that controller could only
|
|
351
|
+
// ever run one attempt — the exact bug that left a conversation dead after a manual
|
|
352
|
+
// bridge restart. Only the desktop disposing the conversation ends a lifetime.
|
|
353
|
+
this.lifetimes = new Map();
|
|
354
|
+
this.reconnectMinMs = options.reconnectMinMs ?? RECONNECT_MIN_MS;
|
|
355
|
+
this.reconnectMaxMs = options.reconnectMaxMs ?? RECONNECT_MAX_MS;
|
|
356
|
+
// Failed interaction cards survive a reconnect, so they are keyed to the
|
|
357
|
+
// conversation, not to the channel that tried to carry them.
|
|
358
|
+
this.interactionScopes = new Map();
|
|
359
|
+
this.liveModelSelections = new WeakMap();
|
|
360
|
+
this.ctx.on("session/event", (session, event) => this.captureEvent(session, event));
|
|
361
|
+
this.ctx.on("agent/disposed", ({ agent }) => this.dispose(agent.session.id));
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
lifetimeFor(sessionId) {
|
|
365
|
+
let lifetime = this.lifetimes.get(sessionId);
|
|
366
|
+
if (!lifetime) {
|
|
367
|
+
lifetime = new AbortController();
|
|
368
|
+
this.lifetimes.set(sessionId, lifetime);
|
|
369
|
+
}
|
|
370
|
+
return lifetime;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
async connect(agent, options = {}) {
|
|
374
|
+
this.close(agent.session.id);
|
|
375
|
+
const origin = String(process.env.AGENTBRIDGE_ORIGIN || DEFAULT_ORIGIN).replace(/\/$/, "");
|
|
376
|
+
const modelDirectory = await this.modelDirectory(agent);
|
|
377
|
+
// A conversation the phone asked for registers against the session it already
|
|
378
|
+
// opened, so the bridge binds that one instead of minting a second pairing.
|
|
379
|
+
const bridgeSessionId = typeof options.bridgeSessionId === "string" ? options.bridgeSessionId : "";
|
|
380
|
+
// A reconnect must not consume a pairing code or add a device: the phone that
|
|
381
|
+
// already owns this conversation keeps owning it.
|
|
382
|
+
const reconnecting = options.reconnecting === true;
|
|
383
|
+
const response = await fetch(`${origin}/api/local/dsh-desktop/register`, {
|
|
384
|
+
method: "POST",
|
|
385
|
+
headers: { "content-type": "application/json" },
|
|
386
|
+
body: JSON.stringify({
|
|
387
|
+
sessionId: agent.session.id,
|
|
388
|
+
cwd: agent.session.header.cwd,
|
|
389
|
+
title: agent.session.header.title,
|
|
390
|
+
provider: agent.options.provider,
|
|
391
|
+
model: agent.options.model,
|
|
392
|
+
modelDirectory,
|
|
393
|
+
integrationVersion: INTEGRATION_VERSION,
|
|
394
|
+
...(bridgeSessionId ? { bridgeSessionId } : {}),
|
|
395
|
+
...(reconnecting ? { reconnect: true } : {}),
|
|
396
|
+
}),
|
|
397
|
+
});
|
|
398
|
+
const registration = await readResponse(response);
|
|
399
|
+
const state = {
|
|
400
|
+
agent,
|
|
401
|
+
origin,
|
|
402
|
+
channel: registration.channel,
|
|
403
|
+
controller: new AbortController(),
|
|
404
|
+
lifetime: this.lifetimeFor(agent.session.id),
|
|
405
|
+
cursor: 0,
|
|
406
|
+
pendingEvents: [],
|
|
407
|
+
phoneMessageIds: new Set(),
|
|
408
|
+
// rpc ids this phone already answered, so DSH's own "resolved" echo is
|
|
409
|
+
// not forwarded back and rendered as a second, duplicate resolution.
|
|
410
|
+
answered: new Set(),
|
|
411
|
+
eventTimer: null,
|
|
412
|
+
flushing: false,
|
|
413
|
+
retryPending: false,
|
|
414
|
+
};
|
|
415
|
+
this.bySession.set(agent.session.id, state);
|
|
416
|
+
void this.poll(state);
|
|
417
|
+
void this.watchInteractions(state);
|
|
418
|
+
return registration;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Re-register after the bridge forgot this channel.
|
|
423
|
+
*
|
|
424
|
+
* A bridge restart, a crash, or a replaced channel all look the same from here:
|
|
425
|
+
* every call 401/404/409. Before this, that state was permanent — the only fix
|
|
426
|
+
* was walking back to the computer and running /phone again — so the agent looks
|
|
427
|
+
* dead from the phone while the desktop is perfectly healthy. Reconnecting keeps
|
|
428
|
+
* the same DSH conversation and the same bridge session.
|
|
429
|
+
*
|
|
430
|
+
* There is deliberately no attempt cap. Stopping the bridge by hand (安全停止) and
|
|
431
|
+
* starting it again is a human-scale pause that easily outlives a minute, and giving
|
|
432
|
+
* up then left the conversation dead until someone walked back to the desktop. The
|
|
433
|
+
* only bound is the interval, so a bridge that stays down is polled at most every
|
|
434
|
+
* `RECONNECT_MAX_MS`, and disposing the conversation still stops the loop.
|
|
435
|
+
*/
|
|
436
|
+
async ensureConnection(state) {
|
|
437
|
+
const lifetime = state.lifetime ?? this.lifetimeFor(state.agent.session.id);
|
|
438
|
+
if (lifetime.signal.aborted) return false;
|
|
439
|
+
if (state.reconnecting) return state.reconnecting;
|
|
440
|
+
state.reconnecting = (async () => {
|
|
441
|
+
let delay = 0;
|
|
442
|
+
let attempt = 0;
|
|
443
|
+
while (!lifetime.signal.aborted) {
|
|
444
|
+
// First attempt is immediate (a bridge restart is usually already over);
|
|
445
|
+
// later ones back off so a permanently dead bridge is not hammered.
|
|
446
|
+
if (delay > 0) await sleep(delay, lifetime.signal);
|
|
447
|
+
delay = Math.min(Math.max(delay * 2, this.reconnectMinMs), this.reconnectMaxMs);
|
|
448
|
+
if (lifetime.signal.aborted) return false;
|
|
449
|
+
attempt += 1;
|
|
450
|
+
try {
|
|
451
|
+
await this.connect(state.agent, { reconnecting: true });
|
|
452
|
+
this.ctx.logger.warn?.(`AgentBridge: reconnected "${state.agent.session.header.title ?? state.agent.session.id}" after the bridge forgot the channel (attempt ${attempt})`);
|
|
453
|
+
return true;
|
|
454
|
+
} catch (error) {
|
|
455
|
+
// One line per attempt would bury the desktop log during a long outage.
|
|
456
|
+
if (attempt === 1 || attempt % 10 === 0) {
|
|
457
|
+
this.ctx.logger.warn?.(`AgentBridge reconnect attempt ${attempt} failed: ${textFromError(error)} (still retrying)`);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
return false;
|
|
462
|
+
})().finally(() => { state.reconnecting = null; });
|
|
463
|
+
return state.reconnecting;
|
|
464
|
+
}
|
|
465
|
+
// Interaction retries live on the *lifetime*, not on the channel state. A reconnect
|
|
466
|
+
// (or a dropped channel) throws the state away; a question that failed to cross the
|
|
467
|
+
// wire must survive that, otherwise the phone sees the card a second after the
|
|
468
|
+
// desktop — or not at all, which is the bug this queue removes.
|
|
469
|
+
#interactionScope(sessionId) {
|
|
470
|
+
let scope = this.interactionScopes.get(sessionId);
|
|
471
|
+
if (!scope) {
|
|
472
|
+
scope = { queue: [], draining: false };
|
|
473
|
+
this.interactionScopes.set(sessionId, scope);
|
|
474
|
+
}
|
|
475
|
+
return scope;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// Questions and approvals never reach the session event log with an
|
|
479
|
+
// answerable id, so they are read from DSH's own client stream and answered
|
|
480
|
+
// through `apiProxy.respond`. Same seam the desktop window uses, which is what
|
|
481
|
+
// lets a phone answer a question the desktop is also showing.
|
|
482
|
+
async watchInteractions(state) {
|
|
483
|
+
const events = this.ctx.apiProxy?.events;
|
|
484
|
+
if (typeof events?.mux !== "function") return;
|
|
485
|
+
const sessionId = state.agent.session.id;
|
|
486
|
+
const scope = this.#interactionScope(sessionId);
|
|
487
|
+
// Cards that failed before this channel existed are still owed to the phone.
|
|
488
|
+
void this.#drainInteractions(state, scope, sessionId);
|
|
489
|
+
try {
|
|
490
|
+
for await (const envelope of events.mux({}, state.controller.signal)) {
|
|
491
|
+
if (state.controller.signal.aborted) return;
|
|
492
|
+
const record = interactionRecord(envelope, sessionId);
|
|
493
|
+
if (!record) continue;
|
|
494
|
+
if (this.#claimEcho(state, record)) continue;
|
|
495
|
+
scope.queue.push(record);
|
|
496
|
+
void this.#drainInteractions(state, scope, sessionId);
|
|
497
|
+
}
|
|
498
|
+
} catch (error) {
|
|
499
|
+
if (state.controller.signal.aborted) return;
|
|
500
|
+
if (isStaleChannel(error)) {
|
|
501
|
+
await this.ensureConnection(state);
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
this.ctx.logger.warn(`AgentBridge interaction stream failed: ${textFromError(error)}`);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
async #drainInteractions(state, scope, sessionId) {
|
|
509
|
+
if (scope.draining) return;
|
|
510
|
+
scope.draining = true;
|
|
511
|
+
try {
|
|
512
|
+
while (scope.queue.length > 0) {
|
|
513
|
+
// Always post through whatever channel owns the conversation right now:
|
|
514
|
+
// a reconnect replaced `state`, and the new channel is the only one that
|
|
515
|
+
// the bridge still knows.
|
|
516
|
+
const current = this.bySession.get(sessionId);
|
|
517
|
+
if (!current || current.controller.signal.aborted) return;
|
|
518
|
+
try {
|
|
519
|
+
await this.postInteractions(current, scope.queue[0]);
|
|
520
|
+
scope.queue.shift();
|
|
521
|
+
} catch (error) {
|
|
522
|
+
if (this.bySession.get(sessionId) !== current) return; // replaced; the new drain takes over
|
|
523
|
+
if (isStaleChannel(error)) {
|
|
524
|
+
await this.ensureConnection(current);
|
|
525
|
+
return; // the new state's watchInteractions drains this scope
|
|
526
|
+
}
|
|
527
|
+
// Keep the failed card at the head and retry it: losing it is the bug
|
|
528
|
+
// this queue exists to remove.
|
|
529
|
+
this.ctx.logger.warn(`AgentBridge interaction sync failed: ${textFromError(error)} (kept in the queue)`);
|
|
530
|
+
await sleep(1_000, current.controller.signal);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
} finally {
|
|
534
|
+
scope.draining = false;
|
|
535
|
+
// A newer channel may have taken over while we were waiting; whoever owns
|
|
536
|
+
// the conversation now finishes the queue.
|
|
537
|
+
if (scope.queue.length > 0 && this.interactionScopes.has(sessionId)) {
|
|
538
|
+
const current = this.bySession.get(sessionId);
|
|
539
|
+
if (current) void this.#drainInteractions(current, scope, sessionId);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// Drop the resolution echo of an interaction this phone answered itself.
|
|
545
|
+
#claimEcho(state, record) {
|
|
546
|
+
if (record.kind === "question-resolved" && state.answered.has(record.requestId)) {
|
|
547
|
+
state.answered.delete(record.requestId);
|
|
548
|
+
return true;
|
|
549
|
+
}
|
|
550
|
+
if (record.kind === "approval-resolved" && state.answered.has(`${APPROVAL_PREFIX}${record.dshApprovalId}`)) {
|
|
551
|
+
state.answered.delete(`${APPROVAL_PREFIX}${record.dshApprovalId}`);
|
|
552
|
+
return true;
|
|
553
|
+
}
|
|
554
|
+
return false;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
async postInteractions(state, record) {
|
|
558
|
+
if (!state.channel.interactionsPath) return;
|
|
559
|
+
const response = await fetch(`${state.origin}${state.channel.interactionsPath}`, {
|
|
560
|
+
method: "POST",
|
|
561
|
+
headers: {
|
|
562
|
+
authorization: `Bearer ${state.channel.token}`,
|
|
563
|
+
"content-type": "application/json",
|
|
564
|
+
},
|
|
565
|
+
body: JSON.stringify({ interactions: [record] }),
|
|
566
|
+
signal: state.controller.signal,
|
|
567
|
+
});
|
|
568
|
+
await readResponse(response);
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
async respond(rpcId, result) {
|
|
572
|
+
if (typeof this.ctx.apiProxy?.respond !== "function") throw new Error("This DSH Desktop build cannot answer questions from the phone");
|
|
573
|
+
return await this.ctx.apiProxy.respond({ type: "client-response", rpcId, result });
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
async modelDirectory(agent) {
|
|
577
|
+
const current = selectionFromAgent(agent);
|
|
578
|
+
try {
|
|
579
|
+
const response = await this.ctx.apiProxy.sessions.models({
|
|
580
|
+
rpcId: randomUUID(),
|
|
581
|
+
payload: { sessionId: agent.session.id },
|
|
582
|
+
});
|
|
583
|
+
const result = response?.result;
|
|
584
|
+
if (!result?.ok) {
|
|
585
|
+
if (result?.error?.code === "session-not-found") {
|
|
586
|
+
return await this.hostModelDirectory(current, result.error.message);
|
|
587
|
+
}
|
|
588
|
+
throw new Error(result?.error?.message || "DSH Desktop did not provide its model directory");
|
|
589
|
+
}
|
|
590
|
+
return result.value;
|
|
591
|
+
} catch (error) {
|
|
592
|
+
return {
|
|
593
|
+
current,
|
|
594
|
+
routable: false,
|
|
595
|
+
groups: [],
|
|
596
|
+
failures: [{ id: "dsh-model-directory", name: "DSH Desktop", message: textFromError(error) }],
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
async hostModelDirectory(current, sessionError) {
|
|
602
|
+
const response = await this.ctx.apiProxy.llm.models({ rpcId: randomUUID(), payload: {} });
|
|
603
|
+
const result = response?.result;
|
|
604
|
+
if (!result?.ok) throw new Error(result?.error?.message || "DSH Desktop did not provide its host model directory");
|
|
605
|
+
return compactModelDirectory(result.value, current, [{
|
|
606
|
+
id: "dsh-session-models",
|
|
607
|
+
name: "DSH Desktop",
|
|
608
|
+
message: `当前 UI 会话不在 session.models 注册表中,已改用 DSH 全局模型目录:${sessionError}`,
|
|
609
|
+
}]);
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
liveModelSelection(agent) {
|
|
613
|
+
const existing = this.liveModelSelections.get(agent);
|
|
614
|
+
if (existing) return existing;
|
|
615
|
+
const selection = { current: selectionFromAgent(agent), assembled: undefined };
|
|
616
|
+
agent.ctx.on("system-prompt/assemble", async (_assembly, _context, next) => {
|
|
617
|
+
const selected = selection.current;
|
|
618
|
+
const assembled = await next();
|
|
619
|
+
selection.assembled = selected;
|
|
620
|
+
if (!selected) return assembled;
|
|
621
|
+
return { ...assembled, variables: { ...assembled.variables, provider: selected.provider, model: selected.model } };
|
|
622
|
+
});
|
|
623
|
+
agent.ctx.on("agent/request", async (_payload, next) => {
|
|
624
|
+
const resolved = await next();
|
|
625
|
+
const selected = selection.assembled;
|
|
626
|
+
if (!selected) return resolved;
|
|
627
|
+
const { reasoningEffort: _inheritedEffort, ...withoutInheritedEffort } = resolved;
|
|
628
|
+
return {
|
|
629
|
+
...withoutInheritedEffort,
|
|
630
|
+
provider: selected.provider,
|
|
631
|
+
model: selected.model,
|
|
632
|
+
...(selected.reasoningEffort ? { reasoningEffort: selected.reasoningEffort } : {}),
|
|
633
|
+
};
|
|
634
|
+
});
|
|
635
|
+
this.liveModelSelections.set(agent, selection);
|
|
636
|
+
return selection;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
async selectModel(agent, requested) {
|
|
640
|
+
const response = await this.ctx.apiProxy.sessions.selectModel({
|
|
641
|
+
rpcId: randomUUID(),
|
|
642
|
+
payload: { sessionId: agent.session.id, ...requested },
|
|
643
|
+
});
|
|
644
|
+
const result = response?.result;
|
|
645
|
+
if (result?.ok) return result.value.selected;
|
|
646
|
+
if (result?.error?.code !== "session-not-found") {
|
|
647
|
+
throw new Error(result?.error?.message || "DSH Desktop rejected the model selection");
|
|
648
|
+
}
|
|
649
|
+
const resolved = await this.ctx.llm.resolveCallConfig(requested);
|
|
650
|
+
const selected = {
|
|
651
|
+
provider: resolved.provider,
|
|
652
|
+
model: resolved.model,
|
|
653
|
+
...(resolved.reasoningEffort ? { reasoningEffort: resolved.reasoningEffort } : {}),
|
|
654
|
+
};
|
|
655
|
+
this.liveModelSelection(agent).current = selected;
|
|
656
|
+
return selected;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
async reportCommandResult(state, requestId, result) {
|
|
660
|
+
const response = await fetch(`${state.origin}${state.channel.resultsPath}`, {
|
|
661
|
+
method: "POST",
|
|
662
|
+
headers: {
|
|
663
|
+
authorization: `Bearer ${state.channel.token}`,
|
|
664
|
+
"content-type": "application/json",
|
|
665
|
+
},
|
|
666
|
+
body: JSON.stringify({ requestId, result }),
|
|
667
|
+
signal: state.controller.signal,
|
|
668
|
+
});
|
|
669
|
+
await readResponse(response);
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* Open a new conversation inside this desktop app and hand it to the phone.
|
|
674
|
+
*
|
|
675
|
+
* The conversation has to be a real DSH session, so it is created through the
|
|
676
|
+
* agent service rather than faked in the bridge. Registering it against the
|
|
677
|
+
* bridge session the phone already opened is what resolves the phone's create
|
|
678
|
+
* call; if anything here fails the reason travels back as the command result.
|
|
679
|
+
*/
|
|
680
|
+
async createSession(state, command) {
|
|
681
|
+
try {
|
|
682
|
+
// Read defensively: a build that does not inject `agents` throws on the bare
|
|
683
|
+
// property access, and that raw Cordis error was all the phone ever saw. The
|
|
684
|
+
// try/catch keeps the explanatory error reachable in that case too.
|
|
685
|
+
let service = null;
|
|
686
|
+
try {
|
|
687
|
+
service = this.ctx.agents ?? null;
|
|
688
|
+
} catch {
|
|
689
|
+
service = null;
|
|
690
|
+
}
|
|
691
|
+
const create = typeof service?.create === "function" ? service.create.bind(service) : null;
|
|
692
|
+
if (!create) throw new Error("这个 DSH Desktop 版本不支持从手机新建会话(缺少 ctx.agents.create)");
|
|
693
|
+
const cwd = typeof command.cwd === "string" && command.cwd ? command.cwd : state.agent.session.header.cwd;
|
|
694
|
+
if (!cwd) throw new Error("这个会话没有项目目录,无法新建");
|
|
695
|
+
const sessionId = `session-${randomUUID()}`;
|
|
696
|
+
const options = state.agent.options ?? {};
|
|
697
|
+
const handle = await create({
|
|
698
|
+
sessionId,
|
|
699
|
+
meta: { cwd },
|
|
700
|
+
...(options.provider && options.model
|
|
701
|
+
? { agentOptions: { ...options, provider: options.provider, model: options.model } }
|
|
702
|
+
: {}),
|
|
703
|
+
});
|
|
704
|
+
const agent = handle?.agent;
|
|
705
|
+
if (!agent) throw new Error("DSH Desktop 没有返回新建的会话");
|
|
706
|
+
await this.connect(agent, { bridgeSessionId: command.bridgeSessionId });
|
|
707
|
+
await this.reportCommandResult(state, command.requestId, { ok: true, sessionId: agent.session.id });
|
|
708
|
+
} catch (error) {
|
|
709
|
+
await this.reportCommandResult(state, command.requestId, { ok: false, error: textFromError(error) }).catch(() => undefined);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
async answerQuestion(state, command) {
|
|
714
|
+
const cancelled = command.kind === "cancel-question";
|
|
715
|
+
const answers = Array.isArray(command.answers) ? command.answers : [];
|
|
716
|
+
// Claim the rpc id before answering: DSH broadcasts `question/resolved`
|
|
717
|
+
// while `respond()` is still settling, and the echo must not be forwarded
|
|
718
|
+
// as a second resolution for this same card.
|
|
719
|
+
state.answered.add(command.rpcId);
|
|
720
|
+
try {
|
|
721
|
+
const receipt = await this.respond(command.rpcId, cancelled
|
|
722
|
+
? { ok: false, error: { code: "cancelled", message: "the user skipped the question" } }
|
|
723
|
+
: { ok: true, value: { sessionId: state.agent.session.id, answer: { answers } } });
|
|
724
|
+
if (!receipt?.accepted) {
|
|
725
|
+
state.answered.delete(command.rpcId);
|
|
726
|
+
await this.reportCommandResult(state, command.requestId, {
|
|
727
|
+
ok: false,
|
|
728
|
+
error: `DSH Desktop did not accept this answer (${receipt?.reason ?? "unknown"})`,
|
|
729
|
+
});
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
await this.reportCommandResult(state, command.requestId, { ok: true });
|
|
733
|
+
} catch (error) {
|
|
734
|
+
state.answered.delete(command.rpcId);
|
|
735
|
+
await this.reportCommandResult(state, command.requestId, { ok: false, error: textFromError(error) });
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
async answerApproval(state, command) {
|
|
740
|
+
const key = `${APPROVAL_PREFIX}${command.dshApprovalId}`;
|
|
741
|
+
state.answered.add(key);
|
|
742
|
+
try {
|
|
743
|
+
const receipt = await this.respond(command.rpcId, {
|
|
744
|
+
ok: true,
|
|
745
|
+
value: {
|
|
746
|
+
sessionId: state.agent.session.id,
|
|
747
|
+
approvalId: command.dshApprovalId,
|
|
748
|
+
outcome: command.outcome === "allowed-once" ? "allowed-once" : "rejected",
|
|
749
|
+
},
|
|
750
|
+
});
|
|
751
|
+
if (!receipt?.accepted) {
|
|
752
|
+
state.answered.delete(key);
|
|
753
|
+
await this.reportCommandResult(state, command.requestId, {
|
|
754
|
+
ok: false,
|
|
755
|
+
error: `DSH Desktop did not accept this decision (${receipt?.reason ?? "unknown"})`,
|
|
756
|
+
});
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
await this.reportCommandResult(state, command.requestId, { ok: true });
|
|
760
|
+
} catch (error) {
|
|
761
|
+
state.answered.delete(key);
|
|
762
|
+
await this.reportCommandResult(state, command.requestId, { ok: false, error: textFromError(error) });
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/** Tear the channel down; the conversation itself lives on (a reconnect reuses it). */
|
|
767
|
+
close(sessionId) {
|
|
768
|
+
const state = this.bySession.get(sessionId);
|
|
769
|
+
if (!state) return;
|
|
770
|
+
state.controller.abort();
|
|
771
|
+
if (state.eventTimer) clearTimeout(state.eventTimer);
|
|
772
|
+
this.bySession.delete(sessionId);
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/** The desktop let go of the conversation: stop every loop, including reconnect. */
|
|
776
|
+
dispose(sessionId) {
|
|
777
|
+
this.lifetimes.get(sessionId)?.abort();
|
|
778
|
+
this.lifetimes.delete(sessionId);
|
|
779
|
+
// A disposed conversation can no longer answer its own questions, so the queue
|
|
780
|
+
// that would deliver them goes with it.
|
|
781
|
+
this.interactionScopes.delete(sessionId);
|
|
782
|
+
this.close(sessionId);
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
captureEvent(session, event) {
|
|
786
|
+
const state = this.bySession.get(session.id);
|
|
787
|
+
if (!state || state.controller.signal.aborted) return;
|
|
788
|
+
const origin = event.type === "user/message" && state.phoneMessageIds.delete(event.data?.id)
|
|
789
|
+
? "phone"
|
|
790
|
+
: "desktop";
|
|
791
|
+
// Shrink before queueing: a giant event wedges the channel if it reaches the
|
|
792
|
+
// wire inside a rejected batch, and then every later flush replays it.
|
|
793
|
+
state.pendingEvents.push({ event: shrinkEventForWire(event), origin });
|
|
794
|
+
this.scheduleFlush(state);
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
// Only one batch may be in flight at a time. Overlapping flushes used to let a
|
|
798
|
+
// newer batch overtake an older one, which reordered a turn's streamed text on
|
|
799
|
+
// the phone and made the bridge treat the older batch as already seen.
|
|
800
|
+
scheduleFlush(state) {
|
|
801
|
+
if (state.flushing || state.retryPending || state.eventTimer || state.controller.signal.aborted) return;
|
|
802
|
+
const delay = state.pendingEvents.length >= 50 ? 0 : EVENT_BATCH_DELAY_MS;
|
|
803
|
+
state.eventTimer = setTimeout(() => {
|
|
804
|
+
state.eventTimer = null;
|
|
805
|
+
void this.flushEvents(state);
|
|
806
|
+
}, delay);
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
async flushEvents(state) {
|
|
810
|
+
if (state.flushing || state.retryPending || state.controller.signal.aborted || state.pendingEvents.length === 0) return;
|
|
811
|
+
state.flushing = true;
|
|
812
|
+
let failure = null;
|
|
813
|
+
// One batch per POST, chosen by byte budget as well as item count: the bridge
|
|
814
|
+
// refuses a whole batch that overruns its limit, and a rejected batch is replayed
|
|
815
|
+
// in full on the next flush — so an oversized event wedged the channel behind
|
|
816
|
+
// itself in an endless `Request body is too large` loop. Each item here was
|
|
817
|
+
// already shrunk at capture time, so a batch under the budget always gets through.
|
|
818
|
+
while (state.pendingEvents.length > 0 && !state.controller.signal.aborted && !failure) {
|
|
819
|
+
const batch = [];
|
|
820
|
+
let bytes = 12; // `{"events":[`
|
|
821
|
+
for (let count = 0; count < EVENT_MAX_ITEMS && state.pendingEvents.length > 0; count += 1) {
|
|
822
|
+
const item = state.pendingEvents.shift();
|
|
823
|
+
const itemBytes = JSON.stringify(item).length + 1;
|
|
824
|
+
if (bytes + itemBytes > EVENT_POST_BUDGET_BYTES && batch.length > 0) {
|
|
825
|
+
state.pendingEvents.unshift(item);
|
|
826
|
+
break;
|
|
827
|
+
}
|
|
828
|
+
batch.push(item);
|
|
829
|
+
bytes += itemBytes;
|
|
830
|
+
}
|
|
831
|
+
// should not happen: items are shrunk at capture time; a lone item over the
|
|
832
|
+
// budget would wedge the loop, so send it as-is and let the bridge's own cap
|
|
833
|
+
// (1 MB, above the per-item budget) be the safety net.
|
|
834
|
+
if (batch.length === 0) {
|
|
835
|
+
batch.push(state.pendingEvents.shift());
|
|
836
|
+
}
|
|
837
|
+
let failed = null;
|
|
838
|
+
try {
|
|
839
|
+
const response = await fetch(`${state.origin}${state.channel.eventsPath}`, {
|
|
840
|
+
method: "POST",
|
|
841
|
+
headers: {
|
|
842
|
+
authorization: `Bearer ${state.channel.token}`,
|
|
843
|
+
"content-type": "application/json",
|
|
844
|
+
},
|
|
845
|
+
body: JSON.stringify({ events: batch }),
|
|
846
|
+
signal: state.controller.signal,
|
|
847
|
+
});
|
|
848
|
+
await readResponse(response);
|
|
849
|
+
} catch (error) {
|
|
850
|
+
failed = error;
|
|
851
|
+
state.pendingEvents.unshift(...batch);
|
|
852
|
+
}
|
|
853
|
+
if (failed) {
|
|
854
|
+
failure = failed;
|
|
855
|
+
break;
|
|
856
|
+
}
|
|
857
|
+
if (state.controller.signal.aborted) break;
|
|
858
|
+
}
|
|
859
|
+
state.flushing = false;
|
|
860
|
+
if (state.controller.signal.aborted) return;
|
|
861
|
+
|
|
862
|
+
if (failure && isStaleChannel(failure)) {
|
|
863
|
+
await this.ensureConnection(state);
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
if (failure) {
|
|
867
|
+
this.ctx.logger.warn(`AgentBridge event sync failed: ${textFromError(failure)}`);
|
|
868
|
+
// Hold everything back until the failed batch has been retried, so the
|
|
869
|
+
// bridge never receives a newer batch ahead of an older one.
|
|
870
|
+
state.retryPending = true;
|
|
871
|
+
await sleep(1_000, state.controller.signal);
|
|
872
|
+
state.retryPending = false;
|
|
873
|
+
if (!state.controller.signal.aborted) void this.flushEvents(state);
|
|
874
|
+
return;
|
|
875
|
+
}
|
|
876
|
+
if (state.pendingEvents.length) this.scheduleFlush(state);
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
async poll(state) {
|
|
880
|
+
while (!state.controller.signal.aborted) {
|
|
881
|
+
try {
|
|
882
|
+
const response = await fetch(`${state.origin}${state.channel.pollPath}?after=${state.cursor}`, {
|
|
883
|
+
headers: { authorization: `Bearer ${state.channel.token}` },
|
|
884
|
+
signal: state.controller.signal,
|
|
885
|
+
});
|
|
886
|
+
const body = await readResponse(response);
|
|
887
|
+
for (const command of body.commands || []) {
|
|
888
|
+
if (command.kind === "message") {
|
|
889
|
+
const message = createUserMessage(command.text);
|
|
890
|
+
state.phoneMessageIds.add(message.id);
|
|
891
|
+
state.agent.followup(message);
|
|
892
|
+
} else if (command.kind === "cancel") {
|
|
893
|
+
state.agent.cancel({ kind: "user" }, { keepInbox: true });
|
|
894
|
+
} else if (command.kind === "select-model") {
|
|
895
|
+
try {
|
|
896
|
+
const selected = await this.selectModel(state.agent, {
|
|
897
|
+
provider: command.selection?.provider,
|
|
898
|
+
model: command.selection?.model,
|
|
899
|
+
...(command.selection?.reasoningEffort ? { reasoningEffort: command.selection.reasoningEffort } : {}),
|
|
900
|
+
});
|
|
901
|
+
await this.reportCommandResult(state, command.requestId, { ok: true, selected });
|
|
902
|
+
} catch (error) {
|
|
903
|
+
await this.reportCommandResult(state, command.requestId, { ok: false, error: textFromError(error) });
|
|
904
|
+
}
|
|
905
|
+
} else if (command.kind === "answer-question" || command.kind === "cancel-question") {
|
|
906
|
+
await this.answerQuestion(state, command);
|
|
907
|
+
} else if (command.kind === "create-session") {
|
|
908
|
+
await this.createSession(state, command);
|
|
909
|
+
} else if (command.kind === "answer-approval") {
|
|
910
|
+
await this.answerApproval(state, command);
|
|
911
|
+
}
|
|
912
|
+
state.cursor = Math.max(state.cursor, command.seq);
|
|
913
|
+
}
|
|
914
|
+
} catch (error) {
|
|
915
|
+
if (state.controller.signal.aborted) return;
|
|
916
|
+
if (isStaleChannel(error)) {
|
|
917
|
+
await this.ensureConnection(state);
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
this.ctx.logger.warn(`AgentBridge command polling failed: ${textFromError(error)}`);
|
|
921
|
+
}
|
|
922
|
+
await sleep(POLL_DELAY_MS, state.controller.signal);
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
function apply(ctx) {
|
|
928
|
+
const connections = new PhoneConnections(ctx);
|
|
929
|
+
ctx.commands.register({
|
|
930
|
+
name: "phone",
|
|
931
|
+
description: "pair this exact DSH Desktop conversation with a phone",
|
|
932
|
+
recordInput: false,
|
|
933
|
+
handler: async ({ agent }) => {
|
|
934
|
+
if (!agent.session.header.cwd) {
|
|
935
|
+
return { kind: "error", text: "当前会话没有项目目录,无法绑定手机。请先在项目文件夹中打开会话。" };
|
|
936
|
+
}
|
|
937
|
+
try {
|
|
938
|
+
const registration = await connections.connect(agent);
|
|
939
|
+
const model = [agent.options.provider, agent.options.model].filter(Boolean).join(" / ") || "当前 DSH 配置";
|
|
940
|
+
return {
|
|
941
|
+
kind: "success",
|
|
942
|
+
text: [
|
|
943
|
+
"手机接管二维码已生成(5 分钟内、仅可使用一次):",
|
|
944
|
+
``,
|
|
945
|
+
registration.pairing.url,
|
|
946
|
+
`项目:${registration.project.cwd}`,
|
|
947
|
+
`会话:${agent.session.id}`,
|
|
948
|
+
`模型:${model}`,
|
|
949
|
+
].join("\n\n"),
|
|
950
|
+
};
|
|
951
|
+
} catch (error) {
|
|
952
|
+
const origin = String(process.env.AGENTBRIDGE_ORIGIN || DEFAULT_ORIGIN).replace(/\/$/, "");
|
|
953
|
+
return {
|
|
954
|
+
kind: "error",
|
|
955
|
+
text: isBridgeAbsent(error)
|
|
956
|
+
? bridgeSetupText(origin)
|
|
957
|
+
: `无法连接 AgentBridge:${textFromError(error)}。请确认本机 ${origin} 正在运行。`,
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
},
|
|
961
|
+
});
|
|
962
|
+
|
|
963
|
+
// Bring the bridge up in the background as soon as the plugin loads, so by the
|
|
964
|
+
// time the user types /phone the local service is already there. Deliberately
|
|
965
|
+
// not awaited: a slow spawn must never delay desktop startup, and every failure
|
|
966
|
+
// is silent — /phone still prints the manual steps when nothing came up.
|
|
967
|
+
void startBridge(String(process.env.AGENTBRIDGE_ORIGIN || DEFAULT_ORIGIN).replace(/\/$/, "")).catch(() => {});
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
export { apply, inject, name };
|