Skip to main content

base/provider/
mod.rs

1//! Model providers as `settings.json` describes them — the `providers` list,
2//! each entry's vendor, protocol, models, tiers and quota — the contract a
3//! session's code routes its calls through ([`TaskRouting`]), and where
4//! quota usage is kept ([`QuotaLedger`]).
5//!
6//! Lives in `base` so `Settings` can carry these types directly. The router
7//! that falls back along `model.order` is `model::routing`; building a live
8//! client from a [`ProviderConfig`] needs a concrete protocol and is the
9//! assembly's job (`assembly::model_router`).
10
11use serde::{Deserialize, Serialize};
12
13use crate::interface::model::Effort;
14
15mod quota;
16mod routing;
17
18pub use quota::{PeriodUsage, QuotaLedger, QuotaStatus};
19pub use routing::{Destination, ProviderSwitch, RouteObserver, TaskRouting};
20
21/// The wire protocol a provider speaks.
22#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
23pub enum ApiType {
24    #[serde(rename = "anthropic")]
25    Anthropic,
26    #[serde(rename = "openai_chat")]
27    OpenAIChat,
28    #[serde(rename = "openai_responses")]
29    OpenAIResponses,
30}
31
32/// Who runs the endpoint. Decides what the protocol leaves open: how thinking
33/// is switched on, whether reasoning goes back, how effort is spelled.
34#[derive(
35    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema,
36)]
37#[serde(rename_all = "snake_case")]
38pub enum Vendor {
39    Anthropic,
40    Openai,
41    Deepseek,
42    Qwen,
43    Vllm,
44    Sglang,
45    #[default]
46    Generic,
47}
48
49/// The request fields an OpenAI-style endpoint switches thinking with.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum ThinkingToggle {
52    /// `"thinking": {"type": "enabled" | "disabled"}`.
53    Deepseek,
54    /// `"enable_thinking": true | false`.
55    EnableThinking,
56    /// `"chat_template_kwargs": {"enable_thinking": true | false}`.
57    ChatTemplateKwargs,
58}
59
60impl Vendor {
61    pub fn thinking_toggle(self) -> Option<ThinkingToggle> {
62        match self {
63            Self::Deepseek => Some(ThinkingToggle::Deepseek),
64            Self::Qwen => Some(ThinkingToggle::EnableThinking),
65            Self::Vllm | Self::Sglang => Some(ThinkingToggle::ChatTemplateKwargs),
66            Self::Anthropic | Self::Openai | Self::Generic => None,
67        }
68    }
69
70    /// Whether the model's `reasoning_content` has to be echoed on the
71    /// assistant messages of the current tool loop.
72    pub fn passes_reasoning_back(self) -> bool {
73        self == Self::Deepseek
74    }
75
76    /// `effort` as this vendor's endpoint names it.
77    pub fn effort(self, effort: Effort) -> Effort {
78        match (self, effort) {
79            (Self::Deepseek, Effort::Medium | Effort::Xhigh) => Effort::High,
80            (_, effort) => effort,
81        }
82    }
83}
84
85/// A model tier. Tasks and sessions ask for a tier; each provider says which
86/// of its models serves it.
87#[derive(
88    Debug,
89    Clone,
90    Copy,
91    PartialEq,
92    Eq,
93    Hash,
94    PartialOrd,
95    Ord,
96    Serialize,
97    Deserialize,
98    schemars::JsonSchema,
99)]
100#[serde(rename_all = "snake_case")]
101pub enum Tier {
102    Strong,
103    Balanced,
104    Fast,
105}
106
107impl Tier {
108    pub const ALL: [Tier; 3] = [Tier::Strong, Tier::Balanced, Tier::Fast];
109
110    pub fn as_str(self) -> &'static str {
111        match self {
112            Self::Strong => "strong",
113            Self::Balanced => "balanced",
114            Self::Fast => "fast",
115        }
116    }
117
118    pub fn from_name(name: &str) -> Option<Tier> {
119        Self::ALL.into_iter().find(|tier| tier.as_str() == name)
120    }
121
122    /// The tier a Claude Code model alias stands for.
123    pub fn from_claude_alias(name: &str) -> Option<Tier> {
124        match name {
125            "opus" => Some(Self::Strong),
126            "sonnet" => Some(Self::Balanced),
127            "haiku" => Some(Self::Fast),
128            _ => None,
129        }
130    }
131}
132
133/// Which of a provider's models serves each tier, as written.
134#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
135#[serde(default, deny_unknown_fields)]
136pub struct Tiers {
137    /// Required.
138    #[serde(skip_serializing_if = "Option::is_none")]
139    pub strong: Option<String>,
140    /// Unset, `strong`'s.
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub balanced: Option<String>,
143    /// Unset, `balanced`'s.
144    #[serde(skip_serializing_if = "Option::is_none")]
145    pub fast: Option<String>,
146}
147
148/// [`Tiers`] with the gaps filled.
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub struct ResolvedTiers {
151    pub strong: String,
152    pub balanced: String,
153    pub fast: String,
154}
155
156impl ResolvedTiers {
157    pub fn all(model: &str) -> Self {
158        Self {
159            strong: model.to_string(),
160            balanced: model.to_string(),
161            fast: model.to_string(),
162        }
163    }
164
165    pub fn get(&self, tier: Tier) -> &str {
166        match tier {
167            Tier::Strong => &self.strong,
168            Tier::Balanced => &self.balanced,
169            Tier::Fast => &self.fast,
170        }
171    }
172
173    /// The tier `model` serves here: `prefer` when it is one of them, else
174    /// the first of strong, balanced, fast.
175    pub fn tier_of(&self, model: &str, prefer: Tier) -> Option<Tier> {
176        if self.get(prefer) == model {
177            return Some(prefer);
178        }
179        Tier::ALL.into_iter().find(|tier| self.get(*tier) == model)
180    }
181
182    pub fn contains(&self, model: &str) -> bool {
183        Tier::ALL.into_iter().any(|tier| self.get(tier) == model)
184    }
185}
186
187/// Token limits per period, counted as uncached input plus cache writes plus
188/// output; cache reads do not count. A period left out has no limit.
189#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
190#[serde(default, deny_unknown_fields)]
191pub struct Quota {
192    /// From 00:00 local time.
193    #[serde(skip_serializing_if = "Option::is_none")]
194    pub day: Option<u64>,
195    /// From Monday 00:00 local time.
196    #[serde(skip_serializing_if = "Option::is_none")]
197    pub week: Option<u64>,
198    /// From the 1st, 00:00 local time.
199    #[serde(skip_serializing_if = "Option::is_none")]
200    pub month: Option<u64>,
201}
202
203impl Quota {
204    pub fn is_unlimited(&self) -> bool {
205        self.day.is_none() && self.week.is_none() && self.month.is_none()
206    }
207}
208
209/// One entry of `providers`.
210#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
211#[serde(deny_unknown_fields)]
212pub struct ProviderConfig {
213    /// Unique, of ASCII letters, digits, `-` and `_`. When the tiers define
214    /// the same id twice, the first in load order (global, scene, project;
215    /// each tier's `settings.local.json` after its `settings.json`) is used
216    /// and the rest ignored.
217    #[schemars(pattern(r"^[a-z0-9_-]+$"))]
218    pub id: String,
219    /// `anthropic`, `openai`, `deepseek`, `qwen`, `vllm`, `sglang` or
220    /// `generic` (default). Decides how thinking is switched, whether
221    /// reasoning is sent back and how effort is spelled.
222    #[serde(default)]
223    pub vendor: Vendor,
224    /// `anthropic` (default), `openai_chat` or `openai_responses`, or a
225    /// protocol the host registered.
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub api: Option<String>,
228    /// Required for `openai_chat`; `anthropic` without one uses Anthropic's
229    /// own API, `openai_responses` OpenAI's.
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub base_url: Option<String>,
232    /// The environment variable holding the key. Without one the host's
233    /// credential source is asked. No child process inherits it once a
234    /// settings file names it, unless `sandbox.env.allow` does.
235    #[serde(default, skip_serializing_if = "Option::is_none")]
236    pub api_key_env: Option<String>,
237    /// The models this provider serves, each an id or an object with what
238    /// the engine should know about it. Empty accepts any id. Not fetched
239    /// from the provider — `config.listModels` does that, on request.
240    #[serde(default, skip_serializing_if = "Vec::is_empty")]
241    pub models: Vec<ModelEntry>,
242    /// Which model serves `strong`, `balanced` and `fast`. `strong` is
243    /// required; `balanced` defaults to `strong`'s, `fast` to `balanced`'s.
244    /// Each must be in `models` when `models` lists any.
245    #[serde(default)]
246    pub tiers: Tiers,
247    /// Token limits; past one, the provider is skipped until the period
248    /// turns over.
249    #[serde(default, skip_serializing_if = "Quota::is_unlimited")]
250    pub quota: Quota,
251    /// The provider the engine supplies when the settings define none.
252    #[serde(skip)]
253    #[schemars(skip)]
254    pub builtin: bool,
255}
256
257/// One entry of a provider's `models`.
258#[derive(Debug, Clone, PartialEq, Serialize, schemars::JsonSchema)]
259#[serde(untagged)]
260#[non_exhaustive]
261pub enum ModelEntry {
262    Id(String),
263    Spec(ModelSpec),
264}
265
266/// A model with what the engine should know about it beyond its id.
267///
268/// `context_window` and `max_output` are applied to the model's calls;
269/// `reasoning_levels` and `input_types` are kept and reported; nothing in
270/// the engine decides by them.
271#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
272#[serde(deny_unknown_fields)]
273pub struct ModelSpec {
274    pub id: String,
275    #[serde(default, skip_serializing_if = "Option::is_none")]
276    pub context_window: Option<u64>,
277    /// The most `max_tokens` a call to this model is sent with, and the most
278    /// a reply cut off at its limit is retried with. Unset, the model's
279    /// documented limit, looked up by its id.
280    #[serde(default, skip_serializing_if = "Option::is_none")]
281    pub max_output: Option<u32>,
282    #[serde(default, skip_serializing_if = "Option::is_none")]
283    pub reasoning_levels: Option<Vec<String>>,
284    #[serde(default, skip_serializing_if = "Option::is_none")]
285    pub input_types: Option<Vec<String>>,
286}
287
288impl ModelEntry {
289    pub fn id(&self) -> &str {
290        match self {
291            Self::Id(id) => id,
292            Self::Spec(spec) => &spec.id,
293        }
294    }
295
296    pub fn spec(&self) -> Option<&ModelSpec> {
297        match self {
298            Self::Id(_) => None,
299            Self::Spec(spec) => Some(spec),
300        }
301    }
302}
303
304impl From<&str> for ModelEntry {
305    fn from(id: &str) -> Self {
306        Self::Id(id.to_string())
307    }
308}
309
310impl From<String> for ModelEntry {
311    fn from(id: String) -> Self {
312        Self::Id(id)
313    }
314}
315
316/// By hand rather than `untagged`, so a malformed entry says what is wrong
317/// with it instead of that it matched no variant.
318impl<'de> Deserialize<'de> for ModelEntry {
319    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
320        use serde::de::Error;
321        match serde_json::Value::deserialize(d)? {
322            serde_json::Value::String(id) => Ok(Self::Id(id)),
323            object @ serde_json::Value::Object(_) => serde_json::from_value(object)
324                .map(Self::Spec)
325                .map_err(|e| D::Error::custom(format!("a model entry: {e}"))),
326            _ => Err(D::Error::custom(
327                "a model entry is an id string or an object with `id`",
328            )),
329        }
330    }
331}
332
333impl ProviderConfig {
334    /// The id of the provider the engine supplies when the settings define
335    /// none.
336    pub const BUILTIN_ID: &'static str = "anthropic";
337
338    /// The provider used when the settings define none: Anthropic's API,
339    /// keyed and addressed from the environment, every tier `model`.
340    pub fn builtin(model: &str) -> Self {
341        Self {
342            id: Self::BUILTIN_ID.to_string(),
343            vendor: Vendor::Anthropic,
344            api: Some("anthropic".to_string()),
345            tiers: Tiers {
346                strong: Some(model.to_string()),
347                balanced: None,
348                fast: None,
349            },
350            builtin: true,
351            ..Default::default()
352        }
353    }
354
355    /// Why `id` cannot name a provider, if it cannot. The id is the name of
356    /// the provider's quota usage file as it stands, so it holds nothing a
357    /// file name would have to change — and no capital, since `Ab` and `ab`
358    /// are one file on a case-insensitive file system.
359    pub fn id_problem(id: &str) -> Option<String> {
360        if id.is_empty() {
361            return Some("a provider needs an `id`".to_string());
362        }
363        let fits = id
364            .bytes()
365            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_');
366        (!fits).then(|| {
367            format!("provider id `{id}` may hold only lowercase ASCII letters, digits, `-` and `_`")
368        })
369    }
370
371    /// `api`, defaulted.
372    pub fn api(&self) -> &str {
373        self.api.as_deref().unwrap_or("anthropic")
374    }
375
376    /// Whether `model` may be sent to this provider: listed, or nothing is.
377    pub fn accepts_model(&self, model: &str) -> bool {
378        self.models.is_empty() || self.models.iter().any(|m| m.id() == model)
379    }
380
381    /// Whether `models` lists `model`.
382    pub fn lists_model(&self, model: &str) -> bool {
383        self.models.iter().any(|m| m.id() == model)
384    }
385
386    pub fn model_ids(&self) -> Vec<&str> {
387        self.models.iter().map(ModelEntry::id).collect()
388    }
389
390    /// What `models` says about `model` beyond its id, if anything.
391    pub fn model_spec(&self, model: &str) -> Option<&ModelSpec> {
392        self.models
393            .iter()
394            .find(|m| m.id() == model)
395            .and_then(ModelEntry::spec)
396    }
397
398    /// The tiers with the gaps filled, or why this entry is not usable.
399    pub fn resolved_tiers(&self) -> Result<ResolvedTiers, String> {
400        let id = &self.id;
401        let strong = self
402            .tiers
403            .strong
404            .clone()
405            .filter(|m| !m.is_empty())
406            .ok_or_else(|| format!("provider `{id}` has no `tiers.strong`"))?;
407        let balanced = self
408            .tiers
409            .balanced
410            .clone()
411            .unwrap_or_else(|| strong.clone());
412        let fast = self.tiers.fast.clone().unwrap_or_else(|| balanced.clone());
413        let resolved = ResolvedTiers {
414            strong,
415            balanced,
416            fast,
417        };
418        if !self.models.is_empty() {
419            for tier in Tier::ALL {
420                let model = resolved.get(tier);
421                if !self.lists_model(model) {
422                    return Err(format!(
423                        "provider `{id}`: `tiers.{}` is `{model}`, which is not in its `models`",
424                        tier.as_str()
425                    ));
426                }
427            }
428        }
429        Ok(resolved)
430    }
431}
432
433/// One model a provider's endpoint lists, with only what the endpoint said.
434#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
435pub struct ListedModel {
436    pub id: String,
437    #[serde(default, skip_serializing_if = "Option::is_none")]
438    pub display_name: Option<String>,
439    #[serde(default, skip_serializing_if = "Option::is_none")]
440    pub context_window: Option<u64>,
441    #[serde(default, skip_serializing_if = "Option::is_none")]
442    pub max_output: Option<u32>,
443    #[serde(default, skip_serializing_if = "Option::is_none")]
444    pub input_types: Option<Vec<String>>,
445    /// Whether the model reasons, when the endpoint says.
446    #[serde(default, skip_serializing_if = "Option::is_none")]
447    pub reasoning: Option<bool>,
448}
449
450/// The tier each kind of model call asks for. The task types: `main` (the
451/// conversation), `subagent` (sub-agents started without a model of their
452/// own), `compact` (summarizing for compaction), `memory` (extracting
453/// memories), `title` (naming a session), `web_search` (`WebSearch`) and
454/// `web_fetch` (`WebFetch` reading a page — unset, `WebFetch` uses no model
455/// and returns the page text).
456#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
457#[serde(default, deny_unknown_fields)]
458pub struct TaskTiers {
459    /// Default `strong`.
460    pub main: Tier,
461    /// Default `balanced`.
462    pub subagent: Tier,
463    /// Default `fast`.
464    pub compact: Tier,
465    /// Default `fast`.
466    pub memory: Tier,
467    /// Default `fast`.
468    pub title: Tier,
469    /// Default `fast`.
470    pub web_search: Tier,
471    /// Default unset: no model reads fetched pages.
472    #[serde(skip_serializing_if = "Option::is_none")]
473    pub web_fetch: Option<Tier>,
474}
475
476impl Default for TaskTiers {
477    fn default() -> Self {
478        Self {
479            main: Tier::Strong,
480            subagent: Tier::Balanced,
481            compact: Tier::Fast,
482            memory: Tier::Fast,
483            title: Tier::Fast,
484            web_search: Tier::Fast,
485            web_fetch: None,
486        }
487    }
488}
489
490impl TaskTiers {
491    pub const MAIN: &'static str = "main";
492    pub const SUBAGENT: &'static str = "subagent";
493    pub const COMPACT: &'static str = "compact";
494    pub const MEMORY: &'static str = "memory";
495    pub const TITLE: &'static str = "title";
496    pub const WEB_SEARCH: &'static str = "web_search";
497    pub const WEB_FETCH: &'static str = "web_fetch";
498
499    /// The tier `task` asks for; `None` for a task with no model, or one not
500    /// in the list.
501    pub fn get(&self, task: &str) -> Option<Tier> {
502        match task {
503            Self::MAIN => Some(self.main),
504            Self::SUBAGENT => Some(self.subagent),
505            Self::COMPACT => Some(self.compact),
506            Self::MEMORY => Some(self.memory),
507            Self::TITLE => Some(self.title),
508            Self::WEB_SEARCH => Some(self.web_search),
509            Self::WEB_FETCH => self.web_fetch,
510            _ => None,
511        }
512    }
513}
514
515/// The providers `order` puts calls through, first to last, each with its
516/// tiers filled — or what is wrong with the configuration. Every defined
517/// provider is checked, ordered or not. An empty `order` is the first
518/// defined provider alone.
519pub fn routing_order<'a>(
520    providers: &'a [ProviderConfig],
521    order: &[String],
522) -> Result<Vec<(&'a ProviderConfig, ResolvedTiers)>, String> {
523    let mut resolved = Vec::with_capacity(providers.len());
524    for provider in providers {
525        if let Some(problem) = ProviderConfig::id_problem(&provider.id) {
526            return Err(problem);
527        }
528        resolved.push((provider, provider.resolved_tiers()?));
529    }
530    let Some(first) = providers.first() else {
531        return Err("no provider is defined".to_string());
532    };
533    let order: Vec<&str> = match order.is_empty() {
534        true => vec![first.id.as_str()],
535        false => order.iter().map(String::as_str).collect(),
536    };
537    let mut out: Vec<(&ProviderConfig, ResolvedTiers)> = Vec::with_capacity(order.len());
538    for id in order {
539        if out.iter().any(|(p, _)| p.id == id) {
540            continue;
541        }
542        let Some((provider, tiers)) = resolved.iter().find(|(p, _)| p.id == id) else {
543            return Err(format!(
544                "`model.order` names provider `{id}`, which no `providers` entry defines"
545            ));
546        };
547        out.push((provider, tiers.clone()));
548    }
549    Ok(out)
550}
551
552#[cfg(test)]
553mod tests;