typesafeai-sdk 0.2.0

Rust SDK for TypeSafe AI — typed judgments from System One models like Jev
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
//! The TypeSafe AI API client.
//!
//! Mirrors the Python `TypeSafeClient` and JavaScript `TypeSafeClient`:
//! a client struct with configurable API key, base URL, default model,
//! timeout, and retry policy. The primary method is [`TypeSafeClient::system_one`],
//! which sends a `POST /v1/systemone` request and returns a typed
//! [`SystemOneResponse`].
//!
//! # Example
//! ```no_run
//! use typesafeai_sdk::{TypeSafeClient, noul, choice, score};
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let client = TypeSafeClient::from_env()?;
//!
//! let response = client.system_one(
//!     "I was charged twice. Please help.",
//!     [
//!         ("billing".to_string(), noul("Is this about billing?").into()),
//!         ("tone".to_string(), choice("What is the tone?", [
//!             ("calm".to_string(), None),
//!             ("angry".to_string(), None),
//!         ].into()).into()),
//!     ].into(),
//! ).await?;
//!
//! if let Some(answer) = response.noul("billing") {
//!     println!("{}", answer.noul);
//! }
//! # Ok(())
//! # }
//! ```

use std::collections::HashMap;
use std::env;
use std::fmt;
use std::time::Duration;

use reqwest::header::{HeaderMap, HeaderName, HeaderValue, ACCEPT, AUTHORIZATION, RETRY_AFTER};
use reqwest::{Client as HttpClient, Method, StatusCode};
use serde_json::Value;

use crate::error::{ErrorKind, Result, TypeSafeError};
use crate::questions::{validate_questions, Question};
use crate::retry::{jitter_seed, RetryPolicy};
use crate::types::{
    ListModelsResponse, SetRawBody, SetRequestId, SystemOneRequest, SystemOneResponse,
};

const DEFAULT_BASE_URL: &str = "https://api.typesafe.ai";
const DEFAULT_MODEL: &str = "jev-latest";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
const SDK_USER_AGENT: &str = concat!("typesafe-sdk/", env!("CARGO_PKG_VERSION"));
const SYSTEM_ONE_PATH: &str = "/v1/systemone";
const MODELS_PATH: &str = "/v1/models";
const RETRY_AFTER_MS_HEADER: &str = "retry-after-ms";
const REQUEST_ID_HEADER: &str = "x-typesafe-request-id";
/// Maximum number of characters of a response body echoed into an error.
const MAX_ERROR_BODY_CHARS: usize = 512;

/// Configuration for constructing a [`TypeSafeClient`].
///
/// All fields are public for construction, but prefer [`ClientConfig::default`]
/// or the builder methods on [`RetryPolicy`] for common cases.
#[derive(Clone)]
#[non_exhaustive]
pub struct ClientConfig {
    /// API key for authentication.
    ///
    /// Set this directly or use [`TypeSafeClient::from_env`] to read it
    /// from the `TYPESAFE_API_KEY` environment variable.
    pub api_key: String,
    /// API root. Defaults to `https://api.typesafe.ai`.
    ///
    /// A base path is supported and preserved: e.g. `https://example.com/api`
    /// produces endpoints like `https://example.com/api/v1/systemone`.
    /// Credentials, query parameters, and fragments are rejected.
    pub base_url: String,
    /// Default model. Defaults to `jev-latest`.
    pub default_model: String,
    /// Per-attempt timeout. Defaults to 10 seconds.
    pub timeout: Duration,
    /// Retry policy. Defaults to 2 retries with exponential backoff + jitter.
    pub retry: RetryPolicy,
}

impl Default for ClientConfig {
    fn default() -> Self {
        Self {
            api_key: String::new(),
            base_url: DEFAULT_BASE_URL.to_string(),
            default_model: DEFAULT_MODEL.to_string(),
            timeout: DEFAULT_TIMEOUT,
            retry: RetryPolicy::default(),
        }
    }
}

impl ClientConfig {
    /// Create a new `ClientConfig` with the given API key and all other
    /// fields set to their defaults.
    ///
    /// Use the `.with_*()` methods to override individual fields.
    #[must_use]
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            ..Self::default()
        }
    }

    /// Set the API key.
    #[must_use]
    pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
        self.api_key = api_key.into();
        self
    }

    /// Set the base URL.
    #[must_use]
    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = base_url.into();
        self
    }

    /// Set the default model.
    #[must_use]
    pub fn with_default_model(mut self, default_model: impl Into<String>) -> Self {
        self.default_model = default_model.into();
        self
    }

    /// Set the per-attempt timeout.
    #[must_use]
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Set the retry policy.
    #[must_use]
    pub fn with_retry(mut self, retry: RetryPolicy) -> Self {
        self.retry = retry;
        self
    }
}

impl fmt::Debug for ClientConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ClientConfig")
            .field("api_key", &"<redacted>")
            .field("base_url", &self.base_url)
            .field("default_model", &self.default_model)
            .field("timeout", &self.timeout)
            .field("retry", &self.retry)
            .finish()
    }
}

/// Client for the TypeSafe AI API.
///
/// Construct with [`TypeSafeClient::new`] or [`TypeSafeClient::from_env`].
/// Cloning is cheap and shares the underlying connection pool.
#[derive(Clone)]
#[non_exhaustive]
pub struct TypeSafeClient {
    config: ClientConfig,
    http: HttpClient,
}

impl fmt::Debug for TypeSafeClient {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TypeSafeClient")
            .field("config", &self.config)
            .finish_non_exhaustive()
    }
}

/// A failed attempt, carrying the server's `Retry-After` hint (if any) so the
/// retry loop can honour it. Internal: the public API only exposes
/// [`TypeSafeError`].
struct Failure {
    error: TypeSafeError,
    retry_after: Option<Duration>,
}

impl From<TypeSafeError> for Failure {
    fn from(error: TypeSafeError) -> Self {
        Self {
            error,
            retry_after: None,
        }
    }
}

/// Per-call options for [`TypeSafeClient::system_one_with_opts`].
///
/// Built with a builder pattern. Start with [`SystemOneOpts::new`] and chain
/// `.with_*()` methods. Fields not set use the client's defaults.
///
/// # Example
/// ```no_run
/// use typesafeai_sdk::SystemOneOpts;
///
/// let opts = SystemOneOpts::new()
///     .with_model(Some("jev-latest".to_string()))
///     .with_state("I was charged twice.")
///     .with_extra_body(serde_json::json!({"priority": "high"}));
/// ```
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct SystemOneOpts {
    /// Override the client's default model for this call.
    pub(crate) model: Option<String>,
    /// The state to evaluate. If not set, defaults to `null`.
    pub(crate) state: Option<Value>,
    /// Extra fields to merge into the request body for forward compatibility.
    pub(crate) extra_body: Option<Value>,
}

impl SystemOneOpts {
    /// Create a new empty options set (all fields use client defaults).
    pub fn new() -> Self {
        Self::default()
    }

    /// Override the model for this call. `None` uses the client default.
    #[must_use = "the returned SystemOneOpts should be used"]
    pub fn with_model(mut self, model: Option<String>) -> Self {
        self.model = model;
        self
    }

    /// Set the state to evaluate. Accepts a string, JSON object, or array.
    #[must_use = "the returned SystemOneOpts should be used"]
    pub fn with_state(mut self, state: impl Into<Value>) -> Self {
        self.state = Some(state.into());
        self
    }

    /// Set extra fields to merge into the request body for forward
    /// compatibility. Keys that collide with known fields (`state`, `model`,
    /// `questions`) are ignored — the known fields take precedence.
    #[must_use = "the returned SystemOneOpts should be used"]
    pub fn with_extra_body(mut self, extra: Value) -> Self {
        self.extra_body = Some(extra);
        self
    }
}

impl TypeSafeClient {
    /// Create a new client with the given API key and default settings.
    #[must_use = "the returned client should be used to make API calls"]
    pub fn new(api_key: impl Into<String>) -> Result<Self> {
        let config = ClientConfig {
            api_key: api_key.into(),
            ..ClientConfig::default()
        };
        Self::from_config(config)
    }

    /// Create a new client from a full [`ClientConfig`].
    #[must_use = "the returned client should be used to make API calls"]
    pub fn from_config(mut config: ClientConfig) -> Result<Self> {
        // Trim whitespace: a stray newline from an env file would otherwise
        // become an opaque transport error.
        config.api_key = config.api_key.trim().to_string();

        if config.api_key.is_empty() {
            return Err(TypeSafeError::new(ErrorKind::Validation(
                "No API key was provided. Pass an API key to `TypeSafeClient::new` or set the `TYPESAFE_API_KEY` environment variable."
                    .to_string(),
            )));
        }

        // Normalize the base URL: trim trailing slash and validate scheme/host.
        config.base_url = config.base_url.trim().trim_end_matches('/').to_string();
        validate_base_url(&config.base_url)?;

        // Validate the default model name.
        if config.default_model.trim().is_empty() {
            return Err(TypeSafeError::new(ErrorKind::Validation(
                "Default model name cannot be empty.".to_string(),
            )));
        }

        // Build the auth header once. Marking it sensitive keeps the key out
        // of reqwest's debug output.
        let mut auth =
            HeaderValue::from_str(&format!("Bearer {}", config.api_key)).map_err(|_| {
                TypeSafeError::new(ErrorKind::Validation(
                    "The API key contains characters that are not valid in an HTTP header."
                        .to_string(),
                ))
            })?;
        auth.set_sensitive(true);

        let mut headers = HeaderMap::new();
        headers.insert(AUTHORIZATION, auth);
        headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
        headers.insert(
            HeaderName::from_static("x-typesafe-sdk"),
            HeaderValue::from_static(SDK_USER_AGENT),
        );

        let http = HttpClient::builder()
            .timeout(config.timeout)
            .user_agent(SDK_USER_AGENT)
            .default_headers(headers)
            .build()
            .map_err(|e| TypeSafeError::new(ErrorKind::Transport(e)))?;

        Ok(Self { config, http })
    }

    /// Create a new client, reading the API key from the `TYPESAFE_API_KEY`
    /// environment variable. Also reads `TYPESAFE_BASE_URL` and
    /// `TYPESAFE_DEFAULT_MODEL` if set.
    #[must_use = "the returned client should be used to make API calls"]
    pub fn from_env() -> Result<Self> {
        let api_key = env::var("TYPESAFE_API_KEY").unwrap_or_default();
        let mut config = ClientConfig {
            api_key,
            ..ClientConfig::default()
        };

        if let Ok(base) = env::var("TYPESAFE_BASE_URL") {
            if !base.trim().is_empty() {
                config.base_url = base;
            }
        }

        if let Ok(model) = env::var("TYPESAFE_DEFAULT_MODEL") {
            if !model.trim().is_empty() {
                config.default_model = model;
            }
        }

        Self::from_config(config)
    }

    /// Returns the base URL this client is configured to use.
    pub fn base_url(&self) -> &str {
        &self.config.base_url
    }

    /// Returns the default model this client uses.
    pub fn default_model(&self) -> &str {
        &self.config.default_model
    }

    // -----------------------------------------------------------------------
    // system_one
    // -----------------------------------------------------------------------

    /// Answer named questions about text or structured state.
    ///
    /// Sends a `POST /v1/systemone` request and returns a typed
    /// [`SystemOneResponse`].
    ///
    /// # Arguments
    /// - `state` — text, a JSON object, or an array to evaluate. Accepts
    ///   `&str`, `String`, or any `serde_json::Value`.
    /// - `questions` — a non-empty map of question names to [`Question`]s.
    ///
    /// Use [`system_one_with_model`](Self::system_one_with_model) to override
    /// the client's default model.
    ///
    /// # Retry safety
    ///
    /// This is a `POST` request. The SDK automatically retries on transient
    /// failures (429, 5xx, connection errors, timeouts), but a timeout does
    /// not guarantee the server did not process the request. If the endpoint
    /// has side effects (credit consumption, usage recording, downstream
    /// triggers), a retry may result in duplicate processing. Future versions
    /// will support an `Idempotency-Key` header to make retries safe.
    ///
    /// To avoid replaying a POST whose body the server already processed,
    /// errors that occur while *reading the response body* — including
    /// timeouts and truncated bodies — are classified as non-retryable
    /// [`TypeSafeError::Transport`] rather than [`TypeSafeError::Connection`]
    /// or [`TypeSafeError::Timeout`].
    ///
    /// # Errors
    /// - [`TypeSafeError::Validation`] if questions are empty or a choice or
    ///   score question has fewer than two criteria.
    /// - [`TypeSafeError::Authentication`] if the API key is invalid.
    /// - [`TypeSafeError::RateLimit`] if rate-limited (after retries).
    /// - [`TypeSafeError::Connection`] / [`TypeSafeError::Timeout`] on
    ///   network failures (after retries).
    pub async fn system_one(
        &self,
        state: impl Into<Value>,
        questions: HashMap<String, Question>,
    ) -> Result<SystemOneResponse> {
        self.system_one_with_model(state, questions, None).await
    }

    /// Like [`system_one`](Self::system_one) but with an explicit model
    /// override (`None` uses the client default).
    pub async fn system_one_with_model(
        &self,
        state: impl Into<Value>,
        questions: HashMap<String, Question>,
        model: Option<&str>,
    ) -> Result<SystemOneResponse> {
        let opts = SystemOneOpts::new()
            .with_model(model.map(|m| m.to_string()))
            .with_state(state);
        self.system_one_with_opts(questions, opts).await
    }

    /// Like [`system_one`](Self::system_one) but with full per-call options
    /// via a [`SystemOneOpts`] builder.
    ///
    /// This allows overriding the model, adding extra body fields for
    /// forward compatibility, and attaching custom headers — all per-call.
    ///
    /// # Example
    /// ```no_run
    /// use typesafeai_sdk::{TypeSafeClient, noul, SystemOneOpts};
    /// use std::collections::HashMap;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = TypeSafeClient::from_env()?;
    /// let mut questions = HashMap::new();
    /// questions.insert("billing".to_string(), noul("Is this about billing?").into());
    ///
    /// let opts = SystemOneOpts::new()
    ///     .with_model(Some("jev-latest".to_string()))
    ///     .with_extra_body(serde_json::json!({"user_id": "u123"}));
    ///
    /// let response = client.system_one_with_opts(questions, opts).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn system_one_with_opts(
        &self,
        questions: HashMap<String, Question>,
        opts: SystemOneOpts,
    ) -> Result<SystemOneResponse> {
        validate_questions(&questions)?;

        let model_name = opts
            .model
            .unwrap_or_else(|| self.config.default_model.clone());
        if model_name.trim().is_empty() {
            return Err(TypeSafeError::new(ErrorKind::Validation(
                "Model name cannot be empty.".to_string(),
            )));
        }

        let request = SystemOneRequest {
            state: opts.state.unwrap_or(Value::Null),
            model: model_name,
            questions,
            extra_body: opts.extra_body,
        };

        let mut body = serde_json::to_value(&request)?;

        // Merge extra_body fields at the top level for forward compatibility.
        // Known fields (state, model, questions) take precedence over
        // extra_body keys.
        if let Some(extra) = &request.extra_body {
            if let (Some(obj), Some(extra_obj)) = (body.as_object_mut(), extra.as_object()) {
                for (k, v) in extra_obj {
                    if !obj.contains_key(k) {
                        obj.insert(k.clone(), v.clone());
                    }
                }
            }
        }

        self.request_with_retry(Method::POST, SYSTEM_ONE_PATH, Some(body))
            .await
    }

    // -----------------------------------------------------------------------
    // models
    // -----------------------------------------------------------------------

    /// List available models. Sends `GET /v1/models`.
    pub async fn list_models(&self) -> Result<ListModelsResponse> {
        self.request_with_retry(Method::GET, MODELS_PATH, None)
            .await
    }

    // -----------------------------------------------------------------------
    // Internal HTTP + retry
    // -----------------------------------------------------------------------

    async fn request_with_retry<T: serde::de::DeserializeOwned + 'static>(
        &self,
        method: Method,
        path: &str,
        body: Option<Value>,
    ) -> Result<T> {
        let url = format!("{}{}", self.config.base_url, path);
        let retry = &self.config.retry;

        let started = std::time::Instant::now();
        let mut attempt = 0;
        loop {
            match self.attempt_request(&method, &url, body.as_ref()).await {
                Ok(resp) => return Ok(resp),
                Err(failure) => {
                    if !failure.error.is_retryable() || attempt >= retry.max_retries {
                        return Err(failure.error);
                    }

                    let delay = match failure.retry_after {
                        // Honour the server's hint, unless it asks us to wait
                        // longer than `max_delay`: then give up instead of
                        // stalling the caller.
                        Some(hint) => match retry.delay_for_retry_after(attempt, hint) {
                            Some(delay) => delay,
                            None => return Err(failure.error),
                        },
                        None => retry.delay_for_with_jitter(attempt, jitter_seed()),
                    };

                    // Stop before a delay that would exceed the budget.
                    if retry.budget_exceeded(started.elapsed(), delay) {
                        return Err(failure.error);
                    }

                    tokio::time::sleep(delay).await;
                    attempt += 1;
                }
            }
        }
    }

    async fn attempt_request<T: serde::de::DeserializeOwned + 'static>(
        &self,
        method: &Method,
        url: &str,
        body: Option<&Value>,
    ) -> std::result::Result<T, Failure> {
        // Auth, Accept, User-Agent and X-TypeSafe-SDK are default headers set
        // once in `from_config`; `.json()` sets Content-Type.
        let mut request = self.http.request(method.clone(), url);
        if let Some(b) = body {
            request = request.json(b);
        }

        let response = request
            .send()
            .await
            .map_err(|e| map_reqwest_error(e, self.config.timeout))?;

        self.parse_response(response).await
    }

    async fn parse_response<T: serde::de::DeserializeOwned + 'static>(
        &self,
        response: reqwest::Response,
    ) -> std::result::Result<T, Failure> {
        let status = response.status();
        let headers = response.headers();
        // Capture the request ID for both success and error paths.
        let request_id = headers
            .get(REQUEST_ID_HEADER)
            .and_then(|v| v.to_str().ok())
            .map(|s| s.to_string());
        // Prefer retry-after-ms (milliseconds, more precise) over the
        // standard Retry-After (seconds). Either may be absent.
        let retry_after = headers
            .get(RETRY_AFTER_MS_HEADER)
            .and_then(|v| v.to_str().ok())
            .and_then(parse_retry_after_ms)
            .or_else(|| {
                headers
                    .get(RETRY_AFTER)
                    .and_then(|v| v.to_str().ok())
                    .and_then(parse_retry_after)
            });

        let text = response.text().await.map_err(map_body_error)?;

        if status.is_success() {
            let mut result: T = serde_json::from_str(&text).map_err(|e| {
                Failure::from(TypeSafeError::new(ErrorKind::ResponseValidation {
                    message: format!(
                        "Failed to parse response body: {e}\nBody: {}",
                        truncate(&text, MAX_ERROR_BODY_CHARS)
                    ),
                    field_path: None,
                }))
            })?;
            // Inject the request ID and raw body into the response type.
            // This is a no-op for types that don't implement the traits.
            let raw = serde_json::from_str::<Value>(&text).ok();
            inject_metadata(&mut result, request_id.clone(), raw);
            return Ok(result);
        }

        // Map HTTP status codes to typed errors, mirroring the Python/JS SDKs.
        let message = Self::extract_error_message(&text)
            .unwrap_or_else(|| truncate(&text, MAX_ERROR_BODY_CHARS));
        let kind = match status {
            StatusCode::UNAUTHORIZED => ErrorKind::Authentication(message),
            StatusCode::BAD_REQUEST => ErrorKind::BadRequest(message),
            StatusCode::NOT_FOUND => ErrorKind::NotFound(message),
            StatusCode::UNPROCESSABLE_ENTITY => ErrorKind::UnprocessableEntity(message),
            StatusCode::TOO_MANY_REQUESTS => ErrorKind::RateLimit(message),
            StatusCode::INTERNAL_SERVER_ERROR
            | StatusCode::BAD_GATEWAY
            | StatusCode::SERVICE_UNAVAILABLE
            | StatusCode::GATEWAY_TIMEOUT => ErrorKind::InternalServer(message),
            s if s.as_u16() == 529 => ErrorKind::Overloaded(message),
            _ => ErrorKind::Api {
                status: status.as_u16(),
                message,
            },
        };
        Err(Failure {
            error: TypeSafeError::with_request_id(kind, request_id),
            retry_after,
        })
    }

    /// Try to extract a human-readable error message from the response body.
    /// The API typically returns `{"error": {"message": "..."}}` or
    /// `{"detail": "..."}`.
    fn extract_error_message(text: &str) -> Option<String> {
        let value: Value = serde_json::from_str(text).ok()?;
        let obj = value.as_object()?;
        if let Some(error) = obj.get("error") {
            if let Some(msg) = error.get("message").and_then(|m| m.as_str()) {
                return Some(msg.to_string());
            }
            if let Some(msg) = error.as_str() {
                return Some(msg.to_string());
            }
        }
        if let Some(detail) = obj.get("detail").and_then(|d| d.as_str()) {
            return Some(detail.to_string());
        }
        if let Some(message) = obj.get("message").and_then(|m| m.as_str()) {
            return Some(message.to_string());
        }
        None
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Inject the request ID and raw JSON body into a response type if it
/// implements [`SetRequestId`](crate::types::SetRequestId) and/or
/// [`SetRawBody`](crate::types::SetRawBody).
///
/// Uses runtime type checking via `Any` so the generic `parse_response`
/// can stay monomorphic without requiring all `T` to implement the traits.
fn inject_metadata<T: 'static>(value: &mut T, request_id: Option<String>, raw: Option<Value>) {
    use std::any::Any;
    if let Some(resp) = (value as &mut dyn Any).downcast_mut::<SystemOneResponse>() {
        resp.set_request_id(request_id);
        resp.set_raw(raw);
    } else if let Some(resp) = (value as &mut dyn Any).downcast_mut::<ListModelsResponse>() {
        resp.set_request_id(request_id);
        resp.set_raw(raw);
    }
}

/// Map a `reqwest` error to the appropriate `TypeSafeError` variant.
///
/// - timeouts -> [`TypeSafeError::Timeout`], reporting the *configured* timeout
/// - connect failures (refused, reset, DNS) -> [`TypeSafeError::Connection`]
/// - everything else (body read, builder, redirect, decode, request
///   construction) is deterministic or occurs after the server has already
///   processed the request, so it stays a non-retryable
///   [`TypeSafeError::Transport`]
///
/// `is_request()` and `is_body()` are intentionally **not** classified as
/// `Connection`. `is_request()` covers the entire request lifecycle, including
/// non-retryable errors like builder failures, redirect loops, and decode
/// errors. `is_body()` indicates a failure while *reading the response body*,
/// which happens **after** the server has already received and processed the
/// request — retrying a POST in that state risks duplicate side effects.
/// Only `is_connect()` (pre-request network failure) is retryable.
fn map_reqwest_error(e: reqwest::Error, timeout: Duration) -> TypeSafeError {
    if e.is_timeout() {
        TypeSafeError::new(ErrorKind::Timeout(timeout))
    } else if e.is_connect() {
        TypeSafeError::new(ErrorKind::Connection(e.to_string()))
    } else {
        TypeSafeError::new(ErrorKind::Transport(e))
    }
}

/// Map an error that occurred while *reading the response body*.
///
/// By the time we're reading the body, the server has already received and
/// processed the request. Any failure here — timeout, truncated body, or
/// connection reset — must be non-retryable to avoid replaying a POST whose
/// side effects the server may have already applied.
fn map_body_error(e: reqwest::Error) -> TypeSafeError {
    TypeSafeError::new(ErrorKind::Transport(e))
}

/// Parse a `Retry-After` header value given in seconds.
///
/// The HTTP-date form is not supported (it needs a date parser); such values
/// return `None`, and the SDK falls back to its own backoff.
fn parse_retry_after(value: &str) -> Option<Duration> {
    value.trim().parse::<u64>().ok().map(Duration::from_secs)
}

/// Parse a `retry-after-ms` header value given in milliseconds.
///
/// This is a non-standard header used by some API gateways to express
/// sub-second retry delays with more precision than the standard
/// `Retry-After` (seconds) header.
fn parse_retry_after_ms(value: &str) -> Option<Duration> {
    value.trim().parse::<u64>().ok().map(Duration::from_millis)
}

/// Truncate a string to at most `max_chars` *characters*, appending "..." if
/// anything was cut. Slicing at a char boundary means non-ASCII bodies can't
/// cause a panic.
fn truncate(s: &str, max_chars: usize) -> String {
    match s.char_indices().nth(max_chars) {
        Some((idx, _)) => format!("{}...", &s[..idx]),
        None => s.to_string(),
    }
}

/// Validate the base URL: it must be `https`, or `http` only for a loopback
/// host (development/testing). The URL is parsed rather than prefix-matched so
/// look-alikes such as `http://localhost.evil.example` or
/// `http://localhost@evil.example` are rejected.
fn validate_base_url(raw: &str) -> Result<()> {
    let url = reqwest::Url::parse(raw).map_err(|e| {
        TypeSafeError::new(ErrorKind::Validation(format!(
            "Base URL is not a valid URL: {e}"
        )))
    })?;

    // Reject credentials, query parameters, and fragments — a base URL
    // should be a bare origin + optional path.
    if !url.username().is_empty()
        || url.password().is_some()
        || url.query().is_some()
        || url.fragment().is_some()
    {
        return Err(TypeSafeError::new(ErrorKind::Validation(
            "Base URL must not contain credentials, query parameters, or fragments.".to_string(),
        )));
    }

    match (url.scheme(), url.host_str()) {
        ("https", Some(_)) => Ok(()),
        ("http", Some("localhost" | "127.0.0.1" | "::1" | "[::1]")) => Ok(()),
        (scheme, _) => Err(TypeSafeError::new(ErrorKind::Validation(format!(
            "Base URL must use https:// (or http:// for localhost/127.0.0.1/::1 during development); got scheme `{scheme}` and an unsupported host."
        )))),
    }
}

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

    #[test]
    fn new_requires_api_key() {
        let result = TypeSafeClient::new("");
        assert!(result.is_err());
    }

    #[test]
    fn from_config_requires_api_key() {
        let config = ClientConfig::default();
        let result = TypeSafeClient::from_config(config);
        assert!(result.is_err());
    }

    #[test]
    fn extract_error_message_from_nested_object() {
        let text = r#"{"error":{"message":"Invalid API key"}}"#;
        let msg = TypeSafeClient::extract_error_message(text).unwrap();
        assert_eq!(msg, "Invalid API key");
    }

    #[test]
    fn extract_error_message_from_detail() {
        let text = r#"{"detail":"Not found"}"#;
        let msg = TypeSafeClient::extract_error_message(text).unwrap();
        assert_eq!(msg, "Not found");
    }

    #[test]
    fn extract_error_message_returns_none_for_plain_text() {
        let text = "plain text error";
        assert!(TypeSafeClient::extract_error_message(text).is_none());
    }

    #[test]
    fn debug_redacts_api_key() {
        let config = ClientConfig {
            api_key: "secret_key_123".to_string(),
            ..ClientConfig::default()
        };
        let debug_str = format!("{config:?}");
        assert!(!debug_str.contains("secret_key_123"));
        assert!(debug_str.contains("<redacted>"));
    }

    #[test]
    fn client_debug_does_not_leak_api_key() {
        let client = TypeSafeClient::new("secret_key_123").unwrap();
        let debug_str = format!("{client:?}");
        assert!(!debug_str.contains("secret_key_123"));
    }

    #[test]
    fn trims_api_key_whitespace() {
        // A stray newline from an env file should be trimmed.
        let client = TypeSafeClient::new("  apikey_test  \n").unwrap();
        assert_eq!(client.config.api_key, "apikey_test");
    }

    #[test]
    fn rejects_api_key_that_is_not_a_valid_header_value() {
        let err = TypeSafeClient::new("bad\nkey").unwrap_err();
        assert!(
            matches!(err.kind(), ErrorKind::Validation(_)),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_http_base_url() {
        let config = ClientConfig {
            api_key: "test".to_string(),
            base_url: "http://api.typesafe.ai".to_string(),
            ..ClientConfig::default()
        };
        assert!(TypeSafeClient::from_config(config).is_err());
    }

    #[test]
    fn allows_localhost_http() {
        let config = ClientConfig {
            api_key: "test".to_string(),
            base_url: "http://localhost:8080".to_string(),
            ..ClientConfig::default()
        };
        assert!(TypeSafeClient::from_config(config).is_ok());
    }

    #[test]
    fn trims_trailing_slash_from_base_url() {
        let config = ClientConfig {
            api_key: "test".to_string(),
            base_url: "https://api.typesafe.ai/".to_string(),
            ..ClientConfig::default()
        };
        let client = TypeSafeClient::from_config(config).unwrap();
        assert_eq!(client.base_url(), "https://api.typesafe.ai");
    }

    /// A base URL with a trailing slash must not produce a double slash
    /// when joined with a path like `/v1/systemone`.
    #[test]
    fn trailing_slash_does_not_produce_double_slash() {
        let config = ClientConfig {
            api_key: "test".to_string(),
            base_url: "https://api.typesafe.ai/v1/".to_string(),
            ..ClientConfig::default()
        };
        let client = TypeSafeClient::from_config(config).unwrap();
        // Trailing slash is stripped, so joining with "/v1/systemone"
        // produces a single slash, not "//".
        let url = format!("{}{}", client.base_url(), "/v1/systemone");
        assert_eq!(url, "https://api.typesafe.ai/v1/v1/systemone");
        assert!(!url.contains("//v1"), "double slash in URL: {url}");
    }

    /// Regression: a `starts_with("http://localhost")` check accepted these
    /// look-alikes, sending the API key in plaintext to an attacker's host.
    #[test]
    fn base_url_rejects_localhost_lookalikes() {
        for bad in [
            "http://localhost.evil.example",
            "http://127.0.0.1.evil.example/v1",
            "http://localhost@evil.example",
            "http://localhostevil.example",
            "ftp://localhost",
            "not a url",
            "",
        ] {
            assert!(
                validate_base_url(bad).is_err(),
                "{bad:?} should be rejected"
            );
        }
    }

    #[test]
    fn base_url_accepts_valid_urls() {
        for good in [
            "https://api.typesafe.ai",
            "HTTPS://API.TYPESAFE.AI",
            "https://api.typesafe.ai/prefix",
            "http://localhost",
            "http://localhost:8080",
            "http://LOCALHOST:8080",
            "http://127.0.0.1:9000",
            "http://[::1]:9000",
        ] {
            assert!(
                validate_base_url(good).is_ok(),
                "{good:?} should be accepted"
            );
        }
    }

    #[test]
    fn truncate_shortens_long_strings() {
        let long = "x".repeat(600);
        let truncated = truncate(&long, 512);
        assert_eq!(truncated.len(), 515); // 512 + "..."
        assert!(truncated.ends_with("..."));
    }

    #[test]
    fn truncate_leaves_short_strings_alone() {
        assert_eq!(truncate("hello", 512), "hello");
        assert_eq!(truncate("exactly", 7), "exactly");
    }

    /// Regression: byte-slicing at `max` panicked when it fell inside a
    /// multi-byte character (512 % 3 != 0 for "€").
    #[test]
    fn truncate_handles_multibyte_characters() {
        let long = "€".repeat(600);
        let truncated = truncate(&long, 512);
        assert_eq!(truncated.chars().count(), 515); // 512 chars + "..."
        assert!(truncated.ends_with("..."));

        // Emoji (4 bytes) and mixed scripts, at many cut points.
        let mixed = "héllo wörld 日本語 🙂".repeat(20);
        for max in 0..mixed.chars().count() + 2 {
            let _ = truncate(&mixed, max); // must not panic
        }
    }

    #[test]
    fn parse_retry_after_seconds() {
        assert_eq!(parse_retry_after("5"), Some(Duration::from_secs(5)));
        assert_eq!(parse_retry_after("  10  "), Some(Duration::from_secs(10)));
        assert_eq!(parse_retry_after("not a number"), None);
        // HTTP-date form is intentionally unsupported.
        assert_eq!(parse_retry_after("Wed, 21 Oct 2026 07:28:00 GMT"), None);
    }

    #[test]
    fn parse_retry_after_ms_parses_milliseconds() {
        assert_eq!(
            parse_retry_after_ms("500"),
            Some(Duration::from_millis(500))
        );
        assert_eq!(
            parse_retry_after_ms("  1500  "),
            Some(Duration::from_millis(1500))
        );
        assert_eq!(parse_retry_after_ms("not a number"), None);
    }

    /// Builder errors are deterministic, so they must map to the
    /// non-retryable `Transport` variant, not `Connection`.
    #[test]
    fn builder_errors_are_not_retryable() {
        let err = reqwest::Client::new().get("not a url").build().unwrap_err();
        let mapped = map_reqwest_error(err, Duration::from_secs(1));
        assert!(
            matches!(mapped.kind(), ErrorKind::Transport(_)),
            "got {mapped:?}"
        );
        assert!(!mapped.is_retryable());
    }

    /// IPv6 loopback `::1` should be accepted (reqwest's `host_str()` returns
    /// `::1` without brackets).
    #[test]
    fn base_url_accepts_ipv6_loopback() {
        assert!(validate_base_url("http://[::1]:8080").is_ok());
        assert!(validate_base_url("http://[::1]").is_ok());
    }

    #[test]
    fn from_config_rejects_empty_default_model() {
        let config = ClientConfig {
            api_key: "test".to_string(),
            default_model: "  ".to_string(),
            ..ClientConfig::default()
        };
        let err = TypeSafeClient::from_config(config).unwrap_err();
        assert!(
            matches!(err.kind(), ErrorKind::Validation(ref m) if m.contains("model")),
            "got {err:?}"
        );
    }

    #[test]
    fn timeout_error_preserves_subsecond_duration() {
        let err = TypeSafeError::new(ErrorKind::Timeout(Duration::from_millis(150)));
        let msg = err.to_string();
        assert!(
            msg.contains("150ms"),
            "expected 150ms in message, got: {msg}"
        );
    }

    #[test]
    fn base_url_rejects_credentials() {
        assert!(validate_base_url("https://user:password@api.typesafe.ai").is_err());
        assert!(validate_base_url("https://user@api.typesafe.ai").is_err());
    }

    #[test]
    fn base_url_rejects_query_and_fragment() {
        assert!(validate_base_url("https://api.typesafe.ai?foo=bar").is_err());
        assert!(validate_base_url("https://api.typesafe.ai#fragment").is_err());
    }

    #[test]
    fn base_url_accepts_path() {
        assert!(validate_base_url("https://api.typesafe.ai/api").is_ok());
        assert!(validate_base_url("https://api.typesafe.ai/v1/").is_ok());
    }
}