ultron-ai 1.0.2

Provider layer of packages/ai: message model, streaming events, every API implementation (Anthropic, OpenAI completions/responses/codex, Azure, Google, Vertex, Mistral, Bedrock, pi-messages, Claude Code CLI, Claude subscription), provider auth and every OAuth flow, images API, model catalog, user models.json, env API keys
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
//! HTTP transport seam, cancellation, SDK-shaped API errors and the provider retry policy
//! (`utils/provider-retry.ts`, `utils/error-body.ts`, and the error construction of the pinned OpenAI/Anthropic SDKs).

use crate::provider::{ProviderError, REQUEST_ABORTED};
use jsrt::json_parse::parse_json;
use serde_json::Value;
use std::collections::BTreeMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use tokio::sync::Notify;

pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// Lower-cased header names, as `fetch` `Headers` presents them.
pub type HeaderMap = BTreeMap<String, String>;

#[derive(Clone, Debug, PartialEq)]
pub struct HttpRequest {
    pub method: String,
    pub url: String,
    pub headers: HeaderMap,
    pub body: String,
}

/// The bytes `request` puts on the wire: its body, encoded as its `content-encoding` header names (`zstd`: one
/// zstd frame, as `zlib.zstdCompressSync` makes; ruzstd's fastest level, which any zstd decoder reads). Fake
/// transports see the JSON body and the header; a real one sends this.
pub fn wire_body(request: &HttpRequest) -> Vec<u8> {
    let zstd = request.headers.iter().any(|(name, value)| {
        name.eq_ignore_ascii_case("content-encoding") && value.trim().eq_ignore_ascii_case("zstd")
    });
    if !zstd {
        return request.body.clone().into_bytes();
    }
    ruzstd::encoding::compress_to_vec(request.body.as_bytes(), ruzstd::encoding::CompressionLevel::Fastest)
}

/// The body of a request received with `content_encoding` (a server's view of [`wire_body`]): `zstd` decoded, else
/// as is.
pub fn decode_wire_body(content_encoding: Option<&str>, bytes: &[u8]) -> Result<Vec<u8>, String> {
    if !content_encoding.is_some_and(|e| e.trim().eq_ignore_ascii_case("zstd")) {
        return Ok(bytes.to_vec());
    }
    let mut decoder = ruzstd::decoding::StreamingDecoder::new(bytes).map_err(|e| e.to_string())?;
    let mut out = Vec::new();
    std::io::Read::read_to_end(&mut decoder, &mut out).map_err(|e| e.to_string())?;
    Ok(out)
}

/// A response body read chunk by chunk; `Ok(None)` is the end.
pub trait Body: Send {
    fn next_chunk(&mut self) -> BoxFuture<'_, Result<Option<Vec<u8>>, String>>;
}

pub struct HttpResponse {
    pub status: u16,
    pub headers: HeaderMap,
    pub body: Box<dyn Body>,
}

/// Sends one request. `Err` is a connection failure (no response).
pub trait Transport: Send + Sync {
    fn send(&self, request: HttpRequest) -> BoxFuture<'_, Result<HttpResponse, String>>;

    /// This transport presenting a TLS client certificate (mTLS), as Node's `https.Agent({ cert, key })` does: the
    /// certificate (chain) and private key files' contents, PEM. A transport that cannot fails.
    fn with_client_identity(&self, cert: &[u8], key: &[u8]) -> Result<Arc<dyn Transport>, String> {
        let _ = (cert, key);
        Err("this HTTP transport cannot present a TLS client certificate".into())
    }

    /// A copy of this transport that owns its connections, for work that outlives the call on another thread and
    /// runtime (the AWS SDK's background credential refresh); `None` when it cannot, and that work is skipped.
    fn detached(&self) -> Option<Arc<dyn Transport>> {
        None
    }

    /// This transport speaking HTTP/1.1 only (the SDK's `NodeHttpHandler` in place of its HTTP/2 handler); `None`
    /// when it cannot, and requests keep this transport.
    fn http1_only(&self) -> Option<Arc<dyn Transport>> {
        None
    }

    /// Whether [`Transport::websocket`] opens sockets (the runtime has `WebSocket`); without, a provider that
    /// prefers WebSockets falls back as upstream does in a runtime without one.
    fn websocket_available(&self) -> bool {
        false
    }

    /// `new WebSocket(url, { headers })`, resolved once it is open: the socket, or why it could not open.
    fn websocket(
        &self,
        url: String,
        headers: HeaderMap,
    ) -> BoxFuture<'_, Result<Box<dyn crate::websocket::WebSocketConnection>, String>> {
        let _ = (url, headers);
        Box::pin(async { Err(crate::websocket::NO_WEBSOCKET.to_string()) })
    }
}

/// Request cancellation shared between the caller and the provider (`AbortSignal`).
#[derive(Clone, Debug, Default)]
pub struct AbortSignal(Arc<SignalState>);

#[derive(Debug, Default)]
struct SignalState {
    aborted: AtomicBool,
    notify: Notify,
}

impl AbortSignal {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn abort(&self) {
        self.0.aborted.store(true, Ordering::SeqCst);
        self.0.notify.notify_waiters();
    }

    pub fn aborted(&self) -> bool {
        self.0.aborted.load(Ordering::SeqCst)
    }

    pub async fn cancelled(&self) {
        loop {
            let notified = self.0.notify.notified();
            if self.aborted() {
                return;
            }
            notified.await;
        }
    }
}

pub(crate) fn is_aborted(signal: Option<&AbortSignal>) -> bool {
    signal.is_some_and(AbortSignal::aborted)
}

/// Resolves when `signal` aborts; never without one.
pub(crate) async fn cancelled(signal: Option<&AbortSignal>) {
    match signal {
        Some(signal) => signal.cancelled().await,
        None => std::future::pending().await,
    }
}

/// Which SDK's error construction to mirror.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Sdk {
    Anthropic,
    OpenAi,
}

/// A failed provider request or stream, carrying what upstream's error objects carry.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Failure {
    pub message: String,
    pub status: Option<u16>,
    pub headers: Option<Box<HeaderMap>>,
    /// The SDK error's `error` field (OpenAI: the body's `error` object; Anthropic: the whole body).
    pub error: Option<Box<Value>>,
    /// An SDK `APIError` (statusless only for connection failures); plain `Error`s are never retried.
    pub api: bool,
    /// Raw `error.metadata.raw` from an OpenAI error body.
    pub raw_metadata: Option<String>,
}

impl ProviderError for Failure {
    fn plain(message: String) -> Self {
        Failure::plain(message)
    }
}

impl Failure {
    pub fn plain(message: impl Into<String>) -> Self {
        Failure {
            message: message.into(),
            status: None,
            headers: None,
            error: None,
            api: false,
            raw_metadata: None,
        }
    }

    /// `APIError.makeMessage` and `APIError.generate` of both SDKs.
    pub fn api(
        sdk: Sdk,
        status: Option<u16>,
        headers: Option<HeaderMap>,
        body: Option<Value>,
        text: Option<String>,
    ) -> Self {
        let error = match sdk {
            Sdk::Anthropic => body.clone(),
            Sdk::OpenAi => body.as_ref().and_then(|b| b.get("error").cloned()),
        };
        let message_field = error
            .as_ref()
            .and_then(|e| e.get("message"))
            .filter(|m| jsrt::value::truthy(Some(m)));
        let msg = match (message_field, &error) {
            (Some(Value::String(s)), _) => Some(s.clone()),
            (Some(other), _) => Some(jsrt::json::stringify(other)),
            (None, Some(e)) if jsrt::value::truthy(Some(e)) => Some(jsrt::json::stringify(e)),
            _ => text.filter(|t| !t.is_empty()),
        };
        let message = match (status, msg) {
            (Some(status), Some(msg)) if !msg.is_empty() => format!("{status} {msg}"),
            (Some(status), _) => format!("{status} status code (no body)"),
            (None, Some(msg)) if !msg.is_empty() => msg,
            _ => "(no status code or body)".to_string(),
        };
        let raw_metadata = error
            .as_ref()
            .and_then(|e| e.pointer("/metadata/raw"))
            .filter(|r| jsrt::value::truthy(Some(r)))
            .map(|raw| jsrt::value::string(Some(raw)));
        Failure {
            message,
            status,
            headers: headers.map(Box::new),
            error: error.map(Box::new),
            api: true,
            raw_metadata,
        }
    }

    fn connection() -> Self {
        Failure {
            api: true,
            ..Failure::plain("Connection error.")
        }
    }

    /// The SDK's `APIConnectionTimeoutError` (statusless, so retried like a connection failure).
    fn timed_out() -> Self {
        Failure {
            api: true,
            ..Failure::plain(REQUEST_TIMED_OUT)
        }
    }

    fn header(&self, name: &str) -> Option<&str> {
        self.headers.as_ref()?.get(name).map(String::as_str)
    }
}

pub(crate) const MAX_PROVIDER_ERROR_BODY_CHARS: usize = 4000;

/// `formatProviderError(normalizeProviderError(error), prefix)`.
pub(crate) fn format_provider_error(failure: &Failure, prefix: Option<&str>) -> String {
    let body = failure
        .error
        .as_ref()
        .filter(|e| e.as_object().is_some_and(|o| !o.is_empty()))
        .map(|e| jsrt::json::stringify(e))
        .map(|text| text.trim().to_string())
        .filter(|text| !text.is_empty())
        .map(|text| truncate_error_text(&text, MAX_PROVIDER_ERROR_BODY_CHARS));
    let carries_body = body.as_ref().is_none_or(|b| failure.message.contains(b.as_str()));
    match (carries_body, failure.status, body) {
        (false, Some(status), Some(body)) => match prefix {
            Some(prefix) => format!("{prefix} ({status}): {body}"),
            None => format!("{status}: {body}"),
        },
        (_, status, _) => match (prefix, status) {
            (Some(prefix), Some(status)) => format!("{prefix} ({status}): {}", failure.message),
            _ => failure.message.clone(),
        },
    }
}

pub(crate) fn truncate_error_text(text: &str, max: usize) -> String {
    let len = jsrt::utf16::len(text);
    if len <= max {
        return text.to_string();
    }
    format!("{}... [truncated {} chars]", jsrt::utf16::head(text, max), len - max)
}

#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct RetryOptions {
    pub max_retries: Option<u32>,
    pub max_retry_delay_ms: Option<f64>,
    /// The SDKs' per-request `timeout` (`options.timeoutMs`): the longest wait for the response headers of one
    /// attempt; it ends as `APIConnectionTimeoutError` ("Request timed out."), which is retried.
    pub timeout_ms: Option<u64>,
}

pub(crate) const DEFAULT_MAX_RETRY_DELAY_MS: f64 = 60_000.0;

fn is_retryable(failure: &Failure) -> bool {
    match failure.header("x-should-retry") {
        Some("true") => return true,
        Some("false") => return false,
        _ => {}
    }
    match failure.status {
        None => true,
        Some(status) => matches!(status, 408 | 409 | 429) || status >= 500,
    }
}

fn validate_delay(delay_ms: f64, max: Option<f64>, message: &str) -> Result<f64, Failure> {
    let max = max.unwrap_or(DEFAULT_MAX_RETRY_DELAY_MS);
    if max > 0.0 && delay_ms > max {
        return Err(Failure::plain(format!(
            "Server requested {}s retry delay (max: {}s). {message}",
            (delay_ms / 1000.0).ceil(),
            (max / 1000.0).ceil()
        )));
    }
    Ok(delay_ms)
}

/// `Date.parse(text) - Date.now()` for a `retry-after` HTTP date (`Wed, 21 Oct 2015 07:28:00 GMT`); `None` (NaN) when
/// it is not one.
pub(crate) fn until_http_date_ms(text: &str) -> Option<f64> {
    let date = parse_http_date(text)?;
    Some((date - jsrt::date::now_ms()) as f64)
}

/// `Date.parse` of the IMF-fixdate a `retry-after` header holds (`Sun, 06 Nov 1994 08:49:37 GMT`); `None` (NaN) for
/// anything else. Only the literal `GMT` zone is read: RFC 9110 senders write no other, and V8 would apply the offset
/// of a named zone such as `PST`.
pub fn parse_http_date(text: &str) -> Option<i64> {
    const MONTHS: [&str; 12] = [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    ];
    let parts: Vec<&str> = text.split_whitespace().collect();
    let [_, day, month, year, time, "GMT"] = parts[..] else {
        return None;
    };
    let month = MONTHS.iter().position(|m| m.eq_ignore_ascii_case(month))? as u32 + 1;
    let hms: Vec<i64> = time.split(':').map(|p| p.parse().ok()).collect::<Option<_>>()?;
    let [h, m, s] = hms[..] else {
        return None;
    };
    let days = jsrt::date::days_from_civil(year.parse().ok()?, month, day.parse().ok()?);
    Some((days * 86_400 + h * 3600 + m * 60 + s) * 1000)
}

/// Delay before retry `retry_index`. A non-numeric `retry-after` is an HTTP date: wait until then (a past date at
/// once); one that does not parse is `NaN` upstream, which passes the cap and sleeps 0 ms.
fn retry_delay_ms(failure: &Failure, retry_index: u32, max: Option<f64>) -> Result<f64, Failure> {
    if let Some(value) = failure
        .header("retry-after-ms")
        .filter(|v| !v.is_empty())
        .map(jsrt::number::parse_float)
        .filter(|v| !v.is_nan())
    {
        return validate_delay(value, max, &failure.message);
    }
    if let Some(retry_after) = failure.header("retry-after").filter(|v| !v.is_empty()) {
        let seconds = jsrt::number::parse_float(retry_after);
        let delay = if seconds.is_nan() {
            until_http_date_ms(retry_after).unwrap_or(0.0)
        } else {
            seconds * 1000.0
        };
        return validate_delay(delay, max, &failure.message);
    }
    let exponential = (0.5 * 2f64.powi(retry_index as i32)).min(8.0) * 1000.0;
    Ok(exponential * (1.0 - jitter() * 0.25))
}

fn jitter() -> f64 {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.subsec_nanos());
    f64::from(nanos % 1_000_000) / 1_000_000.0
}

/// Send `request` and turn a non-2xx response into the SDK's `APIError`, retrying like `retryProviderRequest`.
pub(crate) async fn send_with_retry(
    transport: &dyn Transport,
    request: &HttpRequest,
    sdk: Sdk,
    retry: RetryOptions,
    signal: Option<&AbortSignal>,
) -> Result<HttpResponse, Failure> {
    let max_retries = retry.max_retries.unwrap_or(0);
    crate::provider::retry(
        signal,
        || Failure::plain(REQUEST_ABORTED),
        |_| send_once(transport, request, sdk, retry.timeout_ms, signal),
        |failure, retry_index| {
            if is_aborted(signal) {
                return Err(Failure::plain(REQUEST_ABORTED));
            }
            if retry_index >= max_retries || !failure.api || !is_retryable(&failure) {
                return Err(failure);
            }
            retry_delay_ms(&failure, retry_index, retry.max_retry_delay_ms)
        },
    )
    .await
}

async fn send_once(
    transport: &dyn Transport,
    request: &HttpRequest,
    sdk: Sdk,
    timeout_ms: Option<u64>,
    signal: Option<&AbortSignal>,
) -> Result<HttpResponse, Failure> {
    if is_aborted(signal) {
        return Err(Failure {
            api: true,
            ..Failure::plain("Request was aborted.")
        });
    }
    let timed_out = async {
        match timeout_ms {
            Some(ms) => tokio::time::sleep(Duration::from_millis(ms)).await,
            None => std::future::pending().await,
        }
    };
    let sent = tokio::select! {
        sent = transport.send(request.clone()) => sent,
        () = cancelled(signal) => return Err(Failure { api: true, ..Failure::plain("Request was aborted.") }),
        () = timed_out => return Err(Failure { api: true, ..Failure::plain("Request timed out.") }),
    };
    let mut response = sent.map_err(|error| {
        if error == REQUEST_TIMED_OUT {
            Failure::timed_out()
        } else {
            Failure::connection()
        }
    })?;
    if (200..300).contains(&response.status) {
        return Ok(response);
    }
    let mut bytes = Vec::new();
    while let Ok(Some(chunk)) = response.body.next_chunk().await {
        bytes.extend_from_slice(&chunk);
    }
    let text = String::from_utf8_lossy(&bytes).into_owned();
    let body = parse_json(&text).ok().filter(|body| jsrt::value::truthy(Some(body)));
    let text = if body.is_some() { None } else { Some(text) };
    Err(Failure::api(
        sdk,
        Some(response.status),
        Some(response.headers),
        body,
        text,
    ))
}

/// What a [`TimeoutTransport`] fails a request with; [`send_with_retry`] reports it as the SDK's
/// `APIConnectionTimeoutError`.
pub(crate) const REQUEST_TIMED_OUT: &str = "Request timed out.";

/// A transport whose requests fail with [`REQUEST_TIMED_OUT`] when the response headers take longer than `timeout`
/// (the OpenAI SDK's request `timeout`: aborted until `fetch` resolves, not while the body is read).
pub(crate) struct TimeoutTransport<'a> {
    pub inner: &'a dyn Transport,
    pub timeout: Duration,
}

impl Transport for TimeoutTransport<'_> {
    fn send(&self, request: HttpRequest) -> BoxFuture<'_, Result<HttpResponse, String>> {
        Box::pin(async move {
            tokio::time::timeout(self.timeout, self.inner.send(request))
                .await
                .map_err(|_| REQUEST_TIMED_OUT.to_string())?
        })
    }
}

/// Ordered header assignments: names are case-insensitive, later values win, `None` removes.
#[derive(Clone, Debug, Default)]
pub(crate) struct HeaderBuilder(Vec<(String, Option<String>)>);

impl HeaderBuilder {
    pub fn set(&mut self, name: &str, value: impl Into<String>) -> &mut Self {
        self.0.push((name.to_string(), Some(value.into())));
        self
    }

    /// `headers.delete(name)`.
    pub fn remove(&mut self, name: &str) -> &mut Self {
        self.0.push((name.to_string(), None));
        self
    }

    pub fn extend<'a, I>(&mut self, headers: I) -> &mut Self
    where
        I: IntoIterator<Item = (&'a String, &'a Option<String>)>,
    {
        self.0.extend(headers.into_iter().map(|(k, v)| (k.clone(), v.clone())));
        self
    }

    pub fn extend_set<'a, I>(&mut self, headers: I) -> &mut Self
    where
        I: IntoIterator<Item = (&'a String, &'a String)>,
    {
        self.0
            .extend(headers.into_iter().map(|(k, v)| (k.clone(), Some(v.clone()))));
        self
    }

    /// The OpenAI SDK client's `OpenAI-Organization` and `OpenAI-Project` headers (its constructor defaults
    /// `organization = readEnv('OPENAI_ORG_ID')`, `project = readEnv('OPENAI_PROJECT_ID')`: the process environment,
    /// trimmed, blank as unset), under the model's and the caller's headers.
    pub fn openai_sdk_identity(&mut self) -> &mut Self {
        for (header, var) in [
            ("OpenAI-Organization", "OPENAI_ORG_ID"),
            ("OpenAI-Project", "OPENAI_PROJECT_ID"),
        ] {
            if let Some(value) = std::env::var(var)
                .ok()
                .map(|v| v.trim().to_string())
                .filter(|v| !v.is_empty())
            {
                self.set(header, value);
            }
        }
        self
    }

    pub fn build(&self) -> HeaderMap {
        let mut map = HeaderMap::new();
        for (name, value) in &self.0 {
            let name = name.to_ascii_lowercase();
            match value {
                Some(value) => map.insert(name, value.clone()),
                None => map.remove(&name),
            };
        }
        map
    }
}

/// `hasHeader`: a non-blank value under `name`, case-insensitively.
pub(crate) fn has_header(headers: Option<&indexmap::IndexMap<String, Option<String>>>, name: &str) -> bool {
    headers.is_some_and(|headers| {
        headers
            .iter()
            .any(|(k, v)| k.eq_ignore_ascii_case(name) && v.as_ref().is_some_and(|v| !v.trim().is_empty()))
    })
}

/// SDK URL join: one duplicate slash between base and path is dropped.
pub(crate) fn join_url(base: &str, path: &str) -> String {
    match (base.ends_with('/'), path.strip_prefix('/')) {
        (true, Some(rest)) => format!("{base}{rest}"),
        _ => format!("{base}{path}"),
    }
}

/// `DEFAULT_HTTP_IDLE_TIMEOUT_MS` of `core/http-dispatcher.ts`.
pub const DEFAULT_HTTP_IDLE_TIMEOUT: Duration = Duration::from_millis(config::keys::DEFAULT_HTTP_IDLE_TIMEOUT_MS);

/// The idle timeout a `httpIdleTimeoutMs` setting selects (`None`: disabled; an invalid or missing setting is the
/// default).
pub fn http_idle_timeout(setting: Option<&Value>) -> Option<Duration> {
    match setting.and_then(config::keys::parse_timeout_ms) {
        Some(0.0) => None,
        Some(ms) => Some(Duration::from_millis(ms as u64)),
        None => Some(DEFAULT_HTTP_IDLE_TIMEOUT),
    }
}

#[derive(Clone, Debug, Default)]
pub struct ReqwestTransport {
    /// Built from `config` by the first request: building one loads and parses the system's root certificates, and
    /// a transport built for a handler that only answers inspections never sends. Clones share it.
    client: Arc<OnceLock<reqwest::Client>>,
    timeout: Option<Duration>,
    /// The longest wait for the response headers, or between two body chunks (undici's `headersTimeout` and
    /// `bodyTimeout`, which TypeScript sets to `httpIdleTimeoutMs`).
    idle: Option<Duration>,
    /// How `client` was built, so a client presenting a certificate can be built alike (`None`: a caller's client).
    config: Option<crate::net::ClientConfig>,
}

impl ReqwestTransport {
    pub fn new(timeout: Option<Duration>) -> Self {
        Self::lazy(crate::net::ClientConfig::default(), timeout)
    }

    /// A transport whose clients are built from `config` (an injected environment's proxies).
    pub fn configured(config: crate::net::ClientConfig, timeout: Option<Duration>) -> Result<Self, String> {
        let client = config.client()?;
        Ok(ReqwestTransport {
            config: Some(config),
            ..Self::with_client(client, timeout)
        })
    }

    /// [`ReqwestTransport::configured`] with the proxies of the environment `var` holds (`HTTP_PROXY`,
    /// `HTTPS_PROXY`, `NO_PROXY`, as the TypeScript HTTP stack reads them).
    pub fn for_env(var: &dyn Fn(&str) -> Option<String>, timeout: Option<Duration>) -> Self {
        Self::lazy(crate::net::ClientConfig::from_lookup(var), timeout)
    }

    /// A transport whose client is built from `config` when it first sends (a client `config` cannot build is the
    /// default configuration's, as [`ReqwestTransport::for_env`] always fell back).
    fn lazy(config: crate::net::ClientConfig, timeout: Option<Duration>) -> Self {
        ReqwestTransport {
            client: Arc::default(),
            timeout,
            idle: None,
            config: Some(config),
        }
    }

    pub fn with_client(client: reqwest::Client, timeout: Option<Duration>) -> Self {
        ReqwestTransport {
            client: Arc::new(OnceLock::from(client)),
            timeout,
            idle: None,
            config: None,
        }
    }

    fn client(&self) -> &reqwest::Client {
        self.client.get_or_init(|| {
            self.config
                .as_ref()
                .and_then(|config| config.client().ok())
                .or_else(|| crate::net::ClientConfig::default().client().ok())
                .unwrap_or_default()
        })
    }

    /// Fail a request whose headers, or whose next body chunk, take longer than `idle` (`None`: wait forever).
    /// A stalled body fails as `terminated`, as Node's fetch reports undici's body timeout, which the retry
    /// classifier retries.
    pub fn with_idle_timeout(mut self, idle: Option<Duration>) -> Self {
        self.idle = idle;
        self
    }
}

struct ReqwestBody(reqwest::Response, Option<Duration>);

impl Body for ReqwestBody {
    fn next_chunk(&mut self) -> BoxFuture<'_, Result<Option<Vec<u8>>, String>> {
        Box::pin(async move {
            let chunk = self.0.chunk();
            let chunk = match self.1 {
                Some(idle) => tokio::time::timeout(idle, chunk)
                    .await
                    .map_err(|_| "terminated".to_string())?,
                None => chunk.await,
            };
            chunk.map(|c| c.map(|b| b.to_vec())).map_err(|e| e.to_string())
        })
    }
}

impl Transport for ReqwestTransport {
    fn with_client_identity(&self, cert: &[u8], key: &[u8]) -> Result<Arc<dyn Transport>, String> {
        let config = self
            .config
            .as_ref()
            .ok_or("this HTTP transport cannot present a TLS client certificate")?;
        let mut pem = cert.to_vec();
        if !pem.ends_with(b"\n") {
            pem.push(b'\n');
        }
        pem.extend_from_slice(key);
        let identity = reqwest::Identity::from_pem(&pem).map_err(|e| e.to_string())?;
        let client = config
            .builder()?
            .identity(identity)
            .build()
            .map_err(|e| e.to_string())?;
        Ok(Arc::new(ReqwestTransport {
            client: Arc::new(OnceLock::from(client)),
            timeout: self.timeout,
            idle: self.idle,
            config: self.config.clone(),
        }))
    }

    /// A new client (its own connection pool, so it works on another runtime) built as this one was; a caller's own
    /// client is rebuilt without a proxy, as [`Transport::websocket`] does.
    fn detached(&self) -> Option<Arc<dyn Transport>> {
        let builder = match &self.config {
            Some(config) => config.builder().ok()?,
            None => reqwest::Client::builder().no_proxy(),
        };
        Some(Arc::new(ReqwestTransport {
            client: Arc::new(OnceLock::from(builder.build().ok()?)),
            timeout: self.timeout,
            idle: self.idle,
            config: self.config.clone(),
        }))
    }

    fn http1_only(&self) -> Option<Arc<dyn Transport>> {
        let client = self.config.as_ref()?.builder().ok()?.http1_only().build().ok()?;
        Some(Arc::new(ReqwestTransport {
            client: Arc::new(OnceLock::from(client)),
            timeout: self.timeout,
            idle: self.idle,
            config: self.config.clone(),
        }))
    }

    fn websocket_available(&self) -> bool {
        true
    }

    /// An HTTP/1.1 upgrade through this transport's proxies (a caller's own client: no proxy).
    fn websocket(
        &self,
        url: String,
        headers: HeaderMap,
    ) -> BoxFuture<'_, Result<Box<dyn crate::websocket::WebSocketConnection>, String>> {
        Box::pin(async move {
            let builder = match &self.config {
                Some(config) => config.builder()?,
                None => reqwest::Client::builder().no_proxy(),
            };
            let client = builder.http1_only().build().map_err(|e| e.to_string())?;
            crate::websocket::connect(&client, &url, &headers).await
        })
    }

    fn send(&self, request: HttpRequest) -> BoxFuture<'_, Result<HttpResponse, String>> {
        Box::pin(async move {
            let method = reqwest::Method::from_bytes(request.method.as_bytes()).map_err(|e| e.to_string())?;
            let mut builder = self.client().request(method, &request.url).body(wire_body(&request));
            for (name, value) in &request.headers {
                builder = builder.header(name, value);
            }
            if let Some(timeout) = self.timeout {
                builder = builder.timeout(timeout);
            }
            let response = match self.idle {
                Some(idle) => tokio::time::timeout(idle, builder.send())
                    .await
                    .map_err(|_| "Headers Timeout Error".to_string())?,
                None => builder.send().await,
            }
            .map_err(|e| e.to_string())?;
            let status = response.status().as_u16();
            let mut headers = HeaderMap::new();
            for (name, value) in response.headers() {
                if let Ok(value) = value.to_str() {
                    headers.insert(name.as_str().to_string(), value.to_string());
                }
            }
            Ok(HttpResponse {
                status,
                headers,
                body: Box::new(ReqwestBody(response, self.idle)),
            })
        })
    }
}

/// The SSE body reader both stream loops use: each call yields the next chunk, `None` at the end, or the abort.
pub(crate) enum Read {
    Chunk(Vec<u8>),
    End,
    Aborted,
    Failed(String),
}

pub(crate) async fn read_chunk(body: &mut dyn Body, signal: Option<&AbortSignal>) -> Read {
    tokio::select! {
        chunk = body.next_chunk() => match chunk {
            Ok(Some(bytes)) => Read::Chunk(bytes),
            Ok(None) => Read::End,
            Err(error) => Read::Failed(error),
        },
        () = cancelled(signal) => Read::Aborted,
    }
}