File size: 119,494 Bytes
625dafa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
#!/usr/bin/env python3
import asyncio
import os
import re
import shutil
import signal
import subprocess
import json
import platform
import time
import uuid
import tempfile
import socket
import glob as std_glob
import fnmatch
from pathlib import Path
from typing import AsyncIterator, Tuple
from datetime import datetime
from collections import deque
import aiofiles
import aiofiles.os
import hashlib
import anyio
from py.get_setting import load_settings
from py.get_setting import SKILLS_DIR,IS_DOCKER

COMMAND_TIMEOUT = 300  # 5分钟超时

# ==================== 环境初始化 ====================

try:
    from zerobox import Sandbox, SandboxCommandError
    HAS_ZEROBOX = True
except ImportError:
    HAS_ZEROBOX = False

def get_shell_environment():
    """通过子进程获取完整的 shell 环境"""
    shell = os.environ.get('SHELL', '/bin/zsh')
    home = Path.home()
    
    config_commands = [
        f'source {home}/.zshrc && env',
        f'source {home}/.bash_profile && env', 
        f'source {home}/.bashrc && env',
        'env'
    ]
    
    # Windows 环境简单跳过
    if platform.system() == "Windows":
        return

    for cmd in config_commands:
        try:
            result = subprocess.run(
                [shell, '-i', '-c', cmd],
                capture_output=True,
                text=True,
                timeout=5
            )
            if result.returncode == 0:
                for line in result.stdout.splitlines():
                    if '=' in line:
                        var_name, var_value = line.split('=', 1)
                        os.environ[var_name] = var_value
                print("Successfully loaded environment from shell")
                return
        except Exception as e:
            continue
    
    print("Warning: Could not load shell environment, using current environment")

get_shell_environment()

# ==================== 核心基础设施:流处理 ====================


async def read_stream(stream, *, is_error: bool = False):
    """
    改进的流读取器:支持多编码回退,确保能抓取到系统原始报错。
    """
    if stream is None:
        return
    
    prefix = "[ERROR] " if is_error else ""
    
    while True:
        line_bytes = await stream.readline()
        if not line_bytes:
            break
            
        decoded = ""
        # 依次尝试:UTF-8 -> GBK (Windows) -> CP437 -> 替换模式
        for enc in ['utf-8', 'gbk', 'cp437']:
            try:
                decoded = line_bytes.decode(enc).rstrip()
                break
            except UnicodeDecodeError:
                continue
        
        if not decoded:
            decoded = line_bytes.decode('utf-8', errors='replace').rstrip()
            
        yield f"{prefix}{decoded}"

# 修改 read_stream 为分块读取,防止进度条挂起
async def read_stream_chunks(stream, prefix=""):
    """
    分块读取流,不等待换行符,解决进度条显示问题。
    """
    if stream is None:
        return
    
    try:
        while True:
            # 读取 4KB 数据块
            chunk = await stream.read(4096)
            if not chunk:
                break
            
            # 尝试多种编码解码
            decoded = ""
            for enc in ['utf-8', 'gbk', 'cp437']:
                try:
                    decoded = chunk.decode(enc)
                    break
                except UnicodeDecodeError:
                    continue
            
            if not decoded:
                decoded = chunk.decode('utf-8', errors='replace')
            
            if decoded:
                yield f"{prefix}{decoded}"
    except Exception as e:
        yield f"[System Stream Error] {e}"


async def _merge_streams(*streams):
    """合并多个异步流"""
    streams = [s.__aiter__() for s in streams]
    while streams:
        for stream in list(streams):
            try:
                item = await stream.__anext__()
                yield item
            except StopAsyncIteration:
                streams.remove(stream)

async def _get_current_cwd() -> str:
    """获取当前配置的工作目录"""
    settings = await load_settings()
    cwd = settings.get("CLISettings", {}).get("cc_path")
    if not cwd:
        raise ValueError("No workspace directory specified in settings (CLISettings.cc_path).")
    return cwd

def get_detailed_exit_info(code: int, command: str) -> str:
    """
    根据退出码和操作系统,生成详细的诊断信息 and 建议。
    """
    cmd_name = command.strip().split()[0] if command.strip() else "unknown"
    system = platform.system()
    
    # 基础映射
    explanations = {
        1: "提示: 退出码 1 表示命令执行失败,请仔细阅读上方输出中的错误信息(如 Error、Fatal、error 关键字)以确定具体原因。",
        2: "Shell 内置命令使用不当。",
        126: "命令不可执行 (权限不足或不是可执行文件)。",
        127: "找不到命令 (Linux/Unix)。",
        130: "由 Control-C 终止。",
        137: "进程被强制杀死 (可能触发了 OOM 内存溢出)。",
        # Windows 特有
        9009: f"Windows: 找不到命令 '{cmd_name}'。请检查程序是否已安装,或是否已加入 PATH 环境变量。",
        5: "Windows: 拒绝访问 (权限不足)。",
    }
    
    info = f"\n[诊断信息] 进程退出码: {code}\n"
    info += f"[解释] {explanations.get(code, '未知错误类型')}\n"
    
    if code in [127, 9009]:
        info += f"💡 建议:\n"
        if system == "Windows":
            info += f"  1. 运行 'where {cmd_name}' 检查程序位置。\n"
            info += f"  2. 如果是刚安装的软件,可能需要重启 Agent 或使用绝对路径。\n"
        else:
            info += f"  1. 运行 'which {cmd_name}' 检查程序位置。\n"
            info += f"  2. 检查环境变量: 'echo $PATH'\n"
            
    return info




# 辅助函数:统计首尾的空行数量
def count_empty_padding(lines):
    start = 0
    while start < len(lines) and not lines[start].strip():
        start += 1
    end = 0
    while end < len(lines) and not lines[len(lines)-1-end].strip():
        end += 1
    return start, end

def _apply_patch(content: str, old_string: str, new_string: str, replace_all: bool = False) -> tuple[bool, str, str]:
    """
    高度鲁棒的补丁应用算法,解决 AI 换行符幻觉和"空行不断膨胀"的问题。
    """
    # 统一换行符为 \n
    content_lf = content.replace('\r\n', '\n')
    old_lf = old_string.replace('\r\n', '\n')
    new_lf = new_string.replace('\r\n', '\n')

    # 1. 绝对精确匹配 (速度最快,且绝不产生多余空行)
    if old_lf in content_lf:
        if replace_all:
            # 检查是否至少有一个匹配(str.replace 自身会处理)
            new_content = content_lf.replace(old_lf, new_lf)
            count = content_lf.count(old_lf)
            return True, new_content, f"Replaced {count} occurrence(s)."
        else:
            count = content_lf.count(old_lf)
            if count > 1:
                return False, content, f"[Error] old_string found {count} times in file. Provide more surrounding context to make it unique, or use replace_all=True."
            return True, content_lf.replace(old_lf, new_lf, 1), "Exact match successful."

    # 2. 智能模糊匹配阶段
    content_lines = content_lf.split('\n')
    old_lines = old_lf.split('\n')
    new_lines = new_lf.split('\n')


    # 统计并剥离 old_lines 首尾用来凑格式的空行
    old_pad_start, old_pad_end = count_empty_padding(old_lines)
    old_actual_end = len(old_lines) - old_pad_end
    old_stripped = old_lines[old_pad_start : old_actual_end]
    
    if not old_stripped:
        return False, content, "old_string is empty or only contains whitespaces."

    # 滑动窗口匹配
    def find_all_matches(ignore_leading=False):
        matches = []
        for i in range(len(content_lines) - len(old_stripped) + 1):
            match = True
            for j in range(len(old_stripped)):
                c_line = content_lines[i+j].rstrip()
                o_line = old_stripped[j].rstrip()
                if ignore_leading:
                    c_line = c_line.lstrip()
                    o_line = o_line.lstrip()
                if c_line != o_line:
                    match = False
                    break
            if match:
                matches.append(i)
        return matches

    def find_match(ignore_leading=False):
        for i in range(len(content_lines) - len(old_stripped) + 1):
            match = True
            for j in range(len(old_stripped)):
                c_line = content_lines[i+j].rstrip()
                o_line = old_stripped[j].rstrip()
                if ignore_leading:
                    c_line = c_line.lstrip()
                    o_line = o_line.lstrip()
                if c_line != o_line:
                    match = False
                    break
            if match:
                return i
        return -1

    if replace_all:
        # replace_all: 找到所有模糊匹配并替换
        matches = find_all_matches(ignore_leading=False)
        match_type = "Fuzzy match (trailing whitespace)"
        if not matches:
            matches = find_all_matches(ignore_leading=True)
            match_type = "Fuzzy match (leading+trailing whitespace)"

        if matches:
            # 从后往前替换,防止索引偏移
            new_pad_start, new_pad_end = count_empty_padding(new_lines)
            strip_front = min(old_pad_start, new_pad_start)
            strip_back = min(old_pad_end, new_pad_end)
            new_actual_end = len(new_lines) - strip_back
            new_final = new_lines[strip_front : new_actual_end]

            result_lines = list(content_lines)
            for match_idx in reversed(matches):
                end_idx = match_idx + len(old_stripped)
                result_lines[match_idx:end_idx] = new_final

            new_content = '\n'.join(result_lines)
            return True, new_content, f"{match_type} - replaced {len(matches)} occurrence(s)."

        # 匹配失败
        first_line_clean = old_stripped[0].strip()
        candidates = []
        for i, line in enumerate(content_lines):
            if first_line_clean and first_line_clean in line:
                candidates.append(f"Line {i+1}: {line.strip()[:80]}")
        err_msg = "[Error] old_string not found in file. Check line endings or indentation.\n"
        if candidates:
            err_msg += "Did you mean one of these locations?\n" + "\n".join(candidates[:5])
        return False, content, err_msg

    match_idx = find_match(ignore_leading=False)
    msg = "Fuzzy match successful (ignored trailing whitespaces)."
    if match_idx == -1:
        match_idx = find_match(ignore_leading=True)
        msg = "Fuzzy match successful (ignored leading/trailing whitespaces)."

    if match_idx != -1:
        # 切片截取被保留的原文
        pre = content_lines[:match_idx]
        post = content_lines[match_idx + len(old_stripped):]
        
        # --- 杜绝空行膨胀的核心逻辑 ---
        new_pad_start, new_pad_end = count_empty_padding(new_lines)
        
        # 抵消 AI 在 old 和 new 中同时附带的无用上下文空行
        # 只有当 AI 故意在 new_string 中多加了空行时(即差值),才将其写入文件
        strip_front = min(old_pad_start, new_pad_start)
        strip_back = min(old_pad_end, new_pad_end)
        
        new_actual_end = len(new_lines) - strip_back
        new_final = new_lines[strip_front : new_actual_end]
        
        # 核心修复:使用纯 List 合并,绝对不硬编码拼接额外的 "\n"
        new_content = '\n'.join(pre + new_final + post)
        return True, new_content, msg

    # 匹配失败,生成带行号的纠错建议给 AI
    first_line_clean = old_stripped[0].strip()
    candidates =[]
    for i, line in enumerate(content_lines):
        if first_line_clean and first_line_clean in line:
            candidates.append(f"Line {i+1}: {line.strip()[:80]}")
            
    err_msg = "[Error] old_string not found in file. Check line endings or indentation.\n"
    if candidates:
        err_msg += "Did you mean one of these locations?\n" + "\n".join(candidates[:5])
    return False, content, err_msg

# ==================== [新增] 核心基础设施:进程管理 ====================

class ProcessManager:
    """全局后台进程管理器 (Docker & Local) - 增强版 (支持 Windows 进程树查杀)"""
    def __init__(self):
        # 结构: {pid: {"proc": proc, "logs": deque, "cmd": str, "type": str, "task": task, "status": str, "start_time": str}}
        self._processes = {}
        self._counter = 0

    def generate_id(self):
        self._counter += 1
        return str(self._counter)

    async def register_process(self, proc, cmd: str, p_type: str):
        """注册并开始监控一个后台进程"""
        pid = self.generate_id()
        logs = deque(maxlen=2000)
        
        task = asyncio.create_task(self._monitor_output(pid, proc, logs))
        
        self._processes[pid] = {
            "proc": proc,
            "logs": logs,
            "cmd": cmd,
            "type": p_type,
            "task": task,
            "status": "running",
            "start_time": datetime.now().isoformat()
        }
        return pid

    async def send_input(self, pid: str, text: str) -> str:
        """
        往指定的后台进程中发送输入(模拟键盘敲击,例如输入 'y\n')
        """
        if pid not in self._processes:
            return f"Error: Process ID {pid} not found."
        
        info = self._processes[pid]
        proc = info["proc"]
        
        if proc.returncode is not None:
            return f"Error: Process {pid} has already exited with code {proc.returncode}."
            
        if not proc.stdin:
            return f"Error: Process {pid} was not started with stdin enabled."
            
        try:
            # 确保发送的文本以换行符结尾,模拟用户按下回车键
            if not text.endswith('\n'):
                text += '\n'
                
            proc.stdin.write(text.encode('utf-8'))
            await proc.stdin.drain()
            
            return f"Successfully sent input '{text.strip()}' to process {pid}."
        except Exception as e:
            return f"Failed to send input: {str(e)}"

    async def _monitor_output(self, pid: str, proc, logs: deque):
        async def read_stream_to_log(stream, prefix=""):
            if not stream: return
            try:
                while True:
                    # 改为读取分块,不再使用 readline()
                    chunk = await stream.read(1024) 
                    if not chunk:
                        break
                    
                    decoded = ""
                    for enc in ['utf-8', 'gbk', 'cp437']:
                        try:
                            decoded = chunk.decode(enc)
                            break
                        except UnicodeDecodeError:
                            continue
                    if not decoded:
                        decoded = chunk.decode('utf-8', errors='replace')

                    timestamp = datetime.now().strftime("%H:%M:%S")
                    
                    # 处理回车符 \r,将其替换为换行,这样 log 中能看到进度条的每一步更新
                    # 如果不需要保留进度条每一行,可以直接 decoded.strip()
                    lines = decoded.replace('\r', '\n').splitlines()
                    for line in lines:
                        if line.strip():
                            logs.append(f"[{timestamp}] {prefix}{line}")
            except Exception as e:
                logs.append(f"[SYSTEM ERROR] {prefix}Monitoring failed: {str(e)}")

        try:
            await asyncio.gather(
                read_stream_to_log(proc.stdout, ""),
                read_stream_to_log(proc.stderr, "[ERR] ")
            )
            await proc.wait()
            if pid in self._processes:
                if "terminated" not in self._processes[pid]["status"]:
                    self._processes[pid]["status"] = f"exited (code {proc.returncode})"
        except Exception:
            pass

    def get_logs(self, pid: str, lines: int = 50) -> str:
        if pid not in self._processes:
            return f"Error: Process ID {pid} not found."
        
        entry = self._processes[pid]
        stored_logs = list(entry["logs"])
        subset = stored_logs[-lines:] if lines > 0 else stored_logs
        
        header = f"--- Logs for Process {pid} ({entry['status']}) ---\nCommand: {entry['cmd']}\n"
        return header + "\n".join(subset)

    def list_processes(self):
        if not self._processes:
            return "No background processes running."
        
        result = ["PID | Type   | Status       | Start Time          | Command"]
        result.append("-" * 90)
        
        active_found = False
        for pid, info in list(self._processes.items()):
            cmd_display = (info['cmd'][:45] + '...') if len(info['cmd']) > 45 else info['cmd']
            start_time = info['start_time'].split('T')[-1][:8]
            result.append(f"{pid:<4}| {info['type']:<7}| {info['status']:<13}| {start_time:<20}| {cmd_display}")
            active_found = True
        
        if not active_found:
            return "No background processes running."
        return "\n".join(result)

    async def kill_process(self, pid: str):
        """
        强制结束进程。
        针对 Windows 使用 taskkill /T 结束进程树,防止子进程残留。
        """
        if pid not in self._processes:
            return f"Error: Process ID {pid} not found."
        
        info = self._processes[pid]
        proc = info["proc"]
        
        # 即使 proc.returncode 已经有值,也要尝试清理可能的孤儿进程
        os_pid = proc.pid
        
        try:
            info["status"] = "terminating..."
            
            if platform.system() == "Windows":
                # Windows: 使用 taskkill /F (强制) /T (进程树) /PID <pid>
                # 这是清理 PowerShell/CMD 启动的子进程的关键
                kill_cmd = f"taskkill /F /T /PID {os_pid}"
                subprocess.run(kill_cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            else:
                # Linux/Mac: 尝试杀进程组 (如果适用) 或标准 terminate
                try:
                    proc.terminate()
                    # 给一点时间优雅退出
                    await asyncio.wait_for(proc.wait(), timeout=2.0)
                except (asyncio.TimeoutError, ProcessLookupError):
                    try:
                        proc.kill()
                    except:
                        pass
            
            info["status"] = "terminated"
            return f"Process {pid} (OS PID {os_pid}) terminated successfully."
            
        except Exception as e:
            return f"Error terminating process {pid}: {str(e)}"
        
    async def kill_all(self):
        """
        关闭所有注册在管理器中的活动进程。
        """
        active_pids = []
        for pid, info in list(self._processes.items()):
            # 过滤掉已经退出的进程
            status = info.get("status", "")
            if "exited" not in status and "terminated" not in status:
                active_pids.append(pid)
        
        if not active_pids:
            return "No active processes to clean up."
            
        print(f"Found {len(active_pids)} active background processes. Terminating...")
        
        # 并发执行清理任务
        tasks = [self.kill_process(pid) for pid in active_pids]
        results = await asyncio.gather(*tasks, return_exceptions=True)
        
        # 打印清理结果
        for pid, res in zip(active_pids, results):
            if isinstance(res, Exception):
                print(f"[Warn] Failed to kill process {pid}: {res}")
            else:
                print(f"[Info] Process cleanup: {res}")

process_manager = ProcessManager()

# ==================== [新增] 核心基础设施:Docker 网络代理 ====================

async def send_process_input_tool(pid: str, text: str) -> str:
    """[Common] 往指定的后台进程发送交互输入(stdin)"""
    if not pid:
        return "Error: 'pid' is required to send input."
    return await process_manager.send_input(pid, text)

class DockerPortProxy:
    """纯 Python 实现的 Docker 端口转发器 (Container -> Host)"""
    def __init__(self, container_name: str):
        self.container_name = container_name
        self.proxies = {} # {local_port: server_obj}

    async def start_forward(self, local_port: int, container_port: int):
        """开启转发:本地 TCP Server -> docker exec 桥接 -> 容器内部端口"""
        if local_port in self.proxies:
            return f"Port {local_port} is already being forwarded."

        if not self._is_port_available(local_port):
            return f"Error: Local port {local_port} is already in use."

        try:
            server = await asyncio.start_server(
                lambda r, w: self._handle_client(r, w, container_port),
                '127.0.0.1', local_port
            )
            
            self.proxies[local_port] = server
            asyncio.create_task(server.serve_forever())
            return f"Success: Forwarding localhost:{local_port} -> Docker:{container_port}"
        except Exception as e:
            return f"Error starting proxy: {str(e)}"

    def _is_port_available(self, port: int) -> bool:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            return s.connect_ex(('127.0.0.1', port)) != 0

    async def _handle_client(self, client_reader, client_writer, container_port):
        """处理每个连接:启动一个 docker exec 进程作为管道"""
        try:
            # 微型 Python 转发脚本,在容器内运行
            proxy_script = (
                "import socket,sys,threading;"
                "s=socket.socket();"
                f"s.connect(('127.0.0.1',{container_port}));"
                "def r():"
                " while True:"
                "  d=s.recv(4096);"
                "  if not d: break;"
                "  sys.stdout.buffer.write(d);sys.stdout.flush();\n"
                "threading.Thread(target=r,daemon=True).start();"
                "while True:"
                " d=sys.stdin.buffer.read(4096);"
                " if not d: break;"
                " s.sendall(d)"
            )

            cmd = [
                "docker", "exec", "-i", 
                self.container_name, 
                "python3", "-u", "-c", proxy_script
            ]

            proc = await asyncio.create_subprocess_exec(
                *cmd,
                stdin=asyncio.subprocess.PIPE,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.DEVNULL 
            )

            async def pipe_reader_to_writer(reader, writer):
                try:
                    while True:
                        data = await reader.read(4096)
                        if not data: break
                        writer.write(data)
                        await writer.drain()
                except Exception:
                    pass
                finally:
                    try: writer.close()
                    except: pass

            await asyncio.gather(
                pipe_reader_to_writer(client_reader, proc.stdin),  # Local -> Docker
                pipe_reader_to_writer(proc.stdout, client_writer)  # Docker -> Local
            )
            try: proc.terminate()
            except: pass

        except Exception as e:
            try: client_writer.close()
            except: pass

    async def stop_forward(self, local_port: int):
        if local_port in self.proxies:
            server = self.proxies[local_port]
            server.close()
            await server.wait_closed()
            del self.proxies[local_port]
            return f"Stopped forwarding on port {local_port}"
        return f"Port {local_port} was not being forwarded."
    
    def list_proxies(self):
        if not self.proxies:
            return "No active port forwardings."
        return "\n".join([f"localhost:{p} -> container:{p} (active)" for p in self.proxies.keys()])

DOCKER_PROXIES = {} # {container_name: ProxyInstance}

# ==================== Docker Sandbox 基础设施 ====================

def get_safe_container_name(cwd: str) -> str:
    """根据路径生成合法容器名"""
    abs_path = str(Path(cwd).resolve())
    path_hash = hashlib.md5(abs_path.encode()).hexdigest()[:12]
    return f"sandbox-{path_hash}"

async def get_or_create_docker_sandbox(cwd: str, image_name: str = "docker/sandbox-templates:claude-code") -> str:
    """获取或创建基于路径的持久化沙盒,并映射全局skills目录"""
    container_name = get_safe_container_name(cwd)
    
    # 获取主机的全局skills目录
    host_skills_dir = SKILLS_DIR
    
    check_proc = await asyncio.create_subprocess_exec(
        "docker", "ps", "-a", "--filter", f"name=^/{container_name}$", "--format", "{{.Names}}|{{.Status}}",
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE
    )
    stdout, _ = await check_proc.communicate()
    output = stdout.decode().strip()
    
    if container_name in output:
        status = output.split("|")[-1] if "|" in output else ""
        if "Up" in status:
            return container_name
        else:
            # 启动已存在的容器
            await asyncio.create_subprocess_exec("docker", "start", container_name, stdout=asyncio.subprocess.PIPE)
            return container_name
    
    # 创建新容器,映射主机的全局skills目录
    # 注意:我们将主机skills目录映射到容器内的 /root/.agents/skills
    # 这是标准Agent Skills CLI使用的路径
    create_cmd = [
        "docker", "run", "-d",
        "--name", container_name,
        "-v", f"{cwd}:/workspace",  # 映射工作目录
        "-v", f"{host_skills_dir}:/home/agent/.agents/skills",   # 映射全局skills目录到容器内
        "-w", "/workspace",
        "--restart", "unless-stopped",
        image_name,
        "tail", "-f", "/dev/null"
    ]
    
    proc = await asyncio.create_subprocess_exec(
        *create_cmd,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE
    )
    stdout, stderr = await proc.communicate()
    
    if proc.returncode == 0:
        # 容器创建成功,确保容器内的skills目录权限正确
        try:
            # 设置容器内skills目录的权限
            chown_cmd = [
                "docker", "exec", container_name,
                "chown", "-R", "root:root", "/root/.agents/skills"
            ]
            chown_proc = await asyncio.create_subprocess_exec(
                *chown_cmd,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE
            )
            await chown_proc.communicate()
        except Exception:
            # 权限设置失败不影响主要功能
            pass
        
        return container_name
    else:
        # 简单重试逻辑
        if "is already in use" in stderr.decode():
            await asyncio.sleep(0.5)
            return await get_or_create_docker_sandbox(cwd, image_name)
        raise Exception(f"Failed to create sandbox: {stderr.decode()}")


async def _exec_docker_cmd_simple(cwd: str, cmd_list: list) -> str:
    """内部辅助函数:在容器内执行简单命令并获取输出"""
    container_name = await get_or_create_docker_sandbox(cwd)
    full_cmd = ["docker", "exec", "-i", "-w", "/workspace", container_name] + cmd_list
    
    proc = await asyncio.create_subprocess_exec(
        *full_cmd,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE
    )
    stdout, stderr = await proc.communicate()
    
    if proc.returncode != 0:
        raise Exception(f"Command failed: {stderr.decode().strip()}")
    return stdout.decode()

# ==================== 敏感信息脱敏工具 ====================

def _is_env_file(file_path: str) -> bool:
    """判断文件是否为环境变量文件(基于文件名)"""
    if not file_path:
        return False
    name = os.path.basename(file_path)
    return (
        name.startswith('.env') or 
        name.startswith('env.') or 
        name in ['.env', 'env', 'environment']
    )

def _mask_sensitive_value(value: str) -> str:
    """脱敏值:将值替换为掩码,只显示首尾部分"""
    v = value.strip()
    if len(v) <= 4:
        return '*' * len(v)
    elif len(v) <= 8:
        return v[0] + '*' * (len(v) - 2) + v[-1]
    else:
        return v[:3] + '*' * (len(v) - 6) + v[-3:]

def _mask_env_content(text: str) -> str:
    """对包含 KEY=VALUE 的行进行脱敏,VALUE 部分替换为掩码"""
    pattern = re.compile(
        r'^(\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*)(\S+)(.*)$',
        re.IGNORECASE
    )
    masked_lines = []
    for line in text.splitlines():
        match = pattern.match(line)
        if match:
            prefix = match.group(1)
            value = match.group(2)
            suffix = match.group(3) or ''
            masked_value = _mask_sensitive_value(value)
            new_line = f"{prefix}{masked_value}{suffix}"
            masked_lines.append(new_line)
        else:
            masked_lines.append(line)
    return "\n".join(masked_lines)

def _maybe_mask_output(file_path: str, output: str) -> str:
    """
    根据文件路径决定是否脱敏输出。
    用于 read_file、read_file_range、tail_file 等工具。
    输出可能包含行号前缀,例如 "   42 | CONTENT"。
    """
    if not _is_env_file(file_path):
        return output

    masked = []
    for line in output.splitlines():
        # 如果包含管道符,可能是带行号的输出
        if '|' in line:
            parts = line.split('|', 1)
            if len(parts) == 2:
                line_no = parts[0].strip()
                content = parts[1]
                masked_line = f"{line_no} | {_mask_env_content(content)}"
            else:
                masked_line = _mask_env_content(line)
        else:
            masked_line = _mask_env_content(line)
        masked.append(masked_line)
    return "\n".join(masked)

# ==================== Docker 环境工具实现 (含新功能) ====================

async def docker_sandbox(command: str, background: bool = False, timeout: int = 600) -> AsyncIterator[str]:
    """
    [Docker] 沙盒执行(打平版,直接返回异步生成器)
    """
    effective_timeout = max(1, min(timeout, 3600))
    settings = await load_settings()
    cwd = settings.get("CLISettings", {}).get("cc_path")
    if not cwd:
        yield "Error: No workspace directory specified."
        return
    
    try:
        container_name = await get_or_create_docker_sandbox(cwd)
    except Exception as e:
        yield f"Docker Sandbox Error: {str(e)}"
        return

    exec_cmd = [
        "docker", "exec", 
        "-i", 
        "-e", "PYTHONUNBUFFERED=1",
        "-e", "TERM=xterm",
        container_name, 
        "sh", "-c", f"cd /workspace && {command}"
    ]
    
    try:
        process = await asyncio.create_subprocess_exec(
            *exec_cmd,
            stdin=asyncio.subprocess.PIPE,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )

        if background:
            pid = await process_manager.register_process(process, f"[Docker] {command}", "docker")
            yield f"[SUCCESS] Docker PID: {pid}"
            return

        queue = asyncio.Queue()
        async def wrap_stdout():
            async for chunk in read_stream_chunks(process.stdout, ""):
                await queue.put(chunk)
        async def wrap_stderr():
            async for chunk in read_stream_chunks(process.stderr, "[Docker stderr] "):
                await queue.put(chunk)

        stdout_task = asyncio.create_task(wrap_stdout())
        stderr_task = asyncio.create_task(wrap_stderr())

        start_time = time.time()
        try:
            while not (stdout_task.done() and stderr_task.done() and queue.empty()):
                remaining = effective_timeout - (time.time() - start_time)
                if remaining <= 0:
                    raise asyncio.TimeoutError()
                try:
                    content = await asyncio.wait_for(queue.get(), timeout=0.1)
                    yield content
                except asyncio.TimeoutError:
                    continue
            
            await process.wait()

        except asyncio.TimeoutError:
            process.kill()
            yield f"\n\n[TIMEOUT ERROR] Docker 命令执行超过 {effective_timeout} 秒已强制终止。注意!命令并未完全执行完毕。"
            yield "\n💡 提示:对于启动应用或大文件下载,请使用 'background': true。"
    except Exception as e:
        yield f"[ERROR] Docker 进程启动失败: {str(e)}"

async def glob_files_tool(pattern: str, exclude: str = "**/node_modules/**,**/.git/**,**/__pycache__/**") -> str:
    """[Docker] Glob 递归查找"""
    try:
        real_cwd = await _get_current_cwd()
        exclude_list = [e.strip() for e in exclude.split(",") if e.strip()]
        
        python_script = f'''
import glob, os, json, fnmatch
files = glob.glob("/workspace/{pattern}", recursive=True)
exclude_patterns = {exclude_list}
filtered = []
for f in files:
    if not os.path.isfile(f): continue
    rel_path = f.replace("/workspace/", "")
    should_exclude = False
    for ex in exclude_patterns:
        if fnmatch.fnmatch(rel_path, ex) or fnmatch.fnmatch(f, ex):
            should_exclude = True; break
    if not should_exclude: filtered.append(rel_path)
print(json.dumps(filtered))
'''
        output = await _exec_docker_cmd_simple(real_cwd, ["python3", "-c", python_script])
        files = json.loads(output)
        if not files: return "[Result] No files found."
        
        lines = [f"[{len(files)} files matched]"]
        for f in files[:50]:
            icon = "🐍" if f.endswith(".py") else "📄"
            lines.append(f"{icon} {f}")
        if len(files) > 50: lines.append(f"... {len(files)-50} more")
        return "\n".join(lines)
    except Exception as e:
        return f"[Error] Glob failed: {str(e)}"

async def todo_write_tool(action: str, id: str = None, content: str = None, 
                          priority: str = "medium", status: str = None) -> str:
    """[Docker] 待办任务管理工具 - 使用3位数字有序ID"""
    try:
        real_cwd = await _get_current_cwd()
        container_name = await get_or_create_docker_sandbox(real_cwd)
        todo_file = "/workspace/.agents/ai_todos.json"
        
        # 从 Docker 容器读取任务列表
        try:
            data = await _exec_docker_cmd_simple(real_cwd, ["cat", todo_file])
            todos = json.loads(data)
        except:
            todos = []
            
        msg = ""

        # 生成下一个有序ID的辅助函数
        def _generate_ordered_id(existing_todos):
            if not existing_todos:
                return "1"
            # 找出最大数字 ID(兼容旧数据)
            numeric_ids = [int(t['id']) for t in existing_todos if t['id'].isdigit()]
            if not numeric_ids:
                return "1"
            return str(max(numeric_ids) + 1)  # 1, 2, 3... 不补零,不限制位数

        if action == "create":
            """创建新任务 - 自动生成3位数字有序ID"""
            if not content: 
                return "[Error] 创建任务必须提供 content 参数"
            
            new_id = _generate_ordered_id(todos)
            new_todo = {
                "id": new_id,
                "content": content,
                "priority": priority,
                "status": "pending",
                "created_at": datetime.now().isoformat(),
                "completed_at": None
            }
            todos.append(new_todo)
            msg = f"[Success] 已创建任务 #{new_id}: {content[:30]}"
            
        elif action == "list":
            """列出所有任务 - 按ID数字排序"""
            if not todos: 
                return "当前暂无任务"
            
            lines = ["📋 **任务列表** (ID越大创建越晚):"]
            sorted_todos = sorted(todos, key=lambda x: int(x['id']) if x['id'].isdigit() else 0)
            
            for t in sorted_todos:
                icon = "✅" if t.get('status') == 'done' else "⏳"
                priority_map = {"high": "🔴", "medium": "🟡", "low": "🟢"}
                p_icon = priority_map.get(t.get('priority', 'medium'), "⚪")
                lines.append(f"{icon} [{t['id']}] {p_icon} {t['content'][:40]}")
            return "\n".join(lines)

        elif action == "complete":
            """【高频】标记任务为已完成 - 幂等操作"""
            if not id: 
                return "[Error] 完成任务必须提供 id (如: 001)"
            
            target = next((t for t in todos if t['id'] == id), None)
            if not target: 
                return f"[Error] 未找到任务 #{id}"
            
            if target.get('status') == 'done':
                msg = f"[Info] 任务 #{id} 已经是完成状态"
            else:
                target['status'] = 'done'
                target['completed_at'] = datetime.now().isoformat()
                msg = f"[Success] 已完成任务 #{id}"

        elif action == "toggle":
            """切换完成状态"""
            if not id: 
                return "[Error] 切换状态必须提供 id"
            
            target = next((t for t in todos if t['id'] == id), None)
            if not target: 
                return f"[Error] 未找到任务 #{id}"
            
            if target.get('status') != 'done':
                target['status'] = 'done'
                target['completed_at'] = datetime.now().isoformat()
                msg = f"[Success] 已完成任务 #{id}"
            else:
                target['status'] = 'pending'
                target['completed_at'] = None
                msg = f"[Success] 已重新打开任务 #{id}"

        elif action == "update":
            """编辑任务详情"""
            if not id: 
                return "[Error] 更新任务必须提供 id"
            
            target = next((t for t in todos if t['id'] == id), None)
            if not target: 
                return f"[Error] 未找到任务 #{id}"
            
            if content: 
                target['content'] = content
            if priority: 
                target['priority'] = priority
            
            if status:
                if status == "done" and target.get('status') != "done":
                    target['completed_at'] = datetime.now().isoformat()
                elif status != "done" and target.get('status') == "done":
                    target['completed_at'] = None
                target['status'] = status
            
            target['updated_at'] = datetime.now().isoformat()
            msg = f"[Success] 已更新任务 #{id}"

        elif action == "delete":
            """删除任务"""
            if not id: 
                return "[Error] 删除任务必须提供 id"
            
            target = next((t for t in todos if t['id'] == id), None)
            if not target: 
                return f"[Error] 未找到任务 #{id}"
            
            todos.remove(target)
            msg = f"[Success] 已删除任务 #{id}"

        else:
            return f"[Error] 未知操作: {action}"

        # 写回 Docker 容器
        with tempfile.NamedTemporaryFile(mode='w', delete=False, encoding='utf-8', newline='\n') as tmp:
            tmp.write(json.dumps(todos, indent=2, ensure_ascii=False))
            tmp_path = tmp.name
        
        await _exec_docker_cmd_simple(real_cwd, ["mkdir", "-p", "/workspace/.agents"])
        dest = f"{container_name}:{todo_file}"
        proc = await asyncio.create_subprocess_exec("docker", "cp", tmp_path, dest, 
                                                    stdout=asyncio.subprocess.PIPE)
        await proc.wait()
        
        if os.path.exists(tmp_path):
            os.unlink(tmp_path)
            
        return msg
        
    except Exception as e:
        return f"[Error] 任务操作失败: {str(e)}"
    
# 恢复原有的 Docker 基础文件工具
async def list_files_tool(path: str = ".", show_all: bool = True) -> str:
    try:
        real_cwd = await _get_current_cwd()
        flag = "-laF" if show_all else "-F"
        return await _exec_docker_cmd_simple(real_cwd, ["ls", flag, path])
    except Exception as e: return str(e)

async def read_file_tool(path: str, start_line: int = None, end_line: int = None) -> str:
    """[Docker] 读取文件"""
    if start_line is not None or end_line is not None:
        return await read_file_range_tool(path, start_line or 1, end_line or 1)
    try:
        real_cwd = await _get_current_cwd()
        script = f"""
import sys

try:
    with open("{path}", "rb") as f:
        if b'\\0' in f.read(1024):
            print("[Error] Cannot read binary file")
            sys.exit(0)
except Exception: pass

total = 0
with open("{path}", "r", encoding="utf-8", errors="replace") as f:
    for i, line in enumerate(f, 1):
        total = i
        if i <= 1000:
            c = line.rstrip('\\r\\n')
            if len(c) > 1000: c = c[:500] + " ... [Truncated] ... " + c[-50:]
            print(f"{{i:5}}: {{c}}")

if total > 1000:
    print(f"\\n... [Warning] File truncated. Showing 1 to 1000 of {{total}} lines.")
"""
        raw_output = await _exec_docker_cmd_simple(real_cwd, ["python3", "-c", script])
        return _maybe_mask_output(path, raw_output)
    except Exception as e: return f"[Error] Read failed: {str(e)}"

async def read_file_range_tool(path: str, start_line: int, end_line: int) -> str:
    """[Docker] 精准读取指定行范围"""
    try:
        if start_line < 1 or end_line < start_line: return "[Error] Invalid line range."
        real_cwd = await _get_current_cwd()
        script = f"""
import sys
with open("{path}", "r", encoding="utf-8", errors="replace") as f:
    for i, line in enumerate(f, 1):
        if i >= {start_line} and i <= {end_line}:
            c = line.rstrip('\\r\\n')
            if len(c) > 1000: c = c[:500] + " ... [Truncated] ... " + c[-50:]
            print(f"{{i:5}}: {{c}}")
        elif i > {end_line}: break
"""
        result = await _exec_docker_cmd_simple(real_cwd, ["python3", "-c", script])
        if len(result) > 50000: result = result[:50000] + "\n... [Warning] Output truncated."
        return _maybe_mask_output(path, result)
    except Exception as e: return str(e)

async def tail_file_tool(path: str, lines: int = 100) -> str:
    """[Docker] 读取文件末尾"""
    try:
        real_cwd = await _get_current_cwd()
        script = f"""
total=$(wc -l < "{path}" 2>/dev/null || echo 0)
start=$((total - {lines} + 1))
if [ $start -lt 1 ]; then start=1; fi
awk -v s=$start 'NR>=s' "{path}" | python3 -c "
import sys
start_idx = int(sys.argv[1])
for i, line in enumerate(sys.stdin, start_idx):
    c = line.rstrip('\\r\\n')
    print(f'{{i:5}}: {{c}}')
" $start
"""
        raw_output = await _exec_docker_cmd_simple(real_cwd, ["sh", "-c", script])
        return _maybe_mask_output(path, raw_output)
    except Exception as e: return str(e)

async def edit_file_tool(path: str, content: str) -> str:
    try:
        real_cwd = await _get_current_cwd()
        container_name = await get_or_create_docker_sandbox(real_cwd)
        with tempfile.NamedTemporaryFile(mode='w', delete=False, encoding='utf-8', newline='\n') as tmp:
            tmp.write(content)
            tmp_path = tmp.name
        await _exec_docker_cmd_simple(real_cwd, ["mkdir", "-p", os.path.dirname(path) or "."])
        dest = f"{container_name}:/workspace/{path}"
        proc = await asyncio.create_subprocess_exec("docker", "cp", tmp_path, dest, stdout=asyncio.subprocess.PIPE)
        await proc.wait()
        os.unlink(tmp_path)
        return f"[Success] Saved {path}"
    except Exception as e: return str(e)

def _mask_grep_output(grep_output: str) -> str:
    """对 grep 输出进行脱敏,对于 .env 文件中的匹配行,遮蔽 VALUE 部分"""
    if not grep_output:
        return grep_output
    lines = grep_output.splitlines()
    masked_lines = []
    for line in lines:
        # grep 输出格式通常为:filename:line_number:matched_text
        parts = line.split(':', 2)
        if len(parts) >= 3:
            fname = parts[0]
            line_no = parts[1]
            content = parts[2]
            # 如果文件名匹配 .env 模式,脱敏内容
            if _is_env_file(fname) or '.env' in fname.lower():
                content = _mask_env_content(content)
            masked_lines.append(f"{fname}:{line_no}:{content}")
        else:
            masked_lines.append(line)
    return "\n".join(masked_lines)


async def search_files_tool(pattern: str, path: str = ".") -> str:
    """[Docker] Grep 搜索"""
    try:
        real_cwd = await _get_current_cwd()
        cmd = f"grep -rn '{pattern}' '{path}'"
        raw_output = await _exec_docker_cmd_simple(real_cwd, ["sh", "-c", cmd])
        if '.env' in raw_output.lower(): return _mask_grep_output(raw_output)
        return raw_output
    except Exception as e: return str(e)


# ==================== [新增] 管理工具:进程与网络 ====================

async def list_processes_tool() -> str:
    """[Common] 列出所有后台进程 (Docker & 本地)"""
    return process_manager.list_processes()

async def get_process_logs_tool(pid: str) -> str:
    """[Common] 获取指定进程的日志"""
    if not pid:
        return "Error: 'pid' is required to fetch logs."
    return process_manager.get_logs(pid)

async def kill_process_tool(pid: str) -> str:
    """[Common] 终止指定的后台进程"""
    if not pid:
        return "Error: 'pid' is required to kill a process."
    return await process_manager.kill_process(pid)

async def docker_manage_ports_tool(action: str, container_port: int = 8000, host_port: int = None) -> str:
    """[Docker] 端口转发管理"""
    try:
        real_cwd = await _get_current_cwd()
        container_name = await get_or_create_docker_sandbox(real_cwd)
        
        if container_name not in DOCKER_PROXIES:
            DOCKER_PROXIES[container_name] = DockerPortProxy(container_name)
        proxy = DOCKER_PROXIES[container_name]
        
        if action == "list":
            return proxy.list_proxies()
        if action == "forward":
            if not host_port: host_port = container_port
            return await proxy.start_forward(host_port, container_port)
        if action == "stop":
            if not host_port: return "Error: host_port required to stop."
            return await proxy.stop_forward(host_port)
        return "Unknown action."
    except Exception as e:
        return f"[Error] Port tool failed: {str(e)}"

async def local_net_tool(action: str, port: int = None) -> str:
    """[Local] 本地网络工具:检查端口占用"""
    if action == "check":
        if not port: return "Error: Port required."
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            result = s.connect_ex(('127.0.0.1', port))
            status = "OPEN/BUSY" if result == 0 else "CLOSED/FREE"
            return f"Port {port} on localhost is {status}."
    
    if action == "scan":
        # 简单扫描常用开发端口
        common_ports = [3000, 5000, 8000, 8080, 80, 443, 3306, 5432]
        results = []
        for p in common_ports:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.settimeout(0.1)
                res = s.connect_ex(('127.0.0.1', p))
                status = "BUSY" if res == 0 else "FREE"
                results.append(f"{p}: {status}")
        return "Common Ports:\n" + "\n".join(results)
        
    return "Unknown action. Use check or scan."

# ==================== 本地环境 (Local) 工具实现 ====================

def resolve_strict_path(cwd: str, sub_path: str, check_symlink: bool = True) -> Path:
    """
    严格工作区路径解析 (已修复跨平台斜杠混用 Bug)
    """
    base = Path(cwd).resolve()
    
    if not sub_path:
        return base
        
    sub_path = sub_path.strip().replace('\x00', '').replace('\n', '')
    
    # ★ 修复:利用 Path.parts 跨平台安全解析路径节点,防止正反斜杠混用逃逸
    if '..' in Path(sub_path).parts:
        raise PermissionError(f"Path traversal detected: {sub_path}")
    
    if os.path.isabs(sub_path) or (len(sub_path) > 1 and sub_path[1] == ':'):
        raise PermissionError(f"Absolute paths not allowed: {sub_path}")
    
    target = (base / sub_path).resolve()
    
    try:
        target.relative_to(base)
    except ValueError:
        raise PermissionError(f"Access denied: {sub_path} resolves outside workspace")
    
    if check_symlink and target.exists():
        real_path = target.resolve(strict=True)
        try:
            real_path.relative_to(base)
        except ValueError:
            raise PermissionError(f"Symlink escape detected: {sub_path} -> {real_path}")
            
    return target


def validate_bash_command(command: str, cwd: str, mode: str = "default") -> Tuple[bool, str]:
    """
    动态路径感知安全校验(涵盖工作区自我毁灭、.NET 类型加速器绕过、异步 Job 炸弹等防御)
    """
    cmd_lower = command.lower()
    
    # 获取规范化的工作区绝对路径
    resolved_cwd = str(Path(cwd).resolve()).lower()
    
    # ==================== [优化] 动态绝对路径逃逸检测 ====================
    # 仅在非 YOLO 模式下检测工作区逃逸
    potential_paths = []
    if mode != "yolo":
        # 预清洗:在提取路径前,先移除所有网络 URL、Git 远程仓库地址、SSH 目标,彻底杜绝联网命令的误判
        # 1. 移除 http://, https://, ftp://, sftp://, git://, ssh:// 等标准 URL
        cmd_for_path_extraction = re.sub(r'[a-zA-Z0-9\+-\.]+://[^\s"\'|&<>]+', ' ', command)
        # 2. 移除 git@github.com:owner/repo.git 或 github.com:owner/repo.git 等 SSH/Git 格式
        cmd_for_path_extraction = re.sub(r'\b(?:[a-zA-Z0-9._%+-]+@)?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}:[^\s"\'|&<>]+', ' ', cmd_for_path_extraction)

        for match in re.finditer(r'([a-zA-Z]:[/\\][^\s"\'|&<>]+|[/\\][^\s"\'|&<>]+)', cmd_for_path_extraction):
            raw_path = match.group(1)
            start_idx = match.start()
            
            # 判定是否为普通相对路径的一部分(如 .\test.txt 或 dir\file.txt)
            if raw_path.startswith('/') or raw_path.startswith('\\'):
                if start_idx > 0:
                    prev_char = cmd_for_path_extraction[start_idx - 1]
                    # 若前驱字符为 '.'、'_' 或字母数字,说明这只是相对路径的一部分,跳过检测
                    if prev_char in ('.', '_') or prev_char.isalnum():
                        continue
            
            potential_paths.append(raw_path)
            
        # 敏感 Windows 根目录列表(长度 >= 5),用于区分路径与 Windows 命令行参数(如 /s, /f, /quiet)
        win_sensitive_dirs = {
            "windows", "users", "program files", "program files (x86)", 
            "programdata", "recovery", "system volume information", "boot", "intel"
        }

        # 允许的系统可执行程序名(避免误判 cmd.exe, powershell.exe 等系统工具本身的路径)
        allowed_system_exes = {
            "cmd.exe", "powershell.exe", "pwsh.exe", "bash.exe", "git.exe", 
            "conhost.exe", "tar.exe", "curl.exe", "ssh.exe", "wsl.exe",
            "bash", "sh", "git", "curl", "ssh", "tar"
        }
        
        for raw_path in potential_paths:
            # Windows 特殊处理:过滤掉命令行参数/开关(如 /s, /f, /q, /quiet 等)
            if platform.system() == "Windows" and raw_path.startswith('/'):
                clean_path = raw_path[1:]
                # 如果不包含其他斜杠/反斜杠,说明是单级路径或参数开关
                if '/' not in clean_path and '\\' not in clean_path:
                    if clean_path.lower() not in win_sensitive_dirs:
                        # 认定为普通的参数开关或非敏感目录,予以放行
                        continue

            # 跨平台驱动器号防护:如果是非 Windows 系统,但路径却包含 Windows 盘符(如 C:\),直接拦截
            if platform.system() != "Windows" and re.match(r'^[a-zA-Z]:', raw_path):
                return False, f"Access to path outside workspace is blocked: {raw_path}"

            try:
                # 规范化命令中出现的每一个绝对路径
                resolved_target = str(Path(raw_path).resolve()).lower()
                
                # 关键判定:如果该绝对路径不以工作区路径(cwd)开头,说明 AI 试图操作外部文件!
                if not resolved_target.startswith(resolved_cwd):
                    # 排除系统级工具路径本身的误判,确保其确实是允许的系统程序,而非敏感目录
                    target_name = Path(resolved_target).name.lower()
                    if target_name in allowed_system_exes:
                        continue
                    return False, f"Access to path outside workspace is blocked: {raw_path}"
            except Exception:
                continue
    # ====================================================================

    # 1. 防止路径穿越逃逸
    if re.search(r'\.\.[/\\]', command) or '..' in Path(command).parts:
        return False, "Path traversal (..) is blocked"

    # 2. 跨平台敏感目录防护 (仅在非 YOLO 模式下拦截,YOLO 模式允许自由调试系统配置文件)
    if mode != "yolo":
        sensitive_roots = [
            r'(?:\s|^)/etc', r'(?:\s|^)/var', r'(?:\s|^)/root', 
            r'(?:\s|^)/bin', r'(?:\s|^)/sbin', r'(?:\s|^)/usr/local/bin',
            r'(?:\s|^)/sys', r'(?:\s|^)/proc', 
            r'(?:\s|^)/Library', r'(?:\s|^)/System',
            r'(?:\s|^)[a-z]:[/\\]Windows', r'(?:\s|^)[a-z]:[/\\]Program Files', 
            r'(?:\s|^)[a-z]:[/\\]Users[/\\](?:Default|Public|Administrator)' 
        ]
        
        for pattern in sensitive_roots:
            if re.search(pattern, command, re.IGNORECASE):
                return False, f"Access to sensitive system directory blocked"

    # 3. 跨平台毁灭性操作 (任何模式均会拦截,保障系统最基础的安全底线)
    destructive_patterns = [
        (r'rm\s+-[rRfF\s]+\s*(/|[a-z]:[/\\])\*?', "Recursive delete root"),
        (r'mkfs\.[a-z]+', "Filesystem format"),                    
        (r'dd\s+if=.*of=/dev/[a-z]', "Direct device write"),       
        (r'>?\s*/dev/(sda|hd|nvme|mmcblk)', "Block device access"),
        (r'chmod\s+-[R\s]*777\s+/', "Change root permissions"),
        (r'chown\s+-[R\s]*root\s+/', "Change root ownership"),
        (r':\(\)\{\s*:\|:&?\s*\};\s*:', "Fork bomb"), 
        (r'(?:\s|^)format\s+[a-z]:', "Windows disk format"),
        (r'(?:\s|^)reg\s+(delete|add)\s+(HKLM|HKEY_LOCAL_MACHINE)', "Modify system registry"),
        (r'(?:\s|^)Remove-Item\s+-Recurse\s+-Force\s+[a-z]:[/\\]', "Powershell recursive delete root"),
        (r'(?:\s|^)nvram\s+-c', "Clear Mac NVRAM"),
        
        # 针对特定漏洞的毁灭性行为防护 (拦截关键系统服务与核心进程控制)
        (r'(?:\s|^)(taskkill|Stop-Process)(?:\.exe)?(?:\s|[/-]).*(?:svchost|lsass|csrss|smss|wininit|services|explorer)\.exe', "System process termination blocked"),
        (r'(?:\s|^)sc(?:\.exe)?\s+(?:stop|delete|config)\s+(?:wuauserv|WinDefend|SamSs|eventlog)', "Critical service modification blocked"),
        (r'(?:\s|^)schtasks(?:\.exe)?\s+/(create|change|delete)', "Scheduled tasks modification blocked"),

        # 防止工作区自我毁灭
        (r'\b(?:rm|remove-item|del|rd|rmdir)(?:\.exe)?\s+-[rRfFsS\s\-]*\s*(?:\.|\*)(?:\s|$|;|&&|\|\||&)', "Workspace self-destruction blocked"),
        (r'\bremove-item\s+-[rR\s\-]*\s*(?:\.|\*)(?:\s|$|;|&&|\|\||&)', "Workspace self-destruction blocked"),
    ]
    
    for pattern, reason in destructive_patterns:
        if re.search(pattern, command, re.IGNORECASE):
            return False, f"Destructive operation blocked: {reason}"
    
    # 4. 风险操作
    if mode != "yolo":
        risk_patterns = [
            (r'(?:\s|^)sudo\s+', "sudo usage blocked"),
            (r'(curl|wget).*\|\s*(sh|bash|zsh|python|perl|php)', "Remote execution via pipe"),
            (r'base64\s+-d\s*\|\s*(sh|bash|zsh|python)', "Obfuscated base64 command execution blocked"),
            (r'$\{?HOME\}?', "HOME env variable usage"),
            (r'~\s*/', "Home directory access via ~"),
            (r'(?:\s|^)osascript\s+-e\s+.*password', "AppleScript password prompt blocked"),
            (r'(Invoke-WebRequest|iwr|Invoke-RestMethod|irm).*\|\s*(Invoke-Expression|iex)', "PowerShell remote script execution"),
            
            # 动态执行、混淆与 .NET 类型/加速器(如 [IO.File])绕过防御
            (r'\b(?:iex|Invoke-Expression)\b', "PowerShell Invoke-Expression blocked"),
            
            # 针对 Char-Code 编码与字符拼接的防御
            (r'\[char\s*\]|\[byte\s*\]', "PowerShell Type Accelerator obfuscation blocked"),
            (r'\[(?:System\.)?Convert\]\s*::\s*ToChar', "PowerShell Convert-ToChar obfuscation blocked"),
            (r'\[(?:System\.)?Text\.Encoding\]', "PowerShell Text Encoding obfuscation blocked"),
            
            # 针对所有 .NET 静态方法和敏感对象初始化的严密防御
            (r'\[[a-zA-Z0-9\._]+\]::', ".NET static methods blocked"),
            (r'New-Object\s+(?:-TypeName\s+)?\[?(?:System\.)?(?:IO|Environment|Diagnostics|Security|Net|DirectoryServices|Management|Reflection|Runtime|ServiceProcess|Convert|Console|Threading|Web|Microsoft)', "Sensitive .NET object creation blocked"),

            (r'\$\{?env:(?:WINDIR|SYSTEMROOT|SYSTEMDRIVE|PROGRAMDATA|PROGRAMFILES|USERPROFILE|APPDATA|LOCALAPPDATA|TEMP|TMP)\}?', "Sensitive environment variable access blocked"),
            
            # 异步 Job 耗尽/分叉炸弹防御
            (r'\b(?:Start-Job|Start-ThreadJob)\b', "Asynchronous job creation blocked"),
            (r'\s+-AsJob\b', "Asynchronous job parameter blocked"),
            (r'ForEach-Object\s+-[Pa-z]*\s*Parallel', "Parallel loop execution blocked"),

            # 限制 WMI/CIM 信息收集命令
            (r'\b(?:Get-WmiObject|Get-CimInstance|Invoke-CimMethod|Invoke-WmiMethod|gwmi|gcim)\b', "WMI/CIM queries blocked"),

            # 基础资源超载/递归炸弹规避
            (r'\*\s*(?:\d{3,}MB|\d+GB|\d{8,})', "Large memory allocation multiplication blocked"),
            (r'function\s+([a-zA-Z0-9_-]+)\s*\{\s*\1\s*\}', "Simple recursion fork bomb blocked"),

            # 进程与服务控制 (普通进程也拦截,除非 yolo)
            (r'(?:\s|^)(taskkill(?:\.exe)?|Stop-Process|Stop-Service|sc(?:\.exe)?\s+stop|sc(?:\.exe)?\s+delete|net(?:\.exe)?\s+stop)(?:\s|[/-]|$)', "Process/Service termination blocked"),
            (r'(?:powershell|pwsh).*(?:-encodedcommand|-enc\s|-e\s)', "PowerShell encoded command execution blocked"),
        ]
        for pattern, reason in risk_patterns:
            if re.search(pattern, command, re.IGNORECASE):
                return False, f"{reason} blocked"
    
    return True, command

async def shell_tool_local(command: str, background: bool = False, timeout: int = 600) -> AsyncIterator[str]:
    """
    [Local] 执行本地命令
    - Windows: 维持原有的 powershell/cmd 逻辑。
    - 非 Windows: 优先使用 zerobox.Sandbox 提供 OS 级沙盒隔离。
    """
    # 限制超时范围:1秒到1小时
    effective_timeout = max(1, min(timeout, 3600))
    
    settings = await load_settings()
    cwd = settings.get("CLISettings", {}).get("cc_path")
    perm = settings.get("localEnvSettings", {}).get("permissionMode", "default")
    
    if not cwd: 
        yield "Error: No workspace directory specified (cc_path)."
        return
    
    # 安全校验策略(双重防护)
    allowed, validate_result = validate_bash_command(command, cwd, mode=perm)
    if not allowed:
        yield f"[Security] Command blocked: {validate_result}"
        return
    
    system = platform.system()

    # ==================== 非 Windows 且安装了 ZeroBox 的情况 ====================
    # 注意:SDK 目前是同步阻塞设计。为了保持 CLI 响应,我们在线程中运行它。
    # 且为了 PID 管理器的兼容性,仅在前台任务(background=False)时使用 SDK。
    if system != "Windows" and HAS_ZEROBOX and not background and not IS_DOCKER:
        try:
            yield f"--- [Sandbox Mode] Executing via zerobox.Sandbox ---\n"
            
            def run_sandbox():
                # 创建沙盒实例:允许读写当前工作目录,开启所有权限以兼容复杂命令
                # 如果需要更严格,可以将 allow_all=True 改为 allow_write=[cwd]
                sb = Sandbox.create({
                    "cwd": cwd,
                    "allow_write": [cwd],  
                    "allow_read": [cwd],  
                    "allow_net": True,
                })
                # 使用 .output() 获取 code, stdout, stderr 且不抛出执行异常
                return sb.sh(command).output(timeout=float(effective_timeout))

            # 在线程池中执行同步的 SDK 调用
            result = await asyncio.to_thread(run_sandbox)
            
            if result.stdout:
                yield result.stdout
            if result.stderr:
                yield f"[stderr] {result.stderr}"
            
            if result.code != 0:
                yield f"\n--- 运行结束 (Exit Code: {result.code}) ---"
                yield get_detailed_exit_info(result.code, command)
            
            return # 任务结束

        except subprocess.TimeoutExpired:
            yield f"\n\n[TIMEOUT ERROR] 命令执行超过 {effective_timeout} 秒已强制终止。"
            return
        except Exception as e:
            yield f"[Sandbox Error] ZeroBox SDK 运行异常: {str(e)}\n尝试回退到标准 Shell...\n"
            # 报错后不返回,继续尝试下方的标准执行逻辑

    # ==================== Windows 或 回退到标准 Shell 的情况 ====================
    
    if system == "Windows":
        exe, args = "powershell.exe", ["-NoLogo", "-NonInteractive", "-Command", command]
    else:
        # 非 Windows 环境回退或后台任务
        exe, args = os.environ.get('SHELL', '/bin/bash'), ["-c", command]

    env = os.environ.copy()
    env["PYTHONUNBUFFERED"] = "1"
    env["TERM"] = "xterm"

    try:
        process = await asyncio.create_subprocess_exec(
            exe, *args,
            stdin=asyncio.subprocess.PIPE,
            stdout=asyncio.subprocess.PIPE, 
            stderr=asyncio.subprocess.PIPE,
            cwd=cwd,
            env=env,
            start_new_session=(system != "Windows")
        )

        if background:
            pid = await process_manager.register_process(process, command, "local")
            yield f"[SUCCESS] Background process started.\nPID: {pid}"
            return

        queue = asyncio.Queue()
        async def wrap_stdout():
            async for chunk in read_stream_chunks(process.stdout, ""):
                await queue.put(chunk)
        async def wrap_stderr():
            async for chunk in read_stream_chunks(process.stderr, "[stderr] "):
                await queue.put(chunk)

        stdout_task = asyncio.create_task(wrap_stdout())
        stderr_task = asyncio.create_task(wrap_stderr())

        start_time = time.time()
        try:
            while not (stdout_task.done() and stderr_task.done() and queue.empty()):
                remaining = effective_timeout - (time.time() - start_time)
                if remaining <= 0:
                    raise asyncio.TimeoutError()
                try:
                    content = await asyncio.wait_for(queue.get(), timeout=0.1)
                    yield content
                except asyncio.TimeoutError:
                    continue

            await process.wait()
            if process.returncode != 0:
                yield f"\n--- 运行结束 (Exit Code: {process.returncode}) ---"
                yield get_detailed_exit_info(process.returncode, command)
                
        except asyncio.TimeoutError:
            # 杀进程树逻辑
            if system == "Windows":
                subprocess.run(f"taskkill /F /T /PID {process.pid}", shell=True, capture_output=True)
            else:
                try:
                    os.killpg(os.getpgid(process.pid), signal.SIGKILL)
                except:
                    process.kill()
            yield f"\n\n[TIMEOUT ERROR] 命令执行超过 {effective_timeout} 秒已强制终止。"
            yield "\n💡 提示:对于长期运行的任务,请使用 'background': true。"
            
    except Exception as e:
        yield f"[系统错误] 无法启动进程: {str(e)}"

# 恢复原有的 Local 文件工具
async def list_files_tool_local(path: str = ".", show_all: bool = True) -> str:
    """[Local] 列出文件:优先显示目录,支持数量截断,过滤隐藏文件"""
    try:
        cwd = await _get_current_cwd()
        target = resolve_strict_path(cwd, path, check_symlink=True)
        
        if not target.is_dir():
            return f"[Error] Not a directory: {path}"

        # 使用 scandir 获取更详细的信息且速度更快
        entries = []
        try:
            with os.scandir(target) as it:
                for entry in it:
                    if not show_all and entry.name.startswith('.'):
                        continue
                    
                    is_dir = entry.is_dir()
                    # 格式:(是否目录, 排序名, 显示字符串)
                    # 目录排在前面 (0),文件排在后面 (1)
                    display_name = f"{entry.name}/" if is_dir else entry.name
                    entries.append((0 if is_dir else 1, entry.name.lower(), display_name))
        except PermissionError:
            return f"[Error] Permission denied accessing: {path}"

        # 排序:先按目录/文件分,再按名称字母序
        entries.sort()

        # 数量截断防止 Token 爆炸
        MAX_ITEMS = 200
        result_lines = [e[2] for e in entries[:MAX_ITEMS]]
        
        summary = f"Total: {len(entries)} items"
        if len(entries) > MAX_ITEMS:
            summary += f" (Showing first {MAX_ITEMS})"
            result_lines.append(f"... {len(entries) - MAX_ITEMS} more items")
        
        return f"{summary} in {path}:\n" + "\n".join(result_lines) if result_lines else "Empty directory."

    except Exception as e:
        return f"[Error] List failed: {str(e)}"

def _format_line(line_number: int, content: str, max_line_chars: int = 1000) -> str:
    """格式化单行为带行号的输出"""
    content_stripped = content.rstrip('\r\n')
    if len(content_stripped) > max_line_chars:
        half = max_line_chars // 2
        display_content = f"{content_stripped[:half]} ... [Truncated] ... {content_stripped[-50:]}"
    else:
        display_content = content_stripped
    return f"{line_number:5}: {display_content}"

async def read_file_tool_local(path: str, start_line: int = None, end_line: int = None) -> str:
    if start_line is not None or end_line is not None:
        return await read_file_range_tool_local(path, start_line or 1, end_line or 1)
    try:
        MAX_LINES = 1000
        MAX_LINE_CHARS = 1000
        MAX_TOTAL_CHARS = 50000
        
        cwd = await _get_current_cwd()
        target = resolve_strict_path(cwd, path, check_symlink=True)
        if not target.exists() or not target.is_file():
            return f"[Error] File not found: {path}"

        # 二进制检查保持不变...
        with open(target, 'rb') as f_bin:
            if b'\0' in f_bin.read(1024):
                return f"[Error] Cannot read binary file: {path}"

        output = []
        current_total_len = 0
        truncated = False
        
        async with aiofiles.open(target, 'r', encoding='utf-8', errors='replace') as f:
            line_idx = 1
            async for line in f:
                formatted = _format_line(line_idx, line, MAX_LINE_CHARS)
                output.append(formatted)
                current_total_len += len(formatted)
                
                if line_idx >= MAX_LINES or current_total_len > MAX_TOTAL_CHARS:
                    truncated = True
                    break
                line_idx += 1

        res = "\n".join(output)
        if truncated:
            res += f"\n\n... [Warning] Content truncated (Safety Limit). Last line read: {line_idx}."
            res += f"\n💡 [Hint] The file is large or has very long lines. Use 'read_file_range_local' to explore specific sections."
        
        # 脱敏处理
        return _maybe_mask_output(path, res)
    except Exception as e: 
        return f"[Error] Read failed: {str(e)}"  

async def read_file_range_tool_local(path: str, start_line: int, end_line: int) -> str:
    """[Local] 精准读取文件指定行范围,增加溢出保护"""
    try:
        MAX_TOTAL_CHARS = 30000  # 单次返回最大字符数,防止上下文爆炸
        MAX_LINE_CHARS = 1000    # 单行最大显示长度
        
        if start_line < 1 or end_line < start_line:
            return "[Error] Invalid line range."
            
        cwd = await _get_current_cwd()
        target = resolve_strict_path(cwd, path, check_symlink=True)
        if not target.exists() or not target.is_file(): 
            return f"[Error] File not found: {path}"

        output = []
        current_total_len = 0
        
        async with aiofiles.open(target, 'r', encoding='utf-8', errors='replace') as f:
            line_idx = 1
            async for line in f:
                if line_idx >= start_line:
                    formatted = _format_line(line_idx, line, MAX_LINE_CHARS)
                    output.append(formatted)
                    current_total_len += len(formatted)
                    
                    if current_total_len > MAX_TOTAL_CHARS:
                        output.append(f"--- [Warning] Output stopped: Reached limit of {MAX_TOTAL_CHARS} chars ---")
                        break
                
                if line_idx >= end_line:
                    break
                line_idx += 1
            
        if not output and line_idx < start_line:
            return f"[Error] start_line ({start_line}) is beyond file length ({line_idx})."
        
        res = "\n".join(output)
        # 脱敏处理
        return _maybe_mask_output(path, res)
    except Exception as e: 
        return f"[Error] Range read failed: {str(e)}"

async def tail_file_tool_local(path: str, lines: int = 100) -> str:
    """[Local] 读取文件末尾"""
    try:
        cwd = await _get_current_cwd()
        target = resolve_strict_path(cwd, path, check_symlink=True)
        if not target.exists() or not target.is_file(): return f"[Error] File not found: {path}"

        async with aiofiles.open(target, 'r', encoding='utf-8', errors='replace') as f:
            all_lines = await f.readlines()
            
        subset = all_lines[-lines:] if lines < len(all_lines) else all_lines
        start_idx = max(1, len(all_lines) - lines + 1)
        
        res = "\n".join(_format_line(i + start_idx, line) for i, line in enumerate(subset))
        return _maybe_mask_output(path, res)
    except Exception as e: return f"[Error] Tail failed: {str(e)}"
    
async def edit_file_tool_local(path: str, content: str) -> str:
    """[Local] 写入文件:修复了绝对路径误判问题"""
    try:
        cwd = await _get_current_cwd()
        # 这一步已经确保了 path 不会逃逸出 cwd
        target = resolve_strict_path(cwd, path, check_symlink=True)
        
        # 1. 确保父目录存在
        parent_dir = target.parent
        # --- 删除了导致报错的 resolve_strict_path(cwd, str(parent_dir)...) ---
        
        await aiofiles.os.makedirs(parent_dir, exist_ok=True)

        # 2. 创建备份 (如果文件存在)
        backup_msg = ""
        if target.exists():
            try:
                backup_path = target.with_suffix(target.suffix + ".bak")
                shutil.copy2(target, backup_path)
                backup_msg = f" (Backup created: {backup_path.name})"
            except Exception as e:
                print(f"[Warn] Backup failed: {e}")

        # 3. 原子写入
        temp_path = target.with_suffix(target.suffix + f".tmp.{uuid.uuid4().hex[:6]}")
        try:
            async with aiofiles.open(temp_path, 'w', encoding='utf-8') as f:
                await f.write(content)
            
            if os.path.exists(target):
                os.replace(temp_path, target)
            else:
                os.rename(temp_path, target)
        except Exception as e:
            if os.path.exists(temp_path):
                os.remove(temp_path)
            raise e

        return f"Saved successfully{backup_msg}."

    except Exception as e:
        return f"[Error] Edit failed: {str(e)}"

async def search_files_tool_local(pattern: str, path: str = ".") -> str:
    """[Local] 智能搜索:支持正则表达式,自动跳过二进制文件和常见忽略目录"""
    try:
        cwd = await _get_current_cwd()
        target_dir = resolve_strict_path(cwd, path, check_symlink=True)
        target_str = str(target_dir)
        
        # 使用 Python 实现搜索
        matches = []
        regex = re.compile(pattern)
        MAX_RESULTS = 1000
        
        SKIP_DIRS = {'.git', 'node_modules', '__pycache__', 'venv', '.env', 'dist', 'build', 'coverage'}
        SKIP_EXTS = {'.pyc', '.pyo', '.so', '.dll', '.exe', '.bin', '.png', '.jpg', '.jpeg', '.gif', '.zip', '.tar', '.gz'}

        def is_binary(file_path):
            try:
                with open(file_path, 'rb') as f:
                    return b'\0' in f.read(1024)
            except: return True

        for root, dirs, files in os.walk(target_str, topdown=True):
            dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith('.')]
            
            for file in files:
                if any(file.endswith(ext) for ext in SKIP_EXTS): continue
                full_path = os.path.join(root, file)
                display_path = os.path.relpath(full_path, cwd)
                
                if is_binary(full_path): continue

                try:
                    async with aiofiles.open(full_path, 'r', encoding='utf-8', errors='replace') as f:
                        content = await f.read()
                        lines = content.splitlines()
                        for i, line in enumerate(lines, 1):
                            if regex.search(line):
                                clean_line = line.strip()[:200]
                                if _is_env_file(file):
                                    clean_line = _mask_env_content(clean_line)
                                matches.append(f"{display_path}:{i}:{clean_line}")
                                if len(matches) >= MAX_RESULTS:
                                    return "\n".join(matches) + f"\n... (Truncated at {MAX_RESULTS} matches)"
                except Exception:
                    continue

        return "\n".join(matches) if matches else "No matches found."
    except Exception as e:
        return f"[Error] Search failed: {str(e)}"


async def glob_files_tool_local(pattern: str, exclude: str = "") -> str:
    """[Local] 智能查找:使用 pathlib.glob 支持 ** 递归,兼容 Windows"""
    try:
        cwd = await _get_current_cwd()
        base = Path(cwd).resolve()

        excludes = [e.strip() for e in exclude.split(",") if e.strip()]
        DEFAULT_EXCLUDES = {'.git', 'node_modules', '__pycache__', 'venv', 'dist', 'build'}

        # 使用 pathlib 的 glob,天然支持 ** 递归,并且与系统分隔符无关
        matched_paths = list(base.glob(pattern))

        results = []
        for p in matched_paths:
            if not p.is_file():
                continue

            # 计算相对路径,用于后续匹配 and 输出
            try:
                rel = p.relative_to(base)
            except ValueError:
                # 如果路径不在 base 内(理论上不会发生),跳过
                continue

            rel_str = rel.as_posix()  # 统一使用正斜杠,跨平台一致

            # 排除命中 exclude 参数中的模式
            if any(fnmatch.fnmatch(rel_str, ex) for ex in excludes):
                continue

            # 排除默认隐藏/构建目录(检查路径中的每一级目录)
            parts = rel.parts
            if any(part in DEFAULT_EXCLUDES or part.startswith('.') for part in parts):
                continue

            results.append(rel_str)

        output = sorted(results)
        limit = 200
        if not output:
            return "No files matched."
        if len(output) > limit:
            return "\n".join(output[:limit]) + f"\n... ({len(output)-limit} more files)"
        return "\n".join(output)

    except Exception as e:
        return f"[Error] Glob failed: {str(e)}"

async def edit_file_string_tool_local(path: str, old_string: str, new_string: str, replace_all: bool = False) -> str:
    """[Local] 精确字符串替换(基于 old_string/new_string,类似 opencode 的 Edit 工具)"""
    try:
        cwd = await _get_current_cwd()
        target = resolve_strict_path(cwd, path, check_symlink=True)
        if not target.exists():
            return f"[Error] File not found: {path}"

        async with aiofiles.open(target, 'r', encoding='utf-8') as f:
            content = await f.read()

        success, new_content, msg = _apply_patch(content, old_string, new_string, replace_all)
        if not success:
            return msg

        try:
            backup_path = target.with_suffix(target.suffix + ".bak")
            shutil.copy2(target, backup_path)
        except: pass

        async with aiofiles.open(target, 'w', encoding='utf-8', newline='\n') as f:
            await f.write(new_content)

        return f"[Success] {msg}"
    except Exception as e:
        return f"[Error] String edit failed: {str(e)}"

async def edit_file_string_tool(path: str, old_string: str, new_string: str, replace_all: bool = False) -> str:
    """[Docker] 精确字符串替换(基于 old_string/new_string,类似 opencode 的 Edit 工具)"""
    try:
        real_cwd = await _get_current_cwd()
        container_name = await get_or_create_docker_sandbox(real_cwd)

        try:
            script = f"""
            import sys
            with open("{path}", "rb") as f:
                sys.stdout.buffer.write(f.read())
            """
            content = await _exec_docker_cmd_simple(real_cwd, ["python3", "-c", script])
        except Exception as e:
            return f"[Error] Cannot read file for editing: {e}"

        success, new_content, msg = _apply_patch(content, old_string, new_string, replace_all)
        if not success:
            return msg

        with tempfile.NamedTemporaryFile(mode='w', delete=False, encoding='utf-8', newline='\n') as tmp:
            tmp.write(new_content)
            tmp_path = tmp.name

        dest_path = f"{container_name}:/workspace/{path}"
        cp_proc = await asyncio.create_subprocess_exec("docker", "cp", tmp_path, dest_path, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        await cp_proc.communicate()
        os.unlink(tmp_path)

        if cp_proc.returncode != 0:
            return "[Error] String edit copy failed."
        return f"[Success] {msg}"
    except Exception as e:
        return f"[Error] String edit failed: {str(e)}"

async def todo_write_tool_local(action: str, id: str = None, content: str = None, 
                                priority: str = "medium", status: str = None) -> str:
    """本地待办任务管理工具 - 使用3位数字有序ID"""
    try:
        cwd = await _get_current_cwd()
        party_dir = Path(cwd) / ".agents"
        if not party_dir.exists():
            await aiofiles.os.makedirs(party_dir, exist_ok=True)
        
        todo_file = party_dir / "ai_todos.json"
        
        # 读取现有任务
        todos = []
        if todo_file.exists():
            try:
                async with aiofiles.open(todo_file, 'r', encoding='utf-8') as f:
                    file_content = await f.read()
                    if file_content.strip():
                        todos = json.loads(file_content)
            except (json.JSONDecodeError, Exception):
                todos = []
            
        msg = ""

        # 生成下一个有序ID的辅助函数
        def _generate_ordered_id(existing_todos):
            if not existing_todos:
                return "1"
            # 找出最大数字 ID(兼容旧数据)
            numeric_ids = [int(t['id']) for t in existing_todos if t['id'].isdigit()]
            if not numeric_ids:
                return "1"
            return str(max(numeric_ids) + 1)  # 1, 2, 3... 不补零,不限制位数

        if action == "create":
            """创建新任务 - 自动生成3位数字有序ID"""
            if not content: 
                return "[Error] 创建任务必须提供 content 参数"
            
            new_id = _generate_ordered_id(todos)
            new_todo = {
                "id": new_id,
                "content": content,
                "priority": priority,
                "status": "pending",
                "created_at": datetime.now().isoformat(),
                "completed_at": None
            }
            todos.append(new_todo)
            msg = f"[Success] 已创建任务 #{new_id}: {content[:30]}"
            
        elif action == "list":
            """列出所有任务 - 按ID数字大小排序"""
            if not todos: 
                return "当前项目暂无任务"
            
            lines = ["📋 **项目任务列表** (ID越大创建越晚):"]
            # 按ID数字排序,确保展示有序性
            sorted_todos = sorted(todos, key=lambda x: int(x['id']) if x['id'].isdigit() else 0)
            
            for t in sorted_todos:
                status_icon = "✅" if t.get('status') == 'done' else "⏳"
                priority_map = {"high": "🔴", "medium": "🟡", "low": "🟢"}
                p_icon = priority_map.get(t.get('priority', 'medium'), "⚪")
                lines.append(f"{status_icon} [{t['id']}] {p_icon} {t['content'][:40]}")
            return "\n".join(lines)

        elif action == "complete":
            """【高频】标记任务为已完成 - 幂等操作"""
            if not id: 
                return "[Error] 完成任务必须提供 id (如: 001)"
            
            target = next((t for t in todos if t['id'] == id), None)
            if not target: 
                return f"[Error] 未找到任务 #{id}"
            
            if target.get('status') == 'done':
                msg = f"[Info] 任务 #{id} 已经是完成状态"
            else:
                target['status'] = 'done'
                target['completed_at'] = datetime.now().isoformat()
                msg = f"[Success] 已完成任务 #{id}"

        elif action == "toggle":
            """切换完成状态 - pending↔done"""
            if not id: 
                return "[Error] 切换状态必须提供 id"
            
            target = next((t for t in todos if t['id'] == id), None)
            if not target: 
                return f"[Error] 未找到任务 #{id}"
            
            if target.get('status') != 'done':
                target['status'] = 'done'
                target['completed_at'] = datetime.now().isoformat()
                msg = f"[Success] 已完成任务 #{id}"
            else:
                target['status'] = 'pending'
                target['completed_at'] = None
                msg = f"[Success] 已重新打开任务 #{id}"

        elif action == "update":
            """编辑任务详情"""
            if not id: 
                return "[Error] 更新任务必须提供 id"
            
            target = next((t for t in todos if t['id'] == id), None)
            if not target: 
                return f"[Error] 未找到任务 #{id}"
            
            if content: 
                target['content'] = content
            if priority: 
                target['priority'] = priority
            
            if status:
                if status == "done" and target.get('status') != "done":
                    target['completed_at'] = datetime.now().isoformat()
                elif status != "done" and target.get('status') == "done":
                    target['completed_at'] = None
                target['status'] = status
            
            target['updated_at'] = datetime.now().isoformat()
            msg = f"[Success] 已更新任务 #{id}"

        elif action == "delete":
            """删除任务"""
            if not id: 
                return "[Error] 删除任务必须提供 id"
            
            target = next((t for t in todos if t['id'] == id), None)
            if not target: 
                return f"[Error] 未找到任务 #{id}"
            
            todos.remove(target)
            msg = f"[Success] 已删除任务 #{id}"

        else:
            return f"[Error] 未知操作: {action}"

        # 保存到本地文件
        async with aiofiles.open(todo_file, 'w', encoding='utf-8') as f:
            await f.write(json.dumps(todos, indent=2, ensure_ascii=False))
            
        return msg

    except Exception as e:
        return f"[Error] 操作失败: {str(e)}"
    
# ==================== [新增] Skill 专用读取工具 ====================

async def read_skill_tool_logic(cwd: str, skill_id: str, is_docker: bool = True) -> str:
    """
    内部通用逻辑:读取 Skill 文件夹结构和说明文档。
    若工作区不存在该技能,且全局技能目录可用,则自动复制到工作区(Docker/Local 均支持)。
    """
    skill_rel_path = f".agents/skills/{skill_id}"
    workspace_skill_path = f"/workspace/.agents/skills/{skill_id}" if is_docker else str(Path(cwd) / ".agents" / "skills" / skill_id)

    # ----- 复制逻辑:工作区缺失时,从全局复制 -----
    if is_docker:
        # Docker 环境:利用已映射的全局技能目录
        container_name = await get_or_create_docker_sandbox(cwd)          # 获取/创建容器
        global_skill_path = f"/home/agent/.agents/skills/{skill_id}"      # 容器内全局技能路径
        try:
            # 1. 检查工作区技能是否存在
            test_cmd = ["test", "-d", workspace_skill_path]
            await _exec_docker_cmd_simple(cwd, test_cmd)                  # 不存在会抛出异常
        except Exception:
            # 2. 工作区不存在,尝试从全局复制
            try:
                # 检查全局技能是否存在
                test_global = ["test", "-d", global_skill_path]
                await _exec_docker_cmd_simple(cwd, test_global)

                # 确保目标父目录存在
                mkdir_cmd = ["mkdir", "-p", f"/workspace/.agents/skills"]
                await _exec_docker_cmd_simple(cwd, mkdir_cmd)

                # 执行复制
                cp_cmd = ["cp", "-r", global_skill_path, f"/workspace/.agents/skills/"]
                await _exec_docker_cmd_simple(cwd, cp_cmd)

                print(f"[Skill AutoCopy][Docker] Copied global skill '{skill_id}' to workspace.")
            except Exception as e:
                # 复制失败或全局技能不存在,继续尝试读取工作区(若不存在则后续报错)
                pass
    else:
        # Local 环境:使用 shutil 复制(已实现,但整合到 logic 中统一管理)
        workspace_path = Path(cwd) / ".agents" / "skills" / skill_id
        if not workspace_path.exists():
            global_path = Path(SKILLS_DIR) / skill_id
            if global_path.exists() and global_path.is_dir():
                try:
                    workspace_path.parent.mkdir(parents=True, exist_ok=True)
                    await asyncio.to_thread(
                        shutil.copytree,
                        global_path,
                        workspace_path,
                        dirs_exist_ok=True
                    )
                    print(f"[Skill AutoCopy][Local] Copied global skill '{skill_id}' to workspace.")
                except Exception as e:
                    print(f"[Skill AutoCopy][Local] Copy failed: {e}. Will fallback to global read.")
                    # 降级读取已由主流程处理

    # ----- 原有读取逻辑保持不变(读取工作区技能)-----
    tree_str = ""
    doc_content = ""

    if is_docker:
        try:
            tree_str = await _exec_docker_cmd_simple(cwd, ["find", skill_rel_path, "-maxdepth", "2", "-not", "-path", '*/.*'])
            for name in ["SKILL.md", "skill.md", "SKILLS.md", "skills.md"]:
                try:
                    doc_path = f"{skill_rel_path}/{name}"
                    doc_content = await _exec_docker_cmd_simple(cwd, ["cat", doc_path])
                    break
                except:
                    continue
        except Exception as e:
            return f"[Error] Skill '{skill_id}' not found or inaccessible in Docker: {str(e)}"
    else:
        try:
            base_path = Path(cwd) / ".agents" / "skills" / skill_id
            if not base_path.exists():
                return f"[Error] Skill '{skill_id}' folder does not exist in workspace and auto-copy failed or global skill unavailable."

            # 生成本地文件树(深度 ≤2)
            tree_lines = [f"{skill_id}/"]
            for p in base_path.rglob("*"):
                if p.name.startswith("."): continue
                depth = len(p.relative_to(base_path).parts)
                if depth > 2: continue
                indent = "  " * depth
                tree_lines.append(f"{indent}{p.name}{'/' if p.is_dir() else ''}")
            tree_str = "\n".join(tree_lines)

            # 读取本地说明文档
            for name in ["SKILL.md", "skill.md", "SKILLS.md", "skills.md"]:
                doc_path = base_path / name
                if doc_path.exists():
                    async with aiofiles.open(doc_path, 'r', encoding='utf-8', errors='replace') as f:
                        doc_content = await f.read()
                    break
        except Exception as e:
            return f"[Error] Skill '{skill_id}' read failed: {str(e)}"

    if not doc_content and not tree_str:
        return f"[Error] Could not find skill details for '{skill_id}'."

    res = f"--- Skill Details: {skill_id} ---\n"
    res += f"\n📂 **Folder Structure:**\n```\n{tree_str}\n```\n"
    res += f"\n📖 **Documentation ({skill_rel_path}):**\n\n{doc_content or '(No SKILL.md found)'}"
    return res

async def read_skill_tool(skill_id: str) -> str:
    """[Docker] 读取特定技能的完整文档和文件树"""
    cwd = await _get_current_cwd()
    return await read_skill_tool_logic(cwd, skill_id, is_docker=True)

async def read_skill_tool_local(skill_id: str) -> str:
    """[Local] 读取特定技能的完整文档和文件树"""
    cwd = await _get_current_cwd()
    return await read_skill_tool_logic(cwd, skill_id, is_docker=False)

COMMON_BASH_DESC = (
    "Execute commands. Guidance: \n"
    "1. For long-running tasks (servers, watchers, large downloads), set 'background': true.\n"
    "2. For medium tasks, adjust 'timeout' (1-3600s, default 600s).\n"
    "3. If 'background' is true, wait a few seconds for initialization before checking logs/status; do not poll rapidly."
)

# ==================== 工具注册表 (完整) ====================

TOOLS_REGISTRY = {
    # --- 只读 ---
    "list_files": {
        "type": "function", "function": {
            "name": "list_files_tool", 
            "description": "List files in docker workspace.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Relative path to list files in (from workspace root)."
                    }, 
                    "show_all": {"type": "boolean", "default": True}
                }, 
                "required": ["path"]
            }
        }
    },
    "read_file": {
        "type": "function", "function": {
            "name": "read_file_tool", 
            "description": "Read file content.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Relative path to file (from workspace root)."
                    }
                }, 
                "required": ["path"]
            }
        }
    },
    "read_file_range": {
        "type": "function", "function": {
            "name": "read_file_range_tool", 
            "description": "Read a specific range of lines from a file. Useful for large files after grepping.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "path": {"type": "string", "description": "Relative path to file"},
                    "start_line": {"type": "integer"},
                    "end_line": {"type": "integer"}
                }, 
                "required": ["path", "start_line", "end_line"]
            }
        }
    },
    "tail_file": {
        "type": "function", "function": {
            "name": "tail_file_tool", 
            "description": "Read the last N lines of a file. Useful for reading logs.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "path": {"type": "string", "description": "Relative path to file"},
                    "lines": {"type": "integer", "default": 100, "description": "Number of lines to read from the end"}
                }, 
                "required": ["path"]
            }
        }
    },
    "search_files": {
        "type": "function", "function": {
            "name": "search_files_tool", 
            "description": "Grep search.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "pattern": {"type": "string"}, 
                    "path": {
                        "type": "string",
                        "description": "Relative path to directory to search in (from workspace root)."
                    }
                }, 
                "required": ["pattern"]
            }
        }
    },
    "glob_files": {
        "type": "function", "function": {
            "name": "glob_files_tool", 
            "description": "Recursive glob.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "pattern": {
                        "type": "string",
                        "description": "Glob pattern (relative to workspace root)."
                    }, 
                    "exclude": {"type": "string"}
                }, 
                "required": ["pattern"]
            }
        }
    },
    "read_skill": {
        "type": "function", "function": {
            "name": "read_skill_tool", 
            "description": "Read full documentation and file tree for a project-specific skill from .agents/skills/.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "skill_id": {"type": "string"}
                }, 
                "required": ["skill_id"]
            }
        }
    },
    # --- 编辑 ---
    "edit_file": {
        "type": "function", "function": {
            "name": "edit_file_tool", 
            "description": "Overwrite file.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Relative path to file (from workspace root)."
                    }, 
                    "content": {"type": "string"}
                }, 
                "required": ["path", "content"]
            }
        }
    },
    "edit_file_string": {
        "type": "function", "function": {
            "name": "edit_file_string_tool",
            "description": "Performs exact string replacements in files. The edit will FAIL if old_string is not unique in the file. Provide larger strings with more surrounding context to make it unique. If you want to replace all occurrences, use replace_all: true.",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Relative path to file (from workspace root)."
                    },
                    "old_string": {
                        "type": "string",
                        "description": "The exact text to replace. Must match exactly including whitespace and indentation."
                    },
                    "new_string": {
                        "type": "string",
                        "description": "The exact text to replace it with (must be different from old_string)."
                    },
                    "replace_all": {
                        "type": "boolean",
                        "default": False,
                        "description": "Replace all occurrences of old_string (default false). When false, the edit will FAIL if old_string is found multiple times."
                    }
                },
                "required": ["path", "old_string", "new_string"]
            }
        }
    },
    # --- 任务 ---
    "todo_write": {
        "type": "function",
        "function": {
            "name": "todo_write_tool",
            "description": "[Docker] 待办任务管理工具。用于在 Docker 沙箱环境中管理任务列表,支持创建、查看、完成、编辑、删除等操作。所有任务持久化存储在容器的 /workspace/.agents/ai_todos.json 文件中。",
            "parameters": {
                "type": "object",
                "properties": {
                    "action": {
                        "type": "string",
                        "enum": ["create", "list", "complete", "toggle", "update", "delete"],
                        "description": "操作类型:create(创建), list(查看所有), complete(标记完成-幂等安全), toggle(切换状态-会反向), update(编辑详情), delete(删除)"
                    },
                    "id": {
                        "type": "string",
                        "description": "任务唯一标识。create时可选(自动生成),其他操作(complete/toggle/update/delete)时必需"
                    },
                    "content": {
                        "type": "string",
                        "description": "任务内容描述。create时必需,update时可选"
                    },
                    "priority": {
                        "type": "string",
                        "enum": ["high", "medium", "low"],
                        "description": "优先级:high(高), medium(中/默认), low(低)。create/update时可选"
                    },
                    "status": {
                        "type": "string",
                        "enum": ["pending", "done"],
                        "description": "【仅用于update】强制设置任务状态:pending(未完成), done(已完成)。注意:标记完成建议使用complete动作而非status参数"
                    }
                },
                "required": ["action"]
            }
        }
    },
    # --- 基础设施 ---
    "bash": {
        "type": "function", "function": {
            "name": "docker_sandbox", 
            "description": f"[Docker] {COMMON_BASH_DESC}",
            "parameters": {
                "type": "object", 
                "properties": {
                    "command": {"type": "string"}, 
                    "background": {"type": "boolean", "description": "Run non-blocking. Returns PID."},
                    "timeout": {
                        "type": "integer", 
                        "default": 60, 
                        "description": "Max execution time in seconds (1-3600). Default 60."
                    }
                }, 
                "required": ["command"]
            }
        }
    },
    "list_processes": {
        "type": "function",
        "function": {
            "name": "list_processes_tool",
            "description": "List all running background processes (both Docker containers and local processes).",
            "parameters": {
                "type": "object",
                "properties": {},
                "required": []
            }
        }
    },
    "get_process_logs": {
        "type": "function",
        "function": {
            "name": "get_process_logs_tool",
            "description": "Retrieve logs for a specific background process using its PID or Container ID.",
            "parameters": {
                "type": "object",
                "properties": {
                    "pid": {
                        "type": "string",
                        "description": "The process ID or container ID to fetch logs for."
                    }
                },
                "required": ["pid"]
            }
        }
    },
    "kill_process": {
        "type": "function",
        "function": {
            "name": "kill_process_tool",
            "description": "Terminate a background process or stop a Docker container using its PID or ID.",
            "parameters": {
                "type": "object",
                "properties": {
                    "pid": {
                        "type": "string",
                        "description": "The process ID or container ID to terminate."
                    }
                },
                "required": ["pid"]
            }
        }
    },
    "manage_ports": {
        "type": "function", "function": {
            "name": "docker_manage_ports_tool", 
            "description": "Forward Docker ports to localhost.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "action": {"type": "string", "enum": ["forward", "stop", "list"]},
                    "container_port": {"type": "integer"},
                    "host_port": {"type": "integer"}
                }, 
                "required": ["action"]
            }
        }
    },
    "send_process_input": {
        "type": "function", "function": {
            "name": "send_process_input_tool",
            "description": "Send standard input (stdin) to an active background process (e.g., sending 'y' or 'yes' to interactive confirmation prompts).",
            "parameters": {
                "type": "object",
                "properties": {
                    "pid": {
                        "type": "string",
                        "description": "The background process ID (PID) to send input to."
                    },
                    "text": {
                        "type": "string",
                        "description": "The text to send to the process. A newline character will be automatically appended if it is missing."
                    }
                },
                "required": ["pid", "text"]
            }
        }
    },
}

LOCAL_TOOLS_REGISTRY = {
    # --- 只读 ---
    "list_files_local": {
        "type": "function", "function": {
            "name": "list_files_tool_local", 
            "description": "List local files.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Relative path to list files in (from current working directory)."
                    }, 
                    "show_all": {"type": "boolean","default": True}
                }, 
                "required": ["path"]
            }
        }
    },
    "read_file_local": {
        "type": "function", "function": {
            "name": "read_file_tool_local", 
            "description": "Read local file.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Relative path to file (from current working directory)."
                    }
                }, 
                "required": ["path"]
            }
        }
    },
    "read_file_range_local": {
        "type": "function", "function": {
            "name": "read_file_range_tool_local", 
            "description": "Read a specific range of lines from a local file. Useful for large files after grepping.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "path": {"type": "string", "description": "Relative path to file"},
                    "start_line": {"type": "integer", "description": "The line number to start reading from."},
                    "end_line": {"type": "integer", "description": "The line number to stop reading at."}
                }, 
                "required": ["path", "start_line", "end_line"]
            }
        }
    },
    "tail_file_local": {
        "type": "function", "function": {
            "name": "tail_file_tool_local", 
            "description": "Read the last N lines of a local file. Useful for reading logs.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "path": {"type": "string", "description": "Relative path to file"},
                    "lines": {"type": "integer", "default": 100}
                }, 
                "required": ["path"]
            }
        }
    },
    "search_files_local": {
         "type": "function", "function": {
            "name": "search_files_tool_local", 
            "description": "Search local files.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "pattern": {"type": "string"},
                    "path": {"type": "string", "description": "Relative directory to search in (default .)"}
                },
                "required": ["pattern"]
            }
        }
    },
    "glob_files_local": {
         "type": "function", "function": {
            "name": "glob_files_tool_local", 
            "description": "Glob local files.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "pattern": {
                        "type": "string",
                        "description": "Glob pattern (relative to current working directory)."
                    },
                    "exclude": {"type": "string", "description": "Comma-separated patterns to exclude"}
                }, 
                "required": ["pattern"]
            }
        }
    },
    "read_skill_local": {
        "type": "function", "function": {
            "name": "read_skill_tool_local", 
            "description": "Read full documentation and file tree for a project-specific skill from .agents/skills/ (Local).",
            "parameters": {
                "type": "object", 
                "properties": {
                    "skill_id": {"type": "string", "description": "The ID of the skill to read."}
                }, 
                "required": ["skill_id"]
            }
        }
    },
    # --- 编辑 ---
    "edit_file_local": {
        "type": "function", "function": {
            "name": "edit_file_tool_local", 
            "description": "Write local file.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Relative path to file (from current working directory)."
                    }, 
                    "content": {"type": "string", "description": "Full file content"}
                }, 
                "required": ["path", "content"]
            }
        }
    },
    "edit_file_string_local": {
        "type": "function", "function": {
            "name": "edit_file_string_tool_local",
            "description": "Performs exact string replacements in local files. The edit will FAIL if old_string is not unique in the file. Provide larger strings with more surrounding context to make it unique. If you want to replace all occurrences, use replace_all: true.",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Relative path to file (from current working directory)."
                    },
                    "old_string": {
                        "type": "string",
                        "description": "The exact text to replace. Must match exactly including whitespace and indentation."
                    },
                    "new_string": {
                        "type": "string",
                        "description": "The exact text to replace it with (must be different from old_string)."
                    },
                    "replace_all": {
                        "type": "boolean",
                        "default": False,
                        "description": "Replace all occurrences of old_string (default false). When false, the edit will FAIL if old_string is found multiple times."
                    }
                },
                "required": ["path", "old_string", "new_string"]
            }
        }
    },
    "todo_write_local": {
        "type": "function",
        "function": {
            "name": "todo_write_tool_local",
            "description": "本地待办任务管理工具。用于管理项目中的任务列表,包括创建、查看、完成、编辑、删除等操作。所有任务持久化存储在项目根目录的 .agents/ai_todos.json 文件中。",
            "parameters": {
                "type": "object",
                "properties": {
                    "action": {
                        "type": "string",
                        "enum": ["create", "list", "complete", "toggle", "update", "delete"],
                        "description": "操作类型:create(创建), list(查看所有), complete(标记完成-幂等), toggle(切换状态-会反向), update(编辑详情), delete(删除)"
                    },
                    "id": {
                        "type": "string",
                        "description": "任务唯一标识。create时可选(自动生成),其他操作(complete/toggle/update/delete)时必需"
                    },
                    "content": {
                        "type": "string",
                        "description": "任务内容描述。create时必需,update时可选"
                    },
                    "priority": {
                        "type": "string",
                        "enum": ["high", "medium", "low"],
                        "description": "优先级:high(高), medium(中/默认), low(低)。create/update时可选"
                    },
                    "status": {
                        "type": "string",
                        "enum": ["pending", "done"],
                        "description": "【仅用于update】强制设置任务状态:pending(未完成), done(已完成)。注意:标记完成建议使用complete动作而非status参数"
                    }
                },
                "required": ["action"]
            }
        }
    },
    # --- 基础设施 ---
    "bash_local": {
        "type": "function", "function": {
            "name": "shell_tool_local", 
            "description": f"[Local] {COMMON_BASH_DESC}",
            "parameters": {
                "type": "object", 
                "properties": {
                    "command": {"type": "string"},
                    "background": {"type": "boolean", "description": "Run in background."},
                    "timeout": {
                        "type": "integer", 
                        "default": 60, 
                        "description": "Max execution time in seconds (1-3600). Default 60."
                    }
                }, 
                "required": ["command"]
            }
        }
    },
    "list_processes": {
        "type": "function",
        "function": {
            "name": "list_processes_tool",
            "description": "List all running background processes (both Docker containers and local processes).",
            "parameters": {
                "type": "object",
                "properties": {},
                "required": []
            }
        }
    },
    "get_process_logs": {
        "type": "function",
        "function": {
            "name": "get_process_logs_tool",
            "description": "Retrieve logs for a specific background process using its PID or Container ID.",
            "parameters": {
                "type": "object",
                "properties": {
                    "pid": {
                        "type": "string",
                        "description": "The process ID or container ID to fetch logs for."
                    }
                },
                "required": ["pid"]
            }
        }
    },
    "kill_process": {
        "type": "function",
        "function": {
            "name": "kill_process_tool",
            "description": "Terminate a background process or stop a Docker container using its PID or ID.",
            "parameters": {
                "type": "object",
                "properties": {
                    "pid": {
                        "type": "string",
                        "description": "The process ID or container ID to terminate."
                    }
                },
                "required": ["pid"]
            }
        }
    },
    "local_net_tool": {
        "type": "function", "function": {
            "name": "local_net_tool", 
            "description": "Check local ports.",
            "parameters": {
                "type": "object", 
                "properties": {
                    "action": {"type": "string", "enum": ["check", "scan"]},
                    "port": {"type": "integer"}
                }, 
                "required": ["action"]
            }
        }
    },
    "send_process_input_local": {
        "type": "function", "function": {
            "name": "send_process_input_tool",
            "description": "Send standard input (stdin) to an active local background process (e.g., sending 'y' or 'yes' to interactive confirmation prompts).",
            "parameters": {
                "type": "object",
                "properties": {
                    "pid": {
                        "type": "string",
                        "description": "The background process ID (PID) to send input to."
                    },
                    "text": {
                        "type": "string",
                        "description": "The text to send to the process. A newline character will be automatically appended if it is missing."
                    }
                },
                "required": ["pid", "text"]
            }
        }
    },
}

def get_tools_for_mode(mode: str) -> list:
    """获取 Docker 环境工具集"""
    # 基础只读
    read = [TOOLS_REGISTRY["list_files"], 
            TOOLS_REGISTRY["read_file"], 
            TOOLS_REGISTRY["read_file_range"],
            TOOLS_REGISTRY["tail_file"],     
            TOOLS_REGISTRY["search_files"], 
            TOOLS_REGISTRY["glob_files"],
            TOOLS_REGISTRY["read_skill"]
            ]
    # 编辑
    edit = [TOOLS_REGISTRY["edit_file"], TOOLS_REGISTRY["edit_file_string"], TOOLS_REGISTRY["todo_write"]]
    # 基础设施 (执行/进程/端口)
    infra = [TOOLS_REGISTRY["bash"], TOOLS_REGISTRY["list_processes"], TOOLS_REGISTRY["get_process_logs"], TOOLS_REGISTRY["kill_process"], TOOLS_REGISTRY["manage_ports"]]
    
    if mode == "default": return read
    if mode == "auto-approve": return read + edit + [TOOLS_REGISTRY["list_processes"], TOOLS_REGISTRY["get_process_logs"], TOOLS_REGISTRY["kill_process"],TOOLS_REGISTRY["send_process_input"]]
    if mode == "yolo": return read + edit + infra
    return read

def get_local_tools_for_mode(mode: str) -> list:
    """获取 Local 环境工具集"""
    read = [
        LOCAL_TOOLS_REGISTRY["list_files_local"], 
        LOCAL_TOOLS_REGISTRY["read_file_local"], 
        LOCAL_TOOLS_REGISTRY["read_file_range_local"],
        LOCAL_TOOLS_REGISTRY["tail_file_local"],    
        LOCAL_TOOLS_REGISTRY["search_files_local"], 
        LOCAL_TOOLS_REGISTRY["glob_files_local"],
        LOCAL_TOOLS_REGISTRY["read_skill_local"] 
    ]
    edit = [LOCAL_TOOLS_REGISTRY["edit_file_local"], LOCAL_TOOLS_REGISTRY["edit_file_string_local"], LOCAL_TOOLS_REGISTRY["todo_write_local"]]
    infra = [
        LOCAL_TOOLS_REGISTRY["bash_local"], 
        LOCAL_TOOLS_REGISTRY["list_processes"], LOCAL_TOOLS_REGISTRY["get_process_logs"], LOCAL_TOOLS_REGISTRY["kill_process"],
        LOCAL_TOOLS_REGISTRY["local_net_tool"]
    ]
    
    if mode == "default": return read
    if mode == "auto-approve": return read + edit + [LOCAL_TOOLS_REGISTRY["list_processes"], LOCAL_TOOLS_REGISTRY["get_process_logs"], LOCAL_TOOLS_REGISTRY["kill_process"], LOCAL_TOOLS_REGISTRY["local_net_tool"],LOCAL_TOOLS_REGISTRY["send_process_input_local"]]
    if mode == "yolo": return read + edit + infra
    return read