agent-framework-foundry-hosting 0.15.0

Host agents and workflows as Azure AI Foundry hosted agents (Responses and Invocations protocols, Foundry state storage)
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
//! `ResponsesHostServer`: an agent or a workflow on the agentserver's
//! Responses routes (upstream `ResponsesHostServer` over
//! `ResponsesAgentServerHost`).
//!
//! | Route | |
//! | --- | --- |
//! | `POST {prefix}/responses` | create (sync, `stream`, `background`) |
//! | `GET {prefix}/responses/{id}` | a stored response; `?stream=true[&starting_after=N]` replays a background response's events (live while it runs) |
//! | `DELETE {prefix}/responses/{id}` | delete it |
//! | `POST {prefix}/responses/{id}/cancel` | cancel a background response |
//! | `GET {prefix}/responses/{id}/input_items` | the request's input items |
//!
//! History follows upstream's default `history_source="agent_server"`: the
//! host keeps each stored response's transcript and sends the prior
//! transcript (from `previous_response_id` or `conversation`) followed by
//! the new input to the model. `store: false` persists nothing.
//!
//! [`HistorySource`] selects who supplies prior messages (the default
//! replays the stored transcript; `Agent` / `Service` resume a host-kept
//! agent session). Turns on one conversation are serialized.
//!
//! Streams are `event: <type>` / `data: <json>` SSE frames with a
//! `sequence_number`: `response.created`, `response.in_progress`, each
//! output item's events in order (`output_item.added`, its content or
//! argument deltas, `output_item.done`; message text, refusals, reasoning
//! summaries, function and MCP calls, tool outputs, images, approval and
//! OAuth consent requests), and `response.completed` (or `incomplete` /
//! `failed`), emitted only after the response is persisted. Sync and
//! streamed responses carry the same `output` and `usage`.
//!
//! Workflows paused on `request_info` (with a
//! [checkpoint store](ResponsesHostServer::with_checkpoint_store)) end with
//! `request_info` function calls; answering them with
//! `function_call_output` items resumes the workflow from its checkpoint.

use std::collections::HashMap;
use std::convert::Infallible;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use agent_framework_core::agent::{AgentRunOptions, SupportsAgentRun};
use agent_framework_core::error::Result;
use agent_framework_core::types::Content;
use agent_framework_core::types::{AgentResponse, ChatOptions, Message};
use agent_framework_core::workflow::{CheckpointStorage, Workflow};
use agent_framework_hosting::responses::openai_error;
use agent_framework_hosting::{responses_to_run, ResponsesRequest};
use async_trait::async_trait;
use axum::extract::{Path, Query, State};
use axum::http::{HeaderMap, HeaderName, HeaderValue, StatusCode};
use axum::response::sse::{Event, KeepAlive, Sse};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Json, Router};
use futures::StreamExt;
use serde::Deserialize;
use serde_json::{json, Map, Value};
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;

use crate::config::FoundryHostConfig;
use crate::host::{with_host_routes, HostOptions};
use crate::output::{OutputError, OutputTracker};
use crate::scope::{headers, ids, FoundryRequestContext, InvalidOriginalSubject};
use crate::stores::{
    FunctionApprovalStore, FunctionApprovalStoreProvider, InMemoryFunctionApprovalStore,
};

/// A turn's request, as the hosted agent or workflow sees it (upstream
/// `HostedResponseRequest`).
#[derive(Clone)]
pub struct HostedResponseRequest {
    /// The new response's id.
    pub response_id: String,
    /// The raw `POST /responses` body.
    pub body: Value,
    /// This request's input as messages.
    pub messages: Vec<Message>,
    /// The prior transcript (from `previous_response_id` or
    /// `conversation`).
    pub history: Vec<Message>,
    /// `previous_response_id`.
    pub previous_response_id: Option<String>,
    /// The conversation id.
    pub conversation_id: Option<String>,
    /// The platform request context.
    pub context: FoundryRequestContext,
    /// The server's checkpoint store ([`ResponsesHostServer::with_checkpoint_store`]).
    /// A workflow factory passes it to
    /// [`WorkflowBuilder::with_checkpointing`](agent_framework_core::workflow::WorkflowBuilder::with_checkpointing)
    /// so a `request_info` pause can be resumed on a later turn.
    pub checkpoint_storage: Option<Arc<dyn CheckpointStorage>>,
}

impl std::fmt::Debug for HostedResponseRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HostedResponseRequest")
            .field("response_id", &self.response_id)
            .field("previous_response_id", &self.previous_response_id)
            .field("conversation_id", &self.conversation_id)
            .field("checkpoint_storage", &self.checkpoint_storage.is_some())
            .finish_non_exhaustive()
    }
}

/// Who supplies prior messages to the model (upstream `history_source`),
/// independently of the caller's `store` flag.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HistorySource {
    /// The host replays the stored outer transcript before this turn's
    /// input, and runs the agent with `store: false` so a storing client
    /// does not keep a second copy.
    #[default]
    AgentServer,
    /// Only this turn's input is sent; the agent's own session (history
    /// providers, or a service conversation it chose) supplies the rest.
    /// The session is kept by the host between stored turns.
    Agent,
    /// Only this turn's input is sent; on a stored turn the client runs with
    /// `store: true` and the service conversation it issues is kept in the
    /// host's session for the next turn. Agents only.
    Service,
}

/// Who runs a `background: true` response (upstream `background_source`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BackgroundSource {
    /// The host runs the turn in its own background task; the agent's
    /// provider is called as for any other turn.
    #[default]
    AgentServer,
    /// The host also asks the agent's provider for a background response
    /// (`ChatOptions::background`) and polls it with the continuation token
    /// the provider returns until it finishes, emitting its output as it is
    /// recorded. Requires [`HistorySource::Service`] and a provider that
    /// supports background responses (such as the OpenAI Responses client);
    /// agents only. Local tools must be idempotent: a poll that completes a
    /// tool call runs it in the host.
    Provider,
}

/// Upstream's provider background polling interval.
const DEFAULT_BACKGROUND_POLL_INTERVAL: Duration = Duration::from_secs(2);

/// Rewrites the caller's model options before an agent runs (upstream
/// `prepare_options`).
pub type OptionsHook =
    Arc<dyn Fn(&HostedResponseRequest, ChatOptions) -> Result<ChatOptions> + Send + Sync>;

/// A workflow paused on `request_info` requests at the end of a stored
/// response: the checkpoint to resume and the wire call ids standing for
/// the workflow's request ids.
#[derive(Debug, Clone, PartialEq)]
pub struct WorkflowPause {
    /// The checkpoint holding the pending requests.
    pub checkpoint_id: String,
    /// `(wire id, workflow request id)` pairs, in request order. The wire id
    /// is the `call_id` a `function_call_output` / `computer_call_output`
    /// answers, or the `approval_request_id` of an `mcp_approval_response`.
    pub requests: Vec<(String, String)>,
    /// The pending requests' data, in the same order (to build typed replies:
    /// approval responses, computer results).
    pub request_data: Vec<Value>,
}

/// A stored response.
#[derive(Debug, Clone)]
pub struct StoredResponse {
    /// The response object.
    pub response: Value,
    /// The request's input items.
    pub input_items: Vec<Value>,
    /// The transcript up to and including this response's output.
    pub transcript: Vec<Message>,
    /// The workflow pause this response ended on, if any.
    pub pause: Option<WorkflowPause>,
    /// The agent session's state bag after this turn (`AgentSession::to_dict`
    /// without history), restored into a `HistorySource::AgentServer`
    /// continuation so session-scoped state (e.g. FIDES labels and hidden
    /// variables) carries over while the transcript is replayed.
    pub session_state: Option<Value>,
}

/// Where responses (and conversation transcripts) are kept.
#[async_trait]
pub trait ResponseStore: Send + Sync {
    /// The response stored under `id`.
    async fn get(&self, id: &str) -> Result<Option<StoredResponse>>;
    /// Store (or replace) a response.
    async fn put(&self, id: &str, response: StoredResponse) -> Result<()>;
    /// Delete a response; whether it existed.
    async fn delete(&self, id: &str) -> Result<bool>;
    /// A conversation's transcript.
    async fn conversation(&self, id: &str) -> Result<Option<Vec<Message>>>;
    /// Replace a conversation's transcript.
    async fn set_conversation(&self, id: &str, transcript: Vec<Message>) -> Result<()>;
    /// A conversation's agent-session state (see
    /// [`StoredResponse::session_state`]). The default keeps none, so a
    /// store that does not override it loses session state across turns.
    async fn conversation_state(&self, _id: &str) -> Result<Option<Value>> {
        Ok(None)
    }
    /// Replace a conversation's agent-session state.
    async fn set_conversation_state(&self, _id: &str, _state: Value) -> Result<()> {
        Ok(())
    }
    /// The ids of every stored response, for the startup sweep
    /// ([`ResponsesHostServer::fail_interrupted_responses`]). The default
    /// lists none, which suits a store that does not outlive the process.
    async fn response_ids(&self) -> Result<Vec<String>> {
        Ok(Vec::new())
    }
    /// Replace a conversation's transcript and session state together (the
    /// state is cleared when `state` is `None`). The host writes a turn's
    /// conversation through this one call, so a store should apply it
    /// atomically: a transcript paired with another turn's state would carry
    /// the wrong session-scoped state (e.g. FIDES labels) into the next turn.
    /// The default calls [`Self::set_conversation`] then
    /// [`Self::set_conversation_state`], which is not atomic; the host
    /// restores the previous transcript and state if it fails.
    async fn update_conversation(
        &self,
        id: &str,
        transcript: Vec<Message>,
        state: Option<Value>,
    ) -> Result<()> {
        self.set_conversation(id, transcript).await?;
        if let Some(state) = state {
            self.set_conversation_state(id, state).await?;
        }
        Ok(())
    }
}

/// A conversation's transcript and session state.
type ConversationRecord = (Vec<Message>, Option<Value>);

/// A process-local [`ResponseStore`].
#[derive(Debug, Clone, Default)]
pub struct InMemoryResponseStore {
    responses: Arc<Mutex<HashMap<String, StoredResponse>>>,
    conversations: Arc<Mutex<HashMap<String, ConversationRecord>>>,
}

#[async_trait]
impl ResponseStore for InMemoryResponseStore {
    async fn get(&self, id: &str) -> Result<Option<StoredResponse>> {
        Ok(self.responses.lock().unwrap().get(id).cloned())
    }
    async fn response_ids(&self) -> Result<Vec<String>> {
        Ok(self.responses.lock().unwrap().keys().cloned().collect())
    }
    async fn put(&self, id: &str, response: StoredResponse) -> Result<()> {
        self.responses
            .lock()
            .unwrap()
            .insert(id.to_string(), response);
        Ok(())
    }
    async fn delete(&self, id: &str) -> Result<bool> {
        Ok(self.responses.lock().unwrap().remove(id).is_some())
    }
    async fn conversation(&self, id: &str) -> Result<Option<Vec<Message>>> {
        Ok(self
            .conversations
            .lock()
            .unwrap()
            .get(id)
            .map(|(transcript, _)| transcript.clone()))
    }
    async fn set_conversation(&self, id: &str, transcript: Vec<Message>) -> Result<()> {
        self.conversations
            .lock()
            .unwrap()
            .entry(id.to_string())
            .or_default()
            .0 = transcript;
        Ok(())
    }
    async fn conversation_state(&self, id: &str) -> Result<Option<Value>> {
        Ok(self
            .conversations
            .lock()
            .unwrap()
            .get(id)
            .and_then(|(_, state)| state.clone()))
    }
    async fn set_conversation_state(&self, id: &str, state: Value) -> Result<()> {
        self.conversations
            .lock()
            .unwrap()
            .entry(id.to_string())
            .or_default()
            .1 = Some(state);
        Ok(())
    }
    async fn update_conversation(
        &self,
        id: &str,
        transcript: Vec<Message>,
        state: Option<Value>,
    ) -> Result<()> {
        self.conversations
            .lock()
            .unwrap()
            .insert(id.to_string(), (transcript, state));
        Ok(())
    }
}

type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;

/// Creates the agent for one request.
pub type AgentFactory = Arc<dyn Fn() -> BoxFuture<Result<Arc<dyn SupportsAgentRun>>> + Send + Sync>;
/// Creates a fresh workflow for one request.
pub type WorkflowFactory = Arc<dyn Fn(&HostedResponseRequest) -> Result<Workflow> + Send + Sync>;
/// Maps a request to a workflow's input.
pub type WorkflowInputParser = Arc<dyn Fn(&HostedResponseRequest) -> Result<Value> + Send + Sync>;

#[derive(Clone)]
enum Target {
    Agent(Arc<dyn SupportsAgentRun>),
    AgentFactory(AgentFactory),
    Workflow {
        factory: WorkflowFactory,
        parse: Option<WorkflowInputParser>,
    },
}

/// Serves an agent or workflow on the Responses routes. See the
/// [module docs](self).
#[derive(Clone)]
pub struct ResponsesHostServer {
    target: Target,
    config: FoundryHostConfig,
    store: Arc<dyn ResponseStore>,
    prefix: String,
    host: HostOptions,
    consent_origins: Option<Vec<String>>,
    checkpoints: Option<Arc<dyn CheckpointStorage>>,
    history: HistorySource,
    background_source: BackgroundSource,
    background_poll_interval: Duration,
    prepare_options: Option<OptionsHook>,
    approval_provider: Option<Arc<dyn FunctionApprovalStoreProvider>>,
    local_approvals: Arc<InMemoryFunctionApprovalStore>,
    /// The agent sessions of the `Agent` / `Service` history sources: in a
    /// session store (with history, so they survive a restart) when the
    /// `session-store` feature is on, else kept live in process.
    #[cfg(feature = "session-store")]
    sessions: Arc<dyn crate::sessions::SessionStoreProvider>,
    #[cfg(not(feature = "session-store"))]
    sessions: Arc<Mutex<HashMap<String, SessionSnapshot>>>,
}

impl std::fmt::Debug for ResponsesHostServer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ResponsesHostServer")
            .field("config", &self.config)
            .field("prefix", &self.prefix)
            .finish_non_exhaustive()
    }
}

impl ResponsesHostServer {
    fn new(target: Target) -> Self {
        Self {
            target,
            config: FoundryHostConfig::local(),
            store: Arc::new(InMemoryResponseStore::default()),
            prefix: String::new(),
            host: HostOptions::default(),
            consent_origins: None,
            checkpoints: None,
            history: HistorySource::default(),
            background_source: BackgroundSource::default(),
            background_poll_interval: DEFAULT_BACKGROUND_POLL_INTERVAL,
            prepare_options: None,
            approval_provider: None,
            local_approvals: Arc::default(),
            #[cfg(feature = "session-store")]
            sessions: Arc::new(crate::sessions::InMemorySessionStoreProvider::default()),
            #[cfg(not(feature = "session-store"))]
            sessions: Arc::default(),
        }
    }

    /// Serve one agent instance for every request. The agent must keep no
    /// per-conversation state outside its session; otherwise use
    /// [`Self::agent_factory`].
    pub fn agent(agent: Arc<dyn SupportsAgentRun>) -> Self {
        Self::new(Target::Agent(agent))
    }

    /// Create an agent per request.
    pub fn agent_factory<F, Fut>(factory: F) -> Self
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Arc<dyn SupportsAgentRun>>> + Send + 'static,
    {
        Self::new(Target::AgentFactory(Arc::new(move || Box::pin(factory()))))
    }

    /// Serve a workflow, built fresh per request. Without
    /// [`Self::with_workflow_input`] the workflow's input is the turn's
    /// messages (prior transcript followed by the new input) as JSON.
    pub fn workflow(
        factory: impl Fn(&HostedResponseRequest) -> Result<Workflow> + Send + Sync + 'static,
    ) -> Self {
        Self::new(Target::Workflow {
            factory: Arc::new(factory),
            parse: None,
        })
    }

    /// Map each request to the workflow's input (upstream `parse_response`).
    pub fn with_workflow_input(
        mut self,
        parse: impl Fn(&HostedResponseRequest) -> Result<Value> + Send + Sync + 'static,
    ) -> Self {
        if let Target::Workflow { parse: slot, .. } = &mut self.target {
            *slot = Some(Arc::new(parse));
        }
        self
    }

    /// The host configuration (default [`FoundryHostConfig::local`]).
    pub fn with_config(mut self, config: FoundryHostConfig) -> Self {
        self.config = config;
        self
    }

    /// Where responses are stored (default in memory).
    pub fn with_response_store(mut self, store: Arc<dyn ResponseStore>) -> Self {
        self.store = store;
        self
    }

    /// A route prefix (e.g. `/v1`).
    pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.prefix = prefix.into().trim_end_matches('/').to_string();
        self
    }

    /// Who supplies prior messages to the model (default
    /// [`HistorySource::AgentServer`]). With `Agent` or `Service`, the
    /// host keeps each stored turn's agent session (in process), keyed by
    /// the response id and the conversation, and resumes it on the next
    /// turn.
    pub fn with_history_source(mut self, source: HistorySource) -> Self {
        self.history = source;
        self
    }

    /// Who runs a `background: true` response (default
    /// [`BackgroundSource::AgentServer`]). [`BackgroundSource::Provider`]
    /// needs [`HistorySource::Service`]; a background request made under any
    /// other history source fails.
    pub fn with_background_source(mut self, source: BackgroundSource) -> Self {
        self.background_source = source;
        self
    }

    /// How long to wait between polls of a provider background response
    /// (default two seconds, as upstream).
    pub fn with_background_poll_interval(mut self, interval: Duration) -> Self {
        self.background_poll_interval = interval;
        self
    }

    /// Rewrite the caller's model options before an agent runs (upstream
    /// `prepare_options`). Not applied to workflows.
    pub fn with_prepare_options(
        mut self,
        hook: impl Fn(&HostedResponseRequest, ChatOptions) -> Result<ChatOptions>
            + Send
            + Sync
            + 'static,
    ) -> Self {
        self.prepare_options = Some(Arc::new(hook));
        self
    }

    /// Where function-approval requests are kept between turns (e.g.
    /// [`FoundryStorage`](crate::FoundryStorage)); without one they are kept
    /// in process. A tool that requires approval surfaces as an
    /// `mcp_approval_request`; a later turn's `mcp_approval_response`
    /// (`approval_request_id`, `approve`) is resolved through this store into
    /// the agent's function-approval response, so the call runs or is
    /// rejected.
    pub fn with_function_approval_store(
        mut self,
        provider: Arc<dyn FunctionApprovalStoreProvider>,
    ) -> Self {
        self.approval_provider = Some(provider);
        self
    }

    /// Where the agent sessions of the `Agent` and `Service` history sources
    /// are kept (feature `session-store`): e.g. a
    /// [`FoundrySessionStoreProvider`](crate::sessions::FoundrySessionStoreProvider),
    /// so `previous_response_id` and `conversation` continuations, history
    /// included, survive a restart. The default is a process-local store.
    #[cfg(feature = "session-store")]
    pub fn with_session_store_provider(
        mut self,
        provider: Arc<dyn crate::sessions::SessionStoreProvider>,
    ) -> Self {
        self.sessions = provider;
        self
    }

    /// The session handle one turn loads from and saves to.
    fn host_sessions(&self, context: &FoundryRequestContext) -> Result<HostSessions> {
        #[cfg(feature = "session-store")]
        {
            Ok(HostSessions(
                self.sessions.session_store(&self.config, context)?,
                self.config.agent_name.clone(),
            ))
        }
        #[cfg(not(feature = "session-store"))]
        {
            let _ = context;
            Ok(HostSessions(self.sessions.clone()))
        }
    }

    fn approval_store(
        &self,
        context: &FoundryRequestContext,
    ) -> Result<Arc<dyn FunctionApprovalStore>> {
        match &self.approval_provider {
            Some(provider) => provider.approval_store(&self.config, context),
            None => Ok(self.local_approvals.clone()),
        }
    }

    /// Where workflow checkpoints are kept: it is handed to the workflow
    /// factory ([`HostedResponseRequest::checkpoint_storage`]) and, when a
    /// run pauses on `request_info`, its pending requests are returned as
    /// `request_info` function calls; answering them with
    /// `function_call_output` items (and `previous_response_id`) resumes the
    /// workflow from its checkpoint (upstream's checkpoint-backed workflow
    /// continuation).
    pub fn with_checkpoint_store(mut self, storage: Arc<dyn CheckpointStorage>) -> Self {
        self.checkpoints = Some(storage);
        self
    }

    /// Restrict OAuth consent links surfaced as `oauth_consent_request`
    /// items to these origins (`https://host[:port]`). Without it any safe
    /// absolute HTTPS link is allowed.
    pub fn with_allowed_oauth_consent_origins(
        mut self,
        origins: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.consent_origins = Some(origins.into_iter().map(Into::into).collect());
        self
    }

    /// Lifecycle hooks and server-version segments for the shared routes.
    pub fn with_host_options(mut self, options: HostOptions) -> Self {
        self.host = options;
        self
    }

    /// The router: the Responses routes plus the shared host routes.
    pub fn into_router(self) -> Router {
        let host = self
            .host
            .clone()
            .server_version_segment("responses")
            .agent_identity(
                self.config.agent_name.clone(),
                self.config.agent_version.clone(),
                self.config.session_id.clone(),
            );
        let (router, _) = self.routes(host);
        router
    }

    /// The router and its shared state.
    fn routes(self, host: HostOptions) -> (Router, Arc<Inner>) {
        let p = self.prefix.clone();
        let state = Arc::new(Inner {
            server: self,
            running: Mutex::new(HashMap::new()),
            replays: Mutex::new(HashMap::new()),
            conversations: Mutex::new(HashMap::new()),
            finals: Mutex::new(HashMap::new()),
        });
        let router = Router::new()
            .route(&format!("{p}/responses"), post(create))
            .route(
                &format!("{p}/responses/{{id}}"),
                get(get_response).delete(delete_response),
            )
            .route(&format!("{p}/responses/{{id}}/cancel"), post(cancel))
            .route(
                &format!("{p}/responses/{{id}}/input_items"),
                get(input_items),
            )
            .with_state(state.clone());
        (with_host_routes(router, host), state)
    }

    /// Serve on the configured port.
    /// Serve on the configured port, after
    /// [`Self::fail_interrupted_responses`].
    pub async fn serve(self) -> Result<()> {
        let config = self.config.clone();
        let swept = self.fail_interrupted_responses().await?;
        if swept > 0 {
            tracing::warn!(
                count = swept,
                "failed background responses interrupted by a restart"
            );
        }
        crate::host::serve(self.into_router(), &config).await
    }

    /// The startup sweep: a background response the store still holds as
    /// `queued` or `in_progress` was interrupted by the previous process
    /// ending, and nothing will finish it, so it is marked `failed` with
    /// upstream's recovery error (its pollers stop waiting, and continuing
    /// from it inherits its predecessor's state as for any failed turn).
    /// Returns how many were failed. [`Self::serve`] runs it first; call it
    /// before serving a router from [`Self::into_router`] yourself.
    ///
    /// Divergence: upstream's resilient task runtime can instead resume a
    /// workflow from its checkpoint; the Rust host does not (see the crate
    /// docs).
    pub async fn fail_interrupted_responses(&self) -> Result<usize> {
        let message = match self.target {
            Target::Workflow { .. } => {
                "Recovery mode is only supported when resilient_background=True."
            }
            _ => "A non-resumable agent cannot be replayed after a process crash.",
        };
        let mut failed = 0;
        for id in self.store.response_ids().await? {
            let Some(mut stored) = self.store.get(&id).await? else {
                continue;
            };
            let interrupted = stored.response["background"] == json!(true)
                && matches!(
                    stored.response["status"].as_str(),
                    Some("queued" | "in_progress")
                );
            if !interrupted {
                continue;
            }
            stored.response["status"] = json!("failed");
            stored.response["error"] = json!({"code": "server_error", "message": message});
            stored.pause = None;
            self.store.put(&id, stored).await?;
            failed += 1;
        }
        Ok(failed)
    }
}

/// Close a background response's replay (its streams end once they have
/// sent every recorded event) and evict it after [`REPLAY_TTL`].
fn end_replay(inner: &Arc<Inner>, id: &str, replay: &Arc<Replay>) {
    replay.finish();
    let evict = inner.clone();
    let id = id.to_string();
    let replay = replay.clone();
    tokio::spawn(async move {
        tokio::time::sleep(REPLAY_TTL).await;
        let mut replays = evict.replays.lock().unwrap();
        // Only this run's buffer (a later run cannot reuse the id, but be exact).
        if replays.get(&id).is_some_and(|r| Arc::ptr_eq(r, &replay)) {
            replays.remove(&id);
        }
    });
}

/// Close the replay of a background turn that was aborted before closing
/// it: record `response`'s terminal event (unless the turn already did),
/// end the replay's streams, and schedule its eviction. A no-op once the
/// replay is closed.
fn close_aborted_replay(inner: &Arc<Inner>, id: &str, response: &Value) {
    let Some(replay) = inner.replays.lock().unwrap().get(id).cloned() else {
        return;
    };
    if replay.done.load(std::sync::atomic::Ordering::SeqCst) {
        return;
    }
    let kind = match response["status"].as_str() {
        Some("cancelled") => "response.cancelled",
        Some("failed") => "response.failed",
        Some("incomplete") => "response.incomplete",
        _ => "response.completed",
    };
    let (sequence, recorded) = {
        let events = replay.events.lock().unwrap();
        let recorded = events.last().is_some_and(|(k, _)| {
            matches!(
                k.as_str(),
                "response.completed"
                    | "response.failed"
                    | "response.incomplete"
                    | "response.cancelled"
            )
        });
        (events.len(), recorded)
    };
    if !recorded {
        replay.push(
            kind,
            &json!({"type": kind, "sequence_number": sequence, "response": response}),
        );
    }
    end_replay(inner, id, &replay);
}

struct Inner {
    server: ResponsesHostServer,
    running: Mutex<HashMap<String, tokio::task::AbortHandle>>,
    replays: Mutex<HashMap<String, Arc<Replay>>>,
    conversations: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
    /// Per response with a live [`TerminalHandle`]: serializes its terminal
    /// writes with cancel / delete.
    finals: Mutex<HashMap<String, Arc<Terminal>>>,
}

/// One response's terminal-write coordination. A turn's persistence runs in
/// its own task (so a disconnect cannot cut it short), which also means it
/// outlives a cancel or delete aborting the turn. Both take `state`, so their
/// writes never interleave, and a cancel or delete first raises `stop`, which
/// the persistence checks before each write: whatever it has not yet
/// written, it skips. A cancel or delete therefore wins unless the turn's
/// writes all committed first.
#[derive(Default)]
struct Terminal {
    stop: std::sync::atomic::AtomicBool,
    state: tokio::sync::Mutex<TerminalState>,
}

#[derive(Default)]
struct TerminalState {
    /// Cancelled or deleted: a persistence that starts later writes nothing.
    finalized: bool,
    /// A persistence stopped part-way: its response record may read as
    /// finished, but the turn did not commit, so it is still cancellable.
    stopped: bool,
}

impl Terminal {
    fn stopping(&self) -> bool {
        self.stop.load(std::sync::atomic::Ordering::SeqCst)
    }
}

/// A holder of one response's [`Terminal`]: the turn (from before it can be
/// cancelled until its persistence ends, shared by every clone of its
/// [`Prepared`]) and each cancel or delete while it runs. Holders of one
/// response share its entry in [`Inner::finals`]; the last to drop removes
/// it, so the map holds only responses with a live holder and nothing is
/// kept after the fact (a turn's later writes go through the entry it
/// already holds).
struct TerminalHandle {
    inner: Arc<Inner>,
    id: String,
    terminal: Option<Arc<Terminal>>,
}

impl std::ops::Deref for TerminalHandle {
    type Target = Terminal;

    fn deref(&self) -> &Terminal {
        self.terminal.as_ref().expect("taken only on drop")
    }
}

impl Drop for TerminalHandle {
    fn drop(&mut self) {
        let mut terminals = self.inner.finals.lock().unwrap();
        // Released under the map lock, so concurrent holders serialize and
        // exactly the last one sees only the map's reference left.
        drop(self.terminal.take());
        if terminals
            .get(&self.id)
            .is_some_and(|t| Arc::strong_count(t) == 1)
        {
            terminals.remove(&self.id);
        }
    }
}

impl Inner {
    /// A holder of `id`'s terminal coordination (see [`TerminalHandle`]).
    fn terminal(self: &Arc<Self>, id: &str) -> TerminalHandle {
        let terminal = self
            .finals
            .lock()
            .unwrap()
            .entry(id.to_string())
            .or_default()
            .clone();
        TerminalHandle {
            inner: self.clone(),
            id: id.to_string(),
            terminal: Some(terminal),
        }
    }

    /// The lock serializing one conversation's turns, from loading its
    /// transcript through persisting the new one, so concurrent turns
    /// cannot drop each other.
    fn conversation_lock(&self, id: &str) -> Arc<tokio::sync::Mutex<()>> {
        let mut locks = self.conversations.lock().unwrap();
        locks.retain(|_, l| Arc::strong_count(l) > 1);
        locks.entry(id.to_string()).or_default().clone()
    }
}

/// How long a background response's events stay replayable after it ends
/// (the agentserver's replay TTL).
const REPLAY_TTL: Duration = Duration::from_secs(600);

/// A background response's stream events, kept for
/// `GET /responses/{id}?stream=true` (live while it runs, then for
/// [`REPLAY_TTL`]).
#[derive(Default)]
struct Replay {
    events: Mutex<Vec<(String, Value)>>,
    done: std::sync::atomic::AtomicBool,
    changed: tokio::sync::Notify,
}

impl Replay {
    fn push(&self, kind: &str, payload: &Value) {
        self.events
            .lock()
            .unwrap()
            .push((kind.to_string(), payload.clone()));
        self.changed.notify_waiters();
    }

    fn finish(&self) {
        self.done.store(true, std::sync::atomic::Ordering::SeqCst);
        self.changed.notify_waiters();
    }
}

/// The `POST /responses` body fields the host reads.
#[derive(Debug, Clone, Deserialize, Default)]
struct CreateResponse {
    #[serde(default)]
    model: Option<String>,
    #[serde(default)]
    input: Value,
    #[serde(default)]
    instructions: Option<String>,
    #[serde(default)]
    stream: bool,
    #[serde(default)]
    store: Option<bool>,
    #[serde(default)]
    background: bool,
    #[serde(default)]
    previous_response_id: Option<String>,
    #[serde(default)]
    conversation: Option<Value>,
    #[serde(default)]
    metadata: Option<Map<String, Value>>,
    #[serde(default)]
    temperature: Option<f32>,
    #[serde(default)]
    top_p: Option<f32>,
    #[serde(default)]
    max_output_tokens: Option<u32>,
}

fn bad_request(message: impl Into<String>) -> Response {
    (
        StatusCode::BAD_REQUEST,
        Json(openai_error(message, "invalid_request_error", None)),
    )
        .into_response()
}

/// A malformed platform header (upstream: a `ValueError` building the
/// request context, answered as a platform-classified invalid request).
fn invalid_platform_context(error: InvalidOriginalSubject) -> Response {
    tracing::warn!(error = %error, "Invalid platform request context");
    let mut response = (
        StatusCode::BAD_REQUEST,
        Json(openai_error(
            error.message(),
            "invalid_request_error",
            Some("invalid_request_error"),
        )),
    )
        .into_response();
    let h = response.headers_mut();
    h.insert(
        HeaderName::from_static(headers::ERROR_SOURCE),
        HeaderValue::from_static("platform"),
    );
    if let Ok(detail) = HeaderValue::from_str(&format!("ValueError: {error}")) {
        h.insert(HeaderName::from_static(headers::ERROR_DETAIL), detail);
    }
    response
}

fn not_found(id: &str) -> Response {
    (
        StatusCode::NOT_FOUND,
        Json(openai_error(
            format!("Response with id '{id}' not found."),
            "invalid_request_error",
            Some("not_found"),
        )),
    )
        .into_response()
}

fn server_error(message: impl Into<String>) -> Response {
    (
        StatusCode::INTERNAL_SERVER_ERROR,
        Json(openai_error(message, "server_error", None)),
    )
        .into_response()
}

fn now_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or_default()
}

/// Everything a turn needs, resolved before it runs.
#[derive(Clone)]
struct Prepared {
    request: HostedResponseRequest,
    create: CreateResponse,
    store: bool,
    model: String,
    input_items: Vec<Value>,
    created_at: u64,
    resume: Option<Resume>,
    /// Held for the turn's whole life (it travels with the turn into
    /// streaming and background tasks).
    _conversation_turn: Option<Arc<tokio::sync::OwnedMutexGuard<()>>>,
    /// The predecessor's session state (`HistorySource::AgentServer`).
    session_state: Option<Value>,
    /// This turn's session state after the run, for persistence.
    session_out: Arc<Mutex<Option<Value>>>,
    /// This turn's completed host sessions (`HistorySource::Agent` /
    /// `Service`), written by [`persist`] only with the turn's other writes.
    staged_sessions: Arc<Mutex<Option<StagedSessions>>>,
    /// Held from before the turn can be cancelled or deleted until its
    /// persistence ends.
    terminal: Arc<TerminalHandle>,
    /// The agent, when resolved before the turn runs (see
    /// [`snapshot_inherited_session`]).
    agent: Option<Arc<dyn SupportsAgentRun>>,
    /// The host-session handle the turn snapshotted its inherited session
    /// through, kept for the run: a store tracks the ETags of the records it
    /// wrote, so the run must replace the snapshot through the same one.
    sessions: Option<Arc<HostSessions>>,
}

/// Replies resuming a paused workflow.
#[derive(Clone)]
struct Resume {
    checkpoint_id: String,
    replies: HashMap<String, Value>,
}

impl Prepared {
    /// The response object's common fields.
    fn decorate(&self, mut response: Value, status: &str) -> Value {
        let id = &self.request.response_id;
        response["id"] = json!(id);
        response["object"] = json!("response");
        response["created_at"] = json!(self.created_at);
        response["model"] = json!(self.model);
        response["status"] = json!(status);
        response["background"] = json!(self.create.background);
        response["store"] = json!(self.store);
        response["previous_response_id"] = json!(self.request.previous_response_id);
        response["conversation"] = match &self.request.conversation_id {
            Some(c) => json!({"id": c}),
            None => Value::Null,
        };
        response["instructions"] = json!(self.create.instructions);
        response["metadata"] = json!(self.create.metadata.clone().unwrap_or_default());
        if response.get("output").is_none() {
            response["output"] = json!([]);
        }
        response
    }

    fn skeleton(&self, status: &str) -> Value {
        self.decorate(json!({}), status)
    }
}

/// Normalize the request input into input items with ids.
fn input_items_of(input: &Value, response_id: &str) -> Vec<Value> {
    let items: Vec<Value> = match input {
        Value::String(text) => vec![json!({
            "type": "message",
            "role": "user",
            "content": [{"type": "input_text", "text": text}],
        })],
        Value::Array(items) => items.clone(),
        Value::Null => Vec::new(),
        other => vec![other.clone()],
    };
    items
        .into_iter()
        .map(|mut item| {
            if item.is_object() && item.get("id").is_none() {
                let prefix = match item.get("type").and_then(Value::as_str) {
                    Some("function_call_output") => "fco",
                    _ => "msg",
                };
                item["id"] = json!(ids::new_id(prefix, Some(response_id)));
            }
            item
        })
        .collect()
}

fn conversation_id(value: &Option<Value>) -> std::result::Result<Option<String>, String> {
    match value {
        None | Some(Value::Null) => Ok(None),
        Some(Value::String(s)) if !s.is_empty() => Ok(Some(s.clone())),
        Some(Value::Object(o)) => match o.get("id").and_then(Value::as_str) {
            Some(id) if !id.is_empty() => Ok(Some(id.to_string())),
            _ => Err("conversation.id must be a non-empty string.".into()),
        },
        _ => Err("conversation must be a string or an object with an id.".into()),
    }
}

async fn create(
    State(inner): State<Arc<Inner>>,
    headers: HeaderMap,
    body: axum::body::Bytes,
) -> Response {
    let body: Value = match serde_json::from_slice(&body) {
        Ok(v @ Value::Object(_)) => v,
        _ => return bad_request("The request body must be a JSON object."),
    };
    let create: CreateResponse = match serde_json::from_value(body.clone()) {
        Ok(c) => c,
        Err(e) => return bad_request(format!("Invalid request: {e}")),
    };
    let store = create.store.unwrap_or(true);
    if create.background && !store {
        return bad_request("background responses require store=true.");
    }
    let conversation = match conversation_id(&create.conversation) {
        Ok(c) => c,
        Err(e) => return bad_request(e),
    };
    if conversation.is_some() && create.previous_response_id.is_some() {
        return bad_request("previous_response_id and conversation cannot both be set.");
    }
    let context = match FoundryRequestContext::from_headers(&headers, None) {
        Ok(context) => context,
        Err(e) => return invalid_platform_context(e),
    };
    let server = &inner.server;
    let conversation_turn = match &conversation {
        Some(id) => Some(Arc::new(inner.conversation_lock(id).lock_owned().await)),
        None => None,
    };
    let mut pause = None;
    let mut session_state = None;
    let history = if let Some(previous) = &create.previous_response_id {
        match server.store.get(previous).await {
            Ok(Some(stored)) => {
                // An unfinished predecessor has no transcript yet:
                // continuing from it would silently drop its turn.
                let status = stored.response["status"].as_str().unwrap_or_default();
                if matches!(status, "queued" | "in_progress") {
                    return bad_request(format!(
                        "Previous response with id '{previous}' is still {status}; \
                         wait for it to finish before continuing from it."
                    ));
                }
                pause = stored.pause;
                session_state = stored.session_state;
                stored.transcript
            }
            Ok(None) => {
                return bad_request(format!("Previous response with id '{previous}' not found."))
            }
            Err(e) => return server_error(e.to_string()),
        }
    } else if let Some(conversation) = &conversation {
        match server.store.conversation_state(conversation).await {
            Ok(state) => session_state = state,
            Err(e) => return server_error(e.to_string()),
        }
        match server.store.conversation(conversation).await {
            Ok(t) => t.unwrap_or_default(),
            Err(e) => return server_error(e.to_string()),
        }
    } else {
        Vec::new()
    };
    if !store
        && server.history == HistorySource::Service
        && (create.previous_response_id.is_some() || conversation.is_some())
    {
        return bad_request(
            "store=false cannot resume service-managed history; start a new one-shot request.",
        );
    }
    let resume = match (&server.target, pause) {
        (Target::Workflow { .. }, Some(pause)) => match workflow_replies(&pause, &create.input) {
            Ok(replies) => Some(Resume {
                checkpoint_id: pause.checkpoint_id,
                replies,
            }),
            Err(e) => return bad_request(e),
        },
        _ => None,
    };
    let response_id = ids::response_id(create.previous_response_id.as_deref());
    // A workflow resume's input is its replies, consumed above.
    let messages = if resume.is_some() {
        Vec::new()
    } else {
        match turn_messages(server, &context, &create.input, store).await {
            Ok(messages) => messages,
            Err(e) => return bad_request(e),
        }
    };
    let prepared = Prepared {
        request: HostedResponseRequest {
            response_id: response_id.clone(),
            body,
            messages,
            history,
            previous_response_id: create.previous_response_id.clone(),
            conversation_id: conversation,
            context,
            checkpoint_storage: server.checkpoints.clone(),
        },
        resume,
        _conversation_turn: conversation_turn,
        session_state,
        session_out: Arc::default(),
        staged_sessions: Arc::default(),
        terminal: Arc::new(inner.terminal(&response_id)),
        agent: None,
        sessions: None,
        input_items: input_items_of(&create.input, &response_id),
        model: create
            .model
            .clone()
            .filter(|m| !m.is_empty())
            .unwrap_or_else(|| {
                if server.config.agent_name.is_empty() {
                    "agent".into()
                } else {
                    server.config.agent_name.clone()
                }
            }),
        store,
        created_at: now_secs(),
        create,
    };
    let mut prepared = prepared;
    if let Err(e) = snapshot_inherited_session(server, &mut prepared).await {
        return match e {
            TurnError::Public(message) => bad_request(message),
            TurnError::Run(e) => {
                tracing::error!(error = %e, "failed to record a turn's inherited session");
                server_error("The response could not be started.".to_string())
            }
        };
    }

    if prepared.create.background {
        return start_background(inner, prepared).await;
    }
    if prepared.create.stream {
        let (tx, rx) = mpsc::channel::<Event>(256);
        let task_inner = inner.clone();
        let task = tokio::spawn(async move {
            let mut events = Events::new(tx);
            run_turn(&task_inner, &prepared, Some(&mut events)).await;
        });
        return sse(&inner.server.config, rx, Some(task.abort_handle()));
    }
    let (status, response) = run_turn(&inner, &prepared, None).await;
    if status == "failed" {
        let message = response
            .pointer("/error/message")
            .and_then(Value::as_str)
            .unwrap_or("The agent run failed.")
            .to_string();
        return server_error(message);
    }
    Json(response).into_response()
}

/// Aborts a request's task when its stream is dropped (the client went
/// away), unless the turn is a background one.
struct AbortOnDrop(Option<tokio::task::AbortHandle>);

impl Drop for AbortOnDrop {
    fn drop(&mut self) {
        if let Some(handle) = self.0.take() {
            handle.abort();
        }
    }
}

fn sse(
    config: &FoundryHostConfig,
    rx: mpsc::Receiver<Event>,
    abort: Option<tokio::task::AbortHandle>,
) -> Response {
    let guard = AbortOnDrop(abort);
    let stream = ReceiverStream::new(rx).map(move |event| {
        let _ = &guard;
        Ok::<_, Infallible>(event)
    });
    let sse = Sse::new(stream);
    if config.sse_keepalive_interval > 0 {
        sse.keep_alive(
            KeepAlive::new()
                .interval(Duration::from_secs(config.sse_keepalive_interval))
                .text("keep-alive"),
        )
        .into_response()
    } else {
        sse.into_response()
    }
}

async fn start_background(inner: Arc<Inner>, prepared: Prepared) -> Response {
    let id = prepared.request.response_id.clone();
    let queued = prepared.skeleton("queued");
    let stored = StoredResponse {
        response: queued.clone(),
        input_items: prepared.input_items.clone(),
        // A cancelled background response keeps this: its history and input
        // (as upstream replays a finished predecessor's history and input).
        transcript: prepared
            .request
            .history
            .iter()
            .chain(&prepared.request.messages)
            .cloned()
            .collect(),
        pause: None,
        // The inherited session state travels with the inherited transcript:
        // a cancelled record must not replay history without the security
        // state (FIDES labels, hidden variables) that history carried.
        session_state: prepared.session_state.clone(),
    };
    if let Err(e) = inner.server.store.put(&id, stored).await {
        return server_error(e.to_string());
    }
    let stream = prepared.create.stream;
    let (tx, rx) = mpsc::channel::<Event>(256);
    let replay = Arc::new(Replay::default());
    inner
        .replays
        .lock()
        .unwrap()
        .insert(id.clone(), replay.clone());
    let task_inner = inner.clone();
    let task_id = id.clone();
    // Registered under the lock the task's own cleanup takes, so a turn that
    // finishes instantly cannot remove its entry before it is inserted (which
    // would leave a finished task registered as running).
    let mut running = inner.running.lock().unwrap();
    let task = tokio::spawn(async move {
        let mut events = Events::new(tx);
        events.replay = Some(replay.clone());
        // Events are always produced (and recorded for replay); with no
        // streaming client the channel's receiver is simply gone.
        run_turn(&task_inner, &prepared, Some(&mut events)).await;
        task_inner.running.lock().unwrap().remove(&task_id);
        end_replay(&task_inner, &task_id, &replay);
    });
    running.insert(id, task.abort_handle());
    drop(running);
    if stream {
        // The run continues if the client disconnects.
        sse(&inner.server.config, rx, None)
    } else {
        Json(queued).into_response()
    }
}

/// Sequenced SSE events for one response.
struct Events {
    tx: mpsc::Sender<Event>,
    sequence: u64,
    replay: Option<Arc<Replay>>,
}

impl Events {
    fn new(tx: mpsc::Sender<Event>) -> Self {
        Self {
            tx,
            sequence: 0,
            replay: None,
        }
    }

    async fn emit(&mut self, kind: &str, mut payload: Value) {
        payload["type"] = json!(kind);
        payload["sequence_number"] = json!(self.sequence);
        self.sequence += 1;
        if let Some(replay) = &self.replay {
            replay.push(kind, &payload);
        }
        let event = Event::default().event(kind).data(payload.to_string());
        // A disconnected client does not stop a background run.
        let _ = self.tx.send(event).await;
    }

    async fn emit_all(&mut self, events: Vec<(String, Value)>) {
        for (kind, payload) in events {
            self.emit(&kind, payload).await;
        }
    }
}

/// Run one turn, emitting stream events when `events` is set; store the
/// outcome when `store` is on. Returns the final status and response.
async fn run_turn(
    inner: &Arc<Inner>,
    prepared: &Prepared,
    mut events: Option<&mut Events>,
) -> (String, Value) {
    let server = &inner.server;
    if let Some(events) = events.as_deref_mut() {
        let skeleton = prepared.skeleton("in_progress");
        events
            .emit(
                "response.created",
                json!({"response": prepared.skeleton("queued")}),
            )
            .await;
        events
            .emit("response.in_progress", json!({"response": skeleton}))
            .await;
    } else if prepared.create.background {
        let _ = update_status(server, prepared, "in_progress").await;
    }
    let mut tracker = OutputTracker::new(
        &prepared.request.response_id,
        server.consent_origins.clone(),
    );
    let result = execute(server, prepared, events.as_deref_mut(), &mut tracker).await;
    let mut pause = None;
    let mut approvals = Vec::new();
    let (status, response, transcript) = match result {
        Ok((agent_response, paused)) => {
            pause = paused;
            tracker.close_all();
            if let Some(events) = events.as_deref_mut() {
                events.emit_all(tracker.drain()).await;
            }
            approvals = tracker.take_approvals();
            let response = final_response(prepared, tracker);
            let status = response["status"]
                .as_str()
                .unwrap_or("completed")
                .to_string();
            let mut transcript = prepared.request.history.clone();
            transcript.extend(prepared.request.messages.iter().cloned());
            transcript.extend(agent_response.messages.iter().cloned());
            (status, response, transcript)
        }
        Err(e) => {
            tracing::error!(response_id = %prepared.request.response_id, error = %e, "hosted response failed");
            let mut response = prepared.skeleton("failed");
            let message = match e {
                TurnError::Public(m) => m,
                TurnError::Run(_) => "The agent run failed.".to_string(),
            };
            response["error"] = json!({"code": "server_error", "message": message});
            let mut transcript = prepared.request.history.clone();
            transcript.extend(prepared.request.messages.iter().cloned());
            ("failed".to_string(), response, transcript)
        }
    };
    // Persist before the terminal event: a client that closes the stream
    // once it sees `response.completed` aborts this task, which must not
    // cancel the write it was told succeeded.
    let (status, response) = if prepared.store {
        // Spawned so a disconnect (which drops this task) cannot cut the
        // writes short and leave the conversation half-updated.
        let mut join_failed = prepared.skeleton("failed");
        let inner = inner.clone();
        let prepared = prepared.clone();
        tokio::spawn(async move {
            // Under the response's terminal lock: a cancel or delete either
            // waits for these writes or has already finalized the response,
            // in which case nothing is written.
            let terminal = prepared.terminal.clone();
            let mut state = terminal.state.lock().await;
            if state.finalized || terminal.stopping() {
                return ("cancelled".to_string(), response);
            }
            match persist(
                &inner.server,
                &prepared,
                &status,
                &response,
                transcript,
                pause,
                approvals,
                &terminal,
            )
            .await
            {
                Ok(true) => (status, response),
                Ok(false) => {
                    state.stopped = true;
                    ("cancelled".to_string(), response)
                }
                Err(_) if terminal.stopping() => {
                    state.stopped = true;
                    ("cancelled".to_string(), response)
                }
                Err(e) => {
                    // A turn whose outcome could not be stored did not
                    // succeed: report it as failed, and record that (best
                    // effort) so a background response is not left in
                    // progress.
                    tracing::error!(error = %e, "failed to persist a hosted response");
                    let mut failed = prepared.skeleton("failed");
                    failed["error"] = json!({
                        "code": "server_error",
                        "message": "The response could not be stored.",
                    });
                    let record = StoredResponse {
                        response: failed.clone(),
                        input_items: prepared.input_items.clone(),
                        transcript: prepared
                            .request
                            .history
                            .iter()
                            .chain(&prepared.request.messages)
                            .cloned()
                            .collect(),
                        pause: None,
                        session_state: prepared.session_state.clone(),
                    };
                    if let Err(e) = inner
                        .server
                        .store
                        .put(&prepared.request.response_id, record)
                        .await
                    {
                        tracing::error!(error = %e, "failed to record a persistence failure");
                    }
                    ("failed".to_string(), failed)
                }
            }
        })
        .await
        .unwrap_or_else(|e| {
            tracing::error!(error = %e, "the persistence task failed");
            join_failed["error"] = json!({
                "code": "server_error",
                "message": "The response could not be stored.",
            });
            ("failed".to_string(), join_failed)
        })
    } else {
        (status, response)
    };
    if let Some(events) = events {
        let kind = match status.as_str() {
            "failed" => "response.failed",
            "incomplete" => "response.incomplete",
            _ => "response.completed",
        };
        events.emit(kind, json!({"response": response})).await;
    }
    (status, response)
}

/// Store the response, then (unless it failed) its conversation's
/// transcript. Stops (returning `false`) before any write once `terminal`
/// is told to stop.
#[allow(clippy::too_many_arguments)] // one turn's outcome, consumed once
async fn persist(
    server: &ResponsesHostServer,
    prepared: &Prepared,
    status: &str,
    response: &Value,
    transcript: Vec<Message>,
    pause: Option<WorkflowPause>,
    approvals: Vec<(String, Content)>,
    terminal: &Terminal,
) -> Result<bool> {
    if !approvals.is_empty() {
        let store = server.approval_store(&prepared.request.context)?;
        for (id, request) in &approvals {
            store.save_approval_request(id, request).await?;
        }
    }
    // A turn that produced no new snapshot (a failed or interrupted run, a
    // workflow) keeps the state it inherited, next to the inherited
    // transcript: continuing from it must not start from a fresh session.
    let session_state = prepared
        .session_out
        .lock()
        .unwrap()
        .take()
        .or_else(|| prepared.session_state.clone());
    let stored = StoredResponse {
        response: response.clone(),
        input_items: prepared.input_items.clone(),
        transcript: transcript.clone(),
        pause,
        session_state: session_state.clone(),
    };
    if terminal.stopping() {
        return Ok(false);
    }
    // The turn's completed sessions (a part of persistence: a session that
    // cannot be saved fails the turn), written before the response record so
    // a client that sees it finished can continue from it at once. Under the
    // response's terminal lock, so a deleted response's snapshot is never
    // recreated; put back to the inherited session when the record cannot
    // be written or a cancel or delete wins.
    let staged = prepared.staged_sessions.lock().unwrap().take();
    let session_keys: Vec<String> = match &staged {
        Some(_) => std::iter::once(response_session_key(&prepared.request.response_id))
            .chain(
                prepared
                    .request
                    .conversation_id
                    .as_deref()
                    .map(conversation_session_key),
            )
            .collect(),
        None => Vec::new(),
    };
    let restore = || async {
        if let Some(staged) = &staged {
            staged.restore(&session_keys).await;
        }
    };
    // The conversation's transcript and state move together. The previous
    // pair is read first (under the conversation's turn lock), before any
    // session advances, so a failed update can put it back rather than leave
    // a new transcript with an old state, and a failed read leaves every
    // session as inherited.
    let conversation_update = match (&prepared.request.conversation_id, status == "failed") {
        (Some(conversation), false) => Some((
            conversation,
            server.store.conversation(conversation).await?,
            server.store.conversation_state(conversation).await?,
        )),
        _ => None,
    };
    if let Some(staged) = &staged {
        staged.save(&session_keys).await?;
    }
    if let Err(e) = server
        .store
        .put(&prepared.request.response_id, stored)
        .await
    {
        restore().await;
        return Err(e);
    }
    // A cancel or delete that arrived during these writes keeps the
    // conversation and every session as they were.
    if terminal.stopping() {
        restore().await;
        return Ok(false);
    }
    // From here every failure restores the sessions it advanced.
    if let Some((conversation, previous_transcript, previous_state)) = conversation_update {
        if let Err(e) = server
            .store
            .update_conversation(conversation, transcript, session_state)
            .await
        {
            if let Err(restore) = server
                .store
                .update_conversation(
                    conversation,
                    previous_transcript.unwrap_or_default(),
                    previous_state,
                )
                .await
            {
                tracing::error!(error = %restore, "failed to restore a conversation after a failed update");
            }
            restore().await;
            return Err(e);
        }
    }
    Ok(true)
}

/// Why a turn failed: a run error (its text stays private) or a projection
/// failure whose message is safe to return.
#[derive(Debug)]
enum TurnError {
    Run(agent_framework_core::error::Error),
    Public(String),
}

impl std::fmt::Display for TurnError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Run(e) => e.fmt(f),
            Self::Public(m) => f.write_str(m),
        }
    }
}

impl From<agent_framework_core::error::Error> for TurnError {
    fn from(e: agent_framework_core::error::Error) -> Self {
        Self::Run(e)
    }
}

impl From<OutputError> for TurnError {
    fn from(e: OutputError) -> Self {
        Self::Public(e.0)
    }
}

impl From<serde_json::Error> for TurnError {
    fn from(e: serde_json::Error) -> Self {
        Self::Run(e.into())
    }
}

async fn update_status(
    server: &ResponsesHostServer,
    prepared: &Prepared,
    status: &str,
) -> Result<()> {
    let id = &prepared.request.response_id;
    if let Some(mut stored) = server.store.get(id).await? {
        stored.response["status"] = json!(status);
        server.store.put(id, stored).await?;
    }
    Ok(())
}

fn run_options(create: &CreateResponse) -> ChatOptions {
    let mut options = ChatOptions::new();
    options.temperature = create.temperature;
    options.top_p = create.top_p;
    options.max_tokens = create.max_output_tokens;
    options.instructions = create.instructions.clone();
    options
}

/// Fold a response (or each streamed update) into the tracker, emitting
/// the stream events as they are produced.
async fn execute(
    server: &ResponsesHostServer,
    prepared: &Prepared,
    events: Option<&mut Events>,
    tracker: &mut OutputTracker,
) -> std::result::Result<(AgentResponse, Option<WorkflowPause>), TurnError> {
    let request = &prepared.request;
    let agent = match &server.target {
        _ if prepared.agent.is_some() => prepared.agent.clone().expect("checked"),
        Target::Agent(agent) => agent.clone(),
        Target::AgentFactory(factory) => factory().await?,
        Target::Workflow { factory, parse } => {
            if server.history == HistorySource::Service {
                return Err(TurnError::Public(
                    "HistorySource::Service is only supported for agents.".into(),
                ));
            }
            let workflow = factory(request)?;
            let storage = server.checkpoints.clone();
            let run = match (&prepared.resume, &storage) {
                (Some(resume), Some(storage)) => {
                    let mut run = workflow
                        .run_from_checkpoint(&resume.checkpoint_id, storage.clone())
                        .await?;
                    run.send_responses(resume.replies.clone()).await?;
                    run
                }
                _ => {
                    let input = match parse {
                        Some(parse) => parse(request)?,
                        None => {
                            let mut all = request.history.clone();
                            all.extend(request.messages.iter().cloned());
                            serde_json::to_value(all)?
                        }
                    };
                    workflow.run(input).await?
                }
            };
            let response = workflow_response(&run.outputs());
            tracker.handle_response(&response)?;
            let pending = run.pending_requests();
            let pause = match (&storage, pending.is_empty()) {
                (Some(storage), false) => {
                    let checkpoint = pause_checkpoint(storage.as_ref(), workflow.id(), &pending)
                        .await?
                        .ok_or_else(|| {
                            TurnError::Public(
                                "The workflow paused without a checkpoint holding its requests; \
                                 build it with the request's checkpoint storage."
                                    .into(),
                            )
                        })?;
                    let mut requests = Vec::new();
                    let mut request_data = Vec::new();
                    for request in &pending {
                        // A built-in `AgentExecutor` computer-use pause: each
                        // pending call is its own `computer_call`, all
                        // answering the one request.
                        if let Some(calls) = computer_use_calls(&request.request_data) {
                            for mut call in calls {
                                let wire_id =
                                    ids::new_id("call", Some(&prepared.request.response_id));
                                call.call_id = wire_id.clone();
                                tracker.handle(&Content::ComputerToolCall(call), None, false)?;
                                requests.push((wire_id, request.request_id.clone()));
                                request_data.push(request.request_data.clone());
                            }
                            continue;
                        }
                        let wire_id =
                            match serde_json::from_value::<Content>(request.request_data.clone()) {
                                // An approval surfaces as `mcp_approval_request`;
                                // its reply is an `mcp_approval_response`.
                                Ok(approval @ Content::FunctionApprovalRequest(_)) => {
                                    tracker.handle(&approval, None, false)?;
                                    tracker.last_approval_id().ok_or_else(|| {
                                        TurnError::Public(
                                            "The approval request was not projected.".into(),
                                        )
                                    })?
                                }
                                other => {
                                    let wire_id =
                                        ids::new_id("call", Some(&prepared.request.response_id));
                                    tracker.handle(
                                        &request_info_call(
                                            &wire_id,
                                            &request.request_data,
                                            other.ok(),
                                        ),
                                        None,
                                        false,
                                    )?;
                                    wire_id
                                }
                            };
                        requests.push((wire_id, request.request_id.clone()));
                        request_data.push(request.request_data.clone());
                    }
                    Some(WorkflowPause {
                        checkpoint_id: checkpoint,
                        requests,
                        request_data,
                    })
                }
                (None, false) => {
                    tracing::warn!(
                        "the workflow paused on request_info but the server has no checkpoint store; \
                         its requests cannot be answered on a later turn"
                    );
                    None
                }
                _ => None,
            };
            if let Some(events) = events {
                events.emit_all(tracker.drain()).await;
            }
            return Ok((response, pause));
        }
    };
    let host_history = server.history == HistorySource::AgentServer;
    let mut messages = if host_history {
        request.history.clone()
    } else {
        Vec::new()
    };
    messages.extend(request.messages.iter().cloned());
    let mut options = run_options(&prepared.create);
    options.store = match server.history {
        HistorySource::AgentServer => Some(false),
        HistorySource::Service => Some(prepared.store),
        HistorySource::Agent => (!prepared.store).then_some(false),
    };
    if let Some(hook) = &server.prepare_options {
        options = hook(request, options)?;
    }
    let options = AgentRunOptions::new().with_chat_options(options);
    let sessions = if host_history {
        None
    } else {
        Some(match &prepared.sessions {
            Some(sessions) => sessions.clone(),
            None => Arc::new(server.host_sessions(&request.context)?),
        })
    };
    // The session the turn inherited, to put back if its writes fail part-way.
    let mut inherited = None;
    let (mut session, local_history) = match &sessions {
        // The transcript is replayed; only the state bag carries over.
        None => match &prepared.session_state {
            Some(state) => (
                agent_framework_core::session::AgentSession::from_dict(state)?,
                None,
            ),
            None => (agent.create_session(), None),
        },
        Some(sessions) => {
            let (mut session, prior) =
                load_session(server, sessions, request, agent.as_ref()).await?;
            inherited = Some((session_snapshot(&session), prior.clone()));
            let history = attach_local_history(&mut session, prior);
            (session, history)
        }
    };
    let provider_background =
        server.background_source == BackgroundSource::Provider && prepared.create.background;
    let response = match events {
        _ if provider_background => {
            if server.history != HistorySource::Service {
                return Err(TurnError::Public(
                    "BackgroundSource::Provider requires HistorySource::Service.".into(),
                ));
            }
            run_provider_background(
                server,
                agent.as_ref(),
                &mut session,
                messages,
                options,
                events,
                tracker,
            )
            .await?
        }
        None => {
            let response = agent
                .run_with_options(messages, Some(&mut session), options)
                .await?;
            if let Some(id) = response.conversation_id.as_deref() {
                session.try_adopt_service_session_id(id);
            }
            tracker.handle_response(&response)?;
            response
        }
        Some(events) => {
            // The stream owns a clone; the state bag is shared, the service
            // conversation id is adopted from the updates.
            let mut stream = agent
                .run_stream(messages, Some(session.clone()), Some(options))
                .await?;
            let mut updates = Vec::new();
            while let Some(update) = stream.next().await {
                let update = update?;
                if let Some(id) = update.conversation_id.as_deref() {
                    session.try_adopt_service_session_id(id);
                }
                tracker.handle_update(&update)?;
                events.emit_all(tracker.drain()).await;
                updates.push(update);
            }
            AgentResponse::from_updates(updates)
        }
    };
    if host_history {
        // Detached, without history: the next turn replays the transcript.
        let mut state = session.to_dict();
        if let Some(map) = state.as_object_mut() {
            map.remove("service_session_id");
        }
        *prepared.session_out.lock().unwrap() = Some(state);
    }
    if let (false, true, Some(sessions)) = (host_history, prepared.store, sessions) {
        // Staged, not written: [`persist`] writes them with the response,
        // under its terminal lock, so a turn whose response is not stored
        // (a failed write, a cancel or delete first) leaves every session as
        // it inherited it.
        *prepared.staged_sessions.lock().unwrap() = Some(StagedSessions {
            sessions,
            agent: agent.clone(),
            session,
            history: local_history,
            inherited,
        });
    }
    Ok((response, None))
}

/// A session's full snapshot, to restore it exactly as stored: with
/// `session-store`, the store's serialized form (its history provider's
/// messages included); without, its state (the host keeps the history
/// apart).
fn session_snapshot(session: &agent_framework_core::session::AgentSession) -> Value {
    #[cfg(feature = "session-store")]
    {
        agent_framework_core::session_store::serialize_session(session)
    }
    #[cfg(not(feature = "session-store"))]
    {
        session.to_dict()
    }
}

/// The session a [`session_snapshot`] describes.
fn restore_session_snapshot(
    agent: &dyn SupportsAgentRun,
    snapshot: &Value,
) -> Result<agent_framework_core::session::AgentSession> {
    #[cfg(feature = "session-store")]
    {
        agent_framework_core::session_store::deserialize_session(agent, snapshot)
    }
    #[cfg(not(feature = "session-store"))]
    {
        let _ = agent;
        agent_framework_core::session::AgentSession::from_dict(snapshot)
    }
}

/// A turn's completed host sessions, waiting for [`persist`].
struct StagedSessions {
    sessions: Arc<HostSessions>,
    agent: Arc<dyn SupportsAgentRun>,
    session: agent_framework_core::session::AgentSession,
    history: Option<agent_framework_core::history::InMemoryHistoryProvider>,
    /// The inherited session's state and history, restored if the turn's
    /// writes fail part-way.
    inherited: Option<(Value, Option<Vec<Message>>)>,
}

impl StagedSessions {
    /// Save the turn's session under `keys`, in order. A failure restores
    /// the keys already written to the inherited session (best effort).
    async fn save(&self, keys: &[String]) -> Result<()> {
        for (i, key) in keys.iter().enumerate() {
            if let Err(e) = self
                .sessions
                .save(
                    self.agent.as_ref(),
                    key,
                    &self.session,
                    self.history.as_ref(),
                )
                .await
            {
                self.restore(&keys[..i]).await;
                return Err(e);
            }
        }
        Ok(())
    }

    /// Put `keys` back to the inherited session (best effort, logged).
    async fn restore(&self, keys: &[String]) {
        let Some((state, prior)) = &self.inherited else {
            return;
        };
        let session = match restore_session_snapshot(self.agent.as_ref(), state) {
            Ok(session) => session,
            Err(e) => {
                tracing::error!(error = %e, "failed to rebuild an inherited session");
                return;
            }
        };
        let history = prior
            .clone()
            .map(agent_framework_core::history::InMemoryHistoryProvider::with_messages);
        for key in keys {
            if let Err(e) = self
                .sessions
                .save(self.agent.as_ref(), key, &session, history.as_ref())
                .await
            {
                tracing::error!(error = %e, "failed to restore an inherited session");
            }
        }
    }
}

/// Run a turn as a provider background response (upstream
/// `_run_provider_background`): submit with `background`, then poll with the
/// continuation token the provider returns until it returns none. Each
/// response's finished output is recorded (and streamed) as it arrives; an
/// unfinished one contributes only the completed tool calls and results a
/// tool loop put ahead of it, since polling repeats the rest.
async fn run_provider_background(
    server: &ResponsesHostServer,
    agent: &dyn SupportsAgentRun,
    session: &mut agent_framework_core::session::AgentSession,
    messages: Vec<Message>,
    options: AgentRunOptions,
    mut events: Option<&mut Events>,
    tracker: &mut OutputTracker,
) -> std::result::Result<AgentResponse, TurnError> {
    let submit = options.clone().with_background(true);
    let mut current = agent
        .run_with_options(messages, Some(&mut *session), submit)
        .await?;
    let mut recorded: Vec<Message> = Vec::new();
    let mut round = 0usize;
    loop {
        if let Some(id) = current.conversation_id.as_deref() {
            session.try_adopt_service_session_id(id);
        }
        let token = current.continuation_token.take();
        let mut output = current;
        if token.is_some() {
            output.messages = completed_prefix(std::mem::take(&mut output.messages));
            output.finish_reason = None;
        }
        // Distinct ids per response, so the tracker does not fold one
        // poll's messages into another's.
        for (i, message) in output.messages.iter_mut().enumerate() {
            if message.message_id.is_none() {
                message.message_id = Some(format!("bg{round}-{i}"));
            }
        }
        if !output.messages.is_empty() || output.usage_details.is_some() {
            tracker.handle_response(&output)?;
            if let Some(events) = events.as_deref_mut() {
                events.emit_all(tracker.drain()).await;
            }
            recorded.extend(output.messages.iter().cloned());
        }
        let Some(token) = token else {
            output.messages = recorded;
            return Ok(output);
        };
        round += 1;
        tokio::time::sleep(server.background_poll_interval).await;
        let poll = options
            .clone()
            .with_background(true)
            .with_continuation_token(token);
        current = agent
            .run_with_options(Vec::new(), Some(&mut *session), poll)
            .await?;
    }
}

/// The messages of an unfinished response that a tool loop completed ahead
/// of it: everything up to and including its last function result.
fn completed_prefix(mut messages: Vec<Message>) -> Vec<Message> {
    for index in (0..messages.len()).rev() {
        let last_result = messages[index]
            .contents
            .iter()
            .rposition(|c| matches!(c, Content::FunctionResult(_)));
        if let Some(offset) = last_result {
            messages.truncate(index + 1);
            messages[index].contents.truncate(offset + 1);
            return messages;
        }
    }
    Vec::new()
}

/// The agent session to continue: the conversation's, else the previous
/// response's, else a new one.
fn response_session_key(response_id: &str) -> String {
    format!("response-{response_id}")
}

fn conversation_session_key(conversation_id: &str) -> String {
    format!("conversation-{conversation_id}")
}

/// One turn's view of the host-kept agent sessions.
#[cfg(feature = "session-store")]
struct HostSessions(
    Arc<dyn agent_framework_core::session_store::AgentSessionStore>,
    /// The configured agent name, the stable namespace sessions are stored
    /// under (see [`Namespaced`]).
    String,
);

/// An agent presented to the session store under a stable, host-level id,
/// so sessions resume across agent instances: an `agent_factory` may build
/// each request's agent with a fresh id, and session stores key by agent id.
#[cfg(feature = "session-store")]
struct Namespaced<'a> {
    inner: &'a dyn SupportsAgentRun,
    id: String,
}

#[cfg(feature = "session-store")]
impl<'a> Namespaced<'a> {
    fn new(inner: &'a dyn SupportsAgentRun, configured: &str) -> Self {
        let name = if configured.is_empty() {
            inner.name().unwrap_or("agent")
        } else {
            configured
        };
        Self {
            inner,
            id: format!("foundry-responses/{name}"),
        }
    }
}

#[cfg(feature = "session-store")]
#[async_trait]
impl SupportsAgentRun for Namespaced<'_> {
    async fn run(
        &self,
        messages: Vec<Message>,
        session: Option<&mut agent_framework_core::session::AgentSession>,
    ) -> Result<AgentResponse> {
        self.inner.run(messages, session).await
    }

    async fn run_with_options(
        &self,
        messages: Vec<Message>,
        session: Option<&mut agent_framework_core::session::AgentSession>,
        options: AgentRunOptions,
    ) -> Result<AgentResponse> {
        self.inner
            .run_with_options(messages, session, options)
            .await
    }

    fn id(&self) -> &str {
        &self.id
    }

    fn name(&self) -> Option<&str> {
        self.inner.name()
    }

    fn create_session(&self) -> agent_framework_core::session::AgentSession {
        self.inner.create_session()
    }
}
#[cfg(not(feature = "session-store"))]
struct HostSessions(Arc<Mutex<HashMap<String, SessionSnapshot>>>);

/// A detached copy of a session (its `to_dict` state and the messages of the
/// history provider the host attached), so each response keeps its own
/// continuation state: live clones would share the state bag and history.
#[cfg(not(feature = "session-store"))]
#[derive(Clone)]
struct SessionSnapshot {
    state: Value,
    history: Option<Vec<Message>>,
}

/// Without the `session-store` feature the host owns the local history: it
/// attaches an in-memory history provider (seeded from the snapshot) to a
/// session the service does not manage, and keeps its handle to snapshot it.
#[cfg(not(feature = "session-store"))]
fn attach_local_history(
    session: &mut agent_framework_core::session::AgentSession,
    prior: Option<Vec<Message>>,
) -> Option<agent_framework_core::history::InMemoryHistoryProvider> {
    if session.service_session_id().is_some() {
        return None;
    }
    let provider = agent_framework_core::history::InMemoryHistoryProvider::with_messages(
        prior.unwrap_or_default(),
    );
    session
        .context_providers
        .insert(0, Arc::new(provider.clone()));
    Some(provider)
}

#[cfg(feature = "session-store")]
fn attach_local_history(
    _session: &mut agent_framework_core::session::AgentSession,
    _prior: Option<Vec<Message>>,
) -> Option<agent_framework_core::history::InMemoryHistoryProvider> {
    None
}

/// For a stored conversation turn kept in host sessions, record the
/// conversation's session as it is now under the turn's own response key,
/// before the turn can run, fail or be cancelled (even while queued). The
/// conversation's turn lock is held, so this is exactly the session the turn
/// inherits; a completed turn replaces it with its own, and a cancelled or
/// failed one keeps it, so continuing from it never picks up the
/// conversation's later turns. Resolves the agent (kept for the turn) to
/// address its sessions.
async fn snapshot_inherited_session(
    server: &ResponsesHostServer,
    prepared: &mut Prepared,
) -> std::result::Result<(), TurnError> {
    let Some(conversation) = &prepared.request.conversation_id else {
        return Ok(());
    };
    if !prepared.store || server.history == HistorySource::AgentServer {
        return Ok(());
    }
    let agent = match &server.target {
        Target::Agent(agent) => agent.clone(),
        Target::AgentFactory(factory) => factory().await?,
        Target::Workflow { .. } => return Ok(()),
    };
    let sessions = Arc::new(server.host_sessions(&prepared.request.context)?);
    sessions
        .copy_or_fresh(
            agent.as_ref(),
            &conversation_session_key(conversation),
            &response_session_key(&prepared.request.response_id),
        )
        .await?;
    prepared.agent = Some(agent);
    prepared.sessions = Some(sessions);
    Ok(())
}

/// What [`HostSessions::load`] returns: the session and, without the
/// `session-store` feature, its detached history.
type LoadedSession = (
    agent_framework_core::session::AgentSession,
    Option<Vec<Message>>,
);

impl HostSessions {
    async fn load(&self, agent: &dyn SupportsAgentRun, key: &str) -> Result<Option<LoadedSession>> {
        #[cfg(feature = "session-store")]
        {
            let key = agent_framework_core::session_store::AgentSessionStoreKey::new(key)?;
            let agent = Namespaced::new(agent, &self.1);
            Ok(self.0.get_session(&agent, &key).await?.map(|s| (s, None)))
        }
        #[cfg(not(feature = "session-store"))]
        {
            let _ = agent;
            let snapshot = self.0.lock().unwrap().get(key).cloned();
            snapshot
                .map(|snapshot| {
                    Ok((
                        agent_framework_core::session::AgentSession::from_dict(&snapshot.state)?,
                        snapshot.history,
                    ))
                })
                .transpose()
        }
    }

    /// Store `from`'s session under `to` as it is now, or a new session
    /// when `from` has none.
    async fn copy_or_fresh(
        &self,
        agent: &dyn SupportsAgentRun,
        from: &str,
        to: &str,
    ) -> Result<()> {
        #[cfg(feature = "session-store")]
        {
            let from = agent_framework_core::session_store::AgentSessionStoreKey::new(from)?;
            let to = agent_framework_core::session_store::AgentSessionStoreKey::new(to)?;
            let namespaced = Namespaced::new(agent, &self.1);
            let session = match self.0.get_session(&namespaced, &from).await? {
                Some(session) => session,
                None => agent.create_session(),
            };
            self.0.save_session(&namespaced, &to, &session).await
        }
        #[cfg(not(feature = "session-store"))]
        {
            let mut sessions = self.0.lock().unwrap();
            let snapshot = match sessions.get(from) {
                Some(snapshot) => snapshot.clone(),
                None => SessionSnapshot {
                    state: agent.create_session().to_dict(),
                    history: None,
                },
            };
            sessions.insert(to.to_string(), snapshot);
            Ok(())
        }
    }

    async fn delete(&self, agent: &dyn SupportsAgentRun, key: &str) -> Result<()> {
        #[cfg(feature = "session-store")]
        {
            let key = agent_framework_core::session_store::AgentSessionStoreKey::new(key)?;
            let agent = Namespaced::new(agent, &self.1);
            self.0.delete_session(&agent, &key).await
        }
        #[cfg(not(feature = "session-store"))]
        {
            let _ = agent;
            self.0.lock().unwrap().remove(key);
            Ok(())
        }
    }

    async fn save(
        &self,
        agent: &dyn SupportsAgentRun,
        key: &str,
        session: &agent_framework_core::session::AgentSession,
        history: Option<&agent_framework_core::history::InMemoryHistoryProvider>,
    ) -> Result<()> {
        #[cfg(feature = "session-store")]
        {
            let _ = history;
            let key = agent_framework_core::session_store::AgentSessionStoreKey::new(key)?;
            let agent = Namespaced::new(agent, &self.1);
            self.0.save_session(&agent, &key, session).await
        }
        #[cfg(not(feature = "session-store"))]
        {
            let _ = agent;
            let snapshot = SessionSnapshot {
                state: session.to_dict(),
                history: history.map(|h| h.list_messages()),
            };
            self.0.lock().unwrap().insert(key.to_string(), snapshot);
            Ok(())
        }
    }
}

/// How many cancelled or failed predecessors [`load_session`] looks through.
const MAX_INHERITED_HOPS: usize = 64;

async fn load_session(
    server: &ResponsesHostServer,
    sessions: &HostSessions,
    request: &HostedResponseRequest,
    agent: &dyn SupportsAgentRun,
) -> std::result::Result<LoadedSession, TurnError> {
    let key = match (&request.conversation_id, &request.previous_response_id) {
        (Some(conversation), _) => Some(conversation_session_key(conversation)),
        (None, Some(previous)) => Some(response_session_key(previous)),
        _ => None,
    };
    let stored = match &key {
        Some(key) => sessions.load(agent, key).await?,
        None => None,
    };
    match (
        stored,
        &request.previous_response_id,
        &request.conversation_id,
    ) {
        (Some(loaded), _, _) => Ok(loaded),
        (None, Some(previous), None) => inherited_session(server, sessions, previous, agent)
            .await?
            .ok_or_else(|| {
                TurnError::Public(format!(
                    "Cannot find an existing agent session for previous_response_id={previous}."
                ))
            }),
        _ => Ok((agent.create_session(), None)),
    }
}

/// The session a cancelled or failed response inherited, since only a
/// completed turn saves one under its response (the counterpart of the
/// `session_state` an `AgentServer` record keeps): its predecessor's, else
/// a new one. (A conversation turn records its inherited session under its
/// own key before running; see [`snapshot_inherited_session`].) `None` when `previous` is not such a
/// response (or the chain is too long or broken).
async fn inherited_session(
    server: &ResponsesHostServer,
    sessions: &HostSessions,
    previous: &str,
    agent: &dyn SupportsAgentRun,
) -> std::result::Result<Option<LoadedSession>, TurnError> {
    let mut current = previous.to_string();
    for _ in 0..MAX_INHERITED_HOPS {
        let Some(stored) = server.store.get(&current).await? else {
            return Ok(None);
        };
        let response = &stored.response;
        if !matches!(response["status"].as_str(), Some("cancelled" | "failed")) {
            return Ok(None);
        }
        if response["conversation"]["id"].is_string() {
            // A conversation turn records the session it inherited under its
            // own key before it runs; the conversation's current session has
            // moved on, so without that record there is nothing to resume.
            return Ok(None);
        }
        let Some(next) = response["previous_response_id"].as_str() else {
            return Ok(Some((agent.create_session(), None)));
        };
        if let Some(loaded) = sessions.load(agent, &response_session_key(next)).await? {
            return Ok(Some(loaded));
        }
        current = next.to_string();
    }
    Ok(None)
}

/// This turn's input as messages, with each `mcp_approval_response` item
/// resolved through the approval store into the original request's
/// function-approval response (upstream `_item_to_message`). As upstream,
/// an unstored (`store=false`) turn keeps no approval state: its approval
/// requests are not saved, and it cannot resolve an `mcp_approval_response`.
async fn turn_messages(
    server: &ResponsesHostServer,
    context: &FoundryRequestContext,
    input: &Value,
    stored: bool,
) -> std::result::Result<Vec<Message>, String> {
    let items = match input {
        Value::Array(items) => items.clone(),
        other => {
            return Ok(responses_to_run(&ResponsesRequest {
                input: other.clone(),
                ..Default::default()
            }))
        }
    };
    let mut messages = Vec::new();
    let mut pending: Vec<Value> = Vec::new();
    let flush = |pending: &mut Vec<Value>, messages: &mut Vec<Message>| {
        if !pending.is_empty() {
            messages.extend(responses_to_run(&ResponsesRequest {
                input: Value::Array(std::mem::take(pending)),
                ..Default::default()
            }));
        }
    };
    for item in items {
        #[cfg(feature = "experimental-computer-use")]
        if let Some(message) = crate::computer::item_to_message(&item)? {
            flush(&mut pending, &mut messages);
            messages.push(message);
            continue;
        }
        if item.get("type").and_then(Value::as_str) != Some("mcp_approval_response") {
            pending.push(item);
            continue;
        }
        flush(&mut pending, &mut messages);
        let (Some(id), Some(approve)) = (
            item.get("approval_request_id").and_then(Value::as_str),
            item.get("approve").and_then(Value::as_bool),
        ) else {
            return Err(
                "An mcp_approval_response requires an approval_request_id and a boolean approve."
                    .into(),
            );
        };
        if !stored {
            return Err(
                "An mcp_approval_response needs store=true: unstored turns keep no approval state."
                    .into(),
            );
        }
        let store = server.approval_store(context).map_err(|e| e.to_string())?;
        let request = store.load_approval_request(id).await.map_err(|_| {
            format!(
                "Approval request with ID '{id}' does not exist (approval requests of store=false responses are not kept)."
            )
        })?;
        let Content::FunctionApprovalRequest(request) = request else {
            return Err(format!(
                "Approval request with ID '{id}' is not a function approval request."
            ));
        };
        messages.push(Message::with_contents(
            agent_framework_core::types::Role::user(),
            vec![Content::FunctionApprovalResponse(
                request.create_response(approve),
            )],
        ));
    }
    flush(&mut pending, &mut messages);
    Ok(messages)
}

/// The newest checkpoint of `workflow_id` holding every pending request.
async fn pause_checkpoint(
    storage: &dyn CheckpointStorage,
    workflow_id: &str,
    pending: &[agent_framework_core::workflow::PendingRequest],
) -> Result<Option<String>> {
    let checkpoints = storage.list(Some(workflow_id)).await?;
    Ok(checkpoints
        .into_iter()
        .filter(|cp| {
            pending.iter().all(|p| {
                cp.pending_requests
                    .iter()
                    .any(|q| q.request_id == p.request_id)
            })
        })
        .max_by_key(|cp| cp.timestamp_millis)
        .map(|cp| cp.checkpoint_id))
}

/// A pending request as the call a client answers (upstream `_project`): a
/// framework function call keeps its name and arguments under the wire id, a
/// computer call keeps its actions under the wire id; anything else is
/// `request_info({request_id, request})`.
fn request_info_call(wire_id: &str, data: &Value, content: Option<Content>) -> Content {
    use agent_framework_core::types::{FunctionArguments, FunctionCallContent};
    match content {
        Some(Content::FunctionCall(mut call)) => {
            call.call_id = wire_id.to_string();
            return Content::FunctionCall(call);
        }
        #[cfg(feature = "experimental-computer-use")]
        Some(Content::ComputerToolCall(mut call)) => {
            call.call_id = wire_id.to_string();
            return Content::ComputerToolCall(call);
        }
        _ => {}
    }
    let mut arguments = HashMap::new();
    arguments.insert("request_id".to_string(), json!(wire_id));
    arguments.insert("request".to_string(), data.clone());
    Content::FunctionCall(FunctionCallContent::new(
        wire_id,
        "request_info",
        Some(FunctionArguments::Object(arguments)),
    ))
}

/// Map the turn's replies onto the paused workflow's requests (upstream
/// `_load_replies`): `function_call_output` answers a call, an
/// `mcp_approval_response` answers an approval with the original request's
/// function-approval response, and a `computer_call_output` answers a
/// computer call with its typed result. The whole pending batch must be
/// answered, exactly once, and not mixed with new input. Function outputs
/// that parse as JSON are passed as JSON; otherwise as the string.
fn workflow_replies(
    pause: &WorkflowPause,
    input: &Value,
) -> std::result::Result<HashMap<String, Value>, String> {
    let items: Vec<Value> = match input {
        Value::Array(items) => items.clone(),
        Value::Null => Vec::new(),
        other => vec![other.clone()],
    };
    if items.is_empty() {
        return Err("Workflow replies require an exact pending stored checkpoint.".into());
    }
    // `(request id, pending content, part of a computer-use envelope)`.
    let pending = |wire: &str| {
        pause.requests.iter().position(|(w, _)| w == wire).map(|i| {
            let data = pause.request_data.get(i).cloned().unwrap_or(Value::Null);
            let request_id = pause.requests[i].1.clone();
            if let Some(calls) = computer_use_calls(&data) {
                // The envelope's calls were projected in order.
                let k = pause.requests[..i]
                    .iter()
                    .filter(|(_, r)| *r == request_id)
                    .count();
                let call = calls.into_iter().nth(k).map(Content::ComputerToolCall);
                return (request_id, call, true);
            }
            (
                request_id,
                serde_json::from_value::<Content>(data).ok(),
                false,
            )
        })
    };
    let mut replies: HashMap<String, Value> = HashMap::new();
    let mut answered = std::collections::HashSet::new();
    for item in items {
        let wire = item
            .get("call_id")
            .or_else(|| item.get("approval_request_id"))
            .and_then(Value::as_str)
            .map(str::to_string);
        let (request_id, reply) = match item.get("type").and_then(Value::as_str) {
            Some("mcp_approval_response") => {
                let (Some(wire), Some(approve)) = (
                    item.get("approval_request_id").and_then(Value::as_str),
                    item.get("approve").and_then(Value::as_bool),
                ) else {
                    return Err(
                        "An approval reply requires its exact ID and a boolean decision.".into(),
                    );
                };
                let Some((request_id, Some(Content::FunctionApprovalRequest(request)), _)) =
                    pending(wire)
                else {
                    return Err(
                        "The approval is unavailable in this exact pending checkpoint.".into(),
                    );
                };
                let response = Content::FunctionApprovalResponse(request.create_response(approve));
                (
                    request_id,
                    serde_json::to_value(response).map_err(|e| e.to_string())?,
                )
            }
            Some(kind @ ("function_call_output" | "computer_call_output")) => {
                let Some(call_id) = item.get("call_id").and_then(Value::as_str) else {
                    return Err("A workflow reply requires its pending call ID.".into());
                };
                let Some((request_id, content, envelope)) = pending(call_id) else {
                    return Err(
                        "A reply must match its wire ID in the exact pending workflow checkpoint."
                            .into(),
                    );
                };
                if matches!(content, Some(Content::FunctionApprovalRequest(_))) {
                    return Err("An approval cannot be replaced by a function result.".into());
                }
                if envelope {
                    // One result per call; the request is answered with all
                    // of them (core's computer-use resumption).
                    if kind != "computer_call_output" {
                        return Err(
                            "A pending computer call must be answered with a computer_call_output."
                                .into(),
                        );
                    }
                    let result = computer_reply(&item, content)?;
                    if !answered.insert(call_id.to_string()) {
                        return Err("Duplicate workflow replies are not allowed.".into());
                    }
                    if let Value::Array(results) =
                        replies.entry(request_id).or_insert_with(|| json!([]))
                    {
                        results.push(result);
                    }
                    continue;
                }
                if kind == "computer_call_output" {
                    (request_id, computer_reply(&item, content)?)
                } else {
                    let output = match item.get("output") {
                        Some(Value::String(text)) => serde_json::from_str(text)
                            .unwrap_or_else(|_| Value::String(text.clone())),
                        Some(other) => other.clone(),
                        None => Value::Null,
                    };
                    (request_id, output)
                }
            }
            _ => return Err("Pending workflow replies cannot be mixed with new input.".into()),
        };
        if replies.insert(request_id, reply).is_some() || !wire.is_some_and(|w| answered.insert(w))
        {
            return Err("Duplicate workflow replies are not allowed.".into());
        }
    }
    if answered.len() != pause.requests.len() {
        return Err("Answer exactly the complete pending workflow request batch.".into());
    }
    Ok(replies)
}

/// The pending calls of a built-in `AgentExecutor` computer-use pause (a
/// [`ComputerUseRequest`](agent_framework_core::workflow::ComputerUseRequest)
/// envelope); `None` for any other request.
#[cfg(feature = "experimental-computer-use")]
fn computer_use_calls(
    data: &Value,
) -> Option<Vec<agent_framework_core::types::ComputerToolCallContent>> {
    serde_json::from_value::<agent_framework_core::workflow::ComputerUseRequest>(data.clone())
        .ok()
        .map(|request| request.computer_calls)
        .filter(|calls| !calls.is_empty())
}

#[cfg(not(feature = "experimental-computer-use"))]
fn computer_use_calls(
    _: &Value,
) -> Option<Vec<agent_framework_core::types::ComputerToolCallContent>> {
    None
}

/// A `computer_call_output` answering a paused workflow's computer call: the
/// typed result, correlated with the original call.
#[cfg(feature = "experimental-computer-use")]
fn computer_reply(item: &Value, pending: Option<Content>) -> std::result::Result<Value, String> {
    let Some(Content::ComputerToolCall(call)) = pending else {
        return Err("The computer reply has no matching pending computer request.".into());
    };
    let message = crate::computer::item_to_message(item)?.ok_or_else(|| {
        "A computer reply requires a typed screenshot and safety acknowledgement.".to_string()
    })?;
    let [Content::ComputerToolResult(mut result)] = <[Content; 1]>::try_from(message.contents)
        .map_err(|_| {
            "A computer reply requires a typed screenshot and safety acknowledgement.".to_string()
        })?
    else {
        return Err(
            "A computer reply requires a typed screenshot and safety acknowledgement.".into(),
        );
    };
    result.call_id = call.call_id;
    serde_json::to_value(Content::ComputerToolResult(result)).map_err(|e| e.to_string())
}

#[cfg(not(feature = "experimental-computer-use"))]
fn computer_reply(_: &Value, _: Option<Content>) -> std::result::Result<Value, String> {
    Err("Computer replies need the `experimental-computer-use` feature.".into())
}

/// A workflow's outputs as an agent response: agent responses and messages
/// keep their contents; anything else becomes text.
fn workflow_response(outputs: &[Value]) -> AgentResponse {
    let mut messages = Vec::new();
    for value in outputs {
        if let Ok(response) = serde_json::from_value::<AgentResponse>(value.clone()) {
            if !response.messages.is_empty() {
                messages.extend(response.messages);
                continue;
            }
        }
        if let Ok(list) = serde_json::from_value::<Vec<Message>>(value.clone()) {
            if !list.is_empty() {
                messages.extend(
                    list.into_iter()
                        .filter(|m| m.role.to_string() == "assistant"),
                );
                continue;
            }
        }
        if let Ok(message) = serde_json::from_value::<Message>(value.clone()) {
            messages.push(message);
            continue;
        }
        let text = output_text(value);
        if !text.is_empty() {
            messages.push(Message::assistant(text));
        }
    }
    AgentResponse {
        messages,
        ..Default::default()
    }
}

/// A workflow output as text.
fn output_text(value: &Value) -> String {
    match value {
        Value::String(s) => s.clone(),
        Value::Null => String::new(),
        other => other.to_string(),
    }
}

/// The final response object from the tracker's items.
fn final_response(prepared: &Prepared, tracker: OutputTracker) -> Value {
    let (output, usage, incomplete) = tracker.finish();
    let output_text: String = output
        .iter()
        .filter(|i| i["type"] == "message")
        .flat_map(|i| i["content"].as_array().cloned().unwrap_or_default())
        .filter(|p| p["type"] == "output_text")
        .filter_map(|p| p["text"].as_str().map(str::to_string))
        .collect();
    let status = if incomplete.is_some() {
        "incomplete"
    } else {
        "completed"
    };
    let mut value = json!({
        "output": output,
        "output_text": output_text,
        "parallel_tool_calls": true,
        "tool_choice": "auto",
        "tools": [],
        "error": null,
        "incomplete_details": incomplete.map(|reason| json!({"reason": reason})),
    });
    if let Some(usage) = usage {
        value["usage"] = usage;
    }
    prepared.decorate(value, status)
}

#[derive(Debug, Deserialize, Default)]
struct GetQuery {
    #[serde(default)]
    stream: Option<String>,
    #[serde(default)]
    starting_after: Option<String>,
}

async fn get_response(
    State(inner): State<Arc<Inner>>,
    Path(id): Path<String>,
    Query(query): Query<GetQuery>,
) -> Response {
    let stored = match inner.server.store.get(&id).await {
        Ok(Some(stored)) => stored,
        Ok(None) => return not_found(&id),
        Err(e) => return server_error(e.to_string()),
    };
    if !matches!(query.stream.as_deref(), Some("true") | Some("1")) {
        return Json(stored.response).into_response();
    }
    let after: i64 = match query.starting_after.as_deref().map(str::parse) {
        None => -1,
        Some(Ok(n)) => n,
        Some(Err(_)) => return bad_request("starting_after must be an integer"),
    };
    if stored.response["background"] != json!(true) {
        return bad_request(
            "This response cannot be streamed because it was not created with background=true.",
        );
    }
    let Some(replay) = inner.replays.lock().unwrap().get(&id).cloned() else {
        return bad_request(
            "This response cannot be streamed because it was not created with stream=true \
             or the stream TTL has expired.",
        );
    };
    let (tx, rx) = mpsc::channel::<Event>(256);
    tokio::spawn(async move {
        let mut next = 0usize;
        loop {
            let changed = replay.changed.notified();
            tokio::pin!(changed);
            changed.as_mut().enable();
            let batch: Vec<(String, Value)> = replay.events.lock().unwrap()[next..].to_vec();
            next += batch.len();
            for (kind, payload) in batch {
                if payload["sequence_number"].as_i64().unwrap_or(-1) <= after {
                    continue;
                }
                let event = Event::default().event(kind).data(payload.to_string());
                if tx.send(event).await.is_err() {
                    return;
                }
            }
            let done = replay.done.load(std::sync::atomic::Ordering::SeqCst);
            if done && next >= replay.events.lock().unwrap().len() {
                return;
            }
            changed.await;
        }
    });
    sse(&inner.server.config, rx, None)
}

async fn delete_response(
    State(inner): State<Arc<Inner>>,
    headers: HeaderMap,
    Path(id): Path<String>,
) -> Response {
    let handle = inner.running.lock().unwrap().remove(&id);
    let was_running = handle.is_some();
    let terminal = inner.terminal(&id);
    if let Some(handle) = handle {
        terminal
            .stop
            .store(true, std::sync::atomic::Ordering::SeqCst);
        handle.abort();
    }
    // A deleted response is not replayable: end any open replay streams
    // (the aborted task never will) and drop its buffer.
    let replay = inner.replays.lock().unwrap().remove(&id);
    if let Some(replay) = replay {
        replay.finish();
    }
    // An in-flight persistence (it outlives the abort) has been told to
    // stop: wait for it, then finalize so one that has not yet started
    // writes nothing. The response stays deleted.
    let mut state = terminal.state.lock().await;
    let exists = match inner.server.store.get(&id).await {
        Ok(stored) => stored.is_some(),
        Err(e) => return server_error(e.to_string()),
    };
    // Its session snapshot goes with it (the conversation keeps its own).
    if exists || was_running {
        let context = FoundryRequestContext::identity_from_headers(&headers, None);
        if let Err(e) = delete_response_session(&inner.server, &context, &id).await {
            tracing::error!(error = %e, "failed to delete a response's session");
            return server_error("The response's session could not be deleted.".to_string());
        }
    }
    let deleted = inner.server.store.delete(&id).await;
    if was_running || matches!(deleted, Ok(true)) {
        state.finalized = true;
    }
    match deleted {
        Ok(true) => Json(json!({"id": id, "object": "response", "deleted": true})).into_response(),
        Ok(false) => not_found(&id),
        Err(e) => server_error(e.to_string()),
    }
}

/// Delete the agent session a stored turn saved under `id`'s response key
/// (`HistorySource::Agent` / `Service`).
async fn delete_response_session(
    server: &ResponsesHostServer,
    context: &FoundryRequestContext,
    id: &str,
) -> std::result::Result<(), TurnError> {
    if server.history == HistorySource::AgentServer {
        return Ok(());
    }
    let agent = match &server.target {
        Target::Agent(agent) => agent.clone(),
        Target::AgentFactory(factory) => factory().await?,
        Target::Workflow { .. } => return Ok(()),
    };
    server
        .host_sessions(context)?
        .delete(agent.as_ref(), &response_session_key(id))
        .await?;
    Ok(())
}

async fn cancel(State(inner): State<Arc<Inner>>, Path(id): Path<String>) -> Response {
    let stored = match inner.server.store.get(&id).await {
        Ok(Some(stored)) => stored,
        Ok(None) => return not_found(&id),
        Err(e) => return server_error(e.to_string()),
    };
    if stored.response["background"] != json!(true) {
        return bad_request("Only background responses can be cancelled.");
    }
    let handle = inner.running.lock().unwrap().remove(&id);
    let mut stored = stored;
    if let Some(handle) = handle {
        // The aborted turn's persistence outlives the abort: tell it to stop,
        // then wait for it under the response's terminal lock (or finalize
        // first, so it writes nothing). The turn may have committed its
        // terminal status meanwhile: only an unfinished response (or one
        // whose persistence stopped part-way) becomes cancelled.
        let terminal = inner.terminal(&id);
        terminal
            .stop
            .store(true, std::sync::atomic::Ordering::SeqCst);
        handle.abort();
        let mut state = terminal.state.lock().await;
        stored = match inner.server.store.get(&id).await {
            Ok(Some(current)) => current,
            Ok(None) => return not_found(&id),
            Err(e) => return server_error(e.to_string()),
        };
        let unfinished = state.stopped
            || matches!(
                stored.response["status"].as_str(),
                Some("queued" | "in_progress")
            );
        if !unfinished {
            // The turn committed before the abort landed, so it never closed
            // its replay: close it on the committed outcome.
            close_aborted_replay(&inner, &id, &stored.response);
            if stored.response["status"] == json!("cancelled") {
                return Json(stored.response).into_response();
            }
            return bad_request("Cannot cancel a response that has already finished.");
        }
        stored.response["status"] = json!("cancelled");
        // The aborted task never closes its replay: record the cancellation,
        // end the replay's streams, and schedule its eviction.
        close_aborted_replay(&inner, &id, &stored.response);
        if let Err(e) = inner.server.store.put(&id, stored.clone()).await {
            return server_error(e.to_string());
        }
        state.finalized = true;
        state.stopped = false;
    } else if stored.response["status"] != json!("cancelled") {
        return bad_request("Cannot cancel a response that has already finished.");
    }
    Json(stored.response).into_response()
}

#[derive(Debug, Deserialize)]
struct ListQuery {
    #[serde(default)]
    order: Option<String>,
    #[serde(default)]
    limit: Option<usize>,
}

async fn input_items(
    State(inner): State<Arc<Inner>>,
    Path(id): Path<String>,
    Query(query): Query<ListQuery>,
) -> Response {
    let stored = match inner.server.store.get(&id).await {
        Ok(Some(stored)) => stored,
        Ok(None) => return not_found(&id),
        Err(e) => return server_error(e.to_string()),
    };
    let mut items = stored.input_items;
    if query.order.as_deref() != Some("asc") {
        items.reverse();
    }
    let limit = query.limit.unwrap_or(20).clamp(1, 100);
    let has_more = items.len() > limit;
    items.truncate(limit);
    Json(json!({
        "object": "list",
        "first_id": items.first().and_then(|i| i.get("id")).cloned(),
        "last_id": items.last().and_then(|i| i.get("id")).cloned(),
        "has_more": has_more,
        "data": items,
    }))
    .into_response()
}

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

    #[test]
    fn ids_carry_and_reuse_partition_keys() {
        let first = ids::response_id(None);
        assert!(first.starts_with("caresp_"));
        assert_eq!(first.len(), "caresp_".len() + 50);
        let key = ids::partition_key(&first).unwrap();
        assert!(key.ends_with("00"));
        let next = ids::message_id(Some(&first));
        assert_eq!(ids::partition_key(&next).unwrap(), key);
    }

    /// Replies at once, except to `hang`, which never finishes.
    struct Hang;

    #[async_trait]
    impl SupportsAgentRun for Hang {
        async fn run(
            &self,
            messages: Vec<Message>,
            _session: Option<&mut agent_framework_core::session::AgentSession>,
        ) -> Result<AgentResponse> {
            if messages.last().map(|m| m.text()).as_deref() == Some("hang") {
                std::future::pending::<()>().await;
            }
            Ok(AgentResponse {
                messages: vec![Message::assistant("done")],
                ..Default::default()
            })
        }

        fn id(&self) -> &str {
            "hang"
        }
    }

    async fn raw_call(
        router: &Router,
        method: &str,
        path: String,
        body: Option<Value>,
    ) -> (axum::http::StatusCode, String) {
        use tower::ServiceExt;
        let request = axum::http::Request::builder()
            .method(method)
            .uri(path)
            .header("content-type", "application/json")
            .body(axum::body::Body::from(
                body.map(|b| b.to_string()).unwrap_or_default(),
            ))
            .unwrap();
        let response = router.clone().oneshot(request).await.unwrap();
        let status = response.status();
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        (status, String::from_utf8_lossy(&bytes).into_owned())
    }

    /// Holds the first conversation write until released: the response
    /// record is already committed then.
    #[derive(Default)]
    struct GatedConversation {
        inner: InMemoryResponseStore,
        tripped: std::sync::atomic::AtomicBool,
        entered: tokio::sync::Notify,
        release: tokio::sync::Notify,
    }

    #[async_trait]
    impl ResponseStore for GatedConversation {
        async fn get(&self, id: &str) -> Result<Option<StoredResponse>> {
            self.inner.get(id).await
        }
        async fn put(&self, id: &str, response: StoredResponse) -> Result<()> {
            self.inner.put(id, response).await
        }
        async fn delete(&self, id: &str) -> Result<bool> {
            self.inner.delete(id).await
        }
        async fn conversation(&self, id: &str) -> Result<Option<Vec<Message>>> {
            self.inner.conversation(id).await
        }
        async fn set_conversation(&self, id: &str, transcript: Vec<Message>) -> Result<()> {
            if !self.tripped.swap(true, std::sync::atomic::Ordering::SeqCst) {
                self.entered.notify_one();
                self.release.notified().await;
            }
            self.inner.set_conversation(id, transcript).await
        }
    }

    #[tokio::test]
    async fn a_late_cancel_still_closes_and_evicts_the_replay() {
        let store = Arc::new(GatedConversation::default());
        let (router, inner) = ResponsesHostServer::agent(Arc::new(Hang))
            .with_response_store(store.clone())
            .routes(HostOptions::default());
        let (_, queued) = raw_call(
            &router,
            "POST",
            "/responses".into(),
            Some(json!({"input": "hi", "background": true, "conversation": "c_late"})),
        )
        .await;
        let id = serde_json::from_str::<Value>(&queued).unwrap()["id"]
            .as_str()
            .unwrap()
            .to_string();
        // The turn has committed its completed response and is finishing
        // its writes when the cancel arrives.
        tokio::time::timeout(Duration::from_secs(5), store.entered.notified())
            .await
            .unwrap();
        let cancel = tokio::spawn({
            let router = router.clone();
            let path = format!("/responses/{id}/cancel");
            async move { raw_call(&router, "POST", path, Some(json!({}))).await }
        });
        tokio::time::sleep(Duration::from_millis(100)).await;
        store.release.notify_one();
        let (status, _) = cancel.await.unwrap();
        assert_eq!(
            status,
            axum::http::StatusCode::BAD_REQUEST,
            "already finished"
        );
        let stored = store.get(&id).await.unwrap().unwrap();
        assert_eq!(
            stored.response["status"], "completed",
            "the committed status stays"
        );
        // Replay streams end, on the committed terminal event.
        let (_, body) = tokio::time::timeout(
            Duration::from_secs(5),
            raw_call(&router, "GET", format!("/responses/{id}?stream=true"), None),
        )
        .await
        .expect("the replay ends");
        let last = body
            .split("\n\n")
            .filter_map(|frame| frame.lines().find_map(|l| l.strip_prefix("event: ")))
            .last()
            .map(str::to_string);
        assert_eq!(last.as_deref(), Some("response.completed"), "{body}");
        // And the buffer is evicted after the replay TTL.
        tokio::time::pause();
        tokio::time::advance(REPLAY_TTL + Duration::from_secs(1)).await;
        for _ in 0..10 {
            tokio::task::yield_now().await;
        }
        assert!(!inner.replays.lock().unwrap().contains_key(&id));
    }

    /// Whether the host keeps a session under `key`.
    async fn has_session(inner: &Arc<Inner>, key: &str) -> bool {
        #[cfg(feature = "session-store")]
        {
            let store = inner
                .server
                .sessions
                .session_store(&inner.server.config, &FoundryRequestContext::default())
                .unwrap();
            let agent = Namespaced::new(&Hang, &inner.server.config.agent_name);
            let key = agent_framework_core::session_store::AgentSessionStoreKey::new(key).unwrap();
            store.get_session(&agent, &key).await.unwrap().is_some()
        }
        #[cfg(not(feature = "session-store"))]
        {
            inner.server.sessions.lock().unwrap().contains_key(key)
        }
    }

    #[tokio::test]
    async fn deleting_a_response_deletes_its_session_snapshot() {
        for history in [HistorySource::Agent, HistorySource::Service] {
            let (router, inner) = ResponsesHostServer::agent(Arc::new(Hang))
                .with_history_source(history)
                .routes(HostOptions::default());
            let mut ids = Vec::new();
            for body in [
                json!({"input": "hi"}),
                json!({"input": "hi", "conversation": "c_del"}),
            ] {
                let (status, reply) =
                    raw_call(&router, "POST", "/responses".into(), Some(body)).await;
                assert_eq!(status, axum::http::StatusCode::OK, "{reply}");
                let reply: Value = serde_json::from_str(&reply).unwrap();
                ids.push(reply["id"].as_str().unwrap().to_string());
            }
            for id in &ids {
                assert!(
                    has_session(&inner, &response_session_key(id)).await,
                    "{history:?}"
                );
            }
            for id in &ids {
                let (status, _) =
                    raw_call(&router, "DELETE", format!("/responses/{id}"), None).await;
                assert_eq!(status, axum::http::StatusCode::OK);
                assert!(
                    !has_session(&inner, &response_session_key(id)).await,
                    "{history:?}: the response's snapshot is deleted"
                );
            }
            assert!(
                has_session(&inner, &conversation_session_key("c_del")).await,
                "{history:?}: the conversation keeps its session"
            );
        }
    }

    #[tokio::test]
    async fn terminal_coordination_is_reclaimed() {
        use tower::ServiceExt;
        let (router, inner) =
            ResponsesHostServer::agent(Arc::new(Hang)).routes(HostOptions::default());
        let call = |method: &str, path: String, body: Option<Value>| {
            let request = axum::http::Request::builder()
                .method(method)
                .uri(path)
                .header("content-type", "application/json")
                .body(axum::body::Body::from(
                    body.map(|b| b.to_string()).unwrap_or_default(),
                ))
                .unwrap();
            let router = router.clone();
            async move {
                let response = router.oneshot(request).await.unwrap();
                let status = response.status();
                let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
                    .await
                    .unwrap();
                (
                    status,
                    serde_json::from_slice::<Value>(&bytes).unwrap_or(Value::Null),
                )
            }
        };
        for i in 0..20 {
            let input = if i % 2 == 0 { "hang" } else { "hi" };
            let (_, queued) = call(
                "POST",
                "/responses".into(),
                Some(json!({"input": input, "background": true})),
            )
            .await;
            let id = queued["id"].as_str().unwrap().to_string();
            if i % 4 < 2 {
                // Cancel a hanging turn, or (once it finished) fail to.
                call("POST", format!("/responses/{id}/cancel"), Some(json!({}))).await;
            }
            let (status, _) = call("DELETE", format!("/responses/{id}"), None).await;
            assert_eq!(status, axum::http::StatusCode::OK);
            // Deleting again, or an unknown id, keeps nothing either.
            call("DELETE", format!("/responses/{id}"), None).await;
            call("POST", format!("/responses/{id}/cancel"), Some(json!({}))).await;
        }
        let (_, done) = call("POST", "/responses".into(), Some(json!({"input": "hi"}))).await;
        assert_eq!(done["status"], "completed");
        // Aborted tasks drop their holders as the runtime reclaims them.
        for _ in 0..100 {
            if inner.finals.lock().unwrap().is_empty() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        assert_eq!(inner.finals.lock().unwrap().len(), 0, "no tombstones");
    }

    #[test]
    fn string_input_becomes_a_user_message_item() {
        let items = input_items_of(&json!("hi"), "caresp_x");
        assert_eq!(items[0]["role"], "user");
        assert_eq!(items[0]["content"][0]["text"], "hi");
        assert!(items[0]["id"].as_str().unwrap().starts_with("msg_"));
    }
}