Skip to main content

typesafeai_sdk/
client.rs

1//! The TypeSafe AI API client.
2//!
3//! Mirrors the Python `TypeSafeClient` and JavaScript `TypeSafeClient`:
4//! a client struct with configurable API key, base URL, default model,
5//! timeout, and retry policy. The primary method is [`TypeSafeClient::system_one`],
6//! which sends a `POST /v1/systemone` request and returns a typed
7//! [`SystemOneResponse`].
8//!
9//! # Example
10//! ```no_run
11//! use typesafeai_sdk::{TypeSafeClient, noul, choice, score};
12//!
13//! # #[tokio::main]
14//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
15//! let client = TypeSafeClient::from_env()?;
16//!
17//! let response = client.system_one(
18//!     "I was charged twice. Please help.",
19//!     [
20//!         ("billing".to_string(), noul("Is this about billing?").into()),
21//!         ("tone".to_string(), choice("What is the tone?", [
22//!             ("calm".to_string(), None),
23//!             ("angry".to_string(), None),
24//!         ].into()).into()),
25//!     ].into(),
26//! ).await?;
27//!
28//! if let Some(answer) = response.noul("billing") {
29//!     println!("{}", answer.noul);
30//! }
31//! # Ok(())
32//! # }
33//! ```
34
35use std::collections::HashMap;
36use std::env;
37use std::fmt;
38use std::time::Duration;
39
40use reqwest::header::{HeaderMap, HeaderName, HeaderValue, ACCEPT, AUTHORIZATION, RETRY_AFTER};
41use reqwest::{redirect, Client as HttpClient, Method, StatusCode};
42use serde_json::Value;
43
44use crate::error::{ErrorKind, Result, TypeSafeError};
45use crate::questions::{validate_questions, Question};
46use crate::retry::{jitter_seed, RetryPolicy};
47use crate::types::{ListModelsResponse, SetMetadata, SystemOneRequest, SystemOneResponse};
48
49/// Maximum response body size to read into memory (1 MiB). Protects against
50/// a malicious or buggy server returning an enormous body that would exhaust
51/// memory.
52const MAX_RESPONSE_BODY_BYTES: usize = 1024 * 1024;
53
54/// Header names that callers may not set via `with_extra_header`. These are
55/// either set by the SDK itself (auth, accept, SDK ID) or are hop-by-hop /
56/// content headers that must not be tampered with.
57const PROTECTED_HEADER_NAMES: &[&str] = &[
58    "authorization",
59    "accept",
60    "x-typesafe-sdk",
61    "content-type",
62    "content-length",
63    "transfer-encoding",
64    "host",
65    "connection",
66    "cookie",
67    "proxy-authorization",
68    "proxy-authenticate",
69    "te",
70    "trailer",
71    "upgrade",
72];
73
74const DEFAULT_BASE_URL: &str = "https://api.typesafe.ai";
75const DEFAULT_MODEL: &str = "jev-latest";
76const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
77const SDK_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));
78const SYSTEM_ONE_PATH: &str = "/v1/systemone";
79const MODELS_PATH: &str = "/v1/models";
80const RETRY_AFTER_MS_HEADER: &str = "retry-after-ms";
81const REQUEST_ID_HEADER: &str = "x-typesafe-request-id";
82/// Maximum number of characters of a response body echoed into an error.
83const MAX_ERROR_BODY_CHARS: usize = 512;
84
85/// Configuration for constructing a [`TypeSafeClient`].
86///
87/// All fields are public for inspection and mutation, but the struct is
88/// `#[non_exhaustive]`, so external crates must use [`ClientConfig::new`]
89/// or [`ClientConfig::default`] plus the builder methods to construct
90/// configurations.
91#[derive(Clone)]
92#[non_exhaustive]
93pub struct ClientConfig {
94    /// API key for authentication.
95    ///
96    /// Set this directly or use [`TypeSafeClient::from_env`] to read it
97    /// from the `TYPESAFE_API_KEY` environment variable.
98    pub api_key: String,
99    /// API root. Defaults to `https://api.typesafe.ai`.
100    ///
101    /// A base path is supported and preserved: e.g. `https://example.com/api`
102    /// produces endpoints like `https://example.com/api/v1/systemone`.
103    /// Credentials, query parameters, and fragments are rejected.
104    pub base_url: String,
105    /// Default model. Defaults to `jev-latest`.
106    pub default_model: String,
107    /// Per-attempt timeout. Defaults to 10 seconds.
108    pub timeout: Duration,
109    /// Retry policy. Defaults to 2 retries with exponential backoff + jitter.
110    pub retry: RetryPolicy,
111    /// Custom `reqwest::Client` to use for HTTP requests. If `None`, a new
112    /// client is built from the other config fields. This allows sharing a
113    /// connection pool or using a custom TLS configuration.
114    pub http_client: Option<HttpClient>,
115}
116
117impl Default for ClientConfig {
118    /// Create a `ClientConfig` with all fields at their defaults.
119    ///
120    /// **Note:** `api_key` defaults to an empty string, which will cause
121    /// [`TypeSafeClient::from_config`] to return an
122    /// [`Authentication`](ErrorKind::Authentication) error on the first
123    /// request. Use [`ClientConfig::new`] or set `api_key` explicitly
124    /// before constructing a client.
125    fn default() -> Self {
126        Self {
127            api_key: String::new(),
128            base_url: DEFAULT_BASE_URL.to_string(),
129            default_model: DEFAULT_MODEL.to_string(),
130            timeout: DEFAULT_TIMEOUT,
131            retry: RetryPolicy::default(),
132            http_client: None,
133        }
134    }
135}
136
137impl ClientConfig {
138    /// Create a new `ClientConfig` with the given API key and all other
139    /// fields set to their defaults.
140    ///
141    /// Use the `.with_*()` methods to override individual fields.
142    #[must_use]
143    pub fn new(api_key: impl Into<String>) -> Self {
144        Self {
145            api_key: api_key.into(),
146            ..Self::default()
147        }
148    }
149
150    /// Set the API key.
151    #[must_use]
152    pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
153        self.api_key = api_key.into();
154        self
155    }
156
157    /// Set the base URL.
158    #[must_use]
159    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
160        self.base_url = base_url.into();
161        self
162    }
163
164    /// Set the default model.
165    #[must_use]
166    pub fn with_default_model(mut self, default_model: impl Into<String>) -> Self {
167        self.default_model = default_model.into();
168        self
169    }
170
171    /// Set the per-attempt timeout.
172    ///
173    /// This is the timeout for a single HTTP request, not the total time
174    /// across all retries. The first attempt always uses the full configured
175    /// timeout; subsequent attempts are capped at the remaining retry budget
176    /// (if set). See [`RetryPolicy::budget`](crate::RetryPolicy::budget).
177    #[must_use]
178    pub fn with_timeout(mut self, timeout: Duration) -> Self {
179        self.timeout = timeout;
180        self
181    }
182
183    /// Set the retry policy.
184    #[must_use]
185    pub fn with_retry(mut self, retry: RetryPolicy) -> Self {
186        self.retry = retry;
187        self
188    }
189
190    /// Provide a custom `reqwest::Client` for HTTP requests. If not set, the
191    /// client builds one from the other config fields (timeout, default
192    /// headers). Use this to share a connection pool or apply custom TLS
193    /// settings.
194    ///
195    /// The client is used as-is, so the caller controls redirect behavior.
196    /// The SDK's default client disables redirects to prevent POST replay
197    /// via 307/308; a custom client that follows redirects does not have
198    /// this protection.
199    #[must_use]
200    pub fn with_http_client(mut self, client: HttpClient) -> Self {
201        self.http_client = Some(client);
202        self
203    }
204}
205
206impl fmt::Debug for ClientConfig {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        f.debug_struct("ClientConfig")
209            .field("api_key", &"<redacted>")
210            .field("base_url", &self.base_url)
211            .field("default_model", &self.default_model)
212            .field("timeout", &self.timeout)
213            .field("retry", &self.retry)
214            .field("http_client", &self.http_client.is_some())
215            .finish()
216    }
217}
218
219/// Client for the TypeSafe AI API.
220///
221/// Construct with [`TypeSafeClient::new`] or [`TypeSafeClient::from_env`].
222/// Cloning is cheap and shares the underlying connection pool.
223#[derive(Clone)]
224#[non_exhaustive]
225pub struct TypeSafeClient {
226    config: ClientConfig,
227    http: HttpClient,
228    /// The pre-built `Authorization: Bearer <key>` header value, stored so it
229    /// can be attached per-request even when the caller supplies a custom
230    /// `reqwest::Client` (whose default headers we cannot modify).
231    auth_header: HeaderValue,
232}
233
234impl fmt::Debug for TypeSafeClient {
235    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236        f.debug_struct("TypeSafeClient")
237            .field("config", &self.config)
238            .finish_non_exhaustive()
239    }
240}
241
242/// A failed attempt, carrying the server's `Retry-After` hint (if any) so the
243/// retry loop can honour it. Internal: the public API only exposes
244/// [`TypeSafeError`].
245struct Failure {
246    error: TypeSafeError,
247    retry_after: Option<Duration>,
248}
249
250impl From<TypeSafeError> for Failure {
251    fn from(error: TypeSafeError) -> Self {
252        Self {
253            error,
254            retry_after: None,
255        }
256    }
257}
258
259/// Internal per-call options passed through the retry loop.
260/// `None` fields mean "use the client default".
261struct CallOpts {
262    extra_headers: Vec<(String, String)>,
263    timeout: Option<Duration>,
264    retry: Option<RetryPolicy>,
265}
266
267impl CallOpts {
268    /// Create an empty options set (use all client defaults).
269    fn empty() -> Self {
270        Self {
271            extra_headers: Vec::new(),
272            timeout: None,
273            retry: None,
274        }
275    }
276}
277
278/// Per-call options for [`TypeSafeClient::system_one_with_opts`].
279///
280/// Built with a builder pattern. Start with [`SystemOneOpts::new`] and chain
281/// `.with_*()` methods. Fields not set use the client's defaults.
282///
283/// # Example
284/// ```no_run
285/// use typesafeai_sdk::SystemOneOpts;
286/// use std::time::Duration;
287///
288/// let opts = SystemOneOpts::new()
289///     .with_model(Some("jev-latest".to_string()))
290///     .with_state("I was charged twice.")
291///     .with_extra_body(serde_json::json!({"priority": "high"}))
292///     .with_timeout(Duration::from_secs(30))
293///     .with_extra_header("X-Trace-Id", "abc123");
294/// ```
295#[derive(Clone, Default)]
296#[non_exhaustive]
297pub struct SystemOneOpts {
298    /// Override the client's default model for this call.
299    pub(crate) model: Option<String>,
300    /// The state to evaluate. If not set, defaults to `null`.
301    pub(crate) state: Option<Value>,
302    /// Extra fields to merge into the request body for forward compatibility.
303    /// Reserved keys (`state`, `model`, `questions`) are rejected; use the
304    /// dedicated methods instead. Object values are replaced rather than
305    /// deep-merged.
306    pub(crate) extra_body: Option<Value>,
307    /// Additional headers to send with this call only.
308    pub(crate) extra_headers: Vec<(String, String)>,
309    /// Per-call timeout override. `None` uses the client default.
310    pub(crate) timeout: Option<Duration>,
311    /// Per-call retry policy override. `None` uses the client default.
312    pub(crate) retry: Option<RetryPolicy>,
313}
314
315impl fmt::Debug for SystemOneOpts {
316    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317        f.debug_struct("SystemOneOpts")
318            .field("model", &self.model)
319            // Redact state — it may contain sensitive user data.
320            .field("state", &self.state.as_ref().map(|_| "<redacted>"))
321            // Redact extra_body — it may contain sensitive user data.
322            .field(
323                "extra_body",
324                &self.extra_body.as_ref().map(|_| "<redacted>"),
325            )
326            // Redact header values — they may contain tokens.
327            .field(
328                "extra_headers",
329                &self
330                    .extra_headers
331                    .iter()
332                    .map(|(k, _)| (k.as_str(), "<redacted>"))
333                    .collect::<Vec<_>>(),
334            )
335            .field("timeout", &self.timeout)
336            .field("retry", &self.retry)
337            .finish()
338    }
339}
340
341impl SystemOneOpts {
342    /// Create a new empty options set (all fields use client defaults).
343    #[must_use = "the returned SystemOneOpts should be used"]
344    pub fn new() -> Self {
345        Self::default()
346    }
347
348    /// Override the model for this call. `None` uses the client default.
349    #[must_use = "the returned SystemOneOpts should be used"]
350    pub fn with_model(mut self, model: Option<impl Into<String>>) -> Self {
351        self.model = model.map(|m| m.into());
352        self
353    }
354
355    /// Set the state to evaluate. Accepts a string, JSON object, or array.
356    #[must_use = "the returned SystemOneOpts should be used"]
357    pub fn with_state(mut self, state: impl Into<Value>) -> Self {
358        self.state = Some(state.into());
359        self
360    }
361
362    /// Set extra fields to merge into the request body for forward
363    /// compatibility. Reserved keys (`state`, `model`, `questions`) are
364    /// rejected with a validation error — use the dedicated methods
365    /// (`with_state`, `with_model`, or the `questions` argument) instead.
366    /// Object values are replaced rather than deep-merged.
367    #[must_use = "the returned SystemOneOpts should be used"]
368    pub fn with_extra_body(mut self, extra: Value) -> Self {
369        self.extra_body = Some(extra);
370        self
371    }
372
373    /// Add a custom header to send with this call only. Headers set here
374    /// are applied on top of the client's default headers. Authentication,
375    /// `Accept`, and SDK identification headers remain protected and cannot
376    /// be overridden.
377    ///
378    /// Can be called multiple times to add multiple headers.
379    #[must_use = "the returned SystemOneOpts should be used"]
380    pub fn with_extra_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
381        self.extra_headers.push((name.into(), value.into()));
382        self
383    }
384
385    /// Override the timeout for this call only. `None` uses the client default.
386    #[must_use = "the returned SystemOneOpts should be used"]
387    pub fn with_timeout(mut self, timeout: Duration) -> Self {
388        self.timeout = Some(timeout);
389        self
390    }
391
392    /// Override the retry policy for this call only. `None` uses the client
393    /// default.
394    #[must_use = "the returned SystemOneOpts should be used"]
395    pub fn with_retry(mut self, retry: RetryPolicy) -> Self {
396        self.retry = Some(retry);
397        self
398    }
399}
400
401impl TypeSafeClient {
402    /// Create a new client with the given API key and default settings.
403    #[must_use = "the returned client should be used to make API calls"]
404    pub fn new(api_key: impl Into<String>) -> Result<Self> {
405        let config = ClientConfig {
406            api_key: api_key.into(),
407            ..ClientConfig::default()
408        };
409        Self::from_config(config)
410    }
411
412    /// Create a new client from a full [`ClientConfig`].
413    #[must_use = "the returned client should be used to make API calls"]
414    pub fn from_config(mut config: ClientConfig) -> Result<Self> {
415        // Trim whitespace: a stray newline from an env file would otherwise
416        // become an opaque transport error.
417        config.api_key = config.api_key.trim().to_string();
418
419        if config.api_key.is_empty() {
420            return Err(TypeSafeError::new(ErrorKind::Validation(
421                "No API key was provided. Pass an API key to `TypeSafeClient::new` or set the `TYPESAFE_API_KEY` environment variable."
422                    .to_string(),
423            )));
424        }
425
426        // Normalize the base URL: trim trailing slash and validate scheme/host.
427        config.base_url = config.base_url.trim().trim_end_matches('/').to_string();
428        validate_base_url(&config.base_url)?;
429
430        // Validate the default model name.
431        if config.default_model.trim().is_empty() {
432            return Err(TypeSafeError::new(ErrorKind::Validation(
433                "Default model name cannot be empty.".to_string(),
434            )));
435        }
436
437        // Build the auth header once. Marking it sensitive keeps the key out
438        // of reqwest's debug output.
439        let mut auth =
440            HeaderValue::from_str(&format!("Bearer {}", config.api_key)).map_err(|_| {
441                TypeSafeError::new(ErrorKind::Validation(
442                    "The API key contains characters that are not valid in an HTTP header."
443                        .to_string(),
444                ))
445            })?;
446        auth.set_sensitive(true);
447
448        let mut headers = HeaderMap::new();
449        headers.insert(AUTHORIZATION, auth.clone());
450        headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
451        headers.insert(
452            HeaderName::from_static("x-typesafe-sdk"),
453            HeaderValue::from_static(SDK_USER_AGENT),
454        );
455
456        // Use the caller-provided HTTP client if given; otherwise build one
457        // from the config. A provided client is used as-is so the caller
458        // controls TLS, proxies, connection pools, etc. Auth and SDK headers
459        // are attached per-request in `attempt_request` so they work with both
460        // paths.
461        let http = match config.http_client.take() {
462            Some(client) => client,
463            None => HttpClient::builder()
464                .timeout(config.timeout)
465                .user_agent(SDK_USER_AGENT)
466                .default_headers(headers)
467                // Never follow redirects: a 307/308 would replay the POST body
468                // (and the Authorization header) to a potentially different host.
469                .redirect(redirect::Policy::none())
470                .build()
471                .map_err(|e| TypeSafeError::new(ErrorKind::Transport(e.to_string())))?,
472        };
473
474        Ok(Self {
475            config,
476            http,
477            auth_header: auth,
478        })
479    }
480
481    /// Create a new client, reading the API key from the `TYPESAFE_API_KEY`
482    /// environment variable. Also reads `TYPESAFE_BASE_URL` and
483    /// `TYPESAFE_DEFAULT_MODEL` if set.
484    #[must_use = "the returned client should be used to make API calls"]
485    pub fn from_env() -> Result<Self> {
486        let api_key = env::var("TYPESAFE_API_KEY").unwrap_or_default();
487        let mut config = ClientConfig {
488            api_key,
489            ..ClientConfig::default()
490        };
491
492        if let Ok(base) = env::var("TYPESAFE_BASE_URL") {
493            if !base.trim().is_empty() {
494                config.base_url = base;
495            }
496        }
497
498        if let Ok(model) = env::var("TYPESAFE_DEFAULT_MODEL") {
499            if !model.trim().is_empty() {
500                config.default_model = model;
501            }
502        }
503
504        Self::from_config(config)
505    }
506
507    /// Returns the base URL this client is configured to use.
508    pub fn base_url(&self) -> &str {
509        &self.config.base_url
510    }
511
512    /// Returns the default model this client uses.
513    pub fn default_model(&self) -> &str {
514        &self.config.default_model
515    }
516
517    // -----------------------------------------------------------------------
518    // system_one
519    // -----------------------------------------------------------------------
520
521    /// Answer named questions about text or structured state.
522    ///
523    /// Sends a `POST /v1/systemone` request and returns a typed
524    /// [`SystemOneResponse`].
525    ///
526    /// # Arguments
527    /// - `state` — text, a JSON object, or an array to evaluate. Accepts
528    ///   `&str`, `String`, or any `serde_json::Value`.
529    /// - `questions` — a non-empty map of question names to [`Question`]s.
530    ///
531    /// Use [`system_one_with_model`](Self::system_one_with_model) to override
532    /// the client's default model.
533    ///
534    /// # Retry safety
535    ///
536    /// This is a `POST` request. The SDK automatically retries on transient
537    /// failures (408, 429, 500, 502, 503, 504, 529, connection errors,
538    /// timeouts), but a timeout does
539    /// not guarantee the server did not process the request. If the endpoint
540    /// has side effects (credit consumption, usage recording, downstream
541    /// triggers), a retry may result in duplicate processing. Future versions
542    /// will support an `Idempotency-Key` header to make retries safe.
543    ///
544    /// To avoid replaying a POST whose body the server already processed,
545    /// errors that occur while *reading the response body* — including
546    /// timeouts and truncated bodies — are classified as non-retryable
547    /// [`ErrorKind::Transport`] rather than [`ErrorKind::Connection`]
548    /// or [`ErrorKind::Timeout`].
549    ///
550    /// # Errors
551    /// - [`ErrorKind::Validation`] if questions are empty or a choice or
552    ///   score question has fewer than two criteria.
553    /// - [`ErrorKind::Authentication`] if the API key is invalid.
554    /// - [`ErrorKind::RateLimit`] if rate-limited (after retries).
555    /// - [`ErrorKind::Connection`] / [`ErrorKind::Timeout`] on
556    ///   network failures (after retries).
557    pub async fn system_one(
558        &self,
559        state: impl Into<Value>,
560        questions: HashMap<String, Question>,
561    ) -> Result<SystemOneResponse> {
562        self.system_one_with_model(state, questions, None).await
563    }
564
565    /// Like [`system_one`](Self::system_one) but with an explicit model
566    /// override (`None` uses the client default).
567    pub async fn system_one_with_model(
568        &self,
569        state: impl Into<Value>,
570        questions: HashMap<String, Question>,
571        model: Option<&str>,
572    ) -> Result<SystemOneResponse> {
573        let opts = SystemOneOpts::new().with_model(model).with_state(state);
574        self.system_one_with_opts(questions, opts).await
575    }
576
577    /// Like [`system_one`](Self::system_one) but with full per-call options
578    /// via a [`SystemOneOpts`] builder.
579    ///
580    /// This allows overriding the model, adding extra body fields for
581    /// forward compatibility, and attaching custom headers — all per-call.
582    ///
583    /// # Example
584    /// ```no_run
585    /// use typesafeai_sdk::{TypeSafeClient, noul, SystemOneOpts};
586    /// use std::collections::HashMap;
587    ///
588    /// # #[tokio::main]
589    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
590    /// let client = TypeSafeClient::from_env()?;
591    /// let mut questions = HashMap::new();
592    /// questions.insert("billing".to_string(), noul("Is this about billing?").into());
593    ///
594    /// let opts = SystemOneOpts::new()
595    ///     .with_model(Some("jev-latest".to_string()))
596    ///     .with_extra_body(serde_json::json!({"user_id": "u123"}));
597    ///
598    /// let response = client.system_one_with_opts(questions, opts).await?;
599    /// # Ok(())
600    /// # }
601    /// ```
602    pub async fn system_one_with_opts(
603        &self,
604        questions: HashMap<String, Question>,
605        opts: SystemOneOpts,
606    ) -> Result<SystemOneResponse> {
607        validate_questions(&questions)?;
608
609        let model_name = opts
610            .model
611            .unwrap_or_else(|| self.config.default_model.clone());
612        if model_name.trim().is_empty() {
613            return Err(TypeSafeError::new(ErrorKind::Validation(
614                "Model name cannot be empty.".to_string(),
615            )));
616        }
617
618        let request = SystemOneRequest {
619            state: opts.state.unwrap_or(Value::Null),
620            model: model_name,
621            questions,
622        };
623
624        let mut body = serde_json::to_value(&request)?;
625
626        // Merge extra_body fields at the top level for forward compatibility.
627        // Reserved keys (state, model, questions) are rejected outright so
628        // that extra_body cannot override or bypass validation of the known
629        // fields.
630        if let Some(extra) = &opts.extra_body {
631            let extra_obj = extra.as_object().ok_or_else(|| {
632                TypeSafeError::new(ErrorKind::Validation(
633                    "extra_body must be a JSON object.".to_string(),
634                ))
635            })?;
636            const RESERVED_KEYS: &[&str] = &["state", "model", "questions"];
637            for key in extra_obj.keys() {
638                if RESERVED_KEYS.contains(&key.as_str()) {
639                    return Err(TypeSafeError::new(ErrorKind::Validation(format!(
640                        "extra_body cannot override reserved key `{key}`. \
641                         Use the dedicated method (with_state, with_model, or the \
642                         questions argument) instead."
643                    ))));
644                }
645            }
646            let body_obj = body.as_object_mut().ok_or_else(|| {
647                TypeSafeError::new(ErrorKind::Validation(
648                    "Internal error: request body is not a JSON object.".to_string(),
649                ))
650            })?;
651            for (k, v) in extra_obj {
652                body_obj.insert(k.clone(), v.clone());
653            }
654        }
655
656        let call_opts = CallOpts {
657            extra_headers: opts.extra_headers,
658            timeout: opts.timeout,
659            retry: opts.retry,
660        };
661
662        self.request_with_retry_opts(Method::POST, SYSTEM_ONE_PATH, Some(body), &call_opts)
663            .await
664    }
665
666    // -----------------------------------------------------------------------
667    // models
668    // -----------------------------------------------------------------------
669
670    /// List available models. Sends `GET /v1/models`.
671    pub async fn list_models(&self) -> Result<ListModelsResponse> {
672        self.request_with_retry_opts(Method::GET, MODELS_PATH, None, &CallOpts::empty())
673            .await
674    }
675
676    // -----------------------------------------------------------------------
677    // Internal HTTP + retry
678    // -----------------------------------------------------------------------
679
680    async fn request_with_retry_opts<T: serde::de::DeserializeOwned + SetMetadata>(
681        &self,
682        method: Method,
683        path: &str,
684        body: Option<Value>,
685        opts: &CallOpts,
686    ) -> Result<T> {
687        let url = format!("{}{}", self.config.base_url, path);
688        let retry = opts.retry.as_ref().unwrap_or(&self.config.retry);
689        let timeout = opts.timeout.unwrap_or(self.config.timeout);
690
691        let started = std::time::Instant::now();
692        let mut attempt = 0;
693        let mut last_error: Option<TypeSafeError> = None;
694        loop {
695            // The first attempt (attempt == 0) always uses the full configured
696            // timeout — the budget should not shorten the initial request.
697            // On subsequent attempts, cap the timeout at the remaining budget
698            // so a single retry cannot push the total elapsed time past it.
699            let attempt_timeout = if attempt == 0 {
700                timeout
701            } else {
702                match retry.budget {
703                    Some(budget) => {
704                        let remaining = budget.saturating_sub(started.elapsed());
705                        if remaining.is_zero() {
706                            // Budget exhausted — return the last real error,
707                            // not a synthetic Timeout. `last_error` is always
708                            // `Some` here because this branch only runs on
709                            // retries (attempt > 0), and `last_error` is set
710                            // before every sleep.
711                            return Err(last_error.expect("last_error must be set on a retry"));
712                        }
713                        std::cmp::min(timeout, remaining)
714                    }
715                    None => timeout,
716                }
717            };
718
719            match self
720                .attempt_request(&method, &url, body.as_ref(), opts, attempt_timeout)
721                .await
722            {
723                Ok(resp) => return Ok(resp),
724                Err(failure) => {
725                    let err = failure.error;
726
727                    if !err.is_retryable() || attempt >= retry.max_retries {
728                        return Err(err);
729                    }
730
731                    let delay = match failure.retry_after {
732                        // Honour the server's hint, unless it asks us to wait
733                        // longer than `max_delay`: then give up instead of
734                        // stalling the caller.
735                        Some(hint) => match retry.delay_for_retry_after(attempt, hint) {
736                            Some(delay) => delay,
737                            None => return Err(err),
738                        },
739                        None => retry.delay_for_with_jitter(attempt, jitter_seed()),
740                    };
741
742                    // Stop before a delay that would exceed the budget.
743                    // Return the last real error, not a synthetic Timeout.
744                    if retry.budget_exceeded(started.elapsed(), delay) {
745                        return Err(err);
746                    }
747
748                    // Require a minimum useful attempt window after sleeping.
749                    // If the remaining budget after the delay is too small to
750                    // be useful (less than 10% of the configured timeout, or
751                    // less than 100ms), don't bother sleeping and retrying —
752                    // return the last real error.
753                    if let Some(budget) = retry.budget {
754                        let remaining_after_delay =
755                            budget.saturating_sub(started.elapsed().saturating_add(delay));
756                        let min_window = std::cmp::max(
757                            Duration::from_millis(100),
758                            Duration::from_millis(timeout.as_millis() as u64 / 10),
759                        );
760                        if remaining_after_delay < min_window {
761                            return Err(err);
762                        }
763                    }
764
765                    last_error = Some(err);
766                    tokio::time::sleep(delay).await;
767                    attempt += 1;
768                }
769            }
770        }
771    }
772
773    async fn attempt_request<T: serde::de::DeserializeOwned + SetMetadata>(
774        &self,
775        method: &Method,
776        url: &str,
777        body: Option<&Value>,
778        opts: &CallOpts,
779        timeout: Duration,
780    ) -> std::result::Result<T, Failure> {
781        // Attach auth, Accept, and SDK headers per-request so they are present
782        // even when the caller supplies a custom `reqwest::Client` whose
783        // default headers we cannot modify.
784        let mut request = self
785            .http
786            .request(method.clone(), url)
787            .timeout(timeout)
788            .header(AUTHORIZATION, &self.auth_header)
789            .header(ACCEPT, "application/json")
790            .header("x-typesafe-sdk", SDK_USER_AGENT);
791
792        if let Some(b) = body {
793            request = request.json(b);
794        }
795
796        // Apply per-call extra headers. Protected headers are rejected with an
797        // error to prevent accidental credential leakage, SDK identification
798        // removal, or content/header corruption.
799        for (name, value) in &opts.extra_headers {
800            let lower = name.to_ascii_lowercase();
801            if PROTECTED_HEADER_NAMES.contains(&lower.as_str()) {
802                return Err(Failure::from(TypeSafeError::new(ErrorKind::Validation(
803                    format!(
804                        "Header `{name}` is protected and cannot be set via with_extra_header."
805                    ),
806                ))));
807            }
808            let hn = HeaderName::try_from(name.as_str()).map_err(|_| {
809                Failure::from(TypeSafeError::new(ErrorKind::Validation(format!(
810                    "Invalid header name: {name}"
811                ))))
812            })?;
813            let hv = HeaderValue::try_from(value.as_str()).map_err(|_| {
814                Failure::from(TypeSafeError::new(ErrorKind::Validation(format!(
815                    "Invalid header value for `{name}`: contains invalid characters."
816                ))))
817            })?;
818            request = request.header(hn, hv);
819        }
820
821        let response = request
822            .send()
823            .await
824            .map_err(|e| map_reqwest_error(e, timeout))?;
825
826        self.parse_response(response).await
827    }
828
829    async fn parse_response<T: serde::de::DeserializeOwned + SetMetadata>(
830        &self,
831        response: reqwest::Response,
832    ) -> std::result::Result<T, Failure> {
833        let status = response.status();
834        let headers = response.headers();
835        // Capture the request ID for both success and error paths.
836        let request_id = headers
837            .get(REQUEST_ID_HEADER)
838            .and_then(|v| v.to_str().ok())
839            .map(|s| s.to_string());
840        // Prefer retry-after-ms (milliseconds, more precise) over the
841        // standard Retry-After (seconds). Either may be absent.
842        let retry_after = headers
843            .get(RETRY_AFTER_MS_HEADER)
844            .and_then(|v| v.to_str().ok())
845            .and_then(parse_retry_after_ms)
846            .or_else(|| {
847                headers
848                    .get(RETRY_AFTER)
849                    .and_then(|v| v.to_str().ok())
850                    .and_then(parse_retry_after)
851            });
852
853        // Classify the status code into an `ErrorKind` once, using a single
854        // source of truth. For error statuses, the body is only used for the
855        // message — the kind is determined by the status code alone.
856        if let Some(kind) = Self::kind_for_status(status) {
857            // For error statuses, read the body for the message. If the body
858            // read itself fails (timeout, oversized), still return the error
859            // classified from the status code — the status is authoritative.
860            let text = match read_body_capped(response, MAX_RESPONSE_BODY_BYTES).await {
861                Ok(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
862                Err(_) => String::new(),
863            };
864            let message = Self::extract_error_message(&text)
865                .map(|m| truncate(&m, MAX_ERROR_BODY_CHARS))
866                .unwrap_or_else(|| truncate(&text, MAX_ERROR_BODY_CHARS));
867            let kind = Self::with_message(kind, message);
868            return Err(Failure {
869                error: TypeSafeError::with_request_id(kind, request_id),
870                retry_after,
871            });
872        }
873
874        // Read the body with a size cap to protect against unbounded memory
875        // consumption from a malicious or buggy server.
876        let bytes = read_body_capped(response, MAX_RESPONSE_BODY_BYTES).await?;
877        let text = String::from_utf8_lossy(&bytes);
878
879        if status.is_success() {
880            // Parse once into a `Value`, then deserialize `T` from it so we
881            // can reuse the same `Value` for the `raw` field without a second
882            // parse.
883            let raw: Value = serde_json::from_str(&text).map_err(|e| {
884                Failure::from(TypeSafeError::new(ErrorKind::ResponseValidation {
885                    message: format!(
886                        "Failed to parse response body: {e}\nBody: {}",
887                        truncate(&text, MAX_ERROR_BODY_CHARS)
888                    ),
889                    field_path: None,
890                }))
891            })?;
892            let mut result: T = T::deserialize(&raw).map_err(|e| {
893                Failure::from(TypeSafeError::new(ErrorKind::ResponseValidation {
894                    message: format!(
895                        "Failed to parse response body: {e}\nBody: {}",
896                        truncate(&text, MAX_ERROR_BODY_CHARS)
897                    ),
898                    field_path: None,
899                }))
900            })?;
901            // Inject the request ID (only if the header was present) and raw
902            // body into the response type via the trait.
903            result.set_metadata(request_id, Some(raw));
904            return Ok(result);
905        }
906
907        // This should be unreachable — all non-success statuses are handled
908        // by kind_for_status above. But just in case, return a generic API
909        // error.
910        let kind = ErrorKind::Api {
911            status: status.as_u16(),
912            message: String::new(),
913        };
914        Err(Failure {
915            error: TypeSafeError::with_request_id(kind, request_id),
916            retry_after,
917        })
918    }
919
920    /// Classify an HTTP status code into an `ErrorKind`. Returns `None` for
921    /// success statuses (2xx). This is the single source of truth for
922    /// status-to-kind mapping — both the retry decision (via
923    /// `ErrorKind::is_retryable`) and the error variant are derived from
924    /// this, so they can never drift apart.
925    fn kind_for_status(status: StatusCode) -> Option<ErrorKind> {
926        // All 2xx statuses are success — no error. Using `is_success()`
927        // instead of a hardcoded list ensures we don't miss codes like 203,
928        // 205, or 208.
929        if status.is_success() {
930            return None;
931        }
932
933        match status {
934            // Client errors.
935            StatusCode::UNAUTHORIZED => Some(ErrorKind::Authentication(String::new())),
936            StatusCode::BAD_REQUEST => Some(ErrorKind::BadRequest(String::new())),
937            StatusCode::NOT_FOUND => Some(ErrorKind::NotFound(String::new())),
938            StatusCode::UNPROCESSABLE_ENTITY => Some(ErrorKind::UnprocessableEntity(String::new())),
939            StatusCode::REQUEST_TIMEOUT => Some(ErrorKind::RequestTimeout(String::new())),
940
941            // Retryable server errors.
942            StatusCode::TOO_MANY_REQUESTS => Some(ErrorKind::RateLimit(String::new())),
943            StatusCode::INTERNAL_SERVER_ERROR
944            | StatusCode::BAD_GATEWAY
945            | StatusCode::SERVICE_UNAVAILABLE
946            | StatusCode::GATEWAY_TIMEOUT => Some(ErrorKind::InternalServer(String::new())),
947
948            // Everything else.
949            _ if status.as_u16() == 529 => Some(ErrorKind::Overloaded(String::new())),
950            _ => Some(ErrorKind::Api {
951                status: status.as_u16(),
952                message: String::new(),
953            }),
954        }
955    }
956
957    /// Inject a message into an `ErrorKind` that was classified from the
958    /// status code. This avoids re-matching the status — the kind is already
959    /// determined, we just fill in the message.
960    fn with_message(kind: ErrorKind, message: String) -> ErrorKind {
961        match kind {
962            ErrorKind::Authentication(_) => ErrorKind::Authentication(message),
963            ErrorKind::BadRequest(_) => ErrorKind::BadRequest(message),
964            ErrorKind::NotFound(_) => ErrorKind::NotFound(message),
965            ErrorKind::UnprocessableEntity(_) => ErrorKind::UnprocessableEntity(message),
966            ErrorKind::RequestTimeout(_) => ErrorKind::RequestTimeout(message),
967            ErrorKind::RateLimit(_) => ErrorKind::RateLimit(message),
968            ErrorKind::InternalServer(_) => ErrorKind::InternalServer(message),
969            ErrorKind::Overloaded(_) => ErrorKind::Overloaded(message),
970            ErrorKind::Api { status, .. } => ErrorKind::Api { status, message },
971            other => other,
972        }
973    }
974
975    /// Try to extract a human-readable error message from the response body.
976    /// The API typically returns `{"error": {"message": "..."}}` or
977    /// `{"detail": "..."}`.
978    fn extract_error_message(text: &str) -> Option<String> {
979        let value: Value = serde_json::from_str(text).ok()?;
980        let obj = value.as_object()?;
981        if let Some(error) = obj.get("error") {
982            if let Some(msg) = error.get("message").and_then(|m| m.as_str()) {
983                return Some(msg.to_string());
984            }
985            if let Some(msg) = error.as_str() {
986                return Some(msg.to_string());
987            }
988        }
989        if let Some(detail) = obj.get("detail").and_then(|d| d.as_str()) {
990            return Some(detail.to_string());
991        }
992        if let Some(message) = obj.get("message").and_then(|m| m.as_str()) {
993            return Some(message.to_string());
994        }
995        None
996    }
997}
998
999// ---------------------------------------------------------------------------
1000// Helpers
1001// ---------------------------------------------------------------------------
1002
1003/// Read the response body into a `Vec<u8>` with a maximum size cap.
1004/// Returns `Err` if the body exceeds `max_bytes`, using a transport error.
1005async fn read_body_capped(
1006    response: reqwest::Response,
1007    max_bytes: usize,
1008) -> std::result::Result<Vec<u8>, TypeSafeError> {
1009    let mut bytes = Vec::new();
1010    let mut resp = response;
1011    loop {
1012        match resp.chunk().await {
1013            Ok(Some(chunk)) => {
1014                if bytes.len() + chunk.len() > max_bytes {
1015                    return Err(TypeSafeError::new(ErrorKind::Transport(format!(
1016                        "response body exceeds maximum size of {max_bytes} bytes"
1017                    ))));
1018                }
1019                bytes.extend_from_slice(&chunk);
1020            }
1021            Ok(None) => break,
1022            Err(e) => return Err(TypeSafeError::new(ErrorKind::Transport(e.to_string()))),
1023        }
1024    }
1025    Ok(bytes)
1026}
1027
1028/// Map a `reqwest` error to the appropriate `TypeSafeError` variant.
1029///
1030/// - timeouts -> [`ErrorKind::Timeout`], reporting the *configured* timeout
1031/// - connect failures (refused, reset, DNS) -> [`ErrorKind::Connection`]
1032/// - everything else (body read, builder, redirect, decode, request
1033///   construction) is deterministic or occurs after the server has already
1034///   processed the request, so it stays a non-retryable
1035///   [`ErrorKind::Transport`]
1036///
1037/// `is_request()` and `is_body()` are intentionally **not** classified as
1038/// `Connection`. `is_request()` covers the entire request lifecycle, including
1039/// non-retryable errors like builder failures, redirect loops, and decode
1040/// errors. `is_body()` indicates a failure while *reading the response body*,
1041/// which happens **after** the server has already received and processed the
1042/// request — retrying a POST in that state risks duplicate side effects.
1043/// Only `is_connect()` (pre-request network failure) is retryable.
1044fn map_reqwest_error(e: reqwest::Error, timeout: Duration) -> TypeSafeError {
1045    if e.is_timeout() {
1046        TypeSafeError::new(ErrorKind::Timeout(timeout))
1047    } else if e.is_connect() {
1048        TypeSafeError::new(ErrorKind::Connection(e.to_string()))
1049    } else {
1050        TypeSafeError::new(ErrorKind::Transport(e.to_string()))
1051    }
1052}
1053
1054/// Parse a `Retry-After` header value given in seconds.
1055///
1056/// The HTTP-date form is not supported (it needs a date parser); such values
1057/// return `None`, and the SDK falls back to its own backoff.
1058fn parse_retry_after(value: &str) -> Option<Duration> {
1059    value.trim().parse::<u64>().ok().map(Duration::from_secs)
1060}
1061
1062/// Parse a `retry-after-ms` header value given in milliseconds.
1063///
1064/// This is a non-standard header used by some API gateways to express
1065/// sub-second retry delays with more precision than the standard
1066/// `Retry-After` (seconds) header.
1067fn parse_retry_after_ms(value: &str) -> Option<Duration> {
1068    value.trim().parse::<u64>().ok().map(Duration::from_millis)
1069}
1070
1071/// Truncate a string to at most `max_chars` *characters*, appending "..."
1072/// (3 chars) if anything was cut — so the returned string can be up to
1073/// `max_chars + 3` characters long. Slicing at a char boundary means
1074/// non-ASCII bodies can't cause a panic.
1075fn truncate(s: &str, max_chars: usize) -> String {
1076    match s.char_indices().nth(max_chars) {
1077        Some((idx, _)) => format!("{}...", &s[..idx]),
1078        None => s.to_string(),
1079    }
1080}
1081
1082/// Validate the base URL: it must be `https`, or `http` only for a loopback
1083/// host (development/testing). The URL is parsed rather than prefix-matched so
1084/// look-alikes such as `http://localhost.evil.example` or
1085/// `http://localhost@evil.example` are rejected.
1086fn validate_base_url(raw: &str) -> Result<()> {
1087    let url = reqwest::Url::parse(raw).map_err(|e| {
1088        TypeSafeError::new(ErrorKind::Validation(format!(
1089            "Base URL is not a valid URL: {e}"
1090        )))
1091    })?;
1092
1093    // Reject credentials, query parameters, and fragments — a base URL
1094    // should be a bare origin + optional path.
1095    if !url.username().is_empty()
1096        || url.password().is_some()
1097        || url.query().is_some()
1098        || url.fragment().is_some()
1099    {
1100        return Err(TypeSafeError::new(ErrorKind::Validation(
1101            "Base URL must not contain credentials, query parameters, or fragments.".to_string(),
1102        )));
1103    }
1104
1105    match (url.scheme(), url.host_str()) {
1106        ("https", Some(_)) => Ok(()),
1107        ("http", Some("localhost" | "127.0.0.1" | "::1" | "[::1]")) => Ok(()),
1108        (scheme, _) => Err(TypeSafeError::new(ErrorKind::Validation(format!(
1109            "Base URL must use https:// (or http:// for localhost/127.0.0.1/::1 during development); got scheme `{scheme}` and an unsupported host."
1110        )))),
1111    }
1112}
1113
1114#[cfg(test)]
1115mod tests {
1116    use super::*;
1117
1118    #[test]
1119    fn new_requires_api_key() {
1120        let result = TypeSafeClient::new("");
1121        assert!(result.is_err());
1122    }
1123
1124    #[test]
1125    fn from_config_requires_api_key() {
1126        let config = ClientConfig::default();
1127        let result = TypeSafeClient::from_config(config);
1128        assert!(result.is_err());
1129    }
1130
1131    #[test]
1132    fn extract_error_message_from_nested_object() {
1133        let text = r#"{"error":{"message":"Invalid API key"}}"#;
1134        let msg = TypeSafeClient::extract_error_message(text).unwrap();
1135        assert_eq!(msg, "Invalid API key");
1136    }
1137
1138    #[test]
1139    fn extract_error_message_from_detail() {
1140        let text = r#"{"detail":"Not found"}"#;
1141        let msg = TypeSafeClient::extract_error_message(text).unwrap();
1142        assert_eq!(msg, "Not found");
1143    }
1144
1145    #[test]
1146    fn extract_error_message_returns_none_for_plain_text() {
1147        let text = "plain text error";
1148        assert!(TypeSafeClient::extract_error_message(text).is_none());
1149    }
1150
1151    #[test]
1152    fn debug_redacts_api_key() {
1153        let config = ClientConfig {
1154            api_key: "secret_key_123".to_string(),
1155            ..ClientConfig::default()
1156        };
1157        let debug_str = format!("{config:?}");
1158        assert!(!debug_str.contains("secret_key_123"));
1159        assert!(debug_str.contains("<redacted>"));
1160    }
1161
1162    #[test]
1163    fn client_debug_does_not_leak_api_key() {
1164        let client = TypeSafeClient::new("secret_key_123").unwrap();
1165        let debug_str = format!("{client:?}");
1166        assert!(!debug_str.contains("secret_key_123"));
1167    }
1168
1169    #[test]
1170    fn trims_api_key_whitespace() {
1171        // A stray newline from an env file should be trimmed.
1172        let client = TypeSafeClient::new("  apikey_test  \n").unwrap();
1173        assert_eq!(client.config.api_key, "apikey_test");
1174    }
1175
1176    #[test]
1177    fn rejects_api_key_that_is_not_a_valid_header_value() {
1178        let err = TypeSafeClient::new("bad\nkey").unwrap_err();
1179        assert!(
1180            matches!(err.kind(), ErrorKind::Validation(_)),
1181            "got {err:?}"
1182        );
1183    }
1184
1185    #[test]
1186    fn rejects_http_base_url() {
1187        let config = ClientConfig {
1188            api_key: "test".to_string(),
1189            base_url: "http://api.typesafe.ai".to_string(),
1190            ..ClientConfig::default()
1191        };
1192        assert!(TypeSafeClient::from_config(config).is_err());
1193    }
1194
1195    #[test]
1196    fn allows_localhost_http() {
1197        let config = ClientConfig {
1198            api_key: "test".to_string(),
1199            base_url: "http://localhost:8080".to_string(),
1200            ..ClientConfig::default()
1201        };
1202        assert!(TypeSafeClient::from_config(config).is_ok());
1203    }
1204
1205    #[test]
1206    fn trims_trailing_slash_from_base_url() {
1207        let config = ClientConfig {
1208            api_key: "test".to_string(),
1209            base_url: "https://api.typesafe.ai/".to_string(),
1210            ..ClientConfig::default()
1211        };
1212        let client = TypeSafeClient::from_config(config).unwrap();
1213        assert_eq!(client.base_url(), "https://api.typesafe.ai");
1214    }
1215
1216    /// A base URL with a trailing slash must not produce a double slash
1217    /// when joined with a path like `/v1/systemone`.
1218    #[test]
1219    fn trailing_slash_does_not_produce_double_slash() {
1220        let config = ClientConfig {
1221            api_key: "test".to_string(),
1222            base_url: "https://api.typesafe.ai/v1/".to_string(),
1223            ..ClientConfig::default()
1224        };
1225        let client = TypeSafeClient::from_config(config).unwrap();
1226        // Trailing slash is stripped, so joining with "/v1/systemone"
1227        // produces a single slash, not "//".
1228        let url = format!("{}{}", client.base_url(), "/v1/systemone");
1229        assert_eq!(url, "https://api.typesafe.ai/v1/v1/systemone");
1230        assert!(!url.contains("//v1"), "double slash in URL: {url}");
1231    }
1232
1233    /// Regression: a `starts_with("http://localhost")` check accepted these
1234    /// look-alikes, sending the API key in plaintext to an attacker's host.
1235    #[test]
1236    fn base_url_rejects_localhost_lookalikes() {
1237        for bad in [
1238            "http://localhost.evil.example",
1239            "http://127.0.0.1.evil.example/v1",
1240            "http://localhost@evil.example",
1241            "http://localhostevil.example",
1242            "ftp://localhost",
1243            "not a url",
1244            "",
1245        ] {
1246            assert!(
1247                validate_base_url(bad).is_err(),
1248                "{bad:?} should be rejected"
1249            );
1250        }
1251    }
1252
1253    #[test]
1254    fn base_url_accepts_valid_urls() {
1255        for good in [
1256            "https://api.typesafe.ai",
1257            "HTTPS://API.TYPESAFE.AI",
1258            "https://api.typesafe.ai/prefix",
1259            "http://localhost",
1260            "http://localhost:8080",
1261            "http://LOCALHOST:8080",
1262            "http://127.0.0.1:9000",
1263            "http://[::1]:9000",
1264        ] {
1265            assert!(
1266                validate_base_url(good).is_ok(),
1267                "{good:?} should be accepted"
1268            );
1269        }
1270    }
1271
1272    #[test]
1273    fn truncate_shortens_long_strings() {
1274        let long = "x".repeat(600);
1275        let truncated = truncate(&long, 512);
1276        assert_eq!(truncated.len(), 515); // 512 + "..."
1277        assert!(truncated.ends_with("..."));
1278    }
1279
1280    #[test]
1281    fn truncate_leaves_short_strings_alone() {
1282        assert_eq!(truncate("hello", 512), "hello");
1283        assert_eq!(truncate("exactly", 7), "exactly");
1284    }
1285
1286    /// Regression: byte-slicing at `max` panicked when it fell inside a
1287    /// multi-byte character (512 % 3 != 0 for "€").
1288    #[test]
1289    fn truncate_handles_multibyte_characters() {
1290        let long = "€".repeat(600);
1291        let truncated = truncate(&long, 512);
1292        assert_eq!(truncated.chars().count(), 515); // 512 chars + "..."
1293        assert!(truncated.ends_with("..."));
1294
1295        // Emoji (4 bytes) and mixed scripts, at many cut points.
1296        let mixed = "héllo wörld 日本語 🙂".repeat(20);
1297        for max in 0..mixed.chars().count() + 2 {
1298            let _ = truncate(&mixed, max); // must not panic
1299        }
1300    }
1301
1302    #[test]
1303    fn parse_retry_after_seconds() {
1304        assert_eq!(parse_retry_after("5"), Some(Duration::from_secs(5)));
1305        assert_eq!(parse_retry_after("  10  "), Some(Duration::from_secs(10)));
1306        assert_eq!(parse_retry_after("not a number"), None);
1307        // HTTP-date form is intentionally unsupported.
1308        assert_eq!(parse_retry_after("Wed, 21 Oct 2026 07:28:00 GMT"), None);
1309    }
1310
1311    #[test]
1312    fn parse_retry_after_ms_parses_milliseconds() {
1313        assert_eq!(
1314            parse_retry_after_ms("500"),
1315            Some(Duration::from_millis(500))
1316        );
1317        assert_eq!(
1318            parse_retry_after_ms("  1500  "),
1319            Some(Duration::from_millis(1500))
1320        );
1321        assert_eq!(parse_retry_after_ms("not a number"), None);
1322    }
1323
1324    /// Builder errors are deterministic, so they must map to the
1325    /// non-retryable `Transport` variant, not `Connection`.
1326    #[test]
1327    fn builder_errors_are_not_retryable() {
1328        let err = reqwest::Client::new().get("not a url").build().unwrap_err();
1329        let mapped = map_reqwest_error(err, Duration::from_secs(1));
1330        assert!(
1331            matches!(mapped.kind(), ErrorKind::Transport(_)),
1332            "got {mapped:?}"
1333        );
1334        assert!(!mapped.is_retryable());
1335    }
1336
1337    /// IPv6 loopback `::1` should be accepted (reqwest's `host_str()` returns
1338    /// `::1` without brackets).
1339    #[test]
1340    fn base_url_accepts_ipv6_loopback() {
1341        assert!(validate_base_url("http://[::1]:8080").is_ok());
1342        assert!(validate_base_url("http://[::1]").is_ok());
1343    }
1344
1345    #[test]
1346    fn from_config_rejects_empty_default_model() {
1347        let config = ClientConfig {
1348            api_key: "test".to_string(),
1349            default_model: "  ".to_string(),
1350            ..ClientConfig::default()
1351        };
1352        let err = TypeSafeClient::from_config(config).unwrap_err();
1353        assert!(
1354            matches!(err.kind(), ErrorKind::Validation(ref m) if m.contains("model")),
1355            "got {err:?}"
1356        );
1357    }
1358
1359    #[test]
1360    fn timeout_error_preserves_subsecond_duration() {
1361        let err = TypeSafeError::new(ErrorKind::Timeout(Duration::from_millis(150)));
1362        let msg = err.to_string();
1363        assert!(
1364            msg.contains("150ms"),
1365            "expected 150ms in message, got: {msg}"
1366        );
1367    }
1368
1369    #[test]
1370    fn base_url_rejects_credentials() {
1371        assert!(validate_base_url("https://user:password@api.typesafe.ai").is_err());
1372        assert!(validate_base_url("https://user@api.typesafe.ai").is_err());
1373    }
1374
1375    #[test]
1376    fn base_url_rejects_query_and_fragment() {
1377        assert!(validate_base_url("https://api.typesafe.ai?foo=bar").is_err());
1378        assert!(validate_base_url("https://api.typesafe.ai#fragment").is_err());
1379    }
1380
1381    #[test]
1382    fn base_url_accepts_path() {
1383        assert!(validate_base_url("https://api.typesafe.ai/api").is_ok());
1384        assert!(validate_base_url("https://api.typesafe.ai/v1/").is_ok());
1385    }
1386}