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::ToolCall;
6use rig_core::completion::message::ToolChoice;
7use rig_core::completion::{AssistantContent, CompletionModel, Message};
8use rig_core::providers::{anthropic, gemini, openai, openrouter};
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11use std::future::Future;
12use std::pin::Pin;
13use std::sync::Arc;
14use std::time::{Duration, SystemTime, UNIX_EPOCH};
15use tokio::sync::Semaphore;
16use tracing::warn;
17
18const MAX_COMPLETION_ATTEMPTS: usize = 4;
19const RATE_LIMIT_MAX_COMPLETION_ATTEMPTS: usize = 8;
20const BASE_BACKOFF_MS: u64 = 250;
21const MAX_BACKOFF_MS: u64 = 5_000;
22const RATE_LIMIT_BASE_BACKOFF_MS: u64 = 5_000;
23const RATE_LIMIT_MAX_BACKOFF_MS: u64 = 60_000;
24
25#[derive(Debug, Clone, Serialize, Deserialize)]
26pub struct Completion {
27    pub model: String,
28    pub prompt: Message,
29    pub preamble: Option<String>,
30    pub history: Vec<Message>,
31    pub tools: Vec<rig_core::completion::ToolDefinition>,
32    pub tool_choice: Option<ToolChoice>,
33    pub max_tokens: Option<u64>,
34    pub additional_params: Option<Value>,
35}
36
37impl Completion {
38    pub fn preamble(mut self, preamble: impl Into<String>) -> Self {
39        self.preamble = Some(preamble.into());
40        self
41    }
42
43    pub fn tools(mut self, tools: Vec<rig_core::completion::ToolDefinition>) -> Self {
44        self.tools = tools;
45        self
46    }
47
48    pub fn history(mut self, history: Vec<Message>) -> Self {
49        self.history = history;
50        self
51    }
52
53    pub fn max_tokens(mut self, max_tokens: u64) -> Self {
54        self.max_tokens = Some(max_tokens);
55        self
56    }
57
58    pub fn additional_params(mut self, additional_params: Value) -> Self {
59        self.additional_params = Some(additional_params);
60        self
61    }
62}
63
64impl From<Completion> for rig_core::completion::CompletionRequest {
65    fn from(value: Completion) -> Self {
66        let chat_history = value
67            .history
68            .into_iter()
69            .chain(std::iter::once(value.prompt))
70            .collect::<Vec<_>>();
71        rig_core::completion::CompletionRequest {
72            model: None,
73            chat_history: OneOrMany::many(chat_history)
74                .expect("completion request must include at least one message"),
75            preamble: value.preamble,
76            documents: Vec::new(),
77            tools: value.tools,
78            temperature: None,
79            max_tokens: value.max_tokens,
80            additional_params: value.additional_params,
81            output_schema: None,
82            tool_choice: value.tool_choice,
83        }
84    }
85}
86
87#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
88pub enum FinishReason {
89    None,
90    Stop,
91    MaxTokens,
92    ToolUse,
93    Other(String),
94}
95
96#[derive(Debug, Clone, Deserialize, Serialize)]
97pub struct CompletionResponse {
98    pub choice: OneOrMany<AssistantContent>,
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    pub input_tokens: u64,
107    pub output_tokens: u64,
108    pub total_tokens: u64,
109}
110
111impl TokenUsage {
112    pub fn new(input_tokens: u64, output_tokens: u64) -> Self {
113        Self {
114            input_tokens,
115            output_tokens,
116            total_tokens: input_tokens.saturating_add(output_tokens),
117        }
118    }
119}
120
121#[derive(Debug, Clone, Default)]
122pub struct ConversationUsageWindow {
123    compact_threshold: Option<u64>,
124    usage: TokenUsage,
125}
126
127impl ConversationUsageWindow {
128    pub fn new(compact_threshold: Option<u64>) -> Self {
129        Self {
130            compact_threshold,
131            usage: TokenUsage::default(),
132        }
133    }
134
135    pub fn should_compact(&self) -> bool {
136        self.compact_threshold
137            .map(|threshold| self.usage.total_tokens >= threshold)
138            .unwrap_or(false)
139    }
140
141    pub fn usage(&self) -> TokenUsage {
142        self.usage
143    }
144
145    pub fn record(&mut self, usage: TokenUsage) {
146        // input_tokens from each API response is the full context size for that call,
147        // not just the new tokens — replace rather than accumulate so should_compact()
148        // compares against the actual current context size
149        self.usage = usage;
150    }
151
152    pub fn reset(&mut self) {
153        self.usage = TokenUsage::default();
154    }
155}
156
157impl CompletionResponse {
158    pub fn message(&self) -> Message {
159        Message::Assistant {
160            id: None,
161            content: self.choice.clone(),
162        }
163    }
164
165    pub fn tool_calls(&self) -> Option<Vec<ToolCall>> {
166        if self.finish_reason != FinishReason::ToolUse {
167            return None;
168        }
169        let calls = self
170            .choice
171            .iter()
172            .filter_map(|content| match content {
173                AssistantContent::ToolCall(call) => Some(call.clone()),
174                _ => None,
175            })
176            .collect::<Vec<_>>();
177        if calls.is_empty() { None } else { Some(calls) }
178    }
179
180    pub fn text(&self) -> String {
181        // join the raw text blocks first, then strip once: a think block that spans
182        // (or a truncated one that runs to EOF) is judged against the whole text, and an
183        // all-reasoning response collapses to "" so callers' is_empty() checks fire.
184        let raw = self
185            .choice
186            .iter()
187            .filter_map(|content| match content {
188                AssistantContent::Text(text) => Some(text.text().to_string()),
189                _ => None,
190            })
191            .collect::<Vec<_>>()
192            .join("\n");
193        strip_think_blocks(&raw)
194    }
195}
196
197// some providers (notably MiniMax/GLM/DeepSeek via OpenRouter) emit chain-of-thought
198// inline as <think>...</think> in the message content rather than in a structured
199// reasoning field rig can drop. A depth-tracking scanner (not a single regex, which can't
200// match balanced nesting) keeps text only at nesting depth 0, so:
201//   - `<think...>` / `</think...>` are matched case-insensitively, tolerating padded tags
202//     like `<think >` (a regex whose open tag lacked `\s*` would leak their bodies)
203//   - nested tags can't leak: inner reasoning stays inside depth > 0
204//   - an unterminated block is dropped through end-of-text rather than leaking its body
205//   - a stray closing tag at depth 0 is dropped
206// note: this is content-wide, so a review that legitimately quotes a <think> tag in a code
207// snippet will have it stripped too — an accepted tradeoff for clean aggregation.
208fn strip_think_blocks(text: &str) -> String {
209    // match `<think` (or `</think` when `close`) + optional whitespace + `>` at the start of
210    // `s`, case-insensitively; return the matched byte length. `<thinking>` is not a tag (the
211    // char after `think` must be whitespace or `>`).
212    fn match_think_tag(s: &str, close: bool) -> Option<usize> {
213        let prefix = if close { "</think" } else { "<think" };
214        if !s.get(..prefix.len())?.eq_ignore_ascii_case(prefix) {
215            return None;
216        }
217        let after = &s[prefix.len()..];
218        let ws = after.len() - after.trim_start().len();
219        after[ws..]
220            .starts_with('>')
221            .then_some(prefix.len() + ws + 1)
222    }
223
224    let mut out = String::with_capacity(text.len());
225    let mut depth: usize = 0;
226    let mut rest = text;
227    while !rest.is_empty() {
228        if rest.starts_with('<') {
229            if let Some(len) = match_think_tag(rest, false) {
230                depth += 1;
231                rest = &rest[len..];
232                continue;
233            }
234            if let Some(len) = match_think_tag(rest, true) {
235                depth = depth.saturating_sub(1);
236                rest = &rest[len..];
237                continue;
238            }
239        }
240        let ch = rest.chars().next().expect("rest is non-empty");
241        if depth == 0 {
242            out.push(ch);
243        }
244        rest = &rest[ch.len_utf8()..];
245    }
246    out.trim().to_string()
247}
248
249pub trait LLMClient: Send + Sync {
250    fn completion(
251        &self,
252        completion: Completion,
253    ) -> impl Future<Output = Result<CompletionResponse>> + Send;
254
255    fn into_arc(self) -> Arc<dyn LLMClientDyn>
256    where
257        Self: Sized + 'static,
258    {
259        Arc::new(self)
260    }
261}
262
263pub trait LLMClientDyn: Send + Sync {
264    fn completion(
265        &self,
266        completion: Completion,
267    ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>>;
268}
269
270impl<T: LLMClient> LLMClientDyn for T {
271    fn completion(
272        &self,
273        completion: Completion,
274    ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>> {
275        Box::pin(LLMClient::completion(self, completion))
276    }
277}
278
279impl LLMClient for Box<dyn LLMClientDyn> {
280    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
281        (**self).completion(completion).await
282    }
283}
284
285pub struct RetryingLLM<C> {
286    inner: C,
287}
288
289pub trait WithRetryExt: Sized {
290    fn with_retry(self) -> RetryingLLM<Self> {
291        RetryingLLM { inner: self }
292    }
293}
294
295impl<T: LLMClient> WithRetryExt for T {}
296
297impl<C: LLMClient> LLMClient for RetryingLLM<C> {
298    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
299        let mut attempt = 0usize;
300        loop {
301            attempt += 1;
302            match self.inner.completion(completion.clone()).await {
303                Ok(response) => {
304                    if response.text().is_empty() && response.tool_calls().is_none() {
305                        if attempt >= MAX_COMPLETION_ATTEMPTS {
306                            eyre::bail!("model returned empty response after {attempt} attempts");
307                        }
308                        let backoff = jittered_backoff(attempt, BASE_BACKOFF_MS, MAX_BACKOFF_MS);
309                        warn!(
310                            model = %completion.model,
311                            attempt,
312                            max_attempts = MAX_COMPLETION_ATTEMPTS,
313                            backoff_ms = backoff.as_millis(),
314                            "retrying after empty model response"
315                        );
316                        tokio::time::sleep(backoff).await;
317                        continue;
318                    }
319                    return Ok(response);
320                }
321                Err(err) => {
322                    let policy = retry_policy(&err);
323                    if !policy.retry || attempt >= policy.max_attempts {
324                        return Err(err);
325                    }
326                    let backoff =
327                        jittered_backoff(attempt, policy.base_backoff_ms, policy.max_backoff_ms);
328                    warn!(
329                        model = %completion.model,
330                        attempt,
331                        max_attempts = policy.max_attempts,
332                        backoff_ms = backoff.as_millis(),
333                        error = %err,
334                        "retrying model completion after error"
335                    );
336                    tokio::time::sleep(backoff).await;
337                }
338            }
339        }
340    }
341}
342
343/// randomly alternates between models within a single agentic loop — see https://xbow.com/blog/alloy-agents
344///
345/// inner clients must already be wrapped with retry (e.g. via `.with_retry()`); AlloyClient does not add retry itself
346pub struct AlloyClient {
347    slots: Vec<(Arc<dyn LLMClientDyn>, String)>,
348}
349
350impl AlloyClient {
351    pub fn new(slots: Vec<(Arc<dyn LLMClientDyn>, String)>) -> Result<Self> {
352        if slots.is_empty() {
353            eyre::bail!("AlloyClient requires at least one slot");
354        }
355        Ok(Self { slots })
356    }
357
358    fn pick_idx(&self) -> usize {
359        use rand::RngExt;
360        rand::rng().random_range(0..self.slots.len())
361    }
362}
363
364impl LLMClientDyn for AlloyClient {
365    fn completion(
366        &self,
367        mut completion: Completion,
368    ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>> {
369        let (client, model) = &self.slots[self.pick_idx()];
370        completion.model = model.clone();
371        let client = Arc::clone(client);
372        let model = model.clone();
373        Box::pin(async move {
374            let mut response = client.completion(completion).await?;
375            response.selected_model = Some(model);
376            Ok(response)
377        })
378    }
379}
380
381/// Run a single completion under a concurrency permit. The permit is held only for the duration of
382/// this one call and released immediately after — never across a subagent spawn — so callers may
383/// block on acquire without risking deadlock. This is the single chokepoint that bounds account-wide
384/// in-flight LLM calls; route every concurrent completion (agent turns, compaction) through it.
385pub async fn throttled_completion(
386    semaphore: &Semaphore,
387    client: &Arc<dyn LLMClientDyn>,
388    completion: Completion,
389) -> Result<CompletionResponse> {
390    let _permit = semaphore.acquire().await.expect("llm semaphore closed");
391    client.completion(completion).await
392}
393
394struct RetryPolicy {
395    retry: bool,
396    max_attempts: usize,
397    base_backoff_ms: u64,
398    max_backoff_ms: u64,
399}
400
401fn retry_policy(err: &eyre::Report) -> RetryPolicy {
402    if is_rate_limit_error(err) {
403        return RetryPolicy {
404            retry: true,
405            max_attempts: RATE_LIMIT_MAX_COMPLETION_ATTEMPTS,
406            base_backoff_ms: RATE_LIMIT_BASE_BACKOFF_MS,
407            max_backoff_ms: RATE_LIMIT_MAX_BACKOFF_MS,
408        };
409    }
410
411    if is_non_retryable_client_error(err) {
412        return RetryPolicy {
413            retry: false,
414            max_attempts: 0,
415            base_backoff_ms: 0,
416            max_backoff_ms: 0,
417        };
418    }
419
420    RetryPolicy {
421        retry: true,
422        max_attempts: MAX_COMPLETION_ATTEMPTS,
423        base_backoff_ms: BASE_BACKOFF_MS,
424        max_backoff_ms: MAX_BACKOFF_MS,
425    }
426}
427
428/// HTTP status codes the retry/refresh classifiers key on, paired with their canonical reason
429/// phrase. The phrase lets us recognize the plain-text `"<code> <reason>"` status-line form
430/// (`401 Unauthorized`, `429 Too Many Requests`) that carries no JSON status key.
431const STATUS_REASONS: &[(u16, &str)] = &[
432    (400, "bad request"),
433    (401, "unauthorized"),
434    (402, "payment required"),
435    (403, "forbidden"),
436    (404, "not found"),
437    (429, "too many requests"),
438    (500, "internal server error"),
439    (502, "bad gateway"),
440    (503, "service unavailable"),
441    (504, "gateway timeout"),
442];
443
444/// How far back (in bytes) to scan for a status key before a candidate number. Comfortably covers
445/// `"statusCode": ` even with extra spacing, while staying local enough that an unrelated
446/// `code`/`status` field elsewhere in the body doesn't bleed in.
447const STATUS_KEY_WINDOW: usize = 24;
448
449/// True if `status` (an HTTP status code) appears in `msg` as a genuine status reference: a
450/// standalone number (not part of a longer digit run) that is *also* in an HTTP-status context —
451/// either immediately followed by its canonical reason phrase (`401 Unauthorized`) or preceded
452/// within [`STATUS_KEY_WINDOW`] by a `status`/`code` key (covering `"statusCode": 401`, `:401`,
453/// `Invalid status code 401`, ...). The context requirement keeps incidental standalone numbers in
454/// a raw provider body — `400 tokens`, `trace 404`, `req_402abc` — from being misread as the
455/// response status. Provider errors surface the status only inside the raw body, whose punctuation
456/// varies (spaced `"statusCode": 401` vs compact `"statusCode":401`), so we can't rely on fixed
457/// delimiters; the trade-off is that a status carrying neither a nearby key nor a reason phrase is
458/// not recognized (rare in practice, and recoverable — at worst a retried/failed request).
459pub(crate) fn mentions_http_status(msg: &str, status: u16) -> bool {
460    let lower = msg.to_ascii_lowercase();
461    let needle = status.to_string();
462    let reason = STATUS_REASONS
463        .iter()
464        .find(|(code, _)| *code == status)
465        .map(|(_, phrase)| *phrase);
466    let bytes = lower.as_bytes();
467    let mut from = 0;
468    while let Some(rel) = lower[from..].find(&needle) {
469        let start = from + rel;
470        let end = start + needle.len();
471        let prev_digit = start > 0 && bytes[start - 1].is_ascii_digit();
472        let next_digit = end < bytes.len() && bytes[end].is_ascii_digit();
473        if !prev_digit && !next_digit && status_in_context(&lower, start, end, reason) {
474            return true;
475        }
476        from = start + 1;
477    }
478    false
479}
480
481/// Whether the standalone number at `start..end` in `lower` (already lowercased) sits in an
482/// HTTP-status context: followed by its reason phrase, or preceded within [`STATUS_KEY_WINDOW`] by a
483/// `status`/`code` key. `start`/`end` are byte offsets on char boundaries (the needle is ASCII); the
484/// preceding-window start is floored to a boundary so a multibyte char in the body can't panic the
485/// slice.
486fn status_in_context(lower: &str, start: usize, end: usize, reason: Option<&str>) -> bool {
487    if let Some(reason) = reason {
488        if lower[end..].trim_start().starts_with(reason) {
489            return true;
490        }
491    }
492    let mut window_start = start.saturating_sub(STATUS_KEY_WINDOW);
493    while !lower.is_char_boundary(window_start) {
494        window_start += 1;
495    }
496    // `statuscode` is the lowercased compact `statusCode` (no separator), where neither `status`
497    // nor `code` is a whole word on its own, so it needs its own key.
498    key_word_present(lower, window_start, start, "status")
499        || key_word_present(lower, window_start, start, "code")
500        || key_word_present(lower, window_start, start, "statuscode")
501}
502
503/// Whether `key` appears as a whole word within `lower[lo..hi]`. The left edge must be the string
504/// start or a non-`[a-z0-9_]` byte; the right edge must be the string end or a non-`[a-z0-9]` byte
505/// (`_` is allowed on the right so `status_code` still matches via the `status` key, while
506/// `decode`/`encode`/`unicode`/`error_code`/`codec`/`statuslike` do NOT count as keys). Boundary
507/// checks read `lower`'s absolute bytes, so a word split by the `[lo..hi]` window edge is judged
508/// against its real neighbours. `key` is ASCII; `lo`/`hi` are on char boundaries.
509fn key_word_present(lower: &str, lo: usize, hi: usize, key: &str) -> bool {
510    let bytes = lower.as_bytes();
511    let region = &lower[lo..hi];
512    let mut from = 0;
513    while let Some(rel) = region[from..].find(key) {
514        let abs = lo + from + rel;
515        let left_ok = abs == 0 || {
516            let b = bytes[abs - 1];
517            !b.is_ascii_alphanumeric() && b != b'_'
518        };
519        let after = abs + key.len();
520        let right_ok = after >= bytes.len() || !bytes[after].is_ascii_alphanumeric();
521        if left_ok && right_ok {
522            return true;
523        }
524        from += rel + 1;
525    }
526    false
527}
528
529/// Permanent error *types* that direct Anthropic/OpenAI bodies carry instead of a numeric status.
530/// rig flattens a non-2xx response to `ProviderError(<raw body>)` with the HTTP status dropped, so
531/// for those providers the numeric-status matchers never fire — these strings are the only signal.
532/// `insufficient_quota` (out of credits) is permanent despite arriving as HTTP 429: retrying never
533/// helps. Auth/permission `403`-class types are deliberately included here, *not* in the rate-limit
534/// set. All lowercase; matched as substrings on the lowercased chain.
535const NON_RETRYABLE_ERROR_TYPES: &[&str] = &[
536    "authentication_error",
537    "invalid_api_key",
538    "permission_error",
539    "permission_denied",
540    "invalid_request_error",
541    "not_found_error",
542    "context_length_exceeded",
543    "insufficient_quota",
544];
545
546/// Transient error *types* (overload / throttling) that warrant the rate-limit backoff policy.
547const RATE_LIMIT_ERROR_TYPES: &[&str] = &[
548    "rate_limit_error",
549    "rate_limit_exceeded",
550    "overloaded_error",
551];
552
553/// Error types that often arrive with HTTP 429 but are not transient throttles.
554const PERMANENT_QUOTA_ERROR_TYPES: &[&str] = &["insufficient_quota"];
555
556fn is_non_retryable_client_error(err: &eyre::Report) -> bool {
557    // Walk the whole chain: provider clients map non-2xx to a `ProviderError` carrying the raw
558    // response body, then `.wrap_err_with(...)` adds a top-level context. `err.to_string()` renders
559    // only that context, so the status code would be invisible; `{err:#}` joins the full chain.
560    let msg = format!("{err:#}");
561    // a 5xx response takes precedence: even when a 4xx is nested in the body (e.g. an upstream
562    // `"code": 403` inside a 502 envelope), the response itself is a retryable server error, so we
563    // must not classify it as a permanent client error. Cover the full registered 5xx range; the
564    // JSON `status`/`code`-key form is matched even for codes without a reason phrase here.
565    if [500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511]
566        .iter()
567        .any(|&status| mentions_http_status(&msg, status))
568    {
569        return false;
570    }
571    if [400, 401, 402, 403, 404]
572        .iter()
573        .any(|&status| mentions_http_status(&msg, status))
574    {
575        return true;
576    }
577    let lower = msg.to_ascii_lowercase();
578    NON_RETRYABLE_ERROR_TYPES.iter().any(|t| lower.contains(t))
579}
580
581fn is_rate_limit_error(err: &eyre::Report) -> bool {
582    // Same reasoning as `is_non_retryable_client_error`: walk the full chain so a 429 carried in a
583    // wrapped `ProviderError` body still maps to the rate-limit backoff policy. Permanent quota
584    // types are excluded first because retrying them only burns the full rate-limit retry budget.
585    let msg = format!("{err:#}").to_ascii_lowercase();
586    if PERMANENT_QUOTA_ERROR_TYPES.iter().any(|t| msg.contains(t)) {
587        return false;
588    }
589    mentions_http_status(&msg, 429)
590        || msg.contains("rate limit")
591        || msg.contains("too many requests")
592        || msg.contains("tokens per minute")
593        || msg.contains("requests per minute")
594        || RATE_LIMIT_ERROR_TYPES.iter().any(|t| msg.contains(t))
595}
596
597fn jittered_backoff(attempt: usize, base_backoff_ms: u64, max_backoff_ms: u64) -> Duration {
598    let exp = 2u64.saturating_pow((attempt - 1) as u32);
599    let base = (base_backoff_ms * exp).min(max_backoff_ms);
600    let jitter = jitter_factor();
601    let jittered = (base as f64 * jitter).round() as u64;
602    Duration::from_millis(jittered.max(1))
603}
604
605fn jitter_factor() -> f64 {
606    let nanos = SystemTime::now()
607        .duration_since(UNIX_EPOCH)
608        .map(|d| d.subsec_nanos())
609        .unwrap_or(0);
610    let scaled = (nanos % 1000) as f64 / 1000.0;
611    0.5 + scaled
612}
613
614#[derive(Debug, Deserialize)]
615struct OpenRouterErrorEnvelope {
616    error: OpenRouterErrorBody,
617}
618
619#[derive(Debug, Deserialize)]
620struct OpenRouterErrorBody {
621    message: String,
622    code: Option<u16>,
623}
624
625fn normalize_openrouter_completion_error(err: &CompletionError) -> eyre::Report {
626    match err {
627        CompletionError::ResponseError(msg) => normalize_openrouter_response_error(msg),
628        CompletionError::ProviderError(msg) => eyre::eyre!("ProviderError: {msg}"),
629        _ => eyre::eyre!("{err}"),
630    }
631}
632
633fn normalize_openrouter_response_error(msg: &str) -> eyre::Report {
634    if msg.contains("no message or tool call") || msg.contains("no choices") {
635        return eyre::eyre!("empty response from model (no message or tool call)");
636    }
637
638    if let Some(err) = parse_openrouter_error_envelope(msg) {
639        return match err.code {
640            Some(code) => eyre::eyre!(
641                "HttpError: Invalid status code {code} OpenRouter provider error: {}",
642                err.message
643            ),
644            None => eyre::eyre!("ProviderError: {}", err.message),
645        };
646    }
647
648    eyre::eyre!("ResponseError: {msg}")
649}
650
651fn parse_openrouter_error_envelope(msg: &str) -> Option<OpenRouterErrorBody> {
652    let body = msg.split_once("response body:")?.1.trim();
653    serde_json::from_str::<OpenRouterErrorEnvelope>(body)
654        .ok()
655        .map(|envelope| envelope.error)
656}
657
658fn is_local_base_url(base_url: Option<&str>) -> bool {
659    base_url
660        .map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
661        .unwrap_or(false)
662}
663
664/// Resolve the API key when its env var is unset: a local base_url needs no real key, otherwise it
665/// is a hard error naming the missing var.
666fn missing_or_local(key_env: &str, base_url: Option<&str>) -> Result<String> {
667    if is_local_base_url(base_url) {
668        Ok("local".to_string())
669    } else {
670        Err(eyre::eyre!("missing env var {key_env}"))
671    }
672}
673
674pub enum LLMProvider {
675    Anthropic {
676        base_url: Option<String>,
677        api_key_env: Option<String>,
678    },
679    Gemini {
680        base_url: Option<String>,
681        api_key_env: Option<String>,
682    },
683    OpenAi {
684        base_url: Option<String>,
685        api_key_env: Option<String>,
686    },
687    OpenRouter {
688        api_key_env: String,
689    },
690}
691
692impl LLMProvider {
693    pub fn client_from_env(&self) -> Result<Box<dyn LLMClientDyn>> {
694        match self {
695            LLMProvider::Anthropic {
696                base_url,
697                api_key_env,
698            } => {
699                let key_env = api_key_env.as_deref().unwrap_or("ANTHROPIC_API_KEY");
700                let api_key = std::env::var(key_env)
701                    .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
702                let mut builder = anthropic::Client::builder().api_key(api_key);
703                if let Some(url) = base_url {
704                    builder = builder.base_url(url);
705                }
706                Ok(Box::new(builder.build()?))
707            }
708            LLMProvider::Gemini {
709                base_url,
710                api_key_env,
711            } => {
712                // An explicit api_key_env overrides the GEMINI_API_KEY → GOOGLE_AI_API_KEY default
713                // chain; a local base_url needs no key (mirrors the Anthropic/OpenAi arms).
714                let api_key = match api_key_env {
715                    Some(key_env) => std::env::var(key_env)
716                        .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?,
717                    None => std::env::var("GEMINI_API_KEY")
718                        .or_else(|_| std::env::var("GOOGLE_AI_API_KEY"))
719                        .or_else(|_| {
720                            missing_or_local(
721                                "GEMINI_API_KEY (or GOOGLE_AI_API_KEY)",
722                                base_url.as_deref(),
723                            )
724                        })?,
725                };
726                let mut builder = gemini::Client::builder().api_key(api_key);
727                if let Some(url) = base_url {
728                    builder = builder.base_url(url);
729                }
730                let client = builder
731                    .build()
732                    .map_err(|e| eyre::eyre!("failed to create Gemini client: {e}"))?;
733                Ok(Box::new(client))
734            }
735            LLMProvider::OpenAi {
736                base_url,
737                api_key_env,
738            } => {
739                let key_env = api_key_env.as_deref().unwrap_or("OPENAI_API_KEY");
740                let api_key = std::env::var(key_env)
741                    .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
742                let mut builder = openai::CompletionsClient::builder().api_key(&api_key);
743                if let Some(url) = base_url {
744                    builder = builder.base_url(url);
745                }
746                Ok(Box::new(builder.build()?))
747            }
748            LLMProvider::OpenRouter { api_key_env } => {
749                let api_key = std::env::var(api_key_env)
750                    .map_err(|_| eyre::eyre!("missing env var {api_key_env}"))?;
751                let client = openrouter::Client::builder()
752                    .api_key(&api_key)
753                    .http_headers(openrouter_headers()?)
754                    .build()?;
755                Ok(Box::new(client))
756            }
757        }
758    }
759}
760
761pub fn openrouter_headers() -> Result<reqwest::header::HeaderMap> {
762    let mut headers = reqwest::header::HeaderMap::new();
763    headers.insert(
764        "HTTP-Referer",
765        "https://github.com/arsenyinfo/nitpicker".parse()?,
766    );
767    headers.insert("X-OpenRouter-Title", "nitpicker".parse()?);
768    headers.insert(
769        "X-OpenRouter-Categories",
770        "cli-agent,programming-app".parse()?,
771    );
772    Ok(headers)
773}
774
775impl LLMClient for openrouter::Client {
776    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
777        let model_name = completion.model.clone();
778        let mut request: rig_core::completion::CompletionRequest = completion.into();
779        request.model = Some(model_name.clone());
780        let model = self.completion_model(&model_name);
781        let response = model
782            .completion(request)
783            .await
784            .map_err(|e| normalize_openrouter_completion_error(&e))?;
785        let mut finish_reason = response
786            .raw_response
787            .choices
788            .first()
789            .and_then(|c| c.finish_reason.as_deref())
790            .map(|reason| match reason {
791                "stop" => FinishReason::Stop,
792                "length" => FinishReason::MaxTokens,
793                "tool_calls" => FinishReason::ToolUse,
794                other => FinishReason::Other(other.to_string()),
795            })
796            .unwrap_or(FinishReason::None);
797        if response
798            .choice
799            .iter()
800            .any(|content| matches!(content, AssistantContent::ToolCall(_)))
801        {
802            finish_reason = FinishReason::ToolUse;
803        }
804        let usage = response
805            .raw_response
806            .usage
807            .map(|u| TokenUsage::new(u.prompt_tokens as u64, u.completion_tokens as u64))
808            .unwrap_or_default();
809        Ok(CompletionResponse {
810            choice: response.choice,
811            finish_reason,
812            usage,
813            selected_model: Some(model_name),
814        })
815    }
816}
817
818/// Create a Gemini client that routes through the local OAuth proxy
819#[cfg(feature = "antigravity")]
820pub fn create_gemini_client_with_proxy(
821    proxy_url: &str,
822) -> Result<std::sync::Arc<dyn LLMClientDyn>> {
823    // Build a Gemini client with the proxy URL as the base URL
824    // The API key doesn't matter for OAuth proxy, but is required by the builder
825    let api_key = std::env::var("GEMINI_API_KEY").unwrap_or_else(|_| "oauth-proxy".to_string());
826    let client = gemini::Client::builder()
827        .api_key(api_key)
828        .base_url(proxy_url)
829        .build()?;
830    Ok(client.with_retry().into_arc())
831}
832
833impl LLMClient for anthropic::Client {
834    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
835        let model_name = completion.model.clone();
836        let mut request: rig_core::completion::CompletionRequest = completion.into();
837        request.model = Some(model_name.clone());
838        let model = self.completion_model(model_name.clone());
839        let response = model
840            .completion(request)
841            .await
842            .wrap_err_with(|| format!("Anthropic completion failed for model '{model_name}'"))?;
843        let mut finish_reason = response
844            .raw_response
845            .stop_reason
846            .clone()
847            .map(|reason| match reason.as_str() {
848                "end_turn" => FinishReason::Stop,
849                "max_tokens" => FinishReason::MaxTokens,
850                "tool_use" => FinishReason::ToolUse,
851                other => FinishReason::Other(other.to_string()),
852            })
853            .unwrap_or(FinishReason::None);
854        if response
855            .choice
856            .iter()
857            .any(|content| matches!(content, AssistantContent::ToolCall(_)))
858        {
859            finish_reason = FinishReason::ToolUse;
860        }
861        Ok(CompletionResponse {
862            choice: response.choice,
863            finish_reason,
864            usage: TokenUsage::new(response.usage.input_tokens, response.usage.output_tokens),
865            selected_model: Some(model_name),
866        })
867    }
868}
869
870impl LLMClient for gemini::Client {
871    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
872        let model_name = completion.model.clone();
873        let params = GeminiAdditionalParams::from_completion(&completion);
874        let mut request: rig_core::completion::CompletionRequest = completion.into();
875        request.model = Some(model_name.clone());
876        request.additional_params = Some(serde_json::to_value(params)?);
877        let model = self.completion_model(model_name.clone());
878        let response = model
879            .completion(request)
880            .await
881            .wrap_err_with(|| format!("Gemini completion failed for model '{model_name}'"))?;
882        let mut finish_reason = response
883            .raw_response
884            .candidates
885            .first()
886            .and_then(|candidate| candidate.finish_reason.clone())
887            .map(map_gemini_finish_reason)
888            .unwrap_or(FinishReason::None);
889        if response
890            .choice
891            .iter()
892            .any(|content| matches!(content, AssistantContent::ToolCall(_)))
893        {
894            finish_reason = FinishReason::ToolUse;
895        }
896        Ok(CompletionResponse {
897            choice: response.choice,
898            finish_reason,
899            usage: TokenUsage::new(response.usage.input_tokens, response.usage.output_tokens),
900            selected_model: Some(model_name),
901        })
902    }
903}
904
905fn model_needs_max_completion_tokens(model: &str) -> bool {
906    model.starts_with("o1")
907        || model.starts_with("o3")
908        || model.starts_with("o4")
909        || model.starts_with("gpt-4o")
910        || model.starts_with("gpt-4.1")
911        || model.starts_with("gpt-4.5")
912        || model.starts_with("gpt-5")
913}
914
915pub(crate) fn merge_json(mut base: Value, extra: Value) -> Value {
916    if let (Some(base_obj), Some(extra_obj)) = (base.as_object_mut(), extra.as_object()) {
917        for (k, v) in extra_obj {
918            base_obj.insert(k.clone(), v.clone());
919        }
920        base
921    } else {
922        extra
923    }
924}
925
926impl LLMClient for openai::CompletionsClient {
927    async fn completion(&self, mut completion: Completion) -> Result<CompletionResponse> {
928        // Newer OpenAI models (o1, o3, o4-mini, gpt-4o, gpt-5, etc.) reject the legacy
929        // `max_tokens` param and require `max_completion_tokens` instead. Since rig always
930        // serializes `max_tokens`, we move the value into `additional_params` and clear it.
931        if let Some(max) = completion.max_tokens {
932            if model_needs_max_completion_tokens(&completion.model) {
933                let extra = serde_json::json!({ "max_completion_tokens": max });
934                completion.additional_params = Some(match completion.additional_params.take() {
935                    Some(existing) => merge_json(existing, extra),
936                    None => extra,
937                });
938                completion.max_tokens = None;
939            }
940        }
941        let model_name = completion.model.clone();
942        let mut request: rig_core::completion::CompletionRequest = completion.into();
943        request.model = Some(model_name.clone());
944        let model = self.completion_model(model_name.clone());
945        let response = model
946            .completion(request)
947            .await
948            .wrap_err_with(|| format!("OpenAI completion failed for model '{model_name}'"))?;
949        let mut finish_reason = response
950            .raw_response
951            .choices
952            .first()
953            .map(|choice| match choice.finish_reason.as_str() {
954                "stop" => FinishReason::Stop,
955                "length" => FinishReason::MaxTokens,
956                "tool_calls" => FinishReason::ToolUse,
957                other => FinishReason::Other(other.to_string()),
958            })
959            .unwrap_or(FinishReason::None);
960        if response
961            .choice
962            .iter()
963            .any(|content| matches!(content, AssistantContent::ToolCall(_)))
964        {
965            finish_reason = FinishReason::ToolUse;
966        }
967        Ok(CompletionResponse {
968            choice: response.choice,
969            finish_reason,
970            usage: TokenUsage::new(response.usage.input_tokens, response.usage.output_tokens),
971            selected_model: Some(model_name),
972        })
973    }
974}
975
976#[derive(Debug, Serialize)]
977struct GeminiAdditionalParams {
978    generation_config: Option<GenerationConfig>,
979}
980
981impl GeminiAdditionalParams {
982    fn from_completion(completion: &Completion) -> Self {
983        let config = GenerationConfig {
984            max_output_tokens: completion.max_tokens.map(|value| value as i32),
985        };
986        Self {
987            generation_config: Some(config),
988        }
989    }
990}
991
992#[derive(Debug, Serialize, Default)]
993struct GenerationConfig {
994    #[serde(skip_serializing_if = "Option::is_none")]
995    max_output_tokens: Option<i32>,
996}
997
998fn map_gemini_finish_reason(
999    reason: gemini::completion::gemini_api_types::FinishReason,
1000) -> FinishReason {
1001    use gemini::completion::gemini_api_types::FinishReason as GeminiFinishReason;
1002    match reason {
1003        GeminiFinishReason::Stop => FinishReason::Stop,
1004        GeminiFinishReason::MaxTokens => FinishReason::MaxTokens,
1005        GeminiFinishReason::FinishReasonUnspecified => FinishReason::None,
1006        other => FinishReason::Other(format!("{other:?}")),
1007    }
1008}
1009
1010#[cfg(test)]
1011mod tests {
1012    use super::*;
1013
1014    /// Reproduce how a provider 401 actually reaches the retry layer: rig surfaces the raw
1015    /// response body as `ProviderError`, and the per-provider `completion` impls wrap it with
1016    /// `.wrap_err_with(...)`. The status only lives in the source, so the classifier must walk
1017    /// the chain rather than read `err.to_string()`.
1018    fn wrapped_provider_error(body: &str) -> eyre::Report {
1019        let inner = eyre::eyre!("ProviderError: {body}");
1020        Err::<(), _>(inner)
1021            .wrap_err("Anthropic completion failed for model 'claude'")
1022            .unwrap_err()
1023    }
1024
1025    #[test]
1026    fn strips_full_think_block() {
1027        let raw = "<think>let me reason about this</think>\n\nThe bug is in foo().";
1028        assert_eq!(strip_think_blocks(raw), "The bug is in foo().");
1029    }
1030
1031    #[test]
1032    fn strips_stray_empty_think_tags() {
1033        // OpenRouter hoists MiniMax's reasoning into a separate field but leaves the tags.
1034        let raw = "<think></think>\n## Findings\n- looks fine";
1035        assert_eq!(strip_think_blocks(raw), "## Findings\n- looks fine");
1036    }
1037
1038    #[test]
1039    fn strips_unbalanced_and_multiline_think() {
1040        let raw = "intro\n<think>\nstep 1\nstep 2\n</think>verdict: ok</think>";
1041        assert_eq!(strip_think_blocks(raw), "intro\nverdict: ok");
1042    }
1043
1044    #[test]
1045    fn leaves_non_think_text_untouched() {
1046        let raw = "no reasoning tags here, just review text";
1047        assert_eq!(strip_think_blocks(raw), raw);
1048    }
1049
1050    #[test]
1051    fn strips_unterminated_think_to_eof() {
1052        // a streamed/truncated block with no closing tag must not leak its body.
1053        let raw = "answer first\n<think>reasoning that never closes\nstep 2";
1054        assert_eq!(strip_think_blocks(raw), "answer first");
1055    }
1056
1057    #[test]
1058    fn all_reasoning_collapses_to_empty() {
1059        // an all-think response (incl. the multi-block join) must be empty so the
1060        // agent loop's is_empty() nudge path fires instead of returning "\n".
1061        let joined = format!("{}\n{}", "<think>round one</think>", "<think>round two");
1062        assert_eq!(strip_think_blocks(&joined), "");
1063    }
1064
1065    #[test]
1066    fn strips_nested_think_blocks() {
1067        // a single non-greedy regex stops at the first </think> and leaks the tail; the
1068        // depth-tracking scanner must drop the whole balanced span.
1069        let raw = "<think>outer <think>inner</think> still hidden</think>answer";
1070        assert_eq!(strip_think_blocks(raw), "answer");
1071    }
1072
1073    #[test]
1074    fn strips_whitespace_padded_think_tags() {
1075        // `<think >` must be recognized as an open tag, not leaked as content.
1076        let raw = "<think >hidden</think >visible";
1077        assert_eq!(strip_think_blocks(raw), "visible");
1078    }
1079
1080    #[test]
1081    fn leaves_thinking_word_untouched() {
1082        // `<thinking>` is a different tag — the char after `think` must be ws or `>`.
1083        let raw = "see <thinking>kept</thinking> here";
1084        assert_eq!(
1085            strip_think_blocks(raw),
1086            "see <thinking>kept</thinking> here"
1087        );
1088    }
1089
1090    #[test]
1091    fn non_retryable_detects_status_in_wrapped_source() {
1092        let err = wrapped_provider_error(r#"{"statusCode": 401, "message": "Unauthorized"}"#);
1093        // `to_string()` only renders the top-level context — proves we must look deeper.
1094        assert!(!err.to_string().contains("401"));
1095        assert!(is_non_retryable_client_error(&err));
1096    }
1097
1098    #[test]
1099    fn non_retryable_false_for_server_error() {
1100        let err = wrapped_provider_error(r#"{"statusCode": 500, "message": "boom"}"#);
1101        assert!(!is_non_retryable_client_error(&err));
1102    }
1103
1104    #[test]
1105    fn rate_limit_detects_429_in_wrapped_source() {
1106        let err = wrapped_provider_error(r#"{"statusCode": 429, "message": "Too Many Requests"}"#);
1107        assert!(is_rate_limit_error(&err));
1108    }
1109
1110    #[test]
1111    fn classifiers_detect_compact_json_status() {
1112        // Compact bodies (no space after the colon) must still classify — `:401,` / `:429,` would
1113        // slip past a plain `" 401"` / `" 429"` substring check.
1114        let unauthorized = wrapped_provider_error(r#"{"statusCode":401,"message":"nope"}"#);
1115        assert!(is_non_retryable_client_error(&unauthorized));
1116        let throttled = wrapped_provider_error(r#"{"statusCode":429,"message":"slow down"}"#);
1117        assert!(is_rate_limit_error(&throttled));
1118    }
1119
1120    #[test]
1121    fn mentions_http_status_requires_standalone_number() {
1122        assert!(mentions_http_status(r#"{"code":401}"#, 401)); // bounded by punctuation, `code` key
1123        assert!(mentions_http_status("got 401 unauthorized", 401)); // reason phrase follows
1124        assert!(!mentions_http_status("request id 4017 failed", 401)); // part of a longer run
1125        assert!(!mentions_http_status("token count 1401", 401)); // trailing digits
1126    }
1127
1128    #[test]
1129    fn mentions_http_status_requires_status_context() {
1130        // A standalone status-valued number that is neither keyed nor followed by its reason phrase
1131        // is incidental, not the response status — don't misclassify the surrounding error.
1132        assert!(!mentions_http_status("max 400 tokens allowed", 400));
1133        assert!(!mentions_http_status("trace 404 emitted", 404));
1134        assert!(!mentions_http_status("req_402abc failed", 402)); // embedded in an identifier
1135        assert!(!mentions_http_status("retry after 429 seconds", 429)); // bare number, wrong meaning
1136        // Genuine status references in their usual shapings still match.
1137        assert!(mentions_http_status(
1138            r#"{"statusCode":429,"message":"slow"}"#,
1139            429
1140        ));
1141        assert!(mentions_http_status(
1142            "HttpError: Invalid status code 401",
1143            401
1144        ));
1145        assert!(mentions_http_status("429 Too Many Requests", 429)); // reason phrase
1146    }
1147
1148    #[test]
1149    fn key_must_be_a_whole_word_not_a_substring() {
1150        // `code` embedded in another word is not a status key, so these transient errors must NOT
1151        // be classified as non-retryable client errors (they should keep their retries).
1152        assert!(!mentions_http_status("decode error 404", 404)); // decode contains "code"
1153        assert!(!mentions_http_status("unicode error 400", 400)); // unicode contains "code"
1154        assert!(!mentions_http_status("encode failure 403", 403)); // encode contains "code"
1155        assert!(!mentions_http_status("error_code 402 seen", 402)); // underscore is a left edge
1156        // right boundary: `code`/`status` as a prefix of a longer word is not a key either.
1157        assert!(!mentions_http_status("codec 404 negotiation failed", 404));
1158        assert!(!mentions_http_status("statuslike 401 marker", 401));
1159        // window edge: even if the 24-byte key window cuts `unicode` right before `code`, the real
1160        // preceding char ('i') is still consulted, so it stays a non-match.
1161        assert!(!mentions_http_status("xxxxxxxxxxxxxxxxxunicode 404", 404));
1162        // `status_code` is still a real key (matched via the `status` word).
1163        assert!(mentions_http_status(r#"{"status_code": 401}"#, 401));
1164    }
1165
1166    #[test]
1167    fn classifies_provider_error_types_without_numeric_status() {
1168        // rig flattens direct Anthropic/OpenAI non-2xx to ProviderError(body) with no numeric status;
1169        // these bodies carry only string error types. Confirm the type matchers fire.
1170        let anthropic_auth = wrapped_provider_error(
1171            r#"{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}"#,
1172        );
1173        assert!(!anthropic_auth.to_string().contains("401"));
1174        assert!(is_non_retryable_client_error(&anthropic_auth));
1175        assert!(!is_rate_limit_error(&anthropic_auth));
1176
1177        let openai_key =
1178            wrapped_provider_error(r#"{"error":{"code":"invalid_api_key","message":"bad key"}}"#);
1179        assert!(is_non_retryable_client_error(&openai_key));
1180
1181        let bad_request = wrapped_provider_error(
1182            r#"{"error":{"type":"invalid_request_error","message":"prompt is too long"}}"#,
1183        );
1184        assert!(is_non_retryable_client_error(&bad_request));
1185
1186        let ctx_len = wrapped_provider_error(r#"{"error":{"code":"context_length_exceeded"}}"#);
1187        assert!(is_non_retryable_client_error(&ctx_len));
1188
1189        // insufficient_quota is permanent (out of credits) despite arriving as HTTP 429.
1190        let quota = wrapped_provider_error(
1191            r#"{"error":{"type":"insufficient_quota","message":"exceeded your current quota"}}"#,
1192        );
1193        assert!(is_non_retryable_client_error(&quota));
1194        assert!(!is_rate_limit_error(&quota));
1195
1196        let quota_with_429 = wrapped_provider_error(
1197            r#"{"statusCode":429,"error":{"type":"insufficient_quota","message":"Too Many Requests"}}"#,
1198        );
1199        assert!(is_non_retryable_client_error(&quota_with_429));
1200        assert!(!is_rate_limit_error(&quota_with_429));
1201        assert!(!retry_policy(&quota_with_429).retry);
1202
1203        // Transient overload/throttling types take the rate-limit policy and are not non-retryable.
1204        let overloaded =
1205            wrapped_provider_error(r#"{"type":"error","error":{"type":"overloaded_error"}}"#);
1206        assert!(is_rate_limit_error(&overloaded));
1207        assert!(!is_non_retryable_client_error(&overloaded));
1208
1209        let throttled = wrapped_provider_error(r#"{"error":{"code":"rate_limit_exceeded"}}"#);
1210        assert!(is_rate_limit_error(&throttled));
1211    }
1212
1213    #[test]
1214    fn server_error_takes_precedence_over_nested_4xx() {
1215        // a 5xx response whose body nests a 4xx (e.g. an upstream code) is a retryable server
1216        // error, not a permanent client error — so it must NOT be classified non-retryable.
1217        let err = wrapped_provider_error(r#"{"statusCode":502,"error":{"code":403}}"#);
1218        assert!(!is_non_retryable_client_error(&err));
1219        // 5xx codes without a reason phrase here (501) are still matched via the status key.
1220        let nested = wrapped_provider_error(r#"{"statusCode":501,"error":{"code":403}}"#);
1221        assert!(!is_non_retryable_client_error(&nested));
1222        // a genuine 4xx with no 5xx in the chain is still non-retryable.
1223        let pure_4xx = wrapped_provider_error(r#"{"statusCode":403,"message":"forbidden"}"#);
1224        assert!(is_non_retryable_client_error(&pure_4xx));
1225    }
1226}