myco 0.3.0

Multi-host coding agent CLI (local in-process + SSH remotes)
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
//! Anthropic Messages API backend.
//!
//! Ref: https://platform.claude.com/docs/en/api/messages/create
//! Streaming: https://platform.claude.com/docs/en/build-with-claude/streaming

use std::sync::Arc;

use crate::core::*;

use super::*;

/// Anthropic Messages API settings ([`BackendConfig::Anthropic`]).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AnthropicBackendConfig {
    pub anthropic_base_url: String,
    pub anthropic_auth_token: String,
    pub max_tokens_per_generate: usize,
    pub enable_prompt_caching: bool,
    pub debug_dump_api_requests: bool,
    /// When set, enables Anthropic extended thinking at this effort level.
    ///
    /// The request shape follows the model's [`ThinkingMode`]: `adaptive` sends
    /// `thinking.type: "adaptive"` plus `output_config.effort`; `budget` sends
    /// `thinking.type: "enabled"` with a mapped `budget_tokens`; `none` sends
    /// no thinking fields regardless of this value.
    ///
    /// Defaults to [`Effort::DEFAULT`] so thinking is always on for interactive use.
    pub effort: Option<Effort>,
}

impl Default for AnthropicBackendConfig {
    fn default() -> Self {
        Self {
            // No built-in gateway: the catalog (config.toml) supplies base_url.
            anthropic_base_url: String::new(),
            anthropic_auth_token: String::new(),
            max_tokens_per_generate: 8192,
            enable_prompt_caching: true,
            debug_dump_api_requests: false,
            effort: Some(Effort::DEFAULT),
        }
    }
}

/// Stateless Anthropic driver. Conversation history is owned by the caller.
pub struct AnthropicGenerativeModel {
    model: ModelSpec,
    system_prompt: String,
    tools: Vec<AnthropicTool>,
    backend: AnthropicBackendConfig,
    client: reqwest::Client,
}

impl AnthropicGenerativeModel {
    pub fn new(
        config: GenerativeModelConfig,
        backend: AnthropicBackendConfig,
    ) -> Result<Arc<Self>, ModelCreationError> {
        if config.model.protocol != Protocol::AnthropicMessages {
            return Err(ModelCreationError::BadConfig(format!(
                "model `{}` speaks {}, not {}",
                config.model,
                config.model.protocol,
                Protocol::AnthropicMessages
            )));
        }

        let mut headers = reqwest::header::HeaderMap::from_iter([
            (
                reqwest::header::CONTENT_TYPE,
                "application/json".parse().unwrap(),
            ),
            (
                "anthropic-version".parse().unwrap(),
                "2023-06-01".parse().unwrap(),
            ),
        ]);
        // Empty token = `auth = "none"` in the catalog (local proxies); send no
        // auth header. Credential *presence* is the catalog's job
        // (`ModelCatalog::get`), not the driver's.
        //
        // api.anthropic.com authenticates API keys (`sk-ant-…`) via the
        // `x-api-key` header and rejects them as `Authorization: Bearer`;
        // Bearer is the convention for gateway/OAuth tokens. Pick by token
        // shape so both work against the default base URL.
        let token = &backend.anthropic_auth_token;
        if !token.is_empty() {
            let (auth_header, auth_value) = if token.starts_with("sk-ant-") {
                ("x-api-key", token.clone())
            } else {
                ("authorization", format!("Bearer {token}"))
            };
            headers.insert(
                reqwest::header::HeaderName::from_static(auth_header),
                // Never echo the token into the error: it ends up in logs.
                auth_value.parse().map_err(|e| {
                    ModelCreationError::BadConfig(format!(
                        "auth token is not a valid HTTP header value: {e}"
                    ))
                })?,
            );
        }
        let client = reqwest::ClientBuilder::new()
            .default_headers(headers)
            .build()
            .map_err(|e| ModelCreationError::Uncategorized(format!("{e:?}")))?;

        let tools = config
            .tools
            .into_iter()
            .map(|spec| AnthropicTool {
                name: spec.name,
                description: spec.description,
                input_schema: spec.input_schema,
            })
            .collect();

        Ok(Arc::new(Self {
            model: config.model,
            system_prompt: config.system_prompt,
            tools,
            backend,
            client,
        }))
    }

    async fn start_message_stream(
        &self,
        messages: &[AnthropicMessage],
    ) -> Result<reqwest::Response, GenerateError> {
        // Anthropic only honors `cache_control` on content blocks (system / messages /
        // tools), never as a top-level request field. Put the breakpoint on the system
        // prompt text block so the stable prefix can be cached across turns.
        let system = if self.system_prompt.is_empty() {
            None
        } else {
            Some(vec![AnthropicSystemText {
                type_: "text",
                text: &self.system_prompt,
                cache_control: if self.backend.enable_prompt_caching {
                    Some(AnthropicCacheControl::Ephemeral)
                } else {
                    None
                },
            }])
        };

        let (thinking, output_config) =
            thinking_request_fields(self.model.thinking, self.backend.effort);
        // Anthropic requires max_tokens > thinking.budget_tokens for non-adaptive
        // extended thinking (e.g. Haiku). Adaptive thinking has no budget field.
        let mut max_tokens = self.backend.max_tokens_per_generate;
        if let Some(AnthropicThinkingConfig::Enabled { budget_tokens }) = &thinking {
            let need = (*budget_tokens as usize).saturating_add(1024);
            if max_tokens <= *budget_tokens as usize {
                max_tokens = need;
            }
        }
        let request = AnthropicMessagesRequest {
            max_tokens,
            model: &self.model.api_id,
            messages,
            system,
            tools: &self.tools,
            stream: true,
            thinking,
            output_config,
        };

        if self.backend.debug_dump_api_requests {
            eprintln!("{}", serde_json::to_string_pretty(&request).unwrap());
        }

        let raw_response = self
            .client
            .post(format!("{}/v1/messages", self.backend.anthropic_base_url))
            .json(&request)
            .send()
            .await
            .map_err(|e| GenerateError::ExecutionError(format!("{e:?}")))?;

        if !raw_response.status().is_success() {
            let status = raw_response.status();
            let body = raw_response
                .text()
                .await
                .unwrap_or_else(|e| format!("<failed to read body: {e:?}>"));
            return Err(GenerateError::ExecutionError(format!(
                "Anthropic API returned HTTP {status}: {body}"
            )));
        }

        Ok(raw_response)
    }
}

impl GenerativeModel for AnthropicGenerativeModel {
    fn generate(&self, input: &[Message]) -> AsyncStream<Result<MessagePart, GenerateError>> {
        let messages = convert_messages(input);
        let model = self.model.clone();
        let system_prompt = self.system_prompt.clone();
        let tools = self.tools.clone();
        let backend = self.backend.clone();
        let client = self.client.clone();

        let (tx, rx) = tokio::sync::mpsc::channel::<Result<MessagePart, GenerateError>>(32);

        tokio::spawn(async move {
            let driver = AnthropicGenerativeModel {
                model,
                system_prompt,
                tools,
                backend,
                client,
            };

            let response = match driver.start_message_stream(&messages).await {
                Ok(r) => r,
                Err(e) => {
                    let _ = tx.send(Err(e)).await;
                    return;
                }
            };

            if let Err(e) = drive_anthropic_sse_stream(response, tx.clone()).await {
                let _ = tx.send(Err(e)).await;
            }
        });

        Box::pin(futures::stream::unfold(rx, |mut rx| async move {
            rx.recv().await.map(|item| (item, rx))
        }))
    }
}

//
// Message conversion
//

fn convert_messages(input: &[Message]) -> Vec<AnthropicMessage> {
    let mut out: Vec<AnthropicMessage> = Vec::new();

    for message in input {
        let anthropic = match message {
            Message::UserMessage { content } => AnthropicMessage {
                role: AnthropicRole::User,
                content: content
                    .iter()
                    .cloned()
                    .map(AnthropicContent::from)
                    .collect(),
            },
            Message::ToolResults { tool_use_results } => AnthropicMessage {
                role: AnthropicRole::User,
                content: tool_use_results
                    .iter()
                    .map(|result| AnthropicContent::ToolResult {
                        tool_use_id: result.id.clone(),
                        content: result
                            .content
                            .iter()
                            .cloned()
                            .map(AnthropicContent::from)
                            .collect(),
                        is_error: result.is_error,
                    })
                    .collect(),
            },
            Message::AssistantMessage {
                content,
                tool_uses,
                turn_end_reason: _,
            } => {
                // Thinking may be stored in history for resume/UI; never echo it back to the API.
                let mut blocks: Vec<AnthropicContent> = content
                    .iter()
                    .filter(|c| !matches!(c, Content::Thinking { .. }))
                    .cloned()
                    .map(AnthropicContent::from)
                    .collect();
                for tool_use in tool_uses {
                    blocks.push(AnthropicContent::ToolUse {
                        id: tool_use.id.clone(),
                        name: tool_use.name.clone(),
                        input: tool_use.input.clone(),
                    });
                }
                // A thinking-only turn (e.g. max_tokens hit mid-thinking)
                // strips to nothing; the API rejects empty assistant content
                // on every later request, permanently wedging the session.
                if blocks.is_empty() {
                    continue;
                }
                AnthropicMessage {
                    role: AnthropicRole::Assistant,
                    content: blocks,
                }
            }
        };

        // Anthropic requires alternating roles; merge consecutive same-role turns.
        // Tool-result blocks must appear before any other content in a user message.
        if let Some(last) = out.last_mut()
            && last.role == anthropic.role
        {
            if last.role == AnthropicRole::User {
                let new_is_only_tool_results = !anthropic.content.is_empty()
                    && anthropic
                        .content
                        .iter()
                        .all(|c| matches!(c, AnthropicContent::ToolResult { .. }));
                if new_is_only_tool_results {
                    let mut combined = anthropic.content;
                    combined.append(&mut last.content);
                    last.content = combined;
                } else {
                    last.content.extend(anthropic.content);
                }
            } else {
                last.content.extend(anthropic.content);
            }
            continue;
        }
        out.push(anthropic);
    }

    out
}

//
// SSE streaming
//

async fn drive_anthropic_sse_stream(
    response: reqwest::Response,
    tx: tokio::sync::mpsc::Sender<Result<MessagePart, GenerateError>>,
) -> Result<(), GenerateError> {
    if tx.send(Ok(MessagePart::MessageStart)).await.is_err() {
        // Consumer dropped (turn cancelled): stop reading so the response
        // body drops and the provider stops generating/billing.
        return Ok(());
    }

    let mut byte_stream = response.bytes_stream();
    let mut sse = SseParser::default();
    let mut acc = StreamAccumulator::default();

    while let Some(chunk) = byte_stream.next().await {
        let chunk = chunk.map_err(|e| {
            GenerateError::ExecutionError(format!("Error reading Anthropic stream body: {e:?}"))
        })?;

        for data in sse.push(&chunk) {
            let event: AnthropicStreamEvent = serde_json::from_str(&data).map_err(|e| {
                GenerateError::MalformedResponseError(format!(
                    "Failed to parse Anthropic SSE event JSON: {e}; data={data}"
                ))
            })?;

            for item in acc.handle_event(event)? {
                if tx.send(Ok(item)).await.is_err() {
                    return Ok(());
                }
            }

            if acc.finished {
                break;
            }
        }

        if acc.finished {
            break;
        }
    }

    // Validate stream completed with a stop reason and parseable tool inputs.
    acc.finish()?;
    Ok(())
}

//
// Stream accumulation (`SseParser` is shared, in mod.rs)
//

/// Maps Anthropic's unified content-block indices onto separate content/tool-use index spaces.
#[derive(Default)]
struct StreamAccumulator {
    block_kinds: Vec<Option<BlockKind>>,
    /// Parallel builders used only to validate tool input JSON at the end.
    tool_input_json: Vec<Option<String>>,
    stop_reason: Option<AnthropicStopReason>,
    finished: bool,
}

#[derive(Clone, Copy)]
enum BlockKind {
    Content { index: usize },
    ToolUse { index: usize },
    Ignored,
}

impl StreamAccumulator {
    fn ensure_slot(&mut self, anthropic_index: usize) {
        while self.block_kinds.len() <= anthropic_index {
            self.block_kinds.push(None);
            self.tool_input_json.push(None);
        }
    }

    fn content_count(&self) -> usize {
        self.block_kinds
            .iter()
            .filter(|k| matches!(k, Some(BlockKind::Content { .. })))
            .count()
    }

    fn tool_use_count(&self) -> usize {
        self.block_kinds
            .iter()
            .filter(|k| matches!(k, Some(BlockKind::ToolUse { .. })))
            .count()
    }

    fn handle_event(
        &mut self,
        event: AnthropicStreamEvent,
    ) -> Result<Vec<MessagePart>, GenerateError> {
        let mut out = Vec::new();

        match event {
            AnthropicStreamEvent::MessageStart { .. } => {
                // Already emitted MessageStart at stream open.
            }
            AnthropicStreamEvent::ContentBlockStart {
                index,
                content_block,
            } => {
                self.ensure_slot(index);
                match content_block {
                    AnthropicStreamContentBlock::Text { text } => {
                        let content_index = self.content_count();
                        self.block_kinds[index] = Some(BlockKind::Content {
                            index: content_index,
                        });
                        out.push(MessagePart::ContentStart(ContentStart::Text {
                            index: content_index,
                        }));
                        if !text.is_empty() {
                            out.push(MessagePart::ContentDelta(ContentDelta::Text {
                                index: content_index,
                                delta: text,
                            }));
                        }
                    }
                    AnthropicStreamContentBlock::Thinking {
                        thinking,
                        signature,
                    } => {
                        let content_index = self.content_count();
                        self.block_kinds[index] = Some(BlockKind::Content {
                            index: content_index,
                        });
                        out.push(MessagePart::ContentStart(ContentStart::Thinking {
                            index: content_index,
                            signature,
                            redacted: false,
                        }));
                        if !thinking.is_empty() {
                            out.push(MessagePart::ContentDelta(ContentDelta::Thinking {
                                index: content_index,
                                delta: thinking,
                            }));
                        }
                    }
                    AnthropicStreamContentBlock::RedactedThinking { data } => {
                        let content_index = self.content_count();
                        self.block_kinds[index] = Some(BlockKind::Content {
                            index: content_index,
                        });
                        // Preserve opaque payload in signature; no plaintext deltas.
                        out.push(MessagePart::ContentStart(ContentStart::Thinking {
                            index: content_index,
                            signature: if data.is_empty() { None } else { Some(data) },
                            redacted: true,
                        }));
                    }
                    AnthropicStreamContentBlock::ToolUse { id, name, input } => {
                        let tool_index = self.tool_use_count();
                        self.block_kinds[index] = Some(BlockKind::ToolUse { index: tool_index });
                        // Input arrives via input_json_delta; starter object is usually empty.
                        let _ = input;
                        self.tool_input_json[index] = Some(String::new());
                        out.push(MessagePart::ToolUseStart(ToolUseStart {
                            index: tool_index,
                            id,
                            name,
                        }));
                    }
                    AnthropicStreamContentBlock::Other => {
                        self.block_kinds[index] = Some(BlockKind::Ignored);
                        self.tool_input_json[index] = None;
                    }
                }
            }
            AnthropicStreamEvent::ContentBlockDelta { index, delta } => {
                self.ensure_slot(index);
                let kind = self
                    .block_kinds
                    .get(index)
                    .and_then(|k| *k)
                    .ok_or_else(|| {
                        GenerateError::MalformedResponseError(format!(
                            "content_block_delta for unknown index {index}"
                        ))
                    })?;

                match (kind, delta) {
                    (
                        BlockKind::Content {
                            index: content_index,
                        },
                        AnthropicDelta::TextDelta { text },
                    ) => {
                        out.push(MessagePart::ContentDelta(ContentDelta::Text {
                            index: content_index,
                            delta: text,
                        }));
                    }
                    (
                        BlockKind::Content {
                            index: content_index,
                        },
                        AnthropicDelta::ThinkingDelta { thinking },
                    ) => {
                        out.push(MessagePart::ContentDelta(ContentDelta::Thinking {
                            index: content_index,
                            delta: thinking,
                        }));
                    }
                    (
                        BlockKind::Content {
                            index: content_index,
                        },
                        AnthropicDelta::InputJsonDelta { .. },
                    ) => {
                        return Err(GenerateError::MalformedResponseError(format!(
                            "input_json_delta on content block index {content_index}"
                        )));
                    }
                    (
                        BlockKind::ToolUse { index: tool_index },
                        AnthropicDelta::InputJsonDelta { partial_json },
                    ) => {
                        if let Some(Some(acc)) = self.tool_input_json.get_mut(index) {
                            acc.push_str(&partial_json);
                        }
                        out.push(MessagePart::ToolUseDelta(ToolUseDelta {
                            index: tool_index,
                            input_json_delta: partial_json,
                        }));
                    }
                    (
                        BlockKind::ToolUse { .. },
                        AnthropicDelta::TextDelta { .. } | AnthropicDelta::ThinkingDelta { .. },
                    ) => {
                        return Err(GenerateError::MalformedResponseError(
                            "text/thinking delta on tool_use block".into(),
                        ));
                    }
                    (BlockKind::Ignored, _) | (_, AnthropicDelta::Other) => {}
                }
            }
            AnthropicStreamEvent::ContentBlockStop { .. } => {}
            AnthropicStreamEvent::MessageDelta { delta, usage } => {
                if let Some(u) = usage {
                    out.push(MessagePart::Usage(u.into_token_usage()));
                }
                if let Some(stop_reason) = delta.stop_reason {
                    if matches!(stop_reason, AnthropicStopReason::Refusal) {
                        return Err(GenerateError::RefusalError(
                            "Anthropic stop_reason=refusal".into(),
                        ));
                    }
                    self.stop_reason = Some(stop_reason.clone());
                    out.push(MessagePart::TurnEndReason(TurnEndReason::from(stop_reason)));
                }
            }
            AnthropicStreamEvent::MessageStop => {
                self.finished = true;
            }
            AnthropicStreamEvent::Ping => {}
            AnthropicStreamEvent::Error { error } => {
                return Err(GenerateError::ExecutionError(format!(
                    "Anthropic stream error event: {error}"
                )));
            }
            AnthropicStreamEvent::Other => {}
        }

        Ok(out)
    }

    fn finish(self) -> Result<(), GenerateError> {
        if self.stop_reason.is_none() {
            return Err(GenerateError::MalformedResponseError(
                "Anthropic stream ended without a stop_reason".into(),
            ));
        }

        for (i, json) in self.tool_input_json.into_iter().enumerate() {
            if let Some(json) = json {
                // No deltas means empty object input.
                let json = if json.is_empty() { "{}" } else { json.as_str() };
                if let Err(e) = serde_json::from_str::<serde_json::Value>(json) {
                    return Err(GenerateError::MalformedResponseError(format!(
                        "Malformed stream: tool use input JSON at block {i} is invalid: {e}"
                    )));
                }
            }
        }

        Ok(())
    }
}

//
// Anthropic streaming event types
//

#[derive(Debug, serde::Deserialize)]
#[serde(tag = "type")]
enum AnthropicStreamEvent {
    #[serde(rename = "message_start")]
    MessageStart {
        #[serde(default)]
        #[allow(dead_code)]
        message: serde_json::Value,
    },
    #[serde(rename = "content_block_start")]
    ContentBlockStart {
        index: usize,
        content_block: AnthropicStreamContentBlock,
    },
    #[serde(rename = "content_block_delta")]
    ContentBlockDelta { index: usize, delta: AnthropicDelta },
    #[serde(rename = "content_block_stop")]
    ContentBlockStop {
        #[serde(default)]
        #[allow(dead_code)]
        index: usize,
    },
    #[serde(rename = "message_delta")]
    MessageDelta {
        delta: AnthropicMessageDelta,
        #[serde(default)]
        usage: Option<AnthropicUsage>,
    },
    #[serde(rename = "message_stop")]
    MessageStop,
    #[serde(rename = "ping")]
    Ping,
    #[serde(rename = "error")]
    Error { error: serde_json::Value },
    #[serde(other)]
    Other,
}

#[derive(Debug, serde::Deserialize)]
#[serde(tag = "type")]
enum AnthropicStreamContentBlock {
    #[serde(rename = "text")]
    Text {
        #[serde(default)]
        text: String,
    },
    #[serde(rename = "thinking")]
    Thinking {
        #[serde(default)]
        thinking: String,
        #[serde(default)]
        signature: Option<String>,
    },
    #[serde(rename = "redacted_thinking")]
    RedactedThinking {
        #[serde(default)]
        data: String,
    },
    #[serde(rename = "tool_use")]
    ToolUse {
        id: String,
        name: String,
        #[serde(default)]
        input: serde_json::Value,
    },
    #[serde(other)]
    Other,
}

#[derive(Debug, serde::Deserialize)]
#[serde(tag = "type")]
enum AnthropicDelta {
    #[serde(rename = "text_delta")]
    TextDelta { text: String },
    #[serde(rename = "thinking_delta")]
    ThinkingDelta { thinking: String },
    #[serde(rename = "input_json_delta")]
    InputJsonDelta { partial_json: String },
    #[serde(other)]
    Other,
}

#[derive(Debug, serde::Deserialize)]
struct AnthropicMessageDelta {
    stop_reason: Option<AnthropicStopReason>,
}

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

impl AnthropicUsage {
    fn into_token_usage(self) -> crate::generative_model::TokenUsage {
        crate::generative_model::TokenUsage {
            input_tokens: self.input_tokens,
            output_tokens: self.output_tokens,
            cache_read_tokens: self.cache_read_input_tokens,
            cache_creation_tokens: self.cache_creation_input_tokens,
        }
    }
}

//
// Request / wire types
//

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)]
enum AnthropicRole {
    #[serde(rename = "assistant")]
    Assistant,
    #[serde(rename = "user")]
    User,
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
struct AnthropicMessage {
    role: AnthropicRole,
    content: Vec<AnthropicContent>,
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
#[serde(tag = "type")]
enum AnthropicContent {
    #[serde(rename = "text")]
    Text { text: String },

    #[serde(rename = "image")]
    Image { source: AnthropicImageSource },

    #[serde(rename = "thinking")]
    Thinking {
        thinking: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        signature: Option<String>,
    },

    #[serde(rename = "redacted_thinking")]
    RedactedThinking {
        #[serde(default)]
        data: String,
    },

    #[serde(rename = "tool_use")]
    ToolUse {
        id: String,
        name: String,
        input: serde_json::Value,
    },

    #[serde(rename = "tool_result")]
    ToolResult {
        tool_use_id: String,
        content: Vec<AnthropicContent>,
        is_error: bool,
    },
}

/// Wire form of Anthropic image `source`. Public `Content::Image.source` is an opaque
/// string that we interpret as a URL, a `data:` URL, or raw base64 (default PNG).
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)]
#[serde(tag = "type")]
enum AnthropicImageSource {
    #[serde(rename = "base64")]
    Base64 { media_type: String, data: String },
    #[serde(rename = "url")]
    Url { url: String },
}

fn anthropic_image_source(source: String) -> AnthropicImageSource {
    if source.starts_with("http://") || source.starts_with("https://") {
        return AnthropicImageSource::Url { url: source };
    }
    if let Some(rest) = source.strip_prefix("data:") {
        // data:[<media_type>][;base64],<data>
        if let Some((meta, data)) = rest.split_once(',') {
            let media_type = meta
                .split(';')
                .next()
                .filter(|s| !s.is_empty())
                .unwrap_or("image/png")
                .to_string();
            return AnthropicImageSource::Base64 {
                media_type,
                data: data.to_string(),
            };
        }
    }
    AnthropicImageSource::Base64 {
        media_type: "image/png".into(),
        data: source,
    }
}

impl From<Content> for AnthropicContent {
    fn from(content: Content) -> Self {
        match content {
            Content::Text { text } => AnthropicContent::Text { text },
            Content::Image { source } => AnthropicContent::Image {
                source: anthropic_image_source(source),
            },
            Content::Thinking {
                text,
                signature,
                redacted: false,
            } => AnthropicContent::Thinking {
                thinking: text,
                signature,
            },
            Content::Thinking {
                signature,
                redacted: true,
                ..
            } => AnthropicContent::RedactedThinking {
                data: signature.unwrap_or_default(),
            },
        }
    }
}

#[derive(Debug, serde::Serialize)]
struct AnthropicMessagesRequest<'a> {
    max_tokens: usize,
    messages: &'a [AnthropicMessage],
    model: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    system: Option<Vec<AnthropicSystemText<'a>>>,
    tools: &'a [AnthropicTool],
    stream: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    thinking: Option<AnthropicThinkingConfig>,
    #[serde(skip_serializing_if = "Option::is_none")]
    output_config: Option<AnthropicOutputConfig>,
}

/// Wire form of Anthropic `thinking` request field.
///
/// Newer models reject `type: "enabled"` and require adaptive thinking plus
/// `output_config.effort`. Older models require `type: "enabled"` with a budget.
#[derive(Debug, serde::Serialize, Clone, PartialEq, Eq)]
#[serde(tag = "type")]
enum AnthropicThinkingConfig {
    #[serde(rename = "enabled")]
    Enabled { budget_tokens: u32 },
    #[serde(rename = "adaptive")]
    Adaptive {
        /// `"summarized"` surfaces readable thinking text; default on newest models is
        /// `"omitted"` (empty `thinking` field).
        #[serde(skip_serializing_if = "Option::is_none")]
        display: Option<&'static str>,
    },
}

#[derive(Debug, serde::Serialize, Clone, PartialEq, Eq)]
struct AnthropicOutputConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    effort: Option<&'static str>,
}

/// Build `thinking` / `output_config` for the given model when effort is set.
fn thinking_request_fields(
    mode: ThinkingMode,
    effort: Option<Effort>,
) -> (
    Option<AnthropicThinkingConfig>,
    Option<AnthropicOutputConfig>,
) {
    let Some(effort) = effort else {
        return (None, None);
    };

    match mode {
        ThinkingMode::Adaptive => (
            Some(AnthropicThinkingConfig::Adaptive {
                // Agent UIs stream thinking; omit would yield empty thinking deltas.
                display: Some("summarized"),
            }),
            Some(AnthropicOutputConfig {
                effort: Some(effort.as_str()),
            }),
        ),
        ThinkingMode::Budget => (
            Some(AnthropicThinkingConfig::Enabled {
                budget_tokens: effort.budget_tokens(),
            }),
            None,
        ),
        // `effort` is rejected for this protocol at catalog resolution.
        ThinkingMode::Effort | ThinkingMode::None => (None, None),
    }
}

/// System prompt as a content-block array so `cache_control` can be attached.
#[derive(Debug, serde::Serialize)]
struct AnthropicSystemText<'a> {
    #[serde(rename = "type")]
    type_: &'static str,
    text: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    cache_control: Option<AnthropicCacheControl>,
}

#[derive(Debug, serde::Serialize, Clone, Copy)]
#[serde(tag = "type")]
enum AnthropicCacheControl {
    #[serde(rename = "ephemeral")]
    Ephemeral,
}

#[derive(Debug, Clone, serde::Serialize)]
struct AnthropicTool {
    name: String,
    description: String,
    input_schema: serde_json::Value,
}

#[derive(Clone, Debug, serde::Deserialize)]
enum AnthropicStopReason {
    #[serde(rename = "end_turn")]
    EndTurn,
    #[serde(rename = "max_tokens")]
    MaxTokens,
    #[serde(rename = "stop_sequence")]
    StopSequence,
    #[serde(rename = "tool_use")]
    ToolUse,
    #[serde(rename = "pause_turn")]
    PauseTurn,
    #[serde(rename = "refusal")]
    Refusal,
    /// The API grows stop reasons over time (`model_context_window_exceeded`
    /// arrived in 2025); an unknown one must not fail the whole message_delta
    /// event and discard an already-streamed generation.
    #[serde(other)]
    Unknown,
}

impl From<AnthropicStopReason> for TurnEndReason {
    fn from(stop_reason: AnthropicStopReason) -> Self {
        match stop_reason {
            AnthropicStopReason::EndTurn => TurnEndReason::EndTurn,
            AnthropicStopReason::MaxTokens => TurnEndReason::MaxTokens,
            AnthropicStopReason::ToolUse => TurnEndReason::ToolUse,
            AnthropicStopReason::StopSequence => {
                TurnEndReason::Other("Anthropic::StopSequence".into())
            }
            AnthropicStopReason::PauseTurn => TurnEndReason::Other("Anthropic::PauseTurn".into()),
            AnthropicStopReason::Refusal => TurnEndReason::Other("Anthropic::Refusal".into()),
            AnthropicStopReason::Unknown => TurnEndReason::Other("Anthropic::Unknown".into()),
        }
    }
}

//
// Tests
//

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

    #[test]
    fn test_role_serdes() {
        let role = AnthropicRole::Assistant;
        let json = serde_json::to_string(&role).unwrap();
        assert_eq!(json, r#""assistant""#);
    }

    #[test]
    fn test_content_serdes() {
        let content = AnthropicContent::Text {
            text: "Hello, world".to_string(),
        };
        let json = serde_json::to_string(&content).unwrap();
        assert_eq!(json, r#"{"type":"text","text":"Hello, world"}"#);
    }

    #[test]
    fn image_source_url_and_base64_wire_format() {
        let url = AnthropicContent::from(Content::Image {
            source: "https://example.com/a.png".into(),
        });
        let url_json = serde_json::to_value(&url).unwrap();
        assert_eq!(url_json["type"], "image");
        assert_eq!(url_json["source"]["type"], "url");
        assert_eq!(url_json["source"]["url"], "https://example.com/a.png");

        let b64 = AnthropicContent::from(Content::Image {
            source: "iVBORw0KGgo=".into(),
        });
        let b64_json = serde_json::to_value(&b64).unwrap();
        assert_eq!(b64_json["source"]["type"], "base64");
        assert_eq!(b64_json["source"]["media_type"], "image/png");
        assert_eq!(b64_json["source"]["data"], "iVBORw0KGgo=");

        let data_url = AnthropicContent::from(Content::Image {
            source: "data:image/jpeg;base64,/9j/4AAQ".into(),
        });
        let data_json = serde_json::to_value(&data_url).unwrap();
        assert_eq!(data_json["source"]["type"], "base64");
        assert_eq!(data_json["source"]["media_type"], "image/jpeg");
        assert_eq!(data_json["source"]["data"], "/9j/4AAQ");
    }

    #[test]
    fn request_puts_cache_control_on_system_block_not_root() {
        let system = vec![AnthropicSystemText {
            type_: "text",
            text: "You are helpful.",
            cache_control: Some(AnthropicCacheControl::Ephemeral),
        }];
        let request = AnthropicMessagesRequest {
            max_tokens: 128,
            model: "claude-haiku-4-5",
            messages: &[],
            system: Some(system),
            tools: &[],
            stream: true,
            thinking: None,
            output_config: None,
        };
        let json = serde_json::to_value(&request).unwrap();
        assert!(json.get("cache_control").is_none());
        assert_eq!(json["system"][0]["type"], "text");
        assert_eq!(json["system"][0]["text"], "You are helpful.");
        assert_eq!(json["system"][0]["cache_control"]["type"], "ephemeral");
        assert!(json["system"][0]["cache_control"].get("ttl").is_none());
    }

    #[test]
    fn request_omits_system_when_empty() {
        let request = AnthropicMessagesRequest {
            max_tokens: 128,
            model: "claude-haiku-4-5",
            messages: &[],
            system: None,
            tools: &[],
            stream: true,
            thinking: None,
            output_config: None,
        };
        let json = serde_json::to_value(&request).unwrap();
        assert!(json.get("system").is_none());
    }

    #[test]
    fn adaptive_thinking_uses_effort_not_budget() {
        let (thinking, output_config) =
            thinking_request_fields(ThinkingMode::Adaptive, Some(Effort::High));
        let request = AnthropicMessagesRequest {
            max_tokens: 128,
            model: "claude-opus-4-8",
            messages: &[],
            system: None,
            tools: &[],
            stream: true,
            thinking,
            output_config,
        };
        let json = serde_json::to_value(&request).unwrap();
        assert_eq!(json["thinking"]["type"], "adaptive");
        assert_eq!(json["thinking"]["display"], "summarized");
        assert!(json["thinking"].get("budget_tokens").is_none());
        assert_eq!(json["output_config"]["effort"], "high");
    }

    #[test]
    fn manual_thinking_uses_budget_tokens() {
        let (thinking, output_config) =
            thinking_request_fields(ThinkingMode::Budget, Some(Effort::Medium));
        let request = AnthropicMessagesRequest {
            max_tokens: 128,
            model: "claude-haiku-4-5",
            messages: &[],
            system: None,
            tools: &[],
            stream: true,
            thinking,
            output_config,
        };
        let json = serde_json::to_value(&request).unwrap();
        assert_eq!(json["thinking"]["type"], "enabled");
        assert_eq!(
            json["thinking"]["budget_tokens"],
            Effort::Medium.budget_tokens()
        );
        assert!(json.get("output_config").is_none());
    }

    #[test]
    fn effort_budget_token_mapping() {
        assert_eq!(Effort::Low.budget_tokens(), 1_024);
        assert_eq!(Effort::Medium.budget_tokens(), 4_096);
        assert_eq!(Effort::High.budget_tokens(), 16_000);
        assert_eq!(Effort::Max.budget_tokens(), 64_000);
    }

    #[test]
    fn max_tokens_raised_above_enabled_thinking_budget() {
        // Default backend max_tokens is 8192; High budget is 16000 — request builder
        // must raise max_tokens (validated by reimplementing the clamp here).
        let budget = Effort::High.budget_tokens() as usize;
        let configured = 8192usize;
        let max_tokens = if configured <= budget {
            budget.saturating_add(1024)
        } else {
            configured
        };
        assert!(max_tokens > budget);
        assert_eq!(max_tokens, 16_000 + 1024);
    }

    #[test]
    fn thinking_omitted_when_effort_unset() {
        let (thinking, output_config) = thinking_request_fields(ThinkingMode::Adaptive, None);
        assert!(thinking.is_none());
        assert!(output_config.is_none());
    }

    #[test]
    fn thinking_mode_none_sends_no_thinking_fields() {
        let (thinking, output_config) =
            thinking_request_fields(ThinkingMode::None, Some(Effort::High));
        assert!(thinking.is_none());
        assert!(output_config.is_none());
    }

    #[test]
    fn test_sse_parser_basic() {
        let mut parser = SseParser::default();
        let chunk = b"event: message_start\ndata: {\"type\":\"message_start\"}\n\n\
                      data: {\"type\":\"ping\"}\n\n";
        let events = parser.push(chunk);
        assert_eq!(events.len(), 2);
        assert!(events[0].contains("message_start"));
        assert!(events[1].contains("ping"));
    }

    #[test]
    fn test_convert_messages_merges_consecutive_user() {
        let input = [
            Message::UserMessage {
                content: vec![Content::Text { text: "hi".into() }],
            },
            Message::ToolResults {
                tool_use_results: vec![ToolResult {
                    id: "toolu_1".into(),
                    content: vec![Content::Text { text: "ok".into() }],
                    is_error: false,
                }],
            },
        ];
        let msgs = convert_messages(&input);
        assert_eq!(msgs.len(), 1);
        assert!(matches!(msgs[0].role, AnthropicRole::User));
        assert_eq!(msgs[0].content.len(), 2);
        // tool_result blocks must come first in a user message.
        assert!(matches!(
            msgs[0].content[0],
            AnthropicContent::ToolResult { .. }
        ));
        assert!(matches!(msgs[0].content[1], AnthropicContent::Text { .. }));
    }

    #[test]
    fn thinking_delta_maps_to_content_delta() {
        let mut acc = StreamAccumulator::default();
        let parts = acc
            .handle_event(AnthropicStreamEvent::ContentBlockStart {
                index: 0,
                content_block: AnthropicStreamContentBlock::Thinking {
                    thinking: String::new(),
                    signature: Some("sig123".into()),
                },
            })
            .unwrap();
        assert!(matches!(
            &parts[0],
            MessagePart::ContentStart(ContentStart::Thinking {
                index: 0,
                signature: Some(s),
                redacted: false,
            }) if s == "sig123"
        ));

        let parts = acc
            .handle_event(AnthropicStreamEvent::ContentBlockDelta {
                index: 0,
                delta: AnthropicDelta::ThinkingDelta {
                    thinking: "step 1".into(),
                },
            })
            .unwrap();
        match &parts[0] {
            MessagePart::ContentDelta(ContentDelta::Thinking { index, delta }) => {
                assert_eq!(*index, 0);
                assert_eq!(delta, "step 1");
            }
            other => panic!("expected thinking delta, got {other:?}"),
        }

        let parts = acc
            .handle_event(AnthropicStreamEvent::ContentBlockStart {
                index: 1,
                content_block: AnthropicStreamContentBlock::Text { text: "hi".into() },
            })
            .unwrap();
        // content_index is remapped: thinking occupied content slot 0, text is 1.
        assert!(matches!(
            &parts[0],
            MessagePart::ContentStart(ContentStart::Text { index: 1 })
        ));
        assert!(matches!(
            &parts[1],
            MessagePart::ContentDelta(ContentDelta::Text { index: 1, delta }) if delta == "hi"
        ));
    }

    #[test]
    fn thinking_content_round_trips_signature() {
        let c = Content::Thinking {
            text: "secret plan".into(),
            signature: Some("sig".into()),
            redacted: false,
        };
        match AnthropicContent::from(c) {
            AnthropicContent::Thinking {
                thinking,
                signature,
            } => {
                assert_eq!(thinking, "secret plan");
                assert_eq!(signature.as_deref(), Some("sig"));
            }
            other => panic!("expected thinking wire block, got {other:?}"),
        }

        let redacted = Content::Thinking {
            text: String::new(),
            signature: Some("opaque".into()),
            redacted: true,
        };
        match AnthropicContent::from(redacted) {
            AnthropicContent::RedactedThinking { data } => assert_eq!(data, "opaque"),
            other => panic!("expected redacted_thinking, got {other:?}"),
        }
    }

    #[test]
    fn test_stream_accumulator_text_and_tool_index_remap() {
        let mut acc = StreamAccumulator::default();

        let items = acc
            .handle_event(AnthropicStreamEvent::ContentBlockStart {
                index: 0,
                content_block: AnthropicStreamContentBlock::Text {
                    text: String::new(),
                },
            })
            .unwrap();
        assert!(matches!(
            items[0],
            MessagePart::ContentStart(ContentStart::Text { index: 0 })
        ));

        let items = acc
            .handle_event(AnthropicStreamEvent::ContentBlockDelta {
                index: 0,
                delta: AnthropicDelta::TextDelta { text: "Hi".into() },
            })
            .unwrap();
        match &items[0] {
            MessagePart::ContentDelta(ContentDelta::Text { index, delta }) => {
                assert_eq!(*index, 0);
                assert_eq!(delta, "Hi");
            }
            _ => panic!(),
        }

        let items = acc
            .handle_event(AnthropicStreamEvent::ContentBlockStart {
                index: 1,
                content_block: AnthropicStreamContentBlock::ToolUse {
                    id: "toolu_1".into(),
                    name: "get_weather".into(),
                    input: serde_json::json!({}),
                },
            })
            .unwrap();
        match &items[0] {
            MessagePart::ToolUseStart(ToolUseStart { index, id, name }) => {
                assert_eq!(*index, 0); // remapped tool index
                assert_eq!(id, "toolu_1");
                assert_eq!(name, "get_weather");
            }
            _ => panic!(),
        }

        let items = acc
            .handle_event(AnthropicStreamEvent::ContentBlockDelta {
                index: 1,
                delta: AnthropicDelta::InputJsonDelta {
                    partial_json: r#"{"city":"SF"}"#.into(),
                },
            })
            .unwrap();
        match &items[0] {
            MessagePart::ToolUseDelta(ToolUseDelta {
                index,
                input_json_delta,
            }) => {
                assert_eq!(*index, 0);
                assert_eq!(input_json_delta, r#"{"city":"SF"}"#);
            }
            _ => panic!(),
        }

        acc.handle_event(AnthropicStreamEvent::MessageDelta {
            delta: AnthropicMessageDelta {
                stop_reason: Some(AnthropicStopReason::ToolUse),
            },
            usage: None,
        })
        .unwrap();
        acc.handle_event(AnthropicStreamEvent::MessageStop).unwrap();
        acc.finish().unwrap();
    }
}