mofa-foundation 0.1.1

MoFA Foundation - Core building blocks and utilities
Documentation
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
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
//! 标准 LLM Agent 实现
//!
//! 框架提供的开箱即用的 LLM Agent,用户只需配置 provider 即可使用
//!
//! # 示例
//!
//! ```rust,ignore
//! use mofa_sdk::kernel::AgentInput;
//! use mofa_sdk::runtime::run_agents;
//! use mofa_sdk::llm::LLMAgentBuilder;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let agent = LLMAgentBuilder::from_env()?
//!         .with_id("my-llm-agent")
//!         .with_system_prompt("You are a helpful assistant.")
//!         .build();
//!
//!     let outputs = run_agents(agent, vec![AgentInput::text("Hello")]).await?;
//!     println!("{}", outputs[0].to_text());
//!     Ok(())
//! }
//! ```

use super::client::{ChatSession, LLMClient};
use super::provider::{ChatStream, LLMProvider};
use super::tool_executor::ToolExecutor;
use super::types::{ChatMessage, LLMError, LLMResult, Tool};
use crate::llm::{
    AnthropicConfig, AnthropicProvider, GeminiConfig, GeminiProvider, OllamaConfig, OllamaProvider,
};
use crate::prompt;
use futures::{Stream, StreamExt};
use mofa_kernel::agent::AgentMetadata;
use mofa_kernel::agent::AgentState;
use mofa_kernel::plugin::{AgentPlugin, PluginType};
use mofa_plugins::tts::TTSPlugin;
use std::collections::HashMap;
use std::io::Write;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use tokio::sync::{Mutex, RwLock};

/// Type alias for TTS audio stream - boxed to avoid exposing kokoro-tts types
pub type TtsAudioStream = Pin<Box<dyn Stream<Item = (Vec<f32>, Duration)> + Send>>;

/// Cancellation token for cooperative cancellation
struct CancellationToken {
    cancel: Arc<AtomicBool>,
}

impl CancellationToken {
    fn new() -> Self {
        Self {
            cancel: Arc::new(AtomicBool::new(false)),
        }
    }

    fn is_cancelled(&self) -> bool {
        self.cancel.load(Ordering::Relaxed)
    }

    fn cancel(&self) {
        self.cancel.store(true, Ordering::Relaxed);
    }

    fn clone_token(&self) -> CancellationToken {
        CancellationToken {
            cancel: Arc::clone(&self.cancel),
        }
    }
}

/// 流式文本响应类型
///
/// 每次 yield 一个文本片段(delta content)
pub type TextStream = Pin<Box<dyn Stream<Item = LLMResult<String>> + Send>>;

/// TTS 流句柄:持有 sink 和消费者任务
///
/// 用于实时流式 TTS,允许 incremental 提交文本
#[cfg(feature = "kokoro")]
struct TTSStreamHandle {
    sink: mofa_plugins::tts::kokoro_wrapper::SynthSink<String>,
    _stream_handle: tokio::task::JoinHandle<()>,
}

/// Active TTS session with cancellation support
struct TTSSession {
    cancellation_token: CancellationToken,
    is_active: Arc<AtomicBool>,
}

impl TTSSession {
    fn new(token: CancellationToken) -> Self {
        let is_active = Arc::new(AtomicBool::new(true));
        TTSSession {
            cancellation_token: token,
            is_active,
        }
    }

    fn cancel(&self) {
        self.cancellation_token.cancel();
        self.is_active.store(false, Ordering::Relaxed);
    }

    fn is_active(&self) -> bool {
        self.is_active.load(Ordering::Relaxed)
    }
}

/// 句子缓冲区:按标点符号断句(内部实现)
struct SentenceBuffer {
    buffer: String,
}

impl SentenceBuffer {
    fn new() -> Self {
        Self {
            buffer: String::new(),
        }
    }

    /// 推入文本块,返回完整句子(如果有)
    fn push(&mut self, text: &str) -> Option<String> {
        for ch in text.chars() {
            self.buffer.push(ch);
            // 句末标点:。!?!?
            if matches!(ch, '' | '' | '' | '!' | '?') {
                let sentence = self.buffer.trim().to_string();
                if !sentence.is_empty() {
                    self.buffer.clear();
                    return Some(sentence);
                }
            }
        }
        None
    }

    /// 刷新剩余内容
    fn flush(&mut self) -> Option<String> {
        if self.buffer.trim().is_empty() {
            None
        } else {
            let remaining = self.buffer.trim().to_string();
            self.buffer.clear();
            Some(remaining)
        }
    }
}

/// 流式响应事件
#[derive(Debug, Clone)]
pub enum StreamEvent {
    /// 文本片段
    Text(String),
    /// 工具调用开始
    ToolCallStart { id: String, name: String },
    /// 工具调用参数片段
    ToolCallDelta { id: String, arguments_delta: String },
    /// 完成原因
    Done(Option<String>),
}

/// LLM Agent 配置
#[derive(Clone)]
pub struct LLMAgentConfig {
    /// Agent ID
    pub agent_id: String,
    /// Agent 名称
    pub name: String,
    /// 系统提示词
    pub system_prompt: Option<String>,
    /// 默认温度
    pub temperature: Option<f32>,
    /// 默认最大 token 数
    pub max_tokens: Option<u32>,
    /// 自定义配置
    pub custom_config: HashMap<String, String>,
    /// 用户 ID,用于数据库持久化和多用户场景
    pub user_id: Option<String>,
    /// 租户 ID,用于多租户支持
    pub tenant_id: Option<String>,
    /// 上下文窗口大小,用于滑动窗口消息管理(单位:轮数/rounds)
    ///
    /// 注意:单位是**轮数**(rounds),不是 token 数量
    /// 每轮对话 ≈ 1 个用户消息 + 1 个助手响应
    pub context_window_size: Option<usize>,
}

impl Default for LLMAgentConfig {
    fn default() -> Self {
        Self {
            agent_id: "llm-agent".to_string(),
            name: "LLM Agent".to_string(),
            system_prompt: None,
            temperature: Some(0.7),
            max_tokens: Some(4096),
            custom_config: HashMap::new(),
            user_id: None,
            tenant_id: None,
            context_window_size: None,
        }
    }
}

/// 标准 LLM Agent
///
/// 框架提供的开箱即用的 LLM Agent 实现
///
/// # 多会话支持
///
/// LLMAgent 支持多会话管理,每个会话有唯一的 session_id:
///
/// ```rust,ignore
/// // 创建新会话
/// let session_id = agent.create_session().await;
///
/// // 使用指定会话对话
/// agent.chat_with_session(&session_id, "Hello").await?;
///
/// // 切换默认会话
/// agent.switch_session(&session_id).await?;
///
/// // 获取所有会话ID
/// let sessions = agent.list_sessions().await;
/// ```
///
/// # TTS 支持
///
/// LLMAgent 支持通过统一的插件系统配置 TTS:
///
/// ```rust,ignore
/// // 创建 TTS 插件(引擎 + 可选音色)
/// let tts_plugin = TTSPlugin::with_engine("tts", kokoro_engine, Some("zf_090"));
///
/// // 通过插件系统添加
/// let agent = LLMAgentBuilder::new()
///     .with_id("my-agent")
///     .with_provider(Arc::new(openai_from_env()?))
///     .with_plugin(tts_plugin)
///     .build();
///
/// // 直接使用 TTS
/// agent.tts_speak("Hello world").await?;
///
/// // 高级用法:自定义配置
/// let tts_plugin = TTSPlugin::with_engine("tts", kokoro_engine, Some("zf_090"))
///     .with_config(TTSPluginConfig {
///         streaming_chunk_size: 8192,
///         ..Default::default()
///     });
/// ```
pub struct LLMAgent {
    config: LLMAgentConfig,
    /// 智能体元数据
    metadata: AgentMetadata,
    client: LLMClient,
    /// 多会话存储 (session_id -> ChatSession)
    sessions: Arc<RwLock<HashMap<String, Arc<RwLock<ChatSession>>>>>,
    /// 当前活动会话ID
    active_session_id: Arc<RwLock<String>>,
    tools: Vec<Tool>,
    tool_executor: Option<Arc<dyn ToolExecutor>>,
    event_handler: Option<Box<dyn LLMAgentEventHandler>>,
    /// 插件列表
    plugins: Vec<Box<dyn AgentPlugin>>,
    /// 当前智能体状态
    state: AgentState,
    /// 保存 provider 用于创建新会话
    provider: Arc<dyn LLMProvider>,
    /// Prompt 模板插件
    prompt_plugin: Option<Box<dyn prompt::PromptTemplatePlugin>>,
    /// TTS 插件(通过 builder 配置)
    tts_plugin: Option<Arc<Mutex<TTSPlugin>>>,
    /// 缓存的 Kokoro TTS 引擎(只需初始化一次,后续可复用)
    #[cfg(feature = "kokoro")]
    cached_kokoro_engine: Arc<Mutex<Option<Arc<mofa_plugins::tts::kokoro_wrapper::KokoroTTS>>>>,
    /// Active TTS session for cancellation
    active_tts_session: Arc<Mutex<Option<TTSSession>>>,
    /// 持久化存储(可选,用于从数据库加载历史会话)
    message_store: Option<Arc<dyn crate::persistence::MessageStore + Send + Sync>>,
    session_store: Option<Arc<dyn crate::persistence::SessionStore + Send + Sync>>,
    /// 用户 ID(用于从数据库加载会话)
    persistence_user_id: Option<uuid::Uuid>,
    /// Agent ID(用于从数据库加载会话)
    persistence_agent_id: Option<uuid::Uuid>,
}

/// LLM Agent 事件处理器
///
/// 允许用户自定义事件处理逻辑
#[async_trait::async_trait]
pub trait LLMAgentEventHandler: Send + Sync {
    /// Clone this handler trait object
    fn clone_box(&self) -> Box<dyn LLMAgentEventHandler>;

    /// 获取 Any 类型用于 downcasting
    fn as_any(&self) -> &dyn std::any::Any;

    /// 处理用户消息前的钩子
    async fn before_chat(&self, message: &str) -> LLMResult<Option<String>> {
        Ok(Some(message.to_string()))
    }

    /// 处理用户消息前的钩子(带模型名称)
    ///
    /// 默认实现调用 `before_chat`。
    /// 如果需要知道使用的模型名称(例如用于持久化),请实现此方法。
    async fn before_chat_with_model(
        &self,
        message: &str,
        _model: &str,
    ) -> LLMResult<Option<String>> {
        self.before_chat(message).await
    }

    /// 处理 LLM 响应后的钩子
    async fn after_chat(&self, response: &str) -> LLMResult<Option<String>> {
        Ok(Some(response.to_string()))
    }

    /// 处理 LLM 响应后的钩子(带元数据)
    ///
    /// 默认实现调用 after_chat。
    /// 如果需要访问响应元数据(如 response_id, model, token counts),请实现此方法。
    async fn after_chat_with_metadata(
        &self,
        response: &str,
        _metadata: &super::types::LLMResponseMetadata,
    ) -> LLMResult<Option<String>> {
        self.after_chat(response).await
    }

    /// 处理工具调用
    async fn on_tool_call(&self, name: &str, arguments: &str) -> LLMResult<Option<String>> {
        let _ = (name, arguments);
        Ok(None)
    }

    /// 处理错误
    async fn on_error(&self, error: &LLMError) -> LLMResult<Option<String>> {
        let _ = error;
        Ok(None)
    }
}

impl Clone for Box<dyn LLMAgentEventHandler> {
    fn clone(&self) -> Self {
        self.clone_box()
    }
}

impl LLMAgent {
    /// 创建新的 LLM Agent
    pub fn new(config: LLMAgentConfig, provider: Arc<dyn LLMProvider>) -> Self {
        Self::with_initial_session(config, provider, None)
    }

    /// 创建新的 LLM Agent,并指定初始会话 ID
    ///
    /// # 参数
    /// - `config`: Agent 配置
    /// - `provider`: LLM Provider
    /// - `initial_session_id`: 初始会话 ID,如果为 None 则使用自动生成的 ID
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// let agent = LLMAgent::with_initial_session(
    ///     config,
    ///     provider,
    ///     Some("user-session-001".to_string())
    /// );
    /// ```
    pub fn with_initial_session(
        config: LLMAgentConfig,
        provider: Arc<dyn LLMProvider>,
        initial_session_id: Option<String>,
    ) -> Self {
        let client = LLMClient::new(provider.clone());

        let mut session = if let Some(sid) = initial_session_id {
            ChatSession::with_id_str(&sid, LLMClient::new(provider.clone()))
        } else {
            ChatSession::new(LLMClient::new(provider.clone()))
        };

        // 设置系统提示
        if let Some(ref prompt) = config.system_prompt {
            session = session.with_system(prompt.clone());
        }

        // 设置上下文窗口大小
        session = session.with_context_window_size(config.context_window_size);

        let session_id = session.session_id().to_string();
        let session_arc = Arc::new(RwLock::new(session));

        // 初始化会话存储
        let mut sessions = HashMap::new();
        sessions.insert(session_id.clone(), session_arc);

        // Clone fields needed for metadata before moving config
        let agent_id = config.agent_id.clone();
        let name = config.name.clone();

        // 创建 AgentCapabilities
        let capabilities = mofa_kernel::agent::AgentCapabilities::builder()
            .tags(vec![
                "llm".to_string(),
                "chat".to_string(),
                "text-generation".to_string(),
                "multi-session".to_string(),
            ])
            .build();

        Self {
            config,
            metadata: AgentMetadata {
                id: agent_id,
                name,
                description: None,
                version: None,
                capabilities,
                state: AgentState::Created,
            },
            client,
            sessions: Arc::new(RwLock::new(sessions)),
            active_session_id: Arc::new(RwLock::new(session_id)),
            tools: Vec::new(),
            tool_executor: None,
            event_handler: None,
            plugins: Vec::new(),
            state: AgentState::Created,
            provider,
            prompt_plugin: None,
            tts_plugin: None,
            #[cfg(feature = "kokoro")]
            cached_kokoro_engine: Arc::new(Mutex::new(None)),
            active_tts_session: Arc::new(Mutex::new(None)),
            message_store: None,
            session_store: None,
            persistence_user_id: None,
            persistence_agent_id: None,
        }
    }

    /// 创建新的 LLM Agent,并尝试从数据库加载初始会话(异步版本)
    ///
    /// 如果提供了 persistence stores 且 session_id 存在于数据库中,
    /// 会自动加载历史消息并应用滑动窗口。
    ///
    /// # 参数
    /// - `config`: Agent 配置
    /// - `provider`: LLM Provider
    /// - `initial_session_id`: 初始会话 ID,如果为 None 则使用自动生成的 ID
    /// - `message_store`: 消息存储(可选,用于从数据库加载历史)
    /// - `session_store`: 会话存储(可选,用于从数据库加载历史)
    /// - `persistence_user_id`: 用户 ID(用于从数据库加载会话)
    /// - `persistence_agent_id`: Agent ID(用于从数据库加载会话)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// let agent = LLMAgent::with_initial_session_async(
    ///     config,
    ///     provider,
    ///     Some("user-session-001".to_string()),
    ///     Some(message_store),
    ///     Some(session_store),
    ///     Some(user_id),
    ///     Some(agent_id),
    /// ).await?;
    /// ```
    pub async fn with_initial_session_async(
        config: LLMAgentConfig,
        provider: Arc<dyn LLMProvider>,
        initial_session_id: Option<String>,
        message_store: Option<Arc<dyn crate::persistence::MessageStore + Send + Sync>>,
        session_store: Option<Arc<dyn crate::persistence::SessionStore + Send + Sync>>,
        persistence_user_id: Option<uuid::Uuid>,
        persistence_tenant_id: Option<uuid::Uuid>,
        persistence_agent_id: Option<uuid::Uuid>,
    ) -> Self {
        let client = LLMClient::new(provider.clone());

        // Clone initial_session_id to avoid move issues
        let initial_session_id_clone = initial_session_id.clone();

        // 1. 尝试从数据库加载会话(如果有 stores 且指定了 session_id)
        let session = if let (
            Some(sid),
            Some(msg_store),
            Some(sess_store),
            Some(user_id),
            Some(tenant_id),
            Some(agent_id),
        ) = (
            initial_session_id_clone,
            message_store.clone(),
            session_store.clone(),
            persistence_user_id,
            persistence_tenant_id,
            persistence_agent_id,
        ) {
            // Clone stores before moving them into ChatSession::load
            let msg_store_clone = msg_store.clone();
            let sess_store_clone = sess_store.clone();

            let session_uuid = uuid::Uuid::parse_str(&sid).unwrap_or_else(|_| {
                tracing::warn!("⚠️ 无效的 session_id 格式 '{}', 将生成新的 UUID", sid);
                uuid::Uuid::now_v7()
            });

            // 尝试从数据库加载
            match ChatSession::load(
                session_uuid,
                LLMClient::new(provider.clone()),
                user_id,
                agent_id,
                tenant_id,
                msg_store,
                sess_store,
                config.context_window_size,
            )
            .await
            {
                Ok(loaded_session) => {
                    tracing::info!(
                        "✅ 从数据库加载会话: {} ({} 条消息)",
                        sid,
                        loaded_session.messages().len()
                    );
                    loaded_session
                }
                Err(e) => {
                    // 会话不存在,创建新会话(使用用户指定的ID和从persistence获取的user_id/agent_id)
                    tracing::info!("📝 创建新会话并持久化: {} (数据库中不存在: {})", sid, e);

                    // Clone stores again for the fallback case
                    let msg_store_clone2 = msg_store_clone.clone();
                    let sess_store_clone2 = sess_store_clone.clone();

                    // 使用正确的 user_id 和 agent_id 创建会话,并持久化到数据库
                    match ChatSession::with_id_and_stores_and_persist(
                        session_uuid,
                        LLMClient::new(provider.clone()),
                        user_id,
                        agent_id,
                        tenant_id,
                        msg_store_clone,
                        sess_store_clone,
                        config.context_window_size,
                    )
                    .await
                    {
                        Ok(mut new_session) => {
                            if let Some(ref prompt) = config.system_prompt {
                                new_session = new_session.with_system(prompt.clone());
                            }
                            new_session
                        }
                        Err(persist_err) => {
                            tracing::error!("❌ 持久化会话失败: {}, 降级为内存会话", persist_err);
                            // 降级:如果持久化失败,创建内存会话
                            let new_session = ChatSession::with_id_and_stores(
                                session_uuid,
                                LLMClient::new(provider.clone()),
                                user_id,
                                agent_id,
                                tenant_id,
                                msg_store_clone2,
                                sess_store_clone2,
                                config.context_window_size,
                            );
                            if let Some(ref prompt) = config.system_prompt {
                                new_session.with_system(prompt.clone())
                            } else {
                                new_session
                            }
                        }
                    }
                }
            }
        } else {
            // 没有 persistence stores,创建普通会话
            let mut session = if let Some(sid) = initial_session_id {
                ChatSession::with_id_str(&sid, LLMClient::new(provider.clone()))
            } else {
                ChatSession::new(LLMClient::new(provider.clone()))
            };
            if let Some(ref prompt) = config.system_prompt {
                session = session.with_system(prompt.clone());
            }
            session.with_context_window_size(config.context_window_size)
        };

        let session_id = session.session_id().to_string();
        let session_arc = Arc::new(RwLock::new(session));

        // 初始化会话存储
        let mut sessions = HashMap::new();
        sessions.insert(session_id.clone(), session_arc);

        // Clone fields needed for metadata before moving config
        let agent_id = config.agent_id.clone();
        let name = config.name.clone();

        // 创建 AgentCapabilities
        let capabilities = mofa_kernel::agent::AgentCapabilities::builder()
            .tags(vec![
                "llm".to_string(),
                "chat".to_string(),
                "text-generation".to_string(),
                "multi-session".to_string(),
            ])
            .build();

        Self {
            config,
            metadata: AgentMetadata {
                id: agent_id,
                name,
                description: None,
                version: None,
                capabilities,
                state: AgentState::Created,
            },
            client,
            sessions: Arc::new(RwLock::new(sessions)),
            active_session_id: Arc::new(RwLock::new(session_id)),
            tools: Vec::new(),
            tool_executor: None,
            event_handler: None,
            plugins: Vec::new(),
            state: AgentState::Created,
            provider,
            prompt_plugin: None,
            tts_plugin: None,
            #[cfg(feature = "kokoro")]
            cached_kokoro_engine: Arc::new(Mutex::new(None)),
            active_tts_session: Arc::new(Mutex::new(None)),
            message_store,
            session_store,
            persistence_user_id,
            persistence_agent_id,
        }
    }

    /// 获取配置
    pub fn config(&self) -> &LLMAgentConfig {
        &self.config
    }

    /// 获取 LLM Client
    pub fn client(&self) -> &LLMClient {
        &self.client
    }

    // ========================================================================
    // 会话管理方法
    // ========================================================================

    /// 获取当前活动会话ID
    pub async fn current_session_id(&self) -> String {
        self.active_session_id.read().await.clone()
    }

    /// 创建新会话
    ///
    /// 返回新会话的 session_id
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// let session_id = agent.create_session().await;
    /// agent.chat_with_session(&session_id, "Hello").await?;
    /// ```
    pub async fn create_session(&self) -> String {
        let mut session = ChatSession::new(LLMClient::new(self.provider.clone()));

        // 使用动态 Prompt 模板(如果可用)
        let mut system_prompt = self.config.system_prompt.clone();

        if let Some(ref plugin) = self.prompt_plugin
            && let Some(template) = plugin.get_current_template().await
        {
            // 渲染默认模板
            system_prompt = match template.render(&[]) {
                Ok(prompt) => Some(prompt),
                Err(_) => self.config.system_prompt.clone(),
            };
        }

        if let Some(ref prompt) = system_prompt {
            session = session.with_system(prompt.clone());
        }

        // 设置上下文窗口大小
        session = session.with_context_window_size(self.config.context_window_size);

        let session_id = session.session_id().to_string();
        let session_arc = Arc::new(RwLock::new(session));

        let mut sessions = self.sessions.write().await;
        sessions.insert(session_id.clone(), session_arc);

        session_id
    }

    /// 使用指定ID创建新会话
    ///
    /// 如果 session_id 已存在,返回错误
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// let session_id = agent.create_session_with_id("user-123-session").await?;
    /// ```
    pub async fn create_session_with_id(&self, session_id: impl Into<String>) -> LLMResult<String> {
        let session_id = session_id.into();

        {
            let sessions = self.sessions.read().await;
            if sessions.contains_key(&session_id) {
                return Err(LLMError::Other(format!(
                    "Session with id '{}' already exists",
                    session_id
                )));
            }
        }

        let mut session =
            ChatSession::with_id_str(&session_id, LLMClient::new(self.provider.clone()));

        // 使用动态 Prompt 模板(如果可用)
        let mut system_prompt = self.config.system_prompt.clone();

        if let Some(ref plugin) = self.prompt_plugin
            && let Some(template) = plugin.get_current_template().await
        {
            // 渲染默认模板
            system_prompt = match template.render(&[]) {
                Ok(prompt) => Some(prompt),
                Err(_) => self.config.system_prompt.clone(),
            };
        }

        if let Some(ref prompt) = system_prompt {
            session = session.with_system(prompt.clone());
        }

        // 设置上下文窗口大小
        session = session.with_context_window_size(self.config.context_window_size);

        let session_arc = Arc::new(RwLock::new(session));

        let mut sessions = self.sessions.write().await;
        sessions.insert(session_id.clone(), session_arc);

        Ok(session_id)
    }

    /// 切换当前活动会话
    ///
    /// # 错误
    /// 如果 session_id 不存在则返回错误
    pub async fn switch_session(&self, session_id: &str) -> LLMResult<()> {
        let sessions = self.sessions.read().await;
        if !sessions.contains_key(session_id) {
            return Err(LLMError::Other(format!(
                "Session '{}' not found",
                session_id
            )));
        }
        drop(sessions);

        let mut active = self.active_session_id.write().await;
        *active = session_id.to_string();
        Ok(())
    }

    /// 获取或创建会话
    ///
    /// 如果 session_id 存在则返回它,否则使用该 ID 创建新会话
    pub async fn get_or_create_session(&self, session_id: impl Into<String>) -> String {
        let session_id = session_id.into();

        {
            let sessions = self.sessions.read().await;
            if sessions.contains_key(&session_id) {
                return session_id;
            }
        }

        // 会话不存在,创建新的
        let _ = self.create_session_with_id(&session_id).await;
        session_id
    }

    /// 删除会话
    ///
    /// # 注意
    /// 不能删除当前活动会话,需要先切换到其他会话
    pub async fn remove_session(&self, session_id: &str) -> LLMResult<()> {
        let active = self.active_session_id.read().await.clone();
        if active == session_id {
            return Err(LLMError::Other(
                "Cannot remove active session. Switch to another session first.".to_string(),
            ));
        }

        let mut sessions = self.sessions.write().await;
        if sessions.remove(session_id).is_none() {
            return Err(LLMError::Other(format!(
                "Session '{}' not found",
                session_id
            )));
        }

        Ok(())
    }

    /// 列出所有会话ID
    pub async fn list_sessions(&self) -> Vec<String> {
        let sessions = self.sessions.read().await;
        sessions.keys().cloned().collect()
    }

    /// 获取会话数量
    pub async fn session_count(&self) -> usize {
        let sessions = self.sessions.read().await;
        sessions.len()
    }

    /// 检查会话是否存在
    pub async fn has_session(&self, session_id: &str) -> bool {
        let sessions = self.sessions.read().await;
        sessions.contains_key(session_id)
    }

    // ========================================================================
    // TTS 便捷方法
    // ========================================================================

    /// 使用 TTS 合成并播放文本
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// agent.tts_speak("Hello world").await?;
    /// ```
    pub async fn tts_speak(&self, text: &str) -> LLMResult<()> {
        let tts = self
            .tts_plugin
            .as_ref()
            .ok_or_else(|| LLMError::Other("TTS plugin not configured".to_string()))?;

        let mut tts_guard = tts.lock().await;
        tts_guard
            .synthesize_and_play(text)
            .await
            .map_err(|e| LLMError::Other(format!("TTS synthesis failed: {}", e)))
    }

    /// 使用 TTS 流式合成文本
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// agent.tts_speak_streaming("Hello world", Box::new(|audio| {
    ///     println!("Got {} bytes of audio", audio.len());
    /// })).await?;
    /// ```
    pub async fn tts_speak_streaming(
        &self,
        text: &str,
        callback: Box<dyn Fn(Vec<u8>) + Send + Sync>,
    ) -> LLMResult<()> {
        let tts = self
            .tts_plugin
            .as_ref()
            .ok_or_else(|| LLMError::Other("TTS plugin not configured".to_string()))?;

        let mut tts_guard = tts.lock().await;
        tts_guard
            .synthesize_streaming(text, callback)
            .await
            .map_err(|e| LLMError::Other(format!("TTS streaming failed: {}", e)))
    }

    /// 使用 TTS 流式合成文本(f32 native format,更高效)
    ///
    /// This method is more efficient for KokoroTTS as it uses the native f32 format
    /// without the overhead of f32 -> i16 -> u8 conversion.
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use rodio::buffer::SamplesBuffer;
    ///
    /// agent.tts_speak_f32_stream("Hello world", Box::new(|audio_f32| {
    ///     // audio_f32 is Vec<f32> with values in [-1.0, 1.0]
    ///     sink.append(SamplesBuffer::new(1, 24000, audio_f32));
    /// })).await?;
    /// ```
    pub async fn tts_speak_f32_stream(
        &self,
        text: &str,
        callback: Box<dyn Fn(Vec<f32>) + Send + Sync>,
    ) -> LLMResult<()> {
        let tts = self
            .tts_plugin
            .as_ref()
            .ok_or_else(|| LLMError::Other("TTS plugin not configured".to_string()))?;

        let mut tts_guard = tts.lock().await;
        tts_guard
            .synthesize_streaming_f32(text, callback)
            .await
            .map_err(|e| LLMError::Other(format!("TTS f32 streaming failed: {}", e)))
    }

    /// 获取 TTS 音频流(仅支持 Kokoro TTS)
    ///
    /// Returns a direct stream of (audio_f32, duration) tuples from KokoroTTS.
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use futures::StreamExt;
    /// use rodio::buffer::SamplesBuffer;
    ///
    /// if let Ok(mut stream) = agent.tts_create_stream("Hello world").await {
    ///     while let Some((audio, took)) = stream.next().await {
    ///         // audio is Vec<f32> with values in [-1.0, 1.0]
    ///         sink.append(SamplesBuffer::new(1, 24000, audio));
    ///     }
    /// }
    /// ```
    pub async fn tts_create_stream(&self, text: &str) -> LLMResult<TtsAudioStream> {
        #[cfg(feature = "kokoro")]
        {
            use mofa_plugins::tts::kokoro_wrapper::KokoroTTS;

            // 首先检查是否有缓存的引擎(只需初始化一次)
            let cached_engine = {
                let cache_guard = self.cached_kokoro_engine.lock().await;
                cache_guard.clone()
            };

            let kokoro = if let Some(engine) = cached_engine {
                // 使用缓存的引擎(无需再次获取 tts_plugin 的锁)
                engine
            } else {
                // 首次调用:获取 tts_plugin 的锁,downcast 并缓存
                let tts = self
                    .tts_plugin
                    .as_ref()
                    .ok_or_else(|| LLMError::Other("TTS plugin not configured".to_string()))?;

                let tts_guard = tts.lock().await;

                let engine = tts_guard
                    .engine()
                    .ok_or_else(|| LLMError::Other("TTS engine not initialized".to_string()))?;

                if let Some(kokoro_ref) = engine.as_any().downcast_ref::<KokoroTTS>() {
                    // 克隆 KokoroTTS(内部使用 Arc,克隆只是增加引用计数)
                    let cloned = kokoro_ref.clone();
                    let cloned_arc = Arc::new(cloned);

                    // 获取 voice 配置
                    let voice = tts_guard
                        .stats()
                        .get("default_voice")
                        .and_then(|v| v.as_str())
                        .unwrap_or("default");

                    // 缓存克隆的引擎
                    {
                        let mut cache_guard = self.cached_kokoro_engine.lock().await;
                        *cache_guard = Some(cloned_arc.clone());
                    }

                    cloned_arc
                } else {
                    return Err(LLMError::Other("TTS engine is not KokoroTTS".to_string()));
                }
            };

            // 使用缓存的引擎创建 stream(无需再次获取 tts_plugin 的锁)
            let voice = "default"; // 可以从配置中获取
            let (mut sink, stream) = kokoro
                .create_stream(voice)
                .await
                .map_err(|e| LLMError::Other(format!("Failed to create TTS stream: {}", e)))?;

            // Submit text for synthesis
            sink.synth(text.to_string()).await.map_err(|e| {
                LLMError::Other(format!("Failed to submit text for synthesis: {}", e))
            })?;

            // Box the stream to hide the concrete type
            return Ok(Box::pin(stream));
        }

        #[cfg(not(feature = "kokoro"))]
        {
            Err(LLMError::Other("Kokoro feature not enabled".to_string()))
        }
    }

    /// Stream multiple sentences through a single TTS stream
    ///
    /// This is more efficient than calling tts_speak_f32_stream multiple times
    /// because it reuses the same stream for all sentences, following the kokoro-tts
    /// streaming pattern: ONE stream, multiple synth calls, continuous audio output.
    ///
    /// # Arguments
    /// - `sentences`: Vector of text sentences to synthesize
    /// - `callback`: Function to call with each audio chunk (Vec<f32>)
    ///
    /// # Example
    /// ```rust,ignore
    /// use rodio::buffer::SamplesBuffer;
    ///
    /// let sentences = vec!["Hello".to_string(), "World".to_string()];
    /// agent.tts_speak_f32_stream_batch(
    ///     sentences,
    ///     Box::new(|audio_f32| {
    ///         sink.append(SamplesBuffer::new(1, 24000, audio_f32));
    ///     }),
    /// ).await?;
    /// ```
    pub async fn tts_speak_f32_stream_batch(
        &self,
        sentences: Vec<String>,
        callback: Box<dyn Fn(Vec<f32>) + Send + Sync>,
    ) -> LLMResult<()> {
        let tts = self
            .tts_plugin
            .as_ref()
            .ok_or_else(|| LLMError::Other("TTS plugin not configured".to_string()))?;

        let tts_guard = tts.lock().await;

        #[cfg(feature = "kokoro")]
        {
            use mofa_plugins::tts::kokoro_wrapper::KokoroTTS;

            let engine = tts_guard
                .engine()
                .ok_or_else(|| LLMError::Other("TTS engine not initialized".to_string()))?;

            if let Some(kokoro) = engine.as_any().downcast_ref::<KokoroTTS>() {
                let voice = tts_guard
                    .stats()
                    .get("default_voice")
                    .and_then(|v| v.as_str())
                    .unwrap_or("default")
                    .to_string();

                // Create ONE stream for all sentences
                let (mut sink, mut stream) = kokoro
                    .create_stream(&voice)
                    .await
                    .map_err(|e| LLMError::Other(format!("Failed to create TTS stream: {}", e)))?;

                // Spawn a task to consume the stream continuously
                tokio::spawn(async move {
                    while let Some((audio, _took)) = stream.next().await {
                        callback(audio);
                    }
                });

                // Submit all sentences to the same sink
                for sentence in sentences {
                    sink.synth(sentence)
                        .await
                        .map_err(|e| LLMError::Other(format!("Failed to submit text: {}", e)))?;
                }

                return Ok(());
            }

            return Err(LLMError::Other("TTS engine is not KokoroTTS".to_string()));
        }

        #[cfg(not(feature = "kokoro"))]
        {
            Err(LLMError::Other("Kokoro feature not enabled".to_string()))
        }
    }

    /// 检查是否配置了 TTS 插件
    pub fn has_tts(&self) -> bool {
        self.tts_plugin.is_some()
    }

    /// Interrupt currently playing TTS audio
    ///
    /// Stops current audio playback and cancels any ongoing TTS synthesis.
    /// Call this before starting a new TTS request for clean transition.
    ///
    /// # Example
    /// ```rust,ignore
    /// // User enters new input while audio is playing
    /// agent.interrupt_tts().await?;
    /// agent.chat_with_tts(&session_id, new_input).await?;
    /// ```
    pub async fn interrupt_tts(&self) -> LLMResult<()> {
        let mut session_guard = self.active_tts_session.lock().await;
        if let Some(session) = session_guard.take() {
            session.cancel();
        }
        Ok(())
    }

    // ========================================================================
    // LLM + TTS 流式对话方法
    // ========================================================================

    /// 流式聊天并自动 TTS 播放(最简版本)
    ///
    /// 自动处理:
    /// - 流式 LLM 输出
    /// - 按标点断句
    /// - 批量 TTS 播放
    ///
    /// # 示例
    /// ```rust,ignore
    /// agent.chat_with_tts(&session_id, "你好").await?;
    /// ```
    pub async fn chat_with_tts(
        &self,
        session_id: &str,
        message: impl Into<String>,
    ) -> LLMResult<()> {
        self.chat_with_tts_internal(session_id, message, None).await
    }

    /// 流式聊天并自动 TTS 播放(自定义音频处理)
    ///
    /// # 示例
    /// ```rust,ignore
    /// use rodio::buffer::SamplesBuffer;
    ///
    /// agent.chat_with_tts_callback(&session_id, "你好", |audio| {
    ///     sink.append(SamplesBuffer::new(1, 24000, audio));
    /// }).await?;
    /// ```
    pub async fn chat_with_tts_callback(
        &self,
        session_id: &str,
        message: impl Into<String>,
        callback: impl Fn(Vec<f32>) + Send + Sync + 'static,
    ) -> LLMResult<()> {
        self.chat_with_tts_internal(session_id, message, Some(Box::new(callback)))
            .await
    }

    /// 创建实时 TTS 流
    ///
    /// 返回的 handle 允许 incremental 提交文本,实现真正的实时流式 TTS。
    ///
    /// # 核心机制
    /// 1. 创建 TTS stream(仅一次)
    /// 2. 启动消费者任务(持续接收音频块)
    /// 3. 返回的 sink 支持多次 `synth()` 调用
    #[cfg(feature = "kokoro")]
    async fn create_tts_stream_handle(
        &self,
        callback: Box<dyn Fn(Vec<f32>) + Send + Sync>,
        cancellation_token: Option<CancellationToken>,
    ) -> LLMResult<TTSStreamHandle> {
        use mofa_plugins::tts::kokoro_wrapper::KokoroTTS;

        let tts = self
            .tts_plugin
            .as_ref()
            .ok_or_else(|| LLMError::Other("TTS plugin not configured".to_string()))?;

        let tts_guard = tts.lock().await;
        let engine = tts_guard
            .engine()
            .ok_or_else(|| LLMError::Other("TTS engine not initialized".to_string()))?;

        let kokoro = engine
            .as_any()
            .downcast_ref::<KokoroTTS>()
            .ok_or_else(|| LLMError::Other("TTS engine is not KokoroTTS".to_string()))?;

        let voice = tts_guard
            .stats()
            .get("default_voice")
            .and_then(|v| v.as_str())
            .unwrap_or("default")
            .to_string();

        // 创建 TTS stream(只创建一次)
        let (sink, mut stream) = kokoro
            .create_stream(&voice)
            .await
            .map_err(|e| LLMError::Other(format!("Failed to create TTS stream: {}", e)))?;

        // Clone cancellation token for the spawned task
        let token_clone = cancellation_token.as_ref().map(|t| t.clone_token());

        // 启动消费者任务(持续接收音频块,支持取消检查)
        let stream_handle = tokio::spawn(async move {
            while let Some((audio, _took)) = stream.next().await {
                // 检查取消信号
                if let Some(ref token) = token_clone {
                    if token.is_cancelled() {
                        break; // 退出循环,停止音频处理
                    }
                }
                callback(audio);
            }
        });

        Ok(TTSStreamHandle {
            sink,
            _stream_handle: stream_handle,
        })
    }

    /// 内部实现:LLM + TTS 实时流式对话
    ///
    /// # 核心机制
    /// 1. 在 LLM 流式输出**之前**创建 TTS stream
    /// 2. 检测到完整句子时立即提交到 TTS
    /// 3. LLM 流和 TTS 流并行运行
    async fn chat_with_tts_internal(
        &self,
        session_id: &str,
        message: impl Into<String>,
        callback: Option<Box<dyn Fn(Vec<f32>) + Send + Sync>>,
    ) -> LLMResult<()> {
        #[cfg(feature = "kokoro")]
        {
            use mofa_plugins::tts::kokoro_wrapper::KokoroTTS;

            let callback = match callback {
                Some(cb) => cb,
                None => {
                    // 无 TTS 请求,仅流式输出文本
                    let mut text_stream =
                        self.chat_stream_with_session(session_id, message).await?;
                    while let Some(result) = text_stream.next().await {
                        match result {
                            Ok(text_chunk) => {
                                print!("{}", text_chunk);
                                std::io::stdout().flush().map_err(|e| {
                                    LLMError::Other(format!("Failed to flush stdout: {}", e))
                                })?;
                            }
                            Err(e) if e.to_string().contains("__stream_end__") => break,
                            Err(e) => return Err(e),
                        }
                    }
                    println!();
                    return Ok(());
                }
            };

            // Step 0: 取消任何现有的 TTS 会话
            self.interrupt_tts().await?;

            // Step 1: 创建 cancellation token
            let cancellation_token = CancellationToken::new();

            // Step 2: 在 LLM 流式输出之前创建 TTS stream(传入 cancellation token)
            let mut tts_handle = self
                .create_tts_stream_handle(callback, Some(cancellation_token.clone_token()))
                .await?;

            // Step 3: 创建并跟踪新的 TTS session
            let session = TTSSession::new(cancellation_token);

            {
                let mut active_session = self.active_tts_session.lock().await;
                *active_session = Some(session);
            }

            let mut buffer = SentenceBuffer::new();

            // Step 4: 流式处理 LLM 响应,实时提交句子到 TTS
            let mut text_stream = self.chat_stream_with_session(session_id, message).await?;

            while let Some(result) = text_stream.next().await {
                match result {
                    Ok(text_chunk) => {
                        // 检查是否已被取消
                        {
                            let active_session = self.active_tts_session.lock().await;
                            if let Some(ref session) = *active_session {
                                if !session.is_active() {
                                    return Ok(()); // 优雅退出
                                }
                            }
                        }

                        // 实时显示文本
                        print!("{}", text_chunk);
                        std::io::stdout().flush().map_err(|e| {
                            LLMError::Other(format!("Failed to flush stdout: {}", e))
                        })?;

                        // 检测句子并立即提交到 TTS
                        if let Some(sentence) = buffer.push(&text_chunk) {
                            if let Err(e) = tts_handle.sink.synth(sentence).await {
                                eprintln!("[TTS Error] Failed to submit sentence: {}", e);
                                // 继续流式处理,即使 TTS 失败
                            }
                        }
                    }
                    Err(e) if e.to_string().contains("__stream_end__") => break,
                    Err(e) => return Err(e),
                }
            }

            // Step 5: 提交剩余文本
            if let Some(remaining) = buffer.flush() {
                if let Err(e) = tts_handle.sink.synth(remaining).await {
                    eprintln!("[TTS Error] Failed to submit final sentence: {}", e);
                }
            }

            // Step 6: 清理会话
            {
                let mut active_session = self.active_tts_session.lock().await;
                *active_session = None;
            }

            // Step 7: 等待 TTS 流完成(所有音频块处理完毕)
            let _ = tokio::time::timeout(
                tokio::time::Duration::from_secs(30),
                tts_handle._stream_handle,
            )
            .await
            .map_err(|_| LLMError::Other("TTS stream processing timeout".to_string()))
            .and_then(|r| r.map_err(|e| LLMError::Other(format!("TTS stream task failed: {}", e))));

            Ok(())
        }

        #[cfg(not(feature = "kokoro"))]
        {
            // 当 kokoro feature 未启用时,使用批量处理模式
            let mut text_stream = self.chat_stream_with_session(session_id, message).await?;
            let mut buffer = SentenceBuffer::new();
            let mut sentences = Vec::new();

            // 收集所有句子
            while let Some(result) = text_stream.next().await {
                match result {
                    Ok(text_chunk) => {
                        print!("{}", text_chunk);
                        std::io::stdout().flush().map_err(|e| {
                            LLMError::Other(format!("Failed to flush stdout: {}", e))
                        })?;

                        if let Some(sentence) = buffer.push(&text_chunk) {
                            sentences.push(sentence);
                        }
                    }
                    Err(e) if e.to_string().contains("__stream_end__") => break,
                    Err(e) => return Err(e),
                }
            }

            // 添加剩余内容
            if let Some(remaining) = buffer.flush() {
                sentences.push(remaining);
            }

            // 批量播放 TTS(如果有回调)
            if !sentences.is_empty()
                && let Some(cb) = callback
            {
                for sentence in &sentences {
                    println!("\n[TTS] {}", sentence);
                }
                // 注意:非 kokoro 环境下无法调用此方法
                // 这里需要根据实际情况处理
                let _ = cb;
            }

            Ok(())
        }
    }

    /// 内部方法:获取会话 Arc
    async fn get_session_arc(&self, session_id: &str) -> LLMResult<Arc<RwLock<ChatSession>>> {
        let sessions = self.sessions.read().await;
        sessions
            .get(session_id)
            .cloned()
            .ok_or_else(|| LLMError::Other(format!("Session '{}' not found", session_id)))
    }

    // ========================================================================
    // 对话方法
    // ========================================================================

    /// 发送消息并获取响应(使用当前活动会话)
    pub async fn chat(&self, message: impl Into<String>) -> LLMResult<String> {
        let session_id = self.active_session_id.read().await.clone();
        self.chat_with_session(&session_id, message).await
    }

    /// 使用指定会话发送消息并获取响应
    ///
    /// # 参数
    /// - `session_id`: 会话唯一标识
    /// - `message`: 用户消息
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// let session_id = agent.create_session().await;
    /// let response = agent.chat_with_session(&session_id, "Hello").await?;
    /// ```
    pub async fn chat_with_session(
        &self,
        session_id: &str,
        message: impl Into<String>,
    ) -> LLMResult<String> {
        let message = message.into();

        // 获取模型名称
        let model = self.provider.default_model();

        // 调用 before_chat 钩子(带模型名称)
        let processed_message = if let Some(ref handler) = self.event_handler {
            match handler.before_chat_with_model(&message, model).await? {
                Some(msg) => msg,
                None => return Ok(String::new()),
            }
        } else {
            message
        };

        // 获取会话
        let session = self.get_session_arc(session_id).await?;

        // 发送消息
        let mut session_guard = session.write().await;
        let response = match session_guard.send(&processed_message).await {
            Ok(resp) => resp,
            Err(e) => {
                if let Some(ref handler) = self.event_handler
                    && let Some(fallback) = handler.on_error(&e).await?
                {
                    return Ok(fallback);
                }
                return Err(e);
            }
        };

        // 调用 after_chat 钩子(带元数据)
        let final_response = if let Some(ref handler) = self.event_handler {
            // 从会话中获取响应元数据
            let metadata = session_guard.last_response_metadata();
            if let Some(meta) = metadata {
                match handler.after_chat_with_metadata(&response, meta).await? {
                    Some(resp) => resp,
                    None => response,
                }
            } else {
                // 回退到旧方法(没有元数据)
                match handler.after_chat(&response).await? {
                    Some(resp) => resp,
                    None => response,
                }
            }
        } else {
            response
        };

        Ok(final_response)
    }

    /// 简单问答(不保留上下文)
    pub async fn ask(&self, question: impl Into<String>) -> LLMResult<String> {
        let question = question.into();

        let mut builder = self.client.chat();

        // 使用动态 Prompt 模板(如果可用)
        let mut system_prompt = self.config.system_prompt.clone();

        if let Some(ref plugin) = self.prompt_plugin
            && let Some(template) = plugin.get_current_template().await
        {
            // 渲染默认模板(可以根据需要添加变量)
            match template.render(&[]) {
                Ok(prompt) => system_prompt = Some(prompt),
                Err(_) => {
                    // 如果渲染失败,使用回退的系统提示词
                    system_prompt = self.config.system_prompt.clone();
                }
            }
        }

        // 设置系统提示词
        if let Some(ref system) = system_prompt {
            builder = builder.system(system.clone());
        }

        if let Some(temp) = self.config.temperature {
            builder = builder.temperature(temp);
        }

        if let Some(tokens) = self.config.max_tokens {
            builder = builder.max_tokens(tokens);
        }

        builder = builder.user(question);

        // 添加工具
        if let Some(ref executor) = self.tool_executor {
            let tools = if self.tools.is_empty() {
                executor.available_tools().await?
            } else {
                self.tools.clone()
            };

            if !tools.is_empty() {
                builder = builder.tools(tools);
            }

            builder = builder.with_tool_executor(executor.clone());
            let response = builder.send_with_tools().await?;
            return response
                .content()
                .map(|s| s.to_string())
                .ok_or_else(|| LLMError::Other("No content in response".to_string()));
        }

        let response = builder.send().await?;
        response
            .content()
            .map(|s| s.to_string())
            .ok_or_else(|| LLMError::Other("No content in response".to_string()))
    }

    /// 设置 Prompt 场景
    pub async fn set_prompt_scenario(&self, scenario: impl Into<String>) {
        let scenario = scenario.into();

        if let Some(ref plugin) = self.prompt_plugin {
            plugin.set_active_scenario(&scenario).await;
        }
    }

    /// 清空对话历史(当前活动会话)
    pub async fn clear_history(&self) {
        let session_id = self.active_session_id.read().await.clone();
        let _ = self.clear_session_history(&session_id).await;
    }

    /// 清空指定会话的对话历史
    pub async fn clear_session_history(&self, session_id: &str) -> LLMResult<()> {
        let session = self.get_session_arc(session_id).await?;
        let mut session_guard = session.write().await;
        session_guard.clear();
        Ok(())
    }

    /// 获取对话历史(当前活动会话)
    pub async fn history(&self) -> Vec<ChatMessage> {
        let session_id = self.active_session_id.read().await.clone();
        self.get_session_history(&session_id)
            .await
            .unwrap_or_default()
    }

    /// 获取指定会话的对话历史
    pub async fn get_session_history(&self, session_id: &str) -> LLMResult<Vec<ChatMessage>> {
        let session = self.get_session_arc(session_id).await?;
        let session_guard = session.read().await;
        Ok(session_guard.messages().to_vec())
    }

    /// 设置工具
    pub fn set_tools(&mut self, tools: Vec<Tool>, executor: Arc<dyn ToolExecutor>) {
        self.tools = tools;
        self.tool_executor = Some(executor);

        // 更新 session 中的工具
        // 注意:这需要重新创建 session,因为 with_tools 消耗 self
    }

    /// 设置事件处理器
    pub fn set_event_handler(&mut self, handler: Box<dyn LLMAgentEventHandler>) {
        self.event_handler = Some(handler);
    }

    /// 向智能体添加插件
    pub fn add_plugin<P: AgentPlugin + 'static>(&mut self, plugin: P) {
        self.plugins.push(Box::new(plugin));
    }

    /// 向智能体添加插件列表
    pub fn add_plugins(&mut self, plugins: Vec<Box<dyn AgentPlugin>>) {
        self.plugins.extend(plugins);
    }

    // ========================================================================
    // 流式对话方法
    // ========================================================================

    /// 流式问答(不保留上下文)
    ///
    /// 返回一个 Stream,每次 yield 一个文本片段
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use futures::StreamExt;
    ///
    /// let mut stream = agent.ask_stream("Tell me a story").await?;
    /// while let Some(result) = stream.next().await {
    ///     match result {
    ///         Ok(text) => print!("{}", text),
    ///         Err(e) => einfo!("Error: {}", e),
    ///     }
    /// }
    /// ```
    pub async fn ask_stream(&self, question: impl Into<String>) -> LLMResult<TextStream> {
        let question = question.into();

        let mut builder = self.client.chat();

        if let Some(ref system) = self.config.system_prompt {
            builder = builder.system(system.clone());
        }

        if let Some(temp) = self.config.temperature {
            builder = builder.temperature(temp);
        }

        if let Some(tokens) = self.config.max_tokens {
            builder = builder.max_tokens(tokens);
        }

        builder = builder.user(question);

        // 发送流式请求
        let chunk_stream = builder.send_stream().await?;

        // 转换为纯文本流
        Ok(Self::chunk_stream_to_text_stream(chunk_stream))
    }

    /// 流式多轮对话(保留上下文)
    ///
    /// 注意:流式对话会在收到完整响应后更新历史记录
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use futures::StreamExt;
    ///
    /// let mut stream = agent.chat_stream("Hello!").await?;
    /// let mut full_response = String::new();
    /// while let Some(result) = stream.next().await {
    ///     match result {
    ///         Ok(text) => {
    ///             print!("{}", text);
    ///             full_response.push_str(&text);
    ///         }
    ///         Err(e) => einfo!("Error: {}", e),
    ///     }
    /// }
    /// info!();
    /// ```
    pub async fn chat_stream(&self, message: impl Into<String>) -> LLMResult<TextStream> {
        let session_id = self.active_session_id.read().await.clone();
        self.chat_stream_with_session(&session_id, message).await
    }

    /// 使用指定会话进行流式多轮对话
    ///
    /// # 参数
    /// - `session_id`: 会话唯一标识
    /// - `message`: 用户消息
    pub async fn chat_stream_with_session(
        &self,
        session_id: &str,
        message: impl Into<String>,
    ) -> LLMResult<TextStream> {
        let message = message.into();

        // 获取模型名称
        let model = self.provider.default_model();

        // 调用 before_chat 钩子(带模型名称)
        let processed_message = if let Some(ref handler) = self.event_handler {
            match handler.before_chat_with_model(&message, model).await? {
                Some(msg) => msg,
                None => return Ok(Box::pin(futures::stream::empty())),
            }
        } else {
            message
        };

        // 获取会话
        let session = self.get_session_arc(session_id).await?;

        // 获取当前历史
        let history = {
            let session_guard = session.read().await;
            session_guard.messages().to_vec()
        };

        // 构建请求
        let mut builder = self.client.chat();

        if let Some(ref system) = self.config.system_prompt {
            builder = builder.system(system.clone());
        }

        if let Some(temp) = self.config.temperature {
            builder = builder.temperature(temp);
        }

        if let Some(tokens) = self.config.max_tokens {
            builder = builder.max_tokens(tokens);
        }

        // 添加历史消息
        builder = builder.messages(history);
        builder = builder.user(processed_message.clone());

        // 发送流式请求
        let chunk_stream = builder.send_stream().await?;

        // 在流式处理前,先添加用户消息到历史
        {
            let mut session_guard = session.write().await;
            session_guard
                .messages_mut()
                .push(ChatMessage::user(&processed_message));
        }

        // 创建一个包装流,在完成时更新历史并调用事件处理
        let event_handler = self.event_handler.clone().map(Arc::new);
        let wrapped_stream =
            Self::create_history_updating_stream(chunk_stream, session, event_handler);

        Ok(wrapped_stream)
    }

    /// 获取原始流式响应块(包含完整信息)
    ///
    /// 如果需要访问工具调用等详细信息,使用此方法
    pub async fn ask_stream_raw(&self, question: impl Into<String>) -> LLMResult<ChatStream> {
        let question = question.into();

        let mut builder = self.client.chat();

        if let Some(ref system) = self.config.system_prompt {
            builder = builder.system(system.clone());
        }

        if let Some(temp) = self.config.temperature {
            builder = builder.temperature(temp);
        }

        if let Some(tokens) = self.config.max_tokens {
            builder = builder.max_tokens(tokens);
        }

        builder = builder.user(question);

        builder.send_stream().await
    }

    /// 流式对话并收集完整响应(使用当前活动会话)
    ///
    /// 同时返回流和一个 channel 用于获取完整响应
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use futures::StreamExt;
    ///
    /// let (mut stream, full_response_rx) = agent.chat_stream_with_full("Hi").await?;
    ///
    /// while let Some(result) = stream.next().await {
    ///     if let Ok(text) = result {
    ///         print!("{}", text);
    ///     }
    /// }
    ///
    /// let full_response = full_response_rx.await?;
    /// info!("\nFull response: {}", full_response);
    /// ```
    pub async fn chat_stream_with_full(
        &self,
        message: impl Into<String>,
    ) -> LLMResult<(TextStream, tokio::sync::oneshot::Receiver<String>)> {
        let session_id = self.active_session_id.read().await.clone();
        self.chat_stream_with_full_session(&session_id, message)
            .await
    }

    /// 使用指定会话进行流式对话并收集完整响应
    ///
    /// # 参数
    /// - `session_id`: 会话唯一标识
    /// - `message`: 用户消息
    pub async fn chat_stream_with_full_session(
        &self,
        session_id: &str,
        message: impl Into<String>,
    ) -> LLMResult<(TextStream, tokio::sync::oneshot::Receiver<String>)> {
        let message = message.into();

        // 获取模型名称
        let model = self.provider.default_model();

        // 调用 before_chat 钩子(带模型名称)
        let processed_message = if let Some(ref handler) = self.event_handler {
            match handler.before_chat_with_model(&message, model).await? {
                Some(msg) => msg,
                None => {
                    let (tx, rx) = tokio::sync::oneshot::channel();
                    let _ = tx.send(String::new());
                    return Ok((Box::pin(futures::stream::empty()), rx));
                }
            }
        } else {
            message
        };

        // 获取会话
        let session = self.get_session_arc(session_id).await?;

        // 获取当前历史
        let history = {
            let session_guard = session.read().await;
            session_guard.messages().to_vec()
        };

        // 构建请求
        let mut builder = self.client.chat();

        if let Some(ref system) = self.config.system_prompt {
            builder = builder.system(system.clone());
        }

        if let Some(temp) = self.config.temperature {
            builder = builder.temperature(temp);
        }

        if let Some(tokens) = self.config.max_tokens {
            builder = builder.max_tokens(tokens);
        }

        builder = builder.messages(history);
        builder = builder.user(processed_message.clone());

        let chunk_stream = builder.send_stream().await?;

        // 添加用户消息到历史
        {
            let mut session_guard = session.write().await;
            session_guard
                .messages_mut()
                .push(ChatMessage::user(&processed_message));
        }

        // 创建 channel 用于传递完整响应
        let (tx, rx) = tokio::sync::oneshot::channel();

        // 创建收集完整响应的流
        let event_handler = self.event_handler.clone().map(Arc::new);
        let wrapped_stream =
            Self::create_collecting_stream(chunk_stream, session, tx, event_handler);

        Ok((wrapped_stream, rx))
    }

    // ========================================================================
    // 内部辅助方法
    // ========================================================================

    /// 将 chunk stream 转换为纯文本 stream
    fn chunk_stream_to_text_stream(chunk_stream: ChatStream) -> TextStream {
        use futures::StreamExt;

        let text_stream = chunk_stream.filter_map(|result| async move {
            match result {
                Ok(chunk) => {
                    // 提取文本内容
                    if let Some(choice) = chunk.choices.first()
                        && let Some(ref content) = choice.delta.content
                        && !content.is_empty()
                    {
                        return Some(Ok(content.clone()));
                    }
                    None
                }
                Err(e) => Some(Err(e)),
            }
        });

        Box::pin(text_stream)
    }

    /// 创建更新历史的流
    fn create_history_updating_stream(
        chunk_stream: ChatStream,
        session: Arc<RwLock<ChatSession>>,
        event_handler: Option<Arc<Box<dyn LLMAgentEventHandler>>>,
    ) -> TextStream {
        use super::types::LLMResponseMetadata;

        let collected = Arc::new(tokio::sync::Mutex::new(String::new()));
        let collected_clone = collected.clone();
        let event_handler_clone = event_handler.clone();
        let metadata_collected = Arc::new(tokio::sync::Mutex::new(None::<LLMResponseMetadata>));
        let metadata_collected_clone = metadata_collected.clone();

        let stream = chunk_stream.filter_map(move |result| {
            let collected = collected.clone();
            let event_handler = event_handler.clone();
            let metadata_collected = metadata_collected.clone();
            async move {
                match result {
                    Ok(chunk) => {
                        if let Some(choice) = chunk.choices.first() {
                            if choice.finish_reason.is_some() {
                                // 最后一个块包含 usage 数据,保存元数据
                                let metadata = LLMResponseMetadata::from(&chunk);
                                *metadata_collected.lock().await = Some(metadata);
                                return None;
                            }
                            if let Some(ref content) = choice.delta.content
                                && !content.is_empty()
                            {
                                let mut collected = collected.lock().await;
                                collected.push_str(content);
                                return Some(Ok(content.clone()));
                            }
                        }
                        None
                    }
                    Err(e) => {
                        if let Some(handler) = event_handler {
                            let _ = handler.on_error(&e).await;
                        }
                        Some(Err(e))
                    }
                }
            }
        });

        let stream = stream
            .chain(futures::stream::once(async move {
                let full_response = collected_clone.lock().await.clone();
                let metadata = metadata_collected_clone.lock().await.clone();
                if !full_response.is_empty() {
                    let mut session = session.write().await;
                    session
                        .messages_mut()
                        .push(ChatMessage::assistant(&full_response));

                    // 滑动窗口:裁剪历史消息以保持固定大小
                    let window_size = session.context_window_size();
                    if window_size.is_some() {
                        let current_messages = session.messages().to_vec();
                        *session.messages_mut() = ChatSession::apply_sliding_window_static(
                            &current_messages,
                            window_size,
                        );
                    }

                    if let Some(handler) = event_handler_clone {
                        if let Some(meta) = &metadata {
                            let _ = handler.after_chat_with_metadata(&full_response, meta).await;
                        } else {
                            let _ = handler.after_chat(&full_response).await;
                        }
                    }
                }
                Err(LLMError::Other("__stream_end__".to_string()))
            }))
            .filter_map(|result| async move {
                match result {
                    Ok(s) => Some(Ok(s)),
                    Err(e) if e.to_string() == "__stream_end__" => None,
                    Err(e) => Some(Err(e)),
                }
            });

        Box::pin(stream)
    }

    /// 创建收集完整响应的流
    fn create_collecting_stream(
        chunk_stream: ChatStream,
        session: Arc<RwLock<ChatSession>>,
        tx: tokio::sync::oneshot::Sender<String>,
        event_handler: Option<Arc<Box<dyn LLMAgentEventHandler>>>,
    ) -> TextStream {
        use super::types::LLMResponseMetadata;
        use futures::StreamExt;

        let collected = Arc::new(tokio::sync::Mutex::new(String::new()));
        let collected_clone = collected.clone();
        let event_handler_clone = event_handler.clone();
        let metadata_collected = Arc::new(tokio::sync::Mutex::new(None::<LLMResponseMetadata>));
        let metadata_collected_clone = metadata_collected.clone();

        let stream = chunk_stream.filter_map(move |result| {
            let collected = collected.clone();
            let event_handler = event_handler.clone();
            let metadata_collected = metadata_collected.clone();
            async move {
                match result {
                    Ok(chunk) => {
                        if let Some(choice) = chunk.choices.first() {
                            if choice.finish_reason.is_some() {
                                // 最后一个块包含 usage 数据,保存元数据
                                let metadata = LLMResponseMetadata::from(&chunk);
                                *metadata_collected.lock().await = Some(metadata);
                                return None;
                            }
                            if let Some(ref content) = choice.delta.content
                                && !content.is_empty()
                            {
                                let mut collected = collected.lock().await;
                                collected.push_str(content);
                                return Some(Ok(content.clone()));
                            }
                        }
                        None
                    }
                    Err(e) => {
                        if let Some(handler) = event_handler {
                            let _ = handler.on_error(&e).await;
                        }
                        Some(Err(e))
                    }
                }
            }
        });

        // 在流结束后更新历史并发送完整响应
        let stream = stream
            .chain(futures::stream::once(async move {
                let full_response = collected_clone.lock().await.clone();
                let mut processed_response = full_response.clone();
                let metadata = metadata_collected_clone.lock().await.clone();

                if !full_response.is_empty() {
                    let mut session = session.write().await;
                    session
                        .messages_mut()
                        .push(ChatMessage::assistant(&processed_response));

                    // 滑动窗口:裁剪历史消息以保持固定大小
                    let window_size = session.context_window_size();
                    if window_size.is_some() {
                        let current_messages = session.messages().to_vec();
                        *session.messages_mut() = ChatSession::apply_sliding_window_static(
                            &current_messages,
                            window_size,
                        );
                    }

                    // 调用 after_chat 钩子(带元数据)
                    if let Some(handler) = event_handler_clone {
                        if let Some(meta) = &metadata {
                            if let Ok(Some(resp)) = handler
                                .after_chat_with_metadata(&processed_response, meta)
                                .await
                            {
                                processed_response = resp;
                            }
                        } else if let Ok(Some(resp)) = handler.after_chat(&processed_response).await
                        {
                            processed_response = resp;
                        }
                    }
                }

                let _ = tx.send(processed_response);

                Err(LLMError::Other("__stream_end__".to_string()))
            }))
            .filter_map(|result| async move {
                match result {
                    Ok(s) => Some(Ok(s)),
                    Err(e) if e.to_string() == "__stream_end__" => None,
                    Err(e) => Some(Err(e)),
                }
            });

        Box::pin(stream)
    }
}

/// LLM Agent 构建器
pub struct LLMAgentBuilder {
    agent_id: String,
    name: Option<String>,
    provider: Option<Arc<dyn LLMProvider>>,
    system_prompt: Option<String>,
    temperature: Option<f32>,
    max_tokens: Option<u32>,
    tools: Vec<Tool>,
    tool_executor: Option<Arc<dyn ToolExecutor>>,
    event_handler: Option<Box<dyn LLMAgentEventHandler>>,
    plugins: Vec<Box<dyn AgentPlugin>>,
    custom_config: HashMap<String, String>,
    prompt_plugin: Option<Box<dyn prompt::PromptTemplatePlugin>>,
    session_id: Option<String>,
    user_id: Option<String>,
    tenant_id: Option<String>,
    context_window_size: Option<usize>,
    /// 持久化存储(用于从数据库加载历史会话)
    message_store: Option<Arc<dyn crate::persistence::MessageStore + Send + Sync>>,
    session_store: Option<Arc<dyn crate::persistence::SessionStore + Send + Sync>>,
    persistence_user_id: Option<uuid::Uuid>,
    persistence_tenant_id: Option<uuid::Uuid>,
    persistence_agent_id: Option<uuid::Uuid>,
}

impl LLMAgentBuilder {
    /// 创建新的构建器
    pub fn new() -> Self {
        Self {
            agent_id: uuid::Uuid::now_v7().to_string(),
            name: None,
            provider: None,
            system_prompt: None,
            temperature: None,
            max_tokens: None,
            tools: Vec::new(),
            tool_executor: None,
            event_handler: None,
            plugins: Vec::new(),
            custom_config: HashMap::new(),
            prompt_plugin: None,
            session_id: None,
            user_id: None,
            tenant_id: None,
            context_window_size: None,
            message_store: None,
            session_store: None,
            persistence_user_id: None,
            persistence_tenant_id: None,
            persistence_agent_id: None,
        }
    }

    /// 设置id
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.agent_id = id.into();
        self
    }

    /// 设置名称
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// 设置 LLM Provider
    pub fn with_provider(mut self, provider: Arc<dyn LLMProvider>) -> Self {
        self.provider = Some(provider);
        self
    }

    /// 设置系统提示词
    pub fn with_system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.system_prompt = Some(prompt.into());
        self
    }

    /// 设置温度
    pub fn with_temperature(mut self, temperature: f32) -> Self {
        self.temperature = Some(temperature);
        self
    }

    /// 设置最大 token 数
    pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
        self.max_tokens = Some(max_tokens);
        self
    }

    /// 添加工具
    pub fn with_tool(mut self, tool: Tool) -> Self {
        self.tools.push(tool);
        self
    }

    /// 设置工具列表
    pub fn with_tools(mut self, tools: Vec<Tool>) -> Self {
        self.tools = tools;
        self
    }

    /// 设置工具执行器
    pub fn with_tool_executor(mut self, executor: Arc<dyn ToolExecutor>) -> Self {
        self.tool_executor = Some(executor);
        self
    }

    /// 设置事件处理器
    pub fn with_event_handler(mut self, handler: Box<dyn LLMAgentEventHandler>) -> Self {
        self.event_handler = Some(handler);
        self
    }

    /// 添加插件
    pub fn with_plugin(mut self, plugin: impl AgentPlugin + 'static) -> Self {
        self.plugins.push(Box::new(plugin));
        self
    }

    /// 添加插件列表
    pub fn with_plugins(mut self, plugins: Vec<Box<dyn AgentPlugin>>) -> Self {
        self.plugins.extend(plugins);
        self
    }

    /// 添加持久化插件(便捷方法)
    ///
    /// 持久化插件实现了 AgentPlugin trait,同时也是一个 LLMAgentEventHandler,
    /// 会自动注册到 agent 的插件列表和事件处理器中。
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use mofa_sdk::persistence::{PersistencePlugin, PostgresStore};
    /// use mofa_sdk::llm::LLMAgentBuilder;
    /// use std::sync::Arc;
    /// use uuid::Uuid;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let store = Arc::new(PostgresStore::connect("postgres://localhost/mofa").await?);
    /// let user_id = Uuid::now_v7();
    /// let tenant_id = Uuid::now_v7();
    /// let agent_id = Uuid::now_v7();
    /// let session_id = Uuid::now_v7();
    ///
    /// let plugin = PersistencePlugin::new(
    ///     "persistence-plugin",
    ///     store,
    ///     user_id,
    ///     tenant_id,
    ///     agent_id,
    ///     session_id,
    /// );
    ///
    /// let agent = LLMAgentBuilder::new()
    ///     .with_id("my-agent")
    ///     .with_persistence_plugin(plugin)
    ///     .build_async()
    ///     .await;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_persistence_plugin(
        mut self,
        plugin: crate::persistence::PersistencePlugin,
    ) -> Self {
        self.message_store = Some(plugin.message_store());
        self.session_store = plugin.session_store();
        self.persistence_user_id = Some(plugin.user_id());
        self.persistence_tenant_id = Some(plugin.tenant_id());
        self.persistence_agent_id = Some(plugin.agent_id());

        // 将持久化插件添加到插件列表
        // 同时作为事件处理器
        let plugin_box: Box<dyn AgentPlugin> = Box::new(plugin.clone());
        let event_handler: Box<dyn LLMAgentEventHandler> = Box::new(plugin);
        self.plugins.push(plugin_box);
        self.event_handler = Some(event_handler);
        self
    }

    /// 设置 Prompt 模板插件
    pub fn with_prompt_plugin(
        mut self,
        plugin: impl prompt::PromptTemplatePlugin + 'static,
    ) -> Self {
        self.prompt_plugin = Some(Box::new(plugin));
        self
    }

    /// 设置支持热重载的 Prompt 模板插件
    pub fn with_hot_reload_prompt_plugin(
        mut self,
        plugin: prompt::HotReloadableRhaiPromptPlugin,
    ) -> Self {
        self.prompt_plugin = Some(Box::new(plugin));
        self
    }

    /// 添加自定义配置
    pub fn with_config(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.custom_config.insert(key.into(), value.into());
        self
    }

    /// 设置初始会话 ID
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// let agent = LLMAgentBuilder::new()
    ///     .with_id("my-agent")
    ///     .with_initial_session_id("user-session-001")
    ///     .build();
    /// ```
    pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
        self.session_id = Some(session_id.into());
        self
    }

    /// 设置用户 ID
    ///
    /// 用于数据库持久化和多用户场景的消息隔离。
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// let agent = LLMAgentBuilder::new()
    ///     .with_id("my-agent")
    ///     .with_user("user-123")
    ///     .build();
    /// ```
    pub fn with_user(mut self, user_id: impl Into<String>) -> Self {
        self.user_id = Some(user_id.into());
        self
    }

    /// 设置租户 ID
    ///
    /// 用于多租户支持,实现不同租户的数据隔离。
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// let agent = LLMAgentBuilder::new()
    ///     .with_id("my-agent")
    ///     .with_tenant("tenant-abc")
    ///     .build();
    /// ```
    pub fn with_tenant(mut self, tenant_id: impl Into<String>) -> Self {
        self.tenant_id = Some(tenant_id.into());
        self
    }

    /// 设置上下文窗口大小(滑动窗口)
    ///
    /// 用于滑动窗口消息管理,指定保留的最大对话轮数。
    /// 当消息历史超过此大小时,会自动裁剪较早的消息。
    ///
    /// # 参数
    /// - `size`: 上下文窗口大小(单位:轮数,rounds)
    ///
    /// # 注意
    /// - 单位是**轮数**(rounds),不是 token 数量
    /// - 每轮对话 ≈ 1 个用户消息 + 1 个助手响应
    /// - 系统消息始终保留,不计入轮数限制
    /// - 从数据库加载消息时也会应用此限制
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// let agent = LLMAgentBuilder::new()
    ///     .with_id("my-agent")
    ///     .with_sliding_window(10)  // 只保留最近 10 轮对话
    ///     .build();
    /// ```
    pub fn with_sliding_window(mut self, size: usize) -> Self {
        self.context_window_size = Some(size);
        self
    }

    /// 从环境变量创建基础配置
    ///
    /// 自动配置:
    /// - OpenAI Provider(从 OPENAI_API_KEY)
    /// - 默认 temperature (0.7) 和 max_tokens (4096)
    ///
    /// # 环境变量
    /// - OPENAI_API_KEY: OpenAI API 密钥(必需)
    /// - OPENAI_BASE_URL: 可选的 API 基础 URL
    /// - OPENAI_MODEL: 可选的默认模型
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use mofa_sdk::llm::LLMAgentBuilder;
    ///
    /// let agent = LLMAgentBuilder::from_env()?
    ///     .with_system_prompt("You are a helpful assistant.")
    ///     .build();
    /// ```
    pub fn from_env() -> LLMResult<Self> {
        use super::openai::{OpenAIConfig, OpenAIProvider};

        let api_key = std::env::var("OPENAI_API_KEY").map_err(|_| {
            LLMError::ConfigError("OPENAI_API_KEY environment variable not set".to_string())
        })?;

        let mut config = OpenAIConfig::new(api_key);

        if let Ok(base_url) = std::env::var("OPENAI_BASE_URL") {
            config = config.with_base_url(&base_url);
        }

        if let Ok(model) = std::env::var("OPENAI_MODEL") {
            config = config.with_model(&model);
        }

        Ok(Self::new()
            .with_provider(Arc::new(OpenAIProvider::with_config(config)))
            .with_temperature(0.7)
            .with_max_tokens(4096))
    }

    /// 构建 LLM Agent
    ///
    /// # Panics
    /// 如果未设置 provider 则 panic
    pub fn build(self) -> LLMAgent {
        let provider = self
            .provider
            .expect("LLM provider must be set before building");

        let config = LLMAgentConfig {
            agent_id: self.agent_id.clone(),
            name: self.name.unwrap_or_else(|| self.agent_id.clone()),
            system_prompt: self.system_prompt,
            temperature: self.temperature,
            max_tokens: self.max_tokens,
            custom_config: self.custom_config,
            user_id: self.user_id,
            tenant_id: self.tenant_id,
            context_window_size: self.context_window_size,
        };

        let mut agent = LLMAgent::with_initial_session(config, provider, self.session_id);

        // 设置Prompt模板插件
        agent.prompt_plugin = self.prompt_plugin;

        if let Some(executor) = self.tool_executor {
            agent.set_tools(self.tools, executor);
        }

        if let Some(handler) = self.event_handler {
            agent.set_event_handler(handler);
        }

        // 处理插件列表:提取 TTS 插件
        let mut plugins = self.plugins;
        let mut tts_plugin = None;

        // 查找并提取 TTS 插件
        for i in (0..plugins.len()).rev() {
            if plugins[i].as_any().is::<mofa_plugins::tts::TTSPlugin>() {
                // 使用 Any::downcast_ref 检查类型
                // 由于我们需要获取所有权,这里使用 is 检查后移除
                let plugin = plugins.remove(i);
                // 尝试 downcast
                if let Ok(tts) = plugin.into_any().downcast::<mofa_plugins::tts::TTSPlugin>() {
                    tts_plugin = Some(Arc::new(Mutex::new(*tts)));
                }
            }
        }

        // 添加剩余插件
        agent.add_plugins(plugins);

        // 设置 TTS 插件
        agent.tts_plugin = tts_plugin;

        agent
    }

    /// 尝试构建 LLM Agent
    ///
    /// 如果未设置 provider 则返回错误
    pub fn try_build(self) -> LLMResult<LLMAgent> {
        let provider = self
            .provider
            .ok_or_else(|| LLMError::ConfigError("LLM provider not set".to_string()))?;

        let config = LLMAgentConfig {
            agent_id: self.agent_id.clone(),
            name: self.name.unwrap_or_else(|| self.agent_id.clone()),
            system_prompt: self.system_prompt,
            temperature: self.temperature,
            max_tokens: self.max_tokens,
            custom_config: self.custom_config,
            user_id: self.user_id,
            tenant_id: self.tenant_id,
            context_window_size: self.context_window_size,
        };

        let mut agent = LLMAgent::with_initial_session(config, provider, self.session_id);

        if let Some(executor) = self.tool_executor {
            agent.set_tools(self.tools, executor);
        }

        if let Some(handler) = self.event_handler {
            agent.set_event_handler(handler);
        }

        // 处理插件列表:提取 TTS 插件
        let mut plugins = self.plugins;
        let mut tts_plugin = None;

        // 查找并提取 TTS 插件
        for i in (0..plugins.len()).rev() {
            if plugins[i].as_any().is::<mofa_plugins::tts::TTSPlugin>() {
                // 使用 Any::downcast_ref 检查类型
                // 由于我们需要获取所有权,这里使用 is 检查后移除
                let plugin = plugins.remove(i);
                // 尝试 downcast
                if let Ok(tts) = plugin.into_any().downcast::<mofa_plugins::tts::TTSPlugin>() {
                    tts_plugin = Some(Arc::new(Mutex::new(*tts)));
                }
            }
        }

        // 添加剩余插件
        agent.add_plugins(plugins);

        // 设置 TTS 插件
        agent.tts_plugin = tts_plugin;

        Ok(agent)
    }

    /// 异步构建 LLM Agent(支持从数据库加载会话)
    ///
    /// 使用持久化插件加载会话历史。
    ///
    /// # 示例(使用持久化插件)
    ///
    /// ```rust,ignore
    /// use mofa_sdk::persistence::{PersistencePlugin, PostgresStore};
    ///
    /// let store = PostgresStore::connect("postgres://localhost/mofa").await?;
    /// let user_id = Uuid::now_v7();
    /// let tenant_id = Uuid::now_v7();
    /// let agent_id = Uuid::now_v7();
    /// let session_id = Uuid::now_v7();
    ///
    /// let plugin = PersistencePlugin::new(
    ///     "persistence-plugin",
    ///     Arc::new(store),
    ///     user_id,
    ///     tenant_id,
    ///     agent_id,
    ///     session_id,
    /// );
    ///
    /// let agent = LLMAgentBuilder::from_env()?
    ///     .with_system_prompt("You are helpful.")
    ///     .with_persistence_plugin(plugin)
    ///     .build_async()
    ///     .await;
    /// ```
    pub async fn build_async(mut self) -> LLMAgent {
        let provider = self
            .provider
            .expect("LLM provider must be set before building");

        // Clone tenant_id for potential fallback use before moving into config
        let tenant_id_for_persistence = self.tenant_id.clone();

        let config = LLMAgentConfig {
            agent_id: self.agent_id.clone(),
            name: self.name.unwrap_or_else(|| self.agent_id.clone()),
            system_prompt: self.system_prompt,
            temperature: self.temperature,
            max_tokens: self.max_tokens,
            custom_config: self.custom_config,
            user_id: self.user_id,
            tenant_id: self.tenant_id,
            context_window_size: self.context_window_size,
        };

        // Fallback: If stores are set but persistence_tenant_id is None, use tenant_id
        let persistence_tenant_id = if self.session_store.is_some()
            && self.persistence_tenant_id.is_none()
            && tenant_id_for_persistence.is_some()
        {
            uuid::Uuid::parse_str(&tenant_id_for_persistence.unwrap()).ok()
        } else {
            self.persistence_tenant_id
        };

        // 使用异步方法,支持从数据库加载
        let mut agent = LLMAgent::with_initial_session_async(
            config,
            provider,
            self.session_id,
            self.message_store,
            self.session_store,
            self.persistence_user_id,
            persistence_tenant_id,
            self.persistence_agent_id,
        )
        .await;

        // 设置Prompt模板插件
        agent.prompt_plugin = self.prompt_plugin;

        if self.tools.is_empty() {
            if let Some(executor) = self.tool_executor.as_ref() {
                if let Ok(tools) = executor.available_tools().await {
                    self.tools = tools;
                }
            }
        }

        if let Some(executor) = self.tool_executor {
            agent.set_tools(self.tools, executor);
        }

        // 处理插件列表:
        // 1. 从持久化插件加载历史(新方式)
        // 2. 提取 TTS 插件
        let mut plugins = self.plugins;
        let mut tts_plugin = None;
        let history_loaded_from_plugin = false;

        // 查找并提取 TTS 插件
        for i in (0..plugins.len()).rev() {
            if plugins[i].as_any().is::<mofa_plugins::tts::TTSPlugin>() {
                // 使用 Any::downcast_ref 检查类型
                // 由于我们需要获取所有权,这里使用 is 检查后移除
                let plugin = plugins.remove(i);
                // 尝试 downcast
                if let Ok(tts) = plugin.into_any().downcast::<mofa_plugins::tts::TTSPlugin>() {
                    tts_plugin = Some(Arc::new(Mutex::new(*tts)));
                }
            }
        }

        // 从持久化插件加载历史(新方式)
        if !history_loaded_from_plugin {
            for plugin in &plugins {
                // 通过 metadata 识别持久化插件
                if plugin.metadata().plugin_type == PluginType::Storage
                    && plugin
                        .metadata()
                        .capabilities
                        .contains(&"message_persistence".to_string())
                {
                    // 这里我们无法直接调用泛型 PersistencePlugin 的 load_history
                    // 因为 trait object 无法访问泛型方法
                    // 历史加载将由 LLMAgent 在首次运行时通过 store 完成
                    tracing::info!("📦 检测到持久化插件,将在 agent 初始化后加载历史");
                    break;
                }
            }
        }

        // 添加剩余插件
        agent.add_plugins(plugins);

        // 设置 TTS 插件
        agent.tts_plugin = tts_plugin;

        // 设置事件处理器
        if let Some(handler) = self.event_handler {
            agent.set_event_handler(handler);
        }

        agent
    }
}

// ============================================================================
// 从配置文件创建
// ============================================================================

impl LLMAgentBuilder {
    /// 从 agent.yml 配置文件创建 Builder
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use mofa_sdk::llm::LLMAgentBuilder;
    ///
    /// let agent = LLMAgentBuilder::from_config_file("agent.yml")?
    ///     .build();
    /// ```
    pub fn from_config_file(path: impl AsRef<std::path::Path>) -> LLMResult<Self> {
        let config = crate::config::AgentYamlConfig::from_file(path)
            .map_err(|e| LLMError::ConfigError(e.to_string()))?;
        Self::from_yaml_config(config)
    }

    /// 从 YAML 配置创建 Builder
    pub fn from_yaml_config(config: crate::config::AgentYamlConfig) -> LLMResult<Self> {
        let mut builder = Self::new()
            .with_id(&config.agent.id)
            .with_name(&config.agent.name);
        // 配置 LLM provider
        if let Some(llm_config) = config.llm {
            let provider = create_provider_from_config(&llm_config)?;
            builder = builder.with_provider(Arc::new(provider));

            if let Some(temp) = llm_config.temperature {
                builder = builder.with_temperature(temp);
            }
            if let Some(tokens) = llm_config.max_tokens {
                builder = builder.with_max_tokens(tokens);
            }
            if let Some(prompt) = llm_config.system_prompt {
                builder = builder.with_system_prompt(prompt);
            }
        }

        Ok(builder)
    }

    // ========================================================================
    // 数据库加载方法
    // ========================================================================

    /// 从数据库加载 agent 配置(全局查找)
    ///
    /// 根据 agent_code 从数据库加载 agent 配置及其关联的 provider。
    ///
    /// # 参数
    /// - `store`: 实现了 AgentStore 的持久化存储
    /// - `agent_code`: Agent 代码(唯一标识)
    ///
    /// # 错误
    /// - 如果 agent 不存在
    /// - 如果 agent 被禁用 (agent_status = false)
    /// - 如果 provider 被禁用 (enabled = false)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use mofa_sdk::{llm::LLMAgentBuilder, persistence::PostgresStore};
    ///
    /// let store = PostgresStore::from_env().await?;
    /// let agent = LLMAgentBuilder::from_database(&store, "my-agent").await?.build();
    /// ```
    #[cfg(feature = "persistence-postgres")]
    pub async fn from_database<S>(store: &S, agent_code: &str) -> LLMResult<Self>
    where
        S: crate::persistence::AgentStore + Send + Sync,
    {
        let config = store
            .get_agent_by_code_with_provider(agent_code)
            .await
            .map_err(|e| LLMError::Other(format!("Failed to load agent from database: {}", e)))?
            .ok_or_else(|| {
                LLMError::Other(format!(
                    "Agent with code '{}' not found in database",
                    agent_code
                ))
            })?;

        Self::from_agent_config(&config)
    }

    /// 从数据库加载 agent 配置(租户隔离)
    ///
    /// 根据 tenant_id 和 agent_code 从数据库加载 agent 配置及其关联的 provider。
    ///
    /// # 参数
    /// - `store`: 实现了 AgentStore 的持久化存储
    /// - `tenant_id`: 租户 ID
    /// - `agent_code`: Agent 代码
    ///
    /// # 错误
    /// - 如果 agent 不存在
    /// - 如果 agent 被禁用 (agent_status = false)
    /// - 如果 provider 被禁用 (enabled = false)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use mofa_sdk::{llm::LLMAgentBuilder, persistence::PostgresStore};
    /// use uuid::Uuid;
    ///
    /// let store = PostgresStore::from_env().await?;
    /// let tenant_id = Uuid::parse_str("xxx-xxx-xxx")?;
    /// let agent = LLMAgentBuilder::from_database_with_tenant(&store, tenant_id, "my-agent").await?.build();
    /// ```
    #[cfg(feature = "persistence-postgres")]
    pub async fn from_database_with_tenant<S>(
        store: &S,
        tenant_id: uuid::Uuid,
        agent_code: &str,
    ) -> LLMResult<Self>
    where
        S: crate::persistence::AgentStore + Send + Sync,
    {
        let config = store
            .get_agent_by_code_and_tenant_with_provider(tenant_id, agent_code)
            .await
            .map_err(|e| LLMError::Other(format!("Failed to load agent from database: {}", e)))?
            .ok_or_else(|| {
                LLMError::Other(format!(
                    "Agent with code '{}' not found for tenant {}",
                    agent_code, tenant_id
                ))
            })?;

        Self::from_agent_config(&config)
    }

    /// 使用数据库 agent 配置,但允许进一步定制
    ///
    /// 加载数据库配置后,可以继续使用 builder 方法进行定制。
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// let agent = LLMAgentBuilder::with_database_agent(&store, "my-agent")
    ///     .await?
    ///     .with_temperature(0.8)  // 覆盖数据库中的温度设置
    ///     .with_system_prompt("Custom prompt")  // 覆盖系统提示词
    ///     .build();
    /// ```
    #[cfg(feature = "persistence-postgres")]
    pub async fn with_database_agent<S>(store: &S, agent_code: &str) -> LLMResult<Self>
    where
        S: crate::persistence::AgentStore + Send + Sync,
    {
        Self::from_database(store, agent_code).await
    }

    /// 从 AgentConfig 创建 Builder(内部辅助方法)
    #[cfg(feature = "persistence-postgres")]
    pub fn from_agent_config(config: &crate::persistence::AgentConfig) -> LLMResult<Self> {
        use super::openai::{OpenAIConfig, OpenAIProvider};

        let agent = &config.agent;
        let provider = &config.provider;

        // 检查 agent 是否启用
        if !agent.agent_status {
            return Err(LLMError::Other(format!(
                "Agent '{}' is disabled (agent_status = false)",
                agent.agent_code
            )));
        }

        // 检查 provider 是否启用
        if !provider.enabled {
            return Err(LLMError::Other(format!(
                "Provider '{}' is disabled (enabled = false)",
                provider.provider_name
            )));
        }

        // 根据 provider_type 创建 LLM Provider
        let llm_provider: Arc<dyn super::LLMProvider> = match provider.provider_type.as_str() {
            "openai" | "azure" | "compatible" | "local" => {
                let mut openai_config = OpenAIConfig::new(provider.api_key.clone());
                openai_config = openai_config.with_base_url(&provider.api_base);
                openai_config = openai_config.with_model(&agent.model_name);

                if let Some(temp) = agent.temperature {
                    openai_config = openai_config.with_temperature(temp);
                }

                if let Some(max_tokens) = agent.max_completion_tokens {
                    openai_config = openai_config.with_max_tokens(max_tokens as u32);
                }

                Arc::new(OpenAIProvider::with_config(openai_config))
            }
            "anthropic" => {
                let mut cfg = AnthropicConfig::new(provider.api_key.clone());
                cfg = cfg.with_base_url(&provider.api_base);
                cfg = cfg.with_model(&agent.model_name);

                if let Some(temp) = agent.temperature {
                    cfg = cfg.with_temperature(temp);
                }
                if let Some(tokens) = agent.max_completion_tokens {
                    cfg = cfg.with_max_tokens(tokens as u32);
                }

                Arc::new(AnthropicProvider::with_config(cfg))
            }
            "gemini" => {
                let mut cfg = GeminiConfig::new(provider.api_key.clone());
                cfg = cfg.with_base_url(&provider.api_base);
                cfg = cfg.with_model(&agent.model_name);

                if let Some(temp) = agent.temperature {
                    cfg = cfg.with_temperature(temp);
                }
                if let Some(tokens) = agent.max_completion_tokens {
                    cfg = cfg.with_max_tokens(tokens as u32);
                }

                Arc::new(GeminiProvider::with_config(cfg))
            }
            "ollama" => {
                let mut ollama_config = OllamaConfig::new();
                ollama_config = ollama_config.with_base_url(&provider.api_base);
                ollama_config = ollama_config.with_model(&agent.model_name);

                if let Some(temp) = agent.temperature {
                    ollama_config = ollama_config.with_temperature(temp);
                }

                if let Some(max_tokens) = agent.max_completion_tokens {
                    ollama_config = ollama_config.with_max_tokens(max_tokens as u32);
                }

                Arc::new(OllamaProvider::with_config(ollama_config))
            }
            other => {
                return Err(LLMError::Other(format!(
                    "Unsupported provider type: {}",
                    other
                )));
            }
        };

        // 创建基础 builder
        let mut builder = Self::new()
            .with_id(agent.id.clone())
            .with_name(agent.agent_name.clone())
            .with_provider(llm_provider)
            .with_system_prompt(agent.system_prompt.clone())
            .with_tenant(agent.tenant_id.to_string());

        // 设置可选参数
        if let Some(temp) = agent.temperature {
            builder = builder.with_temperature(temp);
        }
        if let Some(tokens) = agent.max_completion_tokens {
            builder = builder.with_max_tokens(tokens as u32);
        }
        if let Some(limit) = agent.context_limit {
            builder = builder.with_sliding_window(limit as usize);
        }

        // 处理 custom_params (JSONB) - 将每个 key-value 添加到 custom_config
        if let Some(ref params) = agent.custom_params {
            if let Some(obj) = params.as_object() {
                for (key, value) in obj.iter() {
                    let value_str: String = match value {
                        serde_json::Value::String(s) => s.clone(),
                        serde_json::Value::Bool(b) => b.to_string(),
                        serde_json::Value::Number(n) => n.to_string(),
                        _ => value.to_string(),
                    };
                    builder = builder.with_config(key.as_str(), value_str);
                }
            }
        }

        // 处理 response_format
        if let Some(ref format) = agent.response_format {
            builder = builder.with_config("response_format", format);
        }

        // 处理 stream
        if let Some(stream) = agent.stream {
            builder = builder.with_config("stream", if stream { "true" } else { "false" });
        }

        Ok(builder)
    }
}

/// 从配置创建 LLM Provider

fn create_provider_from_config(
    config: &crate::config::LLMYamlConfig,
) -> LLMResult<super::openai::OpenAIProvider> {
    use super::openai::{OpenAIConfig, OpenAIProvider};

    match config.provider.as_str() {
        "openai" => {
            let api_key = config
                .api_key
                .clone()
                .or_else(|| std::env::var("OPENAI_API_KEY").ok())
                .ok_or_else(|| LLMError::ConfigError("OpenAI API key not set".to_string()))?;

            let mut openai_config = OpenAIConfig::new(api_key);

            if let Some(ref model) = config.model {
                openai_config = openai_config.with_model(model);
            }
            if let Some(ref base_url) = config.base_url {
                openai_config = openai_config.with_base_url(base_url);
            }
            if let Some(temp) = config.temperature {
                openai_config = openai_config.with_temperature(temp);
            }
            if let Some(tokens) = config.max_tokens {
                openai_config = openai_config.with_max_tokens(tokens);
            }

            Ok(OpenAIProvider::with_config(openai_config))
        }
        "azure" => {
            let endpoint = config.base_url.clone().ok_or_else(|| {
                LLMError::ConfigError("Azure endpoint (base_url) not set".to_string())
            })?;
            let api_key = config
                .api_key
                .clone()
                .or_else(|| std::env::var("AZURE_OPENAI_API_KEY").ok())
                .ok_or_else(|| LLMError::ConfigError("Azure API key not set".to_string()))?;
            let deployment = config
                .deployment
                .clone()
                .or_else(|| config.model.clone())
                .ok_or_else(|| {
                    LLMError::ConfigError("Azure deployment name not set".to_string())
                })?;

            Ok(OpenAIProvider::azure(endpoint, api_key, deployment))
        }
        "compatible" | "local" => {
            let base_url = config.base_url.clone().ok_or_else(|| {
                LLMError::ConfigError("base_url not set for compatible provider".to_string())
            })?;
            let model = config
                .model
                .clone()
                .unwrap_or_else(|| "default".to_string());

            Ok(OpenAIProvider::local(base_url, model))
        }
        other => Err(LLMError::ConfigError(format!(
            "Unknown provider: {}",
            other
        ))),
    }
}

// ============================================================================
// MoFAAgent 实现 - 新的统一微内核架构
// ============================================================================

#[async_trait::async_trait]
impl mofa_kernel::agent::MoFAAgent for LLMAgent {
    fn id(&self) -> &str {
        &self.metadata.id
    }

    fn name(&self) -> &str {
        &self.metadata.name
    }

    fn capabilities(&self) -> &mofa_kernel::agent::AgentCapabilities {
        // 将 metadata 中的 capabilities 转换为 AgentCapabilities
        // 这里需要使用一个静态的 AgentCapabilities 实例
        // 或者在 LLMAgent 中存储一个 AgentCapabilities 字段
        // 为了简化,我们创建一个基于当前 metadata 的实现
        use mofa_kernel::agent::AgentCapabilities;

        // 注意:这里返回的是一个临时引用,实际使用中可能需要调整 LLMAgent 的结构
        // 来存储一个 AgentCapabilities 实例
        // 这里我们使用一个 hack 来返回一个静态实例
        static CAPABILITIES: std::sync::OnceLock<AgentCapabilities> = std::sync::OnceLock::new();

        CAPABILITIES.get_or_init(|| {
            AgentCapabilities::builder()
                .tag("llm")
                .tag("chat")
                .tag("text-generation")
                .input_type(mofa_kernel::agent::InputType::Text)
                .output_type(mofa_kernel::agent::OutputType::Text)
                .supports_streaming(true)
                .supports_tools(true)
                .build()
        })
    }

    async fn initialize(
        &mut self,
        ctx: &mofa_kernel::agent::AgentContext,
    ) -> mofa_kernel::agent::AgentResult<()> {
        // 初始化所有插件(load -> init)
        let mut plugin_config = mofa_kernel::plugin::PluginConfig::new();
        for (k, v) in &self.config.custom_config {
            plugin_config.set(k, v);
        }
        if let Some(user_id) = &self.config.user_id {
            plugin_config.set("user_id", user_id);
        }
        if let Some(tenant_id) = &self.config.tenant_id {
            plugin_config.set("tenant_id", tenant_id);
        }
        let session_id = self.active_session_id.read().await.clone();
        plugin_config.set("session_id", session_id);

        let plugin_ctx =
            mofa_kernel::plugin::PluginContext::new(self.id()).with_config(plugin_config);

        for plugin in &mut self.plugins {
            plugin
                .load(&plugin_ctx)
                .await
                .map_err(|e| mofa_kernel::agent::AgentError::InitializationFailed(e.to_string()))?;
            plugin
                .init_plugin()
                .await
                .map_err(|e| mofa_kernel::agent::AgentError::InitializationFailed(e.to_string()))?;
        }
        self.state = mofa_kernel::agent::AgentState::Ready;

        // 将上下文信息保存到 metadata(如果需要)
        let _ = ctx;

        Ok(())
    }

    async fn execute(
        &mut self,
        input: mofa_kernel::agent::AgentInput,
        _ctx: &mofa_kernel::agent::AgentContext,
    ) -> mofa_kernel::agent::AgentResult<mofa_kernel::agent::AgentOutput> {
        use mofa_kernel::agent::{AgentError, AgentInput, AgentOutput};

        // 将 AgentInput 转换为字符串
        let message = match input {
            AgentInput::Text(text) => text,
            AgentInput::Json(json) => json.to_string(),
            _ => {
                return Err(AgentError::ValidationFailed(
                    "Unsupported input type for LLMAgent".to_string(),
                ));
            }
        };

        // 执行 chat
        let response = self
            .chat(&message)
            .await
            .map_err(|e| AgentError::ExecutionFailed(format!("LLM chat failed: {}", e)))?;

        // 将响应转换为 AgentOutput
        Ok(AgentOutput::text(response))
    }

    async fn shutdown(&mut self) -> mofa_kernel::agent::AgentResult<()> {
        // 销毁所有插件
        for plugin in &mut self.plugins {
            plugin
                .unload()
                .await
                .map_err(|e| mofa_kernel::agent::AgentError::ShutdownFailed(e.to_string()))?;
        }
        self.state = mofa_kernel::agent::AgentState::Shutdown;
        Ok(())
    }

    fn state(&self) -> mofa_kernel::agent::AgentState {
        self.state.clone()
    }
}

// ============================================================================
// 便捷函数
// ============================================================================

/// 快速创建简单的 LLM Agent
///
/// # 示例
///
/// ```rust,ignore
/// use mofa_sdk::llm::{simple_llm_agent, openai_from_env};
/// use std::sync::Arc;
///
/// let agent = simple_llm_agent(
///     "my-agent",
///     Arc::new(openai_from_env()),
///     "You are a helpful assistant."
/// );
/// ```
pub fn simple_llm_agent(
    agent_id: impl Into<String>,
    provider: Arc<dyn LLMProvider>,
    system_prompt: impl Into<String>,
) -> LLMAgent {
    LLMAgentBuilder::new()
        .with_id(agent_id)
        .with_provider(provider)
        .with_system_prompt(system_prompt)
        .build()
}

/// 从配置文件创建 LLM Agent
///
/// # 示例
///
/// ```rust,ignore
/// use mofa_sdk::llm::agent_from_config;
///
/// let agent = agent_from_config("agent.yml")?;
/// ```

pub fn agent_from_config(path: impl AsRef<std::path::Path>) -> LLMResult<LLMAgent> {
    LLMAgentBuilder::from_config_file(path)?.try_build()
}