aither-claude 0.22.0

Claude provider integration for aither
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
//! SSE response parsing for the Claude API.

use aither_core::llm::{Event as LLMEvent, ReasoningState, Usage as TokenUsage};

use crate::PROVIDER_NAME;
use serde::Deserialize;
use serde_json::Value;
use zenwave::sse::Event;

use crate::error::ClaudeError;

/// Initial `message_start` event data.
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct MessageStartEvent {
    /// The message object.
    pub message: MessageObject,
}

/// Message object from `message_start`.
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct MessageObject {
    /// Unique message ID.
    pub id: String,
    /// Model that generated the response.
    pub model: String,
    /// Reason the response stopped (null while streaming).
    #[serde(default)]
    pub stop_reason: Option<String>,
    /// Token usage information.
    #[serde(default)]
    pub usage: Option<Usage>,
}

/// Token usage information.
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct Usage {
    /// Number of input tokens.
    pub input_tokens: u32,
    /// Number of output tokens.
    pub output_tokens: u32,
    /// Number of input tokens written into cache.
    #[serde(default)]
    pub cache_creation_input_tokens: Option<u32>,
    /// Number of input tokens read from cache.
    #[serde(default)]
    pub cache_read_input_tokens: Option<u32>,
    /// Detailed cache creation token counts by TTL.
    #[serde(default)]
    pub cache_creation: Option<CacheCreation>,
}

impl Usage {
    fn cache_write_tokens(&self) -> Option<u32> {
        self.cache_creation_input_tokens
            .or_else(|| self.cache_creation.as_ref().and_then(CacheCreation::total))
    }
}

/// Content block start event data.
#[derive(Debug, Deserialize)]
pub struct ContentBlockStartEvent {
    /// Index of this content block.
    pub index: usize,
    /// The content block being started.
    pub content_block: ContentBlockType,
}

/// Types of content blocks.
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type")]
#[allow(dead_code)]
pub enum ContentBlockType {
    /// Text content block.
    #[serde(rename = "text")]
    Text {
        /// Initial text (usually empty).
        text: String,
    },
    /// Thinking/reasoning content block.
    #[serde(rename = "thinking")]
    Thinking {
        /// Initial thinking text. Empty when `display` is `omitted`.
        thinking: String,
        /// Encrypted copy of the full reasoning, replayed back unmodified.
        #[serde(default)]
        signature: String,
    },
    /// Safety-redacted thinking. Carries no readable text, only ciphertext.
    #[serde(rename = "redacted_thinking")]
    RedactedThinking {
        /// Opaque encrypted thinking, replayed back unmodified.
        data: String,
    },
    /// Tool use content block.
    #[serde(rename = "tool_use")]
    ToolUse {
        /// Unique ID for this tool use.
        id: String,
        /// Tool name.
        name: String,
        /// Tool input (builds up via deltas).
        #[serde(default)]
        input: Value,
    },
    /// Server-executed tool use — the API runs it, the caller only observes.
    #[serde(rename = "server_tool_use")]
    ServerToolUse {
        /// Unique ID for this tool use.
        id: String,
        /// Tool name (`web_search`, `web_fetch`, `code_execution`, ...).
        name: String,
        /// Tool input (builds up via `input_json_delta`).
        #[serde(default)]
        input: Value,
    },
    /// Result of a server-side web search.
    #[serde(rename = "web_search_tool_result")]
    WebSearchToolResult {
        /// ID of the `server_tool_use` block this answers.
        tool_use_id: String,
        /// Search hits or an error object.
        #[serde(default)]
        content: Value,
    },
    /// Result of a server-side web fetch.
    #[serde(rename = "web_fetch_tool_result")]
    WebFetchToolResult {
        /// ID of the `server_tool_use` block this answers.
        tool_use_id: String,
        /// Retrieved document or an error object.
        #[serde(default)]
        content: Value,
    },
    /// Result of a server-side code execution.
    #[serde(rename = "code_execution_tool_result")]
    CodeExecutionToolResult {
        /// ID of the `server_tool_use` block this answers.
        tool_use_id: String,
        /// Execution output or an error object.
        #[serde(default)]
        content: Value,
    },
    /// Result of a server-side bash code execution.
    #[serde(rename = "bash_code_execution_tool_result")]
    BashCodeExecutionToolResult {
        /// ID of the `server_tool_use` block this answers.
        tool_use_id: String,
        /// Execution output or an error object.
        #[serde(default)]
        content: Value,
    },
    /// Result of a server-side text-editor code execution.
    #[serde(rename = "text_editor_code_execution_tool_result")]
    TextEditorCodeExecutionToolResult {
        /// ID of the `server_tool_use` block this answers.
        tool_use_id: String,
        /// Execution output or an error object.
        #[serde(default)]
        content: Value,
    },
    /// A block type this crate does not model yet — ignored rather than
    /// fatal, matching the API's forwards-compatibility contract.
    #[serde(other)]
    Unknown,
}

/// Content block delta event data.
#[derive(Debug, Deserialize)]
pub struct ContentBlockDeltaEvent {
    /// Index of the content block being updated.
    pub index: usize,
    /// The delta update.
    pub delta: DeltaType,
}

/// Types of delta updates.
#[derive(Debug, Deserialize)]
#[serde(tag = "type")]
#[allow(clippy::enum_variant_names)]
pub enum DeltaType {
    /// Text delta.
    #[serde(rename = "text_delta")]
    TextDelta {
        /// Text fragment to append.
        text: String,
    },
    /// Thinking delta.
    #[serde(rename = "thinking_delta")]
    ThinkingDelta {
        /// Thinking fragment to append.
        thinking: String,
    },
    /// Signature delta, arriving once just before the thinking block closes.
    #[serde(rename = "signature_delta")]
    SignatureDelta {
        /// The block's signature.
        signature: String,
    },
    /// Input JSON delta for tool use.
    #[serde(rename = "input_json_delta")]
    InputJsonDelta {
        /// Partial JSON to append.
        partial_json: String,
    },
    /// A delta type this crate does not model yet — ignored rather than
    /// fatal, matching the API's forwards-compatibility contract.
    #[serde(other)]
    Unknown,
}

/// Message delta event data (final updates).
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct MessageDeltaEvent {
    /// Delta updates to the message.
    pub delta: MessageDelta,
    /// Updated usage information.
    #[serde(default)]
    pub usage: Option<DeltaUsage>,
}

/// Message-level delta updates.
#[derive(Debug, Deserialize)]
pub struct MessageDelta {
    /// Reason the response stopped.
    pub stop_reason: Option<String>,
}

/// Usage information in message delta.
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct DeltaUsage {
    /// Total output tokens.
    #[serde(default)]
    pub output_tokens: Option<u32>,
    /// Number of input tokens written into cache.
    #[serde(default)]
    pub cache_creation_input_tokens: Option<u32>,
    /// Number of input tokens read from cache.
    #[serde(default)]
    pub cache_read_input_tokens: Option<u32>,
    /// Detailed cache creation token counts by TTL.
    #[serde(default)]
    pub cache_creation: Option<CacheCreation>,
}

impl DeltaUsage {
    fn cache_write_tokens(&self) -> Option<u32> {
        self.cache_creation_input_tokens
            .or_else(|| self.cache_creation.as_ref().and_then(CacheCreation::total))
    }
}

/// Detailed cache creation token counts by TTL.
#[derive(Debug, Deserialize)]
pub struct CacheCreation {
    /// Tokens created with 5-minute TTL.
    #[serde(default)]
    pub ephemeral_5m_input_tokens: Option<u32>,
    /// Tokens created with 1-hour TTL.
    #[serde(default)]
    pub ephemeral_1h_input_tokens: Option<u32>,
}

impl CacheCreation {
    fn total(&self) -> Option<u32> {
        // `None` and `Some(0)` mean different things here: the former is
        // "the API said nothing about cache creation", the latter "nothing was
        // cached", so only sum when at least one field was reported.
        match (
            self.ephemeral_5m_input_tokens,
            self.ephemeral_1h_input_tokens,
        ) {
            (None, None) => None,
            (a, b) => Some(a.unwrap_or(0).saturating_add(b.unwrap_or(0))),
        }
    }
}

/// Parsed tool call from a completed `tool_use` block.
#[derive(Debug, Clone)]
pub struct ToolCall {
    /// Unique ID for this tool use.
    pub id: String,
    /// Tool name.
    pub name: String,
    /// Parsed tool input.
    pub input: Value,
}

/// Non-streaming `/v1/messages` response body.
///
/// The wire shape mirrors the terminal state an SSE stream ends in: the same
/// content blocks arrive complete rather than as start/delta/stop triples.
#[derive(Debug, Deserialize)]
pub struct MessagesResponse {
    /// Content blocks produced by the model.
    pub content: Vec<ContentBlockType>,
    /// Reason generation stopped.
    #[serde(default)]
    pub stop_reason: Option<String>,
    /// Token usage for the call.
    #[serde(default)]
    pub usage: Option<Usage>,
}

/// Projects a non-streaming [`MessagesResponse`] into the same event stream a
/// streaming response would have produced.
///
/// Each block is replayed through the same start/delta/stop handling the SSE
/// parser drives, so every block type the stream can carry is projected by
/// construction rather than re-implemented here.
#[must_use]
pub fn response_events(response: MessagesResponse) -> Vec<LLMEvent> {
    let mut state = StreamState::new();
    let mut events = Vec::new();
    for (index, block) in response.content.into_iter().enumerate() {
        events.extend(state.replay_block(index, block));
    }
    if let Some(usage) = response.usage {
        state.uncached_input_tokens = Some(usage.input_tokens);
        state.completion_tokens = Some(usage.output_tokens);
        state.cache_write_tokens = usage.cache_write_tokens();
        state.cache_read_tokens = usage.cache_read_input_tokens;
        state.refresh_prompt_tokens();
    }
    state.stop_reason = response.stop_reason;
    events.extend(state.maybe_usage_event());
    for call in state.tool_calls {
        events.push(LLMEvent::tool_call(call.id, call.name, call.input));
    }
    events
}

/// State for tracking content blocks during streaming.
#[derive(Debug, Default)]
pub struct StreamState {
    /// Current content blocks being built.
    pub blocks: Vec<BlockState>,
    /// Completed tool calls.
    pub tool_calls: Vec<ToolCall>,
    /// Final stop reason.
    pub stop_reason: Option<String>,
    /// Prompt/input token usage.
    pub prompt_tokens: Option<u32>,
    /// Uncached input tokens (`usage.input_tokens` from Claude).
    pub uncached_input_tokens: Option<u32>,
    /// Completion/output token usage.
    pub completion_tokens: Option<u32>,
    /// Prompt cache read token usage.
    pub cache_read_tokens: Option<u32>,
    /// Prompt cache write token usage.
    pub cache_write_tokens: Option<u32>,
    /// Whether usage has already been emitted.
    pub usage_emitted: bool,
}

/// State of an individual content block.
#[derive(Debug, Clone)]
pub enum BlockState {
    /// Text block with accumulated text.
    Text(String),
    /// Thinking block with accumulated reasoning and its signature.
    Thinking {
        /// Accumulated thinking text; empty when `display` is `omitted`.
        text: String,
        /// Signature, which arrives as a single delta before the block closes.
        signature: String,
    },
    /// Safety-redacted thinking block.
    RedactedThinking(String),
    /// Tool use block with accumulated JSON.
    ToolUse {
        /// Tool use ID.
        id: String,
        /// Tool name.
        name: String,
        /// Accumulated input JSON string.
        input_json: String,
    },
    /// Server-executed tool use with accumulated input JSON.
    ServerToolUse {
        /// Tool use ID.
        id: String,
        /// Tool name.
        name: String,
        /// Accumulated input JSON string.
        input_json: String,
    },
}

impl StreamState {
    /// Create a new empty stream state.
    pub fn new() -> Self {
        Self::default()
    }

    fn maybe_usage_event(&mut self) -> Option<LLMEvent> {
        if self.usage_emitted {
            return None;
        }
        if self.prompt_tokens.is_none()
            && self.completion_tokens.is_none()
            && self.cache_read_tokens.is_none()
            && self.cache_write_tokens.is_none()
            && self.stop_reason.is_none()
        {
            return None;
        }
        self.usage_emitted = true;
        let total_tokens = match (self.prompt_tokens, self.completion_tokens) {
            (Some(prompt), Some(completion)) => Some(prompt + completion),
            _ => None,
        };
        Some(LLMEvent::Usage(TokenUsage {
            prompt_tokens: self.prompt_tokens,
            completion_tokens: self.completion_tokens,
            total_tokens,
            reasoning_tokens: None,
            cache_read_tokens: self.cache_read_tokens,
            cache_write_tokens: self.cache_write_tokens,
            cost_usd: None,
            stop_reason: self.stop_reason.clone(),
        }))
    }

    fn refresh_prompt_tokens(&mut self) {
        // As above: report a total only when the API reported at least one of
        // the components, so "not stated" stays distinct from "zero".
        let parts = [
            self.uncached_input_tokens,
            self.cache_read_tokens,
            self.cache_write_tokens,
        ];
        self.prompt_tokens = parts.iter().any(Option::is_some).then(|| {
            parts
                .iter()
                .flatten()
                .fold(0u32, |total, part| total.saturating_add(*part))
        });
    }
}

/// Parse a single SSE event into LLM events.
///
/// Updates the stream state and returns events to emit.
///
/// # Errors
///
/// Returns [`ClaudeError`] if the event body does not parse, or if the API sent
/// an `error` event.
pub fn parse_event(event: &Event, state: &mut StreamState) -> Result<Vec<LLMEvent>, ClaudeError> {
    let data = event.text_data();

    match event.event().unwrap_or("") {
        "message_start" => {
            state.apply_message_start(serde_json::from_str(data)?);
            Ok(Vec::new())
        }
        "content_block_start" => Ok(state.begin_block(serde_json::from_str(data)?)),
        "content_block_delta" => Ok(state.apply_block_delta(serde_json::from_str(data)?)),
        "content_block_stop" => {
            #[derive(Deserialize)]
            struct StopEvent {
                index: usize,
            }
            let ev: StopEvent = serde_json::from_str(data)?;
            Ok(state.finish_block(ev.index))
        }
        "message_delta" => {
            state.apply_message_delta(serde_json::from_str(data)?);
            Ok(Vec::new())
        }
        "message_stop" => Ok(state.maybe_usage_event().into_iter().collect()),
        // Keepalives carry nothing to emit.
        "ping" | "" => Ok(Vec::new()),
        "error" => Err(parse_error_event(data)),
        unknown => {
            // Anthropic adds event types over time; an unfamiliar one is not a
            // reason to fail the stream.
            tracing::debug!("Unknown Claude SSE event type: {unknown}");
            Ok(Vec::new())
        }
    }
}

/// Reads the message out of an `error` event, falling back to its raw body.
fn parse_error_event(data: &str) -> ClaudeError {
    #[derive(Deserialize)]
    struct ErrorEvent {
        error: ErrorDetail,
    }
    #[derive(Deserialize)]
    struct ErrorDetail {
        #[serde(rename = "type")]
        error_type: String,
        message: String,
    }

    serde_json::from_str::<ErrorEvent>(data).map_or_else(
        |_| ClaudeError::Api(data.to_string()),
        |ev| ClaudeError::StreamEvent {
            error_type: ev.error.error_type,
            message: ev.error.message,
        },
    )
}

impl StreamState {
    /// Records the usage figures the API reports when a message opens.
    fn apply_message_start(&mut self, ev: MessageStartEvent) {
        let Some(usage) = ev.message.usage else {
            return;
        };
        self.uncached_input_tokens = Some(usage.input_tokens);
        self.completion_tokens = Some(usage.output_tokens);
        self.cache_write_tokens = usage.cache_write_tokens();
        self.cache_read_tokens = usage.cache_read_input_tokens;
        self.refresh_prompt_tokens();
    }

    /// Opens a content block, emitting whatever text arrived with it.
    fn begin_block(&mut self, ev: ContentBlockStartEvent) -> Vec<LLMEvent> {
        ensure_block_capacity(self, ev.index);

        // Server tool results carry their payload whole at block start.
        if let Some((tool, tool_use_id, content)) = ev.content_block.server_tool_result() {
            return vec![LLMEvent::builtin_result(
                tool_use_id,
                tool,
                server_tool_result_text(tool, content),
            )];
        }

        match ev.content_block {
            ContentBlockType::Text { text } => {
                self.blocks[ev.index] = BlockState::Text(text.clone());
                if text.is_empty() {
                    Vec::new()
                } else {
                    vec![LLMEvent::Text(text)]
                }
            }
            ContentBlockType::Thinking {
                thinking,
                signature,
            } => {
                self.blocks[ev.index] = BlockState::Thinking {
                    text: thinking.clone(),
                    signature,
                };
                if thinking.is_empty() {
                    Vec::new()
                } else {
                    vec![LLMEvent::Reasoning(thinking)]
                }
            }
            // Redacted thinking has no readable text, so it produces no
            // Reasoning event — only state, emitted when the block closes.
            ContentBlockType::RedactedThinking { data } => {
                self.blocks[ev.index] = BlockState::RedactedThinking(data);
                Vec::new()
            }
            ContentBlockType::ToolUse { id, name, .. } => {
                // Emit an initial delta so a UI can show the tool name before
                // any arguments have streamed in.
                let started = LLMEvent::ToolCallDelta {
                    id: id.clone(),
                    name: name.clone(),
                    arguments_fragment: String::new(),
                };
                self.blocks[ev.index] = BlockState::ToolUse {
                    id,
                    name,
                    input_json: String::new(),
                };
                vec![started]
            }
            ContentBlockType::ServerToolUse { id, name, .. } => {
                self.blocks[ev.index] = BlockState::ServerToolUse {
                    id,
                    name,
                    input_json: String::new(),
                };
                Vec::new()
            }
            // Server tool results were handled above; unknown blocks drop.
            _ => Vec::new(),
        }
    }

    /// Appends a delta to its block, emitting it if it is text the caller sees.
    ///
    /// A delta whose type does not match the block it names is dropped: the two
    /// disagreeing leaves nothing meaningful to append.
    fn apply_block_delta(&mut self, ev: ContentBlockDeltaEvent) -> Vec<LLMEvent> {
        let Some(block) = self.blocks.get_mut(ev.index) else {
            return Vec::new();
        };

        match (block, ev.delta) {
            (BlockState::Text(text), DeltaType::TextDelta { text: delta }) => {
                text.push_str(&delta);
                vec![LLMEvent::Text(delta)]
            }
            (BlockState::Thinking { text, .. }, DeltaType::ThinkingDelta { thinking: delta }) => {
                text.push_str(&delta);
                vec![LLMEvent::Reasoning(delta)]
            }
            // Arrives once, just before content_block_stop. With
            // `display: "omitted"` it is the only delta the block produces.
            (
                BlockState::Thinking { signature, .. },
                DeltaType::SignatureDelta {
                    signature: delta, ..
                },
            ) => {
                signature.push_str(&delta);
                Vec::new()
            }
            (
                BlockState::ToolUse {
                    id,
                    name,
                    input_json,
                },
                DeltaType::InputJsonDelta { partial_json },
            ) => {
                input_json.push_str(&partial_json);
                vec![LLMEvent::ToolCallDelta {
                    id: id.clone(),
                    name: name.clone(),
                    arguments_fragment: partial_json,
                }]
            }
            (
                BlockState::ServerToolUse { input_json, .. },
                DeltaType::InputJsonDelta { partial_json },
            ) => {
                input_json.push_str(&partial_json);
                Vec::new()
            }
            _ => Vec::new(),
        }
    }

    /// Closes a content block, turning a finished tool-use block into a call.
    ///
    /// Arguments that did not parse become an empty object rather than failing
    /// the stream: the tool reports the mismatch far more usefully than a
    /// truncated JSON error would.
    /// A closed thinking block emits its state here rather than at block start,
    /// because the signature arrives last: only now is the block complete
    /// enough to be replayed. The payload is the whole block re-serialized, so
    /// that `thinking` and `redacted_thinking` — which have different shapes —
    /// both round-trip without core knowing either.
    fn finish_block(&mut self, index: usize) -> Vec<LLMEvent> {
        match self.blocks.get(index) {
            Some(BlockState::ToolUse {
                id,
                name,
                input_json,
            }) => {
                let input = serde_json::from_str(input_json)
                    .unwrap_or_else(|_| Value::Object(serde_json::Map::new()));
                self.tool_calls.push(ToolCall {
                    id: id.clone(),
                    name: name.clone(),
                    input,
                });
                Vec::new()
            }
            Some(BlockState::Thinking { text, signature }) => {
                // An unsigned block cannot be verified on replay, so there is
                // nothing worth preserving.
                if signature.is_empty() {
                    return Vec::new();
                }
                let block = serde_json::json!({
                    "type": "thinking",
                    "thinking": text,
                    "signature": signature,
                });
                vec![LLMEvent::ReasoningState(ReasoningState::new(
                    PROVIDER_NAME,
                    block.to_string(),
                ))]
            }
            Some(BlockState::RedactedThinking(data)) => {
                let block = serde_json::json!({
                    "type": "redacted_thinking",
                    "data": data,
                });
                vec![LLMEvent::ReasoningState(ReasoningState::new(
                    PROVIDER_NAME,
                    block.to_string(),
                ))]
            }
            Some(BlockState::ServerToolUse {
                id,
                name,
                input_json,
            }) => {
                let input = serde_json::from_str::<Value>(input_json)
                    .unwrap_or_else(|_| Value::Object(serde_json::Map::new()));
                // The server runs the call between this block and the result
                // block, so the call event belongs at close — with the input
                // complete — not at open.
                vec![LLMEvent::builtin_call(
                    id,
                    name,
                    server_tool_call_detail(&input),
                )]
            }
            Some(BlockState::Text(_)) | None => Vec::new(),
        }
    }

    /// Folds in the running usage figures the API reports as it generates.
    fn apply_message_delta(&mut self, ev: MessageDeltaEvent) {
        self.stop_reason = ev.delta.stop_reason;
        let Some(usage) = ev.usage else {
            return;
        };
        if let Some(output_tokens) = usage.output_tokens {
            self.completion_tokens = Some(output_tokens);
        }
        if let Some(cache_write_tokens) = usage.cache_write_tokens() {
            self.cache_write_tokens = Some(cache_write_tokens);
        }
        if let Some(cache_read_tokens) = usage.cache_read_input_tokens {
            self.cache_read_tokens = Some(cache_read_tokens);
        }
        self.refresh_prompt_tokens();
    }

    /// Replays a complete content block through the block lifecycle —
    /// non-streaming responses deliver whole blocks, so this synthesizes the
    /// start/delta/stop sequence a stream would have carried for them.
    ///
    /// Tool input travels as `input_json_delta` events on a block that opens
    /// with an empty `input`, and a missing input means the stream sent none.
    fn replay_block(&mut self, index: usize, block: ContentBlockType) -> Vec<LLMEvent> {
        let input_json = match &block {
            ContentBlockType::ToolUse { input, .. }
            | ContentBlockType::ServerToolUse { input, .. }
                if !input.is_null() =>
            {
                Some(input.to_string())
            }
            _ => None,
        };
        let mut events = self.begin_block(ContentBlockStartEvent {
            index,
            content_block: block,
        });
        if let Some(partial_json) = input_json {
            events.extend(self.apply_block_delta(ContentBlockDeltaEvent {
                index,
                delta: DeltaType::InputJsonDelta { partial_json },
            }));
        }
        events.extend(self.finish_block(index));
        events
    }
}

/// Ensure the blocks vector has capacity for the given index.
fn ensure_block_capacity(state: &mut StreamState, index: usize) {
    while state.blocks.len() <= index {
        state.blocks.push(BlockState::Text(String::new()));
    }
}

/// Check if an SSE event should be skipped.
pub fn should_skip_event(event: &Event) -> bool {
    let data = event.text_data();
    data.is_empty() || event.event() == Some("ping")
}

impl ContentBlockType {
    /// `(tool_name, tool_use_id, content)` for server tool result blocks —
    /// blocks the API executes itself and delivers whole.
    fn server_tool_result(&self) -> Option<(&'static str, &str, &Value)> {
        Some(match self {
            Self::WebSearchToolResult {
                tool_use_id,
                content,
            } => ("web_search", tool_use_id, content),
            Self::WebFetchToolResult {
                tool_use_id,
                content,
            } => ("web_fetch", tool_use_id, content),
            Self::CodeExecutionToolResult {
                tool_use_id,
                content,
            } => ("code_execution", tool_use_id, content),
            Self::BashCodeExecutionToolResult {
                tool_use_id,
                content,
            } => ("bash_code_execution", tool_use_id, content),
            Self::TextEditorCodeExecutionToolResult {
                tool_use_id,
                content,
            } => ("text_editor_code_execution", tool_use_id, content),
            _ => return None,
        })
    }
}

/// Invocation detail for a server tool call: the query, URL or command the
/// block carried, compact JSON otherwise.
fn server_tool_call_detail(input: &Value) -> String {
    for key in ["query", "url", "command", "code"] {
        if let Some(value) = input.get(key).and_then(Value::as_str) {
            return value.to_string();
        }
    }
    match input {
        Value::Object(map) if map.is_empty() => String::new(),
        other => other.to_string(),
    }
}

/// One-line summary of a server tool result block: the error code on failure,
/// a result count or output excerpt on success.
fn server_tool_result_text(tool: &str, content: &Value) -> String {
    if let Some(code) = content.get("error_code").and_then(Value::as_str) {
        return format!("error: {code}");
    }
    if tool == "web_search" {
        // `web_search_result_block` wraps a list of hits.
        if let Some(hits) = content.get("content").and_then(Value::as_array) {
            return format!("{} results", hits.len());
        }
        if content.is_array() {
            return format!("{} results", content.as_array().map_or(0, Vec::len));
        }
    }
    if tool == "web_fetch"
        && let Some(url) = content.get("url").and_then(Value::as_str)
    {
        return format!("fetched {url}");
    }
    if let Some(text) = ["stdout", "stderr"]
        .iter()
        .filter_map(|key| content.get(*key).and_then(Value::as_str))
        .find(|text| !text.is_empty())
    {
        return text.chars().take(200).collect();
    }
    "completed".to_string()
}

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

    fn block_start(data: &str) -> ContentBlockStartEvent {
        serde_json::from_str(data).expect("content_block_start parses")
    }

    #[test]
    fn server_tool_use_emits_builtin_call_at_block_close() {
        let mut state = StreamState::new();
        let events = state.begin_block(block_start(
            r#"{"index":0,"content_block":{"type":"server_tool_use","id":"srvtoolu_1","name":"web_search","input":{}}}"#,
        ));
        assert!(events.is_empty());

        let events = state.apply_block_delta(
            serde_json::from_str(
                r#"{"index":0,"delta":{"type":"input_json_delta","partial_json":"{\"query\":\"rust\"}"}}"#,
            )
            .expect("delta parses"),
        );
        assert!(events.is_empty());

        match state.finish_block(0).as_slice() {
            [LLMEvent::BuiltInToolCall { id, tool, detail }] => {
                assert_eq!(id, "srvtoolu_1");
                assert_eq!(tool, "web_search");
                assert_eq!(detail, "rust");
            }
            other => panic!("expected BuiltInToolCall, got {other:?}"),
        }
        // Server calls never join the client-side tool queue.
        assert!(state.tool_calls.is_empty());
    }

    #[test]
    fn web_search_tool_result_emits_builtin_result() {
        let mut state = StreamState::new();
        match state
            .begin_block(block_start(
                r#"{"index":1,"content_block":{"type":"web_search_tool_result","tool_use_id":"srvtoolu_1","content":{"type":"web_search_result_block","content":[{"type":"web_search_result","title":"t","url":"u"}]}}}"#,
            ))
            .as_slice()
        {
            [LLMEvent::BuiltInToolResult { id, tool, result }] => {
                assert_eq!(id, "srvtoolu_1");
                assert_eq!(tool, "web_search");
                assert_eq!(result, "1 results");
            }
            other => panic!("expected BuiltInToolResult, got {other:?}"),
        }
    }

    #[test]
    fn unknown_block_types_are_tolerated() {
        let mut state = StreamState::new();
        let events = state.begin_block(block_start(
            r#"{"index":0,"content_block":{"type":"some_future_block","id":"x"}}"#,
        ));
        assert!(events.is_empty());
    }

    #[test]
    fn usage_event_includes_claude_cache_token_stats() {
        let mut state = StreamState::new();
        state.prompt_tokens = Some(120);
        state.completion_tokens = Some(30);
        state.cache_read_tokens = Some(90);
        state.cache_write_tokens = Some(45);
        state.stop_reason = Some("end_turn".to_string());

        let event = state
            .maybe_usage_event()
            .expect("usage event should be emitted");
        match event {
            LLMEvent::Usage(usage) => {
                assert_eq!(usage.prompt_tokens, Some(120));
                assert_eq!(usage.completion_tokens, Some(30));
                assert_eq!(usage.total_tokens, Some(150));
                assert_eq!(usage.cache_read_tokens, Some(90));
                assert_eq!(usage.cache_write_tokens, Some(45));
                assert_eq!(usage.stop_reason.as_deref(), Some("end_turn"));
            }
            _ => panic!("expected usage event"),
        }
    }

    #[test]
    fn usage_event_is_not_reemitted() {
        let mut state = StreamState::new();
        state.prompt_tokens = Some(1);
        assert!(state.maybe_usage_event().is_some());
        assert!(state.maybe_usage_event().is_none());
    }

    #[test]
    fn cache_creation_total_sums_5m_and_1h_tokens() {
        let cache_creation = CacheCreation {
            ephemeral_5m_input_tokens: Some(20),
            ephemeral_1h_input_tokens: Some(30),
        };
        assert_eq!(cache_creation.total(), Some(50));
    }

    #[test]
    fn refresh_prompt_tokens_adds_uncached_and_cache_tokens() {
        let mut state = StreamState::new();
        state.uncached_input_tokens = Some(40);
        state.cache_read_tokens = Some(30);
        state.cache_write_tokens = Some(10);
        state.refresh_prompt_tokens();
        assert_eq!(state.prompt_tokens, Some(80));
    }

    #[test]
    fn response_events_matches_streaming_projection() {
        let response: MessagesResponse = serde_json::from_str(
            r#"{
                "content": [
                    {"type": "text", "text": "Checking the weather."},
                    {"type": "thinking", "thinking": "Need a forecast.", "signature": "sig_1"},
                    {"type": "tool_use", "id": "toolu_1", "name": "get_weather", "input": {"city": "Paris"}},
                    {"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search", "input": {"query": "Paris weather"}},
                    {"type": "web_search_tool_result", "tool_use_id": "srvtoolu_1", "content": [{"type": "web_search_result", "title": "t", "url": "u"}]}
                ],
                "stop_reason": "tool_use",
                "usage": {"input_tokens": 40, "output_tokens": 30, "cache_read_input_tokens": 10, "cache_creation_input_tokens": 5}
            }"#,
        )
        .expect("response parses");

        // The same response as the API would have streamed it.
        let streamed = [
            (
                "message_start",
                r#"{"message":{"id":"msg_1","model":"claude-test","usage":{"input_tokens":40,"output_tokens":1,"cache_read_input_tokens":10,"cache_creation_input_tokens":5}}}"#,
            ),
            (
                "content_block_start",
                r#"{"index":0,"content_block":{"type":"text","text":""}}"#,
            ),
            (
                "content_block_delta",
                r#"{"index":0,"delta":{"type":"text_delta","text":"Checking the weather."}}"#,
            ),
            ("content_block_stop", r#"{"index":0}"#),
            (
                "content_block_start",
                r#"{"index":1,"content_block":{"type":"thinking","thinking":""}}"#,
            ),
            (
                "content_block_delta",
                r#"{"index":1,"delta":{"type":"thinking_delta","thinking":"Need a forecast."}}"#,
            ),
            (
                "content_block_delta",
                r#"{"index":1,"delta":{"type":"signature_delta","signature":"sig_1"}}"#,
            ),
            ("content_block_stop", r#"{"index":1}"#),
            (
                "content_block_start",
                r#"{"index":2,"content_block":{"type":"tool_use","id":"toolu_1","name":"get_weather","input":{}}}"#,
            ),
            (
                "content_block_delta",
                r#"{"index":2,"delta":{"type":"input_json_delta","partial_json":"{\"city\":\"Paris\"}"}}"#,
            ),
            ("content_block_stop", r#"{"index":2}"#),
            (
                "content_block_start",
                r#"{"index":3,"content_block":{"type":"server_tool_use","id":"srvtoolu_1","name":"web_search","input":{}}}"#,
            ),
            (
                "content_block_delta",
                r#"{"index":3,"delta":{"type":"input_json_delta","partial_json":"{\"query\":\"Paris weather\"}"}}"#,
            ),
            ("content_block_stop", r#"{"index":3}"#),
            (
                "content_block_start",
                r#"{"index":4,"content_block":{"type":"web_search_tool_result","tool_use_id":"srvtoolu_1","content":[{"type":"web_search_result","title":"t","url":"u"}]}}"#,
            ),
            ("content_block_stop", r#"{"index":4}"#),
            (
                "message_delta",
                r#"{"delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":30}}"#,
            ),
            ("message_stop", r#"{"type":"message_stop"}"#),
        ];

        let mut state = StreamState::new();
        let mut expected = Vec::new();
        for (kind, data) in streamed {
            expected.extend(
                parse_event(&Event::from_data(data).with_event(kind), &mut state)
                    .expect("SSE event parses"),
            );
        }
        // The client drains completed tool calls after the stream ends.
        expected.extend(
            std::mem::take(&mut state.tool_calls)
                .into_iter()
                .map(|call| LLMEvent::tool_call(call.id, call.name, call.input)),
        );

        assert!(
            expected
                .iter()
                .any(|event| matches!(event, LLMEvent::BuiltInToolCall { .. }))
        );
        assert!(
            expected
                .iter()
                .any(|event| matches!(event, LLMEvent::BuiltInToolResult { .. }))
        );
        assert_eq!(
            format!("{:?}", response_events(response)),
            format!("{expected:?}")
        );
    }
}