1mod 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;
13#[cfg(test)]
14pub(crate) mod tests;
15mod usage;
16
17use std::{
18 net::IpAddr,
19 path::Path,
20 sync::{Arc, Mutex},
21 time::Duration,
22};
23
24use error_body::Body;
25use futures_util::StreamExt;
26use rig_core::{
27 Model,
28 completion::{CompletionRequest, CompletionResponse, FinishReason},
29 error::ProviderError,
30 observe::{Action, AdapterContext, AdapterEvent, Observation, Subject, Witness},
31 providers::{anthropic, gemini, openai},
32 streaming::{CompletionStream, Item, StreamEvent},
33};
34use serde::{Deserialize, Serialize};
35use serde_json::{Map, Value, json};
36use tokio::time::Instant;
37use tokio_util::sync::CancellationToken;
38
39pub use api::{Api, EndpointApi};
40
41use crate::{
42 agent::error::{Code, Failure},
43 auth::providers::{self, ApiKey, Custom},
44 config::{Backend, ModelId, Provider},
45};
46
47const ATTEMPTS: usize = 3;
49const RETRY_BACKOFF_BASE: Duration = Duration::from_millis(250);
52const MAX_DIAGNOSTIC_CHARS: usize = 4096;
54const ANTHROPIC_OUTPUT_TOKENS: u64 = 16_384;
57
58pub enum Client {
62 Openai(Box<Model<openai::responses_api::wire::Responses>>, String),
63 Chat(Box<Model<openai::wire::Chat>>, String),
64 Anthropic(Box<Model<anthropic::wire::Messages>>, String),
65 Gemini(Box<Model<gemini::completion::GenerateContent>>, String),
66 Codex(codex::Codex),
67}
68
69pub(crate) enum Route {
71 ClaudeAgent,
72 Http(HttpRoute),
73}
74
75pub(crate) struct HttpRoute {
76 api: Api,
77 base: url::Url,
78 key: Option<ApiKey>,
79}
80
81pub(crate) fn route(
85 backend: &Backend,
86 state: Option<&Path>,
87 repo: Option<&Path>,
88 purpose: &str,
89) -> Result<Route, Failure> {
90 let missing = |message: String| Failure::new(Code::Authentication, message);
91 let provider = match backend.builtin() {
92 Some(provider) => provider,
93 None => match providers::custom(backend, state, repo)? {
94 Some(Custom::Alias { provider }) => provider,
95 Some(Custom::Endpoint { api, url, key }) => {
96 return Ok(Route::Http(HttpRoute {
97 api: api.into(),
98 base: url.into_url(),
99 key,
100 }));
101 }
102 None => {
103 return Err(missing(format!(
104 "No provider named {backend} is set up on this machine; add it in Settings → Providers or with `artifactize provider add {backend}`."
105 )));
106 }
107 },
108 };
109 if provider == Provider::ClaudeAgent {
110 return Ok(Route::ClaudeAgent);
111 }
112 let key = match providers::key_variable(provider) {
113 Some(variable) => Some(providers::key(provider, state, repo)?.ok_or_else(|| {
114 missing(format!(
115 "{variable} or a saved {provider} key is required {purpose}."
116 ))
117 })?),
118 None => None,
119 };
120 Ok(Route::Http(HttpRoute {
121 api: provider.into(),
122 base: base_url(provider)?,
123 key,
124 }))
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize)]
128#[serde(rename_all = "camelCase")]
129pub struct Attempt {
130 #[serde(default)]
131 pub turn: usize,
132 #[serde(default)]
133 pub attempt: usize,
134 #[serde(default)]
135 pub usage: usage::Usage,
136 #[serde(skip_serializing_if = "Option::is_none")]
137 pub error: Option<String>,
138 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub error_code: Option<Code>,
140}
141
142struct Classified {
144 code: Code,
145 message: String,
146 retry_after: Option<Duration>,
147 output_failed: bool,
148}
149
150impl From<Classified> for Failure {
151 fn from(classified: Classified) -> Self {
152 Self {
153 output_failed: classified.output_failed,
154 ..Self::new(classified.code, classified.message)
155 }
156 }
157}
158
159impl From<Failure> for Classified {
160 fn from(failure: Failure) -> Self {
161 Self {
162 code: failure.code,
163 message: failure.message,
164 retry_after: None,
165 output_failed: failure.output_failed,
166 }
167 }
168}
169
170#[derive(Default)]
172struct ReportedUsage(Mutex<std::collections::BTreeMap<String, u64>>);
173
174impl Witness for ReportedUsage {
175 fn observe(&self, observation: Observation) {
176 if let Action::Adapter { observation } = observation.action
177 && let AdapterEvent::Usage { usage } = observation.event
178 {
179 let mut counters = self.0.lock().unwrap();
180 for (name, value) in [
181 ("inputTokens", usage.input_tokens),
182 ("outputTokens", usage.output_tokens),
183 ("totalTokens", usage.total_tokens),
184 ("cacheReadTokens", usage.cached_input_tokens),
185 ("reasoningTokens", usage.reasoning_tokens),
186 ] {
187 insert_counter(&mut counters, name, value);
188 }
189 }
190 }
191}
192
193fn insert_counter(
194 counters: &mut std::collections::BTreeMap<String, u64>,
195 name: &str,
196 value: Option<u64>,
197) {
198 if let Some(value) = value.filter(|value| *value <= crate::types::MAX_SAFE_JSON_INTEGER) {
199 counters.insert(name.into(), value);
200 }
201}
202
203impl Client {
204 pub fn new(
207 backend: &Backend,
208 model: &crate::config::ModelId,
209 state: &Path,
210 repo: &Path,
211 ) -> Result<Self, Failure> {
212 match route(backend, Some(state), Some(repo), "for this Agent backend")? {
213 Route::Http(route) => Self::at(route, model, state, repo),
214 Route::ClaudeAgent => Err(Failure::new(
215 Code::AgentError,
216 "Unsupported client backend: claude-agent runs reviews through Claude Code.",
217 )),
218 }
219 }
220
221 pub(crate) fn at(
224 HttpRoute { api, base, key }: HttpRoute,
225 model: &crate::config::ModelId,
226 state: &Path,
227 repo: &Path,
228 ) -> Result<Self, Failure> {
229 if api == Api::Codex {
230 return Ok(Self::Codex(codex::Codex::new(model, base, state, repo)?));
231 }
232 let base = adapter_base(&base);
233 let key = key.map(|key| key.expose().to_owned()).unwrap_or_default();
235 let http = delivery::Tap::new(http_client()?);
236 let openai = || {
237 openai::OpenAIConfig::new(key.clone())
238 .with_base_url(base)
239 .connect(http.clone())
240 };
241 Ok(match api {
242 Api::OpenaiResponses => {
243 Self::Openai(Box::new(openai().responses(model.as_str())), key.clone())
244 }
245 Api::OpenaiChat => Self::Chat(Box::new(openai().chat(model.as_str())), key.clone()),
246 Api::Anthropic => Self::Anthropic(
247 Box::new(
248 anthropic::AnthropicConfig::new(key.clone())
249 .with_base_url(base)
250 .connect(http)
251 .completion(model.as_str()),
252 ),
253 key,
254 ),
255 Api::Gemini => Self::Gemini(
256 Box::new(
257 gemini::GeminiConfig::new(key.clone())
258 .with_base_url(base)
259 .connect(http)
260 .completion(model.as_str()),
261 ),
262 key,
263 ),
264 Api::Codex | Api::ClaudeAgent => unreachable!("handled above"),
265 })
266 }
267
268 pub fn api(&self) -> Api {
270 match self {
271 Self::Openai(..) => Api::OpenaiResponses,
272 Self::Chat(..) => Api::OpenaiChat,
273 Self::Anthropic(..) => Api::Anthropic,
274 Self::Gemini(..) => Api::Gemini,
275 Self::Codex(_) => Api::Codex,
276 }
277 }
278
279 pub fn parameters(
283 api: Api,
284 reasoning: Option<&str>,
285 session: &crate::types::SessionId,
286 ) -> Result<Value, String> {
287 if let Some(reasoning) = reasoning {
288 api.validate_reasoning(reasoning)?;
289 }
290 Ok(match api {
291 Api::OpenaiChat => reasoning.map_or(
292 json!({}),
293 |effort| json!({"reasoning_effort":effort, "parallel_tool_calls":false}),
294 ),
295 Api::Gemini => reasoning.map_or(
296 json!({}),
297 |effort| json!({"generationConfig":{"thinkingConfig":{"thinkingLevel":effort}}}),
298 ),
299 Api::OpenaiResponses => {
300 let mut value = json!({
301 "store":false,
302 "parallel_tool_calls":false,
303 "include":["reasoning.encrypted_content"],
304 "prompt_cache_key":session,
305 });
306 if let Some(reasoning) = reasoning {
307 value["reasoning"] = json!({"effort":reasoning});
308 }
309 value
310 }
311 Api::Anthropic => reasoning.map_or(
312 json!({}),
313 |effort| json!({"thinking":{"type":"adaptive"}, "output_config":{"effort":effort}}),
314 ),
315 Api::ClaudeAgent => {
318 let mut value = json!({"thinking":"adaptive", "thinkingDisplay":"summarized"});
319 if let Some(effort) = reasoning {
320 value["effort"] = json!(effort);
321 }
322 value
323 }
324 Api::Codex => {
327 let mut value = json!({"prompt_cache_key":session});
328 if let Some(effort) = reasoning {
329 value["reasoning"] = json!({"effort":effort, "summary":"auto"});
330 }
331 value
332 }
333 })
334 }
335
336 pub fn output_format(api: Api, parameters: &mut Value, schema: Value) {
340 fn section<'a>(parameters: &'a mut Value, name: &str) -> &'a mut Map<String, Value> {
341 parameters
342 .as_object_mut()
343 .expect("parameters object")
344 .entry(name)
345 .or_insert_with(|| json!({}))
346 .as_object_mut()
347 .expect("parameter section object")
348 }
349 match api {
350 Api::OpenaiResponses | Api::Codex => {
351 parameters["text"] = json!({"format":{
352 "type":"json_schema", "name":"artifactize_verdict", "strict":true,
353 "schema":schema,
354 }});
355 }
356 Api::OpenaiChat => {
357 parameters["response_format"] = json!({"type":"json_schema", "json_schema":{
358 "name":"artifactize_verdict", "strict":true, "schema":schema,
359 }});
360 }
361 Api::ClaudeAgent => {
362 parameters["jsonSchema"] = schema;
363 }
364 Api::Anthropic => {
365 section(parameters, "output_config").insert(
366 "format".into(),
367 json!({"type":"json_schema", "schema":schema}),
368 );
369 }
370 Api::Gemini => {
371 let config = section(parameters, "generationConfig");
372 config.insert("responseMimeType".into(), json!("application/json"));
373 config.insert("responseJsonSchema".into(), schema);
374 }
375 }
376 }
377
378 async fn stream(
379 &self,
380 mut request: CompletionRequest,
381 observed: AdapterContext,
382 ) -> Result<CompletionStream, Classified> {
383 match self {
384 Self::Openai(model, _) => model.stream_observed(request, observed),
385 Self::Chat(model, _) => model.stream_observed(request, observed),
386 Self::Gemini(model, _) => model.stream_observed(request, observed),
387 Self::Anthropic(model, _) => {
388 request.max_tokens = Some(ANTHROPIC_OUTPUT_TOKENS);
389 model.stream_observed(request, observed)
390 }
391 Self::Codex(client) => {
393 let model = client.model().await.map_err(|error| Classified {
394 code: if error.transient {
395 Code::Transient
396 } else {
397 Code::Authentication
398 },
399 message: error.message,
400 retry_after: None,
401 output_failed: false,
402 })?;
403 model.stream_observed(request, observed)
404 }
405 }
406 .map_err(|error| self.classify(&error, time::OffsetDateTime::now_utc()))
407 }
408
409 fn sent(&self) -> Vec<String> {
411 match self {
412 Self::Openai(_, key)
413 | Self::Chat(_, key)
414 | Self::Anthropic(_, key)
415 | Self::Gemini(_, key) => Some(key.clone())
416 .filter(|key| !key.is_empty())
417 .into_iter()
418 .collect(),
419 Self::Codex(client) => client.sent(),
420 }
421 }
422
423 fn classify(&self, error: &ProviderError, now: time::OffsetDateTime) -> Classified {
427 let response = error.provider_response();
428 let body = response.and_then(|response| Body::parse(response.body.as_bytes()));
429 let body = body.as_ref();
430 let (status, code) = match error {
432 ProviderError::Relayed(report) => (report.http_status, report.code.as_deref()),
433 _ => (
434 response.and_then(|response| response.status.map(|status| status.as_u16())),
435 response
436 .and_then(|response| response.code.as_deref())
437 .or_else(|| body.and_then(Body::provider_code)),
438 ),
439 };
440 let http = status.and_then(|status| reqwest::StatusCode::from_u16(status).ok());
441 let fallback = || diagnostic_from(body, error);
442 let text = match self {
443 Self::Codex(_) => {
444 let unix = u64::try_from(now.unix_timestamp())
445 .ok()
446 .map(crate::auth::codex::Timestamp::from_seconds);
447 codex::diagnostic_text(http, body, fallback, unix)
448 }
449 _ => fallback(),
450 };
451 let sent = self.sent();
452 let sent: Vec<&str> = sent.iter().map(String::as_str).collect();
453 let message = crate::secret::server_text(&text, &sent, MAX_DIAGNOSTIC_CHARS);
454 let text = format!("{} {text}", code.unwrap_or_default()).to_lowercase();
456 let any = |terms: &[&str]| terms.iter().any(|term| text.contains(term));
457 let code = if matches!(self, Self::Codex(_))
458 && body.is_some_and(|body| body.usage_limit(http))
459 || any(&["quota", "billing", "credit balance", "usage limit"])
460 {
461 Code::Quota
462 } else if matches!(status, Some(401 | 403))
463 || any(&[
464 "authentication",
465 "unauthorized",
466 "permission",
467 "invalid_api_key",
468 "api key",
469 ])
470 {
471 Code::Authentication
472 } else if status == Some(429) || any(&["rate_limit", "rate limit"]) {
473 Code::RateLimit
474 } else if error.is_retryable()
475 || matches!(self, Self::Openai(..) | Self::Codex(_))
476 && body.and_then(|body| body.codex_fields().code()) == Some("server_is_overloaded")
477 || http.is_some_and(|status| status.is_server_error())
479 || (status.is_none()
480 && matches!(
481 code,
482 Some(
485 "overloaded_error" | "server_is_overloaded" | "server_error" | "api_error"
486 )
487 ))
488 {
489 Code::Transient
490 } else {
491 Code::ProviderError
492 };
493 Classified {
494 code,
495 message,
496 retry_after: retry_after(error, now),
497 output_failed: false,
498 }
499 }
500}
501
502mod turn;
503pub use turn::Turn;
504
505const MILLIS_PER_SECOND: u32 = 1000;
507
508fn retry_after(error: &ProviderError, now: time::OffsetDateTime) -> Option<Duration> {
511 wait_header(error.provider_response_headers()?, now)
512}
513
514fn wait_header(
515 headers: &rig_core::http_client::HeaderMap,
516 now: time::OffsetDateTime,
517) -> Option<Duration> {
518 let header = |name: &str| headers.get(name)?.to_str().ok().map(str::trim);
519 let seconds = |value: &str| {
520 value
521 .parse::<f64>()
522 .ok()
523 .filter(|value| value.is_finite() && *value >= 0.0)
524 .and_then(|value| Duration::try_from_secs_f64(value).ok())
525 };
526 if let Some(wait) = header("retry-after-ms").and_then(seconds) {
527 return Some(wait / MILLIS_PER_SECOND);
528 }
529 let value = header("retry-after")?;
530 seconds(value).or_else(|| {
531 let at = time::OffsetDateTime::parse(value, &time::format_description::well_known::Rfc2822)
532 .ok()?;
533 Some(Duration::try_from(at - now).unwrap_or_default())
534 })
535}
536
537fn diagnostic_text(error: &ProviderError) -> String {
540 let body = error
541 .provider_response_body()
542 .and_then(|body| Body::parse(body.as_bytes()));
543 diagnostic_from(body.as_ref(), error)
544}
545
546fn diagnostic_hiding(error: &ProviderError, secrets: &[&str]) -> String {
549 crate::secret::server_text(&diagnostic_text(error), secrets, MAX_DIAGNOSTIC_CHARS)
550}
551
552fn diagnostic_from(body: Option<&Body>, error: &ProviderError) -> String {
553 match body.and_then(Body::provider_message) {
554 Some(message) => clean_text(message),
555 None => clean_text(&error.to_string()),
556 }
557}
558
559pub fn base_url_variable(provider: Provider) -> Option<&'static str> {
562 match provider {
563 Provider::Openai => Some("ARTIFACTIZE_OPENAI_BASE_URL"),
564 Provider::Anthropic => Some("ARTIFACTIZE_ANTHROPIC_BASE_URL"),
565 Provider::Gemini => Some("ARTIFACTIZE_GEMINI_BASE_URL"),
566 Provider::Codex => Some("ARTIFACTIZE_CODEX_BASE_URL"),
567 Provider::ClaudeAgent => None,
568 }
569}
570
571const TEST_ENDPOINTS: [&str; 5] = [
573 "ARTIFACTIZE_OPENAI_BASE_URL",
574 "ARTIFACTIZE_ANTHROPIC_BASE_URL",
575 "ARTIFACTIZE_GEMINI_BASE_URL",
576 "ARTIFACTIZE_CODEX_BASE_URL",
577 crate::auth::codex::AUTH_URL_VARIABLE,
578];
579
580#[derive(Debug, Clone, PartialEq, Eq)]
583pub struct TestEndpoint(url::Url);
584
585impl TestEndpoint {
586 pub(crate) fn into_url(self) -> url::Url {
587 self.0
588 }
589 pub fn root(&self) -> &str {
592 self.0.as_str().trim_end_matches('/')
593 }
594}
595
596impl std::str::FromStr for TestEndpoint {
597 type Err = String;
598 fn from_str(value: &str) -> Result<Self, Self::Err> {
599 loopback_url(value)
600 }
601}
602
603impl std::fmt::Display for TestEndpoint {
604 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
605 formatter.write_str(self.root())
606 }
607}
608
609impl Serialize for TestEndpoint {
610 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
611 serializer.serialize_str(self.root())
612 }
613}
614
615pub fn test_endpoint(provider: Provider) -> Result<Option<TestEndpoint>, String> {
617 base_url_variable(provider).map_or(Ok(None), variable_endpoint)
618}
619
620pub fn variable_endpoint(variable: &str) -> Result<Option<TestEndpoint>, String> {
623 variable_endpoint_in(variable, crate::platform::environment::var)
624}
625
626pub fn variable_endpoint_in(
628 variable: &str,
629 var: impl Fn(&str) -> Option<std::ffi::OsString>,
630) -> Result<Option<TestEndpoint>, String> {
631 let Some(value) = var(variable).filter(|value| !value.is_empty()) else {
632 return Ok(None);
633 };
634 value
635 .to_str()
636 .ok_or_else(|| "it is not UTF-8".to_owned())
637 .and_then(loopback_url)
638 .map(Some)
639 .map_err(|error| format!("{variable}: {error}."))
640}
641
642pub fn active_test_endpoint() -> Option<&'static str> {
644 TEST_ENDPOINTS.into_iter().find(|variable| {
645 crate::platform::environment::var(variable).is_some_and(|value| !value.is_empty())
646 })
647}
648
649fn loopback_url(value: &str) -> Result<TestEndpoint, String> {
651 let url = url::Url::parse(value).map_err(|_| "it is not a URL".to_owned())?;
652 let loopback = match url.host() {
653 Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
654 Some(url::Host::Ipv4(ip)) => IpAddr::V4(ip).is_loopback(),
655 Some(url::Host::Ipv6(ip)) => IpAddr::V6(ip).is_loopback(),
656 None => false,
657 };
658 if !matches!(url.scheme(), "http" | "https") || !loopback {
659 return Err("a test endpoint must be http(s) on localhost, 127.0.0.0/8 or [::1]".into());
660 }
661 if !url.username().is_empty()
662 || url.password().is_some()
663 || url.query().is_some()
664 || url.fragment().is_some()
665 {
666 return Err("a test endpoint has no credentials, query or fragment".into());
667 }
668 Ok(TestEndpoint(url))
669}
670
671fn base_url(provider: Provider) -> Result<url::Url, String> {
674 if let Some(endpoint) = test_endpoint(provider)? {
675 return Ok(endpoint.0);
676 }
677 let base = match provider {
678 Provider::Openai => "https://api.openai.com/v1",
679 Provider::Anthropic => "https://api.anthropic.com",
680 Provider::Gemini => gemini::BASE_URL,
681 Provider::Codex => codex::BASE_URL,
682 Provider::ClaudeAgent => unreachable!("Claude Code has no HTTP route"),
683 };
684 Ok(url::Url::parse(base).expect("built-in provider base URL"))
685}
686
687fn adapter_base(base: &url::Url) -> &str {
689 base.as_str().trim_end_matches('/')
690}
691
692fn http_client() -> Result<reqwest::Client, String> {
693 reqwest::Client::builder()
694 .retry(reqwest::retry::never())
695 .redirect(reqwest::redirect::Policy::none())
696 .build()
697 .map_err(|error| error.to_string())
698}
699
700fn clean_text(message: &str) -> String {
702 String::from_utf8(crate::runtime::clean_output(message.as_bytes()))
703 .expect("clean output is UTF-8")
704}