zeptoclaw 0.9.0

Ultra-lightweight personal AI assistant
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
//! Configuration type definitions for ZeptoClaw
//!
//! This module defines all configuration structs used throughout the framework.
//! All types implement serde traits for JSON serialization and have sensible defaults.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Project management backend selection.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ProjectBackend {
    /// GitHub Issues REST API.
    #[default]
    Github,
    /// Jira REST API v3.
    Jira,
    /// Linear GraphQL API.
    Linear,
}

/// Project management tool configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ProjectConfig {
    /// Backend to use (github, jira, linear).
    pub backend: ProjectBackend,
    /// Default project key/repo (e.g., "owner/repo" for GitHub, "PROJ" for Jira).
    pub default_project: String,
    /// Jira base URL (e.g., "https://your-org.atlassian.net").
    pub jira_url: String,
    /// Jira API token (base64 encoded "email:token").
    pub jira_token: Option<String>,
    /// GitHub personal access token.
    pub github_token: Option<String>,
    /// Linear API key.
    pub linear_api_key: Option<String>,
}

impl Default for ProjectConfig {
    fn default() -> Self {
        Self {
            backend: ProjectBackend::Github,
            default_project: String::new(),
            jira_url: String::new(),
            jira_token: None,
            github_token: None,
            linear_api_key: None,
        }
    }
}

/// Main configuration struct for ZeptoClaw
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[derive(Default)]
pub struct Config {
    /// Agent configuration (models, tokens, iterations)
    pub agents: AgentConfig,
    /// Channel configurations (Telegram, Discord, Slack, etc.)
    pub channels: ChannelsConfig,
    /// LLM provider configurations (Claude, OpenAI, OpenRouter, etc.)
    pub providers: ProvidersConfig,
    /// Gateway server configuration
    pub gateway: GatewayConfig,
    /// Tools configuration
    pub tools: ToolsConfig,
    /// Memory configuration
    pub memory: MemoryConfig,
    /// Heartbeat background task configuration
    pub heartbeat: HeartbeatConfig,
    /// Skills system configuration
    pub skills: SkillsConfig,
    /// Runtime configuration for container isolation
    pub runtime: RuntimeConfig,
    /// Containerized agent configuration
    pub container_agent: ContainerAgentConfig,
    /// Swarm / multi-agent delegation configuration
    pub swarm: SwarmConfig,
    /// Tool approval configuration
    pub approval: crate::tools::approval::ApprovalConfig,
    /// Plugin system configuration
    pub plugins: crate::plugins::types::PluginConfig,
    /// Telemetry export configuration
    pub telemetry: crate::utils::telemetry::TelemetryConfig,
    /// Cost tracking configuration
    pub cost: crate::utils::cost::CostConfig,
    /// Batch processing configuration
    pub batch: crate::batch::BatchConfig,
    /// Hook system configuration
    pub hooks: crate::hooks::HooksConfig,
    /// Safety layer configuration
    pub safety: crate::safety::SafetyConfig,
    /// Context compaction configuration
    pub compaction: CompactionConfig,
    /// MCP (Model Context Protocol) server configuration
    pub mcp: McpConfig,
    /// Routines (event/webhook/cron triggers) configuration
    pub routines: RoutinesConfig,
    /// Tunnel configuration for exposing local ports publicly
    pub tunnel: TunnelConfig,
    /// Stripe payment integration configuration.
    pub stripe: StripeConfig,
    /// LLM response cache configuration
    pub cache: CacheConfig,
    /// Agent mode configuration (observer/assistant/autonomous)
    pub agent_mode: crate::security::agent_mode::AgentModeConfig,
    /// Device pairing configuration (bearer token auth for gateway)
    pub pairing: PairingConfig,
    /// Session validation and repair behavior.
    pub session: SessionConfig,
    /// Custom CLI-defined tools (shell commands as agent tools).
    #[serde(default)]
    pub custom_tools: Vec<CustomToolDef>,
    /// Audio transcription configuration.
    pub transcription: TranscriptionConfig,
    /// Named tool profiles for per-channel/context tool filtering.
    /// Key = profile name, Value = None means all tools, Some(vec) means only those tools.
    #[serde(default)]
    pub tool_profiles: HashMap<String, Option<Vec<String>>>,
    /// Project management tool configuration (GitHub Issues, Jira, Linear).
    pub project: ProjectConfig,
    /// HTTP health server configuration.
    #[serde(default)]
    pub health: HealthConfig,
    /// Device event system configuration (USB hotplug monitoring).
    #[serde(default)]
    pub devices: DevicesConfig,
    /// Logging configuration (format, level, optional file output).
    #[serde(default)]
    pub logging: LoggingConfig,
    /// Panel (control panel) configuration.
    #[serde(default)]
    pub panel: PanelConfig,
    /// r8r workflow-engine bridge configuration.
    #[serde(default)]
    pub r8r_bridge: R8rBridgeConfig,
}

// ============================================================================
// Logging Configuration
// ============================================================================

/// Log output format.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum LogFormat {
    /// Default tracing pretty-print.
    Pretty,
    /// Component-tagged format — grep-friendly (`[component] message`).
    Component,
    /// Structured JSON lines for log aggregators.
    Json,
}

fn default_log_format() -> LogFormat {
    LogFormat::Component
}

fn default_log_level() -> String {
    "info".to_string()
}

/// Logging configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    /// Log output format (default: component).
    #[serde(default = "default_log_format")]
    pub format: LogFormat,
    /// Optional path to a log file. When set and format is `json`, logs are
    /// written to this file in addition to (or instead of) stdout.
    pub file: Option<String>,
    /// Log level filter string (default: "info").
    #[serde(default = "default_log_level")]
    pub level: String,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            format: default_log_format(),
            file: None,
            level: default_log_level(),
        }
    }
}

// ============================================================================
// Device Event System Configuration
// ============================================================================

/// Device event monitoring configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DevicesConfig {
    /// Enable device event monitoring (default: false).
    #[serde(default)]
    pub enabled: bool,
    /// Monitor USB hotplug events (default: false).
    #[serde(default)]
    pub monitor_usb: bool,
}

// ============================================================================
// Panel Configuration
// ============================================================================

/// Authentication mode for the panel.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AuthMode {
    /// Bearer token auth (default) — no login screen.
    #[default]
    Token,
    /// Username/password login with JWT session.
    Password,
    /// No authentication (localhost trust only).
    None,
}

/// Panel (control panel) configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PanelConfig {
    /// Whether the panel is enabled.
    pub enabled: bool,
    /// Port for the panel frontend (static files).
    pub port: u16,
    /// Port for the API server.
    pub api_port: u16,
    /// Authentication mode.
    pub auth_mode: AuthMode,
    /// Bind address (default: 127.0.0.1).
    pub bind: String,
}

impl Default for PanelConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            port: 9092,
            api_port: 9091,
            auth_mode: AuthMode::Token,
            bind: "127.0.0.1".to_string(),
        }
    }
}

// ============================================================================
// r8r Bridge Configuration
// ============================================================================

/// Channel target for routing r8r events to a specific messaging channel.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelTarget {
    /// Channel name (e.g. "telegram", "slack").
    pub channel: String,
    /// Chat/channel ID on that platform.
    pub chat_id: String,
}

/// Configuration for the r8r workflow-engine bridge.
///
/// When enabled, ZeptoClaw connects to an r8r instance over WebSocket to
/// receive workflow events (approvals, execution results, health) and send
/// back decisions and workflow triggers.
#[derive(Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct R8rBridgeConfig {
    /// Whether the r8r bridge is enabled.
    pub enabled: bool,
    /// WebSocket endpoint for the r8r event stream.
    pub endpoint: String,
    /// Bearer token for authenticating with r8r.
    pub token: Option<String>,
    /// Default channel target for events that have no specific routing.
    pub default_channel: Option<ChannelTarget>,
    /// Per-workflow approval routing overrides (workflow name -> channel target).
    #[serde(default)]
    pub approval_routing: HashMap<String, ChannelTarget>,
    /// Maximum reconnect backoff interval in seconds.
    pub reconnect_max_interval_secs: u64,
    /// Interval between health pings in seconds.
    pub health_ping_interval_secs: u64,
}

impl std::fmt::Debug for R8rBridgeConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("R8rBridgeConfig")
            .field("enabled", &self.enabled)
            .field("endpoint", &self.endpoint)
            .field("token", &self.token.as_ref().map(|_| "[REDACTED]"))
            .field("default_channel", &self.default_channel)
            .field("approval_routing", &self.approval_routing)
            .field(
                "reconnect_max_interval_secs",
                &self.reconnect_max_interval_secs,
            )
            .field("health_ping_interval_secs", &self.health_ping_interval_secs)
            .finish()
    }
}

impl Default for R8rBridgeConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            endpoint: "ws://localhost:8080/api/ws/events".to_string(),
            token: None,
            default_channel: None,
            approval_routing: HashMap::new(),
            reconnect_max_interval_secs: 30,
            health_ping_interval_secs: 60,
        }
    }
}

// ============================================================================
// Cache Configuration
// ============================================================================

/// LLM response cache configuration.
///
/// When enabled, caches LLM responses keyed by SHA-256 of
/// `(model, system_prompt, user_prompt)`. Supports TTL expiry and LRU eviction.
/// Persists to `~/.zeptoclaw/cache/responses.json`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CacheConfig {
    /// Whether the response cache is enabled.
    pub enabled: bool,
    /// Time-to-live for cache entries in seconds.
    pub ttl_secs: u64,
    /// Maximum number of cached entries before LRU eviction.
    pub max_entries: usize,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            ttl_secs: 3600,
            max_entries: 500,
        }
    }
}

// ============================================================================
// Pairing Configuration
// ============================================================================

/// Device pairing configuration.
///
/// When enabled, the gateway requires a valid bearer token from paired devices.
/// Devices are paired via a 6-digit one-time code exchanged for a bearer token.
/// Tokens are stored as SHA-256 hashes for security.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PairingConfig {
    /// Whether device pairing is required for gateway access.
    pub enabled: bool,
    /// Maximum failed pairing/validation attempts before lockout.
    pub max_attempts: u32,
    /// Duration in seconds to lock out after max_attempts is exceeded.
    pub lockout_secs: u64,
}

impl Default for PairingConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            max_attempts: 5,
            lockout_secs: 300,
        }
    }
}

/// Session validation and auto-repair configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SessionConfig {
    /// Automatically repair malformed conversation histories when loaded.
    pub auto_repair: bool,
}

impl Default for SessionConfig {
    fn default() -> Self {
        Self { auto_repair: true }
    }
}

// ============================================================================
// Health Server Configuration
// ============================================================================

fn default_health_host() -> String {
    "127.0.0.1".to_string()
}

fn default_health_port() -> u16 {
    9090
}

/// HTTP health server configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthConfig {
    /// Whether the health HTTP server is enabled (default: false).
    #[serde(default)]
    pub enabled: bool,
    /// Host/IP to bind the health server (default: 127.0.0.1).
    #[serde(default = "default_health_host")]
    pub host: String,
    /// Port to bind the health server (default: 9090).
    #[serde(default = "default_health_port")]
    pub port: u16,
}

impl Default for HealthConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            host: default_health_host(),
            port: default_health_port(),
        }
    }
}

// ============================================================================
// Compaction Configuration
// ============================================================================

/// Context compaction configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CompactionConfig {
    /// Whether automatic context compaction is enabled.
    pub enabled: bool,
    /// Maximum context window size in tokens.
    pub context_limit: usize,
    /// Fraction (0.0-1.0) of context_limit that triggers compaction.
    pub threshold: f64,
    /// Fraction (0.0-1.0) for emergency truncation mode.
    pub emergency_threshold: f64,
    /// Fraction (0.0-1.0) for critical hard-trim mode.
    pub critical_threshold: f64,
}

impl Default for CompactionConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            context_limit: 100_000,
            threshold: 0.70,
            emergency_threshold: 0.90,
            critical_threshold: 0.95,
        }
    }
}

// ============================================================================
// MCP Configuration
// ============================================================================

/// MCP (Model Context Protocol) server configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct McpConfig {
    /// MCP server definitions.
    pub servers: Vec<McpServerConfig>,
}

/// Configuration for a single MCP server.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpServerConfig {
    /// Human-readable server name (used as tool name prefix).
    pub name: String,
    /// Server URL endpoint (for HTTP transport).
    pub url: Option<String>,
    /// Server command (for stdio transport).
    pub command: Option<String>,
    /// Server command arguments (for stdio transport).
    pub args: Option<Vec<String>>,
    /// Environment variables for stdio server process.
    pub env: Option<std::collections::HashMap<String, String>>,
    /// Request timeout in seconds (default: 30).
    #[serde(default = "default_mcp_timeout")]
    pub timeout_secs: u64,
}

fn default_mcp_timeout() -> u64 {
    30
}

// ============================================================================
// Routines Configuration
// ============================================================================

/// Routines (event/webhook/cron triggers) configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RoutinesConfig {
    /// Whether the routines engine is enabled.
    pub enabled: bool,
    /// Cron tick interval in seconds.
    pub cron_interval_secs: u64,
    /// Maximum concurrent routine executions.
    pub max_concurrent: usize,
    /// Random jitter in milliseconds added to cron tick intervals.
    #[serde(default)]
    pub jitter_ms: u64,
    /// Policy for missed schedules when process restarts.
    #[serde(default)]
    pub on_miss: crate::cron::OnMiss,
}

impl Default for RoutinesConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            cron_interval_secs: 60,
            max_concurrent: 3,
            jitter_ms: 0,
            on_miss: crate::cron::OnMiss::Skip,
        }
    }
}

// ============================================================================
// Stripe Configuration
// ============================================================================

/// Stripe payment integration configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct StripeConfig {
    /// Stripe secret key (sk_live_... or sk_test_...). Supports ENC[...] encryption.
    pub secret_key: Option<String>,
    /// Default currency code for payment intents (e.g., "usd", "myr", "sgd").
    pub default_currency: String,
    /// Webhook signing secret for signature verification. Optional.
    pub webhook_secret: Option<String>,
}

impl Default for StripeConfig {
    fn default() -> Self {
        Self {
            secret_key: None,
            default_currency: "usd".to_string(),
            webhook_secret: None,
        }
    }
}

// ============================================================================
// Tunnel Configuration
// ============================================================================

/// Tunnel configuration for exposing local ports via public URLs.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct TunnelConfig {
    /// Tunnel provider name ("cloudflare", "ngrok", "tailscale", or "auto").
    pub provider: Option<String>,
    /// Cloudflare Tunnel configuration.
    pub cloudflare: Option<CloudflareTunnelConfig>,
    /// ngrok tunnel configuration.
    pub ngrok: Option<NgrokTunnelConfig>,
    /// Tailscale Funnel/Serve configuration.
    pub tailscale: Option<TailscaleTunnelConfig>,
}

/// Cloudflare Tunnel provider configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct CloudflareTunnelConfig {
    /// Cloudflare Tunnel token for named tunnels. If omitted, uses quick tunnel (trycloudflare.com).
    pub token: Option<String>,
}

/// ngrok tunnel provider configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct NgrokTunnelConfig {
    /// ngrok authtoken for authenticated tunnels.
    pub authtoken: Option<String>,
    /// Custom domain to use (requires ngrok paid plan).
    pub domain: Option<String>,
}

/// Tailscale Funnel/Serve provider configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct TailscaleTunnelConfig {
    /// Use Tailscale Funnel (public) instead of Serve (tailnet-only). Default: true.
    #[serde(default = "default_true")]
    pub funnel: bool,
}

impl Default for TailscaleTunnelConfig {
    fn default() -> Self {
        Self { funnel: true }
    }
}

fn default_true() -> bool {
    true
}

// ============================================================================
// Transcription Configuration
// ============================================================================

/// Configuration for audio transcription (voice messages).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct TranscriptionConfig {
    /// Whether to transcribe audio messages (default: true).
    pub enabled: bool,
    /// Whisper-compatible model name (default: "whisper-1").
    pub model: String,
}

impl Default for TranscriptionConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            model: "whisper-1".to_string(),
        }
    }
}

/// Agent configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[derive(Default)]
pub struct AgentConfig {
    /// Default agent settings
    pub defaults: AgentDefaults,
}

/// Configuration for the multi-layered tool loop guard.
///
/// Controls ping-pong detection, outcome-aware blocking, poll relaxation,
/// graduated responses, and backoff scheduling for repeated tool calls.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LoopGuardConfig {
    /// Master switch to enable/disable the loop guard.
    pub enabled: bool,
    /// Number of identical call hashes before emitting a warning.
    pub warn_threshold: u32,
    /// Number of identical call hashes before blocking the call.
    pub block_threshold: u32,
    /// Total repetitions across all hashes before tripping the circuit breaker.
    pub global_circuit_breaker: u32,
    /// Minimum repeated cycles required to detect ping-pong oscillation (period 2 or 3).
    pub ping_pong_min_repeats: u32,
    /// Threshold multiplier for commands matching poll/status patterns.
    pub poll_multiplier: u32,
    /// Number of identical outcome hashes before emitting a warning.
    pub outcome_warn_threshold: u32,
    /// Number of identical outcome hashes before blocking the call.
    pub outcome_block_threshold: u32,
    /// Sliding window size for recent call tracking. When the call sequence
    /// exceeds this limit, older entries are pruned and counters rebuilt to
    /// prevent unbounded memory growth and false-positive warnings.
    #[serde(default = "default_window_size")]
    pub window_size: u32,
}

fn default_window_size() -> u32 {
    200
}

impl Default for LoopGuardConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            warn_threshold: 3,
            block_threshold: 5,
            global_circuit_breaker: 30,
            ping_pong_min_repeats: 3,
            poll_multiplier: 3,
            outcome_warn_threshold: 2,
            outcome_block_threshold: 3,
            window_size: default_window_size(),
        }
    }
}

/// Default agent settings
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AgentDefaults {
    /// Workspace directory path
    pub workspace: String,
    /// Default model to use
    pub model: String,
    /// Maximum tokens for responses
    pub max_tokens: u32,
    /// Temperature for generation
    pub temperature: f32,
    /// Maximum tool iterations per turn
    pub max_tool_iterations: u32,
    /// Maximum wall-clock time (seconds) for a single agent run.
    pub agent_timeout_secs: u64,
    /// Maximum wall-clock time (seconds) for a single tool call. 0 = use agent_timeout_secs.
    pub tool_timeout_secs: u64,
    /// How to handle messages arriving during an active run.
    pub message_queue_mode: MessageQueueMode,
    /// Whether to stream the final LLM response token-by-token in CLI mode.
    pub streaming: bool,
    /// Per-session token budget (input + output). 0 = unlimited.
    pub token_budget: u64,
    /// Use compact (shorter) tool descriptions to save tokens.
    #[serde(default)]
    pub compact_tools: bool,
    /// Default tool profile name (from `tool_profiles`). Omit for all tools.
    #[serde(default)]
    pub tool_profile: Option<String>,
    /// Active hand package name (HAND.toml + SKILL.md) if selected.
    #[serde(default)]
    pub active_hand: Option<String>,
    /// IANA timezone for the agent (e.g., "Asia/Kuala_Lumpur", "US/Pacific").
    /// Used for time-aware system prompts and message timestamps.
    /// Defaults to system local timezone, falls back to "UTC".
    #[serde(default = "default_timezone")]
    pub timezone: String,
    /// Loop guard configuration for repeated tool-call detection.
    #[serde(default)]
    pub loop_guard: LoopGuardConfig,
    /// Maximum bytes allowed per tool result before truncation.
    #[serde(default = "default_max_tool_result_bytes")]
    pub max_tool_result_bytes: usize,
    /// Maximum total tool calls allowed per agent run. None = unlimited.
    #[serde(default)]
    pub max_tool_calls: Option<u32>,
    /// Custom system prompt injected into ContextBuilder. Takes priority over
    /// template and hand system prompts when set. Useful for gateway/headless
    /// mode where the system prompt must come from config, not CLI flags.
    #[serde(default)]
    pub system_prompt: Option<String>,
}

/// Detect the system's IANA timezone.
///
/// Priority: `TZ` env → `/etc/localtime` symlink → `"UTC"`.
fn default_timezone() -> String {
    if let Ok(tz) = std::env::var("TZ") {
        if !tz.is_empty() {
            return tz;
        }
    }
    #[cfg(unix)]
    {
        if let Ok(target) = std::fs::read_link("/etc/localtime") {
            let path = target.to_string_lossy();
            if let Some(pos) = path.find("zoneinfo/") {
                return path[pos + 9..].to_string();
            }
        }
    }
    "UTC".to_string()
}

fn default_max_tool_result_bytes() -> usize {
    crate::utils::sanitize::DEFAULT_MAX_RESULT_BYTES
}

/// Default model compile-time configuration.
/// Set `ZEPTOCLAW_DEFAULT_MODEL` at compile time to override.
const COMPILE_TIME_DEFAULT_MODEL: &str = match option_env!("ZEPTOCLAW_DEFAULT_MODEL") {
    Some(v) => v,
    None => "claude-sonnet-4-6",
};

impl Default for AgentDefaults {
    fn default() -> Self {
        Self {
            workspace: "~/.zeptoclaw/workspace".to_string(),
            model: COMPILE_TIME_DEFAULT_MODEL.to_string(),
            max_tokens: 8192,
            temperature: 0.7,
            max_tool_iterations: 20,
            agent_timeout_secs: 300,
            tool_timeout_secs: 0,
            message_queue_mode: MessageQueueMode::default(),
            streaming: true,
            token_budget: 0,
            compact_tools: false,
            tool_profile: None,
            active_hand: None,
            timezone: default_timezone(),
            loop_guard: LoopGuardConfig::default(),
            max_tool_result_bytes: default_max_tool_result_bytes(),
            max_tool_calls: None,
            system_prompt: None,
        }
    }
}

/// How to handle messages that arrive while an agent run is active.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum MessageQueueMode {
    /// Buffer messages, concatenate into one when current run finishes.
    #[default]
    Collect,
    /// Buffer messages, replay each as a separate run after current finishes.
    Followup,
}

// ============================================================================
// Channel Configurations
// ============================================================================

/// All channel configurations
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ChannelsConfig {
    /// Telegram bot configuration
    pub telegram: Option<TelegramConfig>,
    /// Discord bot configuration
    pub discord: Option<DiscordConfig>,
    /// Slack bot configuration
    pub slack: Option<SlackConfig>,
    /// WhatsApp Web native channel configuration (requires `whatsapp-web` feature).
    #[serde(alias = "whatsapp")]
    pub whatsapp_web: Option<WhatsAppWebConfig>,
    /// WhatsApp Cloud API configuration (official API, no bridge)
    pub whatsapp_cloud: Option<WhatsAppCloudConfig>,
    /// Feishu (Lark) configuration
    pub feishu: Option<FeishuConfig>,
    /// Lark/Feishu WS long-connection configuration
    pub lark: Option<LarkConfig>,
    /// MaixCam configuration
    pub maixcam: Option<MaixCamConfig>,
    /// QQ configuration
    pub qq: Option<QQConfig>,
    /// DingTalk configuration
    pub dingtalk: Option<DingTalkConfig>,
    /// Webhook inbound channel configuration
    pub webhook: Option<WebhookConfig>,
    /// Email channel configuration (IMAP IDLE + SMTP). Feature-gated behind channel-email.
    pub email: Option<EmailConfig>,
    /// Serial (UART) channel configuration. Requires `hardware` feature.
    pub serial: Option<SerialChannelConfig>,
    /// MQTT channel configuration. Requires `mqtt` feature.
    pub mqtt: Option<MqttChannelConfig>,
    /// ACP (Agent Client Protocol) stdio channel configuration.
    pub acp: Option<AcpChannelConfig>,
    /// Directory for channel plugins (default: ~/.zeptoclaw/channels/)
    #[serde(default)]
    pub channel_plugins_dir: Option<String>,
}

/// Serial (UART) channel configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SerialChannelConfig {
    /// Whether the channel is enabled.
    pub enabled: bool,
    /// Serial port path (e.g., "/dev/ttyUSB0", "COM3").
    pub port: String,
    /// Baud rate (default: 115200).
    pub baud_rate: u32,
    /// Allow only specific sender IDs.
    #[serde(default)]
    pub allow_from: Vec<String>,
    /// Deny all senders unless in allowlist.
    #[serde(default)]
    pub deny_by_default: bool,
}

impl Default for SerialChannelConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            port: String::new(),
            baud_rate: 115_200,
            allow_from: Vec::new(),
            deny_by_default: false,
        }
    }
}

/// ACP (Agent Client Protocol) channel configuration.
///
/// **Gateway mode (`zeptoclaw gateway`):** `enabled` has no effect here.
/// The ACP stdio transport is exclusively for `zeptoclaw acp`, where the process
/// is spawned as a subprocess by an ACP client (e.g. `acpx`). To expose ACP in
/// gateway mode, set `channels.acp.http.enabled = true` instead.
///
/// **`zeptoclaw acp`:** reads `allow_from`, `deny_by_default`, and `http` from
/// this config. The `enabled` field is accepted but ignored (the subcommand always
/// runs ACP stdio regardless).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct AcpChannelConfig {
    /// Accepted for backward compatibility but has no effect in gateway mode.
    /// `zeptoclaw acp` always starts ACP stdio regardless of this flag.
    #[serde(default)]
    pub enabled: bool,
    /// Allow only specific sender/client IDs (empty = allow all unless deny_by_default).
    #[serde(default)]
    pub allow_from: Vec<String>,
    /// When true, empty allow_from rejects all senders.
    #[serde(default)]
    pub deny_by_default: bool,
    /// Optional HTTP transport configuration. When present and enabled, the ACP
    /// HTTP channel is registered alongside (or instead of) the stdio channel.
    #[serde(default)]
    pub http: Option<AcpHttpConfig>,
    /// Optional session time-to-live in seconds. When set, idle sessions are
    /// reaped before the session cap is checked on each `session/new` call.
    #[serde(default)]
    pub session_ttl_secs: Option<u64>,
}

/// ACP streamable HTTP transport configuration.
///
/// When `channels.acp.http.enabled` is true, the gateway registers an HTTP
/// listener that accepts JSON-RPC 2.0 messages via `POST /acp`. `session/prompt`
/// responses are streamed back as Server-Sent Events; all other methods return
/// synchronous JSON responses. `channels.acp.enabled` is not required.
#[derive(Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AcpHttpConfig {
    /// Whether the HTTP transport is active.
    pub enabled: bool,
    /// TCP port to listen on. Default: 8765.
    pub port: u16,
    /// Bind address. Default: "127.0.0.1".
    pub bind: String,
    /// Optional Bearer token. When set, all requests must supply
    /// `Authorization: Bearer <token>`.
    pub auth_token: Option<String>,
}

impl std::fmt::Debug for AcpHttpConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AcpHttpConfig")
            .field("enabled", &self.enabled)
            .field("port", &self.port)
            .field("bind", &self.bind)
            .field(
                "auth_token",
                &self.auth_token.as_ref().map(|_| "<redacted>"),
            )
            .finish()
    }
}

impl Default for AcpHttpConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            port: 8765,
            bind: "127.0.0.1".to_string(),
            auth_token: None,
        }
    }
}

/// MQTT channel configuration for IoT device communication.
#[derive(Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MqttChannelConfig {
    /// Whether the channel is enabled.
    pub enabled: bool,
    /// MQTT broker URL (e.g., "mqtt://localhost:1883").
    pub broker_url: String,
    /// Client ID for the MQTT connection.
    pub client_id: String,
    /// Topics to subscribe to for inbound messages (e.g., ["zeptoclaw/inbox/#"]).
    pub subscribe_topics: Vec<String>,
    /// Topic prefix for publishing responses (e.g., "zeptoclaw/outbox").
    pub publish_prefix: String,
    /// QoS level (0 = at most once, 1 = at least once, 2 = exactly once).
    pub qos: u8,
    /// MQTT broker username (optional).
    #[serde(default)]
    pub username: String,
    /// MQTT broker password (optional).
    #[serde(default)]
    pub password: String,
    /// Allow only specific device/sender IDs.
    #[serde(default)]
    pub allow_from: Vec<String>,
    /// Deny all senders unless in allowlist.
    #[serde(default)]
    pub deny_by_default: bool,
}

impl Default for MqttChannelConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            broker_url: "mqtt://localhost:1883".to_string(),
            client_id: "zeptoclaw-agent".to_string(),
            subscribe_topics: vec!["zeptoclaw/inbox/#".to_string()],
            publish_prefix: "zeptoclaw/outbox".to_string(),
            qos: 1,
            username: String::new(),
            password: String::new(),
            allow_from: Vec::new(),
            deny_by_default: false,
        }
    }
}

impl std::fmt::Debug for MqttChannelConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MqttChannelConfig")
            .field("enabled", &self.enabled)
            .field("broker_url", &self.broker_url)
            .field("client_id", &self.client_id)
            .field("subscribe_topics", &self.subscribe_topics)
            .field("publish_prefix", &self.publish_prefix)
            .field("qos", &self.qos)
            .field("username", &self.username)
            .field("password", &"[redacted]")
            .field("allow_from", &self.allow_from)
            .field("deny_by_default", &self.deny_by_default)
            .finish()
    }
}

/// Webhook inbound channel configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// Address to bind the HTTP server to
    #[serde(default = "default_webhook_bind_address")]
    pub bind_address: String,
    /// Port to listen on
    #[serde(default = "default_webhook_port")]
    pub port: u16,
    /// URL path to accept webhook requests on
    #[serde(default = "default_webhook_path")]
    pub path: String,
    /// Optional Bearer token for request authentication
    #[serde(default)]
    pub auth_token: Option<String>,
    /// Optional HMAC secret for request signature verification.
    #[serde(default)]
    pub signature_secret: Option<String>,
    /// Header carrying the request HMAC signature when `signature_secret` is set.
    #[serde(default = "default_webhook_signature_header")]
    pub signature_header: String,
    /// Server-controlled sender ID used when `trust_payload_identity` is disabled.
    #[serde(default)]
    pub sender_id: Option<String>,
    /// Optional server-controlled chat ID used when `trust_payload_identity` is disabled.
    /// Falls back to `sender_id` when omitted.
    #[serde(default)]
    pub chat_id: Option<String>,
    /// When true, accept caller-supplied `sender` and `chat_id` from webhook JSON.
    #[serde(default)]
    pub trust_payload_identity: bool,
    /// Allowlist of sender IDs (empty = allow all unless `deny_by_default` is set)
    #[serde(default)]
    pub allow_from: Vec<String>,
    /// When true, empty `allow_from` rejects all senders (strict mode).
    #[serde(default)]
    pub deny_by_default: bool,
}

fn default_webhook_bind_address() -> String {
    "127.0.0.1".to_string()
}

fn default_webhook_port() -> u16 {
    9876
}

fn default_webhook_path() -> String {
    "/webhook".to_string()
}

fn default_webhook_signature_header() -> String {
    "X-ZeptoClaw-Signature-256".to_string()
}

impl Default for WebhookConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            bind_address: default_webhook_bind_address(),
            port: default_webhook_port(),
            path: default_webhook_path(),
            auth_token: None,
            signature_secret: None,
            signature_header: default_webhook_signature_header(),
            sender_id: None,
            chat_id: None,
            trust_payload_identity: false,
            allow_from: Vec::new(),
            deny_by_default: false,
        }
    }
}

fn default_telegram_allow_usernames() -> bool {
    true
}

fn default_telegram_reactions() -> bool {
    true
}

/// Telegram channel configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct TelegramConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// Bot token from BotFather
    pub token: String,
    /// Allowlist of numeric user IDs (empty = allow all unless `deny_by_default` is set).
    ///
    /// Legacy username entries are only honored when `allow_usernames` is true.
    #[serde(default)]
    pub allow_from: Vec<String>,
    /// When true, empty `allow_from` rejects all senders (strict mode).
    #[serde(default)]
    pub deny_by_default: bool,
    /// Legacy compatibility toggle for username-based allowlist entries.
    ///
    /// New configs should keep this disabled and use numeric Telegram user IDs only.
    #[serde(default = "default_telegram_allow_usernames")]
    pub allow_usernames: bool,
    /// Whether to show processing reactions (👀 on receipt, ✅ on completion).
    #[serde(default = "default_telegram_reactions")]
    pub reactions: bool,
}

impl Default for TelegramConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            token: String::new(),
            allow_from: Vec::new(),
            deny_by_default: false,
            allow_usernames: default_telegram_allow_usernames(),
            reactions: default_telegram_reactions(),
        }
    }
}

/// Discord channel configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DiscordConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// Bot token from Discord Developer Portal
    pub token: String,
    /// Allowlist of user IDs (empty = allow all unless `deny_by_default` is set)
    #[serde(default)]
    pub allow_from: Vec<String>,
    /// When true, empty `allow_from` rejects all senders (strict mode).
    #[serde(default)]
    pub deny_by_default: bool,
}

/// Slack channel configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SlackConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// Bot token (xoxb-...)
    pub bot_token: String,
    /// App-level token (xapp-...)
    pub app_token: String,
    /// Allowlist of user IDs (empty = allow all unless `deny_by_default` is set)
    #[serde(default)]
    pub allow_from: Vec<String>,
    /// When true, empty `allow_from` rejects all senders (strict mode).
    #[serde(default)]
    pub deny_by_default: bool,
}

/// WhatsApp Cloud API channel configuration (official Meta API).
///
/// Uses Meta's webhook system for inbound messages and the Cloud API
/// for outbound replies. Does not require the whatsmeow-rs bridge.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WhatsAppCloudConfig {
    /// Whether the channel is enabled.
    #[serde(default)]
    pub enabled: bool,
    /// Phone number ID from Meta Business dashboard.
    #[serde(default)]
    pub phone_number_id: String,
    /// Permanent access token for Cloud API.
    #[serde(default)]
    pub access_token: String,
    /// Webhook verify token (you choose this secret, must match Meta dashboard).
    #[serde(default)]
    pub webhook_verify_token: String,
    /// Optional Meta app secret used to verify `X-Hub-Signature-256` callback signatures.
    #[serde(default)]
    pub app_secret: Option<String>,
    /// Address to bind the webhook HTTP server to.
    #[serde(default = "default_whatsapp_cloud_bind")]
    pub bind_address: String,
    /// Port for the webhook HTTP server.
    #[serde(default = "default_whatsapp_cloud_port")]
    pub port: u16,
    /// URL path for the webhook endpoint.
    #[serde(default = "default_whatsapp_cloud_path")]
    pub path: String,
    /// Allowlist of phone numbers (empty = allow all unless `deny_by_default` is set).
    #[serde(default)]
    pub allow_from: Vec<String>,
    /// When true, empty `allow_from` rejects all senders (strict mode).
    #[serde(default)]
    pub deny_by_default: bool,
}

fn default_whatsapp_cloud_bind() -> String {
    "127.0.0.1".to_string()
}

fn default_whatsapp_cloud_port() -> u16 {
    9877
}

fn default_whatsapp_cloud_path() -> String {
    "/whatsapp".to_string()
}

impl Default for WhatsAppCloudConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            phone_number_id: String::new(),
            access_token: String::new(),
            webhook_verify_token: String::new(),
            app_secret: None,
            bind_address: default_whatsapp_cloud_bind(),
            port: default_whatsapp_cloud_port(),
            path: default_whatsapp_cloud_path(),
            allow_from: Vec::new(),
            deny_by_default: false,
        }
    }
}

/// WhatsApp Web native channel configuration (personal WhatsApp via QR pairing).
///
/// Uses wa-rs for direct WhatsApp Web protocol support. No Meta Business
/// account required — pairs via QR code like WhatsApp Desktop.
/// Requires: `--features whatsapp-web`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WhatsAppWebConfig {
    /// Whether the channel is enabled.
    #[serde(default)]
    pub enabled: bool,
    /// Directory for session persistence (SQLite database).
    /// Default: ~/.zeptoclaw/state/whatsapp_web
    #[serde(default = "default_whatsapp_web_auth_dir")]
    pub auth_dir: String,
    /// Allowlist of phone numbers in E.164 format (e.g., "+60123456789").
    /// Empty = allow all unless `deny_by_default` is set.
    #[serde(default)]
    pub allow_from: Vec<String>,
    /// When true, empty `allow_from` rejects all senders (strict mode).
    #[serde(default)]
    pub deny_by_default: bool,
}

fn default_whatsapp_web_auth_dir() -> String {
    "~/.zeptoclaw/state/whatsapp_web".to_string()
}

impl Default for WhatsAppWebConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            auth_dir: default_whatsapp_web_auth_dir(),
            allow_from: Vec::new(),
            deny_by_default: false,
        }
    }
}

/// Feishu (Lark) channel configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FeishuConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// App ID
    pub app_id: String,
    /// App Secret
    pub app_secret: String,
    /// Encrypt Key for event subscription
    #[serde(default)]
    pub encrypt_key: String,
    /// Verification Token
    #[serde(default)]
    pub verification_token: String,
    /// Allowlist of user IDs (empty = allow all unless `deny_by_default` is set)
    #[serde(default)]
    pub allow_from: Vec<String>,
    /// When true, empty `allow_from` rejects all senders (strict mode).
    #[serde(default)]
    pub deny_by_default: bool,
}

/// Lark (international) / Feishu (China) channel configuration.
///
/// Uses the Lark WS long-connection (pbbp2) for receiving events —
/// no public HTTPS endpoint required.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct LarkConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// Lark / Feishu application ID
    pub app_id: String,
    /// Lark / Feishu application secret
    pub app_secret: String,
    /// When true, use Feishu (open.feishu.cn); when false, use Lark (open.larksuite.com)
    #[serde(default)]
    pub feishu: bool,
    /// Allowlist of sender open_ids (empty = allow all unless deny_by_default)
    #[serde(default)]
    pub allowed_senders: Vec<String>,
    /// Bot's own open_id — messages from the bot itself are silently dropped
    #[serde(default)]
    pub bot_open_id: Option<String>,
    /// When true, empty allowed_senders rejects all senders (strict mode)
    #[serde(default)]
    pub deny_by_default: bool,
}

/// MaixCam channel configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaixCamConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// Host to bind to
    #[serde(default = "default_maixcam_host")]
    pub host: String,
    /// Port to listen on
    #[serde(default = "default_maixcam_port")]
    pub port: u16,
    /// Allowlist of device IDs (empty = allow all unless `deny_by_default` is set)
    #[serde(default)]
    pub allow_from: Vec<String>,
    /// When true, empty `allow_from` rejects all senders (strict mode).
    #[serde(default)]
    pub deny_by_default: bool,
}

fn default_maixcam_host() -> String {
    "0.0.0.0".to_string()
}

fn default_maixcam_port() -> u16 {
    18790
}

impl Default for MaixCamConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            host: default_maixcam_host(),
            port: default_maixcam_port(),
            allow_from: Vec::new(),
            deny_by_default: false,
        }
    }
}

/// QQ channel configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct QQConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// App ID
    pub app_id: String,
    /// App Secret
    pub app_secret: String,
    /// Allowlist of QQ numbers (empty = allow all unless `deny_by_default` is set)
    #[serde(default)]
    pub allow_from: Vec<String>,
    /// When true, empty `allow_from` rejects all senders (strict mode).
    #[serde(default)]
    pub deny_by_default: bool,
}

/// DingTalk channel configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DingTalkConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// Client ID
    pub client_id: String,
    /// Client Secret
    pub client_secret: String,
    /// Allowlist of user IDs (empty = allow all unless `deny_by_default` is set)
    #[serde(default)]
    pub allow_from: Vec<String>,
    /// When true, empty `allow_from` rejects all senders (strict mode).
    #[serde(default)]
    pub deny_by_default: bool,
}

// ============================================================================
// Provider Configurations
// ============================================================================

/// All LLM provider configurations
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ProvidersConfig {
    /// Anthropic Claude configuration
    pub anthropic: Option<ProviderConfig>,
    /// OpenAI configuration
    pub openai: Option<ProviderConfig>,
    /// OpenRouter configuration
    pub openrouter: Option<ProviderConfig>,
    /// Groq configuration
    pub groq: Option<ProviderConfig>,
    /// Zhipu (GLM) configuration
    pub zhipu: Option<ProviderConfig>,
    /// VLLM configuration
    pub vllm: Option<ProviderConfig>,
    /// Google Gemini configuration
    pub gemini: Option<ProviderConfig>,
    /// Google Vertex AI configuration (Gemini models via Vertex AI regional endpoints).
    /// `api_key` holds the GCP project ID, `api_base` holds the location (e.g. "us-central1").
    #[serde(default)]
    pub vertex: Option<ProviderConfig>,
    /// Ollama (local models) configuration
    pub ollama: Option<ProviderConfig>,
    /// Nvidia NIM configuration
    pub nvidia: Option<ProviderConfig>,
    /// DeepSeek configuration
    pub deepseek: Option<ProviderConfig>,
    /// Kimi (Moonshot AI) configuration
    pub kimi: Option<ProviderConfig>,
    /// Azure OpenAI configuration (OpenAI-compatible with api-key header).
    #[serde(default)]
    pub azure: Option<ProviderConfig>,
    /// Amazon Bedrock configuration (OpenAI-compatible endpoint; SigV4 required externally).
    #[serde(default)]
    pub bedrock: Option<ProviderConfig>,
    /// xAI (Grok) configuration (OpenAI-compatible).
    #[serde(default)]
    pub xai: Option<ProviderConfig>,
    /// Baidu Qianfan configuration (OpenAI-compatible v2 endpoint).
    #[serde(default)]
    pub qianfan: Option<ProviderConfig>,
    /// Novita AI configuration (OpenAI-compatible endpoint).
    #[serde(default)]
    pub novita: Option<ProviderConfig>,
    /// Retry behavior for runtime provider calls
    pub retry: RetryConfig,
    /// Fallback behavior across multiple configured runtime providers
    pub fallback: FallbackConfig,
    /// Provider rotation configuration for 3+ health-aware providers
    pub rotation: RotationConfig,
    /// External binary provider plugins (JSON-RPC 2.0 over stdin/stdout)
    #[serde(default)]
    pub plugins: Vec<ProviderPluginConfig>,
}

/// Generic provider configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProviderConfig {
    /// API key for authentication
    #[serde(default)]
    pub api_key: Option<String>,
    /// Custom API base URL
    #[serde(default)]
    pub api_base: Option<String>,
    /// Authentication method: "api_key" (default), "oauth", or "auto"
    #[serde(default)]
    pub auth_method: Option<String>,
    /// Per-provider model override. When set, this model is used instead of
    /// `agents.defaults.model` when this provider is selected (e.g. in fallback chains).
    #[serde(default)]
    pub model: Option<String>,
    /// Per-provider usage quota configuration. When set, the provider will be
    /// wrapped in a `QuotaProvider` that enforces the configured limits.
    #[serde(default)]
    pub quota: Option<crate::providers::quota::QuotaConfig>,
    /// Custom auth header name, e.g. "api-key" for Azure. Overrides spec default.
    #[serde(default)]
    pub auth_header: Option<String>,
    /// API version query param, e.g. "2024-08-01-preview" for Azure.
    #[serde(default)]
    pub api_version: Option<String>,
}

impl ProviderConfig {
    /// Resolve the authentication method for this provider.
    pub fn resolved_auth_method(&self) -> crate::auth::AuthMethod {
        crate::auth::AuthMethod::from_option(self.auth_method.as_deref())
    }
}

/// Configuration for an external binary LLM provider plugin.
///
/// The binary is invoked once per `chat()` call and communicates via
/// JSON-RPC 2.0 over stdin/stdout.
///
/// # Example (config.json)
/// ```json
/// {
///   "providers": {
///     "plugins": [
///       {"name": "myprovider", "command": "/usr/local/bin/my-provider", "args": ["--mode", "chat"]}
///     ]
///   }
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderPluginConfig {
    /// Unique provider name. Plugin providers activate when no built-in provider (Anthropic/OpenAI) is configured.
    pub name: String,
    /// Path to the provider binary
    pub command: String,
    /// Additional arguments passed to the binary
    #[serde(default)]
    pub args: Vec<String>,
}

/// Retry behavior for runtime provider calls.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RetryConfig {
    /// Enable automatic retry for transient provider errors.
    pub enabled: bool,
    /// Maximum number of retry attempts.
    pub max_retries: u32,
    /// Base delay in milliseconds for exponential backoff.
    pub base_delay_ms: u64,
    /// Maximum delay cap in milliseconds for exponential backoff.
    pub max_delay_ms: u64,
    /// Total wall-clock retry budget in milliseconds. 0 = unlimited.
    pub retry_budget_ms: u64,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            max_retries: 3,
            base_delay_ms: 1_000,
            max_delay_ms: 30_000,
            retry_budget_ms: 45_000,
        }
    }
}

/// Fallback behavior across multiple configured runtime providers.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct FallbackConfig {
    /// Enable provider fallback (primary -> secondary) when possible.
    pub enabled: bool,
    /// Optional preferred fallback provider id (e.g. "openai", "anthropic").
    pub provider: Option<String>,
}

/// Provider rotation configuration for 3+ health-aware providers.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RotationConfig {
    /// Enable provider rotation.
    #[serde(default)]
    pub enabled: bool,
    /// Provider names in rotation order (e.g., \["anthropic", "openai", "groq"\]).
    #[serde(default)]
    pub order: Vec<String>,
    /// Rotation strategy (priority or round_robin).
    #[serde(default)]
    pub strategy: crate::providers::rotation::RotationStrategy,
    /// Consecutive failures before marking provider unhealthy (default: 3).
    #[serde(default = "default_rotation_failure_threshold")]
    pub failure_threshold: u32,
    /// Seconds to wait before retrying unhealthy provider (default: 30).
    #[serde(default = "default_rotation_cooldown_secs")]
    pub cooldown_secs: u64,
}

fn default_rotation_failure_threshold() -> u32 {
    3
}

fn default_rotation_cooldown_secs() -> u64 {
    30
}

impl Default for RotationConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            order: Vec::new(),
            strategy: crate::providers::rotation::RotationStrategy::default(),
            failure_threshold: default_rotation_failure_threshold(),
            cooldown_secs: default_rotation_cooldown_secs(),
        }
    }
}

// ============================================================================
// Gateway Configuration
// ============================================================================

/// Rate limiting configuration for gateway endpoints.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct RateLimitConfig {
    /// Max pairing requests per minute per IP (0 = unlimited).
    pub pair_per_min: u32,
    /// Max webhook requests per minute per IP (0 = unlimited).
    pub webhook_per_min: u32,
}

/// Startup guard configuration — degrade after consecutive crashes.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct StartupGuardConfig {
    /// Enable startup guard (default: true).
    pub enabled: bool,
    /// Consecutive crashes before entering degraded mode (default: 4).
    pub crash_threshold: u32,
    /// Time window in seconds — crashes older than this are stale (default: 300).
    pub window_secs: u64,
}

impl Default for StartupGuardConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            crash_threshold: 4,
            window_secs: 300,
        }
    }
}

/// Gateway server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct GatewayConfig {
    /// Host to bind to
    pub host: String,
    /// Port to listen on
    pub port: u16,
    /// Per-IP rate limiting for gateway endpoints.
    #[serde(default)]
    pub rate_limit: RateLimitConfig,
    /// Startup guard — degrade after consecutive crashes.
    #[serde(default)]
    pub startup_guard: StartupGuardConfig,
}

impl Default for GatewayConfig {
    fn default() -> Self {
        Self {
            host: "0.0.0.0".to_string(),
            port: 8080,
            rate_limit: RateLimitConfig::default(),
            startup_guard: StartupGuardConfig::default(),
        }
    }
}

// ============================================================================
// Tools Configuration
// ============================================================================

/// Voice transcription tool configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct TranscribeConfig {
    /// Enable the transcribe tool
    #[serde(default)]
    pub enabled: bool,
    /// Groq API key for Whisper transcription
    pub groq_api_key: Option<String>,
    /// Whisper model to use
    #[serde(default = "default_transcribe_model")]
    pub model: String,
}

fn default_transcribe_model() -> String {
    "whisper-large-v3-turbo".to_string()
}

/// Tools configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ToolsConfig {
    /// Web tools configuration
    pub web: WebToolsConfig,
    /// WhatsApp Cloud API tool configuration
    pub whatsapp: WhatsAppToolConfig,
    /// Google Sheets tool configuration
    pub google_sheets: GoogleSheetsToolConfig,
    /// Google Workspace tool configuration (Gmail + Calendar)
    #[serde(default)]
    pub google: GoogleToolConfig,
    /// HTTP request tool configuration
    pub http_request: Option<HttpRequestConfig>,
    /// Voice transcription tool configuration
    #[serde(default)]
    pub transcribe: TranscribeConfig,
    /// Skills marketplace (ClawHub) configuration
    #[serde(default)]
    pub skills: SkillsMarketplaceConfig,
    /// Enable coding-specific tools (grep, find). Default: false.
    ///
    /// These tools assume a laptop/server environment with bash available.
    /// Enable when using ZeptoClaw as a coding agent. The built-in "coder"
    /// template enables them automatically; this flag lets you enable them
    /// without switching templates.
    ///
    /// Example: `"tools": { "coding_tools": true }`
    #[serde(default)]
    pub coding_tools: bool,
    /// Tools to deny (disable). Set by startup guard in degraded mode.
    #[serde(default)]
    pub deny: Vec<String>,
}

/// Configuration for the HTTP request tool.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct HttpRequestConfig {
    /// Allowlist of domains the agent may call. Required — tool fails fast if empty.
    #[serde(default)]
    pub allowed_domains: Vec<String>,
    /// Request timeout in seconds. Default: 30.
    #[serde(default = "default_http_request_timeout")]
    pub timeout_secs: u64,
    /// Maximum response body size in bytes. Default: 512KB.
    #[serde(default = "default_http_request_max_bytes")]
    pub max_response_bytes: usize,
}

fn default_http_request_timeout() -> u64 {
    30
}

fn default_http_request_max_bytes() -> usize {
    512 * 1024
}

/// Web tools configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct WebToolsConfig {
    /// Web search configuration
    pub search: WebSearchConfig,
}

/// Web search configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct WebSearchConfig {
    /// Search provider: "brave", "searxng", "ddg" (default: auto-detect)
    #[serde(default)]
    pub provider: Option<String>,
    /// API key for Brave Search
    #[serde(default)]
    pub api_key: Option<String>,
    /// SearXNG instance URL (e.g. "https://search.example.com")
    #[serde(default)]
    pub api_url: Option<String>,
    /// Maximum search results to return
    pub max_results: u32,
}

impl Default for WebSearchConfig {
    fn default() -> Self {
        Self {
            provider: None,
            api_key: None,
            api_url: None,
            max_results: 5,
        }
    }
}

/// WhatsApp Cloud API tool configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct WhatsAppToolConfig {
    /// WhatsApp Business account ID (optional, informational)
    #[serde(default)]
    pub business_account_id: Option<String>,
    /// Phone number ID used in Cloud API endpoint path
    #[serde(default)]
    pub phone_number_id: Option<String>,
    /// Permanent access token for Cloud API
    #[serde(default)]
    pub access_token: Option<String>,
    /// Optional webhook verify token
    #[serde(default)]
    pub webhook_verify_token: Option<String>,
    /// Default template language code
    pub default_language: String,
}

impl Default for WhatsAppToolConfig {
    fn default() -> Self {
        Self {
            business_account_id: None,
            phone_number_id: None,
            access_token: None,
            webhook_verify_token: None,
            default_language: "ms".to_string(),
        }
    }
}

/// Google Sheets tool configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct GoogleSheetsToolConfig {
    /// OAuth bearer access token (recommended for tool usage)
    #[serde(default)]
    pub access_token: Option<String>,
    /// Optional service account JSON encoded as base64
    #[serde(default)]
    pub service_account_base64: Option<String>,
}

/// Google Workspace tool configuration (Gmail + Calendar).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct GoogleToolConfig {
    /// OAuth bearer access token (fallback when no stored OAuth session)
    #[serde(default)]
    pub access_token: Option<String>,
    /// Google OAuth client ID
    #[serde(default)]
    pub client_id: Option<String>,
    /// Google OAuth client secret
    #[serde(default)]
    pub client_secret: Option<String>,
    /// Default calendar ID for calendar actions
    pub default_calendar: String,
    /// Maximum results for gmail_search
    pub max_search_results: u32,
}

impl Default for GoogleToolConfig {
    fn default() -> Self {
        Self {
            access_token: None,
            client_id: None,
            client_secret: None,
            default_calendar: "primary".to_string(),
            max_search_results: 20,
        }
    }
}

// ============================================================================
// Memory Configuration
// ============================================================================

/// Memory backend selection.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum MemoryBackend {
    /// Disable memory tools.
    #[serde(rename = "none")]
    Disabled,
    /// Built-in substring search (default, zero cost).
    #[default]
    Builtin,
    /// BM25 keyword scoring (feature: memory-bm25).
    Bm25,
    /// LLM embedding + cosine similarity (feature: memory-embedding).
    Embedding,
    /// HNSW approximate nearest neighbor (feature: memory-hnsw).
    Hnsw,
    /// Tantivy full-text search engine (feature: memory-tantivy).
    Tantivy,
    /// QMD backend (falls back safely when unavailable).
    Qmd,
}

/// Memory citation mode.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum MemoryCitationsMode {
    /// Show citations depending on channel context.
    #[default]
    Auto,
    /// Always include citations in snippets.
    On,
    /// Never include citations in snippets.
    Off,
}

/// Memory configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MemoryConfig {
    /// Memory backend to use.
    pub backend: MemoryBackend,
    /// Citation mode for memory snippets.
    pub citations: MemoryCitationsMode,
    /// Whether to include MEMORY.md + memory/**/*.md by default.
    pub include_default_memory: bool,
    /// Default maximum memory search results.
    pub max_results: u32,
    /// Minimum score threshold for memory search results.
    pub min_score: f32,
    /// Maximum snippet length returned per result.
    pub max_snippet_chars: u32,
    /// Extra workspace-relative file/dir paths to include.
    #[serde(default)]
    pub extra_paths: Vec<String>,
    /// Embedding provider name. Only used when backend is "embedding".
    #[serde(default)]
    pub embedding_provider: Option<String>,
    /// Embedding model name. Only used when backend is "embedding".
    #[serde(default)]
    pub embedding_model: Option<String>,
    /// HNSW index file path override. Only used when backend is "hnsw".
    #[serde(default)]
    pub hnsw_index_path: Option<String>,
    /// Tantivy index directory path override. Only used when backend is "tantivy".
    #[serde(default)]
    pub tantivy_index_path: Option<String>,
    /// Memory hygiene scheduler configuration.
    #[serde(default)]
    pub hygiene: crate::memory::hygiene::HygieneConfig,
}

impl Default for MemoryConfig {
    fn default() -> Self {
        Self {
            backend: MemoryBackend::Builtin,
            citations: MemoryCitationsMode::Auto,
            include_default_memory: true,
            max_results: 6,
            min_score: 0.2,
            max_snippet_chars: 700,
            extra_paths: Vec::new(),
            embedding_provider: None,
            embedding_model: None,
            hnsw_index_path: None,
            tantivy_index_path: None,
            hygiene: crate::memory::hygiene::HygieneConfig::default(),
        }
    }
}

// ============================================================================
// Heartbeat Configuration
// ============================================================================

/// Heartbeat background service configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct HeartbeatConfig {
    /// Enable or disable heartbeat service.
    pub enabled: bool,
    /// Heartbeat interval in seconds.
    pub interval_secs: u64,
    /// Optional heartbeat file path override.
    #[serde(default)]
    pub file_path: Option<String>,
    /// Channel and chat ID to route heartbeat messages through, in "channel:chat_id" format
    /// (e.g., "telegram:123456789"). Controls both where the inbound heartbeat prompt is
    /// processed and where responses are delivered. If unset, falls back to the internal
    /// "heartbeat:system" pseudo-channel (no outbound delivery).
    #[serde(default)]
    pub deliver_to: Option<String>,
}

impl Default for HeartbeatConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            interval_secs: 30 * 60,
            file_path: None,
            deliver_to: None,
        }
    }
}

// ============================================================================

// ============================================================================
// Skills Marketplace (ClawHub) Configuration
// ============================================================================

/// Skills marketplace (ClawHub) tool configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct SkillsMarketplaceConfig {
    /// Enable skills marketplace tools (find_skills, install_skill).
    #[serde(default)]
    pub enabled: bool,
    /// ClawHub registry settings.
    #[serde(default)]
    pub clawhub: ClawHubConfig,
    /// In-memory search cache settings.
    #[serde(default)]
    pub search_cache: SearchCacheConfig,
}

/// ClawHub registry connection settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ClawHubConfig {
    /// Enable the ClawHub registry (requires skills.enabled too).
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Base URL for the ClawHub API.
    #[serde(default = "default_clawhub_url")]
    pub base_url: String,
    /// Optional Bearer token for authenticated registry access.
    #[serde(default)]
    pub auth_token: Option<String>,
    /// Hostnames explicitly allowed to bypass SSRF checks.
    ///
    /// Use this for self-hosted skill registries on private networks
    /// (e.g., `["registry.internal.corp"]`). Public registries like
    /// `clawhub.ai` do not need to be listed here.
    #[serde(default)]
    pub allowed_hosts: Vec<String>,
}

fn default_clawhub_url() -> String {
    "https://clawhub.ai".to_string()
}

impl Default for ClawHubConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            base_url: default_clawhub_url(),
            auth_token: None,
            allowed_hosts: Vec::new(),
        }
    }
}

/// In-memory search result cache settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SearchCacheConfig {
    /// Maximum number of cached queries.
    #[serde(default = "default_cache_size")]
    pub max_size: usize,
    /// Cache entry TTL in seconds.
    #[serde(default = "default_cache_ttl")]
    pub ttl_seconds: u64,
}

fn default_cache_size() -> usize {
    50
}

fn default_cache_ttl() -> u64 {
    300
}

impl Default for SearchCacheConfig {
    fn default() -> Self {
        Self {
            max_size: default_cache_size(),
            ttl_seconds: default_cache_ttl(),
        }
    }
}

// Skills Configuration
// ============================================================================

/// Skills system configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SkillsConfig {
    /// Enable or disable the skills system.
    pub enabled: bool,
    /// Optional workspace skills directory override.
    #[serde(default)]
    pub workspace_dir: Option<String>,
    /// Skills that should always be injected into context.
    #[serde(default)]
    pub always_load: Vec<String>,
    /// Built-in or workspace skills to disable by name.
    #[serde(default)]
    pub disabled: Vec<String>,
    /// Optional GitHub token for skill search deep scanning.
    #[serde(default)]
    pub github_token: Option<String>,
}

impl Default for SkillsConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            workspace_dir: None,
            always_load: Vec::new(),
            disabled: Vec::new(),
            github_token: None,
        }
    }
}

// ============================================================================
// Swarm / Multi-Agent Delegation Configuration
// ============================================================================

/// Swarm / multi-agent delegation configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SwarmConfig {
    /// Whether delegation is enabled.
    pub enabled: bool,
    /// Maximum delegation depth (1 = no sub-sub-agents).
    pub max_depth: u32,
    /// Maximum concurrent sub-agents (for future parallel mode).
    pub max_concurrent: u32,
    /// Pre-defined role presets with tool whitelists.
    pub roles: std::collections::HashMap<String, SwarmRole>,
}

impl Default for SwarmConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_depth: 1,
            max_concurrent: 3,
            roles: std::collections::HashMap::new(),
        }
    }
}

/// A pre-defined sub-agent role with system prompt and tool whitelist.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct SwarmRole {
    /// System prompt for this role.
    pub system_prompt: String,
    /// Allowed tool names (empty = all minus delegate/spawn).
    pub tools: Vec<String>,
}

// ============================================================================
// Runtime Configuration
// ============================================================================

/// Container runtime type for shell command execution
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum RuntimeType {
    /// Native execution (no container isolation)
    #[default]
    Native,
    /// Docker container isolation
    Docker,
    /// Apple Container isolation (macOS only)
    #[serde(rename = "apple")]
    AppleContainer,
    /// Landlock kernel LSM sandbox (Linux only, requires kernel 5.13+)
    #[cfg(target_os = "linux")]
    Landlock,
    /// Firejail userspace sandbox (Linux only, requires firejail binary)
    #[cfg(target_os = "linux")]
    Firejail,
    /// Bubblewrap OCI sandbox (Linux only, requires bwrap binary)
    #[cfg(target_os = "linux")]
    Bubblewrap,
}

/// Runtime configuration for shell execution
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RuntimeConfig {
    /// Type of container runtime to use
    pub runtime_type: RuntimeType,
    /// Whether to fall back to native runtime if configured runtime is unavailable
    pub allow_fallback_to_native: bool,
    /// Path to JSON allowlist used to validate runtime extra mounts
    #[serde(default = "default_mount_allowlist_path")]
    pub mount_allowlist_path: String,
    /// Docker-specific configuration
    pub docker: DockerConfig,
    /// Apple Container-specific configuration (macOS)
    pub apple: AppleContainerConfig,
    /// Landlock sandbox configuration (Linux only).
    pub landlock: LandlockConfig,
    /// Firejail sandbox configuration (Linux only).
    pub firejail: FirejailConfig,
    /// Bubblewrap sandbox configuration (Linux only).
    pub bubblewrap: BubblewrapConfig,
}

fn default_mount_allowlist_path() -> String {
    "~/.zeptoclaw/mount-allowlist.json".to_string()
}

impl Default for RuntimeConfig {
    fn default() -> Self {
        Self {
            runtime_type: RuntimeType::Native,
            allow_fallback_to_native: false,
            mount_allowlist_path: default_mount_allowlist_path(),
            docker: DockerConfig::default(),
            apple: AppleContainerConfig::default(),
            landlock: LandlockConfig::default(),
            firejail: FirejailConfig::default(),
            bubblewrap: BubblewrapConfig::default(),
        }
    }
}

/// Docker runtime configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DockerConfig {
    /// Docker image to use for shell execution
    pub image: String,
    /// Additional volume mounts (host:container format)
    pub extra_mounts: Vec<String>,
    /// Memory limit (e.g., "512m")
    pub memory_limit: Option<String>,
    /// CPU limit (e.g., "1.0")
    pub cpu_limit: Option<String>,
    /// Network mode (default: none for security)
    pub network: String,
    /// PID limit to prevent fork bombs (e.g., 100). None = no limit.
    #[serde(default)]
    pub pids_limit: Option<u32>,
    /// Container stop timeout in seconds (matches agent timeout).
    /// Docker sends SIGTERM, waits this long, then SIGKILL.
    #[serde(default = "default_stop_timeout")]
    pub stop_timeout_secs: u64,
}

fn default_stop_timeout() -> u64 {
    300 // match agent default timeout
}

impl Default for DockerConfig {
    fn default() -> Self {
        Self {
            image: "alpine:latest".to_string(),
            extra_mounts: Vec::new(),
            memory_limit: Some("512m".to_string()),
            cpu_limit: Some("1.0".to_string()),
            network: "none".to_string(),
            pids_limit: Some(100),
            stop_timeout_secs: default_stop_timeout(),
        }
    }
}

/// Apple Container runtime configuration (macOS only)
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct AppleContainerConfig {
    /// Container image/bundle path
    pub image: String,
    /// Additional directory mounts
    pub extra_mounts: Vec<String>,
    /// Allow use of Apple Container runtime (experimental).
    /// When false (default), requesting the Apple Container runtime returns an error.
    pub allow_experimental: bool,
}

// ============================================================================
// Linux Sandbox Runtime Configuration
// ============================================================================

/// Landlock LSM sandbox configuration (Linux only).
///
/// Restricts filesystem access at the kernel level using the Linux Landlock LSM.
/// Requires Linux kernel 5.13+. Degrades gracefully on older kernels.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LandlockConfig {
    /// Directories the sandboxed process may read (recursive).
    pub fs_read_dirs: Vec<String>,
    /// Directories the sandboxed process may write (recursive).
    pub fs_write_dirs: Vec<String>,
    /// Automatically add the agent workspace to the read allow list.
    pub allow_read_workspace: bool,
    /// Automatically add the agent workspace to the write allow list.
    pub allow_write_workspace: bool,
}

impl Default for LandlockConfig {
    fn default() -> Self {
        Self {
            fs_read_dirs: vec![
                "/usr".to_string(),
                "/lib".to_string(),
                "/lib64".to_string(),
                "/etc".to_string(),
                "/bin".to_string(),
                "/sbin".to_string(),
                "/tmp".to_string(),
            ],
            fs_write_dirs: vec!["/tmp".to_string()],
            allow_read_workspace: true,
            allow_write_workspace: true,
        }
    }
}

/// Firejail sandbox configuration (Linux only).
///
/// Wraps commands with `firejail` using Linux namespaces + seccomp.
/// Requires the `firejail` binary on PATH.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct FirejailConfig {
    /// Path to a custom firejail profile file.
    /// When None, `--noprofile` is used.
    pub profile: Option<String>,
    /// Extra arguments passed verbatim to firejail before the command.
    pub extra_args: Vec<String>,
}

/// Bubblewrap sandbox configuration (Linux only).
///
/// Wraps commands with `bwrap` (bubblewrap), a lightweight OCI-compatible sandbox.
/// Requires the `bwrap` binary on PATH.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct BubblewrapConfig {
    /// Read-only bind mounts (each entry is a host path bound at the same container path).
    pub ro_binds: Vec<String>,
    /// Bind /dev into the sandbox (needed for most commands).
    pub dev_bind: bool,
    /// Bind /proc into the sandbox.
    pub proc_bind: bool,
    /// Extra arguments passed verbatim to bwrap before the command.
    pub extra_args: Vec<String>,
}

impl Default for BubblewrapConfig {
    fn default() -> Self {
        Self {
            ro_binds: vec![
                "/usr".to_string(),
                "/lib".to_string(),
                "/lib64".to_string(),
                "/etc".to_string(),
                "/bin".to_string(),
                "/sbin".to_string(),
            ],
            dev_bind: true,
            proc_bind: true,
            extra_args: vec![],
        }
    }
}

// ============================================================================
// Containerized Agent Configuration
// ============================================================================

/// Container backend for the containerized agent proxy.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ContainerAgentBackend {
    /// Auto-detect: on macOS try Apple Container first, then Docker.
    #[default]
    Auto,
    /// Always use Docker.
    Docker,
    /// Use Apple Container (macOS only).
    #[cfg(target_os = "macos")]
    #[serde(rename = "apple")]
    Apple,
}

/// Configuration for containerized agent mode.
///
/// When running with `--containerized`, the gateway spawns each agent
/// in an isolated container for multi-user safety.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ContainerAgentConfig {
    /// Container backend to use (auto, docker, apple).
    pub backend: ContainerAgentBackend,
    /// Container image for the agent.
    pub image: String,
    /// Docker binary path/name override (Docker backend only).
    pub docker_binary: Option<String>,
    /// Memory limit (e.g., "1g") — Docker only, ignored by Apple Container.
    pub memory_limit: Option<String>,
    /// CPU limit (e.g., "2.0") — Docker only, ignored by Apple Container.
    pub cpu_limit: Option<String>,
    /// Request timeout in seconds.
    pub timeout_secs: u64,
    /// Network mode (default: "none" for security) — Docker only.
    pub network: String,
    /// Extra volume mounts (host:container format).
    pub extra_mounts: Vec<String>,
    /// Maximum number of concurrent container invocations.
    pub max_concurrent: usize,
}

impl Default for ContainerAgentConfig {
    fn default() -> Self {
        Self {
            backend: ContainerAgentBackend::Auto,
            image: "zeptoclaw:latest".to_string(),
            docker_binary: None,
            memory_limit: Some("1g".to_string()),
            cpu_limit: Some("2.0".to_string()),
            timeout_secs: 300,
            network: "none".to_string(),
            extra_mounts: Vec::new(),
            max_concurrent: 5,
        }
    }
}

/// A tool defined as a shell command in config.
///
/// Custom tools let users expose any shell command as an agent tool
/// without writing Rust code, plugin manifests, or MCP servers.
///
/// # Example
///
/// ```
/// use zeptoclaw::config::CustomToolDef;
/// use std::collections::HashMap;
///
/// let def = CustomToolDef {
///     name: "cpu_temp".to_string(),
///     description: "Read CPU temperature".to_string(),
///     command: "cat /sys/class/thermal/thermal_zone0/temp".to_string(),
///     parameters: None,
///     working_dir: None,
///     timeout_secs: None,
///     env: None,
/// };
/// assert_eq!(def.name, "cpu_temp");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomToolDef {
    /// Tool name (alphanumeric + underscore only, used by LLM to invoke).
    pub name: String,
    /// Short description (keep under 60 chars for token efficiency).
    pub description: String,
    /// Shell command to execute. Supports {{param}} interpolation.
    pub command: String,
    /// Optional parameter definitions. Keys are param names, values are JSON Schema types.
    /// If omitted, tool takes no parameters (zero schema overhead).
    #[serde(default)]
    pub parameters: Option<HashMap<String, String>>,
    /// Optional working directory override.
    #[serde(default)]
    pub working_dir: Option<String>,
    /// Command timeout in seconds (default: 30).
    #[serde(default)]
    pub timeout_secs: Option<u64>,
    /// Optional environment variables.
    #[serde(default)]
    pub env: Option<HashMap<String, String>>,
}

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

    #[test]
    fn test_swarm_config_defaults() {
        let config = SwarmConfig::default();
        assert!(config.enabled);
        assert_eq!(config.max_depth, 1);
        assert_eq!(config.max_concurrent, 3);
        assert!(config.roles.is_empty());
    }

    #[test]
    fn test_swarm_config_deserialize() {
        let json = r#"{
            "enabled": true,
            "roles": {
                "researcher": {
                    "system_prompt": "You are a researcher.",
                    "tools": ["web_search", "web_fetch"]
                }
            }
        }"#;
        let config: SwarmConfig = serde_json::from_str(json).unwrap();
        assert!(config.enabled);
        assert_eq!(config.roles.len(), 1);
        let role = config.roles.get("researcher").unwrap();
        assert_eq!(role.tools, vec!["web_search", "web_fetch"]);
    }

    #[test]
    fn test_swarm_role_defaults() {
        let role = SwarmRole::default();
        assert!(role.system_prompt.is_empty());
        assert!(role.tools.is_empty());
    }

    #[test]
    fn test_streaming_defaults_to_true() {
        let defaults = AgentDefaults::default();
        assert!(defaults.streaming);
    }

    #[test]
    fn test_streaming_config_deserialize() {
        let json = r#"{"streaming": true}"#;
        let defaults: AgentDefaults = serde_json::from_str(json).unwrap();
        assert!(defaults.streaming);
    }

    #[test]
    fn test_config_with_swarm_deserialize() {
        let json = r#"{
            "swarm": {
                "enabled": false,
                "max_depth": 2
            }
        }"#;
        let config: Config = serde_json::from_str(json).unwrap();
        assert!(!config.swarm.enabled);
        assert_eq!(config.swarm.max_depth, 2);
    }

    #[test]
    fn test_heartbeat_config_default_deliver_to() {
        let config = HeartbeatConfig::default();
        assert!(config.deliver_to.is_none());
    }

    #[test]
    fn test_heartbeat_config_deserialize_deliver_to() {
        let json = r#"{"enabled": true, "interval_secs": 600, "deliver_to": "telegram"}"#;
        let config: HeartbeatConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.deliver_to, Some("telegram".to_string()));
    }

    #[test]
    fn test_heartbeat_config_deserialize_no_deliver_to() {
        let json = r#"{"enabled": true, "interval_secs": 600}"#;
        let config: HeartbeatConfig = serde_json::from_str(json).unwrap();
        assert!(config.deliver_to.is_none());
    }

    #[test]
    fn test_custom_tool_def_deserialize() {
        let json = r#"{
            "name": "cpu_temp",
            "description": "Read CPU temp",
            "command": "cat /sys/class/thermal/thermal_zone0/temp",
            "parameters": {"zone": "string"},
            "working_dir": "/tmp",
            "timeout_secs": 10,
            "env": {"LANG": "C"}
        }"#;
        let def: CustomToolDef = serde_json::from_str(json).unwrap();
        assert_eq!(def.name, "cpu_temp");
        assert_eq!(def.description, "Read CPU temp");
        assert_eq!(def.command, "cat /sys/class/thermal/thermal_zone0/temp");
        assert_eq!(
            def.parameters.as_ref().unwrap().get("zone").unwrap(),
            "string"
        );
        assert_eq!(def.working_dir.as_ref().unwrap(), "/tmp");
        assert_eq!(def.timeout_secs.unwrap(), 10);
        assert_eq!(def.env.as_ref().unwrap().get("LANG").unwrap(), "C");
    }

    #[test]
    fn test_custom_tool_def_minimal() {
        let json = r#"{"name": "test", "description": "Test tool", "command": "echo hi"}"#;
        let def: CustomToolDef = serde_json::from_str(json).unwrap();
        assert_eq!(def.name, "test");
        assert!(def.parameters.is_none());
        assert!(def.working_dir.is_none());
        assert!(def.timeout_secs.is_none());
        assert!(def.env.is_none());
    }

    #[test]
    fn test_custom_tool_def_with_parameters() {
        let json = r#"{
            "name": "search_logs",
            "description": "Search logs",
            "command": "grep {{pattern}} /var/log/app.log",
            "parameters": {"pattern": "string"}
        }"#;
        let def: CustomToolDef = serde_json::from_str(json).unwrap();
        let params = def.parameters.unwrap();
        assert_eq!(params.len(), 1);
        assert_eq!(params.get("pattern").unwrap(), "string");
    }

    #[test]
    fn test_custom_tools_default_empty() {
        let config = Config::default();
        assert!(config.custom_tools.is_empty());
    }

    #[test]
    fn test_tool_profiles_deserialize() {
        let json = r#"{
            "tool_profiles": {
                "minimal": ["shell", "longterm_memory"],
                "full": null
            }
        }"#;
        let config: Config = serde_json::from_str(json).unwrap();
        assert_eq!(config.tool_profiles.len(), 2);
        let minimal = config.tool_profiles.get("minimal").unwrap();
        assert_eq!(minimal.as_ref().unwrap().len(), 2);
        assert!(config.tool_profiles.get("full").unwrap().is_none());
    }

    #[test]
    fn test_tool_profiles_default_empty() {
        let config = Config::default();
        assert!(config.tool_profiles.is_empty());
    }

    #[test]
    fn test_compact_tools_default_false() {
        let defaults = AgentDefaults::default();
        assert!(!defaults.compact_tools);
        assert!(defaults.tool_profile.is_none());
    }

    #[test]
    fn test_compact_tools_deserialize() {
        let json =
            r#"{"agents": {"defaults": {"compact_tools": true, "tool_profile": "minimal"}}}"#;
        let config: Config = serde_json::from_str(json).unwrap();
        assert!(config.agents.defaults.compact_tools);
        assert_eq!(
            config.agents.defaults.tool_profile.as_ref().unwrap(),
            "minimal"
        );
    }

    #[test]
    fn test_routines_config_jitter_default() {
        let config = RoutinesConfig::default();
        assert_eq!(config.jitter_ms, 0);
    }

    #[test]
    fn test_routines_config_jitter_deserialize() {
        let json = r#"{"enabled": true, "cron_interval_secs": 60, "max_concurrent": 3, "jitter_ms": 5000}"#;
        let config: RoutinesConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.jitter_ms, 5000);
    }

    #[test]
    fn test_tunnel_config_defaults() {
        let config = TunnelConfig::default();
        assert!(config.provider.is_none());
        assert!(config.cloudflare.is_none());
        assert!(config.ngrok.is_none());
        assert!(config.tailscale.is_none());
    }

    #[test]
    fn test_tunnel_config_deserialize() {
        let json = r#"{"tunnel": {"provider": "cloudflare", "cloudflare": {"token": "abc"}}}"#;
        let config: Config = serde_json::from_str(json).unwrap();
        assert_eq!(config.tunnel.provider.as_deref(), Some("cloudflare"));
        assert_eq!(
            config.tunnel.cloudflare.as_ref().unwrap().token.as_deref(),
            Some("abc")
        );
    }

    #[test]
    fn test_tailscale_tunnel_config_default_funnel_true() {
        let config = TailscaleTunnelConfig::default();
        assert!(config.funnel);
    }

    #[test]
    fn test_ngrok_tunnel_config_deserialize() {
        let json = r#"{"tunnel": {"provider": "ngrok", "ngrok": {"authtoken": "tok_123", "domain": "my.ngrok.io"}}}"#;
        let config: Config = serde_json::from_str(json).unwrap();
        assert_eq!(config.tunnel.provider.as_deref(), Some("ngrok"));
        let ngrok = config.tunnel.ngrok.as_ref().unwrap();
        assert_eq!(ngrok.authtoken.as_deref(), Some("tok_123"));
        assert_eq!(ngrok.domain.as_deref(), Some("my.ngrok.io"));
    }

    #[test]
    fn test_r8r_bridge_config_debug_redacts_token() {
        let config = R8rBridgeConfig {
            token: Some("super-secret-token".to_string()),
            ..Default::default()
        };
        let debug_output = format!("{:?}", config);
        assert!(
            !debug_output.contains("super-secret-token"),
            "token must not appear in Debug output"
        );
        assert!(
            debug_output.contains("REDACTED"),
            "Debug output should show [REDACTED]"
        );
    }

    #[test]
    fn test_r8r_bridge_config_debug_none_token() {
        let config = R8rBridgeConfig::default();
        let debug_output = format!("{:?}", config);
        assert!(debug_output.contains("None"));
    }

    #[test]
    fn test_whatsapp_cloud_config_defaults() {
        let config = WhatsAppCloudConfig::default();
        assert!(!config.enabled);
        assert!(config.phone_number_id.is_empty());
        assert!(config.access_token.is_empty());
        assert!(config.webhook_verify_token.is_empty());
        assert!(config.app_secret.is_none());
        assert_eq!(config.bind_address, "127.0.0.1");
        assert_eq!(config.port, 9877);
        assert_eq!(config.path, "/whatsapp");
        assert!(config.allow_from.is_empty());
        assert!(!config.deny_by_default);
    }

    #[test]
    fn test_whatsapp_cloud_config_deserialize() {
        let json = r#"{
            "enabled": true,
            "phone_number_id": "123456",
            "access_token": "EAAx...",
            "webhook_verify_token": "my-verify-secret",
            "app_secret": "meta-secret",
            "port": 8443,
            "allow_from": ["60123456789"]
        }"#;
        let config: WhatsAppCloudConfig = serde_json::from_str(json).unwrap();
        assert!(config.enabled);
        assert_eq!(config.phone_number_id, "123456");
        assert_eq!(config.access_token, "EAAx...");
        assert_eq!(config.webhook_verify_token, "my-verify-secret");
        assert_eq!(config.app_secret.as_deref(), Some("meta-secret"));
        assert_eq!(config.port, 8443);
        assert_eq!(config.allow_from, vec!["60123456789"]);
    }

    #[test]
    fn test_channels_config_with_whatsapp_cloud() {
        let json = r#"{
            "channels": {
                "whatsapp_cloud": {
                    "enabled": true,
                    "phone_number_id": "999",
                    "access_token": "tok",
                    "webhook_verify_token": "verify"
                }
            }
        }"#;
        let config: Config = serde_json::from_str(json).unwrap();
        let wac = config.channels.whatsapp_cloud.unwrap();
        assert!(wac.enabled);
        assert_eq!(wac.phone_number_id, "999");
    }

    #[test]
    fn test_channels_config_whatsapp_legacy_alias_deserializes_to_whatsapp_web() {
        let json = r#"{
            "channels": {
                "whatsapp": {
                    "enabled": true,
                    "auth_dir": "/tmp/wa-legacy"
                }
            }
        }"#;
        let config: Config = serde_json::from_str(json).unwrap();
        let wa = config.channels.whatsapp_web.unwrap();
        assert!(wa.enabled);
        assert_eq!(wa.auth_dir, "/tmp/wa-legacy");
    }

    #[test]
    fn test_memory_backend_bm25_deserialize() {
        let json = r#"{"memory": {"backend": "bm25"}}"#;
        let config: Config = serde_json::from_str(json).unwrap();
        assert_eq!(config.memory.backend, MemoryBackend::Bm25);
    }

    #[test]
    fn test_memory_backend_embedding_deserialize() {
        let json = r#"{"memory": {"backend": "embedding", "embedding_provider": "openai", "embedding_model": "text-embedding-3-small"}}"#;
        let config: Config = serde_json::from_str(json).unwrap();
        assert_eq!(config.memory.backend, MemoryBackend::Embedding);
        assert_eq!(config.memory.embedding_provider.as_deref(), Some("openai"));
        assert_eq!(
            config.memory.embedding_model.as_deref(),
            Some("text-embedding-3-small")
        );
    }

    #[test]
    fn test_memory_backend_hnsw_deserialize() {
        let json = r#"{"memory": {"backend": "hnsw"}}"#;
        let config: Config = serde_json::from_str(json).unwrap();
        assert_eq!(config.memory.backend, MemoryBackend::Hnsw);
    }

    #[test]
    fn test_memory_backend_tantivy_deserialize() {
        let json = r#"{"memory": {"backend": "tantivy"}}"#;
        let config: Config = serde_json::from_str(json).unwrap();
        assert_eq!(config.memory.backend, MemoryBackend::Tantivy);
    }

    #[test]
    fn test_transcription_config_defaults() {
        let config = Config::default();
        assert_eq!(config.transcription.model, "whisper-1");
        assert!(config.transcription.enabled);
    }

    #[test]
    fn test_memory_config_new_fields_default_none() {
        let config = MemoryConfig::default();
        assert!(config.embedding_provider.is_none());
        assert!(config.embedding_model.is_none());
        assert!(config.hnsw_index_path.is_none());
        assert!(config.tantivy_index_path.is_none());
    }

    #[test]
    fn test_docker_config_defaults() {
        let config = DockerConfig::default();
        assert_eq!(config.pids_limit, Some(100));
        assert_eq!(config.stop_timeout_secs, 300);
        assert_eq!(config.memory_limit, Some("512m".to_string()));
        assert_eq!(config.cpu_limit, Some("1.0".to_string()));
        assert_eq!(config.network, "none");
    }

    #[test]
    fn test_docker_config_deserialize_new_fields() {
        let json = r#"{"pids_limit": 50, "stop_timeout_secs": 120}"#;
        let config: DockerConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.pids_limit, Some(50));
        assert_eq!(config.stop_timeout_secs, 120);
    }

    #[test]
    fn test_docker_config_deserialize_no_pids_limit() {
        let json = r#"{}"#;
        let config: DockerConfig = serde_json::from_str(json).unwrap();
        // Field-level #[serde(default)] on Option<u32> yields None when the key is absent.
        // The struct-level #[serde(default)] only applies when the whole struct key is missing.
        assert_eq!(config.pids_limit, None);
        assert_eq!(config.stop_timeout_secs, 300);
    }

    #[test]
    fn test_landlock_config_default_read_dirs() {
        let cfg = LandlockConfig::default();
        assert!(cfg.fs_read_dirs.iter().any(|d| d == "/usr"));
        assert!(cfg.allow_read_workspace);
        assert!(cfg.allow_write_workspace);
    }

    #[test]
    fn test_firejail_config_default_no_profile() {
        let cfg = FirejailConfig::default();
        assert!(cfg.profile.is_none());
        assert!(cfg.extra_args.is_empty());
    }

    #[test]
    fn test_bubblewrap_config_default_ro_binds() {
        let cfg = BubblewrapConfig::default();
        assert!(cfg.ro_binds.iter().any(|d| d == "/usr"));
        assert!(cfg.dev_bind);
        assert!(cfg.proc_bind);
    }

    #[test]
    fn test_runtime_config_has_sandbox_fields() {
        let cfg = RuntimeConfig::default();
        assert!(cfg.landlock.fs_read_dirs.contains(&"/usr".to_string()));
        assert!(cfg.firejail.profile.is_none());
        assert!(cfg.bubblewrap.dev_bind);
    }

    #[test]
    fn test_google_tool_config_default() {
        let config = GoogleToolConfig::default();
        assert!(config.access_token.is_none());
        assert!(config.client_id.is_none());
        assert!(config.client_secret.is_none());
        assert_eq!(config.default_calendar, "primary");
        assert_eq!(config.max_search_results, 20);
    }

    #[test]
    fn test_google_tool_config_deserialize() {
        let json = r#"{
            "access_token": "ya29.test",
            "client_id": "123.apps.googleusercontent.com",
            "client_secret": "secret",
            "default_calendar": "work",
            "max_search_results": 50
        }"#;
        let config: GoogleToolConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.access_token.as_deref(), Some("ya29.test"));
        assert_eq!(config.default_calendar, "work");
        assert_eq!(config.max_search_results, 50);
    }

    #[test]
    fn test_provider_config_model_default_is_none() {
        let config = ProviderConfig::default();
        assert!(config.model.is_none());
    }

    #[test]
    fn test_provider_config_model_deserialize() {
        let json = r#"{
            "api_key": "sk-test",
            "model": "gpt-4o"
        }"#;
        let config: ProviderConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.api_key.as_deref(), Some("sk-test"));
        assert_eq!(config.model.as_deref(), Some("gpt-4o"));
    }

    #[test]
    fn test_provider_config_model_absent() {
        let json = r#"{"api_key": "sk-test"}"#;
        let config: ProviderConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.api_key.as_deref(), Some("sk-test"));
        assert!(config.model.is_none());
    }

    #[test]
    fn test_provider_config_quota_default_is_none() {
        let config = ProviderConfig::default();
        assert!(config.quota.is_none());
    }

    #[test]
    fn test_provider_config_quota_serde() {
        use crate::providers::quota::{QuotaAction, QuotaConfig, QuotaPeriod};

        // Serialize a ProviderConfig with a quota set and round-trip it.
        let original = ProviderConfig {
            api_key: Some("sk-test".to_string()),
            quota: Some(QuotaConfig {
                max_cost_usd: Some(10.0),
                max_tokens: None,
                period: QuotaPeriod::Monthly,
                action: QuotaAction::Reject,
            }),
            ..Default::default()
        };

        let json = serde_json::to_string(&original).unwrap();
        let decoded: ProviderConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(decoded.api_key.as_deref(), Some("sk-test"));
        let quota = decoded
            .quota
            .expect("quota should be present after round-trip");
        assert_eq!(quota.max_cost_usd, Some(10.0));
        assert!(quota.max_tokens.is_none());
        assert_eq!(quota.period, QuotaPeriod::Monthly);
        assert_eq!(quota.action, QuotaAction::Reject);

        // A JSON object with no "quota" key should deserialize with quota: None.
        let no_quota_json = r#"{"api_key": "sk-test"}"#;
        let no_quota: ProviderConfig = serde_json::from_str(no_quota_json).unwrap();
        assert!(
            no_quota.quota.is_none(),
            "missing quota key should deserialize as None"
        );
    }

    #[test]
    fn test_mcp_server_config_stdio_fields() {
        let json = r#"{
            "name": "test",
            "command": "node",
            "args": ["server.js"],
            "env": {"KEY": "val"},
            "timeout_secs": 30
        }"#;
        let config: McpServerConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.name, "test");
        assert_eq!(config.command, Some("node".to_string()));
        assert_eq!(config.args, Some(vec!["server.js".to_string()]));
        assert_eq!(
            config
                .env
                .as_ref()
                .and_then(|e| e.get("KEY"))
                .map(|s| s.as_str()),
            Some("val")
        );
        assert!(config.url.is_none());
    }

    #[test]
    fn test_provider_config_auth_header_and_api_version_default_none() {
        let c = ProviderConfig::default();
        assert!(c.auth_header.is_none());
        assert!(c.api_version.is_none());
    }

    #[test]
    fn test_providers_config_has_azure_and_bedrock_fields() {
        let c = ProvidersConfig::default();
        assert!(c.azure.is_none());
        assert!(c.bedrock.is_none());
    }

    #[test]
    fn test_azure_provider_config_round_trips() {
        let json = r#"{
            "providers": {
                "azure": {
                    "api_key": "my-azure-key",
                    "api_base": "https://myco.openai.azure.com/openai/deployments/gpt-4o",
                    "auth_header": "api-key",
                    "api_version": "2024-08-01-preview"
                }
            }
        }"#;
        let config: Config = serde_json::from_str(json).unwrap();
        let azure = config.providers.azure.as_ref().unwrap();
        assert_eq!(azure.api_key.as_deref(), Some("my-azure-key"));
        assert_eq!(azure.auth_header.as_deref(), Some("api-key"));
        assert_eq!(azure.api_version.as_deref(), Some("2024-08-01-preview"));
    }

    #[test]
    fn test_web_search_config_defaults() {
        let cfg = WebSearchConfig::default();
        assert_eq!(cfg.provider, None);
        assert_eq!(cfg.api_key, None);
        assert_eq!(cfg.api_url, None);
        assert_eq!(cfg.max_results, 5);
    }

    #[test]
    fn test_web_search_config_deserialize_provider() {
        let json = r#"{"provider": "searxng", "api_url": "https://search.example.com"}"#;
        let cfg: WebSearchConfig = serde_json::from_str(json).unwrap();
        assert_eq!(cfg.provider.as_deref(), Some("searxng"));
        assert_eq!(cfg.api_url.as_deref(), Some("https://search.example.com"));
    }
}

// ---------------------------------------------------------------------------
// EmailConfig  (used by channels::EmailChannel, feature-gated: channel-email)
// ---------------------------------------------------------------------------

fn default_email_imap_port() -> u16 {
    993
}
fn default_email_smtp_port() -> u16 {
    587
}
fn default_email_imap_folder() -> String {
    "INBOX".into()
}
fn default_email_idle_timeout_secs() -> u64 {
    1740
}

/// Email channel configuration (IMAP IDLE inbound + SMTP outbound).
///
/// Stored under `channels.email` in `config.json`.
/// The channel is only functional when built with `--features channel-email`.
#[derive(Clone, Serialize, Deserialize)]
pub struct EmailConfig {
    /// IMAP server hostname (e.g. `imap.gmail.com`)
    pub imap_host: String,
    /// IMAP server port. Default: 993 (implicit TLS).
    #[serde(default = "default_email_imap_port")]
    pub imap_port: u16,
    /// SMTP server hostname (e.g. `smtp.gmail.com`)
    pub smtp_host: String,
    /// SMTP server port. Default: 587 (STARTTLS).
    #[serde(default = "default_email_smtp_port")]
    pub smtp_port: u16,
    /// IMAP/SMTP login username.
    pub username: String,
    /// IMAP/SMTP login password (or app-password).
    pub password: String,
    /// IMAP mailbox folder to watch. Default: `INBOX`.
    #[serde(default = "default_email_imap_folder")]
    pub imap_folder: String,
    /// Optional display name used as "From" header in outgoing mail.
    #[serde(default)]
    pub display_name: Option<String>,
    /// Allowlist of sender email addresses or domains.
    ///
    /// These entries are matched against the parsed inbound `From` header.
    /// Use upstream authenticated-mail enforcement (SPF/DKIM/DMARC) if sender
    /// authenticity matters.
    #[serde(default)]
    pub allowed_senders: Vec<String>,
    /// When `true` and `allowed_senders` is empty, all senders are denied.
    #[serde(default)]
    pub deny_by_default: bool,
    /// Seconds before restarting IDLE (RFC 2177 recommends < 30 min). Default: 1740.
    #[serde(default = "default_email_idle_timeout_secs")]
    pub idle_timeout_secs: u64,
    /// When `true`, the channel is active. Default: `false`.
    #[serde(default)]
    pub enabled: bool,
}

impl Default for EmailConfig {
    fn default() -> Self {
        Self {
            imap_host: String::new(),
            imap_port: default_email_imap_port(),
            smtp_host: String::new(),
            smtp_port: default_email_smtp_port(),
            username: String::new(),
            password: String::new(),
            imap_folder: default_email_imap_folder(),
            display_name: None,
            allowed_senders: Vec::new(),
            deny_by_default: false,
            idle_timeout_secs: default_email_idle_timeout_secs(),
            enabled: false,
        }
    }
}

impl std::fmt::Debug for EmailConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EmailConfig")
            .field("imap_host", &self.imap_host)
            .field("imap_port", &self.imap_port)
            .field("smtp_host", &self.smtp_host)
            .field("smtp_port", &self.smtp_port)
            .field("username", &self.username)
            .field("password", &"[redacted]")
            .field("imap_folder", &self.imap_folder)
            .field("display_name", &self.display_name)
            .field("allowed_senders", &self.allowed_senders)
            .field("deny_by_default", &self.deny_by_default)
            .field("idle_timeout_secs", &self.idle_timeout_secs)
            .field("enabled", &self.enabled)
            .finish()
    }
}