Skip to main content

vtcode_llm/providers/shared/
stream.rs

1//! OpenAI-compatible stream assembly, ordered deltas, and tool-call accumulation.
2
3use crate::error_display;
4use crate::provider::{LLMError, LLMResponse, LLMStreamEvent, ToolCall};
5use crate::providers::common::{extract_reasoning_text_from_serialized_details, map_finish_reason_common};
6use crate::providers::split_reasoning_from_text;
7use serde_json::{Map, Value};
8
9use super::sse::find_sse_boundary;
10use super::{
11    ReasoningBuffer, TagStreamSanitizer, Utf8StreamDecoder, check_sse_tail_bound, extract_data_payload,
12    find_sse_boundary_bytes,
13};
14
15#[derive(Debug, thiserror::Error)]
16pub enum StreamAssemblyError {
17    #[error("missing field `{0}` in stream payload")]
18    MissingField(&'static str),
19    #[error("invalid stream payload: {0}")]
20    InvalidPayload(String),
21}
22
23impl StreamAssemblyError {
24    #[cold]
25    pub(crate) fn into_llm_error(self, provider: &str) -> LLMError {
26        let message = self.to_string();
27        let formatted = error_display::format_llm_error(provider, &message);
28        LLMError::Provider { message: formatted, metadata: None }
29    }
30}
31
32pub trait StreamTelemetry: Send + Sync {
33    fn on_content_delta(&self, _delta: &str) {}
34    fn on_reasoning_delta(&self, _delta: &str) {}
35    fn on_reasoning_stage(&self, _stage: &str) {}
36    fn on_tool_call_delta(&self) {}
37}
38
39#[derive(Default)]
40pub struct NoopStreamTelemetry;
41
42impl StreamTelemetry for NoopStreamTelemetry {}
43
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum StreamFragment {
46    Content(String),
47    Reasoning(String),
48}
49
50#[derive(Default, Debug)]
51pub struct StreamDelta {
52    fragments: Vec<StreamFragment>,
53}
54
55impl StreamDelta {
56    pub(crate) fn push_content(&mut self, text: &str) {
57        if text.is_empty() {
58            return;
59        }
60
61        match self.fragments.last_mut() {
62            Some(StreamFragment::Content(existing)) => existing.push_str(text),
63            _ => self.fragments.push(StreamFragment::Content(text.to_string())),
64        }
65    }
66
67    pub(crate) fn push_reasoning(&mut self, text: &str) {
68        if text.is_empty() {
69            return;
70        }
71
72        match self.fragments.last_mut() {
73            Some(StreamFragment::Reasoning(existing)) => existing.push_str(text),
74            _ => self.fragments.push(StreamFragment::Reasoning(text.to_string())),
75        }
76    }
77
78    pub(crate) fn is_empty(&self) -> bool {
79        self.fragments.is_empty()
80    }
81
82    pub(crate) fn into_fragments(self) -> Vec<StreamFragment> {
83        self.fragments
84    }
85
86    pub fn extend(&mut self, other: StreamDelta) {
87        self.fragments.extend(other.fragments);
88    }
89}
90
91/// Generate a globally unique fallback id for tool calls whose provider
92/// omitted one. Index-based fallbacks (`tool_call_{index}`) reset every
93/// response, so the same id recurs across assistant messages and corrupts
94/// id-keyed history correlation downstream. Uniqueness across responses and
95/// process restarts (resumed sessions replay ids from checkpoints) is
96/// required, hence a random uuid rather than a counter.
97pub(crate) fn generate_tool_call_id() -> String {
98    format!("call_{}", uuid::Uuid::new_v4().simple())
99}
100
101#[derive(Default, Clone)]
102pub struct ToolCallBuilder {
103    id: Option<String>,
104    namespace: Option<String>,
105    name: Option<String>,
106    arguments: String,
107}
108
109impl ToolCallBuilder {
110    pub(crate) fn apply_delta(&mut self, delta: &Value) {
111        if let Some(id) = delta.get("id").and_then(|value| value.as_str()) {
112            self.id = Some(id.to_string());
113        }
114
115        if let Some(namespace) = delta.get("namespace").and_then(|value| value.as_str()) {
116            self.namespace = Some(namespace.to_string());
117        }
118
119        if let Some(function) = delta.get("function") {
120            if let Some(namespace) = function.get("namespace").and_then(|value| value.as_str()) {
121                self.namespace = Some(namespace.to_string());
122            }
123
124            if let Some(name) = function.get("name").and_then(|value| value.as_str()) {
125                self.name = Some(name.to_string());
126            }
127
128            if let Some(arguments_value) = function.get("arguments") {
129                if let Some(arguments) = arguments_value.as_str() {
130                    self.arguments.push_str(arguments);
131                } else if arguments_value.is_object() || arguments_value.is_array() {
132                    self.arguments.push_str(&arguments_value.to_string());
133                }
134            }
135        }
136    }
137
138    fn finalize(self) -> Option<ToolCall> {
139        let name = self.name?;
140        let id = self.id.unwrap_or_else(generate_tool_call_id);
141        let arguments = if self.arguments.is_empty() {
142            "{}".to_string()
143        } else {
144            self.arguments
145        };
146
147        Some(ToolCall::function_with_namespace(id, self.namespace, name, arguments))
148    }
149}
150
151fn update_tool_calls(builders: &mut Vec<ToolCallBuilder>, deltas: &[Value]) {
152    for (position, delta) in deltas.iter().enumerate() {
153        let index = delta
154            .get("index")
155            .and_then(|value| value.as_u64())
156            .map(|value| value as usize)
157            .unwrap_or(position);
158
159        if builders.len() <= index {
160            builders.resize_with(index + 1, ToolCallBuilder::default);
161        }
162        let Some(builder) = builders.get_mut(index) else {
163            continue;
164        };
165
166        builder.apply_delta(delta);
167    }
168}
169
170fn finalize_tool_calls(builders: Vec<ToolCallBuilder>) -> Option<Vec<ToolCall>> {
171    let calls: Vec<ToolCall> = builders.into_iter().filter_map(ToolCallBuilder::finalize).collect();
172
173    (!calls.is_empty()).then_some(calls)
174}
175
176/// Helper to aggregate streaming events and produce a final LLMResponse.
177pub(crate) struct StreamAggregator {
178    model: String,
179    pub(crate) content: String,
180    pub(crate) reasoning: String,
181    reasoning_details: Vec<String>,
182    reasoning_buffer: ReasoningBuffer,
183    pub(crate) tool_builders: Vec<ToolCallBuilder>,
184    pub(crate) usage: Option<crate::provider::Usage>,
185    finish_reason: crate::provider::FinishReason,
186    pub(crate) sanitizer: TagStreamSanitizer,
187    pub(crate) compaction: Option<String>,
188}
189
190#[derive(Clone, Copy, Debug, PartialEq, Eq)]
191pub enum OpenAiDeltaOrder {
192    ReasoningFirst,
193    ContentFirst,
194}
195
196fn emit_reasoning_delta(
197    aggregator: &mut StreamAggregator,
198    tx: &tokio::sync::mpsc::UnboundedSender<Result<LLMStreamEvent, LLMError>>,
199    delta: &Value,
200    reasoning_fields: &[&'static str],
201) {
202    // Pick the first non-empty reasoning field, allowing providers to declare a
203    // fallback order (e.g. `["reasoning", "reasoning_content"]`).
204    // Empty strings are skipped so that a present-but-empty primary field
205    // does not block fallback to the next candidate.
206    let Some(reasoning) = reasoning_fields
207        .iter()
208        .find_map(|field| delta.get(*field).and_then(Value::as_str).filter(|s| !s.is_empty()))
209    else {
210        return;
211    };
212    let Some(delta) = aggregator.handle_reasoning(reasoning) else {
213        return;
214    };
215    let _ = tx.send(Ok(LLMStreamEvent::Reasoning { delta }));
216}
217
218fn emit_content_delta(
219    aggregator: &mut StreamAggregator,
220    tx: &tokio::sync::mpsc::UnboundedSender<Result<LLMStreamEvent, LLMError>>,
221    delta: &Value,
222) {
223    let Some(content) = delta.get("content").and_then(Value::as_str) else {
224        return;
225    };
226    for event in aggregator.handle_content(content) {
227        let _ = tx.send(Ok(event));
228    }
229}
230
231pub(crate) fn handle_openai_compatible_chunk(
232    value: &Value,
233    aggregator: &mut StreamAggregator,
234    tx: &tokio::sync::mpsc::UnboundedSender<Result<LLMStreamEvent, LLMError>>,
235    reasoning_fields: &[&'static str],
236    delta_order: OpenAiDeltaOrder,
237    include_cache_metrics: bool,
238) {
239    if let Some(choices) = value.get("choices").and_then(Value::as_array)
240        && let Some(choice) = choices.first()
241    {
242        if let Some(delta) = choice.get("delta") {
243            match delta_order {
244                OpenAiDeltaOrder::ReasoningFirst => {
245                    emit_reasoning_delta(aggregator, tx, delta, reasoning_fields);
246                    emit_content_delta(aggregator, tx, delta);
247                }
248                OpenAiDeltaOrder::ContentFirst => {
249                    emit_content_delta(aggregator, tx, delta);
250                    emit_reasoning_delta(aggregator, tx, delta, reasoning_fields);
251                }
252            }
253
254            if let Some(tool_calls) = delta.get("tool_calls").and_then(Value::as_array) {
255                aggregator.handle_tool_calls(tool_calls);
256            }
257        }
258
259        if let Some(reason) = choice.get("finish_reason").and_then(Value::as_str) {
260            aggregator.set_finish_reason(map_finish_reason_common(reason));
261        }
262    }
263
264    if let Some(_usage_value) = value.get("usage")
265        && let Some(usage) = crate::providers::common::parse_usage_openai_format(value, include_cache_metrics)
266    {
267        aggregator.set_usage(usage);
268    }
269}
270
271impl StreamAggregator {
272    pub(crate) fn new(model: String) -> Self {
273        Self {
274            model,
275            content: String::new(),
276            reasoning: String::new(),
277            reasoning_details: Vec::new(),
278            reasoning_buffer: ReasoningBuffer::default(),
279            tool_builders: Vec::new(),
280            usage: None,
281            finish_reason: crate::provider::FinishReason::Stop,
282            sanitizer: TagStreamSanitizer::new(),
283            compaction: None,
284        }
285    }
286
287    /// Process a content delta, applying sanitization for reasoning tags.
288    pub(crate) fn handle_content(&mut self, delta: &str) -> Vec<LLMStreamEvent> {
289        self.content.push_str(delta);
290        self.sanitizer.process_chunk(delta)
291    }
292
293    /// Process a reasoning delta from a dedicated field.
294    pub(crate) fn handle_reasoning(&mut self, delta: &str) -> Option<String> {
295        let result = self.reasoning_buffer.push(delta);
296        if let Some(ref d) = result {
297            self.reasoning.push_str(d);
298        }
299        result
300    }
301
302    /// Store structured reasoning details received from streaming deltas.
303    pub(crate) fn set_reasoning_details(&mut self, details: &[Value]) {
304        if details.is_empty() {
305            return;
306        }
307
308        self.reasoning_details = details
309            .iter()
310            .map(|detail| detail.as_str().map(ToOwned::to_owned).unwrap_or_else(|| detail.to_string()))
311            .collect();
312    }
313
314    /// Append a completed structured item received from a streaming
315    /// output-item event.
316    pub(crate) fn append_reasoning_detail(&mut self, detail: &Value) {
317        let serialized = detail.as_str().map(ToOwned::to_owned).unwrap_or_else(|| detail.to_string());
318        if !self.reasoning_details.iter().any(|existing| existing == &serialized) {
319            self.reasoning_details.push(serialized);
320        }
321    }
322
323    /// Process tool call deltas.
324    pub(crate) fn handle_tool_calls(&mut self, deltas: &[Value]) {
325        update_tool_calls(&mut self.tool_builders, deltas);
326    }
327
328    /// Set usage metrics.
329    pub(crate) fn set_usage(&mut self, usage: crate::provider::Usage) {
330        self.usage = Some(usage);
331    }
332
333    /// Set finish reason.
334    pub(crate) fn set_finish_reason(&mut self, reason: crate::provider::FinishReason) {
335        self.finish_reason = reason;
336    }
337
338    /// Finalize and produce the completed LLMResponse.
339    pub(crate) fn finalize(mut self) -> LLMResponse {
340        // Collect any leftover bits from sanitizer
341        for event in self.sanitizer.finalize() {
342            match event {
343                LLMStreamEvent::Token { delta } => {
344                    self.content.push_str(&delta);
345                }
346                LLMStreamEvent::Reasoning { delta } => {
347                    self.reasoning.push_str(&delta);
348                }
349                _ => {}
350            }
351        }
352
353        let reasoning_details = if self.reasoning_details.is_empty() {
354            None
355        } else {
356            Some(self.reasoning_details)
357        };
358        let mut reasoning = if self.reasoning.is_empty() {
359            self.reasoning_buffer.finalize()
360        } else {
361            Some(self.reasoning)
362        };
363        if reasoning.is_none() {
364            reasoning = reasoning_details
365                .as_ref()
366                .and_then(|details| extract_reasoning_text_from_serialized_details(details));
367        }
368
369        LLMResponse {
370            content: if self.content.is_empty() {
371                None
372            } else {
373                Some(self.content)
374            },
375            tool_calls: finalize_tool_calls(self.tool_builders),
376            model: self.model,
377            usage: self.usage,
378            finish_reason: self.finish_reason,
379            reasoning,
380            reasoning_details,
381            tool_references: Vec::new(),
382            request_id: None,
383            organization_id: None,
384            compaction: self.compaction,
385        }
386    }
387}
388
389/// Common helper for processing OpenAI-compatible SSE streams.
390///
391/// This simplifies stream implementations across providers like DeepSeek, ZAI, Moonshot, etc.
392/// Especially optimized for high-performance models like Gemini 3 and GLM-5.
393pub(crate) async fn process_openai_stream<S, E, F>(
394    mut byte_stream: S,
395    provider_name: &'static str,
396    model: String,
397    mut on_chunk: F,
398) -> Result<LLMResponse, LLMError>
399where
400    S: futures::Stream<Item = Result<bytes::Bytes, E>> + Unpin,
401    E: std::fmt::Display,
402    F: FnMut(Value) -> Result<(), LLMError>,
403{
404    use crate::providers::error_handling::format_network_error;
405    use futures::StreamExt;
406
407    let mut buf: Vec<u8> = Vec::new();
408    let mut offset = 0usize;
409    let mut decoder = Utf8StreamDecoder::new();
410    let mut last_response_value = None;
411
412    while let Some(chunk_result) = byte_stream.next().await {
413        let chunk_bytes = chunk_result.map_err(|e| format_network_error(provider_name, &e.to_string()))?;
414        decoder.push_bytes(&chunk_bytes, &mut buf);
415
416        while let Some((boundary_idx, boundary_len)) = find_sse_boundary_bytes(&buf, offset) {
417            let event = std::str::from_utf8(&buf[offset..boundary_idx]).expect("valid utf-8 stream data");
418            offset = boundary_idx + boundary_len;
419
420            if let Some(data) = extract_data_payload(event) {
421                if data == "[DONE]" {
422                    break;
423                }
424
425                for line in data.lines() {
426                    let trimmed = line.trim();
427                    if trimmed.is_empty() {
428                        continue;
429                    }
430
431                    if let Ok(value) = serde_json::from_str::<Value>(trimmed) {
432                        on_chunk(value.clone())?;
433                        last_response_value = Some(value);
434                    }
435                }
436            }
437        }
438
439        // Drain the consumed prefix so `buf` stays bounded to the unprocessed
440        // tail rather than growing for the entire stream lifetime.
441        if offset > 0 {
442            buf.drain(..offset);
443            offset = 0;
444        }
445
446        // Fail closed: a peer that never emits an event boundary must not
447        // grow the retained tail without bound. Measured after the drain so
448        // one large-but-complete event still parses.
449        if let Err(overflow) = check_sse_tail_bound(buf.len()) {
450            let message = error_display::format_llm_error(provider_name, &overflow.to_string());
451            return Err(LLMError::Provider { message, metadata: None });
452        }
453    }
454
455    // Attempt to extract final response metadata (usage, etc) from last chunk if not already done
456    let mut final_response = LLMResponse {
457        content: None,
458        tool_calls: None,
459        model,
460        usage: None,
461        finish_reason: crate::provider::FinishReason::Stop,
462        reasoning: None,
463        reasoning_details: None,
464        tool_references: Vec::new(),
465        request_id: None,
466        organization_id: None,
467        compaction: None,
468    };
469
470    if let Some(value) = last_response_value
471        && value.get("usage").is_some()
472    {
473        final_response.usage = crate::providers::common::parse_usage_openai_format(&value, true);
474    }
475
476    Ok(final_response)
477}
478
479pub(crate) fn parse_openai_tool_calls(calls: &[Value]) -> Vec<ToolCall> {
480    calls
481        .iter()
482        .filter_map(|call| {
483            let id = call.get("id").and_then(|v| v.as_str())?;
484            let function = call.get("function")?;
485            let namespace = call
486                .get("namespace")
487                .and_then(|v| v.as_str())
488                .or_else(|| function.get("namespace").and_then(|v| v.as_str()))
489                .map(ToOwned::to_owned);
490            let name = function.get("name").and_then(|v| v.as_str())?;
491            let arguments = function.get("arguments");
492            let serialized = arguments.map_or_else(
493                || "{}".to_string(),
494                |value| {
495                    if value.is_string() {
496                        value.as_str().unwrap_or("").to_string()
497                    } else {
498                        value.to_string()
499                    }
500                },
501            );
502            Some(ToolCall::function_with_namespace(id.to_string(), namespace, name.to_string(), serialized))
503        })
504        .collect()
505}
506
507fn push_unique_tool_reference(tool_references: &mut Vec<String>, tool_name: &str) {
508    if !tool_references.iter().any(|existing| existing == tool_name) {
509        tool_references.push(tool_name.to_string());
510    }
511}
512
513pub(crate) fn collect_tool_references_from_tool_search_output(value: &Value, tool_references: &mut Vec<String>) {
514    match value {
515        Value::Array(items) => {
516            for item in items {
517                collect_tool_references_from_tool_search_output(item, tool_references);
518            }
519        }
520        Value::Object(object) => {
521            if let Some(tools) = object.get("tools").and_then(Value::as_array) {
522                for tool in tools {
523                    collect_tool_references_from_tool_search_output(tool, tool_references);
524                }
525            } else if let Some(tool_name) = object.get("tool_name").and_then(Value::as_str) {
526                push_unique_tool_reference(tool_references, tool_name);
527            } else if let Some(function) = object.get("function").and_then(Value::as_object)
528                && let Some(tool_name) = function.get("name").and_then(Value::as_str)
529            {
530                push_unique_tool_reference(tool_references, tool_name);
531            } else if let Some(tool_name) = object.get("name").and_then(Value::as_str) {
532                push_unique_tool_reference(tool_references, tool_name);
533            }
534
535            if let Some(tool_refs) = object.get("tool_references").and_then(Value::as_array) {
536                for tool_ref in tool_refs {
537                    collect_tool_references_from_tool_search_output(tool_ref, tool_references);
538                }
539            }
540        }
541        _ => {}
542    }
543}
544
545fn append_text_with_reasoning(
546    text: &str,
547    aggregated_content: &mut String,
548    reasoning: &mut ReasoningBuffer,
549    deltas: &mut StreamDelta,
550    telemetry: &impl StreamTelemetry,
551) {
552    let (segments, cleaned) = split_reasoning_from_text(text);
553
554    if segments.is_empty() && cleaned.is_none() {
555        if !text.is_empty() {
556            aggregated_content.push_str(text);
557            deltas.push_content(text);
558            telemetry.on_content_delta(text);
559        }
560        return;
561    }
562
563    for segment in segments {
564        if let Some(stage) = &segment.stage {
565            telemetry.on_reasoning_stage(stage);
566        }
567        if let Some(delta) = reasoning.push(&segment.text) {
568            telemetry.on_reasoning_delta(&delta);
569            deltas.push_reasoning(&delta);
570        }
571    }
572
573    if let Some(cleaned_text) = cleaned
574        && !cleaned_text.is_empty()
575    {
576        aggregated_content.push_str(&cleaned_text);
577        telemetry.on_content_delta(&cleaned_text);
578        deltas.push_content(&cleaned_text);
579    }
580}
581
582fn apply_tool_call_delta_from_content(
583    builders: &mut Vec<ToolCallBuilder>,
584    container: &Map<String, Value>,
585    telemetry: &impl StreamTelemetry,
586) {
587    apply_tool_call_delta_with_index(builders, container, telemetry, None, None);
588}
589
590fn apply_tool_call_delta_with_index(
591    builders: &mut Vec<ToolCallBuilder>,
592    container: &Map<String, Value>,
593    telemetry: &impl StreamTelemetry,
594    fallback_index: Option<usize>,
595    fallback_id: Option<Value>,
596) {
597    fn extract_tool_call_id(container: &Map<String, Value>) -> Option<Value> {
598        container.get("id").cloned().or_else(|| {
599            container
600                .get("tool_call")
601                .and_then(|value| value.as_object())
602                .and_then(|inner| inner.get("id"))
603                .cloned()
604        })
605    }
606
607    let explicit_index = container
608        .get("tool_call")
609        .and_then(|value| value.as_object())
610        .and_then(|tool_call| tool_call.get("index"))
611        .and_then(|value| value.as_u64())
612        .or_else(|| container.get("index").and_then(|value| value.as_u64()));
613
614    let index = explicit_index.map(|value| value as usize).or(fallback_index).unwrap_or(0);
615
616    let current_id = extract_tool_call_id(container).or_else(|| fallback_id.clone());
617
618    if let Some(nested) = container.get("delta").and_then(|value| value.as_object()) {
619        apply_tool_call_delta_with_index(builders, nested, telemetry, Some(index), current_id.clone());
620    }
621
622    let delta_source = container
623        .get("tool_call")
624        .and_then(|value| value.as_object())
625        .unwrap_or(container);
626
627    let mut delta_map = Map::new();
628
629    if let Some(id_value) = extract_tool_call_id(delta_source).or_else(|| current_id.clone()) {
630        delta_map.insert("id".to_string(), id_value);
631    }
632
633    if let Some(function_value) = delta_source.get("function").or_else(|| container.get("function")) {
634        delta_map.insert("function".to_string(), function_value.clone());
635    }
636
637    if delta_map.is_empty() {
638        return;
639    }
640
641    if builders.len() <= index {
642        builders.resize_with(index + 1, ToolCallBuilder::default);
643    }
644
645    let mut deltas = vec![Value::Null; index + 1];
646    deltas[index] = Value::Object(delta_map);
647    update_tool_calls(builders, &deltas);
648    telemetry.on_tool_call_delta();
649}
650
651#[cfg(test)]
652mod tests {
653    use super::*;
654    use serde_json::json;
655
656    #[test]
657    fn finalize_tool_calls_drops_empty_builders() {
658        let builders = vec![ToolCallBuilder::default()];
659        assert!(finalize_tool_calls(builders).is_none());
660    }
661
662    #[test]
663    fn finalize_fabricates_unique_ids_across_batches() {
664        let idless_builder = || {
665            let mut builder = ToolCallBuilder::default();
666            builder.apply_delta(&json!({"function": {"name": "foo", "arguments": "{}"}}));
667            builder
668        };
669
670        let first = finalize_tool_calls(vec![idless_builder(), idless_builder()]).expect("calls expected");
671        let second = finalize_tool_calls(vec![idless_builder(), idless_builder()]).expect("calls expected");
672
673        let ids: Vec<&str> = first.iter().chain(second.iter()).map(|call| call.id.as_str()).collect();
674        let unique: std::collections::HashSet<&str> = ids.iter().copied().collect();
675        assert_eq!(unique.len(), ids.len(), "fabricated ids must be unique across responses");
676
677        for id in ids {
678            let hex = id.strip_prefix("call_").expect("fabricated id prefix");
679            assert_eq!(hex.len(), 32);
680            assert!(hex.chars().all(|ch| ch.is_ascii_hexdigit()));
681        }
682    }
683
684    #[test]
685    fn finalize_preserves_provider_supplied_id() {
686        let mut builder = ToolCallBuilder::default();
687        builder.apply_delta(&json!({"id": "provider-id-1", "function": {"name": "foo"}}));
688        let call = builder.finalize().expect("call expected");
689        assert_eq!(call.id, "provider-id-1");
690    }
691
692    #[test]
693    fn append_text_with_reasoning_tracks_segments() {
694        let telemetry = NoopStreamTelemetry;
695        let mut aggregated = String::new();
696        let mut reasoning = ReasoningBuffer::default();
697        let mut delta = StreamDelta::default();
698        append_text_with_reasoning("Hello", &mut aggregated, &mut reasoning, &mut delta, &telemetry);
699        assert_eq!(aggregated, "Hello");
700        assert_eq!(delta.into_fragments(), vec![StreamFragment::Content("Hello".into())]);
701    }
702
703    #[test]
704    fn apply_tool_call_delta_updates_builder() {
705        let telemetry = NoopStreamTelemetry;
706        let mut builders = Vec::new();
707        let container = json!({
708            "index": 0,
709            "function": {"name": "foo", "arguments": "{}"}
710        })
711        .as_object()
712        .cloned()
713        .unwrap();
714        apply_tool_call_delta_from_content(&mut builders, &container, &telemetry);
715        let calls = finalize_tool_calls(builders).expect("call expected");
716        let func = calls[0].function.as_ref().expect("function call should be present");
717        assert_eq!(func.name, "foo");
718    }
719
720    #[test]
721    fn apply_tool_call_delta_uses_outer_index_for_nested_delta() {
722        let telemetry = NoopStreamTelemetry;
723        let mut builders = Vec::new();
724        let container = json!({
725            "delta": {
726                "tool_call": {
727                    "function": {
728                        "name": "foo",
729                        "arguments": "{\"value\":1}"
730                    }
731                }
732            },
733            "index": 1,
734            "id": "call-1"
735        })
736        .as_object()
737        .cloned()
738        .unwrap();
739
740        apply_tool_call_delta_from_content(&mut builders, &container, &telemetry);
741
742        let calls = finalize_tool_calls(builders).expect("call expected");
743        assert_eq!(calls.len(), 1);
744        assert_eq!(calls[0].id, "call-1");
745        let func = calls[0].function.as_ref().expect("function call should be present");
746        assert_eq!(func.arguments, "{\"value\":1}");
747    }
748
749    #[test]
750    fn update_tool_calls_respects_explicit_index() {
751        let mut builders = Vec::new();
752        let deltas = vec![json!({
753            "index": 2,
754            "id": "call_3",
755            "function": {
756                "name": "get_weather",
757                "arguments": "{\"city\":\"Beijing\"}"
758            }
759        })];
760
761        update_tool_calls(&mut builders, &deltas);
762
763        let calls = finalize_tool_calls(builders).expect("call expected");
764        assert_eq!(calls.len(), 1);
765        assert_eq!(calls[0].id, "call_3");
766        let function = calls[0].function.as_ref().expect("function expected");
767        assert_eq!(function.name, "get_weather");
768        assert_eq!(function.arguments, "{\"city\":\"Beijing\"}");
769    }
770
771    #[test]
772    fn stream_aggregator_derives_reasoning_from_details_when_missing() {
773        let mut aggregator = StreamAggregator::new("test-model".to_string());
774        aggregator.set_reasoning_details(&[json!({
775            "type": "reasoning.text",
776            "text": "step one"
777        })]);
778
779        let response = aggregator.finalize();
780        assert_eq!(response.reasoning.as_deref(), Some("step one"));
781        assert!(response.reasoning_details.is_some());
782    }
783
784    #[test]
785    fn handle_chunk_extracts_content_delta() {
786        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
787        let mut aggregator = StreamAggregator::new("test-model".to_string());
788        let chunk = json!({
789            "choices": [{"delta": {"content": "hello"}}]
790        });
791
792        handle_openai_compatible_chunk(&chunk, &mut aggregator, &tx, &[], OpenAiDeltaOrder::ContentFirst, false);
793
794        let event = rx.try_recv().expect("event expected");
795        match event.unwrap() {
796            LLMStreamEvent::Token { delta } => {
797                assert_eq!(delta, "hello");
798            }
799            other => panic!("expected Token event, got {other:?}"),
800        }
801    }
802
803    #[test]
804    fn handle_chunk_extracts_reasoning_delta() {
805        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
806        let mut aggregator = StreamAggregator::new("test-model".to_string());
807        let chunk = json!({
808            "choices": [{"delta": {"reasoning_content": "thinking..."}}]
809        });
810
811        handle_openai_compatible_chunk(
812            &chunk,
813            &mut aggregator,
814            &tx,
815            &["reasoning_content"],
816            OpenAiDeltaOrder::ReasoningFirst,
817            false,
818        );
819
820        let event = rx.try_recv().expect("event expected");
821        match event.unwrap() {
822            LLMStreamEvent::Reasoning { delta } => {
823                assert_eq!(delta, "thinking...");
824            }
825            other => panic!("expected Reasoning event, got {other:?}"),
826        }
827    }
828
829    #[test]
830    fn handle_chunk_aggregates_tool_calls() {
831        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
832        let mut aggregator = StreamAggregator::new("test-model".to_string());
833        let chunk = json!({
834            "choices": [{
835                "delta": {
836                    "tool_calls": [{
837                        "index": 0,
838                        "id": "call_1",
839                        "function": {"name": "search", "arguments": "{\"q\":\"test\"}"}
840                    }]
841                }
842            }]
843        });
844
845        handle_openai_compatible_chunk(&chunk, &mut aggregator, &tx, &[], OpenAiDeltaOrder::ContentFirst, false);
846
847        let response = aggregator.finalize();
848        let calls = response.tool_calls.expect("tool calls expected");
849        assert_eq!(calls.len(), 1);
850        assert_eq!(calls[0].id, "call_1");
851        let func = calls[0].function.as_ref().expect("function expected");
852        assert_eq!(func.name, "search");
853        assert_eq!(func.arguments, "{\"q\":\"test\"}");
854    }
855
856    #[test]
857    fn handle_chunk_skips_empty_reasoning_and_falls_back() {
858        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
859        let mut aggregator = StreamAggregator::new("test-model".to_string());
860        // Evolink-style: reasoning is empty string, reasoning_content has actual content
861        let chunk = json!({
862            "choices": [{"delta": {"reasoning": "", "reasoning_content": "actual reasoning"}}]
863        });
864
865        handle_openai_compatible_chunk(
866            &chunk,
867            &mut aggregator,
868            &tx,
869            &["reasoning", "reasoning_content"],
870            OpenAiDeltaOrder::ReasoningFirst,
871            false,
872        );
873
874        let event = rx.try_recv().expect("event expected");
875        match event.unwrap() {
876            LLMStreamEvent::Reasoning { delta } => {
877                assert_eq!(delta, "actual reasoning");
878            }
879            other => panic!("expected Reasoning event, got {other:?}"),
880        }
881    }
882
883    #[test]
884    fn handle_chunk_passes_include_cache_metrics_to_usage() {
885        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
886        let mut aggregator = StreamAggregator::new("test-model".to_string());
887        let chunk = json!({
888            "choices": [{"delta": {}}],
889            "usage": {
890                "prompt_tokens": 100,
891                "completion_tokens": 50,
892                "total_tokens": 150,
893                "prompt_cache_hit_tokens": 30,
894                "prompt_cache_miss_tokens": 70
895            }
896        });
897
898        // With include_cache_metrics = false (Evolink/Moonshot/StepFun/ZAI behavior)
899        handle_openai_compatible_chunk(&chunk, &mut aggregator, &tx, &[], OpenAiDeltaOrder::ContentFirst, false);
900
901        let response = aggregator.finalize();
902        let usage = response.usage.expect("usage expected");
903        assert_eq!(usage.prompt_tokens, 100);
904        assert_eq!(usage.cached_prompt_tokens, None);
905        assert_eq!(usage.cache_creation_tokens, None);
906
907        // With include_cache_metrics = true (DeepSeek behavior)
908        let mut aggregator2 = StreamAggregator::new("test-model".to_string());
909        handle_openai_compatible_chunk(&chunk, &mut aggregator2, &tx, &[], OpenAiDeltaOrder::ContentFirst, true);
910
911        let response2 = aggregator2.finalize();
912        let usage2 = response2.usage.expect("usage expected");
913        assert_eq!(usage2.prompt_tokens, 100);
914        assert_eq!(usage2.cached_prompt_tokens, Some(30));
915        assert_eq!(usage2.cache_creation_tokens, Some(70));
916    }
917
918    #[tokio::test]
919    async fn process_openai_stream_fails_closed_on_boundaryless_tail_over_cap() {
920        use crate::providers::shared::MAX_SSE_TAIL_BYTES;
921        use futures::stream;
922
923        // The real growth shape: small boundary-less chunks accumulating past
924        // the cap across loop iterations, tripping on the third chunk.
925        let byte_stream = stream::iter(vec![
926            Ok::<bytes::Bytes, std::convert::Infallible>(bytes::Bytes::from("x".repeat(MAX_SSE_TAIL_BYTES / 2))),
927            Ok::<bytes::Bytes, std::convert::Infallible>(bytes::Bytes::from("y".repeat(MAX_SSE_TAIL_BYTES / 2))),
928            Ok::<bytes::Bytes, std::convert::Infallible>(bytes::Bytes::from_static(b"zz")),
929        ]);
930        let result = process_openai_stream(byte_stream, "test-provider", "test-model".to_string(), |_| Ok(())).await;
931        let err = result.expect_err("boundary-less tail over the cap must fail closed");
932        match err {
933            LLMError::Provider { message, .. } => {
934                assert!(message.contains("test-provider"), "{message}");
935                assert!(message.contains("without an event boundary"), "{message}");
936            }
937            other => panic!("expected Provider error, got {other:?}"),
938        }
939    }
940
941    #[tokio::test]
942    async fn process_openai_stream_accepts_boundaryless_tail_under_cap() {
943        use crate::providers::shared::MAX_SSE_TAIL_BYTES;
944        use futures::stream;
945
946        let tail = "x".repeat(MAX_SSE_TAIL_BYTES - 1);
947        let byte_stream = stream::iter(vec![Ok::<bytes::Bytes, std::convert::Infallible>(bytes::Bytes::from(tail))]);
948        let mut calls = 0;
949        let result = process_openai_stream(byte_stream, "test-provider", "test-model".to_string(), |_| {
950            calls += 1;
951            Ok(())
952        })
953        .await;
954        assert!(result.is_ok(), "under-cap tail at EOF must not error: {result:?}");
955        assert_eq!(calls, 0, "boundary-less tail carries no complete event");
956    }
957
958    #[tokio::test]
959    async fn process_openai_stream_measures_the_retained_tail_after_drain() {
960        use crate::providers::shared::MAX_SSE_TAIL_BYTES;
961        use futures::stream;
962
963        // Pre-drain peak tops the cap, but the completed event drains and the
964        // retained tail is empty: the bound guards retention, not one event.
965        let first = "x".repeat(MAX_SSE_TAIL_BYTES - 100);
966        let second = format!("{}\n\n", "y".repeat(200));
967        let byte_stream = stream::iter(vec![
968            Ok::<bytes::Bytes, std::convert::Infallible>(bytes::Bytes::from(first)),
969            Ok::<bytes::Bytes, std::convert::Infallible>(bytes::Bytes::from(second)),
970        ]);
971        let result = process_openai_stream(byte_stream, "test-provider", "test-model".to_string(), |_| Ok(())).await;
972        assert!(result.is_ok(), "drained tail must not trip the bound: {result:?}");
973    }
974
975    #[tokio::test]
976    async fn process_openai_stream_still_delivers_small_events() {
977        use futures::stream;
978
979        let byte_stream = stream::iter(vec![Ok::<bytes::Bytes, std::convert::Infallible>(bytes::Bytes::from_static(
980            b"data: {\"choices\": [{\"delta\": {\"content\": \"hi\"}}]}\n\n",
981        ))]);
982        let mut seen = Vec::new();
983        let result = process_openai_stream(byte_stream, "test-provider", "test-model".to_string(), |value| {
984            seen.push(value);
985            Ok(())
986        })
987        .await;
988        assert!(result.is_ok(), "{result:?}");
989        assert_eq!(seen.len(), 1);
990        assert_eq!(seen[0]["choices"][0]["delta"]["content"], "hi");
991    }
992}