agentsdk 0.6.2

An open-source Rust library for building AI-powered applications, inspired by the Vercel AI SDK. It provides a robust, type-safe, and easy-to-use interface for interacting with various Large Language Models (LLMs).
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
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
//! This module provides the client for interacting with the AI providers.
//! It is a thin wrapper around the `reqwest` crate.

use crate::core::utils::join_url;
use crate::error::{Error, Result};
use futures::Stream;
use futures::StreamExt;
use reqwest;
use reqwest::IntoUrl;
use reqwest_eventsource::{Event, RequestBuilderExt};
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::OnceLock;
use std::time::Duration;

/// Configuration for retry behavior on API requests.
#[derive(Debug, Clone)]
struct RetryConfig {
    /// Maximum number of retry attempts (default: 3).
    max_retries: u32,

    /// Initial wait time before first retry (default: 500ms).
    initial_wait: Duration,

    /// Maximum wait time between retries (default: 20 seconds).
    max_wait: Duration,
    /// Whether to add jitter to backoff (default: true).

    #[allow(dead_code)]
    /// Whether to add jitter to backoff.
    /// turn on the `jitter` feature to use (pulls in `fastrand`).
    use_jitter: bool,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_retries: 3,
            initial_wait: Duration::from_millis(500),
            max_wait: Duration::from_secs(20),
            use_jitter: true,
        }
    }
}

/// Shared `reqwest::Client` for non-streaming requests (has a 180s response timeout).
#[allow(dead_code)]
static HTTP_CLIENT: OnceLock<reqwest::Client> = OnceLock::new();

/// Shared `reqwest::Client` for streaming requests (no response timeout).
#[allow(dead_code)]
static HTTP_STREAMING_CLIENT: OnceLock<reqwest::Client> = OnceLock::new();

// TODO: reasoning for two different clients in connection pooling is not
// working during tests. make sure to fix this later.
//
/// Returns the shared HTTP client for non-streaming requests.
#[allow(dead_code)]
#[cfg(not(feature = "test-access"))]
fn get_client() -> &'static reqwest::Client {
    HTTP_CLIENT.get_or_init(|| {
        reqwest::Client::builder()
            .pool_max_idle_per_host(32)
            .pool_idle_timeout(Duration::from_secs(120))
            .tcp_keepalive(Duration::from_secs(30))
            .connect_timeout(Duration::from_secs(5))
            .timeout(Duration::from_secs(180))
            .build()
            .expect("Failed to build shared HTTP client")
    })
}

/// Returns the shared HTTP client for streaming requests.
/// Identical to [`get_client`] except `.timeout()` is intentionally omitted for streaming.
#[allow(dead_code)]
#[cfg(not(feature = "test-access"))]
fn get_streaming_client() -> &'static reqwest::Client {
    HTTP_STREAMING_CLIENT.get_or_init(|| {
        reqwest::Client::builder()
            .pool_max_idle_per_host(32)
            .pool_idle_timeout(Duration::from_secs(120))
            .tcp_keepalive(Duration::from_secs(30))
            .connect_timeout(Duration::from_secs(5))
            .build()
            .expect("Failed to build shared HTTP streaming client")
    })
}

#[cfg(feature = "test-access")]
fn get_client() -> reqwest::Client {
    reqwest::Client::new()
}

#[cfg(feature = "test-access")]
fn get_streaming_client() -> reqwest::Client {
    reqwest::Client::new()
}

/// Checks if a status code is retryable.
fn is_retryable_status(status: reqwest::StatusCode) -> bool {
    matches!(
        status,
        reqwest::StatusCode::TOO_MANY_REQUESTS
            | reqwest::StatusCode::BAD_GATEWAY
            | reqwest::StatusCode::SERVICE_UNAVAILABLE
            | reqwest::StatusCode::GATEWAY_TIMEOUT
    )
}

/// Parses the Retry-After header to get the wait duration.
fn parse_retry_after(headers: &reqwest::header::HeaderMap) -> Option<Duration> {
    headers
        .get(reqwest::header::RETRY_AFTER)
        .and_then(|v| v.to_str().ok())
        .and_then(|s| {
            // Try parsing as seconds (integer)
            if let Ok(seconds) = s.parse::<u64>() {
                return Some(Duration::from_secs(seconds));
            }
            None
        })
}

/// Calculates the next wait duration with exponential backoff and optional jitter.
fn calculate_backoff(
    retry_count: u32,
    config: &RetryConfig,
    retry_after: Option<Duration>,
) -> Duration {
    // If server provides Retry-After, respect it
    if let Some(duration) = retry_after {
        return duration.min(config.max_wait);
    }

    // Calculate exponential backoff: initial_wait * 2^retry_count
    let backoff = config
        .initial_wait
        .saturating_mul(2_u32.saturating_pow(retry_count));
    let backoff = backoff.min(config.max_wait);

    // Add jitter to prevent thundering herd (±10% of backoff time).
    // Requires the `jitter` feature (pulls in `fastrand`).
    #[cfg(feature = "jitter")]
    if config.use_jitter {
        let jitter_pct = fastrand::i64(-100..=100) as f64 / 1000.0; // Range: -0.1 to +0.1
        let jitter_ms = (backoff.as_millis() as f64 * jitter_pct) as i64;

        return if jitter_ms >= 0 {
            backoff.saturating_add(Duration::from_millis(jitter_ms as u64))
        } else {
            backoff.saturating_sub(Duration::from_millis((-jitter_ms) as u64))
        };
    }

    backoff
}

/// Shared retry logic for HTTP requests.
///
/// This function handles:
/// - Exponential backoff with configurable limits
/// - Jitter to prevent thundering herd
/// - Retry-After header parsing
/// - Retryable HTTP status codes (429, 502, 503, 504)
/// - Retryable transport errors (timeout, connection failure)
/// - Request body reconstruction on each retry
async fn retry_request<F, T>(
    url: reqwest::Url,
    method: reqwest::Method,
    headers: reqwest::header::HeaderMap,
    query_params: Vec<(&str, &str)>,
    body_fn: F,
    config: RetryConfig,
) -> Result<T>
where
    F: Fn() -> reqwest::Body,
    T: DeserializeOwned + std::fmt::Debug,
{
    let client = get_client();
    let mut retry_count = 0;

    loop {
        let body = body_fn();

        let resp = match client
            .request(method.clone(), url.clone())
            .headers(headers.clone())
            .query(&query_params)
            .body(body)
            .send()
            .await
        {
            Ok(r) => r,
            // retry none HTTP-level errors (timeout, connection refused)
            Err(e) if (e.is_timeout() || e.is_connect()) && retry_count < config.max_retries => {
                let wait_time = calculate_backoff(retry_count, &config, None);
                retry_count += 1;
                log::warn!(
                    "Request failed with retryable error (attempt {}/{}): {}. Retrying after {:?}...",
                    retry_count,
                    config.max_retries + 1,
                    e,
                    wait_time
                );
                tokio::time::sleep(wait_time).await;
                continue;
            }
            Err(e) => {
                log::error!("Request failed: {e}");
                return Err(Error::ApiError {
                    status_code: e.status(),
                    details: e.to_string(),
                });
            }
        };

        let status = resp.status();
        let response_headers = resp.headers().clone();
        let resp_text = resp.text().await.map_err(|e| Error::ApiError {
            status_code: e.status(),
            details: format!("Failed to read response: {e}"),
        })?;

        if status.is_success() {
            log::debug!("Request succeeded on attempt {}", retry_count + 1);
            return serde_json::from_str(&resp_text).map_err(|e| Error::ApiError {
                status_code: Some(status),
                details: format!("Failed to parse response: {e}"),
            });
        }

        // Check if error is retryable and we have retries left
        if is_retryable_status(status) && retry_count < config.max_retries {
            // Parse Retry-After header if present
            let retry_after = parse_retry_after(&response_headers);
            let wait_time = calculate_backoff(retry_count, &config, retry_after);
            retry_count += 1;

            log::warn!(
                "Request failed with status {} (attempt {}/{}). Retrying after {:?}...",
                status,
                retry_count,
                config.max_retries + 1,
                wait_time
            );

            tokio::time::sleep(wait_time).await;
            continue;
        }

        // Non-retryable error or exhausted retries
        if retry_count >= config.max_retries {
            log::error!(
                "Request failed after {} retries with status {}: {}",
                retry_count + 1,
                status,
                resp_text
            );
        } else {
            log::error!("Request failed with non-retryable status {status}: {resp_text}");
        }

        return Err(Error::ApiError {
            status_code: Some(status),
            details: resp_text,
        });
    }
}

/// Merges a typed request body with provider-level and request-level body fields.
/// Request-level fields take priority over provider-level fields.
#[allow(dead_code)]
pub(crate) fn merge_body<T>(
    request: &T,
    provider_level: Option<&serde_json::Map<String, serde_json::Value>>,
    request_level: Option<&serde_json::Map<String, serde_json::Value>>,
) -> Result<reqwest::Body>
where
    T: Serialize,
{
    let body_bytes = serde_json::to_vec(request)
        .map_err(|e| Error::Other(format!("Failed to serialize request body: {e}")))?;
    let mut json: serde_json::Value = serde_json::from_slice(&body_bytes)
        .map_err(|e| Error::Other(format!("Failed to parse request body as JSON: {e}")))?;

    let map = json
        .as_object_mut()
        .ok_or_else(|| Error::Other("Request body must serialize to a JSON object".to_string()))?;

    if let Some(provider_overrides) = provider_level {
        map.extend(provider_overrides.clone());
    }

    if let Some(request_overrides) = request_level {
        map.extend(request_overrides.clone());
    }

    let body_bytes = serde_json::to_vec(&json)
        .map_err(|e| Error::Other(format!("Failed to encode request body: {e}")))?;

    Ok(reqwest::Body::from(body_bytes))
}

/// Merges default, provider-level, and request-level headers.
/// Request-level headers take priority over provider-level headers,
/// which take priority over the provider defaults.
#[allow(dead_code)]
pub(crate) fn merge_headers(
    mut default_headers: reqwest::header::HeaderMap,
    provider_level: Option<&HashMap<String, String>>,
    request_level: Option<&HashMap<String, String>>,
) -> Result<reqwest::header::HeaderMap> {
    if let Some(provider_headers) = provider_level {
        let provider_headers = reqwest::header::HeaderMap::try_from(provider_headers)
            .map_err(|e| Error::InvalidInput(format!("Invalid headers: {}", e)))?;
        default_headers.extend(provider_headers);
    }

    if let Some(request_headers) = request_level {
        let request_headers = reqwest::header::HeaderMap::try_from(request_headers)
            .map_err(|e| Error::InvalidInput(format!("Invalid headers: {}", e)))?;
        default_headers.extend(request_headers);
    }

    Ok(default_headers)
}

#[allow(dead_code)]
pub(crate) trait LanguageModelClient {
    type Response: DeserializeOwned + std::fmt::Debug + Clone;
    type StreamEvent: DeserializeOwned + std::fmt::Debug + Clone;

    fn path(&self) -> String;
    fn method(&self) -> reqwest::Method;
    fn query_params(&self) -> Vec<(&str, &str)>;
    fn body(&self) -> Result<reqwest::Body>;
    fn headers(&self) -> Result<reqwest::header::HeaderMap>;

    async fn send(&self, base_url: impl IntoUrl) -> Result<Self::Response> {
        let url = join_url(base_url, &self.path())?;

        let body_bytes = {
            let raw = self.body()?;
            match raw.as_bytes() {
                Some(bytes) => bytes.to_vec(),
                None => {
                    log::warn!("Request body is not retryable (streaming body)");
                    vec![]
                }
            }
        };

        let method = self.method();
        let query_params = self.query_params();
        let config = RetryConfig::default();

        retry_request(
            url,
            method,
            self.headers()?,
            query_params,
            move || reqwest::Body::from(body_bytes.clone()),
            config,
        )
        .await
    }

    /// Parses an SSE event into a StreamEvent ( ProviderStreamEvent )
    fn parse_stream_sse(
        event: std::result::Result<Event, reqwest_eventsource::Error>,
    ) -> Result<Self::StreamEvent>;

    /// Returns true to mark the stream as ended
    fn end_stream(event: &Self::StreamEvent) -> bool;

    async fn send_and_stream(
        &self,
        base_url: impl IntoUrl,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<Self::StreamEvent>> + Send>>>
    where
        Self::StreamEvent: Send + 'static,
        Self: Sync,
    {
        let client = get_streaming_client();

        let url = join_url(base_url, &self.path())?;

        // Establish the event source stream directly
        // Note: Status code errors (including 429) will be surfaced as stream events
        // and should be handled by retry logic in the provider's stream_text() method
        let events_stream = client
            .request(self.method(), url.clone())
            .headers(self.headers()?)
            .query(&self.query_params())
            .body(self.body()?)
            .eventsource()
            .map_err(|e| Error::ApiError {
                status_code: None,
                details: format!("SSE stream error: {e}"),
            })?;

        // Map events to deserialized StreamEvent ( ProviderStreamEvent )
        // Filter out Event::Open (connection acknowledgement with no data) before parsing,
        // so providers never receive a spurious NotSupported chunk as the first stream item.
        let mapped_stream = events_stream
            .filter(|e| futures::future::ready(!matches!(e, Ok(Event::Open))))
            .map(|event_result| Self::parse_stream_sse(event_result));

        // State that indicates if the stream has ended
        let ended = std::sync::Arc::new(std::sync::Mutex::new(false));

        // Scan to end or mark the stream as ended
        let stream = mapped_stream.scan(ended, |ended, res| {
            let mut ended = ended.lock().unwrap();

            if *ended {
                return futures::future::ready(None); // Stop the stream after end event
            }

            *ended = res.as_ref().map_or(true, |evt| Self::end_stream(evt)); // Mark the stream as ended on api error or end event

            futures::future::ready(Some(res)) // Emit the event
        });

        Ok(Box::pin(stream))
    }
}
/// Trait for embedding model clients to interact with embedding APIs.
#[allow(dead_code)]
pub(crate) trait EmbeddingClient {
    type Response: DeserializeOwned + std::fmt::Debug + Clone;

    fn path(&self) -> String;
    fn method(&self) -> reqwest::Method;
    fn query_params(&self) -> Vec<(&str, &str)>;
    fn body(&self) -> Result<reqwest::Body>;
    fn headers(&self) -> Result<reqwest::header::HeaderMap>;

    async fn send(&self, base_url: impl IntoUrl) -> Result<Self::Response> {
        let base_url = base_url
            .into_url()
            .map_err(|_| Error::InvalidInput("Invalid base URL".into()))?;

        let url = join_url(base_url, &self.path())?;

        // Serialize body once to avoid consumption issues on retries
        let body_bytes = {
            let body = self.body()?;
            // Convert Body to bytes - this is the critical fix for retry body consumption
            match body.as_bytes() {
                Some(bytes) => bytes.to_vec(),
                None => {
                    // If body doesn't have as_bytes (streaming body), we can't retry it
                    log::warn!("Request body is not retryable (streaming body)");
                    vec![]
                }
            }
        };

        let method = self.method();
        let query_params = self.query_params();
        let config = RetryConfig::default();

        retry_request(
            url,
            method,
            self.headers()?,
            query_params,
            move || reqwest::Body::from(body_bytes.clone()),
            config,
        )
        .await
    }
}

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

    /// Helper to create a custom RetryConfig for testing
    fn test_config(
        max_retries: u32,
        initial_wait_ms: u64,
        max_wait_ms: u64,
        use_jitter: bool,
    ) -> RetryConfig {
        RetryConfig {
            max_retries,
            initial_wait: Duration::from_millis(initial_wait_ms),
            max_wait: Duration::from_millis(max_wait_ms),
            use_jitter,
        }
    }

    // ========================================================================
    // Tests for Retry-After Header Handling
    // ========================================================================

    #[test]
    fn test_calculate_backoff_with_retry_after_header() {
        let config = test_config(5, 1000, 30000, false);
        let retry_after = Some(Duration::from_secs(5));

        let result = calculate_backoff(0, &config, retry_after);
        assert_eq!(result, Duration::from_secs(5));
    }

    #[test]
    fn test_calculate_backoff_retry_after_capped_at_max_wait() {
        let config = test_config(5, 1000, 10000, false);
        let retry_after = Some(Duration::from_secs(60)); // 60s > 10s max

        let result = calculate_backoff(0, &config, retry_after);
        assert_eq!(result, Duration::from_millis(10000));
    }

    #[test]
    fn test_calculate_backoff_retry_after_below_max_wait() {
        let config = test_config(5, 1000, 30000, false);
        let retry_after = Some(Duration::from_millis(5000));

        let result = calculate_backoff(3, &config, retry_after);
        assert_eq!(result, Duration::from_millis(5000));
    }

    #[test]
    fn test_calculate_backoff_retry_after_zero() {
        let config = test_config(5, 1000, 30000, false);
        let retry_after = Some(Duration::from_secs(0));

        let result = calculate_backoff(0, &config, retry_after);
        assert_eq!(result, Duration::from_secs(0));
    }

    #[test]
    fn test_calculate_backoff_retry_after_very_large() {
        let config = test_config(5, 1000, 1000, false);
        let retry_after = Some(Duration::from_secs(u64::MAX / 2));

        let result = calculate_backoff(0, &config, retry_after);
        assert_eq!(result, Duration::from_millis(1000)); // Capped at max_wait
    }

    // ========================================================================
    // Tests for Exponential Backoff (No Jitter)
    // ========================================================================

    #[test]
    fn test_calculate_backoff_retry_count_zero_no_jitter() {
        let config = test_config(5, 1000, 30000, false);

        let result = calculate_backoff(0, &config, None);
        // 1000ms * 2^0 = 1000ms
        assert_eq!(result, Duration::from_millis(1000));
    }

    #[test]
    fn test_calculate_backoff_retry_count_one_no_jitter() {
        let config = test_config(5, 1000, 30000, false);

        let result = calculate_backoff(1, &config, None);
        // 1000ms * 2^1 = 2000ms
        assert_eq!(result, Duration::from_millis(2000));
    }

    #[test]
    fn test_calculate_backoff_retry_count_two_no_jitter() {
        let config = test_config(5, 1000, 30000, false);

        let result = calculate_backoff(2, &config, None);
        // 1000ms * 2^2 = 4000ms
        assert_eq!(result, Duration::from_millis(4000));
    }

    #[test]
    fn test_calculate_backoff_retry_count_three_no_jitter() {
        let config = test_config(5, 1000, 30000, false);

        let result = calculate_backoff(3, &config, None);
        // 1000ms * 2^3 = 8000ms
        assert_eq!(result, Duration::from_millis(8000));
    }

    #[test]
    fn test_calculate_backoff_retry_count_four_no_jitter() {
        let config = test_config(5, 1000, 30000, false);

        let result = calculate_backoff(4, &config, None);
        // 1000ms * 2^4 = 16000ms
        assert_eq!(result, Duration::from_millis(16000));
    }

    #[test]
    fn test_calculate_backoff_retry_count_five_no_jitter() {
        let config = test_config(5, 1000, 30000, false);

        let result = calculate_backoff(5, &config, None);
        // 1000ms * 2^5 = 32000ms, but capped at 30000ms
        assert_eq!(result, Duration::from_millis(30000));
    }

    #[test]
    fn test_calculate_backoff_exceeds_max_wait_no_jitter() {
        let config = test_config(5, 1000, 5000, false);

        let result = calculate_backoff(3, &config, None);
        // 1000ms * 2^3 = 8000ms, but capped at 5000ms
        assert_eq!(result, Duration::from_millis(5000));
    }

    #[test]
    fn test_calculate_backoff_exactly_at_max_wait_no_jitter() {
        let config = test_config(5, 1000, 8000, false);

        let result = calculate_backoff(3, &config, None);
        // 1000ms * 2^3 = 8000ms, exactly at max_wait
        assert_eq!(result, Duration::from_millis(8000));
    }

    #[test]
    fn test_calculate_backoff_large_retry_count_no_jitter() {
        let config = test_config(100, 1000, 30000, false);

        let result = calculate_backoff(20, &config, None);
        // 1000ms * 2^20 would be huge, should be capped at 30000ms
        assert_eq!(result, Duration::from_millis(30000));
    }

    #[test]
    fn test_calculate_backoff_saturation_no_jitter() {
        let config = test_config(5, 1_000_000, 60000, false);

        // 1_000_000ms * 2^10 would overflow, should saturate
        let result = calculate_backoff(10, &config, None);
        // Should be capped at max_wait
        assert_eq!(result, Duration::from_millis(60000));
    }

    // ========================================================================
    // Tests for Exponential Backoff with Jitter (requires `jitter` feature)
    // ========================================================================

    #[cfg(feature = "jitter")]
    #[test]
    fn test_calculate_backoff_with_jitter_within_range() {
        let config = test_config(5, 1000, 30000, true);

        let result = calculate_backoff(2, &config, None);
        // Base: 1000ms * 2^2 = 4000ms
        // Jitter should be ±10% = 3600ms to 4400ms
        let _base = Duration::from_millis(4000);
        let min = Duration::from_millis(3600);
        let max = Duration::from_millis(4400);

        assert!(
            result >= min && result <= max,
            "Result {result:?} should be between {min:?} and {max:?}"
        );
    }

    #[cfg(feature = "jitter")]
    #[test]
    fn test_calculate_backoff_with_jitter_different_retry_counts() {
        let config = test_config(5, 1000, 30000, true);

        for retry_count in 0..5 {
            let result = calculate_backoff(retry_count, &config, None);
            let base = 1000 * 2_u64.pow(retry_count);
            let min = (base as f64 * 0.9) as u64;
            let max = (base as f64 * 1.1) as u64;

            assert!(
                result >= Duration::from_millis(min) && result <= Duration::from_millis(max),
                "Retry count {}: result {:?} should be between {:?} and {:?}",
                retry_count,
                result,
                Duration::from_millis(min),
                Duration::from_millis(max)
            );
        }
    }

    #[cfg(feature = "jitter")]
    #[test]
    fn test_calculate_backoff_jitter_respects_max_wait() {
        let config = test_config(5, 1000, 10000, true);

        // Base would be 16000ms, but max_wait is 10000ms
        let result = calculate_backoff(4, &config, None);

        // The implementation caps BEFORE jitter, so the result can be up to ±10%
        // of max_wait: 9000ms to 11000ms.
        assert!(
            result >= Duration::from_millis(9000) && result <= Duration::from_millis(11000),
            "Result {result:?} should be around 10000ms ±10%"
        );
    }

    #[cfg(feature = "jitter")]
    #[test]
    fn test_calculate_backoff_jitter_independent_calls_in_range() {
        let config = test_config(5, 1000, 30000, true);

        let result1 = calculate_backoff(2, &config, None);
        let result2 = calculate_backoff(2, &config, None);

        let min = Duration::from_millis(3600);
        let max = Duration::from_millis(4400);

        assert!(result1 >= min && result1 <= max);
        assert!(result2 >= min && result2 <= max);
    }

    #[cfg(feature = "jitter")]
    #[test]
    fn test_calculate_backoff_jitter_at_zero_retry_count() {
        let config = test_config(5, 1000, 30000, true);

        let result = calculate_backoff(0, &config, None);
        // Base: 1000ms * 2^0 = 1000ms
        // Jitter: ±10% = 900ms to 1100ms
        assert!(
            result >= Duration::from_millis(900) && result <= Duration::from_millis(1100),
            "Result {result:?} should be around 1000ms ±10%"
        );
    }

    // ========================================================================
    // Tests for Edge Cases
    // ========================================================================

    #[test]
    fn test_calculate_backoff_initial_wait_zero() {
        let config = test_config(5, 0, 30000, false);

        let result = calculate_backoff(5, &config, None);
        // 0ms * 2^5 = 0ms
        assert_eq!(result, Duration::from_millis(0));
    }

    #[test]
    fn test_calculate_backoff_max_wait_zero() {
        let config = test_config(5, 1000, 0, false);

        let result = calculate_backoff(0, &config, None);
        // Should be capped at max_wait = 0
        assert_eq!(result, Duration::from_millis(0));
    }

    #[test]
    fn test_calculate_backoff_both_zeros() {
        let config = test_config(5, 0, 0, false);

        let result = calculate_backoff(10, &config, None);
        assert_eq!(result, Duration::from_millis(0));
    }

    #[test]
    fn test_calculate_backoff_very_large_initial_wait() {
        let config = RetryConfig {
            max_retries: 5,
            initial_wait: Duration::from_secs(1_000_000),
            max_wait: Duration::from_secs(2_000_000),
            use_jitter: false,
        };

        let result = calculate_backoff(0, &config, None);
        assert_eq!(result, Duration::from_secs(1_000_000));
    }

    #[test]
    fn test_calculate_backoff_overflow_protection() {
        let config = RetryConfig {
            max_retries: 100,
            initial_wait: Duration::from_millis(u64::MAX / 2),
            max_wait: Duration::from_secs(60),
            use_jitter: false,
        };

        // This should saturate multiplication and get capped at max_wait
        let result = calculate_backoff(10, &config, None);
        assert_eq!(result, Duration::from_secs(60));
    }

    #[test]
    fn test_calculate_backoff_u32_max_retry_count() {
        let config = test_config(u32::MAX, 1000, 30000, false);

        // Should saturate and cap at max_wait
        let result = calculate_backoff(u32::MAX, &config, None);
        assert_eq!(result, Duration::from_millis(30000));
    }

    #[test]
    fn test_calculate_backoff_power_of_two_overflow() {
        let config = test_config(100, 1000, 60000, false);

        // 2^63 would overflow u32::saturating_pow
        let result = calculate_backoff(63, &config, None);
        // Should saturate and cap at max_wait
        assert_eq!(result, Duration::from_millis(60000));
    }

    #[cfg(feature = "jitter")]
    #[test]
    fn test_calculate_backoff_jitter_with_zero_base() {
        let config = test_config(5, 0, 30000, true);

        let result = calculate_backoff(0, &config, None);
        // Base is 0, jitter of ±10% of 0 is still 0
        assert_eq!(result, Duration::from_millis(0));
    }

    #[cfg(feature = "jitter")]
    #[test]
    fn test_calculate_backoff_jitter_with_very_small_base() {
        let config = test_config(5, 10, 30000, true);

        let result = calculate_backoff(0, &config, None);
        // Base: 10ms, jitter ±10% = 9ms to 11ms
        assert!(
            result >= Duration::from_millis(9) && result <= Duration::from_millis(11),
            "Result {result:?} should be around 10ms ±10%"
        );
    }

    #[test]
    fn test_calculate_backoff_sequence_increases_exponentially() {
        let config = test_config(5, 1000, 100000, false);

        let mut prev_result = Duration::from_millis(0);
        for retry_count in 0..10 {
            let result = calculate_backoff(retry_count, &config, None);
            // Each result should be greater than or equal to previous (until cap)
            assert!(
                result >= prev_result,
                "Retry count {retry_count}: {result:?} should be >= {prev_result:?}"
            );

            // Each result should be approximately double the previous (until cap)
            if retry_count > 0 {
                let ratio = result.as_millis() as f64 / prev_result.as_millis() as f64;
                if result.as_millis() < config.max_wait.as_millis() {
                    assert!(
                        (ratio - 2.0).abs() < 0.01,
                        "Retry count {retry_count}: ratio {ratio} should be ~2.0"
                    );
                }
            }

            prev_result = result;
        }
    }

    // ========================================================================
    // Tests for is_retryable_status
    // ========================================================================

    #[test]
    fn test_is_retryable_status_429() {
        assert!(is_retryable_status(reqwest::StatusCode::TOO_MANY_REQUESTS));
    }

    #[test]
    fn test_is_retryable_status_502() {
        assert!(is_retryable_status(reqwest::StatusCode::BAD_GATEWAY));
    }

    #[test]
    fn test_is_retryable_status_503() {
        assert!(is_retryable_status(
            reqwest::StatusCode::SERVICE_UNAVAILABLE
        ));
    }

    #[test]
    fn test_is_retryable_status_504() {
        assert!(is_retryable_status(reqwest::StatusCode::GATEWAY_TIMEOUT));
    }

    #[test]
    fn test_is_retryable_status_200_not_retryable() {
        assert!(!is_retryable_status(reqwest::StatusCode::OK));
    }

    #[test]
    fn test_is_retryable_status_400_not_retryable() {
        assert!(!is_retryable_status(reqwest::StatusCode::BAD_REQUEST));
    }

    #[test]
    fn test_is_retryable_status_401_not_retryable() {
        assert!(!is_retryable_status(reqwest::StatusCode::UNAUTHORIZED));
    }

    #[test]
    fn test_is_retryable_status_403_not_retryable() {
        assert!(!is_retryable_status(reqwest::StatusCode::FORBIDDEN));
    }

    #[test]
    fn test_is_retryable_status_404_not_retryable() {
        assert!(!is_retryable_status(reqwest::StatusCode::NOT_FOUND));
    }

    #[test]
    fn test_is_retryable_status_500_not_retryable() {
        // 500 Internal Server Error is usually not retryable
        assert!(!is_retryable_status(
            reqwest::StatusCode::INTERNAL_SERVER_ERROR
        ));
    }

    // ========================================================================
    // Tests for parse_retry_after
    // ========================================================================

    #[test]
    fn test_parse_retry_after_valid_seconds() {
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::RETRY_AFTER,
            reqwest::header::HeaderValue::from_static("120"),
        );

        let result = parse_retry_after(&headers);
        assert_eq!(result, Some(Duration::from_secs(120)));
    }

    #[test]
    fn test_parse_retry_after_zero_seconds() {
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::RETRY_AFTER,
            reqwest::header::HeaderValue::from_static("0"),
        );

        let result = parse_retry_after(&headers);
        assert_eq!(result, Some(Duration::from_secs(0)));
    }

    #[test]
    fn test_parse_retry_after_large_seconds() {
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::RETRY_AFTER,
            reqwest::header::HeaderValue::from_static("86400"), // 24 hours
        );

        let result = parse_retry_after(&headers);
        assert_eq!(result, Some(Duration::from_secs(86400)));
    }

    #[test]
    fn test_parse_retry_after_missing_header() {
        let headers = reqwest::header::HeaderMap::new();

        let result = parse_retry_after(&headers);
        assert_eq!(result, None);
    }

    #[test]
    fn test_parse_retry_after_invalid_format() {
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::RETRY_AFTER,
            reqwest::header::HeaderValue::from_static("invalid"),
        );

        let result = parse_retry_after(&headers);
        assert_eq!(result, None);
    }

    #[test]
    fn test_parse_retry_after_http_date_format() {
        // HTTP date format is not currently supported, should return None
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::RETRY_AFTER,
            reqwest::header::HeaderValue::from_static("Wed, 21 Oct 2025 07:28:00 GMT"),
        );

        let result = parse_retry_after(&headers);
        assert_eq!(result, None); // Not implemented yet
    }

    #[test]
    fn test_parse_retry_after_negative_number() {
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::RETRY_AFTER,
            reqwest::header::HeaderValue::from_static("-10"),
        );

        let result = parse_retry_after(&headers);
        assert_eq!(result, None); // Should fail to parse as u64
    }

    #[test]
    fn test_parse_retry_after_decimal_number() {
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::RETRY_AFTER,
            reqwest::header::HeaderValue::from_static("10.5"),
        );

        let result = parse_retry_after(&headers);
        assert_eq!(result, None); // Should fail to parse as u64
    }

    #[derive(serde::Serialize)]
    struct TestBody<'a> {
        model: &'a str,
        #[serde(skip_serializing_if = "Option::is_none")]
        temperature: Option<f32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        reasoning: Option<serde_json::Value>,
    }

    fn parse_body(body: reqwest::Body) -> serde_json::Value {
        let bytes = body.as_bytes().expect("body should be available as bytes");
        serde_json::from_slice(bytes).expect("body should contain valid json")
    }

    #[test]
    fn test_merge_body_without_overrides() {
        let body = TestBody {
            model: "gpt-4o",
            temperature: None,
            reasoning: None,
        };

        let parsed = parse_body(merge_body(&body, None, None).expect("body should merge"));

        assert_eq!(parsed["model"], "gpt-4o");
        assert!(parsed.get("temperature").is_none());
    }

    #[test]
    fn test_merge_body_adds_new_fields() {
        let body = TestBody {
            model: "gpt-4o",
            temperature: None,
            reasoning: None,
        };
        let mut request = serde_json::Map::new();
        request.insert("store".to_string(), serde_json::Value::Bool(false));
        request.insert(
            "instructions".to_string(),
            serde_json::Value::String("Be helpful".to_string()),
        );

        let parsed =
            parse_body(merge_body(&body, None, Some(&request)).expect("body should merge"));

        assert_eq!(parsed["model"], "gpt-4o");
        assert_eq!(parsed["store"], false);
        assert_eq!(parsed["instructions"], "Be helpful");
    }

    #[test]
    fn test_merge_body_request_overrides_provider_level_fields() {
        let body = TestBody {
            model: "gpt-4o",
            temperature: Some(0.5),
            reasoning: None,
        };
        let mut provider = serde_json::Map::new();
        provider.insert("store".to_string(), serde_json::Value::Bool(false));
        provider.insert(
            "temperature".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.7).expect("valid number")),
        );

        let mut request = serde_json::Map::new();
        request.insert("store".to_string(), serde_json::Value::Bool(true));
        request.insert(
            "temperature".to_string(),
            serde_json::Value::Number(serde_json::Number::from_f64(0.9).expect("valid number")),
        );

        let parsed = parse_body(
            merge_body(&body, Some(&provider), Some(&request)).expect("body should merge"),
        );

        assert_eq!(parsed["model"], "gpt-4o");
        assert_eq!(parsed["store"], true);
        assert_eq!(parsed["temperature"], 0.9);
    }

    #[test]
    fn test_merge_body_preserves_nested_objects() {
        let body = TestBody {
            model: "gpt-4o",
            temperature: None,
            reasoning: Some(serde_json::json!({ "effort": "high" })),
        };
        let mut request = serde_json::Map::new();
        request.insert("store".to_string(), serde_json::Value::Bool(false));

        let parsed =
            parse_body(merge_body(&body, None, Some(&request)).expect("body should merge"));

        assert_eq!(parsed["model"], "gpt-4o");
        assert_eq!(parsed["reasoning"]["effort"], "high");
        assert_eq!(parsed["store"], false);
    }

    #[test]
    fn test_merge_body_rejects_non_object_requests() {
        let err = merge_body(&serde_json::Value::String("oops".to_string()), None, None)
            .expect_err("non-object bodies should fail");

        assert!(matches!(err, Error::Other(_)));
    }

    #[test]
    fn test_merge_headers_without_overrides() {
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::AUTHORIZATION,
            reqwest::header::HeaderValue::from_static("Bearer test-key"),
        );

        let merged = merge_headers(headers.clone(), None, None).expect("headers should merge");

        assert_eq!(
            merged.get(reqwest::header::AUTHORIZATION),
            headers.get(reqwest::header::AUTHORIZATION)
        );
        assert_eq!(merged.len(), 1);
    }

    #[test]
    fn test_merge_headers_request_overrides_provider_level_headers() {
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::CONTENT_TYPE,
            reqwest::header::HeaderValue::from_static("application/json"),
        );

        let provider = HashMap::from([
            ("x-trace-id".to_string(), "provider-trace".to_string()),
            ("x-provider".to_string(), "openai".to_string()),
        ]);
        let request = HashMap::from([
            ("x-trace-id".to_string(), "request-trace".to_string()),
            ("x-request".to_string(), "generate-text".to_string()),
        ]);

        let merged =
            merge_headers(headers, Some(&provider), Some(&request)).expect("headers should merge");

        assert_eq!(merged["content-type"], "application/json");
        assert_eq!(merged["x-trace-id"], "request-trace");
        assert_eq!(merged["x-provider"], "openai");
        assert_eq!(merged["x-request"], "generate-text");
    }

    #[test]
    fn test_merge_headers_rejects_invalid_header_name() {
        let provider = HashMap::from([("bad header".to_string(), "value".to_string())]);

        let err = merge_headers(reqwest::header::HeaderMap::new(), Some(&provider), None)
            .expect_err("invalid header name should fail");

        assert_eq!(
            err.to_string(),
            "Invalid input: Invalid headers: invalid HTTP header name"
        );
    }

    #[test]
    fn test_merge_headers_rejects_invalid_header_value() {
        let request = HashMap::from([("x-trace-id".to_string(), "\ninvalid".to_string())]);

        let err = merge_headers(reqwest::header::HeaderMap::new(), None, Some(&request))
            .expect_err("invalid header value should fail");

        assert_eq!(
            err.to_string(),
            "Invalid input: Invalid headers: failed to parse header value"
        );
    }
}