Skip to main content

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