Skip to main content

nitpicker_agent/
llm.rs

1use eyre::{Result, WrapErr};
2use rig_core::OneOrMany;
3use rig_core::client::CompletionClient;
4use rig_core::completion::CompletionError;
5use rig_core::completion::message::ReasoningContent;
6use rig_core::completion::message::ToolCall;
7use rig_core::completion::message::ToolChoice;
8use rig_core::completion::{AssistantContent, CompletionModel, Message};
9use rig_core::providers::{anthropic, gemini, openai, openrouter};
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12use std::future::Future;
13use std::pin::Pin;
14use std::sync::Arc;
15use std::time::{Duration, SystemTime, UNIX_EPOCH};
16use tokio::sync::Semaphore;
17use tracing::warn;
18
19const MAX_COMPLETION_ATTEMPTS: usize = 4;
20const RATE_LIMIT_MAX_COMPLETION_ATTEMPTS: usize = 8;
21const BASE_BACKOFF_MS: u64 = 250;
22const MAX_BACKOFF_MS: u64 = 5_000;
23const RATE_LIMIT_BASE_BACKOFF_MS: u64 = 5_000;
24const RATE_LIMIT_MAX_BACKOFF_MS: u64 = 60_000;
25const ANTHROPIC_DEFAULT_MAX_TOKENS: u64 = 8_192;
26
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct Completion {
29    pub model: String,
30    pub prompt: Message,
31    pub preamble: Option<String>,
32    pub history: Vec<Message>,
33    pub tools: Vec<rig_core::completion::ToolDefinition>,
34    pub tool_choice: Option<ToolChoice>,
35    pub max_tokens: Option<u64>,
36    pub additional_params: Option<Value>,
37}
38
39impl Completion {
40    pub fn preamble(mut self, preamble: impl Into<String>) -> Self {
41        self.preamble = Some(preamble.into());
42        self
43    }
44
45    pub fn tools(mut self, tools: Vec<rig_core::completion::ToolDefinition>) -> Self {
46        self.tools = tools;
47        self
48    }
49
50    pub fn history(mut self, history: Vec<Message>) -> Self {
51        self.history = history;
52        self
53    }
54
55    pub fn max_tokens(mut self, max_tokens: u64) -> Self {
56        self.max_tokens = Some(max_tokens);
57        self
58    }
59
60    pub fn additional_params(mut self, additional_params: Value) -> Self {
61        self.additional_params = Some(additional_params);
62        self
63    }
64}
65
66impl From<Completion> for rig_core::completion::CompletionRequest {
67    fn from(value: Completion) -> Self {
68        let chat_history = value
69            .history
70            .into_iter()
71            .chain(std::iter::once(value.prompt))
72            .collect::<Vec<_>>();
73        rig_core::completion::CompletionRequest {
74            model: None,
75            chat_history: OneOrMany::many(chat_history)
76                .expect("completion request must include at least one message"),
77            preamble: value.preamble,
78            documents: Vec::new(),
79            tools: value.tools,
80            temperature: None,
81            max_tokens: value.max_tokens,
82            additional_params: value.additional_params,
83            output_schema: None,
84            tool_choice: value.tool_choice,
85            // local telemetry policy only (`#[serde(skip)]`), never sent to a provider
86            record_telemetry_content: false,
87        }
88    }
89}
90
91#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
92pub enum FinishReason {
93    None,
94    Stop,
95    MaxTokens,
96    ToolUse,
97    Other(String),
98}
99
100#[derive(Debug, Clone, Deserialize, Serialize)]
101pub struct CompletionResponse {
102    pub choice: OneOrMany<AssistantContent>,
103    pub finish_reason: FinishReason,
104    pub usage: TokenUsage,
105    pub selected_model: Option<String>,
106}
107
108#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
109pub struct TokenUsage {
110    /// Every prompt token the provider processed for this call, cache reads included.
111    pub input_tokens: u64,
112    pub output_tokens: u64,
113    /// Always `input_tokens + output_tokens`.
114    pub total_tokens: u64,
115    /// A breakdown of `input_tokens`, not an additional charge. Passed through verbatim.
116    #[serde(default)]
117    pub cached_input_tokens: u64,
118    /// The part of `input_tokens` written into the cache on this call.
119    #[serde(default)]
120    pub cache_creation_input_tokens: u64,
121}
122
123/// Whether a provider's reported prompt count already contains its cache reads. Stated by each
124/// client, never inferred: provider totals can carry categories that are neither prompt nor output
125/// (Gemini) or disagree with their own parts (OpenRouter), so arithmetic tests misclassify.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum CacheAccounting {
128    /// Anthropic: cache reads and writes are reported beside `input_tokens`, not within it.
129    OutsidePrompt,
130    /// OpenAI (chat and Responses), OpenRouter, Gemini: cache reads are already in the prompt.
131    InsidePrompt,
132}
133
134impl TokenUsage {
135    /// Normalize usage so `input_tokens` always means every prompt token processed, cache reads
136    /// included — without it an Anthropic cache hit under-reports the prompt and
137    /// `ConversationUsageWindow::should_compact` never fires.
138    ///
139    /// Numbers are re-bucketed, never invented: a provider contradicting itself is reported as it
140    /// reported itself. `total_tokens` is `input + output`, so anything counted outside both
141    /// (Gemini's thinking tokens) goes unmetered.
142    pub fn from_provider(usage: &rig_core::completion::Usage, accounting: CacheAccounting) -> Self {
143        let input_tokens = match accounting {
144            CacheAccounting::OutsidePrompt => usage
145                .input_tokens
146                .saturating_add(usage.cached_input_tokens)
147                .saturating_add(usage.cache_creation_input_tokens),
148            CacheAccounting::InsidePrompt => usage.input_tokens,
149        };
150        Self {
151            input_tokens,
152            output_tokens: usage.output_tokens,
153            total_tokens: input_tokens.saturating_add(usage.output_tokens),
154            cached_input_tokens: usage.cached_input_tokens,
155            cache_creation_input_tokens: usage.cache_creation_input_tokens,
156        }
157    }
158}
159
160#[derive(Debug, Clone, Default)]
161pub struct ConversationUsageWindow {
162    compact_threshold: Option<u64>,
163    usage: TokenUsage,
164}
165
166impl ConversationUsageWindow {
167    pub fn new(compact_threshold: Option<u64>) -> Self {
168        Self {
169            compact_threshold,
170            usage: TokenUsage::default(),
171        }
172    }
173
174    pub fn should_compact(&self) -> bool {
175        self.compact_threshold
176            .map(|threshold| self.usage.total_tokens >= threshold)
177            .unwrap_or(false)
178    }
179
180    pub fn usage(&self) -> TokenUsage {
181        self.usage
182    }
183
184    pub fn record(&mut self, usage: TokenUsage) {
185        // Each response reports the whole prompt it was sent, not the new tokens, so replace
186        // rather than accumulate. Note this is the size of the *last* request: tool results
187        // appended after it are not counted until the next response comes back.
188        self.usage = usage;
189    }
190
191    pub fn reset(&mut self) {
192        self.usage = TokenUsage::default();
193    }
194}
195
196impl CompletionResponse {
197    pub fn message(&self) -> Message {
198        Message::Assistant {
199            id: None,
200            content: self.choice.clone(),
201        }
202    }
203
204    pub fn tool_calls(&self) -> Option<Vec<ToolCall>> {
205        if self.finish_reason != FinishReason::ToolUse {
206            return None;
207        }
208        let calls = self
209            .choice
210            .iter()
211            .filter_map(|content| match content {
212                AssistantContent::ToolCall(call) => Some(call.clone()),
213                _ => None,
214            })
215            .collect::<Vec<_>>();
216        if calls.is_empty() { None } else { Some(calls) }
217    }
218
219    pub fn text(&self) -> String {
220        // join the raw text blocks first, then strip once: a think block that spans
221        // (or a truncated one that runs to EOF) is judged against the whole text, and an
222        // all-reasoning response collapses to "" so callers' is_empty() checks fire.
223        let raw = self
224            .choice
225            .iter()
226            .filter_map(|content| match content {
227                AssistantContent::Text(text) => Some(text.text().to_string()),
228                _ => None,
229            })
230            .collect::<Vec<_>>()
231            .join("\n");
232        let (stripped, unclosed_body) = scan_think_blocks(&raw);
233        // only an *unclosed* block can hide an answer; a closed one that leaves nothing behind is
234        // genuinely all-reasoning and must read as empty so the retry fires.
235        let Some(start) = unclosed_body else {
236            return stripped;
237        };
238        // Recovery runs even with text before the block: that text only makes the loss silent,
239        // since a non-empty response never retries.
240        let recovered = self.recover_unterminated_think(&raw[start..]);
241        match (stripped.is_empty(), recovered.is_empty()) {
242            (_, true) => stripped,
243            (true, false) => recovered,
244            (false, false) => format!("{stripped}\n\n{recovered}"),
245        }
246    }
247
248    /// Salvage an answer that an unterminated `<think>` block swallowed.
249    ///
250    /// Where the reasoning ends is only knowable because the provider also reports it structurally
251    /// and the block repeats it verbatim before the answer, so it is subtracted, never guessed. An
252    /// unmatched body returns empty: serving it would pass chain-of-thought off as the verdict.
253    fn recover_unterminated_think(&self, body: &str) -> String {
254        let Some(reasoning) = self.reasoning_text() else {
255            return String::new();
256        };
257        let body = body.trim_start();
258        let Some(answer) = body.strip_prefix(reasoning.trim()) else {
259            return String::new();
260        };
261        // Word boundary, not whitespace: reasoning ending mid-word ("Ver" against "Verdict:") is a
262        // coincidental prefix, but real replies do run straight on from the final punctuation.
263        let cuts_mid_word = reasoning
264            .trim()
265            .chars()
266            .next_back()
267            .is_some_and(char::is_alphanumeric)
268            && answer.starts_with(char::is_alphanumeric);
269        match cuts_mid_word {
270            true => String::new(),
271            false => answer.trim().to_string(),
272        }
273    }
274
275    /// The response's structured reasoning, as reported beside the message content.
276    fn reasoning_text(&self) -> Option<String> {
277        let text = self
278            .choice
279            .iter()
280            .filter_map(|content| match content {
281                AssistantContent::Reasoning(reasoning) => Some(&reasoning.content),
282                _ => None,
283            })
284            .flatten()
285            .filter_map(|block| match block {
286                ReasoningContent::Text { text, .. } => Some(text.as_str()),
287                // Summary paraphrases and Encrypted/Redacted are opaque; none appear verbatim in
288                // the block, so they would corrupt the reconstruction rather than complete it.
289                _ => None,
290            })
291            .collect::<String>();
292        match text.trim().is_empty() {
293            true => None,
294            false => Some(text),
295        }
296    }
297}
298
299// some providers (notably MiniMax/GLM/DeepSeek via OpenRouter) emit chain-of-thought
300// inline as <think>...</think> in the message content rather than in a structured
301// reasoning field rig can drop. A depth-tracking scanner (not a single regex, which can't
302// match balanced nesting) keeps text only at nesting depth 0, so:
303//   - `<think...>` / `</think...>` are matched case-insensitively, tolerating padded tags
304//     like `<think >` (a regex whose open tag lacked `\s*` would leak their bodies)
305//   - nested tags can't leak: inner reasoning stays inside depth > 0
306//   - an unterminated block is dropped through end-of-text rather than leaking its body
307//   - a stray closing tag at depth 0 is dropped
308// note: this is content-wide, so a review that legitimately quotes a <think> tag in a code
309// snippet will have it stripped too — an accepted tradeoff for clean aggregation.
310/// The text outside think blocks, plus where the body of an unclosed block begins. An offset
311/// rather than a flag so recovery never re-parses tags: with several blocks or a stray closer, the
312/// first `<think>` is not the one that stayed open.
313fn scan_think_blocks(text: &str) -> (String, Option<usize>) {
314    // match `<think` (or `</think` when `close`) + optional whitespace + `>` at the start of
315    // `s`, case-insensitively; return the matched byte length. `<thinking>` is not a tag (the
316    // char after `think` must be whitespace or `>`).
317    fn match_think_tag(s: &str, close: bool) -> Option<usize> {
318        let prefix = if close { "</think" } else { "<think" };
319        if !s.get(..prefix.len())?.eq_ignore_ascii_case(prefix) {
320            return None;
321        }
322        let after = &s[prefix.len()..];
323        let ws = after.len() - after.trim_start().len();
324        after[ws..]
325            .starts_with('>')
326            .then_some(prefix.len() + ws + 1)
327    }
328
329    let mut out = String::with_capacity(text.len());
330    let mut depth: usize = 0;
331    let mut consumed = 0usize;
332    let mut open_body_start = None;
333    let mut rest = text;
334    while !rest.is_empty() {
335        if rest.starts_with('<') {
336            if let Some(len) = match_think_tag(rest, false) {
337                depth += 1;
338                consumed += len;
339                if depth == 1 {
340                    open_body_start = Some(consumed);
341                }
342                rest = &rest[len..];
343                continue;
344            }
345            if let Some(len) = match_think_tag(rest, true) {
346                depth = depth.saturating_sub(1);
347                if depth == 0 {
348                    open_body_start = None;
349                }
350                consumed += len;
351                rest = &rest[len..];
352                continue;
353            }
354        }
355        let ch = rest.chars().next().expect("rest is non-empty");
356        if depth == 0 {
357            out.push(ch);
358        }
359        consumed += ch.len_utf8();
360        rest = &rest[ch.len_utf8()..];
361    }
362    let unclosed_body = match depth > 0 {
363        true => open_body_start,
364        false => None,
365    };
366    (out.trim().to_string(), unclosed_body)
367}
368
369pub trait LLMClient: Send + Sync {
370    fn completion(
371        &self,
372        completion: Completion,
373    ) -> impl Future<Output = Result<CompletionResponse>> + Send;
374
375    fn into_arc(self) -> Arc<dyn LLMClientDyn>
376    where
377        Self: Sized + 'static,
378    {
379        Arc::new(self)
380    }
381}
382
383pub trait LLMClientDyn: Send + Sync {
384    fn completion(
385        &self,
386        completion: Completion,
387    ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>>;
388}
389
390impl<T: LLMClient> LLMClientDyn for T {
391    fn completion(
392        &self,
393        completion: Completion,
394    ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>> {
395        Box::pin(LLMClient::completion(self, completion))
396    }
397}
398
399impl LLMClient for Box<dyn LLMClientDyn> {
400    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
401        (**self).completion(completion).await
402    }
403}
404
405/// What the provider said about a response carrying neither text nor a tool call. Without it an
406/// exhausted output budget is indistinguishable from a model that had nothing to say.
407fn empty_response_diagnosis(response: &CompletionResponse) -> String {
408    let output_tokens = response.usage.output_tokens;
409    match &response.finish_reason {
410        FinishReason::MaxTokens => format!(
411            "hit the output limit after {output_tokens} tokens without emitting content — \
412             reasoning consumed the whole budget, so raise max_tokens or leave it unset to use \
413             the provider's own limit"
414        ),
415        other => format!("finish_reason {other:?}, {output_tokens} output tokens"),
416    }
417}
418
419pub struct RetryingLLM<C> {
420    inner: C,
421}
422
423pub trait WithRetryExt: Sized {
424    fn with_retry(self) -> RetryingLLM<Self> {
425        RetryingLLM { inner: self }
426    }
427}
428
429impl<T: LLMClient> WithRetryExt for T {}
430
431impl<C: LLMClient> LLMClient for RetryingLLM<C> {
432    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
433        let mut attempt = 0usize;
434        loop {
435            attempt += 1;
436            match self.inner.completion(completion.clone()).await {
437                Ok(response) => {
438                    if response.text().is_empty() && response.tool_calls().is_none() {
439                        let diagnosis = empty_response_diagnosis(&response);
440                        if attempt >= MAX_COMPLETION_ATTEMPTS {
441                            eyre::bail!(
442                                "model returned empty response after {attempt} attempts: {diagnosis}"
443                            );
444                        }
445                        let backoff = jittered_backoff(attempt, BASE_BACKOFF_MS, MAX_BACKOFF_MS);
446                        warn!(
447                            model = %completion.model,
448                            attempt,
449                            max_attempts = MAX_COMPLETION_ATTEMPTS,
450                            backoff_ms = backoff.as_millis(),
451                            diagnosis,
452                            "retrying after empty model response"
453                        );
454                        tokio::time::sleep(backoff).await;
455                        continue;
456                    }
457                    return Ok(response);
458                }
459                Err(err) => {
460                    let policy = retry_policy(&err);
461                    if !policy.retry || attempt >= policy.max_attempts {
462                        return Err(err);
463                    }
464                    let backoff =
465                        jittered_backoff(attempt, policy.base_backoff_ms, policy.max_backoff_ms);
466                    warn!(
467                        model = %completion.model,
468                        attempt,
469                        max_attempts = policy.max_attempts,
470                        backoff_ms = backoff.as_millis(),
471                        error = %err,
472                        "retrying model completion after error"
473                    );
474                    tokio::time::sleep(backoff).await;
475                }
476            }
477        }
478    }
479}
480
481/// randomly alternates between models within a single agentic loop — see https://xbow.com/blog/alloy-agents
482///
483/// inner clients must already be wrapped with retry (e.g. via `.with_retry()`); AlloyClient does not add retry itself
484/// One model in the pool, carrying the settings that belong to it rather than to the role.
485pub struct AlloySlot {
486    pub client: Arc<dyn LLMClientDyn>,
487    pub model: String,
488    pub max_tokens: Option<u64>,
489}
490
491pub struct AlloyClient {
492    slots: Vec<AlloySlot>,
493}
494
495impl AlloyClient {
496    pub fn new(slots: Vec<AlloySlot>) -> Result<Self> {
497        if slots.is_empty() {
498            eyre::bail!("AlloyClient requires at least one slot");
499        }
500        Ok(Self { slots })
501    }
502
503    fn pick_idx(&self) -> usize {
504        use rand::RngExt;
505        rand::rng().random_range(0..self.slots.len())
506    }
507}
508
509impl LLMClientDyn for AlloyClient {
510    fn completion(
511        &self,
512        mut completion: Completion,
513    ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>> {
514        let slot = &self.slots[self.pick_idx()];
515        completion.model = slot.model.clone();
516        // the selected model's own cap, not the role's: a cap belongs to the model it was set for
517        completion.max_tokens = slot.max_tokens;
518        let client = Arc::clone(&slot.client);
519        let model = slot.model.clone();
520        Box::pin(async move {
521            let mut response = client.completion(completion).await?;
522            response.selected_model = Some(model);
523            Ok(response)
524        })
525    }
526}
527
528/// Run a single completion under a concurrency permit. The permit is held only for the duration of
529/// this one call and released immediately after — never across a subagent spawn — so callers may
530/// block on acquire without risking deadlock. This is the single chokepoint that bounds account-wide
531/// in-flight LLM calls; route every concurrent completion (agent turns, compaction) through it.
532pub async fn throttled_completion(
533    semaphore: &Semaphore,
534    client: &Arc<dyn LLMClientDyn>,
535    completion: Completion,
536) -> Result<CompletionResponse> {
537    let _permit = semaphore.acquire().await.expect("llm semaphore closed");
538    client.completion(completion).await
539}
540
541struct RetryPolicy {
542    retry: bool,
543    max_attempts: usize,
544    base_backoff_ms: u64,
545    max_backoff_ms: u64,
546}
547
548fn retry_policy(err: &eyre::Report) -> RetryPolicy {
549    if is_rate_limit_error(err) {
550        return RetryPolicy {
551            retry: true,
552            max_attempts: RATE_LIMIT_MAX_COMPLETION_ATTEMPTS,
553            base_backoff_ms: RATE_LIMIT_BASE_BACKOFF_MS,
554            max_backoff_ms: RATE_LIMIT_MAX_BACKOFF_MS,
555        };
556    }
557
558    if is_non_retryable_client_error(err) {
559        return RetryPolicy {
560            retry: false,
561            max_attempts: 0,
562            base_backoff_ms: 0,
563            max_backoff_ms: 0,
564        };
565    }
566
567    RetryPolicy {
568        retry: true,
569        max_attempts: MAX_COMPLETION_ATTEMPTS,
570        base_backoff_ms: BASE_BACKOFF_MS,
571        max_backoff_ms: MAX_BACKOFF_MS,
572    }
573}
574
575/// HTTP status codes the retry/refresh classifiers key on, paired with their canonical reason
576/// phrase. The phrase lets us recognize the plain-text `"<code> <reason>"` status-line form
577/// (`401 Unauthorized`, `429 Too Many Requests`) that carries no JSON status key.
578const STATUS_REASONS: &[(u16, &str)] = &[
579    (400, "bad request"),
580    (401, "unauthorized"),
581    (402, "payment required"),
582    (403, "forbidden"),
583    (404, "not found"),
584    (429, "too many requests"),
585    (500, "internal server error"),
586    (502, "bad gateway"),
587    (503, "service unavailable"),
588    (504, "gateway timeout"),
589];
590
591/// How far back (in bytes) to scan for a status key before a candidate number. Comfortably covers
592/// `"statusCode": ` even with extra spacing, while staying local enough that an unrelated
593/// `code`/`status` field elsewhere in the body doesn't bleed in.
594const STATUS_KEY_WINDOW: usize = 24;
595
596/// True if `status` (an HTTP status code) appears in `msg` as a genuine status reference: a
597/// standalone number (not part of a longer digit run) that is *also* in an HTTP-status context —
598/// either immediately followed by its canonical reason phrase (`401 Unauthorized`) or preceded
599/// within [`STATUS_KEY_WINDOW`] by a `status`/`code` key (covering `"statusCode": 401`, `:401`,
600/// `Invalid status code 401`, ...). The context requirement keeps incidental standalone numbers in
601/// a raw provider body — `400 tokens`, `trace 404`, `req_402abc` — from being misread as the
602/// response status. Provider errors surface the status only inside the raw body, whose punctuation
603/// varies (spaced `"statusCode": 401` vs compact `"statusCode":401`), so we can't rely on fixed
604/// delimiters; the trade-off is that a status carrying neither a nearby key nor a reason phrase is
605/// not recognized (rare in practice, and recoverable — at worst a retried/failed request).
606pub(crate) fn mentions_http_status(msg: &str, status: u16) -> bool {
607    let lower = msg.to_ascii_lowercase();
608    let needle = status.to_string();
609    let reason = STATUS_REASONS
610        .iter()
611        .find(|(code, _)| *code == status)
612        .map(|(_, phrase)| *phrase);
613    let bytes = lower.as_bytes();
614    let mut from = 0;
615    while let Some(rel) = lower[from..].find(&needle) {
616        let start = from + rel;
617        let end = start + needle.len();
618        let prev_digit = start > 0 && bytes[start - 1].is_ascii_digit();
619        let next_digit = end < bytes.len() && bytes[end].is_ascii_digit();
620        if !prev_digit && !next_digit && status_in_context(&lower, start, end, reason) {
621            return true;
622        }
623        from = start + 1;
624    }
625    false
626}
627
628/// Whether the standalone number at `start..end` in `lower` (already lowercased) sits in an
629/// HTTP-status context: followed by its reason phrase, or preceded within [`STATUS_KEY_WINDOW`] by a
630/// `status`/`code` key. `start`/`end` are byte offsets on char boundaries (the needle is ASCII); the
631/// preceding-window start is floored to a boundary so a multibyte char in the body can't panic the
632/// slice.
633fn status_in_context(lower: &str, start: usize, end: usize, reason: Option<&str>) -> bool {
634    if let Some(reason) = reason {
635        if lower[end..].trim_start().starts_with(reason) {
636            return true;
637        }
638    }
639    let mut window_start = start.saturating_sub(STATUS_KEY_WINDOW);
640    while !lower.is_char_boundary(window_start) {
641        window_start += 1;
642    }
643    // `statuscode` is the lowercased compact `statusCode` (no separator), where neither `status`
644    // nor `code` is a whole word on its own, so it needs its own key.
645    key_word_present(lower, window_start, start, "status")
646        || key_word_present(lower, window_start, start, "code")
647        || key_word_present(lower, window_start, start, "statuscode")
648}
649
650/// Whether `key` appears as a whole word within `lower[lo..hi]`. The left edge must be the string
651/// start or a non-`[a-z0-9_]` byte; the right edge must be the string end or a non-`[a-z0-9]` byte
652/// (`_` is allowed on the right so `status_code` still matches via the `status` key, while
653/// `decode`/`encode`/`unicode`/`error_code`/`codec`/`statuslike` do NOT count as keys). Boundary
654/// checks read `lower`'s absolute bytes, so a word split by the `[lo..hi]` window edge is judged
655/// against its real neighbours. `key` is ASCII; `lo`/`hi` are on char boundaries.
656fn key_word_present(lower: &str, lo: usize, hi: usize, key: &str) -> bool {
657    let bytes = lower.as_bytes();
658    let region = &lower[lo..hi];
659    let mut from = 0;
660    while let Some(rel) = region[from..].find(key) {
661        let abs = lo + from + rel;
662        let left_ok = abs == 0 || {
663            let b = bytes[abs - 1];
664            !b.is_ascii_alphanumeric() && b != b'_'
665        };
666        let after = abs + key.len();
667        let right_ok = after >= bytes.len() || !bytes[after].is_ascii_alphanumeric();
668        if left_ok && right_ok {
669            return true;
670        }
671        from += rel + 1;
672    }
673    false
674}
675
676/// Permanent error *types* that direct Anthropic/OpenAI bodies carry instead of a numeric status.
677/// rig flattens a non-2xx response to `ProviderError(<raw body>)` with the HTTP status dropped, so
678/// for those providers the numeric-status matchers never fire — these strings are the only signal.
679/// `insufficient_quota` (out of credits) is permanent despite arriving as HTTP 429: retrying never
680/// helps. Auth/permission `403`-class types are deliberately included here, *not* in the rate-limit
681/// set. All lowercase; matched as substrings on the lowercased chain.
682const NON_RETRYABLE_ERROR_TYPES: &[&str] = &[
683    "authentication_error",
684    "invalid_api_key",
685    "permission_error",
686    "permission_denied",
687    "invalid_request_error",
688    "not_found_error",
689    "context_length_exceeded",
690    "insufficient_quota",
691];
692
693/// Transient error *types* (overload / throttling) that warrant the rate-limit backoff policy.
694const RATE_LIMIT_ERROR_TYPES: &[&str] = &[
695    "rate_limit_error",
696    "rate_limit_exceeded",
697    "overloaded_error",
698];
699
700/// Error types that often arrive with HTTP 429 but are not transient throttles.
701const PERMANENT_QUOTA_ERROR_TYPES: &[&str] = &["insufficient_quota"];
702
703/// Whether an error chain reports a context-window overflow — the one synthesis failure
704/// where "select fewer presets" is real remediation. Matches the OpenAI-style type token
705/// (`context_length_exceeded`) and the Anthropic shape — an `invalid_request_error` whose
706/// message says the prompt is too long; a generic `invalid_request_error` alone does NOT
707/// qualify (those are malformed-request bugs, not size problems).
708pub fn is_context_length_error(err: &eyre::Report) -> bool {
709    let msg = format!("{err:#}").to_ascii_lowercase();
710    msg.contains("context_length_exceeded")
711        || (msg.contains("invalid_request_error") && msg.contains("prompt is too long"))
712}
713
714fn is_non_retryable_client_error(err: &eyre::Report) -> bool {
715    // Walk the whole chain: provider clients map non-2xx to a `ProviderError` carrying the raw
716    // response body, then `.wrap_err_with(...)` adds a top-level context. `err.to_string()` renders
717    // only that context, so the status code would be invisible; `{err:#}` joins the full chain.
718    let msg = format!("{err:#}");
719    // a 5xx response takes precedence: even when a 4xx is nested in the body (e.g. an upstream
720    // `"code": 403` inside a 502 envelope), the response itself is a retryable server error, so we
721    // must not classify it as a permanent client error. Cover the full registered 5xx range; the
722    // JSON `status`/`code`-key form is matched even for codes without a reason phrase here.
723    if [500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511]
724        .iter()
725        .any(|&status| mentions_http_status(&msg, status))
726    {
727        return false;
728    }
729    if [400, 401, 402, 403, 404]
730        .iter()
731        .any(|&status| mentions_http_status(&msg, status))
732    {
733        return true;
734    }
735    let lower = msg.to_ascii_lowercase();
736    NON_RETRYABLE_ERROR_TYPES.iter().any(|t| lower.contains(t))
737}
738
739fn is_rate_limit_error(err: &eyre::Report) -> bool {
740    // Same reasoning as `is_non_retryable_client_error`: walk the full chain so a 429 carried in a
741    // wrapped `ProviderError` body still maps to the rate-limit backoff policy. Permanent quota
742    // types are excluded first because retrying them only burns the full rate-limit retry budget.
743    let msg = format!("{err:#}").to_ascii_lowercase();
744    if PERMANENT_QUOTA_ERROR_TYPES.iter().any(|t| msg.contains(t)) {
745        return false;
746    }
747    mentions_http_status(&msg, 429)
748        || msg.contains("rate limit")
749        || msg.contains("too many requests")
750        || msg.contains("tokens per minute")
751        || msg.contains("requests per minute")
752        || RATE_LIMIT_ERROR_TYPES.iter().any(|t| msg.contains(t))
753}
754
755fn jittered_backoff(attempt: usize, base_backoff_ms: u64, max_backoff_ms: u64) -> Duration {
756    let exp = 2u64.saturating_pow((attempt - 1) as u32);
757    let base = (base_backoff_ms * exp).min(max_backoff_ms);
758    let jitter = jitter_factor();
759    let jittered = (base as f64 * jitter).round() as u64;
760    Duration::from_millis(jittered.max(1))
761}
762
763fn jitter_factor() -> f64 {
764    let nanos = SystemTime::now()
765        .duration_since(UNIX_EPOCH)
766        .map(|d| d.subsec_nanos())
767        .unwrap_or(0);
768    let scaled = (nanos % 1000) as f64 / 1000.0;
769    0.5 + scaled
770}
771
772#[derive(Debug, Deserialize)]
773struct OpenRouterErrorEnvelope {
774    error: OpenRouterErrorBody,
775}
776
777#[derive(Debug, Deserialize)]
778struct OpenRouterErrorBody {
779    message: String,
780    code: Option<u16>,
781}
782
783fn normalize_openrouter_completion_error(err: &CompletionError) -> eyre::Report {
784    match err {
785        CompletionError::ResponseError(msg) => normalize_openrouter_response_error(msg),
786        CompletionError::ProviderError(msg) => eyre::eyre!("ProviderError: {msg}"),
787        _ => eyre::eyre!("{err}"),
788    }
789}
790
791fn normalize_openrouter_response_error(msg: &str) -> eyre::Report {
792    if msg.contains("no message or tool call") || msg.contains("no choices") {
793        return eyre::eyre!("empty response from model (no message or tool call)");
794    }
795
796    if let Some(err) = parse_openrouter_error_envelope(msg) {
797        return match err.code {
798            Some(code) => eyre::eyre!(
799                "HttpError: Invalid status code {code} OpenRouter provider error: {}",
800                err.message
801            ),
802            None => eyre::eyre!("ProviderError: {}", err.message),
803        };
804    }
805
806    eyre::eyre!("ResponseError: {msg}")
807}
808
809fn parse_openrouter_error_envelope(msg: &str) -> Option<OpenRouterErrorBody> {
810    let body = msg.split_once("response body:")?.1.trim();
811    serde_json::from_str::<OpenRouterErrorEnvelope>(body)
812        .ok()
813        .map(|envelope| envelope.error)
814}
815
816fn is_local_base_url(base_url: Option<&str>) -> bool {
817    base_url
818        .map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
819        .unwrap_or(false)
820}
821
822/// Resolve the API key when its env var is unset: a local base_url needs no real key, otherwise it
823/// is a hard error naming the missing var.
824fn missing_or_local(key_env: &str, base_url: Option<&str>) -> Result<String> {
825    if is_local_base_url(base_url) {
826        Ok("local".to_string())
827    } else {
828        Err(eyre::eyre!("missing env var {key_env}"))
829    }
830}
831
832pub enum LLMProvider {
833    Anthropic {
834        base_url: Option<String>,
835        api_key_env: Option<String>,
836    },
837    Gemini {
838        base_url: Option<String>,
839        api_key_env: Option<String>,
840    },
841    OpenAi {
842        base_url: Option<String>,
843        api_key_env: Option<String>,
844    },
845    OpenRouter {
846        api_key_env: String,
847    },
848}
849
850impl LLMProvider {
851    pub fn client_from_env(&self) -> Result<Box<dyn LLMClientDyn>> {
852        match self {
853            LLMProvider::Anthropic {
854                base_url,
855                api_key_env,
856            } => {
857                let key_env = api_key_env.as_deref().unwrap_or("ANTHROPIC_API_KEY");
858                let api_key = std::env::var(key_env)
859                    .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
860                let mut builder = anthropic::Client::builder().api_key(api_key);
861                if let Some(url) = base_url {
862                    builder = builder.base_url(url);
863                }
864                Ok(Box::new(builder.build()?))
865            }
866            LLMProvider::Gemini {
867                base_url,
868                api_key_env,
869            } => {
870                // An explicit api_key_env overrides the GEMINI_API_KEY → GOOGLE_AI_API_KEY default
871                // chain; a local base_url needs no key (mirrors the Anthropic/OpenAi arms).
872                let api_key = match api_key_env {
873                    Some(key_env) => std::env::var(key_env)
874                        .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?,
875                    None => std::env::var("GEMINI_API_KEY")
876                        .or_else(|_| std::env::var("GOOGLE_AI_API_KEY"))
877                        .or_else(|_| {
878                            missing_or_local(
879                                "GEMINI_API_KEY (or GOOGLE_AI_API_KEY)",
880                                base_url.as_deref(),
881                            )
882                        })?,
883                };
884                let mut builder = gemini::Client::builder().api_key(api_key);
885                if let Some(url) = base_url {
886                    builder = builder.base_url(url);
887                }
888                let client = builder
889                    .build()
890                    .map_err(|e| eyre::eyre!("failed to create Gemini client: {e}"))?;
891                Ok(Box::new(client))
892            }
893            LLMProvider::OpenAi {
894                base_url,
895                api_key_env,
896            } => {
897                let key_env = api_key_env.as_deref().unwrap_or("OPENAI_API_KEY");
898                let api_key = std::env::var(key_env)
899                    .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
900                let mut builder = openai::CompletionsClient::builder().api_key(&api_key);
901                if let Some(url) = base_url {
902                    builder = builder.base_url(url);
903                }
904                Ok(Box::new(builder.build()?))
905            }
906            LLMProvider::OpenRouter { api_key_env } => {
907                let api_key = std::env::var(api_key_env)
908                    .map_err(|_| eyre::eyre!("missing env var {api_key_env}"))?;
909                let client = openrouter::Client::builder()
910                    .api_key(&api_key)
911                    .http_headers(openrouter_headers()?)
912                    .build()?;
913                Ok(Box::new(client))
914            }
915        }
916    }
917}
918
919pub fn openrouter_headers() -> Result<reqwest::header::HeaderMap> {
920    let mut headers = reqwest::header::HeaderMap::new();
921    headers.insert(
922        "HTTP-Referer",
923        "https://github.com/arsenyinfo/nitpicker".parse()?,
924    );
925    headers.insert("X-OpenRouter-Title", "nitpicker".parse()?);
926    headers.insert(
927        "X-OpenRouter-Categories",
928        "cli-agent,programming-app".parse()?,
929    );
930    Ok(headers)
931}
932
933impl LLMClient for openrouter::Client {
934    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
935        let model_name = completion.model.clone();
936        let mut request: rig_core::completion::CompletionRequest = completion.into();
937        request.model = Some(model_name.clone());
938        let model = self.completion_model(&model_name);
939        let response = model
940            .completion(request)
941            .await
942            .map_err(|e| normalize_openrouter_completion_error(&e))?;
943        let finish_reason = response
944            .raw_response
945            .choices
946            .first()
947            .and_then(|c| c.finish_reason.as_deref())
948            .map(|reason| match reason {
949                "stop" => FinishReason::Stop,
950                "length" => FinishReason::MaxTokens,
951                "tool_calls" => FinishReason::ToolUse,
952                other => FinishReason::Other(other.to_string()),
953            })
954            .unwrap_or(FinishReason::None);
955        let finish_reason = resolve_finish_reason(&response.choice, finish_reason);
956        Ok(CompletionResponse {
957            choice: response.choice,
958            finish_reason,
959            usage: TokenUsage::from_provider(&response.usage, CacheAccounting::InsidePrompt),
960            selected_model: Some(model_name),
961        })
962    }
963}
964
965/// Create a Gemini client that routes through the local OAuth proxy
966#[cfg(feature = "antigravity")]
967pub fn create_gemini_client_with_proxy(
968    proxy_url: &str,
969) -> Result<std::sync::Arc<dyn LLMClientDyn>> {
970    // Build a Gemini client with the proxy URL as the base URL
971    // The API key doesn't matter for OAuth proxy, but is required by the builder
972    let api_key = std::env::var("GEMINI_API_KEY").unwrap_or_else(|_| "oauth-proxy".to_string());
973    let client = gemini::Client::builder()
974        .api_key(api_key)
975        .base_url(proxy_url)
976        .build()?;
977    Ok(client.with_retry().into_arc())
978}
979
980impl LLMClient for anthropic::Client {
981    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
982        let model_name = completion.model.clone();
983        let mut request: rig_core::completion::CompletionRequest = completion.into();
984        request.model = Some(model_name.clone());
985        // Anthropic requires `max_tokens`, so "no cap" cannot be expressed here. rig's own default
986        // covers only model names it recognizes and falls back to 2048 for every compatible
987        // gateway — less than one review turn spends on reasoning.
988        request
989            .max_tokens
990            .get_or_insert(ANTHROPIC_DEFAULT_MAX_TOKENS);
991        let model = self.completion_model(model_name.clone());
992        let response = model
993            .completion(request)
994            .await
995            .wrap_err_with(|| format!("Anthropic completion failed for model '{model_name}'"))?;
996        let finish_reason = response
997            .raw_response
998            .stop_reason
999            .clone()
1000            .map(|reason| match reason.as_str() {
1001                "end_turn" => FinishReason::Stop,
1002                "max_tokens" => FinishReason::MaxTokens,
1003                "tool_use" => FinishReason::ToolUse,
1004                other => FinishReason::Other(other.to_string()),
1005            })
1006            .unwrap_or(FinishReason::None);
1007        let finish_reason = resolve_finish_reason(&response.choice, finish_reason);
1008        Ok(CompletionResponse {
1009            choice: response.choice,
1010            finish_reason,
1011            usage: TokenUsage::from_provider(&response.usage, CacheAccounting::OutsidePrompt),
1012            selected_model: Some(model_name),
1013        })
1014    }
1015}
1016
1017impl LLMClient for gemini::Client {
1018    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
1019        let model_name = completion.model.clone();
1020        let params = build_gemini_additional_params(&completion)?;
1021        let mut request: rig_core::completion::CompletionRequest = completion.into();
1022        request.model = Some(model_name.clone());
1023        request.additional_params = Some(params);
1024        let model = self.completion_model(model_name.clone());
1025        let response = model
1026            .completion(request)
1027            .await
1028            .wrap_err_with(|| format!("Gemini completion failed for model '{model_name}'"))?;
1029        let finish_reason = response
1030            .raw_response
1031            .candidates
1032            .first()
1033            .and_then(|candidate| candidate.finish_reason.clone())
1034            .map(map_gemini_finish_reason)
1035            .unwrap_or(FinishReason::None);
1036        let finish_reason = resolve_finish_reason(&response.choice, finish_reason);
1037        Ok(CompletionResponse {
1038            choice: response.choice,
1039            finish_reason,
1040            usage: TokenUsage::from_provider(&response.usage, CacheAccounting::InsidePrompt),
1041            selected_model: Some(model_name),
1042        })
1043    }
1044}
1045
1046fn model_needs_max_completion_tokens(model: &str) -> bool {
1047    model.starts_with("o1")
1048        || model.starts_with("o3")
1049        || model.starts_with("o4")
1050        || model.starts_with("gpt-4o")
1051        || model.starts_with("gpt-4.1")
1052        || model.starts_with("gpt-4.5")
1053        || model.starts_with("gpt-5")
1054}
1055
1056/// Deep-merge `extra` over `base`: nested objects are merged recursively; on a scalar/type
1057/// conflict `extra` wins. Used to overlay computed request params without discarding caller-set
1058/// ones (e.g. a Gemini `generation_config` the caller supplied alongside its own keys).
1059pub(crate) fn merge_json(base: Value, extra: Value) -> Value {
1060    match (base, extra) {
1061        (Value::Object(mut base_obj), Value::Object(extra_obj)) => {
1062            for (k, v) in extra_obj {
1063                let merged = match base_obj.remove(&k) {
1064                    Some(existing) => merge_json(existing, v),
1065                    None => v,
1066                };
1067                base_obj.insert(k, merged);
1068            }
1069            Value::Object(base_obj)
1070        }
1071        (_, extra) => extra,
1072    }
1073}
1074
1075impl LLMClient for openai::CompletionsClient {
1076    async fn completion(&self, mut completion: Completion) -> Result<CompletionResponse> {
1077        // Newer OpenAI models (o1, o3, o4-mini, gpt-4o, gpt-5, etc.) reject the legacy
1078        // `max_tokens` param and require `max_completion_tokens` instead. Since rig always
1079        // serializes `max_tokens`, we move the value into `additional_params` and clear it.
1080        if let Some(max) = completion.max_tokens {
1081            if model_needs_max_completion_tokens(&completion.model) {
1082                let extra = serde_json::json!({ "max_completion_tokens": max });
1083                completion.additional_params = Some(match completion.additional_params.take() {
1084                    Some(existing) => merge_json(existing, extra),
1085                    None => extra,
1086                });
1087                completion.max_tokens = None;
1088            }
1089        }
1090        let model_name = completion.model.clone();
1091        let mut request: rig_core::completion::CompletionRequest = completion.into();
1092        request.model = Some(model_name.clone());
1093        let model = self.completion_model(model_name.clone());
1094        let response = model
1095            .completion(request)
1096            .await
1097            .wrap_err_with(|| format!("OpenAI completion failed for model '{model_name}'"))?;
1098        let finish_reason = response
1099            .raw_response
1100            .choices
1101            .first()
1102            .map(|choice| match choice.finish_reason.as_str() {
1103                "stop" => FinishReason::Stop,
1104                "length" => FinishReason::MaxTokens,
1105                "tool_calls" => FinishReason::ToolUse,
1106                other => FinishReason::Other(other.to_string()),
1107            })
1108            .unwrap_or(FinishReason::None);
1109        let finish_reason = resolve_finish_reason(&response.choice, finish_reason);
1110        Ok(CompletionResponse {
1111            choice: response.choice,
1112            finish_reason,
1113            usage: TokenUsage::from_provider(&response.usage, CacheAccounting::InsidePrompt),
1114            selected_model: Some(model_name),
1115        })
1116    }
1117}
1118
1119#[derive(Debug, Serialize)]
1120struct GeminiAdditionalParams {
1121    generation_config: Option<GenerationConfig>,
1122}
1123
1124impl GeminiAdditionalParams {
1125    fn from_completion(completion: &Completion) -> Self {
1126        let config = GenerationConfig {
1127            // saturating: `as i32` would turn a cap past i32::MAX into a negative field
1128            max_output_tokens: completion
1129                .max_tokens
1130                .map(|value| i32::try_from(value).unwrap_or(i32::MAX)),
1131        };
1132        Self {
1133            generation_config: Some(config),
1134        }
1135    }
1136}
1137
1138/// Overlay the computed generation config onto any caller-supplied `additional_params` instead of
1139/// replacing them, mirroring the OpenAI path's `merge_json`. The computed value wins on conflict
1140/// (e.g. the typed `max_tokens`), while caller keys like safety settings or a nested
1141/// `generation_config.temperature` survive.
1142fn build_gemini_additional_params(completion: &Completion) -> Result<Value> {
1143    let computed = serde_json::to_value(GeminiAdditionalParams::from_completion(completion))?;
1144    Ok(match &completion.additional_params {
1145        Some(existing) => merge_json(existing.clone(), computed),
1146        None => computed,
1147    })
1148}
1149
1150#[derive(Debug, Serialize, Default)]
1151struct GenerationConfig {
1152    #[serde(skip_serializing_if = "Option::is_none")]
1153    max_output_tokens: Option<i32>,
1154}
1155
1156/// A structured tool call in the choice overrides the wire finish reason: providers can pair
1157/// tool calls with `stop`-like reasons, and `CompletionResponse::tool_calls()` only surfaces
1158/// calls when the reason is `ToolUse`.
1159fn resolve_finish_reason(
1160    choice: &OneOrMany<AssistantContent>,
1161    wire_reason: FinishReason,
1162) -> FinishReason {
1163    match choice
1164        .iter()
1165        .any(|content| matches!(content, AssistantContent::ToolCall(_)))
1166    {
1167        true => FinishReason::ToolUse,
1168        false => wire_reason,
1169    }
1170}
1171
1172fn map_gemini_finish_reason(
1173    reason: gemini::completion::gemini_api_types::FinishReason,
1174) -> FinishReason {
1175    use gemini::completion::gemini_api_types::FinishReason as GeminiFinishReason;
1176    match reason {
1177        GeminiFinishReason::Stop => FinishReason::Stop,
1178        GeminiFinishReason::MaxTokens => FinishReason::MaxTokens,
1179        GeminiFinishReason::FinishReasonUnspecified => FinishReason::None,
1180        other => FinishReason::Other(format!("{other:?}")),
1181    }
1182}
1183
1184#[cfg(test)]
1185mod tests {
1186    use super::*;
1187    use rig_core::completion::Usage;
1188
1189    fn strip_think_blocks(text: &str) -> String {
1190        scan_think_blocks(text).0
1191    }
1192    use serde_json::json;
1193
1194    fn response_with(choice: Vec<AssistantContent>) -> CompletionResponse {
1195        CompletionResponse {
1196            choice: OneOrMany::many(choice).expect("non-empty choice"),
1197            finish_reason: FinishReason::Stop,
1198            usage: TokenUsage::default(),
1199            selected_model: None,
1200        }
1201    }
1202
1203    fn reasoning_item(text: &str) -> AssistantContent {
1204        AssistantContent::Reasoning(rig_core::completion::message::Reasoning::new(text))
1205    }
1206
1207    /// The block is never closed, so the scanner drops the verdict with the reasoning — but the
1208    /// reasoning is also reported structurally, so it can be subtracted exactly.
1209    #[test]
1210    fn unterminated_think_keeps_the_answer_and_drops_the_duplicated_reasoning() {
1211        let reasoning = "The debate is extremely brief. The Actor suggested `eyre`.";
1212        let response = response_with(vec![
1213            reasoning_item(reasoning),
1214            AssistantContent::text(format!(
1215                "<think>\n{reasoning}\n\n### Verdict\n**Agreed: use `eyre` for applications.**"
1216            )),
1217        ]);
1218        assert_eq!(
1219            response.text(),
1220            "### Verdict\n**Agreed: use `eyre` for applications.**"
1221        );
1222    }
1223
1224    /// Leading text hides the answer just as thoroughly, but makes the response read as
1225    /// successful — so nothing retries and the verdict is lost silently.
1226    #[test]
1227    fn unterminated_think_after_a_prefix_still_recovers_the_answer() {
1228        let reasoning = "Weighing both sides.";
1229        let response = response_with(vec![
1230            reasoning_item(reasoning),
1231            AssistantContent::text(format!(
1232                "Here is my review.\n<think>\n{reasoning}\n\n### Verdict\nShip it."
1233            )),
1234        ]);
1235        assert_eq!(
1236            response.text(),
1237            "Here is my review.\n\n### Verdict\nShip it."
1238        );
1239    }
1240
1241    /// OpenRouter splits `reasoning_details` mid-sentence, so a newline join stops the fragments
1242    /// matching their copy inside the block and the whole chain leaks into the answer.
1243    #[test]
1244    fn fragmented_reasoning_is_concatenated_without_separators() {
1245        let response = response_with(vec![
1246            reasoning_item("weighing the options"),
1247            reasoning_item(" carefully."),
1248            AssistantContent::text("<think>\nweighing the options carefully.\n\nVerdict: ship it."),
1249        ]);
1250        assert_eq!(response.text(), "Verdict: ship it.");
1251    }
1252
1253    /// With no structured reasoning there is no way to tell reasoning from answer. Returning the
1254    /// body would both serve chain-of-thought as the verdict and make the response read as
1255    /// non-empty, silencing the retry that exists for a reply that never answered.
1256    #[test]
1257    fn unterminated_think_without_structured_reasoning_stays_empty() {
1258        let response = response_with(vec![AssistantContent::text(
1259            "<think>\nweighing it up\n\nVerdict: ship it.",
1260        )]);
1261        assert!(response.text().is_empty());
1262    }
1263
1264    /// A summary is a paraphrase of the chain, not a slice of it, so it cannot be subtracted from
1265    /// the body — matching it as a fragment would leave a mangled prefix behind.
1266    #[test]
1267    fn summary_reasoning_is_not_used_to_split_the_body() {
1268        let response = response_with(vec![
1269            AssistantContent::Reasoning(rig_core::completion::message::Reasoning::summaries(vec![
1270                "brief".to_string(),
1271            ])),
1272            AssistantContent::text("<think>private chain"),
1273        ]);
1274        assert!(response.text().is_empty());
1275    }
1276
1277    /// A reasoning string that happens to be a byte prefix of the answer must not chop it: "Ver"
1278    /// against "Verdict: ship it." would otherwise yield "dict: ship it.".
1279    #[test]
1280    fn a_prefix_that_cuts_mid_word_is_not_treated_as_reasoning() {
1281        let response = response_with(vec![
1282            reasoning_item("Ver"),
1283            AssistantContent::text("<think>Verdict: ship it."),
1284        ]);
1285        assert!(response.text().is_empty());
1286    }
1287
1288    /// With several blocks, the one that stayed open is not the first tag in the text. Recovery
1289    /// keys off the scanner's offset, so an earlier *closed* block cannot misdirect it.
1290    #[test]
1291    fn recovery_targets_the_block_that_stayed_open() {
1292        let response = response_with(vec![
1293            reasoning_item("secret"),
1294            AssistantContent::text("<think>old</think>\n<think>secret\n\nFINAL"),
1295        ]);
1296        assert_eq!(response.text(), "FINAL");
1297    }
1298
1299    /// A stray closing tag at depth 0 is dropped by the scanner and must not be mistaken for the
1300    /// opener when recovering.
1301    #[test]
1302    fn a_stray_closing_tag_does_not_misdirect_recovery() {
1303        let response = response_with(vec![
1304            reasoning_item("secret"),
1305            AssistantContent::text("</think><think>secret\n\nFINAL"),
1306        ]);
1307        assert_eq!(response.text(), "FINAL");
1308    }
1309
1310    /// A response that is only reasoning still collapses to empty, so the empty-response retry
1311    /// keeps working for models that genuinely returned no answer.
1312    #[test]
1313    fn a_reasoning_only_response_is_still_empty() {
1314        let reasoning = "still thinking about it";
1315        let response = response_with(vec![
1316            reasoning_item(reasoning),
1317            AssistantContent::text(format!("<think>\n{reasoning}")),
1318        ]);
1319        assert!(response.text().is_empty());
1320        let closed = response_with(vec![AssistantContent::text(
1321            "<think>done deliberating</think>",
1322        )]);
1323        assert!(closed.text().is_empty());
1324    }
1325
1326    /// A well-formed closed block is untouched by the recovery path.
1327    #[test]
1328    fn closed_think_block_still_yields_only_the_answer() {
1329        let response = response_with(vec![AssistantContent::text(
1330            "<think>weighing it up</think>Verdict: ship it.",
1331        )]);
1332        assert_eq!(response.text(), "Verdict: ship it.");
1333    }
1334
1335    /// Mirrors rig's Anthropic mapping: `input_tokens` excludes the cache buckets and
1336    /// `total_tokens` is their sum plus output (`anthropic/completion.rs`).
1337    fn anthropic_usage(input: u64, output: u64, cached: u64, creation: u64) -> Usage {
1338        let mut usage = Usage::new();
1339        usage.input_tokens = input;
1340        usage.output_tokens = output;
1341        usage.cached_input_tokens = cached;
1342        usage.cache_creation_input_tokens = creation;
1343        usage.total_tokens = input + cached + creation + output;
1344        usage
1345    }
1346
1347    fn anthropic(usage: &Usage) -> TokenUsage {
1348        TokenUsage::from_provider(usage, CacheAccounting::OutsidePrompt)
1349    }
1350
1351    fn prompt_inclusive(usage: &Usage) -> TokenUsage {
1352        TokenUsage::from_provider(usage, CacheAccounting::InsidePrompt)
1353    }
1354
1355    /// The same 3508-token prompt served from cache, as each provider reports it: Anthropic shows
1356    /// `input_tokens: 52` with the rest under `cache_read`, OpenAI shows the whole prompt. Both
1357    /// must meter identically, or a mixed-provider run sums numbers that mean different things —
1358    /// and the Anthropic shape read raw is what hid 98% of the prompt.
1359    #[test]
1360    fn provider_shapes_meter_a_cache_hit_identically() {
1361        let from_anthropic = anthropic(&anthropic_usage(52, 8, 3456, 0));
1362        let mut openai = Usage::new();
1363        openai.input_tokens = 3508;
1364        openai.output_tokens = 8;
1365        openai.cached_input_tokens = 3456;
1366        openai.total_tokens = 3516;
1367        let from_openai = prompt_inclusive(&openai);
1368
1369        assert_eq!(from_anthropic.input_tokens, 3508);
1370        assert_eq!(from_anthropic.input_tokens, from_openai.input_tokens);
1371        assert_eq!(
1372            from_anthropic.cached_input_tokens,
1373            from_openai.cached_input_tokens
1374        );
1375        for usage in [from_anthropic, from_openai] {
1376            assert_eq!(usage.total_tokens, usage.input_tokens + usage.output_tokens);
1377        }
1378    }
1379
1380    /// Gemini reports thinking and tool-use prompts beside both `input_tokens` and
1381    /// `output_tokens`, and its parts don't sum to its total — so no arithmetic can tell its shape
1382    /// apart from Anthropic's. Numbers are rig's own fixture (`gemini/completion.rs`) with the
1383    /// cache lowered to 8, the value that makes the buckets *look* like they fit outside the
1384    /// prompt. Charging them would report a 40-token prompt as 48.
1385    #[test]
1386    fn gemini_cache_reads_are_never_added_to_its_prompt() {
1387        let mut usage = Usage::new();
1388        usage.input_tokens = 40;
1389        usage.output_tokens = 30;
1390        usage.reasoning_tokens = 10;
1391        usage.tool_use_prompt_tokens = 12;
1392        usage.cached_input_tokens = 8;
1393        usage.total_tokens = 100;
1394        let usage = prompt_inclusive(&usage);
1395        assert_eq!(usage.input_tokens, 40);
1396        assert_eq!(usage.cached_input_tokens, 8);
1397    }
1398
1399    /// An OpenRouter gateway may report a total larger than prompt + completion. That slack must
1400    /// not turn its cache reads — already inside `prompt_tokens` — into extra prompt tokens.
1401    #[test]
1402    fn openrouter_total_disagreement_does_not_inflate_the_prompt() {
1403        let mut usage = Usage::new();
1404        usage.input_tokens = 500;
1405        usage.output_tokens = 10;
1406        usage.cached_input_tokens = 5;
1407        usage.total_tokens = 515;
1408        let usage = prompt_inclusive(&usage);
1409        assert_eq!(usage.input_tokens, 500);
1410        assert_eq!(usage.total_tokens, 510);
1411    }
1412
1413    /// A gateway that omits usage totals must still meter the prompt it reported.
1414    #[test]
1415    fn missing_provider_total_still_meters_reported_input() {
1416        let mut usage = Usage::new();
1417        usage.input_tokens = 1200;
1418        usage.output_tokens = 40;
1419        let usage = prompt_inclusive(&usage);
1420        assert_eq!(usage.input_tokens, 1200);
1421        assert_eq!(usage.total_tokens, 1240);
1422    }
1423
1424    /// Anthropic charges a cache *write* too, and reports it outside `input_tokens` like a read.
1425    #[test]
1426    fn anthropic_cache_writes_count_toward_the_prompt() {
1427        let usage = anthropic(&anthropic_usage(90, 10, 0, 4100));
1428        assert_eq!(usage.cache_creation_input_tokens, 4100);
1429        assert_eq!(usage.input_tokens, 4190);
1430        assert_eq!(usage.total_tokens, 4200);
1431    }
1432
1433    /// A provider reporting more cache than prompt is contradicting itself. Reporting the prompt
1434    /// as 5000 to make the breakdown fit would invent 4990 tokens of spend that were never billed,
1435    /// so both numbers are passed through as reported and the contradiction stays visible.
1436    #[test]
1437    fn contradictory_cache_metadata_is_not_papered_over() {
1438        let mut usage = Usage::new();
1439        usage.input_tokens = 10;
1440        usage.output_tokens = 5;
1441        usage.total_tokens = 15;
1442        usage.cached_input_tokens = 5_000;
1443        usage.cache_creation_input_tokens = 700;
1444        let usage = prompt_inclusive(&usage);
1445        assert_eq!(usage.input_tokens, 10);
1446        assert_eq!(usage.total_tokens, 15);
1447        assert_eq!(usage.cached_input_tokens, 5_000);
1448        assert_eq!(usage.cache_creation_input_tokens, 700);
1449    }
1450
1451    /// The whole point of the normalization: a cache hit must still trip the compaction
1452    /// threshold, since the full prompt is what gets re-sent next turn.
1453    #[test]
1454    fn compaction_threshold_sees_the_cached_prompt() {
1455        let mut window = ConversationUsageWindow::new(Some(3_000));
1456        window.record(anthropic(&anthropic_usage(52, 8, 3456, 0)));
1457        assert!(window.should_compact());
1458    }
1459
1460    /// The cache fields are `#[serde(default)]` so trajectories written before they existed
1461    /// still decode.
1462    #[test]
1463    fn usage_without_cache_fields_still_deserializes() {
1464        let usage: TokenUsage = serde_json::from_value(
1465            json!({"input_tokens": 10, "output_tokens": 2, "total_tokens": 12}),
1466        )
1467        .expect("legacy usage payload must decode");
1468        assert_eq!(usage.input_tokens, 10);
1469        assert_eq!(usage.cached_input_tokens, 0);
1470    }
1471
1472    /// Reproduce how a provider 401 actually reaches the retry layer: rig surfaces the raw
1473    /// response body as `ProviderError`, and the per-provider `completion` impls wrap it with
1474    /// `.wrap_err_with(...)`. The status only lives in the source, so the classifier must walk
1475    /// the chain rather than read `err.to_string()`.
1476    fn wrapped_provider_error(body: &str) -> eyre::Report {
1477        let inner = eyre::eyre!("ProviderError: {body}");
1478        Err::<(), _>(inner)
1479            .wrap_err("Anthropic completion failed for model 'claude'")
1480            .unwrap_err()
1481    }
1482
1483    fn gemini_completion(max_tokens: Option<u64>, additional_params: Option<Value>) -> Completion {
1484        Completion {
1485            model: "gemini-3-pro".to_string(),
1486            prompt: Message::user("hi".to_string()),
1487            preamble: None,
1488            history: Vec::new(),
1489            tools: Vec::new(),
1490            tool_choice: None,
1491            max_tokens,
1492            additional_params,
1493        }
1494    }
1495
1496    #[test]
1497    fn merge_json_is_deep_and_extra_wins() {
1498        // nested objects merge recursively; scalar conflicts resolve to `extra`.
1499        let merged = merge_json(
1500            json!({"generation_config": {"temperature": 0.2}, "a": 1}),
1501            json!({"generation_config": {"max_output_tokens": 50}, "a": 2}),
1502        );
1503        assert_eq!(
1504            merged,
1505            json!({"generation_config": {"temperature": 0.2, "max_output_tokens": 50}, "a": 2})
1506        );
1507    }
1508
1509    #[test]
1510    fn gemini_params_preserve_caller_config() {
1511        // A caller's safety settings and nested generation_config must survive the computed overlay.
1512        let params = build_gemini_additional_params(&gemini_completion(
1513            Some(50),
1514            Some(json!({
1515                "generation_config": {"temperature": 0.2},
1516                "safetySettings": [{"category": "HARM", "threshold": "NONE"}]
1517            })),
1518        ))
1519        .unwrap();
1520        assert_eq!(
1521            params,
1522            json!({
1523                "generation_config": {"temperature": 0.2, "max_output_tokens": 50},
1524                "safetySettings": [{"category": "HARM", "threshold": "NONE"}]
1525            })
1526        );
1527    }
1528
1529    #[test]
1530    fn gemini_params_none_yields_generation_config_only() {
1531        let params = build_gemini_additional_params(&gemini_completion(Some(50), None)).unwrap();
1532        assert_eq!(
1533            params,
1534            json!({"generation_config": {"max_output_tokens": 50}})
1535        );
1536    }
1537
1538    #[test]
1539    fn strips_full_think_block() {
1540        let raw = "<think>let me reason about this</think>\n\nThe bug is in foo().";
1541        assert_eq!(strip_think_blocks(raw), "The bug is in foo().");
1542    }
1543
1544    #[test]
1545    fn strips_stray_empty_think_tags() {
1546        // OpenRouter hoists MiniMax's reasoning into a separate field but leaves the tags.
1547        let raw = "<think></think>\n## Findings\n- looks fine";
1548        assert_eq!(strip_think_blocks(raw), "## Findings\n- looks fine");
1549    }
1550
1551    #[test]
1552    fn strips_unbalanced_and_multiline_think() {
1553        let raw = "intro\n<think>\nstep 1\nstep 2\n</think>verdict: ok</think>";
1554        assert_eq!(strip_think_blocks(raw), "intro\nverdict: ok");
1555    }
1556
1557    #[test]
1558    fn leaves_non_think_text_untouched() {
1559        let raw = "no reasoning tags here, just review text";
1560        assert_eq!(strip_think_blocks(raw), raw);
1561    }
1562
1563    #[test]
1564    fn strips_unterminated_think_to_eof() {
1565        // a streamed/truncated block with no closing tag must not leak its body.
1566        let raw = "answer first\n<think>reasoning that never closes\nstep 2";
1567        assert_eq!(strip_think_blocks(raw), "answer first");
1568    }
1569
1570    #[test]
1571    fn all_reasoning_collapses_to_empty() {
1572        // an all-think response (incl. the multi-block join) must be empty so the
1573        // agent loop's is_empty() nudge path fires instead of returning "\n".
1574        let joined = format!("{}\n{}", "<think>round one</think>", "<think>round two");
1575        assert_eq!(strip_think_blocks(&joined), "");
1576    }
1577
1578    #[test]
1579    fn strips_nested_think_blocks() {
1580        // a single non-greedy regex stops at the first </think> and leaks the tail; the
1581        // depth-tracking scanner must drop the whole balanced span.
1582        let raw = "<think>outer <think>inner</think> still hidden</think>answer";
1583        assert_eq!(strip_think_blocks(raw), "answer");
1584    }
1585
1586    #[test]
1587    fn strips_whitespace_padded_think_tags() {
1588        // `<think >` must be recognized as an open tag, not leaked as content.
1589        let raw = "<think >hidden</think >visible";
1590        assert_eq!(strip_think_blocks(raw), "visible");
1591    }
1592
1593    #[test]
1594    fn leaves_thinking_word_untouched() {
1595        // `<thinking>` is a different tag — the char after `think` must be ws or `>`.
1596        let raw = "see <thinking>kept</thinking> here";
1597        assert_eq!(
1598            strip_think_blocks(raw),
1599            "see <thinking>kept</thinking> here"
1600        );
1601    }
1602
1603    #[test]
1604    fn non_retryable_detects_status_in_wrapped_source() {
1605        let err = wrapped_provider_error(r#"{"statusCode": 401, "message": "Unauthorized"}"#);
1606        // `to_string()` only renders the top-level context — proves we must look deeper.
1607        assert!(!err.to_string().contains("401"));
1608        assert!(is_non_retryable_client_error(&err));
1609    }
1610
1611    #[test]
1612    fn non_retryable_false_for_server_error() {
1613        let err = wrapped_provider_error(r#"{"statusCode": 500, "message": "boom"}"#);
1614        assert!(!is_non_retryable_client_error(&err));
1615    }
1616
1617    #[test]
1618    fn rate_limit_detects_429_in_wrapped_source() {
1619        let err = wrapped_provider_error(r#"{"statusCode": 429, "message": "Too Many Requests"}"#);
1620        assert!(is_rate_limit_error(&err));
1621    }
1622
1623    #[test]
1624    fn classifiers_detect_compact_json_status() {
1625        // Compact bodies (no space after the colon) must still classify — `:401,` / `:429,` would
1626        // slip past a plain `" 401"` / `" 429"` substring check.
1627        let unauthorized = wrapped_provider_error(r#"{"statusCode":401,"message":"nope"}"#);
1628        assert!(is_non_retryable_client_error(&unauthorized));
1629        let throttled = wrapped_provider_error(r#"{"statusCode":429,"message":"slow down"}"#);
1630        assert!(is_rate_limit_error(&throttled));
1631    }
1632
1633    #[test]
1634    fn mentions_http_status_requires_standalone_number() {
1635        assert!(mentions_http_status(r#"{"code":401}"#, 401)); // bounded by punctuation, `code` key
1636        assert!(mentions_http_status("got 401 unauthorized", 401)); // reason phrase follows
1637        assert!(!mentions_http_status("request id 4017 failed", 401)); // part of a longer run
1638        assert!(!mentions_http_status("token count 1401", 401)); // trailing digits
1639    }
1640
1641    #[test]
1642    fn mentions_http_status_requires_status_context() {
1643        // A standalone status-valued number that is neither keyed nor followed by its reason phrase
1644        // is incidental, not the response status — don't misclassify the surrounding error.
1645        assert!(!mentions_http_status("max 400 tokens allowed", 400));
1646        assert!(!mentions_http_status("trace 404 emitted", 404));
1647        assert!(!mentions_http_status("req_402abc failed", 402)); // embedded in an identifier
1648        assert!(!mentions_http_status("retry after 429 seconds", 429)); // bare number, wrong meaning
1649        // Genuine status references in their usual shapings still match.
1650        assert!(mentions_http_status(
1651            r#"{"statusCode":429,"message":"slow"}"#,
1652            429
1653        ));
1654        assert!(mentions_http_status(
1655            "HttpError: Invalid status code 401",
1656            401
1657        ));
1658        assert!(mentions_http_status("429 Too Many Requests", 429)); // reason phrase
1659    }
1660
1661    #[test]
1662    fn key_must_be_a_whole_word_not_a_substring() {
1663        // `code` embedded in another word is not a status key, so these transient errors must NOT
1664        // be classified as non-retryable client errors (they should keep their retries).
1665        assert!(!mentions_http_status("decode error 404", 404)); // decode contains "code"
1666        assert!(!mentions_http_status("unicode error 400", 400)); // unicode contains "code"
1667        assert!(!mentions_http_status("encode failure 403", 403)); // encode contains "code"
1668        assert!(!mentions_http_status("error_code 402 seen", 402)); // underscore is a left edge
1669        // right boundary: `code`/`status` as a prefix of a longer word is not a key either.
1670        assert!(!mentions_http_status("codec 404 negotiation failed", 404));
1671        assert!(!mentions_http_status("statuslike 401 marker", 401));
1672        // window edge: even if the 24-byte key window cuts `unicode` right before `code`, the real
1673        // preceding char ('i') is still consulted, so it stays a non-match.
1674        assert!(!mentions_http_status("xxxxxxxxxxxxxxxxxunicode 404", 404));
1675        // `status_code` is still a real key (matched via the `status` word).
1676        assert!(mentions_http_status(r#"{"status_code": 401}"#, 401));
1677    }
1678
1679    #[test]
1680    fn classifies_provider_error_types_without_numeric_status() {
1681        // rig flattens direct Anthropic/OpenAI non-2xx to ProviderError(body) with no numeric status;
1682        // these bodies carry only string error types. Confirm the type matchers fire.
1683        let anthropic_auth = wrapped_provider_error(
1684            r#"{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}"#,
1685        );
1686        assert!(!anthropic_auth.to_string().contains("401"));
1687        assert!(is_non_retryable_client_error(&anthropic_auth));
1688        assert!(!is_rate_limit_error(&anthropic_auth));
1689
1690        let openai_key =
1691            wrapped_provider_error(r#"{"error":{"code":"invalid_api_key","message":"bad key"}}"#);
1692        assert!(is_non_retryable_client_error(&openai_key));
1693
1694        let bad_request = wrapped_provider_error(
1695            r#"{"error":{"type":"invalid_request_error","message":"prompt is too long"}}"#,
1696        );
1697        assert!(is_non_retryable_client_error(&bad_request));
1698
1699        let ctx_len = wrapped_provider_error(r#"{"error":{"code":"context_length_exceeded"}}"#);
1700        assert!(is_non_retryable_client_error(&ctx_len));
1701
1702        // Both provider shapes of a context overflow classify as such; a generic
1703        // invalid_request_error must NOT — the fewer-presets remediation would be
1704        // misdirection on a malformed-request bug.
1705        assert!(is_context_length_error(&ctx_len));
1706        assert!(is_context_length_error(&bad_request));
1707        let malformed = wrapped_provider_error(
1708            r#"{"error":{"type":"invalid_request_error","message":"tools[0] is invalid"}}"#,
1709        );
1710        assert!(!is_context_length_error(&malformed));
1711
1712        // insufficient_quota is permanent (out of credits) despite arriving as HTTP 429.
1713        let quota = wrapped_provider_error(
1714            r#"{"error":{"type":"insufficient_quota","message":"exceeded your current quota"}}"#,
1715        );
1716        assert!(is_non_retryable_client_error(&quota));
1717        assert!(!is_rate_limit_error(&quota));
1718
1719        let quota_with_429 = wrapped_provider_error(
1720            r#"{"statusCode":429,"error":{"type":"insufficient_quota","message":"Too Many Requests"}}"#,
1721        );
1722        assert!(is_non_retryable_client_error(&quota_with_429));
1723        assert!(!is_rate_limit_error(&quota_with_429));
1724        assert!(!retry_policy(&quota_with_429).retry);
1725
1726        // Transient overload/throttling types take the rate-limit policy and are not non-retryable.
1727        let overloaded =
1728            wrapped_provider_error(r#"{"type":"error","error":{"type":"overloaded_error"}}"#);
1729        assert!(is_rate_limit_error(&overloaded));
1730        assert!(!is_non_retryable_client_error(&overloaded));
1731
1732        let throttled = wrapped_provider_error(r#"{"error":{"code":"rate_limit_exceeded"}}"#);
1733        assert!(is_rate_limit_error(&throttled));
1734    }
1735
1736    #[test]
1737    fn server_error_takes_precedence_over_nested_4xx() {
1738        // a 5xx response whose body nests a 4xx (e.g. an upstream code) is a retryable server
1739        // error, not a permanent client error — so it must NOT be classified non-retryable.
1740        let err = wrapped_provider_error(r#"{"statusCode":502,"error":{"code":403}}"#);
1741        assert!(!is_non_retryable_client_error(&err));
1742        // 5xx codes without a reason phrase here (501) are still matched via the status key.
1743        let nested = wrapped_provider_error(r#"{"statusCode":501,"error":{"code":403}}"#);
1744        assert!(!is_non_retryable_client_error(&nested));
1745        // a genuine 4xx with no 5xx in the chain is still non-retryable.
1746        let pure_4xx = wrapped_provider_error(r#"{"statusCode":403,"message":"forbidden"}"#);
1747        assert!(is_non_retryable_client_error(&pure_4xx));
1748    }
1749
1750    fn tool_call_content() -> AssistantContent {
1751        use rig_core::completion::message::ToolFunction;
1752        AssistantContent::ToolCall(ToolCall::new(
1753            "call-1".to_string(),
1754            ToolFunction::new("read_file".to_string(), serde_json::json!({ "path": "x" })),
1755        ))
1756    }
1757
1758    /// Providers can pair tool calls with `stop`-like wire reasons; `tool_calls()` only
1759    /// surfaces calls under `ToolUse`, so the override losing would silently end the agent loop.
1760    #[test]
1761    fn a_structured_tool_call_overrides_any_wire_finish_reason() {
1762        let alone = OneOrMany::one(tool_call_content());
1763        let beside_text = OneOrMany::many(vec![
1764            AssistantContent::text("narration before the call"),
1765            tool_call_content(),
1766        ])
1767        .expect("two items");
1768        for choice in [alone, beside_text] {
1769            for wire in [
1770                FinishReason::Stop,
1771                FinishReason::MaxTokens,
1772                FinishReason::None,
1773                FinishReason::Other("length_capped".to_string()),
1774            ] {
1775                assert_eq!(resolve_finish_reason(&choice, wire), FinishReason::ToolUse);
1776            }
1777        }
1778    }
1779
1780    #[test]
1781    fn without_tool_calls_the_wire_finish_reason_stands() {
1782        let choice = OneOrMany::one(AssistantContent::text("done"));
1783        for wire in [
1784            FinishReason::Stop,
1785            FinishReason::MaxTokens,
1786            FinishReason::None,
1787            FinishReason::Other("content_filter".to_string()),
1788        ] {
1789            assert_eq!(resolve_finish_reason(&choice, wire.clone()), wire);
1790        }
1791    }
1792}