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    /// `host`: the engine holds no key for it and asks none of anyone; its
238    /// requests go out without credentials through the network the embedder
239    /// gave (`EmbedConfig.model_network`), which adds them. Default `key`.
240    #[serde(default, skip_serializing_if = "ProviderAuth::is_key")]
241    pub auth: ProviderAuth,
242    /// The models this provider serves, each an id or an object with what
243    /// the engine should know about it. Empty accepts any id. Not fetched
244    /// from the provider — `config.listModels` does that, on request.
245    #[serde(default, skip_serializing_if = "Vec::is_empty")]
246    pub models: Vec<ModelEntry>,
247    /// Which model serves `strong`, `balanced` and `fast`. `strong` is
248    /// required; `balanced` defaults to `strong`'s, `fast` to `balanced`'s.
249    /// Each must be in `models` when `models` lists any.
250    #[serde(default)]
251    pub tiers: Tiers,
252    /// Token limits; past one, the provider is skipped until the period
253    /// turns over.
254    #[serde(default, skip_serializing_if = "Quota::is_unlimited")]
255    pub quota: Quota,
256    /// The provider the engine supplies when the settings define none.
257    #[serde(skip)]
258    #[schemars(skip)]
259    pub builtin: bool,
260}
261
262/// Who puts a provider's credentials on its requests.
263#[derive(
264    Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
265)]
266#[serde(rename_all = "lowercase")]
267#[non_exhaustive]
268pub enum ProviderAuth {
269    /// The engine, with the key its credential source gives.
270    #[default]
271    Key,
272    /// The embedder, on the way out.
273    Host,
274}
275
276impl ProviderAuth {
277    pub fn is_key(&self) -> bool {
278        *self == Self::Key
279    }
280}
281
282/// One entry of a provider's `models`.
283#[derive(Debug, Clone, PartialEq, Serialize, schemars::JsonSchema)]
284#[serde(untagged)]
285#[non_exhaustive]
286pub enum ModelEntry {
287    Id(String),
288    Spec(ModelSpec),
289}
290
291/// A model with what the engine should know about it beyond its id.
292///
293/// `context_window` and `max_output` are applied to the model's calls;
294/// `reasoning_levels` and `input_types` are kept and reported; nothing in
295/// the engine decides by them.
296#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
297#[serde(deny_unknown_fields)]
298pub struct ModelSpec {
299    pub id: String,
300    #[serde(default, skip_serializing_if = "Option::is_none")]
301    pub context_window: Option<u64>,
302    /// The most `max_tokens` a call to this model is sent with, and the most
303    /// a reply cut off at its limit is retried with. Unset, the model's
304    /// documented limit, looked up by its id.
305    #[serde(default, skip_serializing_if = "Option::is_none")]
306    pub max_output: Option<u32>,
307    #[serde(default, skip_serializing_if = "Option::is_none")]
308    pub reasoning_levels: Option<Vec<String>>,
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub input_types: Option<Vec<String>>,
311}
312
313impl ModelEntry {
314    pub fn id(&self) -> &str {
315        match self {
316            Self::Id(id) => id,
317            Self::Spec(spec) => &spec.id,
318        }
319    }
320
321    pub fn spec(&self) -> Option<&ModelSpec> {
322        match self {
323            Self::Id(_) => None,
324            Self::Spec(spec) => Some(spec),
325        }
326    }
327}
328
329impl From<&str> for ModelEntry {
330    fn from(id: &str) -> Self {
331        Self::Id(id.to_string())
332    }
333}
334
335impl From<String> for ModelEntry {
336    fn from(id: String) -> Self {
337        Self::Id(id)
338    }
339}
340
341/// By hand rather than `untagged`, so a malformed entry says what is wrong
342/// with it instead of that it matched no variant.
343impl<'de> Deserialize<'de> for ModelEntry {
344    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
345        use serde::de::Error;
346        match serde_json::Value::deserialize(d)? {
347            serde_json::Value::String(id) => Ok(Self::Id(id)),
348            object @ serde_json::Value::Object(_) => serde_json::from_value(object)
349                .map(Self::Spec)
350                .map_err(|e| D::Error::custom(format!("a model entry: {e}"))),
351            _ => Err(D::Error::custom(
352                "a model entry is an id string or an object with `id`",
353            )),
354        }
355    }
356}
357
358impl ProviderConfig {
359    /// The id of the provider the engine supplies when the settings define
360    /// none.
361    pub const BUILTIN_ID: &'static str = "anthropic";
362
363    /// The provider used when the settings define none: Anthropic's API,
364    /// keyed and addressed from the environment, every tier `model`.
365    pub fn builtin(model: &str) -> Self {
366        Self {
367            id: Self::BUILTIN_ID.to_string(),
368            vendor: Vendor::Anthropic,
369            api: Some("anthropic".to_string()),
370            tiers: Tiers {
371                strong: Some(model.to_string()),
372                balanced: None,
373                fast: None,
374            },
375            builtin: true,
376            ..Default::default()
377        }
378    }
379
380    /// Why `id` cannot name a provider, if it cannot. The id is the name of
381    /// the provider's quota usage file as it stands, so it holds nothing a
382    /// file name would have to change — and no capital, since `Ab` and `ab`
383    /// are one file on a case-insensitive file system.
384    pub fn id_problem(id: &str) -> Option<String> {
385        if id.is_empty() {
386            return Some("a provider needs an `id`".to_string());
387        }
388        let fits = id
389            .bytes()
390            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_');
391        (!fits).then(|| {
392            format!("provider id `{id}` may hold only lowercase ASCII letters, digits, `-` and `_`")
393        })
394    }
395
396    /// `api`, defaulted.
397    pub fn api(&self) -> &str {
398        self.api.as_deref().unwrap_or("anthropic")
399    }
400
401    /// Whether `model` may be sent to this provider: listed, or nothing is.
402    pub fn accepts_model(&self, model: &str) -> bool {
403        self.models.is_empty() || self.models.iter().any(|m| m.id() == model)
404    }
405
406    /// Whether `models` lists `model`.
407    pub fn lists_model(&self, model: &str) -> bool {
408        self.models.iter().any(|m| m.id() == model)
409    }
410
411    pub fn model_ids(&self) -> Vec<&str> {
412        self.models.iter().map(ModelEntry::id).collect()
413    }
414
415    /// What `models` says about `model` beyond its id, if anything.
416    pub fn model_spec(&self, model: &str) -> Option<&ModelSpec> {
417        self.models
418            .iter()
419            .find(|m| m.id() == model)
420            .and_then(ModelEntry::spec)
421    }
422
423    /// The tiers with the gaps filled, or why this entry is not usable.
424    pub fn resolved_tiers(&self) -> Result<ResolvedTiers, String> {
425        let id = &self.id;
426        let strong = self
427            .tiers
428            .strong
429            .clone()
430            .filter(|m| !m.is_empty())
431            .ok_or_else(|| format!("provider `{id}` has no `tiers.strong`"))?;
432        let balanced = self
433            .tiers
434            .balanced
435            .clone()
436            .unwrap_or_else(|| strong.clone());
437        let fast = self.tiers.fast.clone().unwrap_or_else(|| balanced.clone());
438        let resolved = ResolvedTiers {
439            strong,
440            balanced,
441            fast,
442        };
443        if !self.models.is_empty() {
444            for tier in Tier::ALL {
445                let model = resolved.get(tier);
446                if !self.lists_model(model) {
447                    return Err(format!(
448                        "provider `{id}`: `tiers.{}` is `{model}`, which is not in its `models`",
449                        tier.as_str()
450                    ));
451                }
452            }
453        }
454        Ok(resolved)
455    }
456}
457
458/// One model a provider's endpoint lists, with only what the endpoint said.
459#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
460pub struct ListedModel {
461    pub id: String,
462    #[serde(default, skip_serializing_if = "Option::is_none")]
463    pub display_name: Option<String>,
464    #[serde(default, skip_serializing_if = "Option::is_none")]
465    pub context_window: Option<u64>,
466    #[serde(default, skip_serializing_if = "Option::is_none")]
467    pub max_output: Option<u32>,
468    #[serde(default, skip_serializing_if = "Option::is_none")]
469    pub input_types: Option<Vec<String>>,
470    /// Whether the model reasons, when the endpoint says.
471    #[serde(default, skip_serializing_if = "Option::is_none")]
472    pub reasoning: Option<bool>,
473}
474
475/// The tier each kind of model call asks for. The task types: `main` (the
476/// conversation), `subagent` (sub-agents started without a model of their
477/// own), `compact` (summarizing for compaction), `memory` (extracting
478/// memories), `title` (naming a session), `web_search` (`WebSearch`) and
479/// `web_fetch` (`WebFetch` reading a page — unset, `WebFetch` uses no model
480/// and returns the page text).
481#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
482#[serde(default, deny_unknown_fields)]
483pub struct TaskTiers {
484    /// Default `strong`.
485    pub main: Tier,
486    /// Default `balanced`.
487    pub subagent: Tier,
488    /// Default `fast`.
489    pub compact: Tier,
490    /// Default `fast`.
491    pub memory: Tier,
492    /// Default `fast`.
493    pub title: Tier,
494    /// Default `fast`.
495    pub web_search: Tier,
496    /// Default unset: no model reads fetched pages.
497    #[serde(skip_serializing_if = "Option::is_none")]
498    pub web_fetch: Option<Tier>,
499}
500
501impl Default for TaskTiers {
502    fn default() -> Self {
503        Self {
504            main: Tier::Strong,
505            subagent: Tier::Balanced,
506            compact: Tier::Fast,
507            memory: Tier::Fast,
508            title: Tier::Fast,
509            web_search: Tier::Fast,
510            web_fetch: None,
511        }
512    }
513}
514
515impl TaskTiers {
516    pub const MAIN: &'static str = "main";
517    pub const SUBAGENT: &'static str = "subagent";
518    pub const COMPACT: &'static str = "compact";
519    pub const MEMORY: &'static str = "memory";
520    pub const TITLE: &'static str = "title";
521    pub const WEB_SEARCH: &'static str = "web_search";
522    pub const WEB_FETCH: &'static str = "web_fetch";
523
524    /// The tier `task` asks for; `None` for a task with no model, or one not
525    /// in the list.
526    pub fn get(&self, task: &str) -> Option<Tier> {
527        match task {
528            Self::MAIN => Some(self.main),
529            Self::SUBAGENT => Some(self.subagent),
530            Self::COMPACT => Some(self.compact),
531            Self::MEMORY => Some(self.memory),
532            Self::TITLE => Some(self.title),
533            Self::WEB_SEARCH => Some(self.web_search),
534            Self::WEB_FETCH => self.web_fetch,
535            _ => None,
536        }
537    }
538}
539
540/// The providers `order` puts calls through, first to last, each with its
541/// tiers filled — or what is wrong with the configuration. Every defined
542/// provider is checked, ordered or not. An empty `order` is the first
543/// defined provider alone.
544pub fn routing_order<'a>(
545    providers: &'a [ProviderConfig],
546    order: &[String],
547) -> Result<Vec<(&'a ProviderConfig, ResolvedTiers)>, String> {
548    let mut resolved = Vec::with_capacity(providers.len());
549    for provider in providers {
550        if let Some(problem) = ProviderConfig::id_problem(&provider.id) {
551            return Err(problem);
552        }
553        resolved.push((provider, provider.resolved_tiers()?));
554    }
555    let Some(first) = providers.first() else {
556        return Err("no provider is defined".to_string());
557    };
558    let order: Vec<&str> = match order.is_empty() {
559        true => vec![first.id.as_str()],
560        false => order.iter().map(String::as_str).collect(),
561    };
562    let mut out: Vec<(&ProviderConfig, ResolvedTiers)> = Vec::with_capacity(order.len());
563    for id in order {
564        if out.iter().any(|(p, _)| p.id == id) {
565            continue;
566        }
567        let Some((provider, tiers)) = resolved.iter().find(|(p, _)| p.id == id) else {
568            return Err(format!(
569                "`model.order` names provider `{id}`, which no `providers` entry defines"
570            ));
571        };
572        out.push((provider, tiers.clone()));
573    }
574    Ok(out)
575}
576
577#[cfg(test)]
578mod tests;