openai-ergonomic 0.26.0

Ergonomic Rust wrapper for OpenAI API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
//! Streaming support for chat completions and the Responses API.
//!
//! This module provides streaming functionality for `OpenAI` chat completions using
//! Server-Sent Events (SSE). The streaming API allows receiving responses incrementally
//! as they are generated, enabling real-time user experiences. The Responses API's events
//! ([`ResponsesEvent`](crate::responses_api::ResponsesEvent)) go through the same
//! [`InterceptedStream`].
//!
//! A chat completion stream completes with `data: [DONE]` or after a chunk with a
//! `finish_reason`; a body that ends before either yields [`Error::StreamConnection`] as its
//! last item, so a cut-off stream is never reported as [`StreamOutcome::Completed`].
//!
//! # Example
//!
//! ```rust,no_run
//! use openai_ergonomic::Client;
//! use futures::StreamExt;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let client = Client::from_env()?.build();
//!
//!     let builder = client.chat().user("Tell me a story");
//!     let mut stream = client.send_chat_stream(builder).await?;
//!
//!     while let Some(chunk) = stream.next().await {
//!         let chunk = chunk?;
//!         if let Some(content) = chunk.content() {
//!             print!("{}", content);
//!         }
//!     }
//!
//!     Ok(())
//! }
//! ```
//!
//! # Interceptor Support
//!
//! Streaming responses automatically work with interceptors. When interceptors are
//! configured, they will receive hooks for:
//! - `before_request`: Called before streaming starts
//! - `on_stream_chunk`: Called for each chunk as it arrives
//! - `on_stream_terminal`: Called once on completion, failure, or cancellation
//!
//! Use `send_chat_stream_with_completion` or `send_responses_stream_with_completion` when
//! application shutdown needs to wait for all managed interceptor callbacks. Drop a stream after
//! stopping early, then await `StreamCompletion::wait` before flushing telemetry exporters.
//!
//! See the `langfuse_streaming` example for a complete demonstration.

use crate::interceptor::{StreamChunkContext, StreamEndContext, StreamTerminalContext};
use crate::time::{Instant, Spawner};
use crate::{Error, MaybeSend, MaybeSync, Result};
#[cfg(test)]
use bytes::Bytes;
use futures::future::FutureExt;
use futures::stream::Stream;
use futures::StreamExt;
use openai_client_base::models::{
    ChatCompletionStreamResponseDelta, CreateChatCompletionStreamResponse,
};
use std::any::Any;
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Duration;
use timvw_rust_runtime::sse;
use tokio::sync::mpsc::{self, OwnedPermit};
use tokio::sync::watch;

const STREAM_CALLBACK_QUEUE_CAPACITY: usize = 1;
const MAX_RETAINED_CALLBACK_FAILURES: usize = 64;
const MAX_CALLBACK_DIAGNOSTIC_CHARS: usize = 512;

/// Classification of the terminal stream failure.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum StreamFailureKind {
    /// The underlying response stream failed while receiving data.
    Connection,
    /// An SSE event could not be decoded.
    Parsing,
    /// The stream exceeded an internal buffer limit or otherwise failed buffering.
    Buffer,
    /// Any other stream error.
    Other,
}

/// Safe, owned classification of an error yielded by a stream.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StreamFailure {
    /// The broad error category. Raw response data is not retained.
    pub kind: StreamFailureKind,
}

impl StreamFailure {
    fn from_error(error: &Error) -> Self {
        let kind = match error {
            Error::StreamConnection { .. } | Error::Http(_) => StreamFailureKind::Connection,
            Error::StreamParsing { .. } | Error::Json(_) => StreamFailureKind::Parsing,
            Error::StreamBuffer { .. } => StreamFailureKind::Buffer,
            _ => StreamFailureKind::Other,
        };
        Self { kind }
    }
}

/// The first terminal event observed for an intercepted stream.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum StreamOutcome {
    /// The stream ended normally: for chat, `data: [DONE]` or the end of the body after a
    /// `finish_reason`; for the Responses API, a terminal event (`response.completed`,
    /// `response.incomplete`, `response.failed` or `error`).
    Completed,
    /// The stream yielded an error item.
    StreamFailed(StreamFailure),
    /// The consumer dropped the stream before EOF or an error item.
    Cancelled,
}

/// The interceptor hook associated with a callback failure.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StreamCallbackHook {
    /// A per-chunk callback.
    Chunk,
    /// The once-per-stream terminal callback.
    Terminal,
}

/// How an interceptor callback failed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StreamCallbackFailureKind {
    /// The callback returned an error.
    ReturnedError,
    /// The callback panicked with unwinding enabled.
    Panicked,
}

/// A bounded diagnostic for one callback failure.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StreamCallbackFailure {
    /// The hook that failed.
    pub hook: StreamCallbackHook,
    /// Zero-based position of the interceptor in the registered chain.
    pub interceptor_index: usize,
    /// Zero-based chunk index for chunk hooks; `None` for the terminal hook.
    pub chunk_index: Option<usize>,
    /// Whether the callback returned an error or panicked.
    pub kind: StreamCallbackFailureKind,
    /// A short diagnostic. It never includes serialized request or chunk data.
    pub diagnostic: String,
    /// Whether the diagnostic was shortened to the configured character limit.
    pub diagnostic_truncated: bool,
}

/// Immutable summary sealed after all managed stream callbacks have finished.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StreamCompletionReport {
    /// The latched terminal outcome.
    pub outcome: StreamOutcome,
    /// Number of successfully decoded chunks admitted to callback processing.
    pub total_chunks: usize,
    /// Time from intercepted stream construction to terminal processing.
    pub duration: Duration,
    /// Last observed input token count, if supplied by the stream.
    pub input_tokens: Option<i64>,
    /// Last observed output token count, if supplied by the stream.
    pub output_tokens: Option<i64>,
    /// Number of interceptor callbacks attempted.
    pub callback_attempts: usize,
    /// Number of interceptor callbacks that returned successfully.
    pub callback_successes: usize,
    /// Exact number of interceptor callbacks that failed.
    pub callback_failure_count: usize,
    /// Retained callback failure details, capped at 64 entries.
    pub callback_failures: Vec<StreamCallbackFailure>,
    /// Exact number of failure details omitted after the retention cap.
    pub truncated_failure_details: usize,
}

/// The dispatcher ended without sealing a completion report.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[error("stream callback dispatcher ended before producing a completion report")]
pub struct CompletionUnavailable;

/// Cloneable wait handle for one intercepted stream's callback drain.
#[derive(Clone, Debug)]
pub struct StreamCompletion {
    report: watch::Receiver<Option<Arc<StreamCompletionReport>>>,
}

impl StreamCompletion {
    /// Wait for the terminal event and all accepted callback work to finish.
    ///
    /// Repeated and concurrent waits return the same immutable report. Dropping a waiter does
    /// not cancel the stream or the dispatcher.
    pub async fn wait(
        &self,
    ) -> std::result::Result<Arc<StreamCompletionReport>, CompletionUnavailable> {
        let mut report = self.report.clone();
        loop {
            let current = { report.borrow().clone() };
            if let Some(value) = current {
                return Ok(value);
            }
            if report.changed().await.is_err() {
                return Err(CompletionUnavailable);
            }
        }
    }
}

pub(crate) mod sealed {
    /// Seals [`InterceptedItem`](super::InterceptedItem).
    pub trait Sealed {}
}

/// An item of a stream whose interceptor callbacks [`InterceptedStream`] dispatches: a
/// [`ChatCompletionChunk`] or a [`ResponsesEvent`](crate::responses_api::ResponsesEvent).
///
/// This trait is sealed: it cannot be implemented outside this crate.
pub trait InterceptedItem: sealed::Sealed + MaybeSend + 'static {
    /// The item as the JSON passed to [`Interceptor::on_stream_chunk`](crate::Interceptor::on_stream_chunk).
    fn chunk_json(&self) -> String;
    /// The input and output token counts the item reports, if any.
    fn token_usage(&self) -> Option<(i64, i64)>;
}

impl sealed::Sealed for ChatCompletionChunk {}

impl InterceptedItem for ChatCompletionChunk {
    fn chunk_json(&self) -> String {
        serde_json::to_string(self.raw_response()).unwrap_or_else(|_| "{}".to_string())
    }

    fn token_usage(&self) -> Option<(i64, i64)> {
        match &self.raw_response().usage {
            Some(Some(usage)) => Some((usage.prompt_tokens, usage.completion_tokens)),
            _ => None,
        }
    }
}

/// Type alias for a boxed stream of chat completion chunks.
///
/// Client methods use this type to preserve one public stream shape while managing ordered
/// interceptor callbacks and stream lifecycle reporting.
///
/// The stream is `Send` natively; on WebAssembly, where the host's streams cannot leave its
/// thread, it is not.
#[cfg(not(target_family = "wasm"))]
pub type BoxedChatStream = Pin<Box<dyn Stream<Item = Result<ChatCompletionChunk>> + Send>>;
/// Type alias for a boxed stream of chat completion chunks.
///
/// Client methods use this type to preserve one public stream shape while managing ordered
/// interceptor callbacks and stream lifecycle reporting.
///
/// The stream is `Send` natively; on WebAssembly, where the host's streams cannot leave its
/// thread, it is not.
#[cfg(target_family = "wasm")]
pub type BoxedChatStream = Pin<Box<dyn Stream<Item = Result<ChatCompletionChunk>>>>;

/// A streaming chunk from a chat completion response.
///
/// Each chunk represents a delta update from the model as it generates the response.
#[derive(Debug, Clone)]
pub struct ChatCompletionChunk {
    /// The underlying stream response
    response: CreateChatCompletionStreamResponse,
}

impl ChatCompletionChunk {
    /// Create a new chunk from a stream response.
    #[must_use]
    pub fn new(response: CreateChatCompletionStreamResponse) -> Self {
        Self { response }
    }

    /// Get the content delta from this chunk, if any.
    ///
    /// Returns the text content that was generated in this chunk.
    #[must_use]
    pub fn content(&self) -> Option<&str> {
        self.response
            .choices
            .first()
            .and_then(|choice| choice.delta.content.as_ref().and_then(|c| c.as_deref()))
    }

    /// Get the role from this chunk, if any.
    ///
    /// This is typically only present in the first chunk. `None` means this chunk has no role. A
    /// role this crate does not know is `Some("unknown")`, and the API's own text is not kept.
    #[must_use]
    pub fn role(&self) -> Option<&str> {
        self.response
            .choices
            .first()
            .and_then(|choice| choice.delta.role.as_ref())
            .map(|role| match role {
                openai_client_base::models::chat_completion_stream_response_delta::Role::System => {
                    "system"
                }
                openai_client_base::models::chat_completion_stream_response_delta::Role::User => {
                    "user"
                }
                openai_client_base::models::chat_completion_stream_response_delta::Role::Assistant => {
                    "assistant"
                }
                openai_client_base::models::chat_completion_stream_response_delta::Role::Tool => {
                    "tool"
                }
                openai_client_base::models::chat_completion_stream_response_delta::Role::Developer => {
                    "developer"
                }
                openai_client_base::models::chat_completion_stream_response_delta::Role::Unknown => {
                    "unknown"
                }
            })
    }

    /// Get tool calls from this chunk, if any.
    #[must_use]
    pub fn tool_calls(
        &self,
    ) -> Option<&Vec<openai_client_base::models::ChatCompletionMessageToolCallChunk>> {
        self.response
            .choices
            .first()
            .and_then(|choice| choice.delta.tool_calls.as_ref())
    }

    /// Get the finish reason, if any.
    ///
    /// This indicates why the generation stopped and is only present in the last chunk. A reason
    /// this crate does not know is `Some("unknown")`, so [`Self::is_final`] still holds, and the
    /// API's own text is not kept.
    #[must_use]
    pub fn finish_reason(&self) -> Option<&str> {
        self.response.choices.first().and_then(|choice| choice.finish_reason.as_ref()).and_then(Option::as_ref).map(|reason| {
            match reason {
                openai_client_base::models::create_chat_completion_stream_response_choices_inner::FinishReason::Stop => "stop",
                openai_client_base::models::create_chat_completion_stream_response_choices_inner::FinishReason::Length => "length",
                openai_client_base::models::create_chat_completion_stream_response_choices_inner::FinishReason::ToolCalls => "tool_calls",
                openai_client_base::models::create_chat_completion_stream_response_choices_inner::FinishReason::ContentFilter => "content_filter",
                openai_client_base::models::create_chat_completion_stream_response_choices_inner::FinishReason::FunctionCall => "function_call",
                openai_client_base::models::create_chat_completion_stream_response_choices_inner::FinishReason::Unknown => "unknown",
            }
        })
    }

    /// Check if this is the last chunk in the stream.
    #[must_use]
    pub fn is_final(&self) -> bool {
        self.finish_reason().is_some()
    }

    /// Get the underlying raw response.
    #[must_use]
    pub fn raw_response(&self) -> &CreateChatCompletionStreamResponse {
        &self.response
    }

    /// Get the delta object directly.
    #[must_use]
    pub fn delta(&self) -> Option<&ChatCompletionStreamResponseDelta> {
        self.response.choices.first().map(|choice| &choice.delta)
    }
}

/// A stream of chat completion chunks.
///
/// This stream yields `ChatCompletionChunk` items as the model generates the response.
/// The stream ends when the model finishes generating or encounters an error.
pub struct ChatCompletionStream {
    inner: BoxedChatStream,
}

impl ChatCompletionStream {
    /// Create a new stream from a byte stream response.
    ///
    /// Parses Server-Sent Events (SSE) format and yields chat completion chunks. The stream
    /// completes at `data: [DONE]`, or at the end of the body after a chunk with a
    /// `finish_reason`; a body that ends before either yields [`Error::StreamConnection`].
    pub fn new(response: timvw_rust_runtime::Response) -> Self {
        Self {
            inner: Box::pin(decode_frames(crate::sse_frames::frames(
                response.bytes_stream(),
            ))),
        }
    }

    /// Create a stream from the events of a response, such as those of a generated `_stream` method
    /// (`EventStream::into_events`).
    ///
    /// [`sse::Events`] ends at `data: [DONE]` without yielding it, so here the stream completes
    /// only after a chunk with a `finish_reason`; it yields [`Error::StreamConnection`] when the
    /// events end before one.
    pub fn from_events(events: sse::Events) -> Self {
        Self {
            inner: Box::pin(decode_frames(crate::sse_frames::from_events(events))),
        }
    }

    /// Collect all remaining content from the stream into a single string.
    ///
    /// This is a convenience method that reads all chunks and concatenates their content.
    pub async fn collect_content(mut self) -> Result<String> {
        let mut content = String::new();
        while let Some(chunk) = self.next().await {
            let chunk = chunk?;
            if let Some(text) = chunk.content() {
                content.push_str(text);
            }
        }
        Ok(content)
    }
}

impl Stream for ChatCompletionStream {
    type Item = Result<ChatCompletionChunk>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.inner.as_mut().poll_next(cx)
    }
}

struct ChunkEvent {
    chunk_json: String,
    chunk_index: usize,
    input_tokens: Option<i64>,
    output_tokens: Option<i64>,
}

type ReserveFuture = crate::BoxFuture<
    'static,
    std::result::Result<OwnedPermit<ChunkEvent>, mpsc::error::SendError<()>>,
>;

/// Wrapper for a stream that dispatches bounded, ordered interceptor callbacks.
///
/// The wrapper's direct constructor may be called outside a Tokio runtime, but it must be polled
/// inside one (natively; on WebAssembly the callbacks run on the JavaScript host's event loop,
/// `wasm_bindgen_futures::spawn_local`, and no Tokio runtime is involved). Use
/// [`Self::new_with_completion`] to validate the runtime and obtain a drain handle.
pub struct InterceptedStream<
    T: MaybeSend + MaybeSync + 'static = (),
    C: InterceptedItem = ChatCompletionChunk,
> {
    inner: Option<crate::BoxStream<'static, Result<C>>>,
    interceptors: Arc<crate::interceptor::InterceptorChain<T>>,
    operation: String,
    model: String,
    request_json: String,
    state: Arc<T>,
    start_time: Instant,
    chunk_index: usize,
    input_tokens: Option<i64>,
    output_tokens: Option<i64>,
    started: bool,
    queue_tx: Option<mpsc::Sender<ChunkEvent>>,
    reserve_future: Option<ReserveFuture>,
    reserved: Option<OwnedPermit<ChunkEvent>>,
    terminal_tx: Option<watch::Sender<Option<StreamOutcome>>>,
    report_tx: Option<watch::Sender<Option<Arc<StreamCompletionReport>>>>,
    terminated: bool,
}

impl<T: MaybeSend + MaybeSync + 'static, C: InterceptedItem> InterceptedStream<T, C> {
    /// Create an intercepted stream.
    ///
    /// Construction does not require a runtime. The first poll must occur inside an active
    /// Tokio runtime. Dropping the stream before its first poll starts no dispatcher.
    pub fn new(
        inner: impl Stream<Item = Result<C>> + MaybeSend + 'static,
        interceptors: Arc<crate::interceptor::InterceptorChain<T>>,
        operation: String,
        model: String,
        request_json: String,
        state: T,
    ) -> Self {
        Self {
            inner: Some(crate::box_stream(inner)),
            interceptors,
            operation,
            model,
            request_json,
            state: Arc::new(state),
            start_time: Instant::now(),
            chunk_index: 0,
            input_tokens: None,
            output_tokens: None,
            started: false,
            queue_tx: None,
            reserve_future: None,
            reserved: None,
            terminal_tx: None,
            report_tx: None,
            terminated: false,
        }
    }

    /// Create an intercepted stream and a handle that resolves after callback drain.
    ///
    /// An active Tokio runtime is required natively (not on WebAssembly). This method returns an
    /// error instead of panicking when called outside one.
    pub fn new_with_completion(
        inner: impl Stream<Item = Result<C>> + MaybeSend + 'static,
        interceptors: Arc<crate::interceptor::InterceptorChain<T>>,
        operation: String,
        model: String,
        request_json: String,
        state: T,
    ) -> Result<(Self, StreamCompletion)> {
        let runtime = Spawner::current().ok_or_else(|| {
            Error::Config(
                "InterceptedStream::new_with_completion requires an active Tokio runtime".into(),
            )
        })?;
        let mut stream = Self::new(inner, interceptors, operation, model, request_json, state);
        let completion = stream.start_lifecycle(&runtime);
        Ok((stream, completion))
    }

    fn start_lifecycle(&mut self, runtime: &Spawner) -> StreamCompletion {
        let (report_tx, report_rx) = watch::channel(None);
        if self.interceptors.is_empty() {
            self.started = true;
            self.report_tx = Some(report_tx);
            return StreamCompletion { report: report_rx };
        }

        let (queue_tx, queue_rx) = mpsc::channel(STREAM_CALLBACK_QUEUE_CAPACITY);
        let (terminal_tx, terminal_rx) = watch::channel(None);

        let interceptors = Arc::clone(&self.interceptors);
        let operation = self.operation.clone();
        let model = self.model.clone();
        let request_json = self.request_json.clone();
        let state = Arc::clone(&self.state);
        let start_time = self.start_time;

        runtime.spawn(async move {
            dispatch_stream_callbacks(
                queue_rx,
                terminal_rx,
                report_tx,
                interceptors,
                operation,
                model,
                request_json,
                state,
                start_time,
            )
            .await;
        });

        self.queue_tx = Some(queue_tx);
        self.terminal_tx = Some(terminal_tx);
        self.started = true;
        StreamCompletion { report: report_rx }
    }

    fn finish(&mut self, outcome: StreamOutcome) {
        self.terminated = true;
        // EOF and errors can be emitted before the HTTP body itself is exhausted (for example,
        // an invalid SSE frame followed by a pending body). Release that transport immediately.
        self.inner.take();
        self.reserve_future.take();
        self.reserved.take();
        self.queue_tx.take();
        if let Some(report_tx) = self.report_tx.take() {
            let report = StreamCompletionReport {
                outcome,
                total_chunks: self.chunk_index,
                duration: self.start_time.elapsed(),
                input_tokens: self.input_tokens,
                output_tokens: self.output_tokens,
                callback_attempts: 0,
                callback_successes: 0,
                callback_failure_count: 0,
                callback_failures: Vec::new(),
                truncated_failure_details: 0,
            };
            let _ = report_tx.send(Some(Arc::new(report)));
        }
        if let Some(terminal_tx) = self.terminal_tx.take() {
            terminal_tx.send_if_modified(|current| {
                if current.is_none() {
                    *current = Some(outcome);
                    true
                } else {
                    false
                }
            });
        }
    }

    #[allow(clippy::expect_used)] // `inner` is only taken once the stream is finished
    fn poll_inner(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<C>>> {
        self.inner
            .as_mut()
            .expect("live intercepted stream has an inner stream")
            .as_mut()
            .poll_next(cx)
    }
}

impl<T: MaybeSend + MaybeSync + 'static> InterceptedStream<T, ChatCompletionChunk> {
    /// Collect all remaining content from the stream into a single string.
    ///
    /// The stream's callbacks remain ordered and the dispatcher is allowed to finish after this
    /// method returns. Use [`StreamCompletion::wait`] when application shutdown needs a drain barrier.
    pub async fn collect_content(mut self) -> Result<String> {
        let mut content = String::new();
        while let Some(chunk) = self.next().await {
            let chunk = chunk?;
            if let Some(text) = chunk.content() {
                content.push_str(text);
            }
        }
        Ok(content)
    }
}

impl<T: MaybeSend + MaybeSync + 'static, C: InterceptedItem> Drop for InterceptedStream<T, C> {
    fn drop(&mut self) {
        if !self.terminated {
            self.finish(StreamOutcome::Cancelled);
        }
    }
}

impl<T: MaybeSend + MaybeSync + 'static, C: InterceptedItem> Stream for InterceptedStream<T, C> {
    type Item = Result<C>;

    #[allow(clippy::expect_used)] // the queue sender and reserved slot are set before use
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        if this.terminated {
            return Poll::Ready(None);
        }

        if !this.started {
            let Some(runtime) = Spawner::current() else {
                this.terminated = true;
                this.inner.take();
                return Poll::Ready(Some(Err(Error::Config(
                    "InterceptedStream must be polled inside an active Tokio runtime".into(),
                ))));
            };
            this.start_lifecycle(&runtime);
        }

        if this.interceptors.is_empty() {
            return match this.poll_inner(cx) {
                Poll::Ready(Some(Ok(chunk))) => {
                    update_usage(this, &chunk);
                    this.chunk_index = this.chunk_index.saturating_add(1);
                    Poll::Ready(Some(Ok(chunk)))
                }
                Poll::Ready(Some(Err(error))) => {
                    let outcome = StreamOutcome::StreamFailed(StreamFailure::from_error(&error));
                    this.finish(outcome);
                    Poll::Ready(Some(Err(error)))
                }
                Poll::Ready(None) => {
                    this.finish(StreamOutcome::Completed);
                    Poll::Ready(None)
                }
                Poll::Pending => Poll::Pending,
            };
        }

        if this.reserved.is_none() {
            if this.reserve_future.is_none() {
                let sender = this
                    .queue_tx
                    .as_ref()
                    .expect("started stream has queue sender")
                    .clone();
                this.reserve_future = Some(Box::pin(sender.reserve_owned()));
            }
            match this
                .reserve_future
                .as_mut()
                .expect("reserve future was just initialized")
                .as_mut()
                .poll(cx)
            {
                Poll::Pending => return Poll::Pending,
                Poll::Ready(Ok(permit)) => {
                    this.reserve_future.take();
                    this.reserved = Some(permit);
                }
                Poll::Ready(Err(_)) => {
                    this.finish(StreamOutcome::StreamFailed(StreamFailure {
                        kind: StreamFailureKind::Other,
                    }));
                    return Poll::Ready(Some(Err(Error::Internal(
                        "stream callback dispatcher stopped unexpectedly".into(),
                    ))));
                }
            }
        }

        match this.poll_inner(cx) {
            Poll::Ready(Some(Ok(chunk))) => {
                update_usage(this, &chunk);
                let event = ChunkEvent {
                    chunk_json: chunk.chunk_json(),
                    chunk_index: this.chunk_index,
                    input_tokens: this.input_tokens,
                    output_tokens: this.output_tokens,
                };
                this.reserved
                    .take()
                    .expect("polling the inner stream requires a reserved callback slot")
                    .send(event);
                this.chunk_index = this.chunk_index.saturating_add(1);
                Poll::Ready(Some(Ok(chunk)))
            }
            Poll::Ready(Some(Err(error))) => {
                let outcome = StreamOutcome::StreamFailed(StreamFailure::from_error(&error));
                this.finish(outcome);
                Poll::Ready(Some(Err(error)))
            }
            Poll::Ready(None) => {
                this.finish(StreamOutcome::Completed);
                Poll::Ready(None)
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

fn update_usage<T: MaybeSend + MaybeSync + 'static, C: InterceptedItem>(
    stream: &mut InterceptedStream<T, C>,
    chunk: &C,
) {
    if let Some((input_tokens, output_tokens)) = chunk.token_usage() {
        stream.input_tokens = Some(input_tokens);
        stream.output_tokens = Some(output_tokens);
    }
}

async fn dispatch_stream_callbacks<T: MaybeSend + MaybeSync + 'static>(
    mut queue: mpsc::Receiver<ChunkEvent>,
    mut terminal: watch::Receiver<Option<StreamOutcome>>,
    report_tx: watch::Sender<Option<Arc<StreamCompletionReport>>>,
    interceptors: Arc<crate::interceptor::InterceptorChain<T>>,
    operation: String,
    model: String,
    request_json: String,
    state: Arc<T>,
    start_time: Instant,
) {
    let mut report = StreamCompletionReport {
        outcome: StreamOutcome::Completed,
        total_chunks: 0,
        duration: Duration::ZERO,
        input_tokens: None,
        output_tokens: None,
        callback_attempts: 0,
        callback_successes: 0,
        callback_failure_count: 0,
        callback_failures: Vec::new(),
        truncated_failure_details: 0,
    };

    let outcome = loop {
        tokio::select! {
            changed = terminal.changed() => {
                if changed.is_err() {
                    return;
                }
                let current = *terminal.borrow();
                if let Some(outcome) = current {
                    break outcome;
                }
            }
            event = queue.recv() => if let Some(event) = event {
                    dispatch_chunk_event(
                        &mut report,
                        &interceptors,
                        &operation,
                        &model,
                        &request_json,
                        &state,
                        event,
                    ).await;
                } else {
                    // Closing the chunk sender can race with the separate terminal signal in
                    // this select. Wait for that signal instead of treating queue closure as
                    // an unavailable report by itself.
                    let current = *terminal.borrow();
                    if let Some(outcome) = current {
                        break outcome;
                    }
                    if terminal.changed().await.is_err() {
                        return;
                    }
                    let current = *terminal.borrow();
                    if let Some(outcome) = current {
                        break outcome;
                    }
                }
        }
    };

    // The producer closes the chunk queue before signaling terminal. Drain all admitted chunks
    // before sending the one terminal callback to every interceptor.
    while let Some(event) = queue.recv().await {
        dispatch_chunk_event(
            &mut report,
            &interceptors,
            &operation,
            &model,
            &request_json,
            &state,
            event,
        )
        .await;
    }

    report.outcome = outcome;
    report.duration = start_time.elapsed();
    dispatch_terminal_event(
        &mut report,
        &interceptors,
        &operation,
        &model,
        &request_json,
        &state,
        outcome,
    )
    .await;
    let _ = report_tx.send(Some(Arc::new(report)));
}

async fn dispatch_chunk_event<T: MaybeSend + MaybeSync + 'static>(
    report: &mut StreamCompletionReport,
    interceptors: &crate::interceptor::InterceptorChain<T>,
    operation: &str,
    model: &str,
    request_json: &str,
    state: &T,
    event: ChunkEvent,
) {
    report.total_chunks = report.total_chunks.saturating_add(1);
    if let Some(input_tokens) = event.input_tokens {
        report.input_tokens = Some(input_tokens);
    }
    if let Some(output_tokens) = event.output_tokens {
        report.output_tokens = Some(output_tokens);
    }

    let ctx = StreamChunkContext {
        operation,
        model,
        request_json,
        chunk_json: &event.chunk_json,
        chunk_index: event.chunk_index,
        state,
    };
    for (interceptor_index, interceptor) in interceptors.iter().enumerate() {
        record_callback(
            report,
            StreamCallbackHook::Chunk,
            interceptor_index,
            Some(event.chunk_index),
            || interceptor.on_stream_chunk(&ctx),
        )
        .await;
    }
}

async fn dispatch_terminal_event<T: MaybeSend + MaybeSync + 'static>(
    report: &mut StreamCompletionReport,
    interceptors: &crate::interceptor::InterceptorChain<T>,
    operation: &str,
    model: &str,
    request_json: &str,
    state: &T,
    outcome: StreamOutcome,
) {
    let summary = StreamEndContext {
        operation,
        model,
        request_json,
        total_chunks: report.total_chunks,
        duration: report.duration,
        input_tokens: report.input_tokens,
        output_tokens: report.output_tokens,
        state,
    };
    let ctx = StreamTerminalContext { summary, outcome };
    for (interceptor_index, interceptor) in interceptors.iter().enumerate() {
        record_callback(
            report,
            StreamCallbackHook::Terminal,
            interceptor_index,
            None,
            || interceptor.on_stream_terminal(&ctx),
        )
        .await;
    }
}

async fn record_callback<F, Fut>(
    report: &mut StreamCompletionReport,
    hook: StreamCallbackHook,
    interceptor_index: usize,
    chunk_index: Option<usize>,
    callback: F,
) where
    F: FnOnce() -> Fut + MaybeSend,
    Fut: Future<Output = Result<()>> + MaybeSend,
{
    report.callback_attempts = report.callback_attempts.saturating_add(1);
    let callback_future = match std::panic::catch_unwind(AssertUnwindSafe(callback)) {
        Ok(callback) => callback,
        Err(payload) => {
            let diagnostic = panic_diagnostic(payload.as_ref());
            record_callback_failure(
                report,
                hook,
                interceptor_index,
                chunk_index,
                StreamCallbackFailureKind::Panicked,
                &diagnostic,
            );
            return;
        }
    };
    match AssertUnwindSafe(callback_future).catch_unwind().await {
        Ok(Ok(())) => report.callback_successes = report.callback_successes.saturating_add(1),
        Ok(Err(error)) => {
            let diagnostic = std::panic::catch_unwind(AssertUnwindSafe(|| error.to_string()))
                .unwrap_or_else(|_| {
                    "callback returned an error (diagnostic formatting panicked)".into()
                });
            record_callback_failure(
                report,
                hook,
                interceptor_index,
                chunk_index,
                StreamCallbackFailureKind::ReturnedError,
                &diagnostic,
            );
        }
        Err(payload) => {
            let diagnostic = panic_diagnostic(payload.as_ref());
            record_callback_failure(
                report,
                hook,
                interceptor_index,
                chunk_index,
                StreamCallbackFailureKind::Panicked,
                &diagnostic,
            );
        }
    }
}

fn record_callback_failure(
    report: &mut StreamCompletionReport,
    hook: StreamCallbackHook,
    interceptor_index: usize,
    chunk_index: Option<usize>,
    kind: StreamCallbackFailureKind,
    diagnostic: &str,
) {
    report.callback_failure_count = report.callback_failure_count.saturating_add(1);
    if report.callback_failures.len() == MAX_RETAINED_CALLBACK_FAILURES {
        report.truncated_failure_details = report.truncated_failure_details.saturating_add(1);
        return;
    }
    let (diagnostic, diagnostic_truncated) = truncate_diagnostic(diagnostic);
    report.callback_failures.push(StreamCallbackFailure {
        hook,
        interceptor_index,
        chunk_index,
        kind,
        diagnostic,
        diagnostic_truncated,
    });
}

fn truncate_diagnostic(value: &str) -> (String, bool) {
    let mut chars = value.chars();
    let truncated: String = chars.by_ref().take(MAX_CALLBACK_DIAGNOSTIC_CHARS).collect();
    if chars.next().is_some() {
        (truncated, true)
    } else {
        (truncated, false)
    }
}

fn panic_diagnostic(payload: &(dyn Any + Send)) -> String {
    payload
        .downcast_ref::<String>()
        .cloned()
        .or_else(|| {
            payload
                .downcast_ref::<&'static str>()
                .map(|value| (*value).to_string())
        })
        .unwrap_or_else(|| "callback panicked with a non-string payload".into())
}

/// Parse an SSE stream into chat completion chunks.
///
/// The `text/event-stream` framing is the runtime's parser ([`sse::Decoder`]): events are dispatched when a
/// blank line completes them, an incomplete trailing event is discarded, and `data: [DONE]` ends the stream. Each
/// payload is decoded here, so a parse error keeps the offending chunk. A parse or connection error ends the stream and
/// releases the HTTP body at once.
#[cfg(test)]
fn parse_sse_stream<S>(byte_stream: S) -> impl Stream<Item = Result<ChatCompletionChunk>> + Send
where
    S: Stream<Item = std::result::Result<Bytes, timvw_rust_runtime::Error>> + Send + 'static,
{
    decode_frames(crate::sse_frames::frames(byte_stream))
}

/// Message of the error that ends a chat stream cut off before it completed.
const CHAT_STREAM_CUT_OFF: &str = "the stream ended before `data: [DONE]` or a finish_reason";

/// Decode the frames of a chat completion stream; the first error is the last item.
///
/// The stream completes at `data: [DONE]`, or at the end of the body once a chunk carried a
/// `finish_reason`; otherwise the end of the body yields [`Error::StreamConnection`].
fn decode_frames(
    frames: crate::BoxStream<
        'static,
        std::result::Result<crate::sse_frames::Frame, timvw_rust_runtime::Error>,
    >,
) -> impl Stream<Item = Result<ChatCompletionChunk>> + MaybeSend {
    use crate::sse_frames::Frame;

    futures::stream::unfold(Some((frames, false)), |state| async move {
        let (mut frames, mut finished) = state?;
        loop {
            match frames.next().await {
                Some(Ok(Frame::Event(event))) if event.data.is_empty() => {}
                Some(Ok(Frame::Event(event))) => {
                    return Some(match decode_chunk(&event.data) {
                        Ok(chunk) => {
                            finished |= chunk
                                .raw_response()
                                .choices
                                .iter()
                                .any(|choice| matches!(choice.finish_reason, Some(Some(_))));
                            (Ok(chunk), Some((frames, finished)))
                        }
                        // Dropping the frames drops the HTTP body.
                        Err(error) => (Err(error), None),
                    });
                }
                Some(Ok(Frame::Done)) => return None,
                Some(Err(error)) => {
                    return Some((
                        Err(Error::StreamConnection {
                            message: format!("Stream connection error: {error}"),
                        }),
                        None,
                    ));
                }
                None if finished => return None,
                None => {
                    return Some((
                        Err(Error::StreamConnection {
                            message: CHAT_STREAM_CUT_OFF.to_string(),
                        }),
                        None,
                    ));
                }
            }
        }
    })
    .fuse()
}

/// Decode one `data:` payload.
fn decode_chunk(data: &str) -> Result<ChatCompletionChunk> {
    let response: CreateChatCompletionStreamResponse =
        serde_json::from_str(data).map_err(|e| Error::StreamParsing {
            message: format!("Failed to deserialize chunk: {e}"),
            chunk: data.to_string(),
        })?;
    Ok(ChatCompletionChunk::new(response))
}

/// Parse a single SSE line into a chat completion chunk.
#[cfg(test)]
fn parse_sse_line(line: &str) -> Result<Option<ChatCompletionChunk>> {
    // Skip empty lines and comments
    if line.is_empty() || line.starts_with(':') {
        return Ok(None);
    }

    // Handle SSE format: "data: {json}"
    if let Some(data) = line.strip_prefix("data:") {
        let data = data.strip_prefix(' ').unwrap_or(data);
        // Check for [DONE] marker
        if data == "[DONE]" {
            return Ok(None);
        }

        return decode_chunk(data).map(Some);
    }

    // Ignore other SSE fields (event:, id:, retry:)
    Ok(None)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
    // Test hooks are plain `async fn` without `.await`, as users write them; the lint
    // exists only in newer Clippy, hence `unknown_lints` for the MSRV toolchain.
    #![allow(unknown_lints, clippy::unused_async_trait_impl)]
    use super::*;
    use std::sync::atomic::{AtomicBool, Ordering};

    struct PendingBody {
        bytes: Option<Bytes>,
        dropped: Arc<AtomicBool>,
    }

    impl Stream for PendingBody {
        type Item = std::result::Result<Bytes, timvw_rust_runtime::Error>;

        fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
            self.bytes
                .take()
                .map_or_else(|| Poll::Pending, |bytes| Poll::Ready(Some(Ok(bytes))))
        }
    }

    impl Drop for PendingBody {
        fn drop(&mut self) {
            self.dropped.store(true, Ordering::SeqCst);
        }
    }

    struct TerminalFlag(Arc<AtomicBool>);

    impl crate::interceptor::Interceptor for TerminalFlag {
        async fn on_stream_terminal(&self, _ctx: &StreamTerminalContext<'_>) -> Result<()> {
            self.0.store(true, Ordering::SeqCst);
            Ok(())
        }
    }

    #[tokio::test]
    async fn terminal_parser_result_releases_pending_http_body_immediately() {
        for (payload, expected) in [
            ("data: {not-json}\n\n", Some(StreamFailureKind::Parsing)),
            ("data: [DONE]\n\n", None),
        ] {
            let body_dropped = Arc::new(AtomicBool::new(false));
            let terminal_called = Arc::new(AtomicBool::new(false));
            let body = PendingBody {
                bytes: Some(Bytes::from(payload)),
                dropped: Arc::clone(&body_dropped),
            };
            let chat_stream = ChatCompletionStream {
                inner: Box::pin(parse_sse_stream(body)),
            };
            let mut interceptors = crate::interceptor::InterceptorChain::new();
            interceptors.add(Box::new(TerminalFlag(Arc::clone(&terminal_called))));
            let (mut stream, completion) = InterceptedStream::new_with_completion(
                chat_stream,
                Arc::new(interceptors),
                "chat".into(),
                "mock-model".into(),
                "{}".into(),
                (),
            )
            .unwrap();

            match expected {
                Some(_) => assert!(matches!(
                    stream.next().await.unwrap(),
                    Err(Error::StreamParsing { .. })
                )),
                None => assert!(stream.next().await.is_none()),
            }
            assert!(body_dropped.load(Ordering::SeqCst));
            assert!(stream.next().await.is_none());
            assert!(stream.next().await.is_none());

            let report = tokio::time::timeout(Duration::from_secs(1), completion.wait())
                .await
                .expect("terminal callback drain must finish")
                .unwrap();
            assert_eq!(
                report.outcome,
                expected.map_or(StreamOutcome::Completed, |kind| {
                    StreamOutcome::StreamFailed(StreamFailure { kind })
                })
            );
            assert!(terminal_called.load(Ordering::SeqCst));
        }
    }

    #[test]
    fn test_parse_sse_line_with_content() {
        let line = r#"data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1234567890,"model":"gpt-4","choices":[{"index":0,"delta":{"role":"assistant","content":"Hello"},"finish_reason":null}]}"#;

        let result = parse_sse_line(line).unwrap();
        assert!(result.is_some());

        let chunk = result.unwrap();
        assert_eq!(chunk.content(), Some("Hello"));
        assert_eq!(chunk.role(), Some("assistant"));
        assert_eq!(chunk.finish_reason(), None);
        assert_eq!(chunk.raw_response().choices[0].finish_reason, Some(None));
        assert!(!chunk.is_final());
        assert!(!crate::responses::ChatCompletionStreamResponseWrapper::new(
            chunk.raw_response().clone()
        )
        .is_finished());
    }

    #[test]
    fn test_parse_sse_line_with_missing_finish_reason() {
        let line = r#"data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1234567890,"model":"gpt-4","choices":[{"index":0,"delta":{}}]}"#;
        let chunk = parse_sse_line(line).unwrap().unwrap();
        assert_eq!(chunk.finish_reason(), None);
        assert_eq!(chunk.raw_response().choices[0].finish_reason, None);
        assert!(!chunk.is_final());
    }

    #[test]
    fn test_parse_sse_line_with_finish_reason() {
        let line = r#"data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1234567890,"model":"gpt-4","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":null}"#;
        let chunk = parse_sse_line(line).unwrap().unwrap();
        assert_eq!(chunk.finish_reason(), Some("stop"));
        assert!(chunk.is_final());
        assert!(crate::responses::ChatCompletionStreamResponseWrapper::new(
            chunk.raw_response().clone()
        )
        .is_finished());
    }

    #[test]
    fn test_finish_reason_helper_maps_all_supported_reasons() {
        for (wire, expected) in [
            ("stop", "stop"),
            ("length", "length"),
            ("tool_calls", "tool_calls"),
            ("content_filter", "content_filter"),
            ("function_call", "function_call"),
        ] {
            let event = serde_json::json!({
                "id": "chatcmpl-123",
                "object": "chat.completion.chunk",
                "created": 1,
                "model": "gpt-4",
                "choices": [{"index": 0, "delta": {}, "finish_reason": wire}],
            });
            let chunk = parse_sse_line(&format!("data: {event}")).unwrap().unwrap();
            assert_eq!(chunk.finish_reason(), Some(expected));
        }
    }

    #[test]
    fn test_new_finish_reason_is_unknown_and_still_final() {
        let chunk = parse_sse_line(
            r#"data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1,"model":"gpt-4","choices":[{"index":0,"delta":{"content":"kept"},"finish_reason":"brand_new_reason"}]}"#,
        )
        .unwrap()
        .unwrap();
        assert_eq!(chunk.finish_reason(), Some("unknown"));
        // A stream must not read on for a last chunk because the API found a new way to stop.
        assert!(chunk.is_final());
        assert_eq!(chunk.content(), Some("kept"));
    }

    #[test]
    fn test_new_role_is_unknown_not_absent() {
        let with_new_role = parse_sse_line(
            r#"data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1,"model":"gpt-4","choices":[{"index":0,"delta":{"role":"brand_new_role","content":"kept"},"finish_reason":null}]}"#,
        )
        .unwrap()
        .unwrap();
        assert_eq!(with_new_role.role(), Some("unknown"));
        assert_eq!(with_new_role.content(), Some("kept"));

        let without_role = parse_sse_line(
            r#"data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1,"model":"gpt-4","choices":[{"index":0,"delta":{"content":"kept"},"finish_reason":null}]}"#,
        )
        .unwrap()
        .unwrap();
        assert_eq!(without_role.role(), None);
    }

    #[test]
    fn test_final_audio_update_has_no_finish_reason() {
        let line = r#"data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1,"model":"gpt-4o-audio-preview","choices":[{"index":0,"delta":{"audio":{"expires_at":1700000000}}}]}"#;
        let chunk = parse_sse_line(line).unwrap().unwrap();
        assert_eq!(chunk.finish_reason(), None);
        assert_eq!(chunk.raw_response().choices[0].finish_reason, None);
        assert!(!chunk.is_final());
    }

    #[test]
    fn test_empty_choices_without_usage_are_not_finished() {
        let line = r#"data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1,"model":"gpt-4","choices":[]}"#;
        let chunk = parse_sse_line(line).unwrap().unwrap();
        assert_eq!(chunk.finish_reason(), None);
        assert!(!chunk.is_final());
    }

    #[test]
    fn test_usage_only_chunk_is_not_a_finished_choice() {
        let line = r#"data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1234567890,"model":"gpt-4","choices":[],"usage":{"prompt_tokens":3,"completion_tokens":4,"total_tokens":7}}"#;
        let chunk = parse_sse_line(line).unwrap().unwrap();
        assert_eq!(chunk.finish_reason(), None);
        assert!(!crate::responses::ChatCompletionStreamResponseWrapper::new(
            chunk.raw_response().clone()
        )
        .is_finished());
    }

    #[test]
    fn test_parse_sse_line_done_marker() {
        let line = "data: [DONE]";
        let result = parse_sse_line(line).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_sse_line_empty() {
        let line = "";
        let result = parse_sse_line(line).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_sse_line_comment() {
        let line = ": this is a comment";
        let result = parse_sse_line(line).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_sse_line_removes_only_one_space_after_colon() {
        let result = parse_sse_line("data:  {not-json}").unwrap_err();
        assert!(matches!(
            result,
            Error::StreamParsing { chunk, .. } if chunk == " {not-json}"
        ));
    }

    #[tokio::test]
    async fn test_parse_sse_stream_handles_cr_only_while_connection_is_open() {
        let bytes = Bytes::from(
            "data: {\"id\":\"chatcmpl-123\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"gpt-4\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"cr-only\"},\"finish_reason\":null}]}\r\r",
        );
        let source = futures::stream::iter(vec![Ok::<Bytes, timvw_rust_runtime::Error>(bytes)])
            .chain(futures::stream::pending());
        let mut stream = Box::pin(parse_sse_stream(source));

        let chunk = tokio::time::timeout(std::time::Duration::from_millis(250), stream.next())
            .await
            .expect("CR-only event should dispatch without waiting for more bytes")
            .unwrap()
            .unwrap();
        assert_eq!(chunk.content(), Some("cr-only"));
    }

    #[tokio::test]
    async fn test_parse_sse_stream_handles_split_crlf_before_lf_blank_line() {
        let json = r#"{"id":"chatcmpl-123","object":"chat.completion.chunk","created":1,"model":"gpt-4","choices":[{"index":0,"delta":{"content":"split"},"finish_reason":null}]}"#;
        let chunks = vec![
            Ok::<Bytes, timvw_rust_runtime::Error>(Bytes::from(format!("data: {json}\r"))),
            Ok(Bytes::from("\n")),
            Ok(Bytes::from("\n")),
        ];
        let source = futures::stream::iter(chunks).chain(futures::stream::pending());
        let mut stream = Box::pin(parse_sse_stream(source));

        let chunk = tokio::time::timeout(std::time::Duration::from_millis(250), stream.next())
            .await
            .expect("split CRLF followed by a blank LF line should dispatch promptly")
            .unwrap()
            .unwrap();
        assert_eq!(chunk.content(), Some("split"));
    }

    #[tokio::test]
    async fn test_parse_sse_stream_ignores_space_only_field_between_data_lines() {
        let bytes = Bytes::from(
            "data: {\n \ndata: \"id\":\"chatcmpl-123\",\ndata: \"object\":\"chat.completion.chunk\",\ndata: \"created\":1,\ndata: \"model\":\"gpt-4\",\ndata: \"choices\":[{\"index\":0,\"delta\":{\"content\":\"multiline\"},\"finish_reason\":null}]\ndata: }\n\n",
        );
        let mut stream = Box::pin(parse_sse_stream(futures::stream::iter(vec![Ok(bytes)])));

        let chunk = stream.next().await.unwrap().unwrap();
        assert_eq!(chunk.content(), Some("multiline"));
        // Neither `[DONE]` nor a finish_reason: the stream was cut off.
        assert!(matches!(
            stream.next().await.unwrap(),
            Err(Error::StreamConnection { .. })
        ));
        assert!(stream.next().await.is_none());
    }

    #[tokio::test]
    async fn test_parse_sse_stream_handles_fragmented_crlf_and_usage_only_events() {
        let first_event = format!(
            "data: {{\"id\":\"chatcmpl-123\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"gpt-4\",\"choices\":[{{\"index\":0,\"delta\":{{\"content\":{}}},\"finish_reason\":null}}]}}\r\n\r\n",
            serde_json::to_string("Hello 🦀").unwrap()
        );
        let crab = first_event
            .as_bytes()
            .windows(4)
            .position(|window| window == "🦀".as_bytes())
            .unwrap();
        let crlf = first_event
            .as_bytes()
            .windows(4)
            .position(|window| window == b"\r\n\r\n")
            .unwrap();
        let first_bytes = first_event.as_bytes();
        let fragmented = vec![
            Ok(Bytes::copy_from_slice(&first_bytes[..5]),),
            Ok(Bytes::copy_from_slice(&first_bytes[5..crab + 2]),),
            Ok(Bytes::copy_from_slice(&first_bytes[(crab + 2)..=crlf]),),
            Ok(Bytes::copy_from_slice(&first_bytes[crlf + 1..crlf + 2]),),
            Ok(Bytes::copy_from_slice(&first_bytes[crlf + 2..]),),
            Ok(Bytes::from(
                "data: {\"id\":\"chatcmpl-123\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"gpt-4\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\" done\"},\"finish_reason\":\"stop\"}]}\r\n\r\ndata: {\"id\":\"chatcmpl-123\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"gpt-4\",\"choices\":[],\"usage\":{\"prompt_tokens\":3,\"completion_tokens\":4,\"total_tokens\":7}}\r\n\r\ndata: [DONE]\r\n\r\n",
            )),
        ];

        let mut stream = Box::pin(parse_sse_stream(futures::stream::iter(fragmented)));
        let first = stream.next().await.unwrap().unwrap();
        let second = stream.next().await.unwrap().unwrap();
        let usage = stream.next().await.unwrap().unwrap();

        assert_eq!(first.content(), Some("Hello 🦀"));
        assert_eq!(second.content(), Some(" done"));
        assert_eq!(usage.raw_response().choices.as_slice(), &[]);
        assert_eq!(
            usage
                .raw_response()
                .usage
                .as_ref()
                .unwrap()
                .as_ref()
                .unwrap()
                .total_tokens,
            7
        );
        assert!(stream.next().await.is_none());
    }

    #[tokio::test]
    async fn test_parse_sse_stream_reports_malformed_json() {
        let bytes = Bytes::from("data: {not-json}\n\n");
        let mut stream = Box::pin(parse_sse_stream(futures::stream::iter(vec![Ok(bytes)])));

        assert!(matches!(
            stream.next().await.unwrap(),
            Err(Error::StreamParsing { .. })
        ));
        assert!(stream.next().await.is_none());
    }

    #[tokio::test]
    async fn test_parse_sse_stream_delivers_valid_event_before_parse_error() {
        let bytes = Bytes::from(
            "data: {\"id\":\"chatcmpl-123\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"gpt-4\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"kept\"},\"finish_reason\":null}]}\n\ndata: {not-json}\n\n",
        );
        let mut stream = Box::pin(parse_sse_stream(futures::stream::iter(vec![Ok(bytes)])));

        assert_eq!(
            stream.next().await.unwrap().unwrap().content(),
            Some("kept")
        );
        assert!(matches!(
            stream.next().await.unwrap(),
            Err(Error::StreamParsing { .. })
        ));
        assert!(stream.next().await.is_none());
        assert!(stream.next().await.is_none());
    }

    #[tokio::test]
    async fn test_parse_sse_stream_stops_at_done() {
        let bytes = Bytes::from(
            "data: {\"id\":\"chatcmpl-123\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"gpt-4\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"before\"},\"finish_reason\":null}]}\n\ndata: [DONE]\n\ndata: {\"id\":\"chatcmpl-123\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"gpt-4\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"after\"},\"finish_reason\":null}]}\n\n",
        );
        let mut stream = Box::pin(parse_sse_stream(futures::stream::iter(vec![Ok(bytes)])));

        assert_eq!(
            stream.next().await.unwrap().unwrap().content(),
            Some("before")
        );
        assert!(stream.next().await.is_none());
        assert!(stream.next().await.is_none());
    }

    #[tokio::test]
    async fn test_parse_sse_stream_discards_incomplete_trailing_event() {
        let bytes = Bytes::from(
            "data: {\"id\":\"chatcmpl-123\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"gpt-4\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"complete\"},\"finish_reason\":null}]}\n\ndata: {\"id\":\"chatcmpl-123\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"gpt-4\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"missing blank line\"},\"finish_reason\":null}]}\ndata: {partial",
        );
        let mut stream = Box::pin(parse_sse_stream(futures::stream::iter(vec![Ok(bytes)])));

        assert_eq!(
            stream.next().await.unwrap().unwrap().content(),
            Some("complete")
        );
        assert!(matches!(
            stream.next().await.unwrap(),
            Err(Error::StreamConnection { .. })
        ));
        assert!(stream.next().await.is_none());
        assert!(stream.next().await.is_none());
    }

    #[tokio::test]
    async fn completion_wait_reports_unavailable_if_worker_sender_closes() {
        let (sender, report) = watch::channel(None);
        let completion = StreamCompletion { report };
        drop(sender);
        assert_eq!(completion.wait().await, Err(CompletionUnavailable));
    }

    fn chunk_event(content: &str, finish_reason: Option<&str>) -> String {
        let finish_reason =
            finish_reason.map_or_else(|| "null".to_string(), |reason| format!("\"{reason}\""));
        format!(
            "data: {{\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"gpt-4\",\"choices\":[{{\"index\":0,\"delta\":{{\"content\":\"{content}\"}},\"finish_reason\":{finish_reason}}}]}}\n\n"
        )
    }

    async fn collect_outcome(body: String) -> (Vec<String>, Option<Error>) {
        let mut stream = Box::pin(parse_sse_stream(futures::stream::iter(vec![Ok(
            Bytes::from(body),
        )])));
        let mut contents = Vec::new();
        while let Some(item) = stream.next().await {
            match item {
                Ok(chunk) => contents.push(chunk.content().unwrap_or_default().to_string()),
                Err(error) => return (contents, Some(error)),
            }
        }
        (contents, None)
    }

    #[tokio::test]
    async fn chat_stream_completes_at_done_without_finish_reason() {
        let (contents, error) =
            collect_outcome(format!("{}data: [DONE]\n\n", chunk_event("a", None))).await;
        assert_eq!(contents, ["a"]);
        assert!(error.is_none());
    }

    #[tokio::test]
    async fn chat_stream_completes_at_eof_after_finish_reason() {
        let (contents, error) = collect_outcome(format!(
            "{}{}",
            chunk_event("a", None),
            chunk_event("b", Some("stop"))
        ))
        .await;
        assert_eq!(contents, ["a", "b"]);
        assert!(error.is_none());
    }

    #[tokio::test]
    async fn chat_stream_cut_off_before_done_or_finish_reason_is_an_error() {
        let (contents, error) = collect_outcome(chunk_event("a", None)).await;
        assert_eq!(contents, ["a"]);
        assert!(matches!(
            error,
            Some(Error::StreamConnection { message }) if message == CHAT_STREAM_CUT_OFF
        ));
    }
}