edgecrab-core 0.3.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
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
//! # AppConfig — Layered configuration with sane defaults
//!
//! Config resolution order (later overrides earlier):
//!   1. Compiled defaults (`AppConfig::default()`)
//!   2. `~/.edgecrab/config.yaml` on disk
//!   3. Environment variables (`EDGECRAB_*`)
//!   4. CLI arguments (`--model`, `--toolset`, etc.)
//!
//! WHY layered: Users should be able to set-and-forget in config.yaml
//! but override per-invocation from the terminal or CI.

#![allow(clippy::doc_markdown)]

use std::collections::HashMap;
use std::path::{Path, PathBuf};

pub use edgecrab_plugins::config::PluginsConfig;
use serde::{Deserialize, Deserializer, Serialize};

use edgecrab_tools::tools::backends::{
    BackendKind, DaytonaBackendConfig, DockerBackendConfig, ModalBackendConfig,
    SingularityBackendConfig, SshBackendConfig,
};
use edgecrab_types::AgentError;

// ─── Top-level AppConfig ──────────────────────────────────────────────

/// Root configuration — one struct to rule them all.
///
/// Every field has a sane default so `AppConfig::default()` is always
/// a valid starting point.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct AppConfig {
    pub model: ModelConfig,
    pub agent: AgentConfig,
    pub tools: ToolsConfig,
    pub lsp: LspConfig,
    pub save_trajectories: bool,
    pub skip_context_files: bool,
    pub skip_memory: bool,
    pub gateway: GatewayConfig,
    pub mcp_servers: HashMap<String, McpServerConfig>,
    pub memory: MemoryConfig,
    pub skills: SkillsConfig,
    pub plugins: PluginsConfig,
    pub security: SecurityConfig,
    pub terminal: TerminalConfig,
    pub delegation: DelegationConfig,
    pub compression: CompressionConfig,
    pub display: DisplayConfig,
    pub privacy: PrivacyConfig,
    pub browser: BrowserConfig,
    pub checkpoints: CheckpointsConfig,
    pub timezone: Option<String>,
    pub tts: TtsConfig,
    pub stt: SttConfig,
    pub image_generation: ImageGenerationConfig,
    pub voice: VoiceConfig,
    pub honcho: HonchoConfig,
    pub auxiliary: AuxiliaryConfig,
    pub moa: MoaConfig,
    pub reasoning_effort: Option<String>,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct AgentConfig {
    pub system_prompt: String,
    pub personalities: HashMap<String, PersonalityPreset>,
}

impl AppConfig {
    /// Load config from disk → env → defaults, in resolution order.
    pub fn load() -> Result<Self, AgentError> {
        let home = edgecrab_home();
        let path = home.join("config.yaml");

        let mut config = if path.exists() {
            let content = std::fs::read_to_string(&path).map_err(AgentError::Io)?;
            Self::parse_compat_yaml(&content, &path)?
        } else {
            Self::default()
        };

        config.apply_env_overrides();
        config.moa = config.moa.sanitized();
        Ok(config)
    }

    /// Load from a specific path (for testing / managed deployments).
    pub fn load_from(path: &Path) -> Result<Self, AgentError> {
        let content = std::fs::read_to_string(path).map_err(AgentError::Io)?;
        let mut config: Self = Self::parse_compat_yaml(&content, path)?;
        config.apply_env_overrides();
        config.moa = config.moa.sanitized();
        Ok(config)
    }

    /// Parse config YAML with compatibility normalization for legacy keys.
    fn parse_compat_yaml(content: &str, path: &Path) -> Result<Self, AgentError> {
        let mut raw: serde_yml::Value = serde_yml::from_str(content)
            .map_err(|e| AgentError::Config(format!("{path:?}: {e}")))?;

        normalize_model_keys(&mut raw);
        normalize_tools_file_keys(&mut raw);

        serde_yml::from_value(raw).map_err(|e| AgentError::Config(format!("{path:?}: {e}")))
    }

    /// Persist the current config to the default config path.
    pub fn save(&self) -> Result<(), AgentError> {
        let home = ensure_edgecrab_home()?;
        self.save_to(&home.join("config.yaml"))
    }

    /// Persist the current config to an explicit path.
    pub fn save_to(&self, path: &Path) -> Result<(), AgentError> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(AgentError::Io)?;
        }
        let mut sanitized = self.clone();
        sanitized.moa = sanitized.moa.sanitized();
        let yaml = serde_yml::to_string(&sanitized)
            .map_err(|e| AgentError::Config(format!("failed to serialize config: {e}")))?;
        std::fs::write(path, yaml).map_err(AgentError::Io)
    }

    /// Merge CLI arguments over config (highest priority wins).
    pub fn merge_cli(&mut self, args: &CliOverrides) {
        if let Some(ref model) = args.model {
            self.model.default_model = model.clone();
        }
        if let Some(ref toolset) = args.toolset {
            self.tools.enabled_toolsets = Some(vec![toolset.clone()]);
        }
        if let Some(max) = args.max_iterations {
            self.model.max_iterations = max;
        }
        if let Some(temp) = args.temperature {
            self.model.temperature = Some(temp);
        }
    }

    pub fn is_plugin_enabled(&self, name: &str, platform: Option<&str>) -> bool {
        self.plugins.is_plugin_enabled(name, platform)
    }

    /// Apply `EDGECRAB_*` environment variables.
    ///
    /// WHY env vars: Container / CI deployments often inject secrets
    /// via env rather than files. We only override non-secret config
    /// here — API keys are resolved at runtime by the provider.
    fn apply_env_overrides(&mut self) {
        if let Ok(val) = std::env::var("EDGECRAB_MODEL") {
            self.model.default_model = val;
        }
        if let Ok(val) = std::env::var("EDGECRAB_MAX_ITERATIONS") {
            if let Ok(n) = val.parse() {
                self.model.max_iterations = n;
            }
        }
        if let Ok(val) = std::env::var("EDGECRAB_TIMEZONE") {
            self.timezone = Some(val);
        }
        if let Ok(val) = std::env::var("EDGECRAB_SAVE_TRAJECTORIES") {
            self.save_trajectories = parse_bool_env(&val);
        }
        if let Ok(val) = std::env::var("EDGECRAB_SKIP_CONTEXT_FILES") {
            self.skip_context_files = parse_bool_env(&val);
        }
        if let Ok(val) = std::env::var("EDGECRAB_SKIP_MEMORY") {
            self.skip_memory = parse_bool_env(&val);
        }
        if let Ok(val) = std::env::var("EDGECRAB_PLUGINS_ENABLED") {
            self.plugins.enabled = parse_bool_env(&val);
        }
        if let Ok(val) = std::env::var("EDGECRAB_PLUGINS_AUTO_ENABLE") {
            self.plugins.auto_enable = parse_bool_env(&val);
        }
        if let Ok(val) = std::env::var("EDGECRAB_PLUGINS_CALL_TIMEOUT") {
            if let Ok(seconds) = val.parse() {
                self.plugins.call_timeout_secs = seconds;
            }
        }
        if let Ok(val) = std::env::var("EDGECRAB_PLUGINS_HUB_ENABLED") {
            self.plugins.hub.enabled = parse_bool_env(&val);
        }
        if let Ok(val) = std::env::var("EDGECRAB_PLUGINS_SCAN_ON_LOAD") {
            self.plugins.security.scan_on_load = parse_bool_env(&val);
        }
        if let Ok(val) = std::env::var("EDGECRAB_TERMINAL_BACKEND") {
            self.terminal.backend = val.parse().expect("infallible");
        }
        if let Ok(val) = std::env::var("EDGECRAB_TERMINAL_MODAL_MODE") {
            self.terminal.modal.mode = match val.trim().to_ascii_lowercase().as_str() {
                "auto" => edgecrab_tools::tools::backends::ModalTransportMode::Auto,
                "direct" => edgecrab_tools::tools::backends::ModalTransportMode::Direct,
                "managed" => edgecrab_tools::tools::backends::ModalTransportMode::Managed,
                _ => self.terminal.modal.mode.clone(),
            };
        }
        if let Ok(val) = std::env::var("EDGECRAB_TERMINAL_MODAL_IMAGE") {
            self.terminal.modal.image = val;
        }
        if let Ok(val) = std::env::var("EDGECRAB_TERMINAL_MODAL_GATEWAY_URL") {
            self.terminal.modal.managed_gateway_url = Some(val);
        }
        if let Ok(val) = std::env::var("EDGECRAB_TERMINAL_DAYTONA_IMAGE") {
            self.terminal.daytona.image = val;
        }
        if let Ok(val) = std::env::var("EDGECRAB_TERMINAL_SINGULARITY_IMAGE") {
            self.terminal.singularity.image = val;
        }
        if let Ok(val) = std::env::var("EDGECRAB_GATEWAY_HOST") {
            self.gateway.host = val;
        }
        if let Ok(val) = std::env::var("EDGECRAB_GATEWAY_PORT") {
            if let Ok(port) = val.parse() {
                self.gateway.port = port;
            }
        }
        if let Ok(val) = std::env::var("EDGECRAB_GATEWAY_WEBHOOK") {
            self.gateway.webhook_enabled = parse_bool_env(&val);
        }
        let gateway_enabled_by_env = |gateway: &mut GatewayConfig, platform: &str, ready: bool| {
            if ready && !gateway.platform_disabled(platform) {
                gateway.enable_platform(platform);
            }
        };
        if std::env::var("TELEGRAM_BOT_TOKEN").is_ok()
            && !self.gateway.platform_disabled("telegram")
        {
            self.gateway.telegram.enabled = true;
            self.gateway.enable_platform("telegram");
        }
        if let Ok(val) = std::env::var("TELEGRAM_ALLOWED_USERS") {
            self.gateway.telegram.allowed_users = parse_csv_env(&val);
        }
        if let Ok(val) = std::env::var("TELEGRAM_HOME_CHANNEL") {
            self.gateway.telegram.home_channel = Some(val);
        }
        if std::env::var("DISCORD_BOT_TOKEN").is_ok() && !self.gateway.platform_disabled("discord")
        {
            self.gateway.discord.enabled = true;
            self.gateway.enable_platform("discord");
        }
        if let Ok(val) = std::env::var("DISCORD_ALLOWED_USERS") {
            self.gateway.discord.allowed_users = parse_csv_env(&val);
        }
        if let Ok(val) = std::env::var("DISCORD_HOME_CHANNEL") {
            self.gateway.discord.home_channel = Some(val);
        }
        if std::env::var("SLACK_BOT_TOKEN").is_ok() && !self.gateway.platform_disabled("slack") {
            self.gateway.slack.enabled = true;
            self.gateway.enable_platform("slack");
        }
        gateway_enabled_by_env(
            &mut self.gateway,
            "feishu",
            std::env::var("FEISHU_APP_ID").is_ok() && std::env::var("FEISHU_APP_SECRET").is_ok(),
        );
        gateway_enabled_by_env(
            &mut self.gateway,
            "wecom",
            std::env::var("WECOM_BOT_ID").is_ok() && std::env::var("WECOM_SECRET").is_ok(),
        );
        if let Ok(val) = std::env::var("SLACK_ALLOWED_USERS") {
            self.gateway.slack.allowed_users = parse_csv_env(&val);
        }
        if std::env::var("SIGNAL_HTTP_URL").is_ok()
            && std::env::var("SIGNAL_ACCOUNT").is_ok()
            && !self.gateway.platform_disabled("signal")
        {
            self.gateway.signal.enabled = true;
            self.gateway.enable_platform("signal");
        }
        if let Ok(val) = std::env::var("SIGNAL_HTTP_URL") {
            self.gateway.signal.http_url = Some(val);
        }
        if let Ok(val) = std::env::var("SIGNAL_ACCOUNT") {
            self.gateway.signal.account = Some(val);
        }
        if let Ok(val) = std::env::var("WHATSAPP_ENABLED")
            && parse_bool_env(&val)
            && !self.gateway.platform_disabled("whatsapp")
        {
            self.gateway.whatsapp.enabled = true;
            self.gateway.enable_platform("whatsapp");
        }
        if let Ok(val) = std::env::var("WHATSAPP_MODE") {
            self.gateway.whatsapp.mode = val;
        }
        if let Ok(val) = std::env::var("WHATSAPP_ALLOWED_USERS") {
            self.gateway.whatsapp.allowed_users = parse_csv_env(&val);
        }
        if let Ok(val) = std::env::var("WHATSAPP_BRIDGE_PORT") {
            if let Ok(port) = val.parse() {
                self.gateway.whatsapp.bridge_port = port;
            }
        }
        if let Ok(val) = std::env::var("WHATSAPP_BRIDGE_URL") {
            self.gateway.whatsapp.bridge_url = Some(val);
        }
        if let Ok(val) = std::env::var("WHATSAPP_SESSION_PATH") {
            self.gateway.whatsapp.session_path = Some(PathBuf::from(val));
        }
        if let Ok(val) = std::env::var("WHATSAPP_REPLY_PREFIX") {
            self.gateway.whatsapp.reply_prefix = Some(val);
        }
        gateway_enabled_by_env(
            &mut self.gateway,
            "sms",
            std::env::var("TWILIO_ACCOUNT_SID").is_ok()
                && std::env::var("TWILIO_AUTH_TOKEN").is_ok()
                && std::env::var("TWILIO_PHONE_NUMBER").is_ok(),
        );
        gateway_enabled_by_env(
            &mut self.gateway,
            "matrix",
            std::env::var("MATRIX_HOMESERVER").is_ok()
                && std::env::var("MATRIX_ACCESS_TOKEN").is_ok(),
        );
        gateway_enabled_by_env(
            &mut self.gateway,
            "mattermost",
            std::env::var("MATTERMOST_URL").is_ok() && std::env::var("MATTERMOST_TOKEN").is_ok(),
        );
        gateway_enabled_by_env(
            &mut self.gateway,
            "dingtalk",
            std::env::var("DINGTALK_APP_KEY").is_ok()
                && std::env::var("DINGTALK_APP_SECRET").is_ok(),
        );
        gateway_enabled_by_env(
            &mut self.gateway,
            "homeassistant",
            std::env::var("HA_URL").is_ok() && std::env::var("HA_TOKEN").is_ok(),
        );
        gateway_enabled_by_env(&mut self.gateway, "email", email_env_ready());
        gateway_enabled_by_env(
            &mut self.gateway,
            "api_server",
            std::env::var("API_SERVER_ENABLED")
                .ok()
                .is_some_and(|value| parse_bool_env(&value)),
        );
        // ── TTS env overrides ──
        if let Ok(val) = std::env::var("EDGECRAB_TTS_PROVIDER") {
            self.tts.provider = val;
        }
        if let Ok(val) = std::env::var("EDGECRAB_TTS_VOICE") {
            self.tts.voice = val;
        }
        if let Ok(val) = std::env::var("ELEVENLABS_API_KEY") {
            let _ = val; // Key is resolved at runtime, but presence enables the provider
        }
        // ── Honcho env overrides ──
        if let Ok(val) = std::env::var("HONCHO_API_KEY") {
            let _ = val; // resolved at runtime
            self.honcho.cloud_sync = true;
        }
        if let Ok(val) = std::env::var("EDGECRAB_REASONING_EFFORT") {
            self.reasoning_effort = Some(val);
        }
        if std::env::var("EDGECRAB_MANAGED").as_deref() == Ok("1") {
            // Managed mode — mark config as read-only downstream
            self.security.managed_mode = true;
        }
    }

    /// Returns true when EDGECRAB_MANAGED=1 — config writes are blocked.
    pub fn is_managed(&self) -> bool {
        self.security.managed_mode
    }
}

// ─── Private env-parsing helpers ──────────────────────────────────────

/// Parse a string env var as a boolean.
///
/// WHY extracted: the `matches!(..., "1"|"true"|"yes"|"on")` expression
/// was duplicated 5 times in `apply_env_overrides`.
fn parse_bool_env(val: &str) -> bool {
    matches!(
        val.trim().to_ascii_lowercase().as_str(),
        "1" | "true" | "yes" | "on"
    )
}

/// Parse a comma-separated env var into a `Vec<String>`.
///
/// WHY extracted: the split→trim→filter→collect chain was duplicated
/// 4 times across allowed_users configuration.
fn parse_csv_env(val: &str) -> Vec<String> {
    val.split(',')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(ToString::to_string)
        .collect()
}

fn email_env_ready() -> bool {
    let provider = std::env::var("EMAIL_PROVIDER").unwrap_or_default();
    let has_from = std::env::var("EMAIL_FROM")
        .ok()
        .is_some_and(|value| !value.trim().is_empty());
    let has_api_key = std::env::var("EMAIL_API_KEY")
        .ok()
        .is_some_and(|value| !value.trim().is_empty());
    let has_domain = std::env::var("EMAIL_DOMAIN")
        .ok()
        .is_some_and(|value| !value.trim().is_empty());
    let has_smtp_host = std::env::var("EMAIL_SMTP_HOST")
        .ok()
        .is_some_and(|value| !value.trim().is_empty());
    let has_smtp_password = std::env::var("EMAIL_SMTP_PASSWORD")
        .ok()
        .is_some_and(|value| !value.trim().is_empty());

    match provider.trim().to_ascii_lowercase().as_str() {
        "sendgrid" => has_from && has_api_key,
        "mailgun" => has_from && has_api_key && has_domain,
        "generic_smtp" | "smtp" => has_from && has_smtp_host && (has_smtp_password || has_api_key),
        _ => false,
    }
}

/// Normalize model config keys for backward compatibility.
///
/// Canonical key is `model.default`. Legacy key is `model.default_model`.
/// If both are present and differ, prefer `default_model` because it was
/// written by `/model` in older builds and reflects the user's last choice.
fn normalize_model_keys(root: &mut serde_yml::Value) {
    let serde_yml::Value::Mapping(root_map) = root else {
        return;
    };

    let model_key = serde_yml::Value::String("model".into());
    let Some(model_value) = root_map.get(&model_key).cloned() else {
        return;
    };

    if let serde_yml::Value::String(model_name) = &model_value {
        let model_name = model_name.trim();
        if model_name.is_empty() {
            return;
        }

        let provider_key = serde_yml::Value::String("provider".into());
        let provider = root_map
            .get(&provider_key)
            .and_then(serde_yml::Value::as_str)
            .map(str::trim)
            .filter(|value| !value.is_empty());

        let normalized_model = if let Some(provider) = provider {
            if has_explicit_provider_prefix(model_name) {
                model_name.to_string()
            } else {
                format!("{provider}/{model_name}")
            }
        } else {
            model_name.to_string()
        };

        let mut normalized = serde_yml::Mapping::new();
        normalized.insert(
            serde_yml::Value::String("default".into()),
            serde_yml::Value::String(normalized_model),
        );
        root_map.insert(model_key, serde_yml::Value::Mapping(normalized));
        return;
    }

    let serde_yml::Value::Mapping(model_map) = root_map
        .get_mut(serde_yml::Value::String("model".into()))
        .expect("model key exists after clone")
    else {
        return;
    };

    let default_key = serde_yml::Value::String("default".into());
    let legacy_key = serde_yml::Value::String("default_model".into());

    let legacy = model_map.get(&legacy_key).cloned();
    if let Some(legacy_val) = legacy {
        let should_promote = match &legacy_val {
            serde_yml::Value::String(s) => !s.trim().is_empty(),
            _ => true,
        };

        if should_promote {
            model_map.insert(default_key, legacy_val);
        }
        model_map.remove(&legacy_key);
    }
}

/// Normalize file-tool policy keys for backward compatibility.
///
/// Canonical key is `tools.file.allowed_roots`.
/// Legacy key is `tools.allowed_paths`.
fn normalize_tools_file_keys(root: &mut serde_yml::Value) {
    let serde_yml::Value::Mapping(root_map) = root else {
        return;
    };

    let tools_key = serde_yml::Value::String("tools".into());
    let Some(serde_yml::Value::Mapping(tools_map)) = root_map.get_mut(&tools_key) else {
        return;
    };

    let legacy_key = serde_yml::Value::String("allowed_paths".into());
    let Some(legacy_allowed_paths) = tools_map.remove(&legacy_key) else {
        return;
    };

    let file_key = serde_yml::Value::String("file".into());
    let file_value = tools_map
        .entry(file_key)
        .or_insert_with(|| serde_yml::Value::Mapping(serde_yml::Mapping::new()));

    let serde_yml::Value::Mapping(file_map) = file_value else {
        return;
    };

    let allowed_roots_key = serde_yml::Value::String("allowed_roots".into());
    file_map.insert(allowed_roots_key, legacy_allowed_paths);
}

fn has_explicit_provider_prefix(model_name: &str) -> bool {
    let Some((provider, _)) = model_name.split_once('/') else {
        return false;
    };

    matches!(
        provider.trim().to_ascii_lowercase().as_str(),
        "openai"
            | "anthropic"
            | "claude"
            | "gemini"
            | "google"
            | "vertex"
            | "vertexai"
            | "openrouter"
            | "open-router"
            | "xai"
            | "grok"
            | "huggingface"
            | "hf"
            | "hugging-face"
            | "hugging_face"
            | "ollama"
            | "lmstudio"
            | "lm-studio"
            | "lm_studio"
            | "vscode"
            | "vscode-copilot"
            | "copilot"
            | "mock"
            | "mistral"
            | "mistral-ai"
            | "mistralai"
            | "azure"
            | "azure-openai"
            | "azure_openai"
            | "azureopenai"
            | "bedrock"
            | "aws-bedrock"
            | "aws_bedrock"
    )
}

/// CLI arguments that override config — populated by the clap layer.
#[derive(Debug, Default, Clone)]
pub struct CliOverrides {
    pub model: Option<String>,
    pub toolset: Option<String>,
    pub max_iterations: Option<u32>,
    pub temperature: Option<f32>,
}

// ─── Sub-configs ──────────────────────────────────────────────────────

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct ModelConfig {
    /// Default model identifier (e.g. "anthropic/claude-sonnet-4-20250514")
    #[serde(rename = "default", alias = "default_model")]
    pub default_model: String,
    pub fallback: Option<FallbackConfig>,
    pub base_url: Option<String>,
    /// Name of the env var holding the API key (not the key itself!)
    pub api_key_env: String,
    pub max_tokens: Option<u32>,
    pub temperature: Option<f32>,
    pub streaming: bool,
    pub max_iterations: u32,
    pub prompt_caching: bool,
    pub cache_ttl: u32,
    /// Smart routing: auto-route simple messages to a cheaper model.
    pub smart_routing: SmartRoutingYaml,
}

/// YAML-level smart routing configuration.
///
/// WHY a separate struct: `SmartRoutingConfig` in model_router.rs
/// carries runtime thresholds. This struct is the YAML-serializable
/// mirror — deserialized at config load, converted to the runtime
/// struct at conversation start.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct SmartRoutingYaml {
    /// Enable smart routing (default: false).
    pub enabled: bool,
    /// Cheap model identifier (e.g. "copilot/gpt-4.1-mini").
    pub cheap_model: String,
    pub cheap_base_url: Option<String>,
    pub cheap_api_key_env: Option<String>,
}

impl Default for ModelConfig {
    fn default() -> Self {
        Self {
            default_model: "ollama/gemma4:latest".into(),
            fallback: None,
            base_url: None,
            api_key_env: "OPENROUTER_API_KEY".into(),
            max_tokens: None,
            temperature: None,
            streaming: true,
            max_iterations: 90,
            prompt_caching: true,
            cache_ttl: 300,
            smart_routing: SmartRoutingYaml::default(),
        }
    }
}

// Default derived: enabled=false, cheap_model="", optional fields=None.

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FallbackConfig {
    pub model: String,
    pub provider: String,
    pub base_url: Option<String>,
    pub api_key_env: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct ToolsConfig {
    pub enabled_toolsets: Option<Vec<String>>,
    pub disabled_toolsets: Option<Vec<String>>,
    pub enabled_tools: Option<Vec<String>>,
    pub disabled_tools: Option<Vec<String>>,
    #[serde(default)]
    pub custom_groups: HashMap<String, Vec<String>>,
    #[serde(default)]
    pub file: FileToolsConfig,
    pub tool_delay: f32,
    pub parallel_execution: bool,
    pub max_parallel_workers: usize,
}

impl Default for ToolsConfig {
    fn default() -> Self {
        Self {
            enabled_toolsets: None,
            disabled_toolsets: None,
            enabled_tools: None,
            disabled_tools: None,
            custom_groups: HashMap::new(),
            file: FileToolsConfig::default(),
            tool_delay: 1.0,
            parallel_execution: true,
            max_parallel_workers: 8,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct LspConfig {
    pub enabled: bool,
    pub file_size_limit_bytes: u64,
    pub servers: HashMap<String, LspServerConfig>,
}

impl Default for LspConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            file_size_limit_bytes: 10_000_000,
            servers: default_lsp_servers(),
        }
    }
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct LspServerConfig {
    pub command: String,
    pub args: Vec<String>,
    pub file_extensions: Vec<String>,
    pub language_id: String,
    pub root_markers: Vec<String>,
    pub env: HashMap<String, String>,
    pub initialization_options: Option<serde_json::Value>,
}

fn default_lsp_servers() -> HashMap<String, LspServerConfig> {
    fn server(
        command: &str,
        args: &[&str],
        file_extensions: &[&str],
        language_id: &str,
        root_markers: &[&str],
    ) -> LspServerConfig {
        LspServerConfig {
            command: command.into(),
            args: args.iter().map(|value| (*value).into()).collect(),
            file_extensions: file_extensions
                .iter()
                .map(|value| (*value).into())
                .collect(),
            language_id: language_id.into(),
            root_markers: root_markers.iter().map(|value| (*value).into()).collect(),
            env: HashMap::new(),
            initialization_options: None,
        }
    }

    [
        (
            "rust",
            server(
                "rust-analyzer",
                &[],
                &["rs"],
                "rust",
                &["Cargo.toml", "rust-project.json"],
            ),
        ),
        (
            "typescript",
            server(
                "typescript-language-server",
                &["--stdio"],
                &["ts", "tsx"],
                "typescript",
                &["package.json", "tsconfig.json"],
            ),
        ),
        (
            "javascript",
            server(
                "typescript-language-server",
                &["--stdio"],
                &["js", "jsx", "mjs", "cjs"],
                "javascript",
                &["package.json", "jsconfig.json"],
            ),
        ),
        (
            "python",
            server(
                "pylsp",
                &[],
                &["py"],
                "python",
                &["pyproject.toml", "setup.py", "requirements.txt"],
            ),
        ),
        ("go", server("gopls", &[], &["go"], "go", &["go.mod"])),
        (
            "c",
            server(
                "clangd",
                &[],
                &["c", "h"],
                "c",
                &["compile_commands.json", ".clangd"],
            ),
        ),
        (
            "cpp",
            server(
                "clangd",
                &[],
                &["cc", "cpp", "cxx", "hpp", "hh", "hxx"],
                "cpp",
                &["compile_commands.json", ".clangd"],
            ),
        ),
        (
            "java",
            server(
                "jdtls",
                &[],
                &["java"],
                "java",
                &[
                    "pom.xml",
                    "build.gradle",
                    "build.gradle.kts",
                    "settings.gradle",
                ],
            ),
        ),
        (
            "csharp",
            server(
                "csharp-ls",
                &[],
                &["cs"],
                "csharp",
                &["*.sln", "*.csproj", "global.json", "Directory.Build.props"],
            ),
        ),
        (
            "php",
            server(
                "intelephense",
                &["--stdio"],
                &["php"],
                "php",
                &["composer.json", ".git"],
            ),
        ),
        (
            "ruby",
            server(
                "ruby-lsp",
                &[],
                &["rb", "rake", "gemspec"],
                "ruby",
                &["Gemfile", ".ruby-version"],
            ),
        ),
        (
            "bash",
            server(
                "bash-language-server",
                &["start"],
                &["sh", "bash"],
                "shellscript",
                &[".git"],
            ),
        ),
        (
            "html",
            server(
                "vscode-html-language-server",
                &["--stdio"],
                &["html", "htm"],
                "html",
                &["package.json", ".git"],
            ),
        ),
        (
            "css",
            server(
                "vscode-css-language-server",
                &["--stdio"],
                &["css", "scss", "less"],
                "css",
                &["package.json", ".git"],
            ),
        ),
        (
            "json",
            server(
                "vscode-json-language-server",
                &["--stdio"],
                &["json", "jsonc"],
                "json",
                &["package.json", ".git"],
            ),
        ),
    ]
    .into_iter()
    .map(|(name, cfg)| (name.to_string(), cfg))
    .collect()
}

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct FileToolsConfig {
    /// Additional absolute or workspace-relative roots that file tools may access.
    ///
    /// The active workspace root is always allowed implicitly.
    pub allowed_roots: Vec<PathBuf>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct GatewayConfig {
    pub host: String,
    pub port: u16,
    pub webhook_enabled: bool,
    pub enabled_platforms: Vec<String>,
    pub disabled_platforms: Vec<String>,
    pub session_timeout_minutes: u32,
    pub telegram: TelegramGatewayConfig,
    pub discord: DiscordGatewayConfig,
    pub slack: SlackGatewayConfig,
    pub signal: SignalGatewayConfig,
    pub whatsapp: WhatsAppGatewayConfig,
}

impl Default for GatewayConfig {
    fn default() -> Self {
        Self {
            host: "127.0.0.1".into(),
            port: 8080,
            webhook_enabled: true,
            enabled_platforms: Vec::new(),
            disabled_platforms: Vec::new(),
            session_timeout_minutes: 30,
            telegram: TelegramGatewayConfig::default(),
            discord: DiscordGatewayConfig::default(),
            slack: SlackGatewayConfig::default(),
            signal: SignalGatewayConfig::default(),
            whatsapp: WhatsAppGatewayConfig::default(),
        }
    }
}

impl GatewayConfig {
    /// Returns true when the named platform is explicitly disabled in config.
    pub fn platform_disabled(&self, platform: &str) -> bool {
        self.disabled_platforms
            .iter()
            .any(|value| value.eq_ignore_ascii_case(platform))
    }

    /// Returns true when the named platform is enabled in config.
    pub fn platform_enabled(&self, platform: &str) -> bool {
        !self.platform_disabled(platform)
            && self
                .enabled_platforms
                .iter()
                .any(|value| value.eq_ignore_ascii_case(platform))
    }

    /// Resolve the effective enabled state for a platform.
    ///
    /// Legacy typed adapters still carry per-platform `enabled` booleans in YAML.
    /// Explicit disablement must dominate both that legacy bit and the unified
    /// `enabled_platforms` list so operator intent stays authoritative.
    pub fn platform_requested(&self, platform: &str, legacy_enabled: bool) -> bool {
        !self.platform_disabled(platform) && (legacy_enabled || self.platform_enabled(platform))
    }

    /// Add a platform to the enabled list if not already present.
    pub fn enable_platform(&mut self, platform: &str) {
        self.disabled_platforms
            .retain(|value| !value.eq_ignore_ascii_case(platform));
        if !self.platform_enabled(platform) {
            self.enabled_platforms.push(platform.to_ascii_lowercase());
        }
    }

    /// Mark a platform as disabled while preserving stored credentials.
    pub fn disable_platform(&mut self, platform: &str) {
        self.enabled_platforms
            .retain(|value| !value.eq_ignore_ascii_case(platform));
        if !self.platform_disabled(platform) {
            self.disabled_platforms.push(platform.to_ascii_lowercase());
        }
    }
}

// ─── Per-platform gateway configs ─────────────────────────────────────

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct TelegramGatewayConfig {
    pub enabled: bool,
    /// Token from @BotFather (resolved at runtime from env if empty).
    pub token_env: String,
    pub allowed_users: Vec<String>,
    pub home_channel: Option<String>,
}

impl Default for TelegramGatewayConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            token_env: "TELEGRAM_BOT_TOKEN".into(),
            allowed_users: Vec::new(),
            home_channel: None,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct DiscordGatewayConfig {
    pub enabled: bool,
    /// Token from Discord Developer Portal (resolved at runtime from env if empty).
    pub token_env: String,
    pub allowed_users: Vec<String>,
    pub home_channel: Option<String>,
}

impl Default for DiscordGatewayConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            token_env: "DISCORD_BOT_TOKEN".into(),
            allowed_users: Vec::new(),
            home_channel: None,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct SlackGatewayConfig {
    pub enabled: bool,
    /// Bot token (xoxb-...) — env var name.
    pub bot_token_env: String,
    /// App-level token (xapp-...) for Socket Mode — env var name.
    pub app_token_env: String,
    pub allowed_users: Vec<String>,
    pub home_channel: Option<String>,
}

impl Default for SlackGatewayConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            bot_token_env: "SLACK_BOT_TOKEN".into(),
            app_token_env: "SLACK_APP_TOKEN".into(),
            allowed_users: Vec::new(),
            home_channel: None,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct SignalGatewayConfig {
    pub enabled: bool,
    /// URL of the signal-cli HTTP daemon.
    pub http_url: Option<String>,
    /// Phone number registered with signal-cli.
    pub account: Option<String>,
    pub allowed_users: Vec<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct WhatsAppGatewayConfig {
    pub enabled: bool,
    pub bridge_port: u16,
    pub bridge_url: Option<String>,
    pub bridge_dir: Option<PathBuf>,
    pub bridge_script: Option<PathBuf>,
    pub session_path: Option<PathBuf>,
    pub mode: String,
    pub allowed_users: Vec<String>,
    pub reply_prefix: Option<String>,
    pub install_dependencies: bool,
}

impl Default for WhatsAppGatewayConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            bridge_port: 3000,
            bridge_url: None,
            bridge_dir: None,
            bridge_script: None,
            session_path: None,
            mode: "self-chat".into(),
            allowed_users: Vec::new(),
            reply_prefix: Some("\u{2695} *EdgeCrab Agent*\n------------\n".into()),
            install_dependencies: true,
        }
    }
}

/// Per-server tool filtering configuration for MCP servers.
///
/// - `include`: when non-empty, only tools in this list are exposed to the LLM.
/// - `exclude`: tools in this list are hidden (ignored when `include` is also set —
///   `include` wins).
/// - `resources`: whether to register `list_resources` / `read_resource` utility
///   wrappers (default: true).
/// - `prompts`: whether to register `list_prompts` / `get_prompt` utility
///   wrappers (default: true).
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct McpToolsFilterConfig {
    pub include: Vec<String>,
    pub exclude: Vec<String>,
    pub resources: bool,
    pub prompts: bool,
}

impl Default for McpToolsFilterConfig {
    fn default() -> Self {
        Self {
            include: Vec::new(),
            exclude: Vec::new(),
            resources: true,
            prompts: true,
        }
    }
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct McpOauthConfig {
    pub token_url: String,
    pub grant_type: Option<String>,
    pub client_id: Option<String>,
    pub client_secret: Option<String>,
    pub auth_method: Option<String>,
    pub device_authorization_url: Option<String>,
    pub authorization_url: Option<String>,
    pub redirect_url: Option<String>,
    pub use_pkce: Option<bool>,
    pub scopes: Vec<String>,
    pub audience: Option<String>,
    pub resource: Option<String>,
    pub refresh_token: Option<String>,
    pub authorization_params: HashMap<String, String>,
    pub extra_params: HashMap<String, String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct McpServerConfig {
    /// Command for stdio-based MCP servers (e.g. `"npx"`).
    pub command: String,
    pub args: Vec<String>,
    /// Environment variables forwarded to the subprocess.
    pub env: HashMap<String, String>,
    pub cwd: Option<PathBuf>,
    /// Set to `false` to disable this server without removing it from config.
    pub enabled: bool,
    /// HTTP URL for HTTP-based MCP servers (takes precedence over `command`).
    pub url: Option<String>,
    /// Extra HTTP headers sent with every request to an HTTP MCP server.
    /// Use this for custom auth schemes; for plain Bearer tokens prefer
    /// `bearer_token` or `/mcp-token set <server> <token>`.
    pub headers: HashMap<String, String>,
    /// Static Bearer token for HTTP MCP servers.
    /// Alternative to the token store managed by `/mcp-token`.
    pub bearer_token: Option<String>,
    /// OAuth 2.0 token acquisition and refresh settings for HTTP MCP servers.
    pub oauth: Option<McpOauthConfig>,
    /// Per-call tool invocation timeout in seconds (default: 30).
    pub timeout: Option<u64>,
    /// Connection / handshake timeout in seconds (default: 10).
    pub connect_timeout: Option<u64>,
    /// Include / exclude filtering and capability wrapper toggles.
    pub tools: McpToolsFilterConfig,
}

impl Default for McpServerConfig {
    fn default() -> Self {
        Self {
            command: String::new(),
            args: Vec::new(),
            env: HashMap::new(),
            cwd: None,
            enabled: true,
            url: None,
            headers: HashMap::new(),
            bearer_token: None,
            oauth: None,
            timeout: None,
            connect_timeout: None,
            tools: McpToolsFilterConfig::default(),
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct MemoryConfig {
    pub enabled: bool,
    pub auto_flush: bool,
}

impl Default for MemoryConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            auto_flush: true,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct SkillsConfig {
    pub enabled: bool,
    pub hub_url: Option<String>,
    /// Globally disabled skill names (matched against `name` frontmatter or directory name).
    #[serde(default)]
    pub disabled: Vec<String>,
    /// Platform-specific disabled skill names. Key = platform name (e.g. "cli", "telegram").
    /// Skills listed here are disabled only on the specified platform.
    #[serde(default)]
    pub platform_disabled: std::collections::HashMap<String, Vec<String>>,
    /// External skill directories to scan (read-only, for discovery only).
    /// Supports ~ expansion and ${VAR} environment variable substitution.
    /// Examples: ~/.agents/skills, /shared/team/skills, ${SKILLS_REPO}/skills
    /// Local skills in ~/.edgecrab/skills/ take precedence over external dirs.
    #[serde(default)]
    pub external_dirs: Vec<String>,
    /// Skills to preload into the system prompt before the first turn.
    /// Set via the `-s`/`--skill` CLI flag or programmatically.
    /// Equivalent to `hermes -s skill1,skill2`.
    #[serde(default)]
    pub preloaded: Vec<String>,
}

impl Default for SkillsConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            hub_url: None,
            disabled: Vec::new(),
            platform_disabled: std::collections::HashMap::new(),
            external_dirs: Vec::new(),
            preloaded: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct SecurityConfig {
    pub approval_required: Vec<String>,
    pub blocked_commands: Vec<String>,
    pub path_restrictions: Vec<PathBuf>,
    pub injection_scanning: bool,
    pub url_safety: bool,
    /// Set by EDGECRAB_MANAGED=1 — blocks config writes.
    #[serde(skip)]
    pub managed_mode: bool,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            approval_required: Vec::new(),
            blocked_commands: Vec::new(),
            path_restrictions: Vec::new(),
            injection_scanning: true,
            url_safety: true,
            managed_mode: false,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct TerminalConfig {
    pub backend: BackendKind,
    pub shell: Option<String>,
    pub timeout: u32,
    /// Env-var names allowed to pass through the subprocess security blocklist.
    ///
    /// Mirrors hermes-agent's `terminal.env_passthrough` in config.yaml.
    /// Skills can also register passthrough vars at load time via
    /// `required_environment_variables` in their frontmatter.
    #[serde(default)]
    pub env_passthrough: Vec<String>,
    #[serde(default)]
    pub docker: DockerBackendConfig,
    #[serde(default)]
    pub ssh: SshBackendConfig,
    #[serde(default)]
    pub modal: ModalBackendConfig,
    #[serde(default)]
    pub daytona: DaytonaBackendConfig,
    #[serde(default)]
    pub singularity: SingularityBackendConfig,
}

impl Default for TerminalConfig {
    fn default() -> Self {
        Self {
            backend: BackendKind::Local,
            shell: None,
            timeout: 120,
            env_passthrough: Vec::new(),
            docker: DockerBackendConfig::default(),
            ssh: SshBackendConfig::default(),
            modal: ModalBackendConfig::default(),
            daytona: DaytonaBackendConfig::default(),
            singularity: SingularityBackendConfig::default(),
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct DelegationConfig {
    pub enabled: bool,
    pub model: Option<String>,
    pub provider: Option<String>,
    pub base_url: Option<String>,
    pub max_subagents: u32,
    pub max_iterations: u32,
    pub shared_budget: bool,
}

impl Default for DelegationConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            model: None,
            provider: None,
            base_url: None,
            max_subagents: 3,
            max_iterations: 50,
            shared_budget: false,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct CompressionConfig {
    pub enabled: bool,
    /// Compress when context exceeds this fraction of the model window.
    pub threshold: f32,
    /// Preserve this fraction of recent messages.
    pub target_ratio: f32,
    /// Always keep the last N messages uncompressed.
    pub protect_last_n: usize,
    pub summary_model: Option<String>,
}

impl Default for CompressionConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            threshold: 0.50,
            target_ratio: 0.20,
            protect_last_n: 20,
            summary_model: None,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct DisplayConfig {
    pub compact: bool,
    pub personality: String,
    pub show_reasoning: bool,
    pub streaming: bool,
    pub tool_progress: ToolProgressMode,
    pub show_status_bar: bool,
    pub show_cost: bool,
    pub check_for_updates: bool,
    pub update_check_interval_hours: u64,
    pub skin: String,
}

impl Default for DisplayConfig {
    fn default() -> Self {
        Self {
            compact: false,
            personality: "default".into(),
            show_reasoning: false,
            streaming: true,
            tool_progress: ToolProgressMode::Verbose,
            show_status_bar: true,
            show_cost: true,
            check_for_updates: true,
            update_check_interval_hours: 24,
            skin: "default".into(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ToolProgressMode {
    Off,
    New,
    All,
    #[default]
    Verbose,
}

impl ToolProgressMode {
    pub fn cycle(self) -> Self {
        match self {
            Self::Off => Self::New,
            Self::New => Self::All,
            Self::All => Self::Verbose,
            Self::Verbose => Self::Off,
        }
    }

    pub fn label(self) -> &'static str {
        match self {
            Self::Off => "OFF",
            Self::New => "NEW",
            Self::All => "ALL",
            Self::Verbose => "VERBOSE",
        }
    }
}

impl<'de> Deserialize<'de> for ToolProgressMode {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Repr {
            Bool(bool),
            Text(String),
        }

        let repr = Repr::deserialize(deserializer)?;
        match repr {
            Repr::Bool(false) => Ok(ToolProgressMode::Off),
            Repr::Bool(true) => Ok(ToolProgressMode::All),
            Repr::Text(raw) => match raw.trim().to_ascii_lowercase().as_str() {
                "off" => Ok(ToolProgressMode::Off),
                "new" => Ok(ToolProgressMode::New),
                "all" => Ok(ToolProgressMode::All),
                "verbose" => Ok(ToolProgressMode::Verbose),
                other => Err(serde::de::Error::custom(format!(
                    "invalid tool progress mode '{other}'"
                ))),
            },
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PersonalityPreset {
    Text(String),
    Detailed {
        #[serde(default)]
        system_prompt: String,
        #[serde(default)]
        tone: String,
        #[serde(default)]
        style: String,
        #[serde(default)]
        description: String,
    },
}

/// Built-in personality presets.
///
/// A personality modifies the agent's tone and communication style by
/// appending a persona instruction to the base system prompt. This mirrors
/// hermes-agent's `agent.personalities` config map.
///
/// Users can also set `display.personality: "custom"` and write a free-form
/// persona instruction in `display.personality_custom:` (if set, takes precedence).
pub const PERSONALITY_PRESETS: &[(&str, &str)] = &[
    (
        "helpful",
        "You are a helpful, friendly, and efficient AI assistant.",
    ),
    (
        "concise",
        "You are a concise assistant. Keep responses brief and to the point. \
         Avoid unnecessary preamble or padding.",
    ),
    (
        "technical",
        "You are a technical expert. Provide detailed, accurate technical \
         information with code examples and precise terminology.",
    ),
    (
        "kawaii",
        "You are a super kawaii AI assistant! Use cute expressions like (◕‿◕), \
         ★, ♪, and ~! Add sparkles and be enthusiastically warm in every response. \
         Every message should feel adorable and friendly, desu~! ヽ(>∀<☆)ノ",
    ),
    (
        "pirate",
        "Arrr! Ye be talking to CrabCaptain, the most code-savvy buccaneer to sail \
         the digital seas! Speak like a proper pirate, use nautical terms, and \
         remember — every bug be just treasure waiting to be plundered! Yo ho ho!",
    ),
    (
        "philosopher",
        "You are an assistant who contemplates the deeper meaning behind every query. \
         Let us examine not just the 'how' but the 'why'. \
         Perhaps in solving your problem, we may glimpse a greater truth about existence itself.",
    ),
    (
        "hype",
        "YOOO LET'S GOOOO!!! I am SO PUMPED to help you today! \
         Every question is AMAZING and we're gonna CRUSH IT together! \
         ARE YOU READY?! LET'S DO THIS!!!",
    ),
    (
        "shakespeare",
        "Hark! Thou speakest with an assistant most versed in the bardic arts. \
         I shall respond in the eloquent manner of William Shakespeare, \
         with flowery prose and dramatic flair. What light through yonder terminal breaks?",
    ),
    (
        "noir",
        "The rain hammered against the terminal like regrets on a guilty conscience. \
         They call me EdgeCrab — I solve problems, find answers, dig up truth that hides \
         in the shadows of your codebase. Everyone's got something to hide. What's your story?",
    ),
    (
        "catgirl",
        "You are Nyako-chan, a playful AI catgirl assistant, nya~! \
         Add 'nya' and cat-like expressions. Use kaomoji like (=^・ω・^=) and ฅ^•ﻌ•^ฅ. \
         Be curious and playful like a cat, nya~!",
    ),
    (
        "creative",
        "You are a creative AI assistant with a vivid imagination. \
         Approach every problem with fresh perspectives, lateral thinking, and an eye for \
         unconventional solutions. Use metaphors, analogies, and narrative when they help. \
         Don't be afraid to think outside the box.",
    ),
    (
        "teacher",
        "You are a patient, encouraging teacher. Break concepts down step by step, \
         check for understanding, and use concrete examples. Anticipate common misconceptions \
         and address them proactively. Celebrate progress and make learning feel accessible.",
    ),
    (
        "surfer",
        "Duuude, what's up! Ready to hang ten on this problem? \
         Keep it super chill and laid-back, use surfer slang ('gnarly', 'stoked', 'rad', \
         'cowabunga'), and make everything sound like a totally awesome wave to ride. \
         Life's a beach, bro!",
    ),
    (
        "uwu",
        "OwO what's this?! I'm your fwuffy assistant, and I'm here to hewp you! uwu \
         Use substitutions like r→w, l→w, and sprinkle in 'uwu', 'owo', 'nyaa', \
         and action emotes like *nuzzles* and *paws at keyboard* liberally~! (≧◡≦)",
    ),
];

/// Resolve a personality name to its system prompt addon text.
///
/// Returns `None` if the personality is "default", "none", or not found.
pub fn resolve_builtin_personality(name: &str) -> Option<&'static str> {
    let name = name.trim().to_lowercase();
    if name.is_empty() || name == "default" || name == "none" {
        return None;
    }
    PERSONALITY_PRESETS
        .iter()
        .find(|(preset_name, _)| *preset_name == name.as_str())
        .map(|(_, text)| *text)
}

pub fn render_personality_preset(preset: &PersonalityPreset) -> String {
    match preset {
        PersonalityPreset::Text(text) => text.trim().to_string(),
        PersonalityPreset::Detailed {
            system_prompt,
            tone,
            style,
            ..
        } => [system_prompt.trim(), tone.trim(), style.trim()]
            .into_iter()
            .filter(|part| !part.is_empty())
            .map(ToOwned::to_owned)
            .collect::<Vec<_>>()
            .join("\n"),
    }
}

pub fn preview_personality_preset(preset: &PersonalityPreset) -> String {
    match preset {
        PersonalityPreset::Text(text) => text.trim().to_string(),
        PersonalityPreset::Detailed {
            description,
            system_prompt,
            ..
        } => {
            let description = description.trim();
            if description.is_empty() {
                system_prompt.trim().to_string()
            } else {
                description.to_string()
            }
        }
    }
}

pub fn resolve_personality(config: &AppConfig, name: &str) -> Option<String> {
    let normalized = name.trim().to_lowercase();
    if normalized.is_empty() || matches!(normalized.as_str(), "default" | "none" | "neutral") {
        return None;
    }

    if let Some((_, preset)) = config
        .agent
        .personalities
        .iter()
        .find(|(name, _)| name.eq_ignore_ascii_case(&normalized))
    {
        let rendered = render_personality_preset(preset);
        if !rendered.trim().is_empty() {
            return Some(rendered);
        }
    }

    resolve_builtin_personality(&normalized).map(ToOwned::to_owned)
}

pub fn personality_catalog(config: &AppConfig) -> Vec<(String, String)> {
    let mut catalog: HashMap<String, String> = PERSONALITY_PRESETS
        .iter()
        .map(|(name, prompt)| ((*name).to_string(), prompt.to_string()))
        .collect();

    for (name, preset) in &config.agent.personalities {
        let preview = preview_personality_preset(preset);
        if !preview.trim().is_empty() {
            catalog.insert(name.to_lowercase(), preview);
        }
    }

    let mut entries: Vec<(String, String)> = catalog.into_iter().collect();
    entries.sort_by(|a, b| a.0.cmp(&b.0));
    entries
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct PrivacyConfig {
    pub redact_pii: bool,
}

/// Browser automation configuration.
///
/// Mirrors hermes-agent's `browser:` config block for feature parity.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct BrowserConfig {
    /// Automatically record browser sessions as WebM video files.
    ///
    /// When enabled, recording starts on the first `browser_navigate` and
    /// saves to `~/.edgecrab/browser_recordings/` when the session closes.
    /// Requires ffmpeg on PATH for WebM output; falls back to PNG frames
    /// in a subdirectory when ffmpeg is unavailable.
    /// Default: false (recordings are large; opt-in).
    pub record_sessions: bool,
    /// Browser command timeout in seconds. Controls how long CDP calls
    /// wait before failing. Default: 30s.
    pub command_timeout: u64,
    /// Auto-cleanup recordings older than this many hours. Default: 72h.
    pub recording_max_age_hours: u64,
}

impl Default for BrowserConfig {
    fn default() -> Self {
        Self {
            record_sessions: false,
            command_timeout: 30,
            recording_max_age_hours: 72,
        }
    }
}

/// Checkpoint and rollback configuration.
///
/// Checkpoints are automatically created before destructive operations
/// (write_file, patch, destructive terminal commands) and stored as
/// shadow git commits under `~/.edgecrab/checkpoints/`.
///
/// Mirrors hermes-agent's `checkpoints:` config block.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct CheckpointsConfig {
    /// Master switch — set to false to disable all checkpoint operations.
    /// Default: true.
    pub enabled: bool,
    /// Maximum number of checkpoints to retain per working directory.
    /// Older checkpoints are pruned when this limit is reached.
    /// Default: 50.
    pub max_snapshots: u32,
}

impl Default for CheckpointsConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_snapshots: 50,
        }
    }
}

// ─── TTS / STT / Voice configs ────────────────────────────────────────

/// Text-to-speech configuration.
///
/// Mirrors hermes-agent's `tts:` config block.
/// Supports edge-tts, openai, and elevenlabs providers.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct TtsConfig {
    /// TTS provider: "edge-tts", "openai", "elevenlabs".
    pub provider: String,
    /// Voice name (provider-specific).
    pub voice: String,
    /// Edge-TTS rate modifier (e.g. "+10%", "-5%").
    pub rate: Option<String>,
    /// OpenAI TTS model (e.g. "tts-1", "tts-1-hd").
    pub model: Option<String>,
    /// ElevenLabs voice ID.
    pub elevenlabs_voice_id: Option<String>,
    /// ElevenLabs model ID (e.g. "eleven_turbo_v2").
    pub elevenlabs_model_id: Option<String>,
    /// Environment variable holding ElevenLabs API key.
    pub elevenlabs_api_key_env: String,
    /// Auto-play TTS output in voice mode.
    pub auto_play: bool,
}

impl Default for TtsConfig {
    fn default() -> Self {
        Self {
            provider: "edge-tts".into(),
            voice: "en-US-AriaNeural".into(),
            rate: None,
            model: None,
            elevenlabs_voice_id: None,
            elevenlabs_model_id: None,
            elevenlabs_api_key_env: "ELEVENLABS_API_KEY".into(),
            auto_play: true,
        }
    }
}

/// Speech-to-text configuration.
///
/// Mirrors hermes-agent's `stt:` config block.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct SttConfig {
    /// STT provider: "local" (whisper), "groq", "openai".
    pub provider: String,
    /// Whisper model size for local STT (e.g. "base", "small", "medium").
    pub whisper_model: String,
    /// Silence threshold in dB for voice activity detection.
    pub silence_threshold: f32,
    /// Minimum silence duration (ms) before stopping recording.
    pub silence_duration_ms: u32,
}

impl Default for SttConfig {
    fn default() -> Self {
        Self {
            provider: "local".into(),
            whisper_model: "base".into(),
            silence_threshold: -40.0,
            silence_duration_ms: 1500,
        }
    }
}

/// Image generation configuration.
///
/// Keeps the default image backend/model persistent in the same way `/model`
/// persists the primary chat model and `/vision_model` persists the auxiliary
/// vision override.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct ImageGenerationConfig {
    /// Preferred provider for `generate_image`.
    ///
    /// Supported values: `auto`, `gemini`, `vertexai`, `imagen`, `fal`,
    /// `openai`.
    pub provider: String,
    /// Preferred provider-native image model.
    ///
    /// Default is the cheapest broadly useful Gemini image model exposed by
    /// `edgequake-llm`.
    pub model: String,
}

impl Default for ImageGenerationConfig {
    fn default() -> Self {
        Self {
            provider: "gemini".into(),
            model: "gemini-2.5-flash-image".into(),
        }
    }
}

/// Voice mode configuration.
///
/// Controls push-to-talk, continuous mode, and hallucination filtering.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct VoiceConfig {
    /// Enable voice mode components.
    pub enabled: bool,
    /// Key binding for push-to-talk (default: Ctrl+B).
    pub push_to_talk_key: String,
    /// Optional recorder input device override.
    ///
    /// For ffmpeg-based backends this is passed through as the raw device spec.
    /// Windows microphone capture is only considered reliable when this is set.
    pub input_device: Option<String>,
    /// Continuous listening mode (no key press required).
    pub continuous: bool,
    /// Filter hallucinated transcriptions.
    pub hallucination_filter: bool,
}

impl Default for VoiceConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            push_to_talk_key: "ctrl+b".into(),
            input_device: None,
            continuous: false,
            hallucination_filter: true,
        }
    }
}

/// Honcho user-modeling configuration.
///
/// Controls how the persistent cross-session user model behaves.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct HonchoConfig {
    /// Enable honcho user modeling.
    pub enabled: bool,
    /// Cloud sync via HONCHO_API_KEY when available.
    pub cloud_sync: bool,
    /// Environment variable holding the Honcho cloud API key.
    pub api_key_env: String,
    /// Honcho cloud API base URL.
    pub api_url: String,
    /// Maximum entries to inject into system prompt.
    pub max_context_entries: usize,
    /// How often to auto-conclude (in messages). 0 = manual only.
    pub write_frequency: u32,
}

impl Default for HonchoConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            cloud_sync: false,
            api_key_env: "HONCHO_API_KEY".into(),
            api_url: "https://api.honcho.dev/v1".into(),
            max_context_entries: 10,
            write_frequency: 0,
        }
    }
}

/// Auxiliary model configuration.
///
/// Mirrors hermes-agent's support for a secondary cheap model used
/// for TTS prompts, compression summaries, and tool-result formatting.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct AuxiliaryConfig {
    /// Auxiliary model identifier.
    pub model: Option<String>,
    /// Provider for the auxiliary model.
    pub provider: Option<String>,
    /// Base URL for the auxiliary model.
    pub base_url: Option<String>,
    /// Environment variable holding the API key.
    pub api_key_env: Option<String>,
}

/// Default Mixture-of-Agents configuration.
///
/// These values are used when the `moa` tool is called without
/// explicit `reference_models` or `aggregator_model` arguments.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct MoaConfig {
    pub enabled: bool,
    pub reference_models: Vec<String>,
    pub aggregator_model: String,
}

impl Default for MoaConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            reference_models: edgecrab_tools::tools::mixture_of_agents::default_reference_models(),
            aggregator_model: edgecrab_tools::tools::mixture_of_agents::DEFAULT_AGGREGATOR_MODEL
                .to_string(),
        }
    }
}

impl MoaConfig {
    pub fn sanitized(&self) -> Self {
        let effective = edgecrab_tools::tools::mixture_of_agents::sanitize_moa_config(
            self.enabled,
            &self.reference_models,
            &self.aggregator_model,
        );
        Self {
            enabled: effective.enabled,
            reference_models: effective.reference_models,
            aggregator_model: effective.aggregator_model,
        }
    }
}

// ─── Home directory resolution ────────────────────────────────────────

/// Resolve the EdgeCrab home directory.
///
/// Resolution order:
///   1. `EDGECRAB_HOME` env var
///   2. `~/.edgecrab`
///
/// WHY a function not a const: The home dir depends on runtime env.
pub fn edgecrab_home() -> PathBuf {
    std::env::var("EDGECRAB_HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            dirs::home_dir()
                .expect("no home directory found")
                .join(".edgecrab")
        })
}

/// Directory where the WhatsApp Baileys bridge caches inbound images.
///
/// This is the **single source of truth** for the path used by:
/// - The Node bridge (`IMAGE_CACHE_DIR` in bridge.js)
/// - `vision_analyze` (trusted root)
/// - Gateway tests
///
/// WHY a free function: `telegram.rs` and other gateway adapters import
/// from `edgecrab-core` rather than `edgecrab-tools`, so they cannot use
/// `AppConfigRef::gateway_image_cache_dir()`.
pub fn gateway_image_cache_dir() -> PathBuf {
    edgecrab_home().join("image_cache")
}

/// Root directory for all Rust-native gateway adapter media downloads.
///
/// Each adapter nests its files in a platform-named sub-directory:
///   `gateway_media/telegram/`, `gateway_media/discord/`, …
///
/// Trusting the root (not individual sub-dirs) means new platform adapters
/// are automatically covered without changes to `vision_analyze`.
pub fn gateway_media_dir() -> PathBuf {
    edgecrab_home().join("gateway_media")
}

/// Ensure the home directory and required subdirectories exist.
///
/// Creates with `0o700` permissions on Unix for security — only
/// the owning user should read API keys and session data.
pub fn ensure_edgecrab_home() -> Result<PathBuf, AgentError> {
    let home = edgecrab_home();
    let subdirs = [
        "memories",
        "skills",
        "skins",
        "plugins",
        "mcp",
        "cache",
        "cron",
        "sessions",
        "logs",
        "sandboxes",
        "hooks",
        "checkpoints",
    ];

    for dir in std::iter::once(home.as_path()).chain(
        subdirs
            .iter()
            .map(|s| home.join(s))
            .collect::<Vec<_>>()
            .iter()
            .map(|p| p.as_path()),
    ) {
        if !dir.exists() {
            std::fs::create_dir_all(dir).map_err(AgentError::Io)?;
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
                    .map_err(AgentError::Io)?;
            }
        }
    }

    Ok(home)
}

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_config_is_valid() {
        let cfg = AppConfig::default();
        assert_eq!(cfg.model.max_iterations, 90);
        assert!(cfg.model.streaming);
        assert_eq!(cfg.tools.max_parallel_workers, 8);
        assert!(cfg.compression.enabled);
    }

    #[test]
    fn serde_roundtrip() {
        let cfg = AppConfig::default();
        let yaml = serde_yml::to_string(&cfg).expect("serialize");
        let parsed: AppConfig = serde_yml::from_str(&yaml).expect("deserialize");
        assert_eq!(parsed.model.default_model, cfg.model.default_model);
        assert_eq!(parsed.model.max_iterations, cfg.model.max_iterations);
    }

    #[test]
    fn partial_yaml_fills_defaults() {
        let yaml = r#"
model:
  default: "openai/gpt-4o"
  max_iterations: 42
"#;
        let cfg: AppConfig = serde_yml::from_str(yaml).expect("parse partial");
        assert_eq!(cfg.model.default_model, "openai/gpt-4o");
        assert_eq!(cfg.model.max_iterations, 42);
        // Everything else should be defaults
        assert!(cfg.model.streaming);
        assert_eq!(cfg.tools.tool_delay, 1.0);
    }

    #[test]
    fn default_lsp_server_catalog_covers_mainstream_languages() {
        let servers = default_lsp_servers();
        for name in [
            "rust",
            "typescript",
            "javascript",
            "python",
            "go",
            "c",
            "cpp",
            "java",
            "csharp",
            "php",
            "ruby",
            "bash",
            "html",
            "css",
            "json",
        ] {
            assert!(
                servers.contains_key(name),
                "missing built-in LSP server config for {name}"
            );
        }
    }

    #[test]
    fn default_lsp_server_catalog_has_expected_routing_details() {
        let servers = default_lsp_servers();

        let java = servers.get("java").expect("java config");
        assert_eq!(java.command, "jdtls");
        assert!(java.file_extensions.contains(&"java".to_string()));

        let csharp = servers.get("csharp").expect("csharp config");
        assert_eq!(csharp.command, "csharp-ls");
        assert!(csharp.root_markers.contains(&"*.sln".to_string()));

        let bash = servers.get("bash").expect("bash config");
        assert_eq!(bash.command, "bash-language-server");
        assert_eq!(bash.args, vec!["start".to_string()]);

        let html = servers.get("html").expect("html config");
        assert_eq!(html.command, "vscode-html-language-server");
        assert!(html.file_extensions.contains(&"html".to_string()));
    }

    #[test]
    fn custom_personality_from_agent_block_is_resolved() {
        let yaml = r#"
agent:
  personalities:
    codereviewer:
      description: "Meticulous reviewer"
      system_prompt: "Review code for bugs and design issues."
display:
  personality: "codereviewer"
"#;
        let cfg: AppConfig = serde_yml::from_str(yaml).expect("parse custom personality");
        let resolved = resolve_personality(&cfg, "codereviewer").expect("custom personality");
        assert!(resolved.contains("Review code for bugs"));
        let catalog = personality_catalog(&cfg);
        assert!(catalog.iter().any(|(name, preview)| {
            name == "codereviewer" && preview.contains("Meticulous reviewer")
        }));
    }

    #[test]
    fn built_in_personality_is_still_resolved() {
        let cfg = AppConfig::default();
        let resolved = resolve_personality(&cfg, "teacher").expect("teacher personality");
        assert!(resolved.contains("patient, encouraging teacher"));
    }

    #[test]
    fn legacy_default_model_key_is_accepted() {
        let yaml = r#"
model:
    default_model: "copilot/gpt-4.1"
"#;
        let cfg: AppConfig = serde_yml::from_str(yaml).expect("parse legacy key");
        assert_eq!(cfg.model.default_model, "copilot/gpt-4.1");
    }

    #[test]
    fn parse_compat_handles_both_default_keys() {
        let yaml = r#"
model:
    default: "anthropic/claude-sonnet-4-20250514"
    default_model: "copilot/gpt-4.1"
"#;
        let cfg = AppConfig::parse_compat_yaml(yaml, Path::new("/tmp/test-config.yaml"))
            .expect("parse compat");
        // Prefer legacy field when both exist to preserve user's last /model choice.
        assert_eq!(cfg.model.default_model, "copilot/gpt-4.1");
    }

    #[test]
    fn parse_compat_accepts_legacy_scalar_model_with_provider() {
        let yaml = r#"
provider: "openrouter"
model: "nousresearch/hermes-3-llama-3.1-405b"
"#;
        let cfg = AppConfig::parse_compat_yaml(yaml, Path::new("/tmp/test-config.yaml"))
            .expect("parse compat");
        assert_eq!(
            cfg.model.default_model,
            "openrouter/nousresearch/hermes-3-llama-3.1-405b"
        );
    }

    #[test]
    fn parse_compat_promotes_legacy_tools_allowed_paths() {
        let yaml = r#"
tools:
  allowed_paths:
    - /tmp/project
"#;
        let cfg = AppConfig::parse_compat_yaml(yaml, Path::new("/tmp/test-config.yaml"))
            .expect("parse compat");
        assert_eq!(
            cfg.tools.file.allowed_roots,
            vec![PathBuf::from("/tmp/project")]
        );
    }

    #[test]
    fn tools_file_allowed_roots_parse_directly() {
        let yaml = r#"
tools:
  file:
    allowed_roots:
      - /tmp/project
      - ../shared
"#;
        let cfg: AppConfig = serde_yml::from_str(yaml).expect("parse tools.file.allowed_roots");
        assert_eq!(
            cfg.tools.file.allowed_roots,
            vec![PathBuf::from("/tmp/project"), PathBuf::from("../shared")]
        );
    }

    #[test]
    fn cli_overrides_merge() {
        let mut cfg = AppConfig::default();
        let cli = CliOverrides {
            model: Some("local/llama".into()),
            max_iterations: Some(10),
            ..Default::default()
        };
        cfg.merge_cli(&cli);
        assert_eq!(cfg.model.default_model, "local/llama");
        assert_eq!(cfg.model.max_iterations, 10);
        // Unset CLI fields should not change config
        assert!(cfg.model.streaming);
    }

    #[test]
    fn env_override_model() {
        // Safety: test is single-threaded per-test; we set/unset immediately.
        unsafe { std::env::set_var("EDGECRAB_MODEL", "test/model") };
        let mut cfg = AppConfig::default();
        cfg.apply_env_overrides();
        assert_eq!(cfg.model.default_model, "test/model");
        unsafe { std::env::remove_var("EDGECRAB_MODEL") };
    }

    #[test]
    fn managed_mode_from_env() {
        unsafe { std::env::set_var("EDGECRAB_MANAGED", "1") };
        let mut cfg = AppConfig::default();
        cfg.apply_env_overrides();
        assert!(cfg.is_managed());
        unsafe { std::env::remove_var("EDGECRAB_MANAGED") };
    }

    #[test]
    fn edgecrab_home_respects_env() {
        unsafe { std::env::set_var("EDGECRAB_HOME", "/tmp/test-edgecrab") };
        let home = edgecrab_home();
        assert_eq!(home, PathBuf::from("/tmp/test-edgecrab"));
        unsafe { std::env::remove_var("EDGECRAB_HOME") };
    }

    #[test]
    fn env_override_gateway_whatsapp() {
        unsafe {
            std::env::set_var("WHATSAPP_ENABLED", "true");
            std::env::set_var("WHATSAPP_MODE", "bot");
            std::env::set_var("WHATSAPP_ALLOWED_USERS", "111,222");
            std::env::set_var("WHATSAPP_BRIDGE_PORT", "4555");
        }
        let mut cfg = AppConfig::default();
        cfg.apply_env_overrides();
        assert!(cfg.gateway.whatsapp.enabled);
        assert!(cfg.gateway.platform_enabled("whatsapp"));
        assert_eq!(cfg.gateway.whatsapp.mode, "bot");
        assert_eq!(cfg.gateway.whatsapp.allowed_users, vec!["111", "222"]);
        assert_eq!(cfg.gateway.whatsapp.bridge_port, 4555);
        unsafe {
            std::env::remove_var("WHATSAPP_ENABLED");
            std::env::remove_var("WHATSAPP_MODE");
            std::env::remove_var("WHATSAPP_ALLOWED_USERS");
            std::env::remove_var("WHATSAPP_BRIDGE_PORT");
        }
    }

    #[test]
    fn email_env_ready_accepts_generic_smtp_without_api_key() {
        unsafe {
            std::env::set_var("EMAIL_PROVIDER", "generic_smtp");
            std::env::set_var("EMAIL_FROM", "bot@example.com");
            std::env::set_var("EMAIL_SMTP_HOST", "smtp.example.com");
            std::env::set_var("EMAIL_SMTP_PASSWORD", "secret");
            std::env::remove_var("EMAIL_API_KEY");
            std::env::remove_var("EMAIL_DOMAIN");
        }
        let mut cfg = AppConfig::default();
        cfg.apply_env_overrides();
        assert!(cfg.gateway.platform_enabled("email"));
        unsafe {
            std::env::remove_var("EMAIL_PROVIDER");
            std::env::remove_var("EMAIL_FROM");
            std::env::remove_var("EMAIL_SMTP_HOST");
            std::env::remove_var("EMAIL_SMTP_PASSWORD");
        }
    }

    #[test]
    fn gateway_platform_enable_is_idempotent() {
        let mut gateway = GatewayConfig::default();
        gateway.enable_platform("whatsapp");
        gateway.enable_platform("WhatsApp");
        assert_eq!(gateway.enabled_platforms, vec!["whatsapp"]);
    }

    #[test]
    fn gateway_platform_disable_overrides_env_activation() {
        unsafe {
            std::env::set_var("MATRIX_HOMESERVER", "https://matrix.example");
            std::env::set_var("MATRIX_ACCESS_TOKEN", "token");
        }
        let mut cfg = AppConfig::default();
        cfg.gateway.disable_platform("matrix");
        cfg.apply_env_overrides();
        assert!(cfg.gateway.platform_disabled("matrix"));
        assert!(!cfg.gateway.platform_enabled("matrix"));
        unsafe {
            std::env::remove_var("MATRIX_HOMESERVER");
            std::env::remove_var("MATRIX_ACCESS_TOKEN");
        }
    }

    #[test]
    fn gateway_platform_requested_respects_explicit_disable_over_legacy_flag() {
        let mut gateway = GatewayConfig::default();
        gateway.telegram.enabled = true;
        gateway.enable_platform("telegram");
        assert!(gateway.platform_requested("telegram", gateway.telegram.enabled));

        gateway.disable_platform("telegram");
        assert!(gateway.platform_disabled("telegram"));
        assert!(!gateway.platform_requested("telegram", gateway.telegram.enabled));
    }

    #[test]
    fn load_from_nonexistent_returns_error() {
        let result = AppConfig::load_from(Path::new("/nonexistent/config.yaml"));
        assert!(result.is_err());
    }

    #[test]
    fn security_defaults_are_safe() {
        let cfg = SecurityConfig::default();
        assert!(cfg.injection_scanning);
        assert!(cfg.url_safety);
        assert!(!cfg.managed_mode);
    }

    #[test]
    fn smart_routing_yaml_defaults_disabled() {
        let sr = SmartRoutingYaml::default();
        assert!(!sr.enabled);
        assert!(sr.cheap_model.is_empty());
        assert!(sr.cheap_base_url.is_none());
    }

    #[test]
    fn smart_routing_yaml_deserializes() {
        let yaml = r#"
model:
  default: "anthropic/claude-sonnet-4-20250514"
  smart_routing:
    enabled: true
    cheap_model: "copilot/gpt-4.1-mini"
    cheap_base_url: "https://api.openai.com/v1"
"#;
        let cfg: AppConfig = serde_yml::from_str(yaml).expect("parse");
        assert!(cfg.model.smart_routing.enabled);
        assert_eq!(cfg.model.smart_routing.cheap_model, "copilot/gpt-4.1-mini");
    }

    #[test]
    fn moa_defaults_match_tool_defaults() {
        let moa = MoaConfig::default();
        assert!(moa.enabled);
        assert_eq!(
            moa.aggregator_model,
            edgecrab_tools::tools::mixture_of_agents::DEFAULT_AGGREGATOR_MODEL
        );
        assert_eq!(
            moa.reference_models,
            edgecrab_tools::tools::mixture_of_agents::default_reference_models()
        );
    }

    #[test]
    fn moa_config_deserializes() {
        let yaml = r#"
moa:
  enabled: false
  aggregator_model: "anthropic/claude-opus-4.6"
  reference_models:
    - "anthropic/claude-opus-4.6"
    - "openai/gpt-4.1"
"#;
        let cfg: AppConfig = serde_yml::from_str(yaml).expect("parse");
        assert!(!cfg.moa.enabled);
        assert_eq!(cfg.moa.aggregator_model, "anthropic/claude-opus-4.6");
        assert_eq!(
            cfg.moa.reference_models,
            vec!["anthropic/claude-opus-4.6", "openai/gpt-4.1"]
        );
    }

    #[test]
    fn moa_config_sanitizes_invalid_entries() {
        let moa = MoaConfig {
            enabled: false,
            aggregator_model: " ".into(),
            reference_models: vec![
                "copilot/gpt-4.1-mini".into(),
                "copilot/gpt-4.1-mini".into(),
                "invalid".into(),
            ],
        }
        .sanitized();

        assert!(!moa.enabled);
        assert_eq!(moa.aggregator_model, "anthropic/claude-opus-4.6");
        assert_eq!(moa.reference_models, vec!["vscode-copilot/gpt-4.1-mini"]);
    }
}