lingshu-core 0.10.0

Agent core: conversation loop, prompt builder, context compression, model routing
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
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
//! # Agent — core entry point for conversation execution
//!
//! WHY a builder: The Agent needs ~10 dependencies injected (provider,
//! tools, state DB, callbacks, config). A builder prevents 10-argument
//! constructors and makes optional dependencies explicit.
//!
//! ```text
//!   AgentBuilder::new("model")
//!       .provider(provider)
//!       .tools(registry)
//!       .state_db(db)
//!       .build()? ──→ Agent
//!//!                      ├── .chat("hi")        → simple interface
//!                      └── .run_conversation() → full interface
//! ```

use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
use std::sync::atomic::{AtomicU32, Ordering};

use tokio::sync::{Mutex, RwLock};
use tokio_util::sync::CancellationToken;

use lingshu_plugins::{discover_plugins, hermes_supports_hook, invoke_hermes_hook};
use lingshu_state::SessionDb;
use lingshu_tools::ProcessTable;
use lingshu_tools::TodoStore;
use lingshu_tools::config_ref::{AppConfigRef, LspServerConfigRef};
use lingshu_tools::registry::{GatewaySender, ToolInventoryEntry, ToolRegistry};
use lingshu_types::{
    AgentError, ApiMode, Cost, Message, OriginChat, Platform, Role, RunOutcome, Usage,
};
use edgequake_llm::LLMProvider;

use crate::config::AppConfig;

// ─── Agent ────────────────────────────────────────────────────────────

pub struct Agent {
    /// WHY RwLock on config: Model hot-swap (/model command) updates the
    /// model name at runtime. RwLock allows concurrent reads during the
    /// conversation loop while permitting rare writes on model switch.
    pub(crate) config: RwLock<AgentConfig>,
    /// WHY RwLock on provider: The /model command swaps the LLM provider
    /// at runtime. The conversation loop clones the Arc at loop start,
    /// so in-flight conversations aren't affected by a swap.
    pub(crate) provider: RwLock<Arc<dyn LLMProvider>>,
    #[allow(dead_code)] // Used in Phase 1.6 conversation loop
    pub(crate) state_db: Option<Arc<SessionDb>>,
    pub(crate) tool_registry: RwLock<Option<Arc<ToolRegistry>>>,
    /// Gateway-backed outbound sender for `send_message`.
    ///
    /// None in plain CLI / cron sessions. Set by the messaging gateway runtime
    /// so tool execution can deliver to external platforms without duplicating
    /// transport logic inside the agent loop.
    pub(crate) gateway_sender: RwLock<Option<Arc<dyn GatewaySender>>>,
    /// Shared process table for background-process management tools.
    /// WHY on Agent: All tool invocations in the same session share the
    /// same process namespace — Agent lifetime == session lifetime.
    pub(crate) process_table: Arc<ProcessTable>,
    /// Serializes conversation execution without blocking session readers.
    ///
    /// WHY separate from `session`: the old design used the session write lock
    /// as both the mutable state guard and the conversation-level mutex. That
    /// kept `/status`, session inspection, and other read paths blocked for the
    /// full duration of prompt assembly, API calls, and tool execution.
    pub(crate) conversation_lock: Mutex<()>,
    pub(crate) session: RwLock<SessionState>,
    pub(crate) budget: Arc<IterationBudget>,
    /// Cancel token is wrapped in a Mutex so it can be RESET before each new
    /// conversation turn. CancellationToken is a one-way latch — once cancelled
    /// it cannot be un-cancelled. By replacing it with a fresh token at the
    /// start of execute_loop we ensure Ctrl+C only stops the current turn, not
    /// all future turns.
    pub(crate) cancel: std::sync::Mutex<CancellationToken>,
    /// Dedicated cancel token for the process-table GC task.
    ///
    /// WHY separate from `cancel`: `cancel` is reset on every new conversation
    /// turn (see execute_loop) so it can't drive a long-lived background task.
    /// `gc_cancel` lives for the full Agent lifetime and is cancelled via
    /// `Drop` so the GC stops when the Agent is dropped.  Mirrors the cleanup
    /// semantics of hermes-agent's `FINISHED_TTL_SECONDS` periodic cleanup.
    pub(crate) gc_cancel: CancellationToken,
    /// Per-session task list — survives context compression.
    ///
    /// WHY on Agent: The Agent lifetime == session lifetime. Placing the store
    /// here mirrors hermes-agent's `self._todo_store` on the `AIAgent` class.
    /// After each compression `format_for_injection()` re-injects active items
    /// so the model never loses its plan across context-window boundaries.
    pub(crate) todo_store: Arc<lingshu_tools::TodoStore>,
    /// Persistent session goals — survives compression and restarts.
    pub(crate) goal_store: Arc<dyn crate::goals::GoalStore>,
    /// Pluggable context engine for custom context management strategies.
    /// WHY Option: The default `BuiltinCompressorEngine` is used when None.
    /// External engines inject additional tool schemas at session start.
    pub(crate) context_engine: Option<Arc<dyn crate::context_engine::ContextEngine>>,

    // ── Steering ──────────────────────────────────────────────────────────
    //
    // Mission steering allows the TUI (or gateway) to inject guidance text
    // into the running agent loop without stopping it.
    //
    // WHY separate channel from cancel: cancel is a one-way latch; steering
    // needs to carry text payloads and allow multiple events per turn.
    //
    // WHY Mutex<Option<SteeringReceiver>>: the receiver is moved into
    // execute_loop for its duration.  Using Mutex<Option<Receiver>> lets
    // execute_loop take ownership while still being accessible to public API.
    // The channel is recreated at the start of each new conversation turn.
    //
    // WHY steer_tx is public(crate): The TUI (lingshu-cli) accesses it via
    // Agent::steer_sender() which clones the Arc-less Sender.
    pub(crate) steer_tx: crate::steering::SteeringSender,
    pub(crate) steer_rx: std::sync::Mutex<Option<crate::steering::SteeringReceiver>>,
    /// Stream sink active only while `execute_loop` is running (SteerPending events).
    pub(crate) steer_event_tx:
        std::sync::Mutex<Option<tokio::sync::mpsc::UnboundedSender<crate::StreamEvent>>>,
    /// Count of steering events queued but not yet injected at a tool boundary.
    pub(crate) steer_pending: std::sync::atomic::AtomicUsize,
}

/// Options for cloning an agent into a fresh isolated session.
#[derive(Debug, Clone, Default)]
pub struct IsolatedAgentOptions {
    /// Optional fixed session identifier for the child session.
    pub session_id: Option<String>,
    /// Optional platform override for the child session.
    pub platform: Option<Platform>,
    /// Optional quiet-mode override.
    pub quiet_mode: Option<bool>,
    /// Optional origin chat override for gateway-created isolated sessions.
    pub origin_chat: Option<OriginChat>,
    /// Pin kanban worker to a specific task card.
    pub kanban_task_id: Option<String>,
    /// Spawn worker with a named profile's config/state (kanban assignee).
    pub profile: Option<String>,
    /// Install root for profile resolution (`~/.lingshu`).
    pub install_root: Option<std::path::PathBuf>,
}

/// Immutable per-agent configuration (subset of AppConfig relevant to the loop).
#[derive(Debug, Clone)]
pub struct AgentConfig {
    pub model: String,
    pub max_iterations: u32,
    pub enabled_toolsets: Vec<String>,
    pub disabled_toolsets: Vec<String>,
    pub enabled_tools: Vec<String>,
    pub disabled_tools: Vec<String>,
    pub streaming: bool,
    pub temperature: Option<f32>,
    pub platform: Platform,
    pub api_mode: ApiMode,
    pub session_id: Option<String>,
    pub quiet_mode: bool,
    pub save_trajectories: bool,
    pub skip_context_files: bool,
    pub skip_memory: bool,
    pub reasoning_effort: Option<String>,
    /// Optional persona/personality instruction appended to the system prompt.
    /// Resolved from `config.display.personality` via `resolve_personality()`.
    pub personality_addon: Option<String>,
    /// Optional custom prompt persisted in config and appended to the base prompt.
    pub custom_system_prompt: Option<String>,
    /// Model config for routing (base_url, api_key_env, smart routing).
    pub model_config: crate::config::ModelConfig,
    /// Skills config — disabled skills, platform-specific disabled.
    pub skills_config: crate::config::SkillsConfig,
    /// Memory config — write approval gate, etc.
    pub memory_config: crate::config::MemoryConfig,
    /// Terminal/shell dangerous-command approval policy.
    pub approvals_config: crate::config::ApprovalsConfig,
    /// Kanban multi-agent board settings.
    pub kanban_config: crate::config::KanbanConfig,
    /// When set, scopes kanban lifecycle tools to this task (dispatcher workers).
    pub kanban_task_id: Option<String>,
    /// Plugin config — enable/disable state and install root.
    pub plugins_config: crate::config::PluginsConfig,
    /// Delegation runtime controls mirrored from AppConfig.delegation.
    pub delegation_enabled: bool,
    pub delegation_model: Option<String>,
    pub delegation_provider: Option<String>,
    pub delegation_max_subagents: u32,
    pub delegation_max_iterations: u32,
    /// Origin of the current session — named platform + chat identifier.
    ///
    /// Set by the gateway when a message arrives from a real chat
    /// (Telegram, WhatsApp, Discord, etc.).  Passed into every `ToolContext`
    /// so that `manage_cron_jobs(action='create', deliver='origin')` can
    /// record the correct delivery target without the LLM needing to know it.
    /// None in CLI / cron / test sessions.
    pub origin_chat: Option<OriginChat>,
    /// Browser automation config (recording, timeouts).
    pub browser: crate::config::BrowserConfig,
    /// Whether automatic checkpoints are enabled.
    pub checkpoints_enabled: bool,
    /// Maximum checkpoints to retain per working directory.
    pub checkpoints_max_snapshots: u32,
    pub checkpoints_max_total_size_mb: u32,
    pub checkpoints_max_file_size_mb: u32,
    pub computer_use_enabled: bool,
    pub computer_use_keep_last_n_screenshots: u32,
    pub computer_use_confirm_destructive: bool,
    pub computer_use_cua_cmd: String,
    /// Active terminal backend and backend-specific configuration.
    pub terminal_backend: lingshu_tools::tools::backends::BackendKind,
    pub terminal_docker: lingshu_tools::tools::backends::DockerBackendConfig,
    pub terminal_ssh: lingshu_tools::tools::backends::SshBackendConfig,
    pub terminal_modal: lingshu_tools::tools::backends::ModalBackendConfig,
    pub terminal_daytona: lingshu_tools::tools::backends::DaytonaBackendConfig,
    pub terminal_singularity: lingshu_tools::tools::backends::SingularityBackendConfig,
    /// Context-compression policy copied from AppConfig at session start.
    pub compression: crate::config::CompressionConfig,
    /// Auxiliary side-task routing (vision, compression, other helper calls).
    pub auxiliary: crate::config::AuxiliaryConfig,
    /// Shadow judge configuration (completion oracle).
    pub shadow_judge: crate::config::ShadowJudgeConfig,
    /// Persistent goals / Ralph loop configuration.
    pub goals: crate::config::GoalsConfig,
    /// Default Mixture-of-Agents roster and aggregator.
    pub moa: crate::config::MoaConfig,
    /// Voice output configuration projected from AppConfig.
    pub tts: crate::config::TtsConfig,
    /// Voice input configuration projected from AppConfig.
    pub stt: crate::config::SttConfig,
    /// Default image generation provider/model projected from AppConfig.
    pub image_generation: crate::config::ImageGenerationConfig,
    /// Env-var names allowed to pass through the subprocess security blocklist.
    ///
    /// Populated from `terminal.env_passthrough` in config.yaml and applied
    /// to the global registry when the Agent is built.  Skills that declare
    /// `required_environment_variables` also feed the registry at load time.
    pub terminal_env_passthrough: Vec<String>,
    /// Additional file roots trusted by file tools beyond the active workspace.
    pub file_allowed_roots: Vec<std::path::PathBuf>,
    /// Denied prefixes layered over the workspace and allow-root policy.
    pub path_restrictions: Vec<std::path::PathBuf>,
    /// LSP runtime configuration projected from AppConfig.
    pub lsp: crate::config::LspConfig,
    /// Whether tool-result spill-to-artifact is enabled.
    pub result_spill: bool,
    /// Byte threshold for spilling tool results.
    pub result_spill_threshold: usize,
    /// Preview lines kept in the spill stub.
    pub result_spill_preview_lines: usize,
    /// Per-turn aggregate tool-result char budget (`0` = disabled).
    pub result_turn_budget_chars: usize,
    /// Maximum write payload KiB (None = use default 32 KiB).
    pub max_write_payload_kib: Option<u32>,
    /// Default `write_file` create_dirs when the model omits the flag (local homelab paths).
    pub local_write_create_dirs: bool,
    /// Absolute completion cap for local tool turns (yaml; env overrides).
    pub local_max_tool_turn_tokens: usize,
    /// Per-turn file-mutation footers (success log + failure advisory).
    pub file_mutation_verifier: bool,
    /// Cross-session Anthropic prompt prefix cache (stable/dynamic split + TTL).
    pub cache: crate::config::CacheConfig,
    /// Pluggable web search backend chain.
    pub web_search: crate::config::WebSearchConfig,
    /// Hermes-aligned `web:` capability overrides (search_backend / extract_backend / backend).
    pub web: crate::config::WebToolsConfig,
}

impl Default for AgentConfig {
    fn default() -> Self {
        Self {
            model: "ollama/gemma4:latest".into(),
            max_iterations: 90,
            enabled_toolsets: Vec::new(),
            disabled_toolsets: Vec::new(),
            enabled_tools: Vec::new(),
            disabled_tools: Vec::new(),
            streaming: true,
            temperature: None,
            platform: Platform::Cli,
            api_mode: ApiMode::ChatCompletions,
            session_id: None,
            quiet_mode: false,
            save_trajectories: false,
            skip_context_files: false,
            skip_memory: false,
            reasoning_effort: None,
            personality_addon: None,
            custom_system_prompt: None,
            model_config: crate::config::ModelConfig::default(),
            skills_config: crate::config::SkillsConfig::default(),
            memory_config: crate::config::MemoryConfig::default(),
            approvals_config: crate::config::ApprovalsConfig::default(),
            kanban_config: crate::config::KanbanConfig::default(),
            kanban_task_id: None,
            plugins_config: crate::config::PluginsConfig::default(),
            delegation_enabled: true,
            delegation_model: None,
            delegation_provider: None,
            delegation_max_subagents: 3,
            delegation_max_iterations: 50,
            origin_chat: None,
            browser: crate::config::BrowserConfig::default(),
            checkpoints_enabled: true,
            checkpoints_max_snapshots: 20,
            checkpoints_max_total_size_mb: 200,
            checkpoints_max_file_size_mb: 10,
            computer_use_enabled: false,
            computer_use_keep_last_n_screenshots: 1,
            computer_use_confirm_destructive: true,
            computer_use_cua_cmd: "cua-driver".into(),
            terminal_backend: lingshu_tools::tools::backends::BackendKind::Local,
            terminal_docker: lingshu_tools::tools::backends::DockerBackendConfig::default(),
            terminal_ssh: lingshu_tools::tools::backends::SshBackendConfig::default(),
            terminal_modal: lingshu_tools::tools::backends::ModalBackendConfig::default(),
            terminal_daytona: lingshu_tools::tools::backends::DaytonaBackendConfig::default(),
            terminal_singularity:
                lingshu_tools::tools::backends::SingularityBackendConfig::default(),
            compression: crate::config::CompressionConfig::default(),
            auxiliary: crate::config::AuxiliaryConfig::default(),
            shadow_judge: crate::config::ShadowJudgeConfig::default(),
            goals: crate::config::GoalsConfig::default(),
            moa: crate::config::MoaConfig::default(),
            tts: crate::config::TtsConfig::default(),
            stt: crate::config::SttConfig::default(),
            image_generation: crate::config::ImageGenerationConfig::default(),
            terminal_env_passthrough: Vec::new(),
            file_allowed_roots: Vec::new(),
            path_restrictions: Vec::new(),
            lsp: crate::config::LspConfig::default(),
            result_spill: true,
            result_spill_threshold: 16_384,
            result_spill_preview_lines: 80,
            result_turn_budget_chars: 200_000,
            max_write_payload_kib: None,
            local_write_create_dirs: true,
            local_max_tool_turn_tokens:
                lingshu_tools::mutation_turn_policy::LOCAL_TOOL_TURN_ABS_MAX_TOKENS,
            file_mutation_verifier: true,
            cache: crate::config::CacheConfig::default(),
            web_search: crate::config::WebSearchConfig::default(),
            web: crate::config::WebToolsConfig::default(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ResolvedToolPolicy {
    pub expanded_enabled: Vec<String>,
    pub expanded_disabled: Vec<String>,
    pub parent_active_toolsets: Vec<String>,
}

pub(crate) fn resolve_tool_policy(config: &AgentConfig) -> ResolvedToolPolicy {
    let expanded_enabled = lingshu_tools::toolsets::expand_toolset_names(&config.enabled_toolsets);
    let expanded_disabled =
        lingshu_tools::toolsets::expand_toolset_names(&config.disabled_toolsets);
    let parent_active_toolsets = if config.enabled_toolsets.is_empty()
        || lingshu_tools::toolsets::contains_all_sentinel(&config.enabled_toolsets)
        || expanded_enabled.is_empty()
    {
        Vec::new()
    } else {
        expanded_enabled
            .iter()
            .filter(|toolset| {
                !expanded_disabled
                    .iter()
                    .any(|disabled| disabled == *toolset)
            })
            .cloned()
            .collect()
    };

    ResolvedToolPolicy {
        expanded_enabled,
        expanded_disabled,
        parent_active_toolsets,
    }
}

impl AgentConfig {
    fn lsp_server_refs(&self) -> std::collections::HashMap<String, LspServerConfigRef> {
        self.lsp
            .servers
            .iter()
            .map(|(name, server)| {
                (
                    name.clone(),
                    LspServerConfigRef {
                        command: server.command.clone(),
                        args: server.args.clone(),
                        file_extensions: server.file_extensions.clone(),
                        language_id: server.language_id.clone(),
                        root_markers: server.root_markers.clone(),
                        env: server.env.clone(),
                        initialization_options: server.initialization_options.clone(),
                    },
                )
            })
            .collect()
    }

    fn disabled_skills_for_platform(&self) -> Vec<String> {
        let mut disabled = self.skills_config.disabled.clone();
        let platform_key = self.platform.to_string();
        if let Some(platform_disabled) = self.skills_config.platform_disabled.get(&platform_key) {
            disabled.extend(platform_disabled.iter().cloned());
        }
        disabled
    }

    fn disabled_plugins_for_platform(&self) -> Vec<String> {
        let mut disabled = self.plugins_config.disabled.clone();
        let platform_key = self.platform.to_string();
        if let Some(platform_disabled) = self.plugins_config.platform_disabled.get(&platform_key) {
            disabled.extend(platform_disabled.iter().cloned());
        }
        disabled
    }

    pub(crate) fn to_app_config_ref(
        &self,
        gateway_running: bool,
        tool_policy: &ResolvedToolPolicy,
    ) -> AppConfigRef {
        AppConfigRef {
            lingshu_home: crate::config::lingshu_home(),
            file_allowed_roots: self.file_allowed_roots.clone(),
            path_restrictions: self.path_restrictions.clone(),
            lsp_enabled: self.lsp.enabled,
            lsp_file_size_limit_bytes: self.lsp.file_size_limit_bytes,
            lsp_post_write_timeout_ms: self.lsp.timeout_ms,
            lsp_servers: self.lsp_server_refs(),
            delegation_enabled: self.delegation_enabled,
            delegation_model: self.delegation_model.clone(),
            delegation_provider: self.delegation_provider.clone(),
            delegation_max_subagents: self.delegation_max_subagents,
            delegation_max_iterations: self.delegation_max_iterations,
            parent_active_toolsets: tool_policy.parent_active_toolsets.clone(),
            disabled_toolsets: tool_policy.expanded_disabled.clone(),
            enabled_tools: self.enabled_tools.clone(),
            disabled_tools: self.disabled_tools.clone(),
            external_skill_dirs: self.skills_config.external_dirs.clone(),
            disabled_skills: self.disabled_skills_for_platform(),
            disabled_plugins: self.disabled_plugins_for_platform(),
            plugin_install_dir: self.plugins_config.install_dir.clone(),
            preloaded_skills: self.skills_config.preloaded.clone(),
            skills_write_approval: self.skills_config.write_approval,
            memory_write_approval: self.memory_config.write_approval,
            approval_mode: self.approvals_config.mode,
            approvals_smart_model: self.approvals_config.smart_model.clone(),
            kanban_enabled: self.kanban_config.enabled,
            kanban_claim_ttl_secs: self.kanban_config.claim_ttl_secs,
            kanban_default_max_runtime_secs: self.kanban_config.default_max_runtime_secs,
            skills_hub_url: self.skills_config.hub_url.clone(),
            browser_record_sessions: self.browser.record_sessions,
            browser_command_timeout: self.browser.command_timeout,
            browser_recording_max_age_hours: self.browser.recording_max_age_hours,
            checkpoints_enabled: self.checkpoints_enabled,
            checkpoints_max_snapshots: self.checkpoints_max_snapshots,
            checkpoints_max_total_size_mb: self.checkpoints_max_total_size_mb,
            checkpoints_max_file_size_mb: self.checkpoints_max_file_size_mb,
            computer_use_enabled: self.computer_use_enabled,
            computer_use_keep_last_n_screenshots: self.computer_use_keep_last_n_screenshots,
            computer_use_confirm_destructive: self.computer_use_confirm_destructive,
            computer_use_cua_cmd: self.computer_use_cua_cmd.clone(),
            active_model: self.model.clone(),
            terminal_backend: self.terminal_backend.clone(),
            terminal_docker: self.terminal_docker.clone(),
            terminal_ssh: self.terminal_ssh.clone(),
            terminal_modal: self.terminal_modal.clone(),
            terminal_daytona: self.terminal_daytona.clone(),
            terminal_singularity: self.terminal_singularity.clone(),
            terminal_env_passthrough: self.terminal_env_passthrough.clone(),
            auxiliary_provider: self.auxiliary.provider.clone(),
            auxiliary_model: self.auxiliary.model.clone(),
            auxiliary_base_url: self.auxiliary.base_url.clone(),
            auxiliary_api_key_env: self.auxiliary.api_key_env.clone(),
            moa_enabled: self.moa.enabled,
            moa_reference_models: self.moa.reference_models.clone(),
            moa_aggregator_model: Some(self.moa.aggregator_model.clone()),
            tts_provider: Some(self.tts.provider.clone()),
            tts_voice: Some(self.tts.voice.clone()),
            tts_rate: self.tts.rate.clone(),
            tts_model: self.tts.model.clone(),
            tts_elevenlabs_voice_id: self.tts.elevenlabs_voice_id.clone(),
            tts_elevenlabs_model_id: self.tts.elevenlabs_model_id.clone(),
            tts_elevenlabs_api_key_env: Some(self.tts.elevenlabs_api_key_env.clone()),
            stt_provider: Some(self.stt.provider.clone()),
            stt_whisper_model: Some(self.stt.whisper_model.clone()),
            image_provider: Some(self.image_generation.provider.clone()),
            image_model: Some(self.image_generation.model.clone()),
            result_spill: self.result_spill,
            result_spill_threshold: self.result_spill_threshold,
            result_spill_preview_lines: self.result_spill_preview_lines,
            result_turn_budget_chars: self.result_turn_budget_chars,
            max_write_payload_kib: self.max_write_payload_kib.map_or(
                lingshu_tools::edit_contract::DEFAULT_MAX_MUTATION_PAYLOAD_KIB,
                |kib| kib as usize,
            ),
            local_write_create_dirs: crate::local_provider_policy::effective_local_write_create_dirs(
                self.local_write_create_dirs,
                &self.model,
            ),
            local_max_tool_turn_tokens: self.local_max_tool_turn_tokens,
            web_search: lingshu_tools::config_ref::WebSearchConfigRef {
                primary: self.web_search.primary.clone(),
                fallbacks: self.web_search.fallbacks.clone(),
                timeout_secs: self.web_search.timeout_secs,
                backends: self
                    .web_search
                    .backends
                    .iter()
                    .map(|(k, v)| {
                        (
                            k.clone(),
                            lingshu_tools::config_ref::WebSearchBackendConfigRef {
                                api_key: v.api_key.clone(),
                                endpoint: v.endpoint.clone(),
                                rps: v.rps,
                                timeout_secs: v.timeout_secs,
                            },
                        )
                    })
                    .collect(),
            },
            web: lingshu_tools::config_ref::WebToolsConfigRef {
                search_backend: self.web.search_backend.clone(),
                extract_backend: self.web.extract_backend.clone(),
                backend: self.web.backend.clone(),
            },
            gateway_running,
            ..Default::default()
        }
    }
}

/// Per-session mutable state, protected by RwLock.
#[derive(Clone, Default)]
pub struct SessionState {
    /// Unique session identifier — set once at conversation start,
    /// persisted to SQLite at loop end for session search/history.
    pub session_id: Option<String>,
    pub messages: Vec<Message>,
    pub cached_system_prompt: Option<String>,
    /// Stable (cacheable) zone of the system prompt — set alongside
    /// `cached_system_prompt` when the prompt is built via `build_blocks()`.
    ///
    /// When Some, the conversation layer splits the combined prompt at this
    /// boundary and sends two system messages to Anthropic: the stable block
    /// with `cache_control: ephemeral` (cross-session cache hit) and the
    /// dynamic remainder without cache_control.
    ///
    /// Always cleared together with `cached_system_prompt`.
    pub cached_stable_prompt: Option<String>,
    pub user_turn_count: u32,
    pub api_call_count: u32,
    pub session_input_tokens: u64,
    pub session_output_tokens: u64,
    pub session_cache_read_tokens: u64,
    pub session_cache_write_tokens: u64,
    pub session_reasoning_tokens: u64,
    /// Prompt-side tokens from the most recent model call.
    ///
    /// This tracks current context pressure. Session token counters above track
    /// cumulative spend across the whole conversation.
    pub last_prompt_tokens: u64,
    /// Disable native streamed tool turns after a provider rejects them once.
    ///
    /// WHY session-scoped: some provider/model combinations incorrectly
    /// advertise streamed tool support, then reject the actual request at
    /// runtime. Once observed, repeating the same request wastes latency and
    /// spams users with avoidable 400s. Plain text streaming still remains on.
    pub native_tool_streaming_disabled: bool,
    /// Provider/model pairs that rejected multimodal tool-result content (Hermes parity).
    pub tool_result_image_downgrades: std::collections::HashSet<(String, String)>,
    /// Terminal harness outcome for the most recent completed run.
    pub last_run_outcome: Option<RunOutcome>,
    pub session_tool_call_count: u32,
    /// Consecutive turns where the model emitted an unregistered tool name (Hermes parity).
    pub invalid_tool_call_retries: u32,
    /// True after the first successful context compression in this session.
    ///
    /// FP33: After the first compression fires, we append a one-shot note to
    /// `cached_system_prompt` informing the model that earlier turns have been
    /// compacted.  Subsequent compressions do NOT modify the system prompt so
    /// that Anthropic's prompt cache breakpoints remain stable.
    pub first_compression_done: bool,
}

impl SessionState {
    /// Invalidate prompt cache and inject the handoff brief user message.
    pub(crate) fn apply_model_transfer_outcome(
        &mut self,
        outcome: &crate::model_transfer::ModelTransferOutcome,
    ) {
        self.cached_system_prompt = None;
        self.cached_stable_prompt = None;
        if outcome.compressed {
            self.first_compression_done = true;
        }
        self.messages.push(Message::user(
            &crate::model_transfer::format_model_transfer_user_message(
                &outcome.from_model,
                &outcome.to_model,
                &outcome.brief,
                outcome.compressed,
            ),
        ));
    }
}

/// Lock-free iteration budget — prevents runaway tool loops.
///
/// WHY AtomicU32: The budget is checked on every loop iteration and
/// decremented atomically. No mutex contention on the hot path.
pub struct IterationBudget {
    remaining: AtomicU32,
    max: u32,
}

impl IterationBudget {
    pub fn new(max: u32) -> Self {
        Self {
            remaining: AtomicU32::new(max),
            max,
        }
    }

    /// Try to consume one iteration. Returns false when exhausted.
    pub fn try_consume(&self) -> bool {
        // CAS loop: only decrement if remaining > 0.
        loop {
            let current = self.remaining.load(Ordering::Relaxed);
            if current == 0 {
                return false;
            }
            if self
                .remaining
                .compare_exchange_weak(current, current - 1, Ordering::Relaxed, Ordering::Relaxed)
                .is_ok()
            {
                return true;
            }
        }
    }

    pub fn remaining(&self) -> u32 {
        self.remaining.load(Ordering::Relaxed)
    }

    pub fn max(&self) -> u32 {
        self.max
    }

    pub fn used(&self) -> u32 {
        self.max.saturating_sub(self.remaining())
    }

    pub fn reset(&self) {
        self.remaining.store(self.max, Ordering::Relaxed);
    }
}

/// Result of a full conversation run.
#[derive(Debug, Clone)]
pub struct ConversationResult {
    pub final_response: String,
    pub messages: Vec<Message>,
    pub session_id: String,
    pub api_calls: u32,
    pub interrupted: bool,
    /// True when the iteration budget was exhausted before the LLM produced
    /// a final text response. Distinct from `interrupted` (user Ctrl+C).
    pub budget_exhausted: bool,
    /// Authoritative terminal state for the run.
    pub run_outcome: RunOutcome,
    pub model: String,
    pub usage: Usage,
    pub cost: Cost,
    /// Per-tool-call error records accumulated across the entire conversation.
    ///
    /// Mirrors hermes-agent's `AgentResult.tool_errors: List[ToolError]`.
    /// Each entry captures the turn number, tool name, arguments, and the
    /// error text — enabling structured observability and RL training without
    /// requiring callers to parse raw message history.
    pub tool_errors: Vec<lingshu_types::ToolErrorRecord>,
}

// ─── Simple API ───────────────────────────────────────────────────────

impl Agent {
    fn build_runtime_clone(
        config: AgentConfig,
        provider: Arc<dyn LLMProvider>,
        state_db: Option<Arc<SessionDb>>,
        tool_registry: Option<Arc<ToolRegistry>>,
        context_engine: Option<Arc<dyn crate::context_engine::ContextEngine>>,
        goal_store: Option<Arc<dyn crate::goals::GoalStore>>,
    ) -> Self {
        let budget = Arc::new(IterationBudget::new(config.max_iterations));

        let gc_cancel = CancellationToken::new();
        let process_table = Arc::new(ProcessTable::new());
        process_table.spawn_gc_task(gc_cancel.clone());

        let (steer_tx, steer_rx) = crate::steering::steering_channel();
        let goal_store =
            goal_store.unwrap_or_else(|| crate::goals::goal_store_for_db(state_db.clone()));
        Self {
            config: RwLock::new(config),
            provider: RwLock::new(provider),
            state_db,
            tool_registry: RwLock::new(tool_registry),
            gateway_sender: RwLock::new(None),
            process_table,
            conversation_lock: Mutex::new(()),
            session: RwLock::new(SessionState::default()),
            budget,
            cancel: std::sync::Mutex::new(CancellationToken::new()),
            gc_cancel,
            todo_store: Arc::new(TodoStore::new()),
            goal_store,
            context_engine,
            steer_tx,
            steer_rx: std::sync::Mutex::new(Some(steer_rx)),
            steer_event_tx: std::sync::Mutex::new(None),
            steer_pending: std::sync::atomic::AtomicUsize::new(0),
        }
    }

    /// Simple interface — send a message, get a response string.
    pub async fn chat(&self, message: &str) -> Result<String, AgentError> {
        let result = self.run_conversation(message, None, None).await?;
        Ok(result.final_response)
    }

    /// Session-aware interface — run a turn relative to the provided workspace.
    pub async fn chat_in_cwd(&self, message: &str, cwd: &Path) -> Result<String, AgentError> {
        let result = self
            .run_conversation_in_cwd(message, None, None, cwd)
            .await?;
        Ok(result.final_response)
    }

    /// Inject or replace the gateway-backed outbound sender used by `send_message`.
    pub async fn set_gateway_sender(&self, sender: Arc<dyn GatewaySender>) {
        *self.gateway_sender.write().await = Some(sender);
    }

    /// Toggle the shadow judge completion oracle for this session.
    ///
    /// Safe to call while a conversation is running — the value is read at
    /// the next `LoopAction::Done` decision point, not during the LLM call.
    pub async fn set_shadow_judge_enabled(&self, enabled: bool) {
        self.config.write().await.shadow_judge.enabled = enabled;
    }

    /// Returns the current shadow judge enabled state.
    pub async fn shadow_judge_enabled(&self) -> bool {
        self.config.read().await.shadow_judge.enabled
    }

    /// Gateway interface — send a message with origin context (platform + chat_id).
    ///
    /// Unlike `chat()`, this sets the origin so that `manage_cron_jobs` jobs
    /// created in this session will have deliver='origin' route back to the
    /// correct chat automatically.  Also updates `config.platform` so the
    /// system prompt includes the correct platform hints (WhatsApp, Telegram, etc.).
    pub async fn chat_with_origin(
        &self,
        message: &str,
        platform: &str,
        chat_id: &str,
    ) -> Result<String, AgentError> {
        // Set origin_chat and platform for this conversation turn.
        {
            let mut cfg = self.config.write().await;
            cfg.origin_chat = Some(OriginChat::new(platform, chat_id));
            cfg.platform = platform_from_str(platform).unwrap_or(cfg.platform);
        }
        let result = self.run_conversation(message, None, None).await?;
        {
            // Clear origin after the turn so it isn't stale for the next message.
            let mut cfg = self.config.write().await;
            cfg.origin_chat = None;
        }
        Ok(result.final_response)
    }

    /// Streaming gateway interface — sets origin context, then streams events.
    ///
    /// Combines the origin-context setup of `chat_with_origin()` with the
    /// progressive streaming of `chat_streaming()`.  This is the method the
    /// gateway dispatch loop should call so that:
    /// 1. `manage_cron_jobs` jobs route back to the originating chat.
    /// 2. The system prompt includes the correct platform hints.
    /// 3. Streamed `Token`, `Reasoning`, `ToolExec`, … events reach the caller.
    pub async fn chat_streaming_with_origin(
        &self,
        message: &str,
        platform: &str,
        chat_id: &str,
        chunk_tx: tokio::sync::mpsc::UnboundedSender<StreamEvent>,
    ) -> Result<(), AgentError> {
        // Set origin and platform — identical to chat_with_origin().
        {
            let mut cfg = self.config.write().await;
            cfg.origin_chat = Some(OriginChat::new(platform, chat_id));
            cfg.platform = platform_from_str(platform).unwrap_or(cfg.platform);
        }

        let result = self.chat_streaming(message, chunk_tx).await;

        // Clear origin after the turn regardless of success/failure.
        {
            let mut cfg = self.config.write().await;
            cfg.origin_chat = None;
        }

        result
    }

    /// Streaming interface — sends tokens to `chunk_tx` as they arrive.
    ///
    /// WHY delegate to execute_loop: We want the full ReAct loop (tools,
    /// memory, prompt builder, retries) to remain the single source of truth.
    /// When the provider supports native tool streaming, `execute_loop()` now
    /// emits live token/reasoning events directly. Otherwise we fall back to
    /// streaming the final response in chunks after the synchronous turn ends.
    pub async fn chat_streaming(
        &self,
        message: &str,
        chunk_tx: tokio::sync::mpsc::UnboundedSender<StreamEvent>,
    ) -> Result<(), AgentError> {
        tracing::info!(message_len = message.len(), "chat_streaming: entered");
        let streaming_enabled = {
            let config = self.config.read().await;
            tracing::info!(streaming = config.streaming, model = %config.model, "chat_streaming: config read");
            config.streaming
        };

        let (event_tx, mut event_rx) = tokio::sync::mpsc::unbounded_channel();
        let saw_live_content = Arc::new(AtomicBool::new(false));
        let saw_live_content_forwarder = saw_live_content.clone();
        let chunk_tx_forwarder = chunk_tx.clone();
        let forwarder = tokio::spawn(async move {
            while let Some(event) = event_rx.recv().await {
                if matches!(event, StreamEvent::Token(_) | StreamEvent::Reasoning(_)) {
                    saw_live_content_forwarder.store(true, AtomicOrdering::Relaxed);
                }
                let _ = chunk_tx_forwarder.send(event);
            }
        });

        match self
            .execute_loop(message, None, None, Some(&event_tx), None, None)
            .await
        {
            Ok(result) => {
                drop(event_tx);
                let _ = forwarder.await;
                // Fallback path: provider doesn't expose live deltas through
                // the full tool loop, so synthesize only what the user asked for:
                // - streaming ON  → chunk the final answer for progressive UX
                // - streaming OFF → send one complete answer at the end
                if !saw_live_content.load(AtomicOrdering::Relaxed) {
                    if let Some(reasoning) = result
                        .messages
                        .iter()
                        .rev()
                        .find(|msg| msg.role == Role::Assistant)
                        .and_then(|msg| msg.reasoning.clone())
                        .filter(|reasoning| !reasoning.trim().is_empty())
                    {
                        let _ = chunk_tx.send(StreamEvent::Reasoning(reasoning));
                    }

                    if streaming_enabled {
                        for chunk in result.final_response.as_bytes().chunks(50) {
                            let text = String::from_utf8_lossy(chunk).into_owned();
                            let _ = chunk_tx.send(StreamEvent::Token(text));
                        }
                    } else if !result.final_response.is_empty() {
                        let _ = chunk_tx.send(StreamEvent::Token(result.final_response.clone()));
                    }
                }
                let _ = chunk_tx.send(StreamEvent::Done);
                Ok(())
            }
            Err(e) => {
                drop(event_tx);
                let _ = forwarder.await;
                let _ = chunk_tx.send(StreamEvent::Error(e.to_string()));
                Err(e)
            }
        }
    }

    /// Full conversation interface.
    ///
    /// Delegates to `execute_loop()` (conversation.rs) which implements
    /// the full agent loop with retry, tool dispatch, and cancellation.
    pub async fn run_conversation(
        &self,
        user_message: &str,
        system_message: Option<&str>,
        conversation_history: Option<Vec<Message>>,
    ) -> Result<ConversationResult, AgentError> {
        self.execute_loop(
            user_message,
            system_message,
            conversation_history,
            None,
            None,
            None,
        )
        .await
    }

    /// Full conversation interface with an explicit workspace root.
    pub async fn run_conversation_in_cwd(
        &self,
        user_message: &str,
        system_message: Option<&str>,
        conversation_history: Option<Vec<Message>>,
        cwd: &Path,
    ) -> Result<ConversationResult, AgentError> {
        self.execute_loop(
            user_message,
            system_message,
            conversation_history,
            None,
            Some(cwd),
            None,
        )
        .await
    }

    /// Clone the agent runtime into a fresh isolated session.
    ///
    /// WHY this exists: `/background` and similar workflows need the current
    /// model, provider, tool configuration, and state DB wiring, but must not
    /// share conversation history, process tables, or cancellation state with
    /// the foreground session.
    pub async fn fork_isolated(&self, options: IsolatedAgentOptions) -> Result<Self, AgentError> {
        let profile = options
            .profile
            .as_deref()
            .map(crate::kanban_profiles::normalize_profile_name)
            .filter(|s| !s.is_empty());

        let (mut config, provider, state_db) = if let Some(profile_name) = profile {
            let root = options
                .install_root
                .clone()
                .unwrap_or_else(crate::kanban_profiles::install_root);
            let profile_cfg =
                crate::kanban_profiles::load_config_for_profile(&root, &profile_name)?;
            let model = profile_cfg.model.default_model.clone();
            let provider = if let Some((provider_name, model_name)) = model.split_once('/') {
                let canonical = lingshu_tools::vision_models::normalize_provider_name(provider_name);
                lingshu_tools::create_provider_for_model(&canonical, model_name)
                    .map_err(|e| AgentError::Config(format!("kanban worker provider: {e}")))?
            } else {
                return Err(AgentError::Config(format!(
                    "kanban worker profile '{profile_name}' model must be provider/model form, got '{model}'"
                )));
            };
            let _profile_home =
                crate::kanban_profiles::profile_effective_home(&root, &profile_name);
            let db = Arc::new(
                lingshu_state::SessionDb::open_default()
                    .map_err(|e| AgentError::Database(format!("profile state db: {e}")))?,
            );
            let agent_cfg = AgentBuilder::from_config(&profile_cfg).into_agent_config();
            (agent_cfg, provider, Some(db))
        } else {
            let config = self.config.read().await.clone();
            let provider = self.provider.read().await.clone();
            let state_db = self.state_db.clone();
            (config, provider, state_db)
        };

        let gateway_sender = self.gateway_sender.read().await.clone();

        if let Some(session_id) = options.session_id {
            config.session_id = Some(session_id);
        } else {
            config.session_id = None;
        }
        if let Some(platform) = options.platform {
            config.platform = platform;
        }
        if let Some(quiet_mode) = options.quiet_mode {
            config.quiet_mode = quiet_mode;
        }
        config.origin_chat = options.origin_chat;
        config.kanban_task_id = options.kanban_task_id;
        if config.kanban_task_id.is_some()
            && !config
                .enabled_toolsets
                .iter()
                .any(|t| t.eq_ignore_ascii_case("kanban"))
        {
            config.enabled_toolsets.push("kanban".into());
        }

        let child = Self::build_runtime_clone(
            config,
            provider,
            state_db,
            self.tool_registry.read().await.clone(),
            self.context_engine.clone(),
            None,
        );
        if let Some(sender) = gateway_sender {
            child.set_gateway_sender(sender).await;
        }
        Ok(child)
    }

    /// Signal the agent to stop at the next iteration boundary.
    pub fn interrupt(&self) {
        self.cancel
            .lock()
            .expect("cancel mutex not poisoned")
            .cancel();
    }

    /// Shared background process table (terminal tools, `/tail` panel).
    pub fn process_table(&self) -> Arc<ProcessTable> {
        self.process_table.clone()
    }

    /// Whether the cancellation token has been triggered.
    pub fn is_cancelled(&self) -> bool {
        self.cancel
            .lock()
            .expect("cancel mutex not poisoned")
            .is_cancelled()
    }

    /// Return the sender half of the steering channel.
    ///
    /// The caller (TUI, gateway) stores this sender and calls `send()` to inject
    /// guidance into the running agent loop.  The sender is `Clone`, so multiple
    /// independent senders (main input + steer overlay) can coexist.
    ///
    /// ## Example
    ///
    /// ```ignore
    /// let steer_tx = agent.steer_sender();
    /// steer_tx.send(SteeringEvent::new(SteeringKind::Hint, "focus on auth")).ok();
    /// ```
    pub fn steer_sender(&self) -> crate::steering::SteeringSender {
        self.steer_tx.clone()
    }

    /// Send a steering event and notify streaming clients of the pending count.
    pub fn send_steering(
        &self,
        event: crate::steering::SteeringEvent,
    ) -> Result<(), tokio::sync::mpsc::error::SendError<crate::steering::SteeringEvent>> {
        use std::sync::atomic::Ordering;
        let count = self.steer_pending.fetch_add(1, Ordering::Relaxed) + 1;
        if let Some(tx) = self
            .steer_event_tx
            .lock()
            .expect("steer_event_tx mutex not poisoned")
            .clone()
        {
            let _ = tx.send(crate::StreamEvent::SteerPending { count });
        }
        self.steer_tx.send(event)
    }

    /// Reset session state for a new conversation.
    pub async fn new_session(&self) {
        let previous_session_id = self.session.read().await.session_id.clone();
        let config = self.config.read().await.clone();
        if let Some(session_id) = previous_session_id.as_deref() {
            self.fire_session_boundary_hooks(
                &config,
                "on_session_finalize",
                session_id,
                config.platform,
            )
            .await;
        }

        // Clear the per-session env passthrough registry so stale skill
        // registrations from the previous session don't leak.  Re-register
        // config-level passthrough entries immediately so they remain
        // available for the new session's very first PersistentShell spawn.
        let passthrough = { config.terminal_env_passthrough.clone() };
        lingshu_tools::tools::backends::local::clear_env_passthrough();
        if !passthrough.is_empty() {
            lingshu_tools::tools::backends::local::register_env_passthrough(&passthrough);
        }

        let mut session = self.session.write().await;
        *session = SessionState::default();
        let new_session_id = uuid::Uuid::new_v4().to_string();
        session.session_id = Some(new_session_id.clone());
        self.budget.reset();
        drop(session);

        self.fire_session_boundary_hooks(
            &config,
            "on_session_reset",
            &new_session_id,
            config.platform,
        )
        .await;
    }

    pub async fn finalize_session(&self) {
        let session_id = self.session.read().await.session_id.clone();
        let config = self.config.read().await.clone();
        if let Some(session_id) = session_id.as_deref() {
            self.fire_session_boundary_hooks(
                &config,
                "on_session_finalize",
                session_id,
                config.platform,
            )
            .await;
        }
    }

    /// Hot-swap the LLM model and provider at runtime.
    ///
    /// WHY: The `/model` command needs to switch providers without
    /// restarting the CLI. In-flight conversations are not affected
    /// because `execute_loop()` clones the provider Arc at loop start.
    pub async fn swap_model(&self, model: String, provider: Arc<dyn LLMProvider>) {
        {
            let mut cfg = self.config.write().await;
            cfg.model = model;
        }
        {
            let mut prov = self.provider.write().await;
            *prov = provider;
        }
    }

    /// Instant model switch — Hermes `/model` parity (no brief, no auxiliary LLM).
    pub async fn switch_model_fast(
        &self,
        target_spec: &str,
    ) -> Result<crate::model_transfer::ModelSwitchOutcome, crate::model_transfer::ModelTransferError>
    {
        use crate::model_catalog::ModelCatalog;
        use crate::model_transfer::{
            ModelSwitchOutcome, create_model_transfer_provider, resolve_model_transfer_target,
        };

        let target = resolve_model_transfer_target(target_spec)?;
        let current_model = self.config.read().await.model.clone();
        if ModelCatalog::equivalent_model_specs(&target.display, &current_model) {
            return Err(crate::model_transfer::ModelTransferError::SameModel);
        }
        let provider = create_model_transfer_provider(&target)?;
        self.swap_model(target.display.clone(), provider).await;

        if let Some(db) = &self.state_db
            && let Some(session_id) = self.session.read().await.session_id.as_deref()
            && let Err(err) = db.update_session_model(session_id, &target.display).await
        {
            tracing::warn!(error = %err, "fast model switch session DB update failed");
        }

        Ok(ModelSwitchOutcome {
            from_model: current_model,
            to_model: target.display,
        })
    }

    /// Transfer the live session to another model with brief + window check.
    ///
    /// Used by `/transfer-model` in CLI and gateway. For instant hot-swap use
    /// [`switch_model_fast`](Self::switch_model_fast) (`/model`).
    pub async fn perform_model_transfer(
        &self,
        target_model: &str,
        events: Option<tokio::sync::mpsc::UnboundedSender<StreamEvent>>,
    ) -> Result<
        crate::model_transfer::ModelTransferOutcome,
        crate::model_transfer::ModelTransferError,
    > {
        let (compression_cfg, auxiliary_model, current_model, main_provider) = {
            let cfg = self.config.read().await;
            (
                cfg.compression.clone(),
                cfg.auxiliary.model.clone(),
                cfg.model.clone(),
                self.provider.read().await.clone(),
            )
        };

        let (outcome, new_provider) = {
            let mut session = self.session.write().await;
            let system_prompt = session.cached_system_prompt.clone();
            let mut ctx = crate::model_transfer::ModelTransferContext {
                current_model: &current_model,
                messages: &mut session.messages,
                system_prompt: system_prompt.as_deref(),
                compression_cfg: &compression_cfg,
                main_provider,
                auxiliary_model: auxiliary_model.as_deref(),
            };
            let (outcome, new_provider) =
                crate::model_transfer::ModelTransferOrchestrator::execute(&mut ctx, target_model)
                    .await?;

            session.apply_model_transfer_outcome(&outcome);

            (outcome, new_provider)
        };

        self.swap_model(outcome.to_model.clone(), new_provider)
            .await;

        if outcome.compressed
            && let Some(session_id) = self.session.read().await.session_id.as_deref()
        {
            // FP17: compression discards prior read_file results — same reset as in-loop compression.
            lingshu_tools::read_tracker::reset_read_dedup(session_id);
        }

        if let Some(db) = &self.state_db
            && let Some(session_id) = self.session.read().await.session_id.as_deref()
        {
            if let Err(err) = db.update_session_model(session_id, &outcome.to_model).await {
                tracing::warn!(error = %err, "handoff session model DB update failed");
            }
            if let Err(err) = db.record_model_transfer(
                session_id,
                &outcome.from_model,
                &outcome.to_model,
                &outcome.brief,
            ).await {
                tracing::warn!(error = %err, "handoff DB record failed");
            }
        }

        if let Some(tx) = events {
            let _ = tx.send(StreamEvent::ModelTransferComplete {
                from: outcome.from_model.clone(),
                to: outcome.to_model.clone(),
                brief: outcome.brief.clone(),
                compressed: outcome.compressed,
            });
        }

        Ok(outcome)
    }

    /// Get the current model name.
    pub async fn model(&self) -> String {
        self.config.read().await.model.clone()
    }

    async fn fire_session_boundary_hooks(
        &self,
        config: &AgentConfig,
        hook_name: &str,
        session_id: &str,
        platform: Platform,
    ) {
        let Ok(discovery) = discover_plugins(&config.plugins_config, platform) else {
            return;
        };
        for plugin in discovery
            .plugins
            .iter()
            .filter(|plugin| hermes_supports_hook(plugin, hook_name))
        {
            if let Err(error) = invoke_hermes_hook(
                plugin,
                hook_name,
                serde_json::json!({
                    "session_id": session_id,
                    "platform": platform.to_string(),
                }),
            )
            .await
            {
                tracing::warn!(plugin = %plugin.name, ?error, hook = hook_name, "Hermes session-boundary hook failed");
            }
        }
    }

    /// Snapshot of live session stats for `/status`, `/cost`, `/history` commands.
    pub async fn session_snapshot(&self) -> SessionSnapshot {
        let session = self.session.read().await;
        let config = self.config.read().await;
        SessionSnapshot {
            session_id: session.session_id.clone(),
            model: config.model.clone(),
            message_count: session.messages.len(),
            user_turn_count: session.user_turn_count,
            api_call_count: session.api_call_count,
            input_tokens: session.session_input_tokens,
            output_tokens: session.session_output_tokens,
            cache_read_tokens: session.session_cache_read_tokens,
            cache_write_tokens: session.session_cache_write_tokens,
            reasoning_tokens: session.session_reasoning_tokens,
            last_prompt_tokens: session.last_prompt_tokens,
            budget_remaining: self.budget.remaining(),
            budget_max: self.budget.max(),
        }
    }

    /// Best-effort synchronous snapshot accessor for non-async inspection paths.
    pub fn try_session_snapshot(&self) -> Option<SessionSnapshot> {
        let session = self.session.try_read().ok()?;
        let config = self.config.try_read().ok()?;
        Some(SessionSnapshot {
            session_id: session.session_id.clone(),
            model: config.model.clone(),
            message_count: session.messages.len(),
            user_turn_count: session.user_turn_count,
            api_call_count: session.api_call_count,
            input_tokens: session.session_input_tokens,
            output_tokens: session.session_output_tokens,
            cache_read_tokens: session.session_cache_read_tokens,
            cache_write_tokens: session.session_cache_write_tokens,
            reasoning_tokens: session.session_reasoning_tokens,
            last_prompt_tokens: session.last_prompt_tokens,
            budget_remaining: self.budget.remaining(),
            budget_max: self.budget.max(),
        })
    }

    /// Get the currently assembled system prompt (if cached).
    pub async fn system_prompt(&self) -> Option<String> {
        self.session.read().await.cached_system_prompt.clone()
    }

    /// Terminal outcome for the most recent completed run, if any.
    pub async fn last_run_outcome(&self) -> Option<RunOutcome> {
        self.session.read().await.last_run_outcome.clone()
    }

    pub async fn custom_system_prompt(&self) -> Option<String> {
        self.config.read().await.custom_system_prompt.clone()
    }

    /// Publish the latest local turn snapshot back into shared session state.
    ///
    /// WHY whole-state replace: execute_loop now owns a local SessionState copy
    /// so expensive work happens lock-free. Publishing the full snapshot keeps
    /// read paths coherent without re-introducing field-by-field lock churn.
    pub(crate) async fn publish_session_state(&self, session: &SessionState) {
        *self.session.write().await = session.clone();
    }

    /// Append a note to the cached system prompt.
    ///
    /// Used to inject runtime context (e.g. "browser is now connected to live
    /// Chrome") without consuming a full user→model conversation turn.
    /// The note is appended once; callers should guard for idempotency.
    /// If the system prompt hasn't been built yet it will be set as the full
    /// prompt at first-turn assembly time and this note will be ignored — the
    /// note is silently discarded rather than force-building the prompt early.
    pub async fn append_to_system_prompt(&self, note: &str) {
        let mut session = self.session.write().await;
        if let Some(ref mut prompt) = session.cached_system_prompt {
            prompt.push_str("\n\n");
            prompt.push_str(note);
        }
        // If the system prompt isn't cached yet (no messages sent) we store the
        // note in a pending field so it can be appended at build time.
        // For simplicity we skip that path — callers send /browser connect after
        // the first message, so the prompt is already cached.
    }

    pub async fn invalidate_system_prompt(&self) {
        let mut session = self.session.write().await;
        session.cached_system_prompt = None;
        session.cached_stable_prompt = None;
    }

    pub async fn set_personality_addon(&self, addon: Option<String>) {
        {
            let mut config = self.config.write().await;
            config.personality_addon = addon;
        }
        self.invalidate_system_prompt().await;
    }

    pub async fn set_custom_system_prompt(&self, prompt: Option<String>) {
        {
            let mut config = self.config.write().await;
            config.custom_system_prompt = prompt.and_then(|value| {
                let trimmed = value.trim();
                (!trimmed.is_empty()).then_some(trimmed.to_string())
            });
        }
        self.invalidate_system_prompt().await;
    }

    pub async fn preloaded_skills(&self) -> Vec<String> {
        self.config.read().await.skills_config.preloaded.clone()
    }

    pub fn preloaded_skills_snapshot(&self) -> Vec<String> {
        self.config
            .try_read()
            .map(|config| config.skills_config.preloaded.clone())
            .unwrap_or_default()
    }

    pub async fn set_preloaded_skills(&self, skills: Vec<String>) {
        {
            let mut config = self.config.write().await;
            config.skills_config.preloaded = skills;
        }
        self.invalidate_system_prompt().await;
    }

    /// Inject a synthetic assistant message directly into the conversation history.
    ///
    /// Used after runtime context changes (e.g. `/browser connect`) to make the
    /// model "remember" that its capabilities changed, overriding any prior turns
    /// where it claimed not to have those capabilities.  The injected message is
    /// NOT sent to the LLM — it appears in the history context that the LLM reads
    /// on the NEXT real user turn.
    pub async fn inject_assistant_context(&self, text: &str) {
        let mut session = self.session.write().await;
        session.messages.push(Message::assistant(text));
    }

    /// Get full message history for export.
    pub async fn messages(&self) -> Vec<Message> {
        self.session.read().await.messages.clone()
    }

    /// Best-effort synchronous message accessor for non-async inspection paths.
    pub fn try_messages(&self) -> Option<Vec<Message>> {
        Some(self.session.try_read().ok()?.messages.clone())
    }

    /// Remove the last user + assistant turn from history (undo).
    /// Returns the number of messages removed (0 if history is empty).
    pub async fn undo_last_turn(&self) -> usize {
        let mut session = self.session.write().await;
        let mut removed = 0;
        // Walk backwards: remove assistant/tool messages, then the user message.
        while let Some(m) = session.messages.last() {
            if m.role == Role::User {
                session.messages.pop();
                removed += 1;
                break;
            }
            session.messages.pop();
            removed += 1;
        }
        removed
    }

    /// Force context compression on the next turn.
    pub async fn force_compress(&self) {
        let provider = self.provider.read().await.clone();
        let config = self.config.read().await.clone();
        let mut session = self.session.write().await;
        let params = crate::compression::CompressionParams::from_model_config(
            &config.model,
            &config.compression,
        );
        // Pass None for spill context in force_compress — this is a manual /compress
        // command and we don't have a cwd/session_id readily available. Tool results
        // are still pruned with the generic placeholder, which is fine for /compress.
        let (compressed, _llm_succeeded) =
            crate::compression::compress_with_llm(&session.messages, &params, &provider, None)
                .await;
        session.messages = compressed;
    }

    /// Set the session title (persisted on next DB write).
    pub async fn set_session_title(&self, title: String) {
        let session = self.session.read().await;
        if let (Some(db), Some(sid)) = (&self.state_db, &session.session_id) {
            let _ = db.update_session_title(sid, &title).await;
        }
    }

    async fn ensure_session_id(&self) -> Result<String, AgentError> {
        let session_id = {
            let mut session = self.session.write().await;
            if session.session_id.is_none() {
                session.session_id = Some(uuid::Uuid::new_v4().to_string());
            }
            session
                .session_id
                .clone()
                .expect("session_id initialized above")
        };

        if let Some(db) = &self.state_db {
            let config = self.config.read().await;
            let (source, user_id) = match &config.origin_chat {
                Some(origin) => (origin.platform.clone(), Some(origin.chat_id.clone())),
                None => (config.platform.to_string(), None),
            };
            db.ensure_session_row(
                &session_id,
                &source,
                user_id.as_deref(),
                Some(config.model.as_str()),
            ).await?;
        }

        Ok(session_id)
    }

    /// Ensure the session row exists in SQLite (for platform `/handoff`).
    pub async fn ensure_persisted_session(&self) -> Result<String, AgentError> {
        self.ensure_session_id().await
    }

    /// Set or replace the persistent top-level goal for the current session.
    pub async fn goal_set(&self, text: &str) -> Result<String, AgentError> {
        let session_id = self.ensure_session_id().await?;
        let max_turns = self.config.read().await.goals.max_turns.max(1);
        self.goal_store.set_goal(&session_id, text, max_turns)?;
        Ok(format!(
            "⊙ Goal set ({max_turns}-turn budget): {}\n\
             After each turn, a judge model checks if the goal is done. \
             Lingshu keeps working until it is, you pause/clear it, or the budget is exhausted.",
            text.trim()
        ))
    }

    /// Display status for the active goal (Hermes-compatible `/goal status`).
    pub async fn goal_status(&self) -> Result<String, AgentError> {
        let session_id = self.ensure_session_id().await?;
        let state = self.goal_store.active(&session_id)?;
        if state.is_empty() {
            return Ok(crate::goals::status_line(&state));
        }
        if state.subgoals.is_empty() {
            return Ok(crate::goals::status_line(&state));
        }
        Ok(format!(
            "{}\n{}",
            crate::goals::status_line(&state),
            crate::goals::render_subgoals_list(&state)
        ))
    }

    /// Raw goal state for UI surfaces (status bar chip, etc.).
    pub async fn goal_state(&self) -> Result<crate::goals::GoalState, AgentError> {
        let session_id = self.ensure_session_id().await?;
        self.goal_store.active(&session_id)
    }

    /// Resume a paused goal loop and return an optional auto-continuation prompt.
    pub async fn goal_resume_with_kickoff(&self) -> Result<(String, Option<String>), AgentError> {
        let session_id = self.ensure_session_id().await?;
        let state = self.goal_store.active(&session_id)?;
        if state.is_empty() {
            return Ok(("No goal to resume.".into(), None));
        }
        self.goal_store.resume(&session_id, true)?;
        let refreshed = self.goal_store.active(&session_id)?;
        let continuation = crate::goals::next_continuation_prompt(&refreshed);
        let msg = format!(
            "▶ Goal resumed: {}",
            refreshed.goal_text.as_deref().unwrap_or("")
        );
        Ok((msg, continuation))
    }

    /// Display the active goal block (injection preview).
    pub async fn goal_show(&self) -> Result<String, AgentError> {
        let session_id = self.ensure_session_id().await?;
        let state = self.goal_store.active(&session_id)?;
        if state.is_empty() {
            return Ok("No active goal. Use /goal <text> to set one.".into());
        }
        Ok(crate::goals::render_goal_block(&state))
    }

    /// Clear all goals for the current session.
    pub async fn goal_clear(&self) -> Result<String, AgentError> {
        let session_id = self.ensure_session_id().await?;
        let had = !self.goal_store.active(&session_id)?.is_empty();
        self.goal_store.clear(&session_id)?;
        Ok(if had {
            "✓ Goal cleared.".into()
        } else {
            "No active goal.".into()
        })
    }

    /// Pause the Ralph loop for the current session.
    pub async fn goal_pause(&self) -> Result<String, AgentError> {
        let session_id = self.ensure_session_id().await?;
        let state = self.goal_store.active(&session_id)?;
        if state.is_empty() {
            return Ok("No goal set.".into());
        }
        self.goal_store.pause(&session_id, "user-paused")?;
        Ok(format!(
            "⏸ Goal paused: {}",
            state.goal_text.as_deref().unwrap_or("")
        ))
    }

    /// Resume a paused goal loop.
    pub async fn goal_resume(&self) -> Result<String, AgentError> {
        let session_id = self.ensure_session_id().await?;
        let state = self.goal_store.active(&session_id)?;
        if state.is_empty() {
            return Ok("No goal to resume.".into());
        }
        self.goal_store.resume(&session_id, true)?;
        Ok(format!(
            "▶ Goal resumed: {}",
            state.goal_text.as_deref().unwrap_or("")
        ))
    }

    /// Push a subgoal onto the current goal stack.
    pub async fn subgoal_push(&self, text: &str) -> Result<String, AgentError> {
        let session_id = self.ensure_session_id().await?;
        self.goal_store.push_subgoal(&session_id, text)?;
        Ok(format!("📌 Subgoal added: {}", text.trim()))
    }

    /// List subgoals for the active goal.
    pub async fn subgoal_list(&self) -> Result<String, AgentError> {
        let session_id = self.ensure_session_id().await?;
        let state = self.goal_store.active(&session_id)?;
        if !state.has_goal() {
            return Ok("No active goal. Set one with /goal <text>.".into());
        }
        Ok(format!(
            "{}\n{}",
            crate::goals::status_line(&state),
            crate::goals::render_subgoals_list(&state)
        ))
    }

    /// Remove a subgoal by 1-based index.
    pub async fn subgoal_remove(&self, index_1based: usize) -> Result<String, AgentError> {
        let session_id = self.ensure_session_id().await?;
        let removed = self.goal_store.remove_subgoal(&session_id, index_1based)?;
        Ok(format!("Removed subgoal #{index_1based}: {removed}"))
    }

    /// Clear all subgoals while keeping the top-level goal.
    pub async fn subgoal_clear(&self) -> Result<String, AgentError> {
        let session_id = self.ensure_session_id().await?;
        let prev = self.goal_store.clear_subgoals(&session_id)?;
        Ok(format!("Cleared {prev} subgoal(s)."))
    }

    /// Mark the most recently pushed incomplete subgoal as done.
    pub async fn subgoal_done(&self) -> Result<String, AgentError> {
        let session_id = self.ensure_session_id().await?;
        match self.goal_store.complete_subgoal(&session_id)? {
            Some(sub) => Ok(format!("✅ Subgoal done: {}", sub.text)),
            None => Ok("No incomplete subgoals to mark done.".into()),
        }
    }

    /// True when the session has an active Ralph-loop goal.
    pub async fn goal_is_active(&self) -> Result<bool, AgentError> {
        let session_id = self.ensure_session_id().await?;
        let state = self.goal_store.active(&session_id)?;
        Ok(state.status == crate::goals::GoalStatus::Active && state.has_goal())
    }

    /// Run the goal judge after a completed turn and return continuation decision.
    pub async fn goal_evaluate_after_turn(
        &self,
        last_response: &str,
        interrupted: bool,
    ) -> Result<crate::goals::GoalContinuationDecision, AgentError> {
        let session_id = self.ensure_session_id().await?;
        let cfg = self.config.read().await.clone();
        let provider = self.provider.read().await.clone();
        let model = cfg.model.clone();
        crate::goals::evaluate_goal_after_turn(
            self.goal_store.clone(),
            &session_id,
            last_response,
            interrupted,
            &cfg.goals,
            &cfg.auxiliary.goal_judge,
            cfg.auxiliary.model.as_deref(),
            provider,
            &model,
        )
        .await
    }

    /// Access the goal store (for tests and gateway wiring).
    pub fn goal_store(&self) -> Arc<dyn crate::goals::GoalStore> {
        self.goal_store.clone()
    }

    /// Restore a persisted session from the state DB into the live session state.
    pub async fn restore_session(&self, id: &str) -> Result<usize, AgentError> {
        let db = self
            .state_db
            .as_ref()
            .ok_or_else(|| AgentError::Config("No state database configured".into()))?;

        let record = db
            .get_session(id).await?
            .ok_or_else(|| AgentError::Config(format!("Session not found: {id}")))?;
        let messages = db.get_messages(id).await?;

        {
            let mut session = self.session.write().await;
            session.session_id = Some(record.id.clone());
            session.cached_system_prompt = record.system_prompt.clone();
            session.user_turn_count = messages
                .iter()
                .filter(|m| matches!(m.role, lingshu_types::Role::User))
                .count() as u32;
            session.api_call_count = 0;
            session.session_input_tokens = record.input_tokens.max(0) as u64;
            session.session_output_tokens = record.output_tokens.max(0) as u64;
            session.session_cache_read_tokens = record.cache_read_tokens.max(0) as u64;
            session.session_cache_write_tokens = record.cache_write_tokens.max(0) as u64;
            session.session_reasoning_tokens = record.reasoning_tokens.max(0) as u64;
            session.last_prompt_tokens = 0;
            session.messages = messages;
        }

        if let Some(model) = record.model {
            let mut config = self.config.write().await;
            config.model = model;
        }
        self.budget.reset();

        Ok(self.session.read().await.messages.len())
    }

    /// List persisted sessions (delegates to SessionDb).
    pub async fn list_sessions(
        &self,
        limit: usize,
    ) -> Result<Vec<lingshu_state::SessionSummary>, AgentError> {
        match &self.state_db {
            Some(db) => db.list_sessions(limit).await,
            None => Ok(Vec::new()),
        }
    }

    /// Delete a persisted session by ID (delegates to SessionDb).
    pub async fn delete_session(&self, id: &str) -> Result<(), AgentError> {
        match &self.state_db {
            Some(db) => db.delete_session(id).await,
            None => Err(AgentError::Config("No state database configured".into())),
        }
    }

    /// Rename a persisted session (set or change its title).
    pub async fn rename_session(&self, id: &str, title: &str) -> Result<(), AgentError> {
        match &self.state_db {
            Some(db) => db.update_session_title(id, title).await,
            None => Err(AgentError::Config("No state database configured".into())),
        }
    }

    /// Prune old ended sessions. Returns the number of sessions deleted.
    pub async fn prune_sessions(
        &self,
        older_than_days: u32,
        source: Option<&str>,
    ) -> Result<usize, AgentError> {
        match &self.state_db {
            Some(db) => db.prune_sessions(older_than_days, source).await,
            None => Ok(0),
        }
    }

    /// Check if a state database is configured.
    pub fn has_state_db(&self) -> bool {
        self.state_db.is_some()
    }

    /// Return a clone of the state DB handle, if configured.
    pub fn state_db_handle(&self) -> Option<Arc<SessionDb>> {
        self.state_db.clone()
    }

    /// Return a clone of the current provider handle.
    ///
    /// Used by the gateway for deterministic pre-processing steps such as
    /// eager image analysis before the conversation turn starts.
    pub async fn provider_handle(&self) -> Arc<dyn LLMProvider> {
        self.provider.read().await.clone()
    }

    /// Return a clone of the current auxiliary side-task routing config.
    pub async fn auxiliary_config(&self) -> crate::config::AuxiliaryConfig {
        self.config.read().await.auxiliary.clone()
    }

    /// Return the current smart-routing configuration for future turns.
    pub async fn smart_routing_config(&self) -> crate::config::SmartRoutingYaml {
        self.config.read().await.model_config.smart_routing.clone()
    }

    /// Return the current Mixture-of-Agents defaults for future tool calls.
    pub async fn moa_config(&self) -> crate::config::MoaConfig {
        self.config.read().await.moa.clone()
    }

    /// Return the current voice/media configuration used by direct tools.
    pub async fn media_config(
        &self,
    ) -> (
        crate::config::TtsConfig,
        crate::config::SttConfig,
        crate::config::ImageGenerationConfig,
    ) {
        let config = self.config.read().await;
        (
            config.tts.clone(),
            config.stt.clone(),
            config.image_generation.clone(),
        )
    }

    /// List all registered tool names.
    pub async fn tool_names(&self) -> Vec<String> {
        match self.tool_registry.read().await.as_ref() {
            Some(reg) => reg
                .tool_names()
                .into_iter()
                .map(|s| s.to_string())
                .collect(),
            None => Vec::new(),
        }
    }

    /// List toolsets with their tool counts.
    pub async fn toolset_summary(&self) -> Vec<(String, usize)> {
        match self.tool_registry.read().await.as_ref() {
            Some(reg) => reg.toolset_summary(),
            None => Vec::new(),
        }
    }

    /// Rich tool inventory for UI selectors and diagnostics.
    pub async fn tool_inventory(&self) -> Vec<ToolInventoryEntry> {
        let registry = self.tool_registry.read().await.clone();
        let Some(registry) = registry else {
            return Vec::new();
        };
        let config = self.config.read().await.clone();
        let tool_policy = resolve_tool_policy(&config);
        let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
        let ctx = lingshu_tools::registry::ToolContext {
            task_id: "tool-inventory".into(),
            cwd,
            session_id: config
                .session_id
                .clone()
                .unwrap_or_else(|| "tool-inventory".into()),
            user_task: None,
            cancel: CancellationToken::new(),
            config: config
                .to_app_config_ref(self.gateway_sender.read().await.is_some(), &tool_policy),
            state_db: self.state_db.clone(),
            platform: config.platform,
            process_table: Some(self.process_table.clone()),
            provider: Some(self.provider.read().await.clone()),
            tool_registry: Some(registry.clone()),
            delegate_depth: 0,
            delegate_agent_id: None,
            delegate_parent_id: None,
            sub_agent_runner: None,
            delegation_event_tx: None,
            clarify_tx: None,
            approval_tx: None,
            on_skills_changed: None,
            gateway_sender: self.gateway_sender.read().await.clone(),
            origin_chat: config.origin_chat.clone(),
            session_key: config.session_id.clone(),
            todo_store: Some(self.todo_store.clone()),
            current_tool_call_id: None,
            current_tool_name: None,
            injected_messages: None,
            tool_progress_tx: None,
            watch_notification_tx: None,
            mutation_turn: None,
            lsp_gate: None,
            kanban_task_id: config.kanban_task_id.clone(),
        };
        registry.tool_inventory(&ctx)
    }

    /// Hot-swap the runtime tool registry for future turns.
    pub async fn set_tool_registry(&self, registry: Arc<ToolRegistry>) {
        *self.tool_registry.write().await = Some(registry);
    }

    /// Update the plugins config used by runtime tool gating.
    pub async fn set_plugins_config(&self, plugins_config: lingshu_plugins::PluginsConfig) {
        let mut config = self.config.write().await;
        config.plugins_config = plugins_config;
    }

    /// Set reasoning effort on the agent config.
    pub async fn set_reasoning_effort(&self, level: Option<String>) {
        let mut config = self.config.write().await;
        config.reasoning_effort = level;
    }

    /// Enable or disable live token streaming for future turns.
    pub async fn set_streaming(&self, enabled: bool) {
        let mut config = self.config.write().await;
        config.streaming = enabled;
        config.model_config.streaming = enabled;
    }

    /// Update auxiliary side-task routing for future turns.
    pub async fn set_auxiliary_config(&self, auxiliary: crate::config::AuxiliaryConfig) {
        let mut config = self.config.write().await;
        config.auxiliary = auxiliary;
    }

    /// Update dangerous-command approval policy for future tool turns.
    pub async fn set_approvals_config(&self, approvals: crate::config::ApprovalsConfig) {
        let mut config = self.config.write().await;
        config.approvals_config = approvals;
    }

    /// Update kanban board settings for future tool turns.
    pub async fn set_kanban_config(&self, kanban: crate::config::KanbanConfig) {
        let mut config = self.config.write().await;
        config.kanban_config = kanban;
    }

    /// Update smart routing for future turns.
    pub async fn set_smart_routing_config(&self, smart_routing: crate::config::SmartRoutingYaml) {
        let mut config = self.config.write().await;
        config.model_config.smart_routing = smart_routing;
    }

    /// Update the default image generation routing for future turns.
    pub async fn set_image_generation_config(
        &self,
        image_generation: crate::config::ImageGenerationConfig,
    ) {
        let mut config = self.config.write().await;
        config.image_generation = image_generation;
    }

    /// Update the default Mixture-of-Agents roster and aggregator.
    pub async fn set_moa_config(&self, moa: crate::config::MoaConfig) {
        let mut config = self.config.write().await;
        config.moa = moa.sanitized();
    }

    /// Refresh in-memory `web_search` from disk after `/web` chain edits.
    ///
    /// Tool dispatch already reads the on-disk chain via [`effective_web_search_config`];
    /// this keeps the agent snapshot aligned for diagnostics and future turns.
    pub async fn reload_web_search_from_disk(&self) {
        let path = crate::config::lingshu_home().join("config.yaml");
        let loaded = if path.is_file() {
            crate::config::AppConfig::load_from(&path)
                .map(|cfg| cfg.web_search)
                .unwrap_or_default()
        } else {
            crate::config::WebSearchConfig::default()
        };
        let mut config = self.config.write().await;
        config.web_search = loaded;
    }

    /// Current LSP configuration (post-write diagnostics gate + language servers).
    pub async fn lsp_config(&self) -> crate::config::LspConfig {
        self.config.read().await.lsp.clone()
    }

    /// Enable or disable the LSP layer for future tool calls in this session.
    pub async fn set_lsp_enabled(&self, enabled: bool) {
        let mut config = self.config.write().await;
        config.lsp.enabled = enabled;
    }

    /// Enable or disable computer_use for future tool calls in this session.
    pub async fn set_computer_use_enabled(&self, enabled: bool) {
        let mut config = self.config.write().await;
        config.computer_use_enabled = enabled;
        if enabled
            && !config
                .enabled_toolsets
                .iter()
                .any(|name| name.eq_ignore_ascii_case("computer_use"))
        {
            config.enabled_toolsets.push("computer_use".to_string());
        }
    }

    /// Update the enabled/disabled toolset filters for future turns.
    pub async fn set_toolset_filters(&self, enabled: Vec<String>, disabled: Vec<String>) {
        let mut config = self.config.write().await;
        config.enabled_toolsets = enabled;
        config.disabled_toolsets = disabled;
    }

    /// Update the tool and toolset filters for future turns.
    pub async fn set_tool_filters(
        &self,
        enabled_toolsets: Vec<String>,
        disabled_toolsets: Vec<String>,
        enabled_tools: Vec<String>,
        disabled_tools: Vec<String>,
    ) {
        let mut config = self.config.write().await;
        config.enabled_toolsets = enabled_toolsets;
        config.disabled_toolsets = disabled_toolsets;
        config.enabled_tools = enabled_tools;
        config.disabled_tools = disabled_tools;
    }

    /// Current enabled/disabled toolset filters used for schema resolution.
    pub async fn toolset_filters(&self) -> (Vec<String>, Vec<String>) {
        let config = self.config.read().await;
        (
            config.enabled_toolsets.clone(),
            config.disabled_toolsets.clone(),
        )
    }

    /// Current tool and toolset filters used for schema resolution.
    pub async fn tool_filters(&self) -> (Vec<String>, Vec<String>, Vec<String>, Vec<String>) {
        let config = self.config.read().await;
        (
            config.enabled_toolsets.clone(),
            config.disabled_toolsets.clone(),
            config.enabled_tools.clone(),
            config.disabled_tools.clone(),
        )
    }
}

/// Read-only snapshot of current session state for display.
#[derive(Debug, Clone)]
pub struct SessionSnapshot {
    pub session_id: Option<String>,
    pub model: String,
    pub message_count: usize,
    pub user_turn_count: u32,
    pub api_call_count: u32,
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub cache_read_tokens: u64,
    pub cache_write_tokens: u64,
    pub reasoning_tokens: u64,
    pub last_prompt_tokens: u64,
    pub budget_remaining: u32,
    pub budget_max: u32,
}

impl SessionSnapshot {
    pub fn prompt_tokens(&self) -> u64 {
        self.input_tokens + self.cache_read_tokens + self.cache_write_tokens
    }

    pub fn total_tokens(&self) -> u64 {
        self.prompt_tokens() + self.output_tokens + self.reasoning_tokens
    }

    pub fn context_pressure_tokens(&self) -> u64 {
        // Return the per-call context size — how much of the context window
        // the current conversation occupies.  This is set from the last
        // API response's prompt_tokens + cache_hit_tokens, or from a
        // character-count estimate when the provider omits usage data.
        //
        // We intentionally do NOT fall back to the cumulative
        // session_input_tokens counter here: that counter grows by
        // prompt_tokens on every turn and would roughly double (or more)
        // across a multi-turn conversation, which is the wrong signal for
        // "how full is the context window right now?".
        self.last_prompt_tokens
    }
}

/// Risk-graduated approval choices surfaced by `StreamEvent::Approval`.
///
/// - `Once`    — approve this specific invocation only.
/// - `Session` — approve all identical commands for the rest of the session.
/// - `Always`  — persist approval to disk so future sessions skip the dialog.
/// - `Deny`    — refuse; the agent should not execute the command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApprovalChoice {
    Once,
    Session,
    Always,
    Deny,
}

/// Events sent from the streaming agent to the TUI.
///
/// WHY an enum: The channel carries multiple event types — partial
/// tokens, completion signal, and errors. A single `String` channel
/// can't distinguish done from error, forcing consumers to use
/// sentinel strings (fragile). An enum is explicit and exhaustive.
pub enum StreamEvent {
    /// A partial response token/chunk.
    Token(String),
    /// A reasoning / think-mode chunk.
    Reasoning(String),
    /// The model is streaming a tool call before arguments are complete.
    ToolGenerating {
        /// Stable tool call id from the LLM tool invocation (or stream placeholder).
        tool_call_id: String,
        /// Tool name being drafted (e.g. "terminal")
        name: String,
        /// Partial JSON arguments accumulated so far.
        partial_args: String,
    },
    /// A tool execution has started.
    ToolExec {
        /// Stable tool call id from the LLM tool invocation.
        tool_call_id: String,
        /// Tool name (e.g. "web_search")
        name: String,
        /// Raw JSON arguments string (for preview extraction in the TUI)
        args_json: String,
    },
    /// A tool surfaced an intermediate progress update.
    ToolProgress {
        /// Stable tool call id from the LLM tool invocation.
        tool_call_id: String,
        /// Tool name (e.g. "moa")
        name: String,
        /// Human-readable progress message for the active invocation.
        message: String,
    },
    /// A tool execution has completed.
    ToolDone {
        /// Stable tool call id from the LLM tool invocation.
        tool_call_id: String,
        /// Tool name (e.g. "web_search")
        name: String,
        /// Raw JSON arguments string (for preview extraction in the TUI)
        args_json: String,
        /// Short machine-generated summary of the tool outcome.
        result_preview: Option<String>,
        /// Elapsed milliseconds
        duration_ms: u64,
        /// Whether the result looks like an error
        is_error: bool,
    },
    /// A delegated child agent has started.
    SubAgentStart {
        task_index: usize,
        task_count: usize,
        goal: String,
        /// Delegation depth from parent agent (1 = first-level delegate).
        depth: u32,
        /// Stable subagent id for tree grouping / replay.
        agent_id: String,
        /// Parent subagent id when nested; `None` for top-level spawns.
        parent_id: Option<String>,
    },
    /// A delegated child agent surfaced intermediate reasoning text.
    SubAgentReasoning {
        task_index: usize,
        task_count: usize,
        text: String,
    },
    /// A delegated child agent called a tool.
    SubAgentToolExec {
        task_index: usize,
        task_count: usize,
        name: String,
        args_json: String,
    },
    /// A delegated child agent has finished.
    SubAgentFinish {
        task_index: usize,
        task_count: usize,
        status: String,
        duration_ms: u64,
        summary: String,
        api_calls: u32,
        model: Option<String>,
    },
    /// The run has finished and the harness has assessed the terminal state.
    RunFinished { outcome: RunOutcome },
    /// Per-turn file-mutation footer (success log and/or failure advisory).
    Footer(String),
    /// The response transport is complete.
    Done,
    /// An error occurred — the response is incomplete.
    Error(String),
    /// The agent needs a clarifying answer from the user.
    /// The caller must send the answer to `response_tx` to unblock the agent.
    Clarify {
        question: String,
        /// Up to 4 predefined answer choices, or None for open-ended.
        choices: Option<Vec<String>>,
        response_tx: tokio::sync::oneshot::Sender<String>,
    },
    /// The agent is requesting approval before executing a potentially risky command.
    ///
    /// The caller presents a risk-graduated dialog (once / session / always / deny)
    /// and sends the user's `ApprovalChoice` to `response_tx` to unblock the agent.
    /// When `deny` is chosen the agent should abort the tool execution.
    Approval {
        /// Short human-readable description of the action to be approved.
        command: String,
        /// Full command string (may be >70 chars; "view" expands this in the TUI).
        full_command: String,
        /// Concrete policy reasons that caused the approval gate to trigger.
        reasons: Vec<String>,
        /// Channel to send the user's choice back to the agent.
        response_tx: tokio::sync::oneshot::Sender<ApprovalChoice>,
    },
    /// The agent is requesting a secret string from the user (e.g. an API key,
    /// environment variable value, or sudo password).
    ///
    /// The TUI should render a masked input overlay (`•••`) so the value never
    /// appears in the scrollback. It then sends the secret string to
    /// `response_tx` to unblock the agent. Sending an empty string aborts.
    SecretRequest {
        /// The name of the variable or credential being requested (e.g. "OPENAI_API_KEY").
        var_name: String,
        /// Human-readable prompt to show the user.
        prompt: String,
        /// Whether this is a sudo / privilege-escalation prompt (affects the UI colour).
        is_sudo: bool,
        /// Channel to send the secret value back to the agent (empty = abort).
        response_tx: tokio::sync::oneshot::Sender<String>,
    },
    /// A lifecycle hook event emitted from the conversation loop.
    ///
    /// Subscribers (gateway, CLI) receive these events and forward them to
    /// the `HookRegistry` so tool:pre/post and llm:pre/post hooks fire without
    /// creating a circular dependency from lingshu-core into lingshu-gateway.
    HookEvent {
        /// The event type (e.g. "tool:pre", "llm:post").
        event: String,
        /// JSON-serialized context payload.
        context_json: String,
    },
    /// Context pressure warning: token usage is approaching the compression threshold.
    ///
    /// Emitted when estimated tokens exceed 85 % of the compression threshold —
    /// before compression fires. The TUI / gateway surfaces this as a status
    /// indicator so the user knows the context is filling up. After a successful
    /// compression the status reverts to `Ok` (no event is emitted for that).
    ContextPressure {
        /// Estimated current token usage.
        estimated_tokens: usize,
        /// Compression threshold in tokens (context_window × threshold_fraction).
        threshold_tokens: usize,
    },
    /// Ephemeral human-facing activity notice (compression, background process watch, etc.).
    ActivityNotice(String),
    /// Periodic progress while a blocking non-streaming LLM request runs (LM Studio, Ollama).
    ///
    /// WHY separate from ActivityNotice: wait state must update shelf/status even when the
    /// activity feed section is collapsed (Info notices are hidden in Skip mode).
    LlmWaitProgress {
        provider: String,
        elapsed_secs: u64,
        has_tools: bool,
        /// Rough prompt mass before the request (chars/4 heuristic).
        prompt_tokens_estimated: Option<u64>,
        /// Provider-reported or catalog context window.
        context_length: Option<u64>,
        /// LM Studio native prefill progress (0–100), when streaming.
        prefill_pct: Option<f32>,
    },
    /// Throttled tail from a background process (survives after `run_process` ToolDone).
    BackgroundProcessTail {
        process_id: String,
        command_preview: String,
        tail: String,
    },
    /// Background process exited (updates the monitor line in the TUI).
    BackgroundProcessFinished {
        process_id: String,
        exit_code: Option<i32>,
    },
    /// A steering event is waiting in the channel (pending injection).
    ///
    /// Emitted when the TUI sends a steer but before the loop has reached
    /// a tool boundary. The TUI uses this to show "⛵ N pending" in the
    /// status bar. Count is the total number of pending events.
    SteerPending { count: usize },
    /// A steering message was successfully injected into the conversation.
    ///
    /// Emitted immediately after the steer is appended to `session.messages`,
    /// before the next API call. The TUI uses this to:
    /// - Clear the `SteerPending` count from the status bar.
    /// - Show a brief "⛵ steer applied" confirmation.
    /// - Append the steer text to the output scroll buffer.
    SteerApplied {
        /// The full combined steer message that was injected.
        message: String,
    },
    /// Model handoff completed — brief shown before the next turn.
    ModelTransferComplete {
        from: String,
        to: String,
        brief: String,
        compressed: bool,
    },
}

impl std::fmt::Debug for StreamEvent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Token(t) => write!(f, "Token({t:?})"),
            Self::Reasoning(t) => write!(f, "Reasoning({t:?})"),
            Self::ToolGenerating { name, .. } => write!(f, "ToolGenerating({name:?})"),
            Self::ToolExec { name, .. } => write!(f, "ToolExec({name:?})"),
            Self::ToolProgress { name, message, .. } => {
                write!(f, "ToolProgress({name:?}, {message:?})")
            }
            Self::ToolDone {
                name,
                duration_ms,
                is_error,
                ..
            } => {
                write!(f, "ToolDone({name:?}, {duration_ms}ms, err={is_error})")
            }
            Self::SubAgentStart {
                task_index,
                task_count,
                goal,
                depth,
                agent_id,
                parent_id,
            } => write!(
                f,
                "SubAgentStart({}/{}, d{depth}, id={agent_id}, parent={parent_id:?}, {:?})",
                task_index + 1,
                task_count,
                goal
            ),
            Self::SubAgentReasoning {
                task_index,
                task_count,
                text,
            } => write!(
                f,
                "SubAgentReasoning({}/{}, {:?})",
                task_index + 1,
                task_count,
                text
            ),
            Self::SubAgentToolExec {
                task_index,
                task_count,
                name,
                ..
            } => write!(
                f,
                "SubAgentToolExec({}/{}, {:?})",
                task_index + 1,
                task_count,
                name
            ),
            Self::SubAgentFinish {
                task_index,
                task_count,
                status,
                duration_ms,
                ..
            } => write!(
                f,
                "SubAgentFinish({}/{}, {:?}, {}ms)",
                task_index + 1,
                task_count,
                status,
                duration_ms
            ),
            Self::RunFinished { outcome } => write!(
                f,
                "RunFinished(state={:?}, exit_reason={:?})",
                outcome.state, outcome.exit_reason
            ),
            Self::Done => write!(f, "Done"),
            Self::Error(e) => write!(f, "Error({e:?})"),
            Self::Clarify {
                question, choices, ..
            } => {
                if choices.is_some() {
                    write!(f, "Clarify({question:?}, multiple-choice)")
                } else {
                    write!(f, "Clarify({question:?})")
                }
            }
            Self::Approval { command, .. } => write!(f, "Approval({command:?})"),
            Self::SecretRequest {
                var_name, is_sudo, ..
            } => write!(f, "SecretRequest({var_name:?}, sudo={is_sudo})"),
            Self::HookEvent { event, .. } => write!(f, "HookEvent({event:?})"),
            Self::ContextPressure {
                estimated_tokens,
                threshold_tokens,
            } => write!(
                f,
                "ContextPressure(est={estimated_tokens}, threshold={threshold_tokens})"
            ),
            Self::ActivityNotice(text) => {
                let preview = &text[..text.len().min(60)];
                write!(f, "ActivityNotice({preview:?}…)")
            }
            Self::LlmWaitProgress {
                provider,
                elapsed_secs,
                has_tools,
                prompt_tokens_estimated,
                context_length,
                prefill_pct,
            } => write!(
                f,
                "LlmWaitProgress({provider}, {elapsed_secs}s, tools={has_tools}, \
                 prompt={prompt_tokens_estimated:?}, ctx={context_length:?}, prefill={prefill_pct:?})"
            ),
            Self::BackgroundProcessTail {
                process_id, tail, ..
            } => {
                let preview = &tail[..tail.len().min(40)];
                write!(f, "BackgroundProcessTail({process_id}, {preview:?}…)")
            }
            Self::BackgroundProcessFinished {
                process_id,
                exit_code,
            } => write!(f, "BackgroundProcessFinished({process_id}, {exit_code:?})"),
            Self::SteerPending { count } => write!(f, "SteerPending({count})"),
            Self::SteerApplied { message } => {
                let preview = &message[..message.len().min(60)];
                write!(f, "SteerApplied({preview:?}…)")
            }
            Self::ModelTransferComplete {
                from,
                to,
                compressed,
                ..
            } => {
                write!(
                    f,
                    "ModelTransferComplete({from:?}{to:?}, compressed={compressed})"
                )
            }
            Self::Footer(text) => {
                let preview = &text[..text.len().min(60)];
                write!(f, "Footer({preview:?}…)")
            }
        }
    }
}

// ─── Helpers ─────────────────────────────────────────────────────────

/// Parse a platform name string into a `Platform` variant.
///
/// Used by `chat_with_origin` so the gateway can pass the string name
/// of the originating platform and get the correct platform hint into
/// the system prompt.
fn platform_from_str(s: &str) -> Option<Platform> {
    match s {
        "cli" => Some(Platform::Cli),
        "telegram" => Some(Platform::Telegram),
        "discord" => Some(Platform::Discord),
        "slack" => Some(Platform::Slack),
        "whatsapp" => Some(Platform::Whatsapp),
        "feishu" => Some(Platform::Feishu),
        "wecom" => Some(Platform::Wecom),
        "signal" => Some(Platform::Signal),
        "email" => Some(Platform::Email),
        "matrix" => Some(Platform::Matrix),
        "mattermost" => Some(Platform::Mattermost),
        "dingtalk" => Some(Platform::DingTalk),
        "sms" => Some(Platform::Sms),
        "webhook" => Some(Platform::Webhook),
        "api" | "api_server" => Some(Platform::Api),
        "homeassistant" => Some(Platform::HomeAssistant),
        "cron" => Some(Platform::Cron),
        _ => None,
    }
}

// ─── Builder ──────────────────────────────────────────────────────────

pub struct AgentBuilder {
    config: AgentConfig,
    provider: Option<Arc<dyn LLMProvider>>,
    state_db: Option<Arc<SessionDb>>,
    tool_registry: Option<Arc<ToolRegistry>>,
    context_engine: Option<Arc<dyn crate::context_engine::ContextEngine>>,
    goal_store: Option<Arc<dyn crate::goals::GoalStore>>,
}

impl AgentBuilder {
    pub fn new(model: &str) -> Self {
        Self {
            config: AgentConfig {
                model: model.to_string(),
                ..Default::default()
            },
            provider: None,
            state_db: None,
            tool_registry: None,
            context_engine: None,
            goal_store: None,
        }
    }

    /// Construct from an existing AppConfig.
    pub fn from_config(config: &AppConfig) -> Self {
        // Resolve personality preset → persona instruction addon
        let personality_addon =
            crate::config::resolve_personality(config, &config.display.personality);

        Self {
            config: AgentConfig {
                custom_system_prompt: (!config.agent.system_prompt.trim().is_empty())
                    .then_some(config.agent.system_prompt.clone()),
                model: config.model.default_model.clone(),
                enabled_toolsets: config.tools.enabled_toolsets.clone().unwrap_or_default(),
                disabled_toolsets: config.tools.disabled_toolsets.clone().unwrap_or_default(),
                enabled_tools: config.tools.enabled_tools.clone().unwrap_or_default(),
                disabled_tools: config.tools.disabled_tools.clone().unwrap_or_default(),
                max_iterations: config.model.max_iterations,
                streaming: config.model.streaming,
                save_trajectories: config.save_trajectories,
                skip_context_files: config.skip_context_files,
                skip_memory: config.skip_memory,
                temperature: config.model.temperature,
                model_config: config.model.clone(),
                skills_config: config.skills.clone(),
                memory_config: config.memory.clone(),
                approvals_config: config.approvals.clone(),
                kanban_config: config.kanban.clone(),
                kanban_task_id: None,
                plugins_config: config.plugins.clone(),
                delegation_enabled: config.delegation.enabled,
                delegation_model: config.delegation.model.clone(),
                delegation_provider: config.delegation.provider.clone(),
                delegation_max_subagents: config.delegation.max_subagents,
                delegation_max_iterations: config.delegation.max_iterations,
                personality_addon,
                browser: config.browser.clone(),
                checkpoints_enabled: config.checkpoints.enabled,
                checkpoints_max_snapshots: config.checkpoints.max_snapshots,
                checkpoints_max_total_size_mb: config.checkpoints.max_total_size_mb,
                checkpoints_max_file_size_mb: config.checkpoints.max_file_size_mb,
                computer_use_enabled: config.computer_use.enabled,
                computer_use_keep_last_n_screenshots: config.computer_use.keep_last_n_screenshots,
                computer_use_confirm_destructive: config.computer_use.confirm_destructive,
                computer_use_cua_cmd: config.computer_use.cua_driver_cmd.clone(),
                terminal_backend: config.terminal.backend.clone(),
                terminal_docker: config.terminal.docker.clone(),
                terminal_ssh: config.terminal.ssh.clone(),
                terminal_modal: config.terminal.modal.clone(),
                terminal_daytona: config.terminal.daytona.clone(),
                terminal_singularity: config.terminal.singularity.clone(),
                compression: config.compression.clone(),
                auxiliary: config.auxiliary.clone(),
                shadow_judge: config.shadow_judge.clone(),
                goals: config.goals.clone(),
                moa: config.moa.clone(),
                tts: config.tts.clone(),
                stt: config.stt.clone(),
                image_generation: config.image_generation.clone(),
                terminal_env_passthrough: config.terminal.env_passthrough.clone(),
                file_allowed_roots: config.tools.file.allowed_roots.clone(),
                path_restrictions: config.security.path_restrictions.clone(),
                lsp: config.lsp.clone(),
                result_spill: config.tools.result_spill,
                result_spill_threshold: config.tools.result_spill_threshold,
                result_spill_preview_lines: config.tools.result_spill_preview_lines,
                result_turn_budget_chars: config.tools.result_turn_budget_chars,
                max_write_payload_kib: config.tools.file.max_write_payload_kib,
                local_write_create_dirs: config.local_inference.write_create_dirs,
                local_max_tool_turn_tokens: config.local_inference.max_tool_turn_tokens,
                file_mutation_verifier: config.display.file_mutation_verifier,
                cache: config.cache.clone(),
                web_search: config.web_search.clone(),
                web: config.web.clone(),
                ..Default::default()
            },
            provider: None,
            state_db: None,
            tool_registry: None,
            context_engine: None,
            goal_store: None,
        }
    }

    pub fn provider(mut self, p: Arc<dyn LLMProvider>) -> Self {
        self.provider = Some(p);
        self
    }

    pub fn state_db(mut self, db: Arc<SessionDb>) -> Self {
        self.state_db = Some(db);
        self
    }

    pub fn tools(mut self, registry: Arc<ToolRegistry>) -> Self {
        self.tool_registry = Some(registry);
        self
    }

    pub fn context_engine(mut self, engine: Arc<dyn crate::context_engine::ContextEngine>) -> Self {
        self.context_engine = Some(engine);
        self
    }

    pub fn goal_store(mut self, store: Arc<dyn crate::goals::GoalStore>) -> Self {
        self.goal_store = Some(store);
        self
    }

    pub fn max_iterations(mut self, n: u32) -> Self {
        self.config.max_iterations = n;
        self
    }

    pub fn streaming(mut self, enabled: bool) -> Self {
        self.config.streaming = enabled;
        self
    }

    pub fn platform(mut self, p: Platform) -> Self {
        self.config.platform = p;
        self
    }

    pub fn session_id(mut self, id: String) -> Self {
        self.config.session_id = Some(id);
        self
    }

    /// Set the origin chat context — (platform_name, chat_id) — for gateway sessions.
    ///
    /// This is forwarded into every `ToolContext` so that
    /// `manage_cron_jobs(action='create', deliver='origin')` knows where to
    /// deliver job output without the LLM needing to know the raw chat ID.
    pub fn origin_chat(mut self, platform: String, chat_id: String) -> Self {
        self.config.origin_chat = Some(OriginChat::new(platform, chat_id));
        self
    }

    pub fn temperature(mut self, t: f32) -> Self {
        self.config.temperature = Some(t);
        self
    }

    pub fn quiet_mode(mut self, enabled: bool) -> Self {
        self.config.quiet_mode = enabled;
        self
    }

    /// Set enabled toolsets (only tools in these toolsets will be available).
    pub fn enabled_toolsets(mut self, toolsets: Vec<String>) -> Self {
        self.config.enabled_toolsets = toolsets;
        self
    }

    /// Set disabled toolsets (tools in these toolsets will be excluded).
    pub fn disabled_toolsets(mut self, toolsets: Vec<String>) -> Self {
        self.config.disabled_toolsets = toolsets;
        self
    }

    /// Set enabled tools by name.
    pub fn enabled_tools(mut self, tools: Vec<String>) -> Self {
        self.config.enabled_tools = tools;
        self
    }

    /// Set disabled tools by name.
    pub fn disabled_tools(mut self, tools: Vec<String>) -> Self {
        self.config.disabled_tools = tools;
        self
    }

    /// Set a custom system prompt (instructions) appended to the base prompt.
    pub fn custom_system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.config.custom_system_prompt = Some(prompt.into());
        self
    }

    /// Skip loading workspace context files such as AGENTS.md.
    pub fn skip_context_files(mut self, skip: bool) -> Self {
        self.config.skip_context_files = skip;
        self
    }

    /// Skip loading persistent memory and user profile sections.
    pub fn skip_memory(mut self, skip: bool) -> Self {
        self.config.skip_memory = skip;
        self
    }

    pub fn build(self) -> Result<Agent, AgentError> {
        let provider = self
            .provider
            .ok_or_else(|| AgentError::Config("provider is required".into()))?;
        Ok(Agent::build_runtime_clone(
            self.config,
            provider,
            self.state_db,
            self.tool_registry,
            self.context_engine,
            self.goal_store,
        ))
    }

    /// Extract built agent config (for kanban profile worker forks).
    pub fn into_agent_config(self) -> AgentConfig {
        self.config
    }
}

// ─── Agent Drop ───────────────────────────────────────────────────────

impl Drop for Agent {
    /// Cancel the GC task when the Agent is dropped so the background
    /// tokio task doesn't outlive the process table it references.
    fn drop(&mut self) {
        self.gc_cancel.cancel();
    }
}

// ─── Tests ────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use lingshu_tools::registry::GatewaySender;
    use edgequake_llm::traits::{
        ChatMessage, CompletionOptions, StreamChunk, ToolChoice, ToolDefinition,
    };
    use futures::StreamExt;
    use tokio::sync::Notify;

    struct ReasoningStreamProvider;
    struct SlowChatProvider {
        started: Arc<Notify>,
        release: Arc<Notify>,
    }
    struct MockGatewaySender;

    #[test]
    fn platform_from_str_accepts_gateway_api_server_alias() {
        assert_eq!(platform_from_str("api"), Some(Platform::Api));
        assert_eq!(platform_from_str("api_server"), Some(Platform::Api));
    }

    #[async_trait]
    impl LLMProvider for ReasoningStreamProvider {
        fn name(&self) -> &str {
            "reasoning-stream"
        }

        fn model(&self) -> &str {
            "reasoning-stream/mock"
        }

        fn max_context_length(&self) -> usize {
            128_000
        }

        async fn complete(
            &self,
            _prompt: &str,
        ) -> edgequake_llm::Result<edgequake_llm::LLMResponse> {
            Ok(edgequake_llm::LLMResponse::new(
                "fallback complete",
                self.model(),
            ))
        }

        async fn complete_with_options(
            &self,
            prompt: &str,
            _options: &CompletionOptions,
        ) -> edgequake_llm::Result<edgequake_llm::LLMResponse> {
            self.complete(prompt).await
        }

        async fn chat(
            &self,
            messages: &[ChatMessage],
            options: Option<&CompletionOptions>,
        ) -> edgequake_llm::Result<edgequake_llm::LLMResponse> {
            self.chat_with_tools(messages, &[], None, options).await
        }

        async fn chat_with_tools(
            &self,
            _messages: &[ChatMessage],
            _tools: &[ToolDefinition],
            _tool_choice: Option<ToolChoice>,
            _options: Option<&CompletionOptions>,
        ) -> edgequake_llm::Result<edgequake_llm::LLMResponse> {
            let mut response = edgequake_llm::LLMResponse::new("nonstreamed answer", self.model());
            response.thinking_content = Some("hidden reasoning".to_string());
            Ok(response)
        }

        async fn stream(
            &self,
            _prompt: &str,
        ) -> edgequake_llm::Result<futures::stream::BoxStream<'static, edgequake_llm::Result<String>>>
        {
            Ok(futures::stream::iter(vec![Ok("plain stream".to_string())]).boxed())
        }

        async fn chat_with_tools_stream(
            &self,
            _messages: &[ChatMessage],
            _tools: &[ToolDefinition],
            _tool_choice: Option<ToolChoice>,
            _options: Option<&CompletionOptions>,
        ) -> edgequake_llm::Result<
            futures::stream::BoxStream<'static, edgequake_llm::Result<StreamChunk>>,
        > {
            let chunks = vec![
                Ok(StreamChunk::ThinkingContent {
                    text: "live reasoning".to_string(),
                    tokens_used: Some(3),
                    budget_total: None,
                }),
                Ok(StreamChunk::Content("streamed answer".to_string())),
                Ok(StreamChunk::Finished {
                    reason: "stop".to_string(),
                    ttft_ms: None,
                    usage: None,
                }),
            ];
            Ok(futures::stream::iter(chunks).boxed())
        }

        fn supports_streaming(&self) -> bool {
            true
        }

        fn supports_tool_streaming(&self) -> bool {
            true
        }

        fn supports_function_calling(&self) -> bool {
            true
        }
    }

    #[async_trait]
    impl LLMProvider for SlowChatProvider {
        fn name(&self) -> &str {
            "slow-chat"
        }

        fn model(&self) -> &str {
            "slow-chat/mock"
        }

        fn max_context_length(&self) -> usize {
            128_000
        }

        async fn complete(
            &self,
            prompt: &str,
        ) -> edgequake_llm::Result<edgequake_llm::LLMResponse> {
            Ok(edgequake_llm::LLMResponse::new(prompt, self.model()))
        }

        async fn complete_with_options(
            &self,
            prompt: &str,
            _options: &CompletionOptions,
        ) -> edgequake_llm::Result<edgequake_llm::LLMResponse> {
            self.complete(prompt).await
        }

        async fn chat(
            &self,
            messages: &[ChatMessage],
            options: Option<&CompletionOptions>,
        ) -> edgequake_llm::Result<edgequake_llm::LLMResponse> {
            self.chat_with_tools(messages, &[], None, options).await
        }

        async fn chat_with_tools(
            &self,
            _messages: &[ChatMessage],
            _tools: &[ToolDefinition],
            _tool_choice: Option<ToolChoice>,
            _options: Option<&CompletionOptions>,
        ) -> edgequake_llm::Result<edgequake_llm::LLMResponse> {
            self.started.notify_waiters();
            self.release.notified().await;
            Ok(edgequake_llm::LLMResponse::new("slow answer", self.model()))
        }
    }

    #[async_trait]
    impl GatewaySender for MockGatewaySender {
        async fn send_message(
            &self,
            _platform: &str,
            _recipient: &str,
            _message: &str,
        ) -> Result<(), String> {
            Ok(())
        }

        async fn list_targets(&self) -> Result<Vec<String>, String> {
            Ok(vec!["telegram".into()])
        }
    }

    fn write_session_hook_plugin(dir: &Path) {
        std::fs::write(
            dir.join("plugin.yaml"),
            r#"
name: session-hooks
version: "1.0.0"
description: Session boundary recorder
provides_hooks:
  - on_session_finalize
  - on_session_reset
"#,
        )
        .expect("manifest");
        std::fs::write(
            dir.join("__init__.py"),
            r#"
import json
from pathlib import Path

def _append(event_name, session_id, platform, **kwargs):
    target = Path(__file__).with_name("session-hooks.jsonl")
    with target.open("a", encoding="utf-8") as handle:
        handle.write(json.dumps({"event": event_name, "session_id": session_id, "platform": platform}) + "\n")

def register(ctx):
    ctx.register_hook("on_session_finalize", lambda **kwargs: _append("on_session_finalize", **kwargs))
    ctx.register_hook("on_session_reset", lambda **kwargs: _append("on_session_reset", **kwargs))
"#,
        )
        .expect("plugin");
    }

    #[test]
    fn iteration_budget_counts_down() {
        let budget = IterationBudget::new(3);
        assert!(budget.try_consume());
        assert!(budget.try_consume());
        assert!(budget.try_consume());
        assert!(!budget.try_consume());
        assert_eq!(budget.used(), 3);
    }

    #[test]
    fn iteration_budget_reset() {
        let budget = IterationBudget::new(2);
        budget.try_consume();
        budget.try_consume();
        assert!(!budget.try_consume());
        budget.reset();
        assert!(budget.try_consume());
        assert_eq!(budget.remaining(), 1);
    }

    #[test]
    fn builder_requires_provider() {
        let result = AgentBuilder::new("test/model").build();
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn builder_with_mock_provider() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .max_iterations(10)
            .build()
            .expect("build agent");

        let cfg = agent.config.read().await;
        assert_eq!(cfg.model, "mock");
        assert_eq!(cfg.max_iterations, 10);
        assert_eq!(agent.budget.remaining(), 10);
    }

    #[tokio::test]
    async fn chat_with_mock_provider() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .build()
            .expect("build agent");

        let result = agent.chat("hello").await;
        assert!(result.is_ok());
        // MockProvider returns a canned response
        let response = result.expect("response");
        assert!(!response.is_empty());
    }

    #[tokio::test]
    async fn try_session_snapshot_remains_readable_during_slow_turn() {
        let started = Arc::new(Notify::new());
        let release = Arc::new(Notify::new());
        let provider: Arc<dyn LLMProvider> = Arc::new(SlowChatProvider {
            started: started.clone(),
            release: release.clone(),
        });
        let agent = Arc::new(
            AgentBuilder::new("slow-chat/mock")
                .provider(provider)
                .build()
                .expect("build agent"),
        );

        let agent_task = agent.clone();
        let chat_task = tokio::spawn(async move { agent_task.chat("hello").await });

        tokio::time::timeout(std::time::Duration::from_secs(2), started.notified())
            .await
            .expect("provider started");

        let snapshot = agent
            .try_session_snapshot()
            .expect("session snapshot should stay readable mid-turn");
        assert_eq!(snapshot.message_count, 1);
        assert_eq!(snapshot.user_turn_count, 1);

        release.notify_waiters();
        let result = chat_task.await.expect("join").expect("chat");
        assert_eq!(result, "slow answer");
    }

    #[test]
    fn from_config_wires_agent_flags() {
        let config = AppConfig {
            save_trajectories: true,
            skip_context_files: true,
            skip_memory: true,
            ..Default::default()
        };

        let builder = AgentBuilder::from_config(&config);

        assert!(builder.config.save_trajectories);
        assert!(builder.config.skip_context_files);
        assert!(builder.config.skip_memory);
    }

    #[test]
    fn resolve_tool_policy_expands_aliases_once() {
        let config = AgentConfig {
            enabled_toolsets: vec!["core".into()],
            disabled_toolsets: vec!["browser".into()],
            ..Default::default()
        };

        let policy = resolve_tool_policy(&config);
        assert!(
            policy
                .expanded_enabled
                .iter()
                .any(|toolset| toolset == "file")
        );
        assert!(
            policy
                .expanded_disabled
                .iter()
                .any(|toolset| toolset == "browser")
        );
        assert!(
            !policy
                .parent_active_toolsets
                .iter()
                .any(|toolset| toolset == "browser")
        );
    }

    #[test]
    fn app_config_ref_projection_keeps_runtime_policy_consistent() {
        let config = AgentConfig {
            platform: Platform::Telegram,
            enabled_toolsets: vec!["core".into()],
            disabled_toolsets: vec!["browser".into()],
            ..Default::default()
        };

        let policy = resolve_tool_policy(&config);
        let projected = config.to_app_config_ref(true, &policy);

        assert!(projected.gateway_running);
        assert_eq!(
            projected.parent_active_toolsets,
            policy.parent_active_toolsets
        );
        assert_eq!(projected.disabled_toolsets, policy.expanded_disabled);
    }

    #[tokio::test]
    async fn new_session_resets_state() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .max_iterations(5)
            .build()
            .expect("build agent");

        // Use some budget
        agent.budget.try_consume();
        agent.budget.try_consume();
        assert_eq!(agent.budget.remaining(), 3);

        // Chat to add messages
        let _ = agent.chat("hi").await;

        // Reset
        agent.new_session().await;
        assert_eq!(agent.budget.remaining(), 5);
        let session = agent.session.read().await;
        assert!(session.messages.is_empty());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn session_boundary_hooks_fire_on_new_and_finalize() {
        let temp = tempfile::TempDir::new().expect("tempdir");
        let plugin_dir = temp.path().join("session-hooks");
        std::fs::create_dir_all(&plugin_dir).expect("plugin dir");
        write_session_hook_plugin(&plugin_dir);

        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let mut config = AppConfig::default();
        config.plugins.external_dirs = vec![temp.path().to_string_lossy().to_string()];

        let agent = AgentBuilder::from_config(&config)
            .provider(provider)
            .build()
            .expect("build agent");

        let old_session_id = "existing-session".to_string();
        agent.session.write().await.session_id = Some(old_session_id.clone());

        agent.new_session().await;
        let new_session_id = agent
            .session
            .read()
            .await
            .session_id
            .clone()
            .expect("new session id");
        agent.finalize_session().await;

        let log = std::fs::read_to_string(plugin_dir.join("session-hooks.jsonl")).expect("log");
        assert!(log.contains("on_session_finalize"));
        assert!(log.contains("on_session_reset"));
        assert!(log.contains(&old_session_id));
        assert!(log.contains(&new_session_id));
    }

    #[tokio::test]
    async fn interrupt_triggers_cancellation() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .build()
            .expect("build agent");

        assert!(!agent.is_cancelled());
        agent.interrupt();
        assert!(agent.is_cancelled());
    }

    /// After an interrupt, execute_loop must reset the cancel token so the
    /// agent can still process subsequent conversation turns.  Without this
    /// reset, Ctrl+C would permanently break the agent for the rest of the
    /// session.
    #[tokio::test]
    async fn cancel_resets_between_turns() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .build()
            .expect("build agent");

        // Interrupt and confirm the token is now cancelled
        agent.interrupt();
        assert!(agent.is_cancelled());

        // A new chat call should succeed — execute_loop resets the token
        let result = agent.chat("hello after cancel").await;
        assert!(result.is_ok(), "expected success after cancel: {result:?}");
        // Token must not still be cancelled after a clean (non-interrupted) turn
        assert!(!agent.is_cancelled());
    }

    #[tokio::test]
    async fn conversation_result_structure() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .session_id("test-session".into())
            .build()
            .expect("build agent");

        let result = agent
            .run_conversation("hello", Some("You are helpful."), None)
            .await
            .expect("conversation");

        assert_eq!(result.session_id, "test-session");
        assert_eq!(result.api_calls, 1);
        assert!(!result.interrupted);
        assert_eq!(result.model, "mock");
        // Messages: user + assistant
        assert_eq!(result.messages.len(), 2);
    }

    #[tokio::test]
    async fn session_state_gets_session_id_after_chat() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .build()
            .expect("build agent");

        // Before chat, session_id is None
        {
            let session = agent.session.read().await;
            assert!(session.session_id.is_none());
        }

        // After chat, session_id is populated (auto-generated UUID)
        let _ = agent.chat("hello").await;
        {
            let session = agent.session.read().await;
            assert!(session.session_id.is_some());
        }
    }

    #[tokio::test]
    async fn fork_isolated_creates_fresh_session_state() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let parent = AgentBuilder::new("mock")
            .provider(provider)
            .max_iterations(7)
            .build()
            .expect("build agent");

        let _ = parent.chat("parent turn").await.expect("parent chat");
        let parent_before = parent.session_snapshot().await;

        let child = parent
            .fork_isolated(IsolatedAgentOptions {
                session_id: Some("bg-test".into()),
                quiet_mode: Some(true),
                ..Default::default()
            })
            .await
            .expect("fork isolated");

        let child_before = child.session_snapshot().await;
        let child_cfg = child.config.read().await;
        assert_eq!(child_before.message_count, 0);
        assert_eq!(child_before.api_call_count, 0);
        assert_eq!(child_before.model, parent_before.model);
        assert_eq!(child_cfg.session_id.as_deref(), Some("bg-test"));
        assert_eq!(child.budget.remaining(), 7);
        drop(child_cfg);

        let _ = child.chat("background turn").await.expect("child chat");

        let parent_after = parent.session_snapshot().await;
        let child_after = child.session_snapshot().await;
        assert_eq!(parent_after.message_count, parent_before.message_count);
        assert!(child_after.message_count > 0);
        assert_eq!(child_after.session_id.as_deref(), Some("bg-test"));
        assert_ne!(parent_after.session_id, child_after.session_id);
    }

    #[tokio::test]
    async fn fork_isolated_preserves_gateway_sender() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let parent = AgentBuilder::new("mock")
            .provider(provider)
            .build()
            .expect("build agent");
        parent.set_gateway_sender(Arc::new(MockGatewaySender)).await;

        let child = parent
            .fork_isolated(IsolatedAgentOptions::default())
            .await
            .expect("fork isolated");

        assert!(child.gateway_sender.read().await.is_some());
    }

    #[tokio::test]
    async fn model_config_propagates_to_agent() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .build()
            .expect("build agent");

        let cfg = agent.config.read().await;
        assert!(!cfg.model_config.smart_routing.enabled);
        assert!(cfg.model_config.smart_routing.cheap_model.is_empty());
    }

    #[tokio::test]
    async fn chat_streaming_emits_reasoning_when_enabled() {
        let provider: Arc<dyn LLMProvider> = Arc::new(ReasoningStreamProvider);
        let agent = AgentBuilder::new("reasoning-stream/mock")
            .provider(provider)
            .streaming(true)
            .build()
            .expect("build agent");

        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        agent
            .chat_streaming("hello", tx)
            .await
            .expect("streaming chat");

        let mut saw_reasoning = false;
        let mut saw_token = false;
        let mut saw_done = false;

        while let Some(event) = rx.recv().await {
            match event {
                StreamEvent::Reasoning(text) => saw_reasoning |= !text.is_empty(),
                StreamEvent::Token(text) => saw_token |= !text.is_empty(),
                StreamEvent::Done => {
                    saw_done = true;
                    break;
                }
                _ => {}
            }
        }

        assert!(
            saw_reasoning,
            "expected a live reasoning event when streaming is enabled"
        );
        assert!(saw_token, "expected streamed answer tokens");
        assert!(saw_done, "expected the stream to terminate cleanly");
    }

    #[tokio::test]
    async fn chat_streaming_sends_single_final_answer_when_streaming_disabled() {
        let provider: Arc<dyn LLMProvider> = Arc::new(ReasoningStreamProvider);
        let agent = AgentBuilder::new("reasoning-stream/mock")
            .provider(provider)
            .streaming(false)
            .build()
            .expect("build agent");

        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        agent
            .chat_streaming("hello", tx)
            .await
            .expect("streaming chat");

        let mut saw_reasoning = false;
        let mut token_events = 0usize;
        let mut collected_tokens = String::new();

        while let Some(event) = rx.recv().await {
            match event {
                StreamEvent::Reasoning(text) => saw_reasoning |= !text.is_empty(),
                StreamEvent::Token(text) => {
                    token_events += 1;
                    collected_tokens.push_str(&text);
                }
                StreamEvent::Done => break,
                _ => {}
            }
        }

        assert!(
            saw_reasoning,
            "final reasoning content should still be available for think mode"
        );
        assert_eq!(
            token_events, 1,
            "streaming-off mode should emit one complete answer instead of pseudo-streaming chunks"
        );
        assert_eq!(collected_tokens, "nonstreamed answer");
    }

    #[tokio::test]
    async fn session_personality_overlay_replaces_previous_overlay() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .build()
            .expect("build agent");

        {
            let mut session = agent.session.write().await;
            session.cached_system_prompt = Some("Base prompt".to_string());
        }

        agent
            .set_personality_addon(Some("First overlay".to_string()))
            .await;
        assert!(agent.system_prompt().await.is_none());

        {
            let mut session = agent.session.write().await;
            session.cached_system_prompt = Some("Base prompt".to_string());
        }

        agent
            .set_personality_addon(Some("Second overlay".to_string()))
            .await;
        assert!(agent.system_prompt().await.is_none());

        agent.set_personality_addon(None).await;
        assert!(agent.system_prompt().await.is_none());
    }

    #[test]
    fn session_snapshot_prompt_tokens_include_cache_buckets() {
        let snap = SessionSnapshot {
            session_id: None,
            model: "mock/model".into(),
            message_count: 0,
            user_turn_count: 0,
            api_call_count: 0,
            input_tokens: 3,
            output_tokens: 10,
            cache_read_tokens: 15_000,
            cache_write_tokens: 2_000,
            reasoning_tokens: 7,
            last_prompt_tokens: 1_234,
            budget_remaining: 0,
            budget_max: 0,
        };

        assert_eq!(snap.prompt_tokens(), 17_003);
        assert_eq!(snap.total_tokens(), 17_020);
        assert_eq!(snap.context_pressure_tokens(), 1_234);
    }

    #[tokio::test]
    async fn restore_session_reuses_persisted_system_prompt() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let db = Arc::new(SessionDb::open_default().expect("db"));
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let session = lingshu_state::SessionRecord {
            id: "restore-me".into(),
            source: "cli".into(),
            user_id: None,
            model: Some("mock/model".into()),
            system_prompt: Some("Persisted system prompt".into()),
            parent_session_id: None,
            started_at: 1.0,
            ended_at: Some(2.0),
            end_reason: None,
            message_count: 2,
            tool_call_count: 0,
            input_tokens: 10,
            output_tokens: 4,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            reasoning_tokens: 0,
            estimated_cost_usd: None,
            title: Some("restore".into()),
            handoff_state: None,
            handoff_platform: None,
            handoff_error: None,
        };
        db.save_session(&session).await.expect("save session");
        db.save_message("restore-me", &Message::user("hello"))
            .await
            .expect("save user");
        db.save_message("restore-me", &Message::assistant("hi"))
            .await
            .expect("save assistant");

        let agent = AgentBuilder::new("mock/model")
            .provider(provider)
            .state_db(db)
            .build()
            .expect("build agent");

        let restored = agent.restore_session("restore-me").await.expect("restore");
        assert_eq!(restored, 2);
        assert_eq!(
            agent.system_prompt().await.as_deref(),
            Some("Persisted system prompt")
        );
    }

    // ── FP31: cache_write_tokens on LLMResponse ───────────────────────

    #[test]
    fn llm_response_cache_write_tokens_defaults_to_none() {
        let r = edgequake_llm::LLMResponse::new("hello", "test-model");
        assert!(
            r.cache_write_tokens.is_none(),
            "cache_write_tokens must default to None"
        );
    }

    #[test]
    fn llm_response_cache_write_tokens_builder() {
        let r = edgequake_llm::LLMResponse::new("hello", "test-model").with_cache_write_tokens(42);
        assert_eq!(r.cache_write_tokens, Some(42));
    }

    #[test]
    fn stream_usage_cache_write_tokens_builder() {
        use edgequake_llm::traits::StreamUsage;
        let u = StreamUsage::new(10, 5).with_cache_write_tokens(99);
        assert_eq!(u.cache_write_tokens, Some(99));
    }

    // ── FP33: first_compression_done on SessionState ──────────────────

    #[test]
    fn session_state_first_compression_done_defaults_false() {
        let s = SessionState::default();
        assert!(
            !s.first_compression_done,
            "first_compression_done must start as false"
        );
    }

    #[test]
    fn session_state_first_compression_done_can_be_set() {
        let s = SessionState {
            first_compression_done: true,
            ..SessionState::default()
        };
        assert!(s.first_compression_done);
    }

    #[test]
    fn apply_model_transfer_outcome_clears_cache_and_injects_brief() {
        let outcome = crate::model_transfer::ModelTransferOutcome {
            from_model: "a/m1".into(),
            to_model: "b/m2".into(),
            brief: "Continue tests.".into(),
            compressed: true,
            from_context_window: 200_000,
            target_context_window: 128_000,
        };
        let mut session = SessionState {
            cached_system_prompt: Some("stable".into()),
            cached_stable_prompt: Some("stable".into()),
            messages: vec![Message::user("hello")],
            ..SessionState::default()
        };
        session.apply_model_transfer_outcome(&outcome);
        assert!(session.cached_system_prompt.is_none());
        assert!(session.cached_stable_prompt.is_none());
        assert!(session.first_compression_done);
        assert_eq!(session.messages.len(), 2);
        assert!(
            session.messages[1]
                .text_content()
                .contains("Continue tests.")
        );
    }

    #[tokio::test]
    async fn goal_set_before_first_chat_avoids_foreign_key_error() {
        let db = Arc::new(lingshu_state::SessionDb::open_default().expect("open db"));
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .state_db(db)
            .build()
            .expect("build");

        let msg = agent
            .goal_set("Refactor demo module in ./demo")
            .await
            .expect("goal set before any chat turn");
        assert!(msg.contains("Goal set"));

        let shown = agent.goal_show().await.expect("show");
        assert!(shown.contains("Refactor demo module"));
    }

    #[tokio::test]
    async fn goal_set_does_not_mutate_cached_system_prompt() {
        use crate::goals::InMemoryGoalStore;

        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let goal_store = Arc::new(InMemoryGoalStore::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .goal_store(goal_store)
            .build()
            .expect("build");

        agent.chat("hello").await.expect("chat");
        let before = agent.session.read().await.cached_system_prompt.clone();
        agent
            .goal_set("Refactor payment service")
            .await
            .expect("goal set");
        let after = agent.session.read().await.cached_system_prompt.clone();
        assert_eq!(before, after, "cached system prompt must remain unchanged");
    }

    #[tokio::test]
    async fn perform_model_transfer_clears_cached_prompt_and_injects_brief() {
        use crate::goals::{GoalStore, InMemoryGoalStore};
        use crate::model_transfer::{
            ModelTransferContext, ModelTransferOrchestrator, resolve_model_transfer_target,
        };

        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let goal_store = Arc::new(InMemoryGoalStore::new());
        let db = Arc::new(lingshu_state::SessionDb::open_default().expect("open db"));
        let agent = AgentBuilder::new("anthropic/claude-opus-4.6")
            .provider(provider.clone())
            .goal_store(goal_store.clone())
            .state_db(db)
            .build()
            .expect("build");

        agent
            .goal_set("finish session handoff tests")
            .await
            .expect("goal");
        agent.chat("implement session handoff").await.expect("chat");
        let session_id = agent.session.read().await.session_id.clone().expect("sid");

        {
            let mut session = agent.session.write().await;
            session.cached_system_prompt = Some("stable block".into());
            session.cached_stable_prompt = Some("stable".into());
        }

        let target = resolve_model_transfer_target("anthropic/claude-haiku-4.5").expect("catalog");
        let mut messages = agent.messages().await;
        let cfg = agent.config.read().await.compression.clone();
        let mut ctx = ModelTransferContext {
            current_model: "anthropic/claude-opus-4.6",
            messages: &mut messages,
            system_prompt: Some("stable block"),
            compression_cfg: &cfg,
            main_provider: provider.clone(),
            auxiliary_model: None,
        };
        let (outcome, new_provider) =
            ModelTransferOrchestrator::execute_with_provider(&mut ctx, &target, provider)
                .await
                .expect("handoff");

        {
            let mut session = agent.session.write().await;
            session.messages = messages;
            session.apply_model_transfer_outcome(&outcome);
        }
        agent
            .swap_model(outcome.to_model.clone(), new_provider)
            .await;

        let session = agent.session.read().await;
        assert!(session.cached_system_prompt.is_none());
        assert!(session.cached_stable_prompt.is_none());
        assert!(
            session.messages.last().is_some_and(|m| {
                m.role == Role::User
                    && m.text_content()
                        .starts_with("Continuing from previous session")
            }),
            "handoff brief should be injected as user message"
        );
        assert_eq!(agent.model().await, "anthropic/claude-haiku-4.5");

        let goal = goal_store.as_ref().active(&session_id).expect("goal load");
        assert!(
            goal.goal_text
                .as_deref()
                .is_some_and(|g| g.contains("handoff")),
            "standing goal must survive model handoff"
        );
    }

    #[tokio::test]
    async fn perform_model_transfer_persists_audit_trail() {
        use crate::model_transfer::{
            ModelTransferContext, ModelTransferOrchestrator, resolve_model_transfer_target,
        };

        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let db = Arc::new(lingshu_state::SessionDb::open_default().expect("open db"));
        let agent = AgentBuilder::new("anthropic/claude-opus-4.6")
            .provider(provider.clone())
            .state_db(db.clone())
            .build()
            .expect("build");

        agent
            .chat("work on model transfer unification")
            .await
            .expect("chat");
        let session_id = agent.session.read().await.session_id.clone().expect("sid");

        // CI has no ANTHROPIC_API_KEY — use mock provider via orchestrator, then apply
        // the same post-handoff persistence path as `perform_model_transfer`.
        let target = resolve_model_transfer_target("anthropic/claude-haiku-4.5").expect("catalog");
        let mut messages = agent.messages().await;
        let cfg = agent.config.read().await.compression.clone();
        let mut ctx = ModelTransferContext {
            current_model: "anthropic/claude-opus-4.6",
            messages: &mut messages,
            system_prompt: None,
            compression_cfg: &cfg,
            main_provider: provider.clone(),
            auxiliary_model: None,
        };
        let (outcome, new_provider) =
            ModelTransferOrchestrator::execute_with_provider(&mut ctx, &target, provider)
                .await
                .expect("handoff");
        {
            let mut session = agent.session.write().await;
            session.messages = messages;
            session.apply_model_transfer_outcome(&outcome);
        }
        agent
            .swap_model(outcome.to_model.clone(), new_provider)
            .await;
        db.update_session_model(&session_id, &outcome.to_model)
            .await
            .expect("session model update");
        db.record_model_transfer(
            &session_id,
            &outcome.from_model,
            &outcome.to_model,
            &outcome.brief,
        )
        .await
        .expect("record transfer");

        assert_eq!(outcome.to_model, "anthropic/claude-haiku-4.5");
        assert_eq!(agent.model().await, "anthropic/claude-haiku-4.5");

        let records = db
            .list_model_transfers(&session_id)
            .await
            .expect("list transfers");
        assert_eq!(records.len(), 1);
        assert_eq!(records[0].from_model, "anthropic/claude-opus-4.6");
        assert_eq!(records[0].to_model, "anthropic/claude-haiku-4.5");
        assert!(!records[0].brief.trim().is_empty());
    }
}