aither-claude 0.22.0

Claude provider integration for aither
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
//! Request building and message conversion for the Claude API.

use aither_core::llm::{
    Attachment, Message, Role,
    model::{
        ClaudeCacheBreakpointTarget, ClaudeExplicitCacheBreakpoints, ClaudeNativeTools,
        ClaudePromptCache, ClaudePromptCacheStrategy, ClaudePromptCacheTtl, Parameters,
        ReasoningEffort, ToolChoice,
    },
    tool::ToolDefinition,
};
// Only the native file:// reader encodes anything here.
use crate::PROVIDER_NAME;
use crate::error::ClaudeError;
#[cfg(not(target_arch = "wasm32"))]
use base64::Engine;
use serde::Serialize;
use serde_json::Value;

/// Claude Messages API request body.
#[derive(Debug, Serialize)]
pub struct MessagesRequest {
    /// Model identifier.
    pub model: String,
    /// Maximum tokens to generate.
    pub max_tokens: u32,
    /// Conversation messages.
    pub messages: Vec<MessagePayload>,
    /// System prompt (extracted from messages).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system: Option<SystemPayload>,
    /// Enable streaming.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub stream: bool,
    /// Sampling temperature.
    ///
    /// # Deprecated by Anthropic
    ///
    /// Anthropic marks `temperature` deprecated. Models newer than the Claude 4
    /// generation accept only `1.0`, for backwards compatibility; other values
    /// are rejected with a 400. It is still sent when set, because callers
    /// pointing at legacy models legitimately need it — steer newer models with
    /// [`crate::request::MessagesRequest::output_config`] effort instead.
    ///
    /// See <https://platform.claude.com/docs/en/api/messages>.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    /// Nucleus sampling probability.
    ///
    /// # Deprecated by Anthropic
    ///
    /// Deprecated alongside [`Self::temperature`]. Newer models accept only
    /// values `>= 0.99`. Kept for legacy models; see [`Self::temperature`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,
    /// Top-k sampling.
    ///
    /// # Deprecated by Anthropic
    ///
    /// The most restricted of the three: newer models reject `top_k` outright
    /// rather than accepting a compatibility value. Kept for legacy models; see
    /// [`Self::temperature`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_k: Option<u32>,
    /// Stop sequences.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_sequences: Option<Vec<String>>,
    /// Available tools.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<ToolPayload>>,
    /// Tool choice policy.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<ToolChoicePayload>,
    /// Thinking configuration.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking: Option<ThinkingPayload>,
    /// Output shaping, including reasoning effort.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_config: Option<OutputConfigPayload>,
    /// Prompt cache control.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_control: Option<CacheControlPayload>,
}

/// Claude thinking configuration.
///
/// Only adaptive thinking is modelled. The manual
/// `{"type": "enabled", "budget_tokens": N}` mode is deprecated on the 4.6
/// generation and returns a 400 on every model after it, so aither does not
/// offer a way to construct it.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ThinkingPayload {
    /// Let Claude decide when and how deeply to think, steered by effort.
    Adaptive {
        /// Whether thinking text is returned. Omitted uses the model default,
        /// which is `omitted` on the newest models.
        #[serde(skip_serializing_if = "Option::is_none")]
        display: Option<ThinkingDisplay>,
    },
    /// Turn thinking off.
    ///
    /// Rejected at `xhigh` and `max` effort, and on models whose thinking is
    /// always on.
    Disabled,
}

/// Whether Claude returns its thinking text.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ThinkingDisplay {
    /// Return a summary of the thinking.
    Summarized,
    /// Return thinking blocks with empty text, carrying only the signature.
    Omitted,
}

/// Claude output configuration.
#[derive(Debug, Clone, Serialize)]
pub struct OutputConfigPayload {
    /// How much effort Claude puts into the response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effort: Option<&'static str>,
}

/// Maps the portable effort ladder onto Claude's `output_config.effort`.
///
/// [`ReasoningEffort::None`] is absent here on purpose: Claude expresses "do not
/// think" as `thinking: {"type": "disabled"}`, not as an effort level, so
/// [`build_thinking`] handles it and this returns `None` for it.
///
/// # Errors
///
/// Returns [`ClaudeError`] for [`ReasoningEffort::Minimal`], which Claude's
/// effort scale does not have. Rounding it up to `low` would silently buy the
/// caller more reasoning than they asked for.
pub fn claude_effort(effort: ReasoningEffort) -> Result<Option<&'static str>, ClaudeError> {
    match effort {
        ReasoningEffort::None => Ok(None),
        ReasoningEffort::Low => Ok(Some("low")),
        ReasoningEffort::Medium => Ok(Some("medium")),
        ReasoningEffort::High => Ok(Some("high")),
        ReasoningEffort::XHigh => Ok(Some("xhigh")),
        ReasoningEffort::Max => Ok(Some("max")),
        ReasoningEffort::Minimal => Err(ClaudeError::Api(
            "Claude effort has no 'minimal' level; the lowest is Low".to_string(),
        )),
    }
}

/// Builds the `thinking` field.
///
/// Returns `None` when the caller expressed no preference, leaving the model's
/// own default in force — which is thinking-on for the Claude 5 generation and
/// thinking-off for 4.6 through 4.8.
#[must_use]
pub const fn build_thinking(params: &ParameterSnapshot) -> Option<ThinkingPayload> {
    match (params.reasoning_effort, params.include_reasoning) {
        (Some(ReasoningEffort::None), _) => Some(ThinkingPayload::Disabled),
        // The caller wants to read the thinking.
        (_, true) => Some(ThinkingPayload::Adaptive {
            display: Some(ThinkingDisplay::Summarized),
        }),
        // An effort was set but the text is unwanted: ask for thinking without
        // it, which also lets the server skip streaming thinking tokens.
        (Some(_), false) => Some(ThinkingPayload::Adaptive {
            display: Some(ThinkingDisplay::Omitted),
        }),
        // No preference at all: leave the model's own default in force.
        (None, false) => None,
    }
}

/// Builds the `output_config` field.
///
/// # Errors
///
/// Returns [`ClaudeError`] when the requested effort has no Claude equivalent.
pub fn build_output_config(
    params: &ParameterSnapshot,
) -> Result<Option<OutputConfigPayload>, ClaudeError> {
    let Some(effort) = params.reasoning_effort else {
        return Ok(None);
    };
    let effort = claude_effort(effort)?;
    Ok(effort.map(|effort| OutputConfigPayload {
        effort: Some(effort),
    }))
}

/// Individual message in Claude format.
#[derive(Debug, Clone, Serialize)]
pub struct MessagePayload {
    /// Role: "user", "assistant", or "system" for an effort-only message.
    pub role: &'static str,
    /// Message content; empty on an effort-only system message.
    pub content: ContentPayload,
    /// The effort for the rest of the conversation, on an effort-only
    /// system message (beta [`MID_CONVERSATION_OUTPUT_CONFIG_BETA`]).
    ///
    /// [`MID_CONVERSATION_OUTPUT_CONFIG_BETA`]: crate::constant::MID_CONVERSATION_OUTPUT_CONFIG_BETA
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_config: Option<OutputConfigPayload>,
}

impl MessagePayload {
    /// The effort-only system message changing the effort to `effort` for
    /// the rest of the conversation, leaving every earlier byte, and the
    /// request-level effort, as they were.
    ///
    /// # Errors
    ///
    /// Returns an error for an effort Claude cannot set per message:
    /// `Minimal`, which Claude does not have, and `None`, which Claude
    /// expresses only as request-level `thinking: {"type": "disabled"}`.
    pub fn effort_update(effort: ReasoningEffort) -> Result<Self, ClaudeError> {
        let level = claude_effort(effort)?.ok_or_else(|| {
            ClaudeError::Api(
                "Claude turns thinking off only at the request level; a per-message \
                 effort update cannot set effort None"
                    .to_string(),
            )
        })?;
        Ok(Self {
            role: "system",
            content: ContentPayload::Blocks(Vec::new()),
            output_config: Some(OutputConfigPayload {
                effort: Some(level),
            }),
        })
    }

    /// Whether this is an effort-only system message, which needs
    /// [`MID_CONVERSATION_OUTPUT_CONFIG_BETA`](crate::constant::MID_CONVERSATION_OUTPUT_CONFIG_BETA).
    #[must_use]
    pub const fn is_effort_update(&self) -> bool {
        self.output_config.is_some()
    }
}

/// Message content - either a simple string or array of content blocks.
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum ContentPayload {
    /// Simple text content.
    Text(String),
    /// Array of content blocks (for multimodal or tool results).
    Blocks(Vec<ContentBlock>),
}

/// System prompt payload in Claude format.
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum SystemPayload {
    /// Simple system text.
    Text(String),
    /// System content blocks.
    Blocks(Vec<SystemTextBlock>),
}

/// System text block.
#[derive(Debug, Clone, Serialize)]
pub struct SystemTextBlock {
    /// Claude text block kind.
    #[serde(rename = "type")]
    pub kind: &'static str,
    /// Block text.
    pub text: String,
    /// Optional explicit cache control for this block.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_control: Option<CacheControlPayload>,
}

/// Content block types for multimodal messages.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
pub enum ContentBlock {
    /// Text content block.
    #[serde(rename = "text")]
    Text {
        /// The text content.
        text: String,
        /// Optional explicit cache control for this block.
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControlPayload>,
    },
    /// Image content block.
    #[serde(rename = "image")]
    Image {
        /// Image source (base64 or URL).
        source: MediaSource,
        /// Optional explicit cache control for this block.
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControlPayload>,
    },
    /// PDF document content block.
    #[serde(rename = "document")]
    Document {
        /// PDF source (base64 or URL).
        source: MediaSource,
        /// Optional explicit cache control for this block.
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControlPayload>,
    },
    /// Thinking block replayed from a previous turn.
    ///
    /// Anthropic requires these back "complete and unmodified", so the text and
    /// signature are the ones Claude produced, never regenerated.
    #[serde(rename = "thinking")]
    Thinking {
        /// The thinking text, empty when the turn used `display: "omitted"`.
        thinking: String,
        /// The signature Claude issued for this block.
        signature: String,
    },
    /// Safety-redacted thinking block replayed from a previous turn.
    #[serde(rename = "redacted_thinking")]
    RedactedThinking {
        /// Opaque encrypted thinking.
        data: String,
    },
    /// Tool use block (in assistant responses).
    #[serde(rename = "tool_use")]
    ToolUse {
        /// Unique ID for this tool use.
        id: String,
        /// Tool name.
        name: String,
        /// Tool input arguments.
        input: Value,
        /// Optional explicit cache control for this block.
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControlPayload>,
    },
    /// Tool result block (in user messages).
    #[serde(rename = "tool_result")]
    ToolResult {
        /// ID of the `tool_use` this is responding to.
        tool_use_id: String,
        /// Tool output content.
        content: String,
        /// Optional explicit cache control for this block.
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControlPayload>,
    },
}

/// Image source for vision requests.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
pub enum MediaSource {
    /// Base64-encoded image data.
    #[serde(rename = "base64")]
    Base64 {
        /// MIME type (image/jpeg, image/png, image/gif, image/webp).
        media_type: String,
        /// Base64-encoded image data.
        data: String,
    },
    /// URL-referenced image.
    #[serde(rename = "url")]
    Url {
        /// Full URL to the image.
        url: String,
    },
}

/// Tool definition in Claude format.
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum ToolPayload {
    /// User-defined tool.
    Custom(CustomToolPayload),
    /// Anthropic-defined tool.
    Native(NativeToolPayload),
}

/// Custom tool definition in Claude format.
#[derive(Debug, Clone, Serialize)]
pub struct CustomToolPayload {
    /// Tool name.
    pub name: String,
    /// Tool description.
    pub description: String,
    /// JSON schema for tool input.
    pub input_schema: Value,
    /// Optional explicit cache control for this tool block.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_control: Option<CacheControlPayload>,
}

/// Anthropic-defined tool definition.
#[derive(Debug, Clone, Serialize)]
pub struct NativeToolPayload {
    /// Tool type.
    #[serde(rename = "type")]
    pub kind: &'static str,
    /// Tool name.
    pub name: &'static str,
    /// Optional maximum character count for text editor views.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_characters: Option<u32>,
}

/// Claude prompt cache control payload.
#[derive(Debug, Clone, Serialize)]
pub struct CacheControlPayload {
    /// Cache type.
    #[serde(rename = "type")]
    pub kind: &'static str,
    /// Optional TTL override (`1h`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttl: Option<&'static str>,
}

impl From<ClaudePromptCache> for CacheControlPayload {
    fn from(cache: ClaudePromptCache) -> Self {
        let ttl = match cache.ttl {
            ClaudePromptCacheTtl::FiveMinutes => None,
            ClaudePromptCacheTtl::OneHour => Some(ClaudePromptCacheTtl::OneHour.as_str()),
        };
        Self {
            kind: "ephemeral",
            ttl,
        }
    }
}

/// Tool choice payload for Claude Messages API.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ToolChoicePayload {
    /// Let Claude decide when to call a tool.
    Auto {
        /// Forbids Claude from requesting more than one tool per turn.
        #[serde(skip_serializing_if = "Option::is_none")]
        disable_parallel_tool_use: Option<bool>,
    },
    /// Require Claude to call at least one tool.
    Any {
        /// Forbids Claude from requesting more than one tool per turn.
        #[serde(skip_serializing_if = "Option::is_none")]
        disable_parallel_tool_use: Option<bool>,
    },
    /// Restrict tool calling to a single tool by name.
    Tool {
        /// Name of the tool Claude is allowed to call.
        name: String,
        /// Forbids Claude from requesting more than one tool per turn.
        #[serde(skip_serializing_if = "Option::is_none")]
        disable_parallel_tool_use: Option<bool>,
    },
    /// Forbid tool calls outright.
    None,
}

/// Snapshot of parameters for request building.
#[derive(Clone, Default)]
#[allow(dead_code)]
pub struct ParameterSnapshot {
    /// Sampling temperature.
    pub temperature: Option<f32>,
    /// Nucleus sampling probability.
    pub top_p: Option<f32>,
    /// Top-k sampling.
    pub top_k: Option<u32>,
    /// Maximum tokens to generate.
    pub max_tokens: Option<u32>,
    /// Stop sequences.
    pub stop_sequences: Option<Vec<String>>,
    /// Whether to include reasoning/thinking.
    pub include_reasoning: bool,
    /// Whether Claude may request several tools per turn. `None` keeps Anthropic's default.
    pub parallel_tool_calls: Option<bool>,
    /// Requested reasoning effort.
    pub reasoning_effort: Option<ReasoningEffort>,
    /// Whether the request asks for a streaming response.
    pub stream: Option<bool>,
    /// Tool choice policy.
    pub tool_choice: ToolChoice,
    /// Claude-specific cache controls.
    pub cache: Option<ClaudePromptCache>,
    /// Claude-native tools.
    pub native_tools: ClaudeNativeTools,
}

impl From<&Parameters> for ParameterSnapshot {
    fn from(params: &Parameters) -> Self {
        Self {
            temperature: params.temperature,
            top_p: params.top_p,
            top_k: params.top_k,
            max_tokens: params.max_tokens,
            stop_sequences: params.stop.clone(),
            include_reasoning: params.include_reasoning,
            parallel_tool_calls: params.parallel_tool_calls,
            reasoning_effort: params.reasoning_effort,
            stream: params.stream,
            tool_choice: params.tool_choice.clone(),
            cache: params.cache.claude,
            native_tools: params.native_tools.claude.clone(),
        }
    }
}

/// Convert aither messages to Claude format, extracting system messages.
///
/// Returns (`system_prompt`, messages). A single system message is emitted as
/// plain text, while multiple system messages are preserved as system blocks.
pub async fn to_claude_messages(
    messages: &[Message],
) -> Result<(Option<SystemPayload>, Vec<MessagePayload>), String> {
    let mut system_parts: Vec<String> = Vec::new();
    let mut claude_messages: Vec<MessagePayload> = Vec::new();

    for message in messages {
        match message.role() {
            Role::System => {
                system_parts.push(message.content().to_string());
            }
            Role::User | Role::Tool => {
                let content = if matches!(message.role(), Role::Tool) {
                    build_tool_result_content(message)
                } else {
                    build_user_content(message).await?
                };
                claude_messages.push(MessagePayload {
                    role: "user",
                    output_config: None,
                    content,
                });
            }
            Role::Assistant => {
                claude_messages.push(MessagePayload {
                    role: "assistant",
                    output_config: None,
                    content: build_assistant_content(message),
                });
            }
            Role::Configuration => {
                let effort = message
                    .configured_effort()
                    .expect("a configuration message carries its effort");
                claude_messages.push(
                    MessagePayload::effort_update(effort).map_err(|error| error.to_string())?,
                );
            }
        }
    }

    let system = if system_parts.is_empty() {
        None
    } else if system_parts.len() == 1 {
        Some(SystemPayload::Text(system_parts.remove(0)))
    } else {
        Some(SystemPayload::Blocks(
            system_parts
                .into_iter()
                .map(|text| SystemTextBlock {
                    kind: "text",
                    text,
                    cache_control: None,
                })
                .collect(),
        ))
    };

    Ok((system, claude_messages))
}

/// Build content for a user message, handling image and PDF attachments.
async fn build_user_content(message: &Message) -> Result<ContentPayload, String> {
    let attachments = message.attachments();

    if attachments.is_empty() {
        return Ok(ContentPayload::Text(flatten_content(message)));
    }

    let mut blocks: Vec<ContentBlock> = Vec::with_capacity(attachments.len() + 1);
    for attachment in attachments {
        let source = parse_media_source(attachment).await?;
        let media_type = attachment.media_type().as_ref();
        if media_type.starts_with("image/") {
            blocks.push(ContentBlock::Image {
                source,
                cache_control: None,
            });
        } else if media_type == "application/pdf" {
            blocks.push(ContentBlock::Document {
                source,
                cache_control: None,
            });
        } else {
            return Err(format!(
                "Claude Messages API does not support attachment MIME type '{media_type}'"
            ));
        }
    }

    let text = flatten_content(message);
    if !text.is_empty() {
        blocks.push(ContentBlock::Text {
            text,
            cache_control: None,
        });
    }

    if blocks.len() == 1
        && let Some(ContentBlock::Text {
            text,
            cache_control: None,
        }) = blocks.pop()
    {
        return Ok(ContentPayload::Text(text));
    }

    Ok(ContentPayload::Blocks(blocks))
}

/// Decodes reasoning this crate previously emitted back into content blocks.
///
/// The payload is this crate's own encoding, so decoding it here keeps core
/// ignorant of Claude's block taxonomy while still round-tripping both
/// `thinking` and `redacted_thinking`. State from another provider, and state
/// that no longer parses, is dropped: Anthropic documents stripping foreign
/// thinking rather than rejecting the turn.
fn replayed_thinking_blocks(message: &Message) -> Vec<ContentBlock> {
    #[derive(serde::Deserialize)]
    #[serde(tag = "type")]
    enum Replayed {
        #[serde(rename = "thinking")]
        Thinking { thinking: String, signature: String },
        #[serde(rename = "redacted_thinking")]
        RedactedThinking { data: String },
    }

    message
        .reasoning()
        .iter()
        .filter_map(|state| {
            let payload = state.payload_for(PROVIDER_NAME).or_else(|| {
                tracing::debug!(
                    provider = state.provider(),
                    "dropping reasoning state from another provider"
                );
                None
            })?;
            match serde_json::from_str::<Replayed>(payload) {
                Ok(Replayed::Thinking {
                    thinking,
                    signature,
                }) => Some(ContentBlock::Thinking {
                    thinking,
                    signature,
                }),
                Ok(Replayed::RedactedThinking { data }) => {
                    Some(ContentBlock::RedactedThinking { data })
                }
                Err(error) => {
                    tracing::debug!(%error, "dropping unparsable Claude reasoning state");
                    None
                }
            }
        })
        .collect()
}

fn build_assistant_content(message: &Message) -> ContentPayload {
    let tool_calls = message.tool_calls();
    // Thinking must lead the turn, so its presence alone forces block form even
    // when there are no tool calls to report.
    let thinking = replayed_thinking_blocks(message);
    if tool_calls.is_empty() && thinking.is_empty() {
        return ContentPayload::Text(flatten_content(message));
    }

    let mut blocks = thinking;
    let text = flatten_content(message);
    if !text.is_empty() {
        blocks.push(ContentBlock::Text {
            text,
            cache_control: None,
        });
    }

    for call in tool_calls {
        blocks.push(ContentBlock::ToolUse {
            id: call.id.clone(),
            name: call.name.clone(),
            input: call.arguments.clone(),
            cache_control: None,
        });
    }

    ContentPayload::Blocks(blocks)
}

fn build_tool_result_content(message: &Message) -> ContentPayload {
    let tool_use_id = message.tool_call_id().unwrap_or_else(|| {
        panic!("Tool message missing tool_call_id required by Claude tool_result payload")
    });
    let content = flatten_content(message);
    ContentPayload::Blocks(vec![ContentBlock::ToolResult {
        tool_use_id: tool_use_id.to_string(),
        content,
        cache_control: None,
    }])
}

/// Apply Claude cache strategy to request payload sections.
///
/// Returns top-level `cache_control` when automatic caching is selected.
/// Explicit mode mutates blocks in-place and returns `None`.
pub fn apply_cache_strategy(
    system: &mut Option<SystemPayload>,
    messages: &mut [MessagePayload],
    tools: &mut Option<Vec<ToolPayload>>,
    cache: ClaudePromptCache,
) -> Result<Option<CacheControlPayload>, String> {
    let default_ttl = cache.ttl;
    match cache.strategy {
        ClaudePromptCacheStrategy::Automatic => {
            let automatic = maybe_automatic_cache_control(
                system.as_ref(),
                messages,
                tools.as_ref(),
                default_ttl,
                None,
            )?;
            Ok(automatic.map(|(cache_control, _)| cache_control))
        }
        ClaudePromptCacheStrategy::Explicit(breakpoints) => {
            let applied =
                apply_explicit_breakpoints(system, messages, tools, breakpoints, default_ttl)?;
            validate_mixed_ttl_ordering(&applied)?;
            Ok(None)
        }
        ClaudePromptCacheStrategy::AutomaticAndExplicit(breakpoints) => {
            let mut applied =
                apply_explicit_breakpoints(system, messages, tools, breakpoints, default_ttl)?;
            let automatic = maybe_automatic_cache_control(
                system.as_ref(),
                messages,
                tools.as_ref(),
                default_ttl,
                Some(breakpoints),
            )?;
            if let Some((cache_control, automatic_breakpoint)) = automatic {
                applied.push(automatic_breakpoint);
                validate_mixed_ttl_ordering(&applied)?;
                return Ok(Some(cache_control));
            }
            validate_mixed_ttl_ordering(&applied)?;
            Ok(None)
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct PromptPosition {
    section: u8,
    major: usize,
    minor: usize,
}

impl PromptPosition {
    const fn tool(index: usize) -> Self {
        Self {
            section: 0,
            major: index,
            minor: 0,
        }
    }

    const fn system(index: usize) -> Self {
        Self {
            section: 1,
            major: index,
            minor: 0,
        }
    }

    const fn message(message_index: usize, block_index: usize) -> Self {
        Self {
            section: 2,
            major: message_index,
            minor: block_index,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct AppliedBreakpoint {
    position: PromptPosition,
    ttl: ClaudePromptCacheTtl,
}

fn apply_explicit_breakpoints(
    system: &mut Option<SystemPayload>,
    messages: &mut [MessagePayload],
    tools: &mut Option<Vec<ToolPayload>>,
    breakpoints: ClaudeExplicitCacheBreakpoints,
    default_ttl: ClaudePromptCacheTtl,
) -> Result<Vec<AppliedBreakpoint>, String> {
    let mut applied = Vec::new();
    for breakpoint in breakpoints.iter() {
        let ttl = breakpoint.effective_ttl(default_ttl);
        let cache_control = cache_control_payload_for_ttl(ttl);
        let position =
            mark_target_cache_control(system, messages, tools, breakpoint.target, &cache_control)?;
        applied.push(AppliedBreakpoint { position, ttl });
    }
    Ok(applied)
}

#[allow(clippy::ref_option)]
fn maybe_automatic_cache_control(
    system: Option<&SystemPayload>,
    messages: &[MessagePayload],
    tools: Option<&Vec<ToolPayload>>,
    ttl: ClaudePromptCacheTtl,
    explicit_breakpoints: Option<ClaudeExplicitCacheBreakpoints>,
) -> Result<Option<(CacheControlPayload, AppliedBreakpoint)>, String> {
    let Some((position, existing_control)) = find_last_cacheable_block(system, messages, tools)
    else {
        // No cacheable block exists: skip automatic caching as Anthropic does.
        return Ok(None);
    };

    if let Some(existing_control) = existing_control {
        if cache_control_matches_ttl(&existing_control, ttl) {
            // Anthropic behavior: automatic is a no-op when last block already has same TTL.
            return Ok(None);
        }
        return Err(
            "Claude automatic cache_control conflicts with explicit cache_control on the last cacheable block".to_string(),
        );
    }

    if let Some(explicit_breakpoints) = explicit_breakpoints
        && explicit_breakpoints.is_full()
    {
        return Err(
            "Claude supports at most 4 cache breakpoints; automatic caching needs one free slot"
                .to_string(),
        );
    }

    let cache_control = cache_control_payload_for_ttl(ttl);
    Ok(Some((cache_control, AppliedBreakpoint { position, ttl })))
}

#[allow(clippy::ref_option)]
fn find_last_cacheable_block(
    system: Option<&SystemPayload>,
    messages: &[MessagePayload],
    tools: Option<&Vec<ToolPayload>>,
) -> Option<(PromptPosition, Option<CacheControlPayload>)> {
    for (message_index, message) in messages.iter().enumerate().rev() {
        match &message.content {
            ContentPayload::Text(text) => {
                if !text.is_empty() {
                    return Some((PromptPosition::message(message_index, 0), None));
                }
            }
            ContentPayload::Blocks(blocks) => {
                if let Some(block_index) = last_cacheable_block_index(blocks) {
                    return Some((
                        PromptPosition::message(message_index, block_index),
                        block_cache_control(&blocks[block_index]).cloned(),
                    ));
                }
            }
        }
    }

    if let Some(system) = system {
        match system {
            SystemPayload::Text(text) => {
                if !text.is_empty() {
                    return Some((PromptPosition::system(0), None));
                }
            }
            SystemPayload::Blocks(blocks) => {
                if let Some(system_index) = blocks.iter().rposition(|block| !block.text.is_empty())
                {
                    return Some((
                        PromptPosition::system(system_index),
                        blocks[system_index].cache_control.clone(),
                    ));
                }
            }
        }
    }

    if let Some(tools) = tools
        && let Some((tool_index, tool)) = tools
            .iter()
            .enumerate()
            .rev()
            .find_map(|(index, tool)| custom_tool(tool).map(|custom| (index, custom)))
    {
        return Some((PromptPosition::tool(tool_index), tool.cache_control.clone()));
    }

    None
}

const fn cache_control_payload_for_ttl(ttl: ClaudePromptCacheTtl) -> CacheControlPayload {
    CacheControlPayload {
        kind: "ephemeral",
        ttl: match ttl {
            ClaudePromptCacheTtl::FiveMinutes => None,
            ClaudePromptCacheTtl::OneHour => Some(ClaudePromptCacheTtl::OneHour.as_str()),
        },
    }
}

fn cache_control_matches_ttl(
    cache_control: &CacheControlPayload,
    ttl: ClaudePromptCacheTtl,
) -> bool {
    let expected = cache_control_payload_for_ttl(ttl);
    cache_control.kind == expected.kind && cache_control.ttl == expected.ttl
}

fn validate_mixed_ttl_ordering(applied: &[AppliedBreakpoint]) -> Result<(), String> {
    if applied.is_empty() {
        return Ok(());
    }
    let mut ordered = applied.to_vec();
    ordered.sort_by_key(|breakpoint| breakpoint.position);
    let mut seen_five_minute = false;
    for breakpoint in ordered {
        match breakpoint.ttl {
            ClaudePromptCacheTtl::OneHour => {
                if seen_five_minute {
                    return Err(
                        "Claude mixed TTL ordering requires 1h cache breakpoints to appear before 5m breakpoints".to_string(),
                    );
                }
            }
            ClaudePromptCacheTtl::FiveMinutes => {
                seen_five_minute = true;
            }
        }
    }
    Ok(())
}

fn mark_target_cache_control(
    system: &mut Option<SystemPayload>,
    messages: &mut [MessagePayload],
    tools: &mut Option<Vec<ToolPayload>>,
    target: ClaudeCacheBreakpointTarget,
    cache_control: &CacheControlPayload,
) -> Result<PromptPosition, String> {
    match target {
        ClaudeCacheBreakpointTarget::LastTool => mark_last_tool_cache_control(tools, cache_control),
        ClaudeCacheBreakpointTarget::Tool(index) => {
            mark_tool_cache_control(tools, index, cache_control)
        }
        ClaudeCacheBreakpointTarget::LastSystem => {
            mark_last_system_cache_control(system, cache_control)
        }
        ClaudeCacheBreakpointTarget::System(index) => {
            mark_system_cache_control(system, index, cache_control)
        }
        ClaudeCacheBreakpointTarget::LastMessage => {
            mark_last_message_cache_control(messages, cache_control)
        }
        ClaudeCacheBreakpointTarget::Message {
            message_index,
            block_index,
        } => mark_message_cache_control(messages, message_index, block_index, cache_control),
    }
}

fn mark_last_tool_cache_control(
    tools: &mut Option<Vec<ToolPayload>>,
    cache_control: &CacheControlPayload,
) -> Result<PromptPosition, String> {
    let tools = tools.as_mut().ok_or_else(|| {
        "Claude explicit cache breakpoint requested for tools but tools are empty".to_string()
    })?;
    let (index, tool) = tools
        .iter_mut()
        .enumerate()
        .rev()
        .find_map(|(index, tool)| custom_tool_mut(tool).map(|custom| (index, custom)))
        .ok_or_else(|| {
            "Claude explicit cache breakpoint requested for tools but no custom tool exists"
                .to_string()
        })?;
    set_cache_control(
        &mut tool.cache_control,
        cache_control,
        "tool breakpoint already has conflicting cache_control",
    )?;
    Ok(PromptPosition::tool(index))
}

fn mark_tool_cache_control(
    tools: &mut Option<Vec<ToolPayload>>,
    index: usize,
    cache_control: &CacheControlPayload,
) -> Result<PromptPosition, String> {
    let tools = tools.as_mut().ok_or_else(|| {
        "Claude explicit cache breakpoint requested for tools but tools are empty".to_string()
    })?;
    let tool = tools
        .get_mut(index)
        .ok_or_else(|| format!("Claude explicit tool breakpoint index {index} is out of range"))?;
    let tool = custom_tool_mut(tool).ok_or_else(|| {
        format!("Claude explicit tool breakpoint index {index} targets a native tool")
    })?;
    set_cache_control(
        &mut tool.cache_control,
        cache_control,
        "tool breakpoint already has conflicting cache_control",
    )?;
    Ok(PromptPosition::tool(index))
}

fn mark_last_system_cache_control(
    system: &mut Option<SystemPayload>,
    cache_control: &CacheControlPayload,
) -> Result<PromptPosition, String> {
    let system_payload = system.as_mut().ok_or_else(|| {
        "Claude explicit cache breakpoint requested for system but no system prompt exists"
            .to_string()
    })?;
    let blocks = ensure_system_blocks(system_payload);
    let index = blocks
        .iter()
        .rposition(|block| !block.text.is_empty())
        .ok_or_else(|| {
            "Claude explicit cache breakpoint requested for system but all system text blocks are empty"
                .to_string()
        })?;
    set_cache_control(
        &mut blocks[index].cache_control,
        cache_control,
        "system breakpoint already has conflicting cache_control",
    )?;
    Ok(PromptPosition::system(index))
}

fn mark_system_cache_control(
    system: &mut Option<SystemPayload>,
    index: usize,
    cache_control: &CacheControlPayload,
) -> Result<PromptPosition, String> {
    let system_payload = system.as_mut().ok_or_else(|| {
        "Claude explicit cache breakpoint requested for system but no system prompt exists"
            .to_string()
    })?;
    let blocks = ensure_system_blocks(system_payload);
    let block = blocks.get_mut(index).ok_or_else(|| {
        format!("Claude explicit system breakpoint index {index} is out of range")
    })?;
    if block.text.is_empty() {
        return Err(format!(
            "Claude explicit system breakpoint index {index} targets an empty text block"
        ));
    }
    set_cache_control(
        &mut block.cache_control,
        cache_control,
        "system breakpoint already has conflicting cache_control",
    )?;
    Ok(PromptPosition::system(index))
}

fn ensure_system_blocks(system: &mut SystemPayload) -> &mut Vec<SystemTextBlock> {
    if let SystemPayload::Text(text) = system {
        *system = SystemPayload::Blocks(vec![SystemTextBlock {
            kind: "text",
            text: core::mem::take(text),
            cache_control: None,
        }]);
    }
    match system {
        SystemPayload::Blocks(blocks) => blocks,
        SystemPayload::Text(_) => panic!("System payload conversion to blocks failed"),
    }
}

fn mark_last_message_cache_control(
    messages: &mut [MessagePayload],
    cache_control: &CacheControlPayload,
) -> Result<PromptPosition, String> {
    for (message_index, message) in messages.iter_mut().enumerate().rev() {
        match &mut message.content {
            ContentPayload::Text(text) => {
                if text.is_empty() {
                    continue;
                }
                let text = core::mem::take(text);
                message.content = ContentPayload::Blocks(vec![ContentBlock::Text {
                    text,
                    cache_control: Some(cache_control.clone()),
                }]);
                return Ok(PromptPosition::message(message_index, 0));
            }
            ContentPayload::Blocks(blocks) => {
                // last_cacheable_block_index already excluded thinking blocks,
                // so this slot is always present.
                if let Some(index) = last_cacheable_block_index(blocks)
                    && let Some(slot) = block_cache_control_mut(&mut blocks[index])
                {
                    set_cache_control(
                        slot,
                        cache_control,
                        "message breakpoint already has conflicting cache_control",
                    )?;
                    return Ok(PromptPosition::message(message_index, index));
                }
            }
        }
    }
    Err("Claude explicit cache breakpoint requested for messages but no cacheable message block exists".to_string())
}

fn mark_message_cache_control(
    messages: &mut [MessagePayload],
    message_index: usize,
    block_index: usize,
    cache_control: &CacheControlPayload,
) -> Result<PromptPosition, String> {
    let message = messages.get_mut(message_index).ok_or_else(|| {
        format!("Claude explicit message breakpoint message_index {message_index} is out of range")
    })?;
    if let ContentPayload::Text(text) = &mut message.content {
        if block_index != 0 {
            return Err(format!(
                "Claude explicit message breakpoint block_index {block_index} is invalid for text-only message at index {message_index}"
            ));
        }
        if text.is_empty() {
            return Err(format!(
                "Claude explicit message breakpoint targets empty text message at index {message_index}"
            ));
        }
        let text = core::mem::take(text);
        message.content = ContentPayload::Blocks(vec![ContentBlock::Text {
            text,
            cache_control: None,
        }]);
    }

    let blocks = match &mut message.content {
        ContentPayload::Blocks(blocks) => blocks,
        ContentPayload::Text(_) => panic!("message content conversion to blocks failed"),
    };
    let block = blocks.get_mut(block_index).ok_or_else(|| {
        format!(
            "Claude explicit message breakpoint block_index {block_index} is out of range for message index {message_index}"
        )
    })?;
    if !is_cacheable_block(block) {
        return Err(format!(
            "Claude explicit message breakpoint targets a non-cacheable block at message index {message_index}, block index {block_index}"
        ));
    }
    let slot = block_cache_control_mut(block).ok_or_else(|| {
        format!(
            "Claude explicit message breakpoint targets a thinking block at message index {message_index}, block index {block_index}, which cannot carry cache_control"
        )
    })?;
    set_cache_control(
        slot,
        cache_control,
        "message breakpoint already has conflicting cache_control",
    )?;
    Ok(PromptPosition::message(message_index, block_index))
}

fn last_cacheable_block_index(blocks: &[ContentBlock]) -> Option<usize> {
    blocks.iter().rposition(|block| match block {
        ContentBlock::Text { text, .. } => !text.is_empty(),
        ContentBlock::Image { .. }
        | ContentBlock::Document { .. }
        | ContentBlock::ToolUse { .. }
        | ContentBlock::ToolResult { .. } => true,
        // Anthropic defines no cache_control on thinking blocks.
        ContentBlock::Thinking { .. } | ContentBlock::RedactedThinking { .. } => false,
    })
}

const fn is_cacheable_block(block: &ContentBlock) -> bool {
    match block {
        ContentBlock::Text { text, .. } => !text.is_empty(),
        ContentBlock::Image { .. }
        | ContentBlock::Document { .. }
        | ContentBlock::ToolUse { .. }
        | ContentBlock::ToolResult { .. } => true,
        ContentBlock::Thinking { .. } | ContentBlock::RedactedThinking { .. } => false,
    }
}

/// Returns `None` for blocks that have no `cache_control` field at all.
///
/// Callers reach this only after [`is_cacheable_block`], so a `None` here means
/// a caller skipped that check rather than a user error.
const fn block_cache_control_mut(
    block: &mut ContentBlock,
) -> Option<&mut Option<CacheControlPayload>> {
    match block {
        ContentBlock::Text { cache_control, .. }
        | ContentBlock::Image { cache_control, .. }
        | ContentBlock::Document { cache_control, .. }
        | ContentBlock::ToolUse { cache_control, .. }
        | ContentBlock::ToolResult { cache_control, .. } => Some(cache_control),
        ContentBlock::Thinking { .. } | ContentBlock::RedactedThinking { .. } => None,
    }
}

const fn block_cache_control(block: &ContentBlock) -> Option<&CacheControlPayload> {
    match block {
        ContentBlock::Text { cache_control, .. }
        | ContentBlock::Image { cache_control, .. }
        | ContentBlock::Document { cache_control, .. }
        | ContentBlock::ToolUse { cache_control, .. }
        | ContentBlock::ToolResult { cache_control, .. } => cache_control.as_ref(),
        ContentBlock::Thinking { .. } | ContentBlock::RedactedThinking { .. } => None,
    }
}

fn set_cache_control(
    slot: &mut Option<CacheControlPayload>,
    expected: &CacheControlPayload,
    mismatch_error: &str,
) -> Result<(), String> {
    if let Some(current) = slot {
        if current.kind != expected.kind || current.ttl != expected.ttl {
            return Err(mismatch_error.to_string());
        }
        return Ok(());
    }
    *slot = Some(expected.clone());
    Ok(())
}

/// Converts a typed attachment into a Claude media source.
async fn parse_media_source(attachment: &Attachment) -> Result<MediaSource, String> {
    let url = attachment.url();
    let media_type = attachment.media_type().as_ref();
    match url.scheme() {
        "data" => {
            let after_data = url
                .as_str()
                .strip_prefix("data:")
                .ok_or_else(|| "attachment data URL is malformed".to_string())?;
            let (header, data) = after_data
                .split_once(',')
                .ok_or_else(|| "attachment data URL is missing its payload".to_string())?;
            let encoded_media_type = header
                .strip_suffix(";base64")
                .ok_or_else(|| "attachment data URL must use base64 encoding".to_string())?;
            if encoded_media_type != media_type {
                return Err(format!(
                    "attachment MIME type '{media_type}' does not match data URL MIME type '{encoded_media_type}'"
                ));
            }
            Ok(MediaSource::Base64 {
                media_type: media_type.to_string(),
                data: data.to_string(),
            })
        }
        // wasm32 has no filesystem, and CI builds this crate for it with -D warnings.
        #[cfg(target_arch = "wasm32")]
        "file" => {
            Err("Claude attachments from file:// URLs are not supported on wasm32".to_string())
        }
        #[cfg(not(target_arch = "wasm32"))]
        "file" => {
            let path = url
                .to_file_path()
                .map_err(|()| "attachment file URL could not be converted to a path".to_string())?;
            let data = async_fs::read(&path).await.map_err(|error| {
                format!("failed to read attachment '{}': {error}", path.display())
            })?;
            Ok(MediaSource::Base64 {
                media_type: media_type.to_string(),
                data: base64::engine::general_purpose::STANDARD.encode(data),
            })
        }
        "http" | "https" => Ok(MediaSource::Url {
            url: url.as_str().to_string(),
        }),
        scheme => Err(format!(
            "Claude does not support attachment URL scheme '{scheme}'"
        )),
    }
}

/// Flatten message content.
fn flatten_content(message: &Message) -> String {
    message.content().to_owned()
}

const fn custom_tool(tool: &ToolPayload) -> Option<&CustomToolPayload> {
    match tool {
        ToolPayload::Custom(tool) => Some(tool),
        ToolPayload::Native(_) => None,
    }
}

const fn custom_tool_mut(tool: &mut ToolPayload) -> Option<&mut CustomToolPayload> {
    match tool {
        ToolPayload::Custom(tool) => Some(tool),
        ToolPayload::Native(_) => None,
    }
}

/// Convert aither tool definitions to Claude format.
pub fn convert_tools(definitions: &[ToolDefinition]) -> Vec<ToolPayload> {
    definitions
        .iter()
        .map(|tool| {
            ToolPayload::Custom(CustomToolPayload {
                name: tool.name().to_string(),
                description: tool.description().to_string(),
                input_schema: tool.arguments_openai_schema(),
                cache_control: None,
            })
        })
        .collect()
}

pub fn convert_native_tools(tools: &ClaudeNativeTools) -> Vec<ToolPayload> {
    let mut payload = Vec::new();
    if tools.web_search {
        payload.push(ToolPayload::Native(NativeToolPayload {
            kind: "web_search_20260209",
            name: "web_search",
            max_characters: None,
        }));
    }
    if tools.web_fetch {
        payload.push(ToolPayload::Native(NativeToolPayload {
            kind: "web_fetch_20260209",
            name: "web_fetch",
            max_characters: None,
        }));
    }
    if tools.code_execution {
        payload.push(ToolPayload::Native(NativeToolPayload {
            kind: "code_execution_20260120",
            name: "code_execution",
            max_characters: None,
        }));
    }
    if tools.bash {
        payload.push(ToolPayload::Native(NativeToolPayload {
            kind: "bash_20250124",
            name: "bash",
            max_characters: None,
        }));
    }
    if let Some(text_editor) = tools.text_editor {
        payload.push(ToolPayload::Native(NativeToolPayload {
            kind: "text_editor_20250728",
            name: "str_replace_based_edit_tool",
            max_characters: text_editor.max_characters,
        }));
    }
    payload
}

pub fn filter_tool_definitions(
    definitions: Vec<ToolDefinition>,
    choice: &ToolChoice,
) -> Vec<ToolDefinition> {
    match choice {
        ToolChoice::None => Vec::new(),
        ToolChoice::Exact(name) => definitions
            .into_iter()
            .filter(|tool| tool.name() == name)
            .collect(),
        ToolChoice::Auto | ToolChoice::Required => definitions,
    }
}

pub fn tool_choice_payload(
    choice: &ToolChoice,
    has_tools: bool,
    parallel_tool_calls: Option<bool>,
) -> Option<ToolChoicePayload> {
    if !has_tools {
        return None;
    }
    // Anthropic states the negative: the wire flag disables parallelism, while
    // the portable parameter enables it.
    let disable_parallel_tool_use = parallel_tool_calls.map(|enabled| !enabled);
    match choice {
        ToolChoice::None => Some(ToolChoicePayload::None),
        ToolChoice::Auto => Some(ToolChoicePayload::Auto {
            disable_parallel_tool_use,
        }),
        ToolChoice::Required => Some(ToolChoicePayload::Any {
            disable_parallel_tool_use,
        }),
        ToolChoice::Exact(name) => Some(ToolChoicePayload::Tool {
            name: name.clone(),
            disable_parallel_tool_use,
        }),
    }
}

#[cfg(test)]
#[allow(clippy::match_wildcard_for_single_variants)]
mod tests {
    use super::*;
    use aither_core::llm::{
        Attachment, ReasoningState, ToolCall,
        model::{
            ClaudeCacheBreakpointTarget, ClaudeExplicitCacheBreakpoint,
            ClaudeExplicitCacheBreakpoints, ClaudePromptCache, ClaudePromptCacheStrategy,
            ClaudePromptCacheTtl, Parameters, ToolChoice,
        },
    };

    /// The serialized system prompt and messages of a conversation.
    async fn wire(messages: &[Message]) -> (String, Vec<String>) {
        let (system, encoded) = to_claude_messages(messages)
            .await
            .expect("encode Claude messages");
        (
            serde_json::to_string(&system).expect("system serializes"),
            encoded
                .iter()
                .map(|message| serde_json::to_string(message).expect("message serializes"))
                .collect(),
        )
    }

    /// An effort change goes as an effort-only system message after the
    /// earlier messages, which serialize byte for byte as before; the
    /// request-level effort is the caller's, unchanged.
    #[tokio::test]
    async fn an_effort_update_is_an_effort_only_system_message_after_an_unchanged_prefix() {
        let before = vec![
            Message::system("You are terse."),
            Message::user("Plan the migration."),
            Message::assistant("Here is the plan."),
        ];
        let mut after = before.clone();
        after.push(Message::configuration(ReasoningEffort::Low));
        after.push(Message::user("Now rename the config file."));

        let (system_before, messages_before) = wire(&before).await;
        let (system_after, messages_after) = wire(&after).await;
        assert_eq!(
            system_before, system_after,
            "the system prompt is unchanged"
        );
        assert_eq!(
            messages_before[..],
            messages_after[..messages_before.len()],
            "earlier messages are byte-identical"
        );
        assert_eq!(
            messages_after[messages_before.len()],
            r#"{"role":"system","content":[],"output_config":{"effort":"low"}}"#
        );
    }

    /// Clearing the effort after a Low update sends the model's documented
    /// default as a new effort-only message, which overrides Low; every
    /// earlier message serializes byte for byte as before.
    #[tokio::test]
    async fn clearing_after_a_low_update_sends_the_models_default() {
        let default = aither_models::default_reasoning_effort("claude-opus-5-5")
            .expect("Claude Opus 5.5 has a documented default");
        let low = vec![
            Message::user("Plan the migration."),
            Message::assistant("Here is the plan."),
            Message::configuration(ReasoningEffort::Low),
            Message::user("Rename the config file."),
            Message::assistant("Renamed."),
        ];
        let mut cleared = low.clone();
        cleared.push(Message::configuration(default));
        cleared.push(Message::user("Now review the whole migration."));

        let (_, before) = wire(&low).await;
        let (_, after) = wire(&cleared).await;
        assert_eq!(
            before[..],
            after[..before.len()],
            "earlier bytes are unchanged"
        );
        assert_eq!(
            after[before.len()],
            r#"{"role":"system","content":[],"output_config":{"effort":"medium"}}"#,
            "the update to the default follows, overriding Low"
        );
    }

    #[test]
    fn an_effort_update_cannot_turn_thinking_off_or_go_below_low() {
        assert!(MessagePayload::effort_update(ReasoningEffort::None).is_err());
        assert!(MessagePayload::effort_update(ReasoningEffort::Minimal).is_err());
    }

    #[tokio::test]
    async fn assistant_tool_calls_are_encoded_as_tool_use_blocks() {
        let messages = vec![Message::assistant_with_tool_calls(
            "Working on it",
            vec![ToolCall {
                reasoning_state: None,
                id: "call_1".to_string(),
                name: "lookup".to_string(),
                arguments: serde_json::json!({"q":"rust"}),
            }],
        )];
        let (_, encoded) = to_claude_messages(&messages)
            .await
            .expect("encode Claude messages");
        assert_eq!(encoded.len(), 1);
        assert_eq!(encoded[0].role, "assistant");
        match &encoded[0].content {
            ContentPayload::Blocks(blocks) => {
                assert_eq!(blocks.len(), 2);
                assert!(matches!(blocks[0], ContentBlock::Text { .. }));
                assert!(matches!(blocks[1], ContentBlock::ToolUse { .. }));
            }
            other @ ContentPayload::Text(_) => {
                panic!("expected assistant blocks payload, got: {other:?}")
            }
        }
    }

    #[tokio::test]
    async fn tool_message_is_encoded_as_tool_result_block() {
        let messages = vec![Message::tool("call_9", "{\"ok\":true}")];
        let (_, encoded) = to_claude_messages(&messages)
            .await
            .expect("encode Claude messages");
        assert_eq!(encoded.len(), 1);
        assert_eq!(encoded[0].role, "user");
        match &encoded[0].content {
            ContentPayload::Blocks(blocks) => {
                assert_eq!(blocks.len(), 1);
                match &blocks[0] {
                    ContentBlock::ToolResult {
                        tool_use_id,
                        content,
                        ..
                    } => {
                        assert_eq!(tool_use_id, "call_9");
                        assert_eq!(content, "{\"ok\":true}");
                    }
                    other => panic!("expected tool_result block, got: {other:?}"),
                }
            }
            other @ ContentPayload::Text(_) => {
                panic!("expected user blocks payload, got: {other:?}")
            }
        }
    }

    #[tokio::test]
    async fn image_and_pdf_attachments_use_distinct_blocks() {
        let image = Attachment::new(
            "data:image/png;base64,AA==".parse().expect("image URL"),
            "image/png".parse().expect("image MIME"),
        );
        let pdf = Attachment::new(
            "https://platform.claude.com/docs/en/build-with-claude/pdf-support/sample.pdf"
                .parse()
                .expect("PDF URL"),
            "application/pdf".parse().expect("PDF MIME"),
        );
        let messages = vec![Message::user("inspect").with_attachments([image, pdf])];
        let (_, encoded) = to_claude_messages(&messages)
            .await
            .expect("encode Claude attachments");
        let ContentPayload::Blocks(blocks) = &encoded[0].content else {
            panic!("expected Claude content blocks");
        };
        assert!(matches!(blocks[0], ContentBlock::Image { .. }));
        assert!(matches!(blocks[1], ContentBlock::Document { .. }));
        assert!(matches!(blocks[2], ContentBlock::Text { .. }));
    }

    #[tokio::test]
    async fn audio_attachment_fails_instead_of_becoming_an_image() {
        let audio = Attachment::new(
            "data:audio/wav;base64,AA==".parse().expect("audio URL"),
            "audio/wav".parse().expect("audio MIME"),
        );
        let messages = vec![Message::user("listen").with_attachment(audio)];
        let error = to_claude_messages(&messages)
            .await
            .expect_err("Claude audio input must fail");
        assert!(error.contains("does not support attachment MIME type"));
    }

    #[test]
    fn required_tool_choice_maps_to_any() {
        let payload = tool_choice_payload(&ToolChoice::Required, true, None)
            .expect("required should create payload");
        let json = serde_json::to_value(payload).expect("serialize tool choice");
        assert_eq!(json["type"], "any");
    }

    #[test]
    fn exact_tool_choice_maps_to_named_tool() {
        let payload = tool_choice_payload(&ToolChoice::Exact("search".to_string()), true, None)
            .expect("exact should create payload");
        let json = serde_json::to_value(payload).expect("serialize tool choice");
        assert_eq!(json["type"], "tool");
        assert_eq!(json["name"], "search");
    }

    fn tool_choice_json(choice: &ToolChoice, parallel: Option<bool>) -> serde_json::Value {
        let payload = tool_choice_payload(choice, true, parallel).expect("tool choice payload");
        serde_json::to_value(payload).expect("serialize tool choice")
    }

    /// Anthropic states the flag negatively, so the portable "enable parallel"
    /// parameter has to invert on its way to the wire.
    #[test]
    fn parallel_tool_calls_inverts_into_disable_parallel_tool_use() {
        let serialized = tool_choice_json(&ToolChoice::Auto, Some(false));
        assert_eq!(serialized["disable_parallel_tool_use"], true);

        let parallel = tool_choice_json(&ToolChoice::Required, Some(true));
        assert_eq!(parallel["disable_parallel_tool_use"], false);
    }

    /// Unset must stay off the wire entirely so Anthropic's own default applies.
    #[test]
    fn unset_parallel_tool_calls_is_omitted() {
        for choice in [
            ToolChoice::Auto,
            ToolChoice::Required,
            ToolChoice::Exact("search".to_string()),
        ] {
            let serialized = tool_choice_json(&choice, None);
            assert_eq!(
                serialized.get("disable_parallel_tool_use"),
                None,
                "{choice:?} leaked a parallelism hint"
            );
        }
    }

    #[test]
    fn exact_tool_choice_carries_the_parallelism_hint() {
        let serialized = tool_choice_json(&ToolChoice::Exact("search".to_string()), Some(false));
        assert_eq!(serialized["type"], "tool");
        assert_eq!(serialized["name"], "search");
        assert_eq!(serialized["disable_parallel_tool_use"], true);
    }

    /// Anthropic expresses "do not call tools" as a choice, not as an absent
    /// tool list, and that variant takes no parallelism hint.
    #[test]
    fn none_tool_choice_maps_to_the_none_variant() {
        let serialized = tool_choice_json(&ToolChoice::None, Some(false));
        assert_eq!(serialized["type"], "none");
        assert_eq!(serialized.get("disable_parallel_tool_use"), None);
    }

    /// The round trip that CLA-2 made impossible: state out of the response
    /// parser must come back as a replayable block, signature intact.
    #[test]
    fn thinking_state_round_trips_into_the_assistant_turn() {
        let state = ReasoningState::new(
            PROVIDER_NAME,
            serde_json::json!({
                "type": "thinking",
                "thinking": "step one",
                "signature": "sig-abc",
            })
            .to_string(),
        );
        let message = Message::assistant_with_reasoning(
            "answer",
            vec![ToolCall::new("call_1", "search", serde_json::json!({}))],
            vec![state],
        );

        let value = serde_json::to_value(build_assistant_content(&message))
            .expect("serialize assistant content");
        let blocks = value.as_array().expect("block form");

        // Anthropic requires the turn to begin with its thinking blocks.
        assert_eq!(blocks[0]["type"], "thinking");
        assert_eq!(blocks[0]["thinking"], "step one");
        assert_eq!(blocks[0]["signature"], "sig-abc");
        assert!(blocks.iter().any(|block| block["type"] == "tool_use"));
    }

    #[test]
    fn redacted_thinking_round_trips() {
        let state = ReasoningState::new(
            PROVIDER_NAME,
            serde_json::json!({"type": "redacted_thinking", "data": "cipher"}).to_string(),
        );
        let message = Message::assistant_with_reasoning("", Vec::new(), vec![state]);
        let value = serde_json::to_value(build_assistant_content(&message))
            .expect("serialize assistant content");
        assert_eq!(value[0]["type"], "redacted_thinking");
        assert_eq!(value[0]["data"], "cipher");
    }

    /// Thinking blocks are tied to the model that produced them, so state from
    /// another provider is stripped rather than replayed.
    #[test]
    fn foreign_reasoning_state_is_dropped() {
        let message = Message::assistant_with_reasoning(
            "answer",
            Vec::new(),
            vec![ReasoningState::new(
                "openai",
                serde_json::json!({"type": "reasoning", "id": "rs_1"}).to_string(),
            )],
        );
        assert!(replayed_thinking_blocks(&message).is_empty());
    }

    #[test]
    fn tool_choice_is_absent_without_tools() {
        assert!(tool_choice_payload(&ToolChoice::Auto, false, Some(false)).is_none());
    }

    fn snapshot(params: &Parameters) -> ParameterSnapshot {
        ParameterSnapshot::from(params)
    }

    /// Anthropic's effort ladder, verbatim. `minimal` is absent from it.
    #[test]
    fn effort_maps_onto_the_anthropic_ladder() {
        for (effort, expected) in [
            (ReasoningEffort::Low, "low"),
            (ReasoningEffort::Medium, "medium"),
            (ReasoningEffort::High, "high"),
            (ReasoningEffort::XHigh, "xhigh"),
            (ReasoningEffort::Max, "max"),
        ] {
            let config =
                build_output_config(&snapshot(&Parameters::default().reasoning_effort(effort)))
                    .expect("effort supported by Claude")
                    .expect("output config");
            let value = serde_json::to_value(config).expect("serialize output config");
            assert_eq!(value["effort"], expected);
        }
    }

    #[test]
    fn minimal_effort_is_rejected() {
        let error = build_output_config(&snapshot(
            &Parameters::default().reasoning_effort(ReasoningEffort::Minimal),
        ))
        .expect_err("Claude has no minimal effort");
        assert!(error.to_string().contains("no 'minimal' level"));
    }

    /// `None` is a thinking mode on Claude, not an effort level, so it must
    /// produce `thinking: {"type":"disabled"}` and no `output_config`.
    #[test]
    fn none_effort_disables_thinking_rather_than_setting_an_effort() {
        let snap = snapshot(&Parameters::default().reasoning_effort(ReasoningEffort::None));

        let thinking = build_thinking(&snap).expect("thinking payload");
        let value = serde_json::to_value(thinking).expect("serialize thinking");
        assert_eq!(value["type"], "disabled");

        assert!(
            build_output_config(&snap)
                .expect("None is supported")
                .is_none()
        );
    }

    /// Adaptive is already the model's own mode, so the only reason to send a
    /// thinking config is to ask for the text — otherwise stay off the wire.
    #[test]
    fn thinking_is_only_sent_when_the_caller_wants_the_text() {
        assert!(build_thinking(&snapshot(&Parameters::default())).is_none());

        let thinking = build_thinking(&snapshot(&Parameters::default().include_reasoning(true)))
            .expect("thinking payload");
        let value = serde_json::to_value(thinking).expect("serialize thinking");
        assert_eq!(value["type"], "adaptive");
        assert_eq!(value["display"], "summarized");
    }

    /// An effort without a request for the text means "think harder, don't show
    /// me" — which is `display: "omitted"`, and also lets the server skip
    /// streaming thinking tokens.
    #[test]
    fn effort_without_visible_text_asks_for_omitted_display() {
        let thinking = build_thinking(&snapshot(
            &Parameters::default().reasoning_effort(ReasoningEffort::High),
        ))
        .expect("thinking payload");
        let value = serde_json::to_value(thinking).expect("serialize thinking");
        assert_eq!(value["type"], "adaptive");
        assert_eq!(value["display"], "omitted");
    }

    /// The deprecated manual mode must be unrepresentable, not merely unused:
    /// it returns a 400 on every model after the 4.6 generation.
    #[test]
    fn thinking_never_serializes_a_token_budget() {
        let thinking = build_thinking(&snapshot(&Parameters::default().include_reasoning(true)))
            .expect("thinking payload");
        let value = serde_json::to_value(thinking).expect("serialize thinking");
        assert_ne!(value["type"], "enabled");
        assert_eq!(value.get("budget_tokens"), None);
    }

    #[test]
    fn parameter_snapshot_preserves_claude_cache_setting() {
        let params = Parameters::default()
            .claude_prompt_cache(ClaudePromptCache::new(ClaudePromptCacheTtl::OneHour));
        let snapshot = ParameterSnapshot::from(&params);
        assert_eq!(
            snapshot.cache,
            Some(ClaudePromptCache::new(ClaudePromptCacheTtl::OneHour))
        );
    }

    #[test]
    fn other_providers_cache_sections_do_not_hide_the_claude_breakpoints() {
        let breakpoints = ClaudeExplicitCacheBreakpoints::new(ClaudeExplicitCacheBreakpoint::new(
            ClaudeCacheBreakpointTarget::LastSystem,
        ));
        let mut params = Parameters::default()
            .prompt_cache_key("session:alpha")
            .prompt_cache_retention(aither_core::llm::model::OpenAIPromptCacheRetention::Hours24)
            .gemini_cached_content("cachedContents/abc")
            .claude_prompt_cache_explicit(ClaudePromptCacheTtl::OneHour, breakpoints);
        params.structured_outputs = true;
        let snapshot = ParameterSnapshot::from(&params);
        assert_eq!(
            snapshot.cache,
            Some(ClaudePromptCache::explicit(
                ClaudePromptCacheTtl::OneHour,
                breakpoints
            ))
        );
    }

    #[test]
    fn cache_control_payload_serializes_expected_shape() {
        let one_hour =
            CacheControlPayload::from(ClaudePromptCache::new(ClaudePromptCacheTtl::OneHour));
        let one_hour_json = serde_json::to_value(one_hour).expect("serialize one hour payload");
        assert_eq!(one_hour_json["type"], "ephemeral");
        assert_eq!(one_hour_json["ttl"], "1h");

        let short =
            CacheControlPayload::from(ClaudePromptCache::new(ClaudePromptCacheTtl::FiveMinutes));
        let short_json = serde_json::to_value(short).expect("serialize five minute payload");
        assert_eq!(short_json["type"], "ephemeral");
        assert!(short_json.get("ttl").is_none());
    }

    #[tokio::test]
    async fn multiple_system_messages_are_preserved_as_system_blocks() {
        let messages = vec![
            Message::system("Instruction A"),
            Message::system("Instruction B"),
            Message::user("Hello"),
        ];
        let (system, encoded) = to_claude_messages(&messages)
            .await
            .expect("encode Claude messages");
        assert_eq!(encoded.len(), 1);
        let system = system.expect("system payload should exist");
        match system {
            SystemPayload::Blocks(blocks) => {
                assert_eq!(blocks.len(), 2);
                assert_eq!(blocks[0].text, "Instruction A");
                assert_eq!(blocks[1].text, "Instruction B");
            }
            other @ SystemPayload::Text(_) => {
                panic!("expected system blocks payload, got: {other:?}")
            }
        }
    }

    #[test]
    fn automatic_cache_strategy_returns_top_level_cache_control() {
        let mut system = Some(SystemPayload::Text("You are helpful".to_string()));
        let mut messages = vec![MessagePayload {
            role: "user",
            output_config: None,
            content: ContentPayload::Text("Hello".to_string()),
        }];
        let mut tools = None;
        let cache = ClaudePromptCache::automatic(ClaudePromptCacheTtl::FiveMinutes);
        let top_level = apply_cache_strategy(&mut system, &mut messages, &mut tools, cache)
            .expect("automatic cache strategy should succeed");
        let top_level = top_level.expect("automatic strategy should return top-level cache");
        assert_eq!(top_level.kind, "ephemeral");
        assert!(top_level.ttl.is_none());
    }

    #[test]
    fn explicit_message_breakpoint_marks_last_message_block() {
        let mut system = None;
        let mut messages = vec![MessagePayload {
            role: "assistant",
            output_config: None,
            content: ContentPayload::Blocks(vec![ContentBlock::ToolUse {
                id: "call_1".to_string(),
                name: "search".to_string(),
                input: serde_json::json!({"q":"mars"}),
                cache_control: None,
            }]),
        }];
        let mut tools = None;
        let cache = ClaudePromptCache::new(ClaudePromptCacheTtl::OneHour).with_strategy(
            ClaudePromptCacheStrategy::Explicit(ClaudeExplicitCacheBreakpoints::messages_only()),
        );
        let top_level = apply_cache_strategy(&mut system, &mut messages, &mut tools, cache)
            .expect("explicit strategy should succeed");
        assert!(top_level.is_none());

        match &messages[0].content {
            ContentPayload::Blocks(blocks) => match &blocks[0] {
                ContentBlock::ToolUse { cache_control, .. } => {
                    let cache_control =
                        cache_control.as_ref().expect("cache control should be set");
                    assert_eq!(cache_control.kind, "ephemeral");
                    assert_eq!(cache_control.ttl, Some("1h"));
                }
                other => panic!("expected tool_use block, got: {other:?}"),
            },
            other @ ContentPayload::Text(_) => {
                panic!("expected block payload, got: {other:?}")
            }
        }
    }

    #[test]
    fn explicit_breakpoint_target_out_of_range_fails_fast() {
        let mut system = None;
        let mut messages = vec![MessagePayload {
            role: "user",
            output_config: None,
            content: ContentPayload::Text("hello".to_string()),
        }];
        let mut tools = None;
        let cache = ClaudePromptCache::explicit(
            ClaudePromptCacheTtl::FiveMinutes,
            ClaudeExplicitCacheBreakpoints::new(ClaudeExplicitCacheBreakpoint::new(
                ClaudeCacheBreakpointTarget::Message {
                    message_index: 0,
                    block_index: 1,
                },
            )),
        );
        let err = apply_cache_strategy(&mut system, &mut messages, &mut tools, cache)
            .expect_err("explicit strategy with out-of-range block index must fail");
        assert!(err.contains("block_index"));
    }

    #[test]
    fn automatic_and_explicit_strategy_sets_both_levels() {
        let mut system = Some(SystemPayload::Text("You are helpful".to_string()));
        let mut messages = vec![MessagePayload {
            role: "user",
            output_config: None,
            content: ContentPayload::Text("Tell me about Mars".to_string()),
        }];
        let mut tools = Some(vec![ToolPayload::Custom(CustomToolPayload {
            name: "search".to_string(),
            description: "search docs".to_string(),
            input_schema: serde_json::json!({"type":"object"}),
            cache_control: None,
        })]);

        let cache =
            ClaudePromptCache::automatic_with_explicit(ClaudePromptCacheTtl::FiveMinutes, {
                ClaudeExplicitCacheBreakpoints::new(ClaudeExplicitCacheBreakpoint::new(
                    ClaudeCacheBreakpointTarget::LastTool,
                ))
                .with_second(ClaudeExplicitCacheBreakpoint::new(
                    ClaudeCacheBreakpointTarget::LastSystem,
                ))
            });
        let top_level = apply_cache_strategy(&mut system, &mut messages, &mut tools, cache)
            .expect("combined strategy should succeed");
        assert!(top_level.is_some());

        let tools = tools.expect("tools should stay present");
        assert!(
            tools
                .last()
                .and_then(custom_tool)
                .and_then(|tool| tool.cache_control.as_ref())
                .is_some()
        );
    }

    #[test]
    fn mixed_ttl_requires_one_hour_before_five_minutes() {
        let mut system = Some(SystemPayload::Text("System".to_string()));
        let mut messages = vec![MessagePayload {
            role: "user",
            output_config: None,
            content: ContentPayload::Text("Hello".to_string()),
        }];
        let mut tools = Some(vec![ToolPayload::Custom(CustomToolPayload {
            name: "search".to_string(),
            description: "search docs".to_string(),
            input_schema: serde_json::json!({"type":"object"}),
            cache_control: None,
        })]);

        let breakpoints = ClaudeExplicitCacheBreakpoints::new(
            ClaudeExplicitCacheBreakpoint::new(ClaudeCacheBreakpointTarget::LastTool)
                .with_ttl(ClaudePromptCacheTtl::FiveMinutes),
        )
        .with_second(
            ClaudeExplicitCacheBreakpoint::new(ClaudeCacheBreakpointTarget::LastMessage)
                .with_ttl(ClaudePromptCacheTtl::OneHour),
        );
        let cache = ClaudePromptCache::explicit(ClaudePromptCacheTtl::FiveMinutes, breakpoints);
        let err = apply_cache_strategy(&mut system, &mut messages, &mut tools, cache)
            .expect_err("5m before 1h should fail mixed TTL ordering validation");
        assert!(err.contains("1h"));
    }

    #[test]
    fn automatic_with_full_explicit_slots_fails_when_no_overlap() {
        let mut system = Some(SystemPayload::Blocks(vec![
            SystemTextBlock {
                kind: "text",
                text: "S0".to_string(),
                cache_control: None,
            },
            SystemTextBlock {
                kind: "text",
                text: "S1".to_string(),
                cache_control: None,
            },
        ]));
        let mut messages = vec![
            MessagePayload {
                role: "assistant",
                output_config: None,
                content: ContentPayload::Blocks(vec![ContentBlock::ToolUse {
                    id: "call_1".to_string(),
                    name: "search".to_string(),
                    input: serde_json::json!({"q":"mars"}),
                    cache_control: None,
                }]),
            },
            MessagePayload {
                role: "user",
                output_config: None,
                content: ContentPayload::Text("Final user message".to_string()),
            },
        ];
        let mut tools = Some(vec![ToolPayload::Custom(CustomToolPayload {
            name: "search".to_string(),
            description: "search docs".to_string(),
            input_schema: serde_json::json!({"type":"object"}),
            cache_control: None,
        })]);

        let breakpoints = ClaudeExplicitCacheBreakpoints::new(ClaudeExplicitCacheBreakpoint::new(
            ClaudeCacheBreakpointTarget::Tool(0),
        ))
        .with_second(ClaudeExplicitCacheBreakpoint::new(
            ClaudeCacheBreakpointTarget::System(0),
        ))
        .with_third(ClaudeExplicitCacheBreakpoint::new(
            ClaudeCacheBreakpointTarget::System(1),
        ))
        .with_fourth(ClaudeExplicitCacheBreakpoint::new(
            ClaudeCacheBreakpointTarget::Message {
                message_index: 0,
                block_index: 0,
            },
        ));
        let cache = ClaudePromptCache::automatic_with_explicit(
            ClaudePromptCacheTtl::FiveMinutes,
            breakpoints,
        );
        let err = apply_cache_strategy(&mut system, &mut messages, &mut tools, cache)
            .expect_err("automatic caching should fail when all 4 explicit slots are occupied");
        assert!(err.contains("at most 4 cache breakpoints"));
    }
}