distri-types 0.3.8

Shared message, tool, and config types for Distri
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
use crate::AgentError;
use crate::a2a::AgentSkill;
use crate::browser::{BrowserAgentConfig, BrowsrClientConfig};
use crate::configuration::DefinitionOverrides;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::default::Default;

/// Default timeout for external tool execution in seconds
pub const DEFAULT_EXTERNAL_TOOL_TIMEOUT_SECS: u64 = 120;

/// A reference to a stored skill that an agent can load on demand
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
pub struct AvailableSkill {
    /// The skill ID (UUID)
    pub id: String,
    /// Human-readable skill name (for display in the partial)
    pub name: String,
    /// Brief description of what this skill does (shown to the agent)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Unified Agent Strategy Configuration
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
#[derive(Default)]
pub struct AgentStrategy {
    /// Depth of reasoning (shallow, standard, deep)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning_depth: Option<ReasoningDepth>,

    /// Execution mode - tools vs code
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub execution_mode: Option<ExecutionMode>,
    /// When to replan
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub replanning: Option<ReplanningConfig>,

    /// Timeout in seconds for external tool execution (default: 120)
    /// External tools are tools that delegate execution to the frontend/client.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub external_tool_timeout_secs: Option<u64>,
}

impl AgentStrategy {
    /// Get reasoning depth with default fallback
    pub fn get_reasoning_depth(&self) -> ReasoningDepth {
        self.reasoning_depth.clone().unwrap_or_default()
    }

    /// Get execution mode with default fallback
    pub fn get_execution_mode(&self) -> ExecutionMode {
        self.execution_mode.clone().unwrap_or_default()
    }

    /// Get replanning config with default fallback
    pub fn get_replanning(&self) -> ReplanningConfig {
        self.replanning.clone().unwrap_or_default()
    }

    /// Get external tool timeout with default fallback
    pub fn get_external_tool_timeout_secs(&self) -> u64 {
        self.external_tool_timeout_secs
            .unwrap_or(DEFAULT_EXTERNAL_TOOL_TIMEOUT_SECS)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum CodeLanguage {
    #[default]
    Typescript,
}

impl std::fmt::Display for CodeLanguage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CodeLanguage::Typescript => write!(f, "typescript"),
        }
    }
}

/// Reflection configuration
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
pub struct ReflectionConfig {
    /// Whether to enable reflection
    #[serde(default)]
    pub enabled: bool,
    /// Name of the agent definition to use for reflection.
    /// Must be an agent that has the "reflect" tool configured.
    /// If not set, uses the built-in reflection_agent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reflection_agent: Option<String>,
    /// When to trigger reflection
    #[serde(default)]
    pub trigger: ReflectionTrigger,
    /// Depth of reflection
    #[serde(default)]
    pub depth: ReflectionDepth,
}

/// When to trigger reflection
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "snake_case")]
pub enum ReflectionTrigger {
    /// At the end of execution
    #[default]
    EndOfExecution,
    /// After each step
    AfterEachStep,
    /// After failures only
    AfterFailures,
    /// After N steps
    AfterNSteps(usize),
}

/// Depth of reflection
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "snake_case")]
pub enum ReflectionDepth {
    /// Light reflection
    #[default]
    Light,
    /// Standard reflection
    Standard,
    /// Deep reflection
    Deep,
}

/// Configuration for planning operations
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PlanConfig {
    /// The model settings for the planning agent
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_settings: Option<ModelSettings>,
    /// The maximum number of iterations allowed during planning
    #[serde(default = "default_plan_max_iterations")]
    pub max_iterations: usize,
}

impl Default for PlanConfig {
    fn default() -> Self {
        Self {
            model_settings: None,
            max_iterations: default_plan_max_iterations(),
        }
    }
}

fn default_plan_max_iterations() -> usize {
    10
}

/// Depth of reasoning for planning
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ReasoningDepth {
    /// Shallow reasoning - direct action with minimal thought, skip reasoning sections
    Shallow,
    /// Standard reasoning - moderate planning and thought
    #[default]
    Standard,
    /// Deep reasoning - extensive planning, multi-step analysis, and comprehensive thinking
    Deep,
}

/// Execution mode - tools vs code
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default, PartialEq)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum ExecutionMode {
    /// Use tools for execution
    #[default]
    Tools,
    /// Use code execution
    Code { language: CodeLanguage },
}

/// Replanning configuration
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "snake_case")]
pub struct ReplanningConfig {
    /// When to trigger replanning
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger: Option<ReplanningTrigger>,
    /// Whether to replan at all
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
}

/// When to trigger replanning
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "snake_case")]
pub enum ReplanningTrigger {
    /// Never replan (default)
    #[default]
    Never,
    /// Replan after execution reflection
    AfterReflection,
    /// Replan after N iterations
    AfterNIterations(usize),
    /// Replan after failures
    AfterFailures,
}

impl ReplanningConfig {
    /// Get trigger with default fallback
    pub fn get_trigger(&self) -> ReplanningTrigger {
        self.trigger.clone().unwrap_or_default()
    }

    /// Get enabled with default fallback
    pub fn is_enabled(&self) -> bool {
        self.enabled.unwrap_or(false)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "snake_case")]
pub enum ExecutionKind {
    #[default]
    Retriable,
    Interleaved,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "snake_case")]
pub enum MemoryKind {
    #[default]
    None,
    ShortTerm,
    LongTerm,
}

/// How tools are delivered to the LLM in the prompt.
///
/// Controls the tradeoff between prompt size and tool discoverability:
/// - `Full`: All tools get full schemas (classic behavior, largest prompt)
/// - `Deferred`: Core tools get full schemas; others are name+description only
/// - `NamesOnly`: Maximum savings — only core tools have schemas
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ToolDeliveryMode {
    /// All tools get full schemas in the prompt.
    #[serde(alias = "all_tools")]
    Full,
    /// Core tools get full schemas; others get name+description only (default).
    #[default]
    #[serde(alias = "tool_search")]
    Deferred,
    /// Only tool names are listed. Model must use `tool_search` for everything
    /// except core tools. Maximum context savings.
    NamesOnly,
}

/// Which OpenAI-family API format to use when talking to the LLM.
///
/// - `Auto` (default): Auto-detects from the model name. Codex models use Responses API,
///   everything else uses Chat Completions.
/// - `Completions`: Forces the Chat Completions API (`/v1/chat/completions`)
/// - `Responses`: Forces the Responses API (`/v1/responses`)
///
/// Most OpenAI models (GPT-4o, GPT-4.1, GPT-5, o1, etc.) support both APIs.
/// Codex models (`codex-*`, `*-codex`) are Responses API only.
/// OpenAI recommends the Responses API for new projects (better caching, reasoning).
///
/// Can be set at the model_settings level in agent definitions:
/// ```toml
/// [model_settings]
/// model = "codex-mini-latest"
/// api_format = "responses"  # or "completions" or "auto"
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum OpenAiApiFormat {
    /// Auto-detect based on model name (codex models → Responses, everything else → Completions)
    #[default]
    Auto,
    /// Chat Completions API (`/v1/chat/completions`)
    Completions,
    /// Responses API (`/v1/responses`) — required for Codex models, recommended for new projects
    Responses,
}

impl OpenAiApiFormat {
    /// Resolve the effective format given a model name.
    /// When `Auto`, inspects the model name to decide.
    pub fn resolve(&self, model: &str) -> ResolvedOpenAiApiFormat {
        match self {
            OpenAiApiFormat::Completions => ResolvedOpenAiApiFormat::Completions,
            OpenAiApiFormat::Responses => ResolvedOpenAiApiFormat::Responses,
            OpenAiApiFormat::Auto => {
                if Self::model_requires_responses_api(model) {
                    ResolvedOpenAiApiFormat::Responses
                } else {
                    ResolvedOpenAiApiFormat::Completions
                }
            }
        }
    }

    /// Heuristic: models that require the Responses API.
    ///
    /// These models return errors on /v1/chat/completions and MUST use /v1/responses:
    /// - Codex models: codex-mini-latest, gpt-5.1-codex, gpt-5.3-codex, etc.
    /// - Pro models: gpt-5-pro, gpt-5.2-pro, gpt-5.4-pro, o3-pro
    /// - Deep research models: o3-deep-research, o4-mini-deep-research
    fn model_requires_responses_api(model: &str) -> bool {
        let m = model.to_lowercase();
        // Codex models (codex-*, *-codex, */codex*)
        m.starts_with("codex")
            || m.ends_with("-codex")
            || m.contains("/codex")
            // Pro models (*-pro) — require multi-turn interactions only Responses supports
            || m.ends_with("-pro")
            // Deep research models (*-deep-research)
            || m.ends_with("-deep-research")
    }
}

/// Resolved (non-Auto) API format
#[derive(Debug, Clone, PartialEq)]
pub enum ResolvedOpenAiApiFormat {
    Completions,
    Responses,
}

/// Supported tool call formats
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ToolCallFormat {
    /// New XML format: Streaming-capable XML tool calls
    /// Example: <search><query>test</query></search>
    #[default]
    Xml,
    /// New JSON format: JSONL with tool_calls blocks
    /// Example: ```tool_calls\n{"name":"search","arguments":{"query":"test"}}```
    JsonL,

    /// Code execution format: TypeScript/JavaScript code blocks
    /// Example: ```typescript ... ```
    Code,
    #[serde(rename = "provider")]
    Provider,
    None,
}

#[derive(Debug, Serialize, Deserialize, Clone, JsonSchema, Default)]
pub struct UserMessageOverrides {
    /// The parts to include in the user message
    pub parts: Vec<PartDefinition>,
    /// If true, artifacts will be expanded to their actual content (e.g., image artifacts become Part::Image)
    #[serde(default)]
    pub include_artifacts: bool,
    /// If true (default), step count information will be included at the end of the user message
    #[serde(default = "default_include_step_count")]
    pub include_step_count: Option<bool>,
}

fn default_include_step_count() -> Option<bool> {
    Some(true)
}

#[derive(Debug, Serialize, Deserialize, Clone, JsonSchema)]
#[serde(tag = "type", content = "source", rename_all = "snake_case")]
pub enum PartDefinition {
    Template(String),   // Prompt Template Key
    SessionKey(String), // Session key reference
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct LlmDefinition {
    /// The name of the agent.
    pub name: String,
    /// Settings related to the model used by the agent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_settings: Option<ModelSettings>,
    /// Tool calling configuration
    #[serde(default)]
    pub tool_format: ToolCallFormat,
    /// How tools are delivered to the LLM (all upfront vs on-demand search)
    #[serde(default)]
    pub tool_delivery_mode: ToolDeliveryMode,
}

impl LlmDefinition {
    /// Get a reference to model_settings.
    /// Returns an error if model_settings is None.
    pub fn ms(&self) -> Result<&ModelSettings, String> {
        self.model_settings.as_ref().ok_or_else(|| {
            "No model configured. Please set a default model in Agent Settings → Default Model."
                .to_string()
        })
    }

    /// Get a mutable reference to model_settings.
    /// Returns an error if model_settings is None.
    pub fn ms_mut(&mut self) -> Result<&mut ModelSettings, String> {
        self.model_settings.as_mut().ok_or_else(|| {
            "No model configured. Please set a default model in Agent Settings → Default Model."
                .to_string()
        })
    }
}

/// Runtime environment in which the agent is executing.
/// Determines which built-in agent variants and tools are available.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Hash, Default)]
#[serde(rename_all = "snake_case")]
pub enum RuntimeMode {
    /// Running from distri-cli with local filesystem access
    Cli,
    /// Running on distri-cloud server (browsr sandbox for code execution)
    #[default]
    Cloud,
    /// Running in browser with IndexedDB filesystem
    Browser,
}

/// Agent definition - complete configuration for an agent
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
pub struct StandardDefinition {
    /// The name of the agent.
    pub name: String,
    /// A brief description of the agent's purpose.
    #[serde(default)]
    pub description: String,

    /// The version of the agent.
    #[serde(default = "default_agent_version")]
    pub version: Option<String>,

    /// Instructions for the agent - serves as an introduction defining what the agent is and does.
    #[serde(default)]
    pub instructions: String,

    /// A list of MCP server definitions associated with the agent.
    #[serde(default)]
    pub mcp_servers: Option<Vec<McpDefinition>>,
    /// Settings related to the model used by the agent.
    /// When `None`, the agent inherits model settings from the orchestrator context defaults.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_settings: Option<ModelSettings>,
    /// Optional lower-level model settings for lightweight analysis helpers
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub analysis_model_settings: Option<ModelSettings>,

    /// The size of the history to maintain for the agent.
    #[serde(default = "default_history_size")]
    pub history_size: Option<usize>,
    /// The new strategy configuration for the agent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub strategy: Option<AgentStrategy>,
    /// A2A-specific fields
    #[serde(default)]
    pub icon_url: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_iterations: Option<usize>,

    /// A2A agent card skills metadata (describes capabilities for agent-to-agent protocol)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub skills_description: Vec<AgentSkill>,

    /// Skills available for on-demand loading by this agent
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub available_skills: Vec<AvailableSkill>,

    /// List of sub-agents that this agent can transfer control to
    #[serde(default)]
    pub sub_agents: Vec<String>,

    /// Tool calling configuration
    #[serde(default)]
    pub tool_format: ToolCallFormat,

    /// How tools are delivered to the LLM (all upfront vs on-demand search)
    #[serde(default)]
    pub tool_delivery_mode: ToolDeliveryMode,

    /// Tools configuration for this agent
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tools: Option<ToolsConfig>,

    /// Custom handlebars partials (name -> template path) for use in custom prompts
    #[serde(default, skip_serializing_if = "std::collections::HashMap::is_empty")]
    pub partials: std::collections::HashMap<String, String>,

    /// Reflection configuration for post-execution analysis using a subagent
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reflection: Option<ReflectionConfig>,
    /// Whether to enable TODO management functionality
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enable_todos: Option<bool>,

    /// Browser configuration for this agent (enables shared Chromium automation)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub browser_config: Option<BrowserAgentConfig>,

    /// Whether to include shell/code execution tools (start_shell, execute_shell, stop_shell)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub include_shell: Option<bool>,

    /// Context size override for this agent (overrides model_settings.context_size)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_size: Option<u32>,

    /// Strategy for prompt construction (append default template vs fully custom)
    #[serde(
        skip_serializing_if = "Option::is_none",
        default = "default_append_default_instructions"
    )]
    pub append_default_instructions: Option<bool>,
    /// Whether to include the built-in scratchpad/history in prompts (default: true)
    #[serde(
        skip_serializing_if = "Option::is_none",
        default = "default_include_scratchpad"
    )]
    pub include_scratchpad: Option<bool>,

    /// Optional hook names to attach to this agent
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub hooks: Vec<String>,

    /// Custom user message construction (dynamic prompting)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_message_overrides: Option<UserMessageOverrides>,

    /// Whether context compaction is enabled for this agent (default: true)
    #[serde(
        default = "default_compaction_enabled",
        skip_serializing_if = "is_true"
    )]
    pub compaction_enabled: bool,

    /// **DEPRECATED**: prefer `runtime = ["cli"]` instead.
    ///
    /// When true, this is treated as `runtime = [Cli]` — the agent needs a
    /// CLI-style local environment (filesystem, shell exec). In a Cloud
    /// runtime the orchestrator forks the call into a sandbox via
    /// `BackgroundRunner`. Kept for backwards compatibility with existing
    /// agent definitions and the `--remote` CLI flag / `DefinitionOverrides.remote`.
    #[serde(default, alias = "deepagent")]
    pub remote: bool,

    /// Runtime constraint for this agent. Like Docker's `platforms` field:
    ///
    /// - empty / omitted → runs in any runtime (default).
    /// - `["cli"]` → only runs when `ExecutorContext.runtime_mode == Cli`,
    ///   OR via a `BackgroundRunner` providing `Cli` (e.g. `SandboxLauncher`
    ///   spawning `distri-cli` inside a browsr container).
    /// - `["cli", "cloud"]` → runs in either Cli or Cloud, but not Browser.
    ///
    /// When the current runtime doesn't match any allowed value and no
    /// compatible runner exists, the orchestrator fails fast at request entry.
    ///
    /// Accepts both scalar (`runtime = "cli"`) and array (`runtime = ["cli"]`)
    /// syntax in TOML/JSON for ergonomics.
    #[serde(
        default,
        deserialize_with = "deserialize_runtime_modes",
        skip_serializing_if = "Vec::is_empty"
    )]
    pub runtime: Vec<RuntimeMode>,
}

/// Accept either a single `RuntimeMode` string or an array of them.
fn deserialize_runtime_modes<'de, D>(deserializer: D) -> Result<Vec<RuntimeMode>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de::{self, Deserialize};

    #[derive(Deserialize)]
    #[serde(untagged)]
    enum OneOrMany {
        One(RuntimeMode),
        Many(Vec<RuntimeMode>),
    }

    match Option::<OneOrMany>::deserialize(deserializer)? {
        None => Ok(Vec::new()),
        Some(OneOrMany::One(rt)) => Ok(vec![rt]),
        Some(OneOrMany::Many(v)) => {
            // Reject duplicates so authors notice typos like ["cli", "cli"].
            let mut seen = std::collections::HashSet::new();
            for rt in &v {
                let key = format!("{:?}", rt);
                if !seen.insert(key) {
                    return Err(de::Error::custom(format!(
                        "duplicate runtime entry: {:?}",
                        rt
                    )));
                }
            }
            Ok(v)
        }
    }
}
fn default_append_default_instructions() -> Option<bool> {
    Some(true)
}
fn default_include_scratchpad() -> Option<bool> {
    Some(true)
}
fn default_compaction_enabled() -> bool {
    true
}
fn is_true(v: &bool) -> bool {
    *v
}
impl StandardDefinition {
    /// The set of runtimes this agent is allowed to run in, with the
    /// deprecated `remote: true` flag merged in (treated as `[Cli]` when
    /// `runtime` is empty).
    ///
    /// Empty result = no constraint = runs anywhere.
    pub fn allowed_runtimes(&self) -> Vec<RuntimeMode> {
        if !self.runtime.is_empty() {
            return self.runtime.clone();
        }
        if self.remote {
            return vec![RuntimeMode::Cli];
        }
        Vec::new()
    }

    /// Whether this agent can execute given the caller's `current` runtime,
    /// optionally with a `BackgroundRunner` providing an alternative runtime
    /// via remote dispatch.
    ///
    /// Returns true when:
    /// - the agent has no runtime constraint, OR
    /// - the current runtime matches one of the allowed runtimes, OR
    /// - a runner is available whose `provided_runtime` matches one of the
    ///   allowed runtimes.
    pub fn is_runnable_in(
        &self,
        current: &RuntimeMode,
        runner_provides: Option<&RuntimeMode>,
    ) -> bool {
        let allowed = self.allowed_runtimes();
        if allowed.is_empty() {
            return true;
        }
        if allowed.iter().any(|rt| rt == current) {
            return true;
        }
        match runner_provides {
            Some(p) => allowed.iter().any(|rt| rt == p),
            None => false,
        }
    }

    /// Check if browser should be initialized automatically in orchestrator (default: false)
    pub fn should_use_browser(&self) -> bool {
        self.browser_config
            .as_ref()
            .map(|cfg| cfg.is_enabled())
            .unwrap_or(false)
    }

    /// Returns browser config if defined
    pub fn browser_settings(&self) -> Option<&BrowserAgentConfig> {
        self.browser_config.as_ref()
    }

    /// Returns the runtime Chromium driver configuration if enabled
    pub fn browser_runtime_config(&self) -> Option<BrowsrClientConfig> {
        self.browser_config.as_ref().map(|cfg| cfg.runtime_config())
    }

    /// Should browser session state be serialized after tool runs
    pub fn should_persist_browser_session(&self) -> bool {
        self.browser_config
            .as_ref()
            .map(|cfg| cfg.should_persist_session())
            .unwrap_or(false)
    }

    /// Check if reflection is enabled (default: false)
    pub fn is_reflection_enabled(&self) -> bool {
        self.reflection.as_ref().map(|r| r.enabled).unwrap_or(false)
    }

    /// Get the reflection configuration, if any
    pub fn reflection_config(&self) -> Option<&ReflectionConfig> {
        self.reflection.as_ref().filter(|r| r.enabled)
    }
    /// Check if TODO management functionality is enabled (default: false)
    pub fn is_todos_enabled(&self) -> bool {
        self.enable_todos.unwrap_or(false)
    }

    /// Check if shell/code execution tools should be included (default: false)
    pub fn should_include_shell(&self) -> bool {
        self.include_shell.unwrap_or(false)
    }

    /// Get model settings if configured.
    pub fn model_settings(&self) -> Option<&ModelSettings> {
        self.model_settings.as_ref()
    }

    /// Get a mutable reference to model settings, if present.
    pub fn model_settings_mut(&mut self) -> Option<&mut ModelSettings> {
        self.model_settings.as_mut()
    }

    /// Get the effective context size (agent-level override or model settings)
    pub fn get_effective_context_size(&self) -> u32 {
        self.context_size
            .filter(|&s| s > 0)
            .or_else(|| {
                self.model_settings()
                    .map(|ms| ms.inner.context_size)
                    .filter(|&s| s > 0)
            })
            .unwrap_or_else(default_context_size)
    }

    /// Model settings to use for lightweight browser analysis helpers (e.g., observe_summary commands)
    pub fn analysis_model_settings_config(&self) -> Option<&ModelSettings> {
        self.analysis_model_settings
            .as_ref()
            .or_else(|| self.model_settings())
    }

    /// Whether to include the persistent scratchpad/history in prompts
    pub fn include_scratchpad(&self) -> bool {
        self.include_scratchpad.unwrap_or(true)
    }

    /// Apply definition overrides to this agent definition
    pub fn apply_overrides(&mut self, overrides: DefinitionOverrides) {
        // Override model settings (only if model_settings already exists)
        if let Some(ref mut ms) = self.model_settings {
            if let Some(model) = overrides.model {
                // Strip provider prefix if present (e.g. "custom_microsoft_foundry/gpt-5.4" → "gpt-5.4")
                ms.model = model
                    .split_once('/')
                    .map(|(_, m)| m.to_string())
                    .unwrap_or(model);
            }
            if let Some(temperature) = overrides.temperature {
                ms.inner.temperature = Some(temperature);
            }
            if let Some(max_tokens) = overrides.max_tokens {
                ms.inner.max_tokens = Some(max_tokens);
            }
        }

        // Override max_iterations
        if let Some(max_iterations) = overrides.max_iterations {
            self.max_iterations = Some(max_iterations);
        }

        // Override instructions
        if let Some(instructions) = overrides.instructions {
            self.instructions = instructions;
        }

        if let Some(remote) = overrides.remote {
            self.remote = remote;
        }

        if let Some(use_browser) = overrides.use_browser {
            let mut config = self.browser_config.clone().unwrap_or_default();
            config.enabled = use_browser;
            self.browser_config = Some(config);
        }

        // Append dynamic tool factories
        if let Some(dynamic_tools) = overrides.dynamic_tools {
            let tools = self.tools.get_or_insert_with(ToolsConfig::default);
            tools.dynamic.extend(dynamic_tools);
        }
    }
}

/// Tools configuration for agents
/// Canonical list of valid builtin tool names.
///
/// Includes both server-executed tools (search, start_shell, etc.) and
/// client-executed tools (http_request). Agent definitions reference these
/// by name in `tools.builtin = [...]`.
pub const VALID_BUILTIN_TOOLS: &[&str] = &[
    // Agent control
    "final",
    "reflect",
    "transfer_to_agent",
    // Browser & scraping
    "browsr_scrape",
    "browsr_browser",
    "browsr_crawl",
    "browser_step",
    "search",
    // Shell
    "start_shell",
    "execute_shell",
    "stop_shell",
    // Code execution
    "distri_execute_code",
    // Tool discovery
    "tool_search",
    "load_skill",
    // Connection & secrets
    "inject_connection_env",
    // Logging
    "console_log",
    // Artifacts & filesystem
    "artifact_tool",
    // Todos
    "todos",
];

/// Tools that always get full schemas, never deferred.
/// These are the most commonly used tools that agents need immediately.
pub const CORE_TOOLS: &[&str] = &[
    "final",
    "transfer_to_agent",
    "tool_search",
    "write_todos",
    "execute_shell",
    "start_shell",
    "load_skill",
];

/// Default threshold: defer tools when total count exceeds this.
pub const DEFAULT_DEFERRED_THRESHOLD: usize = 15;

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(deny_unknown_fields)]
pub struct ToolsConfig {
    /// Built-in tools to include (e.g., ["final", "transfer_to_agent"])
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub builtin: Vec<String>,

    /// Dynamic tool factories — each creates a named tool at runtime.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dynamic: Vec<crate::dynamic_tool::DynamicToolFactory>,

    /// MCP server tool configurations
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub mcp: Vec<McpToolConfig>,

    /// External tools to include from client
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub external: Option<Vec<String>>,

    /// How tools are delivered to the model. Defaults to `Full`.
    /// When set to `Deferred`, only core tools get full schemas;
    /// others appear as name+description and must be fetched via `tool_search`.
    #[serde(default, skip_serializing_if = "is_default_delivery_mode")]
    pub delivery_mode: ToolDeliveryMode,

    /// Tool count threshold for automatic deferral.
    /// When `delivery_mode` is `Deferred` and total tools exceed this,
    /// non-core tools are deferred. Default: 15.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deferred_threshold: Option<usize>,

    /// Additional tool names to always include with full schemas (beyond CORE_TOOLS).
    /// Useful for agent-specific tools that should never be deferred.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub always_full_schema: Vec<String>,
}

fn is_default_delivery_mode(mode: &ToolDeliveryMode) -> bool {
    *mode == ToolDeliveryMode::Deferred
}

impl ToolsConfig {
    /// Validate that all builtin tool names are recognized.
    /// Returns a list of invalid tool names, or empty if all are valid.
    pub fn invalid_builtin_tools(&self) -> Vec<String> {
        self.builtin
            .iter()
            .filter(|name| !VALID_BUILTIN_TOOLS.contains(&name.as_str()))
            .cloned()
            .collect()
    }

    /// Whether a tool should always get a full schema (never deferred).
    pub fn is_core_tool(&self, name: &str) -> bool {
        CORE_TOOLS.contains(&name)
            || self.always_full_schema.iter().any(|n| n == name)
            // call_* agent tools are always core (the model needs to know how to call sub-agents)
            || name.starts_with("call_")
    }

    /// Effective threshold for automatic tool deferral.
    pub fn effective_threshold(&self) -> usize {
        self.deferred_threshold
            .unwrap_or(DEFAULT_DEFERRED_THRESHOLD)
    }

    /// Determine the effective delivery mode given the total tool count.
    /// If mode is `Full` but tool count exceeds threshold, stays `Full`
    /// Deferred always stays Deferred — context efficiency is the default.
    pub fn effective_delivery_mode(&self, _total_tools: usize) -> ToolDeliveryMode {
        self.delivery_mode.clone()
    }
}

// Where filesystem and artifact tools should execute.
// Deprecated: filesystem tools are no longer included as server builtins.

/// Configuration for tools from an MCP server
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct McpToolConfig {
    /// Name of the MCP server
    pub server: String,

    /// Include patterns (glob-style, e.g., ["fetch_*", "extract_text"])
    /// Use ["*"] to include all tools from the server
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub include: Vec<String>,

    /// Exclude patterns (glob-style, e.g., ["delete_*", "rm_*"])
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub exclude: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct McpDefinition {
    /// The filter applied to the tools in this MCP definition.
    #[serde(default)]
    pub filter: Option<Vec<String>>,
    /// The name of the MCP server.
    pub name: String,
    /// The type of the MCP server (Tool or Agent).
    #[serde(default)]
    pub r#type: McpServerType,
    /// Authentication configuration for this MCP server.
    #[serde(default)]
    pub auth_config: Option<crate::a2a::SecurityScheme>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum McpServerType {
    #[default]
    Tool,
    Agent,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields, rename_all = "lowercase", tag = "name")]
pub enum ModelProvider {
    #[serde(rename = "openai")]
    OpenAI {},
    #[serde(rename = "openai_compat")]
    OpenAICompatible {
        base_url: String,
        api_key: Option<String>,
        project_id: Option<String>,
    },
    #[serde(rename = "azure_openai")]
    AzureOpenAI {
        base_url: String,
        api_key: Option<String>,
        deployment: String,
        #[serde(default = "ModelProvider::azure_api_version")]
        api_version: String,
    },
    #[serde(rename = "anthropic")]
    Anthropic {
        #[serde(default = "ModelProvider::anthropic_base_url")]
        base_url: Option<String>,
        api_key: Option<String>,
    },
    #[serde(rename = "gemini")]
    Gemini {
        #[serde(default = "ModelProvider::gemini_base_url")]
        base_url: String,
        api_key: Option<String>,
    },
    #[serde(rename = "azure_ai_foundry")]
    AzureAiFoundry {
        base_url: String,
        api_key: Option<String>,
    },
    #[serde(rename = "aws_bedrock")]
    AwsBedrock {
        base_url: String,
        api_key: Option<String>,
    },
    #[serde(rename = "google_vertex")]
    GoogleVertex {
        base_url: String,
        api_key: Option<String>,
        project_id: Option<String>,
    },
    #[serde(rename = "alibaba_cloud")]
    AlibabaCloud {
        #[serde(default = "ModelProvider::alibaba_cloud_base_url")]
        base_url: String,
        api_key: Option<String>,
    },
}
/// Defines the secret requirements for a provider
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderSecretDefinition {
    /// Provider identifier (e.g., "openai", "anthropic")
    pub id: String,
    /// Human-readable label
    pub label: String,
    /// List of required secret keys with metadata
    pub keys: Vec<SecretKeyDefinition>,
}

/// Defines a single secret key requirement
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecretKeyDefinition {
    /// The environment variable / secret store key (e.g., "OPENAI_API_KEY")
    pub key: String,
    /// Human-readable label
    pub label: String,
    /// Placeholder for UI input
    pub placeholder: String,
    /// Whether this secret is required (vs optional)
    #[serde(default = "default_required")]
    pub required: bool,
    /// Whether this field contains sensitive data (masked in UI, stored encrypted).
    /// Defaults to true. Set to false for non-sensitive config like URLs, project IDs.
    #[serde(default = "default_sensitive")]
    pub sensitive: bool,
}

fn default_required() -> bool {
    true
}

fn default_sensitive() -> bool {
    true
}

/// A model entry within a provider
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelInfo {
    /// Model identifier (e.g., "gpt-4o", "claude-sonnet-4")
    pub id: String,
    /// Human-readable name
    pub name: String,
}

/// Combined provider definition used in default_models.json.
/// Merges secret key definitions and well-known models into one entry per provider.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct DefaultProviderEntry {
    id: String,
    label: String,
    keys: Vec<SecretKeyDefinition>,
    models: Vec<crate::models::Model>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct DefaultModelsFile {
    providers: Vec<DefaultProviderEntry>,
}

fn load_default_providers() -> &'static [DefaultProviderEntry] {
    use std::sync::OnceLock;
    static PROVIDERS: OnceLock<Vec<DefaultProviderEntry>> = OnceLock::new();
    PROVIDERS.get_or_init(|| {
        let json = include_str!("default_models.json");
        let file: DefaultModelsFile =
            serde_json::from_str(json).expect("Failed to parse default_models.json");
        file.providers
    })
}

/// Models grouped by provider, with configuration status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderModels {
    /// Provider identifier
    pub provider_id: String,
    /// Human-readable provider name
    pub provider_label: String,
    /// Available models for this provider
    pub models: Vec<crate::models::Model>,
}

/// Provider models with configuration status (returned by API)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderModelsStatus {
    /// Provider identifier
    pub provider_id: String,
    /// Human-readable provider name
    pub provider_label: String,
    /// Whether the provider's API key is configured
    pub configured: bool,
    /// Available models for this provider
    pub models: Vec<crate::models::Model>,
}

impl Default for ModelProvider {
    fn default() -> Self {
        ModelProvider::OpenAI {}
    }
}

impl ModelProvider {
    pub fn openai_base_url() -> String {
        "https://api.openai.com/v1".to_string()
    }

    pub fn anthropic_base_url() -> Option<String> {
        None
    }

    pub fn gemini_base_url() -> String {
        "https://generativelanguage.googleapis.com/v1beta/openai".to_string()
    }

    pub fn azure_api_version() -> String {
        "2024-06-01".to_string()
    }

    pub fn alibaba_cloud_base_url() -> String {
        "https://dashscope-intl.aliyuncs.com/compatible-mode/v1".to_string()
    }

    /// Returns the provider type enum for this provider.
    pub fn provider_type(&self) -> crate::models::ProviderType {
        match self {
            ModelProvider::OpenAI {} => crate::models::ProviderType::OpenAI,
            ModelProvider::OpenAICompatible { .. } => {
                crate::models::ProviderType::Custom("openai_compat".to_string())
            }
            ModelProvider::AzureOpenAI { .. } => crate::models::ProviderType::Azure,
            ModelProvider::Anthropic { .. } => crate::models::ProviderType::Anthropic,
            ModelProvider::Gemini { .. } => crate::models::ProviderType::Gemini,
            ModelProvider::AzureAiFoundry { .. } => crate::models::ProviderType::AzureAiFoundry,
            ModelProvider::AwsBedrock { .. } => crate::models::ProviderType::AwsBedrock,
            ModelProvider::GoogleVertex { .. } => crate::models::ProviderType::GoogleVertex,
            ModelProvider::AlibabaCloud { .. } => crate::models::ProviderType::AlibabaCloud,
        }
    }

    /// Returns the provider ID string for secret lookup and "provider/model" format.
    pub fn provider_id(&self) -> &str {
        match self {
            ModelProvider::OpenAI {} => "openai",
            ModelProvider::OpenAICompatible { .. } => "openai_compat",
            ModelProvider::AzureOpenAI { .. } => "azure_openai",
            ModelProvider::Anthropic { .. } => "anthropic",
            ModelProvider::Gemini { .. } => "gemini",
            ModelProvider::AzureAiFoundry { .. } => "azure_ai_foundry",
            ModelProvider::AwsBedrock { .. } => "aws_bedrock",
            ModelProvider::GoogleVertex { .. } => "google_vertex",
            ModelProvider::AlibabaCloud { .. } => "alibaba_cloud",
        }
    }

    /// Returns the required secret keys for this provider.
    pub fn required_secret_keys(&self) -> Vec<&'static str> {
        match self {
            ModelProvider::OpenAI {} => vec!["OPENAI_API_KEY"],
            ModelProvider::OpenAICompatible { api_key, .. } => {
                if api_key.is_some() {
                    vec![]
                } else {
                    vec!["OPENAI_API_KEY"]
                }
            }
            ModelProvider::AzureOpenAI { api_key, .. } => {
                if api_key.is_some() {
                    vec![]
                } else {
                    vec!["AZURE_OPENAI_API_KEY"]
                }
            }
            ModelProvider::Anthropic { api_key, .. } => {
                if api_key.is_some() {
                    vec![]
                } else {
                    vec!["ANTHROPIC_API_KEY"]
                }
            }
            ModelProvider::Gemini { api_key, .. } => {
                if api_key.is_some() {
                    vec![]
                } else {
                    vec!["GEMINI_API_KEY"]
                }
            }
            ModelProvider::AzureAiFoundry { api_key, .. } => {
                if api_key.is_some() {
                    vec![]
                } else {
                    vec!["AZURE_AI_FOUNDRY_API_KEY"]
                }
            }
            ModelProvider::AwsBedrock { api_key, .. } => {
                if api_key.is_some() {
                    vec![]
                } else {
                    vec!["AWS_ACCESS_KEY_ID"]
                }
            }
            ModelProvider::GoogleVertex { api_key, .. } => {
                if api_key.is_some() {
                    vec![]
                } else {
                    vec!["GOOGLE_VERTEX_API_KEY"]
                }
            }
            ModelProvider::AlibabaCloud { api_key, .. } => {
                if api_key.is_some() {
                    vec![]
                } else {
                    vec!["DASHSCOPE_API_KEY"]
                }
            }
        }
    }

    /// Returns all provider secret definitions, loaded from default_models.json.
    pub fn all_provider_definitions() -> Vec<ProviderSecretDefinition> {
        load_default_providers()
            .iter()
            .map(|p| ProviderSecretDefinition {
                id: p.id.clone(),
                label: p.label.clone(),
                keys: p.keys.clone(),
            })
            .collect()
    }

    /// Returns the well-known models grouped by provider, loaded from default_models.json.
    pub fn well_known_models() -> Vec<ProviderModels> {
        load_default_providers()
            .iter()
            .filter(|p| !p.models.is_empty())
            .map(|p| ProviderModels {
                provider_id: p.id.clone(),
                provider_label: p.label.clone(),
                models: p.models.clone(),
            })
            .collect()
    }

    /// Get the human-readable name for a provider
    pub fn display_name(&self) -> &'static str {
        match self {
            ModelProvider::OpenAI {} => "OpenAI",
            ModelProvider::OpenAICompatible { .. } => "OpenAI Compatible",
            ModelProvider::AzureOpenAI { .. } => "Azure",
            ModelProvider::Anthropic { .. } => "Anthropic",
            ModelProvider::Gemini { .. } => "Google Gemini",
            ModelProvider::AzureAiFoundry { .. } => "Azure AI Foundry",
            ModelProvider::AwsBedrock { .. } => "AWS Bedrock",
            ModelProvider::GoogleVertex { .. } => "Google Vertex AI",
            ModelProvider::AlibabaCloud { .. } => "Alibaba Cloud",
        }
    }

    /// OTel `gen_ai.provider.name` attribute value for this provider.
    /// Uses the semantic convention identifiers from the 2025 GenAI spec.
    pub fn otel_provider_name(&self) -> &'static str {
        match self {
            ModelProvider::OpenAI { .. } => "openai",
            ModelProvider::OpenAICompatible { .. } => "openai",
            ModelProvider::AzureOpenAI { .. } => "azure.ai.openai",
            ModelProvider::Anthropic { .. } => "anthropic",
            ModelProvider::Gemini { .. } => "google.gemini",
            ModelProvider::AzureAiFoundry { .. } => "azure.ai.inference",
            ModelProvider::AwsBedrock { .. } => "aws.bedrock",
            ModelProvider::GoogleVertex { .. } => "gcp.vertex_ai",
            ModelProvider::AlibabaCloud { .. } => "alibaba_cloud",
        }
    }
}

/// Model settings configuration.
/// A `ModelSettings` always has a valid model string.
/// Use `Option<ModelSettings>` when no model is configured yet.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ModelSettings {
    pub model: String,
    #[serde(flatten)]
    pub inner: ModelSettingsInner,
}

/// Optional/defaultable model parameters. Split from `ModelSettings` so callers
/// can construct `ModelSettings { model: "...", ..Default::default() }` easily
/// via the `inner` field having `Default`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
pub struct ModelSettingsInner {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u32>,
    #[serde(default = "default_context_size")]
    pub context_size: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub frequency_penalty: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub presence_penalty: Option<f32>,
    #[serde(default = "default_model_provider")]
    pub provider: ModelProvider,
    /// Additional parameters for the agent, if any.
    #[serde(default)]
    pub parameters: Option<serde_json::Value>,
    /// The format of the response, if specified.
    #[serde(default)]
    pub response_format: Option<serde_json::Value>,
    /// Which OpenAI-family API format to use (auto-detected by default).
    /// Only relevant for OpenAI, OpenAI-compatible, and Azure OpenAI providers.
    #[serde(default, skip_serializing_if = "is_default_api_format")]
    pub api_format: OpenAiApiFormat,
}

impl ModelSettings {
    /// Create a new `ModelSettings` with the given model and default inner settings.
    pub fn new(model: impl Into<String>) -> Self {
        Self {
            model: model.into(),
            inner: ModelSettingsInner::default(),
        }
    }

    /// Parse a "provider/model" string (e.g. "anthropic/claude-sonnet-4") into ModelSettings.
    /// Returns None if the format is invalid.
    /// For custom providers (prefixed with "custom_"), returns an OpenAICompatible provider
    /// with empty base_url/api_key — the caller must fill these from secrets/config.
    /// Parse "provider/model" string into ModelSettings.
    /// Returns Err with a descriptive message if the provider is not recognized.
    /// Returns Ok(None) if the input is empty or has no slash.
    pub fn from_provider_model_str(s: &str) -> Result<Option<Self>, String> {
        let Some((provider_str, model_id)) = s.split_once('/') else {
            return Ok(None);
        };
        if model_id.is_empty() {
            return Ok(None);
        }
        let provider = match provider_str {
            "openai" => ModelProvider::OpenAI {},
            "anthropic" => ModelProvider::Anthropic {
                base_url: None,
                api_key: None,
            },
            "azure_openai" | "azure" => ModelProvider::AzureOpenAI {
                base_url: String::new(),
                api_key: None,
                deployment: model_id.to_string(),
                api_version: ModelProvider::azure_api_version(),
            },
            "gemini" => ModelProvider::Gemini {
                base_url: ModelProvider::gemini_base_url(),
                api_key: None,
            },
            "azure_ai_foundry" => ModelProvider::AzureAiFoundry {
                base_url: String::new(),
                api_key: None,
            },
            "aws_bedrock" => ModelProvider::AwsBedrock {
                base_url: String::new(),
                api_key: None,
            },
            "google_vertex" => ModelProvider::GoogleVertex {
                base_url: String::new(),
                api_key: None,
                project_id: None,
            },
            "alibaba_cloud" => ModelProvider::AlibabaCloud {
                base_url: ModelProvider::alibaba_cloud_base_url(),
                api_key: None,
            },
            _ if provider_str.starts_with("custom_") => ModelProvider::OpenAICompatible {
                base_url: String::new(),
                api_key: None,
                project_id: None,
            },
            // Unknown providers — treat as OpenAI-compatible
            _ => ModelProvider::OpenAICompatible {
                base_url: String::new(),
                api_key: None,
                project_id: None,
            },
        };
        Ok(Some(Self {
            model: model_id.to_string(),
            inner: ModelSettingsInner {
                provider,
                ..Default::default()
            },
        }))
    }

    /// Merge base (workspace) model settings with agent/request-level overrides.
    ///
    /// Provider resolution:
    /// - If the override explicitly sets a provider (not the default OpenAI),
    ///   the override's provider and model are used.
    /// - If only the base has a non-default provider and the override uses default
    ///   OpenAI, the base's provider AND model win — the override's bare model name
    ///   is ignored because it may not exist on the base provider.
    /// - Otherwise, the override's model wins if non-empty.
    ///
    /// Scalar fields (temperature, max_tokens, etc.) use override if present, else base.
    ///
    /// Returns `None` if the final model string is empty.
    pub fn merge(&self, override_settings: &ModelSettings) -> Option<ModelSettings> {
        let default_provider = ModelProvider::OpenAI {};
        let override_has_explicit_provider = std::mem::discriminant(&override_settings.inner.provider)
            != std::mem::discriminant(&default_provider);
        let base_has_explicit_provider = std::mem::discriminant(&self.inner.provider)
            != std::mem::discriminant(&default_provider);

        let (provider, model) = if override_has_explicit_provider {
            // Override explicitly set a provider — use override's provider and model.
            let model = if !override_settings.model.is_empty() {
                override_settings.model.clone()
            } else {
                self.model.clone()
            };
            (override_settings.inner.provider.clone(), model)
        } else if base_has_explicit_provider {
            // Base uses a non-default provider and override didn't specify one — use
            // base's provider AND model to avoid mismatching model names.
            let model = if !self.model.is_empty() {
                self.model.clone()
            } else if !override_settings.model.is_empty() {
                override_settings.model.clone()
            } else {
                String::new()
            };
            (self.inner.provider.clone(), model)
        } else {
            // Both use default OpenAI — override model can win.
            let model = if !override_settings.model.is_empty() {
                override_settings.model.clone()
            } else {
                self.model.clone()
            };
            (self.inner.provider.clone(), model)
        };

        if model.is_empty() {
            return None;
        }

        let default_context_size = 20000u32;
        Some(ModelSettings {
            model,
            inner: ModelSettingsInner {
                temperature: override_settings
                    .inner
                    .temperature
                    .or(self.inner.temperature),
                max_tokens: override_settings.inner.max_tokens.or(self.inner.max_tokens),
                context_size: if override_settings.inner.context_size != default_context_size {
                    override_settings.inner.context_size
                } else {
                    self.inner.context_size
                },
                top_p: override_settings.inner.top_p.or(self.inner.top_p),
                frequency_penalty: override_settings
                    .inner
                    .frequency_penalty
                    .or(self.inner.frequency_penalty),
                presence_penalty: override_settings
                    .inner
                    .presence_penalty
                    .or(self.inner.presence_penalty),
                provider,
                parameters: if override_settings.inner.parameters.is_some() {
                    override_settings.inner.parameters.clone()
                } else {
                    self.inner.parameters.clone()
                },
                response_format: if override_settings.inner.response_format.is_some() {
                    override_settings.inner.response_format.clone()
                } else {
                    self.inner.response_format.clone()
                },
                api_format: if override_settings.inner.api_format != OpenAiApiFormat::Auto {
                    override_settings.inner.api_format.clone()
                } else {
                    self.inner.api_format.clone()
                },
            },
        })
    }
}

// Default functions
pub fn default_agent_version() -> Option<String> {
    Some("0.2.2".to_string())
}

fn default_model_provider() -> ModelProvider {
    ModelProvider::OpenAI {}
}

fn default_context_size() -> u32 {
    20000 // Default limit for general use - agents can override with higher values as needed
}

fn is_default_api_format(f: &OpenAiApiFormat) -> bool {
    *f == OpenAiApiFormat::Auto
}

fn default_history_size() -> Option<usize> {
    Some(5)
}

impl StandardDefinition {
    pub fn validate(&self) -> anyhow::Result<()> {
        // Basic validation - can be expanded
        if self.name.is_empty() {
            return Err(anyhow::anyhow!("Agent name cannot be empty"));
        }

        // Validate reflection configuration
        if let Some(ref reflection) = self.reflection
            && reflection.enabled
        {
            // If a custom reflection_agent is specified, validate the name
            if let Some(ref agent_name) = reflection.reflection_agent
                && agent_name.is_empty()
            {
                return Err(anyhow::anyhow!(
                    "Reflection agent name cannot be empty when specified"
                ));
            }
        }

        Ok(())
    }

    /// Validate that a reflection agent definition has the "reflect" tool configured.
    /// This is called at registration time when we have access to the full agent config.
    pub fn validate_reflection_agent(agent_def: &StandardDefinition) -> anyhow::Result<()> {
        let has_reflect_tool = agent_def
            .tools
            .as_ref()
            .map(|t| t.builtin.iter().any(|name| name == "reflect"))
            .unwrap_or(false);

        if !has_reflect_tool {
            // The built-in reflection_agent gets the reflect tool automatically,
            // but custom reflection agents must explicitly list it
            anyhow::bail!(
                "Reflection agent '{}' must have the 'reflect' tool in its tools.builtin configuration",
                agent_def.name
            );
        }

        Ok(())
    }
}

impl From<StandardDefinition> for LlmDefinition {
    fn from(definition: StandardDefinition) -> Self {
        let model_settings = match (definition.model_settings, definition.context_size) {
            (Some(mut ms), Some(ctx)) => {
                ms.inner.context_size = ctx;
                Some(ms)
            }
            (ms, _) => ms,
        };

        Self {
            name: definition.name,
            model_settings,
            tool_format: definition.tool_format,
            tool_delivery_mode: definition.tool_delivery_mode,
        }
    }
}

impl ToolsConfig {
    /// Create a simple configuration with just built-in tools
    pub fn builtin_only(tools: Vec<&str>) -> Self {
        Self {
            builtin: tools.into_iter().map(|s| s.to_string()).collect(),
            ..Default::default()
        }
    }

    /// Create a configuration that includes all tools from an MCP server
    pub fn mcp_all(server: &str) -> Self {
        Self {
            mcp: vec![McpToolConfig {
                server: server.to_string(),
                include: vec!["*".to_string()],
                exclude: vec![],
            }],
            ..Default::default()
        }
    }

    /// Create a configuration with specific MCP tool patterns
    pub fn mcp_filtered(server: &str, include: Vec<&str>, exclude: Vec<&str>) -> Self {
        Self {
            mcp: vec![McpToolConfig {
                server: server.to_string(),
                include: include.into_iter().map(|s| s.to_string()).collect(),
                exclude: exclude.into_iter().map(|s| s.to_string()).collect(),
            }],
            ..Default::default()
        }
    }
}

pub async fn parse_agent_markdown_content(content: &str) -> Result<StandardDefinition, AgentError> {
    // Split by --- to separate TOML frontmatter from markdown content
    let parts: Vec<&str> = content.split("---").collect();

    if parts.len() < 3 {
        return Err(AgentError::Validation(
            "Invalid agent markdown format. Expected TOML frontmatter between --- markers"
                .to_string(),
        ));
    }

    // Parse TOML frontmatter (parts[1] is between the first two --- markers)
    let toml_content = parts[1].trim();
    let mut agent_def: crate::StandardDefinition =
        toml::from_str(toml_content).map_err(|e| AgentError::Validation(e.to_string()))?;

    // Validate agent name format using centralized validation
    if let Err(validation_error) = validate_plugin_name(&agent_def.name) {
        return Err(AgentError::Validation(format!(
            "Invalid agent name '{}': {}",
            agent_def.name, validation_error
        )));
    }

    // Validate that agent name characters are valid (alphanumeric, underscore, or single '/' for namespacing)
    if !agent_def
        .name
        .chars()
        .all(|c| c.is_alphanumeric() || c == '_' || c == '/')
        || agent_def
            .name
            .chars()
            .next()
            .is_some_and(|c| c.is_numeric())
        || agent_def.name.chars().filter(|&c| c == '/').count() > 1
    {
        return Err(AgentError::Validation(format!(
            "Invalid agent name '{}': Agent names must be alphanumeric with underscores, at most one '/' for namespacing (e.g. '_system/plan'), cannot start with number.",
            agent_def.name
        )));
    }

    // Extract markdown instructions (everything after the second ---)
    let instructions = parts[2..].join("---").trim().to_string();

    // Set the instructions in the agent definition
    agent_def.instructions = instructions;

    Ok(agent_def)
}

/// Validate plugin name follows naming conventions
/// Plugin names must be valid identifiers. At most one '/' is allowed for workspace namespacing (e.g. 'workspace/agent').
pub fn validate_plugin_name(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("Plugin name cannot be empty".to_string());
    }

    if name.contains('-') {
        return Err(format!(
            "Plugin name '{}' cannot contain hyphens. Use underscores instead.",
            name
        ));
    }

    let slash_count = name.chars().filter(|&c| c == '/').count();
    if slash_count > 1 {
        return Err(format!(
            "Plugin name '{}' can contain at most one '/' for workspace namespacing (e.g. 'workspace/agent')",
            name
        ));
    }

    // Validate each segment (split by optional slash)
    let segments: Vec<&str> = name.split('/').collect();
    for segment in &segments {
        if segment.is_empty() {
            return Err(format!(
                "Plugin name '{}' has an empty segment around '/'",
                name
            ));
        }

        if let Some(first_char) = segment.chars().next()
            && !first_char.is_ascii_alphabetic()
            && first_char != '_'
        {
            return Err(format!(
                "Each segment in '{}' must start with a letter or underscore",
                name
            ));
        }

        for ch in segment.chars() {
            if !ch.is_ascii_alphanumeric() && ch != '_' {
                return Err(format!(
                    "Plugin name '{}' can only contain letters, numbers, underscores, and at most one '/' for namespacing",
                    name
                ));
            }
        }
    }

    Ok(())
}

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

    #[test]
    fn test_compaction_enabled_defaults_to_true_via_serde() {
        // serde default uses default_compaction_enabled() -> true
        let json = r#"{"name": "test"}"#;
        let def: StandardDefinition = serde_json::from_str(json).unwrap();
        assert!(def.compaction_enabled);
    }

    #[test]
    fn test_compaction_enabled_deserializes_true_when_absent() {
        let json = r#"{"name": "test", "description": "test agent"}"#;
        let def: StandardDefinition = serde_json::from_str(json).unwrap();
        assert!(def.compaction_enabled);
    }

    #[test]
    fn test_compaction_enabled_deserializes_false() {
        let json = r#"{"name": "test", "description": "test agent", "compaction_enabled": false}"#;
        let def: StandardDefinition = serde_json::from_str(json).unwrap();
        assert!(!def.compaction_enabled);
    }

    #[test]
    fn test_compaction_enabled_true_skipped_in_serialization() {
        let def = StandardDefinition {
            name: "test".to_string(),
            compaction_enabled: true,
            ..Default::default()
        };
        let json = serde_json::to_string(&def).unwrap();
        assert!(!json.contains("compaction_enabled"));
    }

    #[test]
    fn test_compaction_enabled_false_serialized() {
        let def = StandardDefinition {
            name: "test".to_string(),
            compaction_enabled: false,
            ..Default::default()
        };
        let json = serde_json::to_string(&def).unwrap();
        assert!(json.contains("\"compaction_enabled\":false"));
    }

    #[test]
    fn test_max_tokens_optional_defaults_to_none() {
        let def = StandardDefinition::default();
        assert!(def.model_settings().is_none());
    }

    #[test]
    fn test_max_tokens_deserializes_when_present() {
        let json =
            r#"{"name": "test", "model_settings": {"model": "gpt-4.1", "max_tokens": 4096}}"#;
        let def: StandardDefinition = serde_json::from_str(json).unwrap();
        assert_eq!(def.model_settings().unwrap().inner.max_tokens, Some(4096));
    }

    #[test]
    fn test_max_tokens_none_when_absent() {
        let json = r#"{"name": "test", "model_settings": {"model": "gpt-4.1"}}"#;
        let def: StandardDefinition = serde_json::from_str(json).unwrap();
        assert!(def.model_settings().unwrap().inner.max_tokens.is_none());
    }

    #[test]
    fn test_max_tokens_none_skipped_in_serialization() {
        let settings = ModelSettings {
            model: "test-model".to_string(),
            inner: ModelSettingsInner {
                max_tokens: None,
                provider: ModelProvider::OpenAI {},
                ..Default::default()
            },
        };
        let json = serde_json::to_string(&settings).unwrap();
        assert!(!json.contains("max_tokens"));
    }

    #[test]
    fn test_max_tokens_some_serialized() {
        let settings = ModelSettings {
            model: "test-model".to_string(),
            inner: ModelSettingsInner {
                max_tokens: Some(2048),
                provider: ModelProvider::OpenAI {},
                ..Default::default()
            },
        };
        let json = serde_json::to_string(&settings).unwrap();
        assert!(json.contains("\"max_tokens\":2048"));
    }

    #[test]
    fn test_api_format_auto_detect_codex_prefix() {
        let fmt = OpenAiApiFormat::Auto;
        assert_eq!(
            fmt.resolve("codex-mini-latest"),
            ResolvedOpenAiApiFormat::Responses
        );
        assert_eq!(
            fmt.resolve("codex-mini-2025-01-24"),
            ResolvedOpenAiApiFormat::Responses
        );
    }

    #[test]
    fn test_api_format_auto_detect_codex_suffix() {
        let fmt = OpenAiApiFormat::Auto;
        assert_eq!(
            fmt.resolve("gpt-5.1-codex"),
            ResolvedOpenAiApiFormat::Responses
        );
        assert_eq!(
            fmt.resolve("gpt-5.3-codex"),
            ResolvedOpenAiApiFormat::Responses
        );
    }

    #[test]
    fn test_api_format_auto_detect_pro_models() {
        let fmt = OpenAiApiFormat::Auto;
        assert_eq!(fmt.resolve("gpt-5-pro"), ResolvedOpenAiApiFormat::Responses);
        assert_eq!(
            fmt.resolve("gpt-5.2-pro"),
            ResolvedOpenAiApiFormat::Responses
        );
        assert_eq!(
            fmt.resolve("gpt-5.4-pro"),
            ResolvedOpenAiApiFormat::Responses
        );
        assert_eq!(fmt.resolve("o3-pro"), ResolvedOpenAiApiFormat::Responses);
    }

    #[test]
    fn test_api_format_auto_detect_deep_research_models() {
        let fmt = OpenAiApiFormat::Auto;
        assert_eq!(
            fmt.resolve("o3-deep-research"),
            ResolvedOpenAiApiFormat::Responses
        );
        assert_eq!(
            fmt.resolve("o4-mini-deep-research"),
            ResolvedOpenAiApiFormat::Responses
        );
    }

    #[test]
    fn test_api_format_auto_detect_non_codex() {
        let fmt = OpenAiApiFormat::Auto;
        assert_eq!(fmt.resolve("gpt-4o"), ResolvedOpenAiApiFormat::Completions);
        assert_eq!(fmt.resolve("gpt-4.1"), ResolvedOpenAiApiFormat::Completions);
        assert_eq!(fmt.resolve("gpt-5"), ResolvedOpenAiApiFormat::Completions);
        assert_eq!(fmt.resolve("o1"), ResolvedOpenAiApiFormat::Completions);
        assert_eq!(
            fmt.resolve("gpt-5.4-mini"),
            ResolvedOpenAiApiFormat::Completions
        );
        assert_eq!(fmt.resolve("o3-mini"), ResolvedOpenAiApiFormat::Completions);
    }

    #[test]
    fn test_api_format_explicit_override() {
        // Explicit Responses overrides auto-detect even for non-codex models
        assert_eq!(
            OpenAiApiFormat::Responses.resolve("gpt-4o"),
            ResolvedOpenAiApiFormat::Responses
        );
        // Explicit Completions overrides auto-detect even for codex models
        assert_eq!(
            OpenAiApiFormat::Completions.resolve("codex-mini-latest"),
            ResolvedOpenAiApiFormat::Completions
        );
    }

    #[test]
    fn test_api_format_defaults_to_auto() {
        let inner = ModelSettingsInner::default();
        assert_eq!(inner.api_format, OpenAiApiFormat::Auto);
    }

    #[test]
    fn test_api_format_auto_skipped_in_serialization() {
        let settings = ModelSettings {
            model: "test-model".to_string(),
            inner: ModelSettingsInner {
                provider: ModelProvider::OpenAI {},
                ..Default::default()
            },
        };
        let json = serde_json::to_string(&settings).unwrap();
        assert!(!json.contains("api_format"));
    }

    #[test]
    fn test_api_format_responses_serialized() {
        let settings = ModelSettings {
            model: "test-model".to_string(),
            inner: ModelSettingsInner {
                api_format: OpenAiApiFormat::Responses,
                provider: ModelProvider::OpenAI {},
                ..Default::default()
            },
        };
        let json = serde_json::to_string(&settings).unwrap();
        assert!(json.contains("\"api_format\":\"responses\""));
    }

    #[test]
    fn test_api_format_deserializes_from_toml() {
        let toml_str = r#"
            model = "codex-mini-latest"
            api_format = "responses"
            [provider]
            name = "openai"
        "#;
        let settings: ModelSettings = toml::from_str(toml_str).unwrap();
        assert_eq!(settings.inner.api_format, OpenAiApiFormat::Responses);
    }

    // ── ToolDeliveryMode tests ────────────────────────────────────

    #[test]
    fn test_tool_delivery_mode_defaults_to_deferred() {
        let mode: ToolDeliveryMode = Default::default();
        assert_eq!(mode, ToolDeliveryMode::Deferred);
    }

    #[test]
    fn test_tool_delivery_mode_backwards_compat_all_tools() {
        // Old configs that used "all_tools" should deserialize to Full
        let json = r#""all_tools""#;
        let mode: ToolDeliveryMode = serde_json::from_str(json).unwrap();
        assert_eq!(mode, ToolDeliveryMode::Full);
    }

    #[test]
    fn test_tool_delivery_mode_backwards_compat_tool_search() {
        // Old configs that used "tool_search" should deserialize to Deferred
        let json = r#""tool_search""#;
        let mode: ToolDeliveryMode = serde_json::from_str(json).unwrap();
        assert_eq!(mode, ToolDeliveryMode::Deferred);
    }

    #[test]
    fn test_tools_config_is_core_tool() {
        let config = ToolsConfig::default();
        assert!(config.is_core_tool("final"));
        assert!(config.is_core_tool("tool_search"));
        assert!(config.is_core_tool("execute_shell"));
        assert!(config.is_core_tool("call_coder"));
        assert!(!config.is_core_tool("browsr_scrape"));
    }

    #[test]
    fn test_tools_config_always_full_schema() {
        let config = ToolsConfig {
            always_full_schema: vec!["browsr_scrape".to_string()],
            ..Default::default()
        };
        assert!(config.is_core_tool("browsr_scrape"));
        assert!(!config.is_core_tool("browsr_browser"));
    }

    #[test]
    fn test_effective_delivery_mode_full_stays_full() {
        let config = ToolsConfig {
            delivery_mode: ToolDeliveryMode::Full,
            ..Default::default()
        };
        // Even with many tools, Full stays Full
        assert_eq!(config.effective_delivery_mode(100), ToolDeliveryMode::Full);
    }

    #[test]
    fn test_effective_delivery_mode_deferred_stays_deferred() {
        let config = ToolsConfig {
            delivery_mode: ToolDeliveryMode::Deferred,
            deferred_threshold: Some(20),
            ..Default::default()
        };
        // Deferred always stays Deferred regardless of count
        assert_eq!(
            config.effective_delivery_mode(10),
            ToolDeliveryMode::Deferred
        );
    }

    #[test]
    fn test_effective_delivery_mode_deferred_over_threshold() {
        let config = ToolsConfig {
            delivery_mode: ToolDeliveryMode::Deferred,
            deferred_threshold: Some(10),
            ..Default::default()
        };
        // Over threshold: stays Deferred
        assert_eq!(
            config.effective_delivery_mode(15),
            ToolDeliveryMode::Deferred
        );
    }

    #[test]
    fn test_runtime_mode_serde() {
        let mode: RuntimeMode = serde_json::from_str("\"cloud\"").unwrap();
        assert_eq!(mode, RuntimeMode::Cloud);
        let mode: RuntimeMode = serde_json::from_str("\"cli\"").unwrap();
        assert_eq!(mode, RuntimeMode::Cli);
        let mode: RuntimeMode = serde_json::from_str("\"browser\"").unwrap();
        assert_eq!(mode, RuntimeMode::Browser);
        assert_eq!(RuntimeMode::default(), RuntimeMode::Cloud);
        let json = serde_json::to_string(&RuntimeMode::Cli).unwrap();
        assert_eq!(json, "\"cli\"");
    }

    // ── ModelSettings::merge tests ──────────────────────────────────────────

    #[test]
    fn merge_both_default_openai_agent_model_wins() {
        let base = ModelSettings::new("gpt-5.1");
        let agent = ModelSettings::new("gpt-4.1-mini");

        let result = base.merge(&agent).unwrap();
        assert_eq!(result.model, "gpt-4.1-mini");
        assert!(matches!(result.inner.provider, ModelProvider::OpenAI {}));
    }

    #[test]
    fn merge_both_default_openai_base_model_used_when_agent_empty() {
        let base = ModelSettings::new("gpt-5.1");
        let agent = ModelSettings::new("");

        let result = base.merge(&agent).unwrap();
        assert_eq!(result.model, "gpt-5.1");
    }

    #[test]
    fn merge_agent_explicit_provider_wins() {
        let base = ModelSettings {
            model: "gpt-5.1".into(),
            inner: ModelSettingsInner {
                provider: ModelProvider::OpenAICompatible {
                    base_url: "https://custom.com/v1".into(),
                    api_key: Some("key".into()),
                    project_id: None,
                },
                ..Default::default()
            },
        };
        let agent = ModelSettings {
            model: "claude-sonnet-4".into(),
            inner: ModelSettingsInner {
                provider: ModelProvider::Anthropic {
                    base_url: None,
                    api_key: None,
                },
                ..Default::default()
            },
        };

        let result = base.merge(&agent).unwrap();
        assert_eq!(result.model, "claude-sonnet-4");
        assert!(matches!(result.inner.provider, ModelProvider::Anthropic { .. }));
    }

    #[test]
    fn merge_agent_explicit_provider_no_model_uses_base() {
        let base = ModelSettings::new("gpt-5.1");
        let agent = ModelSettings {
            model: "".into(),
            inner: ModelSettingsInner {
                provider: ModelProvider::Anthropic {
                    base_url: None,
                    api_key: None,
                },
                ..Default::default()
            },
        };

        let result = base.merge(&agent).unwrap();
        assert_eq!(result.model, "gpt-5.1");
        assert!(matches!(result.inner.provider, ModelProvider::Anthropic { .. }));
    }

    #[test]
    fn merge_workspace_custom_provider_overrides_agent_model() {
        let base = ModelSettings {
            model: "gpt-5.4".into(),
            inner: ModelSettingsInner {
                provider: ModelProvider::OpenAICompatible {
                    base_url: "https://custom.azure.com/openai/v1".into(),
                    api_key: Some("test-key".into()),
                    project_id: None,
                },
                ..Default::default()
            },
        };
        // Agent has no explicit provider (default OpenAI) but different model
        let agent = ModelSettings::new("gpt-5.1");

        let result = base.merge(&agent).unwrap();
        assert_eq!(result.model, "gpt-5.4");
        assert!(matches!(result.inner.provider, ModelProvider::OpenAICompatible { .. }));
    }

    #[test]
    fn merge_workspace_custom_provider_agent_empty_model() {
        let base = ModelSettings {
            model: "gpt-5.4".into(),
            inner: ModelSettingsInner {
                provider: ModelProvider::OpenAICompatible {
                    base_url: "https://custom.azure.com/openai/v1".into(),
                    api_key: Some("test-key".into()),
                    project_id: None,
                },
                ..Default::default()
            },
        };
        let agent = ModelSettings::new("");

        let result = base.merge(&agent).unwrap();
        assert_eq!(result.model, "gpt-5.4");
    }

    #[test]
    fn merge_both_empty_returns_none() {
        let base = ModelSettings::new("");
        let agent = ModelSettings::new("");

        assert!(base.merge(&agent).is_none());
    }

    #[test]
    fn merge_workspace_empty_agent_empty_returns_none() {
        let base = ModelSettings {
            model: "".into(),
            inner: ModelSettingsInner {
                provider: ModelProvider::OpenAICompatible {
                    base_url: "https://custom.com".into(),
                    api_key: None,
                    project_id: None,
                },
                ..Default::default()
            },
        };
        let agent = ModelSettings::new("");

        assert!(base.merge(&agent).is_none());
    }

    #[test]
    fn merge_temperature_max_tokens_override() {
        let base = ModelSettings {
            model: "gpt-5.1".into(),
            inner: ModelSettingsInner {
                temperature: Some(0.5),
                max_tokens: Some(1000),
                top_p: Some(0.9),
                ..Default::default()
            },
        };
        let agent = ModelSettings {
            model: "gpt-4.1-mini".into(),
            inner: ModelSettingsInner {
                temperature: Some(0.9),
                max_tokens: None, // no override
                ..Default::default()
            },
        };

        let result = base.merge(&agent).unwrap();
        assert_eq!(result.model, "gpt-4.1-mini");
        assert_eq!(result.inner.temperature, Some(0.9));
        assert_eq!(result.inner.max_tokens, Some(1000)); // base value preserved
        assert_eq!(result.inner.top_p, Some(0.9));      // base value preserved
    }

    #[test]
    fn merge_context_size_non_default_wins() {
        let base = ModelSettings {
            model: "gpt-5.1".into(),
            inner: ModelSettingsInner {
                context_size: 20000, // default
                ..Default::default()
            },
        };
        let agent = ModelSettings {
            model: "gpt-4.1-mini".into(),
            inner: ModelSettingsInner {
                context_size: 100000, // explicitly set
                ..Default::default()
            },
        };

        let result = base.merge(&agent).unwrap();
        assert_eq!(result.inner.context_size, 100000);
    }

    #[test]
    fn merge_context_size_default_falls_back() {
        let base = ModelSettings {
            model: "gpt-5.1".into(),
            inner: ModelSettingsInner {
                context_size: 128000,
                ..Default::default()
            },
        };
        let agent = ModelSettings {
            model: "gpt-4.1-mini".into(),
            inner: ModelSettingsInner {
                context_size: 20000, // default — should use base
                ..Default::default()
            },
        };

        let result = base.merge(&agent).unwrap();
        assert_eq!(result.inner.context_size, 128000);
    }

    #[test]
    fn merge_azure_ai_foundry_base_url_preserved() {
        let base = ModelSettings {
            model: "gpt-5.4".into(),
            inner: ModelSettingsInner {
                provider: ModelProvider::AzureAiFoundry {
                    base_url: "https://myresource.openai.azure.com".into(),
                    api_key: Some("test-key".into()),
                },
                ..Default::default()
            },
        };
        let agent = ModelSettings::new("gpt-5.1");

        let result = base.merge(&agent).unwrap();
        assert_eq!(result.model, "gpt-5.4"); // workspace model wins
        assert!(matches!(result.inner.provider, ModelProvider::AzureAiFoundry { .. }));
        if let ModelProvider::AzureAiFoundry { base_url, .. } = result.inner.provider {
            assert_eq!(base_url, "https://myresource.openai.azure.com");
        }
    }

    #[test]
    fn merge_anthropic_provider_preserves_base_url() {
        let base = ModelSettings {
            model: "claude-sonnet-4".into(),
            inner: ModelSettingsInner {
                provider: ModelProvider::Anthropic {
                    base_url: Some("https://custom.anthropic.com".into()),
                    api_key: Some("key".into()),
                },
                temperature: Some(0.7),
                ..Default::default()
            },
        };
        let agent = ModelSettings::new("");

        let result = base.merge(&agent).unwrap();
        assert_eq!(result.model, "claude-sonnet-4");
        assert_eq!(result.inner.temperature, Some(0.7));
        if let ModelProvider::Anthropic { base_url, api_key } = result.inner.provider {
            assert_eq!(base_url, Some("https://custom.anthropic.com".into()));
            assert_eq!(api_key, Some("key".into()));
        }
    }

    #[test]
    fn merge_response_format_agent_wins() {
        let base = ModelSettings {
            model: "gpt-5.1".into(),
            inner: ModelSettingsInner {
                response_format: Some(serde_json::json!({"type": "text"})),
                ..Default::default()
            },
        };
        let agent = ModelSettings {
            model: "gpt-4.1-mini".into(),
            inner: ModelSettingsInner {
                response_format: Some(serde_json::json!({"type": "json_object"})),
                ..Default::default()
            },
        };

        let result = base.merge(&agent).unwrap();
        assert_eq!(
            result.inner.response_format,
            Some(serde_json::json!({"type": "json_object"}))
        );
    }

    #[test]
    fn merge_response_format_base_fallback() {
        let base = ModelSettings {
            model: "gpt-5.1".into(),
            inner: ModelSettingsInner {
                response_format: Some(serde_json::json!({"type": "text"})),
                ..Default::default()
            },
        };
        let agent = ModelSettings::new("gpt-4.1-mini");

        let result = base.merge(&agent).unwrap();
        assert_eq!(
            result.inner.response_format,
            Some(serde_json::json!({"type": "text"}))
        );
    }

    #[test]
    fn merge_parameters_agent_wins() {
        let base = ModelSettings {
            model: "gpt-5.1".into(),
            inner: ModelSettingsInner {
                parameters: Some(serde_json::json!({"key": "base"})),
                ..Default::default()
            },
        };
        let agent = ModelSettings {
            model: "gpt-4.1-mini".into(),
            inner: ModelSettingsInner {
                parameters: Some(serde_json::json!({"key": "agent"})),
                ..Default::default()
            },
        };

        let result = base.merge(&agent).unwrap();
        assert_eq!(
            result.inner.parameters,
            Some(serde_json::json!({"key": "agent"}))
        );
    }
}