ante-llm 0.4.2

Streaming LLM client for Anthropic, OpenAI, Gemini and Chat Completions servers, from the Ante coding agent
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
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
// Copyright 2026 Antigma Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{
    future::Future,
    pin::Pin,
    time::{Duration, Instant},
};

use anyhow::Result;
use async_trait::async_trait;
use eventsource_stream::{Event, EventStreamError, Eventsource};
use futures_util::{Stream, StreamExt as _};
use reqwest::{
    StatusCode,
    header::{ACCEPT, CONTENT_ENCODING, CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue},
};
use serde::{Serialize, de::DeserializeOwned};
use tokio_util::bytes::Bytes;
use tracing::{debug, info};

use crate::auth::{AuthedClient, Token};
use crate::compress::{compress, encoding_for};
use crate::error::{LlmError, LlmErrorKind};
pub use crate::retry_policy::RetryPolicy;
use crate::stream_driver::{StreamMapper, drive_stream};
use crate::streaming::collect;
use crate::{
    retry_policy::retry_after_header,
    types::{
        ChatRequest, ChatResponse, ChatResponseStream, DEFAULT_STREAM_IDLE_TIMEOUT_SECS, ModelSpec,
    },
};

/// Trait for LLM clients that can send messages and stream responses
#[async_trait]
pub trait ChatClient: Send + Sync {
    /// Send one request and get a streaming response.
    /// The returned stream owns its idle timeout at the transport boundary,
    /// including activity that produces no normalized events. The open is
    /// bounded there too: a provider that accepts the request and never
    /// answers fails at the transport's deadline, so a caller races the open
    /// against cancellation alone.
    async fn stream_chat(&self, request: ChatRequest) -> Result<ChatResponseStream, LlmError>;

    /// Send one request and get the complete response: the stream, collected.
    /// Every call rides the one streaming transport, so a provider keeps no
    /// second response decoder, and the stream's checks — the idle timeout,
    /// the terminal stop — hold for complete responses too.
    async fn chat(&self, request: ChatRequest) -> Result<ChatResponse, LlmError> {
        collect(self.stream_chat(request).await?, |_| {}).await.into_result()
    }

    async fn list_models(&self) -> Result<Vec<ModelSpec>, LlmError> {
        Err(LlmError::message(
            LlmErrorKind::InvalidRequest,
            "model listing is not supported by this provider",
        ))
    }
}

/// [`ChatClient::chat`], retried once without `tool_choice` when
/// the provider rejects the parameter, whether the rejection arrives as
/// the HTTP status or inside the stream. Callers that forbid tool calls
/// already constrain the reply through their instruction text, so
/// `tool_choice` is a best-effort hint there, not a correctness guarantee.
pub async fn chat_with_tool_choice_fallback(
    client: &dyn ChatClient,
    request: ChatRequest,
) -> Result<ChatResponse, LlmError> {
    // The conversation rides as shared `Arc`s, so the retry clone is cheap.
    let retry =
        request.tool_choice.is_some().then(|| ChatRequest { tool_choice: None, ..request.clone() });
    match (client.chat(request).await, retry) {
        (Err(err), Some(retry)) if err.is_tool_choice_rejection() => {
            info!("provider rejected tool_choice, retrying once without it: {err}");
            client.chat(retry).await
        }
        (result, _) => result,
    }
}

/// A client for sending HTTP requests to LLM providers
#[derive(Debug, Clone)]
pub struct Client {
    base_url: String,
    auth: AuthedClient,
    /// Headers sent on every request, the WebSocket handshake included.
    headers: HeaderMap,
    retry_policy: RetryPolicy,
    stream_idle_timeout: Duration,
}

/// Raw buffered response returned after the retry policy has run.
#[derive(Debug)]
pub struct ClientResponse {
    /// The HTTP status.
    pub status: StatusCode,
    /// The response headers.
    pub headers: HeaderMap,
    /// The whole body.
    pub body: String,
}

pub(crate) type RawSseStream = Pin<Box<dyn Stream<Item = Result<Event, LlmError>> + Send>>;

/// Result of opening an SSE endpoint after retrying the initial HTTP request.
pub(crate) enum ClientSseResponse {
    Stream(RawSseStream),
    Error(ClientResponse),
}

/// A [`Client`] bound to one provider's error classifier. Every method
/// returns typed values with errors already classified. The classifier for
/// non-success HTTP bodies is the only provider-specific part: chunk decoding
/// rides on the chunk type's `Deserialize` impl, and semantic stream mapping
/// stays in [`StreamMapper`].
#[derive(Clone)]
pub(crate) struct ProviderClient {
    transport: Client,
    /// Classify a non-success HTTP response body. A plain `fn`: every provider
    /// classifier is stateless.
    classify: fn(ClientResponse) -> LlmError,
}

impl ProviderClient {
    pub(crate) fn new(transport: Client, classify: fn(ClientResponse) -> LlmError) -> Self {
        Self { transport, classify }
    }

    /// The client underneath, for a transport that runs its own protocol.
    pub(crate) fn raw(&self) -> &Client {
        &self.transport
    }

    pub(crate) fn base_url(&self) -> &str {
        self.transport.base_url()
    }

    pub(crate) fn stream_idle_timeout(&self) -> Duration {
        self.transport.stream_idle_timeout()
    }

    /// POST `body` and decode the JSON response as `Resp`. A non-success
    /// response is classified by the provider; a malformed success body is a
    /// decode failure (via `From<serde_json::Error>`).
    pub(crate) async fn post_json<Resp, Req>(
        &self,
        path: &str,
        body: &Req,
    ) -> Result<Resp, LlmError>
    where
        Resp: DeserializeOwned,
        Req: Serialize + ?Sized,
    {
        let resp = self.transport.post(path, body).await?;
        self.decode_json(resp)
    }

    /// GET with `query` and decode the JSON response as `Resp`.
    pub(crate) async fn get_json<Resp, Q>(&self, path: &str, query: &Q) -> Result<Resp, LlmError>
    where
        Resp: DeserializeOwned,
        Q: Serialize + ?Sized,
    {
        let resp = self.transport.get(path, query).await?;
        self.decode_json(resp)
    }

    /// POST an SSE request and decode each event's data as JSON into `T`.
    /// A non-success initial response is classified by the provider.
    pub(crate) async fn post_chunks<T, Req>(
        &self,
        path: &str,
        body: &Req,
    ) -> Result<impl Stream<Item = Result<T, LlmError>> + Send + Unpin + 'static, LlmError>
    where
        T: DeserializeOwned + Send + 'static,
        Req: Serialize + ?Sized,
    {
        let response = self.transport.post_sse(path, body).await?;
        match response {
            ClientSseResponse::Stream(stream) => Ok(decode_chunks(stream)),
            ClientSseResponse::Error(resp) => Err(self.classify_error(resp)),
        }
    }

    /// POST an SSE request and drive the decoded chunks through `mapper`: the
    /// whole streaming pipeline in one call. The chunk type is the mapper's
    /// [`StreamMapper::Raw`].
    pub(crate) async fn post_stream<Req, M>(
        &self,
        path: &str,
        body: &Req,
        mapper: M,
    ) -> Result<ChatResponseStream, LlmError>
    where
        Req: Serialize + ?Sized,
        M: StreamMapper,
        M::Raw: DeserializeOwned,
    {
        let chunks = self.post_chunks(path, body).await?;
        Ok(drive_stream(chunks, mapper))
    }

    fn decode_json<Resp: DeserializeOwned>(&self, resp: ClientResponse) -> Result<Resp, LlmError> {
        if !resp.status.is_success() {
            return Err(self.classify_error(resp));
        }
        Ok(serde_json::from_str(&resp.body)?)
    }

    /// Classify a non-success response, carrying the transport-level
    /// `Retry-After` out on the error. Stamped here — the one seam every
    /// classified response passes through — so provider classifiers keep
    /// owning body semantics only, never headers.
    fn classify_error(&self, resp: ClientResponse) -> LlmError {
        let retry_after = retry_after_header(&resp.headers);
        let mut err = (self.classify)(resp);
        err.detail.retry_after = err.detail.retry_after.or(retry_after);
        err
    }
}

/// Decode SSE events as JSON chunks. The `[DONE]` sentinel ends the stream,
/// so a server that holds the connection open after it cannot hang the call.
/// Keepalives and empty data carry no payload: they are dropped after the
/// transport has counted them as activity.
fn decode_chunks<T>(
    events: RawSseStream,
) -> impl Stream<Item = Result<T, LlmError>> + Send + Unpin + 'static
where
    T: DeserializeOwned + Send + 'static,
{
    events
        .take_while(|raw| std::future::ready(!matches!(raw, Ok(event) if event.data == "[DONE]")))
        .filter_map(|raw| {
            std::future::ready(match raw {
                Ok(raw) => decode_json_event(&raw),
                Err(err) => Some(Err(err)),
            })
        })
}

/// Decode one SSE event's data as JSON, ignoring keepalives.
/// Invalid JSON in a data event remains a malformed-response error.
fn decode_json_event<T: DeserializeOwned>(raw: &Event) -> Option<Result<T, LlmError>> {
    if raw.event == "keepalive" || raw.data.is_empty() {
        return None;
    }
    Some(serde_json::from_str(&raw.data).map_err(|err| {
        LlmError::malformed_response(format!(
            "failed to parse SSE data as JSON for event {}: {err}",
            raw.event
        ))
    }))
}

/// Bound silence between transport reads, before any event filtering.
/// A timeout terminates the stream with a reconnectable error.
pub fn with_idle_timeout<S, T>(raw: S, timeout: Duration) -> impl Stream<Item = Result<T, LlmError>>
where
    S: Stream<Item = Result<T, LlmError>> + Unpin,
{
    futures_util::stream::unfold(Some(raw), move |raw| async move {
        let mut raw = raw?;
        match tokio::time::timeout(timeout, raw.next()).await {
            Err(_elapsed) => Some((
                Err(LlmError::unexpected_eof(format!(
                    "stream idle for {}s with no data",
                    timeout.as_secs()
                ))),
                None,
            )),
            Ok(Some(item)) => Some((item, Some(raw))),
            Ok(None) => None,
        }
    })
}

/// Time out raw reads so SSE comments and keepalives count as activity even
/// when the event parser or provider decoder emits no event for them.
fn sse_events<S, B>(bytes: S, idle_timeout: Duration) -> RawSseStream
where
    S: Stream<Item = Result<B, LlmError>> + Send + Unpin + 'static,
    B: AsRef<[u8]> + Send + 'static,
{
    let stream = with_idle_timeout(bytes, idle_timeout).eventsource().map(|sse| match sse {
        // Event data can contain model output and tool arguments. Keep it out
        // of tracing, which may be exported even in debug builds.
        Ok(raw) => Ok(raw),
        Err(EventStreamError::Transport(err)) => Err(err),
        Err(err) => Err(LlmError::malformed_response(format!("SSE decode error: {err}"))),
    });
    Box::pin(stream)
}

impl Client {
    /// A client for the endpoint at `base_url`, sending through `auth`.
    pub fn new(base_url: impl Into<String>, auth: AuthedClient) -> Self {
        Self {
            base_url: base_url.into(),
            auth,
            headers: HeaderMap::new(),
            retry_policy: RetryPolicy::default(),
            stream_idle_timeout: Duration::from_secs(DEFAULT_STREAM_IDLE_TIMEOUT_SECS),
        }
    }

    /// Headers sent on every request, such as a provider's beta flags. The
    /// credential is placed by `auth`, not here.
    pub fn with_headers(mut self, headers: HeaderMap) -> Self {
        self.headers = headers;
        self
    }

    /// Add `name` unless the caller already set it.
    pub(crate) fn with_default_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
        self.headers.entry(name).or_insert(value);
        self
    }

    /// Customize the retry policy for this client.
    pub fn with_retry_policy(mut self, retry_policy: RetryPolicy) -> Self {
        self.retry_policy = retry_policy;
        self
    }

    /// How long a stream may take to open, and stay silent between reads,
    /// before the call fails.
    pub fn with_stream_idle_timeout(mut self, timeout: Duration) -> Self {
        self.stream_idle_timeout = timeout;
        self
    }

    /// The idle timeout this client was built with.
    pub fn stream_idle_timeout(&self) -> Duration {
        self.stream_idle_timeout
    }

    pub(crate) fn base_url(&self) -> &str {
        &self.base_url
    }

    /// The auth layer, for a transport that cannot go through reqwest's
    /// `RequestBuilder` (a WebSocket handshake) and runs its protocol itself.
    pub(crate) fn auth(&self) -> &AuthedClient {
        &self.auth
    }

    /// The provider's extra headers with `token` placed as the provider
    /// places its credential, for the same transports.
    pub(crate) fn transport_headers(&self, token: Option<&Token>) -> Result<HeaderMap, LlmError> {
        let mut headers = self.headers.clone();
        if let Some(token) = token {
            headers.extend(self.auth.headers(token)?);
        }
        Ok(headers)
    }

    /// POST `body` as JSON to `path` on this endpoint, with the same
    /// credential, headers and retries as a model call, and buffer the whole
    /// response. The whole call has one deadline: the stream idle timeout.
    pub async fn post<Req>(&self, path: &str, body: &Req) -> Result<ClientResponse, LlmError>
    where
        Req: Serialize + ?Sized,
    {
        self.send_json(path, body, None, read_response).await
    }

    /// GET `path` on this endpoint, bounded like [`Self::post`].
    pub async fn get<Q>(&self, path: &str, query: &Q) -> Result<ClientResponse, LlmError>
    where
        Q: Serialize + ?Sized,
    {
        let url = self.url(path);
        self.send_with_retry(|http| http.get(url.clone()).query(query), &url, read_response).await
    }

    pub(crate) async fn post_sse<Req>(
        &self,
        path: &str,
        body: &Req,
    ) -> Result<ClientSseResponse, LlmError>
    where
        Req: Serialize + ?Sized,
    {
        self.send_json(path, body, Some("text/event-stream"), |resp| async move {
            if resp.status().is_success() {
                let stream = sse_events(
                    resp.bytes_stream().map(|result| result.map_err(LlmError::sse_transport)),
                    self.stream_idle_timeout,
                );
                Ok(ClientSseResponse::Stream(stream))
            } else {
                read_response(resp).await.map(ClientSseResponse::Error)
            }
        })
        .await
    }

    /// POST `body` as JSON and hand the answer to `read`. The body is
    /// serialized once, so every retry sends the same bytes, and compressed
    /// when the endpoint accepts it. Each answer writes the one record of
    /// what was sent and whether the provider took it.
    async fn send_json<Req, H, Fut, T>(
        &self,
        path: &str,
        body: &Req,
        accept: Option<&str>,
        mut read: H,
    ) -> Result<T, LlmError>
    where
        Req: Serialize + ?Sized,
        H: FnMut(reqwest::Response) -> Fut,
        Fut: Future<Output = std::result::Result<T, reqwest::Error>>,
    {
        let started = Instant::now();
        let url = self.url(path);
        let json =
            serde_json::to_vec(body).map_err(|err| LlmError::request_conversion(err.into()))?;
        let json_bytes = json.len();
        let compressed = encoding_for(&url)
            .and_then(|encoding| Some((compress(&json, encoding)?, encoding.name())));
        // `json` moves in here either way, so a compressed body frees it before
        // the send rather than holding it across every attempt.
        let (upload, encoding) =
            compressed.map_or((json, None), |(bytes, encoding)| (bytes, Some(encoding)));
        let upload = Bytes::from(upload);
        self.send_with_retry(
            |http| {
                let mut request = http.post(url.clone()).header(CONTENT_TYPE, "application/json");
                if let Some(encoding) = encoding {
                    request = request.header(CONTENT_ENCODING, encoding);
                }
                if let Some(accept) = accept {
                    request = request.header(ACCEPT, accept);
                }
                request.body(upload.clone())
            },
            &url,
            |resp| {
                debug!(
                    encoding = encoding.unwrap_or("identity"),
                    json_bytes,
                    upload_bytes = upload.len(),
                    http_status = resp.status().as_u16(),
                    elapsed_ms = started.elapsed().as_millis() as u64,
                    "llm request answered"
                );
                read(resp)
            },
        )
        .await
    }

    /// Run one request shape under the retry policy; a send or read failure
    /// that outlasts it is classified by [`classify_send_failure`]. Each
    /// attempt rides the auth layer, which answers a rejected credential with
    /// one recovery and one resend; its own failures (no credential, a
    /// refresh that fails) arrive classified by its source.
    ///
    /// Every call gets one deadline, the idle timeout: the headers, an error
    /// body, a buffered body, an OAuth refresh and the backoff between
    /// attempts all spend it, and a hit ends the call because no budget is
    /// left for another attempt. A reqwest request timeout would cut a
    /// stream's body too, so none is set here.
    async fn send_with_retry<F, H, Fut, T>(
        &self,
        mut make_req: F,
        url: &str,
        mut handle_success: H,
    ) -> Result<T, LlmError>
    where
        F: FnMut(&reqwest::Client) -> reqwest::RequestBuilder,
        H: FnMut(reqwest::Response) -> Fut,
        Fut: Future<Output = std::result::Result<T, reqwest::Error>>,
    {
        within(self.stream_idle_timeout, async {
            let mut attempt: u32 = 0;
            loop {
                let send_result =
                    self.auth.send(|http| make_req(http).headers(self.headers.clone())).await?;

                // Classify the attempt: terminal arms `return`; transient arms yield a
                // `Retry`. The `attempt < max_count` guards mean an exhausted budget
                // falls through to the terminal arm, which returns the same error.
                let retry = match send_result {
                    // A `Retry-After` longer than this layer's delay cap is not
                    // truncated and hammered (that would re-hit a provider that
                    // asked for room): the guard fails, the response classifies
                    // below, and the wait rides out on the error for the
                    // caller-level retry to honor.
                    Ok(resp)
                        if self.retry_policy.should_retry_status(resp.status())
                            && attempt < self.retry_policy.max_count
                            && retry_after_header(resp.headers())
                                .is_none_or(|wait| wait <= self.retry_policy.max_delay) =>
                    {
                        let status = resp.status();
                        Retry {
                            delay: retry_after_header(resp.headers())
                                .unwrap_or_else(|| self.retry_policy.next_delay(attempt)),
                            reason: format!("HTTP {status}"),
                        }
                    }
                    Ok(resp) => match handle_success(resp).await {
                        Ok(value) => {
                            if attempt > 0 {
                                info!(url = %url, retries = attempt, "request succeeded after retries");
                            }
                            return Ok(value);
                        }
                        Err(err)
                            if self.retry_policy.should_retry_error(&err)
                                && attempt < self.retry_policy.max_count =>
                        {
                            Retry {
                                delay: self.retry_policy.next_delay(attempt),
                                reason: format!("response read error ({err:?})"),
                            }
                        }
                        Err(err) => return Err(classify_send_failure(&self.retry_policy, &err)),
                    },
                    Err(err)
                        if self.retry_policy.should_retry_error(&err)
                            && attempt < self.retry_policy.max_count =>
                    {
                        Retry {
                            delay: self.retry_policy.next_delay(attempt),
                            reason: format!("request error ({err:?})"),
                        }
                    }
                    Err(err) => return Err(classify_send_failure(&self.retry_policy, &err)),
                };

                info!(
                    url = %url,
                    attempt,
                    delay_ms = retry.delay.as_millis() as u64,
                    reason = %retry.reason,
                    "retrying request"
                );
                tokio::time::sleep(retry.delay).await;
                attempt = attempt.saturating_add(1);
            }
        })
        .await?
    }

    fn url(&self, path: &str) -> String {
        format!("{}/{}", self.base_url.trim_end_matches('/'), path.trim_start_matches('/'))
    }
}

/// A transient outcome from one send attempt: back off for `delay`, then retry.
/// `reason` is used only for the log line.
struct Retry {
    delay: Duration,
    reason: String,
}

/// Run `fut`, or fail with [`LlmErrorKind::Timeout`] once `bound` has passed.
pub(crate) async fn within<T>(
    bound: Duration,
    fut: impl Future<Output = T>,
) -> Result<T, LlmError> {
    tokio::time::timeout(bound, fut).await.map_err(|_| {
        LlmError::message(LlmErrorKind::Timeout, format!("no response within {}s", bound.as_secs()))
    })
}

async fn read_response(
    resp: reqwest::Response,
) -> std::result::Result<ClientResponse, reqwest::Error> {
    let status = resp.status();
    let headers = resp.headers().clone();
    let body = resp.text().await?;
    Ok(ClientResponse { status, headers, body })
}

/// Terminal classification for a send or body read that failed with no
/// response body to classify. A failure class the policy retries is a network
/// fault whose inline budget ran out — [`LlmError::transport`], transient, so
/// the caller-level retry picks up where this layer stopped. Anything else
/// (builder error, redirect loop) is deterministic and surfaces verbatim.
fn classify_send_failure(policy: &RetryPolicy, err: &reqwest::Error) -> LlmError {
    if policy.should_retry_error(err) {
        LlmError::transport(err.to_string())
    } else {
        LlmError::message(LlmErrorKind::Unknown, err.to_string())
    }
}

#[cfg(test)]
mod retry_tests;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::auth::test_support::StubSource;
    use crate::compress::Encoding;
    use crate::test_support::unauthenticated;
    use crate::types::{Message, ToolChoice, Usage};
    use async_trait::async_trait;
    use reqwest::header::HeaderValue;

    #[tokio::test(start_paused = true)]
    async fn idle_timeout_yields_unexpected_eof() {
        // A stream that never yields: only the idle timer can resolve.
        let raw = futures_util::stream::pending::<Result<(), LlmError>>();
        let mut stream = Box::pin(with_idle_timeout(raw, Duration::from_secs(17)));

        let err = stream.next().await.expect("timeout should yield an item").unwrap_err();
        assert_eq!(err.kind, LlmErrorKind::UnexpectedEof);
        assert!(err.to_string().contains("17s"), "configured timeout should be reported: {err}");
    }

    #[tokio::test(start_paused = true)]
    async fn sse_keepalives_reset_idle_timeout_before_filtering() {
        let bytes = futures_util::stream::iter([
            ": heartbeat\n\n",
            "event: keepalive\n\n",
            "event: keepalive\ndata: still working\n\n",
            "data:\n\n",
            "data: {\"text\":\"pong\"}\n\n",
        ])
        .then(|chunk| async move {
            tokio::time::sleep(Duration::from_secs(10)).await;
            Ok(chunk)
        })
        .chain(futures_util::stream::pending());
        let stream = sse_events(Box::pin(bytes), Duration::from_secs(17));
        let mut decoded = decode_chunks::<serde_json::Value>(stream);

        let start = tokio::time::Instant::now();
        assert_eq!(decoded.next().await.unwrap().unwrap(), serde_json::json!({"text": "pong"}));
        assert_eq!(start.elapsed(), Duration::from_secs(50));
        let err = decoded.next().await.unwrap().unwrap_err();
        assert_eq!(err.kind, LlmErrorKind::UnexpectedEof);
        assert_eq!(start.elapsed(), Duration::from_secs(67));
    }

    #[tokio::test(start_paused = true)]
    async fn done_sentinel_ends_the_stream_on_a_held_connection() {
        // A server that keeps the connection open after `[DONE]` must not
        // hang the stream until the idle timeout.
        let bytes = futures_util::stream::iter([
            Ok::<_, LlmError>("data: {\"text\":\"pong\"}\n\n"),
            Ok("data: [DONE]\n\n"),
        ])
        .chain(futures_util::stream::pending());
        let stream = sse_events(Box::pin(bytes), Duration::from_secs(17));
        let mut decoded = decode_chunks::<serde_json::Value>(stream);

        let start = tokio::time::Instant::now();
        assert_eq!(decoded.next().await.unwrap().unwrap(), serde_json::json!({"text": "pong"}));
        assert!(decoded.next().await.is_none(), "`[DONE]` ends the stream");
        assert_eq!(start.elapsed(), Duration::ZERO, "no wait for the idle timeout");
    }

    #[tokio::test]
    async fn sse_payloads_are_not_logged_even_when_decoding_fails() {
        use tracing::instrument::WithSubscriber;

        let log = tempfile::NamedTempFile::new().unwrap();
        let subscriber = tracing_subscriber::fmt()
            .with_max_level(tracing::Level::TRACE)
            .with_ansi(false)
            .without_time()
            .with_writer(log.reopen().unwrap())
            .finish();
        async {
            let bytes = futures_util::stream::iter([
                Ok("data: {\"text\":\"private-model-output\"}\n\n"),
                Ok("data: {\"argument\":\"private-tool-argument\"\n\n"),
                Ok("data: [DONE]\n\n"),
            ]);
            let stream = sse_events(bytes, Duration::from_secs(17));
            let mut decoded = decode_chunks::<serde_json::Value>(stream);
            assert_eq!(
                decoded.next().await.unwrap().unwrap(),
                serde_json::json!({"text": "private-model-output"})
            );
            let err = decoded.next().await.unwrap().unwrap_err();
            assert_eq!(err.kind, LlmErrorKind::MalformedResponse);
            assert!(err.to_string().contains("EOF while parsing an object"));
            assert!(decoded.next().await.is_none());
        }
        .with_subscriber(subscriber)
        .await;

        let output = std::fs::read_to_string(log.path()).unwrap();
        assert!(!output.contains("private-model-output"), "model output leaked: {output}");
        assert!(!output.contains("private-tool-argument"), "tool argument leaked: {output}");
        assert!(!output.contains("sse ["), "per-event logging returned: {output}");
    }

    #[tokio::test]
    async fn invalid_sse_utf8_is_malformed_response() {
        let bytes = futures_util::stream::iter([Ok(vec![0, 159])]);
        let err = sse_events(bytes, Duration::from_secs(17)).next().await.unwrap().unwrap_err();
        assert_eq!(err.kind, LlmErrorKind::MalformedResponse);
        assert!(err.retry_delay(1).is_none());
    }

    /// Rejects any request carrying `tool_choice` the way OpenCode zen's Go
    /// models do, recording each request's `tool_choice`; succeeds without it.
    #[derive(Default)]
    struct ToolChoicePickyClient {
        seen: std::sync::Mutex<Vec<Option<ToolChoice>>>,
    }

    #[async_trait]
    impl ChatClient for ToolChoicePickyClient {
        async fn chat(&self, request: ChatRequest) -> Result<ChatResponse, LlmError> {
            self.seen.lock().unwrap().push(request.tool_choice.clone());
            if request.tool_choice.is_some() {
                return Err(LlmError::http(
                    LlmErrorKind::InvalidRequest,
                    StatusCode::BAD_REQUEST,
                    Some("invalid_request_error".to_string()),
                    "Upstream request failed: [invalid_request_error] only `\"auto\"` is \
                     supported for `tool_choice`. `\"none\"`, `\"required\"`, and named \
                     function choices are not currently supported"
                        .to_string(),
                ));
            }
            Ok(ChatResponse {
                message: Message::model("ok".to_string()),
                stop_reason: None,
                usage: Usage::default(),
            })
        }

        async fn stream_chat(&self, _request: ChatRequest) -> Result<ChatResponseStream, LlmError> {
            panic!("stream_chat should not be called");
        }
    }

    #[tokio::test]
    async fn tool_choice_rejection_retries_once_without_the_parameter() {
        let client = ToolChoicePickyClient::default();
        let request = ChatRequest { tool_choice: Some(ToolChoice::Forbid), ..Default::default() };

        let response = chat_with_tool_choice_fallback(&client, request).await.expect("fallback");

        assert_eq!(response.message.content.as_text(), "ok");
        let seen = client.seen.lock().unwrap();
        assert_eq!(seen.as_slice(), [Some(ToolChoice::Forbid), None]);
    }

    #[tokio::test]
    async fn unrelated_invalid_request_is_not_retried() {
        struct InvalidParamClient {
            calls: std::sync::Mutex<u32>,
        }

        #[async_trait]
        impl ChatClient for InvalidParamClient {
            async fn chat(&self, _request: ChatRequest) -> Result<ChatResponse, LlmError> {
                *self.calls.lock().unwrap() += 1;
                Err(LlmError::http(
                    LlmErrorKind::InvalidRequest,
                    StatusCode::BAD_REQUEST,
                    None,
                    "Invalid assistant message: content or tool_calls must be set".to_string(),
                ))
            }

            async fn stream_chat(
                &self,
                _request: ChatRequest,
            ) -> Result<ChatResponseStream, LlmError> {
                panic!("stream_chat should not be called");
            }
        }

        let client = InvalidParamClient { calls: std::sync::Mutex::new(0) };
        let request = ChatRequest { tool_choice: Some(ToolChoice::Forbid), ..Default::default() };

        let err = chat_with_tool_choice_fallback(&client, request).await.unwrap_err();

        assert_eq!(err.kind, LlmErrorKind::InvalidRequest);
        assert_eq!(*client.calls.lock().unwrap(), 1, "only a tool_choice rejection may retry");
    }

    #[tokio::test]
    async fn local_tool_choice_validation_error_is_not_retried() {
        struct ConversionFailingClient {
            calls: std::sync::Mutex<u32>,
        }

        #[async_trait]
        impl ChatClient for ConversionFailingClient {
            async fn chat(&self, _request: ChatRequest) -> Result<ChatResponse, LlmError> {
                *self.calls.lock().unwrap() += 1;
                // A conversion failure means the provider never saw the
                // request; the fallback resending it would mask a caller bug.
                Err(LlmError::request_conversion(anyhow::anyhow!(
                    "tool_choice requires a tool call but the request has no tools"
                )))
            }

            async fn stream_chat(
                &self,
                _request: ChatRequest,
            ) -> Result<ChatResponseStream, LlmError> {
                panic!("stream_chat should not be called");
            }
        }

        let client = ConversionFailingClient { calls: std::sync::Mutex::new(0) };
        let request = ChatRequest { tool_choice: Some(ToolChoice::Required), ..Default::default() };

        let err = chat_with_tool_choice_fallback(&client, request).await.unwrap_err();

        assert_eq!(err.kind, LlmErrorKind::InvalidRequest);
        assert_eq!(
            *client.calls.lock().unwrap(),
            1,
            "local validation errors have no provider origin and must not retry"
        );
    }

    /// A rejected credential is recovered and the request resent inside one
    /// attempt of the retry ladder, so the ladder sees only the final answer.
    #[tokio::test]
    async fn a_rejected_credential_is_recovered_within_the_attempt() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::header("authorization", "Bearer old"))
            .respond_with(wiremock::ResponseTemplate::new(401))
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_string("ok"))
            .mount(&server)
            .await;
        let base_url = format!("http://api.anthropic.com:{}", server.address().port());
        let http = reqwest::Client::builder()
            .no_proxy()
            .resolve("api.anthropic.com", *server.address())
            .build()
            .unwrap();
        let client = Client::new(
            base_url,
            AuthedClient::new(
                http,
                crate::auth::Placement::Bearer,
                std::sync::Arc::new(StubSource::new(["old", "new"])),
            ),
        );

        let body = serde_json::json!({"content": "hello".repeat(4000)});
        let expected = compress(&serde_json::to_vec(&body).unwrap(), Encoding::Gzip).unwrap();
        let response = client.post("/v1/messages", &body).await.expect("recovered");

        assert_eq!(response.status, StatusCode::OK);
        let requests = server.received_requests().await.unwrap();
        assert_eq!(requests.len(), 2);
        for request in requests {
            assert_eq!(request.headers[CONTENT_ENCODING], "gzip");
            assert_eq!(request.body, expected);
        }
    }

    #[test]
    fn classify_error_stamps_retry_after_from_headers() {
        fn classify(resp: ClientResponse) -> LlmError {
            LlmError::http(LlmErrorKind::RateLimited, resp.status, None, "slow down".to_string())
        }
        let transport = unauthenticated("https://api.example.test/v1");
        let provider = ProviderClient::new(transport, classify);

        let mut headers = HeaderMap::new();
        headers.insert("retry-after", HeaderValue::from_static("30"));
        let err = provider.classify_error(ClientResponse {
            status: StatusCode::TOO_MANY_REQUESTS,
            headers,
            body: String::new(),
        });
        assert_eq!(err.detail.retry_after, Some(std::time::Duration::from_secs(30)));

        let err = provider.classify_error(ClientResponse {
            status: StatusCode::TOO_MANY_REQUESTS,
            headers: HeaderMap::new(),
            body: String::new(),
        });
        assert_eq!(err.detail.retry_after, None, "no header means no server-mandated wait");
    }

    /// A client for a provider that accepts every request and never answers
    /// it, with a 100ms idle bound and the default inline retries, which the
    /// bound must preclude. The server rides along so it outlives the call.
    async fn never_answering_client() -> (wiremock::MockServer, Client) {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_delay(Duration::from_secs(30)))
            .mount(&server)
            .await;
        let client =
            unauthenticated(server.uri()).with_stream_idle_timeout(Duration::from_millis(100));
        (server, client)
    }

    // A buffered request against a provider that accepts and never answers
    // times out at the idle bound, transient so the caller-level retry
    // understands it, and without a second attempt, which the deadline has
    // no budget for.
    #[tokio::test]
    async fn buffered_request_times_out_at_the_idle_bound() {
        let (server, client) = never_answering_client().await;

        let started = std::time::Instant::now();
        let err = client
            .post("/chat", &serde_json::json!({}))
            .await
            .expect_err("a response that never comes must time out");
        assert!(started.elapsed() < Duration::from_secs(5), "bounded by the idle timeout");
        assert_eq!(err.kind, LlmErrorKind::Timeout, "{err}");
        assert_eq!(server.received_requests().await.unwrap().len(), 1, "no second attempt");
    }

    // A stream's open against the same provider is bounded the same way.
    #[tokio::test]
    async fn stream_open_times_out_at_the_idle_bound() {
        let (server, client) = never_answering_client().await;

        let started = std::time::Instant::now();
        let err = client
            .post_sse("/chat", &serde_json::json!({}))
            .await
            .err()
            .expect("a stream that never opens must time out");
        assert!(started.elapsed() < Duration::from_secs(5), "bounded by the idle timeout");
        assert_eq!(err.kind, LlmErrorKind::Timeout, "{err}");
        assert_eq!(server.received_requests().await.unwrap().len(), 1, "no second attempt");
    }

    // A slow 503 starts an inline retry, and the retry runs under the same
    // deadline, not a fresh one: the second attempt is cut at the call's
    // bound, and no third attempt starts.
    #[tokio::test]
    async fn inline_retries_run_under_the_call_deadline() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(wiremock::ResponseTemplate::new(503).set_delay(Duration::from_secs(1)))
            .up_to_n_times(2)
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_delay(Duration::from_secs(30)))
            .mount(&server)
            .await;
        let client = unauthenticated(server.uri())
            .with_retry_policy(RetryPolicy {
                base_delay: Duration::from_millis(10),
                max_delay: Duration::from_millis(10),
                ..RetryPolicy::default()
            })
            .with_stream_idle_timeout(Duration::from_millis(1500));

        let started = std::time::Instant::now();
        let err = client
            .post("/chat", &serde_json::json!({}))
            .await
            .expect_err("the retry must be cut at the call's bound");
        assert!(started.elapsed() < Duration::from_secs(3), "one bound for the whole call");
        assert_eq!(err.kind, LlmErrorKind::Timeout, "{err}");
        assert_eq!(server.received_requests().await.unwrap().len(), 2, "one retry, no third");
    }

    // A rejection whose error body never arrives is bounded the same way: the
    // headers opened the response, the body is what the attempt still owes.
    #[tokio::test]
    async fn stream_open_error_body_times_out_at_the_idle_bound() {
        use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base_url = format!("http://{}", listener.local_addr().unwrap());
        tokio::spawn(async move {
            let (mut socket, _) = listener.accept().await.unwrap();
            let _ = socket.read(&mut [0_u8; 4096]).await;
            let headers = b"HTTP/1.1 500 Internal Server Error\r\n\
                Content-Type: application/json\r\nContent-Length: 100\r\n\r\n";
            socket.write_all(headers).await.unwrap();
            tokio::time::sleep(Duration::from_secs(30)).await;
        });
        let client = unauthenticated(base_url).with_stream_idle_timeout(Duration::from_millis(100));

        let err = tokio::time::timeout(
            Duration::from_secs(5),
            client.post_sse("/chat", &serde_json::json!({})),
        )
        .await
        .expect("bounded by the idle timeout")
        .err()
        .expect("an error body that never comes must time out");
        assert_eq!(err.kind, LlmErrorKind::Timeout, "{err}");
    }
}