edgecrab-core 0.2.2

Agent core: conversation loop, prompt builder, context compression, model routing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
//! # 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 edgecrab_state::SessionDb;
use edgecrab_tools::ProcessTable;
use edgecrab_tools::TodoStore;
use edgecrab_tools::config_ref::{AppConfigRef, LspServerConfigRef};
use edgecrab_tools::registry::{GatewaySender, ToolInventoryEntry, ToolRegistry};
use edgecrab_types::{AgentError, ApiMode, Cost, Message, Platform, Role, 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: 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<edgecrab_tools::TodoStore>,
}

/// 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<(String, String)>,
}

/// 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>,
    /// 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,
    /// 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 — (platform_name, chat_id).
    ///
    /// 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<(String, String)>,
    /// 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,
    /// Active terminal backend and backend-specific configuration.
    pub terminal_backend: edgecrab_tools::tools::backends::BackendKind,
    pub terminal_docker: edgecrab_tools::tools::backends::DockerBackendConfig,
    pub terminal_ssh: edgecrab_tools::tools::backends::SshBackendConfig,
    pub terminal_modal: edgecrab_tools::tools::backends::ModalBackendConfig,
    pub terminal_daytona: edgecrab_tools::tools::backends::DaytonaBackendConfig,
    pub terminal_singularity: edgecrab_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,
    /// 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,
}

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,
            model_config: crate::config::ModelConfig::default(),
            skills_config: crate::config::SkillsConfig::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: 50,
            terminal_backend: edgecrab_tools::tools::backends::BackendKind::Local,
            terminal_docker: edgecrab_tools::tools::backends::DockerBackendConfig::default(),
            terminal_ssh: edgecrab_tools::tools::backends::SshBackendConfig::default(),
            terminal_modal: edgecrab_tools::tools::backends::ModalBackendConfig::default(),
            terminal_daytona: edgecrab_tools::tools::backends::DaytonaBackendConfig::default(),
            terminal_singularity:
                edgecrab_tools::tools::backends::SingularityBackendConfig::default(),
            compression: crate::config::CompressionConfig::default(),
            auxiliary: crate::config::AuxiliaryConfig::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(),
        }
    }
}

#[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 = edgecrab_tools::toolsets::expand_toolset_names(&config.enabled_toolsets);
    let expanded_disabled =
        edgecrab_tools::toolsets::expand_toolset_names(&config.disabled_toolsets);
    let parent_active_toolsets = if config.enabled_toolsets.is_empty()
        || edgecrab_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
    }

    pub(crate) fn to_app_config_ref(
        &self,
        gateway_running: bool,
        tool_policy: &ResolvedToolPolicy,
    ) -> AppConfigRef {
        AppConfigRef {
            edgecrab_home: crate::config::edgecrab_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_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(),
            preloaded_skills: self.skills_config.preloaded.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,
            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()),
            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>,
    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,
    pub session_tool_call_count: u32,
}

/// 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,
    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<edgecrab_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>>,
    ) -> 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());

        Self {
            config: RwLock::new(config),
            provider: RwLock::new(provider),
            state_db,
            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()),
        }
    }

    /// 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);
    }

    /// 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((platform.to_string(), chat_id.to_string()));
            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((platform.to_string(), chat_id.to_string()));
            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> {
        let streaming_enabled = {
            let config = self.config.read().await;
            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)
            .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,
        )
        .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),
        )
        .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 mut config = self.config.read().await.clone();
        let provider = self.provider.read().await.clone();
        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;

        let child = Self::build_runtime_clone(
            config,
            provider,
            self.state_db.clone(),
            self.tool_registry.clone(),
        );
        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();
    }

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

    /// Reset session state for a new conversation.
    pub async fn new_session(&self) {
        // 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 = {
            let cfg = self.config.read().await;
            cfg.terminal_env_passthrough.clone()
        };
        edgecrab_tools::tools::backends::local::clear_env_passthrough();
        if !passthrough.is_empty() {
            edgecrab_tools::tools::backends::local::register_env_passthrough(&passthrough);
        }

        let mut session = self.session.write().await;
        *session = SessionState::default();
        self.budget.reset();
    }

    /// 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;
        }
    }

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

    /// 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()
    }

    /// 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;
    }

    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;
    }

    /// 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,
        );
        session.messages =
            crate::compression::compress_with_llm(&session.messages, &params, &provider).await;
    }

    /// 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);
        }
    }

    /// 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)?
            .ok_or_else(|| AgentError::Config(format!("Session not found: {id}")))?;
        let messages = db.get_messages(id)?;

        {
            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, edgecrab_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 fn list_sessions(
        &self,
        limit: usize,
    ) -> Result<Vec<edgecrab_state::SessionSummary>, AgentError> {
        match &self.state_db {
            Some(db) => db.list_sessions(limit),
            None => Ok(Vec::new()),
        }
    }

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

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

    /// Prune old ended sessions. Returns the number of sessions deleted.
    pub 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),
            None => Err(AgentError::Config("No state database configured".into())),
        }
    }

    /// 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 async fn state_db(&self) -> Option<Arc<SessionDb>> {
        self.state_db.clone()
    }

    /// Return a clone of the state DB handle without requiring an async hop.
    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 {
            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 {
            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 Some(registry) = &self.tool_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 = edgecrab_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: self.tool_registry.clone(),
            delegate_depth: 0,
            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,
            tool_progress_tx: None,
        };
        registry.tool_inventory(&ctx)
    }

    /// 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 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();
    }

    /// 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 {
        if self.last_prompt_tokens > 0 {
            self.last_prompt_tokens
        } else {
            self.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),
    /// 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,
    },
    /// 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 response 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 edgecrab-core into edgecrab-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,
    },
}

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::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,
            } => write!(
                f,
                "SubAgentStart({}/{}, {:?})",
                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::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})"
            ),
        }
    }
}

// ─── 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>>,
}

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,
        }
    }

    /// 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 {
                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(),
                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,
                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(),
                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(),
                ..Default::default()
            },
            provider: None,
            state_db: None,
            tool_registry: 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 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((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
    }

    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,
        ))
    }
}

// ─── 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 edgecrab_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()])
        }
    }

    #[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]
    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(&tmp.path().join("sessions.db")).expect("db"));
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let session = edgecrab_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()),
        };
        db.save_session(&session).expect("save session");
        db.save_message("restore-me", &Message::user("hello"), 1.0)
            .expect("save user");
        db.save_message("restore-me", &Message::assistant("hi"), 2.0)
            .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")
        );
    }
}