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