返回 CodeWhale
catalog_models_dev.py
根目录 / scripts / catalog / catalog_models_dev.py
1 #!/usr/bin/env python3
2 """Models.dev catalog refresh / snapshot automation for CodeWhale (#4117).
3
4 Fetches the public Models.dev combined catalog, validates offline bundled seed
5 shape, supports OpenRouter public-listing inspection, and generates the offline
6 seed (#6396). It never accepts, prints, or persists API keys / auth headers.
7 The only thing it writes from fetched JSON is the seed lock: the rows the spec
8 references, projected onto allowlisted fields with credential-shaped keys
9 scrubbed. The raw document is never written.
10
11 Usage examples:
12
13 # Regenerate the offline seed (see docs/CATALOG_REFRESH.md)
14 scripts/catalog/catalog_models_dev.py seed lock --dry-run # review report only
15 scripts/catalog/catalog_models_dev.py seed lock # pin upstream rows
16 scripts/catalog/catalog_models_dev.py seed render # write the seed
17 scripts/catalog/catalog_models_dev.py seed render --check # CI: seed == render
18 scripts/catalog/catalog_models_dev.py seed age --max-days 30 # CI: the pin is not stale
19 scripts/catalog/catalog_models_dev.py seed discover [--write] # new allowlisted-vendor models
20
21 # Dry-run: fetch + validate, print counts (no write)
22 scripts/catalog/catalog_models_dev.py refresh
23
24 # Validate the in-repo offline seed still parses as Models.dev-shaped JSON
25 scripts/catalog/catalog_models_dev.py snapshot --check \\
26 crates/config/assets/models_dev.bundled.json
27
28 # OpenRouter public /models listing (no key), dry-run only
29 scripts/catalog/catalog_models_dev.py refresh --provider openrouter \\
30 --sort newest --limit 100
31
32 Environment:
33 CODEWHALE_MODELS_DEV_URL Override Models.dev catalog URL
34 CODEWHALE_MODELS_DEV_PATH Read catalog JSON from a local file instead of network
35 """
36
37 from __future__ import annotations
38
39 import argparse
40 import difflib
41 import hashlib
42 import json
43 import os
44 import re
45 import sys
46 import urllib.error
47 import urllib.request
48 from datetime import datetime, timedelta, timezone
49 from pathlib import Path
50 from typing import Any
51
52 DEFAULT_MODELS_DEV_URL = "https://models.dev/catalog.json"
53 DEFAULT_OPENROUTER_MODELS_URL = "https://openrouter.ai/api/v1/models"
54 USER_AGENT = "CodeWhale-catalog-automation/0.9.0 (+https://github.com/codewhale-hq/CodeWhale)"
55 FETCH_TIMEOUT_SECS = 60
56
57
58 def die(msg: str, code: int = 1) -> None:
59 print(f"error: {msg}", file=sys.stderr)
60 raise SystemExit(code)
61
62
63 def load_json_bytes(raw: bytes, source: str) -> Any:
64 try:
65 text = raw.decode("utf-8")
66 except UnicodeDecodeError as exc:
67 die(f"{source}: not utf-8 ({exc})")
68 try:
69 return json.loads(text)
70 except json.JSONDecodeError as exc:
71 die(f"{source}: invalid JSON ({exc})")
72
73
74 def fetch_url(url: str) -> bytes:
75 req = urllib.request.Request(
76 url,
77 headers={
78 "User-Agent": USER_AGENT,
79 "Accept": "application/json",
80 # Explicitly no Authorization header — public endpoints only.
81 },
82 method="GET",
83 )
84 try:
85 with urllib.request.urlopen(req, timeout=FETCH_TIMEOUT_SECS) as resp:
86 # Refuse to follow into non-JSON surprise payloads larger than 64 MiB.
87 data = resp.read(64 * 1024 * 1024 + 1)
88 if len(data) > 64 * 1024 * 1024:
89 die(f"{url}: response exceeds 64 MiB safety cap")
90 ctype = resp.headers.get("Content-Type", "")
91 if "json" not in ctype.lower() and not data.lstrip().startswith((b"{", b"[")):
92 die(f"{url}: unexpected Content-Type {ctype!r}")
93 return data
94 except urllib.error.HTTPError as exc:
95 die(f"{url}: HTTP {exc.code} {exc.reason}")
96 except urllib.error.URLError as exc:
97 die(f"{url}: {exc.reason}")
98
99
100 def load_models_dev_catalog() -> tuple[dict[str, Any], str, bool]:
101 """Return (document, source_label, is_local_file).
102
103 Network fetches are dry-run only for write paths: CodeQL treats remote JSON
104 as potentially sensitive, and Models.dev is large enough that maintainers
105 should stage via CODEWHALE_MODELS_DEV_PATH before writing a cache/snapshot.
106 """
107 path_override = os.environ.get("CODEWHALE_MODELS_DEV_PATH", "").strip()
108 if path_override:
109 p = Path(path_override)
110 if not p.is_file():
111 die(f"CODEWHALE_MODELS_DEV_PATH not a file: {p}")
112 raw = p.read_bytes()
113 data = load_json_bytes(raw, str(p))
114 return ensure_models_dev_shape(data, str(p)), f"file:{p}", True
115
116 url = os.environ.get("CODEWHALE_MODELS_DEV_URL", DEFAULT_MODELS_DEV_URL).strip()
117 if not url:
118 url = DEFAULT_MODELS_DEV_URL
119 raw = fetch_url(url)
120 data = load_json_bytes(raw, url)
121 return ensure_models_dev_shape(data, url), f"url:{url}", False
122
123
124 def ensure_models_dev_shape(data: Any, source: str) -> dict[str, Any]:
125 if not isinstance(data, dict):
126 die(f"{source}: expected object root")
127 # Allow optional _meta (CodeWhale offline seed) and require models+providers
128 # when present so we never write a partial secret leak document.
129 models = data.get("models")
130 providers = data.get("providers")
131 if models is None and providers is None:
132 die(f"{source}: missing both 'models' and 'providers'")
133 if models is not None and not isinstance(models, dict):
134 die(f"{source}: 'models' must be an object")
135 if providers is not None and not isinstance(providers, dict):
136 die(f"{source}: 'providers' must be an object")
137 # Rebuild a public document from allowlisted top-level keys only so we never
138 # persist credential-shaped fields even if a future Models.dev field adds them.
139 return public_models_dev_document(data)
140
141
142 def is_credential_key(key: str) -> bool:
143 banned_exact = {
144 "api_key",
145 "apikey",
146 "authorization",
147 "token",
148 "access_token",
149 "refresh_token",
150 "secret",
151 "password",
152 "client_secret",
153 }
154 lowered = key.lower()
155 return lowered in banned_exact or lowered.endswith("_api_key") or lowered.endswith("_secret")
156
157
158 def strip_sensitive_fields(node: Any) -> Any:
159 """Drop keys that look like credentials; never persist auth material."""
160 if isinstance(node, dict):
161 out: dict[str, Any] = {}
162 for key, value in node.items():
163 if not isinstance(key, str) or is_credential_key(key):
164 continue
165 out[key] = strip_sensitive_fields(value)
166 return out
167 if isinstance(node, list):
168 return [strip_sensitive_fields(item) for item in node]
169 if isinstance(node, (str, int, float, bool)) or node is None:
170 return node
171 # Drop non-JSON-scalar oddities rather than serializing them.
172 return None
173
174
175 def public_models_dev_document(data: dict[str, Any]) -> dict[str, Any]:
176 """Construct a write-safe Models.dev-shaped document (public metadata only)."""
177 out: dict[str, Any] = {}
178 if isinstance(data.get("_meta"), dict):
179 out["_meta"] = strip_sensitive_fields(data["_meta"])
180 if isinstance(data.get("models"), dict):
181 out["models"] = strip_sensitive_fields(data["models"])
182 if isinstance(data.get("providers"), dict):
183 out["providers"] = strip_sensitive_fields(data["providers"])
184 return out
185
186
187 def public_source_label(source: str) -> str:
188 """Log a catalog origin without query/fragment (tokens live there)."""
189 if source.startswith("url:"):
190 url = source[4:]
191 for sep in ("?", "#"):
192 url = url.split(sep, 1)[0]
193 return f"url:{url}"
194 return source
195
196
197 def public_limit_value(value: Any) -> str:
198 """Format a catalog limit for logs. Never print credential-shaped strings.
199
200 Remote catalog JSON is tainted for clear-text-logging rules. Only numeric
201 limits are meaningful here; anything else (including token-shaped strings)
202 is replaced with a constant so the raw value cannot reach stdout.
203 """
204 if isinstance(value, bool):
205 return "redacted"
206 if value is None:
207 return "null"
208 if isinstance(value, int):
209 return str(value)
210 if isinstance(value, float):
211 return format(value, ".6g")
212 return "redacted"
213
214
215 def catalog_stats(data: dict[str, Any]) -> str:
216 models = data.get("models") or {}
217 providers = data.get("providers") or {}
218 offerings = 0
219 if isinstance(providers, dict):
220 for prov in providers.values():
221 if isinstance(prov, dict):
222 models_map = prov.get("models") or {}
223 if isinstance(models_map, dict):
224 offerings += len(models_map)
225 return (
226 f"providers={len(providers) if isinstance(providers, dict) else 0} "
227 f"canonical_models={len(models) if isinstance(models, dict) else 0} "
228 f"provider_offerings={offerings}"
229 )
230
231
232
233 def cmd_refresh(args: argparse.Namespace) -> None:
234 if args.provider and args.provider.lower() == "openrouter":
235 refresh_openrouter(args)
236 return
237 if args.provider:
238 die(
239 f"unsupported --provider {args.provider!r} "
240 "(supported: openrouter, or omit for Models.dev)"
241 )
242
243 data, source, _is_local = load_models_dev_catalog()
244 print(f"loaded Models.dev catalog from {source}")
245 print(catalog_stats(data))
246 if args.write_cache or args.write:
247 die(
248 "disk writes are intentionally unsupported (secret-free by design); "
249 "to update the offline seed use `seed lock` then `seed render`"
250 )
251 print("dry-run complete (no secrets; no disk write)")
252
253
254 def refresh_openrouter(args: argparse.Namespace) -> None:
255 url = DEFAULT_OPENROUTER_MODELS_URL
256 raw = fetch_url(url)
257 data = load_json_bytes(raw, url)
258 if not isinstance(data, dict) or "data" not in data:
259 die(f"{url}: expected {{ data: [...] }} envelope")
260 rows = data["data"]
261 if not isinstance(rows, list):
262 die(f"{url}: data is not a list")
263
264 # Optional sort / limit for local inspection — never secrets.
265 if args.sort == "newest":
266 def created_key(row: Any) -> float:
267 if not isinstance(row, dict):
268 return 0.0
269 created = row.get("created")
270 try:
271 return float(created)
272 except (TypeError, ValueError):
273 return 0.0
274
275 rows = sorted(rows, key=created_key, reverse=True)
276 if args.limit is not None and args.limit > 0:
277 rows = rows[: args.limit]
278
279 # Project only public catalog fields — never the raw response object —
280 # so credential-shaped keys cannot reach disk even if OpenRouter adds them.
281 public_rows: list[dict[str, Any]] = []
282 allowed = {
283 "id",
284 "name",
285 "created",
286 "description",
287 "context_length",
288 "architecture",
289 "pricing",
290 "top_provider",
291 "per_request_limits",
292 "supported_parameters",
293 }
294 for row in rows:
295 if not isinstance(row, dict):
296 continue
297 projected: dict[str, Any] = {}
298 for key in allowed:
299 if key in row and not is_credential_key(key):
300 projected[key] = strip_sensitive_fields(row[key])
301 if projected.get("id"):
302 public_rows.append(projected)
303 payload = {
304 "_meta": {
305 "source": "openrouter.ai/api/v1/models",
306 "note": "Public model listing for cache dogfood; not the Models.dev SoT.",
307 "count": len(public_rows),
308 "sort": args.sort,
309 "limit": args.limit,
310 },
311 "data": public_rows,
312 }
313 print(f"loaded OpenRouter models: {len(public_rows)} rows (sort={args.sort}, limit={args.limit})")
314 if args.write_cache:
315 # OpenRouter listing is always network-sourced; avoid disk write of remote JSON.
316 die(
317 "OpenRouter refresh is dry-run only (no disk write). "
318 "Use Models.dev with CODEWHALE_MODELS_DEV_PATH for offline snapshots."
319 )
320 else:
321 print("dry-run complete (OpenRouter writes disabled; use Models.dev local path for caches)")
322 _ = payload # keep payload construction for future offline path
323
324
325 def cmd_snapshot(args: argparse.Namespace) -> None:
326 target = Path(args.path)
327 if args.check:
328 if not target.is_file():
329 die(f"--check: missing {target}")
330 raw = target.read_bytes()
331 data = load_json_bytes(raw, str(target))
332 ensure_models_dev_shape(data, str(target))
333 print(f"ok: {target} is Models.dev-shaped ({catalog_stats(data)})")
334 return
335
336 data, source, _is_local = load_models_dev_catalog()
337 print(f"loaded Models.dev catalog from {source}")
338 print(catalog_stats(data))
339 if args.write or args.force_full:
340 die(
341 "disk writes are intentionally unsupported for this automation; "
342 "the offline seed is generated: use `seed lock` then `seed render`"
343 )
344 print("dry-run complete (use --check PATH to validate an existing snapshot)")
345
346
347 # ---------------------------------------------------------------------------
348 # Offline seed generator (#6396)
349 #
350 # The offline seed (crates/config/assets/models_dev.bundled.json) is generated,
351 # never hand-edited:
352 #
353 # spec scripts/catalog/models_dev_seed.toml what to carry (reviewed)
354 # lock scripts/catalog/models_dev_seed.lock.json upstream rows, pinned
355 # seed crates/config/assets/models_dev.bundled.json = render(spec, lock)
356 #
357 # `seed lock` is the only network step and the review step: it fetches
358 # Models.dev, keeps only the rows the spec references (allowlisted fields,
359 # credential-shaped keys scrubbed), and prints what changed. `seed render` is
360 # offline and deterministic; CI runs `seed render --check`.
361 #
362 # The spec selects and maps; it never states a value that contradicts
363 # upstream. Policy (a withheld price, a clamped limit) lives in the runtime
364 # corrections file, crates/config/assets/catalog_corrections.json, so it
365 # holds online as well as offline. The one additive exception is a `curated`
366 # row for a model upstream does not list yet; `seed lock` fails once upstream
367 # lists it, so a curated row can never shadow an upstream fact.
368 # ---------------------------------------------------------------------------
369
370 SEED_SPEC = Path("scripts/catalog/models_dev_seed.toml")
371 SEED_LOCK = Path("scripts/catalog/models_dev_seed.lock.json")
372 SEED_ASSET = Path("crates/config/assets/models_dev.bundled.json")
373 CORRECTIONS_ASSET = Path("crates/config/assets/catalog_corrections.json")
374 DESCRIPTORS_ASSET = Path("crates/config/assets/provider_descriptors.json")
375 SEED_RENDER_COMMAND = "python3 scripts/catalog/catalog_models_dev.py seed render"
376 # Seeded providers whose fallback pin legitimately differs from the descriptor.
377 # Identification from the provider's own model list is the authority; this map
378 # is only for a pin that is not that identified id and must stay that way.
379 SEED_DEFAULT_EXCEPTIONS: dict[str, str] = {
380 "zai": "GLM-5.3 stays the Z.ai default while GLM-5.4 is Coding-Plan-only and has no fast sibling.",
381 }
382 # Tokens that mark a row as a smaller/faster or non-stable release: newer than
383 # the default, but not a replacement for it.
384 VARIANT_TOKENS: frozenset[str] = frozenset(
385 {
386 "audio",
387 "beta",
388 "coder",
389 "distill",
390 "distilled",
391 "embed",
392 "embedding",
393 "experimental",
394 "fast",
395 "haiku",
396 "image",
397 "lite",
398 "max",
399 "micro",
400 "mini",
401 "nano",
402 "preview",
403 "reranker",
404 "small",
405 "tiny",
406 "tts",
407 "turbo",
408 "vision",
409 }
410 )
411
412 # Exactly the fields crates/config/src/models_dev.rs reads, in render order.
413 PROVIDER_MODEL_FIELDS = (
414 "id",
415 "base_model",
416 "canonical_model_id",
417 "name",
418 "description",
419 "type",
420 "family",
421 "knowledge",
422 "release_date",
423 "last_updated",
424 "default",
425 "attachment",
426 "reasoning",
427 "reasoning_options",
428 "interleaved",
429 "tool_call",
430 "structured_output",
431 "temperature",
432 "open_weights",
433 "modalities",
434 "limit",
435 "cost",
436 "provider",
437 "status",
438 "experimental",
439 )
440 CANONICAL_MODEL_FIELDS = (
441 "id",
442 "name",
443 "description",
444 "type",
445 "family",
446 "knowledge",
447 "release_date",
448 "last_updated",
449 "attachment",
450 "reasoning",
451 "tool_call",
452 "structured_output",
453 "temperature",
454 "open_weights",
455 "modalities",
456 "limit",
457 "license",
458 "links",
459 "weights",
460 "benchmarks",
461 )
462 NESTED_FIELDS = {
463 "limit": ("context", "input", "output"),
464 "modalities": ("input", "output"),
465 "cost": ("input", "output", "cache_read", "cache_write", "reasoning", "input_audio", "output_audio", "tiers", "context_over_200k"),
466 "provider": ("npm", "api", "shape", "body", "headers"),
467 }
468 # Mapping-only keys a spec model entry may carry. None of them restates an
469 # upstream fact: `base_model` is the seed's compatibility join; generated
470 # upstream provider rows may carry `canonical_model_id`.
471 SPEC_MODEL_KEYS = {"id", "upstream_id", "from", "base_model", "curated"}
472 SPEC_PROVIDER_KEYS = {"id", "upstream", "name", "api", "npm", "env", "doc", "default", "models"}
473 SAFE_PUBLIC_TEXT = re.compile(r"^[A-Za-z0-9 ._:/()+\-]{0,64}$")
474
475
476 def project_fields(row: Any, fields: tuple[str, ...]) -> dict[str, Any]:
477 """Keep only allowlisted fields, in a fixed order, scrubbed."""
478 if not isinstance(row, dict):
479 return {}
480 out: dict[str, Any] = {}
481 for field in fields:
482 if field not in row or row[field] is None:
483 continue
484 value = strip_sensitive_fields(row[field])
485 nested = NESTED_FIELDS.get(field)
486 if nested is not None:
487 if not isinstance(value, dict):
488 continue
489 value = {key: value[key] for key in nested if value.get(key) is not None}
490 if not value:
491 continue
492 out[field] = value
493 return out
494
495
496 def public_value(value: Any) -> str:
497 """Format an upstream value for the review report without echoing secrets."""
498 if isinstance(value, bool):
499 return "true" if value else "false"
500 if value is None or isinstance(value, (int, float)):
501 return public_limit_value(value)
502 if isinstance(value, str):
503 if SAFE_PUBLIC_TEXT.match(value) and not value.lower().startswith(("sk-", "bearer")):
504 return value
505 return "redacted"
506 if isinstance(value, list):
507 return "[" + ", ".join(public_value(item) for item in value) + "]"
508 if isinstance(value, dict):
509 return "{" + ", ".join(
510 f"{public_value(key)}: {public_value(item)}" for key, item in value.items()
511 ) + "}"
512 return "redacted"
513
514
515 def flatten(value: Any, prefix: str = "") -> dict[str, Any]:
516 if isinstance(value, dict):
517 out: dict[str, Any] = {}
518 for key, item in value.items():
519 out.update(flatten(item, f"{prefix}.{key}" if prefix else str(key)))
520 return out
521 return {prefix: value}
522
523
524 def load_seed_spec(path: Path) -> dict[str, Any]:
525 import tomllib
526
527 if not path.is_file():
528 die(f"seed spec missing: {path}")
529 try:
530 spec = tomllib.loads(path.read_text(encoding="utf-8"))
531 except tomllib.TOMLDecodeError as exc:
532 die(f"{path}: invalid TOML ({exc})")
533 return normalize_seed_spec(spec, str(path))
534
535
536 def normalize_seed_spec(spec: dict[str, Any], source: str) -> dict[str, Any]:
537 """Validate the spec and expand shorthand model entries."""
538 if not isinstance(spec.get("source"), dict) or not spec["source"].get("url"):
539 die(f"{source}: [source].url is required")
540 meta = spec.get("meta", {})
541 if not isinstance(meta, dict) or not all(isinstance(v, str) for v in meta.values()):
542 die(f"{source}: [meta] values must be strings")
543 curated: dict[tuple[str, str], dict[str, Any]] = {}
544 for entry in spec.get("curated", []):
545 key = (entry.get("provider", ""), entry.get("id", ""))
546 if not all(key) or not str(entry.get("reason", "")).strip():
547 die(f"{source}: curated rows need provider, id and a reason")
548 if not isinstance(entry.get("row"), dict):
549 die(f"{source}: curated {key[0]}/{key[1]} needs a [curated.row] table")
550 if key in curated:
551 die(f"{source}: curated {key[0]}/{key[1]} is listed twice")
552 curated[key] = entry
553 providers = []
554 seen_providers: set[str] = set()
555 for provider in spec.get("providers", []):
556 unknown = set(provider) - SPEC_PROVIDER_KEYS
557 pid = provider.get("id", "")
558 if unknown:
559 die(f"{source}: provider {pid} has unknown keys {sorted(unknown)}")
560 if not pid or pid in seen_providers:
561 die(f"{source}: provider ids must be present and unique ({pid!r})")
562 seen_providers.add(pid)
563 models = []
564 seen_models: set[str] = set()
565 for raw in provider.get("models", []):
566 entry = {"id": raw} if isinstance(raw, str) else dict(raw)
567 unknown = set(entry) - SPEC_MODEL_KEYS
568 if unknown:
569 die(
570 f"{source}: {pid}/{entry.get('id')} has unknown keys {sorted(unknown)}; "
571 "the spec maps rows, it never restates upstream values "
572 "(policy goes in crates/config/assets/catalog_corrections.json)"
573 )
574 mid = entry.get("id", "")
575 if not mid or mid in seen_models:
576 die(f"{source}: {pid} model ids must be present and unique ({mid!r})")
577 seen_models.add(mid)
578 if entry.get("curated") and (pid, mid) not in curated:
579 die(f"{source}: {pid}/{mid} is marked curated but has no [[curated]] row")
580 if not entry.get("curated") and (pid, mid) in curated:
581 die(f"{source}: {pid}/{mid} has a [[curated]] row but is not marked curated")
582 models.append(entry)
583 defaults = [m["id"] for m in models if m["id"] == provider.get("default")]
584 if len(defaults) != 1:
585 die(f"{source}: provider {pid} must name exactly one default among its models")
586 providers.append({**provider, "upstream": provider.get("upstream", pid), "models": models})
587 used_curated = {
588 (p["id"], m["id"]) for p in providers for m in p["models"] if m.get("curated")
589 }
590 for key in curated:
591 if key not in used_curated:
592 die(f"{source}: curated {key[0]}/{key[1]} is not listed under its provider")
593 canonical = []
594 for entry in spec.get("canonical", []):
595 entry = {"key": entry} if isinstance(entry, str) else dict(entry)
596 if not entry.get("key"):
597 die(f"{source}: canonical entries need a key")
598 canonical.append({"key": entry["key"], "upstream": entry.get("upstream", entry["key"])})
599 discover = spec.get("discover", {})
600 skip = discover.get("skip", [])
601 since_days = discover.get("since_days", DISCOVER_DEFAULT_SINCE_DAYS)
602 if (
603 not isinstance(skip, list)
604 or not all(isinstance(item, str) for item in skip)
605 or not isinstance(since_days, int)
606 or isinstance(since_days, bool)
607 or since_days <= 0
608 ):
609 die(f"{source}: [discover] needs skip = [ids] and a positive integer since_days")
610 return {
611 "source": spec["source"],
612 "meta": meta,
613 "discover": {"skip": skip, "since_days": since_days},
614 "providers": providers,
615 "curated": curated,
616 "canonical": canonical,
617 }
618
619
620 def descriptor_defaults(path: Path) -> dict[str, str]:
621 """Default model per provider id, read from the shipped descriptor list."""
622 document = read_json_file(path)
623 providers = document.get("providers")
624 if not isinstance(providers, list):
625 die(f"{path}: `providers` must be a list of provider descriptors")
626 defaults: dict[str, str] = {}
627 for entry in providers:
628 if not isinstance(entry, dict) or not isinstance(entry.get("default_model"), str):
629 continue
630 for key in ("id", "catalog_id"):
631 name = entry.get(key)
632 if isinstance(name, str) and name:
633 defaults.setdefault(name, entry["default_model"])
634 return defaults
635
636
637 def version_id(model_id: str) -> tuple[str, int, tuple[int, ...]] | None:
638 """`stem-major.minor` only.
639
640 `grok-4.7` and `muse-spark-1.3` match. `gpt-6`, `gpt-6.1-sol`,
641 `gemini-3.1-pro-preview`, `kimi-k2.7-code` and dated snapshots do not:
642 a different product line, a major jump, or an extra suffix is not a
643 successor of the pinned id.
644 """
645 match = re.fullmatch(r"(.+)-(\d+)\.(\d+(?:\.\d+)*)", model_id.strip())
646 if match is None:
647 return None
648 return (
649 match.group(1).lower(),
650 int(match.group(2)),
651 tuple(int(part) for part in match.group(3).split(".")),
652 )
653
654
655 def variant_id(model_id: str, name: str = "") -> bool:
656 tokens = [token for token in re.split(r"[^a-z0-9]+", f"{model_id} {name}".lower()) if token]
657 return any(token in VARIANT_TOKENS or token.startswith("flash") for token in tokens)
658
659
660 def identify_listed_default(rows: list[dict[str, Any]], pinned: str) -> str:
661 """Default id implied by one provider's own model list.
662
663 The pin is the fallback when the list has no same-line successor. A
664 successor must share stem and major, carry a higher minor, and must not
665 be a variant, a retired row, or a regression of tool calling or a
666 published context/output limit. A newer row on a different line
667 (`gpt-6` beside `gpt-5.6`, `gemini-4-argon` beside `gemini-3.1-pro-preview`,
668 `sakana-namazu` beside `fugu`) does not replace the pin. An explicit
669 upstream `default` flag, when the list actually carries one, wins over
670 both the pin and a successor.
671 """
672 usable = [row for row in rows if isinstance(row, dict) and isinstance(row.get("id"), str)]
673 flagged = [row["id"] for row in usable if row.get("default") is True and row["id"] != pinned]
674 # Our own render stamps `default` from this function. Treat a flag that
675 # merely repeats the pin as not an upstream choice. A flag on a different
676 # id is an explicit list decision.
677 if len(flagged) == 1:
678 return flagged[0]
679 parsed = version_id(pinned)
680 if parsed is None:
681 return pinned
682 pin_row = next((row for row in usable if row["id"] == pinned), {})
683 pin_limit = pin_row.get("limit") if isinstance(pin_row.get("limit"), dict) else {}
684 stem, major, _rest = parsed
685 best_id: str | None = None
686 best_rest: tuple[int, ...] | None = None
687 best_date = ""
688 for row in usable:
689 model_id = row["id"]
690 if row.get("status") in ("deprecated", "retired"):
691 continue
692 if row.get("type") not in (None, "language"):
693 continue
694 if variant_id(model_id, str(row.get("name") or "")):
695 continue
696 found = version_id(model_id)
697 if found is None or found[0] != stem or found[1] != major:
698 continue
699 if pin_row.get("tool_call") is True and row.get("tool_call") is False:
700 continue
701 row_limit = row.get("limit") if isinstance(row.get("limit"), dict) else {}
702 if any(
703 isinstance(pin_limit.get(field), int)
704 and isinstance(row_limit.get(field), int)
705 and row_limit[field] < pin_limit[field]
706 for field in ("context", "output")
707 ):
708 continue
709 date = row.get("release_date") if isinstance(row.get("release_date"), str) else ""
710 if best_rest is None or found[2] > best_rest or (found[2] == best_rest and date > best_date):
711 best_id, best_rest, best_date = model_id, found[2], date
712 return best_id or pinned
713
714
715 def seed_descriptor_default_errors(spec: dict[str, Any], path: Path) -> list[str]:
716 """Descriptor defaults that disagree with the provider model list."""
717 defaults = descriptor_defaults(path)
718 errors: list[str] = []
719 for provider in spec["providers"]:
720 pid = provider["id"]
721 if pid in SEED_DEFAULT_EXCEPTIONS:
722 continue
723 identified = identify_listed_default(provider["models"], provider["default"])
724 declared = defaults.get(pid)
725 if declared is None:
726 errors.append(f"{pid}: seeded provider has no default_model in {path}")
727 elif declared != identified:
728 errors.append(
729 f"{pid}: {path} defaults to {declared!r} but the model list "
730 f"identifies {identified!r} (pin {provider['default']!r})"
731 )
732 return errors
733
734
735 def upstream_ref(provider: dict[str, Any], model: dict[str, Any]) -> tuple[str, str]:
736 """The (upstream provider, upstream model id) a spec row projects."""
737 return (
738 model.get("from", provider["upstream"]),
739 model.get("upstream_id", model["id"]),
740 )
741
742
743 def find_row(rows: dict[str, Any], model_id: str) -> tuple[str, Any] | None:
744 """Exact id first, then a unique case-insensitive match (`GLM-5.2` ~ `glm-5.2`)."""
745 if model_id in rows:
746 return model_id, rows[model_id]
747 matches = [key for key in rows if key.lower() == model_id.lower()]
748 if len(matches) == 1:
749 return matches[0], rows[matches[0]]
750 return None
751
752
753 def build_seed_lock(
754 spec: dict[str, Any], upstream: dict[str, Any], raw: bytes, fetched_at: str
755 ) -> tuple[dict[str, Any], list[str]]:
756 """Project the spec's referenced upstream rows. Returns (lock, errors)."""
757 errors: list[str] = []
758 up_providers = upstream.get("providers") or {}
759 up_models = upstream.get("models") or {}
760 lock_providers: dict[str, dict[str, Any]] = {}
761 for provider in spec["providers"]:
762 for model in provider["models"]:
763 up_provider, up_id = upstream_ref(provider, model)
764 rows = (up_providers.get(up_provider) or {}).get("models") or {}
765 found = find_row(rows, up_id)
766 label = f"{provider['id']}/{model['id']}"
767 if model.get("curated"):
768 if found is not None:
769 errors.append(
770 f"{label}: curated, but upstream {up_provider} now lists "
771 f"{found[0]}; drop the [[curated]] row and derive it"
772 )
773 continue
774 if found is None:
775 errors.append(f"{label}: upstream {up_provider} does not list {up_id}")
776 continue
777 lock_providers.setdefault(up_provider, {})[found[0]] = project_fields(
778 found[1], PROVIDER_MODEL_FIELDS
779 )
780 lock_models: dict[str, Any] = {}
781 for entry in spec["canonical"]:
782 row = up_models.get(entry["upstream"])
783 if row is None:
784 errors.append(f"canonical {entry['key']}: upstream does not list {entry['upstream']}")
785 continue
786 lock_models[entry["upstream"]] = project_fields(row, CANONICAL_MODEL_FIELDS)
787 lock = {
788 "source": {
789 "url": spec["source"]["url"],
790 "fetched_at": fetched_at,
791 "sha256": hashlib.sha256(raw).hexdigest(),
792 },
793 "models": dict(sorted(lock_models.items())),
794 "providers": {
795 key: dict(sorted(rows.items())) for key, rows in sorted(lock_providers.items())
796 },
797 }
798 return lock, errors
799
800
801 def seed_lock_report(
802 spec: dict[str, Any],
803 old_lock: dict[str, Any] | None,
804 new_lock: dict[str, Any],
805 upstream: dict[str, Any],
806 corrections: dict[str, Any] | None,
807 ) -> list[str]:
808 """Human review lines for the PR body: what a re-lock changes."""
809 lines: list[str] = []
810 old_rows = flatten((old_lock or {}).get("providers", {}))
811 old_rows_by_provider = (old_lock or {}).get("providers", {})
812 old_rows.update(flatten({"models": (old_lock or {}).get("models", {})}))
813 new_rows = flatten(new_lock.get("providers", {}))
814 new_rows.update(flatten({"models": new_lock.get("models", {})}))
815 changed = [
816 f" {path}: {public_value(old_rows.get(path))} -> {public_value(new_rows.get(path))}"
817 for path in sorted(set(old_rows) | set(new_rows))
818 if old_rows.get(path) != new_rows.get(path)
819 ]
820 lines.append(f"field changes: {len(changed)}")
821 lines.extend(changed)
822
823 if corrections:
824 stale = stale_corrections(spec, new_lock, corrections)
825 lines.append(f"stale corrections (upstream now agrees; delete them): {len(stale)}")
826 lines.extend(f" {line}" for line in stale)
827
828 referenced = {
829 upstream_ref(p, m)[0]: set() for p in spec["providers"] for m in p["models"]
830 }
831 for provider in spec["providers"]:
832 for model in provider["models"]:
833 up_provider, _ = upstream_ref(provider, model)
834 referenced[up_provider].update(new_lock["providers"].get(up_provider, {}))
835 freshness: list[str] = []
836 for provider in spec["providers"]:
837 default = next(m for m in provider["models"] if m["id"] == provider["default"])
838 up_provider, up_id = upstream_ref(provider, default)
839 rows = new_lock["providers"].get(up_provider, {})
840 found = find_row(rows, up_id)
841 released = (found[1] if found else {}).get("release_date")
842 newer = sorted(
843 (
844 (row["release_date"], model_id)
845 for model_id, row in rows.items()
846 if model_id != up_id
847 and isinstance(row.get("release_date"), str)
848 and isinstance(released, str)
849 and row["release_date"] > released
850 ),
851 reverse=True,
852 )[:5]
853 detail = f"released {public_value(released)}" if released else "no release_date"
854 if newer:
855 shown = ", ".join(f"{public_value(mid)} ({public_value(date)})" for date, mid in newer)
856 freshness.append(f" {provider['id']}: default {public_value(provider['default'])} {detail}; newer upstream: {shown}")
857 else:
858 freshness.append(f" {provider['id']}: default {public_value(provider['default'])} {detail}")
859 lines.append("default freshness (information only; decide whether a newer model should be the default):")
860 lines.extend(freshness)
861
862 carried: dict[str, set[str]] = {up_provider: set() for up_provider in old_rows_by_provider}
863 for provider in spec["providers"]:
864 for model in provider["models"]:
865 up_provider, up_id = upstream_ref(provider, model)
866 if model.get("curated"):
867 continue
868 found = find_row(new_lock["providers"].get(up_provider, {}), up_id)
869 if found is not None:
870 carried.setdefault(up_provider, set()).add(found[0])
871 rot = [
872 f" {up_provider}.{model_id}"
873 for up_provider, rows in sorted(old_rows_by_provider.items())
874 for model_id in sorted(set(rows) - carried.get(up_provider, set()))
875 ]
876 lines.append(
877 "lock rows the spec no longer references (removed by this re-lock, not upstream deletions): "
878 f"{len(rot)}"
879 )
880 lines.extend(rot)
881
882 new_upstream: list[str] = []
883 for up_provider, carried in sorted(referenced.items()):
884 rows = ((upstream.get("providers") or {}).get(up_provider) or {}).get("models") or {}
885 extra = sorted(set(rows) - carried)
886 if extra:
887 shown = ", ".join(public_value(model) for model in extra[:8])
888 more = f" (+{len(extra) - 8} more)" if len(extra) > 8 else ""
889 new_upstream.append(f" {up_provider}: {len(extra)} not carried: {shown}{more}")
890 lines.append("upstream models not carried (information only):")
891 lines.extend(new_upstream or [" none"])
892 return lines
893
894
895 def stale_corrections(
896 spec: dict[str, Any], lock: dict[str, Any], corrections: dict[str, Any]
897 ) -> list[str]:
898 """Corrections whose patched value upstream now states itself."""
899 rows_by_provider: dict[str, dict[str, Any]] = {}
900 for provider in spec["providers"]:
901 rows = rows_by_provider.setdefault(provider["id"], {})
902 for model in provider["models"]:
903 up_provider, up_id = upstream_ref(provider, model)
904 found = find_row(lock["providers"].get(up_provider, {}), up_id)
905 if found is not None:
906 rows[model["id"]] = found[1]
907 stale: list[str] = []
908 for rule in corrections.get("providers", []):
909 rows = rows_by_provider.get(rule.get("provider"), {})
910 if rows and not any(row.get("cost") for row in rows.values()):
911 stale.append(f"{rule['provider']}: pricing_withheld, but no carried row has a price")
912 for fix in corrections.get("models", []):
913 row = rows_by_provider.get(fix.get("provider"), {}).get(fix.get("id"))
914 if row is None:
915 continue
916 limit = row.get("limit") or {}
917 label = f"{fix['provider']}/{fix['id']}"
918 if "max_output" in fix and limit.get("output") == fix["max_output"]:
919 stale.append(f"{label}: max_output {fix['max_output']} equals upstream")
920 if "context_window" in fix and limit.get("context") == fix["context_window"]:
921 stale.append(f"{label}: context_window {fix['context_window']} equals upstream")
922 if "pricing_withheld" in fix and not row.get("cost"):
923 stale.append(f"{label}: pricing_withheld, but upstream lists no price")
924 if "reasoning_options" in fix and row.get("reasoning_options") == fix["reasoning_options"]:
925 stale.append(f"{label}: reasoning_options equal upstream")
926 return stale
927
928
929 def validate_reviewed(data: Any) -> dict[str, Any]:
930 """Refuse malformed authored supplements before the deterministic render."""
931 def identifier(value: Any) -> bool:
932 return isinstance(value, str) and bool(value) and len(value.encode("utf-8")) <= 512 and value == value.strip() and not any(ord(c) < 32 or 127 <= ord(c) <= 159 for c in value)
933
934 def positive(value: Any) -> bool:
935 return value is None or isinstance(value, int) and not isinstance(value, bool) and 0 < value <= 0xffffffff
936
937 if not isinstance(data, dict) or not identifier(data.get("revision")):
938 die("reviewed model catalog missing or malformed")
939 intrinsic = data.get("intrinsic", {})
940 if not isinstance(intrinsic, dict):
941 die("reviewed intrinsic facts must be an object")
942 for key, row in intrinsic.items():
943 if not identifier(key) or not isinstance(row, dict) or not identifier(row.get("source")) or any(not positive(row.get(field)) for field in ("context_window", "max_output", "generation_default")) or any(not (row.get(field) is None or isinstance(row.get(field), bool)) for field in ("reasoning", "thought_signatures_required", "thinking_can_disable")):
944 die("malformed reviewed intrinsic fact")
945 public = data.get("public_models", [])
946 if not isinstance(public, list):
947 die("reviewed public models must be an array")
948 seen: set[str] = set()
949 for row in public:
950 if not isinstance(row, dict) or not identifier(row.get("id")) or row["id"] in seen or row["id"].lower() not in intrinsic:
951 die("missing or duplicate reviewed public model")
952 seen.add(row["id"])
953 for key in ("completion_rosters", "constants", "groups"):
954 if not isinstance(data.get(key, {}), dict):
955 die(f"reviewed {key} must be an object")
956 for entries in data.get("completion_rosters", {}).values():
957 if not isinstance(entries, list) or any(not identifier(value) for value in entries):
958 die("malformed reviewed completion roster")
959 for reference in data.get("numeric_refs", {}).values():
960 if not isinstance(reference, dict) or reference.get("field") not in ("context_window", "max_output", "generation_default") or reference.get("model") not in intrinsic or not positive(intrinsic[reference["model"]].get(reference["field"])) or intrinsic[reference["model"]].get(reference["field"]) is None:
961 die("missing or malformed numeric model contract")
962 return data
963
964
965 def render_seed(spec: dict[str, Any], lock: dict[str, Any], reviewed_source: dict[str, Any]) -> str:
966 """Render the offline seed from spec + lock. Pure and deterministic."""
967 errors: list[str] = []
968 providers_out: dict[str, Any] = {}
969 row_count = 0
970 for provider in spec["providers"]:
971 models_out: dict[str, Any] = {}
972 listed_facts: list[dict[str, Any]] = []
973 for model in provider["models"]:
974 key = (provider["id"], model["id"])
975 up_provider, up_id = upstream_ref(provider, model)
976 locked = find_row(lock["providers"].get(up_provider, {}), up_id)
977 if model.get("curated"):
978 if locked is not None:
979 errors.append(f"{key[0]}/{key[1]}: curated row also present in the lock")
980 continue
981 row = project_fields(spec["curated"][key]["row"], PROVIDER_MODEL_FIELDS)
982 elif locked is None:
983 errors.append(
984 f"{key[0]}/{key[1]}: not in the lock (run `python3 scripts/catalog/catalog_models_dev.py seed lock`)"
985 )
986 continue
987 else:
988 row = dict(locked[1])
989 row["id"] = model["id"]
990 if model.get("base_model"):
991 canonical = row.get("canonical_model_id")
992 if canonical is not None and canonical != model["base_model"]:
993 errors.append(f"{key[0]}/{key[1]}: seed base_model conflicts with upstream canonical_model_id")
994 continue
995 row["base_model"] = model["base_model"]
996 listed_facts.append(dict(row))
997 row.pop("default", None)
998 models_out[model["id"]] = project_fields(row, PROVIDER_MODEL_FIELDS)
999 row_count += 1
1000 identified = (
1001 provider["default"]
1002 if provider["id"] in SEED_DEFAULT_EXCEPTIONS
1003 else identify_listed_default(listed_facts, provider["default"])
1004 )
1005 if identified in models_out:
1006 stamped = dict(models_out[identified])
1007 stamped["default"] = True
1008 models_out[identified] = project_fields(stamped, PROVIDER_MODEL_FIELDS)
1009 header = {"id": provider["id"]}
1010 for field in ("name", "api", "npm", "doc", "env"):
1011 if field in provider:
1012 header[field] = provider[field]
1013 providers_out[provider["id"]] = {**header, "models": models_out}
1014 models_out = {}
1015 for entry in spec["canonical"]:
1016 row = lock["models"].get(entry["upstream"])
1017 if row is None:
1018 errors.append(f"canonical {entry['key']}: not in the lock")
1019 continue
1020 models_out[entry["key"]] = project_fields({**row, "id": entry["key"]}, CANONICAL_MODEL_FIELDS)
1021 if errors:
1022 die("seed render refused:\n " + "\n ".join(errors))
1023 meta = dict(spec["meta"])
1024 meta["generated_by"] = (
1025 f"{SEED_RENDER_COMMAND} from {SEED_SPEC} and {SEED_LOCK}. "
1026 "Do not edit this file by hand; see docs/CATALOG_REFRESH.md."
1027 )
1028 source = lock["source"]
1029 meta["upstream"] = f"{source['url']} fetched {source['fetched_at']} sha256 {source['sha256']}"
1030 meta["coverage"] = (
1031 f"{len(providers_out)} providers, {row_count} provider model rows, "
1032 f"{len(models_out)} canonical model entries."
1033 )
1034 validate_reviewed(reviewed_source)
1035 document = {"_meta": meta, "models": models_out, "providers": providers_out}
1036 ensure_models_dev_shape(document, "rendered seed")
1037 return json.dumps(document, indent=2, ensure_ascii=False) + "\n"
1038
1039
1040 def read_json_file(path: Path) -> Any:
1041 if not path.is_file():
1042 die(f"missing {path}")
1043 return load_json_bytes(path.read_bytes(), str(path))
1044
1045
1046 def load_upstream_payload(
1047 spec: dict[str, Any], snapshot: str | None = None
1048 ) -> tuple[bytes, str, dict[str, Any]]:
1049 """The pinned upstream document: snapshot, local file, then the spec URL."""
1050 if snapshot:
1051 raw = Path(snapshot).read_bytes()
1052 source = f"file:{snapshot}"
1053 else:
1054 path_override = os.environ.get("CODEWHALE_MODELS_DEV_PATH", "").strip()
1055 if path_override:
1056 raw = Path(path_override).read_bytes()
1057 source = f"file:{path_override}"
1058 else:
1059 url = os.environ.get("CODEWHALE_MODELS_DEV_URL", "").strip() or spec["source"]["url"]
1060 raw = fetch_url(url)
1061 source = f"url:{url}"
1062 return raw, source, ensure_models_dev_shape(load_json_bytes(raw, source), source)
1063
1064
1065 def cmd_defaults_audit(args: argparse.Namespace) -> None:
1066 spec = load_seed_spec(Path(args.spec))
1067 lock = read_json_file(Path(getattr(args, "lock", None) or SEED_LOCK))
1068 defaults = descriptor_defaults(Path(args.descriptors))
1069 print(
1070 "rule: a provider default is the same-line successor in that provider's "
1071 "own model list, or the pin when the list has none. A newer row on a "
1072 "different line is not a successor. The descriptor must match."
1073 )
1074 stale: list[str] = []
1075 promoted: list[str] = []
1076 for provider in spec["providers"]:
1077 rows: list[dict[str, Any]] = []
1078 for model in provider["models"]:
1079 up_provider, up_id = upstream_ref(provider, model)
1080 locked = find_row(lock.get("providers", {}).get(up_provider, {}), up_id)
1081 row = dict(locked[1]) if locked is not None else {"id": model["id"]}
1082 row["id"] = model["id"]
1083 rows.append(row)
1084 identified = identify_listed_default(rows, provider["default"])
1085 declared = defaults.get(provider["id"])
1086 if declared != identified:
1087 stale.append(
1088 f"{provider['id']}: descriptor {declared!r}, list identifies {identified!r}, "
1089 f"pin {provider['default']!r}"
1090 )
1091 elif identified != provider["default"]:
1092 promoted.append(f"{provider['id']}: pin {provider['default']!r} -> {identified}")
1093 for line in promoted:
1094 print(f"promoted {line}")
1095 for line in stale:
1096 print(f"STALE {line}")
1097 print(f"{len(spec['providers']) - len(stale)} descriptors match their model list; {len(stale)} stale")
1098 if stale:
1099 die(
1100 "provider defaults disagree with their model lists:\n "
1101 + "\n ".join(stale)
1102 + "\n set each descriptor default_model to the identified id"
1103 )
1104
1105
1106 def cmd_seed_lock(args: argparse.Namespace) -> None:
1107 spec = load_seed_spec(Path(args.spec))
1108 drift = seed_descriptor_default_errors(spec, Path(args.descriptors))
1109 if drift:
1110 die("descriptor/seed default drift:\n " + "\n ".join(drift))
1111 raw, source, upstream = load_upstream_payload(spec)
1112 fetched_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
1113 new_lock, errors = build_seed_lock(spec, upstream, raw, fetched_at)
1114 lock_path = Path(args.lock)
1115 old_lock = read_json_file(lock_path) if lock_path.is_file() else None
1116 corrections_path = Path(args.corrections)
1117 corrections = read_json_file(corrections_path) if corrections_path.is_file() else None
1118 print(f"upstream: {public_source_label(source)} sha256 {new_lock['source']['sha256']}")
1119 for line in seed_lock_report(spec, old_lock, new_lock, upstream, corrections):
1120 print(line)
1121 if errors:
1122 die("seed lock refused:\n " + "\n ".join(errors))
1123 if args.dry_run:
1124 print("dry-run: lock not written")
1125 return
1126 lock_path.write_text(json.dumps(new_lock, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
1127 print(f"wrote {lock_path}; next: {SEED_RENDER_COMMAND}")
1128
1129
1130 def cmd_seed_render(args: argparse.Namespace) -> None:
1131 spec = load_seed_spec(Path(args.spec))
1132 drift = seed_descriptor_default_errors(spec, Path(args.descriptors))
1133 if drift:
1134 die("descriptor/seed default drift:\n " + "\n ".join(drift))
1135 lock = read_json_file(Path(args.lock))
1136 corrections = read_json_file(Path(args.corrections))
1137 providers = {provider["id"] for provider in spec["providers"]}
1138 models = {(provider["id"], model["id"]) for provider in spec["providers"] for model in provider["models"]}
1139 missing = [str(rule.get("provider")) for rule in corrections.get("providers", []) if rule.get("provider") not in providers]
1140 missing.extend(f"{row.get('provider')}/{row.get('id')}" for row in corrections.get("models", []) if (row.get("provider"), row.get("id")) not in models)
1141 if missing:
1142 die("seed corrections name absent targets: " + ", ".join(missing))
1143 rendered = render_seed(spec, lock, corrections.get("reviewed"))
1144 target = Path(args.out)
1145 if args.check:
1146 current = target.read_text(encoding="utf-8") if target.is_file() else ""
1147 if current == rendered:
1148 print(f"ok: {target} matches {SEED_SPEC} + {SEED_LOCK}")
1149 return
1150 diff = list(
1151 difflib.unified_diff(
1152 current.splitlines(),
1153 rendered.splitlines(),
1154 fromfile=f"{target} (committed)",
1155 tofile=f"{target} (rendered)",
1156 lineterm="",
1157 )
1158 )
1159 for line in diff[:200]:
1160 print(line)
1161 if len(diff) > 200:
1162 print(f"... {len(diff) - 200} more diff lines")
1163 die(
1164 f"{target} is not the rendered seed. It is generated: put the change in "
1165 f"{SEED_SPEC} (selection/mapping) or {CORRECTIONS_ASSET} (policy), then run "
1166 f"`{SEED_RENDER_COMMAND}`"
1167 )
1168 target.write_text(rendered, encoding="utf-8")
1169 print(f"wrote {target}")
1170
1171
1172 def cmd_seed_age(args: argparse.Namespace) -> None:
1173 lock = read_json_file(Path(args.lock))
1174 fetched_at = (lock.get("source") or {}).get("fetched_at")
1175 if not isinstance(fetched_at, str):
1176 die(f"{args.lock} has no source.fetched_at; the seed was never pinned")
1177 try:
1178 pinned = datetime.strptime(fetched_at, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
1179 except ValueError:
1180 die(f"{args.lock} source.fetched_at is not UTC ISO-8601: {fetched_at!r}")
1181 age_days = max(0.0, (datetime.now(timezone.utc) - pinned).total_seconds() / 86400.0)
1182 if age_days > args.max_days:
1183 die(
1184 f"the offline seed is {age_days:.1f} days old (limit {args.max_days}d), pinned {fetched_at}.\n"
1185 "The bundled roster freezes at the last hand-run re-lock, so every install offline "
1186 "or past the live TTL keeps an old model list. Re-lock and land it:\n"
1187 " python3 scripts/catalog/catalog_models_dev.py seed lock\n"
1188 f" {SEED_RENDER_COMMAND}\n"
1189 "See docs/CATALOG_REFRESH.md."
1190 )
1191 print(f"ok: offline seed pinned {fetched_at} ({age_days:.1f} days old, limit {args.max_days}d)")
1192
1193
1194 DISCOVER_VENDORS: dict[str, tuple[str, str | None, tuple[str, ...]]] = {
1195 "anthropic": ("Anthropic", "anthropic", ()),
1196 "openai": ("OpenAI", "openai", ()),
1197 "google": ("Google", "google", ()),
1198 "deepseek": ("DeepSeek", "deepseek", ()),
1199 "xai": ("xAI", "xai", ()),
1200 "moonshotai": ("Moonshot/Kimi", "moonshot", ()),
1201 "zai": ("Z.ai", "zai", ()),
1202 "minimax": ("MiniMax", "minimax", ()),
1203 "alibaba": ("Qwen", None, ("qwen", "qwq")),
1204 "mistral": ("Mistral", None, ("mistral", "codestral", "ministral", "devstral", "magistral", "pixtral")),
1205 "meta": ("Meta", "meta", ()),
1206 "xiaomi": ("Xiaomi MiMo", "xiaomi-mimo", ()),
1207 "stepfun": ("StepFun", "stepfun", ()),
1208 }
1209 DISCOVER_DEFAULT_SINCE_DAYS = 45
1210 DISCOVER_NON_CHAT_TOKENS = {
1211 "asr", "audio", "computer", "embed", "embedding", "image", "imagine", "latest",
1212 "live", "moderation", "ocr", "realtime", "rerank", "reranker", "research",
1213 "transcribe", "tts", "video",
1214 }
1215 DISCOVER_SNAPSHOT_ID = re.compile(r"-(\d{8}|\d{4}-\d{2}-\d{2})$")
1216 ISO_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
1217 DISCOVER_SAFE_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$")
1218
1219
1220 def discover_exclusion(model_id: str, row: dict[str, Any], since: str) -> str | None:
1221 """Why a models.dev row is not a public chat model, or None when it qualifies."""
1222 if not DISCOVER_SAFE_ID.match(model_id):
1223 return "id outside the safe character set"
1224 release = row.get("release_date")
1225 if not isinstance(release, str) or not ISO_DATE.match(release):
1226 return "no release_date"
1227 if release < since:
1228 return "older than the window"
1229 if row.get("status") in ("deprecated", "retired"):
1230 return "deprecated"
1231 if DISCOVER_SNAPSHOT_ID.search(model_id):
1232 return "dated snapshot"
1233 if DISCOVER_NON_CHAT_TOKENS & set(re.split(r"[^a-z0-9]+", model_id.lower())):
1234 return "not a chat model id"
1235 if (row.get("modalities") or {}).get("output") != ["text"] or row.get("tool_call") is not True:
1236 return "not a text model with tool calling"
1237 context = (row.get("limit") or {}).get("context")
1238 if not isinstance(context, int) or isinstance(context, bool) or context <= 0:
1239 return "no context limit"
1240 return None
1241
1242
1243 def discover_candidates(
1244 upstream: dict[str, Any],
1245 reviewed: dict[str, Any],
1246 skip: list[str],
1247 since: str,
1248 ) -> list[dict[str, Any]]:
1249 """Allowlisted-vendor chat models released since `since` that the public list lacks."""
1250 known = {str(key).lower() for key in reviewed.get("intrinsic", {})}
1251 for entry in reviewed.get("public_models", []):
1252 known.add(entry["id"].lower())
1253 known.update(str(alias).lower() for alias in entry.get("aliases", []))
1254 known.update(str(item).lower() for item in skip)
1255 found: list[dict[str, Any]] = []
1256 for vendor, (label, spec_provider, prefixes) in DISCOVER_VENDORS.items():
1257 rows = (upstream.get("providers", {}).get(vendor) or {}).get("models") or {}
1258 for model_id, row in sorted(rows.items()):
1259 if prefixes and not model_id.lower().startswith(prefixes):
1260 continue
1261 if model_id.lower() in known or discover_exclusion(model_id, row, since):
1262 continue
1263 limit = row["limit"]
1264 output = limit.get("output")
1265 found.append(
1266 {
1267 "vendor": vendor,
1268 "label": label,
1269 "spec_provider": spec_provider,
1270 "id": model_id,
1271 "release_date": row["release_date"],
1272 "context_window": limit["context"],
1273 "max_output": output if isinstance(output, int) and not isinstance(output, bool) and output > 0 else None,
1274 "reasoning": row.get("reasoning") is True,
1275 }
1276 )
1277 found.sort(key=lambda item: (item["release_date"], item["vendor"], item["id"]))
1278 return found
1279
1280
1281 def append_spec_model(spec_text: str, provider_id: str, model_id: str) -> str:
1282 """Add a bare model id to the end of one provider's `models` array."""
1283 block = re.search(rf'^\[\[providers\]\]\nid = "{re.escape(provider_id)}"\n', spec_text, re.M)
1284 if block is None:
1285 die(f"seed spec has no provider {provider_id}")
1286 opener = re.compile(r"^models = \[\n", re.M).search(spec_text, block.end())
1287 nxt = spec_text.find("[[providers]]", block.end())
1288 if opener is None or (nxt != -1 and opener.start() > nxt):
1289 die(f"seed spec provider {provider_id}: could not find its models array")
1290 end = spec_text.index("\n]\n", opener.end() - 1) + 1
1291 return spec_text[:end] + f' "{model_id}",\n' + spec_text[end:]
1292
1293
1294 VENDOR_FAMILY = {
1295 "anthropic": "Anthropic",
1296 "openai": "OpenAi",
1297 "google": "Google",
1298 "deepseek": "DeepSeek",
1299 "xai": "Xai",
1300 "moonshotai": "Moonshot",
1301 "zai": "Zai",
1302 "minimax": "Minimax",
1303 "alibaba": "Qwen",
1304 "mistral": "Mistral",
1305 "meta": "Meta",
1306 "xiaomi": "XiaomiMimo",
1307 "stepfun": "Stepfun",
1308 }
1309
1310
1311 def apply_discoveries(
1312 found: list[dict[str, Any]],
1313 corrections: dict[str, Any],
1314 spec: dict[str, Any],
1315 spec_text: str,
1316 today: str,
1317 ) -> tuple[dict[str, Any], str]:
1318 reviewed = corrections["reviewed"]
1319 seeded = {(p["id"], m["id"].lower()) for p in spec["providers"] for m in p["models"]}
1320 for item in found:
1321 intrinsic: dict[str, Any] = {
1322 "source": f"models.dev {item['vendor']}/{item['id']}, discovered {today}; unreviewed",
1323 "context_window": item["context_window"],
1324 }
1325 if item["max_output"]:
1326 intrinsic["max_output"] = item["max_output"]
1327 intrinsic["reasoning"] = item["reasoning"]
1328 intrinsic["family"] = VENDOR_FAMILY[item["vendor"]]
1329 reviewed["intrinsic"][item["id"].lower()] = intrinsic
1330 reviewed["public_models"].append(
1331 {
1332 "id": item["id"],
1333 "label": item["label"],
1334 "added_at": item["release_date"],
1335 "aliases": [item["id"]],
1336 }
1337 )
1338 if item["spec_provider"] and (item["spec_provider"], item["id"].lower()) not in seeded:
1339 spec_text = append_spec_model(spec_text, item["spec_provider"], item["id"])
1340 return corrections, spec_text
1341
1342
1343 def cmd_seed_discover(args: argparse.Namespace) -> None:
1344 spec = load_seed_spec(Path(args.spec))
1345 since = args.since or (
1346 datetime.now(timezone.utc) - timedelta(days=spec["discover"]["since_days"])
1347 ).strftime("%Y-%m-%d")
1348 if not ISO_DATE.match(since):
1349 die(f"--since must be YYYY-MM-DD, got {since!r}")
1350 _, source, upstream = load_upstream_payload(spec, args.snapshot)
1351 corrections_path = Path(args.corrections)
1352 corrections = read_json_file(corrections_path)
1353 found = discover_candidates(upstream, corrections["reviewed"], spec["discover"]["skip"], since)
1354 print(f"upstream: {public_source_label(source)}; vendors: {', '.join(DISCOVER_VENDORS)}; released since {since}")
1355 for item in found:
1356 target = item["spec_provider"] or "public list only"
1357 print(f" {item['release_date']} {item['vendor']}/{item['id']} ctx {item['context_window']} out {item['max_output']} -> {target}")
1358 print(f"{len(found)} new model(s)")
1359 if not args.write or not found:
1360 return
1361 spec_path = Path(args.spec)
1362 today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
1363 corrections, spec_text = apply_discoveries(
1364 found, corrections, spec, spec_path.read_text(encoding="utf-8"), today
1365 )
1366 corrections_path.write_text(json.dumps(corrections, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
1367 spec_path.write_text(spec_text, encoding="utf-8")
1368 print(f"wrote {corrections_path} and {spec_path}; next: seed lock, seed render")
1369
1370
1371 def build_parser() -> argparse.ArgumentParser:
1372 p = argparse.ArgumentParser(
1373 description="Secret-free Models.dev / OpenRouter catalog automation (#4117)"
1374 )
1375 sub = p.add_subparsers(dest="cmd", required=True)
1376
1377 refresh = sub.add_parser("refresh", help="Fetch live catalog / provider models")
1378 refresh.add_argument(
1379 "--provider",
1380 default=None,
1381 help="Optional provider id (currently: openrouter). Omit for Models.dev.",
1382 )
1383 refresh.add_argument(
1384 "--sort",
1385 default="newest",
1386 choices=["newest", "none"],
1387 help="OpenRouter sort order (default: newest)",
1388 )
1389 refresh.add_argument(
1390 "--limit",
1391 type=int,
1392 default=100,
1393 help="OpenRouter row cap (default: 100; 0 = no cap)",
1394 )
1395 refresh.add_argument(
1396 "--write-cache",
1397 metavar="PATH",
1398 help="Deprecated/unsupported: validate-only automation never writes fetched JSON",
1399 )
1400 refresh.add_argument(
1401 "--write",
1402 metavar="PATH",
1403 help="Deprecated/unsupported alias of --write-cache",
1404 )
1405 refresh.set_defaults(func=cmd_refresh)
1406
1407 snapshot = sub.add_parser(
1408 "snapshot",
1409 help="Validate or write a Models.dev-shaped snapshot document",
1410 )
1411 snapshot.add_argument(
1412 "path",
1413 nargs="?",
1414 default="crates/config/assets/models_dev.bundled.json",
1415 help="Snapshot path (default: offline seed asset)",
1416 )
1417 snapshot.add_argument(
1418 "--check",
1419 action="store_true",
1420 help="Validate existing file only (no network)",
1421 )
1422 snapshot.add_argument(
1423 "--write",
1424 action="store_true",
1425 help="Deprecated/unsupported: validate-only automation never writes snapshots",
1426 )
1427 snapshot.add_argument(
1428 "--force-full",
1429 action="store_true",
1430 help="Deprecated/unsupported with --write; retained for clear failure messages",
1431 )
1432 snapshot.set_defaults(func=cmd_snapshot)
1433
1434 seed = sub.add_parser(
1435 "seed",
1436 help="Generate the offline seed from the reviewed spec and a pinned lock",
1437 )
1438 seed_sub = seed.add_subparsers(dest="seed_cmd", required=True)
1439 lock = seed_sub.add_parser(
1440 "lock",
1441 help="Fetch upstream, pin the rows the spec references, print the review report",
1442 )
1443 lock.add_argument("--dry-run", action="store_true", help="Print the report; write nothing")
1444 render = seed_sub.add_parser(
1445 "render", help="Render the seed from spec + lock (offline, deterministic)"
1446 )
1447 render.add_argument(
1448 "--check",
1449 action="store_true",
1450 help="Fail with a diff when the committed seed differs from the rendered one",
1451 )
1452 render.add_argument("--out", default=str(SEED_ASSET), help="Seed path to write or check")
1453 age = seed_sub.add_parser(
1454 "age",
1455 help="Fail when the pinned seed is older than the allowed age (offline)",
1456 )
1457 age.add_argument(
1458 "--max-days",
1459 type=float,
1460 default=30.0,
1461 help="Maximum age of source.fetched_at in days (default: 30)",
1462 )
1463 age.set_defaults(func=cmd_seed_age)
1464 for command in (lock, render, age):
1465 command.add_argument("--spec", default=str(SEED_SPEC))
1466 command.add_argument("--lock", default=str(SEED_LOCK))
1467 command.add_argument("--corrections", default=str(CORRECTIONS_ASSET))
1468 command.add_argument("--descriptors", default=str(DESCRIPTORS_ASSET))
1469 lock.set_defaults(func=cmd_seed_lock)
1470 render.set_defaults(func=cmd_seed_render)
1471
1472 discover = seed_sub.add_parser(
1473 "discover",
1474 help="List (or with --write, add) allowlisted-vendor models the public list lacks",
1475 )
1476 discover.add_argument("--write", action="store_true", help="Add the rows to the spec and corrections")
1477 discover.add_argument("--since", help="Earliest release_date, YYYY-MM-DD (default: spec window)")
1478 discover.add_argument("--snapshot", help="Read a local models.dev JSON instead of fetching")
1479 discover.add_argument("--spec", default=str(SEED_SPEC))
1480 discover.add_argument("--corrections", default=str(CORRECTIONS_ASSET))
1481 discover.set_defaults(func=cmd_seed_discover)
1482
1483 defaults = sub.add_parser(
1484 "defaults", help="Audit shipped provider defaults against a live catalog"
1485 )
1486 defaults_sub = defaults.add_subparsers(dest="defaults_cmd", required=True)
1487 audit = defaults_sub.add_parser(
1488 "audit",
1489 help="Fail when a descriptor default disagrees with its provider model list",
1490 )
1491 audit.add_argument("--spec", default=str(SEED_SPEC))
1492 audit.add_argument("--lock", default=str(SEED_LOCK))
1493 audit.add_argument("--descriptors", default=str(DESCRIPTORS_ASSET))
1494 audit.set_defaults(func=cmd_defaults_audit)
1495 return p
1496
1497
1498 def main(argv: list[str] | None = None) -> None:
1499 parser = build_parser()
1500 args = parser.parse_args(argv)
1501 args.func(args)
1502
1503
1504 if __name__ == "__main__":
1505 main()
1506
1506 lines PYTHON