mindfork 0.16.0

A terminal AI chat written in Rust: local models via llama.cpp, or OpenAI, Anthropic, Gemini, Grok and OpenRouter in the cloud, with persistent memory, notes, RAG and tools.
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
//! Serde types for the Anthropic Messages protocol (`/v1/messages`) and translating the domain
//! [`ChatRequest`] into its format. Differences from OpenAI (see ADR 0004, Phase 2):
//! - the system message — a **top-level** `system` field (not a role in `messages`);
//! - only `user`/`assistant` roles; tool results — `tool_result` blocks
//!   **inside a user message** (there's no `tool` role);
//! - assistant tool calls — `tool_use` blocks in its `content`;
//! - `max_tokens` is **required**; a tool's schema is `input_schema` (not `parameters`).
//!
//! Adjacent messages of the same role are merged (Anthropic requires strict
//! user/assistant alternation; our agentic-loop produces several `tool` messages in a row →
//! one user block).

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::entities::sampling::ReasoningEffort;
use crate::shared::api::contract::{ApiImage, ApiMessage, ApiRole, ChatRequest};
use crate::shared::api::effort::CarriesEffort;
use crate::shared::api::error::EngineError;

/// The default `max_tokens` if unset in sampling (Anthropic requires the field).
pub const DEFAULT_MAX_TOKENS: u64 = 4096;

// ---------- request ----------

#[derive(Debug, Serialize)]
pub struct AntRequest {
    pub model: String,
    pub max_tokens: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system: Option<String>,
    pub messages: Vec<AntMessage>,
    pub stream: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<AntTool>>,
    /// Extended thinking. Modern Claude models (Opus 4.6+/Sonnet 4.6/Fable 5) accept
    /// only `{type:"adaptive"}` — the old `budget_tokens` gets a `400`. `display:
    /// "summarized"` is needed so the "thoughts" text arrives non-empty (default `omitted`).
    /// Sent only when reasoning is enabled. See docs/journal/engine.md (CoT for Claude).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking: Option<AntThinking>,
    /// Reasoning depth (`output_config.effort`, GA). Sent only with thinking and
    /// a set `reasoning_effort` (except `none`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_config: Option<AntOutputConfig>,
}

/// Anthropic's extended-thinking config. `type` is `adaptive` — the only "on"
/// mode from Opus 4.7 on — or, for the 4.5 generation, which has no adaptive
/// mode, `enabled` with a `budget_tokens` ([`AntRequest::think_within_a_budget`]);
/// `display` — `summarized` for a visible CoT, taken by both.
#[derive(Debug, Serialize)]
pub struct AntThinking {
    #[serde(rename = "type")]
    pub kind: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub budget_tokens: Option<u64>,
    pub display: &'static str,
}

/// Anthropic's `output_config`: effort level (`low`/`medium`/`high`/`xhigh`/`max`).
#[derive(Debug, Serialize)]
pub struct AntOutputConfig {
    pub effort: &'static str,
}

#[derive(Debug, Serialize)]
pub struct AntMessage {
    pub role: &'static str,
    pub content: Vec<AntBlock>,
}

/// A message content block. Serialized with an internal `type` tag.
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AntBlock {
    Text {
        text: String,
    },
    /// A reasoning block (extended thinking) for resending. Must come **first**
    /// in an assistant turn with `tool_use`; the signature is mandatory (otherwise `400`). See
    /// [`ThinkingBlock`](crate::shared::api::contract::ThinkingBlock).
    Thinking {
        thinking: String,
        signature: String,
    },
    ToolUse {
        id: String,
        name: String,
        input: Value,
    },
    ToolResult {
        tool_use_id: String,
        content: AntToolResultContent,
    },
    /// An image the user attached (spec §9.10). Anthropic takes three source types
    /// (base64, a URL, a Files-API `file_id`); we send base64, because the payload is
    /// already in hand — the chat file stores it — and the other two would add an upload
    /// round trip or a hosting requirement for no gain at our sizes.
    Image {
        source: AntImageSource,
    },
}

/// The `content` of an [`AntBlock::ToolResult`]: a plain string, or an array of blocks.
///
/// Anthropic accepts both, and the array form is the only way an image can ride along with
/// a tool's answer (verified live on claude-haiku-4-5,
/// docs/research/mcp-tool-images.md §2.2). The `untagged` representation is what keeps the
/// promise: a result with no images serializes as the bare JSON string this builder has
/// always emitted, byte for byte. Pinned by
/// `a_tool_result_without_images_keeps_its_string_content`.
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum AntToolResultContent {
    Text(String),
    Blocks(Vec<AntBlock>),
}

/// The `source` of an [`AntBlock::Image`]. Only the base64 variant exists here; the
/// struct is separate (rather than inline fields) because Anthropic nests it, and
/// `media_type` is a required sibling of the data rather than a guess from the bytes.
#[derive(Debug, Serialize)]
pub struct AntImageSource {
    #[serde(rename = "type")]
    pub kind: &'static str,
    pub media_type: String,
    pub data: String,
}

#[derive(Debug, Serialize)]
pub struct AntTool {
    pub name: String,
    pub description: String,
    pub input_schema: Value,
}

/// Builds the Anthropic request body from the domain [`ChatRequest`]. `model` is required.
/// From sampling, **only `max_tokens`** is sent (the required field): the newest
/// Claude models (4.x) have "locked in" sampling and reject `temperature`/`top_p`/`top_k`
/// as deprecated (HTTP 400), so these fields aren't sent at all. The UI marks them
/// as unsupported for Claude. See ADR 0004 and docs/journal/engine.md (Phase 2).
pub fn build_request(req: &ChatRequest, model: &str, stream: bool) -> AntRequest {
    let tools = if req.tools.is_empty() {
        None
    } else {
        Some(
            req.tools
                .iter()
                .map(|t| AntTool {
                    name: t.name.clone(),
                    description: t.description.clone(),
                    input_schema: t.parameters.clone(),
                })
                .collect(),
        )
    };
    // Extended thinking is enabled by the sampling `thinking` flag, in the adaptive
    // shape: from Opus 4.7 on `budget_tokens` is a `400`, and depth is set by `effort`.
    // The sampling's `reasoning_budget` is never sent. A model that has no adaptive
    // mode — the 4.5 generation — refuses this shape, and the client asks again in
    // the other one (`AntRequest::think_within_a_budget`).
    // A continuation request (`/continue`, spec §6.4) goes out without it:
    // Anthropic rejects a prefill combined with extended thinking, and resuming
    // a visible reply must not re-open reasoning — the same choice the
    // OpenAI-compatible wire makes with `enable_thinking: false`.
    let thinking =
        (req.sampling.thinking == Some(true) && !req.continue_final).then_some(AntThinking {
            kind: ADAPTIVE,
            budget_tokens: None,
            display: "summarized",
        });
    let output_config = thinking.as_ref().and_then(|_| {
        req.sampling
            .reasoning_effort
            .and_then(ant_effort)
            .map(|effort| AntOutputConfig { effort })
    });
    let mut messages = build_messages(req);
    // The trailing assistant message is the prefill being continued, and
    // Anthropic rejects a prefill that ends in whitespace — the **wire copy**
    // is right-trimmed; the stored message keeps its bytes (the seam caveat is
    // recorded in docs/research/continue-generation.md §4h).
    if req.continue_final
        && let Some(last) = messages.last_mut().filter(|m| m.role == "assistant")
        && let Some(AntBlock::Text { text }) = last.content.last_mut()
    {
        text.truncate(text.trim_end().len());
    }
    AntRequest {
        model: model.to_string(),
        max_tokens: req
            .sampling
            .max_tokens
            .map(|m| m as u64)
            .unwrap_or(DEFAULT_MAX_TOKENS),
        system: req.system.clone(),
        messages,
        stream,
        tools,
        thinking,
        output_config,
    }
}

/// The effort level → Anthropic's `output_config.effort` value. `None`
/// (including `ReasoningEffort::None`) — the field isn't sent.
///
/// The API's vocabulary is `low`/`medium`/`high`/`xhigh`/`max` (measured
/// 2026-10-01, docs/research/effort-tiers.md §2): `minimal` is a schema error
/// there, so it rides as `low`; the top two are sent as they are. Which of them
/// a **model** has is its own — the 4.6 generation has `max` and no `xhigh` —
/// and its refusal names what it takes, which the client answers
/// ([`refuses_effort`]).
fn ant_effort(e: ReasoningEffort) -> Option<&'static str> {
    match e {
        ReasoningEffort::None => None,
        ReasoningEffort::Minimal | ReasoningEffort::Low => Some("low"),
        ReasoningEffort::Medium => Some("medium"),
        ReasoningEffort::High => Some("high"),
        ReasoningEffort::XHigh => Some("xhigh"),
        ReasoningEffort::Max => Some("max"),
    }
}

impl CarriesEffort for AntRequest {
    /// The `output_config.effort` the body carries — sent only with thinking on.
    fn effort(&self) -> Option<&'static str> {
        self.output_config.as_ref().map(|c| c.effort)
    }

    /// Asks for `instead` in place of that effort; with `None` the config goes
    /// and the model reasons at its own depth.
    fn respell_effort(&mut self, instead: Option<&'static str>) {
        if self.output_config.is_some() {
            self.output_config = instead.map(|effort| AntOutputConfig { effort });
        }
    }
}

/// `thinking.type` for the mode where the model decides how much to think.
const ADAPTIVE: &str = "adaptive";

/// The least a thinking budget may be — the API's own floor (*"budget_tokens:
/// Input should be greater than or equal to 1024"*).
const MIN_THINKING_BUDGET: u64 = 1024;

impl AntRequest {
    /// Whether the body asks for adaptive thinking — the shape a model of the
    /// 4.5 generation refuses.
    pub fn thinks_adaptively(&self) -> bool {
        self.thinking.as_ref().is_some_and(|t| t.kind == ADAPTIVE)
    }

    /// Rewrites adaptive thinking in the shape the 4.5 generation takes:
    /// `{type: "enabled", budget_tokens}`. A body that does not think adaptively
    /// is left as it is.
    ///
    /// Measured 2026-10-01 on `claude-haiku-4-5`, `claude-sonnet-4-5` and
    /// `claude-opus-4-5` (docs/journal/engine.md): adaptive is a `400` on all
    /// three, `enabled` with a budget a `200` with a `thinking` block, and
    /// `display: "summarized"` is taken beside it.
    ///
    /// - **The effort becomes the budget** ([`thinking_budget`]) and
    ///   `output_config` goes: Sonnet 4.5 and Haiku 4.5 answer any effort with
    ///   *"This model does not support the effort parameter"*, and one rule
    ///   for the three is worth more than Opus 4.5's `low`…`high`.
    /// - **Half the reply's cap at most.** `max_tokens` covers the thinking and
    ///   the answer, and the API refuses a budget that is not below it; half
    ///   leaves the answer at least as much as the thoughts.
    /// - **No room, no thinking.** Under the API's floor of 1024 the turn goes
    ///   out without thinking rather than not at all.
    pub fn think_within_a_budget(&mut self) {
        if !self.thinks_adaptively() {
            return;
        }
        let wished = thinking_budget(self.output_config.as_ref().map(|c| c.effort));
        self.output_config = None;
        let room = self.max_tokens / 2;
        self.thinking = (room >= MIN_THINKING_BUDGET).then(|| AntThinking {
            kind: "enabled",
            budget_tokens: Some(wished.min(room)),
            display: "summarized",
        });
    }
}

/// The thinking budget an effort level stands for, in tokens — the table the
/// Gemini 2.5 wire already maps the same scale onto (`gemini::wire`): `low`
/// 1024, `medium` 8192, `high` and above 24576. A turn that names no depth
/// thinks at `medium`'s.
fn thinking_budget(effort: Option<&str>) -> u64 {
    match effort {
        Some("low") => MIN_THINKING_BUDGET,
        Some("high" | "xhigh" | "max") => 24576,
        _ => 8192,
    }
}

/// Whether a failed request was refused for asking to think adaptively —
/// *"adaptive thinking is not supported on this model"*. A `400` only, and two
/// substrings rather than the sentence, because providers reword; a false
/// positive costs one extra round trip.
pub fn refuses_adaptive_thinking(err: &EngineError) -> bool {
    if err.status != Some(400) {
        return false;
    }
    let message = err.message.to_lowercase();
    message.contains("adaptive thinking") && message.contains("not supported")
}

/// Whether a failed request was refused for the effort level it carried —
/// *"This model does not support effort level 'xhigh'. Supported levels: high,
/// low, max, medium."* A `400` only, and the two words rather than the
/// sentence, because providers reword; a false positive costs one extra round
/// trip.
pub fn refuses_effort(err: &EngineError) -> bool {
    err.status == Some(400) && err.message.to_lowercase().contains("effort level")
}

/// Translates history into Anthropic messages, merging adjacent ones of the same role.
fn build_messages(req: &ChatRequest) -> Vec<AntMessage> {
    let mut out: Vec<AntMessage> = Vec::new();
    for m in &req.messages {
        let (role, blocks): (&'static str, Vec<AntBlock>) = match m.role {
            ApiRole::User => ("user", user_blocks(m)),
            ApiRole::Assistant => {
                let mut blocks = Vec::new();
                // A thinking block (with a signature) must go FIRST in an assistant turn with
                // tool_use — otherwise Anthropic returns 400. Only placed on the current
                // agentic-loop turn (see ApiMessage::with_thinking_blocks). One block per reply
                // without the interleaved-thinking beta, which the app does not request;
                // were several to arrive, each would be resent as its own block.
                for tb in &m.thinking {
                    blocks.push(AntBlock::Thinking {
                        thinking: tb.text.clone(),
                        signature: tb.signature.clone(),
                    });
                }
                blocks.extend(text_blocks(&m.content));
                for tc in &m.tool_calls {
                    // Our arguments are a JSON string; Anthropic STRICTLY requires
                    // `input` to be an OBJECT. An argument-less call could have been saved
                    // in history as `null` (old chats), and `"null"`/an array/a scalar
                    // would parse into a non-object → Anthropic 400 ("tool_use.input:
                    // Input should be an object"). Any non-object is coerced to `{}`.
                    let input = serde_json::from_str::<Value>(&tc.arguments)
                        .ok()
                        .filter(Value::is_object)
                        .unwrap_or_else(|| serde_json::json!({}));
                    blocks.push(AntBlock::ToolUse {
                        id: tc.id.clone(),
                        name: tc.name.clone(),
                        input,
                    });
                }
                ("assistant", blocks)
            }
            // A tool result → a tool_result block inside a user message.
            ApiRole::Tool => ("user", vec![tool_result_block(m)]),
            // The system message goes as the top-level `system` field, not in messages.
            ApiRole::System => continue,
        };
        if blocks.is_empty() {
            continue;
        }
        match out.last_mut() {
            Some(last) if last.role == role => last.content.extend(blocks),
            _ => out.push(AntMessage {
                role,
                content: blocks,
            }),
        }
    }
    out
}

fn text_blocks(content: &str) -> Vec<AntBlock> {
    if content.is_empty() {
        Vec::new()
    } else {
        vec![AntBlock::Text {
            text: content.to_string(),
        }]
    }
}

/// The blocks of a user turn: images (each behind its label) first, then the text.
///
/// Images before text is Anthropic's own documented recommendation, and it is the order
/// every backend in this project uses so that a prompt behaves the same wherever it is
/// sent. A message with no images produces exactly what [`text_blocks`] always did.
fn user_blocks(m: &ApiMessage) -> Vec<AntBlock> {
    if m.images.is_empty() {
        return text_blocks(&m.content);
    }
    let mut blocks = image_blocks(&m.images);
    blocks.extend(text_blocks(&m.content));
    blocks
}

/// Image blocks, each preceded by its label when it has one. Shared by the user turn and
/// the tool result, so both carry an image in exactly the same base64 shape.
fn image_blocks(images: &[ApiImage]) -> Vec<AntBlock> {
    let mut blocks = Vec::with_capacity(images.len() * 2);
    for image in images {
        if let Some(label) = &image.label {
            blocks.push(AntBlock::Text {
                text: label.clone(),
            });
        }
        blocks.push(AntBlock::Image {
            source: AntImageSource {
                kind: "base64",
                media_type: image.mime.clone(),
                data: image.data.to_string(),
            },
        });
    }
    blocks
}

/// The `tool_result` block for a tool message (spec §9.10, docs/research/mcp-tool-images.md).
///
/// With no images the `content` stays the plain string it always was. With images it
/// becomes an array of blocks — the tool's own text **first** (it is the answer; the image
/// illustrates it), then each image behind its label. Anthropic's images-before-text advice
/// is about a user's request, not a tool's output, so the user ordering is deliberately not
/// mirrored here.
fn tool_result_block(m: &ApiMessage) -> AntBlock {
    let tool_use_id = m.tool_call_id.clone().unwrap_or_default();
    if m.images.is_empty() {
        return AntBlock::ToolResult {
            tool_use_id,
            content: AntToolResultContent::Text(m.content.clone()),
        };
    }
    let mut blocks = text_blocks(&m.content);
    blocks.extend(image_blocks(&m.images));
    AntBlock::ToolResult {
        tool_use_id,
        content: AntToolResultContent::Blocks(blocks),
    }
}

// ---------- streaming events ----------

/// An Anthropic SSE stream event (the tag is the `type` field in `data`). Uninteresting events
/// (`ping`, `content_block_stop`, `message_stop`) land in [`AntStreamEvent::Other`].
///
/// `error` is **not** one of them, though it used to be: Anthropic documents that a
/// failure after the stream opens arrives as an `error` event — an
/// `overloaded_error` there is the same condition as a pre-stream `529` — and
/// letting it fall into `Other` made an overloaded truncation identical to a normal
/// completion (docs/research/cloud-retry-backoff.md §1.2).
#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AntStreamEvent {
    MessageStart {
        message: AntStartMessage,
    },
    ContentBlockStart {
        index: usize,
        content_block: AntStartBlock,
    },
    ContentBlockDelta {
        index: usize,
        delta: AntDelta,
    },
    MessageDelta {
        delta: AntStopDelta,
        #[serde(default)]
        usage: Option<AntUsage>,
    },
    Error {
        #[serde(default)]
        error: AntStreamError,
    },
    #[serde(other)]
    Other,
}

/// The payload of an in-stream `error` event. `type` names the condition
/// (`overloaded_error`, `api_error`, …) and is the half worth showing; `message` is
/// prose and can be empty.
#[derive(Debug, Default, Deserialize)]
pub struct AntStreamError {
    #[serde(default, rename = "type")]
    pub name: String,
    #[serde(default)]
    pub message: String,
}

#[derive(Debug, Deserialize)]
pub struct AntStartMessage {
    #[serde(default)]
    pub usage: Option<AntUsage>,
}

/// The start of a content block. Only `tool_use` matters (gives id+tool name).
#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AntStartBlock {
    ToolUse {
        id: String,
        name: String,
    },
    #[serde(other)]
    Other,
}

/// A content block delta.
#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AntDelta {
    TextDelta {
        text: String,
    },
    InputJsonDelta {
        partial_json: String,
    },
    ThinkingDelta {
        thinking: String,
    },
    /// The "thoughts" block's signature (arrives at the end of the thinking block). Needed for
    /// resending thinking on tool-use in the same turn.
    SignatureDelta {
        signature: String,
    },
    #[serde(other)]
    Other,
}

#[derive(Debug, Default, Deserialize)]
pub struct AntStopDelta {
    #[serde(default)]
    pub stop_reason: Option<String>,
}

#[derive(Debug, Default, Deserialize)]
pub struct AntUsage {
    #[serde(default)]
    pub input_tokens: u32,
    #[serde(default)]
    pub output_tokens: u32,
}

/// `claude-haiku-4-5`'s answer to a thinking turn, as it came on 2026-10-01.
#[cfg(test)]
pub(super) const ADAPTIVE_REFUSED: &str = r#"{"type":"error","error":{"type":"invalid_request_error","message":"adaptive thinking is not supported on this model"},"request_id":"req_x"}"#;

/// `claude-sonnet-4-6`'s answer to `effort: "xhigh"`, as it came on 2026-10-01 —
/// the fixture of this module's tests and the client's.
#[cfg(test)]
pub(super) const EFFORT_REFUSED: &str = r#"{"type":"error","error":{"type":"invalid_request_error","message":"This model does not support effort level 'xhigh'. Supported levels: high, low, max, medium."},"request_id":"req_x"}"#;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::entities::sampling::{ReasoningEffort, SamplingConfig};
    use crate::shared::api::contract::{ApiMessage, ApiToolCall, ThinkingBlock, ToolSchema};

    fn req(messages: Vec<ApiMessage>) -> ChatRequest {
        ChatRequest {
            continue_final: false,
            system: Some("Ты — ассистент.".into()),
            messages,
            sampling: SamplingConfig {
                temperature: Some(0.7),
                top_k: Some(40),
                max_tokens: Some(256),
                ..Default::default()
            },
            tools: vec![],
        }
    }

    /// A user turn with no images must serialize exactly as it did before image
    /// support — one text block, nothing else. The mirror of the Chat Completions
    /// guarantee (spec §9.10): a text-only conversation cannot change shape because a
    /// sibling feature landed.
    #[test]
    fn a_text_only_user_turn_is_unchanged_by_the_image_support() {
        let body = build_request(&req(vec![ApiMessage::user("привет")]), "claude-x", false);
        let json = serde_json::to_value(&body).unwrap();
        let content = json["messages"][0]["content"].as_array().unwrap();
        assert_eq!(content.len(), 1);
        assert_eq!(content[0]["type"], "text");
        assert_eq!(content[0]["text"], "привет");
    }

    #[test]
    fn images_become_base64_blocks_ahead_of_the_text() {
        let msg =
            ApiMessage::user("what is this?").with_images(vec![crate::shared::api::ApiImage::new(
                "image/png",
                "QUJD",
                Some("Image #1 — \"a.png\":".into()),
            )]);
        let json = serde_json::to_value(build_request(&req(vec![msg]), "claude-x", false)).unwrap();
        let content = json["messages"][0]["content"].as_array().unwrap();
        // Label, image, then the user's own words — the order Anthropic documents.
        assert_eq!(content.len(), 3);
        assert_eq!(content[0]["type"], "text");
        assert_eq!(content[0]["text"], "Image #1 — \"a.png\":");
        assert_eq!(content[1]["type"], "image");
        assert_eq!(content[1]["source"]["type"], "base64");
        assert_eq!(content[1]["source"]["media_type"], "image/png");
        assert_eq!(
            content[1]["source"]["data"], "QUJD",
            "the payload is bare base64 here, NOT a data: URI — that is the OpenAI shape"
        );
        assert_eq!(content[2]["text"], "what is this?");
    }

    /// An image-only message ("look at this") must not grow an empty text block:
    /// Anthropic rejects a blank `text`, so this is a 400 rather than cosmetics.
    #[test]
    fn an_image_only_turn_carries_no_empty_text_block() {
        let msg = ApiMessage::user("").with_images(vec![crate::shared::api::ApiImage::new(
            "image/jpeg",
            "QQ==",
            None,
        )]);
        let json = serde_json::to_value(build_request(&req(vec![msg]), "claude-x", false)).unwrap();
        let content = json["messages"][0]["content"].as_array().unwrap();
        assert_eq!(content.len(), 1);
        assert_eq!(content[0]["type"], "image");
        assert_eq!(content[0]["source"]["media_type"], "image/jpeg");
    }

    /// The tool-side half of the same guarantee: without images the `tool_result`
    /// `content` must stay a bare JSON **string**, not a one-element block array. Every
    /// stored conversation that ever called a tool replays through this path.
    #[test]
    fn a_tool_result_without_images_keeps_its_string_content() {
        let r = req(vec![
            ApiMessage::user("посчитай"),
            ApiMessage::assistant_tool_calls(
                "",
                vec![ApiToolCall {
                    thought_signature: None,
                    id: "t1".into(),
                    name: "calc".into(),
                    arguments: "{}".into(),
                }],
            ),
            ApiMessage::tool("t1", "2"),
        ]);
        let json = serde_json::to_value(build_request(&r, "claude-x", false)).unwrap();
        let block = &json["messages"][2]["content"][0];
        assert_eq!(block["type"], "tool_result");
        assert!(
            block["content"].is_string(),
            "a result with no images must serialize as a string, got {:?}",
            block["content"]
        );
        assert_eq!(block["content"], "2");
    }

    /// An MCP screenshot tool: `tool_result.content` widens into an array of blocks —
    /// the result text first, then the labelled image as bare base64.
    #[test]
    fn a_tool_result_image_becomes_a_block_after_the_result_text() {
        let r = req(vec![
            ApiMessage::user("сними скриншот"),
            ApiMessage::assistant_tool_calls(
                "",
                vec![ApiToolCall {
                    thought_signature: None,
                    id: "t1".into(),
                    name: "screenshot".into(),
                    arguments: "{}".into(),
                }],
            ),
            ApiMessage::tool("t1", "screenshot taken").with_images(vec![
                crate::shared::api::ApiImage::new(
                    "image/png",
                    "QUJD",
                    Some("Image #1 — \"shot.png\":".into()),
                ),
            ]),
        ]);
        let json = serde_json::to_value(build_request(&r, "claude-x", false)).unwrap();
        let block = &json["messages"][2]["content"][0];
        assert_eq!(block["type"], "tool_result");
        assert_eq!(block["tool_use_id"], "t1");
        let inner = block["content"].as_array().unwrap();
        assert_eq!(inner.len(), 3);
        assert_eq!(inner[0]["type"], "text");
        assert_eq!(inner[0]["text"], "screenshot taken");
        assert_eq!(inner[1]["type"], "text");
        assert_eq!(inner[1]["text"], "Image #1 — \"shot.png\":");
        assert_eq!(inner[2]["type"], "image");
        assert_eq!(inner[2]["source"]["type"], "base64");
        assert_eq!(inner[2]["source"]["media_type"], "image/png");
        assert_eq!(
            inner[2]["source"]["data"], "QUJD",
            "bare base64 inside a tool_result too — never a data: URI"
        );
    }

    /// A tool that returns only an image must not add an empty `text` block: Anthropic
    /// rejects a blank `text`, so this is a 400 rather than cosmetics.
    #[test]
    fn an_image_only_tool_result_carries_no_empty_text_block() {
        let r = req(vec![
            ApiMessage::user("сними скриншот"),
            ApiMessage::assistant_tool_calls(
                "",
                vec![ApiToolCall {
                    thought_signature: None,
                    id: "t1".into(),
                    name: "screenshot".into(),
                    arguments: "{}".into(),
                }],
            ),
            ApiMessage::tool("t1", "").with_images(vec![crate::shared::api::ApiImage::new(
                "image/jpeg",
                "QQ==",
                None,
            )]),
        ]);
        let json = serde_json::to_value(build_request(&r, "claude-x", false)).unwrap();
        let inner = json["messages"][2]["content"][0]["content"]
            .as_array()
            .unwrap();
        assert_eq!(inner.len(), 1);
        assert_eq!(inner[0]["type"], "image");
        assert_eq!(inner[0]["source"]["media_type"], "image/jpeg");
    }

    #[test]
    fn system_is_top_level_and_sampling_mapped() {
        let body = build_request(&req(vec![ApiMessage::user("привет")]), "claude-x", true);
        let json = serde_json::to_value(&body).unwrap();
        assert_eq!(json["model"], "claude-x");
        assert_eq!(json["system"], "Ты — ассистент.");
        assert_eq!(json["max_tokens"], 256);
        // Claude 4.x doesn't accept temperature/top_p/top_k — don't send them at all.
        assert!(json.get("temperature").is_none());
        assert!(json.get("top_p").is_none());
        assert!(json.get("top_k").is_none());
        // The message — a user with a text block.
        assert_eq!(json["messages"][0]["role"], "user");
        assert_eq!(json["messages"][0]["content"][0]["type"], "text");
        assert_eq!(json["messages"][0]["content"][0]["text"], "привет");
    }

    #[test]
    fn max_tokens_defaults_when_absent() {
        let mut r = req(vec![ApiMessage::user("hi")]);
        r.sampling.max_tokens = None;
        let json = serde_json::to_value(build_request(&r, "claude-x", false)).unwrap();
        assert_eq!(json["max_tokens"], DEFAULT_MAX_TOKENS);
    }

    #[test]
    fn tool_calls_become_tool_use_and_results_merge_into_user() {
        // assistant(tool_use) → tool → tool: two results merge into one user.
        let r = req(vec![
            ApiMessage::user("посчитай"),
            ApiMessage::assistant_tool_calls(
                "",
                vec![ApiToolCall {
                    thought_signature: None,
                    id: "t1".into(),
                    name: "calc".into(),
                    arguments: "{\"x\":1}".into(),
                }],
            ),
            ApiMessage::tool("t1", "2"),
            ApiMessage::tool("t1", "доп"),
        ]);
        let json = serde_json::to_value(build_request(&r, "claude-x", true)).unwrap();
        // [0] user, [1] assistant(tool_use), [2] user(2× tool_result).
        assert_eq!(json["messages"][1]["role"], "assistant");
        assert_eq!(json["messages"][1]["content"][0]["type"], "tool_use");
        assert_eq!(json["messages"][1]["content"][0]["name"], "calc");
        assert_eq!(json["messages"][1]["content"][0]["input"]["x"], 1);
        assert_eq!(json["messages"][2]["role"], "user");
        assert_eq!(json["messages"][2]["content"][0]["type"], "tool_result");
        assert_eq!(json["messages"][2]["content"][0]["tool_use_id"], "t1");
        assert_eq!(json["messages"][2]["content"][1]["content"], "доп");
    }

    #[test]
    fn tool_use_input_coerced_to_object_when_not_object() {
        // An argument-less call could have been saved in history as `null` → the string "null".
        // Anthropic strictly requires an object — coerce to `{}` (otherwise 400).
        for raw in ["null", "", "[1,2]", "42", "\"x\""] {
            let r = req(vec![
                ApiMessage::user("введи"),
                ApiMessage::assistant_tool_calls(
                    "",
                    vec![ApiToolCall {
                        thought_signature: None,
                        id: "t1".into(),
                        name: "get_sampling".into(),
                        arguments: raw.into(),
                    }],
                ),
            ]);
            let json = serde_json::to_value(build_request(&r, "claude-x", true)).unwrap();
            let input = &json["messages"][1]["content"][0]["input"];
            assert!(
                input.is_object(),
                "input must be an object for arguments={raw:?}, got {input}"
            );
        }
    }

    #[test]
    fn tools_use_input_schema() {
        let mut r = req(vec![ApiMessage::user("hi")]);
        r.tools = vec![ToolSchema {
            name: "calc".into(),
            description: "Считает".into(),
            parameters: serde_json::json!({"type":"object"}),
        }];
        let json = serde_json::to_value(build_request(&r, "claude-x", true)).unwrap();
        assert_eq!(json["tools"][0]["name"], "calc");
        assert_eq!(json["tools"][0]["input_schema"]["type"], "object");
        assert!(json["tools"][0].get("parameters").is_none());
    }

    #[test]
    fn parses_stream_events() {
        let start =
            r#"{"type":"message_start","message":{"usage":{"input_tokens":25,"output_tokens":1}}}"#;
        match serde_json::from_str::<AntStreamEvent>(start).unwrap() {
            AntStreamEvent::MessageStart { message } => {
                assert_eq!(message.usage.unwrap().input_tokens, 25)
            }
            other => panic!("expected MessageStart, got {other:?}"),
        }
        let td =
            r#"{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}"#;
        match serde_json::from_str::<AntStreamEvent>(td).unwrap() {
            AntStreamEvent::ContentBlockDelta {
                delta: AntDelta::TextDelta { text },
                ..
            } => assert_eq!(text, "hi"),
            other => panic!("expected TextDelta, got {other:?}"),
        }
        let tu = r#"{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"tu1","name":"calc","input":{}}}"#;
        match serde_json::from_str::<AntStreamEvent>(tu).unwrap() {
            AntStreamEvent::ContentBlockStart {
                index,
                content_block: AntStartBlock::ToolUse { id, name },
            } => {
                assert_eq!(index, 1);
                assert_eq!(id, "tu1");
                assert_eq!(name, "calc");
            }
            other => panic!("expected ToolUse start, got {other:?}"),
        }
        let md = r#"{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":15}}"#;
        match serde_json::from_str::<AntStreamEvent>(md).unwrap() {
            AntStreamEvent::MessageDelta { delta, usage } => {
                assert_eq!(delta.stop_reason.as_deref(), Some("tool_use"));
                assert_eq!(usage.unwrap().output_tokens, 15);
            }
            other => panic!("expected MessageDelta, got {other:?}"),
        }
        // ping/other — Other (no crash).
        assert!(matches!(
            serde_json::from_str::<AntStreamEvent>(r#"{"type":"ping"}"#).unwrap(),
            AntStreamEvent::Other
        ));
    }

    #[test]
    fn thinking_off_by_default() {
        // Default sampling (thinking=None) — the thinking field isn't sent.
        let json = serde_json::to_value(build_request(
            &req(vec![ApiMessage::user("привет")]),
            "claude-x",
            true,
        ))
        .unwrap();
        assert!(json.get("thinking").is_none());
        assert!(json.get("output_config").is_none());
    }

    #[test]
    fn thinking_enabled_sends_adaptive_with_effort() {
        // thinking=true → adaptive+summarized; reasoning_effort → output_config.effort.
        // Claude 4.x rejects budget_tokens (reasoning_budget) — DON'T send it.
        let mut r = req(vec![ApiMessage::user("посчитай")]);
        r.sampling.thinking = Some(true);
        r.sampling.reasoning_effort = Some(ReasoningEffort::High);
        r.sampling.reasoning_budget = Some(0);
        let json = serde_json::to_value(build_request(&r, "claude-x", true)).unwrap();
        assert_eq!(json["thinking"]["type"], "adaptive");
        assert_eq!(json["thinking"]["display"], "summarized");
        assert_eq!(json["output_config"]["effort"], "high");
        // reasoning_budget doesn't leak out (no budget_tokens key).
        assert!(json.get("budget_tokens").is_none());
        assert!(json["thinking"].get("budget_tokens").is_none());
    }

    #[test]
    fn thinking_effort_none_omits_output_config() {
        // thinking is enabled, but effort isn't set → output_config isn't sent.
        let mut r = req(vec![ApiMessage::user("hi")]);
        r.sampling.thinking = Some(true);
        let json = serde_json::to_value(build_request(&r, "claude-x", true)).unwrap();
        assert_eq!(json["thinking"]["type"], "adaptive");
        assert!(json.get("output_config").is_none());
    }

    /// A thinking turn at `effort`.
    fn thinking_at(effort: ReasoningEffort) -> AntRequest {
        let mut r = req(vec![ApiMessage::user("hi")]);
        r.sampling.thinking = Some(true);
        r.sampling.reasoning_effort = Some(effort);
        build_request(&r, "claude-x", true)
    }

    /// The API's own five levels: the top two go out as they are — `xhigh` rode
    /// as `high` until the API had the value — and `minimal`, which it has not,
    /// as `low`.
    #[test]
    fn the_scale_maps_onto_the_apis_five_levels() {
        for (effort, sent) in [
            (ReasoningEffort::Minimal, "low"),
            (ReasoningEffort::Low, "low"),
            (ReasoningEffort::Medium, "medium"),
            (ReasoningEffort::High, "high"),
            (ReasoningEffort::XHigh, "xhigh"),
            (ReasoningEffort::Max, "max"),
        ] {
            assert_eq!(thinking_at(effort).effort(), Some(sent), "{effort:?}");
        }
        // The switch is not a level: thinking on with `none` sends no config.
        assert_eq!(thinking_at(ReasoningEffort::None).effort(), None);
    }

    #[test]
    fn a_refused_level_is_respelt_or_removed() {
        let mut body = thinking_at(ReasoningEffort::XHigh);
        body.respell_effort(Some("high"));
        let json = serde_json::to_value(&body).unwrap();
        assert_eq!(json["output_config"]["effort"], "high");
        assert_eq!(json["thinking"]["type"], "adaptive", "thinking stays on");
        body.respell_effort(None);
        let json = serde_json::to_value(&body).unwrap();
        assert!(json.get("output_config").is_none(), "{json}");
        // A body that carries no effort gains none.
        let mut plain = build_request(&req(vec![ApiMessage::user("hi")]), "claude-x", true);
        plain.respell_effort(Some("high"));
        assert_eq!(plain.effort(), None);
    }

    #[test]
    fn only_a_400_about_the_effort_level_is_a_refusal_of_it() {
        let refusal = |status: u16, body: &str| {
            EngineError::status(
                crate::shared::api::error::SUBJECT_ANTHROPIC,
                reqwest::StatusCode::from_u16(status).unwrap(),
                &reqwest::header::HeaderMap::new(),
                body,
            )
        };
        assert!(refuses_effort(&refusal(400, EFFORT_REFUSED)));
        assert!(!refuses_effort(&refusal(529, EFFORT_REFUSED)));
        // The other `400` a thinking turn can meet, measured on the 4.5 generation —
        // each predicate reads its own refusal and not the other's.
        assert!(!refuses_effort(&refusal(400, ADAPTIVE_REFUSED)));
        assert!(refuses_adaptive_thinking(&refusal(400, ADAPTIVE_REFUSED)));
        assert!(!refuses_adaptive_thinking(&refusal(529, ADAPTIVE_REFUSED)));
        assert!(!refuses_adaptive_thinking(&refusal(400, EFFORT_REFUSED)));
    }

    /// A thinking turn at `effort` (or at none) under a reply cap of `max_tokens`,
    /// rewritten for a model without adaptive thinking.
    fn budgeted(effort: Option<ReasoningEffort>, max_tokens: usize) -> serde_json::Value {
        let mut r = req(vec![ApiMessage::user("hi")]);
        r.sampling.thinking = Some(true);
        r.sampling.reasoning_effort = effort;
        r.sampling.max_tokens = Some(max_tokens);
        let mut body = build_request(&r, "claude-x", true);
        assert!(body.thinks_adaptively());
        body.think_within_a_budget();
        assert!(!body.thinks_adaptively());
        serde_json::to_value(&body).unwrap()
    }

    /// The effort becomes the budget, capped at half the reply's cap, and the
    /// effort parameter itself goes — Sonnet 4.5 and Haiku 4.5 have none.
    #[test]
    fn adaptive_thinking_is_rewritten_as_a_budget() {
        for (effort, max_tokens, budget) in [
            // Room for every wish.
            (Some(ReasoningEffort::Minimal), 64000, 1024),
            (Some(ReasoningEffort::Low), 64000, 1024),
            (Some(ReasoningEffort::Medium), 64000, 8192),
            (Some(ReasoningEffort::High), 64000, 24576),
            (Some(ReasoningEffort::XHigh), 64000, 24576),
            (Some(ReasoningEffort::Max), 64000, 24576),
            // No depth named, or the switch beside thinking on: `medium`'s.
            (None, 64000, 8192),
            (Some(ReasoningEffort::None), 64000, 8192),
            // The app's default cap: half of it is the ceiling.
            (Some(ReasoningEffort::High), 16384, 8192),
            (None, 16384, 8192),
            // The least room there is.
            (Some(ReasoningEffort::High), 2048, 1024),
        ] {
            let json = budgeted(effort, max_tokens);
            assert_eq!(
                json["thinking"],
                serde_json::json!({"type": "enabled", "budget_tokens": budget, "display": "summarized"}),
                "{effort:?} under {max_tokens}"
            );
            assert!(json.get("output_config").is_none(), "{effort:?}: {json}");
            assert!(
                json["thinking"]["budget_tokens"].as_u64().unwrap()
                    < json["max_tokens"].as_u64().unwrap(),
                "the API refuses a budget that is not below the cap"
            );
        }
    }

    /// Under the API's floor there is no budget to give: the turn goes out
    /// without thinking, and without the effort that rode beside it.
    #[test]
    fn no_room_for_a_budget_means_no_thinking() {
        let json = budgeted(Some(ReasoningEffort::High), 2047);
        assert!(json.get("thinking").is_none(), "{json}");
        assert!(json.get("output_config").is_none(), "{json}");
    }

    /// A turn that does not think has nothing to rewrite, and the adaptive
    /// shape itself is unchanged on the wire.
    #[test]
    fn a_turn_without_adaptive_thinking_is_left_alone() {
        let mut plain = build_request(&req(vec![ApiMessage::user("hi")]), "claude-x", true);
        assert!(!plain.thinks_adaptively());
        plain.think_within_a_budget();
        assert!(
            serde_json::to_value(&plain)
                .unwrap()
                .get("thinking")
                .is_none()
        );
        let adaptive = serde_json::to_value(thinking_at(ReasoningEffort::High)).unwrap();
        assert_eq!(
            adaptive["thinking"],
            serde_json::json!({"type": "adaptive", "display": "summarized"})
        );
    }

    #[test]
    fn thinking_block_prepended_to_assistant_tool_use() {
        // An assistant turn with tool_use + a thinking block: thinking comes first (with a signature),
        // then tool_use. Anthropic requires exactly this order (otherwise 400).
        let r = req(vec![
            ApiMessage::user("посчитай"),
            ApiMessage::assistant_tool_calls(
                "",
                vec![ApiToolCall {
                    thought_signature: None,
                    id: "t1".into(),
                    name: "calc".into(),
                    arguments: "{\"x\":1}".into(),
                }],
            )
            .with_thinking_blocks(vec![ThinkingBlock {
                text: "надо сложить".into(),
                signature: "sig-abc".into(),
                id: None,
            }]),
            ApiMessage::tool("t1", "2"),
        ]);
        let json = serde_json::to_value(build_request(&r, "claude-x", true)).unwrap();
        let blocks = &json["messages"][1]["content"];
        assert_eq!(blocks[0]["type"], "thinking");
        assert_eq!(blocks[0]["thinking"], "надо сложить");
        assert_eq!(blocks[0]["signature"], "sig-abc");
        assert_eq!(blocks[1]["type"], "tool_use");
        assert_eq!(blocks[1]["name"], "calc");
    }

    #[test]
    fn assistant_without_thinking_has_no_thinking_block() {
        // Without a thinking block (a regular/historical turn) — no thinking block in the output.
        let r = req(vec![
            ApiMessage::user("посчитай"),
            ApiMessage::assistant_tool_calls(
                "",
                vec![ApiToolCall {
                    thought_signature: None,
                    id: "t1".into(),
                    name: "calc".into(),
                    arguments: "{}".into(),
                }],
            ),
            ApiMessage::tool("t1", "2"),
        ]);
        let json = serde_json::to_value(build_request(&r, "claude-x", true)).unwrap();
        assert_eq!(json["messages"][1]["content"][0]["type"], "tool_use");
    }

    #[test]
    fn parses_signature_delta() {
        let sd = r#"{"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig-xyz"}}"#;
        match serde_json::from_str::<AntStreamEvent>(sd).unwrap() {
            AntStreamEvent::ContentBlockDelta {
                delta: AntDelta::SignatureDelta { signature },
                ..
            } => assert_eq!(signature, "sig-xyz"),
            other => panic!("expected SignatureDelta, got {other:?}"),
        }
    }
}

/// In-stream `error` events — the shape Anthropic sheds load with once a stream is
/// open. See docs/research/cloud-retry-backoff.md §1.2.
#[cfg(test)]
mod stream_error_tests {
    use super::*;

    #[test]
    fn an_overloaded_error_event_is_parsed_rather_than_ignored() {
        // Verbatim from Anthropic's streaming docs.
        let data = r#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#;
        let event: AntStreamEvent = serde_json::from_str(data).unwrap();
        let AntStreamEvent::Error { error } = event else {
            panic!("an error event must not land in Other — that is the defect");
        };
        assert_eq!(error.name, "overloaded_error");
        assert_eq!(error.message, "Overloaded");
        assert!(crate::shared::api::error::stream_error_transient(
            &error.name,
            None
        ));
    }

    #[test]
    fn an_error_event_without_a_message_still_names_the_condition() {
        let data = r#"{"type":"error","error":{"type":"api_error"}}"#;
        let AntStreamEvent::Error { error } = serde_json::from_str(data).unwrap() else {
            panic!("expected an error event")
        };
        assert_eq!(
            crate::shared::api::error::stream_error_text(&error.name, &error.message),
            "api_error"
        );
    }

    /// The events that genuinely carry nothing must keep falling through — the new
    /// variant must not widen into them.
    #[test]
    fn uninteresting_events_still_land_in_other() {
        for data in [
            r#"{"type":"ping"}"#,
            r#"{"type":"message_stop"}"#,
            r#"{"type":"content_block_stop","index":0}"#,
        ] {
            assert!(matches!(
                serde_json::from_str::<AntStreamEvent>(data).unwrap(),
                AntStreamEvent::Other
            ));
        }
    }

    /// `/continue` (spec §6.4): the flag right-trims the trailing prefill (a
    /// prefill ending in whitespace is a `400`) and drops the thinking block
    /// (prefill is incompatible with extended thinking) — and with it off the
    /// body is byte-identical, thinking included.
    #[test]
    fn continuation_trims_the_prefill_and_drops_thinking() {
        let mut r = ChatRequest {
            messages: vec![
                ApiMessage::user("вопрос"),
                ApiMessage::assistant("Оборванный ответ "),
            ],
            ..Default::default()
        };
        r.sampling.thinking = Some(true);
        let off = serde_json::to_value(build_request(&r, "claude-haiku-4-5", false)).unwrap();
        assert_eq!(
            off["messages"][1]["content"][0]["text"],
            "Оборванный ответ "
        );
        assert_eq!(off["thinking"]["type"], "adaptive");

        r.continue_final = true;
        let on = serde_json::to_value(build_request(&r, "claude-haiku-4-5", false)).unwrap();
        assert_eq!(
            on["messages"][1]["content"][0]["text"], "Оборванный ответ",
            "the wire copy is right-trimmed; the stored message keeps its bytes"
        );
        assert!(
            on.get("thinking").is_none(),
            "prefill is incompatible with extended thinking"
        );
        // ...and nothing else moves with the flag.
        let (mut a, mut b) = (off, on);
        for j in [&mut a, &mut b] {
            j.as_object_mut().unwrap().remove("thinking");
            j["messages"][1]["content"][0]
                .as_object_mut()
                .unwrap()
                .remove("text");
        }
        assert_eq!(
            a, b,
            "the flag touches only the trim and the thinking block"
        );
    }
}