mutil-ai 0.7.0

A beginner-friendly, provider-neutral Rust AI SDK with a strict normalization layer.
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
use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Duration;

use bytes::Bytes;
use futures_core::Stream;

use crate::audit::{AuditContext, AuditOutcome, FirstTokenKind};
use crate::cancel::CancellationToken;
use crate::error::{Error, ErrorKind, Result};
use crate::security::{RequestBudget, ResponseLimits};
use crate::sse::{SseError, SseEvent, SseMessage, SseParser};
use crate::types::{
    ChatResponse, NativeToolCall, ReasoningKind, ResponseMetadata, ServerToolState, Usage,
};

/// A boxed provider-neutral stream of model events.
pub type ModelStream = Pin<Box<dyn Stream<Item = Result<StreamEvent>> + Send + 'static>>;

/// Opt-in transport reconnect policy for an already-started SSE stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StreamReconnectPolicy {
    /// Maximum number of reconnect attempts before the stream fails.
    pub max_attempts: u32,
    /// Delay between attempts, used when neither the server nor the parser
    /// supplied a `retry` hint.
    pub delay: Duration,
    /// Refuse reconnect when no SSE event id has been observed.
    pub require_event_id: bool,
    /// Refuse reconnect delays above this cap (including server retry hints).
    pub max_delay: Duration,
    /// Suppress a replayed suffix only when the server guarantees replay semantics.
    /// Off by default: inherited SSE IDs are not unique event identifiers.
    pub deduplicate_replay: bool,
}

impl Default for StreamReconnectPolicy {
    fn default() -> Self {
        Self {
            max_attempts: 2,
            delay: Duration::from_millis(250),
            require_event_id: true,
            max_delay: Duration::from_secs(60),
            deduplicate_replay: false,
        }
    }
}

impl StreamReconnectPolicy {
    /// Creates the default policy: 2 attempts, 250 ms delay, requiring an
    /// event id.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the maximum number of reconnect attempts.
    pub fn max_attempts(mut self, max_attempts: u32) -> Self {
        self.max_attempts = max_attempts;
        self
    }

    /// Sets the delay between reconnect attempts.
    pub fn delay(mut self, delay: Duration) -> Self {
        self.delay = delay;
        self
    }

    /// Sets whether reconnecting requires an observed SSE event id.
    pub fn require_event_id(mut self, require_event_id: bool) -> Self {
        self.require_event_id = require_event_id;
        self
    }

    /// Sets the maximum permitted reconnect delay.
    pub fn max_delay(mut self, max_delay: Duration) -> Self {
        self.max_delay = max_delay;
        self
    }

    /// Enables suffix replay suppression for servers with documented resume semantics.
    pub fn deduplicate_replay(mut self, enabled: bool) -> Self {
        self.deduplicate_replay = enabled;
        self
    }
}

/// A provider-neutral streaming event.
#[derive(Debug, Clone, PartialEq)]
pub enum StreamEvent {
    /// The HTTP response was accepted and the stream is starting.
    Start {
        provider: &'static str,
        model: String,
        metadata: ResponseMetadata,
    },
    /// Incremental assistant-visible text.
    TextDelta { text: String },
    /// Incremental reasoning summary or readable reasoning text.
    ReasoningDelta { kind: ReasoningKind, text: String },
    /// Incremental tool-call data.
    ///
    /// `index` identifies the tool call within the assistant message.
    ToolCallDelta {
        index: usize,
        id: Option<String>,
        name: Option<String>,
        arguments_delta: String,
    },
    /// The complete tool arguments accumulated so far for a call.
    ToolCallProgress {
        index: usize,
        id: Option<String>,
        name: Option<String>,
        arguments_so_far: String,
    },
    /// Raw custom input progress. This event is not proof of completion.
    NativeToolProgress {
        index: usize,
        item_id: Option<String>,
        input_so_far: String,
    },
    /// A completed native item. Applications must still apply cancellation and
    /// response-level scheduling policy before executing a write.
    NativeToolCompleted { index: usize, call: NativeToolCall },
    /// A provider-hosted or built-in tool changed state.
    ServerToolStatus {
        tool: String,
        call_id: Option<String>,
        state: ServerToolState,
    },
    /// Usage reported during the stream. Providers may send this only at the end.
    Usage { usage: Usage },
    /// A server-directed SSE retry delay.
    Retry { delay: Duration },
    /// The SDK scheduled a retry or reconnect with stable metadata.
    Retrying {
        attempt: u32,
        max_attempts: u32,
        delay: Duration,
        reason: String,
    },
    /// A recoverable stream error. Terminal errors are returned as `Err`.
    Error { error: StreamError },
    /// The stream completed and the SDK assembled a normal response.
    ///
    /// Consumers that persist conversation history should append
    /// `response.message`, not reconstruct it from deltas.
    Done {
        response: Box<ChatResponse>,
        finish_reason: Option<String>,
    },
}

/// Stable, content-free metadata for a recoverable stream error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StreamError {
    /// The error classification, safe to match on.
    pub kind: ErrorKind,
    /// A human-readable description without request content.
    pub message: String,
    /// Whether the SDK or caller may retry the request.
    pub recoverable: bool,
}

/// Provider-specific mapper from one SSE message to zero or more events.
pub(crate) trait SseMapper: Send + Unpin + 'static {
    fn configure_limits(&mut self, _limits: ResponseLimits) {}
    fn map(&mut self, message: SseMessage) -> Result<Vec<StreamEvent>>;

    /// Whether a clean EOF is a valid terminal condition for this protocol.
    fn eof_is_terminal(&self) -> bool {
        true
    }

    /// The SSE parser used by [`SseStream`] for this protocol. Adapters may
    /// override it to opt into e.g. [`crate::sse::TailPolicy::Flush`].
    fn sse_parser(&self) -> SseParser {
        SseParser::new()
    }

    fn finish(&mut self) -> Result<Vec<StreamEvent>> {
        Ok(Vec::new())
    }
}

pub(crate) fn sse_stream_with_audit<M>(
    response: reqwest::Response,
    mapper: M,
    cancellation: Option<CancellationToken>,
    idle_timeout: Option<Duration>,
    audit: Option<AuditContext>,
    budget: RequestBudget,
) -> ModelStream
where
    M: SseMapper,
{
    let metadata = ResponseMetadata::from_response(&response);
    let cancellation_future = cancellation_future(cancellation.clone());
    Box::pin(SseStream {
        inner: Box::pin(response.bytes_stream()),
        parser: mapper.sse_parser().with_byte_limits(
            budget.limits.max_sse_line_bytes,
            budget.limits.max_sse_event_bytes,
        ),
        mapper,
        queue: VecDeque::new(),
        finished: false,
        terminal: false,
        last_event_id: None,
        recent_events: VecDeque::new(),
        recent_bytes: 0,
        replay_events: None,
        replay_started: false,
        reconnect: None,
        reconnect_future: None,
        cancellation,
        cancellation_future,
        idle_timeout,
        idle_deadline: idle_deadline(idle_timeout),
        audit,
        audit_finished: false,
        audit_status: Some(metadata.status),
        audit_provider_request_id: metadata.request_id,
        total_deadline: budget
            .deadline
            .map(|deadline| Box::pin(tokio::time::sleep_until(deadline))),
        budget,
        event_count: 0,
    })
}

type CancellationFuture = Pin<Box<dyn Future<Output = ()> + Send>>;

fn cancellation_future(cancellation: Option<CancellationToken>) -> Option<CancellationFuture> {
    cancellation.map(|cancellation| {
        Box::pin(async move {
            cancellation.cancelled().await;
        }) as CancellationFuture
    })
}

type IdleDeadline = Pin<Box<tokio::time::Sleep>>;

fn idle_deadline(timeout: Option<Duration>) -> Option<IdleDeadline> {
    timeout.map(|timeout| Box::pin(tokio::time::sleep(timeout)))
}

type ReconnectFuture = Pin<Box<dyn Future<Output = Result<reqwest::Response>> + Send>>;

trait ReconnectFactory: Send {
    fn connect(&mut self, last_event_id: Option<String>) -> ReconnectFuture;
}

impl<F> ReconnectFactory for F
where
    F: FnMut(Option<String>) -> ReconnectFuture + Send + 'static,
{
    fn connect(&mut self, last_event_id: Option<String>) -> ReconnectFuture {
        self(last_event_id)
    }
}

struct ReconnectState {
    factory: Box<dyn ReconnectFactory>,
    policy: StreamReconnectPolicy,
    attempts: u32,
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn sse_stream_with_reconnect<M, F>(
    response: reqwest::Response,
    mapper: M,
    policy: StreamReconnectPolicy,
    factory: F,
    cancellation: Option<CancellationToken>,
    idle_timeout: Option<Duration>,
    audit: Option<AuditContext>,
    budget: RequestBudget,
) -> ModelStream
where
    M: SseMapper,
    F: FnMut(Option<String>) -> ReconnectFuture + Send + 'static,
{
    let metadata = ResponseMetadata::from_response(&response);
    let cancellation_future = cancellation_future(cancellation.clone());
    Box::pin(SseStream {
        inner: Box::pin(response.bytes_stream()),
        parser: mapper.sse_parser().with_byte_limits(
            budget.limits.max_sse_line_bytes,
            budget.limits.max_sse_event_bytes,
        ),
        mapper,
        queue: VecDeque::new(),
        finished: false,
        terminal: false,
        last_event_id: None,
        recent_events: VecDeque::new(),
        recent_bytes: 0,
        replay_events: None,
        replay_started: false,
        reconnect: Some(ReconnectState {
            factory: Box::new(factory),
            policy,
            attempts: 0,
        }),
        reconnect_future: None,
        cancellation,
        cancellation_future,
        idle_timeout,
        idle_deadline: idle_deadline(idle_timeout),
        audit,
        audit_finished: false,
        audit_status: Some(metadata.status),
        audit_provider_request_id: metadata.request_id,
        total_deadline: budget
            .deadline
            .map(|deadline| Box::pin(tokio::time::sleep_until(deadline))),
        budget,
        event_count: 0,
    })
}

struct SseStream<M> {
    inner: Pin<Box<dyn Stream<Item = std::result::Result<Bytes, reqwest::Error>> + Send>>,
    parser: SseParser,
    mapper: M,
    queue: VecDeque<Result<StreamEvent>>,
    finished: bool,
    terminal: bool,
    last_event_id: Option<String>,
    recent_events: VecDeque<Arc<SseMessage>>,
    recent_bytes: usize,
    replay_events: Option<VecDeque<Arc<SseMessage>>>,
    replay_started: bool,
    reconnect: Option<ReconnectState>,
    reconnect_future: Option<ReconnectFuture>,
    cancellation: Option<CancellationToken>,
    cancellation_future: Option<CancellationFuture>,
    idle_timeout: Option<Duration>,
    idle_deadline: Option<IdleDeadline>,
    audit: Option<AuditContext>,
    audit_finished: bool,
    audit_status: Option<u16>,
    audit_provider_request_id: Option<String>,
    budget: RequestBudget,
    total_deadline: Option<IdleDeadline>,
    event_count: usize,
}

const MAX_REPLAY_BYTES: usize = 1024 * 1024;
const MAX_REPLAY_EVENTS: usize = 4096;

impl<M> SseStream<M>
where
    M: SseMapper,
{
    fn finish_audit(&mut self, error: Option<&Error>, usage: Option<Usage>) {
        if self.audit_finished {
            return;
        }
        let Some(audit) = &self.audit else {
            return;
        };
        self.audit_finished = true;
        let outcome = match error {
            Some(Error::Cancelled) => AuditOutcome::Cancelled,
            Some(_) => AuditOutcome::Failure,
            None => AuditOutcome::Success,
        };
        audit.request_finished_with_request_id(
            outcome,
            self.audit_status,
            self.audit_provider_request_id.clone(),
            error,
            usage,
        );
    }

    fn enqueue_events(&mut self, events: Vec<StreamEvent>) {
        for event in events {
            if let Some(audit) = &self.audit {
                match &event {
                    StreamEvent::TextDelta { .. } => audit.first_token(FirstTokenKind::Text),
                    StreamEvent::ReasoningDelta { .. } => {
                        audit.first_token(FirstTokenKind::Reasoning);
                    }
                    StreamEvent::ToolCallDelta { .. } | StreamEvent::ToolCallProgress { .. } => {
                        audit.first_token(FirstTokenKind::ToolCall);
                    }
                    _ => {}
                }
            }
            if let StreamEvent::Done { response, .. } = &event {
                self.terminal = true;
                self.finish_audit(None, response.usage.clone());
            }
            self.queue.push_back(Ok(event));
        }
    }

    fn process_sse(&mut self, event: SseEvent) {
        if self.finished || self.terminal {
            return;
        }
        self.event_count += 1;
        if self.event_count > self.budget.limits.max_stream_events {
            self.fail(Error::ResponseLimit {
                resource: "SSE events",
                limit: self.budget.limits.max_stream_events,
            });
            return;
        }
        match event {
            SseEvent::Retry(delay) => self.queue.push_back(Ok(StreamEvent::Retry { delay })),
            SseEvent::Message(message) => {
                self.last_event_id = message.id.clone().filter(|id| !id.is_empty());
                if self.is_replayed(&message) {
                    return;
                }
                if self
                    .reconnect
                    .as_ref()
                    .is_some_and(|state| state.policy.deduplicate_replay)
                {
                    self.remember_event(&message);
                }

                match self.mapper.map(message) {
                    Ok(events) => self.enqueue_events(events),
                    Err(error) => {
                        self.finish_audit(Some(&error), None);
                        self.queue.push_back(Err(error));
                        self.finished = true;
                    }
                }
            }
        }
    }

    fn is_replayed(&mut self, message: &SseMessage) -> bool {
        let Some(replay) = self.replay_events.as_mut() else {
            return false;
        };
        if !self.replay_started {
            if let Some(index) = replay.iter().position(|old| old.as_ref() == message) {
                replay.drain(..index);
                self.replay_started = true;
            } else {
                self.replay_events = None;
                return false;
            }
        }
        if replay.front().is_some_and(|old| old.as_ref() == message) {
            replay.pop_front();
            if replay.is_empty() {
                self.replay_events = None;
            }
            true
        } else {
            self.replay_events = None;
            false
        }
    }

    fn remember_event(&mut self, message: &SseMessage) {
        if message.id.as_ref().is_none_or(String::is_empty) {
            return;
        }
        let bytes = message.data.len()
            + message.id.as_ref().map_or(0, String::len)
            + message.event.as_ref().map_or(0, String::len);
        // An oversized event cannot participate in safe bounded replay matching.
        if bytes > MAX_REPLAY_BYTES {
            self.recent_events.clear();
            self.recent_bytes = 0;
            return;
        }
        self.recent_bytes += bytes;
        self.recent_events.push_back(Arc::new(message.clone()));
        while self.recent_bytes > MAX_REPLAY_BYTES || self.recent_events.len() > MAX_REPLAY_EVENTS {
            if let Some(old) = self.recent_events.pop_front() {
                self.recent_bytes -= old.data.len()
                    + old.id.as_ref().map_or(0, String::len)
                    + old.event.as_ref().map_or(0, String::len);
            }
        }
    }

    fn fail(&mut self, error: Error) {
        self.finish_audit(Some(&error), None);
        self.queue.push_back(Err(error));
        self.finished = true;
    }

    fn process_sse_result(&mut self, result: std::result::Result<Vec<SseEvent>, SseError>) {
        match result {
            Ok(events) => {
                for event in events {
                    self.process_sse(event);
                }
            }
            Err(error) => {
                let error = Error::StreamProtocol(error.to_string());
                self.finish_audit(Some(&error), None);
                self.queue.push_back(Err(error));
                self.finished = true;
            }
        }
    }

    fn finish_stream(&mut self) {
        self.finished = true;

        match self.parser.finish() {
            Ok(events) => {
                for event in events {
                    self.process_sse(event);
                }
            }
            Err(error) => {
                let error = Error::StreamProtocol(error.to_string());
                self.finish_audit(Some(&error), None);
                self.queue.push_back(Err(error));
                return;
            }
        }

        if self.terminal || self.queue.iter().any(Result::is_err) {
            return;
        }

        match self.mapper.finish() {
            Ok(events) => self.enqueue_events(events),
            Err(error) => {
                self.finish_audit(Some(&error), None);
                self.queue.push_back(Err(error));
            }
        }

        if !self.terminal && !self.queue.iter().any(Result::is_err) {
            let error =
                Error::StreamProtocol("stream ended without a provider terminal event".to_string());
            self.finish_audit(Some(&error), None);
            self.queue.push_back(Err(error));
        }
    }

    fn schedule_reconnect(&mut self, delay_hint: Option<Duration>) -> bool {
        if self.terminal || self.finished {
            return false;
        }
        let Some(reconnect) = self.reconnect.as_mut() else {
            return false;
        };
        if reconnect.attempts >= reconnect.policy.max_attempts {
            return false;
        }
        if reconnect.policy.require_event_id && self.last_event_id.is_none() {
            return false;
        }

        let last_event_id = self.last_event_id.clone();
        let delay = delay_hint
            .or_else(|| self.parser.retry())
            .unwrap_or(reconnect.policy.delay);
        if delay > reconnect.policy.max_delay {
            return false;
        }
        if reconnect.policy.deduplicate_replay {
            self.replay_events = Some(self.recent_events.clone());
            self.replay_started = false;
        }
        reconnect.attempts += 1;
        if let Some(audit) = &self.audit {
            audit.stream_reconnect_scheduled(reconnect.attempts, delay, last_event_id.is_some());
        }
        let future = reconnect.factory.connect(last_event_id);
        self.queue.push_back(Ok(StreamEvent::Retry { delay }));
        self.queue.push_back(Ok(StreamEvent::Retrying {
            attempt: reconnect.attempts,
            max_attempts: reconnect.policy.max_attempts,
            delay,
            reason: "stream reconnect".to_string(),
        }));
        self.idle_deadline = None;
        let cancellation = self.cancellation.clone();
        self.reconnect_future = Some(Box::pin(async move {
            if let Some(cancellation) = cancellation {
                tokio::select! {
                    biased;
                    _ = cancellation.cancelled() => Err(Error::Cancelled),
                    _ = tokio::time::sleep(delay) => future.await,
                }
            } else {
                tokio::time::sleep(delay).await;
                future.await
            }
        }));
        true
    }

    fn cancel(&mut self) {
        let error = Error::Cancelled;
        self.finish_audit(Some(&error), None);
        self.queue.push_back(Err(error));
        self.finished = true;
    }

    fn reset_idle_deadline(&mut self) {
        self.idle_deadline = idle_deadline(self.idle_timeout);
    }

    fn handle_idle_timeout(&mut self) {
        if self.schedule_reconnect(None) {
            self.idle_deadline = None;
            return;
        }
        let error = Error::Timeout("stream idle timeout".to_string());
        self.finish_audit(Some(&error), None);
        self.queue.push_back(Err(error));
        self.finished = true;
    }

    fn handle_transport_error(&mut self, error: reqwest::Error) {
        if self.schedule_reconnect(None) {
            return;
        }
        let error = Error::from(error);
        self.finish_audit(Some(&error), None);
        self.queue.push_back(Err(error));
        self.finished = true;
    }
}

impl<M> Drop for SseStream<M> {
    fn drop(&mut self) {
        if self.audit_finished {
            return;
        }
        let Some(audit) = &self.audit else {
            return;
        };
        audit.request_finished_with_request_id(
            AuditOutcome::Cancelled,
            self.audit_status,
            self.audit_provider_request_id.clone(),
            None,
            None,
        );
        self.audit_finished = true;
    }
}

impl<M> Stream for SseStream<M>
where
    M: SseMapper,
{
    type Item = Result<StreamEvent>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        loop {
            if !this.finished && !this.terminal {
                if this
                    .cancellation
                    .as_ref()
                    .is_some_and(CancellationToken::is_cancelled)
                {
                    this.queue.clear();
                    this.cancel();
                    continue;
                }
                if let Some(mut deadline) = this.total_deadline.take() {
                    match deadline.as_mut().poll(cx) {
                        Poll::Pending => this.total_deadline = Some(deadline),
                        Poll::Ready(()) => {
                            this.queue.clear();
                            this.fail(Error::Timeout("total request deadline".into()));
                            continue;
                        }
                    }
                }
            }
            if let Some(event) = this.queue.pop_front() {
                return Poll::Ready(Some(event));
            }

            if this.terminal {
                this.finished = true;
                return Poll::Ready(None);
            }

            if this.finished {
                return Poll::Ready(None);
            }

            if let Some(mut future) = this.cancellation_future.take() {
                match future.as_mut().poll(cx) {
                    Poll::Pending => {
                        this.cancellation_future = Some(future);
                    }
                    Poll::Ready(()) => {
                        this.cancel();
                        continue;
                    }
                }
            }

            if this.reconnect_future.is_none()
                && let Some(mut deadline) = this.idle_deadline.take()
            {
                match deadline.as_mut().poll(cx) {
                    Poll::Pending => {
                        this.idle_deadline = Some(deadline);
                    }
                    Poll::Ready(()) => {
                        this.handle_idle_timeout();
                        continue;
                    }
                }
            }

            if let Some(mut future) = this.reconnect_future.take() {
                match future.as_mut().poll(cx) {
                    Poll::Pending => {
                        this.reconnect_future = Some(future);
                        return Poll::Pending;
                    }
                    Poll::Ready(Ok(response)) => {
                        this.inner = Box::pin(response.bytes_stream());
                        this.parser.reset_for_reconnect();
                        this.reset_idle_deadline();
                        continue;
                    }
                    Poll::Ready(Err(error)) => {
                        if this.schedule_reconnect(error.retry_after()) {
                            continue;
                        }
                        this.finish_audit(Some(&error), None);
                        this.queue.push_back(Err(error));
                        this.finished = true;
                        continue;
                    }
                }
            }

            match this.inner.as_mut().poll_next(cx) {
                Poll::Pending => return Poll::Pending,
                Poll::Ready(Some(Ok(bytes))) => {
                    if let Some(audit) = &this.audit {
                        audit.add_response_bytes(bytes.len());
                    }
                    if let Err(error) = this.budget.add_bytes(bytes.len()) {
                        this.fail(error);
                        continue;
                    }
                    this.reset_idle_deadline();
                    let result = this.parser.push(&bytes);
                    this.process_sse_result(result);
                }
                Poll::Ready(Some(Err(error))) => this.handle_transport_error(error),
                Poll::Ready(None) => {
                    if !this.terminal
                        && !this.mapper.eof_is_terminal()
                        && this.schedule_reconnect(None)
                    {
                        continue;
                    }
                    this.finish_stream();
                }
            }
        }
    }
}

/// Await the next stream event without requiring the caller to import
/// `futures_util::StreamExt`.
pub async fn next_event(stream: &mut ModelStream) -> Option<Result<StreamEvent>> {
    use std::future::poll_fn;

    poll_fn(|cx| stream.as_mut().poll_next(cx)).await
}

/// Collect a stream into the final response while preserving all events.
///
/// This is mainly useful for tests and for applications that intentionally do
/// not render tokens incrementally.
pub async fn collect_stream(mut stream: ModelStream) -> Result<ChatResponse> {
    while let Some(event) = next_event(&mut stream).await {
        if let StreamEvent::Done { response, .. } = event? {
            return Ok(*response);
        }
    }

    Err(Error::StreamProtocol(
        "stream ended without a Done event".to_string(),
    ))
}

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

    struct TestMapper {
        text: String,
    }

    impl SseMapper for TestMapper {
        fn map(&mut self, message: SseMessage) -> Result<Vec<StreamEvent>> {
            self.text.push_str(&message.data);
            Ok(vec![StreamEvent::TextDelta { text: message.data }])
        }

        fn finish(&mut self) -> Result<Vec<StreamEvent>> {
            Ok(vec![StreamEvent::Done {
                response: Box::new(ChatResponse::new(Message::assistant(&self.text))),
                finish_reason: Some("stop".to_string()),
            }])
        }
    }

    #[test]
    fn sse_stream_handles_split_cjk_and_emits_done() {
        let payload = "retry: 10\ndata: 你好\n\n";
        let split = payload.find("你").expect("CJK marker exists") + "你".len() - 1;
        let chunks = vec![
            Ok::<_, reqwest::Error>(Bytes::copy_from_slice(&payload.as_bytes()[..split])),
            Ok::<_, reqwest::Error>(Bytes::copy_from_slice(&payload.as_bytes()[split..])),
        ];
        let inner: Pin<Box<dyn Stream<Item = std::result::Result<Bytes, reqwest::Error>> + Send>> =
            Box::pin(futures_util::stream::iter(chunks));
        let stream: ModelStream = Box::pin(SseStream {
            inner,
            parser: SseParser::new(),
            mapper: TestMapper {
                text: String::new(),
            },
            queue: VecDeque::new(),
            finished: false,
            terminal: false,
            last_event_id: None,
            recent_events: VecDeque::new(),
            recent_bytes: 0,
            replay_events: None,
            replay_started: false,
            reconnect: None,
            reconnect_future: None,
            cancellation: None,
            cancellation_future: None,
            idle_timeout: None,
            idle_deadline: None,
            audit: None,
            audit_finished: false,
            audit_status: None,
            audit_provider_request_id: None,
            budget: RequestBudget::new(&crate::RequestOptions::default()).unwrap(),
            total_deadline: None,
            event_count: 0,
        });

        let response = futures_executor::block_on(collect_stream(stream)).unwrap();
        assert_eq!(response.text(), "你好");
    }
}