1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
use std::collections::HashMap;
use std::path::PathBuf;
use crate::event::EventSink;
pub(crate) use supercode_runtime::glob_match;
pub use supercode_runtime::CachePlan;
/// The default OpenRouter base URL. Any OpenAI-compatible endpoint works too.
pub const OPENROUTER_BASE_URL: &str = "https://openrouter.ai/api/v1";
/// Environment variable consulted for the API key when none is set explicitly.
pub const DEFAULT_API_KEY_ENV: &str = "OPENROUTER_API_KEY";
/// Built-in prompt templates (slash commands), e.g. `/code-review`.
fn default_prompts() -> std::collections::HashMap<String, String> {
let mut m = std::collections::HashMap::new();
m.insert(
"code-review".to_string(),
"Review the current code changes for correctness bugs, then for \
reuse/simplification/efficiency cleanups. {args}\nUse the available tools to \
inspect the diff and files. Report findings grouped by severity."
.to_string(),
);
m
}
/// A default, deliberately small system prompt. Override it freely.
pub const DEFAULT_SYSTEM_PROMPT: &str = "\
You are supercode, a precise and efficient AI coding agent operating in a user's \
working directory. Use the available tools to inspect and modify files and run \
commands. Prefer reading before writing. Make minimal, correct changes and explain \
what you did concisely.";
/// When the agent must seek approval before running a tool — the analog of
/// Codex's `-a untrusted|on-request|never` and Claude's permission modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ApprovalPolicy {
/// Never ask — every tool call runs automatically (default).
#[default]
Never,
/// Ask for tools not on the auto-approve allowlist.
OnRequest,
/// Ask for every tool call.
Untrusted,
/// P5-1 (COMPOSABLE-HARNESS-DESIGN.md §3.2 S8, §4.3 cx-parity): Codex's
/// `-a on-request` default — escalation is INITIATED BY THE MODEL, not
/// decided by a client-side allowlist check the way [`Self::OnRequest`]
/// is (`Config::needs_approval`'s `OnRequest` arm consults
/// `Config::auto_approved_tools`/`tool_allow_patterns`; Codex's
/// `on-request` instead runs sandboxed writes/reads silently and only
/// asks when the MODEL itself requests to leave the sandbox —
/// `protocol.rs:921-924`). Using [`Self::OnRequest`] for cx-parity would
/// prompt on every non-allowlisted call, where stock Codex prompts
/// almost never — a materially different (over-prompting, but not
/// unsafe) posture, which is why `configfile::parse_approval_str`
/// previously fell back to [`Self::Untrusted`] rather than silently
/// picking the wrong existing variant (S8's original fail-safe). This
/// variant now exists so cx-parity resolves to its INTENDED posture
/// instead of that fail-safe. `Config::needs_approval` (the coarse,
/// tool-name-only legacy gate — no model-escalation signal reaches it)
/// treats this conservatively, the same as [`Self::OnRequest`]; the P5-1
/// permissions engine (`crate::permissions`, the richer canonicalized-
/// command-aware gate `crate::agent::Agent` consults when
/// `Config::permissions_enabled` is on) treats it per Codex's real
/// posture — see that gate's doc comment.
ModelRequested,
}
/// A callback consulted when a tool call needs approval. Returns `true` to allow.
pub type ApprovalHandler = Box<dyn Fn(&crate::message::ToolCall) -> bool + Send + Sync>;
/// A pre-tool hook: receives the tool name and parsed arguments before
/// execution. Return `Some(reason)` to BLOCK the call (the reason is fed back to
/// the model), or `None` to allow it.
pub type PreToolHook = Box<dyn Fn(&str, &serde_json::Value) -> Option<String> + Send + Sync>;
/// A post-tool hook: receives the tool name, its output, and whether it errored,
/// after execution (observational — logging, metrics, side effects).
pub type PostToolHook = Box<dyn Fn(&str, &str, bool) + Send + Sync>;
/// How tools are advertised to the model (B6, D16).
///
/// `Full` sends every enabled tool's schema on every request (today's
/// behavior). `Deferred` advertises only a `core` allowlist plus a synthetic
/// `tool_search` meta-tool; everything else — the MCP surface above all,
/// since `McpTool::from_client` eagerly wraps every remote tool with its full
/// `input_schema` — is discoverable via `tool_search` and only advertised
/// (on the *next* request) once activated.
#[derive(Debug, Clone, Default)]
pub enum ToolAdvertising {
/// All enabled tools every request (today's behavior).
#[default]
Full,
/// Only `core` tools + the `tool_search` meta-tool; everything else is
/// discoverable via `tool_search` and advertised only after activation.
Deferred {
/// Tool names advertised eagerly on every request.
core: Vec<String>,
},
}
/// Optional-policy gates resolved from `[capabilities.reduction]`.
///
/// `None` preserves [`crate::reduce::ReductionPolicy`]'s established
/// default for callers that use reduced mode without the composable module
/// surface. A preset or direct capability setting supplies only the gates it
/// names; the CLI applies them when it constructs the live policy.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ReductionPolicySettings {
pub stale_reads: Option<bool>,
pub diff_reads: Option<bool>,
pub duplicates: Option<bool>,
pub tool_input_elision: Option<bool>,
pub supersede: Option<bool>,
pub normalize_output: Option<bool>,
pub image_redaction: Option<bool>,
pub span_summaries: Option<bool>,
}
/// Per-tool customization: enable/disable a tool and/or override the description
/// the model sees for it.
#[derive(Debug, Clone, Default)]
pub struct ToolOverride {
/// If `Some(false)`, the tool is hidden from the model entirely.
pub enabled: Option<bool>,
/// If `Some`, replaces the tool's built-in description in the schema.
pub description: Option<String>,
/// If `Some`, overrides [`Config::tool_schema_tier`] (TR-8/T5) for this
/// specific tool — e.g. keep one fat MCP tool at `Full` while the global
/// knob shrinks everything else to `Minimal`.
pub schema_tier: Option<crate::tools::SchemaTier>,
/// P4e (design §3.1/§S14 `core.tools.bash.timeout_secs`): the DEFAULT
/// execution timeout (seconds) for the `bash` tool when a model-issued
/// call doesn't supply its own `timeout_ms` argument — see
/// `tools::builtins::BashTool::execute`'s precedence (an explicit
/// per-call `timeout_ms` always wins; this only replaces the BUILT-IN
/// `DEFAULT_BASH_TIMEOUT_MS` fallback). Only meaningful on the `bash`
/// entry; other tools ignore it. `None` (the default) is byte-identical
/// to today's behavior — `BashTool`'s internal 120s default stands.
pub timeout_secs: Option<u64>,
}
/// Everything that shapes an [`crate::Agent`]: the model and endpoint, the
/// credentials, sampling parameters, the system prompt, and per-tool overrides.
///
/// Build one with [`Config::builder`].
#[non_exhaustive]
pub struct Config {
/// Model identifier as understood by the endpoint, e.g.
/// `anthropic/claude-opus-4-8` or `openai/gpt-5` on OpenRouter.
pub model: String,
/// Base URL of the OpenAI-compatible endpoint (no trailing `/chat/...`).
pub base_url: String,
/// Explicit API key. If `None`, [`Self::api_key_env`] is consulted.
pub api_key: Option<String>,
/// Environment variable to read the API key from when [`Self::api_key`] is unset.
pub api_key_env: String,
/// P4 (COMPOSABLE-HARNESS-DESIGN.md §5.2 "P4", §1.8/§3.1
/// `core.api_key_cmd`, D6 row): a credential-helper command (pi§6
/// `!command` form). Consulted by `Agent::new` when [`Self::api_key`]
/// is unset: the command is run through the shell, its trimmed stdout
/// becomes the key, and a non-zero exit or empty output falls through to
/// [`Self::api_key_env`] rather than failing outright. `None` (the
/// default) means this is never consulted — byte-identical to today's
/// behavior. SECURITY: this is a command string, never a secret value —
/// [`Self::api_key`] itself must never be file-plaintext (§3.2 S13);
/// `api_key_cmd` is `[project-forbidden]` at every config-file layer
/// (§3.3), same trust boundary as `base_url`/`api_key_env`.
pub api_key_cmd: Option<String>,
/// System prompt prepended to every conversation.
pub system_prompt: String,
/// Optional sampling temperature.
pub temperature: Option<f32>,
/// Optional output token cap.
pub max_tokens: Option<u32>,
/// Maximum number of model/tool iterations per [`crate::Agent::send`] call.
pub max_iterations: usize,
/// Reasoning/effort level sent to the model (`reasoning_effort`).
pub effort: Option<String>,
/// Structured-output constraint (`response_format`), e.g. a json_schema.
pub response_format: Option<serde_json::Value>,
/// Extra request-body fields merged in (provider-native passthrough:
/// prompt-cache controls, provider-specific knobs).
pub extra_body: serde_json::Map<String, serde_json::Value>,
/// Optional cap on cumulative output tokens across one [`crate::Agent::send`]
/// loop; the loop stops once exceeded. Output tokens only; input/prompt
/// tokens are not counted, so this is not a cost cap.
pub max_total_output_tokens: Option<u64>,
/// Max bytes of a single tool result fed back into the conversation. Output
/// beyond this is truncated with a notice, so one runaway command (a huge
/// log, a binary dump) can't explode the context window. `None` disables the
/// cap. Defaults to 100 KB.
pub max_tool_output_bytes: Option<usize>,
/// Working directory tools operate within.
pub cwd: PathBuf,
/// Additional roots beyond `cwd` (the analog of `--add-dir` / multi-root):
/// searched for project-context files and available to tools.
pub additional_dirs: Vec<PathBuf>,
/// Whether to auto-load `CLAUDE.md` / `AGENTS.md` into the system prompt.
pub load_project_context: bool,
/// Filesystem confinement applied to write-capable tools.
pub sandbox: crate::tools::SandboxPolicy,
/// When the agent must seek approval before running a tool.
pub approval: ApprovalPolicy,
/// Tools that never require approval under [`ApprovalPolicy::OnRequest`].
pub auto_approved_tools: std::collections::HashSet<String>,
/// P4 (design §5.2 "P4": "deny-rule patterns generalizing
/// auto_approved_tools" — the S-sized generalization, NOT the full P5
/// `capabilities.permissions.rules` deny→ask→allow engine, §2.1
/// dependency 3's command-canonicalization prerequisite is P5-only).
/// Glob patterns (`*` wildcard, see [`glob_match`]) matched against a
/// tool's NAME — no argument/command-level matching. Any match forces
/// [`Config::needs_approval`] to `true` UNCONDITIONALLY, even under
/// [`ApprovalPolicy::Never`] — the entire point of a deny rule is a
/// hard floor `--yes`/`Never` can't bypass. Sourced from
/// `capabilities.permissions.rules.deny` (§3.1 module 11); empty by
/// default (today's behavior, byte-identical).
pub tool_deny_patterns: Vec<String>,
/// P4: the ALLOW-pattern generalization of [`Self::auto_approved_tools`]
/// — glob patterns matched against a tool's NAME, exempting a match from
/// approval under [`ApprovalPolicy::OnRequest`] exactly like an exact
/// `auto_approved_tools` entry does (never consulted under `Untrusted`,
/// same as `auto_approved_tools`). Sourced from
/// `capabilities.permissions.rules.allow`; empty by default.
pub tool_allow_patterns: Vec<String>,
/// Consulted when a tool call needs approval; `None` denies by default.
pub approval_handler: Option<ApprovalHandler>,
/// Runs before each tool executes; may block the call.
pub pre_tool_hook: Option<PreToolHook>,
/// Runs after each tool executes (observational).
pub post_tool_hook: Option<PostToolHook>,
/// Named prompt templates (skills / slash commands). A user message of the
/// form `/<name> <args>` is expanded to the template with `{args}` filled.
pub prompts: HashMap<String, String>,
/// If set, the conversation is compacted once it grows beyond this many
/// messages (older middle turns are summarized into one marker), keeping the
/// system prompt and the most recent turns.
pub compact_after_messages: Option<usize>,
/// Per-tool enable/disable + description overrides, keyed by tool name.
pub tool_overrides: HashMap<String, ToolOverride>,
/// How tools are advertised to the model (B6). Defaults to [`ToolAdvertising::Full`].
pub tool_advertising: ToolAdvertising,
/// Extra HTTP headers sent with every request (e.g. OpenRouter's
/// `HTTP-Referer` / `X-Title` attribution headers).
pub extra_headers: HashMap<String, String>,
/// Optional sink for streaming [`crate::AgentEvent`]s.
pub event_sink: Option<EventSink>,
/// Prompt-caching plan (B7). Defaults to [`CachePlan::Off`]; reduced mode
/// (`--reduced`, D5/D14) defaults it to [`CachePlan::ImportedPrefix`]
/// (wired at the CLI's reduced-mode assembly point, `crates/cli/src/main.rs`).
pub cache_plan: CachePlan,
/// Resolved optional reduction gates. These are kept separate from the
/// live policy because freshness probes and prepared summaries are
/// per-request data, not configuration.
pub reduction_policy: ReductionPolicySettings,
/// Whether the explicit reversible handoff projection is available.
/// This is separate from [`Self::reduction_policy`] because handoff is
/// an offline command over an existing sidecar, not a per-request
/// projection pass. Defaults to `true`; only an explicit composable
/// `capabilities.reduction.handoff = false` disables it.
pub handoff_enabled: bool,
/// Global tool-schema tier (TR-8/T5): how verbose ADVERTISED tool
/// schemas are. Defaults to [`crate::tools::SchemaTier::Full`] (today's
/// behavior — byte-identical schemas). A per-tool override in
/// [`ToolOverride::schema_tier`] wins over this for that tool. Tool
/// definitions are config, never session content, so this never affects
/// what's stored or exported — only what's advertised on the wire.
pub tool_schema_tier: crate::tools::SchemaTier,
/// UX-26 (B7-warn): whether [`crate::Agent`] emits
/// [`crate::AgentEvent::CacheWarning`] when a turn under
/// [`CachePlan::ImportedPrefix`] likely paid a full-price prompt-cache
/// miss despite reuse being expected (idle past the provider's TTL, or
/// usage reporting a near-zero cache-read ratio). Defaults to `true`
/// (on-brand token-economics feedback, on by default like the savings
/// figures `inspect stats` already surfaces); the CLI's
/// `--no-cache-warnings` flag / `cache_warnings = false` config / the
/// `SUPERCODE_CACHE_WARNINGS=0` env var turn it off. A no-op — never
/// checked — for any caller not using `CachePlan::ImportedPrefix`, so
/// this changes nothing under `CachePlan::Off` (today's default outside
/// reduced mode).
pub cache_warnings: bool,
/// P3 (COMPOSABLE-HARNESS-DESIGN.md §5.2 phase P3, mandatory risk-2
/// mitigation, §5.3 risk 2): the `[experimental] module_registry` flag.
/// `false` (the default) means [`crate::tools::ToolRegistry::from_config`]
/// returns EXACTLY [`crate::tools::ToolRegistry::with_builtins`] — the
/// runtime path is byte-for-byte today's behavior. Only when explicitly
/// turned on does [`Self::module_activation`] start shaping the
/// registry/prompt assembly.
pub module_registry: bool,
/// P3: the resolved §2 module-activation set (pure config → set,
/// computed by [`crate::configfile::resolve`]/[`crate::modules::ModuleActivation::from_harness`]
/// with no agent loop required). Only consulted when
/// [`Self::module_registry`] is `true`.
pub module_activation: crate::modules::ModuleActivation,
/// P3: the effective `[core.tools] enabled` list (§3.1) — which of the
/// core four (`read_file`/`bash`/`edit_file`/`write_file`, plus any
/// future core tool name) are present at all. Defaults to the §1.2
/// default-active four, matching [`crate::tools::ToolRegistry::with_builtins`]'s
/// unconditional registration. Only consulted when
/// [`Self::module_registry`] is `true`.
pub core_tools_enabled: Vec<String>,
/// P3: `[core.skills].enabled` (§1.4 obligation 4, D-7) — whether the
/// skills prompt section may appear at all. Still gated by D-7's read
/// pathway (`read_file` or `bash` present in [`Self::core_tools_enabled`])
/// at the assembly site. Only consulted when [`Self::module_registry`]
/// is `true`.
pub skills_enabled: bool,
/// P4 (COMPOSABLE-HARNESS-DESIGN.md §5.2 "P4", §3.1
/// `capabilities.model_catalog.small_model`, catalog §4a "Small/utility
/// model routing knob"): a cheaper/faster model id a caller (e.g. a
/// [`crate::reduce::summarize::SpanSummarizer`] implementation, or an
/// auto-title side-call) MAY use instead of [`Self::model`] for
/// low-stakes side-calls. `None` (the default) means every such
/// consumer falls back to the main model — the exact §2.1 D-9 fallback
/// behavior — since nothing in this crate resolves this field on its
/// own; it is a knob a caller reads, not a routing loop this crate runs.
pub small_model: Option<String>,
/// P4 (§3.1 `capabilities.model_catalog.fallback`, catalog §4a "Model
/// aliases + failure fallback chain"): an ordered list of full model
/// slugs a caller MAY retry against, in order, if [`Self::model`] fails.
/// Empty (the default) means no fallback chain is configured. Like
/// [`Self::small_model`], this is the resolved TABLE only — see
/// [`crate::model_catalog`]'s module doc for the scope boundary between
/// "a resolved list of slugs" (this field, S-sized) and an actual
/// retry/failover loop that consumes it (a separate, larger change).
pub model_fallback: Vec<String>,
/// P4b (COMPOSABLE-HARNESS-DESIGN.md design doc S5.2 "P4", S1.4/S3.1
/// `core.env_context`, catalog S4a "Environment context block
/// injection"): when `true`, `Agent::with_parts` appends a short
/// `# Environment` block (cwd, platform, date, best-effort git branch)
/// to the system prompt, alongside `Self::load_project_context`'s
/// instruction files. `false` (the default) is byte-identical to
/// today's behavior.
pub env_context: bool,
/// P4b (S1.4/S3.1 `core.project_root_markers`, catalog:232): filenames
/// that mark a directory as the project root for `Self::env_context`'s
/// git-status probe. Defaults to `[".git"]`.
pub project_root_markers: Vec<String>,
/// P4b (S1.4/S3.1 `core.project_doc_max_bytes`, cx2 "project_doc_max_bytes"
/// analog, S5.2 P4 "instruction-walk nuances"): a hygiene cap on the
/// TOTAL bytes of instruction-file content (`Self::load_project_context`'s
/// global + project tiers combined) appended to the system prompt. `None`
/// (the default) is uncapped -- byte-identical to today's behavior; only
/// an explicit `Some(n)` truncates the assembled block (with a trailing
/// notice), mirroring `Self::max_tool_output_bytes`'s cap-with-notice
/// shape.
pub project_doc_max_bytes: Option<usize>,
/// P4b (S1.4/S3.1 `core.instruction_imports`, catalog:85): when `true`,
/// an instruction file may reference another file via an `@relative/path`
/// token (CC's import syntax) -- the referenced file's contents are
/// inlined in its place, resolved relative to the IMPORTING file's own
/// directory, to a max depth of 4 (CC's own default) to bound cycles.
/// `false` (the default) leaves `@` tokens as plain literal text --
/// byte-identical to today's behavior.
pub instruction_imports: bool,
/// P4b (S1.1/S3.1 `core.retry`, pi3 shape): whether a transient
/// (connection failure / 5xx) provider error is retried at all. This
/// EXTENDS a pre-existing, always-on transport-layer mechanism
/// (`provider::OpenAiProvider`'s internal `HttpOptions` retry — 2
/// attempts / 500ms base backoff, hardcoded, not previously
/// config-file-settable) rather than adding a second one: `true` (the
/// default, matching today's always-on behavior byte-for-byte when
/// `Self::retry_max_retries`/`Self::retry_base_delay_ms` are also both
/// unset) keeps retrying; an explicit `false` is a NEW capability —
/// disabling the transport retry entirely.
pub retry_enabled: bool,
/// Override the transport retry's attempt count. `None` (the default)
/// keeps the pre-existing built-in default (2).
pub retry_max_retries: Option<u32>,
/// Override the transport retry's base backoff delay in milliseconds
/// (doubles per attempt). `None` (the default) keeps the pre-existing
/// built-in default (500ms).
pub retry_base_delay_ms: Option<u64>,
/// P4b (S1.5/S3.1 `core.compaction.reserve_tokens`, pi2 shape): once
/// set, `Agent::maybe_compact` ALSO triggers when the estimated token
/// size of the live history is within `reserve_tokens` of the model's
/// context window -- in addition to (not instead of)
/// `Self::compact_after_messages`'s message-count trigger. `None` (the
/// default) leaves the pressure trigger off -- byte-identical to today's
/// message-count-only behavior.
pub compaction_reserve_tokens: Option<u64>,
/// P4b (S1.5/S3.1 `core.compaction.keep_recent_tokens`): when the
/// PRESSURE trigger (not the message-count one) fires, how many of the
/// most recent tokens (estimated) to keep verbatim instead of a fixed
/// message count. Only consulted when `Self::compaction_reserve_tokens`
/// is `Some` and the pressure trigger is what fired.
pub compaction_keep_recent_tokens: Option<u64>,
/// P4b (S1.5/S3.1 `core.compaction.focus_instructions`, catalog D2 "no
/// instruction steering" gap): free text appended to the synthetic
/// compaction marker message every time compaction fires (either
/// trigger), steering the model on what to keep focusing on
/// post-compaction (CC's manual-compact `/compact <focus>` analog).
/// `None` (the default) leaves the marker text byte-identical to
/// today's.
pub compaction_focus_instructions: Option<String>,
/// P4b (S1.6/S3.1 `core.session.auto_title`, catalog:150, D-9): whether
/// `crate::session_title::auto_title` may be invoked at all by a caller
/// (the caller still supplies the `SessionTitler` side-call itself --
/// this is only the gate, mirroring `Self::small_model`'s "a knob a
/// caller reads" framing). `false` (the default): callers should treat
/// auto-title as off.
pub auto_title: bool,
/// P4b (S1.7/S3.1 `core.steering`, pi3 semantics): how queued mid-turn
/// steering messages (`Agent::queue_steer`) are drained -- `All`
/// delivers every queued message at once, `OneAtATime` (the default)
/// delivers one per drain point.
pub steering_mode: SteeringMode,
/// P4b (S1.7/S3.1 `core.steering.follow_up_mode`): how queued follow-up
/// messages (`Agent::queue_follow_up`) are drained once the loop is
/// otherwise idle (no more tool calls pending).
pub follow_up_mode: SteeringMode,
/// P4b (S1.9/S3.1 `[core] stop_gate`, D3 "stop/completion gating", CC
/// Stop-hook semantics cc3): consulted exactly once per `run_loop`
/// iteration that would otherwise return a final answer (no more tool
/// calls pending, and the follow-up queue is empty). Receives the
/// would-be-final assistant message; `Some(reason)` VETOES termination
/// -- `reason` is injected as a new user message and the loop continues
/// (still bounded by `Self::max_iterations`); `None` allows the stop.
/// Code-only, like `Self::pre_tool_hook`/`Self::post_tool_hook` --
/// the CLI's declarative `[hooks] stop = "cmd"` form (module 17)
/// populates this SAME single slot rather than adding a second call
/// site, so the two can never double-fire (S2 module 17's "hooks layer
/// on core's gate" note). `None` (the default) is byte-identical to
/// today's behavior.
pub stop_gate: Option<StopGateHook>,
/// P4c (COMPOSABLE-HARNESS-DESIGN.md S1.2/S3.1 `core.tools.read_file
/// multimodal`, catalog S4a "Multimodal read (image passthrough on
/// `read_file`)"): when `true`, `read_file` returns a recognized image
/// file (`.png`/`.jpg`/`.jpeg`/`.gif`/`.webp`/`.bmp`) as a model-visible
/// image content block instead of decoding it as (garbled) UTF-8 text.
/// `false` (the default) is byte-identical to today's behavior.
pub read_file_multimodal: bool,
/// P4c (S1.2/S3.1 `core.tools.edit_file.require_read_before_edit`,
/// UNIQUE CC row, catalog:32): when `true`, `edit_file` refuses unless
/// the target path was read (via `read_file`) earlier in this same
/// conversation -- tracked in `ToolContext`. `false` (the default) is
/// byte-identical to today's behavior.
pub edit_file_require_read_before_edit: bool,
/// P4c (S1.2/S3.1 `core.tools.edit_file.notebook_aware`, UNIQUE CC row
/// "NotebookEdit", catalog:40): when `true`, `edit_file` additionally
/// accepts Jupyter cell replace/insert/delete operations against a
/// `.ipynb` target (see `tools::builtins::EditFileTool`'s cell-op args)
/// instead of only the exact-string replace it always supports. `false`
/// (the default) is byte-identical to today's behavior.
pub edit_file_notebook_aware: bool,
/// P4c (S1.2/S3.1 `core.shell_env_snapshot`, SPLIT CC+CX row,
/// catalog:338): when `true`, `Agent::new`/`with_parts` captures the
/// user's interactive login-shell environment ONCE at construction
/// (`$SHELL -lc env`, best-effort) and every `bash` call inherits it
/// directly instead of needing to re-source shell rc files per call.
/// `false` (the default) is byte-identical to today's behavior -- no
/// snapshot is captured, and `bash` sees only the ambient process
/// environment, exactly as before this landed.
pub shell_env_snapshot: bool,
/// P4c (S5.2 P4 "doom-loop breaker", oc `doom_loop` UNIQUE row,
/// catalog D3): when `Some(n)` with `n >= 2`, a tool call whose name AND
/// arguments are byte-identical to the previous `n - 1` consecutive
/// calls is refused (fed back to the model as an error) instead of
/// executed -- the counter resets the moment a call differs. `None`
/// (the default) is byte-identical to today's behavior: no repetition
/// tracking, no call is ever refused on this basis.
pub doom_loop_threshold: Option<u32>,
/// P4c (S1.4/S3.1 `core.nested_instructions`, catalog:84, deferred from
/// P4b): when `true`, a `read_file`/`edit_file` call that touches a path
/// inside a subdirectory carrying its OWN `CLAUDE.md`/`AGENTS.md` (a
/// directory other than `Config.cwd` itself, which
/// `Self::load_project_context` already loads once at session start)
/// appends that subdirectory's instructions to the tool's OWN result the
/// FIRST time a path under it is touched this conversation (deduped
/// thereafter -- tracked in `ToolContext`, mirrors CC/OC's "auto-attach
/// on read, deduped" semantics, catalog:84). Reuses the same
/// canonicalize+containment safety check P4b's `@`-import expansion
/// uses (`agent::import_target_is_contained`) so a symlink cannot walk
/// the injection outside `Config.cwd`. `false` (the default) is
/// byte-identical to today's behavior.
pub nested_instructions: bool,
/// P4c (S1.10/S3.1 `core.model_switch.allow_switch`, D9 row, dep 8):
/// gates whether `Agent::switch_model` does more than the pre-existing
/// `Agent::set_model` mechanics (design's "UX-30 dev/02" -- swap
/// `Config.model` for the next request, nothing else touched). `false`
/// (the default) makes `switch_model` byte-identical to calling
/// `set_model` directly: no persisted `model_change` record, no
/// reasoning-artifact filtering. `true` additionally (1) appends a
/// typed `model_change::ModelChangeRecord` to
/// `Agent::model_change_records`, and (2) runs
/// `reduce::rehydrate::filter_reasoning_artifacts` over `Agent::history`
/// so model-A's reasoning/thinking artifacts (`ChatMessage::metadata`
/// keys and any `content_parts` reasoning blocks) never reach
/// model-B's context (S1.13, dep 8).
pub model_switch_allow_switch: bool,
/// P4e (§1.4/§3.1 `core.context_injections`, catalog:91 "Synthetic
/// context-injection blocks"): the master gate for
/// [`Self::context_injection_blocks`] -- when `false` (the default),
/// `Agent::with_parts` never appends any of them, byte-identical to
/// today's behavior. `true` splices in whatever named blocks are set,
/// at the same assembly site P4b's `env_context` block uses, right
/// after it.
pub context_injections: bool,
/// P4e: named ambient context blocks a caller/embedder populates
/// programmatically (mirrors `Self::prompts`/`Self::stop_gate`'s
/// code-extensible shape) -- there is no `[core.context_injections.*]`
/// FILE table because the §3.1 schema's `core.context_injections` key
/// is already a scalar boolean gate, and TOML forbids a key being both
/// scalar and table (the same S-fix documented on
/// `[core.model_switch]`). Consulted only when
/// [`Self::context_injections`] is `true`; empty (the default) is a
/// no-op even then. Each block is appended verbatim as `\n\n# {name}\n{content}`,
/// in list order.
pub context_injection_blocks: Vec<ContextInjectionBlock>,
/// P4e (§1.5/§3.1 `core.compaction.enabled`, "no master gate exists
/// yet"): the master on/off switch for ALL auto-compaction
/// (`Agent::maybe_compact`), composing with -- not replacing -- the
/// existing `Self::compact_after_messages`/`Self::compaction_reserve_tokens`/
/// `Self::compaction_keep_recent_tokens` triggers: `false` disables
/// every trigger unconditionally; `true` (the default, matching
/// today's behavior, where nothing has ever gated compaction) changes
/// nothing -- whichever triggers are configured still fire exactly as
/// before.
pub compaction_enabled: bool,
/// P4e (§3.1 `core.parallel_tool_calls`, catalog:59 "Independent
/// sibling calls run concurrently"): when `true` and an assistant turn
/// requests more than one tool call, `Agent::run_loop` runs their
/// `Tool::execute` futures CONCURRENTLY via `Self::run_tools_concurrently`
/// instead of one at a time -- see that method's doc comment for
/// exactly which part of dispatch stays strictly sequential (approval /
/// doom-loop / pre-tool-hook checks, and every `record`/`history`
/// append, which the lossless sidecar's append-order invariant, S1.13,
/// requires to stay deterministic). `false` (the default) is
/// byte-identical to today's sequential-await-per-call loop.
pub parallel_tool_calls: bool,
/// P4e (§1.6/§3.1 `core.session.git_metadata`, catalog:331 "Git branch/
/// sha captured … closes the loop" -- the WRITE half; supercode already
/// preserves a foreign session's own `gitBranch`-shaped fields
/// verbatim on IMPORT via `Session::raw`'s byte-for-byte capture).
/// When `true`, `Agent::with_parts` captures a
/// `git_metadata::GitMetadataRecord` (best-effort branch/sha/dirty,
/// like `Self::env_context`'s git probe) once at construction, readable
/// via `Agent::git_metadata` and persistable via
/// `Agent::save_git_metadata`. `false` (the default) is byte-identical
/// to today's behavior: no capture, `Agent::git_metadata()` is always
/// `None`.
pub session_git_metadata: bool,
/// P4e (§1.6/§3.1 `core.session.dir`): overrides the session store's
/// root directory. A caller-read knob (like `Self::small_model`) --
/// the CLI's `session_store()` (main.rs) is the consumer. `None` (the
/// default) leaves the CLI's own default (`$SUPERCODE_HOME/sessions`)
/// untouched.
pub session_dir: Option<String>,
/// P4e (§1.6/§3.1 `core.session.persist`, D5 row): whether a caller
/// should persist this session to the store at all. A caller-read gate
/// only -- `Agent`/`Config` never call `SessionStore` directly (no
/// `SessionStore` handle lives on `Config`); a caller checks this
/// field directly before calling `store.save(...)`, the same
/// "mechanism vs. gate" split `Self::auto_title` established. `true`
/// (the default) matches today's behavior: every caller that already
/// calls `store.save(...)` keeps doing so unconditionally.
pub session_persist: bool,
/// P4e (§1.6/§3.1 `core.session.name`): an explicit session name a
/// caller should use instead of auto-minting one (the CLI's
/// `mint_session_name`). A caller-read knob, same posture as
/// `Self::session_dir`. `None` (the default) leaves auto-naming
/// untouched.
pub session_name: Option<String>,
/// P4e (§1.6/§3.1 `core.session.retention_days`): the archive-pruning
/// window `store::SessionStore::prune_expired` consults. `None` (the
/// default) means "never prune" -- byte-identical to today's behavior
/// (nothing ever prunes automatically).
pub session_retention_days: Option<u32>,
/// P4e (§1.6/§3.1 `core.session.export_format`, catalog:283 "transcript
/// export for humans"): `text` | `html`, consumed by
/// `human_export::render_transcript`. Defaults to
/// [`crate::human_export::HumanExportFormat::Text`].
pub session_export_format: crate::human_export::HumanExportFormat,
/// P5-1 (§3.1 `capabilities.permissions.enabled`, module 10/11
/// activation): the master gate for `crate::permissions` — when `false`
/// (the default), `Agent::prepare_tool_call`'s tool-dispatch gate uses
/// EXACTLY the pre-P5-1 [`Self::needs_approval`] path, byte-for-byte —
/// no behavior change. `true` switches the gate to the richer
/// canonicalized-command-aware [`crate::permissions::rules`] engine
/// (deny→ask→allow first-match, C5), consulting
/// [`Self::permissions_ask_patterns`] (together with the pre-existing
/// [`Self::tool_deny_patterns`]/[`Self::tool_allow_patterns`] as the
/// engine's deny/allow tiers) and [`Self::permissions_protected_paths`].
pub permissions_enabled: bool,
/// P5-1 (§3.1 `capabilities.permissions.rules.ask`, module 11): the
/// engine's `ask` tier — the sibling of the pre-existing
/// [`Self::tool_deny_patterns`]/[`Self::tool_allow_patterns`] (P4),
/// which become the engine's `deny`/`allow` tiers respectively when
/// [`Self::permissions_enabled`] is on (see
/// `crate::permissions::rules::RuleSet`). Empty by default. Only
/// consulted when [`Self::permissions_enabled`] is `true`.
pub permissions_ask_patterns: Vec<String>,
/// P5-1 (§3.1 `capabilities.permissions.protected_paths.paths`, module
/// 13): glob patterns that are an unconditional DENY floor for both
/// read and write access (cc§4 "never auto-approved… `.git/**`,
/// `.env*`, …"), expanded via
/// [`crate::permissions::rules::protected_path_deny_rules`] into the
/// engine's `deny` tier. Empty by default. Only consulted when
/// [`Self::permissions_enabled`] is `true`.
///
/// **Honesty note on coverage (F4, Fable-5 adversarial review):** at
/// the rule-engine layer this floor is enforced for (a) `read_file`/
/// `write_file`/`edit_file`-shaped path calls, (b) a `bash`/`shell`
/// command's direct output/input redirect targets (`>`, `>>`, `&>`,
/// `>|`, `&>>`, `<`), (c) `apply_patch`'s target path(s), and (d) a
/// best-effort set of known argv-writers (`tee`, `dd of=`, `cp`/`mv`/
/// `install`, `sed -i`, `truncate`, `ln`) — see
/// `crate::permissions::canon::known_writer_targets`'s doc comment for
/// that heuristic's named gaps. A write this rule layer genuinely
/// cannot statically resolve (an opaque wrapper — `eval`, `sh -c`, …
/// — or a dynamic `$VAR`/`` `cmd` `` target) is forced to at least
/// `Ask`, never silently `Allow`. What this layer does NOT provide is
/// COMPLETE OS-level write confinement of arbitrary bash — that is
/// `capabilities.permissions.sandbox`'s job (P5 module 10, a later
/// unit), not this one's.
pub permissions_protected_paths: Vec<String>,
/// P5-1 (§3.1 `capabilities.permissions.sandbox.network.*`, module 12
/// carry-forward): the domain allow/deny policy `crate::tools::WebFetchTool`/
/// `WebSearchTool` enforce via `crate::tools::ToolContext::check_network`
/// — the enforcement POINT already existed (P4c); this is its real
/// config source (`crate::configfile::materialize_config`). `None` (the
/// default) is byte-identical to today's behavior: no policy is
/// enforced, exactly the honest gap `NetworkPolicy`'s own doc comment
/// (`crate::tools`) already names.
pub network_policy: Option<crate::tools::NetworkPolicy>,
/// P5-10 (§3.1 `capabilities.permissions.sandbox.enabled`, module 12):
/// whether the OS-level backstop (Landlock on Linux, seatbelt on
/// macOS) is engaged for the `bash`/`shell` subprocess. `None` (the
/// default — unset by the bare `sandbox = "<tier>"` shorthand, or a
/// CLI `--sandbox` flag, neither of which touch this table key) keeps
/// the PRE-P5-10 trigger byte-identical: `crate::sandbox::
/// os_sandbox_active` falls back to "confine whenever the tier isn't
/// `DangerFullAccess`", exactly what the macOS seatbelt path already
/// did off `Self::sandbox` alone. `Some(false)` (the table form's
/// explicit opt-out — `cc-parity`'s posture) turns the OS backstop off
/// even for a confining tier; `Some(true)` forces it on.
pub sandbox_os_enabled: Option<bool>,
/// P5-10 (§3.1 `capabilities.permissions.sandbox.escalation`, module
/// 12): what happens when a confining fs tier is requested but this
/// platform/kernel can't enforce it — see
/// [`crate::sandbox::SandboxEscalation`]. Defaults to `Deny`
/// (fail-closed), matching `capabilities.permissions.sandbox`'s own
/// `escalation = "deny"` config default.
pub sandbox_escalation: crate::sandbox::SandboxEscalation,
/// P5-10 (§3.1 `capabilities.permissions.sandbox.env_policy`, module
/// 12): child-process environment sanitization for the spawned
/// `bash`/`shell` subprocess — see
/// [`crate::sandbox::SandboxEnvPolicy`]. Defaults to `Inherit`
/// (byte-identical to pre-P5-10 behavior: the full environment passes
/// through unchanged).
pub sandbox_env_policy: crate::sandbox::SandboxEnvPolicy,
/// P5-3 (§3.1 `capabilities.subagents.enabled`, module 9 activation):
/// the master gate for the `spawn_subagent`/`subagent_status` agent
/// the master gate for the `spawn_subagent`/`subagent_status` agent
/// intrinsics — when `false` (the default), `Agent::tool_schemas` never
/// advertises them and `Agent::run_tool`'s interception is a pure
/// pass-through to the pre-P5-3 dispatch, byte-for-byte unchanged.
pub subagents_enabled: bool,
/// P5-3 (§3.1 `capabilities.subagents.max_depth`, resource bound): the
/// maximum spawn-tree depth — a depth-`max_depth` agent may not spawn
/// (its child would land at `max_depth + 1`). Only consulted when
/// [`Self::subagents_enabled`] is `true`.
pub subagents_max_depth: usize,
/// P5-3 (resource bound, NOT in the §3.1 illustrative schema snippet —
/// added per the build brief's explicit "max concurrent subagents…
/// cap, fail-closed... configurable"): the maximum number of subagents
/// in flight anywhere in one spawn tree at once (root-to-leaf, shared
/// via [`crate::agent::Agent`]'s concurrency gauge). Only consulted
/// when [`Self::subagents_enabled`] is `true`.
pub subagents_max_concurrent: usize,
/// P5-3 (§3.1 `capabilities.subagents.background`): whether
/// `spawn_subagent`'s `background: true` argument is honored at all —
/// `false` (the default) refuses every background spawn regardless of
/// [`Self::subagents_background_prompts`].
pub subagents_background: bool,
/// P5-3 (§2.2 C6, §3.1 `capabilities.subagents.background_prompts`):
/// the auto-policy a background child's tool approvals route through.
/// `None` (the default) means a background spawn is refused
/// (`Error::SubagentBackgroundPolicyMissing`) — a detached child must
/// never reach an interactive prompt it can't answer.
pub subagents_background_prompts: Option<crate::subagents::BackgroundPromptsPolicy>,
/// Claude Code emulation: advertise and accept its `Agent` tool name and
/// argument vocabulary in addition to Supercode's native
/// `spawn_subagent` intrinsic. Default `false`; enabled only for an
/// explicitly imported Claude continuation.
pub subagents_claude_agent_alias: bool,
/// Claude Code resume compatibility for the scheduler-shaped
/// `CronCreate`/`CronDelete`/`CronList`/`ScheduleWakeup` intrinsics.
/// The imported manifest is always paused and these tools only mutate
/// that inert state; no timer is started. Default `false` so ordinary
/// agents do not gain a harness-specific tool surface.
pub claude_runtime_tools_enabled: bool,
/// P5-3 (§3.1 `capabilities.subagents.agents.<name>`, D3 "named-defs"):
/// named subagent types, keyed by the name the model passes as
/// `spawn_subagent`'s `agent_type` argument.
pub subagents_definitions: HashMap<String, crate::subagents::NamedAgentDefinition>,
/// P5-3 (runtime-only, NEVER set from a config file — only
/// `Agent::run_spawn_subagent` sets it on a freshly-built CHILD
/// `Config` before constructing that child): how deep in the spawn
/// tree the agent built from this `Config` is. `0` is a top-level
/// agent; a config file / [`ConfigBuilder`] caller that never spawns
/// leaves this at its `0` default.
pub subagent_depth: usize,
/// P5-4 (§3.1 `capabilities.tui.enabled`, module 30 activation, §1.9
/// recorded deviation): the master gate for the full-screen TUI —
/// when `false` (the default), `crates/cli`'s `chat()` runs the
/// pre-P5-4 rustyline REPL loop byte-for-byte, and every P5-4 seam
/// below (`Agent::set_permissions_approval_handler`/
/// `Agent::set_child_approval_handler_factory`/
/// `crate::mcp::McpClient::set_elicitation_handler`) is simply never
/// invoked with a TUI-backed implementation. `crates/cli`'s TUI runner
/// additionally requires stdin/stdout/stderr all be a real tty before
/// activating even when this is `true` — see that crate's
/// `tui::should_activate` doc comment.
pub tui_enabled: bool,
/// P5-4 (§3.1 `capabilities.tui.theme`): `"dark"` | `"light"` — which
/// built-in [`crate::tui::Theme`] the renderer starts with. Unknown or
/// unset values fall back to `"dark"` (`crate::tui::Theme::default()`).
pub tui_theme: String,
/// P5-4 (§3.1 `capabilities.tui.vim_mode`, D8 "vim"): whether the
/// input buffer starts in vim-style modal editing (normal/insert)
/// rather than plain single-mode editing. See
/// `crate::tui::InputMode`'s doc comment for the (deliberately
/// basic — hjkl/i/a/o/dd/x) scope of what's implemented.
pub tui_vim_mode: bool,
/// P5-4 (§3.1 `capabilities.tui.keymap.<action> = "<key>"`,
/// "configurable keybindings"): per-action key overrides layered on
/// top of [`crate::tui::Keymap::default()`] — see that type's doc
/// comment for the action names and key-spec syntax understood.
pub tui_keymap: HashMap<String, String>,
/// P5-5 (§3.1 `capabilities.session_tree.enabled`, design §2 module 21
/// activation): the master gate for the native in-place session tree
/// (`crate::session_tree`) — a pure "does the harness advertise/prefer
/// tree-mode session semantics" signal for a caller (CLI/TUI) to consult.
/// `false` (the default, matching every `HarnessConfig` that never sets
/// this table) changes nothing about [`crate::session_tree::SessionTree`]
/// itself, which has no runtime dependency on this flag (a caller can
/// always construct/use one directly, exactly like
/// [`crate::store::SessionStore::fork`] isn't gated on any capability
/// either) — this field exists purely so a future integration point has
/// a resolved config signal to read, matching every other P5 module's
/// "carried on `Config`, pure config → set" convention.
pub session_tree_enabled: bool,
/// P5-5 (§3.1 `capabilities.session_tree.branch_summaries`, module 21
/// "branch summaries"): whether a caller wiring
/// [`crate::session_tree::SessionTree::splice_for_linear_export`] into a
/// C7 linear-export path should generate/attach summaries for off-path
/// branches at all, vs. leaving them unsummarized (still fully present
/// in the sidecar either way — this only controls the human-readable
/// digest, never the underlying lossless data). Defaults `true` (the
/// §3.1 schema's own default) when [`Self::session_tree_enabled`] is
/// `true` and this key is unset.
pub session_tree_branch_summaries: bool,
/// P5-5 (§3.1 `capabilities.session_tree.labels`, module 21 "entry
/// labels"): whether a caller's UI/CLI surface should expose
/// [`crate::session_tree::SessionTree::label`]/`clear_label` at all.
/// Defaults `true` (the §3.1 schema's own default) when
/// [`Self::session_tree_enabled`] is `true` and this key is unset. Like
/// [`Self::session_tree_branch_summaries`], this is advisory — the
/// underlying `SessionTree` API always supports labeling regardless.
pub session_tree_labels: bool,
/// P5-6 (§3.1 `capabilities.tools_background.enabled`, module 4
/// activation): the master gate for the `background_exec`/
/// `background_status`/`background_list`/`background_kill` agent
/// intrinsics — when `false` (the default), `Agent::tool_schemas`
/// never advertises them and `Agent::prepare_tool_call`'s interception
/// is a pure pass-through to the pre-P5-6 dispatch, byte-for-byte
/// unchanged (a hallucinated call falls through to the ordinary
/// unknown-tool error, exactly like `spawn_subagent`'s own disabled
/// posture).
pub tools_background_enabled: bool,
/// P5-6 (resource bound, NOT in the §3.1 illustrative schema snippet —
/// added per the build brief's explicit "max-concurrent cap,
/// fail-closed", mirroring [`Self::subagents_max_concurrent`]'s own
/// precedent): the maximum number of background jobs this agent may
/// have running at once. Only consulted when
/// [`Self::tools_background_enabled`] is `true`.
pub tools_background_max_concurrent: usize,
/// P5-6 (resource bound, "must not OOM" — mirrors
/// `crate::mcp::MCP_MAX_RESPONSE_BYTES`'s hardening-cap precedent): the
/// maximum number of bytes of combined stdout/stderr retained per
/// background job — output beyond this is truncated-with-marker, never
/// buffered further (`crate::background::CapturedOutput::append`).
/// Only consulted when [`Self::tools_background_enabled`] is `true`.
pub tools_background_max_output_bytes: usize,
/// P5-9 (§3.1 `capabilities.checkpoint.enabled`, module 20 activation):
/// the master gate for file checkpointing — when `false` (the
/// default), `crate::agent::build_tool_context` never touches disk for
/// this at all: no `crate::checkpoint::CheckpointStore` is opened, no
/// shadow directory is created, `ToolContext::write_observer` stays
/// `None`, and every write-tool call site's observer branch is a
/// pure no-op — byte-identical to before this module existed. See
/// `crate::checkpoint`'s module doc comment for the full design.
pub checkpoint_enabled: bool,
/// P5-9 (bounded-disk requirement, NOT in the §3.1 illustrative schema
/// snippet — added per the build brief's explicit "bounded... no
/// unbounded disk growth", mirroring [`Self::tools_background_max_concurrent`]'s
/// own precedent): the maximum number of checkpoints retained per
/// project before the oldest are pruned. Only consulted when
/// [`Self::checkpoint_enabled`] is `true`.
pub checkpoint_retain: usize,
/// P5-9 (embedder/test override, NOT a `[capabilities.checkpoint]`
/// schema key — this is a Rust-only knob, the same class as
/// [`Self::pre_tool_hook`]/[`Self::post_tool_hook`]): where the shadow
/// store lives. `None` (the default) means
/// `crate::checkpoint::observer_for_config` derives the location from
/// `crate::agent::global_instructions_dir()` + a hash of [`Self::cwd`]
/// (mirroring the CLI's own `cwd_tag` precedent) — set this to make the
/// location hermetic/deterministic (tests; embedders that want a
/// specific on-disk layout) without touching process-global env vars.
pub checkpoint_dir: Option<PathBuf>,
/// P5-11 (§3.1 `capabilities.lsp.enabled`, module 28 activation): the
/// master gate for LSP server lifecycle + edit-path diagnostics (D1).
/// `false` (the default) means `crate::agent::build_tool_context` never
/// touches `crate::lsp::manager_for_config` at all — no child process
/// is ever spawned, `ToolContext::write_observer`'s chain never gains
/// an LSP entry — byte-identical to before this module existed. See
/// `crate::lsp`'s module doc comment for the accepted gaps (no
/// auto-provisioned server fleet, no symbol-indexing query tool).
pub lsp_enabled: bool,
/// P5-11 (`capabilities.lsp.servers.<name>`): the configured language
/// servers, in alphabetical order by server name (a TOML table has no
/// inherent ordering — `configfile::materialize_config` sorts
/// explicitly for reproducibility) — first extension match wins. Only
/// consulted when [`Self::lsp_enabled`] is `true`. An empty `Vec` with
/// `lsp_enabled = true` is legal but warns once
/// (`crate::lsp::manager_for_config`) — very likely a config mistake.
pub lsp_servers: Vec<(String, crate::lsp::LspServerSpec)>,
/// P5-11 (bounded-context requirement, NOT in the §3.1 illustrative
/// schema snippet — added per the build brief's explicit "a flood
/// mustn't blow context", mirroring [`Self::tools_background_max_output_bytes`]'s
/// own precedent): the maximum number of diagnostics rendered into a
/// single tool result. Only consulted when [`Self::lsp_enabled`] is
/// `true`.
pub lsp_max_diagnostics: usize,
/// P5-11 (bounded-latency requirement): how long to wait for a
/// configured server to publish diagnostics after a
/// `didOpen`/`didChange` before giving up gracefully. Only consulted
/// when [`Self::lsp_enabled`] is `true`.
pub lsp_timeout_secs: u64,
/// P5-11 (§3.1 `capabilities.formatters.enabled`, module 29
/// activation): the master gate for format-on-write. `false` (the
/// default) means the shared D-5 write-observer chain never gains a
/// `crate::formatters::FormatObserver` entry — byte-identical to
/// before this module existed.
pub formatters_enabled: bool,
/// P5-11 (`capabilities.formatters.<name>`): the configured formatter
/// commands, in alphabetical order by formatter name (same "TOML has
/// no inherent ordering" rationale as [`Self::lsp_servers`]) — first
/// extension match wins. Only consulted when
/// [`Self::formatters_enabled`] is `true`.
pub formatters: Vec<(String, crate::formatters::FormatterSpec)>,
/// P5-11 (§3.1 `capabilities.formatters.diff_back`, C10): whether a
/// formatter's rewrite is diffed back into the calling tool's result
/// so the model's file-memory stays truthful (design line 534, "must
/// diff-back into the result"). `true` is the C10-SAFE default; `false`
/// still runs the formatter but withholds the annotation — legal, but
/// the model then has a stale belief about the file's exact bytes
/// until it re-reads it.
pub formatters_diff_back: bool,
/// P5-11 (bounded-latency requirement, "a hanging formatter can't hang
/// the loop — timeout + kill like hooks"): how long a single formatter
/// invocation may run before it's treated as failed (the file is left
/// untouched). Only consulted when [`Self::formatters_enabled`] is
/// `true`.
pub formatters_timeout_secs: u64,
/// P5-12 (§2 module 14 `trust`, D-10): the master gate for the
/// project/workspace trust concept — `false` (the default) means
/// [`Self::trust_default`] is never consulted and [`crate::plugins`]
/// treats every plugin as untrusted (see
/// [`crate::plugins::is_trusted`]'s doc comment). `[capabilities.trust]`
/// is project-forbidden (`configfile::PROJECT_FORBIDDEN_CAPABILITY_TABLES`
/// / `userconfig`'s own copy): only the user/global layer — or a
/// preset extended from it — may ever set this, exactly like
/// `hooks`/`plugins`/`server` (a project asserting its OWN trust would
/// defeat the entire point of the gate).
pub trust_enabled: bool,
/// P5-12 (`capabilities.trust.default`): the workspace-trust decision —
/// see [`crate::plugins::TrustDecision`]'s doc comment for why, absent a
/// wired interactive upgrade flow, only [`crate::plugins::TrustDecision::Always`]
/// actually unlocks plugin loading in this build (an honest,
/// documented gap — not a silent no-op: `ask`/`never` both cleanly
/// refuse, they don't pretend to prompt). Only consulted when
/// [`Self::trust_enabled`] is `true`.
pub trust_default: crate::plugins::TrustDecision,
/// P5-12 (§2 module 18 `plugins`, §3.1 `capabilities.plugins.enabled`):
/// the master gate for out-of-process, manifest-declared plugins (see
/// [`crate::plugins`]'s module doc comment for the ABI). `false` (the
/// default) means `crate::agent`'s tool-registration path never touches
/// [`crate::plugins::discover_and_load`] at all — no directory read, no
/// manifest parse, no subprocess — byte-identical to before this module
/// existed.
pub plugins_enabled: bool,
/// P5-12 (`capabilities.plugins.dirs`): EXTRA directories to scan for
/// `<plugin-name>/plugin.toml` manifests, on top of the always-scanned
/// `$SUPERCODE_HOME/plugins` (see [`crate::plugins::discover_manifests`]).
/// `[capabilities.plugins]` (this field included) is project-forbidden,
/// so this can only ever come from the trusted user/global layer or a
/// preset. Only consulted when [`Self::plugins_enabled`] is `true` AND
/// the workspace is trusted (see [`crate::plugins::is_trusted`]).
pub plugins_dirs: Vec<PathBuf>,
}
/// P4e (§1.4/§3.1 `core.context_injections`): one named ambient context
/// block -- see [`Config::context_injection_blocks`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContextInjectionBlock {
/// The block's heading, rendered as `# {name}`.
pub name: String,
/// The block's body text, appended verbatim under the heading.
pub content: String,
}
impl ContextInjectionBlock {
/// Build a named block.
pub fn new(name: impl Into<String>, content: impl Into<String>) -> Self {
ContextInjectionBlock {
name: name.into(),
content: content.into(),
}
}
}
/// How queued steering/follow-up messages are drained (S1.7, pi3
/// `steeringMode`/`followUpMode`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SteeringMode {
/// Deliver every queued message at once.
All,
/// Deliver exactly one queued message per drain point (the default).
#[default]
OneAtATime,
}
impl SteeringMode {
/// Parse the `"all"` / `"one-at-a-time"` config strings (S3.1).
pub fn parse(s: &str) -> Option<SteeringMode> {
match s {
"all" => Some(SteeringMode::All),
"one-at-a-time" | "one_at_a_time" => Some(SteeringMode::OneAtATime),
_ => None,
}
}
}
/// A stop-gate hook: receives the would-be-final assistant message; returns
/// `Some(reason)` to veto termination and continue the loop (the reason is
/// injected as a new user message), or `None` to allow the stop. See
/// `Config::stop_gate`.
pub type StopGateHook = Box<dyn Fn(&str) -> Option<String> + Send + Sync>;
impl Default for Config {
fn default() -> Self {
Config {
model: "anthropic/claude-opus-4-8".to_string(),
base_url: OPENROUTER_BASE_URL.to_string(),
api_key: None,
api_key_env: DEFAULT_API_KEY_ENV.to_string(),
api_key_cmd: None,
system_prompt: DEFAULT_SYSTEM_PROMPT.to_string(),
temperature: None,
max_tokens: None,
max_iterations: 25,
effort: None,
response_format: None,
extra_body: serde_json::Map::new(),
max_total_output_tokens: None,
max_tool_output_bytes: Some(100_000),
cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
additional_dirs: Vec::new(),
load_project_context: false,
sandbox: crate::tools::SandboxPolicy::default(),
approval: ApprovalPolicy::default(),
auto_approved_tools: std::collections::HashSet::new(),
tool_deny_patterns: Vec::new(),
tool_allow_patterns: Vec::new(),
approval_handler: None,
pre_tool_hook: None,
post_tool_hook: None,
prompts: default_prompts(),
compact_after_messages: None,
tool_overrides: HashMap::new(),
tool_advertising: ToolAdvertising::default(),
extra_headers: HashMap::new(),
event_sink: None,
cache_plan: CachePlan::default(),
reduction_policy: ReductionPolicySettings::default(),
handoff_enabled: true,
tool_schema_tier: crate::tools::SchemaTier::default(),
cache_warnings: true,
module_registry: false,
module_activation: crate::modules::ModuleActivation::default(),
core_tools_enabled: ["read_file", "bash", "edit_file", "write_file"]
.iter()
.map(|s| s.to_string())
.collect(),
skills_enabled: false,
small_model: None,
model_fallback: Vec::new(),
env_context: false,
project_root_markers: vec![".git".to_string()],
project_doc_max_bytes: None,
instruction_imports: false,
retry_enabled: true,
retry_max_retries: None,
retry_base_delay_ms: None,
compaction_reserve_tokens: None,
compaction_keep_recent_tokens: None,
compaction_focus_instructions: None,
auto_title: false,
steering_mode: SteeringMode::default(),
follow_up_mode: SteeringMode::default(),
stop_gate: None,
read_file_multimodal: false,
edit_file_require_read_before_edit: false,
edit_file_notebook_aware: false,
shell_env_snapshot: false,
doom_loop_threshold: None,
nested_instructions: false,
model_switch_allow_switch: false,
context_injections: false,
context_injection_blocks: Vec::new(),
// P4e: `true` because today's behavior (before this master gate
// existed) is "compaction fires whenever a trigger is
// configured" -- a default of `true` preserves that exactly;
// only an explicit `false` newly suppresses it.
compaction_enabled: true,
parallel_tool_calls: false,
session_git_metadata: false,
session_dir: None,
session_persist: true,
session_name: None,
session_retention_days: None,
session_export_format: crate::human_export::HumanExportFormat::default(),
permissions_enabled: false,
permissions_ask_patterns: Vec::new(),
permissions_protected_paths: Vec::new(),
network_policy: None,
sandbox_os_enabled: None,
sandbox_escalation: crate::sandbox::SandboxEscalation::default(),
sandbox_env_policy: crate::sandbox::SandboxEnvPolicy::default(),
subagents_enabled: false,
subagents_max_depth: 2,
subagents_max_concurrent: 4,
subagents_background: false,
subagents_background_prompts: None,
subagents_claude_agent_alias: false,
claude_runtime_tools_enabled: false,
subagents_definitions: HashMap::new(),
subagent_depth: 0,
tui_enabled: false,
tui_theme: "dark".to_string(),
tui_vim_mode: false,
tui_keymap: HashMap::new(),
session_tree_enabled: false,
session_tree_branch_summaries: false,
session_tree_labels: false,
tools_background_enabled: false,
tools_background_max_concurrent: crate::background::DEFAULT_MAX_CONCURRENT,
tools_background_max_output_bytes: crate::background::DEFAULT_MAX_OUTPUT_BYTES,
checkpoint_enabled: false,
checkpoint_retain: crate::checkpoint::DEFAULT_RETAIN,
checkpoint_dir: None,
lsp_enabled: false,
lsp_servers: Vec::new(),
lsp_max_diagnostics: crate::lsp::DEFAULT_LSP_MAX_DIAGNOSTICS,
lsp_timeout_secs: crate::lsp::DEFAULT_LSP_TIMEOUT_SECS,
formatters_enabled: false,
formatters: Vec::new(),
formatters_diff_back: true,
formatters_timeout_secs: crate::formatters::DEFAULT_FORMATTER_TIMEOUT_SECS,
trust_enabled: false,
trust_default: crate::plugins::TrustDecision::Ask,
plugins_enabled: false,
plugins_dirs: Vec::new(),
}
}
}
impl Config {
/// Start building a [`Config`] from defaults.
pub fn builder() -> ConfigBuilder {
ConfigBuilder {
config: Config::default(),
}
}
/// Whether a tool is enabled given the overrides (defaults to enabled).
pub fn tool_enabled(&self, name: &str) -> bool {
self.tool_overrides
.get(name)
.and_then(|o| o.enabled)
.unwrap_or(true)
}
/// Whether a tool call requires approval before it runs, given the
/// policy, the auto-approve allowlist, and (P4) the deny/allow glob
/// PATTERN lists — see [`Self::tool_deny_patterns`]/
/// [`Self::tool_allow_patterns`]'s doc comments for the exact
/// semantics. Both are empty by default, so this is byte-identical to
/// pre-P4 behavior for any `Config` that doesn't set them.
pub fn needs_approval(&self, tool: &str) -> bool {
// Deny wins unconditionally, even under `Never` — a deny pattern is
// a hard floor, not just another allowlist entry.
if self.tool_deny_patterns.iter().any(|p| glob_match(p, tool)) {
return true;
}
match self.approval {
ApprovalPolicy::Never => false,
// P5-1: this coarse, tool-name-only gate has no model-escalation
// signal to consult (that requires the canonicalized-command
// context only `crate::permissions`'s richer gate has), so
// `ModelRequested` is treated the same, conservative way
// `OnRequest` is here — the safe simplification documented on
// `ApprovalPolicy::ModelRequested` itself. The P5-1 engine
// (active when `Self::permissions_enabled` is `true`) is where
// Codex's real "mostly silent, escalation asks" posture is
// approximated instead.
ApprovalPolicy::OnRequest | ApprovalPolicy::ModelRequested => {
!self.auto_approved_tools.contains(tool)
&& !self.tool_allow_patterns.iter().any(|p| glob_match(p, tool))
}
ApprovalPolicy::Untrusted => true,
}
}
/// The effective description for a tool, applying any override.
pub fn tool_description<'a>(&'a self, name: &str, builtin: &'a str) -> &'a str {
self.tool_overrides
.get(name)
.and_then(|o| o.description.as_deref())
.unwrap_or(builtin)
}
/// The effective schema tier for a tool (TR-8/T5): a per-tool override if
/// set, else the global [`Self::tool_schema_tier`].
pub fn schema_tier_for(&self, name: &str) -> crate::tools::SchemaTier {
self.tool_overrides
.get(name)
.and_then(|o| o.schema_tier)
.unwrap_or(self.tool_schema_tier)
}
}
/// A single tool's file-settable overrides — the `ConfigProfile` mirror of
/// [`ToolOverride`] (COMPOSABLE-HARNESS-DESIGN.md §3.1 `[core.tools.<name>]`,
/// §3.2 mapping row `core.tools.enabled` + `[core.tools.<n>].*`).
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct ToolOverrideProfile {
/// `Some(false)` hides the tool from the model entirely.
pub enabled: Option<bool>,
/// Replaces the tool's built-in description.
pub description: Option<String>,
/// Per-tool schema tier: `full` | `medium` | `minimal`.
pub schema_tier: Option<String>,
/// P4e (§3.1 `core.tools.bash.timeout_secs`, S14) -- see
/// `ToolOverride::timeout_secs`. Only meaningful on the `bash` entry.
pub timeout_secs: Option<u64>,
}
/// The serializable subset of a [`Config`] that can live in a config file.
/// (Callbacks/handlers are code-only and are not represented here.)
///
/// Grown from its original 9 fields to the P1 §3.2 surface
/// (COMPOSABLE-HARNESS-DESIGN.md §5.2 "P1" migration step): every `[core]`
/// scalar/table/array `Config` maps to lives here so it becomes file-settable
/// for the first time, per the design's stated framing gap (§3.0).
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct ConfigProfile {
/// Model id.
pub model: Option<String>,
/// Endpoint base URL.
pub base_url: Option<String>,
/// Environment variable to read the API key from (§3.1 `core.api_key_env`;
/// §3.2: "today absent from BOTH files").
pub api_key_env: Option<String>,
/// Credential-helper command (§3.1 `core.api_key_cmd`, D6 row) — see
/// [`Config::api_key_cmd`].
pub api_key_cmd: Option<String>,
/// System prompt.
pub system_prompt: Option<String>,
/// P4 (§3.1 `core.append_system_prompt`, D2 row 1): an additive suffix
/// composed onto whatever [`Self::system_prompt`] resolves to (the
/// profile's own value if set, else whatever the builder already had —
/// see [`ConfigBuilder::apply_profile`]'s composition order), distinct
/// from REPLACING it. `[project-forbidden]`, same trust boundary as
/// `system_prompt` (§3.3: prompt injection).
pub append_system_prompt: Option<String>,
/// Sampling temperature.
pub temperature: Option<f32>,
/// Output token cap per request.
pub max_tokens: Option<u32>,
/// Reasoning/effort level.
pub effort: Option<String>,
/// Sandbox policy: `read_only` | `workspace_write` | `danger_full_access`.
pub sandbox: Option<String>,
/// Approval policy: `never` | `on_request` | `untrusted`.
pub approval: Option<String>,
/// Auto-load CLAUDE.md / AGENTS.md.
pub project_context: Option<bool>,
/// Per-`send` iteration budget (§3.1 `core.max_iterations`).
pub max_iterations: Option<usize>,
/// Extra roots beyond `cwd` (§3.1 `core.additional_dirs`); arrays
/// replace wholesale on overlay (§3.3).
pub additional_dirs: Option<Vec<String>>,
/// Compact once the conversation exceeds this many messages (§3.1
/// `core.compaction.after_messages`; `0` = trigger off).
pub compact_after_messages: Option<usize>,
/// Prompt-caching plan: `off` | `imported_prefix` (§3.1
/// `capabilities.cache.plan`).
pub cache_plan: Option<String>,
/// How tools are advertised: `full` | `deferred` (§3.1
/// `capabilities.deferred_tools`).
pub tool_advertising: Option<String>,
/// The eagerly-advertised core allowlist when `tool_advertising =
/// "deferred"` (§3.1 `capabilities.deferred_tools.core`); arrays replace.
pub tool_advertising_core: Option<Vec<String>>,
/// Global tool-schema tier: `full` | `medium` | `minimal` (§3.1
/// `core.tools.schema_tier`).
pub schema_tier: Option<String>,
/// Tools that never require approval under `ApprovalPolicy::OnRequest`
/// (§3.1 `capabilities.permissions.auto_approved_tools`); arrays replace.
pub auto_approved_tools: Option<Vec<String>>,
/// P4: deny-pattern generalization of `auto_approved_tools` (§3.1
/// `capabilities.permissions.rules.deny`) — see
/// [`Config::tool_deny_patterns`]. Arrays replace.
pub tool_deny_patterns: Option<Vec<String>>,
/// P4: allow-pattern generalization of `auto_approved_tools` (§3.1
/// `capabilities.permissions.rules.allow`) — see
/// [`Config::tool_allow_patterns`]. Arrays replace.
pub tool_allow_patterns: Option<Vec<String>>,
/// Extra HTTP headers merged in (§3.1 `core.extra_headers`); a table,
/// merged key-wise on overlay (§3.3).
pub extra_headers: Option<HashMap<String, String>>,
/// Extra request-body fields merged in (§3.1 `core.extra_body`); a
/// table, merged key-wise on overlay (§3.3).
pub extra_body: Option<serde_json::Map<String, serde_json::Value>>,
/// Max bytes of a single tool result (§3.1 `core.max_tool_output_bytes`).
pub max_tool_output_bytes: Option<usize>,
/// Cap on cumulative output tokens per `send` loop (§3.1
/// `core.max_total_output_tokens`).
pub max_total_output_tokens: Option<u64>,
/// Named prompt templates (§3.1 `[core.prompts]`); a table, merged
/// key-wise (new/overridden names layer onto the built-ins, they don't
/// wholesale-replace them).
pub prompts: Option<HashMap<String, String>>,
/// Per-tool enable/disable + description/schema-tier overrides, keyed
/// by tool name (§3.1 `[core.tools.<name>]`, §3.2 "today in no file");
/// a table, merged key-wise per tool.
pub tool_overrides: Option<HashMap<String, ToolOverrideProfile>>,
/// P4b (S3.1 `core.env_context`) -- see `Config::env_context`.
pub env_context: Option<bool>,
/// P4b (S3.1 `core.project_root_markers`) -- see
/// `Config::project_root_markers`; arrays replace.
pub project_root_markers: Option<Vec<String>>,
/// P4b (S3.1 `core.project_doc_max_bytes`) -- see
/// `Config::project_doc_max_bytes`.
pub project_doc_max_bytes: Option<usize>,
/// P4b (S3.1 `core.instruction_imports`) -- see
/// `Config::instruction_imports`.
pub instruction_imports: Option<bool>,
/// P4b (S3.1 `core.retry.enabled`) -- see `Config::retry_enabled`.
pub retry_enabled: Option<bool>,
/// P4b (S3.1 `core.retry.max_retries`) -- see `Config::retry_max_retries`.
pub retry_max_retries: Option<u32>,
/// P4b (S3.1 `core.retry.base_delay_ms`) -- see
/// `Config::retry_base_delay_ms`.
pub retry_base_delay_ms: Option<u64>,
/// P4b (S3.1 `core.compaction.reserve_tokens`) -- see
/// `Config::compaction_reserve_tokens`.
pub compaction_reserve_tokens: Option<u64>,
/// P4b (S3.1 `core.compaction.keep_recent_tokens`) -- see
/// `Config::compaction_keep_recent_tokens`.
pub compaction_keep_recent_tokens: Option<u64>,
/// P4b (S3.1 `core.compaction.focus_instructions`) -- see
/// `Config::compaction_focus_instructions`.
pub compaction_focus_instructions: Option<String>,
/// P4b (S3.1 `core.session.auto_title`) -- see `Config::auto_title`.
pub auto_title: Option<bool>,
/// P4b (S3.1 `core.steering.steering_mode`) -- see
/// `Config::steering_mode`.
pub steering_mode: Option<String>,
/// P4b (S3.1 `core.steering.follow_up_mode`) -- see
/// `Config::follow_up_mode`.
pub follow_up_mode: Option<String>,
/// P4c (S3.1 `core.tools.read_file.multimodal`) -- see
/// `Config::read_file_multimodal`.
pub read_file_multimodal: Option<bool>,
/// P4c (S3.1 `core.tools.edit_file.require_read_before_edit`) -- see
/// `Config::edit_file_require_read_before_edit`.
pub edit_file_require_read_before_edit: Option<bool>,
/// P4c (S3.1 `core.tools.edit_file.notebook_aware`) -- see
/// `Config::edit_file_notebook_aware`.
pub edit_file_notebook_aware: Option<bool>,
/// P4c (S3.1 `core.shell_env_snapshot`) -- see
/// `Config::shell_env_snapshot`.
pub shell_env_snapshot: Option<bool>,
/// P4c (S3.1 `core.doom_loop_threshold`) -- see
/// `Config::doom_loop_threshold`.
pub doom_loop_threshold: Option<u32>,
/// P4c (S3.1 `core.nested_instructions`) -- see
/// `Config::nested_instructions`.
pub nested_instructions: Option<bool>,
/// P4c (S3.1 `core.model_switch.allow_switch`) -- see
/// `Config::model_switch_allow_switch`.
pub model_switch_allow_switch: Option<bool>,
/// P4e (S3.1 `core.context_injections`) -- see
/// `Config::context_injections`. Only the boolean gate is
/// file/profile-settable; `Config::context_injection_blocks`' actual
/// content is code-only (see its doc comment).
pub context_injections: Option<bool>,
/// P4e (S3.1 `core.compaction.enabled`) -- see
/// `Config::compaction_enabled`.
pub compaction_enabled: Option<bool>,
/// P4e (S3.1 `core.parallel_tool_calls`) -- see
/// `Config::parallel_tool_calls`.
pub parallel_tool_calls: Option<bool>,
/// P4e (S3.1 `core.session.git_metadata`) -- see
/// `Config::session_git_metadata`.
pub session_git_metadata: Option<bool>,
/// P4e (S3.1 `core.session.dir`) -- see `Config::session_dir`.
pub session_dir: Option<String>,
/// P4e (S3.1 `core.session.persist`) -- see `Config::session_persist`.
pub session_persist: Option<bool>,
/// P4e (S3.1 `core.session.name`) -- see `Config::session_name`.
pub session_name: Option<String>,
/// P4e (S3.1 `core.session.retention_days`) -- see
/// `Config::session_retention_days`.
pub session_retention_days: Option<u32>,
/// P4e (S3.1 `core.session.export_format`) -- see
/// `Config::session_export_format`. `"text"` | `"html"`; an
/// unrecognized string is a no-op warning, like `steering_mode`.
pub session_export_format: Option<String>,
}
/// A config file: a set of named profiles (the analog of Codex `-p/--profile`).
/// This is the **SDK/embedder** config surface; the supercode CLI uses a
/// separate TOML config (`userconfig::FileConfig` in the `cli` crate) and does
/// not expose this file or a `--profile` flag.
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct ConfigFile {
/// Profiles keyed by name.
#[serde(default)]
pub profiles: HashMap<String, ConfigProfile>,
}
impl Config {
/// Load a named profile from a JSON config file into a builder. Layered:
/// start from defaults, then apply the named profile's set fields.
pub fn from_profile_file(
path: impl AsRef<std::path::Path>,
profile: &str,
) -> crate::Result<ConfigBuilder> {
let text = std::fs::read_to_string(path.as_ref())?;
let file: ConfigFile = serde_json::from_str(&text).map_err(crate::Error::Decode)?;
let p = file
.profiles
.get(profile)
.ok_or_else(|| crate::Error::Other(format!("no profile `{profile}` in config file")))?;
Ok(ConfigBuilder::default().apply_profile(p))
}
}
impl ConfigBuilder {
/// Apply the set fields of a [`ConfigProfile`] over the current builder.
pub fn apply_profile(mut self, p: &ConfigProfile) -> Self {
if let Some(m) = &p.model {
self.config.model = m.clone();
}
if let Some(u) = &p.base_url {
self.config.base_url = u.clone();
}
if let Some(s) = &p.system_prompt {
self.config.system_prompt = s.clone();
}
if let Some(extra) = &p.append_system_prompt {
// P4 (§3.1 `core.append_system_prompt`): additive, composed onto
// whatever `system_prompt` is on the builder AT THIS POINT —
// either the value just applied above, or whatever the caller
// already set/left at its `Config::default()` — never a
// replacement. This intentionally runs regardless of whether
// `p.system_prompt` was set, so an append-only profile still
// composes onto the existing base.
self.config.system_prompt = format!("{}\n\n{extra}", self.config.system_prompt);
}
self.config.temperature = p.temperature.or(self.config.temperature);
self.config.max_tokens = p.max_tokens.or(self.config.max_tokens);
if p.effort.is_some() {
self.config.effort = p.effort.clone();
}
if let Some(sb) = &p.sandbox {
// Fail *safe*: an unrecognized value (typo, future variant) must not
// silently grant full filesystem access. Only the explicit
// danger string opts out of confinement.
self.config.sandbox = match sb.as_str() {
"read_only" | "read-only" | "readonly" => crate::tools::SandboxPolicy::ReadOnly,
"workspace_write" | "workspace-write" => {
crate::tools::SandboxPolicy::WorkspaceWrite
}
"danger_full_access" | "danger-full-access" => {
crate::tools::SandboxPolicy::DangerFullAccess
}
other => {
tracing::warn!(
"unknown sandbox policy `{other}` in profile; defaulting to read_only"
);
crate::tools::SandboxPolicy::ReadOnly
}
};
}
if let Some(ap) = &p.approval {
// Fail safe: an unrecognized value defaults to the most-prompting
// policy, never to `never`.
self.config.approval = match ap.as_str() {
"on_request" | "on-request" => ApprovalPolicy::OnRequest,
"untrusted" => ApprovalPolicy::Untrusted,
"never" => ApprovalPolicy::Never,
// P5-1 (§3.2 S8): cx-parity's real intended posture — see
// `ApprovalPolicy::ModelRequested`'s doc comment.
"model_requested" | "model-requested" => ApprovalPolicy::ModelRequested,
other => {
tracing::warn!(
"unknown approval policy `{other}` in profile; defaulting to untrusted"
);
ApprovalPolicy::Untrusted
}
};
}
if let Some(pc) = p.project_context {
self.config.load_project_context = pc;
}
if let Some(env) = &p.api_key_env {
self.config.api_key_env = env.clone();
}
if let Some(cmd) = &p.api_key_cmd {
self.config.api_key_cmd = Some(cmd.clone());
}
// Scalars replace (§3.3).
if let Some(n) = p.max_iterations {
self.config.max_iterations = n;
}
// Arrays replace wholesale (§3.3), not append — predictable overlay.
if let Some(dirs) = &p.additional_dirs {
self.config.additional_dirs = dirs.iter().map(std::path::PathBuf::from).collect();
}
if let Some(n) = p.compact_after_messages {
self.config.compact_after_messages = Some(n);
}
if let Some(plan) = &p.cache_plan {
// Fail safe: an unrecognized value never silently opts into
// caching behavior the operator didn't ask for.
self.config.cache_plan = match plan.as_str() {
"off" => CachePlan::Off,
"imported_prefix" | "imported-prefix" => CachePlan::ImportedPrefix,
other => {
tracing::warn!("unknown cache plan `{other}` in profile; defaulting to off");
CachePlan::Off
}
};
}
if p.tool_advertising.is_some() || p.tool_advertising_core.is_some() {
// F6 fix: per-key replace (§3.3) — neither key alone may clobber
// the other's current value. Compute the effective core list
// FIRST (the profile's new value if given, else whatever's
// already active) so an explicit `"deferred"` mode with no
// `_core` doesn't wipe an existing list, then only change the
// MODE if the profile actually set one — setting `_core` alone
// must not silently reset the mode to `Full` (which previously
// discarded the array outright, since `Full` ignores it).
let existing_core = match &self.config.tool_advertising {
ToolAdvertising::Deferred { core } => core.clone(),
ToolAdvertising::Full => Vec::new(),
};
let core = p.tool_advertising_core.clone().unwrap_or(existing_core);
self.config.tool_advertising = match p.tool_advertising.as_deref() {
Some("deferred") => ToolAdvertising::Deferred { core },
Some("full") => ToolAdvertising::Full,
Some(other) => {
tracing::warn!(
"unknown tool_advertising mode `{other}` in profile; defaulting to full"
);
ToolAdvertising::Full
}
None => match &self.config.tool_advertising {
// Mode untouched — only refresh the core list if
// already `Deferred` (`Full` has nowhere to put one).
ToolAdvertising::Deferred { .. } => ToolAdvertising::Deferred { core },
ToolAdvertising::Full => ToolAdvertising::Full,
},
};
}
if let Some(tier) = &p.schema_tier {
// Fail safe: unrecognized value keeps the verbose (never
// under-informative) default rather than guessing a shrink tier.
self.config.tool_schema_tier =
crate::tools::SchemaTier::parse(tier).unwrap_or_else(|| {
tracing::warn!("unknown schema tier `{tier}` in profile; defaulting to full");
crate::tools::SchemaTier::Full
});
}
// Arrays replace wholesale (§3.3).
if let Some(tools) = &p.auto_approved_tools {
self.config.auto_approved_tools = tools.iter().cloned().collect();
}
if let Some(patterns) = &p.tool_deny_patterns {
self.config.tool_deny_patterns = patterns.clone();
}
if let Some(patterns) = &p.tool_allow_patterns {
self.config.tool_allow_patterns = patterns.clone();
}
// Tables merge key-wise (§3.3), not wholesale replace.
if let Some(headers) = &p.extra_headers {
for (k, v) in headers {
self.config.extra_headers.insert(k.clone(), v.clone());
}
}
if let Some(body) = &p.extra_body {
for (k, v) in body {
self.config.extra_body.insert(k.clone(), v.clone());
}
}
if let Some(n) = p.max_tool_output_bytes {
self.config.max_tool_output_bytes = Some(n);
}
if let Some(n) = p.max_total_output_tokens {
self.config.max_total_output_tokens = Some(n);
}
if let Some(prompts) = &p.prompts {
for (k, v) in prompts {
self.config.prompts.insert(k.clone(), v.clone());
}
}
if let Some(overrides) = &p.tool_overrides {
for (name, o) in overrides {
let entry = self.config.tool_overrides.entry(name.clone()).or_default();
if let Some(en) = o.enabled {
entry.enabled = Some(en);
}
if let Some(desc) = &o.description {
entry.description = Some(desc.clone());
}
if let Some(tier) = &o.schema_tier {
entry.schema_tier = Some(crate::tools::SchemaTier::parse(tier).unwrap_or_else(|| {
tracing::warn!(
"unknown schema tier `{tier}` in tool override `{name}`; defaulting to full"
);
crate::tools::SchemaTier::Full
}));
}
if let Some(t) = o.timeout_secs {
entry.timeout_secs = Some(t);
}
}
}
// P4b: scalars replace (S3.3).
if let Some(v) = p.env_context {
self.config.env_context = v;
}
if let Some(v) = &p.project_root_markers {
self.config.project_root_markers = v.clone();
}
if let Some(v) = p.project_doc_max_bytes {
self.config.project_doc_max_bytes = Some(v);
}
if let Some(v) = p.instruction_imports {
self.config.instruction_imports = v;
}
if let Some(v) = p.retry_enabled {
self.config.retry_enabled = v;
}
if let Some(v) = p.retry_max_retries {
self.config.retry_max_retries = Some(v);
}
if let Some(v) = p.retry_base_delay_ms {
self.config.retry_base_delay_ms = Some(v);
}
if let Some(v) = p.compaction_reserve_tokens {
self.config.compaction_reserve_tokens = Some(v);
}
if let Some(v) = p.compaction_keep_recent_tokens {
self.config.compaction_keep_recent_tokens = Some(v);
}
if let Some(v) = &p.compaction_focus_instructions {
self.config.compaction_focus_instructions = Some(v.clone());
}
if let Some(v) = p.auto_title {
self.config.auto_title = v;
}
if let Some(mode) = &p.steering_mode {
// Fail safe: an unrecognized value keeps the current setting
// rather than guessing.
match SteeringMode::parse(mode) {
Some(m) => self.config.steering_mode = m,
None => tracing::warn!("unknown steering_mode `{mode}` in profile; ignoring"),
}
}
if let Some(mode) = &p.follow_up_mode {
match SteeringMode::parse(mode) {
Some(m) => self.config.follow_up_mode = m,
None => tracing::warn!("unknown follow_up_mode `{mode}` in profile; ignoring"),
}
}
// P4c: scalars replace (S3.3).
if let Some(v) = p.read_file_multimodal {
self.config.read_file_multimodal = v;
}
if let Some(v) = p.edit_file_require_read_before_edit {
self.config.edit_file_require_read_before_edit = v;
}
if let Some(v) = p.edit_file_notebook_aware {
self.config.edit_file_notebook_aware = v;
}
if let Some(v) = p.shell_env_snapshot {
self.config.shell_env_snapshot = v;
}
if let Some(v) = p.doom_loop_threshold {
self.config.doom_loop_threshold = Some(v);
}
if let Some(v) = p.nested_instructions {
self.config.nested_instructions = v;
}
if let Some(v) = p.model_switch_allow_switch {
self.config.model_switch_allow_switch = v;
}
// P4e: scalars replace (S3.3).
if let Some(v) = p.context_injections {
self.config.context_injections = v;
}
if let Some(v) = p.compaction_enabled {
self.config.compaction_enabled = v;
}
if let Some(v) = p.parallel_tool_calls {
self.config.parallel_tool_calls = v;
}
if let Some(v) = p.session_git_metadata {
self.config.session_git_metadata = v;
}
if let Some(v) = &p.session_dir {
self.config.session_dir = Some(v.clone());
}
if let Some(v) = p.session_persist {
self.config.session_persist = v;
}
if let Some(v) = &p.session_name {
self.config.session_name = Some(v.clone());
}
if let Some(v) = p.session_retention_days {
self.config.session_retention_days = Some(v);
}
if let Some(fmt) = &p.session_export_format {
match crate::human_export::HumanExportFormat::parse(fmt) {
Some(f) => self.config.session_export_format = f,
None => {
tracing::warn!("unknown session export_format `{fmt}` in profile; ignoring")
}
}
}
self
}
}
/// Fluent builder for [`Config`].
#[derive(Default)]
pub struct ConfigBuilder {
config: Config,
}
impl ConfigBuilder {
/// P4d (design §5.2 P1 CLI-adapter): resume building from an
/// ALREADY-constructed [`Config`] rather than [`Config::default`] — lets
/// a caller that assembled a `Config` with its own precedence logic
/// (e.g. the CLI's `build_config`: flag > env > project > user >
/// interactive-default) layer a narrowly-scoped [`ConfigProfile`] on top
/// via [`Self::apply_profile`] afterward, reusing that method's correct
/// per-key merge semantics (tables merge key-wise, e.g.
/// `tool_overrides`/`prompts`/`extra_headers`/`extra_body`) instead of a
/// second hand-rolled copy of the same merge logic at the call site.
pub fn from_config(config: Config) -> Self {
ConfigBuilder { config }
}
/// Set the model identifier.
pub fn model(mut self, model: impl Into<String>) -> Self {
self.config.model = model.into();
self
}
/// Set the OpenAI-compatible base URL (defaults to OpenRouter).
pub fn base_url(mut self, url: impl Into<String>) -> Self {
self.config.base_url = url.into();
self
}
/// Provide the API key explicitly.
pub fn api_key(mut self, key: impl Into<String>) -> Self {
self.config.api_key = Some(key.into());
self
}
/// Change which environment variable the key is read from.
pub fn api_key_env(mut self, var: impl Into<String>) -> Self {
self.config.api_key_env = var.into();
self
}
/// Set the credential-helper command — see [`Config::api_key_cmd`].
pub fn api_key_cmd(mut self, cmd: impl Into<String>) -> Self {
self.config.api_key_cmd = Some(cmd.into());
self
}
/// Replace the system prompt.
pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
self.config.system_prompt = prompt.into();
self
}
/// Set the sampling temperature.
pub fn temperature(mut self, t: f32) -> Self {
self.config.temperature = Some(t);
self
}
/// Set the max output tokens.
pub fn max_tokens(mut self, n: u32) -> Self {
self.config.max_tokens = Some(n);
self
}
/// Set the per-`send` iteration budget.
pub fn max_iterations(mut self, n: usize) -> Self {
self.config.max_iterations = n;
self
}
/// Set the reasoning/effort level (`reasoning_effort`).
pub fn effort(mut self, level: impl Into<String>) -> Self {
self.config.effort = Some(level.into());
self
}
/// Constrain output to a JSON schema (`response_format`).
pub fn response_format(mut self, format: serde_json::Value) -> Self {
self.config.response_format = Some(format);
self
}
/// Merge an extra request-body field (provider-native passthrough).
pub fn extra_body_field(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
self.config.extra_body.insert(key.into(), value);
self
}
/// Cap cumulative output tokens across one `send` loop.
/// Cap a single tool result at `n` bytes (see
/// [`Config::max_tool_output_bytes`]). Pass `0` only via the field to disable.
pub fn max_tool_output_bytes(mut self, n: usize) -> Self {
self.config.max_tool_output_bytes = Some(n);
self
}
/// Cap on cumulative output tokens across one send loop. Output tokens
/// only; input/prompt tokens are not counted, so this is not a cost cap.
pub fn max_total_output_tokens(mut self, n: u64) -> Self {
self.config.max_total_output_tokens = Some(n);
self
}
/// Set the working directory tools operate in.
pub fn cwd(mut self, dir: impl Into<PathBuf>) -> Self {
self.config.cwd = dir.into();
self
}
/// Add an extra root directory (`--add-dir` / multi-root / worktree).
pub fn add_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.config.additional_dirs.push(dir.into());
self
}
/// Enable auto-loading of `CLAUDE.md` / `AGENTS.md` into the system prompt.
pub fn project_context(mut self, enabled: bool) -> Self {
self.config.load_project_context = enabled;
self
}
/// Register a named prompt template (skill / slash command).
pub fn prompt(mut self, name: impl Into<String>, template: impl Into<String>) -> Self {
self.config.prompts.insert(name.into(), template.into());
self
}
/// Compact the conversation once it exceeds `n` messages.
pub fn compact_after_messages(mut self, n: usize) -> Self {
self.config.compact_after_messages = Some(n);
self
}
/// Set the filesystem sandbox policy for write-capable tools.
pub fn sandbox(mut self, policy: crate::tools::SandboxPolicy) -> Self {
self.config.sandbox = policy;
self
}
/// Set the tool-approval policy.
pub fn approval(mut self, policy: ApprovalPolicy) -> Self {
self.config.approval = policy;
self
}
/// Add a tool to the auto-approve allowlist (no approval under `OnRequest`).
pub fn auto_approve_tool(mut self, name: impl Into<String>) -> Self {
self.config.auto_approved_tools.insert(name.into());
self
}
/// P4: add a glob pattern to [`Config::tool_deny_patterns`] — a match
/// forces approval unconditionally, even under `ApprovalPolicy::Never`.
pub fn deny_tool_pattern(mut self, pattern: impl Into<String>) -> Self {
self.config.tool_deny_patterns.push(pattern.into());
self
}
/// P4: add a glob pattern to [`Config::tool_allow_patterns`] — the
/// pattern generalization of [`Self::auto_approve_tool`].
pub fn allow_tool_pattern(mut self, pattern: impl Into<String>) -> Self {
self.config.tool_allow_patterns.push(pattern.into());
self
}
/// Set the handler consulted when a tool call needs approval.
pub fn approval_handler(mut self, handler: ApprovalHandler) -> Self {
self.config.approval_handler = Some(handler);
self
}
/// Set the pre-tool hook (may block a call by returning `Some(reason)`).
pub fn pre_tool_hook(mut self, hook: PreToolHook) -> Self {
self.config.pre_tool_hook = Some(hook);
self
}
/// Set the post-tool hook (observational).
pub fn post_tool_hook(mut self, hook: PostToolHook) -> Self {
self.config.post_tool_hook = Some(hook);
self
}
/// Disable a tool by name.
pub fn disable_tool(mut self, name: impl Into<String>) -> Self {
self.config
.tool_overrides
.entry(name.into())
.or_default()
.enabled = Some(false);
self
}
/// Enable a tool by name (overriding a prior disable).
pub fn enable_tool(mut self, name: impl Into<String>) -> Self {
self.config
.tool_overrides
.entry(name.into())
.or_default()
.enabled = Some(true);
self
}
/// Override the description the model sees for a tool.
pub fn tool_description(
mut self,
name: impl Into<String>,
description: impl Into<String>,
) -> Self {
self.config
.tool_overrides
.entry(name.into())
.or_default()
.description = Some(description.into());
self
}
/// Set how tools are advertised to the model (B6).
pub fn tool_advertising(mut self, advertising: ToolAdvertising) -> Self {
self.config.tool_advertising = advertising;
self
}
/// Set the global tool-schema tier (TR-8/T5): how verbose ADVERTISED
/// tool schemas are. Per-tool overrides ([`Self::tool_schema_tier`])
/// still win for the specific tools they name.
pub fn schema_tier(mut self, tier: crate::tools::SchemaTier) -> Self {
self.config.tool_schema_tier = tier;
self
}
/// Override the schema tier for a single tool (TR-8/T5), regardless of
/// the global knob — e.g. keep one load-bearing tool at `Full` while
/// everything else shrinks to `Minimal`.
pub fn tool_schema_tier(
mut self,
name: impl Into<String>,
tier: crate::tools::SchemaTier,
) -> Self {
self.config
.tool_overrides
.entry(name.into())
.or_default()
.schema_tier = Some(tier);
self
}
/// Add an extra HTTP header sent on every request.
pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.config.extra_headers.insert(key.into(), value.into());
self
}
/// Attach a streaming event sink.
pub fn event_sink(mut self, sink: EventSink) -> Self {
self.config.event_sink = Some(sink);
self
}
/// Set the prompt-caching plan (B7).
pub fn cache_plan(mut self, plan: CachePlan) -> Self {
self.config.cache_plan = plan;
self
}
/// UX-26 (B7-warn): enable/disable the cache-cold warning (default on).
pub fn cache_warnings(mut self, enabled: bool) -> Self {
self.config.cache_warnings = enabled;
self
}
/// P3: turn on the `[experimental] module_registry` gate — see
/// [`Config::module_registry`].
pub fn module_registry(mut self, enabled: bool) -> Self {
self.config.module_registry = enabled;
self
}
/// P3: set the resolved module-activation set — see
/// [`Config::module_activation`].
pub fn module_activation(mut self, activation: crate::modules::ModuleActivation) -> Self {
self.config.module_activation = activation;
self
}
/// P3: set the effective `[core.tools] enabled` list — see
/// [`Config::core_tools_enabled`].
pub fn core_tools_enabled(mut self, tools: Vec<String>) -> Self {
self.config.core_tools_enabled = tools;
self
}
/// P3: set `[core.skills].enabled` — see [`Config::skills_enabled`].
pub fn skills_enabled(mut self, enabled: bool) -> Self {
self.config.skills_enabled = enabled;
self
}
/// P4: set the small/utility model id — see `Config::small_model`.
pub fn small_model(mut self, model: impl Into<String>) -> Self {
self.config.small_model = Some(model.into());
self
}
/// P4: set the model failure-fallback chain — see `Config::model_fallback`.
pub fn model_fallback(mut self, chain: Vec<String>) -> Self {
self.config.model_fallback = chain;
self
}
/// P4b: turn on the environment-context block — see [`Config::env_context`].
pub fn env_context(mut self, enabled: bool) -> Self {
self.config.env_context = enabled;
self
}
/// P4b: set the project-root marker filenames — see
/// [`Config::project_root_markers`].
pub fn project_root_markers(mut self, markers: Vec<String>) -> Self {
self.config.project_root_markers = markers;
self
}
/// P4b: cap the total bytes of assembled instruction-file content — see
/// [`Config::project_doc_max_bytes`].
pub fn project_doc_max_bytes(mut self, n: usize) -> Self {
self.config.project_doc_max_bytes = Some(n);
self
}
/// P4b: turn on `@path` instruction imports — see
/// [`Config::instruction_imports`].
pub fn instruction_imports(mut self, enabled: bool) -> Self {
self.config.instruction_imports = enabled;
self
}
/// P4b: configure request retry with backoff — see
/// [`Config::retry_enabled`]. `max_retries`/`base_delay_ms` override the
/// transport's built-in defaults when `Some`.
pub fn retry(
mut self,
enabled: bool,
max_retries: Option<u32>,
base_delay_ms: Option<u64>,
) -> Self {
self.config.retry_enabled = enabled;
self.config.retry_max_retries = max_retries;
self.config.retry_base_delay_ms = base_delay_ms;
self
}
/// P4b: turn on the compaction token-pressure trigger — see
/// [`Config::compaction_reserve_tokens`].
pub fn compaction_pressure(mut self, reserve_tokens: u64, keep_recent_tokens: u64) -> Self {
self.config.compaction_reserve_tokens = Some(reserve_tokens);
self.config.compaction_keep_recent_tokens = Some(keep_recent_tokens);
self
}
/// P4b: set the compaction focus instructions — see
/// [`Config::compaction_focus_instructions`].
pub fn compaction_focus_instructions(mut self, text: impl Into<String>) -> Self {
self.config.compaction_focus_instructions = Some(text.into());
self
}
/// P4b: turn on the auto-title gate — see [`Config::auto_title`].
pub fn auto_title(mut self, enabled: bool) -> Self {
self.config.auto_title = enabled;
self
}
/// P4b: set the mid-turn steering delivery mode — see
/// [`Config::steering_mode`].
pub fn steering_mode(mut self, mode: SteeringMode) -> Self {
self.config.steering_mode = mode;
self
}
/// P4b: set the idle follow-up delivery mode — see
/// [`Config::follow_up_mode`].
pub fn follow_up_mode(mut self, mode: SteeringMode) -> Self {
self.config.follow_up_mode = mode;
self
}
/// P4b: install a stop-gate hook — see [`Config::stop_gate`].
pub fn stop_gate(mut self, hook: StopGateHook) -> Self {
self.config.stop_gate = Some(hook);
self
}
/// P4c: turn on multimodal `read_file` — see [`Config::read_file_multimodal`].
pub fn read_file_multimodal(mut self, enabled: bool) -> Self {
self.config.read_file_multimodal = enabled;
self
}
/// P4c: require a prior read before `edit_file` accepts an edit — see
/// [`Config::edit_file_require_read_before_edit`].
pub fn edit_file_require_read_before_edit(mut self, enabled: bool) -> Self {
self.config.edit_file_require_read_before_edit = enabled;
self
}
/// P4c: turn on notebook-cell-aware `edit_file` — see
/// [`Config::edit_file_notebook_aware`].
pub fn edit_file_notebook_aware(mut self, enabled: bool) -> Self {
self.config.edit_file_notebook_aware = enabled;
self
}
/// P4c: turn on shell-environment snapshotting — see
/// [`Config::shell_env_snapshot`].
pub fn shell_env_snapshot(mut self, enabled: bool) -> Self {
self.config.shell_env_snapshot = enabled;
self
}
/// P4c: set the doom-loop repetition threshold — see
/// [`Config::doom_loop_threshold`].
pub fn doom_loop_threshold(mut self, n: u32) -> Self {
self.config.doom_loop_threshold = Some(n);
self
}
/// P4c: turn on on-demand nested instruction loading — see
/// [`Config::nested_instructions`].
pub fn nested_instructions(mut self, enabled: bool) -> Self {
self.config.nested_instructions = enabled;
self
}
/// P4c: turn on mid-session model switch's persisted-record +
/// reasoning-filter behavior — see [`Config::model_switch_allow_switch`].
pub fn model_switch_allow_switch(mut self, enabled: bool) -> Self {
self.config.model_switch_allow_switch = enabled;
self
}
/// P4e: turn on ambient context-injection blocks — see
/// [`Config::context_injections`].
pub fn context_injections(mut self, enabled: bool) -> Self {
self.config.context_injections = enabled;
self
}
/// P4e: append one named ambient context block — see
/// [`Config::context_injection_blocks`].
pub fn context_injection_block(
mut self,
name: impl Into<String>,
content: impl Into<String>,
) -> Self {
self.config
.context_injection_blocks
.push(ContextInjectionBlock::new(name, content));
self
}
/// P4e: master gate for all auto-compaction — see
/// [`Config::compaction_enabled`].
pub fn compaction_enabled(mut self, enabled: bool) -> Self {
self.config.compaction_enabled = enabled;
self
}
/// P4e: run independent tool calls concurrently — see
/// [`Config::parallel_tool_calls`].
pub fn parallel_tool_calls(mut self, enabled: bool) -> Self {
self.config.parallel_tool_calls = enabled;
self
}
/// P4e: capture git branch/sha/dirty at construction — see
/// [`Config::session_git_metadata`].
pub fn session_git_metadata(mut self, enabled: bool) -> Self {
self.config.session_git_metadata = enabled;
self
}
/// P4e DEFECT-FIX: ephemeral vs. persisted session gate — see
/// [`Config::session_persist`].
pub fn session_persist(mut self, enabled: bool) -> Self {
self.config.session_persist = enabled;
self
}
/// P4e DEFECT-FIX: a caller-configured session name — see
/// [`Config::session_name`].
pub fn session_name(mut self, name: impl Into<String>) -> Self {
self.config.session_name = Some(name.into());
self
}
/// P5-3 (§3.1 `capabilities.subagents.enabled`) — see
/// [`Config::subagents_enabled`].
pub fn subagents_enabled(mut self, enabled: bool) -> Self {
self.config.subagents_enabled = enabled;
self
}
/// P5-3 (§3.1 `capabilities.subagents.max_depth`) — see
/// [`Config::subagents_max_depth`].
pub fn subagents_max_depth(mut self, n: usize) -> Self {
self.config.subagents_max_depth = n;
self
}
/// P5-3 (resource bound) — see [`Config::subagents_max_concurrent`].
pub fn subagents_max_concurrent(mut self, n: usize) -> Self {
self.config.subagents_max_concurrent = n;
self
}
/// P5-3 (§3.1 `capabilities.subagents.background`) — see
/// [`Config::subagents_background`].
pub fn subagents_background(mut self, enabled: bool) -> Self {
self.config.subagents_background = enabled;
self
}
/// P5-3 (§2.2 C6) — see [`Config::subagents_background_prompts`].
pub fn subagents_background_prompts(
mut self,
policy: crate::subagents::BackgroundPromptsPolicy,
) -> Self {
self.config.subagents_background_prompts = Some(policy);
self
}
/// Enable Claude Code's `Agent` compatibility alias for named subagents.
pub fn subagents_claude_agent_alias(mut self, enabled: bool) -> Self {
self.config.subagents_claude_agent_alias = enabled;
self
}
/// Enable Claude's paused runtime-state compatibility intrinsics.
pub fn claude_runtime_tools_enabled(mut self, enabled: bool) -> Self {
self.config.claude_runtime_tools_enabled = enabled;
self
}
/// P5-3 (§3.1 `capabilities.subagents.agents.<name>`) — register one
/// named agent definition, keyed by [`crate::subagents::NamedAgentDefinition::name`].
pub fn subagent_definition(mut self, def: crate::subagents::NamedAgentDefinition) -> Self {
self.config
.subagents_definitions
.insert(def.name.clone(), def);
self
}
/// P5-3 (runtime-only) — see [`Config::subagent_depth`]. Not something
/// an ordinary caller sets by hand; `Agent::run_spawn_subagent` sets it
/// on the CHILD config it builds.
pub fn subagent_depth(mut self, depth: usize) -> Self {
self.config.subagent_depth = depth;
self
}
/// P5-6 (§3.1 `capabilities.tools_background.enabled`) — see
/// [`Config::tools_background_enabled`].
pub fn tools_background_enabled(mut self, enabled: bool) -> Self {
self.config.tools_background_enabled = enabled;
self
}
/// P5-6 (resource bound) — see [`Config::tools_background_max_concurrent`].
pub fn tools_background_max_concurrent(mut self, n: usize) -> Self {
self.config.tools_background_max_concurrent = n;
self
}
/// P5-6 (resource bound) — see [`Config::tools_background_max_output_bytes`].
pub fn tools_background_max_output_bytes(mut self, n: usize) -> Self {
self.config.tools_background_max_output_bytes = n;
self
}
/// P5-9 (§3.1 `capabilities.checkpoint.enabled`) — see
/// [`Config::checkpoint_enabled`].
pub fn checkpoint_enabled(mut self, enabled: bool) -> Self {
self.config.checkpoint_enabled = enabled;
self
}
/// P5-9 (bounded-disk requirement) — see [`Config::checkpoint_retain`].
pub fn checkpoint_retain(mut self, n: usize) -> Self {
self.config.checkpoint_retain = n;
self
}
/// P5-9 (embedder/test override) — see [`Config::checkpoint_dir`].
pub fn checkpoint_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.config.checkpoint_dir = Some(dir.into());
self
}
/// P5-11 (§3.1 `capabilities.lsp.enabled`) — see [`Config::lsp_enabled`].
pub fn lsp_enabled(mut self, enabled: bool) -> Self {
self.config.lsp_enabled = enabled;
self
}
/// P5-11 (`capabilities.lsp.servers`) — see [`Config::lsp_servers`].
pub fn lsp_servers(mut self, servers: Vec<(String, crate::lsp::LspServerSpec)>) -> Self {
self.config.lsp_servers = servers;
self
}
/// P5-11 (bounded-context requirement) — see [`Config::lsp_max_diagnostics`].
pub fn lsp_max_diagnostics(mut self, n: usize) -> Self {
self.config.lsp_max_diagnostics = n;
self
}
/// P5-11 (bounded-latency requirement) — see [`Config::lsp_timeout_secs`].
pub fn lsp_timeout_secs(mut self, secs: u64) -> Self {
self.config.lsp_timeout_secs = secs;
self
}
/// P5-11 (§3.1 `capabilities.formatters.enabled`) — see
/// [`Config::formatters_enabled`].
pub fn formatters_enabled(mut self, enabled: bool) -> Self {
self.config.formatters_enabled = enabled;
self
}
/// P5-11 (`capabilities.formatters.<name>`) — see [`Config::formatters`].
pub fn formatters(
mut self,
formatters: Vec<(String, crate::formatters::FormatterSpec)>,
) -> Self {
self.config.formatters = formatters;
self
}
/// P5-11 (§3.1 `capabilities.formatters.diff_back`, C10) — see
/// [`Config::formatters_diff_back`].
pub fn formatters_diff_back(mut self, diff_back: bool) -> Self {
self.config.formatters_diff_back = diff_back;
self
}
/// P5-11 (bounded-latency requirement) — see [`Config::formatters_timeout_secs`].
pub fn formatters_timeout_secs(mut self, secs: u64) -> Self {
self.config.formatters_timeout_secs = secs;
self
}
/// P5-12 (§3.1 `capabilities.trust.enabled`) — see [`Config::trust_enabled`].
pub fn trust_enabled(mut self, enabled: bool) -> Self {
self.config.trust_enabled = enabled;
self
}
/// P5-12 (`capabilities.trust.default`) — see [`Config::trust_default`].
pub fn trust_default(mut self, default: crate::plugins::TrustDecision) -> Self {
self.config.trust_default = default;
self
}
/// P5-12 (§3.1 `capabilities.plugins.enabled`) — see [`Config::plugins_enabled`].
pub fn plugins_enabled(mut self, enabled: bool) -> Self {
self.config.plugins_enabled = enabled;
self
}
/// P5-12 (`capabilities.plugins.dirs`) — see [`Config::plugins_dirs`].
pub fn plugins_dirs(mut self, dirs: Vec<PathBuf>) -> Self {
self.config.plugins_dirs = dirs;
self
}
/// Finalize the configuration.
pub fn build(self) -> Config {
self.config
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Every NEW `ConfigProfile` field the P1 migration adds (design
/// §5.2/§3.2's explicit unblock list) actually reaches the built
/// `Config` through `apply_profile`.
#[test]
fn apply_profile_applies_every_new_p1_field() {
let mut tool_overrides = HashMap::new();
tool_overrides.insert(
"write_file".to_string(),
ToolOverrideProfile {
enabled: Some(false),
description: Some("custom".to_string()),
schema_tier: Some("minimal".to_string()),
timeout_secs: None,
},
);
let mut extra_headers = HashMap::new();
extra_headers.insert("X-Title".to_string(), "supercode".to_string());
let mut extra_body = serde_json::Map::new();
extra_body.insert("provider_flag".to_string(), serde_json::json!(true));
let mut prompts = HashMap::new();
prompts.insert("standup".to_string(), "Summarize {args}".to_string());
let profile = ConfigProfile {
api_key_env: Some("MY_KEY".to_string()),
max_iterations: Some(40),
additional_dirs: Some(vec!["../sibling".to_string()]),
compact_after_messages: Some(50),
cache_plan: Some("imported_prefix".to_string()),
tool_advertising: Some("deferred".to_string()),
tool_advertising_core: Some(vec!["bash".to_string()]),
schema_tier: Some("medium".to_string()),
auto_approved_tools: Some(vec!["read_file".to_string()]),
extra_headers: Some(extra_headers),
extra_body: Some(extra_body),
max_tool_output_bytes: Some(4096),
max_total_output_tokens: Some(8192),
prompts: Some(prompts),
tool_overrides: Some(tool_overrides),
..Default::default()
};
let config = ConfigBuilder::default().apply_profile(&profile).build();
assert_eq!(config.api_key_env, "MY_KEY");
assert_eq!(config.max_iterations, 40);
assert_eq!(
config.additional_dirs,
vec![std::path::PathBuf::from("../sibling")]
);
assert_eq!(config.compact_after_messages, Some(50));
assert_eq!(config.cache_plan, CachePlan::ImportedPrefix);
match &config.tool_advertising {
ToolAdvertising::Deferred { core } => assert_eq!(core, &vec!["bash".to_string()]),
ToolAdvertising::Full => panic!("expected Deferred"),
}
assert_eq!(config.tool_schema_tier, crate::tools::SchemaTier::Medium);
assert!(config.auto_approved_tools.contains("read_file"));
assert_eq!(
config.extra_headers.get("X-Title").map(String::as_str),
Some("supercode")
);
assert_eq!(
config.extra_body.get("provider_flag"),
Some(&serde_json::json!(true))
);
assert_eq!(config.max_tool_output_bytes, Some(4096));
assert_eq!(config.max_total_output_tokens, Some(8192));
assert_eq!(
config.prompts.get("standup").map(String::as_str),
Some("Summarize {args}")
);
assert!(!config.tool_enabled("write_file"));
assert_eq!(config.tool_description("write_file", "builtin"), "custom");
assert_eq!(
config.schema_tier_for("write_file"),
crate::tools::SchemaTier::Minimal
);
// Built-in prompts survive — `prompts` is a table merge, not a
// wholesale replace (§3.3).
assert!(config.prompts.contains_key("code-review"));
}
/// P4 (§3.1 `core.append_system_prompt`, D2 row 1): additive, composed
/// onto the DEFAULT system prompt when no `system_prompt` override is
/// set — distinct from replacing it.
#[test]
fn apply_profile_append_system_prompt_composes_onto_the_default() {
let profile = ConfigProfile {
append_system_prompt: Some("Always run tests before committing.".to_string()),
..Default::default()
};
let config = ConfigBuilder::default().apply_profile(&profile).build();
assert_eq!(
config.system_prompt,
format!("{DEFAULT_SYSTEM_PROMPT}\n\nAlways run tests before committing.")
);
}
/// Composed onto an EXPLICIT `system_prompt` override in the SAME
/// profile, not the default — replacement then append, in that order.
#[test]
fn apply_profile_append_system_prompt_composes_onto_an_explicit_override() {
let profile = ConfigProfile {
system_prompt: Some("You are terse.".to_string()),
append_system_prompt: Some("Always run tests before committing.".to_string()),
..Default::default()
};
let config = ConfigBuilder::default().apply_profile(&profile).build();
assert_eq!(
config.system_prompt,
"You are terse.\n\nAlways run tests before committing."
);
}
/// Default-off: no `append_system_prompt` set leaves `system_prompt`
/// completely untouched (byte-identical to today's behavior).
#[test]
fn apply_profile_no_append_system_prompt_leaves_system_prompt_untouched() {
let profile = ConfigProfile {
system_prompt: Some("You are terse.".to_string()),
..Default::default()
};
let config = ConfigBuilder::default().apply_profile(&profile).build();
assert_eq!(config.system_prompt, "You are terse.");
}
/// Unknown enum strings fail SAFE (existing precedent, config.rs
/// `sandbox`/`approval` parsing) — extended to the two NEW enum-shaped
/// fields this migration adds.
#[test]
fn apply_profile_fails_safe_on_unknown_new_enums() {
let profile = ConfigProfile {
cache_plan: Some("bogus".to_string()),
schema_tier: Some("bogus".to_string()),
tool_advertising: Some("bogus".to_string()),
..Default::default()
};
let config = ConfigBuilder::default().apply_profile(&profile).build();
assert_eq!(config.cache_plan, CachePlan::Off);
assert_eq!(config.tool_schema_tier, crate::tools::SchemaTier::Full);
// F5 fix: this was a bare `matches!(...)` with no `assert!` around
// it, so the expression's bool result was silently discarded — the
// fail-safe behavior it names was never actually checked.
assert!(matches!(config.tool_advertising, ToolAdvertising::Full));
}
/// F6: setting only `tool_advertising_core` (mode absent) must not
/// silently reset the mode to `Full`, discarding the array — and
/// setting `tool_advertising = "deferred"` with no `_core` must not wipe
/// an already-set core list. Each key replaces independently (§3.3).
#[test]
fn apply_profile_tool_advertising_mode_and_core_replace_independently() {
// Only `_core` set on top of an already-`Deferred` config: the mode
// must stay `Deferred`, with the NEW core list — not reset to
// `Full` (the pre-fix bug).
let builder = ConfigBuilder::default().tool_advertising(ToolAdvertising::Deferred {
core: vec!["bash".to_string()],
});
let profile = ConfigProfile {
tool_advertising_core: Some(vec!["read_file".to_string(), "bash".to_string()]),
..Default::default()
};
let config = builder.apply_profile(&profile).build();
match &config.tool_advertising {
ToolAdvertising::Deferred { core } => {
assert_eq!(core, &vec!["read_file".to_string(), "bash".to_string()])
}
ToolAdvertising::Full => panic!("mode must not reset to Full when only _core is set"),
}
// Mode = "deferred" set with no `_core`: must keep the existing
// core list, not wipe it to empty.
let builder2 = ConfigBuilder::default().tool_advertising(ToolAdvertising::Deferred {
core: vec!["bash".to_string()],
});
let profile2 = ConfigProfile {
tool_advertising: Some("deferred".to_string()),
..Default::default()
};
let config2 = builder2.apply_profile(&profile2).build();
match &config2.tool_advertising {
ToolAdvertising::Deferred { core } => assert_eq!(core, &vec!["bash".to_string()]),
ToolAdvertising::Full => panic!("expected Deferred to survive"),
}
}
/// Tables merge key-wise (§3.3): applying a profile with one
/// `tool_overrides` entry must not blow away a different tool's
/// override already on the builder.
#[test]
fn apply_profile_merges_tool_overrides_key_wise() {
let builder = ConfigBuilder::default().disable_tool("bash");
let mut overrides = HashMap::new();
overrides.insert(
"read_file".to_string(),
ToolOverrideProfile {
enabled: Some(false),
description: None,
schema_tier: None,
timeout_secs: None,
},
);
let profile = ConfigProfile {
tool_overrides: Some(overrides),
..Default::default()
};
let config = builder.apply_profile(&profile).build();
assert!(!config.tool_enabled("bash"));
assert!(!config.tool_enabled("read_file"));
}
// -----------------------------------------------------------------
// P4: deny-rule PATTERNS generalizing auto_approved_tools (§5.2 "P4").
// -----------------------------------------------------------------
#[test]
fn glob_match_exact_and_wildcard_forms() {
assert!(glob_match("bash", "bash"));
assert!(!glob_match("bash", "bash2"));
assert!(glob_match("bash*", "bash"));
assert!(glob_match("bash*", "bash_tool"));
assert!(!glob_match("bash*", "not_bash"));
assert!(glob_match("*_write", "edit_write"));
assert!(!glob_match("*_write", "write_edit"));
assert!(glob_match("mcp__*__search", "mcp__github__search"));
assert!(glob_match("*", "anything at all"));
assert!(glob_match("*", ""));
assert!(glob_match("", ""));
assert!(!glob_match("", "x"));
// Multiple `*`s in one pattern (the iterative two-pointer rewrite's
// main new surface area vs. the old single-recursion-site matcher).
assert!(glob_match("*a*a*a*", "aaaa"));
assert!(glob_match("*a*b*c*", "xaxbxcx"));
assert!(!glob_match("*a*b*c*", "xbxax"));
assert!(glob_match("a*b*c", "aXbXc"));
assert!(glob_match("a*b*c", "abc"));
assert!(!glob_match("a*b*c", "acb"));
}
/// LOW-2 (Fable-5 P4a review): `tool_deny_patterns`/`tool_allow_patterns`
/// can be project-controlled (a project may only ADD to `rules.deny`,
/// never replace it — see `configfile::merge_permissions_capability` —
/// but an ADDED pattern is still attacker-chosen content), so a crafted
/// pattern must not be able to make `glob_match` itself a self-DoS on
/// every tool call. The old naive recursive matcher
/// (`Some(b'*') => inner(&p[1..], t) || (!t.is_empty() &&
/// inner(p, &t[1..]))`) backtracks exponentially on a pattern with many
/// `*`s against a text with no matching suffix; this proves the
/// iterative rewrite returns promptly on exactly that shape.
#[test]
fn glob_match_pathological_pattern_returns_promptly() {
let pattern = "*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*b";
let text = "a".repeat(40);
let start = std::time::Instant::now();
let result = glob_match(pattern, &text);
let elapsed = start.elapsed();
assert!(!result, "text has no trailing 'b', so this must not match");
assert!(
elapsed < std::time::Duration::from_millis(200),
"glob_match took {elapsed:?} on a pathological pattern — exponential backtracking regressed"
);
}
/// Default-off: empty deny/allow patterns leave `needs_approval`
/// byte-identical to pre-P4 behavior (the existing `auto_approved_tools`
/// contract, unaffected).
#[test]
fn needs_approval_default_unaffected_by_empty_patterns() {
let config = Config::builder()
.approval(ApprovalPolicy::OnRequest)
.auto_approve_tool("read_file")
.build();
assert!(config.tool_deny_patterns.is_empty());
assert!(config.tool_allow_patterns.is_empty());
assert!(!config.needs_approval("read_file"));
assert!(config.needs_approval("bash"));
}
/// Happy path: a deny pattern forces approval even under
/// `ApprovalPolicy::Never` — the entire point of a deny rule is a hard
/// floor `--yes`/`Never` can't bypass.
#[test]
fn needs_approval_deny_pattern_forces_approval_even_under_never() {
let config = Config::builder()
.approval(ApprovalPolicy::Never)
.deny_tool_pattern("bash*")
.build();
assert!(config.needs_approval("bash"));
assert!(config.needs_approval("bash_tool"));
// A non-matching tool is unaffected — still `Never`.
assert!(!config.needs_approval("read_file"));
}
/// Happy path: an allow pattern exempts a matching tool from approval
/// under `OnRequest`, exactly like an exact `auto_approved_tools` entry.
#[test]
fn needs_approval_allow_pattern_exempts_under_on_request() {
let config = Config::builder()
.approval(ApprovalPolicy::OnRequest)
.allow_tool_pattern("read_*")
.build();
assert!(!config.needs_approval("read_file"));
assert!(!config.needs_approval("read_dir"));
assert!(config.needs_approval("bash"));
}
/// Deny wins over allow when a tool matches both — deny is checked
/// first and returns unconditionally.
#[test]
fn needs_approval_deny_wins_over_allow_on_the_same_tool() {
let config = Config::builder()
.approval(ApprovalPolicy::OnRequest)
.allow_tool_pattern("bash*")
.deny_tool_pattern("bash*")
.build();
assert!(config.needs_approval("bash"));
}
/// An allow pattern never exempts anything under `Untrusted` — same
/// scoping `auto_approved_tools` already has (only consulted under
/// `OnRequest`).
#[test]
fn needs_approval_allow_pattern_never_exempts_under_untrusted() {
let config = Config::builder()
.approval(ApprovalPolicy::Untrusted)
.allow_tool_pattern("*")
.build();
assert!(config.needs_approval("read_file"));
}
// ---- P4b: default-off / unchanged-unless-set for every new field -----
#[test]
fn p4b_defaults_are_byte_identical_to_pre_p4b_behavior() {
let config = Config::default();
assert!(!config.env_context);
assert_eq!(config.project_root_markers, vec![".git".to_string()]);
assert_eq!(config.project_doc_max_bytes, None);
assert!(!config.instruction_imports);
// retry_enabled defaults TRUE (matches the pre-existing always-on
// transport retry — see `provider::HttpOptions::from_retry_config`),
// but the override knobs default unset, so the transport sees its
// own untouched built-in defaults.
assert!(config.retry_enabled);
assert_eq!(config.retry_max_retries, None);
assert_eq!(config.retry_base_delay_ms, None);
assert_eq!(config.compaction_reserve_tokens, None);
assert_eq!(config.compaction_keep_recent_tokens, None);
assert_eq!(config.compaction_focus_instructions, None);
assert!(!config.auto_title);
assert_eq!(config.steering_mode, SteeringMode::OneAtATime);
assert_eq!(config.follow_up_mode, SteeringMode::OneAtATime);
assert!(config.stop_gate.is_none());
}
#[test]
fn apply_profile_applies_every_new_p4b_field() {
let profile = ConfigProfile {
env_context: Some(true),
project_root_markers: Some(vec![".hg".to_string()]),
project_doc_max_bytes: Some(16_384),
instruction_imports: Some(true),
retry_enabled: Some(false),
retry_max_retries: Some(9),
retry_base_delay_ms: Some(750),
compaction_reserve_tokens: Some(8_000),
compaction_keep_recent_tokens: Some(12_000),
compaction_focus_instructions: Some("keep fixing the auth bug".to_string()),
auto_title: Some(true),
steering_mode: Some("all".to_string()),
follow_up_mode: Some("one-at-a-time".to_string()),
..Default::default()
};
let config = ConfigBuilder::default().apply_profile(&profile).build();
assert!(config.env_context);
assert_eq!(config.project_root_markers, vec![".hg".to_string()]);
assert_eq!(config.project_doc_max_bytes, Some(16_384));
assert!(config.instruction_imports);
assert!(!config.retry_enabled);
assert_eq!(config.retry_max_retries, Some(9));
assert_eq!(config.retry_base_delay_ms, Some(750));
assert_eq!(config.compaction_reserve_tokens, Some(8_000));
assert_eq!(config.compaction_keep_recent_tokens, Some(12_000));
assert_eq!(
config.compaction_focus_instructions.as_deref(),
Some("keep fixing the auth bug")
);
assert!(config.auto_title);
assert_eq!(config.steering_mode, SteeringMode::All);
assert_eq!(config.follow_up_mode, SteeringMode::OneAtATime);
}
#[test]
fn apply_profile_unrecognized_steering_mode_is_ignored_not_defaulted_wrongly() {
let profile = ConfigProfile {
steering_mode: Some("bogus".to_string()),
..Default::default()
};
let config = ConfigBuilder::default().apply_profile(&profile).build();
// Fail safe: an unrecognized value leaves the built-in default in
// place rather than panicking or guessing.
assert_eq!(config.steering_mode, SteeringMode::OneAtATime);
}
// ---- P4c: default-off / unchanged-unless-set for every new field -----
#[test]
fn p4c_defaults_are_byte_identical_to_pre_p4c_behavior() {
let config = Config::default();
assert!(!config.read_file_multimodal);
assert!(!config.edit_file_require_read_before_edit);
assert!(!config.edit_file_notebook_aware);
assert!(!config.shell_env_snapshot);
assert_eq!(config.doom_loop_threshold, None);
assert!(!config.nested_instructions);
assert!(!config.model_switch_allow_switch);
}
#[test]
fn apply_profile_applies_every_new_p4c_field() {
let profile = ConfigProfile {
read_file_multimodal: Some(true),
edit_file_require_read_before_edit: Some(true),
edit_file_notebook_aware: Some(true),
shell_env_snapshot: Some(true),
doom_loop_threshold: Some(3),
nested_instructions: Some(true),
model_switch_allow_switch: Some(true),
..Default::default()
};
let config = ConfigBuilder::default().apply_profile(&profile).build();
assert!(config.read_file_multimodal);
assert!(config.edit_file_require_read_before_edit);
assert!(config.edit_file_notebook_aware);
assert!(config.shell_env_snapshot);
assert_eq!(config.doom_loop_threshold, Some(3));
assert!(config.nested_instructions);
assert!(config.model_switch_allow_switch);
}
#[test]
fn builder_methods_set_every_new_p4c_field() {
let config = Config::builder()
.read_file_multimodal(true)
.edit_file_require_read_before_edit(true)
.edit_file_notebook_aware(true)
.shell_env_snapshot(true)
.doom_loop_threshold(5)
.nested_instructions(true)
.model_switch_allow_switch(true)
.build();
assert!(config.read_file_multimodal);
assert!(config.edit_file_require_read_before_edit);
assert!(config.edit_file_notebook_aware);
assert!(config.shell_env_snapshot);
assert_eq!(config.doom_loop_threshold, Some(5));
assert!(config.nested_instructions);
assert!(config.model_switch_allow_switch);
}
}