Skip to main content

artifactize_provider/
llm.rs

1//! Exact-model rig backends with explicit API-key or Codex credentials, the custom providers
2//! of this machine, and the loopback-only test endpoint override for offline fake providers.
3
4mod api;
5pub mod codex;
6mod degenerate;
7pub mod delivery;
8pub mod driver;
9pub mod error;
10mod error_body;
11pub mod models;
12#[cfg(test)]
13pub(crate) mod tests;
14mod usage;
15
16use std::{
17    net::IpAddr,
18    sync::{Arc, Mutex},
19    time::Duration,
20};
21
22use error_body::Body;
23use futures_util::StreamExt;
24use rig_core::{
25    Model,
26    completion::{CompletionRequest, CompletionResponse, FinishReason},
27    error::ProviderError,
28    observe::{Action, AdapterContext, AdapterEvent, Observation, Subject, Witness},
29    providers::{anthropic, gemini, openai},
30    streaming::{CompletionStream, Item, StreamEvent},
31};
32use serde::{Deserialize, Serialize};
33use serde_json::{Map, Value, json};
34use tokio::time::Instant;
35use tokio_util::sync::CancellationToken;
36
37pub use api::{Api, EndpointApi};
38pub use error::{Code, Failure};
39pub use usage::Usage;
40
41/// A runtime builder for synchronous callers driving the asynchronous provider API.
42pub use tokio::runtime::Builder as RuntimeBuilder;
43
44use crate::{
45    auth::{
46        Location,
47        providers::{self, ApiKey, Custom},
48    },
49    names::{DirectBackend, HttpProvider, ModelId},
50    secret::{Inventory, history::History},
51};
52
53/// Attempts per turn: the first and up to two retries.
54const ATTEMPTS: usize = 3;
55/// Start transient retries at 250 ms and double per attempt when the provider
56/// sends no Retry-After; cancellation and the review deadline still bound every wait.
57const RETRY_BACKOFF_BASE: Duration = Duration::from_millis(250);
58/// Bound sanitized provider diagnostics retained in errors and audit records.
59const MAX_DIAGNOSTIC_CHARS: usize = 4096;
60/// Messages requires a per-turn output limit. Allow room for reasoning and answer text
61/// while bounding one response; this is independent of the conversation's token budget.
62const ANTHROPIC_OUTPUT_TOKENS: u64 = 16_384;
63
64/// A backend's client for one conversation. The API-key backends keep the key they send (empty for
65/// an endpoint without one): a provider error may echo it, and every error leaves through the
66/// shared rule for server text.
67pub struct Client {
68    transport: Transport,
69    managed: History,
70    sources: Sources,
71}
72
73#[derive(Default)]
74struct Sources {
75    providers: Option<Location>,
76    codex: Option<Location>,
77}
78
79impl Sources {
80    fn inventory(&self) -> Inventory {
81        Inventory::read(self.providers.as_ref(), self.codex.as_ref())
82    }
83}
84
85enum Transport {
86    Openai(Box<Model<openai::responses_api::wire::Responses>>),
87    Chat(Box<Model<openai::wire::Chat>>),
88    Anthropic(Box<Model<anthropic::wire::Messages>>),
89    Gemini(Box<Model<gemini::completion::GenerateContent>>),
90    Codex(Box<codex::Codex>),
91}
92
93/// A direct HTTP target and the credentials scoped to that target. Only this crate can
94/// select the endpoint for a built-in key or Codex login.
95pub struct HttpRoute {
96    api: Api,
97    base: url::Url,
98    key: Option<ApiKey>,
99    location: Option<Location>,
100}
101
102impl HttpRoute {
103    pub fn api(&self) -> Api {
104        self.api
105    }
106
107    /// A built-in provider, or a configured custom endpoint/alias. A missing custom name
108    /// is returned to the caller, which may maintain separate catalogs.
109    pub fn resolve(
110        backend: &DirectBackend,
111        location: Result<&Location, &str>,
112        purpose: &str,
113    ) -> Result<Option<Self>, Failure> {
114        Self::resolve_route(backend, location, purpose).map_err(|mut failure| {
115            failure.message = Inventory::read(location.ok(), location.ok()).scrub(&failure.message);
116            failure
117        })
118    }
119
120    fn resolve_route(
121        backend: &DirectBackend,
122        location: Result<&Location, &str>,
123        purpose: &str,
124    ) -> Result<Option<Self>, Failure> {
125        let provider = match backend {
126            DirectBackend::Builtin { provider } => *provider,
127            DirectBackend::Custom { name } => {
128                match providers::custom(name, location.map_err(str::to_owned)?)? {
129                    Some(Custom::Alias { provider }) => provider,
130                    Some(Custom::Endpoint { api, url, key }) => {
131                        return Ok(Some(Self {
132                            api: api.into(),
133                            base: url.into_url(),
134                            key,
135                            location: location.ok().cloned(),
136                        }));
137                    }
138                    None => return Ok(None),
139                }
140            }
141        };
142        let key = match providers::key_variable(provider) {
143            Some(variable) => Some(providers::key(provider, location)?.ok_or_else(|| {
144                Failure::new(
145                    Code::Authentication,
146                    format!("{variable} or a saved {provider} key is required {purpose}."),
147                )
148            })?),
149            None => None,
150        };
151        Ok(Some(Self {
152            api: provider.into(),
153            base: base_url(provider)?,
154            key,
155            location: location.ok().cloned(),
156        }))
157    }
158}
159
160#[derive(Debug, Clone, Serialize, Deserialize)]
161#[serde(rename_all = "camelCase")]
162pub struct Attempt {
163    #[serde(default)]
164    pub turn: usize,
165    #[serde(default)]
166    pub attempt: usize,
167    #[serde(default)]
168    pub usage: usage::Usage,
169    #[serde(skip_serializing_if = "Option::is_none")]
170    pub error: Option<String>,
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub error_code: Option<Code>,
173}
174
175/// A classified provider failure, with the wait the provider asked for, if any.
176struct Classified {
177    code: Code,
178    message: String,
179    retry_after: Option<Duration>,
180    output_failed: bool,
181}
182
183impl From<Classified> for Failure {
184    fn from(classified: Classified) -> Self {
185        Self {
186            output_failed: classified.output_failed,
187            ..Self::new(classified.code, classified.message)
188        }
189    }
190}
191
192impl From<Failure> for Classified {
193    fn from(failure: Failure) -> Self {
194        Self {
195            code: failure.code,
196            message: failure.message,
197            retry_after: None,
198            output_failed: failure.output_failed,
199        }
200    }
201}
202
203// Only counters cross this boundary; prompts, reasoning and raw responses stay transient.
204#[derive(Default)]
205struct ReportedUsage(Mutex<std::collections::BTreeMap<String, u64>>);
206
207impl Witness for ReportedUsage {
208    fn observe(&self, observation: Observation) {
209        if let Action::Adapter { observation } = observation.action
210            && let AdapterEvent::Usage { usage } = observation.event
211        {
212            let mut counters = self.0.lock().unwrap();
213            for (name, value) in [
214                ("inputTokens", usage.input_tokens),
215                ("outputTokens", usage.output_tokens),
216                ("totalTokens", usage.total_tokens),
217                ("cacheReadTokens", usage.cached_input_tokens),
218                ("reasoningTokens", usage.reasoning_tokens),
219            ] {
220                insert_counter(&mut counters, name, value);
221            }
222        }
223    }
224}
225
226// Bound counters to the IEEE-754 exact integer range of JSON clients.
227const MAX_SAFE_JSON_INTEGER: u64 = (1 << 53) - 1;
228
229fn insert_counter(
230    counters: &mut std::collections::BTreeMap<String, u64>,
231    name: &str,
232    value: Option<u64>,
233) {
234    if let Some(value) = value.filter(|value| *value <= MAX_SAFE_JSON_INTEGER) {
235        counters.insert(name.into(), value);
236    }
237}
238
239impl Client {
240    /// Connect to the selected model without letting a caller redirect a managed credential.
241    pub fn at(
242        HttpRoute {
243            api,
244            base,
245            key,
246            location,
247        }: HttpRoute,
248        model: &ModelId,
249        codex_location: Result<Location, String>,
250    ) -> Result<Self, Failure> {
251        let sources = Sources {
252            providers: location,
253            codex: codex_location.as_ref().ok().cloned(),
254        };
255        let managed =
256            History::watch(sources.providers.as_ref(), sources.codex.as_ref()).map_err(|_| {
257                Failure::new(
258                    Code::ProviderError,
259                    "Cannot protect credentials during the provider turn.",
260                )
261            })?;
262        let mut observed = sources.inventory();
263        if api == Api::Codex {
264            managed.update(observed);
265            return Ok(Self {
266                transport: Transport::Codex(Box::new(codex::Codex::new(
267                    model,
268                    base,
269                    codex_location,
270                )?)),
271                managed,
272                sources,
273            });
274        }
275        let base = adapter_base(&base);
276        // An endpoint without a key sends an empty one, which keyless servers ignore.
277        let key = key.map(|key| key.expose().to_owned()).unwrap_or_default();
278        observed.include(key.clone());
279        managed.update(observed);
280        let http = delivery::Tap::new(http_client()?);
281        let openai = || {
282            openai::OpenAIConfig::new(key.clone())
283                .with_base_url(base)
284                .connect(http.clone())
285        };
286        let transport = match api {
287            Api::OpenaiResponses => Transport::Openai(Box::new(openai().responses(model.as_str()))),
288            Api::OpenaiChat => Transport::Chat(Box::new(openai().chat(model.as_str()))),
289            Api::Anthropic => Transport::Anthropic(Box::new(
290                anthropic::AnthropicConfig::new(key)
291                    .with_base_url(base)
292                    .connect(http)
293                    .completion(model.as_str()),
294            )),
295            Api::Gemini => Transport::Gemini(Box::new(
296                gemini::GeminiConfig::new(key)
297                    .with_base_url(base)
298                    .connect(http)
299                    .completion(model.as_str()),
300            )),
301            Api::Codex => unreachable!("handled above"),
302        };
303        Ok(Self {
304            transport,
305            managed,
306            sources,
307        })
308    }
309
310    /// An OpenAI Responses model already configured by its caller (also used by fixtures).
311    #[doc(hidden)]
312    pub fn from_openai(
313        model: Box<Model<openai::responses_api::wire::Responses>>,
314        key: String,
315    ) -> Self {
316        let managed = History::default();
317        managed.update(Inventory::new([key]));
318        Self {
319            transport: Transport::Openai(model),
320            managed,
321            sources: Sources::default(),
322        }
323    }
324
325    /// An Anthropic model already configured by its caller (also used by fixtures).
326    #[doc(hidden)]
327    pub fn from_anthropic(model: Box<Model<anthropic::wire::Messages>>, key: String) -> Self {
328        let managed = History::default();
329        managed.update(Inventory::new([key]));
330        Self {
331            transport: Transport::Anthropic(model),
332            managed,
333            sources: Sources::default(),
334        }
335    }
336
337    /// The API this client's requests use.
338    pub fn api(&self) -> Api {
339        match &self.transport {
340            Transport::Openai(_) => Api::OpenaiResponses,
341            Transport::Chat(_) => Api::OpenaiChat,
342            Transport::Anthropic(_) => Api::Anthropic,
343            Transport::Gemini(_) => Api::Gemini,
344            Transport::Codex(_) => Api::Codex,
345        }
346    }
347
348    /// The provider parameters of every request of one conversation. The Responses backends key
349    /// their prompt cache on the review's `session` id; Anthropic, Gemini and Chat
350    /// Completions cache by prefix alone.
351    pub fn parameters(api: Api, reasoning: Option<&str>, cache_key: &str) -> Result<Value, String> {
352        if let Some(reasoning) = reasoning {
353            api.validate_reasoning(reasoning)?;
354        }
355        Ok(Self::parameters_unchecked(api, reasoning, cache_key))
356    }
357
358    /// The caller already validated against the provider's per-model catalog.
359    pub fn parameters_unchecked(api: Api, reasoning: Option<&str>, cache_key: &str) -> Value {
360        match api {
361            Api::OpenaiChat => reasoning.map_or(
362                json!({}),
363                |effort| json!({"reasoning_effort":effort, "parallel_tool_calls":false}),
364            ),
365            Api::Gemini => reasoning.map_or(
366                json!({}),
367                |effort| json!({"generationConfig":{"thinkingConfig":{"thinkingLevel":effort}}}),
368            ),
369            Api::OpenaiResponses => {
370                let mut value = json!({
371                    "store":false,
372                    "parallel_tool_calls":false,
373                    "include":["reasoning.encrypted_content"],
374                    "prompt_cache_key":cache_key,
375                });
376                if let Some(reasoning) = reasoning {
377                    value["reasoning"] = json!({"effort":reasoning});
378                }
379                value
380            }
381            Api::Anthropic => reasoning.map_or(
382                json!({}),
383                |effort| json!({"thinking":{"type":"adaptive"}, "output_config":{"effort":effort}}),
384            ),
385            // rig's Codex contract states store:false and encrypted reasoning itself. The
386            // `session-id` header repeats the cache key (see `codex::envelope`).
387            Api::Codex => {
388                let mut value = json!({"prompt_cache_key":cache_key});
389                if let Some(effort) = reasoning {
390                    value["reasoning"] = json!({"effort":effort, "summary":"auto"});
391                }
392                value
393            }
394        }
395    }
396
397    /// Structured output constrains the final answer only; tool calls keep their contract.
398    /// Merge Anthropic's format with the reasoning effort already in output_config, and
399    /// Gemini's with the thinking level already in generationConfig. A malformed
400    /// parameters value, or a malformed configuration section, contributes no settings.
401    pub fn output_format(api: Api, parameters: &mut Value, name: &str, schema: Value) {
402        fn object(value: &mut Value) -> &mut Map<String, Value> {
403            if !value.is_object() {
404                *value = Value::Object(Map::new());
405            }
406            value.as_object_mut().expect("initialized parameter object")
407        }
408        fn section<'a>(parameters: &'a mut Value, name: &str) -> &'a mut Map<String, Value> {
409            object(object(parameters).entry(name).or_insert(Value::Null))
410        }
411        let _ = object(parameters);
412        match api {
413            Api::OpenaiResponses | Api::Codex => {
414                parameters["text"] = json!({"format":{
415                    "type":"json_schema", "name":name, "strict":true,
416                    "schema":schema,
417                }});
418            }
419            Api::OpenaiChat => {
420                parameters["response_format"] = json!({"type":"json_schema", "json_schema":{
421                    "name":name, "strict":true, "schema":schema,
422                }});
423            }
424            Api::Anthropic => {
425                section(parameters, "output_config").insert(
426                    "format".into(),
427                    json!({"type":"json_schema", "schema":schema}),
428                );
429            }
430            Api::Gemini => {
431                let config = section(parameters, "generationConfig");
432                config.insert("responseMimeType".into(), json!("application/json"));
433                config.insert("responseJsonSchema".into(), schema);
434            }
435        }
436    }
437
438    async fn stream(
439        &self,
440        mut request: CompletionRequest,
441        observed: AdapterContext,
442    ) -> Result<CompletionStream, Classified> {
443        // The transport sees unsanitized output. Only the delivery and response
444        // boundaries below it can publish content, even if the caller opted in.
445        request.record_telemetry_content = false;
446        match &self.transport {
447            Transport::Openai(model) => model.stream_observed(request, observed),
448            Transport::Chat(model) => model.stream_observed(request, observed),
449            Transport::Gemini(model) => model.stream_observed(request, observed),
450            Transport::Anthropic(model) => {
451                request.max_tokens = Some(ANTHROPIC_OUTPUT_TOKENS);
452                model.stream_observed(request, observed)
453            }
454            // Each turn reads the credentials afresh, refreshing them when due.
455            Transport::Codex(client) => {
456                let model = client.model().await.map_err(|error| Classified {
457                    code: if error.transient {
458                        Code::Transient
459                    } else {
460                        Code::Authentication
461                    },
462                    message: error.message,
463                    retry_after: None,
464                    output_failed: false,
465                })?;
466                delivery::register(self.inventory());
467                model.stream_observed(request, observed)
468            }
469        }
470        .map_err(|error| self.classify(&error, time::OffsetDateTime::now_utc(), &self.inventory()))
471    }
472
473    fn inventory(&self) -> Inventory {
474        let mut inventory = self.sources.inventory();
475        if let Transport::Codex(client) = &self.transport {
476            inventory.merge(client.known());
477        }
478        self.managed.update(inventory)
479    }
480
481    fn scrub_failure(&self, mut failure: Failure) -> Failure {
482        failure.message = self.inventory().scrub(&failure.message);
483        failure
484    }
485
486    /// The error code of a provider failure, from its status, codes and message. Its message
487    /// is the shared rule's: text holding part of a credential this client sent is withheld
488    /// before it reaches output, delivery events, attempts or saved sessions.
489    fn classify(
490        &self,
491        error: &ProviderError,
492        now: time::OffsetDateTime,
493        inventory: &Inventory,
494    ) -> Classified {
495        let response = error.provider_response();
496        let body = response.and_then(|response| Body::parse(response.body.as_bytes()));
497        let body = body.as_ref();
498        // Relays may already have a machine code and status independently of the reply.
499        let (status, code) = match error {
500            ProviderError::Relayed(report) => (report.http_status, report.code.as_deref()),
501            _ => (
502                response.and_then(|response| response.status.map(|status| status.as_u16())),
503                response
504                    .and_then(|response| response.code.as_deref())
505                    .or_else(|| body.and_then(Body::provider_code)),
506            ),
507        };
508        let http = status.and_then(|status| reqwest::StatusCode::from_u16(status).ok());
509        let fallback = || diagnostic_from(body, error);
510        let text = match &self.transport {
511            Transport::Codex(_) => {
512                let unix = u64::try_from(now.unix_timestamp())
513                    .ok()
514                    .map(crate::auth::codex::Timestamp::from_seconds);
515                codex::diagnostic_text(http, body, fallback, unix, inventory)
516            }
517            _ => fallback(),
518        };
519        let message = inventory.diagnostic(&text, MAX_DIAGNOSTIC_CHARS);
520        // Classified by the whole text (codes and words), never shown.
521        let text = format!("{} {text}", code.unwrap_or_default()).to_lowercase();
522        let any = |terms: &[&str]| terms.iter().any(|term| text.contains(term));
523        let code = if matches!(self.transport, Transport::Codex(_))
524            && body.is_some_and(|body| body.usage_limit(http))
525            || any(&["quota", "billing", "credit balance", "usage limit"])
526        {
527            Code::Quota
528        } else if matches!(status, Some(401 | 403))
529            || any(&[
530                "authentication",
531                "unauthorized",
532                "permission",
533                "invalid_api_key",
534                "api key",
535            ])
536        {
537            Code::Authentication
538        } else if status == Some(429) || any(&["rate_limit", "rate limit"]) {
539            Code::RateLimit
540        } else if error.is_retryable()
541            || matches!(self.transport, Transport::Openai(_) | Transport::Codex(_))
542                && body.and_then(|body| body.codex_fields().code()) == Some("server_is_overloaded")
543            // A server-side failure can clear without changing the request.
544            || http.is_some_and(|status| status.is_server_error())
545            || (status.is_none()
546                && matches!(
547                    code,
548                    // Codex reports overloads inside a successful HTTP stream, without
549                    // an HTTP error status; it is the same retryable provider failure.
550                    Some(
551                        "overloaded_error" | "server_is_overloaded" | "server_error" | "api_error"
552                    )
553                ))
554        {
555            Code::Transient
556        } else {
557            Code::ProviderError
558        };
559        Classified {
560            code,
561            message,
562            retry_after: retry_after(error, now),
563            output_failed: false,
564        }
565    }
566}
567
568mod protection;
569mod turn;
570pub use turn::Turn;
571
572/// `retry-after-ms` is read as a count of seconds first, so a thousandth of it is the wait.
573const MILLIS_PER_SECOND: u32 = 1000;
574
575/// The wait a provider asked for: `retry-after-ms`, or `Retry-After` in seconds or as an
576/// HTTP date.
577fn retry_after(error: &ProviderError, now: time::OffsetDateTime) -> Option<Duration> {
578    wait_header(error.provider_response_headers()?, now)
579}
580
581fn wait_header(
582    headers: &rig_core::http_client::HeaderMap,
583    now: time::OffsetDateTime,
584) -> Option<Duration> {
585    let header = |name: &str| headers.get(name)?.to_str().ok().map(str::trim);
586    let seconds = |value: &str| {
587        value
588            .parse::<f64>()
589            .ok()
590            .filter(|value| value.is_finite() && *value >= 0.0)
591            .and_then(|value| Duration::try_from_secs_f64(value).ok())
592    };
593    if let Some(wait) = header("retry-after-ms").and_then(seconds) {
594        return Some(wait / MILLIS_PER_SECOND);
595    }
596    let value = header("retry-after")?;
597    seconds(value).or_else(|| {
598        let at = time::OffsetDateTime::parse(value, &time::format_description::well_known::Rfc2822)
599            .ok()?;
600        Some(Duration::try_from(at - now).unwrap_or_default())
601    })
602}
603
604/// A provider error as text, cleaned for a terminal but not clipped: callers decide what of
605/// it may be shown ([`crate::secret::server_text`]) before cutting it.
606fn diagnostic_text(error: &ProviderError) -> String {
607    let body = error
608        .provider_response_body()
609        .and_then(|body| Body::parse(body.as_bytes()));
610    diagnostic_from(body.as_ref(), error)
611}
612
613fn diagnostic_from(body: Option<&Body>, error: &ProviderError) -> String {
614    match body.and_then(Body::provider_message) {
615        Some(message) => clean_text(message),
616        None => clean_text(&error.to_string()),
617    }
618}
619
620/// The environment variable that points a built-in provider at a loopback test endpoint;
621/// `None` for Claude Code, which reaches its service itself.
622pub fn base_url_variable(provider: HttpProvider) -> &'static str {
623    match provider {
624        HttpProvider::Openai => "ARTIFACTIZE_OPENAI_BASE_URL",
625        HttpProvider::Anthropic => "ARTIFACTIZE_ANTHROPIC_BASE_URL",
626        HttpProvider::Gemini => "ARTIFACTIZE_GEMINI_BASE_URL",
627        HttpProvider::Codex => "ARTIFACTIZE_CODEX_BASE_URL",
628    }
629}
630
631/// Every test endpoint variable: the backends' API roots and the Codex sign-in root.
632const TEST_ENDPOINTS: [&str; 5] = [
633    "ARTIFACTIZE_OPENAI_BASE_URL",
634    "ARTIFACTIZE_ANTHROPIC_BASE_URL",
635    "ARTIFACTIZE_GEMINI_BASE_URL",
636    "ARTIFACTIZE_CODEX_BASE_URL",
637    crate::auth::codex::AUTH_URL_VARIABLE,
638];
639
640/// A test endpoint: an http(s) URL on localhost, 127.0.0.0/8 or [::1], without
641/// credentials, a query or a fragment. A test endpoint never leaves the machine.
642#[derive(Debug, Clone, PartialEq, Eq)]
643pub struct TestEndpoint(url::Url);
644
645impl TestEndpoint {
646    pub(crate) fn into_url(self) -> url::Url {
647        self.0
648    }
649    /// The endpoint as an API root, the text an SDK or a request path starts from: its URL
650    /// without a trailing slash.
651    pub fn root(&self) -> &str {
652        self.0.as_str().trim_end_matches('/')
653    }
654}
655
656impl std::str::FromStr for TestEndpoint {
657    type Err = String;
658    fn from_str(value: &str) -> Result<Self, Self::Err> {
659        loopback_url(value)
660    }
661}
662
663impl std::fmt::Display for TestEndpoint {
664    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
665        formatter.write_str(self.root())
666    }
667}
668
669impl Serialize for TestEndpoint {
670    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
671        serializer.serialize_str(self.root())
672    }
673}
674
675/// The loopback test endpoint that replaces the provider's API root, if one is set.
676pub fn test_endpoint(provider: HttpProvider) -> Result<Option<TestEndpoint>, String> {
677    variable_endpoint(base_url_variable(provider))
678}
679
680pub fn variable_endpoint(variable: &str) -> Result<Option<TestEndpoint>, String> {
681    variable_endpoint_in(variable, crate::platform::var)
682}
683
684/// [`variable_endpoint`] read from `var` instead of this process's environment.
685pub fn variable_endpoint_in(
686    variable: &str,
687    var: impl Fn(&str) -> Option<std::ffi::OsString>,
688) -> Result<Option<TestEndpoint>, String> {
689    let Some(value) = var(variable).filter(|value| !value.is_empty()) else {
690        return Ok(None);
691    };
692    crate::platform::as_text(&value)
693        .map_err(str::to_owned)
694        .and_then(loopback_url)
695        .map(Some)
696        .map_err(|error| format!("{variable}: {error}."))
697}
698
699/// The first test endpoint variable that is set, valid or not.
700pub fn active_test_endpoint() -> Option<&'static str> {
701    TEST_ENDPOINTS
702        .into_iter()
703        .find(|variable| crate::platform::var(variable).is_some_and(|value| !value.is_empty()))
704}
705
706/// `value` as a [`TestEndpoint`], or why it is not one.
707fn loopback_url(value: &str) -> Result<TestEndpoint, String> {
708    let url = url::Url::parse(value).map_err(|_| "it is not a URL".to_owned())?;
709    let loopback = match url.host() {
710        Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
711        Some(url::Host::Ipv4(ip)) => IpAddr::V4(ip).is_loopback(),
712        Some(url::Host::Ipv6(ip)) => IpAddr::V6(ip).is_loopback(),
713        None => false,
714    };
715    if !matches!(url.scheme(), "http" | "https") || !loopback {
716        return Err("a test endpoint must be http(s) on localhost, 127.0.0.0/8 or [::1]".into());
717    }
718    if !url.username().is_empty()
719        || url.password().is_some()
720        || url.query().is_some()
721        || url.fragment().is_some()
722    {
723        return Err("a test endpoint has no credentials, query or fragment".into());
724    }
725    Ok(TestEndpoint(url))
726}
727
728/// The provider's API root: its loopback test endpoint, else the provider's. Claude Code
729/// has none: it reaches its service itself.
730fn base_url(provider: HttpProvider) -> Result<url::Url, String> {
731    if let Some(endpoint) = test_endpoint(provider)? {
732        return Ok(endpoint.0);
733    }
734    let base = match provider {
735        HttpProvider::Openai => "https://api.openai.com/v1",
736        HttpProvider::Anthropic => "https://api.anthropic.com",
737        HttpProvider::Gemini => gemini::BASE_URL,
738        HttpProvider::Codex => codex::BASE_URL,
739    };
740    Ok(url::Url::parse(base).expect("built-in provider base URL"))
741}
742
743/// Rig model listing appends a path starting with `/` to this textual root.
744fn adapter_base(base: &url::Url) -> &str {
745    base.as_str().trim_end_matches('/')
746}
747
748fn http_client() -> Result<reqwest::Client, String> {
749    reqwest::Client::builder()
750        .retry(reqwest::retry::never())
751        .redirect(reqwest::redirect::Policy::none())
752        .build()
753        .map_err(|error| error.to_string())
754}
755
756/// `message` cleaned for a terminal (escape sequences and control characters), unclipped.
757fn clean_text(message: &str) -> String {
758    String::from_utf8(crate::platform::clean_text(message.as_bytes()))
759        .expect("clean output is UTF-8")
760}