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