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                // First-party Anthropic supports cache_control. An arbitrary compatible gateway
1216                // may reject that field, so custom base URLs keep the legacy request shape unless
1217                // they are constructed explicitly as an AnthropicPromptCachingClient.
1218                let enable_prompt_caching = base_url.is_none();
1219                let key_env = api_key_env.as_deref().unwrap_or("ANTHROPIC_API_KEY");
1220                let api_key = std::env::var(key_env)
1221                    .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
1222                let mut builder = anthropic::Client::builder().api_key(api_key);
1223                if let Some(url) = base_url {
1224                    builder = builder.base_url(url);
1225                }
1226                let client = builder.build()?;
1227                match enable_prompt_caching {
1228                    true => Ok(Box::new(AnthropicPromptCachingClient::new(client))),
1229                    false => Ok(Box::new(client)),
1230                }
1231            }
1232            LLMProvider::Gemini {
1233                base_url,
1234                api_key_env,
1235            } => {
1236                // An explicit api_key_env overrides the GEMINI_API_KEY → GOOGLE_AI_API_KEY default
1237                // chain; a local base_url needs no key (mirrors the Anthropic/OpenAi arms).
1238                let api_key = match api_key_env {
1239                    Some(key_env) => std::env::var(key_env)
1240                        .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?,
1241                    None => std::env::var("GEMINI_API_KEY")
1242                        .or_else(|_| std::env::var("GOOGLE_AI_API_KEY"))
1243                        .or_else(|_| {
1244                            missing_or_local(
1245                                "GEMINI_API_KEY (or GOOGLE_AI_API_KEY)",
1246                                base_url.as_deref(),
1247                            )
1248                        })?,
1249                };
1250                let mut builder = gemini::Client::builder().api_key(api_key);
1251                if let Some(url) = base_url {
1252                    builder = builder.base_url(url);
1253                }
1254                let client = builder
1255                    .build()
1256                    .map_err(|e| eyre::eyre!("failed to create Gemini client: {e}"))?;
1257                Ok(Box::new(client))
1258            }
1259            LLMProvider::OpenAi {
1260                base_url,
1261                api_key_env,
1262            } => {
1263                let key_env = api_key_env.as_deref().unwrap_or("OPENAI_API_KEY");
1264                let api_key = std::env::var(key_env)
1265                    .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
1266                let mut builder = openai::CompletionsClient::builder().api_key(&api_key);
1267                if let Some(url) = base_url {
1268                    builder = builder.base_url(url);
1269                }
1270                Ok(Box::new(builder.build()?))
1271            }
1272            LLMProvider::OpenRouter { api_key_env } => {
1273                let api_key = std::env::var(api_key_env)
1274                    .map_err(|_| eyre::eyre!("missing env var {api_key_env}"))?;
1275                let client = openrouter::Client::builder()
1276                    .api_key(&api_key)
1277                    .http_headers(openrouter_headers()?)
1278                    .build()?;
1279                Ok(Box::new(client))
1280            }
1281        }
1282    }
1283}
1284
1285pub fn openrouter_headers() -> Result<reqwest::header::HeaderMap> {
1286    let mut headers = reqwest::header::HeaderMap::new();
1287    headers.insert(
1288        "HTTP-Referer",
1289        "https://github.com/arsenyinfo/nitpicker".parse()?,
1290    );
1291    headers.insert("X-OpenRouter-Title", "nitpicker".parse()?);
1292    headers.insert(
1293        "X-OpenRouter-Categories",
1294        "cli-agent,programming-app".parse()?,
1295    );
1296    Ok(headers)
1297}
1298
1299impl LLMClient for openrouter::Client {
1300    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
1301        let model_name = completion.model.clone();
1302        let mut request: rig_core::completion::CompletionRequest = completion.into();
1303        request.model = Some(model_name.clone());
1304        let model = self.completion_model(&model_name);
1305        let response = model
1306            .completion(request)
1307            .await
1308            .map_err(normalize_openrouter_completion_error)
1309            .wrap_err_with(|| format!("OpenRouter completion failed for model '{model_name}'"))?;
1310        let finish_reason = response
1311            .raw_response
1312            .choices
1313            .first()
1314            .and_then(|c| c.finish_reason.as_deref())
1315            .map(|reason| match reason {
1316                "stop" => FinishReason::Stop,
1317                "length" => FinishReason::MaxTokens,
1318                "tool_calls" => FinishReason::ToolUse,
1319                other => FinishReason::Other(other.to_string()),
1320            })
1321            .unwrap_or(FinishReason::None);
1322        let finish_reason = resolve_finish_reason(&response.choice, finish_reason);
1323        Ok(CompletionResponse {
1324            choice: response.choice,
1325            finish_reason,
1326            usage: TokenUsage::from_provider(&response.usage, CacheAccounting::InsidePrompt),
1327            selected_model: Some(model_name),
1328        })
1329    }
1330}
1331
1332/// Create a Gemini client that routes through the local OAuth proxy
1333#[cfg(feature = "antigravity")]
1334pub fn create_gemini_client_with_proxy(
1335    proxy_url: &str,
1336) -> Result<std::sync::Arc<dyn LLMClientDyn>> {
1337    // Build a Gemini client with the proxy URL as the base URL
1338    // The API key doesn't matter for OAuth proxy, but is required by the builder
1339    let api_key = std::env::var("GEMINI_API_KEY").unwrap_or_else(|_| "oauth-proxy".to_string());
1340    let client = gemini::Client::builder()
1341        .api_key(api_key)
1342        .base_url(proxy_url)
1343        .build()?;
1344    Ok(client.with_retry().into_arc())
1345}
1346
1347/// Anthropic client policy used by first-party and Foundry routes. Rig's typed caching modes add
1348/// stable tools/system breakpoints plus a moving top-level conversation breakpoint.
1349pub(crate) struct AnthropicPromptCachingClient {
1350    inner: anthropic::Client,
1351}
1352
1353impl AnthropicPromptCachingClient {
1354    pub(crate) fn new(inner: anthropic::Client) -> Self {
1355        Self { inner }
1356    }
1357}
1358
1359async fn complete_anthropic(
1360    client: &anthropic::Client,
1361    completion: Completion,
1362    prompt_caching: bool,
1363) -> Result<CompletionResponse> {
1364    let model_name = completion.model.clone();
1365    let mut request: rig_core::completion::CompletionRequest = completion.into();
1366    request.model = Some(model_name.clone());
1367    // Anthropic requires `max_tokens`, so "no cap" cannot be expressed here. rig's own default
1368    // covers only model names it recognizes and falls back to 2048 for every compatible gateway —
1369    // less than one review turn spends on reasoning.
1370    request
1371        .max_tokens
1372        .get_or_insert(ANTHROPIC_DEFAULT_MAX_TOKENS);
1373    let mut model = client.completion_model(model_name.clone());
1374    if prompt_caching {
1375        model = model.with_prompt_caching().with_automatic_caching();
1376    }
1377    let response = model
1378        .completion(request)
1379        .await
1380        .wrap_err_with(|| format!("Anthropic completion failed for model '{model_name}'"))?;
1381    let finish_reason = response
1382        .raw_response
1383        .stop_reason
1384        .clone()
1385        .map(|reason| match reason.as_str() {
1386            "end_turn" => FinishReason::Stop,
1387            "max_tokens" => FinishReason::MaxTokens,
1388            "tool_use" => FinishReason::ToolUse,
1389            other => FinishReason::Other(other.to_string()),
1390        })
1391        .unwrap_or(FinishReason::None);
1392    let finish_reason = resolve_finish_reason(&response.choice, finish_reason);
1393    Ok(CompletionResponse {
1394        choice: response.choice,
1395        finish_reason,
1396        usage: TokenUsage::from_provider(&response.usage, CacheAccounting::OutsidePrompt),
1397        selected_model: Some(model_name),
1398    })
1399}
1400
1401impl LLMClient for anthropic::Client {
1402    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
1403        complete_anthropic(self, completion, false).await
1404    }
1405}
1406
1407impl LLMClient for AnthropicPromptCachingClient {
1408    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
1409        complete_anthropic(&self.inner, completion, true).await
1410    }
1411}
1412
1413impl LLMClient for gemini::Client {
1414    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
1415        let model_name = completion.model.clone();
1416        let params = build_gemini_additional_params(&completion)?;
1417        let mut request: rig_core::completion::CompletionRequest = completion.into();
1418        request.model = Some(model_name.clone());
1419        request.additional_params = Some(params);
1420        let model = self.completion_model(model_name.clone());
1421        let response = model
1422            .completion(request)
1423            .await
1424            .wrap_err_with(|| format!("Gemini completion failed for model '{model_name}'"))?;
1425        let finish_reason = response
1426            .raw_response
1427            .candidates
1428            .first()
1429            .and_then(|candidate| candidate.finish_reason.clone())
1430            .map(map_gemini_finish_reason)
1431            .unwrap_or(FinishReason::None);
1432        let finish_reason = resolve_finish_reason(&response.choice, finish_reason);
1433        Ok(CompletionResponse {
1434            choice: response.choice,
1435            finish_reason,
1436            usage: TokenUsage::from_provider(&response.usage, CacheAccounting::InsidePrompt),
1437            selected_model: Some(model_name),
1438        })
1439    }
1440}
1441
1442fn model_needs_max_completion_tokens(model: &str) -> bool {
1443    model.starts_with("o1")
1444        || model.starts_with("o3")
1445        || model.starts_with("o4")
1446        || model.starts_with("gpt-4o")
1447        || model.starts_with("gpt-4.1")
1448        || model.starts_with("gpt-4.5")
1449        || model.starts_with("gpt-5")
1450}
1451
1452/// Deep-merge `extra` over `base`: nested objects are merged recursively; on a scalar/type
1453/// conflict `extra` wins. Used to overlay computed request params without discarding caller-set
1454/// ones (e.g. a Gemini `generation_config` the caller supplied alongside its own keys).
1455pub(crate) fn merge_json(base: Value, extra: Value) -> Value {
1456    match (base, extra) {
1457        (Value::Object(mut base_obj), Value::Object(extra_obj)) => {
1458            for (k, v) in extra_obj {
1459                let merged = match base_obj.remove(&k) {
1460                    Some(existing) => merge_json(existing, v),
1461                    None => v,
1462                };
1463                base_obj.insert(k, merged);
1464            }
1465            Value::Object(base_obj)
1466        }
1467        (_, extra) => extra,
1468    }
1469}
1470
1471impl LLMClient for openai::CompletionsClient {
1472    async fn completion(&self, mut completion: Completion) -> Result<CompletionResponse> {
1473        // Newer OpenAI models (o1, o3, o4-mini, gpt-4o, gpt-5, etc.) reject the legacy
1474        // `max_tokens` param and require `max_completion_tokens` instead. Since rig always
1475        // serializes `max_tokens`, we move the value into `additional_params` and clear it.
1476        if let Some(max) = completion.max_tokens {
1477            if model_needs_max_completion_tokens(&completion.model) {
1478                let extra = serde_json::json!({ "max_completion_tokens": max });
1479                completion.additional_params = Some(match completion.additional_params.take() {
1480                    Some(existing) => merge_json(existing, extra),
1481                    None => extra,
1482                });
1483                completion.max_tokens = None;
1484            }
1485        }
1486        let model_name = completion.model.clone();
1487        let mut request: rig_core::completion::CompletionRequest = completion.into();
1488        request.model = Some(model_name.clone());
1489        let model = self.completion_model(model_name.clone());
1490        let response = model
1491            .completion(request)
1492            .await
1493            .wrap_err_with(|| format!("OpenAI completion failed for model '{model_name}'"))?;
1494        let finish_reason = response
1495            .raw_response
1496            .choices
1497            .first()
1498            .map(|choice| match choice.finish_reason.as_str() {
1499                "stop" => FinishReason::Stop,
1500                "length" => FinishReason::MaxTokens,
1501                "tool_calls" => FinishReason::ToolUse,
1502                other => FinishReason::Other(other.to_string()),
1503            })
1504            .unwrap_or(FinishReason::None);
1505        let finish_reason = resolve_finish_reason(&response.choice, finish_reason);
1506        Ok(CompletionResponse {
1507            choice: response.choice,
1508            finish_reason,
1509            usage: TokenUsage::from_provider(&response.usage, CacheAccounting::InsidePrompt),
1510            selected_model: Some(model_name),
1511        })
1512    }
1513}
1514
1515#[derive(Debug, Serialize)]
1516struct GeminiAdditionalParams {
1517    generation_config: Option<GenerationConfig>,
1518}
1519
1520impl GeminiAdditionalParams {
1521    fn from_completion(completion: &Completion) -> Self {
1522        let config = GenerationConfig {
1523            // saturating: `as i32` would turn a cap past i32::MAX into a negative field
1524            max_output_tokens: completion
1525                .max_tokens
1526                .map(|value| i32::try_from(value).unwrap_or(i32::MAX)),
1527        };
1528        Self {
1529            generation_config: Some(config),
1530        }
1531    }
1532}
1533
1534/// Overlay the computed generation config onto any caller-supplied `additional_params` instead of
1535/// replacing them, mirroring the OpenAI path's `merge_json`. The computed value wins on conflict
1536/// (e.g. the typed `max_tokens`), while caller keys like safety settings or a nested
1537/// `generation_config.temperature` survive.
1538fn build_gemini_additional_params(completion: &Completion) -> Result<Value> {
1539    let computed = serde_json::to_value(GeminiAdditionalParams::from_completion(completion))?;
1540    Ok(match &completion.additional_params {
1541        Some(existing) => merge_json(existing.clone(), computed),
1542        None => computed,
1543    })
1544}
1545
1546#[derive(Debug, Serialize, Default)]
1547struct GenerationConfig {
1548    #[serde(skip_serializing_if = "Option::is_none")]
1549    max_output_tokens: Option<i32>,
1550}
1551
1552/// A structured tool call in the choice overrides the wire finish reason: providers can pair
1553/// tool calls with `stop`-like reasons, and `CompletionResponse::tool_calls()` only surfaces
1554/// calls when the reason is `ToolUse`.
1555fn resolve_finish_reason(
1556    choice: &OneOrMany<AssistantContent>,
1557    wire_reason: FinishReason,
1558) -> FinishReason {
1559    match choice
1560        .iter()
1561        .any(|content| matches!(content, AssistantContent::ToolCall(_)))
1562    {
1563        true => FinishReason::ToolUse,
1564        false => wire_reason,
1565    }
1566}
1567
1568fn map_gemini_finish_reason(
1569    reason: gemini::completion::gemini_api_types::FinishReason,
1570) -> FinishReason {
1571    use gemini::completion::gemini_api_types::FinishReason as GeminiFinishReason;
1572    match reason {
1573        GeminiFinishReason::Stop => FinishReason::Stop,
1574        GeminiFinishReason::MaxTokens => FinishReason::MaxTokens,
1575        GeminiFinishReason::FinishReasonUnspecified => FinishReason::None,
1576        other => FinishReason::Other(format!("{other:?}")),
1577    }
1578}
1579
1580#[cfg(test)]
1581mod tests {
1582    use super::*;
1583    use rig_core::completion::Usage;
1584    use std::sync::Mutex as StdMutex;
1585    use tokio::io::{AsyncReadExt, AsyncWriteExt};
1586    use tokio::net::TcpListener;
1587
1588    fn strip_think_blocks(text: &str) -> String {
1589        scan_think_blocks(text).0
1590    }
1591    use serde_json::json;
1592
1593    fn response_with(choice: Vec<AssistantContent>) -> CompletionResponse {
1594        CompletionResponse {
1595            choice: OneOrMany::many(choice).expect("non-empty choice"),
1596            finish_reason: FinishReason::Stop,
1597            usage: TokenUsage::default(),
1598            selected_model: None,
1599        }
1600    }
1601
1602    struct RecordingClient {
1603        fail: bool,
1604        calls: Arc<StdMutex<Vec<Completion>>>,
1605    }
1606
1607    impl LLMClient for RecordingClient {
1608        async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
1609            self.calls.lock().unwrap().push(completion);
1610            if self.fail {
1611                eyre::bail!("route failed");
1612            }
1613            Ok(response_with(vec![AssistantContent::text("ok")]))
1614        }
1615    }
1616
1617    fn recording_slot(
1618        model: &str,
1619        max_tokens: Option<u64>,
1620        fail: bool,
1621    ) -> (FallbackSlot, Arc<StdMutex<Vec<Completion>>>) {
1622        let calls = Arc::new(StdMutex::new(Vec::new()));
1623        let client = RecordingClient {
1624            fail,
1625            calls: Arc::clone(&calls),
1626        }
1627        .into_arc();
1628        (FallbackSlot::new(client, model, max_tokens), calls)
1629    }
1630
1631    fn test_completion() -> Completion {
1632        Completion {
1633            model: "logical-primary".to_string(),
1634            prompt: Message::user("continue"),
1635            preamble: Some("system".to_string()),
1636            history: vec![Message::user("prior work")],
1637            tools: Vec::new(),
1638            tool_choice: None,
1639            max_tokens: Some(999),
1640            additional_params: None,
1641        }
1642    }
1643
1644    #[tokio::test]
1645    async fn anthropic_first_party_policy_emits_cache_control_on_the_wire() {
1646        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1647        let address = listener.local_addr().unwrap();
1648        let server = tokio::spawn(async move {
1649            let (mut socket, _) = listener.accept().await.unwrap();
1650            let mut request = Vec::new();
1651            let header_end = loop {
1652                let mut chunk = [0_u8; 4096];
1653                let read = socket.read(&mut chunk).await.unwrap();
1654                assert!(read > 0, "client closed before sending HTTP headers");
1655                request.extend_from_slice(&chunk[..read]);
1656                if let Some(index) = request.windows(4).position(|w| w == b"\r\n\r\n") {
1657                    break index + 4;
1658                }
1659            };
1660            let headers = String::from_utf8_lossy(&request[..header_end]);
1661            let content_length = headers
1662                .lines()
1663                .find_map(|line| {
1664                    let (name, value) = line.split_once(':')?;
1665                    name.eq_ignore_ascii_case("content-length")
1666                        .then(|| value.trim().parse::<usize>().unwrap())
1667                })
1668                .expect("request must carry content-length");
1669            while request.len() < header_end + content_length {
1670                let mut chunk = [0_u8; 4096];
1671                let read = socket.read(&mut chunk).await.unwrap();
1672                assert!(read > 0, "client closed before sending the request body");
1673                request.extend_from_slice(&chunk[..read]);
1674            }
1675
1676            let response_body = json!({
1677                "content": [{ "type": "text", "text": "ok" }],
1678                "id": "msg_test",
1679                "model": "claude-test",
1680                "role": "assistant",
1681                "type": "message",
1682                "stop_reason": "end_turn",
1683                "stop_sequence": null,
1684                "usage": { "input_tokens": 1, "output_tokens": 1 }
1685            })
1686            .to_string();
1687            let response = format!(
1688                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{response_body}",
1689                response_body.len()
1690            );
1691            socket.write_all(response.as_bytes()).await.unwrap();
1692            serde_json::from_slice::<Value>(&request[header_end..header_end + content_length])
1693                .unwrap()
1694        });
1695
1696        let client = anthropic::Client::builder()
1697            .api_key("test-key")
1698            .base_url(format!("http://{address}"))
1699            .build()
1700            .unwrap();
1701        let caching_client = AnthropicPromptCachingClient::new(client);
1702        let mut completion = test_completion();
1703        completion.model = "claude-test".to_string();
1704        completion.tools = vec![rig_core::completion::ToolDefinition {
1705            name: "read_file".to_string(),
1706            description: "Read a file".to_string(),
1707            parameters: json!({
1708                "type": "object",
1709                "properties": { "path": { "type": "string" } },
1710                "required": ["path"]
1711            }),
1712        }];
1713
1714        LLMClient::completion(&caching_client, completion)
1715            .await
1716            .unwrap();
1717        let body = server.await.unwrap();
1718        assert_eq!(body["cache_control"]["type"], "ephemeral");
1719        assert_eq!(body["system"][0]["cache_control"]["type"], "ephemeral");
1720        assert_eq!(
1721            body["tools"].as_array().unwrap().last().unwrap()["cache_control"]["type"],
1722            "ephemeral"
1723        );
1724    }
1725
1726    #[tokio::test]
1727    async fn priority_client_uses_next_route_without_losing_the_completion() {
1728        let (first, first_calls) = recording_slot("first", Some(10), true);
1729        let (second, second_calls) = recording_slot("second", Some(20), false);
1730        let client = PriorityClient::new(vec![first, second]).unwrap();
1731
1732        let response = client.completion(test_completion()).await.unwrap();
1733
1734        assert_eq!(response.selected_model.as_deref(), Some("second"));
1735        {
1736            let first_guard = first_calls.lock().unwrap();
1737            let second_guard = second_calls.lock().unwrap();
1738            assert_eq!(first_guard.len(), 1);
1739            assert_eq!(second_guard.len(), 1);
1740            assert_eq!(first_guard[0].model, "first");
1741            assert_eq!(first_guard[0].max_tokens, Some(10));
1742            assert_eq!(second_guard[0].model, "second");
1743            assert_eq!(second_guard[0].max_tokens, Some(20));
1744            assert_eq!(second_guard[0].history.len(), 1);
1745            assert_eq!(second_guard[0].preamble.as_deref(), Some("system"));
1746        }
1747
1748        // A successful failover becomes this logical agent's active route, so the next turn does
1749        // not probe the failed primary again.
1750        client.completion(test_completion()).await.unwrap();
1751        assert_eq!(first_calls.lock().unwrap().len(), 1);
1752        assert_eq!(second_calls.lock().unwrap().len(), 2);
1753    }
1754
1755    #[tokio::test]
1756    async fn priority_clients_share_slots_without_sharing_stickiness() {
1757        let (failed, failed_calls) = recording_slot("failed", None, true);
1758        let (healthy, healthy_calls) = recording_slot("healthy", None, false);
1759        let first = PriorityClient::new(vec![failed.clone(), healthy.clone()]).unwrap();
1760        let independent = PriorityClient::new(vec![failed, healthy]).unwrap();
1761
1762        first.completion(test_completion()).await.unwrap();
1763        first.completion(test_completion()).await.unwrap();
1764        independent.completion(test_completion()).await.unwrap();
1765
1766        // The first logical agent sticks to its successful fallback, while the independent agent
1767        // still starts from its own primary. Shared slot state is tested separately for quota.
1768        assert_eq!(failed_calls.lock().unwrap().len(), 2);
1769        assert_eq!(healthy_calls.lock().unwrap().len(), 3);
1770    }
1771
1772    #[test]
1773    fn fallback_slot_clones_share_one_failover_warning_claim() {
1774        let (slot, _) = recording_slot("shared-route", None, false);
1775        let clone = slot.clone();
1776
1777        assert!(slot.claim_failover_warning());
1778        assert!(!clone.claim_failover_warning());
1779
1780        // Dedupe follows a concrete route, not its model string: distinct credentials using the
1781        // same model must each retain their own warning claim.
1782        let (same_model_distinct_route, _) = recording_slot("shared-route", None, false);
1783        assert!(same_model_distinct_route.claim_failover_warning());
1784    }
1785
1786    struct FailOnCallClient {
1787        calls: Arc<AtomicUsize>,
1788        fail_on: usize,
1789    }
1790
1791    impl LLMClient for FailOnCallClient {
1792        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
1793            let call = self.calls.fetch_add(1, Ordering::Relaxed) + 1;
1794            if call == self.fail_on {
1795                eyre::bail!("request-specific route failure")
1796            }
1797            Ok(response_with(vec![AssistantContent::text("ok")]))
1798        }
1799    }
1800
1801    #[tokio::test]
1802    async fn agent_fork_inherits_but_cannot_overwrite_parent_stickiness() {
1803        let first_calls = Arc::new(AtomicUsize::new(0));
1804        let second_calls = Arc::new(AtomicUsize::new(0));
1805        let first = FallbackSlot::new(
1806            FailOnCallClient {
1807                calls: Arc::clone(&first_calls),
1808                fail_on: 1,
1809            }
1810            .into_arc(),
1811            "first",
1812            None,
1813        );
1814        let second = FallbackSlot::new(
1815            FailOnCallClient {
1816                calls: Arc::clone(&second_calls),
1817                fail_on: 2,
1818            }
1819            .into_arc(),
1820            "second",
1821            None,
1822        );
1823        let parent = PriorityClient::new(vec![first, second]).unwrap();
1824
1825        // The parent fails over to `second`; the fork inherits that route, then independently
1826        // wraps back to `first` when its own request fails there.
1827        parent.completion(test_completion()).await.unwrap();
1828        let fork = parent.fork_for_agent().expect("priority clients can fork");
1829        fork.completion(test_completion()).await.unwrap();
1830        parent.completion(test_completion()).await.unwrap();
1831
1832        // The parent's final turn still starts on `second`. A shared active index would have made
1833        // it start on `first`, while a fork reset to zero would have skipped `second` initially.
1834        assert_eq!(first_calls.load(Ordering::Relaxed), 2);
1835        assert_eq!(second_calls.load(Ordering::Relaxed), 3);
1836    }
1837
1838    #[tokio::test]
1839    async fn priority_client_wraps_through_declaration_order() {
1840        let (first, first_calls) = recording_slot("first", None, false);
1841        let (second, second_calls) = recording_slot("second", None, true);
1842        let (third, third_calls) = recording_slot("third", None, true);
1843        // Production callers rotate the configured ring so the logical primary is first.
1844        let client = PriorityClient::new(vec![second, third, first]).unwrap();
1845
1846        let response = client.completion(test_completion()).await.unwrap();
1847
1848        assert_eq!(response.selected_model.as_deref(), Some("first"));
1849        assert_eq!(second_calls.lock().unwrap().len(), 1);
1850        assert_eq!(third_calls.lock().unwrap().len(), 1);
1851        assert_eq!(first_calls.lock().unwrap().len(), 1);
1852    }
1853
1854    struct MaxTokensClient {
1855        calls: Arc<AtomicUsize>,
1856    }
1857
1858    impl LLMClient for MaxTokensClient {
1859        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
1860            self.calls.fetch_add(1, Ordering::Relaxed);
1861            let mut response = response_with(vec![AssistantContent::text("partial")]);
1862            response.finish_reason = FinishReason::MaxTokens;
1863            response.usage.output_tokens = 10;
1864            Ok(response)
1865        }
1866    }
1867
1868    #[tokio::test]
1869    async fn priority_client_retries_truncated_response_on_the_next_route() {
1870        let truncated_calls = Arc::new(AtomicUsize::new(0));
1871        let truncated = FallbackSlot::new(
1872            MaxTokensClient {
1873                calls: Arc::clone(&truncated_calls),
1874            }
1875            .into_arc(),
1876            "truncated",
1877            Some(10),
1878        );
1879        let (healthy, healthy_calls) = recording_slot("healthy", Some(20), false);
1880        let client = PriorityClient::new(vec![truncated, healthy]).unwrap();
1881
1882        let response = client.completion(test_completion()).await.unwrap();
1883
1884        assert_eq!(response.selected_model.as_deref(), Some("healthy"));
1885        assert_eq!(truncated_calls.load(Ordering::Relaxed), 1);
1886        assert_eq!(healthy_calls.lock().unwrap().len(), 1);
1887    }
1888
1889    struct ToolUseClient {
1890        calls: Arc<AtomicUsize>,
1891    }
1892
1893    impl LLMClient for ToolUseClient {
1894        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
1895            use rig_core::completion::message::ToolFunction;
1896            self.calls.fetch_add(1, Ordering::Relaxed);
1897            let mut response = response_with(vec![AssistantContent::ToolCall(ToolCall::new(
1898                "call-1".to_string(),
1899                ToolFunction::new("allowed".to_string(), serde_json::json!({})),
1900            ))]);
1901            response.finish_reason = FinishReason::ToolUse;
1902            Ok(response)
1903        }
1904    }
1905
1906    struct RequiredToolClient {
1907        calls: Arc<AtomicUsize>,
1908    }
1909
1910    impl LLMClient for RequiredToolClient {
1911        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
1912            use rig_core::completion::message::ToolFunction;
1913            self.calls.fetch_add(1, Ordering::Relaxed);
1914            let mut response = response_with(vec![AssistantContent::ToolCall(ToolCall::new(
1915                "call-1".to_string(),
1916                ToolFunction::new("submit".to_string(), serde_json::json!({})),
1917            ))]);
1918            response.finish_reason = FinishReason::ToolUse;
1919            Ok(response)
1920        }
1921    }
1922
1923    #[tokio::test]
1924    async fn priority_client_retries_unexpected_tool_use_for_no_tools_request() {
1925        let tool_use_calls = Arc::new(AtomicUsize::new(0));
1926        let tool_use = FallbackSlot::new(
1927            ToolUseClient {
1928                calls: Arc::clone(&tool_use_calls),
1929            }
1930            .into_arc(),
1931            "tool-use",
1932            None,
1933        );
1934        let (healthy, healthy_calls) = recording_slot("healthy", None, false);
1935        let client = PriorityClient::new(vec![tool_use, healthy]).unwrap();
1936
1937        let response = client.completion(test_completion()).await.unwrap();
1938
1939        assert_eq!(response.selected_model.as_deref(), Some("healthy"));
1940        assert_eq!(tool_use_calls.load(Ordering::Relaxed), 1);
1941        assert_eq!(healthy_calls.lock().unwrap().len(), 1);
1942    }
1943
1944    #[tokio::test]
1945    async fn priority_client_accepts_tool_use_when_tools_were_declared() {
1946        let tool_use_calls = Arc::new(AtomicUsize::new(0));
1947        let tool_use = FallbackSlot::new(
1948            ToolUseClient {
1949                calls: Arc::clone(&tool_use_calls),
1950            }
1951            .into_arc(),
1952            "tool-use",
1953            None,
1954        );
1955        let (unused, unused_calls) = recording_slot("unused", None, false);
1956        let client = PriorityClient::new(vec![tool_use, unused]).unwrap();
1957        let mut completion = test_completion();
1958        completion.tools.push(rig_core::completion::ToolDefinition {
1959            name: "allowed".to_string(),
1960            description: "An allowed tool".to_string(),
1961            parameters: serde_json::json!({"type": "object"}),
1962        });
1963
1964        let response = client.completion(completion).await.unwrap();
1965
1966        assert_eq!(response.finish_reason, FinishReason::ToolUse);
1967        assert_eq!(response.selected_model.as_deref(), Some("tool-use"));
1968        assert_eq!(tool_use_calls.load(Ordering::Relaxed), 1);
1969        assert!(unused_calls.lock().unwrap().is_empty());
1970    }
1971
1972    #[tokio::test]
1973    async fn required_tool_protocol_failure_tries_the_next_route() {
1974        let (plain_text, plain_text_calls) = recording_slot("plain-text", None, false);
1975        let required_tool_calls = Arc::new(AtomicUsize::new(0));
1976        let required_tool = FallbackSlot::new(
1977            RequiredToolClient {
1978                calls: Arc::clone(&required_tool_calls),
1979            }
1980            .into_arc(),
1981            "required-tool",
1982            None,
1983        );
1984        let client = PriorityClient::new(vec![plain_text, required_tool]).unwrap();
1985        let mut completion = test_completion();
1986        completion.tools.push(rig_core::completion::ToolDefinition {
1987            name: "submit".to_string(),
1988            description: "Submit the result".to_string(),
1989            parameters: serde_json::json!({"type": "object"}),
1990        });
1991        completion.tool_choice = Some(ToolChoice::Required);
1992
1993        let response = client.completion(completion).await.unwrap();
1994
1995        assert_eq!(response.selected_model.as_deref(), Some("required-tool"));
1996        assert_eq!(plain_text_calls.lock().unwrap().len(), 1);
1997        assert_eq!(required_tool_calls.load(Ordering::Relaxed), 1);
1998    }
1999
2000    #[tokio::test]
2001    async fn undeclared_required_tool_call_tries_the_next_route() {
2002        let wrong_tool_calls = Arc::new(AtomicUsize::new(0));
2003        let wrong_tool = FallbackSlot::new(
2004            ToolUseClient {
2005                calls: Arc::clone(&wrong_tool_calls),
2006            }
2007            .into_arc(),
2008            "wrong-tool",
2009            None,
2010        );
2011        let required_tool_calls = Arc::new(AtomicUsize::new(0));
2012        let required_tool = FallbackSlot::new(
2013            RequiredToolClient {
2014                calls: Arc::clone(&required_tool_calls),
2015            }
2016            .into_arc(),
2017            "required-tool",
2018            None,
2019        );
2020        let client = PriorityClient::new(vec![wrong_tool, required_tool]).unwrap();
2021        let mut completion = test_completion();
2022        completion.tools.push(rig_core::completion::ToolDefinition {
2023            name: "submit".to_string(),
2024            description: "Submit the result".to_string(),
2025            parameters: serde_json::json!({"type": "object"}),
2026        });
2027        completion.tool_choice = Some(ToolChoice::Required);
2028
2029        let response = client.completion(completion).await.unwrap();
2030
2031        assert_eq!(response.selected_model.as_deref(), Some("required-tool"));
2032        assert_eq!(wrong_tool_calls.load(Ordering::Relaxed), 1);
2033        assert_eq!(required_tool_calls.load(Ordering::Relaxed), 1);
2034    }
2035
2036    #[tokio::test]
2037    async fn specifically_disallowed_tool_call_tries_the_next_route() {
2038        let wrong_tool_calls = Arc::new(AtomicUsize::new(0));
2039        let wrong_tool = FallbackSlot::new(
2040            ToolUseClient {
2041                calls: Arc::clone(&wrong_tool_calls),
2042            }
2043            .into_arc(),
2044            "wrong-tool",
2045            None,
2046        );
2047        let required_tool_calls = Arc::new(AtomicUsize::new(0));
2048        let required_tool = FallbackSlot::new(
2049            RequiredToolClient {
2050                calls: Arc::clone(&required_tool_calls),
2051            }
2052            .into_arc(),
2053            "required-tool",
2054            None,
2055        );
2056        let client = PriorityClient::new(vec![wrong_tool, required_tool]).unwrap();
2057        let mut completion = test_completion();
2058        for name in ["allowed", "submit"] {
2059            completion.tools.push(rig_core::completion::ToolDefinition {
2060                name: name.to_string(),
2061                description: "A declared tool".to_string(),
2062                parameters: serde_json::json!({"type": "object"}),
2063            });
2064        }
2065        completion.tool_choice = Some(ToolChoice::Specific {
2066            function_names: vec!["submit".to_string()],
2067        });
2068
2069        let response = client.completion(completion).await.unwrap();
2070
2071        assert_eq!(response.selected_model.as_deref(), Some("required-tool"));
2072        assert_eq!(wrong_tool_calls.load(Ordering::Relaxed), 1);
2073        assert_eq!(required_tool_calls.load(Ordering::Relaxed), 1);
2074    }
2075
2076    #[tokio::test]
2077    async fn priority_client_reports_when_every_route_is_unavailable() {
2078        let (slot, calls) = recording_slot("unavailable", None, false);
2079        slot.mark_unavailable();
2080        let client = PriorityClient::new(vec![slot]).unwrap();
2081
2082        let err = client.completion(test_completion()).await.unwrap_err();
2083
2084        assert_eq!(
2085            format!("{err:#}"),
2086            "all configured model routes are unavailable for this run"
2087        );
2088        assert!(calls.lock().unwrap().is_empty());
2089    }
2090
2091    #[tokio::test]
2092    async fn alloy_without_fallback_attempts_only_the_selected_route() {
2093        let (first, first_calls) = recording_slot("first", None, true);
2094        let (second, second_calls) = recording_slot("second", None, true);
2095        let client =
2096            AlloyClient::new(vec![AlloySlot::from(&first), AlloySlot::from(&second)]).unwrap();
2097
2098        assert!(client.completion(test_completion()).await.is_err());
2099        assert_eq!(
2100            first_calls.lock().unwrap().len() + second_calls.lock().unwrap().len(),
2101            1
2102        );
2103    }
2104
2105    #[tokio::test]
2106    async fn alloy_fallback_succeeds_from_every_random_start() {
2107        let (failed_a, _) = recording_slot("failed-a", None, true);
2108        let (healthy, _) = recording_slot("healthy", None, false);
2109        let (failed_b, _) = recording_slot("failed-b", None, true);
2110        let client =
2111            AlloyClient::new_with_fallback_routes(vec![failed_a, healthy, failed_b]).unwrap();
2112
2113        // Whichever slot randomness selects first, walking the ring once must reach `healthy`.
2114        for _ in 0..32 {
2115            let response = client.completion(test_completion()).await.unwrap();
2116            assert_eq!(response.selected_model.as_deref(), Some("healthy"));
2117        }
2118    }
2119
2120    #[test]
2121    fn alloy_random_start_excludes_unavailable_routes() {
2122        let (unavailable, _) = recording_slot("unavailable", None, false);
2123        unavailable.mark_unavailable();
2124        let (first, _) = recording_slot("first", None, false);
2125        let (second, _) = recording_slot("second", None, false);
2126        let client =
2127            AlloyClient::new_with_fallback_routes(vec![unavailable, first, second]).unwrap();
2128
2129        assert_eq!(client.available_indices(), vec![1, 2]);
2130        for _ in 0..32 {
2131            assert!(matches!(client.pick_idx(), Some(1 | 2)));
2132        }
2133    }
2134
2135    struct QuotaClient {
2136        calls: Arc<AtomicUsize>,
2137    }
2138
2139    impl LLMClient for QuotaClient {
2140        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
2141            self.calls.fetch_add(1, Ordering::Relaxed);
2142            Err(eyre::Report::new(CompletionError::from_http_response(
2143                reqwest::StatusCode::TOO_MANY_REQUESTS,
2144                r#"{"error":{"code":"usage_limit_reached"}}"#,
2145            )))
2146        }
2147    }
2148
2149    #[tokio::test]
2150    async fn quota_failure_is_shared_across_agent_forks_for_the_run() {
2151        let quota_calls = Arc::new(AtomicUsize::new(0));
2152        let quota = FallbackSlot::new(
2153            QuotaClient {
2154                calls: Arc::clone(&quota_calls),
2155            }
2156            .into_arc(),
2157            "quota",
2158            None,
2159        );
2160        let (healthy, _) = recording_slot("healthy", None, false);
2161        let first = PriorityClient::new(vec![quota, healthy]).unwrap();
2162        let second = first.fork_for_agent().expect("priority clients can fork");
2163
2164        first.completion(test_completion()).await.unwrap();
2165        second.completion(test_completion()).await.unwrap();
2166
2167        assert_eq!(quota_calls.load(Ordering::Relaxed), 1);
2168    }
2169
2170    fn reasoning_item(text: &str) -> AssistantContent {
2171        AssistantContent::Reasoning(rig_core::completion::message::Reasoning::new(text))
2172    }
2173
2174    /// The block is never closed, so the scanner drops the verdict with the reasoning — but the
2175    /// reasoning is also reported structurally, so it can be subtracted exactly.
2176    #[test]
2177    fn unterminated_think_keeps_the_answer_and_drops_the_duplicated_reasoning() {
2178        let reasoning = "The debate is extremely brief. The Actor suggested `eyre`.";
2179        let response = response_with(vec![
2180            reasoning_item(reasoning),
2181            AssistantContent::text(format!(
2182                "<think>\n{reasoning}\n\n### Verdict\n**Agreed: use `eyre` for applications.**"
2183            )),
2184        ]);
2185        assert_eq!(
2186            response.text(),
2187            "### Verdict\n**Agreed: use `eyre` for applications.**"
2188        );
2189    }
2190
2191    /// Leading text hides the answer just as thoroughly, but makes the response read as
2192    /// successful — so nothing retries and the verdict is lost silently.
2193    #[test]
2194    fn unterminated_think_after_a_prefix_still_recovers_the_answer() {
2195        let reasoning = "Weighing both sides.";
2196        let response = response_with(vec![
2197            reasoning_item(reasoning),
2198            AssistantContent::text(format!(
2199                "Here is my review.\n<think>\n{reasoning}\n\n### Verdict\nShip it."
2200            )),
2201        ]);
2202        assert_eq!(
2203            response.text(),
2204            "Here is my review.\n\n### Verdict\nShip it."
2205        );
2206    }
2207
2208    /// OpenRouter splits `reasoning_details` mid-sentence, so a newline join stops the fragments
2209    /// matching their copy inside the block and the whole chain leaks into the answer.
2210    #[test]
2211    fn fragmented_reasoning_is_concatenated_without_separators() {
2212        let response = response_with(vec![
2213            reasoning_item("weighing the options"),
2214            reasoning_item(" carefully."),
2215            AssistantContent::text("<think>\nweighing the options carefully.\n\nVerdict: ship it."),
2216        ]);
2217        assert_eq!(response.text(), "Verdict: ship it.");
2218    }
2219
2220    /// With no structured reasoning there is no way to tell reasoning from answer. Returning the
2221    /// body would both serve chain-of-thought as the verdict and make the response read as
2222    /// non-empty, silencing the retry that exists for a reply that never answered.
2223    #[test]
2224    fn unterminated_think_without_structured_reasoning_stays_empty() {
2225        let response = response_with(vec![AssistantContent::text(
2226            "<think>\nweighing it up\n\nVerdict: ship it.",
2227        )]);
2228        assert!(response.text().is_empty());
2229    }
2230
2231    /// A summary is a paraphrase of the chain, not a slice of it, so it cannot be subtracted from
2232    /// the body — matching it as a fragment would leave a mangled prefix behind.
2233    #[test]
2234    fn summary_reasoning_is_not_used_to_split_the_body() {
2235        let response = response_with(vec![
2236            AssistantContent::Reasoning(rig_core::completion::message::Reasoning::summaries(vec![
2237                "brief".to_string(),
2238            ])),
2239            AssistantContent::text("<think>private chain"),
2240        ]);
2241        assert!(response.text().is_empty());
2242    }
2243
2244    /// A reasoning string that happens to be a byte prefix of the answer must not chop it: "Ver"
2245    /// against "Verdict: ship it." would otherwise yield "dict: ship it.".
2246    #[test]
2247    fn a_prefix_that_cuts_mid_word_is_not_treated_as_reasoning() {
2248        let response = response_with(vec![
2249            reasoning_item("Ver"),
2250            AssistantContent::text("<think>Verdict: ship it."),
2251        ]);
2252        assert!(response.text().is_empty());
2253    }
2254
2255    /// With several blocks, the one that stayed open is not the first tag in the text. Recovery
2256    /// keys off the scanner's offset, so an earlier *closed* block cannot misdirect it.
2257    #[test]
2258    fn recovery_targets_the_block_that_stayed_open() {
2259        let response = response_with(vec![
2260            reasoning_item("secret"),
2261            AssistantContent::text("<think>old</think>\n<think>secret\n\nFINAL"),
2262        ]);
2263        assert_eq!(response.text(), "FINAL");
2264    }
2265
2266    /// A stray closing tag at depth 0 is dropped by the scanner and must not be mistaken for the
2267    /// opener when recovering.
2268    #[test]
2269    fn a_stray_closing_tag_does_not_misdirect_recovery() {
2270        let response = response_with(vec![
2271            reasoning_item("secret"),
2272            AssistantContent::text("</think><think>secret\n\nFINAL"),
2273        ]);
2274        assert_eq!(response.text(), "FINAL");
2275    }
2276
2277    /// A response that is only reasoning still collapses to empty, so the empty-response retry
2278    /// keeps working for models that genuinely returned no answer.
2279    #[test]
2280    fn a_reasoning_only_response_is_still_empty() {
2281        let reasoning = "still thinking about it";
2282        let response = response_with(vec![
2283            reasoning_item(reasoning),
2284            AssistantContent::text(format!("<think>\n{reasoning}")),
2285        ]);
2286        assert!(response.text().is_empty());
2287        let closed = response_with(vec![AssistantContent::text(
2288            "<think>done deliberating</think>",
2289        )]);
2290        assert!(closed.text().is_empty());
2291    }
2292
2293    /// A well-formed closed block is untouched by the recovery path.
2294    #[test]
2295    fn closed_think_block_still_yields_only_the_answer() {
2296        let response = response_with(vec![AssistantContent::text(
2297            "<think>weighing it up</think>Verdict: ship it.",
2298        )]);
2299        assert_eq!(response.text(), "Verdict: ship it.");
2300    }
2301
2302    /// Mirrors rig's Anthropic mapping: `input_tokens` excludes the cache buckets and
2303    /// `total_tokens` is their sum plus output (`anthropic/completion.rs`).
2304    fn anthropic_usage(input: u64, output: u64, cached: u64, creation: u64) -> Usage {
2305        let mut usage = Usage::new();
2306        usage.input_tokens = input;
2307        usage.output_tokens = output;
2308        usage.cached_input_tokens = cached;
2309        usage.cache_creation_input_tokens = creation;
2310        usage.total_tokens = input + cached + creation + output;
2311        usage
2312    }
2313
2314    fn anthropic(usage: &Usage) -> TokenUsage {
2315        TokenUsage::from_provider(usage, CacheAccounting::OutsidePrompt)
2316    }
2317
2318    fn prompt_inclusive(usage: &Usage) -> TokenUsage {
2319        TokenUsage::from_provider(usage, CacheAccounting::InsidePrompt)
2320    }
2321
2322    /// The same 3508-token prompt served from cache, as each provider reports it: Anthropic shows
2323    /// `input_tokens: 52` with the rest under `cache_read`, OpenAI shows the whole prompt. Both
2324    /// must meter identically, or a mixed-provider run sums numbers that mean different things —
2325    /// and the Anthropic shape read raw is what hid 98% of the prompt.
2326    #[test]
2327    fn provider_shapes_meter_a_cache_hit_identically() {
2328        let from_anthropic = anthropic(&anthropic_usage(52, 8, 3456, 0));
2329        let mut openai = Usage::new();
2330        openai.input_tokens = 3508;
2331        openai.output_tokens = 8;
2332        openai.cached_input_tokens = 3456;
2333        openai.total_tokens = 3516;
2334        let from_openai = prompt_inclusive(&openai);
2335
2336        assert_eq!(from_anthropic.input_tokens, 3508);
2337        assert_eq!(from_anthropic.input_tokens, from_openai.input_tokens);
2338        assert_eq!(
2339            from_anthropic.cached_input_tokens,
2340            from_openai.cached_input_tokens
2341        );
2342        for usage in [from_anthropic, from_openai] {
2343            assert_eq!(usage.total_tokens, usage.input_tokens + usage.output_tokens);
2344        }
2345    }
2346
2347    /// Gemini reports thinking and tool-use prompts beside both `input_tokens` and
2348    /// `output_tokens`, and its parts don't sum to its total — so no arithmetic can tell its shape
2349    /// apart from Anthropic's. Numbers are rig's own fixture (`gemini/completion.rs`) with the
2350    /// cache lowered to 8, the value that makes the buckets *look* like they fit outside the
2351    /// prompt. Charging them would report a 40-token prompt as 48.
2352    #[test]
2353    fn gemini_cache_reads_are_never_added_to_its_prompt() {
2354        let mut usage = Usage::new();
2355        usage.input_tokens = 40;
2356        usage.output_tokens = 30;
2357        usage.reasoning_tokens = 10;
2358        usage.tool_use_prompt_tokens = 12;
2359        usage.cached_input_tokens = 8;
2360        usage.total_tokens = 100;
2361        let usage = prompt_inclusive(&usage);
2362        assert_eq!(usage.input_tokens, 40);
2363        assert_eq!(usage.cached_input_tokens, 8);
2364    }
2365
2366    /// An OpenRouter gateway may report a total larger than prompt + completion. That slack must
2367    /// not turn its cache reads — already inside `prompt_tokens` — into extra prompt tokens.
2368    #[test]
2369    fn openrouter_total_disagreement_does_not_inflate_the_prompt() {
2370        let mut usage = Usage::new();
2371        usage.input_tokens = 500;
2372        usage.output_tokens = 10;
2373        usage.cached_input_tokens = 5;
2374        usage.total_tokens = 515;
2375        let usage = prompt_inclusive(&usage);
2376        assert_eq!(usage.input_tokens, 500);
2377        assert_eq!(usage.total_tokens, 510);
2378    }
2379
2380    /// A gateway that omits usage totals must still meter the prompt it reported.
2381    #[test]
2382    fn missing_provider_total_still_meters_reported_input() {
2383        let mut usage = Usage::new();
2384        usage.input_tokens = 1200;
2385        usage.output_tokens = 40;
2386        let usage = prompt_inclusive(&usage);
2387        assert_eq!(usage.input_tokens, 1200);
2388        assert_eq!(usage.total_tokens, 1240);
2389    }
2390
2391    /// Anthropic charges a cache *write* too, and reports it outside `input_tokens` like a read.
2392    #[test]
2393    fn anthropic_cache_writes_count_toward_the_prompt() {
2394        let usage = anthropic(&anthropic_usage(90, 10, 0, 4100));
2395        assert_eq!(usage.cache_creation_input_tokens, 4100);
2396        assert_eq!(usage.input_tokens, 4190);
2397        assert_eq!(usage.total_tokens, 4200);
2398    }
2399
2400    /// A provider reporting more cache than prompt is contradicting itself. Reporting the prompt
2401    /// as 5000 to make the breakdown fit would invent 4990 tokens of spend that were never billed,
2402    /// so both numbers are passed through as reported and the contradiction stays visible.
2403    #[test]
2404    fn contradictory_cache_metadata_is_not_papered_over() {
2405        let mut usage = Usage::new();
2406        usage.input_tokens = 10;
2407        usage.output_tokens = 5;
2408        usage.total_tokens = 15;
2409        usage.cached_input_tokens = 5_000;
2410        usage.cache_creation_input_tokens = 700;
2411        let usage = prompt_inclusive(&usage);
2412        assert_eq!(usage.input_tokens, 10);
2413        assert_eq!(usage.total_tokens, 15);
2414        assert_eq!(usage.cached_input_tokens, 5_000);
2415        assert_eq!(usage.cache_creation_input_tokens, 700);
2416    }
2417
2418    /// The whole point of the normalization: a cache hit must still trip the compaction
2419    /// threshold, since the full prompt is what gets re-sent next turn.
2420    #[test]
2421    fn compaction_threshold_sees_the_cached_prompt() {
2422        let mut window = ConversationUsageWindow::new(Some(3_000));
2423        window.record(anthropic(&anthropic_usage(52, 8, 3456, 0)));
2424        assert!(window.should_compact());
2425    }
2426
2427    /// The cache fields are `#[serde(default)]` so trajectories written before they existed
2428    /// still decode.
2429    #[test]
2430    fn usage_without_cache_fields_still_deserializes() {
2431        let usage: TokenUsage = serde_json::from_value(
2432            json!({"input_tokens": 10, "output_tokens": 2, "total_tokens": 12}),
2433        )
2434        .expect("legacy usage payload must decode");
2435        assert_eq!(usage.input_tokens, 10);
2436        assert_eq!(usage.cached_input_tokens, 0);
2437    }
2438
2439    fn provider_error(status: Option<u16>, body: &str) -> eyre::Report {
2440        let error = match status {
2441            Some(status) => CompletionError::from_http_response(
2442                reqwest::StatusCode::from_u16(status).unwrap(),
2443                body,
2444            ),
2445            None => CompletionError::from_provider_body(body),
2446        };
2447        eyre::Report::new(error).wrap_err("completion failed for model 'test'")
2448    }
2449
2450    fn gemini_completion(max_tokens: Option<u64>, additional_params: Option<Value>) -> Completion {
2451        Completion {
2452            model: "gemini-3-pro".to_string(),
2453            prompt: Message::user("hi".to_string()),
2454            preamble: None,
2455            history: Vec::new(),
2456            tools: Vec::new(),
2457            tool_choice: None,
2458            max_tokens,
2459            additional_params,
2460        }
2461    }
2462
2463    #[test]
2464    fn merge_json_is_deep_and_extra_wins() {
2465        // nested objects merge recursively; scalar conflicts resolve to `extra`.
2466        let merged = merge_json(
2467            json!({"generation_config": {"temperature": 0.2}, "a": 1}),
2468            json!({"generation_config": {"max_output_tokens": 50}, "a": 2}),
2469        );
2470        assert_eq!(
2471            merged,
2472            json!({"generation_config": {"temperature": 0.2, "max_output_tokens": 50}, "a": 2})
2473        );
2474    }
2475
2476    #[test]
2477    fn gemini_params_preserve_caller_config() {
2478        // A caller's safety settings and nested generation_config must survive the computed overlay.
2479        let params = build_gemini_additional_params(&gemini_completion(
2480            Some(50),
2481            Some(json!({
2482                "generation_config": {"temperature": 0.2},
2483                "safetySettings": [{"category": "HARM", "threshold": "NONE"}]
2484            })),
2485        ))
2486        .unwrap();
2487        assert_eq!(
2488            params,
2489            json!({
2490                "generation_config": {"temperature": 0.2, "max_output_tokens": 50},
2491                "safetySettings": [{"category": "HARM", "threshold": "NONE"}]
2492            })
2493        );
2494    }
2495
2496    #[test]
2497    fn gemini_params_none_yields_generation_config_only() {
2498        let params = build_gemini_additional_params(&gemini_completion(Some(50), None)).unwrap();
2499        assert_eq!(
2500            params,
2501            json!({"generation_config": {"max_output_tokens": 50}})
2502        );
2503    }
2504
2505    #[test]
2506    fn strips_full_think_block() {
2507        let raw = "<think>let me reason about this</think>\n\nThe bug is in foo().";
2508        assert_eq!(strip_think_blocks(raw), "The bug is in foo().");
2509    }
2510
2511    #[test]
2512    fn strips_stray_empty_think_tags() {
2513        // OpenRouter hoists MiniMax's reasoning into a separate field but leaves the tags.
2514        let raw = "<think></think>\n## Findings\n- looks fine";
2515        assert_eq!(strip_think_blocks(raw), "## Findings\n- looks fine");
2516    }
2517
2518    #[test]
2519    fn strips_unbalanced_and_multiline_think() {
2520        let raw = "intro\n<think>\nstep 1\nstep 2\n</think>verdict: ok</think>";
2521        assert_eq!(strip_think_blocks(raw), "intro\nverdict: ok");
2522    }
2523
2524    #[test]
2525    fn leaves_non_think_text_untouched() {
2526        let raw = "no reasoning tags here, just review text";
2527        assert_eq!(strip_think_blocks(raw), raw);
2528    }
2529
2530    #[test]
2531    fn strips_unterminated_think_to_eof() {
2532        // a streamed/truncated block with no closing tag must not leak its body.
2533        let raw = "answer first\n<think>reasoning that never closes\nstep 2";
2534        assert_eq!(strip_think_blocks(raw), "answer first");
2535    }
2536
2537    #[test]
2538    fn all_reasoning_collapses_to_empty() {
2539        // an all-think response (incl. the multi-block join) must be empty so the
2540        // agent loop's is_empty() nudge path fires instead of returning "\n".
2541        let joined = format!("{}\n{}", "<think>round one</think>", "<think>round two");
2542        assert_eq!(strip_think_blocks(&joined), "");
2543    }
2544
2545    #[test]
2546    fn response_text_collapses_whitespace_only_content_to_empty() {
2547        let response = response_with(vec![AssistantContent::text(" \n\t ")]);
2548        assert!(response.text().is_empty());
2549    }
2550
2551    #[test]
2552    fn strips_nested_think_blocks() {
2553        // a single non-greedy regex stops at the first </think> and leaks the tail; the
2554        // depth-tracking scanner must drop the whole balanced span.
2555        let raw = "<think>outer <think>inner</think> still hidden</think>answer";
2556        assert_eq!(strip_think_blocks(raw), "answer");
2557    }
2558
2559    #[test]
2560    fn strips_whitespace_padded_think_tags() {
2561        // `<think >` must be recognized as an open tag, not leaked as content.
2562        let raw = "<think >hidden</think >visible";
2563        assert_eq!(strip_think_blocks(raw), "visible");
2564    }
2565
2566    #[test]
2567    fn leaves_thinking_word_untouched() {
2568        // `<thinking>` is a different tag — the char after `think` must be ws or `>`.
2569        let raw = "see <thinking>kept</thinking> here";
2570        assert_eq!(
2571            strip_think_blocks(raw),
2572            "see <thinking>kept</thinking> here"
2573        );
2574    }
2575
2576    #[test]
2577    fn classifiers_use_captured_http_status() {
2578        let unauthorized = provider_error(Some(401), r#"{"message":"Unauthorized"}"#);
2579        assert!(!unauthorized.to_string().contains("401"));
2580        assert_eq!(provider_http_status(&unauthorized), Some(401));
2581        assert!(is_non_retryable_client_error(&unauthorized));
2582
2583        let throttled = provider_error(Some(429), r#"{"message":"slow down"}"#);
2584        assert!(is_rate_limit_error(&throttled));
2585        assert_eq!(
2586            retry_policy(&throttled).max_attempts,
2587            RATE_LIMIT_MAX_COMPLETION_ATTEMPTS
2588        );
2589
2590        let server = provider_error(Some(503), r#"{"message":"unavailable"}"#);
2591        assert_eq!(
2592            classify_provider_failure(&server),
2593            ProviderFailureClass::Server
2594        );
2595        assert_eq!(retry_policy(&server).max_attempts, MAX_COMPLETION_ATTEMPTS);
2596    }
2597
2598    #[test]
2599    fn exact_quota_codes_skip_same_route_retries() {
2600        for code in PERMANENT_QUOTA_ERROR_CODES {
2601            let body = format!(r#"{{"error":{{"code":"{code}"}}}}"#);
2602            let err = provider_error(Some(429), &body);
2603            assert!(is_long_window_quota_error(&err), "{code}");
2604            assert!(!is_rate_limit_error(&err), "{code}");
2605            assert!(!retry_policy(&err).retry, "{code}");
2606            assert!(is_sticky_fallback_error(&err), "{code}");
2607        }
2608    }
2609
2610    #[test]
2611    fn structured_kimi_quota_messages_are_the_narrow_compatibility_fallback() {
2612        for (status, message) in [
2613            (429, "out of tokens per 5h window; reset in 2h"),
2614            (429, "You've hit your usage limit"),
2615            (
2616                403,
2617                "You've reached your usage limit for this billing cycle. Your quota will be refreshed in the next cycle.",
2618            ),
2619        ] {
2620            let body = json!({"error": {"type": "access_terminated_error", "message": message}});
2621            let err = provider_error(Some(status), &body.to_string());
2622            assert!(is_long_window_quota_error(&err), "{message}");
2623            assert!(!retry_policy(&err).retry, "{message}");
2624        }
2625
2626        // Diagnostic text outside a structured provider body is deliberately ignored.
2627        let untyped = eyre::eyre!("insufficient_quota: out of tokens per 5h window");
2628        assert_eq!(
2629            classify_provider_failure(&untyped),
2630            ProviderFailureClass::Unknown
2631        );
2632        assert_eq!(retry_policy(&untyped).max_attempts, MAX_COMPLETION_ATTEMPTS);
2633    }
2634
2635    #[test]
2636    fn real_5xx_status_precedes_nested_quota_and_rate_codes() {
2637        for status in (500..600).filter(|&status| status != 529) {
2638            for body in [
2639                r#"{"upstream":{"error":{"code":"insufficient_quota","message":"out of tokens per 5h window"}}}"#,
2640                r#"{"upstream":{"error":{"type":"overloaded_error"}}}"#,
2641            ] {
2642                let err = provider_error(Some(status), body);
2643                assert_eq!(
2644                    classify_provider_failure(&err),
2645                    ProviderFailureClass::Server
2646                );
2647                let policy = retry_policy(&err);
2648                assert!(policy.retry);
2649                assert_eq!(policy.max_attempts, MAX_COMPLETION_ATTEMPTS);
2650                assert!(!is_sticky_fallback_error(&err));
2651            }
2652        }
2653    }
2654
2655    #[test]
2656    fn anthropic_529_overload_uses_the_long_overload_policy() {
2657        let err = provider_error(
2658            Some(529),
2659            r#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#,
2660        );
2661
2662        assert_eq!(
2663            classify_provider_failure(&err),
2664            ProviderFailureClass::RateLimit
2665        );
2666        let policy = retry_policy(&err);
2667        assert!(policy.retry);
2668        assert_eq!(policy.max_attempts, RATE_LIMIT_MAX_COMPLETION_ATTEMPTS);
2669        assert_eq!(policy.base_backoff_ms, RATE_LIMIT_BASE_BACKOFF_MS);
2670        assert!(is_sticky_fallback_error(&err));
2671    }
2672
2673    #[test]
2674    fn exact_provider_codes_classify_without_http_status() {
2675        for code in [
2676            "authentication_error",
2677            "invalid_api_key",
2678            "permission_error",
2679        ] {
2680            let body = format!(r#"{{"error":{{"type":"{code}"}}}}"#);
2681            let err = provider_error(None, &body);
2682            assert!(is_non_retryable_client_error(&err), "{code}");
2683        }
2684
2685        for code in RATE_LIMIT_ERROR_CODES {
2686            let body = format!(r#"{{"error":{{"code":"{code}"}}}}"#);
2687            let err = provider_error(None, &body);
2688            assert!(is_rate_limit_error(&err), "{code}");
2689        }
2690    }
2691
2692    #[test]
2693    fn context_length_uses_exact_code_and_structured_message() {
2694        let openai = provider_error(Some(400), r#"{"error":{"code":"context_length_exceeded"}}"#);
2695        assert!(is_context_length_error(&openai));
2696
2697        let anthropic = provider_error(
2698            Some(400),
2699            r#"{"error":{"type":"invalid_request_error","message":"prompt is too long"}}"#,
2700        );
2701        assert!(is_context_length_error(&anthropic));
2702
2703        let malformed = provider_error(
2704            Some(400),
2705            r#"{"error":{"type":"invalid_request_error","message":"tools[0] is invalid"}}"#,
2706        );
2707        assert!(!is_context_length_error(&malformed));
2708        assert!(is_non_retryable_client_error(&malformed));
2709    }
2710
2711    #[test]
2712    fn provider_json_status_hint_handles_success_error_envelopes() {
2713        let err = provider_error(
2714            Some(200),
2715            r#"{"error":{"code":429,"type":"rate_limit_error","message":"slow down"}}"#,
2716        );
2717        assert_eq!(provider_http_status(&err), Some(429));
2718        assert!(is_rate_limit_error(&err));
2719    }
2720
2721    #[test]
2722    fn text_provider_body_only_uses_the_quota_message_fallback() {
2723        for status in [403, 429] {
2724            let err = provider_error(
2725                Some(status),
2726                "You've reached your usage limit for this billing cycle; refresh in the next cycle",
2727            );
2728            assert!(is_long_window_quota_error(&err));
2729            assert!(!retry_policy(&err).retry);
2730            assert!(is_sticky_fallback_error(&err));
2731        }
2732
2733        let err = provider_error(Some(429), "insufficient_quota in a non-JSON response");
2734        // Arbitrary body text is not scanned for codes; the captured 429 still classifies.
2735        assert!(is_rate_limit_error(&err));
2736
2737        let statusless = provider_error(None, "insufficient_quota in a non-JSON response");
2738        assert_eq!(
2739            classify_provider_failure(&statusless),
2740            ProviderFailureClass::Unknown
2741        );
2742        assert!(!is_sticky_fallback_error(&statusless));
2743    }
2744
2745    #[test]
2746    fn top_level_status_hint_precedes_nested_numeric_codes() {
2747        let err = provider_error(
2748            Some(200),
2749            r#"{"statusCode":502,"upstream":{"error":{"code":403,"type":"insufficient_quota"}}}"#,
2750        );
2751        assert_eq!(provider_http_status(&err), Some(502));
2752        assert_eq!(
2753            classify_provider_failure(&err),
2754            ProviderFailureClass::Server
2755        );
2756        assert!(!is_sticky_fallback_error(&err));
2757    }
2758
2759    #[test]
2760    fn compact_provider_error_body_keeps_large_json_classifiable() {
2761        let body = json!({
2762            "error": {
2763                "type": "usage_limit_reached",
2764                "message": "quota exhausted",
2765                "diagnostic": "x".repeat(4_000),
2766            }
2767        })
2768        .to_string();
2769        let compact = compact_provider_error_body(&body, 1_000);
2770        serde_json::from_str::<Value>(&compact).expect("compacted provider body stays valid JSON");
2771        let err = provider_error(Some(429), &compact);
2772        assert!(is_long_window_quota_error(&err));
2773    }
2774
2775    #[test]
2776    fn provider_error_truncation_reuses_utf8_boundary_handling() {
2777        assert_eq!(truncate_utf8("aéz", 2), "a…");
2778    }
2779
2780    #[test]
2781    fn openrouter_normalization_preserves_typed_provider_source() {
2782        let err = normalize_openrouter_completion_error(CompletionError::from_http_response(
2783            reqwest::StatusCode::TOO_MANY_REQUESTS,
2784            r#"{"error":{"type":"insufficient_quota"}}"#,
2785        ));
2786        assert_eq!(provider_http_status(&err), Some(429));
2787        assert!(is_long_window_quota_error(&err));
2788    }
2789
2790    fn tool_call_content() -> AssistantContent {
2791        use rig_core::completion::message::ToolFunction;
2792        AssistantContent::ToolCall(ToolCall::new(
2793            "call-1".to_string(),
2794            ToolFunction::new("read_file".to_string(), serde_json::json!({ "path": "x" })),
2795        ))
2796    }
2797
2798    /// Providers can pair tool calls with `stop`-like wire reasons; `tool_calls()` only
2799    /// surfaces calls under `ToolUse`, so the override losing would silently end the agent loop.
2800    #[test]
2801    fn a_structured_tool_call_overrides_any_wire_finish_reason() {
2802        let alone = OneOrMany::one(tool_call_content());
2803        let beside_text = OneOrMany::many(vec![
2804            AssistantContent::text("narration before the call"),
2805            tool_call_content(),
2806        ])
2807        .expect("two items");
2808        for choice in [alone, beside_text] {
2809            for wire in [
2810                FinishReason::Stop,
2811                FinishReason::MaxTokens,
2812                FinishReason::None,
2813                FinishReason::Other("length_capped".to_string()),
2814            ] {
2815                assert_eq!(resolve_finish_reason(&choice, wire), FinishReason::ToolUse);
2816            }
2817        }
2818    }
2819
2820    #[test]
2821    fn without_tool_calls_the_wire_finish_reason_stands() {
2822        let choice = OneOrMany::one(AssistantContent::text("done"));
2823        for wire in [
2824            FinishReason::Stop,
2825            FinishReason::MaxTokens,
2826            FinishReason::None,
2827            FinishReason::Other("content_filter".to_string()),
2828        ] {
2829            assert_eq!(resolve_finish_reason(&choice, wire.clone()), wire);
2830        }
2831    }
2832}