mur_common/model.rs
1//! Named model registry shared by all agents.
2//!
3//! On disk: `~/.mur/models.yaml`. Schema:
4//!
5//! ```yaml
6//! schema_version: 1
7//! models:
8//! anthropic_opus_4_7:
9//! provider: anthropic
10//! model: claude-opus-4-7
11//! secret: env:ANTHROPIC_API_KEY
12//! capabilities: [chat, tools]
13//! ```
14
15use crate::route::{RoutePolicy, RouteTier};
16use crate::secret::SecretRef;
17use serde::{Deserialize, Serialize};
18use std::collections::BTreeMap;
19use std::path::{Path, PathBuf};
20
21/// Who pays when this model answers.
22///
23/// A ChatGPT-subscription model (`provider: codex`) and an OpenAI Platform
24/// model can share a model id and a wire format while landing on different
25/// bills, so the registry says which. `None` on entries written before this
26/// field existed — readers render that as unknown, never as free.
27#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
28#[serde(rename_all = "snake_case")]
29pub enum BillingMode {
30 /// Covered by a flat subscription (ChatGPT Plus/Pro via Codex).
31 Subscription,
32 /// Metered per token against an API key.
33 UsageBilled,
34 /// Runs on this machine; no bill.
35 Local,
36}
37
38#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
39pub struct ModelEntry {
40 #[serde(default)]
41 pub provider: String,
42 /// Who makes this model — the models.dev catalog vendor (`deepseek`,
43 /// `groq`, `mistral`, …).
44 ///
45 /// Distinct from `provider`, which is the wire protocol MUR dials: a
46 /// DeepSeek entry is `provider: openai` + `vendor: deepseek`, because the
47 /// runtime reaches it over the OpenAI protocol while the catalog files it
48 /// under DeepSeek. Only recorded when the two differ — for Anthropic,
49 /// OpenAI and Ollama the protocol already names the vendor.
50 ///
51 /// `None` on entries written before this field existed; readers should go
52 /// through [`ModelEntry::vendor_candidates`] rather than reading it raw.
53 #[serde(default, skip_serializing_if = "Option::is_none")]
54 pub vendor: Option<String>,
55 #[serde(default)]
56 pub model: String,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub base_url: Option<String>,
59 #[serde(default, skip_serializing_if = "Option::is_none")]
60 pub secret: Option<SecretRef>,
61 #[serde(default, skip_serializing_if = "Vec::is_empty")]
62 pub capabilities: Vec<String>,
63 #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
64 pub params: serde_json::Value,
65 /// Routing tier: cheap/local vs frontier/expensive.
66 /// When absent, the router infers based on provider.
67 #[serde(default, skip_serializing_if = "Option::is_none")]
68 pub tier: Option<RouteTier>,
69 /// Estimated USD cost per 1000 output tokens.
70 /// Used for ledger cost estimates.
71 #[serde(default, skip_serializing_if = "Option::is_none")]
72 pub cost_per_1k_tokens: Option<f64>,
73 /// Estimated USD cost per 1000 input tokens.
74 /// New field for split input/output cost tracking.
75 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub input_cost_per_1k: Option<f64>,
77 /// Estimated USD cost per 1000 output tokens.
78 /// New field for split input/output cost tracking.
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub output_cost_per_1k: Option<f64>,
81 /// Estimated USD cost per 1000 prompt tokens served from the provider's
82 /// prompt cache. `None` = unknown: cost accounting then prices a cached
83 /// token at the full input rate, which is an upper bound.
84 #[serde(default, skip_serializing_if = "Option::is_none")]
85 pub cache_read_cost_per_1k: Option<f64>,
86 /// Estimated USD cost per 1000 prompt tokens written to the provider's
87 /// prompt cache (Anthropic bills these above the input rate). `None` =
88 /// unknown: priced at the input rate.
89 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub cache_write_cost_per_1k: Option<f64>,
91 /// Model context window size in tokens.
92 #[serde(default, skip_serializing_if = "Option::is_none")]
93 pub context_window: Option<u64>,
94 /// Output-token ceiling sent on every request to this model that does not
95 /// set its own.
96 ///
97 /// On models with extended thinking this budget covers thinking AND the
98 /// visible reply together, so a high `effort` can spend all of it before
99 /// any text is produced. `None` leaves the provider client's own default
100 /// in place (the Anthropic client's built-in constant; nothing at all for
101 /// OpenAI-protocol clients, which then get the server's default). A
102 /// request that names its own `max_tokens` keeps it — this is a default,
103 /// not a clamp.
104 #[serde(default, skip_serializing_if = "Option::is_none")]
105 pub max_tokens: Option<u32>,
106 /// When the rates above were recorded.
107 ///
108 /// Vendors move prices; a rate written months ago is a guess wearing the
109 /// costume of a fact, and nothing else on this struct can tell the two
110 /// apart. `None` means unknown — entries predating this field, or hand-
111 /// written ones — which is honest rather than defaulting to "fresh".
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub priced_at: Option<chrono::DateTime<chrono::Utc>>,
114 /// See [`BillingMode`]. `None` = unknown.
115 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub billing: Option<BillingMode>,
117 /// Whether the model id came from the provider's live catalog
118 /// (`Some(true)`) or was typed by hand when discovery failed
119 /// (`Some(false)`). `None` on entries that predate the field.
120 #[serde(default, skip_serializing_if = "Option::is_none")]
121 pub catalog_verified: Option<bool>,
122}
123
124/// Vendor label implied by an endpoint host: `https://api.deepseek.com/v1` →
125/// `deepseek`. Best-effort — a host that does not carry the vendor's name
126/// (Google's `generativelanguage.googleapis.com`) yields the wrong label,
127/// which is why `vendor` is recorded explicitly on new entries.
128fn vendor_label_of_url(base_url: Option<&str>) -> Option<String> {
129 let host = base_url?
130 .split("//")
131 .nth(1)
132 .unwrap_or(base_url?)
133 .split(['/', ':'])
134 .next()
135 .unwrap_or("");
136 let label = host.strip_prefix("api.").unwrap_or(host);
137 let first = label.split('.').next().unwrap_or("");
138 (!first.is_empty()).then(|| first.to_string())
139}
140
141const LOCAL_MODEL_PROVIDERS: &[&str] = &[
142 "ollama",
143 "mlx",
144 "llamacpp",
145 "llama_cpp",
146 "localai",
147 "lmstudio",
148 "local",
149];
150
151/// Whether a provider is a known in-process or on-machine model backend.
152pub fn provider_is_local(provider: &str) -> bool {
153 LOCAL_MODEL_PROVIDERS.contains(&provider.to_ascii_lowercase().as_str())
154}
155
156/// Canonical billing inference for registry entries without explicit metadata.
157pub fn inferred_billing_for_provider(provider: &str) -> BillingMode {
158 if provider_is_local(provider) {
159 BillingMode::Local
160 } else if matches!(provider.to_ascii_lowercase().as_str(), "codex" | "claude") {
161 BillingMode::Subscription
162 } else {
163 BillingMode::UsageBilled
164 }
165}
166
167impl ModelEntry {
168 /// How this model is paid for, for the cost gates. An explicit `billing:`
169 /// is the answer; without one the provider decides what it can:
170 /// `ollama` runs on this machine, `codex` and `claude` ride a flat
171 /// subscription. Everything else — including a loopback `base_url`, which
172 /// is just as often the model gateway fronting a metered API — is treated
173 /// as metered. Guessing "free" is the one mistake a cost gate must not
174 /// make; a wrong "metered" costs the user one line in `models.yaml`
175 /// (`billing: local`), and the gate says so when it applies.
176 pub fn billing_or_inferred(&self) -> BillingMode {
177 self.billing
178 .unwrap_or_else(|| inferred_billing_for_provider(&self.provider))
179 }
180
181 /// Effective route tier, honoring an explicit registry tier first.
182 pub fn effective_route_tier(&self) -> RouteTier {
183 self.tier.unwrap_or_else(|| {
184 if provider_is_local(&self.provider) {
185 RouteTier::Local
186 } else {
187 RouteTier::Frontier
188 }
189 })
190 }
191 /// Resolve effective per-1k rates as `(input, output)`.
192 ///
193 /// The deprecated `cost_per_1k_tokens` is treated as the output rate and
194 /// also as the input fallback, so legacy single-rate entries keep working.
195 pub fn effective_costs(&self) -> (Option<f64>, Option<f64>) {
196 let output = self.output_cost_per_1k.or(self.cost_per_1k_tokens);
197 let input = self.input_cost_per_1k.or(self.cost_per_1k_tokens);
198 (input, output)
199 }
200
201 /// Projected USD cost for a token workload. A known rate on only one side
202 /// is used for the other side; no rates remains unknown rather than free.
203 pub fn projected_cost(&self, input_tokens: u64, output_tokens: u64) -> Option<f64> {
204 self.cost_with_cache(input_tokens, 0, 0, output_tokens)
205 }
206
207 /// USD cost of real usage whose prompt is split by cache use.
208 ///
209 /// `input_tokens` is the whole prompt, cached or not — what
210 /// `LlmResponse::input_tokens` reports — and `cache_read` / `cache_write`
211 /// are the parts of it served from and written to the provider cache. A
212 /// cache rate the entry lacks falls back to its input rate. A split larger
213 /// than the prompt is clamped, so no token is priced twice. `None` when
214 /// the entry has no rates at all.
215 pub fn cost_with_cache(
216 &self,
217 input_tokens: u64,
218 cache_read: u64,
219 cache_write: u64,
220 output_tokens: u64,
221 ) -> Option<f64> {
222 let (input, output) = self.effective_costs();
223 let fallback = input.or(output)?;
224 let input = input.unwrap_or(fallback);
225 let output = output.unwrap_or(fallback);
226 let read = cache_read.min(input_tokens);
227 let write = cache_write.min(input_tokens - read);
228 let uncached = input_tokens - read - write;
229 let per_1k = |tokens: u64, rate: f64| tokens as f64 / 1_000.0 * rate;
230 Some(
231 per_1k(uncached, input)
232 + per_1k(read, self.cache_read_cost_per_1k.unwrap_or(input))
233 + per_1k(write, self.cache_write_cost_per_1k.unwrap_or(input))
234 + per_1k(output_tokens, output),
235 )
236 }
237
238 /// Catalog vendor names to try for this entry, most specific first.
239 ///
240 /// The recorded `vendor` wins. Failing that — legacy entries, or anything
241 /// written by hand — the host of `base_url` is tried
242 /// (`https://api.deepseek.com` → `deepseek`), then `provider`, which names
243 /// the vendor only when the vendor happens to have its own client.
244 ///
245 /// Every caller that asks an external catalog about an entry must go
246 /// through this. Asking with `provider` alone reports every
247 /// OpenAI-compatible third party as unknown.
248 pub fn vendor_candidates(&self) -> Vec<String> {
249 let mut out: Vec<String> = Vec::with_capacity(3);
250 let mut push = |v: &str| {
251 if !v.is_empty() && !out.iter().any(|e| e == v) {
252 out.push(v.to_string());
253 }
254 };
255 if let Some(v) = self.vendor.as_deref() {
256 push(v);
257 }
258 if let Some(label) = vendor_label_of_url(self.base_url.as_deref()) {
259 push(&label);
260 }
261 push(&self.provider);
262 out
263 }
264
265 /// Whether this entry carries any rate at all.
266 pub fn is_priced(&self) -> bool {
267 let (input, output) = self.effective_costs();
268 input.is_some() || output.is_some()
269 }
270
271 /// Stamp `priced_at` with `now`, but only if a rate is actually present —
272 /// a date on an unpriced entry would claim a freshness it does not have.
273 /// Never overwrites an existing stamp with an older one.
274 pub fn stamp_priced_at(&mut self, now: chrono::DateTime<chrono::Utc>) {
275 if self.is_priced() && self.priced_at.is_none_or(|prev| prev < now) {
276 self.priced_at = Some(now);
277 }
278 }
279
280 /// How long ago the rates were recorded, or `None` when unstamped.
281 pub fn price_age(&self, now: chrono::DateTime<chrono::Utc>) -> Option<chrono::TimeDelta> {
282 self.priced_at.map(|at| now - at)
283 }
284}
285
286#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
287pub struct RoleEntry {
288 /// Registry model ID (key in `models:`) to use as primary.
289 pub primary: String,
290 /// Fallback model ID if primary is unavailable.
291 #[serde(default, skip_serializing_if = "Option::is_none")]
292 pub fallback: Option<String>,
293 /// Optional daily cost cap in USD.
294 #[serde(default, skip_serializing_if = "Option::is_none")]
295 pub cost_budget_per_day_usd: Option<f64>,
296 /// If true, only use local models when handling sensitive data.
297 #[serde(default)]
298 pub privacy_local_only: bool,
299 /// Per-role routing policy override.
300 /// When absent, the router uses the default heuristic.
301 #[serde(default, skip_serializing_if = "Option::is_none")]
302 pub route_policy: Option<RoutePolicy>,
303}
304
305#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
306pub struct ModelRegistry {
307 pub schema_version: u32,
308 #[serde(default)]
309 pub models: BTreeMap<String, ModelEntry>,
310 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
311 pub roles: BTreeMap<String, RoleEntry>,
312}
313
314impl Default for ModelRegistry {
315 fn default() -> Self {
316 Self {
317 schema_version: 1,
318 models: BTreeMap::new(),
319 roles: BTreeMap::new(),
320 }
321 }
322}
323
324impl ModelRegistry {
325 pub fn load_from(path: &Path) -> anyhow::Result<Self> {
326 if !path.exists() {
327 return Ok(Self::default());
328 }
329 let body = std::fs::read_to_string(path)?;
330 if body.trim().is_empty() {
331 return Ok(Self::default());
332 }
333 Ok(serde_yaml_ng::from_str(&body)?)
334 }
335
336 pub fn save_to(&self, path: &Path) -> anyhow::Result<()> {
337 if let Some(parent) = path.parent() {
338 std::fs::create_dir_all(parent)?;
339 }
340 let body = serde_yaml_ng::to_string(self)?;
341 let tmp = path.with_extension("yaml.tmp");
342 std::fs::write(&tmp, body)?;
343 std::fs::rename(&tmp, path)?;
344 Ok(())
345 }
346
347 pub fn default_path() -> anyhow::Result<PathBuf> {
348 // Honor MUR_HOME (used by test harnesses and Windows CI, where
349 // `dirs::home_dir()` reads SHGetKnownFolderPath and ignores HOME).
350 Ok(crate::home::mur_home_or_err()?.join("models.yaml"))
351 }
352
353 /// Return the primary model ID for `role`, or the fallback if the primary
354 /// is not in the `models` map, or `None` if the role is not configured.
355 pub fn resolve_role(&self, role: &str) -> Option<&str> {
356 let entry = self.roles.get(role)?;
357 if self.models.contains_key(&entry.primary) {
358 return Some(&entry.primary);
359 }
360 // primary not in registry — try fallback
361 if let Some(fb) = &entry.fallback
362 && self.models.contains_key(fb)
363 {
364 return Some(fb);
365 }
366 // role configured but no available model
367 None
368 }
369}
370
371use crate::agent::AgentProfile;
372use crate::config::{DEFAULT_ROUTING_THRESHOLD, ModelSwitchConfig, RoutingConfig};
373
374/// Build the ordered list of model_refs to try: `[primary, ...fallback]`.
375/// Priority per-agent → global. The primary is de-duplicated out of the chain
376/// (no point retrying the same ref back-to-back). Returns empty when nothing is
377/// configured, so the caller keeps today's single-inline-model behaviour.
378pub fn resolve_model_refs(
379 profile: &AgentProfile,
380 cfg: &ModelSwitchConfig,
381 routed_primary: Option<String>,
382) -> Vec<String> {
383 let primary = routed_primary
384 .or_else(|| profile.model_ref.clone())
385 .or_else(|| cfg.default.clone());
386 let chain = if !profile.fallback_chain.is_empty() {
387 profile.fallback_chain.clone()
388 } else {
389 cfg.fallback_chain.clone()
390 };
391 let mut out: Vec<String> = Vec::new();
392 if let Some(p) = primary {
393 out.push(p);
394 }
395 for r in chain {
396 if !out.contains(&r) {
397 out.push(r);
398 }
399 }
400 out
401}
402
403/// Opt-in difficulty heuristic: pick `frontier` when the estimated input token
404/// count exceeds the threshold, else `cheap`. `None` when misconfigured (caller
405/// falls through to model_ref/global default).
406pub fn choose_by_difficulty(est_input_tokens: u32, r: &RoutingConfig) -> Option<String> {
407 let threshold = r
408 .threshold_input_tokens
409 .unwrap_or(DEFAULT_ROUTING_THRESHOLD);
410 match (r.cheap.as_ref(), r.frontier.as_ref()) {
411 (Some(cheap), Some(frontier)) => Some(if est_input_tokens > threshold {
412 frontier.clone()
413 } else {
414 cheap.clone()
415 }),
416 _ => None,
417 }
418}
419
420/// Registry capability strings. The baseline (`chat`) is legacy-permissive —
421/// an entry with no `capabilities` at all predates the field and is assumed
422/// chat-capable. Everything above the baseline is fail-closed.
423pub const CAP_CHAT: &str = "chat";
424pub const CAP_TOOLS: &str = "tools";
425pub const CAP_VISION: &str = "vision";
426
427/// A capability the request needs from whatever model serves it. Derived from
428/// the request itself (an image in the messages, a tool list) and never from
429/// config: a router may only substitute a model that can do the job.
430#[derive(Debug, Clone, Copy, PartialEq, Eq)]
431pub enum Requirement {
432 /// The request carries an image; the model has to be able to see it.
433 Vision,
434 /// The request declares tools; the model has to be able to call them.
435 Tools,
436}
437
438impl Requirement {
439 /// The registry capability an entry must declare to satisfy this.
440 pub fn capability(self) -> &'static str {
441 match self {
442 Requirement::Vision => CAP_VISION,
443 Requirement::Tools => CAP_TOOLS,
444 }
445 }
446
447 /// Does an entry that declares NO capabilities at all satisfy this?
448 ///
449 /// The two requirements differ in how they fail, and the answer follows
450 /// the failure mode rather than a blanket rule:
451 ///
452 /// - `Vision`: **no**. A model that cannot see answers an image request
453 /// with confident nonsense — silent, and unrecoverable for that turn.
454 /// That is the failure this gate exists to prevent, so silence about
455 /// vision is treated as absence of it.
456 /// - `Tools`: **yes**. A model that cannot call tools fails loudly (the
457 /// provider rejects the request) and the existing retry/advance path
458 /// already handles it. Treating undeclared as incapable would drop every
459 /// entry written before `capabilities` existed — in practice most of a
460 /// real registry — out of the fallback chain of every tool-carrying turn,
461 /// which is a large regression bought for very little.
462 ///
463 /// An entry that DOES declare capabilities is taken at its word either
464 /// way: if it enumerated what it can do and left `tools` out, that is a
465 /// statement, not silence.
466 fn permitted_when_undeclared(self) -> bool {
467 match self {
468 Requirement::Vision => false,
469 Requirement::Tools => true,
470 }
471 }
472}
473
474/// Can this entry serve a request needing `reqs`?
475///
476/// No registry write path emits `vision` today, so a `Vision` requirement
477/// disqualifies every current entry — auto-substitution goes inert for image
478/// requests rather than answering them blind. The same code makes a finer
479/// distinction the day entries start declaring it; there is no second version
480/// of this function to write later.
481pub fn satisfies(e: &ModelEntry, reqs: &[Requirement]) -> bool {
482 let chat_capable = e.capabilities.is_empty() || e.capabilities.iter().any(|c| c == CAP_CHAT);
483 if !chat_capable {
484 return false;
485 }
486 reqs.iter().all(|r| {
487 if e.capabilities.is_empty() {
488 r.permitted_when_undeclared()
489 } else {
490 e.capabilities.iter().any(|c| c == r.capability())
491 }
492 })
493}
494
495/// Pick the cheapest registry entry that can serve a request needing `reqs`,
496/// excluding `exclude` (the agent's own primary). None when no qualifying
497/// entry exists → caller keeps normal candidates (fail-expensive).
498pub fn pick_cheap_model(
499 reg: &ModelRegistry,
500 exclude: Option<&str>,
501 reqs: &[Requirement],
502) -> Option<String> {
503 reg.models
504 .iter()
505 .filter(|(k, _)| exclude != Some(k.as_str()))
506 .filter(|(_, e)| satisfies(e, reqs))
507 .filter_map(|(k, e)| e.projected_cost(4_000, 1_000).map(|c| (c, k.clone())))
508 .min_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal))
509 .map(|(_, k)| k)
510}
511
512#[cfg(test)]
513mod tests;
514
515#[cfg(test)]
516mod io_tests;
517
518#[cfg(test)]
519mod switch_tests;