jevrs 0.1.1

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

use http::{
    HeaderName, HeaderValue, Method, Request, Response, StatusCode,
    header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE, USER_AGENT},
};
use jevrs_core::{
    Answered, Answers, Error, ErrorDetail, Model, QuestionSet, Questions, classify, decode, encode,
};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::{NoSleep, RetryPolicy, Sleep, Transport};
#[cfg(all(
    any(feature = "reqwest", feature = "native-tls"),
    not(target_arch = "wasm32")
))]
use crate::{ReqwestTransport, TokioSleep};
#[cfg(all(target_arch = "wasm32", target_env = "p2"))]
use crate::{Wasip2Sleep, Wasip2Transport};
#[cfg(all(target_arch = "wasm32", target_env = "p3"))]
use crate::{Wasip3Sleep, Wasip3Transport};

const DEFAULT_BASE_URL: &str = "https://api.typesafe.ai";
const EVALUATE_PATH: &str = "/v1/systemone";
const MODELS_PATH: &str = "/v1/models";

/// A Jev model advertised by [`Client::models`].
///
/// Use this to present available models or select a [`Model`] by name. Unknown
/// response fields remain in [`Self::extra`] for forward compatibility.
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct ModelInfo {
    /// Use this name to construct a [`Model`] for an evaluation request.
    pub name: String,
    /// Use this optional summary when presenting a model picker.
    pub description: Option<String>,
    /// Use this optional timestamp when showing model recency.
    pub release_date: Option<String>,
    /// Inspect additional fields only when adopting a newer API extension.
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// The target-selected HTTP transport.
///
/// On native targets this resolves to [`ReqwestTransport`]. The other target
/// selections are `Wasip2Transport` and `Wasip3Transport`.
#[cfg(all(
    any(feature = "reqwest", feature = "native-tls"),
    not(target_arch = "wasm32")
))]
#[cfg_attr(
    docsrs,
    doc(cfg(all(
        any(feature = "reqwest", feature = "native-tls"),
        not(target_arch = "wasm32")
    )))
)]
pub type DefaultTransport = ReqwestTransport;

/// The target-selected retry sleeper.
///
/// On native targets this resolves to [`TokioSleep`]. The other target
/// selections are `Wasip2Sleep` and `Wasip3Sleep`.
#[cfg(all(
    any(feature = "reqwest", feature = "native-tls"),
    not(target_arch = "wasm32")
))]
#[cfg_attr(
    docsrs,
    doc(cfg(all(
        any(feature = "reqwest", feature = "native-tls"),
        not(target_arch = "wasm32")
    )))
)]
pub type DefaultSleep = TokioSleep;

/// The target-selected HTTP transport.
///
/// On `wasm32-wasip2` this resolves to [`Wasip2Transport`]. The other target
/// selections are `ReqwestTransport` and `Wasip3Transport`.
#[cfg(all(target_arch = "wasm32", target_env = "p2"))]
#[cfg_attr(docsrs, doc(cfg(all(target_arch = "wasm32", target_env = "p2"))))]
pub type DefaultTransport = Wasip2Transport;

/// The target-selected retry sleeper.
///
/// On `wasm32-wasip2` this resolves to [`Wasip2Sleep`]. The other target
/// selections are `TokioSleep` and `Wasip3Sleep`.
#[cfg(all(target_arch = "wasm32", target_env = "p2"))]
#[cfg_attr(docsrs, doc(cfg(all(target_arch = "wasm32", target_env = "p2"))))]
pub type DefaultSleep = Wasip2Sleep;

/// The target-selected HTTP transport.
///
/// On `wasm32-wasip3` this resolves to [`Wasip3Transport`]. The other target
/// selections are `ReqwestTransport` and `Wasip2Transport`.
#[cfg(all(target_arch = "wasm32", target_env = "p3"))]
#[cfg_attr(docsrs, doc(cfg(all(target_arch = "wasm32", target_env = "p3"))))]
pub type DefaultTransport = Wasip3Transport;

/// The target-selected retry sleeper.
///
/// On `wasm32-wasip3` this resolves to [`Wasip3Sleep`]. The other target
/// selections are `TokioSleep` and `Wasip2Sleep`.
#[cfg(all(target_arch = "wasm32", target_env = "p3"))]
#[cfg_attr(docsrs, doc(cfg(all(target_arch = "wasm32", target_env = "p3"))))]
pub type DefaultSleep = Wasip3Sleep;

/// An async Jev API client backed by target-selected or custom I/O.
///
/// Use [`Client::from_env`] for the target's default transport, or
/// [`ClientBuilder::new`] with a custom [`Transport`]. Use [`Self::ask`] for a
/// [`QuestionSet`] and [`Self::evaluate`] for a runtime-built [`Questions`]
/// batch.
pub struct Client<T: Transport, S: Sleep = NoSleep> {
    base_url: String,
    api_key: String,
    model: Model,
    retry: RetryPolicy,
    transport: T,
    sleep: S,
    extra_headers: Vec<(HeaderName, HeaderValue)>,
}

#[cfg(any(
    all(
        any(feature = "reqwest", feature = "native-tls"),
        not(target_arch = "wasm32")
    ),
    all(target_arch = "wasm32", target_env = "p2"),
    all(target_arch = "wasm32", target_env = "p3")
))]
impl Client<DefaultTransport, DefaultSleep> {
    /// Starts configuring a client with the target's default transport.
    ///
    /// Use [`ClientBuilder::new`] when supplying a custom transport.
    ///
    /// ```no_run
    /// use jevrs::{Client, Error};
    ///
    /// # fn configured() -> Result<(), Error> {
    /// let client = Client::builder()
    ///     .from_env()?
    ///     .build()?;
    /// # let _ = client;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn builder() -> ClientBuilder<DefaultTransport, DefaultSleep> {
        ClientBuilder::new(DefaultTransport::default()).sleep(DefaultSleep::default())
    }

    /// Creates a client from standard Jev environment variables.
    ///
    /// ```no_run
    /// use jevrs::{Client, Error};
    ///
    /// # fn configured() -> Result<(), Error> {
    /// let client = Client::from_env()?;
    /// # let _ = client;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`] when `TYPESAFE_API_KEY` is unavailable, or a
    /// configuration error when the environment contains an invalid base URL.
    pub fn from_env() -> Result<Self, Error> {
        Self::builder().from_env()?.build()
    }
}

impl<T: Transport, S: Sleep> Client<T, S> {
    /// Asks a statically declared question set using the configured model.
    ///
    /// The returned [`Answered`] value exposes generated fields directly while
    /// retaining model and token-usage metadata.
    ///
    /// ```no_run
    /// use jevrs::{Client, Noul, Questions};
    ///
    /// #[derive(Questions)]
    /// struct Triage {
    ///     #[jev(noul = "Does this convey urgency?")]
    ///     is_urgent: Noul,
    /// }
    ///
    /// # async fn run() -> Result<(), jevrs::Error> {
    /// let client = Client::from_env()?;
    /// let triage = client
    ///     .ask::<Triage>(&"Help! My payouts have been failing for 3 days.")
    ///     .await?;
    /// println!("urgent probability: {:.2}", triage.is_urgent.p.get());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns a question-building, encoding, transport, HTTP, or decoding
    /// [`Error`].
    pub async fn ask<Q: QuestionSet>(&self, state: &impl Serialize) -> Result<Answered<Q>, Error> {
        self.ask_with::<Q>(&self.model, state).await
    }

    /// Asks a statically declared question set with a one-request model override.
    ///
    /// Use this instead of [`Self::ask`] when most requests use the client's
    /// configured model but one must use another [`Model`].
    ///
    /// # Errors
    ///
    /// Returns a question-building, encoding, transport, HTTP, or decoding
    /// [`Error`].
    pub async fn ask_with<Q: QuestionSet>(
        &self,
        model: &Model,
        state: &impl Serialize,
    ) -> Result<Answered<Q>, Error> {
        let (questions, handles) = Q::questions()?;
        let answers = self.evaluate_with(model, state, &questions).await?;
        Ok(Answered::from_answers(&handles, &answers))
    }

    /// Evaluates a runtime-built question batch using the configured model.
    ///
    /// Use [`Self::ask`] instead when a [`QuestionSet`] defines the schema.
    ///
    /// # Errors
    ///
    /// Returns an encoding, transport, HTTP, or response-decoding [`Error`].
    pub async fn evaluate(
        &self,
        state: &impl Serialize,
        questions: &Questions,
    ) -> Result<Answers, Error> {
        self.evaluate_with(&self.model, state, questions).await
    }

    /// Evaluates a runtime-built batch with a one-request model override.
    ///
    /// Use this instead of [`Self::evaluate`] when only this request needs a
    /// different [`Model`].
    ///
    /// # Errors
    ///
    /// Returns an encoding, transport, HTTP, or response-decoding [`Error`].
    pub async fn evaluate_with(
        &self,
        model: &Model,
        state: &impl Serialize,
        questions: &Questions,
    ) -> Result<Answers, Error> {
        let request_body = encode(model, state, questions)?;
        let response_body = self.send(Method::POST, EVALUATE_PATH, request_body).await?;
        decode(questions, &response_body)
    }

    /// Lists models when an application needs discovery instead of a known alias.
    ///
    /// # Errors
    ///
    /// Returns a transport, HTTP, or JSON-decoding [`Error`].
    pub async fn models(&self) -> Result<Vec<ModelInfo>, Error> {
        let body = self.send(Method::GET, MODELS_PATH, Vec::new()).await?;
        let response: ModelsResponse = serde_json::from_slice(&body)?;
        Ok(response.models)
    }

    async fn send(&self, method: Method, path: &str, body: Vec<u8>) -> Result<Vec<u8>, Error> {
        let mut attempt = 0;
        loop {
            let request = self.request(method.clone(), path, body.clone())?;
            match self.transport.send(request).await {
                Ok(response) if response.status().is_success() => return Ok(response.into_body()),
                Ok(response) => {
                    let error = classify_response(&response);
                    let retry_after = match &error {
                        Error::RateLimited { retry_after, .. } => *retry_after,
                        Error::Overloaded { .. } => None,
                        _ => return Err(error),
                    };
                    if attempt >= self.retry.max_retries {
                        return Err(error);
                    }
                    self.sleep
                        .sleep(self.retry.delay_for(attempt, retry_after))
                        .await;
                }
                Err(error) => {
                    if attempt >= self.retry.max_retries || !T::is_retryable(&error) {
                        return Err(Error::Transport(Box::new(error)));
                    }
                    self.sleep.sleep(self.retry.delay_for(attempt, None)).await;
                }
            }
            attempt += 1;
        }
    }

    fn request(
        &self,
        method: Method,
        path: &str,
        body: Vec<u8>,
    ) -> Result<Request<Vec<u8>>, Error> {
        let authorization = HeaderValue::from_str(&format!("Bearer {}", self.api_key))
            .map_err(|error| config(error.to_string()))?;
        let mut builder = Request::builder()
            .method(method)
            .uri(format!("{}{path}", self.base_url))
            .header(AUTHORIZATION, authorization)
            .header(CONTENT_TYPE, "application/json")
            .header(ACCEPT, "application/json")
            .header(USER_AGENT, concat!("jevrs/", env!("CARGO_PKG_VERSION")));
        for (name, value) in &self.extra_headers {
            builder = builder.header(name, value);
        }
        builder
            .body(body)
            .map_err(|error| config(error.to_string()))
    }
}

impl<T: Transport, S: Sleep> fmt::Debug for Client<T, S> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Client")
            .field("base_url", &self.base_url)
            .field("api_key", &"***")
            .field("model", &self.model)
            .field("retry", &self.retry)
            .field("extra_header_count", &self.extra_headers.len())
            .finish_non_exhaustive()
    }
}

/// Configures a [`Client`] without coupling it to a particular runtime.
///
/// Supplying a [`Sleep`] implementation enables the configured retry policy;
/// the default [`NoSleep`] forces retries off.
///
/// ```no_run
/// use jevrs::{Client, ClientBuilder, Error, Model, Transport};
///
/// fn configured<T: Transport>(transport: T) -> Result<Client<T>, Error> {
///     let builder: ClientBuilder<T> = ClientBuilder::new(transport);
///     builder.from_env()?.model(Model::PREVIEW).build()
/// }
/// ```
pub struct ClientBuilder<T: Transport, S: Sleep = NoSleep> {
    base_url: String,
    api_key: Option<String>,
    model: Model,
    retry: RetryPolicy,
    transport: T,
    sleep: S,
    extra_headers: Vec<(HeaderName, HeaderValue)>,
}

impl<T: Transport> ClientBuilder<T, NoSleep> {
    /// Starts a client with a custom transport and retries disabled.
    ///
    /// Add a [`Sleep`] with [`Self::sleep`] to enable retry delays.
    #[must_use]
    pub fn new(transport: T) -> Self {
        Self {
            base_url: DEFAULT_BASE_URL.into(),
            api_key: None,
            model: Model::default(),
            retry: RetryPolicy::default(),
            transport,
            sleep: NoSleep,
            extra_headers: Vec::new(),
        }
    }
}

impl<T: Transport, S: Sleep> ClientBuilder<T, S> {
    /// Sets a bearer token supplied directly by the application.
    ///
    /// Use [`Self::from_env`] when configuration should come from standard Jev
    /// environment variables.
    #[must_use]
    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        self.api_key = Some(key.into());
        self
    }

    /// Loads credentials and optional endpoint overrides from the environment.
    ///
    /// `TYPESAFE_BASE_URL` takes precedence over `TYPESAFE_API_BASE`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`] when `TYPESAFE_API_KEY` is unavailable.
    pub fn from_env(mut self) -> Result<Self, Error> {
        let api_key = env::var("TYPESAFE_API_KEY")
            .map_err(|_| missing_api_key("TYPESAFE_API_KEY is not set"))?;
        self.api_key = Some(api_key);
        if let Ok(base_url) = env::var("TYPESAFE_BASE_URL") {
            self.base_url = base_url;
        } else if let Ok(base_url) = env::var("TYPESAFE_API_BASE") {
            self.base_url = base_url;
        }
        Ok(self)
    }

    /// Overrides the API origin for a proxy, test server, or compatible endpoint.
    ///
    /// One trailing slash is tolerated.
    #[must_use]
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = base_url.into();
        self
    }

    /// Sets the default model used by [`Client::ask`] and [`Client::evaluate`].
    #[must_use]
    pub fn model(mut self, model: Model) -> Self {
        self.model = model;
        self
    }

    /// Replaces retry limits and backoff when the defaults do not fit the caller.
    #[must_use]
    pub fn retry(mut self, retry: RetryPolicy) -> Self {
        self.retry = retry;
        self
    }

    /// Supplies the timer used between retry attempts.
    ///
    /// A client built with [`NoSleep`] always has zero retries.
    #[must_use]
    pub fn sleep<S2: Sleep>(self, sleep: S2) -> ClientBuilder<T, S2> {
        ClientBuilder {
            base_url: self.base_url,
            api_key: self.api_key,
            model: self.model,
            retry: self.retry,
            transport: self.transport,
            sleep,
            extra_headers: self.extra_headers,
        }
    }

    /// Appends a header for proxy routing, tracing, or another integration need.
    #[must_use]
    pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
        self.extra_headers.push((name, value));
        self
    }

    /// Validates configuration at startup and creates the reusable client.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`] when no API key was configured, or
    /// [`Error::Config`] when the base URL cannot form a valid endpoint URI.
    pub fn build(mut self) -> Result<Client<T, S>, Error> {
        let api_key = self
            .api_key
            .take()
            .ok_or_else(|| missing_api_key("TYPESAFE_API_KEY was not configured"))?;
        if let Some(stripped) = self.base_url.strip_suffix('/') {
            self.base_url = stripped.into();
        }
        format!("{}{}", self.base_url, EVALUATE_PATH)
            .parse::<http::Uri>()
            .map_err(|error| config(error.to_string()))?;
        if !S::RETRIES_ENABLED {
            self.retry.max_retries = 0;
        }
        Ok(Client {
            base_url: self.base_url,
            api_key,
            model: self.model,
            retry: self.retry,
            transport: self.transport,
            sleep: self.sleep,
            extra_headers: self.extra_headers,
        })
    }
}

impl<T: Transport, S: Sleep> fmt::Debug for ClientBuilder<T, S> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ClientBuilder")
            .field("base_url", &self.base_url)
            .field("api_key", &"***")
            .field("model", &self.model)
            .field("retry", &self.retry)
            .field("extra_header_count", &self.extra_headers.len())
            .finish_non_exhaustive()
    }
}

#[derive(Deserialize)]
struct ModelsResponse {
    models: Vec<ModelInfo>,
}

fn classify_response(response: &Response<Vec<u8>>) -> Error {
    let status = response.status().as_u16();
    let retry_after = response
        .headers()
        .get("retry-after")
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.parse::<u64>().ok())
        .map(Duration::from_secs);
    let request_id = response
        .headers()
        .get("x-typesafe-request-id")
        .and_then(|value| value.to_str().ok())
        .map(str::to_owned);
    classify(status, response.body(), retry_after, request_id.as_deref())
}

fn missing_api_key(message: &str) -> Error {
    Error::Auth {
        status: StatusCode::UNAUTHORIZED.as_u16(),
        detail: ErrorDetail {
            error_type: Some("configuration_error".into()),
            message: Some(message.into()),
            request_id: None,
            raw: String::new(),
        },
    }
}

fn config(reason: String) -> Error {
    Error::Config { reason }
}

#[cfg(all(test, feature = "test-util"))]
mod tests {
    use std::time::Duration;

    use http::{HeaderName, HeaderValue, Method, Response, header};
    use jevrs_core::{
        Answers, DynChoiceAnswer, DynChoiceQ, DynScoreAnswer, DynScoreQ, Handle, Model, NoulAnswer,
        NoulQ, QuestionSet, Questions,
    };
    use serde_json::{Value, json};

    use super::{Client, ClientBuilder, Error};
    use crate::{
        MockError, MockSleep, MockTransport, RetryPolicy,
        test_support::{block_on, fixtures},
    };

    const KEY: &str = "super-secret-key";
    #[cfg(all(
        any(feature = "reqwest", feature = "native-tls"),
        not(target_arch = "wasm32")
    ))]
    const DEFAULT_FROM_ENV_CASE: &str = "JEVRS_DEFAULT_FROM_ENV_TEST_CASE";

    #[test]
    #[cfg(any(
        all(
            any(feature = "reqwest", feature = "native-tls"),
            not(target_arch = "wasm32")
        ),
        all(target_arch = "wasm32", target_env = "p2"),
        all(target_arch = "wasm32", target_env = "p3")
    ))]
    fn default_builder_uses_target_selected_io() {
        let _: ClientBuilder<super::DefaultTransport, super::DefaultSleep> = Client::builder();
    }

    #[test]
    fn custom_builder_builds_with_no_sleep() {
        let _: Client<MockTransport, crate::NoSleep> = ClientBuilder::new(MockTransport::default())
            .api_key(KEY)
            .build()
            .unwrap();
    }

    #[test]
    #[cfg(all(
        any(feature = "reqwest", feature = "native-tls"),
        not(target_arch = "wasm32")
    ))]
    fn default_from_env_matches_builder_from_env() {
        match std::env::var(DEFAULT_FROM_ENV_CASE).as_deref() {
            Ok("unset") => {
                let default_error = Client::from_env().unwrap_err();
                let builder_error = Client::builder().from_env().unwrap_err();
                let Error::Auth {
                    status: default_status,
                    detail: default_detail,
                } = default_error
                else {
                    panic!("default client returned the wrong error: {default_error}");
                };
                let Error::Auth {
                    status: builder_status,
                    detail: builder_detail,
                } = builder_error
                else {
                    panic!("builder returned the wrong error: {builder_error}");
                };
                assert_eq!(default_status, builder_status);
                assert_eq!(default_detail, builder_detail);
            }
            Ok("set") => {
                let _: Client<super::DefaultTransport, super::DefaultSleep> =
                    Client::from_env().unwrap();
            }
            _ => {
                run_default_from_env_case("unset", None);
                run_default_from_env_case("set", Some(KEY));
            }
        }
    }

    #[cfg(all(
        any(feature = "reqwest", feature = "native-tls"),
        not(target_arch = "wasm32")
    ))]
    // A subprocess provides two environment states because edition 2024 makes `std::env::set_var` unsafe and this crate forbids unsafe code.
    fn run_default_from_env_case(case: &str, api_key: Option<&str>) {
        let mut command = std::process::Command::new(std::env::current_exe().unwrap());
        command
            .args([
                "--exact",
                "client::tests::default_from_env_matches_builder_from_env",
                "--nocapture",
            ])
            .env(DEFAULT_FROM_ENV_CASE, case)
            .env_remove("TYPESAFE_BASE_URL")
            .env_remove("TYPESAFE_API_BASE");
        if let Some(api_key) = api_key {
            command.env("TYPESAFE_API_KEY", api_key);
        } else {
            command.env_remove("TYPESAFE_API_KEY");
        }
        let output = command.output().unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            output.status.success(),
            "child test failed:\nstdout:\n{}\nstderr:\n{}",
            stdout,
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(
            stdout.contains("1 passed"),
            "child test filter matched nothing:\nstdout:\n{stdout}"
        );
    }

    fn fixture_body(name: &str) -> Vec<u8> {
        serde_json::to_vec(&fixtures::load(name, "response")["body"]).unwrap()
    }

    fn response(status: u16, body: &[u8]) -> Response<Vec<u8>> {
        Response::builder()
            .status(status)
            .header("x-typesafe-request-id", "req_deadbeef")
            .body(body.to_vec())
            .unwrap()
    }

    fn fixed_retry() -> RetryPolicy {
        RetryPolicy {
            jitter: false,
            ..RetryPolicy::default()
        }
    }

    #[test]
    fn evaluate_frames_method_url_headers_and_body() {
        let transport = MockTransport::new([Ok(response(200, &fixture_body("triage")))]);
        let recorder = transport.clone();
        let client = ClientBuilder::new(transport)
            .api_key(KEY)
            .base_url("https://example.test")
            .header(
                HeaderName::from_static("x-extra"),
                HeaderValue::from_static("last"),
            )
            .build()
            .unwrap();
        let (questions, _, _, _) = fixtures::triage();

        block_on(client.evaluate(&fixtures::STATE, &questions)).unwrap();

        let mut requests = recorder.take_requests();
        let request = requests.pop().unwrap();
        assert_eq!(request.method(), Method::POST);
        assert_eq!(request.uri(), "https://example.test/v1/systemone");
        assert_eq!(request.headers().len(), 5);
        assert_eq!(
            request.headers()[header::AUTHORIZATION],
            "Bearer super-secret-key"
        );
        assert_eq!(request.headers()[header::CONTENT_TYPE], "application/json");
        assert_eq!(request.headers()[header::ACCEPT], "application/json");
        assert_eq!(
            request.headers()[header::USER_AGENT],
            concat!("jevrs/", env!("CARGO_PKG_VERSION"))
        );
        assert_eq!(request.headers()["x-extra"], "last");
        let body: Value = serde_json::from_slice(request.body()).unwrap();
        assert_eq!(body["state"], fixtures::STATE);
        assert_eq!(body["model"], "jev-latest");
        assert_eq!(body["questions"].as_object().unwrap().len(), 3);
    }

    struct Triage;

    struct TriageHandles {
        is_urgent: Handle<NoulQ>,
        department: Handle<DynChoiceQ>,
        frustration: Handle<DynScoreQ>,
    }

    struct TriageAnswers {
        is_urgent: NoulAnswer,
        department: DynChoiceAnswer,
        frustration: DynScoreAnswer,
    }

    impl QuestionSet for Triage {
        type Handles = TriageHandles;
        type Answers = TriageAnswers;

        fn questions() -> Result<(Questions, Self::Handles), jevrs_core::Error> {
            let (questions, is_urgent, department, frustration) = fixtures::triage();
            Ok((
                questions,
                TriageHandles {
                    is_urgent,
                    department,
                    frustration,
                },
            ))
        }

        fn answers(handles: &Self::Handles, answers: &Answers) -> Self::Answers {
            TriageAnswers {
                is_urgent: Clone::clone(answers.get(handles.is_urgent)),
                department: Clone::clone(answers.get(handles.department)),
                frustration: Clone::clone(answers.get(handles.frustration)),
            }
        }
    }

    #[test]
    fn ask_sends_derived_shape_and_returns_typed_result() {
        let transport = MockTransport::new([Ok(response(200, &fixture_body("triage")))]);
        let recorder = transport.clone();
        let client = ClientBuilder::new(transport).api_key(KEY).build().unwrap();

        let triage = block_on(client.ask::<Triage>(&fixtures::STATE)).unwrap();

        let request = recorder.take_requests().pop().unwrap();
        let body: Value = serde_json::from_slice(request.body()).unwrap();
        assert_eq!(body, fixtures::load("triage", "request"));
        assert!((triage.is_urgent.p.get() - 0.95).abs() < f64::EPSILON);
        assert_eq!(triage.department.pick, "billing");
        assert_eq!(triage.frustration.nearest(), 1);
        assert_eq!(triage.model(), "jev-1.13.0");
        assert_eq!(triage.usage().input_tokens, 414);
    }

    #[test]
    fn models_frames_method_url_and_full_headers() {
        let transport = MockTransport::new([Ok(response(200, &fixture_body("models")))]);
        let recorder = transport.clone();
        let client = ClientBuilder::new(transport)
            .api_key(KEY)
            .base_url("https://example.test")
            .build()
            .unwrap();

        block_on(client.models()).unwrap();

        let request = recorder.take_requests().pop().unwrap();
        assert_eq!(request.method(), Method::GET);
        assert_eq!(request.uri(), "https://example.test/v1/models");
        assert!(request.body().is_empty());
        assert_eq!(request.headers().len(), 4);
        assert_eq!(
            request.headers()[header::AUTHORIZATION],
            "Bearer super-secret-key"
        );
        assert_eq!(request.headers()[header::CONTENT_TYPE], "application/json");
        assert_eq!(request.headers()[header::ACCEPT], "application/json");
        assert_eq!(
            request.headers()[header::USER_AGENT],
            concat!("jevrs/", env!("CARGO_PKG_VERSION"))
        );
    }

    #[test]
    fn base_url_accepts_one_trailing_slash() {
        for base_url in ["https://example.test", "https://example.test/"] {
            let transport = MockTransport::new([Ok(response(200, &fixture_body("models")))]);
            let recorder = transport.clone();
            let client = ClientBuilder::new(transport)
                .api_key(KEY)
                .base_url(base_url)
                .build()
                .unwrap();

            block_on(client.models()).unwrap();

            assert_eq!(
                recorder.take_requests().pop().unwrap().uri(),
                "https://example.test/v1/models"
            );
        }
    }

    #[test]
    fn malformed_base_url_is_a_configuration_error() {
        let error = ClientBuilder::new(MockTransport::default())
            .api_key(KEY)
            .base_url("not a url")
            .build()
            .unwrap_err();

        assert!(matches!(error, jevrs_core::Error::Config { .. }));
    }

    #[test]
    fn invalid_authorization_value_is_a_configuration_error() {
        let client = ClientBuilder::new(MockTransport::default())
            .api_key("bad\nkey")
            .build()
            .unwrap();
        let (questions, _, _, _) = fixtures::triage();

        let error = block_on(client.evaluate(&fixtures::STATE, &questions)).unwrap_err();

        assert!(matches!(error, jevrs_core::Error::Config { .. }));
    }

    #[test]
    fn evaluate_with_overrides_the_body_model() {
        let transport = MockTransport::new([Ok(response(200, &fixture_body("triage")))]);
        let recorder = transport.clone();
        let client = ClientBuilder::new(transport).api_key(KEY).build().unwrap();
        let (questions, _, _, _) = fixtures::triage();

        block_on(client.evaluate_with(&Model::PREVIEW, &fixtures::STATE, &questions)).unwrap();

        let request = recorder.take_requests().pop().unwrap();
        let body: Value = serde_json::from_slice(request.body()).unwrap();
        assert_eq!(body["model"], "jev-preview");
    }

    #[test]
    fn recorded_triage_pair_round_trips() {
        let transport = MockTransport::new([Ok(response(200, &fixture_body("triage")))]);
        let client = ClientBuilder::new(transport).api_key(KEY).build().unwrap();
        let (questions, urgent, department, frustration) = fixtures::triage();

        let answers = block_on(client.evaluate(&fixtures::STATE, &questions)).unwrap();

        assert_eq!(answers.model(), "jev-1.13.0");
        assert!(answers[urgent].is_yes(0.9));
        assert_eq!(answers[department].pick, "billing");
        assert!((0.0..=2.0).contains(&answers[frustration].expected()));
        assert_eq!(answers.usage().input_tokens, 414);
    }

    #[test]
    fn rate_limit_retries_once_with_policy_delay() {
        let transport = MockTransport::new([
            Ok(response(429, br#"{"detail":"slow down"}"#)),
            Ok(response(200, &fixture_body("triage"))),
        ]);
        let recorder = transport.clone();
        let sleep = MockSleep::default();
        let sleep_recorder = sleep.clone();
        let policy = fixed_retry();
        let client = ClientBuilder::new(transport)
            .api_key(KEY)
            .retry(policy)
            .sleep(sleep)
            .build()
            .unwrap();
        let (questions, _, _, _) = fixtures::triage();

        block_on(client.evaluate(&fixtures::STATE, &questions)).unwrap();

        assert_eq!(recorder.take_requests().len(), 2);
        assert_eq!(sleep_recorder.take_durations(), [policy.delay_for(0, None)]);
    }

    #[test]
    fn retry_after_integer_seconds_takes_precedence() {
        let limited = Response::builder()
            .status(429)
            .header("retry-after", "2")
            .body(br#"{"detail":"slow down"}"#.to_vec())
            .unwrap();
        let transport =
            MockTransport::new([Ok(limited), Ok(response(200, &fixture_body("triage")))]);
        let sleep = MockSleep::default();
        let sleep_recorder = sleep.clone();
        let client = ClientBuilder::new(transport)
            .api_key(KEY)
            .sleep(sleep)
            .build()
            .unwrap();
        let (questions, _, _, _) = fixtures::triage();

        block_on(client.evaluate(&fixtures::STATE, &questions)).unwrap();

        assert_eq!(sleep_recorder.take_durations(), [Duration::from_secs(2)]);
    }

    #[test]
    fn overload_exhausts_retries() {
        let transport = MockTransport::new([
            Ok(response(529, br#"{"detail":"busy"}"#)),
            Ok(response(529, br#"{"detail":"busy"}"#)),
            Ok(response(529, br#"{"detail":"busy"}"#)),
        ]);
        let recorder = transport.clone();
        let sleep = MockSleep::default();
        let sleep_recorder = sleep.clone();
        let client = ClientBuilder::new(transport)
            .api_key(KEY)
            .retry(fixed_retry())
            .sleep(sleep)
            .build()
            .unwrap();
        let (questions, _, _, _) = fixtures::triage();

        let error = block_on(client.evaluate(&fixtures::STATE, &questions)).unwrap_err();

        assert!(matches!(error, jevrs_core::Error::Overloaded { .. }));
        assert_eq!(recorder.take_requests().len(), 3);
        assert_eq!(
            sleep_recorder.take_durations(),
            [Duration::from_millis(500), Duration::from_secs(1)]
        );
    }

    #[test]
    fn authentication_failure_does_not_retry() {
        let transport = MockTransport::new([
            Ok(response(401, br#"{"detail":"bad key"}"#)),
            Ok(response(200, &fixture_body("triage"))),
        ]);
        let recorder = transport.clone();
        let sleep = MockSleep::default();
        let sleep_recorder = sleep.clone();
        let client = ClientBuilder::new(transport)
            .api_key(KEY)
            .sleep(sleep)
            .build()
            .unwrap();
        let (questions, _, _, _) = fixtures::triage();

        let error = block_on(client.evaluate(&fixtures::STATE, &questions)).unwrap_err();

        let jevrs_core::Error::Auth { detail, .. } = error else {
            panic!("expected authentication error");
        };
        assert_eq!(detail.request_id.as_deref(), Some("req_deadbeef"));
        assert_eq!(recorder.take_requests().len(), 1);
        assert!(sleep_recorder.take_durations().is_empty());
    }

    #[test]
    fn transport_retryability_controls_retries() {
        let retrying = MockTransport::new([
            Err(MockError { retryable: true }),
            Ok(response(200, &fixture_body("triage"))),
        ]);
        let retrying_recorder = retrying.clone();
        let client = ClientBuilder::new(retrying)
            .api_key(KEY)
            .sleep(MockSleep::default())
            .build()
            .unwrap();
        let (questions, _, _, _) = fixtures::triage();
        block_on(client.evaluate(&fixtures::STATE, &questions)).unwrap();
        assert_eq!(retrying_recorder.take_requests().len(), 2);

        let failing = MockTransport::new([
            Err(MockError { retryable: false }),
            Ok(response(200, &fixture_body("triage"))),
        ]);
        let failing_recorder = failing.clone();
        let client = ClientBuilder::new(failing)
            .api_key(KEY)
            .sleep(MockSleep::default())
            .build()
            .unwrap();
        let (questions, _, _, _) = fixtures::triage();
        let error = block_on(client.evaluate(&fixtures::STATE, &questions)).unwrap_err();
        assert!(matches!(error, jevrs_core::Error::Transport(_)));
        assert_eq!(failing_recorder.take_requests().len(), 1);
    }

    #[test]
    fn no_sleep_never_retries() {
        let transport = MockTransport::new([
            Ok(response(429, br#"{"detail":"slow down"}"#)),
            Ok(response(200, &fixture_body("triage"))),
        ]);
        let recorder = transport.clone();
        let client = ClientBuilder::new(transport)
            .api_key(KEY)
            .retry(fixed_retry())
            .build()
            .unwrap();
        let (questions, _, _, _) = fixtures::triage();

        let error = block_on(client.evaluate(&fixtures::STATE, &questions)).unwrap_err();

        assert!(matches!(error, jevrs_core::Error::RateLimited { .. }));
        assert_eq!(recorder.take_requests().len(), 1);
    }

    #[test]
    fn debug_redacts_api_key() {
        let builder = ClientBuilder::new(MockTransport::default()).api_key(KEY);
        let builder_debug = format!("{builder:?}");
        assert!(builder_debug.contains("***"));
        assert!(!builder_debug.contains(KEY));

        let client = builder.build().unwrap();
        let client_debug = format!("{client:?}");
        assert!(client_debug.contains("***"));
        assert!(!client_debug.contains(KEY));
    }

    #[test]
    fn models_parse_release_date_and_unknown_fields() {
        let mut body = fixtures::load("models", "response")["body"].clone();
        body["models"][0]["future_field"] = json!(true);
        let transport =
            MockTransport::new([Ok(response(200, &serde_json::to_vec(&body).unwrap()))]);
        let client = ClientBuilder::new(transport).api_key(KEY).build().unwrap();

        let models = block_on(client.models()).unwrap();

        assert_eq!(models[0].name, "jev-latest");
        assert_eq!(
            models[0].release_date.as_deref(),
            Some("2026-09-10T18:38:01.391457+00:00")
        );
        assert_eq!(models[0].extra["future_field"], json!(true));
    }
}