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
//! Streaming for any wire framing: the chat stream driver and vendor
//! frames.
//!
//! A streamed response arrives in *frames* of its wire framing: SSE events
//! ([`sse`](crate::sse)), NDJSON lines ([`ndjson`](crate::ndjson)), or the
//! messages of another framing an adapter frames itself. What turns frames
//! into chat stream events is the same loop for all of them, and so are the
//! rules a hand-written loop gets wrong, so they live here:
//!
//! - **The driver.** [`FramedChatStream`] runs an adapter's
//! [`ChatFrameDecoder`] over a stream of frames: it ends the stream after
//! the first error, runs the decoder's end-of-body or failure hook once,
//! classifies a failed read (a stream timeout stays a timeout), and never
//! polls the body after the stream ended.
//! - **Vendor frames.** [`VendorFrames`] surfaces frames of a type an
//! adapter does not model (`event: search_results`, an NDJSON line of an
//! unknown `type`) as response-level provider data under the adapter's
//! namespace, with one warning per frame type, so they are never decoded
//! as the adapter's own and never dropped.
//!
//! Framing the bytes stays with a framer ([`SseStream`](crate::sse::SseStream),
//! [`NdjsonStream`](crate::ndjson::NdjsonStream), or your own stream of
//! frames), and decoding the frames' data with each adapter: the helpers
//! frame, drive and surface, they do not interpret.
use Cow;
use ;
use fmt;
use Pin;
use ;
use ;
use ;
use Value;
/// An adapter's decoder for one streamed response: frames of type `F` in
/// (an [`SseEvent`](crate::sse::SseEvent), an NDJSON line), chat stream
/// events out. [`FramedChatStream`] drives it.
///
/// The decoder holds what only the adapter knows: its wire format, when its
/// response starts and ends, and its error classification. The driver holds
/// the loop every streaming adapter needs, and its guarantees:
///
/// - each frame goes to [`frame`](Self::frame), in order;
/// - the stream ends after the first error, from the decoder or from the
/// body: the items after it are dropped;
/// - when the body ends, [`end`](Self::end) runs; when reading or framing
/// it fails, [`fail`](Self::fail) runs, with the failure already
/// classified. At most one of them runs, once, and only while the decoder
/// is not done (it has yielded no error and [`is_done`](Self::is_done) is
/// `false`);
/// - the stream ends once the decoder is done, without waiting for the
/// body to close, and the body is never polled after the stream ended.
///
/// A decoder yields warnings and response-level provider data as they
/// arrive, even before its `ResponseStart`:
/// [`Prepared::finish_stream`](allama::adapter::chat::Prepared::finish_stream) puts
/// them after the start ([`start_first`](allama::adapter::chat::start_first)).
///
/// An SSE adapter implements `ChatFrameDecoder<SseEvent>`, and
/// [`SseChatStream`](crate::sse::SseChatStream) drives it.
///
/// Each method returns the items of one frame as a `Vec`, and this shape is
/// deliberate and stable. An empty `Vec` does not allocate, and a frame that
/// yields events was decoded from JSON anyway, so an `out: &mut Vec<_>` sink
/// parameter would save one small allocation per frame and cost every decoder
/// a harder signature: early returns become pushes, and a decoder that
/// forgets to push loses an error silently.
///
/// ```
/// use allama::{Error, Result, StreamEvent, StreamErrorKind};
/// use allama_http::TransportError;
/// use allama_http::framing::{ChatFrameDecoder, FramedChatStream};
/// use allama_http::ndjson::NdjsonStream;
/// use futures_util::{FutureExt, StreamExt, stream};
///
/// /// `{"text": ..}` lines, then `{"done": true}`.
/// struct Lines {
/// started: bool,
/// done: bool,
/// }
///
/// impl ChatFrameDecoder<String> for Lines {
/// fn frame(&mut self, line: String) -> Vec<Result<StreamEvent>> {
/// let json: serde_json::Value = match serde_json::from_str(&line) {
/// Ok(json) => json,
/// Err(error) => return vec![Err(Error::stream_decode(error.to_string()))],
/// };
/// let mut out = Vec::new();
/// if !self.started {
/// self.started = true;
/// out.push(Ok(StreamEvent::response_start(None, None)));
/// out.push(Ok(StreamEvent::block_start(0, allama::StreamBlockType::Text)));
/// }
/// if json["done"] == true {
/// self.done = true;
/// out.push(Ok(StreamEvent::block_stop(0)));
/// out.push(Ok(StreamEvent::ResponseStop));
/// } else {
/// out.push(Ok(StreamEvent::text_delta(0, json["text"].as_str().unwrap_or_default())));
/// }
/// out
/// }
///
/// fn end(&mut self) -> Vec<Result<StreamEvent>> {
/// let error = Error::stream(StreamErrorKind::Incomplete, "the stream ended early");
/// vec![Err(error.authored().with_provider("lines"))]
/// }
///
/// fn fail(&mut self, error: Error) -> Vec<Result<StreamEvent>> {
/// vec![Err(error.with_provider("lines"))]
/// }
///
/// fn is_done(&self) -> bool {
/// self.done
/// }
/// }
///
/// let body = stream::iter([Ok::<_, TransportError>(
/// &b"{\"text\":\"Hel\"}\n{\"text\":\"lo\"}\n{\"done\":true}\n"[..],
/// )]);
/// let lines = NdjsonStream::new(body);
/// let stream = FramedChatStream::new(lines, Lines { started: false, done: false });
/// let events: Vec<_> = stream.collect().now_or_never().unwrap();
/// assert_eq!(events.len(), 6);
/// assert!(matches!(events[5], Ok(StreamEvent::ResponseStop)));
/// ```
/// A chat stream decoded from a response's frames by an adapter's
/// [`ChatFrameDecoder`], with the driver guarantees the decoder trait
/// lists.
///
/// `frames` is any stream of `Result<frame, error>`: an
/// [`SseStream`](crate::sse::SseStream), an
/// [`NdjsonStream`](crate::ndjson::NdjsonStream), or a framer of your own.
/// It is unboxed and `Send` (for a `Send` body); box it into a
/// [`ChatStream`](allama::ChatStream) with
/// [`Prepared::finish_stream`](allama::adapter::chat::Prepared::finish_stream):
///
/// ```ignore
/// let lines = NdjsonStream::new(response.into_body()).max_line_size(max_stream_event_size);
/// Ok(prepared.finish_stream(FramedChatStream::new(lines, StreamDecoder::new(request_id))))
/// ```
// The driver never pins its fields: it polls the frames through
// `Pin::new`, which needs them `Unpin` itself.
/// Surfaces vendor frames: stream frames of a type an adapter does not
/// model.
///
/// Endpoints and proxies add frames to standard streams: a named SSE event
/// (`event: search_results`), an NDJSON line of a `type` the API does not
/// define. An adapter never decodes them as its own and never drops them:
/// [`surface`](Self::surface) turns each one into events, as it arrives,
/// and [`finish`](Self::finish) completes them when the response ends.
///
/// # Events
///
/// - The first frame of a type is preceded by one [`Warning`]
/// (`WarningKind::Other`, `Subject::Response`, with the provider name).
/// - Each frame yields a
/// [`ResponseProviderData`](StreamEvent::ResponseProviderData) event
/// under the adapter's namespace and the frame type, holding that frame's
/// payload alone, as a one-element array: a live consumer sees each
/// payload once, as it arrives, in constant work per frame.
/// - [`finish`](Self::finish), called by the decoder just before its
/// `ResponseStop`, yields one more `ResponseProviderData` event holding
/// the whole array, in arrival order, of every type that arrived more
/// than once. [`ProviderData::merge`] replaces a value by key, so a
/// collector that merges the events ends with every payload of every
/// type: the collected response's provider data holds the full arrays.
///
/// Before 2026-10-07 each event carried the whole array so far, which made a
/// stream with a vendor frame per chunk quadratic in time and in what a
/// recording holds. An adapter that forgets [`finish`](Self::finish) keeps
/// only the last payload of a repeated type in its collected response.
///
/// A vendor frame never starts the response. Yield the returned events as
/// they come, also before `ResponseStart`:
/// [`Prepared::finish_stream`](allama::adapter::chat::Prepared::finish_stream) holds
/// them until the start ([`start_first`](allama::adapter::chat::start_first)).
/// `allama_conformance::stream_frames::assert_unknown_stream_frames_surfaced`
/// checks the result.
///
/// ```
/// use allama::{StreamEvent, WarningKind};
/// use allama_http::framing::VendorFrames;
///
/// let mut frames = VendorFrames::new("demo", "openai-compat:demo");
/// let first = frames.surface("search_results", r#"{"url":"https://a"}"#);
/// assert!(matches!(
/// &first[0],
/// StreamEvent::Warning { warning, .. } if warning.kind == WarningKind::Other
/// ));
/// let second = frames.surface("search_results", "not json");
/// let StreamEvent::ResponseProviderData { provider_data, .. } = &second[0] else {
/// panic!("{second:?}")
/// };
/// assert_eq!(
/// provider_data.get_raw("openai-compat:demo", "search_results"),
/// Some(&serde_json::json!(["not json"])),
/// );
///
/// // Before `ResponseStop`: the whole array of each repeated type.
/// let Some(StreamEvent::ResponseProviderData { provider_data, .. }) = frames.finish() else {
/// panic!()
/// };
/// assert_eq!(
/// provider_data.get_raw("openai-compat:demo", "search_results"),
/// Some(&serde_json::json!([{"url": "https://a"}, "not json"])),
/// );
/// ```
/// Classifies a framer's failure.
type ErrorMap<E> = ;
/// The loop of [`FramedChatStream`]: a decoder and the items it yielded
/// that the stream has not.
pub