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] = &[
957    "insufficient_quota",
958    "usage_limit_reached",
959    "subscription:free-usage-exhausted",
960    "subscription:usage-exhausted",
961];
962
963#[derive(Debug, Clone, Copy, PartialEq, Eq)]
964enum ProviderFailureClass {
965    Server,
966    PermanentQuota,
967    RateLimit,
968    ContextLength,
969    NonRetryableClient,
970    Unknown,
971}
972
973impl ProviderFailureClass {
974    /// Stable `error.type` vocabulary for the `llm.attempt` span.
975    fn as_str(self) -> &'static str {
976        match self {
977            Self::Server => "server",
978            Self::PermanentQuota => "permanent_quota",
979            Self::RateLimit => "rate_limit",
980            Self::ContextLength => "context_length",
981            Self::NonRetryableClient => "non_retryable_client",
982            Self::Unknown => "unknown",
983        }
984    }
985}
986
987#[derive(Debug, Default)]
988struct ProviderErrorFacts {
989    status: Option<u16>,
990    body_status: Option<u16>,
991    body_code_status: Option<u16>,
992    codes: Vec<String>,
993    messages: Vec<String>,
994}
995
996impl ProviderErrorFacts {
997    fn from_report(err: &eyre::Report) -> Option<Self> {
998        let completion_error = err
999            .chain()
1000            .find_map(|source| source.downcast_ref::<ProviderError>())?;
1001        let mut facts = Self {
1002            status: completion_error
1003                .provider_response_status()
1004                .map(|status| status.as_u16()),
1005            ..Self::default()
1006        };
1007        match completion_error.provider_response_json() {
1008            Ok(Some(body)) => {
1009                collect_provider_status_hints(&body, &mut facts);
1010                collect_provider_error_fields(&body, &mut facts);
1011            }
1012            Err(_) => {
1013                if let Some(body) = completion_error.provider_response_body() {
1014                    // Some compatible gateways return text/plain. This is the sole unstructured
1015                    // compatibility input: it is still the provider body, never the rendered
1016                    // eyre chain or surrounding diagnostic text.
1017                    facts.messages.push(body.to_string());
1018                }
1019            }
1020            Ok(None) => {}
1021        }
1022        Some(facts)
1023    }
1024
1025    fn effective_status(&self) -> Option<u16> {
1026        match self.status {
1027            Some(status) if !(200..300).contains(&status) => Some(status),
1028            _ => self.body_status.or(self.body_code_status).or(self.status),
1029        }
1030    }
1031
1032    fn has_code(&self, expected: &[&str]) -> bool {
1033        self.codes
1034            .iter()
1035            .any(|code| expected.contains(&code.as_str()))
1036    }
1037}
1038
1039fn numeric_field(object: &serde_json::Map<String, Value>, keys: &[&str]) -> Option<u16> {
1040    keys.iter().find_map(|key| {
1041        object
1042            .get(*key)
1043            .and_then(Value::as_u64)
1044            .and_then(|value| u16::try_from(value).ok())
1045    })
1046}
1047
1048/// Rank body-carried status hints by their semantic position instead of whichever numeric field a
1049/// recursive traversal happens to encounter first. Top-level status fields describe an envelope;
1050/// a numeric provider `code` is only a fallback for 2xx/statusless error envelopes.
1051fn collect_provider_status_hints(value: &Value, facts: &mut ProviderErrorFacts) {
1052    let Some(root) = value.as_object() else {
1053        return;
1054    };
1055    facts.body_status = numeric_field(root, &["status", "statusCode", "status_code"]);
1056    facts.body_code_status = numeric_field(root, &["code"]);
1057
1058    if let Some(error) = root.get("error").and_then(Value::as_object) {
1059        facts.body_status = facts
1060            .body_status
1061            .or_else(|| numeric_field(error, &["status", "statusCode", "status_code"]));
1062        facts.body_code_status = facts
1063            .body_code_status
1064            .or_else(|| numeric_field(error, &["code"]));
1065    }
1066}
1067
1068/// Collect only semantically named scalar fields from a provider JSON error envelope. Recursing
1069/// covers gateway shapes such as `{ "upstream": { "error": ... } }`; the real outer HTTP status
1070/// is stored separately and always wins over nested provider facts.
1071fn collect_provider_error_fields(value: &Value, facts: &mut ProviderErrorFacts) {
1072    match value {
1073        Value::Object(object) => {
1074            for (key, value) in object {
1075                match (key.as_str(), value) {
1076                    ("code" | "type" | "status" | "error_type", Value::String(value)) => {
1077                        facts.codes.push(value.to_ascii_lowercase());
1078                    }
1079                    ("message", Value::String(value)) => facts.messages.push(value.clone()),
1080                    _ => collect_provider_error_fields(value, facts),
1081                }
1082            }
1083        }
1084        Value::Array(values) => {
1085            for value in values {
1086                collect_provider_error_fields(value, facts);
1087            }
1088        }
1089        _ => {}
1090    }
1091}
1092
1093/// Keep Codex's stored provider error bounded without turning valid JSON into an unparseable
1094/// prefix. Large structured bodies are projected to the exact facts used by the classifier;
1095/// malformed/text bodies retain the old bounded-prefix behavior.
1096pub(crate) fn compact_provider_error_body(body: &str, compact_above_bytes: usize) -> String {
1097    if body.len() <= compact_above_bytes {
1098        return body.to_string();
1099    }
1100    let Ok(value) = serde_json::from_str::<Value>(body) else {
1101        return truncate_utf8(body, compact_above_bytes);
1102    };
1103    let mut facts = ProviderErrorFacts::default();
1104    collect_provider_status_hints(&value, &mut facts);
1105    collect_provider_error_fields(&value, &mut facts);
1106    let codes = facts
1107        .codes
1108        .into_iter()
1109        .take(16)
1110        .map(|code| serde_json::json!({ "code": truncate_utf8(&code, 128) }))
1111        .collect::<Vec<_>>();
1112    let messages = facts
1113        .messages
1114        .into_iter()
1115        .take(4)
1116        .map(|message| serde_json::json!({ "message": truncate_utf8(&message, 512) }))
1117        .collect::<Vec<_>>();
1118    serde_json::json!({
1119        "status": facts.body_status,
1120        "code": facts.body_code_status,
1121        "details": codes,
1122        "messages": messages,
1123    })
1124    .to_string()
1125}
1126
1127fn truncate_utf8(value: &str, max_bytes: usize) -> String {
1128    if value.len() <= max_bytes {
1129        return value.to_string();
1130    }
1131    let end = floor_char_boundary(value, max_bytes);
1132    format!("{}…", &value[..end])
1133}
1134
1135fn classify_provider_failure(err: &eyre::Report) -> ProviderFailureClass {
1136    let Some(facts) = ProviderErrorFacts::from_report(err) else {
1137        return ProviderFailureClass::Unknown;
1138    };
1139    let status = facts.effective_status();
1140
1141    // Anthropic defines a captured HTTP 529 carrying `overloaded_error` as provider overload. It
1142    // follows the longer overload/throttling policy; an arbitrary gateway 5xx with a nested
1143    // overload payload must still retain normal server-error precedence.
1144    if facts.status == Some(529) && facts.has_code(&["overloaded_error"]) {
1145        return ProviderFailureClass::RateLimit;
1146    }
1147    // The captured HTTP status is otherwise the outer response. A gateway 5xx therefore remains
1148    // transient even when its JSON body embeds an upstream quota or client-error payload.
1149    if status.is_some_and(|status| (500..600).contains(&status)) {
1150        return ProviderFailureClass::Server;
1151    }
1152    if facts.has_code(PERMANENT_QUOTA_ERROR_CODES)
1153        || facts
1154            .messages
1155            .iter()
1156            .any(|message| is_long_window_quota_message(message))
1157    {
1158        return ProviderFailureClass::PermanentQuota;
1159    }
1160    if facts.has_code(RATE_LIMIT_ERROR_CODES) || status == Some(429) {
1161        return ProviderFailureClass::RateLimit;
1162    }
1163    if facts.has_code(&["context_length_exceeded"])
1164        || (facts.has_code(&["invalid_request_error"])
1165            && facts
1166                .messages
1167                .iter()
1168                .any(|message| message.to_ascii_lowercase().contains("prompt is too long")))
1169    {
1170        return ProviderFailureClass::ContextLength;
1171    }
1172    if facts.has_code(NON_RETRYABLE_ERROR_CODES)
1173        || status.is_some_and(|status| (400..=404).contains(&status))
1174    {
1175        return ProviderFailureClass::NonRetryableClient;
1176    }
1177    ProviderFailureClass::Unknown
1178}
1179
1180pub(crate) fn provider_http_status(err: &eyre::Report) -> Option<u16> {
1181    ProviderErrorFacts::from_report(err).and_then(|facts| facts.effective_status())
1182}
1183
1184pub(crate) fn provider_error_has_code(err: &eyre::Report, expected: &[&str]) -> bool {
1185    ProviderErrorFacts::from_report(err).is_some_and(|facts| facts.has_code(expected))
1186}
1187
1188/// Whether an error chain reports a context-window overflow — the one synthesis failure
1189/// where "select fewer presets" is real remediation. Matches the OpenAI-style type token
1190/// (`context_length_exceeded`) and the Anthropic shape — an `invalid_request_error` whose
1191/// message says the prompt is too long; a generic `invalid_request_error` alone does NOT
1192/// qualify (those are malformed-request bugs, not size problems).
1193pub fn is_context_length_error(err: &eyre::Report) -> bool {
1194    classify_provider_failure(err) == ProviderFailureClass::ContextLength
1195}
1196
1197#[cfg(test)]
1198fn is_non_retryable_client_error(err: &eyre::Report) -> bool {
1199    matches!(
1200        classify_provider_failure(err),
1201        ProviderFailureClass::ContextLength | ProviderFailureClass::NonRetryableClient
1202    )
1203}
1204
1205#[cfg(test)]
1206fn is_rate_limit_error(err: &eyre::Report) -> bool {
1207    classify_provider_failure(err) == ProviderFailureClass::RateLimit
1208}
1209
1210#[cfg(test)]
1211fn is_long_window_quota_error(err: &eyre::Report) -> bool {
1212    classify_provider_failure(err) == ProviderFailureClass::PermanentQuota
1213}
1214
1215fn is_long_window_quota_message(msg: &str) -> bool {
1216    let msg = msg.to_ascii_lowercase();
1217    msg.contains("out of tokens")
1218        || msg.contains("hit your usage limit")
1219        || msg.contains("usage limit has been reached")
1220        || ((msg.contains("usage limit") || msg.contains("token limit"))
1221            && (msg.contains("window")
1222                || msg.contains("reset")
1223                || msg.contains("refresh")
1224                || msg.contains("billing cycle")
1225                || msg.contains("next cycle")
1226                || msg.contains("5h")
1227                || msg.contains("5 h")
1228                || msg.contains("5 hour")))
1229}
1230
1231/// Whether an error represents an operational provider limit that cannot recover during this run.
1232/// CLI layers use this to present a concise message while retaining the full report at debug level.
1233pub fn is_operational_limit_error(err: &eyre::Report) -> bool {
1234    is_sticky_fallback_error(err)
1235}
1236
1237fn is_sticky_fallback_error(err: &eyre::Report) -> bool {
1238    matches!(
1239        classify_provider_failure(err),
1240        ProviderFailureClass::PermanentQuota | ProviderFailureClass::RateLimit
1241    )
1242}
1243
1244fn jittered_backoff(attempt: usize, base_backoff_ms: u64, max_backoff_ms: u64) -> Duration {
1245    let exp = 2u64.saturating_pow((attempt - 1) as u32);
1246    let base = (base_backoff_ms * exp).min(max_backoff_ms);
1247    let jitter = jitter_factor();
1248    let jittered = (base as f64 * jitter).round() as u64;
1249    Duration::from_millis(jittered.max(1))
1250}
1251
1252fn jitter_factor() -> f64 {
1253    let nanos = SystemTime::now()
1254        .duration_since(UNIX_EPOCH)
1255        .map(|d| d.subsec_nanos())
1256        .unwrap_or(0);
1257    let scaled = (nanos % 1000) as f64 / 1000.0;
1258    0.5 + scaled
1259}
1260
1261fn normalize_completion_error(err: ProviderError) -> eyre::Report {
1262    let empty_response = matches!(
1263        &err,
1264        ProviderError::Response(msg)
1265            if msg.contains("no message or tool call") || msg.contains("no choices")
1266    );
1267    let report = eyre::Report::new(err);
1268    if empty_response {
1269        report.wrap_err("empty response from model (no message or tool call)")
1270    } else {
1271        report
1272    }
1273}
1274
1275/// OpenRouter fails a Gemini turn over between upstreams (Vertex, AI Studio), and each rejects
1276/// a thought signature the other minted with a 400 that names it only in the gateway's `raw`
1277/// upstream text. History without signatures is accepted.
1278fn is_foreign_thought_signature_rejection(err: &ProviderError) -> bool {
1279    fn raw_mentions_signature(value: &Value) -> bool {
1280        match value {
1281            Value::Object(object) => {
1282                object
1283                    .iter()
1284                    .any(|(key, value)| match (key.as_str(), value) {
1285                        ("raw", Value::String(raw)) => {
1286                            raw.to_ascii_lowercase().contains("thought signature")
1287                        }
1288                        _ => raw_mentions_signature(value),
1289                    })
1290            }
1291            Value::Array(values) => values.iter().any(raw_mentions_signature),
1292            _ => false,
1293        }
1294    }
1295    let status = err.provider_response_status().map(|status| status.as_u16());
1296    match (status, err.provider_response_json()) {
1297        (Some(400), Ok(Some(body))) => raw_mentions_signature(&body),
1298        _ => false,
1299    }
1300}
1301
1302/// The request with every reasoning block dropped from its history; an assistant message left
1303/// with no content is dropped whole. `None` when nothing but reasoning was sent.
1304fn without_reasoning(
1305    mut request: rig_core::completion::CompletionRequest,
1306) -> Option<rig_core::completion::CompletionRequest> {
1307    request
1308        .chat_history
1309        .retain_mut(|message| match Arc::make_mut(message) {
1310            Message::Assistant(turn) => {
1311                turn.content
1312                    .retain(|item| !matches!(item, AssistantContent::Reasoning(_)));
1313                !turn.content.is_empty()
1314            }
1315            _ => true,
1316        });
1317    (!request.chat_history.is_empty()).then_some(request)
1318}
1319
1320fn is_local_base_url(base_url: Option<&str>) -> bool {
1321    base_url
1322        .map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
1323        .unwrap_or(false)
1324}
1325
1326/// Resolve the API key when its env var is unset: a local base_url needs no real key, otherwise it
1327/// is a hard error naming the missing var.
1328fn missing_or_local(key_env: &str, base_url: Option<&str>) -> Result<String> {
1329    if is_local_base_url(base_url) {
1330        Ok("local".to_string())
1331    } else {
1332        Err(eyre::eyre!("missing env var {key_env}"))
1333    }
1334}
1335
1336pub enum LLMProvider {
1337    Anthropic {
1338        base_url: Option<String>,
1339        api_key_env: Option<String>,
1340    },
1341    Gemini {
1342        base_url: Option<String>,
1343        api_key_env: Option<String>,
1344    },
1345    OpenAi {
1346        base_url: Option<String>,
1347        api_key_env: Option<String>,
1348    },
1349    OpenRouter {
1350        api_key_env: String,
1351    },
1352    OpenCode {
1353        service: OpenCodeService,
1354        base_url: Option<String>,
1355        api_key_env: Option<String>,
1356    },
1357}
1358
1359#[derive(Clone, Copy)]
1360pub enum OpenCodeService {
1361    Console,
1362    Go,
1363}
1364
1365tokio::task_local! {
1366    pub(crate) static OPENCODE_SESSION: String;
1367}
1368
1369impl LLMProvider {
1370    pub fn client_from_env(&self) -> Result<Box<dyn LLMClientDyn>> {
1371        match self {
1372            LLMProvider::Anthropic {
1373                base_url,
1374                api_key_env,
1375            } => {
1376                // First-party Anthropic supports cache_control. An arbitrary compatible gateway
1377                // may reject that field, so custom base URLs keep the legacy request shape unless
1378                // they are constructed explicitly as an AnthropicPromptCachingClient.
1379                let enable_prompt_caching = base_url.is_none();
1380                let key_env = api_key_env.as_deref().unwrap_or("ANTHROPIC_API_KEY");
1381                let api_key = std::env::var(key_env)
1382                    .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
1383                let config = anthropic::AnthropicConfig::new(api_key);
1384                let config = match base_url {
1385                    Some(url) => config.with_base_url(url),
1386                    None => config,
1387                };
1388                Ok(Box::new(RigClient::Anthropic(
1389                    config,
1390                    enable_prompt_caching,
1391                )))
1392            }
1393            LLMProvider::Gemini {
1394                base_url,
1395                api_key_env,
1396            } => {
1397                // An explicit api_key_env overrides the GEMINI_API_KEY → GOOGLE_AI_API_KEY default
1398                // chain; a local base_url needs no key (mirrors the Anthropic/OpenAi arms).
1399                let api_key = match api_key_env {
1400                    Some(key_env) => std::env::var(key_env)
1401                        .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?,
1402                    None => std::env::var("GEMINI_API_KEY")
1403                        .or_else(|_| std::env::var("GOOGLE_AI_API_KEY"))
1404                        .or_else(|_| {
1405                            missing_or_local(
1406                                "GEMINI_API_KEY (or GOOGLE_AI_API_KEY)",
1407                                base_url.as_deref(),
1408                            )
1409                        })?,
1410                };
1411                let config = gemini::GeminiConfig::new(api_key);
1412                let config = match base_url {
1413                    Some(url) => config.with_base_url(url),
1414                    None => config,
1415                };
1416                Ok(Box::new(RigClient::Gemini(
1417                    config.connect(ReqwestClient::default()),
1418                )))
1419            }
1420            LLMProvider::OpenAi {
1421                base_url,
1422                api_key_env,
1423            } => {
1424                let key_env = api_key_env.as_deref().unwrap_or("OPENAI_API_KEY");
1425                let api_key = std::env::var(key_env)
1426                    .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
1427                Ok(Box::new(RigClient::openai(api_key, base_url.as_deref())))
1428            }
1429            LLMProvider::OpenRouter { api_key_env } => {
1430                let api_key = std::env::var(api_key_env)
1431                    .map_err(|_| eyre::eyre!("missing env var {api_key_env}"))?;
1432                Ok(Box::new(RigClient::openrouter(&api_key)?))
1433            }
1434            LLMProvider::OpenCode {
1435                service,
1436                base_url,
1437                api_key_env,
1438            } => {
1439                let key_env = api_key_env.as_deref().unwrap_or("OPENCODE_API_KEY");
1440                let key = std::env::var(key_env)
1441                    .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
1442                let http = reqwest::Client::builder()
1443                    .user_agent(concat!("nitpicker-agent/", env!("CARGO_PKG_VERSION")))
1444                    .build()?;
1445                Ok(Box::new(OpenCodeClient {
1446                    service: *service,
1447                    key: key.into(),
1448                    base_url: base_url.clone(),
1449                    http: ReqwestClient::from(http),
1450                }))
1451            }
1452        }
1453    }
1454}
1455
1456struct OpenCodeClient {
1457    service: OpenCodeService,
1458    key: rig_core::wire::Secret,
1459    base_url: Option<String>,
1460    http: ReqwestClient,
1461}
1462
1463impl LLMClient for OpenCodeClient {
1464    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
1465        use rig_core::{catalog::Catalog, providers::registry::ConnectOptions};
1466        let provider = match self.service {
1467            OpenCodeService::Console => "opencode",
1468            OpenCodeService::Go => "opencode-go",
1469        };
1470        let model_name = completion.model.clone();
1471        let reference = format!("{provider}/{model_name}");
1472        let mut options = ConnectOptions::new()
1473            .api_key(self.key.clone())
1474            .http(self.http.clone());
1475        if let Some(url) = &self.base_url {
1476            options = options.base_url(url);
1477        }
1478        let model = Catalog::builtin().connect_with(reference.as_str(), options)?;
1479        let mut request = CompletionRequest::from(completion);
1480        if matches!(self.service, OpenCodeService::Go) {
1481            request.options.cache_key = Some(
1482                OPENCODE_SESSION
1483                    .try_with(String::clone)
1484                    .unwrap_or_else(|_| uuid::Uuid::new_v4().to_string()),
1485            );
1486        }
1487        let response = model
1488            .call(request)
1489            .await
1490            .map_err(normalize_completion_error)
1491            .wrap_err_with(|| format!("{provider} completion failed for model '{model_name}'"))?;
1492        Ok(CompletionResponse::from_rig(response, model_name))
1493    }
1494}
1495
1496pub fn openrouter_headers() -> Result<reqwest::header::HeaderMap> {
1497    let mut headers = reqwest::header::HeaderMap::new();
1498    headers.insert(
1499        "HTTP-Referer",
1500        "https://github.com/arsenyinfo/nitpicker".parse()?,
1501    );
1502    headers.insert("X-OpenRouter-Title", "nitpicker".parse()?);
1503    headers.insert(
1504        "X-OpenRouter-Categories",
1505        "cli-agent,programming-app".parse()?,
1506    );
1507    Ok(headers)
1508}
1509
1510pub(crate) enum RigClient {
1511    Anthropic(anthropic::AnthropicConfig, bool),
1512    Gemini(gemini::Gemini),
1513    OpenAi(openai::OpenAI),
1514    OpenRouter(openai::OpenAI),
1515}
1516
1517impl RigClient {
1518    pub(crate) fn openai(key: impl Into<rig_core::wire::Secret>, base_url: Option<&str>) -> Self {
1519        let config = openai::OpenAIConfig::new(key).with_route(openai::wire::Route::Chat);
1520        let config = match base_url {
1521            Some(url) => config.with_base_url(url),
1522            None => config,
1523        };
1524        Self::OpenAi(config.connect(ReqwestClient::default()))
1525    }
1526
1527    pub(crate) fn openrouter(key: &str) -> Result<Self> {
1528        let config = openai::OpenAIConfig::with_key(&openai::wire::OPENROUTER, key);
1529        let http = reqwest::Client::builder()
1530            .default_headers(openrouter_headers()?)
1531            .build()?;
1532        Ok(Self::OpenRouter(config.connect(ReqwestClient::from(http))))
1533    }
1534}
1535
1536impl LLMClient for RigClient {
1537    async fn completion(&self, mut completion: Completion) -> Result<CompletionResponse> {
1538        let model_name = completion.model.clone();
1539        if matches!(self, Self::OpenAi(_))
1540            && model_needs_max_completion_tokens(&model_name)
1541            && let Some(max) = completion.max_tokens.take()
1542        {
1543            let extra = serde_json::json!({ "max_completion_tokens": max });
1544            completion.additional_params = Some(match completion.additional_params.take() {
1545                Some(existing) => merge_json(existing, extra),
1546                None => extra,
1547            });
1548        }
1549        let mut request = CompletionRequest::from(completion);
1550        let response = match self {
1551            Self::Anthropic(config, caching) => {
1552                request.max_tokens.get_or_insert(ANTHROPIC_DEFAULT_MAX_TOKENS);
1553                let wire = config.completion(&model_name);
1554                let wire = match caching {
1555                    true => {
1556                        request.options.cache = Some(rig_core::completion::CacheRetention::Short);
1557                        wire.with_prompt_caching()
1558                    }
1559                    false => wire.with_tool_input_streaming(anthropic::ToolInputStreaming::Off),
1560                };
1561                rig_core::Model::new(wire, ReqwestClient::default()).call(request).await
1562            }
1563            Self::Gemini(client) => client.completion(&model_name).call(request).await,
1564            Self::OpenAi(client) => client.completion(&model_name).call(request).await,
1565            Self::OpenRouter(client) => {
1566                let model = client.completion(&model_name);
1567                match model.call(request.clone()).await {
1568            Err(err) if is_foreign_thought_signature_rejection(&err) => {
1569                match without_reasoning(request) {
1570                    Some(stripped) => {
1571                        warn!(
1572                            model = %model_name,
1573                            "upstream rejected a replayed thought signature; retrying without reasoning history"
1574                        );
1575                        model.call(stripped).await
1576                    }
1577                    None => Err(err),
1578                }
1579            }
1580            other => other,
1581                }
1582            }
1583        }
1584        .map_err(normalize_completion_error)
1585        .wrap_err_with(|| format!("completion failed for model '{model_name}'"))?;
1586        Ok(CompletionResponse::from_rig(response, model_name))
1587    }
1588}
1589
1590/// Create a Gemini client that routes through the local OAuth proxy
1591#[cfg(feature = "antigravity")]
1592pub fn create_gemini_client_with_proxy(
1593    proxy_url: &str,
1594) -> Result<std::sync::Arc<dyn LLMClientDyn>> {
1595    // Build a Gemini client with the proxy URL as the base URL
1596    // The API key doesn't matter for OAuth proxy, but is required by the builder
1597    let api_key = std::env::var("GEMINI_API_KEY").unwrap_or_else(|_| "oauth-proxy".to_string());
1598    let client = RigClient::Gemini(
1599        gemini::GeminiConfig::new(api_key)
1600            .with_base_url(proxy_url)
1601            .connect(ReqwestClient::default()),
1602    );
1603    Ok(client.with_retry().into_arc())
1604}
1605
1606fn model_needs_max_completion_tokens(model: &str) -> bool {
1607    model.starts_with("o1")
1608        || model.starts_with("o3")
1609        || model.starts_with("o4")
1610        || model.starts_with("gpt-4o")
1611        || model.starts_with("gpt-4.1")
1612        || model.starts_with("gpt-4.5")
1613        || model.starts_with("gpt-5")
1614        || model.starts_with("gpt-6")
1615}
1616
1617/// Deep-merge `extra` over `base`: nested objects are merged recursively; on a scalar/type
1618/// conflict `extra` wins. Used to overlay computed request params without discarding caller-set
1619/// ones (e.g. a Gemini `generation_config` the caller supplied alongside its own keys).
1620pub(crate) fn merge_json(base: Value, extra: Value) -> Value {
1621    match (base, extra) {
1622        (Value::Object(mut base_obj), Value::Object(extra_obj)) => {
1623            for (k, v) in extra_obj {
1624                let merged = match base_obj.remove(&k) {
1625                    Some(existing) => merge_json(existing, v),
1626                    None => v,
1627                };
1628                base_obj.insert(k, merged);
1629            }
1630            Value::Object(base_obj)
1631        }
1632        (_, extra) => extra,
1633    }
1634}
1635
1636/// A structured tool call in the choice overrides the wire finish reason: providers can pair
1637/// tool calls with `stop`-like reasons, and `CompletionResponse::tool_calls()` only surfaces
1638/// calls when the reason is `ToolUse`.
1639fn resolve_finish_reason(choice: &[AssistantContent], wire_reason: FinishReason) -> FinishReason {
1640    match choice
1641        .iter()
1642        .any(|content| matches!(content, AssistantContent::ToolCall(_)))
1643    {
1644        true => FinishReason::ToolUse,
1645        false => wire_reason,
1646    }
1647}
1648
1649#[cfg(test)]
1650mod tests {
1651    use super::*;
1652    use rig_core::ProviderError as CompletionError;
1653    use rig_core::completion::Usage;
1654    use rig_core::message::{CallId, ToolName};
1655    use std::sync::Mutex as StdMutex;
1656    use tokio::io::{AsyncReadExt, AsyncWriteExt};
1657    use tokio::net::TcpListener;
1658
1659    fn strip_think_blocks(text: &str) -> String {
1660        scan_think_blocks(text).0
1661    }
1662    use serde_json::json;
1663
1664    fn response_with(choice: Vec<AssistantContent>) -> CompletionResponse {
1665        CompletionResponse {
1666            choice,
1667            origin: None,
1668            finish_reason: FinishReason::Stop,
1669            usage: TokenUsage::default(),
1670            selected_model: None,
1671        }
1672    }
1673
1674    struct RecordingClient {
1675        fail: bool,
1676        calls: Arc<StdMutex<Vec<Completion>>>,
1677    }
1678
1679    impl LLMClient for RecordingClient {
1680        async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
1681            self.calls.lock().unwrap().push(completion);
1682            if self.fail {
1683                eyre::bail!("route failed");
1684            }
1685            Ok(response_with(vec![AssistantContent::text("ok")]))
1686        }
1687    }
1688
1689    fn recording_slot(
1690        model: &str,
1691        max_tokens: Option<u64>,
1692        fail: bool,
1693    ) -> (FallbackSlot, Arc<StdMutex<Vec<Completion>>>) {
1694        let calls = Arc::new(StdMutex::new(Vec::new()));
1695        let client = RecordingClient {
1696            fail,
1697            calls: Arc::clone(&calls),
1698        }
1699        .into_arc();
1700        (FallbackSlot::new(client, model, max_tokens), calls)
1701    }
1702
1703    fn test_completion() -> Completion {
1704        Completion {
1705            model: "logical-primary".to_string(),
1706            prompt: Message::user("continue"),
1707            preamble: Some("system".to_string()),
1708            history: vec![Message::user("prior work")],
1709            tools: Vec::new(),
1710            tool_choice: None,
1711            max_tokens: Some(999),
1712            additional_params: None,
1713        }
1714    }
1715
1716    async fn exchange_http(listener: &TcpListener, response_body: Value) -> (String, Value) {
1717        let (mut socket, _) = listener.accept().await.unwrap();
1718        let mut request = Vec::new();
1719        let header_end = loop {
1720            let mut chunk = [0_u8; 4096];
1721            let read = socket.read(&mut chunk).await.unwrap();
1722            assert!(read > 0, "client closed before sending HTTP headers");
1723            request.extend_from_slice(&chunk[..read]);
1724            if let Some(index) = request.windows(4).position(|w| w == b"\r\n\r\n") {
1725                break index + 4;
1726            }
1727        };
1728        let headers = String::from_utf8_lossy(&request[..header_end]);
1729        let content_length = headers
1730            .lines()
1731            .find_map(|line| {
1732                let (name, value) = line.split_once(':')?;
1733                name.eq_ignore_ascii_case("content-length")
1734                    .then(|| value.trim().parse::<usize>().unwrap())
1735            })
1736            .expect("request must carry content-length");
1737        while request.len() < header_end + content_length {
1738            let mut chunk = [0_u8; 4096];
1739            let read = socket.read(&mut chunk).await.unwrap();
1740            assert!(read > 0, "client closed before sending the request body");
1741            request.extend_from_slice(&chunk[..read]);
1742        }
1743
1744        let response_body = response_body.to_string();
1745        let response = format!(
1746            "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{response_body}",
1747            response_body.len()
1748        );
1749        socket.write_all(response.as_bytes()).await.unwrap();
1750        (
1751            String::from_utf8(request[..header_end].to_vec()).unwrap(),
1752            serde_json::from_slice::<Value>(&request[header_end..header_end + content_length])
1753                .unwrap(),
1754        )
1755    }
1756
1757    #[tokio::test]
1758    async fn anthropic_first_party_policy_emits_cache_control_on_the_wire() {
1759        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1760        let address = listener.local_addr().unwrap();
1761        let server = tokio::spawn(async move {
1762            exchange_http(
1763                &listener,
1764                json!({
1765                    "content": [{ "type": "text", "text": "ok" }],
1766                    "id": "msg_test",
1767                    "model": "claude-test",
1768                    "role": "assistant",
1769                    "type": "message",
1770                    "stop_reason": "end_turn",
1771                    "stop_sequence": null,
1772                    "usage": {
1773                        "input_tokens": 52, "output_tokens": 8,
1774                        "cache_read_input_tokens": 3456, "cache_creation_input_tokens": 120
1775                    }
1776                }),
1777            )
1778            .await
1779            .1
1780        });
1781
1782        let caching_client = RigClient::Anthropic(
1783            anthropic::AnthropicConfig::new("test-key").with_base_url(format!("http://{address}")),
1784            true,
1785        );
1786        let mut completion = test_completion();
1787        completion.model = "claude-test".to_string();
1788        completion.tools = vec![rig_core::completion::ToolDefinition {
1789            name: ToolName::new("read_file").unwrap(),
1790            annotations: Default::default(),
1791            description: "Read a file".to_string(),
1792            parameters: json!({
1793                "type": "object",
1794                "properties": { "path": { "type": "string" } },
1795                "required": ["path"]
1796            }),
1797        }];
1798
1799        let reply = LLMClient::completion(&caching_client, completion)
1800            .await
1801            .unwrap();
1802        assert_eq!(reply.usage.input_tokens, 3628);
1803        assert_eq!(reply.usage.cached_input_tokens, 3456);
1804        assert_eq!(reply.usage.cache_creation_input_tokens, 120);
1805        let body = server.await.unwrap();
1806        assert_eq!(body["cache_control"]["type"], "ephemeral");
1807        assert_eq!(body["system"][0]["cache_control"]["type"], "ephemeral");
1808        assert_eq!(
1809            body["tools"].as_array().unwrap().last().unwrap()["cache_control"]["type"],
1810            "ephemeral"
1811        );
1812    }
1813
1814    #[tokio::test]
1815    async fn opencode_go_routes_chat_and_keeps_its_session_across_turns() {
1816        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1817        let base_url = format!("http://{}", listener.local_addr().unwrap());
1818        let response = json!({
1819            "id": "chatcmpl_1", "created": 1, "object": "chat.completion", "model": "glm-5.3",
1820            "choices": [{
1821                "index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"
1822            }],
1823            "usage": {"prompt_tokens": 2, "completion_tokens": 1, "total_tokens": 3}
1824        });
1825        let server = tokio::spawn(async move {
1826            let first = exchange_http(&listener, json!({
1827                "id": "chatcmpl_tool", "created": 1, "object": "chat.completion", "model": "glm-5.3",
1828                "choices": [{
1829                    "index": 0, "finish_reason": "tool_calls",
1830                    "message": {"role": "assistant", "tool_calls": [{
1831                        "id": "call_1", "type": "function",
1832                        "function": {"name": "read_file", "arguments": "{\"path\":\"fixture.txt\"}"}
1833                    }]}
1834                }],
1835            })).await;
1836            let second = exchange_http(&listener, response).await;
1837            [first, second]
1838        });
1839        let client = LLMProvider::OpenCode {
1840            service: OpenCodeService::Go,
1841            base_url: Some(base_url),
1842            api_key_env: Some("NITPICKER_TEST_OPENCODE_LOOPBACK_KEY".to_string()),
1843        }
1844        .client_from_env()
1845        .unwrap();
1846        let dir = tempfile::tempdir().unwrap();
1847        std::fs::write(dir.path().join("fixture.txt"), "cobalt").unwrap();
1848        let answer = crate::AgentBuilder::new("test", "glm-5.3", "system", client.into_arc())
1849            .max_turns(3)
1850            .run("read the fixture", &crate::tools::all_tools(), dir.path())
1851            .await
1852            .unwrap();
1853        assert_eq!(answer.text, "ok");
1854        let requests = server.await.unwrap();
1855        let sessions = requests.each_ref().map(|(headers, body)| {
1856            let mut lines = headers.lines();
1857            assert_eq!(
1858                lines.next(),
1859                Some("POST /openai/v1/chat/completions HTTP/1.1")
1860            );
1861            let headers: std::collections::HashMap<_, _> =
1862                lines.filter_map(|line| line.split_once(": ")).collect();
1863            assert_eq!(
1864                headers.get("user-agent"),
1865                Some(&concat!("nitpicker-agent/", env!("CARGO_PKG_VERSION")))
1866            );
1867            assert_eq!(body["model"], "glm-5.3");
1868            uuid::Uuid::parse_str(headers["x-opencode-session"]).unwrap()
1869        });
1870        assert_eq!(sessions[0], sessions[1]);
1871        let tool_reply = requests[1].1["messages"]
1872            .as_array()
1873            .unwrap()
1874            .iter()
1875            .find(|message| message["role"] == "tool")
1876            .unwrap();
1877        assert_eq!(tool_reply["tool_call_id"], "call_1");
1878    }
1879
1880    #[tokio::test]
1881    async fn priority_client_uses_next_route_without_losing_the_completion() {
1882        let (first, first_calls) = recording_slot("first", Some(10), true);
1883        let (second, second_calls) = recording_slot("second", Some(20), false);
1884        let client = PriorityClient::new(vec![first, second]).unwrap();
1885
1886        let response = client.completion(test_completion()).await.unwrap();
1887
1888        assert_eq!(response.selected_model.as_deref(), Some("second"));
1889        {
1890            let first_guard = first_calls.lock().unwrap();
1891            let second_guard = second_calls.lock().unwrap();
1892            assert_eq!(first_guard.len(), 1);
1893            assert_eq!(second_guard.len(), 1);
1894            assert_eq!(first_guard[0].model, "first");
1895            assert_eq!(first_guard[0].max_tokens, Some(10));
1896            assert_eq!(second_guard[0].model, "second");
1897            assert_eq!(second_guard[0].max_tokens, Some(20));
1898            assert_eq!(second_guard[0].history.len(), 1);
1899            assert_eq!(second_guard[0].preamble.as_deref(), Some("system"));
1900        }
1901
1902        // A successful failover becomes this logical agent's active route, so the next turn does
1903        // not probe the failed primary again.
1904        client.completion(test_completion()).await.unwrap();
1905        assert_eq!(first_calls.lock().unwrap().len(), 1);
1906        assert_eq!(second_calls.lock().unwrap().len(), 2);
1907    }
1908
1909    #[tokio::test]
1910    async fn priority_clients_share_slots_without_sharing_stickiness() {
1911        let (failed, failed_calls) = recording_slot("failed", None, true);
1912        let (healthy, healthy_calls) = recording_slot("healthy", None, false);
1913        let first = PriorityClient::new(vec![failed.clone(), healthy.clone()]).unwrap();
1914        let independent = PriorityClient::new(vec![failed, healthy]).unwrap();
1915
1916        first.completion(test_completion()).await.unwrap();
1917        first.completion(test_completion()).await.unwrap();
1918        independent.completion(test_completion()).await.unwrap();
1919
1920        // The first logical agent sticks to its successful fallback, while the independent agent
1921        // still starts from its own primary. Shared slot state is tested separately for quota.
1922        assert_eq!(failed_calls.lock().unwrap().len(), 2);
1923        assert_eq!(healthy_calls.lock().unwrap().len(), 3);
1924    }
1925
1926    #[test]
1927    fn fallback_slot_clones_share_one_failover_warning_claim() {
1928        let (slot, _) = recording_slot("shared-route", None, false);
1929        let clone = slot.clone();
1930
1931        assert!(slot.claim_failover_warning());
1932        assert!(!clone.claim_failover_warning());
1933
1934        // Dedupe follows a concrete route, not its model string: distinct credentials using the
1935        // same model must each retain their own warning claim.
1936        let (same_model_distinct_route, _) = recording_slot("shared-route", None, false);
1937        assert!(same_model_distinct_route.claim_failover_warning());
1938    }
1939
1940    struct FailOnCallClient {
1941        calls: Arc<AtomicUsize>,
1942        fail_on: usize,
1943    }
1944
1945    impl LLMClient for FailOnCallClient {
1946        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
1947            let call = self.calls.fetch_add(1, Ordering::Relaxed) + 1;
1948            if call == self.fail_on {
1949                eyre::bail!("request-specific route failure")
1950            }
1951            Ok(response_with(vec![AssistantContent::text("ok")]))
1952        }
1953    }
1954
1955    #[tokio::test]
1956    async fn agent_fork_inherits_but_cannot_overwrite_parent_stickiness() {
1957        let first_calls = Arc::new(AtomicUsize::new(0));
1958        let second_calls = Arc::new(AtomicUsize::new(0));
1959        let first = FallbackSlot::new(
1960            FailOnCallClient {
1961                calls: Arc::clone(&first_calls),
1962                fail_on: 1,
1963            }
1964            .into_arc(),
1965            "first",
1966            None,
1967        );
1968        let second = FallbackSlot::new(
1969            FailOnCallClient {
1970                calls: Arc::clone(&second_calls),
1971                fail_on: 2,
1972            }
1973            .into_arc(),
1974            "second",
1975            None,
1976        );
1977        let parent = PriorityClient::new(vec![first, second]).unwrap();
1978
1979        // The parent fails over to `second`; the fork inherits that route, then independently
1980        // wraps back to `first` when its own request fails there.
1981        parent.completion(test_completion()).await.unwrap();
1982        let fork = parent.fork_for_agent().expect("priority clients can fork");
1983        fork.completion(test_completion()).await.unwrap();
1984        parent.completion(test_completion()).await.unwrap();
1985
1986        // The parent's final turn still starts on `second`. A shared active index would have made
1987        // it start on `first`, while a fork reset to zero would have skipped `second` initially.
1988        assert_eq!(first_calls.load(Ordering::Relaxed), 2);
1989        assert_eq!(second_calls.load(Ordering::Relaxed), 3);
1990    }
1991
1992    #[tokio::test]
1993    async fn priority_client_wraps_through_declaration_order() {
1994        let (first, first_calls) = recording_slot("first", None, false);
1995        let (second, second_calls) = recording_slot("second", None, true);
1996        let (third, third_calls) = recording_slot("third", None, true);
1997        // Production callers rotate the configured ring so the logical primary is first.
1998        let client = PriorityClient::new(vec![second, third, first]).unwrap();
1999
2000        let response = client.completion(test_completion()).await.unwrap();
2001
2002        assert_eq!(response.selected_model.as_deref(), Some("first"));
2003        assert_eq!(second_calls.lock().unwrap().len(), 1);
2004        assert_eq!(third_calls.lock().unwrap().len(), 1);
2005        assert_eq!(first_calls.lock().unwrap().len(), 1);
2006    }
2007
2008    struct MaxTokensClient {
2009        calls: Arc<AtomicUsize>,
2010    }
2011
2012    impl LLMClient for MaxTokensClient {
2013        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
2014            self.calls.fetch_add(1, Ordering::Relaxed);
2015            let mut response = response_with(vec![AssistantContent::text("partial")]);
2016            response.finish_reason = FinishReason::MaxTokens;
2017            response.usage.output_tokens = 10;
2018            Ok(response)
2019        }
2020    }
2021
2022    #[tokio::test]
2023    async fn priority_client_retries_truncated_response_on_the_next_route() {
2024        let truncated_calls = Arc::new(AtomicUsize::new(0));
2025        let truncated = FallbackSlot::new(
2026            MaxTokensClient {
2027                calls: Arc::clone(&truncated_calls),
2028            }
2029            .into_arc(),
2030            "truncated",
2031            Some(10),
2032        );
2033        let (healthy, healthy_calls) = recording_slot("healthy", Some(20), false);
2034        let client = PriorityClient::new(vec![truncated, healthy]).unwrap();
2035
2036        let response = client.completion(test_completion()).await.unwrap();
2037
2038        assert_eq!(response.selected_model.as_deref(), Some("healthy"));
2039        assert_eq!(truncated_calls.load(Ordering::Relaxed), 1);
2040        assert_eq!(healthy_calls.lock().unwrap().len(), 1);
2041    }
2042
2043    struct ToolUseClient {
2044        calls: Arc<AtomicUsize>,
2045    }
2046
2047    impl LLMClient for ToolUseClient {
2048        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
2049            use rig_core::completion::message::ToolFunction;
2050            self.calls.fetch_add(1, Ordering::Relaxed);
2051            let mut response = response_with(vec![AssistantContent::ToolCall(ToolCall::new(
2052                CallId::from_wire("call-1"),
2053                ToolFunction::new(ToolName::new("allowed").unwrap(), serde_json::json!({})),
2054            ))]);
2055            response.finish_reason = FinishReason::ToolUse;
2056            Ok(response)
2057        }
2058    }
2059
2060    struct RequiredToolClient {
2061        calls: Arc<AtomicUsize>,
2062    }
2063
2064    impl LLMClient for RequiredToolClient {
2065        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
2066            use rig_core::completion::message::ToolFunction;
2067            self.calls.fetch_add(1, Ordering::Relaxed);
2068            let mut response = response_with(vec![AssistantContent::ToolCall(ToolCall::new(
2069                CallId::from_wire("call-1"),
2070                ToolFunction::new(ToolName::new("submit").unwrap(), serde_json::json!({})),
2071            ))]);
2072            response.finish_reason = FinishReason::ToolUse;
2073            Ok(response)
2074        }
2075    }
2076
2077    #[tokio::test]
2078    async fn priority_client_retries_unexpected_tool_use_for_no_tools_request() {
2079        let tool_use_calls = Arc::new(AtomicUsize::new(0));
2080        let tool_use = FallbackSlot::new(
2081            ToolUseClient {
2082                calls: Arc::clone(&tool_use_calls),
2083            }
2084            .into_arc(),
2085            "tool-use",
2086            None,
2087        );
2088        let (healthy, healthy_calls) = recording_slot("healthy", None, false);
2089        let client = PriorityClient::new(vec![tool_use, healthy]).unwrap();
2090
2091        let response = client.completion(test_completion()).await.unwrap();
2092
2093        assert_eq!(response.selected_model.as_deref(), Some("healthy"));
2094        assert_eq!(tool_use_calls.load(Ordering::Relaxed), 1);
2095        assert_eq!(healthy_calls.lock().unwrap().len(), 1);
2096    }
2097
2098    #[tokio::test]
2099    async fn priority_client_accepts_tool_use_when_tools_were_declared() {
2100        let tool_use_calls = Arc::new(AtomicUsize::new(0));
2101        let tool_use = FallbackSlot::new(
2102            ToolUseClient {
2103                calls: Arc::clone(&tool_use_calls),
2104            }
2105            .into_arc(),
2106            "tool-use",
2107            None,
2108        );
2109        let (unused, unused_calls) = recording_slot("unused", None, false);
2110        let client = PriorityClient::new(vec![tool_use, unused]).unwrap();
2111        let mut completion = test_completion();
2112        completion.tools.push(rig_core::completion::ToolDefinition {
2113            name: ToolName::new("allowed").unwrap(),
2114            annotations: Default::default(),
2115            description: "An allowed tool".to_string(),
2116            parameters: serde_json::json!({"type": "object"}),
2117        });
2118
2119        let response = client.completion(completion).await.unwrap();
2120
2121        assert_eq!(response.finish_reason, FinishReason::ToolUse);
2122        assert_eq!(response.selected_model.as_deref(), Some("tool-use"));
2123        assert_eq!(tool_use_calls.load(Ordering::Relaxed), 1);
2124        assert!(unused_calls.lock().unwrap().is_empty());
2125    }
2126
2127    #[tokio::test]
2128    async fn required_tool_protocol_failure_tries_the_next_route() {
2129        let (plain_text, plain_text_calls) = recording_slot("plain-text", None, false);
2130        let required_tool_calls = Arc::new(AtomicUsize::new(0));
2131        let required_tool = FallbackSlot::new(
2132            RequiredToolClient {
2133                calls: Arc::clone(&required_tool_calls),
2134            }
2135            .into_arc(),
2136            "required-tool",
2137            None,
2138        );
2139        let client = PriorityClient::new(vec![plain_text, required_tool]).unwrap();
2140        let mut completion = test_completion();
2141        completion.tools.push(rig_core::completion::ToolDefinition {
2142            name: ToolName::new("submit").unwrap(),
2143            annotations: Default::default(),
2144            description: "Submit the result".to_string(),
2145            parameters: serde_json::json!({"type": "object"}),
2146        });
2147        completion.tool_choice = Some(ToolChoice::Required);
2148
2149        let response = client.completion(completion).await.unwrap();
2150
2151        assert_eq!(response.selected_model.as_deref(), Some("required-tool"));
2152        assert_eq!(plain_text_calls.lock().unwrap().len(), 1);
2153        assert_eq!(required_tool_calls.load(Ordering::Relaxed), 1);
2154    }
2155
2156    #[tokio::test]
2157    async fn undeclared_required_tool_call_tries_the_next_route() {
2158        let wrong_tool_calls = Arc::new(AtomicUsize::new(0));
2159        let wrong_tool = FallbackSlot::new(
2160            ToolUseClient {
2161                calls: Arc::clone(&wrong_tool_calls),
2162            }
2163            .into_arc(),
2164            "wrong-tool",
2165            None,
2166        );
2167        let required_tool_calls = Arc::new(AtomicUsize::new(0));
2168        let required_tool = FallbackSlot::new(
2169            RequiredToolClient {
2170                calls: Arc::clone(&required_tool_calls),
2171            }
2172            .into_arc(),
2173            "required-tool",
2174            None,
2175        );
2176        let client = PriorityClient::new(vec![wrong_tool, required_tool]).unwrap();
2177        let mut completion = test_completion();
2178        completion.tools.push(rig_core::completion::ToolDefinition {
2179            name: ToolName::new("submit").unwrap(),
2180            annotations: Default::default(),
2181            description: "Submit the result".to_string(),
2182            parameters: serde_json::json!({"type": "object"}),
2183        });
2184        completion.tool_choice = Some(ToolChoice::Required);
2185
2186        let response = client.completion(completion).await.unwrap();
2187
2188        assert_eq!(response.selected_model.as_deref(), Some("required-tool"));
2189        assert_eq!(wrong_tool_calls.load(Ordering::Relaxed), 1);
2190        assert_eq!(required_tool_calls.load(Ordering::Relaxed), 1);
2191    }
2192
2193    #[tokio::test]
2194    async fn specifically_disallowed_tool_call_tries_the_next_route() {
2195        let wrong_tool_calls = Arc::new(AtomicUsize::new(0));
2196        let wrong_tool = FallbackSlot::new(
2197            ToolUseClient {
2198                calls: Arc::clone(&wrong_tool_calls),
2199            }
2200            .into_arc(),
2201            "wrong-tool",
2202            None,
2203        );
2204        let required_tool_calls = Arc::new(AtomicUsize::new(0));
2205        let required_tool = FallbackSlot::new(
2206            RequiredToolClient {
2207                calls: Arc::clone(&required_tool_calls),
2208            }
2209            .into_arc(),
2210            "required-tool",
2211            None,
2212        );
2213        let client = PriorityClient::new(vec![wrong_tool, required_tool]).unwrap();
2214        let mut completion = test_completion();
2215        for name in ["allowed", "submit"] {
2216            completion.tools.push(rig_core::completion::ToolDefinition {
2217                name: ToolName::new(name).unwrap(),
2218                annotations: Default::default(),
2219                description: "A declared tool".to_string(),
2220                parameters: serde_json::json!({"type": "object"}),
2221            });
2222        }
2223        completion.tool_choice = Some(ToolChoice::Specific {
2224            function_names: vec![ToolName::new("submit").unwrap()],
2225        });
2226
2227        let response = client.completion(completion).await.unwrap();
2228
2229        assert_eq!(response.selected_model.as_deref(), Some("required-tool"));
2230        assert_eq!(wrong_tool_calls.load(Ordering::Relaxed), 1);
2231        assert_eq!(required_tool_calls.load(Ordering::Relaxed), 1);
2232    }
2233
2234    #[tokio::test]
2235    async fn priority_client_reports_when_every_route_is_unavailable() {
2236        let (slot, calls) = recording_slot("unavailable", None, false);
2237        slot.mark_unavailable();
2238        let client = PriorityClient::new(vec![slot]).unwrap();
2239
2240        let err = client.completion(test_completion()).await.unwrap_err();
2241
2242        assert_eq!(
2243            format!("{err:#}"),
2244            "all configured model routes are unavailable for this run"
2245        );
2246        assert!(calls.lock().unwrap().is_empty());
2247    }
2248
2249    #[tokio::test]
2250    async fn alloy_without_fallback_attempts_only_the_selected_route() {
2251        let (first, first_calls) = recording_slot("first", None, true);
2252        let (second, second_calls) = recording_slot("second", None, true);
2253        let client =
2254            AlloyClient::new(vec![AlloySlot::from(&first), AlloySlot::from(&second)]).unwrap();
2255
2256        assert!(client.completion(test_completion()).await.is_err());
2257        assert_eq!(
2258            first_calls.lock().unwrap().len() + second_calls.lock().unwrap().len(),
2259            1
2260        );
2261    }
2262
2263    #[tokio::test]
2264    async fn alloy_fallback_succeeds_from_every_random_start() {
2265        let (failed_a, _) = recording_slot("failed-a", None, true);
2266        let (healthy, _) = recording_slot("healthy", None, false);
2267        let (failed_b, _) = recording_slot("failed-b", None, true);
2268        let client =
2269            AlloyClient::new_with_fallback_routes(vec![failed_a, healthy, failed_b]).unwrap();
2270
2271        // Whichever slot randomness selects first, walking the ring once must reach `healthy`.
2272        for _ in 0..32 {
2273            let response = client.completion(test_completion()).await.unwrap();
2274            assert_eq!(response.selected_model.as_deref(), Some("healthy"));
2275        }
2276    }
2277
2278    #[test]
2279    fn alloy_random_start_excludes_unavailable_routes() {
2280        let (unavailable, _) = recording_slot("unavailable", None, false);
2281        unavailable.mark_unavailable();
2282        let (first, _) = recording_slot("first", None, false);
2283        let (second, _) = recording_slot("second", None, false);
2284        let client =
2285            AlloyClient::new_with_fallback_routes(vec![unavailable, first, second]).unwrap();
2286
2287        assert_eq!(client.available_indices(), vec![1, 2]);
2288        for _ in 0..32 {
2289            assert!(matches!(client.pick_idx(), Some(1 | 2)));
2290        }
2291    }
2292
2293    struct QuotaClient {
2294        calls: Arc<AtomicUsize>,
2295    }
2296
2297    impl LLMClient for QuotaClient {
2298        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
2299            self.calls.fetch_add(1, Ordering::Relaxed);
2300            Err(eyre::Report::new(CompletionError::from_http_response(
2301                reqwest::StatusCode::TOO_MANY_REQUESTS,
2302                r#"{"error":{"code":"usage_limit_reached"}}"#,
2303            )))
2304        }
2305    }
2306
2307    #[tokio::test]
2308    async fn quota_failure_is_shared_across_agent_forks_for_the_run() {
2309        let quota_calls = Arc::new(AtomicUsize::new(0));
2310        let quota = FallbackSlot::new(
2311            QuotaClient {
2312                calls: Arc::clone(&quota_calls),
2313            }
2314            .into_arc(),
2315            "quota",
2316            None,
2317        );
2318        let (healthy, _) = recording_slot("healthy", None, false);
2319        let first = PriorityClient::new(vec![quota, healthy]).unwrap();
2320        let second = first.fork_for_agent().expect("priority clients can fork");
2321
2322        first.completion(test_completion()).await.unwrap();
2323        second.completion(test_completion()).await.unwrap();
2324
2325        assert_eq!(quota_calls.load(Ordering::Relaxed), 1);
2326    }
2327
2328    fn reasoning_item(text: &str) -> AssistantContent {
2329        AssistantContent::Reasoning(rig_core::completion::message::Reasoning::new(text))
2330    }
2331
2332    /// The block is never closed, so the scanner drops the verdict with the reasoning — but the
2333    /// reasoning is also reported structurally, so it can be subtracted exactly.
2334    #[test]
2335    fn unterminated_think_keeps_the_answer_and_drops_the_duplicated_reasoning() {
2336        let reasoning = "The debate is extremely brief. The Actor suggested `eyre`.";
2337        let response = response_with(vec![
2338            reasoning_item(reasoning),
2339            AssistantContent::text(format!(
2340                "<think>\n{reasoning}\n\n### Verdict\n**Agreed: use `eyre` for applications.**"
2341            )),
2342        ]);
2343        assert_eq!(
2344            response.text(),
2345            "### Verdict\n**Agreed: use `eyre` for applications.**"
2346        );
2347    }
2348
2349    /// Leading text hides the answer just as thoroughly, but makes the response read as
2350    /// successful — so nothing retries and the verdict is lost silently.
2351    #[test]
2352    fn unterminated_think_after_a_prefix_still_recovers_the_answer() {
2353        let reasoning = "Weighing both sides.";
2354        let response = response_with(vec![
2355            reasoning_item(reasoning),
2356            AssistantContent::text(format!(
2357                "Here is my review.\n<think>\n{reasoning}\n\n### Verdict\nShip it."
2358            )),
2359        ]);
2360        assert_eq!(
2361            response.text(),
2362            "Here is my review.\n\n### Verdict\nShip it."
2363        );
2364    }
2365
2366    /// OpenRouter splits `reasoning_details` mid-sentence, so a newline join stops the fragments
2367    /// matching their copy inside the block and the whole chain leaks into the answer.
2368    #[test]
2369    fn fragmented_reasoning_is_concatenated_without_separators() {
2370        let response = response_with(vec![
2371            reasoning_item("weighing the options"),
2372            reasoning_item(" carefully."),
2373            AssistantContent::text("<think>\nweighing the options carefully.\n\nVerdict: ship it."),
2374        ]);
2375        assert_eq!(response.text(), "Verdict: ship it.");
2376    }
2377
2378    /// With no structured reasoning there is no way to tell reasoning from answer. Returning the
2379    /// body would both serve chain-of-thought as the verdict and make the response read as
2380    /// non-empty, silencing the retry that exists for a reply that never answered.
2381    #[test]
2382    fn unterminated_think_without_structured_reasoning_stays_empty() {
2383        let response = response_with(vec![AssistantContent::text(
2384            "<think>\nweighing it up\n\nVerdict: ship it.",
2385        )]);
2386        assert!(response.text().is_empty());
2387    }
2388
2389    #[test]
2390    fn unrelated_reasoning_is_not_used_to_split_the_body() {
2391        let response = response_with(vec![
2392            reasoning_item("brief"),
2393            AssistantContent::text("<think>private chain"),
2394        ]);
2395        assert!(response.text().is_empty());
2396    }
2397
2398    #[test]
2399    fn inline_think_recovery_uses_only_verbatim_native_reasoning() {
2400        let openrouter_reasoning = reasoning_item("").with_native(json!({
2401            "reasoning_details": [
2402                {"type": "reasoning.text", "text": "first"},
2403                {"type": "reasoning.text", "text": " second."},
2404                {"type": "reasoning.summary", "summary": "do not subtract"}
2405            ]
2406        }));
2407        let response = response_with(vec![
2408            openrouter_reasoning,
2409            AssistantContent::text("<think>first second. Verdict: ship it."),
2410        ]);
2411        assert_eq!(response.text(), "Verdict: ship it.");
2412
2413        let summary = reasoning_item("first second.").with_native(json!({"type": "reasoning"}));
2414        let response = response_with(vec![
2415            summary,
2416            AssistantContent::text("<think>first second. Private continuation."),
2417        ]);
2418        assert!(response.text().is_empty());
2419    }
2420
2421    /// A reasoning string that happens to be a byte prefix of the answer must not chop it: "Ver"
2422    /// against "Verdict: ship it." would otherwise yield "dict: ship it.".
2423    #[test]
2424    fn a_prefix_that_cuts_mid_word_is_not_treated_as_reasoning() {
2425        let response = response_with(vec![
2426            reasoning_item("Ver"),
2427            AssistantContent::text("<think>Verdict: ship it."),
2428        ]);
2429        assert!(response.text().is_empty());
2430    }
2431
2432    /// With several blocks, the one that stayed open is not the first tag in the text. Recovery
2433    /// keys off the scanner's offset, so an earlier *closed* block cannot misdirect it.
2434    #[test]
2435    fn recovery_targets_the_block_that_stayed_open() {
2436        let response = response_with(vec![
2437            reasoning_item("secret"),
2438            AssistantContent::text("<think>old</think>\n<think>secret\n\nFINAL"),
2439        ]);
2440        assert_eq!(response.text(), "FINAL");
2441    }
2442
2443    /// A stray closing tag at depth 0 is dropped by the scanner and must not be mistaken for the
2444    /// opener when recovering.
2445    #[test]
2446    fn a_stray_closing_tag_does_not_misdirect_recovery() {
2447        let response = response_with(vec![
2448            reasoning_item("secret"),
2449            AssistantContent::text("</think><think>secret\n\nFINAL"),
2450        ]);
2451        assert_eq!(response.text(), "FINAL");
2452    }
2453
2454    /// A response that is only reasoning still collapses to empty, so the empty-response retry
2455    /// keeps working for models that genuinely returned no answer.
2456    #[test]
2457    fn a_reasoning_only_response_is_still_empty() {
2458        let reasoning = "still thinking about it";
2459        let response = response_with(vec![
2460            reasoning_item(reasoning),
2461            AssistantContent::text(format!("<think>\n{reasoning}")),
2462        ]);
2463        assert!(response.text().is_empty());
2464        let closed = response_with(vec![AssistantContent::text(
2465            "<think>done deliberating</think>",
2466        )]);
2467        assert!(closed.text().is_empty());
2468    }
2469
2470    /// A well-formed closed block is untouched by the recovery path.
2471    #[test]
2472    fn closed_think_block_still_yields_only_the_answer() {
2473        let response = response_with(vec![AssistantContent::text(
2474            "<think>weighing it up</think>Verdict: ship it.",
2475        )]);
2476        assert_eq!(response.text(), "Verdict: ship it.");
2477    }
2478
2479    /// Rig normalizes Anthropic's disjoint input counts before returning them.
2480    fn anthropic_usage(input: u64, output: u64, cached: u64, creation: u64) -> Usage {
2481        let mut usage = Usage::new();
2482        usage.input_tokens = Some(input + cached + creation);
2483        usage.output_tokens = Some(output);
2484        usage.cached_input_tokens = Some(cached);
2485        usage.cache_creation_input_tokens = Some(creation);
2486        usage.total_tokens = Some(input + cached + creation + output);
2487        usage
2488    }
2489
2490    fn anthropic(usage: &Usage) -> TokenUsage {
2491        TokenUsage::from_provider(usage)
2492    }
2493
2494    fn prompt_inclusive(usage: &Usage) -> TokenUsage {
2495        TokenUsage::from_provider(usage)
2496    }
2497
2498    /// The same 3508-token prompt served from cache, as each provider reports it: Anthropic shows
2499    /// `input_tokens: 52` with the rest under `cache_read`, OpenAI shows the whole prompt. Both
2500    /// must meter identically, or a mixed-provider run sums numbers that mean different things —
2501    /// and the Anthropic shape read raw is what hid 98% of the prompt.
2502    #[test]
2503    fn provider_shapes_meter_a_cache_hit_identically() {
2504        let from_anthropic = anthropic(&anthropic_usage(52, 8, 3456, 0));
2505        let mut openai = Usage::new();
2506        openai.input_tokens = Some(3508);
2507        openai.output_tokens = Some(8);
2508        openai.cached_input_tokens = Some(3456);
2509        openai.total_tokens = Some(3516);
2510        let from_openai = prompt_inclusive(&openai);
2511
2512        assert_eq!(from_anthropic.input_tokens, 3508);
2513        assert_eq!(from_anthropic.input_tokens, from_openai.input_tokens);
2514        assert_eq!(
2515            from_anthropic.cached_input_tokens,
2516            from_openai.cached_input_tokens
2517        );
2518        for usage in [from_anthropic, from_openai] {
2519            assert_eq!(usage.total_tokens, usage.input_tokens + usage.output_tokens);
2520        }
2521    }
2522
2523    /// Gemini reports thinking and tool-use prompts beside both `input_tokens` and
2524    /// `output_tokens`, and its parts don't sum to its total — so no arithmetic can tell its shape
2525    /// apart from Anthropic's. Numbers are rig's own fixture (`gemini/completion.rs`) with the
2526    /// cache lowered to 8, the value that makes the buckets *look* like they fit outside the
2527    /// prompt. Charging them would report a 40-token prompt as 48.
2528    #[test]
2529    fn gemini_cache_reads_are_never_added_to_its_prompt() {
2530        let mut usage = Usage::new();
2531        usage.input_tokens = Some(40);
2532        usage.output_tokens = Some(30);
2533        usage.reasoning_tokens = Some(10);
2534        usage.tool_use_prompt_tokens = Some(12);
2535        usage.cached_input_tokens = Some(8);
2536        usage.total_tokens = Some(100);
2537        let usage = prompt_inclusive(&usage);
2538        assert_eq!(usage.input_tokens, 40);
2539        assert_eq!(usage.cached_input_tokens, 8);
2540    }
2541
2542    /// An OpenRouter gateway may report a total larger than prompt + completion. That slack must
2543    /// not turn its cache reads — already inside `prompt_tokens` — into extra prompt tokens.
2544    #[test]
2545    fn openrouter_total_disagreement_does_not_inflate_the_prompt() {
2546        let mut usage = Usage::new();
2547        usage.input_tokens = Some(500);
2548        usage.output_tokens = Some(10);
2549        usage.cached_input_tokens = Some(5);
2550        usage.total_tokens = Some(515);
2551        let usage = prompt_inclusive(&usage);
2552        assert_eq!(usage.input_tokens, 500);
2553        assert_eq!(usage.total_tokens, 510);
2554    }
2555
2556    /// A gateway that omits usage totals must still meter the prompt it reported.
2557    #[test]
2558    fn missing_provider_total_still_meters_reported_input() {
2559        let mut usage = Usage::new();
2560        usage.input_tokens = Some(1200);
2561        usage.output_tokens = Some(40);
2562        let usage = prompt_inclusive(&usage);
2563        assert_eq!(usage.input_tokens, 1200);
2564        assert_eq!(usage.total_tokens, 1240);
2565    }
2566
2567    /// Anthropic charges a cache *write* too, and reports it outside `input_tokens` like a read.
2568    #[test]
2569    fn anthropic_cache_writes_count_toward_the_prompt() {
2570        let usage = anthropic(&anthropic_usage(90, 10, 0, 4100));
2571        assert_eq!(usage.cache_creation_input_tokens, 4100);
2572        assert_eq!(usage.input_tokens, 4190);
2573        assert_eq!(usage.total_tokens, 4200);
2574    }
2575
2576    /// A provider reporting more cache than prompt is contradicting itself. Reporting the prompt
2577    /// as 5000 to make the breakdown fit would invent 4990 tokens of spend that were never billed,
2578    /// so both numbers are passed through as reported and the contradiction stays visible.
2579    #[test]
2580    fn contradictory_cache_metadata_is_not_papered_over() {
2581        let mut usage = Usage::new();
2582        usage.input_tokens = Some(10);
2583        usage.output_tokens = Some(5);
2584        usage.total_tokens = Some(15);
2585        usage.cached_input_tokens = Some(5_000);
2586        usage.cache_creation_input_tokens = Some(700);
2587        let usage = prompt_inclusive(&usage);
2588        assert_eq!(usage.input_tokens, 10);
2589        assert_eq!(usage.total_tokens, 15);
2590        assert_eq!(usage.cached_input_tokens, 5_000);
2591        assert_eq!(usage.cache_creation_input_tokens, 700);
2592    }
2593
2594    /// The whole point of the normalization: a cache hit must still trip the compaction
2595    /// threshold, since the full prompt is what gets re-sent next turn.
2596    #[test]
2597    fn compaction_threshold_sees_the_cached_prompt() {
2598        let mut window = ConversationUsageWindow::new(Some(3_000));
2599        window.record(anthropic(&anthropic_usage(52, 8, 3456, 0)));
2600        assert!(window.should_compact());
2601    }
2602
2603    /// The cache fields are `#[serde(default)]` so trajectories written before they existed
2604    /// still decode.
2605    #[test]
2606    fn usage_without_cache_fields_still_deserializes() {
2607        let usage: TokenUsage = serde_json::from_value(
2608            json!({"input_tokens": 10, "output_tokens": 2, "total_tokens": 12}),
2609        )
2610        .expect("legacy usage payload must decode");
2611        assert_eq!(usage.input_tokens, 10);
2612        assert_eq!(usage.cached_input_tokens, 0);
2613    }
2614
2615    fn provider_error(status: Option<u16>, body: &str) -> eyre::Report {
2616        let error = match status {
2617            Some(status) => CompletionError::from_http_response(
2618                reqwest::StatusCode::from_u16(status).unwrap(),
2619                body,
2620            ),
2621            None => CompletionError::from_provider_body(body),
2622        };
2623        eyre::Report::new(error).wrap_err("completion failed for model 'test'")
2624    }
2625
2626    #[test]
2627    fn foreign_thought_signature_is_recognized_only_as_a_gateway_400() {
2628        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"}}}"#;
2629        let status = |code: u16| {
2630            CompletionError::from_http_response(reqwest::StatusCode::from_u16(code).unwrap(), body)
2631        };
2632        assert!(is_foreign_thought_signature_rejection(&status(400)));
2633        assert!(!is_foreign_thought_signature_rejection(&status(502)));
2634        let other = CompletionError::from_http_response(
2635            reqwest::StatusCode::BAD_REQUEST,
2636            r#"{"error":{"message":"Provider returned error","code":400,"metadata":{"raw":"invalid tool schema"}}}"#,
2637        );
2638        assert!(!is_foreign_thought_signature_rejection(&other));
2639    }
2640
2641    #[test]
2642    fn without_reasoning_declines_a_reasoning_only_request() {
2643        let request: rig_core::completion::CompletionRequest = Completion {
2644            model: "gemini".to_string(),
2645            prompt: Message::Assistant(AssistantMessage::new(vec![AssistantContent::Reasoning(
2646                rig_core::completion::message::Reasoning::new("think"),
2647            )])),
2648            preamble: None,
2649            history: Vec::new(),
2650            tools: Vec::new(),
2651            tool_choice: None,
2652            max_tokens: None,
2653            additional_params: None,
2654        }
2655        .into();
2656        assert!(without_reasoning(request).is_none());
2657    }
2658
2659    #[test]
2660    fn without_reasoning_drops_reasoning_and_reasoning_only_turns() {
2661        let reasoning =
2662            || AssistantContent::Reasoning(rig_core::completion::message::Reasoning::new("think"));
2663        let request: rig_core::completion::CompletionRequest = Completion {
2664            model: "gemini".to_string(),
2665            prompt: Message::user("follow-up"),
2666            preamble: None,
2667            history: vec![
2668                Message::user("task"),
2669                Message::Assistant(AssistantMessage::new(vec![
2670                    reasoning(),
2671                    AssistantContent::text("answer"),
2672                ])),
2673                Message::Assistant(AssistantMessage::new(vec![reasoning()])),
2674            ],
2675            tools: Vec::new(),
2676            tool_choice: None,
2677            max_tokens: None,
2678            additional_params: None,
2679        }
2680        .into();
2681        let kept: Vec<Message> = without_reasoning(request)
2682            .unwrap()
2683            .chat_history
2684            .into_iter()
2685            .map(Arc::unwrap_or_clone)
2686            .collect();
2687        assert_eq!(
2688            kept,
2689            vec![
2690                Message::user("task"),
2691                Message::assistant("answer"),
2692                Message::user("follow-up"),
2693            ]
2694        );
2695    }
2696
2697    fn gemini_completion(max_tokens: Option<u64>, additional_params: Option<Value>) -> Completion {
2698        Completion {
2699            model: "gemini-3-pro".to_string(),
2700            prompt: Message::user("hi".to_string()),
2701            preamble: None,
2702            history: Vec::new(),
2703            tools: Vec::new(),
2704            tool_choice: None,
2705            max_tokens,
2706            additional_params,
2707        }
2708    }
2709
2710    fn gemini_wire_body(completion: Completion) -> Result<Value> {
2711        use rig_core::wire::{Body, Mode, Wire};
2712        let wire = gemini::completion::GenerateContent::new(
2713            gemini::GeminiConfig::new("unused"),
2714            &completion.model,
2715        );
2716        let encoded = wire.encode(completion.into(), Mode::Unary)?;
2717        let Body::Bytes(bytes) = encoded.request.into_body() else {
2718            panic!("expected JSON")
2719        };
2720        Ok(serde_json::from_slice(&bytes)?)
2721    }
2722
2723    #[test]
2724    fn merge_json_is_deep_and_extra_wins() {
2725        // nested objects merge recursively; scalar conflicts resolve to `extra`.
2726        let merged = merge_json(
2727            json!({"generation_config": {"temperature": 0.2}, "a": 1}),
2728            json!({"generation_config": {"max_output_tokens": 50}, "a": 2}),
2729        );
2730        assert_eq!(
2731            merged,
2732            json!({"generation_config": {"temperature": 0.2, "max_output_tokens": 50}, "a": 2})
2733        );
2734    }
2735
2736    #[test]
2737    fn gemini_params_preserve_caller_config() {
2738        // A caller's safety settings and nested generation_config must survive the computed overlay.
2739        let params = gemini_wire_body(gemini_completion(
2740            Some(50),
2741            Some(json!({
2742                "generationConfig": {"temperature": 0.2},
2743                "safetySettings": [{"category": "HARM", "threshold": "NONE"}]
2744            })),
2745        ))
2746        .unwrap();
2747        assert_eq!(
2748            params["generationConfig"],
2749            json!({"temperature": 0.2, "maxOutputTokens": 50})
2750        );
2751        assert_eq!(
2752            params["safetySettings"],
2753            json!([{"category": "HARM", "threshold": "NONE"}])
2754        );
2755    }
2756
2757    #[test]
2758    fn gemini_params_none_yields_generation_config_only() {
2759        let params = gemini_wire_body(gemini_completion(Some(50), None)).unwrap();
2760        assert_eq!(params["generationConfig"], json!({"maxOutputTokens": 50}));
2761    }
2762
2763    #[test]
2764    fn strips_full_think_block() {
2765        let raw = "<think>let me reason about this</think>\n\nThe bug is in foo().";
2766        assert_eq!(strip_think_blocks(raw), "The bug is in foo().");
2767    }
2768
2769    #[test]
2770    fn strips_stray_empty_think_tags() {
2771        // OpenRouter hoists MiniMax's reasoning into a separate field but leaves the tags.
2772        let raw = "<think></think>\n## Findings\n- looks fine";
2773        assert_eq!(strip_think_blocks(raw), "## Findings\n- looks fine");
2774    }
2775
2776    #[test]
2777    fn strips_unbalanced_and_multiline_think() {
2778        let raw = "intro\n<think>\nstep 1\nstep 2\n</think>verdict: ok</think>";
2779        assert_eq!(strip_think_blocks(raw), "intro\nverdict: ok");
2780    }
2781
2782    #[test]
2783    fn leaves_non_think_text_untouched() {
2784        let raw = "no reasoning tags here, just review text";
2785        assert_eq!(strip_think_blocks(raw), raw);
2786    }
2787
2788    #[test]
2789    fn strips_unterminated_think_to_eof() {
2790        // a streamed/truncated block with no closing tag must not leak its body.
2791        let raw = "answer first\n<think>reasoning that never closes\nstep 2";
2792        assert_eq!(strip_think_blocks(raw), "answer first");
2793    }
2794
2795    #[test]
2796    fn all_reasoning_collapses_to_empty() {
2797        // an all-think response (incl. the multi-block join) must be empty so the
2798        // agent loop's is_empty() nudge path fires instead of returning "\n".
2799        let joined = format!("{}\n{}", "<think>round one</think>", "<think>round two");
2800        assert_eq!(strip_think_blocks(&joined), "");
2801    }
2802
2803    #[test]
2804    fn response_text_collapses_whitespace_only_content_to_empty() {
2805        let response = response_with(vec![AssistantContent::text(" \n\t ")]);
2806        assert!(response.text().is_empty());
2807    }
2808
2809    #[test]
2810    fn strips_nested_think_blocks() {
2811        // a single non-greedy regex stops at the first </think> and leaks the tail; the
2812        // depth-tracking scanner must drop the whole balanced span.
2813        let raw = "<think>outer <think>inner</think> still hidden</think>answer";
2814        assert_eq!(strip_think_blocks(raw), "answer");
2815    }
2816
2817    #[test]
2818    fn strips_whitespace_padded_think_tags() {
2819        // `<think >` must be recognized as an open tag, not leaked as content.
2820        let raw = "<think >hidden</think >visible";
2821        assert_eq!(strip_think_blocks(raw), "visible");
2822    }
2823
2824    #[test]
2825    fn leaves_thinking_word_untouched() {
2826        // `<thinking>` is a different tag — the char after `think` must be ws or `>`.
2827        let raw = "see <thinking>kept</thinking> here";
2828        assert_eq!(
2829            strip_think_blocks(raw),
2830            "see <thinking>kept</thinking> here"
2831        );
2832    }
2833
2834    #[test]
2835    fn classifiers_use_captured_http_status() {
2836        let unauthorized = provider_error(Some(401), r#"{"message":"Unauthorized"}"#);
2837        assert!(!unauthorized.to_string().contains("401"));
2838        assert_eq!(provider_http_status(&unauthorized), Some(401));
2839        assert!(is_non_retryable_client_error(&unauthorized));
2840
2841        let throttled = provider_error(Some(429), r#"{"message":"slow down"}"#);
2842        assert!(is_rate_limit_error(&throttled));
2843        assert_eq!(
2844            retry_policy(&throttled).max_attempts,
2845            RATE_LIMIT_MAX_COMPLETION_ATTEMPTS
2846        );
2847
2848        let server = provider_error(Some(503), r#"{"message":"unavailable"}"#);
2849        assert_eq!(
2850            classify_provider_failure(&server),
2851            ProviderFailureClass::Server
2852        );
2853        assert_eq!(retry_policy(&server).max_attempts, MAX_COMPLETION_ATTEMPTS);
2854    }
2855
2856    #[test]
2857    fn exact_quota_codes_skip_same_route_retries() {
2858        for code in PERMANENT_QUOTA_ERROR_CODES {
2859            let body = format!(r#"{{"error":{{"code":"{code}"}}}}"#);
2860            let err = provider_error(Some(429), &body);
2861            assert!(is_long_window_quota_error(&err), "{code}");
2862            assert!(!is_rate_limit_error(&err), "{code}");
2863            assert!(!retry_policy(&err).retry, "{code}");
2864            assert!(is_sticky_fallback_error(&err), "{code}");
2865        }
2866    }
2867
2868    #[test]
2869    fn structured_kimi_quota_messages_are_the_narrow_compatibility_fallback() {
2870        for (status, message) in [
2871            (429, "out of tokens per 5h window; reset in 2h"),
2872            (429, "You've hit your usage limit"),
2873            (
2874                403,
2875                "You've reached your usage limit for this billing cycle. Your quota will be refreshed in the next cycle.",
2876            ),
2877        ] {
2878            let body = json!({"error": {"type": "access_terminated_error", "message": message}});
2879            let err = provider_error(Some(status), &body.to_string());
2880            assert!(is_long_window_quota_error(&err), "{message}");
2881            assert!(!retry_policy(&err).retry, "{message}");
2882        }
2883
2884        // Diagnostic text outside a structured provider body is deliberately ignored.
2885        let untyped = eyre::eyre!("insufficient_quota: out of tokens per 5h window");
2886        assert_eq!(
2887            classify_provider_failure(&untyped),
2888            ProviderFailureClass::Unknown
2889        );
2890        assert_eq!(retry_policy(&untyped).max_attempts, MAX_COMPLETION_ATTEMPTS);
2891    }
2892
2893    #[test]
2894    fn real_5xx_status_precedes_nested_quota_and_rate_codes() {
2895        for status in (500..600).filter(|&status| status != 529) {
2896            for body in [
2897                r#"{"upstream":{"error":{"code":"insufficient_quota","message":"out of tokens per 5h window"}}}"#,
2898                r#"{"upstream":{"error":{"type":"overloaded_error"}}}"#,
2899            ] {
2900                let err = provider_error(Some(status), body);
2901                assert_eq!(
2902                    classify_provider_failure(&err),
2903                    ProviderFailureClass::Server
2904                );
2905                let policy = retry_policy(&err);
2906                assert!(policy.retry);
2907                assert_eq!(policy.max_attempts, MAX_COMPLETION_ATTEMPTS);
2908                assert!(!is_sticky_fallback_error(&err));
2909            }
2910        }
2911    }
2912
2913    #[test]
2914    fn anthropic_529_overload_uses_the_long_overload_policy() {
2915        let err = provider_error(
2916            Some(529),
2917            r#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#,
2918        );
2919
2920        assert_eq!(
2921            classify_provider_failure(&err),
2922            ProviderFailureClass::RateLimit
2923        );
2924        let policy = retry_policy(&err);
2925        assert!(policy.retry);
2926        assert_eq!(policy.max_attempts, RATE_LIMIT_MAX_COMPLETION_ATTEMPTS);
2927        assert_eq!(policy.base_backoff_ms, RATE_LIMIT_BASE_BACKOFF_MS);
2928        assert!(is_sticky_fallback_error(&err));
2929    }
2930
2931    #[test]
2932    fn exact_provider_codes_classify_without_http_status() {
2933        for code in [
2934            "authentication_error",
2935            "invalid_api_key",
2936            "permission_error",
2937        ] {
2938            let body = format!(r#"{{"error":{{"type":"{code}"}}}}"#);
2939            let err = provider_error(None, &body);
2940            assert!(is_non_retryable_client_error(&err), "{code}");
2941        }
2942
2943        for code in RATE_LIMIT_ERROR_CODES {
2944            let body = format!(r#"{{"error":{{"code":"{code}"}}}}"#);
2945            let err = provider_error(None, &body);
2946            assert!(is_rate_limit_error(&err), "{code}");
2947        }
2948    }
2949
2950    #[test]
2951    fn context_length_uses_exact_code_and_structured_message() {
2952        let openai = provider_error(Some(400), r#"{"error":{"code":"context_length_exceeded"}}"#);
2953        assert!(is_context_length_error(&openai));
2954
2955        let anthropic = provider_error(
2956            Some(400),
2957            r#"{"error":{"type":"invalid_request_error","message":"prompt is too long"}}"#,
2958        );
2959        assert!(is_context_length_error(&anthropic));
2960
2961        let malformed = provider_error(
2962            Some(400),
2963            r#"{"error":{"type":"invalid_request_error","message":"tools[0] is invalid"}}"#,
2964        );
2965        assert!(!is_context_length_error(&malformed));
2966        assert!(is_non_retryable_client_error(&malformed));
2967    }
2968
2969    #[test]
2970    fn provider_json_status_hint_handles_success_error_envelopes() {
2971        let err = provider_error(
2972            Some(200),
2973            r#"{"error":{"code":429,"type":"rate_limit_error","message":"slow down"}}"#,
2974        );
2975        assert_eq!(provider_http_status(&err), Some(429));
2976        assert!(is_rate_limit_error(&err));
2977    }
2978
2979    #[test]
2980    fn text_provider_body_only_uses_the_quota_message_fallback() {
2981        for status in [403, 429] {
2982            let err = provider_error(
2983                Some(status),
2984                "You've reached your usage limit for this billing cycle; refresh in the next cycle",
2985            );
2986            assert!(is_long_window_quota_error(&err));
2987            assert!(!retry_policy(&err).retry);
2988            assert!(is_sticky_fallback_error(&err));
2989        }
2990
2991        let err = provider_error(Some(429), "insufficient_quota in a non-JSON response");
2992        // Arbitrary body text is not scanned for codes; the captured 429 still classifies.
2993        assert!(is_rate_limit_error(&err));
2994
2995        let statusless = provider_error(None, "insufficient_quota in a non-JSON response");
2996        assert_eq!(
2997            classify_provider_failure(&statusless),
2998            ProviderFailureClass::Unknown
2999        );
3000        assert!(!is_sticky_fallback_error(&statusless));
3001    }
3002
3003    #[test]
3004    fn top_level_status_hint_precedes_nested_numeric_codes() {
3005        let err = provider_error(
3006            Some(200),
3007            r#"{"statusCode":502,"upstream":{"error":{"code":403,"type":"insufficient_quota"}}}"#,
3008        );
3009        assert_eq!(provider_http_status(&err), Some(502));
3010        assert_eq!(
3011            classify_provider_failure(&err),
3012            ProviderFailureClass::Server
3013        );
3014        assert!(!is_sticky_fallback_error(&err));
3015    }
3016
3017    #[test]
3018    fn compact_provider_error_body_keeps_large_json_classifiable() {
3019        let body = json!({
3020            "error": {
3021                "type": "usage_limit_reached",
3022                "message": "quota exhausted",
3023                "diagnostic": "x".repeat(4_000),
3024            }
3025        })
3026        .to_string();
3027        let compact = compact_provider_error_body(&body, 1_000);
3028        serde_json::from_str::<Value>(&compact).expect("compacted provider body stays valid JSON");
3029        let err = provider_error(Some(429), &compact);
3030        assert!(is_long_window_quota_error(&err));
3031    }
3032
3033    #[test]
3034    fn provider_error_truncation_reuses_utf8_boundary_handling() {
3035        assert_eq!(truncate_utf8("aéz", 2), "a…");
3036    }
3037
3038    #[test]
3039    fn openrouter_normalization_preserves_typed_provider_source() {
3040        let err = normalize_completion_error(CompletionError::from_http_response(
3041            reqwest::StatusCode::TOO_MANY_REQUESTS,
3042            r#"{"error":{"type":"insufficient_quota"}}"#,
3043        ));
3044        assert_eq!(provider_http_status(&err), Some(429));
3045        assert!(is_long_window_quota_error(&err));
3046    }
3047
3048    fn tool_call_content() -> AssistantContent {
3049        use rig_core::completion::message::ToolFunction;
3050        AssistantContent::ToolCall(ToolCall::new(
3051            CallId::from_wire("call-1"),
3052            ToolFunction::new(
3053                ToolName::new("read_file").unwrap(),
3054                serde_json::json!({ "path": "x" }),
3055            ),
3056        ))
3057    }
3058
3059    /// Providers can pair tool calls with `stop`-like wire reasons; `tool_calls()` only
3060    /// surfaces calls under `ToolUse`, so the override losing would silently end the agent loop.
3061    #[test]
3062    fn a_structured_tool_call_overrides_any_wire_finish_reason() {
3063        let alone = vec![tool_call_content()];
3064        let beside_text = vec![
3065            AssistantContent::text("narration before the call"),
3066            tool_call_content(),
3067        ];
3068        for choice in [alone, beside_text] {
3069            for wire in [
3070                FinishReason::Stop,
3071                FinishReason::MaxTokens,
3072                FinishReason::None,
3073                FinishReason::Other("length_capped".to_string()),
3074            ] {
3075                assert_eq!(resolve_finish_reason(&choice, wire), FinishReason::ToolUse);
3076            }
3077        }
3078    }
3079
3080    #[test]
3081    fn without_tool_calls_the_wire_finish_reason_stands() {
3082        let choice = vec![AssistantContent::text("done")];
3083        for wire in [
3084            FinishReason::Stop,
3085            FinishReason::MaxTokens,
3086            FinishReason::None,
3087            FinishReason::Other("content_filter".to_string()),
3088        ] {
3089            assert_eq!(resolve_finish_reason(&choice, wire.clone()), wire);
3090        }
3091    }
3092
3093    mod spans {
3094        use super::*;
3095        use crate::telemetry::capture::SpanCapture;
3096
3097        struct UsageClient;
3098
3099        impl LLMClient for UsageClient {
3100            async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
3101                Ok(CompletionResponse {
3102                    choice: vec![AssistantContent::text("ok")],
3103                    origin: None,
3104                    finish_reason: FinishReason::Stop,
3105                    usage: TokenUsage {
3106                        input_tokens: 100,
3107                        output_tokens: 10,
3108                        total_tokens: 110,
3109                        cached_input_tokens: 80,
3110                        cache_creation_input_tokens: 20,
3111                    },
3112                    selected_model: Some("route-b".to_string()),
3113                })
3114            }
3115        }
3116
3117        const SECRET: &str = "SENTINEL-4f2a";
3118
3119        /// Fails the first `failures` calls with an error that quotes the request, like a
3120        /// provider echoing a rejected prompt would.
3121        struct EchoingFailClient {
3122            calls: Arc<AtomicUsize>,
3123            failures: usize,
3124        }
3125
3126        impl LLMClient for EchoingFailClient {
3127            async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
3128                let call = self.calls.fetch_add(1, Ordering::Relaxed) + 1;
3129                if call <= self.failures {
3130                    eyre::bail!("upstream rejected {SECRET}: {:?}", completion.prompt)
3131                }
3132                Ok(response_with(vec![AssistantContent::text("ok")]))
3133            }
3134        }
3135
3136        fn secret_completion() -> Completion {
3137            let mut completion = test_completion();
3138            completion.prompt = Message::user(format!("prompt {SECRET}"));
3139            completion.preamble = Some(format!("system {SECRET}"));
3140            completion
3141        }
3142
3143        #[tokio::test]
3144        async fn throttled_completion_records_one_chat_span_with_usage() {
3145            let capture = SpanCapture::default();
3146            let _active = capture.activate();
3147            let semaphore = Semaphore::new(1);
3148            let client = UsageClient.into_arc();
3149            throttled_completion(&semaphore, &client, test_completion())
3150                .await
3151                .expect("completion succeeds");
3152
3153            let chats = capture.named("chat");
3154            assert_eq!(chats.len(), 1);
3155            let chat = &chats[0];
3156            assert_eq!(chat.parent, None);
3157            assert_eq!(chat.field("otel.name"), Some("chat logical-primary"));
3158            assert_eq!(chat.field("otel.kind"), Some("client"));
3159            assert_eq!(chat.field("gen_ai.operation.name"), Some("chat"));
3160            assert_eq!(chat.field("gen_ai.request.model"), Some("logical-primary"));
3161            assert_eq!(chat.field("gen_ai.request.max_tokens"), Some("999"));
3162            assert_eq!(chat.field("gen_ai.response.model"), Some("route-b"));
3163            assert_eq!(chat.field("gen_ai.response.finish_reasons"), Some("stop"));
3164            assert_eq!(chat.field("gen_ai.usage.input_tokens"), Some("100"));
3165            assert_eq!(chat.field("gen_ai.usage.output_tokens"), Some("10"));
3166            assert_eq!(
3167                chat.field("gen_ai.usage.cache_read.input_tokens"),
3168                Some("80")
3169            );
3170            assert_eq!(
3171                chat.field("gen_ai.usage.cache_creation.input_tokens"),
3172                Some("20")
3173            );
3174            assert!(chat.field("nitpicker.queue_wait_ms").is_some());
3175            assert_eq!(chat.field("otel.status_code"), None);
3176        }
3177
3178        #[tokio::test(start_paused = true)]
3179        async fn retries_become_attempt_spans_carrying_only_the_failure_class() {
3180            let capture = SpanCapture::default();
3181            let _active = capture.activate();
3182            let semaphore = Semaphore::new(1);
3183            let client = EchoingFailClient {
3184                calls: Arc::new(AtomicUsize::new(0)),
3185                failures: 1,
3186            }
3187            .with_retry()
3188            .into_arc();
3189            throttled_completion(&semaphore, &client, secret_completion())
3190                .await
3191                .expect("second attempt succeeds");
3192
3193            let chat = &capture.named("chat")[0];
3194            assert_eq!(chat.field("otel.status_code"), None);
3195            let attempts = capture.named("llm.attempt");
3196            assert_eq!(attempts.len(), 2);
3197            for attempt in &attempts {
3198                assert_eq!(attempt.parent, Some(chat.id), "attempts nest under chat");
3199                assert_eq!(
3200                    attempt.field("gen_ai.request.model"),
3201                    Some("logical-primary")
3202                );
3203            }
3204            assert_eq!(attempts[0].field("nitpicker.attempt"), Some("1"));
3205            assert_eq!(attempts[0].field("otel.status_code"), Some("ERROR"));
3206            assert_eq!(attempts[0].field("error.type"), Some("unknown"));
3207            assert_eq!(attempts[1].field("nitpicker.attempt"), Some("2"));
3208            assert_eq!(attempts[1].field("otel.status_code"), None);
3209            assert_eq!(attempts[1].field("error.type"), None);
3210            capture.assert_no_secret(SECRET);
3211        }
3212
3213        #[tokio::test(start_paused = true)]
3214        async fn exhausted_retries_mark_the_chat_span_as_error() {
3215            let capture = SpanCapture::default();
3216            let _active = capture.activate();
3217            let semaphore = Semaphore::new(1);
3218            let client = EchoingFailClient {
3219                calls: Arc::new(AtomicUsize::new(0)),
3220                failures: usize::MAX,
3221            }
3222            .with_retry()
3223            .into_arc();
3224            let err = throttled_completion(&semaphore, &client, secret_completion())
3225                .await
3226                .expect_err("every attempt fails");
3227            assert!(
3228                err.to_string().contains(SECRET),
3229                "the caller still sees the real error"
3230            );
3231
3232            let chat = &capture.named("chat")[0];
3233            assert_eq!(chat.field("otel.status_code"), Some("ERROR"));
3234            assert_eq!(chat.field("gen_ai.response.model"), None);
3235            assert_eq!(capture.named("llm.attempt").len(), MAX_COMPLETION_ATTEMPTS);
3236            capture.assert_no_secret(SECRET);
3237        }
3238
3239        #[tokio::test(start_paused = true)]
3240        async fn empty_responses_are_classified_without_quoting_them() {
3241            struct EmptyThenTextClient(Arc<AtomicUsize>);
3242            impl LLMClient for EmptyThenTextClient {
3243                async fn completion(&self, _c: Completion) -> Result<CompletionResponse> {
3244                    let call = self.0.fetch_add(1, Ordering::Relaxed);
3245                    let text = if call == 0 { "" } else { "ok" };
3246                    Ok(response_with(vec![AssistantContent::text(text)]))
3247                }
3248            }
3249            let capture = SpanCapture::default();
3250            let _active = capture.activate();
3251            let semaphore = Semaphore::new(1);
3252            let client = EmptyThenTextClient(Arc::new(AtomicUsize::new(0)))
3253                .with_retry()
3254                .into_arc();
3255            throttled_completion(&semaphore, &client, test_completion())
3256                .await
3257                .expect("retry succeeds");
3258            let attempts = capture.named("llm.attempt");
3259            assert_eq!(attempts.len(), 2);
3260            assert_eq!(attempts[0].field("error.type"), Some("empty_response"));
3261            assert_eq!(attempts[0].field("otel.status_code"), Some("ERROR"));
3262        }
3263    }
3264}