Skip to main content

nitpicker_agent/
llm.rs

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