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