openlatch-client 0.5.2

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
//! The wire-format registry — the one place a provider protocol is named.
//!
//! The model relay forwards for more than one agent, and the agents do not share a
//! protocol: Claude Code speaks the Anthropic Messages API, Codex speaks the
//! OpenAI Responses API. Everything that differs between them — the upstream to
//! forward to, the provider name on the economics event, whether a decoder
//! exists, whether a transform may run, how a request names its own session,
//! where its user turns and tool results sit — is answered *here*, by the
//! format, so that shared decision code in [`super::proxy`] never has to name
//! one.
//!
//! **The format is resolved from the request ROUTE, never from agent identity**
//! (PRD D-7). A multi-provider agent picks its protocol from its own
//! configuration at session time, so no fixed agent→protocol mapping exists to
//! key on. [`WireFormat::resolve`] reads method + path off the request head
//! *before* the body is touched, which is why the registry costs no new parse
//! and cannot move TTFT.
//!
//! ## `Unknown` is the normal answer, not an error
//!
//! Every route the model relay does not capture — `GET /v1/models`,
//! `POST /v1/messages/count_tokens`, the batch endpoints — resolves to
//! [`WireFormat::Unknown`] and is forwarded opaquely, exactly as before this
//! registry existed: no permit, no materialization, and **no economics event**.
//! `Unknown` therefore answers `ANTHROPIC_BASE` for [`WireFormat::default_upstream`]:
//! that is today's forwarding target for those routes, and making it fail would
//! turn an opaque forward into a synthetic 502.
//!
//! One base for every uncaptured route was right while one agent was wired
//! here, and stopped being right when Codex arrived: `GET /v1/models` is
//! uncaptured, Codex issues it every session, and Anthropic is the wrong place
//! to send it. [`WireFormat::resolve_upstream`] is the narrow answer — it moves
//! an uncaptured route to the OpenAI side ONLY on a marker Claude Code never
//! sends, and leaves what it captures untouched.
//!
//! ## Auth mode is not a wire format
//!
//! Codex authenticates two ways — a ChatGPT subscription and a platform API
//! key — and both speak the Responses API on the same route. Same format, two
//! origins, and the credential valid at one is refused by the other. That
//! distinction lives in [`AuthMode`], resolved per request from the agent's own
//! headers, precisely so it never becomes a third [`WireFormat`] variant.

use axum::http::{request::Parts, HeaderMap, Method};

/// The OpenAI first-party base URL, the built-in upstream for
/// [`WireFormat::OpenAiResponses`].
///
/// A HOST, not a path — `Url::join` replaces the base's path with the incoming
/// absolute path, so a `/v1` suffix here would be discarded rather than
/// prefixed. See [`WireFormat::default_upstream`].
pub const OPENAI_BASE: &str = "https://api.openai.com";

/// The Gemini API base URL, the built-in upstream for
/// [`WireFormat::GoogleGenerateContent`].
///
/// A HOST, not a path — `Url::join` replaces the base's path with the incoming
/// absolute path, so a `/v1beta` suffix here would be discarded rather than
/// prefixed, and every route would silently break. See
/// [`WireFormat::default_upstream`].
///
/// Vertex AI speaks the same format on a DIFFERENT, region-prefixed host
/// (`aiplatform.googleapis.com`), which is why this is a **default** upstream
/// and not a claim about where a given install's traffic goes: a customer on
/// Vertex overrides it through `[model_relay.upstream]`, the mechanism that
/// exists for exactly this.
pub const GOOGLE_BASE: &str = "https://generativelanguage.googleapis.com";

/// Ollama's own default, and the only built-in upstream here that is LOCAL.
///
/// A local model server has no cloud origin to fall back to, which is the whole
/// reason this format needs its own entry: before it existed, Ollama's native
/// routes fell to [`WireFormat::Unknown`], whose upstream is Anthropic's — so a
/// Cline user on Ollama had their prompt bodies forwarded to `api.anthropic.com`
/// and got a 404 back. The learned upstream (`upstream:ollama-native`) replaces
/// this whenever the wiring pass has seen where the customer's server actually
/// is; this is what a host that has not been wired yet still answers.
pub const OLLAMA_BASE: &str = "http://127.0.0.1:11434";

/// The backend Codex speaks to on a **ChatGPT subscription**, and the built-in
/// upstream for [`WireFormat::OpenAiResponses`] when the request's own
/// credential names it.
///
/// A host **plus a path**, unlike the other two bases, and that is the point:
/// the subscription endpoint lives under `/backend-api/codex`. See
/// `proxy::join_upstream` for how a based upstream survives the forward — a
/// plain `Url::join` drops the prefix and posts to `chatgpt.com/v1/responses`,
/// which does not exist.
pub const CHATGPT_BASE: &str = "https://chatgpt.com/backend-api/codex";

/// The header Codex sends on every request made with a ChatGPT-subscription
/// credential, naming the account the plan belongs to.
const CHATGPT_ACCOUNT_HEADER: &str = "chatgpt-account-id";

/// Codex's own product tag, sent on every request it makes.
const ORIGINATOR_HEADER: &str = "originator";

/// What [`ORIGINATOR_HEADER`] starts with on every Codex surface —
/// `codex_exec`, `codex_cli_rs`, `codex_vscode`, `codex-tui`.
const CODEX_ORIGINATOR_PREFIX: &str = "codex";

/// Which OpenAI backend a request's own credential is addressed to.
///
/// **Not a wire format.** Codex authenticates two ways and both speak the
/// Responses API — same route, same body, same SSE frames. It is one format at
/// two origins, so it is not a third [`WireFormat`] variant and must not
/// become one. A ChatGPT-plan token carries `api.connectors.*` scopes only and
/// `api.openai.com` answers it with a 403; a platform key is not what the
/// ChatGPT backend accepts. One header separates them, and the agent sends it
/// unprompted.
///
/// Read from the request head, never from agent identity and never from
/// anything this install decided at wiring time: a developer can `codex login`
/// between two turns and change modes without restarting anything we own, so a
/// value resolved once would be stale by the next request.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthMode {
    /// The request carries [`CHATGPT_ACCOUNT_HEADER`] — a subscription
    /// credential, valid only against [`CHATGPT_BASE`].
    ChatGptSubscription,
    /// Everything else: a platform API key, an Anthropic credential, or no
    /// credential at all. The default, and today's behaviour.
    Platform,
}

impl AuthMode {
    /// Resolved from the request's headers — one `contains_key` on the hot
    /// path, before the body is touched.
    pub fn resolve(headers: &HeaderMap) -> Self {
        if headers.contains_key(CHATGPT_ACCOUNT_HEADER) {
            Self::ChatGptSubscription
        } else {
            Self::Platform
        }
    }
}

/// True when the request carries a marker only Codex sends.
///
/// [`CHATGPT_ACCOUNT_HEADER`] names the ChatGPT backend outright.
/// [`ORIGINATOR_HEADER`] is Codex's product tag and rides on every request it
/// makes — the captured `POST /v1/responses` and the uncaptured
/// `GET /v1/models` alike.
///
/// Deliberately **not** the credential's shape. Claude Code on a subscription
/// sends `Authorization: Bearer …` exactly as Codex on a platform key does, so
/// keying on "carries a bearer token" would send Claude's own uncaptured
/// routes to OpenAI — the same cross-provider misroute this exists to fix,
/// pointed the other way.
/// The Ollama native route `path` ends in, or `None`.
///
/// Suffix-matched, not exact, for the reason the `/chat/completions` arm is:
/// a customer may sit their model server behind a path prefix
/// (`https://box.internal/ollama/api/chat`), and an exact match would drop
/// every one of those to `Unknown`.
///
/// `/chat/completions` is excluded FIRST. Ollama serves an OpenAI-compatible
/// surface as well as this one, and a gateway can legitimately publish it under
/// `/api/...` — that route has a decoder and must keep it.
fn ollama_native_route(path: &str) -> Option<&'static str> {
    let path = path
        .strip_suffix('/')
        .filter(|p| !p.is_empty())
        .unwrap_or(path);
    if path.ends_with("/chat/completions") {
        return None;
    }
    const NATIVE: &[&str] = &[
        "/api/chat",
        "/api/generate",
        "/api/embed",
        "/api/embeddings",
        "/api/tags",
        "/api/show",
        "/api/ps",
        "/api/version",
    ];
    NATIVE.iter().copied().find(|r| path.ends_with(r))
}

/// The native routes that are a model call — the only two whose response
/// carries a turn's token counts.
///
/// Every other native route (listing models, showing one, embeddings) reaches
/// the model server through [`WireFormat::resolve_upstream`] but is never
/// captured, exactly as `GET /v1/models` and `/v1/embeddings` are not on the
/// other surfaces. Capturing them emitted an economics event per model listing:
/// a turn that never happened, counted as one.
const OLLAMA_NATIVE_TURNS: &[&str] = &["/api/chat", "/api/generate"];

fn is_codex_request(headers: &HeaderMap) -> bool {
    headers.contains_key(CHATGPT_ACCOUNT_HEADER)
        || headers
            .get(ORIGINATOR_HEADER)
            .and_then(|v| v.to_str().ok())
            .is_some_and(|v| v.starts_with(CODEX_ORIGINATOR_PREFIX))
}

/// Longest session id we will believe. Claude Code's is a 36-char UUID; the cap
/// is generous headroom that still refuses to turn an arbitrary blob into a
/// session label.
const MAX_DECLARED_SESSION_ID: usize = 128;

/// The provider protocol a request speaks, resolved from its route.
///
/// `#[non_exhaustive]`: PRD D-8 names four formats (`anthropic-messages`,
/// `openai-chat-completions`, `openai-responses`, `google-generate-content`)
/// and this unit builds two. The attribute is a downstream-semver affordance
/// only; every intra-crate `match` still breaks usefully when the third lands.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WireFormat {
    /// Anthropic Messages API — `POST /v1/messages`. Claude Code.
    AnthropicMessages,
    /// OpenAI Responses API — `POST /v1/responses`. Codex CLI.
    OpenAiResponses,
    /// OpenAI Chat Completions API — `POST /v1/chat/completions`. The route a
    /// GUI-hosted agent points at an OpenAI-compatible endpoint speaks, which
    /// is very often not OpenAI's own: see [`WireFormat::provider`].
    OpenAiChatCompletions,
    /// Google Generative Language — `POST …:generateContent` and its streaming
    /// sibling, on the Gemini API and on Vertex AI alike.
    GoogleGenerateContent,
    /// Ollama's native API — `POST /api/chat` and `/api/generate`. The rest of
    /// that surface (`GET /api/tags`, `/api/show`, embeddings) is uncaptured
    /// and follows this format's upstream through
    /// [`resolve_upstream`](Self::resolve_upstream).
    ///
    /// NOT OpenAI-compatible: Ollama serves both, and Cline's Ollama provider
    /// dials the native one. Without this variant every one of those routes
    /// resolved to [`Self::Unknown`] and left for Anthropic.
    OllamaNative,
    /// Every route we do not capture. Forwarded opaquely, never measured.
    Unknown,
}

impl WireFormat {
    /// Every variant, in one place.
    ///
    /// Independent sites must walk the full set — the daemon building the
    /// resolved upstream map, `ModelRelayState`'s fan-out of a single URL across
    /// every key, and `model-relay status` rendering the object. Three
    /// hand-written lists on a `#[non_exhaustive]` enum is how they drift; this
    /// is the one list.
    pub const ALL: [WireFormat; 6] = [
        Self::AnthropicMessages,
        Self::OpenAiResponses,
        Self::OpenAiChatCompletions,
        Self::GoogleGenerateContent,
        Self::OllamaNative,
        Self::Unknown,
    ];

    /// Resolved from the request ROUTE. NEVER from agent identity (PRD D-7).
    ///
    /// This reads `parts` only — method and path — and is called BEFORE the
    /// body is touched, which is why the registry costs no new parse and cannot
    /// move TTFT. It is also the only key that stays correct: a multi-provider
    /// agent resolves its format from its own configuration at session time, so
    /// no fixed agent→protocol mapping exists to key on.
    pub fn resolve(parts: &Parts) -> Self {
        if parts.method != Method::POST {
            return Self::Unknown;
        }
        // Ollama's native TURNS only. The rest of that surface is uncaptured
        // and reaches the model server through `resolve_upstream`.
        if ollama_native_route(parts.uri.path()).is_some_and(|r| OLLAMA_NATIVE_TURNS.contains(&r)) {
            return Self::OllamaNative;
        }
        // One trailing slash is stripped before matching. Servers commonly
        // tolerate it and clients commonly send it, and the cost of treating
        // `/v1/messages/` as a different route from `/v1/messages` is not a 404
        // — it is `Unknown`, whose upstream is Anthropic's.
        let path = parts.uri.path();
        let path = path
            .strip_suffix('/')
            .filter(|p| !p.is_empty())
            .unwrap_or(path);
        match path {
            "/v1/messages" => Self::AnthropicMessages,
            "/v1/responses" => Self::OpenAiResponses,
            _ if path.ends_with("/chat/completions") => Self::OpenAiChatCompletions,
            _ => {
                // WIDENED FROM AN EXACT STRING 2026-09-14, after review.
                //
                // The arm above matches any path ENDING in `/chat/completions`,
                // not the single literal `/v1/chat/completions`. The exact form
                // was chosen so that the writer's `/v1` base URL would compose
                // to it — which is true, and which only ever governed the paths
                // WE write. Everything else fell to `Unknown`:
                //
                //   /v1/chat/completions/                  a tolerated trailing slash
                //   /chat/completions                      a base URL with no version segment
                //   /gateway/openai/v1/chat/completions    a corporate path-prefixed gateway
                //   /openai/deployments/{d}/chat/completions   Azure OpenAI
                //
                // `Unknown`'s upstream is Anthropic's, so each of those shipped
                // the caller's own credential to a different vendor. The two
                // failure modes are not symmetric: over-matching captures a turn
                // we need not have captured, while under-matching leaks a key.
                //
                // Query strings need no handling — `Uri::path()` excludes them.
                //
                // Google is the one format whose route carries the model, so it
                // cannot be matched exactly. It is matched on the METHOD SUFFIX,
                // which is what covers both surfaces without this host having to
                // know which one the customer is on:
                //   gemini: /v1beta/models/{model}:generateContent
                //   vertex: /v1/projects/{p}/locations/{l}/publishers/google/…:streamGenerateContent
                //
                // BOTH suffixes, deliberately: ":streamGenerateContent" does NOT
                // end with ":generateContent", so testing one of them would
                // resolve every streaming turn — which is every interactive turn
                // an agent makes — to `Unknown`, and forward it to Anthropic
                // bearing the caller's Google credential.
                if path.ends_with(":generateContent") || path.ends_with(":streamGenerateContent") {
                    Self::GoogleGenerateContent
                } else {
                    Self::Unknown
                }
            }
        }
    }

    /// The format whose UPSTREAM this request follows.
    ///
    /// [`resolve`](Self::resolve) answers what a request *speaks*, and that is
    /// the only thing capture, measurement and the envelope may key on. This
    /// answers the narrower question of where it must be **sent**, and differs
    /// for two cases: an uncaptured route on Ollama's native surface, and an
    /// uncaptured route that is provably Codex's.
    ///
    /// Ollama's is proved by the route itself. A client lists its models with
    /// `GET /api/tags` before it sends anything, and as `Unknown` that request
    /// left for Anthropic and came back a 404 with an Anthropic-shaped body. The
    /// asymmetry that widened the `/chat/completions` arm governs here too:
    /// over-matching sends a request to a LOCAL model server, where it fails in
    /// the customer's own process; under-matching sends their bytes to a
    /// third-party vendor.
    ///
    /// `Unknown`'s built-in upstream is Anthropic's. That was right while
    /// Claude Code was the only agent wired here and became wrong the moment
    /// Codex was — `GET /v1/models` is uncaptured and Codex issues it every
    /// session, so today every Codex install sends it, bearing the caller's
    /// OpenAI credential, to `api.anthropic.com`. That is not a graceful
    /// degradation; it is a cross-provider misroute.
    ///
    /// Promotion needs a marker only Codex sends ([`is_codex_request`]), which
    /// Claude Code emits under neither of its own auth modes. Anything else
    /// keeps today's answer exactly, so a route we cannot attribute still
    /// forwards opaquely instead of becoming a synthetic 502.
    ///
    /// **This never widens what is captured.** A promoted route resolves
    /// `Unknown` from [`resolve`](Self::resolve) still, so it takes no permit,
    /// materializes nothing and emits no economics event.
    pub fn resolve_upstream(parts: &Parts) -> Self {
        match Self::resolve(parts) {
            Self::Unknown if ollama_native_route(parts.uri.path()).is_some() => Self::OllamaNative,
            Self::Unknown if is_codex_request(&parts.headers) => Self::OpenAiResponses,
            resolved => resolved,
        }
    }

    /// What a request speaks when it arrived on a relay endpoint whose provider
    /// speaks `family`.
    ///
    /// The route still decides whenever it can: this changes the answer only
    /// for a route [`resolve`](Self::resolve) calls `Unknown`. A customer's
    /// gateway puts its own prefix in front of the provider's path —
    /// `https://gw.corp/anthropic` makes the agent POST
    /// `/anthropic/v1/messages` — and the exact matches that keep the main
    /// port from over-capturing then miss a turn the endpoint provably carries.
    ///
    /// **A hint, not an override.** The family is taken only for a POST whose
    /// path ENDS in that family's turn route, so a model listing, a token count
    /// or an embedding behind the same prefix stays uncaptured; counting those
    /// as turns is the defect `OLLAMA_NATIVE_TURNS` was written to remove. The
    /// endpoint knows the family because the slot it replaced belongs to one
    /// provider — a fact about OUR configuration, never an agent→protocol table
    /// (PRD D-7).
    pub fn resolve_with_family(parts: &Parts, family: Option<Self>) -> Self {
        match (Self::resolve(parts), family) {
            (Self::Unknown, Some(family))
                if parts.method == Method::POST && family.is_turn_route(parts.uri.path()) =>
            {
                family
            }
            (resolved, _) => resolved,
        }
    }

    /// Whether `path` ends in this format's turn route, whatever prefix sits in
    /// front of it.
    fn is_turn_route(self, path: &str) -> bool {
        let path = path
            .strip_suffix('/')
            .filter(|p| !p.is_empty())
            .unwrap_or(path);
        match self {
            Self::AnthropicMessages => path.ends_with("/messages"),
            Self::OpenAiResponses => path.ends_with("/responses"),
            Self::OpenAiChatCompletions => path.ends_with("/chat/completions"),
            Self::GoogleGenerateContent => {
                path.ends_with(":generateContent") || path.ends_with(":streamGenerateContent")
            }
            Self::OllamaNative => OLLAMA_NATIVE_TURNS.iter().any(|r| path.ends_with(r)),
            Self::Unknown => false,
        }
    }

    /// True when this format is one we capture.
    ///
    /// Written out rather than `!matches!(self, Self::Unknown)`: the negated
    /// form answers `true` for every variant that does not exist yet, so a new
    /// format would be captured — permit taken, body materialized, economics
    /// event emitted — without anyone deciding it should be. Spelled as a
    /// `match`, a new variant is a compile error here and the answer is a
    /// choice someone made.
    pub fn is_captured(self) -> bool {
        match self {
            Self::AnthropicMessages => true,
            Self::OpenAiResponses => true,
            Self::OpenAiChatCompletions => true,
            Self::GoogleGenerateContent => true,
            Self::OllamaNative => true,
            Self::Unknown => false,
        }
    }

    /// The `wireformat` envelope attribute value, and the map key in
    /// `[model_relay.upstream]`. Hyphenated, matching PRD D-8's names verbatim.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::AnthropicMessages => "anthropic-messages",
            Self::OpenAiResponses => "openai-responses",
            Self::OpenAiChatCompletions => "openai-chat-completions",
            Self::GoogleGenerateContent => "google-generate-content",
            Self::OllamaNative => "ollama-native",
            Self::Unknown => "unknown",
        }
    }

    /// `gen_ai.provider.name`. Resolved from the FORMAT, not the upstream host:
    /// a customer pointing us at a corporate gateway is still speaking the
    /// provider's protocol, and reporting the gateway's hostname as the
    /// provider would be junk.
    /// The two answers are asymmetric ON PURPOSE. `/v1/chat/completions` is a
    /// protocol, not a vendor: the same route is served by OpenAI, by every
    /// gateway that emulates it, and by a self-hosted Qwen on a developer's own
    /// box. Answering `"openai"` there would put a vendor's name on traffic
    /// that never reached them — a claim about the customer's spend that is
    /// simply false. `"openai-compatible"` says what the route proves.
    /// `…:generateContent` carries no such ambiguity: the method shape is
    /// Google's own, so `"google"` is a fact.
    pub fn provider(self) -> &'static str {
        match self {
            Self::AnthropicMessages => "anthropic",
            Self::OpenAiResponses => "openai",
            Self::OpenAiChatCompletions => "openai-compatible",
            Self::GoogleGenerateContent => "google",
            Self::OllamaNative => "ollama",
            Self::Unknown => "unknown",
        }
    }

    /// The built-in upstream when `[model_relay.upstream]` names none for this
    /// format. HOSTS, NOT PATHS — `Url::join` replaces the base's path.
    ///
    /// `Unknown` deliberately answers [`super::ANTHROPIC_BASE`]: that is the
    /// single base every unrecognised route is forwarded to today, and an
    /// unroutable `Unknown` would turn an opaque forward into a 502.
    pub fn default_upstream(self) -> &'static str {
        match self {
            Self::AnthropicMessages => super::ANTHROPIC_BASE,
            Self::OpenAiResponses => OPENAI_BASE,
            Self::OpenAiChatCompletions => OPENAI_BASE,
            Self::GoogleGenerateContent => GOOGLE_BASE,
            Self::OllamaNative => OLLAMA_BASE,
            Self::Unknown => super::ANTHROPIC_BASE,
        }
    }

    /// True when this build can decode the format's response stream into token
    /// counts.
    ///
    /// A route can be *recognised* without being *decodable*. Measurement asks
    /// this rather than asking the route, so a captured but undecoded turn
    /// would report `unknown_wire_format` — the honest gap — instead of
    /// `stream_interrupted`, which describes the wrong failure.
    ///
    /// **Not every captured format is decoded**, and the gap between the two
    /// lists is the point of the predicate rather than a defect in it. Each
    /// format named below gained its decoder in the same commit that added it
    /// here: shipping a decoder without the arm labels every correct
    /// measurement `unknown_wire_format` — a measurement that happened,
    /// reported as one that did not — and shipping the arm without a decoder
    /// claims a measurement that never ran. A captured format whose decoder has
    /// not landed answers `false`, reports the honest gap, and still routes its
    /// credential to the right upstream; that is exactly what
    /// route-before-decoder buys.
    pub fn has_decoder(self) -> bool {
        matches!(
            self,
            Self::AnthropicMessages
                | Self::OpenAiResponses
                | Self::OpenAiChatCompletions
                | Self::GoogleGenerateContent
                | Self::OllamaNative
        )
    }

    /// True when the request-transform step may run for this format.
    ///
    /// The bundle's request rules are Anthropic-authored and read an Anthropic
    /// body shape, so they must not be evaluated against another provider's
    /// request. `[model_relay] transforms_act = true` already exists in the field,
    /// so default-off is not sufficient protection — the gate is on the format.
    ///
    /// The predicate lives here, with the format, so shared proxy code never
    /// names a format to decide with: adding a third format must not mean
    /// editing shared decision code.
    pub fn transforms_apply(self) -> bool {
        matches!(self, Self::AnthropicMessages)
    }
}

/// The session id the request declares about itself, or `None`.
///
/// Per format, because naming your own session inside the request body is an
/// agent's own convention and not a property of HTTP:
///
/// - **`AnthropicMessages`** — Claude Code sets the Messages API's
///   `metadata.user_id` to a JSON **string** holding `device_id`,
///   `account_uuid` and `session_id`, and that `session_id` is byte-for-byte
///   the one the hook reports as its subject. Reading it turns attribution from
///   an inference into a fact.
/// - **`OpenAiResponses`** — Codex sets `client_metadata.session_id` to a plain
///   string, and that string is byte-for-byte the id the hook reports as its
///   subject. This arm read `None` until the value was checked rather than
///   assumed: a real turn captured off codex-cli 0.150.1 on 2026-09-06 carried
///   the same id in four places — the `session-id` header, `thread-id`,
///   `client_metadata.session_id` and `prompt_cache_key` — all equal to the
///   `session_meta.session_id` that session wrote to its own rollout, which is
///   the same `Session::session_id()` the hook payload carries. `session_id` is
///   the one of the four named for what it *is*: `prompt_cache_key` is named
///   for the cache and is free to become a prefix digest, and the headers are
///   unreachable from a body-only signature.
/// - **`Unknown`** — `None`; an uncaptured route never reaches a parsed body.
///
/// **Deliberately total and silent.** The field is an agent's internal
/// convention, not a documented contract: it can change shape, drop the key, or
/// hold a plain opaque id for a different agent. Every one of those returns
/// `None` and the cascade carries on exactly as it did — the selector can stop
/// working without anything breaking, which is the only safe way to depend on
/// someone else's undocumented format.
///
/// We read `session_id` and nothing else. Both blobs carry more — Claude Code's
/// `account_uuid` and `device_id`, Codex's `installation_id`, `thread_id` and
/// `turn_id`; those are the caller's identity or a narrower scope than a
/// session, we have no use for either, and not extracting them is cheaper to
/// reason about than extracting and discarding them.
pub fn declared_session_id(fmt: WireFormat, body: &serde_json::Value) -> Option<String> {
    match fmt {
        WireFormat::OllamaNative => None,
        WireFormat::AnthropicMessages => anthropic_declared_session_id(body),
        WireFormat::OpenAiResponses => codex_declared_session_id(body),
        // Chat completions declares no session. It has no field for one, and
        // the nearest candidate is NOT a substitute: `user` is a
        // caller-supplied opaque string whose documented purpose is abuse
        // monitoring, so reading it would attribute every turn to whatever the
        // customer happens to put there — one label for a whole install, or a
        // label naming a human rather than a session. `None` is therefore
        // DELIBERATE here and no longer a placeholder;
        // `chat_completions_declares_no_session_id` is what records the
        // difference, so a later reader does not "fix" it.
        WireFormat::OpenAiChatCompletions => None,
        // generate-content declares no session, in EITHER lane. The Gemini
        // request body is `{contents, systemInstruction, tools,
        // generationConfig, safetySettings, cachedContent}` and the Vertex body
        // adds only `labels` — a deployment-wide key/value map, not a
        // per-session id — so there is no field to read and no near-miss to be
        // tempted by. `None` here is DELIBERATE and no longer a placeholder;
        // `google_declares_no_session_id` is what records the difference so a
        // later reader does not "fix" it, and attribution falls to a lower rung
        // exactly as it does for a Claude Code body that omits the field.
        WireFormat::GoogleGenerateContent => None,
        WireFormat::Unknown => None,
    }
}

/// Accept an id only if it can be a session label without qualification.
///
/// Shared by both arms so one format cannot end up with a laxer rule than the
/// other: a session id becomes a label in the economics record and a key in the
/// registry, and neither wants a blank, an unbounded caller-controlled string,
/// or something carrying control characters.
fn usable_session_id(sid: &str) -> Option<String> {
    let sid = sid.trim();
    if sid.is_empty() || sid.len() > MAX_DECLARED_SESSION_ID {
        return None;
    }
    if sid.chars().any(char::is_control) {
        return None;
    }
    Some(sid.to_string())
}

/// The Messages-API convention, moved verbatim from `proxy.rs`.
fn anthropic_declared_session_id(body: &serde_json::Value) -> Option<String> {
    let raw = body.get("metadata")?.get("user_id")?.as_str()?;
    // Bound the parse: `user_id` is caller-controlled, and a megabyte of JSON
    // here would be work done on every request for no benefit.
    if raw.len() > 4096 {
        return None;
    }
    let parsed: serde_json::Value = serde_json::from_str(raw).ok()?;
    usable_session_id(parsed.get("session_id")?.as_str()?)
}

/// The Responses convention.
///
/// A plain nested string, not JSON inside a string, so there is no inner parse
/// to bound — the outer body parse already happened and `as_str` cannot cost
/// more than the field is long.
fn codex_declared_session_id(body: &serde_json::Value) -> Option<String> {
    usable_session_id(body.get("client_metadata")?.get("session_id")?.as_str()?)
}

/// The conversation-shaped parts of a request body the attribution cascade reads.
///
/// The cascade's two content selectors ask the same two questions of every
/// request — *which user turns is this* and *which tool results is it carrying
/// back* — and no two formats answer them in the same shape. The Messages API
/// keeps its turns under `messages` and nests each `tool_result` inside the user
/// turn that answers it; the Responses API keeps its items under `input` and
/// lists every tool output as a **top-level item of its own**;
/// chat-completions keeps the Messages API's `messages` but makes each result a
/// top-level `role: "tool"` message; generate-content shares NOTHING with any of
/// them — `contents`, `parts`, an untyped text block, and a nested
/// `functionResponse`. Naming those differences here is what keeps
/// [`super::proxy`]'s signal derivation free of them: the shared code hashes,
/// dedupes and bounds, and the format supplies the shape.
///
/// **A new format that answers with a shape no field here can express is a
/// signal to grow this struct, never to return a view that reads as empty.** A
/// selector that never fires degrades to the fallback instead of failing, so a
/// half-expressed shape loses the whole signal in silence — which is why
/// [`Self::content_field`] and the `Option` on [`Self::text_block_type`] exist
/// at all.
pub struct ConversationView<'a> {
    /// The user turns, oldest first. Each is read through [`Self::content_field`],
    /// which holds either a bare string or an array of blocks.
    pub user_turns: Vec<&'a serde_json::Value>,
    /// The field a turn keeps its content under: `content` on the Messages API,
    /// the Responses API and chat-completions; **`parts`** on
    /// generate-content, which shares none of the other three's vocabulary.
    pub content_field: &'static str,
    /// The `type` a text block carries inside the content array — `"text"` on
    /// the Messages API and chat-completions, `"input_text"` on the Responses
    /// API — or `None` when the format's blocks carry no discriminator at all.
    ///
    /// `None` is generate-content's answer and is not laziness: a Gemini `Part`
    /// is a oneof (`text` | `inlineData` | `functionCall` | `functionResponse` |
    /// …) with no `type` key, so a block is a text block exactly when it has a
    /// `text` member. Spelling that as `Some("text")` would match nothing and
    /// yield an empty hash list on every request — a selector that never fires
    /// degrades to the fallback instead of failing, so the whole loss would be
    /// silent.
    pub text_block_type: Option<&'static str>,
    /// The tool-call ids this request is carrying back, newest first.
    pub tool_result_ids: Vec<String>,
}

/// Read a request body into the shared [`ConversationView`], or `None` when this
/// format has no conversation to read.
///
/// Per format, for the same reason [`declared_session_id`] is: the shapes below
/// are each one agent's protocol, and a body that does not match the shape its
/// route promised returns `None` rather than half a view.
pub fn conversation_view(
    fmt: WireFormat,
    body: &serde_json::Value,
) -> Option<ConversationView<'_>> {
    match fmt {
        WireFormat::AnthropicMessages => anthropic_conversation_view(body),
        WireFormat::OpenAiResponses => responses_conversation_view(body),
        WireFormat::OpenAiChatCompletions => chat_completions_conversation_view(body),
        WireFormat::GoogleGenerateContent => google_conversation_view(body),
        // Routed, but with no decoder yet — see `is_captured`.
        WireFormat::OllamaNative => None,
        // An uncaptured route never reaches a parsed body.
        WireFormat::Unknown => None,
    }
}

/// The Messages-API shape, moved verbatim from `proxy.rs`.
fn anthropic_conversation_view(body: &serde_json::Value) -> Option<ConversationView<'_>> {
    let messages = body.get("messages")?.as_array()?;
    let user_turns: Vec<&serde_json::Value> = messages
        .iter()
        .filter(|m| m.get("role").and_then(|r| r.as_str()) == Some("user"))
        .collect();

    // The ids this turn is answering. A `tool_result` block echoes the
    // `tool_use_id` of the call the agent just ran, which is exactly what the
    // hook recorded for the session that ran it. Only the LAST user turn's
    // blocks: an earlier turn's results belong to a turn already answered.
    let mut tool_result_ids = Vec::new();
    if let Some(blocks) = user_turns
        .last()
        .and_then(|last| last.get("content"))
        .and_then(|c| c.as_array())
    {
        for b in blocks {
            if b.get("type").and_then(|t| t.as_str()) != Some("tool_result") {
                continue;
            }
            if let Some(id) = b.get("tool_use_id").and_then(|v| v.as_str()) {
                if !id.is_empty() {
                    tool_result_ids.push(id.to_string());
                }
            }
        }
    }

    Some(ConversationView {
        user_turns,
        content_field: "content",
        text_block_type: Some("text"),
        tool_result_ids,
    })
}

/// The chat-completions shape.
///
/// The turns live under `messages` exactly as they do on the Messages API, and
/// a text block inside `content` is typed `"text"` there too — so the first two
/// members are [`anthropic_conversation_view`]'s, unchanged.
///
/// **The tool-result ids are not.** The Messages API nests a `tool_result`
/// block inside the user turn that answers it; chat-completions makes every
/// result a TOP-LEVEL message of its own — `{"role": "tool", "tool_call_id",
/// "content"}` — which no `role == "user"` filter ever sees. Mirroring the
/// Anthropic helper literally would compile, pass a happy-path test, and return
/// an EMPTY id list on every request: a selector that never fires degrades to
/// the fallback instead of failing, so the whole loss would be silent. The ids
/// are read here the way [`responses_conversation_view`] reads its top-level
/// items instead.
///
/// Keyed on the FIELD, not on `role`, for that helper's reason: `tool_call_id`
/// is what names a call being answered, it appears at the top level of no other
/// message kind (an assistant's own calls nest theirs under `tool_calls[].id`),
/// and a field survives a role-name addition that a name list would not.
///
/// Walked from the END and stopped at the registry's own retention bound, again
/// as the Responses helper is: the registry keeps that many ids per session, so
/// a request's newest ids are the only ones with anything left to match, and a
/// `messages` array carrying a whole conversation's history is not walked past
/// the point of usefulness.
fn chat_completions_conversation_view(body: &serde_json::Value) -> Option<ConversationView<'_>> {
    let messages = body.get("messages")?.as_array()?;
    let user_turns: Vec<&serde_json::Value> = messages
        .iter()
        .filter(|m| m.get("role").and_then(|r| r.as_str()) == Some("user"))
        .collect();

    let mut tool_result_ids: Vec<String> = Vec::new();
    for m in messages.iter().rev() {
        if tool_result_ids.len() >= super::session::RECENT_TOOL_USE_IDS {
            break;
        }
        let Some(id) = m.get("tool_call_id").and_then(|v| v.as_str()) else {
            continue;
        };
        if id.is_empty() || tool_result_ids.iter().any(|k| k == id) {
            continue;
        }
        tool_result_ids.push(id.to_string());
    }

    Some(ConversationView {
        user_turns,
        content_field: "content",
        text_block_type: Some("text"),
        tool_result_ids,
    })
}

/// The Responses-API shape.
///
/// Verified against codex-cli 0.150.1: `codex debug prompt-input <prompt>`
/// renders the typed prompt as its own `message` item, `role: "user"`, carrying a
/// single `input_text` block holding the prompt **verbatim** — byte-for-byte the
/// string the `UserPromptSubmit` hook reports as `prompt`, which is what makes
/// the prompt join an exact match rather than a resemblance.
///
/// The `input` array's bare-string form (`"input": "hello"`) is deliberately not
/// read. It is an API affordance no agent we forward for uses — Codex always
/// serializes the item array — and a branch for a shape we have never seen would
/// be paid on every request to serve a caller that does not exist.
fn responses_conversation_view(body: &serde_json::Value) -> Option<ConversationView<'_>> {
    let items = body.get("input")?.as_array()?;

    // `type` is absent on a plain `{role, content}` item and `"message"` on a
    // typed one; both are turns. The array also carries `developer` items —
    // Codex's instruction preamble — and those are the agent's own text, byte
    // identical across every session it starts, so hashing them would offer a
    // candidate that matches sessions having nothing to do with this request.
    let user_turns: Vec<&serde_json::Value> = items
        .iter()
        .filter(|m| {
            matches!(
                m.get("type").and_then(|t| t.as_str()),
                None | Some("message")
            ) && m.get("role").and_then(|r| r.as_str()) == Some("user")
        })
        .collect();

    // Every Responses item that carries a tool-call id names it `call_id` —
    // `function_call_output`, `custom_tool_call_output`, `mcp_tool_call_output`
    // and `tool_search_output`, plus the `*_call` items each of those answers.
    // Keying on the FIELD rather than on a list of type names is deliberate:
    // Codex has added output variants more than once, and a name list would stop
    // matching the day it adds the next one — silently, since a selector that
    // never fires degrades to the fallback instead of failing.
    //
    // Walked from the END and stopped at the registry's own retention bound. The
    // registry keeps that many ids per session, so a request's newest ids are the
    // only ones with anything left to match, and an `input` carrying a whole
    // conversation's history is not walked past the point of usefulness.
    let mut tool_result_ids: Vec<String> = Vec::new();
    for item in items.iter().rev() {
        if tool_result_ids.len() >= super::session::RECENT_TOOL_USE_IDS {
            break;
        }
        let Some(id) = item.get("call_id").and_then(|v| v.as_str()) else {
            continue;
        };
        // A call and the output answering it repeat one id; two of the eight
        // slots for one tool call would halve what the join can reach.
        if id.is_empty() || tool_result_ids.iter().any(|k| k == id) {
            continue;
        }
        tool_result_ids.push(id.to_string());
    }

    Some(ConversationView {
        user_turns,
        content_field: "content",
        text_block_type: Some("input_text"),
        tool_result_ids,
    })
}

/// The generate-content shape — the one that shares no vocabulary with the
/// other three.
///
/// Every member differs, which is why this is written site by site against
/// Google's `GenerateContentRequest` rather than adapted from a neighbour:
///
/// | | Messages / chat-completions | generate-content |
/// | --- | --- | --- |
/// | turns array | `messages` | **`contents`** |
/// | a turn's content | `content` | **`parts`** |
/// | the model's role | `assistant` | **`model`** |
/// | a text block | `{"type":"text","text":…}` | **`{"text":…}`** — no discriminator |
/// | the system prompt | a `system` role/field | **`systemInstruction`**, top level |
///
/// Only `role == "user"` turns are read, which is the same filter the other
/// three apply. `systemInstruction` is deliberately NOT one of them even though
/// it holds prompt-shaped text: it is the agent's own preamble, byte-identical
/// across every session Cline starts, so hashing it would offer a candidate
/// that matches sessions having nothing to do with this request — the reason
/// the Responses helper skips Codex's `developer` items.
///
/// # The tool-result ids, and why the list is usually empty
///
/// A Gemini tool result is a `functionResponse` PART inside a `user` turn —
/// nested like the Messages API's `tool_result`, not top-level like the other
/// two formats' — and its `id` is **optional**: Google populates it only for
/// parallel calls, matching it to the `functionCall.id` it answers. So this
/// reads the id where there is one and produces an EMPTY list where there is
/// not, which is the honest answer for a body that names no ids. Selector 1
/// then simply does not fire for that request and the cascade falls to selector
/// 2 exactly as it does for a chat-completions body carrying no `tool` message.
///
/// Walked from the END and bounded by the registry's own retention, as both
/// other multi-item helpers are: the registry keeps that many ids per session,
/// so a `contents` array carrying a whole conversation is not walked past the
/// point of usefulness.
fn google_conversation_view(body: &serde_json::Value) -> Option<ConversationView<'_>> {
    let contents = body.get("contents")?.as_array()?;
    let user_turns: Vec<&serde_json::Value> = contents
        .iter()
        .filter(|m| m.get("role").and_then(|r| r.as_str()) == Some("user"))
        .collect();

    let mut tool_result_ids: Vec<String> = Vec::new();
    'outer: for turn in contents.iter().rev() {
        let Some(parts) = turn.get("parts").and_then(|p| p.as_array()) else {
            continue;
        };
        for part in parts.iter().rev() {
            if tool_result_ids.len() >= super::session::RECENT_TOOL_USE_IDS {
                break 'outer;
            }
            let Some(id) = part
                .get("functionResponse")
                .and_then(|f| f.get("id"))
                .and_then(|v| v.as_str())
            else {
                continue;
            };
            if id.is_empty() || tool_result_ids.iter().any(|k| k == id) {
                continue;
            }
            tool_result_ids.push(id.to_string());
        }
    }

    Some(ConversationView {
        user_turns,
        content_field: "parts",
        // Untyped: a Gemini `Part` is a oneof with no `type` key. See the field's
        // own doc — `Some("text")` here would match nothing, silently.
        text_block_type: None,
        tool_result_ids,
    })
}

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

    fn parts_of(method: Method, uri: &str) -> Parts {
        let req = Request::builder()
            .method(method)
            .uri(uri)
            .body(())
            .expect("build request");
        req.into_parts().0
    }

    /// A customer gateway's prefix hides the turn from the exact route match; on
    /// an endpoint that provably serves the family, the turn is still measured.
    #[test]
    fn an_endpoint_family_measures_a_prefixed_turn() {
        let anthropic = Some(WireFormat::AnthropicMessages);
        for uri in [
            "/anthropic/v1/messages",
            "/anthropic/messages",
            "/gw/v1/messages/",
        ] {
            assert_eq!(
                WireFormat::resolve_with_family(&parts_of(Method::POST, uri), anthropic),
                WireFormat::AnthropicMessages,
                "{uri}"
            );
        }
        assert_eq!(
            WireFormat::resolve_with_family(
                &parts_of(Method::POST, "/openai/v1/responses"),
                Some(WireFormat::OpenAiResponses)
            ),
            WireFormat::OpenAiResponses
        );
    }

    /// The hint never turns a listing, a token count or a GET into a turn, and
    /// never overrides what the route itself says.
    #[test]
    fn an_endpoint_family_is_a_hint_not_an_override() {
        let anthropic = Some(WireFormat::AnthropicMessages);
        for (method, uri) in [
            (Method::POST, "/anthropic/v1/messages/count_tokens"),
            (Method::GET, "/anthropic/v1/messages"),
            (Method::GET, "/anthropic/v1/models"),
            (Method::POST, "/anthropic/v1/batches"),
        ] {
            assert_eq!(
                WireFormat::resolve_with_family(&parts_of(method.clone(), uri), anthropic),
                WireFormat::Unknown,
                "{method} {uri}"
            );
        }
        // The route wins over the family when it can decide on its own.
        assert_eq!(
            WireFormat::resolve_with_family(
                &parts_of(Method::POST, "/v1/chat/completions"),
                anthropic
            ),
            WireFormat::OpenAiChatCompletions
        );
        // No family, no hint: the main port's answer, unchanged.
        assert_eq!(
            WireFormat::resolve_with_family(
                &parts_of(Method::POST, "/anthropic/v1/messages"),
                None
            ),
            WireFormat::Unknown
        );
        // Ollama's non-turn routes stay uncaptured behind an Ollama endpoint.
        assert_eq!(
            WireFormat::resolve_with_family(
                &parts_of(Method::POST, "/ollama/api/show"),
                Some(WireFormat::OllamaNative)
            ),
            WireFormat::Unknown
        );
    }

    /// Same, with headers — `(name, value)` pairs applied in order.
    fn parts_with(method: Method, uri: &str, headers: &[(&str, &str)]) -> Parts {
        let mut req = Request::builder().method(method).uri(uri);
        for (k, v) in headers {
            req = req.header(*k, *v);
        }
        req.body(()).expect("build request").into_parts().0
    }

    /// **Ollama's native surface routes to Ollama, not to Anthropic.**
    ///
    /// Cline's Ollama provider speaks this API, not the OpenAI-compatible one.
    /// Every route here used to fall to `Unknown`, whose upstream is
    /// Anthropic's — so a customer's prompt body left for `api.anthropic.com`
    /// and came back a 404.
    #[test]
    fn ollama_native_routes_do_not_leak_to_anthropic() {
        for (method, uri) in [
            (Method::POST, "/api/chat"),
            (Method::POST, "/api/generate"),
            (Method::POST, "/api/embed"),
            (Method::POST, "/api/show"),
            // NON-POST: a client lists models this way before it can send
            // anything.
            (Method::GET, "/api/tags"),
            (Method::GET, "/api/version"),
            // Behind a customer's own path prefix.
            (Method::POST, "/ollama/api/chat"),
            // A tolerated trailing slash.
            (Method::POST, "/api/chat/"),
        ] {
            assert_eq!(
                WireFormat::resolve_upstream(&parts_of(method.clone(), uri)),
                WireFormat::OllamaNative,
                "{method} {uri}"
            );
        }

        assert_eq!(
            WireFormat::OllamaNative.default_upstream(),
            OLLAMA_BASE,
            "a local model server has no cloud origin to fall back to"
        );
        assert_ne!(
            WireFormat::OllamaNative.default_upstream(),
            super::super::ANTHROPIC_BASE,
            "the whole point: this must not be Anthropic's"
        );
    }

    /// **Only a model call is captured.**
    ///
    /// Capturing the whole native surface emitted one economics event per
    /// `GET /api/tags` and `POST /api/show` — found live, where listing models
    /// moved `cloud_forwarded_count` exactly as a turn does. A turn that never
    /// happened, counted as one.
    #[test]
    fn only_ollama_native_turns_are_captured() {
        for (method, uri) in [
            (Method::POST, "/api/chat"),
            (Method::POST, "/api/generate"),
            (Method::POST, "/ollama/api/chat/"),
        ] {
            let parts = parts_of(method.clone(), uri);
            assert_eq!(
                WireFormat::resolve(&parts),
                WireFormat::OllamaNative,
                "{method} {uri}"
            );
            assert!(WireFormat::resolve(&parts).is_captured(), "{method} {uri}");
        }
        for (method, uri) in [
            (Method::GET, "/api/tags"),
            (Method::GET, "/api/version"),
            (Method::GET, "/api/ps"),
            (Method::POST, "/api/show"),
            (Method::POST, "/api/embed"),
            (Method::POST, "/api/embeddings"),
            // The turn route under the wrong method is not a turn either.
            (Method::GET, "/api/chat"),
        ] {
            assert!(
                !WireFormat::resolve(&parts_of(method.clone(), uri)).is_captured(),
                "{method} {uri} is not a model call"
            );
        }
    }

    /// **And it does not steal the OpenAI-compatible surface.**
    ///
    /// Ollama serves both. The chat-completions route has a decoder and a
    /// measured turn; matching it as native would silently stop measuring it.
    #[test]
    fn ollama_native_never_steals_chat_completions() {
        for uri in [
            "/v1/chat/completions",
            // A gateway that publishes the OpenAI surface under /api.
            "/api/v1/chat/completions",
            "/api/chat/completions",
        ] {
            assert_eq!(
                WireFormat::resolve(&parts_of(Method::POST, uri)),
                WireFormat::OpenAiChatCompletions,
                "{uri}"
            );
        }
    }

    #[test]
    fn auth_mode_reads_the_account_header_and_nothing_else() {
        // The measured discriminator: ChatGPT-plan Codex sends this header on
        // every request, a platform key never does.
        assert_eq!(
            AuthMode::resolve(
                &parts_with(
                    Method::POST,
                    "/v1/responses",
                    &[("chatgpt-account-id", "ef1a0c98-317c-4a79-9ed0-9e75361027ed")],
                )
                .headers
            ),
            AuthMode::ChatGptSubscription
        );
        // A bearer credential alone is NOT the signal — Claude Code on a
        // subscription sends one too, and routing on it would send Anthropic
        // traffic to OpenAI.
        assert_eq!(
            AuthMode::resolve(
                &parts_with(
                    Method::POST,
                    "/v1/responses",
                    &[("authorization", "Bearer sk-proj-abc")],
                )
                .headers
            ),
            AuthMode::Platform
        );
        assert_eq!(
            AuthMode::resolve(&parts_of(Method::POST, "/v1/responses").headers),
            AuthMode::Platform
        );
    }

    #[test]
    fn an_uncaptured_codex_route_follows_codex_upstream() {
        // `GET /v1/models` is uncaptured and Codex issues it every session.
        // Before promotion it resolved `Unknown` and left for Anthropic.
        let models = parts_with(
            Method::GET,
            "/v1/models?client_version=0.150.1",
            &[("originator", "codex_exec")],
        );
        assert_eq!(WireFormat::resolve(&models), WireFormat::Unknown);
        assert_eq!(
            WireFormat::resolve_upstream(&models),
            WireFormat::OpenAiResponses
        );

        // The account header promotes on its own.
        let with_account = parts_with(
            Method::GET,
            "/v1/models",
            &[("chatgpt-account-id", "ef1a0c98")],
        );
        assert_eq!(
            WireFormat::resolve_upstream(&with_account),
            WireFormat::OpenAiResponses
        );
    }

    #[test]
    fn an_unmarked_uncaptured_route_still_resolves_unknown() {
        // Claude Code's own uncaptured routes carry neither marker under
        // either of its auth modes, so they keep today's destination.
        for headers in [
            &[][..],
            &[("authorization", "Bearer sk-ant-oat01-abc")][..],
            &[("x-api-key", "sk-ant-api03-abc")][..],
            // An originator that merely CONTAINS the tag is not Codex's.
            &[("originator", "not-codex")][..],
        ] {
            let parts = parts_with(Method::GET, "/v1/models", headers);
            assert_eq!(
                WireFormat::resolve_upstream(&parts),
                WireFormat::Unknown,
                "unmarked route promoted with headers {headers:?}"
            );
        }
    }

    #[test]
    fn promotion_never_widens_what_is_captured() {
        // `resolve_upstream` answers WHERE, never WHAT: a promoted route must
        // still be uncaptured, or it would take a permit and emit an event.
        let promoted = parts_with(Method::GET, "/v1/models", &[("originator", "codex_cli_rs")]);
        assert!(!WireFormat::resolve(&promoted).is_captured());
        // And a captured route is returned untouched by promotion.
        let turn = parts_with(
            Method::POST,
            "/v1/responses",
            &[("originator", "codex_exec")],
        );
        assert_eq!(
            WireFormat::resolve_upstream(&turn),
            WireFormat::resolve(&turn)
        );
    }

    #[test]
    fn resolve_keys_on_route_and_method_only() {
        assert_eq!(
            WireFormat::resolve(&parts_of(Method::POST, "/v1/messages")),
            WireFormat::AnthropicMessages
        );
        assert_eq!(
            WireFormat::resolve(&parts_of(Method::POST, "/v1/responses")),
            WireFormat::OpenAiResponses
        );
        // The method is half the key: a GET on a captured path is not a turn.
        assert_eq!(
            WireFormat::resolve(&parts_of(Method::GET, "/v1/responses")),
            WireFormat::Unknown
        );
        // A prefix of a captured path is a different route, not that route.
        assert_eq!(
            WireFormat::resolve(&parts_of(Method::POST, "/v1/messages/count_tokens")),
            WireFormat::Unknown
        );
        // The shipped routes stay EXACT-STRING now that one arm matches on a
        // suffix: an extension of a captured path is not that path.
        assert_eq!(
            WireFormat::resolve(&parts_of(Method::POST, "/v1/messages/extra")),
            WireFormat::Unknown
        );
        // The method is half the key for the suffix arm too. A GET on a
        // generateContent route is a model listing, not a turn.
        assert_eq!(
            WireFormat::resolve(&parts_of(
                Method::GET,
                "/v1beta/models/gemini-2.5-pro:generateContent"
            )),
            WireFormat::Unknown
        );
    }

    #[test]
    fn all_names_every_variant_exactly_once() {
        // The single list the resolved-upstream map, the state's fan-out and
        // `model-relay status` all walk. A variant missing from it is a silently
        // unrouted format, not a compile error — so the names are pinned.
        let names: Vec<_> = WireFormat::ALL.iter().map(|f| f.as_str()).collect();
        assert_eq!(
            names,
            vec![
                "anthropic-messages",
                "openai-responses",
                "openai-chat-completions",
                "google-generate-content",
                "ollama-native",
                "unknown"
            ]
        );
    }

    #[test]
    fn unknown_forwards_to_the_anthropic_base_as_it_does_today() {
        // Not an improvement target: failing here turns today's opaque forward
        // for `GET /v1/models` into a synthetic 502.
        assert_eq!(
            WireFormat::Unknown.default_upstream(),
            crate::model_relay::ANTHROPIC_BASE
        );
        assert_eq!(WireFormat::OpenAiResponses.default_upstream(), OPENAI_BASE);
        // Chat completions shares OpenAI's host as its DEFAULT — an install
        // pointed at anything else says so in `[model_relay.upstream]`.
        assert_eq!(
            WireFormat::OpenAiChatCompletions.default_upstream(),
            OPENAI_BASE
        );
        // A HOST, not a path: `Url::join` replaces the base's path, so a
        // `/v1beta` here would be discarded and every Google route would break.
        assert_eq!(
            WireFormat::GoogleGenerateContent.default_upstream(),
            GOOGLE_BASE
        );
        assert_eq!(GOOGLE_BASE, "https://generativelanguage.googleapis.com");
    }

    #[test]
    fn chat_completions_resolves_through_every_real_world_path_shape() {
        // Review 2026-09-14 found each of these falling through to `Unknown`,
        // whose upstream is Anthropic's — so each one shipped the caller's own
        // OpenAI-compatible credential to a different vendor. BEA sits behind a
        // corporate HTTP proxy, which makes the gateway row the likely one.
        for path in [
            "/v1/chat/completions",                        // what the writer composes
            "/v1/chat/completions/",                       // a tolerated trailing slash
            "/chat/completions",                           // a base URL with no version
            "/v2/chat/completions",                        // a future or vendor version
            "/gateway/openai/v1/chat/completions",         // path-prefixed gateway
            "/openai/deployments/gpt-4o/chat/completions", // Azure OpenAI
        ] {
            assert_eq!(
                WireFormat::resolve(&parts_of(Method::POST, path)),
                WireFormat::OpenAiChatCompletions,
                "{path} must not fall through to Unknown — its upstream is Anthropic's"
            );
        }
    }

    #[test]
    fn widening_chat_completions_did_not_capture_the_shipped_routes() {
        // The suffix arm sits AFTER the two exact arms, so it must not have
        // stolen them — and a path that merely CONTAINS the segment in the
        // middle is not a chat-completions route.
        assert_eq!(
            WireFormat::resolve(&parts_of(Method::POST, "/v1/messages")),
            WireFormat::AnthropicMessages
        );
        assert_eq!(
            WireFormat::resolve(&parts_of(Method::POST, "/v1/responses")),
            WireFormat::OpenAiResponses
        );
        assert_eq!(
            WireFormat::resolve(&parts_of(Method::POST, "/v1/chat/completions/extra")),
            WireFormat::Unknown,
            "the segment must END the path, not merely appear in it"
        );
        // The trailing-slash strip must not turn "/" into an empty path.
        assert_eq!(
            WireFormat::resolve(&parts_of(Method::POST, "/")),
            WireFormat::Unknown
        );
    }

    #[test]
    fn resolve_matches_chat_completions_exactly() {
        assert_eq!(
            WireFormat::resolve(&parts_of(Method::POST, "/v1/chat/completions")),
            WireFormat::OpenAiChatCompletions
        );
    }

    /// Both Google surfaces, and BOTH method suffixes.
    ///
    /// `":streamGenerateContent"` does NOT end with `":generateContent"`, so a
    /// registry that tested one suffix would resolve every streaming turn —
    /// which is every interactive turn an agent makes — to `Unknown`, and
    /// forward it to Anthropic bearing the caller's Google credential.
    #[test]
    fn resolve_matches_both_google_suffixes() {
        for path in [
            // Gemini API.
            "/v1beta/models/gemini-2.5-pro:generateContent",
            // …and its streaming sibling, with the query string the SDK sends.
            "/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse",
            // Vertex AI: a different host and a much longer path, matched by the
            // same suffix without this host knowing which surface it is on.
            "/v1/projects/p/locations/us-central1/publishers/google/models/\
             gemini-2.5-pro:generateContent",
            "/v1/projects/p/locations/us-central1/publishers/google/models/\
             gemini-2.5-pro:streamGenerateContent",
        ] {
            assert_eq!(
                WireFormat::resolve(&parts_of(Method::POST, path)),
                WireFormat::GoogleGenerateContent,
                "route must resolve to the Google format: {path}"
            );
        }
    }

    #[test]
    fn is_captured_pins_every_arm() {
        // Every variant named, so a new format cannot inherit `true` from a
        // negation and start taking permits nobody granted it.
        assert!(WireFormat::AnthropicMessages.is_captured());
        assert!(WireFormat::OpenAiResponses.is_captured());
        assert!(WireFormat::OpenAiChatCompletions.is_captured());
        assert!(WireFormat::GoogleGenerateContent.is_captured());
        assert!(!WireFormat::Unknown.is_captured());
    }

    /// `/v1/chat/completions` is a PROTOCOL, not a vendor: a self-hosted Qwen,
    /// a corporate gateway and OpenAI itself all serve it. Naming OpenAI there
    /// would put a vendor's name on spend that never reached them.
    ///
    /// Literal equality, not `!=`: a `!= "openai"` assertion passes on any
    /// wrong value, including the empty string.
    #[test]
    fn provider_never_says_openai_for_chat_completions() {
        assert_eq!(
            WireFormat::OpenAiChatCompletions.provider(),
            "openai-compatible"
        );
        // Asymmetric on purpose — the `:generateContent` method shape is
        // Google's own, so there is no ambiguity to hedge.
        assert_eq!(WireFormat::GoogleGenerateContent.provider(), "google");
        // Unchanged for the shipped formats.
        assert_eq!(WireFormat::OpenAiResponses.provider(), "openai");
        assert_eq!(WireFormat::AnthropicMessages.provider(), "anthropic");
    }

    /// The route-before-decoder guarantee: the format is recognised, so the
    /// credential goes to the right upstream, and measurement honestly reports
    /// `unknown_wire_format` instead of inventing a number.
    ///
    /// Split per variant deliberately — one test covering both would go red the
    /// moment EITHER decoder lands, leaving the edit owned by nobody. The plan
    /// that ships the chat-completions decoder flips THIS half.
    ///
    /// **That flip has happened, and the NAME is now history rather than a
    /// claim.** It is kept because the commit that shipped the route gates this
    /// test by name; the assertion below is the current truth, and
    /// `has_decoder_true_for_chat_completions` carries that truth under a name
    /// that does not have to be read twice.
    #[test]
    fn chat_completions_is_captured_and_now_decoded() {
        assert!(WireFormat::OpenAiChatCompletions.is_captured());
        assert!(
            WireFormat::OpenAiChatCompletions.has_decoder(),
            "the decoder landed — see has_decoder_true_for_chat_completions"
        );
    }

    /// The flip, under a name that states what it asserts.
    ///
    /// Asserts NOTHING about any other variant: the plan shipping the next
    /// decoder flips its own arm, and a neighbouring `assert!(!…has_decoder())`
    /// here would turn this test red the day that lands — two plans' tests
    /// destroying each other, with whichever went second taking the blame.
    #[test]
    fn has_decoder_true_for_chat_completions() {
        assert!(WireFormat::OpenAiChatCompletions.has_decoder());
    }

    /// Same guarantee, Google half — and, exactly as its chat-completions
    /// twin above, **the NAME is now history rather than a claim.** The Google
    /// decoder has landed. The test is kept because the commit that shipped the
    /// route gates it by name; the assertion below is the current truth, and
    /// `has_decoder_true_for_google` carries that truth under a name that does
    /// not have to be read twice.
    #[test]
    fn google_is_captured_and_now_decoded() {
        assert!(WireFormat::GoogleGenerateContent.is_captured());
        assert!(
            WireFormat::GoogleGenerateContent.has_decoder(),
            "the decoder landed — see has_decoder_true_for_google"
        );
    }

    /// The flip, under a name that states what it asserts.
    ///
    /// Asserts NOTHING about any other variant, for the reason its
    /// chat-completions twin gives: a neighbouring `assert!(!…has_decoder())`
    /// is a test destroying the next plan's work, with whichever landed second
    /// taking the blame.
    #[test]
    fn has_decoder_true_for_google() {
        assert!(WireFormat::GoogleGenerateContent.has_decoder());
    }

    /// **The stubs are gone, and this test outlived them.**
    ///
    /// It was written for the formats that shipped a route before a decoder,
    /// narrowed to generate-content when the chat-completions decoder landed,
    /// and generate-content was the last one. The name is kept because the
    /// commit that shipped the routes gates it by name — deleting it would turn
    /// that acceptance red for a reason unrelated to what it checks — but what
    /// it asserts is now the INVARIANT the stubs were an instance of, on the one
    /// variant that will always answer it: `None` is this contract's only
    /// failure shape, and an uncaptured route never reaches a parsed body at
    /// all.
    ///
    /// Generate-content's own two answers moved out and up: the view is real
    /// (`google_view_reads_contents_and_parts`) and its `None` session id is now
    /// a decision rather than a placeholder (`google_declares_no_session_id`).
    #[test]
    fn unknown_format_declares_no_session_and_no_view() {
        // Bodies in the shape each captured route actually carries, read under
        // `Unknown` — so the `None` is the arm answering and not a parse that
        // happened to miss.
        let google = serde_json::json!({
            "contents": [{"role": "user", "parts": [{"text": "build the parser"}]}]
        });
        let anthropic = serde_json::json!({
            "messages": [{"role": "user", "content": "build the parser"}],
            "metadata": {"user_id": "{\"session_id\":\"5c7d9833\"}"}
        });

        for body in [&google, &anthropic] {
            assert_eq!(declared_session_id(WireFormat::Unknown, body), None);
            assert!(conversation_view(WireFormat::Unknown, body).is_none());
        }
    }

    /// Generate-content declares no session, and that is a DECISION.
    ///
    /// The Gemini request body is `{contents, systemInstruction, tools,
    /// generationConfig, safetySettings, cachedContent}`; the Vertex body adds
    /// `labels`, a deployment-wide key/value map. There is no session field in
    /// either lane and no near-miss to be tempted by — unlike chat-completions,
    /// whose `user` had to be explicitly refused. Recorded so a later reader
    /// does not "fix" the `None`.
    #[test]
    fn google_declares_no_session_id() {
        let body = serde_json::json!({
            "contents": [{"role": "user", "parts": [{"text": "build the parser"}]}],
            "systemInstruction": {"parts": [{"text": "You are Cline."}]},
            "labels": {"team": "bea"}
        });
        assert_eq!(
            declared_session_id(WireFormat::GoogleGenerateContent, &body),
            None
        );
    }

    /// A generate-content body in the shape Cline actually sends: `contents`
    /// rather than `messages`, `parts` rather than `content`, the model's turns
    /// under role `model`, an UNTYPED text part, a nested `functionResponse`,
    /// and the system prompt as a separate top-level `systemInstruction`.
    fn google_turn() -> serde_json::Value {
        serde_json::json!({
            "systemInstruction": {"parts": [{"text": "You are Cline."}]},
            "contents": [
                {"role": "user", "parts": [{"text": "build the parser"}]},
                {"role": "model", "parts": [
                    {"functionCall": {"id": "fc_a", "name": "read_file", "args": {}}}
                ]},
                {"role": "user", "parts": [
                    {"functionResponse": {"id": "fc_a", "name": "read_file",
                                          "response": {"content": "fn main() {}"}}},
                    {"text": "now fix it"}
                ]}
            ],
            "generationConfig": {"temperature": 0}
        })
    }

    /// Every member of the view, read off the shape that shares no vocabulary
    /// with the other three.
    #[test]
    fn google_view_reads_contents_and_parts() {
        let body = google_turn();
        let view = conversation_view(WireFormat::GoogleGenerateContent, &body).expect("a view");

        assert_eq!(
            view.user_turns.len(),
            2,
            "the `model` turn is not a user turn, and `systemInstruction` is not a turn at all"
        );
        assert_eq!(view.user_turns[0]["parts"][0]["text"], "build the parser");
        assert_eq!(
            view.content_field, "parts",
            "a turn keeps its content under `parts`, not `content`"
        );
        assert_eq!(
            view.text_block_type, None,
            "a Gemini Part is a oneof with no `type` key — matching one reads every turn as empty"
        );
        assert_eq!(
            view.tool_result_ids,
            vec!["fc_a".to_string()],
            "read from the NESTED functionResponse.id, not from a top-level item"
        );
    }

    /// The ordinary case, and the reason the id walk must not be required to
    /// find anything: Google populates `functionResponse.id` only for parallel
    /// calls, so most bodies name no id at all. An empty list is the honest
    /// answer — selector 1 does not fire and the cascade falls through — and a
    /// view is still returned.
    #[test]
    fn google_view_without_ids_is_still_a_view() {
        let body = serde_json::json!({"contents": [
            {"role": "user", "parts": [{"text": "build the parser"}]},
            {"role": "model", "parts": [{"text": "on it"}]},
            {"role": "user", "parts": [
                {"functionResponse": {"name": "read_file", "response": {}}},
                {"text": "now fix it"}
            ]}
        ]});
        let view = conversation_view(WireFormat::GoogleGenerateContent, &body).expect("a view");
        assert_eq!(view.user_turns.len(), 2);
        assert!(view.tool_result_ids.is_empty());
    }

    /// A body that does not match the shape its route promised is `None`, not
    /// half a view — the same refusal every other arm makes.
    #[test]
    fn google_view_is_none_without_contents() {
        let body = serde_json::json!({"messages": [{"role": "user", "content": "hi"}]});
        assert!(conversation_view(WireFormat::GoogleGenerateContent, &body).is_none());
    }

    /// A chat-completions body in the shape Cline actually sends, with the
    /// candidate that must NOT be read present and populated.
    fn chat_turn() -> serde_json::Value {
        serde_json::json!({
            "model": "qwen2.5-coder:14b",
            "user": "cline-user-42",
            "messages": [
                {"role": "system", "content": "You are Cline."},
                {"role": "user", "content": "build the parser"},
                {"role": "assistant", "content": null, "tool_calls": [
                    {"id": "call_a", "type": "function",
                     "function": {"name": "read_file", "arguments": "{}"}}
                ]},
                {"role": "tool", "tool_call_id": "call_a", "content": "fn main() {}"},
                {"role": "user", "content": [{"type": "text", "text": "now fix it"}]}
            ],
            "stream": true,
            "stream_options": {"include_usage": true}
        })
    }

    /// `None` here is a DECISION, not a gap — which is the whole reason this
    /// test exists under its own name.
    ///
    /// The format has no session field, and `user` is not a stand-in for one:
    /// it is caller-supplied and opaque, so reading it would attribute every
    /// turn to whatever the customer put there. The fixture carries a populated
    /// `user` precisely so that an implementation "fixing" this arm by reading
    /// it goes red here instead of shipping a mis-attribution.
    #[test]
    fn chat_completions_declares_no_session_id() {
        let body = chat_turn();
        assert_eq!(
            body["user"], "cline-user-42",
            "the fixture must actually carry the tempting field, or this proves nothing"
        );
        assert_eq!(
            declared_session_id(WireFormat::OpenAiChatCompletions, &body),
            None,
            "`user` is an opaque caller string, never a session id"
        );
    }

    /// The view: `messages` for the turns, and the tool ids the Anthropic shape
    /// cannot reach.
    ///
    /// A chat-completions tool result is a TOP-LEVEL `role: "tool"` message, not
    /// a block nested in the user turn, so a literal mirror of the Messages-API
    /// helper would return an empty id list on every request — silently, since a
    /// selector that never fires degrades to the fallback rather than failing.
    #[test]
    fn chat_completions_view_reads_messages_and_top_level_tool_results() {
        let body = chat_turn();
        let view = conversation_view(WireFormat::OpenAiChatCompletions, &body).expect("a view");

        assert_eq!(
            view.user_turns.len(),
            2,
            "the system, assistant and tool messages are not user turns"
        );
        assert_eq!(view.user_turns[0]["content"], "build the parser");
        assert_eq!(
            view.content_field, "content",
            "same content field as the Messages API"
        );
        assert_eq!(
            view.text_block_type,
            Some("text"),
            "same block type as the Messages API"
        );
        assert_eq!(
            view.tool_result_ids,
            vec!["call_a".to_string()],
            "read from the top-level `role: \"tool\"` message's `tool_call_id`"
        );
    }

    /// The ids are newest-first, deduped across the call/answer pair, and
    /// bounded by what the registry still holds — the same three properties the
    /// Responses helper is pinned on, since this one borrows its walk.
    #[test]
    fn chat_completions_tool_ids_are_newest_first_deduped_and_bounded() {
        let mut messages = vec![serde_json::json!({"role": "user", "content": "go"})];
        for i in 0..(super::super::session::RECENT_TOOL_USE_IDS + 3) {
            messages.push(serde_json::json!({
                "role": "assistant",
                "tool_calls": [{"id": format!("call_{i}"), "type": "function",
                                "function": {"name": "f", "arguments": "{}"}}]
            }));
            // The answer repeats the id — it must not consume a second slot.
            messages.push(serde_json::json!({
                "role": "tool", "tool_call_id": format!("call_{i}"), "content": "ok"
            }));
        }
        let body = serde_json::json!({"messages": messages});
        let view = conversation_view(WireFormat::OpenAiChatCompletions, &body).expect("a view");

        assert_eq!(
            view.tool_result_ids.len(),
            super::super::session::RECENT_TOOL_USE_IDS
        );
        let newest = super::super::session::RECENT_TOOL_USE_IDS + 2;
        assert_eq!(
            view.tool_result_ids[0],
            format!("call_{newest}"),
            "newest first — the oldest ids have nothing left in the registry to match"
        );
        let mut sorted = view.tool_result_ids.clone();
        sorted.sort();
        sorted.dedup();
        assert_eq!(sorted.len(), view.tool_result_ids.len(), "no id twice");
    }

    /// A Responses turn in the shape codex-cli 0.150.1 actually sends: a
    /// `developer` preamble, the `<environment_context>` block Codex prepends as
    /// a user turn of its own, the typed prompt verbatim, and the call/output
    /// pair for the tool it just ran. Captured from `codex debug prompt-input`
    /// and from a session rollout on 2026-09-06.
    fn codex_turn() -> serde_json::Value {
        serde_json::json!({
            "model": "gpt-5-codex",
            "input": [
                {"type": "message", "id": "msg_1", "role": "developer",
                 "content": [{"type": "input_text", "text": "<skills_instructions>…"}]},
                {"type": "message", "id": "msg_2", "role": "user",
                 "content": [{"type": "input_text", "text": "<environment_context>\n  <cwd>/repo</cwd>\n</environment_context>"}]},
                {"type": "message", "id": "msg_3", "role": "user",
                 "content": [{"type": "input_text", "text": "build the parser"}]},
                {"type": "function_call", "id": "fc_1", "call_id": "call_aaa",
                 "name": "shell", "arguments": "{}"},
                {"type": "function_call_output", "id": "fco_1", "call_id": "call_aaa",
                 "output": "ok"}
            ]
        })
    }

    #[test]
    fn the_responses_view_reads_input_and_leaves_the_preamble_alone() {
        let body = codex_turn();
        let view = conversation_view(WireFormat::OpenAiResponses, &body).expect("a view");

        // Two user turns, in order — and NOT the `developer` item. That item is
        // Codex's own instruction preamble: byte identical across every session
        // it starts, so hashing it would offer a candidate matching sessions that
        // have nothing to do with this request.
        assert_eq!(view.user_turns.len(), 2);
        assert_eq!(
            view.user_turns[1]["content"][0]["text"], "build the parser",
            "the typed prompt is the last user turn"
        );
        assert_eq!(view.content_field, "content");
        assert_eq!(view.text_block_type, Some("input_text"));
        assert_eq!(view.tool_result_ids, vec!["call_aaa".to_string()]);
    }

    #[test]
    fn responses_call_ids_are_newest_first_deduped_and_bounded() {
        // A long conversation carries its whole history in `input`. The registry
        // keeps `RECENT_TOOL_USE_IDS` per session, so anything older has nothing
        // left to match and walking to it is work for no answer.
        let mut items = Vec::new();
        for i in 0..40 {
            items.push(serde_json::json!({
                "type": "function_call", "call_id": format!("call_{i:02}"), "name": "shell"
            }));
            // The call and the output answering it repeat one id; spending two
            // slots on one tool call would halve what the join can reach.
            items.push(serde_json::json!({
                "type": "function_call_output", "call_id": format!("call_{i:02}"), "output": "ok"
            }));
        }
        let body = serde_json::json!({ "input": items });
        let view = conversation_view(WireFormat::OpenAiResponses, &body).expect("a view");

        assert_eq!(
            view.tool_result_ids.len(),
            super::super::session::RECENT_TOOL_USE_IDS
        );
        assert_eq!(
            view.tool_result_ids[0], "call_39",
            "newest first — the request's newest ids are the ones still in the registry"
        );
        assert_eq!(view.tool_result_ids[7], "call_32");
    }

    #[test]
    fn every_responses_item_that_carries_an_id_names_it_call_id() {
        // Keyed on the FIELD, not on a list of type names: Codex has added output
        // variants more than once, and a name list would stop matching the day it
        // adds the next — silently, since a selector that never fires degrades to
        // the fallback rather than failing.
        let body = serde_json::json!({"input": [
            {"type": "custom_tool_call_output", "call_id": "call_custom", "output": "ok"},
            {"type": "mcp_tool_call_output", "call_id": "call_mcp", "output": {}},
            {"type": "tool_search_output", "call_id": "call_search", "status": "ok"},
            {"type": "a_variant_that_does_not_exist_yet", "call_id": "call_future"}
        ]});
        let view = conversation_view(WireFormat::OpenAiResponses, &body).expect("a view");
        assert_eq!(
            view.tool_result_ids,
            vec!["call_future", "call_search", "call_mcp", "call_custom"]
        );
    }

    #[test]
    fn each_format_reads_only_its_own_body_shape() {
        // The route picked the format; a body that does not match the shape that
        // route promised yields nothing rather than half a view. `input` read as
        // Messages and `messages` read as Responses are both None — which is what
        // keeps a mis-resolved route from inventing signals.
        let codex = codex_turn();
        let claude = serde_json::json!({"messages": [
            {"role": "user", "content": [{"type": "text", "text": "build the parser"}]}
        ]});

        assert!(conversation_view(WireFormat::AnthropicMessages, &codex).is_none());
        assert!(conversation_view(WireFormat::OpenAiResponses, &claude).is_none());
        // And an uncaptured route never reaches a parsed body at all.
        assert!(conversation_view(WireFormat::Unknown, &codex).is_none());
        assert!(conversation_view(WireFormat::Unknown, &claude).is_none());
    }

    #[test]
    fn the_messages_view_is_unchanged_by_the_move() {
        // The shape moved out of `proxy.rs`; its answers did not. Tool-result ids
        // come from the LAST user turn only — an earlier turn's results belong to
        // a turn already answered.
        let body = serde_json::json!({"messages": [
            {"role": "user", "content": [{"type": "text", "text": "build the parser"}]},
            {"role": "assistant", "content": [
                {"type": "tool_use", "id": "toolu_old", "name": "Bash", "input": {}}
            ]},
            {"role": "user", "content": [
                {"type": "tool_result", "tool_use_id": "toolu_old", "content": "ok"}
            ]},
            {"role": "assistant", "content": [
                {"type": "tool_use", "id": "toolu_new", "name": "Bash", "input": {}}
            ]},
            {"role": "user", "content": [
                {"type": "tool_result", "tool_use_id": "toolu_new", "content": "ok"},
                {"type": "text", "text": "and now the lexer"}
            ]}
        ]});
        let view = conversation_view(WireFormat::AnthropicMessages, &body).expect("a view");
        assert_eq!(view.user_turns.len(), 3);
        assert_eq!(view.content_field, "content");
        assert_eq!(view.text_block_type, Some("text"));
        assert_eq!(view.tool_result_ids, vec!["toolu_new".to_string()]);
    }

    #[test]
    fn each_format_reads_only_its_own_declaration() {
        // Naming your own session in the body is a convention per agent, not a
        // property of HTTP — so each shape is read by exactly one format, and
        // reading a body under the other format yields nothing.
        let claude = serde_json::json!({
            "metadata": {"user_id": r#"{"session_id":"5c7d9833"}"#}
        });
        let codex = serde_json::json!({
            "client_metadata": {
                "session_id": "01a07677-988f-7901-af48-225c7386aabc",
                "thread_id": "01a07677-988f-7901-af48-225c7386aabc",
                "turn_id": "01a07677-7334-74a2-be87-bdd0bbe8fb77",
                "x-codex-installation-id": "5532dc79-4512-4bae-ab73-0dd3e814d329"
            }
        });

        assert_eq!(
            declared_session_id(WireFormat::AnthropicMessages, &claude).as_deref(),
            Some("5c7d9833")
        );
        assert_eq!(
            declared_session_id(WireFormat::OpenAiResponses, &claude),
            None
        );

        assert_eq!(
            declared_session_id(WireFormat::OpenAiResponses, &codex).as_deref(),
            Some("01a07677-988f-7901-af48-225c7386aabc")
        );
        assert_eq!(
            declared_session_id(WireFormat::AnthropicMessages, &codex),
            None
        );

        // An uncaptured route never reaches a parsed body.
        assert_eq!(declared_session_id(WireFormat::Unknown, &claude), None);
        assert_eq!(declared_session_id(WireFormat::Unknown, &codex), None);
    }

    #[test]
    fn codex_reads_session_id_and_not_a_neighbouring_field() {
        // The same object carries `thread_id`, `turn_id` and an installation id.
        // `turn_id` is a NARROWER scope than a session — attributing a turn id as
        // a session would split one session into a new label every turn, which
        // looks like working attribution and is not.
        let body = serde_json::json!({
            "client_metadata": {"session_id": "sess-real", "turn_id": "turn-other",
                                "thread_id": "thread-other"}
        });
        assert_eq!(
            declared_session_id(WireFormat::OpenAiResponses, &body).as_deref(),
            Some("sess-real")
        );

        // `prompt_cache_key` holds the same value today and is deliberately not
        // read: it is named for the cache, and is free to become a prefix digest
        // without Codex changing anything about its sessions.
        let cache_key_only = serde_json::json!({
            "prompt_cache_key": "01a07677-988f-7901-af48-225c7386aabc"
        });
        assert_eq!(
            declared_session_id(WireFormat::OpenAiResponses, &cache_key_only),
            None
        );
    }

    #[test]
    fn a_codex_declaration_that_is_not_usable_is_silently_ignored() {
        // Same doctrine as the Messages arm: the field is another program's
        // internal convention, so every malformed shape degrades to "no declared
        // id" and the cascade carries on — never an error, never a bogus label.
        let cases = [
            serde_json::json!({}),                      // no client_metadata
            serde_json::json!({"client_metadata": {}}), // no session_id
            serde_json::json!({"client_metadata": {"session_id": 42}}), // not a string
            serde_json::json!({"client_metadata": {"session_id": ""}}), // blank
            serde_json::json!({"client_metadata": {"session_id": "   "}}), // whitespace only
            serde_json::json!({"client_metadata": {"session_id": "a\u{0000}b"}}), // control char
            serde_json::json!({"client_metadata": {"session_id": "x".repeat(500)}}), // over the cap
        ];
        for body in cases {
            assert_eq!(
                declared_session_id(WireFormat::OpenAiResponses, &body),
                None,
                "must not trust {body}"
            );
        }
    }
}