ante-llm 0.4.2

Streaming LLM client for Anthropic, OpenAI, Gemini and Chat Completions servers, from the Ante coding agent
Documentation
// Copyright 2026 Antigma Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Streaming driver shared by every LLM provider: the producer side, raw wire
//! events -> shared [`StreamEvent`] vocabulary. [`crate::streaming`] is
//! the consumer side (`StreamEvent` -> `ChatResponse`).
//!
//! Each provider supplies only a [`StreamMapper`]; [`drive_stream`] owns the
//! termination policy. Idle timeouts belong at the transport boundary, before
//! SSE parsing or WebSocket control-frame handling can swallow keepalives.

use crate::error::LlmError;
use crate::types::{ChatResponseStream, StreamEvent};
use futures_util::{Stream, StreamExt};
use std::collections::VecDeque;

/// Translates one provider's raw wire stream into the shared [`StreamEvent`]
/// vocabulary. The only provider-specific part of streaming. `map` is sync:
/// making it async would force the per-event future to be `Send` for no gain.
pub(crate) trait StreamMapper: Send + 'static {
    /// Providers decode their wire events before handing them to the driver, so
    /// the trait only needs `Send + 'static` here.
    type Raw: Send + 'static;
    /// Map one raw event into zero or more normalized events. Stateful. May
    /// classify a provider error *event* (e.g. `response.failed`) into an
    /// [`LlmError`].
    fn map(&mut self, raw: Self::Raw) -> Result<Vec<StreamEvent>, LlmError>;
    /// Trailing events when the raw stream ends: a mapper with buffered state
    /// flushes it here (e.g. a `MessageStop` synthesized from an already-seen
    /// finish reason). Called at most once, on raw EOF; a stream ended by a
    /// mid-stream `MessageStop` never reaches it. The driver, not the mapper,
    /// fails a stream that still has no `MessageStop` after this flush.
    fn on_end(&mut self) -> Result<Vec<StreamEvent>, LlmError> {
        Ok(Vec::new())
    }
}

enum Phase {
    Streaming,
    /// The raw stream reached EOF and `on_end` flushed. Drain `buf`; never
    /// pull raw again. No `MessageStop` has been handed out yet.
    Draining,
    /// A `MessageStop` or an error ended the stream; nothing more to hand out.
    Done,
}

/// Drive a provider's raw wire stream into a [`ChatResponseStream`].
///
/// Hands out mapped events, pulls the next raw event, and runs
/// `mapper.on_end()` once when the raw stream completes. `MessageStop` is
/// terminal on every wire (nothing is pulled after it); an end without one
/// surfaces as `UnexpectedEof`, not a complete response.
pub(crate) fn drive_stream<M, S>(raw: S, mapper: M) -> ChatResponseStream
where
    M: StreamMapper,
    S: Stream<Item = Result<M::Raw, LlmError>> + Send + Unpin + 'static,
{
    let init = (raw, mapper, VecDeque::<StreamEvent>::new(), Phase::Streaming);
    let s = futures_util::stream::unfold(
        init,
        move |(mut raw, mut mapper, mut buf, mut phase)| async move {
            loop {
                // 1. Hand out anything already mapped before pulling more.
                if let Some(ev) = buf.pop_front() {
                    if matches!(ev, StreamEvent::MessageStop { .. }) {
                        // MessageStop is terminal on every wire: drop anything
                        // buffered behind it and stop pulling raw, so a server
                        // that holds the connection open after the final event
                        // cannot hang the stream.
                        buf.clear();
                        phase = Phase::Done;
                    }
                    return Some((Ok(ev), (raw, mapper, buf, phase)));
                }
                match phase {
                    Phase::Streaming => {}
                    // 2. Buffer drained after the stream ended.
                    Phase::Done => return None,
                    Phase::Draining => {
                        // The stream ended without its terminal MessageStop: a
                        // premature close (quiet EOF, proxy cut). Fail it so a
                        // truncated transcript is never passed off as a
                        // complete response.
                        phase = Phase::Done;
                        return Some((
                            Err(LlmError::unexpected_eof("stream ended before completion")),
                            (raw, mapper, buf, phase),
                        ));
                    }
                }
                // 3. Pull the next raw event; transport reads own the idle timeout.
                match raw.next().await {
                    // Idle timeout or producer-classified stream error: the
                    // consumer stops on the first Err.
                    Some(Err(err)) => return Some((Err(err), (raw, mapper, buf, phase))),
                    Some(Ok(item)) => match mapper.map(item) {
                        Ok(evs) => buf.extend(evs), // empty => loop pulls next raw
                        Err(e) => return Some((Err(e), (raw, mapper, buf, phase))), // classified err
                    },
                    None => match mapper.on_end() {
                        // called once: Streaming -> Draining
                        Ok(evs) => {
                            buf.extend(evs);
                            phase = Phase::Draining;
                        }
                        Err(e) => return Some((Err(e), (raw, mapper, buf, Phase::Done))),
                    },
                }
            }
        },
    );
    Box::pin(s)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::with_idle_timeout;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::Duration;

    /// A `StreamMapper` over a `Vec`-backed raw stream. `Raw` is the exact list
    /// of events `map` should emit, so tests control the per-raw output and the
    /// trailing `on_end` output directly.
    struct FakeMapper {
        on_end_events: Vec<StreamEvent>,
        on_end_calls: Arc<AtomicUsize>,
    }

    impl FakeMapper {
        fn new() -> (Self, Arc<AtomicUsize>) {
            let on_end_calls = Arc::new(AtomicUsize::new(0));
            (Self { on_end_events: Vec::new(), on_end_calls: on_end_calls.clone() }, on_end_calls)
        }

        fn with_on_end(events: Vec<StreamEvent>) -> (Self, Arc<AtomicUsize>) {
            let on_end_calls = Arc::new(AtomicUsize::new(0));
            (Self { on_end_events: events, on_end_calls: on_end_calls.clone() }, on_end_calls)
        }
    }

    impl StreamMapper for FakeMapper {
        type Raw = Vec<StreamEvent>;
        fn map(&mut self, raw: Vec<StreamEvent>) -> Result<Vec<StreamEvent>, LlmError> {
            Ok(raw)
        }
        fn on_end(&mut self) -> Result<Vec<StreamEvent>, LlmError> {
            self.on_end_calls.fetch_add(1, Ordering::SeqCst);
            Ok(self.on_end_events.clone())
        }
    }

    fn raw_stream(
        items: Vec<Result<Vec<StreamEvent>, LlmError>>,
    ) -> impl Stream<Item = Result<Vec<StreamEvent>, LlmError>> + Send + Unpin + 'static {
        futures_util::stream::iter(items)
    }

    fn text(s: &str) -> StreamEvent {
        StreamEvent::TextDelta(s.to_string())
    }

    fn stop() -> StreamEvent {
        StreamEvent::MessageStop { usage: Default::default(), stop_reason: None }
    }

    async fn collect(mut stream: ChatResponseStream) -> Vec<Result<StreamEvent, LlmError>> {
        let mut out = Vec::new();
        while let Some(ev) = stream.next().await {
            out.push(ev);
        }
        out
    }

    /// (a) A multi-event `map` result is drained in order before the next raw.
    #[tokio::test]
    async fn multi_event_map_drains_in_order() {
        let (mapper, _) = FakeMapper::new();
        let raw = raw_stream(vec![Ok(vec![text("a"), text("b"), text("c"), stop()])]);
        let out = collect(drive_stream(raw, mapper)).await;

        let texts: Vec<String> = out
            .iter()
            .filter_map(|ev| match ev.as_ref().unwrap() {
                StreamEvent::TextDelta(t) => Some(t.clone()),
                StreamEvent::MessageStop { .. } => None,
                other => panic!("expected TextDelta or MessageStop, got {other:?}"),
            })
            .collect();
        assert_eq!(texts, vec!["a", "b", "c"]);
        assert!(matches!(out.last().unwrap().as_ref().unwrap(), StreamEvent::MessageStop { .. }));
    }

    #[tokio::test(start_paused = true)]
    async fn unmapped_events_keep_the_stream_alive_until_transport_silence() {
        let (mapper, _) = FakeMapper::new();
        let raw = futures_util::stream::iter([vec![], vec![], vec![], vec![text("pong")]])
            .then(|events| async move {
                tokio::time::sleep(Duration::from_secs(10)).await;
                Ok(events)
            })
            .chain(futures_util::stream::pending());
        let raw = with_idle_timeout(Box::pin(raw), Duration::from_secs(17));
        let mut stream = drive_stream(Box::pin(raw), mapper);

        let start = tokio::time::Instant::now();
        assert!(
            matches!(stream.next().await.unwrap().unwrap(), StreamEvent::TextDelta(text) if text == "pong")
        );
        assert_eq!(start.elapsed(), Duration::from_secs(40));
        let err = stream.next().await.unwrap().unwrap_err();
        assert_eq!(err.kind, crate::error::LlmErrorKind::UnexpectedEof);
        assert_eq!(start.elapsed(), Duration::from_secs(57));
    }

    /// (c) `on_end` emits its events then the stream ends, and is called exactly
    /// once (no double-emit on a premature close).
    #[tokio::test]
    async fn on_end_emits_once_then_terminates() {
        let (mapper, calls) = FakeMapper::with_on_end(vec![StreamEvent::ContentStop, stop()]);
        let raw = raw_stream(vec![Ok(vec![text("a")])]);
        let out = collect(drive_stream(raw, mapper)).await;

        assert!(matches!(out[0].as_ref().unwrap(), StreamEvent::TextDelta(t) if t == "a"));
        assert!(matches!(out[1].as_ref().unwrap(), StreamEvent::ContentStop));
        assert!(matches!(out[2].as_ref().unwrap(), StreamEvent::MessageStop { .. }));
        assert_eq!(out.len(), 3, "on_end events must appear exactly once");
        assert_eq!(calls.load(Ordering::SeqCst), 1, "on_end must be called exactly once");
    }

    /// (e) A raw stream `Err` is propagated. (A consumer that keeps polling
    /// past it reaches EOF, which — having no MessageStop — also fails; the
    /// real collector stops at the first Err.)
    #[tokio::test]
    async fn stream_error_is_propagated() {
        let (mapper, _) = FakeMapper::new();
        let raw = raw_stream(vec![Ok(vec![text("a")]), Err(LlmError::transport("boom"))]);
        let out = collect(drive_stream(raw, mapper)).await;

        assert!(matches!(out[0].as_ref().unwrap(), StreamEvent::TextDelta(t) if t == "a"));
        let err = out[1].as_ref().unwrap_err();
        assert_eq!(err.kind, crate::error::LlmErrorKind::Transport);
        assert!(err.to_string().contains("boom"));
        let err = out[2].as_ref().unwrap_err();
        assert_eq!(err.kind, crate::error::LlmErrorKind::UnexpectedEof);
        assert_eq!(out.len(), 3);
    }

    /// (f) A stream that ends without a terminal MessageStop is a premature
    /// close: the events stream out, then the driver fails the stream instead
    /// of passing the truncated transcript off as a complete response.
    #[tokio::test]
    async fn stream_without_message_stop_fails_as_unexpected_eof() {
        let (mapper, _) = FakeMapper::new();
        let raw = raw_stream(vec![Ok(vec![text("partial")])]);
        let out = collect(drive_stream(raw, mapper)).await;

        assert!(matches!(out[0].as_ref().unwrap(), StreamEvent::TextDelta(t) if t == "partial"));
        let err = out[1].as_ref().unwrap_err();
        assert_eq!(err.kind, crate::error::LlmErrorKind::UnexpectedEof);
        assert_eq!(out.len(), 2, "the missing-stop error must be yielded exactly once");
    }

    /// (g) MessageStop is terminal: the driver stops pulling raw events, so a
    /// server that holds the connection open after the final event (observed
    /// on a Gemini bridge speaking the Anthropic wire) cannot hang the stream.
    #[tokio::test]
    async fn driver_stops_pulling_after_message_stop() {
        let (mapper, _) = FakeMapper::new();
        let raw = raw_stream(vec![Ok(vec![text("hi"), stop()])])
            .chain(futures_util::stream::pending::<Result<Vec<StreamEvent>, LlmError>>());

        let out = tokio::time::timeout(
            std::time::Duration::from_secs(1),
            collect(drive_stream(Box::pin(raw), mapper)),
        )
        .await
        .expect("driver kept pulling after MessageStop instead of ending the stream");

        assert!(matches!(out[0].as_ref().unwrap(), StreamEvent::TextDelta(t) if t == "hi"));
        assert!(matches!(out[1].as_ref().unwrap(), StreamEvent::MessageStop { .. }));
        assert_eq!(out.len(), 2);
    }
}