Skip to main content

adk_anthropic/
client.rs

1use std::env;
2use std::fs;
3use std::pin::Pin;
4use std::sync::Arc;
5use std::task::{Context, Poll};
6use std::time::{Duration, Instant};
7
8use futures::Stream;
9use reqwest::header::{HeaderMap, HeaderValue};
10use reqwest::{Client as ReqwestClient, Response, header};
11use serde::Deserialize;
12use tokio::time::sleep;
13
14use crate::AccumulatingStream;
15use crate::backoff::ExponentialBackoff;
16use crate::base_url::{InsecureHttp, validate_base_url};
17use crate::client_logger::ClientLogger;
18use crate::error::{Error, Result};
19use crate::observability::{
20    CLIENT_REQUEST_DURATION, CLIENT_REQUEST_ERRORS, CLIENT_REQUEST_RETRIES, CLIENT_REQUESTS,
21    CLIENT_RETRY_BACKOFF,
22};
23use crate::sse::{process_json_sse, process_sse_with_timeout};
24use crate::types::{
25    BatchRequest, BatchResultItem, FileObject, Message, MessageBatch, MessageCountTokensParams,
26    MessageCreateParams, MessageStreamEvent, MessageTokensCount, ModelInfo, ModelListParams,
27    ModelListResponse, PaginatedList, ServerFallbackMessage, ServerFallbackRequest,
28    ServerFallbackStreamEvent, SkillObject, ThinkingConfig,
29};
30
31use base64::Engine as _;
32
33/// Simple base64 encoding for skill content.
34fn base64_encode(data: &[u8]) -> String {
35    base64::engine::general_purpose::STANDARD.encode(data)
36}
37
38/// A stream wrapper that logs events and the final message through a [`ClientLogger`].
39///
40/// This stream passes through all events from the underlying [`AccumulatingStream`],
41/// logging each event as it occurs and logging the final reconstructed message
42/// when the stream completes.
43pub struct LoggingStream<'a> {
44    inner: AccumulatingStream,
45    logger: &'a dyn ClientLogger,
46    receiver: Option<tokio::sync::oneshot::Receiver<Result<Message>>>,
47}
48
49impl<'a> LoggingStream<'a> {
50    /// Create a new logging stream wrapper.
51    fn new(
52        inner: AccumulatingStream,
53        receiver: tokio::sync::oneshot::Receiver<Result<Message>>,
54        logger: &'a dyn ClientLogger,
55    ) -> Self {
56        Self { inner, logger, receiver: Some(receiver) }
57    }
58}
59
60impl Stream for LoggingStream<'_> {
61    type Item = Result<MessageStreamEvent>;
62
63    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
64        let inner = Pin::new(&mut self.inner);
65        match inner.poll_next(cx) {
66            Poll::Ready(Some(Ok(event))) => {
67                self.logger.log_stream_event(&event);
68                Poll::Ready(Some(Ok(event)))
69            }
70            Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(e))),
71            Poll::Ready(None) => {
72                // Stream ended - try to get the accumulated message
73                if let Some(mut receiver) = self.receiver.take()
74                    && let Ok(Ok(ref message)) = receiver.try_recv()
75                {
76                    self.logger.log_stream_message(message);
77                }
78                Poll::Ready(None)
79            }
80            Poll::Pending => Poll::Pending,
81        }
82    }
83}
84
85const DEFAULT_API_URL: &str = "https://api.anthropic.com";
86const ANTHROPIC_API_VERSION: &str = "2023-06-01";
87/// Matches the official SDKs: long thinking turns routinely exceed a minute.
88const DEFAULT_TIMEOUT: Duration = Duration::from_secs(600);
89/// Upper bound on establishing a connection, so a long request timeout does not
90/// also let an unreachable host hold a request for minutes.
91const MAX_CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
92const SERVER_FALLBACK_BETA: &str = "server-side-fallback-2026-07-01";
93/// Opt-in named when a base URL given in code is rejected for plain HTTP.
94const CODE_INSECURE_HTTP_OPT_IN: &str =
95    "call `allow_insecure_http()` on the client before setting the base URL";
96/// Opt-in named when `ANTHROPIC_BASE_URL` is rejected for plain HTTP.
97const ENV_INSECURE_HTTP_OPT_IN: &str =
98    "set ANTHROPIC_ALLOW_INSECURE_HTTP=1 alongside ANTHROPIC_BASE_URL";
99
100/// Client for the Anthropic API with performance optimizations.
101///
102/// # Timeouts
103///
104/// | Request kind | Bound |
105/// |--------------|-------|
106/// | Non-streaming | [`with_timeout`](Self::with_timeout) covers the whole request (default 10 minutes) |
107/// | Connecting | the request timeout, capped at 60 seconds |
108/// | Streaming, until response headers | the same timeout |
109/// | Streaming body | a 10-minute inactivity timeout between chunks ([`with_http_timeouts`](Self::with_http_timeouts) sets another), plus the optional total bound from [`with_stream_timeout`](Self::with_stream_timeout) |
110///
111/// The `Debug` output redacts the API key.
112#[derive(Clone)]
113pub struct Anthropic {
114    api_key: String,
115    client: ReqwestClient,
116    /// Client without a total timeout, so long streams are not cut off mid-body.
117    stream_client: ReqwestClient,
118    base_url: String,
119    timeout: Duration,
120    stream_timeout: Option<Duration>,
121    idle_timeout: Option<Duration>,
122    max_retries: usize,
123    throughput_ops_sec: f64,
124    reserve_capacity: f64,
125    /// Cached headers for performance - Arc for cheap cloning
126    cached_headers: Arc<HeaderMap>,
127    /// Whether `with_base_url` accepts `http://` to a non-loopback host.
128    allow_insecure_http: bool,
129}
130
131impl std::fmt::Debug for Anthropic {
132    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133        f.debug_struct("Anthropic")
134            .field("api_key", &"[REDACTED]")
135            .field("client", &self.client)
136            .field("stream_client", &self.stream_client)
137            .field("base_url", &self.base_url)
138            .field("timeout", &self.timeout)
139            .field("stream_timeout", &self.stream_timeout)
140            .field("max_retries", &self.max_retries)
141            .field("throughput_ops_sec", &self.throughput_ops_sec)
142            .field("reserve_capacity", &self.reserve_capacity)
143            .field("cached_headers", &self.cached_headers)
144            .field("allow_insecure_http", &self.allow_insecure_http)
145            .finish()
146    }
147}
148
149fn retry_after(value: &str) -> Option<u64> {
150    let value = value.trim();
151    if !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) {
152        let seconds = value.parse::<u64>().ok()?;
153        return seconds.checked_mul(1000).map(|_| seconds);
154    }
155    let deadline = httpdate::parse_http_date(value).ok()?;
156    let delay = deadline.duration_since(std::time::SystemTime::now()).unwrap_or(Duration::ZERO);
157    delay
158        .as_secs()
159        .checked_add(u64::from(delay.subsec_nanos() > 0))
160        .filter(|seconds| seconds.checked_mul(1000).is_some())
161}
162
163impl Anthropic {
164    /// Build the HTTP client. `total_timeout` of `None` leaves response bodies
165    /// unbounded, which the streaming client relies on.
166    fn build_http_client(
167        total_timeout: Option<Duration>,
168        connect_timeout: Duration,
169        idle_timeout: Option<Duration>,
170    ) -> Result<ReqwestClient> {
171        let mut builder = ReqwestClient::builder()
172            .connect_timeout(if idle_timeout.is_some() {
173                connect_timeout
174            } else {
175                connect_timeout.min(MAX_CONNECT_TIMEOUT)
176            })
177            .redirect(reqwest::redirect::Policy::none())
178            .pool_max_idle_per_host(10) // Connection pooling optimization
179            .pool_idle_timeout(Duration::from_secs(90))
180            .tcp_keepalive(Duration::from_secs(60));
181        if let Some(timeout) = idle_timeout {
182            builder = builder.read_timeout(timeout);
183        }
184        if let Some(timeout) = total_timeout {
185            builder = builder.timeout(timeout);
186        }
187        builder.build().map_err(|e| {
188            Error::http_client(format!("Failed to build HTTP client: {e}"), Some(Box::new(e)))
189        })
190    }
191
192    /// Resolve an API key value, handling file:// URLs
193    fn resolve_api_key(key_value: &str) -> Result<String> {
194        if let Some(stripped) = key_value.strip_prefix("file://") {
195            // Handle file:// URLs
196            let path = if stripped.starts_with('/') {
197                // Absolute path: file:///root/.env -> /root/.env
198                stripped.to_string()
199            } else {
200                // Relative path: file://../foo -> ../foo
201                stripped.to_string()
202            };
203
204            fs::read_to_string(&path).map(|content| content.trim().to_string()).map_err(|e| {
205                Error::validation(
206                    format!("Failed to read API key from file '{}': {}", path, e),
207                    Some("api_key".to_string()),
208                )
209            })
210        } else {
211            // Regular API key value
212            Ok(key_value.to_string())
213        }
214    }
215
216    /// Resolve the effective base URL from optional `ANTHROPIC_BASE_URL` and
217    /// `ANTHROPIC_ALLOW_INSECURE_HTTP` values.
218    ///
219    /// A value supplied through the environment is held to the same rule as one
220    /// supplied through [`Anthropic::with_base_url`]: every request attaches the
221    /// API key, so an unencrypted endpoint would leak the credential. The
222    /// acknowledgement for plain HTTP comes from the same source as the URL, so
223    /// an `insecure_http_env` of `1` or `true` (case-insensitive) admits a
224    /// non-loopback `http://` value. When no URL is supplied the default
225    /// Anthropic API URL is used.
226    ///
227    /// # Errors
228    ///
229    /// Returns a validation error when the supplied value is not `https://`, not
230    /// `http://` with a loopback host, and not acknowledged `http://`.
231    fn resolve_base_url(
232        env_value: Option<String>,
233        insecure_http_env: Option<String>,
234    ) -> Result<String> {
235        match env_value {
236            Some(value) => {
237                let acknowledged = insecure_http_env
238                    .as_deref()
239                    .map(str::trim)
240                    .is_some_and(|flag| flag == "1" || flag.eq_ignore_ascii_case("true"));
241                let insecure_http = if acknowledged {
242                    InsecureHttp::Acknowledged
243                } else {
244                    InsecureHttp::Rejected { opt_in: Some(ENV_INSECURE_HTTP_OPT_IN) }
245                };
246                validate_base_url(&value, insecure_http)?;
247                Ok(value)
248            }
249            None => Ok(DEFAULT_API_URL.to_string()),
250        }
251    }
252
253    /// Create a new Anthropic client.
254    ///
255    /// The API key can be provided directly or read from the `ANTHROPIC_API_KEY`
256    /// environment variable. If the value starts with `"file://"`, it will be
257    /// treated as a file path and the API key will be read from that file.
258    ///
259    /// The base URL is resolved from the `ANTHROPIC_BASE_URL` environment
260    /// variable. If not set, the default Anthropic API URL is used.
261    ///
262    /// `ANTHROPIC_BASE_URL` may name a plain `http://` endpoint on a non-loopback
263    /// host, such as an internal gateway, only when `ANTHROPIC_ALLOW_INSECURE_HTTP`
264    /// is set to `1` or `true` (case-insensitive). The client then logs a warning
265    /// and sends the API key unencrypted. `ANTHROPIC_ALLOW_INSECURE_HTTP` applies
266    /// to the environment URL only; a URL given in code needs
267    /// [`allow_insecure_http`](Self::allow_insecure_http).
268    ///
269    /// # Errors
270    ///
271    /// Returns a validation error when `ANTHROPIC_BASE_URL` is set to an
272    /// endpoint that would transmit the API key in cleartext — anything other
273    /// than `https://`, or `http://` with a loopback host (`localhost`,
274    /// `127.0.0.1`, `[::1]`), unless `ANTHROPIC_ALLOW_INSECURE_HTTP`
275    /// acknowledges an `http://` endpoint. A misconfigured environment fails
276    /// loudly rather than silently falling back to the default URL.
277    pub fn new(api_key: Option<String>) -> Result<Self> {
278        let api_key = match api_key {
279            Some(key) => Self::resolve_api_key(&key)?,
280            None => {
281                let env_key = env::var("ANTHROPIC_API_KEY").map_err(|_| {
282                    Error::authentication(
283                        "API key not provided and ANTHROPIC_API_KEY environment variable not set",
284                    )
285                })?;
286                Self::resolve_api_key(&env_key)?
287            }
288        };
289
290        let base_url = Self::resolve_base_url(
291            env::var("ANTHROPIC_BASE_URL").ok(),
292            env::var("ANTHROPIC_ALLOW_INSECURE_HTTP").ok(),
293        )?;
294        Self::from_values(api_key, base_url)
295    }
296
297    /// Create a client with an explicit API key and base URL.
298    ///
299    /// Unlike [`Anthropic::new`], this constructor reads neither `ANTHROPIC_API_KEY`
300    /// nor `ANTHROPIC_BASE_URL`. A `file://` API key is read from that file, as in
301    /// [`Anthropic::new`].
302    ///
303    /// The base URL is validated here, so this constructor cannot take a plain
304    /// `http://` URL to a non-loopback host. For one, construct the client with an
305    /// `https://` URL, then call [`allow_insecure_http`](Self::allow_insecure_http)
306    /// followed by [`with_base_url`](Self::with_base_url).
307    ///
308    /// # Errors
309    ///
310    /// Returns a validation error when `base_url` is not `https://` and not
311    /// `http://` with a loopback host, or when a `file://` API key cannot be read.
312    ///
313    /// # Example
314    ///
315    /// ```
316    /// use adk_anthropic::Anthropic;
317    ///
318    /// let client = Anthropic::new_with_base_url("sk-ant-key", "https://proxy.example.com")?;
319    /// # Ok::<(), adk_anthropic::Error>(())
320    /// ```
321    pub fn new_with_base_url(
322        api_key: impl Into<String>,
323        base_url: impl Into<String>,
324    ) -> Result<Self> {
325        let base_url = base_url.into();
326        validate_base_url(
327            &base_url,
328            InsecureHttp::Rejected { opt_in: Some(CODE_INSECURE_HTTP_OPT_IN) },
329        )?;
330        Self::from_values(Self::resolve_api_key(&api_key.into())?, base_url)
331    }
332
333    fn from_values(api_key: String, base_url: String) -> Result<Self> {
334        let timeout = DEFAULT_TIMEOUT;
335        let client = Self::build_http_client(Some(timeout), timeout, None)?;
336        let stream_client = Self::build_http_client(None, timeout, None)?;
337
338        // Pre-build headers for performance
339        let cached_headers = Arc::new(Self::build_default_headers(&api_key)?);
340
341        Ok(Self {
342            api_key,
343            client,
344            stream_client,
345            base_url,
346            timeout,
347            stream_timeout: None,
348            idle_timeout: None,
349            max_retries: 3,
350            throughput_ops_sec: 1.0 / 60.0,
351            reserve_capacity: 1.0 / 60.0,
352            cached_headers,
353            allow_insecure_http: false,
354        })
355    }
356
357    /// Create an Anthropic client authenticated with a bearer token.
358    ///
359    /// Unlike [`Anthropic::new`], this constructor does not require an API key or
360    /// the `ANTHROPIC_API_KEY` environment variable. Requests carry
361    /// `Authorization: Bearer <token>` and omit `x-api-key`.
362    ///
363    /// # Errors
364    ///
365    /// Returns a validation error when the token is empty or cannot be encoded
366    /// as an HTTP header value.
367    pub fn new_with_auth_token(auth_token: impl Into<String>) -> Result<Self> {
368        Self::new(Some(String::new()))?.with_auth_token(auth_token)
369    }
370
371    /// Replace API-key authentication with a bearer token.
372    ///
373    /// The resulting client omits `x-api-key` from every request.
374    ///
375    /// # Errors
376    ///
377    /// Returns a validation error when the token is empty or cannot be encoded
378    /// as an HTTP header value.
379    pub fn with_auth_token(mut self, auth_token: impl Into<String>) -> Result<Self> {
380        let auth_token = auth_token.into();
381        if auth_token.trim().is_empty() {
382            return Err(Error::validation(
383                "Auth token cannot be empty".to_string(),
384                Some("auth_token".to_string()),
385            ));
386        }
387
388        let mut headers = (*self.cached_headers).clone();
389        headers.remove("x-api-key");
390        let mut value =
391            HeaderValue::from_str(&format!("Bearer {auth_token}")).map_err(|error| {
392                Error::validation(
393                    format!("Invalid auth token format: {error}"),
394                    Some("auth_token".to_string()),
395                )
396            })?;
397        value.set_sensitive(true);
398        headers.insert(header::AUTHORIZATION, value);
399        self.api_key.clear();
400        self.cached_headers = Arc::new(headers);
401        Ok(self)
402    }
403
404    /// Override the `anthropic-version` header used by this client.
405    ///
406    /// # Errors
407    ///
408    /// Returns a validation error when the version is empty or cannot be
409    /// encoded as an HTTP header value.
410    pub fn with_api_version(mut self, api_version: impl Into<String>) -> Result<Self> {
411        let api_version = api_version.into();
412        if api_version.trim().is_empty() {
413            return Err(Error::validation(
414                "API version cannot be empty".to_string(),
415                Some("api_version".to_string()),
416            ));
417        }
418
419        let mut headers = (*self.cached_headers).clone();
420        let value = HeaderValue::from_str(&api_version).map_err(|error| {
421            Error::validation(
422                format!("Invalid API version format: {error}"),
423                Some("api_version".to_string()),
424            )
425        })?;
426        headers.insert("anthropic-version", value);
427        self.cached_headers = Arc::new(headers);
428        Ok(self)
429    }
430
431    /// Allow a plain `http://` base URL on a non-loopback host.
432    ///
433    /// Use this for a trusted internal gateway that is reachable only over plain
434    /// HTTP. Every request attaches the API key, which then crosses the network
435    /// unencrypted. Loopback `http://` URLs and `https://` URLs need no opt-in.
436    ///
437    /// [`with_base_url`](Self::with_base_url) and
438    /// [`with_base_url_and_timeout`](Self::with_base_url_and_timeout) validate the
439    /// URL when they are called, so this method must be called **before** them.
440    /// Accepting a non-loopback `http://` URL logs a warning with the host.
441    ///
442    /// The opt-in applies to URLs given in code. A URL from `ANTHROPIC_BASE_URL`
443    /// is acknowledged by `ANTHROPIC_ALLOW_INSECURE_HTTP` instead; see
444    /// [`new`](Self::new).
445    ///
446    /// # Example
447    ///
448    /// ```
449    /// use adk_anthropic::Anthropic;
450    ///
451    /// let client = Anthropic::new(Some("placeholder-api-key".to_string()))?
452    ///     .allow_insecure_http()
453    ///     .with_base_url("http://10.60.1.20:8080/api/v1/llm/anthropic".to_string())?;
454    /// assert_eq!(client.base_url(), "http://10.60.1.20:8080/api/v1/llm/anthropic");
455    /// # Ok::<(), adk_anthropic::Error>(())
456    /// ```
457    pub fn allow_insecure_http(mut self) -> Self {
458        self.allow_insecure_http = true;
459        self
460    }
461
462    /// Set a custom base URL for this client.
463    ///
464    /// This method allows you to specify a different API endpoint for the client.
465    /// The base URL should be the root URL without the `/v1/` suffix - this will
466    /// be added automatically when constructing request URLs.
467    ///
468    /// The URL is validated when this method is called. To use a plain `http://`
469    /// URL on a non-loopback host, call
470    /// [`allow_insecure_http`](Self::allow_insecure_http) first.
471    ///
472    /// # Errors
473    ///
474    /// Every request made by this client attaches the Anthropic API key, so the
475    /// base URL must be encrypted. Returns a validation error unless the URL uses
476    /// `https://`, or `http://` with a loopback host (`localhost`, `127.0.0.1`,
477    /// `[::1]`) for local development, or `http://` after
478    /// [`allow_insecure_http`](Self::allow_insecure_http).
479    ///
480    /// # Examples
481    ///
482    /// ```
483    /// # use adk_anthropic::Anthropic;
484    /// // For Anthropic's API (default)
485    /// let client = Anthropic::new(Some("placeholder-api-key".to_string()))?
486    ///     .with_base_url("https://api.anthropic.com".to_string())?;
487    ///
488    /// // For Minimax (international)
489    /// let client = Anthropic::new(Some("placeholder-api-key".to_string()))?
490    ///     .with_base_url("https://api.minimax.io/anthropic".to_string())?;
491    ///
492    /// // For Minimax (China)
493    /// let client = Anthropic::new(Some("placeholder-api-key".to_string()))?
494    ///     .with_base_url("https://api.minimaxi.com/anthropic".to_string())?;
495    /// # Ok::<(), adk_anthropic::Error>(())
496    /// ```
497    pub fn with_base_url(mut self, base_url: String) -> Result<Self> {
498        let insecure_http = if self.allow_insecure_http {
499            InsecureHttp::Acknowledged
500        } else {
501            InsecureHttp::Rejected { opt_in: Some(CODE_INSECURE_HTTP_OPT_IN) }
502        };
503        validate_base_url(&base_url, insecure_http)?;
504        self.base_url = base_url;
505        Ok(self)
506    }
507
508    /// Return the effective API base URL used for message requests.
509    pub fn base_url(&self) -> &str {
510        &self.base_url
511    }
512
513    /// Set a custom timeout for this client.
514    ///
515    /// The timeout bounds a whole non-streaming request, and the wait for the
516    /// response headers of a streaming request. A streamed body is not bounded
517    /// by it — see [`with_stream_timeout`](Self::with_stream_timeout). The default
518    /// is 10 minutes; connecting is bounded by the same value, capped at 60 seconds.
519    ///
520    /// # Errors
521    ///
522    /// Returns an HTTP client error when the underlying client cannot be built.
523    pub fn with_timeout(mut self, timeout: Duration) -> Result<Self> {
524        self.timeout = timeout;
525        self.idle_timeout = None;
526        self.client = Self::build_http_client(Some(timeout), timeout, None)?;
527        self.stream_client = Self::build_http_client(None, timeout, None)?;
528        Ok(self)
529    }
530
531    /// Sets connection and byte-inactivity limits without a total request limit.
532    ///
533    /// Incoming body bytes reset the inactivity bound, including SSE comments.
534    /// [`with_timeout`](Self::with_timeout) restores the total-request configuration.
535    ///
536    /// # Example
537    ///
538    /// ```
539    /// use adk_anthropic::Anthropic;
540    /// use std::time::Duration;
541    /// let client = Anthropic::new(Some("test-key".into()))?
542    ///     .with_http_timeouts(Duration::from_secs(10), Duration::from_secs(300))?;
543    /// # Ok::<(), adk_anthropic::Error>(())
544    /// ```
545    ///
546    /// # Errors
547    ///
548    /// Returns an HTTP client error if either transport cannot be built.
549    pub fn with_http_timeouts(mut self, connect: Duration, idle: Duration) -> Result<Self> {
550        self.client = Self::build_http_client(None, connect, Some(idle))?;
551        self.stream_client = Self::build_http_client(None, connect, Some(idle))?;
552        self.timeout = idle;
553        self.idle_timeout = Some(idle);
554        Ok(self)
555    }
556
557    /// Returns the request timeout set by [`with_timeout`](Self::with_timeout).
558    ///
559    /// # Example
560    ///
561    /// ```
562    /// use std::time::Duration;
563    /// use adk_anthropic::Anthropic;
564    ///
565    /// let client = Anthropic::new(Some("placeholder-api-key".to_string()))?;
566    /// assert_eq!(client.timeout(), Duration::from_secs(600));
567    /// # Ok::<(), adk_anthropic::Error>(())
568    /// ```
569    pub fn timeout(&self) -> Duration {
570        self.timeout
571    }
572
573    /// Bound the total duration of each streaming request, body included.
574    ///
575    /// Streams have no total bound by default: a long generation keeps running
576    /// for as long as the server keeps sending data, and a stalled stream fails
577    /// after 10 minutes without data. `None` restores that default.
578    ///
579    /// # Example
580    ///
581    /// ```
582    /// use std::time::Duration;
583    /// use adk_anthropic::Anthropic;
584    ///
585    /// let client = Anthropic::new(Some("placeholder-api-key".to_string()))?
586    ///     .with_stream_timeout(Some(Duration::from_secs(600)));
587    /// # Ok::<(), adk_anthropic::Error>(())
588    /// ```
589    pub fn with_stream_timeout(mut self, stream_timeout: Option<Duration>) -> Self {
590        self.stream_timeout = stream_timeout;
591        self
592    }
593
594    /// Set the maximum number of retries for this client.
595    ///
596    /// This method allows you to specify how many times to retry failed requests.
597    pub fn with_max_retries(mut self, max_retries: usize) -> Self {
598        self.max_retries = max_retries;
599        self
600    }
601
602    /// Get the API key being used by this client.
603    pub fn api_key(&self) -> &str {
604        &self.api_key
605    }
606
607    /// Set the backoff parameters for this client.
608    ///
609    /// This method allows you to configure the exponential backoff algorithm.
610    pub fn with_backoff_params(mut self, throughput_ops_sec: f64, reserve_capacity: f64) -> Self {
611        self.throughput_ops_sec = throughput_ops_sec;
612        self.reserve_capacity = reserve_capacity;
613        self
614    }
615
616    /// Set both a custom base URL and timeout for this client.
617    ///
618    /// This is a convenience method that chains [`with_base_url`](Self::with_base_url)
619    /// and [`with_timeout`](Self::with_timeout). The URL is validated when this
620    /// method is called, so a plain `http://` URL on a non-loopback host needs
621    /// [`allow_insecure_http`](Self::allow_insecure_http) to be called first.
622    ///
623    /// # Errors
624    ///
625    /// Returns the validation error of [`with_base_url`](Self::with_base_url), or
626    /// an HTTP client error when the underlying client cannot be built.
627    ///
628    /// # Example
629    ///
630    /// ```
631    /// use std::time::Duration;
632    ///
633    /// use adk_anthropic::Anthropic;
634    ///
635    /// let client = Anthropic::new(Some("placeholder-api-key".to_string()))?
636    ///     .allow_insecure_http()
637    ///     .with_base_url_and_timeout(
638    ///         "http://gateway.corp.internal/anthropic".to_string(),
639    ///         Duration::from_secs(30),
640    ///     )?;
641    /// # let _ = client;
642    /// # Ok::<(), adk_anthropic::Error>(())
643    /// ```
644    pub fn with_base_url_and_timeout(self, base_url: String, timeout: Duration) -> Result<Self> {
645        self.with_base_url(base_url)?.with_timeout(timeout)
646    }
647
648    /// Build default headers for API requests (static method for initialization).
649    fn build_default_headers(api_key: &str) -> Result<HeaderMap> {
650        let mut headers = HeaderMap::new();
651        headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
652        headers.insert(header::ACCEPT, HeaderValue::from_static("application/json"));
653        let mut api_key_value = HeaderValue::from_str(api_key).map_err(|e| {
654            Error::validation(format!("Invalid API key format: {e}"), Some("api_key".to_string()))
655        })?;
656        // Keeps the key out of `Debug` output of the header map and of request logs.
657        api_key_value.set_sensitive(true);
658        headers.insert("x-api-key", api_key_value);
659        headers.insert("anthropic-version", HeaderValue::from_static(ANTHROPIC_API_VERSION));
660        Ok(headers)
661    }
662
663    /// Get cached headers for performance (no allocation needed).
664    fn default_headers(&self) -> HeaderMap {
665        (*self.cached_headers).clone()
666    }
667
668    /// Adds default HTTP headers, replacing defaults with the same name.
669    ///
670    /// Per-request replacement headers still take precedence. Automatically
671    /// selected beta headers continue to be derived from message parameters. The
672    /// headers are stored on the existing client rather than rebuilding it, so this
673    /// method cannot fail and returns `Self`.
674    ///
675    /// # Example
676    ///
677    /// ```no_run
678    /// use adk_anthropic::Anthropic;
679    /// use reqwest::header::{HeaderMap, HeaderValue};
680    /// let mut headers = HeaderMap::new();
681    /// headers.insert("x-session-id", HeaderValue::from_static("conversation-1"));
682    /// let client = Anthropic::new(Some("api-key".into()))?.with_default_headers(headers);
683    /// # Ok::<(), adk_anthropic::Error>(())
684    /// ```
685    #[must_use]
686    pub fn with_default_headers(mut self, headers: HeaderMap) -> Self {
687        Arc::make_mut(&mut self.cached_headers).extend(headers);
688        self
689    }
690
691    /// Return a copy of the headers this client normally sends.
692    ///
693    /// Callers can modify this map and pass it to
694    /// [`Anthropic::send_with_headers`] or [`Anthropic::stream_with_headers`].
695    /// Those methods use replacement semantics, so the supplied map is sent
696    /// instead of these defaults.
697    pub fn default_headers_for_request(&self) -> HeaderMap {
698        self.default_headers()
699    }
700
701    /// Returns the headers [`Anthropic::send`] or [`Anthropic::stream`] sends for `params`.
702    ///
703    /// The map holds the client defaults plus the beta headers the request's typed
704    /// features require (structured outputs, context management, fast mode) and, when
705    /// `streaming` is true, `accept: text/event-stream`. Callers can modify it and pass it
706    /// to [`Anthropic::send_with_headers`] or [`Anthropic::stream_with_headers`].
707    ///
708    /// # Errors
709    ///
710    /// Returns a validation error when a configured `anthropic-beta` header is not valid
711    /// ASCII or the combined beta list is not a valid header value.
712    ///
713    /// # Example
714    ///
715    /// ```no_run
716    /// use adk_anthropic::{Anthropic, KnownModel, MessageCreateParams, MessageParam, Model};
717    ///
718    /// let client = Anthropic::new(Some("api-key".into()))?;
719    /// let params = MessageCreateParams::new(
720    ///     1024,
721    ///     vec![MessageParam::user("Hello")],
722    ///     Model::Known(KnownModel::ClaudeSonnet46),
723    /// );
724    /// let mut headers = client.message_headers_for_request(&params, false)?;
725    /// headers.remove("anthropic-beta");
726    /// # Ok::<(), adk_anthropic::Error>(())
727    /// ```
728    pub fn message_headers_for_request(
729        &self,
730        params: &MessageCreateParams,
731        streaming: bool,
732    ) -> Result<HeaderMap> {
733        self.message_headers(params, &[], streaming)
734    }
735
736    /// Build a full endpoint URL from the base URL and endpoint path.
737    ///
738    /// This method handles trailing slashes gracefully and always inserts `/v1/`
739    /// between the base URL and endpoint path. This allows the base URL to be
740    /// specified without requiring a specific format (with or without trailing slash,
741    /// with or without `/v1/` suffix).
742    ///
743    /// # Examples
744    ///
745    /// - Base: `https://api.anthropic.com`, endpoint: `messages` → `https://api.anthropic.com/v1/messages`
746    /// - Base: `https://api.minimax.io/anthropic`, endpoint: `messages` → `https://api.minimax.io/anthropic/v1/messages`
747    /// - Base: `https://example.com/`, endpoint: `models` → `https://example.com/v1/models`
748    fn build_url(&self, endpoint: &str) -> String {
749        let base = self.base_url.trim_end_matches('/');
750        format!("{}/v1/{}", base, endpoint)
751    }
752
753    /// Retry wrapper that implements exponential backoff with header-based retry-after
754    async fn retry_with_backoff<F, Fut, T>(&self, operation: F) -> Result<T>
755    where
756        F: Fn() -> Fut,
757        Fut: std::future::Future<Output = Result<T>>,
758    {
759        let backoff = ExponentialBackoff::new(self.throughput_ops_sec, self.reserve_capacity);
760        let mut last_error = None;
761
762        for attempt in 0..=self.max_retries {
763            match operation().await {
764                Ok(result) => return Ok(result),
765                Err(error) => {
766                    // Check if error is retryable
767                    if !error.is_retryable() {
768                        return Err(error);
769                    }
770
771                    // Don't sleep on the last attempt
772                    if attempt == self.max_retries {
773                        last_error = Some(error);
774                        break;
775                    }
776
777                    // Return the original error rather than retrying before a long server delay.
778                    if error.retry_after().is_some_and(|seconds| seconds > 60) {
779                        return Err(error);
780                    }
781
782                    // Calculate backoff duration
783                    let exp_backoff_duration = backoff.next();
784
785                    // Get retry-after from error if available
786                    let header_backoff_duration = error.retry_after().map(Duration::from_secs);
787
788                    // Take the maximum of exponential backoff and header-based backoff
789                    let sleep_duration = match header_backoff_duration {
790                        Some(header_duration) => exp_backoff_duration.max(header_duration),
791                        None => exp_backoff_duration,
792                    };
793
794                    CLIENT_REQUEST_RETRIES.click();
795                    CLIENT_RETRY_BACKOFF.add(sleep_duration.as_secs_f64());
796                    sleep(sleep_duration).await;
797                    last_error = Some(error);
798                }
799            }
800        }
801
802        Err(last_error
803            .unwrap_or_else(|| Error::unknown("Failed after retries without capturing error")))
804    }
805
806    /// Process API response errors and convert to our Error type
807    async fn process_error_response(response: Response) -> Error {
808        let status = response.status();
809        let status_code = status.as_u16();
810
811        // Get headers we might need for error processing
812        let request_id = response
813            .headers()
814            .get("request-id")
815            .or_else(|| response.headers().get("x-request-id"))
816            .and_then(|val| val.to_str().ok())
817            .map(String::from);
818
819        let retry_after = response
820            .headers()
821            .get("retry-after")
822            .and_then(|val| val.to_str().ok())
823            .and_then(retry_after);
824
825        // Try to parse error response body
826        #[derive(Deserialize)]
827        struct ErrorResponse {
828            error: Option<ErrorDetail>,
829        }
830
831        #[derive(Deserialize)]
832        struct ErrorDetail {
833            #[serde(rename = "type")]
834            error_type: Option<String>,
835            message: Option<String>,
836            param: Option<String>,
837        }
838
839        let error_body = match response.text().await {
840            Ok(body) => body,
841            Err(e) => {
842                return if e.is_timeout() {
843                    Error::timeout("HTTP response inactivity timeout", None)
844                } else {
845                    Error::http_client(
846                        format!("Failed to read error response: {e}"),
847                        Some(Box::new(e)),
848                    )
849                };
850            }
851        };
852
853        // Try to parse as JSON first
854        let parsed_error = serde_json::from_str::<ErrorResponse>(&error_body).ok();
855        let error_type =
856            parsed_error.as_ref().and_then(|e| e.error.as_ref()).and_then(|e| e.error_type.clone());
857        let error_message = parsed_error
858            .as_ref()
859            .and_then(|e| e.error.as_ref())
860            .and_then(|e| e.message.clone())
861            .unwrap_or_else(|| error_body.clone());
862        let error_param =
863            parsed_error.as_ref().and_then(|e| e.error.as_ref()).and_then(|e| e.param.clone());
864
865        // Map HTTP status code to appropriate error type
866        match status_code {
867            400 => Error::bad_request(error_message, error_param),
868            401 => Error::authentication(error_message),
869            403 => Error::permission(error_message),
870            404 => Error::not_found(error_message, None, None),
871            408 => {
872                Error::Timeout { status_code: Some(408), message: error_message, duration: None }
873            }
874            429 | 529 => Error::RateLimit { status_code, message: error_message, retry_after },
875            500 => Error::InternalServer { message: error_message, request_id, retry_after },
876            502..=504 => {
877                Error::ServiceUnavailable { status_code, message: error_message, retry_after }
878            }
879            _ => Error::Api {
880                status_code,
881                error_type,
882                message: error_message,
883                request_id,
884                retry_after,
885            },
886        }
887    }
888
889    /// Convert reqwest errors to appropriate Error types
890    fn map_request_error(&self, e: reqwest::Error) -> Error {
891        if e.is_timeout() {
892            Error::timeout(format!("Request timed out: {e}"), Some(self.timeout.as_secs_f64()))
893        } else if e.is_connect() || e.is_body() || e.is_request() {
894            Error::connection(format!("Connection error: {e}"), Some(Box::new(e)))
895        } else {
896            Error::http_client(format!("Request failed: {e}"), Some(Box::new(e)))
897        }
898    }
899
900    /// Execute a POST request with error handling
901    async fn execute_post_request<T: serde::de::DeserializeOwned>(
902        &self,
903        url: &str,
904        body: &impl serde::Serialize,
905        headers: Option<HeaderMap>,
906    ) -> Result<T> {
907        let headers = headers.unwrap_or_else(|| self.default_headers());
908
909        let response = self
910            .client
911            .post(url)
912            .headers(headers)
913            .json(body)
914            .send()
915            .await
916            .map_err(|e| self.map_request_error(e))?;
917
918        if !response.status().is_success() {
919            return Err(Self::process_error_response(response).await);
920        }
921
922        response.json::<T>().await.map_err(|e| {
923            if e.is_timeout() || e.is_body() {
924                self.map_request_error(e)
925            } else {
926                Error::serialization(format!("Failed to parse response: {e}"), Some(Box::new(e)))
927            }
928        })
929    }
930
931    /// Send a streaming POST request on the client that has no total timeout.
932    ///
933    /// The configured timeout bounds the wait for the response headers, the SSE
934    /// layer bounds inactivity in the body, and `stream_timeout`, when set,
935    /// bounds the whole request.
936    async fn send_stream_request(
937        &self,
938        url: &str,
939        headers: HeaderMap,
940        body: &impl serde::Serialize,
941    ) -> Result<Response> {
942        let mut request = self.stream_client.post(url).headers(headers).json(body);
943        if let Some(stream_timeout) = self.stream_timeout {
944            request = request.timeout(stream_timeout);
945        }
946
947        let response = tokio::time::timeout(self.timeout, request.send())
948            .await
949            .map_err(|_| {
950                Error::timeout(
951                    format!(
952                        "Timed out after {} seconds waiting for the streaming response headers",
953                        self.timeout.as_secs_f64()
954                    ),
955                    Some(self.timeout.as_secs_f64()),
956                )
957            })?
958            .map_err(|e| self.map_request_error(e))?;
959
960        if !response.status().is_success() {
961            return Err(Self::process_error_response(response).await);
962        }
963        Ok(response)
964    }
965
966    /// Opens the pooled TLS connections the next request and the next stream would otherwise
967    /// open, with one `GET /v1/models?limit=1` on each client. It spends no tokens.
968    ///
969    /// The connections stay open while idle for the pool's idle timeout, 90 seconds, so call
970    /// it shortly before the turn it readies. An Anthropic-compatible endpoint without a
971    /// models list still opens its connections: only a refused key or an unreachable host
972    /// fails.
973    ///
974    /// # Errors
975    ///
976    /// Returns the API's error when it refuses the key (`401`, `403`) or cannot be reached.
977    ///
978    /// # Example
979    ///
980    /// ```rust,no_run
981    /// use adk_anthropic::Anthropic;
982    ///
983    /// # async fn example() -> adk_anthropic::Result<()> {
984    /// let client = Anthropic::new(None)?;
985    /// client.prewarm().await?;
986    /// # Ok(())
987    /// # }
988    /// ```
989    pub async fn prewarm(&self) -> Result<()> {
990        let url = self.build_url("models");
991        let open = |client: &ReqwestClient| {
992            let request = client.get(&url).headers(self.default_headers()).query(&[("limit", "1")]);
993            async move {
994                let response = request.send().await.map_err(|e| self.map_request_error(e))?;
995                let status = response.status().as_u16();
996                if status == 401 || status == 403 {
997                    return Err(Self::process_error_response(response).await);
998                }
999                // Reading the body returns the connection to the pool.
1000                response.bytes().await.map_err(|e| self.map_request_error(e))?;
1001                Ok(())
1002            }
1003        };
1004        futures::future::try_join(open(&self.client), open(&self.stream_client)).await?;
1005        Ok(())
1006    }
1007
1008    /// Execute a GET request with error handling
1009    async fn execute_get_request<T: serde::de::DeserializeOwned>(
1010        &self,
1011        url: &str,
1012        query_params: Option<&[(String, String)]>,
1013    ) -> Result<T> {
1014        let mut request = self.client.get(url).headers(self.default_headers());
1015
1016        if let Some(params) = query_params {
1017            for (key, value) in params {
1018                request = request.query(&[(key, value)]);
1019            }
1020        }
1021
1022        let response = request.send().await.map_err(|e| self.map_request_error(e))?;
1023
1024        if !response.status().is_success() {
1025            return Err(Self::process_error_response(response).await);
1026        }
1027
1028        response.json::<T>().await.map_err(|e| {
1029            if e.is_timeout() || e.is_body() {
1030                self.map_request_error(e)
1031            } else {
1032                Error::serialization(format!("Failed to parse response: {e}"), Some(Box::new(e)))
1033            }
1034        })
1035    }
1036
1037    fn append_beta_header(headers: &mut HeaderMap, beta: &str) -> Result<()> {
1038        if beta.trim().is_empty() {
1039            return Err(Error::validation(
1040                "Beta identifier cannot be empty".to_string(),
1041                Some("anthropic-beta".to_string()),
1042            ));
1043        }
1044        let existing = headers
1045            .get("anthropic-beta")
1046            .map(HeaderValue::to_str)
1047            .transpose()
1048            .map_err(|error| {
1049                Error::validation(
1050                    format!("Invalid existing anthropic-beta header: {error}"),
1051                    Some("anthropic-beta".to_string()),
1052                )
1053            })?
1054            .unwrap_or_default();
1055        if existing.split(',').any(|value| value.trim() == beta) {
1056            return Ok(());
1057        }
1058
1059        let combined =
1060            if existing.is_empty() { beta.to_string() } else { format!("{existing},{beta}") };
1061        let value = HeaderValue::from_str(&combined).map_err(|error| {
1062            Error::validation(
1063                format!("Invalid anthropic-beta header: {error}"),
1064                Some("anthropic-beta".to_string()),
1065            )
1066        })?;
1067        headers.insert("anthropic-beta", value);
1068        Ok(())
1069    }
1070
1071    fn message_headers(
1072        &self,
1073        params: &MessageCreateParams,
1074        extra_betas: &[&str],
1075        streaming: bool,
1076    ) -> Result<HeaderMap> {
1077        let mut headers = self.default_headers();
1078        if streaming {
1079            headers.insert(header::ACCEPT, HeaderValue::from_static("text/event-stream"));
1080        }
1081        for beta in params.required_betas() {
1082            Self::append_beta_header(&mut headers, beta)?;
1083        }
1084        for beta in &params.betas {
1085            Self::append_beta_header(&mut headers, beta)?;
1086        }
1087        for beta in extra_betas {
1088            Self::append_beta_header(&mut headers, beta)?;
1089        }
1090        Ok(headers)
1091    }
1092
1093    async fn send_with_resolved_headers(
1094        &self,
1095        mut params: MessageCreateParams,
1096        replacement_headers: Option<HeaderMap>,
1097    ) -> Result<Message> {
1098        let start = Instant::now();
1099        CLIENT_REQUESTS.click();
1100
1101        // Validate parameters first
1102        if let Err(err) = params.validate() {
1103            CLIENT_REQUEST_ERRORS.click();
1104            CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1105            return Err(err);
1106        }
1107
1108        // Ensure stream is disabled
1109        params.stream = false;
1110
1111        // Task 8.1: When thinking is Enabled, force temperature to 1.0
1112        if matches!(params.thinking, Some(ThinkingConfig::Enabled { .. })) {
1113            params.temperature = Some(1.0);
1114        }
1115
1116        let headers = match replacement_headers {
1117            Some(headers) => headers,
1118            None => self.message_headers(&params, &[], false)?,
1119        };
1120
1121        let result = self
1122            .retry_with_backoff(|| async {
1123                let url = self.build_url("messages");
1124                self.execute_post_request(&url, &params, Some(headers.clone())).await
1125            })
1126            .await;
1127
1128        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1129        if result.is_err() {
1130            CLIENT_REQUEST_ERRORS.click();
1131        }
1132        result
1133    }
1134
1135    /// Send a message to the API and get a non-streaming response.
1136    pub async fn send(&self, params: MessageCreateParams) -> Result<Message> {
1137        self.send_with_resolved_headers(params, None).await
1138    }
1139
1140    /// Send a message using an exact replacement header map.
1141    ///
1142    /// The supplied headers replace all client defaults and automatically
1143    /// generated beta headers. This permits per-request bearer authentication,
1144    /// API versions, beta selection, and deliberate beta suppression. Start
1145    /// from [`Anthropic::default_headers_for_request`] when only a small change
1146    /// is needed.
1147    ///
1148    /// # Errors
1149    ///
1150    /// Returns an error when the parameters are invalid, a header is invalid,
1151    /// or the request fails.
1152    pub async fn send_with_headers(
1153        &self,
1154        params: MessageCreateParams,
1155        headers: HeaderMap,
1156    ) -> Result<Message> {
1157        self.send_with_resolved_headers(params, Some(headers)).await
1158    }
1159
1160    /// Send a message with caller-selected Anthropic beta versions.
1161    ///
1162    /// Caller-selected betas are de-duplicated with beta headers required by
1163    /// the request's typed features. They are sent only as headers and never
1164    /// serialized into the JSON body.
1165    ///
1166    /// # Errors
1167    ///
1168    /// Returns an error when a beta identifier or message parameter is invalid,
1169    /// or the request fails.
1170    pub async fn send_with_betas(
1171        &self,
1172        params: MessageCreateParams,
1173        betas: &[&str],
1174    ) -> Result<Message> {
1175        let headers = self.message_headers(&params, betas, false)?;
1176        self.send_with_resolved_headers(params, Some(headers)).await
1177    }
1178
1179    /// Send a message to the API with logging and get a non-streaming response.
1180    ///
1181    /// This method is identical to [`send`](Self::send) but additionally logs
1182    /// the response through the provided [`ClientLogger`].
1183    pub async fn send_with_logger(
1184        &self,
1185        params: MessageCreateParams,
1186        logger: &dyn ClientLogger,
1187    ) -> Result<Message> {
1188        let result = self.send(params).await;
1189        if let Ok(ref message) = result {
1190            logger.log_response(message);
1191        }
1192        result
1193    }
1194
1195    /// Send a message to the API and get a streaming response.
1196    ///
1197    /// Returns a stream of MessageStreamEvent objects that can be processed incrementally.
1198    async fn stream_with_resolved_headers(
1199        &self,
1200        params: &MessageCreateParams,
1201        replacement_headers: Option<HeaderMap>,
1202    ) -> Result<impl Stream<Item = Result<MessageStreamEvent>> + use<>> {
1203        let start = Instant::now();
1204        CLIENT_REQUESTS.click();
1205
1206        // Validate parameters first
1207        if let Err(err) = params.validate() {
1208            CLIENT_REQUEST_ERRORS.click();
1209            CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1210            return Err(err);
1211        }
1212
1213        // Task 8.3: Clone and force stream = true in the request body
1214        let mut params = params.clone();
1215        params.stream = true;
1216
1217        // Task 8.1: When thinking is Enabled, force temperature to 1.0
1218        if matches!(params.thinking, Some(ThinkingConfig::Enabled { .. })) {
1219            params.temperature = Some(1.0);
1220        }
1221
1222        let headers = match replacement_headers {
1223            Some(headers) => headers,
1224            None => self.message_headers(&params, &[], true)?,
1225        };
1226
1227        let response = self
1228            .retry_with_backoff(|| async {
1229                let url = self.build_url("messages");
1230                self.send_stream_request(&url, headers.clone(), &params).await
1231            })
1232            .await;
1233
1234        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1235        let response = match response {
1236            Ok(response) => response,
1237            Err(err) => {
1238                CLIENT_REQUEST_ERRORS.click();
1239                return Err(err);
1240            }
1241        };
1242
1243        // Get the byte stream from the response
1244        let stream = response.bytes_stream();
1245
1246        // Create an SSE processor
1247        Ok(process_sse_with_timeout(stream, self.idle_timeout))
1248    }
1249
1250    /// Send a message to the API and stream response events.
1251    pub async fn stream(
1252        &self,
1253        params: &MessageCreateParams,
1254    ) -> Result<impl Stream<Item = Result<MessageStreamEvent>> + use<>> {
1255        self.stream_with_resolved_headers(params, None).await
1256    }
1257
1258    /// Stream a message using an exact replacement header map.
1259    ///
1260    /// The supplied headers replace all defaults, including `Accept`,
1261    /// authentication, API-version, and generated beta headers. Callers should
1262    /// normally include `Accept: text/event-stream`.
1263    ///
1264    /// # Errors
1265    ///
1266    /// Returns an error when the parameters are invalid, a header is invalid,
1267    /// or the request fails.
1268    pub async fn stream_with_headers(
1269        &self,
1270        params: &MessageCreateParams,
1271        headers: HeaderMap,
1272    ) -> Result<impl Stream<Item = Result<MessageStreamEvent>> + use<>> {
1273        self.stream_with_resolved_headers(params, Some(headers)).await
1274    }
1275
1276    /// Stream a message with caller-selected Anthropic beta versions.
1277    ///
1278    /// Caller-selected betas are de-duplicated with beta headers required by
1279    /// the request's typed features. They are sent only as headers and never
1280    /// serialized into the JSON body.
1281    ///
1282    /// # Errors
1283    ///
1284    /// Returns an error when a beta identifier or message parameter is invalid,
1285    /// or the request fails.
1286    pub async fn stream_with_betas(
1287        &self,
1288        params: &MessageCreateParams,
1289        betas: &[&str],
1290    ) -> Result<impl Stream<Item = Result<MessageStreamEvent>> + use<>> {
1291        let headers = self.message_headers(params, betas, true)?;
1292        self.stream_with_resolved_headers(params, Some(headers)).await
1293    }
1294
1295    /// Send a message with Claude server-side refusal fallback enabled.
1296    ///
1297    /// The beta API retries only safety-classifier refusals. Rate limits,
1298    /// overloads, and server failures are returned without fallback.
1299    ///
1300    /// # Errors
1301    ///
1302    /// Returns an error when the request or fallback configuration is invalid,
1303    /// or the request fails.
1304    pub async fn send_with_server_fallbacks(
1305        &self,
1306        mut request: ServerFallbackRequest,
1307    ) -> Result<ServerFallbackMessage> {
1308        let start = Instant::now();
1309        CLIENT_REQUESTS.click();
1310        if let Err(error) = request.validate() {
1311            CLIENT_REQUEST_ERRORS.click();
1312            CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1313            return Err(error);
1314        }
1315
1316        request.params.stream = false;
1317        if matches!(request.params.thinking, Some(ThinkingConfig::Enabled { .. })) {
1318            request.params.temperature = Some(1.0);
1319        }
1320        let headers = self.message_headers(&request.params, &[SERVER_FALLBACK_BETA], false)?;
1321        let result = self
1322            .retry_with_backoff(|| async {
1323                let url = self.build_url("messages");
1324                self.execute_post_request(&url, &request, Some(headers.clone())).await
1325            })
1326            .await;
1327
1328        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1329        if result.is_err() {
1330            CLIENT_REQUEST_ERRORS.click();
1331        }
1332        result
1333    }
1334
1335    /// Stream a message with Claude server-side refusal fallback enabled.
1336    ///
1337    /// # Errors
1338    ///
1339    /// Returns an error when the request or fallback configuration is invalid,
1340    /// or the request fails.
1341    pub async fn stream_with_server_fallbacks(
1342        &self,
1343        request: &ServerFallbackRequest,
1344    ) -> Result<impl Stream<Item = Result<ServerFallbackStreamEvent>> + use<>> {
1345        let start = Instant::now();
1346        CLIENT_REQUESTS.click();
1347        if let Err(error) = request.validate() {
1348            CLIENT_REQUEST_ERRORS.click();
1349            CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1350            return Err(error);
1351        }
1352
1353        let mut request = request.clone();
1354        request.params.stream = true;
1355        if matches!(request.params.thinking, Some(ThinkingConfig::Enabled { .. })) {
1356            request.params.temperature = Some(1.0);
1357        }
1358        let headers = self.message_headers(&request.params, &[SERVER_FALLBACK_BETA], true)?;
1359        let response = self
1360            .retry_with_backoff(|| async {
1361                let url = self.build_url("messages");
1362                self.send_stream_request(&url, headers.clone(), &request).await
1363            })
1364            .await;
1365
1366        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1367        let response = match response {
1368            Ok(response) => response,
1369            Err(error) => {
1370                CLIENT_REQUEST_ERRORS.click();
1371                return Err(error);
1372            }
1373        };
1374        Ok(process_json_sse(response.bytes_stream(), self.idle_timeout))
1375    }
1376
1377    /// Send a message to the API with logging and get a streaming response.
1378    ///
1379    /// This method is identical to [`stream`](Self::stream) but additionally logs
1380    /// each streaming event and the final reconstructed message through the
1381    /// provided [`ClientLogger`].
1382    ///
1383    /// Returns a [`LoggingStream`] that wraps an [`AccumulatingStream`], logging
1384    /// each event as it passes through and logging the final message when the
1385    /// stream completes.
1386    pub async fn stream_with_logger<'a>(
1387        &self,
1388        params: &MessageCreateParams,
1389        logger: &'a dyn ClientLogger,
1390    ) -> Result<LoggingStream<'a>> {
1391        let raw_stream = self.stream(params).await?;
1392        let (accumulating_stream, receiver) = AccumulatingStream::new(raw_stream);
1393        Ok(LoggingStream::new(accumulating_stream, receiver, logger))
1394    }
1395
1396    /// Count tokens for a message.
1397    ///
1398    /// This method counts the number of tokens that would be used by a message with the given parameters.
1399    /// It's useful for estimating costs or making sure your messages fit within the model's context window.
1400    pub async fn count_tokens(
1401        &self,
1402        params: MessageCountTokensParams,
1403    ) -> Result<MessageTokensCount> {
1404        let start = Instant::now();
1405        CLIENT_REQUESTS.click();
1406        let result = self
1407            .retry_with_backoff(|| async {
1408                let url = self.build_url("messages/count_tokens");
1409                self.execute_post_request(&url, &params, None).await
1410            })
1411            .await;
1412
1413        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1414        if result.is_err() {
1415            CLIENT_REQUEST_ERRORS.click();
1416        }
1417        result
1418    }
1419
1420    /// List available models from the API.
1421    ///
1422    /// Returns a paginated list of all available models. Use the parameters to control
1423    /// pagination and filter results.
1424    pub async fn list_models(&self, params: Option<ModelListParams>) -> Result<ModelListResponse> {
1425        let start = Instant::now();
1426        CLIENT_REQUESTS.click();
1427        let result = self
1428            .retry_with_backoff(|| async {
1429                let url = self.build_url("models");
1430
1431                let query_params = params.as_ref().map(|p| {
1432                    let mut params = Vec::new();
1433                    if let Some(ref after_id) = p.after_id {
1434                        params.push(("after_id".to_string(), after_id.clone()));
1435                    }
1436                    if let Some(ref before_id) = p.before_id {
1437                        params.push(("before_id".to_string(), before_id.clone()));
1438                    }
1439                    if let Some(limit) = p.limit {
1440                        params.push(("limit".to_string(), limit.to_string()));
1441                    }
1442                    params
1443                });
1444
1445                self.execute_get_request(&url, query_params.as_deref()).await
1446            })
1447            .await;
1448
1449        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1450        if result.is_err() {
1451            CLIENT_REQUEST_ERRORS.click();
1452        }
1453        result
1454    }
1455
1456    /// Retrieve information about a specific model.
1457    ///
1458    /// Returns detailed information about the specified model, including its
1459    /// ID, creation date, display name, and type.
1460    pub async fn get_model(&self, model_id: &str) -> Result<ModelInfo> {
1461        let start = Instant::now();
1462        CLIENT_REQUESTS.click();
1463        let result = self
1464            .retry_with_backoff(|| async {
1465                let url = self.build_url(&format!("models/{}", model_id));
1466                self.execute_get_request(&url, None).await
1467            })
1468            .await;
1469
1470        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1471        if result.is_err() {
1472            CLIENT_REQUEST_ERRORS.click();
1473        }
1474        result
1475    }
1476
1477    // --- Helper methods for DELETE and multipart requests ---
1478
1479    /// Execute a DELETE request with error handling.
1480    async fn execute_delete_request(&self, url: &str) -> Result<()> {
1481        let response = self
1482            .client
1483            .delete(url)
1484            .headers(self.default_headers())
1485            .send()
1486            .await
1487            .map_err(|e| self.map_request_error(e))?;
1488
1489        if !response.status().is_success() {
1490            return Err(Self::process_error_response(response).await);
1491        }
1492
1493        Ok(())
1494    }
1495
1496    /// Build standard pagination query params.
1497    fn pagination_params(
1498        before_id: Option<&str>,
1499        after_id: Option<&str>,
1500        limit: Option<u32>,
1501    ) -> Option<Vec<(String, String)>> {
1502        let mut params = Vec::new();
1503        if let Some(before) = before_id {
1504            params.push(("before_id".to_string(), before.to_string()));
1505        }
1506        if let Some(after) = after_id {
1507            params.push(("after_id".to_string(), after.to_string()));
1508        }
1509        if let Some(lim) = limit {
1510            params.push(("limit".to_string(), lim.to_string()));
1511        }
1512        if params.is_empty() { None } else { Some(params) }
1513    }
1514
1515    // --- Batches API (Req 13) ---
1516
1517    /// Create a message batch for asynchronous processing.
1518    pub async fn create_batch(&self, requests: Vec<BatchRequest>) -> Result<MessageBatch> {
1519        let start = Instant::now();
1520        CLIENT_REQUESTS.click();
1521        let body = serde_json::json!({ "requests": requests });
1522        let result = self
1523            .retry_with_backoff(|| async {
1524                let url = self.build_url("messages/batches");
1525                self.execute_post_request(&url, &body, None).await
1526            })
1527            .await;
1528        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1529        if result.is_err() {
1530            CLIENT_REQUEST_ERRORS.click();
1531        }
1532        result
1533    }
1534
1535    /// Get the status of a message batch.
1536    pub async fn get_batch(&self, batch_id: &str) -> Result<MessageBatch> {
1537        let start = Instant::now();
1538        CLIENT_REQUESTS.click();
1539        let result = self
1540            .retry_with_backoff(|| async {
1541                let url = self.build_url(&format!("messages/batches/{batch_id}"));
1542                self.execute_get_request(&url, None).await
1543            })
1544            .await;
1545        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1546        if result.is_err() {
1547            CLIENT_REQUEST_ERRORS.click();
1548        }
1549        result
1550    }
1551
1552    /// Get results of a completed batch as newline-delimited JSON.
1553    pub async fn batch_results(&self, batch_id: &str) -> Result<Vec<BatchResultItem>> {
1554        let start = Instant::now();
1555        CLIENT_REQUESTS.click();
1556        let result = self
1557            .retry_with_backoff(|| async {
1558                let url = self.build_url(&format!("messages/batches/{batch_id}/results"));
1559                let response = self
1560                    .client
1561                    .get(&url)
1562                    .headers(self.default_headers())
1563                    .send()
1564                    .await
1565                    .map_err(|e| self.map_request_error(e))?;
1566
1567                if !response.status().is_success() {
1568                    return Err(Self::process_error_response(response).await);
1569                }
1570
1571                let text = response.text().await.map_err(|e| {
1572                    Error::serialization(
1573                        format!("Failed to read batch results: {e}"),
1574                        Some(Box::new(e)),
1575                    )
1576                })?;
1577
1578                let mut items = Vec::new();
1579                for line in text.lines() {
1580                    let trimmed = line.trim();
1581                    if trimmed.is_empty() {
1582                        continue;
1583                    }
1584                    let item: BatchResultItem = serde_json::from_str(trimmed)?;
1585                    items.push(item);
1586                }
1587                Ok(items)
1588            })
1589            .await;
1590        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1591        if result.is_err() {
1592            CLIENT_REQUEST_ERRORS.click();
1593        }
1594        result
1595    }
1596
1597    /// Cancel an in-progress batch.
1598    pub async fn cancel_batch(&self, batch_id: &str) -> Result<MessageBatch> {
1599        let start = Instant::now();
1600        CLIENT_REQUESTS.click();
1601        let result = self
1602            .retry_with_backoff(|| async {
1603                let url = self.build_url(&format!("messages/batches/{batch_id}/cancel"));
1604                self.execute_post_request(&url, &serde_json::json!({}), None).await
1605            })
1606            .await;
1607        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1608        if result.is_err() {
1609            CLIENT_REQUEST_ERRORS.click();
1610        }
1611        result
1612    }
1613
1614    /// Delete a batch.
1615    pub async fn delete_batch(&self, batch_id: &str) -> Result<()> {
1616        let start = Instant::now();
1617        CLIENT_REQUESTS.click();
1618        let result = self
1619            .retry_with_backoff(|| async {
1620                let url = self.build_url(&format!("messages/batches/{batch_id}"));
1621                self.execute_delete_request(&url).await
1622            })
1623            .await;
1624        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1625        if result.is_err() {
1626            CLIENT_REQUEST_ERRORS.click();
1627        }
1628        result
1629    }
1630
1631    /// List message batches with pagination.
1632    pub async fn list_batches(
1633        &self,
1634        before_id: Option<&str>,
1635        after_id: Option<&str>,
1636        limit: Option<u32>,
1637    ) -> Result<PaginatedList<MessageBatch>> {
1638        let start = Instant::now();
1639        CLIENT_REQUESTS.click();
1640        let result = self
1641            .retry_with_backoff(|| async {
1642                let url = self.build_url("messages/batches");
1643                let query = Self::pagination_params(before_id, after_id, limit);
1644                self.execute_get_request(&url, query.as_deref()).await
1645            })
1646            .await;
1647        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1648        if result.is_err() {
1649            CLIENT_REQUEST_ERRORS.click();
1650        }
1651        result
1652    }
1653
1654    // --- Files API (Req 21) ---
1655
1656    /// Upload a file via multipart form upload.
1657    pub async fn upload_file(
1658        &self,
1659        data: Vec<u8>,
1660        mime_type: &str,
1661        filename: &str,
1662        purpose: &str,
1663    ) -> Result<FileObject> {
1664        let start = Instant::now();
1665        CLIENT_REQUESTS.click();
1666
1667        let mime_type = mime_type.to_string();
1668        let filename = filename.to_string();
1669        let purpose = purpose.to_string();
1670
1671        let result = self
1672            .retry_with_backoff(|| {
1673                let data = data.clone();
1674                let mime_type = mime_type.clone();
1675                let filename = filename.clone();
1676                let purpose = purpose.clone();
1677                async move {
1678                    let url = self.build_url("files");
1679                    let part = reqwest::multipart::Part::bytes(data)
1680                        .file_name(filename)
1681                        .mime_str(&mime_type)
1682                        .map_err(|e| {
1683                            Error::validation(
1684                                format!("Invalid MIME type: {e}"),
1685                                Some("mime_type".to_string()),
1686                            )
1687                        })?;
1688                    let form =
1689                        reqwest::multipart::Form::new().text("purpose", purpose).part("file", part);
1690
1691                    let response = self
1692                        .client
1693                        .post(&url)
1694                        .headers(self.default_headers())
1695                        .multipart(form)
1696                        .send()
1697                        .await
1698                        .map_err(|e| self.map_request_error(e))?;
1699
1700                    if !response.status().is_success() {
1701                        return Err(Self::process_error_response(response).await);
1702                    }
1703
1704                    response.json::<FileObject>().await.map_err(|e| {
1705                        Error::serialization(
1706                            format!("Failed to parse file response: {e}"),
1707                            Some(Box::new(e)),
1708                        )
1709                    })
1710                }
1711            })
1712            .await;
1713        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1714        if result.is_err() {
1715            CLIENT_REQUEST_ERRORS.click();
1716        }
1717        result
1718    }
1719
1720    /// Get metadata for a file.
1721    pub async fn get_file(&self, file_id: &str) -> Result<FileObject> {
1722        let start = Instant::now();
1723        CLIENT_REQUESTS.click();
1724        let result = self
1725            .retry_with_backoff(|| async {
1726                let url = self.build_url(&format!("files/{file_id}"));
1727                self.execute_get_request(&url, None).await
1728            })
1729            .await;
1730        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1731        if result.is_err() {
1732            CLIENT_REQUEST_ERRORS.click();
1733        }
1734        result
1735    }
1736
1737    /// Delete a file.
1738    pub async fn delete_file(&self, file_id: &str) -> Result<()> {
1739        let start = Instant::now();
1740        CLIENT_REQUESTS.click();
1741        let result = self
1742            .retry_with_backoff(|| async {
1743                let url = self.build_url(&format!("files/{file_id}"));
1744                self.execute_delete_request(&url).await
1745            })
1746            .await;
1747        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1748        if result.is_err() {
1749            CLIENT_REQUEST_ERRORS.click();
1750        }
1751        result
1752    }
1753
1754    /// List files with pagination.
1755    pub async fn list_files(
1756        &self,
1757        before_id: Option<&str>,
1758        after_id: Option<&str>,
1759        limit: Option<u32>,
1760    ) -> Result<PaginatedList<FileObject>> {
1761        let start = Instant::now();
1762        CLIENT_REQUESTS.click();
1763        let result = self
1764            .retry_with_backoff(|| async {
1765                let url = self.build_url("files");
1766                let query = Self::pagination_params(before_id, after_id, limit);
1767                self.execute_get_request(&url, query.as_deref()).await
1768            })
1769            .await;
1770        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1771        if result.is_err() {
1772            CLIENT_REQUEST_ERRORS.click();
1773        }
1774        result
1775    }
1776
1777    // --- Skills API (Req 22) ---
1778
1779    /// Create a new skill.
1780    pub async fn create_skill(
1781        &self,
1782        name: &str,
1783        description: &str,
1784        content: Vec<u8>,
1785    ) -> Result<SkillObject> {
1786        let start = Instant::now();
1787        CLIENT_REQUESTS.click();
1788        let body = serde_json::json!({
1789            "name": name,
1790            "description": description,
1791            "content": base64_encode(&content),
1792        });
1793        let result = self
1794            .retry_with_backoff(|| async {
1795                let url = self.build_url("skills");
1796                self.execute_post_request(&url, &body, None).await
1797            })
1798            .await;
1799        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1800        if result.is_err() {
1801            CLIENT_REQUEST_ERRORS.click();
1802        }
1803        result
1804    }
1805
1806    /// Get a skill by ID.
1807    pub async fn get_skill(&self, skill_id: &str) -> Result<SkillObject> {
1808        let start = Instant::now();
1809        CLIENT_REQUESTS.click();
1810        let result = self
1811            .retry_with_backoff(|| async {
1812                let url = self.build_url(&format!("skills/{skill_id}"));
1813                self.execute_get_request(&url, None).await
1814            })
1815            .await;
1816        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1817        if result.is_err() {
1818            CLIENT_REQUEST_ERRORS.click();
1819        }
1820        result
1821    }
1822
1823    /// Update a skill's content.
1824    pub async fn update_skill(&self, skill_id: &str, content: Vec<u8>) -> Result<SkillObject> {
1825        let start = Instant::now();
1826        CLIENT_REQUESTS.click();
1827        let body = serde_json::json!({
1828            "content": base64_encode(&content),
1829        });
1830        let result = self
1831            .retry_with_backoff(|| async {
1832                let url = self.build_url(&format!("skills/{skill_id}"));
1833                self.execute_post_request(&url, &body, None).await
1834            })
1835            .await;
1836        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1837        if result.is_err() {
1838            CLIENT_REQUEST_ERRORS.click();
1839        }
1840        result
1841    }
1842
1843    /// Delete a skill.
1844    pub async fn delete_skill(&self, skill_id: &str) -> Result<()> {
1845        let start = Instant::now();
1846        CLIENT_REQUESTS.click();
1847        let result = self
1848            .retry_with_backoff(|| async {
1849                let url = self.build_url(&format!("skills/{skill_id}"));
1850                self.execute_delete_request(&url).await
1851            })
1852            .await;
1853        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1854        if result.is_err() {
1855            CLIENT_REQUEST_ERRORS.click();
1856        }
1857        result
1858    }
1859
1860    /// List skills with pagination.
1861    pub async fn list_skills(
1862        &self,
1863        before_id: Option<&str>,
1864        after_id: Option<&str>,
1865        limit: Option<u32>,
1866    ) -> Result<PaginatedList<SkillObject>> {
1867        let start = Instant::now();
1868        CLIENT_REQUESTS.click();
1869        let result = self
1870            .retry_with_backoff(|| async {
1871                let url = self.build_url("skills");
1872                let query = Self::pagination_params(before_id, after_id, limit);
1873                self.execute_get_request(&url, query.as_deref()).await
1874            })
1875            .await;
1876        CLIENT_REQUEST_DURATION.add(start.elapsed().as_secs_f64());
1877        if result.is_err() {
1878            CLIENT_REQUEST_ERRORS.click();
1879        }
1880        result
1881    }
1882}
1883
1884#[cfg(test)]
1885mod tests {
1886    use super::*;
1887    use std::sync::Arc;
1888    use std::sync::atomic::{AtomicUsize, Ordering};
1889
1890    #[test]
1891    fn debug_output_redacts_api_key_and_bearer_token() {
1892        let client = Anthropic::new(Some("sk-ant-secret-key-value".to_string())).unwrap();
1893        let debug = format!("{client:?}");
1894        assert!(!debug.contains("sk-ant-secret-key-value"), "api key leaked: {debug}");
1895        assert!(debug.contains("[REDACTED]"));
1896
1897        let client = Anthropic::new_with_auth_token("secret-bearer-token").unwrap();
1898        let debug = format!("{client:?}");
1899        assert!(!debug.contains("secret-bearer-token"), "bearer token leaked: {debug}");
1900    }
1901
1902    #[test]
1903    fn api_key_header_is_marked_sensitive() {
1904        let headers = Anthropic::build_default_headers("sk-ant-secret-key-value").unwrap();
1905
1906        assert!(headers.get("x-api-key").unwrap().is_sensitive());
1907    }
1908
1909    #[tokio::test]
1910    async fn retry_logic_with_backoff() {
1911        let client = Anthropic {
1912            api_key: "test".to_string(),
1913            client: ReqwestClient::new(),
1914            stream_client: ReqwestClient::new(),
1915            base_url: "http://localhost".to_string(),
1916            timeout: Duration::from_secs(1),
1917            stream_timeout: None,
1918            idle_timeout: None,
1919            max_retries: 2,
1920            throughput_ops_sec: 1.0 / 60.0,
1921            reserve_capacity: 1.0 / 60.0,
1922            cached_headers: Arc::new(HeaderMap::new()),
1923            allow_insecure_http: false,
1924        };
1925
1926        let attempt_counter = Arc::new(AtomicUsize::new(0));
1927        let counter_clone = attempt_counter.clone();
1928
1929        let result = client
1930            .retry_with_backoff(|| {
1931                let counter = counter_clone.clone();
1932                async move {
1933                    let attempt = counter.fetch_add(1, Ordering::SeqCst);
1934                    match attempt {
1935                        0 | 1 => Err(Error::rate_limit("Rate limited", Some(1))),
1936                        _ => Ok("success".to_string()),
1937                    }
1938                }
1939            })
1940            .await;
1941
1942        assert!(result.is_ok());
1943        assert_eq!(result.unwrap(), "success");
1944        assert_eq!(attempt_counter.load(Ordering::SeqCst), 3);
1945    }
1946
1947    #[tokio::test]
1948    async fn retry_logic_with_non_retryable_error() {
1949        let client = Anthropic {
1950            api_key: "test".to_string(),
1951            client: ReqwestClient::new(),
1952            stream_client: ReqwestClient::new(),
1953            base_url: "http://localhost".to_string(),
1954            timeout: Duration::from_secs(1),
1955            stream_timeout: None,
1956            idle_timeout: None,
1957            max_retries: 2,
1958            throughput_ops_sec: 1.0 / 60.0,
1959            reserve_capacity: 1.0 / 60.0,
1960            cached_headers: Arc::new(HeaderMap::new()),
1961            allow_insecure_http: false,
1962        };
1963
1964        let attempt_counter = Arc::new(AtomicUsize::new(0));
1965        let counter_clone = attempt_counter.clone();
1966
1967        let result: Result<String> = client
1968            .retry_with_backoff(|| {
1969                let counter = counter_clone.clone();
1970                async move {
1971                    counter.fetch_add(1, Ordering::SeqCst);
1972                    Err(Error::authentication("Invalid API key"))
1973                }
1974            })
1975            .await;
1976
1977        assert!(result.is_err());
1978        assert!(result.unwrap_err().is_authentication());
1979        // Should only attempt once since authentication errors are not retryable
1980        assert_eq!(attempt_counter.load(Ordering::SeqCst), 1);
1981    }
1982
1983    #[tokio::test]
1984    async fn retry_logic_max_retries_exceeded() {
1985        let client = Anthropic {
1986            api_key: "test".to_string(),
1987            client: ReqwestClient::new(),
1988            stream_client: ReqwestClient::new(),
1989            base_url: "http://localhost".to_string(),
1990            timeout: Duration::from_secs(1),
1991            stream_timeout: None,
1992            idle_timeout: None,
1993            max_retries: 2,
1994            throughput_ops_sec: 1.0 / 60.0,
1995            reserve_capacity: 1.0 / 60.0,
1996            cached_headers: Arc::new(HeaderMap::new()),
1997            allow_insecure_http: false,
1998        };
1999
2000        let attempt_counter = Arc::new(AtomicUsize::new(0));
2001        let counter_clone = attempt_counter.clone();
2002
2003        let result: Result<String> = client
2004            .retry_with_backoff(|| {
2005                let counter = counter_clone.clone();
2006                async move {
2007                    counter.fetch_add(1, Ordering::SeqCst);
2008                    Err(Error::rate_limit("Always rate limited", Some(1)))
2009                }
2010            })
2011            .await;
2012
2013        assert!(result.is_err());
2014        assert!(result.unwrap_err().is_rate_limit());
2015        // Should attempt max_retries + 1 times (3 total: initial + 2 retries)
2016        assert_eq!(attempt_counter.load(Ordering::SeqCst), 3);
2017    }
2018
2019    #[tokio::test]
2020    async fn error_529_is_retryable() {
2021        // Test that 529 errors are properly mapped to rate_limit and are retryable
2022        let client = Anthropic {
2023            api_key: "test".to_string(),
2024            client: ReqwestClient::new(),
2025            stream_client: ReqwestClient::new(),
2026            base_url: "http://localhost".to_string(),
2027            timeout: Duration::from_secs(1),
2028            stream_timeout: None,
2029            idle_timeout: None,
2030            max_retries: 2,
2031            throughput_ops_sec: 1.0 / 60.0,
2032            reserve_capacity: 1.0 / 60.0,
2033            cached_headers: Arc::new(HeaderMap::new()),
2034            allow_insecure_http: false,
2035        };
2036
2037        let attempt_counter = Arc::new(AtomicUsize::new(0));
2038        let counter_clone = attempt_counter.clone();
2039
2040        let result = client
2041            .retry_with_backoff(|| {
2042                let counter = counter_clone.clone();
2043                async move {
2044                    let attempt = counter.fetch_add(1, Ordering::SeqCst);
2045                    match attempt {
2046                        0 | 1 => {
2047                            // Simulate a 529 overloaded error
2048                            Err(Error::api(
2049                                529,
2050                                Some("overloaded_error".to_string()),
2051                                "Overloaded".to_string(),
2052                                None,
2053                            ))
2054                        }
2055                        _ => Ok("success".to_string()),
2056                    }
2057                }
2058            })
2059            .await;
2060
2061        assert!(result.is_ok());
2062        assert_eq!(result.unwrap(), "success");
2063        // Should retry: initial attempt + 2 retries = 3 total
2064        assert_eq!(attempt_counter.load(Ordering::SeqCst), 3);
2065    }
2066
2067    #[test]
2068    fn error_529_mapped_correctly() {
2069        // Test that a 529 API error is correctly identified as retryable
2070        let error =
2071            Error::api(529, Some("overloaded_error".to_string()), "Overloaded".to_string(), None);
2072        assert!(error.is_retryable());
2073
2074        // Test that rate_limit error (which 529 now maps to) is also retryable
2075        let rate_limit_error = Error::rate_limit("Overloaded", Some(5));
2076        assert!(rate_limit_error.is_retryable());
2077    }
2078
2079    #[test]
2080    fn explicit_configuration() {
2081        if std::env::var_os("ADK_EXPLICIT_CONFIG_CHILD").is_none() {
2082            let status = std::process::Command::new(std::env::current_exe().unwrap())
2083                .args(["--exact", "client::tests::explicit_configuration"])
2084                .env("ADK_EXPLICIT_CONFIG_CHILD", "1")
2085                .env("ANTHROPIC_BASE_URL", "invalid-environment-url")
2086                .status()
2087                .unwrap();
2088            assert!(status.success());
2089            return;
2090        }
2091        let key = "sk-explicit-key";
2092        let client = Anthropic::new_with_base_url(key, "http://127.0.0.1:12345").unwrap();
2093        assert_eq!(client.api_key, key);
2094        assert_eq!(client.cached_headers["x-api-key"], key);
2095        assert_eq!(client.base_url, "http://127.0.0.1:12345");
2096        assert!(Anthropic::new_with_base_url(key, "invalid-explicit-url").is_err());
2097
2098        let dir =
2099            std::env::temp_dir().join(format!("adk_anthropic_explicit_{}", std::process::id()));
2100        std::fs::create_dir_all(&dir).unwrap();
2101        let file = dir.join("key.txt");
2102        std::fs::write(&file, "sk-from-file\n").unwrap();
2103        let client =
2104            Anthropic::new_with_base_url(format!("file://{}", file.display()), "https://a.example")
2105                .unwrap();
2106        std::fs::remove_dir_all(&dir).unwrap();
2107        assert_eq!(client.api_key, "sk-from-file");
2108        assert!(
2109            Anthropic::new_with_base_url("file:///adk-missing-key-file", "https://a.example")
2110                .is_err()
2111        );
2112    }
2113
2114    #[test]
2115    fn resolve_api_key_regular_value() {
2116        let result = Anthropic::resolve_api_key("sk-test-key-123");
2117        assert!(result.is_ok());
2118        assert_eq!(result.unwrap(), "sk-test-key-123");
2119    }
2120
2121    #[test]
2122    fn resolve_api_key_file_url_absolute() {
2123        let test_dir =
2124            std::env::temp_dir().join(format!("adk_anthropic_test_{}", std::process::id()));
2125        std::fs::create_dir_all(&test_dir).unwrap();
2126        let test_file = test_dir.join("test_api_key.txt");
2127        std::fs::write(&test_file, "sk-test-from-file-123\n").unwrap();
2128
2129        let file_url = format!("file://{}", test_file.display());
2130        let result = Anthropic::resolve_api_key(&file_url);
2131
2132        std::fs::remove_dir_all(&test_dir).unwrap();
2133
2134        assert!(result.is_ok());
2135        assert_eq!(result.unwrap(), "sk-test-from-file-123");
2136    }
2137
2138    #[test]
2139    fn resolve_api_key_file_url_relative() {
2140        let test_file = "test_relative_key.txt";
2141        std::fs::write(test_file, "sk-relative-key-456\n").unwrap();
2142
2143        let file_url = format!("file://{}", test_file);
2144        let result = Anthropic::resolve_api_key(&file_url);
2145
2146        std::fs::remove_file(test_file).unwrap();
2147
2148        assert!(result.is_ok());
2149        assert_eq!(result.unwrap(), "sk-relative-key-456");
2150    }
2151
2152    #[test]
2153    fn resolve_api_key_file_url_nonexistent() {
2154        let result = Anthropic::resolve_api_key("file:///nonexistent/path/to/key.txt");
2155        assert!(result.is_err());
2156
2157        let error = result.unwrap_err();
2158        assert!(error.is_validation());
2159        assert!(format!("{}", error).contains("Failed to read API key from file"));
2160    }
2161
2162    #[test]
2163    fn resolve_api_key_file_url_with_whitespace() {
2164        let test_file = "test_whitespace_key.txt";
2165        std::fs::write(test_file, "  sk-whitespace-key-789  \n  ").unwrap();
2166
2167        let file_url = format!("file://{}", test_file);
2168        let result = Anthropic::resolve_api_key(&file_url);
2169
2170        std::fs::remove_file(test_file).unwrap();
2171
2172        assert!(result.is_ok());
2173        assert_eq!(result.unwrap(), "sk-whitespace-key-789");
2174    }
2175
2176    #[test]
2177    fn client_builder_methods() {
2178        let client = Anthropic::new(Some("test_key".to_string())).unwrap();
2179
2180        // Test builder pattern methods
2181        let configured_client = client
2182            .with_base_url("https://custom.api.com".to_string())
2183            .unwrap()
2184            .with_max_retries(5)
2185            .with_backoff_params(2.0, 1.0);
2186
2187        assert_eq!(configured_client.base_url, "https://custom.api.com");
2188        assert_eq!(configured_client.max_retries, 5);
2189        assert_eq!(configured_client.throughput_ops_sec, 2.0);
2190        assert_eq!(configured_client.reserve_capacity, 1.0);
2191    }
2192
2193    #[test]
2194    fn build_url_default_base() {
2195        let client = Anthropic::new(Some("test_key".to_string())).unwrap();
2196        // Default base URL: https://api.anthropic.com
2197        assert_eq!(client.build_url("messages"), "https://api.anthropic.com/v1/messages");
2198        assert_eq!(
2199            client.build_url("messages/count_tokens"),
2200            "https://api.anthropic.com/v1/messages/count_tokens"
2201        );
2202        assert_eq!(client.build_url("models"), "https://api.anthropic.com/v1/models");
2203    }
2204
2205    #[test]
2206    fn build_url_custom_base_without_trailing_slash() {
2207        let client = Anthropic::new(Some("test_key".to_string()))
2208            .unwrap()
2209            .with_base_url("https://api.minimax.io/anthropic".to_string())
2210            .unwrap();
2211        assert_eq!(client.build_url("messages"), "https://api.minimax.io/anthropic/v1/messages");
2212    }
2213
2214    #[test]
2215    fn build_url_custom_base_with_trailing_slash() {
2216        let client = Anthropic::new(Some("test_key".to_string()))
2217            .unwrap()
2218            .with_base_url("https://api.minimax.io/anthropic/".to_string())
2219            .unwrap();
2220        assert_eq!(client.build_url("messages"), "https://api.minimax.io/anthropic/v1/messages");
2221    }
2222
2223    #[test]
2224    fn build_url_minimax_china() {
2225        let client = Anthropic::new(Some("test_key".to_string()))
2226            .unwrap()
2227            .with_base_url("https://api.minimaxi.com/anthropic".to_string())
2228            .unwrap();
2229        assert_eq!(client.build_url("messages"), "https://api.minimaxi.com/anthropic/v1/messages");
2230        assert_eq!(
2231            client.build_url(&format!("models/{}", "claude-3-opus")),
2232            "https://api.minimaxi.com/anthropic/v1/models/claude-3-opus"
2233        );
2234    }
2235
2236    #[test]
2237    fn with_base_url_accepts_https() {
2238        let client = Anthropic::new(Some("placeholder-api-key".to_string()))
2239            .unwrap()
2240            .with_base_url("https://gateway.example.com/anthropic".to_string())
2241            .unwrap();
2242        assert_eq!(client.base_url, "https://gateway.example.com/anthropic");
2243    }
2244
2245    #[test]
2246    fn with_base_url_allows_loopback_http_for_local_dev() {
2247        for url in ["http://localhost:8080", "http://127.0.0.1:8080", "http://[::1]:8080"] {
2248            let client = Anthropic::new(Some("placeholder-api-key".to_string()))
2249                .unwrap()
2250                .with_base_url(url.to_string())
2251                .unwrap_or_else(|e| panic!("loopback url {url} should be accepted: {e}"));
2252            assert_eq!(client.base_url, url);
2253        }
2254    }
2255
2256    #[test]
2257    fn with_base_url_rejects_cleartext_http() {
2258        let err = Anthropic::new(Some("placeholder-api-key".to_string()))
2259            .unwrap()
2260            .with_base_url("http://gateway.internal.example.com".to_string())
2261            .expect_err("a non-loopback http base URL must be rejected");
2262
2263        assert!(err.is_validation(), "expected a validation error, got {err}");
2264        let message = err.to_string();
2265        assert!(
2266            message.contains("unencrypted"),
2267            "error should explain the cleartext risk, got: {message}"
2268        );
2269        assert!(message.contains("'http'"), "error should name the scheme, got: {message}");
2270        assert!(
2271            message.contains("allow_insecure_http"),
2272            "error should name the opt-in, got: {message}"
2273        );
2274    }
2275
2276    #[test]
2277    fn allow_insecure_http_before_with_base_url_accepts_cleartext_http() {
2278        let client = Anthropic::new(Some("placeholder-api-key".to_string()))
2279            .unwrap()
2280            .allow_insecure_http()
2281            .with_base_url("http://10.60.1.20:8080/api/v1/llm/anthropic".to_string())
2282            .unwrap();
2283        assert_eq!(client.base_url, "http://10.60.1.20:8080/api/v1/llm/anthropic");
2284        assert_eq!(
2285            client.build_url("messages"),
2286            "http://10.60.1.20:8080/api/v1/llm/anthropic/v1/messages"
2287        );
2288
2289        let client = Anthropic::new_with_base_url("placeholder-api-key", DEFAULT_API_URL)
2290            .unwrap()
2291            .allow_insecure_http()
2292            .with_base_url_and_timeout(
2293                "http://gateway.corp.internal".to_string(),
2294                Duration::from_secs(5),
2295            )
2296            .unwrap();
2297        assert_eq!(client.base_url, "http://gateway.corp.internal");
2298        assert_eq!(client.timeout, Duration::from_secs(5));
2299    }
2300
2301    #[test]
2302    fn allow_insecure_http_after_with_base_url_is_too_late() {
2303        let err = Anthropic::new(Some("placeholder-api-key".to_string()))
2304            .unwrap()
2305            .with_base_url("http://10.60.1.20:8080".to_string())
2306            .map(Anthropic::allow_insecure_http)
2307            .expect_err("with_base_url validates before the opt-in is set");
2308        assert!(err.is_validation(), "expected a validation error, got {err}");
2309        assert!(
2310            err.to_string().contains("allow_insecure_http"),
2311            "error should name the opt-in, got: {err}"
2312        );
2313    }
2314
2315    #[test]
2316    fn allow_insecure_http_admits_http_only() {
2317        for url in ["ftp://files.example.com", "ws://gateway.example.com", "not-a-url"] {
2318            let err = Anthropic::new(Some("placeholder-api-key".to_string()))
2319                .unwrap()
2320                .allow_insecure_http()
2321                .with_base_url(url.to_string())
2322                .expect_err("the opt-in must not admit other schemes");
2323            assert!(err.is_validation(), "expected a validation error for {url}, got {err}");
2324        }
2325    }
2326
2327    #[test]
2328    fn new_with_base_url_rejection_names_the_opt_in() {
2329        let err = Anthropic::new_with_base_url("placeholder-api-key", "http://10.60.1.20:8080")
2330            .expect_err("a non-loopback http base URL must be rejected");
2331        assert!(
2332            err.to_string().contains("allow_insecure_http"),
2333            "error should name the opt-in, got: {err}"
2334        );
2335    }
2336
2337    #[test]
2338    fn insecure_http_environment() {
2339        const GATEWAY: &str = "http://10.60.1.20:8080/api/v1/llm/anthropic";
2340        if std::env::var_os("ADK_INSECURE_HTTP_ENV_CHILD").is_none() {
2341            let status = std::process::Command::new(std::env::current_exe().unwrap())
2342                .args(["--exact", "client::tests::insecure_http_environment"])
2343                .env("ADK_INSECURE_HTTP_ENV_CHILD", "1")
2344                .env("ANTHROPIC_BASE_URL", GATEWAY)
2345                .env("ANTHROPIC_ALLOW_INSECURE_HTTP", "true")
2346                .status()
2347                .unwrap();
2348            assert!(status.success());
2349            return;
2350        }
2351        let client = Anthropic::new(Some("placeholder-api-key".to_string()))
2352            .expect("ANTHROPIC_ALLOW_INSECURE_HTTP admits the ANTHROPIC_BASE_URL gateway");
2353        assert_eq!(client.base_url(), GATEWAY);
2354
2355        // The environment acknowledges the environment URL only, not URLs given in code.
2356        assert!(!client.allow_insecure_http);
2357        let err = client
2358            .with_base_url("http://gateway.corp.internal".to_string())
2359            .expect_err("a URL given in code needs allow_insecure_http()");
2360        assert!(err.to_string().contains("allow_insecure_http"), "got: {err}");
2361        assert!(Anthropic::new_with_base_url("placeholder-api-key", GATEWAY).is_err());
2362    }
2363
2364    #[test]
2365    fn with_base_url_rejects_non_http_schemes_and_garbage() {
2366        for url in ["ftp://files.example.com", "ws://gateway.example.com", "not-a-url"] {
2367            let err = Anthropic::new(Some("placeholder-api-key".to_string()))
2368                .unwrap()
2369                .with_base_url(url.to_string())
2370                .expect_err("non-https, non-loopback base URL must be rejected");
2371            assert!(err.is_validation(), "expected a validation error for {url}, got {err}");
2372        }
2373    }
2374
2375    // The `ANTHROPIC_BASE_URL` tests exercise `resolve_base_url` directly instead
2376    // of mutating the process environment. The environment is process-global, so
2377    // setting an intentionally-rejected value would race against every other test
2378    // in this binary that calls `Anthropic::new`. `resolve_base_url` is the exact
2379    // code path `Anthropic::new` uses for the env value, so nothing is lost.
2380
2381    #[test]
2382    fn env_base_url_absent_falls_back_to_default() {
2383        let resolved = Anthropic::resolve_base_url(None, None).unwrap();
2384        assert_eq!(resolved, DEFAULT_API_URL);
2385        let resolved = Anthropic::resolve_base_url(None, Some("1".to_string())).unwrap();
2386        assert_eq!(resolved, DEFAULT_API_URL);
2387    }
2388
2389    #[test]
2390    fn env_base_url_accepts_https() {
2391        let resolved = Anthropic::resolve_base_url(
2392            Some("https://gateway.example.com/anthropic".to_string()),
2393            None,
2394        )
2395        .unwrap();
2396        assert_eq!(resolved, "https://gateway.example.com/anthropic");
2397    }
2398
2399    #[test]
2400    fn env_base_url_allows_loopback_http_for_local_dev() {
2401        for url in ["http://localhost:11434", "http://127.0.0.1:11434", "http://[::1]:11434"] {
2402            let resolved = Anthropic::resolve_base_url(Some(url.to_string()), None)
2403                .unwrap_or_else(|e| panic!("loopback url {url} should be accepted: {e}"));
2404            assert_eq!(resolved, url);
2405        }
2406    }
2407
2408    #[test]
2409    fn env_base_url_rejects_cleartext_http() {
2410        for flag in [None, Some("0"), Some("false"), Some("yes"), Some("")] {
2411            let err = Anthropic::resolve_base_url(
2412                Some("http://gateway.internal.example.com".to_string()),
2413                flag.map(str::to_string),
2414            )
2415            .expect_err("a non-loopback http ANTHROPIC_BASE_URL must be rejected");
2416
2417            assert!(err.is_validation(), "expected a validation error, got {err}");
2418            let message = err.to_string();
2419            assert!(
2420                message.contains("unencrypted"),
2421                "error should explain the cleartext risk, got: {message}"
2422            );
2423            assert!(message.contains("'http'"), "error should name the scheme, got: {message}");
2424            assert!(
2425                message.contains("ANTHROPIC_ALLOW_INSECURE_HTTP=1"),
2426                "error should name the environment opt-in for {flag:?}, got: {message}"
2427            );
2428        }
2429    }
2430
2431    #[test]
2432    fn env_base_url_accepts_cleartext_http_when_acknowledged() {
2433        for flag in ["1", "true", "TRUE", " True "] {
2434            let resolved = Anthropic::resolve_base_url(
2435                Some("http://10.60.1.20:8080/api/v1/llm/anthropic".to_string()),
2436                Some(flag.to_string()),
2437            )
2438            .unwrap_or_else(|e| {
2439                panic!("ANTHROPIC_ALLOW_INSECURE_HTTP={flag:?} should admit http: {e}")
2440            });
2441            assert_eq!(resolved, "http://10.60.1.20:8080/api/v1/llm/anthropic");
2442        }
2443    }
2444
2445    #[test]
2446    fn env_base_url_rejects_non_http_schemes_and_garbage() {
2447        for url in ["ftp://files.example.com", "ws://gateway.example.com", "not-a-url"] {
2448            let err = Anthropic::resolve_base_url(Some(url.to_string()), Some("1".to_string()))
2449                .expect_err("non-https, non-loopback ANTHROPIC_BASE_URL must be rejected");
2450            assert!(err.is_validation(), "expected a validation error for {url}, got {err}");
2451        }
2452    }
2453
2454    #[test]
2455    fn with_base_url_and_timeout_rejects_cleartext_http() {
2456        let err = Anthropic::new(Some("placeholder-api-key".to_string()))
2457            .unwrap()
2458            .with_base_url_and_timeout(
2459                "http://gateway.internal.example.com".to_string(),
2460                Duration::from_secs(5),
2461            )
2462            .expect_err("a non-loopback http base URL must be rejected");
2463        assert!(err.is_validation(), "expected a validation error, got {err}");
2464    }
2465
2466    #[test]
2467    fn client_timeout_configuration() {
2468        let client = Anthropic::new(Some("test_key".to_string())).unwrap();
2469        let timeout = Duration::from_secs(30);
2470
2471        let configured_client = client.with_timeout(timeout).unwrap();
2472        assert_eq!(configured_client.timeout, timeout);
2473    }
2474
2475    #[test]
2476    fn client_cached_headers_performance() {
2477        let client = Anthropic::new(Some("test_key".to_string())).unwrap();
2478
2479        // Test that headers are cached and cloning is cheap
2480        let headers1 = client.default_headers();
2481        let headers2 = client.default_headers();
2482
2483        assert_eq!(headers1.len(), headers2.len());
2484        assert!(headers1.contains_key("x-api-key"));
2485        assert!(headers1.contains_key("anthropic-version"));
2486        assert!(headers1.contains_key("content-type"));
2487    }
2488
2489    #[test]
2490    fn request_error_mapping() {
2491        let client = Anthropic::new(Some("test_key".to_string())).unwrap();
2492
2493        // Test different types of reqwest errors are mapped correctly
2494        // Note: These are unit tests for the mapping logic, not integration tests
2495        let _timeout = Duration::from_secs(30);
2496        assert_eq!(client.timeout, DEFAULT_TIMEOUT); // Should use default initially
2497    }
2498
2499    #[test]
2500    fn default_timeout_allows_long_non_streaming_turns() {
2501        let client = Anthropic::new(Some("test_key".to_string())).unwrap();
2502        assert_eq!(client.timeout, Duration::from_secs(600));
2503    }
2504
2505    #[tokio::test]
2506    async fn concurrent_retry_safety() {
2507        use std::sync::atomic::{AtomicUsize, Ordering};
2508        use tokio::spawn;
2509
2510        let client = Anthropic {
2511            api_key: "test".to_string(),
2512            client: ReqwestClient::new(),
2513            stream_client: ReqwestClient::new(),
2514            base_url: "http://localhost".to_string(),
2515            timeout: Duration::from_secs(1),
2516            stream_timeout: None,
2517            idle_timeout: None,
2518            max_retries: 1,
2519            throughput_ops_sec: 1.0,
2520            reserve_capacity: 1.0,
2521            cached_headers: Arc::new(HeaderMap::new()),
2522            allow_insecure_http: false,
2523        };
2524
2525        let attempt_counter = Arc::new(AtomicUsize::new(0));
2526        let mut handles = vec![];
2527
2528        // Spawn multiple concurrent retry operations
2529        for _ in 0..3 {
2530            let client_clone = client.clone();
2531            let counter_clone = attempt_counter.clone();
2532
2533            let handle = spawn(async move {
2534                client_clone
2535                    .retry_with_backoff(|| {
2536                        let counter = counter_clone.clone();
2537                        async move {
2538                            counter.fetch_add(1, Ordering::SeqCst);
2539                            Ok::<String, Error>("success".to_string())
2540                        }
2541                    })
2542                    .await
2543            });
2544            handles.push(handle);
2545        }
2546
2547        // Wait for all operations to complete
2548        for handle in handles {
2549            let result = handle.await.unwrap();
2550            assert!(result.is_ok());
2551        }
2552
2553        // Verify all operations executed
2554        assert_eq!(attempt_counter.load(Ordering::SeqCst), 3);
2555    }
2556}