1pub 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
49const ATTEMPTS: usize = 3;
51const RETRY_BACKOFF_BASE: Duration = Duration::from_millis(250);
54const MAX_DIAGNOSTIC_CHARS: usize = 4096;
56const ANTHROPIC_OUTPUT_TOKENS: u64 = 16_384;
59
60pub 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
71pub(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
84pub(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
147struct 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#[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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 || http.is_some_and(|status| status.is_server_error())
496 || (status.is_none()
497 && matches!(
498 code,
499 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
522const MILLIS_PER_SECOND: u32 = 1000;
524
525fn 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
554fn 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
563fn 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
576pub 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
588const 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#[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 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
632pub fn test_endpoint(provider: Provider) -> Result<Option<TestEndpoint>, String> {
634 base_url_variable(provider).map_or(Ok(None), variable_endpoint)
635}
636
637pub fn variable_endpoint(variable: &str) -> Result<Option<TestEndpoint>, String> {
640 variable_endpoint_in(variable, crate::platform::environment::var)
641}
642
643pub 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
659pub 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
666fn 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
688fn 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
704fn 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
717fn clean_text(message: &str) -> String {
719 String::from_utf8(crate::runtime::clean_output(message.as_bytes()))
720 .expect("clean output is UTF-8")
721}