artifactize-provider 0.27.0

Managed credentials, model discovery and direct HTTP turns for Artifactize.
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
//! Exact-model rig backends with explicit API-key or Codex credentials, the custom providers
//! of this machine, and the loopback-only test endpoint override for offline fake providers.

mod api;
pub mod codex;
mod degenerate;
pub mod delivery;
pub mod driver;
pub mod error;
mod error_body;
pub mod models;
#[cfg(test)]
pub(crate) mod tests;
mod usage;

use std::{
    net::IpAddr,
    sync::{Arc, Mutex},
    time::Duration,
};

use error_body::Body;
use futures_util::StreamExt;
use rig_core::{
    Model,
    completion::{CompletionRequest, CompletionResponse, FinishReason},
    error::ProviderError,
    observe::{Action, AdapterContext, AdapterEvent, Observation, Subject, Witness},
    providers::{anthropic, gemini, openai},
    streaming::{CompletionStream, Item, StreamEvent},
};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use tokio::time::Instant;
use tokio_util::sync::CancellationToken;

pub use api::{Api, EndpointApi};
pub use error::{Code, Failure};
pub use usage::Usage;

/// A runtime builder for synchronous callers driving the asynchronous provider API.
pub use tokio::runtime::Builder as RuntimeBuilder;

use crate::{
    auth::{
        Location,
        providers::{self, ApiKey, Custom},
    },
    names::{DirectBackend, HttpProvider, ModelId},
    secret::{Inventory, history::History},
};

/// Attempts per turn: the first and up to two retries.
const ATTEMPTS: usize = 3;
/// Start transient retries at 250 ms and double per attempt when the provider
/// sends no Retry-After; cancellation and the review deadline still bound every wait.
const RETRY_BACKOFF_BASE: Duration = Duration::from_millis(250);
/// Bound sanitized provider diagnostics retained in errors and audit records.
const MAX_DIAGNOSTIC_CHARS: usize = 4096;
/// Messages requires a per-turn output limit. Allow room for reasoning and answer text
/// while bounding one response; this is independent of the conversation's token budget.
const ANTHROPIC_OUTPUT_TOKENS: u64 = 16_384;

/// A backend's client for one conversation. The API-key backends keep the key they send (empty for
/// an endpoint without one): a provider error may echo it, and every error leaves through the
/// shared rule for server text.
pub struct Client {
    transport: Transport,
    managed: History,
    sources: Sources,
}

#[derive(Default)]
struct Sources {
    providers: Option<Location>,
    codex: Option<Location>,
}

impl Sources {
    fn inventory(&self) -> Inventory {
        Inventory::read(self.providers.as_ref(), self.codex.as_ref())
    }
}

enum Transport {
    Openai(Box<Model<openai::responses_api::wire::Responses>>),
    Chat(Box<Model<openai::wire::Chat>>),
    Anthropic(Box<Model<anthropic::wire::Messages>>),
    Gemini(Box<Model<gemini::completion::GenerateContent>>),
    Codex(Box<codex::Codex>),
}

/// A direct HTTP target and the credentials scoped to that target. Only this crate can
/// select the endpoint for a built-in key or Codex login.
pub struct HttpRoute {
    api: Api,
    base: url::Url,
    key: Option<ApiKey>,
    location: Option<Location>,
}

impl HttpRoute {
    pub fn api(&self) -> Api {
        self.api
    }

    /// A built-in provider, or a configured custom endpoint/alias. A missing custom name
    /// is returned to the caller, which may maintain separate catalogs.
    pub fn resolve(
        backend: &DirectBackend,
        location: Result<&Location, &str>,
        purpose: &str,
    ) -> Result<Option<Self>, Failure> {
        Self::resolve_route(backend, location, purpose).map_err(|mut failure| {
            failure.message = Inventory::read(location.ok(), location.ok()).scrub(&failure.message);
            failure
        })
    }

    fn resolve_route(
        backend: &DirectBackend,
        location: Result<&Location, &str>,
        purpose: &str,
    ) -> Result<Option<Self>, Failure> {
        let provider = match backend {
            DirectBackend::Builtin { provider } => *provider,
            DirectBackend::Custom { name } => {
                match providers::custom(name, location.map_err(str::to_owned)?)? {
                    Some(Custom::Alias { provider }) => provider,
                    Some(Custom::Endpoint { api, url, key }) => {
                        return Ok(Some(Self {
                            api: api.into(),
                            base: url.into_url(),
                            key,
                            location: location.ok().cloned(),
                        }));
                    }
                    None => return Ok(None),
                }
            }
        };
        let key = match providers::key_variable(provider) {
            Some(variable) => Some(providers::key(provider, location)?.ok_or_else(|| {
                Failure::new(
                    Code::Authentication,
                    format!("{variable} or a saved {provider} key is required {purpose}."),
                )
            })?),
            None => None,
        };
        Ok(Some(Self {
            api: provider.into(),
            base: base_url(provider)?,
            key,
            location: location.ok().cloned(),
        }))
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Attempt {
    #[serde(default)]
    pub turn: usize,
    #[serde(default)]
    pub attempt: usize,
    #[serde(default)]
    pub usage: usage::Usage,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_code: Option<Code>,
}

/// A classified provider failure, with the wait the provider asked for, if any.
struct Classified {
    code: Code,
    message: String,
    retry_after: Option<Duration>,
    output_failed: bool,
}

impl From<Classified> for Failure {
    fn from(classified: Classified) -> Self {
        Self {
            output_failed: classified.output_failed,
            ..Self::new(classified.code, classified.message)
        }
    }
}

impl From<Failure> for Classified {
    fn from(failure: Failure) -> Self {
        Self {
            code: failure.code,
            message: failure.message,
            retry_after: None,
            output_failed: failure.output_failed,
        }
    }
}

// Only counters cross this boundary; prompts, reasoning and raw responses stay transient.
#[derive(Default)]
struct ReportedUsage(Mutex<std::collections::BTreeMap<String, u64>>);

impl Witness for ReportedUsage {
    fn observe(&self, observation: Observation) {
        if let Action::Adapter { observation } = observation.action
            && let AdapterEvent::Usage { usage } = observation.event
        {
            let mut counters = self.0.lock().unwrap();
            for (name, value) in [
                ("inputTokens", usage.input_tokens),
                ("outputTokens", usage.output_tokens),
                ("totalTokens", usage.total_tokens),
                ("cacheReadTokens", usage.cached_input_tokens),
                ("reasoningTokens", usage.reasoning_tokens),
            ] {
                insert_counter(&mut counters, name, value);
            }
        }
    }
}

// Bound counters to the IEEE-754 exact integer range of JSON clients.
const MAX_SAFE_JSON_INTEGER: u64 = (1 << 53) - 1;

fn insert_counter(
    counters: &mut std::collections::BTreeMap<String, u64>,
    name: &str,
    value: Option<u64>,
) {
    if let Some(value) = value.filter(|value| *value <= MAX_SAFE_JSON_INTEGER) {
        counters.insert(name.into(), value);
    }
}

impl Client {
    /// Connect to the selected model without letting a caller redirect a managed credential.
    pub fn at(
        HttpRoute {
            api,
            base,
            key,
            location,
        }: HttpRoute,
        model: &ModelId,
        codex_location: Result<Location, String>,
    ) -> Result<Self, Failure> {
        let sources = Sources {
            providers: location,
            codex: codex_location.as_ref().ok().cloned(),
        };
        let managed =
            History::watch(sources.providers.as_ref(), sources.codex.as_ref()).map_err(|_| {
                Failure::new(
                    Code::ProviderError,
                    "Cannot protect credentials during the provider turn.",
                )
            })?;
        let mut observed = sources.inventory();
        if api == Api::Codex {
            managed.update(observed);
            return Ok(Self {
                transport: Transport::Codex(Box::new(codex::Codex::new(
                    model,
                    base,
                    codex_location,
                )?)),
                managed,
                sources,
            });
        }
        let base = adapter_base(&base);
        // An endpoint without a key sends an empty one, which keyless servers ignore.
        let key = key.map(|key| key.expose().to_owned()).unwrap_or_default();
        observed.include(key.clone());
        managed.update(observed);
        let http = delivery::Tap::new(http_client()?);
        let openai = || {
            openai::OpenAIConfig::new(key.clone())
                .with_base_url(base)
                .connect(http.clone())
        };
        let transport = match api {
            Api::OpenaiResponses => Transport::Openai(Box::new(openai().responses(model.as_str()))),
            Api::OpenaiChat => Transport::Chat(Box::new(openai().chat(model.as_str()))),
            Api::Anthropic => Transport::Anthropic(Box::new(
                anthropic::AnthropicConfig::new(key)
                    .with_base_url(base)
                    .connect(http)
                    .completion(model.as_str()),
            )),
            Api::Gemini => Transport::Gemini(Box::new(
                gemini::GeminiConfig::new(key)
                    .with_base_url(base)
                    .connect(http)
                    .completion(model.as_str()),
            )),
            Api::Codex => unreachable!("handled above"),
        };
        Ok(Self {
            transport,
            managed,
            sources,
        })
    }

    /// An OpenAI Responses model already configured by its caller (also used by fixtures).
    #[doc(hidden)]
    pub fn from_openai(
        model: Box<Model<openai::responses_api::wire::Responses>>,
        key: String,
    ) -> Self {
        let managed = History::default();
        managed.update(Inventory::new([key]));
        Self {
            transport: Transport::Openai(model),
            managed,
            sources: Sources::default(),
        }
    }

    /// An Anthropic model already configured by its caller (also used by fixtures).
    #[doc(hidden)]
    pub fn from_anthropic(model: Box<Model<anthropic::wire::Messages>>, key: String) -> Self {
        let managed = History::default();
        managed.update(Inventory::new([key]));
        Self {
            transport: Transport::Anthropic(model),
            managed,
            sources: Sources::default(),
        }
    }

    /// The API this client's requests use.
    pub fn api(&self) -> Api {
        match &self.transport {
            Transport::Openai(_) => Api::OpenaiResponses,
            Transport::Chat(_) => Api::OpenaiChat,
            Transport::Anthropic(_) => Api::Anthropic,
            Transport::Gemini(_) => Api::Gemini,
            Transport::Codex(_) => Api::Codex,
        }
    }

    /// The provider parameters of every request of one conversation. The Responses backends key
    /// their prompt cache on the review's `session` id; Anthropic, Gemini and Chat
    /// Completions cache by prefix alone.
    pub fn parameters(api: Api, reasoning: Option<&str>, cache_key: &str) -> Result<Value, String> {
        if let Some(reasoning) = reasoning {
            api.validate_reasoning(reasoning)?;
        }
        Ok(Self::parameters_unchecked(api, reasoning, cache_key))
    }

    /// The caller already validated against the provider's per-model catalog.
    pub fn parameters_unchecked(api: Api, reasoning: Option<&str>, cache_key: &str) -> Value {
        match api {
            Api::OpenaiChat => reasoning.map_or(
                json!({}),
                |effort| json!({"reasoning_effort":effort, "parallel_tool_calls":false}),
            ),
            Api::Gemini => reasoning.map_or(
                json!({}),
                |effort| json!({"generationConfig":{"thinkingConfig":{"thinkingLevel":effort}}}),
            ),
            Api::OpenaiResponses => {
                let mut value = json!({
                    "store":false,
                    "parallel_tool_calls":false,
                    "include":["reasoning.encrypted_content"],
                    "prompt_cache_key":cache_key,
                });
                if let Some(reasoning) = reasoning {
                    value["reasoning"] = json!({"effort":reasoning});
                }
                value
            }
            Api::Anthropic => reasoning.map_or(
                json!({}),
                |effort| json!({"thinking":{"type":"adaptive"}, "output_config":{"effort":effort}}),
            ),
            // rig's Codex contract states store:false and encrypted reasoning itself. The
            // `session-id` header repeats the cache key (see `codex::envelope`).
            Api::Codex => {
                let mut value = json!({"prompt_cache_key":cache_key});
                if let Some(effort) = reasoning {
                    value["reasoning"] = json!({"effort":effort, "summary":"auto"});
                }
                value
            }
        }
    }

    /// Structured output constrains the final answer only; tool calls keep their contract.
    /// Merge Anthropic's format with the reasoning effort already in output_config, and
    /// Gemini's with the thinking level already in generationConfig. A malformed
    /// parameters value, or a malformed configuration section, contributes no settings.
    pub fn output_format(api: Api, parameters: &mut Value, name: &str, schema: Value) {
        fn object(value: &mut Value) -> &mut Map<String, Value> {
            if !value.is_object() {
                *value = Value::Object(Map::new());
            }
            value.as_object_mut().expect("initialized parameter object")
        }
        fn section<'a>(parameters: &'a mut Value, name: &str) -> &'a mut Map<String, Value> {
            object(object(parameters).entry(name).or_insert(Value::Null))
        }
        let _ = object(parameters);
        match api {
            Api::OpenaiResponses | Api::Codex => {
                parameters["text"] = json!({"format":{
                    "type":"json_schema", "name":name, "strict":true,
                    "schema":schema,
                }});
            }
            Api::OpenaiChat => {
                parameters["response_format"] = json!({"type":"json_schema", "json_schema":{
                    "name":name, "strict":true, "schema":schema,
                }});
            }
            Api::Anthropic => {
                section(parameters, "output_config").insert(
                    "format".into(),
                    json!({"type":"json_schema", "schema":schema}),
                );
            }
            Api::Gemini => {
                let config = section(parameters, "generationConfig");
                config.insert("responseMimeType".into(), json!("application/json"));
                config.insert("responseJsonSchema".into(), schema);
            }
        }
    }

    async fn stream(
        &self,
        mut request: CompletionRequest,
        observed: AdapterContext,
    ) -> Result<CompletionStream, Classified> {
        // The transport sees unsanitized output. Only the delivery and response
        // boundaries below it can publish content, even if the caller opted in.
        request.record_telemetry_content = false;
        match &self.transport {
            Transport::Openai(model) => model.stream_observed(request, observed),
            Transport::Chat(model) => model.stream_observed(request, observed),
            Transport::Gemini(model) => model.stream_observed(request, observed),
            Transport::Anthropic(model) => {
                request.max_tokens = Some(ANTHROPIC_OUTPUT_TOKENS);
                model.stream_observed(request, observed)
            }
            // Each turn reads the credentials afresh, refreshing them when due.
            Transport::Codex(client) => {
                let model = client.model().await.map_err(|error| Classified {
                    code: if error.transient {
                        Code::Transient
                    } else {
                        Code::Authentication
                    },
                    message: error.message,
                    retry_after: None,
                    output_failed: false,
                })?;
                delivery::register(self.inventory());
                model.stream_observed(request, observed)
            }
        }
        .map_err(|error| self.classify(&error, time::OffsetDateTime::now_utc(), &self.inventory()))
    }

    fn inventory(&self) -> Inventory {
        let mut inventory = self.sources.inventory();
        if let Transport::Codex(client) = &self.transport {
            inventory.merge(client.known());
        }
        self.managed.update(inventory)
    }

    fn scrub_failure(&self, mut failure: Failure) -> Failure {
        failure.message = self.inventory().scrub(&failure.message);
        failure
    }

    /// The error code of a provider failure, from its status, codes and message. Its message
    /// is the shared rule's: text holding part of a credential this client sent is withheld
    /// before it reaches output, delivery events, attempts or saved sessions.
    fn classify(
        &self,
        error: &ProviderError,
        now: time::OffsetDateTime,
        inventory: &Inventory,
    ) -> Classified {
        let response = error.provider_response();
        let body = response.and_then(|response| Body::parse(response.body.as_bytes()));
        let body = body.as_ref();
        // Relays may already have a machine code and status independently of the reply.
        let (status, code) = match error {
            ProviderError::Relayed(report) => (report.http_status, report.code.as_deref()),
            _ => (
                response.and_then(|response| response.status.map(|status| status.as_u16())),
                response
                    .and_then(|response| response.code.as_deref())
                    .or_else(|| body.and_then(Body::provider_code)),
            ),
        };
        let http = status.and_then(|status| reqwest::StatusCode::from_u16(status).ok());
        let fallback = || diagnostic_from(body, error);
        let text = match &self.transport {
            Transport::Codex(_) => {
                let unix = u64::try_from(now.unix_timestamp())
                    .ok()
                    .map(crate::auth::codex::Timestamp::from_seconds);
                codex::diagnostic_text(http, body, fallback, unix, inventory)
            }
            _ => fallback(),
        };
        let message = inventory.diagnostic(&text, MAX_DIAGNOSTIC_CHARS);
        // Classified by the whole text (codes and words), never shown.
        let text = format!("{} {text}", code.unwrap_or_default()).to_lowercase();
        let any = |terms: &[&str]| terms.iter().any(|term| text.contains(term));
        let code = if matches!(self.transport, Transport::Codex(_))
            && body.is_some_and(|body| body.usage_limit(http))
            || any(&["quota", "billing", "credit balance", "usage limit"])
        {
            Code::Quota
        } else if matches!(status, Some(401 | 403))
            || any(&[
                "authentication",
                "unauthorized",
                "permission",
                "invalid_api_key",
                "api key",
            ])
        {
            Code::Authentication
        } else if status == Some(429) || any(&["rate_limit", "rate limit"]) {
            Code::RateLimit
        } else if error.is_retryable()
            || matches!(self.transport, Transport::Openai(_) | Transport::Codex(_))
                && body.and_then(|body| body.codex_fields().code()) == Some("server_is_overloaded")
            // A server-side failure can clear without changing the request.
            || http.is_some_and(|status| status.is_server_error())
            || (status.is_none()
                && matches!(
                    code,
                    // Codex reports overloads inside a successful HTTP stream, without
                    // an HTTP error status; it is the same retryable provider failure.
                    Some(
                        "overloaded_error" | "server_is_overloaded" | "server_error" | "api_error"
                    )
                ))
        {
            Code::Transient
        } else {
            Code::ProviderError
        };
        Classified {
            code,
            message,
            retry_after: retry_after(error, now),
            output_failed: false,
        }
    }
}

mod protection;
mod turn;
pub use turn::Turn;

/// `retry-after-ms` is read as a count of seconds first, so a thousandth of it is the wait.
const MILLIS_PER_SECOND: u32 = 1000;

/// The wait a provider asked for: `retry-after-ms`, or `Retry-After` in seconds or as an
/// HTTP date.
fn retry_after(error: &ProviderError, now: time::OffsetDateTime) -> Option<Duration> {
    wait_header(error.provider_response_headers()?, now)
}

fn wait_header(
    headers: &rig_core::http_client::HeaderMap,
    now: time::OffsetDateTime,
) -> Option<Duration> {
    let header = |name: &str| headers.get(name)?.to_str().ok().map(str::trim);
    let seconds = |value: &str| {
        value
            .parse::<f64>()
            .ok()
            .filter(|value| value.is_finite() && *value >= 0.0)
            .and_then(|value| Duration::try_from_secs_f64(value).ok())
    };
    if let Some(wait) = header("retry-after-ms").and_then(seconds) {
        return Some(wait / MILLIS_PER_SECOND);
    }
    let value = header("retry-after")?;
    seconds(value).or_else(|| {
        let at = time::OffsetDateTime::parse(value, &time::format_description::well_known::Rfc2822)
            .ok()?;
        Some(Duration::try_from(at - now).unwrap_or_default())
    })
}

/// A provider error as text, cleaned for a terminal but not clipped: callers decide what of
/// it may be shown ([`crate::secret::server_text`]) before cutting it.
fn diagnostic_text(error: &ProviderError) -> String {
    let body = error
        .provider_response_body()
        .and_then(|body| Body::parse(body.as_bytes()));
    diagnostic_from(body.as_ref(), error)
}

fn diagnostic_from(body: Option<&Body>, error: &ProviderError) -> String {
    match body.and_then(Body::provider_message) {
        Some(message) => clean_text(message),
        None => clean_text(&error.to_string()),
    }
}

/// The environment variable that points a built-in provider at a loopback test endpoint;
/// `None` for Claude Code, which reaches its service itself.
pub fn base_url_variable(provider: HttpProvider) -> &'static str {
    match provider {
        HttpProvider::Openai => "ARTIFACTIZE_OPENAI_BASE_URL",
        HttpProvider::Anthropic => "ARTIFACTIZE_ANTHROPIC_BASE_URL",
        HttpProvider::Gemini => "ARTIFACTIZE_GEMINI_BASE_URL",
        HttpProvider::Codex => "ARTIFACTIZE_CODEX_BASE_URL",
    }
}

/// Every test endpoint variable: the backends' API roots and the Codex sign-in root.
const TEST_ENDPOINTS: [&str; 5] = [
    "ARTIFACTIZE_OPENAI_BASE_URL",
    "ARTIFACTIZE_ANTHROPIC_BASE_URL",
    "ARTIFACTIZE_GEMINI_BASE_URL",
    "ARTIFACTIZE_CODEX_BASE_URL",
    crate::auth::codex::AUTH_URL_VARIABLE,
];

/// A test endpoint: an http(s) URL on localhost, 127.0.0.0/8 or [::1], without
/// credentials, a query or a fragment. A test endpoint never leaves the machine.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TestEndpoint(url::Url);

impl TestEndpoint {
    pub(crate) fn into_url(self) -> url::Url {
        self.0
    }
    /// The endpoint as an API root, the text an SDK or a request path starts from: its URL
    /// without a trailing slash.
    pub fn root(&self) -> &str {
        self.0.as_str().trim_end_matches('/')
    }
}

impl std::str::FromStr for TestEndpoint {
    type Err = String;
    fn from_str(value: &str) -> Result<Self, Self::Err> {
        loopback_url(value)
    }
}

impl std::fmt::Display for TestEndpoint {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.root())
    }
}

impl Serialize for TestEndpoint {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.root())
    }
}

/// The loopback test endpoint that replaces the provider's API root, if one is set.
pub fn test_endpoint(provider: HttpProvider) -> Result<Option<TestEndpoint>, String> {
    variable_endpoint(base_url_variable(provider))
}

pub fn variable_endpoint(variable: &str) -> Result<Option<TestEndpoint>, String> {
    variable_endpoint_in(variable, crate::platform::var)
}

/// [`variable_endpoint`] read from `var` instead of this process's environment.
pub fn variable_endpoint_in(
    variable: &str,
    var: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> Result<Option<TestEndpoint>, String> {
    let Some(value) = var(variable).filter(|value| !value.is_empty()) else {
        return Ok(None);
    };
    crate::platform::as_text(&value)
        .map_err(str::to_owned)
        .and_then(loopback_url)
        .map(Some)
        .map_err(|error| format!("{variable}: {error}."))
}

/// The first test endpoint variable that is set, valid or not.
pub fn active_test_endpoint() -> Option<&'static str> {
    TEST_ENDPOINTS
        .into_iter()
        .find(|variable| crate::platform::var(variable).is_some_and(|value| !value.is_empty()))
}

/// `value` as a [`TestEndpoint`], or why it is not one.
fn loopback_url(value: &str) -> Result<TestEndpoint, String> {
    let url = url::Url::parse(value).map_err(|_| "it is not a URL".to_owned())?;
    let loopback = match url.host() {
        Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
        Some(url::Host::Ipv4(ip)) => IpAddr::V4(ip).is_loopback(),
        Some(url::Host::Ipv6(ip)) => IpAddr::V6(ip).is_loopback(),
        None => false,
    };
    if !matches!(url.scheme(), "http" | "https") || !loopback {
        return Err("a test endpoint must be http(s) on localhost, 127.0.0.0/8 or [::1]".into());
    }
    if !url.username().is_empty()
        || url.password().is_some()
        || url.query().is_some()
        || url.fragment().is_some()
    {
        return Err("a test endpoint has no credentials, query or fragment".into());
    }
    Ok(TestEndpoint(url))
}

/// The provider's API root: its loopback test endpoint, else the provider's. Claude Code
/// has none: it reaches its service itself.
fn base_url(provider: HttpProvider) -> Result<url::Url, String> {
    if let Some(endpoint) = test_endpoint(provider)? {
        return Ok(endpoint.0);
    }
    let base = match provider {
        HttpProvider::Openai => "https://api.openai.com/v1",
        HttpProvider::Anthropic => "https://api.anthropic.com",
        HttpProvider::Gemini => gemini::BASE_URL,
        HttpProvider::Codex => codex::BASE_URL,
    };
    Ok(url::Url::parse(base).expect("built-in provider base URL"))
}

/// Rig model listing appends a path starting with `/` to this textual root.
fn adapter_base(base: &url::Url) -> &str {
    base.as_str().trim_end_matches('/')
}

fn http_client() -> Result<reqwest::Client, String> {
    reqwest::Client::builder()
        .retry(reqwest::retry::never())
        .redirect(reqwest::redirect::Policy::none())
        .build()
        .map_err(|error| error.to_string())
}

/// `message` cleaned for a terminal (escape sequences and control characters), unclipped.
fn clean_text(message: &str) -> String {
    String::from_utf8(crate::platform::clean_text(message.as_bytes()))
        .expect("clean output is UTF-8")
}