wiremux 0.11.4

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

mod chat;
mod complete;
mod converse;

#[cfg(any(feature = "proxy", feature = "client"))]
pub(crate) use converse::complete_exception_detail;
mod encoder;
mod eventstream;
mod gemini;
mod messages;
mod responses;
mod sse;
mod usage;

use serde_json::Value;
use wiremux_auth::{ResolvedProfile, StreamUnknownPolicy, Wire};

use crate::ir::IrStreamEvent;
use crate::map::MapError;

/// Max parallel tool-call index. Hostile values must not force an allocation.
pub const MAX_TOOL_CALL_INDEX: u32 = 128;
/// Max Anthropic `content_block` index. Same cap as [`MAX_TOOL_CALL_INDEX`].
pub const MAX_CONTENT_BLOCK_INDEX: u32 = 128;

/// One SSE frame (`event:` + `data:`). Chat Completions omits `event:`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RawSse {
    /// SSE `event:` field, if present.
    pub event: Option<String>,
    /// SSE `data:` payload (JSON or `[DONE]`).
    pub data: String,
}

impl RawSse {
    /// Parse a document of SSE frames. Comments and blank lines are skipped.
    /// A line or data payload over the SSE cap is an error, not an empty list.
    pub fn parse_all(text: &str) -> Result<Vec<Self>, String> {
        let mut reader = sse::SseFrameReader::new();
        let mut out = reader.feed(text.as_bytes())?;
        if let Some(last) = reader.finish()? {
            out.push(last);
        }
        Ok(out)
    }
}

pub use complete::{
    decode_response, decode_response_with_loss, encode_response, encode_response_with_model,
};
pub use encoder::StreamEncoder;
#[cfg(feature = "proxy")]
pub(crate) use eventstream::unwrap_event_payload;
pub use eventstream::{
    EventStreamReader, MAX_EVENTSTREAM_PENDING,
    encode_exception_message as encode_eventstream_exception,
    encode_message as encode_eventstream_message,
};
pub(crate) use gemini::gemini_call_id;
pub use sse::{MAX_SSE_PENDING, SseFrameReader};

/// Incremental frames from SSE or AWS Event Stream.
pub enum UpstreamFrames {
    /// `text/event-stream`.
    Sse(SseFrameReader),
    /// `application/vnd.amazon.eventstream`.
    Event(EventStreamReader),
}

impl UpstreamFrames {
    /// Event Stream for Converse; SSE otherwise.
    #[must_use]
    pub fn for_wire(wire: Wire) -> Self {
        if matches!(wire, Wire::Converse) {
            Self::Event(EventStreamReader::new())
        } else {
            Self::Sse(SseFrameReader::new())
        }
    }

    /// Append bytes and emit complete frames.
    ///
    /// The optional string is a terminal Event Stream exception after
    /// any frames already parsed from the same chunk.
    pub fn feed(&mut self, bytes: &[u8]) -> Result<(Vec<RawSse>, Option<String>), String> {
        match self {
            Self::Sse(r) => r.feed(bytes).map(|frames| (frames, None)),
            Self::Event(r) => r.feed(bytes),
        }
    }

    /// Trailing SSE frame, if any.
    pub fn drain(&mut self) -> Option<RawSse> {
        match self {
            Self::Sse(r) => r.drain(),
            Self::Event(r) => r.drain(),
        }
    }

    /// EOF. SSE may emit one last frame. Event Stream fails if bytes remain.
    #[cfg(any(feature = "client", feature = "proxy"))]
    pub fn finish(&mut self) -> Result<Option<RawSse>, String> {
        match self {
            Self::Sse(r) => r.finish(),
            Self::Event(r) => r.finish(),
        }
    }
}

/// Decode one SSE frame. `None` is a recognized no-op (ping, or an empty
/// Chat delta with no `error`).
///
/// A Chat chunk with no text, refusal, tool call, audio, or reasoning,
/// and an `error` object or string, is [`MapError::Invalid`]. The detail
/// is the vendor code and message (`server_error: overloaded`). `code`
/// wins over `type`. `id`, `created`, and `finish_reason` do not count
/// as visible.
///
/// A Responses gateway `error` with no event name is the same
/// [`MapError::Invalid`] (`server_error: model catalog unavailable`,
/// or `503`). `{"type":"response.queued"}` stays a no-op.
/// `response.output_text.done` and `response.completed` are
/// [`MapError::Invalid`] when that error is the only payload. Text or
/// a non-empty `output` stays `Ok`. A Converse body with no visible
/// `output` block or `stopReason` is [`MapError::Invalid`] for an
/// OpenAI `error`. Empty text, an empty `toolUse`, and an empty
/// `image` are not blocks. A named tool, text, or media bytes still
/// win. `__type` and `message` stay `Type: message`.
///
/// Unknown names follow `profile.dialect.stream_unknown_policy`. A
/// tool-bearing frame is never `Ok(None)`.
///
/// Chat Completions returns one event for a single text, audio, finish,
/// or usage field. Content together with `finish_reason` or `usage`,
/// two media parts, two `tool_calls`, or one call that includes an id
/// or a name plus `arguments`, is [`MapError::Invalid`] and names
/// [`decode_stream_events`]. That function keeps every call and its
/// argument text. A later chunk that is only
/// `{"index":0,"function":{"arguments":"..."}}` stays
/// [`IrStreamEvent::ToolCallArgDelta`].
pub fn decode_stream_event(
    wire: Wire,
    raw: &RawSse,
    profile: &ResolvedProfile,
) -> Result<Option<IrStreamEvent>, MapError> {
    if raw.event.is_none() && raw.data.trim().is_empty() {
        return Ok(None);
    }

    let name = frame_event_name(wire, raw);
    if !profile.dialect.stream_events.iter().any(|ev| ev == &name) {
        return unknown_event(wire, profile, &name, &raw.data);
    }

    if name == "[DONE]" || raw.data.trim() == "[DONE]" {
        return Ok(Some(IrStreamEvent::Done));
    }

    let value: Value = serde_json::from_str(&raw.data)?;
    match wire {
        Wire::ChatCompletions => chat::decode(&value),
        Wire::Messages => messages::decode(&name, &value),
        Wire::Responses => responses::decode(&name, &value),
        Wire::Gemini => gemini::decode(&value),
        Wire::Converse => converse::decode(&value),
        _ => Err(MapError::Invalid(format!(
            "unsupported wire `{}`",
            wire.as_str()
        ))),
    }
}

/// Gemini function-call sequence for one upstream stream.
///
/// [`decode_stream_events`] starts a fresh decoder, so its ids begin at 0
/// on every call. No process-global counter.
#[derive(Debug, Default)]
pub struct StreamDecoder {
    gemini_call_seq: usize,
}

impl StreamDecoder {
    /// Sequence starts at 0.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Decode one frame. Gemini call ids advance across calls on `self`.
    pub fn decode(
        &mut self,
        wire: Wire,
        raw: &RawSse,
        profile: &ResolvedProfile,
    ) -> Result<Vec<IrStreamEvent>, MapError> {
        decode_stream_events_seq(wire, raw, profile, &mut self.gemini_call_seq)
    }
}

/// Decode one SSE frame into every IR event it carries.
///
/// Chat Completions can put content, `finish_reason`, and `usage` on
/// one chunk. A Messages `message_delta` can carry a stop reason and
/// `usage`. Singular decode keeps one of those. Empty vec is a
/// recognized no-op when the chunk has no `error`.
///
/// A Chat `error` on a chunk with no visible delta is
/// [`MapError::Invalid`], not an empty vec. `id` and `created` do not
/// hide that error. Visible text, a refusal, or a tool call stays `Ok`.
/// An event name that is not in `stream_events` still follows
/// `stream_unknown_policy`.
///
/// A Responses gateway `error` with no event name, and
/// `response.output_text.done` or `response.completed` that is only
/// that error, is [`MapError::Invalid`] rather than an empty vec.
/// A Converse OpenAI `error` with no `output` or `stopReason` is too.
/// A status frame, done text, completed output, and Converse
/// `output` or `stopReason` stay `Ok`.
///
/// Gemini function-call ids start at 0. Use [`StreamDecoder`] to keep
/// the sequence across chunks of one stream.
pub fn decode_stream_events(
    wire: Wire,
    raw: &RawSse,
    profile: &ResolvedProfile,
) -> Result<Vec<IrStreamEvent>, MapError> {
    let mut seq = 0usize;
    decode_stream_events_seq(wire, raw, profile, &mut seq)
}

/// The SSE name was in `stream_events`, or singular decode asked for
/// the plural tool path. An unknown-event `HardError` or `Unknown`
/// frame must keep `stream_unknown_policy`.
fn chat_named_frame(first: &Result<Option<IrStreamEvent>, MapError>) -> bool {
    match first {
        Ok(Some(IrStreamEvent::Unknown { .. })) => false,
        Ok(_) => true,
        Err(MapError::Invalid(detail)) if detail.contains("decode_stream_events") => true,
        Err(_) => false,
    }
}

fn decode_stream_events_seq(
    wire: Wire,
    raw: &RawSse,
    profile: &ResolvedProfile,
    call_seq: &mut usize,
) -> Result<Vec<IrStreamEvent>, MapError> {
    let first = decode_stream_event(wire, raw, profile);
    if matches!(wire, Wire::ChatCompletions)
        && let Ok(value) = serde_json::from_str::<Value>(&raw.data)
    {
        // decode_all runs on every Chat JSON body, including a name that
        // stream_unknown_policy already refused. Do not replace that policy
        // with the vendor error.
        let events = match chat::decode_all(&value) {
            Ok(events) => events,
            Err(err) if chat_named_frame(&first) => return Err(err),
            Err(_) => Vec::new(),
        };
        // Singular refuses a frame that would drop arguments or a second
        // call. The plural decode above already kept them.
        let singular_limit = matches!(
            &first,
            Err(MapError::Invalid(detail)) if detail.contains("decode_stream_events")
        );
        if !events.is_empty() && (first.is_ok() || singular_limit) {
            // decode_all already expanded every tool call. Re-expanding a
            // leading Protocol entry and then appending the tail duplicates
            // a later custom or function call and drops the unknown entry.
            let lone_protocol = matches!(events.as_slice(), [IrStreamEvent::Protocol { .. }]);
            if !lone_protocol {
                return Ok(events);
            }
            if let Some(expanded) = expand_complete_tool_call(wire, &events[0], raw)? {
                return Ok(expanded);
            }
        }
    }
    if matches!(wire, Wire::Responses)
        && let Ok(value) = serde_json::from_str::<Value>(&raw.data)
    {
        let name = frame_event_name(wire, raw);
        let singular_limit = matches!(
            &first,
            Err(MapError::Invalid(detail)) if detail.contains("decode_stream_events")
        );
        if let Some(events) = responses::decode_terminal_events(&name, &value)
            && first.is_ok()
        {
            return Ok(events);
        }
        let events = responses::decode_all(&name, &value)?;
        if !events.is_empty() && (first.is_ok() || singular_limit) {
            return Ok(events);
        }
    }
    let first = first?;
    if matches!(wire, Wire::Converse)
        && let Ok(value) = serde_json::from_str::<Value>(&raw.data)
    {
        let events = converse::decode_metadata_events(&value);
        if events.len() >= 2 {
            return Ok(events);
        }
    }
    // Fan-out runs even when singular decode found nothing. A response id
    // with no candidate used to be dropped because Ok(None) returned first.
    if matches!(wire, Wire::Gemini)
        && let Ok(value) = serde_json::from_str::<Value>(&raw.data)
        && let Some(events) = fan_out_gemini_parts(&value, call_seq)
    {
        return Ok(events);
    }
    let Some(first) = first else {
        return Ok(Vec::new());
    };
    if let Some(expanded) = expand_complete_tool_call(wire, &first, raw)? {
        return Ok(expanded);
    }
    if matches!(wire, Wire::Messages)
        && let Ok(value) = serde_json::from_str::<Value>(&raw.data)
    {
        let name = frame_event_name(wire, raw);
        let usage = match name.as_str() {
            "message_start" => value.pointer("/message/usage"),
            "message_delta" => value.get("usage"),
            _ => None,
        }
        .filter(|v| v.is_object());
        let mut out = Vec::new();
        if name == "message_start"
            && matches!(first, IrStreamEvent::Usage { .. })
            && let Some(id) = value
                .pointer("/message/id")
                .and_then(Value::as_str)
                .filter(|text| !text.trim().is_empty())
        {
            out.push(IrStreamEvent::Protocol {
                item_type: "messages_id".into(),
                payload: serde_json::json!(id),
            });
        }
        if let Some(usage) = usage
            && let Some(tier) = messages::service_tier_from_usage(usage)
        {
            out.push(IrStreamEvent::ServiceTier { tier });
        }
        if name == "message_delta"
            && let Some(text) = messages::stop_details_explanation(&value)
            && !matches!(first, IrStreamEvent::RefusalDelta { .. })
        {
            out.push(IrStreamEvent::RefusalDelta { text });
        }
        let add_delta_usage =
            name == "message_delta" && matches!(first, IrStreamEvent::FinishReason { .. });
        let keep_container = matches!(
            first,
            IrStreamEvent::Usage { .. } | IrStreamEvent::FinishReason { .. }
        );
        if keep_container {
            let container = if name == "message_start" {
                value.pointer("/message/container")
            } else if name == "message_delta" {
                value.get("container")
            } else {
                None
            };
            if let Some(container) = container.filter(|container| container.is_object()) {
                out.push(IrStreamEvent::Container {
                    value: container.clone(),
                });
            }
        }
        if add_delta_usage
            && let Some(text) = value
                .pointer("/delta/stop_sequence")
                .and_then(Value::as_str)
                .filter(|text| !text.trim().is_empty())
        {
            out.push(IrStreamEvent::StopSequence {
                text: text.to_string(),
            });
        }
        if name == "message_delta"
            && matches!(
                first,
                IrStreamEvent::FinishReason { .. } | IrStreamEvent::Usage { .. }
            )
            && let Some(managed) = value.get("context_management").filter(|v| v.is_object())
        {
            out.push(IrStreamEvent::ContextManagement {
                value: managed.clone(),
            });
        }
        if name == "message_delta"
            && matches!(
                first,
                IrStreamEvent::FinishReason { .. } | IrStreamEvent::Usage { .. }
            )
            && let Some(reason) = value
                .pointer("/diagnostics/cache_miss_reason")
                .filter(|reason| reason.is_object())
        {
            out.push(IrStreamEvent::Diagnostics {
                cache_miss_reason: reason.clone(),
            });
        }
        out.push(first);
        if let Some(usage) = usage {
            out.extend(usage::messages_web_search_events(usage));
            out.extend(usage::messages_cache_creation_events(usage));
        }
        if add_delta_usage && let Some(usage) = usage {
            out.push(usage::from_anthropic(usage));
        }
        return Ok(out);
    }
    Ok(vec![first])
}

/// Walk every Gemini part. First-part-wins in `decode` would drop a later
/// `functionCall` after thought or text.
fn gemini_value_has_function_call(value: &Value) -> bool {
    value
        .pointer("/candidates/0/content/parts")
        .and_then(Value::as_array)
        .is_some_and(|parts| {
            parts.iter().any(|p| {
                p.get("functionCall")
                    .is_some_and(crate::completion::gemini_function_call_visible)
            })
        })
}

fn fan_out_gemini_parts(value: &Value, call_seq: &mut usize) -> Option<Vec<IrStreamEvent>> {
    let seq_at_entry = *call_seq;
    let mut out = Vec::new();
    if let Some(id) = value
        .get("responseId")
        .and_then(Value::as_str)
        .filter(|text| !text.trim().is_empty())
    {
        out.push(IrStreamEvent::Protocol {
            item_type: "gemini_response_id".into(),
            payload: serde_json::json!(id),
        });
    }
    if let Some(parts) = value
        .pointer("/candidates/0/content/parts")
        .and_then(Value::as_array)
    {
        for part in parts {
            out.extend(gemini_part_events(part, call_seq));
        }
    }
    if let Some(chunks) = value
        .pointer("/candidates/0/groundingMetadata/groundingChunks")
        .and_then(Value::as_array)
    {
        let supports = value
            .pointer("/candidates/0/groundingMetadata/groundingSupports")
            .and_then(Value::as_array);
        for (idx, chunk) in chunks.iter().enumerate() {
            if let Some(mut annotation) = gemini::annotation_from_grounding_chunk(chunk) {
                if let Some(supports) = supports {
                    gemini::apply_grounding_support(&mut annotation, idx, supports);
                }
                out.push(IrStreamEvent::AnnotationAdded { annotation });
            }
        }
    }
    if let Some(candidate) = value
        .get("candidates")
        .and_then(Value::as_array)
        .and_then(|c| c.first())
    {
        for annotation in gemini::citation_annotations(candidate) {
            out.push(IrStreamEvent::AnnotationAdded { annotation });
        }
    }
    if let Some(metadata) = value
        .pointer("/candidates/0/urlContextMetadata")
        .filter(|metadata| {
            metadata
                .get("urlMetadata")
                .and_then(Value::as_array)
                .is_some_and(|items| !items.is_empty())
        })
    {
        out.push(IrStreamEvent::Protocol {
            item_type: "gemini_url_context".into(),
            payload: metadata.clone(),
        });
    }
    if let Some(metadata) = value
        .pointer("/candidates/0/citationMetadata")
        .filter(|metadata| {
            let sources = metadata
                .get("citationSources")
                .and_then(Value::as_array)
                .is_some_and(|items| !items.is_empty());
            let citations = metadata
                .get("citations")
                .and_then(Value::as_array)
                .is_some_and(|items| !items.is_empty());
            sources || citations
        })
    {
        out.push(IrStreamEvent::Protocol {
            item_type: "gemini_citation_metadata".into(),
            payload: metadata.clone(),
        });
    }
    if let Some(attrs) = value
        .pointer("/candidates/0/groundingAttributions")
        .and_then(Value::as_array)
    {
        for attr in attrs {
            if let Some(annotation) = gemini::annotation_from_grounding_chunk(attr) {
                out.push(IrStreamEvent::AnnotationAdded { annotation });
            }
        }
    }
    if let Some(ev) = gemini::search_entry_from_value(value) {
        out.push(ev);
    }
    if let Some(content) = value
        .pointer("/candidates/0/logprobsResult")
        .and_then(gemini::logprobs_from_result)
    {
        out.push(IrStreamEvent::Logprobs {
            content,
            refusal: None,
        });
    }
    if let Some(text) = value
        .pointer("/candidates/0/finishMessage")
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
    {
        out.push(IrStreamEvent::RefusalDelta {
            text: text.to_string(),
        });
    }
    if let Some(ratings) = value
        .pointer("/candidates/0/safetyRatings")
        .filter(|ratings| ratings.as_array().is_some_and(|items| !items.is_empty()))
    {
        out.push(IrStreamEvent::Protocol {
            item_type: "gemini_safety_ratings".into(),
            payload: ratings.clone(),
        });
    }
    if let Some(ratings) = value
        .pointer("/promptFeedback/safetyRatings")
        .filter(|ratings| ratings.as_array().is_some_and(|items| !items.is_empty()))
    {
        out.push(IrStreamEvent::Protocol {
            item_type: "gemini_prompt_safety".into(),
            payload: ratings.clone(),
        });
    }
    if let Some(message) = value
        .pointer("/promptFeedback/blockReasonMessage")
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|message| !message.is_empty())
    {
        out.push(IrStreamEvent::Protocol {
            item_type: "gemini_block_reason_message".into(),
            payload: Value::from(message),
        });
    }
    // blockReason is enough. blockReasonMessage is optional, and a
    // responseId plus usage would otherwise hide the block from the
    // singular decoder.
    if value
        .pointer("/candidates/0/finishReason")
        .and_then(Value::as_str)
        .is_none_or(|reason| reason.is_empty())
        && let Some(reason) = value
            .pointer("/promptFeedback/blockReason")
            .and_then(Value::as_str)
            .filter(|reason| !reason.is_empty())
    {
        out.push(IrStreamEvent::FinishReason {
            reason: gemini::map_block(reason),
            vendor: Some(reason.to_string()),
        });
    }
    if let Some(score) = value
        .pointer("/candidates/0/avgLogprobs")
        .and_then(Value::as_f64)
        .filter(|score| score.is_finite())
    {
        out.push(IrStreamEvent::Protocol {
            item_type: "gemini_avg_logprobs".into(),
            payload: Value::from(score),
        });
    }
    if let Some(count) = value
        .pointer("/candidates/0/tokenCount")
        .and_then(Value::as_u64)
        .filter(|count| *count > 0)
        .and_then(|count| u32::try_from(count).ok())
    {
        out.push(IrStreamEvent::Protocol {
            item_type: "gemini_candidate_tokens".into(),
            payload: Value::from(count),
        });
    }
    if let Some(reason) = value
        .pointer("/candidates/0/finishReason")
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
    {
        out.push(IrStreamEvent::FinishReason {
            reason: gemini::map_finish(reason, gemini_value_has_function_call(value)),
            vendor: Some(reason.to_string()),
        });
    }
    if let Some(ev) = gemini::service_tier_from_chunk(value) {
        out.push(ev);
    }
    out.extend(usage::gemini_traffic_type_events(value));
    out.extend(usage::gemini_tool_use_prompt_events(value));
    out.extend(usage::gemini_modality_detail_events(value));
    if let Some(ev) = gemini::usage_from_chunk(value) {
        out.push(ev);
    }
    if out.is_empty() {
        *call_seq = seq_at_entry;
        return None;
    }
    Some(out)
}

/// Why a client or proxy rejects a stream that produced frames and then ended.
#[cfg(any(feature = "client", feature = "proxy"))]
pub(crate) const INCOMPLETE_STREAM_MESSAGE: &str = "upstream stream ended before a terminal event";

/// Upstream frame that ends a stream. An empty body is not terminal.
///
/// Maps-only hosts call this on each SSE frame. EOF after content is a
/// failure unless one frame was terminal. [`StreamEncoder::finish`] is
/// for a stream the caller already knows completed.
pub fn frame_is_terminal(wire: Wire, raw: &RawSse, _profile: &ResolvedProfile) -> bool {
    match wire {
        Wire::ChatCompletions => chat_frame_is_terminal(raw),
        Wire::Messages => messages_frame_is_terminal(raw),
        Wire::Responses => responses_frame_is_terminal(raw),
        Wire::Gemini => gemini_frame_is_terminal(raw),
        Wire::Converse => converse_frame_is_terminal(raw),
        _ => false,
    }
}

/// True when any frame is terminal. An empty slice is not.
#[must_use]
pub fn stream_has_terminal(wire: Wire, frames: &[RawSse], profile: &ResolvedProfile) -> bool {
    frames
        .iter()
        .any(|raw| frame_is_terminal(wire, raw, profile))
}

fn chat_frame_is_terminal(raw: &RawSse) -> bool {
    if raw.event.as_deref() == Some("[DONE]") || raw.data.trim() == "[DONE]" {
        return true;
    }
    let Ok(value) = serde_json::from_str::<Value>(&raw.data) else {
        return false;
    };
    value
        .pointer("/choices")
        .and_then(Value::as_array)
        .is_some_and(|choices| {
            choices.iter().any(|choice| {
                choice
                    .get("finish_reason")
                    .and_then(Value::as_str)
                    .is_some_and(|reason| !reason.is_empty())
            })
        })
}

fn messages_frame_is_terminal(raw: &RawSse) -> bool {
    let name = frame_event_name(Wire::Messages, raw);
    if name == "message_stop" {
        return true;
    }
    if name != "message_delta" {
        return false;
    }
    let Ok(value) = serde_json::from_str::<Value>(&raw.data) else {
        return false;
    };
    value
        .pointer("/delta/stop_reason")
        .and_then(Value::as_str)
        .is_some_and(|reason| !reason.is_empty())
}

fn converse_frame_is_terminal(raw: &RawSse) -> bool {
    let Ok(value) = serde_json::from_str::<Value>(&raw.data) else {
        return false;
    };
    // messageStop is the only Converse stream frame that becomes FinishReason.
    value
        .pointer("/messageStop/stopReason")
        .and_then(Value::as_str)
        .is_some()
}

fn responses_frame_is_terminal(raw: &RawSse) -> bool {
    matches!(
        frame_event_name(Wire::Responses, raw).as_str(),
        "response.completed" | "response.incomplete" | "response.failed"
    )
}

fn gemini_frame_is_terminal(raw: &RawSse) -> bool {
    let Ok(value) = serde_json::from_str::<Value>(&raw.data) else {
        return false;
    };
    if value
        .pointer("/candidates/0/finishReason")
        .and_then(Value::as_str)
        .is_some_and(|reason| !reason.is_empty())
    {
        return true;
    }
    // A blocked prompt finishes without a candidate finishReason.
    value
        .pointer("/promptFeedback/blockReason")
        .and_then(Value::as_str)
        .is_some_and(|reason| !reason.is_empty())
}

fn gemini_part_events(part: &Value, call_seq: &mut usize) -> Vec<IrStreamEvent> {
    let mut out = Vec::new();
    if part.get("thought").and_then(Value::as_bool) == Some(true)
        && let Some(text) = part
            .get("text")
            .and_then(Value::as_str)
            .filter(|s| !s.is_empty())
    {
        out.push(IrStreamEvent::ReasoningDelta {
            text: text.to_string(),
        });
    }
    if let Some(sig) = part
        .get("thoughtSignature")
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
        && part.get("functionCall").is_none()
    {
        out.push(IrStreamEvent::ReasoningSignature {
            signature: sig.to_string(),
        });
    }
    if let Some(fc) = part
        .get("functionCall")
        .filter(|call| crate::completion::gemini_function_call_visible(call))
    {
        let name = str_field(fc, "name").unwrap_or_default();
        let thought_signature = part
            .get("thoughtSignature")
            .and_then(Value::as_str)
            .filter(|s| !s.is_empty())
            .map(str::to_string);
        let seq = *call_seq;
        *call_seq += 1;
        let id = gemini::gemini_call_id(fc, &name, seq);
        let index = u32::try_from(seq).unwrap_or(0);
        out.push(IrStreamEvent::ToolCallStart {
            id,
            name,
            thought_signature,
            index,
        });
        if let Some(args) = fc
            .get("args")
            .filter(|a| a.as_object().is_none_or(|m| !m.is_empty()) && !a.is_null())
        {
            out.push(IrStreamEvent::ToolCallArgDelta {
                delta: args.to_string(),
                index,
            });
        }
    } else if crate::completion::gemini_side_part_visible(part) {
        out.push(IrStreamEvent::Protocol {
            item_type: "gemini_code_part".into(),
            payload: part.clone(),
        });
    } else if let Some(ev) = gemini::inline_data_event(part) {
        out.push(ev);
    } else if part.get("thought").and_then(Value::as_bool) != Some(true)
        && let Some(text) = part
            .get("text")
            .and_then(Value::as_str)
            .filter(|s| !s.is_empty())
    {
        out.push(IrStreamEvent::TextDelta {
            text: text.to_string(),
        });
    }
    out
}

fn expand_complete_tool_call(
    wire: Wire,
    first: &IrStreamEvent,
    raw: &RawSse,
) -> Result<Option<Vec<IrStreamEvent>>, MapError> {
    let Ok(value) = serde_json::from_str::<Value>(&raw.data) else {
        return Ok(None);
    };
    match wire {
        Wire::ChatCompletions => expand_chat_tool_call(first, &value),
        Wire::Gemini => Ok(expand_gemini_function_call(first, &value)),
        Wire::Responses => Ok(expand_responses_function_call(first, &value)),
        Wire::Messages | Wire::Converse => Ok(None),
        _ => Ok(None),
    }
}

fn expand_chat_tool_call(
    first: &IrStreamEvent,
    value: &Value,
) -> Result<Option<Vec<IrStreamEvent>>, MapError> {
    let IrStreamEvent::Protocol { .. } = first else {
        return Ok(None);
    };
    let Some(tool_calls) = value
        .pointer("/choices/0/delta/tool_calls")
        .and_then(Value::as_array)
    else {
        return Ok(None);
    };
    let mut out = Vec::new();
    for call in tool_calls {
        let expanded = chat::expand_tool_call(call, value)?;
        if expanded
            .iter()
            .all(|ev| matches!(ev, IrStreamEvent::Protocol { .. }))
        {
            continue;
        }
        out.extend(
            expanded
                .into_iter()
                .filter(|ev| !matches!(ev, IrStreamEvent::Protocol { .. })),
        );
    }
    if out.is_empty() {
        return Ok(None);
    }
    Ok(Some(out))
}

fn expand_gemini_function_call(first: &IrStreamEvent, value: &Value) -> Option<Vec<IrStreamEvent>> {
    let parts = value
        .pointer("/candidates/0/content/parts")
        .and_then(Value::as_array)?;
    let part = parts.iter().find(|p| p.get("functionCall").is_some())?;
    let fc = part.get("functionCall")?;
    let name = str_field(fc, "name").unwrap_or_default();
    let args = fc
        .get("args")
        .filter(|a| a.as_object().is_none_or(|m| !m.is_empty()) && !a.is_null())?;
    let thought_signature = part
        .get("thoughtSignature")
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
        .map(str::to_string);
    match first {
        IrStreamEvent::Protocol { .. } | IrStreamEvent::ToolCallStart { .. } => {}
        _ => return None,
    }
    Some(vec![
        IrStreamEvent::ToolCallStart {
            id: gemini::gemini_call_id(fc, &name, 0),
            name,
            thought_signature,
            index: 0,
        },
        IrStreamEvent::ToolCallArgDelta {
            delta: args.to_string(),
            index: 0,
        },
    ])
}

fn expand_responses_function_call(
    first: &IrStreamEvent,
    value: &Value,
) -> Option<Vec<IrStreamEvent>> {
    let IrStreamEvent::ToolCallStart {
        id,
        name,
        thought_signature,
        index,
    } = first
    else {
        return None;
    };
    let args = value
        .pointer("/item/arguments")
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())?;
    Some(vec![
        IrStreamEvent::ToolCallStart {
            id: id.clone(),
            name: name.clone(),
            thought_signature: thought_signature.clone(),
            index: *index,
        },
        IrStreamEvent::ToolCallArgDelta {
            delta: args.to_string(),
            index: *index,
        },
    ])
}

/// Merge Chat tool-call starts that arrive as id-only then name-only.
///
/// Pending starts are keyed by `index` so interleaved parallel calls
/// do not overwrite each other. Argument deltas stay on that index
/// until the id and the name have both arrived, including deltas that
/// arrive before any start. After the start is emitted, later deltas
/// for that index pass through.
#[derive(Debug, Default)]
pub struct ToolCallAssembler {
    pending: std::collections::BTreeMap<u32, PendingToolStart>,
    /// Indexes whose start was already emitted. Later argument deltas
    /// for those indexes must not wait for another start.
    started: std::collections::BTreeSet<u32>,
}

#[derive(Debug)]
struct PendingToolStart {
    id: String,
    name: String,
    thought_signature: Option<String>,
    index: u32,
    args: Vec<String>,
}

impl ToolCallAssembler {
    /// Empty assembler.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Feed one event. Incomplete starts are held until the name or id arrives.
    ///
    /// A completion id, or any other non-terminal event, does not release
    /// a held start. [`IrStreamEvent::FinishReason`] and [`IrStreamEvent::Done`] do.
    pub fn push(&mut self, ev: IrStreamEvent) -> Vec<IrStreamEvent> {
        match ev {
            IrStreamEvent::ToolCallStart {
                id,
                name,
                thought_signature,
                index,
            } => self.push_start(id, name, thought_signature, index),
            IrStreamEvent::ToolCallArgDelta { delta, index } => {
                if let Some(pending) = self.pending.get_mut(&index) {
                    pending.args.push(delta);
                    return Vec::new();
                }
                if self.started.contains(&index) {
                    return vec![IrStreamEvent::ToolCallArgDelta { delta, index }];
                }
                // No start yet. Hold the fragment so a later start can
                // lead it. `flush` still releases it if the name never comes.
                self.pending.insert(
                    index,
                    PendingToolStart {
                        id: String::new(),
                        name: String::new(),
                        thought_signature: None,
                        index,
                        args: vec![delta],
                    },
                );
                Vec::new()
            }
            other => {
                // Every Chat chunk carries `id` before the tool fields.
                // Flushing on that protocol event would emit the held
                // start before the name arrives. Finish still releases
                // a start the name never completed.
                let mut out = if matches!(
                    other,
                    IrStreamEvent::FinishReason { .. } | IrStreamEvent::Done
                ) {
                    self.flush()
                } else {
                    Vec::new()
                };
                out.push(other);
                out
            }
        }
    }

    /// Emit held starts at end of stream.
    pub fn flush(&mut self) -> Vec<IrStreamEvent> {
        let pending = std::mem::take(&mut self.pending);
        let mut out = Vec::new();
        for (_, pending) in pending {
            if !pending.id.is_empty() || !pending.name.is_empty() {
                self.started.insert(pending.index);
            }
            out.extend(pending.into_events());
        }
        out
    }

    fn push_start(
        &mut self,
        id: String,
        name: String,
        thought_signature: Option<String>,
        index: u32,
    ) -> Vec<IrStreamEvent> {
        let (id, name, thought_signature, args) = if let Some(prev) = self.pending.remove(&index) {
            (
                if id.is_empty() { prev.id } else { id },
                if name.is_empty() { prev.name } else { name },
                thought_signature.or(prev.thought_signature),
                prev.args,
            )
        } else {
            (id, name, thought_signature, Vec::new())
        };
        let pending = PendingToolStart {
            id,
            name,
            thought_signature,
            index,
            args,
        };
        if pending.id.is_empty() || pending.name.is_empty() {
            self.pending.insert(index, pending);
            Vec::new()
        } else {
            self.started.insert(index);
            pending.into_events()
        }
    }
}

impl PendingToolStart {
    fn into_events(self) -> Vec<IrStreamEvent> {
        let mut out = Vec::new();
        // Arguments that never received an id or a name are still the
        // call's fragments. An empty start would look like a second call.
        if !self.id.is_empty() || !self.name.is_empty() {
            out.push(IrStreamEvent::ToolCallStart {
                id: self.id,
                name: self.name,
                thought_signature: self.thought_signature,
                index: self.index,
            });
        }
        for delta in self.args {
            out.push(IrStreamEvent::ToolCallArgDelta {
                delta,
                index: self.index,
            });
        }
        out
    }
}

/// Whether this IR event has a slot on `wire` SSE.
///
/// Protocol names are dialect-specific (`chunk` is Chat and Gemini), so
/// a Chat Protocol must not re-emit on Gemini. A Messages protocol frame
/// is a same-wire event, such as a document citation, and stays on Messages.
#[cfg(feature = "proxy")]
#[must_use]
pub(crate) fn event_has_slot(wire: Wire, ev: &IrStreamEvent) -> bool {
    match ev {
        IrStreamEvent::Protocol { item_type, payload } => {
            (wire == Wire::Messages
                && (messages_protocol_reemits(item_type)
                    || item_type == "messages_id"
                    || item_type == "messages_web_search_requests"
                    || item_type == "messages_web_fetch_requests"
                    || item_type == "messages_cache_creation"
                    || item_type == "messages_citation"))
                || (wire == Wire::Responses
                    && (item_type == "responses_id"
                        || item_type == "responses_previous_id"
                        || item_type == "responses_message_id"
                        || item_type == "responses_message_status"
                        || item_type == "responses_message_phase"
                        || item_type == "responses_message_agent"
                        || item_type == "responses_reasoning_id"
                        || item_type == "responses_reasoning_status"
                        || item_type == "responses_reasoning_content"
                        || item_type == "responses_tool_status"
                        || item_type == "responses_tool_namespace"
                        || item_type == "responses_tool_created_by"
                        || item_type == "responses_tool_caller"
                        || item_type == "responses_tool_item_id"
                        || responses_output_item(item_type, payload)))
                || (wire == Wire::ChatCompletions
                    && matches!(
                        item_type.as_str(),
                        "system_fingerprint"
                            | "chat_completion_id"
                            | "chat_audio_id"
                            | "chat_audio_expires"
                            | "chat_accepted_prediction_tokens"
                            | "chat_rejected_prediction_tokens"
                    ))
                || (wire == Wire::Gemini
                    && matches!(
                        item_type.as_str(),
                        "gemini_response_id"
                            | "gemini_safety_ratings"
                            | "gemini_url_context"
                            | "gemini_citation_metadata"
                            | "gemini_code_part"
                            | "gemini_prompt_safety"
                            | "gemini_block_reason_message"
                            | "gemini_traffic_type"
                            | "gemini_tool_use_prompt_tokens"
                            | "gemini_avg_logprobs"
                            | "gemini_candidate_tokens"
                            | "gemini_prompt_token_details"
                            | "gemini_candidate_token_details"
                    ))
                || (wire == Wire::Converse
                    && matches!(
                        item_type.as_str(),
                        "additionalModelResponseFields"
                            | "metrics"
                            | "trace"
                            | "performanceConfig"
                            | "converse_frame"
                            | "converse_citation"
                            | "converse_redacted_content"
                    ))
        }
        IrStreamEvent::Unknown { .. } => matches!(wire, Wire::Messages | Wire::Responses),
        _ => true,
    }
}

#[cfg(feature = "proxy")]
fn messages_protocol_reemits(item_type: &str) -> bool {
    matches!(
        item_type,
        "message_start"
            | "content_block_start"
            | "content_block_delta"
            | "content_block_stop"
            | "message_delta"
            | "message_stop"
            | "ping"
    )
}

/// Encode one IR event into the target dialect's SSE shape.
pub fn encode_stream_event(wire: Wire, ev: &IrStreamEvent) -> Result<RawSse, MapError> {
    match ev {
        IrStreamEvent::Unknown { event, raw } => Ok(encode_named(event, raw)),
        IrStreamEvent::Protocol { item_type, payload } => {
            if wire == Wire::Responses && responses_output_item(item_type, payload) {
                return Ok(responses_output_item_frame(payload));
            }
            if wire == Wire::ChatCompletions
                && matches!(
                    item_type.as_str(),
                    "system_fingerprint" | "chat_audio_id" | "chat_audio_expires"
                )
            {
                return chat::encode(ev);
            }
            if wire == Wire::Converse && item_type == "converse_frame" {
                return Ok(RawSse {
                    event: None,
                    data: payload.to_string(),
                });
            }
            if wire == Wire::Converse && item_type == "converse_citation" {
                return Ok(RawSse {
                    event: None,
                    data: serde_json::json!({
                        "contentBlockDelta": {
                            "contentBlockIndex": 0,
                            "delta": { "citation": payload }
                        }
                    })
                    .to_string(),
                });
            }
            Ok(encode_named(item_type, payload))
        }
        other => match wire {
            Wire::ChatCompletions => chat::encode(other),
            Wire::Messages => messages::encode(other),
            Wire::Responses => responses::encode(other),
            Wire::Gemini => gemini::encode(other),
            Wire::Converse => {
                let value = converse::encode(other)?;
                Ok(RawSse {
                    event: None,
                    data: value.to_string(),
                })
            }
            _ => Err(MapError::Invalid(format!(
                "unsupported wire `{}`",
                wire.as_str()
            ))),
        },
    }
}

fn responses_output_item(item_type: &str, payload: &Value) -> bool {
    if item_type == "chunk" || item_type == "output_image" {
        return false;
    }
    // SSE names (`content_block_start`, `response.output_item.done`) also
    // have payload.type equal to the event name. Those are not output items.
    if item_type.contains('.') || messages_stream_event(item_type) {
        return false;
    }
    if messages_content_block_type(item_type) {
        return false;
    }
    payload.get("type").and_then(Value::as_str) == Some(item_type)
}

fn messages_stream_event(item_type: &str) -> bool {
    matches!(
        item_type,
        "message_start"
            | "content_block_start"
            | "content_block_delta"
            | "content_block_stop"
            | "message_delta"
            | "message_stop"
            | "ping"
    )
}

/// Messages content blocks stored as Protocol. Not Responses output items.
fn messages_content_block_type(item_type: &str) -> bool {
    matches!(
        item_type,
        "redacted_thinking"
            | "server_tool_use"
            | "web_search_tool_result"
            | "web_fetch_tool_result"
            | "code_execution_tool_result"
            | "mcp_tool_use"
            | "mcp_tool_result"
            | "bash_code_execution_tool_result"
            | "text_editor_code_execution_tool_result"
            | "search_result"
            | "document"
            | "container_upload"
            | "tool_result"
            | "thinking"
            | "image"
    )
}

/// Responses output items that must not be pasted into another wire's body.
pub(super) fn responses_hosted_item_type(item_type: &str) -> bool {
    item_type.ends_with("_call")
        || item_type.ends_with("_call_output")
        || matches!(
            item_type,
            "reasoning"
                | "mcp_list_tools"
                | "mcp_approval_request"
                | "mcp_approval_response"
                | "item_reference"
                | "program"
                | "compaction"
        )
}

#[cfg(feature = "client")]
pub(crate) fn responses_failure_object(value: &Value) -> Option<&Value> {
    responses::failure_object(value)
}

fn responses_output_item_frame(payload: &Value) -> RawSse {
    let index = payload
        .get("output_index")
        .and_then(Value::as_u64)
        .unwrap_or(0);
    let mut item = payload.clone();
    if let Some(obj) = item.as_object_mut() {
        obj.remove("output_index");
    }
    RawSse {
        event: Some("response.output_item.done".into()),
        data: serde_json::json!({
            "type": "response.output_item.done",
            "output_index": index,
            "item": item
        })
        .to_string(),
    }
}

fn encode_named(name: &str, raw: &Value) -> RawSse {
    let data = match raw {
        Value::String(s) => s.clone(),
        other => other.to_string(),
    };
    RawSse {
        event: sse_event_field(name),
        data,
    }
}

fn sse_event_field(name: &str) -> Option<String> {
    match name {
        "" | "chunk" | "[DONE]" => None,
        other => Some(other.to_string()),
    }
}

pub(crate) fn frame_event_name(wire: Wire, raw: &RawSse) -> String {
    if let Some(ev) = raw.event.as_deref().filter(|s| !s.is_empty()) {
        return ev.to_string();
    }
    let trimmed = raw.data.trim();
    if trimmed == "[DONE]" {
        return "[DONE]".into();
    }
    if matches!(wire, Wire::ChatCompletions | Wire::Gemini) {
        return "chunk".into();
    }
    if matches!(wire, Wire::Converse) {
        if let Ok(value) = serde_json::from_str::<Value>(trimmed) {
            for name in [
                "contentBlockDelta",
                "contentBlockStart",
                "contentBlockStop",
                "messageStop",
                "metadata",
                "messageStart",
            ] {
                if value.get(name).is_some() {
                    return name.to_string();
                }
            }
        }
        return "contentBlockDelta".into();
    }
    if let Ok(value) = serde_json::from_str::<Value>(trimmed)
        && let Some(ty) = value.get("type").and_then(Value::as_str)
    {
        return ty.to_string();
    }
    "chunk".into()
}

fn unknown_event(
    wire: Wire,
    profile: &ResolvedProfile,
    name: &str,
    data: &str,
) -> Result<Option<IrStreamEvent>, MapError> {
    // A missing `type` is named `chunk`, which is not a Responses event.
    // A bare `error` matches unary decode. A `response.*` status frame
    // has no gateway detail and stays a no-op.
    if wire == Wire::Responses
        && !responses_unknown_carries_payload(data)
        && let Some(detail) = responses_bare_error(data)
    {
        return Err(MapError::Invalid(detail));
    }
    match profile.dialect.stream_unknown_policy {
        StreamUnknownPolicy::HardError => {
            // A Responses status frame repeats ids. Skip it. A nonempty
            // delta, arguments, code, command, text, or image is the only
            // copy of that content, so it still fails.
            if wire == Wire::Responses && !responses_unknown_carries_payload(data) {
                return Ok(None);
            }
            Err(MapError::HardError {
                path: name.to_string(),
                detail: format!(
                    "unknown stream event `{name}` (stream_unknown_policy = hard-error|passthrough, or add `{name}` to stream_events)"
                ),
            })
        }
        StreamUnknownPolicy::Passthrough => {
            let raw =
                serde_json::from_str(data).unwrap_or_else(|_| Value::String(data.to_string()));
            Ok(Some(IrStreamEvent::Unknown {
                event: name.to_string(),
                raw,
            }))
        }
    }
}

/// Top-level payload only. `response.queued` nests a full Response
/// under `response`; walking that object would treat the snapshot as
/// new text.
fn responses_unknown_carries_payload(data: &str) -> bool {
    let Ok(value) = serde_json::from_str::<Value>(data) else {
        return true;
    };
    let Some(obj) = value.as_object() else {
        return value.as_str().is_some_and(|text| !text.trim().is_empty());
    };
    const KEYS: &[&str] = &[
        "delta",
        "arguments",
        "code",
        "command",
        "text",
        "input",
        "refusal",
        "partial_image_b64",
        "output",
    ];
    KEYS.iter()
        .any(|key| obj.get(*key).is_some_and(responses_payload_value_present))
}

fn responses_bare_error(data: &str) -> Option<String> {
    let value = serde_json::from_str::<Value>(data).ok()?;
    if let Some(detail) = complete::responses_gateway_error(&value) {
        return Some(detail);
    }
    // `status` or `object: response` hides the gateway check. A frame
    // with no text or output is still the vendor error.
    if let Some(text) = crate::completion::json_string_error(&value) {
        return Some(text.to_string());
    }
    if let Some(detail) = value
        .get("error")
        .filter(|err| err.is_object())
        .and_then(crate::completion::error_object_detail)
    {
        return Some(detail);
    }
    responses::failure_detail(&value)
}

fn responses_payload_value_present(value: &Value) -> bool {
    match value {
        Value::String(text) => !text.trim().is_empty(),
        Value::Array(items) => items.iter().any(responses_payload_value_present),
        Value::Object(map) => map.values().any(responses_payload_value_present),
        _ => false,
    }
}

fn str_field(value: &Value, key: &str) -> Option<String> {
    value.get(key)?.as_str().map(str::to_string)
}

/// Chat-shaped SSE `data` that is only an `error` object.
///
/// A choice with text, a refusal, audio bytes, or a real tool call stays
/// a chunk even if `error` is also set. An empty `image_url`, an empty
/// `input_audio`, and `tool_calls: [{}]` are not that payload.
#[cfg(any(feature = "client", feature = "proxy"))]
pub(crate) fn sse_wrapped_error_message(data: &str) -> Option<String> {
    let value: Value = serde_json::from_str(data).ok()?;
    // Empty choices and an empty delta are not a chunk. A top-level
    // delta still counts when that delta has visible text.
    if crate::completion::json_has_completion(&value) || crate::completion::choice_visible(&value) {
        return None;
    }
    if let Some(text) = value
        .get("error")
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|text| !text.is_empty())
    {
        return Some(text.to_string());
    }
    // Responses `event: error` is a flat object. Other wires nest `error`.
    let error = if let Some(error) = value.get("error").filter(|v| v.is_object()) {
        error
    } else if value.get("type").and_then(Value::as_str) == Some("error") {
        &value
    } else {
        return None;
    };
    let message = error
        .get("message")
        .and_then(Value::as_str)
        .filter(|text| !text.is_empty());
    let code = ["type", "code", "status"].iter().find_map(|key| {
        let text = error
            .get(*key)
            .and_then(Value::as_str)
            .filter(|text| !text.is_empty())?;
        if *key == "type" && text == "error" {
            return None;
        }
        Some(text.to_string())
    });
    match (code, message) {
        (Some(code), Some(message)) => Some(format!("{code}: {message}")),
        (None, Some(message)) => Some(message.to_string()),
        _ => Some(data.to_string()),
    }
}

/// String, object, or array. Objects and arrays become compact JSON.
/// Empty string is absent. Anything else is an error, not a silent drop.
fn json_text_field(value: &Value, key: &str) -> Result<Option<String>, MapError> {
    match value.get(key) {
        None => Ok(None),
        Some(Value::String(text)) if text.is_empty() => Ok(None),
        Some(Value::String(text)) => Ok(Some(text.clone())),
        Some(text @ (Value::Object(_) | Value::Array(_))) => Ok(Some(text.to_string())),
        Some(_) => Err(MapError::Invalid(format!(
            "{key} must be a string, object, or array"
        ))),
    }
}

fn u32_field(value: &Value, key: &str) -> Option<u32> {
    value.get(key)?.as_u64().and_then(|n| u32::try_from(n).ok())
}

/// Reject a present index above the cap. Absence is allowed.
///
/// Compare only; never resize a buffer to `index`.
fn check_index(value: &Value, key: &str, cap: u32, kind: &str) -> Result<(), MapError> {
    let Some(raw) = value.get(key) else {
        return Ok(());
    };
    let Some(n) = raw.as_u64() else {
        return Err(MapError::Invalid(format!(
            "{kind} index must be an unsigned integer"
        )));
    };
    if n > u64::from(cap) {
        return Err(MapError::Invalid(format!(
            "{kind} index {n} exceeds cap ({cap})"
        )));
    }
    Ok(())
}

fn protocol(name: &str, value: &Value) -> IrStreamEvent {
    IrStreamEvent::Protocol {
        item_type: name.to_string(),
        payload: value.clone(),
    }
}

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

    #[test]
    fn parse_all_splits_frames_and_skips_comments() {
        let frames = RawSse::parse_all(
            ": keep-alive\n\nevent: ping\ndata: {\"type\":\"ping\"}\n\ndata: [DONE]\n\n",
        )
        .expect("parse short SSE document");
        assert_eq!(frames.len(), 2);
        assert_eq!(frames[0].event.as_deref(), Some("ping"));
        assert_eq!(frames[0].data, r#"{"type":"ping"}"#);
        assert_eq!(frames[1].event, None);
        assert_eq!(frames[1].data, "[DONE]");
    }

    #[test]
    fn parse_all_errors_when_line_exceeds_sse_cap() {
        let frames = RawSse::parse_all("data: hi\n\n").expect("parse one SSE frame");
        assert_eq!(frames.len(), 1);
        assert_eq!(frames[0].data, "hi");

        let oversized = "a".repeat(MAX_SSE_PENDING + 1);
        let err = RawSse::parse_all(&oversized).expect_err("oversized SSE line");
        assert!(err.contains("exceeds"), "{err}");
    }

    #[test]
    fn parse_all_errors_when_joined_data_exceeds_sse_cap() {
        let half = "a".repeat(MAX_SSE_PENDING / 2);
        let doc = format!("data: {half}\ndata: {half}\n\n");
        let err = RawSse::parse_all(&doc).expect_err("joined data over the cap");
        assert!(err.contains("SSE data exceeds"), "{err}");
    }

    fn profile() -> ResolvedProfile {
        wiremux_auth::parse_profile_str(
            r#"
schema_version = 1
id = "t"
wire = "chat-completions"
base_url = "http://127.0.0.1"
"#,
        )
        .expect("profile")
    }

    fn frame(event: Option<&str>, data: &str) -> RawSse {
        RawSse {
            event: event.map(str::to_string),
            data: data.to_string(),
        }
    }

    fn responses_profile() -> ResolvedProfile {
        wiremux_auth::parse_profile_str(
            r#"
schema_version = 1
id = "t"
wire = "responses"
base_url = "http://127.0.0.1"
"#,
        )
        .expect("responses profile")
    }

    fn converse_profile() -> ResolvedProfile {
        wiremux_auth::parse_profile_str(
            r#"
schema_version = 1
id = "t"
wire = "converse"
base_url = "http://127.0.0.1"
"#,
        )
        .expect("converse profile")
    }

    fn assert_invalid(err: MapError, detail: &str) {
        match err {
            MapError::Invalid(got) => assert_eq!(got, detail),
            other => panic!("expected Invalid({detail}), got {other}"),
        }
    }

    fn assert_stream_invalid(wire: Wire, raw: &RawSse, profile: &ResolvedProfile, detail: &str) {
        assert_invalid(
            decode_stream_events(wire, raw, profile).expect_err("decode_stream_events"),
            detail,
        );
        assert_invalid(
            decode_stream_event(wire, raw, profile).expect_err("decode_stream_event"),
            detail,
        );
    }

    #[test]
    fn chat_tool_stream_without_done_is_not_terminal() {
        let profile = profile();
        let frames = [frame(
            None,
            r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"a","arguments":""}}]}}]}"#,
        )];
        assert!(!stream_has_terminal(Wire::ChatCompletions, &[], &profile));
        assert!(!frame_is_terminal(
            Wire::ChatCompletions,
            &frames[0],
            &profile
        ));
        assert!(!stream_has_terminal(
            Wire::ChatCompletions,
            &frames,
            &profile
        ));
        let done = frame(None, "[DONE]");
        assert!(frame_is_terminal(Wire::ChatCompletions, &done, &profile));
        assert!(stream_has_terminal(
            Wire::ChatCompletions,
            &[frames[0].clone(), done],
            &profile
        ));
    }

    #[test]
    fn messages_content_block_stop_is_not_terminal() {
        let profile = profile();
        let stop_block = frame(
            Some("content_block_stop"),
            r#"{"type":"content_block_stop","index":0}"#,
        );
        assert!(!frame_is_terminal(Wire::Messages, &stop_block, &profile));
        let message_stop = frame(Some("message_stop"), r#"{"type":"message_stop"}"#);
        assert!(frame_is_terminal(Wire::Messages, &message_stop, &profile));
    }

    #[test]
    fn wrapped_complete_json_with_finish_reason_is_terminal() {
        let profile = profile();
        let body = frame(
            None,
            r#"{"choices":[{"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}"#,
        );
        assert!(frame_is_terminal(Wire::ChatCompletions, &body, &profile));
    }

    #[test]
    fn gemini_visible_text_keeps_thought_signature() {
        let part = serde_json::json!({
            "text": "answer",
            "thoughtSignature": "sig"
        });
        let mut seq = 0;
        let events = gemini_part_events(&part, &mut seq);
        assert!(
            events
                .iter()
                .any(|ev| matches!(ev, IrStreamEvent::TextDelta { text } if text == "answer")),
            "{events:?}"
        );
        assert!(
            events.iter().any(
                |ev| matches!(ev, IrStreamEvent::ReasoningSignature { signature } if signature == "sig")
            ),
            "{events:?}"
        );
    }

    #[test]
    fn chat_empty_delta_with_error_is_invalid() {
        let profile = profile();
        let empty = frame(
            None,
            r#"{"choices":[{"index":0,"delta":{}}],"error":{"message":"overloaded","type":"server_error"}}"#,
        );
        let err = decode_stream_events(Wire::ChatCompletions, &empty, &profile)
            .expect_err("empty delta plus error");
        assert_eq!(err.to_string(), "server_error: overloaded");
        let singular = decode_stream_event(Wire::ChatCompletions, &empty, &profile)
            .expect_err("singular decode hides the same error");
        assert_eq!(singular.to_string(), "server_error: overloaded");

        let with_id = frame(
            None,
            r#"{"id":"chatcmpl-1","created":1,"choices":[{"index":0,"delta":{}}],"error":{"message":"overloaded","type":"server_error"}}"#,
        );
        let err = decode_stream_events(Wire::ChatCompletions, &with_id, &profile)
            .expect_err("id and created must not hide the error");
        assert_eq!(err.to_string(), "server_error: overloaded");

        let blank = frame(
            None,
            r#"{"choices":[{"index":0,"delta":{"content":""}}],"error":{"message":"overloaded","type":"server_error"}}"#,
        );
        let err = decode_stream_events(Wire::ChatCompletions, &blank, &profile)
            .expect_err("empty content is not a completion");
        assert_eq!(err.to_string(), "server_error: overloaded");

        let stopped = frame(
            None,
            r#"{"choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"error":{"message":"overloaded","type":"server_error"}}"#,
        );
        let err = decode_stream_events(Wire::ChatCompletions, &stopped, &profile)
            .expect_err("finish_reason is not visible text");
        assert_eq!(err.to_string(), "server_error: overloaded");

        let err = decode_stream_events(
            Wire::ChatCompletions,
            &frame(
                None,
                r#"{"choices":[{"index":0,"delta":{}}],"error":"overloaded"}"#,
            ),
            &profile,
        )
        .expect_err("string error");
        assert_eq!(err.to_string(), "overloaded");

        let err = decode_stream_events(
            Wire::ChatCompletions,
            &frame(
                None,
                r#"{"choices":[{"index":0,"delta":{}}],"error":{"code":"model_not_found","type":"invalid_request_error","message":"no such model"}}"#,
            ),
            &profile,
        )
        .expect_err("code wins over type");
        assert_eq!(err.to_string(), "model_not_found: no such model");

        let text = decode_stream_events(
            Wire::ChatCompletions,
            &frame(
                None,
                r#"{"choices":[{"index":0,"delta":{"content":"Hi"}}],"error":{"message":"overloaded","type":"server_error"}}"#,
            ),
            &profile,
        )
        .expect("visible text stays");
        assert!(
            text.iter()
                .any(|ev| matches!(ev, IrStreamEvent::TextDelta { text } if text == "Hi")),
            "{text:?}"
        );

        let refusal = decode_stream_events(
            Wire::ChatCompletions,
            &frame(
                None,
                r#"{"choices":[{"index":0,"delta":{"refusal":"no"}}],"error":{"message":"overloaded"}}"#,
            ),
            &profile,
        )
        .expect("refusal stays");
        assert!(
            refusal
                .iter()
                .any(|ev| matches!(ev, IrStreamEvent::RefusalDelta { text } if text == "no")),
            "{refusal:?}"
        );

        let calls = decode_stream_events(
            Wire::ChatCompletions,
            &frame(
                None,
                r#"{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"lookup","arguments":""}}]}}],"error":{"message":"overloaded"}}"#,
            ),
            &profile,
        )
        .expect("tool call stays");
        assert!(
            calls.iter().any(|ev| matches!(
                ev,
                IrStreamEvent::ToolCallStart { id, name, .. } if id == "call_1" && name == "lookup"
            )),
            "{calls:?}"
        );

        let quiet = decode_stream_events(
            Wire::ChatCompletions,
            &frame(None, r#"{"choices":[{"index":0,"delta":{}}]}"#),
            &profile,
        )
        .expect("empty delta without an error is a no-op");
        assert!(quiet.is_empty(), "{quiet:?}");
    }

    #[test]
    fn chat_empty_media_or_tool_shell_does_not_hide_the_error() {
        let profile = profile();
        let shells = [
            r#"{"choices":[{"message":{"role":"assistant","content":[{"type":"image_url"}]}}],"error":{"message":"backend failed"}}"#,
            r#"{"choices":[{"message":{"role":"assistant","content":[{"type":"input_audio"}]}}],"error":{"message":"backend failed"}}"#,
            r#"{"choices":[{"delta":{"tool_calls":[{}]}}],"error":{"message":"backend failed"}}"#,
        ];
        for body in shells {
            let err = decode_stream_events(Wire::ChatCompletions, &frame(None, body), &profile)
                .expect_err(body);
            assert!(err.to_string().contains("backend failed"), "{body}: {err}");
        }

        let image = decode_stream_events(
            Wire::ChatCompletions,
            &frame(
                None,
                r#"{"choices":[{"delta":{"content":[{"type":"image_url","image_url":{"url":"https://example.com/a.png"}}]}}],"error":{"message":"backend failed"}}"#,
            ),
            &profile,
        )
        .expect("image url stays a completion");
        assert!(
            image.iter().any(|ev| matches!(
                ev,
                IrStreamEvent::Protocol { item_type, .. } if item_type == "image_url"
            )),
            "{image:?}"
        );

        decode_stream_events(
            Wire::ChatCompletions,
            &frame(
                None,
                r#"{"choices":[{"delta":{"content":[{"type":"input_audio","input_audio":{"data":"AAA","format":"wav"}}]}}],"error":{"message":"backend failed"}}"#,
            ),
            &profile,
        )
        .expect("audio data stays a completion");
    }

    #[test]
    fn gemini_empty_part_shell_does_not_hide_the_error() {
        let profile = wiremux_auth::parse_profile_str(
            r#"
schema_version = 1
id = "g"
wire = "gemini"
base_url = "http://127.0.0.1"
"#,
        )
        .expect("gemini profile");
        let shells = [
            r#"{"candidates":[{"content":{"parts":[{"functionCall":{}}]}}],"error":{"message":"backend failed"}}"#,
            r#"{"candidates":[{"content":{"parts":[{"inlineData":{}}]}}],"error":{"message":"backend failed"}}"#,
            r#"{"candidates":[{"content":{"parts":[{"inlineData":{"mimeType":"image/png"}}]}}],"error":{"message":"backend failed"}}"#,
            r#"{"candidates":[{"content":{"parts":[{"fileData":{}}]}}],"error":{"message":"backend failed"}}"#,
            r#"{"candidates":[{"content":{"parts":[{"fileData":{"mimeType":"text/plain"}}]}}],"error":{"message":"backend failed"}}"#,
            r#"{"candidates":[{"content":{"parts":[{"executableCode":{}}]}}],"error":{"message":"backend failed"}}"#,
            r#"{"candidates":[{"content":{"parts":[{"codeExecutionResult":{}}]}}],"error":{"message":"backend failed"}}"#,
            r#"{"candidates":[{"content":{"parts":[{"functionResponse":{}}]}}],"error":{"message":"backend failed"}}"#,
            r#"{"candidates":[{"content":{"parts":[{"toolCall":{}}]}}],"error":{"message":"backend failed"}}"#,
            r#"{"candidates":[{"content":{"parts":[{"toolResponse":{}}]}}],"error":{"message":"backend failed"}}"#,
        ];
        for body in shells {
            let err =
                decode_stream_events(Wire::Gemini, &frame(None, body), &profile).expect_err(body);
            assert!(err.to_string().contains("backend failed"), "{body}: {err}");
            let err = decode_response(Wire::Gemini, body.as_bytes(), &profile).expect_err(body);
            assert!(err.to_string().contains("backend failed"), "{body}: {err}");
            assert_eq!(
                sse_wrapped_error_message(body).as_deref(),
                Some("backend failed"),
                "{body}"
            );
        }

        let quiet = decode_stream_events(
            Wire::Gemini,
            &frame(
                None,
                r#"{"candidates":[{"content":{"parts":[{"functionCall":{}}]}}]}"#,
            ),
            &profile,
        )
        .expect("empty functionCall is a no-op");
        assert!(
            quiet
                .iter()
                .all(|ev| !matches!(ev, IrStreamEvent::ToolCallStart { .. })),
            "{quiet:?}"
        );

        let kept = decode_stream_events(
            Wire::Gemini,
            &frame(
                None,
                r#"{"candidates":[{"content":{"parts":[{"functionCall":{"name":"ping","args":{}}}]}}],"error":{"message":"backend failed"}}"#,
            ),
            &profile,
        )
        .expect("named function call stays");
        assert!(
            kept.iter().any(|ev| matches!(
                ev,
                IrStreamEvent::ToolCallStart { name, .. } if name == "ping"
            )),
            "{kept:?}"
        );
    }

    #[test]
    fn chat_error_on_an_unknown_event_keeps_stream_policy() {
        let raw = frame(
            Some("error"),
            r#"{"error":{"message":"overloaded","type":"server_error"}}"#,
        );
        let err = decode_stream_events(Wire::ChatCompletions, &raw, &profile())
            .expect_err("default policy is hard-error");
        match err {
            MapError::HardError { path, detail } => {
                assert_eq!(path, "error");
                assert!(detail.contains("unknown stream event"), "{detail}");
            }
            other => panic!("expected HardError, got {other}"),
        }

        let pass = wiremux_auth::parse_profile_str(
            r#"
schema_version = 1
id = "t"
wire = "chat-completions"
stream_unknown_policy = "passthrough"
base_url = "http://127.0.0.1"
"#,
        )
        .expect("passthrough");
        let events = decode_stream_events(Wire::ChatCompletions, &raw, &pass)
            .expect("passthrough keeps the frame");
        assert!(
            events
                .iter()
                .any(|ev| matches!(ev, IrStreamEvent::Unknown { event, .. } if event == "error")),
            "{events:?}"
        );
    }

    #[cfg(any(feature = "client", feature = "proxy"))]
    #[test]
    fn sse_wrapped_error_message_extracts_error_object() {
        let msg = sse_wrapped_error_message(
            r#"{"error":{"message":"upstream failed","type":"server_error"}}"#,
        );
        assert_eq!(msg.as_deref(), Some("server_error: upstream failed"));
    }

    #[cfg(any(feature = "client", feature = "proxy"))]
    #[test]
    fn sse_wrapped_error_message_reads_responses_error_event() {
        let raw = r#"{"type":"error","code":"server_error","message":"The server had an error","param":null}"#;
        assert_eq!(
            sse_wrapped_error_message(raw).as_deref(),
            Some("server_error: The server had an error")
        );
    }

    #[test]
    fn responses_error_event_keeps_vendor_message() {
        let profile = wiremux_auth::parse_profile_str(
            r#"
schema_version = 1
id = "t"
wire = "responses"
base_url = "http://127.0.0.1"
"#,
        )
        .expect("profile");
        let raw = frame(
            Some("error"),
            r#"{"type":"error","code":"server_error","message":"The server had an error","param":null}"#,
        );
        let err = decode_stream_event(Wire::Responses, &raw, &profile)
            .expect_err("responses error event");
        let msg = err.to_string();
        assert!(
            msg.contains("The server had an error"),
            "vendor message must survive, got {msg}"
        );
        assert!(
            !msg.contains("unknown stream event"),
            "error is a known Responses event, got {msg}"
        );
    }

    #[test]
    fn responses_done_events_do_not_fail_or_repeat_deltas() {
        let profile = wiremux_auth::parse_profile_str(
            r#"
schema_version = 1
id = "t"
wire = "responses"
base_url = "http://127.0.0.1"
"#,
        )
        .expect("profile");
        let cases = [
            (
                "response.output_text.done",
                r#"{"type":"response.output_text.done","text":"Hi"}"#,
            ),
            (
                "response.content_part.done",
                r#"{"type":"response.content_part.done"}"#,
            ),
            (
                "response.function_call_arguments.done",
                r#"{"type":"response.function_call_arguments.done","arguments":"{}"}"#,
            ),
            (
                "response.refusal.done",
                r#"{"type":"response.refusal.done","refusal":"no"}"#,
            ),
            ("response.audio.done", r#"{"type":"response.audio.done"}"#),
            (
                "response.audio.transcript.done",
                r#"{"type":"response.audio.transcript.done","transcript":"Hi"}"#,
            ),
        ];
        for (event, data) in cases {
            let raw = frame(Some(event), data);
            let events = decode_stream_events(Wire::Responses, &raw, &profile)
                .unwrap_or_else(|err| panic!("{event} is part of a normal stream, got {err}"));
            assert!(
                events.iter().all(|ev| !matches!(
                    ev,
                    IrStreamEvent::TextDelta { .. }
                        | IrStreamEvent::RefusalDelta { .. }
                        | IrStreamEvent::ToolCallArgDelta { .. }
                        | IrStreamEvent::AudioDelta { .. }
                        | IrStreamEvent::AudioTranscriptDelta { .. }
                )),
                "{event} must not repeat the delta, got {events:?}"
            );
        }
    }

    #[test]
    fn responses_reasoning_and_custom_tool_events_keep_deltas() {
        let profile = wiremux_auth::parse_profile_str(
            r#"
schema_version = 1
id = "t"
wire = "responses"
base_url = "http://127.0.0.1"
"#,
        )
        .expect("profile");
        let think = decode_stream_events(
            Wire::Responses,
            &frame(
                Some("response.reasoning_text.delta"),
                r#"{"type":"response.reasoning_text.delta","delta":"think"}"#,
            ),
            &profile,
        )
        .expect("reasoning text delta is a normal event");
        assert!(
            think.iter().any(|ev| matches!(
                ev,
                IrStreamEvent::ReasoningDelta { text } if text == "think"
            )),
            "{think:?}"
        );
        let quiet = [
            "response.reasoning_summary_part.added",
            "response.reasoning_summary_part.done",
            "response.reasoning_summary_text.done",
            "response.reasoning_text.done",
            "response.custom_tool_call_input.done",
        ];
        for event in quiet {
            let events = decode_stream_events(
                Wire::Responses,
                &frame(
                    Some(event),
                    &format!(r#"{{"type":"{event}","text":"full","input":"full"}}"#),
                ),
                &profile,
            )
            .unwrap_or_else(|err| panic!("{event} follows a delta we already accept, got {err}"));
            assert!(
                events.iter().all(|ev| !matches!(
                    ev,
                    IrStreamEvent::ReasoningDelta { .. }
                        | IrStreamEvent::CustomToolCallInputDelta { .. }
                )),
                "{event} must not repeat the delta, got {events:?}"
            );
        }
    }

    #[test]
    fn responses_hosted_tool_progress_is_protocol() {
        let profile = wiremux_auth::parse_profile_str(
            r#"
schema_version = 1
id = "t"
wire = "responses"
base_url = "http://127.0.0.1"
"#,
        )
        .expect("profile");
        let names = [
            "response.web_search_call.in_progress",
            "response.web_search_call.searching",
            "response.web_search_call.completed",
            "response.file_search_call.in_progress",
            "response.file_search_call.searching",
            "response.file_search_call.completed",
            "response.code_interpreter_call.in_progress",
            "response.code_interpreter_call.interpreting",
            "response.code_interpreter_call.completed",
            "response.image_generation_call.in_progress",
            "response.image_generation_call.generating",
            "response.image_generation_call.completed",
            "response.mcp_call.in_progress",
            "response.mcp_call.completed",
            "response.mcp_call.failed",
            "response.mcp_list_tools.in_progress",
            "response.mcp_list_tools.completed",
            "response.mcp_list_tools.failed",
        ];
        for event in names {
            let events = decode_stream_events(
                Wire::Responses,
                &frame(
                    Some(event),
                    &format!(r#"{{"type":"{event}","item_id":"id_1"}}"#),
                ),
                &profile,
            )
            .unwrap_or_else(|err| panic!("{event} must not abort the stream, got {err}"));
            assert!(
                events.iter().any(|ev| matches!(
                    ev,
                    IrStreamEvent::Protocol { item_type, .. } if item_type == event
                )),
                "{event} must stay protocol, got {events:?}"
            );
        }
    }

    #[test]
    fn responses_status_only_unknown_is_skipped_on_hard_error() {
        let profile =
            wiremux_auth::parse_profile_str(include_str!("../../../../presets/openai-codex.toml"))
                .expect("openai-codex");
        let text = decode_stream_events(
            Wire::Responses,
            &frame(
                Some("response.output_text.delta"),
                r#"{"type":"response.output_text.delta","delta":"Hi"}"#,
            ),
            &profile,
        )
        .expect("text delta");
        assert!(
            text.iter()
                .any(|ev| matches!(ev, IrStreamEvent::TextDelta { text } if text == "Hi")),
            "text delta must be kept, got {text:?}"
        );
        let quiet = [
            (
                "response.queued",
                r#"{"type":"response.queued","response":{"id":"resp_1","output":[{"type":"message","content":[{"type":"output_text","text":"already sent"}]}]}}"#,
            ),
            (
                "response.compaction.compacting",
                r#"{"type":"response.compaction.compacting","sequence_number":0,"output_index":0,"item_id":"item_1"}"#,
            ),
            (
                "response.shell_call_command.added",
                r#"{"type":"response.shell_call_command.added","item_id":"sh_1","sequence_number":1}"#,
            ),
        ];
        for (event, data) in quiet {
            let events = decode_stream_events(Wire::Responses, &frame(Some(event), data), &profile)
                .unwrap_or_else(|err| panic!("{event} is status only, got {err}"));
            assert!(
                events.is_empty(),
                "{event} must not emit text or a second delta, got {events:?}"
            );
        }
        let searching = decode_stream_events(
            Wire::Responses,
            &frame(
                Some("response.web_search_call.searching"),
                r#"{"type":"response.web_search_call.searching","item_id":"ws_1"}"#,
            ),
            &profile,
        )
        .expect("searching");
        assert!(
            searching
                .iter()
                .all(|ev| !matches!(ev, IrStreamEvent::TextDelta { .. })),
            "searching must not become text, got {searching:?}"
        );
        let completed = decode_stream_events(
            Wire::Responses,
            &frame(
                Some("response.completed"),
                r#"{"type":"response.completed","response":{"id":"resp_1","status":"completed"}}"#,
            ),
            &profile,
        )
        .expect("completed");
        assert!(
            completed
                .iter()
                .all(|ev| !matches!(ev, IrStreamEvent::TextDelta { .. })),
            "completed must not repeat the text delta, got {completed:?}"
        );

        let payload = [
            (
                "response.mcp_call_arguments.delta",
                r#"{"type":"response.mcp_call_arguments.delta","delta":"{"}"#,
            ),
            (
                "response.mcp_call_arguments.done",
                r#"{"type":"response.mcp_call_arguments.done","arguments":"{}"}"#,
            ),
            (
                "response.code_interpreter_call_code.delta",
                r#"{"type":"response.code_interpreter_call_code.delta","delta":"print(1)"}"#,
            ),
            (
                "response.code_interpreter_call_code.done",
                r#"{"type":"response.code_interpreter_call_code.done","code":"print(1)"}"#,
            ),
            (
                "response.image_generation_call.partial_image",
                r#"{"type":"response.image_generation_call.partial_image","partial_image_b64":"abcd"}"#,
            ),
            (
                "response.shell_call_command.delta",
                r#"{"type":"response.shell_call_command.delta","delta":"ls"}"#,
            ),
            (
                "response.shell_call_command.added",
                r#"{"type":"response.shell_call_command.added","command":"ls"}"#,
            ),
            (
                "response.shell_call_output_content.delta",
                r#"{"type":"response.shell_call_output_content.delta","delta":{"stdout":"ok","stderr":""}}"#,
            ),
            (
                "response.shell_call_output_content.done",
                r#"{"type":"response.shell_call_output_content.done","output":[{"stdout":"ok","stderr":""}]}"#,
            ),
        ];
        for (event, data) in payload {
            let err = decode_stream_events(Wire::Responses, &frame(Some(event), data), &profile)
                .expect_err(event);
            let crate::map::MapError::HardError { detail, .. } = err else {
                panic!("{event} must stay a hard-error, got {err}");
            };
            assert!(
                detail.contains(event),
                "{event} detail must name the event, got {detail}"
            );
        }

        let pass = wiremux_auth::parse_profile_str(
            r#"
schema_version = 1
id = "t"
wire = "responses"
stream_unknown_policy = "passthrough"
base_url = "http://127.0.0.1"
"#,
        )
        .expect("passthrough");
        let events = decode_stream_events(
            Wire::Responses,
            &frame(
                Some("response.queued"),
                r#"{"type":"response.queued","sequence_number":1}"#,
            ),
            &pass,
        )
        .expect("passthrough queued");
        assert!(
            events.iter().any(|ev| matches!(
                ev,
                IrStreamEvent::Unknown { event, .. } if event == "response.queued"
            )),
            "passthrough must forward queued, got {events:?}"
        );
    }

    #[test]
    fn responses_frameless_gateway_error_is_invalid() {
        let profile = responses_profile();
        let cases = [
            (
                r#"{"error":{"message":"model catalog unavailable","type":"server_error"}}"#,
                "server_error: model catalog unavailable",
            ),
            (
                r#"{"error":"model catalog unavailable"}"#,
                "model catalog unavailable",
            ),
            (r#"{"error":{"code":503}}"#, "503"),
            (
                r#"{"status":"failed","error":{"message":"overloaded","type":"server_error"}}"#,
                "server_error: overloaded",
            ),
            (
                r#"{"type":"response.queued","error":{"message":"overloaded","type":"server_error"}}"#,
                "server_error: overloaded",
            ),
        ];
        for (body, detail) in cases {
            assert_stream_invalid(Wire::Responses, &frame(None, body), &profile, detail);
        }

        let queued = frame(None, r#"{"type":"response.queued"}"#);
        let events = decode_stream_events(Wire::Responses, &queued, &profile)
            .expect("status frame stays a no-op");
        assert!(events.is_empty(), "{events:?}");
        let one = decode_stream_event(Wire::Responses, &queued, &profile)
            .expect("status frame stays a no-op");
        assert!(one.is_none(), "{one:?}");

        let failed = frame(
            Some("response.failed"),
            r#"{"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"model catalog unavailable"}}}"#,
        );
        assert_stream_invalid(
            Wire::Responses,
            &failed,
            &profile,
            "server_error: model catalog unavailable",
        );
    }

    #[test]
    fn responses_allowlisted_error_frame_is_invalid() {
        let profile = responses_profile();
        let cases = [
            (
                "response.output_text.done",
                r#"{"type":"response.output_text.done","error":{"message":"overloaded","type":"server_error"}}"#,
                "server_error: overloaded",
            ),
            (
                "response.output_text.done",
                r#"{"type":"response.output_text.done","error":{"code":"model_not_found","type":"invalid_request_error","message":"no such model"}}"#,
                "model_not_found: no such model",
            ),
            (
                "response.output_text.done",
                r#"{"type":"response.output_text.done","text":"","error":"model catalog unavailable"}"#,
                "model catalog unavailable",
            ),
            (
                "response.completed",
                r#"{"type":"response.completed","error":{"message":"overloaded","type":"server_error"}}"#,
                "server_error: overloaded",
            ),
            (
                "response.completed",
                r#"{"type":"response.completed","response":{"output":[]},"error":{"code":503,"type":"server_error"}}"#,
                "503",
            ),
            (
                "response.completed",
                r#"{"type":"response.completed","response":{"usage":{"input_tokens":1,"output_tokens":2}},"error":{"message":"overloaded","type":"server_error"}}"#,
                "server_error: overloaded",
            ),
            (
                "response.completed",
                r#"{"type":"response.completed","response":{"status":"failed","error":{"code":"server_error","message":"overloaded"}}}"#,
                "server_error: overloaded",
            ),
            (
                "response.failed",
                r#"{"type":"response.failed","error":{"message":"overloaded","type":"server_error"}}"#,
                "server_error: overloaded",
            ),
            (
                "response.refusal.done",
                r#"{"type":"response.refusal.done","error":{"message":"overloaded","type":"server_error"}}"#,
                "server_error: overloaded",
            ),
            (
                "response.incomplete",
                r#"{"type":"response.incomplete","error":{"message":"overloaded","type":"server_error"}}"#,
                "server_error: overloaded",
            ),
            (
                "response.created",
                r#"{"type":"response.created","error":{"code":"server_error","message":"overloaded"}}"#,
                "server_error: overloaded",
            ),
        ];
        for (event, body, detail) in cases {
            assert_stream_invalid(Wire::Responses, &frame(Some(event), body), &profile, detail);
        }

        let text = frame(
            Some("response.output_text.done"),
            r#"{"type":"response.output_text.done","text":"Hi","error":{"message":"overloaded","type":"server_error"}}"#,
        );
        let events =
            decode_stream_events(Wire::Responses, &text, &profile).expect("done text stays");
        assert!(events.is_empty(), "{events:?}");
        let one = decode_stream_event(Wire::Responses, &text, &profile).expect("done text stays");
        assert!(one.is_none(), "{one:?}");

        let output = frame(
            Some("response.completed"),
            r#"{"type":"response.completed","response":{"status":"completed","output":[{"type":"message"}]},"error":{"message":"overloaded","type":"server_error"}}"#,
        );
        decode_stream_events(Wire::Responses, &output, &profile).expect("completed output stays");
        decode_stream_event(Wire::Responses, &output, &profile).expect("completed output stays");

        let top_output = frame(
            Some("response.output_text.done"),
            r#"{"type":"response.output_text.done","output":[{"type":"message"}],"error":{"message":"overloaded","type":"server_error"}}"#,
        );
        decode_stream_events(Wire::Responses, &top_output, &profile)
            .expect("top-level output stays");
        decode_stream_event(Wire::Responses, &top_output, &profile)
            .expect("top-level output stays");

        let usage = frame(
            Some("response.completed"),
            r#"{"type":"response.completed","response":{"usage":{"input_tokens":4,"output_tokens":1}}}"#,
        );
        decode_stream_events(Wire::Responses, &usage, &profile).expect("usage stays");
        let one = decode_stream_event(Wire::Responses, &usage, &profile).expect("usage stays");
        assert!(
            one.is_some(),
            "usage without an error is not a no-op: {one:?}"
        );
    }

    #[test]
    fn converse_openai_error_envelope_is_invalid() {
        let profile = converse_profile();
        let cases = [
            (
                r#"{"error":{"message":"overloaded","type":"server_error"}}"#,
                "server_error: overloaded",
            ),
            (
                r#"{"error":"model catalog unavailable"}"#,
                "model catalog unavailable",
            ),
            (
                r#"{"output":null,"error":{"message":"overloaded","type":"server_error"}}"#,
                "server_error: overloaded",
            ),
            (
                r#"{"output":{},"error":{"message":"overloaded","type":"server_error"}}"#,
                "server_error: overloaded",
            ),
            (
                r#"{"stopReason":"","error":"model catalog unavailable"}"#,
                "model catalog unavailable",
            ),
        ];
        for (body, detail) in cases {
            assert_invalid(
                decode_response(Wire::Converse, body.as_bytes(), &profile)
                    .expect_err("decode_response"),
                detail,
            );
            assert_stream_invalid(Wire::Converse, &frame(None, body), &profile, detail);
        }

        let bedrock = r#"{"__type":"ValidationException","message":"The provided model identifier is invalid."}"#;
        let detail = "ValidationException: The provided model identifier is invalid.";
        assert_invalid(
            decode_response(Wire::Converse, bedrock.as_bytes(), &profile).expect_err("bedrock"),
            detail,
        );
        assert_stream_invalid(Wire::Converse, &frame(None, bedrock), &profile, detail);

        let with_output = r#"{"output":{"message":{"role":"assistant","content":[{"text":"Hi"}]}},"stopReason":"end_turn","error":{"message":"overloaded","type":"server_error"}}"#;
        let kept = decode_response(Wire::Converse, with_output.as_bytes(), &profile)
            .expect("output stays");
        assert!(
            kept.iter()
                .any(|ev| matches!(ev, IrStreamEvent::TextDelta { text } if text == "Hi")),
            "{kept:?}"
        );
        decode_stream_events(Wire::Converse, &frame(None, with_output), &profile)
            .expect("output is not a stream error");
        decode_stream_event(Wire::Converse, &frame(None, with_output), &profile)
            .expect("output is not a stream error");

        let with_stop = r#"{"stopReason":"end_turn","error":"model catalog unavailable"}"#;
        let kept = decode_response(Wire::Converse, with_stop.as_bytes(), &profile)
            .expect("stopReason stays");
        assert!(
            kept.iter().any(
                |ev| matches!(ev, IrStreamEvent::FinishReason { reason, .. } if reason == "end_turn")
            ),
            "{kept:?}"
        );
        decode_stream_events(Wire::Converse, &frame(None, with_stop), &profile)
            .expect("stopReason is not a stream error");
        decode_stream_event(Wire::Converse, &frame(None, with_stop), &profile)
            .expect("stopReason is not a stream error");

        let delta = r#"{"contentBlockDelta":{"delta":{"text":"Hi"}},"error":{"message":"overloaded","type":"server_error"}}"#;
        let events = decode_stream_events(Wire::Converse, &frame(None, delta), &profile)
            .expect("delta stays");
        assert!(
            events
                .iter()
                .any(|ev| matches!(ev, IrStreamEvent::TextDelta { text } if text == "Hi")),
            "{events:?}"
        );
    }

    #[test]
    fn converse_empty_output_shell_does_not_hide_the_error() {
        let profile = converse_profile();
        let shells = [
            r#"{"output":{"message":{"role":"assistant","content":[{"text":""}]}},"error":{"message":"backend failed","type":"server_error"}}"#,
            r#"{"output":{"message":{"role":"assistant","content":[{"toolUse":{}}]}},"error":{"message":"backend failed","type":"server_error"}}"#,
            r#"{"output":{"message":{"role":"assistant","content":[{"image":{}}]}},"error":{"message":"backend failed","type":"server_error"}}"#,
            r#"{"output":{"message":{"role":"assistant","content":[{"document":{}}]}},"error":{"message":"backend failed","type":"server_error"}}"#,
        ];
        for body in shells {
            assert_invalid(
                decode_response(Wire::Converse, body.as_bytes(), &profile)
                    .expect_err("empty output shell"),
                "server_error: backend failed",
            );
            assert_stream_invalid(
                Wire::Converse,
                &frame(None, body),
                &profile,
                "server_error: backend failed",
            );
        }

        let bare = r#"{"output":{"message":{"content":[{"toolUse":{}}]}}}"#;
        let events = decode_response(Wire::Converse, bare.as_bytes(), &profile)
            .expect("empty toolUse without an error");
        assert!(
            !events
                .iter()
                .any(|ev| matches!(ev, IrStreamEvent::ToolCallStart { .. })),
            "{events:?}"
        );

        let named = r#"{"output":{"message":{"content":[{"toolUse":{"toolUseId":"t1","name":"ping","input":{}}}]}},"error":{"message":"backend failed","type":"server_error"}}"#;
        let kept =
            decode_response(Wire::Converse, named.as_bytes(), &profile).expect("named tool stays");
        assert!(
            kept.iter().any(|ev| matches!(
                ev,
                IrStreamEvent::ToolCallStart { name, .. } if name == "ping"
            )),
            "{kept:?}"
        );

        let document = r#"{"output":{"message":{"content":[{"document":{"format":"pdf","name":"note","source":{"bytes":"JVBERi0x"}}}]}},"error":{"message":"backend failed"}}"#;
        decode_response(Wire::Converse, document.as_bytes(), &profile)
            .expect("document bytes stay");
        let guard = r#"{"output":{"message":{"content":[{"guardContent":{"text":{"text":"keep me"}}}]}},"error":{"message":"backend failed"}}"#;
        decode_response(Wire::Converse, guard.as_bytes(), &profile).expect("guard text stays");
    }

    #[test]
    fn messages_empty_tool_or_image_shell_does_not_hide_the_error() {
        let profile = wiremux_auth::parse_profile_str(
            "schema_version = 1\nid = \"messages\"\nwire = \"messages\"\n",
        )
        .expect("messages profile");
        let shells = [
            r#"{"content":[{"type":"tool_use"}],"error":{"message":"overloaded"}}"#,
            r#"{"content":[{"type":"image"}],"error":{"message":"overloaded"}}"#,
            r#"{"content":[{}],"error":{"message":"overloaded"}}"#,
        ];
        for body in shells {
            let err = decode_response(Wire::Messages, body.as_bytes(), &profile)
                .expect_err("empty messages shell");
            assert!(err.to_string().contains("overloaded"), "{body} -> {err}");
        }

        let named = r#"{"content":[{"type":"tool_use","id":"toolu_1","name":"ping","input":{}}],"error":{"message":"overloaded"}}"#;
        let kept =
            decode_response(Wire::Messages, named.as_bytes(), &profile).expect("named tool stays");
        assert!(
            kept.iter().any(|ev| matches!(
                ev,
                IrStreamEvent::ToolCallStart { id, name, .. } if id == "toolu_1" && name == "ping"
            )),
            "{kept:?}"
        );

        let image = r#"{"content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aGk="}}],"error":{"message":"overloaded"}}"#;
        decode_response(Wire::Messages, image.as_bytes(), &profile).expect("image bytes stay");

        let file_doc = r#"{"content":[{"type":"document","source":{"type":"file","file_id":"file_abc"}}],"error":{"message":"overloaded"}}"#;
        let kept_doc = decode_response(Wire::Messages, file_doc.as_bytes(), &profile)
            .expect("file document stays");
        assert!(
            kept_doc.iter().any(|ev| matches!(
                ev,
                IrStreamEvent::Protocol { item_type, payload }
                    if item_type == "document"
                        && payload.pointer("/source/file_id").and_then(Value::as_str)
                            == Some("file_abc")
            )),
            "{kept_doc:?}"
        );
        let file_image =
            r#"{"content":[{"type":"image","source":{"type":"file","file_id":"file_img"}}]}"#;
        let kept_image = decode_response(Wire::Messages, file_image.as_bytes(), &profile)
            .expect("file image stays");
        assert!(
            kept_image.iter().any(|ev| matches!(
                ev,
                IrStreamEvent::Protocol { item_type, payload }
                    if item_type == "image"
                        && payload.pointer("/source/file_id").and_then(Value::as_str)
                            == Some("file_img")
            )),
            "{kept_image:?}"
        );
    }

    #[cfg(any(feature = "client", feature = "proxy"))]
    #[test]
    fn sse_wrapped_error_message_reads_error_when_choices_are_empty() {
        let msg = sse_wrapped_error_message(r#"{"choices":[],"error":{"message":"nope"}}"#);
        assert_eq!(msg.as_deref(), Some("nope"));
    }

    #[cfg(any(feature = "client", feature = "proxy"))]
    #[test]
    fn sse_wrapped_error_message_reads_string_error() {
        let msg = sse_wrapped_error_message(r#"{"error":"model catalog unavailable"}"#);
        assert_eq!(msg.as_deref(), Some("model catalog unavailable"));
    }

    #[cfg(any(feature = "client", feature = "proxy"))]
    #[test]
    fn sse_wrapped_error_message_keeps_code_only_payload() {
        let raw = r#"{"error":{"code":"server_error"}}"#;
        assert_eq!(sse_wrapped_error_message(raw).as_deref(), Some(raw));
    }

    #[cfg(any(feature = "client", feature = "proxy"))]
    #[test]
    fn sse_wrapped_error_message_ignores_normal_chat_chunk() {
        let msg =
            sse_wrapped_error_message(r#"{"choices":[{"delta":{"content":"hi"},"index":0}]}"#);
        assert!(msg.is_none(), "{msg:?}");
    }

    #[cfg(any(feature = "client", feature = "proxy"))]
    #[test]
    fn sse_wrapped_error_message_reads_empty_delta() {
        let msg = sse_wrapped_error_message(
            r#"{"choices":[{"delta":{}}],"error":{"message":"overloaded"}}"#,
        );
        assert_eq!(msg.as_deref(), Some("overloaded"));
    }

    #[cfg(any(feature = "client", feature = "proxy"))]
    #[test]
    fn sse_wrapped_error_message_reads_empty_media_and_tool_shells() {
        for body in [
            r#"{"choices":[{"message":{"content":[{"type":"image_url"}]}}],"error":{"message":"backend failed"}}"#,
            r#"{"choices":[{"message":{"content":[{"type":"input_audio"}]}}],"error":{"message":"backend failed"}}"#,
            r#"{"choices":[{"delta":{"tool_calls":[{}]}}],"error":{"message":"backend failed"}}"#,
        ] {
            let msg = sse_wrapped_error_message(body);
            assert_eq!(msg.as_deref(), Some("backend failed"), "{body}: {msg:?}");
        }
        let kept = sse_wrapped_error_message(
            r#"{"choices":[{"delta":{"tool_calls":[{"id":"call_1","function":{"name":"lookup"}}]}}],"error":{"message":"backend failed"}}"#,
        );
        assert!(kept.is_none(), "{kept:?}");
    }

    #[cfg(feature = "proxy")]
    #[test]
    fn event_has_slot_protocol_chunk_is_not_gemini_slot() {
        let ev = IrStreamEvent::Protocol {
            item_type: "chunk".into(),
            payload: Value::Null,
        };
        assert!(!event_has_slot(Wire::Gemini, &ev));
    }

    #[cfg(feature = "proxy")]
    #[test]
    fn event_has_slot_keeps_responses_web_search_call() {
        let ev = IrStreamEvent::Protocol {
            item_type: "web_search_call".into(),
            payload: serde_json::json!({"type": "web_search_call", "id": "ws_1"}),
        };
        assert!(event_has_slot(Wire::Responses, &ev));
    }

    #[test]
    fn converse_message_stop_is_terminal_and_a_delta_is_not() {
        let profile = profile();
        let stop = RawSse {
            event: None,
            data: r#"{"messageStop":{"stopReason":"end_turn"}}"#.into(),
        };
        assert!(frame_is_terminal(Wire::Converse, &stop, &profile));
        let delta = RawSse {
            event: None,
            data: r#"{"contentBlockDelta":{"delta":{"text":"hi"}}}"#.into(),
        };
        assert!(!frame_is_terminal(Wire::Converse, &delta, &profile));
        let empty_reason = RawSse {
            event: None,
            data: r#"{"messageStop":{"stopReason":""}}"#.into(),
        };
        assert!(
            frame_is_terminal(Wire::Converse, &empty_reason, &profile),
            "an empty stopReason string is still the terminal frame"
        );
    }

    #[cfg(feature = "proxy")]
    #[test]
    fn event_has_slot_messages_content_block_start_is_not_responses() {
        let ev = IrStreamEvent::Protocol {
            item_type: "content_block_start".into(),
            payload: serde_json::json!({
                "type": "content_block_start",
                "index": 0,
                "content_block": { "type": "text", "text": "" }
            }),
        };
        assert!(event_has_slot(Wire::Messages, &ev));
        assert!(
            !event_has_slot(Wire::Responses, &ev),
            "Messages lifecycle frames must not become Responses output items"
        );
    }

    #[cfg(feature = "proxy")]
    #[test]
    fn event_has_slot_keeps_converse_document_frame() {
        let ev = IrStreamEvent::Protocol {
            item_type: "converse_frame".into(),
            payload: serde_json::json!({ "contentBlockDelta": {} }),
        };
        assert!(event_has_slot(Wire::Converse, &ev));
        assert!(!event_has_slot(Wire::ChatCompletions, &ev));
        let citation = IrStreamEvent::Protocol {
            item_type: "converse_citation".into(),
            payload: serde_json::json!({ "location": { "documentChar": { "documentIndex": 0 } } }),
        };
        assert!(event_has_slot(Wire::Converse, &citation));
        assert!(!event_has_slot(Wire::Messages, &citation));
    }

    #[test]
    fn check_index_rejects_non_integer_without_saying_over_cap() {
        let err = check_index(
            &serde_json::json!({"index": "nope"}),
            "index",
            4,
            "tool call",
        )
        .expect_err("string index");
        let msg = err.to_string();
        assert!(msg.contains("must be an unsigned integer"), "{msg}");
        assert!(!msg.contains("exceeds cap"), "{msg}");

        let err = check_index(&serde_json::json!({"index": 99}), "index", 4, "tool call")
            .expect_err("index over cap");
        assert!(err.to_string().contains("exceeds cap"), "{err}");
    }

    #[test]
    fn messages_document_citation_is_not_dropped() {
        let profile = wiremux_auth::parse_profile_str(
            r#"
schema_version = 1
id = "t"
wire = "messages"
base_url = "http://127.0.0.1"
"#,
        )
        .expect("profile");
        let data = r#"{"type":"content_block_delta","index":0,"delta":{"type":"citations_delta","citation":{"type":"char_location","cited_text":"The grass is green.","document_index":0,"document_title":"My Document","start_char_index":0,"end_char_index":20}}}"#;
        let events = decode_stream_events(
            Wire::Messages,
            &frame(Some("content_block_delta"), data),
            &profile,
        )
        .expect("char_location");
        assert!(
            events.iter().any(|ev| match ev {
                IrStreamEvent::Protocol { payload, .. } =>
                    payload.to_string().contains("The grass is green."),
                IrStreamEvent::AnnotationAdded { annotation } => {
                    annotation.to_string().contains("The grass is green.")
                        && !annotation
                            .to_string()
                            .contains("web_search_result_location")
                }
                _ => false,
            }),
            "document citation must be kept, got {events:?}"
        );
    }
}