meerkat-client 0.3.3

LLM provider abstraction for Meerkat
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
//! Anthropic Claude API client
//!
//! Implements the LlmClient trait for Anthropic's Claude API.

use crate::error::LlmError;
use crate::types::{LlmClient, LlmDoneOutcome, LlmEvent, LlmRequest};
use async_trait::async_trait;
use futures::{Stream, StreamExt};
use meerkat_core::schema::{CompiledSchema, SchemaError};
use meerkat_core::{Message, OutputSchema, StopReason, Usage};
use serde::Deserialize;
use serde_json::Value;
use std::pin::Pin;
use std::time::Duration;

/// Default connect timeout
const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
/// Default request timeout
const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(300);
/// Default pool idle timeout
const DEFAULT_POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(90);
/// SSE buffer capacity to reduce reallocations
const SSE_BUFFER_CAPACITY: usize = 4096;

/// Client for Anthropic API
pub struct AnthropicClient {
    api_key: String,
    base_url: String,
    http: reqwest::Client,
    connect_timeout: Duration,
    request_timeout: Duration,
    pool_idle_timeout: Duration,
}

/// Builder for AnthropicClient
pub struct AnthropicClientBuilder {
    api_key: String,
    base_url: String,
    connect_timeout: Duration,
    request_timeout: Duration,
    pool_idle_timeout: Duration,
}

impl AnthropicClientBuilder {
    pub fn new(api_key: String) -> Self {
        Self {
            api_key,
            base_url: "https://api.anthropic.com".to_string(),
            connect_timeout: DEFAULT_CONNECT_TIMEOUT,
            request_timeout: DEFAULT_REQUEST_TIMEOUT,
            pool_idle_timeout: DEFAULT_POOL_IDLE_TIMEOUT,
        }
    }

    /// Set custom base URL
    pub fn base_url(mut self, url: String) -> Self {
        self.base_url = url;
        self
    }

    /// Set connection timeout
    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    /// Set request timeout
    pub fn request_timeout(mut self, timeout: Duration) -> Self {
        self.request_timeout = timeout;
        self
    }

    /// Set pool idle timeout
    pub fn pool_idle_timeout(mut self, timeout: Duration) -> Self {
        self.pool_idle_timeout = timeout;
        self
    }

    /// Build the client with configured HTTP settings
    pub fn build(self) -> Result<AnthropicClient, LlmError> {
        let base_url = self.base_url;
        let connect_timeout = self.connect_timeout;
        let request_timeout = self.request_timeout;
        let pool_idle_timeout = self.pool_idle_timeout;
        let http = crate::http::build_http_client_for_base_url(
            reqwest::Client::builder()
                .connect_timeout(connect_timeout)
                .timeout(request_timeout)
                .pool_idle_timeout(pool_idle_timeout)
                .pool_max_idle_per_host(4)
                .tcp_keepalive(Duration::from_secs(30)),
            &base_url,
        )?;

        Ok(AnthropicClient {
            api_key: self.api_key,
            base_url,
            http,
            connect_timeout,
            request_timeout,
            pool_idle_timeout,
        })
    }
}

impl AnthropicClient {
    /// Create a new Anthropic client with the given API key and default HTTP settings
    pub fn new(api_key: String) -> Result<Self, LlmError> {
        AnthropicClientBuilder::new(api_key).build()
    }

    /// Create a builder for more control over HTTP configuration
    pub fn builder(api_key: String) -> AnthropicClientBuilder {
        AnthropicClientBuilder::new(api_key)
    }

    /// Create from environment variable ANTHROPIC_API_KEY
    pub fn from_env() -> Result<Self, LlmError> {
        let api_key = std::env::var("RKAT_ANTHROPIC_API_KEY")
            .or_else(|_| std::env::var("ANTHROPIC_API_KEY"))
            .map_err(|_| LlmError::InvalidApiKey)?;
        Self::new(api_key)
    }

    /// Set custom base URL
    pub fn with_base_url(mut self, url: String) -> Self {
        if let Ok(http) = crate::http::build_http_client_for_base_url(
            reqwest::Client::builder()
                .connect_timeout(self.connect_timeout)
                .timeout(self.request_timeout)
                .pool_idle_timeout(self.pool_idle_timeout)
                .pool_max_idle_per_host(4)
                .tcp_keepalive(Duration::from_secs(30)),
            &url,
        ) {
            self.http = http;
        }
        self.base_url = url;
        self
    }

    /// Build request body for Anthropic API
    fn build_request_body(&self, request: &LlmRequest) -> Result<Value, LlmError> {
        let mut messages = Vec::new();
        let mut system_prompt = None;

        for msg in &request.messages {
            match msg {
                Message::System(s) => {
                    system_prompt = Some(s.content.clone());
                }
                Message::User(u) => {
                    messages.push(serde_json::json!({
                        "role": "user",
                        "content": u.content
                    }));
                }
                Message::Assistant(a) => {
                    // Legacy format: flat content + tool_calls
                    let mut content = Vec::new();

                    if !a.content.is_empty() {
                        content.push(serde_json::json!({
                            "type": "text",
                            "text": a.content
                        }));
                    }

                    for tc in &a.tool_calls {
                        content.push(serde_json::json!({
                            "type": "tool_use",
                            "id": tc.id,
                            "name": tc.name,
                            "input": tc.args
                        }));
                    }

                    messages.push(serde_json::json!({
                        "role": "assistant",
                        "content": content
                    }));
                }
                Message::BlockAssistant(a) => {
                    // New format: ordered blocks with thinking support
                    let mut content = Vec::new();

                    for block in &a.blocks {
                        match block {
                            meerkat_core::AssistantBlock::Text { text, .. } => {
                                // Anthropic text blocks don't use meta
                                if !text.is_empty() {
                                    content.push(serde_json::json!({
                                        "type": "text",
                                        "text": text
                                    }));
                                }
                            }
                            meerkat_core::AssistantBlock::Reasoning { text, meta } => {
                                match meta.as_deref() {
                                    Some(meerkat_core::ProviderMeta::Anthropic { signature }) => {
                                        // Regular thinking block with signature for replay
                                        content.push(serde_json::json!({
                                            "type": "thinking",
                                            "thinking": text,
                                            "signature": signature
                                        }));
                                    }
                                    Some(meerkat_core::ProviderMeta::AnthropicRedacted {
                                        data,
                                    }) => {
                                        // Redacted thinking — pass encrypted data verbatim
                                        content.push(serde_json::json!({
                                            "type": "redacted_thinking",
                                            "data": data
                                        }));
                                    }
                                    Some(meerkat_core::ProviderMeta::AnthropicCompaction {
                                        content: summary,
                                    }) => {
                                        // Compaction summary — replaces prior context
                                        content.push(serde_json::json!({
                                            "type": "compaction",
                                            "content": summary
                                        }));
                                    }
                                    _ => {
                                        tracing::warn!(
                                            "thinking block missing Anthropic signature, skipping"
                                        );
                                        continue;
                                    }
                                }
                            }
                            meerkat_core::AssistantBlock::ToolUse { id, name, args, .. } => {
                                // Parse RawValue to Value for JSON serialization
                                let args_value: Value = serde_json::from_str(args.get())
                                    .unwrap_or_else(|_| serde_json::json!({}));
                                content.push(serde_json::json!({
                                    "type": "tool_use",
                                    "id": id,
                                    "name": name,
                                    "input": args_value
                                }));
                            }
                            // Handle future block types (non_exhaustive pattern)
                            _ => {}
                        }
                    }

                    messages.push(serde_json::json!({
                        "role": "assistant",
                        "content": content
                    }));
                }
                Message::ToolResults { results } => {
                    let mut content = Vec::new();

                    for r in results {
                        content.push(serde_json::json!({
                            "type": "tool_result",
                            "tool_use_id": r.tool_use_id,
                            "content": r.content,
                            "is_error": r.is_error
                        }));
                    }

                    messages.push(serde_json::json!({
                        "role": "user",
                        "content": content
                    }));
                }
            }
        }

        let mut body = serde_json::json!({
            "model": request.model,
            "max_tokens": request.max_tokens,
            "messages": messages,
            "stream": true
        });

        if let Some(system) = system_prompt {
            body["system"] = Value::String(system);
        }

        if let Some(temp) = request.temperature {
            if let Some(num) = serde_json::Number::from_f64(temp as f64) {
                body["temperature"] = Value::Number(num);
            }
        }

        if !request.tools.is_empty() {
            let tools: Vec<Value> = request
                .tools
                .iter()
                .map(|t| {
                    serde_json::json!({
                        "name": t.name,
                        "description": t.description,
                        "input_schema": t.input_schema
                    })
                })
                .collect();
            body["tools"] = Value::Array(tools);
        }

        // Extract provider-specific params
        if let Some(ref params) = request.provider_params {
            // Handle thinking config from three formats:
            // 1. Adaptive (Opus 4.6): {"thinking": {"type": "adaptive"}}
            // 2. Legacy flat format: {"thinking_budget": 10000}
            // 3. Typed enabled: {"thinking": {"type": "enabled", "budget_tokens": 10000}}
            if let Some(thinking) = params.get("thinking") {
                if thinking.get("type").and_then(|t| t.as_str()) == Some("adaptive") {
                    // Opus 4.6 adaptive thinking — pass through directly
                    body["thinking"] = serde_json::json!({"type": "adaptive"});
                } else if let Some(budget) = thinking.get("budget_tokens").and_then(|v| v.as_u64())
                {
                    // Explicit enabled format with budget
                    body["thinking"] = serde_json::json!({
                        "type": "enabled",
                        "budget_tokens": budget
                    });
                }
            } else if let Some(budget) = params.get("thinking_budget").and_then(|v| v.as_u64()) {
                // Legacy flat format
                body["thinking"] = serde_json::json!({
                    "type": "enabled",
                    "budget_tokens": budget
                });
            }

            // top_k must be a number - coerce strings from CLI --param
            if let Some(top_k) = params.get("top_k") {
                let numeric_top_k = match top_k {
                    Value::Number(_) => Some(top_k.clone()),
                    Value::String(s) => s.parse::<u64>().ok().map(|n| Value::Number(n.into())),
                    _ => None,
                };
                if let Some(v) = numeric_top_k {
                    body["top_k"] = v;
                }
            }

            // Handle effort parameter (GA on Opus 4.6, no beta header needed)
            // Format: {"effort": "low"|"medium"|"high"|"max"}
            if let Some(effort) = params.get("effort").and_then(|v| v.as_str()) {
                // Ensure output_config exists (may already be set by structured output below)
                if body.get("output_config").is_none() {
                    body["output_config"] = serde_json::json!({});
                }
                body["output_config"]["effort"] = Value::String(effort.to_string());
            }

            // Handle structured output configuration
            // Format: {"structured_output": {"schema": {...}, "name": "output", "strict": true}}
            if let Some(structured) = params.get("structured_output") {
                let output_schema: OutputSchema = serde_json::from_value(structured.clone())
                    .map_err(|e| LlmError::InvalidRequest {
                        message: format!("Invalid structured_output schema: {e}"),
                    })?;
                let compiled =
                    self.compile_schema(&output_schema)
                        .map_err(|e| LlmError::InvalidRequest {
                            message: e.to_string(),
                        })?;
                // Ensure output_config exists (may already have effort set above)
                if body.get("output_config").is_none() {
                    body["output_config"] = serde_json::json!({});
                }
                body["output_config"]["format"] = serde_json::json!({
                    "type": "json_schema",
                    "schema": compiled.schema
                });
            }

            // Handle inference_geo for data residency (Opus 4.6+)
            // Format: {"inference_geo": "us"} or {"inference_geo": "global"}
            if let Some(geo) = params.get("inference_geo").and_then(|v| v.as_str()) {
                body["inference_geo"] = Value::String(geo.to_string());
            }

            // Handle compaction (Opus 4.6, beta)
            // Format: {"compaction": "auto"} or {"compaction": {"trigger": 150000}}
            if let Some(compaction) = params.get("compaction") {
                if compaction.as_str() == Some("auto") {
                    body["context_management"] = serde_json::json!({
                        "edits": [{"type": "compact_20260112"}]
                    });
                } else if compaction.is_object() {
                    // Allow passing full compaction config: {"trigger": 150000, "instructions": "..."}
                    let mut edit = serde_json::json!({"type": "compact_20260112"});
                    if let Some(obj) = compaction.as_object() {
                        for (k, v) in obj {
                            edit[k] = v.clone();
                        }
                    }
                    body["context_management"] = serde_json::json!({
                        "edits": [edit]
                    });
                }
            }
        }

        Ok(body)
    }

    /// Parse an SSE event from the response
    fn parse_sse_line(line: &str) -> Option<AnthropicEvent> {
        if let Some(data) = Self::strip_data_prefix(line) {
            serde_json::from_str(data).ok()
        } else {
            None
        }
    }

    fn strip_data_prefix(line: &str) -> Option<&str> {
        line.strip_prefix("data: ")
            .or_else(|| line.strip_prefix("data:"))
            .map(str::trim_start)
    }

    fn map_stop_reason(reason: &str) -> StopReason {
        match reason {
            "end_turn" => StopReason::EndTurn,
            "tool_use" => StopReason::ToolUse,
            "max_tokens" => StopReason::MaxTokens,
            "stop_sequence" => StopReason::StopSequence,
            "content_filter" => StopReason::ContentFilter,
            _ => StopReason::EndTurn,
        }
    }
}

/// Recursively add `additionalProperties: false` to all object schemas that
/// have `properties` but no explicit `additionalProperties`.
///
/// This is required by Anthropic's structured output API.
fn ensure_additional_properties_false(value: &mut Value) {
    match value {
        Value::Object(obj) => {
            let is_object_type = match obj.get("type") {
                Some(Value::String(t)) => t == "object",
                Some(Value::Array(types)) => types.iter().any(|t| t.as_str() == Some("object")),
                _ => obj.contains_key("properties"),
            };
            if is_object_type
                && obj.contains_key("properties")
                && !obj.contains_key("additionalProperties")
            {
                obj.insert("additionalProperties".to_string(), Value::Bool(false));
            }

            let keys: Vec<String> = obj.keys().cloned().collect();
            for key in keys {
                if let Some(child) = obj.get_mut(&key) {
                    ensure_additional_properties_false(child);
                }
            }
        }
        Value::Array(items) => {
            for item in items.iter_mut() {
                ensure_additional_properties_false(item);
            }
        }
        _ => {}
    }
}

fn merge_usage(target: &mut Usage, update: &AnthropicUsage) {
    if let Some(v) = update.input_tokens {
        target.input_tokens = v;
    }
    if let Some(v) = update.output_tokens {
        target.output_tokens = v;
    }
    if let Some(v) = update.cache_creation_input_tokens {
        target.cache_creation_tokens = Some(v);
    }
    if let Some(v) = update.cache_read_input_tokens {
        target.cache_read_tokens = Some(v);
    }
}

#[async_trait]
impl LlmClient for AnthropicClient {
    fn stream<'a>(
        &'a self,
        request: &'a LlmRequest,
    ) -> Pin<Box<dyn Stream<Item = Result<LlmEvent, LlmError>> + Send + 'a>> {
        let inner: Pin<Box<dyn Stream<Item = Result<LlmEvent, LlmError>> + Send + 'a>> = Box::pin(
            async_stream::try_stream! {
                let body = self.build_request_body(request)?;

                // Collect beta headers based on request features
                let mut betas = Vec::new();

                // Legacy thinking (type: "enabled") requires interleaved-thinking header
                // Adaptive thinking (Opus 4.6) does NOT need this header
                let thinking_type = body.get("thinking")
                    .and_then(|t| t.get("type"))
                    .and_then(|t| t.as_str());
                if thinking_type == Some("enabled") {
                    betas.push("interleaved-thinking-2025-05-14");
                }

                // Structured output format requires beta header
                if body.get("output_config").and_then(|c| c.get("format")).is_some() {
                    betas.push("structured-outputs-2025-11-13");
                }

                // 1M context window (opt-in via provider_params)
                if let Some(ref params) = request.provider_params {
                    if params.get("context").and_then(|v| v.as_str()) == Some("1m") {
                        betas.push("context-1m-2025-08-07");
                    }
                }

                // Compaction API (beta)
                if body.get("context_management").is_some() {
                    betas.push("compact-2026-01-12");
                }

                let mut req = self.http
                    .post(format!("{}/v1/messages", self.base_url))
                    .header("x-api-key", &self.api_key)
                    .header("anthropic-version", "2023-06-01")
                    .header("Content-Type", "application/json");

                if !betas.is_empty() {
                    req = req.header("anthropic-beta", betas.join(","));
                }

                let response = req
                    .json(&body)
                    .send()
                    .await
                    .map_err(|_| LlmError::NetworkTimeout {
                        duration_ms: 30000,
                    })?;

                let status_code = response.status().as_u16();
                let stream_result = if (200..=299).contains(&status_code) {
                    Ok(response.bytes_stream())
                } else {
                    let text = response.text().await.unwrap_or_default();
                    Err(LlmError::from_http_status(status_code, text))
                };
                let mut stream = stream_result?;
                let mut buffer = String::with_capacity(SSE_BUFFER_CAPACITY);
                let mut current_tool_id: Option<String> = None;
                let mut current_tool_name: Option<String> = None;
                let mut accumulated_tool_args = String::new();
                let mut current_block_type: Option<String> = None;
                let mut current_thinking_signature: Option<String> = None;
                let mut last_stop_reason: Option<StopReason> = None;
                let mut usage = Usage::default();
                let mut saw_done = false;
                let mut saw_event = false;

                macro_rules! handle_event {
                    ($event:expr) => {
                        match $event.event_type.as_str() {
                            "content_block_delta" => {
                                if let Some(delta) = $event.delta {
                                    match delta.delta_type.as_str() {
                                        "text_delta" => {
                                            if let Some(text) = delta.text {
                                                saw_event = true;
                                                yield LlmEvent::TextDelta { delta: text, meta: None };
                                            }
                                        }
                                        "thinking_delta" => {
                                            // Emit incremental thinking content
                                            if let Some(text) = delta.thinking {
                                                saw_event = true;
                                                yield LlmEvent::ReasoningDelta { delta: text };
                                            }
                                        }
                                        "signature_delta" => {
                                            // Signature arrives as separate delta before content_block_stop
                                            if let Some(sig) = delta.signature {
                                                saw_event = true;
                                                current_thinking_signature = Some(sig);
                                            }
                                        }
                                        "input_json_delta" => {
                                            if let Some(partial_json) = delta.partial_json {
                                                accumulated_tool_args.push_str(&partial_json);
                                                saw_event = true;
                                                yield LlmEvent::ToolCallDelta {
                                                    id: current_tool_id.clone().unwrap_or_default(),
                                                    name: None,
                                                    args_delta: partial_json,
                                                };
                                            }
                                        }
                                        "compaction_delta" => {
                                            // Compaction summary arrives as single delta — emit as Reasoning with compaction meta
                                            if let Some(content) = delta.content {
                                                saw_event = true;
                                                yield LlmEvent::ReasoningComplete {
                                                    text: String::new(),
                                                    meta: Some(Box::new(meerkat_core::ProviderMeta::AnthropicCompaction { content })),
                                                };
                                            }
                                        }
                                        _ => {}
                                    }
                                }
                            }
                            "content_block_start" => {
                                if let Some(content_block) = $event.content_block {
                                    current_block_type = Some(content_block.block_type.clone());
                                    match content_block.block_type.as_str() {
                                        "thinking" => {
                                            // Start of thinking block
                                            // Signature may already be present or arrive via signature_delta
                                            current_thinking_signature = content_block.signature;
                                        }
                                        "redacted_thinking" => {
                                            // Redacted by safety systems — emit as Reasoning with redacted meta
                                            if let Some(data) = content_block.data {
                                                saw_event = true;
                                                yield LlmEvent::ReasoningComplete {
                                                    text: String::new(),
                                                    meta: Some(Box::new(meerkat_core::ProviderMeta::AnthropicRedacted { data })),
                                                };
                                            }
                                        }
                                        "compaction" => {
                                            // Compaction block start — content arrives via compaction_delta
                                        }
                                        "tool_use" => {
                                            let id = content_block.id.unwrap_or_default();
                                            current_tool_id = Some(id.clone());
                                            current_tool_name = content_block.name.clone();
                                            accumulated_tool_args.clear();
                                            saw_event = true;
                                            yield LlmEvent::ToolCallDelta {
                                                id,
                                                name: content_block.name,
                                                args_delta: String::new(),
                                            };
                                        }
                                        _ => {}
                                    }
                                }
                            }
                            "content_block_stop" => {
                                // Emit complete events based on block type
                                match current_block_type.as_deref() {
                                    Some("thinking") => {
                                        // Emit ReasoningComplete with Anthropic signature
                                        let meta = current_thinking_signature
                                            .take()
                                            .map(|sig| Box::new(meerkat_core::ProviderMeta::Anthropic { signature: sig }));
                                        yield LlmEvent::ReasoningComplete {
                                            text: String::new(), // Text was already streamed via deltas
                                            meta,
                                        };
                                    }
                                    Some("tool_use") => {
                                        // Finalize tool call: assemble accumulated
                                        // JSON args from deltas into a complete event.
                                        if let Some(ref tool_id) = current_tool_id {
                                            // Accumulate args from the buffer by
                                            // reading the accumulated json string.
                                            // The name was set in content_block_start
                                            // and passed via the initial ToolCallDelta.
                                            // We emit ToolCallComplete with the
                                            // accumulated_tool_args (collected during
                                            // input_json_delta events).
                                            let args_str = accumulated_tool_args.clone();
                                            let args_val: serde_json::Value = serde_json::from_str(&args_str)
                                                .unwrap_or(serde_json::json!({}));
                                            saw_event = true;
                                            yield LlmEvent::ToolCallComplete {
                                                id: tool_id.clone(),
                                                name: current_tool_name.take().unwrap_or_default(),
                                                args: args_val,
                                                meta: None,
                                            };
                                            accumulated_tool_args.clear();
                                        }
                                        current_tool_id = None;
                                    }
                                    _ => {}
                                }
                                current_block_type = None;
                            }
                            "message_delta" => {
                                if let Some(usage_update) = $event.usage {
                                    merge_usage(&mut usage, &usage_update);
                                    saw_event = true;
                                    yield LlmEvent::UsageUpdate {
                                        usage: usage.clone(),
                                    };
                                }
                                if let Some(finish_reason) = $event.delta.and_then(|d| d.stop_reason) {
                                    let reason = Self::map_stop_reason(finish_reason.as_str());
                                    last_stop_reason = Some(reason);
                                    if !saw_done {
                                        saw_event = true;
                                        yield LlmEvent::Done {
                                            outcome: LlmDoneOutcome::Success { stop_reason: reason },
                                        };
                                        saw_done = true;
                                    }
                                }
                            }
                            "message_start" => {
                                if let Some(usage_update) = $event.message.and_then(|m| m.usage) {
                                    merge_usage(&mut usage, &usage_update);
                                    saw_event = true;
                                    yield LlmEvent::UsageUpdate {
                                        usage: usage.clone(),
                                    };
                                }
                            }
                            "message_stop" => {
                                if !saw_done {
                                    let finish_reason = $event.delta.and_then(|d| d.stop_reason);
                                    let reason = finish_reason
                                        .as_deref()
                                        .map(Self::map_stop_reason)
                                        .or(last_stop_reason)
                                        .unwrap_or(StopReason::EndTurn);
                                    last_stop_reason = Some(reason);
                                    saw_event = true;
                                    yield LlmEvent::Done {
                                        outcome: LlmDoneOutcome::Success { stop_reason: reason },
                                    };
                                    saw_done = true;
                                }
                            }
                            _ => {}
                        }
                    };
                }

                macro_rules! handle_line {
                    ($line:expr) => {
                        if !$line.is_empty() {
                            if let Some(data) = Self::strip_data_prefix($line) {
                                if data == "[DONE]" {
                                    if !saw_done {
                                        let reason =
                                            last_stop_reason.unwrap_or(StopReason::EndTurn);
                                        saw_event = true;
                                        yield LlmEvent::Done {
                                            outcome: LlmDoneOutcome::Success { stop_reason: reason },
                                        };
                                        saw_done = true;
                                    }
                                } else if let Some(event) = Self::parse_sse_line($line) {
                                    handle_event!(event);
                                }
                            }
                        }
                    };
                }

                while let Some(chunk) = stream.next().await {
                    let chunk = chunk.map_err(|_| LlmError::ConnectionReset)?;
                    buffer.push_str(&String::from_utf8_lossy(&chunk));

                    while let Some(newline_pos) = buffer.find('\n') {
                        let line = buffer[..newline_pos].trim();
                        handle_line!(line);
                        buffer.drain(..=newline_pos);
                    }
                }

                if !buffer.is_empty() {
                    for line in buffer.lines() {
                        let line = line.trim();
                        handle_line!(line);
                    }
                }

                if !saw_done && saw_event {
                    tracing::warn!(
                        model = %request.model,
                        "Anthropic stream ended without terminal event; emitting synthetic Done"
                    );
                    let reason = last_stop_reason.unwrap_or(StopReason::EndTurn);
                    yield LlmEvent::Done {
                        outcome: LlmDoneOutcome::Success { stop_reason: reason },
                    };
                }
            },
        );

        crate::streaming::ensure_terminal_done(inner)
    }

    fn provider(&self) -> &'static str {
        "anthropic"
    }

    async fn health_check(&self) -> Result<(), LlmError> {
        Ok(())
    }

    fn compile_schema(&self, output_schema: &OutputSchema) -> Result<CompiledSchema, SchemaError> {
        let mut schema = output_schema.schema.as_value().clone();
        ensure_additional_properties_false(&mut schema);

        Ok(CompiledSchema {
            schema,
            warnings: Vec::new(),
        })
    }
}

#[derive(Debug, Deserialize)]
struct AnthropicEvent {
    #[serde(rename = "type")]
    event_type: String,
    delta: Option<AnthropicDelta>,
    content_block: Option<AnthropicContentBlock>,
    message: Option<AnthropicMessage>,
    usage: Option<AnthropicUsage>,
}

#[derive(Debug, Deserialize)]
struct AnthropicDelta {
    #[serde(rename = "type")]
    delta_type: String,
    text: Option<String>,
    partial_json: Option<String>,
    stop_reason: Option<String>,
    /// Thinking content for thinking_delta events
    thinking: Option<String>,
    /// Signature for signature_delta events (arrives separately before content_block_stop)
    signature: Option<String>,
    /// Content for compaction_delta events
    content: Option<String>,
}

#[derive(Debug, Deserialize)]
struct AnthropicContentBlock {
    #[serde(rename = "type")]
    block_type: String,
    id: Option<String>,
    name: Option<String>,
    /// Signature for thinking block continuity
    signature: Option<String>,
    /// Encrypted data for redacted_thinking blocks
    data: Option<String>,
}

#[derive(Debug, Deserialize)]
struct AnthropicMessage {
    usage: Option<AnthropicUsage>,
}

#[derive(Debug, Deserialize)]
struct AnthropicUsage {
    input_tokens: Option<u64>,
    output_tokens: Option<u64>,
    cache_creation_input_tokens: Option<u64>,
    cache_read_input_tokens: Option<u64>,
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use meerkat_core::{AssistantBlock, BlockAssistantMessage, ProviderMeta, UserMessage};

    // =========================================================================
    // Thinking block SSE parsing tests (spec section 3.5)
    // =========================================================================

    #[test]
    fn test_anthropic_content_block_parses_thinking_type() {
        // content_block_start with type: "thinking" should parse
        let json = r#"{"type": "thinking", "thinking": "Let me analyze..."}"#;
        let block: AnthropicContentBlock = serde_json::from_str(json).unwrap();

        assert_eq!(block.block_type, "thinking");
    }

    #[test]
    fn test_anthropic_content_block_parses_thinking_with_signature() {
        // content_block_start may have signature already
        let json = r#"{"type": "thinking", "thinking": "", "signature": "sig_abc123"}"#;
        let block: AnthropicContentBlock = serde_json::from_str(json).unwrap();

        assert_eq!(block.block_type, "thinking");
        assert_eq!(block.signature.as_deref(), Some("sig_abc123"));
    }

    #[test]
    fn test_anthropic_delta_parses_thinking_delta() {
        // content_block_delta with delta type: "thinking_delta"
        let json = r#"{"type": "thinking_delta", "thinking": "I need to consider..."}"#;
        let delta: AnthropicDelta = serde_json::from_str(json).unwrap();

        assert_eq!(delta.delta_type, "thinking_delta");
        assert_eq!(delta.thinking.as_deref(), Some("I need to consider..."));
    }

    #[test]
    fn test_anthropic_delta_parses_signature_delta() {
        // content_block_delta with delta type: "signature_delta"
        let json = r#"{"type": "signature_delta", "signature": "sig_xyz789"}"#;
        let delta: AnthropicDelta = serde_json::from_str(json).unwrap();

        assert_eq!(delta.delta_type, "signature_delta");
        assert_eq!(delta.signature.as_deref(), Some("sig_xyz789"));
    }

    #[test]
    fn test_anthropic_delta_parses_text_delta_unchanged() {
        // Existing text_delta should still work
        let json = r#"{"type": "text_delta", "text": "Hello world"}"#;
        let delta: AnthropicDelta = serde_json::from_str(json).unwrap();

        assert_eq!(delta.delta_type, "text_delta");
        assert_eq!(delta.text.as_deref(), Some("Hello world"));
        assert!(delta.thinking.is_none());
        assert!(delta.signature.is_none());
    }

    #[test]
    fn test_anthropic_delta_parses_input_json_delta_unchanged() {
        // Existing input_json_delta should still work
        let json = r#"{"type": "input_json_delta", "partial_json": "{\"path\":"}"#;
        let delta: AnthropicDelta = serde_json::from_str(json).unwrap();

        assert_eq!(delta.delta_type, "input_json_delta");
        assert_eq!(delta.partial_json.as_deref(), Some("{\"path\":"));
    }

    // =========================================================================
    // Request building tests for BlockAssistantMessage (spec section 3.5)
    // =========================================================================

    #[test]
    fn test_build_request_body_renders_thinking_block_with_signature()
    -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        // Create a session with a thinking block
        let assistant_msg = Message::BlockAssistant(BlockAssistantMessage {
            blocks: vec![
                AssistantBlock::Reasoning {
                    text: "Let me analyze this problem...".to_string(),
                    meta: Some(Box::new(ProviderMeta::Anthropic {
                        signature: "sig_abc123".to_string(),
                    })),
                },
                AssistantBlock::Text {
                    text: "The answer is 42.".to_string(),
                    meta: None,
                },
            ],
            stop_reason: StopReason::EndTurn,
        });

        let request = LlmRequest::new(
            "claude-sonnet-4-5",
            vec![
                Message::User(UserMessage {
                    content: "What is the meaning of life?".to_string(),
                }),
                assistant_msg,
                Message::User(UserMessage {
                    content: "Can you elaborate?".to_string(),
                }),
            ],
        );

        let body = client.build_request_body(&request)?;
        let messages = body["messages"].as_array().unwrap();

        // Second message should be the assistant with thinking + text
        let assistant_content = messages[1]["content"].as_array().unwrap();
        assert_eq!(assistant_content.len(), 2);

        // First block should be thinking
        assert_eq!(assistant_content[0]["type"], "thinking");
        assert_eq!(
            assistant_content[0]["thinking"],
            "Let me analyze this problem..."
        );
        assert_eq!(assistant_content[0]["signature"], "sig_abc123");

        // Second block should be text
        assert_eq!(assistant_content[1]["type"], "text");
        assert_eq!(assistant_content[1]["text"], "The answer is 42.");

        Ok(())
    }

    #[test]
    fn test_build_request_body_skips_thinking_block_without_signature()
    -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        // Thinking block without Anthropic signature should be skipped
        let assistant_msg = Message::BlockAssistant(BlockAssistantMessage {
            blocks: vec![
                AssistantBlock::Reasoning {
                    text: "Some thinking...".to_string(),
                    meta: None, // No signature!
                },
                AssistantBlock::Text {
                    text: "The answer.".to_string(),
                    meta: None,
                },
            ],
            stop_reason: StopReason::EndTurn,
        });

        let request = LlmRequest::new(
            "claude-sonnet-4-5",
            vec![
                Message::User(UserMessage {
                    content: "Question".to_string(),
                }),
                assistant_msg,
            ],
        );

        let body = client.build_request_body(&request)?;
        let messages = body["messages"].as_array().unwrap();

        // Assistant content should only have the text block (thinking skipped)
        let assistant_content = messages[1]["content"].as_array().unwrap();
        assert_eq!(assistant_content.len(), 1);
        assert_eq!(assistant_content[0]["type"], "text");

        Ok(())
    }

    #[test]
    fn test_build_request_body_renders_tool_use_blocks() -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        let assistant_msg = Message::BlockAssistant(BlockAssistantMessage {
            blocks: vec![
                AssistantBlock::Text {
                    text: "I'll read that file for you.".to_string(),
                    meta: None,
                },
                AssistantBlock::ToolUse {
                    id: "tu_123".to_string(),
                    name: "read_file".to_string(),
                    args: serde_json::value::RawValue::from_string(
                        r#"{"path": "/tmp/test.txt"}"#.to_string(),
                    )
                    .unwrap(),
                    meta: None, // Tool use blocks don't have signatures in Anthropic
                },
            ],
            stop_reason: StopReason::ToolUse,
        });

        let request = LlmRequest::new(
            "claude-sonnet-4-5",
            vec![
                Message::User(UserMessage {
                    content: "Read /tmp/test.txt".to_string(),
                }),
                assistant_msg,
            ],
        );

        let body = client.build_request_body(&request)?;
        let messages = body["messages"].as_array().unwrap();
        let assistant_content = messages[1]["content"].as_array().unwrap();

        assert_eq!(assistant_content.len(), 2);
        assert_eq!(assistant_content[0]["type"], "text");
        assert_eq!(assistant_content[1]["type"], "tool_use");
        assert_eq!(assistant_content[1]["id"], "tu_123");
        assert_eq!(assistant_content[1]["name"], "read_file");
        assert_eq!(assistant_content[1]["input"]["path"], "/tmp/test.txt");

        Ok(())
    }

    #[test]
    fn test_build_request_body_adds_thinking_beta_header() -> Result<(), Box<dyn std::error::Error>>
    {
        let client = AnthropicClient::new("test-key".to_string())?;

        // When thinking is enabled via provider_params, beta header should be added
        let request = LlmRequest::new(
            "claude-sonnet-4-5",
            vec![Message::User(UserMessage {
                content: "test".to_string(),
            })],
        )
        .with_provider_param("thinking_budget", 10000);

        let body = client.build_request_body(&request)?;

        // The beta header is added during the HTTP request, not in the body
        // But the thinking config should be in the body
        assert!(body.get("thinking").is_some());
        assert_eq!(body["thinking"]["type"], "enabled");
        assert_eq!(body["thinking"]["budget_tokens"], 10000);

        Ok(())
    }

    // =========================================================================
    // Original tests (unchanged)
    // =========================================================================

    #[test]
    fn test_build_request_body_basic() -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        let request = LlmRequest::new(
            "claude-sonnet-4-20250514",
            vec![Message::User(UserMessage {
                content: "test".to_string(),
            })],
        )
        .with_provider_param("thinking_budget", 10000);

        let body = client.build_request_body(&request)?;

        assert!(
            body.get("thinking").is_some(),
            "thinking field should be present"
        );
        let thinking = &body["thinking"];
        assert_eq!(thinking["type"], "enabled");
        assert_eq!(thinking["budget_tokens"], 10000);
        Ok(())
    }

    #[test]
    fn test_build_request_body_with_top_k() -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        let request = LlmRequest::new(
            "claude-sonnet-4-20250514",
            vec![Message::User(UserMessage {
                content: "test".to_string(),
            })],
        )
        .with_provider_param("top_k", 40);

        let body = client.build_request_body(&request)?;

        assert_eq!(body["top_k"], 40);
        Ok(())
    }

    #[test]
    fn test_build_request_body_no_provider_params() -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;
        let request = LlmRequest::new(
            "claude-sonnet-4-20250514",
            vec![Message::User(UserMessage {
                content: "test".to_string(),
            })],
        );

        let body = client.build_request_body(&request)?;

        assert!(body.get("thinking").is_none());
        assert!(body.get("top_k").is_none());
        assert_eq!(body["model"], "claude-sonnet-4-20250514");
        Ok(())
    }

    #[test]
    fn test_client_builder_creates_configured_client() -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::builder("test-key".to_string())
            .connect_timeout(std::time::Duration::from_secs(5))
            .request_timeout(std::time::Duration::from_secs(120))
            .build()?;

        assert_eq!(client.provider(), "anthropic");
        Ok(())
    }

    #[test]
    fn test_client_default_has_connection_pool() -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;
        assert_eq!(client.provider(), "anthropic");
        Ok(())
    }

    #[test]
    fn test_parse_sse_line() {
        let line = r###"data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}"###;
        let event = AnthropicClient::parse_sse_line(line);
        assert!(event.is_some());
        assert_eq!(event.unwrap().event_type, "content_block_delta");

        let done = AnthropicClient::parse_sse_line("data: [DONE]");
        assert!(done.is_none());

        let comment = AnthropicClient::parse_sse_line(": comment");
        assert!(comment.is_none());

        let event_line = AnthropicClient::parse_sse_line("event: message_start");
        assert!(event_line.is_none());
    }

    #[test]
    fn test_sse_buffer_constants() {
        let buffer_cap = SSE_BUFFER_CAPACITY;
        assert!(buffer_cap >= 256, "SSE buffer should be at least 256 bytes");
        let connect_timeout = DEFAULT_CONNECT_TIMEOUT.as_secs();
        assert!(
            connect_timeout >= 5,
            "Connect timeout should be at least 5s"
        );
        let request_timeout = DEFAULT_REQUEST_TIMEOUT.as_secs();
        assert!(
            request_timeout >= 60,
            "Request timeout should be at least 60s"
        );
    }

    /// Regression: CLI --param passes top_k as string; must coerce to number
    /// Previously: `--param top_k=40` sent `"top_k": "40"` which Anthropic rejects
    #[test]
    fn test_regression_top_k_string_coercion() -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        // Simulate CLI --param which passes values as strings
        let request = LlmRequest::new(
            "claude-sonnet-4-20250514",
            vec![Message::User(UserMessage {
                content: "test".to_string(),
            })],
        )
        .with_provider_param("top_k", "40"); // String, not number!

        let body = client.build_request_body(&request)?;

        // Should be coerced to a number
        assert!(
            body["top_k"].is_number(),
            "top_k should be a number, not string"
        );
        assert_eq!(body["top_k"], 40);
        Ok(())
    }

    /// Regression: non-numeric string values for top_k should be ignored
    #[test]
    fn test_regression_top_k_invalid_string_ignored() -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        let request = LlmRequest::new(
            "claude-sonnet-4-20250514",
            vec![Message::User(UserMessage {
                content: "test".to_string(),
            })],
        )
        .with_provider_param("top_k", "not_a_number");

        let body = client.build_request_body(&request)?;

        // Invalid string should be ignored (no top_k in body)
        assert!(
            body.get("top_k").is_none(),
            "invalid top_k should be ignored"
        );
        Ok(())
    }

    #[test]
    fn test_usage_merge_preserves_input_tokens() {
        let mut usage = Usage::default();
        let start = AnthropicUsage {
            input_tokens: Some(120),
            output_tokens: Some(0),
            cache_creation_input_tokens: Some(4),
            cache_read_input_tokens: Some(2),
        };

        merge_usage(&mut usage, &start);

        assert_eq!(usage.input_tokens, 120);
        assert_eq!(usage.output_tokens, 0);
        assert_eq!(usage.cache_creation_tokens, Some(4));
        assert_eq!(usage.cache_read_tokens, Some(2));

        let delta = AnthropicUsage {
            input_tokens: None,
            output_tokens: Some(7),
            cache_creation_input_tokens: None,
            cache_read_input_tokens: None,
        };

        merge_usage(&mut usage, &delta);

        assert_eq!(usage.input_tokens, 120);
        assert_eq!(usage.output_tokens, 7);
        assert_eq!(usage.cache_creation_tokens, Some(4));
        assert_eq!(usage.cache_read_tokens, Some(2));
    }

    #[test]
    fn test_build_request_body_with_structured_output() -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "age": {"type": "integer"}
            },
            "required": ["name", "age"]
        });

        let request = LlmRequest::new(
            "claude-sonnet-4-20250514",
            vec![Message::User(UserMessage {
                content: "test".to_string(),
            })],
        )
        .with_provider_param(
            "structured_output",
            serde_json::json!({
                "schema": schema,
                "name": "person",
                "strict": true
            }),
        );

        let body = client.build_request_body(&request)?;

        // Check output_config is present with correct structure
        assert!(
            body.get("output_config").is_some(),
            "output_config should be present"
        );
        let output_config = &body["output_config"];
        assert_eq!(output_config["format"]["type"], "json_schema");
        assert!(output_config["format"]["schema"].is_object());
        assert_eq!(
            output_config["format"]["schema"]["additionalProperties"],
            serde_json::json!(false)
        );
        Ok(())
    }

    #[test]
    fn test_build_request_body_without_structured_output() -> Result<(), Box<dyn std::error::Error>>
    {
        let client = AnthropicClient::new("test-key".to_string())?;

        let request = LlmRequest::new(
            "claude-sonnet-4-20250514",
            vec![Message::User(UserMessage {
                content: "test".to_string(),
            })],
        );

        let body = client.build_request_body(&request)?;

        // output_config should not be present
        assert!(
            body.get("output_config").is_none(),
            "output_config should not be present without structured_output"
        );
        Ok(())
    }

    // AdditionalProperties handling is covered by core schema compiler tests.

    // =========================================================================
    // Opus 4.6: Adaptive thinking & effort parameter tests
    // =========================================================================

    #[test]
    fn test_build_request_body_adaptive_thinking() -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        let request = LlmRequest::new(
            "claude-opus-4-6",
            vec![Message::User(UserMessage {
                content: "test".to_string(),
            })],
        )
        .with_provider_param("thinking", serde_json::json!({"type": "adaptive"}));

        let body = client.build_request_body(&request)?;

        assert!(
            body.get("thinking").is_some(),
            "thinking field should be present"
        );
        assert_eq!(body["thinking"]["type"], "adaptive");
        // adaptive mode should NOT have budget_tokens
        assert!(body["thinking"].get("budget_tokens").is_none());
        Ok(())
    }

    #[test]
    fn test_build_request_body_effort_parameter() -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        let request = LlmRequest::new(
            "claude-opus-4-6",
            vec![Message::User(UserMessage {
                content: "test".to_string(),
            })],
        )
        .with_provider_param("effort", "medium");

        let body = client.build_request_body(&request)?;

        assert!(
            body.get("output_config").is_some(),
            "output_config should be present"
        );
        assert_eq!(body["output_config"]["effort"], "medium");
        Ok(())
    }

    #[test]
    fn test_build_request_body_effort_with_structured_output()
    -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "name": {"type": "string"}
            },
            "required": ["name"]
        });

        let mut request = LlmRequest::new(
            "claude-opus-4-6",
            vec![Message::User(UserMessage {
                content: "test".to_string(),
            })],
        );
        request.provider_params = Some(serde_json::json!({
            "effort": "high",
            "structured_output": {
                "schema": schema,
                "name": "output",
                "strict": true
            }
        }));

        let body = client.build_request_body(&request)?;

        // output_config should have BOTH effort and format
        let output_config = &body["output_config"];
        assert_eq!(output_config["effort"], "high");
        assert_eq!(output_config["format"]["type"], "json_schema");
        assert!(output_config["format"]["schema"].is_object());
        Ok(())
    }

    #[test]
    fn test_build_request_body_adaptive_thinking_does_not_set_interleaved_beta()
    -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        let request = LlmRequest::new(
            "claude-opus-4-6",
            vec![Message::User(UserMessage {
                content: "test".to_string(),
            })],
        )
        .with_provider_param("thinking", serde_json::json!({"type": "adaptive"}));

        let body = client.build_request_body(&request)?;

        // Adaptive thinking should be in the body
        assert_eq!(body["thinking"]["type"], "adaptive");
        assert!(
            body["thinking"].get("budget_tokens").is_none(),
            "adaptive thinking should not have budget_tokens"
        );
        Ok(())
    }

    #[test]
    fn test_build_request_body_legacy_thinking_still_works()
    -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        // Legacy flat format should still produce type: enabled
        let request = LlmRequest::new(
            "claude-sonnet-4-5",
            vec![Message::User(UserMessage {
                content: "test".to_string(),
            })],
        )
        .with_provider_param("thinking_budget", 10000);

        let body = client.build_request_body(&request)?;

        assert_eq!(body["thinking"]["type"], "enabled");
        assert_eq!(body["thinking"]["budget_tokens"], 10000);
        Ok(())
    }

    #[test]
    fn test_build_request_body_inference_geo() -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        let request = LlmRequest::new(
            "claude-opus-4-6",
            vec![Message::User(UserMessage {
                content: "test".to_string(),
            })],
        )
        .with_provider_param("inference_geo", "us");

        let body = client.build_request_body(&request)?;

        assert_eq!(body["inference_geo"], "us");
        Ok(())
    }

    #[test]
    fn test_build_request_body_compaction_auto() -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        let request = LlmRequest::new(
            "claude-opus-4-6",
            vec![Message::User(UserMessage {
                content: "test".to_string(),
            })],
        )
        .with_provider_param("compaction", "auto");

        let body = client.build_request_body(&request)?;

        let edits = body["context_management"]["edits"].as_array().unwrap();
        assert_eq!(edits.len(), 1);
        assert_eq!(edits[0]["type"], "compact_20260112");
        Ok(())
    }

    #[test]
    fn test_build_request_body_compaction_with_trigger() -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        let mut request = LlmRequest::new(
            "claude-opus-4-6",
            vec![Message::User(UserMessage {
                content: "test".to_string(),
            })],
        );
        request.provider_params = Some(serde_json::json!({
            "compaction": {
                "trigger": {"type": "input_tokens", "value": 100000}
            }
        }));

        let body = client.build_request_body(&request)?;

        let edits = body["context_management"]["edits"].as_array().unwrap();
        assert_eq!(edits[0]["type"], "compact_20260112");
        assert_eq!(edits[0]["trigger"]["value"], 100000);
        Ok(())
    }

    #[test]
    fn test_build_request_body_redacted_thinking_roundtrip()
    -> Result<(), Box<dyn std::error::Error>> {
        let client = AnthropicClient::new("test-key".to_string())?;

        // Redacted thinking is stored as Reasoning with AnthropicRedacted meta
        let assistant_msg = Message::BlockAssistant(BlockAssistantMessage {
            blocks: vec![
                AssistantBlock::Reasoning {
                    text: String::new(),
                    meta: Some(Box::new(ProviderMeta::AnthropicRedacted {
                        data: "encrypted_blob_abc123".to_string(),
                    })),
                },
                AssistantBlock::Text {
                    text: "The answer.".to_string(),
                    meta: None,
                },
            ],
            stop_reason: StopReason::EndTurn,
        });

        let request = LlmRequest::new(
            "claude-opus-4-6",
            vec![
                Message::User(UserMessage {
                    content: "Question".to_string(),
                }),
                assistant_msg,
            ],
        );

        let body = client.build_request_body(&request)?;
        let messages = body["messages"].as_array().unwrap();
        let assistant_content = messages[1]["content"].as_array().unwrap();

        // First block should be redacted_thinking with encrypted data
        assert_eq!(assistant_content[0]["type"], "redacted_thinking");
        assert_eq!(assistant_content[0]["data"], "encrypted_blob_abc123");

        // Second block should be text
        assert_eq!(assistant_content[1]["type"], "text");
        Ok(())
    }

    #[test]
    fn test_build_request_body_compaction_block_roundtrip() -> Result<(), Box<dyn std::error::Error>>
    {
        let client = AnthropicClient::new("test-key".to_string())?;

        // Compaction is stored as Reasoning with AnthropicCompaction meta
        let assistant_msg = Message::BlockAssistant(BlockAssistantMessage {
            blocks: vec![
                AssistantBlock::Reasoning {
                    text: String::new(),
                    meta: Some(Box::new(ProviderMeta::AnthropicCompaction {
                        content: "Summary of prior conversation...".to_string(),
                    })),
                },
                AssistantBlock::Text {
                    text: "Continuing from summary.".to_string(),
                    meta: None,
                },
            ],
            stop_reason: StopReason::EndTurn,
        });

        let request = LlmRequest::new(
            "claude-opus-4-6",
            vec![
                Message::User(UserMessage {
                    content: "Continue".to_string(),
                }),
                assistant_msg,
            ],
        );

        let body = client.build_request_body(&request)?;
        let messages = body["messages"].as_array().unwrap();
        let assistant_content = messages[1]["content"].as_array().unwrap();

        // First block should be compaction with summary
        assert_eq!(assistant_content[0]["type"], "compaction");
        assert_eq!(
            assistant_content[0]["content"],
            "Summary of prior conversation..."
        );

        // Second block should be text
        assert_eq!(assistant_content[1]["type"], "text");
        Ok(())
    }
}