Skip to main content

nitpicker_agent/
llm.rs

1use crate::tools::floor_char_boundary;
2use eyre::{Result, WrapErr};
3use rig_core::OneOrMany;
4use rig_core::client::CompletionClient;
5use rig_core::completion::CompletionError;
6use rig_core::completion::message::ReasoningContent;
7use rig_core::completion::message::ToolCall;
8use rig_core::completion::message::ToolChoice;
9use rig_core::completion::{AssistantContent, CompletionModel, Message};
10use rig_core::providers::{anthropic, gemini, openai, openrouter};
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13use std::future::Future;
14use std::pin::Pin;
15use std::sync::Arc;
16use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
17use std::time::{Duration, SystemTime, UNIX_EPOCH};
18use tokio::sync::Semaphore;
19use tracing::{debug, warn};
20
21const MAX_COMPLETION_ATTEMPTS: usize = 4;
22const RATE_LIMIT_MAX_COMPLETION_ATTEMPTS: usize = 8;
23const BASE_BACKOFF_MS: u64 = 250;
24const MAX_BACKOFF_MS: u64 = 5_000;
25const RATE_LIMIT_BASE_BACKOFF_MS: u64 = 5_000;
26const RATE_LIMIT_MAX_BACKOFF_MS: u64 = 60_000;
27const ANTHROPIC_DEFAULT_MAX_TOKENS: u64 = 8_192;
28
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct Completion {
31    pub model: String,
32    pub prompt: Message,
33    pub preamble: Option<String>,
34    pub history: Vec<Message>,
35    pub tools: Vec<rig_core::completion::ToolDefinition>,
36    pub tool_choice: Option<ToolChoice>,
37    pub max_tokens: Option<u64>,
38    pub additional_params: Option<Value>,
39}
40
41impl Completion {
42    pub fn preamble(mut self, preamble: impl Into<String>) -> Self {
43        self.preamble = Some(preamble.into());
44        self
45    }
46
47    pub fn tools(mut self, tools: Vec<rig_core::completion::ToolDefinition>) -> Self {
48        self.tools = tools;
49        self
50    }
51
52    pub fn history(mut self, history: Vec<Message>) -> Self {
53        self.history = history;
54        self
55    }
56
57    pub fn max_tokens(mut self, max_tokens: u64) -> Self {
58        self.max_tokens = Some(max_tokens);
59        self
60    }
61
62    pub fn additional_params(mut self, additional_params: Value) -> Self {
63        self.additional_params = Some(additional_params);
64        self
65    }
66}
67
68impl From<Completion> for rig_core::completion::CompletionRequest {
69    fn from(value: Completion) -> Self {
70        let chat_history = value
71            .history
72            .into_iter()
73            .chain(std::iter::once(value.prompt))
74            .collect::<Vec<_>>();
75        rig_core::completion::CompletionRequest {
76            model: None,
77            chat_history: OneOrMany::many(chat_history)
78                .expect("completion request must include at least one message"),
79            preamble: value.preamble,
80            documents: Vec::new(),
81            tools: value.tools,
82            temperature: None,
83            max_tokens: value.max_tokens,
84            additional_params: value.additional_params,
85            output_schema: None,
86            tool_choice: value.tool_choice,
87            // local telemetry policy only (`#[serde(skip)]`), never sent to a provider
88            record_telemetry_content: false,
89        }
90    }
91}
92
93#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
94pub enum FinishReason {
95    None,
96    Stop,
97    MaxTokens,
98    ToolUse,
99    Other(String),
100}
101
102#[derive(Debug, Clone, Deserialize, Serialize)]
103pub struct CompletionResponse {
104    pub choice: OneOrMany<AssistantContent>,
105    pub finish_reason: FinishReason,
106    pub usage: TokenUsage,
107    pub selected_model: Option<String>,
108}
109
110#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
111pub struct TokenUsage {
112    /// Every prompt token the provider processed for this call, cache reads included.
113    pub input_tokens: u64,
114    pub output_tokens: u64,
115    /// Always `input_tokens + output_tokens`.
116    pub total_tokens: u64,
117    /// A breakdown of `input_tokens`, not an additional charge. Passed through verbatim.
118    #[serde(default)]
119    pub cached_input_tokens: u64,
120    /// The part of `input_tokens` written into the cache on this call.
121    #[serde(default)]
122    pub cache_creation_input_tokens: u64,
123}
124
125/// Whether a provider's reported prompt count already contains its cache reads. Stated by each
126/// client, never inferred: provider totals can carry categories that are neither prompt nor output
127/// (Gemini) or disagree with their own parts (OpenRouter), so arithmetic tests misclassify.
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum CacheAccounting {
130    /// Anthropic: cache reads and writes are reported beside `input_tokens`, not within it.
131    OutsidePrompt,
132    /// OpenAI (chat and Responses), OpenRouter, Gemini: cache reads are already in the prompt.
133    InsidePrompt,
134}
135
136impl TokenUsage {
137    /// Normalize usage so `input_tokens` always means every prompt token processed, cache reads
138    /// included — without it an Anthropic cache hit under-reports the prompt and
139    /// `ConversationUsageWindow::should_compact` never fires.
140    ///
141    /// Numbers are re-bucketed, never invented: a provider contradicting itself is reported as it
142    /// reported itself. `total_tokens` is `input + output`, so anything counted outside both
143    /// (Gemini's thinking tokens) goes unmetered.
144    pub fn from_provider(usage: &rig_core::completion::Usage, accounting: CacheAccounting) -> Self {
145        let input_tokens = match accounting {
146            CacheAccounting::OutsidePrompt => usage
147                .input_tokens
148                .saturating_add(usage.cached_input_tokens)
149                .saturating_add(usage.cache_creation_input_tokens),
150            CacheAccounting::InsidePrompt => usage.input_tokens,
151        };
152        Self {
153            input_tokens,
154            output_tokens: usage.output_tokens,
155            total_tokens: input_tokens.saturating_add(usage.output_tokens),
156            cached_input_tokens: usage.cached_input_tokens,
157            cache_creation_input_tokens: usage.cache_creation_input_tokens,
158        }
159    }
160}
161
162#[derive(Debug, Clone, Default)]
163pub struct ConversationUsageWindow {
164    compact_threshold: Option<u64>,
165    usage: TokenUsage,
166}
167
168impl ConversationUsageWindow {
169    pub fn new(compact_threshold: Option<u64>) -> Self {
170        Self {
171            compact_threshold,
172            usage: TokenUsage::default(),
173        }
174    }
175
176    pub fn should_compact(&self) -> bool {
177        self.compact_threshold
178            .map(|threshold| self.usage.total_tokens >= threshold)
179            .unwrap_or(false)
180    }
181
182    pub fn usage(&self) -> TokenUsage {
183        self.usage
184    }
185
186    pub fn record(&mut self, usage: TokenUsage) {
187        // Each response reports the whole prompt it was sent, not the new tokens, so replace
188        // rather than accumulate. Note this is the size of the *last* request: tool results
189        // appended after it are not counted until the next response comes back.
190        self.usage = usage;
191    }
192
193    pub fn reset(&mut self) {
194        self.usage = TokenUsage::default();
195    }
196}
197
198impl CompletionResponse {
199    pub fn message(&self) -> Message {
200        Message::Assistant {
201            id: None,
202            content: self.choice.clone(),
203        }
204    }
205
206    pub fn tool_calls(&self) -> Option<Vec<ToolCall>> {
207        if self.finish_reason != FinishReason::ToolUse {
208            return None;
209        }
210        let calls = self
211            .choice
212            .iter()
213            .filter_map(|content| match content {
214                AssistantContent::ToolCall(call) => Some(call.clone()),
215                _ => None,
216            })
217            .collect::<Vec<_>>();
218        if calls.is_empty() { None } else { Some(calls) }
219    }
220
221    pub fn text(&self) -> String {
222        // join the raw text blocks first, then strip once: a think block that spans
223        // (or a truncated one that runs to EOF) is judged against the whole text, and an
224        // all-reasoning response collapses to "" so callers' is_empty() checks fire.
225        let raw = self
226            .choice
227            .iter()
228            .filter_map(|content| match content {
229                AssistantContent::Text(text) => Some(text.text().to_string()),
230                _ => None,
231            })
232            .collect::<Vec<_>>()
233            .join("\n");
234        let (stripped, unclosed_body) = scan_think_blocks(&raw);
235        // only an *unclosed* block can hide an answer; a closed one that leaves nothing behind is
236        // genuinely all-reasoning and must read as empty so the retry fires.
237        let Some(start) = unclosed_body else {
238            return stripped;
239        };
240        // Recovery runs even with text before the block: that text only makes the loss silent,
241        // since a non-empty response never retries.
242        let recovered = self.recover_unterminated_think(&raw[start..]);
243        match (stripped.is_empty(), recovered.is_empty()) {
244            (_, true) => stripped,
245            (true, false) => recovered,
246            (false, false) => format!("{stripped}\n\n{recovered}"),
247        }
248    }
249
250    /// Salvage an answer that an unterminated `<think>` block swallowed.
251    ///
252    /// Where the reasoning ends is only knowable because the provider also reports it structurally
253    /// and the block repeats it verbatim before the answer, so it is subtracted, never guessed. An
254    /// unmatched body returns empty: serving it would pass chain-of-thought off as the verdict.
255    fn recover_unterminated_think(&self, body: &str) -> String {
256        let Some(reasoning) = self.reasoning_text() else {
257            return String::new();
258        };
259        let body = body.trim_start();
260        let Some(answer) = body.strip_prefix(reasoning.trim()) else {
261            return String::new();
262        };
263        // Word boundary, not whitespace: reasoning ending mid-word ("Ver" against "Verdict:") is a
264        // coincidental prefix, but real replies do run straight on from the final punctuation.
265        let cuts_mid_word = reasoning
266            .trim()
267            .chars()
268            .next_back()
269            .is_some_and(char::is_alphanumeric)
270            && answer.starts_with(char::is_alphanumeric);
271        match cuts_mid_word {
272            true => String::new(),
273            false => answer.trim().to_string(),
274        }
275    }
276
277    /// The response's structured reasoning, as reported beside the message content.
278    fn reasoning_text(&self) -> Option<String> {
279        let text = self
280            .choice
281            .iter()
282            .filter_map(|content| match content {
283                AssistantContent::Reasoning(reasoning) => Some(&reasoning.content),
284                _ => None,
285            })
286            .flatten()
287            .filter_map(|block| match block {
288                ReasoningContent::Text { text, .. } => Some(text.as_str()),
289                // Summary paraphrases and Encrypted/Redacted are opaque; none appear verbatim in
290                // the block, so they would corrupt the reconstruction rather than complete it.
291                _ => None,
292            })
293            .collect::<String>();
294        match text.trim().is_empty() {
295            true => None,
296            false => Some(text),
297        }
298    }
299}
300
301// some providers (notably MiniMax/GLM/DeepSeek via OpenRouter) emit chain-of-thought
302// inline as <think>...</think> in the message content rather than in a structured
303// reasoning field rig can drop. A depth-tracking scanner (not a single regex, which can't
304// match balanced nesting) keeps text only at nesting depth 0, so:
305//   - `<think...>` / `</think...>` are matched case-insensitively, tolerating padded tags
306//     like `<think >` (a regex whose open tag lacked `\s*` would leak their bodies)
307//   - nested tags can't leak: inner reasoning stays inside depth > 0
308//   - an unterminated block is dropped through end-of-text rather than leaking its body
309//   - a stray closing tag at depth 0 is dropped
310// note: this is content-wide, so a review that legitimately quotes a <think> tag in a code
311// snippet will have it stripped too — an accepted tradeoff for clean aggregation.
312/// The text outside think blocks, plus where the body of an unclosed block begins. An offset
313/// rather than a flag so recovery never re-parses tags: with several blocks or a stray closer, the
314/// first `<think>` is not the one that stayed open.
315fn scan_think_blocks(text: &str) -> (String, Option<usize>) {
316    // match `<think` (or `</think` when `close`) + optional whitespace + `>` at the start of
317    // `s`, case-insensitively; return the matched byte length. `<thinking>` is not a tag (the
318    // char after `think` must be whitespace or `>`).
319    fn match_think_tag(s: &str, close: bool) -> Option<usize> {
320        let prefix = if close { "</think" } else { "<think" };
321        if !s.get(..prefix.len())?.eq_ignore_ascii_case(prefix) {
322            return None;
323        }
324        let after = &s[prefix.len()..];
325        let ws = after.len() - after.trim_start().len();
326        after[ws..]
327            .starts_with('>')
328            .then_some(prefix.len() + ws + 1)
329    }
330
331    let mut out = String::with_capacity(text.len());
332    let mut depth: usize = 0;
333    let mut consumed = 0usize;
334    let mut open_body_start = None;
335    let mut rest = text;
336    while !rest.is_empty() {
337        if rest.starts_with('<') {
338            if let Some(len) = match_think_tag(rest, false) {
339                depth += 1;
340                consumed += len;
341                if depth == 1 {
342                    open_body_start = Some(consumed);
343                }
344                rest = &rest[len..];
345                continue;
346            }
347            if let Some(len) = match_think_tag(rest, true) {
348                depth = depth.saturating_sub(1);
349                if depth == 0 {
350                    open_body_start = None;
351                }
352                consumed += len;
353                rest = &rest[len..];
354                continue;
355            }
356        }
357        let ch = rest.chars().next().expect("rest is non-empty");
358        if depth == 0 {
359            out.push(ch);
360        }
361        consumed += ch.len_utf8();
362        rest = &rest[ch.len_utf8()..];
363    }
364    let unclosed_body = match depth > 0 {
365        true => open_body_start,
366        false => None,
367    };
368    (out.trim().to_string(), unclosed_body)
369}
370
371pub trait LLMClient: Send + Sync {
372    fn completion(
373        &self,
374        completion: Completion,
375    ) -> impl Future<Output = Result<CompletionResponse>> + Send;
376
377    fn into_arc(self) -> Arc<dyn LLMClientDyn>
378    where
379        Self: Sized + 'static,
380    {
381        Arc::new(self)
382    }
383}
384
385pub trait LLMClientDyn: Send + Sync {
386    fn completion(
387        &self,
388        completion: Completion,
389    ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>>;
390
391    /// Fork mutable routing state for an independently progressing agent while retaining shared
392    /// provider clients and run-wide route availability. Stateless clients return `None` and may
393    /// safely be shared by `Arc`.
394    fn fork_for_agent(&self) -> Option<Arc<dyn LLMClientDyn>> {
395        None
396    }
397}
398
399impl<T: LLMClient> LLMClientDyn for T {
400    fn completion(
401        &self,
402        completion: Completion,
403    ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>> {
404        Box::pin(LLMClient::completion(self, completion))
405    }
406}
407
408impl LLMClient for Box<dyn LLMClientDyn> {
409    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
410        (**self).completion(completion).await
411    }
412}
413
414/// What the provider said about a response carrying neither text nor a tool call. Without it an
415/// exhausted output budget is indistinguishable from a model that had nothing to say.
416fn empty_response_diagnosis(response: &CompletionResponse) -> String {
417    let output_tokens = response.usage.output_tokens;
418    match &response.finish_reason {
419        FinishReason::MaxTokens => format!(
420            "hit the output limit after {output_tokens} tokens without emitting content — \
421             reasoning consumed the whole budget, so raise max_tokens or leave it unset to use \
422             the provider's own limit"
423        ),
424        other => format!("finish_reason {other:?}, {output_tokens} output tokens"),
425    }
426}
427
428pub struct RetryingLLM<C> {
429    inner: C,
430}
431
432pub trait WithRetryExt: Sized {
433    fn with_retry(self) -> RetryingLLM<Self> {
434        RetryingLLM { inner: self }
435    }
436}
437
438impl<T: LLMClient> WithRetryExt for T {}
439
440impl<C: LLMClient> LLMClient for RetryingLLM<C> {
441    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
442        let mut attempt = 0usize;
443        loop {
444            attempt += 1;
445            match self.inner.completion(completion.clone()).await {
446                Ok(response) => {
447                    if response.text().is_empty() && response.tool_calls().is_none() {
448                        let diagnosis = empty_response_diagnosis(&response);
449                        if attempt >= MAX_COMPLETION_ATTEMPTS {
450                            eyre::bail!(
451                                "model returned empty response after {attempt} attempts: {diagnosis}"
452                            );
453                        }
454                        let backoff = jittered_backoff(attempt, BASE_BACKOFF_MS, MAX_BACKOFF_MS);
455                        warn!(
456                            model = %completion.model,
457                            attempt,
458                            max_attempts = MAX_COMPLETION_ATTEMPTS,
459                            backoff_ms = backoff.as_millis(),
460                            diagnosis,
461                            "retrying after empty model response"
462                        );
463                        tokio::time::sleep(backoff).await;
464                        continue;
465                    }
466                    return Ok(response);
467                }
468                Err(err) => {
469                    let policy = retry_policy(&err);
470                    if !policy.retry || attempt >= policy.max_attempts {
471                        return Err(err);
472                    }
473                    let backoff =
474                        jittered_backoff(attempt, policy.base_backoff_ms, policy.max_backoff_ms);
475                    warn!(
476                        model = %completion.model,
477                        attempt,
478                        max_attempts = policy.max_attempts,
479                        backoff_ms = backoff.as_millis(),
480                        error = %err,
481                        "retrying model completion after error"
482                    );
483                    tokio::time::sleep(backoff).await;
484                }
485            }
486        }
487    }
488}
489
490/// One model route in an alloy/fallback pool, carrying the settings that belong to it rather than
491/// to the logical reviewer role. Inner clients must already be retry-wrapped.
492#[derive(Clone)]
493pub struct AlloySlot {
494    pub client: Arc<dyn LLMClientDyn>,
495    pub model: String,
496    pub max_tokens: Option<u64>,
497}
498
499/// A fallback-capable route. Unlike the legacy public [`AlloySlot`] shape, clones share their
500/// run-local availability and warning state so independent reviewer/aggregator clients stop
501/// probing a quota-exhausted subscription and announce that one route failure only once.
502#[derive(Clone)]
503pub struct FallbackSlot {
504    client: Arc<dyn LLMClientDyn>,
505    model: String,
506    max_tokens: Option<u64>,
507    unavailable: Arc<AtomicBool>,
508    failover_warning_emitted: Arc<AtomicBool>,
509}
510
511impl FallbackSlot {
512    pub fn new(
513        client: Arc<dyn LLMClientDyn>,
514        model: impl Into<String>,
515        max_tokens: Option<u64>,
516    ) -> Self {
517        Self {
518            client,
519            model: model.into(),
520            max_tokens,
521            unavailable: Arc::new(AtomicBool::new(false)),
522            failover_warning_emitted: Arc::new(AtomicBool::new(false)),
523        }
524    }
525
526    fn is_available(&self) -> bool {
527        !self.unavailable.load(Ordering::Acquire)
528    }
529
530    fn mark_unavailable(&self) {
531        self.unavailable.store(true, Ordering::Release);
532    }
533
534    fn claim_failover_warning(&self) -> bool {
535        !self.failover_warning_emitted.swap(true, Ordering::AcqRel)
536    }
537
538    pub fn client(&self) -> Arc<dyn LLMClientDyn> {
539        Arc::clone(&self.client)
540    }
541}
542
543impl From<AlloySlot> for FallbackSlot {
544    fn from(slot: AlloySlot) -> Self {
545        Self::new(slot.client, slot.model, slot.max_tokens)
546    }
547}
548
549impl From<&FallbackSlot> for AlloySlot {
550    fn from(slot: &FallbackSlot) -> Self {
551        Self {
552            client: Arc::clone(&slot.client),
553            model: slot.model.clone(),
554            max_tokens: slot.max_tokens,
555        }
556    }
557}
558
559/// Deterministic failover for one logical reviewer. The caller puts the configured primary first;
560/// after an exhausted client retry policy, the remaining reviewer routes are tried in declaration
561/// order, wrapping at the end. The same completion (including its full history) is replayed, so the
562/// agent does not lose completed investigation work.
563pub struct PriorityClient {
564    slots: Vec<FallbackSlot>,
565    active_idx: AtomicUsize,
566}
567
568impl PriorityClient {
569    pub fn new(slots: Vec<FallbackSlot>) -> Result<Self> {
570        if slots.is_empty() {
571            eyre::bail!("PriorityClient requires at least one slot");
572        }
573        Ok(Self {
574            slots,
575            active_idx: AtomicUsize::new(0),
576        })
577    }
578}
579
580impl LLMClientDyn for PriorityClient {
581    fn completion(
582        &self,
583        completion: Completion,
584    ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>> {
585        Box::pin(complete_from_slots(
586            &self.slots,
587            self.active_idx.load(Ordering::Acquire),
588            true,
589            completion,
590            Some(&self.active_idx),
591        ))
592    }
593
594    fn fork_for_agent(&self) -> Option<Arc<dyn LLMClientDyn>> {
595        Some(Arc::new(Self {
596            slots: self.slots.clone(),
597            active_idx: AtomicUsize::new(self.active_idx.load(Ordering::Acquire)),
598        }))
599    }
600}
601
602/// Randomly chooses the first model for every completion — see
603/// https://xbow.com/blog/alloy-agents. With fallback enabled, a failed random pick falls through
604/// the remaining configured reviewers in declaration order.
605pub struct AlloyClient {
606    slots: Vec<FallbackSlot>,
607    fallback: bool,
608}
609
610impl AlloyClient {
611    pub fn new(slots: Vec<AlloySlot>) -> Result<Self> {
612        Self::build(slots.into_iter().map(FallbackSlot::from).collect(), false)
613    }
614
615    pub fn new_with_fallback_routes(slots: Vec<FallbackSlot>) -> Result<Self> {
616        Self::build(slots, true)
617    }
618
619    fn build(slots: Vec<FallbackSlot>, fallback: bool) -> Result<Self> {
620        if slots.is_empty() {
621            eyre::bail!("AlloyClient requires at least one slot");
622        }
623        Ok(Self { slots, fallback })
624    }
625
626    fn available_indices(&self) -> Vec<usize> {
627        self.slots
628            .iter()
629            .enumerate()
630            .filter_map(|(index, slot)| slot.is_available().then_some(index))
631            .collect()
632    }
633
634    fn pick_idx(&self) -> Option<usize> {
635        use rand::RngExt;
636        let available = self.available_indices();
637        if available.is_empty() {
638            return None;
639        }
640        Some(available[rand::rng().random_range(0..available.len())])
641    }
642}
643
644impl LLMClientDyn for AlloyClient {
645    fn completion(
646        &self,
647        completion: Completion,
648    ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>> {
649        match self.pick_idx() {
650            Some(start_idx) => Box::pin(complete_from_slots(
651                &self.slots,
652                start_idx,
653                self.fallback,
654                completion,
655                None,
656            )),
657            None => Box::pin(async {
658                eyre::bail!("all configured model routes are unavailable for this run")
659            }),
660        }
661    }
662}
663
664fn requires_tool_call(tool_choice: &Option<ToolChoice>) -> bool {
665    matches!(
666        tool_choice.as_ref(),
667        Some(ToolChoice::Required | ToolChoice::Specific { .. })
668    )
669}
670
671fn tool_protocol_error(completion: &Completion, response: &CompletionResponse) -> Option<String> {
672    let calls = response.tool_calls();
673    if response.finish_reason == FinishReason::ToolUse {
674        let Some(calls) = calls.as_ref() else {
675            return Some("reported tool use without returning a tool call".to_string());
676        };
677        if let Some(call) = calls.iter().find(|call| {
678            !completion
679                .tools
680                .iter()
681                .any(|tool| tool.name == call.function.name)
682        }) {
683            return Some(format!("called undeclared tool '{}'", call.function.name));
684        }
685        if let Some(ToolChoice::Specific { function_names }) = &completion.tool_choice
686            && let Some(call) = calls
687                .iter()
688                .find(|call| !function_names.contains(&call.function.name))
689        {
690            return Some(format!(
691                "called tool '{}' instead of the specifically requested tool",
692                call.function.name
693            ));
694        }
695    } else if requires_tool_call(&completion.tool_choice) {
696        return Some("returned text instead of the required tool call".to_string());
697    }
698    None
699}
700
701async fn complete_from_slots(
702    slots: &[FallbackSlot],
703    start_idx: usize,
704    fallback: bool,
705    completion: Completion,
706    sticky_index: Option<&AtomicUsize>,
707) -> Result<CompletionResponse> {
708    if !fallback {
709        let slot = &slots[start_idx];
710        let mut request = completion;
711        request.model = slot.model.clone();
712        request.max_tokens = slot.max_tokens;
713        let mut response = slot.client.completion(request).await?;
714        response.selected_model = Some(slot.model.clone());
715        return Ok(response);
716    }
717
718    let attempts = slots.len();
719    let mut last_err = None;
720    let mut attempted_models = Vec::with_capacity(attempts);
721
722    for offset in 0..attempts {
723        let idx = (start_idx + offset) % slots.len();
724        let slot = &slots[idx];
725        if !slot.is_available() {
726            continue;
727        }
728        let mut request = completion.clone();
729        request.model = slot.model.clone();
730        // A cap belongs to the selected model route, not the logical role whose turn this is.
731        request.max_tokens = slot.max_tokens;
732        attempted_models.push(slot.model.clone());
733        let (err, sticky_failure) = match slot.client.completion(request).await {
734            Ok(mut response) => {
735                let protocol_error = match &response.finish_reason {
736                    FinishReason::MaxTokens => Some(format!(
737                        "model route '{}' reached its output token limit after {} tokens",
738                        slot.model, response.usage.output_tokens
739                    )),
740                    _ => tool_protocol_error(&completion, &response)
741                        .map(|reason| format!("model route '{}': {reason}", slot.model)),
742                };
743                if let Some(message) = protocol_error {
744                    (eyre::eyre!(message), false)
745                } else {
746                    response.selected_model = Some(slot.model.clone());
747                    if let Some(index) = sticky_index {
748                        index.store(idx, Ordering::Release);
749                    }
750                    return Ok(response);
751                }
752            }
753            Err(err) => {
754                let sticky_failure = is_sticky_fallback_error(&err);
755                if sticky_failure {
756                    slot.mark_unavailable();
757                }
758                (err, sticky_failure)
759            }
760        };
761        if let Some(next_idx) = (1..attempts - offset)
762            .map(|step| (idx + step) % slots.len())
763            .find(|&candidate| slots[candidate].is_available())
764        {
765            if sticky_failure {
766                if slot.claim_failover_warning() {
767                    warn!(
768                        failed_model = %slot.model,
769                        next_model = %slots[next_idx].model,
770                        "model unavailable; trying next configured reviewer"
771                    );
772                } else {
773                    debug!(
774                        failed_model = %slot.model,
775                        next_model = %slots[next_idx].model,
776                        error = ?err,
777                        "duplicate unavailable-route failure; continuing with fallback"
778                    );
779                }
780            } else {
781                warn!(
782                    failed_model = %slot.model,
783                    next_model = %slots[next_idx].model,
784                    error = %err,
785                    "model failed; trying next configured reviewer"
786                );
787            }
788        }
789        last_err = Some(err);
790    }
791
792    match last_err {
793        Some(err) => {
794            let attempted = attempted_models.join(" -> ");
795            Err(err.wrap_err(format!("all model routes failed ({attempted})")))
796        }
797        None => eyre::bail!("all configured model routes are unavailable for this run"),
798    }
799}
800
801/// Run a single completion under a concurrency permit. The permit is held only for the duration of
802/// this one call and released immediately after — never across a subagent spawn — so callers may
803/// block on acquire without risking deadlock. This is the single chokepoint that bounds account-wide
804/// in-flight LLM calls; route every concurrent completion (agent turns, compaction) through it.
805pub async fn throttled_completion(
806    semaphore: &Semaphore,
807    client: &Arc<dyn LLMClientDyn>,
808    completion: Completion,
809) -> Result<CompletionResponse> {
810    let _permit = semaphore.acquire().await.expect("llm semaphore closed");
811    client.completion(completion).await
812}
813
814struct RetryPolicy {
815    retry: bool,
816    max_attempts: usize,
817    base_backoff_ms: u64,
818    max_backoff_ms: u64,
819}
820
821fn retry_policy(err: &eyre::Report) -> RetryPolicy {
822    match classify_provider_failure(err) {
823        // A rolling subscription allowance measured in hours cannot recover within this command.
824        // Surface it immediately so fallback can move on instead of entering the 429 backoff loop.
825        ProviderFailureClass::PermanentQuota => RetryPolicy {
826            retry: false,
827            max_attempts: 0,
828            base_backoff_ms: 0,
829            max_backoff_ms: 0,
830        },
831        ProviderFailureClass::RateLimit => RetryPolicy {
832            retry: true,
833            max_attempts: RATE_LIMIT_MAX_COMPLETION_ATTEMPTS,
834            base_backoff_ms: RATE_LIMIT_BASE_BACKOFF_MS,
835            max_backoff_ms: RATE_LIMIT_MAX_BACKOFF_MS,
836        },
837        ProviderFailureClass::ContextLength | ProviderFailureClass::NonRetryableClient => {
838            RetryPolicy {
839                retry: false,
840                max_attempts: 0,
841                base_backoff_ms: 0,
842                max_backoff_ms: 0,
843            }
844        }
845        ProviderFailureClass::Server | ProviderFailureClass::Unknown => RetryPolicy {
846            retry: true,
847            max_attempts: MAX_COMPLETION_ATTEMPTS,
848            base_backoff_ms: BASE_BACKOFF_MS,
849            max_backoff_ms: MAX_BACKOFF_MS,
850        },
851    }
852}
853
854/// Exact provider error codes which describe a request that cannot succeed unchanged. These are
855/// read from structured `error.code` / `error.type` / `error.status` / `error_type` fields, never
856/// searched for in a rendered error string.
857const NON_RETRYABLE_ERROR_CODES: &[&str] = &[
858    "authentication_error",
859    "invalid_api_key",
860    "permission_error",
861    "permission_denied",
862    "invalid_request_error",
863    "not_found_error",
864];
865
866/// Exact transient overload/throttling codes which warrant the longer rate-limit backoff policy.
867const RATE_LIMIT_ERROR_CODES: &[&str] = &[
868    "rate_limit_error",
869    "rate_limit_exceeded",
870    "overloaded_error",
871];
872
873/// Exact provider codes for allowance exhaustion which cannot recover during this command.
874const PERMANENT_QUOTA_ERROR_CODES: &[&str] = &["insufficient_quota", "usage_limit_reached"];
875
876#[derive(Debug, Clone, Copy, PartialEq, Eq)]
877enum ProviderFailureClass {
878    Server,
879    PermanentQuota,
880    RateLimit,
881    ContextLength,
882    NonRetryableClient,
883    Unknown,
884}
885
886#[derive(Debug, Default)]
887struct ProviderErrorFacts {
888    status: Option<u16>,
889    body_status: Option<u16>,
890    body_code_status: Option<u16>,
891    codes: Vec<String>,
892    messages: Vec<String>,
893}
894
895impl ProviderErrorFacts {
896    fn from_report(err: &eyre::Report) -> Option<Self> {
897        let completion_error = err
898            .chain()
899            .find_map(|source| source.downcast_ref::<CompletionError>())?;
900        let mut facts = Self {
901            status: completion_error
902                .provider_response_status()
903                .map(|status| status.as_u16()),
904            ..Self::default()
905        };
906        match completion_error.provider_response_json() {
907            Ok(Some(body)) => {
908                collect_provider_status_hints(&body, &mut facts);
909                collect_provider_error_fields(&body, &mut facts);
910            }
911            Err(_) => {
912                if let Some(body) = completion_error.provider_response_body() {
913                    // Some compatible gateways return text/plain. This is the sole unstructured
914                    // compatibility input: it is still the provider body, never the rendered
915                    // eyre chain or surrounding diagnostic text.
916                    facts.messages.push(body.to_string());
917                }
918            }
919            Ok(None) => {}
920        }
921        Some(facts)
922    }
923
924    fn effective_status(&self) -> Option<u16> {
925        match self.status {
926            Some(status) if !(200..300).contains(&status) => Some(status),
927            _ => self.body_status.or(self.body_code_status).or(self.status),
928        }
929    }
930
931    fn has_code(&self, expected: &[&str]) -> bool {
932        self.codes
933            .iter()
934            .any(|code| expected.contains(&code.as_str()))
935    }
936}
937
938fn numeric_field(object: &serde_json::Map<String, Value>, keys: &[&str]) -> Option<u16> {
939    keys.iter().find_map(|key| {
940        object
941            .get(*key)
942            .and_then(Value::as_u64)
943            .and_then(|value| u16::try_from(value).ok())
944    })
945}
946
947/// Rank body-carried status hints by their semantic position instead of whichever numeric field a
948/// recursive traversal happens to encounter first. Top-level status fields describe an envelope;
949/// a numeric provider `code` is only a fallback for 2xx/statusless error envelopes.
950fn collect_provider_status_hints(value: &Value, facts: &mut ProviderErrorFacts) {
951    let Some(root) = value.as_object() else {
952        return;
953    };
954    facts.body_status = numeric_field(root, &["status", "statusCode", "status_code"]);
955    facts.body_code_status = numeric_field(root, &["code"]);
956
957    if let Some(error) = root.get("error").and_then(Value::as_object) {
958        facts.body_status = facts
959            .body_status
960            .or_else(|| numeric_field(error, &["status", "statusCode", "status_code"]));
961        facts.body_code_status = facts
962            .body_code_status
963            .or_else(|| numeric_field(error, &["code"]));
964    }
965}
966
967/// Collect only semantically named scalar fields from a provider JSON error envelope. Recursing
968/// covers gateway shapes such as `{ "upstream": { "error": ... } }`; the real outer HTTP status
969/// is stored separately and always wins over nested provider facts.
970fn collect_provider_error_fields(value: &Value, facts: &mut ProviderErrorFacts) {
971    match value {
972        Value::Object(object) => {
973            for (key, value) in object {
974                match (key.as_str(), value) {
975                    ("code" | "type" | "status" | "error_type", Value::String(value)) => {
976                        facts.codes.push(value.to_ascii_lowercase());
977                    }
978                    ("message", Value::String(value)) => facts.messages.push(value.clone()),
979                    _ => collect_provider_error_fields(value, facts),
980                }
981            }
982        }
983        Value::Array(values) => {
984            for value in values {
985                collect_provider_error_fields(value, facts);
986            }
987        }
988        _ => {}
989    }
990}
991
992/// Keep Codex's stored provider error bounded without turning valid JSON into an unparseable
993/// prefix. Large structured bodies are projected to the exact facts used by the classifier;
994/// malformed/text bodies retain the old bounded-prefix behavior.
995pub(crate) fn compact_provider_error_body(body: &str, compact_above_bytes: usize) -> String {
996    if body.len() <= compact_above_bytes {
997        return body.to_string();
998    }
999    let Ok(value) = serde_json::from_str::<Value>(body) else {
1000        return truncate_utf8(body, compact_above_bytes);
1001    };
1002    let mut facts = ProviderErrorFacts::default();
1003    collect_provider_status_hints(&value, &mut facts);
1004    collect_provider_error_fields(&value, &mut facts);
1005    let codes = facts
1006        .codes
1007        .into_iter()
1008        .take(16)
1009        .map(|code| serde_json::json!({ "code": truncate_utf8(&code, 128) }))
1010        .collect::<Vec<_>>();
1011    let messages = facts
1012        .messages
1013        .into_iter()
1014        .take(4)
1015        .map(|message| serde_json::json!({ "message": truncate_utf8(&message, 512) }))
1016        .collect::<Vec<_>>();
1017    serde_json::json!({
1018        "status": facts.body_status,
1019        "code": facts.body_code_status,
1020        "details": codes,
1021        "messages": messages,
1022    })
1023    .to_string()
1024}
1025
1026fn truncate_utf8(value: &str, max_bytes: usize) -> String {
1027    if value.len() <= max_bytes {
1028        return value.to_string();
1029    }
1030    let end = floor_char_boundary(value, max_bytes);
1031    format!("{}…", &value[..end])
1032}
1033
1034fn classify_provider_failure(err: &eyre::Report) -> ProviderFailureClass {
1035    let Some(facts) = ProviderErrorFacts::from_report(err) else {
1036        return ProviderFailureClass::Unknown;
1037    };
1038    let status = facts.effective_status();
1039
1040    // Anthropic defines a captured HTTP 529 carrying `overloaded_error` as provider overload. It
1041    // follows the longer overload/throttling policy; an arbitrary gateway 5xx with a nested
1042    // overload payload must still retain normal server-error precedence.
1043    if facts.status == Some(529) && facts.has_code(&["overloaded_error"]) {
1044        return ProviderFailureClass::RateLimit;
1045    }
1046    // The captured HTTP status is otherwise the outer response. A gateway 5xx therefore remains
1047    // transient even when its JSON body embeds an upstream quota or client-error payload.
1048    if status.is_some_and(|status| (500..600).contains(&status)) {
1049        return ProviderFailureClass::Server;
1050    }
1051    if facts.has_code(PERMANENT_QUOTA_ERROR_CODES)
1052        || facts
1053            .messages
1054            .iter()
1055            .any(|message| is_long_window_quota_message(message))
1056    {
1057        return ProviderFailureClass::PermanentQuota;
1058    }
1059    if facts.has_code(RATE_LIMIT_ERROR_CODES) || status == Some(429) {
1060        return ProviderFailureClass::RateLimit;
1061    }
1062    if facts.has_code(&["context_length_exceeded"])
1063        || (facts.has_code(&["invalid_request_error"])
1064            && facts
1065                .messages
1066                .iter()
1067                .any(|message| message.to_ascii_lowercase().contains("prompt is too long")))
1068    {
1069        return ProviderFailureClass::ContextLength;
1070    }
1071    if facts.has_code(NON_RETRYABLE_ERROR_CODES)
1072        || status.is_some_and(|status| (400..=404).contains(&status))
1073    {
1074        return ProviderFailureClass::NonRetryableClient;
1075    }
1076    ProviderFailureClass::Unknown
1077}
1078
1079pub(crate) fn provider_http_status(err: &eyre::Report) -> Option<u16> {
1080    ProviderErrorFacts::from_report(err).and_then(|facts| facts.effective_status())
1081}
1082
1083pub(crate) fn provider_error_has_code(err: &eyre::Report, expected: &[&str]) -> bool {
1084    ProviderErrorFacts::from_report(err).is_some_and(|facts| facts.has_code(expected))
1085}
1086
1087/// Whether an error chain reports a context-window overflow — the one synthesis failure
1088/// where "select fewer presets" is real remediation. Matches the OpenAI-style type token
1089/// (`context_length_exceeded`) and the Anthropic shape — an `invalid_request_error` whose
1090/// message says the prompt is too long; a generic `invalid_request_error` alone does NOT
1091/// qualify (those are malformed-request bugs, not size problems).
1092pub fn is_context_length_error(err: &eyre::Report) -> bool {
1093    classify_provider_failure(err) == ProviderFailureClass::ContextLength
1094}
1095
1096#[cfg(test)]
1097fn is_non_retryable_client_error(err: &eyre::Report) -> bool {
1098    matches!(
1099        classify_provider_failure(err),
1100        ProviderFailureClass::ContextLength | ProviderFailureClass::NonRetryableClient
1101    )
1102}
1103
1104#[cfg(test)]
1105fn is_rate_limit_error(err: &eyre::Report) -> bool {
1106    classify_provider_failure(err) == ProviderFailureClass::RateLimit
1107}
1108
1109#[cfg(test)]
1110fn is_long_window_quota_error(err: &eyre::Report) -> bool {
1111    classify_provider_failure(err) == ProviderFailureClass::PermanentQuota
1112}
1113
1114fn is_long_window_quota_message(msg: &str) -> bool {
1115    let msg = msg.to_ascii_lowercase();
1116    msg.contains("out of tokens")
1117        || msg.contains("hit your usage limit")
1118        || msg.contains("usage limit has been reached")
1119        || ((msg.contains("usage limit") || msg.contains("token limit"))
1120            && (msg.contains("window")
1121                || msg.contains("reset")
1122                || msg.contains("refresh")
1123                || msg.contains("billing cycle")
1124                || msg.contains("next cycle")
1125                || msg.contains("5h")
1126                || msg.contains("5 h")
1127                || msg.contains("5 hour")))
1128}
1129
1130/// Whether an error represents an operational provider limit that cannot recover during this run.
1131/// CLI layers use this to present a concise message while retaining the full report at debug level.
1132pub fn is_operational_limit_error(err: &eyre::Report) -> bool {
1133    is_sticky_fallback_error(err)
1134}
1135
1136fn is_sticky_fallback_error(err: &eyre::Report) -> bool {
1137    matches!(
1138        classify_provider_failure(err),
1139        ProviderFailureClass::PermanentQuota | ProviderFailureClass::RateLimit
1140    )
1141}
1142
1143fn jittered_backoff(attempt: usize, base_backoff_ms: u64, max_backoff_ms: u64) -> Duration {
1144    let exp = 2u64.saturating_pow((attempt - 1) as u32);
1145    let base = (base_backoff_ms * exp).min(max_backoff_ms);
1146    let jitter = jitter_factor();
1147    let jittered = (base as f64 * jitter).round() as u64;
1148    Duration::from_millis(jittered.max(1))
1149}
1150
1151fn jitter_factor() -> f64 {
1152    let nanos = SystemTime::now()
1153        .duration_since(UNIX_EPOCH)
1154        .map(|d| d.subsec_nanos())
1155        .unwrap_or(0);
1156    let scaled = (nanos % 1000) as f64 / 1000.0;
1157    0.5 + scaled
1158}
1159
1160fn normalize_openrouter_completion_error(err: CompletionError) -> eyre::Report {
1161    let empty_response = matches!(
1162        &err,
1163        CompletionError::ResponseError(msg)
1164            if msg.contains("no message or tool call") || msg.contains("no choices")
1165    );
1166    let report = eyre::Report::new(err);
1167    if empty_response {
1168        report.wrap_err("empty response from model (no message or tool call)")
1169    } else {
1170        report
1171    }
1172}
1173
1174fn is_local_base_url(base_url: Option<&str>) -> bool {
1175    base_url
1176        .map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
1177        .unwrap_or(false)
1178}
1179
1180/// Resolve the API key when its env var is unset: a local base_url needs no real key, otherwise it
1181/// is a hard error naming the missing var.
1182fn missing_or_local(key_env: &str, base_url: Option<&str>) -> Result<String> {
1183    if is_local_base_url(base_url) {
1184        Ok("local".to_string())
1185    } else {
1186        Err(eyre::eyre!("missing env var {key_env}"))
1187    }
1188}
1189
1190pub enum LLMProvider {
1191    Anthropic {
1192        base_url: Option<String>,
1193        api_key_env: Option<String>,
1194    },
1195    Gemini {
1196        base_url: Option<String>,
1197        api_key_env: Option<String>,
1198    },
1199    OpenAi {
1200        base_url: Option<String>,
1201        api_key_env: Option<String>,
1202    },
1203    OpenRouter {
1204        api_key_env: String,
1205    },
1206}
1207
1208impl LLMProvider {
1209    pub fn client_from_env(&self) -> Result<Box<dyn LLMClientDyn>> {
1210        match self {
1211            LLMProvider::Anthropic {
1212                base_url,
1213                api_key_env,
1214            } => {
1215                let key_env = api_key_env.as_deref().unwrap_or("ANTHROPIC_API_KEY");
1216                let api_key = std::env::var(key_env)
1217                    .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
1218                let mut builder = anthropic::Client::builder().api_key(api_key);
1219                if let Some(url) = base_url {
1220                    builder = builder.base_url(url);
1221                }
1222                Ok(Box::new(builder.build()?))
1223            }
1224            LLMProvider::Gemini {
1225                base_url,
1226                api_key_env,
1227            } => {
1228                // An explicit api_key_env overrides the GEMINI_API_KEY → GOOGLE_AI_API_KEY default
1229                // chain; a local base_url needs no key (mirrors the Anthropic/OpenAi arms).
1230                let api_key = match api_key_env {
1231                    Some(key_env) => std::env::var(key_env)
1232                        .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?,
1233                    None => std::env::var("GEMINI_API_KEY")
1234                        .or_else(|_| std::env::var("GOOGLE_AI_API_KEY"))
1235                        .or_else(|_| {
1236                            missing_or_local(
1237                                "GEMINI_API_KEY (or GOOGLE_AI_API_KEY)",
1238                                base_url.as_deref(),
1239                            )
1240                        })?,
1241                };
1242                let mut builder = gemini::Client::builder().api_key(api_key);
1243                if let Some(url) = base_url {
1244                    builder = builder.base_url(url);
1245                }
1246                let client = builder
1247                    .build()
1248                    .map_err(|e| eyre::eyre!("failed to create Gemini client: {e}"))?;
1249                Ok(Box::new(client))
1250            }
1251            LLMProvider::OpenAi {
1252                base_url,
1253                api_key_env,
1254            } => {
1255                let key_env = api_key_env.as_deref().unwrap_or("OPENAI_API_KEY");
1256                let api_key = std::env::var(key_env)
1257                    .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
1258                let mut builder = openai::CompletionsClient::builder().api_key(&api_key);
1259                if let Some(url) = base_url {
1260                    builder = builder.base_url(url);
1261                }
1262                Ok(Box::new(builder.build()?))
1263            }
1264            LLMProvider::OpenRouter { api_key_env } => {
1265                let api_key = std::env::var(api_key_env)
1266                    .map_err(|_| eyre::eyre!("missing env var {api_key_env}"))?;
1267                let client = openrouter::Client::builder()
1268                    .api_key(&api_key)
1269                    .http_headers(openrouter_headers()?)
1270                    .build()?;
1271                Ok(Box::new(client))
1272            }
1273        }
1274    }
1275}
1276
1277pub fn openrouter_headers() -> Result<reqwest::header::HeaderMap> {
1278    let mut headers = reqwest::header::HeaderMap::new();
1279    headers.insert(
1280        "HTTP-Referer",
1281        "https://github.com/arsenyinfo/nitpicker".parse()?,
1282    );
1283    headers.insert("X-OpenRouter-Title", "nitpicker".parse()?);
1284    headers.insert(
1285        "X-OpenRouter-Categories",
1286        "cli-agent,programming-app".parse()?,
1287    );
1288    Ok(headers)
1289}
1290
1291impl LLMClient for openrouter::Client {
1292    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
1293        let model_name = completion.model.clone();
1294        let mut request: rig_core::completion::CompletionRequest = completion.into();
1295        request.model = Some(model_name.clone());
1296        let model = self.completion_model(&model_name);
1297        let response = model
1298            .completion(request)
1299            .await
1300            .map_err(normalize_openrouter_completion_error)
1301            .wrap_err_with(|| format!("OpenRouter completion failed for model '{model_name}'"))?;
1302        let finish_reason = response
1303            .raw_response
1304            .choices
1305            .first()
1306            .and_then(|c| c.finish_reason.as_deref())
1307            .map(|reason| match reason {
1308                "stop" => FinishReason::Stop,
1309                "length" => FinishReason::MaxTokens,
1310                "tool_calls" => FinishReason::ToolUse,
1311                other => FinishReason::Other(other.to_string()),
1312            })
1313            .unwrap_or(FinishReason::None);
1314        let finish_reason = resolve_finish_reason(&response.choice, finish_reason);
1315        Ok(CompletionResponse {
1316            choice: response.choice,
1317            finish_reason,
1318            usage: TokenUsage::from_provider(&response.usage, CacheAccounting::InsidePrompt),
1319            selected_model: Some(model_name),
1320        })
1321    }
1322}
1323
1324/// Create a Gemini client that routes through the local OAuth proxy
1325#[cfg(feature = "antigravity")]
1326pub fn create_gemini_client_with_proxy(
1327    proxy_url: &str,
1328) -> Result<std::sync::Arc<dyn LLMClientDyn>> {
1329    // Build a Gemini client with the proxy URL as the base URL
1330    // The API key doesn't matter for OAuth proxy, but is required by the builder
1331    let api_key = std::env::var("GEMINI_API_KEY").unwrap_or_else(|_| "oauth-proxy".to_string());
1332    let client = gemini::Client::builder()
1333        .api_key(api_key)
1334        .base_url(proxy_url)
1335        .build()?;
1336    Ok(client.with_retry().into_arc())
1337}
1338
1339impl LLMClient for anthropic::Client {
1340    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
1341        let model_name = completion.model.clone();
1342        let mut request: rig_core::completion::CompletionRequest = completion.into();
1343        request.model = Some(model_name.clone());
1344        // Anthropic requires `max_tokens`, so "no cap" cannot be expressed here. rig's own default
1345        // covers only model names it recognizes and falls back to 2048 for every compatible
1346        // gateway — less than one review turn spends on reasoning.
1347        request
1348            .max_tokens
1349            .get_or_insert(ANTHROPIC_DEFAULT_MAX_TOKENS);
1350        let model = self.completion_model(model_name.clone());
1351        let response = model
1352            .completion(request)
1353            .await
1354            .wrap_err_with(|| format!("Anthropic completion failed for model '{model_name}'"))?;
1355        let finish_reason = response
1356            .raw_response
1357            .stop_reason
1358            .clone()
1359            .map(|reason| match reason.as_str() {
1360                "end_turn" => FinishReason::Stop,
1361                "max_tokens" => FinishReason::MaxTokens,
1362                "tool_use" => FinishReason::ToolUse,
1363                other => FinishReason::Other(other.to_string()),
1364            })
1365            .unwrap_or(FinishReason::None);
1366        let finish_reason = resolve_finish_reason(&response.choice, finish_reason);
1367        Ok(CompletionResponse {
1368            choice: response.choice,
1369            finish_reason,
1370            usage: TokenUsage::from_provider(&response.usage, CacheAccounting::OutsidePrompt),
1371            selected_model: Some(model_name),
1372        })
1373    }
1374}
1375
1376impl LLMClient for gemini::Client {
1377    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
1378        let model_name = completion.model.clone();
1379        let params = build_gemini_additional_params(&completion)?;
1380        let mut request: rig_core::completion::CompletionRequest = completion.into();
1381        request.model = Some(model_name.clone());
1382        request.additional_params = Some(params);
1383        let model = self.completion_model(model_name.clone());
1384        let response = model
1385            .completion(request)
1386            .await
1387            .wrap_err_with(|| format!("Gemini completion failed for model '{model_name}'"))?;
1388        let finish_reason = response
1389            .raw_response
1390            .candidates
1391            .first()
1392            .and_then(|candidate| candidate.finish_reason.clone())
1393            .map(map_gemini_finish_reason)
1394            .unwrap_or(FinishReason::None);
1395        let finish_reason = resolve_finish_reason(&response.choice, finish_reason);
1396        Ok(CompletionResponse {
1397            choice: response.choice,
1398            finish_reason,
1399            usage: TokenUsage::from_provider(&response.usage, CacheAccounting::InsidePrompt),
1400            selected_model: Some(model_name),
1401        })
1402    }
1403}
1404
1405fn model_needs_max_completion_tokens(model: &str) -> bool {
1406    model.starts_with("o1")
1407        || model.starts_with("o3")
1408        || model.starts_with("o4")
1409        || model.starts_with("gpt-4o")
1410        || model.starts_with("gpt-4.1")
1411        || model.starts_with("gpt-4.5")
1412        || model.starts_with("gpt-5")
1413}
1414
1415/// Deep-merge `extra` over `base`: nested objects are merged recursively; on a scalar/type
1416/// conflict `extra` wins. Used to overlay computed request params without discarding caller-set
1417/// ones (e.g. a Gemini `generation_config` the caller supplied alongside its own keys).
1418pub(crate) fn merge_json(base: Value, extra: Value) -> Value {
1419    match (base, extra) {
1420        (Value::Object(mut base_obj), Value::Object(extra_obj)) => {
1421            for (k, v) in extra_obj {
1422                let merged = match base_obj.remove(&k) {
1423                    Some(existing) => merge_json(existing, v),
1424                    None => v,
1425                };
1426                base_obj.insert(k, merged);
1427            }
1428            Value::Object(base_obj)
1429        }
1430        (_, extra) => extra,
1431    }
1432}
1433
1434impl LLMClient for openai::CompletionsClient {
1435    async fn completion(&self, mut completion: Completion) -> Result<CompletionResponse> {
1436        // Newer OpenAI models (o1, o3, o4-mini, gpt-4o, gpt-5, etc.) reject the legacy
1437        // `max_tokens` param and require `max_completion_tokens` instead. Since rig always
1438        // serializes `max_tokens`, we move the value into `additional_params` and clear it.
1439        if let Some(max) = completion.max_tokens {
1440            if model_needs_max_completion_tokens(&completion.model) {
1441                let extra = serde_json::json!({ "max_completion_tokens": max });
1442                completion.additional_params = Some(match completion.additional_params.take() {
1443                    Some(existing) => merge_json(existing, extra),
1444                    None => extra,
1445                });
1446                completion.max_tokens = None;
1447            }
1448        }
1449        let model_name = completion.model.clone();
1450        let mut request: rig_core::completion::CompletionRequest = completion.into();
1451        request.model = Some(model_name.clone());
1452        let model = self.completion_model(model_name.clone());
1453        let response = model
1454            .completion(request)
1455            .await
1456            .wrap_err_with(|| format!("OpenAI completion failed for model '{model_name}'"))?;
1457        let finish_reason = response
1458            .raw_response
1459            .choices
1460            .first()
1461            .map(|choice| match choice.finish_reason.as_str() {
1462                "stop" => FinishReason::Stop,
1463                "length" => FinishReason::MaxTokens,
1464                "tool_calls" => FinishReason::ToolUse,
1465                other => FinishReason::Other(other.to_string()),
1466            })
1467            .unwrap_or(FinishReason::None);
1468        let finish_reason = resolve_finish_reason(&response.choice, finish_reason);
1469        Ok(CompletionResponse {
1470            choice: response.choice,
1471            finish_reason,
1472            usage: TokenUsage::from_provider(&response.usage, CacheAccounting::InsidePrompt),
1473            selected_model: Some(model_name),
1474        })
1475    }
1476}
1477
1478#[derive(Debug, Serialize)]
1479struct GeminiAdditionalParams {
1480    generation_config: Option<GenerationConfig>,
1481}
1482
1483impl GeminiAdditionalParams {
1484    fn from_completion(completion: &Completion) -> Self {
1485        let config = GenerationConfig {
1486            // saturating: `as i32` would turn a cap past i32::MAX into a negative field
1487            max_output_tokens: completion
1488                .max_tokens
1489                .map(|value| i32::try_from(value).unwrap_or(i32::MAX)),
1490        };
1491        Self {
1492            generation_config: Some(config),
1493        }
1494    }
1495}
1496
1497/// Overlay the computed generation config onto any caller-supplied `additional_params` instead of
1498/// replacing them, mirroring the OpenAI path's `merge_json`. The computed value wins on conflict
1499/// (e.g. the typed `max_tokens`), while caller keys like safety settings or a nested
1500/// `generation_config.temperature` survive.
1501fn build_gemini_additional_params(completion: &Completion) -> Result<Value> {
1502    let computed = serde_json::to_value(GeminiAdditionalParams::from_completion(completion))?;
1503    Ok(match &completion.additional_params {
1504        Some(existing) => merge_json(existing.clone(), computed),
1505        None => computed,
1506    })
1507}
1508
1509#[derive(Debug, Serialize, Default)]
1510struct GenerationConfig {
1511    #[serde(skip_serializing_if = "Option::is_none")]
1512    max_output_tokens: Option<i32>,
1513}
1514
1515/// A structured tool call in the choice overrides the wire finish reason: providers can pair
1516/// tool calls with `stop`-like reasons, and `CompletionResponse::tool_calls()` only surfaces
1517/// calls when the reason is `ToolUse`.
1518fn resolve_finish_reason(
1519    choice: &OneOrMany<AssistantContent>,
1520    wire_reason: FinishReason,
1521) -> FinishReason {
1522    match choice
1523        .iter()
1524        .any(|content| matches!(content, AssistantContent::ToolCall(_)))
1525    {
1526        true => FinishReason::ToolUse,
1527        false => wire_reason,
1528    }
1529}
1530
1531fn map_gemini_finish_reason(
1532    reason: gemini::completion::gemini_api_types::FinishReason,
1533) -> FinishReason {
1534    use gemini::completion::gemini_api_types::FinishReason as GeminiFinishReason;
1535    match reason {
1536        GeminiFinishReason::Stop => FinishReason::Stop,
1537        GeminiFinishReason::MaxTokens => FinishReason::MaxTokens,
1538        GeminiFinishReason::FinishReasonUnspecified => FinishReason::None,
1539        other => FinishReason::Other(format!("{other:?}")),
1540    }
1541}
1542
1543#[cfg(test)]
1544mod tests {
1545    use super::*;
1546    use rig_core::completion::Usage;
1547    use std::sync::Mutex as StdMutex;
1548
1549    fn strip_think_blocks(text: &str) -> String {
1550        scan_think_blocks(text).0
1551    }
1552    use serde_json::json;
1553
1554    fn response_with(choice: Vec<AssistantContent>) -> CompletionResponse {
1555        CompletionResponse {
1556            choice: OneOrMany::many(choice).expect("non-empty choice"),
1557            finish_reason: FinishReason::Stop,
1558            usage: TokenUsage::default(),
1559            selected_model: None,
1560        }
1561    }
1562
1563    struct RecordingClient {
1564        fail: bool,
1565        calls: Arc<StdMutex<Vec<Completion>>>,
1566    }
1567
1568    impl LLMClient for RecordingClient {
1569        async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
1570            self.calls.lock().unwrap().push(completion);
1571            if self.fail {
1572                eyre::bail!("route failed");
1573            }
1574            Ok(response_with(vec![AssistantContent::text("ok")]))
1575        }
1576    }
1577
1578    fn recording_slot(
1579        model: &str,
1580        max_tokens: Option<u64>,
1581        fail: bool,
1582    ) -> (FallbackSlot, Arc<StdMutex<Vec<Completion>>>) {
1583        let calls = Arc::new(StdMutex::new(Vec::new()));
1584        let client = RecordingClient {
1585            fail,
1586            calls: Arc::clone(&calls),
1587        }
1588        .into_arc();
1589        (FallbackSlot::new(client, model, max_tokens), calls)
1590    }
1591
1592    fn test_completion() -> Completion {
1593        Completion {
1594            model: "logical-primary".to_string(),
1595            prompt: Message::user("continue"),
1596            preamble: Some("system".to_string()),
1597            history: vec![Message::user("prior work")],
1598            tools: Vec::new(),
1599            tool_choice: None,
1600            max_tokens: Some(999),
1601            additional_params: None,
1602        }
1603    }
1604
1605    #[tokio::test]
1606    async fn priority_client_uses_next_route_without_losing_the_completion() {
1607        let (first, first_calls) = recording_slot("first", Some(10), true);
1608        let (second, second_calls) = recording_slot("second", Some(20), false);
1609        let client = PriorityClient::new(vec![first, second]).unwrap();
1610
1611        let response = client.completion(test_completion()).await.unwrap();
1612
1613        assert_eq!(response.selected_model.as_deref(), Some("second"));
1614        {
1615            let first_guard = first_calls.lock().unwrap();
1616            let second_guard = second_calls.lock().unwrap();
1617            assert_eq!(first_guard.len(), 1);
1618            assert_eq!(second_guard.len(), 1);
1619            assert_eq!(first_guard[0].model, "first");
1620            assert_eq!(first_guard[0].max_tokens, Some(10));
1621            assert_eq!(second_guard[0].model, "second");
1622            assert_eq!(second_guard[0].max_tokens, Some(20));
1623            assert_eq!(second_guard[0].history.len(), 1);
1624            assert_eq!(second_guard[0].preamble.as_deref(), Some("system"));
1625        }
1626
1627        // A successful failover becomes this logical agent's active route, so the next turn does
1628        // not probe the failed primary again.
1629        client.completion(test_completion()).await.unwrap();
1630        assert_eq!(first_calls.lock().unwrap().len(), 1);
1631        assert_eq!(second_calls.lock().unwrap().len(), 2);
1632    }
1633
1634    #[tokio::test]
1635    async fn priority_clients_share_slots_without_sharing_stickiness() {
1636        let (failed, failed_calls) = recording_slot("failed", None, true);
1637        let (healthy, healthy_calls) = recording_slot("healthy", None, false);
1638        let first = PriorityClient::new(vec![failed.clone(), healthy.clone()]).unwrap();
1639        let independent = PriorityClient::new(vec![failed, healthy]).unwrap();
1640
1641        first.completion(test_completion()).await.unwrap();
1642        first.completion(test_completion()).await.unwrap();
1643        independent.completion(test_completion()).await.unwrap();
1644
1645        // The first logical agent sticks to its successful fallback, while the independent agent
1646        // still starts from its own primary. Shared slot state is tested separately for quota.
1647        assert_eq!(failed_calls.lock().unwrap().len(), 2);
1648        assert_eq!(healthy_calls.lock().unwrap().len(), 3);
1649    }
1650
1651    #[test]
1652    fn fallback_slot_clones_share_one_failover_warning_claim() {
1653        let (slot, _) = recording_slot("shared-route", None, false);
1654        let clone = slot.clone();
1655
1656        assert!(slot.claim_failover_warning());
1657        assert!(!clone.claim_failover_warning());
1658
1659        // Dedupe follows a concrete route, not its model string: distinct credentials using the
1660        // same model must each retain their own warning claim.
1661        let (same_model_distinct_route, _) = recording_slot("shared-route", None, false);
1662        assert!(same_model_distinct_route.claim_failover_warning());
1663    }
1664
1665    struct FailOnCallClient {
1666        calls: Arc<AtomicUsize>,
1667        fail_on: usize,
1668    }
1669
1670    impl LLMClient for FailOnCallClient {
1671        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
1672            let call = self.calls.fetch_add(1, Ordering::Relaxed) + 1;
1673            if call == self.fail_on {
1674                eyre::bail!("request-specific route failure")
1675            }
1676            Ok(response_with(vec![AssistantContent::text("ok")]))
1677        }
1678    }
1679
1680    #[tokio::test]
1681    async fn agent_fork_inherits_but_cannot_overwrite_parent_stickiness() {
1682        let first_calls = Arc::new(AtomicUsize::new(0));
1683        let second_calls = Arc::new(AtomicUsize::new(0));
1684        let first = FallbackSlot::new(
1685            FailOnCallClient {
1686                calls: Arc::clone(&first_calls),
1687                fail_on: 1,
1688            }
1689            .into_arc(),
1690            "first",
1691            None,
1692        );
1693        let second = FallbackSlot::new(
1694            FailOnCallClient {
1695                calls: Arc::clone(&second_calls),
1696                fail_on: 2,
1697            }
1698            .into_arc(),
1699            "second",
1700            None,
1701        );
1702        let parent = PriorityClient::new(vec![first, second]).unwrap();
1703
1704        // The parent fails over to `second`; the fork inherits that route, then independently
1705        // wraps back to `first` when its own request fails there.
1706        parent.completion(test_completion()).await.unwrap();
1707        let fork = parent.fork_for_agent().expect("priority clients can fork");
1708        fork.completion(test_completion()).await.unwrap();
1709        parent.completion(test_completion()).await.unwrap();
1710
1711        // The parent's final turn still starts on `second`. A shared active index would have made
1712        // it start on `first`, while a fork reset to zero would have skipped `second` initially.
1713        assert_eq!(first_calls.load(Ordering::Relaxed), 2);
1714        assert_eq!(second_calls.load(Ordering::Relaxed), 3);
1715    }
1716
1717    #[tokio::test]
1718    async fn priority_client_wraps_through_declaration_order() {
1719        let (first, first_calls) = recording_slot("first", None, false);
1720        let (second, second_calls) = recording_slot("second", None, true);
1721        let (third, third_calls) = recording_slot("third", None, true);
1722        // Production callers rotate the configured ring so the logical primary is first.
1723        let client = PriorityClient::new(vec![second, third, first]).unwrap();
1724
1725        let response = client.completion(test_completion()).await.unwrap();
1726
1727        assert_eq!(response.selected_model.as_deref(), Some("first"));
1728        assert_eq!(second_calls.lock().unwrap().len(), 1);
1729        assert_eq!(third_calls.lock().unwrap().len(), 1);
1730        assert_eq!(first_calls.lock().unwrap().len(), 1);
1731    }
1732
1733    struct MaxTokensClient {
1734        calls: Arc<AtomicUsize>,
1735    }
1736
1737    impl LLMClient for MaxTokensClient {
1738        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
1739            self.calls.fetch_add(1, Ordering::Relaxed);
1740            let mut response = response_with(vec![AssistantContent::text("partial")]);
1741            response.finish_reason = FinishReason::MaxTokens;
1742            response.usage.output_tokens = 10;
1743            Ok(response)
1744        }
1745    }
1746
1747    #[tokio::test]
1748    async fn priority_client_retries_truncated_response_on_the_next_route() {
1749        let truncated_calls = Arc::new(AtomicUsize::new(0));
1750        let truncated = FallbackSlot::new(
1751            MaxTokensClient {
1752                calls: Arc::clone(&truncated_calls),
1753            }
1754            .into_arc(),
1755            "truncated",
1756            Some(10),
1757        );
1758        let (healthy, healthy_calls) = recording_slot("healthy", Some(20), false);
1759        let client = PriorityClient::new(vec![truncated, healthy]).unwrap();
1760
1761        let response = client.completion(test_completion()).await.unwrap();
1762
1763        assert_eq!(response.selected_model.as_deref(), Some("healthy"));
1764        assert_eq!(truncated_calls.load(Ordering::Relaxed), 1);
1765        assert_eq!(healthy_calls.lock().unwrap().len(), 1);
1766    }
1767
1768    struct ToolUseClient {
1769        calls: Arc<AtomicUsize>,
1770    }
1771
1772    impl LLMClient for ToolUseClient {
1773        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
1774            use rig_core::completion::message::ToolFunction;
1775            self.calls.fetch_add(1, Ordering::Relaxed);
1776            let mut response = response_with(vec![AssistantContent::ToolCall(ToolCall::new(
1777                "call-1".to_string(),
1778                ToolFunction::new("allowed".to_string(), serde_json::json!({})),
1779            ))]);
1780            response.finish_reason = FinishReason::ToolUse;
1781            Ok(response)
1782        }
1783    }
1784
1785    struct RequiredToolClient {
1786        calls: Arc<AtomicUsize>,
1787    }
1788
1789    impl LLMClient for RequiredToolClient {
1790        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
1791            use rig_core::completion::message::ToolFunction;
1792            self.calls.fetch_add(1, Ordering::Relaxed);
1793            let mut response = response_with(vec![AssistantContent::ToolCall(ToolCall::new(
1794                "call-1".to_string(),
1795                ToolFunction::new("submit".to_string(), serde_json::json!({})),
1796            ))]);
1797            response.finish_reason = FinishReason::ToolUse;
1798            Ok(response)
1799        }
1800    }
1801
1802    #[tokio::test]
1803    async fn priority_client_retries_unexpected_tool_use_for_no_tools_request() {
1804        let tool_use_calls = Arc::new(AtomicUsize::new(0));
1805        let tool_use = FallbackSlot::new(
1806            ToolUseClient {
1807                calls: Arc::clone(&tool_use_calls),
1808            }
1809            .into_arc(),
1810            "tool-use",
1811            None,
1812        );
1813        let (healthy, healthy_calls) = recording_slot("healthy", None, false);
1814        let client = PriorityClient::new(vec![tool_use, healthy]).unwrap();
1815
1816        let response = client.completion(test_completion()).await.unwrap();
1817
1818        assert_eq!(response.selected_model.as_deref(), Some("healthy"));
1819        assert_eq!(tool_use_calls.load(Ordering::Relaxed), 1);
1820        assert_eq!(healthy_calls.lock().unwrap().len(), 1);
1821    }
1822
1823    #[tokio::test]
1824    async fn priority_client_accepts_tool_use_when_tools_were_declared() {
1825        let tool_use_calls = Arc::new(AtomicUsize::new(0));
1826        let tool_use = FallbackSlot::new(
1827            ToolUseClient {
1828                calls: Arc::clone(&tool_use_calls),
1829            }
1830            .into_arc(),
1831            "tool-use",
1832            None,
1833        );
1834        let (unused, unused_calls) = recording_slot("unused", None, false);
1835        let client = PriorityClient::new(vec![tool_use, unused]).unwrap();
1836        let mut completion = test_completion();
1837        completion.tools.push(rig_core::completion::ToolDefinition {
1838            name: "allowed".to_string(),
1839            description: "An allowed tool".to_string(),
1840            parameters: serde_json::json!({"type": "object"}),
1841        });
1842
1843        let response = client.completion(completion).await.unwrap();
1844
1845        assert_eq!(response.finish_reason, FinishReason::ToolUse);
1846        assert_eq!(response.selected_model.as_deref(), Some("tool-use"));
1847        assert_eq!(tool_use_calls.load(Ordering::Relaxed), 1);
1848        assert!(unused_calls.lock().unwrap().is_empty());
1849    }
1850
1851    #[tokio::test]
1852    async fn required_tool_protocol_failure_tries_the_next_route() {
1853        let (plain_text, plain_text_calls) = recording_slot("plain-text", None, false);
1854        let required_tool_calls = Arc::new(AtomicUsize::new(0));
1855        let required_tool = FallbackSlot::new(
1856            RequiredToolClient {
1857                calls: Arc::clone(&required_tool_calls),
1858            }
1859            .into_arc(),
1860            "required-tool",
1861            None,
1862        );
1863        let client = PriorityClient::new(vec![plain_text, required_tool]).unwrap();
1864        let mut completion = test_completion();
1865        completion.tools.push(rig_core::completion::ToolDefinition {
1866            name: "submit".to_string(),
1867            description: "Submit the result".to_string(),
1868            parameters: serde_json::json!({"type": "object"}),
1869        });
1870        completion.tool_choice = Some(ToolChoice::Required);
1871
1872        let response = client.completion(completion).await.unwrap();
1873
1874        assert_eq!(response.selected_model.as_deref(), Some("required-tool"));
1875        assert_eq!(plain_text_calls.lock().unwrap().len(), 1);
1876        assert_eq!(required_tool_calls.load(Ordering::Relaxed), 1);
1877    }
1878
1879    #[tokio::test]
1880    async fn undeclared_required_tool_call_tries_the_next_route() {
1881        let wrong_tool_calls = Arc::new(AtomicUsize::new(0));
1882        let wrong_tool = FallbackSlot::new(
1883            ToolUseClient {
1884                calls: Arc::clone(&wrong_tool_calls),
1885            }
1886            .into_arc(),
1887            "wrong-tool",
1888            None,
1889        );
1890        let required_tool_calls = Arc::new(AtomicUsize::new(0));
1891        let required_tool = FallbackSlot::new(
1892            RequiredToolClient {
1893                calls: Arc::clone(&required_tool_calls),
1894            }
1895            .into_arc(),
1896            "required-tool",
1897            None,
1898        );
1899        let client = PriorityClient::new(vec![wrong_tool, required_tool]).unwrap();
1900        let mut completion = test_completion();
1901        completion.tools.push(rig_core::completion::ToolDefinition {
1902            name: "submit".to_string(),
1903            description: "Submit the result".to_string(),
1904            parameters: serde_json::json!({"type": "object"}),
1905        });
1906        completion.tool_choice = Some(ToolChoice::Required);
1907
1908        let response = client.completion(completion).await.unwrap();
1909
1910        assert_eq!(response.selected_model.as_deref(), Some("required-tool"));
1911        assert_eq!(wrong_tool_calls.load(Ordering::Relaxed), 1);
1912        assert_eq!(required_tool_calls.load(Ordering::Relaxed), 1);
1913    }
1914
1915    #[tokio::test]
1916    async fn specifically_disallowed_tool_call_tries_the_next_route() {
1917        let wrong_tool_calls = Arc::new(AtomicUsize::new(0));
1918        let wrong_tool = FallbackSlot::new(
1919            ToolUseClient {
1920                calls: Arc::clone(&wrong_tool_calls),
1921            }
1922            .into_arc(),
1923            "wrong-tool",
1924            None,
1925        );
1926        let required_tool_calls = Arc::new(AtomicUsize::new(0));
1927        let required_tool = FallbackSlot::new(
1928            RequiredToolClient {
1929                calls: Arc::clone(&required_tool_calls),
1930            }
1931            .into_arc(),
1932            "required-tool",
1933            None,
1934        );
1935        let client = PriorityClient::new(vec![wrong_tool, required_tool]).unwrap();
1936        let mut completion = test_completion();
1937        for name in ["allowed", "submit"] {
1938            completion.tools.push(rig_core::completion::ToolDefinition {
1939                name: name.to_string(),
1940                description: "A declared tool".to_string(),
1941                parameters: serde_json::json!({"type": "object"}),
1942            });
1943        }
1944        completion.tool_choice = Some(ToolChoice::Specific {
1945            function_names: vec!["submit".to_string()],
1946        });
1947
1948        let response = client.completion(completion).await.unwrap();
1949
1950        assert_eq!(response.selected_model.as_deref(), Some("required-tool"));
1951        assert_eq!(wrong_tool_calls.load(Ordering::Relaxed), 1);
1952        assert_eq!(required_tool_calls.load(Ordering::Relaxed), 1);
1953    }
1954
1955    #[tokio::test]
1956    async fn priority_client_reports_when_every_route_is_unavailable() {
1957        let (slot, calls) = recording_slot("unavailable", None, false);
1958        slot.mark_unavailable();
1959        let client = PriorityClient::new(vec![slot]).unwrap();
1960
1961        let err = client.completion(test_completion()).await.unwrap_err();
1962
1963        assert_eq!(
1964            format!("{err:#}"),
1965            "all configured model routes are unavailable for this run"
1966        );
1967        assert!(calls.lock().unwrap().is_empty());
1968    }
1969
1970    #[tokio::test]
1971    async fn alloy_without_fallback_attempts_only_the_selected_route() {
1972        let (first, first_calls) = recording_slot("first", None, true);
1973        let (second, second_calls) = recording_slot("second", None, true);
1974        let client =
1975            AlloyClient::new(vec![AlloySlot::from(&first), AlloySlot::from(&second)]).unwrap();
1976
1977        assert!(client.completion(test_completion()).await.is_err());
1978        assert_eq!(
1979            first_calls.lock().unwrap().len() + second_calls.lock().unwrap().len(),
1980            1
1981        );
1982    }
1983
1984    #[tokio::test]
1985    async fn alloy_fallback_succeeds_from_every_random_start() {
1986        let (failed_a, _) = recording_slot("failed-a", None, true);
1987        let (healthy, _) = recording_slot("healthy", None, false);
1988        let (failed_b, _) = recording_slot("failed-b", None, true);
1989        let client =
1990            AlloyClient::new_with_fallback_routes(vec![failed_a, healthy, failed_b]).unwrap();
1991
1992        // Whichever slot randomness selects first, walking the ring once must reach `healthy`.
1993        for _ in 0..32 {
1994            let response = client.completion(test_completion()).await.unwrap();
1995            assert_eq!(response.selected_model.as_deref(), Some("healthy"));
1996        }
1997    }
1998
1999    #[test]
2000    fn alloy_random_start_excludes_unavailable_routes() {
2001        let (unavailable, _) = recording_slot("unavailable", None, false);
2002        unavailable.mark_unavailable();
2003        let (first, _) = recording_slot("first", None, false);
2004        let (second, _) = recording_slot("second", None, false);
2005        let client =
2006            AlloyClient::new_with_fallback_routes(vec![unavailable, first, second]).unwrap();
2007
2008        assert_eq!(client.available_indices(), vec![1, 2]);
2009        for _ in 0..32 {
2010            assert!(matches!(client.pick_idx(), Some(1 | 2)));
2011        }
2012    }
2013
2014    struct QuotaClient {
2015        calls: Arc<AtomicUsize>,
2016    }
2017
2018    impl LLMClient for QuotaClient {
2019        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
2020            self.calls.fetch_add(1, Ordering::Relaxed);
2021            Err(eyre::Report::new(CompletionError::from_http_response(
2022                reqwest::StatusCode::TOO_MANY_REQUESTS,
2023                r#"{"error":{"code":"usage_limit_reached"}}"#,
2024            )))
2025        }
2026    }
2027
2028    #[tokio::test]
2029    async fn quota_failure_is_shared_across_agent_forks_for_the_run() {
2030        let quota_calls = Arc::new(AtomicUsize::new(0));
2031        let quota = FallbackSlot::new(
2032            QuotaClient {
2033                calls: Arc::clone(&quota_calls),
2034            }
2035            .into_arc(),
2036            "quota",
2037            None,
2038        );
2039        let (healthy, _) = recording_slot("healthy", None, false);
2040        let first = PriorityClient::new(vec![quota, healthy]).unwrap();
2041        let second = first.fork_for_agent().expect("priority clients can fork");
2042
2043        first.completion(test_completion()).await.unwrap();
2044        second.completion(test_completion()).await.unwrap();
2045
2046        assert_eq!(quota_calls.load(Ordering::Relaxed), 1);
2047    }
2048
2049    fn reasoning_item(text: &str) -> AssistantContent {
2050        AssistantContent::Reasoning(rig_core::completion::message::Reasoning::new(text))
2051    }
2052
2053    /// The block is never closed, so the scanner drops the verdict with the reasoning — but the
2054    /// reasoning is also reported structurally, so it can be subtracted exactly.
2055    #[test]
2056    fn unterminated_think_keeps_the_answer_and_drops_the_duplicated_reasoning() {
2057        let reasoning = "The debate is extremely brief. The Actor suggested `eyre`.";
2058        let response = response_with(vec![
2059            reasoning_item(reasoning),
2060            AssistantContent::text(format!(
2061                "<think>\n{reasoning}\n\n### Verdict\n**Agreed: use `eyre` for applications.**"
2062            )),
2063        ]);
2064        assert_eq!(
2065            response.text(),
2066            "### Verdict\n**Agreed: use `eyre` for applications.**"
2067        );
2068    }
2069
2070    /// Leading text hides the answer just as thoroughly, but makes the response read as
2071    /// successful — so nothing retries and the verdict is lost silently.
2072    #[test]
2073    fn unterminated_think_after_a_prefix_still_recovers_the_answer() {
2074        let reasoning = "Weighing both sides.";
2075        let response = response_with(vec![
2076            reasoning_item(reasoning),
2077            AssistantContent::text(format!(
2078                "Here is my review.\n<think>\n{reasoning}\n\n### Verdict\nShip it."
2079            )),
2080        ]);
2081        assert_eq!(
2082            response.text(),
2083            "Here is my review.\n\n### Verdict\nShip it."
2084        );
2085    }
2086
2087    /// OpenRouter splits `reasoning_details` mid-sentence, so a newline join stops the fragments
2088    /// matching their copy inside the block and the whole chain leaks into the answer.
2089    #[test]
2090    fn fragmented_reasoning_is_concatenated_without_separators() {
2091        let response = response_with(vec![
2092            reasoning_item("weighing the options"),
2093            reasoning_item(" carefully."),
2094            AssistantContent::text("<think>\nweighing the options carefully.\n\nVerdict: ship it."),
2095        ]);
2096        assert_eq!(response.text(), "Verdict: ship it.");
2097    }
2098
2099    /// With no structured reasoning there is no way to tell reasoning from answer. Returning the
2100    /// body would both serve chain-of-thought as the verdict and make the response read as
2101    /// non-empty, silencing the retry that exists for a reply that never answered.
2102    #[test]
2103    fn unterminated_think_without_structured_reasoning_stays_empty() {
2104        let response = response_with(vec![AssistantContent::text(
2105            "<think>\nweighing it up\n\nVerdict: ship it.",
2106        )]);
2107        assert!(response.text().is_empty());
2108    }
2109
2110    /// A summary is a paraphrase of the chain, not a slice of it, so it cannot be subtracted from
2111    /// the body — matching it as a fragment would leave a mangled prefix behind.
2112    #[test]
2113    fn summary_reasoning_is_not_used_to_split_the_body() {
2114        let response = response_with(vec![
2115            AssistantContent::Reasoning(rig_core::completion::message::Reasoning::summaries(vec![
2116                "brief".to_string(),
2117            ])),
2118            AssistantContent::text("<think>private chain"),
2119        ]);
2120        assert!(response.text().is_empty());
2121    }
2122
2123    /// A reasoning string that happens to be a byte prefix of the answer must not chop it: "Ver"
2124    /// against "Verdict: ship it." would otherwise yield "dict: ship it.".
2125    #[test]
2126    fn a_prefix_that_cuts_mid_word_is_not_treated_as_reasoning() {
2127        let response = response_with(vec![
2128            reasoning_item("Ver"),
2129            AssistantContent::text("<think>Verdict: ship it."),
2130        ]);
2131        assert!(response.text().is_empty());
2132    }
2133
2134    /// With several blocks, the one that stayed open is not the first tag in the text. Recovery
2135    /// keys off the scanner's offset, so an earlier *closed* block cannot misdirect it.
2136    #[test]
2137    fn recovery_targets_the_block_that_stayed_open() {
2138        let response = response_with(vec![
2139            reasoning_item("secret"),
2140            AssistantContent::text("<think>old</think>\n<think>secret\n\nFINAL"),
2141        ]);
2142        assert_eq!(response.text(), "FINAL");
2143    }
2144
2145    /// A stray closing tag at depth 0 is dropped by the scanner and must not be mistaken for the
2146    /// opener when recovering.
2147    #[test]
2148    fn a_stray_closing_tag_does_not_misdirect_recovery() {
2149        let response = response_with(vec![
2150            reasoning_item("secret"),
2151            AssistantContent::text("</think><think>secret\n\nFINAL"),
2152        ]);
2153        assert_eq!(response.text(), "FINAL");
2154    }
2155
2156    /// A response that is only reasoning still collapses to empty, so the empty-response retry
2157    /// keeps working for models that genuinely returned no answer.
2158    #[test]
2159    fn a_reasoning_only_response_is_still_empty() {
2160        let reasoning = "still thinking about it";
2161        let response = response_with(vec![
2162            reasoning_item(reasoning),
2163            AssistantContent::text(format!("<think>\n{reasoning}")),
2164        ]);
2165        assert!(response.text().is_empty());
2166        let closed = response_with(vec![AssistantContent::text(
2167            "<think>done deliberating</think>",
2168        )]);
2169        assert!(closed.text().is_empty());
2170    }
2171
2172    /// A well-formed closed block is untouched by the recovery path.
2173    #[test]
2174    fn closed_think_block_still_yields_only_the_answer() {
2175        let response = response_with(vec![AssistantContent::text(
2176            "<think>weighing it up</think>Verdict: ship it.",
2177        )]);
2178        assert_eq!(response.text(), "Verdict: ship it.");
2179    }
2180
2181    /// Mirrors rig's Anthropic mapping: `input_tokens` excludes the cache buckets and
2182    /// `total_tokens` is their sum plus output (`anthropic/completion.rs`).
2183    fn anthropic_usage(input: u64, output: u64, cached: u64, creation: u64) -> Usage {
2184        let mut usage = Usage::new();
2185        usage.input_tokens = input;
2186        usage.output_tokens = output;
2187        usage.cached_input_tokens = cached;
2188        usage.cache_creation_input_tokens = creation;
2189        usage.total_tokens = input + cached + creation + output;
2190        usage
2191    }
2192
2193    fn anthropic(usage: &Usage) -> TokenUsage {
2194        TokenUsage::from_provider(usage, CacheAccounting::OutsidePrompt)
2195    }
2196
2197    fn prompt_inclusive(usage: &Usage) -> TokenUsage {
2198        TokenUsage::from_provider(usage, CacheAccounting::InsidePrompt)
2199    }
2200
2201    /// The same 3508-token prompt served from cache, as each provider reports it: Anthropic shows
2202    /// `input_tokens: 52` with the rest under `cache_read`, OpenAI shows the whole prompt. Both
2203    /// must meter identically, or a mixed-provider run sums numbers that mean different things —
2204    /// and the Anthropic shape read raw is what hid 98% of the prompt.
2205    #[test]
2206    fn provider_shapes_meter_a_cache_hit_identically() {
2207        let from_anthropic = anthropic(&anthropic_usage(52, 8, 3456, 0));
2208        let mut openai = Usage::new();
2209        openai.input_tokens = 3508;
2210        openai.output_tokens = 8;
2211        openai.cached_input_tokens = 3456;
2212        openai.total_tokens = 3516;
2213        let from_openai = prompt_inclusive(&openai);
2214
2215        assert_eq!(from_anthropic.input_tokens, 3508);
2216        assert_eq!(from_anthropic.input_tokens, from_openai.input_tokens);
2217        assert_eq!(
2218            from_anthropic.cached_input_tokens,
2219            from_openai.cached_input_tokens
2220        );
2221        for usage in [from_anthropic, from_openai] {
2222            assert_eq!(usage.total_tokens, usage.input_tokens + usage.output_tokens);
2223        }
2224    }
2225
2226    /// Gemini reports thinking and tool-use prompts beside both `input_tokens` and
2227    /// `output_tokens`, and its parts don't sum to its total — so no arithmetic can tell its shape
2228    /// apart from Anthropic's. Numbers are rig's own fixture (`gemini/completion.rs`) with the
2229    /// cache lowered to 8, the value that makes the buckets *look* like they fit outside the
2230    /// prompt. Charging them would report a 40-token prompt as 48.
2231    #[test]
2232    fn gemini_cache_reads_are_never_added_to_its_prompt() {
2233        let mut usage = Usage::new();
2234        usage.input_tokens = 40;
2235        usage.output_tokens = 30;
2236        usage.reasoning_tokens = 10;
2237        usage.tool_use_prompt_tokens = 12;
2238        usage.cached_input_tokens = 8;
2239        usage.total_tokens = 100;
2240        let usage = prompt_inclusive(&usage);
2241        assert_eq!(usage.input_tokens, 40);
2242        assert_eq!(usage.cached_input_tokens, 8);
2243    }
2244
2245    /// An OpenRouter gateway may report a total larger than prompt + completion. That slack must
2246    /// not turn its cache reads — already inside `prompt_tokens` — into extra prompt tokens.
2247    #[test]
2248    fn openrouter_total_disagreement_does_not_inflate_the_prompt() {
2249        let mut usage = Usage::new();
2250        usage.input_tokens = 500;
2251        usage.output_tokens = 10;
2252        usage.cached_input_tokens = 5;
2253        usage.total_tokens = 515;
2254        let usage = prompt_inclusive(&usage);
2255        assert_eq!(usage.input_tokens, 500);
2256        assert_eq!(usage.total_tokens, 510);
2257    }
2258
2259    /// A gateway that omits usage totals must still meter the prompt it reported.
2260    #[test]
2261    fn missing_provider_total_still_meters_reported_input() {
2262        let mut usage = Usage::new();
2263        usage.input_tokens = 1200;
2264        usage.output_tokens = 40;
2265        let usage = prompt_inclusive(&usage);
2266        assert_eq!(usage.input_tokens, 1200);
2267        assert_eq!(usage.total_tokens, 1240);
2268    }
2269
2270    /// Anthropic charges a cache *write* too, and reports it outside `input_tokens` like a read.
2271    #[test]
2272    fn anthropic_cache_writes_count_toward_the_prompt() {
2273        let usage = anthropic(&anthropic_usage(90, 10, 0, 4100));
2274        assert_eq!(usage.cache_creation_input_tokens, 4100);
2275        assert_eq!(usage.input_tokens, 4190);
2276        assert_eq!(usage.total_tokens, 4200);
2277    }
2278
2279    /// A provider reporting more cache than prompt is contradicting itself. Reporting the prompt
2280    /// as 5000 to make the breakdown fit would invent 4990 tokens of spend that were never billed,
2281    /// so both numbers are passed through as reported and the contradiction stays visible.
2282    #[test]
2283    fn contradictory_cache_metadata_is_not_papered_over() {
2284        let mut usage = Usage::new();
2285        usage.input_tokens = 10;
2286        usage.output_tokens = 5;
2287        usage.total_tokens = 15;
2288        usage.cached_input_tokens = 5_000;
2289        usage.cache_creation_input_tokens = 700;
2290        let usage = prompt_inclusive(&usage);
2291        assert_eq!(usage.input_tokens, 10);
2292        assert_eq!(usage.total_tokens, 15);
2293        assert_eq!(usage.cached_input_tokens, 5_000);
2294        assert_eq!(usage.cache_creation_input_tokens, 700);
2295    }
2296
2297    /// The whole point of the normalization: a cache hit must still trip the compaction
2298    /// threshold, since the full prompt is what gets re-sent next turn.
2299    #[test]
2300    fn compaction_threshold_sees_the_cached_prompt() {
2301        let mut window = ConversationUsageWindow::new(Some(3_000));
2302        window.record(anthropic(&anthropic_usage(52, 8, 3456, 0)));
2303        assert!(window.should_compact());
2304    }
2305
2306    /// The cache fields are `#[serde(default)]` so trajectories written before they existed
2307    /// still decode.
2308    #[test]
2309    fn usage_without_cache_fields_still_deserializes() {
2310        let usage: TokenUsage = serde_json::from_value(
2311            json!({"input_tokens": 10, "output_tokens": 2, "total_tokens": 12}),
2312        )
2313        .expect("legacy usage payload must decode");
2314        assert_eq!(usage.input_tokens, 10);
2315        assert_eq!(usage.cached_input_tokens, 0);
2316    }
2317
2318    fn provider_error(status: Option<u16>, body: &str) -> eyre::Report {
2319        let error = match status {
2320            Some(status) => CompletionError::from_http_response(
2321                reqwest::StatusCode::from_u16(status).unwrap(),
2322                body,
2323            ),
2324            None => CompletionError::from_provider_body(body),
2325        };
2326        eyre::Report::new(error).wrap_err("completion failed for model 'test'")
2327    }
2328
2329    fn gemini_completion(max_tokens: Option<u64>, additional_params: Option<Value>) -> Completion {
2330        Completion {
2331            model: "gemini-3-pro".to_string(),
2332            prompt: Message::user("hi".to_string()),
2333            preamble: None,
2334            history: Vec::new(),
2335            tools: Vec::new(),
2336            tool_choice: None,
2337            max_tokens,
2338            additional_params,
2339        }
2340    }
2341
2342    #[test]
2343    fn merge_json_is_deep_and_extra_wins() {
2344        // nested objects merge recursively; scalar conflicts resolve to `extra`.
2345        let merged = merge_json(
2346            json!({"generation_config": {"temperature": 0.2}, "a": 1}),
2347            json!({"generation_config": {"max_output_tokens": 50}, "a": 2}),
2348        );
2349        assert_eq!(
2350            merged,
2351            json!({"generation_config": {"temperature": 0.2, "max_output_tokens": 50}, "a": 2})
2352        );
2353    }
2354
2355    #[test]
2356    fn gemini_params_preserve_caller_config() {
2357        // A caller's safety settings and nested generation_config must survive the computed overlay.
2358        let params = build_gemini_additional_params(&gemini_completion(
2359            Some(50),
2360            Some(json!({
2361                "generation_config": {"temperature": 0.2},
2362                "safetySettings": [{"category": "HARM", "threshold": "NONE"}]
2363            })),
2364        ))
2365        .unwrap();
2366        assert_eq!(
2367            params,
2368            json!({
2369                "generation_config": {"temperature": 0.2, "max_output_tokens": 50},
2370                "safetySettings": [{"category": "HARM", "threshold": "NONE"}]
2371            })
2372        );
2373    }
2374
2375    #[test]
2376    fn gemini_params_none_yields_generation_config_only() {
2377        let params = build_gemini_additional_params(&gemini_completion(Some(50), None)).unwrap();
2378        assert_eq!(
2379            params,
2380            json!({"generation_config": {"max_output_tokens": 50}})
2381        );
2382    }
2383
2384    #[test]
2385    fn strips_full_think_block() {
2386        let raw = "<think>let me reason about this</think>\n\nThe bug is in foo().";
2387        assert_eq!(strip_think_blocks(raw), "The bug is in foo().");
2388    }
2389
2390    #[test]
2391    fn strips_stray_empty_think_tags() {
2392        // OpenRouter hoists MiniMax's reasoning into a separate field but leaves the tags.
2393        let raw = "<think></think>\n## Findings\n- looks fine";
2394        assert_eq!(strip_think_blocks(raw), "## Findings\n- looks fine");
2395    }
2396
2397    #[test]
2398    fn strips_unbalanced_and_multiline_think() {
2399        let raw = "intro\n<think>\nstep 1\nstep 2\n</think>verdict: ok</think>";
2400        assert_eq!(strip_think_blocks(raw), "intro\nverdict: ok");
2401    }
2402
2403    #[test]
2404    fn leaves_non_think_text_untouched() {
2405        let raw = "no reasoning tags here, just review text";
2406        assert_eq!(strip_think_blocks(raw), raw);
2407    }
2408
2409    #[test]
2410    fn strips_unterminated_think_to_eof() {
2411        // a streamed/truncated block with no closing tag must not leak its body.
2412        let raw = "answer first\n<think>reasoning that never closes\nstep 2";
2413        assert_eq!(strip_think_blocks(raw), "answer first");
2414    }
2415
2416    #[test]
2417    fn all_reasoning_collapses_to_empty() {
2418        // an all-think response (incl. the multi-block join) must be empty so the
2419        // agent loop's is_empty() nudge path fires instead of returning "\n".
2420        let joined = format!("{}\n{}", "<think>round one</think>", "<think>round two");
2421        assert_eq!(strip_think_blocks(&joined), "");
2422    }
2423
2424    #[test]
2425    fn response_text_collapses_whitespace_only_content_to_empty() {
2426        let response = response_with(vec![AssistantContent::text(" \n\t ")]);
2427        assert!(response.text().is_empty());
2428    }
2429
2430    #[test]
2431    fn strips_nested_think_blocks() {
2432        // a single non-greedy regex stops at the first </think> and leaks the tail; the
2433        // depth-tracking scanner must drop the whole balanced span.
2434        let raw = "<think>outer <think>inner</think> still hidden</think>answer";
2435        assert_eq!(strip_think_blocks(raw), "answer");
2436    }
2437
2438    #[test]
2439    fn strips_whitespace_padded_think_tags() {
2440        // `<think >` must be recognized as an open tag, not leaked as content.
2441        let raw = "<think >hidden</think >visible";
2442        assert_eq!(strip_think_blocks(raw), "visible");
2443    }
2444
2445    #[test]
2446    fn leaves_thinking_word_untouched() {
2447        // `<thinking>` is a different tag — the char after `think` must be ws or `>`.
2448        let raw = "see <thinking>kept</thinking> here";
2449        assert_eq!(
2450            strip_think_blocks(raw),
2451            "see <thinking>kept</thinking> here"
2452        );
2453    }
2454
2455    #[test]
2456    fn classifiers_use_captured_http_status() {
2457        let unauthorized = provider_error(Some(401), r#"{"message":"Unauthorized"}"#);
2458        assert!(!unauthorized.to_string().contains("401"));
2459        assert_eq!(provider_http_status(&unauthorized), Some(401));
2460        assert!(is_non_retryable_client_error(&unauthorized));
2461
2462        let throttled = provider_error(Some(429), r#"{"message":"slow down"}"#);
2463        assert!(is_rate_limit_error(&throttled));
2464        assert_eq!(
2465            retry_policy(&throttled).max_attempts,
2466            RATE_LIMIT_MAX_COMPLETION_ATTEMPTS
2467        );
2468
2469        let server = provider_error(Some(503), r#"{"message":"unavailable"}"#);
2470        assert_eq!(
2471            classify_provider_failure(&server),
2472            ProviderFailureClass::Server
2473        );
2474        assert_eq!(retry_policy(&server).max_attempts, MAX_COMPLETION_ATTEMPTS);
2475    }
2476
2477    #[test]
2478    fn exact_quota_codes_skip_same_route_retries() {
2479        for code in PERMANENT_QUOTA_ERROR_CODES {
2480            let body = format!(r#"{{"error":{{"code":"{code}"}}}}"#);
2481            let err = provider_error(Some(429), &body);
2482            assert!(is_long_window_quota_error(&err), "{code}");
2483            assert!(!is_rate_limit_error(&err), "{code}");
2484            assert!(!retry_policy(&err).retry, "{code}");
2485            assert!(is_sticky_fallback_error(&err), "{code}");
2486        }
2487    }
2488
2489    #[test]
2490    fn structured_kimi_quota_messages_are_the_narrow_compatibility_fallback() {
2491        for (status, message) in [
2492            (429, "out of tokens per 5h window; reset in 2h"),
2493            (429, "You've hit your usage limit"),
2494            (
2495                403,
2496                "You've reached your usage limit for this billing cycle. Your quota will be refreshed in the next cycle.",
2497            ),
2498        ] {
2499            let body = json!({"error": {"type": "access_terminated_error", "message": message}});
2500            let err = provider_error(Some(status), &body.to_string());
2501            assert!(is_long_window_quota_error(&err), "{message}");
2502            assert!(!retry_policy(&err).retry, "{message}");
2503        }
2504
2505        // Diagnostic text outside a structured provider body is deliberately ignored.
2506        let untyped = eyre::eyre!("insufficient_quota: out of tokens per 5h window");
2507        assert_eq!(
2508            classify_provider_failure(&untyped),
2509            ProviderFailureClass::Unknown
2510        );
2511        assert_eq!(retry_policy(&untyped).max_attempts, MAX_COMPLETION_ATTEMPTS);
2512    }
2513
2514    #[test]
2515    fn real_5xx_status_precedes_nested_quota_and_rate_codes() {
2516        for status in (500..600).filter(|&status| status != 529) {
2517            for body in [
2518                r#"{"upstream":{"error":{"code":"insufficient_quota","message":"out of tokens per 5h window"}}}"#,
2519                r#"{"upstream":{"error":{"type":"overloaded_error"}}}"#,
2520            ] {
2521                let err = provider_error(Some(status), body);
2522                assert_eq!(
2523                    classify_provider_failure(&err),
2524                    ProviderFailureClass::Server
2525                );
2526                let policy = retry_policy(&err);
2527                assert!(policy.retry);
2528                assert_eq!(policy.max_attempts, MAX_COMPLETION_ATTEMPTS);
2529                assert!(!is_sticky_fallback_error(&err));
2530            }
2531        }
2532    }
2533
2534    #[test]
2535    fn anthropic_529_overload_uses_the_long_overload_policy() {
2536        let err = provider_error(
2537            Some(529),
2538            r#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#,
2539        );
2540
2541        assert_eq!(
2542            classify_provider_failure(&err),
2543            ProviderFailureClass::RateLimit
2544        );
2545        let policy = retry_policy(&err);
2546        assert!(policy.retry);
2547        assert_eq!(policy.max_attempts, RATE_LIMIT_MAX_COMPLETION_ATTEMPTS);
2548        assert_eq!(policy.base_backoff_ms, RATE_LIMIT_BASE_BACKOFF_MS);
2549        assert!(is_sticky_fallback_error(&err));
2550    }
2551
2552    #[test]
2553    fn exact_provider_codes_classify_without_http_status() {
2554        for code in [
2555            "authentication_error",
2556            "invalid_api_key",
2557            "permission_error",
2558        ] {
2559            let body = format!(r#"{{"error":{{"type":"{code}"}}}}"#);
2560            let err = provider_error(None, &body);
2561            assert!(is_non_retryable_client_error(&err), "{code}");
2562        }
2563
2564        for code in RATE_LIMIT_ERROR_CODES {
2565            let body = format!(r#"{{"error":{{"code":"{code}"}}}}"#);
2566            let err = provider_error(None, &body);
2567            assert!(is_rate_limit_error(&err), "{code}");
2568        }
2569    }
2570
2571    #[test]
2572    fn context_length_uses_exact_code_and_structured_message() {
2573        let openai = provider_error(Some(400), r#"{"error":{"code":"context_length_exceeded"}}"#);
2574        assert!(is_context_length_error(&openai));
2575
2576        let anthropic = provider_error(
2577            Some(400),
2578            r#"{"error":{"type":"invalid_request_error","message":"prompt is too long"}}"#,
2579        );
2580        assert!(is_context_length_error(&anthropic));
2581
2582        let malformed = provider_error(
2583            Some(400),
2584            r#"{"error":{"type":"invalid_request_error","message":"tools[0] is invalid"}}"#,
2585        );
2586        assert!(!is_context_length_error(&malformed));
2587        assert!(is_non_retryable_client_error(&malformed));
2588    }
2589
2590    #[test]
2591    fn provider_json_status_hint_handles_success_error_envelopes() {
2592        let err = provider_error(
2593            Some(200),
2594            r#"{"error":{"code":429,"type":"rate_limit_error","message":"slow down"}}"#,
2595        );
2596        assert_eq!(provider_http_status(&err), Some(429));
2597        assert!(is_rate_limit_error(&err));
2598    }
2599
2600    #[test]
2601    fn text_provider_body_only_uses_the_quota_message_fallback() {
2602        for status in [403, 429] {
2603            let err = provider_error(
2604                Some(status),
2605                "You've reached your usage limit for this billing cycle; refresh in the next cycle",
2606            );
2607            assert!(is_long_window_quota_error(&err));
2608            assert!(!retry_policy(&err).retry);
2609            assert!(is_sticky_fallback_error(&err));
2610        }
2611
2612        let err = provider_error(Some(429), "insufficient_quota in a non-JSON response");
2613        // Arbitrary body text is not scanned for codes; the captured 429 still classifies.
2614        assert!(is_rate_limit_error(&err));
2615
2616        let statusless = provider_error(None, "insufficient_quota in a non-JSON response");
2617        assert_eq!(
2618            classify_provider_failure(&statusless),
2619            ProviderFailureClass::Unknown
2620        );
2621        assert!(!is_sticky_fallback_error(&statusless));
2622    }
2623
2624    #[test]
2625    fn top_level_status_hint_precedes_nested_numeric_codes() {
2626        let err = provider_error(
2627            Some(200),
2628            r#"{"statusCode":502,"upstream":{"error":{"code":403,"type":"insufficient_quota"}}}"#,
2629        );
2630        assert_eq!(provider_http_status(&err), Some(502));
2631        assert_eq!(
2632            classify_provider_failure(&err),
2633            ProviderFailureClass::Server
2634        );
2635        assert!(!is_sticky_fallback_error(&err));
2636    }
2637
2638    #[test]
2639    fn compact_provider_error_body_keeps_large_json_classifiable() {
2640        let body = json!({
2641            "error": {
2642                "type": "usage_limit_reached",
2643                "message": "quota exhausted",
2644                "diagnostic": "x".repeat(4_000),
2645            }
2646        })
2647        .to_string();
2648        let compact = compact_provider_error_body(&body, 1_000);
2649        serde_json::from_str::<Value>(&compact).expect("compacted provider body stays valid JSON");
2650        let err = provider_error(Some(429), &compact);
2651        assert!(is_long_window_quota_error(&err));
2652    }
2653
2654    #[test]
2655    fn provider_error_truncation_reuses_utf8_boundary_handling() {
2656        assert_eq!(truncate_utf8("aéz", 2), "a…");
2657    }
2658
2659    #[test]
2660    fn openrouter_normalization_preserves_typed_provider_source() {
2661        let err = normalize_openrouter_completion_error(CompletionError::from_http_response(
2662            reqwest::StatusCode::TOO_MANY_REQUESTS,
2663            r#"{"error":{"type":"insufficient_quota"}}"#,
2664        ));
2665        assert_eq!(provider_http_status(&err), Some(429));
2666        assert!(is_long_window_quota_error(&err));
2667    }
2668
2669    fn tool_call_content() -> AssistantContent {
2670        use rig_core::completion::message::ToolFunction;
2671        AssistantContent::ToolCall(ToolCall::new(
2672            "call-1".to_string(),
2673            ToolFunction::new("read_file".to_string(), serde_json::json!({ "path": "x" })),
2674        ))
2675    }
2676
2677    /// Providers can pair tool calls with `stop`-like wire reasons; `tool_calls()` only
2678    /// surfaces calls under `ToolUse`, so the override losing would silently end the agent loop.
2679    #[test]
2680    fn a_structured_tool_call_overrides_any_wire_finish_reason() {
2681        let alone = OneOrMany::one(tool_call_content());
2682        let beside_text = OneOrMany::many(vec![
2683            AssistantContent::text("narration before the call"),
2684            tool_call_content(),
2685        ])
2686        .expect("two items");
2687        for choice in [alone, beside_text] {
2688            for wire in [
2689                FinishReason::Stop,
2690                FinishReason::MaxTokens,
2691                FinishReason::None,
2692                FinishReason::Other("length_capped".to_string()),
2693            ] {
2694                assert_eq!(resolve_finish_reason(&choice, wire), FinishReason::ToolUse);
2695            }
2696        }
2697    }
2698
2699    #[test]
2700    fn without_tool_calls_the_wire_finish_reason_stands() {
2701        let choice = OneOrMany::one(AssistantContent::text("done"));
2702        for wire in [
2703            FinishReason::Stop,
2704            FinishReason::MaxTokens,
2705            FinishReason::None,
2706            FinishReason::Other("content_filter".to_string()),
2707        ] {
2708            assert_eq!(resolve_finish_reason(&choice, wire.clone()), wire);
2709        }
2710    }
2711}