aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::fs;
use std::io::{self, Read, Write};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use htmd::{
    element_handler::{HandlerResult, Handlers},
    Element, HtmlToMarkdown,
};
use markup5ever_rcdom::{Node, NodeData};
use reqwest::blocking::{Client, Response as HttpResponse};
use reqwest::header::{
    ACCEPT, ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_TYPE, LOCATION, USER_AGENT,
};
use reqwest::redirect::Policy;
use secret_rules::audit::{AuditReason, AuditRecordV1, Decision};
use secret_rules::location::{
    evaluate_request_with_connect, location_kind_token, LabelOutcome, LabelRule, Location,
    RequestView,
};
use secret_rules::material::{check_admissible, encode_for_location};
use secret_rules::scrub::{MatcherSet, ScrubError, Scrubber};
use secret_rules::target::{normalize_request_target, ConnectAuthority};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use url::Url;
use zeroize::Zeroizing;

use crate::lang_id::language_by_extension;

#[path = "url_fetch_sensitive.rs"]
#[cfg(not(any(test, feature = "test-support")))]
mod sensitive;
#[path = "url_fetch_sensitive.rs"]
#[cfg(any(test, feature = "test-support"))]
pub mod sensitive;

const MAX_RESPONSE_BYTES: u64 = 8 * 1024 * 1024;
const CACHE_TTL_MS: u64 = 24 * 60 * 60 * 1000;
/// Longest a request may take to set up its connection (name lookup, TCP
/// and TLS), within the fetch deadline.
const CONNECT_TIMEOUT: Duration = Duration::from_millis(10_000);
/// Longest a request may wait for the response headers, counted from the
/// start of the request, within the fetch deadline. reqwest applies the same
/// limit to each later read of the body.
const HEADERS_TIMEOUT: Duration = Duration::from_millis(15_000);
const BODY_CHUNK_TIMEOUT: Duration = Duration::from_millis(15_000);
const MAX_REDIRECTS: usize = 5;

/// Longest one URL fetch may take, whatever budget the call has left. Every
/// phase (name lookup, connect, response headers, body) shares this one
/// deadline, so redirects and retries cannot multiply it.
const URL_FETCH_CEILING: Duration = Duration::from_secs(20);
/// The last part of the call's budget, kept for building and sending the
/// reply. Neither the download nor reading the downloaded document back may
/// use it, so the reply reaches the caller before the call's own deadline.
pub const URL_REPLY_MARGIN: Duration = Duration::from_secs(1);
/// The part of the call's budget before the reply margin that the download
/// leaves for the work after it: converting HTML, writing the cache, and
/// reading the document back. A download that ends at its deadline still has
/// this much time for that work.
const URL_READ_BACK_RESERVE: Duration = Duration::from_secs(2);
/// The part of the read-back reserve a placeholder fetch's final residual
/// key check may use, counted from the end of the download deadline. The
/// rest stays for writing and reading the document back.
const RESIDUAL_CHECK_RESERVE: Duration = Duration::from_millis(1500);
/// A transient failure is retried only when the backoff plus at least this
/// much time for the next attempt still fit before the fetch deadline.
const MIN_USEFUL_ATTEMPT: Duration = Duration::from_secs(1);

/// Retry budget for transient connect/transport failures only. Agents
/// shouldn't have to retry manually for a single TCP/TLS hiccup. We cap
/// at 2 retries (= 3 total attempts) with short jittered backoff so a
/// genuinely-broken host fails fast instead of dragging the foreground
/// fetch out to many seconds.
///
/// We deliberately do NOT retry on:
///   - HTTP error status (4xx/5xx) — the server actually answered
///   - Redirect errors / SSRF rejections — those are deterministic
///   - Body read stalls — already handled by BODY_CHUNK_TIMEOUT
const TRANSIENT_RETRY_ATTEMPTS: usize = 2;
const TRANSIENT_RETRY_BACKOFFS_MS: [u64; TRANSIENT_RETRY_ATTEMPTS] = [200, 600];
const ACCEPT_HEADER: &str = "application/vnd.github.raw, text/markdown, text/x-markdown, text/html;q=0.9, application/json;q=0.8, text/plain;q=0.5";
const USER_AGENT_VALUE: &str = "aft-opencode-plugin";
const CONVERTED_MARKDOWN_CONTENT_TYPE: &str = "text/markdown; charset=utf-8";

#[derive(Clone, Default)]
pub struct UrlFetchOptions {
    pub allow_private: bool,
    /// Test hook: treat a hostname as resolving to these IPs during SSRF validation.
    /// Production callers leave this empty and use `std::net::ToSocketAddrs`.
    #[doc(hidden)]
    pub public_host_overrides: Vec<(String, Vec<IpAddr>)>,
    /// Test hook: force reqwest to connect a hostname to a local mock server while
    /// SSRF validation still sees `public_host_overrides` above.
    #[doc(hidden)]
    pub connect_overrides: Vec<(String, SocketAddr)>,
    /// Test hook: observes the temp path immediately before the atomic rename.
    #[doc(hidden)]
    pub atomic_write_observer: Option<Arc<dyn Fn(&Path, &Path) + Send + Sync>>,
    /// Test hook: answers host name lookups in place of the system resolver,
    /// so a test can stall or redirect name resolution without a network.
    #[doc(hidden)]
    pub lookup_override: Option<HostLookup>,
    /// Test hook: holds every connection attempt this long before it starts
    /// connecting, standing in for a host that does not answer the connect.
    #[doc(hidden)]
    pub connect_delay: Option<Duration>,
    /// Test hook: the TLS configuration to use instead of the platform
    /// verifier, so a test can trust a local HTTPS server's certificate.
    #[doc(hidden)]
    pub tls_config: Option<rustls::ClientConfig>,
    #[cfg(all(unix, any(test, feature = "test-support")))]
    #[doc(hidden)]
    pub reply_clock_for_test: Option<ReplyClock>,
}

#[cfg(all(unix, any(test, feature = "test-support")))]
type ReplyClock = Arc<dyn Fn() -> Instant + Send + Sync>;

/// A host name lookup: the host's addresses, or the lookup's error.
pub type HostLookup = Arc<dyn Fn(&str) -> io::Result<Vec<IpAddr>> + Send + Sync>;

/// The part of a fetch that was running when its deadline or a stall limit
/// stopped it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FetchPhase {
    Dns,
    Connect,
    Headers,
    Body,
}

impl FetchPhase {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Dns => "dns",
            Self::Connect => "connect",
            Self::Headers => "headers",
            Self::Body => "body",
        }
    }
}

#[derive(Debug, Clone)]
pub struct UrlFetchError {
    code: &'static str,
    message: String,
    phase: Option<FetchPhase>,
    /// HTTP status of a server that answered with an error.
    status: Option<u16>,
    /// Set on a remembered failure: how long until a call fetches again.
    retry_after: Option<Duration>,
    /// Set when the fetch stopped (or never started) only because the
    /// calling tool call had too little budget left. Such a failure says
    /// nothing about the server, so it is never remembered.
    cut_by_call_budget: bool,
}

impl UrlFetchError {
    fn new(message: impl Into<String>) -> Self {
        Self {
            code: "url_fetch_failed",
            message: message.into(),
            phase: None,
            status: None,
            retry_after: None,
            cut_by_call_budget: false,
        }
    }

    fn timeout(phase: FetchPhase, message: impl Into<String>) -> Self {
        Self {
            code: "url_fetch_timeout",
            phase: Some(phase),
            ..Self::new(message)
        }
    }

    /// A placeholder fetch refused by its secret rules or the vault, with the
    /// secret reply code (`secret_refused`, `secrets_unavailable`, ...).
    fn secret(code: &'static str, message: impl Into<String>) -> Self {
        Self {
            code,
            ..Self::new(message)
        }
    }

    /// This error reworded for a refusal that came after a request carrying a
    /// key was sent; any other error is returned unchanged.
    fn after_secret_sent(mut self) -> Self {
        if let Some(rest) = self.message.strip_prefix(SECRET_FETCH_REFUSED) {
            self.message = format!("{SECRET_FETCH_REFUSED_AFTER_SEND}{rest}");
        }
        self
    }

    fn http_status(status: u16, message: impl Into<String>) -> Self {
        Self {
            status: Some(status),
            ..Self::new(message)
        }
    }

    /// Response error code: `url_fetch_timeout` when a deadline or stall
    /// limit stopped the fetch, otherwise `url_fetch_failed`.
    pub fn code(&self) -> &'static str {
        self.code
    }

    /// The phase a timed-out fetch was in; `None` for other failures.
    pub fn phase(&self) -> Option<FetchPhase> {
        self.phase
    }

    /// For a failure repeated from memory instead of a new fetch, the time
    /// until a call for the same URL fetches it again.
    pub fn retry_after(&self) -> Option<Duration> {
        self.retry_after
    }

    /// Failures that would very likely repeat on an immediate retry, and
    /// cost the retry the same wait: timeouts, server errors (5xx), and
    /// client errors (4xx) other than 408 Request Timeout and 429 Too Many
    /// Requests. Refusals by the SSRF check and other local errors are cheap
    /// to reproduce and are not remembered.
    ///
    /// Only failures the server or network caused are remembered: a timeout
    /// cut short by the caller's budget is not, and neither is a failure
    /// that is itself being repeated from memory.
    fn worth_remembering(&self) -> bool {
        if self.cut_by_call_budget || self.retry_after.is_some() {
            return false;
        }
        self.code == "url_fetch_timeout"
            || self
                .status
                .is_some_and(|status| status >= 400 && status != 408 && status != 429)
    }
}

/// One deadline for a whole fetch, taken from the call's filesystem budget
/// (less the read-back reserve and the reply margin) and capped at
/// [`URL_FETCH_CEILING`]. A call with no budget gets the ceiling.
#[derive(Debug, Clone, Copy)]
struct FetchDeadline {
    at: Instant,
    allowed: Duration,
    /// The call's budget, not the URL ceiling, set this deadline: a fetch it
    /// stops was stopped by the caller, not by a slow server.
    set_by_call: bool,
}

impl FetchDeadline {
    fn for_current_call() -> Self {
        let now = Instant::now();
        let ceiling = now + URL_FETCH_CEILING;
        let at = match crate::bounded_io::current() {
            Some(budget) => budget
                .deadline
                .checked_sub(URL_REPLY_MARGIN + URL_READ_BACK_RESERVE)
                .unwrap_or(now)
                .clamp(now, ceiling),
            None => ceiling,
        };
        Self {
            at,
            allowed: at.saturating_duration_since(now),
            set_by_call: at < ceiling,
        }
    }

    fn remaining(&self) -> Duration {
        self.at.saturating_duration_since(Instant::now())
    }

    fn expired(&self) -> bool {
        self.remaining().is_zero()
    }

    fn timeout_error(&self, phase: FetchPhase, url: &str) -> UrlFetchError {
        UrlFetchError {
            cut_by_call_budget: self.set_by_call,
            ..UrlFetchError::timeout(
                phase,
                format!(
                    "URL fetch timed out in the {} phase: the {}ms fetch deadline elapsed fetching {url}",
                    phase.as_str(),
                    self.allowed.as_millis()
                ),
            )
        }
    }
}

impl fmt::Display for UrlFetchError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for UrlFetchError {}

#[derive(Debug, Serialize, Deserialize)]
struct CacheMeta {
    url: String,
    #[serde(rename = "contentType")]
    content_type: String,
    extension: String,
    #[serde(rename = "fetchedAt")]
    fetched_at: u64,
    #[serde(default)]
    download_truncated: bool,
    #[serde(default)]
    downloaded_bytes: usize,
    #[serde(default)]
    total_bytes: Option<u64>,
}

pub fn is_http_url(value: &str) -> bool {
    value.starts_with("http://") || value.starts_with("https://")
}

/// Fetch `url` into the URL cache under `storage_dir` and return the cached
/// document's path. A failure worth remembering (see
/// [`UrlFetchError::worth_remembering`]) is repeated for
/// [`FAILURE_MEMORY`] instead of a new fetch, so an agent that retries a
/// page the server failed gets its answer at once instead of waiting again.
/// A document already in the cache is served regardless.
pub fn fetch_url_to_cache(
    url: &str,
    storage_dir: &Path,
    options: UrlFetchOptions,
) -> Result<PathBuf, UrlFetchError> {
    let key = FailureKey::new(storage_dir, url, options.allow_private);
    let result = download_to_cache(url, storage_dir, options, &key);
    record_fetch(&result);
    match &result {
        Ok(_) => forget_failure(&key),
        Err(error) if error.worth_remembering() => remember_failure(key, error),
        Err(_) => {}
    }
    result
}

/// Count one document asked for in the call's fetch times, with its error.
fn record_fetch<T>(result: &Result<T, UrlFetchError>) {
    timing::record(|times| {
        times.fetches += 1;
        if let Err(error) = result {
            times.error = Some((error.code(), error.phase()));
        }
    });
}

/// How long a remembered failure stands in for a new fetch of its URL.
const FAILURE_MEMORY: Duration = Duration::from_secs(60);

/// A remembered failure is specific to the cache it would have filled and to
/// whether private addresses were allowed.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct FailureKey {
    storage_dir: PathBuf,
    url: String,
    allow_private: bool,
}

impl FailureKey {
    fn new(storage_dir: &Path, url: &str, allow_private: bool) -> Self {
        Self {
            storage_dir: storage_dir.to_path_buf(),
            url: url.to_string(),
            allow_private,
        }
    }
}

struct RememberedFailure {
    error: UrlFetchError,
    at: Instant,
}

/// Remembered failures. Expired entries are dropped on every insert, and a
/// lookup ignores an entry older than [`FAILURE_MEMORY`].
fn failure_memory() -> &'static std::sync::Mutex<HashMap<FailureKey, RememberedFailure>> {
    static FAILURES: std::sync::OnceLock<std::sync::Mutex<HashMap<FailureKey, RememberedFailure>>> =
        std::sync::OnceLock::new();
    FAILURES.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
}

fn remembered_failure(key: &FailureKey) -> Option<UrlFetchError> {
    let failures = failure_memory()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let remembered = failures.get(key)?;
    let age = remembered.at.elapsed();
    let retry_after = FAILURE_MEMORY
        .checked_sub(age)
        .filter(|left| !left.is_zero())?;
    let mut error = remembered.error.clone();
    error.message = format!(
        "{} (cached failure from {}s ago; this URL is fetched again after {}s)",
        error.message,
        age.as_secs(),
        retry_after.as_secs_f64().ceil() as u64
    );
    error.retry_after = Some(retry_after);
    Some(error)
}

fn remember_failure(key: FailureKey, error: &UrlFetchError) {
    let mut failures = failure_memory()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    failures.retain(|_, remembered| remembered.at.elapsed() < FAILURE_MEMORY);
    failures.insert(
        key,
        RememberedFailure {
            error: error.clone(),
            at: Instant::now(),
        },
    );
}

fn forget_failure(key: &FailureKey) {
    failure_memory()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .remove(key);
}

/// Test hook: a document-cache read under `storage_dir` that blocks until
/// released (or for at most 10 s, so a broken test cannot hang the suite),
/// standing in for a cache filesystem that stops answering.
#[cfg(any(test, feature = "test-support"))]
#[derive(Default)]
struct CacheReadStall {
    reached: std::sync::atomic::AtomicUsize,
    released: std::sync::Mutex<bool>,
    release: std::sync::Condvar,
}

#[cfg(any(test, feature = "test-support"))]
impl CacheReadStall {
    #[cfg_attr(not(test), allow(dead_code))]
    fn release(&self) {
        *self.released.lock().unwrap() = true;
        self.release.notify_all();
    }
}

#[cfg(any(test, feature = "test-support"))]
fn cache_read_stalls() -> &'static std::sync::Mutex<HashMap<PathBuf, Arc<CacheReadStall>>> {
    static STALLS: std::sync::OnceLock<std::sync::Mutex<HashMap<PathBuf, Arc<CacheReadStall>>>> =
        std::sync::OnceLock::new();
    STALLS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
}

#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code))]
fn stall_cache_reads(storage_dir: &Path) -> Arc<CacheReadStall> {
    let stall = Arc::new(CacheReadStall::default());
    cache_read_stalls()
        .lock()
        .unwrap()
        .insert(storage_dir.to_path_buf(), Arc::clone(&stall));
    stall
}

#[cfg(any(test, feature = "test-support"))]
fn stall_cache_read_if_requested(storage_dir: &Path) {
    let Some(stall) = cache_read_stalls()
        .lock()
        .unwrap()
        .get(storage_dir)
        .cloned()
    else {
        return;
    };
    stall
        .reached
        .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    let released = stall.released.lock().unwrap();
    let _ = stall
        .release
        .wait_timeout_while(released, Duration::from_secs(10), |released| !*released);
}

/// Test hook: make one remembered failure `by` older.
#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code))]
fn age_remembered_failure(key: &FailureKey, by: Duration) {
    if let Some(remembered) = failure_memory()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .get_mut(key)
    {
        remembered.at = remembered
            .at
            .checked_sub(by)
            .expect("clock far enough along");
    }
}

/// What a document-cache check needs, owned so a helper thread can run it.
struct CacheCheckInput {
    storage_dir: PathBuf,
    hash: String,
    meta_file: PathBuf,
    url: Url,
}

type CacheCheckResult = Result<Option<PathBuf>, UrlFetchError>;

/// A document-cache check running on a helper thread. Calls that find one
/// running for their URL wait for it instead of starting another, so a cache
/// filesystem that stops answering holds at most one thread per URL.
#[derive(Default)]
struct CacheCheck {
    result: std::sync::Mutex<Option<CacheCheckResult>>,
    done: std::sync::Condvar,
}

fn cache_checks() -> &'static std::sync::Mutex<HashMap<FailureKey, Arc<CacheCheck>>> {
    static CHECKS: std::sync::OnceLock<std::sync::Mutex<HashMap<FailureKey, Arc<CacheCheck>>>> =
        std::sync::OnceLock::new();
    CHECKS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
}

/// The latest a bounded cache check may answer: the call's deadline less the
/// reply margin, or the URL ceiling for a call without a budget.
fn cache_check_deadline() -> Instant {
    let now = Instant::now();
    let ceiling = now + URL_FETCH_CEILING;
    match crate::bounded_io::current() {
        Some(budget) => budget
            .deadline
            .checked_sub(URL_REPLY_MARGIN)
            .unwrap_or(now)
            .clamp(now, ceiling),
        None => ceiling,
    }
}

/// Run (or join) the document-cache check for `key` and wait for it until
/// `deadline`. `Ok(None)` means no usable cached copy, including a check
/// that did not finish in time.
fn bounded_cache_check(
    key: &FailureKey,
    input: CacheCheckInput,
    deadline: Instant,
) -> CacheCheckResult {
    let check = {
        let mut checks = cache_checks()
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        match checks.get(key) {
            Some(running) => Arc::clone(running),
            None => {
                let check = Arc::new(CacheCheck::default());
                checks.insert(key.clone(), Arc::clone(&check));
                let worker = Arc::clone(&check);
                let worker_key = key.clone();
                thread::spawn(move || {
                    let result = fresh_cached_path(
                        &input.storage_dir,
                        &input.hash,
                        &input.meta_file,
                        &input.url,
                    );
                    *worker
                        .result
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(result);
                    worker.done.notify_all();
                    cache_checks()
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .remove(&worker_key);
                });
                check
            }
        }
    };
    let mut result = check
        .result
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    loop {
        if let Some(result) = result.as_ref() {
            return result.clone();
        }
        let left = deadline.saturating_duration_since(Instant::now());
        if left.is_zero() {
            return Ok(None);
        }
        result = check
            .done
            .wait_timeout(result, left)
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .0;
    }
}

/// A document that is cached is served (after the SSRF check) even while a
/// failure of the same URL is remembered; only a cache miss is answered by a
/// remembered failure. With a failure remembered, the call waits for the
/// cache check only until its deadline less the reply margin; a check still
/// running then counts as a miss, and its helper thread may run on.
fn download_to_cache(
    url: &str,
    storage_dir: &Path,
    options: UrlFetchOptions,
    failure_key: &FailureKey,
) -> Result<PathBuf, UrlFetchError> {
    let parsed = Url::parse(url).map_err(|_| UrlFetchError::new(format!("Invalid URL: {url}")))?;
    let deadline = FetchDeadline::for_current_call();
    let fetch_url = rewrite_url_for_fetch(&parsed);
    let approved = Arc::new(ApprovedHosts::default());
    let hash = hash_url(url);
    let meta_file = meta_path(storage_dir, &hash);

    // With a failure remembered, the answer is already in memory, so the call
    // must not wait on the cache check past its deadline; the check runs on
    // a helper thread that may outlive the call. No directory is created:
    // nothing will be written.
    if let Some(remembered) = remembered_failure(failure_key) {
        let check = CacheCheckInput {
            storage_dir: storage_dir.to_path_buf(),
            hash,
            meta_file,
            url: fetch_url.clone(),
        };
        let Some(cached) = bounded_cache_check(failure_key, check, cache_check_deadline())? else {
            timing::record(|times| times.remembered_failures += 1);
            return Err(remembered);
        };
        validate_public_url(&fetch_url, &options, &deadline, &approved)?;
        timing::record(|times| times.cache_hits += 1);
        return Ok(cached);
    }

    let dir = cache_dir(storage_dir);
    crate::private_storage::open_dir(storage_dir, &dir).map_err(|error| {
        UrlFetchError::new(format!(
            "Failed to create URL cache directory {}: {error}",
            dir.display()
        ))
    })?;

    let cached = fresh_cached_path(storage_dir, &hash, &meta_file, &fetch_url)?;
    // A cache hit is checked too: the request may refuse private addresses
    // that the call which filled the cache allowed.
    validate_public_url(&fetch_url, &options, &deadline, &approved)?;
    if let Some(cached) = cached {
        timing::record(|times| times.cache_hits += 1);
        return Ok(cached);
    }

    let response = fetch_with_redirects(&fetch_url, url, &options, &deadline, approved)?;
    if !response.status().is_success() {
        return Err(UrlFetchError::http_status(
            response.status().as_u16(),
            format!(
                "HTTP {} {} fetching {url}",
                response.status().as_u16(),
                response.status().canonical_reason().unwrap_or("")
            ),
        ));
    }

    let content_type = response
        .headers()
        .get(CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .unwrap_or("text/plain")
        .to_string();
    let (extension, from_source_path) =
        resolve_fetch_extension(&fetch_url, &content_type).ok_or_else(|| {
            UrlFetchError::new(format!(
                "Unsupported content type '{content_type}' for {url}. Supported: text/html, text/markdown, application/json, text/plain; source files via URL path extension (e.g. .rs, .ts, .mjs)"
            ))
        })?;

    let total_bytes = response.content_length();
    let (mut body, download_truncated) = read_response_body(response, url, &deadline)?;
    let downloaded_bytes = body.len();
    // A byte ceiling can bisect the final UTF-8 character. Do not turn an
    // otherwise valid document prefix into an unreadable cache entry.
    if download_truncated {
        if let Err(error) = std::str::from_utf8(&body) {
            if error.error_len().is_none() {
                body.truncate(error.valid_up_to());
            }
        }
    }
    if from_source_path && body_contains_nul_in_prefix(&body) {
        return Err(UrlFetchError::new(format!(
            "Binary content detected for source URL {url}"
        )));
    }
    let (body, content_type, extension) = if extension == ".html" {
        (
            convert_html_body_to_markdown(&body, url)?,
            CONVERTED_MARKDOWN_CONTENT_TYPE.to_string(),
            ".md",
        )
    } else {
        (body, content_type, extension)
    };

    let content_file = content_path(storage_dir, &hash, extension);
    atomic_write(&content_file, &body, &options)?;

    let meta = CacheMeta {
        url: url.to_string(),
        content_type,
        extension: extension.to_string(),
        fetched_at: now_ms(),
        download_truncated,
        downloaded_bytes,
        total_bytes,
    };
    let meta_bytes = serde_json::to_vec(&meta).map_err(|error| {
        UrlFetchError::new(format!("Failed to encode URL cache metadata: {error}"))
    })?;
    atomic_write(&meta_file, &meta_bytes, &options)?;

    Ok(content_file)
}

/// The fresh cached copy of `url` under `storage_dir`, if there is one. Reads
/// only: it creates no folder, writes nothing and downloads nothing. The cache
/// check is bounded by the call's deadline like a remembered failure's (a
/// stalled cache drive counts as a miss), and a cached copy passes the same
/// scheme and private-address checks as a download before it is served.
pub fn cached_url_document(
    url: &str,
    storage_dir: &Path,
    options: &UrlFetchOptions,
) -> Result<Option<PathBuf>, UrlFetchError> {
    let parsed = Url::parse(url).map_err(|_| UrlFetchError::new(format!("Invalid URL: {url}")))?;
    let deadline = FetchDeadline::for_current_call();
    let fetch_url = rewrite_url_for_fetch(&parsed);
    let hash = hash_url(url);
    let check = CacheCheckInput {
        storage_dir: storage_dir.to_path_buf(),
        meta_file: meta_path(storage_dir, &hash),
        hash,
        url: fetch_url.clone(),
    };
    let key = FailureKey::new(storage_dir, url, options.allow_private);
    let Some(cached) = bounded_cache_check(&key, check, cache_check_deadline())? else {
        return Ok(None);
    };
    validate_public_url(&fetch_url, options, &deadline, &ApprovedHosts::default())?;
    timing::record(|times| times.cache_hits += 1);
    Ok(Some(cached))
}

/// Folder, under the cache root, that holds the private per-call folders of
/// placeholder fetches. It is a sibling of the URL cache, never inside it.
pub const SECRET_FETCH_DIR: &str = "url_secret_fetch";

/// The start of every refusal a placeholder fetch makes on its own (as opposed
/// to a refusal the vault decided) before any request carrying a key was sent.
/// One constant so the wording is reviewed once; the message goes on to name a
/// stable reason token and the URL as the agent wrote it, with the
/// placeholder and never a key.
pub const SECRET_FETCH_REFUSED: &str =
    "Secret placeholder fetch refused; no request carrying the secret was sent";

#[rustfmt::skip]
test_support_visibility! {
/// The start of the same refusals once a request carrying a key has been sent:
/// the response (or a later hop) was refused, so the claim above would be
/// false.
pub(crate) const SECRET_FETCH_REFUSED_AFTER_SEND: &str =
    "Secret placeholder fetch stopped after a request carrying the secret was sent; its response was not used";
}

/// A stand-in key used only to plan where a placeholder fetch would
/// substitute. Real vault bytes are asked for only once a rule matches.
const SECRET_PLANNING_KEY: &[u8] = b"url-fetch-planning-value-0000";

/// The most content codings a placeholder fetch decodes from one response.
const MAX_SECRET_CODINGS: usize = 4;

/// Every label of a well-formed placeholder in `url`, in order and without
/// repeats, or `None` when the URL mentions no placeholder at all.
///
/// A percent-encoded placeholder counts as well as a literal one, because a
/// query value is compared after decoding. `Some` with no labels means the URL
/// mentions the placeholder prefix only in a malformed way: such a URL still
/// takes the placeholder path (no cache, no web-view rewrite), it just has
/// nothing to substitute.
pub fn secret_labels_in_url(url: &str) -> Option<Vec<String>> {
    if !secret_rules::placeholder::contains_placeholder_prefix_loose(url) {
        return None;
    }
    let decoded = percent_decode_path_segment(url);
    let mut labels: Vec<String> = Vec::new();
    for text in [url, decoded.as_str()] {
        for placeholder in secret_rules::placeholder::scan(text) {
            if !labels.iter().any(|label| label == placeholder.label) {
                labels.push(placeholder.label.to_string());
            }
        }
    }
    Some(labels)
}

/// Create the private folder one placeholder fetch writes its document into,
/// under `storage_dir` but outside the URL cache. The caller owns the folder
/// and deletes it when its call returns.
pub fn create_secret_fetch_dir(storage_dir: &Path) -> Result<PathBuf, UrlFetchError> {
    let parent = storage_dir.join(SECRET_FETCH_DIR);
    let failed = |error: io::Error| {
        UrlFetchError::new(format!(
            "Failed to create a private folder for a placeholder fetch under {}: {error}",
            parent.display()
        ))
    };
    crate::private_storage::open_dir(storage_dir, &parent).map_err(failed)?;
    let dir = parent.join(random_nonce());
    // `create_dir` fails when the folder exists, so no other call shares it.
    crate::private_storage::create_dir(&dir).map_err(failed)?;
    Ok(dir)
}

/// What a placeholder fetch may do with its secrets.
pub struct SecretFetch {
    /// The vault each addressed request and audit record go to.
    pub vault: Arc<dyn crate::secret::SecretVault>,
    /// The call's authorization scope; `None` only when the URL holds no
    /// well-formed placeholder, in which case nothing is resolved or audited.
    pub authorization: Option<crate::secret::SecretScope>,
    /// Every label found in the URL, in order.
    pub labels: Vec<String>,
    /// Map an ephemeral test upstream to the vault's HTTPS/443 target.
    #[cfg(any(test, feature = "test-support"))]
    pub test_https_port: Option<u16>,
    /// The fetch call's id: audit records name it, plus the hop index.
    pub call_id: String,
    /// The foreground call's cancellation and absolute reply deadline.
    pub cancellation: SecretFetchCancellation,
}

impl SecretFetch {
    // Cargo feature unification can change test-only fields; keep the constructor signature fixed.
    pub fn new(
        vault: Arc<dyn crate::secret::SecretVault>,
        authorization: Option<crate::secret::SecretScope>,
        labels: Vec<String>,
        test_https_port: Option<u16>,
        call_id: String,
        cancellation: SecretFetchCancellation,
    ) -> Self {
        #[cfg(not(any(test, feature = "test-support")))]
        let _ = test_https_port;
        Self {
            vault,
            authorization,
            labels,
            #[cfg(any(test, feature = "test-support"))]
            test_https_port,
            call_id,
            cancellation,
        }
    }
}

#[derive(Clone, Default)]
pub struct SecretFetchCancellation {
    job: Option<crate::executor::JobCancellation>,
    deadline: Option<Instant>,
    #[cfg(all(unix, any(test, feature = "test-support")))]
    clock: Option<ReplyClock>,
}
impl SecretFetchCancellation {
    pub fn for_current_call(_options: &UrlFetchOptions) -> Self {
        Self {
            job: crate::executor::current_job_cancellation(),
            deadline: crate::secret::call_context::current_fetch_reply_deadline(),
            #[cfg(all(unix, any(test, feature = "test-support")))]
            clock: _options.reply_clock_for_test.clone(),
        }
    }
    fn now(&self) -> Instant {
        #[cfg(all(unix, any(test, feature = "test-support")))]
        if let Some(clock) = &self.clock {
            return clock();
        }
        Instant::now()
    }
    pub(crate) fn is_cancelled(&self) -> bool {
        self.reason().is_some()
    }
    pub(crate) fn reason(&self) -> Option<crate::secret::requests::UseError> {
        self.job
            .as_ref()
            .is_some_and(|job| job.cancel_requested_before_commit())
            .then_some(crate::secret::requests::UseError::Cancelled)
            .or_else(|| {
                self.deadline
                    .is_some_and(|at| self.now() >= at)
                    .then_some(crate::secret::requests::UseError::Expired)
            })
    }
    pub(crate) async fn cancelled(&self) {
        loop {
            if self.is_cancelled() {
                return;
            }
            let delay = self.deadline.map_or(Duration::from_millis(25), |deadline| {
                deadline
                    .saturating_duration_since(self.now())
                    .min(Duration::from_millis(25))
            });
            tokio::time::sleep(delay).await;
        }
    }
}

#[rustfmt::skip]
test_support_visibility! {
/// Keys the vault released during one placeholder fetch. They are kept, wiped
/// on drop, only until the fetch returns, so every header and body read after
/// a key was sent is scrubbed of it.
/// These retained bytes are scrub patterns, never authorization or material
/// for another send; every request obtains its own release from the vault.
#[derive(Default)]
pub(crate) struct HeldKeys(Vec<(String, Zeroizing<Vec<u8>>)>);
}

impl HeldKeys {
    fn matchers(&self) -> Result<Vec<MatcherSet>, ScrubError> {
        self.0
            .iter()
            .map(|(label, key)| MatcherSet::new(label, key))
            .collect()
    }

    #[rustfmt::skip]
    test_support_visibility! {

    /// Hold `key` for `label`, refusing a key whose matcher would collide with
    /// one already held (the scrubber could then write one key into a reply).
    pub(crate) fn hold(&mut self, label: &str, key: &[u8]) -> Result<(), ScrubError> {
        if self
            .0
            .iter()
            .any(|(held, bytes)| held == label && bytes.as_slice() == key)
        {
            return Ok(());
        }
        let mut matchers = self.matchers()?;
        matchers.push(MatcherSet::new(label, key)?);
        Scrubber::new(matchers)?;
        self.0
            .push((label.to_string(), Zeroizing::new(key.to_vec())));
        Ok(())
    }
    }

    /// `bytes` with every held key replaced by its label's placeholder.
    fn scrub(&self, bytes: &[u8]) -> Result<Vec<u8>, ScrubError> {
        let mut scrubber = Scrubber::new(self.matchers()?)?;
        let mut clean = scrubber.push(bytes);
        clean.extend_from_slice(&scrubber.finish());
        Ok(clean)
    }

    fn keys(&self) -> Vec<&[u8]> {
        self.0.iter().map(|(_, key)| key.as_slice()).collect()
    }

    /// Error text from a library (reqwest, the decoders) with every held key
    /// replaced by its placeholder. Text that still spells a key after that,
    /// or that cannot be scrubbed, is dropped whole.
    pub(crate) fn sanitize_detail(&self, detail: &str) -> String {
        let deadline = Instant::now() + DETAIL_CHECK_LIMIT;
        match self.scrub(detail.as_bytes()) {
            Ok(clean) if self.reveal(&clean, deadline).is_clean() => {
                String::from_utf8_lossy(&clean).into_owned()
            }
            _ => String::new(),
        }
    }

    /// Whether `bytes` still spell a held key, as they stand or after a URL
    /// parser or reader normalizes them, checked until `deadline` (see
    /// [`secret_rules::reveal_outcome`]).
    fn reveal(&self, bytes: &[u8], deadline: Instant) -> secret_rules::RevealOutcome {
        secret_rules::reveal_outcome(bytes, &self.keys(), Some(deadline))
    }
}

/// The longest the residual check of a library error's text may run; such
/// text is short, and text the check cannot clear in time is dropped.
const DETAIL_CHECK_LIMIT: Duration = Duration::from_millis(100);

/// Refuse unless the residual check found `bytes` clean: `found` names the
/// refusal when a key was spelled, and a check that could not finish refuses
/// as exhausted or timed out.
fn refuse_unless_clean(
    outcome: secret_rules::RevealOutcome,
    found: &str,
    url: &str,
) -> Result<(), UrlFetchError> {
    match outcome {
        secret_rules::RevealOutcome::Clean => Ok(()),
        secret_rules::RevealOutcome::Found => Err(secret_fetch_refused(found, url)),
        secret_rules::RevealOutcome::Exhausted => {
            Err(secret_fetch_refused("residual_check_exhausted", url))
        }
        secret_rules::RevealOutcome::OutOfTime => {
            Err(secret_fetch_refused("residual_check_timeout", url))
        }
    }
}

fn secret_fetch_refused(reason: &str, url: &str) -> UrlFetchError {
    UrlFetchError::secret(
        crate::secret::SECRET_REFUSED,
        format!("{SECRET_FETCH_REFUSED} ({reason}): {url}"),
    )
}

fn scrub_refusal(url: &str) -> impl Fn(ScrubError) -> UrlFetchError + '_ {
    move |_| secret_fetch_refused("scrubber_unavailable", url)
}

/// Fetch `logical_url`, a URL that mentions a secret placeholder, into
/// `document_dir` and return the converted document's path.
///
/// The URL cache is never read or written, and the web-view rewrite is
/// skipped, so the URL the vault's rule is matched against is the one the
/// agent gave. Every hop, redirects included, is checked against the private
/// address policy and then evaluated from scratch against the granted rules:
/// only a hop a rule covers gets a copy of the URL with the key in its query.
/// Every response header this function reads (`Location` first of all) and
/// the body are scrubbed of each key released so far before they are used, and
/// every message names `logical_url` (or a scrubbed redirect target), never a
/// URL that held a key.
pub fn fetch_url_with_secrets(
    logical_url: &str,
    document_dir: &Path,
    options: UrlFetchOptions,
    secrets: &SecretFetch,
) -> Result<PathBuf, UrlFetchError> {
    let key_sent = std::cell::Cell::new(false);
    let result = fetch_with_secrets(logical_url, document_dir, options, secrets, &key_sent)
        .map_err(|error| {
            // A refusal written as "nothing was sent" is reworded once a request
            // carrying the key has gone out.
            if key_sent.get() {
                error.after_secret_sent()
            } else {
                error
            }
        });
    record_fetch(&result);
    result
}

/// [`fetch_url_with_secrets`], recording in `key_sent` when a request that
/// carried a key has been sent (or attempted).
fn fetch_with_secrets(
    logical_url: &str,
    document_dir: &Path,
    options: UrlFetchOptions,
    secrets: &SecretFetch,
    key_sent: &std::cell::Cell<bool>,
) -> Result<PathBuf, UrlFetchError> {
    let mut current = Url::parse(logical_url)
        .map_err(|_| UrlFetchError::new(format!("Invalid URL: {logical_url}")))?;
    // A fragment never reaches a server, and a rule never matches one.
    current.set_fragment(None);
    let start = current.clone();
    let mut deadline = FetchDeadline::for_current_call();
    let approved = Arc::new(ApprovedHosts::default());
    let progress = Arc::new(ConnectProgress::default());
    let client = build_client(
        &options,
        Arc::clone(&approved),
        Arc::clone(&progress),
        false,
        Some(secrets.cancellation.clone()),
    )?;
    let mut held = HeldKeys::default();
    let mut hop = 0;
    let response = loop {
        if secrets.cancellation.is_cancelled() {
            return Err(secret_fetch_refused("missing_material", logical_url));
        }
        validate_public_url(&current, &options, &deadline, &approved)?;
        let waiting = Instant::now();
        let outbound = secret_hop(&current, hop, secrets, &mut held)?;
        // Approval is a separate person-wait budget, not network time.
        let waited = waiting.elapsed();
        deadline.at += waited;
        crate::bounded_io::exclude_secret_approval_wait(waited);
        let sent = send_request(
            &client,
            &current,
            Some(SecretSend {
                shown: current.as_str(),
                held: &held,
                released: outbound.is_some(),
                cancellation: &secrets.cancellation,
                key_sent,
                outbound: outbound.as_ref(),
            }),
            &deadline,
            &progress,
        );
        // Wipe this function's copy of the key-bearing URL now that it is sent.
        drop(outbound);
        let response = sent?;
        if !response.status().is_redirection() {
            break response;
        }
        if hop == MAX_REDIRECTS {
            return Err(UrlFetchError::new(format!(
                "Too many redirects fetching {logical_url}"
            )));
        }
        // A control byte never belongs in a Location, and URL parsing would
        // drop some of them (a tab), joining text the scrubber saw apart.
        if response.headers().get_all(LOCATION).iter().any(|value| {
            value
                .as_bytes()
                .iter()
                .any(|byte| *byte < 0x20 || *byte == 0x7f)
        }) {
            return Err(secret_fetch_refused("redirect_control_byte", logical_url));
        }
        let location = scrubbed_header(&response, LOCATION, &held, logical_url, &deadline)?
            .filter(|value| value.bytes().all(|byte| (0x20..0x7f).contains(&byte)))
            .ok_or_else(|| {
                UrlFetchError::new(format!(
                    "Redirect from {} missing Location header",
                    current.as_str()
                ))
            })?;
        let mut next = current.join(&location).map_err(|error| {
            UrlFetchError::new(format!(
                "Invalid redirect Location '{location}' from {}: {error}",
                current.as_str()
            ))
        })?;
        next.set_fragment(None);
        // Joining normalizes the URL (dot segments collapse, the host is
        // lowercased, escapes are kept), which can reassemble a key the
        // header scrub did not see. Check the URL exactly as it will be
        // looked up, sent and named, before any of that happens.
        refuse_unless_clean(
            held.reveal(next.as_str().as_bytes(), header_check_deadline(&deadline)),
            "redirect_discloses_key",
            logical_url,
        )?;
        current = next;
        hop += 1;
        timing::record(|times| times.redirects += 1);
    };

    let status = response.status();
    if !status.is_success() {
        return Err(UrlFetchError::http_status(
            status.as_u16(),
            format!(
                "HTTP {} {} fetching {logical_url}",
                status.as_u16(),
                status.canonical_reason().unwrap_or("")
            ),
        ));
    }
    let content_type = scrubbed_header(&response, CONTENT_TYPE, &held, logical_url, &deadline)?
        .unwrap_or_else(|| "text/plain".to_string());
    // `HeaderMap::get` reads only the first field. A second Content-Encoding
    // field could name a coding behind an `identity` first one, so repeated
    // fields refuse the response rather than being read in part.
    if response.headers().get_all(CONTENT_ENCODING).iter().count() > 1 {
        return Err(secret_fetch_refused("content_encoding", logical_url));
    }
    let codings = match scrubbed_header(&response, CONTENT_ENCODING, &held, logical_url, &deadline)?
    {
        Some(value) => secret_content_codings(&value, logical_url)?,
        None if response.headers().contains_key(CONTENT_ENCODING) => {
            return Err(secret_fetch_refused("content_encoding", logical_url));
        }
        None => Vec::new(),
    };
    let (extension, from_source_path) = resolve_fetch_extension(&start, &content_type)
        .ok_or_else(|| {
            UrlFetchError::new(format!(
                "Unsupported content type '{content_type}' for {logical_url}. Supported: text/html, text/markdown, application/json, text/plain; source files via URL path extension (e.g. .rs, .ts, .mjs)"
            ))
        })?;
    // An HTML response is converted whatever its path says (an index.php
    // page, or a .json endpoint answering with an HTML error page). Kept raw,
    // its markup would hide a key split across tags or spelled with entities
    // from the scrub while any browser shows it; converted, the residual
    // check below sees the text a reader sees.
    let is_html =
        extension == ".html" || resolve_extension_from_content_type(&content_type) == Some(".html");
    let total_bytes = codings
        .is_empty()
        .then(|| response.content_length())
        .flatten();
    // A failed read's text comes from reqwest and may name the request URL,
    // which held the key; it is scrubbed like everything else read back.
    let sanitize = |detail: &str| held.sanitize_detail(detail);
    #[cfg(any(test, feature = "test-support"))]
    let response: Box<dyn Read + Send> =
        match TEST_BODY_READ_ERROR.with(|slot| slot.borrow().clone()) {
            Some(message) => Box::new(FailingBody(message)),
            None => Box::new(response),
        };
    let (raw, mut download_truncated) =
        read_response_body_with(response, logical_url, &deadline, &sanitize)?;
    let decoded = decode_secret_body(&raw, &codings, &mut download_truncated, logical_url)?;
    let mut body = held.scrub(&decoded).map_err(scrub_refusal(logical_url))?;
    drop(decoded);
    let downloaded_bytes = body.len();
    if download_truncated {
        if let Err(error) = std::str::from_utf8(&body) {
            if error.error_len().is_none() {
                body.truncate(error.valid_up_to());
            }
        }
    }
    if from_source_path && !is_html && body_contains_nul_in_prefix(&body) {
        return Err(UrlFetchError::new(format!(
            "Binary content detected for source URL {logical_url}"
        )));
    }
    let (body, content_type, extension) = if is_html {
        // Converting HTML can decode entities into new text, so the converted
        // document is scrubbed again before it is written.
        let markdown = convert_html_body_to_markdown(&body, logical_url)?;
        (
            held.scrub(&markdown).map_err(scrub_refusal(logical_url))?,
            CONVERTED_MARKDOWN_CONTENT_TYPE.to_string(),
            ".md",
        )
    } else {
        (body, content_type, extension)
    };

    // The scrub replaced every spelling it recognised, but conversion and
    // plain readers undo more (a Markdown-escaped `\*`, an HTML entity kept in
    // a page served under a source path). A document that still spells a held
    // key after those is refused, never written; so is one the check could
    // not finish, within its work budget or before its share of the call's
    // read-back reserve ran out.
    refuse_unless_clean(
        held.reveal(&body, residual_check_deadline(&deadline)),
        "document_discloses_key",
        logical_url,
    )?;
    let content_file = document_dir.join(format!("document{extension}"));
    write_secret_document(&content_file, &body)?;
    // The metadata sits where `download_notice` looks for it, so a truncated
    // download is disclosed exactly as a cached one is.
    let meta = CacheMeta {
        url: logical_url.to_string(),
        content_type,
        extension: extension.to_string(),
        fetched_at: now_ms(),
        download_truncated,
        downloaded_bytes,
        total_bytes,
    };
    let meta_bytes = serde_json::to_vec(&meta).map_err(|error| {
        UrlFetchError::new(format!("Failed to encode URL fetch metadata: {error}"))
    })?;
    write_secret_document(&content_file.with_extension("meta.json"), &meta_bytes)?;
    Ok(content_file)
}

fn write_secret_document(path: &Path, bytes: &[u8]) -> Result<(), UrlFetchError> {
    crate::private_storage::write(path, bytes).map_err(|error| {
        UrlFetchError::new(format!(
            "Failed to write placeholder fetch document {}: {error}",
            path.display()
        ))
    })
}

/// A response header's value, scrubbed of every held key before anything
/// reads it; `None` when the header is absent or not text.
fn scrubbed_header(
    response: &HttpResponse,
    name: reqwest::header::HeaderName,
    held: &HeldKeys,
    url: &str,
    deadline: &FetchDeadline,
) -> Result<Option<String>, UrlFetchError> {
    let Some(value) = response.headers().get(&name) else {
        return Ok(None);
    };
    let clean = held.scrub(value.as_bytes()).map_err(scrub_refusal(url))?;
    // The scrubbed value is read, joined or quoted next; a key it still
    // spells in a form the scrub missed refuses the response instead.
    refuse_unless_clean(
        held.reveal(&clean, header_check_deadline(deadline)),
        "header_discloses_key",
        url,
    )?;
    Ok(String::from_utf8(clean).ok())
}

#[cfg(any(test, feature = "test-support"))]
thread_local! {
    /// When set, a placeholder fetch's body read fails with this text, so a
    /// test can check what the call site does with a library error.
    static TEST_BODY_READ_ERROR: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
}

/// Make this thread's placeholder fetches fail their body read with
/// `message` until the returned guard drops.
#[cfg(any(test, feature = "test-support"))]
pub fn inject_secret_body_read_error_for_test(message: String) -> impl Drop {
    struct Restore;
    impl Drop for Restore {
        fn drop(&mut self) {
            TEST_BODY_READ_ERROR.with(|slot| slot.replace(None));
        }
    }
    TEST_BODY_READ_ERROR.with(|slot| slot.replace(Some(message)));
    Restore
}

/// A response body whose every read fails with the injected text.
#[cfg(any(test, feature = "test-support"))]
struct FailingBody(String);

#[cfg(any(test, feature = "test-support"))]
impl Read for FailingBody {
    fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
        Err(io::Error::other(self.0.clone()))
    }
}

/// When a placeholder fetch's final residual key check must stop: its share
/// of the read-back reserve after the download deadline, or sooner in a test
/// that injects a shorter limit.
fn residual_check_deadline(deadline: &FetchDeadline) -> Instant {
    #[cfg(any(test, feature = "test-support"))]
    if let Some(limit) = TEST_RESIDUAL_LIMIT.with(std::cell::Cell::get) {
        return Instant::now() + limit;
    }
    deadline.at + RESIDUAL_CHECK_RESERVE
}

/// When the residual check of a response header or a joined redirect URL
/// must stop: the download deadline, since those checks run while the fetch
/// is still downloading, or sooner in a test that injects a shorter limit.
fn header_check_deadline(deadline: &FetchDeadline) -> Instant {
    #[cfg(any(test, feature = "test-support"))]
    if let Some(limit) = TEST_RESIDUAL_LIMIT.with(std::cell::Cell::get) {
        return Instant::now() + limit;
    }
    deadline.at
}

#[cfg(any(test, feature = "test-support"))]
thread_local! {
    /// When set, each of a placeholder fetch's residual checks (headers,
    /// redirect URLs, the document) stops this long after it starts, so a
    /// test can reach the timeout without a slow document.
    static TEST_RESIDUAL_LIMIT: std::cell::Cell<Option<Duration>> = const { std::cell::Cell::new(None) };
}

/// Make this thread's placeholder fetches stop their residual check `limit`
/// after it starts, until the returned guard drops.
#[cfg(any(test, feature = "test-support"))]
pub fn limit_secret_residual_check_for_test(limit: Duration) -> impl Drop {
    struct Restore;
    impl Drop for Restore {
        fn drop(&mut self) {
            TEST_RESIDUAL_LIMIT.with(|slot| slot.set(None));
        }
    }
    TEST_RESIDUAL_LIMIT.with(|slot| slot.set(Some(limit)));
    Restore
}

/// A content coding a placeholder fetch can undo before scrubbing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SecretCoding {
    Identity,
    Gzip,
    Deflate,
    Brotli,
}

/// The codings a response declares, in the order they were applied. A server
/// may encode the body although the request asked for `identity`; any coding
/// this function cannot undo refuses the document, because an encoded key
/// cannot be scrubbed. A coding named twice refuses it too: no ordinary server
/// encodes a body twice the same way, and the limit on stacked codings stays
/// meaningful.
fn secret_content_codings(value: &str, url: &str) -> Result<Vec<SecretCoding>, UrlFetchError> {
    let mut codings = Vec::new();
    for token in value.split(',').map(str::trim) {
        let coding = if token.eq_ignore_ascii_case("identity") {
            SecretCoding::Identity
        } else if token.eq_ignore_ascii_case("gzip") || token.eq_ignore_ascii_case("x-gzip") {
            SecretCoding::Gzip
        } else if token.eq_ignore_ascii_case("deflate") {
            SecretCoding::Deflate
        } else if token.eq_ignore_ascii_case("br") {
            SecretCoding::Brotli
        } else {
            return Err(secret_fetch_refused("content_encoding", url));
        };
        if codings.len() >= MAX_SECRET_CODINGS || codings.contains(&coding) {
            return Err(secret_fetch_refused("content_encoding", url));
        }
        codings.push(coding);
    }
    Ok(codings)
}

/// Undo `codings` (last applied first), keeping at most
/// [`MAX_RESPONSE_BYTES`] of output. A body whose download was cut short keeps
/// what decoded before the cut; any other decoding failure refuses it.
fn decode_secret_body(
    body: &[u8],
    codings: &[SecretCoding],
    truncated: &mut bool,
    url: &str,
) -> Result<sensitive::Bytes, UrlFetchError> {
    use async_compression::tokio::bufread::{BrotliDecoder, GzipDecoder, ZlibDecoder};
    use tokio::io::{AsyncRead, BufReader};

    let mut data = sensitive::Factory::current().copy(body);
    for coding in codings.iter().rev() {
        let input: &[u8] = &data;
        let reader: std::pin::Pin<Box<dyn AsyncRead + Send + '_>> = match coding {
            SecretCoding::Identity => continue,
            SecretCoding::Gzip => {
                let mut decoder = GzipDecoder::new(BufReader::new(input));
                decoder.multiple_members(true);
                Box::pin(decoder)
            }
            SecretCoding::Deflate => Box::pin(ZlibDecoder::new(BufReader::new(input))),
            SecretCoding::Brotli => Box::pin(BrotliDecoder::new(BufReader::new(input))),
        };
        let input_truncated = *truncated;
        let (output, cut) = drain_decoder(reader, input_truncated).map_err(|()| {
            UrlFetchError::new(format!("Failed to decode the response body for {url}"))
        })?;
        if cut {
            *truncated = true;
        }
        data = output;
    }
    Ok(data)
}

/// Read a decoder over an in-memory body to its end, keeping at most
/// [`MAX_RESPONSE_BYTES`]. Returns the output and whether the ceiling cut it.
/// A body whose download was already cut (`input_truncated`) ends mid-stream;
/// what decoded before the cut is kept as a usable prefix.
fn drain_decoder(
    mut reader: std::pin::Pin<Box<dyn tokio::io::AsyncRead + Send + '_>>,
    input_truncated: bool,
) -> Result<(sensitive::Bytes, bool), ()> {
    use std::future::Future;
    use tokio::io::AsyncReadExt;

    let factory = sensitive::Factory::current();
    let mut output = factory.with_capacity(0);
    let polled = {
        let decoding = async {
            let mut buffer = factory.zeroed(16 * 1024);
            loop {
                match reader.read(&mut buffer).await {
                    Ok(0) => return Ok(false),
                    Ok(count) => {
                        let room = (MAX_RESPONSE_BYTES as usize).saturating_sub(output.len());
                        output.extend_from_slice(&buffer[..count.min(room)]);
                        if count > room {
                            return Ok(true);
                        }
                    }
                    Err(_) if input_truncated => return Ok(false),
                    Err(_) => return Err(()),
                }
            }
        };
        // The input is already in memory, so no read ever waits: one poll
        // runs the decoder to its end without an async runtime.
        let mut decoding = std::pin::pin!(decoding);
        let mut context = std::task::Context::from_waker(std::task::Waker::noop());
        decoding.as_mut().poll(&mut context)
    };
    match polled {
        std::task::Poll::Ready(Ok(cut)) => Ok((output, cut)),
        std::task::Poll::Ready(Err(())) | std::task::Poll::Pending => Err(()),
    }
}

#[rustfmt::skip]
test_support_visibility! {

/// Decide one hop of a placeholder fetch; every hop, redirects included, is
/// evaluated as a new request.
///
/// Returns the URL to send when a rule substitutes a key into this hop, or
/// `None` to send `current` itself, whose placeholders then go out literally.
/// Only `query` rules substitute; another location refuses before any card or
/// releasing retry. Each scanned label gets one audit record for the hop,
/// and a hop whose records cannot be written is not sent.
fn secret_hop(
    current: &Url,
    hop: usize,
    secrets: &SecretFetch,
    held: &mut HeldKeys,
) -> Result<Option<SecretOutboundUrl>, UrlFetchError> {
    let logical = current.as_str();
    let path = current.path();
    let target = match current.query() {
        Some(query) => format!("{path}?{query}"),
        None => path.to_string(),
    };
    // Only an HTTPS hop can carry a key.
    let authority = (current.scheme() == "https")
        .then(|| current.host_str().zip(current.port_or_known_default()))
        .flatten()
        .and_then(|(host, port)| {
            secret_rules::target::canonical_host(host)
                .ok()
                .map(|host| ConnectAuthority { host, port })
        });
    let Some(authority) = authority else {
        emit_hop_audit(secrets, held, hop, None, &[], |_| {
            (Decision::Literal, AuditReason::OutOfScope)
        })
        .map_err(|_| secret_fetch_refused("audit_unavailable", logical))?;
        return Ok(None);
    };
    let refused = |held: &HeldKeys, reason: &str| {
        let _ = emit_hop_audit(secrets, held, hop, Some(&authority), &[], |_| {
            (Decision::Refused, AuditReason::Refused)
        });
        secret_fetch_refused(reason, logical)
    };

    let mut rules = Vec::new();
    let mut materials = Vec::new();
    let present = secret_labels_in_url(logical).unwrap_or_default();
    let normalized = normalize_request_target(path).map_err(|_| refused(held, "malformed_path"))?;
    let addressed = crate::secret::ApiKeyTarget {
        scheme: "https".into(),
        host: authority.host.clone(),
        port: Some(443),
        path: String::from_utf8(normalized.wire).map_err(|_| refused(held, "malformed_path"))?,
    };
    let mut eligible = Vec::new();
    for label in &secrets.labels {
        let https_port = authority.port == 443;
        #[cfg(any(test, feature = "test-support"))]
        let https_port = https_port || secrets.test_https_port == Some(authority.port);
        if !https_port || !present.contains(label) {
            continue;
        }
        eligible.push(label.clone());
    }
    let answers = crate::secret::fetch::use_current_secret_labels(
        secrets.vault.clone(),
        &eligible,
        &addressed,
        &target,
        &secrets.cancellation,
    );
    for (label, answer) in eligible.iter().zip(answers) {
        let answer = match answer {
            crate::secret::fetch::FetchDecision::InvalidPlan(reason) => {
                return Err(refused(held, reason))
            }
            crate::secret::fetch::FetchDecision::Proceed(answer) => answer,

            crate::secret::fetch::FetchDecision::Refuse(crate::secret::LabelOutcome::Refuse {
                code,
                message,
            }) => {
                let _ = refused(held, "missing_material");
                return Err(UrlFetchError::secret(code, message));
            }
            _ => return Err(refused(held, "missing_material")),
        };
        if let crate::secret::UseAnswer::Released(released) = answer {
            let (location, material) = released.into_parts();
            let location = secret_rules::location::parse_vault_location(&location)
                .ok_or_else(|| refused(held, "missing_material"))?;
            if !matches!(location, Location::Query(_)) {
                return Err(refused(held, "missing_material"));
            }
            if check_admissible(material.expose(), label, &location).is_err() {
                return Err(refused(held, "material_not_admissible"));
            }
            held.hold(label, material.expose())
                .map_err(|_| refused(held, "replacement_discloses_key"))?;
            rules.push(LabelRule {
                label: label.clone(),
                host: addressed.host.clone(),
                port: authority.port,
                path_prefix: addressed.path.clone(),
                location,
            });
            materials.push(Some(material));
        }
    }
    // Plan with a stand-in key first: the rules decide where a key would go,
    // and refuse an ambiguous request before copying released bytes into a URL.
    let planning: Vec<(String, Vec<u8>)> = rules
        .iter()
        .map(|rule| (rule.label.clone(), SECRET_PLANNING_KEY.to_vec()))
        .collect();
    let view = RequestView::new(&target, Vec::new());
    let plan = evaluate_request_with_connect(&view, &authority, &rules, &planning);
    if let Some(refusal) = plan.refusal {
        return Err(refused(&*held, refusal.reason()));
    }

    let query_start = path.len() + 1;
    let mut edits: Vec<(usize, usize, Zeroizing<Vec<u8>>)> = Vec::new();
    for ((rule, outcome), material) in rules.iter().zip(&plan.labels).zip(&materials) {
        if let LabelOutcome::Substituted {
            byte_start,
            byte_end,
            ..
        } = outcome
        {
            let (Some(material), true) = (material, *byte_start >= query_start) else {
                return Err(refused(&*held, "missing_material"));
            };
            let encoded = encode_for_location(material.expose(), &rule.label, &rule.location)
                .map_err(|_| refused(&*held, "material_not_admissible"))?;
            edits.push((
                byte_start - query_start,
                byte_end - query_start,
                Zeroizing::new(encoded),
            ));
        }
    }
    let decide = |label: &str| -> (Decision, AuditReason) {
        let outcome = rules
            .iter()
            .position(|rule| rule.label == label)
            .and_then(|index| plan.labels.get(index));
        match outcome {
            Some(LabelOutcome::Substituted { .. }) => (Decision::Substituted, AuditReason::Matched),
            Some(LabelOutcome::NotWholeValue) => (Decision::Literal, AuditReason::NotWholeValue),
            _ => (Decision::Literal, AuditReason::OutOfScope),
        }
    };
    if edits.is_empty() {
        emit_hop_audit(secrets, held, hop, Some(&authority), &rules, decide)
            .map_err(|_| secret_fetch_refused("audit_unavailable", logical))?;
        return Ok(None);
    }

    edits.sort_by_key(|(start, _, _)| *start);
    let query = current.query().unwrap_or_default().as_bytes();
    let substituted =
        substitute_query(query, &edits).ok_or_else(|| refused(held, "malformed_query"))?;
    let Ok(substituted) = std::str::from_utf8(&substituted) else {
        return Err(refused(&*held, "malformed_query"));
    };
    // The path sent with a key is the normalized path the rule matched,
    // never another spelling of it.
    let Ok(normalized) = normalize_request_target(path) else {
        return Err(refused(&*held, "malformed_path"));
    };
    let Ok(wire_path) = std::str::from_utf8(&normalized.wire) else {
        return Err(refused(&*held, "malformed_path"));
    };
    emit_hop_audit(secrets, held, hop, Some(&authority), &rules, decide)
        .map_err(|_| secret_fetch_refused("audit_unavailable", logical))?;
    secret_outbound_url(current, wire_path, substituted)
        .map(Some)
        .ok_or_else(|| refused(held, "malformed_query"))
}
}

#[cfg(any(test, feature = "test-support"))]
thread_local! { pub static SECRET_URL_BUILDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; }

#[rustfmt::skip]
test_support_visibility! {
struct SecretOutboundUrl(sensitive::Bytes);
}
impl std::ops::Deref for SecretOutboundUrl {
    type Target = str;
    fn deref(&self) -> &str {
        std::str::from_utf8(&self.0).expect("URL serialization is UTF-8")
    }
}
impl SecretOutboundUrl {
    fn as_str(&self) -> &str {
        self
    }
}
impl fmt::Debug for SecretOutboundUrl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("ProtectedOutboundUrl")
    }
}

fn secret_outbound_url(
    current: &Url,
    wire_path: &str,
    substituted: &str,
) -> Option<SecretOutboundUrl> {
    #[cfg(any(test, feature = "test-support"))]
    SECRET_URL_BUILDS.with(|n| n.set(n.get() + 1));
    let prefix = &current[..url::Position::BeforePath];
    let capacity = prefix
        .len()
        .checked_add(wire_path.len())?
        .checked_add(1)?
        .checked_add(substituted.len())?;
    // Build the complete serialization in protected, pre-sized storage instead
    // of reallocating a partially key-bearing Url with clone/set_query.
    let mut serialized = sensitive::Factory::current().with_capacity(capacity);
    serialized.extend_from_slice(prefix.as_bytes());
    serialized.extend_from_slice(wire_path.as_bytes());
    serialized.extend_from_slice(b"?");
    serialized.extend_from_slice(substituted.as_bytes());
    Some(SecretOutboundUrl(serialized))
}

fn substitute_query(
    query: &[u8],
    edits: &[(usize, usize, Zeroizing<Vec<u8>>)],
) -> Option<Zeroizing<Vec<u8>>> {
    let final_len = edits
        .iter()
        .try_fold(query.len(), |len, (start, end, value)| {
            len.checked_sub(end.checked_sub(*start)?)?
                .checked_add(value.len())
        })?;
    // Allocate the complete result before copying the first credential: growing
    // a partially filled Vec would free an old, unwiped credential allocation.
    let mut substituted = Zeroizing::new(Vec::with_capacity(final_len));
    let mut cursor = 0;
    for (start, end, replacement) in edits {
        if *start < cursor || *end < *start || *end > query.len() {
            return None;
        }
        substituted.extend_from_slice(&query[cursor..*start]);
        substituted.extend_from_slice(replacement);
        cursor = *end;
    }
    substituted.extend_from_slice(&query[cursor..]);
    Some(substituted)
}

/// One audit record per scanned label for one hop. A record is handed to the
/// vault only after the crate's writer checked it against every held key.
fn emit_hop_audit(
    secrets: &SecretFetch,
    held: &HeldKeys,
    hop: usize,
    authority: Option<&ConnectAuthority>,
    rules: &[LabelRule],
    decide: impl Fn(&str) -> (Decision, AuditReason),
) -> Result<(), ()> {
    let origin = format!("{}#{hop}", secrets.call_id);
    let keys = held.keys();
    let mut failed = false;
    for label in &secrets.labels {
        let (decision, reason) = decide(label);
        let mut record = AuditRecordV1::new(
            crate::secret::now_ms(),
            label,
            decision,
            reason,
            &secrets.call_id,
            &origin,
        )
        .with_scope(
            secrets
                .authorization
                .as_ref()
                .map(crate::secret::SecretScope::to_scope_ref),
        );
        if let Some(authority) = authority {
            record.host = Some(authority.host.clone());
            record.port = Some(authority.port);
        }
        if let Some(rule) = rules.iter().find(|rule| &rule.label == label) {
            record = record.with_rule(
                &rule.host,
                rule.port,
                &rule.path_prefix,
                location_kind_token(&rule.location),
            );
        }
        if record.to_json_line_with_keys(&keys).is_err() || secrets.vault.audit(&record).is_err() {
            failed = true;
        }
    }
    if failed {
        Err(())
    } else {
        Ok(())
    }
}

/// What a cleanup sweep learned from one metadata file, kept so the next sweep
/// can skip re-reading it. `len` and `modified` identify the file version the
/// fetch time was read from: the cache rewrites metadata only through a rename
/// of a freshly written file, which always produces a new modification time.
#[derive(Debug, Clone)]
struct CleanupMemoEntry {
    len: u64,
    modified: SystemTime,
    fetched_at: u64,
    extension: String,
}

/// Per cache directory, the metadata facts of the last sweep, keyed by file
/// name. Every configure runs the cleanup sweep, and almost every metadata
/// file is unchanged since the previous one, so an unchanged file costs one
/// stat instead of an open, a read and a JSON parse. A sweep replaces its
/// directory's map with only the files it saw and kept, so removed entries do
/// not accumulate.
fn cleanup_memo() -> &'static std::sync::Mutex<HashMap<PathBuf, HashMap<String, CleanupMemoEntry>>>
{
    static MEMO: std::sync::OnceLock<
        std::sync::Mutex<HashMap<PathBuf, HashMap<String, CleanupMemoEntry>>>,
    > = std::sync::OnceLock::new();
    MEMO.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
}

#[cfg(any(test, feature = "test-support"))]
thread_local! {
    /// Metadata files the cleanup sweep opened on this thread, for tests that
    /// check unchanged files are not read again.
    pub static CLEANUP_META_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

pub fn cleanup_url_cache(storage_dir: &Path) -> Result<usize, UrlFetchError> {
    cleanup_url_cache_at(storage_dir, now_ms())
}

fn cleanup_url_cache_at(storage_dir: &Path, now: u64) -> Result<usize, UrlFetchError> {
    let dir = cache_dir(storage_dir);
    if !dir.exists() {
        return Ok(0);
    }

    let entries = fs::read_dir(&dir).map_err(|error| {
        UrlFetchError::new(format!(
            "URL cache cleanup failed reading {}: {error}",
            dir.display()
        ))
    })?;
    let mut removed = 0usize;
    // Taken out for the sweep and put back at the end, so the lock is never
    // held across file I/O. A concurrent sweep of the same directory finds no
    // memo and reads every file, which is only slower.
    let previous = cleanup_memo()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .remove(&dir)
        .unwrap_or_default();
    let mut kept = HashMap::new();

    for entry in entries.flatten() {
        let path = entry.path();
        let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
            continue;
        };
        if !name.ends_with(".meta.json") {
            continue;
        }

        let version = entry
            .metadata()
            .ok()
            .and_then(|metadata| Some((metadata.len(), metadata.modified().ok()?)));
        let remembered = version.and_then(|(len, modified)| {
            previous
                .get(name)
                .filter(|known| known.len == len && known.modified == modified)
                .cloned()
        });
        let facts = match remembered {
            Some(known) => known,
            None => {
                #[cfg(any(test, feature = "test-support"))]
                CLEANUP_META_READS.with(|reads| reads.set(reads.get() + 1));
                let meta = fs::read_to_string(&path)
                    .ok()
                    .and_then(|content| serde_json::from_str::<CacheMeta>(&content).ok());
                let Some(meta) = meta else {
                    if fs::remove_file(&path).is_ok() {
                        removed += 1;
                    }
                    continue;
                };
                let (len, modified) = version.unwrap_or((u64::MAX, UNIX_EPOCH));
                CleanupMemoEntry {
                    len,
                    modified,
                    fetched_at: meta.fetched_at,
                    extension: meta.extension,
                }
            }
        };

        if now.saturating_sub(facts.fetched_at) <= CACHE_TTL_MS {
            // A file whose version could not be read is not remembered, so the
            // next sweep reads it again.
            if version.is_some() {
                kept.insert(name.to_string(), facts);
            }
            continue;
        }

        let hash = name.trim_end_matches(".meta.json");
        let content = content_path(storage_dir, hash, &facts.extension);
        let _ = fs::remove_file(content);
        if fs::remove_file(&path).is_ok() {
            removed += 1;
        }
    }

    cleanup_memo()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .insert(dir, kept);
    Ok(removed)
}

#[doc(hidden)]
pub fn cache_content_path_for_url(storage_dir: &Path, url: &str, extension: &str) -> PathBuf {
    content_path(storage_dir, &hash_url(url), extension)
}

#[doc(hidden)]
pub fn cache_meta_path_for_url(storage_dir: &Path, url: &str) -> PathBuf {
    meta_path(storage_dir, &hash_url(url))
}

/// Disclose a partial download separately from any later rendering cut. Keys
/// or headings after this prefix have not been inspected.
pub fn download_notice(path: &Path) -> Option<String> {
    let meta_path = path.with_extension("meta.json");
    let meta: CacheMeta = serde_json::from_slice(&fs::read(meta_path).ok()?).ok()?;
    if !meta.download_truncated {
        return None;
    }
    let total = meta
        .total_bytes
        .map(|n| n.to_string())
        .unwrap_or_else(|| format!("≥{}", meta.downloaded_bytes + 1));
    Some(format!(
        "Download truncated at {} of {total} bytes; narrow with a smaller URL or server-side filters (only the downloaded prefix was inspected)",
        meta.downloaded_bytes
    ))
}

#[doc(hidden)]
pub fn is_private_ip_for_test(ip: IpAddr) -> bool {
    is_private_ip(ip)
}

fn cache_dir(storage_dir: &Path) -> PathBuf {
    storage_dir.join("url_cache")
}

fn hash_url(url: &str) -> String {
    let digest = Sha256::digest(url.as_bytes());
    format!("{digest:x}").chars().take(16).collect()
}

/// Rewrite well-known web-view links before fetching because those pages serve
/// an HTML application shell instead of the file contents agents need to read.
fn rewrite_url_for_fetch(url: &Url) -> Url {
    let original = url.clone();
    let mut rewritten = url.clone();
    rewritten.set_fragment(None);

    let Some(host) = url.host_str() else {
        return rewritten;
    };
    if !matches!(url.scheme(), "http" | "https") {
        return rewritten;
    }

    let segments: Vec<&str> = url
        .path_segments()
        .map(|segments| segments.collect())
        .unwrap_or_default();
    let (raw_host, raw_path) = if matches!(host, "github.com" | "www.github.com") {
        if segments.len() >= 5 && matches!(segments[2], "blob" | "raw") {
            (
                "raw.githubusercontent.com",
                format!(
                    "/{}/{}/{}/{}",
                    segments[0],
                    segments[1],
                    segments[3],
                    segments[4..].join("/")
                ),
            )
        } else {
            return rewritten;
        }
    } else if host == "gitlab.com"
        && segments.len() >= 6
        && segments[2] == "-"
        && segments[3] == "blob"
    {
        (
            "gitlab.com",
            format!(
                "/{}/{}/-/raw/{}/{}",
                segments[0],
                segments[1],
                segments[4],
                segments[5..].join("/")
            ),
        )
    } else {
        return rewritten;
    };

    rewritten
        .set_host(Some(raw_host))
        .expect("raw content host should be a valid URL host");
    rewritten.set_path(&raw_path);
    log::debug!(
        "url_fetch: rewriting web-view URL to raw content: {} -> {}",
        original,
        rewritten
    );
    rewritten
}

fn meta_path(storage_dir: &Path, hash: &str) -> PathBuf {
    cache_dir(storage_dir).join(format!("{hash}.meta.json"))
}

fn content_path(storage_dir: &Path, hash: &str, extension: &str) -> PathBuf {
    cache_dir(storage_dir).join(format!("{hash}{extension}"))
}

fn fresh_cached_path(
    storage_dir: &Path,
    hash: &str,
    meta_file: &Path,
    url: &Url,
) -> Result<Option<PathBuf>, UrlFetchError> {
    #[cfg(any(test, feature = "test-support"))]
    stall_cache_read_if_requested(storage_dir);
    if !meta_file.exists() {
        return Ok(None);
    }

    let meta = match fs::read_to_string(meta_file)
        .ok()
        .and_then(|content| serde_json::from_str::<CacheMeta>(&content).ok())
    {
        Some(meta) => meta,
        None => return Ok(None),
    };
    let age = now_ms().saturating_sub(meta.fetched_at);
    if meta.extension == ".html" {
        return Ok(None);
    }

    let content_type = meta.content_type.as_str();
    let current = resolve_fetch_extension(url, content_type);
    // An HTML page is stored converted to Markdown, so a URL whose path ends
    // in .html or .htm finds its cached copy under .md. Comparing against
    // .html would miss the cache on every call and fetch, convert and
    // re-parse the whole page again.
    let expected_ext = current.map(|(ext, _)| if ext == ".html" { ".md" } else { ext });
    if expected_ext != Some(meta.extension.as_str()) {
        return Ok(None);
    }

    let cached = content_path(storage_dir, hash, &meta.extension);
    // Old cache entries predate the iterator ceiling and may contain an
    // unbounded body. Refetch those rather than reintroducing the missed cap.
    let legacy_oversized = meta.downloaded_bytes == 0
        && fs::metadata(&cached).is_ok_and(|m| m.len() > MAX_RESPONSE_BYTES);
    if age < CACHE_TTL_MS && cached.exists() && !legacy_oversized {
        return Ok(Some(cached));
    }
    Ok(None)
}

fn fetch_with_redirects(
    start_url: &Url,
    original_url: &str,
    options: &UrlFetchOptions,
    deadline: &FetchDeadline,
    approved: Arc<ApprovedHosts>,
) -> Result<HttpResponse, UrlFetchError> {
    let progress = Arc::new(ConnectProgress::default());
    let client = build_client(
        options,
        Arc::clone(&approved),
        Arc::clone(&progress),
        true,
        None,
    )?;
    let mut current_url = start_url.clone();

    for redirect_count in 0..=MAX_REDIRECTS {
        validate_public_url(&current_url, options, deadline, &approved)?;
        let response = send_with_transient_retries(&client, &current_url, deadline, &progress)?;

        if !response.status().is_redirection() {
            return Ok(response);
        }
        if redirect_count == MAX_REDIRECTS {
            return Err(UrlFetchError::new(format!(
                "Too many redirects fetching {original_url}"
            )));
        }

        let location = response
            .headers()
            .get(LOCATION)
            .and_then(|value| value.to_str().ok())
            .ok_or_else(|| {
                UrlFetchError::new(format!(
                    "Redirect from {} missing Location header",
                    current_url.as_str()
                ))
            })?;
        current_url = current_url.join(location).map_err(|error| {
            UrlFetchError::new(format!(
                "Invalid redirect Location '{location}' from {}: {error}",
                current_url.as_str()
            ))
        })?;
        timing::record(|times| times.redirects += 1);
    }

    Err(UrlFetchError::new(format!(
        "Too many redirects fetching {original_url}"
    )))
}

/// Issue a single GET with the configured User-Agent + Accept headers and
/// transparently retry only on transient connect/transport failures.
///
/// Returns the response (including 4xx/5xx — caller decides how to treat
/// those). On a non-transient reqwest error (e.g. an HTTP-shaped reply that
/// reqwest still surfaces as Err, or a TLS handshake fault that doesn't read
/// as `is_connect`), the original error is returned immediately so the user
/// sees the real failure without an artificial 800ms-plus delay.
///
/// Every attempt is limited to the time left before `deadline`, and a retry
/// runs only when its backoff plus [`MIN_USEFUL_ATTEMPT`] still fit, so
/// retries can never stretch a fetch past its deadline.
fn send_with_transient_retries(
    client: &Client,
    target: &Url,
    deadline: &FetchDeadline,
    progress: &ConnectProgress,
) -> Result<HttpResponse, UrlFetchError> {
    send_request(client, target, None, deadline, progress)
}

#[derive(Clone, Copy)]
struct SecretSend<'a> {
    shown: &'a str,
    held: &'a HeldKeys,
    released: bool,
    cancellation: &'a SecretFetchCancellation,
    key_sent: &'a std::cell::Cell<bool>,
    outbound: Option<&'a SecretOutboundUrl>,
}

/// [`send_with_transient_retries`] for one request. With `secret` set, the
/// request belongs to a placeholder fetch: every message names the given
/// placeholder URL instead of `target`, a failure is reported through
/// [`send_failure`] with the held keys, and the request asks for an unencoded
/// response so the body can be scrubbed byte for byte.
fn send_request(
    client: &Client,
    target: &Url,
    secret: Option<SecretSend<'_>>,
    deadline: &FetchDeadline,
    progress: &ConnectProgress,
) -> Result<HttpResponse, UrlFetchError> {
    let started = Instant::now();
    let (attempts_before, connect_before) = progress.totals();
    let result = send_request_attempts(client, target, secret, deadline, progress);
    let elapsed = started.elapsed();
    let (attempts, connect) = progress.totals();
    timing::record(|times| {
        times.first_byte += elapsed;
        times.connect += connect.saturating_sub(connect_before);
        times.retries += (attempts - attempts_before).saturating_sub(1) as u32;
    });
    result
}

/// [`send_request`]'s attempts, without its timing.
fn send_request_attempts(
    client: &Client,
    target: &Url,
    secret: Option<SecretSend<'_>>,
    deadline: &FetchDeadline,
    progress: &ConnectProgress,
) -> Result<HttpResponse, UrlFetchError> {
    let named = secret.map_or(target.as_str(), |secret| secret.shown);
    let held = secret.map(|secret| secret.held);
    let mut attempt = 0;
    loop {
        let remaining = deadline.remaining();
        if remaining.is_zero() {
            return Err(deadline.timeout_error(FetchPhase::Connect, named));
        }
        // A per-request timeout replaces reqwest's default 30 s, which would
        // otherwise let one silent server hold each attempt for 30 s.
        progress.begin_attempt();
        // Parse directly from protected serialization and move the Url into
        // reqwest. AFT must not clone a key-bearing URL's ordinary String.
        let outbound = match secret.and_then(|secret| secret.outbound) {
            Some(outbound) => Url::parse(outbound.as_str())
                .map_err(|_| secret_fetch_refused("malformed_query", named))?,
            None => target.clone(),
        };
        let mut request = client
            .get(outbound)
            .header(USER_AGENT, USER_AGENT_VALUE)
            .header(ACCEPT, ACCEPT_HEADER)
            .timeout(remaining.min(HEADERS_TIMEOUT));
        if held.is_some() {
            request = request.header(ACCEPT_ENCODING, "identity");
        }
        if secret.is_some_and(|secret| secret.cancellation.is_cancelled()) {
            return Err(secret_fetch_refused("missing_material", named));
        }
        if let Some(secret) = secret.filter(|secret| secret.released) {
            secret.key_sent.set(true);
        }
        let error = match request.send() {
            Ok(response) => return Ok(response),
            Err(error) => error,
        };
        if secret.is_some_and(|secret| secret.cancellation.is_cancelled()) {
            // A cancelled secret request returns its existing refusal rather
            // than exposing a transport error from connection setup.
            return Err(secret_fetch_refused("missing_material", named));
        }
        let phase = error
            .is_timeout()
            .then(|| timed_out_phase(&error, progress));
        // A server that accepted the request and stayed silent until the
        // headers limit is not a passing connection fault; retrying it would
        // only spend the rest of the deadline the same way.
        // One released key authorizes one send attempt, even if the peer received
        // the credential and reset before its response reached this process.
        let retryable = !secret.is_some_and(|secret| secret.released)
            && is_transient_reqwest_error(&error)
            && phase != Some(FetchPhase::Headers);
        let backoff = TRANSIENT_RETRY_BACKOFFS_MS
            .get(attempt)
            .map(|ms| Duration::from_millis(*ms))
            .filter(|backoff| retryable && *backoff + MIN_USEFUL_ATTEMPT <= deadline.remaining());
        if let Some(backoff) = backoff {
            thread::sleep(backoff);
            attempt += 1;
            continue;
        }
        return Err(send_failure(error, phase, deadline, named, held));
    }
}

/// The error for a request that failed for good, naming `named`. For a
/// placeholder fetch (`held` set) reqwest's error first loses its URL, which
/// carried the key, and the detail left is scrubbed of every held key (or
/// dropped if it still spells one).
fn send_failure(
    error: reqwest::Error,
    phase: Option<FetchPhase>,
    deadline: &FetchDeadline,
    named: &str,
    held: Option<&HeldKeys>,
) -> UrlFetchError {
    let error = if held.is_some() {
        error.without_url()
    } else {
        error
    };
    let detail = reqwest_error_detail(&error);
    let detail = match held {
        Some(held) => held.sanitize_detail(&detail),
        None => detail,
    };
    if let Some(phase) = phase {
        return request_timeout_error(&detail, phase, deadline, named);
    }
    if detail.is_empty() {
        return UrlFetchError::new(format!("Failed to fetch {named}"));
    }
    UrlFetchError::new(format!("Failed to fetch {named}: {detail}"))
}

/// Name the phase a timed-out request was in: a name lookup still running in
/// the resolver, then connection setup still running (or reported by reqwest
/// as the cause), and otherwise the wait for the response headers.
fn timed_out_phase(error: &reqwest::Error, progress: &ConnectProgress) -> FetchPhase {
    if progress.lookup_pending() {
        FetchPhase::Dns
    } else if progress.connect_pending() || error.is_connect() {
        FetchPhase::Connect
    } else {
        FetchPhase::Headers
    }
}

fn request_timeout_error(
    detail: &str,
    phase: FetchPhase,
    deadline: &FetchDeadline,
    target: &str,
) -> UrlFetchError {
    if deadline.expired() {
        return deadline.timeout_error(phase, target);
    }
    let limit = match phase {
        FetchPhase::Dns | FetchPhase::Connect => CONNECT_TIMEOUT,
        FetchPhase::Headers | FetchPhase::Body => HEADERS_TIMEOUT,
    };
    UrlFetchError::timeout(
        phase,
        format!(
            "URL fetch timed out in the {} phase after the {}ms limit fetching {}: {}",
            phase.as_str(),
            limit.as_millis(),
            target,
            detail
        ),
    )
}

/// Classify a reqwest error as transient (worth a quick retry) vs terminal.
///
/// Transient: TCP connect failures, request-build/send TCP-level failures
/// that don't carry status, and timeouts. These typically clear on a single
/// retry — agents shouldn't have to ask twice for a momentary blip.
///
/// Terminal: anything where reqwest got far enough to decode an HTTP-shaped
/// reply (`is_status()`, `is_body()`, `is_decode()`). Retrying those would
/// just hammer a server that already answered.
fn is_transient_reqwest_error(error: &reqwest::Error) -> bool {
    error.is_connect() || error.is_timeout() || error.is_request()
}

fn build_client(
    options: &UrlFetchOptions,
    approved: Arc<ApprovedHosts>,
    progress: Arc<ConnectProgress>,
    automatic_replays: bool,
    cancellation: Option<SecretFetchCancellation>,
) -> Result<Client, UrlFetchError> {
    let resolver = GuardedResolver {
        approved,
        connect_overrides: options.connect_overrides.clone(),
        lookup_override: options.lookup_override.clone(),
        progress: Arc::clone(&progress),
    };
    let builder = Client::builder()
        .redirect(Policy::none())
        .connect_timeout(CONNECT_TIMEOUT)
        .connector_layer(TrackConnect {
            progress,
            delay: options.connect_delay,
            cancellation,
        })
        .dns_resolver(Arc::new(resolver));
    let builder = if automatic_replays {
        builder
    } else {
        builder.retry(reqwest::retry::never())
    };

    let tls_config = match &options.tls_config {
        Some(config) => config.clone(),
        None => crate::platform_tls::client_config().map_err(|error| {
            UrlFetchError::new(format!("Failed to configure URL fetch TLS: {error}"))
        })?,
    };

    builder
        .use_preconfigured_tls(tls_config)
        .build()
        .map_err(|error| UrlFetchError::new(format!("Failed to build URL fetch client: {error}")))
}

/// Host names the SSRF check resolved and approved during one fetch, with
/// the addresses it approved. The resolver hands reqwest exactly these, so
/// the connection cannot reach an address that a second lookup returned (a
/// DNS-rebinding answer), and a redirect back to the same host needs no new
/// lookup.
#[derive(Default)]
struct ApprovedHosts(std::sync::Mutex<HashMap<String, Vec<IpAddr>>>);

impl ApprovedHosts {
    fn get(&self, host: &str) -> Option<Vec<IpAddr>> {
        self.0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get(host)
            .cloned()
    }

    fn insert(&self, host: &str, addresses: Vec<IpAddr>) {
        self.0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(host.to_string(), addresses);
    }
}

/// Connection-setup progress of the current request attempt, read when the
/// request times out to name the phase it was in. A step that a timeout
/// abandoned never reports its end, so each attempt starts from a clean
/// state and a step reports its end only to the attempt that started it.
#[derive(Default)]
struct ConnectProgress(std::sync::Mutex<AttemptProgress>);

#[derive(Default)]
struct AttemptProgress {
    attempt: u64,
    lookup_pending: bool,
    connect_pending: bool,
    /// Time spent setting up connections, summed over every attempt of the
    /// fetch, including attempts a timeout abandoned.
    connect_time: Duration,
}

impl ConnectProgress {
    fn state(&self) -> std::sync::MutexGuard<'_, AttemptProgress> {
        self.0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    fn begin_attempt(&self) {
        let mut state = self.state();
        state.attempt += 1;
        state.lookup_pending = false;
        state.connect_pending = false;
    }

    /// Returns the attempt the connection belongs to.
    fn connect_started(&self) -> u64 {
        let mut state = self.state();
        state.connect_pending = true;
        state.attempt
    }

    fn connected(&self, attempt: u64) {
        let mut state = self.state();
        if state.attempt == attempt {
            state.connect_pending = false;
        }
    }

    fn connect_pending(&self) -> bool {
        self.state().connect_pending
    }

    fn add_connect_time(&self, elapsed: Duration) {
        self.state().connect_time += elapsed;
    }

    /// Attempts begun and connection setup time so far, for the fetch times.
    fn totals(&self) -> (u64, Duration) {
        let state = self.state();
        (state.attempt, state.connect_time)
    }

    /// Returns the attempt the lookup belongs to.
    fn lookup_started(&self) -> u64 {
        let mut state = self.state();
        state.lookup_pending = true;
        state.attempt
    }

    fn lookup_answered(&self, attempt: u64) {
        let mut state = self.state();
        if state.attempt == attempt {
            state.lookup_pending = false;
        }
    }

    fn lookup_pending(&self) -> bool {
        self.state().lookup_pending
    }
}

/// Connector layer that records when a request starts and finishes setting
/// up its connection, so a timeout can tell a stalled connect from a server
/// that accepted the connection and never answered.
#[derive(Clone)]
struct TrackConnect {
    progress: Arc<ConnectProgress>,
    delay: Option<Duration>,
    cancellation: Option<SecretFetchCancellation>,
}

impl<S> tower_layer::Layer<S> for TrackConnect {
    type Service = TrackedConnector<S>;

    fn layer(&self, inner: S) -> Self::Service {
        TrackedConnector {
            inner,
            progress: Arc::clone(&self.progress),
            delay: self.delay,
            cancellation: self.cancellation.clone(),
        }
    }
}

#[derive(Clone)]
struct TrackedConnector<S> {
    inner: S,
    progress: Arc<ConnectProgress>,
    delay: Option<Duration>,
    cancellation: Option<SecretFetchCancellation>,
}

impl<S, Target> tower_service::Service<Target> for TrackedConnector<S>
where
    S: tower_service::Service<Target>,
    S::Future: Send + 'static,
    S::Response: Send + 'static,
    S::Error: Into<Box<dyn std::error::Error + Send + Sync>> + Send + 'static,
{
    type Response = S::Response;
    type Error = Box<dyn std::error::Error + Send + Sync>;
    type Future = std::pin::Pin<
        Box<dyn std::future::Future<Output = Result<S::Response, Self::Error>> + Send>,
    >;

    fn poll_ready(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx).map_err(Into::into)
    }

    fn call(&mut self, target: Target) -> Self::Future {
        let attempt = self.progress.connect_started();
        let progress = Arc::clone(&self.progress);
        let delay = self.delay;
        let cancellation = self.cancellation.clone();
        let connecting = self.inner.call(target);
        Box::pin(async move {
            // Records on drop too, so a connect a timeout abandons still
            // counts the time it took.
            let _timer = ConnectTimer {
                progress: Arc::clone(&progress),
                started: Instant::now(),
            };
            if let Some(delay) = delay {
                tokio::time::sleep(delay).await;
            }
            let connection = connecting.await.map_err(Into::into)?;
            // The inner connector includes DNS, TCP and TLS. Check again at
            // its handover boundary, before hyper can write request bytes.
            if cancellation.is_some_and(|cancel| cancel.is_cancelled()) {
                return Err(std::io::Error::from(std::io::ErrorKind::Interrupted).into());
            }
            progress.connected(attempt);
            Ok(connection)
        })
    }
}

/// Adds the time since `started` to the fetch's connection setup time when
/// dropped.
struct ConnectTimer {
    progress: Arc<ConnectProgress>,
    started: Instant,
}

impl Drop for ConnectTimer {
    fn drop(&mut self) {
        self.progress.add_connect_time(self.started.elapsed());
    }
}

/// The resolver reqwest uses for every connection of a fetch.
///
/// A host the SSRF check approved gets exactly the approved addresses. Any
/// other host is looked up here without the SSRF check: that is a proxy host,
/// or any host when private addresses are allowed. The lookup runs on its own
/// thread so the request's timeout can abandon it: the request stops waiting
/// at the fetch deadline, although the system resolver's thread may run on
/// until its lookup returns.
struct GuardedResolver {
    approved: Arc<ApprovedHosts>,
    connect_overrides: Vec<(String, SocketAddr)>,
    lookup_override: Option<HostLookup>,
    progress: Arc<ConnectProgress>,
}

impl reqwest::dns::Resolve for GuardedResolver {
    fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
        let host = name.as_str().to_string();
        // Port 0 tells reqwest to use the URL's port.
        let ready = |addresses: Vec<SocketAddr>| -> reqwest::dns::Resolving {
            Box::pin(std::future::ready(Ok(
                Box::new(addresses.into_iter()) as reqwest::dns::Addrs
            )))
        };
        if let Some((_, address)) = self
            .connect_overrides
            .iter()
            .find(|(override_host, _)| *override_host == host)
        {
            return ready(vec![*address]);
        }
        if let Some(addresses) = self.approved.get(&host) {
            return ready(
                addresses
                    .into_iter()
                    .map(|ip| SocketAddr::new(ip, 0))
                    .collect(),
            );
        }
        let progress = Arc::clone(&self.progress);
        let attempt = progress.lookup_started();
        let (sender, receiver) = tokio::sync::oneshot::channel();
        let lookup = self.lookup_override.clone();
        thread::spawn(move || {
            let _ = sender.send(lookup_host(&host, lookup.as_ref()));
        });
        Box::pin(async move {
            let answer: Result<io::Result<Vec<IpAddr>>, _> = receiver.await;
            progress.lookup_answered(attempt);
            let addresses = answer
                .unwrap_or_else(|_| Err(io::Error::other("host lookup stopped before answering")))
                .map_err(|error| Box::new(error) as Box<dyn Error + Send + Sync>)?;
            Ok(
                Box::new(addresses.into_iter().map(|ip| SocketAddr::new(ip, 0)))
                    as reqwest::dns::Addrs,
            )
        })
    }
}

fn lookup_host(host: &str, lookup_override: Option<&HostLookup>) -> io::Result<Vec<IpAddr>> {
    if let Some(lookup) = lookup_override {
        return lookup(host);
    }
    Ok((host, 0).to_socket_addrs()?.map(|addr| addr.ip()).collect())
}

/// Refuse a URL that is not http(s) or that points at a private address.
/// A host name is resolved under the fetch deadline and its approved
/// addresses are recorded in `approved` for the resolver.
fn validate_public_url(
    url: &Url,
    options: &UrlFetchOptions,
    deadline: &FetchDeadline,
    approved: &ApprovedHosts,
) -> Result<(), UrlFetchError> {
    let started = Instant::now();
    let result = check_public_url(url, options, deadline, approved);
    let elapsed = started.elapsed();
    timing::record(|times| times.lookup += elapsed);
    result
}

/// [`validate_public_url`] without its timing.
fn check_public_url(
    url: &Url,
    options: &UrlFetchOptions,
    deadline: &FetchDeadline,
    approved: &ApprovedHosts,
) -> Result<(), UrlFetchError> {
    if url.scheme() != "http" && url.scheme() != "https" {
        return Err(UrlFetchError::new(format!(
            "Only http:// and https:// URLs are supported, got: {}:",
            url.scheme()
        )));
    }
    if options.allow_private {
        return Ok(());
    }

    let host = url
        .host_str()
        .ok_or_else(|| UrlFetchError::new(format!("URL missing host: {url}")))?;
    let host_for_parse = host
        .trim_matches(['[', ']'])
        .split('%')
        .next()
        .unwrap_or(host);

    if let Ok(ip) = host_for_parse.parse::<IpAddr>() {
        reject_private_ip(host, ip)?;
        return Ok(());
    }
    if host_for_parse.contains(':') {
        return Err(UrlFetchError::new(format!(
            "Blocked private URL host {host} ({host_for_parse})"
        )));
    }
    if approved.get(host_for_parse).is_some() {
        return Ok(());
    }

    let addresses = resolve_host_ips(host_for_parse, url.as_str(), options, deadline)?;
    if addresses.is_empty() {
        return Err(UrlFetchError::new(format!(
            "Failed to resolve URL host {host}"
        )));
    }
    for ip in &addresses {
        reject_private_ip(host, *ip)?;
    }
    approved.insert(host_for_parse, addresses);
    Ok(())
}

/// Resolve `host` on a helper thread and wait for it no longer than the
/// fetch deadline; the system resolver itself has no timeout.
fn resolve_host_ips(
    host: &str,
    url: &str,
    options: &UrlFetchOptions,
    deadline: &FetchDeadline,
) -> Result<Vec<IpAddr>, UrlFetchError> {
    if let Some((_, ips)) = options
        .public_host_overrides
        .iter()
        .find(|(override_host, _)| override_host == host)
    {
        return Ok(ips.clone());
    }

    let remaining = deadline.remaining();
    if remaining.is_zero() {
        return Err(deadline.timeout_error(FetchPhase::Dns, url));
    }
    let (sender, receiver) = mpsc::channel();
    let owned_host = host.to_string();
    let lookup = options.lookup_override.clone();
    thread::spawn(move || {
        let _ = sender.send(lookup_host(&owned_host, lookup.as_ref()));
    });
    match receiver.recv_timeout(remaining) {
        Ok(Ok(addresses)) => Ok(addresses),
        Ok(Err(error)) => Err(UrlFetchError::new(format!(
            "Failed to resolve URL host {host}: {error}"
        ))),
        Err(mpsc::RecvTimeoutError::Timeout) => Err(deadline.timeout_error(FetchPhase::Dns, url)),
        Err(mpsc::RecvTimeoutError::Disconnected) => Err(UrlFetchError::new(format!(
            "Failed to resolve URL host {host}: lookup stopped before answering"
        ))),
    }
}

fn reject_private_ip(host: &str, ip: IpAddr) -> Result<(), UrlFetchError> {
    if is_private_ip(ip) {
        return Err(UrlFetchError::new(format!(
            "Blocked private URL host {host} ({ip})"
        )));
    }
    Ok(())
}

/// True for any private/link-local/CGNAT/benchmark/multicast/reserved/loopback
/// address (the full set this module refuses to fetch). Exposed so the semantic
/// embedding SSRF guard shares one authoritative range list instead of keeping a
/// drifting copy. Note: this INCLUDES loopback — callers that intentionally
/// allow loopback (e.g. a local Ollama endpoint) must exclude it themselves.
pub fn is_private_or_reserved_ip(ip: IpAddr) -> bool {
    is_private_ip(ip)
}

fn is_private_ip(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(ipv4) => is_private_ipv4(ipv4),
        IpAddr::V6(ipv6) => is_private_ipv6(ipv6),
    }
}

fn is_private_ipv4(ip: Ipv4Addr) -> bool {
    let [a, b, _, _] = ip.octets();
    a == 0
        || a == 10
        || a == 127
        || (a == 172 && (16..=31).contains(&b))
        || (a == 192 && b == 168)
        || (a == 169 && b == 254)
        // RFC 6598 Shared Address Space (CGNAT): 100.64.0.0/10. Not globally
        // routable; used for provider/VPC-internal endpoints — must not be
        // reachable via SSRF.
        || (a == 100 && (64..=127).contains(&b))
        // RFC 2544 benchmark subnet: 198.18.0.0/15. Reserved, non-routable.
        || (a == 198 && (18..=19).contains(&b))
        || a >= 224
}

fn is_private_ipv6(ip: Ipv6Addr) -> bool {
    let segments = ip.segments();
    let top_six_zero = segments[..6].iter().all(|segment| *segment == 0);
    let is_mapped = segments[..5].iter().all(|segment| *segment == 0) && segments[5] == 0xffff;
    if is_mapped || top_six_zero {
        let embedded = Ipv4Addr::new(
            (segments[6] >> 8) as u8,
            (segments[6] & 0xff) as u8,
            (segments[7] >> 8) as u8,
            (segments[7] & 0xff) as u8,
        );
        return is_private_ipv4(embedded);
    }

    let first = segments[0];
    // fe80::/10 link-local, fec0::/10 deprecated site-local (still routed
    // inside some networks), fc00::/7 unique local, ff00::/8 multicast.
    (0xfe80..=0xfeff).contains(&first) || (0xfc00..=0xfdff).contains(&first) || first >= 0xff00
}

const BINARY_SNIFF_PREFIX: usize = 8 * 1024;

fn body_contains_nul_in_prefix(body: &[u8]) -> bool {
    let end = body.len().min(BINARY_SNIFF_PREFIX);
    body[..end].contains(&0)
}

/// Resolve cache extension: URL path (parsed, percent-decoded) first for source
/// languages AFT parses; otherwise content-type mapping.
fn resolve_fetch_extension(url: &Url, content_type: &str) -> Option<(&'static str, bool)> {
    if let Some(ext) = extension_from_url_path(url) {
        return Some((ext, true));
    }
    resolve_extension_from_content_type(content_type).map(|ext| (ext, false))
}

#[rustfmt::skip]
test_support_visibility! {

fn extension_from_url_path(url: &Url) -> Option<&'static str> {
    let path = url.path();
    if path.is_empty() || path == "/" {
        return None;
    }
    let segment = path.rsplit('/').next().unwrap_or(path);
    let file_name = percent_decode_path_segment(segment);
    let dot = file_name.rfind('.')?;
    let ext = &file_name[dot + 1..];
    if ext.is_empty() {
        return None;
    }
    let probe = Path::new("file").with_extension(ext);
    if language_by_extension(&probe).is_some() {
        static_extension_for_lang_ext(ext)
    } else {
        None
    }
}
}

fn percent_decode_path_segment(segment: &str) -> String {
    let mut out = String::with_capacity(segment.len());
    let bytes = segment.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            if let (Some(h1), Some(h2)) = (from_hex(bytes[i + 1]), from_hex(bytes[i + 2])) {
                out.push(char::from(h1 << 4 | h2));
                i += 3;
                continue;
            }
        }
        out.push(bytes[i] as char);
        i += 1;
    }
    out
}

fn from_hex(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

#[rustfmt::skip]
test_support_visibility! {

/// Dotted cache extension for a path extension that `detect_language` accepts.
fn static_extension_for_lang_ext(ext: &str) -> Option<&'static str> {
    match ext.to_ascii_lowercase().as_str() {
        "ts" | "mts" | "cts" => Some(".ts"),
        "tsx" => Some(".tsx"),
        "js" => Some(".js"),
        "jsx" => Some(".jsx"),
        "mjs" => Some(".mjs"),
        "cjs" => Some(".cjs"),
        "py" | "pyi" => Some(".py"),
        "rs" => Some(".rs"),
        "go" => Some(".go"),
        "c" => Some(".c"),
        "h" => Some(".h"),
        "cc" | "cpp" | "cxx" | "hpp" | "hh" => Some(".cpp"),
        "zig" => Some(".zig"),
        "cs" => Some(".cs"),
        "sh" | "bash" | "zsh" => Some(".sh"),
        "html" | "htm" => Some(".html"),
        "md" | "markdown" | "mdx" => Some(".md"),
        "sol" => Some(".sol"),
        "scss" => Some(".scss"),
        "vue" => Some(".vue"),
        "json" | "jsonc" => Some(".json"),
        "scala" | "sc" => Some(".scala"),
        "java" => Some(".java"),
        "rb" => Some(".rb"),
        "kt" | "kts" => Some(".kt"),
        "swift" => Some(".swift"),
        "inc" | "php" => Some(".php"),
        "lua" => Some(".lua"),
        "pl" | "pm" | "t" => Some(".pl"),
        "yaml" | "yml" => Some(".yaml"),
        _ => None,
    }
}
}

fn resolve_extension_from_content_type(content_type: &str) -> Option<&'static str> {
    let lower = content_type.to_ascii_lowercase();
    let media_type = lower
        .split(';')
        .next()
        .unwrap_or("")
        .split(',')
        .next()
        .unwrap_or("")
        .trim();

    match media_type {
        "text/html"
        | "application/xhtml+xml"
        | "application/vnd.github.html"
        | "application/vnd.github+html" => Some(".html"),
        "text/markdown"
        | "text/x-markdown"
        | "application/markdown"
        | "application/vnd.github.raw"
        | "application/vnd.github+raw"
        | "application/vnd.github.v3.raw"
        | "text/plain" => Some(".md"),
        "application/json" | "application/ld+json" => Some(".json"),
        other if other.ends_with("+json") => Some(".json"),
        "text/javascript" | "application/javascript" | "application/ecmascript" => Some(".js"),
        "text/typescript" | "application/typescript" => Some(".ts"),
        _ => None,
    }
}

fn convert_html_body_to_markdown(body: &[u8], url: &str) -> Result<Vec<u8>, UrlFetchError> {
    let started = Instant::now();
    let result = html_body_to_markdown(body, url);
    let elapsed = started.elapsed();
    timing::record(|times| times.convert += elapsed);
    result
}

/// [`convert_html_body_to_markdown`] without its timing.
fn html_body_to_markdown(body: &[u8], url: &str) -> Result<Vec<u8>, UrlFetchError> {
    let html = String::from_utf8_lossy(body);
    let mut markdown = html_to_markdown_converter()
        .convert(&html)
        .map_err(|error| {
            UrlFetchError::new(format!(
                "Failed to convert HTML from {url} to Markdown: {error}"
            ))
        })?;
    if !markdown.ends_with('\n') {
        markdown.push('\n');
    }
    Ok(markdown.into_bytes())
}

/// Page chrome dropped from the converted Markdown. The `<pre>` text walker
/// skips the same tags so a copy button inside a code block stays out of it.
const SKIPPED_HTML_TAGS: [&str; 8] = [
    "head", "script", "style", "nav", "footer", "aside", "noscript", "button",
];

fn html_to_markdown_converter() -> HtmlToMarkdown {
    HtmlToMarkdown::builder()
        .skip_tags(SKIPPED_HTML_TAGS.to_vec())
        .add_handler(
            vec!["pre"],
            |handlers: &dyn Handlers, element: Element| -> Option<HandlerResult> {
                if node_has_descendant_tag(element.node, "code") {
                    Some(fenced_code_block(&element).into())
                } else {
                    handlers.fallback(element)
                }
            },
        )
        .add_handler(
            vec!["a"],
            |handlers: &dyn Handlers, element: Element| -> Option<HandlerResult> {
                if is_permalink_anchor(&element)
                    || handlers.walk_children(element.node).content.trim() == "§"
                {
                    None
                } else if element_attr_value(&element, "href")
                    .is_some_and(|href| href.trim() == "#")
                {
                    Some(handlers.walk_children(element.node).content.into())
                } else {
                    handlers.fallback(element)
                }
            },
        )
        .add_handler(
            vec!["header"],
            |handlers: &dyn Handlers, element: Element| -> Option<HandlerResult> {
                if should_skip_header(&element) {
                    None
                } else {
                    handlers.fallback(element)
                }
            },
        )
        .add_handler(
            vec!["span"],
            |handlers: &dyn Handlers, element: Element| -> Option<HandlerResult> {
                if element_has_class_token(&element, "token-line") {
                    let mut content = handlers.walk_children(element.node).content;
                    content.push('\n');
                    Some(content.into())
                } else {
                    handlers.fallback(element)
                }
            },
        )
        .build()
}

/// Render a `<pre>` that holds code as one fenced block built from the raw
/// text of the whole `<pre>`, not just its `<code>` child.
///
/// htmd fences only the `<code>` element and renders whatever follows it in
/// the `<pre>` as ordinary text. Real pages close `</code>` early: the Chrome
/// DevTools docs end `<code>` in the middle of a JSON string, and the HTML
/// parser then leaves the rest of the block as `<pre>` children after the
/// `<code>`. A browser still shows that as one block, so the Markdown must too.
/// Walking the text ourselves also keeps htmd's text handling (escaping,
/// collapsing blank lines) away from code that has to be copied verbatim.
fn fenced_code_block(element: &Element<'_>) -> String {
    let mut text = PreformattedText::default();
    text.collect(element.node);
    // A break still pending after the last line ends the block, so it is
    // dropped rather than written.
    let mut code = text.output;
    // The line break before `</code>` or `</pre>` ends the last line; it is
    // not an extra blank line inside the block.
    if code.ends_with('\n') {
        code.pop();
    }
    let fence = code_fence_for(&code);
    let language = find_descendant_element(element.node, "code")
        .and_then(|code| node_class_attr(&code))
        .as_deref()
        .and_then(language_from_class)
        .or_else(|| element_attr_value(element, "class").and_then(language_from_class));

    let mut block = String::from("\n\n");
    block.push_str(&fence);
    if let Some(language) = language {
        block.push_str(&language);
    }
    block.push('\n');
    block.push_str(&code);
    block.push('\n');
    block.push_str(&fence);
    block.push_str("\n\n");
    block
}

/// How an element inside a `<pre>` ends the text line it holds.
///
/// Many highlighters emit one element per source line with no newline text
/// between them: Prism `span.token-line` (Docusaurus), Shiki `span.line`,
/// `<li>` per line, table rows (highlight.js line-numbers plugin), or plain
/// per-line `<div>`s. A browser still shows separate lines, so the copied
/// text must break after each one.
#[derive(Clone, Copy, PartialEq, Eq)]
enum PreLineBreak {
    /// Inline element: adds no break.
    None,
    /// One source line, so it always ends a line, even when empty (an empty
    /// row or `span.line` is a blank line of code).
    Line,
    /// Generic block (`<div>`, `<p>`): ends a line only when it holds text,
    /// so an empty line-number `<div>` beside the code does not add a blank
    /// line.
    Block,
}

fn pre_line_break(tag: &str, class: Option<&str>) -> PreLineBreak {
    let has_class =
        |token: &str| class.is_some_and(|value| value.split_ascii_whitespace().any(|c| c == token));
    match tag {
        "tr" | "li" => PreLineBreak::Line,
        "span" if has_class("token-line") || has_class("line") => PreLineBreak::Line,
        "div" | "p" => PreLineBreak::Block,
        _ => PreLineBreak::None,
    }
}

/// The raw text of a `<pre>`, collected exactly as written: no escaping and
/// no whitespace changes.
///
/// A per-line element (see [`PreLineBreak`]) ends its line with a *pending*
/// break rather than a written one. Some highlighters already put a newline
/// between their line elements (Shiki's default output does) and some do
/// not; the pending break is written only when more of the block follows
/// and is absorbed when that next text already starts with a newline, so
/// both layouts give one line per element.
#[derive(Default)]
struct PreformattedText {
    output: String,
    pending_break: bool,
}

impl PreformattedText {
    fn flush_pending_break(&mut self) {
        if self.pending_break {
            self.output.push('\n');
            self.pending_break = false;
        }
    }

    fn push_text(&mut self, text: &str) {
        if text.is_empty() {
            return;
        }
        if self.pending_break && text.starts_with('\n') {
            self.pending_break = false;
        }
        self.flush_pending_break();
        self.output.push_str(text);
    }

    fn collect(&mut self, node: &Node) {
        for child in node.children.borrow().iter() {
            match &child.data {
                NodeData::Text { contents } => self.push_text(&contents.borrow()),
                NodeData::Element { name, attrs, .. } => {
                    let tag = name.local.as_ref();
                    if SKIPPED_HTML_TAGS.contains(&tag) {
                        continue;
                    }
                    if tag == "br" {
                        // A `<br>` right after a finished line starts an
                        // empty line, as it does in a browser.
                        self.flush_pending_break();
                        self.output.push('\n');
                        continue;
                    }
                    let line_break = {
                        let attrs = attrs.borrow();
                        let class = attrs
                            .iter()
                            .find(|attr| attr.name.local.as_ref() == "class")
                            .map(|attr| attr.value.as_ref());
                        pre_line_break(tag, class)
                    };
                    if line_break == PreLineBreak::None {
                        self.collect(child);
                        continue;
                    }
                    // A new line element starts on its own line, so the
                    // previous one's break is written before measuring this
                    // one's text.
                    self.flush_pending_break();
                    let line_start = self.output.len();
                    self.collect(child);
                    let line = &self.output[line_start..];
                    let line_ended = self.pending_break || line.ends_with('\n');
                    let ends_line = match line_break {
                        PreLineBreak::None => false,
                        PreLineBreak::Line => !line_ended,
                        PreLineBreak::Block => !line.is_empty() && !line_ended,
                    };
                    if ends_line {
                        self.pending_break = true;
                    }
                }
                _ => {}
            }
        }
    }
}

/// A backtick fence one longer than the longest backtick run in `code`
/// (at least three), so a run inside the code can never close the block.
fn code_fence_for(code: &str) -> String {
    let mut longest = 0;
    let mut current = 0;
    for ch in code.chars() {
        if ch == '`' {
            current += 1;
            longest = longest.max(current);
        } else {
            current = 0;
        }
    }
    "`".repeat((longest + 1).max(3))
}

/// The `xyz` of a `language-xyz` class token, the convention both Prism and
/// highlight.js use to name a code block's language.
fn language_from_class(class: &str) -> Option<String> {
    class
        .split_ascii_whitespace()
        .find_map(|token| token.strip_prefix("language-"))
        .filter(|language| !language.is_empty())
        .map(str::to_string)
}

fn node_has_descendant_tag(node: &Node, tag: &str) -> bool {
    find_descendant_element(node, tag).is_some()
}

/// The first element named `tag` below `node`, depth first.
fn find_descendant_element(node: &Node, tag: &str) -> Option<Rc<Node>> {
    for child in node.children.borrow().iter() {
        if let NodeData::Element { name, .. } = &child.data {
            if name.local.as_ref() == tag {
                return Some(Rc::clone(child));
            }
            if let Some(found) = find_descendant_element(child, tag) {
                return Some(found);
            }
        }
    }
    None
}

fn node_class_attr(node: &Node) -> Option<String> {
    match &node.data {
        NodeData::Element { attrs, .. } => attrs
            .borrow()
            .iter()
            .find(|attr| attr.name.local.as_ref() == "class")
            .map(|attr| attr.value.to_string()),
        _ => None,
    }
}

fn is_permalink_anchor(element: &Element<'_>) -> bool {
    element_has_class_token(element, "hash-link")
        || element_has_class_token(element, "doc-anchor")
        || element_attr_value(element, "aria-label")
            .is_some_and(|value| value.to_ascii_lowercase().starts_with("direct link to"))
}

fn should_skip_header(element: &Element<'_>) -> bool {
    element_has_class_token(element, "navbar")
        || element_has_class_token(element, "site-header")
        || element_has_class_token(element, "site-nav")
        || element_has_class_token(element, "topbar")
        || element_attr_value(element, "role")
            .is_some_and(|value| value.eq_ignore_ascii_case("banner"))
        || element_attr_value(element, "id").is_some_and(|value| {
            let value = value.to_ascii_lowercase();
            value.contains("navbar") || value.contains("site-header") || value.contains("site-nav")
        })
}

fn element_has_class_token(element: &Element<'_>, token: &str) -> bool {
    element_attr_value(element, "class")
        .is_some_and(|value| value.split_ascii_whitespace().any(|class| class == token))
}

fn element_attr_value<'a>(element: &'a Element<'_>, name: &str) -> Option<&'a str> {
    element
        .attrs
        .iter()
        .find(|attr| attr.name.local.as_ref() == name)
        .map(|attr| attr.value.as_ref())
}

enum BodyReadEvent {
    Chunk(sensitive::Bytes),
    Done,
    /// A read failed after waiting this long for data.
    Error(io::ErrorKind, sensitive::Bytes, Duration),
}

/// Read at most [`MAX_RESPONSE_BYTES`] (plus one lookahead byte) of the body.
/// Two limits stop a slow body: no data for [`BODY_CHUNK_TIMEOUT`], and the
/// fetch deadline, which also stops a server that sends a little data just
/// often enough to avoid the stall limit.
///
/// Whether a failed read was a timeout is decided mainly by time: reqwest
/// reports both its per-read limit and its whole-request limit as an
/// `io::Error` of kind `Other` (its blocking `Read` impl wraps the timeout
/// with `into_io`), and which of those timers or this function's own wait
/// fires first differs between platforms. So a failed read is a body-phase
/// timeout when the fetch deadline has passed, when the read had waited at
/// least [`BODY_CHUNK_TIMEOUT`] for data, or when its kind is `TimedOut` or
/// `WouldBlock`.
fn read_response_body(
    response: impl Read + Send + 'static,
    url: &str,
    deadline: &FetchDeadline,
) -> Result<(Vec<u8>, bool), UrlFetchError> {
    read_response_body_with(response, url, deadline, &|detail: &str| detail.to_string())
        .map(|(body, truncated)| (body.into_plain_vec(), truncated))
}

/// [`read_response_body`] with `detail` applied to the text of a failed read
/// before it goes into the error, so a placeholder fetch can scrub it.
fn read_response_body_with(
    response: impl Read + Send + 'static,
    url: &str,
    deadline: &FetchDeadline,
    detail: &dyn Fn(&str) -> String,
) -> Result<(sensitive::Bytes, bool), UrlFetchError> {
    // Bound the producer, not just its consumer: an unbounded channel can
    // queue the entire response before the caller notices the byte ceiling.
    let (tx, rx) = mpsc::sync_channel(1);
    let factory = sensitive::Factory::current();
    let worker = factory.clone();
    thread::spawn(move || {
        // One lookahead byte distinguishes an exact-size body from a cut,
        // including chunked responses without Content-Length.
        let mut response = response.take(MAX_RESPONSE_BYTES + 1);
        let mut buffer = worker.zeroed(16 * 1024);
        loop {
            let read_started = Instant::now();
            match response.read(&mut buffer) {
                Ok(0) => {
                    let _ = tx.send(BodyReadEvent::Done);
                    break;
                }
                Ok(n) => {
                    if tx
                        .send(BodyReadEvent::Chunk(worker.copy(&buffer[..n])))
                        .is_err()
                    {
                        break;
                    }
                }
                Err(error) => {
                    let kind = error.kind();
                    let message = worker.format(format_args!("{error}"));
                    let waited = read_started.elapsed();
                    let _ = tx.send(BodyReadEvent::Error(kind, message, waited));
                    break;
                }
            }
        }
    });

    /// Records the body's read time and the bytes received when dropped, so
    /// every way out of the read loop counts.
    struct BodyTimer {
        started: Instant,
        bytes: u64,
    }
    impl Drop for BodyTimer {
        fn drop(&mut self) {
            let (elapsed, bytes) = (self.started.elapsed(), self.bytes);
            timing::record(|times| {
                times.body += elapsed;
                times.body_bytes += bytes;
            });
        }
    }
    let mut timer = BodyTimer {
        started: Instant::now(),
        bytes: 0,
    };
    let mut chunks = factory.with_capacity(0);
    let mut total = 0u64;
    let slow_body_error = || {
        if deadline.expired() {
            deadline.timeout_error(FetchPhase::Body, url)
        } else {
            body_stall_error(url)
        }
    };
    loop {
        let wait = BODY_CHUNK_TIMEOUT.min(deadline.remaining());
        if wait.is_zero() {
            return Err(deadline.timeout_error(FetchPhase::Body, url));
        }
        match rx.recv_timeout(wait) {
            Ok(BodyReadEvent::Chunk(chunk)) => {
                let remaining = (MAX_RESPONSE_BYTES - total) as usize;
                chunks.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
                total += chunk.len() as u64;
                timer.bytes = total;
                if total > MAX_RESPONSE_BYTES {
                    return Ok((chunks, true));
                }
            }
            Ok(BodyReadEvent::Done) => return Ok((chunks, false)),
            Ok(BodyReadEvent::Error(kind, message, waited)) => {
                return Err(body_read_failure(
                    deadline,
                    url,
                    kind,
                    &detail(std::str::from_utf8(&message).unwrap_or_default()),
                    waited,
                ));
            }
            Err(mpsc::RecvTimeoutError::Timeout) => return Err(slow_body_error()),
            Err(mpsc::RecvTimeoutError::Disconnected) => {
                return Err(UrlFetchError::new(format!(
                    "Failed to read response body for {url}: body reader stopped unexpectedly"
                )));
            }
        }
    }
}

/// How a failed body read is reported. It is a body-phase timeout when the
/// fetch deadline has passed or the read had waited at least
/// [`BODY_CHUNK_TIMEOUT`], whatever its kind (see [`read_response_body`]);
/// the kinds `TimedOut` and `WouldBlock` also count as a body stall.
fn body_read_failure(
    deadline: &FetchDeadline,
    url: &str,
    kind: io::ErrorKind,
    message: &str,
    waited: Duration,
) -> UrlFetchError {
    if deadline.expired() {
        return deadline.timeout_error(FetchPhase::Body, url);
    }
    if waited >= BODY_CHUNK_TIMEOUT || is_body_stall_kind(kind) {
        return body_stall_error(url);
    }
    if message.is_empty() {
        return UrlFetchError::new(format!("Failed to read response body for {url}"));
    }
    UrlFetchError::new(format!("Failed to read response body for {url}: {message}"))
}

fn body_stall_error(url: &str) -> UrlFetchError {
    UrlFetchError::timeout(
        FetchPhase::Body,
        format!(
            "Body read stalled (no data for {}ms) fetching {url}",
            BODY_CHUNK_TIMEOUT.as_millis()
        ),
    )
}

fn is_body_stall_kind(kind: io::ErrorKind) -> bool {
    matches!(kind, io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock)
}

fn atomic_write(
    final_path: &Path,
    bytes: &[u8],
    options: &UrlFetchOptions,
) -> Result<(), UrlFetchError> {
    let parent = final_path.parent().unwrap_or_else(|| Path::new("."));
    crate::private_storage::create_dir_all(parent).map_err(|error| {
        UrlFetchError::new(format!(
            "Failed to create URL cache parent {}: {error}",
            parent.display()
        ))
    })?;

    let file_name = final_path
        .file_name()
        .and_then(|name| name.to_str())
        .ok_or_else(|| {
            UrlFetchError::new(format!("Invalid cache path: {}", final_path.display()))
        })?;
    let tmp_path = final_path.with_file_name(format!(
        "{file_name}.tmp-{}-{}",
        std::process::id(),
        random_nonce()
    ));

    let write_result = (|| -> io::Result<()> {
        let mut file = crate::private_storage::create(&tmp_path)?;
        file.write_all(bytes)?;
        file.flush()?;
        Ok(())
    })();
    if let Err(error) = write_result {
        let _ = fs::remove_file(&tmp_path);
        return Err(UrlFetchError::new(format!(
            "Failed to write URL cache temp file {}: {error}",
            tmp_path.display()
        )));
    }

    if let Some(observer) = &options.atomic_write_observer {
        observer(&tmp_path, final_path);
    }

    fs::rename(&tmp_path, final_path).map_err(|error| {
        let _ = fs::remove_file(&tmp_path);
        UrlFetchError::new(format!(
            "Failed to finalize URL cache file {}: {error}",
            final_path.display()
        ))
    })
}

fn random_nonce() -> String {
    let mut bytes = [0u8; 8];
    if getrandom::fill(&mut bytes).is_err() {
        let fallback = now_ms() ^ u64::from(std::process::id());
        bytes = fallback.to_le_bytes();
    }
    let mut out = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        use std::fmt::Write as _;
        let _ = write!(out, "{byte:02x}");
    }
    out
}

fn now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis()
        .try_into()
        .unwrap_or(u64::MAX)
}

fn reqwest_error_detail(error: &reqwest::Error) -> String {
    if error.is_timeout() {
        return format!("timeout: {error}");
    }
    if let Some(source) = error.source() {
        return format!("{source}");
    }
    error.to_string()
}

/// Where the time of one tool call's URL fetches went, for the daemon's
/// slow-call log line.
///
/// A fetch spends almost all of its time off the calling thread: the HTTP
/// client runs the connection and the body read on its own runtime, and name
/// lookups run on helper threads. So a slow URL outline shows a long `exec`
/// with almost no CPU, the same as a call blocked on a lock. These counters
/// say which part of the fetch the time went to.
///
/// Collection is per thread and only while a [`FetchTimesScope`] is open on
/// that thread; anywhere else every recorder costs one thread-local read and
/// records nothing. Only what the calling thread waited for is recorded, so
/// the totals stay within the call's own wall time (connection setup is the
/// exception: it is measured where it runs and is part of `first_byte`).
pub mod timing {
    use std::cell::RefCell;
    use std::fmt::Write as _;
    use std::time::Duration;

    use super::FetchPhase;

    /// Every URL fetch one call made, summed.
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
    pub struct UrlFetchTimes {
        /// Documents asked for: downloads, cache hits and failures answered
        /// from memory.
        pub fetches: u32,
        /// Served from the URL cache with no request sent.
        pub cache_hits: u32,
        /// Answered with a failure remembered from an earlier fetch of the
        /// same URL, with no request sent.
        pub remembered_failures: u32,
        /// The private-address check's host name lookups, which run before
        /// each request (and before a cache hit is served).
        pub lookup: Duration,
        /// Connection setup (TCP and TLS) inside the HTTP client, summed over
        /// attempts. Part of `first_byte`.
        pub connect: Duration,
        /// From sending each request until its response headers arrived,
        /// including connection setup, the server's own time to answer, and
        /// any retry backoff; summed over redirect hops.
        pub first_byte: Duration,
        /// Reading response bodies.
        pub body: Duration,
        /// Body bytes received.
        pub body_bytes: u64,
        /// Converting HTML pages to Markdown, on the calling thread.
        pub convert: Duration,
        /// Redirects followed.
        pub redirects: u32,
        /// Requests sent again after a transient connection failure.
        pub retries: u32,
        /// The last failed fetch's error code and, for a timeout, its phase.
        pub error: Option<(&'static str, Option<FetchPhase>)>,
    }

    impl UrlFetchTimes {
        /// `url_fetch=fetches:1,cache_hits:0,remembered:0,lookup:2.10,
        /// connect:40.00,first_byte:5800.00,body:300.00,bytes:51234,
        /// convert:4.00,redirects:0,retries:0` (milliseconds for times), then
        /// `,error:<code>[/<phase>]` when a fetch failed. One field with no
        /// spaces and no URL: the host is already in the call's target kind.
        pub fn render(&self) -> String {
            let ms = |duration: Duration| duration.as_secs_f64() * 1000.0;
            let mut out = format!(
                "url_fetch=fetches:{},cache_hits:{},remembered:{},lookup:{:.2},connect:{:.2},first_byte:{:.2},body:{:.2},bytes:{},convert:{:.2},redirects:{},retries:{}",
                self.fetches,
                self.cache_hits,
                self.remembered_failures,
                ms(self.lookup),
                ms(self.connect),
                ms(self.first_byte),
                ms(self.body),
                self.body_bytes,
                ms(self.convert),
                self.redirects,
                self.retries,
            );
            if let Some((code, phase)) = self.error {
                let _ = write!(out, ",error:{code}");
                if let Some(phase) = phase {
                    let _ = write!(out, "/{}", phase.as_str());
                }
            }
            out
        }
    }

    thread_local! {
        static COLLECTOR: RefCell<Option<UrlFetchTimes>> = const { RefCell::new(None) };
    }

    /// An open collection on this thread; see [`begin`].
    #[must_use = "a scope collects nothing once dropped"]
    pub struct FetchTimesScope {
        /// This scope opened the collection. A scope opened while another
        /// was open leaves the outer one collecting and reports nothing.
        owns: bool,
    }

    /// Start collecting this thread's URL fetch times.
    pub fn begin() -> FetchTimesScope {
        let owns = COLLECTOR.with(|collector| {
            let mut collector = collector.borrow_mut();
            if collector.is_some() {
                return false;
            }
            *collector = Some(UrlFetchTimes::default());
            true
        });
        FetchTimesScope { owns }
    }

    impl FetchTimesScope {
        /// Stop collecting. `None` when no fetch ran, or for a scope nested
        /// inside another.
        pub fn finish(mut self) -> Option<UrlFetchTimes> {
            if !self.owns {
                return None;
            }
            self.owns = false;
            COLLECTOR
                .with(|collector| collector.replace(None))
                .filter(|times| times.fetches > 0)
        }
    }

    impl Drop for FetchTimesScope {
        fn drop(&mut self) {
            // An early return or a panic still closes the collection, so the
            // next call on this thread starts clean.
            if self.owns {
                COLLECTOR.with(|collector| collector.replace(None));
            }
        }
    }

    /// Apply `update` to the open collection, if there is one.
    pub(super) fn record(update: impl FnOnce(&mut UrlFetchTimes)) {
        COLLECTOR.with(|collector| {
            if let Some(times) = collector.borrow_mut().as_mut() {
                update(times);
            }
        });
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use url::Url;

    #[test]
    fn h_header_url_cache_preserves_ambiguous_extension() {
        assert_eq!(super::static_extension_for_lang_ext("h"), Some(".h"));
    }

    fn write_cache_entry(storage: &Path, hash: &str, url: &str, fetched_at: u64) -> PathBuf {
        let dir = cache_dir(storage);
        fs::create_dir_all(&dir).unwrap();
        let meta = CacheMeta {
            url: url.to_string(),
            content_type: "text/markdown".to_string(),
            extension: ".md".to_string(),
            fetched_at,
            download_truncated: false,
            downloaded_bytes: 4,
            total_bytes: Some(4),
        };
        fs::write(content_path(storage, hash, ".md"), "body").unwrap();
        let meta_file = meta_path(storage, hash);
        fs::write(&meta_file, serde_json::to_vec(&meta).unwrap()).unwrap();
        meta_file
    }

    fn cleanup_counting_reads(storage: &Path, now: u64) -> (usize, usize) {
        CLEANUP_META_READS.with(|reads| reads.set(0));
        let removed = cleanup_url_cache_at(storage, now).unwrap();
        (removed, CLEANUP_META_READS.with(std::cell::Cell::get))
    }

    /// Every configure sweeps the URL cache, so a sweep must not reopen
    /// metadata files that have not changed since the previous sweep.
    #[test]
    fn url_cache_cleanup_does_not_reread_unchanged_metadata() {
        let storage = tempfile::tempdir().unwrap();
        let now = 10 * CACHE_TTL_MS;
        for index in 0..3 {
            write_cache_entry(
                storage.path(),
                &format!("fresh{index}"),
                "https://example.com/a",
                now - 1_000,
            );
        }
        let stale = write_cache_entry(
            storage.path(),
            "stale",
            "https://example.com/b",
            now - CACHE_TTL_MS - 1,
        );

        assert_eq!(cleanup_counting_reads(storage.path(), now), (1, 4));
        assert!(!stale.exists());
        assert!(!content_path(storage.path(), "stale", ".md").exists());

        // Nothing changed: no metadata file is opened again.
        assert_eq!(cleanup_counting_reads(storage.path(), now), (0, 0));
    }

    /// A remembered fetch time is still compared with the current time, and a
    /// rewritten metadata file is read again, so the memo never keeps an entry
    /// alive past its TTL.
    #[test]
    fn url_cache_cleanup_memo_still_expires_and_notices_rewrites() {
        let storage = tempfile::tempdir().unwrap();
        let now = 10 * CACHE_TTL_MS;
        let kept = write_cache_entry(storage.path(), "kept", "https://example.com/a", now);
        let rewritten =
            write_cache_entry(storage.path(), "rewritten", "https://example.com/b", now);
        assert_eq!(cleanup_counting_reads(storage.path(), now), (0, 2));

        // A different size is a different version even within one mtime tick.
        write_cache_entry(
            storage.path(),
            "rewritten",
            "https://example.com/b-longer",
            now - CACHE_TTL_MS - 1,
        );
        assert_eq!(cleanup_counting_reads(storage.path(), now), (1, 1));
        assert!(!rewritten.exists());
        assert!(kept.exists());

        // The unchanged file expires from its remembered fetch time.
        assert_eq!(
            cleanup_counting_reads(storage.path(), now + CACHE_TTL_MS + 1),
            (1, 0)
        );
        assert!(!kept.exists());
    }

    #[test]
    fn web_view_urls_rewrite_to_raw_content() {
        let cases = [
            (
                "https://github.com/owner/repo/blob/main/docs/guide.md?download=1#L42",
                "https://raw.githubusercontent.com/owner/repo/main/docs/guide.md?download=1",
            ),
            (
                "https://github.com/owner/repo/raw/v1.2/src/lib.rs?raw=1#L7",
                "https://raw.githubusercontent.com/owner/repo/v1.2/src/lib.rs?raw=1",
            ),
            (
                "https://www.github.com/owner/repo/blob/main/README.md",
                "https://raw.githubusercontent.com/owner/repo/main/README.md",
            ),
            (
                "https://gitlab.com/owner/repo/-/blob/main/docs/guide.md?plain=1#L4",
                "https://gitlab.com/owner/repo/-/raw/main/docs/guide.md?plain=1",
            ),
        ];

        for (input, expected) in cases {
            let url = Url::parse(input).unwrap();
            assert_eq!(rewrite_url_for_fetch(&url).as_str(), expected);
        }
    }

    #[test]
    fn non_web_view_urls_are_not_rewritten() {
        for input in [
            "https://gist.github.com/owner/abcdef/blob/main/file.md",
            "https://github.com/owner/repo",
            "https://github.com/owner/repo/blob",
            "https://api.github.com/repos/owner/repo",
            "https://notgithub.com/owner/repo/blob/main/file.md",
            "https://gitlab.example.com/owner/repo/-/blob/main/file.md",
        ] {
            let url = Url::parse(input).unwrap();
            assert_eq!(rewrite_url_for_fetch(&url).as_str(), input);
        }
    }

    #[test]
    fn extension_from_path_uses_parser_mapping() {
        let url = Url::parse("https://example.com/pkg/index.mjs").unwrap();
        let (ext, from_path) = resolve_fetch_extension(&url, "text/javascript").unwrap();
        assert_eq!(ext, ".mjs");
        assert!(from_path);
    }

    #[test]
    fn text_plain_rs_url_ignores_content_type_gate() {
        let url = Url::parse("https://raw.githubusercontent.com/o/r/main/lib.rs").unwrap();
        let (ext, from_path) = resolve_fetch_extension(&url, "text/plain").unwrap();
        assert_eq!(ext, ".rs");
        assert!(from_path);
    }

    #[test]
    fn extensionless_javascript_maps_to_js() {
        let url = Url::parse("https://cdn.example/bundle").unwrap();
        let (ext, from_path) = resolve_fetch_extension(&url, "text/javascript").unwrap();
        assert_eq!(ext, ".js");
        assert!(!from_path);
    }

    #[test]
    fn extensionless_plain_stays_md() {
        let url = Url::parse("https://example.com/readme").unwrap();
        let (ext, _) = resolve_fetch_extension(&url, "text/plain").unwrap();
        assert_eq!(ext, ".md");
    }

    #[test]
    fn query_and_fragment_do_not_break_path_extension() {
        let url = Url::parse("https://example.com/src/file.ts?v=2#L10").unwrap();
        let (ext, from_path) = resolve_fetch_extension(&url, "text/plain").unwrap();
        assert_eq!(ext, ".ts");
        assert!(from_path);
    }

    #[test]
    fn percent_encoded_path_segment() {
        let url = Url::parse("https://example.com/foo%2Fbar.rs").unwrap();
        // path is /foo%2Fbar.rs - segment is foo%2Fbar.rs -> decode to foo/bar.rs -> ext rs
        let (ext, _) = resolve_fetch_extension(&url, "text/plain").unwrap();
        assert_eq!(ext, ".rs");
    }

    #[test]
    fn binary_sniff_detects_nul() {
        let mut body = vec![b'f', b'n', 0, b' '];
        assert!(body_contains_nul_in_prefix(&body));
        body = vec![b'h'; 9000];
        assert!(!body_contains_nul_in_prefix(&body));
    }

    #[test]
    fn unsupported_pdf_still_errors_via_resolve() {
        let url = Url::parse("https://example.com/doc.pdf").unwrap();
        assert!(resolve_fetch_extension(&url, "application/pdf").is_none());
    }

    #[test]
    fn is_permalink_anchor_doc_anchor_class_drops_anchor() {
        let md = html_to_markdown_converter()
            .convert("<a class=\"doc-anchor\" href=\"#stdio-transport\">x</a>")
            .unwrap();
        assert_eq!(
            md.trim(),
            "",
            "doc-anchor permalink should be dropped: {md:?}"
        );
    }

    #[test]
    fn html_to_markdown_rustdoc_heading_cleanup() {
        let html = "<main><h1>Function <span class=\"fn\">stdio</span>&nbsp;<button id=\"copy-path\">Copy item path</button></h1><h2 class=\"location\"><a href=\"#\">stdio</a></h2><h2><a class=\"doc-anchor\" href=\"#stdio-transport\">§</a>StdIO Transport</h2></main>";
        let md = html_to_markdown_converter().convert(html).unwrap();
        assert!(md.contains("# Function stdio"), "{md:?}");
        assert!(!md.contains("Copy item path"), "{md:?}");
        assert!(md.contains("## stdio"), "{md:?}");
        assert!(!md.contains("[stdio](#)"), "{md:?}");
        assert!(md.contains("## StdIO Transport"), "{md:?}");
        assert!(!md.contains('§'), "{md:?}");
        assert!(!md.contains("](#stdio-transport)"), "{md:?}");
    }

    #[test]
    fn html_to_markdown_docusaurus_hash_link_still_dropped() {
        let html = "<h2>The Retain Pipeline<a class=\"hash-link\" href=\"#x\" aria-label=\"Direct link to The Retain Pipeline\">\u{200b}</a></h2>";
        let md = html_to_markdown_converter().convert(html).unwrap();
        assert!(md.contains("## The Retain Pipeline"), "{md:?}");
        assert!(!md.contains('\u{200b}'), "{md:?}");
    }

    const CHROME_AUTO_CONNECT_HTML: &str =
        include_str!("../../aft/tests/fixtures/url_html/chrome_auto_connect.html");

    /// The fenced blocks of `markdown` as (opening fence line, body). Body
    /// lines lose only the indentation the opening fence has (a list item's
    /// indent), so the code's own indentation is compared as written.
    fn fenced_blocks(markdown: &str) -> Vec<(String, String)> {
        let mut blocks = Vec::new();
        let mut open: Option<(String, usize, Vec<String>)> = None;
        for line in markdown.lines() {
            let trimmed = line.trim_start();
            match open.take() {
                None => {
                    if trimmed.starts_with("```") {
                        let indent = line.len() - trimmed.len();
                        open = Some((trimmed.to_string(), indent, Vec::new()));
                    }
                }
                Some((fence_line, indent, mut body)) => {
                    let fence: String = fence_line.chars().take_while(|c| *c == '`').collect();
                    if trimmed == fence {
                        blocks.push((fence_line, body.join("\n")));
                    } else {
                        let unindented = line
                            .strip_prefix(&" ".repeat(indent))
                            .unwrap_or(line.trim_start());
                        body.push(unindented.to_string());
                        open = Some((fence_line, indent, body));
                    }
                }
            }
        }
        assert!(open.is_none(), "unclosed fence in {markdown}");
        blocks
    }

    #[test]
    fn html_to_markdown_pre_closed_code_early_stays_one_fenced_block() {
        // The live page closes </code> inside the "chrome-devtools-mcp@latest"
        // string; everything after it must still land inside the same fence.
        let md = html_to_markdown_converter()
            .convert(CHROME_AUTO_CONNECT_HTML)
            .unwrap();
        let blocks = fenced_blocks(&md);
        assert_eq!(blocks.len(), 1, "{md}");
        let (fence_line, body) = &blocks[0];
        assert_eq!(fence_line, "```", "{md}");
        assert_eq!(
            body,
            concat!(
                "{\n",
                "  \"mcpServers\": {\n",
                "    \"chrome-devtools\": {\n",
                "      \"command\": \"npx\",\n",
                "      \"args\": [\"chrome-devtools-mcp@latest\", \"--autoConnect\"]\n",
                "    }\n",
                "  }\n",
                "}",
            ),
            "{md}"
        );
        assert!(
            md.contains(r#""args": ["chrome-devtools-mcp@latest", "--autoConnect"]"#),
            "{md}"
        );
        assert!(!md.contains("```ome"), "{md}");
    }

    #[test]
    fn html_to_markdown_pre_keeps_code_verbatim() {
        let html = "<pre><code class=\"language-md\">line *one*\n\n\n\n  # not a heading &lt;b&gt;\n</code></pre>";
        let md = html_to_markdown_converter().convert(html).unwrap();
        assert_eq!(
            md.trim(),
            "```md\nline *one*\n\n\n\n  # not a heading <b>\n```",
            "{md:?}"
        );
    }

    #[test]
    fn html_to_markdown_code_containing_triple_backticks_gets_longer_fence() {
        let html = "<pre><code>Example:\n```rust\nfn main() {}\n```\n</code></pre>";
        let md = html_to_markdown_converter().convert(html).unwrap();
        assert_eq!(
            md.trim(),
            "````\nExample:\n```rust\nfn main() {}\n```\n````",
            "{md:?}"
        );

        let html = "<pre><code>a ````` run</code></pre>";
        let md = html_to_markdown_converter().convert(html).unwrap();
        assert_eq!(md.trim(), "``````\na ````` run\n``````", "{md:?}");
    }

    #[test]
    fn html_to_markdown_pre_without_code_keeps_htmd_rendering() {
        let html = "<pre>plain preformatted</pre>";
        let md = html_to_markdown_converter().convert(html).unwrap();
        assert!(!md.contains("```"), "{md:?}");
        assert!(md.contains("plain preformatted"), "{md:?}");
    }

    #[test]
    fn html_to_markdown_pre_per_line_divs_keep_their_lines() {
        let md = html_to_markdown_converter()
            .convert(include_str!(
                "../../aft/tests/fixtures/url_html/per_line_divs.html"
            ))
            .unwrap();
        let blocks = fenced_blocks(&md);
        assert_eq!(blocks.len(), 1, "{md}");
        // The template literal's single backticks leave the fence at three.
        assert_eq!(blocks[0].0, "```js", "{md}");
        assert_eq!(
            blocks[0].1, "function greet(name) {\n  return `Hello, ${name}`;\n\n}",
            "{md}"
        );
    }

    #[test]
    fn html_to_markdown_pre_table_rows_keep_their_lines() {
        let md = html_to_markdown_converter()
            .convert(include_str!(
                "../../aft/tests/fixtures/url_html/table_rows.html"
            ))
            .unwrap();
        let blocks = fenced_blocks(&md);
        assert_eq!(blocks.len(), 1, "{md}");
        assert_eq!(blocks[0].0, "```python", "{md}");
        assert_eq!(
            blocks[0].1, "def add(a, b):\n    return a + b\n\nprint(add(1, 2))",
            "{md}"
        );
    }

    #[test]
    fn html_to_markdown_pre_shiki_line_spans_keep_their_lines() {
        let md = html_to_markdown_converter()
            .convert(include_str!(
                "../../aft/tests/fixtures/url_html/shiki_lines.html"
            ))
            .unwrap();
        let blocks = fenced_blocks(&md);
        assert_eq!(blocks.len(), 1, "{md}");
        assert_eq!(blocks[0].0, "```", "{md}");
        assert_eq!(
            blocks[0].1,
            "const total = items.reduce((sum, item) => sum + item.price, 0);\n\nconsole.log(total);",
            "{md}"
        );
    }

    #[test]
    fn html_to_markdown_pre_list_item_lines_keep_their_lines() {
        let html = "<pre><code><ol><li>first</li><li></li><li>  third</li></ol></code></pre>";
        let md = html_to_markdown_converter().convert(html).unwrap();
        assert_eq!(md.trim(), "```\nfirst\n\n  third\n```", "{md:?}");
    }

    #[test]
    fn html_to_markdown_pre_newline_text_between_lines_is_not_doubled() {
        // Lines that already end in newline text must not gain a second break.
        let html = "<pre><code><span class=\"line\">a</span>\n<span class=\"line\">b</span>\n<div>c\n</div></code></pre>";
        let md = html_to_markdown_converter().convert(html).unwrap();
        assert_eq!(md.trim(), "```\na\nb\nc\n```", "{md:?}");
    }

    #[test]
    fn code_fence_for_outgrows_longest_backtick_run() {
        assert_eq!(code_fence_for("no ticks"), "```");
        assert_eq!(code_fence_for("`inline` ``double``"), "```");
        assert_eq!(code_fence_for("```"), "````");
        assert_eq!(code_fence_for("``` and ````"), "`````");
    }

    /// htmd decodes an HTML entity into its character and then escapes that
    /// character for Markdown, so the converted text spells a key in a form
    /// the byte matchers alone do not recognise.
    #[test]
    fn html_conversion_markdown_escapes_an_entity_decoded_character() {
        let markdown =
            convert_html_body_to_markdown(b"<p>abcdef&#42;1234567890</p>", "https://example.test/")
                .unwrap();
        let text = String::from_utf8(markdown).unwrap();
        assert!(text.contains("abcdef\\*1234567890"), "{text}");
    }

    /// The text of a failed body read can name the request URL, which held
    /// the key in a placeholder fetch; it is scrubbed before it is reported.
    #[test]
    fn a_failed_body_read_in_a_placeholder_fetch_is_scrubbed_of_held_keys() {
        struct Failing;
        impl Read for Failing {
            fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
                Err(io::Error::other(
                    "error reading body for url (https://api.test/v1?key=fetch-secret-key%2F0123456789%2Babc)",
                ))
            }
        }
        let mut held = HeldKeys::default();
        held.hold("test", b"fetch-secret-key/0123456789+abc")
            .unwrap();
        let deadline = FetchDeadline::for_current_call();
        let sanitize = |detail: &str| held.sanitize_detail(detail);
        let error = read_response_body_with(Failing, "https://api.test/v1", &deadline, &sanitize)
            .expect_err("the read fails");
        let text = error.to_string();
        assert!(!text.contains("fetch-secret-key"), "{text}");
        assert!(text.contains("key={{ck-secret:test}})"), "{text}");
    }

    /// reqwest prints the request URL in its own error text; a placeholder
    /// fetch's failure must drop it (the URL held the key), not merely scrub
    /// the key out of it.
    #[test]
    fn a_placeholder_fetch_send_failure_drops_the_request_url() {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        thread::spawn(move || {
            // Accept one connection and hold it open without answering.
            let accepted = listener.accept();
            thread::sleep(Duration::from_secs(5));
            drop(accepted);
        });
        let url = format!("http://{addr}/v1?key=fetch-secret-key%2F0123456789%2Babc");
        let error = Client::builder()
            .timeout(Duration::from_millis(300))
            .build()
            .unwrap()
            .get(&url)
            .send()
            .expect_err("the silent server times the request out");
        assert!(error.to_string().contains("for url"), "{error}");
        let mut held = HeldKeys::default();
        held.hold("test", b"fetch-secret-key/0123456789+abc")
            .unwrap();
        let deadline = FetchDeadline::for_current_call();
        let failure = send_failure(
            error,
            Some(FetchPhase::Headers),
            &deadline,
            "http://api.test/v1?key={{ck-secret:test}}",
            Some(&held),
        );
        let text = failure.to_string();
        assert!(text.contains("timed out"), "{text}");
        assert!(!text.contains("for url"), "{text}");
        assert!(!text.contains("fetch-secret-key"), "{text}");
    }

    #[test]
    fn deprecated_site_local_ipv6_is_private() {
        for address in ["fec0::1", "feff::1", "fef0:1::1"] {
            let ip: IpAddr = address.parse().unwrap();
            assert!(is_private_ip(ip), "{address}");
        }
        assert!(!is_private_ip("2606:4700::1".parse().unwrap()));
    }
}

#[cfg(any(test, feature = "test-support"))]
/// The fetch times the slow-call line reports, measured against local
/// servers that are slow in a known phase.
#[path = "url_fetch_deadline_tests.rs"]
#[cfg_attr(not(test), allow(dead_code, unused_imports))]
pub mod deadline_tests;

#[cfg(test)]
mod fetch_times_tests {
    use super::timing::UrlFetchTimes;
    use super::*;
    use std::net::TcpListener;

    const DOCUMENT: &[u8] = b"# Guide\n\n## Install\n\nRun the installer.\n";

    /// Answers every connection: reads the request head, waits
    /// `before_headers`, sends the response headers, waits `before_body`,
    /// then sends [`DOCUMENT`] and closes.
    fn slow_server(before_headers: Duration, before_body: Duration) -> SocketAddr {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
        let address = listener.local_addr().expect("test server address");
        thread::spawn(move || {
            for mut stream in listener.incoming().flatten() {
                thread::spawn(move || {
                    let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
                    let mut head = Vec::new();
                    let mut buffer = [0u8; 1024];
                    while !head.windows(4).any(|window| window == b"\r\n\r\n") {
                        match stream.read(&mut buffer) {
                            Ok(0) | Err(_) => return,
                            Ok(n) => head.extend_from_slice(&buffer[..n]),
                        }
                    }
                    thread::sleep(before_headers);
                    let headers = format!(
                        "HTTP/1.1 200 OK\r\ncontent-type: text/markdown\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
                        DOCUMENT.len()
                    );
                    if stream.write_all(headers.as_bytes()).is_err() {
                        return;
                    }
                    let _ = stream.flush();
                    thread::sleep(before_body);
                    let _ = stream.write_all(DOCUMENT);
                });
            }
        });
        address
    }

    fn local() -> UrlFetchOptions {
        UrlFetchOptions {
            allow_private: true,
            ..UrlFetchOptions::default()
        }
    }

    /// One fetch under a call budget, inside a fetch-times scope.
    fn timed_fetch(
        budget: Duration,
        url: &str,
        storage: &Path,
    ) -> (Result<PathBuf, UrlFetchError>, UrlFetchTimes) {
        let _call = crate::bounded_io::enter(Some(crate::bounded_io::Budget::after(budget)));
        let scope = timing::begin();
        let result = fetch_url_to_cache(url, storage, local());
        let times = scope.finish().expect("the fetch was counted");
        (result, times)
    }

    #[test]
    fn url_fetch_times_split_a_slow_download_and_count_a_cache_hit() {
        let storage = tempfile::tempdir().unwrap();
        let address = slow_server(Duration::from_millis(300), Duration::from_millis(200));
        let url = format!("http://127.0.0.1:{}/guide.md", address.port());

        let (result, times) = timed_fetch(Duration::from_secs(10), &url, storage.path());
        result.expect("the slow server answers within the deadline");
        assert_eq!(times.fetches, 1, "{times:?}");
        assert_eq!(times.cache_hits, 0, "{times:?}");
        assert_eq!(times.remembered_failures, 0, "{times:?}");
        assert_eq!((times.redirects, times.retries), (0, 0), "{times:?}");
        assert_eq!(times.error, None, "{times:?}");
        // The server held the headers 300 ms after it read the request, and
        // the body another 200 ms after the headers.
        assert!(times.first_byte >= Duration::from_millis(300), "{times:?}");
        assert!(times.connect <= times.first_byte, "{times:?}");
        assert!(times.body >= Duration::from_millis(150), "{times:?}");
        assert_eq!(times.body_bytes, DOCUMENT.len() as u64, "{times:?}");
        let rendered = times.render();
        assert!(
            rendered.starts_with("url_fetch=fetches:1,cache_hits:0,remembered:0,"),
            "{rendered}"
        );
        assert!(!rendered.contains("guide"), "{rendered}");
        assert!(!rendered.contains(' '), "{rendered}");

        // The same URL again is served from the cache: no request, no body.
        let (result, times) = timed_fetch(Duration::from_secs(10), &url, storage.path());
        result.expect("the cached copy is served");
        assert_eq!((times.fetches, times.cache_hits), (1, 1), "{times:?}");
        assert_eq!(times.first_byte, Duration::ZERO, "{times:?}");
        assert_eq!(times.body_bytes, 0, "{times:?}");
    }

    #[test]
    fn url_fetch_times_name_a_timeout_and_its_phase() {
        let storage = tempfile::tempdir().unwrap();
        let address = slow_server(Duration::from_secs(60), Duration::ZERO);
        let url = format!("http://127.0.0.1:{}/silent.md", address.port());
        // A 5 s call budget leaves the fetch a 2 s deadline (see
        // `FetchDeadline::for_current_call`).
        let (result, times) = timed_fetch(Duration::from_secs(5), &url, storage.path());
        let error = result.expect_err("a server that never answers fails");
        assert_eq!(error.code(), "url_fetch_timeout", "{error}");
        assert_eq!(
            times.error,
            Some(("url_fetch_timeout", Some(FetchPhase::Headers))),
            "{times:?}"
        );
        assert!(
            times.first_byte >= Duration::from_millis(1_500),
            "{times:?}"
        );
        assert_eq!(times.body_bytes, 0, "{times:?}");
        assert!(
            times.render().ends_with(",error:url_fetch_timeout/headers"),
            "{}",
            times.render()
        );
    }

    #[test]
    fn url_fetch_times_collect_only_inside_the_outermost_scope() {
        timing::record(|times| times.fetches += 1);
        assert_eq!(timing::begin().finish(), None, "nothing ran in this scope");

        let outer = timing::begin();
        let inner = timing::begin();
        timing::record(|times| times.fetches += 1);
        assert_eq!(inner.finish(), None);
        timing::record(|times| times.fetches += 1);
        assert_eq!(outer.finish().map(|times| times.fetches), Some(2));

        drop(timing::begin());
        timing::record(|times| times.fetches += 1);
        assert_eq!(timing::begin().finish(), None, "a dropped scope closed");
    }

    #[test]
    fn url_fetch_times_render_every_field_in_milliseconds() {
        let times = UrlFetchTimes {
            fetches: 2,
            cache_hits: 1,
            remembered_failures: 0,
            lookup: Duration::from_micros(2_100),
            connect: Duration::from_millis(40),
            first_byte: Duration::from_micros(5_800_004),
            body: Duration::from_millis(300),
            body_bytes: 51_234,
            convert: Duration::from_millis(4),
            redirects: 1,
            retries: 0,
            error: Some(("url_fetch_failed", None)),
        };
        assert_eq!(
            times.render(),
            "url_fetch=fetches:2,cache_hits:1,remembered:0,lookup:2.10,connect:40.00,first_byte:5800.00,body:300.00,bytes:51234,convert:4.00,redirects:1,retries:0,error:url_fetch_failed"
        );
    }
}

#[cfg(test)]
mod secret_audit_regressions {
    use super::*;
    #[test]
    fn substituted_query_allocates_its_exact_complete_size_before_copying_any_key() {
        let first = Zeroizing::new(vec![b'a'; 1001]);
        let second = Zeroizing::new(vec![b'b'; 2103]);
        let result = substitute_query(b"a=x&b=y", &[(2, 3, first), (6, 7, second)]).unwrap();
        assert_eq!(result.len(), 5 + 1001 + 2103);
        assert_eq!(
            result.capacity(),
            result.len(),
            "a later key must not reallocate a buffer that already contains an earlier key"
        );
        assert_eq!(&result[..2], b"a=");
        assert_eq!(&result[1003..1006], b"&b=");
    }
    #[test]
    fn approval_wait_preserves_the_fetch_and_read_back_network_budget() {
        let _scope = crate::bounded_io::enter(Some(crate::bounded_io::Budget::after(
            Duration::from_secs(25),
        )));
        let before = crate::bounded_io::current().unwrap().deadline;
        let deadline = FetchDeadline::for_current_call();
        let person_wait = Duration::from_secs(360);
        crate::bounded_io::exclude_secret_approval_wait(person_wait);
        assert_eq!(
            crate::bounded_io::current().unwrap().deadline,
            before + person_wait
        );
        assert_eq!(deadline.allowed, URL_FETCH_CEILING);
    }
}