1use crate::prices::Sort;
3use anyhow::{Context, Result, ensure};
4use reqwest::{Url, blocking::Client, redirect::Policy};
5use rust_decimal::Decimal;
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use std::{
9 collections::{BTreeMap, BTreeSet},
10 fs,
11 io::Read,
12 path::Path,
13 str::FromStr,
14 time::Duration,
15};
16
17#[derive(Deserialize)]
18#[serde(deny_unknown_fields)]
19pub struct CatalogMap {
20 pub url: String,
21 pub source: String,
22 pub providers: String,
23 pub models: String,
24 pub provider_models: String,
25 pub canonical_id: String,
26 pub cost: String,
27 #[serde(default)]
28 pub direct_providers: BTreeMap<String, String>,
29 #[serde(default)]
30 pub vendor_aliases: BTreeMap<String, String>,
31}
32impl CatalogMap {
33 pub fn load(root: &Path) -> Result<Self> {
34 let path = root.join("providers/catalogs/models-dev.toml");
35 let text = if path.exists() {
36 ensure!(
37 path.is_file() && !path.is_symlink(),
38 "Catalog definition must be a regular file"
39 );
40 fs::read_to_string(path).context("Could not read catalog definition")?
41 } else {
42 include_str!("../providers/catalogs/models-dev.toml").to_owned()
43 };
44 toml::from_str(&text).context("Invalid catalog definition")
45 }
46 pub fn endpoint(&self, local: bool) -> Result<Url> {
47 let url = Url::parse(&self.url).context("Invalid pricing catalog URL")?;
48 ensure!(
49 url.username().is_empty() && url.password().is_none() && url.fragment().is_none(),
50 "Catalog URL must not contain credentials or a fragment"
51 );
52 ensure!(
53 url.scheme() == "https"
54 || (local
55 && url.scheme() == "http"
56 && matches!(url.host_str(), Some("127.0.0.1" | "[::1]"))),
57 "Catalog requires HTTPS; loopback fixtures need --allow-local-http"
58 );
59 for pointer in [
60 &self.providers,
61 &self.models,
62 &self.provider_models,
63 &self.canonical_id,
64 &self.cost,
65 ] {
66 ensure!(
67 pointer.starts_with('/'),
68 "Catalog mapping requires JSON pointers"
69 );
70 }
71 for (k, v) in self
72 .direct_providers
73 .iter()
74 .chain(self.vendor_aliases.iter())
75 {
76 ensure!(
77 namespace(k) && namespace(v),
78 "Invalid catalog vendor mapping"
79 );
80 }
81 ensure!(
82 safe_url(&self.source).is_some(),
83 "Catalog source must be an HTTPS URL without credentials"
84 );
85 Ok(url)
86 }
87}
88#[derive(Default)]
89pub struct Filter<'a> {
90 pub query: Option<&'a str>,
91 pub vendor: Option<&'a str>,
92 pub provider: Option<&'a str>,
93}
94#[derive(Serialize)]
95pub struct Rates {
96 pub input_per_million: Option<String>,
97 pub output_per_million: Option<String>,
98 pub cache_read_per_million: Option<String>,
99 pub cache_write_per_million: Option<String>,
100}
101#[derive(Serialize)]
102pub struct Tier {
103 pub context_over: u64,
104 pub rates: Rates,
105}
106#[derive(Serialize)]
107pub struct Offer {
108 pub provider: String,
109 pub provider_name: String,
110 pub model_id: String,
111 pub direct: bool,
112 pub rates: Rates,
113 pub tiers: Vec<Tier>,
114 pub status: Option<String>,
115 pub note: Option<String>,
116 pub provider_url: Option<String>,
117 pub catalog_model_updated: Option<String>,
118}
119#[derive(Serialize)]
120pub struct Model {
121 pub id: String,
122 pub name: String,
123 pub vendor: Option<String>,
124 pub family: Option<String>,
125 pub offers: Vec<Offer>,
126}
127#[derive(Serialize)]
128pub struct Report {
129 pub source: String,
130 pub observed_at: u64,
131 pub currency: &'static str,
132 pub sort: Sort,
133 pub unlinked_offers: usize,
134 pub models: Vec<Model>,
135}
136fn norm(s: &str) -> String {
137 s.to_lowercase()
138 .chars()
139 .filter(|c| c.is_alphanumeric())
140 .collect()
141}
142fn clean(s: &str) -> bool {
143 !s.is_empty() && s.len() <= 512 && !s.chars().any(char::is_control)
144}
145fn label(value: &Value, key: &str) -> Option<String> {
146 value
147 .get(key)
148 .and_then(Value::as_str)
149 .filter(|s| clean(s))
150 .map(str::to_owned)
151}
152fn safe_url(s: &str) -> Option<String> {
153 let url = Url::parse(s).ok()?;
154 (clean(s) && url.scheme() == "https" && url.username().is_empty() && url.password().is_none())
155 .then(|| s.to_owned())
156}
157fn rate(value: &Value, key: &str) -> Option<String> {
158 let raw = value.get(key)?;
159 let text = match raw {
160 Value::String(s) => s.clone(),
161 Value::Number(n) => n.to_string(),
162 _ => return None,
163 };
164 let number = Decimal::from_str(&text)
165 .or_else(|_| Decimal::from_scientific(&text))
166 .ok()?;
167 (!number.is_sign_negative()).then(|| number.normalize().to_string())
168}
169fn rates(cost: &Value, text_tokens: bool) -> Rates {
170 let get = |k| if text_tokens { rate(cost, k) } else { None };
171 Rates {
172 input_per_million: get("input"),
173 output_per_million: get("output"),
174 cache_read_per_million: get("cache_read"),
175 cache_write_per_million: get("cache_write"),
176 }
177}
178fn price(rates: &Rates, sort: Sort) -> Option<Decimal> {
179 match sort {
180 Sort::Input => &rates.input_per_million,
181 Sort::Output => &rates.output_per_million,
182 }
183 .as_deref()
184 .and_then(|s| Decimal::from_str(s).ok())
185}
186fn namespace(value: &str) -> bool {
187 !value.is_empty()
188 && value.len() <= 128
189 && value
190 .bytes()
191 .all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b))
192}
193fn canonical(value: &str) -> bool {
194 value
195 .split_once('/')
196 .is_some_and(|(vendor, model)| namespace(vendor) && clean(model))
197}
198pub fn extract(value: &Value, map: &CatalogMap, filter: &Filter<'_>, sort: Sort) -> Result<Report> {
199 for s in [filter.query, filter.vendor, filter.provider]
200 .into_iter()
201 .flatten()
202 {
203 ensure!(
204 !norm(s).is_empty(),
205 "Model, vendor and provider filters cannot be empty"
206 );
207 }
208 ensure!(
209 filter.query.is_some() || filter.vendor.is_some() || filter.provider.is_some(),
210 "Specify a model/family, --vendor, or --provider"
211 );
212 let providers = value
213 .pointer(&map.providers)
214 .and_then(Value::as_object)
215 .context("Pricing catalog provider map missing")?;
216 let metadata = value
217 .pointer(&map.models)
218 .and_then(Value::as_object)
219 .context("Pricing catalog model map missing")?;
220 let vendors: BTreeSet<&str> = metadata
221 .keys()
222 .filter_map(|id| id.split_once('/').map(|(v, _)| v))
223 .collect();
224 let requested_vendor = filter.vendor.map(|v| {
225 map.vendor_aliases
226 .iter()
227 .find(|(k, _)| norm(k) == norm(v))
228 .map(|(_, v)| v.clone())
229 .unwrap_or_else(|| v.to_lowercase())
230 });
231 let mut groups: BTreeMap<String, Model> = BTreeMap::new();
232 let mut unlinked_offers = 0;
233 for (provider_id, provider) in providers {
234 ensure!(namespace(provider_id), "Invalid pricing provider identity");
235 let provider_name = label(provider, "name").unwrap_or_else(|| provider_id.clone());
236 if filter
237 .provider
238 .is_some_and(|p| norm(p) != norm(provider_id) && norm(p) != norm(&provider_name))
239 {
240 continue;
241 }
242 let models = provider
243 .pointer(&map.provider_models)
244 .and_then(Value::as_object)
245 .context("Pricing catalog provider models missing")?;
246 let direct_vendor = map
247 .direct_providers
248 .get(provider_id)
249 .map(String::as_str)
250 .or_else(|| {
251 vendors
252 .contains(provider_id.as_str())
253 .then_some(provider_id.as_str())
254 });
255 for (model_id, offering) in models {
256 ensure!(clean(model_id), "Invalid pricing model identity");
257 let linked = match offering.pointer(&map.canonical_id) {
258 Some(Value::String(id)) => {
259 ensure!(canonical(id), "Invalid canonical model identity");
260 Some(id.clone())
261 }
262 None | Some(Value::Null) => None,
263 _ => anyhow::bail!("Invalid canonical model identity"),
264 };
265 let linked = linked
267 .or_else(|| metadata.contains_key(model_id).then(|| model_id.clone()))
268 .or_else(|| {
269 vendors.contains(provider_id.as_str()).then(|| {
270 if model_id.starts_with(&format!("{provider_id}/")) {
271 model_id.clone()
272 } else {
273 format!("{provider_id}/{model_id}")
274 }
275 })
276 });
277 let vendor = linked
278 .as_deref()
279 .and_then(|id| id.split_once('/').map(|(v, _)| v.to_owned()));
280 if vendor.is_none() {
281 unlinked_offers += 1;
282 }
283 if requested_vendor
284 .as_ref()
285 .is_some_and(|v| vendor.as_ref().is_none_or(|actual| norm(v) != norm(actual)))
286 {
287 continue;
288 }
289 let id = linked
290 .clone()
291 .unwrap_or_else(|| format!("unlinked:{provider_id}/{model_id}"));
292 let meta = linked.as_ref().and_then(|id| metadata.get(id));
293 let name = meta
294 .and_then(|m| label(m, "name"))
295 .or_else(|| label(offering, "name"))
296 .unwrap_or_else(|| model_id.clone());
297 let family = meta
298 .and_then(|m| label(m, "family"))
299 .or_else(|| label(offering, "family"));
300 let outputs = offering
301 .pointer("/modalities/output")
302 .and_then(Value::as_array);
303 let text_tokens = outputs
304 .is_some_and(|a| !a.is_empty() && a.iter().all(|s| s.as_str() == Some("text")));
305 let cost = offering.pointer(&map.cost).unwrap_or(&Value::Null);
306 let mut note = (!text_tokens).then(|| {
307 "Non-text or unspecified output: token rates unavailable; see provider pricing"
308 .to_owned()
309 });
310 let mut tiers = Vec::new();
311 if let Some(raw) = cost.get("tiers") {
312 let raw = raw.as_array().context("Invalid pricing tiers")?;
313 for tier in raw {
314 let threshold = tier
315 .pointer("/tier/size")
316 .and_then(Value::as_u64)
317 .context("Context tier threshold missing")?;
318 ensure!(
319 tier.pointer("/tier/type")
320 .and_then(Value::as_str)
321 .is_none_or(|v| v == "context"),
322 "Unsupported pricing tier type"
323 );
324 ensure!(
325 !tiers.iter().any(|t: &Tier| t.context_over == threshold),
326 "Duplicate context tier"
327 );
328 tiers.push(Tier {
329 context_over: threshold,
330 rates: rates(tier, text_tokens),
331 });
332 }
333 } else if let Some(tier) = cost.get("context_over_200k") {
334 tiers.push(Tier {
335 context_over: 200_000,
336 rates: rates(tier, text_tokens),
337 });
338 }
339 tiers.sort_by_key(|t| t.context_over);
340 if offering.pointer("/experimental/modes").is_some() {
341 let extra = "Mode-specific prices may differ; see provider pricing";
342 note = Some(
343 note.map(|n| format!("{n}; {extra}"))
344 .unwrap_or_else(|| extra.into()),
345 );
346 }
347 let direct = vendor
348 .as_deref()
349 .is_some_and(|v| v == provider_id || direct_vendor == Some(v));
350 let group = groups.entry(id.clone()).or_insert_with(|| Model {
351 id,
352 name,
353 vendor,
354 family,
355 offers: Vec::new(),
356 });
357 group.offers.push(Offer {
358 provider: provider_id.clone(),
359 provider_name: provider_name.clone(),
360 model_id: model_id.clone(),
361 direct,
362 rates: rates(cost, text_tokens),
363 tiers,
364 status: label(offering, "status"),
365 note,
366 provider_url: provider
367 .get("doc")
368 .and_then(Value::as_str)
369 .and_then(safe_url),
370 catalog_model_updated: label(offering, "last_updated"),
371 });
372 }
373 }
374 let mut models: Vec<Model> = groups.into_values().collect();
375 if let Some(query) = filter.query {
376 let q = norm(query);
377 let exact = |m: &Model| {
378 norm(&m.id) == q
379 || norm(m.id.split_once('/').map(|(_, s)| s).unwrap_or(&m.id)) == q
380 || norm(&m.name) == q
381 || m.offers.iter().any(|o| norm(&o.model_id) == q)
382 };
383 if models.iter().any(exact) {
384 models.retain(exact);
385 } else {
386 models.retain(|m| {
387 norm(&m.id).contains(&q)
388 || norm(&m.name).contains(&q)
389 || m.family.as_ref().is_some_and(|f| norm(f).contains(&q))
390 || m.offers.iter().any(|o| norm(&o.model_id).contains(&q))
391 });
392 }
393 }
394 for m in &mut models {
395 let vendor = m.vendor.as_deref().unwrap_or("");
396 m.offers.sort_by(|a, b| {
397 (b.provider == vendor)
398 .cmp(&(a.provider == vendor))
399 .then_with(|| b.direct.cmp(&a.direct))
400 .then_with(|| price(&b.rates, sort).cmp(&price(&a.rates, sort)))
401 .then_with(|| a.provider.cmp(&b.provider))
402 .then_with(|| a.model_id.cmp(&b.model_id))
403 });
404 }
405 let key = |m: &Model| m.offers.iter().find_map(|o| price(&o.rates, sort));
406 models.sort_by(|a, b| key(b).cmp(&key(a)).then_with(|| a.id.cmp(&b.id)));
407 ensure!(
408 !models.is_empty(),
409 "No models matched the model/vendor/provider filters"
410 );
411 Ok(Report {
412 source: map.source.clone(),
413 observed_at: crate::state::now(),
414 currency: "USD",
415 sort,
416 unlinked_offers,
417 models,
418 })
419}
420pub fn fetch(map: &CatalogMap, filter: &Filter<'_>, sort: Sort, local: bool) -> Result<Report> {
421 let endpoint = map.endpoint(local)?;
422 let client = Client::builder()
423 .timeout(Duration::from_secs(30))
424 .connect_timeout(Duration::from_secs(5))
425 .redirect(Policy::none())
426 .build()?;
427 let response = client
428 .get(endpoint)
429 .send()
430 .map_err(|_| anyhow::anyhow!("Pricing catalog request failed or timed out"))?;
431 ensure!(
432 response.status().is_success(),
433 "Pricing catalog returned HTTP {}",
434 response.status().as_u16()
435 );
436 let mut body = Vec::new();
437 response
438 .take(32 * 1024 * 1024 + 1)
439 .read_to_end(&mut body)
440 .context("Could not read pricing catalog")?;
441 ensure!(
442 body.len() <= 32 * 1024 * 1024,
443 "Pricing catalog exceeds size limit"
444 );
445 let value = serde_json::from_slice(&body)
446 .map_err(|_| anyhow::anyhow!("Pricing catalog did not return valid JSON"))?;
447 extract(&value, map, filter, sort)
448}
449fn row(label: &str, rates: &Rates) -> String {
450 format!(
451 " {label:<44} {:>12} {:>12} {:>12}\n",
452 rates.input_per_million.as_deref().unwrap_or("n/a"),
453 rates.output_per_million.as_deref().unwrap_or("n/a"),
454 rates.cache_read_per_million.as_deref().unwrap_or("n/a")
455 )
456}
457pub fn table(report: &Report) -> String {
458 let mut out = format!(
459 "USD / 1M text tokens — direct vendor offers first\nCatalog: {} (fetched at Unix {})\n",
460 report.source, report.observed_at
461 );
462 out.push_str("Listed catalog offers only; rates may lag vendor changes. Subscription fees, non-token charges and discounts are excluded.\n");
463 for model in &report.models {
464 out.push_str(&format!("\n{} — {}\n", model.id, model.name));
465 out.push_str(&format!(
466 " {:<44} {:>12} {:>12} {:>12}\n",
467 "PROVIDER / CONTEXT", "INPUT", "OUTPUT", "CACHE READ"
468 ));
469 if !model.offers.iter().any(|o| o.direct) {
470 out.push_str(" Direct vendor offer not available in these results.\n");
471 }
472 for offer in &model.offers {
473 let label = format!(
474 "{}{} [{}]",
475 offer.provider_name,
476 if offer.direct { " (direct)" } else { "" },
477 offer.model_id
478 );
479 out.push_str(&row(&label, &offer.rates));
480 if let Some(first) = offer.tiers.first() {
481 out.push_str(&format!(
482 " Base rates above: context <= {} tokens\n",
483 first.context_over
484 ));
485 }
486 for (i, tier) in offer.tiers.iter().enumerate() {
487 let upper = offer
488 .tiers
489 .get(i + 1)
490 .map(|t| format!(" to {}", t.context_over))
491 .unwrap_or_default();
492 out.push_str(&row(
493 &format!(" context > {}{upper}", tier.context_over),
494 &tier.rates,
495 ));
496 }
497 if let Some(status) = &offer.status {
498 out.push_str(&format!(" Status: {status}\n"));
499 }
500 if let Some(note) = &offer.note {
501 out.push_str(&format!(" {note}\n"));
502 }
503 if let Some(url) = &offer.provider_url {
504 out.push_str(&format!(" Provider details: {url}\n"));
505 }
506 }
507 }
508 if report.unlinked_offers > 0 {
509 out.push_str(&format!("\n{} catalog offers lack a canonical vendor identity; they remain separate and cannot match --vendor.\n",report.unlinked_offers));
510 }
511 out
512}