Skip to main content

eclipse_core/
provider.rs

1//! OpenAI-compatible chat-completions client. The endpoint and key come only from config.
2
3use crate::config::ProviderConfig;
4use crate::error::{Error, HttpFailure, ProviderFailure, Result};
5use crate::hooks::ToolChoice;
6use crate::message::{Message, Role};
7use crate::stream::{DeltaFn, SseParser, StreamAccumulator};
8use crate::tools::ToolSpec;
9use crate::usage::TurnUsage;
10use async_trait::async_trait;
11use serde_json::{json, Value};
12use std::fmt;
13use std::time::Duration;
14
15#[async_trait]
16pub trait ChatProvider: Send + Sync {
17    /// Send the conversation and return the assistant's reply (text and/or tool calls).
18    async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<Message>;
19
20    /// Like [`chat`](Self::chat), but reports assistant text through `on_delta` as it is
21    /// generated. The returned message is always the complete reply. Providers that
22    /// cannot stream just answer normally and emit no deltas.
23    async fn chat_stream(
24        &self,
25        messages: &[Message],
26        tools: &[ToolSpec],
27        on_delta: DeltaFn<'_>,
28    ) -> Result<Message> {
29        let _ = on_delta;
30        self.chat(messages, tools).await
31    }
32
33    /// One streaming turn with a request patch applied.
34    ///
35    /// The default refuses a non-empty patch instead of dropping it: a hook that set
36    /// `tool_choice` and a provider that ignored it would make the model look irrational for a
37    /// reason nothing in the transcript records.
38    async fn chat_stream_patched(
39        &self,
40        messages: &[Message],
41        tools: &[ToolSpec],
42        on_delta: DeltaFn<'_>,
43        patch: &crate::hooks::RequestPatch,
44    ) -> Result<Message> {
45        if !patch.is_empty() {
46            return Err(Error::provider(format!(
47                "this provider cannot apply a request patch ({} set); use an \
48                 OpenAI-compatible provider, or a hook that only observes",
49                patch.describe()
50            )));
51        }
52        self.chat_stream(messages, tools, on_delta).await
53    }
54
55    /// What the most recent call cost, if the server said. Taken rather than borrowed so a
56    /// caller cannot show the same turn twice; providers that do not measure return `None`.
57    fn take_usage(&self) -> Option<TurnUsage> {
58        None
59    }
60
61    /// Whether this provider's manifest claims it can read a picture (`#346`).
62    ///
63    /// `false` by default, which is the honest answer for anything that is not an
64    /// OpenAI-compatible client with a profile: a test double or an embedder cannot see, and
65    /// `[vision] mode = "native"` against one refuses the attach instead of sending bytes into a
66    /// void.
67    fn can_see(&self) -> bool {
68        false
69    }
70}
71
72/// The optional knobs `[provider]` exposes: *what we want* sent. The wire profile is the
73/// other half — *how this backend spells it*, and whether it understands the field at all.
74///
75/// Every field is optional and an unset one is never sent, so a backend that rejects unknown
76/// fields is never handed one it did not ask for. `[provider] extra_body` is the escape hatch
77/// for the rest.
78#[derive(Debug, Clone, Default, PartialEq)]
79pub struct RequestOptions {
80    pub top_p: Option<f64>,
81    pub seed: Option<i64>,
82    pub stop: Option<Vec<String>>,
83    pub parallel_tool_calls: Option<bool>,
84    pub tool_choice: Option<ToolChoice>,
85    /// Merged into the body after every standing field and before a per-turn patch.
86    pub extra_body: Value,
87}
88
89impl RequestOptions {
90    /// The keys this set of options will actually put on the wire. Used to explain a 400 that
91    /// names one of them instead of leaving the operator with the server's sentence alone.
92    fn applied_keys(&self) -> Vec<&'static str> {
93        let mut keys = Vec::new();
94        if self.top_p.is_some() {
95            keys.push("top_p");
96        }
97        if self.seed.is_some() {
98            keys.push("seed");
99        }
100        if self.stop.is_some() {
101            keys.push("stop");
102        }
103        if self.parallel_tool_calls.is_some() {
104            keys.push("parallel_tool_calls");
105        }
106        if self.tool_choice.is_some() {
107            keys.push("tool_choice");
108        }
109        keys
110    }
111}
112
113pub struct OpenAiProvider {
114    client: reqwest::Client,
115    url: String,
116    api_key: Option<String>,
117    model: String,
118    temperature: Option<f64>,
119    max_tokens: Option<u32>,
120    options: RequestOptions,
121    profile: ProviderProfile,
122    /// Resolved vision capability: per-route `vision` takes precedence over the wire profile.
123    can_see: bool,
124    /// The effort this backend takes, resolved from the profile and its per-model entries.
125    reasoning: Reasoning,
126    /// Where the effort is read from on every request: the session's `/reasoning` override, else
127    /// `[provider] reasoning_effort`. Shared, so setting it does not rebuild the client.
128    dial: crate::reasoning::Shared,
129    stream: bool,
130    max_retries: u32,
131    /// Repeat a request that failed after it went out. See `ProviderConfig::retry_after_send`.
132    retry_after_send: bool,
133    retry_base_delay: Duration,
134    /// How long a *silent* connection is tolerated, not how long a reply may take. Measured
135    /// between body reads, so a reply that keeps streaming can run for as long as the model
136    /// needs — a long reasoning block on a local model is minutes, and a wall-clock cap on the
137    /// whole request ends it mid-sentence with "the connection dropped mid-reply".
138    idle: Duration,
139    /// Filled by every call, drained by [`ChatProvider::take_usage`].
140    last_usage: std::sync::Mutex<Option<TurnUsage>>,
141}
142
143/// How a request is shaped for one backend dialect. Everything here is wire detail: the
144/// conversation, the tools and the prompt never depend on it.
145///
146/// Built in: `openai` and `llamacpp`. A plugin may declare more, and a plugin profile with a
147/// built-in's name replaces it, so a backend quirk needs no code change.
148#[derive(Debug, Clone, PartialEq)]
149pub struct ProviderProfile {
150    pub name: String,
151    /// Send `tool_choice: "auto"` alongside `tools`.
152    pub tool_choice: bool,
153    /// Ask for `stream_options: {include_usage: true}` (OpenAI reports token usage that way;
154    /// some local servers reject the field).
155    pub stream_usage: bool,
156    /// Field name for [`ProviderConfig::max_tokens`]: `max_tokens` or
157    /// `max_completion_tokens`.
158    pub max_tokens_field: Option<String>,
159    /// Advertise tools at all. `false` for backends that break on the `tools` array.
160    pub supports_tools: bool,
161    /// Round-trip the assistant's reasoning into the next request's message body.
162    pub send_reasoning: bool,
163    /// Merged into every request body last, so it wins over the fields above. This is the
164    /// escape hatch for `chat_template_kwargs`, `reasoning_effort` and friends.
165    pub body: serde_json::Value,
166    /// How this backend takes a reasoning effort, when a manifest declares it. Absent = nobody said,
167    /// and then a configured level is sent as `reasoning_effort` verbatim and an unset one is not
168    /// sent at all — the behaviour from before this existed.
169    pub reasoning: Option<crate::reasoning::Policy>,
170    /// Per-model overrides, keyed by the model id this profile serves. A model that reasons on/off
171    /// only, or not at all, is one entry in a manifest — not a code change.
172    pub models: std::collections::BTreeMap<String, ModelReasoning>,
173    /// Standing request policy: context size, output cap, temperature mode, formats this route
174    /// rejects, and the cheap model it publishes. Declared, never compiled in.
175    pub request: RequestPolicy,
176    /// What this route can do that the request body does not say. Reported by `config check` and
177    /// `tools schema`, so "can this backend see an image" is answerable without reading a manifest.
178    pub vision: Option<bool>,
179}
180
181/// The standing request policy a profile declares: the knobs that depend on the model and the
182/// endpoint rather than on one turn.
183#[derive(Debug, Clone, Default, PartialEq)]
184pub struct RequestPolicy {
185    /// Context window to ask for, at `num_ctx_field`.
186    pub num_ctx: Option<u32>,
187    /// Where `num_ctx` goes: `options.num_ctx` for Ollama's native shape, `n_ctx` for llama.cpp's.
188    pub num_ctx_field: Option<String>,
189    /// Hard ceiling on reply tokens, applied to whatever the config asked for.
190    pub max_output: Option<u32>,
191    pub temperature: Option<Temperature>,
192    /// `response_format` types this route rejects outright; one is dropped rather than sent to be
193    /// refused.
194    pub reject_response_formats: Vec<String>,
195    /// The cheap model this provider publishes for titles, compaction and judging.
196    pub aux_model: Option<String>,
197    /// Per-model limits, keyed by the model id.
198    pub models: std::collections::BTreeMap<String, ModelLimits>,
199}
200
201impl RequestPolicy {
202    /// The limits in force for `model`: its own entry where there is one, the profile's otherwise.
203    pub fn limits_for(&self, model: &str) -> ModelLimits {
204        let own = self.models.get(model);
205        ModelLimits {
206            num_ctx: own.and_then(|m| m.num_ctx).or(self.num_ctx),
207            max_output: own.and_then(|m| m.max_output).or(self.max_output),
208        }
209    }
210
211    /// Does this route refuse this `response_format` type?
212    pub fn rejects_format(&self, kind: &str) -> bool {
213        self.reject_response_formats
214            .iter()
215            .any(|rejected| rejected == kind)
216    }
217}
218
219/// Per-model limits only: a model with its own context size or reply cap.
220#[derive(Debug, Clone, Default, PartialEq)]
221pub struct ModelLimits {
222    pub num_ctx: Option<u32>,
223    pub max_output: Option<u32>,
224}
225
226/// What a profile says to do with `temperature`.
227#[derive(Debug, Clone, Copy, PartialEq)]
228pub enum Temperature {
229    /// Send what the config asks for (the default, and what every backend does).
230    #[allow(dead_code)]
231    Default,
232    /// Never send it: some routes reject the field outright.
233    Omit,
234    /// Always send this value, whatever the config says.
235    Fixed(f32),
236}
237
238/// What a model says about its own reasoning, in a manifest.
239#[derive(Debug, Clone, PartialEq, serde::Deserialize, serde::Serialize)]
240#[serde(untagged)]
241pub enum ModelReasoning {
242    /// `reasoning = false`: this model does not reason, so no field is ever sent; `true` inherits the
243    /// profile's policy.
244    Toggle(bool),
245    /// A policy of its own: the shape when the model has an off switch but no graded levels.
246    Policy(crate::reasoning::Policy),
247}
248
249impl Default for ProviderProfile {
250    fn default() -> Self {
251        Self::builtin("openai").expect("openai is a built-in profile")
252    }
253}
254
255impl ProviderProfile {
256    fn make(name: &str, tool_choice: bool, stream_usage: bool, body: serde_json::Value) -> Self {
257        Self {
258            name: name.into(),
259            tool_choice,
260            stream_usage,
261            max_tokens_field: Some("max_tokens".into()),
262            supports_tools: true,
263            send_reasoning: false,
264            body,
265            reasoning: None,
266            models: std::collections::BTreeMap::new(),
267            request: RequestPolicy::default(),
268            vision: None,
269        }
270    }
271
272    /// One of the profiles compiled in, or `None` if there is no such built-in.
273    pub fn builtin(name: &str) -> Option<Self> {
274        match name {
275            "openai" | "" => {
276                let mut p = Self::make("openai", true, true, json!({}));
277                p.send_reasoning = true;
278                p.reasoning = Some(crate::reasoning::Policy::openai());
279                Some(p)
280            }
281            // llama.cpp (and most local servers) accept `tools` but choke on
282            // `stream_options`; they have no `tool_choice` knob worth sending.
283            "llamacpp" => {
284                let mut p = Self::make("llamacpp", false, false, json!({}));
285                // Measured on the local builds (see the shipped manifest): a graded dial on some
286                // models, `none` as the off switch, and `minimal` mapping to nothing at all.
287                p.reasoning = Some(crate::reasoning::Policy::llamacpp());
288                Some(p)
289            }
290            _ => None,
291        }
292    }
293
294    /// Resolve `name` against the built-ins and the profiles plugins declared, plugins
295    /// winning on a name collision.
296    pub fn resolve(name: &str, from_plugins: &[ProviderProfile]) -> crate::Result<Self> {
297        if let Some(p) = from_plugins.iter().find(|p| p.name == name) {
298            return Ok(p.clone());
299        }
300        Self::builtin(name).ok_or_else(|| {
301            crate::Error::Config(format!(
302                "unknown provider profile {name:?}; built in: openai, llamacpp, or one a \
303                 plugin declares"
304            ))
305        })
306    }
307}
308
309/// What a model's reasoning control is, once the profile and its per-model entries are consulted.
310///
311/// Three cases, because "nobody declared it" and "it has none" have to behave differently: the
312/// first keeps the old behaviour (a configured level goes out verbatim), the second sends nothing at
313/// all no matter what is asked.
314#[derive(Debug, Clone, PartialEq)]
315pub enum Reasoning {
316    /// A declared policy: the manifest says what this backend takes.
317    Policy(crate::reasoning::Policy),
318    /// The model does not reason: no field, ever.
319    Off,
320    /// Nobody said. A configured or asked-for level is sent as `reasoning_effort` verbatim.
321    Undeclared,
322}
323
324impl Reasoning {
325    /// The level this route sends when neither the file nor the session asked for one: the
326    /// policy's own declared `default` (`#276`), and `None` where there is nothing to send —
327    /// an undeclared backend, a model that does not reason, or a policy with no dial.
328    ///
329    /// One method rather than a `match` per read-out: the dashboard strip, the TUI, `/reasoning`
330    /// and `/status` all have to answer this the same way, or one of them will describe a default
331    /// the request does not carry.
332    pub fn declared_default(&self) -> Option<&str> {
333        match self {
334            Reasoning::Policy(policy) if policy.has_dial() => policy.default_effort(),
335            Reasoning::Policy(_) | Reasoning::Off | Reasoning::Undeclared => None,
336        }
337    }
338}
339
340impl ProviderProfile {
341    /// The reasoning control for `model`: its own manifest entry, else the profile's.
342    pub fn reasoning_for(&self, model: &str) -> Reasoning {
343        match self.models.get(model) {
344            Some(ModelReasoning::Toggle(false)) => Reasoning::Off,
345            Some(ModelReasoning::Toggle(true)) => match &self.reasoning {
346                Some(policy) => Reasoning::Policy(policy.clone()),
347                None => Reasoning::Undeclared,
348            },
349            Some(ModelReasoning::Policy(policy)) => Reasoning::Policy(policy.clone()),
350            None => match &self.reasoning {
351                Some(policy) => Reasoning::Policy(policy.clone()),
352                None => Reasoning::Undeclared,
353            },
354        }
355    }
356}
357
358/// Longest wait honoured from a `Retry-After` header; a server asking for more is
359/// treated as a final failure rather than stalling the agent.
360const MAX_RETRY_AFTER: Duration = Duration::from_secs(30);
361
362/// Wait before retry number `retry` (1-based): base, 2x base, 4x base, ...
363fn backoff_delay(base: Duration, retry: u32) -> Duration {
364    base.saturating_mul(1u32 << (retry - 1).min(16))
365}
366
367/// The id to quote at support, under any of the names servers use for it.
368fn request_id(headers: &reqwest::header::HeaderMap) -> Option<String> {
369    ["x-request-id", "request-id", "x-amzn-requestid", "cf-ray"]
370        .iter()
371        .find_map(|name| {
372            let value = headers.get(*name)?.to_str().ok()?.trim();
373            (!value.is_empty()).then(|| value.to_string())
374        })
375}
376
377/// Does `haystack` name `field` as a word? Guards short keys like `stop` against matching
378/// the middle of `stop_reason` or of prose.
379fn mentions_field(haystack: &str, field: &str) -> bool {
380    let bytes = haystack.as_bytes();
381    haystack.match_indices(field).any(|(i, _)| {
382        let before_ok = i == 0 || !is_word_byte(bytes[i - 1]);
383        let after = i + field.len();
384        let after_ok = after >= bytes.len() || !is_word_byte(bytes[after]);
385        before_ok && after_ok
386    })
387}
388
389fn is_word_byte(b: u8) -> bool {
390    b.is_ascii_alphanumeric() || b == b'_'
391}
392
393/// Why a request got no answer, in words an operator can act on. The deepest cause is the
394/// useful part: reqwest's own message is `error sending request for url (<url>)`, and the
395/// url is already in the failure.
396fn describe_transport(e: &reqwest::Error) -> String {
397    let detail = deepest_cause(e);
398    if e.is_timeout() {
399        return format!("the request timed out: {detail}");
400    }
401    if e.is_connect() {
402        return format!("the connection could not be established: {detail} — is the server up?");
403    }
404    if e.is_body() || e.is_decode() {
405        return format!("the connection broke while sending or decoding: {detail}");
406    }
407    detail
408}
409
410fn deepest_cause(e: &dyn std::error::Error) -> String {
411    let mut source = e.source();
412    let mut text = e.to_string();
413    while let Some(inner) = source {
414        text = inner.to_string();
415        source = inner.source();
416    }
417    text
418}
419
420/// Say how many attempts were spent, so "it failed" never hides "it retried four times".
421fn with_attempts(failure: ProviderFailure, attempts: u32) -> ProviderFailure {
422    if attempts <= 1 {
423        return failure;
424    }
425    let note = format!("{attempts} attempts, with backoff");
426    match failure {
427        ProviderFailure::Transport { url, message, sent } => ProviderFailure::Transport {
428            url,
429            message: format!("{message} ({note})"),
430            sent,
431        },
432        ProviderFailure::Unauthorized(mut h) => {
433            h.hint = Some(join_hint(h.hint.take(), &note));
434            ProviderFailure::Unauthorized(h)
435        }
436        ProviderFailure::InvalidRequest(mut h) => {
437            h.hint = Some(join_hint(h.hint.take(), &note));
438            ProviderFailure::InvalidRequest(h)
439        }
440        ProviderFailure::Http(mut h) => {
441            h.hint = Some(join_hint(h.hint.take(), &note));
442            ProviderFailure::Http(h)
443        }
444        other => other,
445    }
446}
447
448fn join_hint(hint: Option<String>, note: &str) -> String {
449    match hint {
450        Some(h) => format!("{h}; {note}"),
451        None => note.to_string(),
452    }
453}
454
455/// A `Retry-After` given in seconds (the HTTP-date form is ignored).
456fn retry_after(headers: &reqwest::header::HeaderMap) -> Option<Duration> {
457    headers
458        .get(reqwest::header::RETRY_AFTER)?
459        .to_str()
460        .ok()?
461        .trim()
462        .parse::<u64>()
463        .ok()
464        .map(Duration::from_secs)
465}
466
467impl fmt::Debug for OpenAiProvider {
468    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
469        f.debug_struct("OpenAiProvider")
470            .field("url", &self.url)
471            .field("model", &self.model)
472            .finish_non_exhaustive()
473    }
474}
475
476impl OpenAiProvider {
477    pub fn new(cfg: &ProviderConfig) -> Result<Self> {
478        Self::with_dial(cfg, &[], None)
479    }
480
481    /// The constructor every caller that can be told `/reasoning` uses: the dial is where the
482    /// effort is read from on each request, so it has to outlive the client.
483    pub fn with_dial(
484        cfg: &ProviderConfig,
485        from_plugins: &[ProviderProfile],
486        dial: Option<crate::reasoning::Shared>,
487    ) -> Result<Self> {
488        Self::build(cfg, from_plugins, dial)
489    }
490
491    /// Build the provider, resolving `provider.profile` against the built-in profiles and
492    /// the ones plugins declared.
493    pub fn with_profiles(cfg: &ProviderConfig, from_plugins: &[ProviderProfile]) -> Result<Self> {
494        Self::build(cfg, from_plugins, None)
495    }
496
497    fn build(
498        cfg: &ProviderConfig,
499        from_plugins: &[ProviderProfile],
500        dial: Option<crate::reasoning::Shared>,
501    ) -> Result<Self> {
502        let base = cfg.base_url.trim().trim_end_matches('/');
503        if base.is_empty() {
504            return Err(Error::Config("provider.base_url is not set".into()));
505        }
506        let idle = Duration::from_secs(cfg.timeout_secs.max(1));
507        // No `.timeout()` here: reqwest's timeout bounds the *whole* request, body included, so
508        // it is a deadline on the reply rather than on the connection. `connect_timeout` covers
509        // the one wait that genuinely has a ceiling; every read is bounded by `idle` below.
510        let client = reqwest::Client::builder()
511            .connect_timeout(idle)
512            .build()
513            .map_err(|e| Error::provider(format!("could not build an HTTP client: {e}")))?;
514        let profile =
515            ProviderProfile::resolve(cfg.profile.as_deref().unwrap_or("openai"), from_plugins)?;
516        let can_see = cfg.vision.unwrap_or(profile.vision == Some(true));
517        let options = RequestOptions {
518            top_p: cfg.top_p,
519            seed: cfg.seed,
520            stop: cfg
521                .stop
522                .as_ref()
523                .map(|s| {
524                    s.iter()
525                        .filter(|one| !one.is_empty())
526                        .cloned()
527                        .collect::<Vec<_>>()
528                })
529                .filter(|s: &Vec<String>| !s.is_empty()),
530            parallel_tool_calls: cfg.parallel_tool_calls,
531            tool_choice: cfg.tool_choice.clone(),
532            extra_body: cfg.extra_body.clone().unwrap_or(serde_json::Value::Null),
533        };
534        // A range check here beats a 400 from every backend in turn, each explaining it
535        // differently.
536        if let Some(top_p) = options.top_p {
537            if !(0.0..=1.0).contains(&top_p) {
538                return Err(Error::Config(format!(
539                    "provider.top_p must be between 0 and 1, got {top_p}"
540                )));
541            }
542        }
543        Ok(Self {
544            client,
545            url: format!("{base}/chat/completions"),
546            api_key: cfg.api_key.clone().filter(|k| !k.is_empty()),
547            model: cfg.model.clone(),
548            temperature: cfg.temperature,
549            max_tokens: cfg.max_tokens,
550            options,
551            reasoning: profile.reasoning_for(&cfg.model),
552            dial: dial.unwrap_or_else(|| {
553                std::sync::Arc::new(crate::reasoning::Dial::new(cfg.reasoning_effort.clone()))
554            }),
555            profile,
556            can_see,
557            stream: cfg.stream,
558            max_retries: cfg.max_retries,
559            retry_after_send: cfg.retry_after_send,
560            retry_base_delay: Duration::from_millis(cfg.retry_base_delay_ms),
561            idle,
562            last_usage: std::sync::Mutex::new(None),
563        })
564    }
565
566    /// The profile in force, for diagnostics.
567    pub fn profile_name(&self) -> &str {
568        &self.profile.name
569    }
570
571    /// What this request will ask for: the session's override, else `[provider] reasoning_effort`.
572    pub fn reasoning_effort(&self) -> Option<String> {
573        self.dial.effort()
574    }
575
576    /// The control this backend offers, for a report that has to say whether the level will do
577    /// anything.
578    pub fn reasoning(&self) -> &Reasoning {
579        &self.reasoning
580    }
581
582    pub fn request_body(&self, messages: &[Message], tools: &[ToolSpec]) -> Value {
583        self.request_body_with(messages, tools, &crate::hooks::RequestPatch::default())
584    }
585
586    /// The request body with a turn's patch applied. Order matters: profile fields first, the
587    /// turn's patch last, because a patch is a decision made for this turn and the profile is a
588    /// standing one.
589    pub fn request_body_with(
590        &self,
591        messages: &[Message],
592        tools: &[ToolSpec],
593        patch: &crate::hooks::RequestPatch,
594    ) -> Value {
595        // Reasoning is echoed only as far as it can still do any work. Inside the turn that
596        // produced it, a backend with interleaved thinking needs it to continue its own plan.
597        // On a turn that has already finished, it is text the model spent and acted on: sending
598        // it again is charged to the window every request, for the rest of the session, and a
599        // long session ends up paying for every thought it ever had. `send_reasoning` decides
600        // whether the current turn's thinking goes out at all; this decides how far back it
601        // reaches, and it reaches no further than the newest user message.
602        let live_from = messages
603            .iter()
604            .rposition(|m| m.role == Role::User)
605            .unwrap_or(0);
606        let wire_messages: Vec<Value> = messages
607            .iter()
608            .enumerate()
609            .map(|(i, m)| {
610                let mut v = serde_json::to_value(m).expect("a message serializes");
611                if let Some(obj) = v.as_object_mut() {
612                    // `#346`: a picture is a content part on the wire, never a key of its own.
613                    // A message without pictures takes no branch here and serialises to exactly
614                    // the bytes it did before this existed — the whole history passes through
615                    // this loop, so one changed byte throws away every warm prefix cache.
616                    if !m.images.is_empty() {
617                        obj.remove("images");
618                        match m.wire_content() {
619                            Some(content) => {
620                                obj.insert("content".to_string(), content);
621                            }
622                            None => {
623                                obj.remove("content");
624                            }
625                        }
626                    }
627                    if !self.profile.send_reasoning || i < live_from {
628                        obj.remove("reasoning_content");
629                    }
630                }
631                v
632            })
633            .collect();
634        let mut body = json!({"model": self.model, "messages": wire_messages});
635        if self.profile.supports_tools && !tools.is_empty() {
636            body["tools"] = json!(tools);
637            // The profile says whether this backend understands the field; the config says
638            // what value we want. Left unset, the profile's own default applies (`auto` for
639            // the profiles that have it), which is what the agent wants: call a tool when one
640            // is worth calling.
641            match &self.options.tool_choice {
642                Some(choice) => body["tool_choice"] = choice.to_json(),
643                None if self.profile.tool_choice => body["tool_choice"] = json!("auto"),
644                None => {}
645            }
646        }
647        if let Some(t) = self.temperature {
648            body["temperature"] = json!(t);
649        }
650        if let (Some(max), Some(field)) = (self.max_tokens, &self.profile.max_tokens_field) {
651            body[field] = json!(max);
652        }
653        // The optional knobs, each only when asked for.
654        if let Some(p) = self.options.top_p {
655            body["top_p"] = json!(p);
656        }
657        if let Some(seed) = self.options.seed {
658            body["seed"] = json!(seed);
659        }
660        if let Some(stop) = &self.options.stop {
661            body["stop"] = json!(stop);
662        }
663        // Reasoning is read **here**, per request, not out of the options the client was built
664        // with: `/reasoning high` in a running session has to change the next body. The policy
665        // (from a manifest) decides the field and the value; a backend nobody described gets the
666        // level verbatim, which is what the config did before any of this existed.
667        let asked = self.reasoning_effort();
668        match &self.reasoning {
669            Reasoning::Off => {}
670            Reasoning::Policy(policy) => {
671                let wire = policy.resolve_at(asked.as_deref(), Some(&self.url));
672                // `Set` puts a value at the policy's field; `Body` is an off switch that is a whole
673                // table (`chat_template_kwargs`). Both merge the same way, `Omit` merges nothing.
674                if !matches!(wire, crate::reasoning::Wire::Omit(_)) {
675                    merge_json(&mut body, wire.body(policy));
676                }
677            }
678            Reasoning::Undeclared => {
679                // `omit` is not a value an undeclared backend was asked to take — it is the
680                // absence of the field, and sending the word would be the opposite (`#278`).
681                if let Some(level) = asked.as_deref() {
682                    if !crate::reasoning::is_omit(level) {
683                        body["reasoning_effort"] = json!(level);
684                    }
685                }
686            }
687        }
688        if let Some(parallel) = self.options.parallel_tool_calls {
689            body["parallel_tool_calls"] = json!(parallel);
690        }
691        // Then the profile, so a dialect's explicit fields win over the defaults above.
692        merge_json(&mut body, self.profile.body.clone());
693        // ...then the escape hatch, which exists precisely for what the profile does not
694        // model. A per-turn patch still lands after it: a decision made for this turn is more
695        // specific than a standing one.
696        if !self.options.extra_body.is_null() {
697            merge_json(&mut body, self.options.extra_body.clone());
698        }
699        // After the profile: a per-turn patch is the more specific decision.
700        if let Some(t) = patch.temperature {
701            body["temperature"] = json!(t);
702        }
703        if let (Some(max), Some(field)) = (patch.max_tokens, &self.profile.max_tokens_field) {
704            body[field] = json!(max);
705        }
706        if let Some(choice) = &patch.tool_choice {
707            // A choice needs tools to choose from; sending one without them is a 400 from most
708            // servers, so say what happened instead of shipping an invalid request.
709            if body.get("tools").is_none() {
710                body["tools"] = json!([]);
711            }
712            body["tool_choice"] = choice.to_json();
713        }
714        for (key, value) in &patch.extra_params {
715            body[key.as_str()] = value.clone();
716        }
717        // Last, because these are the backend's constraints rather than the turn's wishes: a route
718        // that rejects `temperature` rejects it whatever the config says, and a cap is a ceiling on
719        // every request, not a default one request may exceed.
720        self.apply_request_policy(&mut body);
721        body
722    }
723
724    /// The profile's standing request policy: context size, reply cap, temperature, refused formats.
725    fn apply_request_policy(&self, body: &mut Value) {
726        let limits = self.profile.request.limits_for(&self.model);
727        if let Some(ctx) = limits.num_ctx {
728            let field = self
729                .profile
730                .request
731                .num_ctx_field
732                .as_deref()
733                .unwrap_or("options.num_ctx");
734            merge_json(body, crate::reasoning::field_path(field, json!(ctx)));
735        }
736        if let Some(cap) = limits.max_output {
737            let field = self
738                .profile
739                .max_tokens_field
740                .clone()
741                .unwrap_or_else(|| "max_tokens".to_string());
742            // A ceiling, not a default: 4096 asked for with a 2048 cap is 2048, and an unset ask is
743            // still capped — a profile that publishes 2048 does not want a runaway reply because
744            // the config left the field out.
745            let asked = body.get(&field).and_then(|v| v.as_u64());
746            let send = match asked {
747                Some(n) => n.min(u64::from(cap)),
748                None => u64::from(cap),
749            };
750            body[field.as_str()] = json!(send);
751        }
752        match self.profile.request.temperature {
753            Some(Temperature::Omit) => {
754                if let Some(obj) = body.as_object_mut() {
755                    obj.remove("temperature");
756                }
757            }
758            Some(Temperature::Fixed(value)) => body["temperature"] = json!(value),
759            Some(Temperature::Default) | None => {}
760        }
761        if let Some(kind) = body
762            .get("response_format")
763            .and_then(|f| f.get("type"))
764            .and_then(|t| t.as_str())
765            .map(str::to_string)
766        {
767            if self.profile.request.rejects_format(&kind) {
768                if let Some(obj) = body.as_object_mut() {
769                    obj.remove("response_format");
770                }
771            }
772        }
773    }
774}
775
776/// Merge `over` into `base`: objects merge key by key, anything else replaces.
777fn merge_json(base: &mut Value, over: Value) {
778    match (base, over) {
779        // Nothing to merge is nothing to do: a profile or a patch that says `null` (a manifest with
780        // no `[provider_profile.body]` table is exactly that) must not be able to replace the
781        // request with it. This is how a profile with no body produced a fifteen-byte request
782        // containing only `{"stream":true}` — the body had been nulled and the index-then-assign
783        // rebuilt an object with that one key in it.
784        (_, Value::Null) => {}
785        (Value::Object(base), Value::Object(over)) => {
786            for (key, value) in over {
787                match base.get_mut(&key) {
788                    Some(slot) => merge_json(slot, value),
789                    None => {
790                        base.insert(key, value);
791                    }
792                }
793            }
794        }
795        (slot, over) => *slot = over,
796    }
797}
798
799/// Extract the first choice's message from a chat-completions response body.
800pub fn parse_response(body: &Value) -> Result<Message> {
801    let msg = body.pointer("/choices/0/message").ok_or_else(|| {
802        Error::Provider(ProviderFailure::Response {
803            message: "the reply has no choices".into(),
804            body: Some(clip(body)),
805        })
806    })?;
807    let mut m: Message = serde_json::from_value(msg.clone()).map_err(|e| {
808        Error::Provider(ProviderFailure::Response {
809            message: format!("the message is not one we can read: {e}"),
810            body: Some(clip(msg)),
811        })
812    })?;
813    m.role = Role::Assistant;
814    m.finish_reason = body
815        .pointer("/choices/0/finish_reason")
816        .and_then(Value::as_str)
817        .map(str::to_string);
818    for (i, call) in m.tool_calls.iter_mut().enumerate() {
819        if call.id.is_empty() {
820            call.id = format!("call_{i}");
821        }
822    }
823    Ok(m)
824}
825
826fn clip(v: &Value) -> String {
827    let s = v.to_string();
828    match s.char_indices().nth(300) {
829        Some((i, _)) => format!("{}…", &s[..i]),
830        None => s,
831    }
832}
833
834impl OpenAiProvider {
835    /// POST the request, retrying while the failure is one the taxonomy calls retryable —
836    /// which is `408`/`429`/`5xx` and anything that never got an answer (a refused, reset or
837    /// timed-out connection), because those are the server's own transient trouble rather
838    /// than a mistake in what we asked for.
839    ///
840    /// Waits `retry_base_delay_ms`, then double, then double again, unless the server sent a
841    /// `Retry-After` (in seconds, honoured up to 30 s; a longer one ends the retries rather
842    /// than stalling the agent). The error reports how many attempts were spent.
843    ///
844    /// Only the *request* is retried here. A stream that breaks after it started is dealt
845    /// with in [`OpenAiProvider::stream_with`], which knows whether the reader has already
846    /// been shown text.
847    async fn send(&self, body: &Value) -> Result<reqwest::Response> {
848        let mut retries = 0u32;
849        loop {
850            let mut req = self.client.post(&self.url).json(body);
851            if let Some(k) = &self.api_key {
852                req = req.bearer_auth(k);
853            }
854            let sent = match tokio::time::timeout(self.idle, req.send()).await {
855                Ok(sent) => sent,
856                Err(_) => {
857                    // The server accepted the connection and said nothing for a whole idle
858                    // budget. That is the one wait worth giving up on.
859                    return Err(Error::Provider(ProviderFailure::Transport {
860                        url: self.url.clone(),
861                        message: format!("the endpoint said nothing for {} s", self.idle.as_secs()),
862                        sent: true,
863                    }));
864                }
865            };
866            let failure = match sent {
867                Ok(resp) if resp.status().is_success() => return Ok(resp),
868                Ok(resp) => self.classify_http(resp, body).await,
869                Err(e) => ProviderFailure::Transport {
870                    url: self.url.clone(),
871                    message: describe_transport(&e),
872                    sent: !e.is_connect(),
873                },
874            };
875            match self.wait_before_retry(retries, &failure) {
876                Some(delay) => {
877                    retries += 1;
878                    tokio::time::sleep(delay).await;
879                }
880                None => return Err(Error::Provider(with_attempts(failure, retries + 1))),
881            }
882        }
883    }
884
885    /// How long to wait before repeating a failed attempt, or `None` to stop trying.
886    ///
887    /// A failure that happened **after the request went out** is only repeated when the config says
888    /// so: `/chat/completions` is billed and not idempotent, so repeating a dropped connection pays
889    /// for the same generation twice, up to `max_retries + 1` times per turn. A connect-stage failure
890    /// never reached the server and is always worth repeating.
891    fn wait_before_retry(&self, retries: u32, failure: &ProviderFailure) -> Option<Duration> {
892        let may_repeat = if failure.after_send() {
893            self.retry_after_send
894        } else {
895            failure.is_retryable()
896        };
897        if !may_repeat || self.max_retries == 0 || retries >= self.max_retries {
898            return None;
899        }
900        match failure.retry_after_secs().map(Duration::from_secs) {
901            Some(asked) if asked > MAX_RETRY_AFTER => None,
902            Some(asked) => Some(asked),
903            None => Some(backoff_delay(self.retry_base_delay, retries + 1)),
904        }
905    }
906
907    /// Turn a non-2xx answer into the failure that describes it, keeping what the server
908    /// said. `sent` is the body we asked with, so a 400 naming a field we set can say which
909    /// config line to look at instead of quoting the server and stopping there.
910    async fn classify_http(&self, resp: reqwest::Response, sent: &Value) -> ProviderFailure {
911        let status = resp.status().as_u16();
912        let request_id = request_id(resp.headers());
913        let retry_after_secs = retry_after(resp.headers()).map(|d| d.as_secs());
914        // The body must be read before the response is dropped; a body we cannot read is not
915        // worth a different failure than a body that is empty. The read is bounded by `idle`
916        // like every other one: an endpoint that answers `503` and then stalls the body — a
917        // proxy mid-shutdown, a broken `base_url` — used to wedge the run here for ever, with
918        // no retry, no error and no budget, because `send()`'s timeout ends at the headers.
919        let text = match tokio::time::timeout(self.idle, resp.text()).await {
920            Ok(Ok(text)) => text,
921            Ok(Err(_)) | Err(_) => String::new(),
922        };
923        let mut failure = HttpFailure {
924            status,
925            body: text.chars().take(600).collect(),
926            request_id,
927            retry_after_secs,
928            hint: None,
929        };
930        failure.hint = self.explain(status, &failure.body, sent);
931        match status {
932            401 | 403 => ProviderFailure::Unauthorized(failure),
933            400 | 404 | 405 | 422 => ProviderFailure::InvalidRequest(failure),
934            _ => ProviderFailure::Http(failure),
935        }
936    }
937
938    /// What to change, when the answer says enough to tell. Only ever adds advice: the
939    /// status and the server's own words are always reported as they came.
940    fn explain(&self, status: u16, body: &str, sent: &Value) -> Option<String> {
941        if status == 404 {
942            return Some(format!(
943                "check provider.base_url and provider.model: `{}` may not be served at this URL",
944                self.model
945            ));
946        }
947        if !matches!(status, 400 | 422) {
948            return None;
949        }
950        let lower = body.to_ascii_lowercase();
951        // A field we sent, named by the server. Longer names first so `top_p` is not matched
952        // by a stray `p`, and a bare `stop` only counts as a word.
953        let mut candidates: Vec<String> = self
954            .options
955            .applied_keys()
956            .into_iter()
957            .map(str::to_string)
958            .collect();
959        if let Some(field) = &self.profile.max_tokens_field {
960            if sent.get(field.as_str()).is_some() {
961                candidates.push(field.clone());
962            }
963        }
964        candidates.sort_by_key(|k| std::cmp::Reverse(k.len()));
965        let named = candidates
966            .iter()
967            .find(|key| mentions_field(&lower, key))
968            .cloned()?;
969        Some(format!(
970            "`{named}` was sent for model `{}` and this server refused it — remove provider.{named} \
971             from the config, or send it under `[provider] extra_body` if this backend spells it \
972             another way",
973            self.model
974        ))
975    }
976
977    /// Read a reply body and what the server said it cost.
978    async fn read_json_reply_timed(
979        mut resp: reqwest::Response,
980        started_ms: u64,
981        idle: Duration,
982    ) -> Result<(Message, TurnUsage)> {
983        // Read the body a chunk at a time, for the same reason the stream reads a chunk at a time:
984        // the budget is silence, not elapsed. `resp.text()` under one `timeout` would put a
985        // wall-clock cap back on the whole reply, which is the bug this function was fixed for.
986        let mut raw = Vec::new();
987        loop {
988            match tokio::time::timeout(idle, resp.chunk()).await {
989                Ok(Ok(Some(chunk))) => raw.extend_from_slice(&chunk),
990                Ok(Ok(None)) => break,
991                Ok(Err(e)) => {
992                    return Err(Error::Provider(ProviderFailure::Transport {
993                        url: "the reply body".into(),
994                        message: format!("the connection dropped while reading it: {e}"),
995                        sent: true,
996                    }))
997                }
998                Err(_) => {
999                    return Err(Error::Provider(ProviderFailure::Transport {
1000                        url: "the reply body".into(),
1001                        message: format!("the endpoint sent nothing for {} s", idle.as_secs()),
1002                        sent: true,
1003                    }))
1004                }
1005            }
1006        }
1007        let text = String::from_utf8_lossy(&raw).into_owned();
1008        let body: Value = serde_json::from_str(&text).map_err(|e| {
1009            Error::Provider(ProviderFailure::Response {
1010                message: format!("the reply is not JSON: {e}"),
1011                body: Some(text.chars().take(600).collect()),
1012            })
1013        })?;
1014        let msg = parse_response(&body)?;
1015        Ok((msg, TurnUsage::from_body(&body, started_ms)))
1016    }
1017
1018    /// Remember what the last call cost. A poisoned lock is not worth failing a turn over:
1019    /// the numbers are diagnostics, so we drop them rather than the conversation.
1020    fn record_usage(&self, usage: TurnUsage) {
1021        if let Ok(mut slot) = self.last_usage.lock() {
1022            *slot = Some(usage);
1023        }
1024    }
1025}
1026
1027#[async_trait]
1028impl ChatProvider for OpenAiProvider {
1029    fn can_see(&self) -> bool {
1030        self.can_see
1031    }
1032
1033    async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<Message> {
1034        let started = std::time::Instant::now();
1035        let resp = self.send(&self.request_body(messages, tools)).await?;
1036        let (msg, usage) =
1037            Self::read_json_reply_timed(resp, started.elapsed().as_millis() as u64, self.idle)
1038                .await?;
1039        self.record_usage(usage);
1040        Ok(msg)
1041    }
1042
1043    fn take_usage(&self) -> Option<TurnUsage> {
1044        self.last_usage.lock().ok().and_then(|mut slot| slot.take())
1045    }
1046
1047    async fn chat_stream_patched(
1048        &self,
1049        messages: &[Message],
1050        tools: &[ToolSpec],
1051        on_delta: DeltaFn<'_>,
1052        patch: &crate::hooks::RequestPatch,
1053    ) -> Result<Message> {
1054        if !self.stream {
1055            let started = std::time::Instant::now();
1056            let resp = self
1057                .send(&self.request_body_with(messages, tools, patch))
1058                .await?;
1059            let (msg, usage) =
1060                Self::read_json_reply_timed(resp, started.elapsed().as_millis() as u64, self.idle)
1061                    .await?;
1062            self.record_usage(usage);
1063            return Ok(msg);
1064        }
1065        self.stream_with(messages, tools, on_delta, patch).await
1066    }
1067
1068    async fn chat_stream(
1069        &self,
1070        messages: &[Message],
1071        tools: &[ToolSpec],
1072        on_delta: DeltaFn<'_>,
1073    ) -> Result<Message> {
1074        if !self.stream {
1075            return self.chat(messages, tools).await;
1076        }
1077        self.stream_with(
1078            messages,
1079            tools,
1080            on_delta,
1081            &crate::hooks::RequestPatch::default(),
1082        )
1083        .await
1084    }
1085}
1086
1087impl OpenAiProvider {
1088    /// The streaming turn with a patch applied, shared by both trait methods.
1089    ///
1090    /// A reply that breaks off before the model finished is retried exactly once, and only
1091    /// when nothing has reached the reader yet: repeating a request whose text is already on
1092    /// screen would print the beginning of the answer twice, which is worse than failing.
1093    /// One retry rather than `max_retries`, because each attempt is a whole model call.
1094    async fn stream_with(
1095        &self,
1096        messages: &[Message],
1097        tools: &[ToolSpec],
1098        on_delta: DeltaFn<'_>,
1099        patch: &crate::hooks::RequestPatch,
1100    ) -> Result<Message> {
1101        let mut body = self.request_body_with(messages, tools, patch);
1102        body["stream"] = json!(true);
1103        if self.profile.stream_usage {
1104            body["stream_options"] = json!({"include_usage": true});
1105        }
1106        // Atomic rather than a Cell: `on_delta` is Send + Sync, so the counter has to be too.
1107        let shown = std::sync::atomic::AtomicUsize::new(0);
1108        let counting = |d: crate::stream::Delta| {
1109            shown.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1110            on_delta(d);
1111        };
1112        let mut attempts = 0u32;
1113        loop {
1114            match self.stream_once(&body, &counting).await {
1115                Ok((msg, usage)) => {
1116                    self.note_usage(usage);
1117                    return Ok(msg);
1118                }
1119                Err(e) => {
1120                    let retry = attempts == 0
1121                        && self.max_retries > 0
1122                        && shown.load(std::sync::atomic::Ordering::Relaxed) == 0
1123                        && e.provider_failure().is_some_and(|f| f.is_retryable());
1124                    if !retry {
1125                        return Err(e);
1126                    }
1127                    attempts += 1;
1128                }
1129            }
1130        }
1131    }
1132
1133    /// One streaming attempt: send, read the events, fold them into a message. No retries
1134    /// here — the caller owns the decision to repeat a whole turn.
1135    async fn stream_once(
1136        &self,
1137        body: &Value,
1138        on_delta: DeltaFn<'_>,
1139    ) -> Result<(Message, TurnUsage)> {
1140        let mut resp = self.send(body).await?;
1141        let is_sse = resp
1142            .headers()
1143            .get(reqwest::header::CONTENT_TYPE)
1144            .and_then(|v| v.to_str().ok())
1145            .is_some_and(|v| v.to_ascii_lowercase().contains("text/event-stream"));
1146        let started = std::time::Instant::now();
1147        if !is_sse {
1148            // The server ignored `stream: true` and sent an ordinary reply.
1149            return Self::read_json_reply_timed(
1150                resp,
1151                started.elapsed().as_millis() as u64,
1152                self.idle,
1153            )
1154            .await;
1155        }
1156        let mut parser = SseParser::default();
1157        let mut acc = StreamAccumulator::default();
1158        let mut received = 0usize;
1159        loop {
1160            let chunk = match tokio::time::timeout(self.idle, resp.chunk()).await {
1161                Ok(Ok(Some(chunk))) => chunk,
1162                Ok(Ok(None)) => break,
1163                // Silence for a whole idle budget mid-stream: the server has stopped talking and
1164                // is not going to resume. This is a drop, not a slow reply.
1165                Err(_) => {
1166                    return Err(Error::Provider(ProviderFailure::Truncated {
1167                        message: format!(
1168                            "the endpoint sent nothing for {} s mid-reply",
1169                            self.idle.as_secs()
1170                        ),
1171                        streamed_chars: received,
1172                    }));
1173                }
1174                Ok(Err(e)) => {
1175                    // A connection that drops after the headers is a reply we were reading and
1176                    // did not finish — the same thing as a stream that stops early, and
1177                    // retryable on the same terms.
1178                    let message = if received == 0 {
1179                        format!("the connection dropped before the reply arrived: {e}")
1180                    } else {
1181                        format!("the connection dropped mid-reply: {e}")
1182                    };
1183                    return Err(Error::Provider(ProviderFailure::Truncated {
1184                        message,
1185                        streamed_chars: received,
1186                    }));
1187                }
1188            };
1189            received += chunk.len();
1190            for event in parser.push(&chunk) {
1191                acc.push_event(&event, on_delta)?;
1192            }
1193        }
1194        for event in parser.finish() {
1195            acc.push_event(&event, on_delta)?;
1196        }
1197        let usage_body = acc.usage_body();
1198        let msg = acc.finish()?;
1199        Ok((
1200            msg,
1201            TurnUsage::from_body(&usage_body, started.elapsed().as_millis() as u64),
1202        ))
1203    }
1204
1205    /// Only remember usage when the server actually said something: the status line shows
1206    /// `--` rather than a zero it would read as "this turn was free".
1207    fn note_usage(&self, usage: TurnUsage) {
1208        if usage.is_empty() {
1209            self.record_usage(TurnUsage {
1210                latency_ms: usage.latency_ms,
1211                ..Default::default()
1212            });
1213        } else {
1214            self.record_usage(usage);
1215        }
1216    }
1217}
1218
1219/// Which models an OpenAI-compatible server says it serves: `GET {base_url}/models`.
1220///
1221/// Written for `eclipse setup`, so it fails small and fast: the wizard wants "what can I
1222/// pick from?" and treats any failure as "ask the user to type a name". A server that
1223/// answers with something other than the OpenAI shape yields an empty list rather than an
1224/// error, because the endpoint exists but the answer is not usable either way.
1225pub async fn list_models(
1226    base_url: &str,
1227    api_key: Option<&str>,
1228    timeout: std::time::Duration,
1229) -> Result<Vec<String>> {
1230    let url = format!("{}/models", base_url.trim_end_matches('/'));
1231    let client = reqwest::Client::builder()
1232        .timeout(timeout)
1233        .build()
1234        .map_err(|e| Error::provider(format!("could not build an HTTP client: {e}")))?;
1235    let mut req = client.get(&url);
1236    if let Some(key) = api_key {
1237        req = req.bearer_auth(key);
1238    }
1239    let resp = req.send().await.map_err(|e| {
1240        Error::Provider(ProviderFailure::Transport {
1241            url: url.clone(),
1242            message: describe_transport(&e),
1243            sent: !e.is_connect(),
1244        })
1245    })?;
1246    let status = resp.status();
1247    let request_id = request_id(resp.headers());
1248    let text = resp.text().await.unwrap_or_default();
1249    if !status.is_success() {
1250        let failure = HttpFailure {
1251            status: status.as_u16(),
1252            body: text.chars().take(300).collect(),
1253            request_id,
1254            retry_after_secs: None,
1255            hint: None,
1256        };
1257        return Err(Error::Provider(
1258            if status.as_u16() == 401 || status.as_u16() == 403 {
1259                ProviderFailure::Unauthorized(failure)
1260            } else {
1261                ProviderFailure::Http(failure)
1262            },
1263        ));
1264    }
1265    let body: serde_json::Value = serde_json::from_str(&text).map_err(|e| {
1266        Error::Provider(ProviderFailure::Response {
1267            message: format!("{url} did not answer with JSON: {e}"),
1268            body: Some(text.chars().take(300).collect()),
1269        })
1270    })?;
1271    let mut out: Vec<String> = body
1272        .get("data")
1273        .and_then(serde_json::Value::as_array)
1274        .map(|rows| {
1275            rows.iter()
1276                .filter_map(|r| r.get("id").and_then(serde_json::Value::as_str))
1277                .map(str::to_string)
1278                .collect()
1279        })
1280        .unwrap_or_default();
1281    out.dedup();
1282    Ok(out)
1283}
1284
1285/// Read the context window the endpoint advertises **for one model**, in one of the dialects
1286/// it may speak. Returns `None` on any failure and never fabricates a number: callers fall
1287/// back to their own budget, then to "no budget".
1288///
1289/// The model id is not optional. An endpoint may serve several models with different windows
1290/// (llama-swap does, namespaced as `provider/model`), and picking the first row that happens
1291/// to carry a figure would report someone else's window — the one bug this signature exists
1292/// to prevent.
1293///
1294/// Three dialects, tried in order:
1295/// 1. `/props` at the root — llama.cpp's own `default_generation_settings.n_ctx`. A bare
1296///    `/props` describes the one model that server loaded, so when a single-model server
1297///    answers, its id is the one we asked about.
1298/// 2. `/props?model=<id>` — routers that expose per-model props. Best effort: llama-swap
1299///    answers `model not found` to the ids it lists, so this is a try, not a promise.
1300/// 3. `/models` — an entry carrying `context_length`, `context_window`, `max_model_len`,
1301///    `n_ctx` or `meta.n_ctx`. Matched by id: exact first, then a tolerant match on the last
1302///    path segment (`x` configured, `mmnuc/x` served) so one endpoint's namespacing is not a
1303///    reason to show nothing. Only when the list holds exactly **one** row and nothing
1304///    matched is that row used — with one candidate the row cannot be the wrong model.
1305///    A multi-row list with no match yields `None` (shown as "no budget"), because a wrong
1306///    window is worse than a missing one: a too-small figure would trim real conversation if
1307///    this ever feeds the loop's budget, and mislead the reader even while it does not.
1308pub async fn advertised_context_window(
1309    base_url: &str,
1310    api_key: Option<&str>,
1311    model: &str,
1312    timeout: std::time::Duration,
1313) -> Option<usize> {
1314    let base = base_url.trim_end_matches('/');
1315    let root = base.strip_suffix("/v1").unwrap_or(base);
1316    let client = reqwest::Client::builder().timeout(timeout).build().ok()?;
1317
1318    // 1 & 2: llama.cpp's props, bare and per-model.
1319    for url in [
1320        format!("{root}/props"),
1321        format!("{root}/props?model={}", encode_query(model)),
1322    ] {
1323        let mut req = client.get(url);
1324        if let Some(key) = api_key {
1325            req = req.bearer_auth(key);
1326        }
1327        let Ok(resp) = req.send().await else { continue };
1328        if !resp.status().is_success() {
1329            continue;
1330        }
1331        let Ok(body) = resp.json::<serde_json::Value>().await else {
1332            continue;
1333        };
1334        if let Some(n) = body
1335            .pointer("/default_generation_settings/n_ctx")
1336            .and_then(serde_json::Value::as_u64)
1337            .filter(|n| *n > 0)
1338        {
1339            return Some(n as usize);
1340        }
1341    }
1342
1343    // 3: the model list, matched by id.
1344    let mut req = client.get(format!("{base}/models"));
1345    if let Some(key) = api_key {
1346        req = req.bearer_auth(key);
1347    }
1348    let Ok(resp) = req.send().await else {
1349        return None;
1350    };
1351    if !resp.status().is_success() {
1352        return None;
1353    }
1354    let Ok(body) = resp.json::<serde_json::Value>().await else {
1355        return None;
1356    };
1357    let rows = body
1358        .get("data")
1359        .and_then(serde_json::Value::as_array)?
1360        .as_slice();
1361
1362    fn id_of(row: &serde_json::Value) -> &str {
1363        row.get("id")
1364            .and_then(serde_json::Value::as_str)
1365            .unwrap_or_default()
1366    }
1367    let figure_of = |row: &serde_json::Value| -> Option<usize> {
1368        for pointer in [
1369            "/context_length",
1370            "/context_window",
1371            "/max_model_len",
1372            "/n_ctx",
1373            "/meta/n_ctx",
1374        ] {
1375            if let Some(n) = row
1376                .pointer(pointer)
1377                .and_then(serde_json::Value::as_u64)
1378                .filter(|n| *n > 0)
1379            {
1380                return Some(n as usize);
1381            }
1382        }
1383        None
1384    };
1385
1386    if let Some(row) = rows.iter().find(|r| id_of(r) == model) {
1387        return figure_of(row);
1388    }
1389    if let Some(row) = rows.iter().find(|r| id_matches_loosely(id_of(r), model)) {
1390        return figure_of(row);
1391    }
1392    // One row and nothing matched: it is the only model there is.
1393    match rows {
1394        [only] => figure_of(only),
1395        _ => None,
1396    }
1397}
1398
1399/// `mmnuc/inkling-2-mini` against `inkling-2-mini` (and the reverse): the last path segment is
1400/// the model's own name, and a router's prefix is about which box serves it, not which model
1401/// it is. Nothing else is tolerated — a substring match would make `qwen-3.8-27b` answer for
1402/// `qwen-3.8-125b`.
1403fn id_matches_loosely(served: &str, configured: &str) -> bool {
1404    let tail = |s: &str| s.rsplit('/').next().unwrap_or(s).to_string();
1405    !served.is_empty() && !configured.is_empty() && tail(served) == tail(configured)
1406}
1407
1408/// Percent-encode what a model id may not carry in a query string. Ids are usually plain
1409/// names, but llama-swap namespaces them with `/`, which is not.
1410fn encode_query(s: &str) -> String {
1411    let mut out = String::with_capacity(s.len());
1412    for b in s.bytes() {
1413        match b {
1414            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
1415                out.push(b as char)
1416            }
1417            _ => out.push_str(&format!("%{b:02X}")),
1418        }
1419    }
1420    out
1421}
1422
1423#[cfg(test)]
1424mod tests {
1425    use super::*;
1426    use crate::tools::{ToolSpec, ToolSpecFunction};
1427    use std::sync::{Arc, Mutex};
1428    use tokio::io::{AsyncReadExt, AsyncWriteExt};
1429    use tokio::sync::Notify;
1430
1431    fn cfg(base: &str) -> ProviderConfig {
1432        ProviderConfig {
1433            base_url: base.into(),
1434            model: "m".into(),
1435            api_key: Some("k".into()),
1436            retry_base_delay_ms: 20,
1437            ..ProviderConfig::default()
1438        }
1439    }
1440
1441    /// A provider without patch support must refuse a non-empty patch: silently dropping it
1442    /// makes the model look irrational for a reason nothing records.
1443    #[tokio::test]
1444    async fn a_provider_that_cannot_patch_says_so_instead_of_dropping_it() {
1445        struct Plain;
1446        #[async_trait]
1447        impl ChatProvider for Plain {
1448            async fn chat(&self, _m: &[Message], _t: &[ToolSpec]) -> Result<Message> {
1449                Ok(Message::assistant("ok"))
1450            }
1451        }
1452        let patch = crate::hooks::RequestPatch {
1453            tool_choice: Some(crate::hooks::ToolChoice::Required),
1454            ..Default::default()
1455        };
1456        let err = Plain
1457            .chat_stream_patched(&[], &[], &|_| {}, &patch)
1458            .await
1459            .unwrap_err()
1460            .to_string();
1461        assert!(err.contains("cannot apply a request patch"), "{err}");
1462        assert!(
1463            err.contains("tool_choice"),
1464            "the error names what was set: {err}"
1465        );
1466
1467        // An empty patch is no patch: the plain path still works.
1468        let ok = Plain
1469            .chat_stream_patched(&[], &[], &|_| {}, &crate::hooks::RequestPatch::default())
1470            .await
1471            .unwrap();
1472        assert_eq!(ok.content.as_deref(), Some("ok"));
1473    }
1474
1475    #[test]
1476    fn requires_base_url_and_trims_slash() {
1477        assert!(OpenAiProvider::new(&ProviderConfig::default()).is_err());
1478        let p = OpenAiProvider::new(&cfg("http://h/v1/")).unwrap();
1479        assert_eq!(p.url, "http://h/v1/chat/completions");
1480    }
1481
1482    #[test]
1483    fn reasoning_is_round_tripped_only_when_the_profile_wants_it() {
1484        let mut m = Message::assistant("done");
1485        m.reasoning = Some("thinking".into());
1486        let openai = OpenAiProvider::new(&cfg("http://h/v1")).unwrap();
1487        assert_eq!(
1488            openai.request_body(&[m.clone()], &[])["messages"][0]["reasoning_content"],
1489            json!("thinking")
1490        );
1491        let mut c = cfg("http://h/v1");
1492        c.profile = Some("llamacpp".into());
1493        let local = OpenAiProvider::new(&c).unwrap();
1494        let body = local.request_body(&[m], &[]);
1495        assert!(
1496            body["messages"][0].get("reasoning_content").is_none(),
1497            "a backend that did not ask for it must not see it: {body}"
1498        );
1499    }
1500
1501    /// Reasoning belongs to the turn that produced it. Once the user has spoken again, that
1502    /// thinking is text the model already spent and acted on — re-sending it charges every later
1503    /// request for a decision that has been made, and a long session pays for all of them.
1504    #[test]
1505    fn reasoning_stops_at_the_end_of_its_turn() {
1506        let p = OpenAiProvider::new(&cfg("http://h/v1")).unwrap();
1507
1508        let mut first = Message::assistant("worked on the old thing");
1509        first.reasoning = Some("old thinking".into());
1510        let mut second = Message::assistant("tool call in the live turn");
1511        second.reasoning = Some("live thinking".into());
1512
1513        let history = [
1514            Message::user("do the old thing"),
1515            first,
1516            Message::tool_result("c1", "ok"),
1517            Message::user("now do the new thing"),
1518            second,
1519        ];
1520        let body = p.request_body(&history, &[]);
1521        let msgs = body["messages"].as_array().unwrap();
1522
1523        assert!(
1524            msgs[1].get("reasoning_content").is_none(),
1525            "the finished turn's thinking is not sent again: {body}"
1526        );
1527        assert_eq!(
1528            msgs[4]["reasoning_content"],
1529            json!("live thinking"),
1530            "the turn in progress still carries its own plan: {body}"
1531        );
1532    }
1533
1534    #[test]
1535    fn request_body_shape() {
1536        let p = OpenAiProvider::new(&cfg("http://h/v1")).unwrap();
1537        let b = p.request_body(&[Message::user("hi")], &[]);
1538        assert_eq!(b["model"], "m");
1539        assert_eq!(b["messages"][0]["role"], "user");
1540        assert!(b.get("tools").is_none());
1541    }
1542
1543    #[test]
1544    fn temperature_is_sent_without_float_noise() {
1545        let mut c = cfg("http://h/v1");
1546        c.temperature = Some(0.7);
1547        let p = OpenAiProvider::new(&c).unwrap();
1548        let b = p.request_body(&[Message::user("hi")], &[]);
1549        assert_eq!(b["temperature"].to_string(), "0.7");
1550    }
1551
1552    #[test]
1553    fn parses_text_and_tool_call_replies() {
1554        let m =
1555            parse_response(&json!({"choices":[{"message":{"role":"assistant","content":"yo"}}]}))
1556                .unwrap();
1557        assert_eq!(m.content.as_deref(), Some("yo"));
1558        let m = parse_response(&json!({"choices":[{"message":{"role":"assistant","content":null,
1559            "tool_calls":[{"id":"","type":"function","function":{"name":"shell","arguments":"{}"}}]}}]}))
1560        .unwrap();
1561        assert_eq!(m.tool_calls[0].function.name, "shell");
1562        assert_eq!(m.tool_calls[0].id, "call_0");
1563        assert!(parse_response(&json!({"error":"x"})).is_err());
1564    }
1565
1566    /// Reads one HTTP request (headers plus any content-length body) off `s`.
1567    async fn read_request(s: &mut tokio::net::TcpStream) -> String {
1568        let mut buf = Vec::new();
1569        loop {
1570            let mut chunk = [0u8; 4096];
1571            let n = s.read(&mut chunk).await.unwrap();
1572            buf.extend_from_slice(&chunk[..n]);
1573            let text = String::from_utf8_lossy(&buf).to_string();
1574            if let Some(idx) = text.find("\r\n\r\n") {
1575                let len = text[..idx]
1576                    .to_lowercase()
1577                    .lines()
1578                    .find_map(|l| {
1579                        l.strip_prefix("content-length: ")
1580                            .map(|v| v.trim().parse::<usize>().unwrap())
1581                    })
1582                    .unwrap_or(0);
1583                if buf.len() >= idx + 4 + len {
1584                    break;
1585                }
1586            }
1587            if n == 0 {
1588                break;
1589            }
1590        }
1591        String::from_utf8_lossy(&buf).to_string()
1592    }
1593
1594    /// One-shot HTTP server: returns the raw request it received.
1595    async fn serve_once(status: &str, body: &str) -> (String, tokio::task::JoinHandle<String>) {
1596        serve_once_typed(status, "application/json", body).await
1597    }
1598
1599    /// Answers with headers announcing a body, then never sends it: a proxy mid-shutdown, or a
1600    /// server whose backend died after the status line. The connection stays open on purpose.
1601    async fn serve_headers_then_stall(status: &str) -> (String, tokio::task::JoinHandle<()>) {
1602        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1603        let base = format!("http://{}/v1", listener.local_addr().unwrap());
1604        let response = format!(
1605            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: 4096\r\nconnection: close\r\n\r\n"
1606        );
1607        let h = tokio::spawn(async move {
1608            let Ok((mut s, _)) = listener.accept().await else {
1609                return;
1610            };
1611            let _ = read_request(&mut s).await;
1612            let _ = s.write_all(response.as_bytes()).await;
1613            let _ = s.flush().await;
1614            // Hold the socket open with no body: the read has nothing to time out on unless the
1615            // caller brought its own budget.
1616            tokio::time::sleep(Duration::from_secs(60)).await;
1617        });
1618        (base, h)
1619    }
1620
1621    async fn serve_once_typed(
1622        status: &str,
1623        content_type: &str,
1624        body: &str,
1625    ) -> (String, tokio::task::JoinHandle<String>) {
1626        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1627        let base = format!("http://{}/v1", listener.local_addr().unwrap());
1628        let response = format!(
1629            "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
1630            body.len()
1631        );
1632        let h = tokio::spawn(async move {
1633            let (mut s, _) = listener.accept().await.unwrap();
1634            let req = read_request(&mut s).await;
1635            s.write_all(response.as_bytes()).await.unwrap();
1636            req
1637        });
1638        (base, h)
1639    }
1640
1641    /// SSE server whose first connection carries `first` and closes (a cut stream), and whose
1642    /// second connection answers normally. Counts the connections it served.
1643    async fn serve_sse_cut_then_ok(
1644        first: &'static str,
1645    ) -> (String, tokio::task::JoinHandle<usize>) {
1646        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1647        let base = format!("http://{}/v1", listener.local_addr().unwrap());
1648        let h = tokio::spawn(async move {
1649            let mut seen = 0;
1650            for attempt in 0..2 {
1651                let Ok(Ok((mut s, _))) =
1652                    tokio::time::timeout(Duration::from_millis(700), listener.accept()).await
1653                else {
1654                    break;
1655                };
1656                let _ = read_request(&mut s).await;
1657                seen += 1;
1658                let body = if attempt == 0 {
1659                    first.to_string()
1660                } else {
1661                    "data: {\"choices\":[{\"delta\":{\"content\":\"whole\"},\"finish_reason\":\"stop\"}]}\n\n\
1662                     data: [DONE]\n\n"
1663                        .to_string()
1664                };
1665                let _ = s
1666                    .write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n")
1667                    .await;
1668                let _ = s.write_all(body.as_bytes()).await;
1669                let _ = s.flush().await;
1670                drop(s);
1671                tokio::time::sleep(Duration::from_millis(20)).await;
1672            }
1673            seen
1674        });
1675        (base, h)
1676    }
1677
1678    /// Streaming server that keeps talking: `n` token events, `gap_ms` apart, then `[DONE]`.
1679    /// A reply that takes far longer than the idle budget, one short wait at a time.
1680    async fn serve_sse_trickle(n: usize, gap_ms: u64) -> (String, tokio::task::JoinHandle<()>) {
1681        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1682        let base = format!("http://{}/v1", listener.local_addr().unwrap());
1683        let h = tokio::spawn(async move {
1684            let (mut s, _) = listener.accept().await.unwrap();
1685            let _ = read_request(&mut s).await;
1686            s.write_all(
1687                b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n",
1688            )
1689            .await
1690            .unwrap();
1691            for i in 0..n {
1692                let ev = format!(
1693                    "data: {{\"choices\":[{{\"delta\":{{\"content\":\"t{i} \"}} ,\"index\":0}}]}}\n\n"
1694                );
1695                s.write_all(ev.as_bytes()).await.unwrap();
1696                s.flush().await.unwrap();
1697                tokio::time::sleep(Duration::from_millis(gap_ms)).await;
1698            }
1699            let _ = s.write_all(b"data: [DONE]\n\n").await;
1700            let _ = s.flush().await;
1701        });
1702        (base, h)
1703    }
1704
1705    /// Streaming server that says one thing and then goes quiet without closing: exactly what a
1706    /// wedged endpoint looks like from the client's side.
1707    async fn serve_sse_then_silence(silence: Duration) -> (String, tokio::task::JoinHandle<()>) {
1708        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1709        let base = format!("http://{}/v1", listener.local_addr().unwrap());
1710        let h = tokio::spawn(async move {
1711            let (mut s, _) = listener.accept().await.unwrap();
1712            let _ = read_request(&mut s).await;
1713            s.write_all(
1714                b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n",
1715            )
1716            .await
1717            .unwrap();
1718            s.write_all(
1719                b"data: {\"choices\":[{\"delta\":{\"content\":\"half\"},\"index\":0}]}\n\n",
1720            )
1721            .await
1722            .unwrap();
1723            s.flush().await.unwrap();
1724            tokio::time::sleep(silence).await;
1725        });
1726        (base, h)
1727    }
1728
1729    /// The bug a 120 s total timeout on the client caused: a local model that thinks for two
1730    /// minutes at ~100 tokens/s produces 12 000 tokens and was guillotined one token from the
1731    /// end, with an error that blamed the server ("the connection dropped mid-reply"). A reply
1732    /// that keeps arriving is not a reply that has hung: the budget is *silence*, not elapsed.
1733    #[tokio::test]
1734    async fn a_reply_that_keeps_arriving_outlives_the_timeout_it_started_under() {
1735        // One second of budget; four seconds of reply, 200 ms at a time, through the streaming
1736        // path the TUI and the dashboard both use.
1737        let (base, h) = serve_sse_trickle(20, 200).await;
1738        let mut c = cfg(&base);
1739        c.timeout_secs = 1;
1740        let p = OpenAiProvider::new(&c).unwrap();
1741        let reply = p
1742            .chat_stream_patched(
1743                &[Message::user("think for a while")],
1744                &[],
1745                &|_: crate::stream::Delta| {},
1746                &crate::hooks::RequestPatch::default(),
1747            )
1748            .await
1749            .unwrap();
1750        let text = reply.content.unwrap_or_default();
1751        assert!(text.contains("t19"), "the last token arrived: {text:?}");
1752        assert_eq!(text.matches('t').count(), 20);
1753        h.await.ok();
1754    }
1755
1756    /// The same rule at the other door: a server that ignores `stream: true` answers with one
1757    /// ordinary body, and that body is read in chunks under the same idle budget. Reading it with
1758    /// one `timeout` over `resp.text()` would cap the reply's length in seconds again.
1759    #[tokio::test]
1760    async fn a_whole_body_that_keeps_arriving_is_read_past_the_budget_too() {
1761        let (base, h) = serve_sse_trickle(20, 200).await;
1762        let mut c = cfg(&base);
1763        c.timeout_secs = 1;
1764        let p = OpenAiProvider::new(&c).unwrap();
1765        // `chat` is the non-streaming entry point: it reads the body as JSON, and the trickle
1766        // server's body is not JSON — so the assertion is on *which* error comes back. A budget
1767        // applied to elapsed time would say "sent nothing for 1 s"; a body read correctly gets to
1768        // parse it and complains about the content instead.
1769        let err = p
1770            .chat(&[Message::user("hi")], &[])
1771            .await
1772            .expect_err("trickled SSE is not JSON");
1773        let text = err.to_string();
1774        assert!(!text.contains("sent nothing"), "read to the end: {text}");
1775        h.await.ok();
1776    }
1777
1778    /// The failing half of the same door. An endpoint that answers `503` and then stalls the body
1779    /// used to wedge the run here for ever: `send()`'s budget ends at the headers, and the error
1780    /// body was read with no ceiling. It is now bounded by the same `idle` budget, and an
1781    /// unreadable body is an empty one — the status is the finding either way.
1782    #[tokio::test]
1783    async fn a_failed_attempt_whose_body_stalls_is_bounded_by_the_idle_budget() {
1784        let (base, h) = serve_headers_then_stall("503 Service Unavailable").await;
1785        let mut c = cfg(&base);
1786        c.timeout_secs = 1;
1787        c.max_retries = 0;
1788        let p = OpenAiProvider::new(&c).unwrap();
1789        let err =
1790            tokio::time::timeout(Duration::from_secs(15), p.chat(&[Message::user("hi")], &[]))
1791                .await
1792                .expect("the body read is bounded: without the fix this never returns")
1793                .expect_err("503 is a failure");
1794        let text = err.to_string();
1795        assert!(
1796            text.contains("503"),
1797            "the status survives an unreadable body: {text}"
1798        );
1799        h.abort();
1800    }
1801
1802    /// The other half of the rule: silence past the budget is a real drop, and the message has to
1803    /// say which rule was broken — an idle budget, not a dropped socket.
1804    #[tokio::test]
1805    async fn a_stream_that_goes_silent_mid_reply_names_the_silence() {
1806        let (base, h) = serve_sse_then_silence(Duration::from_secs(3)).await;
1807        let mut c = cfg(&base);
1808        c.timeout_secs = 1;
1809        c.max_retries = 0;
1810        let p = OpenAiProvider::new(&c).unwrap();
1811        let err = p
1812            .chat(&[Message::user("go quiet")], &[])
1813            .await
1814            .expect_err("silence must not be reported as a finished reply");
1815        let text = err.to_string();
1816        assert!(text.contains("sent nothing for 1 s"), "{text}");
1817        h.abort();
1818    }
1819
1820    /// Streaming server: sends `first`, holds `rest` back until `gate` is notified, then
1821    /// closes the connection (body delimited by close, like many SSE servers).
1822    async fn serve_sse(
1823        first: &'static str,
1824        gate: Arc<Notify>,
1825        rest: &'static str,
1826    ) -> (String, tokio::task::JoinHandle<String>) {
1827        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1828        let base = format!("http://{}/v1", listener.local_addr().unwrap());
1829        let h = tokio::spawn(async move {
1830            let (mut s, _) = listener.accept().await.unwrap();
1831            let req = read_request(&mut s).await;
1832            s.write_all(
1833                b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n",
1834            )
1835            .await
1836            .unwrap();
1837            s.write_all(first.as_bytes()).await.unwrap();
1838            s.flush().await.unwrap();
1839            gate.notified().await;
1840            s.write_all(rest.as_bytes()).await.unwrap();
1841            req
1842        });
1843        (base, h)
1844    }
1845
1846    #[tokio::test]
1847    async fn chat_posts_to_configured_endpoint_with_bearer_key() {
1848        let (base, h) = serve_once(
1849            "200 OK",
1850            r#"{"choices":[{"message":{"role":"assistant","content":"pong"}}]}"#,
1851        )
1852        .await;
1853        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
1854        let reply = p.chat(&[Message::user("ping")], &[]).await.unwrap();
1855        assert_eq!(reply.content.as_deref(), Some("pong"));
1856        let req = h.await.unwrap().to_lowercase();
1857        assert!(req.starts_with("post /v1/chat/completions"), "{req}");
1858        assert!(req.contains("authorization: bearer k"));
1859        assert!(req.contains("\"ping\""));
1860    }
1861
1862    #[tokio::test]
1863    async fn chat_surfaces_http_errors() {
1864        let (base, _h) = serve_once("401 Unauthorized", r#"{"error":"bad key"}"#).await;
1865        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
1866        let err = p
1867            .chat(&[Message::user("x")], &[])
1868            .await
1869            .unwrap_err()
1870            .to_string();
1871        assert!(err.contains("401") && err.contains("bad key"), "{err}");
1872    }
1873
1874    #[tokio::test]
1875    async fn stream_delivers_deltas_before_the_reply_is_complete() {
1876        let gate = Arc::new(Notify::new());
1877        let (base, h) = serve_sse(
1878            "data: {\"choices\":[{\"delta\":{\"content\":\"Hel\"}}]}\n\n\
1879             data: {\"choices\":[{\"delta\":{\"content\":\"lo\"}}]}\n\nda",
1880            gate.clone(),
1881            "ta: {\"choices\":[{\"delta\":{\"content\":\"!\"},\"finish_reason\":\"stop\"}]}\n\n\
1882             data: [DONE]\n\n",
1883        )
1884        .await;
1885        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
1886        let seen = Mutex::new(Vec::<String>::new());
1887        // Releases the rest of the body only once two deltas have been observed, so a
1888        // provider that buffered the whole response would hang until the timeout.
1889        let sink = |d: crate::stream::Delta| {
1890            if let crate::stream::Delta::Text(t) = d {
1891                let mut seen = seen.lock().unwrap();
1892                seen.push(t);
1893                if seen.len() == 2 {
1894                    gate.notify_one();
1895                }
1896            }
1897        };
1898        let reply = tokio::time::timeout(
1899            Duration::from_secs(5),
1900            p.chat_stream(&[Message::user("hi")], &[], &sink),
1901        )
1902        .await
1903        .expect("stream was not delivered incrementally")
1904        .unwrap();
1905        assert_eq!(*seen.lock().unwrap(), ["Hel", "lo", "!"]);
1906        assert_eq!(reply.content.as_deref(), Some("Hello!"));
1907        let req = h.await.unwrap();
1908        assert!(req.contains("\"stream\":true"), "{req}");
1909    }
1910
1911    #[tokio::test]
1912    async fn stream_assembles_tool_calls() {
1913        let gate = Arc::new(Notify::new());
1914        gate.notify_one();
1915        let (base, _h) = serve_sse(
1916            "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"c1\",\"function\":{\"name\":\"shell\",\"arguments\":\"{\\\"command\\\"\"}}]}}]}\n\n",
1917            gate,
1918            "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\":\\\"ls\\\"}\"}}]},\"finish_reason\":\"tool_calls\"}]}\n\n",
1919        )
1920        .await;
1921        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
1922        let reply = p
1923            .chat_stream(&[Message::user("x")], &[], &|_| {})
1924            .await
1925            .unwrap();
1926        assert_eq!(reply.tool_calls[0].id, "c1");
1927        assert_eq!(
1928            reply.tool_calls[0].function.arguments,
1929            r#"{"command":"ls"}"#
1930        );
1931    }
1932
1933    #[tokio::test]
1934    async fn stream_cut_short_is_an_error_not_a_reply() {
1935        let gate = Arc::new(Notify::new());
1936        gate.notify_one();
1937        let (base, _h) = serve_sse(
1938            "data: {\"choices\":[{\"delta\":{\"content\":\"half\"}}]}\n\n",
1939            gate,
1940            "",
1941        )
1942        .await;
1943        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
1944        let err = p
1945            .chat_stream(&[Message::user("x")], &[], &|_| {})
1946            .await
1947            .unwrap_err()
1948            .to_string();
1949        assert!(err.contains("before the model finished"), "{err}");
1950    }
1951
1952    #[tokio::test]
1953    async fn stream_falls_back_to_plain_json_replies() {
1954        let (base, h) = serve_once(
1955            "200 OK",
1956            r#"{"choices":[{"message":{"role":"assistant","content":"whole"}}]}"#,
1957        )
1958        .await;
1959        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
1960        let deltas = Mutex::new(0);
1961        let reply = p
1962            .chat_stream(&[Message::user("x")], &[], &|_| {
1963                *deltas.lock().unwrap() += 1
1964            })
1965            .await
1966            .unwrap();
1967        assert_eq!(reply.content.as_deref(), Some("whole"));
1968        assert_eq!(*deltas.lock().unwrap(), 0);
1969        assert!(h.await.unwrap().contains("\"stream\":true"));
1970    }
1971
1972    #[tokio::test]
1973    async fn streaming_can_be_disabled_and_errors_still_surface() {
1974        let mut c = cfg("http://unused/v1");
1975        c.stream = false;
1976        let (base, h) = serve_once(
1977            "200 OK",
1978            r#"{"choices":[{"message":{"role":"assistant","content":"plain"}}]}"#,
1979        )
1980        .await;
1981        c.base_url = base;
1982        let p = OpenAiProvider::new(&c).unwrap();
1983        let reply = p
1984            .chat_stream(&[Message::user("x")], &[], &|_| {})
1985            .await
1986            .unwrap();
1987        assert_eq!(reply.content.as_deref(), Some("plain"));
1988        assert!(!h.await.unwrap().contains("\"stream\""));
1989
1990        let (base, _h) = serve_once("500 Internal Server Error", "boom").await;
1991        let mut c = cfg(&base);
1992        c.max_retries = 0;
1993        let p = OpenAiProvider::new(&c).unwrap();
1994        let err = p
1995            .chat_stream(&[Message::user("x")], &[], &|_| {})
1996            .await
1997            .unwrap_err()
1998            .to_string();
1999        assert!(err.contains("500") && err.contains("boom"), "{err}");
2000    }
2001
2002    /// Serves one canned `(status, extra headers, body)` per connection, in order, and
2003    /// returns how many requests it saw.
2004    async fn serve_script(
2005        script: Vec<(&'static str, &'static str, &'static str)>,
2006    ) -> (String, tokio::task::JoinHandle<usize>) {
2007        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2008        let base = format!("http://{}/v1", listener.local_addr().unwrap());
2009        let h = tokio::spawn(async move {
2010            let mut seen = 0;
2011            for (status, headers, body) in script {
2012                let accepted = tokio::time::timeout(Duration::from_millis(500), listener.accept());
2013                let Ok(Ok((mut s, _))) = accepted.await else {
2014                    break;
2015                };
2016                read_request(&mut s).await;
2017                seen += 1;
2018                let resp = format!(
2019                    "HTTP/1.1 {status}\r\ncontent-type: application/json\r\n{headers}content-length: {}\r\nconnection: close\r\n\r\n{body}",
2020                    body.len()
2021                );
2022                s.write_all(resp.as_bytes()).await.unwrap();
2023            }
2024            seen
2025        });
2026        (base, h)
2027    }
2028
2029    const OK_BODY: &str = r#"{"choices":[{"message":{"role":"assistant","content":"ok"}}]}"#;
2030
2031    #[test]
2032    fn backoff_doubles_from_the_base() {
2033        let base = Duration::from_secs(2);
2034        let waits: Vec<_> = (1..=3).map(|n| backoff_delay(base, n).as_secs()).collect();
2035        assert_eq!(waits, [2, 4, 8]);
2036        assert!(crate::error::is_retryable_status(429));
2037        assert!(crate::error::is_retryable_status(502));
2038        for s in [400, 401, 403, 404, 422] {
2039            assert!(!crate::error::is_retryable_status(s));
2040        }
2041        assert_eq!(ProviderConfig::default().max_retries, 3);
2042        assert_eq!(ProviderConfig::default().retry_base_delay_ms, 2000);
2043    }
2044
2045    #[tokio::test]
2046    async fn retries_429_and_5xx_then_succeeds_with_backoff() {
2047        let (base, server) = serve_script(vec![
2048            ("429 Too Many Requests", "", "slow down"),
2049            ("503 Service Unavailable", "", "busy"),
2050            ("200 OK", "", OK_BODY),
2051        ])
2052        .await;
2053        let mut c = cfg(&base);
2054        c.retry_base_delay_ms = 60;
2055        let p = OpenAiProvider::new(&c).unwrap();
2056        let start = std::time::Instant::now();
2057        let reply = p.chat(&[Message::user("x")], &[]).await.unwrap();
2058        assert_eq!(reply.content.as_deref(), Some("ok"));
2059        assert_eq!(server.await.unwrap(), 3);
2060        assert!(
2061            start.elapsed() >= Duration::from_millis(60 + 120),
2062            "waited only {:?}",
2063            start.elapsed()
2064        );
2065    }
2066
2067    #[tokio::test]
2068    async fn gives_up_after_max_retries_and_reports_it() {
2069        let (base, server) = serve_script(vec![
2070            ("500 Internal Server Error", "", "e1"),
2071            ("500 Internal Server Error", "", "e2"),
2072            ("500 Internal Server Error", "", "e3"),
2073            ("502 Bad Gateway", "", "last"),
2074            ("200 OK", "", OK_BODY),
2075        ])
2076        .await;
2077        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
2078        let err = p
2079            .chat(&[Message::user("x")], &[])
2080            .await
2081            .unwrap_err()
2082            .to_string();
2083        assert!(
2084            err.contains("502") && err.contains("last") && err.contains("4 attempts"),
2085            "{err}"
2086        );
2087        assert_eq!(server.await.unwrap(), 4, "1 try + 3 retries, no more");
2088    }
2089
2090    #[tokio::test]
2091    async fn other_4xx_are_not_retried() {
2092        for status in ["400 Bad Request", "401 Unauthorized", "404 Not Found"] {
2093            let (base, server) =
2094                serve_script(vec![(status, "", "no"), ("200 OK", "", OK_BODY)]).await;
2095            let p = OpenAiProvider::new(&cfg(&base)).unwrap();
2096            let err = p
2097                .chat(&[Message::user("x")], &[])
2098                .await
2099                .unwrap_err()
2100                .to_string();
2101            assert!(
2102                err.contains(&status[..3]) && !err.contains("gave up"),
2103                "{err}"
2104            );
2105            assert_eq!(server.await.unwrap(), 1, "{status}");
2106        }
2107    }
2108
2109    #[tokio::test]
2110    async fn retries_can_be_disabled_and_retry_after_is_honoured() {
2111        let (base, server) = serve_script(vec![
2112            ("503 Service Unavailable", "", "down"),
2113            ("200 OK", "", OK_BODY),
2114        ])
2115        .await;
2116        let mut c = cfg(&base);
2117        c.max_retries = 0;
2118        let err = OpenAiProvider::new(&c)
2119            .unwrap()
2120            .chat(&[Message::user("x")], &[])
2121            .await
2122            .unwrap_err()
2123            .to_string();
2124        assert!(err.contains("503") && !err.contains("gave up"), "{err}");
2125        assert_eq!(server.await.unwrap(), 1);
2126
2127        // `Retry-After: 0` replaces the (here huge) computed backoff.
2128        let (base, server) = serve_script(vec![
2129            ("429 Too Many Requests", "retry-after: 0\r\n", "wait"),
2130            ("200 OK", "", OK_BODY),
2131        ])
2132        .await;
2133        let mut c = cfg(&base);
2134        c.retry_base_delay_ms = 600_000;
2135        let reply = tokio::time::timeout(
2136            Duration::from_secs(5),
2137            OpenAiProvider::new(&c)
2138                .unwrap()
2139                .chat(&[Message::user("x")], &[]),
2140        )
2141        .await
2142        .expect("Retry-After was ignored")
2143        .unwrap();
2144        assert_eq!(reply.content.as_deref(), Some("ok"));
2145        assert_eq!(server.await.unwrap(), 2);
2146
2147        // A Retry-After beyond the cap is a final failure, not a long sleep.
2148        let (base, server) = serve_script(vec![(
2149            "429 Too Many Requests",
2150            "retry-after: 3600\r\n",
2151            "later",
2152        )])
2153        .await;
2154        let err = OpenAiProvider::new(&cfg(&base))
2155            .unwrap()
2156            .chat(&[Message::user("x")], &[])
2157            .await
2158            .unwrap_err()
2159            .to_string();
2160        assert!(err.contains("429") && err.contains("later"), "{err}");
2161        assert_eq!(server.await.unwrap(), 1, "a Retry-After of an hour is a no");
2162    }
2163
2164    #[tokio::test]
2165    async fn streaming_requests_are_retried_before_the_stream_starts() {
2166        let (base, server) = serve_script(vec![
2167            ("503 Service Unavailable", "", "busy"),
2168            ("200 OK", "", OK_BODY),
2169        ])
2170        .await;
2171        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
2172        let reply = p
2173            .chat_stream(&[Message::user("x")], &[], &|_| {})
2174            .await
2175            .unwrap();
2176        assert_eq!(reply.content.as_deref(), Some("ok"));
2177        assert_eq!(server.await.unwrap(), 2);
2178    }
2179
2180    /// Accepts the first connection, reads the request and closes without answering — what a
2181    /// reset or a crashed proxy looks like — then serves one good reply.
2182    async fn serve_drop_then_ok() -> (String, tokio::task::JoinHandle<usize>) {
2183        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2184        let base = format!("http://{}/v1", listener.local_addr().unwrap());
2185        let h = tokio::spawn(async move {
2186            let mut seen = 0;
2187            if let Ok(Ok((mut s, _))) =
2188                tokio::time::timeout(Duration::from_millis(500), listener.accept()).await
2189            {
2190                read_request(&mut s).await;
2191                seen += 1;
2192                drop(s); // nothing written: the client sees the connection go away
2193                tokio::time::sleep(Duration::from_millis(20)).await;
2194            }
2195            if let Ok(Ok((mut s, _))) =
2196                tokio::time::timeout(Duration::from_millis(500), listener.accept()).await
2197            {
2198                read_request(&mut s).await;
2199                seen += 1;
2200                let resp = format!(
2201                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{OK_BODY}",
2202                    OK_BODY.len()
2203                );
2204                let _ = s.write_all(resp.as_bytes()).await;
2205            }
2206            seen
2207        });
2208        (base, h)
2209    }
2210
2211    /// The connection drops *after* the request body went out. `/chat/completions` is billed and not
2212    /// idempotent, so repeating it may pay for the same generation twice — off by default, and the
2213    /// failure says which knob turns it on rather than leaving the operator to guess.
2214    #[tokio::test]
2215    async fn a_drop_after_the_request_went_out_is_not_repeated_by_default() {
2216        let (base, server) = serve_drop_then_ok().await;
2217        let failed = OpenAiProvider::new(&cfg(&base))
2218            .unwrap()
2219            .chat(&[Message::user("x")], &[])
2220            .await
2221            .expect_err("a drop after the send is not repeated unless the config says so");
2222        let failure = failed.provider_failure().expect("a provider failure");
2223        assert!(
2224            failure.after_send(),
2225            "the failure knows the request had gone out: {failure}"
2226        );
2227        assert_eq!(
2228            server.await.unwrap(),
2229            1,
2230            "exactly one request reached the server"
2231        );
2232    }
2233
2234    /// The same drop, with the cost accepted on purpose: `retry_after_send = true` buys the retry.
2235    #[tokio::test]
2236    async fn a_drop_after_the_send_is_repeated_when_the_config_allows_it() {
2237        let (base, server) = serve_drop_then_ok().await;
2238        let mut c = cfg(&base);
2239        c.retry_after_send = true;
2240        let reply = OpenAiProvider::new(&c)
2241            .unwrap()
2242            .chat(&[Message::user("x")], &[])
2243            .await
2244            .expect("the config allows repeating a request that was already sent");
2245        assert_eq!(reply.content.as_deref(), Some("ok"));
2246        assert_eq!(server.await.unwrap(), 2, "the drop was repeated as asked");
2247    }
2248
2249    #[tokio::test]
2250    async fn a_server_that_is_never_there_gives_up_and_says_how_many_attempts_it_spent() {
2251        // Nothing listens here: every attempt fails to connect, and the retries are finite.
2252        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2253        let base = format!("http://{}/v1", listener.local_addr().unwrap());
2254        drop(listener);
2255        let mut c = cfg(&base);
2256        c.max_retries = 1;
2257        c.retry_base_delay_ms = 1;
2258        let err = OpenAiProvider::new(&c)
2259            .unwrap()
2260            .chat(&[Message::user("x")], &[])
2261            .await
2262            .unwrap_err()
2263            .to_string();
2264        assert!(err.contains("could not reach"), "{err}");
2265        assert!(err.contains("connection could not be established"), "{err}");
2266        assert!(err.contains("2 attempts"), "it says what it spent: {err}");
2267    }
2268
2269    #[tokio::test]
2270    async fn retries_can_be_turned_off_entirely() {
2271        let (base, server) = serve_script(vec![
2272            ("503 Service Unavailable", "", "busy"),
2273            ("200 OK", "", OK_BODY),
2274        ])
2275        .await;
2276        let mut c = cfg(&base);
2277        c.max_retries = 0;
2278        let err = OpenAiProvider::new(&c)
2279            .unwrap()
2280            .chat(&[Message::user("x")], &[])
2281            .await
2282            .unwrap_err()
2283            .to_string();
2284        assert!(err.contains("503"), "{err}");
2285        assert_eq!(server.await.unwrap(), 1, "max_retries = 0 means one try");
2286    }
2287
2288    #[test]
2289    fn the_default_profile_sends_tools_and_usage_the_openai_way() {
2290        let p = OpenAiProvider::new(&cfg("http://h/v1")).unwrap();
2291        assert_eq!(p.profile_name(), "openai");
2292        let tools = vec![ToolSpec {
2293            kind: "function",
2294            function: ToolSpecFunction {
2295                name: "t".into(),
2296                description: "d".into(),
2297                parameters: json!({"type": "object"}),
2298            },
2299        }];
2300        let body = p.request_body(&[Message::user("hi")], &tools);
2301        assert_eq!(body["tool_choice"], "auto");
2302        assert!(
2303            body.get("stream_options").is_none(),
2304            "only sent when streaming"
2305        );
2306        assert!(body.get("max_tokens").is_none(), "no cap unless configured");
2307    }
2308
2309    #[test]
2310    fn the_llamacpp_profile_keeps_tools_but_drops_tool_choice() {
2311        let mut c = cfg("http://h/v1");
2312        c.profile = Some("llamacpp".into());
2313        let p = OpenAiProvider::new(&c).unwrap();
2314        let tools = vec![ToolSpec {
2315            kind: "function",
2316            function: ToolSpecFunction {
2317                name: "t".into(),
2318                description: "d".into(),
2319                parameters: json!({"type": "object"}),
2320            },
2321        }];
2322        let body = p.request_body(&[Message::user("hi")], &tools);
2323        assert!(body.get("tools").is_some());
2324        assert!(body.get("tool_choice").is_none());
2325    }
2326
2327    /// The two shipped manifests, as files — not a copy of what they are believed to say. `#245`:
2328    /// a profile that ships has to be the thing the tests run against, or the manifest is untested
2329    /// prose.
2330    fn shipped(name: &str) -> ProviderProfile {
2331        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2332            .join("../../plugins")
2333            .join(name)
2334            .join("plugin.toml");
2335        let text = std::fs::read_to_string(&path)
2336            .unwrap_or_else(|e| panic!("{} is not readable: {e}", path.display()));
2337        let manifest: crate::plugins::Manifest = toml::from_str(&text)
2338            .unwrap_or_else(|e| panic!("{} does not parse: {e}", path.display()));
2339        let def = manifest
2340            .provider_profiles
2341            .first()
2342            .unwrap_or_else(|| panic!("{} declares no profile", path.display()));
2343        crate::plugins::profile_from_def(def)
2344    }
2345
2346    fn shipped_effort(name: &str, model: &str, asked: Option<&str>) -> serde_json::Value {
2347        let plugin = shipped(name);
2348        let profile_name = plugin.name.clone();
2349        let mut c = cfg("http://h/v1");
2350        c.profile = Some(profile_name);
2351        c.model = model.into();
2352        let dial = std::sync::Arc::new(crate::reasoning::Dial::new(asked.map(str::to_string)));
2353        let p = OpenAiProvider::with_dial(&c, &[plugin], Some(dial)).unwrap();
2354        let body = p.request_body(&[Message::user("hi")], &[]);
2355        body.get("reasoning_effort").cloned().unwrap_or(json!(null))
2356    }
2357
2358    /// `#245` done-when: the exact body for `xhigh`, `minimal`, `none` and nothing-set, on each of
2359    /// the two profiles that ship. Read from `plugins/`, so a manifest edit that breaks the mapping
2360    /// fails here instead of in somebody's session.
2361    #[test]
2362    fn the_shipped_profiles_send_exactly_what_they_promise() {
2363        // llamacpp: three rungs, `xhigh` mapped down to the top rung, `minimal` up to the bottom.
2364        assert_eq!(
2365            shipped_effort(
2366                "provider-profile-llamacpp",
2367                "mmnuc/inkling-2-mini",
2368                Some("xhigh")
2369            ),
2370            json!("high")
2371        );
2372        assert_eq!(
2373            shipped_effort(
2374                "provider-profile-llamacpp",
2375                "mmnuc/inkling-2-mini",
2376                Some("minimal")
2377            ),
2378            json!("low")
2379        );
2380        assert_eq!(
2381            shipped_effort(
2382                "provider-profile-llamacpp",
2383                "mmnuc/inkling-2-mini",
2384                Some("none")
2385            ),
2386            json!("none")
2387        );
2388        assert_eq!(
2389            shipped_effort("provider-profile-llamacpp", "mmnuc/inkling-2-mini", None),
2390            json!("medium"),
2391            "nothing asked resolves the profile's declared default (`#276`)"
2392        );
2393
2394        // ollama-cloud: `xhigh` is `max` (its top rung), `minimal` is `low` because `minimal` 400s.
2395        assert_eq!(
2396            shipped_effort(
2397                "provider-profile-ollama-cloud",
2398                "gpt-oss:120b",
2399                Some("xhigh")
2400            ),
2401            json!("max")
2402        );
2403        assert_eq!(
2404            shipped_effort(
2405                "provider-profile-ollama-cloud",
2406                "gpt-oss:120b",
2407                Some("minimal")
2408            ),
2409            json!("low")
2410        );
2411        assert_eq!(
2412            shipped_effort(
2413                "provider-profile-ollama-cloud",
2414                "gpt-oss:120b",
2415                Some("none")
2416            ),
2417            json!("none")
2418        );
2419        assert_eq!(
2420            shipped_effort("provider-profile-ollama-cloud", "gpt-oss:120b", None),
2421            json!("medium"),
2422            "the cloud profile ships the same default"
2423        );
2424
2425        // A model the profile knows is not a reasoning model gets no field at all — and its off
2426        // switch is a fragment, not `reasoning_effort: "none"`.
2427        assert_eq!(
2428            shipped_effort(
2429                "provider-profile-llamacpp",
2430                "mmnuc/gemma-4-12b-it-qat",
2431                Some("high")
2432            ),
2433            json!(null),
2434            "an off-only model refuses a graded level"
2435        );
2436        assert_eq!(
2437            shipped_effort(
2438                "provider-profile-llamacpp",
2439                "mmnuc/gemma-4-12b-it-qat",
2440                None
2441            ),
2442            json!(null),
2443            "and with nothing asked it still sends nothing: its entry declares no default, so \
2444             `not sent` is the truth about this model rather than the shipped `medium` (`#276`)"
2445        );
2446        let gemma = {
2447            let plugin = shipped("provider-profile-llamacpp");
2448            let mut c = cfg("http://h/v1");
2449            c.profile = Some(plugin.name.clone());
2450            c.model = "mmnuc/gemma-4-12b-it-qat".into();
2451            let dial = std::sync::Arc::new(crate::reasoning::Dial::new(Some("none".into())));
2452            OpenAiProvider::with_dial(&c, &[plugin], Some(dial))
2453                .unwrap()
2454                .request_body(&[Message::user("hi")], &[])
2455        };
2456        assert!(
2457            gemma.get("reasoning_effort").is_none(),
2458            "gemma's off switch is the template kwarg, and the other field is never sent: {gemma}"
2459        );
2460        assert_eq!(
2461            gemma["chat_template_kwargs"]["enable_thinking"],
2462            json!(false),
2463            "the fragment goes out as a nested object"
2464        );
2465    }
2466
2467    /// `#245` done-when: `think = false` reaches an Ollama-looking base URL and nowhere else.
2468    #[test]
2469    fn the_ollama_off_switch_goes_to_ollama_and_nowhere_else() {
2470        use crate::reasoning::looks_like_ollama;
2471        // The matcher itself, which is the part that is easy to get backwards.
2472        for url in [
2473            "http://127.0.0.1:11434/v1",
2474            "http://192.168.1.50:11434",
2475            "http://ollama:11434/v1",
2476            "http://ollama/v1",
2477            "http://my-ollama.lan:8080/v1",
2478            "http://gpu.ollama.internal/v1",
2479            "http://OLLAMA.LOCAL/v1",
2480        ] {
2481            assert!(
2482                looks_like_ollama(url),
2483                "{url} is Ollama on somebody's network"
2484            );
2485        }
2486        for url in [
2487            "https://ollama.com/v1",
2488            "https://api.ollama.ai/v1",
2489            "https://ollama-cloud.example/v1",
2490            "https://llama.mhnets.com/v1",
2491            "http://192.168.1.120:18011/v1",
2492            "",
2493        ] {
2494            assert!(!looks_like_ollama(url), "{url} is not Ollama native");
2495        }
2496
2497        // And the switch follows the URL, through the shipped manifest.
2498        let plugin = shipped("provider-profile-ollama-cloud");
2499        let body_at = |url: &str| {
2500            let mut c = cfg(url);
2501            c.profile = Some(plugin.name.clone());
2502            let dial = std::sync::Arc::new(crate::reasoning::Dial::new(Some("none".into())));
2503            OpenAiProvider::with_dial(&c, std::slice::from_ref(&plugin), Some(dial))
2504                .unwrap()
2505                .request_body(&[Message::user("hi")], &[])
2506        };
2507        let cloud = body_at("https://ollama.com/v1");
2508        assert_eq!(
2509            cloud["reasoning_effort"],
2510            json!("none"),
2511            "the cloud's off switch"
2512        );
2513        assert!(
2514            cloud.get("think").is_none(),
2515            "and never the native flag: {cloud}"
2516        );
2517
2518        let native = body_at("http://127.0.0.1:11434/v1");
2519        assert_eq!(native["think"], json!(false), "the native off switch");
2520        assert!(
2521            native.get("reasoning_effort").is_none(),
2522            "which is not the cloud's: {native}"
2523        );
2524    }
2525
2526    /// The standing request policy: a context size where the manifest says it goes, a reply cap that
2527    /// is a ceiling rather than a default, a temperature the route will not take, and a
2528    /// `response_format` it refuses.
2529    #[test]
2530    fn a_profile_can_constrain_every_request_it_makes() {
2531        let mut plugin = ProviderProfile::builtin("llamacpp").unwrap();
2532        plugin.request = RequestPolicy {
2533            num_ctx: Some(8192),
2534            num_ctx_field: Some("n_ctx".into()),
2535            max_output: Some(2048),
2536            temperature: Some(Temperature::Omit),
2537            reject_response_formats: vec!["json_object".into()],
2538            aux_model: Some("small".into()),
2539            models: [(
2540                "big-model".to_string(),
2541                ModelLimits {
2542                    max_output: Some(1024),
2543                    num_ctx: None,
2544                },
2545            )]
2546            .into_iter()
2547            .collect(),
2548        };
2549        let mut c = cfg("http://h/v1");
2550        c.profile = Some("llamacpp".into());
2551        c.model = "m".into();
2552        c.temperature = Some(0.9);
2553        c.max_tokens = Some(4096);
2554        let p = OpenAiProvider::with_profiles(&c, &[plugin.clone()]).unwrap();
2555
2556        let body = p.request_body(&[Message::user("hi")], &[]);
2557        assert_eq!(body["n_ctx"], json!(8192), "the manifest names the field");
2558        assert_eq!(
2559            body["max_tokens"],
2560            json!(2048),
2561            "the cap wins over the config's 4096"
2562        );
2563        assert!(
2564            body.get("temperature").is_none(),
2565            "a route that rejects it never sees it"
2566        );
2567
2568        // A refusal is dropped rather than sent to be refused.
2569        let mut patch = crate::hooks::RequestPatch::default();
2570        patch
2571            .extra_params
2572            .insert("response_format".into(), json!({"type": "json_object"}));
2573        let body = p.request_body_with(&[Message::user("hi")], &[], &patch);
2574        assert!(body.get("response_format").is_none(), "{body}");
2575        // A format it does not refuse still goes.
2576        let mut patch = crate::hooks::RequestPatch::default();
2577        patch.extra_params.insert(
2578            "response_format".into(),
2579            json!({"type": "json_schema", "json_schema": {}}),
2580        );
2581        let body = p.request_body_with(&[Message::user("hi")], &[], &patch);
2582        assert_eq!(body["response_format"]["type"], json!("json_schema"));
2583
2584        // Per-model limits beat the profile's.
2585        let mut c2 = c.clone();
2586        c2.model = "big-model".into();
2587        let p2 = OpenAiProvider::with_profiles(&c2, &[plugin]).unwrap();
2588        assert_eq!(
2589            p2.request_body(&[Message::user("hi")], &[])["max_tokens"],
2590            json!(1024)
2591        );
2592    }
2593
2594    /// A profile that declares no `body` table must not replace the request with `null`. It did:
2595    /// `merge_json(body, Null)` assigned the null, and the next index-then-assign (`stream: true`)
2596    /// rebuilt an object containing only that key — a fifteen-byte request the endpoint could only
2597    /// answer with "no model id could be identified". Every example manifest had a `body` table, so
2598    /// nothing caught it until a shipped profile without one ran against a real server.
2599    #[test]
2600    fn a_profile_with_no_body_does_not_replace_the_request_with_null() {
2601        let mut plugin = ProviderProfile::builtin("llamacpp").unwrap();
2602        plugin.name = "no-body".into();
2603        plugin.body = serde_json::Value::Null;
2604        let mut c = cfg("http://h/v1");
2605        c.profile = Some("no-body".into());
2606        let p = OpenAiProvider::with_profiles(&c, &[plugin]).unwrap();
2607        let body = p.request_body(&[Message::user("hi")], &[]);
2608        assert_eq!(body["model"], json!("m"), "the model survives the merge");
2609        assert!(body["messages"].is_array(), "{body}");
2610    }
2611
2612    /// #227's headline: `/reasoning high` changes the next request's body in the *same* provider,
2613    /// because the effort is read per request instead of being frozen into the client's options.
2614    #[test]
2615    fn the_effort_is_read_per_request_so_a_session_override_reaches_the_next_body() {
2616        use crate::reasoning::Dial;
2617        let mut c = cfg("http://h/v1");
2618        c.reasoning_effort = Some("low".into());
2619        let dial = std::sync::Arc::new(Dial::new(c.reasoning_effort.clone()));
2620        let p = OpenAiProvider::with_dial(&c, &[], Some(dial.clone())).unwrap();
2621
2622        let body = p.request_body(&[Message::user("hi")], &[]);
2623        assert_eq!(
2624            body["reasoning_effort"],
2625            json!("low"),
2626            "the configured level"
2627        );
2628
2629        dial.set_session(Some("high".into()));
2630        let body = p.request_body(&[Message::user("hi")], &[]);
2631        assert_eq!(
2632            body["reasoning_effort"],
2633            json!("high"),
2634            "the same provider, the next request: no restart"
2635        );
2636
2637        // The built-in OpenAI profile declares no off switch — that endpoint rejects `none` — so
2638        // the field is omitted rather than sent to be refused, which is the difference between a
2639        // 400 and a quiet no-op.
2640        dial.set_session(Some("none".into()));
2641        assert!(p
2642            .request_body(&[Message::user("hi")], &[])
2643            .get("reasoning_effort")
2644            .is_none());
2645    }
2646
2647    /// `#278`: after `#276` made an absent `reasoning_effort` mean the profile's default, there was
2648    /// no way to say "put no field on the wire". `omit` is that word, and every declared profile
2649    /// answers it the same way — asserted against the body, which is the only witness.
2650    #[test]
2651    fn omit_puts_no_reasoning_field_on_the_wire_on_every_declared_profile() {
2652        for (profile, model) in [
2653            ("provider-profile-llamacpp", "mmnuc/inkling-2-mini"),
2654            ("provider-profile-ollama-cloud", "gpt-oss:120b"),
2655        ] {
2656            assert_eq!(
2657                shipped_effort(profile, model, Some("omit")),
2658                json!(null),
2659                "{profile} was asked for no field"
2660            );
2661            assert_ne!(
2662                shipped_effort(profile, model, Some("omit")),
2663                shipped_effort(profile, model, Some("none")),
2664                "{profile}: `omit` and `none` are two outcomes, not one"
2665            );
2666        }
2667    }
2668
2669    /// The other half of the same claim: a backend nobody declared is sent a level verbatim, and
2670    /// `omit` is not a level — sending the word would be the opposite of what it asks.
2671    #[test]
2672    fn an_undeclared_backend_is_not_sent_the_word_omit() {
2673        let c = cfg("http://h/v1");
2674        let dial = std::sync::Arc::new(crate::reasoning::Dial::new(Some("omit".into())));
2675        let p = OpenAiProvider::with_dial(&c, &[], Some(dial)).unwrap();
2676        let body = p.request_body(&[Message::user("hi")], &[]);
2677        assert!(
2678            body.get("reasoning_effort").is_none(),
2679            "an undeclared backend carries no field: {body}"
2680        );
2681    }
2682
2683    /// A level the wire does not have is never sent as itself, and a model with no graded dial gets
2684    /// no field at all — the two ways "it did nothing" used to look like "it worked".
2685    #[test]
2686    fn a_level_the_backend_lacks_is_clamped_or_omitted_never_sent_as_itself() {
2687        use crate::reasoning::{Dial, Policy};
2688        use std::collections::BTreeMap;
2689        let mut c = cfg("http://h/v1");
2690        c.profile = Some("llamacpp".into());
2691        c.reasoning_effort = Some("xhigh".into());
2692        let dial = std::sync::Arc::new(Dial::new(c.reasoning_effort.clone()));
2693
2694        // The built-in llama.cpp policy: three rungs, and a declared map for `xhigh`.
2695        let p = OpenAiProvider::with_dial(&c, &[], Some(dial.clone())).unwrap();
2696        assert_eq!(
2697            p.request_body(&[Message::user("hi")], &[])["reasoning_effort"],
2698            json!("high"),
2699            "xhigh is not a rung llama.cpp has; the nearest weaker one is"
2700        );
2701
2702        // A model that only switches on or off: no graded level goes out at all.
2703        let mut models = BTreeMap::new();
2704        models.insert(
2705            "gemma-4-12b".to_string(),
2706            ModelReasoning::Policy(Policy {
2707                field: "reasoning_effort".into(),
2708                kind: crate::reasoning::Kind::Level,
2709                off: Some("none".into()),
2710                ollama_off: None,
2711                levels: Vec::new(),
2712                map: BTreeMap::new(),
2713                default: None,
2714            }),
2715        );
2716        let mut plugin = ProviderProfile::builtin("llamacpp").unwrap();
2717        plugin.models = models;
2718        let mut c2 = c.clone();
2719        c2.model = "gemma-4-12b".into();
2720        let p = OpenAiProvider::with_dial(&c2, &[plugin], Some(dial.clone())).unwrap();
2721        assert!(
2722            p.request_body(&[Message::user("hi")], &[])
2723                .get("reasoning_effort")
2724                .is_none(),
2725            "a level this model has nowhere to put is omitted, not sent and ignored"
2726        );
2727        // ...and its off switch still works.
2728        dial.set_session(Some("none".into()));
2729        assert_eq!(
2730            p.request_body(&[Message::user("hi")], &[])["reasoning_effort"],
2731            json!("none")
2732        );
2733    }
2734
2735    /// Ollama Cloud's declared mapping, as a manifest writes it: `xhigh` is `max`, `minimal` is
2736    /// `low` (it 400s), and `none` is the only off switch.
2737    #[test]
2738    fn a_declared_vendor_mapping_is_what_reaches_an_ollama_cloud_body() {
2739        use crate::reasoning::{Dial, Policy};
2740        use std::collections::BTreeMap;
2741        let mut map = BTreeMap::new();
2742        map.insert("minimal".to_string(), "low".to_string());
2743        map.insert("xhigh".to_string(), "max".to_string());
2744        let policy = Policy {
2745            field: "reasoning_effort".into(),
2746            kind: crate::reasoning::Kind::Level,
2747            off: Some("none".into()),
2748            ollama_off: None,
2749            levels: vec!["low".into(), "medium".into(), "high".into(), "max".into()],
2750            map,
2751            default: None,
2752        };
2753        let mut plugin = ProviderProfile::builtin("openai").unwrap();
2754        plugin.name = "ollama-cloud".into();
2755        plugin.reasoning = Some(policy);
2756        let mut c = cfg("https://ollama.com/v1");
2757        c.profile = Some("ollama-cloud".into());
2758        let dial = std::sync::Arc::new(Dial::new(None));
2759        let p = OpenAiProvider::with_dial(&c, &[plugin], Some(dial.clone())).unwrap();
2760
2761        for (asked, sent) in [("xhigh", "max"), ("minimal", "low"), ("high", "high")] {
2762            dial.set_session(Some(asked.into()));
2763            assert_eq!(
2764                p.request_body(&[Message::user("hi")], &[])["reasoning_effort"],
2765                json!(sent),
2766                "{asked} on ollama-cloud"
2767            );
2768        }
2769        dial.set_session(Some("none".into()));
2770        assert_eq!(
2771            p.request_body(&[Message::user("hi")], &[])["reasoning_effort"],
2772            json!("none")
2773        );
2774        // Never `think`: that is Ollama's native flag, and this wire ignores it.
2775        dial.set_session(Some("none".into()));
2776        assert!(p
2777            .request_body(&[Message::user("hi")], &[])
2778            .get("think")
2779            .is_none());
2780    }
2781
2782    #[test]
2783    fn a_plugin_profile_can_replace_a_builtin_and_add_body_fields() {
2784        let mut c = cfg("http://h/v1");
2785        c.profile = Some("llamacpp".into());
2786        let plugin = ProviderProfile {
2787            name: "llamacpp".into(),
2788            tool_choice: true,
2789            stream_usage: false,
2790            max_tokens_field: Some("max_completion_tokens".into()),
2791            supports_tools: true,
2792            send_reasoning: false,
2793            body: json!({"chat_template_kwargs": {"enable_thinking": false}}),
2794            reasoning: None,
2795            models: std::collections::BTreeMap::new(),
2796            request: RequestPolicy::default(),
2797            vision: None,
2798        };
2799        let p = OpenAiProvider::with_profiles(&c, &[plugin]).unwrap();
2800        let tools = vec![ToolSpec {
2801            kind: "function",
2802            function: ToolSpecFunction {
2803                name: "t".into(),
2804                description: "d".into(),
2805                parameters: json!({"type": "object"}),
2806            },
2807        }];
2808        let body = p.request_body(&[Message::user("hi")], &tools);
2809        assert_eq!(body["tool_choice"], "auto", "the plugin profile won");
2810        assert_eq!(
2811            body["chat_template_kwargs"]["enable_thinking"],
2812            json!(false),
2813            "profile body fields reach the request"
2814        );
2815    }
2816
2817    #[test]
2818    fn a_profile_can_disable_tools_entirely() {
2819        let mut c = cfg("http://h/v1");
2820        c.profile = Some("notools".into());
2821        let plugin = ProviderProfile {
2822            name: "notools".into(),
2823            tool_choice: true,
2824            stream_usage: true,
2825            max_tokens_field: None,
2826            supports_tools: false,
2827            send_reasoning: false,
2828            body: json!({}),
2829            reasoning: None,
2830            models: std::collections::BTreeMap::new(),
2831            request: RequestPolicy::default(),
2832            vision: None,
2833        };
2834        let p = OpenAiProvider::with_profiles(&c, &[plugin]).unwrap();
2835        let tools = vec![ToolSpec {
2836            kind: "function",
2837            function: ToolSpecFunction {
2838                name: "t".into(),
2839                description: "d".into(),
2840                parameters: json!({"type": "object"}),
2841            },
2842        }];
2843        let body = p.request_body(&[Message::user("hi")], &tools);
2844        assert!(body.get("tools").is_none());
2845        assert!(body.get("tool_choice").is_none());
2846    }
2847
2848    #[test]
2849    fn a_reply_cap_is_sent_under_the_profiles_field_name() {
2850        let mut c = cfg("http://h/v1");
2851        c.max_tokens = Some(64);
2852        let p = OpenAiProvider::new(&c).unwrap();
2853        let body = p.request_body(&[Message::user("hi")], &[]);
2854        assert_eq!(body["max_tokens"], 64);
2855
2856        let mut plugin = ProviderProfile::builtin("openai").unwrap();
2857        plugin.max_tokens_field = Some("max_completion_tokens".into());
2858        let p = OpenAiProvider::with_profiles(&c, &[plugin]).unwrap();
2859        let body = p.request_body(&[Message::user("hi")], &[]);
2860        assert_eq!(body["max_completion_tokens"], 64);
2861        assert!(body.get("max_tokens").is_none());
2862    }
2863
2864    #[test]
2865    fn an_unknown_profile_is_a_config_error_that_lists_the_options() {
2866        let mut c = cfg("http://h/v1");
2867        c.profile = Some("nope".into());
2868        let err = OpenAiProvider::new(&c).unwrap_err().to_string();
2869        assert!(err.contains("unknown provider profile"), "{err}");
2870        assert!(err.contains("llamacpp"), "{err}");
2871    }
2872
2873    const PROPS_404: (&str, &str, &str) = ("404 Not Found", "", r#"{"error":"no props"}"#);
2874
2875    /// One `/props` 404, one `/props?model=` 404, then the model list — the probe's order.
2876    fn props_then_models(models: &'static str) -> Vec<(&'static str, &'static str, &'static str)> {
2877        vec![PROPS_404, PROPS_404, ("200 OK", "", models)]
2878    }
2879
2880    #[tokio::test]
2881    async fn context_window_prefers_llama_cpp_props() {
2882        let (base, h) = serve_script(vec![(
2883            "200 OK",
2884            "",
2885            r#"{"default_generation_settings":{"n_ctx":327680}}"#,
2886        )])
2887        .await;
2888        let got = advertised_context_window(&base, None, "m", Duration::from_millis(400)).await;
2889        assert_eq!(got, Some(327680));
2890        h.await.unwrap();
2891    }
2892
2893    /// The regression the first version shipped: on a multi-model endpoint the first row is
2894    /// not the configured model, and its window is not ours.
2895    #[tokio::test]
2896    async fn a_multi_model_list_reports_the_configured_models_window_not_the_first_row() {
2897        let rows = r#"{"data":[{"id":"mmnuc/gemma-4-12b-it-qat","context_length":131072},
2898                               {"id":"mmnuc/inkling-2-mini","context_length":327680},
2899                               {"id":"pc1/qwen-3.8-125b","context_length":262144}]}"#;
2900        let (base, h) = serve_script(props_then_models(rows)).await;
2901        let got = advertised_context_window(
2902            &base,
2903            None,
2904            "mmnuc/inkling-2-mini",
2905            Duration::from_millis(400),
2906        )
2907        .await;
2908        assert_eq!(
2909            got,
2910            Some(327680),
2911            "the configured model's window, not row 0's"
2912        );
2913        h.await.unwrap();
2914    }
2915
2916    /// One endpoint's namespacing is not a reason to show nothing: `pc1/x` serves `x`.
2917    #[tokio::test]
2918    async fn a_namespaced_id_matches_on_its_last_segment() {
2919        let rows = r#"{"data":[{"id":"mmnuc/gemma-4-12b-it-qat","context_length":131072},
2920                               {"id":"pc1/inkling-2-mini","context_window":327680}]}"#;
2921        let (base, h) = serve_script(props_then_models(rows)).await;
2922        let got =
2923            advertised_context_window(&base, None, "inkling-2-mini", Duration::from_millis(400))
2924                .await;
2925        assert_eq!(got, Some(327680));
2926        h.await.unwrap();
2927    }
2928
2929    /// A substring match would let `qwen-3.8-27b` answer for `qwen-3.8-125b`; only the last
2930    /// path segment is compared.
2931    #[tokio::test]
2932    async fn a_similar_but_different_model_is_not_a_match() {
2933        let rows = r#"{"data":[{"id":"pc1/qwen-3.8-27b","context_length":262144},
2934                               {"id":"pc1/qwen-3.8-125b-model","context_length":32768}]}"#;
2935        let (base, h) = serve_script(props_then_models(rows)).await;
2936        let got =
2937            advertised_context_window(&base, None, "qwen-3.8-125b", Duration::from_millis(400))
2938                .await;
2939        assert_eq!(got, None, "no row is this model, so nothing is invented");
2940        h.await.unwrap();
2941    }
2942
2943    /// A single-model server whose id we did not guess right: with one candidate the row
2944    /// cannot be the wrong model, so its figure is the honest answer.
2945    #[tokio::test]
2946    async fn a_single_row_list_is_used_even_when_its_id_differs() {
2947        let rows = r#"{"data":[{"id":"local-alias","max_model_len":131072}]}"#;
2948        let (base, h) = serve_script(props_then_models(rows)).await;
2949        let got = advertised_context_window(&base, None, "m", Duration::from_millis(400)).await;
2950        assert_eq!(got, Some(131072));
2951        h.await.unwrap();
2952    }
2953
2954    #[tokio::test]
2955    async fn context_window_is_none_when_nothing_answers() {
2956        let rows = r#"{"data":[{"id":"m"}]}"#;
2957        let (base, h) = serve_script(props_then_models(rows)).await;
2958        let got = advertised_context_window(&base, None, "m", Duration::from_millis(400)).await;
2959        assert_eq!(
2960            got, None,
2961            "no figure anywhere: no budget, never an invented one"
2962        );
2963        h.await.unwrap();
2964    }
2965
2966    #[tokio::test]
2967    async fn listing_models_reads_the_openai_shape_and_fails_small() {
2968        // A server that answers `/models` like a real one, and 404s anything else.
2969        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2970        let base = format!("http://{}", listener.local_addr().unwrap());
2971        let serving = std::thread::spawn(move || {
2972            for _ in 0..2 {
2973                let (mut s, _) = listener.accept().unwrap();
2974                let mut buf = [0u8; 2048];
2975                use std::io::{Read, Write};
2976                let n = s.read(&mut buf).unwrap();
2977                let req = String::from_utf8_lossy(&buf[..n]).to_string();
2978                let (code, body) = if req.contains("/wrong") {
2979                    ("404 Not Found", r#"{"error":"nope"}"#)
2980                } else if req.contains("/models") {
2981                    (
2982                        "200 OK",
2983                        r#"{"data":[{"id":"m-one"},{"id":"m-two"},{"id":"m-two"}]}"#,
2984                    )
2985                } else {
2986                    ("404 Not Found", r#"{"error":"nope"}"#)
2987                };
2988                let _ = write!(
2989                    s,
2990                    "HTTP/1.1 {code}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
2991                    body.len()
2992                );
2993            }
2994        });
2995
2996        let models = list_models(&base, None, std::time::Duration::from_secs(2))
2997            .await
2998            .unwrap();
2999        assert_eq!(models, vec!["m-one", "m-two"], "ids, deduplicated");
3000
3001        // A base URL that points somewhere else (or a dead server) is an Err, not a panic:
3002        // the wizard only needs to know it cannot offer a list.
3003        let err = list_models(
3004            &format!("{base}/wrong"),
3005            None,
3006            std::time::Duration::from_secs(2),
3007        )
3008        .await
3009        .expect_err("404 is not a model list");
3010        assert!(err.to_string().contains("404"), "{err}");
3011        serving.join().unwrap();
3012    }
3013
3014    // ---- M10: the failure taxonomy, the retry policy and the typed options --------------
3015
3016    #[tokio::test]
3017    async fn an_http_failure_keeps_the_status_the_body_and_the_request_id() {
3018        // A server that keeps failing: four answers of the same 500, which is what the retry
3019        // loop actually meets. (A one-shot server would be worse than useless here — the
3020        // retries would hit "connection refused" and report that instead of the 500.)
3021        let err_body = r#"{"error":{"message":"upstream model crashed"}}"#;
3022        let (base, server) = serve_script(vec![
3023            (
3024                "500 Internal Server Error",
3025                "x-request-id: req_abc123\r\n",
3026                err_body,
3027            ),
3028            (
3029                "500 Internal Server Error",
3030                "x-request-id: req_abc123\r\n",
3031                err_body,
3032            ),
3033            (
3034                "500 Internal Server Error",
3035                "x-request-id: req_abc123\r\n",
3036                err_body,
3037            ),
3038            (
3039                "500 Internal Server Error",
3040                "x-request-id: req_abc123\r\n",
3041                err_body,
3042            ),
3043        ])
3044        .await;
3045        let err = OpenAiProvider::new(&cfg(&base))
3046            .unwrap()
3047            .chat(&[Message::user("x")], &[])
3048            .await
3049            .unwrap_err();
3050        let failure = err.provider_failure().expect("a provider failure");
3051        assert_eq!(failure.kind(), crate::error::ProviderFailureKind::Http);
3052        assert_eq!(failure.status(), Some(500));
3053        assert!(
3054            failure.body().unwrap().contains("upstream model crashed"),
3055            "the server's own words survive: {:?}",
3056            failure.body()
3057        );
3058        assert_eq!(failure.request_id(), Some("req_abc123"));
3059        assert_eq!(server.await.unwrap(), 4, "1 try + 3 retries");
3060        // ...and the same things are in what a person actually reads.
3061        let rendered = err.to_string();
3062        assert!(rendered.contains("500"), "{rendered}");
3063        assert!(rendered.contains("upstream model crashed"), "{rendered}");
3064        assert!(rendered.contains("req_abc123"), "{rendered}");
3065        assert!(rendered.contains("4 attempts"), "{rendered}");
3066    }
3067
3068    #[tokio::test]
3069    async fn a_wrong_key_is_classified_as_unauthorized_and_not_retried() {
3070        let (base, server) = serve_script(vec![
3071            ("401 Unauthorized", "", r#"{"error":"bad key"}"#),
3072            ("200 OK", "", OK_BODY),
3073        ])
3074        .await;
3075        let err = OpenAiProvider::new(&cfg(&base))
3076            .unwrap()
3077            .chat(&[Message::user("x")], &[])
3078            .await
3079            .unwrap_err();
3080        assert_eq!(
3081            err.provider_failure().map(|f| f.kind()),
3082            Some(crate::error::ProviderFailureKind::Unauthorized)
3083        );
3084        assert!(!err.provider_failure().unwrap().is_retryable());
3085        // The second scripted answer is never asked for.
3086        assert!(
3087            server.await.unwrap() <= 1,
3088            "a bad key is not worth repeating"
3089        );
3090    }
3091
3092    #[tokio::test]
3093    async fn an_option_the_server_refuses_names_the_option_and_the_model() {
3094        let (base, _h) = serve_once(
3095            "400 Bad Request",
3096            r#"{"error":{"message":"unknown field 'top_p'","type":"invalid_request_error"}}"#,
3097        )
3098        .await;
3099        let mut c = cfg(&base);
3100        c.model = "qwen3.8-27b".into();
3101        c.top_p = Some(0.9);
3102        let err = OpenAiProvider::new(&c)
3103            .unwrap()
3104            .chat(&[Message::user("x")], &[])
3105            .await
3106            .unwrap_err();
3107        let failure = err.provider_failure().unwrap();
3108        assert_eq!(
3109            failure.kind(),
3110            crate::error::ProviderFailureKind::InvalidRequest
3111        );
3112        assert_eq!(failure.status(), Some(400));
3113        let hint = failure.hint().expect("a hint naming the field");
3114        assert!(hint.contains("top_p"), "{hint}");
3115        assert!(hint.contains("qwen3.8-27b"), "{hint}");
3116        assert!(
3117            hint.contains("extra_body"),
3118            "it says what to do instead: {hint}"
3119        );
3120        // The operator sees it in the message they actually get.
3121        assert!(err.to_string().contains("provider.top_p"), "{err}");
3122    }
3123
3124    #[tokio::test]
3125    async fn an_unreadable_reply_is_not_retried() {
3126        let (base, server) = serve_script(vec![
3127            ("200 OK", "", "this is not json"),
3128            ("200 OK", "", OK_BODY),
3129        ])
3130        .await;
3131        let err = OpenAiProvider::new(&cfg(&base))
3132            .unwrap()
3133            .chat(&[Message::user("x")], &[])
3134            .await
3135            .unwrap_err();
3136        assert_eq!(
3137            err.provider_failure().map(|f| f.kind()),
3138            Some(crate::error::ProviderFailureKind::Response)
3139        );
3140        assert_eq!(server.await.unwrap(), 1, "reading it twice reads the same");
3141    }
3142
3143    #[test]
3144    fn optional_fields_are_absent_from_the_body_until_asked_for() {
3145        let p = OpenAiProvider::new(&cfg("http://h/v1")).unwrap();
3146        let body = p.request_body(&[Message::user("hi")], &[]);
3147        for key in ["top_p", "seed", "stop", "parallel_tool_calls"] {
3148            assert!(
3149                body.get(key).is_none(),
3150                "{key} must not be sent unless configured: {body}"
3151            );
3152        }
3153        // Reasoning is the one optional field with a shipped answer (`#276`): a route that
3154        // declares a default is sent it, because "an install that was never configured reasons
3155        // at medium" is the whole point of the default. Every field without a declared default
3156        // stays off the wire — and a backend that declares none gets nothing here either,
3157        // which `the_shipped_profiles_send_exactly_what_they_promise` covers.
3158        assert_eq!(
3159            body.get("reasoning_effort"),
3160            Some(&serde_json::json!(crate::reasoning::SHIPPED_DEFAULT)),
3161            "the route's declared default is the level an unconfigured request carries: {body}"
3162        );
3163    }
3164
3165    #[test]
3166    fn top_p_seed_and_the_rest_reach_the_body_when_set() {
3167        let mut c = cfg("http://h/v1");
3168        c.top_p = Some(0.9);
3169        c.seed = Some(7);
3170        c.stop = Some(vec!["</s>".into(), "USER:".into()]);
3171        c.reasoning_effort = Some("high".into());
3172        c.parallel_tool_calls = Some(false);
3173        let p = OpenAiProvider::new(&c).unwrap();
3174        let body = p.request_body(&[Message::user("hi")], &[]);
3175        assert_eq!(body["top_p"], json!(0.9));
3176        assert_eq!(body["seed"], json!(7));
3177        assert_eq!(body["stop"], json!(["</s>", "USER:"]));
3178        assert_eq!(body["reasoning_effort"], json!("high"));
3179        assert_eq!(body["parallel_tool_calls"], json!(false));
3180    }
3181
3182    #[tokio::test]
3183    async fn the_options_are_on_the_wire_not_just_in_the_body_builder() {
3184        let (base, h) = serve_once("200 OK", OK_BODY).await;
3185        let mut c = cfg(&base);
3186        c.top_p = Some(0.9);
3187        c.seed = Some(7);
3188        OpenAiProvider::new(&c)
3189            .unwrap()
3190            .chat(&[Message::user("x")], &[])
3191            .await
3192            .unwrap();
3193        let sent = h.await.unwrap();
3194        assert!(sent.contains("\"top_p\":0.9"), "{sent}");
3195        assert!(sent.contains("\"seed\":7"), "{sent}");
3196    }
3197
3198    #[test]
3199    fn an_out_of_range_top_p_is_a_config_error_rather_than_a_400() {
3200        let mut c = cfg("http://h/v1");
3201        c.top_p = Some(1.5);
3202        let err = OpenAiProvider::new(&c).unwrap_err().to_string();
3203        assert!(err.contains("provider.top_p"), "{err}");
3204        assert!(err.contains("1.5"), "{err}");
3205    }
3206
3207    #[test]
3208    fn a_tool_choice_from_config_overrides_the_profiles_default() {
3209        // The profile's boolean decides whether an *unset* choice is sent; an explicit one is
3210        // the operator's decision and goes out even on a profile that would not default to it.
3211        let tools = vec![ToolSpec {
3212            kind: "function",
3213            function: ToolSpecFunction {
3214                name: "read_file".into(),
3215                description: "read".into(),
3216                parameters: json!({"type": "object"}),
3217            },
3218        }];
3219        let mut c = cfg("http://h/v1");
3220        c.profile = Some("llamacpp".into());
3221        let plain = OpenAiProvider::new(&c).unwrap();
3222        assert!(plain
3223            .request_body(&[Message::user("hi")], &tools)
3224            .get("tool_choice")
3225            .is_none());
3226
3227        c.tool_choice = Some(ToolChoice::Function("read_file".into()));
3228        let forced = OpenAiProvider::new(&c).unwrap();
3229        let body = forced.request_body(&[Message::user("hi")], &tools);
3230        assert_eq!(
3231            body["tool_choice"],
3232            json!({"type": "function", "function": {"name": "read_file"}})
3233        );
3234    }
3235
3236    #[test]
3237    fn extra_body_is_the_escape_hatch_and_a_turn_patch_still_wins() {
3238        let mut c = cfg("http://h/v1");
3239        c.extra_body = Some(json!({
3240            "chat_template_kwargs": {"enable_thinking": false},
3241            "seed": 1
3242        }));
3243        let p = OpenAiProvider::new(&c).unwrap();
3244        let body = p.request_body(&[Message::user("hi")], &[]);
3245        assert_eq!(
3246            body["chat_template_kwargs"]["enable_thinking"],
3247            json!(false)
3248        );
3249        assert_eq!(body["seed"], json!(1));
3250
3251        // A per-turn patch is the more specific decision, so it lands after the escape hatch.
3252        let patch = crate::hooks::RequestPatch {
3253            extra_params: [("seed".to_string(), json!(99))].into_iter().collect(),
3254            ..Default::default()
3255        };
3256        let patched = p.request_body_with(&[Message::user("hi")], &[], &patch);
3257        assert_eq!(patched["seed"], json!(99));
3258        assert_eq!(
3259            patched["chat_template_kwargs"]["enable_thinking"],
3260            json!(false)
3261        );
3262    }
3263
3264    #[tokio::test]
3265    async fn a_stream_cut_before_any_text_is_retried_once_and_can_succeed() {
3266        // Only a usage chunk arrives before the cut: nothing was shown, so repeating the turn
3267        // cannot duplicate anything the reader has seen.
3268        let (base, server) =
3269            serve_sse_cut_then_ok("data: {\"choices\":[],\"usage\":{\"total_tokens\":3}}\n\n")
3270                .await;
3271        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
3272        let reply = p
3273            .chat_stream(&[Message::user("x")], &[], &|_| {})
3274            .await
3275            .expect("a cut before any text is worth one more request");
3276        assert_eq!(reply.content.as_deref(), Some("whole"));
3277        assert_eq!(server.await.unwrap(), 2);
3278    }
3279
3280    #[tokio::test]
3281    async fn a_stream_cut_after_text_is_not_retried() {
3282        // "half" was already handed to the reader; repeating the turn would print it twice.
3283        let (base, server) =
3284            serve_sse_cut_then_ok("data: {\"choices\":[{\"delta\":{\"content\":\"half\"}}]}\n\n")
3285                .await;
3286        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
3287        let seen = Mutex::new(Vec::<String>::new());
3288        let err = p
3289            .chat_stream(&[Message::user("x")], &[], &|d| {
3290                if let crate::stream::Delta::Text(t) = d {
3291                    seen.lock().unwrap().push(t);
3292                }
3293            })
3294            .await
3295            .unwrap_err();
3296        assert_eq!(*seen.lock().unwrap(), ["half"]);
3297        assert_eq!(
3298            err.provider_failure().map(|f| f.kind()),
3299            Some(crate::error::ProviderFailureKind::Truncated)
3300        );
3301        assert_eq!(server.await.unwrap(), 1, "the reader already saw the start");
3302    }
3303
3304    #[test]
3305    fn a_field_name_is_matched_as_a_word_not_as_a_substring() {
3306        assert!(mentions_field("unknown field 'top_p'", "top_p"));
3307        assert!(mentions_field("top_p is not supported", "top_p"));
3308        assert!(!mentions_field("the stop_reason was null", "stop"));
3309        assert!(!mentions_field("unstoppable", "stop"));
3310        assert!(mentions_field("bad value for stop", "stop"));
3311    }
3312
3313    #[test]
3314    fn per_route_vision_overrides_the_profile() {
3315        let mut c = cfg("http://h/v1");
3316        c.profile = Some("llamacpp".into());
3317        assert!(!OpenAiProvider::new(&c).unwrap().can_see());
3318
3319        c.vision = Some(true);
3320        assert!(OpenAiProvider::new(&c).unwrap().can_see());
3321
3322        let mut seeing = ProviderProfile::builtin("openai").unwrap();
3323        seeing.name = "seeing".into();
3324        seeing.vision = Some(true);
3325        let profiles = [seeing];
3326
3327        c.profile = Some("seeing".into());
3328        c.vision = None;
3329        assert!(OpenAiProvider::with_profiles(&c, &profiles)
3330            .unwrap()
3331            .can_see());
3332
3333        c.vision = Some(false);
3334        assert!(!OpenAiProvider::with_profiles(&c, &profiles)
3335            .unwrap()
3336            .can_see());
3337    }
3338}